@analogjs/vite-plugin-nitro 3.0.0-alpha.91 → 3.0.0-alpha.92
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
|
@@ -2,13 +2,41 @@ import { ViteDevServer } from "vite";
|
|
|
2
2
|
/**
|
|
3
3
|
* Registers development server middleware by discovering and loading middleware files.
|
|
4
4
|
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
5
|
+
* This function:
|
|
6
|
+
* 1. Discovers all TypeScript middleware files in the server/middleware directory
|
|
7
|
+
* 2. Dynamically loads each middleware module using Vite's SSR module loader
|
|
8
|
+
* 3. Registers each middleware handler with the Vite development server
|
|
9
|
+
* 4. Handles middleware execution flow and error handling
|
|
9
10
|
*
|
|
10
11
|
* @param root The project root directory path
|
|
11
12
|
* @param sourceRoot The source directory path (e.g., 'src')
|
|
12
13
|
* @param viteServer The Vite development server instance
|
|
14
|
+
*
|
|
15
|
+
* Example usage:
|
|
16
|
+
* await registerDevServerMiddleware('/workspace/my-app', 'src', viteServer);
|
|
17
|
+
*
|
|
18
|
+
* Sample middleware file paths that would be discovered:
|
|
19
|
+
* - /workspace/my-app/src/server/middleware/auth.ts
|
|
20
|
+
* - /workspace/my-app/src/server/middleware/cors.ts
|
|
21
|
+
* - /workspace/my-app/src/server/middleware/logging.ts
|
|
22
|
+
* - /workspace/my-app/src/server/middleware/validation.ts
|
|
23
|
+
*
|
|
24
|
+
* tinyglobby vs fast-glob comparison:
|
|
25
|
+
* - Both support the same glob patterns for file discovery
|
|
26
|
+
* - Both are efficient for finding middleware files
|
|
27
|
+
* - tinyglobby is now used instead of fast-glob
|
|
28
|
+
* - tinyglobby provides similar functionality with smaller bundle size
|
|
29
|
+
* - tinyglobby's globSync returns absolute paths when absolute: true is set
|
|
30
|
+
*
|
|
31
|
+
* globSync options explained:
|
|
32
|
+
* - dot: true - Includes files/directories that start with a dot (e.g., .env.middleware)
|
|
33
|
+
* - absolute: true - Returns absolute file paths instead of relative paths
|
|
34
|
+
*
|
|
35
|
+
* Middleware execution flow:
|
|
36
|
+
* 1. Request comes to Vite dev server
|
|
37
|
+
* 2. Each registered middleware is executed in order
|
|
38
|
+
* 3. If middleware returns a result, request processing stops
|
|
39
|
+
* 4. If middleware returns no result, next middleware is called
|
|
40
|
+
* 5. If no middleware handles the request, it continues to normal Vite processing
|
|
13
41
|
*/
|
|
14
42
|
export declare function registerDevServerMiddleware(root: string, sourceRoot: string, viteServer: ViteDevServer): Promise<void>;
|
|
@@ -1,40 +1,53 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { createEvent } from "h3";
|
|
2
2
|
import { globSync } from "tinyglobby";
|
|
3
|
-
import { H3 } from "nitro/h3";
|
|
4
3
|
//#region packages/vite-plugin-nitro/src/lib/utils/register-dev-middleware.ts
|
|
5
|
-
var PASSTHROUGH_HEADER = "x-analog-passthrough";
|
|
6
4
|
/**
|
|
7
5
|
* Registers development server middleware by discovering and loading middleware files.
|
|
8
6
|
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
7
|
+
* This function:
|
|
8
|
+
* 1. Discovers all TypeScript middleware files in the server/middleware directory
|
|
9
|
+
* 2. Dynamically loads each middleware module using Vite's SSR module loader
|
|
10
|
+
* 3. Registers each middleware handler with the Vite development server
|
|
11
|
+
* 4. Handles middleware execution flow and error handling
|
|
13
12
|
*
|
|
14
13
|
* @param root The project root directory path
|
|
15
14
|
* @param sourceRoot The source directory path (e.g., 'src')
|
|
16
15
|
* @param viteServer The Vite development server instance
|
|
16
|
+
*
|
|
17
|
+
* Example usage:
|
|
18
|
+
* await registerDevServerMiddleware('/workspace/my-app', 'src', viteServer);
|
|
19
|
+
*
|
|
20
|
+
* Sample middleware file paths that would be discovered:
|
|
21
|
+
* - /workspace/my-app/src/server/middleware/auth.ts
|
|
22
|
+
* - /workspace/my-app/src/server/middleware/cors.ts
|
|
23
|
+
* - /workspace/my-app/src/server/middleware/logging.ts
|
|
24
|
+
* - /workspace/my-app/src/server/middleware/validation.ts
|
|
25
|
+
*
|
|
26
|
+
* tinyglobby vs fast-glob comparison:
|
|
27
|
+
* - Both support the same glob patterns for file discovery
|
|
28
|
+
* - Both are efficient for finding middleware files
|
|
29
|
+
* - tinyglobby is now used instead of fast-glob
|
|
30
|
+
* - tinyglobby provides similar functionality with smaller bundle size
|
|
31
|
+
* - tinyglobby's globSync returns absolute paths when absolute: true is set
|
|
32
|
+
*
|
|
33
|
+
* globSync options explained:
|
|
34
|
+
* - dot: true - Includes files/directories that start with a dot (e.g., .env.middleware)
|
|
35
|
+
* - absolute: true - Returns absolute file paths instead of relative paths
|
|
36
|
+
*
|
|
37
|
+
* Middleware execution flow:
|
|
38
|
+
* 1. Request comes to Vite dev server
|
|
39
|
+
* 2. Each registered middleware is executed in order
|
|
40
|
+
* 3. If middleware returns a result, request processing stops
|
|
41
|
+
* 4. If middleware returns no result, next middleware is called
|
|
42
|
+
* 5. If no middleware handles the request, it continues to normal Vite processing
|
|
17
43
|
*/
|
|
18
44
|
async function registerDevServerMiddleware(root, sourceRoot, viteServer) {
|
|
19
45
|
globSync([`${root}/${sourceRoot}/server/middleware/**/*.ts`], {
|
|
20
46
|
dot: true,
|
|
21
47
|
absolute: true
|
|
22
48
|
}).forEach((file) => {
|
|
23
|
-
const app = new H3();
|
|
24
|
-
app.use(async (event) => {
|
|
25
|
-
return (await viteServer.ssrLoadModule(file).then((m) => m.default))(event);
|
|
26
|
-
});
|
|
27
|
-
app.use(() => new Response(null, {
|
|
28
|
-
status: 204,
|
|
29
|
-
headers: { [PASSTHROUGH_HEADER]: "1" }
|
|
30
|
-
}));
|
|
31
49
|
viteServer.middlewares.use(async (req, res, next) => {
|
|
32
|
-
|
|
33
|
-
if (response.headers.get(PASSTHROUGH_HEADER) === "1") {
|
|
34
|
-
next();
|
|
35
|
-
return;
|
|
36
|
-
}
|
|
37
|
-
await writeWebResponseToNode(res, response);
|
|
50
|
+
if (!await (await viteServer.ssrLoadModule(file).then((m) => m.default))(createEvent(req, res))) next();
|
|
38
51
|
});
|
|
39
52
|
});
|
|
40
53
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"register-dev-middleware.js","names":[],"sources":["../../../../src/lib/utils/register-dev-middleware.ts"],"sourcesContent":["import { ViteDevServer } from 'vite';\nimport { EventHandler,
|
|
1
|
+
{"version":3,"file":"register-dev-middleware.js","names":[],"sources":["../../../../src/lib/utils/register-dev-middleware.ts"],"sourcesContent":["import { ViteDevServer } from 'vite';\nimport { EventHandler, createEvent } from 'h3';\nimport { globSync } from 'tinyglobby';\n\n/**\n * Registers development server middleware by discovering and loading middleware files.\n *\n * This function:\n * 1. Discovers all TypeScript middleware files in the server/middleware directory\n * 2. Dynamically loads each middleware module using Vite's SSR module loader\n * 3. Registers each middleware handler with the Vite development server\n * 4. Handles middleware execution flow and error handling\n *\n * @param root The project root directory path\n * @param sourceRoot The source directory path (e.g., 'src')\n * @param viteServer The Vite development server instance\n *\n * Example usage:\n * await registerDevServerMiddleware('/workspace/my-app', 'src', viteServer);\n *\n * Sample middleware file paths that would be discovered:\n * - /workspace/my-app/src/server/middleware/auth.ts\n * - /workspace/my-app/src/server/middleware/cors.ts\n * - /workspace/my-app/src/server/middleware/logging.ts\n * - /workspace/my-app/src/server/middleware/validation.ts\n *\n * tinyglobby vs fast-glob comparison:\n * - Both support the same glob patterns for file discovery\n * - Both are efficient for finding middleware 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 * globSync options explained:\n * - dot: true - Includes files/directories that start with a dot (e.g., .env.middleware)\n * - absolute: true - Returns absolute file paths instead of relative paths\n *\n * Middleware execution flow:\n * 1. Request comes to Vite dev server\n * 2. Each registered middleware is executed in order\n * 3. If middleware returns a result, request processing stops\n * 4. If middleware returns no result, next middleware is called\n * 5. If no middleware handles the request, it continues to normal Vite processing\n */\nexport async function registerDevServerMiddleware(\n root: string,\n sourceRoot: string,\n viteServer: ViteDevServer,\n): Promise<void> {\n // Discover all TypeScript middleware files in the server/middleware directory\n // Pattern: looks for any .ts files in server/middleware/**/*.ts\n const middlewareFiles = globSync(\n [`${root}/${sourceRoot}/server/middleware/**/*.ts`],\n {\n dot: true,\n absolute: true,\n },\n );\n\n // Register each discovered middleware file with the Vite dev server\n middlewareFiles.forEach((file) => {\n viteServer.middlewares.use(async (req, res, next) => {\n // Dynamically load the middleware module using Vite's SSR module loader\n // This allows for hot module replacement during development\n const middlewareHandler: EventHandler = await viteServer\n .ssrLoadModule(file)\n .then((m: unknown) => (m as { default: EventHandler }).default);\n\n // Execute the middleware handler with the request/response event\n const result = await middlewareHandler(createEvent(req, res));\n\n // If middleware doesn't return a result, continue to next middleware\n // If middleware returns a result, stop processing (middleware handled the request)\n if (!result) {\n next();\n }\n });\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4CA,eAAsB,4BACpB,MACA,YACA,YACe;AAGS,UACtB,CAAC,GAAG,KAAK,GAAG,WAAW,4BAA4B,EACnD;EACE,KAAK;EACL,UAAU;EACX,CACF,CAGe,SAAS,SAAS;AAChC,aAAW,YAAY,IAAI,OAAO,KAAK,KAAK,SAAS;AAYnD,OAAI,CAJW,OALyB,MAAM,WAC3C,cAAc,KAAK,CACnB,MAAM,MAAgB,EAAgC,QAAQ,EAG1B,YAAY,KAAK,IAAI,CAAC,CAK3D,OAAM;IAER;GACF"}
|
|
@@ -1,33 +1,5 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
* the fetch-wiring logic stays in sync.
|
|
7
|
-
*
|
|
8
|
-
* The emitted variable is named `serverFetch` — callers should reference it
|
|
9
|
-
* by that name.
|
|
10
|
-
*/
|
|
11
|
-
export declare const SERVER_FETCH_FACTORY_SNIPPET = "\n const serverFetch = createFetch({\n fetch: (resource, init) => {\n const url = resource instanceof Request ? resource.url : resource.toString();\n return fetchWithEvent(event, url, init);\n }\n });";
|
|
12
|
-
/**
|
|
13
|
-
* SSR renderer virtual module content.
|
|
14
|
-
*
|
|
15
|
-
* This code runs inside Nitro's server runtime (Node.js context) where
|
|
16
|
-
* event.node is always populated. In h3 v2, event.node is typed as optional,
|
|
17
|
-
* so we use h3's first-class event properties (event.path, event.method) where
|
|
18
|
-
* possible and apply optional chaining when accessing the Node.js context for
|
|
19
|
-
* the Angular renderer which requires raw req/res objects.
|
|
20
|
-
*
|
|
21
|
-
* h3 v2 idiomatic APIs used:
|
|
22
|
-
* - defineHandler (replaces defineEventHandler / eventHandler)
|
|
23
|
-
* - event.path (replaces event.node.req.url)
|
|
24
|
-
* - getResponseHeader compat shim (still available in h3 v2)
|
|
25
|
-
*/
|
|
26
|
-
export declare function ssrRenderer(): string;
|
|
27
|
-
/**
|
|
28
|
-
* Client-only renderer virtual module content.
|
|
29
|
-
*
|
|
30
|
-
* Used when SSR is disabled — simply serves the static index.html template
|
|
31
|
-
* for every route, letting the client-side Angular router handle navigation.
|
|
32
|
-
*/
|
|
33
|
-
export declare function clientRenderer(): string;
|
|
1
|
+
export declare const ssrRenderer = "\nimport { eventHandler, getResponseHeader } from 'h3';\n// @ts-ignore\nimport renderer from '#analog/ssr';\n// @ts-ignore\nimport template from '#analog/index';\n\nexport default eventHandler(async (event) => {\n const noSSR = getResponseHeader(event, 'x-analog-no-ssr');\n\n if (noSSR === 'true') {\n return template;\n }\n\n const html = await renderer(event.node.req.url, template, {\n req: event.node.req,\n res: event.node.res,\n });\n\n return html;\n});";
|
|
2
|
+
export declare const ssrStreamRenderer: string;
|
|
3
|
+
export declare function createSsrStreamRenderer(prerender?: boolean): string;
|
|
4
|
+
export declare const clientRenderer = "\nimport { eventHandler } from 'h3';\n\n// @ts-ignore\nimport template from '#analog/index';\n\nexport default eventHandler(async () => {\n return template;\n});\n";
|
|
5
|
+
export declare const apiMiddleware = "\nimport { createError, eventHandler, proxyRequest } from 'h3';\nimport { useRuntimeConfig } from '#imports';\n\nexport default eventHandler(async (event) => {\n const prefix = useRuntimeConfig().prefix;\n const apiPrefix = `${prefix}/${useRuntimeConfig().apiPrefix}`;\n\n const url = event.node.req.url || '';\n\n // only match the prefix on a path boundary, otherwise a URL such as\n // '/apihttp://internal-host' would pass startsWith() and be forwarded verbatim\n if (\n url === apiPrefix ||\n url.startsWith(`${apiPrefix}/`) ||\n url.startsWith(`${apiPrefix}?`)\n ) {\n let reqUrl = url.slice(apiPrefix.length);\n if (reqUrl === '' || reqUrl.startsWith('?')) {\n reqUrl = `/${reqUrl}`;\n }\n\n // reject absolute and protocol-relative targets to prevent SSRF\n if (!reqUrl.startsWith('/') || reqUrl.startsWith('//')) {\n throw createError({ statusCode: 400, statusMessage: 'Invalid API route' });\n }\n\n if (\n event.node.req.method === 'GET' &&\n // in the case of XML routes, we want to proxy the request so that nitro gets the correct headers\n // and can render the XML correctly as a static asset\n !event.node.req.url?.endsWith('.xml')\n ) {\n return $fetch(reqUrl, { headers: event.node.req.headers });\n }\n\n return proxyRequest(event, reqUrl, {\n // @ts-ignore\n fetch: $fetch.native,\n });\n }\n});";
|
|
@@ -1,99 +1,145 @@
|
|
|
1
1
|
//#region packages/vite-plugin-nitro/src/lib/utils/renderers.ts
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
* fetch using ofetch's `createFetch` + h3's `fetchWithEvent`.
|
|
5
|
-
*
|
|
6
|
-
* Shared between the SSR renderer and page-endpoint virtual modules so
|
|
7
|
-
* the fetch-wiring logic stays in sync.
|
|
8
|
-
*
|
|
9
|
-
* The emitted variable is named `serverFetch` — callers should reference it
|
|
10
|
-
* by that name.
|
|
11
|
-
*/
|
|
12
|
-
var SERVER_FETCH_FACTORY_SNIPPET = `
|
|
13
|
-
const serverFetch = createFetch({
|
|
14
|
-
fetch: (resource, init) => {
|
|
15
|
-
const url = resource instanceof Request ? resource.url : resource.toString();
|
|
16
|
-
return fetchWithEvent(event, url, init);
|
|
17
|
-
}
|
|
18
|
-
});`;
|
|
19
|
-
/**
|
|
20
|
-
* SSR renderer virtual module content.
|
|
21
|
-
*
|
|
22
|
-
* This code runs inside Nitro's server runtime (Node.js context) where
|
|
23
|
-
* event.node is always populated. In h3 v2, event.node is typed as optional,
|
|
24
|
-
* so we use h3's first-class event properties (event.path, event.method) where
|
|
25
|
-
* possible and apply optional chaining when accessing the Node.js context for
|
|
26
|
-
* the Angular renderer which requires raw req/res objects.
|
|
27
|
-
*
|
|
28
|
-
* h3 v2 idiomatic APIs used:
|
|
29
|
-
* - defineHandler (replaces defineEventHandler / eventHandler)
|
|
30
|
-
* - event.path (replaces event.node.req.url)
|
|
31
|
-
* - getResponseHeader compat shim (still available in h3 v2)
|
|
32
|
-
*/
|
|
33
|
-
function ssrRenderer() {
|
|
34
|
-
return `
|
|
35
|
-
import { createFetch } from 'ofetch';
|
|
36
|
-
import { defineHandler, fetchWithEvent } from 'nitro/h3';
|
|
2
|
+
var ssrRenderer = `
|
|
3
|
+
import { eventHandler, getResponseHeader } from 'h3';
|
|
37
4
|
// @ts-ignore
|
|
38
5
|
import renderer from '#analog/ssr';
|
|
6
|
+
// @ts-ignore
|
|
39
7
|
import template from '#analog/index';
|
|
40
8
|
|
|
41
|
-
|
|
42
|
-
|
|
9
|
+
export default eventHandler(async (event) => {
|
|
10
|
+
const noSSR = getResponseHeader(event, 'x-analog-no-ssr');
|
|
11
|
+
|
|
12
|
+
if (noSSR === 'true') {
|
|
13
|
+
return template;
|
|
14
|
+
}
|
|
43
15
|
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
16
|
+
const html = await renderer(event.node.req.url, template, {
|
|
17
|
+
req: event.node.req,
|
|
18
|
+
res: event.node.res,
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
return html;
|
|
22
|
+
});`;
|
|
23
|
+
var ssrStreamRenderer = createSsrStreamRenderer();
|
|
24
|
+
function createSsrStreamRenderer(prerender = false) {
|
|
25
|
+
return `
|
|
26
|
+
import { eventHandler, getResponseHeader, setResponseHeader } from 'h3';
|
|
27
|
+
// @ts-ignore
|
|
28
|
+
import renderer from '#analog/ssr';
|
|
29
|
+
// @ts-ignore
|
|
30
|
+
import template from '#analog/index';
|
|
31
|
+
|
|
32
|
+
export default eventHandler(async (event) => {
|
|
33
|
+
const noSSR = getResponseHeader(event, 'x-analog-no-ssr');
|
|
48
34
|
|
|
49
35
|
if (noSSR === 'true') {
|
|
50
36
|
return template;
|
|
51
37
|
}
|
|
52
38
|
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
originalUrl: requestPath,
|
|
64
|
-
}
|
|
65
|
-
: {
|
|
66
|
-
headers: { host: 'localhost' },
|
|
67
|
-
url: requestPath,
|
|
68
|
-
originalUrl: requestPath,
|
|
69
|
-
connection: {},
|
|
39
|
+
const noStreaming = ${prerender} || getResponseHeader(event, 'x-analog-no-streaming') === 'true';
|
|
40
|
+
const abort = new AbortController();
|
|
41
|
+
const response = event.node.res;
|
|
42
|
+
const cleanup = () => {
|
|
43
|
+
response.removeListener('close', disconnected);
|
|
44
|
+
response.removeListener('finish', cleanup);
|
|
45
|
+
};
|
|
46
|
+
const disconnected = () => {
|
|
47
|
+
cleanup();
|
|
48
|
+
if (!response.writableEnded) abort.abort();
|
|
70
49
|
};
|
|
71
|
-
|
|
72
|
-
|
|
50
|
+
response.once('close', disconnected);
|
|
51
|
+
response.once('finish', cleanup);
|
|
73
52
|
|
|
74
|
-
|
|
53
|
+
let stream;
|
|
54
|
+
try {
|
|
55
|
+
stream = await renderer(event.node.req.url, template, {
|
|
56
|
+
req: event.node.req,
|
|
57
|
+
res: response,
|
|
58
|
+
streaming: !noStreaming,
|
|
59
|
+
signal: abort.signal,
|
|
60
|
+
renderErrorsAsHtml: true,
|
|
61
|
+
});
|
|
62
|
+
} catch (error) {
|
|
63
|
+
cleanup();
|
|
64
|
+
throw error;
|
|
65
|
+
}
|
|
75
66
|
|
|
76
|
-
|
|
67
|
+
setResponseHeader(event, 'content-type', 'text/html;charset=utf-8');
|
|
68
|
+
|
|
69
|
+
// A \`streaming: false\` route rule sets this header; renderStream then emits
|
|
70
|
+
// the buffered render() output as a single chunk. Collect it into a string so
|
|
71
|
+
// the response is a normal buffered document (content-length), not chunked.
|
|
72
|
+
if (noStreaming) {
|
|
73
|
+
const reader = stream.getReader();
|
|
74
|
+
const decoder = new TextDecoder();
|
|
75
|
+
let html = '';
|
|
76
|
+
for (;;) {
|
|
77
|
+
const { done, value } = await reader.read();
|
|
78
|
+
if (done) break;
|
|
79
|
+
html += decoder.decode(value, { stream: true });
|
|
80
|
+
}
|
|
81
|
+
html += decoder.decode();
|
|
82
|
+
return html;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
setResponseHeader(event, 'content-encoding', 'identity');
|
|
86
|
+
setResponseHeader(event, 'cache-control', 'no-store, no-transform');
|
|
87
|
+
return stream;
|
|
77
88
|
});`;
|
|
78
89
|
}
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
* for every route, letting the client-side Angular router handle navigation.
|
|
84
|
-
*/
|
|
85
|
-
function clientRenderer() {
|
|
86
|
-
return `
|
|
87
|
-
import { defineHandler } from 'nitro/h3';
|
|
90
|
+
var clientRenderer = `
|
|
91
|
+
import { eventHandler } from 'h3';
|
|
92
|
+
|
|
93
|
+
// @ts-ignore
|
|
88
94
|
import template from '#analog/index';
|
|
89
95
|
|
|
90
|
-
export default
|
|
91
|
-
event.res.headers.set('content-type', 'text/html; charset=utf-8');
|
|
96
|
+
export default eventHandler(async () => {
|
|
92
97
|
return template;
|
|
93
98
|
});
|
|
94
99
|
`;
|
|
95
|
-
|
|
100
|
+
var apiMiddleware = `
|
|
101
|
+
import { createError, eventHandler, proxyRequest } from 'h3';
|
|
102
|
+
import { useRuntimeConfig } from '#imports';
|
|
103
|
+
|
|
104
|
+
export default eventHandler(async (event) => {
|
|
105
|
+
const prefix = useRuntimeConfig().prefix;
|
|
106
|
+
const apiPrefix = \`\${prefix}/\${useRuntimeConfig().apiPrefix}\`;
|
|
107
|
+
|
|
108
|
+
const url = event.node.req.url || '';
|
|
109
|
+
|
|
110
|
+
// only match the prefix on a path boundary, otherwise a URL such as
|
|
111
|
+
// '/apihttp://internal-host' would pass startsWith() and be forwarded verbatim
|
|
112
|
+
if (
|
|
113
|
+
url === apiPrefix ||
|
|
114
|
+
url.startsWith(\`\${apiPrefix}/\`) ||
|
|
115
|
+
url.startsWith(\`\${apiPrefix}?\`)
|
|
116
|
+
) {
|
|
117
|
+
let reqUrl = url.slice(apiPrefix.length);
|
|
118
|
+
if (reqUrl === '' || reqUrl.startsWith('?')) {
|
|
119
|
+
reqUrl = \`/\${reqUrl}\`;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// reject absolute and protocol-relative targets to prevent SSRF
|
|
123
|
+
if (!reqUrl.startsWith('/') || reqUrl.startsWith('//')) {
|
|
124
|
+
throw createError({ statusCode: 400, statusMessage: 'Invalid API route' });
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
if (
|
|
128
|
+
event.node.req.method === 'GET' &&
|
|
129
|
+
// in the case of XML routes, we want to proxy the request so that nitro gets the correct headers
|
|
130
|
+
// and can render the XML correctly as a static asset
|
|
131
|
+
!event.node.req.url?.endsWith('.xml')
|
|
132
|
+
) {
|
|
133
|
+
return $fetch(reqUrl, { headers: event.node.req.headers });
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
return proxyRequest(event, reqUrl, {
|
|
137
|
+
// @ts-ignore
|
|
138
|
+
fetch: $fetch.native,
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
});`;
|
|
96
142
|
//#endregion
|
|
97
|
-
export {
|
|
143
|
+
export { apiMiddleware, clientRenderer, createSsrStreamRenderer, ssrRenderer, ssrStreamRenderer };
|
|
98
144
|
|
|
99
145
|
//# sourceMappingURL=renderers.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"renderers.js","names":[],"sources":["../../../../src/lib/utils/renderers.ts"],"sourcesContent":["
|
|
1
|
+
{"version":3,"file":"renderers.js","names":[],"sources":["../../../../src/lib/utils/renderers.ts"],"sourcesContent":["export const ssrRenderer = `\nimport { eventHandler, getResponseHeader } from 'h3';\n// @ts-ignore\nimport renderer from '#analog/ssr';\n// @ts-ignore\nimport template from '#analog/index';\n\nexport default eventHandler(async (event) => {\n const noSSR = getResponseHeader(event, 'x-analog-no-ssr');\n\n if (noSSR === 'true') {\n return template;\n }\n\n const html = await renderer(event.node.req.url, template, {\n req: event.node.req,\n res: event.node.res,\n });\n\n return html;\n});`;\n\nexport const ssrStreamRenderer: string = createSsrStreamRenderer();\n\nexport function createSsrStreamRenderer(prerender = false): string {\n return `\nimport { eventHandler, getResponseHeader, setResponseHeader } from 'h3';\n// @ts-ignore\nimport renderer from '#analog/ssr';\n// @ts-ignore\nimport template from '#analog/index';\n\nexport default eventHandler(async (event) => {\n const noSSR = getResponseHeader(event, 'x-analog-no-ssr');\n\n if (noSSR === 'true') {\n return template;\n }\n\n const noStreaming = ${prerender} || getResponseHeader(event, 'x-analog-no-streaming') === 'true';\n const abort = new AbortController();\n const response = event.node.res;\n const cleanup = () => {\n response.removeListener('close', disconnected);\n response.removeListener('finish', cleanup);\n };\n const disconnected = () => {\n cleanup();\n if (!response.writableEnded) abort.abort();\n };\n response.once('close', disconnected);\n response.once('finish', cleanup);\n\n let stream;\n try {\n stream = await renderer(event.node.req.url, template, {\n req: event.node.req,\n res: response,\n streaming: !noStreaming,\n signal: abort.signal,\n renderErrorsAsHtml: true,\n });\n } catch (error) {\n cleanup();\n throw error;\n }\n\n setResponseHeader(event, 'content-type', 'text/html;charset=utf-8');\n\n // A \\`streaming: false\\` route rule sets this header; renderStream then emits\n // the buffered render() output as a single chunk. Collect it into a string so\n // the response is a normal buffered document (content-length), not chunked.\n if (noStreaming) {\n const reader = stream.getReader();\n const decoder = new TextDecoder();\n let html = '';\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n html += decoder.decode(value, { stream: true });\n }\n html += decoder.decode();\n return html;\n }\n\n setResponseHeader(event, 'content-encoding', 'identity');\n setResponseHeader(event, 'cache-control', 'no-store, no-transform');\n return stream;\n});`;\n}\n\nexport const clientRenderer = `\nimport { eventHandler } from 'h3';\n\n// @ts-ignore\nimport template from '#analog/index';\n\nexport default eventHandler(async () => {\n return template;\n});\n`;\n\nexport const apiMiddleware = `\nimport { createError, eventHandler, proxyRequest } from 'h3';\nimport { useRuntimeConfig } from '#imports';\n\nexport default eventHandler(async (event) => {\n const prefix = useRuntimeConfig().prefix;\n const apiPrefix = \\`\\${prefix}/\\${useRuntimeConfig().apiPrefix}\\`;\n\n const url = event.node.req.url || '';\n\n // only match the prefix on a path boundary, otherwise a URL such as\n // '/apihttp://internal-host' would pass startsWith() and be forwarded verbatim\n if (\n url === apiPrefix ||\n url.startsWith(\\`\\${apiPrefix}/\\`) ||\n url.startsWith(\\`\\${apiPrefix}?\\`)\n ) {\n let reqUrl = url.slice(apiPrefix.length);\n if (reqUrl === '' || reqUrl.startsWith('?')) {\n reqUrl = \\`/\\${reqUrl}\\`;\n }\n\n // reject absolute and protocol-relative targets to prevent SSRF\n if (!reqUrl.startsWith('/') || reqUrl.startsWith('//')) {\n throw createError({ statusCode: 400, statusMessage: 'Invalid API route' });\n }\n\n if (\n event.node.req.method === 'GET' &&\n // in the case of XML routes, we want to proxy the request so that nitro gets the correct headers\n // and can render the XML correctly as a static asset\n !event.node.req.url?.endsWith('.xml')\n ) {\n return $fetch(reqUrl, { headers: event.node.req.headers });\n }\n\n return proxyRequest(event, reqUrl, {\n // @ts-ignore\n fetch: $fetch.native,\n });\n }\n});`;\n"],"mappings":";AAAA,IAAa,cAAc;;;;;;;;;;;;;;;;;;;;;AAsB3B,IAAa,oBAA4B,yBAAyB;AAElE,SAAgB,wBAAwB,YAAY,OAAe;AACjE,QAAO;;;;;;;;;;;;;;wBAce,UAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoDlC,IAAa,iBAAiB;;;;;;;;;;AAW9B,IAAa,gBAAgB"}
|
|
@@ -7,6 +7,8 @@ import { normalizePath } from "vite";
|
|
|
7
7
|
var SERVER_FN_DISPATCH_VIRTUAL = "#ANALOG_SERVER_FN_DISPATCH";
|
|
8
8
|
/** The single transport route all server functions dispatch through. */
|
|
9
9
|
var SERVER_FN_DISPATCH_ROUTE = "/_analog/fn/:id";
|
|
10
|
+
/** URL prefix of that route, for matching requests before the id is known. */
|
|
11
|
+
var SERVER_FN_DISPATCH_PREFIX = "/_analog/fn/";
|
|
10
12
|
/**
|
|
11
13
|
* The Nitro handler registration for the server-function dispatch route.
|
|
12
14
|
* Unlike page endpoints (one handler per file), every server function shares
|
|
@@ -52,6 +54,6 @@ export default createServerFnEventHandler(
|
|
|
52
54
|
`;
|
|
53
55
|
}
|
|
54
56
|
//#endregion
|
|
55
|
-
export { SERVER_FN_DISPATCH_VIRTUAL, buildServerFnDispatchModule, getServerFnDispatchHandler };
|
|
57
|
+
export { SERVER_FN_DISPATCH_PREFIX, SERVER_FN_DISPATCH_VIRTUAL, buildServerFnDispatchModule, getServerFnDispatchHandler };
|
|
56
58
|
|
|
57
59
|
//# sourceMappingURL=server-fn-endpoints.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server-fn-endpoints.js","names":[],"sources":["../../../../src/lib/utils/server-fn-endpoints.ts"],"sourcesContent":["import type { NitroEventHandler } from 'nitropack';\nimport { normalizePath } from 'vite';\n\nimport type { ServerFnHandlerModule } from './get-server-fn-handlers';\n\n/**\n * Nitro virtual-module id for the generated server-function dispatch handler.\n * Referenced from `nitroConfig.handlers` and provided via `nitroConfig.virtual`.\n */\nexport const SERVER_FN_DISPATCH_VIRTUAL = '#ANALOG_SERVER_FN_DISPATCH';\n\n/** The single transport route all server functions dispatch through. */\nexport const SERVER_FN_DISPATCH_ROUTE = '/_analog/fn/:id';\n\n/** URL prefix of that route, for matching requests before the id is known. */\nexport const SERVER_FN_DISPATCH_PREFIX = '/_analog/fn/';\n\n/**\n * The Nitro handler registration for the server-function dispatch route.\n * Unlike page endpoints (one handler per file), every server function shares\n * this one `/_analog/fn/:id` route; the id selects the function at runtime.\n *\n * The route is fixed and NOT `/api`-prefixed: client proxies always call the\n * absolute `/_analog/fn/:id` URL, so an `/api` prefix (as page endpoints use)\n * would leave the handler unreachable in apps that have an API directory.\n */\nexport function getServerFnDispatchHandler(): NitroEventHandler {\n return {\n route: SERVER_FN_DISPATCH_ROUTE,\n handler: SERVER_FN_DISPATCH_VIRTUAL,\n lazy: true,\n };\n}\n\nexport type BuildServerFnDispatchModuleArgs = {\n /** Discovered `*.server.ts` modules, imported for registration side-effects. */\n modules: ServerFnHandlerModule[];\n /**\n * Absolute path to the app's server config module (`app.config.server.ts`),\n * which exports the `ApplicationConfig` (as `config`) that `main.server.ts`\n * renders with. Handlers bootstrap against it, so they see the same DI the\n * app configured. When absent, handlers run with only `providedIn: 'root'`.\n */\n appConfigModule?: string;\n};\n\n/**\n * Generates the source of the Nitro dispatch handler.\n *\n * The handler imports every discovered `*.server.ts` module so each\n * `serverFn(...)` registers itself, imports the app's server config, then on\n * each request looks up the function by id and runs it via `dispatchServerFn` —\n * the same call path the validation harnesses exercise.\n */\nexport function buildServerFnDispatchModule({\n modules,\n appConfigModule,\n}: BuildServerFnDispatchModuleArgs): string {\n const registrationImports = modules\n .map((m) => `import ${JSON.stringify(normalizePath(m.file))};`)\n .join('\\n');\n\n // Bootstrap against the app's own server config so a handler resolves exactly\n // the services, tokens, and interceptors the app configured — one config, no\n // second provider list. Fall back to an empty config when the app has none.\n const appConfig = appConfigModule\n ? `import { config as serverFnAppConfig } from ${JSON.stringify(\n normalizePath(appConfigModule),\n )};`\n : `const serverFnAppConfig = { providers: [] };`;\n\n // `@analogjs/router/server` is a partially-compiled Angular library, and this\n // module is bundled by Nitro rather than by the app's Angular pipeline, so the\n // linker never runs over it. Loading the compiler gives it the JIT fallback.\n // `zone.js` and the server platform init match the SSR entry, so bootstrapping\n // the app injector below runs in the same environment a render would.\n //\n // The transport itself — id decoding, the malformed-body contract, dispatch,\n // and response writing — lives in `createServerFnEventHandler`, so this module\n // is only wiring: bootstrap the app injector from the app's server config, and\n // hand it to that handler.\n return `import '@angular/compiler';\nimport 'zone.js/node';\nimport '@angular/platform-server/init';\nimport { createServerFnAppInjector, createServerFnEventHandler } from '@analogjs/router/server';\n\n// Discovered server-function modules (registration side-effects).\n${registrationImports}\n\n${appConfig}\n\n// Bootstrapped once from the app's own server config, so a handler resolves the\n// same DI as an SSR render (\\`providedIn: 'root'\\` and listed providers alike).\n// No component is bootstrapped, so nothing renders and the router never\n// navigates. Only REQUEST/RESPONSE are rebuilt per call.\nexport default createServerFnEventHandler(\n createServerFnAppInjector(serverFnAppConfig),\n);\n`;\n}\n"],"mappings":";;;;;;AASA,IAAa,6BAA6B;;AAG1C,IAAa,2BAA2B;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"server-fn-endpoints.js","names":[],"sources":["../../../../src/lib/utils/server-fn-endpoints.ts"],"sourcesContent":["import type { NitroEventHandler } from 'nitropack';\nimport { normalizePath } from 'vite';\n\nimport type { ServerFnHandlerModule } from './get-server-fn-handlers';\n\n/**\n * Nitro virtual-module id for the generated server-function dispatch handler.\n * Referenced from `nitroConfig.handlers` and provided via `nitroConfig.virtual`.\n */\nexport const SERVER_FN_DISPATCH_VIRTUAL = '#ANALOG_SERVER_FN_DISPATCH';\n\n/** The single transport route all server functions dispatch through. */\nexport const SERVER_FN_DISPATCH_ROUTE = '/_analog/fn/:id';\n\n/** URL prefix of that route, for matching requests before the id is known. */\nexport const SERVER_FN_DISPATCH_PREFIX = '/_analog/fn/';\n\n/**\n * The Nitro handler registration for the server-function dispatch route.\n * Unlike page endpoints (one handler per file), every server function shares\n * this one `/_analog/fn/:id` route; the id selects the function at runtime.\n *\n * The route is fixed and NOT `/api`-prefixed: client proxies always call the\n * absolute `/_analog/fn/:id` URL, so an `/api` prefix (as page endpoints use)\n * would leave the handler unreachable in apps that have an API directory.\n */\nexport function getServerFnDispatchHandler(): NitroEventHandler {\n return {\n route: SERVER_FN_DISPATCH_ROUTE,\n handler: SERVER_FN_DISPATCH_VIRTUAL,\n lazy: true,\n };\n}\n\nexport type BuildServerFnDispatchModuleArgs = {\n /** Discovered `*.server.ts` modules, imported for registration side-effects. */\n modules: ServerFnHandlerModule[];\n /**\n * Absolute path to the app's server config module (`app.config.server.ts`),\n * which exports the `ApplicationConfig` (as `config`) that `main.server.ts`\n * renders with. Handlers bootstrap against it, so they see the same DI the\n * app configured. When absent, handlers run with only `providedIn: 'root'`.\n */\n appConfigModule?: string;\n};\n\n/**\n * Generates the source of the Nitro dispatch handler.\n *\n * The handler imports every discovered `*.server.ts` module so each\n * `serverFn(...)` registers itself, imports the app's server config, then on\n * each request looks up the function by id and runs it via `dispatchServerFn` —\n * the same call path the validation harnesses exercise.\n */\nexport function buildServerFnDispatchModule({\n modules,\n appConfigModule,\n}: BuildServerFnDispatchModuleArgs): string {\n const registrationImports = modules\n .map((m) => `import ${JSON.stringify(normalizePath(m.file))};`)\n .join('\\n');\n\n // Bootstrap against the app's own server config so a handler resolves exactly\n // the services, tokens, and interceptors the app configured — one config, no\n // second provider list. Fall back to an empty config when the app has none.\n const appConfig = appConfigModule\n ? `import { config as serverFnAppConfig } from ${JSON.stringify(\n normalizePath(appConfigModule),\n )};`\n : `const serverFnAppConfig = { providers: [] };`;\n\n // `@analogjs/router/server` is a partially-compiled Angular library, and this\n // module is bundled by Nitro rather than by the app's Angular pipeline, so the\n // linker never runs over it. Loading the compiler gives it the JIT fallback.\n // `zone.js` and the server platform init match the SSR entry, so bootstrapping\n // the app injector below runs in the same environment a render would.\n //\n // The transport itself — id decoding, the malformed-body contract, dispatch,\n // and response writing — lives in `createServerFnEventHandler`, so this module\n // is only wiring: bootstrap the app injector from the app's server config, and\n // hand it to that handler.\n return `import '@angular/compiler';\nimport 'zone.js/node';\nimport '@angular/platform-server/init';\nimport { createServerFnAppInjector, createServerFnEventHandler } from '@analogjs/router/server';\n\n// Discovered server-function modules (registration side-effects).\n${registrationImports}\n\n${appConfig}\n\n// Bootstrapped once from the app's own server config, so a handler resolves the\n// same DI as an SSR render (\\`providedIn: 'root'\\` and listed providers alike).\n// No component is bootstrapped, so nothing renders and the router never\n// navigates. Only REQUEST/RESPONSE are rebuilt per call.\nexport default createServerFnEventHandler(\n createServerFnAppInjector(serverFnAppConfig),\n);\n`;\n}\n"],"mappings":";;;;;;AASA,IAAa,6BAA6B;;AAG1C,IAAa,2BAA2B;;AAGxC,IAAa,4BAA4B;;;;;;;;;;AAWzC,SAAgB,6BAAgD;AAC9D,QAAO;EACL,OAAO;EACP,SAAS;EACT,MAAM;EACP;;;;;;;;;;AAuBH,SAAgB,4BAA4B,EAC1C,SACA,mBAC0C;AAwB1C,QAAO;;;;;;EAvBqB,QACzB,KAAK,MAAM,UAAU,KAAK,UAAU,cAAc,EAAE,KAAK,CAAC,CAAC,GAAG,CAC9D,KAAK,KAAK,CA2BO;;EAtBF,kBACd,+CAA+C,KAAK,UAClD,cAAc,gBAAgB,CAC/B,CAAC,KACF,+CAoBM"}
|
|
@@ -1,4 +1,11 @@
|
|
|
1
|
-
import
|
|
1
|
+
import { NitroConfig } from "nitropack";
|
|
2
2
|
import type { Plugin } from "vite";
|
|
3
3
|
import { Options } from "./options.js";
|
|
4
|
-
export
|
|
4
|
+
export interface NitroPluginOptions extends NitroConfig {
|
|
5
|
+
/**
|
|
6
|
+
* Analog options for apps that don't use `analog()` from
|
|
7
|
+
* `@analogjs/platform`. They override the options passed to `analog()`.
|
|
8
|
+
*/
|
|
9
|
+
analog?: Options;
|
|
10
|
+
}
|
|
11
|
+
export declare function nitro(pluginOptions?: NitroPluginOptions): Plugin[];
|