@fluojs/runtime 1.1.8 → 3.0.0
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/README.ko.md +292 -21
- package/README.md +292 -21
- package/dist/abort.d.ts +6 -1
- package/dist/abort.d.ts.map +1 -1
- package/dist/abort.js +18 -2
- package/dist/adapters/internal-request-response-factory.d.ts +1 -1
- package/dist/adapters/internal-request-response-factory.d.ts.map +1 -1
- package/dist/adapters/internal-request-response-factory.js +1 -1
- package/dist/adapters/request-response-factory.d.ts +20 -1
- package/dist/adapters/request-response-factory.d.ts.map +1 -1
- package/dist/adapters/request-response-factory.js +75 -22
- package/dist/bootstrap.d.ts +3 -9
- package/dist/bootstrap.d.ts.map +1 -1
- package/dist/bootstrap.js +181 -76
- package/dist/devtools/contracts.d.ts +3 -135
- package/dist/devtools/contracts.d.ts.map +1 -1
- package/dist/devtools/index.d.ts +2 -3
- package/dist/devtools/index.d.ts.map +1 -1
- package/dist/devtools/index.js +1 -2
- package/dist/devtools/snapshot.d.ts +1 -1
- package/dist/devtools/snapshot.d.ts.map +1 -1
- package/dist/devtools/snapshot.js +18 -17
- package/dist/devtools/studio-request-observer.d.ts +14 -0
- package/dist/devtools/studio-request-observer.d.ts.map +1 -0
- package/dist/devtools/studio-request-observer.js +112 -0
- package/dist/devtools/studio-runtime-config.d.ts +25 -0
- package/dist/devtools/studio-runtime-config.d.ts.map +1 -0
- package/dist/devtools/studio-runtime-config.js +59 -0
- package/dist/devtools/studio-runtime.d.ts +12 -18
- package/dist/devtools/studio-runtime.d.ts.map +1 -1
- package/dist/devtools/studio-runtime.js +25 -169
- package/dist/errors.d.ts +26 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +38 -0
- package/dist/health/health.d.ts +18 -4
- package/dist/health/health.d.ts.map +1 -1
- package/dist/health/health.js +5 -2
- package/dist/http-adapter-shared.d.ts +1 -1
- package/dist/http-adapter-shared.d.ts.map +1 -1
- package/dist/http-adapter-shared.js +1 -1
- package/dist/index.d.ts +6 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -1
- package/dist/internal/route-inspection-metadata.d.ts +30 -0
- package/dist/internal/route-inspection-metadata.d.ts.map +1 -0
- package/dist/internal/route-inspection-metadata.js +68 -0
- package/dist/internal.d.ts +6 -1
- package/dist/internal.d.ts.map +1 -1
- package/dist/internal.js +4 -1
- package/dist/module-definition.d.ts +10 -0
- package/dist/module-definition.d.ts.map +1 -0
- package/dist/module-definition.js +12 -0
- package/dist/module-graph.d.ts +42 -1
- package/dist/module-graph.d.ts.map +1 -1
- package/dist/module-graph.js +112 -16
- package/dist/multipart.d.ts +68 -4
- package/dist/multipart.d.ts.map +1 -1
- package/dist/multipart.js +666 -103
- package/dist/platform-component-registry.d.ts +9 -0
- package/dist/platform-component-registry.d.ts.map +1 -0
- package/dist/platform-component-registry.js +70 -0
- package/dist/platform-diagnostic-retention.d.ts +13 -0
- package/dist/platform-diagnostic-retention.d.ts.map +1 -0
- package/dist/platform-diagnostic-retention.js +43 -0
- package/dist/platform-shell-probe-reports.d.ts +8 -0
- package/dist/platform-shell-probe-reports.d.ts.map +1 -0
- package/dist/platform-shell-probe-reports.js +95 -0
- package/dist/platform-shell-probes.d.ts +16 -0
- package/dist/platform-shell-probes.d.ts.map +1 -0
- package/dist/platform-shell-probes.js +141 -0
- package/dist/platform-shell.d.ts +7 -13
- package/dist/platform-shell.d.ts.map +1 -1
- package/dist/platform-shell.js +58 -310
- package/dist/retryable-shutdown.d.ts +7 -0
- package/dist/retryable-shutdown.d.ts.map +1 -0
- package/dist/retryable-shutdown.js +20 -0
- package/dist/route-inspection.d.ts +56 -0
- package/dist/route-inspection.d.ts.map +1 -0
- package/dist/route-inspection.js +80 -0
- package/dist/tokens.d.ts +6 -4
- package/dist/tokens.d.ts.map +1 -1
- package/dist/tokens.js +5 -0
- package/dist/types.d.ts +53 -8
- package/dist/types.d.ts.map +1 -1
- package/dist/web.d.ts +22 -9
- package/dist/web.d.ts.map +1 -1
- package/dist/web.js +80 -34
- package/package.json +13 -26
- package/dist/internal-node.d.ts +0 -2
- package/dist/internal-node.d.ts.map +0 -1
- package/dist/internal-node.js +0 -1
- package/dist/logging/json-logger.d.ts +0 -8
- package/dist/logging/json-logger.d.ts.map +0 -1
- package/dist/logging/json-logger.js +0 -45
- package/dist/logging/logger.d.ts +0 -37
- package/dist/logging/logger.d.ts.map +0 -1
- package/dist/logging/logger.js +0 -103
- package/dist/node/internal-node-compression.d.ts +0 -22
- package/dist/node/internal-node-compression.d.ts.map +0 -1
- package/dist/node/internal-node-compression.js +0 -84
- package/dist/node/internal-node-request.d.ts +0 -162
- package/dist/node/internal-node-request.d.ts.map +0 -1
- package/dist/node/internal-node-request.js +0 -475
- package/dist/node/internal-node-response.d.ts +0 -28
- package/dist/node/internal-node-response.d.ts.map +0 -1
- package/dist/node/internal-node-response.js +0 -205
- package/dist/node/internal-node-shutdown.d.ts +0 -34
- package/dist/node/internal-node-shutdown.d.ts.map +0 -1
- package/dist/node/internal-node-shutdown.js +0 -83
- package/dist/node/internal-node.d.ts +0 -117
- package/dist/node/internal-node.d.ts.map +0 -1
- package/dist/node/internal-node.js +0 -283
- package/dist/node/node-compression.d.ts +0 -2
- package/dist/node/node-compression.d.ts.map +0 -1
- package/dist/node/node-compression.js +0 -1
- package/dist/node/node-request.d.ts +0 -2
- package/dist/node/node-request.d.ts.map +0 -1
- package/dist/node/node-request.js +0 -1
- package/dist/node/node-response.d.ts +0 -2
- package/dist/node/node-response.d.ts.map +0 -1
- package/dist/node/node-response.js +0 -1
- package/dist/node/node-shutdown.d.ts +0 -2
- package/dist/node/node-shutdown.d.ts.map +0 -1
- package/dist/node/node-shutdown.js +0 -1
- package/dist/node/node.d.ts +0 -2
- package/dist/node/node.d.ts.map +0 -1
- package/dist/node/node.js +0 -1
- package/dist/node.d.ts +0 -5
- package/dist/node.d.ts.map +0 -1
- package/dist/node.js +0 -3
package/README.md
CHANGED
|
@@ -4,12 +4,15 @@
|
|
|
4
4
|
|
|
5
5
|
The assembly layer that compiles a module graph and wires DI and HTTP into a runnable application shell.
|
|
6
6
|
|
|
7
|
+
Preparing for the coordinated Node 24 release? Follow the [consumer migration guide](../../docs/getting-started/migrate-node24.md) before upgrading packages.
|
|
8
|
+
|
|
7
9
|
## Table of Contents
|
|
8
10
|
|
|
9
11
|
- [Installation](#installation)
|
|
10
12
|
- [When to Use](#when-to-use)
|
|
11
13
|
- [Quick Start](#quick-start)
|
|
12
14
|
- [Common Patterns](#common-patterns)
|
|
15
|
+
- [Node Static Asset Source](#node-static-asset-source)
|
|
13
16
|
- [Behavioral Contracts](#behavioral-contracts)
|
|
14
17
|
- [Public API Overview](#public-api-overview)
|
|
15
18
|
- [Related Packages](#related-packages)
|
|
@@ -21,13 +24,19 @@ The assembly layer that compiles a module graph and wires DI and HTTP into a run
|
|
|
21
24
|
npm install @fluojs/runtime
|
|
22
25
|
```
|
|
23
26
|
|
|
27
|
+
The published package intentionally declares no package-wide `engines.node`: its root, `./web`, and runtime-neutral internal seams contain no eager Node builtin imports and are shared by Node, Bun, Deno, Cloudflare Workers, and other Web-standard hosts. Node listener, filesystem, logger, compression, and process-signal responsibilities live in `@fluojs/platform-nodejs`, which declares the verified Node engine range.
|
|
28
|
+
|
|
29
|
+
## Node Static Asset Source
|
|
30
|
+
|
|
31
|
+
`@fluojs/http` owns portable static middleware and representation-selection contracts. `@fluojs/platform-nodejs` exports `createNodeFileSystemAssetSource(...)`, its Node filesystem `StaticAssetSource` implementation: it validates the root directory during configuration, keeps lexical and realpath resolution inside that root (including symlink checks), and can select `.br` or `.gz` siblings. For each selected regular-file representation, it opens the verified file, eagerly copies the entire file into an immutable byte snapshot, and closes its `FileHandle` before response writing. Its returned `source()` replays only that snapshot and never reopens or lazily streams the pathname; application owners therefore bound memory by the selected whole-file size, and `size` plus the strong `ETag` describe those exact bytes. Raw Node, Express, and Fastify adapters share this portable middleware/source seam and preserve the selected representation boundary rather than applying adapter-specific re-encoding. This Node-only helper is intentionally absent from `@fluojs/runtime/web`; Web and edge deployments must provide an application-owned source.
|
|
32
|
+
|
|
24
33
|
## When to Use
|
|
25
34
|
|
|
26
35
|
Use this package when you need to:
|
|
27
36
|
- **Bootstrap a fluo application**: Convert your modules into a running HTTP server or microservice.
|
|
28
37
|
- **Orchestrate DI and Lifecycle**: Manage module-graph compilation, provider wiring, and application hooks (`onModuleInit`, `onApplicationBootstrap`).
|
|
29
38
|
- **Create Standalone Contexts**: Run CLI tasks, scripts, or workers that need DI but not an HTTP server.
|
|
30
|
-
- **Diagnostic Inspection**: Produce machine-readable platform snapshots and diagnostic issues for CLI export while leaving graph viewing and Mermaid presentation to Studio.
|
|
39
|
+
- **Diagnostic Inspection**: Produce machine-readable platform snapshots, compiled route catalogs, and diagnostic issues for CLI export while leaving graph viewing and Mermaid presentation to Studio.
|
|
31
40
|
|
|
32
41
|
## Quick Start
|
|
33
42
|
|
|
@@ -62,8 +71,104 @@ const app = await fluoFactory.create(AppModule, {
|
|
|
62
71
|
await app.listen();
|
|
63
72
|
```
|
|
64
73
|
|
|
74
|
+
The `@Get()` above uses the empty relative path, so the controller serves GET `/`.
|
|
75
|
+
With `@Controller('cats')` it would serve `/cats`, not bypass the prefix. An empty
|
|
76
|
+
`@Module()` can also bootstrap and close without inventing providers.
|
|
77
|
+
|
|
65
78
|
## Common Patterns
|
|
66
79
|
|
|
80
|
+
### Health endpoint middleware
|
|
81
|
+
|
|
82
|
+
`HealthModule.forRoot()` accepts class-based `endpointMiddleware` for its generated health and readiness routes. Middleware resolves through DI, runs in declaration order, and applies to both normalized endpoints under an optional custom `path`; omitting it preserves the default behavior.
|
|
83
|
+
|
|
84
|
+
```typescript
|
|
85
|
+
HealthModule.forRoot({
|
|
86
|
+
endpointMiddleware: [HealthProbeAuthMiddleware],
|
|
87
|
+
path: '/internal/',
|
|
88
|
+
});
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
This configuration applies `HealthProbeAuthMiddleware` to `/internal/health` and `/internal/ready`, not to unrelated application routes.
|
|
92
|
+
|
|
93
|
+
### Streaming multipart consumption
|
|
94
|
+
|
|
95
|
+
Use `parseMultipartStream(...)` from `@fluojs/runtime/web` for a standalone raw `Request` or
|
|
96
|
+
request-like body when large uploaded files must not be materialized as `Uint8Array` values. The
|
|
97
|
+
existing `parseMultipart(...)` API remains the explicit buffered mode. Select exactly one mode for
|
|
98
|
+
a request: buffered and streaming parsing of the same body reject with
|
|
99
|
+
`MultipartBodyConsumedError`.
|
|
100
|
+
|
|
101
|
+
```typescript
|
|
102
|
+
import {
|
|
103
|
+
parseMultipartStream,
|
|
104
|
+
type MultipartFilePart,
|
|
105
|
+
} from '@fluojs/runtime/web';
|
|
106
|
+
|
|
107
|
+
for await (const part of parseMultipartStream(request, {
|
|
108
|
+
maxFieldSize: 1 * 1024 * 1024,
|
|
109
|
+
maxFields: 20,
|
|
110
|
+
maxFiles: 4,
|
|
111
|
+
maxFileSize: 20 * 1024 * 1024,
|
|
112
|
+
maxHeaderSize: 8 * 1024,
|
|
113
|
+
maxTotalSize: 25 * 1024 * 1024,
|
|
114
|
+
})) {
|
|
115
|
+
if (part.kind === 'field') {
|
|
116
|
+
continue; // part.name and part.value
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const file: MultipartFilePart = part;
|
|
120
|
+
await store(file.stream); // finish or cancel before reading the next part
|
|
121
|
+
}
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
For Node.js, Express, Fastify, and Web application dispatch, opt in at application bootstrap with
|
|
125
|
+
`multipart.strategy: 'stream'`. The route receives the same `AsyncIterable<MultipartPart>` through
|
|
126
|
+
`RequestContext.request.body`; adapter dispatch creates the iterator but does not pull or buffer it
|
|
127
|
+
before the route consumes it.
|
|
128
|
+
|
|
129
|
+
```typescript
|
|
130
|
+
const app = await bootstrapNodejsApplication(AppModule, {
|
|
131
|
+
multipart: {
|
|
132
|
+
strategy: 'stream',
|
|
133
|
+
maxTotalSize: 25 * 1024 * 1024,
|
|
134
|
+
},
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
@Controller('/uploads')
|
|
138
|
+
class UploadController {
|
|
139
|
+
@Post('/')
|
|
140
|
+
async upload(_input: undefined, context: RequestContext) {
|
|
141
|
+
for await (const part of context.request.body as AsyncIterable<MultipartPart>) {
|
|
142
|
+
// Consume each file stream before advancing to the next part.
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
Streaming mode applies bounded field and header defaults. Buffered `parseMultipart(...)` preserves
|
|
149
|
+
its prior acceptance behavior for fields and headers unless `maxFieldSize`, `maxFields`, or
|
|
150
|
+
`maxHeaderSize` is explicitly configured.
|
|
151
|
+
|
|
152
|
+
`MultipartFilePart.stream` is a Web `ReadableStream<Uint8Array>` with parser-driven
|
|
153
|
+
backpressure: a file body is yielded before the complete request arrives, and the next request
|
|
154
|
+
chunk is read only when the active file stream needs it. File-stream cancellation, request abort,
|
|
155
|
+
parser failures, and every size/count/header limit cancel the active source and release the parser.
|
|
156
|
+
The parser accepts native Fetch `Request` values plus native async-iterable Node/Express/Fastify
|
|
157
|
+
request streams (directly or as `MultipartRequestLike` wrappers); it never exposes adapter-native
|
|
158
|
+
multipart objects or temporary-file APIs.
|
|
159
|
+
|
|
160
|
+
### Optional Early Hints capability
|
|
161
|
+
|
|
162
|
+
The runtime preserves the adapter-owned optional `context.response.earlyHints` capability without making it part of the required response method surface. Node.js, Express, and Fastify responses provide the writer; Web-standard response factories omit it so Bun, Deno, Workers, and custom Fetch hosts are detectable as unsupported before use. Early writes remain independent from final status, headers, body, and commit ownership. See the [`@fluojs/http` Early Hints contract](../http/README.md#early-hints).
|
|
163
|
+
|
|
164
|
+
### Conditional request bootstrap
|
|
165
|
+
|
|
166
|
+
Runtime bootstrap accepts the `conditionalRequest` option from `@fluojs/http`. Its resolver returns explicit representation existence plus optional validators; it runs after middleware and guards, before interceptors and controller invocation. See the [`@fluojs/http` Conditional Requests contract](../http/README.md#conditional-requests) for the resolver shape, RFC 9110 precedence, and `HEAD` rules.
|
|
167
|
+
|
|
168
|
+
### Access log observers
|
|
169
|
+
|
|
170
|
+
Pass `createAccessLogObserver(...)` through the bootstrap `observers` option to route portable request lifecycle records to application-owned structured logging. The observer preserves the dispatcher lifecycle for native adapters by selecting the complete fallback path; see the [`@fluojs/http` Access logging contract](../http/README.md#access-logging) for trusted client identity and header allowlist requirements.
|
|
171
|
+
|
|
67
172
|
### Application Context (No HTTP)
|
|
68
173
|
|
|
69
174
|
For background workers or scripts, use `createApplicationContext` to skip HTTP setup.
|
|
@@ -80,11 +185,42 @@ await userService.doWork();
|
|
|
80
185
|
await context.close();
|
|
81
186
|
```
|
|
82
187
|
|
|
188
|
+
### Migrating PlatformShell Lifecycle Overlap
|
|
189
|
+
|
|
190
|
+
`RuntimePlatformShell.start()` and `stop()` are strictly exclusive. While either transition is active, every overlapping `start()` or `stop()` call returns an immediately rejected promise with `PlatformLifecycleConflictError`, code `PLATFORM_LIFECYCLE_CONFLICT`, and `activeOperation` / `requestedOperation` on both the error and its structured `meta`. The shell never shares, queues, or coalesces overlapping work. Sequential calls made after settlement remain idempotent, and failed transitions release the exclusive gate so callers can retry explicitly.
|
|
191
|
+
|
|
192
|
+
In `@fluojs/runtime` 2.x, overlapping `start()` calls could start the same components more than once, and `stop()` called during an in-flight startup could return before startup settled and leave resources running. When upgrading, give one application boundary ownership of each lifecycle transition. If another path can overlap, catch `PlatformLifecycleConflictError`, wait for the boundary-owned transition to settle, and retry explicitly only if the desired state is still required. Do not recreate a hidden queue around callback reentry; component lifecycle callbacks receive the same immediate conflict after synchronous code or arbitrary `await` boundaries.
|
|
193
|
+
|
|
194
|
+
### Migrating NestJS Lifecycle Hooks
|
|
195
|
+
|
|
196
|
+
The public runtime lifecycle contract has four hooks: startup runs `onModuleInit()` and then `onApplicationBootstrap()`, while shutdown runs `onModuleDestroy()` and then `onApplicationShutdown(signal?)` in reverse lifecycle-instance order. Each eligible singleton `multi: true` contribution is a distinct lifecycle instance: startup follows contribution order and shutdown reverses it. NestJS `beforeApplicationShutdown` is unsupported and is not probed or invoked by fluo.
|
|
197
|
+
|
|
198
|
+
Move shutdown preparation into the documented phase that owns it. Use `onModuleDestroy()` for module-resource teardown that must finish before the application-wide signal phase, or `onApplicationShutdown(signal?)` for signal-aware application cleanup. `@fluojs/runtime` provides no `beforeApplicationShutdown` compatibility shim, alias, fallback, or additional runtime hook.
|
|
199
|
+
|
|
200
|
+
NestJS `app.enableShutdownHooks()` is not an implicit result of every fluo bootstrap path. For the default Node `SIGINT` / `SIGTERM` wiring, use `runNodeApplication(...)` from `@fluojs/platform-nodejs`; it installs the default Node shutdown registration. `FluoFactory.create(...)`, `bootstrapNodeApplication(...)`, and adapter-first Node bootstrap leave signal ownership explicit, so use `createNodeShutdownSignalRegistration(...)` or `registerShutdownSignals(...)` at that Node application boundary when signal handling is required. Fetch-style hosts such as Bun, Deno, and Cloudflare Workers own their own shutdown boundary: do not install Node process signals there, and have the host call `app.close(signal?)` when it receives its shutdown event.
|
|
201
|
+
|
|
202
|
+
Lifecycle hooks are not the listener-close or connection-drain phase. During `app.close(signal?)`, fluo runs the shutdown hooks before `adapter.close(signal?)`; migrated cleanup that requires a closed listener or completed adapter drain belongs at the adapter or host shutdown boundary after close, not in a same-named lifecycle hook.
|
|
203
|
+
|
|
83
204
|
### Studio Devtools Bridge
|
|
84
205
|
|
|
85
|
-
`@fluojs/runtime` can publish live Studio snapshots and request traces
|
|
206
|
+
`@fluojs/runtime` can publish live Studio snapshots and request traces without reading `process.env` directly. `fluo dev --studio` remains the default Node path: the CLI starts the sidecar, creates tokenized Studio config, and injects it before the app imports runtime. Runtime reads those injected fields once, validates the HTTP(S) endpoint, and keeps a frozen private snapshot, so later mutation of the legacy process-global cannot change instrumentation inputs.
|
|
86
207
|
|
|
87
|
-
|
|
208
|
+
Package integrations can instead import `StudioDevtoolsRuntime` and its transport contracts from `@fluojs/runtime/devtools`, then pass a host-owned bridge through `studioDevtools` to `bootstrapApplication(...)`, `fluoFactory.create(...)`, or `fluoFactory.createApplicationContext(...)`. An explicit bridge takes precedence over CLI injection and needs no process-global mutation:
|
|
209
|
+
|
|
210
|
+
```typescript
|
|
211
|
+
import { fluoFactory } from '@fluojs/runtime';
|
|
212
|
+
import { StudioDevtoolsRuntime } from '@fluojs/runtime/devtools';
|
|
213
|
+
|
|
214
|
+
const studioDevtools = new StudioDevtoolsRuntime({
|
|
215
|
+
appId: 'my-bun-app',
|
|
216
|
+
runtime: 'bun',
|
|
217
|
+
transport: { publish: (event) => hostStudioTransport.send(event) },
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
const app = await fluoFactory.create(AppModule, { studioDevtools });
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
This package publishes a transport-neutral seam, not Bun, Deno, or Cloudflare Workers sidecar implementations. A non-Node host is live-Studio supported only when its owner supplies a bridge and executable host integration evidence; otherwise use the inspect/static artifact path. Live route descriptors include the exact `graphNodeId` of their route node; Runtime retains the existing node-ID format while Studio consumes this explicit correlation instead of reproducing it. Request traces intentionally omit bodies, cookies, and full headers, and runtime strips query strings/fragments from the trace `url` before publishing events so local tokens are not copied into Studio event history. Failed-request events use only the fixed `Request failed` message and never include raw exception text, names, stacks, causes, or stringified values.
|
|
88
224
|
|
|
89
225
|
### Global Exception Filters
|
|
90
226
|
|
|
@@ -108,6 +244,83 @@ const app = await fluoFactory.create(AppModule, {
|
|
|
108
244
|
});
|
|
109
245
|
```
|
|
110
246
|
|
|
247
|
+
### Content negotiation
|
|
248
|
+
|
|
249
|
+
`FluoFactory.create(...)` and `bootstrapApplication(...)` accept `contentNegotiation` and forward
|
|
250
|
+
it unchanged to the HTTP dispatcher. Configure formatters once at the application boundary and use
|
|
251
|
+
`@Produces(...)` on routes to select their allowed representations:
|
|
252
|
+
|
|
253
|
+
```typescript
|
|
254
|
+
import { Controller, Get, Produces } from '@fluojs/http';
|
|
255
|
+
import { fluoFactory } from '@fluojs/runtime';
|
|
256
|
+
|
|
257
|
+
@Controller('/reports')
|
|
258
|
+
class ReportController {
|
|
259
|
+
@Produces('application/json', 'text/plain')
|
|
260
|
+
@Get('/')
|
|
261
|
+
getReport() {
|
|
262
|
+
return { ok: true };
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
const app = await fluoFactory.create(AppModule, {
|
|
267
|
+
contentNegotiation: {
|
|
268
|
+
defaultMediaType: 'application/json',
|
|
269
|
+
formatters: [
|
|
270
|
+
{ mediaType: 'application/json', format: JSON.stringify },
|
|
271
|
+
{ mediaType: 'text/plain', format: (value) => `plain:${JSON.stringify(value)}` },
|
|
272
|
+
],
|
|
273
|
+
},
|
|
274
|
+
});
|
|
275
|
+
```
|
|
276
|
+
|
|
277
|
+
Runtime does not parse `Accept` or own response policy. `@fluojs/http` applies the documented
|
|
278
|
+
quality, wildcard, suffix, default, malformed-input, and 406 semantics and emits canonical
|
|
279
|
+
`Vary: Accept` for every successful formatter selection. Standalone application contexts do not
|
|
280
|
+
create an HTTP dispatcher, so they do not use this option. See the
|
|
281
|
+
[HTTP package contract](../http#content-negotiation).
|
|
282
|
+
|
|
283
|
+
### Optional HTML Error Representations
|
|
284
|
+
|
|
285
|
+
`FluoFactory.create(...)` and `bootstrapApplication(...)` accept `errorRepresentation` and pass it
|
|
286
|
+
unchanged to the HTTP dispatcher. Register an application-owned provider when negotiated browser
|
|
287
|
+
requests should receive complete HTML error or not-found documents while JSON remains canonical:
|
|
288
|
+
|
|
289
|
+
```typescript
|
|
290
|
+
function escapeHtml(value: string): string {
|
|
291
|
+
return value
|
|
292
|
+
.replaceAll('&', '&')
|
|
293
|
+
.replaceAll('<', '<')
|
|
294
|
+
.replaceAll('>', '>')
|
|
295
|
+
.replaceAll('"', '"')
|
|
296
|
+
.replaceAll("'", ''');
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
const app = await fluoFactory.create(AppModule, {
|
|
300
|
+
adapter: createNodejsAdapter({ port: 3000 }),
|
|
301
|
+
errorRepresentation: {
|
|
302
|
+
html: {
|
|
303
|
+
render({ json }) {
|
|
304
|
+
return `<!doctype html><main>${json.error.status}: ${escapeHtml(json.error.message)}</main>`;
|
|
305
|
+
},
|
|
306
|
+
},
|
|
307
|
+
},
|
|
308
|
+
});
|
|
309
|
+
```
|
|
310
|
+
|
|
311
|
+
Runtime only wires this option. `@fluojs/http` owns error classification, `Accept` negotiation,
|
|
312
|
+
request scope, response status and headers, `HEAD`, abort, commit, and canonical JSON fallback.
|
|
313
|
+
The returned string or bytes are trusted application HTML: runtime does not escape or sanitize
|
|
314
|
+
request-derived or error-derived values, so the provider must do so before interpolation.
|
|
315
|
+
Standalone application contexts do not use the option because they do not create an HTTP dispatcher.
|
|
316
|
+
See the [HTTP package contract](../http#http-error-representations).
|
|
317
|
+
|
|
318
|
+
### Framework-Managed and Handler-Owned Responses
|
|
319
|
+
|
|
320
|
+
The normal request path is framework-managed: a handler returns a value, interceptors may transform it, and the runtime response writer commits it. This is the path where `@fluojs/serialization` can apply `SerializerInterceptor` to a returned DTO.
|
|
321
|
+
|
|
322
|
+
Advanced handlers can instead take response ownership by calling `RequestContext.response.send(...)`, `redirect(...)`, or a manual streaming helper. Once that response is committed, `SerializerInterceptor`, when present, bypasses serialization and returns the value it received from `next.handle()` unchanged. This does not freeze the chain result: other interceptors may still transform it. Independently, the dispatcher sees the committed response and skips a second success-response write, so it does not write the final interceptor-chain result. Direct response code must therefore produce the final safe payload before committing; a serializer cannot reshape it afterward.
|
|
323
|
+
|
|
111
324
|
### Module Composition
|
|
112
325
|
|
|
113
326
|
fluo uses a strict module graph. Modules must explicitly `export` providers to make them available to `importing` modules.
|
|
@@ -128,33 +341,46 @@ class UsersModule {}
|
|
|
128
341
|
|
|
129
342
|
## Behavioral Contracts
|
|
130
343
|
|
|
131
|
-
-
|
|
132
|
-
-
|
|
344
|
+
- Runtime lifecycle remains a four-hook contract. Startup completes the provider-ordered `onModuleInit()` phase before `onApplicationBootstrap()`; shutdown reverses lifecycle-instance order for `onModuleDestroy()` and then `onApplicationShutdown(signal?)`. Every eligible singleton `multi: true` contribution participates as its own instance in contribution order. NestJS `beforeApplicationShutdown` is unsupported and has no compatibility shim.
|
|
345
|
+
- Request body parsing enforces `maxBodySize` while bytes are still streaming for both Web-standard and Node-backed requests. Oversized Web bodies settle as HTTP 413 without waiting for stream cancellation, and cancellation failures do not mask that response, including on the default cloned-body path where the original request remains unread.
|
|
346
|
+
- `preferNativeJsonBodyReader` remains accepted by `@fluojs/runtime/web` as a deprecated adapter compatibility option, but it no longer changes parsing. Web JSON bodies always use the bounded streaming reader so native whole-body reads cannot bypass `maxBodySize`.
|
|
347
|
+
- On `@fluojs/platform-nodejs`, Node request body parsing normalizes the primary `content-type` media type before JSON and multipart detection, so mixed-case JSON and multipart headers preserve the documented parser behavior.
|
|
133
348
|
- Node-backed and Web-standard request wrappers snapshot cheap request metadata before body parsing, then materialize `body`/`rawBody` once at the dispatch boundary so userland continues to observe synchronous parsed values.
|
|
134
349
|
- Node-backed cookies/query values and Web-standard headers are snapshotted when the request wrapper is created, then lazily normalized and memoized per request; later upstream object mutations do not change the `FrameworkRequest` view.
|
|
135
350
|
- Node-backed request context IDs prefer `x-request-id` and fall back to `x-correlation-id` when `x-request-id` is absent, so error responses and request-aware integrations keep the upstream correlation identifier.
|
|
136
351
|
- `ApplicationContext.get()` and `Application.get()` memoize only direct root singleton class/factory provider lookups known at bootstrap, while preserving alias, request, transient, post-close, multi-provider, and `container.override()` resolution semantics.
|
|
137
352
|
- `multi: true` provider tokens are not context-cache memoized: each `get()` call delegates to DI so the container can assemble a fresh contribution array while still reusing each contribution according to its own provider scope.
|
|
138
353
|
- When `duplicateProviderPolicy` is `warn` or `ignore`, context-cache eligibility and lifecycle hook execution are based on the effective winning provider selected by bootstrap; stale losing providers do not seed cache entries or lifecycle hooks.
|
|
354
|
+
- Module graph compilation validates runtime and `@Module(...)` provider declarations through DI's canonical normalization before cache-key generation or visibility traversal. Malformed `inject` values, dependency wrappers/tokens, and scopes therefore fail with `InvalidProviderError` instead of leaking traversal-specific errors.
|
|
139
355
|
- If application or context bootstrap fails after runtime resources or lifecycle instances have been created, fluo resets readiness, runs registered runtime cleanup callbacks, invokes shutdown hooks for instances resolved so far with `bootstrap-failed`, disposes the container, logs cleanup failures, and rethrows the original bootstrap error.
|
|
140
|
-
- `Application.listen()` and microservice `listen()` are serialized with shutdown: overlapping startup calls share the same in-flight startup, shutdown waits for in-flight startup to settle, and a startup that races with shutdown cannot transition the shell back to `ready` after close begins.
|
|
356
|
+
- `Application.listen()` and microservice `listen()` are serialized with shutdown: overlapping startup calls share the same in-flight startup, shutdown waits for in-flight startup to settle, and a startup that races with shutdown cannot transition the shell back to `ready` after close begins. The public `Application.state` contract remains `bootstrapped` or `ready` while teardown is pending and changes to `closed` only after teardown completes successfully. Independently, starting application or context close synchronously closes a terminal operation gate: `Application.get()`, `ApplicationContext.get()`, `connectMicroservice()`, `startAllMicroservices()`, and application `listen()` reject while teardown is pending and stay rejected after a failed close attempt. Provider lookups admitted immediately before close recheck that gate after asynchronous resolution and cannot return a stale value after shutdown starts. A later `close()` skips completed runtime teardown phases and re-enters incomplete adapter or lifecycle-hook stages according to their own retry contracts. Container-managed `onDestroy()` hooks are terminal best-effort cleanup: every materialized hook is attempted on the first container disposal, failed hooks are retried by a later explicit application or context `close()`, and hooks that completed successfully are never run again. Once microservice close starts, a terminal ingress gate rejects new `send()` and `emit()` calls before runtime or transport handoff, including while `listen()` is still pending and after a failed close attempt.
|
|
357
|
+
- `Application.dispatch()` uses that same synchronous terminal admission gate. A direct dispatch started after `Application.close()` begins rejects before entering the HTTP dispatcher, including while teardown is pending, after a failed close, and after successful close. A dispatch admitted before the gate closes remains dispatcher-owned and is not retroactively cancelled by close.
|
|
358
|
+
- `@fluojs/platform-nodejs` owns each pending raw Node listen operation and its `EADDRINUSE` retry timer. Calling adapter `close()` while startup is retrying cancels the retry, waits for the pending listen to settle, and prevents the listener from binding after shutdown reports completion.
|
|
141
359
|
- Shutdown signal registration failures are user-observable: `runNodeApplication(...)`, `bootstrapNodeApplication(...)`, and adapter-owned runtime helpers close the already-started application with `bootstrap-failed`, log any close failure separately, and reject with the original registration error.
|
|
142
360
|
- Shutdown signal unregistration failures do not skip application close: `app.close()` always continues through adapter shutdown, lifecycle hooks, runtime cleanup callbacks, and container disposal; if close otherwise succeeds it rejects with the unregistration error, and if close also fails it rejects with an aggregate containing both failures.
|
|
143
361
|
- Connected microservices are owned children of their parent `Application`: `startAllMicroservices()` starts them sequentially and rolls back already-started children with `bootstrap-failed` if a later child fails, while `Application.close(signal)` closes connected children before parent lifecycle hooks, adapter shutdown, and container disposal.
|
|
144
362
|
- `FluoFactory.createMicroservice()` preserves the original bootstrap/runtime-resolution error when cleanup fails and logs cleanup failures separately.
|
|
145
363
|
- Bootstrap resolves independent singleton lifecycle providers concurrently, then runs lifecycle hooks in deterministic provider order.
|
|
146
364
|
- Multipart parsing rejects payloads when the cumulative body size exceeds the configured `multipart.maxTotalSize`; runtime adapters default that limit to `maxBodySize` unless you override it.
|
|
365
|
+
- `@fluojs/runtime/web` multipart parsing uses Web-standard `TextEncoder` and `Uint8Array` primitives without requiring the Node.js `Buffer` global. Uploaded file `buffer` values are `Uint8Array`; Node-only consumers can convert them explicitly with `Buffer.from(file.buffer)` at their application boundary.
|
|
366
|
+
- `@fluojs/runtime/web` exposes two mutually exclusive multipart consumption modes: `parseMultipart(...)` buffers fields and files, while `parseMultipartStream(...)` yields discriminated field/file parts and never materializes complete file payloads. Streaming mode enforces per-field, per-file, total-size, field-count, file-count, and header limits while bytes are read; abort, cancellation, and parser failures cancel the active source. A body selected by either mode rejects a second buffered or streaming selection with `MultipartBodyConsumedError`.
|
|
147
367
|
- `createNodeHttpAdapter(...)`, `bootstrapNodeApplication(...)`, and `runNodeApplication(...)` accept `maxBodySize` only as a non-negative integer byte count and fail fast during adapter creation/bootstrap when the value is invalid.
|
|
148
368
|
- Response stream backpressure helpers settle `waitForDrain()` on `drain`, `close`, or `error` so streaming writers do not hang on dead connections.
|
|
369
|
+
- HTTP application bootstrap passes an optional application-owned `errorRepresentation.html` provider to the dispatcher without taking representation ownership. Canonical JSON remains the default; HTTP keeps classification, negotiation, status/header, `HEAD`, abort, commit, and fallback semantics.
|
|
370
|
+
- HTTP response writing is single-owner: framework-managed handler results may be transformed by interceptors before the runtime commits them. Once a handler or response helper commits `RequestContext.response`, the dispatcher skips a second success-response write. `SerializerInterceptor` bypasses serialization and returns the value it received from `next.handle()` unchanged, while other interceptors may still transform the chain result.
|
|
149
371
|
- Runtime health modules report `/ready` as `starting` with HTTP 503 until bootstrap marks them ready, and they return to `starting` as soon as application/context shutdown begins, including failed shutdown attempts.
|
|
150
372
|
- Runtime health module readiness checks receive the current `RequestContext`, allowing public integrations to resolve runtime-exposed status providers without importing internal runtime tokens.
|
|
151
373
|
- Signal-driven shutdown helpers preserve bounded drain semantics, log timeout/failure conditions, and set `process.exitCode` when shutdown does not finish cleanly, but they leave final process termination ownership to the surrounding host runtime.
|
|
152
374
|
- Platform snapshot and diagnostic issue production stay in runtime; graph viewing, filtering presentation, and Mermaid rendering are Studio-owned contracts consumed by CLI and automation callers.
|
|
153
|
-
-
|
|
375
|
+
- Compiled route inspection is a one-way projection from `HandlerDescriptor` values. Effective method, path, version, params, module, controller, and handler fields are copied into frozen entries; ordinary routes use `kind: 'http'`, while runtime-aware integrations can publish a more specific marker such as `react-page`. Route inspection never participates in matching, conflict detection, or dispatch and does not retain request body, cookie, header, query-value, or other request-private data.
|
|
376
|
+
- Runtime-connected Studio instrumentation accepts either an explicit host-owned `studioDevtools` bridge or the default CLI-injected Node config, never direct `process.env` reads. The documented `@fluojs/runtime/devtools` subpath exposes transport-neutral bridge contracts so package integrations do not need private imports or process-global mutation. Explicit bridges take precedence; CLI config is captured once into a validated, frozen private snapshot and remains the no-op fallback when neither bridge nor valid config is present.
|
|
154
377
|
- Studio request traces omit request/response bodies, cookies, and full headers; the trace `url` is sanitized to path-only form before publish so query tokens and fragments are not retained in local Studio event history.
|
|
155
378
|
- Platform component snapshots are runtime-owned contract payloads: each component reports `readiness`, `health`, dependency ids, telemetry tags, diagnostic issues, and resource ownership through `ownership.ownsResources` / `ownership.externallyManaged`. Runtime preserves those ownership flags in shell snapshots so adapters and package integrations can distinguish resources fluo must stop from externally managed resources the host owns.
|
|
156
|
-
-
|
|
379
|
+
- Runtime retains distinct lifecycle diagnostics from validation, start, rollback, and stop. Failures produced by repeatable `ready()`, `health()`, and `snapshot()` probes are bounded to the latest failure for each component and probe phase, so long-running polling cannot grow `PlatformShellSnapshot.diagnostics` without bound while the latest cause remains visible.
|
|
380
|
+
- `RuntimePlatformShell.start()` and `stop()` enforce one strictly exclusive lifecycle transition. Every overlapping operation, including a same-operation call or callback reentry after arbitrary awaits, receives an immediate `PlatformLifecycleConflictError` rejection instead of shared or queued work. The active transition is published before component work begins, failed transitions release it by identity, and explicit retry after settlement preserves sequential idempotency, dependency ordering, private startup rollback, and cleanup retry behavior.
|
|
381
|
+
- Module graph compile-result caching is opt-in through `moduleGraphCache: true`; its process-local cache retains at most 100 least-recently-used successful snapshots, keys entries by root module identity, runtime providers, validation tokens, module replacement pairs, core metadata versions, and the compile algorithm version, and returns isolated graph copies so caller mutations cannot poison later bootstraps. Hosts that need application-owned lifetime control can pass `new ModuleGraphCompileCache(maxEntries)` instead and call `dispose()` during application teardown.
|
|
157
382
|
- `moduleReplacements` is a low-level testing seam on `bootstrapModule(...)` / `BootstrapModuleOptions`. It compiles replacement module metadata while preserving the original logical module identity, rejects replacement cycles through the normal module graph validation path, and does not mutate source module metadata.
|
|
383
|
+
- `raceWithAbort(fn, signal)` always removes its abort listener once `fn` settles, including when `fn` throws synchronously before returning a promise. The synchronous throw is converted into a settled rejection so the cleanup-dependent `finally` flow still runs and the listener is not leaked across repeated failed operations.
|
|
158
384
|
|
|
159
385
|
## Public API Overview
|
|
160
386
|
|
|
@@ -163,41 +389,62 @@ class UsersModule {}
|
|
|
163
389
|
- `Application`: Extends `ApplicationContext` with `listen()`, `dispatch()`, and `state`.
|
|
164
390
|
- `ApplicationContext`: Provides `get<T>(token)`, `close()`, and access to `container`, `modules`, and bootstrap diagnostics.
|
|
165
391
|
- `LifecycleHooks`: Convenience union covering `OnModuleInit`, `OnApplicationBootstrap`, `OnModuleDestroy`, and `OnApplicationShutdown`.
|
|
166
|
-
- `
|
|
392
|
+
- `MicroserviceRuntime`: Transport contract resolved by `FluoFactory.createMicroservice(...)`. Implementations expose `listen()`, optional `send()`/`emit()`, and an optional `close(signal?)`. The optional `markShutdownStarted()` hook is invoked synchronously when the owning shell begins shutdown so implementations can close their own ingress gate before any awaited cleanup, keeping new `send()`/`emit()`/`listen()` attempts rejected even while a racing `listen()` is still settling.
|
|
393
|
+
- `HealthModule.forRoot(options)`: Runtime-owned `/health` and `/ready` module facade whose readiness marker follows bootstrap and shutdown lifecycle transitions. It returns a `RuntimeHealthModule` so first-party runtime-aware packages can register `ReadinessCheck` functions without importing internal runtime seams.
|
|
167
394
|
- `createHealthModule(options)`: Deprecated compatibility helper for the same runtime health module contract; prefer `HealthModule.forRoot(...)` in application-facing module imports.
|
|
395
|
+
- `RuntimeHealthModule`: Module class contract returned by `HealthModule.forRoot(...)`, including `addReadinessCheck(...)`, `markReady()`, and `markStarting()`.
|
|
168
396
|
- `ReadinessCheck`: Function type used by runtime health modules. Checks receive the `/ready` request context and return a boolean or promise.
|
|
169
397
|
- `defineModule(cls, metadata)`: Programmatic module definition helper.
|
|
170
|
-
- `bootstrapApplication(options)`: Lower-level async bootstrap function.
|
|
398
|
+
- `bootstrapApplication(options)`: Lower-level async bootstrap function. `BootstrapApplicationOptions.errorRepresentation` registers the optional HTTP-owned HTML representation provider and `BootstrapApplicationOptions.conditionalRequest` configures representation validation; `CreateApplicationOptions` exposes both fields through `FluoFactory.create(...)`.
|
|
399
|
+
- `@fluojs/runtime/devtools`: Package-integration subpath for `StudioDevtoolsRuntime`, its transport contracts, and live Studio event contracts. Pass the created bridge as `studioDevtools` during application or context bootstrap.
|
|
171
400
|
- `bootstrapModule(...)`: Lower-level module graph bootstrap helper. Its `BootstrapModuleOptions` include `moduleGraphCache` for opt-in compile-result caching and `moduleReplacements` / `ModuleReplacementMap` for testing-only module replacement compilation that keeps authored module identities stable.
|
|
401
|
+
- `ModuleGraphCompileCache`: Bounded caller-owned module graph compile cache. Pass an instance as `moduleGraphCache` and call `dispose()` when its application or host lifetime ends.
|
|
172
402
|
- `createBootstrapTimingDiagnostics(...)`, `createRuntimeDiagnosticsGraph(...)`: Runtime-owned diagnostics snapshot helpers for CLI/support tooling. They produce machine-readable data; Studio owns viewer parsing, graph presentation, and Mermaid rendering.
|
|
403
|
+
- `createRuntimeRouteInspection(...)`, `createRuntimeRouteCatalog(...)`, and `createRuntimeInspectionSnapshot(...)`: Runtime-owned immutable projections that add effective compiled route diagnostics to platform snapshots without changing HTTP route behavior.
|
|
404
|
+
- `RuntimeRouteInspection` and `RuntimeInspectionSnapshot`: Serializable read-only route and inspect artifact contracts. `RuntimeRouteInspection.params` contains parameter names only, never request values.
|
|
173
405
|
- `PlatformShell`, `PlatformComponent`, `PlatformShellSnapshot`, `PlatformSnapshot`, `PlatformDiagnosticIssue`, and related platform report types: Public lifecycle diagnostics and resource-ownership contracts used by runtime-aware packages. `RuntimePlatformShell` preserves component-provided ownership and emits validation/readiness/health diagnostics without requiring consumers to import internal runtime tokens.
|
|
406
|
+
- `PlatformLifecycleOperation`, `PlatformLifecycleConflictError`: Root-exported lifecycle conflict contracts. The error uses code `PLATFORM_LIFECYCLE_CONFLICT` and exposes matching `activeOperation` / `requestedOperation` fields and structured metadata.
|
|
174
407
|
- `createRequestAbortContext(...)`, `trackActiveRequestTransaction(...)`, `untrackActiveRequestTransaction(...)`: Request abort and active transaction helpers used by runtime-aware integrations.
|
|
408
|
+
- `UploadedFile`: Runtime-neutral multipart file descriptor whose in-memory `buffer` payload is a Web-standard `Uint8Array`.
|
|
409
|
+
- `MultipartFieldPart`, `MultipartFilePart`, `MultipartPart`, and `MultipartBodyConsumedError`: Typed streaming multipart contracts. `MultipartFilePart.stream` is single-consumer and must settle before iteration requests the following part.
|
|
410
|
+
|
|
411
|
+
## Runtime-Specific Entry Points
|
|
175
412
|
|
|
176
|
-
|
|
413
|
+
Use `@fluojs/platform-nodejs` for Node-host responsibilities and `@fluojs/runtime/web` for portable Web-standard helpers. Runtime's published `internal*` subpaths remain runtime-neutral package-integration seams for first-party adapters and runtime-aware packages.
|
|
414
|
+
|
|
415
|
+
Migration is direct and intentionally has no compatibility shim:
|
|
416
|
+
|
|
417
|
+
| Removed import | Replacement |
|
|
418
|
+
| :--- | :--- |
|
|
419
|
+
| `@fluojs/runtime/node` | `@fluojs/platform-nodejs` |
|
|
420
|
+
| `@fluojs/runtime/internal-node` | `@fluojs/platform-nodejs/internal` |
|
|
177
421
|
|
|
178
|
-
|
|
422
|
+
Every moved symbol keeps its existing name at the replacement entrypoint; `@fluojs/platform-nodejs` also retains its established `Nodejs*` aliases.
|
|
179
423
|
|
|
180
424
|
| Subpath | Purpose |
|
|
181
425
|
| :--- | :--- |
|
|
182
|
-
| `@fluojs/
|
|
183
|
-
| `@fluojs/runtime/web` | Shared Web-standard request/response utilities for Bun, Deno, and Cloudflare Workers, including `createWebRequestResponseFactory`, `dispatchWebRequest`, `createWebFrameworkRequest`, and `
|
|
184
|
-
| `@fluojs/runtime/internal` | Internal package-integration seam for runtime wiring tokens
|
|
185
|
-
| `@fluojs/
|
|
426
|
+
| `@fluojs/platform-nodejs` | Supported Node.js entrypoint for logger factories, Node adapter/bootstrap helpers, and shutdown signal registration. |
|
|
427
|
+
| `@fluojs/runtime/web` | Shared Web-standard request/response utilities for Bun, Deno, and Cloudflare Workers, including `createWebRequestResponseFactory`, `dispatchWebRequest`, `createWebFrameworkRequest`, buffered `parseMultipart`, and streaming `parseMultipartStream`. |
|
|
428
|
+
| `@fluojs/runtime/internal` | Internal package-integration seam for runtime wiring tokens, runtime-owned metadata and route-inspection helpers, plus `defineModule(...)` and `createRuntimeRouteInspection(...)` for first-party runtime-neutral integrations that must align with compiled runtime descriptors. |
|
|
429
|
+
| `@fluojs/platform-nodejs/internal` | Node-only internal seam for adapter/runtime plumbing; prefer `@fluojs/platform-nodejs` in application code. |
|
|
186
430
|
| `@fluojs/runtime/internal/http-adapter` | Internal HTTP adapter seam for platform packages. |
|
|
187
431
|
| `@fluojs/runtime/internal/request-response-factory` | Internal request/response factory seam for platform packages. |
|
|
188
432
|
|
|
189
|
-
### Node-Specific
|
|
433
|
+
### Node-Specific Package (`@fluojs/platform-nodejs`)
|
|
190
434
|
|
|
191
|
-
Logger factories and other supported Node-only helpers are **not** on the
|
|
435
|
+
Logger factories, `createNodeFileSystemAssetSource({ root, precompressed })` for eager immutable Node/Express/Fastify static asset snapshots, and other supported Node-only helpers are **not** on the portable runtime root. Import them from the Node platform package:
|
|
192
436
|
|
|
193
437
|
```typescript
|
|
194
438
|
import {
|
|
195
439
|
bootstrapNodeApplication,
|
|
196
440
|
createConsoleApplicationLogger,
|
|
197
441
|
createJsonApplicationLogger,
|
|
442
|
+
createNodeFileSystemAssetSource,
|
|
198
443
|
createNodeHttpAdapter,
|
|
199
444
|
runNodeApplication,
|
|
200
|
-
|
|
445
|
+
type NodeFileSystemAssetPrecompression,
|
|
446
|
+
type NodeFileSystemAssetSourceOptions,
|
|
447
|
+
} from '@fluojs/platform-nodejs';
|
|
201
448
|
```
|
|
202
449
|
|
|
203
450
|
```typescript
|
|
@@ -211,6 +458,7 @@ For the public Node runtime surface, `maxBodySize`, `retryDelayMs`, `retryLimit`
|
|
|
211
458
|
|
|
212
459
|
- `createConsoleApplicationLogger()`: Colorized console logger using `process.stdout`/`process.stderr`. The default remains the pretty format. Pass `{ mode: 'minimal' }` for concise `[fluo] LEVEL [context] message` lines, `{ mode: 'silent' }` to suppress runtime logger output, `{ level: 'warn' }` or another threshold to filter lower-severity messages, and `{ color: false }` when you need deterministic non-colored output.
|
|
213
460
|
- `createJsonApplicationLogger()`: Structured JSON logger using `process.stdout`/`process.stderr`.
|
|
461
|
+
- `createNodeFileSystemAssetSource(options)`: Node-only filesystem implementation of the `@fluojs/http` `StaticAssetSource` contract. `NodeFileSystemAssetSourceOptions` names its `{ root, precompressed }` boundary and `NodeFileSystemAssetPrecompression` selects `.br` / `.gz` siblings. Each accepted representation is securely opened, eagerly copied into an immutable in-memory byte snapshot, and its `FileHandle` is closed before middleware response writing. The returned `source()` only replays that snapshot; it never reopens the pathname. Application owners therefore bound memory by the selected asset size, while `size` and the strong `ETag` describe those exact snapshot bytes.
|
|
214
462
|
- `createNodeHttpAdapter()`: Raw Node `http`/`https` adapter factory for adapter-first runtime setup. The helper normalizes the primary Node request `content-type` before JSON/multipart detection and accepts `maxBodySize`, `retryDelayMs`, `retryLimit`, and `shutdownTimeoutMs` only as non-negative integers.
|
|
215
463
|
- `bootstrapNodeApplication()` / `runNodeApplication()`: Node-specific bootstrap helpers used by direct Node runtime flows.
|
|
216
464
|
- `createNodeShutdownSignalRegistration()`, `defaultNodeShutdownSignals()`, `registerShutdownSignals()`: Shutdown registration helpers for hosts that need explicit signal wiring.
|
|
@@ -218,7 +466,7 @@ For the public Node runtime surface, `maxBodySize`, `retryDelayMs`, `retryLimit`
|
|
|
218
466
|
Runtime app logging is separate from CLI lifecycle reporting. Configure `ApplicationLogger` when you want to change logs emitted by the application/runtime itself:
|
|
219
467
|
|
|
220
468
|
```typescript
|
|
221
|
-
import { createConsoleApplicationLogger, createJsonApplicationLogger } from '@fluojs/
|
|
469
|
+
import { createConsoleApplicationLogger, createJsonApplicationLogger } from '@fluojs/platform-nodejs';
|
|
222
470
|
|
|
223
471
|
const minimalLogger = createConsoleApplicationLogger({ mode: 'minimal', level: 'warn' });
|
|
224
472
|
const jsonLogger = createJsonApplicationLogger();
|
|
@@ -226,13 +474,36 @@ const jsonLogger = createJsonApplicationLogger();
|
|
|
226
474
|
|
|
227
475
|
Use CLI reporter flags such as `fluo dev --verbose` when you need raw child-process output from the development command instead.
|
|
228
476
|
|
|
229
|
-
|
|
477
|
+
### Node Compression Failure Migration
|
|
478
|
+
|
|
479
|
+
**Breaking change:** When response compression fails before a Node response commits,
|
|
480
|
+
`FrameworkResponse.send()` rejects. Adapter integrations must await that promise and handle the
|
|
481
|
+
rejection; they must not swallow it or assume that an uncompressed success response was sent.
|
|
482
|
+
|
|
483
|
+
For dispatcher-managed requests, the runtime recovers by writing its JSON 500 envelope. The
|
|
484
|
+
adapter removes a `Content-Type` it assigned for the failed body so the envelope uses
|
|
485
|
+
`application/json`; an explicit `Content-Type` set by application code remains unchanged.
|
|
486
|
+
Consumers that relied on a fulfilled `send()` or a stale adapter-assigned `text/plain` or
|
|
487
|
+
`application/octet-stream` header must handle the rejection or fallback explicitly and set any
|
|
488
|
+
required application-owned header themselves.
|
|
489
|
+
|
|
490
|
+
Lower-level Node compression internals stay behind the `@fluojs/platform-nodejs/internal` seam rather than the public `@fluojs/platform-nodejs` contract.
|
|
491
|
+
|
|
492
|
+
### Runtime Cleanup Callbacks
|
|
493
|
+
|
|
494
|
+
Providers that receive the internal `RUNTIME_CLEANUP_REGISTRATION` token may register cleanup
|
|
495
|
+
callbacks that return `void` or `Promise<void>`. Runtime close and bootstrap-failure cleanup run
|
|
496
|
+
the callbacks in registration order and await each one before entering later cleanup phases.
|
|
497
|
+
Failures do not prevent later callbacks from running: `close()` aggregates cleanup failures and
|
|
498
|
+
leaves that incomplete phase eligible for an explicit retry, while bootstrap preserves its original
|
|
499
|
+
failure and reports cleanup failures through `ApplicationLogger`.
|
|
230
500
|
|
|
231
501
|
## Related Packages
|
|
232
502
|
|
|
233
503
|
- [@fluojs/core](../core): Core decorators and metadata system.
|
|
234
504
|
- [@fluojs/di](../di): Dependency injection container implementation.
|
|
235
505
|
- [@fluojs/http](../http): HTTP routing, controllers, and dispatcher.
|
|
506
|
+
- [@fluojs/serialization](../serialization): Decorator-aware shaping for framework-managed, uncommitted HTTP handler results.
|
|
236
507
|
- [@fluojs/platform-nodejs](../platform-nodejs): Official Node.js HTTP adapter.
|
|
237
508
|
- [@fluojs/studio](../studio): Viewer, filtering, and rendering helpers for runtime-produced snapshots and diagnostic issues.
|
|
238
509
|
|
package/dist/abort.d.ts
CHANGED
|
@@ -3,10 +3,15 @@
|
|
|
3
3
|
* Rejects immediately if the signal is already aborted, or rejects as soon
|
|
4
4
|
* as the signal fires while `fn` is still pending.
|
|
5
5
|
*
|
|
6
|
+
* The abort listener is always removed once `fn` settles, including when
|
|
7
|
+
* `fn` throws synchronously before returning a promise. The synchronous
|
|
8
|
+
* throw is converted into a settled rejection so the cleanup-dependent
|
|
9
|
+
* `finally` flow still runs.
|
|
10
|
+
*
|
|
6
11
|
* @param fn Async operation to execute while observing the abort signal.
|
|
7
12
|
* @param signal Abort signal that can cancel the in-flight operation.
|
|
8
13
|
* @returns The resolved value from `fn` when no abort happens first.
|
|
9
|
-
* @throws {Error} An `AbortError` when the signal is already aborted or aborts before `fn` settles.
|
|
14
|
+
* @throws {Error} An `AbortError` when the signal is already aborted or aborts before `fn` settles. Re-throws the original error when `fn` throws synchronously.
|
|
10
15
|
*/
|
|
11
16
|
export declare function raceWithAbort<T>(fn: () => Promise<T>, signal: AbortSignal): Promise<T>;
|
|
12
17
|
/**
|
package/dist/abort.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"abort.d.ts","sourceRoot":"","sources":["../src/abort.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"abort.d.ts","sourceRoot":"","sources":["../src/abort.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,wBAAsB,aAAa,CAAC,CAAC,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,WAAW,GAAG,OAAO,CAAC,CAAC,CAAC,CA2B5F;AAED;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,OAAO,GAAG,KAAK,CAKvD"}
|
package/dist/abort.js
CHANGED
|
@@ -3,10 +3,15 @@
|
|
|
3
3
|
* Rejects immediately if the signal is already aborted, or rejects as soon
|
|
4
4
|
* as the signal fires while `fn` is still pending.
|
|
5
5
|
*
|
|
6
|
+
* The abort listener is always removed once `fn` settles, including when
|
|
7
|
+
* `fn` throws synchronously before returning a promise. The synchronous
|
|
8
|
+
* throw is converted into a settled rejection so the cleanup-dependent
|
|
9
|
+
* `finally` flow still runs.
|
|
10
|
+
*
|
|
6
11
|
* @param fn Async operation to execute while observing the abort signal.
|
|
7
12
|
* @param signal Abort signal that can cancel the in-flight operation.
|
|
8
13
|
* @returns The resolved value from `fn` when no abort happens first.
|
|
9
|
-
* @throws {Error} An `AbortError` when the signal is already aborted or aborts before `fn` settles.
|
|
14
|
+
* @throws {Error} An `AbortError` when the signal is already aborted or aborts before `fn` settles. Re-throws the original error when `fn` throws synchronously.
|
|
10
15
|
*/
|
|
11
16
|
export async function raceWithAbort(fn, signal) {
|
|
12
17
|
if (signal.aborted) {
|
|
@@ -19,7 +24,18 @@ export async function raceWithAbort(fn, signal) {
|
|
|
19
24
|
signal.addEventListener('abort', onAbort, {
|
|
20
25
|
once: true
|
|
21
26
|
});
|
|
22
|
-
|
|
27
|
+
|
|
28
|
+
// Convert `fn()` invocation into a settled promise so a synchronous
|
|
29
|
+
// throw still flows through the `finally` cleanup that removes the
|
|
30
|
+
// abort listener. `Promise.resolve()` only wraps an already-produced
|
|
31
|
+
// value; it does not catch a throw emitted while `fn()` is invoked.
|
|
32
|
+
let fnResultPromise;
|
|
33
|
+
try {
|
|
34
|
+
fnResultPromise = Promise.resolve(fn());
|
|
35
|
+
} catch (syncError) {
|
|
36
|
+
fnResultPromise = Promise.reject(syncError);
|
|
37
|
+
}
|
|
38
|
+
fnResultPromise.then(resolve, reject).finally(() => {
|
|
23
39
|
signal.removeEventListener('abort', onAbort);
|
|
24
40
|
});
|
|
25
41
|
});
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export { dispatchWithRequestResponseFactory, type DispatchWithRequestResponseFactoryOptions, type RequestResponseFactory, } from './request-response-factory.js';
|
|
1
|
+
export { dispatchWithRequestResponseFactory, finalizeRouteOwnedMultipartBody, type DispatchWithRequestResponseFactoryOptions, type RequestResponseFactory, } from './request-response-factory.js';
|
|
2
2
|
//# sourceMappingURL=internal-request-response-factory.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"internal-request-response-factory.d.ts","sourceRoot":"","sources":["../../src/adapters/internal-request-response-factory.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kCAAkC,EAClC,KAAK,yCAAyC,EAC9C,KAAK,sBAAsB,GAC5B,MAAM,+BAA+B,CAAC"}
|
|
1
|
+
{"version":3,"file":"internal-request-response-factory.d.ts","sourceRoot":"","sources":["../../src/adapters/internal-request-response-factory.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kCAAkC,EAClC,+BAA+B,EAC/B,KAAK,yCAAyC,EAC9C,KAAK,sBAAsB,GAC5B,MAAM,+BAA+B,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export { dispatchWithRequestResponseFactory } from './request-response-factory.js';
|
|
1
|
+
export { dispatchWithRequestResponseFactory, finalizeRouteOwnedMultipartBody } from './request-response-factory.js';
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { Dispatcher, FrameworkRequest, FrameworkResponse } from '@fluojs/http';
|
|
1
|
+
import type { Dispatcher, FrameworkRequest, FrameworkResponse } from '@fluojs/http/portable';
|
|
2
2
|
/** Request/response factory seam used by shared HTTP adapter dispatch helpers. */
|
|
3
3
|
export interface RequestResponseFactory<RawRequest, RawResponse, Response extends FrameworkResponse = FrameworkResponse> {
|
|
4
4
|
createRequest(rawRequest: RawRequest, signal: AbortSignal): Promise<FrameworkRequest>;
|
|
@@ -16,6 +16,18 @@ export interface DispatchWithRequestResponseFactoryOptions<RawRequest, RawRespon
|
|
|
16
16
|
rawRequest: RawRequest;
|
|
17
17
|
rawResponse: RawResponse;
|
|
18
18
|
}
|
|
19
|
+
/** An in-progress factory dispatch with its response shell available immediately. */
|
|
20
|
+
export interface StartedRequestResponseFactoryDispatch<Response extends FrameworkResponse> {
|
|
21
|
+
readonly completion: Promise<Response>;
|
|
22
|
+
readonly response: Response;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Starts one raw platform request dispatch while exposing its mutable response shell.
|
|
26
|
+
*
|
|
27
|
+
* @param options - Factory, dispatcher, and raw platform request/response values for one dispatch.
|
|
28
|
+
* @returns The response shell and its independently settling dispatch lifecycle.
|
|
29
|
+
*/
|
|
30
|
+
export declare function startDispatchWithRequestResponseFactory<RawRequest, RawResponse, Response extends FrameworkResponse = FrameworkResponse>({ dispatcher, dispatcherNotReadyMessage, factory, rawRequest, rawResponse, }: DispatchWithRequestResponseFactoryOptions<RawRequest, RawResponse, Response>): StartedRequestResponseFactoryDispatch<Response>;
|
|
19
31
|
/**
|
|
20
32
|
* Dispatches one raw platform request through the shared request/response factory lifecycle.
|
|
21
33
|
*
|
|
@@ -23,4 +35,11 @@ export interface DispatchWithRequestResponseFactoryOptions<RawRequest, RawRespon
|
|
|
23
35
|
* @returns The framework response after dispatch, error serialization, or default finalization.
|
|
24
36
|
*/
|
|
25
37
|
export declare function dispatchWithRequestResponseFactory<RawRequest, RawResponse, Response extends FrameworkResponse = FrameworkResponse>({ dispatcher, dispatcherNotReadyMessage, factory, rawRequest, rawResponse, }: DispatchWithRequestResponseFactoryOptions<RawRequest, RawResponse, Response>): Promise<Response>;
|
|
38
|
+
/**
|
|
39
|
+
* Finalizes a route-owned multipart body iterator after dispatch completes.
|
|
40
|
+
*
|
|
41
|
+
* @param request Framework request whose multipart body may need finalization.
|
|
42
|
+
* @returns A promise that resolves after the iterator has been returned when applicable.
|
|
43
|
+
*/
|
|
44
|
+
export declare function finalizeRouteOwnedMultipartBody(request: FrameworkRequest | undefined): Promise<void>;
|
|
26
45
|
//# sourceMappingURL=request-response-factory.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"request-response-factory.d.ts","sourceRoot":"","sources":["../../src/adapters/request-response-factory.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"request-response-factory.d.ts","sourceRoot":"","sources":["../../src/adapters/request-response-factory.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAE7F,kFAAkF;AAClF,MAAM,WAAW,sBAAsB,CACrC,UAAU,EACV,WAAW,EACX,QAAQ,SAAS,iBAAiB,GAAG,iBAAiB;IAEtD,aAAa,CAAC,UAAU,EAAE,UAAU,EAAE,MAAM,EAAE,WAAW,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAAC;IACtF,mBAAmB,CAAC,WAAW,EAAE,WAAW,GAAG,WAAW,CAAC;IAC3D,cAAc,CAAC,WAAW,EAAE,WAAW,EAAE,UAAU,EAAE,UAAU,GAAG,QAAQ,CAAC;IAC3E,kBAAkB,CAAC,CAAC,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC9D,gBAAgB,CAAC,UAAU,EAAE,UAAU,GAAG,MAAM,GAAG,SAAS,CAAC;IAC7D,kBAAkB,CAAC,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,SAAS,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAC3F;AAED,2FAA2F;AAC3F,MAAM,WAAW,yCAAyC,CACxD,UAAU,EACV,WAAW,EACX,QAAQ,SAAS,iBAAiB,GAAG,iBAAiB;IAEtD,UAAU,CAAC,EAAE,UAAU,CAAC;IACxB,yBAAyB,EAAE,MAAM,CAAC;IAClC,OAAO,EAAE,sBAAsB,CAAC,UAAU,EAAE,WAAW,EAAE,QAAQ,CAAC,CAAC;IACnE,UAAU,EAAE,UAAU,CAAC;IACvB,WAAW,EAAE,WAAW,CAAC;CAC1B;AAED,qFAAqF;AACrF,MAAM,WAAW,qCAAqC,CAAC,QAAQ,SAAS,iBAAiB;IACvF,QAAQ,CAAC,UAAU,EAAE,OAAO,CAAC,QAAQ,CAAC,CAAC;IACvC,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC;CAC7B;AAED;;;;;GAKG;AACH,wBAAgB,uCAAuC,CACrD,UAAU,EACV,WAAW,EACX,QAAQ,SAAS,iBAAiB,GAAG,iBAAiB,EACtD,EACA,UAAU,EACV,yBAAyB,EACzB,OAAO,EACP,UAAU,EACV,WAAW,GACZ,EAAE,yCAAyC,CAAC,UAAU,EAAE,WAAW,EAAE,QAAQ,CAAC,GAAG,qCAAqC,CAAC,QAAQ,CAAC,CAqChI;AAED;;;;;GAKG;AACH,wBAAsB,kCAAkC,CACtD,UAAU,EACV,WAAW,EACX,QAAQ,SAAS,iBAAiB,GAAG,iBAAiB,EACtD,EACA,UAAU,EACV,yBAAyB,EACzB,OAAO,EACP,UAAU,EACV,WAAW,GACZ,EAAE,yCAAyC,CAAC,UAAU,EAAE,WAAW,EAAE,QAAQ,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAQlG;AAED;;;;;GAKG;AACH,wBAAsB,+BAA+B,CAAC,OAAO,EAAE,gBAAgB,GAAG,SAAS,GAAG,OAAO,CAAC,IAAI,CAAC,CAY1G"}
|