@thexjs/core 1.3.6 → 1.4.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.md +17 -0
- package/dist/adapter.js +2 -1
- package/dist/{chunk-VAWSOVGY.js → chunk-VC5XI6HX.js} +27 -2
- package/dist/chunk-VIXLBKMC.js +170 -0
- package/dist/data.d.ts +0 -1
- package/dist/data.js +89 -21
- package/dist/index.d.ts +74 -2
- package/dist/index.js +170 -100
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -53,6 +53,23 @@ Given a `pagesDir`, `scanPages` walks the directory and maps files to routes:
|
|
|
53
53
|
|
|
54
54
|
Files and directories prefixed with `_` or `.` are never treated as routes.
|
|
55
55
|
|
|
56
|
+
### Route resolution order
|
|
57
|
+
|
|
58
|
+
When several routes could match one URL, the most specific one wins:
|
|
59
|
+
|
|
60
|
+
1. **Static (literal) routes beat dynamic ones** — `/users/new` is served by
|
|
61
|
+
`pages/users/new.tsx`, never by `pages/users/[id].tsx`.
|
|
62
|
+
2. **Single-segment params beat catch-alls** — `[slug].tsx` matches
|
|
63
|
+
`/blog/hello` over `[...rest].tsx`.
|
|
64
|
+
3. **Same-category ties are broken segment-by-segment, positionally**: at the
|
|
65
|
+
first segment where two routes differ, a literal segment (`users`) beats a
|
|
66
|
+
param (`:id`) which beats a catch-all (`*`). For example `pages/users/[id].tsx`
|
|
67
|
+
(`/users/:id`) beats `pages/[slug]/profile.tsx` (`/:slug/profile`) for the
|
|
68
|
+
URL `/users/profile`, because their first segments are literal vs. param.
|
|
69
|
+
Fully tied routes (identical segment specificity) fall back to a lexical
|
|
70
|
+
sort by route path. The outcome is deterministic, independent of the OS's
|
|
71
|
+
directory-scan order — you never need to rename files to force a winner.
|
|
72
|
+
|
|
56
73
|
Underlying scanners (`scanRoutes`, `scanPages`, `scanApiDir`, `scanLayouts`, `scanLayoutsDir`, `scanMiddleware`, `scanNotFound`) and chain resolvers (`findLayoutChain`, `findMiddlewareChain`) are exported if you need to build custom tooling on top of the same conventions.
|
|
57
74
|
|
|
58
75
|
## Route modes: static vs. server
|
package/dist/adapter.js
CHANGED
|
@@ -1,3 +1,8 @@
|
|
|
1
|
+
import {
|
|
2
|
+
OTEL_ERROR_STATUS_CODE,
|
|
3
|
+
tracePhase
|
|
4
|
+
} from "./chunk-VIXLBKMC.js";
|
|
5
|
+
|
|
1
6
|
// src/security/env-isolation.ts
|
|
2
7
|
var PUBLIC_ENV_PREFIX = "THEXJS_PUBLIC_";
|
|
3
8
|
var ENV_ACCESS_PATTERNS = [
|
|
@@ -86,7 +91,6 @@ function createSentryReporter(sentry) {
|
|
|
86
91
|
}
|
|
87
92
|
};
|
|
88
93
|
}
|
|
89
|
-
var OTEL_ERROR_STATUS_CODE = 2;
|
|
90
94
|
function createOtelReporter(tracer) {
|
|
91
95
|
return {
|
|
92
96
|
captureException(error, context) {
|
|
@@ -311,6 +315,21 @@ export function href<T extends keyof RouteMap & string>(
|
|
|
311
315
|
for (const [key, value] of Object.entries(params)) {
|
|
312
316
|
result = result.replace(new RegExp(\`:\${key}(?=/|$)\`), encodeURIComponent(String(value)));
|
|
313
317
|
}
|
|
318
|
+
// Catch-all params have no \`:name\` token in the path \u2014 they render as an
|
|
319
|
+
// anonymous \`*\` segment. Substitute them in segment order, keeping \`/\`
|
|
320
|
+
// between encoded fragments so multi-segment values stay readable. An exact
|
|
321
|
+
// segment-token check (prefixed by \`/\`) is required: a prefix scan of
|
|
322
|
+
// \`:key\` would also match a longer \`:id2\` param and skip the wildcard.
|
|
323
|
+
const isNamedToken = (key: string) => new RegExp(\`(^|/):\${key}(?=/|$)\`).test(path);
|
|
324
|
+
for (const [key, value] of Object.entries(params)) {
|
|
325
|
+
if (!isNamedToken(key)) {
|
|
326
|
+
const encoded = String(value)
|
|
327
|
+
.split("/")
|
|
328
|
+
.map(encodeURIComponent)
|
|
329
|
+
.join("/");
|
|
330
|
+
result = result.replace(/\\*/, encoded);
|
|
331
|
+
}
|
|
332
|
+
}
|
|
314
333
|
result = result.replace(/\\*+$/, "");
|
|
315
334
|
return result;
|
|
316
335
|
}
|
|
@@ -541,7 +560,11 @@ function getServerFunctionHandler(csrfOptions) {
|
|
|
541
560
|
return new Response("Invalid request body", { status: 400 });
|
|
542
561
|
}
|
|
543
562
|
try {
|
|
544
|
-
const result = await
|
|
563
|
+
const result = await tracePhase(
|
|
564
|
+
"x.action",
|
|
565
|
+
{ route: concretePath, action: actionName },
|
|
566
|
+
() => fn(...args)
|
|
567
|
+
);
|
|
545
568
|
return Response.json(result);
|
|
546
569
|
} catch (err) {
|
|
547
570
|
const errorId = crypto.randomUUID().replace(/-/g, "");
|
|
@@ -775,6 +798,8 @@ export {
|
|
|
775
798
|
DEFAULT_MAX_BODY_SIZE,
|
|
776
799
|
RequestBodyTooLargeError,
|
|
777
800
|
enforceRequestBodySize,
|
|
801
|
+
originFromHeader,
|
|
802
|
+
requestOrigin,
|
|
778
803
|
verifyOrigin,
|
|
779
804
|
generateCsrfToken,
|
|
780
805
|
verifyCsrfToken,
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
// src/observability/redact.ts
|
|
2
|
+
var REDACTED = "[REDACTED]";
|
|
3
|
+
var SENSITIVE_KEY_RE = /(password|passwd|token|secret|authorization|cookie|session|credential|api[_ -]?key|private[_ -]?key|access[_ -]?key|refresh[_ -]?token|bearer)/i;
|
|
4
|
+
function isSensitiveKey(key) {
|
|
5
|
+
return SENSITIVE_KEY_RE.test(key);
|
|
6
|
+
}
|
|
7
|
+
function redactString(input) {
|
|
8
|
+
return input.replace(/\b(Bearer|Basic)\s+[A-Za-z0-9._~+/=:-]+/gi, "$1 " + REDACTED).replace(/\b(authorization|auth)\s*[:=]\s*[^\s,;]+/gi, "$1 " + REDACTED).replace(/(\b[a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^/\s@:]*:)([^/\s]*)(@)/g, `$1${REDACTED}$3`);
|
|
9
|
+
}
|
|
10
|
+
function redactValue(value, depth = 0) {
|
|
11
|
+
if (typeof value === "string") return redactString(value);
|
|
12
|
+
if (depth > 10) return value;
|
|
13
|
+
if (Array.isArray(value)) return value.map((v) => redactValue(v, depth + 1));
|
|
14
|
+
if (value !== null && typeof value === "object") {
|
|
15
|
+
const out = {};
|
|
16
|
+
for (const [key, val] of Object.entries(value)) {
|
|
17
|
+
out[key] = isSensitiveKey(key) ? REDACTED : redactValue(val, depth + 1);
|
|
18
|
+
}
|
|
19
|
+
return out;
|
|
20
|
+
}
|
|
21
|
+
return value;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// src/observability/tracing.ts
|
|
25
|
+
var noopSpan = {
|
|
26
|
+
setAttribute: () => {
|
|
27
|
+
},
|
|
28
|
+
recordException: () => {
|
|
29
|
+
},
|
|
30
|
+
setStatus: () => {
|
|
31
|
+
},
|
|
32
|
+
end: () => {
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
var noopTracer = {
|
|
36
|
+
startSpan: () => noopSpan
|
|
37
|
+
};
|
|
38
|
+
var activeTracer = noopTracer;
|
|
39
|
+
function setTracer(tracer) {
|
|
40
|
+
activeTracer = tracer;
|
|
41
|
+
}
|
|
42
|
+
function getTracer() {
|
|
43
|
+
return activeTracer;
|
|
44
|
+
}
|
|
45
|
+
var OTEL_ERROR_STATUS_CODE = 2;
|
|
46
|
+
var requestStorage = null;
|
|
47
|
+
function asyncLocalStorage() {
|
|
48
|
+
if (requestStorage) return requestStorage;
|
|
49
|
+
try {
|
|
50
|
+
const { AsyncLocalStorage } = import.meta.require("node:async_hooks");
|
|
51
|
+
requestStorage = new AsyncLocalStorage();
|
|
52
|
+
} catch {
|
|
53
|
+
requestStorage = {
|
|
54
|
+
getStore: () => void 0,
|
|
55
|
+
run: (_ctx, fn) => fn()
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
return requestStorage;
|
|
59
|
+
}
|
|
60
|
+
async function runWithRequestSpan(requestId, initAttributes, work) {
|
|
61
|
+
const root = activeTracer.startSpan("x.http", {
|
|
62
|
+
attributes: { "x.requestId": requestId, ...initAttributes }
|
|
63
|
+
});
|
|
64
|
+
const storage = asyncLocalStorage();
|
|
65
|
+
return storage.run({ requestId }, async () => {
|
|
66
|
+
try {
|
|
67
|
+
const value = await work(
|
|
68
|
+
(attributes) => {
|
|
69
|
+
if (attributes) {
|
|
70
|
+
for (const [key, item] of Object.entries(attributes)) {
|
|
71
|
+
root.setAttribute(key, item);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
},
|
|
75
|
+
(error) => recordError(root, error)
|
|
76
|
+
);
|
|
77
|
+
root.end();
|
|
78
|
+
return value;
|
|
79
|
+
} catch (error) {
|
|
80
|
+
recordError(root, error);
|
|
81
|
+
root.end();
|
|
82
|
+
throw error;
|
|
83
|
+
}
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
function recordError(span, error) {
|
|
87
|
+
span.recordException(error);
|
|
88
|
+
span.setStatus({
|
|
89
|
+
code: OTEL_ERROR_STATUS_CODE,
|
|
90
|
+
message: error instanceof Error ? error.message : String(error)
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
async function tracePhase(name, attributes, work) {
|
|
94
|
+
const context = asyncLocalStorage().getStore();
|
|
95
|
+
if (!context) return work();
|
|
96
|
+
const span = activeTracer.startSpan(name, {
|
|
97
|
+
attributes: { "x.requestId": context.requestId, ...attributes }
|
|
98
|
+
});
|
|
99
|
+
try {
|
|
100
|
+
return await work();
|
|
101
|
+
} catch (error) {
|
|
102
|
+
recordError(span, error);
|
|
103
|
+
throw error;
|
|
104
|
+
} finally {
|
|
105
|
+
span.end();
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
function tracePhaseSync(name, attributes, work) {
|
|
109
|
+
const context = asyncLocalStorage().getStore();
|
|
110
|
+
if (!context) return work();
|
|
111
|
+
const span = activeTracer.startSpan(name, {
|
|
112
|
+
attributes: { "x.requestId": context.requestId, ...attributes }
|
|
113
|
+
});
|
|
114
|
+
try {
|
|
115
|
+
return work();
|
|
116
|
+
} catch (error) {
|
|
117
|
+
recordError(span, error);
|
|
118
|
+
throw error;
|
|
119
|
+
} finally {
|
|
120
|
+
span.end();
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
function maskSqlLiterals(statement) {
|
|
124
|
+
return statement.replace(/'(?:[^']|'')*'/g, "'?'").replace(/"(?:[^"]|"")*"/g, '"?"');
|
|
125
|
+
}
|
|
126
|
+
function dbTraceAttributes(system, statement) {
|
|
127
|
+
const keyword = /^\s*(\w+)/.exec(statement)?.[1]?.toLowerCase();
|
|
128
|
+
return {
|
|
129
|
+
"db.system": system,
|
|
130
|
+
"db.operation": keyword ?? "other",
|
|
131
|
+
"db.statement": maskSqlLiterals(redactString(statement)).trim().slice(0, 512)
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
var requestIds = /* @__PURE__ */ new WeakMap();
|
|
135
|
+
function traceRequestId(req) {
|
|
136
|
+
return requestIds.get(req) ?? req.headers.get("x-request-id") ?? crypto.randomUUID();
|
|
137
|
+
}
|
|
138
|
+
function withRequestTracing(handler) {
|
|
139
|
+
return async (req, server) => {
|
|
140
|
+
const existing = req.headers.get("x-request-id");
|
|
141
|
+
const requestId = existing ?? crypto.randomUUID();
|
|
142
|
+
if (!existing) requestIds.set(req, requestId);
|
|
143
|
+
const url = new URL(req.url);
|
|
144
|
+
return runWithRequestSpan(
|
|
145
|
+
requestId,
|
|
146
|
+
{ route: url.pathname, method: req.method },
|
|
147
|
+
async (finish) => {
|
|
148
|
+
const res = await handler(req, server);
|
|
149
|
+
finish({ "http.response.status_code": res.status });
|
|
150
|
+
return res;
|
|
151
|
+
}
|
|
152
|
+
);
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export {
|
|
157
|
+
REDACTED,
|
|
158
|
+
isSensitiveKey,
|
|
159
|
+
redactString,
|
|
160
|
+
redactValue,
|
|
161
|
+
setTracer,
|
|
162
|
+
getTracer,
|
|
163
|
+
OTEL_ERROR_STATUS_CODE,
|
|
164
|
+
runWithRequestSpan,
|
|
165
|
+
tracePhase,
|
|
166
|
+
tracePhaseSync,
|
|
167
|
+
dbTraceAttributes,
|
|
168
|
+
traceRequestId,
|
|
169
|
+
withRequestTracing
|
|
170
|
+
};
|
package/dist/data.d.ts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { Database } from 'bun:sqlite';
|
|
2
2
|
|
|
3
|
-
/** A Postgres client scoped to a single transaction (auto-commit/rollback). */
|
|
4
3
|
interface PostgresTransactionClient {
|
|
5
4
|
unsafe(query: string, params?: unknown[]): Promise<unknown>;
|
|
6
5
|
(strings: TemplateStringsArray, ...values: unknown[]): Promise<unknown>;
|
package/dist/data.js
CHANGED
|
@@ -1,3 +1,9 @@
|
|
|
1
|
+
import {
|
|
2
|
+
dbTraceAttributes,
|
|
3
|
+
tracePhase,
|
|
4
|
+
tracePhaseSync
|
|
5
|
+
} from "./chunk-VIXLBKMC.js";
|
|
6
|
+
|
|
1
7
|
// src/data/migrate.ts
|
|
2
8
|
import { readdirSync, readFileSync } from "fs";
|
|
3
9
|
import { join } from "path";
|
|
@@ -39,13 +45,8 @@ function runSQLiteMigrations(db, migrationsDir) {
|
|
|
39
45
|
}
|
|
40
46
|
return result;
|
|
41
47
|
}
|
|
48
|
+
var MIGRATION_LOCK_KEY = 791975531451977;
|
|
42
49
|
async function runPostgresMigrations(client, migrationsDir) {
|
|
43
|
-
await client.unsafe(`CREATE TABLE IF NOT EXISTS _x_migrations (
|
|
44
|
-
name TEXT PRIMARY KEY,
|
|
45
|
-
applied_at TIMESTAMP DEFAULT NOW()
|
|
46
|
-
)`);
|
|
47
|
-
const rows = await client.unsafe("SELECT name FROM _x_migrations");
|
|
48
|
-
const applied = new Set(rows.map((r) => r.name));
|
|
49
50
|
let files;
|
|
50
51
|
try {
|
|
51
52
|
files = readdirSync(migrationsDir).filter((f) => f.endsWith(".sql")).sort(compareMigrationNames);
|
|
@@ -53,19 +54,41 @@ async function runPostgresMigrations(client, migrationsDir) {
|
|
|
53
54
|
return { applied: [], skipped: [] };
|
|
54
55
|
}
|
|
55
56
|
const result = { applied: [], skipped: [] };
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
57
|
+
let failed = null;
|
|
58
|
+
await client.begin(async (tx) => {
|
|
59
|
+
await tx.unsafe("SELECT pg_advisory_xact_lock($1)", [MIGRATION_LOCK_KEY]);
|
|
60
|
+
await tx.unsafe(`CREATE TABLE IF NOT EXISTS _x_migrations (
|
|
61
|
+
name TEXT PRIMARY KEY,
|
|
62
|
+
applied_at TIMESTAMP DEFAULT NOW()
|
|
63
|
+
)`);
|
|
64
|
+
const rows = await tx.unsafe("SELECT name FROM _x_migrations");
|
|
65
|
+
const applied = new Set(rows.map((r) => r.name));
|
|
66
|
+
let seq = 0;
|
|
67
|
+
for (const file of files) {
|
|
68
|
+
if (applied.has(file)) {
|
|
69
|
+
result.skipped.push(file);
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
if (failed !== null) break;
|
|
73
|
+
const raw = readFileSync(join(migrationsDir, file), "utf-8");
|
|
74
|
+
const savepoint = `x_migration_${seq++}`;
|
|
75
|
+
await tx.unsafe(`SAVEPOINT ${savepoint}`);
|
|
76
|
+
try {
|
|
77
|
+
await tx.unsafe(raw);
|
|
78
|
+
await tx.unsafe("INSERT INTO _x_migrations (name) VALUES ($1)", [file]);
|
|
79
|
+
await tx.unsafe(`RELEASE SAVEPOINT ${savepoint}`);
|
|
80
|
+
console.log(`[x] migration applied: ${file}`);
|
|
81
|
+
result.applied.push(file);
|
|
82
|
+
} catch (err) {
|
|
83
|
+
await tx.unsafe(`ROLLBACK TO SAVEPOINT ${savepoint}`).catch(() => {
|
|
84
|
+
});
|
|
85
|
+
await tx.unsafe(`RELEASE SAVEPOINT ${savepoint}`).catch(() => {
|
|
86
|
+
});
|
|
87
|
+
failed = err;
|
|
88
|
+
}
|
|
60
89
|
}
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
await tx.unsafe(raw);
|
|
64
|
-
await tx.unsafe("INSERT INTO _x_migrations (name) VALUES ($1)", [file]);
|
|
65
|
-
});
|
|
66
|
-
console.log(`[x] migration applied: ${file}`);
|
|
67
|
-
result.applied.push(file);
|
|
68
|
-
}
|
|
90
|
+
});
|
|
91
|
+
if (failed !== null) throw failed;
|
|
69
92
|
return result;
|
|
70
93
|
}
|
|
71
94
|
|
|
@@ -137,7 +160,13 @@ function connectPostgres(options = {}) {
|
|
|
137
160
|
return new Proxy(sql, {
|
|
138
161
|
get(target, prop, receiver) {
|
|
139
162
|
if (prop === "unsafe") {
|
|
140
|
-
return (query, params) => run(
|
|
163
|
+
return (query, params) => run(
|
|
164
|
+
() => tracePhase(
|
|
165
|
+
"x.db",
|
|
166
|
+
dbTraceAttributes("postgres", query),
|
|
167
|
+
() => client.unsafe(query, params)
|
|
168
|
+
)
|
|
169
|
+
);
|
|
141
170
|
}
|
|
142
171
|
if (prop === "begin") {
|
|
143
172
|
return (fn) => run(() => client.begin(async (tx) => fn(tx)));
|
|
@@ -147,7 +176,14 @@ function connectPostgres(options = {}) {
|
|
|
147
176
|
},
|
|
148
177
|
apply(_target, _thisArg, args) {
|
|
149
178
|
const [strings, ...values] = args;
|
|
150
|
-
|
|
179
|
+
const statement = strings.join("?");
|
|
180
|
+
return run(
|
|
181
|
+
() => tracePhase(
|
|
182
|
+
"x.db",
|
|
183
|
+
dbTraceAttributes("postgres", statement),
|
|
184
|
+
() => client(strings, ...values)
|
|
185
|
+
)
|
|
186
|
+
);
|
|
151
187
|
}
|
|
152
188
|
});
|
|
153
189
|
}
|
|
@@ -163,6 +199,38 @@ function loadBunSQLite() {
|
|
|
163
199
|
);
|
|
164
200
|
}
|
|
165
201
|
}
|
|
202
|
+
function traceSQLite(db) {
|
|
203
|
+
return new Proxy(db, {
|
|
204
|
+
get(target, prop, receiver) {
|
|
205
|
+
const value = Reflect.get(target, prop, receiver);
|
|
206
|
+
if (typeof value !== "function") return value;
|
|
207
|
+
if (prop === "query") {
|
|
208
|
+
return (sql) => traceStatement(value.call(target, sql), sql);
|
|
209
|
+
}
|
|
210
|
+
if (prop === "run" || prop === "execute") {
|
|
211
|
+
return (...args) => tracePhaseSync(
|
|
212
|
+
"x.db",
|
|
213
|
+
dbTraceAttributes("sqlite", String(args[0] ?? "")),
|
|
214
|
+
() => value.apply(target, args)
|
|
215
|
+
);
|
|
216
|
+
}
|
|
217
|
+
return value.bind(target);
|
|
218
|
+
}
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
function traceStatement(statement, sql) {
|
|
222
|
+
if (statement === null || typeof statement !== "object") return statement;
|
|
223
|
+
return new Proxy(statement, {
|
|
224
|
+
get(target, prop, receiver) {
|
|
225
|
+
const value = Reflect.get(target, prop, receiver);
|
|
226
|
+
if (typeof value !== "function") return value;
|
|
227
|
+
if (prop === "all" || prop === "get" || prop === "run" || prop === "values") {
|
|
228
|
+
return (...args) => tracePhaseSync("x.db", dbTraceAttributes("sqlite", sql), () => value.apply(target, args));
|
|
229
|
+
}
|
|
230
|
+
return value.bind(target);
|
|
231
|
+
}
|
|
232
|
+
});
|
|
233
|
+
}
|
|
166
234
|
function connectSQLite(options) {
|
|
167
235
|
const { Database: DB } = loadBunSQLite();
|
|
168
236
|
const db = new DB(options?.path ?? "data/dev.db");
|
|
@@ -172,7 +240,7 @@ function connectSQLite(options) {
|
|
|
172
240
|
if (options?.foreignKeys !== false) {
|
|
173
241
|
db.run("PRAGMA foreign_keys = ON");
|
|
174
242
|
}
|
|
175
|
-
return db;
|
|
243
|
+
return traceSQLite(db);
|
|
176
244
|
}
|
|
177
245
|
export {
|
|
178
246
|
connectPostgres,
|
package/dist/index.d.ts
CHANGED
|
@@ -766,7 +766,7 @@ declare function withRequestLogging<Server = unknown>(handler: (req: Request, se
|
|
|
766
766
|
declare const REDACTED = "[REDACTED]";
|
|
767
767
|
/** True when a field key looks like it holds a secret value. */
|
|
768
768
|
declare function isSensitiveKey(key: string): boolean;
|
|
769
|
-
/** Masks bearer/basic credentials
|
|
769
|
+
/** Masks bearer/basic credentials, inline `Authorization: ...` values and URI userinfo (connection strings) in a string. */
|
|
770
770
|
declare function redactString(input: string): string;
|
|
771
771
|
/**
|
|
772
772
|
* Recursively redacts a value before it is serialized to a log line:
|
|
@@ -778,6 +778,78 @@ declare function redactString(input: string): string;
|
|
|
778
778
|
*/
|
|
779
779
|
declare function redactValue(value: unknown, depth?: number): unknown;
|
|
780
780
|
|
|
781
|
+
/**
|
|
782
|
+
* Request-scoped tracing.
|
|
783
|
+
*
|
|
784
|
+
* `@thexjs/core` never initializes an OpenTelemetry SDK — apps opt in by
|
|
785
|
+
* providing a tracer whose spans match the tiny surface below (the real OTel
|
|
786
|
+
* `startSpan(name, { attributes })` fits). When no tracer is configured the
|
|
787
|
+
* whole layer degrades to synchronous no-ops, and when work runs outside a
|
|
788
|
+
* traced request (a scheduler, a build-time render, a worker thread) phase
|
|
789
|
+
* spans are skipped entirely.
|
|
790
|
+
*
|
|
791
|
+
* Correlation: every span carries the request's `x.requestId` as the
|
|
792
|
+
* `x.requestId` attribute, and the root `x.http` span also records route,
|
|
793
|
+
* method and response status. SDK-level parent/child wiring is the app's
|
|
794
|
+
* concern (it owns the OTel context); this module records the correlation
|
|
795
|
+
* attribute that makes spans drillable.
|
|
796
|
+
*/
|
|
797
|
+
interface TraceSpan {
|
|
798
|
+
setAttribute(key: string, value: unknown): void;
|
|
799
|
+
recordException(error: unknown): void;
|
|
800
|
+
setStatus(status: {
|
|
801
|
+
code: number;
|
|
802
|
+
message?: string;
|
|
803
|
+
}): void;
|
|
804
|
+
end(): void;
|
|
805
|
+
}
|
|
806
|
+
/** Minimal surface a tracer must expose. Compatible with OTel's `Tracer`. */
|
|
807
|
+
interface TracerLike {
|
|
808
|
+
startSpan(name: string, options?: {
|
|
809
|
+
attributes?: Record<string, unknown>;
|
|
810
|
+
}): TraceSpan;
|
|
811
|
+
}
|
|
812
|
+
declare function setTracer(tracer: TracerLike): void;
|
|
813
|
+
declare function getTracer(): TracerLike;
|
|
814
|
+
/** Matches @opentelemetry/api's SpanStatusCode.ERROR. */
|
|
815
|
+
declare const OTEL_ERROR_STATUS_CODE = 2;
|
|
816
|
+
/**
|
|
817
|
+
* Runs `work` inside a traced request context and the `x.http` root span.
|
|
818
|
+
* `finish` records extra attributes on the root span before it closes (e.g.
|
|
819
|
+
* the response status); `fail` records the error as an exception + error
|
|
820
|
+
* status. Spans started via {@link tracePhase} inside `work` inherit the
|
|
821
|
+
* request id.
|
|
822
|
+
*/
|
|
823
|
+
declare function runWithRequestSpan<T>(requestId: string, initAttributes: Record<string, unknown>, work: (finish: (attributes?: Record<string, unknown>) => void, fail: (error: unknown) => void) => Promise<T>): Promise<T>;
|
|
824
|
+
/**
|
|
825
|
+
* Opens a `x.<name>` span carrying the current request's id around `work`,
|
|
826
|
+
* recording any thrown error. Outside a traced request this is a transparent
|
|
827
|
+
* passthrough (no span, no overhead).
|
|
828
|
+
*/
|
|
829
|
+
declare function tracePhase<T>(name: string, attributes: Record<string, unknown>, work: () => Promise<T>): Promise<T>;
|
|
830
|
+
/**
|
|
831
|
+
* Synchronous variant of {@link tracePhase}, for sync APIs like
|
|
832
|
+
* `bun:sqlite`. Same rules: no request context → plain passthrough.
|
|
833
|
+
*/
|
|
834
|
+
declare function tracePhaseSync<T>(name: string, attributes: Record<string, unknown>, work: () => T): T;
|
|
835
|
+
/**
|
|
836
|
+
* Attribute set for a `x.db` span: driver vendor, the statement's operation
|
|
837
|
+
* family (SELECT/INSERT/...) and a redacted + truncated statement. Statements
|
|
838
|
+
* can embed literals; `redactString` masks bearer/authorization-shaped parts,
|
|
839
|
+
* `maskSqlLiterals` collapses every quoted string, and truncation keeps giant
|
|
840
|
+
* queries out of the trace backend.
|
|
841
|
+
*/
|
|
842
|
+
declare function dbTraceAttributes(system: string, statement: string): Record<string, unknown>;
|
|
843
|
+
declare function traceRequestId(req: Request): string;
|
|
844
|
+
/**
|
|
845
|
+
* Wraps a fetch handler so every request gets an `x.http` root span carrying
|
|
846
|
+
* the request id (reusing an inbound `x-request-id` if the ingress already
|
|
847
|
+
* assigned one, otherwise minting one and sharing it via
|
|
848
|
+
* {@link traceRequestId} so downstream wrappers correlate to the same id).
|
|
849
|
+
* The request object is passed through untouched — see {@link traceRequestId}.
|
|
850
|
+
*/
|
|
851
|
+
declare function withRequestTracing<Server = unknown>(handler: (req: Request, server?: Server) => Response | Promise<Response>): (req: Request, server?: Server) => Promise<Response>;
|
|
852
|
+
|
|
781
853
|
interface RenderOptions {
|
|
782
854
|
title?: string;
|
|
783
855
|
islandScripts?: string[];
|
|
@@ -883,4 +955,4 @@ declare function resetServerFunctions(): void;
|
|
|
883
955
|
declare function registerServerFunctions(routePath: string, paramNames: string[], fns: Record<string, (...args: unknown[]) => Promise<unknown>>): void;
|
|
884
956
|
declare function getServerFunctionHandler(csrfOptions?: CsrfOptions): (req: Request) => Promise<Response | null>;
|
|
885
957
|
|
|
886
|
-
export { type AuditEntry, type AuditEvent, type AuditSink, type BuildOptions, CLIENT_NAV_SCRIPT, type ContentEntry, type CounterSeries, type CreateAppOptions, type CsrfOptions, type CsrfResult, DEFAULT_HISTOGRAM_BUCKETS_MS, DEFAULT_MAX_BODY_SIZE, DefaultNotFound, EnvLeakageError, type ErrorContext, type ErrorReporter, type Frontmatter, type HealthCheck, type HealthCheckOptions, type HistogramSeries, Image, type ImageProps, type ImageProxyOptions, type InMemoryMetricsOptions, type InMemoryMetricsReporter, Island, type IslandEntry, type IslandMode, IslandProvider, type LayoutEntry, Link, type LinkProps, type LoaderArgs, type LoaderReturn, type LogFields, type Logger, type MetricLabels, type MetricsReporter, type MetricsSnapshot, type MiddlewareContext, type MiddlewareEntry, type MiddlewareFn, type MiddlewareNext, type NotFoundEntry, type OtelMeterLike, type OtelTracerLike, PUBLIC_ENV_PREFIX, type ProcessCrashHandlerOptions, REDACTED, type RateLimitOptions, type RateLimitResult, type RateLimitStore, type ReadinessResult, RequestBodyTooLargeError, type RevalidateOptions, type RouteEntry, type RouteMode, type RouteProps, SRCSET_WIDTHS, type SecurityHeadersOptions, type SentryLike, applySecurityHeaders, assertNoEnvLeakage, audit, auditLoginFailure, auditLoginSuccess, auditLogout, auditPasswordChanged, auditPermissionDenied, auditRoleChanged, auditSessionRevoked, build, buildSecurityHeaders, buildSrcSet, checkCsrf, clientIpFromRequest, combineReporters, composeMiddleware, createApp, createConsoleAuditSink, createHealthCheckHandler, createImageProxyHandler, createInMemoryMetrics, createOtelReporter, createOtlpMetricsReporter, createRateLimiter, createRedisRateLimitStore, createSentryReporter, defineConfig, enforceRequestBodySize, escapeHtml, findLayoutChain, findLeakedEnvKeys, findMiddlewareChain, generateCsrfToken, generateManifestSource, generateServerFunctionClient, getAuditSink, getErrorReporter, getServerFunctionHandler, installProcessCrashHandlers, isSensitiveKey, logger, noopAuditSink, noopMetrics, noopReporter, rateLimitMiddleware, redactString, redactValue, registerServerFunctions, renderErrorOverlay, renderMarkdown, renderPage, renderStaticPage, renderStreamingPage, reportException, requestIdFromRequest, resetServerFunctions, scanApiDir, scanContent, scanLayouts, scanLayoutsDir, scanMiddleware, scanNotFound, scanPages, scanRoutes, setAuditSink, setErrorReporter, setImageRemoteHosts, verifyCsrfToken, verifyOrigin, withCsrfCookie, withRequestLogging, withRequestMetrics, writeManifest };
|
|
958
|
+
export { type AuditEntry, type AuditEvent, type AuditSink, type BuildOptions, CLIENT_NAV_SCRIPT, type ContentEntry, type CounterSeries, type CreateAppOptions, type CsrfOptions, type CsrfResult, DEFAULT_HISTOGRAM_BUCKETS_MS, DEFAULT_MAX_BODY_SIZE, DefaultNotFound, EnvLeakageError, type ErrorContext, type ErrorReporter, type Frontmatter, type HealthCheck, type HealthCheckOptions, type HistogramSeries, Image, type ImageProps, type ImageProxyOptions, type InMemoryMetricsOptions, type InMemoryMetricsReporter, Island, type IslandEntry, type IslandMode, IslandProvider, type LayoutEntry, Link, type LinkProps, type LoaderArgs, type LoaderReturn, type LogFields, type Logger, type MetricLabels, type MetricsReporter, type MetricsSnapshot, type MiddlewareContext, type MiddlewareEntry, type MiddlewareFn, type MiddlewareNext, type NotFoundEntry, OTEL_ERROR_STATUS_CODE, type OtelMeterLike, type OtelTracerLike, PUBLIC_ENV_PREFIX, type ProcessCrashHandlerOptions, REDACTED, type RateLimitOptions, type RateLimitResult, type RateLimitStore, type ReadinessResult, RequestBodyTooLargeError, type RevalidateOptions, type RouteEntry, type RouteMode, type RouteProps, SRCSET_WIDTHS, type SecurityHeadersOptions, type SentryLike, type TraceSpan, type TracerLike, applySecurityHeaders, assertNoEnvLeakage, audit, auditLoginFailure, auditLoginSuccess, auditLogout, auditPasswordChanged, auditPermissionDenied, auditRoleChanged, auditSessionRevoked, build, buildSecurityHeaders, buildSrcSet, checkCsrf, clientIpFromRequest, combineReporters, composeMiddleware, createApp, createConsoleAuditSink, createHealthCheckHandler, createImageProxyHandler, createInMemoryMetrics, createOtelReporter, createOtlpMetricsReporter, createRateLimiter, createRedisRateLimitStore, createSentryReporter, dbTraceAttributes, defineConfig, enforceRequestBodySize, escapeHtml, findLayoutChain, findLeakedEnvKeys, findMiddlewareChain, generateCsrfToken, generateManifestSource, generateServerFunctionClient, getAuditSink, getErrorReporter, getServerFunctionHandler, getTracer, installProcessCrashHandlers, isSensitiveKey, logger, noopAuditSink, noopMetrics, noopReporter, rateLimitMiddleware, redactString, redactValue, registerServerFunctions, renderErrorOverlay, renderMarkdown, renderPage, renderStaticPage, renderStreamingPage, reportException, requestIdFromRequest, resetServerFunctions, runWithRequestSpan, scanApiDir, scanContent, scanLayouts, scanLayoutsDir, scanMiddleware, scanNotFound, scanPages, scanRoutes, setAuditSink, setErrorReporter, setImageRemoteHosts, setTracer, tracePhase, tracePhaseSync, traceRequestId, verifyCsrfToken, verifyOrigin, withCsrfCookie, withRequestLogging, withRequestMetrics, withRequestTracing, writeManifest };
|
package/dist/index.js
CHANGED
|
@@ -22,8 +22,10 @@ import {
|
|
|
22
22
|
getServerFunctionHandler,
|
|
23
23
|
islandEntryId,
|
|
24
24
|
noopReporter,
|
|
25
|
+
originFromHeader,
|
|
25
26
|
registerServerFunctions,
|
|
26
27
|
reportException,
|
|
28
|
+
requestOrigin,
|
|
27
29
|
resetServerFunctions,
|
|
28
30
|
scanApiDir,
|
|
29
31
|
scanLayouts,
|
|
@@ -37,7 +39,22 @@ import {
|
|
|
37
39
|
verifyOrigin,
|
|
38
40
|
withCsrfCookie,
|
|
39
41
|
writeManifest
|
|
40
|
-
} from "./chunk-
|
|
42
|
+
} from "./chunk-VC5XI6HX.js";
|
|
43
|
+
import {
|
|
44
|
+
OTEL_ERROR_STATUS_CODE,
|
|
45
|
+
REDACTED,
|
|
46
|
+
dbTraceAttributes,
|
|
47
|
+
getTracer,
|
|
48
|
+
isSensitiveKey,
|
|
49
|
+
redactString,
|
|
50
|
+
redactValue,
|
|
51
|
+
runWithRequestSpan,
|
|
52
|
+
setTracer,
|
|
53
|
+
tracePhase,
|
|
54
|
+
tracePhaseSync,
|
|
55
|
+
traceRequestId,
|
|
56
|
+
withRequestTracing
|
|
57
|
+
} from "./chunk-VIXLBKMC.js";
|
|
41
58
|
|
|
42
59
|
// src/build.ts
|
|
43
60
|
import { cpSync, existsSync, mkdirSync, writeFileSync } from "fs";
|
|
@@ -1046,6 +1063,41 @@ async function resolveHostDefault(hostname) {
|
|
|
1046
1063
|
return [];
|
|
1047
1064
|
}
|
|
1048
1065
|
}
|
|
1066
|
+
function urlForIp(target, ip) {
|
|
1067
|
+
const pinned = new URL(target.toString());
|
|
1068
|
+
pinned.hostname = ip.includes(":") ? `[${ip}]` : ip;
|
|
1069
|
+
return pinned;
|
|
1070
|
+
}
|
|
1071
|
+
function pinToVerifiedIp(target, verifiedIp) {
|
|
1072
|
+
const init = { redirect: "manual", headers: { host: target.host } };
|
|
1073
|
+
if (target.protocol === "https:") {
|
|
1074
|
+
init.tls = { serverName: target.hostname };
|
|
1075
|
+
}
|
|
1076
|
+
return { url: urlForIp(target, verifiedIp), init };
|
|
1077
|
+
}
|
|
1078
|
+
async function resolveProxyTarget(target, resolveHost) {
|
|
1079
|
+
if (isIpLiteral(target.hostname)) {
|
|
1080
|
+
if (isPrivateOrReservedAddress(target.hostname)) {
|
|
1081
|
+
return { status: "reject-literal" };
|
|
1082
|
+
}
|
|
1083
|
+
return { status: "ok", url: target, init: { redirect: "manual" } };
|
|
1084
|
+
}
|
|
1085
|
+
let ips = [];
|
|
1086
|
+
try {
|
|
1087
|
+
ips = await resolveHost(target.hostname);
|
|
1088
|
+
} catch {
|
|
1089
|
+
ips = [];
|
|
1090
|
+
}
|
|
1091
|
+
if (ips.some((ip) => isPrivateOrReservedAddress(ip))) {
|
|
1092
|
+
return { status: "reject-dns" };
|
|
1093
|
+
}
|
|
1094
|
+
const verifiedIp = ips[0];
|
|
1095
|
+
if (verifiedIp !== void 0) {
|
|
1096
|
+
const { url, init } = pinToVerifiedIp(target, verifiedIp);
|
|
1097
|
+
return { status: "ok", url, init };
|
|
1098
|
+
}
|
|
1099
|
+
return { status: "ok", url: target, init: { redirect: "manual" } };
|
|
1100
|
+
}
|
|
1049
1101
|
function enforceImageByteCount(body, maxBytes) {
|
|
1050
1102
|
if (body === null) return null;
|
|
1051
1103
|
const source = body;
|
|
@@ -1095,22 +1147,21 @@ function createImageProxyHandler(options = {}) {
|
|
|
1095
1147
|
if (!allowedUrl(parsed)) {
|
|
1096
1148
|
return new Response("host not allow-listed for image proxy", { status: 403 });
|
|
1097
1149
|
}
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
const ips = await resolveHost(parsed.hostname);
|
|
1105
|
-
publicIp = !ips.some((ip) => isPrivateOrReservedAddress(ip));
|
|
1106
|
-
} catch {
|
|
1107
|
-
publicIp = true;
|
|
1108
|
-
}
|
|
1109
|
-
if (!publicIp) {
|
|
1110
|
-
return new Response("target resolves to a private or reserved address", {
|
|
1111
|
-
status: 403
|
|
1112
|
-
});
|
|
1150
|
+
const rejectFor = (status, hop) => {
|
|
1151
|
+
if (status === "reject-literal") {
|
|
1152
|
+
return new Response(
|
|
1153
|
+
hop ? "upstream redirected to a private or reserved address" : "target is a private or reserved address",
|
|
1154
|
+
{ status: 403 }
|
|
1155
|
+
);
|
|
1113
1156
|
}
|
|
1157
|
+
return new Response(
|
|
1158
|
+
hop ? "upstream redirect resolves to a private or reserved address" : "target resolves to a private or reserved address",
|
|
1159
|
+
{ status: 403 }
|
|
1160
|
+
);
|
|
1161
|
+
};
|
|
1162
|
+
const initial = await resolveProxyTarget(parsed, resolveHost);
|
|
1163
|
+
if (initial.status !== "ok") {
|
|
1164
|
+
return rejectFor(initial.status, false);
|
|
1114
1165
|
}
|
|
1115
1166
|
const wParam = reqUrl.searchParams.get("w");
|
|
1116
1167
|
const qParam = reqUrl.searchParams.get("q");
|
|
@@ -1129,7 +1180,7 @@ function createImageProxyHandler(options = {}) {
|
|
|
1129
1180
|
const isRedirect = (status) => status === 301 || status === 302 || status === 303 || status === 307 || status === 308;
|
|
1130
1181
|
let upstream;
|
|
1131
1182
|
try {
|
|
1132
|
-
upstream = await fetch(
|
|
1183
|
+
upstream = await fetch(initial.url, initial.init);
|
|
1133
1184
|
for (let hop = 0; hop < 5; hop++) {
|
|
1134
1185
|
if (!isRedirect(upstream.status)) break;
|
|
1135
1186
|
const location = upstream.headers.get("location");
|
|
@@ -1142,26 +1193,11 @@ function createImageProxyHandler(options = {}) {
|
|
|
1142
1193
|
if (!allowedUrl(next)) {
|
|
1143
1194
|
return new Response("upstream redirected off the allow-list", { status: 403 });
|
|
1144
1195
|
}
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
});
|
|
1196
|
+
const hopTarget = await resolveProxyTarget(next, resolveHost);
|
|
1197
|
+
if (hopTarget.status !== "ok") {
|
|
1198
|
+
return rejectFor(hopTarget.status, true);
|
|
1149
1199
|
}
|
|
1150
|
-
|
|
1151
|
-
let publicIp = true;
|
|
1152
|
-
try {
|
|
1153
|
-
const ips = await resolveHost(next.hostname);
|
|
1154
|
-
publicIp = !ips.some((ip) => isPrivateOrReservedAddress(ip));
|
|
1155
|
-
} catch {
|
|
1156
|
-
publicIp = true;
|
|
1157
|
-
}
|
|
1158
|
-
if (!publicIp) {
|
|
1159
|
-
return new Response("upstream redirect resolves to a private or reserved address", {
|
|
1160
|
-
status: 403
|
|
1161
|
-
});
|
|
1162
|
-
}
|
|
1163
|
-
}
|
|
1164
|
-
upstream = await fetch(next, { redirect: "manual" });
|
|
1200
|
+
upstream = await fetch(hopTarget.url, hopTarget.init);
|
|
1165
1201
|
}
|
|
1166
1202
|
} catch (err) {
|
|
1167
1203
|
return new Response(`upstream fetch failed: ${String(err)}`, { status: 502 });
|
|
@@ -1209,7 +1245,11 @@ function composeMiddleware(fns, handler) {
|
|
|
1209
1245
|
}
|
|
1210
1246
|
return handler(ctx);
|
|
1211
1247
|
};
|
|
1212
|
-
return
|
|
1248
|
+
return tracePhase(
|
|
1249
|
+
"x.middleware",
|
|
1250
|
+
{ route: new URL(ctx.request.url).pathname },
|
|
1251
|
+
() => dispatch(0)
|
|
1252
|
+
);
|
|
1213
1253
|
};
|
|
1214
1254
|
}
|
|
1215
1255
|
|
|
@@ -1279,29 +1319,6 @@ function createHealthCheckHandler(options = {}) {
|
|
|
1279
1319
|
};
|
|
1280
1320
|
}
|
|
1281
1321
|
|
|
1282
|
-
// src/observability/redact.ts
|
|
1283
|
-
var REDACTED = "[REDACTED]";
|
|
1284
|
-
var SENSITIVE_KEY_RE = /(password|passwd|token|secret|authorization|cookie|session|credential|api[_ -]?key|private[_ -]?key|access[_ -]?key|refresh[_ -]?token|bearer)/i;
|
|
1285
|
-
function isSensitiveKey(key) {
|
|
1286
|
-
return SENSITIVE_KEY_RE.test(key);
|
|
1287
|
-
}
|
|
1288
|
-
function redactString(input) {
|
|
1289
|
-
return input.replace(/\b(Bearer|Basic)\s+[A-Za-z0-9._~+/=:-]+/gi, "$1 " + REDACTED).replace(/\b(?:authorization|auth)\s*[:=]\s*[^\s,;]+/gi, "$1 " + REDACTED);
|
|
1290
|
-
}
|
|
1291
|
-
function redactValue(value, depth = 0) {
|
|
1292
|
-
if (typeof value === "string") return redactString(value);
|
|
1293
|
-
if (depth > 10) return value;
|
|
1294
|
-
if (Array.isArray(value)) return value.map((v) => redactValue(v, depth + 1));
|
|
1295
|
-
if (value !== null && typeof value === "object") {
|
|
1296
|
-
const out = {};
|
|
1297
|
-
for (const [key, val] of Object.entries(value)) {
|
|
1298
|
-
out[key] = isSensitiveKey(key) ? REDACTED : redactValue(val, depth + 1);
|
|
1299
|
-
}
|
|
1300
|
-
return out;
|
|
1301
|
-
}
|
|
1302
|
-
return value;
|
|
1303
|
-
}
|
|
1304
|
-
|
|
1305
1322
|
// src/observability/logger.ts
|
|
1306
1323
|
function write(level, message, fields) {
|
|
1307
1324
|
const entry = {
|
|
@@ -1327,7 +1344,7 @@ var logger = {
|
|
|
1327
1344
|
function withRequestLogging(handler) {
|
|
1328
1345
|
return async (req, server) => {
|
|
1329
1346
|
const start = performance.now();
|
|
1330
|
-
const requestId = req
|
|
1347
|
+
const requestId = traceRequestId(req);
|
|
1331
1348
|
const route = new URL(req.url).pathname;
|
|
1332
1349
|
try {
|
|
1333
1350
|
const res = await handler(req, server);
|
|
@@ -1725,7 +1742,9 @@ function createRedisRateLimitStoreFromClient(clientFactory) {
|
|
|
1725
1742
|
if (count === 1) {
|
|
1726
1743
|
await c.sendCommand("EXPIRE", redisKey, String(ttlSeconds));
|
|
1727
1744
|
}
|
|
1728
|
-
|
|
1745
|
+
const pttl = Number(await c.sendCommand("PTTL", redisKey));
|
|
1746
|
+
const remainingMs = pttl > 0 ? pttl : 0;
|
|
1747
|
+
return { count, resetAt: Date.now() + remainingMs };
|
|
1729
1748
|
}
|
|
1730
1749
|
};
|
|
1731
1750
|
}
|
|
@@ -1733,9 +1752,12 @@ function createRedisRateLimitStoreFromClient(clientFactory) {
|
|
|
1733
1752
|
// src/createApp.ts
|
|
1734
1753
|
function sortRoutes(handlers) {
|
|
1735
1754
|
return handlers.sort((a, b) => {
|
|
1736
|
-
const
|
|
1737
|
-
|
|
1738
|
-
|
|
1755
|
+
const category = routeMatchesForSort(a.entry) - routeMatchesForSort(b.entry);
|
|
1756
|
+
if (category !== 0) return category;
|
|
1757
|
+
for (const [as, bs] of zip(segmentSpecificity(a.entry), segmentSpecificity(b.entry))) {
|
|
1758
|
+
if (as !== bs) return as - bs;
|
|
1759
|
+
}
|
|
1760
|
+
return a.entry.routePath < b.entry.routePath ? -1 : 1;
|
|
1739
1761
|
});
|
|
1740
1762
|
}
|
|
1741
1763
|
function routeMatchesForSort(entry) {
|
|
@@ -1743,6 +1765,16 @@ function routeMatchesForSort(entry) {
|
|
|
1743
1765
|
const isCatchAll = entry.routePath.includes("*");
|
|
1744
1766
|
return isStatic ? 0 : isCatchAll ? 2 : 1;
|
|
1745
1767
|
}
|
|
1768
|
+
function segmentSpecificity(entry) {
|
|
1769
|
+
return entry.routePath.split("/").filter((seg) => seg.length > 0).map((seg) => seg === "*" ? 2 : seg.startsWith(":") ? 1 : 0);
|
|
1770
|
+
}
|
|
1771
|
+
function zip(as, bs) {
|
|
1772
|
+
const out = [];
|
|
1773
|
+
for (let i = 0; i < Math.max(as.length, bs.length); i++) {
|
|
1774
|
+
out.push([as[i], bs[i]]);
|
|
1775
|
+
}
|
|
1776
|
+
return out;
|
|
1777
|
+
}
|
|
1746
1778
|
function projectRootFromRoutesDir(routesDir) {
|
|
1747
1779
|
return join3(routesDir, "..", "..");
|
|
1748
1780
|
}
|
|
@@ -1900,7 +1932,11 @@ async function createApp(options) {
|
|
|
1900
1932
|
const method = req.method;
|
|
1901
1933
|
const handlerFn = module[method];
|
|
1902
1934
|
if (typeof handlerFn === "function") {
|
|
1903
|
-
const result = await
|
|
1935
|
+
const result = await tracePhase(
|
|
1936
|
+
"x.api",
|
|
1937
|
+
{ route: route.routePath, method },
|
|
1938
|
+
async () => handlerFn(req)
|
|
1939
|
+
);
|
|
1904
1940
|
if (result instanceof Response) return result;
|
|
1905
1941
|
if (result === void 0 || result === null) {
|
|
1906
1942
|
return new Response("OK", { status: 200 });
|
|
@@ -1944,7 +1980,11 @@ async function createApp(options) {
|
|
|
1944
1980
|
if (mode === "server") {
|
|
1945
1981
|
let loaderData = {};
|
|
1946
1982
|
if (loader) {
|
|
1947
|
-
const result2 = await
|
|
1983
|
+
const result2 = await tracePhase(
|
|
1984
|
+
"x.loader",
|
|
1985
|
+
{ route: route.routePath },
|
|
1986
|
+
() => loader(ctx)
|
|
1987
|
+
);
|
|
1948
1988
|
if (result2 instanceof Response) return result2;
|
|
1949
1989
|
loaderData = result2;
|
|
1950
1990
|
}
|
|
@@ -1955,23 +1995,27 @@ async function createApp(options) {
|
|
|
1955
1995
|
wrapWithLayouts(Component, ctx.params, loaderData, layoutModules)
|
|
1956
1996
|
);
|
|
1957
1997
|
const cspNonce = generateCspNonce();
|
|
1958
|
-
const stream = await
|
|
1959
|
-
|
|
1960
|
-
|
|
1961
|
-
|
|
1962
|
-
|
|
1963
|
-
|
|
1964
|
-
|
|
1965
|
-
|
|
1966
|
-
|
|
1967
|
-
|
|
1968
|
-
|
|
1969
|
-
|
|
1970
|
-
|
|
1971
|
-
|
|
1972
|
-
|
|
1973
|
-
|
|
1974
|
-
|
|
1998
|
+
const stream = await tracePhase(
|
|
1999
|
+
"x.ssr",
|
|
2000
|
+
{ route: route.routePath, streaming: true },
|
|
2001
|
+
() => renderStreamingPage(content, {
|
|
2002
|
+
stylesheet: stylesheetHref,
|
|
2003
|
+
liveReload: dev,
|
|
2004
|
+
cspNonce,
|
|
2005
|
+
...islandScripts === void 0 ? {
|
|
2006
|
+
// Single-render mode: islands register into `registry`
|
|
2007
|
+
// during the one render that produces the HTML, and the
|
|
2008
|
+
// script list is resolved from that same pass in the lazy
|
|
2009
|
+
// footer — no separate discovery render, so non-deterministic
|
|
2010
|
+
// components can't diverge between two passes.
|
|
2011
|
+
resolveIslandScripts: () => resolveIslandScripts(route.filePath, layoutFilePaths, registry.entries)
|
|
2012
|
+
} : { islandScripts },
|
|
2013
|
+
onRenderError: (error) => {
|
|
2014
|
+
reportException(error, { route: route.routePath, phase: "ssr" });
|
|
2015
|
+
metricsReporter?.incr("x_http_errors_total", 1, { phase: "ssr" });
|
|
2016
|
+
}
|
|
2017
|
+
})
|
|
2018
|
+
);
|
|
1975
2019
|
const res2 = new Response(stream, {
|
|
1976
2020
|
headers: { "Content-Type": "text/html; charset=utf-8" }
|
|
1977
2021
|
});
|
|
@@ -1996,7 +2040,11 @@ async function createApp(options) {
|
|
|
1996
2040
|
const computeHtml = async () => {
|
|
1997
2041
|
let loaderData = {};
|
|
1998
2042
|
if (loader) {
|
|
1999
|
-
const result2 = await
|
|
2043
|
+
const result2 = await tracePhase(
|
|
2044
|
+
"x.loader",
|
|
2045
|
+
{ route: route.routePath },
|
|
2046
|
+
() => loader(ctx)
|
|
2047
|
+
);
|
|
2000
2048
|
if (result2 instanceof Response) return result2;
|
|
2001
2049
|
loaderData = result2;
|
|
2002
2050
|
}
|
|
@@ -2007,14 +2055,18 @@ async function createApp(options) {
|
|
|
2007
2055
|
wrapWithLayouts(Component, ctx.params, loaderData, layoutModules)
|
|
2008
2056
|
);
|
|
2009
2057
|
const cspNonce = generateCspNonce();
|
|
2010
|
-
const html = await
|
|
2011
|
-
|
|
2012
|
-
|
|
2013
|
-
|
|
2014
|
-
|
|
2015
|
-
|
|
2016
|
-
|
|
2017
|
-
|
|
2058
|
+
const html = await tracePhase(
|
|
2059
|
+
"x.ssr",
|
|
2060
|
+
{ route: route.routePath, streaming: false },
|
|
2061
|
+
() => renderPageOnce(content, {
|
|
2062
|
+
stylesheet: stylesheetHref,
|
|
2063
|
+
liveReload: dev,
|
|
2064
|
+
cspNonce,
|
|
2065
|
+
...islandScripts === void 0 ? {
|
|
2066
|
+
resolveIslandScripts: () => resolveIslandScripts(route.filePath, layoutFilePaths, registry.entries)
|
|
2067
|
+
} : { islandScripts }
|
|
2068
|
+
})
|
|
2069
|
+
);
|
|
2018
2070
|
return { html, cspNonce };
|
|
2019
2071
|
};
|
|
2020
2072
|
if (revalidateSeconds > 0) {
|
|
@@ -2312,11 +2364,18 @@ async function createApp(options) {
|
|
|
2312
2364
|
async function handleHydrationMismatch(req) {
|
|
2313
2365
|
if (new URL(req.url).pathname !== "/__x/hydration-mismatch") return null;
|
|
2314
2366
|
if (req.method !== "POST") return new Response("Method not allowed", { status: 405 });
|
|
2315
|
-
const
|
|
2316
|
-
const
|
|
2317
|
-
const
|
|
2318
|
-
const
|
|
2319
|
-
|
|
2367
|
+
const selfOrigin = requestOrigin(req);
|
|
2368
|
+
const rawOrigin = req.headers.get("origin");
|
|
2369
|
+
const rawReferer = req.headers.get("referer");
|
|
2370
|
+
const origin = originFromHeader(rawOrigin);
|
|
2371
|
+
const referer = originFromHeader(rawReferer);
|
|
2372
|
+
if (origin !== null) {
|
|
2373
|
+
if (origin !== selfOrigin) return new Response("Forbidden", { status: 403 });
|
|
2374
|
+
} else if (rawOrigin !== null) {
|
|
2375
|
+
return new Response("Forbidden", { status: 403 });
|
|
2376
|
+
} else if (referer !== null) {
|
|
2377
|
+
if (referer !== selfOrigin) return new Response("Forbidden", { status: 403 });
|
|
2378
|
+
} else if (rawReferer !== null) {
|
|
2320
2379
|
return new Response("Forbidden", { status: 403 });
|
|
2321
2380
|
}
|
|
2322
2381
|
let body;
|
|
@@ -2479,7 +2538,8 @@ data: ${data}
|
|
|
2479
2538
|
};
|
|
2480
2539
|
const devFetchHardened = async (req, server) => withResponseHardening(await guardFetchErrors(withBodySizeLimit(devFetchInner), req, server));
|
|
2481
2540
|
const devFetchBase = loggingEnabled ? withRequestLogging(devFetchHardened) : devFetchHardened;
|
|
2482
|
-
const
|
|
2541
|
+
const devFetchTraced = withRequestTracing(devFetchBase);
|
|
2542
|
+
const devFetch = metricsReporter ? withRequestMetrics(metricsReporter, devFetchTraced) : devFetchTraced;
|
|
2483
2543
|
return {
|
|
2484
2544
|
routes: {},
|
|
2485
2545
|
development: true,
|
|
@@ -2537,7 +2597,8 @@ data: ${data}
|
|
|
2537
2597
|
};
|
|
2538
2598
|
const prodFetchHardened = async (req, server) => withResponseHardening(await guardFetchErrors(withBodySizeLimit(prodFetchInner), req, server));
|
|
2539
2599
|
const prodFetchBase = loggingEnabled ? withRequestLogging(prodFetchHardened) : prodFetchHardened;
|
|
2540
|
-
const
|
|
2600
|
+
const prodFetchTraced = withRequestTracing(prodFetchBase);
|
|
2601
|
+
const prodFetch = metricsReporter ? withRequestMetrics(metricsReporter, prodFetchTraced) : prodFetchTraced;
|
|
2541
2602
|
return {
|
|
2542
2603
|
routes: {},
|
|
2543
2604
|
development: false,
|
|
@@ -2797,6 +2858,7 @@ export {
|
|
|
2797
2858
|
Island,
|
|
2798
2859
|
IslandProvider,
|
|
2799
2860
|
Link,
|
|
2861
|
+
OTEL_ERROR_STATUS_CODE,
|
|
2800
2862
|
PUBLIC_ENV_PREFIX,
|
|
2801
2863
|
REDACTED,
|
|
2802
2864
|
RequestBodyTooLargeError,
|
|
@@ -2828,6 +2890,7 @@ export {
|
|
|
2828
2890
|
createRateLimiter,
|
|
2829
2891
|
createRedisRateLimitStore,
|
|
2830
2892
|
createSentryReporter,
|
|
2893
|
+
dbTraceAttributes,
|
|
2831
2894
|
defineConfig,
|
|
2832
2895
|
enforceRequestBodySize,
|
|
2833
2896
|
escapeHtml,
|
|
@@ -2840,6 +2903,7 @@ export {
|
|
|
2840
2903
|
getAuditSink,
|
|
2841
2904
|
getErrorReporter,
|
|
2842
2905
|
getServerFunctionHandler,
|
|
2906
|
+
getTracer,
|
|
2843
2907
|
installProcessCrashHandlers,
|
|
2844
2908
|
isSensitiveKey,
|
|
2845
2909
|
logger,
|
|
@@ -2858,6 +2922,7 @@ export {
|
|
|
2858
2922
|
reportException,
|
|
2859
2923
|
requestIdFromRequest,
|
|
2860
2924
|
resetServerFunctions,
|
|
2925
|
+
runWithRequestSpan,
|
|
2861
2926
|
scanApiDir,
|
|
2862
2927
|
scanContent,
|
|
2863
2928
|
scanLayouts,
|
|
@@ -2869,10 +2934,15 @@ export {
|
|
|
2869
2934
|
setAuditSink,
|
|
2870
2935
|
setErrorReporter,
|
|
2871
2936
|
setImageRemoteHosts,
|
|
2937
|
+
setTracer,
|
|
2938
|
+
tracePhase,
|
|
2939
|
+
tracePhaseSync,
|
|
2940
|
+
traceRequestId,
|
|
2872
2941
|
verifyCsrfToken,
|
|
2873
2942
|
verifyOrigin,
|
|
2874
2943
|
withCsrfCookie,
|
|
2875
2944
|
withRequestLogging,
|
|
2876
2945
|
withRequestMetrics,
|
|
2946
|
+
withRequestTracing,
|
|
2877
2947
|
writeManifest
|
|
2878
2948
|
};
|
package/package.json
CHANGED