@bleedingdev/modern-js-server-core 3.9.0-ultramodern.1 → 3.9.0-ultramodern.11

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 (51) hide show
  1. package/dist/cjs/adapters/node/index.js +4 -0
  2. package/dist/cjs/adapters/node/plugins/static.js +107 -29
  3. package/dist/cjs/index.js +10 -34
  4. package/dist/cjs/plugins/compat/index.js +1 -0
  5. package/dist/cjs/plugins/render/ssrCache.js +51 -29
  6. package/dist/cjs/serverBase.js +58 -17
  7. package/dist/cjs/utils/error.js +0 -10
  8. package/dist/esm/adapters/node/index.mjs +1 -0
  9. package/dist/esm/adapters/node/plugins/static.mjs +107 -32
  10. package/dist/esm/index.mjs +1 -1
  11. package/dist/esm/plugins/compat/index.mjs +1 -0
  12. package/dist/esm/plugins/render/ssrCache.mjs +51 -29
  13. package/dist/esm/serverBase.mjs +58 -17
  14. package/dist/esm/utils/error.mjs +0 -1
  15. package/dist/esm-node/adapters/node/index.mjs +1 -0
  16. package/dist/esm-node/adapters/node/plugins/static.mjs +107 -32
  17. package/dist/esm-node/index.mjs +1 -1
  18. package/dist/esm-node/plugins/compat/index.mjs +1 -0
  19. package/dist/esm-node/plugins/render/ssrCache.mjs +51 -29
  20. package/dist/esm-node/serverBase.mjs +58 -17
  21. package/dist/esm-node/utils/error.mjs +0 -1
  22. package/dist/types/adapters/node/index.d.ts +2 -0
  23. package/dist/types/adapters/node/plugins/static.d.ts +42 -4
  24. package/dist/types/index.d.ts +1 -2
  25. package/dist/types/serverBase.d.ts +7 -1
  26. package/dist/types/types/config/bff.d.ts +4 -15
  27. package/dist/types/types/config/server.d.ts +1 -3
  28. package/dist/types/types/plugins/plugin.d.ts +15 -1
  29. package/dist/types/types/requestHandler.d.ts +2 -3
  30. package/dist/types/utils/error.d.ts +0 -2
  31. package/package.json +7 -8
  32. package/dist/cjs/adapters/node/plugins/staticModuleFederation.js +0 -173
  33. package/dist/cjs/adapters/node/plugins/staticPrecompressed.js +0 -152
  34. package/dist/cjs/adapters/node/plugins/staticServing.js +0 -206
  35. package/dist/cjs/types/config/bffRuntime.js +0 -18
  36. package/dist/cjs/types/config/serverTelemetry.js +0 -18
  37. package/dist/esm/adapters/node/plugins/staticModuleFederation.mjs +0 -104
  38. package/dist/esm/adapters/node/plugins/staticPrecompressed.mjs +0 -111
  39. package/dist/esm/adapters/node/plugins/staticServing.mjs +0 -152
  40. package/dist/esm/types/config/bffRuntime.mjs +0 -0
  41. package/dist/esm/types/config/serverTelemetry.mjs +0 -0
  42. package/dist/esm-node/adapters/node/plugins/staticModuleFederation.mjs +0 -105
  43. package/dist/esm-node/adapters/node/plugins/staticPrecompressed.mjs +0 -112
  44. package/dist/esm-node/adapters/node/plugins/staticServing.mjs +0 -153
  45. package/dist/esm-node/types/config/bffRuntime.mjs +0 -1
  46. package/dist/esm-node/types/config/serverTelemetry.mjs +0 -1
  47. package/dist/types/adapters/node/plugins/staticModuleFederation.d.ts +0 -13
  48. package/dist/types/adapters/node/plugins/staticPrecompressed.d.ts +0 -13
  49. package/dist/types/adapters/node/plugins/staticServing.d.ts +0 -25
  50. package/dist/types/types/config/bffRuntime.d.ts +0 -116
  51. package/dist/types/types/config/serverTelemetry.d.ts +0 -319
@@ -9,5 +9,5 @@ export { AGGRED_DIR } from "./constants.mjs";
9
9
  export { run, useHonoContext } from "./context.mjs";
10
10
  export { getLoaderCtx } from "./helper.mjs";
11
11
  export { createServerBase } from "./serverBase.mjs";
