@thexjs/core 1.0.0 → 1.2.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/dist/index.js CHANGED
@@ -1,201 +1,18 @@
1
- // src/router.ts
2
- import { readdirSync, statSync, writeFileSync } from "fs";
3
- import { join, relative, sep } from "path";
4
- var ROUTE_FILE = /\.(tsx|ts)$/;
5
- function scanPages(rootDir) {
6
- return scanRoutes(rootDir).map((r) => ({ ...r, isApi: false }));
7
- }
8
- function scanApiDir(rootDir) {
9
- return scanRoutes(rootDir).map((r) => ({
10
- ...r,
11
- routePath: r.routePath === "/" ? "/api" : `/api${r.routePath}`,
12
- isApi: true
13
- }));
14
- }
15
- function scanRoutes(rootDir) {
16
- try {
17
- statSync(rootDir);
18
- } catch {
19
- return [];
20
- }
21
- const entries = [];
22
- function walk(dir) {
23
- for (const name of readdirSync(dir)) {
24
- if (name.startsWith("_") || name.startsWith(".")) continue;
25
- const full = join(dir, name);
26
- const stat = statSync(full);
27
- if (stat.isDirectory()) {
28
- walk(full);
29
- continue;
30
- }
31
- if (!ROUTE_FILE.test(name)) continue;
32
- const rel = relative(rootDir, full).replace(ROUTE_FILE, "");
33
- entries.push(toRouteEntry(rel, full));
34
- }
35
- }
36
- walk(rootDir);
37
- return entries;
38
- }
39
- function toRouteEntry(relPath, filePath) {
40
- const segments = relPath.split(sep);
41
- const paramNames = [];
42
- const isApi = segments[0] === "api";
43
- const routeSegments = segments.map((segment) => {
44
- if (segment === "index") return "";
45
- if (segment.startsWith("[...") && segment.endsWith("]")) {
46
- const name = segment.slice(4, -1);
47
- paramNames.push(name);
48
- return "*";
49
- }
50
- if (segment.startsWith("[") && segment.endsWith("]")) {
51
- const name = segment.slice(1, -1);
52
- paramNames.push(name);
53
- return `:${name}`;
54
- }
55
- return segment;
56
- });
57
- const joined = routeSegments.filter((s) => s.length > 0).join("/");
58
- const routePath = joined.length === 0 ? "/" : `/${joined}`;
59
- return { filePath, routePath, paramNames, isApi };
60
- }
61
- function scanLayouts(rootDir) {
62
- const entries = [];
63
- function walk(dir) {
64
- for (const name of readdirSync(dir)) {
65
- if (name.startsWith(".")) continue;
66
- const full = join(dir, name);
67
- const stat = statSync(full);
68
- if (stat.isDirectory()) {
69
- walk(full);
70
- } else if (name === "_layout.tsx" || name === "_layout.ts") {
71
- entries.push({ filePath: full, dirPath: dir });
72
- }
73
- }
74
- }
75
- walk(rootDir);
76
- return entries;
77
- }
78
- function scanLayoutsDir(layoutsDir) {
79
- const entries = [];
80
- try {
81
- if (!statSync(layoutsDir).isDirectory()) return entries;
82
- } catch {
83
- return entries;
84
- }
85
- for (const name of readdirSync(layoutsDir)) {
86
- if (name.startsWith(".")) continue;
87
- const full = join(layoutsDir, name);
88
- const stat = statSync(full);
89
- if (stat.isFile() && (name.endsWith(".tsx") || name.endsWith(".ts"))) {
90
- entries.push({ filePath: full, dirPath: layoutsDir });
91
- }
92
- }
93
- return entries;
94
- }
95
- function findLayoutChain(routeFilePath, layouts, routesDir) {
96
- const routeDir = join(routeFilePath, "..");
97
- const chain = [];
98
- let current = routeDir;
99
- while (current.startsWith(routesDir)) {
100
- const layout = layouts.find((l) => l.dirPath === current);
101
- if (layout) chain.unshift(layout);
102
- const parent = join(current, "..");
103
- if (parent === current) break;
104
- current = parent;
105
- }
106
- return chain;
107
- }
108
- var NOT_FOUND_CANDIDATES = ["_404.tsx", "_404.ts"];
109
- function scanNotFound(rootDir) {
110
- for (const name of NOT_FOUND_CANDIDATES) {
111
- const full = join(rootDir, name);
112
- try {
113
- statSync(full);
114
- return { filePath: full };
115
- } catch {
116
- }
117
- }
118
- return null;
119
- }
120
- function scanMiddleware(rootDir) {
121
- const entries = [];
122
- function walk(dir) {
123
- for (const name of readdirSync(dir)) {
124
- if (name.startsWith(".")) continue;
125
- const full = join(dir, name);
126
- const stat = statSync(full);
127
- if (stat.isDirectory()) {
128
- walk(full);
129
- } else if (name === "_middleware.ts" || name === "_middleware.tsx") {
130
- entries.push({ filePath: full, dirPath: dir });
131
- }
132
- }
133
- }
134
- walk(rootDir);
135
- return entries;
136
- }
137
- function findMiddlewareChain(routeFilePath, middleware, routesDir) {
138
- const routeDir = join(routeFilePath, "..");
139
- const chain = [];
140
- let current = routeDir;
141
- while (current.startsWith(routesDir)) {
142
- const mw = middleware.find((m) => m.dirPath === current);
143
- if (mw) chain.unshift(mw);
144
- const parent = join(current, "..");
145
- if (parent === current) break;
146
- current = parent;
147
- }
148
- return chain;
149
- }
150
- function routePatternToRegex(routePath) {
151
- const regexStr = routePath.replace(/\//g, "\\/").replace(/:(\w+)/g, "([^/]+)").replace(/\*/g, "(.+)");
152
- return new RegExp(`^${regexStr}$`);
153
- }
154
- function extractParams(routePath, paramNames, url) {
155
- const regex = routePatternToRegex(routePath);
156
- const match = url.match(regex);
157
- if (!match) return null;
158
- const params = {};
159
- let idx = 1;
160
- for (const name of paramNames) {
161
- const value = match[idx];
162
- if (value !== void 0) {
163
- params[name] = value;
164
- }
165
- idx++;
166
- }
167
- return params;
168
- }
169
- function generateManifestSource(routes) {
170
- const routeEntries = routes.map((r) => {
171
- const paramsType = r.paramNames.length === 0 ? "Record<string, never>" : `{ ${r.paramNames.map((n) => `${n}: string`).join("; ")} }`;
172
- return ` "${r.routePath}": ${paramsType};`;
173
- });
174
- return `// Auto-generated by @thexjs/core -- do not edit
175
- export type RouteMap = {
176
- ${routeEntries.join("\n")}
177
- };
178
-
179
- export function href<T extends keyof RouteMap & string>(
180
- path: T,
181
- ...[params]: RouteMap[T] extends Record<string, never> ? [] : [RouteMap[T]]
182
- ): string {
183
- if (!params) return path;
184
- let result: string = path;
185
- for (const [key, value] of Object.entries(params)) {
186
- result = result.replace(new RegExp(\`:\${key}(?=/|$)\`), encodeURIComponent(String(value)));
187
- }
188
- result = result.replace(/\\*+$/, "");
189
- return result;
190
- }
191
- `;
192
- }
193
- function writeManifest(routes, routesDir) {
194
- const source = generateManifestSource(routes);
195
- const manifestPath = join(routesDir, "..", "x-routes.ts");
196
- writeFileSync(manifestPath, source, "utf-8");
197
- return manifestPath;
198
- }
1
+ import {
2
+ extractParams,
3
+ findLayoutChain,
4
+ findMiddlewareChain,
5
+ generateManifestSource,
6
+ routePatternToRegex,
7
+ scanApiDir,
8
+ scanLayouts,
9
+ scanLayoutsDir,
10
+ scanMiddleware,
11
+ scanNotFound,
12
+ scanPages,
13
+ scanRoutes,
14
+ writeManifest
15
+ } from "./chunk-Y3MLOFAG.js";
199
16
 
200
17
  // src/not-found.tsx
201
18
  import { jsx, jsxs } from "react/jsx-runtime";
@@ -538,20 +355,20 @@ ${liveReloadTag} </body>
538
355
 
539
356
  // src/createApp.ts
540
357
  import { existsSync, watch } from "fs";
541
- import { join as join5, resolve, sep as sep3 } from "path";
358
+ import { join as join4, resolve, sep as sep2 } from "path";
542
359
  import { createElement } from "react";
543
360
 
544
361
  // src/content.ts
545
- import { readFileSync, readdirSync as readdirSync2, statSync as statSync2 } from "fs";
546
- import { join as join2, relative as relative2, sep as sep2 } from "path";
362
+ import { readFileSync, readdirSync, statSync } from "fs";
363
+ import { join, relative, sep } from "path";
547
364
  var CONTENT_FILE = /\.(md|mdx)$/;
548
365
  function scanContent(rootDir) {
549
366
  const entries = [];
550
367
  function walk(dir) {
551
- for (const name of readdirSync2(dir)) {
368
+ for (const name of readdirSync(dir)) {
552
369
  if (name.startsWith(".")) continue;
553
- const full = join2(dir, name);
554
- const stat = statSync2(full);
370
+ const full = join(dir, name);
371
+ const stat = statSync(full);
555
372
  if (stat.isDirectory()) {
556
373
  walk(full);
557
374
  continue;
@@ -559,7 +376,7 @@ function scanContent(rootDir) {
559
376
  if (!CONTENT_FILE.test(name)) continue;
560
377
  const raw = readFileSync(full, "utf-8");
561
378
  const { frontmatter, body } = parseFrontmatter(raw);
562
- const rel = relative2(rootDir, full).replace(CONTENT_FILE, "");
379
+ const rel = relative(rootDir, full).replace(CONTENT_FILE, "");
563
380
  const slug = name.replace(CONTENT_FILE, "");
564
381
  const routePath = toContentRoutePath(rel);
565
382
  entries.push({ filePath: full, routePath, slug, frontmatter, body });
@@ -569,7 +386,7 @@ function scanContent(rootDir) {
569
386
  return entries;
570
387
  }
571
388
  function toContentRoutePath(relPath) {
572
- const segments = relPath.split(sep2).filter((s) => s !== "index");
389
+ const segments = relPath.split(sep).filter((s) => s !== "index");
573
390
  const joined = segments.join("/");
574
391
  return joined.length === 0 ? "/" : `/${joined}`;
575
392
  }
@@ -611,19 +428,49 @@ function parseYamlLines(raw) {
611
428
  function escapeHtml2(s) {
612
429
  return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
613
430
  }
431
+ function renderListBlock(block) {
432
+ const lines = block.split("\n");
433
+ const isUl = lines.every((l) => /^\s*[-*]\s+/.test(l));
434
+ const isOl = lines.every((l) => /^\s*\d+\.\s+/.test(l));
435
+ if (!isUl && !isOl) return block;
436
+ const tag = isUl ? "ul" : "ol";
437
+ const items = lines.map((l) => `<li>${l.replace(/^\s*[-*]\s+/, "").replace(/^\s*\d+\.\s+/, "")}</li>`).join("");
438
+ return `<${tag}>${items}</${tag}>`;
439
+ }
440
+ var ALLOWED_LINK_SCHEMES = /* @__PURE__ */ new Set(["http", "https", "mailto"]);
441
+ var LINK_SCHEME_RE = /^([a-z][a-z0-9+.-]*):/i;
442
+ function decodeLinkUrl(url) {
443
+ try {
444
+ return decodeURIComponent(url);
445
+ } catch {
446
+ return url;
447
+ }
448
+ }
449
+ function isSafeLinkUrl(url) {
450
+ const scheme = LINK_SCHEME_RE.exec(decodeLinkUrl(url.trim()))?.[1]?.toLowerCase();
451
+ return scheme === void 0 || ALLOWED_LINK_SCHEMES.has(scheme);
452
+ }
614
453
  function renderMarkdown(md) {
615
454
  const inlineCodes = [];
616
- let html = md.replace(/^### (.+)$/gm, "<h3>$1</h3>").replace(/^## (.+)$/gm, "<h2>$1</h2>").replace(/^# (.+)$/gm, "<h1>$1</h1>").replace(
617
- /`{3}(\w*)\n([\s\S]*?)`{3}/gm,
618
- (_m, _lang, code) => `<pre><code>${escapeHtml2(code.trim())}</code></pre>`
619
- ).replace(/`([^`]+)`/g, (_m, code) => {
455
+ const fences = [];
456
+ let html = escapeHtml2(md).replace(/`{3}(\w*)\n([\s\S]*?)`{3}/gm, (_m, _lang, code) => {
457
+ fences.push(`<pre><code>${code.trim()}</code></pre>`);
458
+ return `__X_FENCE_${fences.length - 1}__`;
459
+ });
460
+ html = html.replace(/^### (.+)$/gm, "<h3>$1</h3>").replace(/^## (.+)$/gm, "<h2>$1</h2>").replace(/^# (.+)$/gm, "<h1>$1</h1>").replace(/`([^`]+)`/g, (_m, code) => {
620
461
  inlineCodes.push(code);
621
462
  return `__X_CODE_${inlineCodes.length - 1}__`;
622
- }).replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>").replace(/\*([^*]+)\*/g, "<em>$1</em>").replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2">$1</a>').replace(/__X_CODE_(\d+)__/g, (_m, i) => `<code>${inlineCodes[Number.parseInt(i)]}</code>`);
463
+ }).replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>").replace(/\*([^*]+)\*/g, "<em>$1</em>").replace(
464
+ /\[([^\]]+)\]\(([^)]+)\)/g,
465
+ (_m, text, href) => isSafeLinkUrl(href) ? `<a href="${href}">${text}</a>` : text
466
+ ).replace(/__X_CODE_(\d+)__/g, (_m, i) => `<code>${inlineCodes[Number.parseInt(i)]}</code>`);
467
+ html = html.replace(/__X_FENCE_(\d+)__/g, (_m, i) => fences[Number.parseInt(i)] ?? "");
623
468
  const blocks = html.split(/\n\n+/);
624
469
  html = blocks.map((b) => {
625
470
  const t = b.trim();
626
471
  if (!t) return "";
472
+ const listBlock = renderListBlock(t);
473
+ if (listBlock !== t) return listBlock;
627
474
  if (t.startsWith("<h") || t.startsWith("<pre") || t.startsWith("<ul") || t.startsWith("<ol"))
628
475
  return t;
629
476
  return `<p>${t}</p>`;
@@ -835,8 +682,8 @@ function Island({
835
682
  }
836
683
 
837
684
  // src/island-bundle.ts
838
- import { mkdirSync, mkdtempSync, rmSync, writeFileSync as writeFileSync3 } from "fs";
839
- import { basename, join as join4 } from "path";
685
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync as writeFileSync2 } from "fs";
686
+ import { basename, join as join3 } from "path";
840
687
 
841
688
  // src/security/env-isolation.ts
842
689
  var PUBLIC_ENV_PREFIX = "THEXJS_PUBLIC_";
@@ -898,8 +745,8 @@ function assertNoEnvLeakage(code, file) {
898
745
  }
899
746
 
900
747
  // src/server-functions.ts
901
- import { writeFileSync as writeFileSync2 } from "fs";
902
- import { join as join3 } from "path";
748
+ import { writeFileSync } from "fs";
749
+ import { join as join2 } from "path";
903
750
 
904
751
  // src/observability/monitoring.ts
905
752
  var noopReporter = {
@@ -1199,12 +1046,12 @@ ${code}
1199
1046
  }
1200
1047
  async function buildIslandBundleInMemory(routeFilePath, layoutFilePaths, islandNames, actionModules, projectRoot) {
1201
1048
  const entryId = islandEntryId(routeFilePath);
1202
- const scratchRoot = join4(projectRoot, ".x", "islands-tmp");
1049
+ const scratchRoot = join3(projectRoot, ".x", "islands-tmp");
1203
1050
  mkdirSync(scratchRoot, { recursive: true });
1204
- const scratchDir = mkdtempSync(join4(scratchRoot, "x-islands-"));
1051
+ const scratchDir = mkdtempSync(join3(scratchRoot, "x-islands-"));
1205
1052
  try {
1206
- const entryPath = join4(scratchDir, `${entryId}.tsx`);
1207
- writeFileSync3(entryPath, generateHydrateEntry(routeFilePath, layoutFilePaths), "utf-8");
1053
+ const entryPath = join3(scratchDir, `${entryId}.tsx`);
1054
+ writeFileSync2(entryPath, generateHydrateEntry(routeFilePath, layoutFilePaths), "utf-8");
1208
1055
  const result = await Bun.build({
1209
1056
  entrypoints: [entryPath],
1210
1057
  target: "browser",
@@ -1338,6 +1185,163 @@ function withRequestLogging(handler) {
1338
1185
  };
1339
1186
  }
1340
1187
 
1188
+ // src/observability/metrics.ts
1189
+ var noopMetrics = {
1190
+ incr: () => {
1191
+ },
1192
+ observe: () => {
1193
+ }
1194
+ };
1195
+ var DEFAULT_HISTOGRAM_BUCKETS_MS = [5, 10, 25, 50, 100, 250, 500, 1e3, 2500, 5e3, 1e4];
1196
+ function seriesKey(name, labels) {
1197
+ if (!labels) return name;
1198
+ const sorted = Object.entries(labels).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => `${k}=${v}`);
1199
+ return `${name}\0${sorted.join("\0")}`;
1200
+ }
1201
+ function createInMemoryMetrics(options = {}) {
1202
+ const buckets = options.histogramBuckets ?? DEFAULT_HISTOGRAM_BUCKETS_MS;
1203
+ const counters = /* @__PURE__ */ new Map();
1204
+ const histograms = /* @__PURE__ */ new Map();
1205
+ function incr(name, delta = 1, labels) {
1206
+ const key = seriesKey(name, labels);
1207
+ let series = counters.get(key);
1208
+ if (!series) {
1209
+ series = { name, labels: labels ?? {}, value: 0 };
1210
+ counters.set(key, series);
1211
+ }
1212
+ series.value += delta;
1213
+ }
1214
+ function observe(name, value, labels) {
1215
+ const key = seriesKey(name, labels);
1216
+ let acc = histograms.get(key);
1217
+ if (!acc) {
1218
+ acc = { bucketCounts: new Array(buckets.length).fill(0), sum: 0, count: 0 };
1219
+ histograms.set(key, acc);
1220
+ }
1221
+ acc.sum += value;
1222
+ acc.count += 1;
1223
+ for (let i = 0; i < buckets.length; i += 1) {
1224
+ const bound = buckets[i];
1225
+ if (bound === void 0) break;
1226
+ if (value <= bound) {
1227
+ for (let j = i; j < buckets.length; j += 1) {
1228
+ acc.bucketCounts[j] = (acc.bucketCounts[j] ?? 0) + 1;
1229
+ }
1230
+ break;
1231
+ }
1232
+ }
1233
+ }
1234
+ function labelsFromKey(key) {
1235
+ const [name] = key.split("\0");
1236
+ const labelPart = name !== void 0 ? key.slice(name.length + 1) : "";
1237
+ const labels = {};
1238
+ if (labelPart) {
1239
+ for (const pair of labelPart.split("\0")) {
1240
+ const eq = pair.indexOf("=");
1241
+ if (eq > 0) labels[pair.slice(0, eq)] = pair.slice(eq + 1);
1242
+ }
1243
+ }
1244
+ return { name: name ?? key, labels };
1245
+ }
1246
+ function snapshot() {
1247
+ const sortedCounters = [...counters.entries()].sort(([a], [b]) => a < b ? -1 : 1).map(([key, series]) => {
1248
+ const { name, labels } = labelsFromKey(key);
1249
+ return { name, labels, value: series.value };
1250
+ });
1251
+ const sortedHistograms = [...histograms.entries()].sort(([a], [b]) => a < b ? -1 : 1).map(([key, acc]) => {
1252
+ const { name, labels } = labelsFromKey(key);
1253
+ return { name, labels, bucketCounts: acc.bucketCounts, sum: acc.sum, count: acc.count };
1254
+ });
1255
+ return { counters: sortedCounters, histograms: sortedHistograms };
1256
+ }
1257
+ function renderMetrics() {
1258
+ const snap = snapshot();
1259
+ const lines = [];
1260
+ for (const counter of snap.counters) {
1261
+ lines.push(`# TYPE ${counter.name} counter`);
1262
+ lines.push(`${counter.name}${formatLabels(counter.labels)} ${counter.value}`);
1263
+ }
1264
+ for (const h of snap.histograms) {
1265
+ const labelWithLe = (le) => {
1266
+ const labels = { ...h.labels, le };
1267
+ return formatLabels(labels);
1268
+ };
1269
+ lines.push(`# TYPE ${h.name} histogram`);
1270
+ for (let i = 0; i < buckets.length; i += 1) {
1271
+ lines.push(`${h.name}_bucket${labelWithLe(String(buckets[i]))} ${h.bucketCounts[i]}`);
1272
+ }
1273
+ lines.push(`${h.name}_bucket${labelWithLe("+Inf")} ${h.count}`);
1274
+ lines.push(`${h.name}_sum${formatLabels(h.labels)} ${h.sum}`);
1275
+ lines.push(`${h.name}_count${formatLabels(h.labels)} ${h.count}`);
1276
+ }
1277
+ return `${lines.join("\n")}
1278
+ `;
1279
+ }
1280
+ function handleMetrics(req) {
1281
+ if (new URL(req.url).pathname !== "/metrics") return null;
1282
+ return new Response(renderMetrics(), {
1283
+ headers: { "Content-Type": "text/plain; version=0.0.4; charset=utf-8" }
1284
+ });
1285
+ }
1286
+ return {
1287
+ incr,
1288
+ observe,
1289
+ snapshot,
1290
+ renderMetrics,
1291
+ handleMetrics,
1292
+ async flush() {
1293
+ }
1294
+ };
1295
+ }
1296
+ function createOtlpMetricsReporter(meter) {
1297
+ const counters = /* @__PURE__ */ new Map();
1298
+ const histograms = /* @__PURE__ */ new Map();
1299
+ return {
1300
+ incr(name, delta, labels) {
1301
+ let counter = counters.get(name);
1302
+ if (!counter) {
1303
+ counter = meter.createCounter(name, { description: `Counter ${name}` });
1304
+ counters.set(name, counter);
1305
+ }
1306
+ counter.add(delta ?? 1, labels);
1307
+ },
1308
+ observe(name, value, labels) {
1309
+ let histogram = histograms.get(name);
1310
+ if (!histogram) {
1311
+ histogram = meter.createHistogram(name, { description: `Histogram ${name}` });
1312
+ histograms.set(name, histogram);
1313
+ }
1314
+ histogram.record(value, labels);
1315
+ }
1316
+ };
1317
+ }
1318
+ function formatLabels(labels) {
1319
+ const entries = Object.entries(labels);
1320
+ if (entries.length === 0) return "";
1321
+ const escaped = entries.map(([k, v]) => `${k}="${escapeLabelValue(v)}"`).join(",");
1322
+ return `{${escaped}}`;
1323
+ }
1324
+ function escapeLabelValue(value) {
1325
+ return value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n");
1326
+ }
1327
+ function withRequestMetrics(reporter, handler) {
1328
+ return async (req, server) => {
1329
+ const start = performance.now();
1330
+ const method = req.method;
1331
+ try {
1332
+ const res = await handler(req, server);
1333
+ reporter.incr("x_http_requests_total", 1, { method, status: String(res.status) });
1334
+ reporter.observe("x_http_request_duration_ms", performance.now() - start, { method });
1335
+ return res;
1336
+ } catch (err) {
1337
+ reporter.incr("x_http_requests_total", 1, { method, status: "500" });
1338
+ reporter.incr("x_http_errors_total", 1, { method });
1339
+ reporter.observe("x_http_request_duration_ms", performance.now() - start, { method });
1340
+ throw err;
1341
+ }
1342
+ };
1343
+ }
1344
+
1341
1345
  // src/security/headers.ts
1342
1346
  var DEFAULT_CSP = "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; frame-ancestors 'none'";
1343
1347
  function buildSecurityHeaders(options = {}) {
@@ -1426,20 +1430,25 @@ async function rateLimitMiddleware(limiter, req, server) {
1426
1430
  }
1427
1431
  });
1428
1432
  }
1429
- function createRedisRateLimitStore(options = {}) {
1430
- let client = null;
1431
- let connecting = null;
1432
- async function connect() {
1433
+ function createBunRedisClient(options) {
1434
+ return async () => {
1433
1435
  const require2 = import.meta.require;
1434
1436
  const mod = require2("bun:redis");
1435
1437
  const instance = options.url ? new mod.RedisClient({ url: options.url }) : new mod.RedisClient();
1436
1438
  await instance.connect();
1437
1439
  return instance;
1438
- }
1440
+ };
1441
+ }
1442
+ function createRedisRateLimitStore(options = {}) {
1443
+ return createRedisRateLimitStoreFromClient(createBunRedisClient(options));
1444
+ }
1445
+ function createRedisRateLimitStoreFromClient(clientFactory) {
1446
+ let client = null;
1447
+ let connecting = null;
1439
1448
  function getClient() {
1440
1449
  if (client) return Promise.resolve(client);
1441
1450
  if (!connecting) {
1442
- connecting = connect().then(
1451
+ connecting = clientFactory().then(
1443
1452
  (c) => {
1444
1453
  client = c;
1445
1454
  return c;
@@ -1468,7 +1477,7 @@ function createRedisRateLimitStore(options = {}) {
1468
1477
 
1469
1478
  // src/createApp.ts
1470
1479
  function projectRootFromRoutesDir(routesDir) {
1471
- return join5(routesDir, "..", "..");
1480
+ return join4(routesDir, "..", "..");
1472
1481
  }
1473
1482
  function resolvePublicAsset(publicDir, pathname) {
1474
1483
  let decoded;
@@ -1477,9 +1486,9 @@ function resolvePublicAsset(publicDir, pathname) {
1477
1486
  } catch {
1478
1487
  return null;
1479
1488
  }
1480
- const target = resolve(join5(publicDir, decoded));
1489
+ const target = resolve(join4(publicDir, decoded));
1481
1490
  const root = resolve(publicDir);
1482
- if (target !== root && !target.startsWith(root + sep3)) return null;
1491
+ if (target !== root && !target.startsWith(root + sep2)) return null;
1483
1492
  return target;
1484
1493
  }
1485
1494
  async function serveStaticAsset(publicDir, req) {
@@ -1529,7 +1538,7 @@ async function createApp(options) {
1529
1538
  const dev = options.development ?? false;
1530
1539
  const primaryDir = options.pagesDir || options.routesDir || "src/pages";
1531
1540
  const projectRoot = projectRootFromRoutesDir(primaryDir);
1532
- const resolvedActionsDir = options.actionsDir ?? (existsSync(join5(projectRoot, "src", "actions")) ? join5(projectRoot, "src", "actions") : void 0);
1541
+ const resolvedActionsDir = options.actionsDir ?? (existsSync(join4(projectRoot, "src", "actions")) ? join4(projectRoot, "src", "actions") : void 0);
1533
1542
  let handlers = [];
1534
1543
  let contentHandlers = [];
1535
1544
  let publicDir = null;
@@ -1575,6 +1584,7 @@ async function createApp(options) {
1575
1584
  setErrorReporter(options.observability.errorReporter);
1576
1585
  }
1577
1586
  const healthHandler = createHealthCheckHandler(options.observability?.health ?? {});
1587
+ const metricsReporter = options.observability?.metrics;
1578
1588
  const rateLimiter = options.security?.rateLimit === false ? null : createRateLimiter(options.security?.rateLimit ?? {});
1579
1589
  const securityHeadersOptions = options.security?.headers;
1580
1590
  const loggingEnabled = options.observability?.logging ?? true;
@@ -1609,6 +1619,7 @@ async function createApp(options) {
1609
1619
  return new Response(`Method ${method} not allowed`, { status: 405 });
1610
1620
  } catch (err) {
1611
1621
  reportException(err, { route: route.routePath, phase: "api" });
1622
+ metricsReporter?.incr("x_http_errors_total", 1, { phase: "api" });
1612
1623
  console.error("[x] API handler error:", err);
1613
1624
  if (dev) {
1614
1625
  return new Response(renderErrorOverlay(err), {
@@ -1709,6 +1720,7 @@ async function createApp(options) {
1709
1720
  return baseHandler({ params, request: req });
1710
1721
  } catch (err) {
1711
1722
  reportException(err, { route: route.routePath, phase: "ssr" });
1723
+ metricsReporter?.incr("x_http_errors_total", 1, { phase: "ssr" });
1712
1724
  console.error("[x] route handler error:", err);
1713
1725
  if (dev) {
1714
1726
  return new Response(renderErrorOverlay(err), {
@@ -1723,9 +1735,9 @@ async function createApp(options) {
1723
1735
  async function buildHandlers() {
1724
1736
  if (options.preloaded) {
1725
1737
  const preloaded = options.preloaded;
1726
- const candidatePublicDir2 = join5(projectRoot, "public");
1738
+ const candidatePublicDir2 = join4(projectRoot, "public");
1727
1739
  publicDir = existsSync(candidatePublicDir2) ? candidatePublicDir2 : null;
1728
- stylesheetHref = options.stylesheetHref ?? (publicDir && existsSync(join5(publicDir, "styles.css")) ? "/styles.css" : void 0);
1740
+ stylesheetHref = options.stylesheetHref ?? (publicDir && existsSync(join4(publicDir, "styles.css")) ? "/styles.css" : void 0);
1729
1741
  if (preloaded.notFoundComponent) notFoundComponent = preloaded.notFoundComponent;
1730
1742
  if (preloaded.notFoundLayout) notFoundLayout = preloaded.notFoundLayout;
1731
1743
  const loaded2 = [];
@@ -1779,7 +1791,7 @@ async function createApp(options) {
1779
1791
  if (apiDir && existsSync(apiDir)) {
1780
1792
  apiFound.push(...scanApiDir(apiDir));
1781
1793
  }
1782
- const legacyApiDir = join5(pagesDir, "api");
1794
+ const legacyApiDir = join4(pagesDir, "api");
1783
1795
  if (existsSync(legacyApiDir) && legacyApiDir !== apiDir) {
1784
1796
  apiFound.push(...scanApiDir(legacyApiDir));
1785
1797
  }
@@ -1814,9 +1826,9 @@ async function createApp(options) {
1814
1826
  }
1815
1827
  }
1816
1828
  }
1817
- const candidatePublicDir = join5(projectRoot, "public");
1829
+ const candidatePublicDir = join4(projectRoot, "public");
1818
1830
  publicDir = existsSync(candidatePublicDir) ? candidatePublicDir : null;
1819
- stylesheetHref = options.stylesheetHref ?? (publicDir && existsSync(join5(publicDir, "styles.css")) ? "/styles.css" : void 0);
1831
+ stylesheetHref = options.stylesheetHref ?? (publicDir && existsSync(join4(publicDir, "styles.css")) ? "/styles.css" : void 0);
1820
1832
  const notFoundEntry = scanNotFound(pagesDir);
1821
1833
  if (notFoundEntry) {
1822
1834
  const mod = await importDev(notFoundEntry.filePath, dev);
@@ -1972,7 +1984,7 @@ async function createApp(options) {
1972
1984
  let rebuildTimeout = null;
1973
1985
  const sseClients = /* @__PURE__ */ new Set();
1974
1986
  try {
1975
- const srcDir = join5(primaryDir, "..", "..", "src");
1987
+ const srcDir = join4(primaryDir, "..", "..", "src");
1976
1988
  const watchDirs = [
1977
1989
  ...new Set(
1978
1990
  [primaryDir, options.apiDir, options.layoutsDir, resolvedActionsDir, srcDir].filter(
@@ -1997,9 +2009,16 @@ async function createApp(options) {
1997
2009
  const url = new URL(req.url).pathname;
1998
2010
  const healthResult = await healthHandler(req);
1999
2011
  if (healthResult !== null) return healthResult;
2012
+ if (metricsReporter?.handleMetrics) {
2013
+ const metricsResult = await metricsReporter.handleMetrics(req);
2014
+ if (metricsResult !== null) return metricsResult;
2015
+ }
2000
2016
  if (rateLimiter) {
2001
2017
  const limited = await rateLimitMiddleware(rateLimiter, req, server);
2002
- if (limited !== null) return limited;
2018
+ if (limited !== null) {
2019
+ metricsReporter?.incr("x_rate_limit_rejections_total", 1, { method: req.method });
2020
+ return limited;
2021
+ }
2003
2022
  }
2004
2023
  if (url === "/__x/reload") {
2005
2024
  const body = new ReadableStream({
@@ -2060,7 +2079,8 @@ data: ${data}
2060
2079
  return renderNotFound(req);
2061
2080
  };
2062
2081
  const devFetchHardened = async (req, server) => withResponseHardening(await devFetchInner(req, server));
2063
- const devFetch = loggingEnabled ? withRequestLogging(devFetchHardened) : devFetchHardened;
2082
+ const devFetchBase = loggingEnabled ? withRequestLogging(devFetchHardened) : devFetchHardened;
2083
+ const devFetch = metricsReporter ? withRequestMetrics(metricsReporter, devFetchBase) : devFetchBase;
2064
2084
  return {
2065
2085
  routes: {},
2066
2086
  development: true,
@@ -2072,9 +2092,16 @@ data: ${data}
2072
2092
  const url = new URL(req.url).pathname;
2073
2093
  const healthResult = await healthHandler(req);
2074
2094
  if (healthResult !== null) return healthResult;
2095
+ if (metricsReporter?.handleMetrics) {
2096
+ const metricsResult = await metricsReporter.handleMetrics(req);
2097
+ if (metricsResult !== null) return metricsResult;
2098
+ }
2075
2099
  if (rateLimiter) {
2076
2100
  const limited = await rateLimitMiddleware(rateLimiter, req, server);
2077
- if (limited !== null) return limited;
2101
+ if (limited !== null) {
2102
+ metricsReporter?.incr("x_rate_limit_rejections_total", 1, { method: req.method });
2103
+ return limited;
2104
+ }
2078
2105
  }
2079
2106
  const revalidationResult = await handleRevalidation(req);
2080
2107
  if (revalidationResult !== null) return revalidationResult;
@@ -2100,7 +2127,8 @@ data: ${data}
2100
2127
  return renderNotFound(req);
2101
2128
  };
2102
2129
  const prodFetchHardened = async (req, server) => withResponseHardening(await prodFetchInner(req, server));
2103
- const prodFetch = loggingEnabled ? withRequestLogging(prodFetchHardened) : prodFetchHardened;
2130
+ const prodFetchBase = loggingEnabled ? withRequestLogging(prodFetchHardened) : prodFetchHardened;
2131
+ const prodFetch = metricsReporter ? withRequestMetrics(metricsReporter, prodFetchBase) : prodFetchBase;
2104
2132
  return {
2105
2133
  routes: {},
2106
2134
  development: false,
@@ -2110,14 +2138,14 @@ data: ${data}
2110
2138
  }
2111
2139
 
2112
2140
  // src/build.ts
2113
- import { cpSync, existsSync as existsSync2, mkdirSync as mkdirSync2, writeFileSync as writeFileSync4 } from "fs";
2114
- import { join as join6, relative as relative3 } from "path";
2141
+ import { cpSync, existsSync as existsSync2, mkdirSync as mkdirSync2, writeFileSync as writeFileSync3 } from "fs";
2142
+ import { join as join5, relative as relative2 } from "path";
2115
2143
  import { createElement as createElement2 } from "react";
2116
2144
  async function build(options) {
2117
- const outDir = options.outDir ?? join6(process.cwd(), ".x");
2118
- const clientDir = join6(outDir, "client");
2119
- const serverDir = join6(outDir, "server");
2120
- const islandsDir = join6(clientDir, "_islands");
2145
+ const outDir = options.outDir ?? join5(process.cwd(), ".x");
2146
+ const clientDir = join5(outDir, "client");
2147
+ const serverDir = join5(outDir, "server");
2148
+ const islandsDir = join5(clientDir, "_islands");
2121
2149
  mkdirSync2(clientDir, { recursive: true });
2122
2150
  mkdirSync2(serverDir, { recursive: true });
2123
2151
  mkdirSync2(islandsDir, { recursive: true });
@@ -2125,13 +2153,13 @@ async function build(options) {
2125
2153
  const apiDir = options.apiDir;
2126
2154
  const actionsDir = options.actionsDir;
2127
2155
  const layoutsDir = options.layoutsDir ?? pagesDir;
2128
- const projectRoot = pagesDir ? join6(pagesDir, "..", "..") : process.cwd();
2129
- const publicDir = join6(projectRoot, "public");
2156
+ const projectRoot = pagesDir ? join5(pagesDir, "..", "..") : process.cwd();
2157
+ const publicDir = join5(projectRoot, "public");
2130
2158
  const hasPublicDir = existsSync2(publicDir);
2131
- const stylesheetHref = hasPublicDir && existsSync2(join6(publicDir, "styles.css")) ? "/styles.css" : void 0;
2159
+ const stylesheetHref = hasPublicDir && existsSync2(join5(publicDir, "styles.css")) ? "/styles.css" : void 0;
2132
2160
  if (hasPublicDir) {
2133
2161
  cpSync(publicDir, clientDir, { recursive: true });
2134
- console.log(`[x] build: copied public/ -> ${relative3(process.cwd(), clientDir)}`);
2162
+ console.log(`[x] build: copied public/ -> ${relative2(process.cwd(), clientDir)}`);
2135
2163
  }
2136
2164
  let routeEntries = [];
2137
2165
  if (pagesDir && existsSync2(pagesDir)) {
@@ -2140,7 +2168,7 @@ async function build(options) {
2140
2168
  if (apiDir && existsSync2(apiDir)) {
2141
2169
  routeEntries.push(...scanApiDir(apiDir));
2142
2170
  }
2143
- const legacyApiDir = pagesDir ? join6(pagesDir, "api") : "";
2171
+ const legacyApiDir = pagesDir ? join5(pagesDir, "api") : "";
2144
2172
  if (legacyApiDir && existsSync2(legacyApiDir) && legacyApiDir !== apiDir) {
2145
2173
  routeEntries.push(...scanApiDir(legacyApiDir));
2146
2174
  }
@@ -2226,8 +2254,8 @@ async function build(options) {
2226
2254
  const content = createElement2(IslandProvider, { registry }, pageContent);
2227
2255
  const html = renderStaticPage(content, { stylesheet: stylesheetHref });
2228
2256
  const outPath = page.entry.routePath === "/" ? "/index.html" : `${page.entry.routePath}/index.html`;
2229
- const fullPath = join6(clientDir, outPath);
2230
- mkdirSync2(join6(fullPath, ".."), { recursive: true });
2257
+ const fullPath = join5(clientDir, outPath);
2258
+ mkdirSync2(join5(fullPath, ".."), { recursive: true });
2231
2259
  if (writtenPaths.has(outPath)) {
2232
2260
  console.warn(` [warn] collision: ${page.entry.routePath} overwrites existing output`);
2233
2261
  }
@@ -2247,7 +2275,7 @@ async function build(options) {
2247
2275
  );
2248
2276
  }
2249
2277
  const finalHtml = renderStaticPage(content, { islandScripts, stylesheet: stylesheetHref });
2250
- writeFileSync4(fullPath, finalHtml, "utf-8");
2278
+ writeFileSync3(fullPath, finalHtml, "utf-8");
2251
2279
  console.log(` [static] ${page.entry.routePath} -> ${outPath}`);
2252
2280
  }
2253
2281
  for (const content of contentEntries) {
@@ -2263,13 +2291,13 @@ async function build(options) {
2263
2291
  stylesheet: stylesheetHref
2264
2292
  });
2265
2293
  const outPath = content.routePath === "/" ? "/index.html" : `${content.routePath}/index.html`;
2266
- const fullPath = join6(clientDir, outPath);
2267
- mkdirSync2(join6(fullPath, ".."), { recursive: true });
2294
+ const fullPath = join5(clientDir, outPath);
2295
+ mkdirSync2(join5(fullPath, ".."), { recursive: true });
2268
2296
  if (writtenPaths.has(outPath)) {
2269
2297
  console.warn(` [warn] collision: content ${content.routePath} overwrites existing output`);
2270
2298
  }
2271
2299
  writtenPaths.add(outPath);
2272
- writeFileSync4(fullPath, html, "utf-8");
2300
+ writeFileSync3(fullPath, html, "utf-8");
2273
2301
  console.log(` [content] ${content.routePath} -> ${outPath}`);
2274
2302
  }
2275
2303
  if (pagesDir || options.routesDir || options.contentDir) {
@@ -2286,8 +2314,8 @@ async function build(options) {
2286
2314
  configImportPath,
2287
2315
  stylesheetHref
2288
2316
  );
2289
- const serverEntryPath = join6(serverDir, "index.ts");
2290
- writeFileSync4(serverEntryPath, serverEntry, "utf-8");
2317
+ const serverEntryPath = join5(serverDir, "index.ts");
2318
+ writeFileSync3(serverEntryPath, serverEntry, "utf-8");
2291
2319
  console.log(
2292
2320
  ` [server] ${serverPages.length} page routes, ${apiRoutes.length} api routes -> server/index.ts`
2293
2321
  );
@@ -2296,12 +2324,12 @@ async function build(options) {
2296
2324
  }
2297
2325
  async function bundleRouteIslands(routeFilePath, layoutFilePaths, islandNames, islandsDir, actionModules) {
2298
2326
  const entryId = islandEntryId(routeFilePath);
2299
- const outdir = join6(islandsDir, entryId);
2327
+ const outdir = join5(islandsDir, entryId);
2300
2328
  mkdirSync2(outdir, { recursive: true });
2301
- const bundlePath = join6(outdir, `${entryId}.js`);
2329
+ const bundlePath = join5(outdir, `${entryId}.js`);
2302
2330
  const hydrateEntry = generateHydrateEntry(routeFilePath, layoutFilePaths);
2303
- const entryPath = join6(outdir, `${entryId}.tsx`);
2304
- writeFileSync4(entryPath, hydrateEntry, "utf-8");
2331
+ const entryPath = join5(outdir, `${entryId}.tsx`);
2332
+ writeFileSync3(entryPath, hydrateEntry, "utf-8");
2305
2333
  try {
2306
2334
  const result = await Bun.build({
2307
2335
  entrypoints: [entryPath],
@@ -2314,7 +2342,7 @@ async function bundleRouteIslands(routeFilePath, layoutFilePaths, islandNames, i
2314
2342
  if (!built) throw new Error("bun build produced no output");
2315
2343
  const code = await built.text();
2316
2344
  assertNoEnvLeakage(code, bundlePath);
2317
- writeFileSync4(bundlePath, wrapIslandBundle(code), "utf-8");
2345
+ writeFileSync3(bundlePath, wrapIslandBundle(code), "utf-8");
2318
2346
  return [`/_islands/${entryId}/${entryId}.js`];
2319
2347
  }
2320
2348
  for (const log of result.logs) {
@@ -2323,7 +2351,7 @@ async function bundleRouteIslands(routeFilePath, layoutFilePaths, islandNames, i
2323
2351
  } catch (err) {
2324
2352
  console.warn(` [islands] build failed for ${routeFilePath}:`, err);
2325
2353
  }
2326
- writeFileSync4(bundlePath, wrapIslandBundle(generateFallbackHydration(islandNames)), "utf-8");
2354
+ writeFileSync3(bundlePath, wrapIslandBundle(generateFallbackHydration(islandNames)), "utf-8");
2327
2355
  return [`/_islands/${entryId}/${entryId}.js`];
2328
2356
  }
2329
2357
  function renderPageWithLayout(Component, params, layoutModules) {
@@ -2406,7 +2434,7 @@ function buildServerEntry(opts, configImportPath, stylesheetHref) {
2406
2434
  return lines.join("\n");
2407
2435
  }
2408
2436
  function relativeImportPath(fromDir, toFile) {
2409
- const rel = relative3(fromDir, toFile).replace(/\\/g, "/").replace(/\.(ts|js|mjs)$/, "");
2437
+ const rel = relative2(fromDir, toFile).replace(/\\/g, "/").replace(/\.(ts|js|mjs)$/, "");
2410
2438
  return rel.startsWith(".") ? rel : `./${rel}`;
2411
2439
  }
2412
2440
 
@@ -2426,6 +2454,7 @@ function Link({ href, children, clientNav = true, prefetch = true, ...rest }) {
2426
2454
  }
2427
2455
  export {
2428
2456
  CLIENT_NAV_SCRIPT,
2457
+ DEFAULT_HISTOGRAM_BUCKETS_MS,
2429
2458
  DefaultNotFound,
2430
2459
  EnvLeakageError,
2431
2460
  Island,
@@ -2442,7 +2471,9 @@ export {
2442
2471
  createApp,
2443
2472
  createHealthCheckHandler,
2444
2473
  createImageProxyHandler,
2474
+ createInMemoryMetrics,
2445
2475
  createOtelReporter,
2476
+ createOtlpMetricsReporter,
2446
2477
  createRateLimiter,
2447
2478
  createRedisRateLimitStore,
2448
2479
  createSentryReporter,
@@ -2457,6 +2488,7 @@ export {
2457
2488
  getErrorReporter,
2458
2489
  getServerFunctionHandler,
2459
2490
  logger,
2491
+ noopMetrics,
2460
2492
  noopReporter,
2461
2493
  rateLimitMiddleware,
2462
2494
  registerServerFunctions,
@@ -2480,5 +2512,6 @@ export {
2480
2512
  verifyOrigin,
2481
2513
  withCsrfCookie,
2482
2514
  withRequestLogging,
2515
+ withRequestMetrics,
2483
2516
  writeManifest
2484
2517
  };