tina4-nodejs 3.13.161 → 3.13.163

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.
@@ -5963,11 +5963,11 @@ var init_firebird = __esm({
5963
5963
  */
5964
5964
  async decodeBlobs(row) {
5965
5965
  if (row === null || typeof row !== "object") return row;
5966
- const record = row;
5967
- for (const key of Object.keys(record)) {
5968
- if (typeof record[key] === "function") {
5969
- record[key] = await this.readBlob(
5970
- record[key]
5966
+ const record2 = row;
5967
+ for (const key of Object.keys(record2)) {
5968
+ if (typeof record2[key] === "function") {
5969
+ record2[key] = await this.readBlob(
5970
+ record2[key]
5971
5971
  );
5972
5972
  }
5973
5973
  }
@@ -13458,12 +13458,12 @@ function crudSortProp(model, requested, pkProp) {
13458
13458
  }
13459
13459
  return pkProp;
13460
13460
  }
13461
- function cellValue(record, col) {
13462
- return record[col];
13461
+ function cellValue(record2, col) {
13462
+ return record2[col];
13463
13463
  }
13464
- function buildCells(columns, record, editable, aligns) {
13464
+ function buildCells(columns, record2, editable, aligns) {
13465
13465
  return columns.map((col, index) => {
13466
- const raw = cellValue(record, col);
13466
+ const raw = cellValue(record2, col);
13467
13467
  const value = h(raw === null || raw === void 0 ? "" : raw);
13468
13468
  const css = aligns[index];
13469
13469
  return editable ? `<td class="${css}" contenteditable="true" data-field="${h(col)}">${value}</td>` : `<td class="${css}">${value}</td>`;
@@ -13626,9 +13626,9 @@ function headerCell(opts, col, align) {
13626
13626
  function tableData(opts) {
13627
13627
  const aligns = opts.columns.map((col) => columnAlignment(opts.model, col));
13628
13628
  const headers = opts.columns.map((col, index) => headerCell(opts, col, aligns[index]));
13629
- const rows = opts.records.map((record) => ({
13630
- id: h(cellValue(record, opts.pk) ?? ""),
13631
- cells: buildCells(opts.columns, record, opts.editable, aligns)
13629
+ const rows = opts.records.map((record2) => ({
13630
+ id: h(cellValue(record2, opts.pk) ?? ""),
13631
+ cells: buildCells(opts.columns, record2, opts.editable, aligns)
13632
13632
  }));
13633
13633
  return {
13634
13634
  headers,
@@ -14827,9 +14827,9 @@ async function eagerLoadHasRelation(instances, model, relatedClass, relationName
14827
14827
  if (nested.length > 0 && related.length > 0) await relatedClass._eagerLoad(related, nested);
14828
14828
  const fkProp = reverseMappedColumn(relatedClass, relation.foreignKey);
14829
14829
  const grouped = {};
14830
- for (const record of related) {
14831
- const key = _joinKey(record[fkProp]);
14832
- (grouped[key] ??= []).push(record);
14830
+ for (const record2 of related) {
14831
+ const key = _joinKey(record2[fkProp]);
14832
+ (grouped[key] ??= []).push(record2);
14833
14833
  }
14834
14834
  for (const instance of instances) {
14835
14835
  const records = grouped[_joinKey(instance[pk])] ?? [];
@@ -14845,7 +14845,7 @@ async function eagerLoadBelongsToRelation(instances, model, relatedClass, relati
14845
14845
  const related = await eagerQueryRelated(relatedClass, relatedPkColumn, values);
14846
14846
  if (nested.length > 0 && related.length > 0) await relatedClass._eagerLoad(related, nested);
14847
14847
  const lookup2 = {};
14848
- for (const record of related) lookup2[_joinKey(record[relatedPk])] = record;
14848
+ for (const record2 of related) lookup2[_joinKey(record2[relatedPk])] = record2;
14849
14849
  for (const instance of instances) {
14850
14850
  const value = instance[fkProp];
14851
14851
  relationshipCache(instance)[relationName] = value !== void 0 && value !== null ? lookup2[_joinKey(value)] ?? null : null;
@@ -18091,7 +18091,7 @@ var init_bolt = __esm({
18091
18091
  const session = this.database ? this.driver.session({ database: this.database }) : this.driver.session();
18092
18092
  try {
18093
18093
  const result = await session.run(cypher, params ?? {});
18094
- return result.records.map((record) => record.toObject());
18094
+ return result.records.map((record2) => record2.toObject());
18095
18095
  } catch (exc) {
18096
18096
  this.lastError = errorMessage(exc);
18097
18097
  const code = exc?.code ?? "";
@@ -26090,7 +26090,7 @@ var init_session = __esm({
26090
26090
  save() {
26091
26091
  if (!this.sessionId || !this.data) return true;
26092
26092
  if (this.isFresh()) return true;
26093
- let record = this.data;
26093
+ let record2 = this.data;
26094
26094
  if (this.stored) {
26095
26095
  const current = this.safeRead(this.sessionId);
26096
26096
  if (this.lastReadFailed) return false;
@@ -26099,9 +26099,9 @@ var init_session = __esm({
26099
26099
  this.ended = true;
26100
26100
  return true;
26101
26101
  }
26102
- if (!this.cleared) record = this.merged(current);
26102
+ if (!this.cleared) record2 = this.merged(current);
26103
26103
  }
26104
- if (this.safeWrite(this.sessionId, record, this.ttl)) {
26104
+ if (this.safeWrite(this.sessionId, record2, this.ttl)) {
26105
26105
  this.dirty = false;
26106
26106
  this.stored = true;
26107
26107
  this.cleared = false;
@@ -26118,19 +26118,19 @@ var init_session = __esm({
26118
26118
  */
26119
26119
  merged(current) {
26120
26120
  const data = this.data;
26121
- const record = { ...current };
26121
+ const record2 = { ...current };
26122
26122
  for (const [key, value] of Object.entries(data)) {
26123
26123
  const print = fingerprint(value);
26124
26124
  if (print === void 0 || !this.loaded.has(key) || this.loaded.get(key) !== print) {
26125
- record[key] = value;
26125
+ record2[key] = value;
26126
26126
  }
26127
26127
  }
26128
26128
  for (const key of this.loaded.keys()) {
26129
26129
  if (!Object.prototype.hasOwnProperty.call(data, key)) {
26130
- delete record[key];
26130
+ delete record2[key];
26131
26131
  }
26132
26132
  }
26133
- return record;
26133
+ return record2;
26134
26134
  }
26135
26135
  /**
26136
26136
  * End the session for this request without touching the store: no id and
@@ -31285,7 +31285,7 @@ data: ${channel.buffer.shift()}
31285
31285
  }
31286
31286
  return { resources };
31287
31287
  }
31288
- _handleResourcesRead(params) {
31288
+ async _handleResourcesRead(params) {
31289
31289
  const uri = params.uri;
31290
31290
  if (!uri) {
31291
31291
  throw new Error("Missing resource URI");
@@ -31294,7 +31294,7 @@ data: ${channel.buffer.shift()}
31294
31294
  if (!resource) {
31295
31295
  throw new Error(`Unknown resource: ${uri}`);
31296
31296
  }
31297
- const result = resource.handler();
31297
+ const result = await resource.handler();
31298
31298
  let text;
31299
31299
  if (typeof result === "string") {
31300
31300
  text = result;
@@ -34828,6 +34828,12 @@ const outBytes = new Uint8Array(workerData.sab, 8);
34828
34828
  // (test/kafkaErrorCodes.test.ts) can assert the floors.
34829
34829
  const PRODUCE_VERSION = 3;
34830
34830
  const FETCH_VERSION = 4;
34831
+ // How long the broker long-polls an empty partition before answering (ms).
34832
+ // Deliberately 1000, not tina4-php / tina4-python's 5000: Node's pop() is
34833
+ // synchronous (Atomics.wait on this worker), so the long-poll blocks the whole
34834
+ // event loop, not one request. The tombstone-skip deadline caps it further while
34835
+ // stepping so a stream of tombstones cannot hold pop() past ~1s.
34836
+ const FETCH_MAX_WAIT_MS = 1000;
34831
34837
 
34832
34838
  let correlationId = 0;
34833
34839
  let brokerSock = null;
@@ -35014,12 +35020,13 @@ async function produce(topic, valueBytes) {
35014
35020
  }
35015
35021
 
35016
35022
  // \u2500\u2500 fetch \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
35017
- function fetchRequest(topic, offset) {
35023
+ function fetchRequest(topic, offset, maxWaitMs) {
35024
+ if (maxWaitMs === undefined) maxWaitMs = FETCH_MAX_WAIT_MS;
35018
35025
  const topicBuf = Buffer.from(topic, "utf-8");
35019
35026
  const buf = Buffer.alloc(4 + 4 + 4 + 4 + 1 + 4 + 2 + topicBuf.length + 4 + 4 + 8 + 4);
35020
35027
  let p = 0;
35021
35028
  buf.writeInt32BE(-1, p); p += 4; // replicaId
35022
- buf.writeInt32BE(1000, p); p += 4; // maxWaitMs
35029
+ buf.writeInt32BE(maxWaitMs, p); p += 4; // maxWaitMs (long-poll bound; capped by the tombstone-skip deadline)
35023
35030
  buf.writeInt32BE(1, p); p += 4; // minBytes
35024
35031
  buf.writeInt32BE(1048576, p); p += 4; // maxBytes
35025
35032
  buf.writeInt8(0, p); p += 1; // isolation READ_UNCOMMITTED
@@ -35032,8 +35039,12 @@ function fetchRequest(topic, offset) {
35032
35039
  buf.writeInt32BE(1048576, p); p += 4;
35033
35040
  return frame(1, FETCH_VERSION, buf);
35034
35041
  }
35035
- // Decode the first record of the partition's record-set: its value string and
35036
- // absolute offset (baseOffset + offsetDelta). null = no usable record.
35042
+ // Decode the FIRST record of the partition's record-set (the cross-framework
35043
+ // contract: only a batch's first record is decoded -- the Tina4 producer writes
35044
+ // one record per batch). Returns its value and absolute offset (baseOffset +
35045
+ // offsetDelta); a tombstone (null value) comes back with value null and its
35046
+ // offset so the caller can step past it. null = no usable record at all (empty /
35047
+ // old-format / short response).
35037
35048
  function firstRecord(buf, start, end) {
35038
35049
  let pos = start;
35039
35050
  while (pos + 12 <= end) {
@@ -35049,8 +35060,7 @@ function firstRecord(buf, start, end) {
35049
35060
  for (let i = 0; i < recordsCount && r < batchEnd; i++) {
35050
35061
  const recLen = readVarint(buf, r);
35051
35062
  let rp = recLen.next;
35052
- const recordEnd = rp + recLen.value;
35053
- rp += 1;
35063
+ rp += 1; // record attributes byte
35054
35064
  rp = readVarint(buf, rp).next; // timestampDelta
35055
35065
  const offDelta = readVarint(buf, rp); rp = offDelta.next;
35056
35066
  const keyLen = readVarint(buf, rp); rp = keyLen.next;
@@ -35062,15 +35072,23 @@ function firstRecord(buf, start, end) {
35062
35072
  offset: Number(baseOffset) + offDelta.value,
35063
35073
  };
35064
35074
  }
35065
- r = recordEnd;
35075
+ // Tombstone (null value) or empty value: hand back a marker carrying its
35076
+ // offset instead of null. Returning null here used to mean "no record", so
35077
+ // pop() never advanced and re-fetched the tombstone for ever -- nothing
35078
+ // after it was delivered. The caller (fetchPastTombstones) steps the
35079
+ // offset on and re-fetches.
35080
+ return {
35081
+ value: null,
35082
+ offset: Number(baseOffset) + offDelta.value,
35083
+ };
35066
35084
  }
35067
35085
  pos = batchEnd;
35068
35086
  }
35069
35087
  return null;
35070
35088
  }
35071
- async function fetchAt(topic, offset) {
35089
+ async function fetchAt(topic, offset, maxWaitMs) {
35072
35090
  const sock = await broker();
35073
- const resp = await rpc(sock, fetchRequest(topic, offset));
35091
+ const resp = await rpc(sock, fetchRequest(topic, offset, maxWaitMs));
35074
35092
  let pos = 4; // correlationId
35075
35093
  pos += 4; // throttleTimeMs
35076
35094
  const topicCount = resp.readInt32BE(pos); pos += 4;
@@ -35206,9 +35224,37 @@ async function broker() {
35206
35224
  // Resume from the committed offset on the FIRST read of a topic in this worker,
35207
35225
  // then advance the in-memory cursor; the committed offset only moves on a
35208
35226
  // commit, so it lags and a crash before commit replays (at-least-once).
35227
+ // Fetch from the cursor, stepping past tombstones, until a record with a value
35228
+ // arrives, the topic is exhausted, or the deadline passes. A tombstone (null
35229
+ // value: Debezium deletes, compacted-topic delete markers) carries no job;
35230
+ // returning "nothing" without moving the offset re-fetched it for ever, so
35231
+ // nothing after it was ever delivered. The 1 s deadline holds while skipping
35232
+ // (the same steady-state bound as tina4-php/tina4-python), and the whole loop
35233
+ // stays inside this one worker round-trip (ADR-0022) -- well under
35234
+ // CALL_TIMEOUT_MS. Nothing is committed here: acknowledging the next record
35235
+ // commits past the skipped tombstones, as before.
35236
+ async function fetchPastTombstones(topic) {
35237
+ const deadline = Date.now() + 1000;
35238
+ let maxWaitMs = FETCH_MAX_WAIT_MS;
35239
+ while (true) {
35240
+ const offset = offsets[topic];
35241
+ const rec = await fetchAt(topic, offset, maxWaitMs);
35242
+ if (rec === null || rec.value !== null) return rec; // nothing, or a real record
35243
+ // Anti-spin: the decoder reads only a batch's first record, so a tombstone
35244
+ // sharing a batch with later records comes back at an offset already passed.
35245
+ // That must never loop this fetch.
35246
+ const next = rec.offset + 1;
35247
+ if (next <= offset) return null;
35248
+ offsets[topic] = next;
35249
+ const remaining = deadline - Date.now();
35250
+ if (remaining <= 0) return null;
35251
+ maxWaitMs = remaining;
35252
+ }
35253
+ }
35254
+
35209
35255
  async function fetchNext(topic) {
35210
35256
  if (!(topic in offsets)) offsets[topic] = await offsetFetch(topic);
35211
- const rec = await fetchAt(topic, offsets[topic]);
35257
+ const rec = await fetchPastTombstones(topic);
35212
35258
  if (rec === null) return null;
35213
35259
  offsets[topic] = rec.offset + 1;
35214
35260
  return rec;
@@ -35713,7 +35759,7 @@ var init_liteBackend = __esm({
35713
35759
  writeReserved(queue, job) {
35714
35760
  const now = this.nowIso();
35715
35761
  const vt = this.visibilityTimeout || 0;
35716
- const record = {
35762
+ const record2 = {
35717
35763
  id: job.id,
35718
35764
  payload: job.payload,
35719
35765
  status: "reserved",
@@ -35725,7 +35771,7 @@ var init_liteBackend = __esm({
35725
35771
  createdAt: job.createdAt ?? now,
35726
35772
  topic: job.topic ?? queue
35727
35773
  };
35728
- writeFileSync11(this.reservedPath(queue, record.id), JSON.stringify(record, null, 2));
35774
+ writeFileSync11(this.reservedPath(queue, record2.id), JSON.stringify(record2, null, 2));
35729
35775
  }
35730
35776
  /**
35731
35777
  * Return expired reservations to the queue (at-least-once delivery).
@@ -35747,29 +35793,29 @@ var init_liteBackend = __esm({
35747
35793
  }
35748
35794
  for (const filename of filenames) {
35749
35795
  const filePath = join23(reservedDir, filename);
35750
- let record;
35796
+ let record2;
35751
35797
  try {
35752
- record = JSON.parse(readFileSync16(filePath, "utf-8"));
35798
+ record2 = JSON.parse(readFileSync16(filePath, "utf-8"));
35753
35799
  } catch {
35754
35800
  continue;
35755
35801
  }
35756
- if (record.availableAt && record.availableAt > now) continue;
35802
+ if (record2.availableAt && record2.availableAt > now) continue;
35757
35803
  try {
35758
35804
  unlinkSync8(filePath);
35759
35805
  } catch {
35760
35806
  continue;
35761
35807
  }
35762
- const attempts = (record.attempts ?? 0) + 1;
35808
+ const attempts = (record2.attempts ?? 0) + 1;
35763
35809
  const error2 = "reservation timed out \u2014 consumer did not acknowledge within the visibility timeout";
35764
35810
  const job = {
35765
- id: record.id,
35766
- payload: record.payload,
35811
+ id: record2.id,
35812
+ payload: record2.payload,
35767
35813
  status: "reserved",
35768
- createdAt: record.createdAt ?? now,
35814
+ createdAt: record2.createdAt ?? now,
35769
35815
  attempts,
35770
35816
  delayUntil: null,
35771
- priority: record.priority ?? 0,
35772
- topic: record.topic ?? queue,
35817
+ priority: record2.priority ?? 0,
35818
+ topic: record2.topic ?? queue,
35773
35819
  error: error2
35774
35820
  };
35775
35821
  if (attempts >= maxRetries) {
@@ -44354,7 +44400,6 @@ async function startServer(config) {
44354
44400
  server.listen(port, host, async () => {
44355
44401
  if (!cluster.isWorker) writePidfile(port);
44356
44402
  const siblingServers = await startLoopbackSiblings(port, host, dispatch);
44357
- await startAllTcpServices(host);
44358
44403
  const displayHost = host === "0.0.0.0" ? "localhost" : host;
44359
44404
  const isDebug = isTruthy(process.env.TINA4_DEBUG);
44360
44405
  const logLevel = (process.env.TINA4_LOG_LEVEL ?? "DEBUG").toUpperCase();
@@ -44435,9 +44480,7 @@ ${reset2}
44435
44480
  aiServer?.closeIdleConnections();
44436
44481
  for (const sibling of siblingServers) sibling.closeIdleConnections();
44437
44482
  });
44438
- const gracefulShutdown = async (signal) => {
44439
- if (shuttingDown) return;
44440
- shuttingDown = true;
44483
+ const runTeardown = async (signal) => {
44441
44484
  Log.info(`Received ${signal}, shutting down gracefully...`);
44442
44485
  if (!cluster.isWorker) removePidfile(port);
44443
44486
  stopAllBackgroundTasks();
@@ -44472,16 +44515,40 @@ ${reset2}
44472
44515
  }
44473
44516
  Log.info("Server stopped.");
44474
44517
  Log.reset();
44518
+ };
44519
+ const degradeTeardownFailure = (signal, err) => {
44520
+ const detail = err instanceof Error ? err.message : String(err);
44521
+ try {
44522
+ Log.error(`Teardown step failed during ${signal} shutdown (exiting cleanly): ${detail}`);
44523
+ } catch {
44524
+ try {
44525
+ process.stderr.write(
44526
+ `tina4: teardown step failed during ${signal} shutdown (exiting cleanly): ${detail}
44527
+ `
44528
+ );
44529
+ } catch {
44530
+ }
44531
+ }
44532
+ };
44533
+ const gracefulShutdown = async (signal) => {
44534
+ if (shuttingDown) return;
44535
+ shuttingDown = true;
44536
+ try {
44537
+ await runTeardown(signal);
44538
+ } catch (err) {
44539
+ degradeTeardownFailure(signal, err);
44540
+ }
44475
44541
  process.exit(0);
44476
44542
  };
44477
44543
  const onSigterm = () => {
44478
- void gracefulShutdown("SIGTERM");
44544
+ void gracefulShutdown("SIGTERM").catch(() => process.exit(0));
44479
44545
  };
44480
44546
  const onSigint = () => {
44481
- void gracefulShutdown("SIGINT");
44547
+ void gracefulShutdown("SIGINT").catch(() => process.exit(0));
44482
44548
  };
44483
44549
  process.on("SIGTERM", onSigterm);
44484
44550
  process.on("SIGINT", onSigint);
44551
+ await startAllTcpServices(host);
44485
44552
  const loopWatchdog = startLoopWatchdog();
44486
44553
  resolvePromise({
44487
44554
  close: () => {
@@ -49819,26 +49886,26 @@ var init_aiClient = __esm({
49819
49886
  if (!part || typeof part !== "object" || Array.isArray(part)) {
49820
49887
  throw new AiConfigError("AI content part must be an object with type and text/source");
49821
49888
  }
49822
- const record = part;
49823
- switch (record.type) {
49889
+ const record2 = part;
49890
+ switch (record2.type) {
49824
49891
  case "text":
49825
- this.validateTextPart(record);
49892
+ this.validateTextPart(record2);
49826
49893
  return;
49827
49894
  case "image":
49828
- this.validateImagePart(record);
49895
+ this.validateImagePart(record2);
49829
49896
  return;
49830
49897
  case "tool_result":
49831
- this.validateToolResultPart(record);
49898
+ this.validateToolResultPart(record2);
49832
49899
  return;
49833
49900
  default:
49834
- throw new AiConfigError(`AI content part has unknown type '${String(record.type)}'`);
49901
+ throw new AiConfigError(`AI content part has unknown type '${String(record2.type)}'`);
49835
49902
  }
49836
49903
  }
49837
- static validateTextPart(record) {
49838
- if (typeof record.text !== "string") throw new AiConfigError("AI text content part requires a string 'text' field");
49904
+ static validateTextPart(record2) {
49905
+ if (typeof record2.text !== "string") throw new AiConfigError("AI text content part requires a string 'text' field");
49839
49906
  }
49840
- static validateImagePart(record) {
49841
- const source = record.source;
49907
+ static validateImagePart(record2) {
49908
+ const source = record2.source;
49842
49909
  if (typeof source !== "string" || source.length === 0) {
49843
49910
  throw new AiConfigError("AI image content part requires a non-empty string 'source' field");
49844
49911
  }
@@ -49849,11 +49916,11 @@ var init_aiClient = __esm({
49849
49916
  throw new AiConfigError("AI image data URI must be data:<media_type>;base64,<payload>");
49850
49917
  }
49851
49918
  }
49852
- static validateToolResultPart(record) {
49853
- if (typeof record.tool_use_id !== "string" || record.tool_use_id.length === 0) {
49919
+ static validateToolResultPart(record2) {
49920
+ if (typeof record2.tool_use_id !== "string" || record2.tool_use_id.length === 0) {
49854
49921
  throw new AiConfigError("AI tool_result part requires a non-empty string 'tool_use_id'");
49855
49922
  }
49856
- if (typeof record.content !== "string") throw new AiConfigError("AI tool_result part requires a string 'content'");
49923
+ if (typeof record2.content !== "string") throw new AiConfigError("AI tool_result part requires a string 'content'");
49857
49924
  }
49858
49925
  /**
49859
49926
  * Validate the outbound tool declarations (ADR-0061). Each tool needs a
@@ -49869,14 +49936,14 @@ var init_aiClient = __esm({
49869
49936
  if (!tool || typeof tool !== "object" || Array.isArray(tool)) {
49870
49937
  throw new AiConfigError("AI tool must be an object with name, description, parameters");
49871
49938
  }
49872
- const record = tool;
49873
- if (typeof record.name !== "string" || record.name.length === 0) {
49939
+ const record2 = tool;
49940
+ if (typeof record2.name !== "string" || record2.name.length === 0) {
49874
49941
  throw new AiConfigError("AI tool requires a non-empty string 'name'");
49875
49942
  }
49876
- if (typeof record.description !== "string") {
49943
+ if (typeof record2.description !== "string") {
49877
49944
  throw new AiConfigError("AI tool requires a string 'description'");
49878
49945
  }
49879
- if (!record.parameters || typeof record.parameters !== "object" || Array.isArray(record.parameters)) {
49946
+ if (!record2.parameters || typeof record2.parameters !== "object" || Array.isArray(record2.parameters)) {
49880
49947
  throw new AiConfigError("AI tool requires a JSON-Schema object 'parameters'");
49881
49948
  }
49882
49949
  }
@@ -49893,8 +49960,8 @@ var init_aiClient = __esm({
49893
49960
  return;
49894
49961
  }
49895
49962
  if (choice && typeof choice === "object" && !Array.isArray(choice)) {
49896
- const record = choice;
49897
- if (typeof record.name !== "string" || record.name.length === 0) {
49963
+ const record2 = choice;
49964
+ if (typeof record2.name !== "string" || record2.name.length === 0) {
49898
49965
  throw new AiConfigError("AI toolChoice object requires a non-empty string 'name'");
49899
49966
  }
49900
49967
  return;
@@ -50959,38 +51026,37 @@ function runAll(options = {}) {
50959
51026
  const { quiet = false, failfast = false } = options;
50960
51027
  const results = { passed: 0, failed: 0, errors: 0, details: [] };
50961
51028
  for (const entry of registry2) {
50962
- if (!quiet) {
50963
- console.log(`
51029
+ if (!quiet) console.log(`
50964
51030
  ${entry.name}`);
51031
+ for (const assertion of entry.assertions) {
51032
+ const label = assertionLabel(assertion, entry.name);
51033
+ const ok = record(results, label, quiet, () => judge(assertion, callSync(entry.fn, assertion.args)));
51034
+ if (!ok && failfast) {
51035
+ printSummary(results, quiet);
51036
+ return results;
51037
+ }
50965
51038
  }
51039
+ }
51040
+ printSummary(results, quiet);
51041
+ return results;
51042
+ }
51043
+ async function runAllAsync(options = {}) {
51044
+ const { quiet = false, failfast = false, timeoutMs = 3e4 } = options;
51045
+ checkTimeout(timeoutMs);
51046
+ const results = { passed: 0, failed: 0, errors: 0, details: [] };
51047
+ for (const entry of registry2) {
51048
+ if (!quiet) console.log(`
51049
+ ${entry.name}`);
50966
51050
  for (const assertion of entry.assertions) {
50967
51051
  const label = assertionLabel(assertion, entry.name);
50968
- try {
50969
- runAssertion(entry.fn, assertion);
50970
- results.passed++;
50971
- results.details.push({ name: label, status: "passed" });
50972
- if (!quiet) {
50973
- console.log(` \x1B[32m+\x1B[0m ${label}`);
50974
- }
50975
- } catch (err) {
50976
- if (err instanceof TestAssertionError) {
50977
- results.failed++;
50978
- results.details.push({ name: label, status: "failed", message: err.message });
50979
- if (!quiet) {
50980
- console.log(` \x1B[31mx\x1B[0m ${label}: ${err.message}`);
50981
- }
50982
- } else {
50983
- results.errors++;
50984
- const msg = err instanceof Error ? `${err.constructor.name}: ${err.message}` : String(err);
50985
- results.details.push({ name: label, status: "error", message: msg });
50986
- if (!quiet) {
50987
- console.log(` \x1B[33m!\x1B[0m ${label}: ${msg}`);
50988
- }
50989
- }
50990
- if (failfast) {
50991
- printSummary(results, quiet);
50992
- return results;
50993
- }
51052
+ const outcome = await callAsync(entry.fn, assertion.args, timeoutMs);
51053
+ const ok = record(results, label, quiet, () => {
51054
+ if (outcome instanceof TestRunError) throw outcome;
51055
+ judge(assertion, outcome);
51056
+ });
51057
+ if (!ok && failfast) {
51058
+ printSummary(results, quiet);
51059
+ return results;
50994
51060
  }
50995
51061
  }
50996
51062
  }
@@ -51000,47 +51066,103 @@ function runAll(options = {}) {
51000
51066
  function reset() {
51001
51067
  registry2.length = 0;
51002
51068
  }
51003
- function runAssertion(fn, assertion) {
51004
- const { type: type2, args } = assertion;
51069
+ function isThenable(value) {
51070
+ return value !== null && (typeof value === "object" || typeof value === "function") && typeof value.then === "function";
51071
+ }
51072
+ function callSync(fn, args) {
51073
+ let value;
51074
+ try {
51075
+ value = fn(...args);
51076
+ } catch (error2) {
51077
+ return { threw: true, error: error2 };
51078
+ }
51079
+ if (isThenable(value)) {
51080
+ Promise.resolve(value).then(void 0, () => void 0);
51081
+ throw new TestRunError(
51082
+ "returned a Promise (async test function): runAll() cannot judge it, use await runAllAsync()"
51083
+ );
51084
+ }
51085
+ return { threw: false, value };
51086
+ }
51087
+ function checkTimeout(timeoutMs) {
51088
+ if (timeoutMs === Infinity) return;
51089
+ if (!(timeoutMs > 0 && timeoutMs <= MAX_TIMER_MS)) {
51090
+ throw new RangeError(
51091
+ `timeoutMs must be Infinity or a number of milliseconds in (0, ${MAX_TIMER_MS}], got ${timeoutMs}`
51092
+ );
51093
+ }
51094
+ }
51095
+ async function callAsync(fn, args, timeoutMs) {
51096
+ let timer;
51097
+ try {
51098
+ const value = fn(...args);
51099
+ if (!isThenable(value)) return { threw: false, value };
51100
+ if (timeoutMs === Infinity) return { threw: false, value: await value };
51101
+ const timeout = new Promise((_, reject) => {
51102
+ timer = setTimeout(
51103
+ () => reject(new TestRunError(`did not settle within ${timeoutMs} ms`)),
51104
+ timeoutMs
51105
+ );
51106
+ });
51107
+ return { threw: false, value: await Promise.race([Promise.resolve(value), timeout]) };
51108
+ } catch (error2) {
51109
+ if (error2 instanceof TestRunError) return error2;
51110
+ return { threw: true, error: error2 };
51111
+ } finally {
51112
+ if (timer !== void 0) clearTimeout(timer);
51113
+ }
51114
+ }
51115
+ function record(results, label, quiet, check) {
51116
+ try {
51117
+ check();
51118
+ results.passed++;
51119
+ results.details.push({ name: label, status: "passed" });
51120
+ if (!quiet) console.log(` \x1B[32m+\x1B[0m ${label}`);
51121
+ return true;
51122
+ } catch (err) {
51123
+ if (err instanceof TestAssertionError) {
51124
+ results.failed++;
51125
+ results.details.push({ name: label, status: "failed", message: err.message });
51126
+ if (!quiet) console.log(` \x1B[31mx\x1B[0m ${label}: ${err.message}`);
51127
+ } else {
51128
+ results.errors++;
51129
+ const msg = err instanceof Error ? `${err.constructor.name}: ${err.message}` : String(err);
51130
+ results.details.push({ name: label, status: "error", message: msg });
51131
+ if (!quiet) console.log(` \x1B[33m!\x1B[0m ${label}: ${msg}`);
51132
+ }
51133
+ return false;
51134
+ }
51135
+ }
51136
+ function judgeRaises(assertion, outcome) {
51137
+ const ExcClass = assertion.exception;
51138
+ if (!outcome.threw) throw new TestAssertionError(`expected ${ExcClass.name} to be raised`);
51139
+ const err = outcome.error;
51140
+ if (err instanceof ExcClass) return;
51141
+ throw new TestAssertionError(
51142
+ `expected ${ExcClass.name}, got ${err instanceof Error ? err.constructor.name : typeof err}: ${err}`
51143
+ );
51144
+ }
51145
+ function judge(assertion, outcome) {
51146
+ const { type: type2 } = assertion;
51147
+ if (type2 === "raises") return judgeRaises(assertion, outcome);
51148
+ if (outcome.threw) throw outcome.error;
51149
+ const result = outcome.value;
51005
51150
  switch (type2) {
51006
51151
  case "equal": {
51007
- const result = fn(...args);
51008
51152
  const expected = assertion.expected;
51009
51153
  if (result !== expected) {
51010
51154
  throw new TestAssertionError(
51011
51155
  `expected ${JSON.stringify(expected)}, got ${JSON.stringify(result)}`
51012
51156
  );
51013
51157
  }
51014
- break;
51015
- }
51016
- case "raises": {
51017
- const ExcClass = assertion.exception;
51018
- try {
51019
- fn(...args);
51020
- } catch (err) {
51021
- if (err instanceof ExcClass) {
51022
- return;
51023
- }
51024
- throw new TestAssertionError(
51025
- `expected ${ExcClass.name}, got ${err instanceof Error ? err.constructor.name : typeof err}: ${err}`
51026
- );
51027
- }
51028
- throw new TestAssertionError(`expected ${ExcClass.name} to be raised`);
51029
- }
51030
- case "true": {
51031
- const result = fn(...args);
51032
- if (!result) {
51033
- throw new TestAssertionError(`expected truthy, got ${JSON.stringify(result)}`);
51034
- }
51035
- break;
51036
- }
51037
- case "false": {
51038
- const result = fn(...args);
51039
- if (result) {
51040
- throw new TestAssertionError(`expected falsy, got ${JSON.stringify(result)}`);
51041
- }
51042
- break;
51158
+ return;
51043
51159
  }
51160
+ case "true":
51161
+ if (!result) throw new TestAssertionError(`expected truthy, got ${JSON.stringify(result)}`);
51162
+ return;
51163
+ case "false":
51164
+ if (result) throw new TestAssertionError(`expected falsy, got ${JSON.stringify(result)}`);
51165
+ return;
51044
51166
  default:
51045
51167
  throw new Error(`unknown assertion type: ${type2}`);
51046
51168
  }
@@ -51069,7 +51191,7 @@ function printSummary(results, quiet) {
51069
51191
  `
51070
51192
  );
51071
51193
  }
51072
- var registry2, TestAssertionError;
51194
+ var registry2, TestAssertionError, TestRunError, MAX_TIMER_MS;
51073
51195
  var init_testing = __esm({
51074
51196
  "src/testing.ts"() {
51075
51197
  "use strict";
@@ -51080,6 +51202,13 @@ var init_testing = __esm({
51080
51202
  this.name = "TestAssertionError";
51081
51203
  }
51082
51204
  };
51205
+ TestRunError = class extends Error {
51206
+ constructor(message) {
51207
+ super(message);
51208
+ this.name = "TestRunError";
51209
+ }
51210
+ };
51211
+ MAX_TIMER_MS = 2147483647;
51083
51212
  }
51084
51213
  });
51085
51214
 
@@ -51895,6 +52024,7 @@ __export(index_exports, {
51895
52024
  resolveTemplate: () => resolveTemplate,
51896
52025
  responseCache: () => responseCache,
51897
52026
  runAll: () => runAll,
52027
+ runAllAsync: () => runAllAsync,
51898
52028
  runRouteMiddlewares: () => runRouteMiddlewares,
51899
52029
  runWithCspNonce: () => runWithCspNonce,
51900
52030
  runtimeDir: () => runtimeDir,
@@ -52297,6 +52427,7 @@ export {
52297
52427
  resolveTemplate,
52298
52428
  responseCache,
52299
52429
  runAll,
52430
+ runAllAsync,
52300
52431
  runRouteMiddlewares,
52301
52432
  runWithCspNonce,
52302
52433
  runtimeDir,