@qwik.dev/router 2.0.0-beta.9 → 2.0.0-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/lib/adapters/azure-swa/vite/index.d.ts +2 -2
  2. package/lib/adapters/azure-swa/vite/index.mjs +44 -57
  3. package/lib/adapters/bun-server/vite/index.d.ts +2 -2
  4. package/lib/adapters/bun-server/vite/index.mjs +16 -22
  5. package/lib/adapters/cloud-run/vite/index.d.ts +2 -2
  6. package/lib/adapters/cloud-run/vite/index.mjs +15 -19
  7. package/lib/adapters/cloudflare-pages/vite/index.d.ts +2 -2
  8. package/lib/adapters/cloudflare-pages/vite/index.mjs +45 -76
  9. package/lib/adapters/deno-server/vite/index.d.ts +2 -2
  10. package/lib/adapters/deno-server/vite/index.mjs +25 -34
  11. package/lib/adapters/netlify-edge/vite/index.d.ts +2 -2
  12. package/lib/adapters/netlify-edge/vite/index.mjs +49 -89
  13. package/lib/adapters/node-server/vite/index.d.ts +2 -2
  14. package/lib/adapters/node-server/vite/index.mjs +16 -22
  15. package/lib/adapters/shared/vite/index.d.ts +9 -16
  16. package/lib/adapters/shared/vite/index.mjs +280 -293
  17. package/lib/adapters/ssg/vite/index.d.ts +1 -1
  18. package/lib/adapters/ssg/vite/index.mjs +13 -299
  19. package/lib/adapters/vercel-edge/vite/index.d.ts +3 -3
  20. package/lib/adapters/vercel-edge/vite/index.mjs +75 -79
  21. package/lib/chunks/dev-preloaded-route-loader.mjs +2 -0
  22. package/lib/chunks/format.mjs +24 -0
  23. package/lib/chunks/fs.mjs +143 -0
  24. package/lib/chunks/head.qwik.mjs +1570 -0
  25. package/lib/chunks/http-error.qwik.mjs +28 -0
  26. package/lib/chunks/pathname.mjs +58 -0
  27. package/lib/chunks/request-body-limit.mjs +27 -0
  28. package/lib/chunks/request-path.mjs +53 -0
  29. package/lib/chunks/route-trie-key.mjs +10 -0
  30. package/lib/chunks/routes.mjs +26 -0
  31. package/lib/chunks/server-error.mjs +38 -0
  32. package/lib/chunks/static-file.mjs +70 -0
  33. package/lib/chunks/system.mjs +271 -0
  34. package/lib/chunks/user-response.mjs +1878 -0
  35. package/lib/chunks/worker-thread.mjs +274 -0
  36. package/lib/index.d.ts +550 -182
  37. package/lib/index.qwik.mjs +1746 -2057
  38. package/lib/middleware/aws-lambda/index.d.ts +15 -17
  39. package/lib/middleware/aws-lambda/index.mjs +46 -50
  40. package/lib/middleware/azure-swa/index.mjs +85 -294
  41. package/lib/middleware/bun/index.d.ts +22 -5
  42. package/lib/middleware/bun/index.mjs +118 -201
  43. package/lib/middleware/cloudflare-pages/index.d.ts +2 -0
  44. package/lib/middleware/cloudflare-pages/index.mjs +103 -101
  45. package/lib/middleware/deno/index.d.ts +22 -5
  46. package/lib/middleware/deno/index.mjs +103 -191
  47. package/lib/middleware/firebase/index.mjs +22 -31
  48. package/lib/middleware/netlify-edge/index.d.ts +2 -0
  49. package/lib/middleware/netlify-edge/index.mjs +64 -80
  50. package/lib/middleware/node/index.d.ts +17 -5
  51. package/lib/middleware/node/index.mjs +298 -269
  52. package/lib/middleware/request-handler/index.d.ts +259 -58
  53. package/lib/middleware/request-handler/index.mjs +108 -1730
  54. package/lib/middleware/vercel-edge/index.d.ts +2 -0
  55. package/lib/middleware/vercel-edge/index.mjs +77 -100
  56. package/lib/modules.d.ts +7 -4
  57. package/lib/service-worker/index.mjs +14 -0
  58. package/lib/ssg/index.d.ts +50 -26
  59. package/lib/ssg/index.mjs +257 -43
  60. package/lib/vite/index.d.ts +59 -11
  61. package/lib/vite/index.mjs +2534 -27536
  62. package/modules.d.ts +7 -4
  63. package/package.json +53 -70
  64. package/lib/adapters/azure-swa/vite/index.cjs +0 -96
  65. package/lib/adapters/bun-server/vite/index.cjs +0 -50
  66. package/lib/adapters/cloud-run/vite/index.cjs +0 -47
  67. package/lib/adapters/cloudflare-pages/vite/index.cjs +0 -115
  68. package/lib/adapters/deno-server/vite/index.cjs +0 -62
  69. package/lib/adapters/netlify-edge/vite/index.cjs +0 -130
  70. package/lib/adapters/node-server/vite/index.cjs +0 -50
  71. package/lib/adapters/shared/vite/index.cjs +0 -338
  72. package/lib/adapters/ssg/vite/index.cjs +0 -339
  73. package/lib/adapters/vercel-edge/vite/index.cjs +0 -118
  74. package/lib/index.qwik.cjs +0 -2112
  75. package/lib/middleware/node/index.cjs +0 -310
  76. package/lib/middleware/request-handler/index.cjs +0 -1766
  77. package/lib/service-worker.cjs +0 -17
  78. package/lib/service-worker.mjs +0 -15
  79. package/lib/ssg/deno.mjs +0 -8
  80. package/lib/ssg/index.cjs +0 -67
  81. package/lib/ssg/node.cjs +0 -1128
  82. package/lib/ssg/node.mjs +0 -1090
  83. package/lib/vite/index.cjs +0 -27607
