@thexjs/core 1.2.4 → 1.3.1

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,9 +1,27 @@
1
1
  import {
2
+ EnvLeakageError,
3
+ PUBLIC_ENV_PREFIX,
4
+ assertNoEnvLeakage,
5
+ buildIslandBundleInMemory,
6
+ bundleRouteIslandsToDisk,
7
+ checkCsrf,
8
+ combineReporters,
9
+ createOtelReporter,
10
+ createSentryReporter,
2
11
  extractParams,
3
12
  findLayoutChain,
13
+ findLeakedEnvKeys,
4
14
  findMiddlewareChain,
15
+ generateCsrfToken,
5
16
  generateManifestSource,
6
- routePatternToRegex,
17
+ generateServerFunctionClient,
18
+ getErrorReporter,
19
+ getServerFunctionHandler,
20
+ islandEntryId,
21
+ noopReporter,
22
+ registerServerFunctions,
23
+ reportException,
24
+ resetServerFunctions,
7
25
  scanApiDir,
8
26
  scanLayouts,
9
27
  scanLayoutsDir,
@@ -11,12 +29,16 @@ import {
11
29
  scanNotFound,
12
30
  scanPages,
13
31
  scanRoutes,
32
+ setErrorReporter,
33
+ verifyCsrfToken,
34
+ verifyOrigin,
35
+ withCsrfCookie,
14
36
  writeManifest
15
- } from "./chunk-O6SIM7EF.js";
37
+ } from "./chunk-MYYP67KQ.js";
16
38
 
17
39
  // src/build.ts
18
- import { cpSync, existsSync, mkdirSync as mkdirSync2, writeFileSync as writeFileSync3 } from "fs";
19
- import { join as join4, relative as relative2 } from "path";
40
+ import { cpSync, existsSync, mkdirSync, writeFileSync } from "fs";
41
+ import { join as join2, relative as relative2 } from "path";
20
42
  import { createElement } from "react";
21
43
 
22
44
  // src/content.ts
