lody 0.54.0 → 0.55.0

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.js CHANGED
@@ -49,7 +49,7 @@ import require$$0$a, { execSync, exec, execFileSync, execFile as execFile$1 } fr
49
49
  import { randomFillSync, randomUUID, createHash } from "node:crypto";
50
50
  import require$$0$b from "net";
51
51
  import require$$4$3 from "tls";
52
- import { i as imports, _ as __wbg_set_wasm$1, r as rawWasm, L as LoroDoc, E as EphemeralStoreWasm, U as UndoManager, c as callPendingEvents$3, a as LoroTree, b as LoroText, d as LoroMovableList, e as LoroList, f as LoroMap, g as __vite__initWasm, V as VersionVector, h as decodeImportBlobMeta, __tla as __tla_0 } from "./chunks/loro_wasm_bg-DgxHrrrp.js";
52
+ import { i as imports, _ as __wbg_set_wasm$1, r as rawWasm, L as LoroDoc, E as EphemeralStoreWasm, U as UndoManager, c as callPendingEvents$3, a as LoroTree, b as LoroText, d as LoroMovableList, e as LoroList, f as LoroMap, g as __vite__initWasm, V as VersionVector, h as decodeImportBlobMeta, __tla as __tla_0 } from "./chunks/loro_wasm_bg-ICD3atfE.js";
53
53
  import * as fs$5 from "fs/promises";
54
54
  import fs__default$1, { stat as stat$1, readFile as readFile$1, statfs } from "fs/promises";
55
55
  import fsPromises, { stat, open } from "node:fs/promises";
@@ -4068,7 +4068,7 @@ let __tla = Promise.all([
4068
4068
  }
4069
4069
  return true;
4070
4070
  }
