goravel-vite-plugin 0.1.0 → 0.2.0

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/README.md CHANGED
@@ -107,6 +107,23 @@ Both commands run it. A build merges the inputs with `input` and `assets` and bu
107
107
 
108
108
  What it cannot see is a computed argument such as `{{ vite .entry }}`. Those calls are reported under `dynamic`, the plugin warns about them, and you add the entry to `input` yourself.
109
109
 
110
+ ### Modules
111
+
112
+ An application built from modules (`foundation.Setup().WithModules(...)`) reports them too:
113
+
114
+ ```json
115
+ "modules":[{"name":"blog","path":"modules/blog","entries":["modules/blog/resources/js/app.js"],"aliases":{"@blog-assets":"modules/blog/resources/assets"}}]
116
+ ```
117
+
118
+ For each module the plugin:
119
+
120
+ - builds its `entries` (the module's `ViteEntries()`), whether or not a view references them;
121
+ - aliases `@<name>` to `<path>/resources/js` when that directory exists, so `import x from '@blog/x.js'` and `{{ vite "@blog/app.js" }}` work;
122
+ - adds the aliases the module declares (`ViteAliases()`); a module's own `@<name>` replaces the one above;
123
+ - with `refresh: true`, watches `<path>/resources/views`, `<path>/routes` and `<path>/lang` where they exist. Any other `refresh` value is watched as given.
124
+
125
+ An alias of the same name in your `resolve.alias` wins over a module's. The `discovered` option carries `modules` like the rest, and output without the key, from a framework that has no modules, works as before.
126
+
110
127
  ### Building without Go
111
128
 
112
129
  Where the build runs without a Go toolchain, for example a Node-only Docker stage, save the command's output and hand it over:
@@ -170,6 +187,24 @@ The framework registers three functions for every view once the `Vite` provider
170
187
  | `{{ viteAsset "resources/images/logo.svg" }}` | The URL of a built asset |
171
188
  | `{{ viteReactRefresh }}` | The preamble `@vitejs/plugin-react` needs; empty outside the dev server |
172
189
 
190
+ ### Aliases in templates
191
+
192
+ An entry or asset may be written through an alias, in templates and in Go (`facades.Vite().Tags`, `Asset`, `Content`):
193
+
194
+ ```html
195
+ {{ vite "@/app.js" }} <!-- resources/js/app.js -->
196
+ {{ viteAsset "@/../images/logo.svg" }} <!-- resources/images/logo.svg -->
197
+ ```
198
+
199
+ The framework resolves them with a table the plugin hands over: every `resolve.alias` whose name is a string starting with `@` and whose replacement is a directory inside the project, the plugin's own `@` and yours alike. Patterns, packages in `node_modules` and directories outside the project are left out. The table is written where the framework already reads:
200
+
201
+ - a build adds it to the manifest under the reserved key `"goravel:aliases"`: `{"@": "resources/js"}`;
202
+ - the dev server writes it to the hot file, which is one line of JSON: `{"url":"http://localhost:5173","aliases":{"@":"resources/js"}}`.
203
+
204
+ After the alias is replaced the path is cleaned (`a/./b`, `a/../b`) on both sides, so a build and the dev server name the same file, and a path that leaves the project is refused. An `@` entry reported by `vite:inputs` that no alias matches fails the build.
205
+
206
+ `collectAliases`, `resolveAlias` and `resolveEntry` are exported for tools that build the `discovered` option themselves.
207
+
173
208
  ## Development
174
209
 
175
210
  ```bash
@@ -182,8 +217,15 @@ The tests run a real Vite build and dev server in a temporary directory. Node st
182
217
  ### Releasing
183
218
 
184
219
  1. Bump `version` in `package.json` and move the `Unreleased` entries in [CHANGELOG.md](CHANGELOG.md) under the new version.
185
- 2. Commit, tag `vX.Y.Z` and push the tag.
186
- 3. Run `pnpm publish`. It builds and runs the tests first.
220
+ 2. Commit, tag `vX.Y.Z` and push the tag. The [`publish`](.github/workflows/publish.yml) workflow builds, tests and stages the release with `npm stage publish`; a hyphenated version (`v0.2.0-beta.1`) stages to the `next` dist-tag instead of `latest`.
221
+ 3. Approve the staged release with 2FA. The job summary carries the command:
222
+ ```bash
223
+ npm stage approve <stage-id>
224
+ ```
225
+ You can also approve on npmjs.com under *Staged Packages*. Nothing is installable before that. A version can be staged only once — to rebuild, `npm stage reject <stage-id>`, fix, and push the tag again.
226
+ 4. To rehearse, run the workflow by hand and leave *dry run* on: it needs no credentials and stages nothing.
227
+
228
+ Staging uses npm [trusted publishing](https://docs.npmjs.com/trusted-publishers) and [staged publishing](https://docs.npmjs.com/staged-publishing), so no npm token is stored here. The trusted publisher on npmjs.com is organization `goravel`, repository `vite-plugin`, workflow `publish.yml`, no environment, and it is stage-only: it allows `npm stage publish`, while `npm publish` and `npm dist-tag` are deliberately left disallowed — that is npm's maximum-security posture, and a dist-tag grant could repoint `latest` without any staged approval. `0.1.0` went out by hand before the workflow existed.
187
229
 
188
230
  ## Contributing
189
231
 
@@ -0,0 +1,16 @@
1
+ import type { AliasOptions } from 'vite';
2
+ /** The manifest key the alias table is written under; no source path contains a colon. */
3
+ export declare const aliasesKey = "goravel:aliases";
4
+ /**
5
+ * The aliases the application can resolve in `{{ vite "@/app.js" }}`: those whose name starts
6
+ * with `@` and whose replacement is a directory inside the root, as root-relative slash paths.
7
+ * The first alias of a name wins, as in Vite.
8
+ */
9
+ export declare function collectAliases(root: string, alias: AliasOptions | undefined): Record<string, string>;
10
+ /** Replaces a leading alias, the longest first, at a path boundary: `@` never captures `@blog/...`. Null when none matches. */
11
+ export declare function resolveAlias(entry: string, aliases: Record<string, string>): string | null;
12
+ /**
13
+ * An entry as the manifest names it, the same way the framework resolves it: without a leading
14
+ * slash, its alias replaced, cleaned of `.` and `..`, and refused when it leaves the project.
15
+ */
16
+ export declare function resolveEntry(entry: string, aliases: Record<string, string>): string;
@@ -0,0 +1,72 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ /** The manifest key the alias table is written under; no source path contains a colon. */
4
+ export const aliasesKey = 'goravel:aliases';
5
+ /**
6
+ * The aliases the application can resolve in `{{ vite "@/app.js" }}`: those whose name starts
7
+ * with `@` and whose replacement is a directory inside the root, as root-relative slash paths.
8
+ * The first alias of a name wins, as in Vite.
9
+ */
10
+ export function collectAliases(root, alias) {
11
+ const entries = Array.isArray(alias)
12
+ ? alias.map(({ find, replacement }) => [find, replacement])
13
+ : Object.entries((alias ?? {}));
14
+ const aliases = {};
15
+ for (const [find, replacement] of entries) {
16
+ if (typeof find !== 'string' || !find.startsWith('@') || typeof replacement !== 'string' || find in aliases) {
17
+ continue;
18
+ }
19
+ const directory = aliasDirectory(root, replacement);
20
+ if (directory !== null) {
21
+ aliases[find] = directory;
22
+ }
23
+ }
24
+ return aliases;
25
+ }
26
+ /** A replacement as a directory relative to the root: an absolute path inside it, or a root-relative `/path`. */
27
+ function aliasDirectory(root, replacement) {
28
+ if (!path.isAbsolute(replacement) && !replacement.startsWith('/')) {
29
+ return null;
30
+ }
31
+ for (const candidate of [path.resolve(replacement), path.join(root, replacement)]) {
32
+ const relative = path.relative(root, candidate);
33
+ if (relative === '' || relative.startsWith('..') || path.isAbsolute(relative) || relative.split(path.sep).includes('node_modules')) {
34
+ continue;
35
+ }
36
+ if (fs.statSync(candidate, { throwIfNoEntry: false })?.isDirectory()) {
37
+ return relative.split(path.sep).join('/');
38
+ }
39
+ }
40
+ return null;
41
+ }
42
+ /** Replaces a leading alias, the longest first, at a path boundary: `@` never captures `@blog/...`. Null when none matches. */
43
+ export function resolveAlias(entry, aliases) {
44
+ let found;
45
+ for (const alias of Object.keys(aliases)) {
46
+ if ((entry === alias || entry.startsWith(alias + '/')) && alias.length > (found?.length ?? 0)) {
47
+ found = alias;
48
+ }
49
+ }
50
+ return found === undefined ? null : aliases[found] + entry.slice(found.length);
51
+ }
52
+ /**
53
+ * An entry as the manifest names it, the same way the framework resolves it: without a leading
54
+ * slash, its alias replaced, cleaned of `.` and `..`, and refused when it leaves the project.
55
+ */
56
+ export function resolveEntry(entry, aliases) {
57
+ let resolved = entry.replace(/^\//, '');
58
+ if (resolved.startsWith('@')) {
59
+ const replaced = resolveAlias(resolved, aliases);
60
+ if (replaced === null) {
61
+ const known = Object.keys(aliases).sort();
62
+ throw new Error(`goravel-vite-plugin: no alias matches "${entry}" (from artisan vite:inputs). ` +
63
+ (known.length > 0 ? `Known aliases: ${known.join(', ')}.` : 'No alias points inside the project.'));
64
+ }
65
+ resolved = replaced;
66
+ }
67
+ const cleaned = path.posix.normalize(resolved.replaceAll('\\', '/')).replace(/\/+$/, '');
68
+ if (cleaned === '..' || cleaned.startsWith('../') || cleaned.startsWith('/') || path.win32.isAbsolute(cleaned)) {
69
+ throw new Error(`goravel-vite-plugin: "${entry}" resolves to "${cleaned}", outside the project`);
70
+ }
71
+ return cleaned === '' ? '.' : cleaned;
72
+ }
package/dist/config.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { Config as FullReloadConfig } from 'vite-plugin-full-reload';
2
- import { type DiscoveredInputs } from './discover.js';
2
+ import { type DiscoveredInputs, type DiscoveredModule } from './discover.js';
3
3
  /** The framework's default manifest path, used when the application reports none. */
4
4
  export declare const defaultManifest = ".vite/manifest.json";
5
5
  /** An entry point, a list of them or a map of names to entry points, as Vite's `build.rollupOptions.input` takes it. */
@@ -82,6 +82,8 @@ export interface ResolvedPluginConfig {
82
82
  buildDirectory: string | undefined;
83
83
  hotFile: string | undefined;
84
84
  refresh: boolean | string | string[] | RefreshConfig | RefreshConfig[];
85
+ /** The configuration `refresh: true` became, which the modules' directories are added to; null for any other value. */
86
+ defaultRefresh: RefreshConfig | null;
85
87
  assets: string[];
86
88
  transformOnServe: (code: string, url: DevServerUrl) => string;
87
89
  }
@@ -98,6 +100,8 @@ export interface ResolvedPaths {
98
100
  export declare const refreshPaths: readonly string[];
99
101
  /** Those of `refreshPaths` that exist under the given directory. */
100
102
  export declare function existingRefreshPaths(cwd: string): string[];
103
+ /** The globs of the modules' view, route and language directories that exist. */
104
+ export declare function moduleRefreshPaths(cwd: string, modules: DiscoveredModule[]): string[];
101
105
  /** @param cwd - The working directory, which the refresh paths are relative to; the other paths wait for Vite's root. */
102
106
  export declare function resolvePluginConfig(config: string | string[] | PluginConfig | undefined, cwd: string): ResolvedPluginConfig;
103
107
  /**
package/dist/config.js CHANGED
@@ -9,6 +9,14 @@ export const refreshPaths = ['lang/**', 'resources/lang/**', 'resources/views/**
9
9
  export function existingRefreshPaths(cwd) {
10
10
  return refreshPaths.filter((pattern) => existsSync(path.resolve(cwd, pattern.replace(/\*\*$/, ''))));
11
11
  }
12
+ /** What `refresh: true` watches inside a module: views, routes and language files. */
13
+ const moduleRefreshDirectories = ['resources/views', 'routes', 'lang'];
14
+ /** The globs of the modules' view, route and language directories that exist. */
15
+ export function moduleRefreshPaths(cwd, modules) {
16
+ return modules.flatMap((module) => moduleRefreshDirectories
17
+ .filter((directory) => existsSync(path.resolve(cwd, module.path, directory)))
18
+ .map((directory) => path.posix.join(module.path, directory, '**')));
19
+ }
12
20
  /** @param cwd - The working directory, which the refresh paths are relative to; the other paths wait for Vite's root. */
13
21
  export function resolvePluginConfig(config, cwd) {
14
22
  if (typeof config === 'undefined') {
@@ -26,6 +34,7 @@ export function resolvePluginConfig(config, cwd) {
26
34
  throw new Error('goravel-vite-plugin: discoverCommand must name a command.');
27
35
  }
28
36
  const discoverTimeout = config.discoverTimeout ?? defaultDiscoverTimeout;
37
+ const defaultRefresh = config.refresh === true ? { paths: existingRefreshPaths(cwd) } : null;
29
38
  if (!Number.isFinite(discoverTimeout) || discoverTimeout <= 0) {
30
39
  throw new Error('goravel-vite-plugin: discoverTimeout must be a number of milliseconds greater than zero.');
31
40
  }
@@ -38,7 +47,8 @@ export function resolvePluginConfig(config, cwd) {
38
47
  publicDirectory: subdirectory(config.publicDirectory, 'publicDirectory'),
39
48
  buildDirectory: subdirectory(config.buildDirectory, 'buildDirectory'),
40
49
  hotFile: config.hotFile,
41
- refresh: config.refresh === true ? [{ paths: existingRefreshPaths(cwd) }] : (config.refresh ?? false),
50
+ refresh: defaultRefresh ? [defaultRefresh] : (config.refresh ?? false),
51
+ defaultRefresh,
42
52
  assets: typeof config.assets === 'string' ? [config.assets] : (config.assets ?? []),
43
53
  transformOnServe: config.transformOnServe ?? ((code) => code),
44
54
  };
@@ -12,6 +12,19 @@ export interface DiscoveredInputs {
12
12
  }[];
13
13
  /** The paths of config/vite.go; absent from a framework that does not report them. */
14
14
  paths?: DiscoveredPaths;
15
+ /** The application's modules; absent from a framework that does not report them. */
16
+ modules?: DiscoveredModule[];
17
+ }
18
+ /** A module of the application, every path relative to the project root. */
19
+ export interface DiscoveredModule {
20
+ /** Aliased as `@<name>` to `<path>/resources/js` when that directory exists. */
21
+ name: string;
22
+ /** The module directory. */
23
+ path: string;
24
+ /** Entries to build although no view may reference them. */
25
+ entries: string[];
26
+ /** Aliases the module declares, name to directory. */
27
+ aliases?: Record<string, string>;
15
28
  }
16
29
  /** The paths as `config/vite.go` sets them. */
17
30
  export interface DiscoveredPaths {
package/dist/discover.js CHANGED
@@ -41,14 +41,15 @@ export function discoverInputs(command, root, timeout = defaultDiscoverTimeout)
41
41
  }
42
42
  /** Checks the shape of the command's output or of the `discovered` option. */
43
43
  export function validateInputs(value) {
44
- const { inputs, assets, dynamic, paths } = (value ?? {});
44
+ const { inputs, assets, dynamic, paths, modules } = (value ?? {});
45
45
  if (!isStringList(inputs) ||
46
46
  !isStringList(assets) ||
47
47
  (dynamic !== undefined &&
48
48
  (!Array.isArray(dynamic) ||
49
49
  dynamic.some((call) => typeof call?.template !== 'string' || typeof call?.function !== 'string'))) ||
50
- (paths !== undefined && !isPaths(paths))) {
51
- throw new Error('goravel-vite-plugin: discovered inputs must look like { inputs: string[], assets: string[], dynamic?: { template: string, function: string }[], paths?: { public_directory: string, build_directory: string, hot_file: string, manifest: string } }, got ' +
50
+ (paths !== undefined && !isPaths(paths)) ||
51
+ (modules !== undefined && (!Array.isArray(modules) || !modules.every(isModule)))) {
52
+ throw new Error('goravel-vite-plugin: discovered inputs must look like { inputs: string[], assets: string[], dynamic?: { template: string, function: string }[], paths?: { public_directory: string, build_directory: string, hot_file: string, manifest: string }, modules?: { name: string, path: string, entries: string[], aliases?: Record<string, string> }[] }, got ' +
52
53
  JSON.stringify(value));
53
54
  }
54
55
  return {
@@ -56,8 +57,24 @@ export function validateInputs(value) {
56
57
  assets,
57
58
  ...(dynamic === undefined ? {} : { dynamic }),
58
59
  ...(paths === undefined ? {} : { paths }),
60
+ ...(modules === undefined ? {} : { modules }),
59
61
  };
60
62
  }
63
+ function isModule(value) {
64
+ const module = value;
65
+ return (typeof module === 'object' &&
66
+ module !== null &&
67
+ typeof module.name === 'string' &&
68
+ module.name !== '' &&
69
+ typeof module.path === 'string' &&
70
+ module.path !== '' &&
71
+ isStringList(module.entries) &&
72
+ (module.aliases === undefined ||
73
+ (typeof module.aliases === 'object' &&
74
+ module.aliases !== null &&
75
+ !Array.isArray(module.aliases) &&
76
+ Object.values(module.aliases).every((target) => typeof target === 'string'))));
77
+ }
61
78
  function isPaths(value) {
62
79
  const paths = value;
63
80
  return (typeof paths === 'object' &&
package/dist/index.d.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  import { type ConfigEnv, type Plugin, type UserConfig } from 'vite';
2
2
  import { refreshPaths, type PluginConfig } from './config.js';
3
3
  export type { DevServerUrl, InputOption, PluginConfig, RefreshConfig, ResolvedPaths, ResolvedPluginConfig } from './config.js';
4
- export type { DiscoveredInputs, DiscoveredPaths } from './discover.js';
4
+ export type { DiscoveredInputs, DiscoveredModule, DiscoveredPaths } from './discover.js';
5
+ export { collectAliases, resolveAlias, resolveEntry } from './aliases.js';
5
6
  interface GoravelPlugin extends Plugin {
6
7
  config: (config: UserConfig, env: ConfigEnv) => UserConfig;
7
8
  }
package/dist/index.js CHANGED
@@ -4,9 +4,11 @@ import colors from 'picocolors';
4
4
  import { globSync } from 'tinyglobby';
5
5
  import { createLogger, loadEnv, version as viteVersion } from 'vite';
6
6
  import fullReload from 'vite-plugin-full-reload';
7
- import { defaultManifest, refreshPaths, resolvePaths, resolvePluginConfig, } from './config.js';
7
+ import { aliasesKey, collectAliases, resolveEntry } from './aliases.js';
8
+ import { defaultManifest, moduleRefreshPaths, refreshPaths, resolvePaths, resolvePluginConfig, } from './config.js';
8
9
  import { discoverInputs } from './discover.js';
9
10
  import { configuredOrigin, devServerIndex, ensureCommandShouldRunInEnvironment, goravelVersion, placeholderOrigin, pluginVersion, resolveDevServerUrl, resolveEnvironmentServerConfig, } from './server.js';
11
+ export { collectAliases, resolveAlias, resolveEntry } from './aliases.js';
10
12
  /** The directories `refresh: true` watches (those that exist); extend them with `refresh: [...refreshPaths, 'app/**']`. */
11
13
  export { refreshPaths };
12
14
  const logger = createLogger('info', { prefix: '[goravel-vite-plugin]' });
@@ -79,9 +81,8 @@ function resolveGoravelPlugin(pluginConfig, assets) {
79
81
  let resolvedConfig;
80
82
  let userConfig;
81
83
  let paths;
82
- const defaultAliases = {
83
- '@': '/resources/js',
84
- };
84
+ // The @ aliases that point inside the project, handed to the application through the manifest and the hot file.
85
+ let aliases = {};
85
86
  // The URL the browser reaches the dev server at, known once it listens (or from
86
87
  // server.origin); undefined where there is no server of its own to listen.
87
88
  let devServerUrl;
@@ -117,8 +118,18 @@ function resolveGoravelPlugin(pluginConfig, assets) {
117
118
  logger.warn(`${userInputKey(userConfig)} is set in your Vite config, so it is built as written and the plugin's 'input' is ignored, ` +
118
119
  'along with the entries discovered from the views. Name the entries in one place or the other.', { timestamp: true });