@@ -21,6 +21,8 @@ export declare type QwikCityVercelEdgeOptions = QwikRouterVercelEdgeOptions;
21
21
 
22
22
  /** @public */
23
23
  export declare interface QwikRouterVercelEdgeOptions extends ServerRenderOptions {
24
+ /** Maximum request body size in bytes. Defaults to 10 MiB. */
25
+ requestBodyLimit?: number;
24
26
  }
25
27
 
26
28
  export { }
@@ -1,110 +1,87 @@
1
- // packages/qwik-router/src/middleware/vercel-edge/index.ts
2
- import { _deserialize, _serialize, _verifySerializable } from "@qwik.dev/core/internal";
1
+ import { r as limitRequestBody } from "../../chunks/request-body-limit.mjs";
2
+ import { isDev } from "@qwik.dev/core/build";
3
3
  import { setServerPlatform } from "@qwik.dev/core/server";
4
- import {
5
- getNotFound,
6
- isStaticPath,
7
- mergeHeadersCookies,
8
- requestHandler
9
- } from "../request-handler/index.mjs";
4
+ import { getErrorHtml, isStaticPath, mergeHeadersCookies, requestHandler } from "@qwik.dev/router/middleware/request-handler";
10
5
  var COUNTRY_HEADER_NAME = "x-vercel-ip-country";
11
6
  var IP_HEADER_NAME = "x-real-ip";
12
7
  var VERCEL_COOKIE = "__vdpl";
13
8
  var VERCEL_SKEW_PROTECTION_ENABLED = "VERCEL_SKEW_PROTECTION_ENABLED";
14
9
  var VERCEL_DEPLOYMENT_ID = "VERCEL_DEPLOYMENT_ID";
15
10
  var BASE_URL = "BASE_URL";