4071
- let TimeoutError$3 = class TimeoutError2 extends Error {
4071
+ let TimeoutError$2 = class TimeoutError2 extends Error {
4072
4072
  constructor(message) {
4073
4073
  super(message);
4074
4074
  Object.setPrototypeOf(this, TimeoutError2.prototype);
@@ -4078,7 +4078,7 @@ let __tla = Promise.all([
4078
4078
  let timeoutHandle;
4079
4079
  const timeoutPromise = new Promise(function timeoutFunction(_resolve, reject) {
4080
4080
  timeoutHandle = setTimeout(function timeoutHandler() {
4081
- reject(new TimeoutError$3("Operation timed out."));
4081
+ reject(new TimeoutError$2("Operation timed out."));
4082
4082
  }, timeout2);
4083
4083
  });
4084
4084
  return Promise.race([
@@ -4203,7 +4203,7 @@ let __tla = Promise.all([
4203
4203
  SDK_INFO,
4204
4204
  TRACE_PARENT_HEADER,
4205
4205
  TRACE_STATE_HEADER,
4206
- TimeoutError: TimeoutError$3,
4206
+ TimeoutError: TimeoutError$2,
4207
4207
  TraceState,
4208
4208
  W3CBaggagePropagator,
4209
4209
  W3CTraceContextPropagator,
@@ -36822,7 +36822,7 @@ Mongoose Error Code: ${error2.code}` : ""}`
36822
36822
  return client;
36823
36823
  }
36824
36824
  const name = "lody";
36825
- const version$4 = "0.54.0";
36825
+ const version$4 = "0.55.0";
36826
36826
  const description$1 = "Lody Agent CLI tool for managing remote command execution";
36827
36827
  const type$2 = "module";
36828
36828
  const main$3 = "dist/index.js";
@@ -52071,11 +52071,11 @@ ${originalIndentation}`;
52071
52071
  function mod(n, x) {
52072
52072
  return (n % x + x) % x;
52073
52073
  }
52074
- var indexOf$2;
52074
+ var indexOf$1;
52075
52075
  if (Array.prototype.indexOf) {
52076
- indexOf$2 = Array.prototype.indexOf;
52076
+ indexOf$1 = Array.prototype.indexOf;
52077
52077
  } else {
52078
- indexOf$2 = function(o) {
52078
+ indexOf$1 = function(o) {
52079
52079
  var i2;
52080
52080
  for (i2 = 0; i2 < this.length; ++i2) {
52081
52081
  if (this[i2] === o) {
@@ -52160,26 +52160,26 @@ ${originalIndentation}`;
52160
52160
  }
52161
52161
  if (strict) {
52162
52162
  if (format2 === "MMM") {
52163
- ii = indexOf$2.call(this._shortMonthsParse, llc);
52163
+ ii = indexOf$1.call(this._shortMonthsParse, llc);
52164
52164
  return ii !== -1 ? ii : null;
52165
52165
  } else {
52166
- ii = indexOf$2.call(this._longMonthsParse, llc);
52166
+ ii = indexOf$1.call(this._longMonthsParse, llc);
52167
52167
  return ii !== -1 ? ii : null;
52168
52168
  }
52169
52169
  } else {
52170
52170
  if (format2 === "MMM") {
52171
- ii = indexOf$2.call(this._shortMonthsParse, llc);
52171
+ ii = indexOf$1.call(this._shortMonthsParse, llc);
52172
52172
  if (ii !== -1) {
52173
52173
  return ii;
52174
52174
  }
52175
- ii = indexOf$2.call(this._longMonthsParse, llc);
52175
+ ii = indexOf$1.call(this._longMonthsParse, llc);
52176
52176
  return ii !== -1 ? ii : null;
52177
52177
  } else {
52178
- ii = indexOf$2.call(this._longMonthsParse, llc);
52178
+ ii = indexOf$1.call(this._longMonthsParse, llc);
52179
52179
  if (ii !== -1) {
52180
52180
  return ii;
52181
52181
  }
52182
- ii = indexOf$2.call(this._shortMonthsParse, llc);
52182
+ ii = indexOf$1.call(this._shortMonthsParse, llc);
52183
52183
  return ii !== -1 ? ii : null;
52184
52184
  }
52185
52185
  }
@@ -52509,48 +52509,48 @@ ${originalIndentation}`;
52509
52509
  }
52510
52510
  if (strict) {
52511
52511
  if (format2 === "dddd") {
52512
- ii = indexOf$2.call(this._weekdaysParse, llc);
52512
+ ii = indexOf$1.call(this._weekdaysParse, llc);
52513
52513
  return ii !== -1 ? ii : null;
52514
52514
  } else if (format2 === "ddd") {
52515
- ii = indexOf$2.call(this._shortWeekdaysParse, llc);
52515
+ ii = indexOf$1.call(this._shortWeekdaysParse, llc);
52516
52516
  return ii !== -1 ? ii : null;
52517
52517
  } else {
52518
- ii = indexOf$2.call(this._minWeekdaysParse, llc);
52518
+ ii = indexOf$1.call(this._minWeekdaysParse, llc);
52519
52519
  return ii !== -1 ? ii : null;
52520
52520
  }
52521
52521
  } else {
52522
52522
  if (format2 === "dddd") {
52523
- ii = indexOf$2.call(this._weekdaysParse, llc);
52523
+ ii = indexOf$1.call(this._weekdaysParse, llc);
52524
52524
  if (ii !== -1) {
52525
52525
  return ii;
52526
52526
  }
52527
- ii = indexOf$2.call(this._shortWeekdaysParse, llc);
52527
+ ii = indexOf$1.call(this._shortWeekdaysParse, llc);
52528
52528
  if (ii !== -1) {
52529
52529
  return ii;
52530
52530
  }
52531
- ii = indexOf$2.call(this._minWeekdaysParse, llc);
52531
+ ii = indexOf$1.call(this._minWeekdaysParse, llc);
52532
52532
  return ii !== -1 ? ii : null;
52533
52533
  } else if (format2 === "ddd") {
52534
- ii = indexOf$2.call(this._shortWeekdaysParse, llc);
52534
+ ii = indexOf$1.call(this._shortWeekdaysParse, llc);
52535
52535
  if (ii !== -1) {
52536
52536
  return ii;
52537
52537
  }
52538
- ii = indexOf$2.call(this._weekdaysParse, llc);
52538
+ ii = indexOf$1.call(this._weekdaysParse, llc);
52539
52539
  if (ii !== -1) {
52540
52540
  return ii;
52541
52541
  }
52542
- ii = indexOf$2.call(this._minWeekdaysParse, llc);
52542
+ ii = indexOf$1.call(this._minWeekdaysParse, llc);
52543
52543
  return ii !== -1 ? ii : null;
52544
52544
  } else {
52545
- ii = indexOf$2.call(this._minWeekdaysParse, llc);
52545
+ ii = indexOf$1.call(this._minWeekdaysParse, llc);
52546
52546
  if (ii !== -1) {
52547
52547
  return ii;
52548
52548
  }
52549
- ii = indexOf$2.call(this._weekdaysParse, llc);
52549
+ ii = indexOf$1.call(this._weekdaysParse, llc);
52550
52550
  if (ii !== -1) {
52551
52551
  return ii;
52552
52552
  }
52553
- ii = indexOf$2.call(this._shortWeekdaysParse, llc);
52553
+ ii = indexOf$1.call(this._shortWeekdaysParse, llc);
52554
52554
  return ii !== -1 ? ii : null;
52555
52555
  }
52556
52556
  }
@@ -53627,7 +53627,7 @@ ${originalIndentation}`;
53627
53627
  function isDurationValid(m) {
53628
53628
  var key2, unitHasDecimal = false, i2, orderLen = ordering.length;
53629
53629
  for (key2 in m) {
53630
- if (hasOwnProp(m, key2) && !(indexOf$2.call(ordering, key2) !== -1 && (m[key2] == null || !isNaN(m[key2])))) {
53630
+ if (hasOwnProp(m, key2) && !(indexOf$1.call(ordering, key2) !== -1 && (m[key2] == null || !isNaN(m[key2])))) {
53631
53631
  return false;
53632
53632
  }
53633
53633
  }
@@ -74690,7 +74690,7 @@ Task description:
74690
74690
  }
74691
74691
  finalize$1(instance.exports);
74692
74692
  } else {
74693
- const wkmod = wasmModuleOrExports instanceof WebAssembly.Module ? wasmModuleOrExports : await import("./chunks/loro_wasm_bg-DgxHrrrp.js").then(async (m) => {
74693
+ const wkmod = wasmModuleOrExports instanceof WebAssembly.Module ? wasmModuleOrExports : await import("./chunks/loro_wasm_bg-ICD3atfE.js").then(async (m) => {
74694
74694
  await m.__tla;
74695
74695
  return m;
74696
74696
  }).then((n) => n.r);
@@ -92691,7 +92691,7 @@ ${val.stack}`;
92691
92691
  console.info(prefix, ...args2);
92692
92692
  };
92693
92693
  };
92694
- var ProtocolError$2 = class ProtocolError extends Error {
92694
+ var ProtocolError$1 = class ProtocolError extends Error {
92695
92695
  status;
92696
92696
  detail;
92697
92697
  constructor(message, status, detail) {
@@ -92700,7 +92700,7 @@ ${val.stack}`;
92700
92700
  this.detail = detail;
92701
92701
  }
92702
92702
  };
92703
- var TimeoutError$2 = class TimeoutError extends Error {
92703
+ var TimeoutError$1 = class TimeoutError extends Error {
92704
92704
  phase;
92705
92705
  timeoutMs;
92706
92706
  constructor(phase, timeoutMs) {
@@ -92709,11 +92709,11 @@ ${val.stack}`;
92709
92709
  this.timeoutMs = timeoutMs;
92710
92710
  }
92711
92711
  };
92712
- function isAbortError$1(error2) {
92712
+ function isAbortError(error2) {
92713
92713
  return error2 instanceof DOMException ? error2.name === "AbortError" : typeof error2 === "object" && error2 != null && "name" in error2 && error2.name === "AbortError";
92714
92714
  }
92715
- async function responseToStreamError$1(response, context2) {
92716
- const bodyText = await safeReadBodyText$1(response);
92715
+ async function responseToStreamError(response, context2) {
92716
+ const bodyText = await safeReadBodyText(response);
92717
92717
  const message = bodyText.length > 0 ? `${context2} failed with status ${response.status}: ${bodyText}` : `${context2} failed with status ${response.status}`;
92718
92718
  const presentBody = bodyText.length > 0 ? bodyText : void 0;
92719
92719
  switch (response.status) {
@@ -92737,7 +92737,7 @@ ${val.stack}`;
92737
92737
  status: 403,
92738
92738
  message,
92739
92739
  bodyText: presentBody,
92740
- detail: producerEpochDetail$1(response)
92740
+ detail: producerEpochDetail(response)
92741
92741
  };
92742
92742
  case 404:
92743
92743
  return {
@@ -92752,7 +92752,7 @@ ${val.stack}`;
92752
92752
  status: 409,
92753
92753
  message,
92754
92754
  bodyText: presentBody,
92755
- detail: conflictDetail$1(response, bodyText)
92755
+ detail: conflictDetail(response, bodyText)
92756
92756
  };
92757
92757
  case 410:
92758
92758
  return {
@@ -92774,7 +92774,7 @@ ${val.stack}`;
92774
92774
  message,
92775
92775
  status: response.status,
92776
92776
  statusText: response.statusText,
92777
- headers: headersToObject$1$1(response.headers),
92777
+ headers: headersToObject$1(response.headers),
92778
92778
  bodyText: bodyText.length > 0 ? bodyText : void 0,
92779
92779
  cause: {
92780
92780
  type: "http_response",
@@ -92784,13 +92784,13 @@ ${val.stack}`;
92784
92784
  };
92785
92785
  }
92786
92786
  }
92787
- function thrownToStreamError$1(error2) {
92788
- if (error2 instanceof TimeoutError$2) return {
92787
+ function thrownToStreamError(error2) {
92788
+ if (error2 instanceof TimeoutError$1) return {
92789
92789
  code: "timeout",
92790
92790
  phase: error2.phase,
92791
92791
  message: error2.message
92792
92792
  };
92793
- if (error2 instanceof ProtocolError$2) return {
92793
+ if (error2 instanceof ProtocolError$1) return {
92794
92794
  code: "protocol_error",
92795
92795
  message: error2.message,
92796
92796
  status: error2.status,
@@ -92812,10 +92812,10 @@ ${val.stack}`;
92812
92812
  cause: error2
92813
92813
  };
92814
92814
  }
92815
- function isRetryableLiveError$1(error2) {
92816
- return isRetryableStreamError$1(error2);
92815
+ function isRetryableLiveError(error2) {
92816
+ return isRetryableStreamError(error2);
92817
92817
  }
92818
- function producerEpochDetail$1(response) {
92818
+ function producerEpochDetail(response) {
92819
92819
  const value = response.headers.get("Producer-Epoch");
92820
92820
  if (value == null) return;
92821
92821
  const parsed = Number.parseInt(value, 10);
@@ -92827,16 +92827,16 @@ ${val.stack}`;
92827
92827
  serverEpoch: parsed
92828
92828
  };
92829
92829
  }
92830
- function conflictDetail$1(response, bodyText) {
92831
- if (isTrueHeader$1(response.headers.get("Stream-Closed"))) return {
92830
+ function conflictDetail(response, bodyText) {
92831
+ if (isTrueHeader(response.headers.get("Stream-Closed"))) return {
92832
92832
  kind: "stream_closed",
92833
92833
  nextOffset: response.headers.get("Stream-Next-Offset") ?? void 0
92834
92834
  };
92835
- const expectedSeq = parseOptionalInteger$1$1(response.headers.get("Producer-Expected-Seq"));
92835
+ const expectedSeq = parseOptionalInteger$1(response.headers.get("Producer-Expected-Seq"));
92836
92836
  if (expectedSeq != null) return {
92837
92837
  kind: "producer_seq_gap",
92838
92838
  expectedSeq,
92839
- receivedSeq: parseOptionalInteger$1$1(response.headers.get("Producer-Received-Seq")) ?? void 0
92839
+ receivedSeq: parseOptionalInteger$1(response.headers.get("Producer-Received-Seq")) ?? void 0
92840
92840
  };
92841
92841
  const normalized = bodyText.toLowerCase();
92842
92842
  if (normalized.includes("content type")) return {
@@ -92849,39 +92849,39 @@ ${val.stack}`;
92849
92849
  kind: "other"
92850
92850
  };
92851
92851
  }
92852
- function parseOptionalInteger$1$1(value) {
92852
+ function parseOptionalInteger$1(value) {
92853
92853
  if (value == null) return null;
92854
92854
  const parsed = Number.parseInt(value, 10);
92855
92855
  if (!Number.isFinite(parsed) || parsed < 0) return null;
92856
92856
  return parsed;
92857
92857
  }
92858
- function isTrueHeader$1(value) {
92858
+ function isTrueHeader(value) {
92859
92859
  return value?.trim().toLowerCase() === "true";
92860
92860
  }
92861
- function headersToObject$1$1(headers) {
92861
+ function headersToObject$1(headers) {
92862
92862
  const result = {};
92863
92863
  headers.forEach((value, name2) => {
92864
92864
  result[name2] = value;
92865
92865
  });
92866
92866
  return result;
92867
92867
  }
92868
- async function safeReadBodyText$1(response) {
92868
+ async function safeReadBodyText(response) {
92869
92869
  try {
92870
92870
  return await response.text();
92871
92871
  } catch {
92872
92872
  return "";
92873
92873
  }
92874
92874
  }
92875
- function isRetryableStreamError$1(error2) {
92875
+ function isRetryableStreamError(error2) {
92876
92876
  return error2.code === "network_error" || error2.code === "timeout";
92877
92877
  }
92878
- const DEFAULT_TIMEOUT_CONFIG$1 = {
92878
+ const DEFAULT_TIMEOUT_CONFIG = {
92879
92879
  connectTimeoutMs: 1e4,
92880
92880
  pollTimeoutMs: 3e4
92881
92881
  };
92882
- function normalizeTimeoutConfig$1(value) {
92883
- const connectTimeoutMs = value?.connectTimeoutMs ?? DEFAULT_TIMEOUT_CONFIG$1.connectTimeoutMs;
92884
- const pollTimeoutMs = value?.pollTimeoutMs ?? DEFAULT_TIMEOUT_CONFIG$1.pollTimeoutMs;
92882
+ function normalizeTimeoutConfig(value) {
92883
+ const connectTimeoutMs = value?.connectTimeoutMs ?? DEFAULT_TIMEOUT_CONFIG.connectTimeoutMs;
92884
+ const pollTimeoutMs = value?.pollTimeoutMs ?? DEFAULT_TIMEOUT_CONFIG.pollTimeoutMs;
92885
92885
  if (!Number.isFinite(connectTimeoutMs) || connectTimeoutMs < 0) throw new Error("timeout.connectTimeoutMs must be a non-negative finite number");
92886
92886
  if (!Number.isFinite(pollTimeoutMs) || pollTimeoutMs < 0) throw new Error("timeout.pollTimeoutMs must be a non-negative finite number");
92887
92887
  return {
@@ -92889,7 +92889,7 @@ ${val.stack}`;
92889
92889
  pollTimeoutMs: Math.floor(pollTimeoutMs)
92890
92890
  };
92891
92891
  }
92892
- function mergeAbortSignals$1$1(...signals2) {
92892
+ function mergeAbortSignals$1(...signals2) {
92893
92893
  const active2 = signals2.filter((signal) => signal != null);
92894
92894
  if (active2.length === 0) return;
92895
92895
  if (active2.length === 1) return active2[0];
@@ -92908,12 +92908,12 @@ ${val.stack}`;
92908
92908
  }
92909
92909
  return controller.signal;
92910
92910
  }
92911
- async function fetchWithTimeout$1(fetchImpl, input2, init2, timeoutMs, phase) {
92911
+ async function fetchWithTimeout(fetchImpl, input2, init2, timeoutMs, phase) {
92912
92912
  if (!(timeoutMs > 0)) return await fetchImpl(input2, init2);
92913
92913
  const controller = new AbortController();
92914
- const signal = mergeAbortSignals$1$1(init2.signal, controller.signal);
92914
+ const signal = mergeAbortSignals$1(init2.signal, controller.signal);
92915
92915
  const timer2 = setTimeout(() => {
92916
- controller.abort(new TimeoutError$2(phase, timeoutMs));
92916
+ controller.abort(new TimeoutError$1(phase, timeoutMs));
92917
92917
  }, timeoutMs);
92918
92918
  try {
92919
92919
  return await fetchImpl(input2, {
@@ -92921,25 +92921,25 @@ ${val.stack}`;
92921
92921
  signal
92922
92922
  });
92923
92923
  } catch (error2) {
92924
- if (controller.signal.aborted && controller.signal.reason instanceof TimeoutError$2) throw controller.signal.reason;
92924
+ if (controller.signal.aborted && controller.signal.reason instanceof TimeoutError$1) throw controller.signal.reason;
92925
92925
  throw error2;
92926
92926
  } finally {
92927
92927
  clearTimeout(timer2);
92928
92928
  }
92929
92929
  }
92930
- var AuthorizedHttpClient$1 = class AuthorizedHttpClient {
92930
+ var AuthorizedHttpClient = class {
92931
92931
  fetchImpl;
92932
92932
  authProvider;
92933
92933
  authRefreshInFlight;
92934
92934
  constructor(options) {
92935
92935
  this.fetchImpl = options.fetchImpl;
92936
- this.authProvider = normalizeAuthProvider$2(options.auth);
92936
+ this.authProvider = normalizeAuthProvider$1(options.auth);
92937
92937
  }
92938
92938
  async fetchAuthorized(input2, init2, timeoutMs, phase, options) {
92939
92939
  const firstToken = await this.resolveToken({
92940
92940
  reason: "request"
92941
92941
  });
92942
- const firstResponse = await fetchWithTimeout$1(this.fetchImpl, input2, {
92942
+ const firstResponse = await fetchWithTimeout(this.fetchImpl, input2, {
92943
92943
  ...init2,
92944
92944
  headers: this.attachAuthorization(init2.headers, firstToken)
92945
92945
  }, timeoutMs, phase);
@@ -92948,7 +92948,7 @@ ${val.stack}`;
92948
92948
  await firstResponse.body?.cancel().catch(() => {
92949
92949
  });
92950
92950
  const refreshedToken = await this.refreshTokenAfterFailure(firstResponse.status, firstToken);
92951
- return await fetchWithTimeout$1(this.fetchImpl, input2, {
92951
+ return await fetchWithTimeout(this.fetchImpl, input2, {
92952
92952
  ...init2,
92953
92953
  headers: this.attachAuthorization(init2.headers, refreshedToken)
92954
92954
  }, timeoutMs, phase);
@@ -92978,7 +92978,7 @@ ${val.stack}`;
92978
92978
  return headers;
92979
92979
  }
92980
92980
  };
92981
- function normalizeAuthProvider$2(auth) {
92981
+ function normalizeAuthProvider$1(auth) {
92982
92982
  if (auth == null) return;
92983
92983
  if (typeof auth === "string") {
92984
92984
  const token2 = auth.trim();
@@ -92989,20 +92989,20 @@ ${val.stack}`;
92989
92989
  return token2.length === 0 ? void 0 : token2;
92990
92990
  };
92991
92991
  }
92992
- function decodeMultipartMixed$1(boundary, data) {
92992
+ function decodeMultipartMixed(boundary, data) {
92993
92993
  const delimiter2 = new TextEncoder().encode(`--${boundary}`);
92994
92994
  const closeDelimiter = new TextEncoder().encode(`--${boundary}--`);
92995
92995
  const crlfCrlf = new TextEncoder().encode("\r\n\r\n");
92996
92996
  const parts2 = [];
92997
92997
  let pos = 0;
92998
- const firstDelimPos = indexOf$1(data, delimiter2, pos);
92998
+ const firstDelimPos = indexOf(data, delimiter2, pos);
92999
92999
  if (firstDelimPos < 0) return parts2;
93000
93000
  pos = firstDelimPos + delimiter2.byteLength;
93001
93001
  if (pos < data.byteLength && data[pos] === 13) pos += 1;
93002
93002
  if (pos < data.byteLength && data[pos] === 10) pos += 1;
93003
93003
  while (pos < data.byteLength) {
93004
- if (startsWith$1(data.subarray(pos), closeDelimiter.subarray(delimiter2.byteLength))) break;
93005
- const headerEnd = indexOf$1(data, crlfCrlf, pos);
93004
+ if (startsWith(data.subarray(pos), closeDelimiter.subarray(delimiter2.byteLength))) break;
93005
+ const headerEnd = indexOf(data, crlfCrlf, pos);
93006
93006
  if (headerEnd < 0) break;
93007
93007
  const headerBytes = data.subarray(pos, headerEnd);
93008
93008
  const headerText = new TextDecoder().decode(headerBytes);
@@ -93014,7 +93014,7 @@ ${val.stack}`;
93014
93014
  contentType = line3.slice(colon + 1).trim();
93015
93015
  }
93016
93016
  const bodyStart = headerEnd + crlfCrlf.byteLength;
93017
- const nextDelimiter = indexOf$1(data, delimiter2, bodyStart);
93017
+ const nextDelimiter = indexOf(data, delimiter2, bodyStart);
93018
93018
  if (nextDelimiter < 0) {
93019
93019
  parts2.push({
93020
93020
  contentType,
@@ -93035,22 +93035,22 @@ ${val.stack}`;
93035
93035
  }
93036
93036
  return parts2;
93037
93037
  }
93038
- function extractBoundary$1(contentType) {
93038
+ function extractBoundary(contentType) {
93039
93039
  return /boundary=("?)([^";,\s]+)\1/i.exec(contentType)?.[2] ?? null;
93040
93040
  }
93041
- function indexOf$1(haystack, needle, from2) {
93041
+ function indexOf(haystack, needle, from2) {
93042
93042
  outer: for (let i2 = from2; i2 <= haystack.byteLength - needle.byteLength; i2 += 1) {
93043
93043
  for (let j = 0; j < needle.byteLength; j += 1) if (haystack[i2 + j] !== needle[j]) continue outer;
93044
93044
  return i2;
93045
93045
  }
93046
93046
  return -1;
93047
93047
  }
93048
- function startsWith$1(data, prefix) {
93048
+ function startsWith(data, prefix) {
93049
93049
  if (data.byteLength < prefix.byteLength) return false;
93050
93050
  for (let i2 = 0; i2 < prefix.byteLength; i2 += 1) if (data[i2] !== prefix[i2]) return false;
93051
93051
  return true;
93052
93052
  }
93053
- const DEFAULT_RETRY_CONFIG$1 = {
93053
+ const DEFAULT_RETRY_CONFIG = {
93054
93054
  delays: [
93055
93055
  0,
93056
93056
  500,
@@ -93063,16 +93063,16 @@ ${val.stack}`;
93063
93063
  jitterFraction: 0.2,
93064
93064
  maxAttempts: 5
93065
93065
  };
93066
- function normalizeRetryConfig$1(value) {
93067
- const delays = value?.delays ?? DEFAULT_RETRY_CONFIG$1.delays;
93066
+ function normalizeRetryConfig(value) {
93067
+ const delays = value?.delays ?? DEFAULT_RETRY_CONFIG.delays;
93068
93068
  if (delays.length === 0) throw new Error("retry.delays must contain at least one entry");
93069
93069
  const normalizedDelays = delays.map((delay2) => {
93070
93070
  if (!Number.isFinite(delay2) || delay2 < 0) throw new Error("retry.delays must contain non-negative finite numbers");
93071
93071
  return Math.floor(delay2);
93072
93072
  });
93073
- const jitterFraction = value?.jitterFraction ?? DEFAULT_RETRY_CONFIG$1.jitterFraction;
93073
+ const jitterFraction = value?.jitterFraction ?? DEFAULT_RETRY_CONFIG.jitterFraction;
93074
93074
  if (!Number.isFinite(jitterFraction) || jitterFraction < 0) throw new Error("retry.jitterFraction must be a non-negative finite number");
93075
- const maxAttempts = value?.maxAttempts ?? DEFAULT_RETRY_CONFIG$1.maxAttempts;
93075
+ const maxAttempts = value?.maxAttempts ?? DEFAULT_RETRY_CONFIG.maxAttempts;
93076
93076
  if (!Number.isInteger(maxAttempts) || maxAttempts < 0) throw new Error("retry.maxAttempts must be a non-negative integer");
93077
93077
  return {
93078
93078
  delays: normalizedDelays,
@@ -93080,16 +93080,16 @@ ${val.stack}`;
93080
93080
  maxAttempts
93081
93081
  };
93082
93082
  }
93083
- function applyJitter$2(baseMs, fraction) {
93083
+ function applyJitter$1(baseMs, fraction) {
93084
93084
  if (baseMs === 0) return 0;
93085
93085
  const jitter = baseMs * fraction * (2 * Math.random() - 1);
93086
93086
  return Math.max(0, Math.round(baseMs + jitter));
93087
93087
  }
93088
- function computeRetryDelay$2(attempt, config2 = DEFAULT_RETRY_CONFIG$1) {
93088
+ function computeRetryDelay$1(attempt, config2 = DEFAULT_RETRY_CONFIG) {
93089
93089
  const index2 = Math.min(attempt, config2.delays.length - 1);
93090
- return applyJitter$2(config2.delays[index2] ?? 0, config2.jitterFraction);
93090
+ return applyJitter$1(config2.delays[index2] ?? 0, config2.jitterFraction);
93091
93091
  }
93092
- async function sleep$3(delayMs, signal) {
93092
+ async function sleep$2(delayMs, signal) {
93093
93093
  if (delayMs <= 0) {
93094
93094
  if (signal?.aborted === true) throw signal.reason;
93095
93095
  return;
@@ -93118,21 +93118,21 @@ ${val.stack}`;
93118
93118
  }
93119
93119
  });
93120
93120
  }
93121
- function getRequiredHeader$1(headers, name2, context2) {
93121
+ function getRequiredHeader(headers, name2, context2) {
93122
93122
  const value = headers.get(name2);
93123
93123
  if (value != null && value.length > 0) return value;
93124
- throw new ProtocolError$2(`${context2} response missing ${name2}. If this is cross-origin, expose it via Access-Control-Expose-Headers (${name2.toLowerCase()}). Visible headers: ${visibleHeaderNames$1(headers)}`);
93124
+ throw new ProtocolError$1(`${context2} response missing ${name2}. If this is cross-origin, expose it via Access-Control-Expose-Headers (${name2.toLowerCase()}). Visible headers: ${visibleHeaderNames(headers)}`);
93125
93125
  }
93126
- function hasTrueHeader$1(headers, name2) {
93126
+ function hasTrueHeader(headers, name2) {
93127
93127
  return headers.get(name2)?.trim().toLowerCase() === "true";
93128
93128
  }
93129
- function parseOptionalInteger$2(value) {
93129
+ function parseOptionalInteger(value) {
93130
93130
  if (value == null) return null;
93131
93131
  const parsed = Number.parseInt(value, 10);
93132
93132
  if (!Number.isFinite(parsed) || parsed < 0) return null;
93133
93133
  return parsed;
93134
93134
  }
93135
- function visibleHeaderNames$1(headers) {
93135
+ function visibleHeaderNames(headers) {
93136
93136
  const names2 = [];
93137
93137
  headers.forEach((_value, name2) => {
93138
93138
  names2.push(name2);
@@ -93141,60 +93141,60 @@ ${val.stack}`;
93141
93141
  names2.sort();
93142
93142
  return names2.join(", ");
93143
93143
  }
93144
- const encoder$1 = new TextEncoder();
93145
- const decoder$1 = new TextDecoder();
93146
- function createStreamPart$1(contentType, body) {
93144
+ const encoder = new TextEncoder();
93145
+ const decoder = new TextDecoder();
93146
+ function createStreamPart(contentType, body) {
93147
93147
  return {
93148
93148
  contentType,
93149
93149
  body,
93150
93150
  text() {
93151
- return decoder$1.decode(body);
93151
+ return decoder.decode(body);
93152
93152
  },
93153
93153
  json() {
93154
- return JSON.parse(decoder$1.decode(body));
93154
+ return JSON.parse(decoder.decode(body));
93155
93155
  }
93156
93156
  };
93157
93157
  }
93158
- function normalizeStreamPartLike$1(input2) {
93158
+ function normalizeStreamPartLike(input2) {
93159
93159
  return {
93160
- contentType: normalizeContentType$1(input2.contentType),
93161
- body: normalizeStreamBody$1(input2.body)
93160
+ contentType: normalizeContentType(input2.contentType),
93161
+ body: normalizeStreamBody(input2.body)
93162
93162
  };
93163
93163
  }
93164
- function normalizeContentType$1(contentType) {
93164
+ function normalizeContentType(contentType) {
93165
93165
  const normalized = contentType.trim();
93166
93166
  if (normalized.length === 0) throw new Error("contentType must be a non-empty string");
93167
93167
  return normalized;
93168
93168
  }
93169
- function normalizeOptionalContentType$1(contentType) {
93169
+ function normalizeOptionalContentType(contentType) {
93170
93170
  if (contentType == null) return;
93171
- return normalizeContentType$1(contentType);
93171
+ return normalizeContentType(contentType);
93172
93172
  }
93173
- function normalizeStreamBody$1(body) {
93174
- if (typeof body === "string") return encoder$1.encode(body);
93173
+ function normalizeStreamBody(body) {
93174
+ if (typeof body === "string") return encoder.encode(body);
93175
93175
  if (body instanceof Uint8Array) return body.slice();
93176
93176
  if (body instanceof ArrayBuffer) return new Uint8Array(body.slice(0));
93177
93177
  if (ArrayBuffer.isView(body)) return new Uint8Array(body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength));
93178
93178
  throw new Error("unsupported stream body type");
93179
93179
  }
93180
- function toRequestBody$1(bytes) {
93180
+ function toRequestBody(bytes) {
93181
93181
  return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
93182
93182
  }
93183
- function isSseUnsupportedErrorText$2(message) {
93183
+ function isSseUnsupportedErrorText$1(message) {
93184
93184
  const normalized = message.trim().toLowerCase();
93185
93185
  if (normalized.length === 0) return false;
93186
93186
  const mentionsSse = normalized.includes("sse") || normalized.includes("text/event-stream");
93187
93187
  const mentionsCompatibility = normalized.includes("unsupported") || normalized.includes("not support") || normalized.includes("incompatible") || normalized.includes("content type");
93188
93188
  return mentionsSse && mentionsCompatibility;
93189
93189
  }
93190
- function parseSseControlData$2(data) {
93190
+ function parseSseControlData$1(data) {
93191
93191
  let parsed;
93192
93192
  try {
93193
93193
  parsed = JSON.parse(data);
93194
93194
  } catch {
93195
- throw new ProtocolError$2("invalid sse control event JSON");
93195
+ throw new ProtocolError$1("invalid sse control event JSON");
93196
93196
  }
93197
- if (typeof parsed !== "object" || parsed == null || typeof parsed.streamNextOffset !== "string") throw new ProtocolError$2("sse control event missing streamNextOffset");
93197
+ if (typeof parsed !== "object" || parsed == null || typeof parsed.streamNextOffset !== "string") throw new ProtocolError$1("sse control event missing streamNextOffset");
93198
93198
  const streamClosed = parsed.streamClosed === true;
93199
93199
  const streamCursor = typeof parsed.streamCursor === "string" ? parsed.streamCursor : void 0;
93200
93200
  return {
@@ -93204,13 +93204,13 @@ ${val.stack}`;
93204
93204
  streamCursor
93205
93205
  };
93206
93206
  }
93207
- function decodeSsePayload$1(data, dataEncoding) {
93207
+ function decodeSsePayload(data, dataEncoding) {
93208
93208
  const normalizedEncoding = dataEncoding?.trim().toLowerCase();
93209
93209
  if (normalizedEncoding == null || normalizedEncoding.length === 0) return new TextEncoder().encode(data);
93210
- if (normalizedEncoding !== "base64") throw new ProtocolError$2(`unsupported stream-sse-data-encoding '${dataEncoding}'`);
93211
- return decodeBase64Bytes$2(data.replace(/[\r\n]/g, ""));
93210
+ if (normalizedEncoding !== "base64") throw new ProtocolError$1(`unsupported stream-sse-data-encoding '${dataEncoding}'`);
93211
+ return decodeBase64Bytes$1(data.replace(/[\r\n]/g, ""));
93212
93212
  }
93213
- async function* readSseEvents$1(stream2, options = {}) {
93213
+ async function* readSseEvents(stream2, options = {}) {
93214
93214
  const reader2 = stream2.getReader();
93215
93215
  const decoder2 = new TextDecoder();
93216
93216
  let pendingText = "";
@@ -93296,7 +93296,7 @@ ${val.stack}`;
93296
93296
  }
93297
93297
  }
93298
93298
  }
93299
- function decodeBase64Bytes$2(encoded) {
93299
+ function decodeBase64Bytes$1(encoded) {
93300
93300
  if (typeof Buffer !== "undefined") return new Uint8Array(Buffer.from(encoded, "base64"));
93301
93301
  if (typeof atob === "function") {
93302
93302
  const binary2 = atob(encoded);
@@ -93306,7 +93306,7 @@ ${val.stack}`;
93306
93306
  }
93307
93307
  throw new Error("base64 decoding is unavailable");
93308
93308
  }
93309
- var StreamsClient$1 = class StreamsClient {
93309
+ var StreamsClient = class {
93310
93310
  streamUrl;
93311
93311
  http;
93312
93312
  defaultHeaders;
@@ -93319,19 +93319,19 @@ ${val.stack}`;
93319
93319
  this.streamUrl = options.url instanceof URL ? new URL(options.url) : new URL(options.url);
93320
93320
  const fetchImpl = options.fetch ?? globalThis.fetch?.bind(globalThis);
93321
93321
  if (typeof fetchImpl !== "function") throw new Error("fetch is unavailable; pass options.fetch explicitly");
93322
- this.http = new AuthorizedHttpClient$1({
93322
+ this.http = new AuthorizedHttpClient({
93323
93323
  fetchImpl,
93324
93324
  auth: options.auth
93325
93325
  });
93326
93326
  this.defaultHeaders = new Headers(options.headers);
93327
- this.retryConfig = normalizeRetryConfig$1(options.retry);
93328
- this.timeoutConfig = normalizeTimeoutConfig$1(options.timeout);
93327
+ this.retryConfig = normalizeRetryConfig(options.retry);
93328
+ this.timeoutConfig = normalizeTimeoutConfig(options.timeout);
93329
93329
  this.onRetry = options.onRetry;
93330
93330
  }
93331
93331
  async create(input2 = {}) {
93332
- validateCreateInput$1(input2);
93333
- const part = input2.part == null ? void 0 : normalizeStreamPartLike$1(input2.part);
93334
- const requestedContentType = part?.contentType ?? normalizeOptionalContentType$1(input2.contentType) ?? void 0;
93332
+ validateCreateInput(input2);
93333
+ const part = input2.part == null ? void 0 : normalizeStreamPartLike(input2.part);
93334
+ const requestedContentType = part?.contentType ?? normalizeOptionalContentType(input2.contentType) ?? void 0;
93335
93335
  try {
93336
93336
  const requestUrl = this.streamEndpoint();
93337
93337
  const headers = this.mergeHeaders(input2.headers);
@@ -93342,14 +93342,14 @@ ${val.stack}`;
93342
93342
  const response = await this.http.fetchAuthorized(requestUrl, {
93343
93343
  method: "PUT",
93344
93344
  headers,
93345
- body: part == null ? void 0 : toRequestBody$1(part.body)
93345
+ body: part == null ? void 0 : toRequestBody(part.body)
93346
93346
  }, this.timeoutConfig.connectTimeoutMs, "connect");
93347
93347
  if (response.status !== 200 && response.status !== 201) return {
93348
93348
  ok: false,
93349
- result: await responseToStreamError$1(response, "create")
93349
+ result: await responseToStreamError(response, "create")
93350
93350
  };
93351
93351
  const contentType = this.resolveContentType(response, "create", requestedContentType ?? "application/octet-stream");
93352
- const nextOffset = getRequiredHeader$1(response.headers, "Stream-Next-Offset", "create");
93352
+ const nextOffset = getRequiredHeader(response.headers, "Stream-Next-Offset", "create");
93353
93353
  this.knownContentType = contentType;
93354
93354
  return {
93355
93355
  ok: true,
@@ -93357,13 +93357,13 @@ ${val.stack}`;
93357
93357
  created: response.status === 201,
93358
93358
  contentType,
93359
93359
  nextOffset,
93360
- closed: hasTrueHeader$1(response.headers, "Stream-Closed")
93360
+ closed: hasTrueHeader(response.headers, "Stream-Closed")
93361
93361
  }, input2, "PUT", requestUrl, response)
93362
93362
  };
93363
93363
  } catch (error2) {
93364
93364
  return {
93365
93365
  ok: false,
93366
- result: thrownToStreamError$1(error2)
93366
+ result: thrownToStreamError(error2)
93367
93367
  };
93368
93368
  }
93369
93369
  }
@@ -93372,7 +93372,8 @@ ${val.stack}`;
93372
93372
  const requestUrl = this.streamEndpoint();
93373
93373
  const response = await this.http.fetchAuthorized(requestUrl, {
93374
93374
  method: "DELETE",
93375
- headers: this.mergeHeaders(input2.headers)
93375
+ headers: this.mergeHeaders(input2.headers),
93376
+ signal: input2.signal
93376
93377
  }, this.timeoutConfig.connectTimeoutMs, "connect");
93377
93378
  if (response.status === 404) return {
93378
93379
  ok: true,
@@ -93382,7 +93383,7 @@ ${val.stack}`;
93382
93383
  };
93383
93384
  if (response.status !== 200 && response.status !== 204) return {
93384
93385
  ok: false,
93385
- result: await responseToStreamError$1(response, "delete")
93386
+ result: await responseToStreamError(response, "delete")
93386
93387
  };
93387
93388
  return {
93388
93389
  ok: true,
@@ -93393,7 +93394,7 @@ ${val.stack}`;
93393
93394
  } catch (error2) {
93394
93395
  return {
93395
93396
  ok: false,
93396
- result: thrownToStreamError$1(error2)
93397
+ result: thrownToStreamError(error2)
93397
93398
  };
93398
93399
  }
93399
93400
  }
@@ -93402,22 +93403,23 @@ ${val.stack}`;
93402
93403
  const requestUrl = this.streamEndpoint();
93403
93404
  const response = await this.http.fetchAuthorized(requestUrl, {
93404
93405
  method: "HEAD",
93405
- headers: this.mergeHeaders(input2.headers)
93406
+ headers: this.mergeHeaders(input2.headers),
93407
+ signal: input2.signal
93406
93408
  }, this.timeoutConfig.connectTimeoutMs, "connect");
93407
93409
  if (!response.ok) return {
93408
93410
  ok: false,
93409
- result: await responseToStreamError$1(response, "head")
93411
+ result: await responseToStreamError(response, "head")
93410
93412
  };
93411
93413
  const contentType = this.resolveContentType(response, "head", this.knownContentType);
93412
- const nextOffset = getRequiredHeader$1(response.headers, "Stream-Next-Offset", "head");
93414
+ const nextOffset = getRequiredHeader(response.headers, "Stream-Next-Offset", "head");
93413
93415
  this.knownContentType = contentType;
93414
93416
  return {
93415
93417
  ok: true,
93416
93418
  result: this.withMeta({
93417
93419
  contentType,
93418
93420
  nextOffset,
93419
- closed: hasTrueHeader$1(response.headers, "Stream-Closed"),
93420
- ttlSeconds: parseOptionalInteger$2(response.headers.get("Stream-TTL")) ?? void 0,
93421
+ closed: hasTrueHeader(response.headers, "Stream-Closed"),
93422
+ ttlSeconds: parseOptionalInteger(response.headers.get("Stream-TTL")) ?? void 0,
93421
93423
  expiresAt: response.headers.get("Stream-Expires-At") ?? void 0,
93422
93424
  snapshotOffset: response.headers.get("Stream-Snapshot-Offset") ?? void 0
93423
93425
  }, input2, "HEAD", requestUrl, response)
@@ -93425,26 +93427,26 @@ ${val.stack}`;
93425
93427
  } catch (error2) {
93426
93428
  return {
93427
93429
  ok: false,
93428
- result: thrownToStreamError$1(error2)
93430
+ result: thrownToStreamError(error2)
93429
93431
  };
93430
93432
  }
93431
93433
  }
93432
93434
  async append(input2) {
93433
- validateAppendInput$1(input2);
93434
- const part = input2.part == null ? void 0 : normalizeStreamPartLike$1(input2.part);
93435
+ validateAppendInput(input2);
93436
+ const part = input2.part == null ? void 0 : normalizeStreamPartLike(input2.part);
93435
93437
  let attempt = 0;
93436
93438
  while (true) try {
93437
93439
  const requestUrl = this.streamEndpoint();
93438
93440
  const response = await this.http.fetchAuthorized(requestUrl, {
93439
93441
  method: "POST",
93440
93442
  headers: this.appendHeaders(input2, part?.contentType),
93441
- body: part == null ? void 0 : toRequestBody$1(part.body)
93443
+ body: part == null ? void 0 : toRequestBody(part.body)
93442
93444
  }, this.timeoutConfig.connectTimeoutMs, "connect", {
93443
93445
  shouldRetryAuthFailure: (nextResponse) => nextResponse.status === 401 || nextResponse.status === 403 && nextResponse.headers.get("Producer-Epoch") == null
93444
93446
  });
93445
93447
  if (response.status !== 200 && response.status !== 204) return {
93446
93448
  ok: false,
93447
- result: await responseToStreamError$1(response, "append")
93449
+ result: await responseToStreamError(response, "append")
93448
93450
  };
93449
93451
  if (part != null) this.knownContentType = part.contentType;
93450
93452
  return {
@@ -93452,12 +93454,12 @@ ${val.stack}`;
93452
93454
  result: this.withMeta(this.parseAppendOutput(response, input2), input2, "POST", requestUrl, response)
93453
93455
  };
93454
93456
  } catch (error2) {
93455
- const result = thrownToStreamError$1(error2);
93456
- if (input2.producer == null || !isAppendRetryable$1(result) || attempt >= this.retryConfig.maxAttempts) return {
93457
+ const result = thrownToStreamError(error2);
93458
+ if (input2.producer == null || !isAppendRetryable(result) || attempt >= this.retryConfig.maxAttempts) return {
93457
93459
  ok: false,
93458
93460
  result
93459
93461
  };
93460
- const delay2 = computeRetryDelay$2(attempt, this.retryConfig);
93462
+ const delay2 = computeRetryDelay$1(attempt, this.retryConfig);
93461
93463
  attempt += 1;
93462
93464
  this.onRetry?.({
93463
93465
  operation: "append",
@@ -93466,7 +93468,7 @@ ${val.stack}`;
93466
93468
  delayMs: delay2,
93467
93469
  maxAttempts: this.retryConfig.maxAttempts
93468
93470
  });
93469
- await sleep$3(delay2);
93471
+ await sleep$2(delay2);
93470
93472
  }
93471
93473
  }
93472
93474
  async close(input2 = {}) {
@@ -93501,7 +93503,7 @@ ${val.stack}`;
93501
93503
  };
93502
93504
  }
93503
93505
  async readOnce(input2 = {}) {
93504
- validateReadOnceInput$1(input2);
93506
+ validateReadOnceInput(input2);
93505
93507
  const requestOffset = input2.offset ?? "-1";
93506
93508
  try {
93507
93509
  const requestUrl = this.readEndpoint({
@@ -93518,12 +93520,12 @@ ${val.stack}`;
93518
93520
  }, timeoutMs, phase);
93519
93521
  if (!response.ok) return {
93520
93522
  ok: false,
93521
- result: await responseToStreamError$1(response, "read once")
93523
+ result: await responseToStreamError(response, "read once")
93522
93524
  };
93523
93525
  if (response.status === 204) {
93524
- const nextOffset = getRequiredHeader$1(response.headers, "Stream-Next-Offset", "read once");
93525
- if (!hasTrueHeader$1(response.headers, "Stream-Up-To-Date")) throw new ProtocolError$2("long-poll 204 response missing Stream-Up-To-Date: true");
93526
- const closed = hasTrueHeader$1(response.headers, "Stream-Closed");
93526
+ const nextOffset = getRequiredHeader(response.headers, "Stream-Next-Offset", "read once");
93527
+ if (!hasTrueHeader(response.headers, "Stream-Up-To-Date")) throw new ProtocolError$1("long-poll 204 response missing Stream-Up-To-Date: true");
93528
+ const closed = hasTrueHeader(response.headers, "Stream-Closed");
93527
93529
  const cursor = response.headers.get("Stream-Cursor") ?? void 0;
93528
93530
  return {
93529
93531
  ok: true,
@@ -93549,7 +93551,7 @@ ${val.stack}`;
93549
93551
  } catch (error2) {
93550
93552
  return {
93551
93553
  ok: false,
93552
- result: thrownToStreamError$1(error2)
93554
+ result: thrownToStreamError(error2)
93553
93555
  };
93554
93556
  }
93555
93557
  }
@@ -93558,28 +93560,29 @@ ${val.stack}`;
93558
93560
  const requestUrl = this.subresourceEndpoint("/bootstrap");
93559
93561
  const response = await this.http.fetchAuthorized(requestUrl, {
93560
93562
  method: "GET",
93561
- headers: this.mergeHeaders(input2.headers)
93563
+ headers: this.mergeHeaders(input2.headers),
93564
+ signal: input2.signal
93562
93565
  }, this.timeoutConfig.connectTimeoutMs, "connect");
93563
93566
  if (!response.ok) return {
93564
93567
  ok: false,
93565
- result: await responseToStreamError$1(response, "bootstrap")
93566
- };
93567
- const boundary = extractBoundary$1(response.headers.get("Content-Type") ?? "");
93568
- if (boundary == null) throw new ProtocolError$2("bootstrap response must be multipart/mixed");
93569
- const nextOffset = getRequiredHeader$1(response.headers, "Stream-Next-Offset", "bootstrap");
93570
- const snapshotOffset = getRequiredHeader$1(response.headers, "Stream-Snapshot-Offset", "bootstrap");
93571
- const parts2 = decodeMultipartMixed$1(boundary, new Uint8Array(await response.arrayBuffer()));
93572
- if (parts2.length === 0) throw new ProtocolError$2("bootstrap response must include at least one MIME part");
93568
+ result: await responseToStreamError(response, "bootstrap")
93569
+ };
93570
+ const boundary = extractBoundary(response.headers.get("Content-Type") ?? "");
93571
+ if (boundary == null) throw new ProtocolError$1("bootstrap response must be multipart/mixed");
93572
+ const nextOffset = getRequiredHeader(response.headers, "Stream-Next-Offset", "bootstrap");
93573
+ const snapshotOffset = getRequiredHeader(response.headers, "Stream-Snapshot-Offset", "bootstrap");
93574
+ const parts2 = decodeMultipartMixed(boundary, new Uint8Array(await response.arrayBuffer()));
93575
+ if (parts2.length === 0) throw new ProtocolError$1("bootstrap response must include at least one MIME part");
93573
93576
  const first2 = parts2[0];
93574
- const snapshot = snapshotOffset === "-1" && first2?.body.byteLength === 0 ? null : createStreamPart$1(first2.contentType, first2.body);
93575
- const updates = parts2.slice(1).map((part) => createStreamPart$1(part.contentType, part.body));
93577
+ const snapshot = snapshotOffset === "-1" && first2?.body.byteLength === 0 ? null : createStreamPart(first2.contentType, first2.body);
93578
+ const updates = parts2.slice(1).map((part) => createStreamPart(part.contentType, part.body));
93576
93579
  if (updates.length > 0) this.knownContentType = updates[0].contentType;
93577
93580
  return {
93578
93581
  ok: true,
93579
93582
  result: this.withMeta({
93580
93583
  snapshotOffset,
93581
93584
  nextOffset,
93582
- upToDate: hasTrueHeader$1(response.headers, "Stream-Up-To-Date"),
93585
+ upToDate: hasTrueHeader(response.headers, "Stream-Up-To-Date"),
93583
93586
  cursor: response.headers.get("Stream-Cursor") ?? void 0,
93584
93587
  snapshot,
93585
93588
  updates
@@ -93588,7 +93591,7 @@ ${val.stack}`;
93588
93591
  } catch (error2) {
93589
93592
  return {
93590
93593
  ok: false,
93591
- result: thrownToStreamError$1(error2)
93594
+ result: thrownToStreamError(error2)
93592
93595
  };
93593
93596
  }
93594
93597
  }
@@ -93597,7 +93600,8 @@ ${val.stack}`;
93597
93600
  const requestUrl = this.subresourceEndpoint("/snapshot");
93598
93601
  const response = await this.http.fetchAuthorized(requestUrl, {
93599
93602
  method: "GET",
93600
- headers: this.mergeHeaders(input2.headers)
93603
+ headers: this.mergeHeaders(input2.headers),
93604
+ signal: input2.signal
93601
93605
  }, this.timeoutConfig.connectTimeoutMs, "connect");
93602
93606
  if (response.status === 404) return {
93603
93607
  ok: true,
@@ -93605,7 +93609,7 @@ ${val.stack}`;
93605
93609
  };
93606
93610
  if (!response.ok) return {
93607
93611
  ok: false,
93608
- result: await responseToStreamError$1(response, "read latest snapshot")
93612
+ result: await responseToStreamError(response, "read latest snapshot")
93609
93613
  };
93610
93614
  return {
93611
93615
  ok: true,
@@ -93614,21 +93618,22 @@ ${val.stack}`;
93614
93618
  } catch (error2) {
93615
93619
  return {
93616
93620
  ok: false,
93617
- result: thrownToStreamError$1(error2)
93621
+ result: thrownToStreamError(error2)
93618
93622
  };
93619
93623
  }
93620
93624
  }
93621
93625
  async readSnapshot(offset2, input2 = {}) {
93622
- assertNonEmptyString$1(offset2, "offset");
93626
+ assertNonEmptyString(offset2, "offset");
93623
93627
  try {
93624
93628
  const requestUrl = this.subresourceEndpoint(`/snapshot/${encodeURIComponent(offset2)}`);
93625
93629
  const response = await this.http.fetchAuthorized(requestUrl, {
93626
93630
  method: "GET",
93627
- headers: this.mergeHeaders(input2.headers)
93631
+ headers: this.mergeHeaders(input2.headers),
93632
+ signal: input2.signal
93628
93633
  }, this.timeoutConfig.connectTimeoutMs, "connect");
93629
93634
  if (!response.ok) return {
93630
93635
  ok: false,
93631
- result: await responseToStreamError$1(response, "read snapshot")
93636
+ result: await responseToStreamError(response, "read snapshot")
93632
93637
  };
93633
93638
  return {
93634
93639
  ok: true,
@@ -93637,13 +93642,13 @@ ${val.stack}`;
93637
93642
  } catch (error2) {
93638
93643
  return {
93639
93644
  ok: false,
93640
- result: thrownToStreamError$1(error2)
93645
+ result: thrownToStreamError(error2)
93641
93646
  };
93642
93647
  }
93643
93648
  }
93644
93649
  async putSnapshot(input2) {
93645
- assertNonEmptyString$1(input2.offset, "offset");
93646
- const part = normalizeStreamPartLike$1(input2.part);
93650
+ assertNonEmptyString(input2.offset, "offset");
93651
+ const part = normalizeStreamPartLike(input2.part);
93647
93652
  try {
93648
93653
  const requestUrl = this.subresourceEndpoint(`/snapshot/${encodeURIComponent(input2.offset)}`);
93649
93654
  const response = await this.http.fetchAuthorized(requestUrl, {
@@ -93651,11 +93656,11 @@ ${val.stack}`;
93651
93656
  headers: this.mergeHeaders(input2.headers, {
93652
93657
  "Content-Type": part.contentType
93653
93658
  }),
93654
- body: toRequestBody$1(part.body)
93659
+ body: toRequestBody(part.body)
93655
93660
  }, this.timeoutConfig.connectTimeoutMs, "connect");
93656
93661
  if (response.status !== 200 && response.status !== 204) return {
93657
93662
  ok: false,
93658
- result: await responseToStreamError$1(response, "put snapshot")
93663
+ result: await responseToStreamError(response, "put snapshot")
93659
93664
  };
93660
93665
  return {
93661
93666
  ok: true,
@@ -93667,17 +93672,18 @@ ${val.stack}`;
93667
93672
  } catch (error2) {
93668
93673
  return {
93669
93674
  ok: false,
93670
- result: thrownToStreamError$1(error2)
93675
+ result: thrownToStreamError(error2)
93671
93676
  };
93672
93677
  }
93673
93678
  }
93674
93679
  async deleteSnapshot(offset2, input2 = {}) {
93675
- assertNonEmptyString$1(offset2, "offset");
93680
+ assertNonEmptyString(offset2, "offset");
93676
93681
  try {
93677
93682
  const requestUrl = this.subresourceEndpoint(`/snapshot/${encodeURIComponent(offset2)}`);
93678
93683
  const response = await this.http.fetchAuthorized(requestUrl, {
93679
93684
  method: "DELETE",
93680
- headers: this.mergeHeaders(input2.headers)
93685
+ headers: this.mergeHeaders(input2.headers),
93686
+ signal: input2.signal
93681
93687
  }, this.timeoutConfig.connectTimeoutMs, "connect");
93682
93688
  if (response.status === 404) return {
93683
93689
  ok: true,
@@ -93687,7 +93693,7 @@ ${val.stack}`;
93687
93693
  };
93688
93694
  if (response.status !== 200 && response.status !== 204) return {
93689
93695
  ok: false,
93690
- result: await responseToStreamError$1(response, "delete snapshot")
93696
+ result: await responseToStreamError(response, "delete snapshot")
93691
93697
  };
93692
93698
  return {
93693
93699
  ok: true,
@@ -93698,19 +93704,19 @@ ${val.stack}`;
93698
93704
  } catch (error2) {
93699
93705
  return {
93700
93706
  ok: false,
93701
- result: thrownToStreamError$1(error2)
93707
+ result: thrownToStreamError(error2)
93702
93708
  };
93703
93709
  }
93704
93710
  }
93705
93711
  async openSseSession(input2) {
93706
- validateOpenSseSessionInput$1(input2);
93712
+ validateOpenSseSessionInput(input2);
93707
93713
  const requestUrl = this.readEndpoint({
93708
93714
  offset: input2.offset,
93709
93715
  cursor: input2.cursor,
93710
93716
  live: "sse"
93711
93717
  });
93712
93718
  const controller = new AbortController();
93713
- const signal = mergeAbortSignals$3(input2.signal, controller.signal);
93719
+ const signal = mergeAbortSignals$2(input2.signal, controller.signal);
93714
93720
  try {
93715
93721
  const response = await this.http.fetchAuthorized(requestUrl, {
93716
93722
  method: "GET",
@@ -93721,11 +93727,11 @@ ${val.stack}`;
93721
93727
  }, this.timeoutConfig.connectTimeoutMs, "connect");
93722
93728
  if (!response.ok) return {
93723
93729
  ok: false,
93724
- result: await responseToStreamError$1(response, "open sse session")
93730
+ result: await responseToStreamError(response, "open sse session")
93725
93731
  };
93726
- if (response.body == null) throw new ProtocolError$2("sse response missing body");
93727
- if (!(response.headers.get("Content-Type") ?? "").toLowerCase().includes("text/event-stream")) throw new ProtocolError$2("sse response must use text/event-stream content type");
93728
- const events = createSessionEvents$1(response.body, signal, input2.onActivity);
93732
+ if (response.body == null) throw new ProtocolError$1("sse response missing body");
93733
+ if (!(response.headers.get("Content-Type") ?? "").toLowerCase().includes("text/event-stream")) throw new ProtocolError$1("sse response must use text/event-stream content type");
93734
+ const events = createSessionEvents(response.body, signal, input2.onActivity);
93729
93735
  return {
93730
93736
  ok: true,
93731
93737
  result: {
@@ -93733,7 +93739,7 @@ ${val.stack}`;
93733
93739
  cursor: response.headers.get("Stream-Cursor") ?? void 0,
93734
93740
  dataEncoding: response.headers.get("Stream-SSE-Data-Encoding") ?? void 0,
93735
93741
  events,
93736
- meta: input2.includeMeta === true ? createOperationMeta$1("GET", requestUrl, response) : void 0,
93742
+ meta: input2.includeMeta === true ? createOperationMeta("GET", requestUrl, response) : void 0,
93737
93743
  cancel: async () => {
93738
93744
  controller.abort(new DOMException("Aborted", "AbortError"));
93739
93745
  try {
@@ -93746,12 +93752,12 @@ ${val.stack}`;
93746
93752
  } catch (error2) {
93747
93753
  return {
93748
93754
  ok: false,
93749
- result: thrownToStreamError$1(error2)
93755
+ result: thrownToStreamError(error2)
93750
93756
  };
93751
93757
  }
93752
93758
  }
93753
93759
  live(input2) {
93754
- validateLiveInput$1(input2);
93760
+ validateLiveInput(input2);
93755
93761
  return this.liveInternal({
93756
93762
  offset: input2.offset,
93757
93763
  mode: input2.mode ?? "auto",
@@ -93798,7 +93804,7 @@ ${val.stack}`;
93798
93804
  }, this.timeoutConfig.connectTimeoutMs, "connect");
93799
93805
  if (response.status === 400) {
93800
93806
  const errorText = await response.text();
93801
- if (allowFallback && isSseUnsupportedErrorText$2(errorText)) return "fallback";
93807
+ if (allowFallback && isSseUnsupportedErrorText$1(errorText)) return "fallback";
93802
93808
  yield {
93803
93809
  type: "error",
93804
93810
  mode: "sse",
@@ -93814,12 +93820,12 @@ ${val.stack}`;
93814
93820
  yield {
93815
93821
  type: "error",
93816
93822
  mode: "sse",
93817
- error: await responseToStreamError$1(response, "live sse")
93823
+ error: await responseToStreamError(response, "live sse")
93818
93824
  };
93819
93825
  return "done";
93820
93826
  }
93821
- if (response.body == null) throw new ProtocolError$2("sse response missing body");
93822
- if (!(response.headers.get("Content-Type") ?? "").toLowerCase().includes("text/event-stream")) throw new ProtocolError$2("sse response must use text/event-stream content type");
93827
+ if (response.body == null) throw new ProtocolError$1("sse response missing body");
93828
+ if (!(response.headers.get("Content-Type") ?? "").toLowerCase().includes("text/event-stream")) throw new ProtocolError$1("sse response must use text/event-stream content type");
93823
93829
  if (reconnectAttempt > 0) yield {
93824
93830
  type: "reconnected",
93825
93831
  mode: "sse",
@@ -93830,15 +93836,15 @@ ${val.stack}`;
93830
93836
  const dataEncoding = response.headers.get("stream-sse-data-encoding");
93831
93837
  let pendingPayloads = [];
93832
93838
  let sawControlEvent = false;
93833
- for await (const event of readSseEvents$1(response.body, {
93839
+ for await (const event of readSseEvents(response.body, {
93834
93840
  signal
93835
93841
  })) {
93836
93842
  if (event.event === "data") {
93837
- pendingPayloads.push(decodeSsePayload$1(event.data, dataEncoding));
93843
+ pendingPayloads.push(decodeSsePayload(event.data, dataEncoding));
93838
93844
  continue;
93839
93845
  }
93840
93846
  if (event.event !== "control") continue;
93841
- const control = parseSseControlData$2(event.data);
93847
+ const control = parseSseControlData$1(event.data);
93842
93848
  sawControlEvent = true;
93843
93849
  state2.offset = control.nextOffset;
93844
93850
  const effectiveCursor = control.streamCursor ?? state2.cursor;
@@ -93848,7 +93854,7 @@ ${val.stack}`;
93848
93854
  mode: "sse",
93849
93855
  nextOffset: control.nextOffset,
93850
93856
  cursor: effectiveCursor,
93851
- payload: createStreamPart$1(state2.contentType, payload)
93857
+ payload: createStreamPart(state2.contentType, payload)
93852
93858
  };
93853
93859
  pendingPayloads = [];
93854
93860
  if (control.streamClosed) {
@@ -93871,10 +93877,10 @@ ${val.stack}`;
93871
93877
  if (sawControlEvent) continue;
93872
93878
  throw new TypeError("sse connection closed");
93873
93879
  } catch (error2) {
93874
- if (signal?.aborted && isAbortError$1(error2)) return "done";
93875
- const mapped = thrownToStreamError$1(error2);
93876
- if (!isRetryableLiveError$1(mapped) || attempt >= this.retryConfig.maxAttempts) {
93877
- const retryExhausted = isRetryableLiveError$1(mapped) && attempt >= this.retryConfig.maxAttempts;
93880
+ if (signal?.aborted && isAbortError(error2)) return "done";
93881
+ const mapped = thrownToStreamError(error2);
93882
+ if (!isRetryableLiveError(mapped) || attempt >= this.retryConfig.maxAttempts) {
93883
+ const retryExhausted = isRetryableLiveError(mapped) && attempt >= this.retryConfig.maxAttempts;
93878
93884
  yield {
93879
93885
  type: "error",
93880
93886
  mode: "sse",
@@ -93885,7 +93891,7 @@ ${val.stack}`;
93885
93891
  };
93886
93892
  return "done";
93887
93893
  }
93888
- const delayMs = computeRetryDelay$2(attempt, this.retryConfig);
93894
+ const delayMs = computeRetryDelay$1(attempt, this.retryConfig);
93889
93895
  const nextAttempt = attempt + 1;
93890
93896
  this.onRetry?.({
93891
93897
  operation: "live-sse",
@@ -93902,7 +93908,7 @@ ${val.stack}`;
93902
93908
  error: mapped
93903
93909
  };
93904
93910
  try {
93905
- await sleep$3(delayMs, signal);
93911
+ await sleep$2(delayMs, signal);
93906
93912
  } catch {
93907
93913
  return "done";
93908
93914
  }
@@ -93926,9 +93932,9 @@ ${val.stack}`;
93926
93932
  signal
93927
93933
  }, this.timeoutConfig.pollTimeoutMs, "poll");
93928
93934
  if (response.status === 204) {
93929
- const nextOffset = getRequiredHeader$1(response.headers, "Stream-Next-Offset", "live long-poll");
93930
- if (!hasTrueHeader$1(response.headers, "Stream-Up-To-Date")) throw new ProtocolError$2("long-poll 204 response missing Stream-Up-To-Date: true");
93931
- const closed = hasTrueHeader$1(response.headers, "Stream-Closed");
93935
+ const nextOffset = getRequiredHeader(response.headers, "Stream-Next-Offset", "live long-poll");
93936
+ if (!hasTrueHeader(response.headers, "Stream-Up-To-Date")) throw new ProtocolError$1("long-poll 204 response missing Stream-Up-To-Date: true");
93937
+ const closed = hasTrueHeader(response.headers, "Stream-Closed");
93932
93938
  const effectiveCursor = response.headers.get("Stream-Cursor") ?? void 0 ?? state2.cursor;
93933
93939
  if (reconnectAttempt > 0) yield {
93934
93940
  type: "reconnected",
@@ -93959,7 +93965,7 @@ ${val.stack}`;
93959
93965
  yield {
93960
93966
  type: "error",
93961
93967
  mode: "long-poll",
93962
- error: await responseToStreamError$1(response, "live long-poll")
93968
+ error: await responseToStreamError(response, "live long-poll")
93963
93969
  };
93964
93970
  return;
93965
93971
  }
@@ -93996,10 +94002,10 @@ ${val.stack}`;
93996
94002
  cursor: outputCursor
93997
94003
  };
93998
94004
  } catch (error2) {
93999
- if (signal?.aborted && isAbortError$1(error2)) return;
94000
- const mapped = thrownToStreamError$1(error2);
94001
- if (!isRetryableLiveError$1(mapped) || attempt >= this.retryConfig.maxAttempts) {
94002
- const retryExhausted = isRetryableLiveError$1(mapped) && attempt >= this.retryConfig.maxAttempts;
94005
+ if (signal?.aborted && isAbortError(error2)) return;
94006
+ const mapped = thrownToStreamError(error2);
94007
+ if (!isRetryableLiveError(mapped) || attempt >= this.retryConfig.maxAttempts) {
94008
+ const retryExhausted = isRetryableLiveError(mapped) && attempt >= this.retryConfig.maxAttempts;
94003
94009
  yield {
94004
94010
  type: "error",
94005
94011
  mode: "long-poll",
@@ -94010,7 +94016,7 @@ ${val.stack}`;
94010
94016
  };
94011
94017
  return;
94012
94018
  }
94013
- const delayMs = computeRetryDelay$2(attempt, this.retryConfig);
94019
+ const delayMs = computeRetryDelay$1(attempt, this.retryConfig);
94014
94020
  const nextAttempt = attempt + 1;
94015
94021
  this.onRetry?.({
94016
94022
  operation: "live-long-poll",
@@ -94027,7 +94033,7 @@ ${val.stack}`;
94027
94033
  error: mapped
94028
94034
  };
94029
94035
  try {
94030
- await sleep$3(delayMs, signal);
94036
+ await sleep$2(delayMs, signal);
94031
94037
  } catch {
94032
94038
  return;
94033
94039
  }
@@ -94062,17 +94068,17 @@ ${val.stack}`;
94062
94068
  if (input2?.includeMeta !== true) return result;
94063
94069
  return {
94064
94070
  ...result,
94065
- meta: createOperationMeta$1(method, url, response)
94071
+ meta: createOperationMeta(method, url, response)
94066
94072
  };
94067
94073
  }
94068
94074
  parseAppendOutput(response, input2) {
94069
94075
  return {
94070
94076
  status: response.status,
94071
- nextOffset: getRequiredHeader$1(response.headers, "Stream-Next-Offset", "append"),
94072
- closed: hasTrueHeader$1(response.headers, "Stream-Closed"),
94077
+ nextOffset: getRequiredHeader(response.headers, "Stream-Next-Offset", "append"),
94078
+ closed: hasTrueHeader(response.headers, "Stream-Closed"),
94073
94079
  producer: input2.producer == null ? void 0 : {
94074
- epoch: parseOptionalInteger$2(response.headers.get("Producer-Epoch")) ?? input2.producer.epoch,
94075
- seq: parseOptionalInteger$2(response.headers.get("Producer-Seq")) ?? input2.producer.seq
94080
+ epoch: parseOptionalInteger(response.headers.get("Producer-Epoch")) ?? input2.producer.epoch,
94081
+ seq: parseOptionalInteger(response.headers.get("Producer-Seq")) ?? input2.producer.seq
94076
94082
  }
94077
94083
  };
94078
94084
  }
@@ -94081,20 +94087,20 @@ ${val.stack}`;
94081
94087
  this.knownContentType = contentType;
94082
94088
  return {
94083
94089
  requestOffset,
94084
- nextOffset: getRequiredHeader$1(response.headers, "Stream-Next-Offset", context2),
94085
- upToDate: hasTrueHeader$1(response.headers, "Stream-Up-To-Date"),
94086
- closed: hasTrueHeader$1(response.headers, "Stream-Closed"),
94090
+ nextOffset: getRequiredHeader(response.headers, "Stream-Next-Offset", context2),
94091
+ upToDate: hasTrueHeader(response.headers, "Stream-Up-To-Date"),
94092
+ closed: hasTrueHeader(response.headers, "Stream-Closed"),
94087
94093
  cursor: response.headers.get("Stream-Cursor") ?? void 0,
94088
- payload: createStreamPart$1(contentType, new Uint8Array(await response.arrayBuffer()))
94094
+ payload: createStreamPart(contentType, new Uint8Array(await response.arrayBuffer()))
94089
94095
  };
94090
94096
  }
94091
94097
  async parseSnapshotReadOutput(response, context2) {
94092
94098
  const contentType = this.resolveContentType(response, context2);
94093
94099
  return {
94094
- snapshotOffset: getRequiredHeader$1(response.headers, "Stream-Snapshot-Offset", context2),
94095
- nextOffset: getRequiredHeader$1(response.headers, "Stream-Next-Offset", context2),
94096
- upToDate: hasTrueHeader$1(response.headers, "Stream-Up-To-Date"),
94097
- payload: createStreamPart$1(contentType, new Uint8Array(await response.arrayBuffer()))
94100
+ snapshotOffset: getRequiredHeader(response.headers, "Stream-Snapshot-Offset", context2),
94101
+ nextOffset: getRequiredHeader(response.headers, "Stream-Next-Offset", context2),
94102
+ upToDate: hasTrueHeader(response.headers, "Stream-Up-To-Date"),
94103
+ payload: createStreamPart(contentType, new Uint8Array(await response.arrayBuffer()))
94098
94104
  };
94099
94105
  }
94100
94106
  async ensureKnownContentType() {
@@ -94114,7 +94120,7 @@ ${val.stack}`;
94114
94120
  const headerValue = response.headers.get("Content-Type");
94115
94121
  if (headerValue != null && headerValue.length > 0) return headerValue;
94116
94122
  if (fallback2 != null && fallback2.length > 0) return fallback2;
94117
- throw new ProtocolError$2(`${context2} response missing Content-Type`);
94123
+ throw new ProtocolError$1(`${context2} response missing Content-Type`);
94118
94124
  }
94119
94125
  streamEndpoint() {
94120
94126
  return this.streamUrl.toString();
@@ -94133,50 +94139,50 @@ ${val.stack}`;
94133
94139
  return target.toString();
94134
94140
  }
94135
94141
  };
94136
- function validateCreateInput$1(input2) {
94137
- if (input2.ttlSeconds != null) assertNonNegativeSafeInteger$1(input2.ttlSeconds, "ttlSeconds");
94138
- if (input2.expiresAt != null) assertNonEmptyString$1(input2.expiresAt, "expiresAt");
94142
+ function validateCreateInput(input2) {
94143
+ if (input2.ttlSeconds != null) assertNonNegativeSafeInteger(input2.ttlSeconds, "ttlSeconds");
94144
+ if (input2.expiresAt != null) assertNonEmptyString(input2.expiresAt, "expiresAt");
94139
94145
  if (input2.ttlSeconds != null && input2.expiresAt != null) throw new Error("create input must not include both ttlSeconds and expiresAt");
94140
- if (input2.contentType != null) normalizeContentType$1(input2.contentType);
94146
+ if (input2.contentType != null) normalizeContentType(input2.contentType);
94141
94147
  }
94142
- function validateAppendInput$1(input2) {
94143
- if (input2.streamSeq != null) assertNonEmptyString$1(input2.streamSeq, "streamSeq");
94148
+ function validateAppendInput(input2) {
94149
+ if (input2.streamSeq != null) assertNonEmptyString(input2.streamSeq, "streamSeq");
94144
94150
  if (input2.producer != null) {
94145
- assertNonEmptyString$1(input2.producer.producerId, "producer.producerId");
94146
- assertNonNegativeSafeInteger$1(input2.producer.epoch, "producer.epoch");
94147
- assertNonNegativeSafeInteger$1(input2.producer.seq, "producer.seq");
94151
+ assertNonEmptyString(input2.producer.producerId, "producer.producerId");
94152
+ assertNonNegativeSafeInteger(input2.producer.epoch, "producer.epoch");
94153
+ assertNonNegativeSafeInteger(input2.producer.seq, "producer.seq");
94148
94154
  }
94149
94155
  if (input2.part == null) {
94150
94156
  if (input2.close !== true) throw new Error("append requires part unless close is true");
94151
94157
  return;
94152
94158
  }
94153
- if (normalizeStreamPartLike$1(input2.part).body.byteLength === 0 && input2.close !== true) throw new Error("append requires a non-empty body unless close is true");
94159
+ if (normalizeStreamPartLike(input2.part).body.byteLength === 0 && input2.close !== true) throw new Error("append requires a non-empty body unless close is true");
94154
94160
  }
94155
- function validateReadInput$1(input2) {
94156
- if (input2.offset != null) assertNonEmptyString$1(input2.offset, "offset");
94157
- if (input2.cursor != null) assertNonEmptyString$1(input2.cursor, "cursor");
94161
+ function validateReadInput(input2) {
94162
+ if (input2.offset != null) assertNonEmptyString(input2.offset, "offset");
94163
+ if (input2.cursor != null) assertNonEmptyString(input2.cursor, "cursor");
94158
94164
  }
94159
- function validateReadOnceInput$1(input2) {
94160
- validateReadInput$1(input2);
94165
+ function validateReadOnceInput(input2) {
94166
+ validateReadInput(input2);
94161
94167
  if (input2.live != null && input2.live !== "long-poll") throw new Error("readOnce live mode must be long-poll when provided");
94162
94168
  }
94163
- function validateOpenSseSessionInput$1(input2) {
94164
- assertNonEmptyString$1(input2.offset, "offset");
94165
- if (input2.cursor != null) assertNonEmptyString$1(input2.cursor, "cursor");
94169
+ function validateOpenSseSessionInput(input2) {
94170
+ assertNonEmptyString(input2.offset, "offset");
94171
+ if (input2.cursor != null) assertNonEmptyString(input2.cursor, "cursor");
94166
94172
  }
94167
- function validateLiveInput$1(input2) {
94168
- assertNonEmptyString$1(input2.offset, "offset");
94173
+ function validateLiveInput(input2) {
94174
+ assertNonEmptyString(input2.offset, "offset");
94169
94175
  }
94170
- function assertNonEmptyString$1(value, name2) {
94176
+ function assertNonEmptyString(value, name2) {
94171
94177
  if (value.trim().length === 0) throw new Error(`${name2} must be a non-empty string`);
94172
94178
  }
94173
- function assertNonNegativeSafeInteger$1(value, name2) {
94179
+ function assertNonNegativeSafeInteger(value, name2) {
94174
94180
  if (!Number.isSafeInteger(value) || value < 0) throw new Error(`${name2} must be a non-negative safe integer`);
94175
94181
  }
94176
- function isAppendRetryable$1(error2) {
94182
+ function isAppendRetryable(error2) {
94177
94183
  return error2.code === "network_error" || error2.code === "timeout";
94178
94184
  }
94179
- function createOperationMeta$1(method, url, response) {
94185
+ function createOperationMeta(method, url, response) {
94180
94186
  return {
94181
94187
  request: {
94182
94188
  method,
@@ -94185,33 +94191,33 @@ ${val.stack}`;
94185
94191
  response: {
94186
94192
  status: response.status,
94187
94193
  statusText: response.statusText,
94188
- headers: headersToObject$2(response.headers)
94194
+ headers: headersToObject(response.headers)
94189
94195
  }
94190
94196
  };
94191
94197
  }
94192
- function headersToObject$2(headers) {
94198
+ function headersToObject(headers) {
94193
94199
  const result = {};
94194
94200
  headers.forEach((value, name2) => {
94195
94201
  result[name2] = value;
94196
94202
  });
94197
94203
  return result;
94198
94204
  }
94199
- function createSessionEvents$1(stream2, signal, onActivity) {
94205
+ function createSessionEvents(stream2, signal, onActivity) {
94200
94206
  return {
94201
94207
  async *[Symbol.asyncIterator]() {
94202
94208
  try {
94203
- yield* readSseEvents$1(stream2, {
94209
+ yield* readSseEvents(stream2, {
94204
94210
  signal,
94205
94211
  onActivity
94206
94212
  });
94207
94213
  } catch (error2) {
94208
- if (signal?.aborted && isAbortError$1(error2)) return;
94214
+ if (signal?.aborted && isAbortError(error2)) return;
94209
94215
  throw error2;
94210
94216
  }
94211
94217
  }
94212
94218
  };
94213
94219
  }
94214
- function mergeAbortSignals$3(...signals2) {
94220
+ function mergeAbortSignals$2(...signals2) {
94215
94221
  const active2 = signals2.filter((signal) => signal != null);
94216
94222
  if (active2.length === 0) return;
94217
94223
  if (active2.length === 1) return active2[0];
@@ -94366,15 +94372,15 @@ ${val.stack}`;
94366
94372
  pollTimeoutMs: 3e4,
94367
94373
  liveInactivityTimeoutMs: 45e3
94368
94374
  };
94369
- function applyJitter$1(baseMs, fraction) {
94375
+ function applyJitter(baseMs, fraction) {
94370
94376
  if (baseMs === 0) return 0;
94371
94377
  const jitter = baseMs * fraction * (2 * Math.random() - 1);
94372
94378
  return Math.max(0, Math.round(baseMs + jitter));
94373
94379
  }
94374
- function computeRetryDelay$1(attempt, config2 = DEFAULT_RECONNECT_CONFIG, minDelayMs) {
94380
+ function computeRetryDelay(attempt, config2 = DEFAULT_RECONNECT_CONFIG, minDelayMs) {
94375
94381
  const { delays, jitterFraction } = config2;
94376
94382
  const scheduled2 = delays[Math.min(attempt, delays.length - 1)];
94377
- return applyJitter$1(typeof minDelayMs === "number" && minDelayMs > scheduled2 ? minDelayMs : scheduled2, jitterFraction);
94383
+ return applyJitter(typeof minDelayMs === "number" && minDelayMs > scheduled2 ? minDelayMs : scheduled2, jitterFraction);
94378
94384
  }
94379
94385
  const BINARY_CONTENT_TYPE = "application/octet-stream";
94380
94386
  function encodeItems(items2) {
@@ -94725,7 +94731,7 @@ stream:${scope2.streamId}`;
94725
94731
  if (options?.body !== void 0 && options.body.length > 0) this.body = options.body;
94726
94732
  }
94727
94733
  };
94728
- var TimeoutError$1 = class TimeoutError extends Error {
94734
+ var TimeoutError = class extends Error {
94729
94735
  timeoutType;
94730
94736
  timeoutMs;
94731
94737
  constructor(timeoutType, timeoutMs) {
@@ -94734,7 +94740,7 @@ stream:${scope2.streamId}`;
94734
94740
  this.timeoutMs = timeoutMs;
94735
94741
  }
94736
94742
  };
94737
- var ProtocolError$1 = class ProtocolError extends Error {
94743
+ var ProtocolError = class extends Error {
94738
94744
  status;
94739
94745
  constructor(message, status) {
94740
94746
  super(message);
@@ -94751,7 +94757,7 @@ stream:${scope2.streamId}`;
94751
94757
  function isObject$1(value) {
94752
94758
  return typeof value === "object" && value != null;
94753
94759
  }
94754
- function decodeBase64Bytes$1(encoded) {
94760
+ function decodeBase64Bytes(encoded) {
94755
94761
  const normalized = encoded.replace(/[\r\n]/g, "");
94756
94762
  if (typeof Buffer !== "undefined") return new Uint8Array(Buffer.from(normalized, "base64"));
94757
94763
  if (typeof atob === "function") {
@@ -94766,10 +94772,10 @@ stream:${scope2.streamId}`;
94766
94772
  const normalized = dataEncoding?.trim().toLowerCase();
94767
94773
  if (normalized == null || normalized.length === 0) return;
94768
94774
  if (normalized === "base64") return "base64";
94769
- throw new ProtocolError$1(`unsupported stream-sse-data-encoding '${dataEncoding}'`);
94775
+ throw new ProtocolError(`unsupported stream-sse-data-encoding '${dataEncoding}'`);
94770
94776
  }
94771
94777
  function decodeSseRawPayload(data, dataEncoding) {
94772
- if (dataEncoding === "base64") return decodeBase64Bytes$1(data);
94778
+ if (dataEncoding === "base64") return decodeBase64Bytes(data);
94773
94779
  return new TextEncoder().encode(data);
94774
94780
  }
94775
94781
  function decodeSseItemPayloads(data, dataEncoding) {
@@ -94797,14 +94803,14 @@ stream:${scope2.streamId}`;
94797
94803
  ];
94798
94804
  }
94799
94805
  }
94800
- function parseSseControlData$1(data) {
94806
+ function parseSseControlData(data) {
94801
94807
  let parsed;
94802
94808
  try {
94803
94809
  parsed = JSON.parse(data);
94804
94810
  } catch {
94805
- throw new ProtocolError$1("invalid sse control event JSON");
94811
+ throw new ProtocolError("invalid sse control event JSON");
94806
94812
  }
94807
- if (!isObject$1(parsed) || typeof parsed.streamNextOffset !== "string") throw new ProtocolError$1("sse control event missing streamNextOffset");
94813
+ if (!isObject$1(parsed) || typeof parsed.streamNextOffset !== "string") throw new ProtocolError("sse control event missing streamNextOffset");
94808
94814
  const streamCursor = typeof parsed.streamCursor === "string" ? parsed.streamCursor : void 0;
94809
94815
  return {
94810
94816
  nextOffset: parsed.streamNextOffset,
@@ -94812,14 +94818,14 @@ stream:${scope2.streamId}`;
94812
94818
  streamCursor
94813
94819
  };
94814
94820
  }
94815
- function isSseUnsupportedErrorText$1(message) {
94821
+ function isSseUnsupportedErrorText(message) {
94816
94822
  const normalized = message.trim().toLowerCase();
94817
94823
  if (normalized.length === 0) return false;
94818
94824
  const mentionsSse = normalized.includes("sse") || normalized.includes("text/event-stream");
94819
94825
  const mentionsCompatibility = normalized.includes("unsupported") || normalized.includes("not support") || normalized.includes("incompatible") || normalized.includes("content type");
94820
94826
  return mentionsSse && mentionsCompatibility;
94821
94827
  }
94822
- function sleep$2(ms2, signal) {
94828
+ function sleep$1(ms2, signal) {
94823
94829
  if (signal?.aborted) return Promise.resolve();
94824
94830
  return new Promise((resolve2) => {
94825
94831
  const timer2 = setTimeout(resolve2, ms2);
@@ -94831,7 +94837,7 @@ stream:${scope2.streamId}`;
94831
94837
  });
94832
94838
  });
94833
94839
  }
94834
- function mergeAbortSignals$2(...signals2) {
94840
+ function mergeAbortSignals(...signals2) {
94835
94841
  const active2 = signals2.filter((signal) => signal != null);
94836
94842
  if (active2.length === 0) return;
94837
94843
  if (active2.length === 1) return active2[0];
@@ -94889,13 +94895,13 @@ stream:${scope2.streamId}`;
94889
94895
  retriable: true,
94890
94896
  atMs: Date.now()
94891
94897
  };
94892
- if (err2 instanceof ProtocolError$1) return {
94898
+ if (err2 instanceof ProtocolError) return {
94893
94899
  code: "protocol",
94894
94900
  message,
94895
94901
  retriable: false,
94896
94902
  atMs: Date.now()
94897
94903
  };
94898
- if (err2 instanceof TimeoutError$1) return {
94904
+ if (err2 instanceof TimeoutError) return {
94899
94905
  code: "timeout",
94900
94906
  message,
94901
94907
  retriable: true,
@@ -94972,13 +94978,13 @@ stream:${scope2.streamId}`;
94972
94978
  body: error2.body
94973
94979
  }
94974
94980
  };
94975
- if (error2 instanceof ProtocolError$1) return {
94981
+ if (error2 instanceof ProtocolError) return {
94976
94982
  code: "protocol_error",
94977
94983
  retryable: false,
94978
94984
  status: error2.status,
94979
94985
  message: error2.message
94980
94986
  };
94981
- if (error2 instanceof TimeoutError$1) return {
94987
+ if (error2 instanceof TimeoutError) return {
94982
94988
  code: "timeout",
94983
94989
  retryable: true,
94984
94990
  phase: error2.timeoutType,
@@ -95038,7 +95044,7 @@ stream:${scope2.streamId}`;
95038
95044
  return !result.upToDate && result.updates.length === 0 && result.nextOffset === requestOffset;
95039
95045
  }
95040
95046
  function isAuthOrProtocolError(error2) {
95041
- return error2 instanceof ProtocolError$1 || error2 instanceof HttpError && [
95047
+ return error2 instanceof ProtocolError || error2 instanceof HttpError && [
95042
95048
  400,
95043
95049
  401,
95044
95050
  403,
@@ -95046,7 +95052,7 @@ stream:${scope2.streamId}`;
95046
95052
  409
95047
95053
  ].includes(error2.status);
95048
95054
  }
95049
- function normalizeAuthProvider$1(auth) {
95055
+ function normalizeAuthProvider(auth) {
95050
95056
  if (auth == null) return;
95051
95057
  if (typeof auth === "string") {
95052
95058
  const token2 = auth.trim();
@@ -95125,6 +95131,57 @@ stream:${scope2.streamId}`;
95125
95131
  if (current2 != null && incoming != null) return incoming > current2 ? responseNextOffset : currentOffset;
95126
95132
  return currentOffset;
95127
95133
  }
95134
+ const bodySizeEncoder = new TextEncoder();
95135
+ function normalizeShardOrigins(urls, label2) {
95136
+ if (urls == null) return;
95137
+ const out2 = [];
95138
+ for (const raw of urls) {
95139
+ const trimmed = raw.trim();
95140
+ if (trimmed.length === 0) continue;
95141
+ const url = new URL(trimmed);
95142
+ if (url.protocol !== "http:" && url.protocol !== "https:") throw new Error(`${label2} shard URL must use http or https`);
95143
+ if (url.pathname !== "/" || url.search !== "" || url.hash !== "") throw new Error(`${label2} shard URL must be an origin URL`);
95144
+ out2.push(url.origin);
95145
+ }
95146
+ return out2.length === 0 ? void 0 : out2;
95147
+ }
95148
+ function normalizeShardUrlsOptions(options) {
95149
+ if (options == null) return;
95150
+ const largePostMinBytes = options.largePostMinBytes ?? 0;
95151
+ if (!Number.isSafeInteger(largePostMinBytes) || largePostMinBytes < 0) throw new Error("shardUrls.largePostMinBytes must be a non-negative safe integer");
95152
+ const normalized = {
95153
+ bootstrap: normalizeShardOrigins(options.bootstrap, "shardUrls.bootstrap"),
95154
+ catchup: normalizeShardOrigins(options.catchup, "shardUrls.catchup"),
95155
+ largePost: normalizeShardOrigins(options.largePost, "shardUrls.largePost"),
95156
+ largePostMinBytes
95157
+ };
95158
+ if (normalized.bootstrap == null && normalized.catchup == null && normalized.largePost == null) return;
95159
+ return normalized;
95160
+ }
95161
+ function requestBodyByteLength(body) {
95162
+ if (body == null) return 0;
95163
+ if (typeof body === "string") return bodySizeEncoder.encode(body).byteLength;
95164
+ if (body instanceof ArrayBuffer) return body.byteLength;
95165
+ if (ArrayBuffer.isView(body)) return body.byteLength;
95166
+ if (typeof Blob !== "undefined" && body instanceof Blob) return body.size;
95167
+ if (typeof URLSearchParams !== "undefined" && body instanceof URLSearchParams) return bodySizeEncoder.encode(body.toString()).byteLength;
95168
+ }
95169
+ function createRandomShardStart(originCount) {
95170
+ if (originCount <= 1) return 0;
95171
+ try {
95172
+ const crypto2 = globalThis.crypto;
95173
+ if (crypto2 != null) {
95174
+ const values = new Uint32Array(1);
95175
+ crypto2.getRandomValues(values);
95176
+ return (values[0] ?? 0) % originCount;
95177
+ }
95178
+ } catch {
95179
+ }
95180
+ return Math.floor(Math.random() * originCount);
95181
+ }
95182
+ function normalizedStreamPath(streamUrl) {
95183
+ return streamUrl.pathname.endsWith("/") ? streamUrl.pathname.slice(0, -1) : streamUrl.pathname;
95184
+ }
95128
95185
  var StreamsTransportClient = class {
95129
95186
  streamUrl;
95130
95187
  adapter;
@@ -95132,14 +95189,18 @@ stream:${scope2.streamId}`;
95132
95189
  fetchImpl;
95133
95190
  authProvider;
95134
95191
  reconnectConfig;
95192
+ shardUrls;
95193
+ shardCursorIndexes = {};
95135
95194
  authRefreshInFlight;
95136
95195
  constructor(options) {
95137
95196
  this.streamUrl = options.streamUrl;
95138
95197
  this.adapter = options.adapter;
95139
- this.client = new StreamsClient$1({
95198
+ this.fetchImpl = options.fetchImpl;
95199
+ this.shardUrls = normalizeShardUrlsOptions(options.shardUrls);
95200
+ this.client = new StreamsClient({
95140
95201
  url: options.streamUrl,
95141
95202
  auth: options.authProvider,
95142
- fetch: options.fetchImpl,
95203
+ fetch: this.fetchRouted.bind(this),
95143
95204
  retry: {
95144
95205
  maxAttempts: 0
95145
95206
  },
@@ -95148,10 +95209,44 @@ stream:${scope2.streamId}`;
95148
95209
  pollTimeoutMs: options.reconnectConfig.pollTimeoutMs
95149
95210
  }
95150
95211
  });
95151
- this.fetchImpl = options.fetchImpl;
95152
95212
  this.authProvider = options.authProvider;
95153
95213
  this.reconnectConfig = options.reconnectConfig;
95154
95214
  }
95215
+ fetchRouted(input2, init2) {
95216
+ return this.fetchImpl(this.routeRequestUrl(input2, init2), init2);
95217
+ }
95218
+ routeRequestUrl(input2, init2) {
95219
+ const shardUrls = this.shardUrls;
95220
+ if (shardUrls == null) return input2;
95221
+ const operation = this.classifyShardOperation(input2, init2, shardUrls);
95222
+ if (operation == null) return input2;
95223
+ const origins = operation === "bootstrap" ? shardUrls.bootstrap : operation === "catchup" ? shardUrls.catchup : shardUrls.largePost;
95224
+ if (origins == null || origins.length === 0) return input2;
95225
+ const target = new URL(input2);
95226
+ const shardOrigin = new URL(this.nextShardOrigin(operation, origins));
95227
+ target.protocol = shardOrigin.protocol;
95228
+ target.host = shardOrigin.host;
95229
+ target.username = "";
95230
+ target.password = "";
95231
+ return target.toString();
95232
+ }
95233
+ nextShardOrigin(operation, origins) {
95234
+ const currentIndex = this.shardCursorIndexes[operation] ?? createRandomShardStart(origins.length);
95235
+ this.shardCursorIndexes[operation] = (currentIndex + 1) % origins.length;
95236
+ return origins[currentIndex % origins.length];
95237
+ }
95238
+ classifyShardOperation(input2, init2, shardUrls) {
95239
+ const method = (init2?.method ?? "GET").toUpperCase();
95240
+ const requestUrl = new URL(input2);
95241
+ const streamUrl = new URL(this.streamUrl);
95242
+ const streamPath = normalizedStreamPath(streamUrl);
95243
+ if (method === "GET" && requestUrl.pathname === `${streamPath}/bootstrap`) return "bootstrap";
95244
+ if (method === "GET" && requestUrl.pathname === streamUrl.pathname && requestUrl.searchParams.has("offset") && requestUrl.searchParams.get("live") !== "sse") return "catchup";
95245
+ if (method !== "POST" || requestUrl.pathname !== streamUrl.pathname) return;
95246
+ const bodyLength = requestBodyByteLength(init2?.body);
95247
+ if (bodyLength == null || bodyLength === 0 || bodyLength < shardUrls.largePostMinBytes) return;
95248
+ return "large-post";
95249
+ }
95155
95250
  async createStreamRequest() {
95156
95251
  const adapterHeaders = this.adapter.getCreateStreamHeaders ? await this.adapter.getCreateStreamHeaders() : void 0;
95157
95252
  const result = await this.client.create({
@@ -95195,10 +95290,11 @@ stream:${scope2.streamId}`;
95195
95290
  async bootstrap() {
95196
95291
  const result = await this.client.bootstrap();
95197
95292
  if (!result.ok) throw this.toTransportFailure(result.result);
95293
+ const snapshot = result.result.snapshotOffset === "-1" ? new Uint8Array() : result.result.snapshot?.body ?? new Uint8Array();
95198
95294
  return {
95199
95295
  nextOffset: result.result.nextOffset,
95200
95296
  upToDate: result.result.upToDate,
95201
- snapshot: result.result.snapshot?.body ?? new Uint8Array(),
95297
+ snapshot,
95202
95298
  updates: result.result.updates.flatMap((part) => decodeMultipartPartItems(part.body)),
95203
95299
  streamCursor: result.result.cursor
95204
95300
  };
@@ -95289,32 +95385,32 @@ stream:${scope2.streamId}`;
95289
95385
  if (!response.ok) {
95290
95386
  if (response.status === 400) {
95291
95387
  const message = await response.text();
95292
- if (isSseUnsupportedErrorText$1(message)) return {
95388
+ if (isSseUnsupportedErrorText(message)) return {
95293
95389
  kind: "unsupported"
95294
95390
  };
95295
95391
  throw new HttpError(message.length > 0 ? `ephemeral live read failed: ${message}` : "ephemeral live read failed", response.status);
95296
95392
  }
95297
95393
  throw await this.responseToEphemeralFailure(response, "ephemeral live read");
95298
95394
  }
95299
- if (response.body == null) throw new ProtocolError$1("ephemeral sse response missing body");
95300
- if (!(response.headers.get("Content-Type") ?? "").toLowerCase().includes("text/event-stream")) throw new ProtocolError$1("ephemeral sse response must use text/event-stream content type");
95395
+ if (response.body == null) throw new ProtocolError("ephemeral sse response missing body");
95396
+ if (!(response.headers.get("Content-Type") ?? "").toLowerCase().includes("text/event-stream")) throw new ProtocolError("ephemeral sse response must use text/event-stream content type");
95301
95397
  const dataEncoding = response.headers.get("Stream-SSE-Data-Encoding") ?? void 0;
95302
95398
  const consume = async () => {
95303
95399
  let sawBootstrap = false;
95304
- for await (const event of readSseEvents$1(response.body)) {
95400
+ for await (const event of readSseEvents(response.body)) {
95305
95401
  if (!sawBootstrap) {
95306
- if (event.event !== "bootstrap") throw new ProtocolError$1(`ephemeral sse must start with bootstrap, got '${event.event}'`);
95307
- await onBootstrap(decodeSsePayload$1(event.data, dataEncoding));
95402
+ if (event.event !== "bootstrap") throw new ProtocolError(`ephemeral sse must start with bootstrap, got '${event.event}'`);
95403
+ await onBootstrap(decodeSsePayload(event.data, dataEncoding));
95308
95404
  sawBootstrap = true;
95309
95405
  continue;
95310
95406
  }
95311
95407
  if (event.event === "data") {
95312
- await onData(decodeSsePayload$1(event.data, dataEncoding));
95408
+ await onData(decodeSsePayload(event.data, dataEncoding));
95313
95409
  continue;
95314
95410
  }
95315
- throw new ProtocolError$1(`unexpected ephemeral sse event '${event.event}'`);
95411
+ throw new ProtocolError(`unexpected ephemeral sse event '${event.event}'`);
95316
95412
  }
95317
- if (!sawBootstrap) throw new ProtocolError$1("ephemeral sse ended before bootstrap");
95413
+ if (!sawBootstrap) throw new ProtocolError("ephemeral sse ended before bootstrap");
95318
95414
  return {
95319
95415
  kind: "ok"
95320
95416
  };
@@ -95363,9 +95459,9 @@ stream:${scope2.streamId}`;
95363
95459
  }
95364
95460
  async fetchWithTimeout(input2, init2, timeoutMs, phase) {
95365
95461
  const controller = new AbortController();
95366
- const signal = mergeAbortSignals$2(init2.signal, controller.signal);
95462
+ const signal = mergeAbortSignals(init2.signal, controller.signal);
95367
95463
  const timer2 = setTimeout(() => {
95368
- controller.abort(new TimeoutError$1(phase, timeoutMs));
95464
+ controller.abort(new TimeoutError(phase, timeoutMs));
95369
95465
  }, timeoutMs);
95370
95466
  try {
95371
95467
  return await this.fetchImpl(input2, {
@@ -95373,7 +95469,7 @@ stream:${scope2.streamId}`;
95373
95469
  signal
95374
95470
  });
95375
95471
  } catch (error2) {
95376
- if (controller.signal.aborted && controller.signal.reason instanceof TimeoutError$1) throw controller.signal.reason;
95472
+ if (controller.signal.aborted && controller.signal.reason instanceof TimeoutError) throw controller.signal.reason;
95377
95473
  throw error2;
95378
95474
  } finally {
95379
95475
  clearTimeout(timer2);
@@ -95428,11 +95524,11 @@ stream:${scope2.streamId}`;
95428
95524
  body: error2.bodyText
95429
95525
  });
95430
95526
  case "timeout":
95431
- return new TimeoutError$1(error2.phase, error2.phase === "poll" ? this.reconnectConfig.pollTimeoutMs : this.reconnectConfig.connectTimeoutMs);
95527
+ return new TimeoutError(error2.phase, error2.phase === "poll" ? this.reconnectConfig.pollTimeoutMs : this.reconnectConfig.connectTimeoutMs);
95432
95528
  case "network_error":
95433
95529
  return error2.cause instanceof TypeError ? error2.cause : new TypeError(error2.message);
95434
95530
  case "protocol_error":
95435
- return new ProtocolError$1(error2.message, error2.status);
95531
+ return new ProtocolError(error2.message, error2.status);
95436
95532
  case "unknown":
95437
95533
  if (typeof error2.status === "number") return new HttpError(error2.message, error2.status, {
95438
95534
  requestId: extractRequestIdFromHeaders(error2.headers),
@@ -95494,7 +95590,7 @@ stream:${scope2.streamId}`;
95494
95590
  if (result.result.code === "not_found") return {
95495
95591
  kind: "not-found"
95496
95592
  };
95497
- if (result.result.code === "bad_request" && isSseUnsupportedErrorText$1(result.result.message)) return {
95593
+ if (result.result.code === "bad_request" && isSseUnsupportedErrorText(result.result.message)) return {
95498
95594
  kind: "unsupported"
95499
95595
  };
95500
95596
  throw this.toTransportFailure(result.result);
@@ -95521,7 +95617,7 @@ stream:${scope2.streamId}`;
95521
95617
  continue;
95522
95618
  }
95523
95619
  if (event.event !== "control") continue;
95524
- const control = parseSseControlData$1(event.data);
95620
+ const control = parseSseControlData(event.data);
95525
95621
  const updates = [];
95526
95622
  for (const eventData of pendingDataEvents) updates.push(...decodeSseItemPayloads(eventData, session.dataEncoding));
95527
95623
  pendingDataEvents = [];
@@ -95636,7 +95732,7 @@ stream:${scope2.streamId}`;
95636
95732
  this.client = new StreamsTransportClient({
95637
95733
  streamUrl: options.streamUrl,
95638
95734
  adapter: createNoopAdapter(),
95639
- authProvider: normalizeAuthProvider$1(options.auth),
95735
+ authProvider: normalizeAuthProvider(options.auth),
95640
95736
  fetchImpl: options.fetch ?? globalThis.fetch.bind(globalThis),
95641
95737
  reconnectConfig: this.reconnectConfig
95642
95738
  });
@@ -95814,7 +95910,7 @@ stream:${scope2.streamId}`;
95814
95910
  if (result.kind === "ok") {
95815
95911
  state2.retryAttempt = 0;
95816
95912
  this.setReadStatus(state2, "reconnecting");
95817
- await sleep$2(0);
95913
+ await sleep$1(0);
95818
95914
  continue;
95819
95915
  }
95820
95916
  if (result.kind === "unsupported") throw new Error("ephemeral stream requires SSE support");
@@ -95846,9 +95942,9 @@ stream:${scope2.streamId}`;
95846
95942
  this.rejectFirstOpen(state2, toError$1(error2));
95847
95943
  return;
95848
95944
  }
95849
- const delay2 = computeRetryDelay$1(state2.retryAttempt, this.reconnectConfig);
95945
+ const delay2 = computeRetryDelay(state2.retryAttempt, this.reconnectConfig);
95850
95946
  state2.retryAttempt += 1;
95851
- await sleep$2(delay2, state2.retrySleepController.signal);
95947
+ await sleep$1(delay2, state2.retrySleepController.signal);
95852
95948
  }
95853
95949
  }
95854
95950
  }
@@ -95884,9 +95980,9 @@ stream:${scope2.streamId}`;
95884
95980
  return;
95885
95981
  }
95886
95982
  this.setWriteStatus(state2, "reconnecting");
95887
- const delay2 = computeRetryDelay$1(attempt, this.reconnectConfig);
95983
+ const delay2 = computeRetryDelay(attempt, this.reconnectConfig);
95888
95984
  attempt += 1;
95889
- await sleep$2(delay2, state2.retrySleepController.signal);
95985
+ await sleep$1(delay2, state2.retrySleepController.signal);
95890
95986
  }
95891
95987
  }
95892
95988
  } finally {
@@ -96273,7 +96369,7 @@ stream:${scope2.streamId}`;
96273
96369
  const MIN_RECONNECT_DELAY_MS = 1e3;
96274
96370
  const MIN_SUCCESSFUL_SSE_DURATION_MS = 5e3;
96275
96371
  function reconnectDelayWithFloor(attempt, config2) {
96276
- return Math.max(computeRetryDelay$1(attempt, config2), MIN_RECONNECT_DELAY_MS);
96372
+ return Math.max(computeRetryDelay(attempt, config2), MIN_RECONNECT_DELAY_MS);
96277
96373
  }
96278
96374
  function fastSseCloseDelay(startedAtMs) {
96279
96375
  const elapsedMs = Math.max(0, Date.now() - startedAtMs);
@@ -96315,7 +96411,7 @@ stream:${scope2.streamId}`;
96315
96411
  constructor(options) {
96316
96412
  this.streamUrl = options.streamUrl;
96317
96413
  this.adapter = options.adapter;
96318
- const authProvider = normalizeAuthProvider$1(options.auth);
96414
+ const authProvider = normalizeAuthProvider(options.auth);
96319
96415
  this.createStreamIfMissing = options.createStreamIfMissing ?? false;
96320
96416
  const fetchImpl = options.fetch ?? globalThis.fetch.bind(globalThis);
96321
96417
  this.remoteCursorStore = options.remoteCursorStore ?? new InMemoryRemoteCursorStore();
@@ -96342,7 +96438,8 @@ stream:${scope2.streamId}`;
96342
96438
  adapter: this.adapter,
96343
96439
  authProvider,
96344
96440
  fetchImpl,
96345
- reconnectConfig: this.reconnectConfig
96441
+ reconnectConfig: this.reconnectConfig,
96442
+ shardUrls: options.shardUrls
96346
96443
  });
96347
96444
  this.cursorManager = this.createCursorManager(this.adapter, (cursor, source) => this.saveRemoteCursor(cursor, source));
96348
96445
  this.volatileCursorManager = this.createCursorManager(this.adapter, async (cursor) => cursor);
@@ -96513,6 +96610,29 @@ stream:${scope2.streamId}`;
96513
96610
  };
96514
96611
  }
96515
96612
  }
96613
+ async catchup(params = {}) {
96614
+ try {
96615
+ this.disableWriteOnlyMode("appendWriteOnly cannot be used after catchup() on the same transport");
96616
+ const state2 = this.joinState;
96617
+ if (state2 != null && !state2.closed) return {
96618
+ ok: true,
96619
+ value: {
96620
+ cursor: await this.catchupJoinState(state2, params)
96621
+ }
96622
+ };
96623
+ return {
96624
+ ok: true,
96625
+ value: {
96626
+ cursor: (await this.resolvePullOnlyRemoteState()).cursor
96627
+ }
96628
+ };
96629
+ } catch (error2) {
96630
+ return {
96631
+ ok: false,
96632
+ error: toTransportError(error2)
96633
+ };
96634
+ }
96635
+ }
96516
96636
  async appendWriteOnly() {
96517
96637
  return await this.enqueueExclusive(async () => {
96518
96638
  try {
@@ -96760,6 +96880,40 @@ stream:${scope2.streamId}`;
96760
96880
  return await this.bootstrapState(this.createInitialCursor());
96761
96881
  }
96762
96882
  }
96883
+ async resolvePullOnlyRemoteState() {
96884
+ const loaded = await this.remoteCursorStore.load(this.streamUrl);
96885
+ const cursor = loaded ?? this.createInitialCursor();
96886
+ try {
96887
+ if (loaded == null) return await this.bootstrapState(cursor);
96888
+ return await this.catchupFromCursor(cursor);
96889
+ } catch (error2) {
96890
+ if (!isStreamNotFoundError(error2) || !this.createStreamIfMissing) throw error2;
96891
+ await this.ensureStreamExists();
96892
+ return await this.bootstrapState(this.createInitialCursor());
96893
+ }
96894
+ }
96895
+ async catchupJoinState(state2, params) {
96896
+ if (state2.readSubStatus === "connecting") {
96897
+ await state2.started;
96898
+ return state2.cursor;
96899
+ }
96900
+ if (state2.readSubStatus === "ok" && params.force !== true) return state2.cursor;
96901
+ const cursor = await this.enqueueExclusive(async () => {
96902
+ if (state2.closed) throw new Error("subscription closed");
96903
+ const caughtUp = await this.catchupFromCursor(state2.cursor, void 0, state2.streamCursor, (previousVersion, nextVersion) => {
96904
+ this.snapshotManager.observeRemoteVersion(state2, previousVersion, nextVersion);
96905
+ });
96906
+ state2.cursor = caughtUp.cursor;
96907
+ state2.streamCursor = caughtUp.streamCursor;
96908
+ return state2.cursor;
96909
+ });
96910
+ if (state2.closed) return cursor;
96911
+ state2.retryAttempt = 0;
96912
+ state2.lastError = void 0;
96913
+ if (state2.readSubStatus !== "ok" || state2.writeSubStatus === "error") this.rejoin();
96914
+ else if (state2.pendingLocal.length > 0) this.flushPendingLocal(state2);
96915
+ return cursor;
96916
+ }
96763
96917
  async bootstrapState(cursor, options = {}) {
96764
96918
  const cursorManager = options.cursorManager ?? this.cursorManager;
96765
96919
  const result = await this.client.bootstrap();
@@ -96779,7 +96933,7 @@ stream:${scope2.streamId}`;
96779
96933
  streamCursor: bootstrapCursor
96780
96934
  };
96781
96935
  }
96782
- async catchup(cursor, live, streamCursor, onRemoteVersionApplied) {
96936
+ async catchupFromCursor(cursor, live, streamCursor, onRemoteVersionApplied) {
96783
96937
  const result = await this.catchupOrGone(cursor, {
96784
96938
  live,
96785
96939
  streamCursor,
@@ -97126,7 +97280,7 @@ stream:${scope2.streamId}`;
97126
97280
  state2.retryAttempt = 0;
97127
97281
  this.setReadSubStatus(state2, "ok");
97128
97282
  if (state2.pendingLocal.length > 0) this.flushPendingLocal(state2);
97129
- await sleep$2(0);
97283
+ await sleep$1(0);
97130
97284
  continue;
97131
97285
  }
97132
97286
  const sseRequestOffset = state2.cursor.nextOffset;
@@ -97180,12 +97334,12 @@ stream:${scope2.streamId}`;
97180
97334
  if (sseResult.kind === "ok") {
97181
97335
  state2.retryAttempt = 0;
97182
97336
  state2.streamCursor = sseResult.latestCursor;
97183
- await sleep$2(fastSseCloseDelay(sseStartedAtMs), state2.retrySleepController.signal);
97337
+ await sleep$1(fastSseCloseDelay(sseStartedAtMs), state2.retrySleepController.signal);
97184
97338
  continue;
97185
97339
  }
97186
97340
  if (sseResult.kind === "unsupported") {
97187
97341
  state2.liveMode = "long-poll";
97188
- await sleep$2(0);
97342
+ await sleep$1(0);
97189
97343
  continue;
97190
97344
  }
97191
97345
  if (sseResult.kind === "not-found") {
@@ -97237,7 +97391,7 @@ stream:${scope2.streamId}`;
97237
97391
  return;
97238
97392
  }
97239
97393
  state2.retryAttempt += 1;
97240
- await sleep$2(reconnectDelayWithFloor(state2.retryAttempt - 1, this.reconnectConfig), state2.retrySleepController.signal);
97394
+ await sleep$1(reconnectDelayWithFloor(state2.retryAttempt - 1, this.reconnectConfig), state2.retrySleepController.signal);
97241
97395
  continue;
97242
97396
  }
97243
97397
  const abortReason = capturedController.signal.reason;
@@ -97284,9 +97438,9 @@ stream:${scope2.streamId}`;
97284
97438
  this.setReadSubStatus(state2, "disconnected");
97285
97439
  return;
97286
97440
  }
97287
- const delay2 = computeRetryDelay$1(state2.retryAttempt, this.reconnectConfig, error2 instanceof HttpError ? error2.retryAfterMs : void 0);
97441
+ const delay2 = computeRetryDelay(state2.retryAttempt, this.reconnectConfig, error2 instanceof HttpError ? error2.retryAfterMs : void 0);
97288
97442
  state2.retryAttempt += 1;
97289
- await sleep$2(delay2, state2.retrySleepController.signal);
97443
+ await sleep$1(delay2, state2.retrySleepController.signal);
97290
97444
  }
97291
97445
  }
97292
97446
  }
@@ -97366,9 +97520,9 @@ stream:${scope2.streamId}`;
97366
97520
  return;
97367
97521
  }
97368
97522
  this.setWriteSubStatus(state2, "reconnecting");
97369
- const delay2 = computeRetryDelay$1(attempts, this.reconnectConfig, error2 instanceof HttpError ? error2.retryAfterMs : void 0);
97523
+ const delay2 = computeRetryDelay(attempts, this.reconnectConfig, error2 instanceof HttpError ? error2.retryAfterMs : void 0);
97370
97524
  attempts += 1;
97371
- await sleep$2(delay2, state2.retrySleepController.signal);
97525
+ await sleep$1(delay2, state2.retrySleepController.signal);
97372
97526
  }
97373
97527
  }
97374
97528
  } finally {
@@ -118352,1540 +118506,6 @@ ${this.stack.split("\n").slice(1).join("\n")}` : this.toString();
118352
118506
  });
118353
118507
  }
118354
118508
  }
118355
- var ProtocolError = class extends Error {
118356
- status;
118357
- detail;
118358
- constructor(message, status, detail) {
118359
- super(message);
118360
- this.status = status;
118361
- this.detail = detail;
118362
- }
118363
- };
118364
- var TimeoutError = class extends Error {
118365
- phase;
118366
- timeoutMs;
118367
- constructor(phase, timeoutMs) {
118368
- super(`TIMEOUT: ${phase} request exceeded ${timeoutMs}ms`);
118369
- this.phase = phase;
118370
- this.timeoutMs = timeoutMs;
118371
- }
118372
- };
118373
- function isAbortError(error2) {
118374
- return error2 instanceof DOMException ? error2.name === "AbortError" : typeof error2 === "object" && error2 != null && "name" in error2 && error2.name === "AbortError";
118375
- }
118376
- async function responseToStreamError(response, context2) {
118377
- const bodyText = await safeReadBodyText(response);
118378
- const message = bodyText.length > 0 ? `${context2} failed with status ${response.status}: ${bodyText}` : `${context2} failed with status ${response.status}`;
118379
- switch (response.status) {
118380
- case 400:
118381
- return {
118382
- code: "bad_request",
118383
- status: 400,
118384
- message
118385
- };
118386
- case 401:
118387
- return {
118388
- code: "unauthorized",
118389
- status: 401,
118390
- message
118391
- };
118392
- case 403:
118393
- return {
118394
- code: "forbidden",
118395
- status: 403,
118396
- message,
118397
- detail: producerEpochDetail(response)
118398
- };
118399
- case 404:
118400
- return {
118401
- code: "not_found",
118402
- status: 404,
118403
- message
118404
- };
118405
- case 409:
118406
- return {
118407
- code: "conflict",
118408
- status: 409,
118409
- message,
118410
- detail: conflictDetail(response, bodyText)
118411
- };
118412
- case 410:
118413
- return {
118414
- code: "gone",
118415
- status: 410,
118416
- message
118417
- };
118418
- case 429:
118419
- return {
118420
- code: "rate_limited",
118421
- status: 429,
118422
- message
118423
- };
118424
- default:
118425
- return {
118426
- code: "unknown",
118427
- message,
118428
- status: response.status,
118429
- statusText: response.statusText,
118430
- headers: headersToObject$1(response.headers),
118431
- bodyText: bodyText.length > 0 ? bodyText : void 0,
118432
- cause: {
118433
- type: "http_response",
118434
- status: response.status,
118435
- statusText: response.statusText
118436
- }
118437
- };
118438
- }
118439
- }
118440
- function thrownToStreamError(error2) {
118441
- if (error2 instanceof TimeoutError) return {
118442
- code: "timeout",
118443
- phase: error2.phase,
118444
- message: error2.message
118445
- };
118446
- if (error2 instanceof ProtocolError) return {
118447
- code: "protocol_error",
118448
- message: error2.message,
118449
- status: error2.status,
118450
- detail: error2.detail
118451
- };
118452
- if (error2 instanceof TypeError) return {
118453
- code: "network_error",
118454
- message: error2.message,
118455
- cause: error2
118456
- };
118457
- if (error2 instanceof Error) return {
118458
- code: "unknown",
118459
- message: error2.message,
118460
- cause: error2
118461
- };
118462
- return {
118463
- code: "unknown",
118464
- message: String(error2),
118465
- cause: error2
118466
- };
118467
- }
118468
- function isRetryableLiveError(error2) {
118469
- return isRetryableStreamError(error2);
118470
- }
118471
- function producerEpochDetail(response) {
118472
- const value = response.headers.get("Producer-Epoch");
118473
- if (value == null) return;
118474
- const parsed = Number.parseInt(value, 10);
118475
- if (!Number.isFinite(parsed) || parsed < 0) return {
118476
- kind: "other"
118477
- };
118478
- return {
118479
- kind: "stale_producer_epoch",
118480
- serverEpoch: parsed
118481
- };
118482
- }
118483
- function conflictDetail(response, bodyText) {
118484
- if (isTrueHeader(response.headers.get("Stream-Closed"))) return {
118485
- kind: "stream_closed",
118486
- nextOffset: response.headers.get("Stream-Next-Offset") ?? void 0
118487
- };
118488
- const expectedSeq = parseOptionalInteger$1(response.headers.get("Producer-Expected-Seq"));
118489
- if (expectedSeq != null) return {
118490
- kind: "producer_seq_gap",
118491
- expectedSeq,
118492
- receivedSeq: parseOptionalInteger$1(response.headers.get("Producer-Received-Seq")) ?? void 0
118493
- };
118494
- const normalized = bodyText.toLowerCase();
118495
- if (normalized.includes("content type")) return {
118496
- kind: "content_type_mismatch"
118497
- };
118498
- if (normalized.includes("stream-seq") || normalized.includes("sequence")) return {
118499
- kind: "stream_seq_conflict"
118500
- };
118501
- return {
118502
- kind: "other"
118503
- };
118504
- }
118505
- function parseOptionalInteger$1(value) {
118506
- if (value == null) return null;
118507
- const parsed = Number.parseInt(value, 10);
118508
- if (!Number.isFinite(parsed) || parsed < 0) return null;
118509
- return parsed;
118510
- }
118511
- function isTrueHeader(value) {
118512
- return value?.trim().toLowerCase() === "true";
118513
- }
118514
- function headersToObject$1(headers) {
118515
- const result = {};
118516
- headers.forEach((value, name2) => {
118517
- result[name2] = value;
118518
- });
118519
- return result;
118520
- }
118521
- async function safeReadBodyText(response) {
118522
- try {
118523
- return await response.text();
118524
- } catch {
118525
- return "";
118526
- }
118527
- }
118528
- function isRetryableStreamError(error2) {
118529
- return error2.code === "network_error" || error2.code === "timeout";
118530
- }
118531
- const DEFAULT_TIMEOUT_CONFIG = {
118532
- connectTimeoutMs: 1e4,
118533
- pollTimeoutMs: 3e4
118534
- };
118535
- function normalizeTimeoutConfig(value) {
118536
- const connectTimeoutMs = value?.connectTimeoutMs ?? DEFAULT_TIMEOUT_CONFIG.connectTimeoutMs;
118537
- const pollTimeoutMs = value?.pollTimeoutMs ?? DEFAULT_TIMEOUT_CONFIG.pollTimeoutMs;
118538
- if (!Number.isFinite(connectTimeoutMs) || connectTimeoutMs < 0) throw new Error("timeout.connectTimeoutMs must be a non-negative finite number");
118539
- if (!Number.isFinite(pollTimeoutMs) || pollTimeoutMs < 0) throw new Error("timeout.pollTimeoutMs must be a non-negative finite number");
118540
- return {
118541
- connectTimeoutMs: Math.floor(connectTimeoutMs),
118542
- pollTimeoutMs: Math.floor(pollTimeoutMs)
118543
- };
118544
- }
118545
- function mergeAbortSignals$1(...signals2) {
118546
- const active2 = signals2.filter((signal) => signal != null);
118547
- if (active2.length === 0) return;
118548
- if (active2.length === 1) return active2[0];
118549
- if (typeof AbortSignal.any === "function") return AbortSignal.any(active2);
118550
- const controller = new AbortController();
118551
- for (const signal of active2) {
118552
- if (signal.aborted) {
118553
- controller.abort(signal.reason);
118554
- break;
118555
- }
118556
- signal.addEventListener("abort", () => {
118557
- controller.abort(signal.reason);
118558
- }, {
118559
- once: true
118560
- });
118561
- }
118562
- return controller.signal;
118563
- }
118564
- async function fetchWithTimeout(fetchImpl, input2, init2, timeoutMs, phase) {
118565
- if (!(timeoutMs > 0)) return await fetchImpl(input2, init2);
118566
- const controller = new AbortController();
118567
- const signal = mergeAbortSignals$1(init2.signal, controller.signal);
118568
- const timer2 = setTimeout(() => {
118569
- controller.abort(new TimeoutError(phase, timeoutMs));
118570
- }, timeoutMs);
118571
- try {
118572
- return await fetchImpl(input2, {
118573
- ...init2,
118574
- signal
118575
- });
118576
- } catch (error2) {
118577
- if (controller.signal.aborted && controller.signal.reason instanceof TimeoutError) throw controller.signal.reason;
118578
- throw error2;
118579
- } finally {
118580
- clearTimeout(timer2);
118581
- }
118582
- }
118583
- var AuthorizedHttpClient = class {
118584
- fetchImpl;
118585
- authProvider;
118586
- authRefreshInFlight;
118587
- constructor(options) {
118588
- this.fetchImpl = options.fetchImpl;
118589
- this.authProvider = normalizeAuthProvider(options.auth);
118590
- }
118591
- async fetchAuthorized(input2, init2, timeoutMs, phase, options) {
118592
- const firstToken = await this.resolveToken({
118593
- reason: "request"
118594
- });
118595
- const firstResponse = await fetchWithTimeout(this.fetchImpl, input2, {
118596
- ...init2,
118597
- headers: this.attachAuthorization(init2.headers, firstToken)
118598
- }, timeoutMs, phase);
118599
- const shouldRetryAuthFailure = options?.shouldRetryAuthFailure ?? ((response) => response.status === 401 || response.status === 403);
118600
- if (this.authProvider == null || !shouldRetryAuthFailure(firstResponse)) return firstResponse;
118601
- await firstResponse.body?.cancel().catch(() => {
118602
- });
118603
- const refreshedToken = await this.refreshTokenAfterFailure(firstResponse.status, firstToken);
118604
- return await fetchWithTimeout(this.fetchImpl, input2, {
118605
- ...init2,
118606
- headers: this.attachAuthorization(init2.headers, refreshedToken)
118607
- }, timeoutMs, phase);
118608
- }
118609
- async resolveToken(context2) {
118610
- if (this.authProvider == null) return;
118611
- return await this.authProvider(context2);
118612
- }
118613
- async refreshTokenAfterFailure(status, previousToken) {
118614
- if (this.authProvider == null) return;
118615
- if (this.authRefreshInFlight == null) this.authRefreshInFlight = this.resolveToken({
118616
- reason: "unauthorized",
118617
- status,
118618
- previousToken
118619
- }).finally(() => {
118620
- this.authRefreshInFlight = void 0;
118621
- });
118622
- return await this.authRefreshInFlight;
118623
- }
118624
- attachAuthorization(base, token2) {
118625
- const headers = new Headers(base);
118626
- if (token2 == null || token2.length === 0) {
118627
- headers.delete("Authorization");
118628
- return headers;
118629
- }
118630
- headers.set("Authorization", `Bearer ${token2}`);
118631
- return headers;
118632
- }
118633
- };
118634
- function normalizeAuthProvider(auth) {
118635
- if (auth == null) return;
118636
- if (typeof auth === "string") {
118637
- const token2 = auth.trim();
118638
- return async () => token2.length === 0 ? void 0 : token2;
118639
- }
118640
- return async (context2) => {
118641
- const token2 = (await auth(context2))?.trim() ?? "";
118642
- return token2.length === 0 ? void 0 : token2;
118643
- };
118644
- }
118645
- function decodeMultipartMixed(boundary, data) {
118646
- const delimiter2 = new TextEncoder().encode(`--${boundary}`);
118647
- const closeDelimiter = new TextEncoder().encode(`--${boundary}--`);
118648
- const crlfCrlf = new TextEncoder().encode("\r\n\r\n");
118649
- const parts2 = [];
118650
- let pos = 0;
118651
- const firstDelimPos = indexOf(data, delimiter2, pos);
118652
- if (firstDelimPos < 0) return parts2;
118653
- pos = firstDelimPos + delimiter2.byteLength;
118654
- if (pos < data.byteLength && data[pos] === 13) pos += 1;
118655
- if (pos < data.byteLength && data[pos] === 10) pos += 1;
118656
- while (pos < data.byteLength) {
118657
- if (startsWith(data.subarray(pos), closeDelimiter.subarray(delimiter2.byteLength))) break;
118658
- const headerEnd = indexOf(data, crlfCrlf, pos);
118659
- if (headerEnd < 0) break;
118660
- const headerBytes = data.subarray(pos, headerEnd);
118661
- const headerText = new TextDecoder().decode(headerBytes);
118662
- let contentType = "application/octet-stream";
118663
- for (const line3 of headerText.split("\r\n")) {
118664
- const colon = line3.indexOf(":");
118665
- if (colon <= 0) continue;
118666
- if (line3.slice(0, colon).trim().toLowerCase() !== "content-type") continue;
118667
- contentType = line3.slice(colon + 1).trim();
118668
- }
118669
- const bodyStart = headerEnd + crlfCrlf.byteLength;
118670
- const nextDelimiter = indexOf(data, delimiter2, bodyStart);
118671
- if (nextDelimiter < 0) {
118672
- parts2.push({
118673
- contentType,
118674
- body: data.subarray(bodyStart)
118675
- });
118676
- break;
118677
- }
118678
- let bodyEnd = nextDelimiter;
118679
- if (bodyEnd >= 2 && data[bodyEnd - 2] === 13 && data[bodyEnd - 1] === 10) bodyEnd -= 2;
118680
- parts2.push({
118681
- contentType,
118682
- body: data.subarray(bodyStart, bodyEnd)
118683
- });
118684
- pos = nextDelimiter + delimiter2.byteLength;
118685
- if (pos + 1 < data.byteLength && data[pos] === 45 && data[pos + 1] === 45) break;
118686
- if (pos < data.byteLength && data[pos] === 13) pos += 1;
118687
- if (pos < data.byteLength && data[pos] === 10) pos += 1;
118688
- }
118689
- return parts2;
118690
- }
118691
- function extractBoundary(contentType) {
118692
- return /boundary=("?)([^";,\s]+)\1/i.exec(contentType)?.[2] ?? null;
118693
- }
118694
- function indexOf(haystack, needle, from2) {
118695
- outer: for (let i2 = from2; i2 <= haystack.byteLength - needle.byteLength; i2 += 1) {
118696
- for (let j = 0; j < needle.byteLength; j += 1) if (haystack[i2 + j] !== needle[j]) continue outer;
118697
- return i2;
118698
- }
118699
- return -1;
118700
- }
118701
- function startsWith(data, prefix) {
118702
- if (data.byteLength < prefix.byteLength) return false;
118703
- for (let i2 = 0; i2 < prefix.byteLength; i2 += 1) if (data[i2] !== prefix[i2]) return false;
118704
- return true;
118705
- }
118706
- const DEFAULT_RETRY_CONFIG = {
118707
- delays: [
118708
- 0,
118709
- 500,
118710
- 1e3,
118711
- 2e3,
118712
- 4e3,
118713
- 8e3,
118714
- 15e3
118715
- ],
118716
- jitterFraction: 0.2,
118717
- maxAttempts: 5
118718
- };
118719
- function normalizeRetryConfig(value) {
118720
- const delays = value?.delays ?? DEFAULT_RETRY_CONFIG.delays;
118721
- if (delays.length === 0) throw new Error("retry.delays must contain at least one entry");
118722
- const normalizedDelays = delays.map((delay2) => {
118723
- if (!Number.isFinite(delay2) || delay2 < 0) throw new Error("retry.delays must contain non-negative finite numbers");
118724
- return Math.floor(delay2);
118725
- });
118726
- const jitterFraction = value?.jitterFraction ?? DEFAULT_RETRY_CONFIG.jitterFraction;
118727
- if (!Number.isFinite(jitterFraction) || jitterFraction < 0) throw new Error("retry.jitterFraction must be a non-negative finite number");
118728
- const maxAttempts = value?.maxAttempts ?? DEFAULT_RETRY_CONFIG.maxAttempts;
118729
- if (!Number.isInteger(maxAttempts) || maxAttempts < 0) throw new Error("retry.maxAttempts must be a non-negative integer");
118730
- return {
118731
- delays: normalizedDelays,
118732
- jitterFraction,
118733
- maxAttempts
118734
- };
118735
- }
118736
- function applyJitter(baseMs, fraction) {
118737
- if (baseMs === 0) return 0;
118738
- const jitter = baseMs * fraction * (2 * Math.random() - 1);
118739
- return Math.max(0, Math.round(baseMs + jitter));
118740
- }
118741
- function computeRetryDelay(attempt, config2 = DEFAULT_RETRY_CONFIG) {
118742
- const index2 = Math.min(attempt, config2.delays.length - 1);
118743
- return applyJitter(config2.delays[index2] ?? 0, config2.jitterFraction);
118744
- }
118745
- async function sleep$1(delayMs, signal) {
118746
- if (delayMs <= 0) {
118747
- if (signal?.aborted === true) throw signal.reason;
118748
- return;
118749
- }
118750
- await new Promise((resolve2, reject) => {
118751
- const timer2 = setTimeout(() => {
118752
- cleanup();
118753
- resolve2();
118754
- }, delayMs);
118755
- const onAbort = () => {
118756
- clearTimeout(timer2);
118757
- cleanup();
118758
- reject(signal?.reason);
118759
- };
118760
- const cleanup = () => {
118761
- signal?.removeEventListener("abort", onAbort);
118762
- };
118763
- if (signal != null) {
118764
- if (signal.aborted) {
118765
- onAbort();
118766
- return;
118767
- }
118768
- signal.addEventListener("abort", onAbort, {
118769
- once: true
118770
- });
118771
- }
118772
- });
118773
- }
118774
- function getRequiredHeader(headers, name2, context2) {
118775
- const value = headers.get(name2);
118776
- if (value != null && value.length > 0) return value;
118777
- throw new ProtocolError(`${context2} response missing ${name2}. If this is cross-origin, expose it via Access-Control-Expose-Headers (${name2.toLowerCase()}). Visible headers: ${visibleHeaderNames(headers)}`);
118778
- }
118779
- function hasTrueHeader(headers, name2) {
118780
- return headers.get(name2)?.trim().toLowerCase() === "true";
118781
- }
118782
- function parseOptionalInteger(value) {
118783
- if (value == null) return null;
118784
- const parsed = Number.parseInt(value, 10);
118785
- if (!Number.isFinite(parsed) || parsed < 0) return null;
118786
- return parsed;
118787
- }
118788
- function visibleHeaderNames(headers) {
118789
- const names2 = [];
118790
- headers.forEach((_value, name2) => {
118791
- names2.push(name2);
118792
- });
118793
- if (names2.length === 0) return "(none)";
118794
- names2.sort();
118795
- return names2.join(", ");
118796
- }
118797
- const encoder = new TextEncoder();
118798
- const decoder = new TextDecoder();
118799
- function createStreamPart(contentType, body) {
118800
- return {
118801
- contentType,
118802
- body,
118803
- text() {
118804
- return decoder.decode(body);
118805
- },
118806
- json() {
118807
- return JSON.parse(decoder.decode(body));
118808
- }
118809
- };
118810
- }
118811
- function normalizeStreamPartLike(input2) {
118812
- return {
118813
- contentType: normalizeContentType(input2.contentType),
118814
- body: normalizeStreamBody(input2.body)
118815
- };
118816
- }
118817
- function normalizeContentType(contentType) {
118818
- const normalized = contentType.trim();
118819
- if (normalized.length === 0) throw new Error("contentType must be a non-empty string");
118820
- return normalized;
118821
- }
118822
- function normalizeOptionalContentType(contentType) {
118823
- if (contentType == null) return;
118824
- return normalizeContentType(contentType);
118825
- }
118826
- function normalizeStreamBody(body) {
118827
- if (typeof body === "string") return encoder.encode(body);
118828
- if (body instanceof Uint8Array) return body.slice();
118829
- if (body instanceof ArrayBuffer) return new Uint8Array(body.slice(0));
118830
- if (ArrayBuffer.isView(body)) return new Uint8Array(body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength));
118831
- throw new Error("unsupported stream body type");
118832
- }
118833
- function toRequestBody(bytes) {
118834
- return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
118835
- }
118836
- function isSseUnsupportedErrorText(message) {
118837
- const normalized = message.trim().toLowerCase();
118838
- if (normalized.length === 0) return false;
118839
- const mentionsSse = normalized.includes("sse") || normalized.includes("text/event-stream");
118840
- const mentionsCompatibility = normalized.includes("unsupported") || normalized.includes("not support") || normalized.includes("incompatible") || normalized.includes("content type");
118841
- return mentionsSse && mentionsCompatibility;
118842
- }
118843
- function parseSseControlData(data) {
118844
- let parsed;
118845
- try {
118846
- parsed = JSON.parse(data);
118847
- } catch {
118848
- throw new ProtocolError("invalid sse control event JSON");
118849
- }
118850
- if (typeof parsed !== "object" || parsed == null || typeof parsed.streamNextOffset !== "string") throw new ProtocolError("sse control event missing streamNextOffset");
118851
- const streamClosed = parsed.streamClosed === true;
118852
- const streamCursor = typeof parsed.streamCursor === "string" ? parsed.streamCursor : void 0;
118853
- return {
118854
- nextOffset: parsed.streamNextOffset,
118855
- upToDate: parsed.upToDate === true || streamClosed,
118856
- streamClosed,
118857
- streamCursor
118858
- };
118859
- }
118860
- function decodeSsePayload(data, dataEncoding) {
118861
- const normalizedEncoding = dataEncoding?.trim().toLowerCase();
118862
- if (normalizedEncoding == null || normalizedEncoding.length === 0) return new TextEncoder().encode(data);
118863
- if (normalizedEncoding !== "base64") throw new ProtocolError(`unsupported stream-sse-data-encoding '${dataEncoding}'`);
118864
- return decodeBase64Bytes(data.replace(/[\r\n]/g, ""));
118865
- }
118866
- async function* readSseEvents(stream2, options = {}) {
118867
- const reader2 = stream2.getReader();
118868
- const decoder2 = new TextDecoder();
118869
- let pendingText = "";
118870
- let currentEvent = "";
118871
- let dataLines = [];
118872
- let abortHandler;
118873
- const cancelReader = async () => {
118874
- await reader2.cancel(options.signal?.reason).catch(() => {
118875
- });
118876
- };
118877
- if (options.signal?.aborted) {
118878
- await cancelReader();
118879
- return;
118880
- }
118881
- if (options.signal != null) {
118882
- abortHandler = () => {
118883
- cancelReader();
118884
- };
118885
- options.signal.addEventListener("abort", abortHandler, {
118886
- once: true
118887
- });
118888
- }
118889
- const notifyActivity = () => {
118890
- try {
118891
- options.onActivity?.();
118892
- } catch {
118893
- }
118894
- };
118895
- const flushEvent = async function* () {
118896
- if (dataLines.length === 0) {
118897
- currentEvent = "";
118898
- return;
118899
- }
118900
- const eventType = currentEvent.length === 0 ? "message" : currentEvent;
118901
- const data = dataLines.join("\n");
118902
- currentEvent = "";
118903
- dataLines = [];
118904
- yield {
118905
- event: eventType,
118906
- data
118907
- };
118908
- };
118909
- try {
118910
- while (true) {
118911
- const { done: done2, value } = await reader2.read();
118912
- if (value != null) {
118913
- if (value.byteLength > 0) notifyActivity();
118914
- pendingText += decoder2.decode(value, {
118915
- stream: true
118916
- });
118917
- while (true) {
118918
- const newline = pendingText.indexOf("\n");
118919
- if (newline < 0) break;
118920
- const rawLine = pendingText.slice(0, newline);
118921
- pendingText = pendingText.slice(newline + 1);
118922
- const line3 = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
118923
- if (line3.length === 0) {
118924
- yield* flushEvent();
118925
- continue;
118926
- }
118927
- if (line3.startsWith(":")) continue;
118928
- if (line3.startsWith("event:")) {
118929
- currentEvent = line3.slice(6).trim();
118930
- continue;
118931
- }
118932
- if (line3.startsWith("data:")) dataLines.push(line3.slice(5).replace(/^ /, ""));
118933
- }
118934
- }
118935
- if (!done2) continue;
118936
- pendingText += decoder2.decode();
118937
- if (pendingText.length > 0) {
118938
- const line3 = pendingText.endsWith("\r") ? pendingText.slice(0, -1) : pendingText;
118939
- if (line3.startsWith("data:")) dataLines.push(line3.slice(5).replace(/^ /, ""));
118940
- }
118941
- yield* flushEvent();
118942
- return;
118943
- }
118944
- } finally {
118945
- if (abortHandler != null && options.signal != null) options.signal.removeEventListener("abort", abortHandler);
118946
- try {
118947
- await reader2.cancel();
118948
- } catch {
118949
- }
118950
- }
118951
- }
118952
- function decodeBase64Bytes(encoded) {
118953
- if (typeof Buffer !== "undefined") return new Uint8Array(Buffer.from(encoded, "base64"));
118954
- if (typeof atob === "function") {
118955
- const binary2 = atob(encoded);
118956
- const out2 = new Uint8Array(binary2.length);
118957
- for (let i2 = 0; i2 < binary2.length; i2 += 1) out2[i2] = binary2.charCodeAt(i2);
118958
- return out2;
118959
- }
118960
- throw new Error("base64 decoding is unavailable");
118961
- }
118962
- var StreamsClient = class {
118963
- streamUrl;
118964
- http;
118965
- defaultHeaders;
118966
- retryConfig;
118967
- timeoutConfig;
118968
- onRetry;
118969
- knownContentType;
118970
- constructor(options) {
118971
- if (options.url == null) throw new Error("StreamsClient requires url");
118972
- this.streamUrl = options.url instanceof URL ? new URL(options.url) : new URL(options.url);
118973
- const fetchImpl = options.fetch ?? globalThis.fetch?.bind(globalThis);
118974
- if (typeof fetchImpl !== "function") throw new Error("fetch is unavailable; pass options.fetch explicitly");
118975
- this.http = new AuthorizedHttpClient({
118976
- fetchImpl,
118977
- auth: options.auth
118978
- });
118979
- this.defaultHeaders = new Headers(options.headers);
118980
- this.retryConfig = normalizeRetryConfig(options.retry);
118981
- this.timeoutConfig = normalizeTimeoutConfig(options.timeout);
118982
- this.onRetry = options.onRetry;
118983
- }
118984
- async create(input2 = {}) {
118985
- validateCreateInput(input2);
118986
- const part = input2.part == null ? void 0 : normalizeStreamPartLike(input2.part);
118987
- const requestedContentType = part?.contentType ?? normalizeOptionalContentType(input2.contentType) ?? void 0;
118988
- try {
118989
- const requestUrl = this.streamEndpoint();
118990
- const headers = this.mergeHeaders(input2.headers);
118991
- if (requestedContentType != null) headers.set("Content-Type", requestedContentType);
118992
- if (input2.ttlSeconds != null) headers.set("Stream-TTL", String(input2.ttlSeconds));
118993
- if (input2.expiresAt != null) headers.set("Stream-Expires-At", input2.expiresAt);
118994
- if (input2.close === true) headers.set("Stream-Closed", "true");
118995
- const response = await this.http.fetchAuthorized(requestUrl, {
118996
- method: "PUT",
118997
- headers,
118998
- body: part == null ? void 0 : toRequestBody(part.body)
118999
- }, this.timeoutConfig.connectTimeoutMs, "connect");
119000
- if (response.status !== 200 && response.status !== 201) return {
119001
- ok: false,
119002
- result: await responseToStreamError(response, "create")
119003
- };
119004
- const contentType = this.resolveContentType(response, "create", requestedContentType ?? "application/octet-stream");
119005
- const nextOffset = getRequiredHeader(response.headers, "Stream-Next-Offset", "create");
119006
- this.knownContentType = contentType;
119007
- return {
119008
- ok: true,
119009
- result: this.withMeta({
119010
- created: response.status === 201,
119011
- contentType,
119012
- nextOffset,
119013
- closed: hasTrueHeader(response.headers, "Stream-Closed")
119014
- }, input2, "PUT", requestUrl, response)
119015
- };
119016
- } catch (error2) {
119017
- return {
119018
- ok: false,
119019
- result: thrownToStreamError(error2)
119020
- };
119021
- }
119022
- }
119023
- async delete(input2 = {}) {
119024
- try {
119025
- const requestUrl = this.streamEndpoint();
119026
- const response = await this.http.fetchAuthorized(requestUrl, {
119027
- method: "DELETE",
119028
- headers: this.mergeHeaders(input2.headers)
119029
- }, this.timeoutConfig.connectTimeoutMs, "connect");
119030
- if (response.status === 404) return {
119031
- ok: true,
119032
- result: this.withMeta({
119033
- deleted: false
119034
- }, input2, "DELETE", requestUrl, response)
119035
- };
119036
- if (response.status !== 200 && response.status !== 204) return {
119037
- ok: false,
119038
- result: await responseToStreamError(response, "delete")
119039
- };
119040
- return {
119041
- ok: true,
119042
- result: this.withMeta({
119043
- deleted: true
119044
- }, input2, "DELETE", requestUrl, response)
119045
- };
119046
- } catch (error2) {
119047
- return {
119048
- ok: false,
119049
- result: thrownToStreamError(error2)
119050
- };
119051
- }
119052
- }
119053
- async head(input2 = {}) {
119054
- try {
119055
- const requestUrl = this.streamEndpoint();
119056
- const response = await this.http.fetchAuthorized(requestUrl, {
119057
- method: "HEAD",
119058
- headers: this.mergeHeaders(input2.headers)
119059
- }, this.timeoutConfig.connectTimeoutMs, "connect");
119060
- if (!response.ok) return {
119061
- ok: false,
119062
- result: await responseToStreamError(response, "head")
119063
- };
119064
- const contentType = this.resolveContentType(response, "head", this.knownContentType);
119065
- const nextOffset = getRequiredHeader(response.headers, "Stream-Next-Offset", "head");
119066
- this.knownContentType = contentType;
119067
- return {
119068
- ok: true,
119069
- result: this.withMeta({
119070
- contentType,
119071
- nextOffset,
119072
- closed: hasTrueHeader(response.headers, "Stream-Closed"),
119073
- ttlSeconds: parseOptionalInteger(response.headers.get("Stream-TTL")) ?? void 0,
119074
- expiresAt: response.headers.get("Stream-Expires-At") ?? void 0,
119075
- snapshotOffset: response.headers.get("Stream-Snapshot-Offset") ?? void 0
119076
- }, input2, "HEAD", requestUrl, response)
119077
- };
119078
- } catch (error2) {
119079
- return {
119080
- ok: false,
119081
- result: thrownToStreamError(error2)
119082
- };
119083
- }
119084
- }
119085
- async append(input2) {
119086
- validateAppendInput(input2);
119087
- const part = input2.part == null ? void 0 : normalizeStreamPartLike(input2.part);
119088
- let attempt = 0;
119089
- while (true) try {
119090
- const requestUrl = this.streamEndpoint();
119091
- const response = await this.http.fetchAuthorized(requestUrl, {
119092
- method: "POST",
119093
- headers: this.appendHeaders(input2, part?.contentType),
119094
- body: part == null ? void 0 : toRequestBody(part.body)
119095
- }, this.timeoutConfig.connectTimeoutMs, "connect", {
119096
- shouldRetryAuthFailure: (nextResponse) => nextResponse.status === 401 || nextResponse.status === 403 && nextResponse.headers.get("Producer-Epoch") == null
119097
- });
119098
- if (response.status !== 200 && response.status !== 204) return {
119099
- ok: false,
119100
- result: await responseToStreamError(response, "append")
119101
- };
119102
- if (part != null) this.knownContentType = part.contentType;
119103
- return {
119104
- ok: true,
119105
- result: this.withMeta(this.parseAppendOutput(response, input2), input2, "POST", requestUrl, response)
119106
- };
119107
- } catch (error2) {
119108
- const result = thrownToStreamError(error2);
119109
- if (input2.producer == null || !isAppendRetryable(result) || attempt >= this.retryConfig.maxAttempts) return {
119110
- ok: false,
119111
- result
119112
- };
119113
- const delay2 = computeRetryDelay(attempt, this.retryConfig);
119114
- attempt += 1;
119115
- this.onRetry?.({
119116
- operation: "append",
119117
- error: result,
119118
- attempt,
119119
- delayMs: delay2,
119120
- maxAttempts: this.retryConfig.maxAttempts
119121
- });
119122
- await sleep$1(delay2);
119123
- }
119124
- }
119125
- async close(input2 = {}) {
119126
- return await this.append({
119127
- close: true,
119128
- headers: input2.headers,
119129
- includeMeta: input2.includeMeta,
119130
- producer: input2.producer
119131
- });
119132
- }
119133
- async read(input2 = {}) {
119134
- const result = await this.readOnce(input2);
119135
- if (!result.ok) return result;
119136
- if (result.result.payload == null) return {
119137
- ok: false,
119138
- result: {
119139
- code: "protocol_error",
119140
- message: "read response must include a payload body"
119141
- }
119142
- };
119143
- return {
119144
- ok: true,
119145
- result: {
119146
- requestOffset: result.result.requestOffset,
119147
- nextOffset: result.result.nextOffset,
119148
- upToDate: result.result.upToDate,
119149
- closed: result.result.closed,
119150
- cursor: result.result.cursor,
119151
- payload: result.result.payload,
119152
- meta: result.result.meta
119153
- }
119154
- };
119155
- }
119156
- async readOnce(input2 = {}) {
119157
- validateReadOnceInput(input2);
119158
- const requestOffset = input2.offset ?? "-1";
119159
- try {
119160
- const requestUrl = this.readEndpoint({
119161
- offset: requestOffset,
119162
- cursor: input2.cursor,
119163
- live: input2.live
119164
- });
119165
- const timeoutMs = input2.live === "long-poll" ? this.timeoutConfig.pollTimeoutMs : this.timeoutConfig.connectTimeoutMs;
119166
- const phase = input2.live === "long-poll" ? "poll" : "connect";
119167
- const response = await this.http.fetchAuthorized(requestUrl, {
119168
- method: "GET",
119169
- headers: this.mergeHeaders(input2.headers),
119170
- signal: input2.signal
119171
- }, timeoutMs, phase);
119172
- if (!response.ok) return {
119173
- ok: false,
119174
- result: await responseToStreamError(response, "read once")
119175
- };
119176
- if (response.status === 204) {
119177
- const nextOffset = getRequiredHeader(response.headers, "Stream-Next-Offset", "read once");
119178
- if (!hasTrueHeader(response.headers, "Stream-Up-To-Date")) throw new ProtocolError("long-poll 204 response missing Stream-Up-To-Date: true");
119179
- const closed = hasTrueHeader(response.headers, "Stream-Closed");
119180
- const cursor = response.headers.get("Stream-Cursor") ?? void 0;
119181
- return {
119182
- ok: true,
119183
- result: this.withMeta({
119184
- status: 204,
119185
- requestOffset,
119186
- nextOffset,
119187
- upToDate: true,
119188
- closed,
119189
- cursor,
119190
- payload: null
119191
- }, input2, "GET", requestUrl, response)
119192
- };
119193
- }
119194
- const output = await this.parseReadOutput(response, requestOffset, "read once");
119195
- return {
119196
- ok: true,
119197
- result: this.withMeta({
119198
- status: 200,
119199
- ...output
119200
- }, input2, "GET", requestUrl, response)
119201
- };
119202
- } catch (error2) {
119203
- return {
119204
- ok: false,
119205
- result: thrownToStreamError(error2)
119206
- };
119207
- }
119208
- }
119209
- async bootstrap(input2 = {}) {
119210
- try {
119211
- const requestUrl = this.subresourceEndpoint("/bootstrap");
119212
- const response = await this.http.fetchAuthorized(requestUrl, {
119213
- method: "GET",
119214
- headers: this.mergeHeaders(input2.headers),
119215
- signal: input2.signal
119216
- }, this.timeoutConfig.connectTimeoutMs, "connect");
119217
- if (!response.ok) return {
119218
- ok: false,
119219
- result: await responseToStreamError(response, "bootstrap")
119220
- };
119221
- const boundary = extractBoundary(response.headers.get("Content-Type") ?? "");
119222
- if (boundary == null) throw new ProtocolError("bootstrap response must be multipart/mixed");
119223
- const nextOffset = getRequiredHeader(response.headers, "Stream-Next-Offset", "bootstrap");
119224
- const snapshotOffset = getRequiredHeader(response.headers, "Stream-Snapshot-Offset", "bootstrap");
119225
- const parts2 = decodeMultipartMixed(boundary, new Uint8Array(await response.arrayBuffer()));
119226
- if (parts2.length === 0) throw new ProtocolError("bootstrap response must include at least one MIME part");
119227
- const first2 = parts2[0];
119228
- const snapshot = snapshotOffset === "-1" && first2?.body.byteLength === 0 ? null : createStreamPart(first2.contentType, first2.body);
119229
- const updates = parts2.slice(1).map((part) => createStreamPart(part.contentType, part.body));
119230
- if (updates.length > 0) this.knownContentType = updates[0].contentType;
119231
- return {
119232
- ok: true,
119233
- result: this.withMeta({
119234
- snapshotOffset,
119235
- nextOffset,
119236
- upToDate: hasTrueHeader(response.headers, "Stream-Up-To-Date"),
119237
- cursor: response.headers.get("Stream-Cursor") ?? void 0,
119238
- snapshot,
119239
- updates
119240
- }, input2, "GET", requestUrl, response)
119241
- };
119242
- } catch (error2) {
119243
- return {
119244
- ok: false,
119245
- result: thrownToStreamError(error2)
119246
- };
119247
- }
119248
- }
119249
- async readLatestSnapshot(input2 = {}) {
119250
- try {
119251
- const requestUrl = this.subresourceEndpoint("/snapshot");
119252
- const response = await this.http.fetchAuthorized(requestUrl, {
119253
- method: "GET",
119254
- headers: this.mergeHeaders(input2.headers)
119255
- }, this.timeoutConfig.connectTimeoutMs, "connect");
119256
- if (response.status === 404) return {
119257
- ok: true,
119258
- result: null
119259
- };
119260
- if (!response.ok) return {
119261
- ok: false,
119262
- result: await responseToStreamError(response, "read latest snapshot")
119263
- };
119264
- return {
119265
- ok: true,
119266
- result: this.withMeta(await this.parseSnapshotReadOutput(response, "read latest snapshot"), input2, "GET", requestUrl, response)
119267
- };
119268
- } catch (error2) {
119269
- return {
119270
- ok: false,
119271
- result: thrownToStreamError(error2)
119272
- };
119273
- }
119274
- }
119275
- async readSnapshot(offset2, input2 = {}) {
119276
- assertNonEmptyString(offset2, "offset");
119277
- try {
119278
- const requestUrl = this.subresourceEndpoint(`/snapshot/${encodeURIComponent(offset2)}`);
119279
- const response = await this.http.fetchAuthorized(requestUrl, {
119280
- method: "GET",
119281
- headers: this.mergeHeaders(input2.headers)
119282
- }, this.timeoutConfig.connectTimeoutMs, "connect");
119283
- if (!response.ok) return {
119284
- ok: false,
119285
- result: await responseToStreamError(response, "read snapshot")
119286
- };
119287
- return {
119288
- ok: true,
119289
- result: this.withMeta(await this.parseSnapshotReadOutput(response, "read snapshot"), input2, "GET", requestUrl, response)
119290
- };
119291
- } catch (error2) {
119292
- return {
119293
- ok: false,
119294
- result: thrownToStreamError(error2)
119295
- };
119296
- }
119297
- }
119298
- async putSnapshot(input2) {
119299
- assertNonEmptyString(input2.offset, "offset");
119300
- const part = normalizeStreamPartLike(input2.part);
119301
- try {
119302
- const requestUrl = this.subresourceEndpoint(`/snapshot/${encodeURIComponent(input2.offset)}`);
119303
- const response = await this.http.fetchAuthorized(requestUrl, {
119304
- method: "PUT",
119305
- headers: this.mergeHeaders(input2.headers, {
119306
- "Content-Type": part.contentType
119307
- }),
119308
- body: toRequestBody(part.body)
119309
- }, this.timeoutConfig.connectTimeoutMs, "connect");
119310
- if (response.status !== 200 && response.status !== 204) return {
119311
- ok: false,
119312
- result: await responseToStreamError(response, "put snapshot")
119313
- };
119314
- return {
119315
- ok: true,
119316
- result: this.withMeta({
119317
- stored: true,
119318
- snapshotOffset: input2.offset
119319
- }, input2, "PUT", requestUrl, response)
119320
- };
119321
- } catch (error2) {
119322
- return {
119323
- ok: false,
119324
- result: thrownToStreamError(error2)
119325
- };
119326
- }
119327
- }
119328
- async deleteSnapshot(offset2, input2 = {}) {
119329
- assertNonEmptyString(offset2, "offset");
119330
- try {
119331
- const requestUrl = this.subresourceEndpoint(`/snapshot/${encodeURIComponent(offset2)}`);
119332
- const response = await this.http.fetchAuthorized(requestUrl, {
119333
- method: "DELETE",
119334
- headers: this.mergeHeaders(input2.headers)
119335
- }, this.timeoutConfig.connectTimeoutMs, "connect");
119336
- if (response.status === 404) return {
119337
- ok: true,
119338
- result: this.withMeta({
119339
- deleted: false
119340
- }, input2, "DELETE", requestUrl, response)
119341
- };
119342
- if (response.status !== 200 && response.status !== 204) return {
119343
- ok: false,
119344
- result: await responseToStreamError(response, "delete snapshot")
119345
- };
119346
- return {
119347
- ok: true,
119348
- result: this.withMeta({
119349
- deleted: true
119350
- }, input2, "DELETE", requestUrl, response)
119351
- };
119352
- } catch (error2) {
119353
- return {
119354
- ok: false,
119355
- result: thrownToStreamError(error2)
119356
- };
119357
- }
119358
- }
119359
- async openSseSession(input2) {
119360
- validateOpenSseSessionInput(input2);
119361
- const requestUrl = this.readEndpoint({
119362
- offset: input2.offset,
119363
- cursor: input2.cursor,
119364
- live: "sse"
119365
- });
119366
- const controller = new AbortController();
119367
- const signal = mergeAbortSignals(input2.signal, controller.signal);
119368
- try {
119369
- const response = await this.http.fetchAuthorized(requestUrl, {
119370
- method: "GET",
119371
- headers: this.mergeHeaders(input2.headers, {
119372
- Accept: "text/event-stream"
119373
- }),
119374
- signal
119375
- }, this.timeoutConfig.connectTimeoutMs, "connect");
119376
- if (!response.ok) return {
119377
- ok: false,
119378
- result: await responseToStreamError(response, "open sse session")
119379
- };
119380
- if (response.body == null) throw new ProtocolError("sse response missing body");
119381
- if (!(response.headers.get("Content-Type") ?? "").toLowerCase().includes("text/event-stream")) throw new ProtocolError("sse response must use text/event-stream content type");
119382
- const events = createSessionEvents(response.body, signal, input2.onActivity);
119383
- return {
119384
- ok: true,
119385
- result: {
119386
- nextOffset: response.headers.get("Stream-Next-Offset") ?? void 0,
119387
- cursor: response.headers.get("Stream-Cursor") ?? void 0,
119388
- dataEncoding: response.headers.get("Stream-SSE-Data-Encoding") ?? void 0,
119389
- events,
119390
- meta: input2.includeMeta === true ? createOperationMeta("GET", requestUrl, response) : void 0,
119391
- cancel: async () => {
119392
- controller.abort(new DOMException("Aborted", "AbortError"));
119393
- try {
119394
- await response.body?.cancel();
119395
- } catch {
119396
- }
119397
- }
119398
- }
119399
- };
119400
- } catch (error2) {
119401
- return {
119402
- ok: false,
119403
- result: thrownToStreamError(error2)
119404
- };
119405
- }
119406
- }
119407
- live(input2) {
119408
- validateLiveInput(input2);
119409
- return this.liveInternal({
119410
- offset: input2.offset,
119411
- mode: input2.mode ?? "auto",
119412
- signal: input2.signal
119413
- });
119414
- }
119415
- async *liveInternal(input2) {
119416
- if (input2.mode === "long-poll") {
119417
- const state3 = {
119418
- offset: input2.offset,
119419
- contentType: this.knownContentType ?? "application/octet-stream"
119420
- };
119421
- yield* this.runLongPollLive(state3, input2.signal);
119422
- return;
119423
- }
119424
- const contentTypeResult = await this.ensureKnownContentType();
119425
- if (!contentTypeResult.ok) {
119426
- yield {
119427
- type: "error",
119428
- mode: "sse",
119429
- error: contentTypeResult.result
119430
- };
119431
- return;
119432
- }
119433
- const state2 = {
119434
- offset: input2.offset,
119435
- contentType: contentTypeResult.result
119436
- };
119437
- if (await (yield* this.runSseLive(state2, input2.signal, input2.mode === "auto")) === "fallback") yield* this.runLongPollLive(state2, input2.signal);
119438
- }
119439
- async *runSseLive(state2, signal, allowFallback) {
119440
- let attempt = 0;
119441
- let reconnectAttempt = 0;
119442
- while (true) {
119443
- if (signal?.aborted) return "done";
119444
- try {
119445
- const response = await this.http.fetchAuthorized(this.readEndpoint({
119446
- offset: state2.offset,
119447
- cursor: state2.cursor,
119448
- live: "sse"
119449
- }), {
119450
- method: "GET",
119451
- signal
119452
- }, this.timeoutConfig.connectTimeoutMs, "connect");
119453
- if (response.status === 400) {
119454
- const errorText = await response.text();
119455
- if (allowFallback && isSseUnsupportedErrorText(errorText)) return "fallback";
119456
- yield {
119457
- type: "error",
119458
- mode: "sse",
119459
- error: {
119460
- code: "bad_request",
119461
- status: 400,
119462
- message: errorText.length > 0 ? `live sse failed with status 400: ${errorText}` : "live sse failed with status 400"
119463
- }
119464
- };
119465
- return "done";
119466
- }
119467
- if (!response.ok) {
119468
- yield {
119469
- type: "error",
119470
- mode: "sse",
119471
- error: await responseToStreamError(response, "live sse")
119472
- };
119473
- return "done";
119474
- }
119475
- if (response.body == null) throw new ProtocolError("sse response missing body");
119476
- if (!(response.headers.get("Content-Type") ?? "").toLowerCase().includes("text/event-stream")) throw new ProtocolError("sse response must use text/event-stream content type");
119477
- if (reconnectAttempt > 0) yield {
119478
- type: "reconnected",
119479
- mode: "sse",
119480
- attempt: reconnectAttempt
119481
- };
119482
- attempt = 0;
119483
- reconnectAttempt = 0;
119484
- const dataEncoding = response.headers.get("stream-sse-data-encoding");
119485
- let pendingPayloads = [];
119486
- let sawControlEvent = false;
119487
- for await (const event of readSseEvents(response.body, {
119488
- signal
119489
- })) {
119490
- if (event.event === "data") {
119491
- pendingPayloads.push(decodeSsePayload(event.data, dataEncoding));
119492
- continue;
119493
- }
119494
- if (event.event !== "control") continue;
119495
- const control = parseSseControlData(event.data);
119496
- sawControlEvent = true;
119497
- state2.offset = control.nextOffset;
119498
- const effectiveCursor = control.streamCursor ?? state2.cursor;
119499
- state2.cursor = effectiveCursor;
119500
- for (const payload of pendingPayloads) yield {
119501
- type: "data",
119502
- mode: "sse",
119503
- nextOffset: control.nextOffset,
119504
- cursor: effectiveCursor,
119505
- payload: createStreamPart(state2.contentType, payload)
119506
- };
119507
- pendingPayloads = [];
119508
- if (control.streamClosed) {
119509
- yield {
119510
- type: "eof",
119511
- mode: "sse",
119512
- nextOffset: control.nextOffset
119513
- };
119514
- return "done";
119515
- }
119516
- if (control.upToDate) yield {
119517
- type: "up_to_date",
119518
- mode: "sse",
119519
- nextOffset: control.nextOffset,
119520
- cursor: effectiveCursor
119521
- };
119522
- }
119523
- if (signal?.aborted) return "done";
119524
- if (pendingPayloads.length > 0) throw new TypeError("sse connection closed before control event");
119525
- if (sawControlEvent) continue;
119526
- throw new TypeError("sse connection closed");
119527
- } catch (error2) {
119528
- if (signal?.aborted && isAbortError(error2)) return "done";
119529
- const mapped = thrownToStreamError(error2);
119530
- if (!isRetryableLiveError(mapped) || attempt >= this.retryConfig.maxAttempts) {
119531
- const retryExhausted = isRetryableLiveError(mapped) && attempt >= this.retryConfig.maxAttempts;
119532
- yield {
119533
- type: "error",
119534
- mode: "sse",
119535
- error: mapped,
119536
- attempt,
119537
- maxAttempts: this.retryConfig.maxAttempts,
119538
- retryExhausted
119539
- };
119540
- return "done";
119541
- }
119542
- const delayMs = computeRetryDelay(attempt, this.retryConfig);
119543
- const nextAttempt = attempt + 1;
119544
- this.onRetry?.({
119545
- operation: "live-sse",
119546
- error: mapped,
119547
- attempt: nextAttempt,
119548
- delayMs,
119549
- maxAttempts: this.retryConfig.maxAttempts
119550
- });
119551
- yield {
119552
- type: "reconnecting",
119553
- mode: "sse",
119554
- attempt: nextAttempt,
119555
- delayMs,
119556
- error: mapped
119557
- };
119558
- try {
119559
- await sleep$1(delayMs, signal);
119560
- } catch {
119561
- return "done";
119562
- }
119563
- attempt = nextAttempt;
119564
- reconnectAttempt = nextAttempt;
119565
- }
119566
- }
119567
- }
119568
- async *runLongPollLive(state2, signal) {
119569
- let attempt = 0;
119570
- let reconnectAttempt = 0;
119571
- while (true) {
119572
- if (signal?.aborted) return;
119573
- try {
119574
- const response = await this.http.fetchAuthorized(this.readEndpoint({
119575
- offset: state2.offset,
119576
- cursor: state2.cursor,
119577
- live: "long-poll"
119578
- }), {
119579
- method: "GET",
119580
- signal
119581
- }, this.timeoutConfig.pollTimeoutMs, "poll");
119582
- if (response.status === 204) {
119583
- const nextOffset = getRequiredHeader(response.headers, "Stream-Next-Offset", "live long-poll");
119584
- if (!hasTrueHeader(response.headers, "Stream-Up-To-Date")) throw new ProtocolError("long-poll 204 response missing Stream-Up-To-Date: true");
119585
- const closed = hasTrueHeader(response.headers, "Stream-Closed");
119586
- const effectiveCursor = response.headers.get("Stream-Cursor") ?? void 0 ?? state2.cursor;
119587
- if (reconnectAttempt > 0) yield {
119588
- type: "reconnected",
119589
- mode: "long-poll",
119590
- attempt: reconnectAttempt
119591
- };
119592
- attempt = 0;
119593
- reconnectAttempt = 0;
119594
- state2.offset = nextOffset;
119595
- state2.cursor = effectiveCursor;
119596
- if (closed) {
119597
- yield {
119598
- type: "eof",
119599
- mode: "long-poll",
119600
- nextOffset
119601
- };
119602
- return;
119603
- }
119604
- yield {
119605
- type: "up_to_date",
119606
- mode: "long-poll",
119607
- nextOffset,
119608
- cursor: effectiveCursor
119609
- };
119610
- continue;
119611
- }
119612
- if (!response.ok) {
119613
- yield {
119614
- type: "error",
119615
- mode: "long-poll",
119616
- error: await responseToStreamError(response, "live long-poll")
119617
- };
119618
- return;
119619
- }
119620
- if (reconnectAttempt > 0) yield {
119621
- type: "reconnected",
119622
- mode: "long-poll",
119623
- attempt: reconnectAttempt
119624
- };
119625
- attempt = 0;
119626
- reconnectAttempt = 0;
119627
- const output = await this.parseReadOutput(response, state2.offset, "live long-poll");
119628
- const outputCursor = output.cursor ?? state2.cursor;
119629
- state2.offset = output.nextOffset;
119630
- state2.cursor = outputCursor;
119631
- yield {
119632
- type: "data",
119633
- mode: "long-poll",
119634
- nextOffset: output.nextOffset,
119635
- cursor: outputCursor,
119636
- payload: output.payload
119637
- };
119638
- if (output.closed) {
119639
- yield {
119640
- type: "eof",
119641
- mode: "long-poll",
119642
- nextOffset: output.nextOffset
119643
- };
119644
- return;
119645
- }
119646
- if (output.upToDate) yield {
119647
- type: "up_to_date",
119648
- mode: "long-poll",
119649
- nextOffset: output.nextOffset,
119650
- cursor: outputCursor
119651
- };
119652
- } catch (error2) {
119653
- if (signal?.aborted && isAbortError(error2)) return;
119654
- const mapped = thrownToStreamError(error2);
119655
- if (!isRetryableLiveError(mapped) || attempt >= this.retryConfig.maxAttempts) {
119656
- const retryExhausted = isRetryableLiveError(mapped) && attempt >= this.retryConfig.maxAttempts;
119657
- yield {
119658
- type: "error",
119659
- mode: "long-poll",
119660
- error: mapped,
119661
- attempt,
119662
- maxAttempts: this.retryConfig.maxAttempts,
119663
- retryExhausted
119664
- };
119665
- return;
119666
- }
119667
- const delayMs = computeRetryDelay(attempt, this.retryConfig);
119668
- const nextAttempt = attempt + 1;
119669
- this.onRetry?.({
119670
- operation: "live-long-poll",
119671
- error: mapped,
119672
- attempt: nextAttempt,
119673
- delayMs,
119674
- maxAttempts: this.retryConfig.maxAttempts
119675
- });
119676
- yield {
119677
- type: "reconnecting",
119678
- mode: "long-poll",
119679
- attempt: nextAttempt,
119680
- delayMs,
119681
- error: mapped
119682
- };
119683
- try {
119684
- await sleep$1(delayMs, signal);
119685
- } catch {
119686
- return;
119687
- }
119688
- attempt = nextAttempt;
119689
- reconnectAttempt = nextAttempt;
119690
- }
119691
- }
119692
- }
119693
- appendHeaders(input2, contentType) {
119694
- const headers = this.mergeHeaders(input2.headers);
119695
- if (contentType != null) headers.set("Content-Type", contentType);
119696
- if (input2.close === true) headers.set("Stream-Closed", "true");
119697
- if (input2.streamSeq != null) headers.set("Stream-Seq", input2.streamSeq);
119698
- if (input2.producer != null) {
119699
- headers.set("Producer-Id", input2.producer.producerId);
119700
- headers.set("Producer-Epoch", String(input2.producer.epoch));
119701
- headers.set("Producer-Seq", String(input2.producer.seq));
119702
- }
119703
- return headers;
119704
- }
119705
- mergeHeaders(...layers) {
119706
- const headers = new Headers(this.defaultHeaders);
119707
- for (const layer2 of layers) {
119708
- if (layer2 == null) continue;
119709
- new Headers(layer2).forEach((value, name2) => {
119710
- headers.set(name2, value);
119711
- });
119712
- }
119713
- return headers;
119714
- }
119715
- withMeta(result, input2, method, url, response) {
119716
- if (input2?.includeMeta !== true) return result;
119717
- return {
119718
- ...result,
119719
- meta: createOperationMeta(method, url, response)
119720
- };
119721
- }
119722
- parseAppendOutput(response, input2) {
119723
- return {
119724
- status: response.status,
119725
- nextOffset: getRequiredHeader(response.headers, "Stream-Next-Offset", "append"),
119726
- closed: hasTrueHeader(response.headers, "Stream-Closed"),
119727
- producer: input2.producer == null ? void 0 : {
119728
- epoch: parseOptionalInteger(response.headers.get("Producer-Epoch")) ?? input2.producer.epoch,
119729
- seq: parseOptionalInteger(response.headers.get("Producer-Seq")) ?? input2.producer.seq
119730
- }
119731
- };
119732
- }
119733
- async parseReadOutput(response, requestOffset, context2) {
119734
- const contentType = this.resolveContentType(response, context2, this.knownContentType);
119735
- this.knownContentType = contentType;
119736
- return {
119737
- requestOffset,
119738
- nextOffset: getRequiredHeader(response.headers, "Stream-Next-Offset", context2),
119739
- upToDate: hasTrueHeader(response.headers, "Stream-Up-To-Date"),
119740
- closed: hasTrueHeader(response.headers, "Stream-Closed"),
119741
- cursor: response.headers.get("Stream-Cursor") ?? void 0,
119742
- payload: createStreamPart(contentType, new Uint8Array(await response.arrayBuffer()))
119743
- };
119744
- }
119745
- async parseSnapshotReadOutput(response, context2) {
119746
- const contentType = this.resolveContentType(response, context2);
119747
- return {
119748
- snapshotOffset: getRequiredHeader(response.headers, "Stream-Snapshot-Offset", context2),
119749
- nextOffset: getRequiredHeader(response.headers, "Stream-Next-Offset", context2),
119750
- upToDate: hasTrueHeader(response.headers, "Stream-Up-To-Date"),
119751
- payload: createStreamPart(contentType, new Uint8Array(await response.arrayBuffer()))
119752
- };
119753
- }
119754
- async ensureKnownContentType() {
119755
- if (this.knownContentType != null) return {
119756
- ok: true,
119757
- result: this.knownContentType
119758
- };
119759
- const headResult = await this.head();
119760
- if (!headResult.ok) return headResult;
119761
- this.knownContentType = headResult.result.contentType;
119762
- return {
119763
- ok: true,
119764
- result: headResult.result.contentType
119765
- };
119766
- }
119767
- resolveContentType(response, context2, fallback2) {
119768
- const headerValue = response.headers.get("Content-Type");
119769
- if (headerValue != null && headerValue.length > 0) return headerValue;
119770
- if (fallback2 != null && fallback2.length > 0) return fallback2;
119771
- throw new ProtocolError(`${context2} response missing Content-Type`);
119772
- }
119773
- streamEndpoint() {
119774
- const target = new URL(this.streamUrl);
119775
- target.search = "";
119776
- return target.toString();
119777
- }
119778
- subresourceEndpoint(suffix) {
119779
- const target = new URL(this.streamUrl);
119780
- target.search = "";
119781
- target.pathname = `${target.pathname.endsWith("/") ? target.pathname.slice(0, -1) : target.pathname}${suffix}`;
119782
- return target.toString();
119783
- }
119784
- readEndpoint(input2) {
119785
- const target = new URL(this.streamEndpoint());
119786
- target.searchParams.set("offset", input2.offset);
119787
- if (input2.cursor != null && input2.cursor.length > 0) target.searchParams.set("cursor", input2.cursor);
119788
- if (input2.live != null) target.searchParams.set("live", input2.live);
119789
- return target.toString();
119790
- }
119791
- };
119792
- function validateCreateInput(input2) {
119793
- if (input2.ttlSeconds != null) assertNonNegativeSafeInteger(input2.ttlSeconds, "ttlSeconds");
119794
- if (input2.expiresAt != null) assertNonEmptyString(input2.expiresAt, "expiresAt");
119795
- if (input2.ttlSeconds != null && input2.expiresAt != null) throw new Error("create input must not include both ttlSeconds and expiresAt");
119796
- if (input2.contentType != null) normalizeContentType(input2.contentType);
119797
- }
119798
- function validateAppendInput(input2) {
119799
- if (input2.streamSeq != null) assertNonEmptyString(input2.streamSeq, "streamSeq");
119800
- if (input2.producer != null) {
119801
- assertNonEmptyString(input2.producer.producerId, "producer.producerId");
119802
- assertNonNegativeSafeInteger(input2.producer.epoch, "producer.epoch");
119803
- assertNonNegativeSafeInteger(input2.producer.seq, "producer.seq");
119804
- }
119805
- if (input2.part == null) {
119806
- if (input2.close !== true) throw new Error("append requires part unless close is true");
119807
- return;
119808
- }
119809
- if (normalizeStreamPartLike(input2.part).body.byteLength === 0 && input2.close !== true) throw new Error("append requires a non-empty body unless close is true");
119810
- }
119811
- function validateReadInput(input2) {
119812
- if (input2.offset != null) assertNonEmptyString(input2.offset, "offset");
119813
- if (input2.cursor != null) assertNonEmptyString(input2.cursor, "cursor");
119814
- }
119815
- function validateReadOnceInput(input2) {
119816
- validateReadInput(input2);
119817
- if (input2.live != null && input2.live !== "long-poll") throw new Error("readOnce live mode must be long-poll when provided");
119818
- }
119819
- function validateOpenSseSessionInput(input2) {
119820
- assertNonEmptyString(input2.offset, "offset");
119821
- if (input2.cursor != null) assertNonEmptyString(input2.cursor, "cursor");
119822
- }
119823
- function validateLiveInput(input2) {
119824
- assertNonEmptyString(input2.offset, "offset");
119825
- }
119826
- function assertNonEmptyString(value, name2) {
119827
- if (value.trim().length === 0) throw new Error(`${name2} must be a non-empty string`);
119828
- }
119829
- function assertNonNegativeSafeInteger(value, name2) {
119830
- if (!Number.isSafeInteger(value) || value < 0) throw new Error(`${name2} must be a non-negative safe integer`);
119831
- }
119832
- function isAppendRetryable(error2) {
119833
- return error2.code === "network_error" || error2.code === "timeout";
119834
- }
119835
- function createOperationMeta(method, url, response) {
119836
- return {
119837
- request: {
119838
- method,
119839
- url
119840
- },
119841
- response: {
119842
- status: response.status,
119843
- statusText: response.statusText,
119844
- headers: headersToObject(response.headers)
119845
- }
119846
- };
119847
- }
119848
- function headersToObject(headers) {
119849
- const result = {};
119850
- headers.forEach((value, name2) => {
119851
- result[name2] = value;
119852
- });
119853
- return result;
119854
- }
119855
- function createSessionEvents(stream2, signal, onActivity) {
119856
- return {
119857
- async *[Symbol.asyncIterator]() {
119858
- try {
119859
- yield* readSseEvents(stream2, {
119860
- signal,
119861
- onActivity
119862
- });
119863
- } catch (error2) {
119864
- if (signal?.aborted && isAbortError(error2)) return;
119865
- throw error2;
119866
- }
119867
- }
119868
- };
119869
- }
119870
- function mergeAbortSignals(...signals2) {
119871
- const active2 = signals2.filter((signal) => signal != null);
119872
- if (active2.length === 0) return;
119873
- if (active2.length === 1) return active2[0];
119874
- if (typeof AbortSignal.any === "function") return AbortSignal.any(active2);
119875
- const controller = new AbortController();
119876
- for (const signal of active2) {
119877
- if (signal.aborted) {
119878
- controller.abort(signal.reason);
119879
- break;
119880
- }
119881
- signal.addEventListener("abort", () => {
119882
- controller.abort(signal.reason);
119883
- }, {
119884
- once: true
119885
- });
119886
- }
119887
- return controller.signal;
119888
- }
119889
118509
  const DEFAULT_GATEWAY_BASE_URL = "https://streams-api-proxy.loro.dev";
119890
118510
  const JSON_RPC_VERSION$1 = "2.0";
119891
118511
  const LORO_STREAMS_RPC_VERSION = "1";