119
120
  }
121
+ const modules = discovered?.modules ?? [];
122
+ // full-reload reads its paths when the server starts, after this hook; explicit refresh values are left alone.
123
+ const refreshed = pluginConfig.defaultRefresh?.paths;
124
+ refreshed?.push(...moduleRefreshPaths(root, modules).filter((pattern) => !refreshed.includes(pattern)));
125
+ // The user's aliases come first, so theirs wins over the plugin's of the same name.
126
+ const defaultAliases = pluginAliases(root, modules);
127
+ const alias = Array.isArray(userConfig.resolve?.alias)
128
+ ? [...userConfig.resolve.alias, ...Object.entries(defaultAliases).map(([find, replacement]) => ({ find, replacement }))]
129
+ : { ...defaultAliases, ...userConfig.resolve?.alias };
130
+ aliases = collectAliases(root, alias);
120
131
  // Absolute, so Rollup (Vite 7) finds the entries under a root that is not the working directory.
121
- const input = absoluteInput(command === 'build' ? resolveBuildInput(pluginConfig, discovered, assets, userNamedTheEntries) : (pluginConfig.input ?? []), root);
132
+ const input = absoluteInput(command === 'build' ? resolveBuildInput(pluginConfig, discovered, assets, userNamedTheEntries, aliases) : (pluginConfig.input ?? []), root);
122
133
  return {
123
134
  base: userConfig.base ?? (command === 'build' ? resolveBase(userBuildDirectory(userConfig, paths, root) ?? paths.buildDirectory, assetUrl) : ''),
124
135
  // Vite's own public directory would be copied into the build; Goravel serves public/ itself.
@@ -148,20 +159,7 @@ function resolveGoravelPlugin(pluginConfig, assets) {
148
159
  }
149
160
  : undefined),