11
+ /** @public */
16
12
  function createQwikRouter(opts) {
17
- if (opts.qwikCityPlan && !opts.qwikRouterConfig) {
18
- console.warn("qwikCityPlan is deprecated. Simply remove it.");
19
- opts.qwikRouterConfig = opts.qwikCityPlan;
20
- }
21
- const qwikSerializer = {
22
- _deserialize,
23
- _serialize,
24
- _verifySerializable
25
- };
26
- if (opts.manifest) {
27
- setServerPlatform(opts.manifest);
28
- }
29
- async function onVercelEdgeRequest(request) {
30
- try {
31
- const url = new URL(request.url);
32
- if (isStaticPath(request.method, url)) {
33
- return new Response(null, {
34
- headers: {
35
- "x-middleware-next": "1"
36
- }
37
- });
38
- }
39
- const p = (() => globalThis.process)();
40
- const serverRequestEv = {
41
- mode: "server",
42
- locale: void 0,
43
- url,
44
- request,
45
- env: {
46
- get(key) {
47
- return p.env[key];
48
- }
49
- },
50
- getWritableStream: (status, headers, cookies, resolve) => {
51
- const { readable, writable } = new TransformStream();
52
- if (serverRequestEv.env.get(VERCEL_SKEW_PROTECTION_ENABLED)) {
53
- const deploymentId = serverRequestEv.env.get(VERCEL_DEPLOYMENT_ID) || "";
54
- const baseUrl = serverRequestEv.env.get(BASE_URL) || "/";
55
- if (request.headers.has("Sec-Fetch-Dest")) {
56
- cookies.set(VERCEL_COOKIE, deploymentId, {
57
- path: baseUrl,
58
- secure: true,
59
- sameSite: true,
60
- httpOnly: true
61
- });
62
- }
63
- }
64
- const response = new Response(readable, {
65
- status,
66
- headers: mergeHeadersCookies(headers, cookies)
67
- });
68
- resolve(response);
69
- return writable;
70
- },
71
- platform: {},
72
- getClientConn: () => {
73
- return {
74
- ip: request.headers.get(IP_HEADER_NAME) ?? void 0,
75
- country: request.headers.get(COUNTRY_HEADER_NAME) ?? void 0
76
- };
77
- }
78
- };
79
- const handledResponse = await requestHandler(serverRequestEv, opts, qwikSerializer);
80
- if (handledResponse) {
81
- handledResponse.completion.then((v) => {
82
- if (v) {
83
- console.error(v);
84
- }
85
- });
86
- const response = await handledResponse.response;
87
- if (response) {
88
- return response;
89
- }
90
- }
91
- const notFoundHtml = isStaticPath(request.method || "GET", url) ? "Not Found" : getNotFound(url.pathname);
92
- return new Response(notFoundHtml, {
93
- status: 404,
94
- headers: { "Content-Type": "text/html; charset=utf-8", "X-Not-Found": url.pathname }
95
- });
96
- } catch (e) {
97
- console.error(e);
98
- return new Response(String(e || "Error"), {
99
- status: 500,
100
- headers: { "Content-Type": "text/plain; charset=utf-8", "X-Error": "vercel-edge" }
101
- });
102
- }
103
- }
104
- return onVercelEdgeRequest;
13
+ if (opts.manifest) setServerPlatform(opts.manifest);
14
+ async function onVercelEdgeRequest(request) {
15
+ try {
16
+ const url = new URL(request.url);
17
+ if (isStaticPath(request.method, url)) return new Response(null, { headers: { "x-middleware-next": "1" } });
18
+ const p = (() => globalThis.process)();
19
+ const serverRequestEv = {
20
+ mode: "server",
21
+ locale: void 0,
22
+ url,
23
+ request: limitRequestBody(request, opts.requestBodyLimit),
24
+ env: { get(key) {
25
+ return p.env[key];
26
+ } },
27
+ getWritableStream: (status, headers, cookies, resolve) => {
28
+ const { readable, writable } = new TransformStream();
29
+ if (serverRequestEv.env.get(VERCEL_SKEW_PROTECTION_ENABLED)) {
30
+ const deploymentId = serverRequestEv.env.get(VERCEL_DEPLOYMENT_ID) || "";
31
+ const baseUrl = serverRequestEv.env.get(BASE_URL) || "/";
32
+ if (request.headers.has("Sec-Fetch-Dest")) cookies.set(VERCEL_COOKIE, deploymentId, {
33
+ path: baseUrl,
34
+ secure: true,
35
+ sameSite: true,
36
+ httpOnly: true
37
+ });
38
+ }
39
+ resolve(new Response(readable, {
40
+ status,
41
+ headers: mergeHeadersCookies(headers, cookies)
42
+ }));
43
+ return writable;
44
+ },
45
+ platform: {},
46
+ getClientConn: () => {
47
+ return {
48
+ ip: request.headers.get(IP_HEADER_NAME) ?? void 0,
49
+ country: request.headers.get(COUNTRY_HEADER_NAME) ?? void 0
50
+ };
51
+ }
52
+ };
53
+ const handledResponse = await requestHandler(serverRequestEv, opts);
54
+ if (handledResponse) {
55
+ handledResponse.completion.then((completion) => {
56
+ if (completion) console.error(completion);
57
+ });
58
+ const response = await handledResponse.response;
59
+ if (response) return response;
60
+ }
61
+ const notFoundHtml = !request.headers.get("accept")?.includes("text/html") || isStaticPath(request.method || "GET", url) ? "Not Found" : getErrorHtml(404, "Not Found");
62
+ return new Response(notFoundHtml, {
63
+ status: 404,
64
+ headers: {
65
+ "Content-Type": "text/html; charset=utf-8",
66
+ "X-Not-Found": url.pathname
67
+ }
68
+ });
69
+ } catch (e) {
70
+ console.error(e);
71
+ return new Response(isDev ? String(e || "Error") : "Internal Server Error", {
72
+ status: 500,
73
+ headers: {
74
+ "Content-Type": "text/plain; charset=utf-8",
75
+ "X-Error": "vercel-edge"
76
+ }
77
+ });
78
+ }
79
+ }
80
+ return onVercelEdgeRequest;
105
81
  }
