@thexjs/core 1.1.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
  }
@@ -865,8 +682,8 @@ function Island({
865
682
  }
866
683
 
867
684
  // src/island-bundle.ts
868
- import { mkdirSync, mkdtempSync, rmSync, writeFileSync as writeFileSync3 } from "fs";
869
- 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";
870
687
 
871
688
  // src/security/env-isolation.ts
872
689
  var PUBLIC_ENV_PREFIX = "THEXJS_PUBLIC_";
@@ -928,8 +745,8 @@ function assertNoEnvLeakage(code, file) {
928
745
  }
929
746
 
930
747
  // src/server-functions.ts
931
- import { writeFileSync as writeFileSync2 } from "fs";
932
- import { join as join3 } from "path";
748
+ import { writeFileSync } from "fs";
749
+ import { join as join2 } from "path";
933
750
 
934
751
  // src/observability/monitoring.ts
935
752
  var noopReporter = {
@@ -1229,12 +1046,12 @@ ${code}
1229
1046
  }
1230
1047
  async function buildIslandBundleInMemory(routeFilePath, layoutFilePaths, islandNames, actionModules, projectRoot) {
1231
1048
  const entryId = islandEntryId(routeFilePath);
1232
- const scratchRoot = join4(projectRoot, ".x", "islands-tmp");
1049
+ const scratchRoot = join3(projectRoot, ".x", "islands-tmp");
1233
1050
  mkdirSync(scratchRoot, { recursive: true });
1234
- const scratchDir = mkdtempSync(join4(scratchRoot, "x-islands-"));
1051
+ const scratchDir = mkdtempSync(join3(scratchRoot, "x-islands-"));
1235
1052
  try {
1236
- const entryPath = join4(scratchDir, `${entryId}.tsx`);
1237
- writeFileSync3(entryPath, generateHydrateEntry(routeFilePath, layoutFilePaths), "utf-8");
1053
+ const entryPath = join3(scratchDir, `${entryId}.tsx`);
1054
+ writeFileSync2(entryPath, generateHydrateEntry(routeFilePath, layoutFilePaths), "utf-8");
1238
1055
  const result = await Bun.build({
1239
1056
  entrypoints: [entryPath],
1240
1057
  target: "browser",
@@ -1368,6 +1185,163 @@ function withRequestLogging(handler) {
1368
1185
  };
1369
1186
  }
1370
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
+
1371
1345
  // src/security/headers.ts
1372
1346
  var DEFAULT_CSP = "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; frame-ancestors 'none'";
1373
1347
  function buildSecurityHeaders(options = {}) {
@@ -1503,7 +1477,7 @@ function createRedisRateLimitStoreFromClient(clientFactory) {
1503
1477
 
1504
1478
  // src/createApp.ts
1505
1479
  function projectRootFromRoutesDir(routesDir) {
1506
- return join5(routesDir, "..", "..");
1480
+ return join4(routesDir, "..", "..");
1507
1481
  }
1508
1482
  function resolvePublicAsset(publicDir, pathname) {
1509
1483
  let decoded;
@@ -1512,9 +1486,9 @@ function resolvePublicAsset(publicDir, pathname) {
1512
1486
  } catch {
1513
1487
  return null;
1514
1488
  }
1515
- const target = resolve(join5(publicDir, decoded));
1489
+ const target = resolve(join4(publicDir, decoded));
1516
1490
  const root = resolve(publicDir);
1517
- if (target !== root && !target.startsWith(root + sep3)) return null;
1491
+ if (target !== root && !target.startsWith(root + sep2)) return null;
1518
1492
  return target;
1519
1493
  }
1520
1494
  async function serveStaticAsset(publicDir, req) {
@@ -1564,7 +1538,7 @@ async function createApp(options) {
1564
1538
  const dev = options.development ?? false;
1565
1539
  const primaryDir = options.pagesDir || options.routesDir || "src/pages";
1566
1540
  const projectRoot = projectRootFromRoutesDir(primaryDir);
1567
- 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);
1568
1542
  let handlers = [];
1569
1543
  let contentHandlers = [];
1570
1544
  let publicDir = null;
@@ -1610,6 +1584,7 @@ async function createApp(options) {
1610
1584
  setErrorReporter(options.observability.errorReporter);
1611
1585
  }
1612
1586
  const healthHandler = createHealthCheckHandler(options.observability?.health ?? {});
1587
+ const metricsReporter = options.observability?.metrics;
1613
1588
  const rateLimiter = options.security?.rateLimit === false ? null : createRateLimiter(options.security?.rateLimit ?? {});
1614
1589
  const securityHeadersOptions = options.security?.headers;
1615
1590
  const loggingEnabled = options.observability?.logging ?? true;
@@ -1644,6 +1619,7 @@ async function createApp(options) {
1644
1619
  return new Response(`Method ${method} not allowed`, { status: 405 });
1645
1620
  } catch (err) {
1646
1621
  reportException(err, { route: route.routePath, phase: "api" });
1622
+ metricsReporter?.incr("x_http_errors_total", 1, { phase: "api" });
1647
1623
  console.error("[x] API handler error:", err);
1648
1624
  if (dev) {
1649
1625
  return new Response(renderErrorOverlay(err), {
@@ -1744,6 +1720,7 @@ async function createApp(options) {
1744
1720
  return baseHandler({ params, request: req });
1745
1721
  } catch (err) {
1746
1722
  reportException(err, { route: route.routePath, phase: "ssr" });
1723
+ metricsReporter?.incr("x_http_errors_total", 1, { phase: "ssr" });
1747
1724
  console.error("[x] route handler error:", err);
1748
1725
  if (dev) {
1749
1726
  return new Response(renderErrorOverlay(err), {
@@ -1758,9 +1735,9 @@ async function createApp(options) {
1758
1735
  async function buildHandlers() {
1759
1736
  if (options.preloaded) {
1760
1737
  const preloaded = options.preloaded;
1761
- const candidatePublicDir2 = join5(projectRoot, "public");
1738
+ const candidatePublicDir2 = join4(projectRoot, "public");
1762
1739
  publicDir = existsSync(candidatePublicDir2) ? candidatePublicDir2 : null;
1763
- 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);
1764
1741
  if (preloaded.notFoundComponent) notFoundComponent = preloaded.notFoundComponent;
1765
1742
  if (preloaded.notFoundLayout) notFoundLayout = preloaded.notFoundLayout;
1766
1743
  const loaded2 = [];
@@ -1814,7 +1791,7 @@ async function createApp(options) {
1814
1791
  if (apiDir && existsSync(apiDir)) {
1815
1792
  apiFound.push(...scanApiDir(apiDir));
1816
1793
  }
1817
- const legacyApiDir = join5(pagesDir, "api");
1794
+ const legacyApiDir = join4(pagesDir, "api");
1818
1795
  if (existsSync(legacyApiDir) && legacyApiDir !== apiDir) {
1819
1796
  apiFound.push(...scanApiDir(legacyApiDir));
1820
1797
  }
@@ -1849,9 +1826,9 @@ async function createApp(options) {
1849
1826
  }
1850
1827
  }
1851
1828
  }
1852
- const candidatePublicDir = join5(projectRoot, "public");
1829
+ const candidatePublicDir = join4(projectRoot, "public");
1853
1830
  publicDir = existsSync(candidatePublicDir) ? candidatePublicDir : null;
1854
- 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);
1855
1832
  const notFoundEntry = scanNotFound(pagesDir);
1856
1833
  if (notFoundEntry) {
1857
1834
  const mod = await importDev(notFoundEntry.filePath, dev);
@@ -2007,7 +1984,7 @@ async function createApp(options) {
2007
1984
  let rebuildTimeout = null;
2008
1985
  const sseClients = /* @__PURE__ */ new Set();
2009
1986
  try {
2010
- const srcDir = join5(primaryDir, "..", "..", "src");
1987
+ const srcDir = join4(primaryDir, "..", "..", "src");
2011
1988
  const watchDirs = [
2012
1989
  ...new Set(
2013
1990
  [primaryDir, options.apiDir, options.layoutsDir, resolvedActionsDir, srcDir].filter(
@@ -2032,9 +2009,16 @@ async function createApp(options) {
2032
2009
  const url = new URL(req.url).pathname;
2033
2010
  const healthResult = await healthHandler(req);
2034
2011
  if (healthResult !== null) return healthResult;
2012
+ if (metricsReporter?.handleMetrics) {
2013
+ const metricsResult = await metricsReporter.handleMetrics(req);
2014
+ if (metricsResult !== null) return metricsResult;
2015
+ }
2035
2016
  if (rateLimiter) {
2036
2017
  const limited = await rateLimitMiddleware(rateLimiter, req, server);
2037
- 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
+ }
2038
2022
  }
2039
2023
  if (url === "/__x/reload") {
2040
2024
  const body = new ReadableStream({
@@ -2095,7 +2079,8 @@ data: ${data}
2095
2079
  return renderNotFound(req);
2096
2080
  };
2097
2081
  const devFetchHardened = async (req, server) => withResponseHardening(await devFetchInner(req, server));
2098
- const devFetch = loggingEnabled ? withRequestLogging(devFetchHardened) : devFetchHardened;
2082
+ const devFetchBase = loggingEnabled ? withRequestLogging(devFetchHardened) : devFetchHardened;
2083
+ const devFetch = metricsReporter ? withRequestMetrics(metricsReporter, devFetchBase) : devFetchBase;
2099
2084
  return {
2100
2085
  routes: {},
2101
2086
  development: true,
@@ -2107,9 +2092,16 @@ data: ${data}
2107
2092
  const url = new URL(req.url).pathname;
2108
2093
  const healthResult = await healthHandler(req);
2109
2094
  if (healthResult !== null) return healthResult;
2095
+ if (metricsReporter?.handleMetrics) {
2096
+ const metricsResult = await metricsReporter.handleMetrics(req);
2097
+ if (metricsResult !== null) return metricsResult;
2098
+ }
2110
2099
  if (rateLimiter) {
2111
2100
  const limited = await rateLimitMiddleware(rateLimiter, req, server);
2112
- 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
+ }
2113
2105
  }
2114
2106
  const revalidationResult = await handleRevalidation(req);
2115
2107
  if (revalidationResult !== null) return revalidationResult;
@@ -2135,7 +2127,8 @@ data: ${data}
2135
2127
  return renderNotFound(req);
2136
2128
  };
2137
2129
  const prodFetchHardened = async (req, server) => withResponseHardening(await prodFetchInner(req, server));
2138
- const prodFetch = loggingEnabled ? withRequestLogging(prodFetchHardened) : prodFetchHardened;
2130
+ const prodFetchBase = loggingEnabled ? withRequestLogging(prodFetchHardened) : prodFetchHardened;
2131
+ const prodFetch = metricsReporter ? withRequestMetrics(metricsReporter, prodFetchBase) : prodFetchBase;
2139
2132
  return {
2140
2133
  routes: {},
2141
2134
  development: false,
@@ -2145,14 +2138,14 @@ data: ${data}
2145
2138
  }
2146
2139
 
2147
2140
  // src/build.ts
2148
- import { cpSync, existsSync as existsSync2, mkdirSync as mkdirSync2, writeFileSync as writeFileSync4 } from "fs";
2149
- 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";
2150
2143
  import { createElement as createElement2 } from "react";
2151
2144
  async function build(options) {
2152
- const outDir = options.outDir ?? join6(process.cwd(), ".x");
2153
- const clientDir = join6(outDir, "client");
2154
- const serverDir = join6(outDir, "server");
2155
- 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");
2156
2149
  mkdirSync2(clientDir, { recursive: true });
2157
2150
  mkdirSync2(serverDir, { recursive: true });
2158
2151
  mkdirSync2(islandsDir, { recursive: true });
@@ -2160,13 +2153,13 @@ async function build(options) {
2160
2153
  const apiDir = options.apiDir;
2161
2154
  const actionsDir = options.actionsDir;
2162
2155
  const layoutsDir = options.layoutsDir ?? pagesDir;
2163
- const projectRoot = pagesDir ? join6(pagesDir, "..", "..") : process.cwd();
2164
- const publicDir = join6(projectRoot, "public");
2156
+ const projectRoot = pagesDir ? join5(pagesDir, "..", "..") : process.cwd();
2157
+ const publicDir = join5(projectRoot, "public");
2165
2158
  const hasPublicDir = existsSync2(publicDir);
2166
- 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;
2167
2160
  if (hasPublicDir) {
2168
2161
  cpSync(publicDir, clientDir, { recursive: true });
2169
- console.log(`[x] build: copied public/ -> ${relative3(process.cwd(), clientDir)}`);
2162
+ console.log(`[x] build: copied public/ -> ${relative2(process.cwd(), clientDir)}`);
2170
2163
  }
2171
2164
  let routeEntries = [];
2172
2165
  if (pagesDir && existsSync2(pagesDir)) {
@@ -2175,7 +2168,7 @@ async function build(options) {
2175
2168
  if (apiDir && existsSync2(apiDir)) {
2176
2169
  routeEntries.push(...scanApiDir(apiDir));
2177
2170
  }
2178
- const legacyApiDir = pagesDir ? join6(pagesDir, "api") : "";
2171
+ const legacyApiDir = pagesDir ? join5(pagesDir, "api") : "";
2179
2172
  if (legacyApiDir && existsSync2(legacyApiDir) && legacyApiDir !== apiDir) {
2180
2173
  routeEntries.push(...scanApiDir(legacyApiDir));
2181
2174
  }
@@ -2261,8 +2254,8 @@ async function build(options) {
2261
2254
  const content = createElement2(IslandProvider, { registry }, pageContent);
2262
2255
  const html = renderStaticPage(content, { stylesheet: stylesheetHref });
2263
2256
  const outPath = page.entry.routePath === "/" ? "/index.html" : `${page.entry.routePath}/index.html`;
2264
- const fullPath = join6(clientDir, outPath);
2265
- mkdirSync2(join6(fullPath, ".."), { recursive: true });
2257
+ const fullPath = join5(clientDir, outPath);
2258
+ mkdirSync2(join5(fullPath, ".."), { recursive: true });
2266
2259
  if (writtenPaths.has(outPath)) {
2267
2260
  console.warn(` [warn] collision: ${page.entry.routePath} overwrites existing output`);
2268
2261
  }
@@ -2282,7 +2275,7 @@ async function build(options) {
2282
2275
  );
2283
2276
  }
2284
2277
  const finalHtml = renderStaticPage(content, { islandScripts, stylesheet: stylesheetHref });
2285
- writeFileSync4(fullPath, finalHtml, "utf-8");
2278
+ writeFileSync3(fullPath, finalHtml, "utf-8");
2286
2279
  console.log(` [static] ${page.entry.routePath} -> ${outPath}`);
2287
2280
  }
2288
2281
  for (const content of contentEntries) {
@@ -2298,13 +2291,13 @@ async function build(options) {
2298
2291
  stylesheet: stylesheetHref
2299
2292
  });
2300
2293
  const outPath = content.routePath === "/" ? "/index.html" : `${content.routePath}/index.html`;
2301
- const fullPath = join6(clientDir, outPath);
2302
- mkdirSync2(join6(fullPath, ".."), { recursive: true });
2294
+ const fullPath = join5(clientDir, outPath);
2295
+ mkdirSync2(join5(fullPath, ".."), { recursive: true });
2303
2296
  if (writtenPaths.has(outPath)) {
2304
2297
  console.warn(` [warn] collision: content ${content.routePath} overwrites existing output`);
2305
2298
  }
2306
2299
  writtenPaths.add(outPath);
2307
- writeFileSync4(fullPath, html, "utf-8");
2300
+ writeFileSync3(fullPath, html, "utf-8");
2308
2301
  console.log(` [content] ${content.routePath} -> ${outPath}`);
2309
2302
  }
2310
2303
  if (pagesDir || options.routesDir || options.contentDir) {
@@ -2321,8 +2314,8 @@ async function build(options) {
2321
2314
  configImportPath,
2322
2315
  stylesheetHref
2323
2316
  );
2324
- const serverEntryPath = join6(serverDir, "index.ts");
2325
- writeFileSync4(serverEntryPath, serverEntry, "utf-8");
2317
+ const serverEntryPath = join5(serverDir, "index.ts");
2318
+ writeFileSync3(serverEntryPath, serverEntry, "utf-8");
2326
2319
  console.log(
2327
2320
  ` [server] ${serverPages.length} page routes, ${apiRoutes.length} api routes -> server/index.ts`
2328
2321
  );
@@ -2331,12 +2324,12 @@ async function build(options) {
2331
2324
  }
2332
2325
  async function bundleRouteIslands(routeFilePath, layoutFilePaths, islandNames, islandsDir, actionModules) {
2333
2326
  const entryId = islandEntryId(routeFilePath);
2334
- const outdir = join6(islandsDir, entryId);
2327
+ const outdir = join5(islandsDir, entryId);
2335
2328
  mkdirSync2(outdir, { recursive: true });
2336
- const bundlePath = join6(outdir, `${entryId}.js`);
2329
+ const bundlePath = join5(outdir, `${entryId}.js`);
2337
2330
  const hydrateEntry = generateHydrateEntry(routeFilePath, layoutFilePaths);
2338
- const entryPath = join6(outdir, `${entryId}.tsx`);
2339
- writeFileSync4(entryPath, hydrateEntry, "utf-8");
2331
+ const entryPath = join5(outdir, `${entryId}.tsx`);
2332
+ writeFileSync3(entryPath, hydrateEntry, "utf-8");
2340
2333
  try {
2341
2334
  const result = await Bun.build({
2342
2335
  entrypoints: [entryPath],
@@ -2349,7 +2342,7 @@ async function bundleRouteIslands(routeFilePath, layoutFilePaths, islandNames, i
2349
2342
  if (!built) throw new Error("bun build produced no output");
2350
2343
  const code = await built.text();
2351
2344
  assertNoEnvLeakage(code, bundlePath);
2352
- writeFileSync4(bundlePath, wrapIslandBundle(code), "utf-8");
2345
+ writeFileSync3(bundlePath, wrapIslandBundle(code), "utf-8");
2353
2346
  return [`/_islands/${entryId}/${entryId}.js`];
2354
2347
  }
2355
2348
  for (const log of result.logs) {
@@ -2358,7 +2351,7 @@ async function bundleRouteIslands(routeFilePath, layoutFilePaths, islandNames, i
2358
2351
  } catch (err) {
2359
2352
  console.warn(` [islands] build failed for ${routeFilePath}:`, err);
2360
2353
  }
2361
- writeFileSync4(bundlePath, wrapIslandBundle(generateFallbackHydration(islandNames)), "utf-8");
2354
+ writeFileSync3(bundlePath, wrapIslandBundle(generateFallbackHydration(islandNames)), "utf-8");
2362
2355
  return [`/_islands/${entryId}/${entryId}.js`];
2363
2356
  }
2364
2357
  function renderPageWithLayout(Component, params, layoutModules) {
@@ -2441,7 +2434,7 @@ function buildServerEntry(opts, configImportPath, stylesheetHref) {
2441
2434
  return lines.join("\n");
2442
2435
  }
2443
2436
  function relativeImportPath(fromDir, toFile) {
2444
- const rel = relative3(fromDir, toFile).replace(/\\/g, "/").replace(/\.(ts|js|mjs)$/, "");
2437
+ const rel = relative2(fromDir, toFile).replace(/\\/g, "/").replace(/\.(ts|js|mjs)$/, "");
2445
2438
  return rel.startsWith(".") ? rel : `./${rel}`;
2446
2439
  }
2447
2440
 
@@ -2461,6 +2454,7 @@ function Link({ href, children, clientNav = true, prefetch = true, ...rest }) {
2461
2454
  }
2462
2455
  export {
2463
2456
  CLIENT_NAV_SCRIPT,
2457
+ DEFAULT_HISTOGRAM_BUCKETS_MS,
2464
2458
  DefaultNotFound,
2465
2459
  EnvLeakageError,
2466
2460
  Island,
@@ -2477,7 +2471,9 @@ export {
2477
2471
  createApp,
2478
2472
  createHealthCheckHandler,
2479
2473
  createImageProxyHandler,
2474
+ createInMemoryMetrics,
2480
2475
  createOtelReporter,
2476
+ createOtlpMetricsReporter,
2481
2477
  createRateLimiter,
2482
2478
  createRedisRateLimitStore,
2483
2479
  createSentryReporter,
@@ -2492,6 +2488,7 @@ export {
2492
2488
  getErrorReporter,
2493
2489
  getServerFunctionHandler,
2494
2490
  logger,
2491
+ noopMetrics,
2495
2492
  noopReporter,
2496
2493
  rateLimitMiddleware,
2497
2494
  registerServerFunctions,
@@ -2515,5 +2512,6 @@ export {
2515
2512
  verifyOrigin,
2516
2513
  withCsrfCookie,
2517
2514
  withRequestLogging,
2515
+ withRequestMetrics,
2518
2516
  writeManifest
2519
2517
  };