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.
@@ -12973,7 +12973,7 @@ var init_session = __esm({
12973
12973
  save() {
12974
12974
  if (!this.sessionId || !this.data) return true;
12975
12975
  if (this.isFresh()) return true;
12976
- let record = this.data;
12976
+ let record2 = this.data;
12977
12977
  if (this.stored) {
12978
12978
  const current = this.safeRead(this.sessionId);
12979
12979
  if (this.lastReadFailed) return false;
@@ -12982,9 +12982,9 @@ var init_session = __esm({
12982
12982
  this.ended = true;
12983
12983
  return true;
12984
12984
  }
12985
- if (!this.cleared) record = this.merged(current);
12985
+ if (!this.cleared) record2 = this.merged(current);
12986
12986
  }
12987
- if (this.safeWrite(this.sessionId, record, this.ttl)) {
12987
+ if (this.safeWrite(this.sessionId, record2, this.ttl)) {
12988
12988
  this.dirty = false;
12989
12989
  this.stored = true;
12990
12990
  this.cleared = false;
@@ -13001,19 +13001,19 @@ var init_session = __esm({
13001
13001
  */
13002
13002
  merged(current) {
13003
13003
  const data = this.data;
13004
- const record = { ...current };
13004
+ const record2 = { ...current };
13005
13005
  for (const [key, value] of Object.entries(data)) {
13006
13006
  const print = fingerprint(value);
13007
13007
  if (print === void 0 || !this.loaded.has(key) || this.loaded.get(key) !== print) {
13008
- record[key] = value;
13008
+ record2[key] = value;
13009
13009
  }
13010
13010
  }
13011
13011
  for (const key of this.loaded.keys()) {
13012
13012
  if (!Object.prototype.hasOwnProperty.call(data, key)) {
13013
- delete record[key];
13013
+ delete record2[key];
13014
13014
  }
13015
13015
  }
13016
- return record;
13016
+ return record2;
13017
13017
  }
13018
13018
  /**
13019
13019
  * End the session for this request without touching the store: no id and
@@ -18168,7 +18168,7 @@ data: ${channel.buffer.shift()}
18168
18168
  }
18169
18169
  return { resources };
18170
18170
  }
18171
- _handleResourcesRead(params) {
18171
+ async _handleResourcesRead(params) {
18172
18172
  const uri = params.uri;
18173
18173
  if (!uri) {
18174
18174
  throw new Error("Missing resource URI");
@@ -18177,7 +18177,7 @@ data: ${channel.buffer.shift()}
18177
18177
  if (!resource) {
18178
18178
  throw new Error(`Unknown resource: ${uri}`);
18179
18179
  }
18180
- const result = resource.handler();
18180
+ const result = await resource.handler();
18181
18181
  let text;
18182
18182
  if (typeof result === "string") {
18183
18183
  text = result;
@@ -21711,6 +21711,12 @@ const outBytes = new Uint8Array(workerData.sab, 8);
21711
21711
  // (test/kafkaErrorCodes.test.ts) can assert the floors.
21712
21712
  const PRODUCE_VERSION = 3;
21713
21713
  const FETCH_VERSION = 4;
21714
+ // How long the broker long-polls an empty partition before answering (ms).
21715
+ // Deliberately 1000, not tina4-php / tina4-python's 5000: Node's pop() is
21716
+ // synchronous (Atomics.wait on this worker), so the long-poll blocks the whole
21717
+ // event loop, not one request. The tombstone-skip deadline caps it further while
21718
+ // stepping so a stream of tombstones cannot hold pop() past ~1s.
21719
+ const FETCH_MAX_WAIT_MS = 1000;
21714
21720
 
21715
21721
  let correlationId = 0;
21716
21722
  let brokerSock = null;
@@ -21897,12 +21903,13 @@ async function produce(topic, valueBytes) {
21897
21903
  }
21898
21904
 
21899
21905
  // \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
21900
- function fetchRequest(topic, offset) {
21906
+ function fetchRequest(topic, offset, maxWaitMs) {
21907
+ if (maxWaitMs === undefined) maxWaitMs = FETCH_MAX_WAIT_MS;
21901
21908
  const topicBuf = Buffer.from(topic, "utf-8");
21902
21909
  const buf = Buffer.alloc(4 + 4 + 4 + 4 + 1 + 4 + 2 + topicBuf.length + 4 + 4 + 8 + 4);
21903
21910
  let p = 0;
21904
21911
  buf.writeInt32BE(-1, p); p += 4; // replicaId
21905
- buf.writeInt32BE(1000, p); p += 4; // maxWaitMs
21912
+ buf.writeInt32BE(maxWaitMs, p); p += 4; // maxWaitMs (long-poll bound; capped by the tombstone-skip deadline)
21906
21913
  buf.writeInt32BE(1, p); p += 4; // minBytes
21907
21914
  buf.writeInt32BE(1048576, p); p += 4; // maxBytes
21908
21915
  buf.writeInt8(0, p); p += 1; // isolation READ_UNCOMMITTED
@@ -21915,8 +21922,12 @@ function fetchRequest(topic, offset) {
21915
21922
  buf.writeInt32BE(1048576, p); p += 4;
21916
21923
  return frame(1, FETCH_VERSION, buf);
21917
21924
  }
21918
- // Decode the first record of the partition's record-set: its value string and
21919
- // absolute offset (baseOffset + offsetDelta). null = no usable record.
21925
+ // Decode the FIRST record of the partition's record-set (the cross-framework
21926
+ // contract: only a batch's first record is decoded -- the Tina4 producer writes
21927
+ // one record per batch). Returns its value and absolute offset (baseOffset +
21928
+ // offsetDelta); a tombstone (null value) comes back with value null and its
21929
+ // offset so the caller can step past it. null = no usable record at all (empty /
21930
+ // old-format / short response).
21920
21931
  function firstRecord(buf, start, end) {
21921
21932
  let pos = start;
21922
21933
  while (pos + 12 <= end) {
@@ -21932,8 +21943,7 @@ function firstRecord(buf, start, end) {
21932
21943
  for (let i = 0; i < recordsCount && r < batchEnd; i++) {
21933
21944
  const recLen = readVarint(buf, r);
21934
21945
  let rp = recLen.next;
21935
- const recordEnd = rp + recLen.value;
21936
- rp += 1;
21946
+ rp += 1; // record attributes byte
21937
21947
  rp = readVarint(buf, rp).next; // timestampDelta
21938
21948
  const offDelta = readVarint(buf, rp); rp = offDelta.next;
21939
21949
  const keyLen = readVarint(buf, rp); rp = keyLen.next;
@@ -21945,15 +21955,23 @@ function firstRecord(buf, start, end) {
21945
21955
  offset: Number(baseOffset) + offDelta.value,
21946
21956
  };
21947
21957
  }
21948
- r = recordEnd;
21958
+ // Tombstone (null value) or empty value: hand back a marker carrying its
21959
+ // offset instead of null. Returning null here used to mean "no record", so
21960
+ // pop() never advanced and re-fetched the tombstone for ever -- nothing
21961
+ // after it was delivered. The caller (fetchPastTombstones) steps the
21962
+ // offset on and re-fetches.
21963
+ return {
21964
+ value: null,
21965
+ offset: Number(baseOffset) + offDelta.value,
21966
+ };
21949
21967
  }
21950
21968
  pos = batchEnd;
21951
21969
  }
21952
21970
  return null;
21953
21971
  }
21954
- async function fetchAt(topic, offset) {
21972
+ async function fetchAt(topic, offset, maxWaitMs) {
21955
21973
  const sock = await broker();
21956
- const resp = await rpc(sock, fetchRequest(topic, offset));
21974
+ const resp = await rpc(sock, fetchRequest(topic, offset, maxWaitMs));
21957
21975
  let pos = 4; // correlationId
21958
21976
  pos += 4; // throttleTimeMs
21959
21977
  const topicCount = resp.readInt32BE(pos); pos += 4;
@@ -22089,9 +22107,37 @@ async function broker() {
22089
22107
  // Resume from the committed offset on the FIRST read of a topic in this worker,
22090
22108
  // then advance the in-memory cursor; the committed offset only moves on a
22091
22109
  // commit, so it lags and a crash before commit replays (at-least-once).
22110
+ // Fetch from the cursor, stepping past tombstones, until a record with a value
22111
+ // arrives, the topic is exhausted, or the deadline passes. A tombstone (null
22112
+ // value: Debezium deletes, compacted-topic delete markers) carries no job;
22113
+ // returning "nothing" without moving the offset re-fetched it for ever, so
22114
+ // nothing after it was ever delivered. The 1 s deadline holds while skipping
22115
+ // (the same steady-state bound as tina4-php/tina4-python), and the whole loop
22116
+ // stays inside this one worker round-trip (ADR-0022) -- well under
22117
+ // CALL_TIMEOUT_MS. Nothing is committed here: acknowledging the next record
22118
+ // commits past the skipped tombstones, as before.
22119
+ async function fetchPastTombstones(topic) {
22120
+ const deadline = Date.now() + 1000;
22121
+ let maxWaitMs = FETCH_MAX_WAIT_MS;
22122
+ while (true) {
22123
+ const offset = offsets[topic];
22124
+ const rec = await fetchAt(topic, offset, maxWaitMs);
22125
+ if (rec === null || rec.value !== null) return rec; // nothing, or a real record
22126
+ // Anti-spin: the decoder reads only a batch's first record, so a tombstone
22127
+ // sharing a batch with later records comes back at an offset already passed.
22128
+ // That must never loop this fetch.
22129
+ const next = rec.offset + 1;
22130
+ if (next <= offset) return null;
22131
+ offsets[topic] = next;
22132
+ const remaining = deadline - Date.now();
22133
+ if (remaining <= 0) return null;
22134
+ maxWaitMs = remaining;
22135
+ }
22136
+ }
22137
+
22092
22138
  async function fetchNext(topic) {
22093
22139
  if (!(topic in offsets)) offsets[topic] = await offsetFetch(topic);
22094
- const rec = await fetchAt(topic, offsets[topic]);
22140
+ const rec = await fetchPastTombstones(topic);
22095
22141
  if (rec === null) return null;
22096
22142
  offsets[topic] = rec.offset + 1;
22097
22143
  return rec;
@@ -22596,7 +22642,7 @@ var init_liteBackend = __esm({
22596
22642
  writeReserved(queue, job) {
22597
22643
  const now = this.nowIso();
22598
22644
  const vt = this.visibilityTimeout || 0;
22599
- const record = {
22645
+ const record2 = {
22600
22646
  id: job.id,
22601
22647
  payload: job.payload,
22602
22648
  status: "reserved",
@@ -22608,7 +22654,7 @@ var init_liteBackend = __esm({
22608
22654
  createdAt: job.createdAt ?? now,
22609
22655
  topic: job.topic ?? queue
22610
22656
  };
22611
- writeFileSync9(this.reservedPath(queue, record.id), JSON.stringify(record, null, 2));
22657
+ writeFileSync9(this.reservedPath(queue, record2.id), JSON.stringify(record2, null, 2));
22612
22658
  }
22613
22659
  /**
22614
22660
  * Return expired reservations to the queue (at-least-once delivery).
@@ -22630,29 +22676,29 @@ var init_liteBackend = __esm({
22630
22676
  }
22631
22677
  for (const filename of filenames) {
22632
22678
  const filePath = join18(reservedDir, filename);
22633
- let record;
22679
+ let record2;
22634
22680
  try {
22635
- record = JSON.parse(readFileSync14(filePath, "utf-8"));
22681
+ record2 = JSON.parse(readFileSync14(filePath, "utf-8"));
22636
22682
  } catch {
22637
22683
  continue;
22638
22684
  }
22639
- if (record.availableAt && record.availableAt > now) continue;
22685
+ if (record2.availableAt && record2.availableAt > now) continue;
22640
22686
  try {
22641
22687
  unlinkSync7(filePath);
22642
22688
  } catch {
22643
22689
  continue;
22644
22690
  }
22645
- const attempts = (record.attempts ?? 0) + 1;
22691
+ const attempts = (record2.attempts ?? 0) + 1;
22646
22692
  const error2 = "reservation timed out \u2014 consumer did not acknowledge within the visibility timeout";
22647
22693
  const job = {
22648
- id: record.id,
22649
- payload: record.payload,
22694
+ id: record2.id,
22695
+ payload: record2.payload,
22650
22696
  status: "reserved",
22651
- createdAt: record.createdAt ?? now,
22697
+ createdAt: record2.createdAt ?? now,
22652
22698
  attempts,
22653
22699
  delayUntil: null,
22654
- priority: record.priority ?? 0,
22655
- topic: record.topic ?? queue,
22700
+ priority: record2.priority ?? 0,
22701
+ topic: record2.topic ?? queue,
22656
22702
  error: error2
22657
22703
  };
22658
22704
  if (attempts >= maxRetries) {
@@ -31237,7 +31283,6 @@ async function startServer(config) {
31237
31283
  server.listen(port, host, async () => {
31238
31284
  if (!cluster.isWorker) writePidfile(port);
31239
31285
  const siblingServers = await startLoopbackSiblings(port, host, dispatch);
31240
- await startAllTcpServices(host);
31241
31286
  const displayHost = host === "0.0.0.0" ? "localhost" : host;
31242
31287
  const isDebug = isTruthy(process.env.TINA4_DEBUG);
31243
31288
  const logLevel = (process.env.TINA4_LOG_LEVEL ?? "DEBUG").toUpperCase();
@@ -31318,9 +31363,7 @@ ${reset2}
31318
31363
  aiServer?.closeIdleConnections();
31319
31364
  for (const sibling of siblingServers) sibling.closeIdleConnections();
31320
31365
  });
31321
- const gracefulShutdown = async (signal) => {
31322
- if (shuttingDown) return;
31323
- shuttingDown = true;
31366
+ const runTeardown = async (signal) => {
31324
31367
  Log.info(`Received ${signal}, shutting down gracefully...`);
31325
31368
  if (!cluster.isWorker) removePidfile(port);
31326
31369
  stopAllBackgroundTasks();
@@ -31355,16 +31398,40 @@ ${reset2}
31355
31398
  }
31356
31399
  Log.info("Server stopped.");
31357
31400
  Log.reset();
31401
+ };
31402
+ const degradeTeardownFailure = (signal, err) => {
31403
+ const detail = err instanceof Error ? err.message : String(err);
31404
+ try {
31405
+ Log.error(`Teardown step failed during ${signal} shutdown (exiting cleanly): ${detail}`);
31406
+ } catch {
31407
+ try {
31408
+ process.stderr.write(
31409
+ `tina4: teardown step failed during ${signal} shutdown (exiting cleanly): ${detail}
31410
+ `
31411
+ );
31412
+ } catch {
31413
+ }
31414
+ }
31415
+ };
31416
+ const gracefulShutdown = async (signal) => {
31417
+ if (shuttingDown) return;
31418
+ shuttingDown = true;
31419
+ try {
31420
+ await runTeardown(signal);
31421
+ } catch (err) {
31422
+ degradeTeardownFailure(signal, err);
31423
+ }
31358
31424
  process.exit(0);
31359
31425
  };
31360
31426
  const onSigterm = () => {
31361
- void gracefulShutdown("SIGTERM");
31427
+ void gracefulShutdown("SIGTERM").catch(() => process.exit(0));
31362
31428
  };
31363
31429
  const onSigint = () => {
31364
- void gracefulShutdown("SIGINT");
31430
+ void gracefulShutdown("SIGINT").catch(() => process.exit(0));
31365
31431
  };
31366
31432
  process.on("SIGTERM", onSigterm);
31367
31433
  process.on("SIGINT", onSigint);
31434
+ await startAllTcpServices(host);
31368
31435
  const loopWatchdog = startLoopWatchdog();
31369
31436
  resolvePromise({
31370
31437
  close: () => {
@@ -37233,26 +37300,26 @@ var init_aiClient = __esm({
37233
37300
  if (!part || typeof part !== "object" || Array.isArray(part)) {
37234
37301
  throw new AiConfigError("AI content part must be an object with type and text/source");
37235
37302
  }
37236
- const record = part;
37237
- switch (record.type) {
37303
+ const record2 = part;
37304
+ switch (record2.type) {
37238
37305
  case "text":
37239
- this.validateTextPart(record);
37306
+ this.validateTextPart(record2);
37240
37307
  return;
37241
37308
  case "image":
37242
- this.validateImagePart(record);
37309
+ this.validateImagePart(record2);
37243
37310
  return;
37244
37311
  case "tool_result":
37245
- this.validateToolResultPart(record);
37312
+ this.validateToolResultPart(record2);
37246
37313
  return;
37247
37314
  default:
37248
- throw new AiConfigError(`AI content part has unknown type '${String(record.type)}'`);
37315
+ throw new AiConfigError(`AI content part has unknown type '${String(record2.type)}'`);
37249
37316
  }
37250
37317
  }
37251
- static validateTextPart(record) {
37252
- if (typeof record.text !== "string") throw new AiConfigError("AI text content part requires a string 'text' field");
37318
+ static validateTextPart(record2) {
37319
+ if (typeof record2.text !== "string") throw new AiConfigError("AI text content part requires a string 'text' field");
37253
37320
  }
37254
- static validateImagePart(record) {
37255
- const source = record.source;
37321
+ static validateImagePart(record2) {
37322
+ const source = record2.source;
37256
37323
  if (typeof source !== "string" || source.length === 0) {
37257
37324
  throw new AiConfigError("AI image content part requires a non-empty string 'source' field");
37258
37325
  }
@@ -37263,11 +37330,11 @@ var init_aiClient = __esm({
37263
37330
  throw new AiConfigError("AI image data URI must be data:<media_type>;base64,<payload>");
37264
37331
  }
37265
37332
  }
37266
- static validateToolResultPart(record) {
37267
- if (typeof record.tool_use_id !== "string" || record.tool_use_id.length === 0) {
37333
+ static validateToolResultPart(record2) {
37334
+ if (typeof record2.tool_use_id !== "string" || record2.tool_use_id.length === 0) {
37268
37335
  throw new AiConfigError("AI tool_result part requires a non-empty string 'tool_use_id'");
37269
37336
  }
37270
- if (typeof record.content !== "string") throw new AiConfigError("AI tool_result part requires a string 'content'");
37337
+ if (typeof record2.content !== "string") throw new AiConfigError("AI tool_result part requires a string 'content'");
37271
37338
  }
37272
37339
  /**
37273
37340
  * Validate the outbound tool declarations (ADR-0061). Each tool needs a
@@ -37283,14 +37350,14 @@ var init_aiClient = __esm({
37283
37350
  if (!tool || typeof tool !== "object" || Array.isArray(tool)) {
37284
37351
  throw new AiConfigError("AI tool must be an object with name, description, parameters");
37285
37352
  }
37286
- const record = tool;
37287
- if (typeof record.name !== "string" || record.name.length === 0) {
37353
+ const record2 = tool;
37354
+ if (typeof record2.name !== "string" || record2.name.length === 0) {
37288
37355
  throw new AiConfigError("AI tool requires a non-empty string 'name'");
37289
37356
  }
37290
- if (typeof record.description !== "string") {
37357
+ if (typeof record2.description !== "string") {
37291
37358
  throw new AiConfigError("AI tool requires a string 'description'");
37292
37359
  }
37293
- if (!record.parameters || typeof record.parameters !== "object" || Array.isArray(record.parameters)) {
37360
+ if (!record2.parameters || typeof record2.parameters !== "object" || Array.isArray(record2.parameters)) {
37294
37361
  throw new AiConfigError("AI tool requires a JSON-Schema object 'parameters'");
37295
37362
  }
37296
37363
  }
@@ -37307,8 +37374,8 @@ var init_aiClient = __esm({
37307
37374
  return;
37308
37375
  }
37309
37376
  if (choice && typeof choice === "object" && !Array.isArray(choice)) {
37310
- const record = choice;
37311
- if (typeof record.name !== "string" || record.name.length === 0) {
37377
+ const record2 = choice;
37378
+ if (typeof record2.name !== "string" || record2.name.length === 0) {
37312
37379
  throw new AiConfigError("AI toolChoice object requires a non-empty string 'name'");
37313
37380
  }
37314
37381
  return;
@@ -38373,38 +38440,37 @@ function runAll(options = {}) {
38373
38440
  const { quiet = false, failfast = false } = options;
38374
38441
  const results = { passed: 0, failed: 0, errors: 0, details: [] };
38375
38442
  for (const entry of registry2) {
38376
- if (!quiet) {
38377
- console.log(`
38443
+ if (!quiet) console.log(`
38378
38444
  ${entry.name}`);
38445
+ for (const assertion of entry.assertions) {
38446
+ const label = assertionLabel(assertion, entry.name);
38447
+ const ok = record(results, label, quiet, () => judge(assertion, callSync(entry.fn, assertion.args)));
38448
+ if (!ok && failfast) {
38449
+ printSummary(results, quiet);
38450
+ return results;
38451
+ }
38379
38452
  }
38453
+ }
38454
+ printSummary(results, quiet);
38455
+ return results;
38456
+ }
38457
+ async function runAllAsync(options = {}) {
38458
+ const { quiet = false, failfast = false, timeoutMs = 3e4 } = options;
38459
+ checkTimeout(timeoutMs);
38460
+ const results = { passed: 0, failed: 0, errors: 0, details: [] };
38461
+ for (const entry of registry2) {
38462
+ if (!quiet) console.log(`
38463
+ ${entry.name}`);
38380
38464
  for (const assertion of entry.assertions) {
38381
38465
  const label = assertionLabel(assertion, entry.name);
38382
- try {
38383
- runAssertion(entry.fn, assertion);
38384
- results.passed++;
38385
- results.details.push({ name: label, status: "passed" });
38386
- if (!quiet) {
38387
- console.log(` \x1B[32m+\x1B[0m ${label}`);
38388
- }
38389
- } catch (err) {
38390
- if (err instanceof TestAssertionError) {
38391
- results.failed++;
38392
- results.details.push({ name: label, status: "failed", message: err.message });
38393
- if (!quiet) {
38394
- console.log(` \x1B[31mx\x1B[0m ${label}: ${err.message}`);
38395
- }
38396
- } else {
38397
- results.errors++;
38398
- const msg = err instanceof Error ? `${err.constructor.name}: ${err.message}` : String(err);
38399
- results.details.push({ name: label, status: "error", message: msg });
38400
- if (!quiet) {
38401
- console.log(` \x1B[33m!\x1B[0m ${label}: ${msg}`);
38402
- }
38403
- }
38404
- if (failfast) {
38405
- printSummary(results, quiet);
38406
- return results;
38407
- }
38466
+ const outcome = await callAsync(entry.fn, assertion.args, timeoutMs);
38467
+ const ok = record(results, label, quiet, () => {
38468
+ if (outcome instanceof TestRunError) throw outcome;
38469
+ judge(assertion, outcome);
38470
+ });
38471
+ if (!ok && failfast) {
38472
+ printSummary(results, quiet);
38473
+ return results;
38408
38474
  }
38409
38475
  }
38410
38476
  }
@@ -38414,47 +38480,103 @@ function runAll(options = {}) {
38414
38480
  function reset() {
38415
38481
  registry2.length = 0;
38416
38482
  }
38417
- function runAssertion(fn, assertion) {
38418
- const { type: type2, args } = assertion;
38483
+ function isThenable(value) {
38484
+ return value !== null && (typeof value === "object" || typeof value === "function") && typeof value.then === "function";
38485
+ }
38486
+ function callSync(fn, args) {
38487
+ let value;
38488
+ try {
38489
+ value = fn(...args);
38490
+ } catch (error2) {
38491
+ return { threw: true, error: error2 };
38492
+ }
38493
+ if (isThenable(value)) {
38494
+ Promise.resolve(value).then(void 0, () => void 0);
38495
+ throw new TestRunError(
38496
+ "returned a Promise (async test function): runAll() cannot judge it, use await runAllAsync()"
38497
+ );
38498
+ }
38499
+ return { threw: false, value };
38500
+ }
38501
+ function checkTimeout(timeoutMs) {
38502
+ if (timeoutMs === Infinity) return;
38503
+ if (!(timeoutMs > 0 && timeoutMs <= MAX_TIMER_MS)) {
38504
+ throw new RangeError(
38505
+ `timeoutMs must be Infinity or a number of milliseconds in (0, ${MAX_TIMER_MS}], got ${timeoutMs}`
38506
+ );
38507
+ }
38508
+ }
38509
+ async function callAsync(fn, args, timeoutMs) {
38510
+ let timer;
38511
+ try {
38512
+ const value = fn(...args);
38513
+ if (!isThenable(value)) return { threw: false, value };
38514
+ if (timeoutMs === Infinity) return { threw: false, value: await value };
38515
+ const timeout = new Promise((_, reject) => {
38516
+ timer = setTimeout(
38517
+ () => reject(new TestRunError(`did not settle within ${timeoutMs} ms`)),
38518
+ timeoutMs
38519
+ );
38520
+ });
38521
+ return { threw: false, value: await Promise.race([Promise.resolve(value), timeout]) };
38522
+ } catch (error2) {
38523
+ if (error2 instanceof TestRunError) return error2;
38524
+ return { threw: true, error: error2 };
38525
+ } finally {
38526
+ if (timer !== void 0) clearTimeout(timer);
38527
+ }
38528
+ }
38529
+ function record(results, label, quiet, check) {
38530
+ try {
38531
+ check();
38532
+ results.passed++;
38533
+ results.details.push({ name: label, status: "passed" });
38534
+ if (!quiet) console.log(` \x1B[32m+\x1B[0m ${label}`);
38535
+ return true;
38536
+ } catch (err) {
38537
+ if (err instanceof TestAssertionError) {
38538
+ results.failed++;
38539
+ results.details.push({ name: label, status: "failed", message: err.message });
38540
+ if (!quiet) console.log(` \x1B[31mx\x1B[0m ${label}: ${err.message}`);
38541
+ } else {
38542
+ results.errors++;
38543
+ const msg = err instanceof Error ? `${err.constructor.name}: ${err.message}` : String(err);
38544
+ results.details.push({ name: label, status: "error", message: msg });
38545
+ if (!quiet) console.log(` \x1B[33m!\x1B[0m ${label}: ${msg}`);
38546
+ }
38547
+ return false;
38548
+ }
38549
+ }
38550
+ function judgeRaises(assertion, outcome) {
38551
+ const ExcClass = assertion.exception;
38552
+ if (!outcome.threw) throw new TestAssertionError(`expected ${ExcClass.name} to be raised`);
38553
+ const err = outcome.error;
38554
+ if (err instanceof ExcClass) return;
38555
+ throw new TestAssertionError(
38556
+ `expected ${ExcClass.name}, got ${err instanceof Error ? err.constructor.name : typeof err}: ${err}`
38557
+ );
38558
+ }
38559
+ function judge(assertion, outcome) {
38560
+ const { type: type2 } = assertion;
38561
+ if (type2 === "raises") return judgeRaises(assertion, outcome);
38562
+ if (outcome.threw) throw outcome.error;
38563
+ const result = outcome.value;
38419
38564
  switch (type2) {
38420
38565
  case "equal": {
38421
- const result = fn(...args);
38422
38566
  const expected = assertion.expected;
38423
38567
  if (result !== expected) {
38424
38568
  throw new TestAssertionError(
38425
38569
  `expected ${JSON.stringify(expected)}, got ${JSON.stringify(result)}`
38426
38570
  );
38427
38571
  }
38428
- break;
38429
- }
38430
- case "raises": {
38431
- const ExcClass = assertion.exception;
38432
- try {
38433
- fn(...args);
38434
- } catch (err) {
38435
- if (err instanceof ExcClass) {
38436
- return;
38437
- }
38438
- throw new TestAssertionError(
38439
- `expected ${ExcClass.name}, got ${err instanceof Error ? err.constructor.name : typeof err}: ${err}`
38440
- );
38441
- }
38442
- throw new TestAssertionError(`expected ${ExcClass.name} to be raised`);
38443
- }
38444
- case "true": {
38445
- const result = fn(...args);
38446
- if (!result) {
38447
- throw new TestAssertionError(`expected truthy, got ${JSON.stringify(result)}`);
38448
- }
38449
- break;
38450
- }
38451
- case "false": {
38452
- const result = fn(...args);
38453
- if (result) {
38454
- throw new TestAssertionError(`expected falsy, got ${JSON.stringify(result)}`);
38455
- }
38456
- break;
38572
+ return;
38457
38573
  }
38574
+ case "true":
38575
+ if (!result) throw new TestAssertionError(`expected truthy, got ${JSON.stringify(result)}`);
38576
+ return;
38577
+ case "false":
38578
+ if (result) throw new TestAssertionError(`expected falsy, got ${JSON.stringify(result)}`);
38579
+ return;
38458
38580
  default:
38459
38581
  throw new Error(`unknown assertion type: ${type2}`);
38460
38582
  }
@@ -38483,7 +38605,7 @@ function printSummary(results, quiet) {
38483
38605
  `
38484
38606
  );
38485
38607
  }
38486
- var registry2, TestAssertionError;
38608
+ var registry2, TestAssertionError, TestRunError, MAX_TIMER_MS;
38487
38609
  var init_testing = __esm({
38488
38610
  "../core/src/testing.ts"() {
38489
38611
  "use strict";
@@ -38494,6 +38616,13 @@ var init_testing = __esm({
38494
38616
  this.name = "TestAssertionError";
38495
38617
  }
38496
38618
  };
38619
+ TestRunError = class extends Error {
38620
+ constructor(message) {
38621
+ super(message);
38622
+ this.name = "TestRunError";
38623
+ }
38624
+ };
38625
+ MAX_TIMER_MS = 2147483647;
38497
38626
  }
38498
38627
  });
38499
38628
 
@@ -39309,6 +39438,7 @@ __export(src_exports2, {
39309
39438
  resolveTemplate: () => resolveTemplate,
39310
39439
  responseCache: () => responseCache,
39311
39440
  runAll: () => runAll,
39441
+ runAllAsync: () => runAllAsync,
39312
39442
  runRouteMiddlewares: () => runRouteMiddlewares,
39313
39443
  runWithCspNonce: () => runWithCspNonce,
39314
39444
  runtimeDir: () => runtimeDir,
@@ -42322,11 +42452,11 @@ var init_firebird = __esm({
42322
42452
  */
42323
42453
  async decodeBlobs(row) {
42324
42454
  if (row === null || typeof row !== "object") return row;
42325
- const record = row;
42326
- for (const key of Object.keys(record)) {
42327
- if (typeof record[key] === "function") {
42328
- record[key] = await this.readBlob(
42329
- record[key]
42455
+ const record2 = row;
42456
+ for (const key of Object.keys(record2)) {
42457
+ if (typeof record2[key] === "function") {
42458
+ record2[key] = await this.readBlob(
42459
+ record2[key]
42330
42460
  );
42331
42461
  }
42332
42462
  }
@@ -46700,12 +46830,12 @@ function crudSortProp(model, requested, pkProp) {
46700
46830
  }
46701
46831
  return pkProp;
46702
46832
  }
46703
- function cellValue(record, col) {
46704
- return record[col];
46833
+ function cellValue(record2, col) {
46834
+ return record2[col];
46705
46835
  }
46706
- function buildCells(columns, record, editable, aligns) {
46836
+ function buildCells(columns, record2, editable, aligns) {
46707
46837
  return columns.map((col, index) => {
46708
- const raw = cellValue(record, col);
46838
+ const raw = cellValue(record2, col);
46709
46839
  const value = h(raw === null || raw === void 0 ? "" : raw);
46710
46840
  const css = aligns[index];
46711
46841
  return editable ? `<td class="${css}" contenteditable="true" data-field="${h(col)}">${value}</td>` : `<td class="${css}">${value}</td>`;
@@ -46868,9 +46998,9 @@ function headerCell(opts, col, align) {
46868
46998
  function tableData(opts) {
46869
46999
  const aligns = opts.columns.map((col) => columnAlignment(opts.model, col));
46870
47000
  const headers = opts.columns.map((col, index) => headerCell(opts, col, aligns[index]));
46871
- const rows = opts.records.map((record) => ({
46872
- id: h(cellValue(record, opts.pk) ?? ""),
46873
- cells: buildCells(opts.columns, record, opts.editable, aligns)
47001
+ const rows = opts.records.map((record2) => ({
47002
+ id: h(cellValue(record2, opts.pk) ?? ""),
47003
+ cells: buildCells(opts.columns, record2, opts.editable, aligns)
46874
47004
  }));
46875
47005
  return {
46876
47006
  headers,
@@ -47999,9 +48129,9 @@ async function eagerLoadHasRelation(instances, model, relatedClass, relationName
47999
48129
  if (nested.length > 0 && related.length > 0) await relatedClass._eagerLoad(related, nested);
48000
48130
  const fkProp = reverseMappedColumn(relatedClass, relation.foreignKey);
48001
48131
  const grouped = {};
48002
- for (const record of related) {
48003
- const key = _joinKey(record[fkProp]);
48004
- (grouped[key] ??= []).push(record);
48132
+ for (const record2 of related) {
48133
+ const key = _joinKey(record2[fkProp]);
48134
+ (grouped[key] ??= []).push(record2);
48005
48135
  }
48006
48136
  for (const instance of instances) {
48007
48137
  const records = grouped[_joinKey(instance[pk])] ?? [];
@@ -48017,7 +48147,7 @@ async function eagerLoadBelongsToRelation(instances, model, relatedClass, relati
48017
48147
  const related = await eagerQueryRelated(relatedClass, relatedPkColumn, values);
48018
48148
  if (nested.length > 0 && related.length > 0) await relatedClass._eagerLoad(related, nested);
48019
48149
  const lookup2 = {};
48020
- for (const record of related) lookup2[_joinKey(record[relatedPk])] = record;
48150
+ for (const record2 of related) lookup2[_joinKey(record2[relatedPk])] = record2;
48021
48151
  for (const instance of instances) {
48022
48152
  const value = instance[fkProp];
48023
48153
  relationshipCache(instance)[relationName] = value !== void 0 && value !== null ? lookup2[_joinKey(value)] ?? null : null;
@@ -50732,7 +50862,7 @@ var init_bolt = __esm({
50732
50862
  const session = this.database ? this.driver.session({ database: this.database }) : this.driver.session();
50733
50863
  try {
50734
50864
  const result = await session.run(cypher, params ?? {});
50735
- return result.records.map((record) => record.toObject());
50865
+ return result.records.map((record2) => record2.toObject());
50736
50866
  } catch (exc) {
50737
50867
  this.lastError = errorMessage(exc);
50738
50868
  const code = exc?.code ?? "";