@analogjs/platform 3.0.0-beta.19 → 3.0.0-beta.20

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@analogjs/platform",
3
- "version": "3.0.0-beta.19",
3
+ "version": "3.0.0-beta.20",
4
4
  "description": "The fullstack meta-framework for Angular",
5
5
  "type": "module",
6
6
  "author": "Brandon Roberts <robertsbt@gmail.com>",
@@ -31,7 +31,7 @@
31
31
  "url": "https://github.com/sponsors/brandonroberts"
32
32
  },
33
33
  "dependencies": {
34
- "@analogjs/vite-plugin-angular": "3.0.0-beta.19",
34
+ "@analogjs/vite-plugin-angular": "3.0.0-beta.20",
35
35
  "es-toolkit": "^1.45.1",
36
36
  "front-matter": "^4.0.2",
37
37
  "magic-string": "^0.30.21",
@@ -1,3 +1,3 @@
1
- import type { Plugin } from "vite";
1
+ import { type Plugin } from "vite";
2
2
  import { Options } from "./options.js";
3
3
  export declare function depsPlugin(options?: Options): Plugin[];
@@ -1,6 +1,8 @@
1
1
  import { debugPlatform } from "./utils/debug.js";
2
2
  import { getJsTransformConfigKey, isRolldown } from "./utils/rolldown.js";
3
3
  import { angularLinkerPlugin } from "./nitro/angular-linker-plugin.js";
4
+ import { dirname, resolve } from "node:path";
5
+ import { normalizePath } from "vite";
4
6
  import { crawlFrameworkPkgs } from "vitefu";
5
7
  //#region packages/platform/src/lib/deps-plugin.ts
6
8
  var ANGULAR_LINKED_SSR_DEPS = [
@@ -16,12 +18,13 @@ function depsPlugin(options) {
16
18
  config(userConfig) {
17
19
  const jsTransformKey = getJsTransformConfigKey();
18
20
  const userTransform = userConfig?.[jsTransformKey] !== void 0 || jsTransformKey === "oxc" && !!userConfig?.esbuild;
21
+ const transform = options?.server ? { include: [`${normalizePath(resolve(userConfig?.root ?? process.cwd(), dirname(options.server.entry)))}/**/*.ts`] } : { exclude: ["**/*.ts", "**/*.js"] };
19
22
  debugPlatform("deps transform config", {
20
23
  jsTransformKey,
21
- transformExcluded: !userTransform
24
+ transform: userTransform ? "user" : transform
22
25
  });
23
26
  return {
24
- ...userTransform ? {} : { [jsTransformKey]: { exclude: ["**/*.ts", "**/*.js"] } },
27
+ ...userTransform ? {} : { [jsTransformKey]: transform },
25
28
  ssr: {
26
29
  noExternal: [
27
30
  "@analogjs/**",
@@ -1 +1 @@
1
- {"version":3,"file":"deps-plugin.js","names":[],"sources":["../../../src/lib/deps-plugin.ts"],"sourcesContent":["import type { Plugin } from 'vite';\nimport { crawlFrameworkPkgs } from 'vitefu';\n\nimport { angularLinkerPlugin } from './nitro/angular-linker-plugin.js';\nimport { Options } from './options.js';\nimport { debugPlatform } from './utils/debug.js';\nimport { getJsTransformConfigKey, isRolldown } from './utils/rolldown.js';\n\nconst ANGULAR_LINKED_SSR_DEPS = [\n '@angular/compiler',\n '@angular/core',\n '@angular/platform-browser',\n '@angular/platform-server',\n];\n\nexport function depsPlugin(options?: Options): Plugin[] {\n const workspaceRoot =\n options?.workspaceRoot ?? process.env['NX_WORKSPACE_ROOT'] ?? process.cwd();\n\n return [\n {\n name: 'analogjs-deps-plugin',\n config(userConfig) {\n // Skip Vite's built-in ts/js transform so `@analogjs/vite-plugin-angular`\n // (when the user includes it) owns Angular file compilation. Users who\n // run an alternative compiler, or compile non-Angular server code with\n // Vite, set the transform in their own Vite config. Theirs is kept\n // as-is: merging would concatenate these excludes into it, and an\n // exclude wins over any include they set.\n const jsTransformKey = getJsTransformConfigKey();\n // Vite 8 still converts a user's `esbuild` object to `oxc` (unless\n // `oxc` is set), but `esbuild: false` no longer has any effect there.\n const userTransform =\n userConfig?.[jsTransformKey] !== undefined ||\n (jsTransformKey === 'oxc' && !!userConfig?.esbuild);\n debugPlatform('deps transform config', {\n jsTransformKey,\n transformExcluded: !userTransform,\n });\n\n return {\n ...(userTransform\n ? {}\n : { [jsTransformKey]: { exclude: ['**/*.ts', '**/*.js'] } }),\n ssr: {\n noExternal: [\n '@analogjs/**',\n 'es-toolkit',\n 'firebase/**',\n 'firebase-admin/**',\n 'rxfire',\n '@ng-web-apis/**',\n '@taiga-ui/**',\n /^@tanstack\\/angular-/,\n ],\n // The server pre-bundle is resolved separately from the client\n // one, so a secondary entry point left out of it loads its own\n // copy of `@angular/core`. `inject()` then runs against a runtime\n // with no active injection context and SSR fails with NG0203.\n // With Rolldown, the rest of Angular is pre-bundled too and the\n // partial-compilation packages are linked, so the server needs no JIT.\n optimizeDeps: {\n include: [\n ...(isRolldown() ? ANGULAR_LINKED_SSR_DEPS : []),\n '@angular/common',\n '@angular/common/http',\n '@angular/core/rxjs-interop',\n ],\n ...(isRolldown()\n ? { rolldownOptions: { plugins: [angularLinkerPlugin()] } }\n : {}),\n },\n },\n optimizeDeps: {\n include: [\n '@angular/common',\n '@angular/common/http',\n '@angular/core/rxjs-interop',\n 'front-matter',\n ],\n exclude: [\n '@angular/platform-server',\n '@analogjs/content',\n '@analogjs/router',\n '@nx/angular',\n '@nx/vite',\n '@nx/devkit',\n '@nx/js',\n '@nx/devkit',\n '@nx/cypress',\n '@nx/jest',\n '@nx/js',\n '@nx/eslint',\n '@nx/webpack',\n '@nx/web',\n '@nx/workspace',\n '@nx/eslint',\n '@nx/module-federation',\n '@nx/rspack',\n 'webpack',\n 'fsevents',\n 'nx',\n ],\n },\n };\n },\n },\n {\n name: 'analogjs-auto-discover-deps',\n async config(config, { command }) {\n const pkgConfig = await crawlFrameworkPkgs({\n root: workspaceRoot,\n isBuild: command === 'build',\n viteUserConfig: config,\n isSemiFrameworkPkgByJson(pkgJson) {\n return pkgJson['module'] && pkgJson['module'].includes('fesm');\n },\n });\n return pkgConfig;\n },\n },\n ];\n}\n"],"mappings":";;;;;AAQA,IAAM,0BAA0B;CAC9B;CACA;CACA;CACA;AACF;AAEA,SAAgB,WAAW,SAA6B;CACtD,MAAM,gBACJ,SAAS,iBAAiB,QAAQ,IAAI,wBAAwB,QAAQ,IAAI;CAE5E,OAAO,CACL;EACE,MAAM;EACN,OAAO,YAAY;GAOjB,MAAM,iBAAiB,wBAAwB;GAG/C,MAAM,gBACJ,aAAa,oBAAoB,KAAA,KAChC,mBAAmB,SAAS,CAAC,CAAC,YAAY;GAC7C,cAAc,yBAAyB;IACrC;IACA,mBAAmB,CAAC;GACtB,CAAC;GAED,OAAO;IACL,GAAI,gBACA,CAAC,IACD,GAAG,iBAAiB,EAAE,SAAS,CAAC,WAAW,SAAS,EAAE,EAAE;IAC5D,KAAK;KACH,YAAY;MACV;MACA;MACA;MACA;MACA;MACA;MACA;MACA;KACF;KAOA,cAAc;MACZ,SAAS;OACP,GAAI,WAAW,IAAI,0BAA0B,CAAC;OAC9C;OACA;OACA;MACF;MACA,GAAI,WAAW,IACX,EAAE,iBAAiB,EAAE,SAAS,CAAC,oBAAoB,CAAC,EAAE,EAAE,IACxD,CAAC;KACP;IACF;IACA,cAAc;KACZ,SAAS;MACP;MACA;MACA;MACA;KACF;KACA,SAAS;MACP;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;KACF;IACF;GACF;EACF;CACF,GACA;EACE,MAAM;EACN,MAAM,OAAO,QAAQ,EAAE,WAAW;GAShC,OAAO,MARiB,mBAAmB;IACzC,MAAM;IACN,SAAS,YAAY;IACrB,gBAAgB;IAChB,yBAAyB,SAAS;KAChC,OAAO,QAAQ,aAAa,QAAQ,SAAS,CAAC,SAAS,MAAM;IAC/D;GACF,CAAC;EAEH;CACF,CACF;AACF"}
1
+ {"version":3,"file":"deps-plugin.js","names":[],"sources":["../../../src/lib/deps-plugin.ts"],"sourcesContent":["import { dirname, resolve } from 'node:path';\nimport { normalizePath, type Plugin } from 'vite';\nimport { crawlFrameworkPkgs } from 'vitefu';\n\nimport { angularLinkerPlugin } from './nitro/angular-linker-plugin.js';\nimport { Options } from './options.js';\nimport { debugPlatform } from './utils/debug.js';\nimport { getJsTransformConfigKey, isRolldown } from './utils/rolldown.js';\n\nconst ANGULAR_LINKED_SSR_DEPS = [\n '@angular/compiler',\n '@angular/core',\n '@angular/platform-browser',\n '@angular/platform-server',\n];\n\nexport function depsPlugin(options?: Options): Plugin[] {\n const workspaceRoot =\n options?.workspaceRoot ?? process.env['NX_WORKSPACE_ROOT'] ?? process.cwd();\n\n return [\n {\n name: 'analogjs-deps-plugin',\n config(userConfig) {\n // Skip Vite's built-in ts/js transform so `@analogjs/vite-plugin-angular`\n // (when the user includes it) owns Angular file compilation. Users who\n // run an alternative compiler, or compile non-Angular server code with\n // Vite, set the transform in their own Vite config. Theirs is kept\n // as-is: merging would concatenate these excludes into it, and an\n // exclude wins over any include they set.\n const jsTransformKey = getJsTransformConfigKey();\n // Vite 8 still converts a user's `esbuild` object to `oxc` (unless\n // `oxc` is set), but `esbuild: false` no longer has any effect there.\n const userTransform =\n userConfig?.[jsTransformKey] !== undefined ||\n (jsTransformKey === 'oxc' && !!userConfig?.esbuild);\n // With `server`, Vite compiles the server entry's directory instead,\n // which the Angular compiler leaves alone.\n const transform = options?.server\n ? {\n include: [\n `${normalizePath(\n resolve(\n userConfig?.root ?? process.cwd(),\n dirname(options.server.entry),\n ),\n )}/**/*.ts`,\n ],\n }\n : { exclude: ['**/*.ts', '**/*.js'] };\n debugPlatform('deps transform config', {\n jsTransformKey,\n transform: userTransform ? 'user' : transform,\n });\n\n return {\n ...(userTransform ? {} : { [jsTransformKey]: transform }),\n ssr: {\n noExternal: [\n '@analogjs/**',\n 'es-toolkit',\n 'firebase/**',\n 'firebase-admin/**',\n 'rxfire',\n '@ng-web-apis/**',\n '@taiga-ui/**',\n /^@tanstack\\/angular-/,\n ],\n // The server pre-bundle is resolved separately from the client\n // one, so a secondary entry point left out of it loads its own\n // copy of `@angular/core`. `inject()` then runs against a runtime\n // with no active injection context and SSR fails with NG0203.\n // With Rolldown, the rest of Angular is pre-bundled too and the\n // partial-compilation packages are linked, so the server needs no JIT.\n optimizeDeps: {\n include: [\n ...(isRolldown() ? ANGULAR_LINKED_SSR_DEPS : []),\n '@angular/common',\n '@angular/common/http',\n '@angular/core/rxjs-interop',\n ],\n ...(isRolldown()\n ? { rolldownOptions: { plugins: [angularLinkerPlugin()] } }\n : {}),\n },\n },\n optimizeDeps: {\n include: [\n '@angular/common',\n '@angular/common/http',\n '@angular/core/rxjs-interop',\n 'front-matter',\n ],\n exclude: [\n '@angular/platform-server',\n '@analogjs/content',\n '@analogjs/router',\n '@nx/angular',\n '@nx/vite',\n '@nx/devkit',\n '@nx/js',\n '@nx/devkit',\n '@nx/cypress',\n '@nx/jest',\n '@nx/js',\n '@nx/eslint',\n '@nx/webpack',\n '@nx/web',\n '@nx/workspace',\n '@nx/eslint',\n '@nx/module-federation',\n '@nx/rspack',\n 'webpack',\n 'fsevents',\n 'nx',\n ],\n },\n };\n },\n },\n {\n name: 'analogjs-auto-discover-deps',\n async config(config, { command }) {\n const pkgConfig = await crawlFrameworkPkgs({\n root: workspaceRoot,\n isBuild: command === 'build',\n viteUserConfig: config,\n isSemiFrameworkPkgByJson(pkgJson) {\n return pkgJson['module'] && pkgJson['module'].includes('fesm');\n },\n });\n return pkgConfig;\n },\n },\n ];\n}\n"],"mappings":";;;;;;;AASA,IAAM,0BAA0B;CAC9B;CACA;CACA;CACA;AACF;AAEA,SAAgB,WAAW,SAA6B;CACtD,MAAM,gBACJ,SAAS,iBAAiB,QAAQ,IAAI,wBAAwB,QAAQ,IAAI;CAE5E,OAAO,CACL;EACE,MAAM;EACN,OAAO,YAAY;GAOjB,MAAM,iBAAiB,wBAAwB;GAG/C,MAAM,gBACJ,aAAa,oBAAoB,KAAA,KAChC,mBAAmB,SAAS,CAAC,CAAC,YAAY;GAG7C,MAAM,YAAY,SAAS,SACvB,EACE,SAAS,CACP,GAAG,cACD,QACE,YAAY,QAAQ,QAAQ,IAAI,GAChC,QAAQ,QAAQ,OAAO,KAAK,CAC9B,CACF,EAAE,SACJ,EACF,IACA,EAAE,SAAS,CAAC,WAAW,SAAS,EAAE;GACtC,cAAc,yBAAyB;IACrC;IACA,WAAW,gBAAgB,SAAS;GACtC,CAAC;GAED,OAAO;IACL,GAAI,gBAAgB,CAAC,IAAI,GAAG,iBAAiB,UAAU;IACvD,KAAK;KACH,YAAY;MACV;MACA;MACA;MACA;MACA;MACA;MACA;MACA;KACF;KAOA,cAAc;MACZ,SAAS;OACP,GAAI,WAAW,IAAI,0BAA0B,CAAC;OAC9C;OACA;OACA;MACF;MACA,GAAI,WAAW,IACX,EAAE,iBAAiB,EAAE,SAAS,CAAC,oBAAoB,CAAC,EAAE,EAAE,IACxD,CAAC;KACP;IACF;IACA,cAAc;KACZ,SAAS;MACP;MACA;MACA;MACA;KACF;KACA,SAAS;MACP;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;KACF;IACF;GACF;EACF;CACF,GACA;EACE,MAAM;EACN,MAAM,OAAO,QAAQ,EAAE,WAAW;GAShC,OAAO,MARiB,mBAAmB;IACzC,MAAM;IACN,SAAS,YAAY;IACrB,gBAAgB;IAChB,yBAAyB,SAAS;KAChC,OAAO,QAAQ,aAAa,QAAQ,SAAS,CAAC,SAAS,MAAM;IAC/D;GACF,CAAC;EAEH;CACF,CACF;AACF"}
@@ -1,15 +1,15 @@
1
- export declare const ANALOG_JS_ROUTER = "^3.0.0-beta.19";
2
- export declare const ANALOG_JS_CONTENT = "^3.0.0-beta.19";
1
+ export declare const ANALOG_JS_ROUTER = "^3.0.0-beta.20";
2
+ export declare const ANALOG_JS_CONTENT = "^3.0.0-beta.20";
3
3
  export declare const MARKED = "^18.0.0";
4
4
  export declare const MARKED_GFM_HEADING_ID = "^4.1.1";
5
5
  export declare const MARKED_HIGHLIGHT = "^2.2.1";
6
6
  export declare const MARKED_MANGLE = "^1.1.10";
7
7
  export declare const PRISMJS = "^1.29.0";
8
8
  export declare const H3 = "^1.15.11";
9
- export declare const ANALOG_JS_PLATFORM = "^3.0.0-beta.19";
10
- export declare const ANALOG_JS_VITE_PLUGIN_ANGULAR = "^3.0.0-beta.19";
11
- export declare const ANALOG_JS_VITEST_ANGULAR = "^3.0.0-beta.19";
12
- export declare const ANALOG_JS_VITE_PLUGIN_NITRO = "^3.0.0-beta.19";
9
+ export declare const ANALOG_JS_PLATFORM = "^3.0.0-beta.20";
10
+ export declare const ANALOG_JS_VITE_PLUGIN_ANGULAR = "^3.0.0-beta.20";
11
+ export declare const ANALOG_JS_VITEST_ANGULAR = "^3.0.0-beta.20";
12
+ export declare const ANALOG_JS_VITE_PLUGIN_NITRO = "^3.0.0-beta.20";
13
13
  export declare const JSDOM = "^22.0.0";
14
14
  export declare const VITE_TSCONFIG_PATHS = "^4.2.0";
15
15
  export declare const VITE = "^8.0.0";
@@ -1,16 +1,16 @@
1
1
  //#region packages/nx-plugin/src/utils/versions/versions.ts
2
- var ANALOG_JS_ROUTER = "^3.0.0-beta.19";
3
- var ANALOG_JS_CONTENT = "^3.0.0-beta.19";
2
+ var ANALOG_JS_ROUTER = "^3.0.0-beta.20";
3
+ var ANALOG_JS_CONTENT = "^3.0.0-beta.20";
4
4
  var MARKED = "^18.0.0";
5
5
  var MARKED_GFM_HEADING_ID = "^4.1.1";
6
6
  var MARKED_HIGHLIGHT = "^2.2.1";
7
7
  var MARKED_MANGLE = "^1.1.10";
8
8
  var PRISMJS = "^1.29.0";
9
9
  var H3 = "^1.15.11";
10
- var ANALOG_JS_PLATFORM = "^3.0.0-beta.19";
11
- var ANALOG_JS_VITE_PLUGIN_ANGULAR = "^3.0.0-beta.19";
12
- var ANALOG_JS_VITEST_ANGULAR = "^3.0.0-beta.19";
13
- var ANALOG_JS_VITE_PLUGIN_NITRO = "^3.0.0-beta.19";
10
+ var ANALOG_JS_PLATFORM = "^3.0.0-beta.20";
11
+ var ANALOG_JS_VITE_PLUGIN_ANGULAR = "^3.0.0-beta.20";
12
+ var ANALOG_JS_VITEST_ANGULAR = "^3.0.0-beta.20";
13
+ var ANALOG_JS_VITE_PLUGIN_NITRO = "^3.0.0-beta.20";
14
14
  var JSDOM = "^22.0.0";
15
15
  var VITE_TSCONFIG_PATHS = "^4.2.0";
16
16
  var VITE = "^8.0.0";
@@ -1 +1 @@
1
- {"version":3,"file":"versions.js","names":[],"sources":["../../../../../../../../nx-plugin/src/utils/versions/versions.ts"],"sourcesContent":["// dependencies\nexport const ANALOG_JS_ROUTER = '^3.0.0-beta.19';\nexport const ANALOG_JS_CONTENT = '^3.0.0-beta.19';\nexport const MARKED = '^18.0.0';\nexport const MARKED_GFM_HEADING_ID = '^4.1.1';\nexport const MARKED_HIGHLIGHT = '^2.2.1';\nexport const MARKED_MANGLE = '^1.1.10';\nexport const PRISMJS = '^1.29.0';\nexport const H3 = '^1.15.11';\n\n// devDependencies\nexport const ANALOG_JS_PLATFORM = '^3.0.0-beta.19';\nexport const ANALOG_JS_VITE_PLUGIN_ANGULAR = '^3.0.0-beta.19';\nexport const ANALOG_JS_VITEST_ANGULAR = '^3.0.0-beta.19';\nexport const ANALOG_JS_VITE_PLUGIN_NITRO = '^3.0.0-beta.19';\nexport const JSDOM = '^22.0.0';\nexport const VITE_TSCONFIG_PATHS = '^4.2.0';\nexport const VITE = '^8.0.0';\nexport const VITE_7 = '^7.0.0';\nexport const VITE_6 = '^6.4.0';\nexport const VITEST = '^5.0.0';\n"],"mappings":";AACA,IAAa,mBAAmB;AAChC,IAAa,oBAAoB;AACjC,IAAa,SAAS;AACtB,IAAa,wBAAwB;AACrC,IAAa,mBAAmB;AAChC,IAAa,gBAAgB;AAC7B,IAAa,UAAU;AACvB,IAAa,KAAK;AAGlB,IAAa,qBAAqB;AAClC,IAAa,gCAAgC;AAC7C,IAAa,2BAA2B;AACxC,IAAa,8BAA8B;AAC3C,IAAa,QAAQ;AACrB,IAAa,sBAAsB;AACnC,IAAa,OAAO;AACpB,IAAa,SAAS;AACtB,IAAa,SAAS;AACtB,IAAa,SAAS"}
1
+ {"version":3,"file":"versions.js","names":[],"sources":["../../../../../../../../nx-plugin/src/utils/versions/versions.ts"],"sourcesContent":["// dependencies\nexport const ANALOG_JS_ROUTER = '^3.0.0-beta.20';\nexport const ANALOG_JS_CONTENT = '^3.0.0-beta.20';\nexport const MARKED = '^18.0.0';\nexport const MARKED_GFM_HEADING_ID = '^4.1.1';\nexport const MARKED_HIGHLIGHT = '^2.2.1';\nexport const MARKED_MANGLE = '^1.1.10';\nexport const PRISMJS = '^1.29.0';\nexport const H3 = '^1.15.11';\n\n// devDependencies\nexport const ANALOG_JS_PLATFORM = '^3.0.0-beta.20';\nexport const ANALOG_JS_VITE_PLUGIN_ANGULAR = '^3.0.0-beta.20';\nexport const ANALOG_JS_VITEST_ANGULAR = '^3.0.0-beta.20';\nexport const ANALOG_JS_VITE_PLUGIN_NITRO = '^3.0.0-beta.20';\nexport const JSDOM = '^22.0.0';\nexport const VITE_TSCONFIG_PATHS = '^4.2.0';\nexport const VITE = '^8.0.0';\nexport const VITE_7 = '^7.0.0';\nexport const VITE_6 = '^6.4.0';\nexport const VITEST = '^5.0.0';\n"],"mappings":";AACA,IAAa,mBAAmB;AAChC,IAAa,oBAAoB;AACjC,IAAa,SAAS;AACtB,IAAa,wBAAwB;AACrC,IAAa,mBAAmB;AAChC,IAAa,gBAAgB;AAC7B,IAAa,UAAU;AACvB,IAAa,KAAK;AAGlB,IAAa,qBAAqB;AAClC,IAAa,gCAAgC;AAC7C,IAAa,2BAA2B;AACxC,IAAa,8BAA8B;AAC3C,IAAa,QAAQ;AACrB,IAAa,sBAAsB;AACnC,IAAa,OAAO;AACpB,IAAa,SAAS;AACtB,IAAa,SAAS;AACtB,IAAa,SAAS"}
@@ -63,9 +63,25 @@ export interface I18nOptions {
63
63
  outFile?: string;
64
64
  };
65
65
  }
66
+ export interface ServerOptions {
67
+ /**
68
+ * The server entry, relative to the project root. It exports
69
+ * `createApp(): Promise<{ handle, close? }>`, which the dev server mounts,
70
+ * and starts its own server in production. TypeScript in the entry's
71
+ * directory is compiled by Vite.
72
+ */
73
+ entry: string;
74
+ }
66
75
  export interface Options {
67
76
  ssr?: boolean;
68
77
  /**
78
+ * Serve the app from your own server entry (NestJS, Express, Hono, …)
79
+ * instead of Nitro, using `createAnalogHandler()` or
80
+ * `createAnalogRequestHandler()` from `@analogjs/router/server`. Don't add
81
+ * `nitro()` alongside it.
82
+ */
83
+ server?: ServerOptions;
84
+ /**
69
85
  * Prerender the static pages without producing the server output.
70
86
  */
71
87
  static?: boolean;
@@ -10,6 +10,7 @@ import { deferStreamingPlugin, streamingSupportedOnAngular } from "./ssr/defer-s
10
10
  import { serverModePlugin } from "../server-mode-plugin.js";
11
11
  import { typedRoutes } from "./typed-routes-plugin.js";
12
12
  import { analogNitroPlugin } from "./nitro/analog-nitro-plugin.js";
13
+ import { serverPlugin } from "./server-plugin.js";
13
14
  import { createRequire } from "node:module";
14
15
  import { join } from "node:path";
15
16
  //#region packages/platform/src/lib/platform-plugin.ts
@@ -64,6 +65,7 @@ function platformPlugin(opts = {}) {
64
65
  api: { analogOptions: platformOptions }
65
66
  },
66
67
  ...!isTest ? [analogNitroPlugin(platformOptions)] : [],
68
+ ...platformOptions.server && !isTest ? [serverPlugin(platformOptions.server, platformOptions)] : [],
67
69
  ...platformOptions.ssr ? [...ssrBuildPlugin(), ...injectHTMLPlugin()] : [],
68
70
  ...platformOptions.ssr && platformOptions.experimental?.streaming ? [deferStreamingPlugin()] : [],
69
71
  ...!isTest ? depsPlugin(platformOptions) : [],
@@ -1 +1 @@
1
- {"version":3,"file":"platform-plugin.js","names":[],"sources":["../../../src/lib/platform-plugin.ts"],"sourcesContent":["import { createRequire } from 'node:module';\nimport { join } from 'node:path';\nimport { Plugin } from 'vite';\n\nimport { Options } from './options.js';\nimport {\n activateDeferredDebug,\n applyDebugOption,\n debugPlatform,\n} from './utils/debug.js';\nimport { routerPlugin } from './router-plugin.js';\nimport { analogIntegrationPlugin } from './analog-integration-plugin.js';\nimport {\n i18nDefRegistryPlugin,\n ssrBuildPlugin,\n} from './ssr/ssr-build-plugin.js';\nimport { contentPlugin } from './content-plugin.js';\nimport { clearClientPageEndpointsPlugin } from './clear-client-page-endpoint.js';\nimport { depsPlugin } from './deps-plugin.js';\nimport { injectHTMLPlugin } from './ssr/inject-html-plugin.js';\nimport {\n deferStreamingPlugin,\n MIN_STREAMING_ANGULAR_MAJOR,\n streamingSupportedOnAngular,\n} from './ssr/defer-streaming-plugin.js';\nimport { serverModePlugin } from '../server-mode-plugin.js';\nimport { typedRoutes } from './typed-routes-plugin.js';\nimport { analogNitroPlugin } from './nitro/analog-nitro-plugin.js';\n\n/**\n * The installed `@angular/core` major version, resolved from the workspace root\n * (where the app's Angular is installed). Returns `null` when it cannot be\n * detected, in which case streaming is not blocked and the build-time\n * anchor-drift detection is relied on instead.\n */\nfunction getAngularCoreMajor(workspaceRoot: string): number | null {\n try {\n const req = createRequire(join(workspaceRoot, 'noop.js'));\n const { version } = req('@angular/core/package.json') as {\n version: string;\n };\n const major = Number.parseInt(version.split('.')[0], 10);\n return Number.isNaN(major) ? null : major;\n } catch {\n return null;\n }\n}\n\nexport function platformPlugin(opts: Options = {}): Plugin[] {\n applyDebugOption(opts.debug, opts.workspaceRoot);\n\n const isTest = process.env['NODE_ENV'] === 'test' || !!process.env['VITEST'];\n const { ...platformOptions } = {\n ssr: true,\n ...opts,\n };\n\n // Streaming patches the compiled @angular/core, which needs a supported\n // Angular version. Turn it off otherwise so the renderer stays buffered.\n if (platformOptions.ssr && platformOptions.experimental?.streaming) {\n const major = getAngularCoreMajor(\n platformOptions.workspaceRoot ?? process.cwd(),\n );\n if (!streamingSupportedOnAngular(major)) {\n console.warn(\n `[@analogjs/platform] experimental.streaming requires Angular ` +\n `${MIN_STREAMING_ANGULAR_MAJOR}+ (detected v${major}); streaming is ` +\n `disabled and rendering falls back to buffered SSR.`,\n );\n platformOptions.experimental = {\n ...platformOptions.experimental,\n streaming: false,\n };\n }\n }\n\n debugPlatform('experimental options resolved', {\n typedRouting: platformOptions.experimental?.typedRouting,\n });\n\n return [\n ...(platformOptions.experimental?.typedRouting\n ? [\n typedRoutes({\n ...(typeof platformOptions.experimental.typedRouting === 'object'\n ? platformOptions.experimental.typedRouting\n : {}),\n workspaceRoot: platformOptions.workspaceRoot,\n additionalPagesDirs: platformOptions.additionalPagesDirs,\n additionalContentDirs: platformOptions.additionalContentDirs,\n }),\n ]\n : []),\n {\n name: 'analogjs-debug-activate',\n config(_, { command }) {\n activateDeferredDebug(command);\n },\n },\n // `nitro()` from `@analogjs/vite-plugin-nitro` reads these as its defaults.\n {\n name: '@analogjs/platform-options',\n api: { analogOptions: platformOptions },\n },\n ...(!isTest ? [analogNitroPlugin(platformOptions)] : []),\n ...(platformOptions.ssr\n ? [...ssrBuildPlugin(), ...injectHTMLPlugin()]\n : []),\n ...(platformOptions.ssr && platformOptions.experimental?.streaming\n ? [deferStreamingPlugin()]\n : []),\n ...(!isTest ? depsPlugin(platformOptions) : []),\n ...routerPlugin(platformOptions),\n analogIntegrationPlugin(platformOptions),\n ...contentPlugin(platformOptions?.content, platformOptions),\n ...(platformOptions.i18n ? [i18nDefRegistryPlugin()] : []),\n ...serverModePlugin(platformOptions.entryServer),\n clearClientPageEndpointsPlugin(),\n ];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAmCA,SAAS,oBAAoB,eAAsC;CACjE,IAAI;EAEF,MAAM,EAAE,YADI,cAAc,KAAK,eAAe,SAAS,CACnC,CAAA,CAAI,4BAA4B;EAGpD,MAAM,QAAQ,OAAO,SAAS,QAAQ,MAAM,GAAG,CAAC,CAAC,IAAI,EAAE;EACvD,OAAO,OAAO,MAAM,KAAK,IAAI,OAAO;CACtC,QAAQ;EACN,OAAO;CACT;AACF;AAEA,SAAgB,eAAe,OAAgB,CAAC,GAAa;CAC3D,iBAAiB,KAAK,OAAO,KAAK,aAAa;CAE/C,MAAM,SAAA,QAAA,IAAA,aAAqC,UAAU,CAAC,CAAC,QAAQ,IAAI;CACnE,MAAM,EAAE,GAAG,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/platform-plugin.ts"],"sourcesContent":["import { createRequire } from 'node:module';\nimport { join } from 'node:path';\nimport { Plugin } from 'vite';\n\nimport { Options } from './options.js';\nimport {\n activateDeferredDebug,\n applyDebugOption,\n debugPlatform,\n} from './utils/debug.js';\nimport { routerPlugin } from './router-plugin.js';\nimport { analogIntegrationPlugin } from './analog-integration-plugin.js';\nimport {\n i18nDefRegistryPlugin,\n ssrBuildPlugin,\n} from './ssr/ssr-build-plugin.js';\nimport { contentPlugin } from './content-plugin.js';\nimport { clearClientPageEndpointsPlugin } from './clear-client-page-endpoint.js';\nimport { depsPlugin } from './deps-plugin.js';\nimport { injectHTMLPlugin } from './ssr/inject-html-plugin.js';\nimport {\n deferStreamingPlugin,\n MIN_STREAMING_ANGULAR_MAJOR,\n streamingSupportedOnAngular,\n} from './ssr/defer-streaming-plugin.js';\nimport { serverModePlugin } from '../server-mode-plugin.js';\nimport { typedRoutes } from './typed-routes-plugin.js';\nimport { analogNitroPlugin } from './nitro/analog-nitro-plugin.js';\nimport { serverPlugin } from './server-plugin.js';\n\n/**\n * The installed `@angular/core` major version, resolved from the workspace root\n * (where the app's Angular is installed). Returns `null` when it cannot be\n * detected, in which case streaming is not blocked and the build-time\n * anchor-drift detection is relied on instead.\n */\nfunction getAngularCoreMajor(workspaceRoot: string): number | null {\n try {\n const req = createRequire(join(workspaceRoot, 'noop.js'));\n const { version } = req('@angular/core/package.json') as {\n version: string;\n };\n const major = Number.parseInt(version.split('.')[0], 10);\n return Number.isNaN(major) ? null : major;\n } catch {\n return null;\n }\n}\n\nexport function platformPlugin(opts: Options = {}): Plugin[] {\n applyDebugOption(opts.debug, opts.workspaceRoot);\n\n const isTest = process.env['NODE_ENV'] === 'test' || !!process.env['VITEST'];\n const { ...platformOptions } = {\n ssr: true,\n ...opts,\n };\n\n // Streaming patches the compiled @angular/core, which needs a supported\n // Angular version. Turn it off otherwise so the renderer stays buffered.\n if (platformOptions.ssr && platformOptions.experimental?.streaming) {\n const major = getAngularCoreMajor(\n platformOptions.workspaceRoot ?? process.cwd(),\n );\n if (!streamingSupportedOnAngular(major)) {\n console.warn(\n `[@analogjs/platform] experimental.streaming requires Angular ` +\n `${MIN_STREAMING_ANGULAR_MAJOR}+ (detected v${major}); streaming is ` +\n `disabled and rendering falls back to buffered SSR.`,\n );\n platformOptions.experimental = {\n ...platformOptions.experimental,\n streaming: false,\n };\n }\n }\n\n debugPlatform('experimental options resolved', {\n typedRouting: platformOptions.experimental?.typedRouting,\n });\n\n return [\n ...(platformOptions.experimental?.typedRouting\n ? [\n typedRoutes({\n ...(typeof platformOptions.experimental.typedRouting === 'object'\n ? platformOptions.experimental.typedRouting\n : {}),\n workspaceRoot: platformOptions.workspaceRoot,\n additionalPagesDirs: platformOptions.additionalPagesDirs,\n additionalContentDirs: platformOptions.additionalContentDirs,\n }),\n ]\n : []),\n {\n name: 'analogjs-debug-activate',\n config(_, { command }) {\n activateDeferredDebug(command);\n },\n },\n // `nitro()` from `@analogjs/vite-plugin-nitro` reads these as its defaults.\n {\n name: '@analogjs/platform-options',\n api: { analogOptions: platformOptions },\n },\n ...(!isTest ? [analogNitroPlugin(platformOptions)] : []),\n ...(platformOptions.server && !isTest\n ? [serverPlugin(platformOptions.server, platformOptions)]\n : []),\n ...(platformOptions.ssr\n ? [...ssrBuildPlugin(), ...injectHTMLPlugin()]\n : []),\n ...(platformOptions.ssr && platformOptions.experimental?.streaming\n ? [deferStreamingPlugin()]\n : []),\n ...(!isTest ? depsPlugin(platformOptions) : []),\n ...routerPlugin(platformOptions),\n analogIntegrationPlugin(platformOptions),\n ...contentPlugin(platformOptions?.content, platformOptions),\n ...(platformOptions.i18n ? [i18nDefRegistryPlugin()] : []),\n ...serverModePlugin(platformOptions.entryServer),\n clearClientPageEndpointsPlugin(),\n ];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAoCA,SAAS,oBAAoB,eAAsC;CACjE,IAAI;EAEF,MAAM,EAAE,YADI,cAAc,KAAK,eAAe,SAAS,CAC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AAC,GAAG,eAAe,GAAG,GAAG,iBAAiB,CAAC,IAC3C,CAAC;EACL,GAAI,gBAAgB,OAAO,gBAAgB,cAAc,YACrD,CAAC,qBAAqB,CAAC,IACvB,CAAC;EACL,GAAI,CAAC,SAAS,WAAW,eAAe,IAAI,CAAC;EAC7C,GAAG,aAAa,eAAe;EAC/B,wBAAwB,eAAe;EACvC,GAAG,cAAc,iBAAiB,SAAS,eAAe;EAC1D,GAAI,gBAAgB,OAAO,CAAC,sBAAsB,CAAC,IAAI,CAAC;EACxD,GAAG,iBAAiB,gBAAgB,WAAW;EAC/C,+BAA+B;CACjC;AACF"}
@@ -0,0 +1,9 @@
1
+ import { type Plugin } from "vite";
2
+ import type { Options, ServerOptions } from "./options.js";
3
+ /**
4
+ * Builds and serves the app from `server.entry` instead of Nitro: the client
5
+ * and one server bundle in `vite build`, and the entry's app behind Vite's
6
+ * own middleware in dev. Fills in the `ANALOG_SERVER_MANIFEST` placeholder
7
+ * that `createAnalogRequestHandler()` in `@analogjs/router/server` reads.
8
+ */
9
+ export declare function serverPlugin(server: ServerOptions, options?: Options): Plugin;
@@ -0,0 +1,154 @@
1
+ import { getPageEndpoints } from "./get-page-endpoints.js";
2
+ import { getServerFnHandlers } from "./nitro/get-server-fn-handlers.js";
3
+ import { relative, resolve } from "node:path";
4
+ import { existsSync, readFileSync } from "node:fs";
5
+ import { normalizePath } from "vite";
6
+ //#region packages/platform/src/lib/server-plugin.ts
7
+ var MANIFEST_PLACEHOLDER = /ANALOG_SERVER_MANIFEST = \{\}/;
8
+ var DEV_TEMPLATE = Symbol.for("@analogjs/platform/dev-template");
9
+ var HTML_MIDDLEWARES = [
10
+ "viteIndexHtmlMiddleware",
11
+ "vite404Middleware",
12
+ "viteSpaFallbackMiddleware",
13
+ "viteHtmlFallbackMiddleware"
14
+ ];
15
+ var NITRO_PLUGINS = ["nitro:main", "@analogjs/vite-plugin-nitro"];
16
+ /**
17
+ * Builds and serves the app from `server.entry` instead of Nitro: the client
18
+ * and one server bundle in `vite build`, and the entry's app behind Vite's
19
+ * own middleware in dev. Fills in the `ANALOG_SERVER_MANIFEST` placeholder
20
+ * that `createAnalogRequestHandler()` in `@analogjs/router/server` reads.
21
+ */
22
+ function serverPlugin(server, options = {}) {
23
+ const workspaceRoot = options.workspaceRoot ?? process.env["NX_WORKSPACE_ROOT"] ?? process.cwd();
24
+ const apiPrefix = options.apiPrefix ?? "api";
25
+ let root = process.cwd();
26
+ let isBuild = false;
27
+ let builtTemplate;
28
+ let manifestId;
29
+ const rootDir = () => relative(workspaceRoot, root) || ".";
30
+ const indexHtml = () => resolve(root, options.index ?? "index.html");
31
+ return {
32
+ name: "@analogjs/platform-server",
33
+ config(config, { command }) {
34
+ if ((config.plugins ?? []).flat(Infinity).some((p) => NITRO_PLUGINS.includes(p?.name ?? ""))) throw new Error("[@analogjs/platform] `analog({ server })` replaces Nitro; remove `nitro()` from the Vite plugins.");
35
+ root = normalizePath(resolve(config.root ?? process.cwd()));
36
+ isBuild = command === "build";
37
+ const outDir = (name) => resolve(workspaceRoot, "dist", rootDir(), name);
38
+ return {
39
+ environments: {
40
+ client: { build: {
41
+ outDir: outDir("client"),
42
+ rollupOptions: { input: indexHtml() }
43
+ } },
44
+ ssr: { build: {
45
+ outDir: outDir("server"),
46
+ copyPublicDir: false,
47
+ rollupOptions: { input: { main: resolve(root, server.entry) } }
48
+ } }
49
+ },
50
+ builder: {
51
+ sharedPlugins: true,
52
+ async buildApp(builder) {
53
+ await builder.build(builder.environments["client"]);
54
+ await builder.build(builder.environments["ssr"]);
55
+ }
56
+ }
57
+ };
58
+ },
59
+ writeBundle(_options, bundle) {
60
+ if (this.environment.name === "client") {
61
+ const document = bundle[normalizePath(relative(root, indexHtml()))];
62
+ if (document?.type === "asset") builtTemplate = String(document.source);
63
+ }
64
+ },
65
+ transform: {
66
+ filter: { code: "ANALOG_SERVER_MANIFEST" },
67
+ handler(code, id) {
68
+ if (!MANIFEST_PLACEHOLDER.test(code)) return;
69
+ manifestId = id;
70
+ return code.replace(MANIFEST_PLACEHOLDER, `ANALOG_SERVER_MANIFEST = ${serverManifest()}`);
71
+ }
72
+ },
73
+ configureServer(viteServer) {
74
+ globalThis[DEV_TEMPLATE] = (url) => viteServer.transformIndexHtml(url, readFileSync(indexHtml(), "utf-8"));
75
+ const invalidateManifest = (file) => {
76
+ const graph = viteServer.environments["ssr"].moduleGraph;
77
+ const mod = manifestId && graph.getModuleById(manifestId);
78
+ if (file.endsWith(".server.ts") && mod) graph.invalidateModule(mod);
79
+ };
80
+ viteServer.watcher.on("add", invalidateManifest);
81
+ viteServer.watcher.on("unlink", invalidateManifest);
82
+ return () => {
83
+ removeHtmlMiddlewares(viteServer.middlewares);
84
+ viteServer.middlewares.use(devMiddleware(viteServer, resolve(root, server.entry)));
85
+ };
86
+ }
87
+ };
88
+ function requireBuiltTemplate() {
89
+ if (builtTemplate === void 0) throw new Error(`[@analogjs/platform] The client build didn't emit ${relative(root, indexHtml())}, which the server renders around.`);
90
+ return builtTemplate;
91
+ }
92
+ /**
93
+ * The manifest object literal: the template, and lazy imports of the SSR
94
+ * renderer, the server config, every server function module, and page
95
+ * endpoints keyed by route.
96
+ */
97
+ function serverManifest() {
98
+ const src = `${root}/src`;
99
+ const lazy = (file) => `() => import(${JSON.stringify(file)})`;
100
+ const appConfig = [`${src}/app/app.config.server.ts`, `${src}/app.config.server.ts`].find((file) => existsSync(file));
101
+ const discovery = {
102
+ workspaceRoot,
103
+ sourceRoot: "src",
104
+ rootDir: rootDir()
105
+ };
106
+ const pageEndpoints = getPageEndpoints({
107
+ ...discovery,
108
+ additionalPagesDirs: options.additionalPagesDirs
109
+ }).map(({ file, route }) => `${JSON.stringify(`/${apiPrefix}/_analog${route}`)}: ${lazy(normalizePath(file))}`);
110
+ const serverFnModules = getServerFnHandlers(discovery).map(({ file }) => lazy(file));
111
+ const template = isBuild ? `async () => ${JSON.stringify(requireBuiltTemplate())}` : `(url) => globalThis[Symbol.for('@analogjs/platform/dev-template')](url)`;
112
+ return `{
113
+ apiPrefix: ${JSON.stringify(apiPrefix)},
114
+ template: ${template},
115
+ render: () => import(${JSON.stringify(normalizePath(options.entryServer ?? `${src}/main.server.ts`))}).then((m) => m.default),
116
+ config: ${appConfig ? `() => import(${JSON.stringify(appConfig)}).then((m) => m.config)` : `async () => ({ providers: [] })`},
117
+ serverFnModules: [${serverFnModules.join(", ")}],
118
+ pageEndpoints: {${pageEndpoints.join(", ")}},
119
+ }`;
120
+ }
121
+ }
122
+ /**
123
+ * Hands every request Vite doesn't serve to the entry's app. The app is
124
+ * recreated when the server module graph changes (ssrLoadModule returns a new
125
+ * module) and the previous one is closed.
126
+ */
127
+ function devMiddleware(viteServer, entry) {
128
+ let current;
129
+ async function getApp() {
130
+ const loaded = await viteServer.ssrLoadModule(entry);
131
+ if (current?.entry !== loaded) {
132
+ const previous = current;
133
+ current = {
134
+ entry: loaded,
135
+ app: loaded.createApp()
136
+ };
137
+ previous?.app.then((app) => app.close?.(), () => void 0);
138
+ }
139
+ return current.app;
140
+ }
141
+ return (req, res, next) => {
142
+ getApp().then((app) => app.handle(req, res, next)).catch((error) => {
143
+ viteServer.ssrFixStacktrace(error);
144
+ next(error);
145
+ });
146
+ };
147
+ }
148
+ function removeHtmlMiddlewares(middlewares) {
149
+ middlewares.stack = middlewares.stack.filter((layer) => !HTML_MIDDLEWARES.includes(layer.handle.name ?? ""));
150
+ }
151
+ //#endregion
152
+ export { serverPlugin };
153
+
154
+ //# sourceMappingURL=server-plugin.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server-plugin.js","names":[],"sources":["../../../src/lib/server-plugin.ts"],"sourcesContent":["import { existsSync, readFileSync } from 'node:fs';\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport { relative, resolve } from 'node:path';\nimport {\n normalizePath,\n type Connect,\n type Plugin,\n type ViteDevServer,\n} from 'vite';\n\nimport { getPageEndpoints } from './get-page-endpoints.js';\nimport { getServerFnHandlers } from './nitro/get-server-fn-handlers.js';\nimport type { Options, ServerOptions } from './options.js';\n\nconst MANIFEST_PLACEHOLDER = /ANALOG_SERVER_MANIFEST = \\{\\}/;\nconst DEV_TEMPLATE = Symbol.for('@analogjs/platform/dev-template');\nconst HTML_MIDDLEWARES = [\n 'viteIndexHtmlMiddleware',\n 'vite404Middleware',\n 'viteSpaFallbackMiddleware',\n 'viteHtmlFallbackMiddleware',\n];\nconst NITRO_PLUGINS = ['nitro:main', '@analogjs/vite-plugin-nitro'];\n\ntype ServerApp = {\n handle: (\n req: IncomingMessage,\n res: ServerResponse,\n next: (error?: unknown) => void,\n ) => void;\n close?: () => Promise<void>;\n};\ntype ServerEntry = { createApp: () => Promise<ServerApp> };\n\n/**\n * Builds and serves the app from `server.entry` instead of Nitro: the client\n * and one server bundle in `vite build`, and the entry's app behind Vite's\n * own middleware in dev. Fills in the `ANALOG_SERVER_MANIFEST` placeholder\n * that `createAnalogRequestHandler()` in `@analogjs/router/server` reads.\n */\nexport function serverPlugin(\n server: ServerOptions,\n options: Options = {},\n): Plugin {\n const workspaceRoot =\n options.workspaceRoot ?? process.env['NX_WORKSPACE_ROOT'] ?? process.cwd();\n const apiPrefix = options.apiPrefix ?? 'api';\n let root = process.cwd();\n let isBuild = false;\n let builtTemplate: string | undefined;\n let manifestId: string | undefined;\n\n const rootDir = () => relative(workspaceRoot, root) || '.';\n const indexHtml = () => resolve(root, options.index ?? 'index.html');\n\n return {\n name: '@analogjs/platform-server',\n config(config, { command }) {\n const plugins = ((config.plugins ?? []) as unknown[]).flat(Infinity) as (\n | { name?: string }\n | null\n | undefined\n )[];\n if (plugins.some((p) => NITRO_PLUGINS.includes(p?.name ?? ''))) {\n throw new Error(\n '[@analogjs/platform] `analog({ server })` replaces Nitro; remove `nitro()` from the Vite plugins.',\n );\n }\n root = normalizePath(resolve(config.root ?? process.cwd()));\n isBuild = command === 'build';\n const outDir = (name: string) =>\n resolve(workspaceRoot, 'dist', rootDir(), name);\n return {\n environments: {\n client: {\n build: {\n outDir: outDir('client'),\n rollupOptions: { input: indexHtml() },\n },\n },\n ssr: {\n build: {\n outDir: outDir('server'),\n copyPublicDir: false,\n rollupOptions: { input: { main: resolve(root, server.entry) } },\n },\n },\n },\n builder: {\n // One plugin instance for both builds, so the server build sees\n // the document captured from the client build.\n sharedPlugins: true,\n async buildApp(builder) {\n await builder.build(builder.environments['client']);\n await builder.build(builder.environments['ssr']);\n },\n },\n };\n },\n // The server bundle renders around the built document, so take it from\n // the client build's own output.\n writeBundle(_options, bundle) {\n if (this.environment.name === 'client') {\n const document = bundle[normalizePath(relative(root, indexHtml()))];\n if (document?.type === 'asset') {\n builtTemplate = String(document.source);\n }\n }\n },\n transform: {\n filter: { code: 'ANALOG_SERVER_MANIFEST' },\n handler(code, id) {\n if (!MANIFEST_PLACEHOLDER.test(code)) {\n return undefined;\n }\n manifestId = id;\n return code.replace(\n MANIFEST_PLACEHOLDER,\n `ANALOG_SERVER_MANIFEST = ${serverManifest()}`,\n );\n },\n },\n configureServer(viteServer) {\n (globalThis as Record<symbol, unknown>)[DEV_TEMPLATE] = (url: string) =>\n viteServer.transformIndexHtml(url, readFileSync(indexHtml(), 'utf-8'));\n\n // New or removed page endpoints and server functions change the manifest.\n const invalidateManifest = (file: string) => {\n const graph = viteServer.environments['ssr'].moduleGraph;\n const mod = manifestId && graph.getModuleById(manifestId);\n if (file.endsWith('.server.ts') && mod) {\n graph.invalidateModule(mod);\n }\n };\n viteServer.watcher.on('add', invalidateManifest);\n viteServer.watcher.on('unlink', invalidateManifest);\n\n return () => {\n removeHtmlMiddlewares(viteServer.middlewares);\n viteServer.middlewares.use(\n devMiddleware(viteServer, resolve(root, server.entry)),\n );\n };\n },\n };\n\n function requireBuiltTemplate(): string {\n if (builtTemplate === undefined) {\n throw new Error(\n `[@analogjs/platform] The client build didn't emit ${relative(root, indexHtml())}, which the server renders around.`,\n );\n }\n return builtTemplate;\n }\n\n /**\n * The manifest object literal: the template, and lazy imports of the SSR\n * renderer, the server config, every server function module, and page\n * endpoints keyed by route.\n */\n function serverManifest(): string {\n const src = `${root}/src`;\n const lazy = (file: string) => `() => import(${JSON.stringify(file)})`;\n const appConfig = [\n `${src}/app/app.config.server.ts`,\n `${src}/app.config.server.ts`,\n ].find((file) => existsSync(file));\n const discovery = {\n workspaceRoot,\n sourceRoot: 'src',\n rootDir: rootDir(),\n };\n const pageEndpoints = getPageEndpoints({\n ...discovery,\n additionalPagesDirs: options.additionalPagesDirs,\n }).map(\n ({ file, route }) =>\n `${JSON.stringify(`/${apiPrefix}/_analog${route}`)}: ${lazy(normalizePath(file))}`,\n );\n const serverFnModules = getServerFnHandlers(discovery).map(({ file }) =>\n lazy(file),\n );\n const template = isBuild\n ? `async () => ${JSON.stringify(requireBuiltTemplate())}`\n : `(url) => globalThis[Symbol.for('@analogjs/platform/dev-template')](url)`;\n\n return `{\n apiPrefix: ${JSON.stringify(apiPrefix)},\n template: ${template},\n render: () => import(${JSON.stringify(normalizePath(options.entryServer ?? `${src}/main.server.ts`))}).then((m) => m.default),\n config: ${\n appConfig\n ? `() => import(${JSON.stringify(appConfig)}).then((m) => m.config)`\n : `async () => ({ providers: [] })`\n },\n serverFnModules: [${serverFnModules.join(', ')}],\n pageEndpoints: {${pageEndpoints.join(', ')}},\n}`;\n }\n}\n\n/**\n * Hands every request Vite doesn't serve to the entry's app. The app is\n * recreated when the server module graph changes (ssrLoadModule returns a new\n * module) and the previous one is closed.\n */\nfunction devMiddleware(\n viteServer: ViteDevServer,\n entry: string,\n): Connect.NextHandleFunction {\n let current: { entry: ServerEntry; app: Promise<ServerApp> } | undefined;\n\n async function getApp(): Promise<ServerApp> {\n const loaded = (await viteServer.ssrLoadModule(entry)) as ServerEntry;\n if (current?.entry !== loaded) {\n const previous = current;\n current = { entry: loaded, app: loaded.createApp() };\n void previous?.app.then(\n (app) => app.close?.(),\n () => undefined,\n );\n }\n return current.app;\n }\n\n return (req, res, next) => {\n getApp()\n .then((app) => app.handle(req, res, next))\n .catch((error: Error) => {\n viteServer.ssrFixStacktrace(error);\n next(error);\n });\n };\n}\n\nfunction removeHtmlMiddlewares(middlewares: Connect.Server): void {\n middlewares.stack = middlewares.stack.filter(\n (layer) =>\n !HTML_MIDDLEWARES.includes(\n (layer.handle as { name?: string }).name ?? '',\n ),\n );\n}\n"],"mappings":";;;;;;AAcA,IAAM,uBAAuB;AAC7B,IAAM,eAAe,OAAO,IAAI,iCAAiC;AACjE,IAAM,mBAAmB;CACvB;CACA;CACA;CACA;AACF;AACA,IAAM,gBAAgB,CAAC,cAAc,6BAA6B;;;;;;;AAkBlE,SAAgB,aACd,QACA,UAAmB,CAAC,GACZ;CACR,MAAM,gBACJ,QAAQ,iBAAiB,QAAQ,IAAI,wBAAwB,QAAQ,IAAI;CAC3E,MAAM,YAAY,QAAQ,aAAa;CACvC,IAAI,OAAO,QAAQ,IAAI;CACvB,IAAI,UAAU;CACd,IAAI;CACJ,IAAI;CAEJ,MAAM,gBAAgB,SAAS,eAAe,IAAI,KAAK;CACvD,MAAM,kBAAkB,QAAQ,MAAM,QAAQ,SAAS,YAAY;CAEnE,OAAO;EACL,MAAM;EACN,OAAO,QAAQ,EAAE,WAAW;GAM1B,KALkB,OAAO,WAAW,CAAC,EAAA,CAAiB,KAAK,QAKvD,CAAA,CAAQ,MAAM,MAAM,cAAc,SAAS,GAAG,QAAQ,EAAE,CAAC,GAC3D,MAAM,IAAI,MACR,mGACF;GAEF,OAAO,cAAc,QAAQ,OAAO,QAAQ,QAAQ,IAAI,CAAC,CAAC;GAC1D,UAAU,YAAY;GACtB,MAAM,UAAU,SACd,QAAQ,eAAe,QAAQ,QAAQ,GAAG,IAAI;GAChD,OAAO;IACL,cAAc;KACZ,QAAQ,EACN,OAAO;MACL,QAAQ,OAAO,QAAQ;MACvB,eAAe,EAAE,OAAO,UAAU,EAAE;KACtC,EACF;KACA,KAAK,EACH,OAAO;MACL,QAAQ,OAAO,QAAQ;MACvB,eAAe;MACf,eAAe,EAAE,OAAO,EAAE,MAAM,QAAQ,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