@phala/cloud 0.6.3 → 0.6.4

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.
package/dist/index.mjs CHANGED
@@ -440,7 +440,7 @@ function defaultUserAgent(runtime = globalThis) {
440
440
  if (runtime.window !== void 0 && runtime.document !== void 0) {
441
441
  return void 0;
442
442
  }
443
- const product = "phala-cloud-sdk-js/0.6.3";
443
+ const product = "phala-cloud-sdk-js/0.6.4";
444
444
  const token = runtimeToken(runtime);
445
445
  return token ? `${product} ${token}` : product;
446
446
  }
@@ -7518,20 +7518,24 @@ function parseRfc3339(value) {
7518
7518
  if (year < 1 || month < 1 || month > 12 || day < 1 || day > daysInMonth || hour > 23 || minute > 59 || second > 59 || offsetHour > 23 || offsetMinute > 59) {
7519
7519
  return void 0;
7520
7520
  }
7521
- const fractionalMilliseconds = fraction ? Number(`0.${fraction}`) * 1e3 : 0;
7522
7521
  const offset = sign === "+" ? 1 : sign === "-" ? -1 : 0;
7523
- const offsetMilliseconds = offset * (offsetHour * 60 + offsetMinute) * 6e4;
7522
+ const offsetSeconds = offset * (offsetHour * 60 + offsetMinute) * 60;
7524
7523
  const date = /* @__PURE__ */ new Date(0);
7525
7524
  date.setUTCFullYear(year, month - 1, day);
7526
7525
  date.setUTCHours(hour, minute, second, 0);
7527
- return date.getTime() + fractionalMilliseconds - offsetMilliseconds;
7526
+ const seconds = Math.floor(date.getTime() / 1e3) - offsetSeconds;
7527
+ const fractionNonZero = Boolean(fraction && /[1-9]/.test(fraction));
7528
+ return { seconds, fractionNonZero };
7528
7529
  }