12
- export { ErrorDigest, createErrorHtml, createSafeFailureHttpResult, createSafeJsonFailureResponse, getSafeFailureStatus, onError } from "./utils/index.mjs";
12
+ export { ErrorDigest, createErrorHtml, onError } from "./utils/index.mjs";
13
13
  export { getPublicDirConfig, getPublicDirPatterns, getPublicDirRoutePrefixes, normalizePublicDir, normalizePublicDirPath, resolvePublicDirPaths } from "./utils/publicDir.mjs";
@@ -4,6 +4,7 @@ import { getHookRunners, handleSetupResult } from "./hooks.mjs";
4
4
  const compatPlugin = ()=>({
5
5
  name: '@modern-js/server-compat',
6
6
  registryHooks: {
7
+ handleError: createAsyncPipelineHook(),
7
8
  prepareWebServer: createAsyncPipelineHook(),
8
9
  prepareApiServer: createAsyncPipelineHook(),
9
10
  afterMatch: createAsyncPipelineHook(),
@@ -2,54 +2,67 @@ import "node:module";
2
2
  import { createMemoryStorage } from "@modern-js/runtime-utils/storer";
3
3
  import { X_RENDER_CACHE } from "../../constants.mjs";
4
4
  import { createTransformStream, getPathname } from "../../utils/index.mjs";
5
+ const preventsSharedCaching = (headers)=>/(?:^|,)\s*(?:private|no-store|no-cache)\s*(?:[=,]|$)/i.test(headers.get('cache-control') || '');
6
+ const isCacheableResponse = (response)=>200 === response.status && !preventsSharedCaching(response.headers) && !response.headers.has('set-cookie') && !response.headers.get('vary');
5
7
  const removeTailSlash = (s)=>s.replace(/\/+$/, '');
6
8
  const ZERO_RENDER_LEVEL = /"renderLevel":0/;
7
9
  const NO_SSR_CACHE = /<meta\s+[^>]*name=["']no-ssr-cache["'][^>]*>/i;
8
10
  async function processCache({ request, key, requestHandler, requestHandlerOptions, ttl, container, cacheStatus }) {
9
11
  const response = await requestHandler(request, requestHandlerOptions);
10
12
  const { onError } = requestHandlerOptions;
11
- const nonCacheableStatusCodes = [
12
- 204,
13
- 305,
14
- 404,
15
- 405,
16
- 500,
17
- 501,
18
- 502,
19
- 503,
20
- 504
21
- ];
22
- if (nonCacheableStatusCodes.includes(response.status)) return response;
13
+ const deleteCache = async ()=>{
14
+ try {
15
+ await container.delete(key);
16
+ } catch {
17
+ (onError || console.error)('[render-cache] delete cache failed');
18
+ }
19
+ };
20
+ if (!isCacheableResponse(response) || !response.body) {
21
+ await deleteCache();
22
+ return response;
23
+ }
24
+ const headers = Object.fromEntries(response.headers);
23
25
  const decoder = new TextDecoder();
24
26
  if (response.body) {
25
27
  const stream = createTransformStream();
26
28
  const reader = response.body.getReader();
27
29
  const writer = stream.writable.getWriter();
28
30
  let html = '';
29
- const push = ()=>reader.read().then(({ done, value })=>{
31
+ const push = ()=>reader.read().then(async ({ done, value })=>{
30
32
  if (done) {
33
+ html += decoder.decode();
31
34
  const match = ZERO_RENDER_LEVEL.test(html) || NO_SSR_CACHE.test(html);
32
- if (match) return void writer.close();
35
+ if (match) {
36
+ await deleteCache();
37
+ return writer.close();
38
+ }
33
39
  const current = Date.now();
34
40
  const cache = {
35
41
  val: html,
36
- cursor: current
42
+ cursor: current,
43
+ headers
37
44
  };
38
45
  container.set(key, JSON.stringify(cache), {
39
46
  ttl
40
47
  }).catch(()=>{
41
- if (onError) onError(`[render-cache] set cache failed, key: ${key}, value: ${JSON.stringify(cache)}`);
42
- else console.error(`[render-cache] set cache failed, key: ${key}, value: ${JSON.stringify(cache)}`);
48
+ (onError || console.error)('[render-cache] set cache failed');
43
49
  });
44
- writer.close();
45
- return;
50
+ return writer.close();
46
51
  }
47
- const content = decoder.decode(value);
52
+ const content = decoder.decode(value, {
53
+ stream: true
54
+ });
48
55
  html += content;
49
- writer.write(value);
50
- push();
56
+ await writer.write(value);
57
+ return push();
51
58
  });
52
- push();
59
+ push().catch(async (error)=>{
60
+ await Promise.allSettled([
61
+ writer.abort(error),
62
+ reader.cancel(error)
63
+ ]);
64
+ (onError || console.error)('[render-cache] response stream failed');
65
+ });
53
66
  cacheStatus && response.headers.set(X_RENDER_CACHE, cacheStatus);
54
67
  return new Response(stream.readable, {
55
68
  status: response.status,
@@ -64,9 +77,12 @@ function computedKey(req, cacheControl) {
64
77
  const pathname = getPathname(req);
65
78
  const { customKey } = cacheControl;
66
79
  const defaultKey = '/' === pathname ? pathname : removeTailSlash(pathname);
67
- if (!customKey) return defaultKey;
68
- if ('string' == typeof customKey) return customKey;
69
- return customKey(defaultKey);
80
+ if (customKey) if ('string' == typeof customKey) return customKey;
81
+ else return customKey(defaultKey);
82
+ {
83
+ const url = new URL(req.url);
84
+ return `${url.origin}${defaultKey}${url.search}`;
85
+ }
70
86
  }
71
87
  function shouldUseCache(request) {
72
88
  const url = new URL(request.url);
@@ -96,13 +112,15 @@ function matchCacheControl(cacheOption, req) {
96
112
  async function getCacheResult(request, options) {
97
113
  const { cacheControl, container = storage, requestHandler, requestHandlerOptions } = options;
98
114
  const { onError } = requestHandlerOptions;
99
- const key = computedKey(request, cacheControl);
115
+ const hasCredentials = request.headers.has('cookie') || request.headers.has('authorization');
116
+ if ('GET' !== request.method || !shouldUseCache(request) || preventsSharedCaching(request.headers) || hasCredentials && !cacheControl.customKey) return requestHandler(request, requestHandlerOptions);
117
+ const key = `${CACHE_NAMESPACE}:v2:${computedKey(request, cacheControl)}`;
100
118
  let value;
101
119
  try {
102
120
  value = await container.get(key);
103
121
  } catch (_) {
104
- if (onError) onError(`[render-cache] get cache failed, key: ${key}`);
105
- else console.error(`[render-cache] get cache failed, key: ${key}`);
122
+ if (onError) onError('[render-cache] get cache failed');
123
+ else console.error('[render-cache] get cache failed');
106
124
  value = void 0;
107
125
  }
108
126
  const { maxAge, staleWhileRevalidate } = cacheControl;
@@ -123,6 +141,7 @@ async function getCacheResult(request, options) {
123
141
  const cacheStatus = 'hit';
124
142
  return new Response(cache.val, {
125
143
  headers: {
144
+ ...cache.headers,
126
145
  [X_RENDER_CACHE]: cacheStatus
127
146
  }
128
147
  });
@@ -146,10 +165,13 @@ async function getCacheResult(request, options) {
146
165
  container
147
166
  }).then(async (response)=>{
148
167
  await response.text();
168
+ }).catch(()=>{
169
+ (onError || console.error)('[render-cache] revalidation failed');
149
170
  });
150
171
  const cacheStatus = 'stale';
151
172
  return new Response(cache.val, {
152
173
  headers: {
174
+ ...cache.headers,
153
175
  [X_RENDER_CACHE]: cacheStatus
154
176
  }
155
177
  });
@@ -1,5 +1,6 @@
1
1
  import "node:module";
2
2
  import { server as server_server } from "@modern-js/plugin/server";
3
+ import { logger } from "@modern-js/utils";
3
4
  import { Hono } from "hono";
4
5
  import { run } from "./context.mjs";
5
6
  import { handleSetupResult } from "./plugins/compat/hooks.mjs";
@@ -18,22 +19,54 @@ function _class_private_method_init(obj, privateSet) {
18
19
  var _applyMiddlewares = /*#__PURE__*/ new WeakSet();
19
20
  class ServerBase {
20
21
  async init() {
21
- const { serverConfig, config: cliConfig } = this.serverOptions;
22
- const mergedConfig = loadConfig({
23
- cliConfig,
24
- serverConfig: serverConfig || {}
25
- });
26
- const { serverContext } = await server_server.run({
27
- plugins: this.plugins,
28
- options: this.serverOptions,
29
- config: mergedConfig,
30
- handleSetupResult: handleSetupResult
31
- });
32
- serverContext.serverBase = this;
33
- this.serverContext = serverContext;
34
- await serverContext.hooks.onPrepare.call();
35
- _class_private_method_get(this, _applyMiddlewares, applyMiddlewares).call(this);
36
- return this;
22
+ try {
23
+ const { serverConfig, config: cliConfig } = this.serverOptions;
24
+ const mergedConfig = loadConfig({
25
+ cliConfig,
26
+ serverConfig: serverConfig || {}
27
+ });
28
+ const { serverContext } = await server_server.run({
29
+ plugins: this.plugins,
30
+ options: this.serverOptions,
31
+ config: mergedConfig,
32
+ handleSetupResult: handleSetupResult
33
+ });
34
+ serverContext.serverBase = this;
35
+ this.serverContext = serverContext;
36
+ await serverContext.hooks.onPrepare.call();
37
+ _class_private_method_get(this, _applyMiddlewares, applyMiddlewares).call(this);
38
+ return this;
39
+ } catch (error) {
40
+ await this.dispose().catch((disposeError)=>{
41
+ logger.error(disposeError);
42
+ });
43
+ throw error;
44
+ }
45
+ }
46
+ onDispose(disposer) {
47
+ if (this.disposePromise) throw new Error('Cannot register a disposer on a retired server.');
48
+ this.disposers.add(disposer);
49
+ return ()=>{
50
+ this.disposers.delete(disposer);
51
+ };
52
+ }
53
+ dispose() {
54
+ if (!this.disposePromise) {
55
+ const disposers = [
56
+ ...this.disposers
57
+ ].reverse();
58
+ this.disposers.clear();
59
+ this.disposePromise = Promise.resolve().then(async ()=>{
60
+ const errors = [];
61
+ for (const disposer of disposers)try {
62
+ await disposer();
63
+ } catch (error) {
64
+ errors.push(error);
65
+ }
66
+ if (errors.length > 0) throw new AggregateError(errors, 'Failed to dispose server.');
67
+ });
68
+ }
69
+ return this.disposePromise;
37
70
  }
38
71
  addPlugins(plugins) {
39
72
  this.plugins.push(...plugins);
@@ -79,7 +112,15 @@ class ServerBase {
79
112
  }
80
113
  constructor(options){
81
114
  _class_private_method_init(this, _applyMiddlewares);
82
- this.plugins = [];
115
+ this.plugins = [
116
+ {
117
+ name: '@modern-js/server-lifecycle',
118
+ _registryApi: ()=>({
119
+ onDispose: (disposer)=>this.onDispose(disposer)
120
+ })
121
+ }
122
+ ];
123
+ this.disposers = new Set();
83
124
  this.serverContext = null;
84
125
  this.serverOptions = options;
85
126
  this.app = new Hono();
@@ -51,5 +51,4 @@ function onError(digest, error, monitors, req) {
51
51
  else if (req) console.error(`Server Error - ${digest}, error = ${error instanceof Error ? error.stack || error.message : error}, req.url = ${req.url}, req.headers = ${JSON.stringify(headerData)}`);
52
52
  else console.error(`Server Error - ${digest}, error = ${error instanceof Error ? error.stack || error.message : error} `);
53
53
  }
54
- export { createSafeFailureHttpResult, createSafeJsonFailureResponse, getSafeFailureStatus } from "@modern-js/runtime-extensions/safe-failure";
55
54
  export { createErrorHtml, error_ErrorDigest as ErrorDigest, onError };
@@ -3,3 +3,5 @@ export type { ServerNodeContext, ServerNodeMiddleware } from './hono.js';
3
3
  export { connectMid2HonoMid, connectMockMid2HonoMid, httpCallBack2HonoMid, } from './hono.js';
4
4
  export { createNodeServer, createWebRequest, sendResponse, } from './node.js';
5
5
  export { getHtmlTemplates, getServerManifest, injectNodeSeverPlugin, injectResourcePlugin, injectRscManifestPlugin, serverStaticPlugin, } from './plugins/index.js';
6
+ export type { ServerStaticPluginOptions, ServeStaticAsset, StaticAsset, StaticAssetRequest, StaticAssetResponder, StaticPublicFallbackResponder, } from './plugins/static.js';
7
+ export { serveStaticAsset } from './plugins/static.js';
@@ -1,12 +1,50 @@
1
1
  import type { ServerRoute } from '@modern-js/types';
2
2
  import type { HtmlNormalizedConfig, Middleware, OutputNormalizedConfig, ServerNormalizedConfig, ServerPlugin } from '../../../types/index.js';
3
- export declare const serverStaticPlugin: () => ServerPlugin;
3
+ /** A selected file and the native response conventions to use for it. */
4
+ export type StaticAsset = {
5
+ filename: string;
6
+ kind: 'static' | 'public';
7
+ /** An alternate representation retains the original resource's MIME type. */
8
+ mimeFilename?: string;
9
+ responseHeaders?: ServerRoute['responseHeaders'];
10
+ /** True uses the served byte length; omitted preserves native length defaults. */
11
+ contentLength?: boolean;
12
+ /** Optional lexical containment boundary. Use real paths to contain symlinks. */
13
+ root?: string;
14
+ /** Resolve symlinks before checking root. Implies a regular file is required. */
15
+ realpath?: boolean;
16
+ };
17
+ export type StaticAssetRequest = {
18
+ root: string;
19
+ pathPrefix: string;
20
+ };
21
+ /** Native serving of the selected file, optionally choosing another representation. */
22
+ export type ServeStaticAsset = (representation?: Partial<Pick<StaticAsset, 'filename' | 'contentLength'>>) => Promise<Response | null>;
23
+ /**
24
+ * Trusted server extension. Undefined uses the native file; null skips it.
25
+ * A returned response is final. Exceptions use the normal server error handler.
26
+ */
27
+ export type StaticAssetResponder = (context: Parameters<Middleware>[0], asset: StaticAsset, serve: ServeStaticAsset, request: StaticAssetRequest) => Response | null | undefined | Promise<Response | null | undefined>;
28
+ /**
29
+ * Handles requests outside the native static pattern. The continuation only
30
+ * tries native public routes; it returns null on a miss and never calls the next
31
+ * middleware. Returning null from this hook continues the middleware chain.
32
+ */
33
+ export type StaticPublicFallbackResponder = (context: Parameters<Middleware>[0], respondPublic: () => Promise<Response | null>, request: StaticAssetRequest) => Response | null | Promise<Response | null>;
34
+ /** Read a selected file using native readers, MIME, headers and body conversion. */
35
+ export declare function serveStaticAsset(context: Parameters<Middleware>[0], asset: StaticAsset, respond?: (asset: StaticAsset, serve: ServeStaticAsset) => Promise<Response | null>): Promise<Response | null>;
36
+ export type ServerStaticPluginOptions = {
37
+ respondAsset?: StaticAssetResponder;
38
+ respondPublicFallback?: StaticPublicFallbackResponder;
39
+ };
40
+ export declare const serverStaticPlugin: (options?: ServerStaticPluginOptions) => ServerPlugin;
4
41
  export type PublicMiddlwareOptions = {
5
42
  pwd: string;
6
43
  routes: ServerRoute[];
7
- };
8
- export declare function createPublicMiddleware({ pwd, routes, }: PublicMiddlwareOptions): Middleware;
9
- export interface ServerStaticOptions {
44
+ pathPrefix?: string;
45
+ } & ServerStaticPluginOptions;
46
+ export declare function createPublicMiddleware({ pwd, routes, pathPrefix, respondAsset, respondPublicFallback, }: PublicMiddlwareOptions): Middleware;
47
+ export interface ServerStaticOptions extends ServerStaticPluginOptions {
10
48
  pwd: string;
11
49
  output: OutputNormalizedConfig;
12
50
  html: HtmlNormalizedConfig;
@@ -10,6 +10,5 @@ export * from './types/config/index.js';
10
10
  export * from './types/plugins/index.js';
11
11
  export * from './types/render.js';
12
12
  export * from './types/requestHandler.js';
13
- export type { SafeFailureEnvelope, SafeFailureHttpResult } from './utils/index.js';
14
- export { createErrorHtml, createSafeFailureHttpResult, createSafeJsonFailureResponse, ErrorDigest, getSafeFailureStatus, onError, } from './utils/index.js';
13
+ export { createErrorHtml, ErrorDigest, onError, } from './utils/index.js';
15
14
  export { getPublicDirConfig, getPublicDirPatterns, getPublicDirRoutePrefixes, normalizePublicDir, normalizePublicDirPath, resolvePublicDirPaths, } from './utils/publicDir.js';
@@ -12,6 +12,8 @@ export declare class ServerBase<E extends Env = any> {
12
12
  serverOptions: ServerBaseOptions;
13
13
  private app;
14
14
  private plugins;
15
+ private disposers;
16
+ private disposePromise?;
15
17
  private serverContext;
16
18
  constructor(options: ServerBaseOptions);
17
19
  /**
@@ -20,6 +22,10 @@ export declare class ServerBase<E extends Env = any> {
20
22
  * - apply middlewares
21
23
  */
22
24
  init(): Promise<this>;
25
+ /** Register instance resources before initialization can fail. */
26
+ onDispose(disposer: () => void | Promise<void>): () => void;
27
+ /** Retire this instance and release every resource in reverse order once. */
28
+ dispose(): Promise<void>;
23
29
  addPlugins(plugins: ServerPlugin[]): void;
24
30
  get hooks(): ServerPluginHooks;
25
31
  get all(): import("hono/types").HandlerInterface<E, "all", import("hono/types").BlankSchema, "/", "/">;
@@ -30,7 +36,7 @@ export declare class ServerBase<E extends Env = any> {
30
36
  get put(): import("hono/types").HandlerInterface<E, "put", import("hono/types").BlankSchema, "/", "/">;
31
37
  get delete(): import("hono/types").HandlerInterface<E, "delete", import("hono/types").BlankSchema, "/", "/">;
32
38
  get patch(): import("hono/types").HandlerInterface<E, "patch", import("hono/types").BlankSchema, "/", "/">;
33
- get handle(): (request: Request, Env?: {} | E["Bindings"] | undefined, executionCtx?: import("hono").ExecutionContext) => Response | Promise<Response>;
39
+ get handle(): (request: Request, env?: {} | E["Bindings"] | undefined, executionCtx?: import("hono").ExecutionContext) => Response | Promise<Response>;
34
40
  get request(): (input: Request | string | URL, requestInit?: RequestInit, Env?: {} | E["Bindings"] | undefined, executionCtx?: import("hono").ExecutionContext) => Response | Promise<Response>;
35
41
  get notFound(): (handler: import("hono").NotFoundHandler<E>) => import("hono/hono-base").HonoBase<E, import("hono/types").BlankSchema, "/", "/">;
36
42
  get onError(): (handler: import("hono").ErrorHandler<E>) => import("hono/hono-base").HonoBase<E, import("hono/types").BlankSchema, "/", "/">;
@@ -1,6 +1,5 @@
1
+ import type { BffRuntimeFramework } from '@modern-js/plugin/server';
1
2
  import type { HttpMethodDecider } from '@modern-js/types';
2
- import type { BffCrossProjectPolicyUserConfig, BffEffectUserConfig, BffRuntimeFramework } from './bffRuntime.js';
3
- export type { BffCrossProjectPolicyUserConfig, BffEffectDataPlatformBatchUserConfig, BffEffectDataPlatformSelectionUserConfig, BffEffectDataPlatformUserConfig, BffEffectOpenApiUserConfig, BffEffectUserConfig, BffRuntimeFramework, } from './bffRuntime.js';
4
3
  export interface BffUserConfig {
5
4
  prefix?: string | string[];
6
5
  httpMethodDecider?: HttpMethodDecider;
@@ -25,23 +24,13 @@ export interface BffUserConfig {
25
24
  * Custom request creator import path for generated BFF clients.
26
25
  */
27
26
  requestCreator?: string;
27
+ /** Node module exporting a generated-client transform. */
28
+ clientCodegenPlugin?: string;
28
29
  /**
29
30
  * Legacy custom fetcher import path for generated BFF clients.
30
31
  */
31
32
  fetcher?: string;
32
- /**
33
- * Selects the BFF runtime implementation.
34
- *
35
- * - `effect`: only `api/index` (or the configured `bff.effect.entry`) is served.
36
- * - `hono`: only `api/lambda/**` handlers are served.
37
- *
38
- * @default 'effect'
39
- */
33
+ /** Selects a registered BFF runtime implementation. */
40
34
  runtimeFramework?: BffRuntimeFramework;
41
- /**
42
- * Effect runtime configuration. Only applies when `runtimeFramework: 'effect'`.
43
- */
44
- effect?: BffEffectUserConfig;
45
- crossProjectPolicy?: BffCrossProjectPolicyUserConfig;
46
35
  }
47
36
  export type BffNormalizedConfig = BffUserConfig;
@@ -1,7 +1,5 @@
1
1
  import type { SSRMode } from '@modern-js/types';
2
2
  import type { WatchOptions } from '@modern-js/utils';
3
- import type { ServerTelemetryUserConfig } from './serverTelemetry.js';
4
- export type { ServerTelemetryCanaryAutopilotStateStoreUserConfig, ServerTelemetryCanaryAutopilotUserConfig, ServerTelemetryCanaryContractGateUserConfig, ServerTelemetryCanaryRuntimeFallbackSignalAuthUserConfig, ServerTelemetryCanaryRuntimeFallbackSignalTrustPolicyUserConfig, ServerTelemetryCanaryRuntimeFallbackSignalUserConfig, ServerTelemetryCanaryUserConfig, ServerTelemetryExporterOptions, ServerTelemetrySloUserConfig, ServerTelemetryUserConfig, ServerTelemetryVictoriaMetricsOptions, } from './serverTelemetry.js';
5
3
  type Route = string | string[] | {
6
4
  route?: string | string[];
7
5
  disableSpa?: boolean;
@@ -50,7 +48,6 @@ export interface ServerUserConfig {
50
48
  */
51
49
  useJsonScript?: boolean;
52
50
  logger?: boolean | Record<string, unknown>;
53
- telemetry?: ServerTelemetryUserConfig;
54
51
  /**
55
52
  * @description disable hook middleware for performance
56
53
  * @default false
@@ -66,3 +63,4 @@ export interface ServerUserConfig {
66
63
  tsconfigPath?: string;
67
64
  }
68
65
  export type ServerNormalizedConfig = ServerUserConfig;
66
+ export {};
@@ -1,21 +1,35 @@
1
1
  import type { AsyncPipelineHook, ServerContext as BaseServerContext, ServerPlugin as BaseServerPlugin, ServerPluginAPI as BaseServerPluginAPI, ServerPluginExtends as BaseServerPluginExtends } from '@modern-js/plugin';
2
2
  import type { Hooks } from '@modern-js/plugin/server';
3
3
  import type { AfterMatchContext, AfterRenderContext, AfterStreamingRenderContext } from '@modern-js/types';
4
- import type { MiddlewareHandler } from 'hono';
4
+ import type { Context, MiddlewareHandler } from 'hono';
5
+ import type { ServerStaticPluginOptions } from '../../adapters/node/plugins/static.js';
5
6
  import type { APIServerStartInput, MiddlewareObj, ServerConfig, WebAdapter, WebServerStartInput } from './base.js';
6
7
  export type PrepareWebServerFn = (input: WebServerStartInput) => Promise<WebAdapter | null>;
7
8
  export type PrepareApiServerFn = (input: APIServerStartInput) => Promise<MiddlewareHandler>;
8
9
  export type AfterMatchFn = (ctx: AfterMatchContext) => Promise<any>;
9
10
  export type AfterRenderFn = (ctx: AfterRenderContext) => Promise<any>;
10
11
  export type AfterStreamingRenderContextFn = (ctx: AfterStreamingRenderContext) => Promise<AfterStreamingRenderContext>;
12
+ export interface HandleErrorInput {
13
+ error: Error;
14
+ context: Context;
15
+ response?: Response;
16
+ }
17
+ export type HandleErrorFn = (input: HandleErrorInput, next?: (input: HandleErrorInput) => void) => Promise<HandleErrorInput>;
11
18
  export interface ServerPluginExtends extends BaseServerPluginExtends {
12
19
  config: ServerConfig;
20
+ extendApi: {
21
+ /** Release an instance resource on shutdown or failed initialization. */
22
+ onDispose: (disposer: () => void | Promise<void>) => () => void;
23
+ };
13
24
  extendContext: {
25
+ /** Node static response extensions registered during plugin setup. */
26
+ staticAssetResponders?: ServerStaticPluginOptions;
14
27
  middlewares: MiddlewareObj[];
15
28
  renderMiddlewares: MiddlewareObj[];
16
29
  [key: string]: any;
17
30
  };
18
31
  extendHooks: {
32
+ handleError: AsyncPipelineHook<HandleErrorFn>;
19
33
  prepareWebServer: AsyncPipelineHook<PrepareWebServerFn>;
20
34
  prepareApiServer: AsyncPipelineHook<PrepareApiServerFn>;
21
35
  afterMatch: AsyncPipelineHook<AfterMatchFn>;
@@ -1,4 +1,4 @@
1
- import type { Reporter, ServerRoute } from '@modern-js/types';
1
+ import type { OnError, OnTiming, Reporter, ServerRoute } from '@modern-js/types';
2
2
  import type { Monitors, ClientManifest as RscClientManifest, ServerManifest as RscServerManifest, SSRManifest as RscSSRManifest } from '@modern-js/types/server';
3
3
  import type { ServerUserConfig, SourceUserConfig } from './config/index.js';
4
4
  export type Resource = {
@@ -22,8 +22,7 @@ export type RequestHandlerConfig = {
22
22
  enableAsyncEntry?: SourceUserConfig['enableAsyncEntry'];
23
23
  };
24
24
  export type LoaderContext = Map<string, any>;
25
- export type OnError = (err: unknown, key?: string) => void;
26
- export type OnTiming = (name: string, dur: number) => void;
25
+ export type { OnError, OnTiming };
27
26
  export type RequestHandlerOptions = {
28
27
  resource: Resource;
29
28
  config: RequestHandlerConfig;
@@ -1,6 +1,4 @@
1
1
  import type { Monitors } from '@modern-js/types';
2
- export type { SafeFailureEnvelope, SafeFailureHttpResult, } from '@modern-js/runtime-extensions/safe-failure';
3
- export { createSafeFailureHttpResult, createSafeJsonFailureResponse, getSafeFailureStatus, } from '@modern-js/runtime-extensions/safe-failure';
4
2
  export declare const createErrorHtml: (status: number) => string;
5
3
  export declare enum ErrorDigest {
6
4
  ENOTF = "Page could not be found",
package/package.json CHANGED
@@ -17,7 +17,7 @@
17
17
  "modern",
18
18
  "modern.js"
19
19
  ],
20
- "version": "3.9.0-ultramodern.1",
20
+ "version": "3.9.0-ultramodern.11",
21
21
  "types": "./dist/types/index.d.ts",
22
22
  "main": "./dist/cjs/index.js",
23
23
  "exports": {
@@ -66,26 +66,25 @@
66
66
  "node": ">=20"
67
67
  },
68
68
  "dependencies": {
69
- "@modern-js/plugin": "npm:@bleedingdev/modern-js-plugin@3.9.0-ultramodern.1",
70
- "@modern-js/runtime-extensions": "npm:@bleedingdev/modern-js-runtime-extensions@3.9.0-ultramodern.1",
71
- "@modern-js/runtime-utils": "npm:@bleedingdev/modern-js-runtime-utils@3.9.0-ultramodern.1",
72
- "@modern-js/utils": "npm:@bleedingdev/modern-js-utils@3.9.0-ultramodern.1",
69
+ "@modern-js/plugin": "npm:@bleedingdev/modern-js-plugin@3.9.0-ultramodern.11",
70
+ "@modern-js/runtime-utils": "npm:@bleedingdev/modern-js-runtime-utils@3.9.0-ultramodern.11",
71
+ "@modern-js/utils": "npm:@bleedingdev/modern-js-utils@3.9.0-ultramodern.11",
73
72
  "@swc/helpers": "^0.5.23",
74
73
  "@web-std/fetch": "^4.2.1",
75
74
  "@web-std/file": "^3.0.3",
76
75
  "@web-std/stream": "^1.0.3",
77
76
  "cloneable-readable": "^3.0.0",
78
77
  "flatted": "^3.4.4",
79
- "hono": "^4.12.28",
78
+ "hono": "^4.13.7",
80
79
  "ts-deepmerge": "8.0.0"
81
80
  },
82
81
  "devDependencies": {
83
- "@modern-js/types": "npm:@bleedingdev/modern-js-types@3.9.0-ultramodern.1",
82
+ "@modern-js/types": "npm:@bleedingdev/modern-js-types@3.9.0-ultramodern.11",
84
83
  "@rslib/core": "1.0.0",
85
84
  "@scripts/rstest-config": "2.66.0",
86
85
  "@types/cloneable-readable": "^2.0.3",
87
86
  "@types/merge-deep": "^3.0.3",
88
- "@types/node": "^26.2.0",
87
+ "@types/node": "^26.4.1",
89
88
  "@typescript/native-preview": "7.0.0-dev.20260707.2",
90
89
  "http-proxy-middleware": "^4.2.0",
91
90
  "typescript": "^7.0.2"