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.
@@ -70,10 +70,10 @@ var init_databaseResult = __esm({
70
70
  _adapter;
71
71
  _sql;
72
72
  _columnInfoCache;
73
- constructor(records, columns, count, limit, offset, adapter, sql) {
73
+ constructor(records, columns, count2, limit, offset, adapter, sql) {
74
74
  this.records = records ?? [];
75
75
  this.columns = columns ?? (this.records.length > 0 ? Object.keys(this.records[0]) : []);
76
- this.count = count ?? this.records.length;
76
+ this.count = count2 ?? this.records.length;
77
77
  this.limit = limit ?? this.records.length;
78
78
  this.offset = offset ?? 0;
79
79
  this._adapter = adapter;
@@ -366,36 +366,28 @@ var init_modelCollection = __esm({
366
366
  }
367
367
  });
368
368
 
369
- // src/databaseUrl.ts
370
- import { inspect } from "node:util";
371
- function stripOneSlash(path9) {
372
- return path9.startsWith("/") ? path9.slice(1) : path9;
373
- }
374
- function decode(value) {
375
- if (value === void 0 || value === "") return null;
376
- return decodeURIComponent(value);
377
- }
369
+ // ../core/src/urlRedaction.ts
378
370
  function endOfKeywordValue(text, start2) {
379
371
  const open = text[start2];
380
372
  if (open === "{") {
381
373
  const close = text.indexOf("}", start2 + 1);
382
374
  return close === -1 ? text.length : close + 1;
383
375
  }
384
- if (open === "'" || open === '"') {
385
- let i2 = start2 + 1;
386
- while (i2 < text.length) {
387
- if (text[i2] === "\\") {
388
- i2 += 2;
389
- continue;
390
- }
391
- if (text[i2] === open) return i2 + 1;
392
- i2++;
376
+ if (open === "'" || open === '"') return endOfQuoted(text, start2, open);
377
+ const end = text.slice(start2).search(/[;&]/);
378
+ return end === -1 ? text.length : start2 + end;
379
+ }
380
+ function endOfQuoted(text, start2, quote) {
381
+ let i = start2 + 1;
382
+ while (i < text.length) {
383
+ if (text[i] === "\\") {
384
+ i += 2;
385
+ continue;
393
386
  }
394
- return text.length;
387
+ if (text[i] === quote) return i + 1;
388
+ i++;
395
389
  }
396
- let i = start2;
397
- while (i < text.length && text[i] !== ";" && text[i] !== "&") i++;
398
- return i;
390
+ return text.length;
399
391
  }
400
392
  function redactKeywordValues(text) {
401
393
  const pattern = new RegExp(SECRET_KEYWORD_PATTERN.source, SECRET_KEYWORD_PATTERN.flags);
@@ -410,57 +402,258 @@ function redactKeywordValues(text) {
410
402
  }
411
403
  return out + text.slice(cursor);
412
404
  }
413
- function authorityOf(raw) {
414
- const separator = raw.indexOf("://");
415
- if (separator === -1) return null;
416
- const rest = raw.slice(separator + 3);
417
- const end = rest.search(/[/?#]/);
418
- return end === -1 ? rest : rest.slice(0, end);
419
- }
420
- function rawUserinfo(raw) {
421
- const authority = authorityOf(raw);
422
- if (authority === null) return null;
423
- const at = authority.lastIndexOf("@");
424
- return at === -1 ? null : authority.slice(0, at);
425
- }
426
- function redactUserinfoPassword(raw) {
427
- const authority = authorityOf(raw);
428
- if (authority === null) return raw;
429
- const at = authority.lastIndexOf("@");
430
- if (at === -1) return raw;
431
- const colon = authority.slice(0, at).indexOf(":");
432
- if (colon === -1) return raw;
433
- const authorityStart = raw.indexOf("://") + 3;
434
- return raw.slice(0, authorityStart + colon + 1) + REDACTED + raw.slice(authorityStart + at);
405
+ function credentialSpans(line) {
406
+ const spans = [];
407
+ const marker = new RegExp(SCHEME_MARKER.source, "g");
408
+ const lastAt = line.lastIndexOf("@");
409
+ let match;
410
+ while ((match = marker.exec(line)) !== null) {
411
+ const start2 = match.index + match[0].length;
412
+ const withAt = userinfoSpan(line, start2, lastAt);
413
+ if (withAt !== null) {
414
+ spans.push(withAt);
415
+ marker.lastIndex = lastAt + 1;
416
+ continue;
417
+ }
418
+ const portShaped = portShapedSpan(line, start2);
419
+ if (portShaped !== null) {
420
+ spans.push(portShaped);
421
+ break;
422
+ }
423
+ }
424
+ return spans;
425
+ }
426
+ function userinfoSpan(line, start2, lastAt) {
427
+ if (lastAt < start2) return null;
428
+ const colon = line.indexOf(":", start2);
429
+ if (colon === -1 || colon >= lastAt || /[/?#]/.test(line.slice(start2, colon))) return null;
430
+ return { authorityStart: start2, at: lastAt, passwordStart: colon + 1, passwordEnd: lastAt };
431
+ }
432
+ function portShapedSpan(line, start2) {
433
+ const rest = line.slice(start2);
434
+ const authorityEnd = rest.search(/[/?#\s]/);
435
+ const authority = authorityEnd === -1 ? rest : rest.slice(0, authorityEnd);
436
+ const colon = authority.indexOf(":", authority.startsWith("[") ? authority.indexOf("]") + 1 : 0);
437
+ if (colon === -1) return null;
438
+ const port = authority.slice(colon + 1);
439
+ if (port === "") return null;
440
+ if (/^\d+$/.test(port) && !digitLedPassword(rest.slice(authority.length))) return null;
441
+ const maskStart = start2 + colon + 1;
442
+ return { authorityStart: start2, at: -1, passwordStart: maskStart, passwordEnd: keptQueryStart(line, maskStart) };
443
+ }
444
+ function keptQueryStart(line, from) {
445
+ const query = line.indexOf("?", from);
446
+ return query !== -1 && KEPT_QUERY.test(line.slice(query)) ? query : line.length;
447
+ }
448
+ function digitLedPassword(afterPort) {
449
+ if (afterPort.startsWith("#")) return true;
450
+ return afterPort.startsWith("?") && !KEPT_QUERY.test(afterPort.split(/\s/, 1)[0]);
451
+ }
452
+ function rewriteLines(text, render2) {
453
+ return text.split(/(\r?\n)/).map((part) => part === "\n" || part === "\r\n" ? part : render2(part, credentialSpans(part))).join("");
435
454
  }
436
455
  function redactCredentials(raw) {
437
456
  if (typeof raw !== "string" || raw === "") return raw;
438
- return redactKeywordValues(redactUserinfoPassword(raw));
439
- }
440
- function schemeOf(raw) {
441
- const match = raw.match(/^([a-zA-Z][a-zA-Z0-9+.-]*):/);
442
- return match ? match[1].toLowerCase() : null;
443
- }
444
- function hostPortOf(raw) {
445
- const authority = authorityOf(raw);
446
- if (authority === null) return null;
447
- const at = authority.lastIndexOf("@");
448
- const hostPort = at === -1 ? authority : authority.slice(at + 1);
449
- return hostPort === "" ? null : hostPort;
450
- }
451
- function invalidUrlError(raw, engine) {
452
- const named = engine ?? schemeOf(raw);
453
- const subject = named ? `invalid ${named} URL` : "invalid URL (no scheme found)";
454
- const hostPort = hostPortOf(raw);
455
- const at = hostPort === null ? "" : ` at '${hostPort}'`;
456
- return new Error(
457
- `DatabaseUrl: ${subject}${at} - expected scheme://[user[:password]@]host[:port]/database. The URL itself is not shown because it may contain a password.`
457
+ const masked = rewriteLines(raw, (line, spans) => {
458
+ let out = "";
459
+ let cursor = 0;
460
+ for (const span of spans) {
461
+ out += line.slice(cursor, span.passwordStart) + REDACTED;
462
+ cursor = span.passwordEnd;
463
+ }
464
+ return out + line.slice(cursor);
465
+ });
466
+ return redactKeywordValues(masked);
467
+ }
468
+ function stripCredentials(raw) {
469
+ if (typeof raw !== "string" || raw === "") return raw;
470
+ const stripped = rewriteLines(raw, (line, spans) => {
471
+ let out = "";
472
+ let cursor = 0;
473
+ for (const span of spans) {
474
+ if (span.at === -1) {
475
+ out += line.slice(cursor, span.passwordStart) + REDACTED;
476
+ cursor = span.passwordEnd;
477
+ } else {
478
+ out += line.slice(cursor, span.authorityStart);
479
+ cursor = span.at + 1;
480
+ }
481
+ }
482
+ return out + line.slice(cursor);
483
+ });
484
+ return redactKeywordValues(stripped);
485
+ }
486
+ var REDACTED, SCHEME_MARKER, KEPT_QUERY, SECRET_KEYWORD_PATTERN;
487
+ var init_urlRedaction = __esm({
488
+ "../core/src/urlRedaction.ts"() {
489
+ "use strict";
490
+ REDACTED = "***";
491
+ SCHEME_MARKER = /(?<![A-Za-z0-9+.\-/])([A-Za-z][A-Za-z0-9+.-]*)(:\/\/|:\/|\/\/)/g;
492
+ KEPT_QUERY = /^\?[^\s=&#?]+=[^\s&#?]*(?:&[^\s=&#?]+=[^\s&#?]*)*(?:#\S*)?$/;
493
+ SECRET_KEYWORD_PATTERN = /(^|[;&?\s])(pwd|password|passwd)(\s*=\s*)/gi;
494
+ }
495
+ });
496
+
497
+ // ../core/src/connectionUrl.ts
498
+ function decodeComponent(value) {
499
+ try {
500
+ return decodeURIComponent(value);
501
+ } catch {
502
+ return value.replace(/(?:%[0-9A-Fa-f]{2})+/g, (seq) => {
503
+ try {
504
+ return decodeURIComponent(seq);
505
+ } catch {
506
+ return seq;
507
+ }
508
+ });
509
+ }
510
+ }
511
+ function splitHostPort(hostPort) {
512
+ if (hostPort.startsWith("[")) {
513
+ const close = hostPort.indexOf("]");
514
+ if (close === -1) return null;
515
+ const after = hostPort.slice(close + 1);
516
+ if (after !== "" && !after.startsWith(":")) return null;
517
+ return [hostPort.slice(1, close), after === "" ? null : after.slice(1)];
518
+ }
519
+ const colon = hostPort.indexOf(":");
520
+ if (colon === -1) return [hostPort, null];
521
+ return [hostPort.slice(0, colon), hostPort.slice(colon + 1)];
522
+ }
523
+ function splitConnectionUrl(raw, options) {
524
+ const refuse = refuser(raw, options);
525
+ const { scheme, rest } = schemeAndRest(raw, refuse);
526
+ const { userinfo, afterUserinfo } = splitUserinfo(rest, refuse);
527
+ const { hostPort, tail } = hostPortAndTail(afterUserinfo, userinfo !== null, refuse);
528
+ const { host, port } = firstHost(hostPort, options.allowHostList === true, refuse, userinfo !== null ? hostPort : void 0);
529
+ refuseDigitLedPassword(userinfo, port, tail, refuse);
530
+ const { rawUsername, rawPassword } = userinfoParts(userinfo);
531
+ return {
532
+ scheme,
533
+ userinfo,
534
+ rawUsername,
535
+ rawPassword,
536
+ username: decodeOrNull(rawUsername),
537
+ password: decodeOrNull(rawPassword),
538
+ hostPort,
539
+ host,
540
+ port,
541
+ tail
542
+ };
543
+ }
544
+ function refuser(raw, options) {
545
+ const expected = options.expected ?? "scheme://[user[:password]@]host[:port]/path";
546
+ const named = SCHEME_PREFIX.exec(String(raw ?? ""))?.[1]?.toLowerCase();
547
+ const subject = `${options.label}: invalid ${named ? `${named} ` : ""}URL`;
548
+ return (why, hostPort) => new ConnectionUrlError(
549
+ `${subject}${hostPort ? ` at '${hostPort}'` : ""} (${why}) - expected ${expected}. The URL itself is not shown because it may contain a password.`
458
550
  );
459
551
  }
460
- var ENGINE_ALIASES, DEFAULT_PORTS, REDACTED, SECRET_KEYWORD_PATTERN, DatabaseUrl;
552
+ function schemeAndRest(raw, refuse) {
553
+ if (typeof raw !== "string") throw refuse("not a string");
554
+ const head = /^([A-Za-z][A-Za-z0-9+.-]*):\/\//.exec(raw);
555
+ if (!head) throw refuse(SCHEME_PREFIX.test(raw) ? "the scheme must be followed by ://" : "no scheme:// found");
556
+ return { scheme: head[1].toLowerCase(), rest: raw.slice(head[0].length) };
557
+ }
558
+ function splitUserinfo(rest, refuse) {
559
+ const totalAt = count(rest, "@");
560
+ if (totalAt === 0) return { userinfo: null, afterUserinfo: rest };
561
+ const rfcEnd = rest.search(/[/?#]/);
562
+ const rfcAt = count(rfcEnd === -1 ? rest : rest.slice(0, rfcEnd), "@");
563
+ const lastAt = rest.lastIndexOf("@");
564
+ const candidate = rest.slice(0, lastAt);
565
+ const agrees = rfcAt === totalAt || rfcAt === 0 && hasCleanUser(candidate);
566
+ if (!agrees) throw refuse(AT_OUTSIDE_USERINFO);
567
+ return { userinfo: candidate, afterUserinfo: rest.slice(lastAt + 1) };
568
+ }
569
+ function hasCleanUser(userinfo) {
570
+ const colon = userinfo.indexOf(":");
571
+ return colon !== -1 && !/[/?#]/.test(userinfo.slice(0, colon));
572
+ }
573
+ function hostPortAndTail(afterUserinfo, hasUserinfo, refuse) {
574
+ const hostEnd = afterUserinfo.search(/[/?#]/);
575
+ const hostPort = hostEnd === -1 ? afterUserinfo : afterUserinfo.slice(0, hostEnd);
576
+ if (/\s/.test(hostPort)) throw refuse("whitespace in the host");
577
+ if (hasUserinfo && hostPort === "") throw refuse("no host after the credentials");
578
+ return { hostPort, tail: afterUserinfo.slice(hostPort.length) };
579
+ }
580
+ function firstHost(hostPort, allowHostList, refuse, nameable) {
581
+ const hosts = allowHostList ? hostPort.split(",") : [hostPort];
582
+ return hosts.map((piece) => oneHost(piece, refuse, nameable))[0];
583
+ }
584
+ function oneHost(piece, refuse, nameable) {
585
+ const split2 = splitHostPort(piece);
586
+ if (split2 === null) throw refuse("a malformed IPv6 host", nameable);
587
+ const [host, port] = split2;
588
+ if (port === null || port === "") return { host, port: null };
589
+ if (!/^\d+$/.test(port)) throw refuse("the port must be numeric", nameable);
590
+ return { host, port: parseInt(port, 10) };
591
+ }
592
+ function refuseDigitLedPassword(userinfo, port, tail, refuse) {
593
+ if (userinfo !== null || port === null) return;
594
+ if (digitLedPassword(tail)) throw refuse("a port followed by a fragment or a query that is not key=value");
595
+ }
596
+ function userinfoParts(userinfo) {
597
+ if (userinfo === null) return { rawUsername: null, rawPassword: null };
598
+ const colon = userinfo.indexOf(":");
599
+ if (colon === -1) return { rawUsername: userinfo, rawPassword: null };
600
+ return { rawUsername: userinfo.slice(0, colon), rawPassword: userinfo.slice(colon + 1) };
601
+ }
602
+ function canonicalConnectionUrl(parts) {
603
+ let auth = "";
604
+ if (parts.userinfo !== null) {
605
+ auth = encodeURIComponent(parts.username ?? "");
606
+ if (parts.password !== null) auth += `:${encodeURIComponent(parts.password)}`;
607
+ auth += "@";
608
+ }
609
+ return `${parts.scheme}://${auth}${parts.hostPort}${parts.tail}`;
610
+ }
611
+ var ConnectionUrlError, count, SCHEME_PREFIX, AT_OUTSIDE_USERINFO, decodeOrNull;
612
+ var init_connectionUrl = __esm({
613
+ "../core/src/connectionUrl.ts"() {
614
+ "use strict";
615
+ init_urlRedaction();
616
+ ConnectionUrlError = class extends Error {
617
+ constructor(message) {
618
+ super(message);
619
+ this.name = "ConnectionUrlError";
620
+ }
621
+ };
622
+ count = (text, ch) => text.split(ch).length - 1;
623
+ SCHEME_PREFIX = /^([A-Za-z][A-Za-z0-9+.-]*):/;
624
+ AT_OUTSIDE_USERINFO = "an @ outside the user:password part - percent-encode it as %40";
625
+ decodeOrNull = (value) => value === null ? null : decodeComponent(value);
626
+ }
627
+ });
628
+
629
+ // src/databaseUrl.ts
630
+ import { inspect } from "node:util";
631
+ function stripOneSlash(path9) {
632
+ return path9.startsWith("/") ? path9.slice(1) : path9;
633
+ }
634
+ function invalidUrlError(raw, engine, why) {
635
+ let hostPort;
636
+ try {
637
+ const parts = splitConnectionUrl(raw, { label: "DatabaseUrl" });
638
+ if (parts.userinfo !== null && parts.hostPort !== "") hostPort = parts.hostPort;
639
+ } catch {
640
+ }
641
+ return new ConnectionUrlError(
642
+ `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.`
643
+ );
644
+ }
645
+ function split(url) {
646
+ return splitConnectionUrl(url, {
647
+ label: "DatabaseUrl",
648
+ expected: "scheme://[user[:password]@]host[:port]/database"
649
+ });
650
+ }
651
+ var ENGINE_ALIASES, DEFAULT_PORTS, DatabaseUrl;
461
652
  var init_databaseUrl = __esm({
462
653
  "src/databaseUrl.ts"() {
463
654
  "use strict";
655
+ init_urlRedaction();
656
+ init_connectionUrl();
464
657
  ENGINE_ALIASES = {
465
658
  sqlite: "sqlite",
466
659
  sqlite3: "sqlite",
@@ -482,8 +675,6 @@ var init_databaseUrl = __esm({
482
675
  firebird: 3050,
483
676
  mongodb: 27017
484
677
  };
485
- REDACTED = "***";
486
- SECRET_KEYWORD_PATTERN = /(^|[;&?\s])(pwd|password|passwd)(\s*=\s*)/gi;
487
678
  DatabaseUrl = class _DatabaseUrl {
488
679
  engine;
489
680
  /** Null for sqlite and odbc - a file or a DSN string has no host. */
@@ -601,13 +792,14 @@ var init_databaseUrl = __esm({
601
792
  if (url.startsWith("odbc:///")) {
602
793
  return { engine: "odbc", connectionString: url.slice("odbc:///".length) };
603
794
  }
604
- if (url.startsWith("mssql://") || url.startsWith("sqlserver://")) {
605
- return _DatabaseUrl.parseRegexForm(url, "mssql", /(?:mssql|sqlserver):\/\/(?:([^:]+):([^@]+)@)?([^:/]+)(?::(\d+))?\/(.*)/);
795
+ const parts = split(url);
796
+ if (parts.scheme === "mssql" || parts.scheme === "sqlserver") {
797
+ return _DatabaseUrl.parsePathForm(url, parts, "mssql");
606
798
  }
607
- if (url.startsWith("firebird://")) {
608
- return _DatabaseUrl.parseRegexForm(url, "firebird", /firebird:\/\/(?:([^:]+):([^@]+)@)?([^:/]+)(?::(\d+))?\/(.*)/);
799
+ if (parts.scheme === "firebird") {
800
+ return _DatabaseUrl.parsePathForm(url, parts, "firebird");
609
801
  }
610
- return _DatabaseUrl.parseStandard(url);
802
+ return _DatabaseUrl.parseStandard(url, parts);
611
803
  }
612
804
  /**
613
805
  * sqlite is parsed on the RAW string. The URL class collapses `sqlite:/x` and
@@ -633,52 +825,62 @@ var init_databaseUrl = __esm({
633
825
  return { engine: "sqlite", database: normalised.slice("sqlite:".length) };
634
826
  }
635
827
  /**
636
- * mssql and firebird: the URL class does not know these schemes, so they are
637
- * matched directly.
828
+ * mssql and firebird: `host[:port]/database`, split by the shared splitter.
638
829
  *
639
- * The captured path keeps its own leading slash when the URL had two, which is
830
+ * These used to be one regex each that split userinfo at the FIRST `@` and
831
+ * the password at the first `/`, so `mssql://u:p@ss@h/db` connected to a host
832
+ * named `ss@h` and printed it in the driver's error.
833
+ *
834
+ * The database keeps its own leading slash when the URL had two, which is
640
835
  * how the documented absolute Firebird form survives. The old code did
641
836
  * `"/" + match[5]`, ADDING a slash - so an absolute path came back with two
642
837
  * and a relative path was silently made absolute. Verified against live
643
838
  * Firebird 5.0.4: the driver takes one or two leading slashes and rejects a
644
839
  * relative path outright.
645
840
  */
646
- static parseRegexForm(url, engine, pattern) {
647
- const m = url.match(pattern);
648
- if (!m) throw invalidUrlError(url, engine);
841
+ static parsePathForm(url, parts, engine) {
842
+ if (parts.host === "" || /[:/]/.test(parts.host) || parts.hostPort.startsWith("[")) {
843
+ throw invalidUrlError(url, engine, "a host is required");
844
+ }
845
+ if (!parts.tail.startsWith("/")) throw invalidUrlError(url, engine, "a /database is required");
649
846
  return {
650
847
  engine,
651
- username: decode(m[1]),
652
- password: decode(m[2]),
653
- host: m[3],
654
- port: m[4] ? parseInt(m[4], 10) : void 0,
655
- database: m[5]
848
+ username: parts.username === "" ? null : parts.username,
849
+ password: parts.password,
850
+ host: parts.host,
851
+ port: parts.port ?? void 0,
852
+ database: parts.tail.slice(1)
656
853
  };
657
854
  }
658
- /** postgres / mysql / mongodb, via the URL class. */
659
- static parseStandard(url) {
660
- let parsed;
661
- try {
662
- parsed = new URL(url);
663
- } catch {
664
- throw invalidUrlError(url);
665
- }
666
- const scheme = parsed.protocol.replace(/:$/, "").toLowerCase();
667
- const engine = ENGINE_ALIASES[scheme];
855
+ /**
856
+ * postgres / mysql / mongodb.
857
+ *
858
+ * Userinfo comes from the shared splitter (the last-`@` rule), never from the
859
+ * URL class: `new URL()` cuts a password at its first `/`, `?` or `#`, reads
860
+ * `postgres:/u:pw@h` as a path, and throws a TypeError whose `.input` is the
861
+ * whole URL. The class only sees a credential-free rebuild, for the host,
862
+ * port and path it already normalises the way every corpus row expects.
863
+ */
864
+ static parseStandard(url, parts) {
865
+ const engine = ENGINE_ALIASES[parts.scheme];
668
866
  if (engine === void 0) {
669
867
  throw new Error(
670
- `DatabaseUrl: Unsupported database scheme '${scheme}'. Supported: ${Object.keys(ENGINE_ALIASES).join(", ")}`
868
+ `DatabaseUrl: Unsupported database scheme '${parts.scheme}'. Supported: ${Object.keys(ENGINE_ALIASES).join(", ")}`
671
869
  );
672
870
  }
871
+ let parsed;
872
+ try {
873
+ parsed = new URL(`${parts.scheme}://${parts.hostPort}${parts.tail}`);
874
+ } catch {
875
+ throw invalidUrlError(url, engine, "the host, port or path is malformed");
876
+ }
673
877
  const database = stripOneSlash(parsed.pathname);
674
- const userinfo = rawUserinfo(url);
675
- const passwordWasWritten = userinfo !== null && userinfo.includes(":");
676
878
  return {
677
879
  engine,
678
880
  host: parsed.hostname || void 0,
679
881
  port: parsed.port ? parseInt(parsed.port, 10) : void 0,
680
- username: decode(parsed.username),
681
- password: passwordWasWritten ? decodeURIComponent(parsed.password) : null,
882
+ username: parts.username === "" ? null : parts.username,
883
+ password: parts.password,
682
884
  database: engine === "mongodb" ? database || "tina4" : database
683
885
  };
684
886
  }
@@ -3545,11 +3747,11 @@ ${s}\r
3545
3747
  return { value: str, next: after + len + 2 };
3546
3748
  }
3547
3749
  case 42: {
3548
- const count = parseInt(line, 10);
3549
- if (count === -1) return { value: null, next: after };
3750
+ const count2 = parseInt(line, 10);
3751
+ if (count2 === -1) return { value: null, next: after };
3550
3752
  const arr = [];
3551
3753
  let pos = after;
3552
- for (let i = 0; i < count; i++) {
3754
+ for (let i = 0; i < count2; i++) {
3553
3755
  const el = _RespClient.parse(buf, pos);
3554
3756
  if (!el) return null;
3555
3757
  arr.push(el.value);
@@ -3850,7 +4052,7 @@ ${s}\r
3850
4052
  }
3851
4053
  async stats() {
3852
4054
  const now = Date.now() / 1e3;
3853
- let count = 0;
4055
+ let count2 = 0;
3854
4056
  try {
3855
4057
  const files = fs.readdirSync(this.dir).filter((f) => f.endsWith(".json"));
3856
4058
  for (const f of files) {
@@ -3859,14 +4061,14 @@ ${s}\r
3859
4061
  if (data.expiresAt && now > data.expiresAt) {
3860
4062
  fs.unlinkSync(path.join(this.dir, f));
3861
4063
  } else {
3862
- count++;
4064
+ count2++;
3863
4065
  }
3864
4066
  } catch {
3865
4067
  }
3866
4068
  }
3867
4069
  } catch {
3868
4070
  }
3869
- return { hits: this.hits, misses: this.misses, size: count, backend: "file" };
4071
+ return { hits: this.hits, misses: this.misses, size: count2, backend: "file" };
3870
4072
  }
3871
4073
  /**
3872
4074
  * Delete expired cache files and count them. `expiresAt > 0` is load-bearing:
@@ -4667,18 +4869,18 @@ var init_router = __esm({
4667
4869
  }
4668
4870
  };
4669
4871
  RouteRef = class {
4872
+ routes;
4670
4873
  constructor(route) {
4671
- this.route = route;
4874
+ this.routes = Array.isArray(route) ? route : [route];
4672
4875
  }
4673
- route;
4674
4876
  /** Mark this route as requiring bearer-token authentication. */
4675
4877
  secure() {
4676
- this.route.secure = true;
4878
+ for (const route of this.routes) route.secure = true;
4677
4879
  return this;
4678
4880
  }
4679
4881
  /** Opt out of secure-by-default auth (for public write routes). */
4680
4882
  noAuth() {
4681
- this.route.noAuth = true;
4883
+ for (const route of this.routes) route.noAuth = true;
4682
4884
  return this;
4683
4885
  }
4684
4886
  /**
@@ -4688,7 +4890,7 @@ var init_router = __esm({
4688
4890
  * (identity) are orthogonal — chain `.noAuth().noCsrf()` for a public webhook.
4689
4891
  */
4690
4892
  noCsrf() {
4691
- this.route.noCsrf = true;
4893
+ for (const route of this.routes) route.noCsrf = true;
4692
4894
  return this;
4693
4895
  }
4694
4896
  /**
@@ -4696,12 +4898,7 @@ var init_router = __esm({
4696
4898
  * claim. Chain .role()/.can() for AND. Implies auth. Feature 138 / ADR-0058.
4697
4899
  */
4698
4900
  role(...names) {
4699
- const clean = names.filter((n) => n !== "");
4700
- if (clean.length > 0) {
4701
- (this.route.requiredRoles ??= []).push(clean);
4702
- this.route.secure = true;
4703
- }
4704
- return this;
4901
+ return this.guard("requiredRoles", names);
4705
4902
  }
4706
4903
  /**
4707
4904
  * RBAC: require ONE of the named permissions (OR). Reads the verified JWT
@@ -4709,16 +4906,26 @@ var init_router = __esm({
4709
4906
  * concrete requirement. Chain for AND. Implies auth. Feature 138.
4710
4907
  */
4711
4908
  can(...permissions) {
4712
- const clean = permissions.filter((p) => p !== "");
4909
+ return this.guard("requiredPerms", permissions);
4910
+ }
4911
+ /**
4912
+ * Add one OR-group of roles or permissions to every route this ref covers,
4913
+ * and secure them (a guard implies auth). Empty names are dropped; a call
4914
+ * with none left changes nothing.
4915
+ */
4916
+ guard(key, names) {
4917
+ const clean = names.filter((n) => n !== "");
4713
4918
  if (clean.length > 0) {
4714
- (this.route.requiredPerms ??= []).push(clean);
4715
- this.route.secure = true;
4919
+ for (const route of this.routes) {
4920
+ (route[key] ??= []).push(clean);
4921
+ route.secure = true;
4922
+ }
4716
4923
  }
4717
4924
  return this;
4718
4925
  }
4719
4926
  /** Mark this route's response as cacheable. */
4720
4927
  cache() {
4721
- this.route.cached = true;
4928
+ for (const route of this.routes) route.cached = true;
4722
4929
  return this;
4723
4930
  }
4724
4931
  /**
@@ -4726,7 +4933,9 @@ var init_router = __esm({
4726
4933
  * string specs (e.g. `"ResponseCache:300"`), resolved when the route runs.
4727
4934
  */
4728
4935
  middleware(...middlewareClasses) {
4729
- this.route.middlewares = [...this.route.middlewares ?? [], ...middlewareClasses];
4936
+ for (const route of this.routes) {
4937
+ route.middlewares = [...route.middlewares ?? [], ...middlewareClasses];
4938
+ }
4730
4939
  return this;
4731
4940
  }
4732
4941
  };
@@ -4758,6 +4967,10 @@ var init_router = __esm({
4758
4967
  * Add a raw route definition (used internally and by file-based routing).
4759
4968
  */
4760
4969
  addRoute(definition) {
4970
+ return new RouteRef(this.registerRoute(definition));
4971
+ }
4972
+ /** Compile and store one route definition; returns the stored route. */
4973
+ registerRoute(definition) {
4761
4974
  const method = definition.method.toUpperCase();
4762
4975
  const { regex, paramNames, paramTypes } = this.compilePattern(definition.pattern);
4763
4976
  if (!this.routes.has(method)) {
@@ -4789,7 +5002,7 @@ var init_router = __esm({
4789
5002
  requiredPerms: definition.requiredPerms
4790
5003
  };
4791
5004
  routes.push(compiled);
4792
- return new RouteRef(compiled);
5005
+ return compiled;
4793
5006
  }
4794
5007
  /**
4795
5008
  * Register a GET route programmatically.
@@ -4843,13 +5056,16 @@ var init_router = __esm({
4843
5056
  }
4844
5057
  /**
4845
5058
  * Register a route that matches ANY HTTP method.
5059
+ *
5060
+ * One route is stored per method; the returned ref covers all of them, so
5061
+ * `any(...).secure()` / `.role()` / `.noAuth()` apply to every method.
4846
5062
  */
4847
5063
  any(path9, handler, middlewares, meta) {
4848
- let lastRef;
5064
+ const compiled = [];
4849
5065
  for (const method of ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"]) {
4850
- lastRef = this.addRoute({ method, pattern: path9, handler, middlewares, meta });
5066
+ compiled.push(this.registerRoute({ method, pattern: path9, handler, middlewares, meta }));
4851
5067
  }
4852
- return lastRef;
5068
+ return new RouteRef(compiled);
4853
5069
  }
4854
5070
  /**
4855
5071
  * Create a route group with a shared prefix and optional middlewares.
@@ -5274,17 +5490,7 @@ var init_router = __esm({
5274
5490
  });
5275
5491
  }
5276
5492
  any(path9, handler, middlewares, meta) {
5277
- let lastRef;
5278
- for (const method of ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"]) {
5279
- lastRef = this.router.addRoute({
5280
- method,
5281
- pattern: joinGroupPath(this.prefix, path9),
5282
- handler,
5283
- middlewares: this.mergeMiddlewares(middlewares),
5284
- meta
5285
- });
5286
- }
5287
- return lastRef;
5493
+ return this.router.any(joinGroupPath(this.prefix, path9), handler, this.mergeMiddlewares(middlewares), meta);
5288
5494
  }
5289
5495
  /**
5290
5496
  * Nested groups.
@@ -6092,9 +6298,9 @@ function splitArithmetic(expr) {
6092
6298
  return null;
6093
6299
  }
6094
6300
  function evalArithmeticExpression(expr, context) {
6095
- const split = splitArithmetic(expr);
6096
- if (!split) return EXPR_NOT_MATCHED;
6097
- const [pos, op] = split;
6301
+ const split2 = splitArithmetic(expr);
6302
+ if (!split2) return EXPR_NOT_MATCHED;
6303
+ const [pos, op] = split2;
6098
6304
  const lVal = evalExpr(expr.slice(0, pos).trim(), context);
6099
6305
  const rVal = evalExpr(expr.slice(pos + op.length).trim(), context);
6100
6306
  let lNum = lVal != null ? Number(lVal) : 0;
@@ -10275,9 +10481,9 @@ function nestFormFields(pairs) {
10275
10481
  return params;
10276
10482
  };
10277
10483
  const tooDeep = (name) => {
10278
- let count = 0;
10484
+ let count2 = 0;
10279
10485
  for (let at = name.indexOf("["); at !== -1; at = name.indexOf("[", at + 1)) {
10280
- if (++count >= FORM_DEPTH_LIMIT) return true;
10486
+ if (++count2 >= FORM_DEPTH_LIMIT) return true;
10281
10487
  }
10282
10488
  return false;
10283
10489
  };
@@ -11394,11 +11600,11 @@ var init_memcachedHandler = __esm({
11394
11600
  const resp = this.command(`get ${this.key(sessionId)}\r
11395
11601
  `, ["END\r\n"]);
11396
11602
  if (!resp.startsWith("VALUE")) return null;
11397
- const split = resp.indexOf("\r\n");
11398
- if (split === -1) return null;
11399
- const header = resp.slice(0, split).split(" ");
11603
+ const split2 = resp.indexOf("\r\n");
11604
+ if (split2 === -1) return null;
11605
+ const header = resp.slice(0, split2).split(" ");
11400
11606
  const bytes = parseInt(header[3] ?? "0", 10);
11401
- const body = Buffer.from(resp.slice(split + 2), "utf-8").subarray(0, bytes).toString("utf-8");
11607
+ const body = Buffer.from(resp.slice(split2 + 2), "utf-8").subarray(0, bytes).toString("utf-8");
11402
11608
  try {
11403
11609
  return JSON.parse(body);
11404
11610
  } catch {
@@ -12027,7 +12233,7 @@ function column(row, name) {
12027
12233
  if (name in row) return row[name];
12028
12234
  return row[name.toUpperCase()];
12029
12235
  }
12030
- function schemeOf2(url) {
12236
+ function schemeOf(url) {
12031
12237
  const match = url.match(/^([a-zA-Z][a-zA-Z0-9+.-]*):/);
12032
12238
  return match ? match[1].toLowerCase() : "unknown";
12033
12239
  }
@@ -12218,7 +12424,7 @@ var init_databaseHandler = __esm({
12218
12424
  process.env.TINA4_DATABASE_PASSWORD
12219
12425
  );
12220
12426
  } catch {
12221
- throw this.unsupportedEngine(schemeOf2(url));
12427
+ throw this.unsupportedEngine(schemeOf(url));
12222
12428
  }
12223
12429
  if (!SQL_SESSION_ENGINES.includes(parsed.engine)) {
12224
12430
  throw this.unsupportedEngine(parsed.engine);
@@ -13959,19 +14165,19 @@ var init_devMailbox = __esm({
13959
14165
  */
13960
14166
  unreadCount() {
13961
14167
  const dir = this.ensureFolder("inbox");
13962
- let count = 0;
14168
+ let count2 = 0;
13963
14169
  try {
13964
14170
  const files = readdirSync4(dir).filter((f) => f.endsWith(".json"));
13965
14171
  for (const file of files) {
13966
14172
  try {
13967
14173
  const msg = JSON.parse(readFileSync9(join12(dir, file), "utf-8"));
13968
- if (!msg.read) count++;
14174
+ if (!msg.read) count2++;
13969
14175
  } catch {
13970
14176
  }
13971
14177
  }
13972
14178
  } catch {
13973
14179
  }
13974
- return count;
14180
+ return count2;
13975
14181
  }
13976
14182
  /**
13977
14183
  * Delete a message by ID. Removes from all folders.
@@ -14012,7 +14218,7 @@ var init_devMailbox = __esm({
14012
14218
  /**
14013
14219
  * Seed the mailbox with sample messages for development.
14014
14220
  */
14015
- seed(count = 5) {
14221
+ seed(count2 = 5) {
14016
14222
  const subjects = [
14017
14223
  "Welcome to Tina4",
14018
14224
  "Your account has been created",
@@ -14032,7 +14238,7 @@ var init_devMailbox = __esm({
14032
14238
  "billing@service.io",
14033
14239
  "alerts@monitoring.dev"
14034
14240
  ];
14035
- for (let i = 0; i < count; i++) {
14241
+ for (let i = 0; i < count2; i++) {
14036
14242
  const subject = subjects[i % subjects.length];
14037
14243
  const from = senders[i % senders.length];
14038
14244
  const date = new Date(Date.now() - i * 36e5).toISOString();
@@ -17551,12 +17757,12 @@ function registerDevTools(server) {
17551
17757
  return { error: "No database connection" };
17552
17758
  }
17553
17759
  if (!adapter) return { error: "No database connection" };
17554
- const count = args.count || 10;
17760
+ const count2 = args.count || 10;
17555
17761
  const fieldMap = await orm.autoFieldMap(adapter, args.table);
17556
17762
  if (!fieldMap || Object.keys(fieldMap).length === 0) {
17557
17763
  return { error: `Table '${args.table}' not found or has no seedable columns` };
17558
17764
  }
17559
- const summary = await orm.seedTable(adapter, args.table, count, fieldMap);
17765
+ const summary = await orm.seedTable(adapter, args.table, count2, fieldMap);
17560
17766
  return { table: args.table, inserted: summary.seeded, failed: summary.failed };
17561
17767
  } catch (e) {
17562
17768
  return { error: e.message };
@@ -17728,7 +17934,7 @@ function registerDevTools(server) {
17728
17934
  let rel = args.path || "";
17729
17935
  const oldStr = args.old_string || "";
17730
17936
  const newStr = args.new_string || "";
17731
- const count = args.count || 1;
17937
+ const count2 = args.count || 1;
17732
17938
  const projectRoot4 = path3.resolve(process.cwd());
17733
17939
  const proseErr = looksLikeProse(rel);
17734
17940
  if (proseErr) {
@@ -17749,13 +17955,13 @@ function registerDevTools(server) {
17749
17955
  let idx = -1;
17750
17956
  while ((idx = original.indexOf(oldStr, idx + 1)) !== -1) occurrences++;
17751
17957
  if (occurrences === 0) return { error: `old_string not found in ${rel}` };
17752
- if (occurrences !== count) {
17958
+ if (occurrences !== count2) {
17753
17959
  return {
17754
- error: `old_string appears ${occurrences} times, expected ${count}. Expand old_string to make it unique, or set count explicitly.`
17960
+ error: `old_string appears ${occurrences} times, expected ${count2}. Expand old_string to make it unique, or set count explicitly.`
17755
17961
  };
17756
17962
  }
17757
17963
  let updated = original;
17758
- for (let i = 0; i < count; i++) updated = updated.replace(oldStr, newStr);
17964
+ for (let i = 0; i < count2; i++) updated = updated.replace(oldStr, newStr);
17759
17965
  const backupRel = agentBackup(projectRoot4, resolved);
17760
17966
  fs4.writeFileSync(resolved, updated, "utf-8");
17761
17967
  try {
@@ -17767,11 +17973,11 @@ function registerDevTools(server) {
17767
17973
  agentLog(
17768
17974
  projectRoot4,
17769
17975
  "patch.ok",
17770
- `${rel} (replaced ${count}\xD7 old_string, ${oldSize}B \u2192 ${newSize}B, backup: ${backupRel || "(none)"})`
17976
+ `${rel} (replaced ${count2}\xD7 old_string, ${oldSize}B \u2192 ${newSize}B, backup: ${backupRel || "(none)"})`
17771
17977
  );
17772
17978
  const result = {
17773
17979
  patched: rel,
17774
- replacements: count,
17980
+ replacements: count2,
17775
17981
  bytes: newSize
17776
17982
  };
17777
17983
  if (backupRel) {
@@ -18981,12 +19187,12 @@ var init_graphql = __esm({
18981
19187
  */
18982
19188
  assertComplexity(selections, fragments) {
18983
19189
  const depthCap = this.maxDepth > 0 ? this.maxDepth : 1e3;
18984
- let count = 0;
19190
+ let count2 = 0;
18985
19191
  const walk2 = (sels, depth) => {
18986
19192
  if (depth > depthCap) return;
18987
19193
  for (const sel of sels) {
18988
- count++;
18989
- if (count > this.maxNodes) {
19194
+ count2++;
19195
+ if (count2 > this.maxNodes) {
18990
19196
  throw new ComplexityError(`Query exceeds maximum complexity of ${this.maxNodes} nodes`);
18991
19197
  }
18992
19198
  if (sel.kind === "fragment_spread") {
@@ -19456,8 +19662,8 @@ var init_graphql = __esm({
19456
19662
 
19457
19663
  // ../core/src/context/chunker.ts
19458
19664
  function fold(text) {
19459
- const split = text.replace(NUM_COMMA, "").replace(CAMEL, " ").toLowerCase();
19460
- return split.normalize("NFKD").replace(/[^\x00-\x7f]/g, "");
19665
+ const split2 = text.replace(NUM_COMMA, "").replace(CAMEL, " ").toLowerCase();
19666
+ return split2.normalize("NFKD").replace(/[^\x00-\x7f]/g, "");
19461
19667
  }
19462
19668
  function lightStem(token) {
19463
19669
  if (token.length > 3 && token.endsWith("s") && !/(?:ss|us|is)$/.test(token)) {
@@ -19893,6 +20099,9 @@ import { randomUUID as randomUUID2 } from "node:crypto";
19893
20099
  function logConnected(backplaneName, url) {
19894
20100
  console.log(`[Tina4] ${backplaneName} connected to ${redactCredentials(url)}`);
19895
20101
  }
20102
+ function driverUrl(backplaneName, url) {
20103
+ return canonicalConnectionUrl(splitConnectionUrl(url, { label: backplaneName, allowHostList: true }));
20104
+ }
19896
20105
  function observeConnectFailure(ready, backplaneName) {
19897
20106
  ready.catch((error2) => {
19898
20107
  console.error(`[Tina4] ${backplaneName} could not connect: ${error2 instanceof Error ? error2.message : String(error2)}`);
@@ -19934,14 +20143,15 @@ var init_websocketBackplane = __esm({
19934
20143
  "../core/src/websocketBackplane.ts"() {
19935
20144
  "use strict";
19936
20145
  init_optionalPackage();
19937
- init_databaseUrl();
20146
+ init_urlRedaction();
20147
+ init_connectionUrl();
19938
20148
  RedisBackplane = class {
19939
20149
  publisher;
19940
20150
  subscriber;
19941
20151
  url;
19942
20152
  ready;
19943
20153
  constructor(url) {
19944
- const resolvedUrl = url ?? process.env.TINA4_WS_BACKPLANE_URL ?? "redis://localhost:6379";
20154
+ const resolvedUrl = driverUrl("RedisBackplane", url ?? process.env.TINA4_WS_BACKPLANE_URL ?? "redis://localhost:6379");
19945
20155
  this.url = resolvedUrl;
19946
20156
  const redisModuleUrl = resolveOptionalPackage("redis", "RedisBackplane");
19947
20157
  this.ready = (async () => {
@@ -19982,7 +20192,7 @@ var init_websocketBackplane = __esm({
19982
20192
  ready;
19983
20193
  natsModuleUrl;
19984
20194
  constructor(url) {
19985
- const resolvedUrl = url ?? process.env.TINA4_WS_BACKPLANE_URL ?? "nats://localhost:4222";
20195
+ const resolvedUrl = driverUrl("NATSBackplane", url ?? process.env.TINA4_WS_BACKPLANE_URL ?? "nats://localhost:4222");
19986
20196
  this.url = resolvedUrl;
19987
20197
  const natsModuleUrl = resolveOptionalPackage("nats", "NATSBackplane");
19988
20198
  this.natsModuleUrl = natsModuleUrl;
@@ -22867,13 +23077,13 @@ var init_liteBackend = __esm({
22867
23077
  }
22868
23078
  return null;
22869
23079
  }
22870
- popBatch(queue, bridge, count) {
23080
+ popBatch(queue, bridge, count2) {
22871
23081
  const dir = this.ensureDir(queue);
22872
23082
  this.reclaimExpired(queue, bridge.getMaxRetries(), this.nowIso());
22873
23083
  const now = this.nowIso();
22874
23084
  const results = [];
22875
23085
  for (const [filename, job] of this.availableCandidates(queue, now)) {
22876
- if (results.length >= count) break;
23086
+ if (results.length >= count2) break;
22877
23087
  const filePath = join19(dir, filename);
22878
23088
  job.topic = queue;
22879
23089
  job.priority = job.priority ?? 0;
@@ -22924,24 +23134,24 @@ var init_liteBackend = __esm({
22924
23134
  if (isDead || isReserved) {
22925
23135
  return files.length;
22926
23136
  }
22927
- let count = 0;
23137
+ let count2 = 0;
22928
23138
  for (const file of files) {
22929
23139
  try {
22930
23140
  const job = JSON.parse(readFileSync14(join19(scanDir, file), "utf-8"));
22931
- if (job.status === status2) count++;
23141
+ if (job.status === status2) count2++;
22932
23142
  } catch {
22933
23143
  }
22934
23144
  }
22935
- return count;
23145
+ return count2;
22936
23146
  }
22937
23147
  clear(queue) {
22938
23148
  const dir = this.ensureDir(queue);
22939
- let count = 0;
23149
+ let count2 = 0;
22940
23150
  try {
22941
23151
  const files = readdirSync9(dir).filter((f) => f.endsWith(".queue-data"));
22942
23152
  for (const file of files) {
22943
23153
  unlinkSync7(join19(dir, file));
22944
- count++;
23154
+ count2++;
22945
23155
  }
22946
23156
  } catch {
22947
23157
  }
@@ -22951,7 +23161,7 @@ var init_liteBackend = __esm({
22951
23161
  const files = readdirSync9(failedDir).filter((f) => f.endsWith(".queue-data"));
22952
23162
  for (const file of files) {
22953
23163
  unlinkSync7(join19(failedDir, file));
22954
- count++;
23164
+ count2++;
22955
23165
  }
22956
23166
  }
22957
23167
  } catch {
@@ -22962,12 +23172,12 @@ var init_liteBackend = __esm({
22962
23172
  const files = readdirSync9(reservedDir).filter((f) => f.endsWith(".queue-data"));
22963
23173
  for (const file of files) {
22964
23174
  unlinkSync7(join19(reservedDir, file));
22965
- count++;
23175
+ count2++;
22966
23176
  }
22967
23177
  }
22968
23178
  } catch {
22969
23179
  }
22970
- return count;
23180
+ return count2;
22971
23181
  }
22972
23182
  /**
22973
23183
  * Jobs that have failed at least once but are still being retried.
@@ -23047,7 +23257,7 @@ var init_liteBackend = __esm({
23047
23257
  return results;
23048
23258
  }
23049
23259
  purge(queue, status2, maxRetries = 3) {
23050
- let count = 0;
23260
+ let count2 = 0;
23051
23261
  const isDead = _LiteBackend.DEAD_STATES.includes(status2);
23052
23262
  if (isDead) {
23053
23263
  const failedDir = this.ensureFailedDir(queue);
@@ -23056,7 +23266,7 @@ var init_liteBackend = __esm({
23056
23266
  for (const file of files) {
23057
23267
  try {
23058
23268
  unlinkSync7(join19(failedDir, file));
23059
- count++;
23269
+ count2++;
23060
23270
  } catch {
23061
23271
  }
23062
23272
  }
@@ -23071,7 +23281,7 @@ var init_liteBackend = __esm({
23071
23281
  const job = JSON.parse(readFileSync14(join19(dir, file), "utf-8"));
23072
23282
  if (job.status === status2) {
23073
23283
  unlinkSync7(join19(dir, file));
23074
- count++;
23284
+ count2++;
23075
23285
  }
23076
23286
  } catch {
23077
23287
  }
@@ -23079,7 +23289,7 @@ var init_liteBackend = __esm({
23079
23289
  } catch {
23080
23290
  }
23081
23291
  }
23082
- return count;
23292
+ return count2;
23083
23293
  }
23084
23294
  /**
23085
23295
  * Re-queue dead-letter jobs that are under the (possibly raised) limit back
@@ -23089,7 +23299,7 @@ var init_liteBackend = __esm({
23089
23299
  retryFailed(queue, maxRetries = 3) {
23090
23300
  const failedDir = this.ensureFailedDir(queue);
23091
23301
  const queueDir = this.ensureDir(queue);
23092
- let count = 0;
23302
+ let count2 = 0;
23093
23303
  try {
23094
23304
  const files = readdirSync9(failedDir).filter((f) => f.endsWith(".queue-data"));
23095
23305
  for (const file of files) {
@@ -23106,13 +23316,13 @@ var init_liteBackend = __esm({
23106
23316
  const prefix = this.nextPrefix();
23107
23317
  writeFileSync9(join19(queueDir, `${prefix}_${job.id}.queue-data`), JSON.stringify(job, null, 2));
23108
23318
  unlinkSync7(filePath);
23109
- count++;
23319
+ count2++;
23110
23320
  } catch {
23111
23321
  }
23112
23322
  }
23113
23323
  } catch {
23114
23324
  }
23115
- return count;
23325
+ return count2;
23116
23326
  }
23117
23327
  popById(queue, id) {
23118
23328
  const dir = this.ensureDir(queue);
@@ -23384,17 +23594,17 @@ var init_queue = __esm({
23384
23594
  /**
23385
23595
  * Pop up to count jobs at once. Returns a partial batch if fewer available.
23386
23596
  */
23387
- popBatch(count) {
23597
+ popBatch(count2) {
23388
23598
  if (this.externalBackend) {
23389
23599
  const jobs = [];
23390
- for (let i = 0; i < count; i++) {
23600
+ for (let i = 0; i < count2; i++) {
23391
23601
  const job = this.pop();
23392
23602
  if (!job) break;
23393
23603
  jobs.push(job);
23394
23604
  }
23395
23605
  return jobs;
23396
23606
  }
23397
- return this.liteBackend.popBatch(this.topic, this, count);
23607
+ return this.liteBackend.popBatch(this.topic, this, count2);
23398
23608
  }
23399
23609
  /**
23400
23610
  * Process jobs from a queue with a handler function.
@@ -26122,12 +26332,12 @@ function quoteTableRef(name) {
26122
26332
  function parseSeedRequest(url, body) {
26123
26333
  const b = body ?? {};
26124
26334
  const table2 = String(url.searchParams.get("table") ?? b.table ?? "");
26125
- const count = parseInt(String(url.searchParams.get("count") ?? b.count ?? "10"), 10) || 10;
26335
+ const count2 = parseInt(String(url.searchParams.get("count") ?? b.count ?? "10"), 10) || 10;
26126
26336
  const seedRaw = url.searchParams.get("seed") ?? b.seed;
26127
26337
  const seed = seedRaw !== void 0 && seedRaw !== null && String(seedRaw) !== "" ? Number.isNaN(parseInt(String(seedRaw), 10)) ? void 0 : parseInt(String(seedRaw), 10) : void 0;
26128
26338
  const clear = String(url.searchParams.get("clear") ?? b.clear ?? "") === "true" || b.clear === true;
26129
26339
  const strict = String(url.searchParams.get("strict") ?? b.strict ?? "") === "true" || b.strict === true;
26130
- return { table: table2, count, seed, clear, strict };
26340
+ return { table: table2, count: count2, seed, clear, strict };
26131
26341
  }
26132
26342
  function buildSeedFieldMap(columns, fake) {
26133
26343
  const rules = [
@@ -26296,6 +26506,11 @@ function parseEnvFile() {
26296
26506
  }
26297
26507
  return result;
26298
26508
  }
26509
+ function savedUrlIfRedacted(posted) {
26510
+ const current = parseEnvFile().TINA4_DATABASE_URL ?? "";
26511
+ if (posted === "" || current === "" || posted === current) return posted;
26512
+ return posted === redactCredentials(current) ? current : posted;
26513
+ }
26299
26514
  function walkDirRecursive(dir) {
26300
26515
  const results = [];
26301
26516
  if (!existsSync21(dir)) return results;
@@ -26725,6 +26940,7 @@ var init_devAdmin = __esm({
26725
26940
  init_feedback();
26726
26941
  init_mcp();
26727
26942
  init_version();
26943
+ init_urlRedaction();
26728
26944
  cpuCount = osCpus().length;
26729
26945
  DEV_MCP_PREFIXES = ["/__dev/api/mcp", "/__dev/mcp"];
26730
26946
  DEV_PUBLIC_ASSETS = /* @__PURE__ */ new Set(["/__dev/toolbar.css", "/__dev/toolbar.js"]);
@@ -26913,8 +27129,8 @@ var init_devAdmin = __esm({
26913
27129
  static read(id) {
26914
27130
  return this.mailbox.read(id);
26915
27131
  }
26916
- static seed(count = 5) {
26917
- this.mailbox.seed(count);
27132
+ static seed(count2 = 5) {
27133
+ this.mailbox.seed(count2);
26918
27134
  }
26919
27135
  static clear(folder) {
26920
27136
  this.mailbox.clear(folder);
@@ -26947,15 +27163,15 @@ var init_devAdmin = __esm({
26947
27163
  return job;
26948
27164
  }
26949
27165
  static retryFailed() {
26950
- let count = 0;
27166
+ let count2 = 0;
26951
27167
  for (const job of this.jobs) {
26952
27168
  if (job.status === "failed") {
26953
27169
  job.status = "pending";
26954
27170
  job.error = void 0;
26955
- count++;
27171
+ count2++;
26956
27172
  }
26957
27173
  }
26958
- return count;
27174
+ return count2;
26959
27175
  }
26960
27176
  static purgeCompleted() {
26961
27177
  const before = this.jobs.length;
@@ -27462,12 +27678,12 @@ var init_devAdmin = __esm({
27462
27678
  }
27463
27679
  };
27464
27680
  handleQueueRetry = (_req, res) => {
27465
- const count = DevQueue.retryFailed();
27466
- res.json({ retried: count });
27681
+ const count2 = DevQueue.retryFailed();
27682
+ res.json({ retried: count2 });
27467
27683
  };
27468
27684
  handleQueuePurge = (_req, res) => {
27469
- const count = DevQueue.purgeCompleted();
27470
- res.json({ purged: count });
27685
+ const count2 = DevQueue.purgeCompleted();
27686
+ res.json({ purged: count2 });
27471
27687
  };
27472
27688
  handleQueueReplay = (req2, res) => {
27473
27689
  const url = new URL(req2.url ?? "/", "http://localhost");
@@ -27503,9 +27719,9 @@ var init_devAdmin = __esm({
27503
27719
  };
27504
27720
  handleMailboxSeed = (req2, res) => {
27505
27721
  const url = new URL(req2.url ?? "/", "http://localhost");
27506
- const count = parseInt(url.searchParams.get("count") ?? "5", 10);
27507
- DevMailboxStore.seed(count);
27508
- res.json({ seeded: count });
27722
+ const count2 = parseInt(url.searchParams.get("count") ?? "5", 10);
27723
+ DevMailboxStore.seed(count2);
27724
+ res.json({ seeded: count2 });
27509
27725
  };
27510
27726
  handleMailboxClear = (req2, res) => {
27511
27727
  const url = new URL(req2.url ?? "/", "http://localhost");
@@ -27556,7 +27772,7 @@ var init_devAdmin = __esm({
27556
27772
  };
27557
27773
  handleSeed = async (req2, res) => {
27558
27774
  const url = new URL(req2.url ?? "/", "http://localhost");
27559
- const { table: table2, count, seed, clear, strict } = parseSeedRequest(url, req2.body);
27775
+ const { table: table2, count: count2, seed, clear, strict } = parseSeedRequest(url, req2.body);
27560
27776
  if (!table2) {
27561
27777
  res.json({ error: "Missing table parameter" });
27562
27778
  return;
@@ -27572,7 +27788,7 @@ var init_devAdmin = __esm({
27572
27788
  return;
27573
27789
  }
27574
27790
  const fieldMap = buildSeedFieldMap(columns, fake);
27575
- const summary = await seedTable2(db, table2, count, fieldMap, void 0, { clear, strict });
27791
+ const summary = await seedTable2(db, table2, count2, fieldMap, void 0, { clear, strict });
27576
27792
  res.json({ seeded: summary.seeded, failed: summary.failed, errors: summary.errors, table: table2 });
27577
27793
  } catch (e) {
27578
27794
  res.json({ error: e?.message ?? "Database not connected" });
@@ -27719,7 +27935,7 @@ var init_devAdmin = __esm({
27719
27935
  };
27720
27936
  handleSeedRun = async (req2, res) => {
27721
27937
  const body = req2.body || {};
27722
- const count = parseInt(String(body.count ?? "10"), 10) || 10;
27938
+ const count2 = parseInt(String(body.count ?? "10"), 10) || 10;
27723
27939
  try {
27724
27940
  const orm = await Promise.resolve().then(() => (init_index(), index_exports));
27725
27941
  const dirs = ["src/orm", "src/models"].map((d) => resolve12(process.cwd(), d)).filter((d) => existsSync21(d));
@@ -27731,7 +27947,7 @@ var init_devAdmin = __esm({
27731
27947
  res.json({ ok: false, error: "No models found in src/orm/ or src/models/" }, 400);
27732
27948
  return;
27733
27949
  }
27734
- const summaries = await orm.seedModels(classes, count);
27950
+ const summaries = await orm.seedModels(classes, count2);
27735
27951
  let seeded = 0, failed = 0;
27736
27952
  for (const s of Object.values(summaries)) {
27737
27953
  seeded += s.seeded;
@@ -27797,14 +28013,17 @@ var init_devAdmin = __esm({
27797
28013
  handleConnections = (_req, res) => {
27798
28014
  const env = parseEnvFile();
27799
28015
  res.json({
27800
- url: env.TINA4_DATABASE_URL ?? "",
28016
+ // Redacted like the password field below: this used to hand the raw .env
28017
+ // URL - password and all - to any page that could reach the dev API
28018
+ // (GHSA-h2mr-m3v3-cq8c). Save recognises this form and keeps the real URL.
28019
+ url: redactCredentials(env.TINA4_DATABASE_URL ?? ""),
27801
28020
  username: env.TINA4_DATABASE_USERNAME ?? "",
27802
28021
  password: env.TINA4_DATABASE_PASSWORD ? "***" : ""
27803
28022
  });
27804
28023
  };
27805
28024
  handleConnectionsTest = async (req2, res) => {
27806
28025
  const body = req2.body;
27807
- const url = body?.url ?? "";
28026
+ const url = savedUrlIfRedacted(body?.url ?? "");
27808
28027
  const username = body?.username ?? "";
27809
28028
  const password = body?.password ?? "";
27810
28029
  if (!url) {
@@ -27855,7 +28074,7 @@ var init_devAdmin = __esm({
27855
28074
  };
27856
28075
  handleConnectionsSave = (req2, res) => {
27857
28076
  const body = req2.body;
27858
- const url = body?.url ?? "";
28077
+ const url = savedUrlIfRedacted(body?.url ?? "");
27859
28078
  const username = body?.username ?? "";
27860
28079
  const password = body?.password ?? "";
27861
28080
  if (!url) {
@@ -30306,6 +30525,9 @@ function shutdownTimeoutSeconds() {
30306
30525
  }
30307
30526
  return parsed;
30308
30527
  }
30528
+ function shutdownSignals(platform = process.platform) {
30529
+ return platform === "win32" ? ["SIGTERM", "SIGINT", "SIGBREAK"] : ["SIGTERM", "SIGINT"];
30530
+ }
30309
30531
  function bannerSurfaceLines(port, opts) {
30310
30532
  return [
30311
30533
  opts.swaggerEnabled ? `
@@ -30323,7 +30545,7 @@ function swaggerAdvertised() {
30323
30545
  return TRUTHY3.includes(raw);
30324
30546
  }
30325
30547
  function stripUrlCredentials(text) {
30326
- return text.replace(/:\/\/[^/\s]*@/g, "://");
30548
+ return stripCredentials(text);
30327
30549
  }
30328
30550
  function isModuleNotFound(err) {
30329
30551
  const code = err?.code;
@@ -31593,21 +31815,19 @@ ${reset2}
31593
31815
  }
31594
31816
  process.exit(0);
31595
31817
  };
31596
- const onSigterm = () => {
31597
- void gracefulShutdown("SIGTERM").catch(() => process.exit(0));
31598
- };
31599
- const onSigint = () => {
31600
- void gracefulShutdown("SIGINT").catch(() => process.exit(0));
31601
- };
31602
- process.on("SIGTERM", onSigterm);
31603
- process.on("SIGINT", onSigint);
31818
+ const signalListeners = shutdownSignals().map((signal) => ({
31819
+ signal,
31820
+ listener: () => {
31821
+ void gracefulShutdown(signal).catch(() => process.exit(0));
31822
+ }
31823
+ }));
31824
+ signalListeners.forEach(({ signal, listener }) => process.on(signal, listener));
31604
31825
  await startAllTcpServices(host);
31605
31826
  const loopWatchdog = startLoopWatchdog();
31606
31827
  resolvePromise({
31607
31828
  close: () => {
31608
31829
  loopWatchdog.stop();
31609
- process.off("SIGTERM", onSigterm);
31610
- process.off("SIGINT", onSigint);
31830
+ signalListeners.forEach(({ signal, listener }) => process.off(signal, listener));
31611
31831
  stopAllBackgroundTasks();
31612
31832
  stopAcceptingAllTcpServices();
31613
31833
  void drainAllTcpServices();
@@ -31744,6 +31964,7 @@ var init_server = __esm({
31744
31964
  init_background();
31745
31965
  init_tcp();
31746
31966
  init_version();
31967
+ init_urlRedaction();
31747
31968
  __filename = fileURLToPath8(import.meta.url);
31748
31969
  __dirname = dirname12(__filename);
31749
31970
  BUILTIN_ERROR_TEMPLATES_DIR = resolve15(__dirname, "..", "templates");
@@ -31909,8 +32130,18 @@ var init_env = __esm({
31909
32130
  // ../core/src/fakeData.ts
31910
32131
  import { randomInt, randomUUID as randomUUID7 } from "node:crypto";
31911
32132
  import { existsSync as existsSync25, readdirSync as readdirSync16 } from "node:fs";
31912
- import { resolve as resolve16, join as join27 } from "node:path";
32133
+ import { resolve as resolve16, join as join27, basename as basename6 } from "node:path";
31913
32134
  import { pathToFileURL as pathToFileURL2 } from "node:url";
32135
+ function errorText(error2) {
32136
+ return error2 instanceof Error ? error2.message : String(error2);
32137
+ }
32138
+ function isSeedFile(name) {
32139
+ return (name.endsWith(".ts") || name.endsWith(".js")) && !name.startsWith("_");
32140
+ }
32141
+ function seedEntry(mod) {
32142
+ const entry = typeof mod.default === "function" ? mod.default : mod.run;
32143
+ return typeof entry === "function" ? entry : void 0;
32144
+ }
31914
32145
  function mulberry32(seed) {
31915
32146
  let s = seed | 0;
31916
32147
  return () => {
@@ -31920,10 +32151,21 @@ function mulberry32(seed) {
31920
32151
  return ((t ^ t >>> 14) >>> 0) / 4294967296;
31921
32152
  };
31922
32153
  }
31923
- var FIRST_NAMES, LAST_NAMES, DOMAINS, WORDS, CITIES, COUNTRIES, STREETS, JOB_TITLES, CURRENCIES, PRODUCT_ADJECTIVES, PRODUCT_NOUNS, FakeData;
32154
+ var SeedError, FIRST_NAMES, LAST_NAMES, DOMAINS, WORDS, CITIES, COUNTRIES, STREETS, JOB_TITLES, CURRENCIES, PRODUCT_ADJECTIVES, PRODUCT_NOUNS, FakeData;
31924
32155
  var init_fakeData = __esm({
31925
32156
  "../core/src/fakeData.ts"() {
31926
32157
  "use strict";
32158
+ init_logger();
32159
+ SeedError = class extends Error {
32160
+ seedFile;
32161
+ completed;
32162
+ constructor(seedFile, completed, cause) {
32163
+ super(`Seed file failed: ${basename6(seedFile)}: ${errorText(cause)}`, { cause });
32164
+ this.name = "SeedError";
32165
+ this.seedFile = seedFile;
32166
+ this.completed = [...completed];
32167
+ }
32168
+ };
31927
32169
  FIRST_NAMES = [
31928
32170
  "Alice",
31929
32171
  "Bob",
@@ -32403,33 +32645,37 @@ var init_fakeData = __esm({
32403
32645
  return items[this.randInt(0, items.length)];
32404
32646
  }
32405
32647
  /**
32406
- * Run seed files from a directory. Each file should export a default async function.
32407
- * Returns an array of executed file paths.
32648
+ * Run the seed files in a directory in name order, skipping files whose name
32649
+ * starts with "_". A file's default export, or else the named run() that
32650
+ * `generate seeder` writes, is awaited when it is a function.
32651
+ * Returns the executed file paths in order ([] when the directory is missing).
32652
+ * A seed file that throws stops the run: it is logged and a SeedError naming
32653
+ * it is thrown, and no later file runs (ADR-0108).
32408
32654
  */
32409
32655
  async seedDir(seedDir) {
32410
32656
  const dir = resolve16(seedDir ?? "src/seeds");
32411
32657
  if (!existsSync25(dir)) return [];
32412
- const files = readdirSync16(dir).filter((f) => f.endsWith(".ts") || f.endsWith(".js")).sort();
32658
+ const files = readdirSync16(dir).filter(isSeedFile).sort();
32413
32659
  const executed = [];
32414
32660
  for (const file of files) {
32415
32661
  const fullPath = join27(dir, file);
32416
32662
  try {
32417
32663
  const mod = await import(pathToFileURL2(fullPath).href);
32418
- if (typeof mod.default === "function") {
32419
- await mod.default();
32420
- }
32421
- executed.push(fullPath);
32422
- } catch {
32664
+ await seedEntry(mod)?.();
32665
+ } catch (error2) {
32666
+ Log.error(`Seeder: ${file} failed, seeding stopped: ${errorText(error2)}`);
32667
+ throw new SeedError(fullPath, executed, error2);
32423
32668
  }
32669
+ executed.push(fullPath);
32424
32670
  }
32425
32671
  return executed;
32426
32672
  }
32427
32673
  /**
32428
32674
  * Run a generator function `count` times and return the results.
32429
32675
  */
32430
- run(fn, count = 1) {
32676
+ run(fn, count2 = 1) {
32431
32677
  const results = [];
32432
- for (let i = 0; i < count; i++) {
32678
+ for (let i = 0; i < count2; i++) {
32433
32679
  results.push(fn());
32434
32680
  }
32435
32681
  return results;
@@ -32527,6 +32773,7 @@ var init_mqtt = __esm({
32527
32773
  init_logger();
32528
32774
  init_background();
32529
32775
  init_mqttMessage();
32776
+ init_connectionUrl();
32530
32777
  MqttError = class extends Error {
32531
32778
  constructor(message) {
32532
32779
  super(message);
@@ -32632,59 +32879,34 @@ var init_mqtt = __esm({
32632
32879
  if (raw === "") {
32633
32880
  throw new Error(`MQTT url is empty -- set TINA4_MQTT_URL (e.g. ${DEFAULT_URL})`);
32634
32881
  }
32635
- let scheme = null;
32636
- let rest = raw;
32637
32882
  const schemeMatch = raw.match(/^([A-Za-z][A-Za-z0-9+.-]*):\/\//);
32883
+ let target = raw;
32638
32884
  if (schemeMatch) {
32639
- scheme = schemeMatch[1].toLowerCase();
32885
+ const scheme = schemeMatch[1].toLowerCase();
32640
32886
  if (!["mqtt", "tcp", "mqtts"].includes(scheme)) {
32641
32887
  throw new Error(
32642
- `unsupported MQTT url scheme '${scheme}' in '${raw}' -- this client speaks mqtt://, tcp:// or mqtts:// (TLS). WebSocket transports are not implemented.`
32888
+ `unsupported MQTT url scheme '${scheme}' -- this client speaks mqtt://, tcp:// or mqtts:// (TLS). WebSocket transports are not implemented.`
32643
32889
  );
32644
32890
  }
32645
- rest = raw.slice(schemeMatch[0].length);
32646
- }
32647
- const tlsFlag = scheme === "mqtts";
32648
- let username = null;
32649
- let password = null;
32650
- const atPos = rest.lastIndexOf("@");
32651
- if (atPos !== -1) {
32652
- const userinfo = rest.slice(0, atPos);
32653
- rest = rest.slice(atPos + 1);
32654
- const colon = userinfo.indexOf(":");
32655
- if (colon === -1) {
32656
- username = _Mqtt.percentDecode(userinfo);
32657
- } else {
32658
- username = _Mqtt.percentDecode(userinfo.slice(0, colon));
32659
- password = _Mqtt.percentDecode(userinfo.slice(colon + 1));
32660
- }
32661
- }
32662
- const hostPort = rest.split("/", 1)[0];
32663
- let host = hostPort;
32664
- let portStr = null;
32665
- if (hostPort.startsWith("[")) {
32666
- const close = hostPort.indexOf("]");
32667
- if (close === -1) throw new Error(`malformed MQTT url '${raw}' -- unclosed IPv6 bracket`);
32668
- host = hostPort.slice(1, close);
32669
- const after = hostPort.slice(close + 1);
32670
- if (after.startsWith(":")) portStr = after.slice(1);
32671
- } else {
32672
- const colon = hostPort.indexOf(":");
32673
- if (colon !== -1) {
32674
- host = hostPort.slice(0, colon);
32675
- portStr = hostPort.slice(colon + 1);
32676
- }
32891
+ } else if (/^(\[[^\]\s]*\]|[^\s:/@?#[\]]+)(:\d*)?$/.test(raw)) {
32892
+ target = `mqtt://${raw}`;
32893
+ }
32894
+ let parts;
32895
+ try {
32896
+ parts = splitConnectionUrl(target, { label: "Mqtt", expected: "mqtt://[user[:password]@]host[:port]" });
32897
+ } catch (err) {
32898
+ throw new MqttError(`malformed MQTT url -- ${err.message.replace(/^Mqtt: /, "")}`);
32677
32899
  }
32678
- if (host === "") throw new Error(`malformed MQTT url '${raw}' -- expected mqtt://host:port`);
32679
- if (portStr !== null && portStr !== "" && !/^\d+$/.test(portStr)) {
32680
- throw new Error(`malformed MQTT url '${raw}' -- port must be numeric`);
32900
+ if (parts.host === "") {
32901
+ throw new MqttError("malformed MQTT url -- expected mqtt://host:port. The url is not shown because it may contain a password.");
32681
32902
  }
32903
+ const tlsFlag = parts.scheme === "mqtts";
32682
32904
  return {
32683
- host,
32684
- port: portStr !== null && portStr !== "" ? parseInt(portStr, 10) : tlsFlag ? DEFAULT_TLS_PORT : DEFAULT_PORT,
32905
+ host: parts.host,
32906
+ port: parts.port !== null ? parts.port : tlsFlag ? DEFAULT_TLS_PORT : DEFAULT_PORT,
32685
32907
  tls: tlsFlag,
32686
- username: username !== null && username !== "" ? username : null,
32687
- password
32908
+ username: parts.rawUsername !== null && parts.rawUsername !== "" ? _Mqtt.percentDecode(parts.rawUsername) : null,
32909
+ password: parts.rawPassword !== null ? _Mqtt.percentDecode(parts.rawPassword) : null
32688
32910
  };
32689
32911
  }
32690
32912
  /**
@@ -33721,7 +33943,7 @@ import https from "node:https";
33721
33943
  import { URL as URL2 } from "node:url";
33722
33944
  import { randomBytes as randomBytes9 } from "node:crypto";
33723
33945
  import { promises as fsp, createWriteStream } from "node:fs";
33724
- import { basename as basename6 } from "node:path";
33946
+ import { basename as basename7 } from "node:path";
33725
33947
  import { pipeline } from "node:stream/promises";
33726
33948
  function keepCrossOriginHeaders(headers) {
33727
33949
  const out = {};
@@ -34122,7 +34344,7 @@ var init_api = __esm({
34122
34344
  error: err instanceof Error ? err.message : String(err)
34123
34345
  };
34124
34346
  }
34125
- uploadName = filename || basename6(filePath);
34347
+ uploadName = filename || basename7(filePath);
34126
34348
  } else {
34127
34349
  return { http_code: null, body: null, headers: {}, error: "upload requires filePath or fileBytes" };
34128
34350
  }
@@ -34633,7 +34855,7 @@ var init_api = __esm({
34633
34855
  import net4 from "node:net";
34634
34856
  import tls2 from "node:tls";
34635
34857
  import { readFileSync as readFileSync23 } from "node:fs";
34636
- import { basename as basename7 } from "node:path";
34858
+ import { basename as basename8 } from "node:path";
34637
34859
  import { randomUUID as randomUUID8 } from "node:crypto";
34638
34860
  function normaliseEncryption(value, kind) {
34639
34861
  const normalised = value.trim().toLowerCase();
@@ -34796,7 +35018,7 @@ function buildMimeMessage(options) {
34796
35018
  lines.push(options.body);
34797
35019
  }
34798
35020
  for (const filePath of options.attachments) {
34799
- const fileName = basename7(filePath);
35021
+ const fileName = basename8(filePath);
34800
35022
  const fileData = readFileSync23(filePath);
34801
35023
  const base64Data = fileData.toString("base64");
34802
35024
  lines.push("");
@@ -38109,26 +38331,25 @@ var init_aiClient = __esm({
38109
38331
  // ../core/src/queueBackends/rabbitmqBackend.ts
38110
38332
  import { execFileSync as execFileSync4 } from "node:child_process";
38111
38333
  import { randomUUID as randomUUID9 } from "node:crypto";
38334
+ function amqpTarget(url) {
38335
+ return /^[A-Za-z][A-Za-z0-9+.-]*(:\/|\/\/)|[@\s]/.test(url) ? url : `amqp://${url}`;
38336
+ }
38337
+ function amqpCredentials(username, password) {
38338
+ const creds = {};
38339
+ if (username !== null) creds.username = username;
38340
+ if (password !== null) creds.password = password;
38341
+ return creds;
38342
+ }
38112
38343
  function parseAmqpUrl(url) {
38113
38344
  const config = {};
38114
- let rest = url.replace(/^amqps:\/\//, "").replace(/^amqp:\/\//, "");
38115
- const atIndex = rest.indexOf("@");
38116
- if (atIndex !== -1) {
38117
- const creds = rest.slice(0, atIndex);
38118
- rest = rest.slice(atIndex + 1);
38119
- const colonIndex = creds.indexOf(":");
38120
- if (colonIndex !== -1) {
38121
- config.username = creds.slice(0, colonIndex);
38122
- config.password = creds.slice(colonIndex + 1);
38123
- } else {
38124
- config.username = creds;
38125
- }
38126
- }
38127
- let hostport = rest;
38128
- const slashIndex = rest.indexOf("/");
38129
- if (slashIndex !== -1) {
38130
- hostport = rest.slice(0, slashIndex);
38131
- const vhost = rest.slice(slashIndex + 1);
38345
+ const parts = splitConnectionUrl(amqpTarget(url), {
38346
+ label: "parseAmqpUrl",
38347
+ expected: "amqp://[user[:password]@]host[:port][/vhost]"
38348
+ });
38349
+ Object.assign(config, amqpCredentials(parts.rawUsername, parts.rawPassword));
38350
+ const hostport = parts.hostPort;
38351
+ if (parts.tail.startsWith("/")) {
38352
+ const vhost = parts.tail.slice(1);
38132
38353
  if (vhost) {
38133
38354
  config.vhost = decodeURIComponent(vhost);
38134
38355
  }
@@ -38146,6 +38367,7 @@ var AMQP_PROTOCOL_HEADER, CONNECTION_START, CONNECTION_START_OK, CONNECTION_TUNE
38146
38367
  var init_rabbitmqBackend = __esm({
38147
38368
  "../core/src/queueBackends/rabbitmqBackend.ts"() {
38148
38369
  "use strict";
38370
+ init_connectionUrl();
38149
38371
  AMQP_PROTOCOL_HEADER = Buffer.from([65, 77, 81, 80, 0, 0, 9, 1]);
38150
38372
  CONNECTION_START = 10 << 16 | 10;
38151
38373
  CONNECTION_START_OK = 10 << 16 | 11;
@@ -39424,6 +39646,7 @@ __export(src_exports2, {
39424
39646
  SSO: () => Sso,
39425
39647
  SafeString: () => SafeString2,
39426
39648
  SecurityHeadersMiddleware: () => SecurityHeadersMiddleware,
39649
+ SeedError: () => SeedError,
39427
39650
  ServiceRunner: () => ServiceRunner,
39428
39651
  Session: () => Session,
39429
39652
  Sso: () => Sso,
@@ -44241,7 +44464,9 @@ async function buildAdapterFromUrl(url, username, password) {
44241
44464
  }
44242
44465
  case "mongodb": {
44243
44466
  const { MongodbAdapter: MongodbAdapter2 } = await Promise.resolve().then(() => (init_mongodb(), mongodb_exports));
44244
- const adapter = new MongodbAdapter2(url);
44467
+ const adapter = new MongodbAdapter2(
44468
+ canonicalConnectionUrl(splitConnectionUrl(url, { label: "DatabaseUrl", allowHostList: true }))
44469
+ );
44245
44470
  await adapter.connect();
44246
44471
  return adapter;
44247
44472
  }
@@ -44380,6 +44605,7 @@ var init_database = __esm({
44380
44605
  "use strict";
44381
44606
  init_databaseResult();
44382
44607
  init_databaseUrl();
44608
+ init_connectionUrl();
44383
44609
  init_cachedDatabase();
44384
44610
  init_sqlTranslator();
44385
44611
  init_sqlDialect();
@@ -47714,8 +47940,8 @@ var init_queryBuilder = __esm({
47714
47940
  * @param offset - Number of rows to skip.
47715
47941
  * @returns this for chaining.
47716
47942
  */
47717
- limit(count, offset) {
47718
- this.limitVal = count;
47943
+ limit(count2, offset) {
47944
+ this.limitVal = count2;
47719
47945
  if (offset !== void 0) {
47720
47946
  this.offsetVal = offset;
47721
47947
  }
@@ -47731,8 +47957,8 @@ var init_queryBuilder = __esm({
47731
47957
  * @param count - Number of rows to skip.
47732
47958
  * @returns this for chaining.
47733
47959
  */
47734
- offset(count) {
47735
- this.offsetVal = count;
47960
+ offset(count2) {
47961
+ this.offsetVal = count2;
47736
47962
  return this;
47737
47963
  }
47738
47964
  /**
@@ -47744,8 +47970,8 @@ var init_queryBuilder = __esm({
47744
47970
  * @param count - Number of rows to skip.
47745
47971
  * @returns this for chaining.
47746
47972
  */
47747
- skip(count) {
47748
- return this.offset(count);
47973
+ skip(count2) {
47974
+ return this.offset(count2);
47749
47975
  }
47750
47976
  /**
47751
47977
  * Alias for `limit()` -- the Eloquent name; pairs with `skip()`.
@@ -47753,8 +47979,8 @@ var init_queryBuilder = __esm({
47753
47979
  * @param count - Maximum rows to return.
47754
47980
  * @returns this for chaining.
47755
47981
  */
47756
- take(count) {
47757
- return this.limit(count);
47982
+ take(count2) {
47983
+ return this.limit(count2);
47758
47984
  }
47759
47985
  /**
47760
47986
  * Build and return the SQL string without executing.
@@ -49662,7 +49888,7 @@ async function autoFieldMap(db, table2, fake = new FakeData2()) {
49662
49888
  }
49663
49889
  return fieldMap;
49664
49890
  }
49665
- async function seedTable(db, tableName, count = 10, fieldMap, overrides, opts) {
49891
+ async function seedTable(db, tableName, count2 = 10, fieldMap, overrides, opts) {
49666
49892
  if (opts?.seed !== void 0) {
49667
49893
  throw new Error(
49668
49894
  "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() })."
@@ -49674,7 +49900,7 @@ async function seedTable(db, tableName, count = 10, fieldMap, overrides, opts) {
49674
49900
  let seeded = 0;
49675
49901
  let failed = 0;
49676
49902
  const errors = [];
49677
- for (let i = 0; i < count; i++) {
49903
+ for (let i = 0; i < count2; i++) {
49678
49904
  try {
49679
49905
  const row = {};
49680
49906
  for (const [column2, generator] of Object.entries(fieldMap)) {
@@ -49761,7 +49987,7 @@ function pkFieldOf(fields) {
49761
49987
  }
49762
49988
  return "id";
49763
49989
  }
49764
- async function seedOrm(ormClass, count = 10, overrides, seed, opts, fkPools) {
49990
+ async function seedOrm(ormClass, count2 = 10, overrides, seed, opts, fkPools) {
49765
49991
  const merged = { ...opts ?? {} };
49766
49992
  const effectiveOverrides = merged.overrides ?? overrides;
49767
49993
  const effectiveSeed = merged.seed ?? seed;
@@ -49791,7 +50017,7 @@ async function seedOrm(ormClass, count = 10, overrides, seed, opts, fkPools) {
49791
50017
  let seeded = 0;
49792
50018
  let failed = 0;
49793
50019
  const errors = [];
49794
- for (let i = 0; i < count; i++) {
50020
+ for (let i = 0; i < count2; i++) {
49795
50021
  try {
49796
50022
  const attrs = {};
49797
50023
  for (const [name, def] of Object.entries(fields)) {
@@ -49872,7 +50098,7 @@ function topoSortModels(ormClasses) {
49872
50098
  ordered.push(...remaining);
49873
50099
  return ordered;
49874
50100
  }
49875
- async function seedModels(ormClasses, count = 10, opts) {
50101
+ async function seedModels(ormClasses, count2 = 10, opts) {
49876
50102
  const clear = opts?.clear ?? false;
49877
50103
  const seed = opts?.seed;
49878
50104
  const strict = opts?.strict ?? false;
@@ -49900,7 +50126,7 @@ async function seedModels(ormClasses, count = 10, opts) {
49900
50126
  }
49901
50127
  const summary = await seedOrm(
49902
50128
  model,
49903
- count,
50129
+ count2,
49904
50130
  void 0,
49905
50131
  void 0,
49906
50132
  { overrides: modelOverrides, clear: false, seed, strict },
@@ -50248,7 +50474,9 @@ function mongoConnection(uri, dbName) {
50248
50474
  if (!pending) {
50249
50475
  pending = (async () => {
50250
50476
  const { MongoClient } = await importMongoDriver();
50251
- const client = new MongoClient(uri);
50477
+ const client = new MongoClient(
50478
+ canonicalConnectionUrl(splitConnectionUrl(uri, { label: "DocStore", allowHostList: true }))
50479
+ );
50252
50480
  await client.connect();
50253
50481
  return { client, db: client.db(dbName) };
50254
50482
  })();
@@ -50278,6 +50506,7 @@ var InvalidId, OID_RE, ISO_RE, ObjectId, COMPARATORS, SAFE_PATH_SEGMENT, Cursor,
50278
50506
  var init_docstore = __esm({
50279
50507
  "src/docstore.ts"() {
50280
50508
  "use strict";
50509
+ init_connectionUrl();
50281
50510
  InvalidId = class extends Error {
50282
50511
  constructor(message) {
50283
50512
  super(message);
@@ -50619,11 +50848,13 @@ var init_docstore = __esm({
50619
50848
  });
50620
50849
 
50621
50850
  // src/graph/graphUrl.ts
50851
+ import { inspect as inspect2 } from "node:util";
50622
50852
  var SCHEME_ENGINE, ENGINE_DEFAULT_PORT, GraphUrl;
50623
50853
  var init_graphUrl = __esm({
50624
50854
  "src/graph/graphUrl.ts"() {
50625
50855
  "use strict";
50626
- init_databaseUrl();
50856
+ init_urlRedaction();
50857
+ init_connectionUrl();
50627
50858
  SCHEME_ENGINE = {
50628
50859
  ultipa: "ultipa",
50629
50860
  ultipas: "ultipa",
@@ -50655,12 +50886,14 @@ var init_graphUrl = __esm({
50655
50886
  useTls;
50656
50887
  constructor(url) {
50657
50888
  this.raw = url;
50889
+ const expected = "scheme://[user[:password]@]host[:port]/graph (e.g. ultipa://host:60061/mygraph)";
50890
+ const parts = splitConnectionUrl(url, { label: "GraphUrl", expected });
50658
50891
  let parsed;
50659
50892
  try {
50660
- parsed = new URL(url);
50893
+ parsed = new URL(`${parts.scheme}://${parts.hostPort}${parts.tail}`);
50661
50894
  } catch {
50662
- throw new Error(
50663
- `Unsupported graph URL '${redactCredentials(url)}' \u2014 expected scheme://[user[:password]@]host[:port]/graph (e.g. ultipa://host:60061/mygraph).`
50895
+ throw new ConnectionUrlError(
50896
+ `GraphUrl: invalid ${parts.scheme} URL - expected ${expected}. The URL itself is not shown because it may contain a password.`
50664
50897
  );
50665
50898
  }
50666
50899
  const scheme = parsed.protocol.replace(/:$/, "").toLowerCase();
@@ -50676,14 +50909,38 @@ var init_graphUrl = __esm({
50676
50909
  this.port = parsed.port ? parseInt(parsed.port, 10) : ENGINE_DEFAULT_PORT[engine];
50677
50910
  const path9 = (parsed.pathname || "").replace(/^\//, "");
50678
50911
  this.graph = path9 === "" ? null : path9;
50679
- this.username = parsed.username ? decodeURIComponent(parsed.username) : null;
50680
- this.password = parsed.password ? decodeURIComponent(parsed.password) : null;
50912
+ this.username = parts.username ? parts.username : null;
50913
+ this.password = parts.password ? parts.password : null;
50681
50914
  this.params = {};
50682
50915
  for (const [key, value] of parsed.searchParams) {
50683
50916
  if (!(key in this.params)) this.params[key] = value;
50684
50917
  }
50685
50918
  this.useTls = scheme.endsWith("s") || this.params.tls === "1" || this.params.tls === "true";
50686
50919
  }
50920
+ /**
50921
+ * What `JSON.stringify` emits, directly or as one field of a logged object.
50922
+ * `password` and `raw` both hold the secret, so the default dump printed it
50923
+ * twice (GHSA-h2mr-m3v3-cq8c). DatabaseUrl guards the same way; PHP has
50924
+ * __debugInfo/jsonSerialize and Ruby a redacted #inspect.
50925
+ */
50926
+ toJSON() {
50927
+ return {
50928
+ raw: redactCredentials(this.raw),
50929
+ scheme: this.scheme,
50930
+ engine: this.engine,
50931
+ host: this.host,
50932
+ port: this.port,
50933
+ graph: this.graph,
50934
+ username: this.username,
50935
+ password: this.password === null ? null : "***",
50936
+ params: this.params,
50937
+ useTls: this.useTls
50938
+ };
50939
+ }
50940
+ /** What `console.log(url)` / `util.inspect(url)` print. */
50941
+ [inspect2.custom]() {
50942
+ return `GraphUrl('${redactCredentials(this.raw)}')`;
50943
+ }
50687
50944
  /** host:port/graph — for messages, never carrying credentials. */
50688
50945
  getDsn() {
50689
50946
  const target = this.port ? `${this.host}:${this.port}` : this.host;