tina4-nodejs 3.13.165 → 3.13.166

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.
@@ -1423,10 +1423,10 @@ var init_databaseResult = __esm({
1423
1423
  _adapter;
1424
1424
  _sql;
1425
1425
  _columnInfoCache;
1426
- constructor(records, columns, count, limit, offset, adapter, sql) {
1426
+ constructor(records, columns, count2, limit, offset, adapter, sql) {
1427
1427
  this.records = records ?? [];
1428
1428
  this.columns = columns ?? (this.records.length > 0 ? Object.keys(this.records[0]) : []);
1429
- this.count = count ?? this.records.length;
1429
+ this.count = count2 ?? this.records.length;
1430
1430
  this.limit = limit ?? this.records.length;
1431
1431
  this.offset = offset ?? 0;
1432
1432
  this._adapter = adapter;
@@ -1719,36 +1719,28 @@ var init_modelCollection = __esm({
1719
1719
  }
1720
1720
  });
1721
1721
 
1722
- // ../orm/src/databaseUrl.ts
1723
- import { inspect } from "node:util";
1724
- function stripOneSlash(path9) {
1725
- return path9.startsWith("/") ? path9.slice(1) : path9;
1726
- }
1727
- function decode(value) {
1728
- if (value === void 0 || value === "") return null;
1729
- return decodeURIComponent(value);
1730
- }
1722
+ // src/urlRedaction.ts
1731
1723
  function endOfKeywordValue(text, start2) {
1732
1724
  const open = text[start2];
1733
1725
  if (open === "{") {
1734
1726
  const close = text.indexOf("}", start2 + 1);
1735
1727
  return close === -1 ? text.length : close + 1;
1736
1728
  }
1737
- if (open === "'" || open === '"') {
1738
- let i2 = start2 + 1;
1739
- while (i2 < text.length) {
1740
- if (text[i2] === "\\") {
1741
- i2 += 2;
1742
- continue;
1743
- }
1744
- if (text[i2] === open) return i2 + 1;
1745
- i2++;
1729
+ if (open === "'" || open === '"') return endOfQuoted(text, start2, open);
1730
+ const end = text.slice(start2).search(/[;&]/);
1731
+ return end === -1 ? text.length : start2 + end;
1732
+ }
1733
+ function endOfQuoted(text, start2, quote) {
1734
+ let i = start2 + 1;
1735
+ while (i < text.length) {
1736
+ if (text[i] === "\\") {
1737
+ i += 2;
1738
+ continue;
1746
1739
  }
1747
- return text.length;
1740
+ if (text[i] === quote) return i + 1;
1741
+ i++;
1748
1742
  }
1749
- let i = start2;
1750
- while (i < text.length && text[i] !== ";" && text[i] !== "&") i++;
1751
- return i;
1743
+ return text.length;
1752
1744
  }
1753
1745
  function redactKeywordValues(text) {
1754
1746
  const pattern = new RegExp(SECRET_KEYWORD_PATTERN.source, SECRET_KEYWORD_PATTERN.flags);
@@ -1763,57 +1755,258 @@ function redactKeywordValues(text) {
1763
1755
  }
1764
1756
  return out + text.slice(cursor);
1765
1757
  }
1766
- function authorityOf(raw) {
1767
- const separator = raw.indexOf("://");
1768
- if (separator === -1) return null;
1769
- const rest = raw.slice(separator + 3);
1770
- const end = rest.search(/[/?#]/);
1771
- return end === -1 ? rest : rest.slice(0, end);
1772
- }
1773
- function rawUserinfo(raw) {
1774
- const authority = authorityOf(raw);
1775
- if (authority === null) return null;
1776
- const at = authority.lastIndexOf("@");
1777
- return at === -1 ? null : authority.slice(0, at);
1778
- }
1779
- function redactUserinfoPassword(raw) {
1780
- const authority = authorityOf(raw);
1781
- if (authority === null) return raw;
1782
- const at = authority.lastIndexOf("@");
1783
- if (at === -1) return raw;
1784
- const colon = authority.slice(0, at).indexOf(":");
1785
- if (colon === -1) return raw;
1786
- const authorityStart = raw.indexOf("://") + 3;
1787
- return raw.slice(0, authorityStart + colon + 1) + REDACTED + raw.slice(authorityStart + at);
1758
+ function credentialSpans(line) {
1759
+ const spans = [];
1760
+ const marker = new RegExp(SCHEME_MARKER.source, "g");
1761
+ const lastAt = line.lastIndexOf("@");
1762
+ let match;
1763
+ while ((match = marker.exec(line)) !== null) {
1764
+ const start2 = match.index + match[0].length;
1765
+ const withAt = userinfoSpan(line, start2, lastAt);
1766
+ if (withAt !== null) {
1767
+ spans.push(withAt);
1768
+ marker.lastIndex = lastAt + 1;
1769
+ continue;
1770
+ }
1771
+ const portShaped = portShapedSpan(line, start2);
1772
+ if (portShaped !== null) {
1773
+ spans.push(portShaped);
1774
+ break;
1775
+ }
1776
+ }
1777
+ return spans;
1778
+ }
1779
+ function userinfoSpan(line, start2, lastAt) {
1780
+ if (lastAt < start2) return null;
1781
+ const colon = line.indexOf(":", start2);
1782
+ if (colon === -1 || colon >= lastAt || /[/?#]/.test(line.slice(start2, colon))) return null;
1783
+ return { authorityStart: start2, at: lastAt, passwordStart: colon + 1, passwordEnd: lastAt };
1784
+ }
1785
+ function portShapedSpan(line, start2) {
1786
+ const rest = line.slice(start2);
1787
+ const authorityEnd = rest.search(/[/?#\s]/);
1788
+ const authority = authorityEnd === -1 ? rest : rest.slice(0, authorityEnd);
1789
+ const colon = authority.indexOf(":", authority.startsWith("[") ? authority.indexOf("]") + 1 : 0);
1790
+ if (colon === -1) return null;
1791
+ const port = authority.slice(colon + 1);
1792
+ if (port === "") return null;
1793
+ if (/^\d+$/.test(port) && !digitLedPassword(rest.slice(authority.length))) return null;
1794
+ const maskStart = start2 + colon + 1;
1795
+ return { authorityStart: start2, at: -1, passwordStart: maskStart, passwordEnd: keptQueryStart(line, maskStart) };
1796
+ }
1797
+ function keptQueryStart(line, from) {
1798
+ const query = line.indexOf("?", from);
1799
+ return query !== -1 && KEPT_QUERY.test(line.slice(query)) ? query : line.length;
1800
+ }
1801
+ function digitLedPassword(afterPort) {
1802
+ if (afterPort.startsWith("#")) return true;
1803
+ return afterPort.startsWith("?") && !KEPT_QUERY.test(afterPort.split(/\s/, 1)[0]);
1804
+ }
1805
+ function rewriteLines(text, render2) {
1806
+ return text.split(/(\r?\n)/).map((part) => part === "\n" || part === "\r\n" ? part : render2(part, credentialSpans(part))).join("");
1788
1807
  }
1789
1808
  function redactCredentials(raw) {
1790
1809
  if (typeof raw !== "string" || raw === "") return raw;
1791
- return redactKeywordValues(redactUserinfoPassword(raw));
1792
- }
1793
- function schemeOf(raw) {
1794
- const match = raw.match(/^([a-zA-Z][a-zA-Z0-9+.-]*):/);
1795
- return match ? match[1].toLowerCase() : null;
1796
- }
1797
- function hostPortOf(raw) {
1798
- const authority = authorityOf(raw);
1799
- if (authority === null) return null;
1800
- const at = authority.lastIndexOf("@");
1801
- const hostPort = at === -1 ? authority : authority.slice(at + 1);
1802
- return hostPort === "" ? null : hostPort;
1803
- }
1804
- function invalidUrlError(raw, engine) {
1805
- const named = engine ?? schemeOf(raw);
1806
- const subject = named ? `invalid ${named} URL` : "invalid URL (no scheme found)";
1807
- const hostPort = hostPortOf(raw);
1808
- const at = hostPort === null ? "" : ` at '${hostPort}'`;
1809
- return new Error(
1810
- `DatabaseUrl: ${subject}${at} - expected scheme://[user[:password]@]host[:port]/database. The URL itself is not shown because it may contain a password.`
1810
+ const masked = rewriteLines(raw, (line, spans) => {
1811
+ let out = "";
1812
+ let cursor = 0;
1813
+ for (const span of spans) {
1814
+ out += line.slice(cursor, span.passwordStart) + REDACTED;
1815
+ cursor = span.passwordEnd;
1816
+ }
1817
+ return out + line.slice(cursor);
1818
+ });
1819
+ return redactKeywordValues(masked);
1820
+ }
1821
+ function stripCredentials(raw) {
1822
+ if (typeof raw !== "string" || raw === "") return raw;
1823
+ const stripped = rewriteLines(raw, (line, spans) => {
1824
+ let out = "";
1825
+ let cursor = 0;
1826
+ for (const span of spans) {
1827
+ if (span.at === -1) {
1828
+ out += line.slice(cursor, span.passwordStart) + REDACTED;
1829
+ cursor = span.passwordEnd;
1830
+ } else {
1831
+ out += line.slice(cursor, span.authorityStart);
1832
+ cursor = span.at + 1;
1833
+ }
1834
+ }
1835
+ return out + line.slice(cursor);
1836
+ });
1837
+ return redactKeywordValues(stripped);
1838
+ }
1839
+ var REDACTED, SCHEME_MARKER, KEPT_QUERY, SECRET_KEYWORD_PATTERN;
1840
+ var init_urlRedaction = __esm({
1841
+ "src/urlRedaction.ts"() {
1842
+ "use strict";
1843
+ REDACTED = "***";
1844
+ SCHEME_MARKER = /(?<![A-Za-z0-9+.\-/])([A-Za-z][A-Za-z0-9+.-]*)(:\/\/|:\/|\/\/)/g;
1845
+ KEPT_QUERY = /^\?[^\s=&#?]+=[^\s&#?]*(?:&[^\s=&#?]+=[^\s&#?]*)*(?:#\S*)?$/;
1846
+ SECRET_KEYWORD_PATTERN = /(^|[;&?\s])(pwd|password|passwd)(\s*=\s*)/gi;
1847
+ }
1848
+ });
1849
+
1850
+ // src/connectionUrl.ts
1851
+ function decodeComponent(value) {
1852
+ try {
1853
+ return decodeURIComponent(value);
1854
+ } catch {
1855
+ return value.replace(/(?:%[0-9A-Fa-f]{2})+/g, (seq) => {
1856
+ try {
1857
+ return decodeURIComponent(seq);
1858
+ } catch {
1859
+ return seq;
1860
+ }
1861
+ });
1862
+ }
1863
+ }
1864
+ function splitHostPort(hostPort) {
1865
+ if (hostPort.startsWith("[")) {
1866
+ const close = hostPort.indexOf("]");
1867
+ if (close === -1) return null;
1868
+ const after = hostPort.slice(close + 1);
1869
+ if (after !== "" && !after.startsWith(":")) return null;
1870
+ return [hostPort.slice(1, close), after === "" ? null : after.slice(1)];
1871
+ }
1872
+ const colon = hostPort.indexOf(":");
1873
+ if (colon === -1) return [hostPort, null];
1874
+ return [hostPort.slice(0, colon), hostPort.slice(colon + 1)];
1875
+ }
1876
+ function splitConnectionUrl(raw, options) {
1877
+ const refuse = refuser(raw, options);
1878
+ const { scheme, rest } = schemeAndRest(raw, refuse);
1879
+ const { userinfo, afterUserinfo } = splitUserinfo(rest, refuse);
1880
+ const { hostPort, tail } = hostPortAndTail(afterUserinfo, userinfo !== null, refuse);
1881
+ const { host, port } = firstHost(hostPort, options.allowHostList === true, refuse, userinfo !== null ? hostPort : void 0);
1882
+ refuseDigitLedPassword(userinfo, port, tail, refuse);
1883
+ const { rawUsername, rawPassword } = userinfoParts(userinfo);
1884
+ return {
1885
+ scheme,
1886
+ userinfo,
1887
+ rawUsername,
1888
+ rawPassword,
1889
+ username: decodeOrNull(rawUsername),
1890
+ password: decodeOrNull(rawPassword),
1891
+ hostPort,
1892
+ host,
1893
+ port,
1894
+ tail
1895
+ };
1896
+ }
1897
+ function refuser(raw, options) {
1898
+ const expected = options.expected ?? "scheme://[user[:password]@]host[:port]/path";
1899
+ const named = SCHEME_PREFIX.exec(String(raw ?? ""))?.[1]?.toLowerCase();
1900
+ const subject = `${options.label}: invalid ${named ? `${named} ` : ""}URL`;
1901
+ return (why, hostPort) => new ConnectionUrlError(
1902
+ `${subject}${hostPort ? ` at '${hostPort}'` : ""} (${why}) - expected ${expected}. The URL itself is not shown because it may contain a password.`
1811
1903
  );
1812
1904
  }
1813
- var ENGINE_ALIASES, DEFAULT_PORTS, REDACTED, SECRET_KEYWORD_PATTERN, DatabaseUrl;
1905
+ function schemeAndRest(raw, refuse) {
1906
+ if (typeof raw !== "string") throw refuse("not a string");
1907
+ const head = /^([A-Za-z][A-Za-z0-9+.-]*):\/\//.exec(raw);
1908
+ if (!head) throw refuse(SCHEME_PREFIX.test(raw) ? "the scheme must be followed by ://" : "no scheme:// found");
1909
+ return { scheme: head[1].toLowerCase(), rest: raw.slice(head[0].length) };
1910
+ }
1911
+ function splitUserinfo(rest, refuse) {
1912
+ const totalAt = count(rest, "@");
1913
+ if (totalAt === 0) return { userinfo: null, afterUserinfo: rest };
1914
+ const rfcEnd = rest.search(/[/?#]/);
1915
+ const rfcAt = count(rfcEnd === -1 ? rest : rest.slice(0, rfcEnd), "@");
1916
+ const lastAt = rest.lastIndexOf("@");
1917
+ const candidate = rest.slice(0, lastAt);
1918
+ const agrees = rfcAt === totalAt || rfcAt === 0 && hasCleanUser(candidate);
1919
+ if (!agrees) throw refuse(AT_OUTSIDE_USERINFO);
1920
+ return { userinfo: candidate, afterUserinfo: rest.slice(lastAt + 1) };
1921
+ }
1922
+ function hasCleanUser(userinfo) {
1923
+ const colon = userinfo.indexOf(":");
1924
+ return colon !== -1 && !/[/?#]/.test(userinfo.slice(0, colon));
1925
+ }
1926
+ function hostPortAndTail(afterUserinfo, hasUserinfo, refuse) {
1927
+ const hostEnd = afterUserinfo.search(/[/?#]/);
1928
+ const hostPort = hostEnd === -1 ? afterUserinfo : afterUserinfo.slice(0, hostEnd);
1929
+ if (/\s/.test(hostPort)) throw refuse("whitespace in the host");
1930
+ if (hasUserinfo && hostPort === "") throw refuse("no host after the credentials");
1931
+ return { hostPort, tail: afterUserinfo.slice(hostPort.length) };
1932
+ }
1933
+ function firstHost(hostPort, allowHostList, refuse, nameable) {
1934
+ const hosts = allowHostList ? hostPort.split(",") : [hostPort];
1935
+ return hosts.map((piece) => oneHost(piece, refuse, nameable))[0];
1936
+ }
1937
+ function oneHost(piece, refuse, nameable) {
1938
+ const split2 = splitHostPort(piece);
1939
+ if (split2 === null) throw refuse("a malformed IPv6 host", nameable);
1940
+ const [host, port] = split2;
1941
+ if (port === null || port === "") return { host, port: null };
1942
+ if (!/^\d+$/.test(port)) throw refuse("the port must be numeric", nameable);
1943
+ return { host, port: parseInt(port, 10) };
1944
+ }
1945
+ function refuseDigitLedPassword(userinfo, port, tail, refuse) {
1946
+ if (userinfo !== null || port === null) return;
1947
+ if (digitLedPassword(tail)) throw refuse("a port followed by a fragment or a query that is not key=value");
1948
+ }
1949
+ function userinfoParts(userinfo) {
1950
+ if (userinfo === null) return { rawUsername: null, rawPassword: null };
1951
+ const colon = userinfo.indexOf(":");
1952
+ if (colon === -1) return { rawUsername: userinfo, rawPassword: null };
1953
+ return { rawUsername: userinfo.slice(0, colon), rawPassword: userinfo.slice(colon + 1) };
1954
+ }
1955
+ function canonicalConnectionUrl(parts) {
1956
+ let auth = "";
1957
+ if (parts.userinfo !== null) {
1958
+ auth = encodeURIComponent(parts.username ?? "");
1959
+ if (parts.password !== null) auth += `:${encodeURIComponent(parts.password)}`;
1960
+ auth += "@";
1961
+ }
1962
+ return `${parts.scheme}://${auth}${parts.hostPort}${parts.tail}`;
1963
+ }
1964
+ var ConnectionUrlError, count, SCHEME_PREFIX, AT_OUTSIDE_USERINFO, decodeOrNull;
1965
+ var init_connectionUrl = __esm({
1966
+ "src/connectionUrl.ts"() {
1967
+ "use strict";
1968
+ init_urlRedaction();
1969
+ ConnectionUrlError = class extends Error {
1970
+ constructor(message) {
1971
+ super(message);
1972
+ this.name = "ConnectionUrlError";
1973
+ }
1974
+ };
1975
+ count = (text, ch) => text.split(ch).length - 1;
1976
+ SCHEME_PREFIX = /^([A-Za-z][A-Za-z0-9+.-]*):/;
1977
+ AT_OUTSIDE_USERINFO = "an @ outside the user:password part - percent-encode it as %40";
1978
+ decodeOrNull = (value) => value === null ? null : decodeComponent(value);
1979
+ }
1980
+ });
1981
+
1982
+ // ../orm/src/databaseUrl.ts
1983
+ import { inspect } from "node:util";
1984
+ function stripOneSlash(path9) {
1985
+ return path9.startsWith("/") ? path9.slice(1) : path9;
1986
+ }
1987
+ function invalidUrlError(raw, engine, why) {
1988
+ let hostPort;
1989
+ try {
1990
+ const parts = splitConnectionUrl(raw, { label: "DatabaseUrl" });
1991
+ if (parts.userinfo !== null && parts.hostPort !== "") hostPort = parts.hostPort;
1992
+ } catch {
1993
+ }
1994
+ return new ConnectionUrlError(
1995
+ `DatabaseUrl: invalid ${engine} URL${hostPort ? ` at '${hostPort}'` : ""} (${why}) - expected scheme://[user[:password]@]host[:port]/database. The URL itself is not shown because it may contain a password.`
1996
+ );
1997
+ }
1998
+ function split(url) {
1999
+ return splitConnectionUrl(url, {
2000
+ label: "DatabaseUrl",
2001
+ expected: "scheme://[user[:password]@]host[:port]/database"
2002
+ });
2003
+ }
2004
+ var ENGINE_ALIASES, DEFAULT_PORTS, DatabaseUrl;
1814
2005
  var init_databaseUrl = __esm({
1815
2006
  "../orm/src/databaseUrl.ts"() {
1816
2007
  "use strict";
2008
+ init_urlRedaction();
2009
+ init_connectionUrl();
1817
2010
  ENGINE_ALIASES = {
1818
2011
  sqlite: "sqlite",
1819
2012
  sqlite3: "sqlite",
@@ -1835,8 +2028,6 @@ var init_databaseUrl = __esm({
1835
2028
  firebird: 3050,
1836
2029
  mongodb: 27017
1837
2030
  };
1838
- REDACTED = "***";
1839
- SECRET_KEYWORD_PATTERN = /(^|[;&?\s])(pwd|password|passwd)(\s*=\s*)/gi;
1840
2031
  DatabaseUrl = class _DatabaseUrl {
1841
2032
  engine;
1842
2033
  /** Null for sqlite and odbc - a file or a DSN string has no host. */
@@ -1954,13 +2145,14 @@ var init_databaseUrl = __esm({
1954
2145
  if (url.startsWith("odbc:///")) {
1955
2146
  return { engine: "odbc", connectionString: url.slice("odbc:///".length) };
1956
2147
  }
1957
- if (url.startsWith("mssql://") || url.startsWith("sqlserver://")) {
1958
- return _DatabaseUrl.parseRegexForm(url, "mssql", /(?:mssql|sqlserver):\/\/(?:([^:]+):([^@]+)@)?([^:/]+)(?::(\d+))?\/(.*)/);
2148
+ const parts = split(url);
2149
+ if (parts.scheme === "mssql" || parts.scheme === "sqlserver") {
2150
+ return _DatabaseUrl.parsePathForm(url, parts, "mssql");
1959
2151
  }
1960
- if (url.startsWith("firebird://")) {
1961
- return _DatabaseUrl.parseRegexForm(url, "firebird", /firebird:\/\/(?:([^:]+):([^@]+)@)?([^:/]+)(?::(\d+))?\/(.*)/);
2152
+ if (parts.scheme === "firebird") {
2153
+ return _DatabaseUrl.parsePathForm(url, parts, "firebird");
1962
2154
  }
1963
- return _DatabaseUrl.parseStandard(url);
2155
+ return _DatabaseUrl.parseStandard(url, parts);
1964
2156
  }
1965
2157
  /**
1966
2158
  * sqlite is parsed on the RAW string. The URL class collapses `sqlite:/x` and
@@ -1986,52 +2178,62 @@ var init_databaseUrl = __esm({
1986
2178
  return { engine: "sqlite", database: normalised.slice("sqlite:".length) };
1987
2179
  }
1988
2180
  /**
1989
- * mssql and firebird: the URL class does not know these schemes, so they are
1990
- * matched directly.
2181
+ * mssql and firebird: `host[:port]/database`, split by the shared splitter.
1991
2182
  *
1992
- * The captured path keeps its own leading slash when the URL had two, which is
2183
+ * These used to be one regex each that split userinfo at the FIRST `@` and
2184
+ * the password at the first `/`, so `mssql://u:p@ss@h/db` connected to a host
2185
+ * named `ss@h` and printed it in the driver's error.
2186
+ *
2187
+ * The database keeps its own leading slash when the URL had two, which is
1993
2188
  * how the documented absolute Firebird form survives. The old code did
1994
2189
  * `"/" + match[5]`, ADDING a slash - so an absolute path came back with two
1995
2190
  * and a relative path was silently made absolute. Verified against live
1996
2191
  * Firebird 5.0.4: the driver takes one or two leading slashes and rejects a
1997
2192
  * relative path outright.
1998
2193
  */
1999
- static parseRegexForm(url, engine, pattern) {
2000
- const m = url.match(pattern);
2001
- if (!m) throw invalidUrlError(url, engine);
2194
+ static parsePathForm(url, parts, engine) {
2195
+ if (parts.host === "" || /[:/]/.test(parts.host) || parts.hostPort.startsWith("[")) {
2196
+ throw invalidUrlError(url, engine, "a host is required");
2197
+ }
2198
+ if (!parts.tail.startsWith("/")) throw invalidUrlError(url, engine, "a /database is required");
2002
2199
  return {
2003
2200
  engine,
2004
- username: decode(m[1]),
2005
- password: decode(m[2]),
2006
- host: m[3],
2007
- port: m[4] ? parseInt(m[4], 10) : void 0,
2008
- database: m[5]
2201
+ username: parts.username === "" ? null : parts.username,
2202
+ password: parts.password,
2203
+ host: parts.host,
2204
+ port: parts.port ?? void 0,
2205
+ database: parts.tail.slice(1)
2009
2206
  };
2010
2207
  }
2011
- /** postgres / mysql / mongodb, via the URL class. */
2012
- static parseStandard(url) {
2013
- let parsed;
2014
- try {
2015
- parsed = new URL(url);
2016
- } catch {
2017
- throw invalidUrlError(url);
2018
- }
2019
- const scheme = parsed.protocol.replace(/:$/, "").toLowerCase();
2020
- const engine = ENGINE_ALIASES[scheme];
2208
+ /**
2209
+ * postgres / mysql / mongodb.
2210
+ *
2211
+ * Userinfo comes from the shared splitter (the last-`@` rule), never from the
2212
+ * URL class: `new URL()` cuts a password at its first `/`, `?` or `#`, reads
2213
+ * `postgres:/u:pw@h` as a path, and throws a TypeError whose `.input` is the
2214
+ * whole URL. The class only sees a credential-free rebuild, for the host,
2215
+ * port and path it already normalises the way every corpus row expects.
2216
+ */
2217
+ static parseStandard(url, parts) {
2218
+ const engine = ENGINE_ALIASES[parts.scheme];
2021
2219
  if (engine === void 0) {
2022
2220
  throw new Error(
2023
- `DatabaseUrl: Unsupported database scheme '${scheme}'. Supported: ${Object.keys(ENGINE_ALIASES).join(", ")}`
2221
+ `DatabaseUrl: Unsupported database scheme '${parts.scheme}'. Supported: ${Object.keys(ENGINE_ALIASES).join(", ")}`
2024
2222
  );
2025
2223
  }
2224
+ let parsed;
2225
+ try {
2226
+ parsed = new URL(`${parts.scheme}://${parts.hostPort}${parts.tail}`);
2227
+ } catch {
2228
+ throw invalidUrlError(url, engine, "the host, port or path is malformed");
2229
+ }
2026
2230
  const database = stripOneSlash(parsed.pathname);
2027
- const userinfo = rawUserinfo(url);
2028
- const passwordWasWritten = userinfo !== null && userinfo.includes(":");
2029
2231
  return {
2030
2232
  engine,
2031
2233
  host: parsed.hostname || void 0,
2032
2234
  port: parsed.port ? parseInt(parsed.port, 10) : void 0,
2033
- username: decode(parsed.username),
2034
- password: passwordWasWritten ? decodeURIComponent(parsed.password) : null,
2235
+ username: parts.username === "" ? null : parts.username,
2236
+ password: parts.password,
2035
2237
  database: engine === "mongodb" ? database || "tina4" : database
2036
2238
  };
2037
2239
  }
@@ -7577,7 +7779,9 @@ async function buildAdapterFromUrl(url, username, password) {
7577
7779
  }
7578
7780
  case "mongodb": {
7579
7781
  const { MongodbAdapter: MongodbAdapter2 } = await Promise.resolve().then(() => (init_mongodb(), mongodb_exports));
7580
- const adapter = new MongodbAdapter2(url);
7782
+ const adapter = new MongodbAdapter2(
7783
+ canonicalConnectionUrl(splitConnectionUrl(url, { label: "DatabaseUrl", allowHostList: true }))
7784
+ );
7581
7785
  await adapter.connect();
7582
7786
  return adapter;
7583
7787
  }
@@ -7716,6 +7920,7 @@ var init_database = __esm({
7716
7920
  "use strict";
7717
7921
  init_databaseResult();
7718
7922
  init_databaseUrl();
7923
+ init_connectionUrl();
7719
7924
  init_cachedDatabase();
7720
7925
  init_sqlTranslator();
7721
7926
  init_sqlDialect();
@@ -10858,9 +11063,9 @@ function splitArithmetic(expr) {
10858
11063
  return null;
10859
11064
  }
10860
11065
  function evalArithmeticExpression(expr, context) {
10861
- const split = splitArithmetic(expr);
10862
- if (!split) return EXPR_NOT_MATCHED;
10863
- const [pos, op] = split;
11066
+ const split2 = splitArithmetic(expr);
11067
+ if (!split2) return EXPR_NOT_MATCHED;
11068
+ const [pos, op] = split2;
10864
11069
  const lVal = evalExpr(expr.slice(0, pos).trim(), context);
10865
11070
  const rVal = evalExpr(expr.slice(pos + op.length).trim(), context);
10866
11071
  let lNum = lVal != null ? Number(lVal) : 0;
@@ -14284,8 +14489,8 @@ var init_queryBuilder = __esm({
14284
14489
  * @param offset - Number of rows to skip.
14285
14490
  * @returns this for chaining.
14286
14491
  */
14287
- limit(count, offset) {
14288
- this.limitVal = count;
14492
+ limit(count2, offset) {
14493
+ this.limitVal = count2;
14289
14494
  if (offset !== void 0) {
14290
14495
  this.offsetVal = offset;
14291
14496
  }
@@ -14301,8 +14506,8 @@ var init_queryBuilder = __esm({
14301
14506
  * @param count - Number of rows to skip.
14302
14507
  * @returns this for chaining.
14303
14508
  */
14304
- offset(count) {
14305
- this.offsetVal = count;
14509
+ offset(count2) {
14510
+ this.offsetVal = count2;
14306
14511
  return this;
14307
14512
  }
14308
14513
  /**
@@ -14314,8 +14519,8 @@ var init_queryBuilder = __esm({
14314
14519
  * @param count - Number of rows to skip.
14315
14520
  * @returns this for chaining.
14316
14521
  */
14317
- skip(count) {
14318
- return this.offset(count);
14522
+ skip(count2) {
14523
+ return this.offset(count2);
14319
14524
  }
14320
14525
  /**
14321
14526
  * Alias for `limit()` -- the Eloquent name; pairs with `skip()`.
@@ -14323,8 +14528,8 @@ var init_queryBuilder = __esm({
14323
14528
  * @param count - Maximum rows to return.
14324
14529
  * @returns this for chaining.
14325
14530
  */
14326
- take(count) {
14327
- return this.limit(count);
14531
+ take(count2) {
14532
+ return this.limit(count2);
14328
14533
  }
14329
14534
  /**
14330
14535
  * Build and return the SQL string without executing.
@@ -16072,8 +16277,18 @@ var init_baseModel = __esm({
16072
16277
  // src/fakeData.ts
16073
16278
  import { randomInt, randomUUID } from "node:crypto";
16074
16279
  import { existsSync as existsSync7, readdirSync as readdirSync3 } from "node:fs";
16075
- import { resolve as resolve5, join as join8 } from "node:path";
16280
+ import { resolve as resolve5, join as join8, basename as basename2 } from "node:path";
16076
16281
  import { pathToFileURL as pathToFileURL2 } from "node:url";
16282
+ function errorText(error2) {
16283
+ return error2 instanceof Error ? error2.message : String(error2);
16284
+ }
16285
+ function isSeedFile(name) {
16286
+ return (name.endsWith(".ts") || name.endsWith(".js")) && !name.startsWith("_");
16287
+ }
16288
+ function seedEntry(mod) {
16289
+ const entry = typeof mod.default === "function" ? mod.default : mod.run;
16290
+ return typeof entry === "function" ? entry : void 0;
16291
+ }
16077
16292
  function mulberry32(seed) {
16078
16293
  let s = seed | 0;
16079
16294
  return () => {
@@ -16083,10 +16298,21 @@ function mulberry32(seed) {
16083
16298
  return ((t ^ t >>> 14) >>> 0) / 4294967296;
16084
16299
  };
16085
16300
  }
16086
- var FIRST_NAMES, LAST_NAMES, DOMAINS, WORDS, CITIES, COUNTRIES, STREETS, JOB_TITLES, CURRENCIES, PRODUCT_ADJECTIVES, PRODUCT_NOUNS, FakeData;
16301
+ var SeedError, FIRST_NAMES, LAST_NAMES, DOMAINS, WORDS, CITIES, COUNTRIES, STREETS, JOB_TITLES, CURRENCIES, PRODUCT_ADJECTIVES, PRODUCT_NOUNS, FakeData;
16087
16302
  var init_fakeData = __esm({
16088
16303
  "src/fakeData.ts"() {
16089
16304
  "use strict";
16305
+ init_logger();
16306
+ SeedError = class extends Error {
16307
+ seedFile;
16308
+ completed;
16309
+ constructor(seedFile, completed, cause) {
16310
+ super(`Seed file failed: ${basename2(seedFile)}: ${errorText(cause)}`, { cause });
16311
+ this.name = "SeedError";
16312
+ this.seedFile = seedFile;
16313
+ this.completed = [...completed];
16314
+ }
16315
+ };
16090
16316
  FIRST_NAMES = [
16091
16317
  "Alice",
16092
16318
  "Bob",
@@ -16566,33 +16792,37 @@ var init_fakeData = __esm({
16566
16792
  return items[this.randInt(0, items.length)];
16567
16793
  }
16568
16794
  /**
16569
- * Run seed files from a directory. Each file should export a default async function.
16570
- * Returns an array of executed file paths.
16795
+ * Run the seed files in a directory in name order, skipping files whose name
16796
+ * starts with "_". A file's default export, or else the named run() that
16797
+ * `generate seeder` writes, is awaited when it is a function.
16798
+ * Returns the executed file paths in order ([] when the directory is missing).
16799
+ * A seed file that throws stops the run: it is logged and a SeedError naming
16800
+ * it is thrown, and no later file runs (ADR-0108).
16571
16801
  */
16572
16802
  async seedDir(seedDir) {
16573
16803
  const dir = resolve5(seedDir ?? "src/seeds");
16574
16804
  if (!existsSync7(dir)) return [];
16575
- const files = readdirSync3(dir).filter((f) => f.endsWith(".ts") || f.endsWith(".js")).sort();
16805
+ const files = readdirSync3(dir).filter(isSeedFile).sort();
16576
16806
  const executed = [];
16577
16807
  for (const file of files) {
16578
16808
  const fullPath = join8(dir, file);
16579
16809
  try {
16580
16810
  const mod = await import(pathToFileURL2(fullPath).href);
16581
- if (typeof mod.default === "function") {
16582
- await mod.default();
16583
- }
16584
- executed.push(fullPath);
16585
- } catch {
16811
+ await seedEntry(mod)?.();
16812
+ } catch (error2) {
16813
+ Log.error(`Seeder: ${file} failed, seeding stopped: ${errorText(error2)}`);
16814
+ throw new SeedError(fullPath, executed, error2);
16586
16815
  }
16816
+ executed.push(fullPath);
16587
16817
  }
16588
16818
  return executed;
16589
16819
  }
16590
16820
  /**
16591
16821
  * Run a generator function `count` times and return the results.
16592
16822
  */
16593
- run(fn, count = 1) {
16823
+ run(fn, count2 = 1) {
16594
16824
  const results = [];
16595
- for (let i = 0; i < count; i++) {
16825
+ for (let i = 0; i < count2; i++) {
16596
16826
  results.push(fn());
16597
16827
  }
16598
16828
  return results;
@@ -16764,7 +16994,7 @@ async function autoFieldMap(db, table2, fake = new FakeData2()) {
16764
16994
  }
16765
16995
  return fieldMap;
16766
16996
  }
16767
- async function seedTable(db, tableName, count = 10, fieldMap, overrides, opts) {
16997
+ async function seedTable(db, tableName, count2 = 10, fieldMap, overrides, opts) {
16768
16998
  if (opts?.seed !== void 0) {
16769
16999
  throw new Error(
16770
17000
  "seedTable() no longer accepts opts.seed: it has no generators of its own to seed (fieldMap callables are opaque). Build a seeded FakeData yourself and close over it in fieldMap, e.g. const fake = new FakeData(42); seedTable(db, table, count, { name: () => fake.name() })."
@@ -16776,7 +17006,7 @@ async function seedTable(db, tableName, count = 10, fieldMap, overrides, opts) {
16776
17006
  let seeded = 0;
16777
17007
  let failed = 0;
16778
17008
  const errors = [];
16779
- for (let i = 0; i < count; i++) {
17009
+ for (let i = 0; i < count2; i++) {
16780
17010
  try {
16781
17011
  const row = {};
16782
17012
  for (const [column2, generator] of Object.entries(fieldMap)) {
@@ -16863,7 +17093,7 @@ function pkFieldOf(fields) {
16863
17093
  }
16864
17094
  return "id";
16865
17095
  }
16866
- async function seedOrm(ormClass, count = 10, overrides, seed, opts, fkPools) {
17096
+ async function seedOrm(ormClass, count2 = 10, overrides, seed, opts, fkPools) {
16867
17097
  const merged = { ...opts ?? {} };
16868
17098
  const effectiveOverrides = merged.overrides ?? overrides;
16869
17099
  const effectiveSeed = merged.seed ?? seed;
@@ -16893,7 +17123,7 @@ async function seedOrm(ormClass, count = 10, overrides, seed, opts, fkPools) {
16893
17123
  let seeded = 0;
16894
17124
  let failed = 0;
16895
17125
  const errors = [];
16896
- for (let i = 0; i < count; i++) {
17126
+ for (let i = 0; i < count2; i++) {
16897
17127
  try {
16898
17128
  const attrs = {};
16899
17129
  for (const [name, def] of Object.entries(fields)) {
@@ -16974,7 +17204,7 @@ function topoSortModels(ormClasses) {
16974
17204
  ordered.push(...remaining);
16975
17205
  return ordered;
16976
17206
  }
16977
- async function seedModels(ormClasses, count = 10, opts) {
17207
+ async function seedModels(ormClasses, count2 = 10, opts) {
16978
17208
  const clear = opts?.clear ?? false;
16979
17209
  const seed = opts?.seed;
16980
17210
  const strict = opts?.strict ?? false;
@@ -17002,7 +17232,7 @@ async function seedModels(ormClasses, count = 10, opts) {
17002
17232
  }
17003
17233
  const summary = await seedOrm(
17004
17234
  model,
17005
- count,
17235
+ count2,
17006
17236
  void 0,
17007
17237
  void 0,
17008
17238
  { overrides: modelOverrides, clear: false, seed, strict },
@@ -17350,7 +17580,9 @@ function mongoConnection(uri, dbName) {
17350
17580
  if (!pending) {
17351
17581
  pending = (async () => {
17352
17582
  const { MongoClient } = await importMongoDriver();
17353
- const client = new MongoClient(uri);
17583
+ const client = new MongoClient(
17584
+ canonicalConnectionUrl(splitConnectionUrl(uri, { label: "DocStore", allowHostList: true }))
17585
+ );
17354
17586
  await client.connect();
17355
17587
  return { client, db: client.db(dbName) };
17356
17588
  })();
@@ -17380,6 +17612,7 @@ var InvalidId, OID_RE, ISO_RE, ObjectId, COMPARATORS, SAFE_PATH_SEGMENT, Cursor,
17380
17612
  var init_docstore = __esm({
17381
17613
  "../orm/src/docstore.ts"() {
17382
17614
  "use strict";
17615
+ init_connectionUrl();
17383
17616
  InvalidId = class extends Error {
17384
17617
  constructor(message) {
17385
17618
  super(message);
@@ -17721,11 +17954,13 @@ var init_docstore = __esm({
17721
17954
  });
17722
17955
 
17723
17956
  // ../orm/src/graph/graphUrl.ts
17957
+ import { inspect as inspect2 } from "node:util";
17724
17958
  var SCHEME_ENGINE, ENGINE_DEFAULT_PORT, GraphUrl;
17725
17959
  var init_graphUrl = __esm({
17726
17960
  "../orm/src/graph/graphUrl.ts"() {
17727
17961
  "use strict";
17728
- init_databaseUrl();
17962
+ init_urlRedaction();
17963
+ init_connectionUrl();
17729
17964
  SCHEME_ENGINE = {
17730
17965
  ultipa: "ultipa",
17731
17966
  ultipas: "ultipa",
@@ -17757,12 +17992,14 @@ var init_graphUrl = __esm({
17757
17992
  useTls;
17758
17993
  constructor(url) {
17759
17994
  this.raw = url;
17995
+ const expected = "scheme://[user[:password]@]host[:port]/graph (e.g. ultipa://host:60061/mygraph)";
17996
+ const parts = splitConnectionUrl(url, { label: "GraphUrl", expected });
17760
17997
  let parsed;
17761
17998
  try {
17762
- parsed = new URL(url);
17999
+ parsed = new URL(`${parts.scheme}://${parts.hostPort}${parts.tail}`);
17763
18000
  } catch {
17764
- throw new Error(
17765
- `Unsupported graph URL '${redactCredentials(url)}' \u2014 expected scheme://[user[:password]@]host[:port]/graph (e.g. ultipa://host:60061/mygraph).`
18001
+ throw new ConnectionUrlError(
18002
+ `GraphUrl: invalid ${parts.scheme} URL - expected ${expected}. The URL itself is not shown because it may contain a password.`
17766
18003
  );
17767
18004
  }
17768
18005
  const scheme = parsed.protocol.replace(/:$/, "").toLowerCase();
@@ -17778,14 +18015,38 @@ var init_graphUrl = __esm({
17778
18015
  this.port = parsed.port ? parseInt(parsed.port, 10) : ENGINE_DEFAULT_PORT[engine];
17779
18016
  const path9 = (parsed.pathname || "").replace(/^\//, "");
17780
18017
  this.graph = path9 === "" ? null : path9;
17781
- this.username = parsed.username ? decodeURIComponent(parsed.username) : null;
17782
- this.password = parsed.password ? decodeURIComponent(parsed.password) : null;
18018
+ this.username = parts.username ? parts.username : null;
18019
+ this.password = parts.password ? parts.password : null;
17783
18020
  this.params = {};
17784
18021
  for (const [key, value] of parsed.searchParams) {
17785
18022
  if (!(key in this.params)) this.params[key] = value;
17786
18023
  }
17787
18024
  this.useTls = scheme.endsWith("s") || this.params.tls === "1" || this.params.tls === "true";
17788
18025
  }
18026
+ /**
18027
+ * What `JSON.stringify` emits, directly or as one field of a logged object.
18028
+ * `password` and `raw` both hold the secret, so the default dump printed it
18029
+ * twice (GHSA-h2mr-m3v3-cq8c). DatabaseUrl guards the same way; PHP has
18030
+ * __debugInfo/jsonSerialize and Ruby a redacted #inspect.
18031
+ */
18032
+ toJSON() {
18033
+ return {
18034
+ raw: redactCredentials(this.raw),
18035
+ scheme: this.scheme,
18036
+ engine: this.engine,
18037
+ host: this.host,
18038
+ port: this.port,
18039
+ graph: this.graph,
18040
+ username: this.username,
18041
+ password: this.password === null ? null : "***",
18042
+ params: this.params,
18043
+ useTls: this.useTls
18044
+ };
18045
+ }
18046
+ /** What `console.log(url)` / `util.inspect(url)` print. */
18047
+ [inspect2.custom]() {
18048
+ return `GraphUrl('${redactCredentials(this.raw)}')`;
18049
+ }
17789
18050
  /** host:port/graph — for messages, never carrying credentials. */
17790
18051
  getDsn() {
17791
18052
  const target = this.port ? `${this.host}:${this.port}` : this.host;
@@ -19898,11 +20159,11 @@ ${s}\r
19898
20159
  return { value: str, next: after + len + 2 };
19899
20160
  }
19900
20161
  case 42: {
19901
- const count = parseInt(line, 10);
19902
- if (count === -1) return { value: null, next: after };
20162
+ const count2 = parseInt(line, 10);
20163
+ if (count2 === -1) return { value: null, next: after };
19903
20164
  const arr = [];
19904
20165
  let pos = after;
19905
- for (let i = 0; i < count; i++) {
20166
+ for (let i = 0; i < count2; i++) {
19906
20167
  const el = _RespClient.parse(buf, pos);
19907
20168
  if (!el) return null;
19908
20169
  arr.push(el.value);
@@ -20203,7 +20464,7 @@ ${s}\r
20203
20464
  }
20204
20465
  async stats() {
20205
20466
  const now = Date.now() / 1e3;
20206
- let count = 0;
20467
+ let count2 = 0;
20207
20468
  try {
20208
20469
  const files = fs.readdirSync(this.dir).filter((f) => f.endsWith(".json"));
20209
20470
  for (const f of files) {
@@ -20212,14 +20473,14 @@ ${s}\r
20212
20473
  if (data.expiresAt && now > data.expiresAt) {
20213
20474
  fs.unlinkSync(path.join(this.dir, f));
20214
20475
  } else {
20215
- count++;
20476
+ count2++;
20216
20477
  }
20217
20478
  } catch {
20218
20479
  }
20219
20480
  }
20220
20481
  } catch {
20221
20482
  }
20222
- return { hits: this.hits, misses: this.misses, size: count, backend: "file" };
20483
+ return { hits: this.hits, misses: this.misses, size: count2, backend: "file" };
20223
20484
  }
20224
20485
  /**
20225
20486
  * Delete expired cache files and count them. `expiresAt > 0` is load-bearing:
@@ -21020,18 +21281,18 @@ var init_router = __esm({
21020
21281
  }
21021
21282
  };
21022
21283
  RouteRef = class {
21284
+ routes;
21023
21285
  constructor(route) {
21024
- this.route = route;
21286
+ this.routes = Array.isArray(route) ? route : [route];
21025
21287
  }
21026
- route;
21027
21288
  /** Mark this route as requiring bearer-token authentication. */
21028
21289
  secure() {
21029
- this.route.secure = true;
21290
+ for (const route of this.routes) route.secure = true;
21030
21291
  return this;
21031
21292
  }
21032
21293
  /** Opt out of secure-by-default auth (for public write routes). */
21033
21294
  noAuth() {
21034
- this.route.noAuth = true;
21295
+ for (const route of this.routes) route.noAuth = true;
21035
21296
  return this;
21036
21297
  }
21037
21298
  /**
@@ -21041,7 +21302,7 @@ var init_router = __esm({
21041
21302
  * (identity) are orthogonal — chain `.noAuth().noCsrf()` for a public webhook.
21042
21303
  */
21043
21304
  noCsrf() {
21044
- this.route.noCsrf = true;
21305
+ for (const route of this.routes) route.noCsrf = true;
21045
21306
  return this;
21046
21307
  }
21047
21308
  /**
@@ -21049,12 +21310,7 @@ var init_router = __esm({
21049
21310
  * claim. Chain .role()/.can() for AND. Implies auth. Feature 138 / ADR-0058.
21050
21311
  */
21051
21312
  role(...names) {
21052
- const clean = names.filter((n) => n !== "");
21053
- if (clean.length > 0) {
21054
- (this.route.requiredRoles ??= []).push(clean);
21055
- this.route.secure = true;
21056
- }
21057
- return this;
21313
+ return this.guard("requiredRoles", names);
21058
21314
  }
21059
21315
  /**
21060
21316
  * RBAC: require ONE of the named permissions (OR). Reads the verified JWT
@@ -21062,16 +21318,26 @@ var init_router = __esm({
21062
21318
  * concrete requirement. Chain for AND. Implies auth. Feature 138.
21063
21319
  */
21064
21320
  can(...permissions) {
21065
- const clean = permissions.filter((p) => p !== "");
21321
+ return this.guard("requiredPerms", permissions);
21322
+ }
21323
+ /**
21324
+ * Add one OR-group of roles or permissions to every route this ref covers,
21325
+ * and secure them (a guard implies auth). Empty names are dropped; a call
21326
+ * with none left changes nothing.
21327
+ */
21328
+ guard(key, names) {
21329
+ const clean = names.filter((n) => n !== "");
21066
21330
  if (clean.length > 0) {
21067
- (this.route.requiredPerms ??= []).push(clean);
21068
- this.route.secure = true;
21331
+ for (const route of this.routes) {
21332
+ (route[key] ??= []).push(clean);
21333
+ route.secure = true;
21334
+ }
21069
21335
  }
21070
21336
  return this;
21071
21337
  }
21072
21338
  /** Mark this route's response as cacheable. */
21073
21339
  cache() {
21074
- this.route.cached = true;
21340
+ for (const route of this.routes) route.cached = true;
21075
21341
  return this;
21076
21342
  }
21077
21343
  /**
@@ -21079,7 +21345,9 @@ var init_router = __esm({
21079
21345
  * string specs (e.g. `"ResponseCache:300"`), resolved when the route runs.
21080
21346
  */
21081
21347
  middleware(...middlewareClasses) {
21082
- this.route.middlewares = [...this.route.middlewares ?? [], ...middlewareClasses];
21348
+ for (const route of this.routes) {
21349
+ route.middlewares = [...route.middlewares ?? [], ...middlewareClasses];
21350
+ }
21083
21351
  return this;
21084
21352
  }
21085
21353
  };
@@ -21111,6 +21379,10 @@ var init_router = __esm({
21111
21379
  * Add a raw route definition (used internally and by file-based routing).
21112
21380
  */
21113
21381
  addRoute(definition) {
21382
+ return new RouteRef(this.registerRoute(definition));
21383
+ }
21384
+ /** Compile and store one route definition; returns the stored route. */
21385
+ registerRoute(definition) {
21114
21386
  const method = definition.method.toUpperCase();
21115
21387
  const { regex, paramNames, paramTypes } = this.compilePattern(definition.pattern);
21116
21388
  if (!this.routes.has(method)) {
@@ -21142,7 +21414,7 @@ var init_router = __esm({
21142
21414
  requiredPerms: definition.requiredPerms
21143
21415
  };
21144
21416
  routes.push(compiled);
21145
- return new RouteRef(compiled);
21417
+ return compiled;
21146
21418
  }
21147
21419
  /**
21148
21420
  * Register a GET route programmatically.
@@ -21196,13 +21468,16 @@ var init_router = __esm({
21196
21468
  }
21197
21469
  /**
21198
21470
  * Register a route that matches ANY HTTP method.
21471
+ *
21472
+ * One route is stored per method; the returned ref covers all of them, so
21473
+ * `any(...).secure()` / `.role()` / `.noAuth()` apply to every method.
21199
21474
  */
21200
21475
  any(path9, handler, middlewares, meta) {
21201
- let lastRef;
21476
+ const compiled = [];
21202
21477
  for (const method of ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"]) {
21203
- lastRef = this.addRoute({ method, pattern: path9, handler, middlewares, meta });
21478
+ compiled.push(this.registerRoute({ method, pattern: path9, handler, middlewares, meta }));
21204
21479
  }
21205
- return lastRef;
21480
+ return new RouteRef(compiled);
21206
21481
  }
21207
21482
  /**
21208
21483
  * Create a route group with a shared prefix and optional middlewares.
@@ -21627,17 +21902,7 @@ var init_router = __esm({
21627
21902
  });
21628
21903
  }
21629
21904
  any(path9, handler, middlewares, meta) {
21630
- let lastRef;
21631
- for (const method of ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"]) {
21632
- lastRef = this.router.addRoute({
21633
- method,
21634
- pattern: joinGroupPath(this.prefix, path9),
21635
- handler,
21636
- middlewares: this.mergeMiddlewares(middlewares),
21637
- meta
21638
- });
21639
- }
21640
- return lastRef;
21905
+ return this.router.any(joinGroupPath(this.prefix, path9), handler, this.mergeMiddlewares(middlewares), meta);
21641
21906
  }
21642
21907
  /**
21643
21908
  * Nested groups.
@@ -23394,9 +23659,9 @@ function nestFormFields(pairs) {
23394
23659
  return params;
23395
23660
  };
23396
23661
  const tooDeep = (name) => {
23397
- let count = 0;
23662
+ let count2 = 0;
23398
23663
  for (let at = name.indexOf("["); at !== -1; at = name.indexOf("[", at + 1)) {
23399
- if (++count >= FORM_DEPTH_LIMIT) return true;
23664
+ if (++count2 >= FORM_DEPTH_LIMIT) return true;
23400
23665
  }
23401
23666
  return false;
23402
23667
  };
@@ -23820,7 +24085,7 @@ __export(routeDiscovery_exports, {
23820
24085
  rediscoverRoutes: () => rediscoverRoutes
23821
24086
  });
23822
24087
  import { readdirSync as readdirSync5, statSync as statSync7, mkdirSync as mkdirSync8, writeFileSync as writeFileSync5, existsSync as existsSync9 } from "node:fs";
23823
- import { join as join12, relative, basename as basename2, extname as extname2 } from "node:path";
24088
+ import { join as join12, relative, basename as basename3, extname as extname2 } from "node:path";
23824
24089
  import { pathToFileURL as pathToFileURL3 } from "node:url";
23825
24090
  function boolExport(value) {
23826
24091
  return typeof value === "boolean" ? value : void 0;
@@ -23834,7 +24099,7 @@ async function discoverRoutes(routesDir) {
23834
24099
  for (const filePath of files) {
23835
24100
  const ext = extname2(filePath);
23836
24101
  if (ext !== ".ts" && ext !== ".js") continue;
23837
- const name = basename2(filePath, ext).toLowerCase();
24102
+ const name = basename3(filePath, ext).toLowerCase();
23838
24103
  if (!VALID_METHODS.has(name)) continue;
23839
24104
  routeFileCount++;
23840
24105
  const currentMtime = statSync7(filePath).mtimeMs;
@@ -24513,11 +24778,11 @@ var init_memcachedHandler = __esm({
24513
24778
  const resp = this.command(`get ${this.key(sessionId)}\r
24514
24779
  `, ["END\r\n"]);
24515
24780
  if (!resp.startsWith("VALUE")) return null;
24516
- const split = resp.indexOf("\r\n");
24517
- if (split === -1) return null;
24518
- const header = resp.slice(0, split).split(" ");
24781
+ const split2 = resp.indexOf("\r\n");
24782
+ if (split2 === -1) return null;
24783
+ const header = resp.slice(0, split2).split(" ");
24519
24784
  const bytes = parseInt(header[3] ?? "0", 10);
24520
- const body = Buffer.from(resp.slice(split + 2), "utf-8").subarray(0, bytes).toString("utf-8");
24785
+ const body = Buffer.from(resp.slice(split2 + 2), "utf-8").subarray(0, bytes).toString("utf-8");
24521
24786
  try {
24522
24787
  return JSON.parse(body);
24523
24788
  } catch {
@@ -25146,7 +25411,7 @@ function column(row, name) {
25146
25411
  if (name in row) return row[name];
25147
25412
  return row[name.toUpperCase()];
25148
25413
  }
25149
- function schemeOf2(url) {
25414
+ function schemeOf(url) {
25150
25415
  const match = url.match(/^([a-zA-Z][a-zA-Z0-9+.-]*):/);
25151
25416
  return match ? match[1].toLowerCase() : "unknown";
25152
25417
  }
@@ -25337,7 +25602,7 @@ var init_databaseHandler = __esm({
25337
25602
  process.env.TINA4_DATABASE_PASSWORD
25338
25603
  );
25339
25604
  } catch {
25340
- throw this.unsupportedEngine(schemeOf2(url));
25605
+ throw this.unsupportedEngine(schemeOf(url));
25341
25606
  }
25342
25607
  if (!SQL_SESSION_ENGINES.includes(parsed.engine)) {
25343
25608
  throw this.unsupportedEngine(parsed.engine);
@@ -27078,19 +27343,19 @@ var init_devMailbox = __esm({
27078
27343
  */
27079
27344
  unreadCount() {
27080
27345
  const dir = this.ensureFolder("inbox");
27081
- let count = 0;
27346
+ let count2 = 0;
27082
27347
  try {
27083
27348
  const files = readdirSync7(dir).filter((f) => f.endsWith(".json"));
27084
27349
  for (const file of files) {
27085
27350
  try {
27086
27351
  const msg = JSON.parse(readFileSync11(join17(dir, file), "utf-8"));
27087
- if (!msg.read) count++;
27352
+ if (!msg.read) count2++;
27088
27353
  } catch {
27089
27354
  }
27090
27355
  }
27091
27356
  } catch {
27092
27357
  }
27093
- return count;
27358
+ return count2;
27094
27359
  }
27095
27360
  /**
27096
27361
  * Delete a message by ID. Removes from all folders.
@@ -27131,7 +27396,7 @@ var init_devMailbox = __esm({
27131
27396
  /**
27132
27397
  * Seed the mailbox with sample messages for development.
27133
27398
  */
27134
- seed(count = 5) {
27399
+ seed(count2 = 5) {
27135
27400
  const subjects = [
27136
27401
  "Welcome to Tina4",
27137
27402
  "Your account has been created",
@@ -27151,7 +27416,7 @@ var init_devMailbox = __esm({
27151
27416
  "billing@service.io",
27152
27417
  "alerts@monitoring.dev"
27153
27418
  ];
27154
- for (let i = 0; i < count; i++) {
27419
+ for (let i = 0; i < count2; i++) {
27155
27420
  const subject = subjects[i % subjects.length];
27156
27421
  const from = senders[i % senders.length];
27157
27422
  const date = new Date(Date.now() - i * 36e5).toISOString();
@@ -30670,12 +30935,12 @@ function registerDevTools(server) {
30670
30935
  return { error: "No database connection" };
30671
30936
  }
30672
30937
  if (!adapter) return { error: "No database connection" };
30673
- const count = args.count || 10;
30938
+ const count2 = args.count || 10;
30674
30939
  const fieldMap = await orm.autoFieldMap(adapter, args.table);
30675
30940
  if (!fieldMap || Object.keys(fieldMap).length === 0) {
30676
30941
  return { error: `Table '${args.table}' not found or has no seedable columns` };
30677
30942
  }
30678
- const summary = await orm.seedTable(adapter, args.table, count, fieldMap);
30943
+ const summary = await orm.seedTable(adapter, args.table, count2, fieldMap);
30679
30944
  return { table: args.table, inserted: summary.seeded, failed: summary.failed };
30680
30945
  } catch (e) {
30681
30946
  return { error: e.message };
@@ -30847,7 +31112,7 @@ function registerDevTools(server) {
30847
31112
  let rel = args.path || "";
30848
31113
  const oldStr = args.old_string || "";
30849
31114
  const newStr = args.new_string || "";
30850
- const count = args.count || 1;
31115
+ const count2 = args.count || 1;
30851
31116
  const projectRoot4 = path3.resolve(process.cwd());
30852
31117
  const proseErr = looksLikeProse(rel);
30853
31118
  if (proseErr) {
@@ -30868,13 +31133,13 @@ function registerDevTools(server) {
30868
31133
  let idx = -1;
30869
31134
  while ((idx = original.indexOf(oldStr, idx + 1)) !== -1) occurrences++;
30870
31135
  if (occurrences === 0) return { error: `old_string not found in ${rel}` };
30871
- if (occurrences !== count) {
31136
+ if (occurrences !== count2) {
30872
31137
  return {
30873
- error: `old_string appears ${occurrences} times, expected ${count}. Expand old_string to make it unique, or set count explicitly.`
31138
+ error: `old_string appears ${occurrences} times, expected ${count2}. Expand old_string to make it unique, or set count explicitly.`
30874
31139
  };
30875
31140
  }
30876
31141
  let updated = original;
30877
- for (let i = 0; i < count; i++) updated = updated.replace(oldStr, newStr);
31142
+ for (let i = 0; i < count2; i++) updated = updated.replace(oldStr, newStr);
30878
31143
  const backupRel = agentBackup(projectRoot4, resolved);
30879
31144
  fs4.writeFileSync(resolved, updated, "utf-8");
30880
31145
  try {
@@ -30886,11 +31151,11 @@ function registerDevTools(server) {
30886
31151
  agentLog(
30887
31152
  projectRoot4,
30888
31153
  "patch.ok",
30889
- `${rel} (replaced ${count}\xD7 old_string, ${oldSize}B \u2192 ${newSize}B, backup: ${backupRel || "(none)"})`
31154
+ `${rel} (replaced ${count2}\xD7 old_string, ${oldSize}B \u2192 ${newSize}B, backup: ${backupRel || "(none)"})`
30890
31155
  );
30891
31156
  const result = {
30892
31157
  patched: rel,
30893
- replacements: count,
31158
+ replacements: count2,
30894
31159
  bytes: newSize
30895
31160
  };
30896
31161
  if (backupRel) {
@@ -32100,12 +32365,12 @@ var init_graphql = __esm({
32100
32365
  */
32101
32366
  assertComplexity(selections, fragments) {
32102
32367
  const depthCap = this.maxDepth > 0 ? this.maxDepth : 1e3;
32103
- let count = 0;
32368
+ let count2 = 0;
32104
32369
  const walk2 = (sels, depth) => {
32105
32370
  if (depth > depthCap) return;
32106
32371
  for (const sel of sels) {
32107
- count++;
32108
- if (count > this.maxNodes) {
32372
+ count2++;
32373
+ if (count2 > this.maxNodes) {
32109
32374
  throw new ComplexityError(`Query exceeds maximum complexity of ${this.maxNodes} nodes`);
32110
32375
  }
32111
32376
  if (sel.kind === "fragment_spread") {
@@ -32575,8 +32840,8 @@ var init_graphql = __esm({
32575
32840
 
32576
32841
  // src/context/chunker.ts
32577
32842
  function fold(text) {
32578
- const split = text.replace(NUM_COMMA, "").replace(CAMEL, " ").toLowerCase();
32579
- return split.normalize("NFKD").replace(/[^\x00-\x7f]/g, "");
32843
+ const split2 = text.replace(NUM_COMMA, "").replace(CAMEL, " ").toLowerCase();
32844
+ return split2.normalize("NFKD").replace(/[^\x00-\x7f]/g, "");
32580
32845
  }
32581
32846
  function lightStem(token) {
32582
32847
  if (token.length > 3 && token.endsWith("s") && !/(?:ss|us|is)$/.test(token)) {
@@ -32683,7 +32948,7 @@ __export(context_exports, {
32683
32948
  });
32684
32949
  import { DatabaseSync as DatabaseSync4 } from "node:sqlite";
32685
32950
  import { existsSync as existsSync19, mkdirSync as mkdirSync14, readFileSync as readFileSync15, readdirSync as readdirSync11, realpathSync as realpathSync5 } from "node:fs";
32686
- import { basename as basename4, dirname as dirname12, extname as extname6, isAbsolute as isAbsolute6, join as join23, relative as relative4, resolve as resolve12 } from "node:path";
32951
+ import { basename as basename5, dirname as dirname12, extname as extname6, isAbsolute as isAbsolute6, join as join23, relative as relative4, resolve as resolve12 } from "node:path";
32687
32952
  function fts5Supported() {
32688
32953
  try {
32689
32954
  const conn = new DatabaseSync4(":memory:");
@@ -32706,7 +32971,7 @@ function realResolve(abs) {
32706
32971
  } catch {
32707
32972
  }
32708
32973
  try {
32709
- return join23(realpathSync5(dirname12(abs)), basename4(abs));
32974
+ return join23(realpathSync5(dirname12(abs)), basename5(abs));
32710
32975
  } catch {
32711
32976
  return abs;
32712
32977
  }
@@ -32819,7 +33084,7 @@ var init_context = __esm({
32819
33084
  // ── indexing ───────────────────────────────────────────────
32820
33085
  static chunksFor(label, text) {
32821
33086
  const ext = extname6(label).toLowerCase();
32822
- const special = SPECIAL_FILES.has(basename4(label).toLowerCase());
33087
+ const special = SPECIAL_FILES.has(basename5(label).toLowerCase());
32823
33088
  if (CODE_EXTS.has(ext) || CONFIG_EXTS.has(ext) || special) {
32824
33089
  return chunkCode(text, label);
32825
33090
  }
@@ -32916,7 +33181,7 @@ var init_context = __esm({
32916
33181
  if (parts.some((seg) => SKIP_DIRS.has(seg)) || dirParts.some((seg) => seg.startsWith("."))) {
32917
33182
  return -1;
32918
33183
  }
32919
- if (!_Context.eligible(basename4(rel))) return -1;
33184
+ if (!_Context.eligible(basename5(rel))) return -1;
32920
33185
  const stored = rel;
32921
33186
  if (!existsSync19(abs)) {
32922
33187
  this.conn.prepare("DELETE FROM chunks WHERE path = ?").run(stored);
@@ -33012,6 +33277,9 @@ import { randomUUID as randomUUID3 } from "node:crypto";
33012
33277
  function logConnected(backplaneName, url) {
33013
33278
  console.log(`[Tina4] ${backplaneName} connected to ${redactCredentials(url)}`);
33014
33279
  }
33280
+ function driverUrl(backplaneName, url) {
33281
+ return canonicalConnectionUrl(splitConnectionUrl(url, { label: backplaneName, allowHostList: true }));
33282
+ }
33015
33283
  function observeConnectFailure(ready, backplaneName) {
33016
33284
  ready.catch((error2) => {
33017
33285
  console.error(`[Tina4] ${backplaneName} could not connect: ${error2 instanceof Error ? error2.message : String(error2)}`);
@@ -33053,14 +33321,15 @@ var init_websocketBackplane = __esm({
33053
33321
  "src/websocketBackplane.ts"() {
33054
33322
  "use strict";
33055
33323
  init_optionalPackage();
33056
- init_databaseUrl();
33324
+ init_urlRedaction();
33325
+ init_connectionUrl();
33057
33326
  RedisBackplane = class {
33058
33327
  publisher;
33059
33328
  subscriber;
33060
33329
  url;
33061
33330
  ready;
33062
33331
  constructor(url) {
33063
- const resolvedUrl = url ?? process.env.TINA4_WS_BACKPLANE_URL ?? "redis://localhost:6379";
33332
+ const resolvedUrl = driverUrl("RedisBackplane", url ?? process.env.TINA4_WS_BACKPLANE_URL ?? "redis://localhost:6379");
33064
33333
  this.url = resolvedUrl;
33065
33334
  const redisModuleUrl = resolveOptionalPackage("redis", "RedisBackplane");
33066
33335
  this.ready = (async () => {
@@ -33101,7 +33370,7 @@ var init_websocketBackplane = __esm({
33101
33370
  ready;
33102
33371
  natsModuleUrl;
33103
33372
  constructor(url) {
33104
- const resolvedUrl = url ?? process.env.TINA4_WS_BACKPLANE_URL ?? "nats://localhost:4222";
33373
+ const resolvedUrl = driverUrl("NATSBackplane", url ?? process.env.TINA4_WS_BACKPLANE_URL ?? "nats://localhost:4222");
33105
33374
  this.url = resolvedUrl;
33106
33375
  const natsModuleUrl = resolveOptionalPackage("nats", "NATSBackplane");
33107
33376
  this.natsModuleUrl = natsModuleUrl;
@@ -35986,13 +36255,13 @@ var init_liteBackend = __esm({
35986
36255
  }
35987
36256
  return null;
35988
36257
  }
35989
- popBatch(queue, bridge, count) {
36258
+ popBatch(queue, bridge, count2) {
35990
36259
  const dir = this.ensureDir(queue);
35991
36260
  this.reclaimExpired(queue, bridge.getMaxRetries(), this.nowIso());
35992
36261
  const now = this.nowIso();
35993
36262
  const results = [];
35994
36263
  for (const [filename, job] of this.availableCandidates(queue, now)) {
35995
- if (results.length >= count) break;
36264
+ if (results.length >= count2) break;
35996
36265
  const filePath = join24(dir, filename);
35997
36266
  job.topic = queue;
35998
36267
  job.priority = job.priority ?? 0;
@@ -36043,24 +36312,24 @@ var init_liteBackend = __esm({
36043
36312
  if (isDead || isReserved) {
36044
36313
  return files.length;
36045
36314
  }
36046
- let count = 0;
36315
+ let count2 = 0;
36047
36316
  for (const file of files) {
36048
36317
  try {
36049
36318
  const job = JSON.parse(readFileSync16(join24(scanDir, file), "utf-8"));
36050
- if (job.status === status2) count++;
36319
+ if (job.status === status2) count2++;
36051
36320
  } catch {
36052
36321
  }
36053
36322
  }
36054
- return count;
36323
+ return count2;
36055
36324
  }
36056
36325
  clear(queue) {
36057
36326
  const dir = this.ensureDir(queue);
36058
- let count = 0;
36327
+ let count2 = 0;
36059
36328
  try {
36060
36329
  const files = readdirSync12(dir).filter((f) => f.endsWith(".queue-data"));
36061
36330
  for (const file of files) {
36062
36331
  unlinkSync8(join24(dir, file));
36063
- count++;
36332
+ count2++;
36064
36333
  }
36065
36334
  } catch {
36066
36335
  }
@@ -36070,7 +36339,7 @@ var init_liteBackend = __esm({
36070
36339
  const files = readdirSync12(failedDir).filter((f) => f.endsWith(".queue-data"));
36071
36340
  for (const file of files) {
36072
36341
  unlinkSync8(join24(failedDir, file));
36073
- count++;
36342
+ count2++;
36074
36343
  }
36075
36344
  }
36076
36345
  } catch {
@@ -36081,12 +36350,12 @@ var init_liteBackend = __esm({
36081
36350
  const files = readdirSync12(reservedDir).filter((f) => f.endsWith(".queue-data"));
36082
36351
  for (const file of files) {
36083
36352
  unlinkSync8(join24(reservedDir, file));
36084
- count++;
36353
+ count2++;
36085
36354
  }
36086
36355
  }
36087
36356
  } catch {
36088
36357
  }
36089
- return count;
36358
+ return count2;
36090
36359
  }
36091
36360
  /**
36092
36361
  * Jobs that have failed at least once but are still being retried.
@@ -36166,7 +36435,7 @@ var init_liteBackend = __esm({
36166
36435
  return results;
36167
36436
  }
36168
36437
  purge(queue, status2, maxRetries = 3) {
36169
- let count = 0;
36438
+ let count2 = 0;
36170
36439
  const isDead = _LiteBackend.DEAD_STATES.includes(status2);
36171
36440
  if (isDead) {
36172
36441
  const failedDir = this.ensureFailedDir(queue);
@@ -36175,7 +36444,7 @@ var init_liteBackend = __esm({
36175
36444
  for (const file of files) {
36176
36445
  try {
36177
36446
  unlinkSync8(join24(failedDir, file));
36178
- count++;
36447
+ count2++;
36179
36448
  } catch {
36180
36449
  }
36181
36450
  }
@@ -36190,7 +36459,7 @@ var init_liteBackend = __esm({
36190
36459
  const job = JSON.parse(readFileSync16(join24(dir, file), "utf-8"));
36191
36460
  if (job.status === status2) {
36192
36461
  unlinkSync8(join24(dir, file));
36193
- count++;
36462
+ count2++;
36194
36463
  }
36195
36464
  } catch {
36196
36465
  }
@@ -36198,7 +36467,7 @@ var init_liteBackend = __esm({
36198
36467
  } catch {
36199
36468
  }
36200
36469
  }
36201
- return count;
36470
+ return count2;
36202
36471
  }
36203
36472
  /**
36204
36473
  * Re-queue dead-letter jobs that are under the (possibly raised) limit back
@@ -36208,7 +36477,7 @@ var init_liteBackend = __esm({
36208
36477
  retryFailed(queue, maxRetries = 3) {
36209
36478
  const failedDir = this.ensureFailedDir(queue);
36210
36479
  const queueDir = this.ensureDir(queue);
36211
- let count = 0;
36480
+ let count2 = 0;
36212
36481
  try {
36213
36482
  const files = readdirSync12(failedDir).filter((f) => f.endsWith(".queue-data"));
36214
36483
  for (const file of files) {
@@ -36225,13 +36494,13 @@ var init_liteBackend = __esm({
36225
36494
  const prefix = this.nextPrefix();
36226
36495
  writeFileSync11(join24(queueDir, `${prefix}_${job.id}.queue-data`), JSON.stringify(job, null, 2));
36227
36496
  unlinkSync8(filePath);
36228
- count++;
36497
+ count2++;
36229
36498
  } catch {
36230
36499
  }
36231
36500
  }
36232
36501
  } catch {
36233
36502
  }
36234
- return count;
36503
+ return count2;
36235
36504
  }
36236
36505
  popById(queue, id) {
36237
36506
  const dir = this.ensureDir(queue);
@@ -36503,17 +36772,17 @@ var init_queue = __esm({
36503
36772
  /**
36504
36773
  * Pop up to count jobs at once. Returns a partial batch if fewer available.
36505
36774
  */
36506
- popBatch(count) {
36775
+ popBatch(count2) {
36507
36776
  if (this.externalBackend) {
36508
36777
  const jobs = [];
36509
- for (let i = 0; i < count; i++) {
36778
+ for (let i = 0; i < count2; i++) {
36510
36779
  const job = this.pop();
36511
36780
  if (!job) break;
36512
36781
  jobs.push(job);
36513
36782
  }
36514
36783
  return jobs;
36515
36784
  }
36516
- return this.liteBackend.popBatch(this.topic, this, count);
36785
+ return this.liteBackend.popBatch(this.topic, this, count2);
36517
36786
  }
36518
36787
  /**
36519
36788
  * Process jobs from a queue with a handler function.
@@ -39040,7 +39309,7 @@ ${end}
39040
39309
  // src/devAdmin.ts
39041
39310
  import { cpus as osCpus } from "node:os";
39042
39311
  import { readFileSync as readFileSync20, writeFileSync as writeFileSync15, existsSync as existsSync24, readdirSync as readdirSync16, mkdirSync as mkdirSync18, copyFileSync as copyFileSync2, statSync as statSync18, 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";
39043
- import { join as join28, dirname as dirname14, resolve as resolve16, relative as relative8, sep as sep9, basename as basename5 } from "node:path";
39312
+ import { join as join28, dirname as dirname14, resolve as resolve16, relative as relative8, sep as sep9, basename as basename6 } from "node:path";
39044
39313
  import { fileURLToPath as fileURLToPath8 } from "node:url";
39045
39314
  import { timingSafeEqual as timingSafeEqual2 } from "node:crypto";
39046
39315
  import net2 from "node:net";
@@ -39241,12 +39510,12 @@ function quoteTableRef(name) {
39241
39510
  function parseSeedRequest(url, body) {
39242
39511
  const b = body ?? {};
39243
39512
  const table2 = String(url.searchParams.get("table") ?? b.table ?? "");
39244
- const count = parseInt(String(url.searchParams.get("count") ?? b.count ?? "10"), 10) || 10;
39513
+ const count2 = parseInt(String(url.searchParams.get("count") ?? b.count ?? "10"), 10) || 10;
39245
39514
  const seedRaw = url.searchParams.get("seed") ?? b.seed;
39246
39515
  const seed = seedRaw !== void 0 && seedRaw !== null && String(seedRaw) !== "" ? Number.isNaN(parseInt(String(seedRaw), 10)) ? void 0 : parseInt(String(seedRaw), 10) : void 0;
39247
39516
  const clear = String(url.searchParams.get("clear") ?? b.clear ?? "") === "true" || b.clear === true;
39248
39517
  const strict = String(url.searchParams.get("strict") ?? b.strict ?? "") === "true" || b.strict === true;
39249
- return { table: table2, count, seed, clear, strict };
39518
+ return { table: table2, count: count2, seed, clear, strict };
39250
39519
  }
39251
39520
  function buildSeedFieldMap(columns, fake) {
39252
39521
  const rules = [
@@ -39415,6 +39684,11 @@ function parseEnvFile() {
39415
39684
  }
39416
39685
  return result;
39417
39686
  }
39687
+ function savedUrlIfRedacted(posted) {
39688
+ const current = parseEnvFile().TINA4_DATABASE_URL ?? "";
39689
+ if (posted === "" || current === "" || posted === current) return posted;
39690
+ return posted === redactCredentials(current) ? current : posted;
39691
+ }
39418
39692
  function walkDirRecursive(dir) {
39419
39693
  const results = [];
39420
39694
  if (!existsSync24(dir)) return results;
@@ -39480,7 +39754,7 @@ function realPathOf2(target) {
39480
39754
  } catch {
39481
39755
  }
39482
39756
  if (present || dirname14(existing) === existing) break;
39483
- tail.unshift(basename5(existing));
39757
+ tail.unshift(basename6(existing));
39484
39758
  existing = dirname14(existing);
39485
39759
  }
39486
39760
  return join28(realpathSync6(existing), ...tail);
@@ -39844,6 +40118,7 @@ var init_devAdmin = __esm({
39844
40118
  init_feedback();
39845
40119
  init_mcp();
39846
40120
  init_version();
40121
+ init_urlRedaction();
39847
40122
  cpuCount = osCpus().length;
39848
40123
  DEV_MCP_PREFIXES = ["/__dev/api/mcp", "/__dev/mcp"];
39849
40124
  DEV_PUBLIC_ASSETS = /* @__PURE__ */ new Set(["/__dev/toolbar.css", "/__dev/toolbar.js"]);
@@ -40032,8 +40307,8 @@ var init_devAdmin = __esm({
40032
40307
  static read(id) {
40033
40308
  return this.mailbox.read(id);
40034
40309
  }
40035
- static seed(count = 5) {
40036
- this.mailbox.seed(count);
40310
+ static seed(count2 = 5) {
40311
+ this.mailbox.seed(count2);
40037
40312
  }
40038
40313
  static clear(folder) {
40039
40314
  this.mailbox.clear(folder);
@@ -40066,15 +40341,15 @@ var init_devAdmin = __esm({
40066
40341
  return job;
40067
40342
  }
40068
40343
  static retryFailed() {
40069
- let count = 0;
40344
+ let count2 = 0;
40070
40345
  for (const job of this.jobs) {
40071
40346
  if (job.status === "failed") {
40072
40347
  job.status = "pending";
40073
40348
  job.error = void 0;
40074
- count++;
40349
+ count2++;
40075
40350
  }
40076
40351
  }
40077
- return count;
40352
+ return count2;
40078
40353
  }
40079
40354
  static purgeCompleted() {
40080
40355
  const before = this.jobs.length;
@@ -40581,12 +40856,12 @@ var init_devAdmin = __esm({
40581
40856
  }
40582
40857
  };
40583
40858
  handleQueueRetry = (_req, res) => {
40584
- const count = DevQueue.retryFailed();
40585
- res.json({ retried: count });
40859
+ const count2 = DevQueue.retryFailed();
40860
+ res.json({ retried: count2 });
40586
40861
  };
40587
40862
  handleQueuePurge = (_req, res) => {
40588
- const count = DevQueue.purgeCompleted();
40589
- res.json({ purged: count });
40863
+ const count2 = DevQueue.purgeCompleted();
40864
+ res.json({ purged: count2 });
40590
40865
  };
40591
40866
  handleQueueReplay = (req2, res) => {
40592
40867
  const url = new URL(req2.url ?? "/", "http://localhost");
@@ -40622,9 +40897,9 @@ var init_devAdmin = __esm({
40622
40897
  };
40623
40898
  handleMailboxSeed = (req2, res) => {
40624
40899
  const url = new URL(req2.url ?? "/", "http://localhost");
40625
- const count = parseInt(url.searchParams.get("count") ?? "5", 10);
40626
- DevMailboxStore.seed(count);
40627
- res.json({ seeded: count });
40900
+ const count2 = parseInt(url.searchParams.get("count") ?? "5", 10);
40901
+ DevMailboxStore.seed(count2);
40902
+ res.json({ seeded: count2 });
40628
40903
  };
40629
40904
  handleMailboxClear = (req2, res) => {
40630
40905
  const url = new URL(req2.url ?? "/", "http://localhost");
@@ -40675,7 +40950,7 @@ var init_devAdmin = __esm({
40675
40950
  };
40676
40951
  handleSeed = async (req2, res) => {
40677
40952
  const url = new URL(req2.url ?? "/", "http://localhost");
40678
- const { table: table2, count, seed, clear, strict } = parseSeedRequest(url, req2.body);
40953
+ const { table: table2, count: count2, seed, clear, strict } = parseSeedRequest(url, req2.body);
40679
40954
  if (!table2) {
40680
40955
  res.json({ error: "Missing table parameter" });
40681
40956
  return;
@@ -40691,7 +40966,7 @@ var init_devAdmin = __esm({
40691
40966
  return;
40692
40967
  }
40693
40968
  const fieldMap = buildSeedFieldMap(columns, fake);
40694
- const summary = await seedTable2(db, table2, count, fieldMap, void 0, { clear, strict });
40969
+ const summary = await seedTable2(db, table2, count2, fieldMap, void 0, { clear, strict });
40695
40970
  res.json({ seeded: summary.seeded, failed: summary.failed, errors: summary.errors, table: table2 });
40696
40971
  } catch (e) {
40697
40972
  res.json({ error: e?.message ?? "Database not connected" });
@@ -40838,7 +41113,7 @@ var init_devAdmin = __esm({
40838
41113
  };
40839
41114
  handleSeedRun = async (req2, res) => {
40840
41115
  const body = req2.body || {};
40841
- const count = parseInt(String(body.count ?? "10"), 10) || 10;
41116
+ const count2 = parseInt(String(body.count ?? "10"), 10) || 10;
40842
41117
  try {
40843
41118
  const orm = await Promise.resolve().then(() => (init_src(), src_exports));
40844
41119
  const dirs = ["src/orm", "src/models"].map((d) => resolve16(process.cwd(), d)).filter((d) => existsSync24(d));
@@ -40850,7 +41125,7 @@ var init_devAdmin = __esm({
40850
41125
  res.json({ ok: false, error: "No models found in src/orm/ or src/models/" }, 400);
40851
41126
  return;
40852
41127
  }
40853
- const summaries = await orm.seedModels(classes, count);
41128
+ const summaries = await orm.seedModels(classes, count2);
40854
41129
  let seeded = 0, failed = 0;
40855
41130
  for (const s of Object.values(summaries)) {
40856
41131
  seeded += s.seeded;
@@ -40916,14 +41191,17 @@ var init_devAdmin = __esm({
40916
41191
  handleConnections = (_req, res) => {
40917
41192
  const env = parseEnvFile();
40918
41193
  res.json({
40919
- url: env.TINA4_DATABASE_URL ?? "",
41194
+ // Redacted like the password field below: this used to hand the raw .env
41195
+ // URL - password and all - to any page that could reach the dev API
41196
+ // (GHSA-h2mr-m3v3-cq8c). Save recognises this form and keeps the real URL.
41197
+ url: redactCredentials(env.TINA4_DATABASE_URL ?? ""),
40920
41198
  username: env.TINA4_DATABASE_USERNAME ?? "",
40921
41199
  password: env.TINA4_DATABASE_PASSWORD ? "***" : ""
40922
41200
  });
40923
41201
  };
40924
41202
  handleConnectionsTest = async (req2, res) => {
40925
41203
  const body = req2.body;
40926
- const url = body?.url ?? "";
41204
+ const url = savedUrlIfRedacted(body?.url ?? "");
40927
41205
  const username = body?.username ?? "";
40928
41206
  const password = body?.password ?? "";
40929
41207
  if (!url) {
@@ -40974,7 +41252,7 @@ var init_devAdmin = __esm({
40974
41252
  };
40975
41253
  handleConnectionsSave = (req2, res) => {
40976
41254
  const body = req2.body;
40977
- const url = body?.url ?? "";
41255
+ const url = savedUrlIfRedacted(body?.url ?? "");
40978
41256
  const username = body?.username ?? "";
40979
41257
  const password = body?.password ?? "";
40980
41258
  if (!url) {
@@ -43425,6 +43703,9 @@ function shutdownTimeoutSeconds() {
43425
43703
  }
43426
43704
  return parsed;
43427
43705
  }
43706
+ function shutdownSignals(platform = process.platform) {
43707
+ return platform === "win32" ? ["SIGTERM", "SIGINT", "SIGBREAK"] : ["SIGTERM", "SIGINT"];
43708
+ }
43428
43709
  function bannerSurfaceLines(port, opts) {
43429
43710
  return [
43430
43711
  opts.swaggerEnabled ? `
@@ -43442,7 +43723,7 @@ function swaggerAdvertised() {
43442
43723
  return TRUTHY3.includes(raw);
43443
43724
  }
43444
43725
  function stripUrlCredentials(text) {
43445
- return text.replace(/:\/\/[^/\s]*@/g, "://");
43726
+ return stripCredentials(text);
43446
43727
  }
43447
43728
  function isModuleNotFound(err) {
43448
43729
  const code = err?.code;
@@ -44712,21 +44993,19 @@ ${reset2}
44712
44993
  }
44713
44994
  process.exit(0);
44714
44995
  };
44715
- const onSigterm = () => {
44716
- void gracefulShutdown("SIGTERM").catch(() => process.exit(0));
44717
- };
44718
- const onSigint = () => {
44719
- void gracefulShutdown("SIGINT").catch(() => process.exit(0));
44720
- };
44721
- process.on("SIGTERM", onSigterm);
44722
- process.on("SIGINT", onSigint);
44996
+ const signalListeners = shutdownSignals().map((signal) => ({
44997
+ signal,
44998
+ listener: () => {
44999
+ void gracefulShutdown(signal).catch(() => process.exit(0));
45000
+ }
45001
+ }));
45002
+ signalListeners.forEach(({ signal, listener }) => process.on(signal, listener));
44723
45003
  await startAllTcpServices(host);
44724
45004
  const loopWatchdog = startLoopWatchdog();
44725
45005
  resolvePromise({
44726
45006
  close: () => {
44727
45007
  loopWatchdog.stop();
44728
- process.off("SIGTERM", onSigterm);
44729
- process.off("SIGINT", onSigint);
45008
+ signalListeners.forEach(({ signal, listener }) => process.off(signal, listener));
44730
45009
  stopAllBackgroundTasks();
44731
45010
  stopAcceptingAllTcpServices();
44732
45011
  void drainAllTcpServices();
@@ -44863,6 +45142,7 @@ var init_server = __esm({
44863
45142
  init_background();
44864
45143
  init_tcp();
44865
45144
  init_version();
45145
+ init_urlRedaction();
44866
45146
  __filename = fileURLToPath9(import.meta.url);
44867
45147
  __dirname = dirname15(__filename);
44868
45148
  BUILTIN_ERROR_TEMPLATES_DIR = resolve19(__dirname, "..", "templates");
@@ -45114,6 +45394,7 @@ var init_mqtt = __esm({
45114
45394
  init_logger();
45115
45395
  init_background();
45116
45396
  init_mqttMessage();
45397
+ init_connectionUrl();
45117
45398
  MqttError = class extends Error {
45118
45399
  constructor(message) {
45119
45400
  super(message);
@@ -45219,59 +45500,34 @@ var init_mqtt = __esm({
45219
45500
  if (raw === "") {
45220
45501
  throw new Error(`MQTT url is empty -- set TINA4_MQTT_URL (e.g. ${DEFAULT_URL})`);
45221
45502
  }
45222
- let scheme = null;
45223
- let rest = raw;
45224
45503
  const schemeMatch = raw.match(/^([A-Za-z][A-Za-z0-9+.-]*):\/\//);
45504
+ let target = raw;
45225
45505
  if (schemeMatch) {
45226
- scheme = schemeMatch[1].toLowerCase();
45506
+ const scheme = schemeMatch[1].toLowerCase();
45227
45507
  if (!["mqtt", "tcp", "mqtts"].includes(scheme)) {
45228
45508
  throw new Error(
45229
- `unsupported MQTT url scheme '${scheme}' in '${raw}' -- this client speaks mqtt://, tcp:// or mqtts:// (TLS). WebSocket transports are not implemented.`
45509
+ `unsupported MQTT url scheme '${scheme}' -- this client speaks mqtt://, tcp:// or mqtts:// (TLS). WebSocket transports are not implemented.`
45230
45510
  );
45231
45511
  }
45232
- rest = raw.slice(schemeMatch[0].length);
45233
- }
45234
- const tlsFlag = scheme === "mqtts";
45235
- let username = null;
45236
- let password = null;
45237
- const atPos = rest.lastIndexOf("@");
45238
- if (atPos !== -1) {
45239
- const userinfo = rest.slice(0, atPos);
45240
- rest = rest.slice(atPos + 1);
45241
- const colon = userinfo.indexOf(":");
45242
- if (colon === -1) {
45243
- username = _Mqtt.percentDecode(userinfo);
45244
- } else {
45245
- username = _Mqtt.percentDecode(userinfo.slice(0, colon));
45246
- password = _Mqtt.percentDecode(userinfo.slice(colon + 1));
45247
- }
45248
- }
45249
- const hostPort = rest.split("/", 1)[0];
45250
- let host = hostPort;
45251
- let portStr = null;
45252
- if (hostPort.startsWith("[")) {
45253
- const close = hostPort.indexOf("]");
45254
- if (close === -1) throw new Error(`malformed MQTT url '${raw}' -- unclosed IPv6 bracket`);
45255
- host = hostPort.slice(1, close);
45256
- const after = hostPort.slice(close + 1);
45257
- if (after.startsWith(":")) portStr = after.slice(1);
45258
- } else {
45259
- const colon = hostPort.indexOf(":");
45260
- if (colon !== -1) {
45261
- host = hostPort.slice(0, colon);
45262
- portStr = hostPort.slice(colon + 1);
45263
- }
45512
+ } else if (/^(\[[^\]\s]*\]|[^\s:/@?#[\]]+)(:\d*)?$/.test(raw)) {
45513
+ target = `mqtt://${raw}`;
45514
+ }
45515
+ let parts;
45516
+ try {
45517
+ parts = splitConnectionUrl(target, { label: "Mqtt", expected: "mqtt://[user[:password]@]host[:port]" });
45518
+ } catch (err) {
45519
+ throw new MqttError(`malformed MQTT url -- ${err.message.replace(/^Mqtt: /, "")}`);
45264
45520
  }
45265
- if (host === "") throw new Error(`malformed MQTT url '${raw}' -- expected mqtt://host:port`);
45266
- if (portStr !== null && portStr !== "" && !/^\d+$/.test(portStr)) {
45267
- throw new Error(`malformed MQTT url '${raw}' -- port must be numeric`);
45521
+ if (parts.host === "") {
45522
+ throw new MqttError("malformed MQTT url -- expected mqtt://host:port. The url is not shown because it may contain a password.");
45268
45523
  }
45524
+ const tlsFlag = parts.scheme === "mqtts";
45269
45525
  return {
45270
- host,
45271
- port: portStr !== null && portStr !== "" ? parseInt(portStr, 10) : tlsFlag ? DEFAULT_TLS_PORT : DEFAULT_PORT,
45526
+ host: parts.host,
45527
+ port: parts.port !== null ? parts.port : tlsFlag ? DEFAULT_TLS_PORT : DEFAULT_PORT,
45272
45528
  tls: tlsFlag,
45273
- username: username !== null && username !== "" ? username : null,
45274
- password
45529
+ username: parts.rawUsername !== null && parts.rawUsername !== "" ? _Mqtt.percentDecode(parts.rawUsername) : null,
45530
+ password: parts.rawPassword !== null ? _Mqtt.percentDecode(parts.rawPassword) : null
45275
45531
  };
45276
45532
  }
45277
45533
  /**
@@ -46308,7 +46564,7 @@ import https from "node:https";
46308
46564
  import { URL as URL2 } from "node:url";
46309
46565
  import { randomBytes as randomBytes11 } from "node:crypto";
46310
46566
  import { promises as fsp, createWriteStream } from "node:fs";
46311
- import { basename as basename6 } from "node:path";
46567
+ import { basename as basename7 } from "node:path";
46312
46568
  import { pipeline } from "node:stream/promises";
46313
46569
  function keepCrossOriginHeaders(headers) {
46314
46570
  const out = {};
@@ -46709,7 +46965,7 @@ var init_api = __esm({
46709
46965
  error: err instanceof Error ? err.message : String(err)
46710
46966
  };
46711
46967
  }
46712
- uploadName = filename || basename6(filePath);
46968
+ uploadName = filename || basename7(filePath);
46713
46969
  } else {
46714
46970
  return { http_code: null, body: null, headers: {}, error: "upload requires filePath or fileBytes" };
46715
46971
  }
@@ -47220,7 +47476,7 @@ var init_api = __esm({
47220
47476
  import net4 from "node:net";
47221
47477
  import tls2 from "node:tls";
47222
47478
  import { readFileSync as readFileSync25 } from "node:fs";
47223
- import { basename as basename7 } from "node:path";
47479
+ import { basename as basename8 } from "node:path";
47224
47480
  import { randomUUID as randomUUID8 } from "node:crypto";
47225
47481
  function normaliseEncryption(value, kind) {
47226
47482
  const normalised = value.trim().toLowerCase();
@@ -47383,7 +47639,7 @@ function buildMimeMessage(options) {
47383
47639
  lines.push(options.body);
47384
47640
  }
47385
47641
  for (const filePath of options.attachments) {
47386
- const fileName = basename7(filePath);
47642
+ const fileName = basename8(filePath);
47387
47643
  const fileData = readFileSync25(filePath);
47388
47644
  const base64Data = fileData.toString("base64");
47389
47645
  lines.push("");
@@ -50696,26 +50952,25 @@ var init_aiClient = __esm({
50696
50952
  // src/queueBackends/rabbitmqBackend.ts
50697
50953
  import { execFileSync as execFileSync4 } from "node:child_process";
50698
50954
  import { randomUUID as randomUUID9 } from "node:crypto";
50955
+ function amqpTarget(url) {
50956
+ return /^[A-Za-z][A-Za-z0-9+.-]*(:\/|\/\/)|[@\s]/.test(url) ? url : `amqp://${url}`;
50957
+ }
50958
+ function amqpCredentials(username, password) {
50959
+ const creds = {};
50960
+ if (username !== null) creds.username = username;
50961
+ if (password !== null) creds.password = password;
50962
+ return creds;
50963
+ }
50699
50964
  function parseAmqpUrl(url) {
50700
50965
  const config = {};
50701
- let rest = url.replace(/^amqps:\/\//, "").replace(/^amqp:\/\//, "");
50702
- const atIndex = rest.indexOf("@");
50703
- if (atIndex !== -1) {
50704
- const creds = rest.slice(0, atIndex);
50705
- rest = rest.slice(atIndex + 1);
50706
- const colonIndex = creds.indexOf(":");
50707
- if (colonIndex !== -1) {
50708
- config.username = creds.slice(0, colonIndex);
50709
- config.password = creds.slice(colonIndex + 1);
50710
- } else {
50711
- config.username = creds;
50712
- }
50713
- }
50714
- let hostport = rest;
50715
- const slashIndex = rest.indexOf("/");
50716
- if (slashIndex !== -1) {
50717
- hostport = rest.slice(0, slashIndex);
50718
- const vhost = rest.slice(slashIndex + 1);
50966
+ const parts = splitConnectionUrl(amqpTarget(url), {
50967
+ label: "parseAmqpUrl",
50968
+ expected: "amqp://[user[:password]@]host[:port][/vhost]"
50969
+ });
50970
+ Object.assign(config, amqpCredentials(parts.rawUsername, parts.rawPassword));
50971
+ const hostport = parts.hostPort;
50972
+ if (parts.tail.startsWith("/")) {
50973
+ const vhost = parts.tail.slice(1);
50719
50974
  if (vhost) {
50720
50975
  config.vhost = decodeURIComponent(vhost);
50721
50976
  }
@@ -50733,6 +50988,7 @@ var AMQP_PROTOCOL_HEADER, CONNECTION_START, CONNECTION_START_OK, CONNECTION_TUNE
50733
50988
  var init_rabbitmqBackend = __esm({
50734
50989
  "src/queueBackends/rabbitmqBackend.ts"() {
50735
50990
  "use strict";
50991
+ init_connectionUrl();
50736
50992
  AMQP_PROTOCOL_HEADER = Buffer.from([65, 77, 81, 80, 0, 0, 9, 1]);
50737
50993
  CONNECTION_START = 10 << 16 | 10;
50738
50994
  CONNECTION_START_OK = 10 << 16 | 11;
@@ -52011,6 +52267,7 @@ __export(index_exports, {
52011
52267
  SSO: () => Sso,
52012
52268
  SafeString: () => SafeString2,
52013
52269
  SecurityHeadersMiddleware: () => SecurityHeadersMiddleware,
52270
+ SeedError: () => SeedError,
52014
52271
  ServiceRunner: () => ServiceRunner,
52015
52272
  Session: () => Session,
52016
52273
  Sso: () => Sso,
@@ -52414,6 +52671,7 @@ export {
52414
52671
  Sso as SSO,
52415
52672
  SafeString2 as SafeString,
52416
52673
  SecurityHeadersMiddleware,
52674
+ SeedError,
52417
52675
  ServiceRunner,
52418
52676
  Session,
52419
52677
  Sso,