vite-plugin-fvtt 0.1.2 β†’ 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 +93 -34
  3. package/package.json +1 -1
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
@@ -106,16 +106,6 @@ function createPartialViteConfig(config) {
106
106
  if (typeof entry !== "string") logger_default.fail("Only a singular string entry is supported for build.lib.entry");
107
107
  return {
108
108
  base,
109
- esbuild: config.esbuild ?? {
110
- minifyIdentifiers: false,
111
- minifySyntax: true,
112
- minifyWhitespace: true,
113
- keepNames: true
114
- },
115
- server: {
116
- port: foundryPort + 1,
117
- proxy: { [`^(?!${base})`]: `http://${foundryUrl}:${foundryPort}` }
118
- },
119
109
  build: {
120
110
  minify: "esbuild",
121
111
  lib: {
@@ -125,6 +115,20 @@ function createPartialViteConfig(config) {
125
115
  formats,
126
116
  name: context.manifest?.id
127
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}` }
128
132
  }
129
133
  };
130
134
  }
@@ -133,28 +137,80 @@ function createPartialViteConfig(config) {
133
137
  //#region src/server/hmr-client.ts
134
138
  var hmr_client_default = `
135
139
  if (import.meta.hot) {
136
- function refreshApplications() {
140
+ const FVTT_PLUGIN = __FVTT_PLUGIN__
141
+
142
+ function refreshApplications(path = null) {
137
143
  // AppV1 refresh
138
144
  Object.values(foundry.ui.windows).forEach(app => app.render(true))
139
145
  // AppV2 refresh
140
- // TODO: Can we filter out to only refresh the correct apps?
141
- 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))
142
154
  }
143
155
 
144
- import.meta.hot.on('foundryvtt-template-update', async ({ path }) => {
145
- console.log('Vite | Force reload template', path)
146
- Handlebars.unregisterPartial(path)
147
- await foundry.applications.handlebars.getTemplate(path)
148
- 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
+ })
149
170
  })
150
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
+
151
202
  import.meta.hot.on('foundryvtt-language-update', async () => {
152
- console.log('Vite | Force reassigning language')
153
- 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)
154
210
  refreshApplications()
155
211
  })
156
212
  } else console.error('Vite | HMR is disabled')
157
- `;
213
+ //`;
158
214
 
159
215
  //#endregion
160
216
  //#region src/server/trackers/abstract-file-tracker.ts
@@ -506,29 +562,32 @@ function foundryVTTPlugin() {
506
562
  configResolved(config) {
507
563
  context.config = config;
508
564
  },
509
- async closeBundle() {
510
- if (context.config?.mode !== "production") return;
511
- 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();
512
568
  const candidates = ["system.json", "module.json"];
513
569
  for (const file of candidates) {
514
- const src = posix.resolve(process.cwd(), file);
515
- 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);
516
573
  const dest = posix.join(outDir, file);
517
574
  await fs.copy(src, dest);
518
575
  logger_default.info(`Copied ${file} >>> ${dest}`);
519
576
  }
520
577
  }
521
578
  const languages = context.manifest?.languages ?? [];
522
- if (languages.length > 0) {
523
- for (const language of languages) {
524
- if (path_utils_default.getOutDirFile(language.path) !== "") continue;
525
- const languageDataRaw = loadLanguage(language.lang);
526
- const languageData = transform(languageDataRaw);
527
- fs.writeJSONSync(posix.join(path_utils_default.getOutDir(), language.path), languageData);
528
- }
529
- 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);
530
585
  }
531
586
  },
587
+ closeBundle() {
588
+ const languages = context.manifest?.languages ?? [];
589
+ if (languages.length > 0) validator();
590
+ },
532
591
  load(id) {
533
592
  const config = context.config;
534
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.2",
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",