82
+ /**
83
+ * @deprecated Use `createQwikRouter` instead. Will be removed in V3
84
+ * @public
85
+ */
106
86
  var createQwikCity = createQwikRouter;
107
- export {
108
- createQwikCity,
109
- createQwikRouter
110
- };
87
+ export { createQwikCity, createQwikRouter };
package/lib/modules.d.ts CHANGED
@@ -1,15 +1,18 @@
1
1
  declare module '@qwik-router-config' {
2
- export const routes: any[];
3
- export const menus: any[];
2
+ import type { RouteData, RouteModule } from '@qwik.dev/router';
3
+ export const routes: RouteData;
4
+ export const serverPlugins: RouteModule[];
4
5
  export const trailingSlash: boolean;
5
6
  export const basePathname: string;
6
7
  export const cacheModules: boolean;
8
+ export const fallthrough: boolean;
7
9
  const defaultExport: {
8
- routes: any[];
9
- menus: any[];
10
+ routes: RouteData;
11
+ serverPlugins: RouteModule[];
10
12
  trailingSlash: boolean;
11
13
  basePathname: string;
12
14
  cacheModules: boolean;
15
+ fallthrough: boolean;
13
16
  };
14
17
  export default defaultExport;
15
18
  }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * @deprecated This is no longer needed, Qwik now automatically embeds preloading logic into the
3
+ * application.
4
+ *
5
+ * If your service-worker.ts file contains no custom code, you should deploy to production until
6
+ * you're sure that all users picked up the new version, then you can remove it and also remove
7
+ * the `<ServiceWorkerRegister />` component from your `Root.tsx`.
8
+ *
9
+ * If you do have custom service worker logic, you should keep the `service-worker.ts` file and
10
+ * `<ServiceWorkerRegister />` component, but remove the `setupServiceWorker()` call.
11
+ * @public
12
+ */
13
+ var setupServiceWorker = () => {};
14
+ export { setupServiceWorker };
@@ -1,3 +1,5 @@
1
+ import type { QwikRouterConfig } from '@qwik.dev/router';
2
+ import type { Render } from '@qwik.dev/core/server';
1
3
  import type { RenderOptions } from '@qwik.dev/core/server';
2
4
 
3
5
  /**
@@ -6,7 +8,40 @@ import type { RenderOptions } from '@qwik.dev/core/server';
6
8
  *
7
9
  * @public
8
10
  */
9
- export declare function generate(opts: StaticGenerateOptions): Promise<StaticGenerateResult>;
11
+ export declare function generate(opts: SsgInternalOptions): Promise<StaticGenerateResult>;
12
+
13
+ /**
14
+ * Run SSG as a standalone process. Writes `_static-paths.json` to `outDir` and exits with code 0 on
15
+ * success, 1 on error.
16
+ *
17
+ * Intended to be called from a generated `run-ssg.js` wrapper that provides render/config.
18
+ *
19
+ * @public
20
+ */
21
+ export declare function runSsg(opts: SsgInternalOptions): Promise<never>;
22
+
23
+ /**
24
+ * Internal SSG options that include the render function and router config.
25
+ *
26
+ * @public
27
+ */
28
+ export declare interface SsgInternalOptions extends SsgOptions {
29
+ /** SSR render function (default export from `entry.ssr`); worker-only — the main entry omits it. */
30
+ render: Render;
31
+ /** The Qwik Router Config object (default export from `@qwik-router-config`). */
32
+ qwikRouterConfig: QwikRouterConfig;
33
+ /** Path or URL to the worker entry file (`run-ssg-worker.js`); workers are spawned from it. */
34
+ workerFilePath?: string | URL;
35
+ }
36
+
37
+ /** @public */
38
+ declare interface SsgOptions extends SsgRenderOptions {
39
+ /** Defaults to `/` */
40
+ basePathname?: string;
41
+ rootDir?: string;
42
+ }
43
+ export { SsgOptions }
44
+ export { SsgOptions as StaticGenerateOptions }
10
45
 
