@virmator/frontend 14.38.0 → 14.39.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.
@@ -1,5 +1,10 @@
1
1
  import {log, logColors, replaceExtension} from '@augment-vir/common';
2
2
  import {alwaysReloadPlugin} from '@virmator/frontend/src/always-reload.vite.js';
3
+ import {
4
+ backendProxyPlugin,
5
+ type BackendProxyOptions,
6
+ } from '@virmator/frontend/src/backend-proxy.vite.js';
7
+ import {healDepsCachePlugin} from '@virmator/frontend/src/heal-deps-cache.vite.js';
3
8
  import {existsSync} from 'node:fs';
4
9
  import {readFile} from 'node:fs/promises';
5
10
  import {basename, dirname, join, relative} from 'node:path';
@@ -7,6 +12,7 @@ import {type UserConfig, type UserConfigExport} from 'vite';
7
12
 
8
13
  export const basePlugins = [
9
14
  alwaysReloadPlugin(),
15
+ healDepsCachePlugin(),
10
16
  ] as const;
11
17
 
12
18
  const httpsOptions = process.env.HTTPS_CERT_PATH
@@ -46,6 +52,12 @@ export type BaseConfigOptions = {
46
52
  packageDirPath?: string;
47
53
  /** Disables printing of server directory paths. */
48
54
  disableStartupLogs?: boolean;
55
+ /**
56
+ * Proxies dev server requests under a path to a local backend, only for pages loaded from the
57
+ * dev server's own addresses or from the `backendProxyOrigins` in the local frontend config:
58
+ * the repo's `.not-committed/virmator-frontend.*` file, or `backendProxy.localConfigPath`.
59
+ */
60
+ backendProxy?: BackendProxyOptions | undefined;
49
61
  };
50
62
 