@@ -170,416 +192,6 @@ function Island({
170
192
  return /* @__PURE__ */ jsx("div", { "data-island": name, "data-island-id": id, "data-island-client": client, children });
171
193
  }
172
194
 
173
- // src/island-bundle.ts
174
- import { mkdirSync, mkdtempSync, rmSync, writeFileSync as writeFileSync2 } from "fs";
175
- import { basename, join as join3 } from "path";
176
-
177
- // src/security/env-isolation.ts
178
- var PUBLIC_ENV_PREFIX = "THEXJS_PUBLIC_";
179
- var ENV_ACCESS_PATTERNS = [
180
- /\bprocess\.env\.([A-Za-z_][A-Za-z0-9_]*)/g,
181
- /\bprocess\.env\[["']([A-Za-z_][A-Za-z0-9_]*)["']\]/g,
182
- /\bBun\.env\.([A-Za-z_][A-Za-z0-9_]*)/g,
183
- /\bBun\.env\[["']([A-Za-z_][A-Za-z0-9_]*)["']\]/g,
184
- /\bimport\.meta\.env\.([A-Za-z_][A-Za-z0-9_]*)/g,
185
- /\bimport\.meta\.env\[["']([A-Za-z_][A-Za-z0-9_]*)["']\]/g
186
- ];
187
- var SUSPICIOUS_ENV_PATTERNS = [
188
- {
189
- re: /\b(?:process|Bun|import\.meta)\.env\s*\[[^"'`]/g,
190
- label: "dynamic env key access"
191
- },
192
- {
193
- re: /\b(?:process|Bun|import\.meta)\.env\[["'][^"']*["']\s*\+/g,
194
- label: "concatenated env key access"
195
- },
196
- {
197
- re: /\b(?:process|Bun)\.env\b(?!\s*(?:\.|\[))/g,
198
- label: "bare process.env access (aliasing/mutation)"
199
- }
200
- ];
201
- function findLeakedEnvKeys(code) {
202
- const found = /* @__PURE__ */ new Set();
203
- for (const pattern of ENV_ACCESS_PATTERNS) {
204
- for (const match of code.matchAll(pattern)) {
205
- const key = match[1];
206
- if (key && !key.startsWith(PUBLIC_ENV_PREFIX)) {
207
- found.add(key);
208
- }
209
- }
210
- }
211
- for (const { re, label } of SUSPICIOUS_ENV_PATTERNS) {
212
- re.lastIndex = 0;
213
- if (re.test(code)) found.add(`process.env (${label})`);
214
- }
215
- return [...found];
216
- }
217
- var EnvLeakageError = class extends Error {
218
- constructor(file, keys) {
219
- super(
220
- `[x] server-only environment variable(s) leaked into client bundle "${file}": ${keys.join(", ")}. Only "${PUBLIC_ENV_PREFIX}*" variables may be referenced in client-shipped code \u2014 move this access into a loader, server function, or API route.`
221
- );
222
- this.file = file;
223
- this.keys = keys;
224
- this.name = "EnvLeakageError";
225
- }
226
- file;
227
- keys;
228
- };
229
- function assertNoEnvLeakage(code, file) {
230
- const leaked = findLeakedEnvKeys(code);
231
- if (leaked.length > 0) {
232
- throw new EnvLeakageError(file, leaked);
233
- }
234
- }
235
-
236
- // src/server-functions.ts
237
- import { writeFileSync } from "fs";
238
- import { join as join2 } from "path";
239
-
240
- // src/observability/monitoring.ts
241
- var noopReporter = {
242
- captureException: () => {
243
- }
244
- };
245
- var activeReporter = noopReporter;
246
- function setErrorReporter(reporter) {
247
- activeReporter = reporter;
248
- }
249
- function getErrorReporter() {
250
- return activeReporter;
251
- }
252
- function reportException(error, context) {
253
- try {
254
- activeReporter.captureException(error, context);
255
- } catch (reportingError) {
256
- console.error("[x] error reporter threw while handling an exception:", reportingError);
257
- }
258
- }
259
- function createSentryReporter(sentry) {
260
- return {
261
- captureException(error, context) {
262
- sentry.captureException(error, { extra: { ...context } });
263
- },
264
- async flush() {
265
- await sentry.flush?.(2e3);
266
- }
267
- };
268
- }
269
- var OTEL_ERROR_STATUS_CODE = 2;
270
- function createOtelReporter(tracer) {
271
- return {
272
- captureException(error, context) {
273
- const span = tracer.startSpan(`x.${context.phase}.error`);
274
- span.recordException(error);
275
- span.setStatus({
276
- code: OTEL_ERROR_STATUS_CODE,
277
- message: error instanceof Error ? error.message : String(error)
278
- });
279
- span.end();
280
- }
281
- };
282
- }
283
- function combineReporters(...reporters) {
284
- return {
285
- captureException(error, context) {
286
- for (const reporter of reporters) {
287
- try {
288
- reporter.captureException(error, context);
289
- } catch (err) {
290
- console.error("[x] error reporter threw while handling an exception:", err);
291
- }
292
- }
293
- },
294
- async flush() {
295
- await Promise.all(reporters.map((r) => r.flush?.()));
296
- }
297
- };
298
- }
299
-
300
- // src/security/csrf.ts
301
- var CSRF_COOKIE_NAME = "x_csrf_token";
302
- var CSRF_HEADER_NAME = "x-csrf-token";
303
- var SAFE_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD", "OPTIONS"]);
304
- var SECURE_COOKIE_FLAG = process.env.NODE_ENV === "production" ? "; Secure" : "";
305
- function originFromHeader(value) {
306
- if (!value) return null;
307
- try {
308
- return new URL(value).origin;
309
- } catch {
310
- return null;
311
- }
312
- }
313
- function requestOrigin(req) {
314
- const url = new URL(req.url);
315
- return `${url.protocol}//${url.host}`;
316
- }
317
- function verifyOrigin(req, allowedOrigins = []) {
318
- if (SAFE_METHODS.has(req.method)) return { ok: true };
319
- const selfOrigin = requestOrigin(req);
320
- const allowed = new Set([selfOrigin, ...allowedOrigins].filter(Boolean));
321
- const origin = originFromHeader(req.headers.get("origin"));
322
- if (origin) {
323
- return allowed.has(origin) ? { ok: true } : { ok: false, reason: `origin "${origin}" is not an allowed origin` };
324
- }
325
- const referer = originFromHeader(req.headers.get("referer"));
326
- if (referer) {
327
- return allowed.has(referer) ? { ok: true } : { ok: false, reason: `referer origin "${referer}" is not an allowed origin` };
328
- }
329
- return { ok: false, reason: "missing Origin and Referer headers on a mutating request" };
330
- }
331
- function generateCsrfToken() {
332
- return crypto.randomUUID().replace(/-/g, "") + crypto.randomUUID().replace(/-/g, "");
333
- }
334
- function readCookie(req, name) {
335
- const header = req.headers.get("cookie");
336
- if (!header) return null;
337
- for (const part of header.split(";")) {
338
- const [key, ...rest] = part.trim().split("=");
339
- if (key === name) return rest.join("=");
340
- }
341
- return null;
342
- }
343
- function verifyCsrfToken(req) {
344
- if (SAFE_METHODS.has(req.method)) return { ok: true };
345
- const cookieToken = readCookie(req, CSRF_COOKIE_NAME);
346
- const headerToken = req.headers.get(CSRF_HEADER_NAME);
347
- if (!cookieToken || !headerToken) {
348
- return { ok: false, reason: `missing CSRF cookie or "${CSRF_HEADER_NAME}" header` };
349
- }
350
- if (cookieToken !== headerToken) {
351
- return { ok: false, reason: "CSRF token mismatch" };
352
- }
353
- return { ok: true };
354
- }
355
- function withCsrfCookie(req, res) {
356
- if (readCookie(req, CSRF_COOKIE_NAME)) return res;
357
- const token = generateCsrfToken();
358
- const headers = new Headers(res.headers);
359
- headers.append(
360
- "Set-Cookie",
361
- `${CSRF_COOKIE_NAME}=${token}; Path=/; SameSite=Lax${SECURE_COOKIE_FLAG}`
362
- );
363
- return new Response(res.body, { status: res.status, statusText: res.statusText, headers });
364
- }
365
- function checkCsrf(req, options = {}) {
366
- if (options.disabled) return { ok: true };
367
- const originResult = verifyOrigin(req, options.allowedOrigins ?? []);
368
- if (!originResult.ok) return originResult;
369
- if (options.requireToken) {
370
- const tokenResult = verifyCsrfToken(req);
371
- if (!tokenResult.ok) return tokenResult;
372
- }
373
- return { ok: true };
374
- }
375
-
376
- // src/server-functions.ts
377
- function generateServerFunctionClient(routeFilePath, fnNames, endpointBase) {
378
- const fnCalls = fnNames.map(
379
- (name) => `
380
- export async function ${name}(...args: unknown[]): Promise<unknown> {
381
- const res = await fetch("${endpointBase}/${name}", {
382
- method: "POST",
383
- headers: { "Content-Type": "application/json" },
384
- body: JSON.stringify(args),
385
- });
386
- if (!res.ok) throw new Error(await res.text());
387
- return res.json();
388
- }`
389
- ).join("\n");
390
- return `// Auto-generated client for server functions in ${routeFilePath}
391
- // Do not edit.
392
-
393
- ${fnCalls}
394
- `;
395
- }
396
- var ACTION_ROUTES = [];
397
- function resetServerFunctions() {
398
- ACTION_ROUTES.length = 0;
399
- }
400
- function registerServerFunctions(routePath, paramNames, fns) {
401
- const fnMap = new Map(Object.entries(fns));
402
- const existing = ACTION_ROUTES.find((e) => e.routePath === routePath);
403
- if (existing) {
404
- for (const [name, fn] of fnMap) {
405
- existing.fns.set(name, fn);
406
- }
407
- } else {
408
- ACTION_ROUTES.push({ routePath, paramNames, fns: fnMap });
409
- }
410
- }
411
- function getServerFunctionHandler(csrfOptions) {
412
- return async (req) => {
413
- if (req.method !== "POST") return null;
414
- const url = new URL(req.url);
415
- if (!url.pathname.startsWith("/__x/actions/")) return null;
416
- const csrfResult = checkCsrf(req, csrfOptions);
417
- if (!csrfResult.ok) {
418
- return new Response(`Forbidden: ${csrfResult.reason}`, { status: 403 });
419
- }
420
- const parts = url.pathname.replace("/__x/actions/", "").split("/");
421
- if (parts.length < 1) return null;
422
- const actionName = parts.pop();
423
- if (!actionName) return null;
424
- const concretePath = `/${parts.join("/")}`;
425
- for (const entry of ACTION_ROUTES) {
426
- const params = extractActionParams(entry.routePath, entry.paramNames, concretePath);
427
- if (params === null) continue;
428
- const fn = entry.fns.get(actionName);
429
- if (!fn) return new Response("Function not found", { status: 404 });
430
- let args = [];
431
- try {
432
- const body = await req.json();
433
- args = Array.isArray(body) ? body : [body];
434
- } catch {
435
- return new Response("Invalid request body", { status: 400 });
436
- }
437
- try {
438
- const result = await fn(...args);
439
- return Response.json(result);
440
- } catch (err) {
441
- reportException(err, { route: concretePath, phase: "action" });
442
- const message = err instanceof Error ? err.message : "Internal error";
443
- return new Response(message, { status: 500 });
444
- }
445
- }
446
- return new Response("Not found", { status: 404 });
447
- };
448
- }
449
- function extractActionParams(routePath, paramNames, url) {
450
- const regex = routePatternToRegex(routePath);
451
- const match = url.match(regex);
452
- if (!match) return null;
453
- const params = {};
454
- let idx = 1;
455
- for (const name of paramNames) {
456
- const value = match[idx];
457
- if (value !== void 0) {
458
- params[name] = safeDecodeURIComponent(value);
459
- }
460
- idx++;
461
- }
462
- return params;
463
- }
464
- function safeDecodeURIComponent(value) {
465
- try {
466
- return decodeURIComponent(value);
467
- } catch {
468
- return value;
469
- }
470
- }
471
-
472
- // src/island-bundle.ts
473
- function actionsRewritePlugin(actionModules) {
474
- return {
475
- name: "x-actions-rewrite",
476
- setup(build2) {
477
- if (actionModules.size === 0) return;
478
- build2.onLoad({ filter: /\.(ts|tsx)$/ }, (args) => {
479
- const info = actionModules.get(args.path);
480
- if (!info) return void 0;
481
- const endpointBase = info.parentPath === "/" ? "/__x/actions" : `/__x/actions${info.parentPath}`;
482
- const contents = generateServerFunctionClient(args.path, info.fnNames, endpointBase);
483
- return { contents, loader: "ts" };
484
- });
485
- }
486
- };
487
- }
488
- function generateHydrateEntry(routeAbsPath, layoutAbsPaths = []) {
489
- const layoutImports = layoutAbsPaths.map((p, i) => `import * as Layout${i} from "${p}";`).join("\n");
490
- const lookupParts = ["Route.islands?.[name]"];
491
- for (let i = 0; i < layoutAbsPaths.length; i++) {
492
- lookupParts.push(`Layout${i}.islands?.[name]`);
493
- }
494
- const lookup = lookupParts.join(" ?? ");
495
- return `import React from "react";
496
- import { hydrateRoot } from "react-dom/client";
497
- import * as Route from "${routeAbsPath}";
498
- ${layoutImports}
499
-
500
- function resolveIsland(name: string) {
501
- return ${lookup};
502
- }
503
-
504
- // Islands whose render is non-deterministic (e.g. \`useState(() => ...)\` with
505
- // Math.random) can't be hydrated against their SSR output. React recovers by
506
- // re-rendering client-side, so the island is still fully interactive -- the
507
- // mismatch is benign, so swallow the recovery so it doesn't spam the console
508
- // or cascade into React's event system.
509
- function onRecoverableError() {}
510
-
511
- document.querySelectorAll("[data-island]").forEach((el) => {
512
- const name = el.getAttribute("data-island");
513
- if (!name) return;
514
- const Component = resolveIsland(name);
515
- if (!Component) return;
516
- hydrateRoot(el, React.createElement(Component), { onRecoverableError });
517
- });
518
- `;
519
- }
520
- function generateFallbackHydration(islandNames) {
521
- return `// x island hydration fallback \u2014 ${islandNames.join(", ")}
522
- document.querySelectorAll("[data-island]").forEach(function(el) {
523
- el.setAttribute("data-island-hydrated", "false");
524
- });
525
- `;
526
- }
527
- function hashId(str) {
528
- let h = 0;
529
- for (let i = 0; i < str.length; i++) {
530
- h = Math.imul(31, h) + str.charCodeAt(i) | 0;
531
- }
532
- return Math.abs(h).toString(36);
533
- }
534
- function islandEntryId(routeFilePath) {
535
- return `${basename(routeFilePath).replace(/\.(tsx|ts)$/, "")}-${hashId(routeFilePath)}`;
536
- }
537
- function wrapIslandBundle(code) {
538
- return `;(function () {
539
- ${code}
540
- })();
541
- `;
542
- }
543
- async function buildIslandBundleInMemory(routeFilePath, layoutFilePaths, islandNames, actionModules, projectRoot) {
544
- const entryId = islandEntryId(routeFilePath);
545
- const scratchRoot = join3(projectRoot, ".x", "islands-tmp");
546
- mkdirSync(scratchRoot, { recursive: true });
547
- const scratchDir = mkdtempSync(join3(scratchRoot, "x-islands-"));
548
- try {
549
- const entryPath = join3(scratchDir, `${entryId}.tsx`);
550
- writeFileSync2(entryPath, generateHydrateEntry(routeFilePath, layoutFilePaths), "utf-8");
551
- const result = await Bun.build({
552
- entrypoints: [entryPath],
553
- target: "browser",
554
- plugins: [actionsRewritePlugin(actionModules)]
555
- });
556
- if (!result.success) {
557
- for (const log of result.logs) {
558
- console.warn(` [islands] build error: ${log.message}`);
559
- }
560
- return wrapIslandBundle(generateFallbackHydration(islandNames));
561
- }
562
- const outputs = result.outputs.filter((o) => o.kind === "entry-point");
563
- const built = outputs[0] ?? result.outputs[0];
564
- if (!built) return wrapIslandBundle(generateFallbackHydration(islandNames));
565
- const code = await built.text();
566
- assertNoEnvLeakage(code, entryPath);
567
- return wrapIslandBundle(code);
568
- } catch (err) {
569
- if (err instanceof EnvLeakageError) {
570
- console.error(
571
- `\x1B[1;31m\u{1F512} SECURITY: [islands] ${err.message}\x1B[0m
572
- Falling back to a non-interactive hydration stub \u2014 fix the env isolation (prefix with THEXJS_PUBLIC_ or move the access server-side) before relying on this page's client behavior.`
573
- );
574
- return wrapIslandBundle(generateFallbackHydration(islandNames));
575
- }
576
- console.warn(` [islands] build failed for ${routeFilePath}:`, err);
577
- return wrapIslandBundle(generateFallbackHydration(islandNames));
578
- } finally {
579
- rmSync(scratchDir, { recursive: true, force: true });
580
- }
581
- }
582
-
583
195
  // src/render.ts
584
196
  import { renderToReadableStream, renderToStaticMarkup, renderToString } from "react-dom/server";
585
197
 
@@ -888,21 +500,21 @@ ${liveReloadTag} </body>
888
500
 
889
501
  // src/build.ts
890
502
  async function build(options) {
891
- const outDir = options.outDir ?? join4(process.cwd(), ".x");
892
- const clientDir = join4(outDir, "client");
893
- const serverDir = join4(outDir, "server");
894
- const islandsDir = join4(clientDir, "_islands");
895
- mkdirSync2(clientDir, { recursive: true });
896
- mkdirSync2(serverDir, { recursive: true });
897
- mkdirSync2(islandsDir, { recursive: true });
503
+ const outDir = options.outDir ?? join2(process.cwd(), ".x");
504
+ const clientDir = join2(outDir, "client");
505
+ const serverDir = join2(outDir, "server");
506
+ const islandsDir = join2(clientDir, "_islands");
507
+ mkdirSync(clientDir, { recursive: true });
508
+ mkdirSync(serverDir, { recursive: true });
509
+ mkdirSync(islandsDir, { recursive: true });
898
510
  const pagesDir = options.pagesDir ?? options.routesDir ?? "";
899
511
  const apiDir = options.apiDir;
900
512
  const actionsDir = options.actionsDir;
901
513
  const layoutsDir = options.layoutsDir ?? pagesDir;
902
- const projectRoot = pagesDir ? join4(pagesDir, "..", "..") : process.cwd();
903
- const publicDir = join4(projectRoot, "public");
514
+ const projectRoot = pagesDir ? join2(pagesDir, "..", "..") : process.cwd();
515
+ const publicDir = join2(projectRoot, "public");
904
516
  const hasPublicDir = existsSync(publicDir);
905
- const stylesheetHref = hasPublicDir && existsSync(join4(publicDir, "styles.css")) ? "/styles.css" : void 0;
517
+ const stylesheetHref = hasPublicDir && existsSync(join2(publicDir, "styles.css")) ? "/styles.css" : void 0;
906
518
  if (hasPublicDir) {
907
519
  cpSync(publicDir, clientDir, { recursive: true });
908
520
  console.log(`[x] build: copied public/ -> ${relative2(process.cwd(), clientDir)}`);
@@ -914,7 +526,7 @@ async function build(options) {
914
526
  if (apiDir && existsSync(apiDir)) {
915
527
  routeEntries.push(...scanApiDir(apiDir));
916
528
  }
917
- const legacyApiDir = pagesDir ? join4(pagesDir, "api") : "";
529
+ const legacyApiDir = pagesDir ? join2(pagesDir, "api") : "";
918
530
  if (legacyApiDir && existsSync(legacyApiDir) && legacyApiDir !== apiDir) {
919
531
  routeEntries.push(...scanApiDir(legacyApiDir));
920
532
  }
@@ -1000,8 +612,8 @@ async function build(options) {
1000
612
  const content = createElement(IslandProvider, { registry }, pageContent);
1001
613
  const _html = renderStaticPage(content, { stylesheet: stylesheetHref });
1002
614
  const outPath = page.entry.routePath === "/" ? "/index.html" : `${page.entry.routePath}/index.html`;
1003
- const fullPath = join4(clientDir, outPath);
1004
- mkdirSync2(join4(fullPath, ".."), { recursive: true });
615
+ const fullPath = join2(clientDir, outPath);
616
+ mkdirSync(join2(fullPath, ".."), { recursive: true });
1005
617
  if (writtenPaths.has(outPath)) {
1006
618
  console.warn(` [warn] collision: ${page.entry.routePath} overwrites existing output`);
1007
619
  }
@@ -1009,7 +621,7 @@ async function build(options) {
1009
621
  let islandScripts = [];
1010
622
  if (registry.entries.length > 0) {
1011
623
  const uniqueNames = [...new Set(registry.entries.map((e) => e.name))];
1012
- islandScripts = await bundleRouteIslands(
624
+ islandScripts = await bundleRouteIslandsToDisk(
1013
625
  page.filePath,
1014
626
  page.layoutFilePaths,
1015
627
  uniqueNames,
@@ -1021,7 +633,7 @@ async function build(options) {
1021
633
  );
1022
634
  }
1023
635
  const finalHtml = renderStaticPage(content, { islandScripts, stylesheet: stylesheetHref });
1024
- writeFileSync3(fullPath, finalHtml, "utf-8");
636
+ writeFileSync(fullPath, finalHtml, "utf-8");
1025
637
  console.log(` [static] ${page.entry.routePath} -> ${outPath}`);
1026
638
  }
1027
639
  for (const content of contentEntries) {
@@ -1037,13 +649,13 @@ async function build(options) {
1037
649
  stylesheet: stylesheetHref
1038
650
  });
1039
651
  const outPath = content.routePath === "/" ? "/index.html" : `${content.routePath}/index.html`;
1040
- const fullPath = join4(clientDir, outPath);
1041
- mkdirSync2(join4(fullPath, ".."), { recursive: true });
652
+ const fullPath = join2(clientDir, outPath);
653
+ mkdirSync(join2(fullPath, ".."), { recursive: true });
1042
654
  if (writtenPaths.has(outPath)) {
1043
655
  console.warn(` [warn] collision: content ${content.routePath} overwrites existing output`);
1044
656
  }
1045
657
  writtenPaths.add(outPath);
1046
- writeFileSync3(fullPath, html, "utf-8");
658
+ writeFileSync(fullPath, html, "utf-8");
1047
659
  console.log(` [content] ${content.routePath} -> ${outPath}`);
1048
660
  }
1049
661
  if (pagesDir || options.routesDir || options.contentDir) {
@@ -1060,47 +672,14 @@ async function build(options) {
1060
672
  configImportPath,
1061
673
  stylesheetHref
1062
674
  );
1063
- const serverEntryPath = join4(serverDir, "index.ts");
1064
- writeFileSync3(serverEntryPath, serverEntry, "utf-8");
675
+ const serverEntryPath = join2(serverDir, "index.ts");
676
+ writeFileSync(serverEntryPath, serverEntry, "utf-8");
1065
677
  console.log(
1066
678
  ` [server] ${serverPages.length} page routes, ${apiRoutes.length} api routes -> server/index.ts`
1067
679
  );
1068
680
  }
1069
681
  console.log(`[x] build complete -> ${outDir}`);
1070
682
  }
1071
- async function bundleRouteIslands(routeFilePath, layoutFilePaths, islandNames, islandsDir, actionModules) {
1072
- const entryId = islandEntryId(routeFilePath);
1073
- const outdir = join4(islandsDir, entryId);
1074
- mkdirSync2(outdir, { recursive: true });
1075
- const bundlePath = join4(outdir, `${entryId}.js`);
1076
- const hydrateEntry = generateHydrateEntry(routeFilePath, layoutFilePaths);
1077
- const entryPath = join4(outdir, `${entryId}.tsx`);
1078
- writeFileSync3(entryPath, hydrateEntry, "utf-8");
1079
- try {
1080
- const result = await Bun.build({
1081
- entrypoints: [entryPath],
1082
- target: "browser",
1083
- plugins: [actionsRewritePlugin(actionModules)]
1084
- });
1085
- if (result.success) {
1086
- const outputs = result.outputs.filter((o) => o.kind === "entry-point");
1087
- const built = outputs[0] ?? result.outputs[0];
1088
- if (!built) throw new Error("bun build produced no output");
1089
- const code = await built.text();
1090
- assertNoEnvLeakage(code, bundlePath);
1091
- writeFileSync3(bundlePath, wrapIslandBundle(code), "utf-8");
1092
- return [`/_islands/${entryId}/${entryId}.js`];
1093
- }
1094
- for (const log of result.logs) {
1095
- console.warn(` [islands] build error: ${log.message}`);
1096
- }
1097
- } catch (err) {
1098
- if (err instanceof EnvLeakageError) throw err;
1099
- console.warn(` [islands] build failed for ${routeFilePath}:`, err);
1100
- }
1101
- writeFileSync3(bundlePath, wrapIslandBundle(generateFallbackHydration(islandNames)), "utf-8");
1102
- return [`/_islands/${entryId}/${entryId}.js`];
1103
- }
1104
683
  function renderPageWithLayout(Component, params, layoutModules) {
1105
684
  let content = createElement(Component, { params });
1106
685
  for (const Layout of [...layoutModules].reverse()) {
@@ -1184,7 +763,7 @@ function relativeImportPath(fromDir, toFile) {
1184
763
 
1185
764
  // src/createApp.ts
1186
765
  import { existsSync as existsSync2, watch } from "fs";
1187
- import { join as join5, resolve, sep as sep2 } from "path";
766
+ import { join as join3, resolve, sep as sep2 } from "path";
1188
767
  import { createElement as createElement2 } from "react";
1189
768
 
1190
769
  // src/error-overlay.ts
@@ -1336,6 +915,20 @@ function createImageProxyHandler(options = {}) {
1336
915
  if (!allowedUrl(parsed)) {
1337
916
  return new Response("host not allow-listed for image proxy", { status: 403 });
1338
917
  }
918
+ const wParam = reqUrl.searchParams.get("w");
919
+ const qParam = reqUrl.searchParams.get("q");
920
+ if (wParam !== null) {
921
+ const w = Number.parseInt(wParam, 10);
922
+ if (!Number.isFinite(w) || w < 1 || w > 8192) {
923
+ return new Response("invalid w param", { status: 400 });
924
+ }
925
+ }
926
+ if (qParam !== null) {
927
+ const q = Number.parseInt(qParam, 10);
928
+ if (!Number.isFinite(q) || q < 1 || q > 100) {
929
+ return new Response("invalid q param", { status: 400 });
930
+ }
931
+ }
1339
932
  const isRedirect = (status) => status === 301 || status === 302 || status === 303 || status === 307 || status === 308;
1340
933
  let upstream;
1341
934
  try {
@@ -1826,7 +1419,7 @@ function routeMatchesForSort(entry) {
1826
1419
  return isStatic ? 0 : isCatchAll ? 2 : 1;
1827
1420
  }
1828
1421
  function projectRootFromRoutesDir(routesDir) {
1829
- return join5(routesDir, "..", "..");
1422
+ return join3(routesDir, "..", "..");
1830
1423
  }
1831
1424
  function resolvePublicAsset(publicDir, pathname) {
1832
1425
  let decoded;
@@ -1835,7 +1428,7 @@ function resolvePublicAsset(publicDir, pathname) {
1835
1428
  } catch {
1836
1429
  return null;
1837
1430
  }
1838
- const target = resolve(join5(publicDir, decoded));
1431
+ const target = resolve(join3(publicDir, decoded));
1839
1432
  const root = resolve(publicDir);
1840
1433
  if (target !== root && !target.startsWith(root + sep2)) return null;
1841
1434
  return target;
@@ -1887,7 +1480,7 @@ async function createApp(options) {
1887
1480
  const dev = options.development ?? false;
1888
1481
  const primaryDir = options.pagesDir || options.routesDir || "src/pages";
1889
1482
  const projectRoot = projectRootFromRoutesDir(primaryDir);
1890
- const resolvedActionsDir = options.actionsDir ?? (existsSync2(join5(projectRoot, "src", "actions")) ? join5(projectRoot, "src", "actions") : void 0);
1483
+ const resolvedActionsDir = options.actionsDir ?? (existsSync2(join3(projectRoot, "src", "actions")) ? join3(projectRoot, "src", "actions") : void 0);
1891
1484
  let handlers = [];
1892
1485
  let contentHandlers = [];
1893
1486
  let publicDir = null;
@@ -2096,9 +1689,9 @@ async function createApp(options) {
2096
1689
  async function buildHandlers() {
2097
1690
  if (options.preloaded) {
2098
1691
  const preloaded = options.preloaded;
2099
- const candidatePublicDir2 = join5(projectRoot, "public");
1692
+ const candidatePublicDir2 = join3(projectRoot, "public");
2100
1693
  publicDir = existsSync2(candidatePublicDir2) ? candidatePublicDir2 : null;
2101
- stylesheetHref = options.stylesheetHref ?? (publicDir && existsSync2(join5(publicDir, "styles.css")) ? "/styles.css" : void 0);
1694
+ stylesheetHref = options.stylesheetHref ?? (publicDir && existsSync2(join3(publicDir, "styles.css")) ? "/styles.css" : void 0);
2102
1695
  if (preloaded.notFoundComponent) notFoundComponent = preloaded.notFoundComponent;
2103
1696
  if (preloaded.notFoundLayout) notFoundLayout = preloaded.notFoundLayout;
2104
1697
  const loaded2 = [];
@@ -2151,7 +1744,7 @@ async function createApp(options) {
2151
1744
  if (apiDir && existsSync2(apiDir)) {
2152
1745
  apiFound.push(...scanApiDir(apiDir));
2153
1746
  }
2154
- const legacyApiDir = join5(pagesDir, "api");
1747
+ const legacyApiDir = join3(pagesDir, "api");
2155
1748
  if (existsSync2(legacyApiDir) && legacyApiDir !== apiDir) {
2156
1749
  apiFound.push(...scanApiDir(legacyApiDir));
2157
1750
  }
@@ -2186,9 +1779,9 @@ async function createApp(options) {
2186
1779
  }
2187
1780
  }
2188
1781
  }
2189
- const candidatePublicDir = join5(projectRoot, "public");
1782
+ const candidatePublicDir = join3(projectRoot, "public");
2190
1783
  publicDir = existsSync2(candidatePublicDir) ? candidatePublicDir : null;
2191
- stylesheetHref = options.stylesheetHref ?? (publicDir && existsSync2(join5(publicDir, "styles.css")) ? "/styles.css" : void 0);
1784
+ stylesheetHref = options.stylesheetHref ?? (publicDir && existsSync2(join3(publicDir, "styles.css")) ? "/styles.css" : void 0);
2192
1785
  const notFoundEntry = scanNotFound(pagesDir);
2193
1786
  if (notFoundEntry) {
2194
1787
  const mod = await importDev(notFoundEntry.filePath, dev);
@@ -2348,7 +1941,7 @@ async function createApp(options) {
2348
1941
  let rebuildTimeout = null;
2349
1942
  const sseClients = /* @__PURE__ */ new Set();
2350
1943
  try {
2351
- const srcDir = join5(primaryDir, "..", "..", "src");
1944
+ const srcDir = join3(primaryDir, "..", "..", "src");
2352
1945
  const watchDirs = [
2353
1946
  ...new Set(
2354
1947
  [primaryDir, options.apiDir, options.layoutsDir, resolvedActionsDir, srcDir].filter(
@@ -2501,10 +2094,120 @@ data: ${data}
2501
2094
  };
2502
2095
  }
2503
2096
 
2097
+ // src/image.tsx
2098
+ import { jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
2099
+ var DEV = typeof process !== "undefined" && process.env?.NODE_ENV === "development";
2100
+ var PROXY_PATH = "/_x/image";
2101
+ var SRCSET_WIDTHS = [320, 640, 750, 828, 1080, 1200, 1920, 2048, 3840];
2102
+ function isRemoteUrl(src) {
2103
+ return /^https?:\/\//i.test(src);
2104
+ }
2105
+ function proxyUrl(src, w, q) {
2106
+ const params = new URLSearchParams({ url: src });
2107
+ if (w !== void 0) params.set("w", String(w));
2108
+ if (q !== void 0) params.set("q", String(q));
2109
+ return `${PROXY_PATH}?${params.toString()}`;
2110
+ }
2111
+ function devWarn(message) {
2112
+ if (DEV) {
2113
+ console.warn(`[x/image] ${message}`);
2114
+ }
2115
+ }
2116
+ function buildSrcSet(src, opts = {}) {
2117
+ if (!isRemoteUrl(src)) return void 0;
2118
+ try {
2119
+ const hosts = new Set(opts.remoteHosts ?? []);
2120
+ if (!hosts.has(new URL(src).hostname)) return void 0;
2121
+ } catch {
2122
+ return void 0;
2123
+ }
2124
+ return SRCSET_WIDTHS.map((w) => `${proxyUrl(src, w, opts.quality)} ${w}w`).join(", ");
2125
+ }
2126
+ function setImageRemoteHosts(hosts) {
2127
+ _remoteHosts = hosts;
2128
+ }
2129
+ var _remoteHosts;
2130
+ function Image(props) {
2131
+ const {
2132
+ src,
2133
+ alt,
2134
+ width,
2135
+ height,
2136
+ sizes,
2137
+ priority = false,
2138
+ fill = false,
2139
+ placeholder = "empty",
2140
+ blurDataURL,
2141
+ quality,
2142
+ className,
2143
+ style: userStyle,
2144
+ children
2145
+ } = props;
2146
+ const remote = isRemoteUrl(src);
2147
+ if (DEV) {
2148
+ if (fill && (width !== void 0 || height !== void 0)) {
2149
+ devWarn(`both "fill" and width/height are set on "${src}" \u2014 fill ignores dimensions.`);
2150
+ }
2151
+ if (!fill && (width === void 0 || height === void 0)) {
2152
+ devWarn(
2153
+ `missing width/height on "${src}" (causes layout shift). Provide both or use "fill".`
2154
+ );
2155
+ }
2156
+ if (remote) {
2157
+ const host = new URL(src).hostname;
2158
+ if (!_remoteHosts?.includes(host)) {
2159
+ devWarn(
2160
+ `remote src "${src}" host "${host}" is not in images.remoteHosts \u2014 the proxy will 403.`
2161
+ );
2162
+ }
2163
+ }
2164
+ }
2165
+ const resolvedSrc = remote ? proxyUrl(src, quality) : src;
2166
+ const baseStyle = fill ? { position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover" } : { maxWidth: "100%", height: "auto" };
2167
+ if (!fill && width !== void 0 && height !== void 0) {
2168
+ baseStyle.aspectRatio = `${width} / ${height}`;
2169
+ }
2170
+ const placeholderStyle = placeholder === "blur" && blurDataURL ? {
2171
+ backgroundImage: `url(${blurDataURL})`,
2172
+ backgroundSize: "cover",
2173
+ backgroundPosition: "center"
2174
+ } : {};
2175
+ const imgProps = {
2176
+ src: resolvedSrc,
2177
+ sizes,
2178
+ className,
2179
+ style: { ...baseStyle, ...placeholderStyle, ...userStyle },
2180
+ decoding: "async"
2181
+ };
2182
+ if (fill) {
2183
+ imgProps.width = void 0;
2184
+ imgProps.height = void 0;
2185
+ } else {
2186
+ imgProps.width = width;
2187
+ imgProps.height = height;
2188
+ }
2189
+ if (priority) {
2190
+ imgProps.fetchPriority = "high";
2191
+ } else {
2192
+ imgProps.loading = "lazy";
2193
+ }
2194
+ if (remote) {
2195
+ imgProps.srcSet = SRCSET_WIDTHS.map((w) => `${proxyUrl(src, w, quality)} ${w}w`).join(", ");
2196
+ }
2197
+ const img = /* @__PURE__ */ jsx3("img", { alt, ...imgProps });
2198
+ if (children) {
2199
+ return /* @__PURE__ */ jsxs2("picture", { children: [
2200
+ children,
2201
+ img
2202
+ ] });
2203
+ }
2204
+ return img;
2205
+ }
2206
+
2504
2207
  // src/link.tsx
2505
- import { jsx as jsx3 } from "react/jsx-runtime";
2208
+ import { jsx as jsx4 } from "react/jsx-runtime";
2506
2209
  function Link({ href, children, clientNav = true, prefetch = true, ...rest }) {
2507
- return /* @__PURE__ */ jsx3(
2210
+ return /* @__PURE__ */ jsx4(
2508
2211
  "a",
2509
2212
  {
2510
2213
  href,
@@ -2520,14 +2223,17 @@ export {
2520
2223
  DEFAULT_HISTOGRAM_BUCKETS_MS,
2521
2224
  DefaultNotFound,
2522
2225
  EnvLeakageError,
2226
+ Image,
2523
2227
  Island,
2524
2228
  IslandProvider,
2525
2229
  Link,
2526
2230
  PUBLIC_ENV_PREFIX,
2231
+ SRCSET_WIDTHS,
2527
2232
  applySecurityHeaders,
2528
2233
  assertNoEnvLeakage,
2529
2234
  build,
2530
2235
  buildSecurityHeaders,
2236
+ buildSrcSet,
2531
2237
  checkCsrf,
2532
2238
  combineReporters,
2533
2239
  composeMiddleware,
@@ -2571,6 +2277,7 @@ export {
2571
2277
  scanPages,
2572
2278
  scanRoutes,
2573
2279
  setErrorReporter,
2280
+ setImageRemoteHosts,
2574
2281
  verifyCsrfToken,
2575
2282
  verifyOrigin,
2576
2283
  withCsrfCookie,