11
46
  /** @public */
12
47
  export declare interface SsgRenderOptions extends RenderOptions {
@@ -37,24 +72,19 @@ export declare interface SsgRenderOptions extends RenderOptions {
37
72
  * root of the `outDir`. Setting to `null` will prevent the sitemap from being created.
38
73
  */
39
74
  sitemapOutFile?: string | null;
40
- /** Log level. */
41
- log?: 'debug';
75
+ /** Log level. `'quiet'` suppresses per-page output, `'debug'` enables verbose logging. */
76
+ log?: 'debug' | 'quiet';
42
77
  /**
43
78
  * Set to `false` if the generated static HTML files should not be written to disk. Setting to
44
- * `false` is useful if the SSG should only write the `q-data.json` files to disk. Defaults to
79
+ * `false` is useful if the SSG should only write the per-loader data files to disk. Defaults to
45
80
  * `true`.
46
81
  */
47
82
  emitHtml?: boolean;
48
83
  /**
49
- * Set to `false` if the generated `q-data.json` data files should not be written to disk.
50
- * Defaults to `true`.
84
+ * Set to `false` if the generated per-loader data files should not be written to disk. Defaults
85
+ * to `true`.
51
86
  */
52
87
  emitData?: boolean;
53
- /**
54
- * Set to `false` if the static build should not write custom or default `404.html` pages.
55
- * Defaults to `true`.
56
- */
57
- emit404Pages?: boolean;
58
88
  /**
59
89
  * Defines file system routes relative to the source `routes` directory that should be static
60
90
  * generated. Accepts wildcard behavior. This should not include the "base" pathname. If not
@@ -69,21 +99,15 @@ export declare interface SsgRenderOptions extends RenderOptions {
69
99
  exclude?: string[];
70
100
  }
71
101
 
72
- /** @public */
73
- export declare interface StaticGenerateOptions extends SsgRenderOptions {
74
- /**
75
- * Path to the SSR module exporting the default render function. In most cases it'll be
76
- * `./src/entry.ssr.tsx`.
77
- */
78
- renderModulePath: string;
79
- /** Path to the Qwik Router Config module exporting the default `@qwik-router-config`. */
80
- qwikRouterConfigModulePath: string;
81
- /** @deprecated Use `qwikRouterConfigModulePath` instead. Will be removed in V3 */
82
- qwikCityPlanModulePath?: string;
83
- /** Defaults to `/` */
84
- basePathname?: string;
85
- rootDir?: string;
86
- }
102
+ /**
103
+ * Bootstrap a worker thread for SSG rendering. Called from the generated `run-ssg.js` when it
104
+ * detects it's running as a worker thread.
105
+ *
106
+ * @param opts - Must include `render` and `qwikRouterConfig` (imported by the worker entry). The
107
+ * remaining serializable options come from `workerData`.
108
+ * @public
109
+ */
110
+ export declare function startWorker(opts: Pick<SsgInternalOptions, 'render' | 'qwikRouterConfig'>): Promise<void>;
87
111
 
88
112
  /** @public */
89
113
  export declare interface StaticGenerateResult {
package/lib/ssg/index.mjs CHANGED
@@ -1,48 +1,262 @@
1
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
- }) : x)(function(x) {
4
- if (typeof require !== "undefined") return require.apply(this, arguments);
5
- throw Error('Dynamic require of "' + x + '" is not supported');
6
- });
7
-
8
- // packages/qwik-router/src/ssg/index.ts
9
- async function generate(opts) {
10
- const ssgPlatform = await getEntryModule();
11
- const result = await ssgPlatform.generate(opts);
12
- return result;
13
- }
14
- function getEntryModulePath() {
15
- if (isDeno()) {
16
- return "./deno.mjs";
17
- }
18
- if (isNode() || isBun()) {
19
- if (isCjs()) {
20
- return "./node.cjs";
21
- }
22
- return "./node.mjs";
23
- }
24
- throw new Error(`Unsupported platform`);
1
+ import { n as getPathnameForDynamicRoute, t as ensureSlash } from "../chunks/pathname.mjs";
2
+ import { n as isStaticTrieKey, r as unescapeStaticTrieKey } from "../chunks/route-trie-key.mjs";
3
+ import { r as msToString } from "../chunks/format.mjs";
4
+ import { t as createRouteTester } from "../chunks/routes.mjs";
5
+ import { relative } from "node:path";
6
+ import { bold, dim, green, magenta, red } from "kleur/colors";
7
+ async function mainThread(sys) {
8
+ const opts = sys.getOptions();
9
+ validateOptions(opts);
10
+ const main = await sys.createMainProcess();
11
+ const log = await sys.createLogger();
12
+ log.info("\n" + bold(green("Starting Qwik Router SSG...")));
13
+ const qwikRouterConfig = opts.qwikRouterConfig;
14
+ const renderTimeout = 3e4;
15
+ const queue = [];
16
+ const active = /* @__PURE__ */ new Set();
17
+ const routes = qwikRouterConfig.routes;
18
+ const trailingSlash = !!qwikRouterConfig.trailingSlash;
19
+ const includeRoute = createRouteTester(opts.basePathname || "/", opts.include, opts.exclude);
20
+ return new Promise((resolve, reject) => {
21
+ try {
22
+ const timer = sys.createTimer();
23
+ const generatorResult = {
24
+ duration: 0,
25
+ rendered: 0,
26
+ errors: 0,
27
+ staticPaths: []
28
+ };
29
+ let isCompleted = false;
30
+ let isRoutesLoaded = false;
31
+ const completed = async () => {
32
+ const closePromise = main.close();
33
+ generatorResult.duration = timer();
34
+ if (generatorResult.errors === 0) {
35
+ log.info(`\n${green("SSG results")}`);
36
+ if (generatorResult.rendered > 0) log.info(`- Generated: ${dim(`${generatorResult.rendered} page${generatorResult.rendered === 1 ? "" : "s"}`)}`);
37
+ log.info(`- Duration: ${dim(msToString(generatorResult.duration))}`);
38
+ const total = generatorResult.rendered + generatorResult.errors;
39
+ if (total > 0) log.info(`- Average: ${dim(msToString(generatorResult.duration / total) + " per page")}`);
40
+ log.info(``);
41
+ }
42
+ closePromise.then(() => {
43
+ setTimeout(() => resolve(generatorResult));
44
+ }).catch(reject);
45
+ };
46
+ const next = () => {
47
+ while (!isCompleted && main.hasAvailableWorker() && queue.length > 0) {
48
+ const staticRoute = queue.shift();
49
+ if (staticRoute) render(staticRoute).catch((e) => {
50
+ console.error(`render failed for ${staticRoute.pathname}`, e);
51
+ });
52
+ }
53
+ if (!isCompleted && isRoutesLoaded && queue.length === 0 && active.size === 0) {
54
+ isCompleted = true;
55
+ completed().catch((e) => {
56
+ console.error("SSG completion failed", e);
57
+ });
58
+ }
59
+ };
60
+ let isPendingDrain = false;
61
+ const flushQueue = () => {
62
+ if (!isPendingDrain) {
63
+ isPendingDrain = true;
64
+ setTimeout(() => {
65
+ isPendingDrain = false;
66
+ next();
67
+ });
68
+ }
69
+ };
70
+ const render = async (staticRoute) => {
71
+ try {
72
+ active.add(staticRoute.pathname);
73
+ log.debug(`render start: ${staticRoute.pathname}`);
74
+ const result = await Promise.race([main.render({
75
+ type: "render",
76
+ ...staticRoute
77
+ }), new Promise((_, reject) => setTimeout(() => reject(/* @__PURE__ */ new Error(`SSG render timed out after ${renderTimeout}ms`)), renderTimeout))]);
78
+ active.delete(staticRoute.pathname);
79
+ log.debug(`render done: ${staticRoute.pathname}`);
80
+ if (result.error) {
81
+ const err = new Error(result.error.message);
82
+ err.stack = result.error.stack;
83
+ log.error(`\n${bold(red(`!!! ${result.pathname}: Error during SSG`))}`);
84
+ log.error(red(err.message));
85
+ log.error(` Pathname: ${magenta(staticRoute.pathname)}`);
86
+ if (err.stack) log.error(dim(err.stack));
87
+ generatorResult.errors++;
88
+ }
89
+ if (result.filePath != null) {
90
+ generatorResult.rendered++;
91
+ generatorResult.staticPaths.push(result.pathname);
92
+ const base = opts.rootDir ?? opts.outDir;
93
+ const path = relative(base, result.filePath);
94
+ const lastSlash = path.lastIndexOf("/");
95
+ log.info(`${dim(path.slice(0, lastSlash + 1))}${path.slice(lastSlash + 1)}`);
96
+ }
97
+ flushQueue();
98
+ } catch (e) {
99
+ console.error(`render failed for ${staticRoute.pathname}`, e);
100
+ isCompleted = true;
101
+ reject(e);
102
+ }
103
+ };
104
+ const addToQueue = (pathname, params) => {
105
+ if (pathname) {
106
+ pathname = new URL(pathname, `https://qwik.dev`).pathname;
107
+ if (pathname !== opts.basePathname) {
108
+ if (trailingSlash) {
109
+ if (!pathname.endsWith("/")) {
110
+ const segments = pathname.split("/");
111
+ if (!segments[segments.length - 1].includes(".")) pathname = ensureSlash(pathname);
112
+ }
113
+ } else if (pathname.endsWith("/")) pathname = pathname.slice(0, pathname.length - 1);
114
+ }
115
+ if (includeRoute(pathname) && !queue.some((s) => s.pathname === pathname)) {
116
+ queue.push({
117
+ pathname,
118
+ params
119
+ });
120
+ flushQueue();
121
+ }
122
+ }
123
+ };
124
+ /**
125
+ * Traverse the route tree and call the callback for each route that has module loaders.
126
+ * Reconstructs the original pathname and param names from the tree path. Accumulates _L
127
+ * layout loaders from ancestors during traversal.
128
+ */
129
+ const traverseRouteTree = async (node, pathParts, basePathname, ancestorLoaders) => {
130
+ const currentLoaders = node._L ? [...ancestorLoaders, node._L] : ancestorLoaders;
131
+ const index = node._I;
132
+ if (index) {
133
+ const pageLoaders = Array.isArray(index) ? index : [...currentLoaders, index];
134
+ const joinedParts = pathParts.join("/");
135
+ const originalPathname = basePathname + (joinedParts ? ensureSlash(joinedParts) : "");
136
+ const paramNames = pathParts.filter((p) => p.startsWith("[") && p.endsWith("]")).map((p) => p.startsWith("[...") ? p.slice(4, -1) : p.slice(1, -1));
137
+ if (paramNames.length === 0) addToQueue(originalPathname, void 0);
138
+ else {
139
+ const pageLoader = pageLoaders[pageLoaders.length - 1];
140
+ if (typeof pageLoader === "function") {
141
+ const pageModule = await pageLoader();
142
+ if (typeof pageModule.onStaticGenerate === "function") {
143
+ const staticGenerate = await pageModule.onStaticGenerate({ env: { get(key) {
144
+ return sys.getEnv(key);
145
+ } } });
146
+ if (Array.isArray(staticGenerate.params)) for (const params of staticGenerate.params) {
147
+ const pathname = getPathnameForDynamicRoute(originalPathname, paramNames, params);
148
+ addToQueue(pathname, params);
149
+ }
150
+ }
151
+ }
152
+ }
153
+ }
154
+ if (node._4 || node._E) {
155
+ if (!pathParts.some((p) => p.startsWith("["))) {
156
+ const joinedParts = pathParts.join("/");
157
+ const dirPathname = basePathname + (joinedParts ? ensureSlash(joinedParts) : "");
158
+ addToQueue(dirPathname + "404.html", void 0);
159
+ }
160
+ }
161
+ if (node._M) for (const group of node._M) await traverseRouteTree(group, pathParts, basePathname, currentLoaders);
162
+ if (node._W && typeof node._W === "object") {
163
+ const childNode = node._W;
164
+ const paramName = childNode._P;
165
+ const pathPart = paramName ? `[${paramName}]` : "[param]";
166
+ await traverseRouteTree(childNode, [...pathParts, pathPart], basePathname, currentLoaders);
167
+ }
168
+ if (node._A && typeof node._A === "object") {
169
+ const childNode = node._A;
170
+ const paramName = childNode._P;
171
+ const pathPart = paramName ? `[...${paramName}]` : "[...rest]";
172
+ await traverseRouteTree(childNode, [...pathParts, pathPart], basePathname, currentLoaders);
173
+ }
174
+ for (const [key, child] of Object.entries(node)) {
175
+ if (!isStaticTrieKey(key)) continue;
176
+ await traverseRouteTree(child, [...pathParts, unescapeStaticTrieKey(key)], basePathname, currentLoaders);
177
+ }
178
+ };
179
+ const loadStaticRoutes = async () => {
180
+ log.debug("traversing route tree...");
181
+ await traverseRouteTree(routes, [], "/", []);
182
+ log.debug(`route tree traversed, ${queue.length} routes queued, ${active.size} active`);
183
+ isRoutesLoaded = true;
184
+ flushQueue();
185
+ };
186
+ loadStaticRoutes().catch((e) => {
187
+ console.error("SSG route loading failed", e);
188
+ reject(e);
189
+ });
190
+ } catch (e) {
191
+ console.error("SSG main thread failed", e);
192
+ reject(e);
193
+ }
194
+ });
25
195
  }
26
- function getEntryModule() {
27
- const entryModule = getEntryModulePath();
28
- if (isCjs()) {
29
- return __require(entryModule);
30
- }
31
- return import(entryModule);
196
+ function validateOptions(opts) {
197
+ if (!opts.qwikRouterConfig) throw new Error(`Missing "qwikRouterConfig" option`);
198
+ let siteOrigin = opts.origin;
199
+ if (typeof siteOrigin !== "string" || siteOrigin.trim().length === 0) throw new Error(`Missing "origin" option`);
200
+ siteOrigin = siteOrigin.trim();
201
+ if (!/:\/\//.test(siteOrigin) || siteOrigin.startsWith("://")) throw new Error(`"origin" must start with a valid protocol, such as "https://" or "http://", received "${siteOrigin}"`);
202
+ try {
203
+ new URL(siteOrigin);
204
+ } catch (e) {
205
+ throw new Error(`Invalid "origin"`, { cause: e });
206
+ }
32
207
  }
33
- function isDeno() {
34
- return typeof Deno !== "undefined";
35
- }
36
- function isBun() {
37
- return typeof Bun !== "undefined";
208
+ /**
209
+ * Use this function when SSG should be generated from another module, such as a Vite plugin. This
210
+ * function's should be passed the paths of the entry module and Qwik Router Plan.
211
+ *
212
+ * @public
213
+ */
214
+ async function generate(opts) {
215
+ const { createSystem } = await import("../chunks/system.mjs");
216
+ return mainThread(await createSystem(opts));
38
217
  }
39
- function isNode() {
40
- return !isBun() && !isDeno() && typeof process !== "undefined" && !!process.versions?.node;
218
+ /**
219
+ * Run SSG as a standalone process. Writes `_static-paths.json` to `outDir` and exits with code 0 on
220
+ * success, 1 on error.
221
+ *
222
+ * Intended to be called from a generated `run-ssg.js` wrapper that provides render/config.
223
+ *
224
+ * @public
225
+ */
226
+ async function runSsg(opts) {
227
+ try {
228
+ const result = await generate(opts);
229
+ const fs = await import("node:fs");
230
+ const { join } = await import("node:path");
231
+ const staticPathsFile = join(opts.outDir, "_static-paths.json");
232
+ await fs.promises.writeFile(staticPathsFile, JSON.stringify(result.staticPaths));
233
+ if (result.errors > 0) {
234
+ console.error(`SSG completed with ${result.errors} error(s)`);
235
+ process.exit(1);
236
+ }
237
+ process.exit(0);
238
+ } catch (e) {
239
+ console.error("SSG failed:", e);
240
+ process.exit(1);
241
+ }
41
242
  }
42
- function isCjs() {
43
- const req = "require";
44
- return isNode() && typeof globalThis[req] === "function";
243
+ /**
244
+ * Bootstrap a worker thread for SSG rendering. Called from the generated `run-ssg.js` when it
245
+ * detects it's running as a worker thread.
246
+ *
247
+ * @param opts - Must include `render` and `qwikRouterConfig` (imported by the worker entry). The
248
+ * remaining serializable options come from `workerData`.
249
+ * @public
250
+ */
251
+ async function startWorker(opts) {
252
+ const { workerData } = await import("node:worker_threads");
253
+ const mergedOpts = {
254
+ ...workerData,
255
+ render: opts.render,
256
+ qwikRouterConfig: opts.qwikRouterConfig
257
+ };
258
+ const { createSystem } = await import("../chunks/system.mjs");
259
+ const { workerThread } = await import("../chunks/worker-thread.mjs");
260
+ await workerThread(await createSystem(mergedOpts, workerData?.threadId));
45
261
  }
46
- export {
47
- generate
48
- };
262
+ export { generate, runSsg, startWorker };