tw-framework 2.0.0 → 2.0.2

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/testing.cjs CHANGED
@@ -6906,20 +6906,39 @@ function sha12(data) {
6906
6906
  async function md52(data) {
6907
6907
  return hashWithWebCrypto("md5", data);
6908
6908
  }
6909
+ function webcryptoHashName(algorithm) {
6910
+ const key2 = String(algorithm).toLowerCase().replace(/[-_]/g, "");
6911
+ const map2 = {
6912
+ md5: "MD5",
6913
+ sha1: "SHA-1",
6914
+ sha224: "SHA-224",
6915
+ sha256: "SHA-256",
6916
+ sha384: "SHA-384",
6917
+ sha512: "SHA-512"
6918
+ };
6919
+ return map2[key2] ?? algorithm;
6920
+ }
6909
6921
  async function hmac2(data, key2, algorithm = "sha256") {
6910
6922
  const encoder2 = new TextEncoder();
6911
6923
  const keyData = encoder2.encode(key2);
6912
6924
  const messageData = encoder2.encode(data);
6913
- const cryptoKey = await crypto.subtle.importKey("raw", keyData, { name: "HMAC", hash: algorithm }, false, ["sign"]);
6925
+ const cryptoKey = await crypto.subtle.importKey("raw", keyData, { name: "HMAC", hash: webcryptoHashName(algorithm) }, false, ["sign"]);
6914
6926
  const signature = await crypto.subtle.sign("HMAC", cryptoKey, messageData);
6915
6927
  const hashArray = Array.from(new Uint8Array(signature));
6916
6928
  return hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
6917
6929
  }
6930
+ async function verifyHmac(data, key2, signature, algorithm = "sha256") {
6931
+ const expected = await hmac2(data, key2, algorithm);
6932
+ if (expected.length !== signature.length) return false;
6933
+ let diff2 = 0;
6934
+ for (let i = 0; i < expected.length; i++) diff2 |= expected.charCodeAt(i) ^ signature.charCodeAt(i);
6935
+ return diff2 === 0;
6936
+ }
6918
6937
  async function pbkdf2(password, salt, iterations = 1e5, keyLength = 256) {
6919
6938
  const encoder2 = new TextEncoder();
6920
6939
  const keyMaterial = await crypto.subtle.importKey("raw", encoder2.encode(password), "PBKDF2", false, ["deriveBits"]);
6921
6940
  const derivedBits = await crypto.subtle.deriveBits(
6922
- { name: "PBKDF2", salt: encoder2.encode(salt), iterations, hash: "sha256" },
6941
+ { name: "PBKDF2", salt: encoder2.encode(salt), iterations, hash: "SHA-256" },
6923
6942
  keyMaterial,
6924
6943
  keyLength
6925
6944
  );
@@ -6964,9 +6983,16 @@ async function decryptString(encryptedData, password, salt) {
6964
6983
  const key2 = await deriveKey(password, salt);
6965
6984
  return decryptAES(encrypted, key2, iv);
6966
6985
  }
6986
+ async function generateRSASigningKeyPair(bits = 2048) {
6987
+ return crypto.subtle.generateKey(
6988
+ { name: "RSASSA-PKCS1-v1_5", modulusLength: bits, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256" },
6989
+ true,
6990
+ ["sign", "verify"]
6991
+ );
6992
+ }
6967
6993
  async function generateRSAKeyPair(bits = 2048) {
6968
6994
  return crypto.subtle.generateKey(
6969
- { name: "RSA-OAEP", modulusLength: bits, publicExponent: new Uint8Array([1, 0, 1]), hash: "sha256" },
6995
+ { name: "RSA-OAEP", modulusLength: bits, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256" },
6970
6996
  true,
6971
6997
  ["encrypt", "decrypt"]
6972
6998
  );
@@ -8415,36 +8441,6 @@ var init_etag = __esm({
8415
8441
  });
8416
8442
 
8417
8443
  // ../../packages/shared/tw/hashing/hmac.ts
8418
- function bufferToHex2(buffer) {
8419
- const bytes = new Uint8Array(buffer);
8420
- return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
8421
- }
8422
- function timingSafeEqual2(a, b) {
8423
- if (a.length !== b.length) return false;
8424
- let result = 0;
8425
- for (let i = 0; i < a.length; i++) {
8426
- result |= a.charCodeAt(i) ^ b.charCodeAt(i);
8427
- }
8428
- return result === 0;
8429
- }
8430
- async function hmac3(key2, message, algorithm = "SHA-256") {
8431
- const encoder2 = new TextEncoder();
8432
- const keyData = encoder2.encode(key2);
8433
- const messageData = encoder2.encode(message);
8434
- const cryptoKey = await crypto.subtle.importKey(
8435
- "raw",
8436
- keyData,
8437
- { name: "HMAC", hash: algorithm },
8438
- false,
8439
- ["sign"]
8440
- );
8441
- const signature = await crypto.subtle.sign("HMAC", cryptoKey, messageData);
8442
- return bufferToHex2(signature);
8443
- }
8444
- async function verifyHmac(key2, message, signature, algorithm = "SHA-256") {
8445
- const computed6 = await hmac3(key2, message, algorithm);
8446
- return timingSafeEqual2(computed6, signature);
8447
- }
8448
8444
  var init_hmac = __esm({
8449
8445
  "../../packages/shared/tw/hashing/hmac.ts"() {
8450
8446
  }
@@ -9109,6 +9105,7 @@ __export(tw_exports, {
9109
9105
  generatePIN: () => generatePIN,
9110
9106
  generateProofOfKnowledge: () => generateProofOfKnowledge,
9111
9107
  generateRSAKeyPair: () => generateRSAKeyPair,
9108
+ generateRSASigningKeyPair: () => generateRSASigningKeyPair,
9112
9109
  generateSecret: () => generateSecret,
9113
9110
  generateTOTP: () => generateTOTP,
9114
9111
  geolocation: () => geolocation,
@@ -9639,23 +9636,19 @@ function merkleRoot(hashes) {
9639
9636
  return level[0];
9640
9637
  }
9641
9638
  function hmacSign(data, key2) {
9642
- let h1 = 0, h22 = 0;
9643
- for (let i = 0; i < data.length; i++) {
9644
- h1 = (h1 << 5) - h1 + data.charCodeAt(i);
9645
- h1 |= 0;
9646
- }
9647
- for (let i = 0; i < key2.length; i++) {
9648
- h22 = (h22 << 5) - h22 + key2.charCodeAt(i);
9649
- h22 |= 0;
9650
- }
9651
- return (h1 ^ h22).toString(16);
9639
+ return (0, import_node_crypto3.createHmac)("sha256", key2).update(data).digest("hex");
9652
9640
  }
9653
9641
  function hmacVerify(data, key2, signature) {
9654
- return hmacSign(data, key2) === signature;
9642
+ const expected = hmacSign(data, key2);
9643
+ if (expected.length !== signature.length) return false;
9644
+ let diff2 = 0;
9645
+ for (let i = 0; i < expected.length; i++) diff2 |= expected.charCodeAt(i) ^ signature.charCodeAt(i);
9646
+ return diff2 === 0;
9655
9647
  }
9656
- var HTML_TAGS;
9648
+ var import_node_crypto3, HTML_TAGS;
9657
9649
  var init_tw = __esm({
9658
9650
  "../../packages/shared/tw/index.ts"() {
9651
+ import_node_crypto3 = require("node:crypto");
9659
9652
  init_sha();
9660
9653
  init_utils();
9661
9654
  init_manipulate();
@@ -227073,7 +227066,7 @@ function parseTWSelector(cursor, errors, state, parseBody) {
227073
227066
  const after2 = cursor.peek(1);
227074
227067
  if (after2 && after2.type === "COLON") break;
227075
227068
  }
227076
- if (ct.type === "IDENT" && !prevWasMinus && classVal.length > 0 && (CLASS_BOUNDARY_BOOLEAN_ATTRS.has(ct.value) || inlineAttrStartsAt(cursor))) {
227069
+ if ((ct.type === "IDENT" || ct.type === "KEYWORD") && !prevWasMinus && classVal.length > 0 && (CLASS_BOUNDARY_BOOLEAN_ATTRS.has(ct.value) || inlineAttrStartsAt(cursor))) {
227077
227070
  break;
227078
227071
  }
227079
227072
  if (ct.type === "IDENT" || ct.type === "TEXT" || ct.type === "KEYWORD") {
@@ -227101,7 +227094,11 @@ function parseTWSelector(cursor, errors, state, parseBody) {
227101
227094
  while (!cursor.done) {
227102
227095
  const ct = cursor.peek();
227103
227096
  if (!ct) break;
227104
- if (ct.type === "IDENT" && !nextPrevMinus && nextClass.length > 0 && (CLASS_BOUNDARY_BOOLEAN_ATTRS.has(ct.value) || inlineAttrStartsAt(cursor))) {
227097
+ if (ct.type === "IDENT" && ct.value === "on") {
227098
+ const after2 = cursor.peek(1);
227099
+ if (after2 && after2.type === "COLON") break;
227100
+ }
227101
+ if ((ct.type === "IDENT" || ct.type === "KEYWORD") && !nextPrevMinus && nextClass.length > 0 && (CLASS_BOUNDARY_BOOLEAN_ATTRS.has(ct.value) || inlineAttrStartsAt(cursor))) {
227105
227102
  break;
227106
227103
  }
227107
227104
  if (ct.type === "IDENT" || ct.type === "TEXT" || ct.type === "KEYWORD") {
@@ -227391,7 +227388,9 @@ function parseTWSelector(cursor, errors, state, parseBody) {
227391
227388
  const first = cursor.peek();
227392
227389
  const second = cursor.peek(1);
227393
227390
  const CONTROL_FLOW = /* @__PURE__ */ new Set(["for", "if", "while", "switch", "else", "try", "catch"]);
227394
- const isAttrBlock = first && (first.type === "IDENT" || first.type === "KEYWORD") && !CONTROL_FLOW.has(first.value) && HTML_ATTRS_ONLY.has(first.value) && second && (second.type === "STRING" || second.type === "NUMBER" || second.type === "IDENT" || second.type === "KEYWORD");
227391
+ const third = cursor.peek(2);
227392
+ const isPropBlock = second && second.type === "ASSIGN" && third && third.type === "LBRACE";
227393
+ const isAttrBlock = first && (first.type === "IDENT" || first.type === "KEYWORD") && !CONTROL_FLOW.has(first.value) && (HTML_ATTRS_ONLY.has(first.value) || isPropBlock) && second && (second.type === "STRING" || second.type === "NUMBER" || second.type === "IDENT" || second.type === "KEYWORD" || second.type === "ASSIGN");
227395
227394
  if (isAttrBlock) {
227396
227395
  while (!cursor.done) {
227397
227396
  const t3 = cursor.peek();
@@ -227399,6 +227398,34 @@ function parseTWSelector(cursor, errors, state, parseBody) {
227399
227398
  if (t3.type === "IDENT" || t3.type === "KEYWORD") {
227400
227399
  const attrName = t3.value;
227401
227400
  cursor.advance();
227401
+ if (cursor.peek() && (cursor.peek().type === "ASSIGN" || cursor.peek().type === "EQUALS")) {
227402
+ cursor.advance();
227403
+ cursor.skipWhitespace();
227404
+ if (cursor.peek() && cursor.peek().type === "LBRACE") {
227405
+ cursor.advance();
227406
+ let expr = "";
227407
+ let depth = 1;
227408
+ let prevWS = false;
227409
+ while (!cursor.done) {
227410
+ const tk = cursor.peek();
227411
+ if (!tk || tk.type === "EOF") break;
227412
+ if (tk.type === "LBRACE") depth++;
227413
+ else if (tk.type === "RBRACE") {
227414
+ depth--;
227415
+ if (depth === 0) {
227416
+ cursor.advance();
227417
+ break;
227418
+ }
227419
+ }
227420
+ if (expr && prevWS) expr += " ";
227421
+ expr += tk.raw ?? tk.value;
227422
+ prevWS = !!tk.followedByWhitespace;
227423
+ cursor.advance();
227424
+ }
227425
+ el.attrs.push(createAttribute(attrName, expr.trim(), t3.pos.line, t3.pos.col, true));
227426
+ continue;
227427
+ }
227428
+ }
227402
227429
  const vToken = cursor.peek();
227403
227430
  if (vToken && (vToken.type === "STRING" || vToken.type === "NUMBER")) {
227404
227431
  cursor.advance();
@@ -236144,7 +236171,7 @@ var init_types4 = __esm({
236144
236171
  var TW_VERSION, TW_GENERATOR_META;
236145
236172
  var init_version = __esm({
236146
236173
  "../../packages/compiler/tw/codegen/version.ts"() {
236147
- TW_VERSION = "2.0.0";
236174
+ TW_VERSION = "2.0.2";
236148
236175
  TW_GENERATOR_META = `<meta name="generator" content="TW Framework ${TW_VERSION}">`;
236149
236176
  }
236150
236177
  });
@@ -236157,6 +236184,9 @@ function optimizedImageUrl(src, opts = {}) {
236157
236184
  if (opts.quality) p.set("q", String(opts.quality));
236158
236185
  p.set("f", opts.format ?? "auto");
236159
236186
  const qs = p.toString();
236187
+ if (/^https?:\/\//i.test(src)) {
236188
+ return `/_tw/img/_remote?src=${encodeURIComponent(src)}&${qs}`;
236189
+ }
236160
236190
  return `/_tw/img${src.startsWith("/") ? src : "/" + src}?${qs}`;
236161
236191
  }
236162
236192
  function imageAttributesFor(opts, config = DEFAULT_IMAGE_CONFIG) {
@@ -236164,7 +236194,7 @@ function imageAttributesFor(opts, config = DEFAULT_IMAGE_CONFIG) {
236164
236194
  const quality = opts.quality ?? config.quality;
236165
236195
  const format = config.formats[0] ?? "webp";
236166
236196
  const isRemote = /^https?:\/\//i.test(opts.src);
236167
- const src = isRemote ? `/_tw/img/_remote?src=${encodeURIComponent(opts.src)}&w=${opts.width ?? ""}&h=${opts.height ?? ""}&q=${quality}&f=auto` : optimizedImageUrl(opts.src, { width: opts.width, height: opts.height, quality });
236197
+ const src = isRemote ? `/_tw/img/_remote?src=${encodeURIComponent(opts.src)}${opts.width ? `&w=${opts.width}` : ""}${opts.height ? `&h=${opts.height}` : ""}&q=${quality}&f=auto` : optimizedImageUrl(opts.src, { width: opts.width, height: opts.height, quality });
236168
236198
  const widths = config.breakpoints.filter((bp) => width === 0 || bp <= width * 2);
236169
236199
  const srcset = widths.map(
236170
236200
  (bp) => isRemote ? `/_tw/img/_remote?src=${encodeURIComponent(opts.src)}&w=${bp}&q=${quality}&f=auto ${bp}w` : `${optimizedImageUrl(opts.src, { width: bp, quality })} ${bp}w`
@@ -236317,7 +236347,7 @@ function createImageHandler(options) {
236317
236347
  return { data: (0, import_node_fs5.readFileSync)(file), mtime: st.mtimeMs };
236318
236348
  }
236319
236349
  function cacheKey(src, w, h3, q, f, mtime) {
236320
- return (0, import_node_crypto3.createHash)("sha256").update(`${src}|${mtime}|${w}|${h3}|${q}|${f}`).digest("hex").slice(0, 32);
236350
+ return (0, import_node_crypto4.createHash)("sha256").update(`${src}|${mtime}|${w}|${h3}|${q}|${f}`).digest("hex").slice(0, 32);
236321
236351
  }
236322
236352
  async function processBuffer(data, w, h3, q, format) {
236323
236353
  const sharp = await loadSharp();
@@ -236344,7 +236374,7 @@ function createImageHandler(options) {
236344
236374
  }
236345
236375
  if (!warnedNoSharp) {
236346
236376
  warnedNoSharp = true;
236347
- console.warn(" [tw/image] sharp not installed \u2014 serving original images (bun add sharp to enable resizing/WebP/AVIF)");
236377
+ console.warn(" [tw/image] sharp not installed \u2014 using the built-in converter (WebP/AVIF); install sharp for faster resizing");
236348
236378
  }
236349
236379
  return { data, contentType: "", viaSharp: false };
236350
236380
  }
@@ -236428,10 +236458,10 @@ function createImageHandler(options) {
236428
236458
  }
236429
236459
  return { handle, sourceDir, cacheDir, config };
236430
236460
  }
236431
- var import_node_crypto3, import_node_fs5, import_node_path11, import_node_url, DEFAULT_IMAGE_CONFIG, IMAGE_EXTENSIONS, SHARP_FORMATS;
236461
+ var import_node_crypto4, import_node_fs5, import_node_path11, import_node_url, DEFAULT_IMAGE_CONFIG, IMAGE_EXTENSIONS, SHARP_FORMATS;
236432
236462
  var init_tw2 = __esm({
236433
236463
  "../../packages/image/tw/index.ts"() {
236434
- import_node_crypto3 = require("node:crypto");
236464
+ import_node_crypto4 = require("node:crypto");
236435
236465
  import_node_fs5 = require("node:fs");
236436
236466
  import_node_path11 = require("node:path");
236437
236467
  import_node_url = require("node:url");
@@ -236463,7 +236493,11 @@ var init_tw2 = __esm({
236463
236493
  });
236464
236494
 
236465
236495
  // ../../packages/link/tw/index.ts
236496
+ function isDangerousHref(href) {
236497
+ return DANGEROUS_SCHEME.test(href.replace(/[\u0000-\u0020]/g, ""));
236498
+ }
236466
236499
  function isExternalHref(href) {
236500
+ if (isDangerousHref(href)) return false;
236467
236501
  return /^[a-z][a-z0-9+.-]*:/i.test(href) || // any scheme: http(s), mailto, tel, ...
236468
236502
  href.startsWith("//");
236469
236503
  }
@@ -236472,7 +236506,8 @@ function isWebExternal(href) {
236472
236506
  return true;
236473
236507
  }
236474
236508
  function linkAttributesFor(opts) {
236475
- const href = (opts.href ?? "").trim();
236509
+ const rawHref = (opts.href ?? "").trim();
236510
+ const href = isDangerousHref(rawHref) ? "#" : rawHref;
236476
236511
  const external = opts.external === true || isExternalHref(href);
236477
236512
  const attrs = {};
236478
236513
  if (external) {
@@ -236501,8 +236536,10 @@ function linkAttributesFor(opts) {
236501
236536
  if (opts.id) attrs["id"] = opts.id;
236502
236537
  return { href, external, attrs };
236503
236538
  }
236539
+ var DANGEROUS_SCHEME;
236504
236540
  var init_tw3 = __esm({
236505
236541
  "../../packages/link/tw/index.ts"() {
236542
+ DANGEROUS_SCHEME = /^(javascript|data|vbscript):/i;
236506
236543
  }
236507
236544
  });
236508
236545
 
@@ -237015,12 +237052,31 @@ var init_interpolate = __esm({
237015
237052
  });
237016
237053
 
237017
237054
  // ../../packages/compiler/tw/eval/evaluate.ts
237055
+ function setEvalBindings(bindings) {
237056
+ extraBindings = bindings ?? {};
237057
+ }
237018
237058
  function evaluate(expr, vars, sandbox) {
237019
237059
  if (!expr) return "";
237020
237060
  const sb = sandbox ?? defaultSandbox;
237021
237061
  if (vars[expr] !== void 0) {
237022
237062
  return vars[expr];
237023
237063
  }
237064
+ if (expr.startsWith("(") && expr.endsWith(")")) {
237065
+ let d = 0;
237066
+ let wraps = true;
237067
+ for (let i = 0; i < expr.length; i++) {
237068
+ const ch = expr[i];
237069
+ if (ch === "(") d++;
237070
+ else if (ch === ")") {
237071
+ d--;
237072
+ if (d === 0 && i < expr.length - 1) {
237073
+ wraps = false;
237074
+ break;
237075
+ }
237076
+ }
237077
+ }
237078
+ if (wraps && d === 0) return evaluate(expr.slice(1, -1).trim(), vars, sb);
237079
+ }
237024
237080
  if (/^-?\d+(\.\d+)?$/.test(expr)) return expr;
237025
237081
  if (expr.startsWith('"') && expr.endsWith('"') || expr.startsWith("'") && expr.endsWith("'")) {
237026
237082
  return expr.slice(1, -1);
@@ -237028,11 +237084,54 @@ function evaluate(expr, vars, sandbox) {
237028
237084
  if (expr === "true") return "true";
237029
237085
  if (expr === "false") return "false";
237030
237086
  if (expr === "null" || expr === "undefined") return "";
237031
- const ternMatch = expr.match(/^(.+?)\s*\?\s*(.+?)\s*:\s*(.+)$/);
237032
- if (ternMatch) {
237033
- const cond = isTruthy(resolve2(ternMatch[1].trim(), vars, sb));
237034
- return cond ? resolve2(ternMatch[2].trim(), vars, sb) : resolve2(ternMatch[3].trim(), vars, sb);
237087
+ {
237088
+ let depth = 0;
237089
+ let pending2 = 0;
237090
+ let q = -1;
237091
+ let quote = "";
237092
+ for (let i = 0; i < expr.length; i++) {
237093
+ const ch = expr[i];
237094
+ if (quote) {
237095
+ if (ch === "\\") {
237096
+ i++;
237097
+ continue;
237098
+ }
237099
+ if (ch === quote) quote = "";
237100
+ continue;
237101
+ }
237102
+ if (ch === "'" || ch === '"' || ch === "`") {
237103
+ quote = ch;
237104
+ continue;
237105
+ }
237106
+ if (ch === "(" || ch === "[" || ch === "{") {
237107
+ depth++;
237108
+ continue;
237109
+ }
237110
+ if (ch === ")" || ch === "]" || ch === "}") {
237111
+ depth--;
237112
+ continue;
237113
+ }
237114
+ if (depth !== 0) continue;
237115
+ if (ch === "?") {
237116
+ if (pending2 === 0) q = i;
237117
+ pending2++;
237118
+ continue;
237119
+ }
237120
+ if (ch === ":" && pending2 > 0) {
237121
+ pending2--;
237122
+ if (pending2 > 0) continue;
237123
+ const cond = expr.slice(0, q).trim();
237124
+ const cons = expr.slice(q + 1, i).trim();
237125
+ const alt = expr.slice(i + 1).trim();
237126
+ if (cond && cons && alt) {
237127
+ return isTruthy(resolve2(cond, vars, sb)) ? resolve2(cons, vars, sb) : resolve2(alt, vars, sb);
237128
+ }
237129
+ break;
237130
+ }
237131
+ }
237035
237132
  }
237133
+ const dyn = evalWithVars(expr, vars);
237134
+ if (dyn !== null) return dyn;
237036
237135
  const orParts = splitLogical(expr, "||");
237037
237136
  if (orParts.length > 1) {
237038
237137
  for (const part of orParts) {
@@ -237109,7 +237208,7 @@ function evaluate(expr, vars, sandbox) {
237109
237208
  return current2 !== void 0 && current2 !== null ? String(current2) : "";
237110
237209
  }
237111
237210
  const fnMatch = expr.match(/^(\w+)\((.*)\)$/);
237112
- if (fnMatch) {
237211
+ if (fnMatch && isBuiltinName(fnMatch[1])) {
237113
237212
  const fn = fnMatch[1];
237114
237213
  const arg = resolve2(fnMatch[2].trim(), vars, sb);
237115
237214
  return callBuiltin(fn, arg, sb);
@@ -237128,6 +237227,38 @@ function evaluate(expr, vars, sandbox) {
237128
237227
  }
237129
237228
  return expr;
237130
237229
  }
237230
+ function evalWithVars(expr, vars) {
237231
+ if (!expr || /[`\\]/.test(expr)) return null;
237232
+ if (!/^[\w\s.$[\]{}()'"`,+\-*/%?:<>=!&|]*$/.test(expr)) return null;
237233
+ for (const m of expr.matchAll(/\.([A-Za-z_$][\w$]*)\s*\(/g)) {
237234
+ if (!SAFE_MEMBERS.has(m[1])) return null;
237235
+ }
237236
+ const names = [];
237237
+ const vals = [];
237238
+ for (const k of Object.keys(vars)) {
237239
+ if (!/^[A-Za-z_$][\w$]*$/.test(k)) continue;
237240
+ if (k in extraBindings) continue;
237241
+ names.push(k);
237242
+ try {
237243
+ vals.push(JSON.parse(vars[k]));
237244
+ } catch {
237245
+ vals.push(vars[k]);
237246
+ }
237247
+ }
237248
+ for (const k of Object.keys(extraBindings)) {
237249
+ if (!/^[A-Za-z_$][\w$]*$/.test(k)) continue;
237250
+ names.push(k);
237251
+ vals.push(extraBindings[k]);
237252
+ }
237253
+ try {
237254
+ const fn = new Function(...names, `"use strict"; return (${expr});`);
237255
+ const out = fn(...vals);
237256
+ if (out === void 0 || out === null) return null;
237257
+ return typeof out === "object" ? JSON.stringify(out) : String(out);
237258
+ } catch {
237259
+ return null;
237260
+ }
237261
+ }
237131
237262
  function resolve2(token, vars, sandbox) {
237132
237263
  const trimmed = token.trim();
237133
237264
  if (!trimmed) return "";
@@ -237296,7 +237427,7 @@ function coerce(value, targetType) {
237296
237427
  return value;
237297
237428
  }
237298
237429
  }
237299
- var defaultSandbox;
237430
+ var defaultSandbox, extraBindings, SAFE_MEMBERS;
237300
237431
  var init_evaluate = __esm({
237301
237432
  "../../packages/compiler/tw/eval/evaluate.ts"() {
237302
237433
  init_sandbox();
@@ -237304,6 +237435,64 @@ var init_evaluate = __esm({
237304
237435
  init_builtins();
237305
237436
  init_interpolate();
237306
237437
  defaultSandbox = new Sandbox();
237438
+ extraBindings = {};
237439
+ SAFE_MEMBERS = /* @__PURE__ */ new Set([
237440
+ "length",
237441
+ "toUpperCase",
237442
+ "toLowerCase",
237443
+ "trim",
237444
+ "trimStart",
237445
+ "trimEnd",
237446
+ "slice",
237447
+ "substring",
237448
+ "substr",
237449
+ "charAt",
237450
+ "at",
237451
+ "includes",
237452
+ "indexOf",
237453
+ "lastIndexOf",
237454
+ "startsWith",
237455
+ "endsWith",
237456
+ "replace",
237457
+ "replaceAll",
237458
+ "split",
237459
+ "join",
237460
+ "concat",
237461
+ "repeat",
237462
+ "padStart",
237463
+ "padEnd",
237464
+ "toString",
237465
+ "toFixed",
237466
+ "map",
237467
+ "filter",
237468
+ "find",
237469
+ "some",
237470
+ "every",
237471
+ "reduce",
237472
+ "sort",
237473
+ "reverse",
237474
+ // Static helpers on the built-ins (JSON.stringify, Object.keys, Math.round).
237475
+ "stringify",
237476
+ "parse",
237477
+ "keys",
237478
+ "values",
237479
+ "entries",
237480
+ "from",
237481
+ "isArray",
237482
+ "isInteger",
237483
+ "isFinite",
237484
+ "abs",
237485
+ "ceil",
237486
+ "floor",
237487
+ "round",
237488
+ "max",
237489
+ "min",
237490
+ "pow",
237491
+ "sqrt",
237492
+ "random",
237493
+ "now",
237494
+ "toISOString"
237495
+ ]);
237307
237496
  }
237308
237497
  });
237309
237498
 
@@ -237458,9 +237647,78 @@ function callBuiltin(fn, arg, sandbox) {
237458
237647
  function applyFilter(value, filter, args, vars, sandbox) {
237459
237648
  return callBuiltin(filter, value, sandbox);
237460
237649
  }
237650
+ function isBuiltinName(fn) {
237651
+ return BUILTIN_NAMES.has(fn);
237652
+ }
237653
+ var BUILTIN_NAMES;
237461
237654
  var init_builtins = __esm({
237462
237655
  "../../packages/compiler/tw/eval/builtins.ts"() {
237463
237656
  init_evaluate();
237657
+ BUILTIN_NAMES = /* @__PURE__ */ new Set([
237658
+ "Boolean",
237659
+ "Number",
237660
+ "String",
237661
+ "abs",
237662
+ "base64decode",
237663
+ "base64encode",
237664
+ "bool",
237665
+ "camelCase",
237666
+ "capitalize",
237667
+ "ceil",
237668
+ "cos",
237669
+ "date",
237670
+ "decodeURI",
237671
+ "encodeURI",
237672
+ "endsWith",
237673
+ "exp",
237674
+ "first",
237675
+ "float",
237676
+ "floor",
237677
+ "includes",
237678
+ "indexOf",
237679
+ "int",
237680
+ "join",
237681
+ "json",
237682
+ "kebabCase",
237683
+ "last",
237684
+ "len",
237685
+ "length",
237686
+ "log",
237687
+ "lower",
237688
+ "lowercase",
237689
+ "match",
237690
+ "max",
237691
+ "min",
237692
+ "now",
237693
+ "num",
237694
+ "padEnd",
237695
+ "padStart",
237696
+ "parseFloat",
237697
+ "parseInt",
237698
+ "parseJSON",
237699
+ "pow",
237700
+ "random",
237701
+ "repeat",
237702
+ "replace",
237703
+ "reverse",
237704
+ "round",
237705
+ "sin",
237706
+ "size",
237707
+ "slice",
237708
+ "snakeCase",
237709
+ "split",
237710
+ "sqrt",
237711
+ "startsWith",
237712
+ "str",
237713
+ "stringify",
237714
+ "tan",
237715
+ "test",
237716
+ "time",
237717
+ "title",
237718
+ "trim",
237719
+ "upper",
237720
+ "uppercase"
237721
+ ]);
237464
237722
  }
237465
237723
  });
237466
237724
 
@@ -238507,16 +238765,61 @@ function addScope(css, scopeId) {
238507
238765
  out += prelude;
238508
238766
  return out;
238509
238767
  }
238510
- function interpolate2(expr, vars) {
238511
- const masked = expr.replace(/\\\{/g, "O").replace(/\\\}/g, "C");
238512
- const out = masked.replace(/\{([^}]+)\}/g, (_, name) => {
238513
- const key2 = name.trim();
238768
+ function interpolateBraces(input, vars) {
238769
+ let out = "";
238770
+ let i = 0;
238771
+ while (i < input.length) {
238772
+ const ch = input[i];
238773
+ if (ch !== "{") {
238774
+ out += ch;
238775
+ i++;
238776
+ continue;
238777
+ }
238778
+ let depth = 1;
238779
+ let j = i + 1;
238780
+ let quote = "";
238781
+ while (j < input.length && depth > 0) {
238782
+ const c = input[j];
238783
+ if (quote) {
238784
+ if (c === "\\") {
238785
+ j += 2;
238786
+ continue;
238787
+ }
238788
+ if (c === quote) quote = "";
238789
+ j++;
238790
+ continue;
238791
+ }
238792
+ if (c === "'" || c === '"' || c === "`") {
238793
+ quote = c;
238794
+ j++;
238795
+ continue;
238796
+ }
238797
+ if (c === "{") depth++;
238798
+ else if (c === "}") {
238799
+ depth--;
238800
+ if (depth === 0) break;
238801
+ }
238802
+ j++;
238803
+ }
238804
+ if (depth !== 0) {
238805
+ out += ch;
238806
+ i++;
238807
+ continue;
238808
+ }
238809
+ const key2 = input.slice(i + 1, j).trim();
238514
238810
  if (/^[a-zA-Z_$][\w$]*$/.test(key2)) {
238515
- return vars[key2] ?? "";
238811
+ out += vars[key2] ?? "";
238812
+ } else {
238813
+ const val = evaluate(key2, vars);
238814
+ out += val === null ? "" : val;
238516
238815
  }
238517
- const val = evaluate(key2, vars);
238518
- return val === null ? "" : val;
238519
- });
238816
+ i = j + 1;
238817
+ }
238818
+ return out;
238819
+ }
238820
+ function interpolate2(expr, vars) {
238821
+ const masked = expr.replace(/\\\{/g, "O").replace(/\\\}/g, "C");
238822
+ const out = interpolateBraces(masked, vars);
238520
238823
  return out.replace(/\u0001O/g, "{").replace(/\u0001C/g, "}");
238521
238824
  }
238522
238825
  function isTruthy2(val) {
@@ -238953,6 +239256,11 @@ function generateElement(el, ctx) {
238953
239256
  }
238954
239257
  function renderAttrs(el, ctx) {
238955
239258
  const parts = [];
239259
+ const classAttrs = el.attrs.filter((a) => a.name === "class" && !a.isInterpolated && typeof a.value === "string");
239260
+ if (classAttrs.length > 1) {
239261
+ const merged = classAttrs.map((a) => String(a.value).trim()).filter(Boolean).join(" ");
239262
+ el = { ...el, attrs: el.attrs.filter((a) => a.name !== "class").concat([{ ...classAttrs[0], value: merged }]) };
239263
+ }
238956
239264
  for (let attr of el.attrs) {
238957
239265
  if (attr.name === "class" && typeof attr.value === "string" && !attr.isInterpolated) {
238958
239266
  const scoped = ctx.scopedClasses;
@@ -238995,7 +239303,21 @@ function renderBindings(bindings, ctx) {
238995
239303
  if (bindings.length === 0) return "";
238996
239304
  const parts = [];
238997
239305
  for (const binding of bindings) {
238998
- parts.push(`data-tw-bind-${binding.property}="${escapeAttr3(String(binding.expression ?? ""))}"`);
239306
+ const expr = String(binding.expression ?? "");
239307
+ let initial = "";
239308
+ try {
239309
+ if (/^[A-Za-z_$][\w$]*$/.test(expr)) {
239310
+ const v = ctx.stateVars[expr];
239311
+ if (v !== void 0 && v !== null) initial = String(v);
239312
+ } else if (expr) {
239313
+ initial = interpolate2("{" + expr + "}", ctx.stateVars);
239314
+ }
239315
+ } catch {
239316
+ }
239317
+ if (initial && !/[{}]/.test(initial)) {
239318
+ parts.push(`${binding.property}="${escapeAttr3(initial)}"`);
239319
+ }
239320
+ parts.push(`data-tw-bind-${binding.property}="${escapeAttr3(expr)}"`);
238999
239321
  }
239000
239322
  return parts.join(" ");
239001
239323
  }
@@ -239110,8 +239432,13 @@ function generateComponent(comp, ctx) {
239110
239432
  const savedStateVars = { ...ctx.stateVars };
239111
239433
  for (const prop of comp.props) {
239112
239434
  if (typeof prop.value === "string") {
239113
- const resolved = interpolate2(prop.value, ctx.stateVars);
239114
- ctx.stateVars[prop.name] = resolved;
239435
+ const raw = String(prop.value);
239436
+ const head = raw.split(/[.[]/)[0];
239437
+ if (!/[{}]/.test(raw) && Object.prototype.hasOwnProperty.call(ctx.stateVars, head)) {
239438
+ ctx.stateVars[prop.name] = interpolate2("{" + raw + "}", ctx.stateVars);
239439
+ } else {
239440
+ ctx.stateVars[prop.name] = interpolate2(raw, ctx.stateVars);
239441
+ }
239115
239442
  }
239116
239443
  }
239117
239444
  const componentProgram = componentRegistry.get(comp.name);
@@ -239205,6 +239532,14 @@ function generateFor(node, ctx) {
239205
239532
  }
239206
239533
  }
239207
239534
  }
239535
+ if (items.length === 0 && !/^\s*\[/.test(iterableStr)) {
239536
+ try {
239537
+ const evaluated = evaluate(String(node.iterable ?? "").replace(/^\{/, "").replace(/\}$/, "").trim(), ctx.stateVars);
239538
+ const parsed = JSON.parse(evaluated);
239539
+ if (Array.isArray(parsed)) items = parsed;
239540
+ } catch {
239541
+ }
239542
+ }
239208
239543
  for (let i = 0; i < items.length; i++) {
239209
239544
  const childCtx = { ...ctx };
239210
239545
  childCtx.stateVars = { ...ctx.stateVars };
@@ -239225,7 +239560,7 @@ function generateFor(node, ctx) {
239225
239560
  tplSource = node.body.map((c) => generateNode(c, childCtx)).join("");
239226
239561
  }
239227
239562
  const listExpr = String(node.iterable ?? "").replace(/^\{/, "").replace(/\}$/, "");
239228
- const tpl = tplSource.replace(/"/g, "&#34;");
239563
+ const tpl = tplSource.replace(/&/g, "&amp;").replace(/"/g, "&#34;");
239229
239564
  return `<tw-for data-tw-var="${node.varName}"${node.indexName ? ` data-tw-index="${node.indexName}"` : ""} data-tw-list="${listExpr}" data-tw-tpl="${tpl}">${html}</tw-for>`;
239230
239565
  }
239231
239566
  return html;
@@ -243013,16 +243348,22 @@ function generateWithLayoutChain(layoutPrograms, pageProgram, stateVars) {
243013
243348
  }
243014
243349
  };
243015
243350
  let pageTitle = "TW Page";
243351
+ let pageDescription = "";
243016
243352
  for (const dir of pageProgram.directives || []) {
243017
- if (dir.type === "PageDirective" && dir.key === "title") {
243018
- const t3 = dir.value;
243019
- if (t3 != null && String(t3) !== "") pageTitle = String(t3);
243353
+ if (dir.type === "PageDirective") {
243354
+ if (dir.key === "title") {
243355
+ const t3 = dir.value;
243356
+ if (t3 != null && String(t3) !== "") pageTitle = String(t3);
243357
+ } else if (dir.key === "description") {
243358
+ const d = dir.value;
243359
+ if (d != null) pageDescription = String(d);
243360
+ }
243020
243361
  }
243021
243362
  }
243022
243363
  const pageCtx = createContext("ssr");
243023
243364
  seedCtx(pageCtx);
243024
243365
  try {
243025
- pageCtx.stateVars["page"] = JSON.stringify({ title: pageTitle });
243366
+ pageCtx.stateVars["page"] = JSON.stringify({ title: pageTitle, description: pageDescription });
243026
243367
  } catch {
243027
243368
  }
243028
243369
  {
@@ -243178,6 +243519,10 @@ function generate(program, stateVars, genOpts2) {
243178
243519
  const startTime = performance.now();
243179
243520
  const ctx = createContext("ssr");
243180
243521
  if (stateVars) ctx.stateVars = stateVars;
243522
+ if (genOpts2?.imports) {
243523
+ ctx.imports = genOpts2.imports;
243524
+ setEvalBindings(genOpts2.imports);
243525
+ } else setEvalBindings({});
243181
243526
  if (genOpts2 && genOpts2.scopedStyles === false) ctx.scopedStyles = false;
243182
243527
  if (genOpts2?.scopeId) ctx.scopeId = genOpts2.scopeId;
243183
243528
  if (genOpts2?.cssPrefix) ctx.cssPrefix = genOpts2.cssPrefix;
@@ -243262,6 +243607,7 @@ var init_vdom = __esm({
243262
243607
  init_types4();
243263
243608
  init_html2();
243264
243609
  init_builtin_components();
243610
+ init_evaluate();
243265
243611
  }
243266
243612
  });
243267
243613
 
@@ -243603,6 +243949,7 @@ var init_codes = __esm({
243603
243949
  TW095: { message: "Invalid for-loop iterable -- use {varName} or a valid comma-separated literal", severity: "error", category: "syntax" },
243604
243950
  TW096: { message: "Unknown state variable in interpolation (renders empty)", severity: "warning", category: "semantic" },
243605
243951
  TW097: { message: "while with a comparison renders its body ONCE at build time (state cannot mutate during SSR) -- use for loops for repetition", severity: "warning", category: "semantic" },
243952
+ TW098: { message: "Interpolation cannot be evaluated at build time -- it renders as its source text", severity: "warning", category: "semantic" },
243606
243953
  // Server blocks (TW099-TW101)
243607
243954
  TW099: { message: "Unknown server modifier (only ':defer' is supported)", severity: "error", category: "syntax" },
243608
243955
  TW100: { message: "Expected '{' after 'server'", severity: "error", category: "syntax" },
@@ -243626,6 +243973,8 @@ var init_codes = __esm({
243626
243973
  TW117: { message: "fetch() with a request-derived URL (SSRF lint)", severity: "warning", category: "semantic" },
243627
243974
  TW118: { message: "A deferred server block cannot redirect() or notFound() -- the response has already begun", severity: "error", category: "semantic" },
243628
243975
  TW119: { message: "A deferred server block cannot be used on a cached page -- cache { } serves one HTML to every request", severity: "error", category: "semantic" },
243976
+ TW121: { message: "The same name is declared by more than one state { } block (the earlier one wins)", severity: "warning", category: "semantic" },
243977
+ TW122: { message: "More than one default slot in the same component -- a caller's default content has no defined destination", severity: "warning", category: "semantic" },
243629
243978
  // Codes thrown outside the rule engine. TW303 comes from the stylesheet
243630
243979
  // parser (codegen/tss.ts); TW000 is the generic fallback used when an error
243631
243980
  // carries no code of its own.
@@ -243690,6 +244039,7 @@ function checkUnknownTags(program, filePath, diags) {
243690
244039
  forEachNode(program, (node, ctx) => {
243691
244040
  if (!isElement(node)) return;
243692
244041
  if (node.tag[0] === node.tag[0]?.toUpperCase()) return;
244042
+ if (BUILTIN_COMPONENT_TAGS.has(node.tag)) return;
243693
244043
  const parent = ctx?.parent;
243694
244044
  if (parent && (parent.type === "Element" && typeof parent.tag === "string" && parent.tag[0] === parent.tag[0]?.toUpperCase() || parent.type === "Component")) return;
243695
244045
  if (HTML_ELEMENTS2.has(node.tag.toLowerCase())) return;
@@ -244018,6 +244368,14 @@ function checkUnknownStateVars(program, filePath, diags) {
244018
244368
  if (d && d.type === "ServerBlock" && Array.isArray(d.declaredNames)) {
244019
244369
  for (const n of d.declaredNames) known.add(n);
244020
244370
  }
244371
+ if (d && d.type === "ImportDirective" && !d.isTypeOnly) {
244372
+ if (d.defaultImport) known.add(String(d.defaultImport));
244373
+ if (d.namespaceImport) known.add(String(d.namespaceImport));
244374
+ for (const it of d.items ?? []) {
244375
+ const nm = String(it).split(/\s+as\s+/).pop()?.trim();
244376
+ if (nm) known.add(nm);
244377
+ }
244378
+ }
244021
244379
  }
244022
244380
  const texts = [];
244023
244381
  forEachNode(program, (node) => {
@@ -244044,6 +244402,59 @@ function checkUnknownStateVars(program, filePath, diags) {
244044
244402
  "null",
244045
244403
  "undefined"
244046
244404
  ]);
244405
+ const EVALUABLE_METHODS = /* @__PURE__ */ new Set([
244406
+ "length",
244407
+ "toUpperCase",
244408
+ "toLowerCase",
244409
+ "trim",
244410
+ "trimStart",
244411
+ "trimEnd",
244412
+ "slice",
244413
+ "substring",
244414
+ "substr",
244415
+ "charAt",
244416
+ "at",
244417
+ "includes",
244418
+ "indexOf",
244419
+ "lastIndexOf",
244420
+ "startsWith",
244421
+ "endsWith",
244422
+ "replace",
244423
+ "replaceAll",
244424
+ "split",
244425
+ "join",
244426
+ "concat",
244427
+ "repeat",
244428
+ "padStart",
244429
+ "padEnd",
244430
+ "toString",
244431
+ "toFixed",
244432
+ "map",
244433
+ "filter",
244434
+ "find",
244435
+ "some",
244436
+ "every",
244437
+ "reduce",
244438
+ "sort",
244439
+ "reverse",
244440
+ "stringify",
244441
+ "parse",
244442
+ "keys",
244443
+ "values",
244444
+ "entries",
244445
+ "from",
244446
+ "isArray",
244447
+ "round",
244448
+ "floor",
244449
+ "ceil",
244450
+ "abs",
244451
+ "max",
244452
+ "min",
244453
+ "pow",
244454
+ "sqrt",
244455
+ "random",
244456
+ "now"
244457
+ ]);
244047
244458
  for (const node of texts) {
244048
244459
  const text = String(node.value ?? "");
244049
244460
  if (!text.includes("{")) continue;
@@ -244059,6 +244470,22 @@ function checkUnknownStateVars(program, filePath, diags) {
244059
244470
  [`Declare it in the state block, or check the spelling`]
244060
244471
  ));
244061
244472
  }
244473
+ for (const m of text.matchAll(/\{([^{}]+)\}/g)) {
244474
+ const expr = m[1].trim();
244475
+ if (/^[A-Za-z_$][\w$]*$/.test(expr)) continue;
244476
+ for (const c of expr.matchAll(/([A-Za-z_$][\w$]*)\s*\(/g)) {
244477
+ const fn = c[1];
244478
+ if (known.has(fn) || BUILTINS2.has(fn) || EVALUABLE_METHODS.has(fn)) continue;
244479
+ diags.push(createDiagnostic(
244480
+ "TW098",
244481
+ node.line,
244482
+ node.col,
244483
+ filePath,
244484
+ `{${expr}}`,
244485
+ [`Cannot evaluate this at build time -- it renders as its source. Check the name, or simplify the expression`]
244486
+ ));
244487
+ }
244488
+ }
244062
244489
  }
244063
244490
  }
244064
244491
  function checkWhileComparisons(program, filePath, diags) {
@@ -244091,7 +244518,28 @@ function checkDeprecatedImports(program, filePath, diags) {
244091
244518
  }
244092
244519
  }
244093
244520
  }
244094
- var HTML_ELEMENTS2, HTML_ATTRIBUTES2, GLOBAL_ATTRIBUTES2, CSS_PROPERTIES2, CSS_ALIASES2, EVENT_TYPES2, ARIA_ROLES2, ARIA_ATTRIBUTES2, DEPRECATED_IMPORTS;
244521
+ function checkDuplicateDefaultSlots(program, filePath, diags) {
244522
+ let count = 0;
244523
+ let first = null;
244524
+ forEachNode(program, (node) => {
244525
+ if (!node || node.type !== "Slot") return;
244526
+ const name = String(node.name ?? "default");
244527
+ if (name !== "default") return;
244528
+ count++;
244529
+ if (!first) first = node;
244530
+ });
244531
+ if (count > 1 && first) {
244532
+ diags.push(createDiagnostic(
244533
+ "TW122",
244534
+ first.line ?? 1,
244535
+ first.col ?? 1,
244536
+ filePath,
244537
+ `${count} default slots`,
244538
+ ["Keep one default slot -- a caller's default content has no defined destination with two"]
244539
+ ));
244540
+ }
244541
+ }
244542
+ var HTML_ELEMENTS2, HTML_ATTRIBUTES2, GLOBAL_ATTRIBUTES2, CSS_PROPERTIES2, CSS_ALIASES2, EVENT_TYPES2, ARIA_ROLES2, ARIA_ATTRIBUTES2, BUILTIN_COMPONENT_TAGS, DEPRECATED_IMPORTS;
244095
244543
  var init_rules = __esm({
244096
244544
  "../../packages/compiler/tw/diagnostics/rules.ts"() {
244097
244545
  init_visitors();
@@ -244955,6 +245403,7 @@ var init_rules = __esm({
244955
245403
  "aria-valuenow",
244956
245404
  "aria-valuetext"
244957
245405
  ]);
245406
+ BUILTIN_COMPONENT_TAGS = /* @__PURE__ */ new Set(["optImage", "twImage", "twLink", "twImg"]);
244958
245407
  DEPRECATED_IMPORTS = [
244959
245408
  { source: "utils/string/transform", name: "toHex", replacement: "stringToHex", removal: "2.1.0" },
244960
245409
  { source: "utils/string/transform", name: "fromHex", replacement: "hexToString", removal: "2.1.0" },
@@ -244998,6 +245447,7 @@ function diagnose(program, filePath) {
244998
245447
  checkLoopIterables(program, filePath, diagnostics);
244999
245448
  checkUnknownStateVars(program, filePath, diagnostics);
245000
245449
  checkWhileComparisons(program, filePath, diagnostics);
245450
+ checkDuplicateDefaultSlots(program, filePath, diagnostics);
245001
245451
  return diagnostics;
245002
245452
  }
245003
245453
  var RuleEngine;
@@ -247354,6 +247804,28 @@ function lintSsrf(body) {
247354
247804
  while (m = re.exec(body)) out.push("fetch(<dynamic url>)");
247355
247805
  const concat = /fetch\s*\(\s*[^,)]*\b(params|query|headers|cookies)\b[^,)]*\+/g;
247356
247806
  while (m = concat.exec(body)) out.push("fetch(<concatenated url>)");
247807
+ const TAINTED_ROOT = /\b(params|query|headers|cookies)\b/;
247808
+ const tainted = /* @__PURE__ */ new Set();
247809
+ for (let pass = 0; pass < 5; pass++) {
247810
+ let grew = false;
247811
+ const assign = /(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*([^;\n]+)/g;
247812
+ let a;
247813
+ while (a = assign.exec(body)) {
247814
+ const [, name, rhs] = a;
247815
+ if (tainted.has(name)) continue;
247816
+ const fromRoot = TAINTED_ROOT.test(rhs);
247817
+ const fromTainted = [...tainted].some((t3) => new RegExp("\\b" + t3 + "\\b").test(rhs));
247818
+ if (fromRoot || fromTainted) {
247819
+ tainted.add(name);
247820
+ grew = true;
247821
+ }
247822
+ }
247823
+ if (!grew) break;
247824
+ }
247825
+ for (const name of tainted) {
247826
+ const use = new RegExp("fetch\\s*\\(\\s*[^,)]*\\b" + name + "\\b[^,)]*[,)]", "g");
247827
+ if (use.test(body)) out.push("fetch(<request-derived url>)");
247828
+ }
247357
247829
  return out;
247358
247830
  }
247359
247831
  var ts2, ServerSerializationError, MAX_DEPTH;
@@ -247457,6 +247929,36 @@ function serverStateCollisions(program) {
247457
247929
  }
247458
247930
  return out;
247459
247931
  }
247932
+ function checkDeclarationConflicts(program, paramNames = []) {
247933
+ const out = [];
247934
+ const params = new Set(paramNames);
247935
+ const seen = /* @__PURE__ */ new Set();
247936
+ for (const d of program.directives ?? []) {
247937
+ if (d.type !== "StateDirective") continue;
247938
+ for (const decl of d.declarations ?? []) {
247939
+ const name = String(decl.name ?? "");
247940
+ if (!name) continue;
247941
+ if (params.has(name)) {
247942
+ out.push({
247943
+ code: "TW102",
247944
+ message: `state declares '${name}', which collides with the route param '${name}' -- the param overwrites the state value`,
247945
+ line: decl.line ?? d.line ?? 1,
247946
+ col: decl.col ?? d.col ?? 1
247947
+ });
247948
+ }
247949
+ if (seen.has(name)) {
247950
+ out.push({
247951
+ code: "TW121",
247952
+ message: `'${name}' is declared by more than one state { } block -- the earlier declaration wins and this one is dead`,
247953
+ line: decl.line ?? d.line ?? 1,
247954
+ col: decl.col ?? d.col ?? 1
247955
+ });
247956
+ }
247957
+ seen.add(name);
247958
+ }
247959
+ }
247960
+ return out;
247961
+ }
247460
247962
  function serverRouteParamCollisions(blocks, paramNames) {
247461
247963
  const params = new Set(paramNames);
247462
247964
  const out = [];
@@ -247694,7 +248196,14 @@ function checkServerBlocks(program, opts = {}) {
247694
248196
  const blocks = collectServerBlocks(program);
247695
248197
  if (!blocks.length) return [];
247696
248198
  const out = [];
247697
- const push = (code, message, line, col) => out.push({ severity: "error", code, message, line, col, category: "semantic" });
248199
+ const push = (code, message, line, col) => out.push({
248200
+ severity: ERROR_CODES[code]?.severity === "warning" ? "warning" : "error",
248201
+ code,
248202
+ message,
248203
+ line,
248204
+ col,
248205
+ category: "semantic"
248206
+ });
247698
248207
  if (opts.isLayout) {
247699
248208
  for (const b of blocks) push("TW105", "server blocks in layouts are not supported yet", b.line, b.col);
247700
248209
  return out;
@@ -247872,6 +248381,7 @@ function parsePageCache(source) {
247872
248381
  var ts3, REQUEST_IDENTIFIERS, SERVER_REDIRECT_BRAND, SERVER_NOT_FOUND_BRAND, ServerRedirect, ServerNotFound, isServerRedirect, isServerNotFound, DEFAULT_SERVER_BLOCK_TIMEOUT_MS;
247873
248382
  var init_server_blocks = __esm({
247874
248383
  "../../packages/compiler/tw/server-blocks/index.ts"() {
248384
+ init_codes();
247875
248385
  init_serialize();
247876
248386
  ts3 = __toESM(require_typescript(), 1);
247877
248387
  REQUEST_IDENTIFIERS = /* @__PURE__ */ new Set(["headers", "cookies", "query", "params"]);
@@ -254592,6 +255102,7 @@ __export(tw_exports2, {
254592
255102
  canonicalVaryQuery: () => canonicalVaryQuery,
254593
255103
  charCode: () => charCode,
254594
255104
  check: () => check,
255105
+ checkDeclarationConflicts: () => checkDeclarationConflicts,
254595
255106
  checkServerBlocks: () => checkServerBlocks,
254596
255107
  chunksToHTML: () => chunksToHTML,
254597
255108
  clearComponentRegistry: () => clearComponentRegistry,
@@ -255268,7 +255779,8 @@ function genOpts(opts, scopeId) {
255268
255779
  scopedStyles: opts?.compiler?.scopedStyles,
255269
255780
  scopeId,
255270
255781
  cssPrefix: opts?.cssPrefix,
255271
- cssImportPaths: opts?.cssImportPaths
255782
+ cssImportPaths: opts?.cssImportPaths,
255783
+ imports: opts?.imports
255272
255784
  };
255273
255785
  }
255274
255786
  function scopeIdFor(filePath) {
@@ -256007,14 +256519,14 @@ function verifyJwt_hs256(token, secret) {
256007
256519
  return false;
256008
256520
  }
256009
256521
  if (header?.alg !== "HS256") return false;
256010
- const expected = (0, import_node_crypto4.createHmac)("sha256", secret).update(`${h3}.${p}`).digest();
256522
+ const expected = (0, import_node_crypto5.createHmac)("sha256", secret).update(`${h3}.${p}`).digest();
256011
256523
  let got;
256012
256524
  try {
256013
256525
  got = b64urlDecode(sig);
256014
256526
  } catch {
256015
256527
  return false;
256016
256528
  }
256017
- if (expected.length !== got.length || !(0, import_node_crypto4.timingSafeEqual)(expected, got)) return false;
256529
+ if (expected.length !== got.length || !(0, import_node_crypto5.timingSafeEqual)(expected, got)) return false;
256018
256530
  if (typeof payload?.exp === "number" && payload.exp * 1e3 < Date.now()) return false;
256019
256531
  return true;
256020
256532
  }
@@ -256185,11 +256697,11 @@ function evaluateRules(rules, request) {
256185
256697
  }
256186
256698
  return null;
256187
256699
  }
256188
- var import_node_crypto4, Parser, rateBuckets, RATE_BUCKETS_MAX;
256700
+ var import_node_crypto5, Parser, rateBuckets, RATE_BUCKETS_MAX;
256189
256701
  var init_twm_rules = __esm({
256190
256702
  "../../packages/server/tw/routing/twm-rules.ts"() {
256191
256703
  init_tw();
256192
- import_node_crypto4 = require("node:crypto");
256704
+ import_node_crypto5 = require("node:crypto");
256193
256705
  Parser = class {
256194
256706
  constructor(toks, file) {
256195
256707
  this.toks = toks;
@@ -256700,6 +257212,18 @@ function findGlobalError(rootNode2) {
256700
257212
  function findRootError(rootNode2) {
256701
257213
  return (rootNode2.files || []).find((f) => f.type === "error");
256702
257214
  }
257215
+ function findNearestNotFound(rootNode2, pathParts) {
257216
+ let found = (rootNode2.files || []).find((f) => f.type === "not-found");
257217
+ let node = rootNode2;
257218
+ for (const part of pathParts) {
257219
+ const child = (node.children || []).find((c) => c.segment === part);
257220
+ if (!child) break;
257221
+ const f = (child.files || []).find((x) => x.type === "not-found");
257222
+ if (f) found = f;
257223
+ node = child;
257224
+ }
257225
+ return found;
257226
+ }
256703
257227
  function findRootNotFound(rootNode2) {
256704
257228
  return rootNode2.files.find((f) => f.type === "not-found");
256705
257229
  }
@@ -257502,6 +258026,26 @@ var init_render_pipeline = __esm({
257502
258026
  };
257503
258027
  }
257504
258028
  console.error(`[tw] server block failed for ${pageFile}: ${err2?.message ?? err2}`);
258029
+ try {
258030
+ const errFile = ctx.error ?? findRootError(tree);
258031
+ if (errFile) {
258032
+ const compiled = this.compileFile(errFile);
258033
+ let eh = String(compiled.html || "");
258034
+ const em = eh.match(/<body[^>]*>([\s\S]*)<\/body>/i);
258035
+ eh = (em ? em[1] : eh).replace(/<\/?html[^>]*>/gi, "").replace(/<\/?body[^>]*>/gi, "");
258036
+ return {
258037
+ html: this.assembleHTML(eh, compiled.css, "", "Error"),
258038
+ css: "",
258039
+ js: "",
258040
+ status: 500,
258041
+ headers: { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "private, no-store" },
258042
+ fromCache: false,
258043
+ durationMs: 0,
258044
+ serverBlocks: true
258045
+ };
258046
+ }
258047
+ } catch {
258048
+ }
257505
258049
  return {
257506
258050
  html: "<!DOCTYPE html><html><head><title>Server Error</title></head><body><h1>Internal Server Error</h1></body></html>",
257507
258051
  css: "",
@@ -257567,7 +258111,7 @@ var init_render_pipeline = __esm({
257567
258111
  }
257568
258112
  const match = matchRoute(tree, pathname);
257569
258113
  if (!match) {
257570
- const rootNotFound = findRootNotFound(tree);
258114
+ const rootNotFound = findNearestNotFound(tree, pathname.split("/").filter(Boolean));
257571
258115
  if (rootNotFound) {
257572
258116
  const compiled = this.compileFile(rootNotFound);
257573
258117
  let nf = String(compiled.html || "");
@@ -257633,6 +258177,7 @@ var init_render_pipeline = __esm({
257633
258177
  }
257634
258178
  let bodyHTML = pageCompiled.html;
257635
258179
  let allCSS = pageCompiled.css;
258180
+ const parallelSlots = [];
257636
258181
  try {
257637
258182
  const parentNode = match?.node;
257638
258183
  if (parentNode && Array.isArray(parentNode.children)) {
@@ -257643,9 +258188,7 @@ var init_render_pipeline = __esm({
257643
258188
  const sbm = slotBody.match(/<body[^>]*>([\s\S]*)<\/body>/i);
257644
258189
  if (sbm) slotBody = sbm[1];
257645
258190
  slotBody = slotBody.replace(/<\/?html[^>]*>/gi, "").replace(/<\/?body[^>]*>/gi, "");
257646
- const comp = slotName.charAt(0).toUpperCase() + slotName.slice(1);
257647
- const slotRe = new RegExp(`<${comp}(s[^>]*)?>([sS]*?)</${comp}>|<${comp}(s[^>]*)?/>`, "gi");
257648
- bodyHTML = bodyHTML.replace(slotRe, slotBody);
258191
+ parallelSlots.push({ comp: slotName.charAt(0).toUpperCase() + slotName.slice(1), body: slotBody });
257649
258192
  if (slotCompiled.css) allCSS = slotCompiled.css + "\n" + allCSS;
257650
258193
  }
257651
258194
  }
@@ -257664,6 +258207,11 @@ var init_render_pipeline = __esm({
257664
258207
  allJS = templateCompiled.js + "\n" + allJS;
257665
258208
  bodyHTML = this.wrapInLayout(templateCompiled.html, bodyHTML);
257666
258209
  }
258210
+ for (const { comp, body } of parallelSlots) {
258211
+ const slotRe = new RegExp(`<${comp}(\\s[^>]*)?>([\\s\\S]*?)<\\/${comp}>|<${comp}(\\s[^>]*)?/>`, "gi");
258212
+ bodyHTML = bodyHTML.replace(slotRe, body);
258213
+ bodyHTML = bodyHTML.replace(new RegExp(`<!--\\s*TW: unknown component '${comp}'[\\s\\S]*?-->`, "gi"), body);
258214
+ }
257667
258215
  let layoutTitle;
257668
258216
  const liftedParts = [];
257669
258217
  {
@@ -258082,8 +258630,6 @@ ${bodyHTML}`;
258082
258630
  };
258083
258631
  let tags = "";
258084
258632
  const description = pick2("description");
258085
- if (description) tags += ` <meta name="description" content="${esc4(description)}">
258086
- `;
258087
258633
  const keywords = pick2("keywords");
258088
258634
  if (keywords) tags += ` <meta name="keywords" content="${esc4(keywords)}">
258089
258635
  `;
@@ -260265,6 +260811,7 @@ var init_static = __esm({
260265
260811
  if (!(0, import_node_fs13.existsSync)(filePath)) {
260266
260812
  filePath = (0, import_node_path20.join)(this.root, safePath + ".html");
260267
260813
  }
260814
+ let notFoundFallback = false;
260268
260815
  if (!(0, import_node_fs13.existsSync)(filePath)) {
260269
260816
  filePath = (0, import_node_path20.join)(this.root, safePath, this.indexFile);
260270
260817
  }
@@ -260276,6 +260823,7 @@ var init_static = __esm({
260276
260823
  }
260277
260824
  } else {
260278
260825
  filePath = (0, import_node_path20.join)(this.root, "404.html");
260826
+ notFoundFallback = true;
260279
260827
  if (!(0, import_node_fs13.existsSync)(filePath)) {
260280
260828
  return new Response("Not Found", { status: 404, headers: { "Content-Type": "text/plain" } });
260281
260829
  }
@@ -260343,12 +260891,12 @@ var init_static = __esm({
260343
260891
  const gzHeaders = { ...headers, "Content-Encoding": "gzip", "Content-Length": String(gz.length), Vary: "Accept-Encoding" };
260344
260892
  delete gzHeaders["Content-Length"];
260345
260893
  if (this.lastModified) delete gzHeaders["Last-Modified"];
260346
- return new Response(gz, { headers: gzHeaders });
260894
+ return new Response(gz, { headers: gzHeaders, status: notFoundFallback ? 404 : 200 });
260347
260895
  }
260348
260896
  } catch {
260349
260897
  }
260350
260898
  }
260351
- return new Response(bytes, { headers });
260899
+ return new Response(bytes, { headers, status: notFoundFallback ? 404 : 200 });
260352
260900
  }
260353
260901
  /**
260354
260902
  * Parse a `Range: bytes=...` header against a known content length.
@@ -260401,10 +260949,10 @@ var init_static = __esm({
260401
260949
  });
260402
260950
 
260403
260951
  // ../../packages/security/tw/policy.ts
260404
- var import_node_crypto5, CSPBuilder, XSSSanitizer, RateLimiter, CSRFProtection, InputValidator;
260952
+ var import_node_crypto6, CSPBuilder, XSSSanitizer, RateLimiter, CSRFProtection, InputValidator;
260405
260953
  var init_policy = __esm({
260406
260954
  "../../packages/security/tw/policy.ts"() {
260407
- import_node_crypto5 = require("node:crypto");
260955
+ import_node_crypto6 = require("node:crypto");
260408
260956
  CSPBuilder = class _CSPBuilder {
260409
260957
  directives = /* @__PURE__ */ new Map();
260410
260958
  nonces = /* @__PURE__ */ new Set();
@@ -260422,7 +260970,7 @@ var init_policy = __esm({
260422
260970
  return this;
260423
260971
  }
260424
260972
  generateNonce() {
260425
- const nonce = (0, import_node_crypto5.randomBytes)(16).toString("base64");
260973
+ const nonce = (0, import_node_crypto6.randomBytes)(16).toString("base64");
260426
260974
  this.nonces.add(nonce);
260427
260975
  return nonce;
260428
260976
  }
@@ -260671,7 +261219,7 @@ var init_policy = __esm({
260671
261219
  * Generate a Subresource Integrity hash for a script/style.
260672
261220
  */
260673
261221
  generateSRI(content, alg = "sha384") {
260674
- const hash2 = (0, import_node_crypto5.createHash)(alg).update(content).digest("base64");
261222
+ const hash2 = (0, import_node_crypto6.createHash)(alg).update(content).digest("base64");
260675
261223
  return `${alg}-${hash2}`;
260676
261224
  }
260677
261225
  /**
@@ -260752,10 +261300,10 @@ var init_policy = __esm({
260752
261300
  tokens = /* @__PURE__ */ new Map();
260753
261301
  secret;
260754
261302
  constructor(secret) {
260755
- this.secret = secret ?? (0, import_node_crypto5.randomBytes)(32).toString("hex");
261303
+ this.secret = secret ?? (0, import_node_crypto6.randomBytes)(32).toString("hex");
260756
261304
  }
260757
261305
  generateToken(sessionId) {
260758
- const token = (0, import_node_crypto5.randomBytes)(32).toString("hex");
261306
+ const token = (0, import_node_crypto6.randomBytes)(32).toString("hex");
260759
261307
  const expires = Date.now() + 36e5;
260760
261308
  this.tokens.set(sessionId, { value: token, expires });
260761
261309
  return token;
@@ -260998,6 +261546,12 @@ var init_xss_detector = __esm({
260998
261546
  { name: "SQL comment", regex: /--\s/g, severity: "medium", recommendation: "Check for SQL comment injection" },
260999
261547
  { name: "Stacked queries", regex: /;\s*(SELECT|INSERT|UPDATE|DELETE|DROP|UNION)/gi, severity: "high", recommendation: "Prevent stacked queries" },
261000
261548
  { name: "UNION injection", regex: /UNION\s+SELECT/gi, severity: "critical", recommendation: "Filter UNION SELECT from user input" },
261549
+ // Comment-only injections (`admin'--`, `admin'#`, `admin'/*`): a quote
261550
+ // followed by a comment truncates the query and bypasses the login
261551
+ // check, with no OR/UNION for the other patterns to catch.
261552
+ { name: "Comment-terminated injection", regex: /['"`]\s*(--|#|\/\*)/g, severity: "high", recommendation: "A quote followed by a comment truncates the query -- use parameterized queries" },
261553
+ // Parenthesised boolean injection: `') OR ('1'='1`.
261554
+ { name: "Parenthesised boolean injection", regex: /['"`]?\s*\)\s*(OR|AND)\s*\(?\s*['"`]?\s*\d/i, severity: "high", recommendation: "Use parameterized queries instead of building boolean expressions" },
261001
261555
  { name: "Boolean-based injection", regex: /OR\s+1\s*=\s*1/gi, severity: "high", recommendation: "Use parameterized queries to prevent boolean injection" },
261002
261556
  { name: "Time-based injection", regex: /WAITFOR\s+DELAY/gi, severity: "high", recommendation: "Filter WAITFOR DELAY from user input" },
261003
261557
  { name: "DROP statement", regex: /DROP\s+(TABLE|DATABASE)/gi, severity: "critical", recommendation: "Prevent DROP statements in queries" },
@@ -261528,6 +262082,7 @@ var init_logger3 = __esm({
261528
262082
  }
261529
262083
  /** Records an audit event. */
261530
262084
  log(event) {
262085
+ event = { type: "system", actor: "unknown", resource: "unknown", ...event };
261531
262086
  const fullEvent = {
261532
262087
  ...event,
261533
262088
  id: crypto.randomUUID(),
@@ -262544,6 +263099,13 @@ var FILE_SIGNATURES, DANGEROUS_EXTENSIONS, DANGEROUS_MIME_TYPES, ContentSecurity
262544
263099
  var init_protector = __esm({
262545
263100
  "../../packages/security/tw/content-security/protector.ts"() {
262546
263101
  FILE_SIGNATURES = [
263102
+ // Executables and HTML: without these, content renamed to an image extension
263103
+ // had no detected type, the signature check was skipped, and the upload was
263104
+ // accepted as risk "low" -- the exact rename bypass the check exists for.
263105
+ { ext: ["exe", "dll", "sys"], mime: "application/x-msdownload", signature: [77, 90] },
263106
+ { ext: ["elf", "so", "bin"], mime: "application/x-executable", signature: [127, 69, 76, 70] },
263107
+ { ext: ["html", "htm", "xhtml"], mime: "text/html", signature: [60, 104, 116, 109, 108] },
263108
+ { ext: ["html", "htm"], mime: "text/html", signature: [60, 33, 68, 79, 67, 84, 89, 80, 69] },
262547
263109
  { ext: ["jpg", "jpeg"], mime: "image/jpeg", signature: [255, 216, 255] },
262548
263110
  { ext: ["png"], mime: "image/png", signature: [137, 80, 78, 71, 13, 10, 26, 10] },
262549
263111
  { ext: ["gif"], mime: "image/gif", signature: [71, 73, 70, 56] },
@@ -262595,10 +263157,39 @@ var init_protector = __esm({
262595
263157
  ".htpasswd",
262596
263158
  ".svg",
262597
263159
  // Can contain JavaScript
262598
- ".xml"
263160
+ ".xml",
262599
263161
  // Can contain XXE
263162
+ // Active-content types the set used to let through while still blocking .svg
263163
+ // "because it can contain JavaScript" -- .html/.js are script-capable by
263164
+ // definition, so an accepted upload served from our own origin is stored XSS.
263165
+ ".html",
263166
+ ".htm",
263167
+ ".xhtml",
263168
+ ".shtml",
263169
+ ".js",
263170
+ ".mjs",
263171
+ ".cjs",
263172
+ ".jsx",
263173
+ ".ts",
263174
+ ".tsx",
263175
+ ".mhtml",
263176
+ ".hta",
263177
+ ".jsp",
263178
+ ".asp",
263179
+ ".aspx",
263180
+ ".cgi",
263181
+ ".pl"
262600
263182
  ]);
262601
263183
  DANGEROUS_MIME_TYPES = /* @__PURE__ */ new Set([
263184
+ // Active-content types: they can carry script (svg, xhtml, xml) or be
263185
+ // rendered as a document (html, pdf). Blocking .svg by extension while
263186
+ // reporting isContentTypeSafe("image/svg+xml") === true was inconsistent.
263187
+ "image/svg+xml",
263188
+ "text/html",
263189
+ "application/xhtml+xml",
263190
+ "application/pdf",
263191
+ "text/xml",
263192
+ "application/xml",
262602
263193
  "application/javascript",
262603
263194
  "text/javascript",
262604
263195
  "application/x-javascript",
@@ -262653,7 +263244,9 @@ var init_protector = __esm({
262653
263244
  reason: "Empty file",
262654
263245
  sanitizedFilename: sanitized,
262655
263246
  detectedType: "unknown",
262656
- risk: "low"
263247
+ // Unknown content is not low risk -- it is content whose type we could
263248
+ // not establish, which is what a rename bypass looks like.
263249
+ risk: "medium"
262657
263250
  };
262658
263251
  }
262659
263252
  if (this.blockedExtensions.has(ext)) {
@@ -263816,6 +264409,7 @@ var init_nonce_manager = __esm({
263816
264409
  validate(nonce) {
263817
264410
  const entry = this.nonces.get(nonce);
263818
264411
  if (!entry) return false;
264412
+ if (entry.used) return false;
263819
264413
  if (Date.now() > entry.expiresAt) {
263820
264414
  this.nonces.delete(nonce);
263821
264415
  return false;
@@ -264608,7 +265202,15 @@ var init_token_manager = __esm({
264608
265202
  rotateAfterUse;
264609
265203
  maxTokens;
264610
265204
  tokens = /* @__PURE__ */ new Map();
265205
+ /** Tokens this manager issued and already consumed. A rotated token is
265206
+ * deleted from `tokens`, so without this marker a replay found no entry and
265207
+ * fell through to the stateless branch, which accepted it -- defeating the
265208
+ * documented single-use guarantee of `rotateAfterUse`. */
265209
+ consumedTokens = /* @__PURE__ */ new Set();
264611
265210
  constructor(options) {
265211
+ if (!options || typeof options.secret !== "string" || options.secret.length === 0) {
265212
+ throw new Error("createCSRFManager: options.secret is required (the HMAC key used to sign tokens)");
265213
+ }
264612
265214
  this.secret = options.secret;
264613
265215
  this.tokenLength = options.tokenLength ?? 32;
264614
265216
  this.ttl = options.ttl ?? 36e5;
@@ -264708,12 +265310,16 @@ var init_token_manager = __esm({
264708
265310
  }
264709
265311
  entry.used = true;
264710
265312
  if (this.rotateAfterUse) {
265313
+ this.consumedTokens.add(headerPart);
264711
265314
  this.tokens.delete(headerPart);
264712
265315
  const rotated = await this.generate(sessionId ?? void 0);
264713
265316
  return { valid: true, rotated };
264714
265317
  }
264715
265318
  return { valid: true };
264716
265319
  }
265320
+ if (this.consumedTokens.has(headerPart)) {
265321
+ return { valid: false, reason: "Token already used" };
265322
+ }
264717
265323
  const expectedSig = await hmacSign3(
264718
265324
  this.secret,
264719
265325
  `${headerPart}.${sessionId ?? ""}`
@@ -269205,14 +269811,14 @@ function getCachedSSR(pathname) {
269205
269811
  const diskPath = (0, import_node_path21.join)(_diskCacheDir, pathname.replace(/[\/]/g, "_") + ".html");
269206
269812
  if ((0, import_node_fs15.existsSync)(diskPath)) {
269207
269813
  const content = (0, import_node_fs14.readFileSync)(diskPath, "utf-8");
269208
- const etag = (0, import_node_crypto6.createHash)("sha256").update(content).digest("hex").slice(0, 16);
269814
+ const etag = (0, import_node_crypto7.createHash)("sha256").update(content).digest("hex").slice(0, 16);
269209
269815
  _ssrCache.set(pathname, { html: content, etag, expires: Date.now() + 6e4 });
269210
269816
  return { html: content, etag };
269211
269817
  }
269212
269818
  return null;
269213
269819
  }
269214
269820
  function setCachedSSR(pathname, html) {
269215
- const etag = (0, import_node_crypto6.createHash)("sha256").update(html).digest("hex").slice(0, 16);
269821
+ const etag = (0, import_node_crypto7.createHash)("sha256").update(html).digest("hex").slice(0, 16);
269216
269822
  _ssrCache.set(pathname, { html, etag, expires: Date.now() + 6e4 });
269217
269823
  try {
269218
269824
  if (!(0, import_node_fs15.existsSync)(_diskCacheDir)) (0, import_node_fs14.mkdirSync)(_diskCacheDir, { recursive: true });
@@ -269244,13 +269850,13 @@ function generatePreloadHints(assets) {
269244
269850
  }
269245
269851
  return hints.join("\n");
269246
269852
  }
269247
- var import_node_fs14, import_node_crypto6, import_node_path21, import_node_fs15, SSRRenderer, _ssrCache, _diskCacheDir;
269853
+ var import_node_fs14, import_node_crypto7, import_node_path21, import_node_fs15, SSRRenderer, _ssrCache, _diskCacheDir;
269248
269854
  var init_ssr = __esm({
269249
269855
  "../../packages/server/tw/ssr/index.ts"() {
269250
269856
  import_node_fs14 = require("node:fs");
269251
269857
  init_fs_compat();
269252
269858
  init_tw();
269253
- import_node_crypto6 = require("node:crypto");
269859
+ import_node_crypto7 = require("node:crypto");
269254
269860
  import_node_path21 = require("node:path");
269255
269861
  import_node_fs15 = require("node:fs");
269256
269862
  SSRRenderer = class {
@@ -269674,7 +270280,7 @@ function generateNonce2(length = 32) {
269674
270280
  if (typeof crypto !== "undefined" && crypto.getRandomValues) {
269675
270281
  crypto.getRandomValues(bytes);
269676
270282
  } else {
269677
- const hash2 = (0, import_node_crypto7.createHash)("sha256");
270283
+ const hash2 = (0, import_node_crypto8.createHash)("sha256");
269678
270284
  hash2.update(`${Date.now()}-${nonceCounter++}-${Math.random()}`);
269679
270285
  return hash2.digest("base64");
269680
270286
  }
@@ -269792,10 +270398,10 @@ function createProdCSP() {
269792
270398
  "block-all-mixed-content": true
269793
270399
  };
269794
270400
  }
269795
- var import_node_crypto7, DEFAULT_CSP, DEFAULT_OPTIONS5, nonceCounter;
270401
+ var import_node_crypto8, DEFAULT_CSP, DEFAULT_OPTIONS5, nonceCounter;
269796
270402
  var init_security_headers2 = __esm({
269797
270403
  "../../packages/server/tw/security-headers.ts"() {
269798
- import_node_crypto7 = require("node:crypto");
270404
+ import_node_crypto8 = require("node:crypto");
269799
270405
  DEFAULT_CSP = {
269800
270406
  "default-src": ["'self'"],
269801
270407
  "script-src": ["'self'"],
@@ -270589,17 +271195,17 @@ async function hs256(payload, secret, maxAge) {
270589
271195
  const header = { alg: "HS256", typ: "JWT" };
270590
271196
  const body = { ...payload, iat: now, exp: now + maxAge };
270591
271197
  const data = enc(header) + "." + enc(body);
270592
- const { createHmac: createHmac2 } = await import("node:crypto");
270593
- const sig = createHmac2("sha256", secret).update(data).digest("base64url");
271198
+ const { createHmac: createHmac3 } = await import("node:crypto");
271199
+ const sig = createHmac3("sha256", secret).update(data).digest("base64url");
270594
271200
  return data + "." + sig;
270595
271201
  }
270596
271202
  async function verifyHs256(token, secret) {
270597
271203
  const parts = token.split(".");
270598
271204
  if (parts.length !== 3) return null;
270599
- const { createHmac: createHmac2, timingSafeEqual: timingSafeEqual4 } = await import("node:crypto");
270600
- const expected = createHmac2("sha256", secret).update(parts[0] + "." + parts[1]).digest("base64url");
271205
+ const { createHmac: createHmac3, timingSafeEqual: timingSafeEqual3 } = await import("node:crypto");
271206
+ const expected = createHmac3("sha256", secret).update(parts[0] + "." + parts[1]).digest("base64url");
270601
271207
  const a = Buffer.from(expected), b = Buffer.from(parts[2]);
270602
- if (a.length !== b.length || !timingSafeEqual4(a, b)) return null;
271208
+ if (a.length !== b.length || !timingSafeEqual3(a, b)) return null;
270603
271209
  try {
270604
271210
  const body = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
270605
271211
  if (typeof body.exp === "number" && body.exp < Math.floor(Date.now() / 1e3)) return null;
@@ -271084,6 +271690,17 @@ var init_tw9 = __esm({
271084
271690
  cfgIn.redirects = normalizedRedirects.filter(Boolean);
271085
271691
  }
271086
271692
  }
271693
+ if (Array.isArray(cfgIn.redirects)) {
271694
+ const seenFrom = /* @__PURE__ */ new Set();
271695
+ for (const r of cfgIn.redirects) {
271696
+ const from = r && typeof r.from === "string" ? r.from : null;
271697
+ if (!from) continue;
271698
+ if (seenFrom.has(from)) {
271699
+ console.warn("[tw] redirects: '" + from + "' is listed more than once -- the first entry wins, the later one never runs");
271700
+ }
271701
+ seenFrom.add(from);
271702
+ }
271703
+ }
271087
271704
  if (cfgIn.headers && !Array.isArray(cfgIn.headers)) {
271088
271705
  const entries = Object.entries(cfgIn.headers);
271089
271706
  cfgIn.headers = entries.map(([source, headers]) => ({ source, headers }));
@@ -271904,6 +272521,19 @@ ${err2.stack ?? ""}`);
271904
272521
  const isrLookupPath = pathname.length > 1 ? pathname.replace(/\/+$/, "") : pathname;
271905
272522
  if (this.staticHandler && !this.isrRoutes.has(isrLookupPath)) {
271906
272523
  let staticResponse = await this.staticHandler.serve(pathname, request);
272524
+ if (staticResponse.status !== 404) {
272525
+ const reqMethod = request.method.toUpperCase();
272526
+ const allow = "GET, HEAD, OPTIONS";
272527
+ if (reqMethod === "TRACE") {
272528
+ return new Response("Method Not Allowed", { status: 405, headers: { Allow: allow } });
272529
+ }
272530
+ if (reqMethod === "OPTIONS") {
272531
+ return new Response(null, { status: 204, headers: { Allow: allow } });
272532
+ }
272533
+ if (reqMethod !== "GET" && reqMethod !== "HEAD") {
272534
+ return new Response("Method Not Allowed", { status: 405, headers: { Allow: allow } });
272535
+ }
272536
+ }
271907
272537
  if (staticResponse && this.cspEnabled() && (staticResponse.headers.get("content-type") || "").includes("text/html")) {
271908
272538
  try {
271909
272539
  let buf = Buffer.from(await staticResponse.arrayBuffer());
@@ -272048,6 +272678,32 @@ ${err2.stack ?? ""}`);
272048
272678
  });
272049
272679
 
272050
272680
  // ../../packages/runtime/tw/dependency-graph.ts
272681
+ function flushPendingSubs() {
272682
+ if (isFlushing || !pendingSubs) return;
272683
+ isFlushing = true;
272684
+ try {
272685
+ let guard = 0;
272686
+ while (pendingSubs && pendingSubs.size > 0 && guard++ < 1e5) {
272687
+ const batchOf = pendingSubs;
272688
+ pendingSubs = /* @__PURE__ */ new Set();
272689
+ for (const sub of batchOf) {
272690
+ try {
272691
+ sub();
272692
+ } catch (e) {
272693
+ console.error("[TW Reactivity] Signal subscriber error:", e);
272694
+ }
272695
+ }
272696
+ }
272697
+ } finally {
272698
+ isFlushing = false;
272699
+ pendingSubs = null;
272700
+ }
272701
+ }
272702
+ function enqueueSubs(subs) {
272703
+ if (!pendingSubs) pendingSubs = /* @__PURE__ */ new Set();
272704
+ for (const s of subs) pendingSubs.add(s);
272705
+ if (batchDepth === 0) flushPendingSubs();
272706
+ }
272051
272707
  function startBatch() {
272052
272708
  batchDepth++;
272053
272709
  }
@@ -272057,13 +272713,7 @@ function endBatch() {
272057
272713
  batchDepth = 0;
272058
272714
  const effects = Array.from(batchedEffects);
272059
272715
  batchedEffects.clear();
272060
- for (const eff of effects) {
272061
- try {
272062
- eff();
272063
- } catch (e) {
272064
- console.error("[TW Reactivity] Batch effect error:", e);
272065
- }
272066
- }
272716
+ enqueueSubs(effects);
272067
272717
  }
272068
272718
  }
272069
272719
  function batch(fn) {
@@ -272245,12 +272895,14 @@ function isComputed(value) {
272245
272895
  function createScope3() {
272246
272896
  return new ReactiveScope();
272247
272897
  }
272248
- var currentEffect, batchDepth, batchedEffects, SignalImpl, ComputedImpl, watchEffect, currentCleanup, ReactiveScope;
272898
+ var currentEffect, batchDepth, batchedEffects, pendingSubs, isFlushing, SignalImpl, ComputedImpl, watchEffect, currentCleanup, ReactiveScope;
272249
272899
  var init_dependency_graph = __esm({
272250
272900
  "../../packages/runtime/tw/dependency-graph.ts"() {
272251
272901
  currentEffect = null;
272252
272902
  batchDepth = 0;
272253
272903
  batchedEffects = /* @__PURE__ */ new Set();
272904
+ pendingSubs = null;
272905
+ isFlushing = false;
272254
272906
  SignalImpl = class {
272255
272907
  value;
272256
272908
  subscribers = /* @__PURE__ */ new Set();
@@ -272269,19 +272921,9 @@ var init_dependency_graph = __esm({
272269
272921
  if (this.equals(this.value, value)) return;
272270
272922
  this.value = value;
272271
272923
  if (batchDepth > 0) {
272272
- for (const sub of this.subscribers) {
272273
- batchedEffects.add(sub);
272274
- }
272275
- } else {
272276
- const subs = Array.from(this.subscribers);
272277
- for (const sub of subs) {
272278
- try {
272279
- sub();
272280
- } catch (e) {
272281
- console.error("[TW Reactivity] Signal subscriber error:", e);
272282
- }
272283
- }
272924
+ for (const sub of this.subscribers) batchedEffects.add(sub);
272284
272925
  }
272926
+ enqueueSubs(this.subscribers);
272285
272927
  }
272286
272928
  update(fn) {
272287
272929
  this.set(fn(this.value));
@@ -272347,14 +272989,11 @@ var init_dependency_graph = __esm({
272347
272989
  return this.cachedValue;
272348
272990
  }
272349
272991
  notify() {
272350
- const subs = Array.from(this.subscribers);
272351
- for (const sub of subs) {
272352
- try {
272353
- sub();
272354
- } catch (e) {
272355
- console.error("[TW Reactivity] Computed subscriber error:", e);
272356
- }
272992
+ if (batchDepth > 0) {
272993
+ for (const sub of this.subscribers) batchedEffects.add(sub);
272994
+ return;
272357
272995
  }
272996
+ enqueueSubs(this.subscribers);
272358
272997
  }
272359
272998
  set(_value) {
272360
272999
  throw new Error("Cannot set a computed signal");
@@ -275539,10 +276178,12 @@ var init_diff = __esm({
275539
276178
  "../../packages/runtime/tw/diff.ts"() {
275540
276179
  init_vdom2();
275541
276180
  HTML_ESCAPE_MAP = {
275542
- "&": "&",
275543
- "<": "<",
275544
- ">": ">",
275545
- '"': '"',
276181
+ // These four mapped to THEMSELVES, so a <script> tag passed through
276182
+ // untouched -- only ' was actually escaped.
276183
+ "&": "&amp;",
276184
+ "<": "&lt;",
276185
+ ">": "&gt;",
276186
+ '"': "&quot;",
275546
276187
  "'": "&#39;"
275547
276188
  };
275548
276189
  HTML_ESCAPE_REGEX = /[&<>"']/g;
@@ -279072,8 +279713,19 @@ async function hydrateElementById(id, component, root = typeof document !== "und
279072
279713
  );
279073
279714
  }
279074
279715
  function markForHydration(element, componentId, props) {
279716
+ if (!element || typeof componentId !== "string") return;
279075
279717
  element.setAttribute(HYDRATE_ATTR, componentId);
279076
- element.setAttribute("data-tw-props", JSON.stringify(props));
279718
+ let serialised = null;
279719
+ if (props && typeof props === "object") {
279720
+ try {
279721
+ serialised = JSON.stringify(props);
279722
+ } catch {
279723
+ serialised = null;
279724
+ }
279725
+ }
279726
+ if (serialised !== null && serialised !== void 0) {
279727
+ element.setAttribute("data-tw-props", serialised);
279728
+ }
279077
279729
  }
279078
279730
  function unmarkForHydration(element) {
279079
279731
  element.removeAttribute(HYDRATE_ATTR);
@@ -282373,15 +283025,21 @@ function usePathname(opts) {
282373
283025
  function matchPathPattern(path, pattern) {
282374
283026
  const pSeg = path.split("/").filter(Boolean);
282375
283027
  const tSeg = pattern.split("/").filter(Boolean);
282376
- if (pSeg.length !== tSeg.length) return { matches: false, params: {}, score: 0 };
283028
+ const catchAllAt = tSeg.findIndex((t3) => t3.startsWith("[...") || t3.startsWith(":..."));
283029
+ if (catchAllAt === -1) {
283030
+ if (pSeg.length !== tSeg.length) return { matches: false, params: {}, score: 0 };
283031
+ } else if (pSeg.length < tSeg.length) {
283032
+ return { matches: false, params: {}, score: 0 };
283033
+ }
282377
283034
  const params = {};
282378
283035
  let literal = 0;
282379
283036
  for (let i = 0; i < tSeg.length; i++) {
282380
283037
  const t3 = tSeg[i];
282381
283038
  const isParam = t3.startsWith("[") && t3.endsWith("]") || t3.startsWith(":");
282382
283039
  if (isParam) {
282383
- const name = t3.startsWith("[") ? t3.slice(1, -1).replace(/\.\.\.$/, "") : t3.slice(1);
282384
- params[name] = decodeURIComponent(pSeg[i]);
283040
+ const name = t3.startsWith("[") ? t3.slice(1, -1).replace(/^\.\.\./, "") : t3.slice(1);
283041
+ const isCatchAll = t3.startsWith("[...") || t3.startsWith(":...");
283042
+ params[name] = isCatchAll ? pSeg.slice(i).map((seg) => decodeURIComponent(seg)).join("/") : decodeURIComponent(pSeg[i]);
282385
283043
  } else if (t3 !== pSeg[i]) {
282386
283044
  return { matches: false, params: {}, score: 0 };
282387
283045
  } else {
@@ -283196,7 +283854,11 @@ function defineStore(idOrDefinition, maybeDefinition) {
283196
283854
  const getterDeps = Object.values(reactiveState);
283197
283855
  for (const key2 of Object.keys(getters)) {
283198
283856
  const getter = getters[key2];
283199
- getterValues[key2] = computed4(getterDeps, getter);
283857
+ getterValues[key2] = computed4(getterDeps, () => {
283858
+ const snap = {};
283859
+ for (const k of Object.keys(reactiveState)) snap[k] = reactiveState[k].value;
283860
+ return getter.call(snap, snap);
283861
+ });
283200
283862
  }
283201
283863
  const subscribers = /* @__PURE__ */ new Set();
283202
283864
  const actionListeners = /* @__PURE__ */ new Set();
@@ -283221,9 +283883,41 @@ function defineStore(idOrDefinition, maybeDefinition) {
283221
283883
  return () => set.delete(cb);
283222
283884
  }
283223
283885
  };
283886
+ const MUTATORS = /* @__PURE__ */ new Set(["push", "pop", "shift", "unshift", "splice", "sort", "reverse", "fill", "copyWithin"]);
283887
+ const tracking = /* @__PURE__ */ new WeakMap();
283888
+ const track2 = (value, prop) => {
283889
+ if (value === null || typeof value !== "object") return value;
283890
+ const existing2 = tracking.get(value);
283891
+ if (existing2) return existing2;
283892
+ const wrapped = new Proxy(value, {
283893
+ get(t3, key2, recv) {
283894
+ const v = Reflect.get(t3, key2, recv);
283895
+ if (typeof v === "function" && MUTATORS.has(String(key2))) {
283896
+ return (...args) => {
283897
+ const out = v.apply(t3, args);
283898
+ reactiveState[prop]?.touch();
283899
+ return out;
283900
+ };
283901
+ }
283902
+ return v;
283903
+ },
283904
+ set(t3, key2, v) {
283905
+ const ok2 = Reflect.set(t3, key2, v);
283906
+ reactiveState[prop]?.touch();
283907
+ return ok2;
283908
+ },
283909
+ deleteProperty(t3, key2) {
283910
+ const ok2 = Reflect.deleteProperty(t3, key2);
283911
+ reactiveState[prop]?.touch();
283912
+ return ok2;
283913
+ }
283914
+ });
283915
+ tracking.set(value, wrapped);
283916
+ return wrapped;
283917
+ };
283224
283918
  const stateProxy = new Proxy({}, {
283225
283919
  get(_target, prop) {
283226
- return reactiveState[prop]?.value;
283920
+ return track2(reactiveState[prop]?.value, prop);
283227
283921
  },
283228
283922
  set(_target, prop, value) {
283229
283923
  if (reactiveState[prop]) {
@@ -283239,7 +283933,7 @@ function defineStore(idOrDefinition, maybeDefinition) {
283239
283933
  const fn = actions[key2];
283240
283934
  boundActions[key2] = (...args) => {
283241
283935
  actionListeners.forEach((cb) => cb({ name: key2, args }));
283242
- return fn.call(ctx, stateProxy, ...args);
283936
+ return fn.call(stateProxy, stateProxy, ...args);
283243
283937
  };
283244
283938
  }
283245
283939
  for (const rv of Object.values(reactiveState)) {
@@ -283344,6 +284038,14 @@ var init_store = __esm({
283344
284038
  update(updater) {
283345
284039
  this.set(updater(this._value));
283346
284040
  }
284041
+ /**
284042
+ * Re-notify subscribers without replacing the value. An array or object that
284043
+ * was mutated in place (`this.items.push(x)`) has the same identity, so
284044
+ * `set()` short-circuits and nothing downstream hears about it.
284045
+ */
284046
+ touch() {
284047
+ this._notify();
284048
+ }
283347
284049
  subscribe(listener) {
283348
284050
  this._listeners.add(listener);
283349
284051
  return () => {
@@ -283351,9 +284053,10 @@ var init_store = __esm({
283351
284053
  };
283352
284054
  }
283353
284055
  _notify() {
284056
+ const current2 = this.value ?? this._value;
283354
284057
  for (const l of this._listeners) {
283355
284058
  try {
283356
- l();
284059
+ l(current2);
283357
284060
  } catch {
283358
284061
  }
283359
284062
  }
@@ -284359,7 +285062,8 @@ var init_virtual_list = __esm({
284359
285062
  return this.container.scrollTop;
284360
285063
  }
284361
285064
  getFirstVisibleIndex() {
284362
- return this.visibleRange.start;
285065
+ const last = Math.max(0, (this.options?.itemCount ?? 0) - 1);
285066
+ return Math.min(Math.max(this.visibleRange.start, 0), last);
284363
285067
  }
284364
285068
  getLastVisibleIndex() {
284365
285069
  return this.visibleRange.end;