@phala/cloud 0.6.2 → 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.2";
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
- const details = options.code ? `${options.code}: ${options.message}` : 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}`, {
7600
+ const details = options.message;
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,33 +7941,122 @@ function containerLogsDisabledError() {
7835
7941
  httpStatus: 409
7836
7942
  });
7837
7943
  }
7838
- async function getContainerLogEndpoint(client, id, containerName, matchContainerIdPrefix = true) {
7839
- const cvmId = resolveCvmId(id);
7840
- const info = await getCvmInfoLogs(client, cvmId);
7841
- if (info.public_logs === false) {
7842
- 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));
7843
7953
  }
7844
- const composition = await client.get(`/cvms/${cvmId}/composition`);
7845
- if (!composition.containers?.length) {
7846
- throw new Error(`No containers found for CVM '${cvmId}'`);
7954
+ }
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
+ );
7847
7960
  }
7848
- 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;
7849
8004
  if (containerName) {
7850
- containers = containers.filter((c) => {
7851
- const matchedByName = c.names.some((n) => n === containerName || n === `/${containerName}`);
7852
- if (matchedByName) return true;
7853
- if (!matchContainerIdPrefix) return false;
7854
- return c.id.startsWith(containerName);
7855
- });
7856
- if (!containers.length) {
7857
- 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 });
7858
8021
  }
8022
+ throw new LogAccessError({ code: "ERR-17-007", message: "Container not found" });
7859
8023
  }
7860
- const container = containers.find((c) => c.log_endpoint);
7861
- if (!container?.log_endpoint) {
7862
- throw new Error(`No log endpoints available for CVM '${cvmId}'`);
8024
+ if (compositionError) {
8025
+ throw new LogAccessError({ message: compositionError });
7863
8026
  }
7864
- 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));
7865
8060
  }
7866
8061
  function waitForReconnect(signal, delayMs) {
7867
8062
  if (signal?.aborted) return Promise.resolve();
@@ -7889,88 +8084,122 @@ function getErrorHttpStatus(error) {
7889
8084
  return void 0;
7890
8085
  }
7891
8086
  var EMPTY_STREAM_END_MESSAGE = "log stream keeps ending without new output; the container may have stopped";
7892
- 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) {
7893
8089
  let failureCount = 0;
7894
8090
  let expiredRetries = 0;
7895
8091
  let emptyEnds = 0;
8092
+ let lastConnectionStartedAt = 0;
8093
+ let haveStarted = false;
7896
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
+ };
7897
8106
  try {
7898
8107
  const url = await resolveUrl();
7899
8108
  if (signal?.aborted) return;
7900
- const response = await fetch(url, { signal });
8109
+ const response = await logFetch(client, url, signal);
7901
8110
  if (!response.ok) await throwResponseError(response);
7902
- failureCount = 0;
7903
- const delivered = await consume(response) ?? true;
8111
+ onConnected?.();
8112
+ const connectedAt = Date.now();
8113
+ const delivered = await consume(response, markDelivered) ?? deliveredThisConnection;
7904
8114
  expiredRetries = 0;
8115
+ if (delivered) {
8116
+ failureCount = 0;
8117
+ }
8118
+ if (shouldStop?.()) return;
7905
8119
  if (signal?.aborted) return;
7906
- if (trackEmptyEnds) {
7907
- if (delivered) {
7908
- emptyEnds = 0;
7909
- } else {
7910
- emptyEnds += 1;
7911
- if (emptyEnds >= 5) {
7912
- throw new LogAccessError({
7913
- message: EMPTY_STREAM_END_MESSAGE,
7914
- fromStreamBody: true
7915
- });
7916
- }
7917
- 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
+ });
7918
8131
  }
8132
+ await waitForReconnect(signal, backoffDelayMs(emptyEnds));
7919
8133
  }
7920
8134
  } catch (error) {
7921
8135
  if (signal?.aborted || error instanceof Error && error.name === "AbortError") {
7922
8136
  return;
7923
8137
  }
7924
- let retryError = error;
8138
+ const retryError = error;
7925
8139
  if (error instanceof LogAccessError && error.fromStreamBody) {
7926
8140
  throw error;
7927
8141
  }
7928
- 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") {
7929
8147
  expiredRetries += 1;
7930
8148
  if (expiredRetries > 3) throw error;
7931
- try {
7932
- await refreshCvm?.();
7933
- continue;
7934
- } catch (refreshError) {
7935
- retryError = refreshError;
7936
- }
8149
+ continue;
7937
8150
  }
7938
8151
  const status = getErrorHttpStatus(retryError);
7939
- if (status !== void 0 && status < 500) throw retryError;
7940
- 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 {
7941
8157
  throw retryError;
7942
8158
  }
8159
+ if (deliveredThisConnection) {
8160
+ failureCount = 0;
8161
+ }
7943
8162
  failureCount += 1;
7944
8163
  if (failureCount >= 5) throw retryError;
7945
- const delayMs = Math.min(250 * 2 ** (failureCount - 1), 5e3);
8164
+ const delayMs = backoffDelayMs(failureCount);
7946
8165
  await waitForReconnect(signal, delayMs);
7947
8166
  }
7948
8167
  }
7949
8168
  }
7950
8169
  async function fetchCvmChannelLogs(client, id, channel, options = {}) {
8170
+ throwIfAborted(options.signal);
7951
8171
  assertSupportedNodeLogOptions(options);
7952
- const times = resolveLogTimeWindow(options.since, options.until);
7953
- 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);
7954
8174
  const url = buildLogUrl(baseUrl, {
7955
8175
  since: times.since,
7956
8176
  until: times.until,
7957
8177
  tail: options.tail,
7958
8178
  ansi: options.ansi
7959
8179
  });
7960
- const response = await fetch(url, { signal: options.signal });
8180
+ const response = await logFetch(client, url, options.signal);
7961
8181
  if (!response.ok) await throwResponseError(response);
7962
- 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
+ );
7963
8191
  }
7964
8192
  async function streamCvmChannelLogs(client, id, channel, onData, options = {}, signal) {
8193
+ throwIfAborted(signal ?? options.signal);
7965
8194
  assertSupportedNodeLogOptions(options);
7966
8195
  const abort = signal ?? options.signal;
7967
- const times = resolveLogTimeWindow(options.since, options.until);
8196
+ const times = resolveTimes(options.since, options.until);
7968
8197
  let firstRequest = true;
7969
8198
  await followLogRequests(
8199
+ client,
7970
8200
  async () => {
7971
- const baseUrl = await getCvmLogEndpoint(client, id, channel);
8201
+ const baseUrl = await getCvmLogEndpoint(client, id, channel, abort);
7972
8202
  const tail = firstRequest ? options.tail : 0;
7973
- firstRequest = false;
7974
8203
  return buildLogUrl(baseUrl, {
7975
8204
  since: times.since,
7976
8205
  until: times.until,
@@ -7979,40 +8208,50 @@ async function streamCvmChannelLogs(client, id, channel, onData, options = {}, s
7979
8208
  ansi: options.ansi
7980
8209
  });
7981
8210
  },
7982
- (response) => streamResponse(response, onData),
8211
+ (response, markDelivered) => streamResponse(response, onData, markDelivered, options.ansi),
7983
8212
  abort,
7984
- async () => {
7985
- await getCvmInfoLogs(client, resolveCvmId(id));
8213
+ void 0,
8214
+ false,
8215
+ () => {
8216
+ firstRequest = false;
7986
8217
  }
7987
8218
  );
7988
8219
  }
7989
8220
  async function fetchContainerLogsEntries(client, id, options = {}) {
7990
- const times = resolveLogTimeWindow(options.since, options.until);
8221
+ throwIfAborted(options.signal);
8222
+ assertContainerNameOption(options.container);
8223
+ const times = resolveTimes(options.since, options.until);
7991
8224
  const baseUrl = await getContainerLogEndpoint(
7992
8225
  client,
7993
8226
  id,
7994
8227
  options.container,
7995
- options.matchContainerIdPrefix ?? true
8228
+ options.matchContainerIdPrefix ?? true,
8229
+ options.signal
7996
8230
  );
7997
8231
  const url = buildLogUrl(baseUrl, {
7998
8232
  ...times,
7999
8233
  tail: options.tail,
8000
8234
  timestamps: options.timestamps,
8001
- ansi: options.ansi,
8002
8235
  format: options.format ?? "ndjson"
8003
8236
  });
8004
- const response = await fetch(url, { signal: options.signal });
8237
+ const response = await logFetch(client, url, options.signal);
8005
8238
  if (!response.ok) await throwResponseError(response);
8006
- return parseStructuredLogsToEntries(await response.text());
8239
+ return parseStructuredLogsToEntries(await response.text()).map((entry) => ({
8240
+ ...entry,
8241
+ message: applyAnsiPolicy(entry.message, options.ansi)
8242
+ }));
8007
8243
  }
8008
8244
  async function fetchContainerLogs(client, id, options = {}) {
8245
+ throwIfAborted(options.signal);
8246
+ assertContainerNameOption(options.container);
8009
8247
  if (options.format === "text") {
8010
- const times = resolveLogTimeWindow(options.since, options.until);
8248
+ const times = resolveTimes(options.since, options.until);
8011
8249
  const baseUrl = await getContainerLogEndpoint(
8012
8250
  client,
8013
8251
  id,
8014
8252
  options.container,
8015
- options.matchContainerIdPrefix ?? true
8253
+ options.matchContainerIdPrefix ?? true,
8254
+ options.signal
8016
8255
  );
8017
8256
  const url = buildLogUrl(baseUrl, {
8018
8257
  ...times,
@@ -8021,36 +8260,44 @@ async function fetchContainerLogs(client, id, options = {}) {
8021
8260
  ansi: options.ansi,
8022
8261
  format: "text"
8023
8262
  });
8024
- const response = await fetch(url, { signal: options.signal });
8263
+ const response = await logFetch(client, url, options.signal);
8025
8264
  if (!response.ok) await throwResponseError(response);
8026
8265
  const text = await response.text();
8027
- throwIfGuestAgentError(text);
8028
- return text;
8266
+ throwIfTextBodyErrors(text);
8267
+ return applyAnsiPolicy(text, options.ansi);
8029
8268
  }
8030
8269
  const entries = await fetchContainerLogsEntries(client, id, {
8031
8270
  ...options,
8032
8271
  format: "ndjson"
8033
8272
  });
8034
- return entries.map((entry) => entry.message === "" ? "\n" : entry.message).join("");
8273
+ return entries.map((entry) => entry.message).join("");
8035
8274
  }
8036
8275
  async function streamContainerLogsEntries(client, id, onEntry, options = {}, signal) {
8037
8276
  const abort = signal ?? options.signal;
8038
- const times = resolveLogTimeWindow(options.since, options.until);
8039
- 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() };
8040
8281
  let replayCounts = /* @__PURE__ */ new Map();
8041
8282
  let firstRequest = true;
8283
+ let first200Second;
8284
+ let slug;
8042
8285
  const buildRequestUrl = async () => {
8043
- const baseUrl = await getContainerLogEndpoint(
8044
- client,
8045
- id,
8046
- options.container,
8047
- options.matchContainerIdPrefix ?? true
8048
- );
8049
- const tail = firstRequest ? options.tail : void 0;
8050
- 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";
8051
8298
  replayCounts = new Map(cursor.boundaryCounts);
8052
8299
  return buildLogUrl(baseUrl, {
8053
- since: cursor.since,
8300
+ since: firstRequest ? times.since : reconnectSinceValue(cursor.since, first200Second, times.since),
8054
8301
  until: times.until,
8055
8302
  tail,
8056
8303
  follow: true,
@@ -8059,20 +8306,23 @@ async function streamContainerLogsEntries(client, id, onEntry, options = {}, sig
8059
8306
  });
8060
8307
  };
8061
8308
  await followLogRequests(
8309
+ client,
8062
8310
  buildRequestUrl,
8063
- async (response) => {
8311
+ async (response, markDelivered) => {
8064
8312
  let delivered = false;
8065
8313
  await streamNdjsonEntriesResponse(response, (entry) => {
8066
8314
  const timestamp = parseTimestampedMessage(entry.message);
8067
8315
  if (timestamp.second === void 0 || !timestamp.timestamp) {
8068
8316
  delivered = true;
8069
- onEntry(formatFollowContainerEntry(entry, options.timestamps ?? false));
8317
+ markDelivered();
8318
+ onEntry(formatFollowContainerEntry(entry, options.timestamps ?? false, options.ansi));
8070
8319
  return;
8071
8320
  }
8072
8321
  const key = JSON.stringify([entry.channel, entry.message]);
8073
8322
  if (cursor.boundarySecond !== void 0 && timestamp.second < cursor.boundarySecond) {
8074
8323
  delivered = true;
8075
- onEntry(formatFollowContainerEntry(entry, options.timestamps ?? false));
8324
+ markDelivered();
8325
+ onEntry(formatFollowContainerEntry(entry, options.timestamps ?? false, options.ansi));
8076
8326
  return;
8077
8327
  }
8078
8328
  if (timestamp.second === cursor.boundarySecond) {
@@ -8088,18 +8338,22 @@ async function streamContainerLogsEntries(client, id, onEntry, options = {}, sig
8088
8338
  cursor.since = Math.max(cursor.since ?? timestamp.second, timestamp.second);
8089
8339
  cursor.boundaryCounts.set(key, (cursor.boundaryCounts.get(key) ?? 0) + 1);
8090
8340
  delivered = true;
8091
- onEntry(formatFollowContainerEntry(entry, options.timestamps ?? false));
8341
+ markDelivered();
8342
+ onEntry(formatFollowContainerEntry(entry, options.timestamps ?? false, options.ansi));
8092
8343
  });
8093
8344
  return delivered;
8094
8345
  },
8095
8346
  abort,
8096
- async () => {
8097
- await getCvmInfoLogs(client, resolveCvmId(id));
8347
+ void 0,
8348
+ true,
8349
+ () => {
8350
+ firstRequest = false;
8351
+ if (first200Second === void 0) first200Second = Math.floor(Date.now() / 1e3);
8098
8352
  },
8099
- true
8353
+ () => untilReached(times.until, cursor.since)
8100
8354
  );
8101
8355
  }
8102
- async function streamContainerText(response, onData) {
8356
+ async function streamContainerText(response, onData, ansi) {
8103
8357
  const reader = response.body?.getReader();
8104
8358
  if (!reader) throw new Error("No response body available for streaming");
8105
8359
  const decoder = new TextDecoder();
@@ -8114,8 +8368,9 @@ async function streamContainerText(response, onData) {
8114
8368
  while (newline >= 0) {
8115
8369
  const line = buffer.slice(0, newline);
8116
8370
  buffer = buffer.slice(newline + 1);
8117
- throwIfGuestAgentError(line);
8118
- onData(line + "\n");
8371
+ if (!delivered) throwIfGuestAgentError(line);
8372
+ throwTextStreamError(line);
8373
+ onData(applyAnsiPolicy(line + "\n", ansi));
8119
8374
  delivered = true;
8120
8375
  newline = buffer.indexOf("\n");
8121
8376
  }
@@ -8125,8 +8380,9 @@ async function streamContainerText(response, onData) {
8125
8380
  }
8126
8381
  }
8127
8382
  if (buffer) {
8128
- throwIfGuestAgentError(buffer);
8129
- onData(buffer);
8383
+ if (!delivered) throwIfGuestAgentError(buffer);
8384
+ throwTextStreamError(buffer);
8385
+ onData(applyAnsiPolicy(buffer, ansi));
8130
8386
  delivered = true;
8131
8387
  }
8132
8388
  } finally {
@@ -8139,45 +8395,101 @@ async function streamContainerText(response, onData) {
8139
8395
  async function streamContainerLogs(client, id, onData, options = {}, signal) {
8140
8396
  if (options.format === "text") {
8141
8397
  const abort = signal ?? options.signal;
8142
- const times = resolveLogTimeWindow(options.since, options.until);
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();
8143
8403
  let firstRequest = true;
8404
+ let first200Second;
8405
+ let slug;
8144
8406
  await followLogRequests(
8407
+ client,
8145
8408
  async () => {
8146
- const baseUrl = await getContainerLogEndpoint(
8147
- client,
8148
- id,
8149
- options.container,
8150
- options.matchContainerIdPrefix ?? true
8151
- );
8152
- const tail = firstRequest ? options.tail : void 0;
8153
- 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);
8154
8422
  return buildLogUrl(baseUrl, {
8155
- ...times,
8423
+ since: firstRequest ? times.since : reconnectSinceValue(cursor.since, first200Second, times.since),
8424
+ until: times.until,
8156
8425
  tail,
8157
8426
  follow: true,
8158
- timestamps: options.timestamps,
8427
+ timestamps: true,
8159
8428
  ansi: options.ansi,
8160
8429
  format: "text"
8161
8430
  });
8162
8431
  },
8163
- (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
+ },
8164
8477
  abort,
8165
- async () => {
8166
- await getCvmInfoLogs(client, resolveCvmId(id));
8478
+ void 0,
8479
+ true,
8480
+ () => {
8481
+ firstRequest = false;
8482
+ if (first200Second === void 0) first200Second = Math.floor(Date.now() / 1e3);
8167
8483
  },
8168
- true
8484
+ () => untilReached(times.until, cursor.since)
8169
8485
  );
8170
8486
  return;
8171
8487
  }
8172
- return streamContainerLogsEntries(
8173
- client,
8174
- id,
8175
- (entry) => onData(entry.message === "" ? "\n" : entry.message),
8176
- options,
8177
- signal
8178
- );
8488
+ return streamContainerLogsEntries(client, id, (entry) => onData(entry.message), options, signal);
8179
8489
  }
8180
8490
  async function fetchCvmLogs(client, id, source, options = {}) {
8491
+ throwIfAborted(options.signal);
8492
+ if (source.type === "container") assertContainerNameOption(source.name);
8181
8493
  if (source.type === "node") {
8182
8494
  return fetchCvmChannelLogs(client, id, source.channel, options);
8183
8495
  }
@@ -8195,15 +8507,22 @@ async function fetchCvmLogs(client, id, source, options = {}) {
8195
8507
  });
8196
8508
  }
8197
8509
  async function* followCvmLogs(client, id, source, options = {}) {
8510
+ if (source.type === "container") assertContainerNameOption(source.name);
8198
8511
  const pending = [];
8199
8512
  let wake;
8200
8513
  let done = false;
8201
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;
8202
8521
  const push = (item) => {
8203
8522
  pending.push(item);
8204
8523
  wake?.();
8205
8524
  };
8206
- 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(
8207
8526
  client,
8208
8527
  id,
8209
8528
  (data) => push(data),
@@ -8212,7 +8531,7 @@ async function* followCvmLogs(client, id, source, options = {}) {
8212
8531
  container: source.name,
8213
8532
  matchContainerIdPrefix: source.matchContainerIdPrefix
8214
8533
  },
8215
- options.signal
8534
+ signal
8216
8535
  ) : streamContainerLogsEntries(
8217
8536
  client,
8218
8537
  id,
@@ -8222,7 +8541,7 @@ async function* followCvmLogs(client, id, source, options = {}) {
8222
8541
  container: source.name,
8223
8542
  matchContainerIdPrefix: source.matchContainerIdPrefix
8224
8543
  },
8225
- options.signal
8544
+ signal
8226
8545
  );
8227
8546
  void run.then(
8228
8547
  () => {
@@ -8235,16 +8554,20 @@ async function* followCvmLogs(client, id, source, options = {}) {
8235
8554
  wake?.();
8236
8555
  }
8237
8556
  );
8238
- while (!done || pending.length > 0) {
8239
- if (pending.length > 0) {
8240
- yield pending.shift();
8241
- 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
+ });
8242
8566
  }
8243
- await new Promise((resolve) => {
8244
- wake = resolve;
8245
- });
8567
+ if (error) throw error;
8568
+ } finally {
8569
+ abort.abort();
8246
8570
  }
8247
- if (error) throw error;
8248
8571
  }
8249
8572
 
8250
8573
  // src/parse_dotenv.ts