tina4-nodejs 3.13.150 → 3.13.152

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.
Files changed (71) hide show
  1. package/CLAUDE.md +2 -2
  2. package/package.json +5 -9
  3. package/packages/cli/dist/bin.js +1326 -586
  4. package/packages/cli/src/bin.ts +179 -7
  5. package/packages/cli/src/commands/generate.ts +36 -17
  6. package/packages/cli/src/commands/migrateCreate.ts +15 -3
  7. package/packages/cli/src/commands/queue.ts +8 -0
  8. package/packages/cli/src/util.ts +25 -15
  9. package/packages/core/dist/index.js +1172 -574
  10. package/packages/core/src/aiClient.ts +2 -1
  11. package/packages/core/src/api.ts +2 -1
  12. package/packages/core/src/auth.ts +1 -1
  13. package/packages/core/src/authGate.ts +3 -4
  14. package/packages/core/src/cache.ts +6 -1
  15. package/packages/core/src/devAdmin.ts +180 -123
  16. package/packages/core/src/dispatchPipeline.ts +4 -0
  17. package/packages/core/src/docs.ts +5 -3
  18. package/packages/core/src/errorOverlay.ts +18 -9
  19. package/packages/core/src/index.ts +2 -1
  20. package/packages/core/src/mcp.ts +53 -16
  21. package/packages/core/src/messenger.ts +22 -30
  22. package/packages/core/src/middleware.ts +8 -1
  23. package/packages/core/src/optionalPackage.ts +2 -2
  24. package/packages/core/src/plan.ts +3 -3
  25. package/packages/core/src/push.ts +1 -1
  26. package/packages/core/src/request.ts +185 -25
  27. package/packages/core/src/router.ts +3 -2
  28. package/packages/core/src/server.ts +36 -12
  29. package/packages/core/src/session.ts +44 -0
  30. package/packages/core/src/slashTrim.ts +39 -0
  31. package/packages/core/src/wsdl.ts +66 -48
  32. package/packages/core/templates/crud/form.twig +5 -5
  33. package/packages/core/templates/crud/table.twig +2 -2
  34. package/packages/core/templates/errors/302.twig +4 -3
  35. package/packages/frond/dist/index.js +206 -64
  36. package/packages/frond/src/engine.ts +278 -69
  37. package/packages/frond/src/index.ts +1 -1
  38. package/packages/orm/dist/index.js +1156 -560
  39. package/packages/orm/src/adapters/postgres.ts +79 -19
  40. package/packages/orm/src/crudRender.ts +5 -5
  41. package/packages/orm/src/crudTable.ts +1 -1
  42. package/packages/orm/src/database.ts +15 -29
  43. package/packages/orm/src/databaseResult.ts +11 -1
  44. package/packages/orm/src/docstore.ts +24 -8
  45. package/packages/orm/src/realtime/index.ts +1 -0
  46. package/packages/orm/src/realtime/realtime.ts +2 -1
  47. package/packages/orm/src/realtime/s3Client.ts +276 -0
  48. package/packages/orm/src/realtime/storage.ts +19 -60
  49. package/packages/orm/src/sqlTranslator.ts +58 -42
  50. package/packages/swagger/dist/index.js +25 -4
  51. package/packages/swagger/src/generator.ts +7 -4
  52. package/packages/swagger/src/ui.ts +2 -1
  53. package/types/cli/src/bin.d.ts +16 -0
  54. package/types/cli/src/commands/generate.d.ts +11 -0
  55. package/types/cli/src/commands/migrateCreate.d.ts +2 -0
  56. package/types/cli/src/commands/queue.d.ts +2 -0
  57. package/types/cli/src/util.d.ts +2 -1
  58. package/types/core/src/authGate.d.ts +3 -3
  59. package/types/core/src/devAdmin.d.ts +40 -0
  60. package/types/core/src/index.d.ts +2 -1
  61. package/types/core/src/middleware.d.ts +1 -0
  62. package/types/core/src/optionalPackage.d.ts +2 -2
  63. package/types/core/src/request.d.ts +5 -1
  64. package/types/core/src/session.d.ts +25 -0
  65. package/types/core/src/slashTrim.d.ts +6 -0
  66. package/types/frond/src/engine.d.ts +11 -0
  67. package/types/frond/src/index.d.ts +1 -1
  68. package/types/orm/src/adapters/postgres.d.ts +6 -0
  69. package/types/orm/src/realtime/index.d.ts +1 -0
  70. package/types/orm/src/realtime/s3Client.d.ts +48 -0
  71. package/types/orm/src/realtime/storage.d.ts +9 -7
@@ -51,6 +51,12 @@ var init_types = __esm({
51
51
  });
52
52
 
53
53
  // src/databaseResult.ts
54
+ function stripTypeArgs(colType) {
55
+ const open = colType.indexOf("(");
56
+ if (open < 0) return colType;
57
+ const close = colType.indexOf(")", open);
58
+ return close < 0 ? colType : colType.slice(0, open) + colType.slice(close + 1);
59
+ }
54
60
  var DatabaseResult;