150
161
  },
151
- resolve: {
152
- alias: Array.isArray(userConfig.resolve?.alias)
153
- ? [
154
- ...(userConfig.resolve?.alias ?? []),
155
- ...Object.keys(defaultAliases).map((alias) => ({
156
- find: alias,
157
- replacement: defaultAliases[alias],
158
- })),
159
- ]
160
- : {
161
- ...defaultAliases,
162
- ...userConfig.resolve?.alias,
163
- },
164
- },
162
+ resolve: { alias },
165
163
  };
166
164
  },
167
165
  configResolved(config) {
@@ -195,6 +193,18 @@ function resolveGoravelPlugin(pluginConfig, assets) {
195
193
  }
196
194
  return pluginConfig.transformOnServe(code.replaceAll(placeholderOrigin, url), url);
197
195
  },
196
+ writeBundle() {
197
+ const { build, root } = resolvedConfig;
198
+ if (build.manifest === false || build.ssr) {
199
+ return;
200
+ }
201
+ // Vite has written its manifest by now; the alias table joins it under a key no chunk can have.
202
+ const file = path.resolve(root, build.outDir, build.manifest === true ? defaultManifest : build.manifest);
203
+ if (fs.existsSync(file)) {
204
+ const manifest = JSON.parse(fs.readFileSync(file, 'utf8'));
205
+ fs.writeFileSync(file, JSON.stringify({ ...manifest, [aliasesKey]: aliases }, null, 2));
206
+ }
207
+ },
198
208
  configureServer(server) {
199
209
  const appUrl = loadEnv(resolvedConfig.mode, resolvedConfig.envDir, 'APP_URL').APP_URL ?? 'undefined';
200
210
  // A restarted server binds anew, unless the origin was configured.
@@ -212,7 +222,8 @@ function resolveGoravelPlugin(pluginConfig, assets) {
212
222
  }
213
223
  const viteDevServerUrl = origin ?? resolveDevServerUrl(address, server.config);
214
224
  setDevServerUrl(viteDevServerUrl);
215
- const hotFileContent = `${viteDevServerUrl}${server.config.base.replace(/\/$/, '')}`;
225
+ // One line of JSON: the URL, and the aliases the application resolves in {{ vite "@/app.js" }}.
226
+ const hotFileContent = JSON.stringify({ url: `${viteDevServerUrl}${server.config.base.replace(/\/$/, '')}`, aliases });
216
227
  claimHotFile(paths.hotFile, hotFileContent, server.config.logger);
217
228
  // A closed server no longer serves anything, so its hot file goes with it.
218
229
  server.httpServer?.once('close', () => releaseHotFile(paths.hotFile, hotFileContent));
@@ -245,7 +256,6 @@ function resolveGoravelPlugin(pluginConfig, assets) {
245
256
  },
246
257
  };