51
63
  export type ConfigPaths = {
@@ -73,7 +85,11 @@ const externalDeps: string[] = [
73
85
  'playwright',
74
86
  ];
75
87
 
76
- export function createBaseConfig({forGitHubPages, packageDirPath}: BaseConfigOptions): {
88
+ export function createBaseConfig({
89
+ forGitHubPages,
90
+ packageDirPath,
91
+ backendProxy,
92
+ }: BaseConfigOptions): {
77
93
  baseConfig: UserConfig;
78
94
  basePaths: ConfigPaths;
79
95
  } {
@@ -110,6 +126,15 @@ export function createBaseConfig({forGitHubPages, packageDirPath}: BaseConfigOpt
110
126
  root: srcDir,
111
127
  plugins: [
112
128
  ...basePlugins,
129
+ ...(backendProxy
130
+ ? [
131
+ backendProxyPlugin({
132
+ ...backendProxy,
133
+ isHttps: !!httpsOptions,
134
+ repoRootPath: findGitRepoRoot(cwd),
135
+ }),
136
+ ]
137
+ : []),
113
138
  ],
114
139
  build: {
115
140
  outDir,
@@ -2,6 +2,8 @@ import { type PluginOption } from 'vite';
2
2
  /**
3
3
  * There are similar plugins out there that try to do this but they aren't aggressive enough. This
4
4
  * plugin literally always reloads on save, no questions asked.
5
+ *
6
+ * @category Util
5
7
  */
6
8
  export declare function alwaysReloadPlugin(config?: Partial<{
7
9
  exclusions: string[];
@@ -27,6 +27,8 @@ function mapToActualPaths(paths) {
27
27
  /**
28
28
  * There are similar plugins out there that try to do this but they aren't aggressive enough. This
29
29
  * plugin literally always reloads on save, no questions asked.
30
+ *
31
+ * @category Util
30
32
  */
31
33
  export function alwaysReloadPlugin(config = {}) {
32
34
  return {
@@ -0,0 +1,64 @@
1
+ import { type PartialWithUndefined } from '@augment-vir/common';
2
+ import { type PluginOption } from 'vite';
3
+ /**
4
+ * Options for proxying requests from the Vite dev server to a local backend.
5
+ *
6
+ * @category Internal
7
+ */
8
+ export type BackendProxyOptions = {
9
+ /** The port the local backend listens on. */
10
+ backendPort: number;
11
+ } & PartialWithUndefined<{
12
+ /**
13
+ * Requests under this path are proxied to the backend with this path removed, so `/api/users`
14
+ * reaches the backend as `/users`.
15
+ *
16
+ * @default '/api'
17
+ */
18
+ proxyPath: string;
19
+ /**
20
+ * Reads the local frontend config from this file instead of
21
+ * `.not-committed/virmator-frontend.*`. Relative paths resolve from the git repo root. Unlike
22
+ * the default location, this file must exist.
23
+ */
24
+ localConfigPath: string;
25
+ }>;
26
+ /**
27
+ * Shape of the machine-local frontend config, read from any config file type that `config-vir`
28
+ * supports at `.not-committed/virmator-frontend.*` in the git repo root.
29
+ *
30
+ * @category Internal
31
+ */
32
+ export declare const localFrontendConfigShape: import("object-shape-tester").Shape<{
33
+ /**
34
+ * Full origins, such as `https://my-app.example.ts.net`, that may send requests through the
35
+ * backend proxy on top of the addresses the dev server itself listens on. Their host names are
36
+ * also added to Vite's `server.allowedHosts`.
37
+ */
38
+ backendProxyOrigins: string[];
39
+ }>;
40
+ /**
41
+ * Type for a `.not-committed/virmator-frontend.ts` config file: `export default
42
+ * {backendProxyOrigins: []} satisfies LocalFrontendConfig;`
43
+ *
44
+ * @category Main
45
+ */
46
+ export type LocalFrontendConfig = typeof localFrontendConfigShape.runtimeType;
47
+ /**
48
+ * Proxies requests under a path to a local backend, but only for pages loaded from an allowed
49
+ * origin: any address the dev server listens on plus the `backendProxyOrigins` from the local
50
+ * frontend config. The `Origin` header is forwarded unchanged, so the backend must trust those same
51
+ * origins. Requests without browser headers, such as from `curl`, are always proxied, so when the
52
+ * dev server is reachable over a network, so is the backend. WebSocket connections are not
53
+ * proxied.
54
+ *
55
+ * @category Util
56
+ */
57
+ export declare function backendProxyPlugin({ backendPort, proxyPath, localConfigPath, isHttps, repoRootPath, }: Readonly<BackendProxyOptions & {
58
+ isHttps?: boolean | undefined;
59
+ /**
60
+ * The git repo root. The local frontend config is read from its `.not-committed` folder,
61
+ * and a relative `localConfigPath` resolves from it.
62
+ */
63
+ repoRootPath: string;
64
+ }>): PluginOption;
@@ -0,0 +1,173 @@
1
+ import { assertWrap, check } from '@augment-vir/assert';
2
+ import { escapeStringForRegExp, getObjectTypedValues, HttpStatus, } from '@augment-vir/common';
3
+ import { findConfigFile, loadConfig } from 'config-vir';
4
+ import { networkInterfaces } from 'node:os';
5
+ import { join, resolve } from 'node:path';
6
+ import { defineShape } from 'object-shape-tester';
7
+ import { buildUrl, parseUrl } from 'url-vir';
8
+ /**
9
+ * Shape of the machine-local frontend config, read from any config file type that `config-vir`
10
+ * supports at `.not-committed/virmator-frontend.*` in the git repo root.
11
+ *
12
+ * @category Internal
13
+ */
14
+ export const localFrontendConfigShape = defineShape({
15
+ /**
16
+ * Full origins, such as `https://my-app.example.ts.net`, that may send requests through the
17
+ * backend proxy on top of the addresses the dev server itself listens on. Their host names are
18
+ * also added to Vite's `server.allowedHosts`.
19
+ */
20
+ backendProxyOrigins: [''],
21
+ });
22
+ /** @returns Every extra origin from the local frontend config, or none when there is no config. */
23
+ async function loadExtraOrigins({ repoRootPath, localConfigPath, }) {
24
+ const configPath = localConfigPath
25
+ ? resolve(assertWrap.isTruthy(repoRootPath, `No git repo root found to resolve '${localConfigPath}' from.`), localConfigPath)
26
+ : repoRootPath &&
27
+ (await findConfigFile({
28
+ directory: join(repoRootPath, '.not-committed'),
29
+ baseName: 'virmator-frontend',
30
+ }));
31
+ if (!configPath) {
32
+ return [];
33
+ }
34
+ const { backendProxyOrigins } = await loadConfig({
35
+ configPath,
36
+ configShape: localFrontendConfigShape,
37
+ });
38
+ backendProxyOrigins.forEach((origin) => {
39
+ if (!URL.canParse(origin) || parseUrl(origin).origin !== origin) {
40
+ throw new Error(`Invalid backend proxy origin '${origin}' in '${configPath}'. Use only a protocol, host name, and optional port, such as 'https://my-app.example.ts.net'.`);
41
+ }
42
+ });
43
+ return backendProxyOrigins;
44
+ }
45
+ function readServerOrigins({ server, isHttps, }) {
46
+ const resolvedOrigins = [
47
+ ...(server.resolvedUrls?.local || []),
48
+ ...(server.resolvedUrls?.network || []),
49
+ ].map((url) => parseUrl(url).origin);
50
+ const address = server.httpServer?.address();
51
+ if (!address || check.isString(address)) {
52
+ return resolvedOrigins;
53
+ }
54
+ /**
55
+ * `resolvedUrls` only lists the URLs Vite prints at startup: it shows `127.0.0.1` as
56
+ * `localhost` and leaves out IPv6 addresses, even when the server listens on them.
57
+ */
58
+ const isWildcard = address.address === '::' || address.address === '0.0.0.0';
59
+ const listeningAddresses = isWildcard
60
+ ? getObjectTypedValues(networkInterfaces())
61
+ .flat()
62
+ .filter(check.isDefined)
63
+ .filter((detail) => address.address === '::' || detail.family === 'IPv4')
64
+ .map((detail) => detail.address)
65
+ : [
66
+ address.address,
67
+ ];
68
+ return [
69
+ ...resolvedOrigins,
70
+ ...listeningAddresses.map((listeningAddress) => {
71
+ return buildUrl({
72
+ protocol: isHttps ? 'https' : 'http',
73
+ hostname: listeningAddress.includes(':')
74
+ ? `[${listeningAddress}]`
75
+ : listeningAddress,
76
+ port: address.port,
77
+ }).origin;
78
+ }),
79
+ ];
80
+ }
81
+ /**
82
+ * Proxies requests under a path to a local backend, but only for pages loaded from an allowed
83
+ * origin: any address the dev server listens on plus the `backendProxyOrigins` from the local
84
+ * frontend config. The `Origin` header is forwarded unchanged, so the backend must trust those same
85
+ * origins. Requests without browser headers, such as from `curl`, are always proxied, so when the
86
+ * dev server is reachable over a network, so is the backend. WebSocket connections are not
87
+ * proxied.
88
+ *
89
+ * @category Util
90
+ */
91
+ export function backendProxyPlugin({ backendPort, proxyPath = '/api', localConfigPath, isHttps, repoRootPath, }) {
92
+ const extraOriginsPromise = loadExtraOrigins({
93
+ repoRootPath,
94
+ localConfigPath,
95
+ });
96
+ /**
97
+ * Only the serve-only hooks below await this, so without a handler a failed load crashes the
98
+ * process during `vite build` or before Vite calls `config()`. The hooks still rethrow it.
99
+ */
100
+ extraOriginsPromise.catch(() => undefined);
101
+ /**
102
+ * Vite's proxy matches plain string keys with `startsWith`, which would also catch sibling
103
+ * paths like `/apiary`. Keys starting with `^` are matched as regular expressions instead.
104
+ */
105
+ const proxyPathPattern = `^${escapeStringForRegExp(proxyPath)}(?=[/?]|$)`;
106
+ return {
107
+ name: 'backendProxyPlugin',
108
+ apply: 'serve',
109
+ async config() {
110
+ const extraOrigins = await extraOriginsPromise;
111
+ return {
112
+ server: {
113
+ allowedHosts: extraOrigins.map((origin) => parseUrl(origin).hostname),
114
+ proxy: {
115
+ [proxyPathPattern]: {
116
+ target: buildUrl({
117
+ protocol: isHttps ? 'https' : 'http',
118
+ hostname: 'localhost',
119
+ port: backendPort,
120
+ }).origin,
121
+ /** Local dev certificates are usually self-signed. */
122
+ secure: false,
123
+ rewrite(path) {
124
+ const backendPath = path.slice(proxyPath.length);
125
+ return backendPath.startsWith('/')
126
+ ? backendPath
127
+ : `/${backendPath}`;
128
+ },
129
+ },
130
+ },
131
+ },
132
+ };
133
+ },
134
+ async configureServer(server) {
135
+ const extraOrigins = await extraOriginsPromise;
136
+ const proxyPathRegExp = new RegExp(proxyPathPattern);
137
+ /**
138
+ * Middlewares added here run before Vite's own proxy middleware. This isn't mounted on
139
+ * `proxyPath` because Connect's prefix matching differs from the proxy's, such as for
140
+ * `/api.json`.
141
+ */
142
+ server.middlewares.use((request, response, next) => {
143
+ if (!request.url || !proxyPathRegExp.test(request.url)) {
144
+ next();
145
+ return;
146
+ }
147
+ const origin = request.headers.origin;
148
+ /**
149
+ * Browsers omit `Origin` on same-origin GET requests and on cross-site GET requests
150
+ * that don't use CORS, such as an `<img>` tag. `Sec-Fetch-Site` tells those apart.
151
+ * Clients that send neither header are not browsers, and they could forge either
152
+ * header anyway.
153
+ */
154
+ const fetchSite = request.headers['sec-fetch-site'];
155
+ const isAllowed = origin
156
+ ? [
157
+ ...readServerOrigins({
158
+ server,
159
+ isHttps,
160
+ }),
161
+ ...extraOrigins,
162
+ ].includes(origin)
163
+ : !fetchSite || fetchSite === 'same-origin' || fetchSite === 'none';
164
+ if (!isAllowed) {
165
+ response.statusCode = HttpStatus.Forbidden;
166
+ response.end(`Origin '${origin || fetchSite || ''}' is not allowed through the backend proxy.`);
167
+ return;
168
+ }
169
+ next();
170
+ });
171
+ },
172
+ };
173
+ }
@@ -1,4 +1,7 @@
1
1
  import { NpmDepType } from '@virmator/core';
2
+ export * from './always-reload.vite.js';
3
+ export * from './backend-proxy.vite.js';
4
+ export * from './heal-deps-cache.vite.js';
2
5
  /**
3
6
  * A virmator plugin for running and building frontend packages.
4
7
  *
package/dist/frontend.js CHANGED
@@ -6,6 +6,9 @@ import mri from 'mri';
6
6
  import { cp, rm } from 'node:fs/promises';
7
7
  import { join, relative, resolve } from 'node:path';
8
8
  import { pathToFileURL } from 'node:url';
9
+ export * from './always-reload.vite.js';
10
+ export * from './backend-proxy.vite.js';
11
+ export * from './heal-deps-cache.vite.js';
9
12
  /**
10
13
  * A virmator plugin for running and building frontend packages.
11
14
  *
@@ -0,0 +1,10 @@
1
+ import { type PluginOption } from 'vite';
2
+ /**
3
+ * Restarts the dev server (with a forced dependency re-optimization) when Vite's dep optimizer
4
+ * cache gets deleted out from under it, such as by `npm install` or by another `vite --force`
5
+ * server sharing the same `node_modules`. Without this, Vite keeps serving 504 "Outdated Optimize
6
+ * Dep" responses for the deleted files forever and the page stays blank.
7
+ *
8
+ * @category Util
9
+ */
10
+ export declare function healDepsCachePlugin(): PluginOption;
@@ -0,0 +1,64 @@
1
+ import { createBlockingInterval } from '@augment-vir/common';
2
+ import { existsSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ /**
5
+ * Restarts the dev server (with a forced dependency re-optimization) when Vite's dep optimizer
6
+ * cache gets deleted out from under it, such as by `npm install` or by another `vite --force`
7
+ * server sharing the same `node_modules`. Without this, Vite keeps serving 504 "Outdated Optimize
8
+ * Dep" responses for the deleted files forever and the page stays blank.
9
+ *
10
+ * @category Util
11
+ */
12
+ export function healDepsCachePlugin() {
13
+ return {
14
+ name: 'healDepsCachePlugin',
15
+ apply: 'serve',
16
+ configureServer(server) {
17
+ const httpServer = server.httpServer;
18
+ /**
19
+ * Middleware mode has no HTTP server whose `close` event can stop the poll, and the
20
+ * surrounding app owns restarts there anyway.
21
+ */
22
+ if (!httpServer) {
23
+ return;
24
+ }
25
+ const metadataPath = join(server.config.cacheDir, 'deps', '_metadata.json');
26
+ /**
27
+ * `--force` wipes the cache at startup and the optimizer only writes it once the first
28
+ * page load finishes crawling imports, so stay disarmed until the cache has existed.
29
+ */
30
+ let hasSeenMetadata = false;
31
+ /**
32
+ * Vite's own re-optimizations swap in the new cache with two renames, which can leave a
33
+ * brief gap. Only a cache that stays missing across polls counts as deleted.
34
+ */
35
+ let missingPollCount = 0;
36
+ const poll = createBlockingInterval(async () => {
37
+ if (existsSync(metadataPath)) {
38
+ hasSeenMetadata = true;
39
+ missingPollCount = 0;
40
+ return;
41
+ }
42
+ else if (!hasSeenMetadata) {
43
+ return;
44
+ }
45
+ missingPollCount++;
46
+ if (missingPollCount < 2) {
47
+ return;
48
+ }
49
+ hasSeenMetadata = false;
50
+ missingPollCount = 0;
51
+ server.config.logger.warn('Dependency optimizer cache was deleted. Restarting dev server to rebuild it.', {
52
+ timestamp: true,
53
+ });
54
+ /** Connected pages reload on their own once the restarted server is reachable. */
55
+ await server.restart(true);
56
+ }, {
57
+ milliseconds: 500,
58
+ });
59
+ poll.intervalId.unref();
60
+ /** Each restart creates a new HTTP server and runs this hook again. */
61
+ httpServer.once('close', poll.clearInterval);
62
+ },
63
+ };
64
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@virmator/frontend",
3
- "version": "14.38.0",
3
+ "version": "14.39.0",
4
4
  "description": "Default frontend plugin for virmator.",
5
5
  "keywords": [
6
6
  "virmator",
@@ -35,17 +35,21 @@
35
35
  "test:update": "npm test update"
36
36
  },
37
37
  "dependencies": {
38
- "@augment-vir/assert": "^32.5.0",
39
- "@augment-vir/common": "^32.5.0",
40
- "@augment-vir/node": "^32.5.0",
41
- "@virmator/core": "^14.38.0",
42
- "mri": "^1.2.0"
38
+ "@augment-vir/assert": "^32.7.1",
39
+ "@augment-vir/common": "^32.7.1",
40
+ "@augment-vir/node": "^32.7.1",
41
+ "@virmator/core": "^14.39.0",
42
+ "config-vir": "^1.1.0",
43
+ "mri": "^1.2.0",
44
+ "object-shape-tester": "^6.15.3",
45
+ "tsx": "^4.23.15",
46
+ "url-vir": "^2.2.2"
43
47
  },
44
48
  "devDependencies": {
45
- "@augment-vir/test": "^32.5.0",
46
- "@types/node": "^26.6.5",
49
+ "@augment-vir/test": "^32.7.1",
50
+ "@types/node": "^26.6.6",
47
51
  "typescript": "^6.0.3",
48
- "vite": "^8.3.4",
52
+ "vite": "^8.3.8",
49
53
  "vite-tsconfig-paths": "^6.1.1"
50
54
  },
51
55
  "engines": {
@@ -28,6 +28,8 @@ function mapToActualPaths(paths: Readonly<string[]>): Readonly<string[]> {
28
28
  /**
29
29
  * There are similar plugins out there that try to do this but they aren't aggressive enough. This
30
30
  * plugin literally always reloads on save, no questions asked.
31
+ *
32
+ * @category Util
31
33
  */
32
34
  export function alwaysReloadPlugin(
33
35
  config: Partial<{
@@ -0,0 +1,265 @@
1
+ import {assertWrap, check} from '@augment-vir/assert';
2
+ import {
3
+ escapeStringForRegExp,
4
+ getObjectTypedValues,
5
+ HttpStatus,
6
+ type PartialWithUndefined,
7
+ } from '@augment-vir/common';
8
+ import {findConfigFile, loadConfig} from 'config-vir';
9
+ import {networkInterfaces} from 'node:os';
10
+ import {join, resolve} from 'node:path';
11
+ import {defineShape} from 'object-shape-tester';
12
+ import {buildUrl, parseUrl} from 'url-vir';
13
+ import {type PluginOption, type ViteDevServer} from 'vite';
14
+
15
+ /**
16
+ * Options for proxying requests from the Vite dev server to a local backend.
17
+ *
18
+ * @category Internal
19
+ */
20
+ export type BackendProxyOptions = {
21
+ /** The port the local backend listens on. */
22
+ backendPort: number;
23
+ } & PartialWithUndefined<{
24
+ /**
25
+ * Requests under this path are proxied to the backend with this path removed, so `/api/users`
26
+ * reaches the backend as `/users`.
27
+ *
28
+ * @default '/api'
29
+ */
30
+ proxyPath: string;
31
+ /**
32
+ * Reads the local frontend config from this file instead of
33
+ * `.not-committed/virmator-frontend.*`. Relative paths resolve from the git repo root. Unlike
34
+ * the default location, this file must exist.
35
+ */
36
+ localConfigPath: string;
37
+ }>;
38
+
39
+ /**
40
+ * Shape of the machine-local frontend config, read from any config file type that `config-vir`
41
+ * supports at `.not-committed/virmator-frontend.*` in the git repo root.
42
+ *
43
+ * @category Internal
44
+ */
45
+ export const localFrontendConfigShape = defineShape({
46
+ /**
47
+ * Full origins, such as `https://my-app.example.ts.net`, that may send requests through the
48
+ * backend proxy on top of the addresses the dev server itself listens on. Their host names are
49
+ * also added to Vite's `server.allowedHosts`.
50
+ */
51
+ backendProxyOrigins: [''],
52
+ });
53
+
54
+ /**
55
+ * Type for a `.not-committed/virmator-frontend.ts` config file: `export default
56
+ * {backendProxyOrigins: []} satisfies LocalFrontendConfig;`
57
+ *
58
+ * @category Main
59
+ */
60
+ export type LocalFrontendConfig = typeof localFrontendConfigShape.runtimeType;
61
+
62
+ /** @returns Every extra origin from the local frontend config, or none when there is no config. */
63
+ async function loadExtraOrigins({
64
+ repoRootPath,
65
+ localConfigPath,
66
+ }: Readonly<{
67
+ repoRootPath: string;
68
+ localConfigPath: string | undefined;
69
+ }>) {
70
+ const configPath = localConfigPath
71
+ ? resolve(
72
+ assertWrap.isTruthy(
73
+ repoRootPath,
74
+ `No git repo root found to resolve '${localConfigPath}' from.`,
75
+ ),
76
+ localConfigPath,
77
+ )
78
+ : repoRootPath &&
79
+ (await findConfigFile({
80
+ directory: join(repoRootPath, '.not-committed'),
81
+ baseName: 'virmator-frontend',
82
+ }));
83
+
84
+ if (!configPath) {
85
+ return [];
86
+ }
87
+
88
+ const {backendProxyOrigins} = await loadConfig({
89
+ configPath,
90
+ configShape: localFrontendConfigShape,
91
+ });
92
+
93
+ backendProxyOrigins.forEach((origin) => {
94
+ if (!URL.canParse(origin) || parseUrl(origin).origin !== origin) {
95
+ throw new Error(
96
+ `Invalid backend proxy origin '${origin}' in '${configPath}'. Use only a protocol, host name, and optional port, such as 'https://my-app.example.ts.net'.`,
97
+ );
98
+ }
99
+ });
100
+
101
+ return backendProxyOrigins;
102
+ }
103
+
104
+ function readServerOrigins({
105
+ server,
106
+ isHttps,
107
+ }: Readonly<{
108
+ server: Readonly<Pick<ViteDevServer, 'resolvedUrls' | 'httpServer'>>;
109
+ isHttps: boolean | undefined;
110
+ }>) {
111
+ const resolvedOrigins = [
112
+ ...(server.resolvedUrls?.local || []),
113
+ ...(server.resolvedUrls?.network || []),
114
+ ].map((url) => parseUrl(url).origin);
115
+ const address = server.httpServer?.address();
116
+
117
+ if (!address || check.isString(address)) {
118
+ return resolvedOrigins;
119
+ }
120
+
121
+ /**
122
+ * `resolvedUrls` only lists the URLs Vite prints at startup: it shows `127.0.0.1` as
123
+ * `localhost` and leaves out IPv6 addresses, even when the server listens on them.
124
+ */
125
+ const isWildcard = address.address === '::' || address.address === '0.0.0.0';
126
+ const listeningAddresses = isWildcard
127
+ ? getObjectTypedValues(networkInterfaces())
128
+ .flat()
129
+ .filter(check.isDefined)
130
+ .filter((detail) => address.address === '::' || detail.family === 'IPv4')
131
+ .map((detail) => detail.address)
132
+ : [
133
+ address.address,
134
+ ];
135
+
136
+ return [
137
+ ...resolvedOrigins,
138
+ ...listeningAddresses.map((listeningAddress) => {
139
+ return buildUrl({
140
+ protocol: isHttps ? 'https' : 'http',
141
+ hostname: listeningAddress.includes(':')
142
+ ? `[${listeningAddress}]`
143
+ : listeningAddress,
144
+ port: address.port,
145
+ }).origin;
146
+ }),
147
+ ];
148
+ }
149
+
150
+ /**
151
+ * Proxies requests under a path to a local backend, but only for pages loaded from an allowed
152
+ * origin: any address the dev server listens on plus the `backendProxyOrigins` from the local
153
+ * frontend config. The `Origin` header is forwarded unchanged, so the backend must trust those same
154
+ * origins. Requests without browser headers, such as from `curl`, are always proxied, so when the
155
+ * dev server is reachable over a network, so is the backend. WebSocket connections are not
156
+ * proxied.
157
+ *
158
+ * @category Util
159
+ */
160
+ export function backendProxyPlugin({
161
+ backendPort,
162
+ proxyPath = '/api',
163
+ localConfigPath,
164
+ isHttps,
165
+ repoRootPath,
166
+ }: Readonly<
167
+ BackendProxyOptions & {
168
+ isHttps?: boolean | undefined;
169
+ /**
170
+ * The git repo root. The local frontend config is read from its `.not-committed` folder,
171
+ * and a relative `localConfigPath` resolves from it.
172
+ */
173
+ repoRootPath: string;
174
+ }
175
+ >): PluginOption {
176
+ const extraOriginsPromise = loadExtraOrigins({
177
+ repoRootPath,
178
+ localConfigPath,
179
+ });
180
+ /**
181
+ * Only the serve-only hooks below await this, so without a handler a failed load crashes the
182
+ * process during `vite build` or before Vite calls `config()`. The hooks still rethrow it.
183
+ */
184
+ extraOriginsPromise.catch(() => undefined);
185
+ /**
186
+ * Vite's proxy matches plain string keys with `startsWith`, which would also catch sibling
187
+ * paths like `/apiary`. Keys starting with `^` are matched as regular expressions instead.
188
+ */
189
+ const proxyPathPattern = `^${escapeStringForRegExp(proxyPath)}(?=[/?]|$)`;
190
+
191
+ return {
192
+ name: 'backendProxyPlugin',
193
+ apply: 'serve',
194
+ async config() {
195
+ const extraOrigins = await extraOriginsPromise;
196
+
197
+ return {
198
+ server: {
199
+ allowedHosts: extraOrigins.map((origin) => parseUrl(origin).hostname),
200
+ proxy: {
201
+ [proxyPathPattern]: {
202
+ target: buildUrl({
203
+ protocol: isHttps ? 'https' : 'http',
204
+ hostname: 'localhost',
205
+ port: backendPort,
206
+ }).origin,
207
+ /** Local dev certificates are usually self-signed. */
208
+ secure: false,
209
+ rewrite(path) {
210
+ const backendPath = path.slice(proxyPath.length);
211
+ return backendPath.startsWith('/')
212
+ ? backendPath
213
+ : `/${backendPath}`;
214
+ },
215
+ },
216
+ },
217
+ },
218
+ };
219
+ },
220
+ async configureServer(server) {
221
+ const extraOrigins = await extraOriginsPromise;
222
+ const proxyPathRegExp = new RegExp(proxyPathPattern);
223
+
224
+ /**
225
+ * Middlewares added here run before Vite's own proxy middleware. This isn't mounted on
226
+ * `proxyPath` because Connect's prefix matching differs from the proxy's, such as for
227
+ * `/api.json`.
228
+ */
229
+ server.middlewares.use((request, response, next) => {
230
+ if (!request.url || !proxyPathRegExp.test(request.url)) {
231
+ next();
232
+ return;
233
+ }
234
+
235
+ const origin = request.headers.origin;
236
+ /**
237
+ * Browsers omit `Origin` on same-origin GET requests and on cross-site GET requests
238
+ * that don't use CORS, such as an `<img>` tag. `Sec-Fetch-Site` tells those apart.
239
+ * Clients that send neither header are not browsers, and they could forge either
240
+ * header anyway.
241
+ */
242
+ const fetchSite = request.headers['sec-fetch-site'];
243
+ const isAllowed = origin
244
+ ? [
245
+ ...readServerOrigins({
246
+ server,
247
+ isHttps,
248
+ }),
249
+ ...extraOrigins,
250
+ ].includes(origin)
251
+ : !fetchSite || fetchSite === 'same-origin' || fetchSite === 'none';
252
+
253
+ if (!isAllowed) {
254
+ response.statusCode = HttpStatus.Forbidden;
255
+ response.end(
256
+ `Origin '${origin || fetchSite || ''}' is not allowed through the backend proxy.`,
257
+ );
258
+ return;
259
+ }
260
+
261
+ next();
262
+ });
263
+ },
264
+ };
265
+ }
package/src/frontend.ts CHANGED
@@ -8,6 +8,10 @@ import {join, relative, resolve} from 'node:path';
8
8
  import {pathToFileURL} from 'node:url';
9
9
  import {type UserConfig} from 'vite';
10
10
 
11
+ export * from './always-reload.vite.js';
12
+ export * from './backend-proxy.vite.js';
13
+ export * from './heal-deps-cache.vite.js';
14
+
11
15
  /**
12
16
  * A virmator plugin for running and building frontend packages.
13
17
  *
@@ -0,0 +1,76 @@
1
+ import {createBlockingInterval} from '@augment-vir/common';
2
+ import {existsSync} from 'node:fs';
3
+ import {join} from 'node:path';
4
+ import {type PluginOption} from 'vite';
5
+
6
+ /**
7
+ * Restarts the dev server (with a forced dependency re-optimization) when Vite's dep optimizer
8
+ * cache gets deleted out from under it, such as by `npm install` or by another `vite --force`
9
+ * server sharing the same `node_modules`. Without this, Vite keeps serving 504 "Outdated Optimize
10
+ * Dep" responses for the deleted files forever and the page stays blank.
11
+ *
12
+ * @category Util
13
+ */
14
+ export function healDepsCachePlugin(): PluginOption {
15
+ return {
16
+ name: 'healDepsCachePlugin',
17
+ apply: 'serve',
18
+ configureServer(server) {
19
+ const httpServer = server.httpServer;
20
+ /**
21
+ * Middleware mode has no HTTP server whose `close` event can stop the poll, and the
22
+ * surrounding app owns restarts there anyway.
23
+ */
24
+ if (!httpServer) {
25
+ return;
26
+ }
27
+
28
+ const metadataPath = join(server.config.cacheDir, 'deps', '_metadata.json');
29
+ /**
30
+ * `--force` wipes the cache at startup and the optimizer only writes it once the first
31
+ * page load finishes crawling imports, so stay disarmed until the cache has existed.
32
+ */
33
+ let hasSeenMetadata = false;
34
+ /**
35
+ * Vite's own re-optimizations swap in the new cache with two renames, which can leave a
36
+ * brief gap. Only a cache that stays missing across polls counts as deleted.
37
+ */
38
+ let missingPollCount = 0;
39
+
40
+ const poll = createBlockingInterval(
41
+ async () => {
42
+ if (existsSync(metadataPath)) {
43
+ hasSeenMetadata = true;
44
+ missingPollCount = 0;
45
+ return;
46
+ } else if (!hasSeenMetadata) {
47
+ return;
48
+ }
49
+
50
+ missingPollCount++;
51
+ if (missingPollCount < 2) {
52
+ return;
53
+ }
54
+
55
+ hasSeenMetadata = false;
56
+ missingPollCount = 0;
57
+ server.config.logger.warn(
58
+ 'Dependency optimizer cache was deleted. Restarting dev server to rebuild it.',
59
+ {
60
+ timestamp: true,
61
+ },
62
+ );
63
+ /** Connected pages reload on their own once the restarted server is reachable. */
64
+ await server.restart(true);
65
+ },
66
+ {
67
+ milliseconds: 500,
68
+ },
69
+ );
70
+ poll.intervalId.unref();
71
+
72
+ /** Each restart creates a new HTTP server and runs this hook again. */
73
+ httpServer.once('close', poll.clearInterval);
74
+ },
75
+ };
76
+ }