7529
- function parseLogTime(value, nowMs) {
7530
+ function resolveLogInstant(value, nowMs, ceil) {
7531
+ if (typeof value === "number") {
7532
+ return ceil ? Math.ceil(value) : Math.floor(value);
7533
+ }
7530
7534
  if (/^-?\d+$/.test(value)) {
7531
7535
  const seconds = Number(value);
7532
7536
  const milliseconds = seconds * 1e3;
7533
7537
  if (Number.isSafeInteger(seconds) && Number.isSafeInteger(milliseconds)) {
7534
- return milliseconds;
7538
+ return seconds;
7535
7539
  }
7536
7540
  }
7537
7541
  const relative = /^(\d+)([smhd])$/.exec(value);
@@ -7545,18 +7549,20 @@ function parseLogTime(value, nowMs) {
7545
7549
  const duration = Number(relative[1]) * (DURATION_SECONDS[unit] ?? 0);
7546
7550
  const milliseconds = nowMs - duration * 1e3;
7547
7551
  if (Number.isFinite(milliseconds) && Number.isSafeInteger(Math.floor(milliseconds / 1e3))) {
7548
- return milliseconds;
7552
+ return ceil ? Math.ceil(milliseconds / 1e3) : Math.floor(milliseconds / 1e3);
7549
7553
  }
7550
7554
  }
7551
7555
  const rfc3339 = parseRfc3339(value);
7552
- if (rfc3339 !== void 0) return rfc3339;
7556
+ if (rfc3339 !== void 0) {
7557
+ return ceil && rfc3339.fractionNonZero ? rfc3339.seconds + 1 : rfc3339.seconds;
7558
+ }
7553
7559
  throw new Error(
7554
7560
  `Invalid log time '${value}'. Use RFC3339, Unix seconds, or a relative duration such as 10m.`
7555
7561
  );
7556
7562
  }
7557
7563
  function resolveLogTimeWindow(since, until, nowMs = Date.now()) {
7558
- const resolvedSince = since === void 0 ? void 0 : typeof since === "number" ? Math.floor(since) : Math.floor(parseLogTime(since, nowMs) / 1e3);
7559
- const resolvedUntil = until === void 0 ? void 0 : typeof until === "number" ? Math.ceil(until) : Math.ceil(parseLogTime(until, nowMs) / 1e3);
7564
+ const resolvedSince = since === void 0 ? void 0 : resolveLogInstant(since, nowMs, false);
7565
+ const resolvedUntil = until === void 0 ? void 0 : resolveLogInstant(until, nowMs, true);
7560
7566
  if (resolvedSince !== void 0 && !Number.isSafeInteger(resolvedSince) || resolvedUntil !== void 0 && !Number.isSafeInteger(resolvedUntil)) {
7561
7567
  throw new Error("Log time is outside the supported Unix seconds range.");
7562
7568
  }
@@ -7568,42 +7574,46 @@ function resolveLogTimeWindow(since, until, nowMs = Date.now()) {
7568
7574
 
7569
7575
  // src/actions/cvms/logs.ts
7570
7576
  var CVM_LOGS_INFO_API_VERSION = "2026-01-21";
7571
- var LOG_ERROR_HTTP_STATUS = {
7572
- "ERR-17-001": 400,
7573
- "ERR-17-002": 401,
7574
- "ERR-17-003": 401,
7575
- "ERR-17-004": 404,
7576
- "ERR-17-005": 409,
7577
- "ERR-17-006": 409,
7578
- "ERR-17-007": 404,
7579
- "ERR-17-008": 502,
7580
- "ERR-17-009": 502,
7581
- "ERR-17-010": 504,
7582
- "ERR-17-011": 429,
7583
- "ERR-17-012": 503,
7584
- "ERR-17-013": 404
7585
- };
7586
- function logErrorHttpStatus(code) {
7587
- return LOG_ERROR_HTTP_STATUS[code];
7577
+ var LOG_CHANNELS = /* @__PURE__ */ new Set(["stdout", "stderr", "stdin", "console"]);
7578
+ function logFetchHeaders(client) {
7579
+ const headers = new Headers();
7580
+ const ua = defaultUserAgent();
7581
+ if (ua) headers.set("User-Agent", ua);
7582
+ const extra = client.config?.headers;
7583
+ if (extra) {
7584
+ new Headers(extra).forEach((value, key) => {
7585
+ if (key.toLowerCase() === "user-agent") headers.set("User-Agent", value);
7586
+ });
7587
+ }
7588
+ return headers;
7589
+ }
7590
+ function logFetch(client, url, signal) {
7591
+ return fetch(url, {
7592
+ method: "GET",
7593
+ headers: logFetchHeaders(client),
7594
+ signal,
7595
+ redirect: "manual"
7596
+ });
7588
7597
  }
7589
7598
  var LogAccessError = class extends ResourceError {
7590
7599
  constructor(options) {
7591
7600
  const details = options.message;
7592
- const suggestionText = options.suggestions?.length ? `
7593
- Suggestions:
7594
- ${options.suggestions.map((suggestion) => `- ${suggestion}`).join("\n")}` : "";
7595
- const status = options.fromStreamBody ? 0 : options.httpStatus ?? (options.code ? logErrorHttpStatus(options.code) : void 0) ?? 0;
7596
- super(`${details}${suggestionText}`, {
7601
+ const status = options.fromStreamBody ? 0 : options.httpStatus && options.httpStatus > 0 ? options.httpStatus : 0;
7602
+ super(details, {
7597
7603
  status,
7598
7604
  statusText: "",
7599
7605
  errorCode: options.code,
7600
- suggestions: options.suggestions ? [...options.suggestions] : void 0
7606
+ suggestions: options.suggestions ? [...options.suggestions] : void 0,
7607
+ requestId: options.requestId,
7608
+ structuredDetails: options.details,
7609
+ links: options.links
7601
7610
  });
7602
7611
  this.name = "LogAccessError";
7603
7612
  this.code = options.code;
7604
- this.httpStatus = status || void 0;
7613
+ this.httpStatus = options.fromStreamBody || !options.httpStatus || options.httpStatus <= 0 ? void 0 : options.httpStatus;
7605
7614
  this.suggestions = options.suggestions ? [...options.suggestions] : [];
7606
7615
  this.fromStreamBody = options.fromStreamBody === true;
7616
+ this.gatewayStream = options.gatewayStream === true;
7607
7617
  }
7608
7618
  };
7609
7619
  function resolveCvmId(id) {
@@ -7621,12 +7631,13 @@ function buildLogUrl(baseUrl, options) {
7621
7631
  const sep = baseUrl.includes("?") ? "&" : "?";
7622
7632
  return params.length > 0 ? `${baseUrl}${sep}${params.join("&")}` : baseUrl;
7623
7633
  }
7624
- async function streamResponse(response, onData) {
7634
+ async function streamResponse(response, onData, markDelivered, ansi) {
7625
7635
  const reader = response.body?.getReader();
7626
7636
  if (!reader) throw new Error("No response body available for streaming");
7627
7637
  const decoder = new TextDecoder();
7628
7638
  let buffer = "";
7629
7639
  let finished = false;
7640
+ let delivered = false;
7630
7641
  try {
7631
7642
  while (true) {
7632
7643
  const { done, value } = await reader.read();
@@ -7638,7 +7649,9 @@ async function streamResponse(response, onData) {
7638
7649
  const content = line.replace(/\r?\n$/, "");
7639
7650
  if (content !== "[vmm heartbeat]" && content !== "[teepod heartbeat]") {
7640
7651
  throwTextStreamError(content);
7641
- onData(line);
7652
+ markDelivered?.();
7653
+ onData(applyAnsiPolicy(line, ansi));
7654
+ delivered = true;
7642
7655
  }
7643
7656
  newline = buffer.indexOf("\n");
7644
7657
  }
@@ -7649,13 +7662,16 @@ async function streamResponse(response, onData) {
7649
7662
  }
7650
7663
  if (buffer && buffer !== "[vmm heartbeat]" && buffer !== "[teepod heartbeat]") {
7651
7664
  throwTextStreamError(buffer);
7652
- onData(buffer);
7665
+ markDelivered?.();
7666
+ onData(applyAnsiPolicy(buffer, ansi));
7667
+ delivered = true;
7653
7668
  }
7654
7669
  } finally {
7655
7670
  if (!finished) await reader.cancel().catch(() => {
7656
7671
  });
7657
7672
  reader.releaseLock();
7658
7673
  }
7674
+ return delivered;
7659
7675
  }
7660
7676
  async function throwResponseError(response) {
7661
7677
  const body = await response.text();
@@ -7668,16 +7684,35 @@ async function throwResponseError(response) {
7668
7684
  const suggestions = Array.isArray(envelope.suggestions) ? envelope.suggestions.filter((item) => typeof item === "string") : [];
7669
7685
  throw new LogAccessError({
7670
7686
  code: typeof envelope.error_code === "string" ? envelope.error_code : void 0,
7671
- message: typeof envelope.message === "string" ? envelope.message : `HTTP ${response.status} ${response.statusText}`,
7687
+ message: typeof envelope.message === "string" ? envelope.message : `HTTP ${response.status}`,
7672
7688
  httpStatus: response.status,
7673
- suggestions
7689
+ suggestions,
7690
+ requestId: typeof envelope.request_id === "string" ? envelope.request_id : void 0,
7691
+ details: Array.isArray(envelope.details) ? envelope.details : void 0,
7692
+ links: Array.isArray(envelope.links) ? envelope.links : void 0
7674
7693
  });
7675
7694
  }
7695
+ function backoffDelayMs(attempt) {
7696
+ return Math.min(250 * 2 ** (Math.min(Math.max(attempt, 1), 6) - 1), 5e3);
7697
+ }
7676
7698
  function throwTextStreamError(line) {
7677
7699
  const match = /^\[error\] (ERR-17-\d{3}) (.*)$/.exec(line.trim());
7678
7700
  const code = match?.[1];
7679
7701
  const message = match?.[2];
7680
- if (code && message !== void 0) throw new LogAccessError({ code, message });
7702
+ if (code && message !== void 0) {
7703
+ throw new LogAccessError({
7704
+ code,
7705
+ message,
7706
+ gatewayStream: true
7707
+ });
7708
+ }
7709
+ }
7710
+ function throwIfTextBodyErrors(text) {
7711
+ throwIfGuestAgentError(text);
7712
+ for (const line of text.split(/\r?\n/)) throwTextStreamError(line);
7713
+ }
7714
+ function throwIfGatewayTextErrors(text) {
7715
+ for (const line of text.split(/\r?\n/)) throwTextStreamError(line);
7681
7716
  }
7682
7717
  function parseTimestampedMessage(message) {
7683
7718
  const match = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})) (.*)$/s.exec(
@@ -7692,13 +7727,9 @@ function parseTimestampedMessage(message) {
7692
7727
  message: match[2]
7693
7728
  };
7694
7729
  }
7695
- function formatFollowContainerEntry(entry, includeTimestamps) {
7696
- if (includeTimestamps) return { channel: entry.channel, message: entry.message };
7697
- const timestamp = parseTimestampedMessage(entry.message);
7698
- return {
7699
- channel: entry.channel,
7700
- message: timestamp.timestamp ? timestamp.message ?? "" : entry.message
7701
- };
7730
+ function formatFollowContainerEntry(entry, includeTimestamps, ansi) {
7731
+ const raw = includeTimestamps ? entry.message : parseTimestampedMessage(entry.message).timestamp ? parseTimestampedMessage(entry.message).message ?? "" : entry.message;
7732
+ return { channel: entry.channel, message: applyAnsiPolicy(raw, ansi) };
7702
7733
  }
7703
7734
  function guestAgentErrorMessage(text) {
7704
7735
  const trimmed = text.trim();
@@ -7714,6 +7745,18 @@ function guestAgentErrorMessage(text) {
7714
7745
  return void 0;
7715
7746
  }
7716
7747
  function throwIfGuestAgentError(text) {
7748
+ const taken = takeJsonObject(text);
7749
+ if (taken) {
7750
+ const parsed = taken.value;
7751
+ if (typeof parsed.error === "string" && parsed.channel === void 0 && parsed.message === void 0) {
7752
+ throw new LogAccessError({
7753
+ code: "ERR-17-009",
7754
+ message: parsed.error,
7755
+ fromStreamBody: true
7756
+ });
7757
+ }
7758
+ return;
7759
+ }
7717
7760
  const message = guestAgentErrorMessage(text);
7718
7761
  if (message !== void 0) {
7719
7762
  throw new LogAccessError({
@@ -7723,6 +7766,51 @@ function throwIfGuestAgentError(text) {
7723
7766
  });
7724
7767
  }
7725
7768
  }
7769
+ var ANSI_PATTERN = /\x1b(?:\][^\x07\x1b]*(?:\x07|\x1b\\)|\[[0-?]*[ -/]*[@-~]|[ -/]*[0-~])/g;
7770
+ function stripAnsi(text) {
7771
+ return text.replace(ANSI_PATTERN, "");
7772
+ }
7773
+ function applyAnsiPolicy(text, ansi) {
7774
+ return ansi ? text : stripAnsi(text);
7775
+ }
7776
+ function takeJsonObject(buffer) {
7777
+ let i = 0;
7778
+ while (i < buffer.length && /[\s]/.test(buffer[i])) i += 1;
7779
+ if (buffer[i] !== "{") return null;
7780
+ let depth = 0;
7781
+ let inString = false;
7782
+ let escaped = false;
7783
+ for (let j = i; j < buffer.length; j += 1) {
7784
+ const char = buffer[j];
7785
+ if (inString) {
7786
+ if (escaped) {
7787
+ escaped = false;
7788
+ continue;
7789
+ }
7790
+ if (char === "\\") {
7791
+ escaped = true;
7792
+ continue;
7793
+ }
7794
+ if (char === '"') inString = false;
7795
+ continue;
7796
+ }
7797
+ if (char === '"') {
7798
+ inString = true;
7799
+ continue;
7800
+ }
7801
+ if (char === "{") depth += 1;
7802
+ else if (char === "}") {
7803
+ depth -= 1;
7804
+ if (depth === 0) {
7805
+ return {
7806
+ value: JSON.parse(buffer.slice(i, j + 1)),
7807
+ rest: buffer.slice(j + 1)
7808
+ };
7809
+ }
7810
+ }
7811
+ }
7812
+ return null;
7813
+ }
7726
7814
  function parseStructuredLogLineToEntry(line) {
7727
7815
  const trimmed = line.trim();
7728
7816
  if (!trimmed) return null;
@@ -7743,10 +7831,14 @@ function parseStructuredLogLineToEntry(line) {
7743
7831
  throw new LogAccessError({
7744
7832
  code: parsed.error_code,
7745
7833
  message: typeof parsed.message === "string" ? parsed.message : "The log stream ended with an error.",
7746
- suggestions: Array.isArray(parsed.suggestions) ? parsed.suggestions.filter((item) => typeof item === "string") : []
7834
+ gatewayStream: true,
7835
+ suggestions: Array.isArray(parsed.suggestions) ? parsed.suggestions.filter((item) => typeof item === "string") : [],
7836
+ details: Array.isArray(parsed.details) ? parsed.details : void 0,
7837
+ links: Array.isArray(parsed.links) ? parsed.links : void 0,
7838
+ requestId: typeof parsed.request_id === "string" ? parsed.request_id : void 0
7747
7839
  });
7748
7840
  }
7749
- if (parsed.channel !== "stdout" && parsed.channel !== "stderr" || typeof parsed.message !== "string") {
7841
+ if (!LOG_CHANNELS.has(parsed.channel) || typeof parsed.message !== "string") {
7750
7842
  throw new LogAccessError({ message: "Invalid NDJSON log record." });
7751
7843
  }
7752
7844
  const entry = {
@@ -7759,9 +7851,24 @@ function parseStructuredLogLineToEntry(line) {
7759
7851
  }
7760
7852
  function parseStructuredLogsToEntries(input) {
7761
7853
  const entries = [];
7762
- for (const line of input.split(/\r?\n/)) {
7763
- const entry = parseStructuredLogLineToEntry(line);
7854
+ let buffer = input;
7855
+ while (buffer.length > 0) {
7856
+ const taken = takeJsonObject(buffer);
7857
+ if (!taken) {
7858
+ const newline = buffer.indexOf("\n");
7859
+ if (newline < 0) {
7860
+ const entry3 = parseStructuredLogLineToEntry(buffer);
7861
+ if (entry3) entries.push(entry3);
7862
+ break;
7863
+ }
7864
+ const entry2 = parseStructuredLogLineToEntry(buffer.slice(0, newline));
7865
+ if (entry2) entries.push(entry2);
7866
+ buffer = buffer.slice(newline + 1);
7867
+ continue;
7868
+ }
7869
+ const entry = parseStructuredLogLineToEntry(JSON.stringify(taken.value));
7764
7870
  if (entry) entries.push(entry);
7871
+ buffer = taken.rest;
7765
7872
  }
7766
7873
  return entries;
7767
7874
  }
@@ -7775,12 +7882,12 @@ async function streamNdjsonEntriesResponse(response, onEntry) {
7775
7882
  while (true) {
7776
7883
  const { done, value } = await reader.read();
7777
7884
  buffer += decoder.decode(value, { stream: !done });
7778
- let newline = buffer.indexOf("\n");
7779
- while (newline >= 0) {
7780
- const entry = parseStructuredLogLineToEntry(buffer.slice(0, newline));
7885
+ for (; ; ) {
7886
+ const taken = takeJsonObject(buffer);
7887
+ if (!taken) break;
7888
+ const entry = parseStructuredLogLineToEntry(JSON.stringify(taken.value));
7781
7889
  if (entry) onEntry(entry);
7782
- buffer = buffer.slice(newline + 1);
7783
- newline = buffer.indexOf("\n");
7890
+ buffer = taken.rest;
7784
7891
  }
7785
7892
  if (done) {
7786
7893
  finished = true;
@@ -7805,26 +7912,25 @@ function assertSupportedNodeLogOptions(options) {
7805
7912
  options.format === "ndjson" && "format=ndjson"
7806
7913
  ].filter((option) => Boolean(option));
7807
7914
  if (unsupported.length > 0) {
7808
- throw new Error(`${unsupported.join(", ")} not supported for serial/stdout/stderr logs`);
7809
- }
7810
- if (options.ansi && options.format === "ndjson") {
7811
- throw new LogAccessError({
7812
- code: "ERR-17-001",
7813
- message: "ansi is valid only with format=text"
7814
- });
7915
+ throw clientValidationError(
7916
+ `${unsupported.join(", ")} not supported for serial/stdout/stderr logs`
7917
+ );
7815
7918
  }
7816
7919
  }
7817
- async function getCvmInfoLogs(client, cvmId) {
7920
+ async function getCvmInfoLogs(client, cvmId, signal) {
7818
7921
  return await client.get(`/cvms/${cvmId}`, {
7819
- headers: { "X-Phala-Version": CVM_LOGS_INFO_API_VERSION }
7922
+ headers: { "X-Phala-Version": CVM_LOGS_INFO_API_VERSION },
7923
+ signal
7820
7924
  });
7821
7925
  }
7822
- async function getCvmLogEndpoint(client, id, channel) {
7926
+ async function getCvmLogEndpoint(client, id, channel, signal) {
7823
7927
  const cvmId = resolveCvmId(id);
7824
- const info = await getCvmInfoLogs(client, cvmId);
7928
+ const info = await getCvmInfoLogs(client, cvmId, signal);
7825
7929
  const endpoint = info.logs?.[channel];
7826
7930
  if (!endpoint) {
7827
- throw new Error(`No ${channel} log endpoint available for CVM '${cvmId}'`);
7931
+ throw new LogAccessError({
7932
+ message: `No ${channel} log endpoint available for CVM '${cvmId}'`
7933
+ });
7828
7934
  }
7829
7935
  return endpoint;
7830
7936
  }
@@ -7835,35 +7941,122 @@ function containerLogsDisabledError() {
7835
7941
  httpStatus: 409
7836
7942
  });
7837
7943
  }
7838
- async function assertContainerLogsEnabled(client, id) {
7839
- const info = await getCvmInfoLogs(client, resolveCvmId(id));
7840
- if (info.public_logs === false) {
7841
- throw containerLogsDisabledError();
7944
+ var CONTAINER_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/;
7945
+ function clientValidationError(message) {
7946
+ return new LogAccessError({ code: "ERR-17-001", message });
7947
+ }
7948
+ function resolveTimes(since, until) {
7949
+ try {
7950
+ return resolveLogTimeWindow(since, until);
7951
+ } catch (error) {
7952
+ throw clientValidationError(error instanceof Error ? error.message : String(error));
7842
7953
  }
7843
7954
  }
7844
- async function getContainerLogEndpoint(client, id, containerName, matchContainerIdPrefix = true) {
7845
- const cvmId = resolveCvmId(id);
7846
- const composition = await client.get(`/cvms/${cvmId}/composition`);
7847
- if (!composition.containers?.length) {
7848
- throw new Error(`No containers found for CVM '${cvmId}'`);
7955
+ function assertSafeContainerName(name) {
7956
+ if (!CONTAINER_NAME_RE.test(name) || name.includes("..")) {
7957
+ throw clientValidationError(
7958
+ `Invalid container name '${name}'. Use 1\u2013128 characters starting with a letter or digit, then letters, digits, '_', '.', and '-'.`
7959
+ );
7849
7960
  }
7850
- let containers = composition.containers;
7961
+ return name;
7962
+ }
7963
+ function assertContainerNameOption(name) {
7964
+ if (name) assertSafeContainerName(name);
7965
+ }
7966
+ function throwIfAborted(signal) {
7967
+ if (!signal?.aborted) return;
7968
+ const error = new Error("This operation was aborted");
7969
+ error.name = "AbortError";
7970
+ throw error;
7971
+ }
7972
+ function untilReached(until, cursorSince) {
7973
+ if (until === void 0) return false;
7974
+ if (cursorSince !== void 0 && cursorSince >= until) return true;
7975
+ return Math.floor(Date.now() / 1e3) >= until;
7976
+ }
7977
+ function joinContainerLogUrl(base2, name, authQuery) {
7978
+ const trimmed = base2.replace(/\/$/, "");
7979
+ const slug = assertSafeContainerName(name);
7980
+ const url = `${trimmed}/${slug}`;
7981
+ if (!authQuery) return url;
7982
+ return url.includes("?") ? `${url}&${authQuery}` : `${url}?${authQuery}`;
7983
+ }
7984
+ function reconnectSinceValue(cursorSince, first200Second, callerSince) {
7985
+ if (cursorSince !== void 0) return cursorSince;
7986
+ if (callerSince !== void 0) return callerSince;
7987
+ return first200Second;
7988
+ }
7989
+ function exactContainerNameMatch(container, name) {
7990
+ return container.names.some((n) => n === name || n === `/${name}`);
7991
+ }
7992
+ function containerSlug(container, fallback) {
7993
+ return container.names[0]?.replace(/^\//, "") ?? container.id ?? fallback;
7994
+ }
7995
+ async function resolveContainerSlug(client, id, containerName, matchContainerIdPrefix = true, signal) {
7996
+ throwIfAborted(signal);
7997
+ assertContainerNameOption(containerName);
7998
+ const cvmId = resolveCvmId(id);
7999
+ const composition = await client.get(`/cvms/${cvmId}/composition`, {
8000
+ signal
8001
+ });
8002
+ const containers = composition.containers ?? [];
8003
+ const compositionError = typeof composition.error === "string" && composition.error ? composition.error : void 0;
7851
8004
  if (containerName) {
7852
- containers = containers.filter((c) => {
7853
- const matchedByName = c.names.some((n) => n === containerName || n === `/${containerName}`);
7854
- if (matchedByName) return true;
7855
- if (!matchContainerIdPrefix) return false;
7856
- return c.id.startsWith(containerName);
7857
- });
7858
- if (!containers.length) {
7859
- throw new Error(`Container '${containerName}' not found in CVM '${cvmId}'`);
8005
+ const exact = containers.filter((item) => exactContainerNameMatch(item, containerName));
8006
+ if (exact[0]) return containerName;
8007
+ if (matchContainerIdPrefix) {
8008
+ const prefixed = containers.filter((item) => item.id.startsWith(containerName));
8009
+ if (prefixed.length > 1) {
8010
+ throw clientValidationError(
8011
+ `Ambiguous container prefix '${containerName}': ${prefixed.map((item) => item.names[0]?.replace(/^\//, "") ?? item.id).join(", ")}`
8012
+ );
8013
+ }
8014
+ if (prefixed[0]) return containerSlug(prefixed[0], containerName);
8015
+ }
8016
+ if (containers.length > 0) {
8017
+ throw new LogAccessError({ code: "ERR-17-007", message: "Container not found" });
8018
+ }
8019
+ if (compositionError) {
8020
+ throw new LogAccessError({ message: compositionError });
7860
8021
  }
8022
+ throw new LogAccessError({ code: "ERR-17-007", message: "Container not found" });
7861
8023
  }
7862
- const container = containers.find((c) => c.log_endpoint);
7863
- if (!container?.log_endpoint) {
7864
- throw new Error(`No log endpoints available for CVM '${cvmId}'`);
8024
+ if (compositionError) {
8025
+ throw new LogAccessError({ message: compositionError });
7865
8026
  }
7866
- return container.log_endpoint;
8027
+ if (!containers.length) {
8028
+ throw new LogAccessError({ code: "ERR-17-007", message: "Container not found" });
8029
+ }
8030
+ const fallback = containers[0];
8031
+ if (!fallback) {
8032
+ throw new LogAccessError({ code: "ERR-17-007", message: "Container not found" });
8033
+ }
8034
+ return containerSlug(fallback, "app");
8035
+ }
8036
+ async function loadCvmLogInfo(client, id, signal) {
8037
+ const info = await getCvmInfoLogs(client, resolveCvmId(id), signal);
8038
+ if (info.public_logs === false) {
8039
+ throw containerLogsDisabledError();
8040
+ }
8041
+ return info;
8042
+ }
8043
+ function urlFromLogInfo(info, slug, cvmId) {
8044
+ const base2 = info.logs?.container_log_base ?? null;
8045
+ if (!base2) {
8046
+ throw new LogAccessError({ message: `No log endpoints available for CVM '${cvmId}'` });
8047
+ }
8048
+ return joinContainerLogUrl(base2, slug, info.logs?.auth_query);
8049
+ }
8050
+ async function getContainerLogEndpoint(client, id, containerName, matchContainerIdPrefix = true, signal) {
8051
+ const info = await loadCvmLogInfo(client, id, signal);
8052
+ const slug = await resolveContainerSlug(
8053
+ client,
8054
+ id,
8055
+ containerName,
8056
+ matchContainerIdPrefix,
8057
+ signal
8058
+ );
8059
+ return urlFromLogInfo(info, slug, resolveCvmId(id));
7867
8060
  }
7868
8061
  function waitForReconnect(signal, delayMs) {
7869
8062
  if (signal?.aborted) return Promise.resolve();
@@ -7891,91 +8084,122 @@ function getErrorHttpStatus(error) {
7891
8084
  return void 0;
7892
8085
  }
7893
8086
  var EMPTY_STREAM_END_MESSAGE = "log stream keeps ending without new output; the container may have stopped";
7894
- async function followLogRequests(resolveUrl, consume, signal, refreshCvm, trackEmptyEnds = false) {
8087
+ var EMPTY_STREAM_QUIET_MS = 1e4;
8088
+ async function followLogRequests(client, resolveUrl, consume, signal, refreshCvm, trackEmptyEnds = false, onConnected, shouldStop) {
7895
8089
  let failureCount = 0;
7896
8090
  let expiredRetries = 0;
7897
8091
  let emptyEnds = 0;
8092
+ let lastConnectionStartedAt = 0;
8093
+ let haveStarted = false;
7898
8094
  while (!signal?.aborted) {
8095
+ if (haveStarted) {
8096
+ const waitMs = 1e3 - (performance.now() - lastConnectionStartedAt);
8097
+ if (waitMs > 0) await waitForReconnect(signal, waitMs);
8098
+ if (signal?.aborted) return;
8099
+ }
8100
+ lastConnectionStartedAt = performance.now();
8101
+ haveStarted = true;
8102
+ let deliveredThisConnection = false;
8103
+ const markDelivered = () => {
8104
+ deliveredThisConnection = true;
8105
+ };
7899
8106
  try {
7900
8107
  const url = await resolveUrl();
7901
8108
  if (signal?.aborted) return;
7902
- const response = await fetch(url, { signal });
8109
+ const response = await logFetch(client, url, signal);
7903
8110
  if (!response.ok) await throwResponseError(response);
7904
- failureCount = 0;
7905
- const delivered = await consume(response) ?? true;
8111
+ onConnected?.();
8112
+ const connectedAt = Date.now();
8113
+ const delivered = await consume(response, markDelivered) ?? deliveredThisConnection;
7906
8114
  expiredRetries = 0;
8115
+ if (delivered) {
8116
+ failureCount = 0;
8117
+ }
8118
+ if (shouldStop?.()) return;
7907
8119
  if (signal?.aborted) return;
7908
- if (trackEmptyEnds) {
7909
- if (delivered) {
7910
- emptyEnds = 0;
7911
- } else {
7912
- emptyEnds += 1;
7913
- if (emptyEnds >= 5) {
7914
- throw new LogAccessError({
7915
- message: EMPTY_STREAM_END_MESSAGE,
7916
- fromStreamBody: true
7917
- });
7918
- }
7919
- await waitForReconnect(signal, Math.min(250 * 2 ** (emptyEnds - 1), 5e3));
8120
+ if (delivered) {
8121
+ emptyEnds = 0;
8122
+ } else if (Date.now() - connectedAt >= EMPTY_STREAM_QUIET_MS) {
8123
+ emptyEnds = 0;
8124
+ } else {
8125
+ emptyEnds += 1;
8126
+ if (trackEmptyEnds && emptyEnds >= 5) {
8127
+ throw new LogAccessError({
8128
+ message: EMPTY_STREAM_END_MESSAGE,
8129
+ fromStreamBody: true
8130
+ });
7920
8131
  }
8132
+ await waitForReconnect(signal, backoffDelayMs(emptyEnds));
7921
8133
  }
7922
8134
  } catch (error) {
7923
8135
  if (signal?.aborted || error instanceof Error && error.name === "AbortError") {
7924
8136
  return;
7925
8137
  }
7926
- let retryError = error;
8138
+ const retryError = error;
7927
8139
  if (error instanceof LogAccessError && error.fromStreamBody) {
7928
8140
  throw error;
7929
8141
  }
7930
- if (error instanceof LogAccessError && error.code === "ERR-17-003") {
8142
+ emptyEnds = 0;
8143
+ if (deliveredThisConnection) {
8144
+ expiredRetries = 0;
8145
+ }
8146
+ if (error instanceof LogAccessError && !error.gatewayStream && error.code === "ERR-17-003") {
7931
8147
  expiredRetries += 1;
7932
8148
  if (expiredRetries > 3) throw error;
7933
- try {
7934
- await refreshCvm?.();
7935
- continue;
7936
- } catch (refreshError) {
7937
- retryError = refreshError;
7938
- }
8149
+ continue;
7939
8150
  }
7940
8151
  const status = getErrorHttpStatus(retryError);
7941
- if (status !== void 0 && status < 500) throw retryError;
7942
- if (retryError instanceof LogAccessError && status === void 0) {
8152
+ const code = retryError instanceof LogAccessError ? retryError.code : void 0;
8153
+ const gatewayStream = retryError instanceof LogAccessError && retryError.gatewayStream;
8154
+ if (!gatewayStream && code === "ERR-17-002") {
8155
+ } else if (gatewayStream || status === 429 || status !== void 0 && status >= 500 || retryError instanceof TypeError || retryError instanceof UnknownError) {
8156
+ } else {
7943
8157
  throw retryError;
7944
8158
  }
7945
- if (status === void 0 && !(retryError instanceof TypeError)) {
7946
- throw retryError;
8159
+ if (deliveredThisConnection) {
8160
+ failureCount = 0;
7947
8161
  }
7948
8162
  failureCount += 1;
7949
8163
  if (failureCount >= 5) throw retryError;
7950
- const delayMs = Math.min(250 * 2 ** (failureCount - 1), 5e3);
8164
+ const delayMs = backoffDelayMs(failureCount);
7951
8165
  await waitForReconnect(signal, delayMs);
7952
8166
  }
7953
8167
  }
7954
8168
  }
7955
8169
  async function fetchCvmChannelLogs(client, id, channel, options = {}) {
8170
+ throwIfAborted(options.signal);
7956
8171
  assertSupportedNodeLogOptions(options);
7957
- const times = resolveLogTimeWindow(options.since, options.until);
7958
- const baseUrl = await getCvmLogEndpoint(client, id, channel);
8172
+ const times = resolveTimes(options.since, options.until);
8173
+ const baseUrl = await getCvmLogEndpoint(client, id, channel, options.signal);
7959
8174
  const url = buildLogUrl(baseUrl, {
7960
8175
  since: times.since,
7961
8176
  until: times.until,
7962
8177
  tail: options.tail,
7963
8178
  ansi: options.ansi
7964
8179
  });
7965
- const response = await fetch(url, { signal: options.signal });
8180
+ const response = await logFetch(client, url, options.signal);
7966
8181
  if (!response.ok) await throwResponseError(response);
7967
- return response.text();
8182
+ const text = await response.text();
8183
+ throwIfGatewayTextErrors(text);
8184
+ return applyAnsiPolicy(
8185
+ text.split(/(?<=\n)/).filter((line) => {
8186
+ const content = line.replace(/\r?\n$/, "");
8187
+ return content !== "[vmm heartbeat]" && content !== "[teepod heartbeat]";
8188
+ }).join(""),
8189
+ options.ansi
8190
+ );
7968
8191
  }
7969
8192
  async function streamCvmChannelLogs(client, id, channel, onData, options = {}, signal) {
8193
+ throwIfAborted(signal ?? options.signal);
7970
8194
  assertSupportedNodeLogOptions(options);
7971
8195
  const abort = signal ?? options.signal;
7972
- const times = resolveLogTimeWindow(options.since, options.until);
8196
+ const times = resolveTimes(options.since, options.until);
7973
8197
  let firstRequest = true;
7974
8198
  await followLogRequests(
8199
+ client,
7975
8200
  async () => {
7976
- const baseUrl = await getCvmLogEndpoint(client, id, channel);
8201
+ const baseUrl = await getCvmLogEndpoint(client, id, channel, abort);
7977
8202
  const tail = firstRequest ? options.tail : 0;
7978
- firstRequest = false;
7979
8203
  return buildLogUrl(baseUrl, {
7980
8204
  since: times.since,
7981
8205
  until: times.until,
@@ -7984,42 +8208,50 @@ async function streamCvmChannelLogs(client, id, channel, onData, options = {}, s
7984
8208
  ansi: options.ansi
7985
8209
  });
7986
8210
  },
7987
- (response) => streamResponse(response, onData),
8211
+ (response, markDelivered) => streamResponse(response, onData, markDelivered, options.ansi),
7988
8212
  abort,
7989
- async () => {
7990
- await getCvmInfoLogs(client, resolveCvmId(id));
8213
+ void 0,
8214
+ false,
8215
+ () => {
8216
+ firstRequest = false;
7991
8217
  }
7992
8218
  );
7993
8219
  }
7994
8220
  async function fetchContainerLogsEntries(client, id, options = {}) {
7995
- const times = resolveLogTimeWindow(options.since, options.until);
7996
- await assertContainerLogsEnabled(client, id);
8221
+ throwIfAborted(options.signal);
8222
+ assertContainerNameOption(options.container);
8223
+ const times = resolveTimes(options.since, options.until);
7997
8224
  const baseUrl = await getContainerLogEndpoint(
7998
8225
  client,
7999
8226
  id,
8000
8227
  options.container,
8001
- options.matchContainerIdPrefix ?? true
8228
+ options.matchContainerIdPrefix ?? true,
8229
+ options.signal
8002
8230
  );
8003
8231
  const url = buildLogUrl(baseUrl, {
8004
8232
  ...times,
8005
8233
  tail: options.tail,
8006
8234
  timestamps: options.timestamps,
8007
- ansi: options.ansi,
8008
8235
  format: options.format ?? "ndjson"
8009
8236
  });
8010
- const response = await fetch(url, { signal: options.signal });
8237
+ const response = await logFetch(client, url, options.signal);
8011
8238
  if (!response.ok) await throwResponseError(response);
8012
- return parseStructuredLogsToEntries(await response.text());
8239
+ return parseStructuredLogsToEntries(await response.text()).map((entry) => ({
8240
+ ...entry,
8241
+ message: applyAnsiPolicy(entry.message, options.ansi)
8242
+ }));
8013
8243
  }
8014
8244
  async function fetchContainerLogs(client, id, options = {}) {
8245
+ throwIfAborted(options.signal);
8246
+ assertContainerNameOption(options.container);
8015
8247
  if (options.format === "text") {
8016
- const times = resolveLogTimeWindow(options.since, options.until);
8017
- await assertContainerLogsEnabled(client, id);
8248
+ const times = resolveTimes(options.since, options.until);
8018
8249
  const baseUrl = await getContainerLogEndpoint(
8019
8250
  client,
8020
8251
  id,
8021
8252
  options.container,
8022
- options.matchContainerIdPrefix ?? true
8253
+ options.matchContainerIdPrefix ?? true,
8254
+ options.signal
8023
8255
  );
8024
8256
  const url = buildLogUrl(baseUrl, {
8025
8257
  ...times,
@@ -8028,37 +8260,44 @@ async function fetchContainerLogs(client, id, options = {}) {
8028
8260
  ansi: options.ansi,
8029
8261
  format: "text"
8030
8262
  });
8031
- const response = await fetch(url, { signal: options.signal });
8263
+ const response = await logFetch(client, url, options.signal);
8032
8264
  if (!response.ok) await throwResponseError(response);
8033
8265
  const text = await response.text();
8034
- throwIfGuestAgentError(text);
8035
- return text;
8266
+ throwIfTextBodyErrors(text);
8267
+ return applyAnsiPolicy(text, options.ansi);
8036
8268
  }
8037
8269
  const entries = await fetchContainerLogsEntries(client, id, {
8038
8270
  ...options,
8039
8271
  format: "ndjson"
8040
8272
  });
8041
- return entries.map((entry) => entry.message === "" ? "\n" : entry.message).join("");
8273
+ return entries.map((entry) => entry.message).join("");
8042
8274
  }
8043
8275
  async function streamContainerLogsEntries(client, id, onEntry, options = {}, signal) {
8044
8276
  const abort = signal ?? options.signal;
8045
- const times = resolveLogTimeWindow(options.since, options.until);
8046
- await assertContainerLogsEnabled(client, id);
8047
- const cursor = { since: times.since, boundaryCounts: /* @__PURE__ */ new Map() };
8277
+ throwIfAborted(abort);
8278
+ assertContainerNameOption(options.container);
8279
+ const times = resolveTimes(options.since, options.until);
8280
+ const cursor = { boundaryCounts: /* @__PURE__ */ new Map() };
8048
8281
  let replayCounts = /* @__PURE__ */ new Map();
8049
8282
  let firstRequest = true;
8283
+ let first200Second;
8284
+ let slug;
8050
8285
  const buildRequestUrl = async () => {
8051
- const baseUrl = await getContainerLogEndpoint(
8052
- client,
8053
- id,
8054
- options.container,
8055
- options.matchContainerIdPrefix ?? true
8056
- );
8057
- const tail = firstRequest ? options.tail : void 0;
8058
- firstRequest = false;
8286
+ const info = await loadCvmLogInfo(client, id, abort);
8287
+ if (slug === void 0) {
8288
+ slug = await resolveContainerSlug(
8289
+ client,
8290
+ id,
8291
+ options.container,
8292
+ options.matchContainerIdPrefix ?? true,
8293
+ abort
8294
+ );
8295
+ }
8296
+ const baseUrl = urlFromLogInfo(info, slug, resolveCvmId(id));
8297
+ const tail = firstRequest ? options.tail : "all";
8059
8298
  replayCounts = new Map(cursor.boundaryCounts);
8060
8299
  return buildLogUrl(baseUrl, {
8061
- since: cursor.since,
8300
+ since: firstRequest ? times.since : reconnectSinceValue(cursor.since, first200Second, times.since),
8062
8301
  until: times.until,
8063
8302
  tail,
8064
8303
  follow: true,
@@ -8067,20 +8306,23 @@ async function streamContainerLogsEntries(client, id, onEntry, options = {}, sig
8067
8306
  });
8068
8307
  };
8069
8308
  await followLogRequests(
8309
+ client,
8070
8310
  buildRequestUrl,
8071
- async (response) => {
8311
+ async (response, markDelivered) => {
8072
8312
  let delivered = false;
8073
8313
  await streamNdjsonEntriesResponse(response, (entry) => {
8074
8314
  const timestamp = parseTimestampedMessage(entry.message);
8075
8315
  if (timestamp.second === void 0 || !timestamp.timestamp) {
8076
8316
  delivered = true;
8077
- onEntry(formatFollowContainerEntry(entry, options.timestamps ?? false));
8317
+ markDelivered();
8318
+ onEntry(formatFollowContainerEntry(entry, options.timestamps ?? false, options.ansi));
8078
8319
  return;
8079
8320
  }
8080
8321
  const key = JSON.stringify([entry.channel, entry.message]);
8081
8322
  if (cursor.boundarySecond !== void 0 && timestamp.second < cursor.boundarySecond) {
8082
8323
  delivered = true;
8083
- onEntry(formatFollowContainerEntry(entry, options.timestamps ?? false));
8324
+ markDelivered();
8325
+ onEntry(formatFollowContainerEntry(entry, options.timestamps ?? false, options.ansi));
8084
8326
  return;
8085
8327
  }
8086
8328
  if (timestamp.second === cursor.boundarySecond) {
@@ -8096,18 +8338,22 @@ async function streamContainerLogsEntries(client, id, onEntry, options = {}, sig
8096
8338
  cursor.since = Math.max(cursor.since ?? timestamp.second, timestamp.second);
8097
8339
  cursor.boundaryCounts.set(key, (cursor.boundaryCounts.get(key) ?? 0) + 1);
8098
8340
  delivered = true;
8099
- onEntry(formatFollowContainerEntry(entry, options.timestamps ?? false));
8341
+ markDelivered();
8342
+ onEntry(formatFollowContainerEntry(entry, options.timestamps ?? false, options.ansi));
8100
8343
  });
8101
8344
  return delivered;
8102
8345
  },
8103
8346
  abort,
8104
- async () => {
8105
- await assertContainerLogsEnabled(client, id);
8347
+ void 0,
8348
+ true,
8349
+ () => {
8350
+ firstRequest = false;
8351
+ if (first200Second === void 0) first200Second = Math.floor(Date.now() / 1e3);
8106
8352
  },
8107
- true
8353
+ () => untilReached(times.until, cursor.since)
8108
8354
  );
8109
8355
  }
8110
- async function streamContainerText(response, onData) {
8356
+ async function streamContainerText(response, onData, ansi) {
8111
8357
  const reader = response.body?.getReader();
8112
8358
  if (!reader) throw new Error("No response body available for streaming");
8113
8359
  const decoder = new TextDecoder();
@@ -8122,8 +8368,9 @@ async function streamContainerText(response, onData) {
8122
8368
  while (newline >= 0) {
8123
8369
  const line = buffer.slice(0, newline);
8124
8370
  buffer = buffer.slice(newline + 1);
8125
- throwIfGuestAgentError(line);
8126
- onData(line + "\n");
8371
+ if (!delivered) throwIfGuestAgentError(line);
8372
+ throwTextStreamError(line);
8373
+ onData(applyAnsiPolicy(line + "\n", ansi));
8127
8374
  delivered = true;
8128
8375
  newline = buffer.indexOf("\n");
8129
8376
  }
@@ -8133,8 +8380,9 @@ async function streamContainerText(response, onData) {
8133
8380
  }
8134
8381
  }
8135
8382
  if (buffer) {
8136
- throwIfGuestAgentError(buffer);
8137
- onData(buffer);
8383
+ if (!delivered) throwIfGuestAgentError(buffer);
8384
+ throwTextStreamError(buffer);
8385
+ onData(applyAnsiPolicy(buffer, ansi));
8138
8386
  delivered = true;
8139
8387
  }
8140
8388
  } finally {
@@ -8147,46 +8395,101 @@ async function streamContainerText(response, onData) {
8147
8395
  async function streamContainerLogs(client, id, onData, options = {}, signal) {
8148
8396
  if (options.format === "text") {
8149
8397
  const abort = signal ?? options.signal;
8150
- const times = resolveLogTimeWindow(options.since, options.until);
8151
- await assertContainerLogsEnabled(client, id);
8398
+ throwIfAborted(abort);
8399
+ assertContainerNameOption(options.container);
8400
+ const times = resolveTimes(options.since, options.until);
8401
+ const cursor = { boundaryCounts: /* @__PURE__ */ new Map() };
8402
+ let replayCounts = /* @__PURE__ */ new Map();
8152
8403
  let firstRequest = true;
8404
+ let first200Second;
8405
+ let slug;
8153
8406
  await followLogRequests(
8407
+ client,
8154
8408
  async () => {
8155
- const baseUrl = await getContainerLogEndpoint(
8156
- client,
8157
- id,
8158
- options.container,
8159
- options.matchContainerIdPrefix ?? true
8160
- );
8161
- const tail = firstRequest ? options.tail : void 0;
8162
- firstRequest = false;
8409
+ const info = await loadCvmLogInfo(client, id, abort);
8410
+ if (slug === void 0) {
8411
+ slug = await resolveContainerSlug(
8412
+ client,
8413
+ id,
8414
+ options.container,
8415
+ options.matchContainerIdPrefix ?? true,
8416
+ abort
8417
+ );
8418
+ }
8419
+ const baseUrl = urlFromLogInfo(info, slug, resolveCvmId(id));
8420
+ const tail = firstRequest ? options.tail : "all";
8421
+ replayCounts = new Map(cursor.boundaryCounts);
8163
8422
  return buildLogUrl(baseUrl, {
8164
- ...times,
8423
+ since: firstRequest ? times.since : reconnectSinceValue(cursor.since, first200Second, times.since),
8424
+ until: times.until,
8165
8425
  tail,
8166
8426
  follow: true,
8167
- timestamps: options.timestamps,
8427
+ timestamps: true,
8168
8428
  ansi: options.ansi,
8169
8429
  format: "text"
8170
8430
  });
8171
8431
  },
8172
- (response) => streamContainerText(response, onData),
8432
+ async (response, markDelivered) => {
8433
+ let delivered = false;
8434
+ await streamContainerText(
8435
+ response,
8436
+ (line) => {
8437
+ const raw = line.endsWith("\n") ? line.slice(0, -1) : line;
8438
+ throwTextStreamError(raw);
8439
+ const timestamp = parseTimestampedMessage(raw);
8440
+ const out = applyAnsiPolicy(
8441
+ options.timestamps ? line : timestamp.timestamp ? `${timestamp.message ?? ""}${line.endsWith("\n") ? "\n" : ""}` : line,
8442
+ options.ansi
8443
+ );
8444
+ if (timestamp.second === void 0 || !timestamp.timestamp) {
8445
+ delivered = true;
8446
+ markDelivered();
8447
+ onData(out);
8448
+ return;
8449
+ }
8450
+ const key = raw;
8451
+ if (cursor.boundarySecond !== void 0 && timestamp.second < cursor.boundarySecond) {
8452
+ delivered = true;
8453
+ markDelivered();
8454
+ onData(out);
8455
+ return;
8456
+ }
8457
+ if (timestamp.second === cursor.boundarySecond) {
8458
+ const replayCount = replayCounts.get(key) ?? 0;
8459
+ if (replayCount > 0) {
8460
+ replayCounts.set(key, replayCount - 1);
8461
+ return;
8462
+ }
8463
+ } else if (cursor.boundarySecond === void 0 || timestamp.second > cursor.boundarySecond) {
8464
+ cursor.boundarySecond = timestamp.second;
8465
+ cursor.boundaryCounts.clear();
8466
+ }
8467
+ cursor.since = Math.max(cursor.since ?? timestamp.second, timestamp.second);
8468
+ cursor.boundaryCounts.set(key, (cursor.boundaryCounts.get(key) ?? 0) + 1);
8469
+ delivered = true;
8470
+ markDelivered();
8471
+ onData(out);
8472
+ },
8473
+ options.ansi
8474
+ );
8475
+ return delivered;
8476
+ },
8173
8477
  abort,
8174
- async () => {
8175
- await assertContainerLogsEnabled(client, id);
8478
+ void 0,
8479
+ true,
8480
+ () => {
8481
+ firstRequest = false;
8482
+ if (first200Second === void 0) first200Second = Math.floor(Date.now() / 1e3);
8176
8483
  },
8177
- true
8484
+ () => untilReached(times.until, cursor.since)
8178
8485
  );
8179
8486
  return;
8180
8487
  }
8181
- return streamContainerLogsEntries(
8182
- client,
8183
- id,
8184
- (entry) => onData(entry.message === "" ? "\n" : entry.message),
8185
- options,
8186
- signal
8187
- );
8488
+ return streamContainerLogsEntries(client, id, (entry) => onData(entry.message), options, signal);
8188
8489
  }
8189
8490
  async function fetchCvmLogs(client, id, source, options = {}) {
8491
+ throwIfAborted(options.signal);
8492
+ if (source.type === "container") assertContainerNameOption(source.name);
8190
8493
  if (source.type === "node") {
8191
8494
  return fetchCvmChannelLogs(client, id, source.channel, options);
8192
8495
  }
@@ -8204,15 +8507,22 @@ async function fetchCvmLogs(client, id, source, options = {}) {
8204
8507
  });
8205
8508
  }
8206
8509
  async function* followCvmLogs(client, id, source, options = {}) {
8510
+ if (source.type === "container") assertContainerNameOption(source.name);
8207
8511
  const pending = [];
8208
8512
  let wake;
8209
8513
  let done = false;
8210
8514
  let error;
8515
+ const abort = new AbortController();
8516
+ if (options.signal) {
8517
+ if (options.signal.aborted) abort.abort();
8518
+ else options.signal.addEventListener("abort", () => abort.abort(), { once: true });
8519
+ }
8520
+ const signal = abort.signal;
8211
8521
  const push = (item) => {
8212
8522
  pending.push(item);
8213
8523
  wake?.();
8214
8524
  };
8215
- const run = source.type === "node" ? streamCvmChannelLogs(client, id, source.channel, push, options, options.signal) : options.format === "text" ? streamContainerLogs(
8525
+ const run = source.type === "node" ? streamCvmChannelLogs(client, id, source.channel, push, options, signal) : options.format === "text" ? streamContainerLogs(
8216
8526
  client,
8217
8527
  id,
8218
8528
  (data) => push(data),
@@ -8221,7 +8531,7 @@ async function* followCvmLogs(client, id, source, options = {}) {
8221
8531
  container: source.name,
8222
8532
  matchContainerIdPrefix: source.matchContainerIdPrefix
8223
8533
  },
8224
- options.signal
8534
+ signal
8225
8535
  ) : streamContainerLogsEntries(
8226
8536
  client,
8227
8537
  id,
@@ -8231,7 +8541,7 @@ async function* followCvmLogs(client, id, source, options = {}) {
8231
8541
  container: source.name,
8232
8542
  matchContainerIdPrefix: source.matchContainerIdPrefix
8233
8543
  },
8234
- options.signal
8544
+ signal
8235
8545
  );
8236
8546
  void run.then(
8237
8547
  () => {
@@ -8244,16 +8554,20 @@ async function* followCvmLogs(client, id, source, options = {}) {
8244
8554
  wake?.();
8245
8555
  }
8246
8556
  );
8247
- while (!done || pending.length > 0) {
8248
- if (pending.length > 0) {
8249
- yield pending.shift();
8250
- continue;
8557
+ try {
8558
+ while (!done || pending.length > 0) {
8559
+ if (pending.length > 0) {
8560
+ yield pending.shift();
8561
+ continue;
8562
+ }
8563
+ await new Promise((resolve) => {
8564
+ wake = resolve;
8565
+ });
8251
8566
  }
8252
- await new Promise((resolve) => {
8253
- wake = resolve;
8254
- });
8567
+ if (error) throw error;
8568
+ } finally {
8569
+ abort.abort();
8255
8570
  }
8256
- if (error) throw error;
8257
8571
  }
8258
8572
 
8259
8573
  // src/parse_dotenv.ts