247
258
  }
248
- /** The build entries: `input` plus the discovered ones. Discovered assets go into the set. */
249
259
  /**
250
260
  * Warns when Vite writes its manifest under a name the application does not read. The
251
261
  * directory is the build directory's concern, warned about where the base is derived.
@@ -269,23 +279,48 @@ function userInputKey(userConfig) {
269
279
  }
270
280
  return userConfig.build?.rollupOptions?.input !== undefined ? 'build.rollupOptions.input' : undefined;
271
281
  }
272
- /** @param userNamedTheEntries - The user's own entries are built instead, so having none here is no error. */
273
- function resolveBuildInput(pluginConfig, discovered, assets, userNamedTheEntries) {
282
+ /**
283
+ * The build entries: `input` plus the discovered ones. Discovered assets go into the set.
284
+ *
285
+ * @param userNamedTheEntries - The user's own entries are built instead, so having none here is no error.
286
+ */
287
+ function resolveBuildInput(pluginConfig, discovered, assets, userNamedTheEntries, aliases) {
274
288
  if (discovered === null) {
275
289
  return pluginConfig.input ?? [];
276
290
  }
291
+ // Views may name an entry through an alias or with "./" and "..": the manifest keys are the plain paths.
277
292
  for (const asset of discovered.assets) {
278
- assets.add(asset);
293
+ assets.add(resolveEntry(asset, aliases));
279
294
  }
280
295
  for (const call of discovered.dynamic ?? []) {
281
296
  logger.warn(`${call.function} is called with a computed argument in ${call.template}; add that entry to 'input' yourself.`, { timestamp: true });
282
297
  }
283
- const input = mergeInput(pluginConfig.input, discovered.inputs);
298
+ // Module entries are built whether or not a view references them.
299
+ const entries = [...discovered.inputs, ...(discovered.modules ?? []).flatMap((module) => module.entries)];
300
+ const input = mergeInput(pluginConfig.input, [...new Set(entries.map((entry) => resolveEntry(entry, aliases)))]);
284
301
  if (!userNamedTheEntries && (Array.isArray(input) ? input.length === 0 : typeof input === 'object' && Object.keys(input).length === 0)) {
285
302
  throw new Error('goravel-vite-plugin: nothing to build. No view calls {{ vite ... }} with a constant entry point and no "input" is configured.');
286
303
  }
287
304
  return input;
288
305
  }
306
+ /**
307
+ * The plugin's aliases: `@` for the application, `@<name>` for each module with a
308
+ * `resources/js` directory, then those the modules declare, which may replace their own `@<name>`.
309
+ */
310
+ function pluginAliases(root, modules) {
311
+ const aliases = { '@': '/resources/js' };
312
+ for (const module of modules) {
313
+ if (fs.existsSync(path.join(root, module.path, 'resources/js'))) {
314
+ aliases[`@${module.name}`] = path.posix.join('/', module.path, 'resources/js');
315
+ }
316
+ }
317
+ for (const module of modules) {
318
+ for (const [name, directory] of Object.entries(module.aliases ?? {})) {
319
+ aliases[name] = path.posix.join('/', directory);
320
+ }
321
+ }
322
+ return aliases;
323
+ }
289
324
  function runDiscovery(pluginConfig, root) {
290
325
  logger.info(`Asking the application for its paths and entry points with "${pluginConfig.discoverCommand.join(' ')}"`, { timestamp: true });
291
326
  return discoverInputs(pluginConfig.discoverCommand, root, pluginConfig.discoverTimeout);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "goravel-vite-plugin",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Vite plugin for Goravel applications.",
5
5
  "type": "module",
6
6
  "keywords": [
@@ -38,7 +38,7 @@
38
38
  "engines": {
39
39
  "node": "^20.19.0 || >=22.12.0"
40
40
  },
41
- "packageManager": "pnpm@^12.18.0",
41
+ "packageManager": "pnpm@12.18.0",
42
42
  "publishConfig": {
43
43
  "access": "public"
44
44
  },