isr-engine 3.1.1 → 3.1.3
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/dist/cli/cli.js +1 -1
- package/dist/config/loadConfig.d.ts.map +1 -1
- package/dist/{createCacheInspectorMiddleware-BpMpmP_a.js → createCacheInspectorMiddleware-GgzKVkq2.js} +2 -2
- package/dist/{createCacheInspectorMiddleware-BpMpmP_a.js.map → createCacheInspectorMiddleware-GgzKVkq2.js.map} +1 -1
- package/dist/{createISRApp-D88Xp0Fb.js → createISRApp-DPD3Er4F.js} +25 -33
- package/dist/createISRApp-DPD3Er4F.js.map +1 -0
- package/dist/{createImagePlugin-Cdz3QfrJ.js → createImagePlugin-QNvY9vPB.js} +2 -2
- package/dist/{createImagePlugin-Cdz3QfrJ.js.map → createImagePlugin-QNvY9vPB.js.map} +1 -1
- package/dist/defaults/runtime/seo-runtime.d.ts +2 -0
- package/dist/defaults/runtime/seo-runtime.d.ts.map +1 -1
- package/dist/isr-engine.js +3 -3
- package/dist/isr-engine.js.map +1 -1
- package/dist/runtime/routes.d.ts +18 -2
- package/dist/runtime/routes.d.ts.map +1 -1
- package/package.json +20 -28
- package/src/defaults/runtime/defineClientEntry.tsx +26 -15
- package/src/defaults/runtime/defineServerEntry.tsx +47 -44
- package/src/defaults/runtime/request.tsx +2 -2
- package/src/defaults/runtime/seo-runtime.ts +26 -30
- package/src/runtime/routes.tsx +102 -94
- package/dist/Logger-DqBS_3v8.cjs +0 -184
- package/dist/Logger-DqBS_3v8.cjs.map +0 -1
- package/dist/abVariantContext-BvAMuhjj.cjs +0 -510
- package/dist/abVariantContext-BvAMuhjj.cjs.map +0 -1
- package/dist/adapters/observability/index.cjs +0 -152
- package/dist/adapters/observability/index.cjs.map +0 -1
- package/dist/adapters/runtime/index.cjs +0 -100
- package/dist/adapters/runtime/index.cjs.map +0 -1
- package/dist/cli/cli.cjs +0 -372
- package/dist/cli/cli.cjs.map +0 -1
- package/dist/config/defineConfig.cjs +0 -26
- package/dist/config/defineConfig.cjs.map +0 -1
- package/dist/createCacheInspectorMiddleware-DvRhF_-D.cjs +0 -112
- package/dist/createCacheInspectorMiddleware-DvRhF_-D.cjs.map +0 -1
- package/dist/createISRApp-D88Xp0Fb.js.map +0 -1
- package/dist/createISRApp-tRkpdmpp.cjs +0 -8232
- package/dist/createISRApp-tRkpdmpp.cjs.map +0 -1
- package/dist/createImagePlugin-DomuzpoI.cjs +0 -487
- package/dist/createImagePlugin-DomuzpoI.cjs.map +0 -1
- package/dist/defaults/auto-observability.cjs +0 -147
- package/dist/defaults/auto-observability.cjs.map +0 -1
- package/dist/defaults/runtime/defineSiteHooks.cjs +0 -11
- package/dist/defineSiteHooks-BuhvW5YB.cjs +0 -770
- package/dist/defineSiteHooks-BuhvW5YB.cjs.map +0 -1
- package/dist/error500-template-BvZmvKoa.cjs +0 -63
- package/dist/error500-template-BvZmvKoa.cjs.map +0 -1
- package/dist/i18n-CS5QhOO0.cjs +0 -221
- package/dist/i18n-CS5QhOO0.cjs.map +0 -1
- package/dist/image/index.cjs +0 -93
- package/dist/image/index.cjs.map +0 -1
- package/dist/isr-engine.cjs +0 -3332
- package/dist/isr-engine.cjs.map +0 -1
- package/dist/rolldown-runtime-DakpK96I.cjs +0 -43
- package/dist/rsc/browser.cjs +0 -109
- package/dist/rsc/browser.cjs.map +0 -1
- package/dist/rsc/index.cjs +0 -32
- package/dist/rsc-CYT6B6bf.cjs +0 -237
- package/dist/rsc-CYT6B6bf.cjs.map +0 -1
package/src/runtime/routes.tsx
CHANGED
|
@@ -43,7 +43,7 @@ import * as React from 'react';
|
|
|
43
43
|
import type { PageSeoMeta } from '../defaults/runtime/seo-runtime';
|
|
44
44
|
|
|
45
45
|
declare global {
|
|
46
|
-
var
|
|
46
|
+
var __ISR_ENGINE_COMPILED_ROUTE_MANIFESTS__: Map<ResolveRoute, CompiledManifest> | undefined;
|
|
47
47
|
}
|
|
48
48
|
|
|
49
49
|
/** 路由匹配后传给 page 的 props */
|
|
@@ -77,7 +77,7 @@ export interface RouteEntry extends RouteModuleRef {
|
|
|
77
77
|
|
|
78
78
|
export interface RouteManifest {
|
|
79
79
|
routes: readonly RouteEntry[];
|
|
80
|
-
/**
|
|
80
|
+
/** 路由未匹配时渲染此模块,使用其 seo 导出并返回 HTTP 404。 */
|
|
81
81
|
notFound?: RouteModuleRef;
|
|
82
82
|
}
|
|
83
83
|
|
|
@@ -98,10 +98,25 @@ export type PageSeoExport =
|
|
|
98
98
|
ctx: PageSeoContext
|
|
99
99
|
) => PageSeoMeta | null | undefined | Promise<PageSeoMeta | null | undefined>);
|
|
100
100
|
|
|
101
|
-
interface
|
|
101
|
+
interface PreparedPage {
|
|
102
|
+
ref: RouteModuleRef;
|
|
103
|
+
Component: PageComponent;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
interface CompiledRoute extends PreparedPage {
|
|
102
107
|
re: RegExp;
|
|
103
108
|
keys: string[];
|
|
104
|
-
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
interface CompiledManifest {
|
|
112
|
+
routes: CompiledRoute[];
|
|
113
|
+
notFound?: PreparedPage;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
interface RouteMatch {
|
|
117
|
+
page: PreparedPage;
|
|
118
|
+
params: Record<string, string>;
|
|
119
|
+
notFound?: true;
|
|
105
120
|
}
|
|
106
121
|
|
|
107
122
|
function compile(path: string): { re: RegExp; keys: string[] } {
|
|
@@ -124,112 +139,105 @@ export type ResolveRoute = (ctx: {
|
|
|
124
139
|
searchParams: URLSearchParams;
|
|
125
140
|
}) => React.ReactNode;
|
|
126
141
|
|
|
127
|
-
function
|
|
128
|
-
ref
|
|
129
|
-
label: string,
|
|
130
|
-
exportName = 'default',
|
|
131
|
-
fallbackExport?: string
|
|
132
|
-
): PageComponent {
|
|
133
|
-
const requestedExport = ref.export ?? exportName;
|
|
134
|
-
return React.lazy(async () => {
|
|
135
|
-
const mod = await ref.load();
|
|
136
|
-
const exports = mod as Record<string, unknown>;
|
|
137
|
-
const component =
|
|
138
|
-
exports[requestedExport] ?? (fallbackExport ? exports[fallbackExport] : undefined);
|
|
139
|
-
if (!component) {
|
|
140
|
-
throw new Error(`Route component "${label}" does not export "${requestedExport}"`);
|
|
141
|
-
}
|
|
142
|
-
return { default: component as PageComponent };
|
|
143
|
-
});
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
function resolvePageComponent(route: RouteEntry): PageComponent {
|
|
147
|
-
return resolveRouteComponent(route, route.path);
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
function createRouteResolver(
|
|
151
|
-
routes: readonly RouteEntry[],
|
|
152
|
-
notFound?: RouteModuleRef
|
|
153
|
-
): ResolveRoute {
|
|
154
|
-
const compiled: CompiledRoute[] = routes.map(r => ({
|
|
155
|
-
...r,
|
|
156
|
-
Component: resolvePageComponent(r),
|
|
157
|
-
...compile(r.path),
|
|
158
|
-
}));
|
|
159
|
-
const NotFound = notFound ? resolveRouteComponent(notFound, '__not_found__') : undefined;
|
|
160
|
-
|
|
161
|
-
return function resolveRoute({ pathname, searchParams }) {
|
|
162
|
-
const clean = trimTrailingSlashes(pathname) || '/';
|
|
163
|
-
for (const route of compiled) {
|
|
164
|
-
const m = route.re.exec(clean);
|
|
165
|
-
if (!m) continue;
|
|
166
|
-
const params: Record<string, string> = {};
|
|
167
|
-
route.keys.forEach((k, i) => {
|
|
168
|
-
params[k] = decodeURIComponent(m[i + 1] ?? '');
|
|
169
|
-
});
|
|
170
|
-
const Page = route.Component;
|
|
171
|
-
return <Page pathname={clean} searchParams={searchParams} params={params} />;
|
|
172
|
-
}
|
|
173
|
-
if (NotFound) {
|
|
174
|
-
return <NotFound pathname={clean} searchParams={searchParams} params={{}} />;
|
|
175
|
-
}
|
|
176
|
-
return null;
|
|
177
|
-
};
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
function createDefinedRoutes(config: RouteManifest): DefinedRoutes {
|
|
181
|
-
registerRouteManifest(config);
|
|
142
|
+
function preparePage(ref: RouteModuleRef, label: string): PreparedPage {
|
|
143
|
+
const exportName = ref.export ?? 'default';
|
|
182
144
|
return {
|
|
183
|
-
|
|
145
|
+
ref,
|
|
146
|
+
Component: React.lazy(async () => {
|
|
147
|
+
const mod = (await ref.load()) as Record<string, unknown>;
|
|
148
|
+
const component = mod[exportName];
|
|
149
|
+
if (!component) {
|
|
150
|
+
throw new Error(`Route component "${label}" does not export "${exportName}"`);
|
|
151
|
+
}
|
|
152
|
+
return { default: component as PageComponent };
|
|
153
|
+
}),
|
|
184
154
|
};
|
|
185
155
|
}
|
|
186
156
|
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
157
|
+
function matchRoute(manifest: CompiledManifest, pathname: string): RouteMatch | undefined {
|
|
158
|
+
for (const route of manifest.routes) {
|
|
159
|
+
const match = route.re.exec(pathname);
|
|
160
|
+
if (!match) continue;
|
|
161
|
+
const params = Object.fromEntries(
|
|
162
|
+
route.keys.map((key, index) => [key, decodeURIComponent(match[index + 1] ?? '')])
|
|
163
|
+
);
|
|
164
|
+
return { page: route, params };
|
|
165
|
+
}
|
|
166
|
+
if (manifest.notFound) return { page: manifest.notFound, params: {}, notFound: true };
|
|
190
167
|
}
|
|
191
168
|
|
|
192
|
-
function getRouteRegistry():
|
|
193
|
-
globalThis.
|
|
194
|
-
return globalThis.__ISR_ENGINE_ROUTE_MANIFESTS__;
|
|
169
|
+
function getRouteRegistry(): Map<ResolveRoute, CompiledManifest> {
|
|
170
|
+
return (globalThis.__ISR_ENGINE_COMPILED_ROUTE_MANIFESTS__ ??= new Map());
|
|
195
171
|
}
|
|
196
172
|
|
|
197
|
-
function
|
|
198
|
-
|
|
173
|
+
export function defineRoutes(config: RouteManifest): DefinedRoutes {
|
|
174
|
+
const manifest: CompiledManifest = {
|
|
175
|
+
routes: config.routes.map(route => ({
|
|
176
|
+
...compile(route.path),
|
|
177
|
+
...preparePage(route, route.path),
|
|
178
|
+
})),
|
|
179
|
+
notFound: config.notFound && preparePage(config.notFound, '__not_found__'),
|
|
180
|
+
};
|
|
181
|
+
const routes: ResolveRoute = ({ pathname, searchParams }) => {
|
|
182
|
+
const clean = trimTrailingSlashes(pathname) || '/';
|
|
183
|
+
const match = matchRoute(manifest, clean);
|
|
184
|
+
if (!match) return null;
|
|
185
|
+
const { Component } = match.page;
|
|
186
|
+
return <Component pathname={clean} searchParams={searchParams} params={match.params} />;
|
|
187
|
+
};
|
|
188
|
+
getRouteRegistry().set(routes, manifest);
|
|
189
|
+
return { routes };
|
|
199
190
|
}
|
|
200
191
|
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
192
|
+
function matchRegisteredRoute(
|
|
193
|
+
pathname: string,
|
|
194
|
+
routes: ResolveRoute | undefined,
|
|
195
|
+
includeUnambiguousFallback: boolean
|
|
196
|
+
): RouteMatch | undefined {
|
|
197
|
+
const registry = getRouteRegistry();
|
|
198
|
+
const manifest = routes && registry.get(routes);
|
|
199
|
+
if (manifest) return matchRoute(manifest, pathname);
|
|
200
|
+
|
|
201
|
+
// Registered tables can supply normal page SEO. Only the app's own resolver
|
|
202
|
+
// can establish its HTTP 404 when a nested router also registers a fallback.
|
|
203
|
+
let fallback: RouteMatch | undefined;
|
|
204
|
+
let ambiguous = false;
|
|
205
|
+
for (const candidate of registry.values()) {
|
|
206
|
+
const matched = matchRoute(candidate, pathname);
|
|
207
|
+
if (!matched) continue;
|
|
208
|
+
if (!matched.notFound) return matched;
|
|
209
|
+
if (!includeUnambiguousFallback) continue;
|
|
210
|
+
if (fallback) ambiguous = true;
|
|
211
|
+
else fallback = matched;
|
|
214
212
|
}
|
|
215
|
-
return
|
|
213
|
+
return ambiguous ? undefined : fallback;
|
|
216
214
|
}
|
|
217
215
|
|
|
218
|
-
function
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
const
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
216
|
+
export async function resolvePageRoute(
|
|
217
|
+
url: URL,
|
|
218
|
+
routes?: ResolveRoute,
|
|
219
|
+
includeUnambiguousFallback = false
|
|
220
|
+
): Promise<{ notFound: boolean; seoMeta: PageSeoMeta | null }> {
|
|
221
|
+
const pathname = trimTrailingSlashes(url.pathname) || '/';
|
|
222
|
+
const matched = matchRegisteredRoute(pathname, routes, includeUnambiguousFallback);
|
|
223
|
+
if (!matched) return { notFound: false, seoMeta: null };
|
|
224
|
+
const seoMeta = await loadPageSeo(matched.page.ref, {
|
|
225
|
+
url,
|
|
226
|
+
pathname,
|
|
227
|
+
searchParams: url.searchParams,
|
|
228
|
+
params: matched.params,
|
|
228
229
|
});
|
|
229
|
-
return {
|
|
230
|
+
return { notFound: matched.notFound === true, seoMeta };
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
export async function resolvePageSeoMeta(url: URL): Promise<PageSeoMeta | null> {
|
|
234
|
+
return (await resolvePageRoute(url, undefined, true)).seoMeta;
|
|
230
235
|
}
|
|
231
236
|
|
|
232
|
-
async function loadPageSeo(
|
|
237
|
+
async function loadPageSeo(
|
|
238
|
+
route: RouteModuleRef,
|
|
239
|
+
ctx: PageSeoContext
|
|
240
|
+
): Promise<PageSeoMeta | null> {
|
|
233
241
|
const mod = await route.load();
|
|
234
242
|
const exports = mod as Record<string, unknown>;
|
|
235
243
|
const exported = exports.seo ?? exports.generateSeo;
|
package/dist/Logger-DqBS_3v8.cjs
DELETED
|
@@ -1,184 +0,0 @@
|
|
|
1
|
-
const require_rolldown_runtime = require("./rolldown-runtime-DakpK96I.cjs");
|
|
2
|
-
const require_abVariantContext = require("./abVariantContext-BvAMuhjj.cjs");
|
|
3
|
-
let chalk = require("chalk");
|
|
4
|
-
chalk = require_rolldown_runtime.__toESM(chalk, 1);
|
|
5
|
-
let ora = require("ora");
|
|
6
|
-
ora = require_rolldown_runtime.__toESM(ora, 1);
|
|
7
|
-
let path = require("path");
|
|
8
|
-
path = require_rolldown_runtime.__toESM(path, 1);
|
|
9
|
-
let pino = require("pino");
|
|
10
|
-
pino = require_rolldown_runtime.__toESM(pino, 1);
|
|
11
|
-
//#region src/logger/Logger.ts
|
|
12
|
-
var LogLevel = /* @__PURE__ */ function(LogLevel) {
|
|
13
|
-
LogLevel["VERBOSE"] = "verbose";
|
|
14
|
-
LogLevel["DEBUG"] = "debug";
|
|
15
|
-
LogLevel["INFO"] = "info";
|
|
16
|
-
LogLevel["WARN"] = "warn";
|
|
17
|
-
LogLevel["ERROR"] = "error";
|
|
18
|
-
LogLevel["SUCCESS"] = "success";
|
|
19
|
-
return LogLevel;
|
|
20
|
-
}({});
|
|
21
|
-
var Logger = class Logger {
|
|
22
|
-
static instance;
|
|
23
|
-
verboseMode = false;
|
|
24
|
-
logFile = null;
|
|
25
|
-
fileLogger = null;
|
|
26
|
-
fileDestination = null;
|
|
27
|
-
spinner = null;
|
|
28
|
-
static getInstance(options = {}) {
|
|
29
|
-
if (!Logger.instance) {
|
|
30
|
-
Logger.instance = new Logger();
|
|
31
|
-
require_abVariantContext.setOriginLogger(Logger.instance);
|
|
32
|
-
}
|
|
33
|
-
if (options.verbose !== void 0) Logger.instance.verboseMode = options.verbose;
|
|
34
|
-
if (options.logFile !== void 0) Logger.instance.configureFile(options.logFile);
|
|
35
|
-
return Logger.instance;
|
|
36
|
-
}
|
|
37
|
-
/** File destinations are operator configuration; request data is only a record field. */
|
|
38
|
-
configureFile(logFile) {
|
|
39
|
-
if (typeof logFile !== "string" || /[\u0000-\u001f\u007f]/.test(logFile)) throw new TypeError("logFile must be a path without control characters");
|
|
40
|
-
const resolved = logFile ? path.default.resolve(logFile) : null;
|
|
41
|
-
if (resolved === this.logFile) return;
|
|
42
|
-
this.closeFileDestination();
|
|
43
|
-
if (!resolved) return;
|
|
44
|
-
try {
|
|
45
|
-
const destination = pino.default.destination({
|
|
46
|
-
dest: resolved,
|
|
47
|
-
mkdir: true,
|
|
48
|
-
sync: true
|
|
49
|
-
});
|
|
50
|
-
destination.on("error", (error) => {
|
|
51
|
-
if (this.fileDestination === destination) this.closeFileDestination();
|
|
52
|
-
this.reportFileError(error);
|
|
53
|
-
});
|
|
54
|
-
destination.once("close", () => {
|
|
55
|
-
if (this.fileDestination !== destination) return;
|
|
56
|
-
this.fileLogger = null;
|
|
57
|
-
this.fileDestination = null;
|
|
58
|
-
this.logFile = null;
|
|
59
|
-
});
|
|
60
|
-
this.fileDestination = destination;
|
|
61
|
-
this.fileLogger = (0, pino.default)({
|
|
62
|
-
base: null,
|
|
63
|
-
timestamp: false,
|
|
64
|
-
level: "trace",
|
|
65
|
-
hooks: { streamWrite: require_abVariantContext.escapeSupplementalLogControls }
|
|
66
|
-
}, destination);
|
|
67
|
-
this.logFile = resolved;
|
|
68
|
-
} catch (error) {
|
|
69
|
-
this.closeFileDestination();
|
|
70
|
-
this.reportFileError(error);
|
|
71
|
-
}
|
|
72
|
-
}
|
|
73
|
-
closeFileDestination() {
|
|
74
|
-
const destination = this.fileDestination;
|
|
75
|
-
this.fileLogger = null;
|
|
76
|
-
this.fileDestination = null;
|
|
77
|
-
this.logFile = null;
|
|
78
|
-
if (!destination) return;
|
|
79
|
-
try {
|
|
80
|
-
destination.flushSync();
|
|
81
|
-
destination.end();
|
|
82
|
-
} catch (error) {
|
|
83
|
-
destination.destroy();
|
|
84
|
-
this.reportFileError(error);
|
|
85
|
-
}
|
|
86
|
-
}
|
|
87
|
-
reportFileError(error) {
|
|
88
|
-
try {
|
|
89
|
-
process.stderr.write(`Failed to write to log file: ${require_abVariantContext.encodeLogField(require_abVariantContext.snapshotLogArgument(error))}\n`);
|
|
90
|
-
} catch {}
|
|
91
|
-
}
|
|
92
|
-
getLevelColor(level) {
|
|
93
|
-
switch (level) {
|
|
94
|
-
case "error": return chalk.default.red.bold;
|
|
95
|
-
case "warn": return chalk.default.yellow.bold;
|
|
96
|
-
case "success": return chalk.default.green.bold;
|
|
97
|
-
case "info": return chalk.default.blue.bold;
|
|
98
|
-
case "debug": return chalk.default.magenta;
|
|
99
|
-
case "verbose": return chalk.default.gray;
|
|
100
|
-
default: return chalk.default.white;
|
|
101
|
-
}
|
|
102
|
-
}
|
|
103
|
-
log(level, ...args) {
|
|
104
|
-
if (!Object.values(LogLevel).includes(level)) throw new TypeError("Unknown log level");
|
|
105
|
-
if (level === "verbose" && !this.verboseMode) return;
|
|
106
|
-
if (level === "debug" && !this.verboseMode) return;
|
|
107
|
-
if (this.spinner?.isSpinning) this.spinner.stop();
|
|
108
|
-
const timestamp = (/* @__PURE__ */ new Date()).toISOString();
|
|
109
|
-
const traceId = require_abVariantContext.snapshotLogArgument(require_abVariantContext.getTraceId());
|
|
110
|
-
const requestId = require_abVariantContext.snapshotLogArgument(require_abVariantContext.getRequestId());
|
|
111
|
-
const values = args.map(require_abVariantContext.snapshotLogArgument);
|
|
112
|
-
const errors = [];
|
|
113
|
-
const message = values.map((value, index) => {
|
|
114
|
-
if (args[index] instanceof Error) {
|
|
115
|
-
errors.push({
|
|
116
|
-
argument: index,
|
|
117
|
-
error: value
|
|
118
|
-
});
|
|
119
|
-
if (value && typeof value === "object" && !Array.isArray(value)) return value.stack || value.message || JSON.stringify(value, null, 2);
|
|
120
|
-
}
|
|
121
|
-
return typeof value === "string" ? value : JSON.stringify(value, null, 2);
|
|
122
|
-
}).join(" ");
|
|
123
|
-
const levelTag = this.getLevelColor(level)(`[${level.toUpperCase()}]`);
|
|
124
|
-
const traceTag = chalk.default.cyan(`traceId=${require_abVariantContext.encodeLogField(traceId)}`);
|
|
125
|
-
const requestTag = requestId === "unknown" ? "" : chalk.default.blue(`requestId=${require_abVariantContext.encodeLogField(requestId)}`);
|
|
126
|
-
console.log(`${chalk.default.gray(timestamp)} ${levelTag} ${traceTag} ${requestTag} message=${require_abVariantContext.encodeLogField(message)}`);
|
|
127
|
-
if (this.fileLogger) {
|
|
128
|
-
const transportLevel = level === "verbose" ? "trace" : level === "success" ? "info" : level;
|
|
129
|
-
try {
|
|
130
|
-
this.fileLogger[transportLevel]({
|
|
131
|
-
timestamp,
|
|
132
|
-
severity: level,
|
|
133
|
-
traceId,
|
|
134
|
-
requestId,
|
|
135
|
-
args: values,
|
|
136
|
-
errors
|
|
137
|
-
});
|
|
138
|
-
} catch (error) {
|
|
139
|
-
this.closeFileDestination();
|
|
140
|
-
this.reportFileError(error);
|
|
141
|
-
}
|
|
142
|
-
}
|
|
143
|
-
if (this.spinner && !this.spinner.isSpinning) this.spinner.start();
|
|
144
|
-
}
|
|
145
|
-
error(...args) {
|
|
146
|
-
this.log("error", ...args);
|
|
147
|
-
}
|
|
148
|
-
warn(...args) {
|
|
149
|
-
this.log("warn", ...args);
|
|
150
|
-
}
|
|
151
|
-
info(...args) {
|
|
152
|
-
this.log("info", ...args);
|
|
153
|
-
}
|
|
154
|
-
success(...args) {
|
|
155
|
-
this.log("success", ...args);
|
|
156
|
-
}
|
|
157
|
-
debug(...args) {
|
|
158
|
-
this.log("debug", ...args);
|
|
159
|
-
}
|
|
160
|
-
verbose(...args) {
|
|
161
|
-
this.log("verbose", ...args);
|
|
162
|
-
}
|
|
163
|
-
spin(message) {
|
|
164
|
-
if (this.spinner) this.spinner.succeed();
|
|
165
|
-
this.spinner = (0, ora.default)(require_abVariantContext.encodeSpinnerMessage(message)).start();
|
|
166
|
-
return this.spinner;
|
|
167
|
-
}
|
|
168
|
-
stopSpinner(message, success = true) {
|
|
169
|
-
if (this.spinner) {
|
|
170
|
-
if (success) this.spinner.succeed(message === void 0 ? void 0 : require_abVariantContext.encodeSpinnerMessage(message));
|
|
171
|
-
else this.spinner.fail(message === void 0 ? void 0 : require_abVariantContext.encodeSpinnerMessage(message));
|
|
172
|
-
this.spinner = null;
|
|
173
|
-
}
|
|
174
|
-
}
|
|
175
|
-
};
|
|
176
|
-
//#endregion
|
|
177
|
-
Object.defineProperty(exports, "Logger", {
|
|
178
|
-
enumerable: true,
|
|
179
|
-
get: function() {
|
|
180
|
-
return Logger;
|
|
181
|
-
}
|
|
182
|
-
});
|
|
183
|
-
|
|
184
|
-
//# sourceMappingURL=Logger-DqBS_3v8.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"Logger-DqBS_3v8.cjs","names":[],"sources":["../src/logger/Logger.ts"],"sourcesContent":["import chalk from 'chalk';\nimport ora, { Ora } from 'ora';\nimport path from 'path';\nimport pino, { type Logger as PinoLogger } from 'pino';\nimport { getTraceId, getRequestId } from '../context/RequestContext';\nimport {\n encodeLogField,\n encodeSpinnerMessage,\n escapeSupplementalLogControls,\n snapshotLogArgument,\n type LogValue,\n} from './logRecord';\nimport { setOriginLogger } from './runtimeLogger';\n\nexport enum LogLevel {\n VERBOSE = 'verbose',\n DEBUG = 'debug',\n INFO = 'info',\n WARN = 'warn',\n ERROR = 'error',\n SUCCESS = 'success',\n}\n\nexport interface LoggerOptions {\n verbose?: boolean;\n logFile?: string;\n}\n\nexport class Logger {\n private static instance: Logger;\n private verboseMode: boolean = false;\n private logFile: string | null = null;\n private fileLogger: PinoLogger | null = null;\n private fileDestination: ReturnType<typeof pino.destination> | null = null;\n private spinner: Ora | null = null;\n\n public static getInstance(options: LoggerOptions = {}): Logger {\n if (!Logger.instance) {\n Logger.instance = new Logger();\n setOriginLogger(Logger.instance);\n }\n\n if (options.verbose !== undefined) {\n Logger.instance.verboseMode = options.verbose;\n }\n\n if (options.logFile !== undefined) {\n Logger.instance.configureFile(options.logFile);\n }\n\n return Logger.instance;\n }\n\n /** File destinations are operator configuration; request data is only a record field. */\n private configureFile(logFile: string): void {\n // eslint-disable-next-line no-control-regex\n if (typeof logFile !== 'string' || /[\\u0000-\\u001f\\u007f]/.test(logFile)) {\n throw new TypeError('logFile must be a path without control characters');\n }\n const resolved = logFile ? path.resolve(logFile) : null;\n if (resolved === this.logFile) return;\n this.closeFileDestination();\n if (!resolved) return;\n\n try {\n const destination = pino.destination({ dest: resolved, mkdir: true, sync: true });\n destination.on('error', error => {\n if (this.fileDestination === destination) this.closeFileDestination();\n this.reportFileError(error);\n });\n destination.once('close', () => {\n if (this.fileDestination !== destination) return;\n this.fileLogger = null;\n this.fileDestination = null;\n this.logFile = null;\n });\n this.fileDestination = destination;\n this.fileLogger = pino(\n {\n base: null,\n timestamp: false,\n level: 'trace',\n hooks: { streamWrite: escapeSupplementalLogControls },\n },\n destination\n );\n this.logFile = resolved;\n } catch (error) {\n this.closeFileDestination();\n this.reportFileError(error);\n }\n }\n\n private closeFileDestination(): void {\n const destination = this.fileDestination;\n this.fileLogger = null;\n this.fileDestination = null;\n this.logFile = null;\n if (!destination) return;\n try {\n destination.flushSync();\n destination.end();\n } catch (error) {\n destination.destroy();\n this.reportFileError(error);\n }\n }\n\n private reportFileError(error: unknown): void {\n try {\n process.stderr.write(\n `Failed to write to log file: ${encodeLogField(snapshotLogArgument(error))}\\n`\n );\n } catch {\n // Logging failure must never recurse or prevent serving a request.\n }\n }\n\n private getLevelColor(level: LogLevel) {\n switch (level) {\n case LogLevel.ERROR:\n return chalk.red.bold;\n case LogLevel.WARN:\n return chalk.yellow.bold;\n case LogLevel.SUCCESS:\n return chalk.green.bold;\n case LogLevel.INFO:\n return chalk.blue.bold;\n case LogLevel.DEBUG:\n return chalk.magenta;\n case LogLevel.VERBOSE:\n return chalk.gray;\n default:\n return chalk.white;\n }\n }\n\n public log(level: LogLevel, ...args: unknown[]) {\n if (!Object.values(LogLevel).includes(level)) {\n throw new TypeError('Unknown log level');\n }\n\n if (level === LogLevel.VERBOSE && !this.verboseMode) return;\n if (level === LogLevel.DEBUG && !this.verboseMode) return;\n\n if (this.spinner?.isSpinning) this.spinner.stop();\n\n const timestamp = new Date().toISOString();\n const traceId = snapshotLogArgument(getTraceId());\n const requestId = snapshotLogArgument(getRequestId());\n const values = args.map(snapshotLogArgument);\n const errors: Array<{ argument: number; error: LogValue }> = [];\n const message = values\n .map((value, index) => {\n if (args[index] instanceof Error) {\n errors.push({ argument: index, error: value });\n if (value && typeof value === 'object' && !Array.isArray(value)) {\n return value.stack || value.message || JSON.stringify(value, null, 2);\n }\n }\n return typeof value === 'string' ? value : JSON.stringify(value, null, 2);\n })\n .join(' ');\n\n // Encode each field before adding only the logger's own ANSI color sequences.\n const levelTag = this.getLevelColor(level)(`[${level.toUpperCase()}]`);\n const traceTag = chalk.cyan(`traceId=${encodeLogField(traceId)}`);\n const requestTag =\n requestId === 'unknown' ? '' : chalk.blue(`requestId=${encodeLogField(requestId)}`);\n console.log(\n `${chalk.gray(timestamp)} ${levelTag} ${traceTag} ${requestTag} message=${encodeLogField(message)}`\n );\n\n if (this.fileLogger) {\n const transportLevel =\n level === LogLevel.VERBOSE ? 'trace' : level === LogLevel.SUCCESS ? 'info' : level;\n try {\n this.fileLogger[transportLevel]({\n timestamp,\n severity: level,\n traceId,\n requestId,\n args: values,\n errors,\n });\n } catch (error) {\n this.closeFileDestination();\n this.reportFileError(error);\n }\n }\n\n if (this.spinner && !this.spinner.isSpinning) {\n this.spinner.start();\n }\n }\n\n public error(...args: unknown[]) {\n this.log(LogLevel.ERROR, ...args);\n }\n\n public warn(...args: unknown[]) {\n this.log(LogLevel.WARN, ...args);\n }\n\n public info(...args: unknown[]) {\n this.log(LogLevel.INFO, ...args);\n }\n\n public success(...args: unknown[]) {\n this.log(LogLevel.SUCCESS, ...args);\n }\n\n public debug(...args: unknown[]) {\n this.log(LogLevel.DEBUG, ...args);\n }\n\n public verbose(...args: unknown[]) {\n this.log(LogLevel.VERBOSE, ...args);\n }\n\n public spin(message: string): Ora {\n if (this.spinner) {\n this.spinner.succeed();\n }\n this.spinner = ora(encodeSpinnerMessage(message)).start();\n return this.spinner;\n }\n\n public stopSpinner(message?: string, success: boolean = true) {\n if (this.spinner) {\n if (success) {\n this.spinner.succeed(message === undefined ? undefined : encodeSpinnerMessage(message));\n } else {\n this.spinner.fail(message === undefined ? undefined : encodeSpinnerMessage(message));\n }\n this.spinner =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