@analogjs/vite-plugin-nitro 3.0.0-alpha.91 → 3.0.0-alpha.93
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/migrations/migration.json +7 -1
- package/migrations/update-nitro-options/update-nitro-options.d.ts +2 -0
- package/migrations/update-nitro-options/update-nitro-options.js +122 -0
- package/migrations/update-nitro-options/update-nitro-options.js.map +1 -0
- package/package.json +5 -10
- package/src/index.d.ts +5 -5
- package/src/index.js +1 -2
- package/src/index.js.map +1 -1
- package/src/lib/build-server.d.ts +2 -3
- package/src/lib/build-server.js +88 -35
- package/src/lib/build-server.js.map +1 -1
- package/src/lib/build-sitemap.d.ts +8 -8
- package/src/lib/build-sitemap.js +77 -116
- package/src/lib/build-sitemap.js.map +1 -1
- package/src/lib/build-ssr.d.ts +1 -2
- package/src/lib/build-ssr.js +6 -15
- package/src/lib/build-ssr.js.map +1 -1
- package/src/lib/hooks/post-rendering-hook.d.ts +1 -1
- package/src/lib/hooks/post-rendering-hook.js +1 -3
- package/src/lib/hooks/post-rendering-hook.js.map +1 -1
- package/src/lib/options.d.ts +30 -25
- package/src/lib/plugins/dev-server-plugin.d.ts +1 -1
- package/src/lib/plugins/dev-server-plugin.js +13 -11
- package/src/lib/plugins/dev-server-plugin.js.map +1 -1
- package/src/lib/plugins/page-endpoints.js +10 -14
- package/src/lib/plugins/page-endpoints.js.map +1 -1
- package/src/lib/plugins/server-fn-id-plugin.d.ts +4 -1
- package/src/lib/plugins/server-fn-id-plugin.js.map +1 -1
- package/src/lib/runtime/locale-worker-entry.mjs +71 -0
- package/src/lib/runtime/locale-workers.mjs +193 -0
- package/src/lib/utils/get-content-files.js +1 -1
- package/src/lib/utils/get-content-files.js.map +1 -1
- package/src/lib/utils/get-page-handlers.d.ts +10 -7
- package/src/lib/utils/get-page-handlers.js +10 -7
- package/src/lib/utils/get-page-handlers.js.map +1 -1
- package/src/lib/utils/i18n-prerender.d.ts +1 -0
- package/src/lib/utils/i18n-prerender.js +48 -1
- package/src/lib/utils/i18n-prerender.js.map +1 -1
- package/src/lib/utils/i18n-workers.d.ts +6 -0
- package/src/lib/utils/i18n-workers.js +55 -0
- package/src/lib/utils/i18n-workers.js.map +1 -0
- package/src/lib/utils/register-dev-middleware.d.ts +32 -4
- package/src/lib/utils/register-dev-middleware.js +34 -21
- package/src/lib/utils/register-dev-middleware.js.map +1 -1
- package/src/lib/utils/renderers.d.ts +5 -33
- package/src/lib/utils/renderers.js +121 -75
- package/src/lib/utils/renderers.js.map +1 -1
- package/src/lib/utils/server-fn-endpoints.js +3 -1
- package/src/lib/utils/server-fn-endpoints.js.map +1 -1
- package/src/lib/vite-plugin-nitro.d.ts +9 -2
- package/src/lib/vite-plugin-nitro.js +187 -562
- package/src/lib/vite-plugin-nitro.js.map +1 -1
- package/src/lib/utils/debug.d.ts +0 -5
- package/src/lib/utils/debug.js +0 -15
- package/src/lib/utils/debug.js.map +0 -1
- package/src/lib/utils/node-web-bridge.d.ts +0 -3
- package/src/lib/utils/node-web-bridge.js +0 -55
- package/src/lib/utils/node-web-bridge.js.map +0 -1
- package/src/lib/utils/rolldown.d.ts +0 -2
- package/src/lib/utils/rolldown.js +0 -12
- package/src/lib/utils/rolldown.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server-fn-id-plugin.js","names":[],"sources":["../../../../src/lib/plugins/server-fn-id-plugin.ts"],"sourcesContent":["import { serverFnFileId } from '../utils/derive-server-fn-id.js';\nimport { injectServerFnIds } from '../utils/inject-server-fn-ids.js';\n\n/**\n * Nitro-build transform that stamps the derived id into each `serverFn` config\n * in a `*.server.ts`, so a function registers under the same opaque route the\n * client proxy dispatches to. The SSR app build does the same via the platform\n * plugin; this covers the separate Nitro server graph the dispatch handler pulls\n * the modules into.\n */\nexport function serverFnIdPlugin(projectRoot: string) {\n return {\n name: 'analogjs-server-fn-id',\n transform(code: string
|
|
1
|
+
{"version":3,"file":"server-fn-id-plugin.js","names":[],"sources":["../../../../src/lib/plugins/server-fn-id-plugin.ts"],"sourcesContent":["import { serverFnFileId } from '../utils/derive-server-fn-id.js';\nimport { injectServerFnIds } from '../utils/inject-server-fn-ids.js';\n\n/**\n * Nitro-build transform that stamps the derived id into each `serverFn` config\n * in a `*.server.ts`, so a function registers under the same opaque route the\n * client proxy dispatches to. The SSR app build does the same via the platform\n * plugin; this covers the separate Nitro server graph the dispatch handler pulls\n * the modules into.\n */\nexport function serverFnIdPlugin(projectRoot: string): {\n name: string;\n transform(code: string, id: string): { code: string; map: null } | undefined;\n} {\n return {\n name: 'analogjs-server-fn-id',\n transform(\n code: string,\n id: string,\n ): { code: string; map: null } | undefined {\n if (!id.endsWith('.server.ts')) {\n return;\n }\n const injected = injectServerFnIds(code, serverFnFileId(id, projectRoot));\n return injected ? { code: injected.code, map: null } : undefined;\n },\n };\n}\n"],"mappings":";;;;;;;;;;AAUA,SAAgB,iBAAiB,aAG/B;AACA,QAAO;EACL,MAAM;EACN,UACE,MACA,IACyC;AACzC,OAAI,CAAC,GAAG,SAAS,aAAa,CAC5B;GAEF,MAAM,WAAW,kBAAkB,MAAM,eAAe,IAAI,YAAY,CAAC;AACzE,UAAO,WAAW;IAAE,MAAM,SAAS;IAAM,KAAK;IAAM,GAAG,KAAA;;EAE1D"}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { isMainThread, parentPort } from 'node:worker_threads';
|
|
2
|
+
import { createServer } from 'node:http';
|
|
3
|
+
import { once } from 'node:events';
|
|
4
|
+
import config from '#analog/i18n-workers';
|
|
5
|
+
import { createLocaleListener, createLocaleServer } from './locale-workers.mjs';
|
|
6
|
+
|
|
7
|
+
export let localFetch;
|
|
8
|
+
export let closePrerenderer;
|
|
9
|
+
|
|
10
|
+
if (isMainThread) {
|
|
11
|
+
if (
|
|
12
|
+
!import.meta.prerender &&
|
|
13
|
+
(process.env.NITRO_SSL_CERT ||
|
|
14
|
+
process.env.NITRO_SSL_KEY ||
|
|
15
|
+
process.env.NITRO_UNIX_SOCKET)
|
|
16
|
+
) {
|
|
17
|
+
throw new Error(
|
|
18
|
+
'i18n.workers requires an HTTP TCP listener; terminate TLS at your reverse proxy.',
|
|
19
|
+
);
|
|
20
|
+
}
|
|
21
|
+
const { server, close } = await createLocaleServer(new URL(import.meta.url), {
|
|
22
|
+
...config,
|
|
23
|
+
baseURL: process.env.NITRO_APP_BASE_URL || config.baseURL,
|
|
24
|
+
});
|
|
25
|
+
if (import.meta.prerender) {
|
|
26
|
+
server.listen(0, '127.0.0.1');
|
|
27
|
+
await once(server, 'listening');
|
|
28
|
+
const origin = `http://127.0.0.1:${server.address().port}`;
|
|
29
|
+
localFetch = (input, init) => {
|
|
30
|
+
if (!input.toString().startsWith('/')) return fetch(input, init);
|
|
31
|
+
const headers = new Headers(init?.headers);
|
|
32
|
+
if (!headers.has('host')) headers.set('host', 'localhost');
|
|
33
|
+
return fetch(origin + input, { ...init, headers, redirect: 'manual' });
|
|
34
|
+
};
|
|
35
|
+
closePrerenderer = close;
|
|
36
|
+
} else {
|
|
37
|
+
for (const signal of ['SIGINT', 'SIGTERM'])
|
|
38
|
+
process.once(signal, () => void close());
|
|
39
|
+
server.on('error', (error) => {
|
|
40
|
+
console.error(error);
|
|
41
|
+
process.exitCode = 1;
|
|
42
|
+
void close();
|
|
43
|
+
});
|
|
44
|
+
server.listen(
|
|
45
|
+
Number(process.env.NITRO_PORT || process.env.PORT || 3000),
|
|
46
|
+
process.env.NITRO_HOST || process.env.HOST || '0.0.0.0',
|
|
47
|
+
() => {
|
|
48
|
+
console.log(
|
|
49
|
+
`Listening on http://${server.address().address}:${server.address().port}`,
|
|
50
|
+
);
|
|
51
|
+
},
|
|
52
|
+
);
|
|
53
|
+
}
|
|
54
|
+
} else {
|
|
55
|
+
// Initialize before Nitro plugins, endpoints, or the SSR app can evaluate $localize.
|
|
56
|
+
await (
|
|
57
|
+
await import('#analog/ssr')
|
|
58
|
+
).i18nReady;
|
|
59
|
+
const { useNitroApp } = await import('nitropack/runtime');
|
|
60
|
+
const app = useNitroApp();
|
|
61
|
+
const server = createServer(createLocaleListener(app.h3App));
|
|
62
|
+
server.listen(0, '127.0.0.1');
|
|
63
|
+
await once(server, 'listening');
|
|
64
|
+
parentPort.on('message', async (message) => {
|
|
65
|
+
if (message !== 'close') return;
|
|
66
|
+
await new Promise((resolve) => server.close(resolve));
|
|
67
|
+
await app.hooks.callHook('close');
|
|
68
|
+
parentPort.close();
|
|
69
|
+
});
|
|
70
|
+
parentPort.postMessage({ type: 'ready', port: server.address().port });
|
|
71
|
+
}
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
import { Agent, createServer, request } from 'node:http';
|
|
2
|
+
import { Worker } from 'node:worker_threads';
|
|
3
|
+
import { toNodeListener } from 'h3';
|
|
4
|
+
|
|
5
|
+
const CLIENT_ADDRESS_HEADER = 'x-analog-client-address';
|
|
6
|
+
const HOP_BY_HOP_HEADERS = new Set([
|
|
7
|
+
'connection',
|
|
8
|
+
'keep-alive',
|
|
9
|
+
'proxy-authenticate',
|
|
10
|
+
'proxy-authorization',
|
|
11
|
+
'te',
|
|
12
|
+
'trailer',
|
|
13
|
+
'transfer-encoding',
|
|
14
|
+
'upgrade',
|
|
15
|
+
]);
|
|
16
|
+
|
|
17
|
+
function proxyHeaders(headers) {
|
|
18
|
+
const connectionHeaders = new Set(
|
|
19
|
+
headers.connection?.split(',').map((name) => name.trim().toLowerCase()),
|
|
20
|
+
);
|
|
21
|
+
return Object.fromEntries(
|
|
22
|
+
Object.entries(headers).filter(
|
|
23
|
+
([name]) => !HOP_BY_HOP_HEADERS.has(name) && !connectionHeaders.has(name),
|
|
24
|
+
),
|
|
25
|
+
);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function createLocaleListener(app) {
|
|
29
|
+
return toNodeListener({
|
|
30
|
+
...app,
|
|
31
|
+
handler(event) {
|
|
32
|
+
const address = event.node.req.headers[CLIENT_ADDRESS_HEADER];
|
|
33
|
+
delete event.node.req.headers[CLIENT_ADDRESS_HEADER];
|
|
34
|
+
if (address) event.context.clientAddress = address;
|
|
35
|
+
return app.handler(event);
|
|
36
|
+
},
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function selectLocale(
|
|
41
|
+
url,
|
|
42
|
+
acceptLanguage,
|
|
43
|
+
{ locales, defaultLocale, baseURL = '/' },
|
|
44
|
+
) {
|
|
45
|
+
let path = url.split('?')[0];
|
|
46
|
+
const base = baseURL.replace(/\/$/, '');
|
|
47
|
+
if (base && path.startsWith(base + '/')) path = path.slice(base.length);
|
|
48
|
+
const first = path.split('/').filter(Boolean)[0];
|
|
49
|
+
if (locales.includes(first)) return first;
|
|
50
|
+
// Match the router's URL-first locale detection, including unsupported tags.
|
|
51
|
+
if (first && /^[a-z]{2}(-[a-zA-Z]{2,4})?(-[a-zA-Z]{2}|\d{3})?$/.test(first))
|
|
52
|
+
return defaultLocale;
|
|
53
|
+
const preferred = acceptLanguage
|
|
54
|
+
?.split(',')
|
|
55
|
+
.map((part) => {
|
|
56
|
+
const [locale, quality] = part.trim().split(';');
|
|
57
|
+
return {
|
|
58
|
+
locale: locale.trim(),
|
|
59
|
+
quality: quality ? parseFloat(quality.replace('q=', '')) : 1,
|
|
60
|
+
};
|
|
61
|
+
})
|
|
62
|
+
.sort((a, b) => b.quality - a.quality)[0]?.locale;
|
|
63
|
+
return locales.includes(preferred) ? preferred : defaultLocale;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export async function createLocaleServer(entry, config) {
|
|
67
|
+
const workers = [];
|
|
68
|
+
const ports = new Map();
|
|
69
|
+
const agent = new Agent({ keepAlive: true });
|
|
70
|
+
let closing;
|
|
71
|
+
const server = createServer((req, res) => {
|
|
72
|
+
const locale = selectLocale(
|
|
73
|
+
req.url || '/',
|
|
74
|
+
req.headers['accept-language'],
|
|
75
|
+
config,
|
|
76
|
+
);
|
|
77
|
+
const upstream = request(
|
|
78
|
+
{
|
|
79
|
+
hostname: '127.0.0.1',
|
|
80
|
+
port: ports.get(locale),
|
|
81
|
+
path: req.url,
|
|
82
|
+
method: req.method,
|
|
83
|
+
headers: {
|
|
84
|
+
...proxyHeaders(req.headers),
|
|
85
|
+
[CLIENT_ADDRESS_HEADER]: req.socket.remoteAddress,
|
|
86
|
+
},
|
|
87
|
+
agent,
|
|
88
|
+
},
|
|
89
|
+
(response) => {
|
|
90
|
+
res.writeHead(
|
|
91
|
+
response.statusCode,
|
|
92
|
+
response.statusMessage,
|
|
93
|
+
proxyHeaders(response.headers),
|
|
94
|
+
);
|
|
95
|
+
response.on('error', (error) => res.destroy(error));
|
|
96
|
+
response.pipe(res);
|
|
97
|
+
},
|
|
98
|
+
);
|
|
99
|
+
upstream.on('error', () => {
|
|
100
|
+
if (res.headersSent) res.destroy();
|
|
101
|
+
else {
|
|
102
|
+
res.writeHead(502);
|
|
103
|
+
res.end('Locale worker unavailable');
|
|
104
|
+
}
|
|
105
|
+
});
|
|
106
|
+
req.on('aborted', () => upstream.destroy());
|
|
107
|
+
res.on('close', () => {
|
|
108
|
+
if (!res.writableFinished) upstream.destroy();
|
|
109
|
+
});
|
|
110
|
+
req.pipe(upstream);
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
function close() {
|
|
114
|
+
return (closing ??= (async () => {
|
|
115
|
+
const deadline = setTimeout(() => {
|
|
116
|
+
server.closeAllConnections();
|
|
117
|
+
for (const worker of workers) void worker.terminate();
|
|
118
|
+
}, 30_000);
|
|
119
|
+
deadline.unref();
|
|
120
|
+
try {
|
|
121
|
+
await new Promise((resolve) => server.close(resolve));
|
|
122
|
+
agent.destroy();
|
|
123
|
+
await Promise.all(
|
|
124
|
+
workers.map(
|
|
125
|
+
(worker) =>
|
|
126
|
+
new Promise((resolve) => {
|
|
127
|
+
if (worker.threadId === -1) return resolve();
|
|
128
|
+
worker.once('exit', resolve);
|
|
129
|
+
worker.postMessage('close');
|
|
130
|
+
}),
|
|
131
|
+
),
|
|
132
|
+
);
|
|
133
|
+
} finally {
|
|
134
|
+
clearTimeout(deadline);
|
|
135
|
+
}
|
|
136
|
+
})());
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
try {
|
|
140
|
+
await Promise.all(
|
|
141
|
+
config.locales.map(
|
|
142
|
+
(locale) =>
|
|
143
|
+
new Promise((resolve, reject) => {
|
|
144
|
+
const worker = new Worker(entry, {
|
|
145
|
+
env: { ...process.env, ANALOG_I18N_LOCALE: locale },
|
|
146
|
+
});
|
|
147
|
+
workers.push(worker);
|
|
148
|
+
let ready = false;
|
|
149
|
+
const timeout = setTimeout(
|
|
150
|
+
() =>
|
|
151
|
+
reject(
|
|
152
|
+
new Error(`Locale worker ${locale} timed out during startup`),
|
|
153
|
+
),
|
|
154
|
+
30_000,
|
|
155
|
+
);
|
|
156
|
+
const fail = (error) => {
|
|
157
|
+
clearTimeout(timeout);
|
|
158
|
+
if (!ready) reject(error);
|
|
159
|
+
else if (!closing) {
|
|
160
|
+
console.error(error);
|
|
161
|
+
process.exitCode = 1;
|
|
162
|
+
void close();
|
|
163
|
+
}
|
|
164
|
+
};
|
|
165
|
+
worker.on('error', fail);
|
|
166
|
+
worker.on('exit', (code) =>
|
|
167
|
+
fail(new Error(`Locale worker ${locale} exited (${code})`)),
|
|
168
|
+
);
|
|
169
|
+
worker.once('message', (message) => {
|
|
170
|
+
clearTimeout(timeout);
|
|
171
|
+
if (message.type !== 'ready' || !Number.isInteger(message.port)) {
|
|
172
|
+
reject(
|
|
173
|
+
new Error(
|
|
174
|
+
`Invalid startup response from locale worker ${locale}`,
|
|
175
|
+
),
|
|
176
|
+
);
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
ready = true;
|
|
180
|
+
ports.set(locale, message.port);
|
|
181
|
+
resolve();
|
|
182
|
+
});
|
|
183
|
+
}),
|
|
184
|
+
),
|
|
185
|
+
);
|
|
186
|
+
} catch (error) {
|
|
187
|
+
closing = Promise.resolve();
|
|
188
|
+
agent.destroy();
|
|
189
|
+
await Promise.all(workers.map((worker) => worker.terminate()));
|
|
190
|
+
throw error;
|
|
191
|
+
}
|
|
192
|
+
return { server, close };
|
|
193
|
+
}
|
|
@@ -72,7 +72,7 @@ function getMatchingContentFilesWithFrontMatter(workspaceRoot, rootDir, glob, re
|
|
|
72
72
|
return contentFiles.map((f) => {
|
|
73
73
|
const fileContents = readFileSync(f, "utf8");
|
|
74
74
|
const raw = fm(fileContents);
|
|
75
|
-
const match =
|
|
75
|
+
const match = f.replace(root, "").match(/\/([^/.]+)(\.([^/.]+))?$/);
|
|
76
76
|
let name = "";
|
|
77
77
|
let extension = "";
|
|
78
78
|
if (match) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"get-content-files.js","names":[],"sources":["../../../../src/lib/utils/get-content-files.ts"],"sourcesContent":["import { readFileSync } from 'node:fs';\nimport { join, relative, resolve } from 'node:path';\nimport { normalizePath } from 'vite';\nimport { createRequire } from 'node:module';\nimport { globSync } from 'tinyglobby';\n\nimport { PrerenderContentFile } from '../options';\n\nconst require = createRequire(import.meta.url);\n\n/**\n * Discovers content files with front matter and extracts metadata for prerendering.\n *\n * This function:\n * 1. Discovers all content files matching the specified glob pattern\n * 2. Reads each file and parses front matter metadata\n * 3. Extracts file name, extension, and path information\n * 4. Returns structured data for prerendering content pages\n *\n * @param workspaceRoot The workspace root directory path\n * @param rootDir The project root directory relative to workspace\n * @param glob The glob pattern to match content files (e.g., 'content/blog')\n * @returns Array of PrerenderContentFile objects with metadata and front matter\n *\n * Example usage:\n * const contentFiles = getMatchingContentFilesWithFrontMatter(\n * '/workspace',\n * 'apps/my-app',\n * 'content/blog'\n * );\n *\n * Sample discovered file paths:\n * - /workspace/apps/my-app/content/blog/first-post.md\n * - /workspace/apps/my-app/content/blog/2024/01/hello-world.md\n * - /workspace/apps/my-app/content/blog/tech/angular-v17.mdx\n * - /workspace/apps/my-app/content/blog/about/index.md\n *\n * Sample output structure:\n * {\n * name: 'first-post',\n * extension: 'md',\n * path: 'content/blog',\n * attributes: { title: 'My First Post', date: '2024-01-01', tags: ['intro'] }\n * }\n *\n * tinyglobby vs fast-glob comparison:\n * - Both support the same glob patterns for file discovery\n * - Both are efficient for finding content files\n * - tinyglobby is now used instead of fast-glob\n * - tinyglobby provides similar functionality with smaller bundle size\n * - tinyglobby's globSync returns absolute paths when absolute: true is set\n *\n * Front matter parsing:\n * - Uses front-matter library to parse YAML/TOML front matter\n * - Extracts metadata like title, date, tags, author, etc.\n * - Supports both YAML (---) and TOML (+++) delimiters\n * - Returns structured attributes for prerendering\n *\n * File path processing:\n * - Normalizes paths for cross-platform compatibility\n * - Extracts file name without extension\n * - Determines file extension for content type handling\n * - Maintains relative path structure for routing\n */\nexport function getMatchingContentFilesWithFrontMatter(\n workspaceRoot: string,\n rootDir: string,\n glob: string,\n recursive = false,\n): PrerenderContentFile[] {\n // Dynamically require front-matter library\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const fm = require('front-matter');\n\n // Normalize the project root path for consistent path handling\n const root = normalizePath(resolve(workspaceRoot, rootDir));\n\n // Resolve the content directory path relative to the project root\n const resolvedDir = normalizePath(relative(root, join(root, glob)));\n\n // Discover all content files in the specified directory.\n // Default pattern matches only top-level files; recursive opt-in walks subdirectories.\n const pattern = recursive\n ? `${root}/${resolvedDir}/**/*`\n : `${root}/${resolvedDir}/*`;\n const contentFiles: string[] = globSync([pattern], {\n dot: true,\n absolute: true,\n onlyFiles: true,\n });\n\n const dirPrefix = `${root}/${resolvedDir}`;\n\n // Process each discovered content file to extract metadata and front matter\n const mappedFilesWithFm: PrerenderContentFile[] = contentFiles.map((f) => {\n // Read the file contents as UTF-8 text\n const fileContents = readFileSync(f, 'utf8');\n\n // Parse front matter from the file content\n const raw = fm(fileContents);\n\n const filepath =
|
|
1
|
+
{"version":3,"file":"get-content-files.js","names":[],"sources":["../../../../src/lib/utils/get-content-files.ts"],"sourcesContent":["import { readFileSync } from 'node:fs';\nimport { join, relative, resolve } from 'node:path';\nimport { normalizePath } from 'vite';\nimport { createRequire } from 'node:module';\nimport { globSync } from 'tinyglobby';\n\nimport { PrerenderContentFile } from '../options';\n\nconst require = createRequire(import.meta.url);\n\n/**\n * Discovers content files with front matter and extracts metadata for prerendering.\n *\n * This function:\n * 1. Discovers all content files matching the specified glob pattern\n * 2. Reads each file and parses front matter metadata\n * 3. Extracts file name, extension, and path information\n * 4. Returns structured data for prerendering content pages\n *\n * @param workspaceRoot The workspace root directory path\n * @param rootDir The project root directory relative to workspace\n * @param glob The glob pattern to match content files (e.g., 'content/blog')\n * @returns Array of PrerenderContentFile objects with metadata and front matter\n *\n * Example usage:\n * const contentFiles = getMatchingContentFilesWithFrontMatter(\n * '/workspace',\n * 'apps/my-app',\n * 'content/blog'\n * );\n *\n * Sample discovered file paths:\n * - /workspace/apps/my-app/content/blog/first-post.md\n * - /workspace/apps/my-app/content/blog/2024/01/hello-world.md\n * - /workspace/apps/my-app/content/blog/tech/angular-v17.mdx\n * - /workspace/apps/my-app/content/blog/about/index.md\n *\n * Sample output structure:\n * {\n * name: 'first-post',\n * extension: 'md',\n * path: 'content/blog',\n * attributes: { title: 'My First Post', date: '2024-01-01', tags: ['intro'] }\n * }\n *\n * tinyglobby vs fast-glob comparison:\n * - Both support the same glob patterns for file discovery\n * - Both are efficient for finding content files\n * - tinyglobby is now used instead of fast-glob\n * - tinyglobby provides similar functionality with smaller bundle size\n * - tinyglobby's globSync returns absolute paths when absolute: true is set\n *\n * Front matter parsing:\n * - Uses front-matter library to parse YAML/TOML front matter\n * - Extracts metadata like title, date, tags, author, etc.\n * - Supports both YAML (---) and TOML (+++) delimiters\n * - Returns structured attributes for prerendering\n *\n * File path processing:\n * - Normalizes paths for cross-platform compatibility\n * - Extracts file name without extension\n * - Determines file extension for content type handling\n * - Maintains relative path structure for routing\n */\nexport function getMatchingContentFilesWithFrontMatter(\n workspaceRoot: string,\n rootDir: string,\n glob: string,\n recursive = false,\n): PrerenderContentFile[] {\n // Dynamically require front-matter library\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const fm = require('front-matter');\n\n // Normalize the project root path for consistent path handling\n const root = normalizePath(resolve(workspaceRoot, rootDir));\n\n // Resolve the content directory path relative to the project root\n const resolvedDir = normalizePath(relative(root, join(root, glob)));\n\n // Discover all content files in the specified directory.\n // Default pattern matches only top-level files; recursive opt-in walks subdirectories.\n const pattern = recursive\n ? `${root}/${resolvedDir}/**/*`\n : `${root}/${resolvedDir}/*`;\n const contentFiles: string[] = globSync([pattern], {\n dot: true,\n absolute: true,\n onlyFiles: true,\n });\n\n const dirPrefix = `${root}/${resolvedDir}`;\n\n // Process each discovered content file to extract metadata and front matter\n const mappedFilesWithFm: PrerenderContentFile[] = contentFiles.map((f) => {\n // Read the file contents as UTF-8 text\n const fileContents = readFileSync(f, 'utf8');\n\n // Parse front matter from the file content\n const raw = fm(fileContents);\n\n // Get the relative file path by removing the root directory\n const filepath = f.replace(root, '');\n\n // Extract file name and extension using regex\n // Matches: /filename.ext or /filename (with optional extension)\n const match = filepath.match(/\\/([^/.]+)(\\.([^/.]+))?$/);\n let name = '';\n let extension = '';\n if (match) {\n name = match[1]; // File name without extension\n extension = match[3] || ''; // File extension or empty string if no extension\n }\n\n // Path of the file's directory relative to the configured contentDir.\n // For top-level files this is an empty string; for nested files it\n // gives transforms enough context to disambiguate identically-named\n // files (e.g. docs/a/post.md vs docs/b/post.md).\n const relativeDir = normalizePath(relative(dirPrefix, f));\n const lastSlash = relativeDir.lastIndexOf('/');\n const relativePath =\n lastSlash === -1 ? '' : relativeDir.slice(0, lastSlash);\n\n // Return structured content file data for prerendering\n return {\n name,\n extension,\n path: resolvedDir,\n attributes: raw.attributes as { attributes: Record<string, any> },\n content: fileContents,\n relativePath,\n };\n });\n\n return mappedFilesWithFm;\n}\n"],"mappings":";;;;;;AAQA,IAAM,UAAU,cAAc,OAAO,KAAK,IAAI;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwD9C,SAAgB,uCACd,eACA,SACA,MACA,YAAY,OACY;CAGxB,MAAM,KAAK,QAAQ,eAAe;CAGlC,MAAM,OAAO,cAAc,QAAQ,eAAe,QAAQ,CAAC;CAG3D,MAAM,cAAc,cAAc,SAAS,MAAM,KAAK,MAAM,KAAK,CAAC,CAAC;CAOnE,MAAM,eAAyB,SAAS,CAHxB,YACZ,GAAG,KAAK,GAAG,YAAY,SACvB,GAAG,KAAK,GAAG,YAAY,IACsB,EAAE;EACjD,KAAK;EACL,UAAU;EACV,WAAW;EACZ,CAAC;CAEF,MAAM,YAAY,GAAG,KAAK,GAAG;AA2C7B,QAxCkD,aAAa,KAAK,MAAM;EAExE,MAAM,eAAe,aAAa,GAAG,OAAO;EAG5C,MAAM,MAAM,GAAG,aAAa;EAO5B,MAAM,QAJW,EAAE,QAAQ,MAAM,GAAG,CAIb,MAAM,2BAA2B;EACxD,IAAI,OAAO;EACX,IAAI,YAAY;AAChB,MAAI,OAAO;AACT,UAAO,MAAM;AACb,eAAY,MAAM,MAAM;;EAO1B,MAAM,cAAc,cAAc,SAAS,WAAW,EAAE,CAAC;EACzD,MAAM,YAAY,YAAY,YAAY,IAAI;EAC9C,MAAM,eACJ,cAAc,KAAK,KAAK,YAAY,MAAM,GAAG,UAAU;AAGzD,SAAO;GACL;GACA;GACA,MAAM;GACN,YAAY,IAAI;GAChB,SAAS;GACT;GACD;GACD"}
|
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
import
|
|
1
|
+
import { NitroEventHandler } from "nitropack";
|
|
2
2
|
type GetHandlersArgs = {
|
|
3
3
|
workspaceRoot: string;
|
|
4
4
|
sourceRoot: string;
|
|
5
5
|
rootDir: string;
|
|
6
6
|
additionalPagesDirs?: string[];
|
|
7
|
+
hasAPIDir?: boolean;
|
|
7
8
|
};
|
|
8
9
|
/**
|
|
9
10
|
* Discovers and generates Nitro event handlers for server-side page routes.
|
|
@@ -18,6 +19,7 @@ type GetHandlersArgs = {
|
|
|
18
19
|
* @param sourceRoot The source directory path (e.g., 'src')
|
|
19
20
|
* @param rootDir The project root directory relative to workspace
|
|
20
21
|
* @param additionalPagesDirs Optional array of additional pages directories to scan
|
|
22
|
+
* @param hasAPIDir Whether the project has an API directory (affects route prefixing)
|
|
21
23
|
* @returns Array of NitroEventHandler objects with handler paths and route patterns
|
|
22
24
|
*
|
|
23
25
|
* Example usage:
|
|
@@ -26,6 +28,7 @@ type GetHandlersArgs = {
|
|
|
26
28
|
* sourceRoot: 'src',
|
|
27
29
|
* rootDir: 'apps/my-app',
|
|
28
30
|
* additionalPagesDirs: ['/libs/shared/pages'],
|
|
31
|
+
* hasAPIDir: true
|
|
29
32
|
* });
|
|
30
33
|
*
|
|
31
34
|
* Sample discovered file paths:
|
|
@@ -35,10 +38,10 @@ type GetHandlersArgs = {
|
|
|
35
38
|
* - /workspace/apps/my-app/src/app/pages/(auth)/login.server.ts
|
|
36
39
|
*
|
|
37
40
|
* Route transformation examples:
|
|
38
|
-
* - index.server.ts → /
|
|
39
|
-
* - users/[id].server.ts → /
|
|
40
|
-
* - products/[...slug].server.ts → /
|
|
41
|
-
* - (auth)/login.server.ts → /
|
|
41
|
+
* - index.server.ts → /_analog/pages/index
|
|
42
|
+
* - users/[id].server.ts → /_analog/pages/users/:id
|
|
43
|
+
* - products/[...slug].server.ts → /_analog/pages/products/**:slug
|
|
44
|
+
* - (auth)/login.server.ts → /_analog/pages/-auth-/login
|
|
42
45
|
*
|
|
43
46
|
* tinyglobby vs fast-glob comparison:
|
|
44
47
|
* - Both support the same glob patterns for file discovery
|
|
@@ -53,7 +56,7 @@ type GetHandlersArgs = {
|
|
|
53
56
|
* 3. Converts [...param] to **:param for catch-all routes
|
|
54
57
|
* 4. Converts (group) to -group- for route groups
|
|
55
58
|
* 5. Converts dots to forward slashes
|
|
56
|
-
* 6. Prefixes with /
|
|
59
|
+
* 6. Prefixes with /_analog/pages and optionally /api
|
|
57
60
|
*/
|
|
58
|
-
export declare function getPageHandlers({ workspaceRoot, sourceRoot, rootDir, additionalPagesDirs }: GetHandlersArgs): NitroEventHandler[];
|
|
61
|
+
export declare function getPageHandlers({ workspaceRoot, sourceRoot, rootDir, additionalPagesDirs, hasAPIDir }: GetHandlersArgs): NitroEventHandler[];
|
|
59
62
|
export {};
|
|
@@ -15,6 +15,7 @@ import { globSync } from "tinyglobby";
|
|
|
15
15
|
* @param sourceRoot The source directory path (e.g., 'src')
|
|
16
16
|
* @param rootDir The project root directory relative to workspace
|
|
17
17
|
* @param additionalPagesDirs Optional array of additional pages directories to scan
|
|
18
|
+
* @param hasAPIDir Whether the project has an API directory (affects route prefixing)
|
|
18
19
|
* @returns Array of NitroEventHandler objects with handler paths and route patterns
|
|
19
20
|
*
|
|
20
21
|
* Example usage:
|
|
@@ -23,6 +24,7 @@ import { globSync } from "tinyglobby";
|
|
|
23
24
|
* sourceRoot: 'src',
|
|
24
25
|
* rootDir: 'apps/my-app',
|
|
25
26
|
* additionalPagesDirs: ['/libs/shared/pages'],
|
|
27
|
+
* hasAPIDir: true
|
|
26
28
|
* });
|
|
27
29
|
*
|
|
28
30
|
* Sample discovered file paths:
|
|
@@ -32,10 +34,10 @@ import { globSync } from "tinyglobby";
|
|
|
32
34
|
* - /workspace/apps/my-app/src/app/pages/(auth)/login.server.ts
|
|
33
35
|
*
|
|
34
36
|
* Route transformation examples:
|
|
35
|
-
* - index.server.ts → /
|
|
36
|
-
* - users/[id].server.ts → /
|
|
37
|
-
* - products/[...slug].server.ts → /
|
|
38
|
-
* - (auth)/login.server.ts → /
|
|
37
|
+
* - index.server.ts → /_analog/pages/index
|
|
38
|
+
* - users/[id].server.ts → /_analog/pages/users/:id
|
|
39
|
+
* - products/[...slug].server.ts → /_analog/pages/products/**:slug
|
|
40
|
+
* - (auth)/login.server.ts → /_analog/pages/-auth-/login
|
|
39
41
|
*
|
|
40
42
|
* tinyglobby vs fast-glob comparison:
|
|
41
43
|
* - Both support the same glob patterns for file discovery
|
|
@@ -50,16 +52,17 @@ import { globSync } from "tinyglobby";
|
|
|
50
52
|
* 3. Converts [...param] to **:param for catch-all routes
|
|
51
53
|
* 4. Converts (group) to -group- for route groups
|
|
52
54
|
* 5. Converts dots to forward slashes
|
|
53
|
-
* 6. Prefixes with /
|
|
55
|
+
* 6. Prefixes with /_analog/pages and optionally /api
|
|
54
56
|
*/
|
|
55
|
-
function getPageHandlers({ workspaceRoot, sourceRoot, rootDir, additionalPagesDirs }) {
|
|
57
|
+
function getPageHandlers({ workspaceRoot, sourceRoot, rootDir, additionalPagesDirs, hasAPIDir }) {
|
|
56
58
|
return globSync([`${normalizePath(resolve(workspaceRoot, rootDir))}/${sourceRoot}/app/pages/**/*.server.ts`, ...(additionalPagesDirs || []).map((dir) => `${workspaceRoot}${dir}/**/*.server.ts`)], {
|
|
57
59
|
dot: true,
|
|
58
60
|
absolute: true
|
|
59
61
|
}).map((endpointFile) => {
|
|
62
|
+
const route = endpointFile.replace(/^(.*?)\/pages/, "/pages").replace(/\.server\.ts$/, "").replace(/\[\.{3}(.+)\]/g, "**:$1").replace(/\[\.{3}(\w+)\]/g, "**:$1").replace(/\/\((.*?)\)$/, "/-$1-").replace(/\[(\w+)\]/g, ":$1").replace(/\./g, "/");
|
|
60
63
|
return {
|
|
61
64
|
handler: endpointFile,
|
|
62
|
-
route:
|
|
65
|
+
route: `${hasAPIDir ? "/api" : ""}/_analog${route}`,
|
|
63
66
|
lazy: true
|
|
64
67
|
};
|
|
65
68
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"get-page-handlers.js","names":[],"sources":["../../../../src/lib/utils/get-page-handlers.ts"],"sourcesContent":["import { resolve, relative } from 'node:path';\nimport { globSync } from 'tinyglobby';\n\nimport
|
|
1
|
+
{"version":3,"file":"get-page-handlers.js","names":[],"sources":["../../../../src/lib/utils/get-page-handlers.ts"],"sourcesContent":["import { resolve, relative } from 'node:path';\nimport { globSync } from 'tinyglobby';\n\nimport { NitroEventHandler } from 'nitropack';\nimport { normalizePath } from 'vite';\n\ntype GetHandlersArgs = {\n workspaceRoot: string;\n sourceRoot: string;\n rootDir: string;\n additionalPagesDirs?: string[];\n hasAPIDir?: boolean;\n};\n\n/**\n * Discovers and generates Nitro event handlers for server-side page routes.\n *\n * This function:\n * 1. Discovers all .server.ts files in the app/pages directory and additional pages directories\n * 2. Converts file paths to route patterns using Angular-style route syntax\n * 3. Generates Nitro event handlers with proper route mapping and lazy loading\n * 4. Handles dynamic route parameters and catch-all routes\n *\n * @param workspaceRoot The workspace root directory path\n * @param sourceRoot The source directory path (e.g., 'src')\n * @param rootDir The project root directory relative to workspace\n * @param additionalPagesDirs Optional array of additional pages directories to scan\n * @param hasAPIDir Whether the project has an API directory (affects route prefixing)\n * @returns Array of NitroEventHandler objects with handler paths and route patterns\n *\n * Example usage:\n * const handlers = getPageHandlers({\n * workspaceRoot: '/workspace',\n * sourceRoot: 'src',\n * rootDir: 'apps/my-app',\n * additionalPagesDirs: ['/libs/shared/pages'],\n * hasAPIDir: true\n * });\n *\n * Sample discovered file paths:\n * - /workspace/apps/my-app/src/app/pages/index.server.ts\n * - /workspace/apps/my-app/src/app/pages/users/[id].server.ts\n * - /workspace/apps/my-app/src/app/pages/products/[...slug].server.ts\n * - /workspace/apps/my-app/src/app/pages/(auth)/login.server.ts\n *\n * Route transformation examples:\n * - index.server.ts → /_analog/pages/index\n * - users/[id].server.ts → /_analog/pages/users/:id\n * - products/[...slug].server.ts → /_analog/pages/products/**:slug\n * - (auth)/login.server.ts → /_analog/pages/-auth-/login\n *\n * tinyglobby vs fast-glob comparison:\n * - Both support the same glob patterns for file discovery\n * - Both are efficient for finding server-side page files\n * - tinyglobby is now used instead of fast-glob\n * - tinyglobby provides similar functionality with smaller bundle size\n * - tinyglobby's globSync returns absolute paths when absolute: true is set\n *\n * Route transformation rules:\n * 1. Removes .server.ts extension\n * 2. Converts [param] to :param for dynamic routes\n * 3. Converts [...param] to **:param for catch-all routes\n * 4. Converts (group) to -group- for route groups\n * 5. Converts dots to forward slashes\n * 6. Prefixes with /_analog/pages and optionally /api\n */\nexport function getPageHandlers({\n workspaceRoot,\n sourceRoot,\n rootDir,\n additionalPagesDirs,\n hasAPIDir,\n}: GetHandlersArgs): NitroEventHandler[] {\n // Normalize the project root path for consistent path handling\n const root = normalizePath(resolve(workspaceRoot, rootDir));\n\n // Discover all .server.ts files in the app/pages directory and additional pages directories\n // Pattern: looks for any .server.ts files in app/pages/**/*.server.ts and additional directories\n const endpointFiles: string[] = globSync(\n [\n `${root}/${sourceRoot}/app/pages/**/*.server.ts`,\n ...(additionalPagesDirs || []).map(\n (dir) => `${workspaceRoot}${dir}/**/*.server.ts`,\n ),\n ],\n { dot: true, absolute: true },\n );\n\n // Transform each discovered file into a Nitro event handler\n const handlers: NitroEventHandler[] = endpointFiles.map((endpointFile) => {\n // Convert file path to route pattern using Angular-style route syntax\n const route = endpointFile\n .replace(/^(.*?)\\/pages/, '/pages') // Remove everything before /pages\n .replace(/\\.server\\.ts$/, '') // Remove .server.ts extension\n .replace(/\\[\\.{3}(.+)\\]/g, '**:$1') // Convert [...param] to **:param (catch-all routes)\n .replace(/\\[\\.{3}(\\w+)\\]/g, '**:$1') // Alternative catch-all pattern\n .replace(/\\/\\((.*?)\\)$/, '/-$1-') // Convert (group) to -group- (route groups)\n .replace(/\\[(\\w+)\\]/g, ':$1') // Convert [param] to :param (dynamic routes)\n .replace(/\\./g, '/'); // Convert dots to forward slashes\n\n // Return Nitro event handler with absolute handler path and transformed route\n return {\n handler: endpointFile,\n route: `${hasAPIDir ? '/api' : ''}/_analog${route}`,\n lazy: true,\n };\n });\n\n return handlers;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkEA,SAAgB,gBAAgB,EAC9B,eACA,YACA,SACA,qBACA,aACuC;AAoCvC,QA9BgC,SAC9B,CACE,GANS,cAAc,QAAQ,eAAe,QAAQ,CAAC,CAM/C,GAAG,WAAW,4BACtB,IAAI,uBAAuB,EAAE,EAAE,KAC5B,QAAQ,GAAG,gBAAgB,IAAI,iBACjC,CACF,EACD;EAAE,KAAK;EAAM,UAAU;EAAM,CAC9B,CAGmD,KAAK,iBAAiB;EAExE,MAAM,QAAQ,aACX,QAAQ,iBAAiB,SAAS,CAClC,QAAQ,iBAAiB,GAAG,CAC5B,QAAQ,kBAAkB,QAAQ,CAClC,QAAQ,mBAAmB,QAAQ,CACnC,QAAQ,gBAAgB,QAAQ,CAChC,QAAQ,cAAc,MAAM,CAC5B,QAAQ,OAAO,IAAI;AAGtB,SAAO;GACL,SAAS;GACT,OAAO,GAAG,YAAY,SAAS,GAAG,UAAU;GAC5C,MAAM;GACP;GACD"}
|
|
@@ -8,6 +8,7 @@ import { I18nPrerenderOptions } from "../options.js";
|
|
|
8
8
|
*
|
|
9
9
|
* The default locale's routes are included both with and without the prefix
|
|
10
10
|
* so that `/about` and `/en/about` both render.
|
|
11
|
+
* Routes that already have a configured locale prefix are kept as-is.
|
|
11
12
|
*
|
|
12
13
|
* @param routes - The original routes to expand
|
|
13
14
|
* @param i18n - The i18n prerender configuration
|
|
@@ -1,5 +1,52 @@
|
|
|
1
1
|
//#region packages/vite-plugin-nitro/src/lib/utils/i18n-prerender.ts
|
|
2
2
|
/**
|
|
3
|
+
* Expands a list of routes to include locale-prefixed variants.
|
|
4
|
+
*
|
|
5
|
+
* For each route and each locale, generates a prefixed route:
|
|
6
|
+
* '/' + locale + route
|
|
7
|
+
*
|
|
8
|
+
* The default locale's routes are included both with and without the prefix
|
|
9
|
+
* so that `/about` and `/en/about` both render.
|
|
10
|
+
* Routes that already have a configured locale prefix are kept as-is.
|
|
11
|
+
*
|
|
12
|
+
* @param routes - The original routes to expand
|
|
13
|
+
* @param i18n - The i18n prerender configuration
|
|
14
|
+
* @returns Expanded routes with locale prefixes
|
|
15
|
+
*/
|
|
16
|
+
function expandRoutesWithLocales(routes, i18n) {
|
|
17
|
+
const expanded = /* @__PURE__ */ new Set();
|
|
18
|
+
for (const route of routes) {
|
|
19
|
+
const firstSegment = route.split("/").filter(Boolean)[0];
|
|
20
|
+
if (route.includes("/_analog/") || route.startsWith("/api/") || i18n.locales.includes(firstSegment)) {
|
|
21
|
+
expanded.add(route);
|
|
22
|
+
continue;
|
|
23
|
+
}
|
|
24
|
+
for (const locale of i18n.locales) {
|
|
25
|
+
const prefix = `/${locale}`;
|
|
26
|
+
const localizedRoute = route === "/" ? prefix : `${prefix}${route}`;
|
|
27
|
+
expanded.add(localizedRoute);
|
|
28
|
+
}
|
|
29
|
+
expanded.add(route);
|
|
30
|
+
}
|
|
31
|
+
return [...expanded];
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Creates a post-rendering hook that injects the `lang` attribute
|
|
35
|
+
* into the `<html>` tag of prerendered pages based on the route's
|
|
36
|
+
* locale prefix.
|
|
37
|
+
*
|
|
38
|
+
* @param i18n - The i18n prerender configuration
|
|
39
|
+
* @returns A post-rendering hook function
|
|
40
|
+
*/
|
|
41
|
+
function createI18nPostRenderingHook(i18n) {
|
|
42
|
+
return async (route) => {
|
|
43
|
+
if (!route.contents || typeof route.contents !== "string") return;
|
|
44
|
+
const locale = detectLocaleFromRoute(route.route, i18n);
|
|
45
|
+
if (!locale) return;
|
|
46
|
+
route.contents = setHtmlLang(route.contents, locale);
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
3
50
|
* Detects the locale from a prerendered route path by checking
|
|
4
51
|
* the first path segment against the configured locales.
|
|
5
52
|
*/
|
|
@@ -18,6 +65,6 @@ function setHtmlLang(html, locale) {
|
|
|
18
65
|
return html.replace(/<html/i, `<html lang="${locale}"`);
|
|
19
66
|
}
|
|
20
67
|
//#endregion
|
|
21
|
-
export { detectLocaleFromRoute, setHtmlLang };
|
|
68
|
+
export { createI18nPostRenderingHook, detectLocaleFromRoute, expandRoutesWithLocales, setHtmlLang };
|
|
22
69
|
|
|
23
70
|
//# sourceMappingURL=i18n-prerender.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"i18n-prerender.js","names":[],"sources":["../../../../src/lib/utils/i18n-prerender.ts"],"sourcesContent":["import { PrerenderRoute } from 'nitropack';\nimport { I18nPrerenderOptions } from '../options.js';\n\n/**\n * Expands a list of routes to include locale-prefixed variants.\n *\n * For each route and each locale, generates a prefixed route:\n * '/' + locale + route\n *\n * The default locale's routes are included both with and without the prefix\n * so that `/about` and `/en/about` both render.\n *\n * @param routes - The original routes to expand\n * @param i18n - The i18n prerender configuration\n * @returns Expanded routes with locale prefixes\n */\nexport function expandRoutesWithLocales(\n routes: string[],\n i18n: I18nPrerenderOptions,\n): string[] {\n const expanded
|
|
1
|
+
{"version":3,"file":"i18n-prerender.js","names":[],"sources":["../../../../src/lib/utils/i18n-prerender.ts"],"sourcesContent":["import { PrerenderRoute } from 'nitropack';\nimport { I18nPrerenderOptions } from '../options.js';\n\n/**\n * Expands a list of routes to include locale-prefixed variants.\n *\n * For each route and each locale, generates a prefixed route:\n * '/' + locale + route\n *\n * The default locale's routes are included both with and without the prefix\n * so that `/about` and `/en/about` both render.\n * Routes that already have a configured locale prefix are kept as-is.\n *\n * @param routes - The original routes to expand\n * @param i18n - The i18n prerender configuration\n * @returns Expanded routes with locale prefixes\n */\nexport function expandRoutesWithLocales(\n routes: string[],\n i18n: I18nPrerenderOptions,\n): string[] {\n const expanded = new Set<string>();\n\n for (const route of routes) {\n // API routes and explicitly localized routes don't need locale prefixes.\n const firstSegment = route.split('/').filter(Boolean)[0];\n if (\n route.includes('/_analog/') ||\n route.startsWith('/api/') ||\n i18n.locales.includes(firstSegment)\n ) {\n expanded.add(route);\n continue;\n }\n\n for (const locale of i18n.locales) {\n const prefix = `/${locale}`;\n const localizedRoute = route === '/' ? prefix : `${prefix}${route}`;\n expanded.add(localizedRoute);\n }\n\n // Keep the unprefixed route for the default locale\n expanded.add(route);\n }\n\n return [...expanded];\n}\n\n/**\n * Creates a post-rendering hook that injects the `lang` attribute\n * into the `<html>` tag of prerendered pages based on the route's\n * locale prefix.\n *\n * @param i18n - The i18n prerender configuration\n * @returns A post-rendering hook function\n */\nexport function createI18nPostRenderingHook(\n i18n: I18nPrerenderOptions,\n): (route: PrerenderRoute) => Promise<void> {\n return async (route: PrerenderRoute) => {\n if (!route.contents || typeof route.contents !== 'string') {\n return;\n }\n\n const locale = detectLocaleFromRoute(route.route, i18n);\n if (!locale) {\n return;\n }\n\n // Inject or replace the lang attribute on <html>\n route.contents = setHtmlLang(route.contents, locale);\n };\n}\n\n/**\n * Detects the locale from a prerendered route path by checking\n * the first path segment against the configured locales.\n */\nexport function detectLocaleFromRoute(\n route: string,\n i18n: I18nPrerenderOptions,\n): string {\n const segments = route.split('/').filter(Boolean);\n const firstSegment = segments[0];\n\n if (firstSegment && i18n.locales.includes(firstSegment)) {\n return firstSegment;\n }\n\n return i18n.defaultLocale;\n}\n\n/**\n * Sets the `lang` attribute on the `<html>` tag in an HTML string.\n * If a `lang` attribute already exists, it is replaced.\n * If no `lang` attribute exists, it is added.\n */\nexport function setHtmlLang(html: string, locale: string): string {\n // Replace existing lang attribute\n if (/<html[^>]*\\slang\\s*=\\s*[\"'][^\"']*[\"']/i.test(html)) {\n return html.replace(\n /(<html[^>]*\\s)lang\\s*=\\s*[\"'][^\"']*[\"']/i,\n `$1lang=\"${locale}\"`,\n );\n }\n\n // Add lang attribute to <html> tag\n return html.replace(/<html/i, `<html lang=\"${locale}\"`);\n}\n"],"mappings":";;;;;;;;;;;;;;;AAiBA,SAAgB,wBACd,QACA,MACU;CACV,MAAM,2BAAW,IAAI,KAAa;AAElC,MAAK,MAAM,SAAS,QAAQ;EAE1B,MAAM,eAAe,MAAM,MAAM,IAAI,CAAC,OAAO,QAAQ,CAAC;AACtD,MACE,MAAM,SAAS,YAAY,IAC3B,MAAM,WAAW,QAAQ,IACzB,KAAK,QAAQ,SAAS,aAAa,EACnC;AACA,YAAS,IAAI,MAAM;AACnB;;AAGF,OAAK,MAAM,UAAU,KAAK,SAAS;GACjC,MAAM,SAAS,IAAI;GACnB,MAAM,iBAAiB,UAAU,MAAM,SAAS,GAAG,SAAS;AAC5D,YAAS,IAAI,eAAe;;AAI9B,WAAS,IAAI,MAAM;;AAGrB,QAAO,CAAC,GAAG,SAAS;;;;;;;;;;AAWtB,SAAgB,4BACd,MAC0C;AAC1C,QAAO,OAAO,UAA0B;AACtC,MAAI,CAAC,MAAM,YAAY,OAAO,MAAM,aAAa,SAC/C;EAGF,MAAM,SAAS,sBAAsB,MAAM,OAAO,KAAK;AACvD,MAAI,CAAC,OACH;AAIF,QAAM,WAAW,YAAY,MAAM,UAAU,OAAO;;;;;;;AAQxD,SAAgB,sBACd,OACA,MACQ;CAER,MAAM,eADW,MAAM,MAAM,IAAI,CAAC,OAAO,QAAQ,CACnB;AAE9B,KAAI,gBAAgB,KAAK,QAAQ,SAAS,aAAa,CACrD,QAAO;AAGT,QAAO,KAAK;;;;;;;AAQd,SAAgB,YAAY,MAAc,QAAwB;AAEhE,KAAI,yCAAyC,KAAK,KAAK,CACrD,QAAO,KAAK,QACV,4CACA,WAAW,OAAO,GACnB;AAIH,QAAO,KAAK,QAAQ,UAAU,eAAe,OAAO,GAAG"}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { NitroConfig } from "nitropack";
|
|
2
|
+
import type { Options, I18nPrerenderOptions } from "../options.js";
|
|
3
|
+
export declare const I18N_WORKER_SSR_ENTRY = "virtual:analog-i18n/main.server";
|
|
4
|
+
export declare function validateI18nWorkers(options: Options, nitro: NitroConfig): void;
|
|
5
|
+
export declare function resolveI18nWorkers(options: Options, nitro: NitroConfig): boolean;
|
|
6
|
+
export declare function i18nWorkerSsrEntry(entry: string, loader: string, config: I18nPrerenderOptions): string;
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { dirname, join } from "node:path";
|
|
2
|
+
import { fileURLToPath } from "node:url";
|
|
3
|
+
//#region packages/vite-plugin-nitro/src/lib/utils/i18n-workers.ts
|
|
4
|
+
var I18N_WORKER_SSR_ENTRY = "virtual:analog-i18n/main.server";
|
|
5
|
+
function validateI18nWorkers(options, nitro) {
|
|
6
|
+
if (!options.i18n?.loader) throw new Error("i18n.workers requires an i18n.loader module.");
|
|
7
|
+
if (!options.ssr || nitro.preset !== "node-server") throw new Error("i18n.workers requires SSR and the node-server preset.");
|
|
8
|
+
if (options.experimental?.streaming || nitro.experimental?.websocket || Object.keys(nitro.scheduledTasks ?? {}).length) throw new Error("i18n.workers does not support experimental streaming, WebSockets, or scheduled tasks.");
|
|
9
|
+
const { locales, defaultLocale } = options.i18n;
|
|
10
|
+
if (!locales.length || new Set(locales).size !== locales.length || !locales.includes(defaultLocale)) throw new Error("i18n.workers requires unique locales including defaultLocale.");
|
|
11
|
+
}
|
|
12
|
+
function resolveI18nWorkers(options, nitro) {
|
|
13
|
+
const i18n = options.i18n;
|
|
14
|
+
if (!i18n || i18n.workers === false) return false;
|
|
15
|
+
if (i18n.workers !== true && (!i18n.loader || i18n.locales.length < 2)) return false;
|
|
16
|
+
try {
|
|
17
|
+
validateI18nWorkers(options, nitro);
|
|
18
|
+
return true;
|
|
19
|
+
} catch (error) {
|
|
20
|
+
if (i18n.workers === true) throw error;
|
|
21
|
+
console.warn(`[@analogjs/platform] Automatic i18n workers disabled: ${error.message} Concurrent cross-locale SSR remains unisolated.`);
|
|
22
|
+
return false;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
function i18nWorkerSsrEntry(entry, loader, config) {
|
|
26
|
+
return `
|
|
27
|
+
import '@angular/localize/init';
|
|
28
|
+
import { loadTranslations } from '@angular/localize';
|
|
29
|
+
import load from ${JSON.stringify(loader)};
|
|
30
|
+
import { setHtmlLang } from ${JSON.stringify(join(dirname(fileURLToPath(import.meta.url)), "i18n-prerender.js"))};
|
|
31
|
+
|
|
32
|
+
const locale = process.env['ANALOG_I18N_LOCALE'];
|
|
33
|
+
let renderer;
|
|
34
|
+
export const i18nReady = locale ? (async () => {
|
|
35
|
+
if (!${JSON.stringify(config.locales)}.includes(locale)) {
|
|
36
|
+
throw new Error('Unsupported i18n worker locale: ' + locale);
|
|
37
|
+
}
|
|
38
|
+
if (locale !== ${JSON.stringify(config.locales[0])}) {
|
|
39
|
+
loadTranslations(await load(locale));
|
|
40
|
+
}
|
|
41
|
+
renderer = (await import(${JSON.stringify(entry)})).default;
|
|
42
|
+
})() : Promise.resolve();
|
|
43
|
+
|
|
44
|
+
export default async function (...args) {
|
|
45
|
+
if (!locale) throw new Error('This SSR build must run in its locale worker.');
|
|
46
|
+
await i18nReady;
|
|
47
|
+
args[1] = setHtmlLang(args[1], locale);
|
|
48
|
+
return renderer(...args);
|
|
49
|
+
}
|
|
50
|
+
`;
|
|
51
|
+
}
|
|
52
|
+
//#endregion
|
|
53
|
+
export { I18N_WORKER_SSR_ENTRY, i18nWorkerSsrEntry, resolveI18nWorkers, validateI18nWorkers };
|
|
54
|
+
|
|
55
|
+
//# sourceMappingURL=i18n-workers.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"i18n-workers.js","names":[],"sources":["../../../../src/lib/utils/i18n-workers.ts"],"sourcesContent":["import { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { NitroConfig } from 'nitropack';\nimport type { Options, I18nPrerenderOptions } from '../options.js';\n\nexport const I18N_WORKER_SSR_ENTRY = 'virtual:analog-i18n/main.server';\n\nexport function validateI18nWorkers(\n options: Options,\n nitro: NitroConfig,\n): void {\n if (!options.i18n?.loader) {\n throw new Error('i18n.workers requires an i18n.loader module.');\n }\n if (!options.ssr || nitro.preset !== 'node-server') {\n throw new Error('i18n.workers requires SSR and the node-server preset.');\n }\n if (\n options.experimental?.streaming ||\n nitro.experimental?.websocket ||\n Object.keys(nitro.scheduledTasks ?? {}).length\n ) {\n throw new Error(\n 'i18n.workers does not support experimental streaming, WebSockets, or scheduled tasks.',\n );\n }\n const { locales, defaultLocale } = options.i18n;\n if (\n !locales.length ||\n new Set(locales).size !== locales.length ||\n !locales.includes(defaultLocale)\n ) {\n throw new Error(\n 'i18n.workers requires unique locales including defaultLocale.',\n );\n }\n}\n\nexport function resolveI18nWorkers(\n options: Options,\n nitro: NitroConfig,\n): boolean {\n const i18n = options.i18n;\n if (!i18n || i18n.workers === false) return false;\n if (i18n.workers !== true && (!i18n.loader || i18n.locales.length < 2))\n return false;\n try {\n validateI18nWorkers(options, nitro);\n return true;\n } catch (error) {\n if (i18n.workers === true) throw error;\n console.warn(\n `[@analogjs/platform] Automatic i18n workers disabled: ${(error as Error).message} Concurrent cross-locale SSR remains unisolated.`,\n );\n return false;\n }\n}\n\nexport function i18nWorkerSsrEntry(\n entry: string,\n loader: string,\n config: I18nPrerenderOptions,\n) {\n return `\nimport '@angular/localize/init';\nimport { loadTranslations } from '@angular/localize';\nimport load from ${JSON.stringify(loader)};\nimport { setHtmlLang } from ${JSON.stringify(join(dirname(fileURLToPath(import.meta.url)), 'i18n-prerender.js'))};\n\nconst locale = process.env['ANALOG_I18N_LOCALE'];\nlet renderer;\nexport const i18nReady = locale ? (async () => {\n if (!${JSON.stringify(config.locales)}.includes(locale)) {\n throw new Error('Unsupported i18n worker locale: ' + locale);\n }\n if (locale !== ${JSON.stringify(config.locales[0])}) {\n loadTranslations(await load(locale));\n }\n renderer = (await import(${JSON.stringify(entry)})).default;\n})() : Promise.resolve();\n\nexport default async function (...args) {\n if (!locale) throw new Error('This SSR build must run in its locale worker.');\n await i18nReady;\n args[1] = setHtmlLang(args[1], locale);\n return renderer(...args);\n}\n`;\n}\n"],"mappings":";;;AAKA,IAAa,wBAAwB;AAErC,SAAgB,oBACd,SACA,OACM;AACN,KAAI,CAAC,QAAQ,MAAM,OACjB,OAAM,IAAI,MAAM,+CAA+C;AAEjE,KAAI,CAAC,QAAQ,OAAO,MAAM,WAAW,cACnC,OAAM,IAAI,MAAM,wDAAwD;AAE1E,KACE,QAAQ,cAAc,aACtB,MAAM,cAAc,aACpB,OAAO,KAAK,MAAM,kBAAkB,EAAE,CAAC,CAAC,OAExC,OAAM,IAAI,MACR,wFACD;CAEH,MAAM,EAAE,SAAS,kBAAkB,QAAQ;AAC3C,KACE,CAAC,QAAQ,UACT,IAAI,IAAI,QAAQ,CAAC,SAAS,QAAQ,UAClC,CAAC,QAAQ,SAAS,cAAc,CAEhC,OAAM,IAAI,MACR,gEACD;;AAIL,SAAgB,mBACd,SACA,OACS;CACT,MAAM,OAAO,QAAQ;AACrB,KAAI,CAAC,QAAQ,KAAK,YAAY,MAAO,QAAO;AAC5C,KAAI,KAAK,YAAY,SAAS,CAAC,KAAK,UAAU,KAAK,QAAQ,SAAS,GAClE,QAAO;AACT,KAAI;AACF,sBAAoB,SAAS,MAAM;AACnC,SAAO;UACA,OAAO;AACd,MAAI,KAAK,YAAY,KAAM,OAAM;AACjC,UAAQ,KACN,yDAA0D,MAAgB,QAAQ,kDACnF;AACD,SAAO;;;AAIX,SAAgB,mBACd,OACA,QACA,QACA;AACA,QAAO;;;mBAGU,KAAK,UAAU,OAAO,CAAC;8BACZ,KAAK,UAAU,KAAK,QAAQ,cAAc,OAAO,KAAK,IAAI,CAAC,EAAE,oBAAoB,CAAC,CAAC;;;;;SAKxG,KAAK,UAAU,OAAO,QAAQ,CAAC;;;mBAGrB,KAAK,UAAU,OAAO,QAAQ,GAAG,CAAC;;;6BAGxB,KAAK,UAAU,MAAM,CAAC"}
|