vite-plugin-fvtt 0.1.1 β†’ 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +45 -31
  2. package/dist/index.js +133 -62
  3. package/package.json +3 -3
package/README.md CHANGED
@@ -1,23 +1,23 @@
1
1
  # **vite-plugin-fvtt**
2
2
 
3
- A powerful [Vite](https://vitejs.dev/) plugin to **streamline and automate** the development of Foundry VTT modules and systems. It handles manifest resolution, asset copying, language file composition, and template handling with **minimal setup**, letting you focus on your code.
3
+ A [Vite](https://vitejs.dev/) plugin to **streamline and automate** the development of Foundry VTT modules and systems.
4
4
 
5
- ## **πŸš€ Key Features**
5
+ It handles manifest resolution, asset copying, language file composition, and template handling with **minimal setup**, letting you focus on your code.
6
6
 
7
- The primary advantage of this plugin is the ability to develop your module in a modern, isolated environment. You no longer need to work directly inside your Foundry VTT data folder, which can be messy and inefficient. This allows you to leverage Vite's Hot Module Replacement (HMR) and other developer-friendly features without polluting your local installation.
7
+ The plugin's core goal is to enable a robust HMR workflow via Vite's development server, freeing you from Foundry VTT's native HMR and build watch commands.
8
8
 
9
- ## **Getting Started**
9
+ ## **πŸš€ Getting Started**
10
10
 
11
- ### **1. Setup a Foundry VTT Project**
11
+ ### **Step 1. Setup a Foundry VTT Project**
12
12
 
13
13
  Create a standard [Foundry VTT module or system](https://foundryvtt.com/article/module-development/).
14
14
  Place your `module.json` or `system.json` manifest in either your **project root** or your **public/** directory.
15
15
 
16
- ### **2. Add the Plugin to your Vite Config**
16
+ ### **Step 2. Add the Plugin to your Vite Config**
17
17
 
18
18
  Install the plugin with `npm i -D vite-plugin-fvtt`.
19
19
 
20
- Add the plugin to your vite.config.js. The **build.lib.entry** field is required, most of the other settings are infer'd by the plugin from your foundry manifest.
20
+ Add the plugin to your vite.config.js. The **build.lib.entry** field is required; most of the other settings are inferred by the plugin from your Foundry VTT manifest.
21
21
 
22
22
  ```js
23
23
  // vite.config.js
@@ -37,50 +37,64 @@ export default defineConfig({
37
37
  });
38
38
  ```
39
39
 
40
- ## **βš™οΈ How it Works**
40
+ ## **βš™οΈ Features**
41
41
 
42
- ### **Manifest & Asset Resolution**
42
+ ### **1. Configuration**
43
+ The plugin needs to know where your Foundry VTT instance is running to proxy and serve assets correctly. If you want to change anything from the defaults `http://localhost:30000`, create a `.env.foundryvtt.local` file in your project.
44
+ ```ini
45
+ FOUNDRY_URL=localhost
46
+ FOUNDRY_PORT=30000
47
+ ```
48
+
49
+ The Vite dev server will run on `FOUNDRY_PORT + 1`, where you will need to open your browser manually to.
50
+
51
+ ### **2. Manifest & Asset Resolution**
52
+
53
+ The plugin automatically detects your manifest file (`module.json` or `system.json`) in the project **root** or `public/` folder.
54
+
55
+ This plugin shapes the output depending on your manifest; it tries to automatically discover the relevant files in the `root`, `source`, and `public` folders to build the output files. The `public` folder is defined by the Vite config file. The plugin determines the `source` directory based on your `lib.entry` path. For example, if your `lib.entry` is './mysource/package/main.js', the `mysource/` directory is considered your source directory.
56
+
57
+ πŸ’‘ Your entry file should always import your main stylesheet; the manifest dictates how everything is named and output.
58
+
59
+ ### **3. ESModules, Scripts & Styles**
43
60
 
44
- * The plugin automatically detects your manifest file (`module.json` or `system.json`) in the project **root** or `public/` folder.
45
- * Assets referenced in the manifest (styles, esmodules, scripts) are **automatically generated to the build output**, simplifying your build process.
61
+ `esmodules` and `scripts` declared in your manifest are automatically created from your `lib.entry`. Since Vite compiles the module, the plugin expects the `esmodules` or `scripts` entry in your manifest to only point to a single JavaScript file.
46
62
 
47
- ### **Template Handling**
63
+ Stylesheets (CSS/SCSS/LESS) should be imported in your entry file; the plugin ensures they are outputted as the correct file.
48
64
 
49
- * The plugin automatically detects templates in common locations:
50
- * Your public folder (e.g., `public/handlebars/`).
51
- * The project root (e.g., `templates/`).
52
- * A templates folder directly under your entry file's directory (e.g., `src/tpl/`).
53
- * **Note:** Only templates located in the **public folder** are copied to the build output.
65
+ ### **4. Template Handling**
54
66
 
55
- ### **Language File Merging**
67
+ Templates work in HMR properly on the development server; they are autodiscovered as discussed in [2. Manifest & Asset Resolution](#2-manifest--asset-resolution). The development server intercepts the websocket traffic and sends the local templates instead of Foundry VTT's, if present. e.g., a template request to `/systems/mysystem/tpl/character-header.hbs` might be rerouted to `public/tpl/character-header.hbs`. Folder structure inside your project is mirrored, apart from the `system`/`module` specific prefix.
56
68
 
57
- The plugin offers a powerful feature for managing translations.
69
+ ### **5. Language File Merging**
58
70
 
59
- * **Complete Language Files:** Place a complete JSON file (e.g., `public/lang/en.json`) and the plugin will copy it as-is.
60
- * **Partial Language Files:** To modularize your translations, place multiple JSON files in a subdirectory (e.g., `src/lang/en/`). The plugin will automatically **merge them into a single file** (`lang/en.json`) during the build, as specified in your manifest. The plugin looks in **root** or your **source directory** for the paths as specified in your foundry manifest file.
71
+ Supports both complete and partial translation workflows:
61
72
 
62
- ## **Example Project Structure**
73
+ * **Complete files:** Place a complete JSON file (e.g., `public/lang/en.json`) and the plugin will copy it as-is.
74
+ * **Partial files:** Place multiple JSONs inside `src/lang/en/` and the plugin merges them into one `lang/en.json` at build.
75
+
76
+ Merging follows your manifest’s declared language paths, searching in root or source directories.
77
+
78
+ ⚠️ **Note:** HMR works for language files, but non-English locales may not reload as expected.
79
+
80
+ ### **Example Project Structure**
63
81
  ```
64
82
  my-module/
65
83
  β”œβ”€ src/
66
84
  β”‚ β”œβ”€ main.js # The primary module entry file (required by Vite).
67
- β”‚ β”œβ”€ style.css # Your project's main stylesheet.
85
+ β”‚ β”œβ”€ style.css # Your project's main stylesheet, imported by main.js.
68
86
  β”‚ └─ lang/en/ # Directory for partial, merged translation files.
69
87
  β”‚ β”œβ”€ spells.json
70
88
  β”‚ β”œβ”€ abilities.json
71
89
  β”‚ └─ general.json
72
- β”œβ”€ public/
90
+ β”œβ”€ public/ # For static assets (templates, images)
73
91
  β”‚ β”œβ”€ module.json # Your module's manifest file (or system.json).
74
92
  β”‚ └─ templates/ # HTML template files for your module.
75
93
  β”œβ”€ vite.config.js # Your Vite configuration file.
76
94
  ```
77
95
 
78
- ## **πŸ› Known Issues & Troubleshooting**
79
-
80
- * **HMR:** Hot Module Replacement may be inconsistent for non-English language files. A full page refresh or server restart might be needed.
81
- * **App V2:** HMR for Foundry's new App V2 has not been fully tested. If you encounter issues, please open a GitHub issue.
82
- * **General Issues:** If you face unexpected behavior, the first step is always to **restart your dev server (npm run dev) or run a fresh build**. This often resolves caching or HMR-related glitches.
83
-
84
96
  ---
85
97
 
86
- License: MIT
98
+ ## πŸ“„ License
99
+
100
+ [MIT](LICENSE)
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import fs from "fs-extra";
2
2
  import posix from "path/posix";
3
3
  import dotenv from "dotenv";
4
- import { sync } from "glob";
4
+ import { globSync } from "tinyglobby";
5
5
  import { Server } from "socket.io";
6
6
  import { io } from "socket.io-client";
7
7
 
@@ -22,28 +22,6 @@ function loadEnv() {
22
22
  };
23
23
  }
24
24
 
25
- //#endregion
26
- //#region src/config/foundryvtt-manifest.ts
27
- function loadManifest(config) {
28
- if (context?.manifest) return context.manifest;
29
- const publicDir = config.publicDir || "public";
30
- const MANIFEST_LOCATIONS = [
31
- "system.json",
32
- "module.json",
33
- `${publicDir}/system.json`,
34
- `${publicDir}/module.json`
35
- ];
36
- const foundPath = MANIFEST_LOCATIONS.map((relPath) => posix.resolve(process.cwd(), relPath)).find((absPath) => fs.pathExistsSync(absPath));
37
- if (!foundPath) throw new Error(`Could not find a manifest file (system.json or module.json) in project root or ${publicDir}/.`);
38
- try {
39
- const data = fs.readJsonSync(foundPath);
40
- data.manifestType = foundPath.includes("module.json") ? "module" : "system";
41
- return data;
42
- } catch (err) {
43
- throw new Error(`Failed to read manifest at ${foundPath}: ${err?.message || err}`);
44
- }
45
- }
46
-
47
25
  //#endregion
48
26
  //#region src/utils/logger.ts
49
27
  var Logger = class {
@@ -53,7 +31,7 @@ var Logger = class {
53
31
  warn: "\x1B[33m",
54
32
  error: "\x1B[31m"
55
33
  };
56
- constructor({ namespace = "vite-plugin-foundryvtt" } = {}) {
34
+ constructor({ namespace = "vite-plugin-fvtt" } = {}) {
57
35
  this.namespace = namespace;
58
36
  }
59
37
  format(level, message) {
@@ -77,6 +55,40 @@ var Logger = class {
77
55
  };
78
56
  var logger_default = new Logger();
79
57
 
58
+ //#endregion
59
+ //#region src/config/foundryvtt-manifest.ts
60
+ function loadManifest(config) {
61
+ if (context?.manifest) return context.manifest;
62
+ const publicDir = config.publicDir || "public";
63
+ const MANIFEST_LOCATIONS = [
64
+ "system.json",
65
+ "module.json",
66
+ `${publicDir}/system.json`,
67
+ `${publicDir}/module.json`
68
+ ];
69
+ const foundPath = MANIFEST_LOCATIONS.map((relPath) => posix.resolve(process.cwd(), relPath)).find((absPath) => fs.pathExistsSync(absPath));
70
+ if (!foundPath) logger_default.fail(`Could not find a manifest file (system.json or module.json) in project root or ${publicDir}/.`);
71
+ try {
72
+ const data = fs.readJsonSync(foundPath);
73
+ if (!data.id || typeof data.id !== "string") logger_default.fail(`Manifest at ${foundPath} is missing required "id" field.`);
74
+ const hasEsmodules = Array.isArray(data.esmodules) && data.esmodules.length > 0;
75
+ const hasScripts = Array.isArray(data.scripts) && data.scripts.length > 0;
76
+ if (hasEsmodules === hasScripts) logger_default.fail(`Manifest at ${foundPath} must define exactly one of "esmodules" or "scripts".`);
77
+ const result = {
78
+ manifestType: foundPath.includes("module.json") ? "module" : "system",
79
+ id: data.id,
80
+ esmodules: Array.isArray(data.esmodules) ? data.esmodules : [],
81
+ scripts: Array.isArray(data.scripts) ? data.scripts : [],
82
+ styles: Array.isArray(data.styles) ? data.styles : [],
83
+ languages: Array.isArray(data.languages) ? data.languages : [],
84
+ packs: Array.isArray(data.packs) ? data.packs : []
85
+ };
86
+ return result;
87
+ } catch (err) {
88
+ logger_default.fail(`Failed to read manifest at ${foundPath}: ${err?.message || err}`);
89
+ }
90
+ }
91
+
80
92
  //#endregion
81
93
  //#region src/config/vite-options.ts
82
94
  function createPartialViteConfig(config) {
@@ -86,7 +98,7 @@ function createPartialViteConfig(config) {
86
98
  const fileName = (useEsModules ? context.manifest?.esmodules[0] : context.manifest?.scripts?.[0]) ?? "bundle";
87
99
  if (fileName === "bundle") logger_default.warn("No output file specified in manifest, using default \"bundle\"");
88
100
  if (!context.manifest?.styles?.length) logger_default.warn("No CSS file found in manifest");
89
- const cssFileName = posix.parse(context.manifest?.styles[0] ?? "").name;
101
+ const cssFileName = posix.parse(context.manifest?.styles[0] ?? "bundle.css").name;
90
102
  const foundryPort = context.env?.foundryPort ?? 3e4;
91
103
  const foundryUrl = context.env?.foundryUrl ?? "localhost";
92
104
  const entry = (config.build?.lib)?.entry;
@@ -94,16 +106,6 @@ function createPartialViteConfig(config) {
94
106
  if (typeof entry !== "string") logger_default.fail("Only a singular string entry is supported for build.lib.entry");
95
107
  return {
96
108
  base,
97
- esbuild: config.esbuild ?? {
98
- minifyIdentifiers: false,
99
- minifySyntax: true,
100
- minifyWhitespace: true,
101
- keepNames: true
102
- },
103
- server: {
104
- port: foundryPort + 1,
105
- proxy: { [`^(?!${base})`]: `http://${foundryUrl}:${foundryPort}` }
106
- },
107
109
  build: {
108
110
  minify: "esbuild",
109
111
  lib: {
@@ -113,6 +115,20 @@ function createPartialViteConfig(config) {
113
115
  formats,
114
116
  name: context.manifest?.id
115
117
  }
118
+ },
119
+ define: { __FVTT_PLUGIN__: {
120
+ id: context.manifest?.id,
121
+ isSystem: context.manifest?.manifestType === "system"
122
+ } },
123
+ esbuild: config.esbuild ?? {
124
+ minifyIdentifiers: false,
125
+ minifySyntax: true,
126
+ minifyWhitespace: true,
127
+ keepNames: true
128
+ },
129
+ server: {
130
+ port: foundryPort + 1,
131
+ proxy: { [`^(?!${base})`]: `http://${foundryUrl}:${foundryPort}` }
116
132
  }
117
133
  };
118
134
  }
@@ -121,28 +137,80 @@ function createPartialViteConfig(config) {
121
137
  //#region src/server/hmr-client.ts
122
138
  var hmr_client_default = `
123
139
  if (import.meta.hot) {
124
- function refreshApplications() {
140
+ const FVTT_PLUGIN = __FVTT_PLUGIN__
141
+
142
+ function refreshApplications(path = null) {
125
143
  // AppV1 refresh
126
144
  Object.values(foundry.ui.windows).forEach(app => app.render(true))
127
145
  // AppV2 refresh
128
- // TODO: Can we filter out to only refresh the correct apps?
129
- foundry.applications.instances.forEach(appV2 => appV2.render(true))
146
+ if (path)
147
+ foundry.applications.instances.forEach(appV2 => {
148
+ Object.values(appV2.constructor.PARTS ?? {}).forEach(part => {
149
+ const templates = Array.isArray(part.templates) ? part.templates : []
150
+ if (part.template === path || templates.includes(path)) appV2.render(true)
151
+ })
152
+ })
153
+ else foundry.applications.instances.forEach(appV2 => appV2.render(true))
130
154
  }
131
155
 
132
- import.meta.hot.on('foundryvtt-template-update', async ({ path }) => {
133
- console.log('Vite | Force reload template', path)
134
- Handlebars.unregisterPartial(path)
135
- await foundry.applications.handlebars.getTemplate(path)
136
- refreshApplications()
156
+ import.meta.hot.on('foundryvtt-template-update', ({ path }) => {
157
+ game.socket.emit('template', path, response => {
158
+ if (response.error) new Error(response.error)
159
+ let template = undefined
160
+ try {
161
+ template = Handlebars.compile(response.html)
162
+ } catch (error) {
163
+ console.error(error)
164
+ return
165
+ }
166
+ Handlebars.registerPartial(path, template)
167
+ console.log(\`Vite | Retrieved and compiled template \${path}\`)
168
+ refreshApplications(path)
169
+ })
137
170
  })
138
171
 
172
+ async function hmrLanguage(lang, targetObject = game.i18n.translations) {
173
+ try {
174
+ const languages = FVTT_PLUGIN.isSystem
175
+ ? game.system.languages
176
+ : game.modules.get(FVTT_PLUGIN.id)?.languages
177
+ if (!languages) {
178
+ console.warn(
179
+ 'Vite | Got a HMR request to reload languages, however no languages were found.',
180
+ )
181
+ return
182
+ }
183
+ const langEntry = languages.find(l => l.lang === lang)
184
+ if (!langEntry) {
185
+ console.warn('Vite | Got an HMR request for an undefined language')
186
+ return
187
+ }
188
+
189
+ const url = langEntry.path
190
+ const resp = await fetch(url)
191
+ if (!resp.ok) throw new Error('Failed to fetch language file!')
192
+
193
+ const json = await resp.json()
194
+
195
+ foundry.utils.mergeObject(targetObject, json)
196
+ console.log(\`Vite | HMR: Reloaded language '\${lang}'\`)
197
+ } catch (error) {
198
+ console.error(\`Vite | HMR: Error reloading language '\${lang}' for \${FVTT_PLUGIN.id}\`, error);
199
+ }
200
+ }
201
+
139
202
  import.meta.hot.on('foundryvtt-language-update', async () => {
140
- console.log('Vite | Force reassigning language')
141
- await game.i18n.setLanguage(game.i18n.lang)
203
+ const currentLang = game.i18n.lang
204
+ const promises = []
205
+ if (currentLang !== 'en') {
206
+ promises.push(hmrLanguage('en', game.i18n._fallback))
207
+ }
208
+ promises.push(hmrLanguage(currentLang))
209
+ await Promise.all(promises)
142
210
  refreshApplications()
143
211
  })
144
212
  } else console.error('Vite | HMR is disabled')
145
- `;
213
+ //`;
146
214
 
147
215
  //#endregion
148
216
  //#region src/server/trackers/abstract-file-tracker.ts
@@ -330,7 +398,7 @@ function getLocalLanguageFiles(lang, outDir = false) {
330
398
  logger_default.warn(`No language folder found at: ${sourcePath}`);
331
399
  return [];
332
400
  }
333
- return sync(posix.join(sourcePath, "**/*.json"));
401
+ return globSync(posix.join(sourcePath, "**/*.json"));
334
402
  }
335
403
  function loadLanguage(lang, outDir = false) {
336
404
  const files = getLocalLanguageFiles(lang, outDir);
@@ -486,37 +554,40 @@ function validator() {
486
554
  function foundryVTTPlugin() {
487
555
  context.env = loadEnv();
488
556
  return {
489
- name: "vite-plugin-foundryvtt",
557
+ name: "vite-plugin-fvtt",
490
558
  config(config) {
491
- context.manifest = loadManifest(config);
559
+ context.manifest = loadManifest(config) ?? void 0;
492
560
  return createPartialViteConfig(config);
493
561
  },
494
562
  configResolved(config) {
495
563
  context.config = config;
496
564
  },
497
- async closeBundle() {
498
- if (context.config?.mode !== "production") return;
499
- const outDir = posix.resolve(process.cwd(), context.config.build.outDir);
565
+ async writeBundle() {
566
+ if (!context.config) return;
567
+ const outDir = path_utils_default.getOutDir();
500
568
  const candidates = ["system.json", "module.json"];
501
569
  for (const file of candidates) {
502
- const src = posix.resolve(process.cwd(), file);
503
- if (await fs.pathExists(src)) {
570
+ const src = posix.resolve(file);
571
+ if (!path_utils_default.getOutDirFile(file) && fs.existsSync(src)) {
572
+ this.addWatchFile(src);
504
573
  const dest = posix.join(outDir, file);
505
574
  await fs.copy(src, dest);
506
575
  logger_default.info(`Copied ${file} >>> ${dest}`);
507
576
  }
508
577
  }
509
578
  const languages = context.manifest?.languages ?? [];
510
- if (languages.length > 0) {
511
- for (const language of languages) {
512
- if (path_utils_default.getOutDirFile(language.path) !== "") continue;
513
- const languageDataRaw = loadLanguage(language.lang);
514
- const languageData = transform(languageDataRaw);
515
- fs.writeJSONSync(posix.join(path_utils_default.getOutDir(), language.path), languageData);
516
- }
517
- validator();
579
+ if (languages.length > 0) for (const language of languages) {
580
+ if (path_utils_default.getOutDirFile(language.path)) continue;
581
+ getLocalLanguageFiles(language.lang).forEach((langFile) => this.addWatchFile(langFile));
582
+ const languageDataRaw = loadLanguage(language.lang);
583
+ const languageData = transform(languageDataRaw);
584
+ fs.writeJSONSync(posix.join(outDir, language.path), languageData);
518
585
  }
519
586
  },
587
+ closeBundle() {
588
+ const languages = context.manifest?.languages ?? [];
589
+ if (languages.length > 0) validator();
590
+ },
520
591
  load(id) {
521
592
  const config = context.config;
522
593
  const jsFileName = config.build.lib.fileName;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vite-plugin-fvtt",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "A Vite plugin for module and system development for Foundry VTT",
5
5
  "keywords": [
6
6
  "vite",
@@ -43,9 +43,9 @@
43
43
  "dependencies": {
44
44
  "dotenv": "^17.2.1",
45
45
  "fs-extra": "^11.3.1",
46
- "glob": "^11.0.3",
47
46
  "socket.io": "^4.8.1",
48
- "socket.io-client": "^4.8.1"
47
+ "socket.io-client": "^4.8.1",
48
+ "tinyglobby": "^0.2.14"
49
49
  },
50
50
  "peerDependencies": {
51
51
  "vite": "^7.0.0"