55
61
  var init_databaseResult = __esm({
56
62
  "src/databaseResult.ts"() {
@@ -233,7 +239,7 @@ var init_databaseResult = __esm({
233
239
  const [size, decimals] = this._parseTypeSize(colType);
234
240
  return {
235
241
  name: col.name,
236
- type: colType.replace(/\(.*\)/, ""),
242
+ type: stripTypeArgs(colType),
237
243
  size,
238
244
  decimals,
239
245
  nullable: col.nullable ?? true,
@@ -790,12 +796,49 @@ var init_point = __esm({
790
796
  });
791
797
 
792
798
  // src/sqlTranslator.ts
793
- var SQLTranslator, QueryCache;
799
+ function skipQuoted(sql, i, backslashEscapes) {
800
+ const c = sql[i];
801
+ const escapeString = c === "'" && (sql[i - 1] === "E" || sql[i - 1] === "e") && !isIdentChar(sql[i - 2]);
802
+ const backslash = c !== "`" && (escapeString || backslashEscapes);
803
+ const n = sql.length;
804
+ i++;
805
+ while (i < n) {
806
+ if (backslash && sql[i] === "\\") {
807
+ i += 2;
808
+ continue;
809
+ }
810
+ if (sql[i] === c) {
811
+ if (sql[i + 1] === c) {
812
+ i += 2;
813
+ continue;
814
+ }
815
+ return i + 1;
816
+ }
817
+ i++;
818
+ }
819
+ return i;
820
+ }
821
+ function skipLineComment(sql, i) {
822
+ while (i < sql.length && sql[i] !== "\n") i++;
823
+ return i;
824
+ }
825
+ function skipBlockComment(sql, i) {
826
+ const end = sql.indexOf("*/", i + 2);
827
+ return end === -1 ? sql.length : end + 2;
828
+ }
829
+ function skipDollarQuote(sql, i) {
830
+ const tag = sql.slice(i).match(/^\$([A-Za-z_][A-Za-z0-9_]*)?\$/);
831
+ if (!tag) return i;
832
+ const end = sql.indexOf(tag[0], i + tag[0].length);
833
+ return end === -1 ? sql.length : end + tag[0].length;
834
+ }
835
+ var isIdentChar, SQLTranslator, QueryCache;
794
836
  var init_sqlTranslator = __esm({
795
837
  "src/sqlTranslator.ts"() {
796
838
  "use strict";
797
839
  init_databaseUrl();
798
840
  init_point();
841
+ isIdentChar = (ch) => !!ch && /[A-Za-z0-9_]/.test(ch);
799
842
  SQLTranslator = class _SQLTranslator {
800
843
  static SPATIAL_ENGINES = /* @__PURE__ */ new Set(["postgres", "postgresql"]);
801
844
  static SPATIAL_IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*$/;
@@ -1076,47 +1119,26 @@ var init_sqlTranslator = __esm({
1076
1119
  static placeholderPositions(sql, options = {}) {
1077
1120
  const positions = [];
1078
1121
  const n = sql.length;
1079
- const isIdent = (ch) => !!ch && /[A-Za-z0-9_]/.test(ch);
1080
1122
  let i = 0;
1081
1123
  while (i < n) {
1082
1124
  const c = sql[i];
1083
1125
  const next = sql[i + 1];
1084
1126
  if (c === "'" || c === '"' || c === "`") {
1085
- const prev = sql[i - 1];
1086
- const escapeString = c === "'" && (prev === "E" || prev === "e") && !isIdent(sql[i - 2]);
1087
- const backslash = c !== "`" && (escapeString || options.backslashEscapes === true);
1088
- i++;
1089
- while (i < n) {
1090
- if (backslash && sql[i] === "\\") {
1091
- i += 2;
1092
- continue;
1093
- }
1094
- if (sql[i] === c) {
1095
- if (sql[i + 1] === c) {
1096
- i += 2;
1097
- continue;
1098
- }
1099
- i++;
1100
- break;
1101
- }
1102
- i++;
1103
- }
1127
+ i = skipQuoted(sql, i, options.backslashEscapes === true);
1104
1128
  continue;
1105
1129
  }
1106
1130
  if (c === "-" && next === "-") {
1107
- while (i < n && sql[i] !== "\n") i++;
1131
+ i = skipLineComment(sql, i);
1108
1132
  continue;
1109
1133
  }
1110
1134
  if (c === "/" && next === "*") {
1111
- const end = sql.indexOf("*/", i + 2);
1112
- i = end === -1 ? n : end + 2;
1135
+ i = skipBlockComment(sql, i);
1113
1136
  continue;
1114
1137
  }
1115
- if (c === "$" && !isIdent(sql[i - 1])) {
1116
- const tag = sql.slice(i).match(/^\$([A-Za-z_][A-Za-z0-9_]*)?\$/);
1117
- if (tag) {
1118
- const end = sql.indexOf(tag[0], i + tag[0].length);
1119
- i = end === -1 ? n : end + tag[0].length;
1138
+ if (c === "$" && !isIdentChar(sql[i - 1])) {
1139
+ const past = skipDollarQuote(sql, i);
1140
+ if (past !== i) {
1141
+ i = past;
1120
1142
  continue;
1121
1143
  }
1122
1144
  }
@@ -1149,7 +1171,7 @@ var init_sqlTranslator = __esm({
1149
1171
  * → { sql: "INSERT INTO t (x) VALUES (1)", columns: ["id", "name"] }
1150
1172
  */
1151
1173
  static parseReturning(sql) {
1152
- const m = sql.match(/\bRETURNING\s+(.+)$/i);
1174
+ const m = sql.match(/\bRETURNING\s+(\S.*)$/i);
1153
1175
  if (!m) return { sql, columns: [] };
1154
1176
  const columns = m[1].split(",").map((c) => c.trim());
1155
1177
  return {
@@ -1203,7 +1225,12 @@ var init_sqlTranslator = __esm({
1203
1225
  // The `d` flag records group indices, so the head can be sliced at the exact
1204
1226
  // start of the VALUES group rather than by hunting for a parenthesis (the
1205
1227
  // column list has parentheses too).
1206
- static INSERT_VALUES = /^\s*INSERT\s+INTO\s+.+?\s+VALUES\s*\(([^()]*)\)\s*$/dis;
1228
+ static INSERT_VALUES = (
1229
+ // ReDoS-safe: the table ref matches `\S(?:[\s\S]*?\S)?` (bounded by non-space
1230
+ // at both ends) so the separator `\s+` before VALUES can't overlap it the way
1231
+ // the old `.+?\s+` did (polynomial on `INSERT INTO ` + a long space run).
1232
+ /^\s*INSERT\s+INTO\s+\S(?:[\s\S]*?\S)?\s+VALUES\s*\(([^()]*)\)\s*$/dis
1233
+ );
1207
1234
  /**
1208
1235
  * Engines whose lastInsertId reports the FIRST generated id of a multi-row
1209
1236
  * INSERT rather than the last. Verified live, not assumed: a 3-row insert
@@ -1678,6 +1705,30 @@ var init_sqlDialect = __esm({
1678
1705
  }
1679
1706
  });
1680
1707
 
1708
+ // ../core/src/slashTrim.ts
1709
+ function rtrimSlashes(s) {
1710
+ let end = s.length;
1711
+ while (end > 0 && s.charCodeAt(end - 1) === SLASH) end--;
1712
+ return end === s.length ? s : s.slice(0, end);
1713
+ }
1714
+ function trimChar(s, code) {
1715
+ let start2 = 0;
1716
+ let end = s.length;
1717
+ while (start2 < end && s.charCodeAt(start2) === code) start2++;
1718
+ while (end > start2 && s.charCodeAt(end - 1) === code) end--;
1719
+ return start2 === 0 && end === s.length ? s : s.slice(start2, end);
1720
+ }
1721
+ function trimSlashes(s) {
1722
+ return trimChar(s, SLASH);
1723
+ }
1724
+ var SLASH;
1725
+ var init_slashTrim = __esm({
1726
+ "../core/src/slashTrim.ts"() {
1727
+ "use strict";
1728
+ SLASH = 47;
1729
+ }
1730
+ });
1731
+
1681
1732
  // ../core/src/constants.ts
1682
1733
  var HTTP_OK, HTTP_CREATED, HTTP_ACCEPTED, HTTP_NO_CONTENT, HTTP_MOVED, HTTP_REDIRECT, HTTP_NOT_MODIFIED, HTTP_BAD_REQUEST, HTTP_UNAUTHORIZED, HTTP_FORBIDDEN, HTTP_NOT_FOUND, HTTP_METHOD_NOT_ALLOWED, HTTP_CONFLICT, HTTP_GONE, HTTP_UNPROCESSABLE, HTTP_TOO_MANY, HTTP_SERVER_ERROR, HTTP_BAD_GATEWAY, HTTP_UNAVAILABLE, APPLICATION_JSON, APPLICATION_XML, APPLICATION_FORM, APPLICATION_OCTET, TEXT_HTML, TEXT_PLAIN, TEXT_CSV, TEXT_XML;
1683
1734
  var init_constants = __esm({
@@ -2766,7 +2817,7 @@ function resolveAlgorithm(algorithm) {
2766
2817
  return chosen;
2767
2818
  }
2768
2819
  function base64urlEncode(data) {
2769
- return data.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
2820
+ return data.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/={1,2}$/, "");
2770
2821
  }
2771
2822
  function base64urlDecode(str) {
2772
2823
  let s = str.replace(/-/g, "+").replace(/_/g, "/");
@@ -3183,6 +3234,7 @@ function mayStore(req2, vary, cacheControl, setCookie) {
3183
3234
  if (requestHeader(req2, "authorization") !== void 0) return sharedCacheAllowed(cacheControl);
3184
3235
  if (requestHeader(req2, "cookie") !== void 0) return sharedCacheAllowed(cacheControl);
3185
3236
  if (hasSetCookie(setCookie)) return sharedCacheAllowed(cacheControl);
3237
+ if (req2.session?.isFresh && !req2.session.isFresh()) return sharedCacheAllowed(cacheControl);
3186
3238
  return true;
3187
3239
  }
3188
3240
  function varyMatches(entry, req2) {
@@ -4535,7 +4587,7 @@ function coerceParam(raw, type2) {
4535
4587
  }
4536
4588
  function joinGroupPath(prefix, path10) {
4537
4589
  const full = `${prefix}/${path10.replace(/^\/+/, "")}`;
4538
- const trimmed = `/${full.replace(/^\/+|\/+$/g, "")}`;
4590
+ const trimmed = `/${trimSlashes(full)}`;
4539
4591
  return trimmed.replace(/\/+/g, "/");
4540
4592
  }
4541
4593
  async function resolveStringMiddleware(spec) {
@@ -4600,6 +4652,7 @@ var WsRouteRef, RouteRef, Router, RouteGroup, TINA4_DEFAULT_ROUTER, globalRouter
4600
4652
  var init_router = __esm({
4601
4653
  "../core/src/router.ts"() {
4602
4654
  "use strict";
4655
+ init_slashTrim();
4603
4656
  init_dotenv();
4604
4657
  init_middleware();
4605
4658
  WsRouteRef = class {
@@ -4809,7 +4862,7 @@ var init_router = __esm({
4809
4862
  const direct = this.matchRoute(routes, path10);
4810
4863
  if (direct) return direct;
4811
4864
  if (isTrailingSlashRedirectEnabled() && path10.length > 1 && path10.endsWith("/")) {
4812
- const stripped = path10.replace(/\/+$/, "");
4865
+ const stripped = rtrimSlashes(path10);
4813
4866
  if (stripped.length > 0) {
4814
4867
  const retry = this.matchRoute(routes, stripped);
4815
4868
  if (retry) return retry;
@@ -5488,9 +5541,11 @@ __export(engine_exports, {
5488
5541
  escapeHtml: () => escapeHtml,
5489
5542
  expressionFormCache: () => expressionFormCache,
5490
5543
  filterChainCache: () => filterChainCache,
5544
+ frondRange: () => frondRange,
5491
5545
  pathParseCache: () => pathParseCache,
5492
5546
  setCspNonceProvider: () => setCspNonceProvider,
5493
- setFormTokenSessionId: () => setFormTokenSessionId
5547
+ setFormTokenSessionId: () => setFormTokenSessionId,
5548
+ setFormTokenSessionProvider: () => setFormTokenSessionProvider
5494
5549
  });
5495
5550
  import { createHash as createHash3, createHmac as createHmac2, randomBytes as randomBytes3 } from "node:crypto";
5496
5551
  import { readFileSync as readFileSync4, existsSync as existsSync5, statSync as statSync4, realpathSync } from "node:fs";
@@ -5575,6 +5630,14 @@ function renderDump(value) {
5575
5630
  const escaped = dumped.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
5576
5631
  return new SafeString(`<pre>${escaped}</pre>`);
5577
5632
  }
5633
+ function stripTags(input) {
5634
+ let s = input, prev;
5635
+ do {
5636
+ prev = s;
5637
+ s = s.replace(STRIP_TAGS_RE, "");
5638
+ } while (s !== prev);
5639
+ return s;
5640
+ }
5578
5641
  function liveAttr(value) {
5579
5642
  return String(value).replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
5580
5643
  }
@@ -5592,35 +5655,58 @@ function sweepExpiredCache(cache) {
5592
5655
  if (expiresAt2 <= now) cache.delete(key);
5593
5656
  }
5594
5657
  }
5595
- function tokenize(source) {
5658
+ function extractRawBlocks(source) {
5596
5659
  const rawBlocks = [];
5597
- source = source.replace(RAW_BLOCK_RE, (_match, content) => {
5660
+ let out = "";
5661
+ let pos = 0;
5662
+ RAW_OPEN_RE.lastIndex = 0;
5663
+ let om;
5664
+ while ((om = RAW_OPEN_RE.exec(source)) !== null) {
5665
+ const openStart = om.index;
5666
+ const openEnd = RAW_OPEN_RE.lastIndex;
5667
+ RAW_CLOSE_RE.lastIndex = openEnd;
5668
+ const cm = RAW_CLOSE_RE.exec(source);
5669
+ if (cm === null) break;
5598
5670
  const idx = rawBlocks.length;
5599
- rawBlocks.push(content);
5600
- return `\0RAW_${idx}\0`;
5601
- });
5671
+ rawBlocks.push(source.slice(openEnd, cm.index));
5672
+ out += source.slice(pos, openStart) + `\0RAW_${idx}\0`;
5673
+ pos = RAW_CLOSE_RE.lastIndex;
5674
+ RAW_OPEN_RE.lastIndex = pos;
5675
+ }
5676
+ out += source.slice(pos);
5677
+ return { source: out, rawBlocks };
5678
+ }
5679
+ function tokenize(rawSource) {
5680
+ const { source, rawBlocks } = extractRawBlocks(rawSource);
5602
5681
  const tokens = [];
5682
+ const n = source.length;
5603
5683
  let pos = 0;
5604
- TOKEN_RE.lastIndex = 0;
5605
- let m;
5606
- while ((m = TOKEN_RE.exec(source)) !== null) {
5607
- const start2 = m.index;
5608
- if (start2 > pos) {
5609
- tokens.push(["TEXT", source.slice(pos, start2)]);
5684
+ let scan = 0;
5685
+ const exhausted = { "%}": false, "}}": false, "#}": false };
5686
+ while (scan < n) {
5687
+ const brace = source.indexOf("{", scan);
5688
+ if (brace === -1) break;
5689
+ const kind = TAG_KINDS[source[brace + 1]];
5690
+ if (!kind) {
5691
+ scan = brace + 1;
5692
+ continue;
5610
5693
  }
5611
- const raw = m[0];
5612
- if (raw.startsWith("{#")) {
5613
- tokens.push(["COMMENT", raw]);
5614
- } else if (raw.startsWith("{{")) {
5615
- tokens.push(["VAR", raw]);
5616
- } else if (raw.startsWith("{%")) {
5617
- tokens.push(["BLOCK", raw]);
5694
+ if (exhausted[kind.close]) {
5695
+ scan = brace + 1;
5696
+ continue;
5618
5697
  }
5619
- pos = m.index + raw.length;
5620
- }
5621
- if (pos < source.length) {
5622
- tokens.push(["TEXT", source.slice(pos)]);
5698
+ const close = source.indexOf(kind.close, brace + 2);
5699
+ if (close === -1) {
5700
+ exhausted[kind.close] = true;
5701
+ scan = brace + 1;
5702
+ continue;
5703
+ }
5704
+ if (brace > pos) tokens.push(["TEXT", source.slice(pos, brace)]);
5705
+ tokens.push([kind.type, source.slice(brace, close + 2)]);
5706
+ pos = close + 2;
5707
+ scan = close + 2;
5623
5708
  }
5709
+ if (pos < n) tokens.push(["TEXT", source.slice(pos)]);
5624
5710
  if (rawBlocks.length > 0) {
5625
5711
  for (let i = 0; i < tokens.length; i++) {
5626
5712
  if (tokens[i][0] === "TEXT" && tokens[i][1].includes("\0RAW_")) {
@@ -5946,26 +6032,123 @@ function evalConcatOrComparison(expr, context) {
5946
6032
  }
5947
6033
  return EXPR_NOT_MATCHED;
5948
6034
  }
6035
+ function topLevelPositions(expr) {
6036
+ const positions = [];
6037
+ let inQuote = null;
6038
+ let depth = 0;
6039
+ for (let pos = 0; pos < expr.length; pos++) {
6040
+ const ch = expr[pos];
6041
+ if (inQuote) {
6042
+ if (ch === inQuote) inQuote = null;
6043
+ } else if (ch === '"' || ch === "'") {
6044
+ inQuote = ch;
6045
+ } else if ("([{".includes(ch)) {
6046
+ depth++;
6047
+ } else if (")]}".includes(ch)) {
6048
+ depth--;
6049
+ } else if (depth === 0) {
6050
+ positions.push(pos);
6051
+ }
6052
+ }
6053
+ return positions;
6054
+ }
6055
+ function followsOperand(expr, pos) {
6056
+ return /[\w)\]'"]$/.test(expr.slice(0, pos).trimEnd());
6057
+ }
6058
+ function topLevelArithmeticOperators(expr) {
6059
+ const operators = [];
6060
+ let skipUntil = -1;
6061
+ for (const pos of topLevelPositions(expr)) {
6062
+ if (pos < skipUntil || !"+-*/%".includes(expr[pos])) continue;
6063
+ const pair = expr.slice(pos, pos + 2);
6064
+ const op = pair === "**" || pair === "//" ? pair : expr[pos];
6065
+ skipUntil = pos + op.length;
6066
+ if (followsOperand(expr, pos)) operators.push([pos, op]);
6067
+ }
6068
+ return operators;
6069
+ }
6070
+ function splitArithmetic(expr) {
6071
+ const operators = topLevelArithmeticOperators(expr);
6072
+ for (const level of ARITHMETIC_LEVELS) {
6073
+ const matches = operators.filter(([, op]) => level.includes(op));
6074
+ if (matches.length > 0) return level[0] === "**" ? matches[0] : matches[matches.length - 1];
6075
+ }
6076
+ return null;
6077
+ }
5949
6078
  function evalArithmeticExpression(expr, context) {
5950
- for (const op of [" + ", " - ", " * ", " // ", " / ", " % ", " ** "]) {
5951
- const pos = findOutsideQuotes(expr, op);
5952
- if (pos >= 0) {
5953
- const left = expr.slice(0, pos).trim();
5954
- const right = expr.slice(pos + op.length).trim();
5955
- const lVal = evalExpr(left, context);
5956
- const rVal = evalExpr(right, context);
5957
- try {
5958
- let lNum = lVal != null ? Number(lVal) : 0;
5959
- let rNum = rVal != null ? Number(rVal) : 0;
5960
- if (isNaN(lNum)) lNum = 0;
5961
- if (isNaN(rNum)) rNum = 0;
5962
- return ARITHMETIC_OPERATIONS[op.trim()](lNum, rNum);
5963
- } catch {
5964
- return null;
5965
- }
6079
+ const split = splitArithmetic(expr);
6080
+ if (!split) return EXPR_NOT_MATCHED;
6081
+ const [pos, op] = split;
6082
+ const lVal = evalExpr(expr.slice(0, pos).trim(), context);
6083
+ const rVal = evalExpr(expr.slice(pos + op.length).trim(), context);
6084
+ let lNum = lVal != null ? Number(lVal) : 0;
6085
+ let rNum = rVal != null ? Number(rVal) : 0;
6086
+ if (isNaN(lNum)) lNum = 0;
6087
+ if (isNaN(rNum)) rNum = 0;
6088
+ return ARITHMETIC_OPERATIONS[op](lNum, rNum);
6089
+ }
6090
+ function frondRange(start2, end, step = 1) {
6091
+ const numeric = (value) => typeof value === "number" || typeof value === "string" && NUMERIC_RE.test(value);
6092
+ if (!numeric(start2) || !numeric(end) || !numeric(step)) return [];
6093
+ const first = Math.trunc(Number(start2));
6094
+ const last = Math.trunc(Number(end));
6095
+ const stride = Math.abs(Math.trunc(Number(step)));
6096
+ if (stride === 0) return [];
6097
+ const values = [];
6098
+ if (first <= last) for (let value = first; value <= last; value += stride) values.push(value);
6099
+ else for (let value = first; value >= last; value -= stride) values.push(value);
6100
+ return values;
6101
+ }
6102
+ function findRangeOperator(expr) {
6103
+ let pos = findOutsideQuotes(expr, "..");
6104
+ while (pos >= 0) {
6105
+ const partOfEllipsis = expr.startsWith("...", pos) || pos > 0 && expr[pos - 1] === ".";
6106
+ if (pos > 0 && !partOfEllipsis) return findOutsideQuotes(expr.slice(pos + 2), "|") >= 0 ? -1 : pos;
6107
+ const next = findOutsideQuotes(expr.slice(pos + 2), "..");
6108
+ pos = next >= 0 ? pos + 2 + next : -1;
6109
+ }
6110
+ return -1;
6111
+ }
6112
+ function evalRangeExpression(expr, context) {
6113
+ const pos = findRangeOperator(expr);
6114
+ if (pos < 0) return EXPR_NOT_MATCHED;
6115
+ return frondRange(evalExpr(expr.slice(0, pos).trim(), context), evalExpr(expr.slice(pos + 2).trim(), context));
6116
+ }
6117
+ function closingBracketIndex(expr) {
6118
+ let depth = 0;
6119
+ let inQuote = null;
6120
+ for (let i = 0; i < expr.length; i++) {
6121
+ const ch = expr[i];
6122
+ if (inQuote) {
6123
+ if (ch === inQuote) inQuote = null;
6124
+ } else if (ch === '"' || ch === "'") {
6125
+ inQuote = ch;
6126
+ } else if ("([{".includes(ch)) {
6127
+ depth++;
6128
+ } else if (")]}".includes(ch) && --depth === 0) {
6129
+ return i;
5966
6130
  }
5967
6131
  }
5968
- return EXPR_NOT_MATCHED;
6132
+ return -1;
6133
+ }
6134
+ function mapLiteralKey(rawKey, context) {
6135
+ const quoted = rawKey.length >= 2 && (rawKey[0] === '"' || rawKey[0] === "'") && rawKey.endsWith(rawKey[0]);
6136
+ if (quoted) return rawKey.slice(1, -1);
6137
+ return BARE_KEY_RE.test(rawKey) ? rawKey : String(evalExpr(rawKey, context));
6138
+ }
6139
+ function evalMapLiteral(inner, context) {
6140
+ const map = {};
6141
+ for (const pair of inner === "" ? [] : splitArgs(inner)) {
6142
+ const colon = findOutsideQuotes(pair, ":");
6143
+ if (colon > 0) map[mapLiteralKey(pair.slice(0, colon).trim(), context)] = evalExpr(pair.slice(colon + 1).trim(), context);
6144
+ }
6145
+ return map;
6146
+ }
6147
+ function evalCollectionLiteral(expr, context) {
6148
+ if (expr[0] !== "[" && expr[0] !== "{" || closingBracketIndex(expr) !== expr.length - 1) return EXPR_NOT_MATCHED;
6149
+ const inner = expr.slice(1, -1).trim();
6150
+ if (expr[0] === "{") return evalMapLiteral(inner, context);
6151
+ return inner === "" ? [] : splitArgs(inner).map((item) => evalExpr(item.trim(), context));
5969
6152
  }
5970
6153
  function evalFilterExpression(expr, context) {
5971
6154
  if (findOutsideQuotes(expr, "|") >= 0) {
@@ -6387,12 +6570,12 @@ function splitArgs(raw) {
6387
6570
  current += ch;
6388
6571
  continue;
6389
6572
  }
6390
- if (ch === "(" || ch === "[") {
6573
+ if (ch === "(" || ch === "[" || ch === "{") {
6391
6574
  depth++;
6392
6575
  current += ch;
6393
6576
  continue;
6394
6577
  }
6395
- if (ch === ")" || ch === "]") {
6578
+ if (ch === ")" || ch === "]" || ch === "}") {
6396
6579
  depth--;
6397
6580
  current += ch;
6398
6581
  continue;
@@ -6557,11 +6740,14 @@ function formatMatch(match, flags, width, prec, type2, arg) {
6557
6740
  return padFormattedValue(formatValue(type2, precision, arg), flags, width);
6558
6741
  }
6559
6742
  function _b64url(data) {
6560
- return data.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
6743
+ return data.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/={1,2}$/, "");
6561
6744
  }
6562
6745
  function setFormTokenSessionId(sessionId) {
6563
6746
  _formTokenSessionId = sessionId || "";
6564
6747
  }
6748
+ function setFormTokenSessionProvider(fn) {
6749
+ _formTokenSessionProvider = fn;
6750
+ }
6565
6751
  function setCspNonceProvider(fn) {
6566
6752
  _cspNonceProvider = fn;
6567
6753
  }
@@ -6586,8 +6772,9 @@ function _buildFormTokenJwt(descriptor = "") {
6586
6772
  payload.context = descriptor;
6587
6773
  }
6588
6774
  }
6589
- if (_formTokenSessionId) {
6590
- payload.session_id = _formTokenSessionId;
6775
+ const sessionId = _formTokenSessionProvider() || _formTokenSessionId;
6776
+ if (sessionId) {
6777
+ payload.session_id = sessionId;
6591
6778
  }
6592
6779
  const h2 = _b64url(Buffer.from(JSON.stringify(header)));
6593
6780
  const p = _b64url(Buffer.from(JSON.stringify(payload)));
@@ -6603,7 +6790,7 @@ function _generateFormToken(descriptor = "") {
6603
6790
  function _generateFormTokenValue(descriptor = "") {
6604
6791
  return new SafeString(_buildFormTokenJwt(descriptor));
6605
6792
  }
6606
- var SafeString, KNOWN_TAGS, TERMINATOR_TAGS, GATEABLE_TAGS, BLOCK_TAG_ENDS, JSON_UNSAFE_RE, JSON_UNSAFE_MAP, NUMERIC_RE, METHOD_CALL_RE, FN_CALL_RE, IS_NOT_RE, IS_RE, NOT_IN_RE, IN_RE, DIVISIBLE_BY_RE, FILTER_WITH_ARGS_RE, FILTER_COMPARISON_RE, TITLE_WORD_RE, STRIP_TAGS_RE, FAST_FILTERS, FORMAT_RE, LEADING_WS_RE, TRAILING_WS_RE, THOUSANDS_RE, LIVE_RE, LIVE_WS_RE, LIVE_SRC_RE, EXTENDS_RE, EXTENDS_RE_GLOBAL, filterChainCache, pathParseCache, TEMPLATE_CACHE_MAX, MEMO_CACHE_MAX, TOKEN_RE, RAW_BLOCK_RE, EXPR_NOT_MATCHED, ARITHMETIC_OPERATIONS, EXPR_EVALUATORS, expressionFormCache, VarRef, JS_SAFE_RE, MEDIA_TYPE_RE, SANDBOX_EXPR_KEYWORDS, SANDBOX_IDENT_RE, SANDBOX_STRING_RE, UNSAFE_KEYS, BUILTIN_FILTERS, _formTokenSessionId, _cspNonceProvider, Frond;
6793
+ var SafeString, KNOWN_TAGS, TERMINATOR_TAGS, GATEABLE_TAGS, BLOCK_TAG_ENDS, JSON_UNSAFE_RE, JSON_UNSAFE_MAP, NUMERIC_RE, METHOD_CALL_RE, FN_CALL_RE, IS_NOT_RE, IS_RE, NOT_IN_RE, IN_RE, DIVISIBLE_BY_RE, FILTER_WITH_ARGS_RE, FILTER_COMPARISON_RE, TITLE_WORD_RE, STRIP_TAGS_RE, FAST_FILTERS, FORMAT_RE, THOUSANDS_RE, LIVE_RE, LIVE_WS_RE, LIVE_SRC_RE, EXTENDS_RE, EXTENDS_RE_GLOBAL, filterChainCache, pathParseCache, TEMPLATE_CACHE_MAX, MEMO_CACHE_MAX, RAW_OPEN_RE, RAW_CLOSE_RE, TAG_KINDS, EXPR_NOT_MATCHED, ARITHMETIC_OPERATIONS, ARITHMETIC_LEVELS, BARE_KEY_RE, EXPR_EVALUATORS, expressionFormCache, VarRef, JS_SAFE_RE, MEDIA_TYPE_RE, SANDBOX_EXPR_KEYWORDS, SANDBOX_IDENT_RE, SANDBOX_STRING_RE, UNSAFE_KEYS, BUILTIN_FILTERS, _formTokenSessionId, _formTokenSessionProvider, _cspNonceProvider, Frond;
6607
6794
  var init_engine = __esm({
6608
6795
  "../frond/src/engine.ts"() {
6609
6796
  "use strict";
@@ -6705,7 +6892,7 @@ var init_engine = __esm({
6705
6892
  int: (value) => value ? parseInt(String(value), 10) || 0 : 0,
6706
6893
  float: (value) => value ? parseFloat(String(value)) || 0 : 0,
6707
6894
  abs: (value) => typeof value === "number" ? Math.abs(value) : value,
6708
- striptags: (value) => String(value).replace(STRIP_TAGS_RE, ""),
6895
+ striptags: (value) => stripTags(String(value)),
6709
6896
  first: (value) => Array.isArray(value) ? value[0] ?? null : null,
6710
6897
  last: (value) => Array.isArray(value) ? value[value.length - 1] ?? null : null,
6711
6898
  keys: (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? Object.keys(value) : [],
@@ -6719,20 +6906,23 @@ var init_engine = __esm({
6719
6906
  filter: (value) => Array.isArray(value) ? value.filter(Boolean) : value
6720
6907
  };
6721
6908
  FORMAT_RE = /%%|%([-+ 0]*)(\d+)?(?:\.(\d+))?([sdifFeEgGxXob])/g;
6722
- LEADING_WS_RE = /^\s+/;
6723
- TRAILING_WS_RE = /\s+$/;
6724
6909
  THOUSANDS_RE = /\B(?=(\d{3})+(?!\d))/g;
6725
6910
  LIVE_RE = /^live\s+["']([^"']+)["']([\s\S]*)$/;
6726
6911
  LIVE_WS_RE = /ws\s+["']([^"']+)["']/;
6727
6912
  LIVE_SRC_RE = /src\s+["']([^"']+)["']/;
6728
- EXTENDS_RE = /\{%[-\s]*extends\s+["'](.+?)["']\s*[-]?%\}/;
6729
- EXTENDS_RE_GLOBAL = /\{%[-\s]*extends\s+["'](.+?)["']\s*[-]?%\}/g;
6913
+ EXTENDS_RE = /\{%[-\s]*extends\s+["']([^"']+)["']\s*[-]?%\}/;
6914
+ EXTENDS_RE_GLOBAL = /\{%[-\s]*extends\s+["']([^"']+)["']\s*[-]?%\}/g;
6730
6915
  filterChainCache = /* @__PURE__ */ new Map();
6731
6916
  pathParseCache = /* @__PURE__ */ new Map();
6732
6917
  TEMPLATE_CACHE_MAX = 256;
6733
6918
  MEMO_CACHE_MAX = 1024;
6734
- TOKEN_RE = /(\{%-?\s*[\s\S]*?\s*-?%\})|(\{\{-?\s*[\s\S]*?\s*-?\}\})|(\{#[\s\S]*?#\})/g;
6735
- RAW_BLOCK_RE = /\{%-?\s*raw\s*-?%\}([\s\S]*?)\{%-?\s*endraw\s*-?%\}/g;
6919
+ RAW_OPEN_RE = /\{%-?\s*raw\s*-?%\}/g;
6920
+ RAW_CLOSE_RE = /\{%-?\s*endraw\s*-?%\}/g;
6921
+ TAG_KINDS = {
6922
+ "%": { close: "%}", type: "BLOCK" },
6923
+ "{": { close: "}}", type: "VAR" },
6924
+ "#": { close: "#}", type: "COMMENT" }
6925
+ };
6736
6926
  EXPR_NOT_MATCHED = /* @__PURE__ */ Symbol("frond-expression-not-matched");
6737
6927
  ARITHMETIC_OPERATIONS = {
6738
6928
  "+": (left, right) => left + right,
@@ -6743,10 +6933,14 @@ var init_engine = __esm({
6743
6933
  "%": (left, right) => right !== 0 ? left % right : 0,
6744
6934
  "**": (left, right) => left ** right
6745
6935
  };
6936
+ ARITHMETIC_LEVELS = [["+", "-"], ["*", "//", "/", "%"], ["**"]];
6937
+ BARE_KEY_RE = /^[A-Za-z_]\w*$/;
6746
6938
  EXPR_EVALUATORS = [
6939
+ evalCollectionLiteral,
6747
6940
  evalPrimary,
6748
6941
  evalConditional,
6749
6942
  evalConcatOrComparison,
6943
+ evalRangeExpression,
6750
6944
  evalArithmeticExpression,
6751
6945
  evalFilterExpression,
6752
6946
  evalFunctionExpression
@@ -6802,8 +6996,8 @@ var init_engine = __esm({
6802
6996
  },
6803
6997
  title: (v) => String(v).replace(TITLE_WORD_RE, (c) => c.toUpperCase()),
6804
6998
  trim: (v) => String(v).trim(),
6805
- ltrim: (v) => String(v).replace(LEADING_WS_RE, ""),
6806
- rtrim: (v) => String(v).replace(TRAILING_WS_RE, ""),
6999
+ ltrim: (v) => String(v).trimStart(),
7000
+ rtrim: (v) => String(v).trimEnd(),
6807
7001
  length: (v) => {
6808
7002
  if (Array.isArray(v)) return v.length;
6809
7003
  if (typeof v === "string") return v.length;
@@ -6844,7 +7038,7 @@ var init_engine = __esm({
6844
7038
  safe: (v) => v,
6845
7039
  escape: (v, ...a) => escapeStrategy(v, a[0] ?? "html"),
6846
7040
  e: (v, ...a) => escapeStrategy(v, a[0] ?? "html"),
6847
- striptags: (v) => String(v).replace(STRIP_TAGS_RE, ""),
7041
+ striptags: (v) => stripTags(String(v)),
6848
7042
  nl2br: (v) => new SafeString(htmlEscape(String(v)).replace(/\n/g, "<br />\n")),
6849
7043
  abs: (v) => typeof v === "number" ? Math.abs(v) : v,
6850
7044
  round: (v, decimals) => {
@@ -6957,6 +7151,7 @@ var init_engine = __esm({
6957
7151
  js_escape: (v) => new SafeString(jsEscape(v))
6958
7152
  };
6959
7153
  _formTokenSessionId = "";
7154
+ _formTokenSessionProvider = () => "";
6960
7155
  _cspNonceProvider = () => "";
6961
7156
  Frond = class _Frond {
6962
7157
  // ── Class-level registries ──────────────────────────────────
@@ -7110,6 +7305,7 @@ var init_engine = __esm({
7110
7305
  this.globals.form_token = (descriptor) => _generateFormToken(descriptor || "");
7111
7306
  this.globals.formTokenValue = (descriptor) => _generateFormTokenValue(descriptor || "");
7112
7307
  this.globals.form_token_value = (descriptor) => _generateFormTokenValue(descriptor || "");
7308
+ this.globals.range = frondRange;
7113
7309
  this.globals.dump = (value) => renderDump(value);
7114
7310
  this.globals.csp_nonce = () => _cspNonceProvider();
7115
7311
  for (const [k, v] of _Frond.classFilters) this.filters[k] = v;
@@ -7446,20 +7642,20 @@ var init_engine = __esm({
7446
7642
  }
7447
7643
  renderVarToken(tokens, index, context, output) {
7448
7644
  const [content, stripB, stripA] = stripTag(tokens[index][1]);
7449
- if (stripB && output.length > 0) output[output.length - 1] = output[output.length - 1].replace(TRAILING_WS_RE, "");
7645
+ if (stripB && output.length > 0) output[output.length - 1] = output[output.length - 1].trimEnd();
7450
7646
  const result = this.evalVar(content, context);
7451
7647
  output.push(result !== null && result !== void 0 ? String(result) : "");
7452
7648
  if (stripA && index + 1 < tokens.length && tokens[index + 1][0] === "TEXT") {
7453
- tokens[index + 1] = ["TEXT", tokens[index + 1][1].replace(LEADING_WS_RE, "")];
7649
+ tokens[index + 1] = ["TEXT", tokens[index + 1][1].trimStart()];
7454
7650
  }
7455
7651
  return index + 1;
7456
7652
  }
7457
7653
  renderBlockToken(tokens, index, context, output) {
7458
7654
  const [content, stripB, stripA] = stripTag(tokens[index][1]);
7459
- if (stripB && output.length > 0) output[output.length - 1] = output[output.length - 1].replace(TRAILING_WS_RE, "");
7655
+ if (stripB && output.length > 0) output[output.length - 1] = output[output.length - 1].trimEnd();
7460
7656
  const tag = content.split(/\s+/)[0] || "";
7461
7657
  if (stripA && index + 1 < tokens.length && tokens[index + 1][0] === "TEXT") {
7462
- tokens[index + 1] = ["TEXT", tokens[index + 1][1].replace(LEADING_WS_RE, "")];
7658
+ tokens[index + 1] = ["TEXT", tokens[index + 1][1].trimStart()];
7463
7659
  }
7464
7660
  let next;
7465
7661
  if (tag === "if" && this.tagPermitted(tag)) {
@@ -7476,7 +7672,7 @@ var init_engine = __esm({
7476
7672
  next = block.next;
7477
7673
  }
7478
7674
  if (stripA && next < tokens.length && tokens[next][0] === "TEXT") {
7479
- tokens[next] = ["TEXT", tokens[next][1].replace(LEADING_WS_RE, "")];
7675
+ tokens[next] = ["TEXT", tokens[next][1].trimStart()];
7480
7676
  }
7481
7677
  return next;
7482
7678
  }
@@ -7735,7 +7931,7 @@ var init_engine = __esm({
7735
7931
  pushIfBranch(branches, condition, branchTokens, stripBefore) {
7736
7932
  if (stripBefore && branchTokens.length > 0 && branchTokens[branchTokens.length - 1][0] === "TEXT") {
7737
7933
  const last = branchTokens[branchTokens.length - 1];
7738
- branchTokens[branchTokens.length - 1] = ["TEXT", last[1].replace(TRAILING_WS_RE, "")];
7934
+ branchTokens[branchTokens.length - 1] = ["TEXT", last[1].trimEnd()];
7739
7935
  }
7740
7936
  branches.push([condition, branchTokens]);
7741
7937
  }
@@ -7763,7 +7959,7 @@ var init_engine = __esm({
7763
7959
  } else if (tag === "endif") {
7764
7960
  this.pushIfBranch(branches, currentCond, currentTokens, tagStripB);
7765
7961
  if (tagStripA && i + 1 < tokens.length && tokens[i + 1][0] === "TEXT") {
7766
- tokens[i + 1] = ["TEXT", tokens[i + 1][1].replace(LEADING_WS_RE, "")];
7962
+ tokens[i + 1] = ["TEXT", tokens[i + 1][1].trimStart()];
7767
7963
  }
7768
7964
  return { branches, next: i + 1 };
7769
7965
  } else if ((tag === "elseif" || tag === "elif") && depth === 0) {
@@ -9412,7 +9608,8 @@ var init_middleware = __esm({
9412
9608
  "Content-Security-Policy": resolveCspHeader(currentCspNonce()),
9413
9609
  "Referrer-Policy": process.env.TINA4_REFERRER_POLICY ?? "strict-origin-when-cross-origin",
9414
9610
  "X-XSS-Protection": "0",
9415
- "Permissions-Policy": process.env.TINA4_PERMISSIONS_POLICY ?? "camera=(), microphone=(), geolocation=()"
9611
+ "Permissions-Policy": process.env.TINA4_PERMISSIONS_POLICY ?? "camera=(), microphone=(), geolocation=()",
9612
+ "Cross-Origin-Opener-Policy": process.env.TINA4_COOP ?? "same-origin-allow-popups"
9416
9613
  };
9417
9614
  }
9418
9615
  static beforeSecurity(req2, res) {
@@ -9429,7 +9626,7 @@ var init_middleware = __esm({
9429
9626
  if (process.env.TINA4_CSP === void 0) {
9430
9627
  _SecurityHeadersMiddleware.warnCspDefaultOnce();
9431
9628
  }
9432
- for (const name of ["Content-Security-Policy", "Referrer-Policy", "X-XSS-Protection", "Permissions-Policy"]) {
9629
+ for (const name of ["Content-Security-Policy", "Referrer-Policy", "X-XSS-Protection", "Permissions-Policy", "Cross-Origin-Opener-Policy"]) {
9433
9630
  res.header(name, canonical[name]);
9434
9631
  }
9435
9632
  return [req2, res];
@@ -9513,7 +9710,7 @@ var init_middleware = __esm({
9513
9710
  });
9514
9711
 
9515
9712
  // ../core/src/request.ts
9516
- import { mkdirSync as mkdirSync3, realpathSync as realpathSync2, writeFileSync as writeFileSync2 } from "node:fs";
9713
+ import { closeSync as closeSync3, constants as constants2, fstatSync as fstatSync2, ftruncateSync, lstatSync, mkdirSync as mkdirSync3, openSync as openSync3, realpathSync as realpathSync2, unlinkSync as unlinkSync3, writeFileSync as writeFileSync2 } from "node:fs";
9517
9714
  import { dirname as dirname3, join as join6 } from "node:path";
9518
9715
  function makeCaseInsensitiveHeaders(raw) {
9519
9716
  return new Proxy(raw, {
@@ -9549,7 +9746,8 @@ function createRequest(req2) {
9549
9746
  try {
9550
9747
  const url = new URL(req2.url ?? "/", `${proto}://${host}`);
9551
9748
  for (const [key, value] of url.searchParams) {
9552
- query[key] = value;
9749
+ if (isUnsafeFieldName(key)) continue;
9750
+ Reflect.set(query, key, value);
9553
9751
  }
9554
9752
  path10 = url.pathname;
9555
9753
  queryString = url.search.replace(/^\?/, "");
@@ -9561,7 +9759,8 @@ function createRequest(req2) {
9561
9759
  queryString = questionIdx >= 0 ? rawTarget.slice(questionIdx + 1) : "";
9562
9760
  try {
9563
9761
  for (const [key, value] of new URLSearchParams(queryString)) {
9564
- query[key] = value;
9762
+ if (isUnsafeFieldName(key)) continue;
9763
+ Reflect.set(query, key, value);
9565
9764
  }
9566
9765
  } catch {
9567
9766
  }
@@ -9580,7 +9779,8 @@ function createRequest(req2) {
9580
9779
  if (cookieHeader) {
9581
9780
  for (const pair of cookieHeader.split(";")) {
9582
9781
  const [k, ...v] = pair.trim().split("=");
9583
- if (k) cookies[k.trim()] = v.join("=").trim();
9782
+ const name = k ? k.trim() : "";
9783
+ if (name && !isUnsafeFieldName(name)) Reflect.set(cookies, name, v.join("=").trim());
9584
9784
  }
9585
9785
  }
9586
9786
  w.cookies = cookies;
@@ -9671,13 +9871,7 @@ async function parseBody(req2) {
9671
9871
  req2.body = str;
9672
9872
  }
9673
9873
  } else if (contentType.includes("application/x-www-form-urlencoded")) {
9674
- const str = raw.toString("utf-8");
9675
- const params = new URLSearchParams(str);
9676
- const obj = {};
9677
- for (const [key, value] of params) {
9678
- obj[key] = value;
9679
- }
9680
- req2.body = obj;
9874
+ req2.body = nestFormFields([...new URLSearchParams(raw.toString("utf-8"))]);
9681
9875
  } else {
9682
9876
  req2.body = raw.toString("utf-8");
9683
9877
  }
@@ -9687,7 +9881,7 @@ function extractBoundary(contentType) {
9687
9881
  return match ? match[1] ?? match[2] : null;
9688
9882
  }
9689
9883
  function parseMultipart(body, boundary) {
9690
- const fields = {};
9884
+ const pairs = [];
9691
9885
  const files = {};
9692
9886
  const delimiter2 = Buffer.from(`--${boundary}`);
9693
9887
  const closeDelimiter = Buffer.from(`--${boundary}--`);
@@ -9695,7 +9889,7 @@ function parseMultipart(body, boundary) {
9695
9889
  const doubleCrlf = Buffer.from("\r\n\r\n");
9696
9890
  let offset = 0;
9697
9891
  const firstIdx = bufferIndexOf(body, delimiter2, offset);
9698
- if (firstIdx === -1) return { fields, files };
9892
+ if (firstIdx === -1) return { fields: {}, files };
9699
9893
  offset = firstIdx + delimiter2.length;
9700
9894
  if (body[offset] === 13 && body[offset + 1] === 10) {
9701
9895
  offset += 2;
@@ -9719,14 +9913,15 @@ function parseMultipart(body, boundary) {
9719
9913
  content: Buffer.from(content),
9720
9914
  size: content.length
9721
9915
  };
9722
- if (files[disposition.name]) {
9916
+ if (isUnsafeFieldName(disposition.name)) {
9917
+ } else if (files[disposition.name]) {
9723
9918
  const existing = files[disposition.name];
9724
- files[disposition.name] = Array.isArray(existing) ? [...existing, file] : [existing, file];
9919
+ Reflect.set(files, disposition.name, Array.isArray(existing) ? [...existing, file] : [existing, file]);
9725
9920
  } else {
9726
- files[disposition.name] = file;
9921
+ Reflect.set(files, disposition.name, file);
9727
9922
  }
9728
9923
  } else if (disposition.name) {
9729
- fields[disposition.name] = content.toString("utf-8");
9924
+ pairs.push([disposition.name, content.toString("utf-8")]);
9730
9925
  }
9731
9926
  offset = nextDelimIdx + delimiter2.length;
9732
9927
  if (body[offset] === 45 && body[offset + 1] === 45) {
@@ -9736,7 +9931,7 @@ function parseMultipart(body, boundary) {
9736
9931
  offset += 2;
9737
9932
  }
9738
9933
  }
9739
- return { fields, files };
9934
+ return { fields: nestFormFields(pairs), files };
9740
9935
  }
9741
9936
  function saveUpload(file, targetDir, filename) {
9742
9937
  const raw = String(filename ?? file.filename ?? "");
@@ -9752,7 +9947,21 @@ function saveUpload(file, targetDir, filename) {
9752
9947
  if (realParent !== realDir) {
9753
9948
  throw new Error(`refusing to write outside ${targetDir}: ${JSON.stringify(raw)}`);
9754
9949
  }
9755
- writeFileSync2(dest, file.content);
9950
+ if (lstatSync(dest, { throwIfNoEntry: false })?.isSymbolicLink()) unlinkSync3(dest);
9951
+ const flags = constants2.O_WRONLY | constants2.O_CREAT | (constants2.O_NOFOLLOW ?? 0);
9952
+ let fd = openSync3(dest, flags, 384);
9953
+ try {
9954
+ if (fstatSync2(fd).nlink > 1) {
9955
+ closeSync3(fd);
9956
+ fd = -1;
9957
+ unlinkSync3(dest);
9958
+ fd = openSync3(dest, flags | constants2.O_EXCL, 384);
9959
+ }
9960
+ ftruncateSync(fd, 0);
9961
+ writeFileSync2(fd, file.content);
9962
+ } finally {
9963
+ if (fd >= 0) closeSync3(fd);
9964
+ }
9756
9965
  return dest;
9757
9966
  }
9758
9967
  function bufferIndexOf(haystack, needle, offset) {
@@ -9777,10 +9986,98 @@ function parseDisposition(headers) {
9777
9986
  };
9778
9987
  }
9779
9988
  function parsePartContentType(headers) {
9780
- const match = headers.match(/Content-Type:\s*(.+?)(?:\r?\n|$)/i);
9781
- return match?.[1]?.trim() ?? null;
9989
+ const match = headers.match(/Content-Type:([^\r\n]*)/i);
9990
+ const value = match?.[1]?.trim();
9991
+ return value ? value : null;
9992
+ }
9993
+ function nestFormFields(pairs) {
9994
+ const kept = pairs.filter(([name]) => !/(^|[[\]])__proto__([[\]]|$)/.test(name));
9995
+ if (kept.length > FORM_FIELD_LIMIT) return Object.fromEntries(kept);
9996
+ const nested = /* @__PURE__ */ new WeakSet();
9997
+ const node = () => {
9998
+ const created = /* @__PURE__ */ Object.create(null);
9999
+ nested.add(created);
10000
+ return created;
10001
+ };
10002
+ const isNode = (value) => typeof value === "object" && value !== null && nested.has(value);
10003
+ const own = (params, key) => Object.prototype.hasOwnProperty.call(params, key) ? params[key] : void 0;
10004
+ const list = (params, key) => {
10005
+ let current = own(params, key);
10006
+ if (current === void 0) {
10007
+ current = [];
10008
+ Reflect.set(params, key, current);
10009
+ }
10010
+ if (!Array.isArray(current)) throw new RangeError(`expected an array for '${key}'`);
10011
+ return current;
10012
+ };
10013
+ const object = (params, key) => {
10014
+ let current = own(params, key);
10015
+ if (current === void 0) {
10016
+ current = node();
10017
+ Reflect.set(params, key, current);
10018
+ }
10019
+ if (!isNode(current)) throw new RangeError(`expected an object for '${key}'`);
10020
+ return current;
10021
+ };
10022
+ const hasKey = (params, key) => {
10023
+ if (key.includes("[]")) return false;
10024
+ let level = params;
10025
+ for (const part of key.split(/[[\]]+/).filter(Boolean)) {
10026
+ if (!isNode(level) || own(level, part) === void 0) return false;
10027
+ level = level[part];
10028
+ }
10029
+ return true;
10030
+ };
10031
+ const splitName = (name, depth) => {
10032
+ if (depth === 0) {
10033
+ const start2 = name.indexOf("[", 1);
10034
+ return start2 === -1 ? [name, ""] : [name.slice(0, start2), name.slice(start2)];
10035
+ }
10036
+ if (name.startsWith("[]")) return ["[]", name.slice(2)];
10037
+ const close = name.indexOf("]", 1);
10038
+ return name.startsWith("[") && close !== -1 ? [name.slice(1, close), name.slice(close + 1)] : [name, ""];
10039
+ };
10040
+ const putListItem = (items, after, value, depth) => {
10041
+ let childKey = after[2] === "[" && after.endsWith("]") ? after.slice(3, -1) : "";
10042
+ if (childKey === "" || childKey.includes("[") || childKey.includes("]")) childKey = after.slice(2);
10043
+ const last = items[items.length - 1];
10044
+ if (isNode(last) && !hasKey(last, childKey)) put2(last, childKey, value, depth + 1);
10045
+ else items.push(put2(node(), childKey, value, depth + 1));
10046
+ };
10047
+ const put2 = (params, name, value, depth) => {
10048
+ const [key, after] = splitName(name, depth);
10049
+ if (key === "") return void 0;
10050
+ if (after === "" && key === "[]" && depth !== 0) return [value];
10051
+ if (after === "") Reflect.set(params, key, value);
10052
+ else if (after === "[") Reflect.set(params, name, value);
10053
+ else if (after === "[]") list(params, key).push(value);
10054
+ else if (after.startsWith("[]")) putListItem(list(params, key), after, value, depth);
10055
+ else put2(object(params, key), after, value, depth + 1);
10056
+ return params;
10057
+ };
10058
+ const tooDeep = (name) => {
10059
+ let count = 0;
10060
+ for (let at = name.indexOf("["); at !== -1; at = name.indexOf("[", at + 1)) {
10061
+ if (++count >= FORM_DEPTH_LIMIT) return true;
10062
+ }
10063
+ return false;
10064
+ };
10065
+ const fields = node();
10066
+ for (const [name, value] of kept) {
10067
+ if (name.length > FORM_NAME_LIMIT || tooDeep(name)) {
10068
+ Reflect.set(fields, name, value);
10069
+ continue;
10070
+ }
10071
+ try {
10072
+ put2(fields, name, value, 0);
10073
+ } catch (error2) {
10074
+ if (!(error2 instanceof RangeError)) throw error2;
10075
+ Reflect.set(fields, name, value);
10076
+ }
10077
+ }
10078
+ return fields;
9782
10079
  }
9783
- var DEFAULT_MAX_UPLOAD_SIZE, warnedLimits, PayloadTooLargeError;
10080
+ var DEFAULT_MAX_UPLOAD_SIZE, warnedLimits, PayloadTooLargeError, FORM_DEPTH_LIMIT, FORM_FIELD_LIMIT, FORM_NAME_LIMIT, isUnsafeFieldName;
9784
10081
  var init_request = __esm({
9785
10082
  "../core/src/request.ts"() {
9786
10083
  "use strict";
@@ -9795,6 +10092,10 @@ var init_request = __esm({
9795
10092
  this.name = "PayloadTooLargeError";
9796
10093
  }
9797
10094
  };
10095
+ FORM_DEPTH_LIMIT = 32;
10096
+ FORM_FIELD_LIMIT = 4096;
10097
+ FORM_NAME_LIMIT = 1024;
10098
+ isUnsafeFieldName = (key) => key === "__proto__" || key === "constructor" || key === "prototype";
9798
10099
  }
9799
10100
  });
9800
10101
 
@@ -10076,8 +10377,8 @@ var init_ssoIdentity = __esm({
10076
10377
  });
10077
10378
 
10078
10379
  // ../core/src/authGate.ts
10079
- function enforceRouteAuth(req2, res, match, isDevAdmin) {
10080
- if (!(match.secure === true && match.noAuth !== true && !isDevAdmin)) {
10380
+ function enforceRouteAuth(req2, res, match) {
10381
+ if (!(match.secure === true && match.noAuth !== true)) {
10081
10382
  return false;
10082
10383
  }
10083
10384
  const authHeader = req2.headers.authorization ?? "";
@@ -10301,7 +10602,7 @@ var init_routeDiscovery = __esm({
10301
10602
 
10302
10603
  // ../core/src/portTakeover.ts
10303
10604
  import { execFileSync } from "node:child_process";
10304
- import { existsSync as existsSync7, readFileSync as readFileSync5, writeFileSync as writeFileSync4, mkdirSync as mkdirSync5, unlinkSync as unlinkSync3 } from "node:fs";
10605
+ import { existsSync as existsSync7, readFileSync as readFileSync5, writeFileSync as writeFileSync4, mkdirSync as mkdirSync5, unlinkSync as unlinkSync4 } from "node:fs";
10305
10606
  import { join as join8 } from "node:path";
10306
10607
  function isTruthy2(value) {
10307
10608
  return ["true", "1", "yes", "on"].includes(String(value ?? "").trim().toLowerCase());
@@ -10355,7 +10656,7 @@ function readPidfile(port, baseDir) {
10355
10656
  }
10356
10657
  function removePidfile(port, baseDir) {
10357
10658
  try {
10358
- unlinkSync3(pidfilePath(port, baseDir));
10659
+ unlinkSync4(pidfilePath(port, baseDir));
10359
10660
  } catch {
10360
10661
  }
10361
10662
  }
@@ -10456,21 +10757,6 @@ var init_portTakeover = __esm({
10456
10757
  }
10457
10758
  });
10458
10759
 
10459
- // ../core/src/etag.ts
10460
- function etagMatches(ifNoneMatch, etag) {
10461
- const strip = (tag) => tag.trim().replace(/^W\//, "");
10462
- const target = strip(etag);
10463
- return ifNoneMatch.split(",").some((candidate) => {
10464
- const trimmed = candidate.trim();
10465
- return trimmed === "*" || strip(trimmed) === target;
10466
- });
10467
- }
10468
- var init_etag = __esm({
10469
- "../core/src/etag.ts"() {
10470
- "use strict";
10471
- }
10472
- });
10473
-
10474
10760
  // ../core/src/sessionHandlers/syncBridge.ts
10475
10761
  import { Worker } from "node:worker_threads";
10476
10762
  function getBridge(key, workerSource, workerData) {
@@ -11839,14 +12125,18 @@ __export(session_exports, {
11839
12125
  Session: () => Session,
11840
12126
  VALID_SESSION_BACKENDS: () => VALID_SESSION_BACKENDS,
11841
12127
  buildSessionCookie: () => buildSessionCookie,
12128
+ currentFormTokenSessionId: () => currentFormTokenSessionId,
11842
12129
  isSecureScheme: () => isSecureScheme,
11843
12130
  isValidSessionId: () => isValidSessionId,
12131
+ runWithFormTokenSession: () => runWithFormTokenSession,
11844
12132
  sessionCookieName: () => sessionCookieName,
11845
12133
  sessionCookieToSend: () => sessionCookieToSend,
11846
- sessionStrictMode: () => sessionStrictMode
12134
+ sessionStrictMode: () => sessionStrictMode,
12135
+ setFormTokenSession: () => setFormTokenSession
11847
12136
  });
12137
+ import { AsyncLocalStorage as AsyncLocalStorage3 } from "node:async_hooks";
11848
12138
  import { createHash as createHash5, randomBytes as randomBytes4 } from "node:crypto";
11849
- import { existsSync as existsSync8, mkdirSync as mkdirSync6, readFileSync as readFileSync6, writeFileSync as writeFileSync5, unlinkSync as unlinkSync4, readdirSync as readdirSync3 } from "node:fs";
12139
+ import { existsSync as existsSync8, mkdirSync as mkdirSync6, readFileSync as readFileSync6, writeFileSync as writeFileSync5, unlinkSync as unlinkSync5, readdirSync as readdirSync3 } from "node:fs";
11850
12140
  import { join as join9 } from "node:path";
11851
12141
  function isValidSessionId(sessionId) {
11852
12142
  return typeof sessionId === "string" && SESSION_ID_PATTERN.test(sessionId);
@@ -11912,7 +12202,21 @@ function sessionCookieToSend(sess, existingSid, rawReq, rawRes) {
11912
12202
  const socketEncrypted = rawReq.socket?.encrypted === true;
11913
12203
  return buildSessionCookie(newSid, ttl, void 0, forwardedProto, socketEncrypted);
11914
12204
  }
11915
- var SESSION_ID_PATTERN, VALID_SESSION_BACKENDS, CANONICAL_SESSION_BACKENDS, RETIRED_SESSION_BACKENDS, FileSessionHandler, RedisSessionHandler, FLASH_PREFIX, Session;
12205
+ function runWithFormTokenSession(fn) {
12206
+ return sessionStore.run({ session: null }, fn);
12207
+ }
12208
+ function setFormTokenSession(session) {
12209
+ const store = sessionStore.getStore();
12210
+ if (store) store.session = session;
12211
+ }
12212
+ function currentFormTokenSessionId() {
12213
+ const session = sessionStore.getStore()?.session;
12214
+ const sid = session?.getSessionId();
12215
+ if (!session || !sid) return "";
12216
+ if (session.isFresh()) session.set("_tina4_csrf", true);
12217
+ return sid;
12218
+ }
12219
+ var SESSION_ID_PATTERN, VALID_SESSION_BACKENDS, CANONICAL_SESSION_BACKENDS, RETIRED_SESSION_BACKENDS, FileSessionHandler, RedisSessionHandler, FLASH_PREFIX, Session, sessionStore;
11916
12220
  var init_session = __esm({
11917
12221
  "../core/src/session.ts"() {
11918
12222
  "use strict";
@@ -11996,7 +12300,7 @@ var init_session = __esm({
11996
12300
  const wrapper = JSON.parse(raw);
11997
12301
  if (wrapper._expires && wrapper._expires > 0 && Date.now() / 1e3 > wrapper._expires) {
11998
12302
  try {
11999
- unlinkSync4(filePath);
12303
+ unlinkSync5(filePath);
12000
12304
  } catch {
12001
12305
  }
12002
12306
  return null;
@@ -12015,7 +12319,7 @@ var init_session = __esm({
12015
12319
  destroy(sessionId) {
12016
12320
  const filePath = this.filePath(sessionId);
12017
12321
  try {
12018
- if (existsSync8(filePath)) unlinkSync4(filePath);
12322
+ if (existsSync8(filePath)) unlinkSync5(filePath);
12019
12323
  } catch {
12020
12324
  }
12021
12325
  }
@@ -12031,11 +12335,11 @@ var init_session = __esm({
12031
12335
  const raw = readFileSync6(fullPath, "utf-8");
12032
12336
  const wrapper = JSON.parse(raw);
12033
12337
  if (wrapper._expires && wrapper._expires > 0 && now > wrapper._expires) {
12034
- unlinkSync4(fullPath);
12338
+ unlinkSync5(fullPath);
12035
12339
  }
12036
12340
  } catch {
12037
12341
  try {
12038
- unlinkSync4(fullPath);
12342
+ unlinkSync5(fullPath);
12039
12343
  } catch {
12040
12344
  }
12041
12345
  }
@@ -12555,6 +12859,22 @@ var init_session = __esm({
12555
12859
  this.loaded = /* @__PURE__ */ new Map();
12556
12860
  }
12557
12861
  };
12862
+ sessionStore = new AsyncLocalStorage3();
12863
+ }
12864
+ });
12865
+
12866
+ // ../core/src/etag.ts
12867
+ function etagMatches(ifNoneMatch, etag) {
12868
+ const strip = (tag) => tag.trim().replace(/^W\//, "");
12869
+ const target = strip(etag);
12870
+ return ifNoneMatch.split(",").some((candidate) => {
12871
+ const trimmed = candidate.trim();
12872
+ return trimmed === "*" || strip(trimmed) === target;
12873
+ });
12874
+ }
12875
+ var init_etag = __esm({
12876
+ "../core/src/etag.ts"() {
12877
+ "use strict";
12558
12878
  }
12559
12879
  });
12560
12880
 
@@ -12708,6 +13028,7 @@ async function sessionAutoStart(rawReq, rawRes, req2) {
12708
13028
  return;
12709
13029
  }
12710
13030
  req2.session = sess;
13031
+ setFormTokenSession(sess);
12711
13032
  const origEnd = rawRes.end.bind(rawRes);
12712
13033
  let finalised = false;
12713
13034
  rawRes.end = function(...args) {
@@ -12736,6 +13057,7 @@ var _resetRequestCaches, COMPRESSIBLE_PREFIXES;
12736
13057
  var init_dispatchPipeline = __esm({
12737
13058
  "../core/src/dispatchPipeline.ts"() {
12738
13059
  "use strict";
13060
+ init_session();
12739
13061
  init_logger();
12740
13062
  init_etag();
12741
13063
  COMPRESSIBLE_PREFIXES = [
@@ -12885,14 +13207,21 @@ function parseStack(stack) {
12885
13207
  const frames = [];
12886
13208
  const lines = stack.split("\n");
12887
13209
  for (const line of lines) {
12888
- let match = line.match(/^\s*at\s+(.+?)\s+\((.+?):(\d+):(\d+)\)/);
12889
- if (match) {
12890
- frames.push({ func: match[1], file: match[2], line: parseInt(match[3], 10), column: parseInt(match[4], 10) });
12891
- continue;
13210
+ const t = line.trim();
13211
+ if (!t.startsWith("at ")) continue;
13212
+ const rest = t.slice(3);
13213
+ let func = "{anonymous}";
13214
+ let loc = rest;
13215
+ if (rest.endsWith(")")) {
13216
+ const open = rest.lastIndexOf(" (");
13217
+ if (open >= 0) {
13218
+ func = rest.slice(0, open);
13219
+ loc = rest.slice(open + 2, -1);
13220
+ }
12892
13221
  }
12893
- match = line.match(/^\s*at\s+(.+?):(\d+):(\d+)/);
12894
- if (match) {
12895
- frames.push({ func: "{anonymous}", file: match[1], line: parseInt(match[2], 10), column: parseInt(match[3], 10) });
13222
+ const lc = loc.match(/:(\d+):(\d+)$/);
13223
+ if (lc && lc.index !== void 0) {
13224
+ frames.push({ func, file: loc.slice(0, lc.index), line: parseInt(lc[1], 10), column: parseInt(lc[2], 10) });
12896
13225
  }
12897
13226
  }
12898
13227
  return frames;
@@ -13217,7 +13546,7 @@ var init_rateLimiter = __esm({
13217
13546
  });
13218
13547
 
13219
13548
  // ../core/src/devMailbox.ts
13220
- import { mkdirSync as mkdirSync7, readdirSync as readdirSync4, readFileSync as readFileSync9, writeFileSync as writeFileSync6, unlinkSync as unlinkSync5, existsSync as existsSync9 } from "node:fs";
13549
+ import { mkdirSync as mkdirSync7, readdirSync as readdirSync4, readFileSync as readFileSync9, writeFileSync as writeFileSync6, unlinkSync as unlinkSync6, existsSync as existsSync9 } from "node:fs";
13221
13550
  import { join as join11 } from "node:path";
13222
13551
  import { randomUUID } from "node:crypto";
13223
13552
  var DevMailbox;
@@ -13349,7 +13678,7 @@ var init_devMailbox = __esm({
13349
13678
  const filePath = join11(this.mailboxDir, folder, `${msgId}.json`);
13350
13679
  if (existsSync9(filePath)) {
13351
13680
  try {
13352
- unlinkSync5(filePath);
13681
+ unlinkSync6(filePath);
13353
13682
  deleted = true;
13354
13683
  } catch {
13355
13684
  }
@@ -13368,7 +13697,7 @@ var init_devMailbox = __esm({
13368
13697
  if (existsSync9(dir)) {
13369
13698
  const files = readdirSync4(dir).filter((file) => file.endsWith(".json"));
13370
13699
  for (const file of files) {
13371
- unlinkSync5(join11(dir, file));
13700
+ unlinkSync6(join11(dir, file));
13372
13701
  }
13373
13702
  }
13374
13703
  } catch {
@@ -13787,26 +14116,31 @@ function parseFlags(args, booleanFlags) {
13787
14116
  const positional = [];
13788
14117
  let i = 0;
13789
14118
  while (i < args.length) {
13790
- const arg = args[i];
13791
- if (arg.startsWith("--")) {
13792
- const key = arg.slice(2);
13793
- if (booleanFlags?.has(key)) {
13794
- flags[key] = true;
13795
- i += 1;
13796
- } else if (i + 1 < args.length && !args[i + 1].startsWith("--")) {
13797
- flags[key] = args[i + 1];
13798
- i += 2;
13799
- } else {
13800
- flags[key] = true;
13801
- i += 1;
13802
- }
14119
+ if (args[i].startsWith("--")) {
14120
+ i += readFlag(args, i, flags, booleanFlags);
13803
14121
  } else {
13804
- positional.push(arg);
14122
+ positional.push(args[i]);
13805
14123
  i += 1;
13806
14124
  }
13807
14125
  }
13808
14126
  return { flags, positional };
13809
14127
  }
14128
+ function readFlag(args, i, flags, booleanFlags) {
14129
+ const arg = args[i];
14130
+ const eq = arg.indexOf("=");
14131
+ if (eq !== -1) {
14132
+ flags[arg.slice(2, eq)] = arg.slice(eq + 1);
14133
+ return 1;
14134
+ }
14135
+ const key = arg.slice(2);
14136
+ const next = args[i + 1];
14137
+ if (!booleanFlags?.has(key) && next !== void 0 && !next.startsWith("--")) {
14138
+ flags[key] = next;
14139
+ return 2;
14140
+ }
14141
+ flags[key] = true;
14142
+ return 1;
14143
+ }
13810
14144
  var init_util = __esm({
13811
14145
  "../cli/src/util.ts"() {
13812
14146
  "use strict";
@@ -13819,6 +14153,7 @@ __export(generate_exports, {
13819
14153
  DEFAULT_FIELDS: () => DEFAULT_FIELDS,
13820
14154
  GENERATORS: () => GENERATORS,
13821
14155
  RESOLUTION_ENVELOPE_VERSION: () => RESOLUTION_ENVELOPE_VERSION,
14156
+ RESOLUTION_FLAGS: () => RESOLUTION_FLAGS,
13822
14157
  SQL_RESERVED_TABLE_NAMES: () => SQL_RESERVED_TABLE_NAMES,
13823
14158
  aiFill: () => aiFill,
13824
14159
  currentResolution: () => currentResolution,
@@ -14135,6 +14470,10 @@ async function generate(what, name, extraArgs = []) {
14135
14470
  extraArgs = [name, ...extraArgs];
14136
14471
  name = "";
14137
14472
  }
14473
+ if (GENERATORS[what] && !noNameGenerators.has(what) && name.startsWith("-")) {
14474
+ console.log(`Invalid ${what} name: '${name}' - names can't start with '-'.`);
14475
+ process.exit(1);
14476
+ }
14138
14477
  if (!noNameGenerators.has(what) && !name) {
14139
14478
  console.error(` Usage: tina4nodejs generate ${what} <name> [options]`);
14140
14479
  process.exit(1);
@@ -14451,7 +14790,7 @@ function generateCrud(name, flags) {
14451
14790
  if (!__resolution.jsonMode) console.log(`
14452
14791
  Generating CRUD for ${name}...
14453
14792
  `);
14454
- generateModel(name, flags, false);
14793
+ if (!flags["skip-model"]) generateModel(name, flags, false);
14455
14794
  generateCrudAdminRoute(name, table2, isPublic);
14456
14795
  if (!flags["no-templates"]) copyCrudTemplates();
14457
14796
  generateCrudGateTest(name, table2, isPublic);
@@ -15761,7 +16100,7 @@ for (const stmt of statements(downSql)) db.execute(stmt);
15761
16100
  assert("DOWN drops the ${table2} table", db.tableExists("${table2}") === false);`;
15762
16101
  writeTest(`${table2}_migration`, standaloneTest(doc, body));
15763
16102
  }
15764
- var FIELD_TYPE_MAP, SQL_RESERVED_TABLE_NAMES, RESOLUTION_ENVELOPE_VERSION, __resolution, TINA4_EDIT_MARKER, DEFAULT_FIELDS, GENERATORS, GENERATOR_LIST, NEXT_STEPS;
16103
+ var FIELD_TYPE_MAP, SQL_RESERVED_TABLE_NAMES, RESOLUTION_ENVELOPE_VERSION, __resolution, TINA4_EDIT_MARKER, DEFAULT_FIELDS, GENERATORS, RESOLUTION_FLAGS, GENERATOR_LIST, NEXT_STEPS;
15765
16104
  var init_generate = __esm({
15766
16105
  "../cli/src/commands/generate.ts"() {
15767
16106
  "use strict";
@@ -15874,22 +16213,23 @@ var init_generate = __esm({
15874
16213
  TINA4_EDIT_MARKER = /^\s*(?:\/\/|--|\{#|#)\s*tina4:edit\s+(.+?)(?:\s*#\})?\s*$/;
15875
16214
  DEFAULT_FIELDS = [["name", "string"]];
15876
16215
  GENERATORS = {
15877
- model: { handler: generateModel, usage: '<Name> [--fields "name:string,price:float"] [--table-name <name>]', summary: "ORM model + matching migration" },
15878
- route: { handler: generateRoute, usage: "<name> [--model Name] [--public]", summary: "CRUD route file, secure by default (--public opens writes)" },
15879
- crud: { handler: generateCrud, usage: '<Name> [--fields "..."] [--public] [--no-templates]', summary: "Model + migration + AutoCrud-backed admin page (toCrud) + editable crud/ templates + gate test" },
15880
- migration: { handler: (n, f) => generateMigration(n, f, void 0, void 0, !f["no-test"]), usage: "<description>", summary: "Timestamped migration file (UP/DOWN)" },
15881
- middleware: { handler: generateMiddleware, usage: "<Name>", summary: "Middleware with before/after hooks" },
15882
- test: { handler: generateTest, usage: "<name> [--model Name]", summary: "Test file" },
15883
- form: { handler: generateForm, usage: '<Name> [--fields "..."]', summary: "Form template with inputs matching model fields" },
15884
- view: { handler: generateView, usage: '<Name> [--fields "..."]', summary: "List + detail view templates" },
15885
- auth: { handler: (_n, f) => generateAuth(f), usage: "", summary: "Login/register routes (public) + User model + templates" },
15886
- service: { handler: generateService, usage: '<Name> [--every 5m | --cron "..."]', summary: "Scheduled ServiceRunner task (src/services/)" },
15887
- queue: { handler: generateQueue, usage: "<topic>", summary: "Producer + consumer daemon worker (src/services/)" },
15888
- validator: { handler: generateValidator, usage: "<Name>", summary: "Request-body Validator (src/validators/)" },
15889
- seeder: { handler: generateSeeder, usage: "<Model>", summary: "FakeData + seedOrm seeder (src/seeds/)" },
15890
- websocket: { handler: generateWebsocket, usage: "<path>", summary: "websocket() handler (src/routes/)" },
15891
- listener: { handler: generateListener, usage: "<event>", summary: "Events.on(event) listener (src/listeners/)" }
15892
- };
16216
+ model: { handler: generateModel, flags: { fields: true, "table-name": true, "no-migration": false }, usage: '<Name> [--fields "name:string,price:float"] [--table-name <name>]', summary: "ORM model + matching migration" },
16217
+ route: { handler: generateRoute, flags: { model: true, public: false, "table-name": true }, usage: "<name> [--model Name] [--public]", summary: "CRUD route file, secure by default (--public opens writes)" },
16218
+ crud: { handler: generateCrud, flags: { fields: true, "table-name": true, public: false, "no-templates": false, "no-migration": false, "skip-model": false }, usage: '<Name> [--fields "..."] [--public] [--no-templates] [--skip-model]', summary: "Model + migration + AutoCrud-backed admin page (toCrud) + editable crud/ templates + gate test" },
16219
+ migration: { handler: (n, f) => generateMigration(n, f, void 0, void 0, !f["no-test"]), flags: { fields: true, "table-name": true, "no-test": false }, usage: "<description>", summary: "Timestamped migration file (UP/DOWN)" },
16220
+ middleware: { handler: generateMiddleware, flags: {}, usage: "<Name>", summary: "Middleware with before/after hooks" },
16221
+ test: { handler: generateTest, flags: { model: true, public: false, "secure-writes": false }, usage: "<name> [--model Name]", summary: "Test file" },
16222
+ form: { handler: generateForm, flags: { fields: true, "table-name": true }, usage: '<Name> [--fields "..."]', summary: "Form template with inputs matching model fields" },
16223
+ view: { handler: generateView, flags: { fields: true, "table-name": true }, usage: '<Name> [--fields "..."]', summary: "List + detail view templates" },
16224
+ auth: { handler: (_n, f) => generateAuth(f), flags: {}, usage: "", summary: "Login/register routes (public) + User model + templates" },
16225
+ service: { handler: generateService, flags: { every: true, cron: true }, usage: '<Name> [--every 5m | --cron "..."]', summary: "Scheduled ServiceRunner task (src/services/)" },
16226
+ queue: { handler: generateQueue, flags: {}, usage: "<topic>", summary: "Producer + consumer daemon worker (src/services/)" },
16227
+ validator: { handler: generateValidator, flags: {}, usage: "<Name>", summary: "Request-body Validator (src/validators/)" },
16228
+ seeder: { handler: generateSeeder, flags: { "table-name": true }, usage: "<Model>", summary: "FakeData + seedOrm seeder (src/seeds/)" },
16229
+ websocket: { handler: generateWebsocket, flags: {}, usage: "<path>", summary: "websocket() handler (src/routes/)" },
16230
+ listener: { handler: generateListener, flags: {}, usage: "<event>", summary: "Events.on(event) listener (src/listeners/)" }
16231
+ };
16232
+ RESOLUTION_FLAGS = { json: false, "dry-run": false };
15893
16233
  GENERATOR_LIST = Object.keys(GENERATORS).join(", ");
15894
16234
  NEXT_STEPS = {
15895
16235
  model: ({ name, table: table2 }) => [
@@ -16173,21 +16513,45 @@ function safePath(projectRoot3, relPath) {
16173
16513
  if (resolved !== projectRoot3 && !resolved.startsWith(rootPrefix)) {
16174
16514
  throw new Error(`Path escapes project directory: ${relPath}`);
16175
16515
  }
16176
- let real = null;
16516
+ let realRoot;
16177
16517
  try {
16178
- real = fs4.realpathSync(resolved);
16518
+ realRoot = fs4.realpathSync(projectRoot3);
16179
16519
  } catch {
16180
- real = null;
16520
+ return resolved;
16181
16521
  }
16182
- if (real !== null) {
16183
- const realRoot = fs4.realpathSync(projectRoot3);
16184
- const realPrefix = realRoot.endsWith(path3.sep) ? realRoot : realRoot + path3.sep;
16185
- if (real !== realRoot && !real.startsWith(realPrefix)) {
16186
- throw new Error(`Path escapes project directory: ${relPath}`);
16187
- }
16522
+ const real = realPathOf(resolved);
16523
+ const realPrefix = realRoot.endsWith(path3.sep) ? realRoot : realRoot + path3.sep;
16524
+ if (real === null || real !== realRoot && !real.startsWith(realPrefix)) {
16525
+ throw new Error(`Path escapes project directory: ${relPath}`);
16188
16526
  }
16189
16527
  return resolved;
16190
16528
  }
16529
+ function realPathOf(p, hops = 0) {
16530
+ let probe = p;
16531
+ while (!fs4.existsSync(probe) && !isSymlink(probe) && path3.dirname(probe) !== probe) {
16532
+ probe = path3.dirname(probe);
16533
+ }
16534
+ try {
16535
+ return fs4.realpathSync.native(probe);
16536
+ } catch {
16537
+ if (hops >= 40) return null;
16538
+ let target;
16539
+ try {
16540
+ target = fs4.readlinkSync(probe);
16541
+ } catch {
16542
+ return null;
16543
+ }
16544
+ const base = path3.isAbsolute(target) ? target : path3.dirname(probe) + path3.sep + target;
16545
+ return realPathOf(base + p.slice(probe.length), hops + 1);
16546
+ }
16547
+ }
16548
+ function isSymlink(p) {
16549
+ try {
16550
+ return fs4.lstatSync(p).isSymbolicLink();
16551
+ } catch {
16552
+ return false;
16553
+ }
16554
+ }
16191
16555
  function redactEnv(key, value) {
16192
16556
  const sensitive = ["secret", "password", "token", "key", "credential", "api_key"];
16193
16557
  if (sensitive.some((s) => key.toLowerCase().includes(s))) {
@@ -17032,8 +17396,10 @@ function registerDevTools(server) {
17032
17396
  return { error: `Invalid path ${JSON.stringify(rel)}: ${proseErr}` };
17033
17397
  }
17034
17398
  rel = normalizeCoderPath(projectRoot4, rel);
17035
- const resolved = path3.resolve(projectRoot4, rel);
17036
- if (!resolved.startsWith(projectRoot4)) {
17399
+ let resolved;
17400
+ try {
17401
+ resolved = safePath(projectRoot4, rel);
17402
+ } catch {
17037
17403
  return { error: `Path escapes project directory: ${rel}` };
17038
17404
  }
17039
17405
  if (!fs4.existsSync(resolved) || !fs4.statSync(resolved).isFile()) {
@@ -17330,6 +17696,7 @@ var req, PARSE_ERROR, INVALID_REQUEST, METHOD_NOT_FOUND, INVALID_PARAMS, INTERNA
17330
17696
  var init_mcp = __esm({
17331
17697
  "../core/src/mcp.ts"() {
17332
17698
  "use strict";
17699
+ init_slashTrim();
17333
17700
  init_version();
17334
17701
  req = createRequire2(import.meta.url);
17335
17702
  PARSE_ERROR = -32700;
@@ -17356,7 +17723,7 @@ var init_mcp = __esm({
17356
17723
  // threaded, so this in-process map is the whole coordination mechanism.
17357
17724
  _sseChannels = /* @__PURE__ */ new Map();
17358
17725
  constructor(mcpPath, name = "Tina4 MCP", version = "1.0.0") {
17359
- this.path = mcpPath.replace(/\/+$/, "");
17726
+ this.path = rtrimSlashes(mcpPath);
17360
17727
  this.name = name;
17361
17728
  this.version = version;
17362
17729
  _McpServer._instances.push(this);
@@ -21140,7 +21507,7 @@ var init_job = __esm({
21140
21507
  });
21141
21508
 
21142
21509
  // ../core/src/queueBackends/liteBackend.ts
21143
- import { mkdirSync as mkdirSync11, readdirSync as readdirSync9, readFileSync as readFileSync14, writeFileSync as writeFileSync9, unlinkSync as unlinkSync6, existsSync as existsSync16 } from "node:fs";
21510
+ import { mkdirSync as mkdirSync11, readdirSync as readdirSync9, readFileSync as readFileSync14, writeFileSync as writeFileSync9, unlinkSync as unlinkSync7, existsSync as existsSync16 } from "node:fs";
21144
21511
  import { join as join18 } from "node:path";
21145
21512
  import { randomUUID as randomUUID5 } from "node:crypto";
21146
21513
  var LiteBackend;
@@ -21310,7 +21677,7 @@ var init_liteBackend = __esm({
21310
21677
  }
21311
21678
  if (record.availableAt && record.availableAt > now) continue;
21312
21679
  try {
21313
- unlinkSync6(filePath);
21680
+ unlinkSync7(filePath);
21314
21681
  } catch {
21315
21682
  continue;
21316
21683
  }
@@ -21344,10 +21711,10 @@ var init_liteBackend = __esm({
21344
21711
  job.priority = job.priority ?? 0;
21345
21712
  this.writeReserved(queue, job);
21346
21713
  try {
21347
- unlinkSync6(filePath);
21714
+ unlinkSync7(filePath);
21348
21715
  } catch {
21349
21716
  try {
21350
- unlinkSync6(this.reservedPath(queue, job.id));
21717
+ unlinkSync7(this.reservedPath(queue, job.id));
21351
21718
  } catch {
21352
21719
  }
21353
21720
  continue;
@@ -21369,10 +21736,10 @@ var init_liteBackend = __esm({
21369
21736
  job.priority = job.priority ?? 0;
21370
21737
  this.writeReserved(queue, job);
21371
21738
  try {
21372
- unlinkSync6(filePath);
21739
+ unlinkSync7(filePath);
21373
21740
  } catch {
21374
21741
  try {
21375
- unlinkSync6(this.reservedPath(queue, job.id));
21742
+ unlinkSync7(this.reservedPath(queue, job.id));
21376
21743
  } catch {
21377
21744
  }
21378
21745
  continue;
@@ -21387,7 +21754,7 @@ var init_liteBackend = __esm({
21387
21754
  */
21388
21755
  clearReservation(queue, jobId) {
21389
21756
  try {
21390
- unlinkSync6(this.reservedPath(queue, jobId));
21757
+ unlinkSync7(this.reservedPath(queue, jobId));
21391
21758
  } catch {
21392
21759
  }
21393
21760
  }
@@ -21430,7 +21797,7 @@ var init_liteBackend = __esm({
21430
21797
  try {
21431
21798
  const files = readdirSync9(dir).filter((f) => f.endsWith(".queue-data"));
21432
21799
  for (const file of files) {
21433
- unlinkSync6(join18(dir, file));
21800
+ unlinkSync7(join18(dir, file));
21434
21801
  count++;
21435
21802
  }
21436
21803
  } catch {
@@ -21440,7 +21807,7 @@ var init_liteBackend = __esm({
21440
21807
  if (existsSync16(failedDir)) {
21441
21808
  const files = readdirSync9(failedDir).filter((f) => f.endsWith(".queue-data"));
21442
21809
  for (const file of files) {
21443
- unlinkSync6(join18(failedDir, file));
21810
+ unlinkSync7(join18(failedDir, file));
21444
21811
  count++;
21445
21812
  }
21446
21813
  }
@@ -21451,7 +21818,7 @@ var init_liteBackend = __esm({
21451
21818
  if (existsSync16(reservedDir)) {
21452
21819
  const files = readdirSync9(reservedDir).filter((f) => f.endsWith(".queue-data"));
21453
21820
  for (const file of files) {
21454
- unlinkSync6(join18(reservedDir, file));
21821
+ unlinkSync7(join18(reservedDir, file));
21455
21822
  count++;
21456
21823
  }
21457
21824
  }
@@ -21509,7 +21876,7 @@ var init_liteBackend = __esm({
21509
21876
  const prefix = this.nextPrefix();
21510
21877
  const queueDir = join18(this.basePath, q);
21511
21878
  writeFileSync9(join18(queueDir, `${prefix}_${jobId}.queue-data`), JSON.stringify(job, null, 2));
21512
- unlinkSync6(filePath);
21879
+ unlinkSync7(filePath);
21513
21880
  return true;
21514
21881
  }
21515
21882
  }
@@ -21545,7 +21912,7 @@ var init_liteBackend = __esm({
21545
21912
  const files = readdirSync9(failedDir).filter((f) => f.endsWith(".queue-data"));
21546
21913
  for (const file of files) {
21547
21914
  try {
21548
- unlinkSync6(join18(failedDir, file));
21915
+ unlinkSync7(join18(failedDir, file));
21549
21916
  count++;
21550
21917
  } catch {
21551
21918
  }
@@ -21560,7 +21927,7 @@ var init_liteBackend = __esm({
21560
21927
  try {
21561
21928
  const job = JSON.parse(readFileSync14(join18(dir, file), "utf-8"));
21562
21929
  if (job.status === status2) {
21563
- unlinkSync6(join18(dir, file));
21930
+ unlinkSync7(join18(dir, file));
21564
21931
  count++;
21565
21932
  }
21566
21933
  } catch {
@@ -21595,7 +21962,7 @@ var init_liteBackend = __esm({
21595
21962
  job.delayUntil = null;
21596
21963
  const prefix = this.nextPrefix();
21597
21964
  writeFileSync9(join18(queueDir, `${prefix}_${job.id}.queue-data`), JSON.stringify(job, null, 2));
21598
- unlinkSync6(filePath);
21965
+ unlinkSync7(filePath);
21599
21966
  count++;
21600
21967
  } catch {
21601
21968
  }
@@ -21627,10 +21994,10 @@ var init_liteBackend = __esm({
21627
21994
  job.priority = job.priority ?? 0;
21628
21995
  this.writeReserved(queue, job);
21629
21996
  try {
21630
- unlinkSync6(filePath);
21997
+ unlinkSync7(filePath);
21631
21998
  } catch {
21632
21999
  try {
21633
- unlinkSync6(this.reservedPath(queue, job.id));
22000
+ unlinkSync7(this.reservedPath(queue, job.id));
21634
22001
  } catch {
21635
22002
  }
21636
22003
  continue;
@@ -21732,7 +22099,7 @@ var init_liteBackend = __esm({
21732
22099
  retryJob(queue, job, delaySeconds) {
21733
22100
  this.clearReservation(queue, job.id);
21734
22101
  try {
21735
- unlinkSync6(join18(this.ensureFailedDir(queue), `${job.id}.queue-data`));
22102
+ unlinkSync7(join18(this.ensureFailedDir(queue), `${job.id}.queue-data`));
21736
22103
  } catch {
21737
22104
  }
21738
22105
  job.attempts = (job.attempts || 0) + 1;
@@ -22282,7 +22649,8 @@ function archiveDir() {
22282
22649
  return p;
22283
22650
  }
22284
22651
  function slugify(title) {
22285
- const slug = (title || "").trim().toLowerCase().replace(/[^A-Za-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "");
22652
+ const dashed = (title || "").trim().toLowerCase().replace(/[^A-Za-z0-9_-]+/g, "-");
22653
+ const slug = trimChar(dashed, 45);
22286
22654
  return slug.slice(0, 80) || `plan-${Math.floor(Date.now() / 1e3)}`;
22287
22655
  }
22288
22656
  function parse(text) {
@@ -22419,6 +22787,7 @@ var PLAN_DIR, CURRENT_FILE, ARCHIVE_SUBDIR, STEP_RE, Plan;
22419
22787
  var init_plan = __esm({
22420
22788
  "../core/src/plan.ts"() {
22421
22789
  "use strict";
22790
+ init_slashTrim();
22422
22791
  PLAN_DIR = "plan";
22423
22792
  CURRENT_FILE = ".current";
22424
22793
  ARCHIVE_SUBDIR = "done";
@@ -23658,7 +24027,7 @@ function relativePath(absPath, projectRoot3, frameworkRoots) {
23658
24027
  }
23659
24028
  function tokenise(text) {
23660
24029
  if (!text) return [];
23661
- const expanded = text.replace(CAMEL_SPLIT, (_m, a, b, c, d) => a ? `${a} ${b}` : `${c} ${d}`).toLowerCase();
24030
+ const expanded = text.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/([A-Z])(?=[A-Z][a-z])/g, "$1 ").toLowerCase();
23662
24031
  return expanded.split(/[\s_\-./:,;()\[\]{}\\]+/).filter((p) => p.length > 0);
23663
24032
  }
23664
24033
  function summariseDoc(doc) {
@@ -23889,7 +24258,7 @@ function returnFromSignature(signature) {
23889
24258
  const rest = signature.slice(close + 1).trim();
23890
24259
  return rest.startsWith(":") ? rest.slice(1).trim() : "";
23891
24260
  }
23892
- var STDLIB_ALLOWLIST, _DOCS_CACHE, __FILENAME, __DIRNAME, USER_DIRS, CAMEL_SPLIT, FENCE_RE, CALL_RE, sharedFrameworkIndex, Docs;
24261
+ var STDLIB_ALLOWLIST, _DOCS_CACHE, __FILENAME, __DIRNAME, USER_DIRS, FENCE_RE, CALL_RE, sharedFrameworkIndex, Docs;
23893
24262
  var init_docs = __esm({
23894
24263
  "../core/src/docs.ts"() {
23895
24264
  "use strict";
@@ -24028,7 +24397,6 @@ var init_docs = __esm({
24028
24397
  __FILENAME = fileURLToPath5(import.meta.url);
24029
24398
  __DIRNAME = path8.dirname(__FILENAME);
24030
24399
  USER_DIRS = ["src/orm", "src/routes", "src/app", "src/services", "src/models"];
24031
- CAMEL_SPLIT = /([a-z0-9])([A-Z])|([A-Z]+)([A-Z][a-z])/g;
24032
24400
  FENCE_RE = new RegExp(
24033
24401
  String.fromCharCode(96, 96, 96) + "[a-zA-Z0-9_+-]*\\n([\\s\\S]*?)\\n" + String.fromCharCode(96, 96, 96),
24034
24402
  "g"
@@ -24402,7 +24770,7 @@ ${end}
24402
24770
 
24403
24771
  // ../core/src/devAdmin.ts
24404
24772
  import { cpus as osCpus } from "node:os";
24405
- import { readFileSync as readFileSync18, writeFileSync as writeFileSync13, existsSync as existsSync20, readdirSync as readdirSync13, mkdirSync as mkdirSync14, copyFileSync as copyFileSync2, statSync as statSync15, openSync as openSync4, closeSync as closeSync4, fstatSync as fstatSync2, fchmodSync as fchmodSync2, ftruncateSync, constants as constants3, realpathSync as realpathSync6, lstatSync } from "node:fs";
24773
+ import { readFileSync as readFileSync18, writeFileSync as writeFileSync13, existsSync as existsSync20, readdirSync as readdirSync13, mkdirSync as mkdirSync14, copyFileSync as copyFileSync2, statSync as statSync15, openSync as openSync5, closeSync as closeSync5, fstatSync as fstatSync3, fchmodSync as fchmodSync2, ftruncateSync as ftruncateSync2, constants as constants4, realpathSync as realpathSync6, lstatSync as lstatSync3 } from "node:fs";
24406
24774
  import { join as join22, dirname as dirname11, resolve as resolve12, relative as relative9, sep as sep6, basename as basename5 } from "node:path";
24407
24775
  import { fileURLToPath as fileURLToPath6 } from "node:url";
24408
24776
  import { timingSafeEqual as timingSafeEqual2 } from "node:crypto";
@@ -24601,8 +24969,41 @@ function quoteTableRef(name) {
24601
24969
  }
24602
24970
  return parts.map((p) => `"${p}"`).join(".");
24603
24971
  }
24972
+ function parseSeedRequest(url, body) {
24973
+ const b = body ?? {};
24974
+ const table2 = String(url.searchParams.get("table") ?? b.table ?? "");
24975
+ const count = parseInt(String(url.searchParams.get("count") ?? b.count ?? "10"), 10) || 10;
24976
+ const seedRaw = url.searchParams.get("seed") ?? b.seed;
24977
+ const seed = seedRaw !== void 0 && seedRaw !== null && String(seedRaw) !== "" ? Number.isNaN(parseInt(String(seedRaw), 10)) ? void 0 : parseInt(String(seedRaw), 10) : void 0;
24978
+ const clear = String(url.searchParams.get("clear") ?? b.clear ?? "") === "true" || b.clear === true;
24979
+ const strict = String(url.searchParams.get("strict") ?? b.strict ?? "") === "true" || b.strict === true;
24980
+ return { table: table2, count, seed, clear, strict };
24981
+ }
24982
+ function buildSeedFieldMap(columns, fake) {
24983
+ const rules = [
24984
+ [(n) => n.includes("email"), () => fake.email()],
24985
+ [(n) => n.includes("name"), () => fake.name()],
24986
+ [(n) => n.includes("phone"), () => fake.phone()],
24987
+ [(n) => n.includes("address") || n.includes("city") || n.includes("country"), () => fake.address()],
24988
+ [(n) => n.includes("url") || n.includes("website"), () => fake.url()],
24989
+ [(_n, t) => t.includes("int"), () => fake.integer(1, 1e3)],
24990
+ [(_n, t) => /real|float|double|numeric|decimal/.test(t), () => fake.numeric(0, 1e3, 2)],
24991
+ [(_n, t) => t.includes("bool"), () => fake.boolean()],
24992
+ [(_n, t) => t.includes("date") || t.includes("time"), () => fake.date()]
24993
+ ];
24994
+ const sentence = () => fake.sentence(3);
24995
+ const fieldMap = {};
24996
+ for (const col of columns) {
24997
+ if (col.name.toLowerCase() === "id" || col.primaryKey === true) continue;
24998
+ const name = col.name.toLowerCase();
24999
+ const type2 = col.type.toLowerCase();
25000
+ const rule = rules.find(([matches]) => matches(name, type2));
25001
+ fieldMap[col.name] = rule ? rule[1] : sentence;
25002
+ }
25003
+ return fieldMap;
25004
+ }
24604
25005
  function supervisorBaseUrl() {
24605
- const explicit = (process.env.TINA4_SUPERVISOR_URL ?? "").replace(/\/+$/, "");
25006
+ const explicit = rtrimSlashes(process.env.TINA4_SUPERVISOR_URL ?? "");
24606
25007
  if (explicit) return explicit;
24607
25008
  const agentPort = (process.env.TINA4_AGENT_PORT ?? "").trim();
24608
25009
  if (/^\d+$/.test(agentPort)) return `http://127.0.0.1:${parseInt(agentPort, 10)}`;
@@ -24610,6 +25011,42 @@ function supervisorBaseUrl() {
24610
25011
  if (/^\d+$/.test(fwPort)) return `http://127.0.0.1:${parseInt(fwPort, 10) + 2e3}`;
24611
25012
  return "http://127.0.0.1:9145";
24612
25013
  }
25014
+ function buildSupervisorBody(method, body) {
25015
+ if (method !== "POST" && method !== "PUT" && method !== "PATCH" && method !== "DELETE") return void 0;
25016
+ if (body === void 0 || body === null) return void 0;
25017
+ if (typeof body === "string") return body;
25018
+ if (typeof body !== "object") return void 0;
25019
+ let outBody = body;
25020
+ if (!Array.isArray(body)) {
25021
+ const pf = body.plan_file;
25022
+ if (typeof pf === "string" && pf && !pf.includes("/")) outBody = { ...body, plan_file: `plan/${pf}` };
25023
+ }
25024
+ return JSON.stringify(outBody);
25025
+ }
25026
+ async function streamEventStream(res, upstream, timer) {
25027
+ res.raw.writeHead(upstream.status || 200, {
25028
+ "Content-Type": upstream.headers.get("content-type") ?? "text/event-stream",
25029
+ "Cache-Control": "no-cache",
25030
+ Connection: "keep-alive"
25031
+ });
25032
+ if (typeof res.raw.flushHeaders === "function") res.raw.flushHeaders();
25033
+ if (!upstream.body) {
25034
+ res.raw.end();
25035
+ clearTimeout(timer);
25036
+ return;
25037
+ }
25038
+ const reader = upstream.body.getReader();
25039
+ try {
25040
+ while (true) {
25041
+ const { done, value } = await reader.read();
25042
+ if (done) break;
25043
+ if (value) res.raw.write(Buffer.from(value));
25044
+ }
25045
+ } finally {
25046
+ clearTimeout(timer);
25047
+ res.raw.end();
25048
+ }
25049
+ }
24613
25050
  async function proxyToSupervisor(req2, res, downstreamPath) {
24614
25051
  const base = supervisorBaseUrl();
24615
25052
  let qs = "";
@@ -24620,24 +25057,7 @@ async function proxyToSupervisor(req2, res, downstreamPath) {
24620
25057
  }
24621
25058
  const target = `${base}${downstreamPath}${qs}`;
24622
25059
  const method = (req2.method ?? "GET").toUpperCase();
24623
- let bodyText;
24624
- if (method === "POST" || method === "PUT" || method === "PATCH" || method === "DELETE") {
24625
- const body = req2.body;
24626
- if (body !== void 0 && body !== null) {
24627
- if (typeof body === "string") {
24628
- bodyText = body;
24629
- } else if (typeof body === "object") {
24630
- let outBody = body;
24631
- if (!Array.isArray(body)) {
24632
- const pf = body.plan_file;
24633
- if (typeof pf === "string" && pf && !pf.includes("/")) {
24634
- outBody = { ...body, plan_file: `plan/${pf}` };
24635
- }
24636
- }
24637
- bodyText = JSON.stringify(outBody);
24638
- }
24639
- }
24640
- }
25060
+ const bodyText = buildSupervisorBody(method, req2.body);
24641
25061
  const timeoutMs = downstreamPath === "/execute" || downstreamPath === "/chat" ? 6e5 : 3e4;
24642
25062
  const ctrl = new AbortController();
24643
25063
  const timer = setTimeout(() => ctrl.abort(), timeoutMs);
@@ -24663,30 +25083,7 @@ async function proxyToSupervisor(req2, res, downstreamPath) {
24663
25083
  }
24664
25084
  const ct = (upstream.headers.get("content-type") ?? "").toLowerCase();
24665
25085
  if (ct.includes("text/event-stream")) {
24666
- res.raw.writeHead(upstream.status || 200, {
24667
- "Content-Type": upstream.headers.get("content-type") ?? "text/event-stream",
24668
- "Cache-Control": "no-cache",
24669
- Connection: "keep-alive"
24670
- });
24671
- if (typeof res.raw.flushHeaders === "function") {
24672
- res.raw.flushHeaders();
24673
- }
24674
- if (!upstream.body) {
24675
- res.raw.end();
24676
- clearTimeout(timer);
24677
- return;
24678
- }
24679
- const reader = upstream.body.getReader();
24680
- try {
24681
- while (true) {
24682
- const { done, value } = await reader.read();
24683
- if (done) break;
24684
- if (value) res.raw.write(Buffer.from(value));
24685
- }
24686
- } finally {
24687
- clearTimeout(timer);
24688
- res.raw.end();
24689
- }
25086
+ await streamEventStream(res, upstream, timer);
24690
25087
  return;
24691
25088
  }
24692
25089
  clearTimeout(timer);
@@ -24803,13 +25200,13 @@ function handleGalleryDeploy(router) {
24803
25200
  res.json({ deployed: name, files: copied });
24804
25201
  };
24805
25202
  }
24806
- function realPathOf(target) {
25203
+ function realPathOf2(target) {
24807
25204
  let existing = target;
24808
25205
  const tail = [];
24809
25206
  for (; ; ) {
24810
25207
  let present = false;
24811
25208
  try {
24812
- lstatSync(existing);
25209
+ lstatSync3(existing);
24813
25210
  present = true;
24814
25211
  } catch {
24815
25212
  }
@@ -24821,9 +25218,9 @@ function realPathOf(target) {
24821
25218
  }
24822
25219
  function safeJoin(projectRoot3, rel, extraRoots = []) {
24823
25220
  try {
24824
- const root = realPathOf(resolve12(projectRoot3));
24825
- const resolved = realPathOf(resolve12(root, rel));
24826
- const roots = [root, ...extraRoots.filter(Boolean).map((r) => realPathOf(resolve12(r)))];
25221
+ const root = realPathOf2(resolve12(projectRoot3));
25222
+ const resolved = realPathOf2(resolve12(root, rel));
25223
+ const roots = [root, ...extraRoots.filter(Boolean).map((r) => realPathOf2(resolve12(r)))];
24827
25224
  for (const r of roots) {
24828
25225
  if (resolved === r || resolved.startsWith(r.endsWith(sep6) ? r : r + sep6)) return resolved;
24829
25226
  }
@@ -24832,7 +25229,7 @@ function safeJoin(projectRoot3, rel, extraRoots = []) {
24832
25229
  return null;
24833
25230
  }
24834
25231
  function resolvedRelative(projectRoot3, resolvedPath) {
24835
- return relative9(realPathOf(resolve12(projectRoot3)), resolvedPath);
25232
+ return relative9(realPathOf2(resolve12(projectRoot3)), resolvedPath);
24836
25233
  }
24837
25234
  function devFilesHidden(name) {
24838
25235
  if (DEV_FILES_IGNORED.has(name)) return true;
@@ -24860,7 +25257,7 @@ async function devGitInfo(root) {
24860
25257
  if (!inside || inside.trim() !== "true") return empty;
24861
25258
  const branch = (git(["rev-parse", "--abbrev-ref", "HEAD"]) ?? "").trim();
24862
25259
  const topRaw = git(["rev-parse", "--show-toplevel"]);
24863
- const gitRoot = topRaw && topRaw.trim() !== "" ? topRaw.trim().replace(/\\/g, "/").replace(/\/+$/, "") : null;
25260
+ const gitRoot = topRaw && topRaw.trim() !== "" ? rtrimSlashes(topRaw.trim().replace(/\\/g, "/")) : null;
24864
25261
  const status2 = /* @__PURE__ */ new Map();
24865
25262
  const porcelain = git(["status", "--porcelain", "-uall"]);
24866
25263
  if (porcelain) {
@@ -24879,6 +25276,44 @@ async function devGitInfo(root) {
24879
25276
  return empty;
24880
25277
  }
24881
25278
  }
25279
+ function devGitLabel(gitPath, isDir, gitStatus) {
25280
+ const code = gitStatus.get(gitPath);
25281
+ if (code !== void 0) return devGitStatusLabel(code);
25282
+ if (isDir) {
25283
+ const prefix = gitPath + "/";
25284
+ for (const [gf, gc] of gitStatus) {
25285
+ if (gf.startsWith(prefix)) return gc === "??" ? "untracked" : "modified";
25286
+ }
25287
+ }
25288
+ return "clean";
25289
+ }
25290
+ function devDirHasVisibleChild(full) {
25291
+ try {
25292
+ for (const c of readdirSync13(full)) {
25293
+ if (!devFilesHidden(c)) return true;
25294
+ }
25295
+ } catch {
25296
+ }
25297
+ return false;
25298
+ }
25299
+ function buildFileEntry(name, full, entryRel, cwdInGit, gitStatus) {
25300
+ let isDir = false;
25301
+ let size = null;
25302
+ try {
25303
+ const st = statSync15(full);
25304
+ isDir = st.isDirectory();
25305
+ if (!isDir) size = st.size;
25306
+ } catch {
25307
+ }
25308
+ return {
25309
+ name,
25310
+ path: entryRel,
25311
+ is_dir: isDir,
25312
+ has_children: isDir ? devDirHasVisibleChild(full) : null,
25313
+ git_status: devGitLabel(cwdInGit + entryRel, isDir, gitStatus),
25314
+ size
25315
+ };
25316
+ }
24882
25317
  function devAdminLanguage(rel) {
24883
25318
  const base = (rel.split(/[\\/]/).pop() ?? "").toLowerCase();
24884
25319
  if (base === "dockerfile" || base === "dockerfile.dev" || base === "dockerfile.prod") {
@@ -24893,14 +25328,14 @@ function devAdminLanguage(rel) {
24893
25328
  function readDevFile(target) {
24894
25329
  let fd;
24895
25330
  try {
24896
- fd = openSync4(target, constants3.O_RDONLY | constants3.O_NOFOLLOW | constants3.O_NONBLOCK);
24897
- if (!fstatSync2(fd).isFile()) return null;
25331
+ fd = openSync5(target, constants4.O_RDONLY | constants4.O_NOFOLLOW | constants4.O_NONBLOCK);
25332
+ if (!fstatSync3(fd).isFile()) return null;
24898
25333
  return readFileSync18(fd);
24899
25334
  } catch (error2) {
24900
25335
  if (["ENOENT", "ENOTDIR", "ELOOP"].includes(error2.code ?? "")) return null;
24901
25336
  throw error2;
24902
25337
  } finally {
24903
- if (fd !== void 0) closeSync4(fd);
25338
+ if (fd !== void 0) closeSync5(fd);
24904
25339
  }
24905
25340
  }
24906
25341
  function mcpSecureEqual(expected, provided) {
@@ -25131,6 +25566,7 @@ var cpuCount, DEV_MCP_PREFIXES, DEV_PUBLIC_ASSETS, DEV_SECRET_BASENAMES, DEV_SEC
25131
25566
  var init_devAdmin = __esm({
25132
25567
  "../core/src/devAdmin.ts"() {
25133
25568
  "use strict";
25569
+ init_slashTrim();
25134
25570
  init_devMailbox();
25135
25571
  init_upstreamResponse();
25136
25572
  init_dotenv();
@@ -25608,7 +26044,8 @@ var init_devAdmin = __esm({
25608
26044
  router.addRoute({
25609
26045
  method: route.method,
25610
26046
  pattern: route.pattern,
25611
- handler: route.handler
26047
+ handler: route.handler,
26048
+ noAuth: true
25612
26049
  });
25613
26050
  }
25614
26051
  if (mcpEnabled()) {
@@ -25632,7 +26069,8 @@ var init_devAdmin = __esm({
25632
26069
  router.addRoute({
25633
26070
  method: route.method,
25634
26071
  pattern: route.pattern,
25635
- handler: route.handler
26072
+ handler: route.handler,
26073
+ noAuth: true
25636
26074
  });
25637
26075
  }
25638
26076
  getDefaultDevServer();
@@ -25964,13 +26402,7 @@ var init_devAdmin = __esm({
25964
26402
  };
25965
26403
  handleSeed = async (req2, res) => {
25966
26404
  const url = new URL(req2.url ?? "/", "http://localhost");
25967
- const body = req2.body ?? {};
25968
- const table2 = url.searchParams.get("table") ?? body?.table ?? "";
25969
- const count = parseInt(String(url.searchParams.get("count") ?? body?.count ?? "10"), 10) || 10;
25970
- const seedRaw = url.searchParams.get("seed") ?? body?.seed;
25971
- const seed = seedRaw !== void 0 && seedRaw !== null && String(seedRaw) !== "" ? Number.isNaN(parseInt(String(seedRaw), 10)) ? void 0 : parseInt(String(seedRaw), 10) : void 0;
25972
- const clear = String(url.searchParams.get("clear") ?? body?.clear ?? "") === "true" || body?.clear === true;
25973
- const strict = String(url.searchParams.get("strict") ?? body?.strict ?? "") === "true" || body?.strict === true;
26405
+ const { table: table2, count, seed, clear, strict } = parseSeedRequest(url, req2.body);
25974
26406
  if (!table2) {
25975
26407
  res.json({ error: "Missing table parameter" });
25976
26408
  return;
@@ -25985,33 +26417,7 @@ var init_devAdmin = __esm({
25985
26417
  res.json({ error: `Table '${table2}' not found or has no columns` });
25986
26418
  return;
25987
26419
  }
25988
- const fieldMap = {};
25989
- for (const col of columns) {
25990
- const name = col.name.toLowerCase();
25991
- const type2 = col.type.toLowerCase();
25992
- if (name === "id" || col.primaryKey === true) continue;
25993
- if (name.includes("email")) {
25994
- fieldMap[col.name] = () => fake.email();
25995
- } else if (name.includes("name")) {
25996
- fieldMap[col.name] = () => fake.name();
25997
- } else if (name.includes("phone")) {
25998
- fieldMap[col.name] = () => fake.phone();
25999
- } else if (name.includes("address") || name.includes("city") || name.includes("country")) {
26000
- fieldMap[col.name] = () => fake.address();
26001
- } else if (name.includes("url") || name.includes("website")) {
26002
- fieldMap[col.name] = () => fake.url();
26003
- } else if (type2.includes("int")) {
26004
- fieldMap[col.name] = () => fake.integer(1, 1e3);
26005
- } else if (type2.includes("real") || type2.includes("float") || type2.includes("double") || type2.includes("numeric") || type2.includes("decimal")) {
26006
- fieldMap[col.name] = () => fake.numeric(0, 1e3, 2);
26007
- } else if (type2.includes("bool")) {
26008
- fieldMap[col.name] = () => fake.boolean();
26009
- } else if (type2.includes("date") || type2.includes("time")) {
26010
- fieldMap[col.name] = () => fake.date();
26011
- } else {
26012
- fieldMap[col.name] = () => fake.sentence(3);
26013
- }
26014
- }
26420
+ const fieldMap = buildSeedFieldMap(columns, fake);
26015
26421
  const summary = await seedTable2(db, table2, count, fieldMap, void 0, { clear, strict });
26016
26422
  res.json({ seeded: summary.seeded, failed: summary.failed, errors: summary.errors, table: table2 });
26017
26423
  } catch (e) {
@@ -26184,9 +26590,9 @@ var init_devAdmin = __esm({
26184
26590
  };
26185
26591
  handleTest = async (_req, res) => {
26186
26592
  try {
26187
- const { execFile } = await import("node:child_process");
26593
+ const { execFile: execFile2 } = await import("node:child_process");
26188
26594
  const { promisify } = await import("node:util");
26189
- const run = promisify(execFile);
26595
+ const run = promisify(execFile2);
26190
26596
  try {
26191
26597
  const { stdout, stderr } = await run("npm", ["test"], {
26192
26598
  cwd: resolve12(process.cwd()),
@@ -26304,9 +26710,9 @@ var init_devAdmin = __esm({
26304
26710
  }
26305
26711
  try {
26306
26712
  const envPath = join22(process.cwd(), ".env");
26307
- const fd = openSync4(envPath, constants3.O_RDWR | constants3.O_APPEND | constants3.O_CREAT | (constants3.O_NOFOLLOW ?? 0) | (constants3.O_NONBLOCK ?? 0), 384);
26713
+ const fd = openSync5(envPath, constants4.O_RDWR | constants4.O_APPEND | constants4.O_CREAT | (constants4.O_NOFOLLOW ?? 0) | (constants4.O_NONBLOCK ?? 0), 384);
26308
26714
  try {
26309
- const info = fstatSync2(fd);
26715
+ const info = fstatSync3(fd);
26310
26716
  if (!info.isFile() || info.nlink !== 1) throw new Error("Refusing a non-regular or multiply-linked configuration file");
26311
26717
  fchmodSync2(fd, 384);
26312
26718
  const lines = readFileSync18(fd, "utf-8").split("\n");
@@ -26336,10 +26742,10 @@ var init_devAdmin = __esm({
26336
26742
  for (const [key, found] of Object.entries(keysFound)) {
26337
26743
  if (!found) newLines.push(`${key}=${values[key]}`);
26338
26744
  }
26339
- ftruncateSync(fd, 0);
26745
+ ftruncateSync2(fd, 0);
26340
26746
  writeFileSync13(fd, newLines.join("\n") + "\n");
26341
26747
  } finally {
26342
- closeSync4(fd);
26748
+ closeSync5(fd);
26343
26749
  }
26344
26750
  res.json({ success: true });
26345
26751
  } catch (e) {
@@ -26462,48 +26868,7 @@ var init_devAdmin = __esm({
26462
26868
  const full = join22(target, name);
26463
26869
  const entryRel = relative9(root, full).replace(/\\/g, "/");
26464
26870
  if (isSecretPath(entryRel)) continue;
26465
- let isDir = false;
26466
- let size = null;
26467
- try {
26468
- const st = statSync15(full);
26469
- isDir = st.isDirectory();
26470
- if (!isDir) size = st.size;
26471
- } catch {
26472
- }
26473
- const gitPath = cwdInGit + entryRel;
26474
- let gitLabel = "clean";
26475
- const code = gitStatus.get(gitPath);
26476
- if (code !== void 0) {
26477
- gitLabel = devGitStatusLabel(code);
26478
- } else if (isDir) {
26479
- const prefix = gitPath + "/";
26480
- for (const [gf, gc] of gitStatus) {
26481
- if (gf.startsWith(prefix)) {
26482
- gitLabel = gc === "??" ? "untracked" : "modified";
26483
- break;
26484
- }
26485
- }
26486
- }
26487
- let hasChildren = null;
26488
- if (isDir) {
26489
- hasChildren = false;
26490
- try {
26491
- for (const c of readdirSync13(full)) {
26492
- if (devFilesHidden(c)) continue;
26493
- hasChildren = true;
26494
- break;
26495
- }
26496
- } catch {
26497
- }
26498
- }
26499
- entries.push({
26500
- name,
26501
- path: entryRel,
26502
- is_dir: isDir,
26503
- has_children: hasChildren,
26504
- git_status: gitLabel,
26505
- size
26506
- });
26871
+ entries.push(buildFileEntry(name, full, entryRel, cwdInGit, gitStatus));
26507
26872
  }
26508
26873
  res.json({ path: relative9(root, target).replace(/\\/g, "/") || ".", branch, entries });
26509
26874
  };
@@ -27532,7 +27897,10 @@ function generate2(routes, models = []) {
27532
27897
  openapi: resolveOpenApiVersion(),
27533
27898
  info: buildInfo(),
27534
27899
  servers: resolveServers(),
27535
- paths: {},
27900
+ // Prototype-less: route paths are developer-defined, but a null prototype
27901
+ // makes `spec.paths[path][method] = op` structurally pollution-proof
27902
+ // regardless (js/prototype-polluting-assignment). Serialises to JSON the same.
27903
+ paths: /* @__PURE__ */ Object.create(null),
27536
27904
  components: {
27537
27905
  schemas: {},
27538
27906
  // Configurable security schemes (v3.13.42): bearerFormat via env, optional
@@ -27597,7 +27965,7 @@ function buildOperation(route, spec, ctx) {
27597
27965
  const openApiPath = patternToOpenAPI(route.pattern);
27598
27966
  const method = route.method.toLowerCase();
27599
27967
  if (!spec.paths[openApiPath]) {
27600
- spec.paths[openApiPath] = {};
27968
+ spec.paths[openApiPath] = /* @__PURE__ */ Object.create(null);
27601
27969
  }
27602
27970
  const tags = route.meta?.tags ?? inferTags(route.pattern);
27603
27971
  for (const t of tags) {
@@ -27903,7 +28271,7 @@ function inferModelFromPath(pattern) {
27903
28271
  return null;
27904
28272
  }
27905
28273
  function operationIdBase(method, openApiPath) {
27906
- const clean = openApiPath.replace(/^\/+|\/+$/g, "").replace(/\//g, "_").replace(/\.\.\./g, "").replace(/[{}]/g, "").replace(/\*/g, "wildcard");
28274
+ const clean = trimSlashes(openApiPath).replace(/\//g, "_").replace(/\.\.\./g, "").replace(/[{}]/g, "").replace(/\*/g, "wildcard");
27907
28275
  return clean ? `${method}_${clean}` : method;
27908
28276
  }
27909
28277
  function uniqueOperationId(method, openApiPath, seen) {
@@ -27921,6 +28289,7 @@ var WRITE_METHODS, INTERNAL_PREFIXES, registeredSchemes, registeredSchemas, PARA
27921
28289
  var init_generator = __esm({
27922
28290
  "../swagger/src/generator.ts"() {
27923
28291
  "use strict";
28292
+ init_slashTrim();
27924
28293
  WRITE_METHODS = /* @__PURE__ */ new Set(["post", "put", "patch", "delete"]);
27925
28294
  INTERNAL_PREFIXES = ["/swagger", "/__dev", "/__feedback", "/ai", "/rag", "/vision", "/embed", "/image"];
27926
28295
  registeredSchemes = {};
@@ -27942,7 +28311,7 @@ var init_generator = __esm({
27942
28311
 
27943
28312
  // ../swagger/src/ui.ts
27944
28313
  function swaggerUiCdn() {
27945
- return (process.env.TINA4_SWAGGER_UI_CDN ?? "https://cdn.jsdelivr.net/npm/swagger-ui-dist@5").replace(/\/+$/, "");
28314
+ return rtrimSlashes(process.env.TINA4_SWAGGER_UI_CDN ?? "https://cdn.jsdelivr.net/npm/swagger-ui-dist@5");
27946
28315
  }
27947
28316
  function swaggerEnabled() {
27948
28317
  const raw = (process.env.TINA4_SWAGGER_ENABLED ?? "").trim().toLowerCase();
@@ -27998,6 +28367,7 @@ var SWAGGER_UI_HTML;
27998
28367
  var init_ui = __esm({
27999
28368
  "../swagger/src/ui.ts"() {
28000
28369
  "use strict";
28370
+ init_slashTrim();
28001
28371
  SWAGGER_UI_HTML = (specUrl, nonce) => `<!DOCTYPE html>
28002
28372
  <html lang="en">
28003
28373
  <head>
@@ -28415,7 +28785,7 @@ import { resolve as resolve15, dirname as dirname12, join as join25, relative as
28415
28785
  import { existsSync as existsSync23, readdirSync as readdirSync15, readFileSync as readFileSync21, statSync as statSync16 } from "node:fs";
28416
28786
  import { isatty } from "node:tty";
28417
28787
  import { fileURLToPath as fileURLToPath7 } from "node:url";
28418
- import { execFileSync as execFileSync3, exec } from "node:child_process";
28788
+ import { execFileSync as execFileSync3, execFile } from "node:child_process";
28419
28789
  import cluster from "node:cluster";
28420
28790
  import os2 from "node:os";
28421
28791
  function isSwaggerAssetPath(pathname) {
@@ -28551,10 +28921,11 @@ function shouldOpenBrowser(isDevelopment, noBrowser = false) {
28551
28921
  });
28552
28922
  }
28553
28923
  function openBrowser(url) {
28924
+ if (!/^https?:\/\/([A-Za-z0-9.-]+|\[[0-9A-Fa-f:]+\])(:\d{1,5})?\/?$/.test(url)) return;
28554
28925
  setTimeout(() => {
28555
- if (process.platform === "darwin") exec(`open ${url}`);
28556
- else if (process.platform === "win32") exec(`start "" "${url}"`);
28557
- else exec(`xdg-open ${url}`);
28926
+ if (process.platform === "darwin") execFile("open", [url]);
28927
+ else if (process.platform === "win32") execFile("rundll32", ["url.dll,FileProtocolHandler", url]);
28928
+ else execFile("xdg-open", [url]);
28558
28929
  }, 2e3);
28559
28930
  }
28560
28931
  function resolvePortAndHost(config) {
@@ -28669,7 +29040,7 @@ function resetTemplateCache() {
28669
29040
  }
28670
29041
  function resolveTemplate(pathname, templatesDir) {
28671
29042
  if (!templateAutoRoutingEnabled()) return null;
28672
- const cleanPath = pathname.replace(/^\/+/, "").replace(/\/+$/, "") || "index";
29043
+ const cleanPath = trimSlashes(pathname) || "index";
28673
29044
  const isDev2 = (process.env.TINA4_DEBUG ?? "false").toLowerCase() === "true";
28674
29045
  if (isDev2) {
28675
29046
  if (cleanPath.split("/").some((seg) => seg.startsWith("_"))) return null;
@@ -28937,7 +29308,7 @@ async function runGlobalMiddlewarePass(middleware, req2, res) {
28937
29308
  }
28938
29309
  function resolveHandlerArgs(handler, req2, res, routeParams) {
28939
29310
  const fnStr = handler.toString();
28940
- const argMatch = fnStr.match(/^(?:async\s*)?(?:function\s*\w*)?\s*\(([^)]*)\)/);
29311
+ const argMatch = fnStr.match(/^(?:async\s*)?(?:function(?:\s+\w+)?\s*)?\(([^)]*)\)/);
28941
29312
  const argNames = argMatch?.[1]?.split(",").map((a) => a.trim().replace(/[:=].*/, "")) ?? [];
28942
29313
  const filteredArgs = argNames.filter((n) => n.length > 0);
28943
29314
  if (filteredArgs.length === 0) return [];
@@ -28966,7 +29337,7 @@ async function runMatchedRoute(ctx) {
28966
29337
  const { req: req2, res, match, postMatchMiddleware } = ctx;
28967
29338
  req2.params = match.params;
28968
29339
  if (await runGlobalMiddlewarePass(postMatchMiddleware, req2, res)) return;
28969
- if (enforceRouteAuth(req2, res, match, ctx.pathname.startsWith("/__dev"))) return;
29340
+ if (enforceRouteAuth(req2, res, match)) return;
28970
29341
  const routeMiddlewareClasses = (match.middlewares ?? []).filter(isMiddlewareClass);
28971
29342
  let handlerSkipped = false;
28972
29343
  if (match.middlewares && match.middlewares.length > 0) {
@@ -29173,8 +29544,9 @@ async function buildDispatchContext(router, base) {
29173
29544
  const templatesDir = resolve15(root, "src/templates");
29174
29545
  let frondEngine = null;
29175
29546
  try {
29176
- const { Frond: Frond2, setCspNonceProvider: setCspNonceProvider2 } = await Promise.resolve().then(() => (init_engine(), engine_exports));
29547
+ const { Frond: Frond2, setCspNonceProvider: setCspNonceProvider2, setFormTokenSessionProvider: setFormTokenSessionProvider2 } = await Promise.resolve().then(() => (init_engine(), engine_exports));
29177
29548
  setCspNonceProvider2(currentCspNonce);
29549
+ setFormTokenSessionProvider2(currentFormTokenSessionId);
29178
29550
  frondEngine = new Frond2(templatesDir);
29179
29551
  } catch {
29180
29552
  }
@@ -29289,7 +29661,10 @@ async function runDispatch(ctx, rawReq, rawRes) {
29289
29661
  const requestNonce = generateNonce();
29290
29662
  return Log.runWithRequestId(
29291
29663
  requestId,
29292
- () => runWithCspNonce(requestNonce, () => dispatchInner(ctx, rawReq, rawRes, requestId))
29664
+ () => runWithCspNonce(
29665
+ requestNonce,
29666
+ () => runWithFormTokenSession(() => dispatchInner(ctx, rawReq, rawRes, requestId))
29667
+ )
29293
29668
  );
29294
29669
  }
29295
29670
  function loopbackBindHosts(host) {
@@ -29417,8 +29792,9 @@ async function startServer(config) {
29417
29792
  let frondEngine = null;
29418
29793
  setDefaultTemplatesDir(templatesDir);
29419
29794
  try {
29420
- const { Frond: Frond2, setCspNonceProvider: setCspNonceProvider2 } = await Promise.resolve().then(() => (init_engine(), engine_exports));
29795
+ const { Frond: Frond2, setCspNonceProvider: setCspNonceProvider2, setFormTokenSessionProvider: setFormTokenSessionProvider2 } = await Promise.resolve().then(() => (init_engine(), engine_exports));
29421
29796
  setCspNonceProvider2(currentCspNonce);
29797
+ setFormTokenSessionProvider2(currentFormTokenSessionId);
29422
29798
  frondEngine = new Frond2(templatesDir);
29423
29799
  router.addRoute({
29424
29800
  method: "GET",
@@ -29767,6 +30143,7 @@ var __filename, __dirname, BUILTIN_ERROR_TEMPLATES_DIR, BUILTIN_PUBLIC_DIR, swag
29767
30143
  var init_server = __esm({
29768
30144
  "../core/src/server.ts"() {
29769
30145
  "use strict";
30146
+ init_slashTrim();
29770
30147
  init_transport();
29771
30148
  init_router();
29772
30149
  init_authGate();
@@ -29774,6 +30151,7 @@ var init_server = __esm({
29774
30151
  init_portTakeover();
29775
30152
  init_request();
29776
30153
  init_dispatchPipeline();
30154
+ init_session();
29777
30155
  init_response();
29778
30156
  init_middleware();
29779
30157
  init_static();
@@ -31920,6 +32298,7 @@ var ApiStreamError, RETRY_STATUSES, DOWNLOAD_CHUNK_SIZE, MAX_REDIRECTS, STRIP_ON
31920
32298
  var init_api = __esm({
31921
32299
  "../core/src/api.ts"() {
31922
32300
  "use strict";
32301
+ init_slashTrim();
31923
32302
  init_version();
31924
32303
  init_ssrf();
31925
32304
  ApiStreamError = class extends Error {
@@ -32017,7 +32396,7 @@ var init_api = __esm({
32017
32396
  * turns on a per-client, in-memory cookie jar.
32018
32397
  */
32019
32398
  constructor(baseUrl = "", authHeaderOrOptions = "", timeout = 30) {
32020
- this.baseUrl = baseUrl.replace(/\/+$/, "");
32399
+ this.baseUrl = rtrimSlashes(baseUrl);
32021
32400
  this.headers = {};
32022
32401
  this.maxRetries = 0;
32023
32402
  this.retryBackoff = 0.5;
@@ -32783,6 +33162,23 @@ function sendCommand(socket, command) {
32783
33162
  });
32784
33163
  });
32785
33164
  }
33165
+ function pushAlternativeBody(lines, altBoundary, text, body) {
33166
+ lines.push(`Content-Type: multipart/alternative; boundary="${altBoundary}"`);
33167
+ lines.push("");
33168
+ lines.push(`--${altBoundary}`);
33169
+ lines.push("Content-Type: text/plain; charset=UTF-8");
33170
+ lines.push("Content-Transfer-Encoding: 7bit");
33171
+ lines.push("");
33172
+ lines.push(text);
33173
+ lines.push("");
33174
+ lines.push(`--${altBoundary}`);
33175
+ lines.push("Content-Type: text/html; charset=UTF-8");
33176
+ lines.push("Content-Transfer-Encoding: 7bit");
33177
+ lines.push("");
33178
+ lines.push(body);
33179
+ lines.push("");
33180
+ lines.push(`--${altBoundary}--`);
33181
+ }
32786
33182
  function buildMimeMessage(options) {
32787
33183
  const boundary = `----=_Tina4_${Date.now()}_${Math.random().toString(36).substring(2)}`;
32788
33184
  const altBoundary = `----=_Tina4Alt_${Date.now()}_${Math.random().toString(36).substring(2)}`;
@@ -32812,21 +33208,7 @@ function buildMimeMessage(options) {
32812
33208
  lines.push("");
32813
33209
  lines.push(`--${boundary}`);
32814
33210
  if (hasTextAlt) {
32815
- lines.push(`Content-Type: multipart/alternative; boundary="${altBoundary}"`);
32816
- lines.push("");
32817
- lines.push(`--${altBoundary}`);
32818
- lines.push("Content-Type: text/plain; charset=UTF-8");
32819
- lines.push("Content-Transfer-Encoding: 7bit");
32820
- lines.push("");
32821
- lines.push(options.text);
32822
- lines.push("");
32823
- lines.push(`--${altBoundary}`);
32824
- lines.push("Content-Type: text/html; charset=UTF-8");
32825
- lines.push("Content-Transfer-Encoding: 7bit");
32826
- lines.push("");
32827
- lines.push(options.body);
32828
- lines.push("");
32829
- lines.push(`--${altBoundary}--`);
33211
+ pushAlternativeBody(lines, altBoundary, options.text, options.body);
32830
33212
  } else {
32831
33213
  const contentType = options.html ? "text/html" : "text/plain";
32832
33214
  lines.push(`Content-Type: ${contentType}; charset=UTF-8`);
@@ -32851,21 +33233,7 @@ function buildMimeMessage(options) {
32851
33233
  lines.push("");
32852
33234
  lines.push(`--${boundary}--`);
32853
33235
  } else if (hasTextAlt) {
32854
- lines.push(`Content-Type: multipart/alternative; boundary="${altBoundary}"`);
32855
- lines.push("");
32856
- lines.push(`--${altBoundary}`);
32857
- lines.push("Content-Type: text/plain; charset=UTF-8");
32858
- lines.push("Content-Transfer-Encoding: 7bit");
32859
- lines.push("");
32860
- lines.push(options.text);
32861
- lines.push("");
32862
- lines.push(`--${altBoundary}`);
32863
- lines.push("Content-Type: text/html; charset=UTF-8");
32864
- lines.push("Content-Transfer-Encoding: 7bit");
32865
- lines.push("");
32866
- lines.push(options.body);
32867
- lines.push("");
32868
- lines.push(`--${altBoundary}--`);
33236
+ pushAlternativeBody(lines, altBoundary, options.text, options.body);
32869
33237
  } else {
32870
33238
  const contentType = options.html ? "text/html" : "text/plain";
32871
33239
  lines.push(`Content-Type: ${contentType}; charset=UTF-8`);
@@ -33630,61 +33998,72 @@ function decodeEntities(raw) {
33630
33998
  function parseXmlDocument(xml) {
33631
33999
  const stack = [];
33632
34000
  let root = null;
33633
- let position = 0;
33634
34001
  const addText = (text) => {
33635
34002
  const current = stack[stack.length - 1];
33636
34003
  if (current.children.length === 0) current.text += text;
33637
34004
  };
33638
- while (position < xml.length) {
33639
- const nextTag = xml.indexOf("<", position);
34005
+ const skipComment = (at) => {
34006
+ const close = xml.indexOf("-->", at + 4);
34007
+ if (close === -1) malformed();
34008
+ return close + 3;
34009
+ };
34010
+ const readCData = (at) => {
34011
+ const close = xml.indexOf("]]>", at + 9);
34012
+ if (close === -1 || stack.length === 0) malformed();
34013
+ addText(xml.slice(at + 9, close));
34014
+ return close + 3;
34015
+ };
34016
+ const skipProcessingInstruction = (at) => {
34017
+ const close = xml.indexOf("?>", at + 2);
34018
+ if (close === -1) malformed();
34019
+ const target = xml.slice(at + 2, close).split(/\s/, 1)[0];
34020
+ if (target.toLowerCase() === "xml" && at !== 0) malformed();
34021
+ return close + 2;
34022
+ };
34023
+ const closeElement = (at) => {
34024
+ END_TAG.lastIndex = at;
34025
+ const match = END_TAG.exec(xml);
34026
+ const open = stack.pop();
34027
+ if (!match || !open || open.qualifiedName !== match[1]) malformed();
34028
+ return END_TAG.lastIndex;
34029
+ };
34030
+ const openElement = (at) => {
34031
+ START_TAG.lastIndex = at;
34032
+ const match = START_TAG.exec(xml);
34033
+ if (!match || stack.length === 0 && root !== null) malformed();
34034
+ for (const attribute of match[2].matchAll(ATTRIBUTE_VALUE)) decodeEntities(attribute[1] ?? attribute[2]);
34035
+ const qualifiedName = match[1];
34036
+ const element = {
34037
+ name: qualifiedName.slice(qualifiedName.indexOf(":") + 1),
34038
+ qualifiedName,
34039
+ children: [],
34040
+ text: ""
34041
+ };
34042
+ if (stack.length > 0) stack[stack.length - 1].children.push(element);
34043
+ else root = element;
34044
+ if (match[3] !== "/") stack.push(element);
34045
+ return START_TAG.lastIndex;
34046
+ };
34047
+ const readText = (at) => {
34048
+ const nextTag = xml.indexOf("<", at);
33640
34049
  const textEnd = nextTag === -1 ? xml.length : nextTag;
33641
- if (textEnd > position) {
33642
- const raw = xml.slice(position, textEnd);
34050
+ if (textEnd > at) {
34051
+ const raw = xml.slice(at, textEnd);
33643
34052
  if (stack.length > 0) addText(decodeEntities(raw));
33644
34053
  else if (raw.trim() !== "") malformed();
33645
- position = textEnd;
33646
- if (nextTag === -1) break;
33647
- }
33648
- if (xml.startsWith("<!--", position)) {
33649
- const close = xml.indexOf("-->", position + 4);
33650
- if (close === -1) malformed();
33651
- position = close + 3;
33652
- } else if (xml.startsWith("<![CDATA[", position)) {
33653
- const close = xml.indexOf("]]>", position + 9);
33654
- if (close === -1 || stack.length === 0) malformed();
33655
- addText(xml.slice(position + 9, close));
33656
- position = close + 3;
33657
- } else if (xml.startsWith("<?", position)) {
33658
- const close = xml.indexOf("?>", position + 2);
33659
- if (close === -1) malformed();
33660
- const target = xml.slice(position + 2, close).split(/\s/, 1)[0];
33661
- if (target.toLowerCase() === "xml" && position !== 0) malformed();
33662
- position = close + 2;
33663
- } else if (xml.startsWith("<!", position)) {
33664
- malformed();
33665
- } else if (xml.startsWith("</", position)) {
33666
- END_TAG.lastIndex = position;
33667
- const match = END_TAG.exec(xml);
33668
- const open = stack.pop();
33669
- if (!match || !open || open.qualifiedName !== match[1]) malformed();
33670
- position = END_TAG.lastIndex;
33671
- } else {
33672
- START_TAG.lastIndex = position;
33673
- const match = START_TAG.exec(xml);
33674
- if (!match || stack.length === 0 && root !== null) malformed();
33675
- for (const attribute of match[2].matchAll(ATTRIBUTE_VALUE)) decodeEntities(attribute[1] ?? attribute[2]);
33676
- const qualifiedName = match[1];
33677
- const element = {
33678
- name: qualifiedName.slice(qualifiedName.indexOf(":") + 1),
33679
- qualifiedName,
33680
- children: [],
33681
- text: ""
33682
- };
33683
- if (stack.length > 0) stack[stack.length - 1].children.push(element);
33684
- else root = element;
33685
- if (match[3] !== "/") stack.push(element);
33686
- position = START_TAG.lastIndex;
33687
34054
  }
34055
+ return textEnd;
34056
+ };
34057
+ let position = 0;
34058
+ while (position < xml.length) {
34059
+ position = readText(position);
34060
+ if (position >= xml.length) break;
34061
+ if (xml.startsWith("<!--", position)) position = skipComment(position);
34062
+ else if (xml.startsWith("<![CDATA[", position)) position = readCData(position);
34063
+ else if (xml.startsWith("<?", position)) position = skipProcessingInstruction(position);
34064
+ else if (xml.startsWith("<!", position)) malformed();
34065
+ else if (xml.startsWith("</", position)) position = closeElement(position);
34066
+ else position = openElement(position);
33688
34067
  }
33689
34068
  if (root === null || stack.length > 0) malformed();
33690
34069
  return root;
@@ -35174,7 +35553,7 @@ import {
35174
35553
  randomBytes as randomBytes10
35175
35554
  } from "node:crypto";
35176
35555
  function encodeBase64Url(value) {
35177
- return Buffer.from(value).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
35556
+ return Buffer.from(value).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/={1,2}$/, "");
35178
35557
  }
35179
35558
  function decodeBase64Url(value, name) {
35180
35559
  if (typeof value !== "string" || value.length === 0) {
@@ -35425,6 +35804,7 @@ var AiError, AiConfigError, AiTimeoutError, AiParseError, AiHTTPError, Ai, Aggre
35425
35804
  var init_aiClient = __esm({
35426
35805
  "../core/src/aiClient.ts"() {
35427
35806
  "use strict";
35807
+ init_slashTrim();
35428
35808
  init_api();
35429
35809
  AiError = class extends Error {
35430
35810
  };
@@ -35629,7 +36009,7 @@ var init_aiClient = __esm({
35629
36009
  throw new AiConfigError("AI URL must be an http or https URL");
35630
36010
  }
35631
36011
  if (url.protocol !== "http:" && url.protocol !== "https:") throw new AiConfigError("AI URL must be an http or https URL");
35632
- const path10 = url.pathname.replace(/\/+$/, "");
36012
+ const path10 = rtrimSlashes(url.pathname);
35633
36013
  if (path10 === "" || path10 === "/v1" || path10 === "/api" || path10 === "/v1beta/openai") {
35634
36014
  const suffix = provider === "anthropic" ? "/messages" : capability === "embed" ? "/embeddings" : "/chat/completions";
35635
36015
  url.pathname = (path10 || "/v1") + suffix;
@@ -37999,6 +38379,7 @@ __export(src_exports2, {
37999
38379
  backgroundTaskCount: () => backgroundTaskCount,
38000
38380
  buildEnvelope: () => buildEnvelope,
38001
38381
  buildFrame: () => buildFrame,
38382
+ buildSeedFieldMap: () => buildSeedFieldMap,
38002
38383
  buildSessionCookie: () => buildSessionCookie,
38003
38384
  cacheBackendStats: () => cacheBackendStats,
38004
38385
  cacheClear: () => cacheClear,
@@ -38104,6 +38485,7 @@ __export(src_exports2, {
38104
38485
  parseFrame: () => parseFrame,
38105
38486
  parseLineStream: () => parseLineStream,
38106
38487
  parseMultipart: () => parseMultipart,
38488
+ parseSeedRequest: () => parseSeedRequest,
38107
38489
  parseSseStream: () => parseSseStream,
38108
38490
  parseUpgradeHeaders: () => parseUpgradeHeaders,
38109
38491
  patch: () => patch,
@@ -39445,6 +39827,9 @@ var init_postgres = __esm({
39445
39827
  await withConnectTimeout(
39446
39828
  () => {
39447
39829
  this.client = typeof this.config === "string" ? new Client({ connectionString: this.config, ...timeoutOption }) : new Client({ ...this.config, ...timeoutOption });
39830
+ this.client.on("error", () => {
39831
+ this.connectionIsDead = true;
39832
+ });
39448
39833
  return this.client.connect();
39449
39834
  },
39450
39835
  budgetMs,
@@ -39468,6 +39853,52 @@ var init_postgres = __esm({
39468
39853
  throw new Error("PostgreSQL adapter not connected. Call connect() first.");
39469
39854
  }
39470
39855
  }
39856
+ // ── Reconnect after a dropped link (parity with the Python master, #236/#242) ──
39857
+ // pg's Client does not reconnect itself: once the server drops the link it must
39858
+ // be rebuilt. A statement that hits a dropped link reconnects and retries once
39859
+ // when nothing uncommitted went down with it; inside an explicit transaction the
39860
+ // error surfaces. A reconnect that itself fails leaves the link dead (not null-
39861
+ // guarded away), so the NEXT statement retries and recovers once a server returns.
39862
+ connectionIsDead = false;
39863
+ isConnectionError(e) {
39864
+ const msg = e instanceof Error ? e.message : String(e);
39865
+ return /connection terminated|terminating connection|server closed the connection|encountered a connection error|connection closed|not queryable|ECONNRESET|EPIPE|socket hang up/i.test(msg);
39866
+ }
39867
+ async reconnect() {
39868
+ void Promise.resolve(this.client?.end()).catch(() => {
39869
+ });
39870
+ this.client = null;
39871
+ this.connectionIsDead = false;
39872
+ await this.connect();
39873
+ }
39874
+ async ensureLiveConnection() {
39875
+ if (!this._inTransaction && (this.client === null || this.connectionIsDead)) {
39876
+ await this.reconnect();
39877
+ }
39878
+ }
39879
+ async runQuery(sql, params) {
39880
+ await this.ensureLiveConnection();
39881
+ this.ensureConnected();
39882
+ try {
39883
+ return await this.client.query(sql, params);
39884
+ } catch (e) {
39885
+ if (!this.isConnectionError(e)) throw e;
39886
+ this.connectionIsDead = true;
39887
+ if (this._inTransaction) throw e;
39888
+ await this.reconnect();
39889
+ return await this.client.query(sql, params);
39890
+ }
39891
+ }
39892
+ // Transaction control (BEGIN/COMMIT/ROLLBACK) runs RAW - no reconnect, no
39893
+ // pre-heal. A failed BEGIN/COMMIT/ROLLBACK must surface so the connection-pool
39894
+ // layer can discard the connection and restore capacity; reconnecting or
39895
+ // retrying here would mask that failure (databasePoolIsolation contract).
39896
+ // Dropped-link recovery stays on the DATA path (runQuery): the next data
39897
+ // statement heals the link.
39898
+ async rawQuery(sql) {
39899
+ this.ensureConnected();
39900
+ await this.client.query(sql);
39901
+ }
39471
39902
  /** Convert ? placeholders to $1, $2, ... for pg. */
39472
39903
  /** Ensure bytea columns are Buffer (already the case with pg). No-op guard. */
39473
39904
  decodeBlobs(row) {
@@ -39517,7 +39948,6 @@ var init_postgres = __esm({
39517
39948
  return null;
39518
39949
  }
39519
39950
  execute(sql, params) {
39520
- this.ensureConnected();
39521
39951
  const convertedSql = this.convertPlaceholders(sql);
39522
39952
  throw new Error("Use executeAsync() for PostgreSQL \u2014 async adapter requires async methods.");
39523
39953
  }
@@ -39552,9 +39982,8 @@ var init_postgres = __esm({
39552
39982
  }
39553
39983
  /** Async execute for real usage. */
39554
39984
  async executeAsync(sql, params) {
39555
- this.ensureConnected();
39556
39985
  const convertedSql = this.bindable(sql, params);
39557
- const result = await this.client.query(convertedSql, params);
39986
+ const result = await this.runQuery(convertedSql, params);
39558
39987
  if (result.rows?.[0]?.id !== void 0) {
39559
39988
  this._lastInsertId = this.normalizeId(result.rows[0].id);
39560
39989
  }
@@ -39565,9 +39994,8 @@ var init_postgres = __esm({
39565
39994
  }
39566
39995
  /** Async query for real usage. */
39567
39996
  async queryAsync(sql, params) {
39568
- this.ensureConnected();
39569
39997
  const convertedSql = this.bindable(sql, params);
39570
- const result = await this.client.query(convertedSql, params);
39998
+ const result = await this.runQuery(convertedSql, params);
39571
39999
  return result.rows.map((row) => this.decodeBlobs(row));
39572
40000
  }
39573
40001
  fetch(sql, params, limit, skip) {
@@ -39595,7 +40023,6 @@ var init_postgres = __esm({
39595
40023
  throw new Error("Use insertAsync() for PostgreSQL.");
39596
40024
  }
39597
40025
  async insertAsync(table2, data) {
39598
- this.ensureConnected();
39599
40026
  if (Array.isArray(data)) {
39600
40027
  const batch = buildInsertRows(ANSI_DIALECT, table2, data);
39601
40028
  if (!batch) return { success: true, affectedRows: 0 };
@@ -39609,7 +40036,7 @@ var init_postgres = __esm({
39609
40036
  }
39610
40037
  const { sql, values } = buildInsertRow(POSTGRES_DIALECT, table2, data, " RETURNING *");
39611
40038
  try {
39612
- const result = await this.client.query(sql, values);
40039
+ const result = await this.runQuery(sql, values);
39613
40040
  const insertedRow = result.rows[0];
39614
40041
  const id = this.normalizeId(insertedRow?.id);
39615
40042
  if (id !== null) this._lastInsertId = id;
@@ -39626,13 +40053,12 @@ var init_postgres = __esm({
39626
40053
  throw new Error("Use updateAsync() for PostgreSQL.");
39627
40054
  }
39628
40055
  async updateAsync(table2, data, filter, params) {
39629
- this.ensureConnected();
39630
40056
  const { sql, values } = buildUpdate(POSTGRES_DIALECT, table2, data, filter, params, {
39631
40057
  startAt: 1,
39632
40058
  convertFragment: (fragment, startAt) => this.convertPlaceholders(fragment, startAt)
39633
40059
  });
39634
40060
  try {
39635
- const result = await this.client.query(sql, values);
40061
+ const result = await this.runQuery(sql, values);
39636
40062
  return { success: true, affectedRows: result.rowCount ?? 0 };
39637
40063
  } catch (e) {
39638
40064
  return { success: false, affectedRows: 0, error: e.message };
@@ -39642,13 +40068,12 @@ var init_postgres = __esm({
39642
40068
  throw new Error("Use deleteAsync() for PostgreSQL.");
39643
40069
  }
39644
40070
  async deleteAsync(table2, filter, params) {
39645
- this.ensureConnected();
39646
40071
  const { sql, values } = buildDelete(POSTGRES_DIALECT, table2, filter, params, {
39647
40072
  startAt: 1,
39648
40073
  convertFragment: (fragment) => this.bindable(fragment, params)
39649
40074
  });
39650
40075
  try {
39651
- const result = await this.client.query(sql, values);
40076
+ const result = await this.runQuery(sql, values);
39652
40077
  return { success: true, affectedRows: result.rowCount ?? 0 };
39653
40078
  } catch (e) {
39654
40079
  return { success: false, affectedRows: 0, error: e.message };
@@ -39658,22 +40083,28 @@ var init_postgres = __esm({
39658
40083
  throw new Error("Use startTransactionAsync() for PostgreSQL.");
39659
40084
  }
39660
40085
  async startTransactionAsync() {
39661
- await this.executeAsync("BEGIN");
40086
+ await this.rawQuery("BEGIN");
39662
40087
  this._inTransaction = true;
39663
40088
  }
39664
40089
  commit() {
39665
40090
  throw new Error("Use commitAsync() for PostgreSQL.");
39666
40091
  }
39667
40092
  async commitAsync() {
39668
- await this.executeAsync("COMMIT");
39669
- this._inTransaction = false;
40093
+ try {
40094
+ await this.rawQuery("COMMIT");
40095
+ } finally {
40096
+ this._inTransaction = false;
40097
+ }
39670
40098
  }
39671
40099
  rollback() {
39672
40100
  throw new Error("Use rollbackAsync() for PostgreSQL.");
39673
40101
  }
39674
40102
  async rollbackAsync() {
39675
- await this.executeAsync("ROLLBACK");
39676
- this._inTransaction = false;
40103
+ try {
40104
+ await this.rawQuery("ROLLBACK");
40105
+ } finally {
40106
+ this._inTransaction = false;
40107
+ }
39677
40108
  }
39678
40109
  getTables() {
39679
40110
  throw new Error("Use tablesAsync() for PostgreSQL.");
@@ -42497,10 +42928,10 @@ __export(database_exports, {
42497
42928
  stripTrailingSemicolons: () => stripTrailingSemicolons,
42498
42929
  wrapWithCache: () => wrapWithCache
42499
42930
  });
42500
- import { AsyncLocalStorage as AsyncLocalStorage3 } from "node:async_hooks";
42931
+ import { AsyncLocalStorage as AsyncLocalStorage4 } from "node:async_hooks";
42501
42932
  function stripTrailingSemicolons(sql) {
42502
42933
  if (!sql) return sql;
42503
- let stripped = sql.replace(/\s+$/, "");
42934
+ let stripped = sql.trimEnd();
42504
42935
  while (stripped.endsWith(";")) {
42505
42936
  stripped = stripped.slice(0, -1).replace(/\s+$/, "");
42506
42937
  }
@@ -42667,6 +43098,13 @@ async function createAdapterFromUrl(url, username, password) {
42667
43098
  }
42668
43099
  async function buildAdapterFromUrl(url, username, password) {
42669
43100
  const parsed = parseDatabaseUrl(url, username, password);
43101
+ const serverConfig = {
43102
+ host: parsed.host ?? void 0,
43103
+ port: parsed.port ?? void 0,
43104
+ user: parsed.username ?? void 0,
43105
+ password: parsed.password ?? void 0,
43106
+ database: parsed.database || void 0
43107
+ };
42670
43108
  switch (parsed.engine) {
42671
43109
  case "sqlite": {
42672
43110
  const { SQLiteAdapter: SQLiteAdapter2 } = await Promise.resolve().then(() => (init_sqlite(), sqlite_exports));
@@ -42674,49 +43112,25 @@ async function buildAdapterFromUrl(url, username, password) {
42674
43112
  }
42675
43113
  case "postgres": {
42676
43114
  const { PostgresAdapter: PostgresAdapter2 } = await Promise.resolve().then(() => (init_postgres(), postgres_exports));
42677
- const adapter = new PostgresAdapter2({
42678
- host: parsed.host ?? void 0,
42679
- port: parsed.port ?? void 0,
42680
- user: parsed.username ?? void 0,
42681
- password: parsed.password ?? void 0,
42682
- database: parsed.database || void 0
42683
- });
43115
+ const adapter = new PostgresAdapter2(serverConfig);
42684
43116
  await adapter.connect();
42685
43117
  return adapter;
42686
43118
  }
42687
43119
  case "mysql": {
42688
43120
  const { MysqlAdapter: MysqlAdapter2 } = await Promise.resolve().then(() => (init_mysql(), mysql_exports));
42689
- const adapter = new MysqlAdapter2({
42690
- host: parsed.host ?? void 0,
42691
- port: parsed.port ?? void 0,
42692
- user: parsed.username ?? void 0,
42693
- password: parsed.password ?? void 0,
42694
- database: parsed.database || void 0
42695
- });
43121
+ const adapter = new MysqlAdapter2(serverConfig);
42696
43122
  await adapter.connect();
42697
43123
  return adapter;
42698
43124
  }
42699
43125
  case "mssql": {
42700
43126
  const { MssqlAdapter: MssqlAdapter2 } = await Promise.resolve().then(() => (init_mssql(), mssql_exports));
42701
- const adapter = new MssqlAdapter2({
42702
- host: parsed.host ?? void 0,
42703
- port: parsed.port ?? void 0,
42704
- user: parsed.username ?? void 0,
42705
- password: parsed.password ?? void 0,
42706
- database: parsed.database || void 0
42707
- });
43127
+ const adapter = new MssqlAdapter2(serverConfig);
42708
43128
  await adapter.connect();
42709
43129
  return adapter;
42710
43130
  }
42711
43131
  case "firebird": {
42712
43132
  const { FirebirdAdapter: FirebirdAdapter2 } = await Promise.resolve().then(() => (init_firebird(), firebird_exports));
42713
- const adapter = new FirebirdAdapter2({
42714
- host: parsed.host ?? void 0,
42715
- port: parsed.port ?? void 0,
42716
- user: parsed.username ?? void 0,
42717
- password: parsed.password ?? void 0,
42718
- database: parsed.database || void 0
42719
- });
43133
+ const adapter = new FirebirdAdapter2(serverConfig);
42720
43134
  await adapter.connect();
42721
43135
  return adapter;
42722
43136
  }
@@ -42911,9 +43325,9 @@ var init_database = __esm({
42911
43325
  leases = /* @__PURE__ */ new Map();
42912
43326
  discardedSlots = /* @__PURE__ */ new Set();
42913
43327
  repairs = /* @__PURE__ */ new Map();
42914
- leaseOwner = new AsyncLocalStorage3();
42915
- operationStore = new AsyncLocalStorage3();
42916
- txStore = new AsyncLocalStorage3();
43328
+ leaseOwner = new AsyncLocalStorage4();
43329
+ operationStore = new AsyncLocalStorage4();
43330
+ txStore = new AsyncLocalStorage4();
42917
43331
  /**
42918
43332
  * Create a Database wrapping an existing adapter.
42919
43333
  * For creating a Database from a URL, use the async static factories:
@@ -45653,7 +46067,7 @@ function tableData(opts) {
45653
46067
  readonly: !opts.editable,
45654
46068
  inline_script: opts.inlineScript,
45655
46069
  table_name: h(opts.tableName),
45656
- table_id_attr: opts.tableId ? ` id="${h(opts.tableId)}"` : ""
46070
+ table_id: opts.tableId ? String(opts.tableId) : ""
45657
46071
  };
45658
46072
  }
45659
46073
  var init_crudTable = __esm({
@@ -45694,13 +46108,13 @@ function renderModalForm(mode, columns, pk, edit) {
45694
46108
  value: "",
45695
46109
  placeholder: h(`Enter ${label.toLowerCase()}`),
45696
46110
  type: "text",
45697
- required_attr: "",
46111
+ required: false,
45698
46112
  input: true
45699
46113
  };
45700
46114
  });
45701
46115
  return renderCrudTemplate("form", {
45702
46116
  wrap: true,
45703
- form_id_attr: ` id="form-${mode}"`,
46117
+ form_id: `form-${mode}`,
45704
46118
  action: "",
45705
46119
  form_method: "POST",
45706
46120
  method_override: null,
@@ -45757,7 +46171,7 @@ function fieldInputShape(field, base) {
45757
46171
  case "text":
45758
46172
  return { ...base, textarea: true };
45759
46173
  case "boolean":
45760
- return { ...base, checkbox: true, checked_attr: value ? " checked" : "" };
46174
+ return { ...base, checkbox: true, checked: !!value };
45761
46175
  case "select":
45762
46176
  return { ...base, select: true, options_html: buildOptions(field.options, value) };
45763
46177
  case "date":
@@ -45780,7 +46194,7 @@ function buildCustomField(field) {
45780
46194
  label: h(String(label)),
45781
46195
  value: h(field.value ?? ""),
45782
46196
  placeholder: "",
45783
- required_attr: field.required ? " required" : ""
46197
+ required: !!field.required
45784
46198
  };
45785
46199
  return fieldInputShape(field, base);
45786
46200
  }
@@ -45788,7 +46202,7 @@ function generateForm2(fields, options = {}) {
45788
46202
  const verb = String(options.method ?? "POST").toUpperCase();
45789
46203
  return renderCrudTemplate("form", {
45790
46204
  wrap: true,
45791
- form_id_attr: "",
46205
+ form_id: "",
45792
46206
  action: h(options.action ?? "/"),
45793
46207
  form_method: h(verb),
45794
46208
  method_override: ["PUT", "PATCH", "DELETE"].includes(verb) ? verb : null,
@@ -48360,6 +48774,12 @@ import { dirname as dirname16, isAbsolute as isAbsolute6, join as join32 } from
48360
48774
  function iso(d) {
48361
48775
  return d.toISOString();
48362
48776
  }
48777
+ function setOwn(obj, key, value) {
48778
+ Object.defineProperty(obj, key, { value, writable: true, enumerable: true, configurable: true });
48779
+ }
48780
+ function getOwn(obj, key) {
48781
+ return Object.hasOwn(obj, key) ? obj[key] : void 0;
48782
+ }
48363
48783
  function encodeValue(value) {
48364
48784
  if (value instanceof ObjectId) return value.toString();
48365
48785
  if (value instanceof Date) return iso(value);
@@ -48367,7 +48787,7 @@ function encodeValue(value) {
48367
48787
  if (value !== null && typeof value === "object") {
48368
48788
  const out = {};
48369
48789
  for (const [k, v] of Object.entries(value)) {
48370
- out[k] = encodeValue(v);
48790
+ setOwn(out, k, encodeValue(v));
48371
48791
  }
48372
48792
  return out;
48373
48793
  }
@@ -48386,7 +48806,7 @@ function decodeValue(value) {
48386
48806
  if (value !== null && typeof value === "object") {
48387
48807
  const out = {};
48388
48808
  for (const [k, v] of Object.entries(value)) {
48389
- out[k] = decodeValue(v);
48809
+ setOwn(out, k, decodeValue(v));
48390
48810
  }
48391
48811
  return out;
48392
48812
  }
@@ -48532,31 +48952,32 @@ function project(doc, projection) {
48532
48952
  const exclude = new Set(Object.entries(projection).filter(([, v]) => !v).map(([k]) => k));
48533
48953
  if (include.size > 0) {
48534
48954
  const out2 = {};
48535
- for (const k of include) if (k in doc) out2[k] = doc[k];
48955
+ for (const k of include) if (Object.hasOwn(doc, k)) setOwn(out2, k, doc[k]);
48536
48956
  const idVal = projection._id;
48537
48957
  if ((idVal === void 0 || idVal) && "_id" in doc) out2._id = doc._id;
48538
48958
  return out2;
48539
48959
  }
48540
48960
  const out = {};
48541
- for (const [k, v] of Object.entries(doc)) if (!exclude.has(k)) out[k] = v;
48961
+ for (const [k, v] of Object.entries(doc)) if (!exclude.has(k)) setOwn(out, k, v);
48542
48962
  return out;
48543
48963
  }
48544
48964
  function setPath(doc, dotted, value) {
48545
48965
  const parts = dotted.split(".");
48546
48966
  let node = doc;
48547
48967
  for (const p of parts.slice(0, -1)) {
48548
- if (node[p] === void 0 || node[p] === null || typeof node[p] !== "object") {
48549
- node[p] = {};
48968
+ const child = getOwn(node, p);
48969
+ if (child === void 0 || child === null || typeof child !== "object") {
48970
+ setOwn(node, p, {});
48550
48971
  }
48551
48972
  node = node[p];
48552
48973
  }
48553
- node[parts[parts.length - 1]] = value;
48974
+ setOwn(node, parts[parts.length - 1], value);
48554
48975
  }
48555
48976
  function unsetPath(doc, dotted) {
48556
48977
  const parts = dotted.split(".");
48557
48978
  let node = doc;
48558
48979
  for (const p of parts.slice(0, -1)) {
48559
- const next = node[p];
48980
+ const next = getOwn(node, p);
48560
48981
  if (next === null || typeof next !== "object") return;
48561
48982
  node = next;
48562
48983
  }
@@ -49908,20 +50329,210 @@ var init_attachment = __esm({
49908
50329
  }
49909
50330
  });
49910
50331
 
50332
+ // src/realtime/s3Client.ts
50333
+ import { createHash as createHash11, createHmac as createHmac4 } from "node:crypto";
50334
+ function retryAfterSeconds(raw) {
50335
+ if (raw == null) return null;
50336
+ const n = Number(raw);
50337
+ return Number.isFinite(n) ? Math.max(0, n) : null;
50338
+ }
50339
+ function uriEncode(value, isPath) {
50340
+ let out = "";
50341
+ for (const byte of Buffer.from(value, "utf8")) {
50342
+ const ch = String.fromCharCode(byte);
50343
+ if (UNRESERVED.test(ch) || isPath && ch === "/") out += ch;
50344
+ else out += "%" + byte.toString(16).toUpperCase().padStart(2, "0");
50345
+ }
50346
+ return out;
50347
+ }
50348
+ function sha256Hex2(data) {
50349
+ return createHash11("sha256").update(data).digest("hex");
50350
+ }
50351
+ function hmac2(key, msg) {
50352
+ return createHmac4("sha256", key).update(msg, "utf8").digest();
50353
+ }
50354
+ var ALGORITHM, SERVICE, UNRESERVED, MAX_RETRIES, BACKOFF_BASE, BACKOFF_CAP, S3Error, S3ConfigError, sleep, S3Client;
50355
+ var init_s3Client = __esm({
50356
+ "src/realtime/s3Client.ts"() {
50357
+ "use strict";
50358
+ ALGORITHM = "AWS4-HMAC-SHA256";
50359
+ SERVICE = "s3";
50360
+ UNRESERVED = /[A-Za-z0-9\-_.~]/;
50361
+ MAX_RETRIES = 2;
50362
+ BACKOFF_BASE = 0.5;
50363
+ BACKOFF_CAP = 20;
50364
+ S3Error = class extends Error {
50365
+ constructor(status2, message) {
50366
+ super(message);
50367
+ this.status = status2;
50368
+ this.name = "S3Error";
50369
+ }
50370
+ status;
50371
+ /** Seconds from a Retry-After header in its delta-seconds form, else null. */
50372
+ retryAfter = null;
50373
+ };
50374
+ S3ConfigError = class extends Error {
50375
+ constructor(message) {
50376
+ super(message);
50377
+ this.name = "S3ConfigError";
50378
+ }
50379
+ };
50380
+ sleep = (ms) => new Promise((r) => setTimeout(r, ms));
50381
+ S3Client = class {
50382
+ scheme;
50383
+ host;
50384
+ // authority (host[:port]) — matches the Host header
50385
+ prefix;
50386
+ // path an endpoint carries (https://host/s3 -> "/s3"), "" if none
50387
+ region;
50388
+ accessKey;
50389
+ secretKey;
50390
+ timeout;
50391
+ constructor(opts = {}) {
50392
+ this.region = opts.region || "us-east-1";
50393
+ this.accessKey = opts.accessKey || "";
50394
+ this.secretKey = opts.secretKey || "";
50395
+ this.timeout = opts.timeout ?? 3e4;
50396
+ let base = opts.endpoint || `https://s3.${this.region}.amazonaws.com`;
50397
+ while (base.endsWith("/")) base = base.slice(0, -1);
50398
+ const m = /^([a-z][a-z0-9+.-]*):\/\/([^/]+)(\/.*)?$/i.exec(base);
50399
+ this.scheme = m ? m[1] : "https";
50400
+ this.host = m ? m[2] : base;
50401
+ let p = m && m[3] ? m[3] : "";
50402
+ while (p.endsWith("/")) p = p.slice(0, -1);
50403
+ this.prefix = p;
50404
+ }
50405
+ // -- public API (the subset S3Storage uses) --------------------------------
50406
+ async putObject(bucket, key, data, contentType = "application/octet-stream") {
50407
+ const body = Buffer.isBuffer(data) ? data : Buffer.from(data);
50408
+ await this.request("PUT", this.canonicalUri(bucket, key), body, { "content-type": contentType });
50409
+ }
50410
+ async getObject(bucket, key) {
50411
+ return (await this.request("GET", this.canonicalUri(bucket, key), Buffer.alloc(0))).body;
50412
+ }
50413
+ async deleteObject(bucket, key) {
50414
+ await this.request("DELETE", this.canonicalUri(bucket, key), Buffer.alloc(0));
50415
+ }
50416
+ async headObject(bucket, key) {
50417
+ await this.request("HEAD", this.canonicalUri(bucket, key), Buffer.alloc(0));
50418
+ }
50419
+ /** Create the bucket (path-style `PUT /<bucket>`); an already-owned bucket (409) is success. */
50420
+ async createBucket(bucket) {
50421
+ try {
50422
+ await this.request("PUT", `${this.prefix}/${uriEncode(bucket, true)}`, Buffer.alloc(0));
50423
+ } catch (e) {
50424
+ if (!(e instanceof S3Error) || e.status !== 409) throw e;
50425
+ }
50426
+ }
50427
+ /** A URL that fetches the object directly, signed via SigV4 query params. */
50428
+ presignedGetUrl(bucket, key, expires = 3600) {
50429
+ this.requireCredentials();
50430
+ const { amzDate, dateStamp } = this.now();
50431
+ const uri = this.canonicalUri(bucket, key);
50432
+ const scope = `${dateStamp}/${this.region}/${SERVICE}/aws4_request`;
50433
+ const query = {
50434
+ "X-Amz-Algorithm": ALGORITHM,
50435
+ "X-Amz-Credential": `${this.accessKey}/${scope}`,
50436
+ "X-Amz-Date": amzDate,
50437
+ "X-Amz-Expires": String(expires),
50438
+ "X-Amz-SignedHeaders": "host"
50439
+ };
50440
+ const canonicalQs = this.canonicalQuery(query);
50441
+ const canonicalRequest = ["GET", uri, canonicalQs, `host:${this.host}
50442
+ `, "host", "UNSIGNED-PAYLOAD"].join("\n");
50443
+ const signature = this.sign(canonicalRequest, amzDate, dateStamp, scope);
50444
+ return `${this.scheme}://${this.host}${uri}?${canonicalQs}&X-Amz-Signature=${signature}`;
50445
+ }
50446
+ // -- signing + transport ----------------------------------------------------
50447
+ requireCredentials() {
50448
+ if (!this.accessKey || !this.secretKey) {
50449
+ throw new S3ConfigError(
50450
+ "S3 credentials are not set: set TINA4_STORAGE_KEY and TINA4_STORAGE_SECRET"
50451
+ );
50452
+ }
50453
+ }
50454
+ now() {
50455
+ const iso2 = (/* @__PURE__ */ new Date()).toISOString().replace(/[:-]|\.\d{3}/g, "");
50456
+ return { amzDate: iso2, dateStamp: iso2.slice(0, 8) };
50457
+ }
50458
+ canonicalUri(bucket, key) {
50459
+ return `${this.prefix}/${uriEncode(bucket, true)}/${uriEncode(key, true)}`;
50460
+ }
50461
+ canonicalQuery(query) {
50462
+ return Object.keys(query).sort().map((k) => `${uriEncode(k, false)}=${uriEncode(query[k], false)}`).join("&");
50463
+ }
50464
+ signingKey(dateStamp) {
50465
+ const kDate = hmac2(`AWS4${this.secretKey}`, dateStamp);
50466
+ const kRegion = hmac2(kDate, this.region);
50467
+ const kService = hmac2(kRegion, SERVICE);
50468
+ return hmac2(kService, "aws4_request");
50469
+ }
50470
+ sign(canonicalRequest, amzDate, dateStamp, scope) {
50471
+ const stringToSign = [ALGORITHM, amzDate, scope, sha256Hex2(canonicalRequest)].join("\n");
50472
+ return createHmac4("sha256", this.signingKey(dateStamp)).update(stringToSign, "utf8").digest("hex");
50473
+ }
50474
+ async request(method, uri, body, extraHeaders = {}) {
50475
+ this.requireCredentials();
50476
+ for (let attempt = 0; ; attempt++) {
50477
+ const last = attempt === MAX_RETRIES;
50478
+ let delay2 = null;
50479
+ try {
50480
+ return await this.send(method, uri, body, extraHeaders);
50481
+ } catch (e) {
50482
+ if (e instanceof S3Error) {
50483
+ if (last || !(e.status === 429 || e.status >= 500)) throw e;
50484
+ delay2 = e.retryAfter;
50485
+ } else {
50486
+ if (last) throw e;
50487
+ delay2 = null;
50488
+ }
50489
+ }
50490
+ if (delay2 == null) delay2 = Math.random() * (BACKOFF_BASE * 2 ** attempt);
50491
+ await sleep(Math.min(delay2, BACKOFF_CAP) * 1e3);
50492
+ }
50493
+ }
50494
+ async send(method, uri, body, extraHeaders = {}) {
50495
+ const { amzDate, dateStamp } = this.now();
50496
+ const payloadHash = sha256Hex2(body);
50497
+ const signed = {
50498
+ host: this.host,
50499
+ "x-amz-content-sha256": payloadHash,
50500
+ "x-amz-date": amzDate
50501
+ };
50502
+ const signedKeys = Object.keys(signed).sort();
50503
+ const canonicalHeaders = signedKeys.map((k) => `${k}:${signed[k]}
50504
+ `).join("");
50505
+ const signedHeaders = signedKeys.join(";");
50506
+ const canonicalRequest = [method, uri, "", canonicalHeaders, signedHeaders, payloadHash].join("\n");
50507
+ const scope = `${dateStamp}/${this.region}/${SERVICE}/aws4_request`;
50508
+ const signature = this.sign(canonicalRequest, amzDate, dateStamp, scope);
50509
+ const authorization = `${ALGORITHM} Credential=${this.accessKey}/${scope}, SignedHeaders=${signedHeaders}, Signature=${signature}`;
50510
+ const headers = {
50511
+ Authorization: authorization,
50512
+ "x-amz-content-sha256": payloadHash,
50513
+ "x-amz-date": amzDate,
50514
+ ...extraHeaders
50515
+ };
50516
+ const url = `${this.scheme}://${this.host}${uri}`;
50517
+ const init = { method, headers, redirect: "manual" };
50518
+ if (method === "PUT" || method === "POST") init.body = body;
50519
+ if (AbortSignal.timeout) init.signal = AbortSignal.timeout(this.timeout);
50520
+ const response = await fetch(url, init);
50521
+ if (response.status < 200 || response.status >= 300) {
50522
+ const err = new S3Error(response.status, `${method} ${uri}: HTTP ${response.status}`);
50523
+ err.retryAfter = retryAfterSeconds(response.headers.get("retry-after"));
50524
+ throw err;
50525
+ }
50526
+ return { status: response.status, body: Buffer.from(await response.arrayBuffer()) };
50527
+ }
50528
+ };
50529
+ }
50530
+ });
50531
+
49911
50532
  // src/realtime/storage.ts
49912
50533
  import { randomBytes as randomBytes12 } from "node:crypto";
49913
- import { mkdirSync as mkdirSync21, readFileSync as readFileSync26, writeFileSync as writeFileSync18, unlinkSync as unlinkSync8, statSync as statSync19 } from "node:fs";
50534
+ import { mkdirSync as mkdirSync21, readFileSync as readFileSync26, writeFileSync as writeFileSync18, unlinkSync as unlinkSync9, statSync as statSync19 } from "node:fs";
49914
50535
  import { resolve as resolve20, sep as sep8 } from "node:path";
49915
- import { createRequire as createRequire8 } from "node:module";
49916
- function loadAwsSdk(packageName) {
49917
- try {
49918
- return require2(packageName);
49919
- } catch (error2) {
49920
- const missing = error2?.code === "MODULE_NOT_FOUND" && String(error2?.message ?? "").includes(`'${packageName}'`);
49921
- if (!missing) throw error2;
49922
- throw optionalPackageMissing("S3Storage", S3_PACKAGES);
49923
- }
49924
- }
49925
50536
  function storageKey(filename = "") {
49926
50537
  let ext = "";
49927
50538
  if (filename && filename.includes(".")) {
@@ -49946,14 +50557,12 @@ function selectStorage(storage) {
49946
50557
  }
49947
50558
  return new LocalStorage();
49948
50559
  }
49949
- var require2, S3_PACKAGES, UNSAFE, LocalStorage, S3Storage;
50560
+ var UNSAFE, LocalStorage, S3Storage;
49950
50561
  var init_storage = __esm({
49951
50562
  "src/realtime/storage.ts"() {
49952
50563
  "use strict";
49953
50564
  init_src2();
49954
- init_optionalPackage();
49955
- require2 = createRequire8(import.meta.url);
49956
- S3_PACKAGES = ["@aws-sdk/client-s3", "@aws-sdk/s3-request-presigner"];
50565
+ init_s3Client();
49957
50566
  UNSAFE = /[^A-Za-z0-9]/g;
49958
50567
  LocalStorage = class {
49959
50568
  directory;
@@ -49985,7 +50594,7 @@ var init_storage = __esm({
49985
50594
  }
49986
50595
  delete(key) {
49987
50596
  try {
49988
- unlinkSync8(this.pathFor(key));
50597
+ unlinkSync9(this.pathFor(key));
49989
50598
  } catch {
49990
50599
  }
49991
50600
  }
@@ -50003,51 +50612,36 @@ var init_storage = __esm({
50003
50612
  constructor(opts = {}) {
50004
50613
  this.bucket = opts.bucket || process.env.TINA4_STORAGE_BUCKET || "";
50005
50614
  if (!this.bucket) throw new Error("S3Storage requires TINA4_STORAGE_BUCKET");
50006
- const { S3Client } = loadAwsSdk("@aws-sdk/client-s3");
50007
- loadAwsSdk("@aws-sdk/s3-request-presigner");
50008
- const endpoint = opts.endpoint || process.env.TINA4_STORAGE_URL;
50009
50615
  this.client = new S3Client({
50010
- endpoint: endpoint || void 0,
50011
- forcePathStyle: true,
50616
+ endpoint: opts.endpoint || process.env.TINA4_STORAGE_URL || void 0,
50012
50617
  region: opts.region || process.env.TINA4_STORAGE_REGION || "us-east-1",
50013
- credentials: {
50014
- accessKeyId: opts.key || process.env.TINA4_STORAGE_KEY || "",
50015
- secretAccessKey: opts.secret || process.env.TINA4_STORAGE_SECRET || ""
50016
- }
50618
+ accessKey: opts.key || process.env.TINA4_STORAGE_KEY || "",
50619
+ secretKey: opts.secret || process.env.TINA4_STORAGE_SECRET || ""
50017
50620
  });
50018
50621
  }
50019
50622
  async put(key, data, mime = "application/octet-stream") {
50020
- const { PutObjectCommand } = loadAwsSdk("@aws-sdk/client-s3");
50021
- await this.client.send(new PutObjectCommand({ Bucket: this.bucket, Key: key, Body: data, ContentType: mime }));
50623
+ await this.client.putObject(this.bucket, key, data, mime);
50022
50624
  }
50023
50625
  async get(key) {
50024
50626
  try {
50025
- const { GetObjectCommand } = loadAwsSdk("@aws-sdk/client-s3");
50026
- const res = await this.client.send(new GetObjectCommand({ Bucket: this.bucket, Key: key }));
50027
- const chunks = [];
50028
- for await (const chunk of res.Body) chunks.push(Buffer.from(chunk));
50029
- return Buffer.concat(chunks);
50627
+ return await this.client.getObject(this.bucket, key);
50030
50628
  } catch {
50031
50629
  return null;
50032
50630
  }
50033
50631
  }
50034
50632
  async url(key, ttl = 3600) {
50035
- const { GetObjectCommand } = loadAwsSdk("@aws-sdk/client-s3");
50036
- const { getSignedUrl } = loadAwsSdk("@aws-sdk/s3-request-presigner");
50037
- return getSignedUrl(this.client, new GetObjectCommand({ Bucket: this.bucket, Key: key }), { expiresIn: ttl });
50633
+ return this.client.presignedGetUrl(this.bucket, key, ttl);
50038
50634
  }
50039
50635
  async delete(key) {
50040
50636
  try {
50041
- const { DeleteObjectCommand } = loadAwsSdk("@aws-sdk/client-s3");
50042
- await this.client.send(new DeleteObjectCommand({ Bucket: this.bucket, Key: key }));
50637
+ await this.client.deleteObject(this.bucket, key);
50043
50638
  } catch (e) {
50044
50639
  Log.error(`S3Storage delete failed for ${key}: ${e.message}`);
50045
50640
  }
50046
50641
  }
50047
50642
  async exists(key) {
50048
50643
  try {
50049
- const { HeadObjectCommand } = loadAwsSdk("@aws-sdk/client-s3");
50050
- await this.client.send(new HeadObjectCommand({ Bucket: this.bucket, Key: key }));
50644
+ await this.client.headObject(this.bucket, key);
50051
50645
  return true;
50052
50646
  } catch {
50053
50647
  return false;
@@ -50058,7 +50652,7 @@ var init_storage = __esm({
50058
50652
  });
50059
50653
 
50060
50654
  // src/realtime/realtime.ts
50061
- import { createHmac as createHmac4 } from "node:crypto";
50655
+ import { createHmac as createHmac5 } from "node:crypto";
50062
50656
  function iceServers() {
50063
50657
  const stun = process.env.TINA4_RTC_STUN_URLS || DEFAULT_STUN;
50064
50658
  const servers = [{ urls: splitUrls(stun) }];
@@ -50067,14 +50661,14 @@ function iceServers() {
50067
50661
  if (turnUrl && secret) {
50068
50662
  const ttl = parseInt(process.env.TINA4_RTC_TURN_TTL || "3600", 10);
50069
50663
  const username = String(Math.floor(Date.now() / 1e3) + ttl);
50070
- const credential = createHmac4("sha1", secret).update(username).digest("base64");
50664
+ const credential = createHmac5("sha1", secret).update(username).digest("base64");
50071
50665
  servers.push({ urls: splitUrls(turnUrl), username, credential });
50072
50666
  }
50073
50667
  return servers;
50074
50668
  }
50075
50669
  async function realtime(options = {}) {
50076
50670
  const features = options.features ?? ["calls"];
50077
- const raw = (options.prefix ?? "").replace(/^\/+|\/+$/g, "");
50671
+ const raw = trimSlashes(options.prefix ?? "");
50078
50672
  const p = raw ? `/${raw}` : "";
50079
50673
  _authorize = options.authorize;
50080
50674
  if (features.includes("chat") || features.includes("files")) {
@@ -50346,6 +50940,7 @@ var DEFAULT_STUN, _authorize;
50346
50940
  var init_realtime = __esm({
50347
50941
  "src/realtime/realtime.ts"() {
50348
50942
  "use strict";
50943
+ init_slashTrim();
50349
50944
  init_src2();
50350
50945
  init_workspace();
50351
50946
  init_channel();
@@ -50363,6 +50958,7 @@ var init_realtime2 = __esm({
50363
50958
  "use strict";
50364
50959
  init_realtime();
50365
50960
  init_storage();
50961
+ init_s3Client();
50366
50962
  init_workspace();
50367
50963
  init_channel();
50368
50964
  init_channelMember();