@sigil-dev/grimoire 0.9.28 → 0.9.30
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/bin/sigil.ts +4 -0
- package/index.ts +16 -10
- package/package.json +14 -6
- package/server.ts +2 -2
- package/src/adapters/bun.ts +17 -17
- package/src/adapters/static.ts +41 -41
- package/src/adapters/types.ts +36 -36
- package/src/base.ts +4 -1
- package/src/client/csrf.ts +47 -47
- package/src/client/deferred.ts +1 -4
- package/src/client/enhance.ts +160 -160
- package/src/client/router.ts +927 -926
- package/src/config-file.ts +84 -0
- package/src/dev/compile-module.ts +199 -193
- package/src/dev/hmr-client.ts +229 -229
- package/src/dev/hmr-server.ts +274 -266
- package/src/dev/loader.ts +144 -144
- package/src/dev/runtime-bundle.ts +5 -3
- package/src/duration.ts +46 -0
- package/src/env/modules.ts +62 -62
- package/src/env/required.ts +42 -42
- package/src/env/typegen.ts +61 -61
- package/src/headers.ts +105 -105
- package/src/logger/transports.ts +117 -117
- package/src/plugin-order.ts +88 -0
- package/src/rendering/head.ts +49 -49
- package/src/rendering/hydrate.ts +162 -162
- package/src/rendering/images.ts +43 -43
- package/src/rendering/preload.ts +22 -8
- package/src/rendering/ssrPlugin.ts +107 -107
- package/src/rendering/timing.ts +40 -40
- package/src/routing/route-ids.ts +65 -0
- package/src/routing/route.ts +65 -0
- package/src/routing/router.ts +84 -32
- package/src/routing/scanner.ts +18 -5
- package/src/routing/transform-routes.ts +102 -102
- package/src/server/after-response.ts +206 -206
- package/src/server/asset-cache.ts +57 -57
- package/src/server/build.ts +304 -295
- package/src/server/cached.ts +114 -114
- package/src/server/client-address.ts +82 -82
- package/src/server/client-dir.ts +63 -63
- package/src/server/client-entry.ts +44 -44
- package/src/server/context.ts +18 -10
- package/src/server/cookie-utils.ts +80 -80
- package/src/server/coordinator.ts +476 -476
- package/src/server/hooks.ts +122 -122
- package/src/server/index.ts +8 -0
- package/src/server/plugins.ts +172 -172
- package/src/server/prerender.ts +473 -473
- package/src/server/reserved.ts +17 -17
- package/src/server/resolver.ts +149 -123
- package/src/server/rewrite.ts +28 -28
- package/src/server/warm.ts +9 -3
- package/src/server/with-headers.ts +27 -27
- package/src/server/worker.ts +2 -6
- package/src/server-only.ts +78 -0
- package/src/testing/dom.ts +73 -73
- package/src/testing/index.ts +169 -169
- package/src/testing/server.ts +1 -0
- package/src/typegen/index.ts +97 -2
- package/src/types.ts +140 -19
- package/test/after-response.test.ts +132 -132
- package/test/asset-cache-policy.test.ts +6 -2
- package/test/base.test.ts +20 -6
- package/test/cached.test.ts +126 -126
- package/test/client-address.test.ts +78 -78
- package/test/client-csrf.test.ts +61 -61
- package/test/client-dir.test.ts +101 -101
- package/test/client-router.test.ts +37 -5
- package/test/config-file.test.ts +84 -0
- package/test/coordinator.test.ts +9 -2
- package/test/deferred.test.ts +4 -2
- package/test/dev-loader.test.ts +30 -30
- package/test/env.test.ts +171 -171
- package/test/force-production.test.ts +7 -2
- package/test/images.test.ts +20 -8
- package/test/locals-header.test.ts +61 -61
- package/test/middleware.test.ts +243 -243
- package/test/parser-plugins.test.ts +98 -92
- package/test/plugin-handle.test.ts +62 -62
- package/test/plugin-order.test.ts +98 -0
- package/test/plugin-routes.test.ts +47 -42
- package/test/plugin-services-context.test.ts +7 -2
- package/test/preload.test.ts +4 -1
- package/test/prerender.test.ts +3 -1
- package/test/rendering.test.ts +3 -2
- package/test/required-env.test.ts +32 -32
- package/test/resolver-windows.test.ts +22 -23
- package/test/rewrite-html.test.ts +90 -90
- package/test/route-group-layouts.test.ts +38 -36
- package/test/route.test.ts +103 -0
- package/test/routing.test.ts +225 -197
- package/test/scanning.test.ts +53 -33
- package/test/server-context.test.ts +22 -0
- package/test/server-only.test.ts +110 -0
- package/test/server.test.ts +640 -640
- package/test/services.test.ts +3 -3
- package/test/streaming.test.ts +11 -6
- package/test/testing-helpers.test.ts +166 -166
- package/test/typegen.test.ts +209 -112
- package/test/warm.test.ts +96 -96
- package/test/worker-context.test.ts +59 -59
- package/test/workspace-files.test.ts +26 -10
- package/test/workspace-versions.test.ts +146 -131
package/src/env/typegen.ts
CHANGED
|
@@ -1,61 +1,61 @@
|
|
|
1
|
-
import { readFile, writeFile } from "node:fs/promises";
|
|
2
|
-
import { join } from "node:path";
|
|
3
|
-
|
|
4
|
-
export async function generateEnvTypes(
|
|
5
|
-
projectRoot: string,
|
|
6
|
-
outDir: string,
|
|
7
|
-
): Promise<void> {
|
|
8
|
-
const envPath = join(projectRoot, ".env");
|
|
9
|
-
let envContent = "";
|
|
10
|
-
try {
|
|
11
|
-
envContent = await readFile(envPath, "utf-8");
|
|
12
|
-
} catch {
|
|
13
|
-
// no .env file — generate empty types
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
const publicVars: string[] = [];
|
|
17
|
-
const privateVars: string[] = [];
|
|
18
|
-
|
|
19
|
-
for (const line of envContent.split("\n")) {
|
|
20
|
-
const trimmed = line.trim();
|
|
21
|
-
if (!trimmed || trimmed.startsWith("#")) continue;
|
|
22
|
-
const eqIndex = trimmed.indexOf("=");
|
|
23
|
-
if (eqIndex === -1) continue;
|
|
24
|
-
const key = trimmed.slice(0, eqIndex).trim();
|
|
25
|
-
if (!key) continue;
|
|
26
|
-
if (key.startsWith("PUBLIC_")) {
|
|
27
|
-
publicVars.push(key);
|
|
28
|
-
} else {
|
|
29
|
-
privateVars.push(key);
|
|
30
|
-
}
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
const publicTypeContent = `// Auto-generated by Grimoire. Do not edit.
|
|
34
|
-
declare module "$env/static/public" {
|
|
35
|
-
\texport const env: Record<string, string>;
|
|
36
|
-
${publicVars.map((v) => `\texport const ${v}: string;`).join("\n")}
|
|
37
|
-
}
|
|
38
|
-
`;
|
|
39
|
-
|
|
40
|
-
const privateTypeContent = `// Auto-generated by Grimoire. Do not edit.
|
|
41
|
-
declare module "$env/static/private" {
|
|
42
|
-
\texport const env: Record<string, string>;
|
|
43
|
-
${privateVars.map((v) => `\texport const ${v}: string;`).join("\n")}
|
|
44
|
-
}
|
|
45
|
-
`;
|
|
46
|
-
|
|
47
|
-
const dynamicTypeContent = `// Auto-generated by Grimoire. Do not edit.
|
|
48
|
-
declare module "$env/dynamic/public" {
|
|
49
|
-
\texport const env: Record<string, string>;
|
|
50
|
-
}
|
|
51
|
-
declare module "$env/dynamic/private" {
|
|
52
|
-
\texport const env: Record<string, string>;
|
|
53
|
-
}
|
|
54
|
-
`;
|
|
55
|
-
|
|
56
|
-
await Promise.all([
|
|
57
|
-
writeFile(join(outDir, "env-public.d.ts"), publicTypeContent, "utf-8"),
|
|
58
|
-
writeFile(join(outDir, "env-private.d.ts"), privateTypeContent, "utf-8"),
|
|
59
|
-
writeFile(join(outDir, "env-dynamic.d.ts"), dynamicTypeContent, "utf-8"),
|
|
60
|
-
]);
|
|
61
|
-
}
|
|
1
|
+
import { readFile, writeFile } from "node:fs/promises";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
|
|
4
|
+
export async function generateEnvTypes(
|
|
5
|
+
projectRoot: string,
|
|
6
|
+
outDir: string,
|
|
7
|
+
): Promise<void> {
|
|
8
|
+
const envPath = join(projectRoot, ".env");
|
|
9
|
+
let envContent = "";
|
|
10
|
+
try {
|
|
11
|
+
envContent = await readFile(envPath, "utf-8");
|
|
12
|
+
} catch {
|
|
13
|
+
// no .env file — generate empty types
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const publicVars: string[] = [];
|
|
17
|
+
const privateVars: string[] = [];
|
|
18
|
+
|
|
19
|
+
for (const line of envContent.split("\n")) {
|
|
20
|
+
const trimmed = line.trim();
|
|
21
|
+
if (!trimmed || trimmed.startsWith("#")) continue;
|
|
22
|
+
const eqIndex = trimmed.indexOf("=");
|
|
23
|
+
if (eqIndex === -1) continue;
|
|
24
|
+
const key = trimmed.slice(0, eqIndex).trim();
|
|
25
|
+
if (!key) continue;
|
|
26
|
+
if (key.startsWith("PUBLIC_")) {
|
|
27
|
+
publicVars.push(key);
|
|
28
|
+
} else {
|
|
29
|
+
privateVars.push(key);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const publicTypeContent = `// Auto-generated by Grimoire. Do not edit.
|
|
34
|
+
declare module "$env/static/public" {
|
|
35
|
+
\texport const env: Record<string, string>;
|
|
36
|
+
${publicVars.map((v) => `\texport const ${v}: string;`).join("\n")}
|
|
37
|
+
}
|
|
38
|
+
`;
|
|
39
|
+
|
|
40
|
+
const privateTypeContent = `// Auto-generated by Grimoire. Do not edit.
|
|
41
|
+
declare module "$env/static/private" {
|
|
42
|
+
\texport const env: Record<string, string>;
|
|
43
|
+
${privateVars.map((v) => `\texport const ${v}: string;`).join("\n")}
|
|
44
|
+
}
|
|
45
|
+
`;
|
|
46
|
+
|
|
47
|
+
const dynamicTypeContent = `// Auto-generated by Grimoire. Do not edit.
|
|
48
|
+
declare module "$env/dynamic/public" {
|
|
49
|
+
\texport const env: Record<string, string>;
|
|
50
|
+
}
|
|
51
|
+
declare module "$env/dynamic/private" {
|
|
52
|
+
\texport const env: Record<string, string>;
|
|
53
|
+
}
|
|
54
|
+
`;
|
|
55
|
+
|
|
56
|
+
await Promise.all([
|
|
57
|
+
writeFile(join(outDir, "env-public.d.ts"), publicTypeContent, "utf-8"),
|
|
58
|
+
writeFile(join(outDir, "env-private.d.ts"), privateTypeContent, "utf-8"),
|
|
59
|
+
writeFile(join(outDir, "env-dynamic.d.ts"), dynamicTypeContent, "utf-8"),
|
|
60
|
+
]);
|
|
61
|
+
}
|
package/src/headers.ts
CHANGED
|
@@ -1,105 +1,105 @@
|
|
|
1
|
-
import { withHeaders } from "./server/with-headers";
|
|
2
|
-
import type { GrimoirePlugin } from "./types";
|
|
3
|
-
|
|
4
|
-
export interface SecurityHeadersConfig {
|
|
5
|
-
/** Content-Security-Policy. Set false to omit. */
|
|
6
|
-
contentSecurityPolicy?: string | false;
|
|
7
|
-
/** X-Content-Type-Options. Default: "nosniff" */
|
|
8
|
-
contentTypeOptions?: string | false;
|
|
9
|
-
/** X-Frame-Options. Default: "DENY" */
|
|
10
|
-
frameOptions?: string | false;
|
|
11
|
-
/** X-XSS-Protection. Default: "0" (modern browsers; "1; mode=block" for legacy) */
|
|
12
|
-
xssProtection?: string | false;
|
|
13
|
-
/** Referrer-Policy. Default: "strict-origin-when-cross-origin" */
|
|
14
|
-
referrerPolicy?: string | false;
|
|
15
|
-
/** Strict-Transport-Security. Set false to omit. */
|
|
16
|
-
strictTransportSecurity?: string | false;
|
|
17
|
-
/** Permissions-Policy. Default: "camera=(), microphone=(), geolocation=()" */
|
|
18
|
-
permissionsPolicy?: string | false;
|
|
19
|
-
/** Per-route overrides: path pattern → partial config */
|
|
20
|
-
routes?: Record<string, Partial<SecurityHeadersConfig>>;
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
const DEFAULTS: Required<Omit<SecurityHeadersConfig, "routes">> = {
|
|
24
|
-
contentSecurityPolicy:
|
|
25
|
-
"default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:;",
|
|
26
|
-
contentTypeOptions: "nosniff",
|
|
27
|
-
frameOptions: "DENY",
|
|
28
|
-
xssProtection: "0",
|
|
29
|
-
referrerPolicy: "strict-origin-when-cross-origin",
|
|
30
|
-
strictTransportSecurity: "max-age=31536000; includeSubDomains",
|
|
31
|
-
permissionsPolicy: "camera=(), microphone=(), geolocation=()",
|
|
32
|
-
};
|
|
33
|
-
|
|
34
|
-
function resolveHeaders(
|
|
35
|
-
config: SecurityHeadersConfig,
|
|
36
|
-
pathname: string,
|
|
37
|
-
): Record<string, string> {
|
|
38
|
-
// Start with defaults, overlay user config
|
|
39
|
-
const merged = { ...DEFAULTS, ...config };
|
|
40
|
-
delete (merged as any).routes;
|
|
41
|
-
|
|
42
|
-
// Apply route overrides
|
|
43
|
-
if (config.routes) {
|
|
44
|
-
for (const pattern in config.routes) {
|
|
45
|
-
if (pathname.startsWith(pattern)) {
|
|
46
|
-
Object.assign(merged, config.routes[pattern]);
|
|
47
|
-
}
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
const headers: Record<string, string> = {};
|
|
52
|
-
|
|
53
|
-
if (merged.contentSecurityPolicy !== false)
|
|
54
|
-
headers["Content-Security-Policy"] = merged.contentSecurityPolicy;
|
|
55
|
-
if (merged.contentTypeOptions !== false)
|
|
56
|
-
headers["X-Content-Type-Options"] = merged.contentTypeOptions;
|
|
57
|
-
if (merged.frameOptions !== false)
|
|
58
|
-
headers["X-Frame-Options"] = merged.frameOptions;
|
|
59
|
-
if (merged.xssProtection !== false)
|
|
60
|
-
headers["X-XSS-Protection"] = merged.xssProtection;
|
|
61
|
-
if (merged.referrerPolicy !== false)
|
|
62
|
-
headers["Referrer-Policy"] = merged.referrerPolicy;
|
|
63
|
-
if (merged.strictTransportSecurity !== false)
|
|
64
|
-
headers["Strict-Transport-Security"] = merged.strictTransportSecurity;
|
|
65
|
-
if (merged.permissionsPolicy !== false)
|
|
66
|
-
headers["Permissions-Policy"] = merged.permissionsPolicy;
|
|
67
|
-
|
|
68
|
-
return headers;
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
/**
|
|
72
|
-
* Security headers plugin.
|
|
73
|
-
* Adds standard security headers to all responses.
|
|
74
|
-
*
|
|
75
|
-
* Usage:
|
|
76
|
-
*
|
|
77
|
-
* import { securityHeaders } from "@sigil-dev/grimoire/headers";
|
|
78
|
-
*
|
|
79
|
-
* createServer({
|
|
80
|
-
* plugins: [
|
|
81
|
-
* securityHeaders({
|
|
82
|
-
* // override defaults
|
|
83
|
-
* frameOptions: "SAMEORIGIN",
|
|
84
|
-
* // per-route
|
|
85
|
-
* routes: {
|
|
86
|
-
* "/admin": { contentSecurityPolicy: "default-src 'self'" },
|
|
87
|
-
* },
|
|
88
|
-
* }),
|
|
89
|
-
* ],
|
|
90
|
-
* });
|
|
91
|
-
*/
|
|
92
|
-
export function securityHeaders(
|
|
93
|
-
config: SecurityHeadersConfig = {},
|
|
94
|
-
): GrimoirePlugin {
|
|
95
|
-
return {
|
|
96
|
-
name: "grimoire-security-headers",
|
|
97
|
-
async onRequest(req, next) {
|
|
98
|
-
const res = await next();
|
|
99
|
-
const url = new URL(req.url);
|
|
100
|
-
const headers = resolveHeaders(config, url.pathname);
|
|
101
|
-
|
|
102
|
-
return withHeaders(res, Object.entries(headers));
|
|
103
|
-
},
|
|
104
|
-
};
|
|
105
|
-
}
|
|
1
|
+
import { withHeaders } from "./server/with-headers";
|
|
2
|
+
import type { GrimoirePlugin } from "./types";
|
|
3
|
+
|
|
4
|
+
export interface SecurityHeadersConfig {
|
|
5
|
+
/** Content-Security-Policy. Set false to omit. */
|
|
6
|
+
contentSecurityPolicy?: string | false;
|
|
7
|
+
/** X-Content-Type-Options. Default: "nosniff" */
|
|
8
|
+
contentTypeOptions?: string | false;
|
|
9
|
+
/** X-Frame-Options. Default: "DENY" */
|
|
10
|
+
frameOptions?: string | false;
|
|
11
|
+
/** X-XSS-Protection. Default: "0" (modern browsers; "1; mode=block" for legacy) */
|
|
12
|
+
xssProtection?: string | false;
|
|
13
|
+
/** Referrer-Policy. Default: "strict-origin-when-cross-origin" */
|
|
14
|
+
referrerPolicy?: string | false;
|
|
15
|
+
/** Strict-Transport-Security. Set false to omit. */
|
|
16
|
+
strictTransportSecurity?: string | false;
|
|
17
|
+
/** Permissions-Policy. Default: "camera=(), microphone=(), geolocation=()" */
|
|
18
|
+
permissionsPolicy?: string | false;
|
|
19
|
+
/** Per-route overrides: path pattern → partial config */
|
|
20
|
+
routes?: Record<string, Partial<SecurityHeadersConfig>>;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const DEFAULTS: Required<Omit<SecurityHeadersConfig, "routes">> = {
|
|
24
|
+
contentSecurityPolicy:
|
|
25
|
+
"default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:;",
|
|
26
|
+
contentTypeOptions: "nosniff",
|
|
27
|
+
frameOptions: "DENY",
|
|
28
|
+
xssProtection: "0",
|
|
29
|
+
referrerPolicy: "strict-origin-when-cross-origin",
|
|
30
|
+
strictTransportSecurity: "max-age=31536000; includeSubDomains",
|
|
31
|
+
permissionsPolicy: "camera=(), microphone=(), geolocation=()",
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
function resolveHeaders(
|
|
35
|
+
config: SecurityHeadersConfig,
|
|
36
|
+
pathname: string,
|
|
37
|
+
): Record<string, string> {
|
|
38
|
+
// Start with defaults, overlay user config
|
|
39
|
+
const merged = { ...DEFAULTS, ...config };
|
|
40
|
+
delete (merged as any).routes;
|
|
41
|
+
|
|
42
|
+
// Apply route overrides
|
|
43
|
+
if (config.routes) {
|
|
44
|
+
for (const pattern in config.routes) {
|
|
45
|
+
if (pathname.startsWith(pattern)) {
|
|
46
|
+
Object.assign(merged, config.routes[pattern]);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const headers: Record<string, string> = {};
|
|
52
|
+
|
|
53
|
+
if (merged.contentSecurityPolicy !== false)
|
|
54
|
+
headers["Content-Security-Policy"] = merged.contentSecurityPolicy;
|
|
55
|
+
if (merged.contentTypeOptions !== false)
|
|
56
|
+
headers["X-Content-Type-Options"] = merged.contentTypeOptions;
|
|
57
|
+
if (merged.frameOptions !== false)
|
|
58
|
+
headers["X-Frame-Options"] = merged.frameOptions;
|
|
59
|
+
if (merged.xssProtection !== false)
|
|
60
|
+
headers["X-XSS-Protection"] = merged.xssProtection;
|
|
61
|
+
if (merged.referrerPolicy !== false)
|
|
62
|
+
headers["Referrer-Policy"] = merged.referrerPolicy;
|
|
63
|
+
if (merged.strictTransportSecurity !== false)
|
|
64
|
+
headers["Strict-Transport-Security"] = merged.strictTransportSecurity;
|
|
65
|
+
if (merged.permissionsPolicy !== false)
|
|
66
|
+
headers["Permissions-Policy"] = merged.permissionsPolicy;
|
|
67
|
+
|
|
68
|
+
return headers;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Security headers plugin.
|
|
73
|
+
* Adds standard security headers to all responses.
|
|
74
|
+
*
|
|
75
|
+
* Usage:
|
|
76
|
+
*
|
|
77
|
+
* import { securityHeaders } from "@sigil-dev/grimoire/headers";
|
|
78
|
+
*
|
|
79
|
+
* createServer({
|
|
80
|
+
* plugins: [
|
|
81
|
+
* securityHeaders({
|
|
82
|
+
* // override defaults
|
|
83
|
+
* frameOptions: "SAMEORIGIN",
|
|
84
|
+
* // per-route
|
|
85
|
+
* routes: {
|
|
86
|
+
* "/admin": { contentSecurityPolicy: "default-src 'self'" },
|
|
87
|
+
* },
|
|
88
|
+
* }),
|
|
89
|
+
* ],
|
|
90
|
+
* });
|
|
91
|
+
*/
|
|
92
|
+
export function securityHeaders(
|
|
93
|
+
config: SecurityHeadersConfig = {},
|
|
94
|
+
): GrimoirePlugin {
|
|
95
|
+
return {
|
|
96
|
+
name: "grimoire-security-headers",
|
|
97
|
+
async onRequest(req, next) {
|
|
98
|
+
const res = await next();
|
|
99
|
+
const url = new URL(req.url);
|
|
100
|
+
const headers = resolveHeaders(config, url.pathname);
|
|
101
|
+
|
|
102
|
+
return withHeaders(res, Object.entries(headers));
|
|
103
|
+
},
|
|
104
|
+
};
|
|
105
|
+
}
|
package/src/logger/transports.ts
CHANGED
|
@@ -1,117 +1,117 @@
|
|
|
1
|
-
// packages/grimoire/src/logger/transports.ts
|
|
2
|
-
|
|
3
|
-
import { appendFileSync } from "node:fs";
|
|
4
|
-
import type { LogEntry, LogTransport } from "./types.ts";
|
|
5
|
-
|
|
6
|
-
// ── colours (only applied when stdout is a TTY) ──────────────────────────────
|
|
7
|
-
|
|
8
|
-
const isTTY = process.stdout.isTTY;
|
|
9
|
-
const c = isTTY
|
|
10
|
-
? {
|
|
11
|
-
reset: "\x1b[0m",
|
|
12
|
-
dim: "\x1b[2m",
|
|
13
|
-
bold: "\x1b[1m",
|
|
14
|
-
debug: "\x1b[90m", // grey
|
|
15
|
-
info: "\x1b[36m", // cyan
|
|
16
|
-
warn: "\x1b[33m", // yellow
|
|
17
|
-
error: "\x1b[31m", // red
|
|
18
|
-
fatal: "\x1b[35m", // magenta
|
|
19
|
-
scope: "\x1b[34m", // blue
|
|
20
|
-
req: "\x1b[32m", // green
|
|
21
|
-
}
|
|
22
|
-
: (Object.fromEntries(
|
|
23
|
-
[
|
|
24
|
-
"reset",
|
|
25
|
-
"dim",
|
|
26
|
-
"bold",
|
|
27
|
-
"debug",
|
|
28
|
-
"info",
|
|
29
|
-
"warn",
|
|
30
|
-
"error",
|
|
31
|
-
"fatal",
|
|
32
|
-
"scope",
|
|
33
|
-
"req",
|
|
34
|
-
].map((k) => [k, ""]),
|
|
35
|
-
) as Record<string, string>);
|
|
36
|
-
|
|
37
|
-
const LEVEL_LABEL: Record<string, string> = {
|
|
38
|
-
debug: "DBG",
|
|
39
|
-
info: "INF",
|
|
40
|
-
warn: "WRN",
|
|
41
|
-
error: "ERR",
|
|
42
|
-
fatal: "FTL",
|
|
43
|
-
};
|
|
44
|
-
|
|
45
|
-
function ts(timestamp: number): string {
|
|
46
|
-
return new Date(timestamp).toISOString().slice(11, 23); // HH:mm:ss.ms
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
function formatData(data: unknown): string {
|
|
50
|
-
if (data === undefined) return "";
|
|
51
|
-
if (data instanceof Error) return `\n ${data.stack ?? data.message}`;
|
|
52
|
-
if (typeof data !== "object" || data === null) return ` ${String(data)}`;
|
|
53
|
-
|
|
54
|
-
// flat key=value for simple objects, JSON block only for nested/complex
|
|
55
|
-
const entries = Object.entries(data as Record<string, unknown>);
|
|
56
|
-
const isFlat = entries.every(([, v]) => typeof v !== "object" || v === null);
|
|
57
|
-
if (isFlat) {
|
|
58
|
-
return ` ${entries.map(([k, v]) => `${c.dim}${k}=${c.reset}${v}`).join(" ")}`;
|
|
59
|
-
}
|
|
60
|
-
// nested — indent but don't pretty-print the whole thing
|
|
61
|
-
return `\n ${JSON.stringify(data).replace(/,/g, ", ")}`;
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
// ── ConsoleTransport ─────────────────────────────────────────────────────────
|
|
65
|
-
|
|
66
|
-
export class ConsoleTransport implements LogTransport {
|
|
67
|
-
write(entry: LogEntry) {
|
|
68
|
-
const levelColor = c[entry.level] ?? c.info;
|
|
69
|
-
const label = LEVEL_LABEL[entry.level] ?? entry.level.toUpperCase();
|
|
70
|
-
|
|
71
|
-
const worker = entry.worker ? `${c.dim}[${entry.worker}]${c.reset} ` : "";
|
|
72
|
-
const requestId = entry.requestId
|
|
73
|
-
? `${c.req}#${entry.requestId.slice(0, 8)}${c.reset} `
|
|
74
|
-
: "";
|
|
75
|
-
const scope = `${c.scope}${entry.scope}${c.reset}`;
|
|
76
|
-
const time = `${c.dim}${ts(entry.timestamp)}${c.reset}`;
|
|
77
|
-
const lvl = `${levelColor}${c.bold}${label}${c.reset}`;
|
|
78
|
-
const msg = entry.message;
|
|
79
|
-
const data = formatData(entry.data);
|
|
80
|
-
|
|
81
|
-
const line = `${time} ${lvl} ${worker}${requestId}${scope} ${msg}${data}`;
|
|
82
|
-
|
|
83
|
-
if (entry.level === "error" || entry.level === "fatal") {
|
|
84
|
-
process.stderr.write(`${line}\n`);
|
|
85
|
-
} else {
|
|
86
|
-
process.stdout.write(`${line}\n`);
|
|
87
|
-
}
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
// ── FileTransport ────────────────────────────────────────────────────────────
|
|
92
|
-
// Writes newline-delimited JSON for ingestion by log collectors.
|
|
93
|
-
|
|
94
|
-
export class FileTransport implements LogTransport {
|
|
95
|
-
constructor(private path: string) {}
|
|
96
|
-
|
|
97
|
-
write(entry: LogEntry) {
|
|
98
|
-
try {
|
|
99
|
-
appendFileSync(this.path, `${JSON.stringify(entry)}\n`);
|
|
100
|
-
} catch {
|
|
101
|
-
// if the file write fails we can't really do anything useful
|
|
102
|
-
}
|
|
103
|
-
}
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
// ── NullTransport ────────────────────────────────────────────────────────────
|
|
107
|
-
// For tests — captures entries instead of printing them.
|
|
108
|
-
|
|
109
|
-
export class NullTransport implements LogTransport {
|
|
110
|
-
readonly entries: LogEntry[] = [];
|
|
111
|
-
write(entry: LogEntry) {
|
|
112
|
-
this.entries.push(entry);
|
|
113
|
-
}
|
|
114
|
-
clear() {
|
|
115
|
-
this.entries.length = 0;
|
|
116
|
-
}
|
|
117
|
-
}
|
|
1
|
+
// packages/grimoire/src/logger/transports.ts
|
|
2
|
+
|
|
3
|
+
import { appendFileSync } from "node:fs";
|
|
4
|
+
import type { LogEntry, LogTransport } from "./types.ts";
|
|
5
|
+
|
|
6
|
+
// ── colours (only applied when stdout is a TTY) ──────────────────────────────
|
|
7
|
+
|
|
8
|
+
const isTTY = process.stdout.isTTY;
|
|
9
|
+
const c = isTTY
|
|
10
|
+
? {
|
|
11
|
+
reset: "\x1b[0m",
|
|
12
|
+
dim: "\x1b[2m",
|
|
13
|
+
bold: "\x1b[1m",
|
|
14
|
+
debug: "\x1b[90m", // grey
|
|
15
|
+
info: "\x1b[36m", // cyan
|
|
16
|
+
warn: "\x1b[33m", // yellow
|
|
17
|
+
error: "\x1b[31m", // red
|
|
18
|
+
fatal: "\x1b[35m", // magenta
|
|
19
|
+
scope: "\x1b[34m", // blue
|
|
20
|
+
req: "\x1b[32m", // green
|
|
21
|
+
}
|
|
22
|
+
: (Object.fromEntries(
|
|
23
|
+
[
|
|
24
|
+
"reset",
|
|
25
|
+
"dim",
|
|
26
|
+
"bold",
|
|
27
|
+
"debug",
|
|
28
|
+
"info",
|
|
29
|
+
"warn",
|
|
30
|
+
"error",
|
|
31
|
+
"fatal",
|
|
32
|
+
"scope",
|
|
33
|
+
"req",
|
|
34
|
+
].map((k) => [k, ""]),
|
|
35
|
+
) as Record<string, string>);
|
|
36
|
+
|
|
37
|
+
const LEVEL_LABEL: Record<string, string> = {
|
|
38
|
+
debug: "DBG",
|
|
39
|
+
info: "INF",
|
|
40
|
+
warn: "WRN",
|
|
41
|
+
error: "ERR",
|
|
42
|
+
fatal: "FTL",
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
function ts(timestamp: number): string {
|
|
46
|
+
return new Date(timestamp).toISOString().slice(11, 23); // HH:mm:ss.ms
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function formatData(data: unknown): string {
|
|
50
|
+
if (data === undefined) return "";
|
|
51
|
+
if (data instanceof Error) return `\n ${data.stack ?? data.message}`;
|
|
52
|
+
if (typeof data !== "object" || data === null) return ` ${String(data)}`;
|
|
53
|
+
|
|
54
|
+
// flat key=value for simple objects, JSON block only for nested/complex
|
|
55
|
+
const entries = Object.entries(data as Record<string, unknown>);
|
|
56
|
+
const isFlat = entries.every(([, v]) => typeof v !== "object" || v === null);
|
|
57
|
+
if (isFlat) {
|
|
58
|
+
return ` ${entries.map(([k, v]) => `${c.dim}${k}=${c.reset}${v}`).join(" ")}`;
|
|
59
|
+
}
|
|
60
|
+
// nested — indent but don't pretty-print the whole thing
|
|
61
|
+
return `\n ${JSON.stringify(data).replace(/,/g, ", ")}`;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// ── ConsoleTransport ─────────────────────────────────────────────────────────
|
|
65
|
+
|
|
66
|
+
export class ConsoleTransport implements LogTransport {
|
|
67
|
+
write(entry: LogEntry) {
|
|
68
|
+
const levelColor = c[entry.level] ?? c.info;
|
|
69
|
+
const label = LEVEL_LABEL[entry.level] ?? entry.level.toUpperCase();
|
|
70
|
+
|
|
71
|
+
const worker = entry.worker ? `${c.dim}[${entry.worker}]${c.reset} ` : "";
|
|
72
|
+
const requestId = entry.requestId
|
|
73
|
+
? `${c.req}#${entry.requestId.slice(0, 8)}${c.reset} `
|
|
74
|
+
: "";
|
|
75
|
+
const scope = `${c.scope}${entry.scope}${c.reset}`;
|
|
76
|
+
const time = `${c.dim}${ts(entry.timestamp)}${c.reset}`;
|
|
77
|
+
const lvl = `${levelColor}${c.bold}${label}${c.reset}`;
|
|
78
|
+
const msg = entry.message;
|
|
79
|
+
const data = formatData(entry.data);
|
|
80
|
+
|
|
81
|
+
const line = `${time} ${lvl} ${worker}${requestId}${scope} ${msg}${data}`;
|
|
82
|
+
|
|
83
|
+
if (entry.level === "error" || entry.level === "fatal") {
|
|
84
|
+
process.stderr.write(`${line}\n`);
|
|
85
|
+
} else {
|
|
86
|
+
process.stdout.write(`${line}\n`);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// ── FileTransport ────────────────────────────────────────────────────────────
|
|
92
|
+
// Writes newline-delimited JSON for ingestion by log collectors.
|
|
93
|
+
|
|
94
|
+
export class FileTransport implements LogTransport {
|
|
95
|
+
constructor(private path: string) {}
|
|
96
|
+
|
|
97
|
+
write(entry: LogEntry) {
|
|
98
|
+
try {
|
|
99
|
+
appendFileSync(this.path, `${JSON.stringify(entry)}\n`);
|
|
100
|
+
} catch {
|
|
101
|
+
// if the file write fails we can't really do anything useful
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// ── NullTransport ────────────────────────────────────────────────────────────
|
|
107
|
+
// For tests — captures entries instead of printing them.
|
|
108
|
+
|
|
109
|
+
export class NullTransport implements LogTransport {
|
|
110
|
+
readonly entries: LogEntry[] = [];
|
|
111
|
+
write(entry: LogEntry) {
|
|
112
|
+
this.entries.push(entry);
|
|
113
|
+
}
|
|
114
|
+
clear() {
|
|
115
|
+
this.entries.length = 0;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import type { GrimoirePlugin } from "./types";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The listed plugins with each one's `includes` spliced in before it,
|
|
5
|
+
* depth first. One object included twice (two tomes over one database
|
|
6
|
+
* would not, but a shared helper might) is registered once.
|
|
7
|
+
*
|
|
8
|
+
* A listed plugin beats an included one with the same name: listing
|
|
9
|
+
* `adapter({ env: "PG_URL" })` yourself replaces the connection tome would
|
|
10
|
+
* have made. Two listed plugins with one name are left alone; that is the
|
|
11
|
+
* config's own business.
|
|
12
|
+
*/
|
|
13
|
+
export function flattenPlugins<P extends GrimoirePlugin<any>>(
|
|
14
|
+
listed: readonly P[],
|
|
15
|
+
): P[] {
|
|
16
|
+
const listedNames = new Set(listed.map((p) => p.name));
|
|
17
|
+
const seen = new Set<P>();
|
|
18
|
+
const out: P[] = [];
|
|
19
|
+
const visit = (p: P, included: boolean) => {
|
|
20
|
+
if (seen.has(p)) return;
|
|
21
|
+
if (included && listedNames.has(p.name)) return;
|
|
22
|
+
seen.add(p);
|
|
23
|
+
for (const inner of (p.includes ?? []) as P[]) visit(inner, true);
|
|
24
|
+
out.push(p);
|
|
25
|
+
};
|
|
26
|
+
for (const p of listed) visit(p, false);
|
|
27
|
+
return out;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Plugins in the order their `after` and `before` say, and otherwise the
|
|
32
|
+
* order they were listed in.
|
|
33
|
+
*
|
|
34
|
+
* `services()` hands each plugin what the ones before it published, so the
|
|
35
|
+
* list order used to be load-bearing and documented: "register the SQL
|
|
36
|
+
* plugin first". A plugin now says what it needs to run after, and the
|
|
37
|
+
* list can be written in any order.
|
|
38
|
+
*
|
|
39
|
+
* A name a plugin points at that is not registered is ignored here: the
|
|
40
|
+
* plugin that needs it says so when it starts, with the fix. A pattern
|
|
41
|
+
* ending in `*` matches by prefix (`sql:*` is every database).
|
|
42
|
+
*/
|
|
43
|
+
export function orderPlugins<P extends GrimoirePlugin<any>>(
|
|
44
|
+
listed: readonly P[],
|
|
45
|
+
): P[] {
|
|
46
|
+
const plugins = flattenPlugins(listed);
|
|
47
|
+
const n = plugins.length;
|
|
48
|
+
if (n < 2) return plugins;
|
|
49
|
+
const matches = (pattern: string, name: string) =>
|
|
50
|
+
pattern.endsWith("*")
|
|
51
|
+
? name.startsWith(pattern.slice(0, -1))
|
|
52
|
+
: pattern === name;
|
|
53
|
+
const edges: Set<number>[] = plugins.map(() => new Set());
|
|
54
|
+
const add = (from: number, to: number) => {
|
|
55
|
+
if (from !== to) edges[from]!.add(to);
|
|
56
|
+
};
|
|
57
|
+
plugins.forEach((p, i) => {
|
|
58
|
+
for (const pattern of p.after ?? []) {
|
|
59
|
+
plugins.forEach((q, j) => {
|
|
60
|
+
if (matches(pattern, q.name)) add(j, i);
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
for (const pattern of p.before ?? []) {
|
|
64
|
+
plugins.forEach((q, j) => {
|
|
65
|
+
if (matches(pattern, q.name)) add(i, j);
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
});
|
|
69
|
+
const incoming = new Array<number>(n).fill(0);
|
|
70
|
+
for (const set of edges) for (const j of set) incoming[j]!++;
|
|
71
|
+
const out: P[] = [];
|
|
72
|
+
const done = new Array<boolean>(n).fill(false);
|
|
73
|
+
// Kahn's algorithm, always taking the earliest-listed ready plugin, so
|
|
74
|
+
// a list that already satisfies every constraint comes back unchanged.
|
|
75
|
+
for (let k = 0; k < n; k++) {
|
|
76
|
+
const next = incoming.findIndex((c, i) => c === 0 && !done[i]);
|
|
77
|
+
if (next === -1) {
|
|
78
|
+
const stuck = plugins.filter((_, i) => !done[i]).map((p) => p.name);
|
|
79
|
+
throw new Error(
|
|
80
|
+
`Grimoire: plugins ${stuck.map((s) => `"${s}"`).join(", ")} each want to run after another of them, so there is no order that works. Check their \`after\` and \`before\`.`,
|
|
81
|
+
);
|
|
82
|
+
}
|
|
83
|
+
done[next] = true;
|
|
84
|
+
out.push(plugins[next]!);
|
|
85
|
+
for (const j of edges[next]!) incoming[j]!--;
|
|
86
|
+
}
|
|
87
|
+
return out;
|
|
88
|
+
}
|