lody 0.54.1 → 0.55.1

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.1";
36825
+ const version$4 = "0.55.1";
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";
@@ -36865,7 +36865,7 @@ Mongoose Error Code: ${error2.code}` : ""}`
36865
36865
  "node": ">=18.0.0"
36866
36866
  };
36867
36867
  const optionalDependencies = {
36868
- "acp-extension-claude": "0.37.0",
36868
+ "acp-extension-claude": "0.38.0",
36869
36869
  "acp-extension-codex": "0.15.0"
36870
36870
  };
36871
36871
  const devDependencies = {
@@ -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);
@@ -79826,6 +79826,9 @@ Task description:
79826
79826
  _meta: record(string$2(), unknown()).nullish(),
79827
79827
  terminalId: string$2()
79828
79828
  });
79829
+ const zDeleteSessionResponse = object$1({
79830
+ _meta: record(string$2(), unknown()).nullish()
79831
+ });
79829
79832
  const zDiff = object$1({
79830
79833
  _meta: record(string$2(), unknown()).nullish(),
79831
79834
  newText: string$2(),
@@ -79839,6 +79842,9 @@ Task description:
79839
79842
  const zDisableProvidersResponse = object$1({
79840
79843
  _meta: record(string$2(), unknown()).nullish()
79841
79844
  });
79845
+ const zDisconnectMcpResponse = object$1({
79846
+ _meta: record(string$2(), unknown()).nullish()
79847
+ });
79842
79848
  const zElicitationContentValue = union$3([
79843
79849
  string$2(),
79844
79850
  number$3(),
@@ -79944,7 +79950,6 @@ Task description:
79944
79950
  });
79945
79951
  const zListSessionsRequest = object$1({
79946
79952
  _meta: record(string$2(), unknown()).nullish(),
79947
- additionalDirectories: array$3(string$2()).optional(),
79948
79953
  cursor: string$2().nullish(),
79949
79954
  cwd: string$2().nullish()
79950
79955
  });
@@ -79971,9 +79976,29 @@ Task description:
79971
79976
  });
79972
79977
  const zMcpCapabilities = object$1({
79973
79978
  _meta: record(string$2(), unknown()).nullish(),
79979
+ acp: boolean().optional().default(false),
79974
79980
  http: boolean().optional().default(false),
79975
79981
  sse: boolean().optional().default(false)
79976
79982
  });
79983
+ const zMcpConnectionId = string$2();
79984
+ const zConnectMcpResponse = object$1({
79985
+ _meta: record(string$2(), unknown()).nullish(),
79986
+ connectionId: zMcpConnectionId
79987
+ });
79988
+ const zDisconnectMcpRequest = object$1({
79989
+ _meta: record(string$2(), unknown()).nullish(),
79990
+ connectionId: zMcpConnectionId
79991
+ });
79992
+ const zMcpServerAcpId = string$2();
79993
+ const zConnectMcpRequest = object$1({
79994
+ _meta: record(string$2(), unknown()).nullish(),
79995
+ acpId: zMcpServerAcpId
79996
+ });
79997
+ const zMcpServerAcp = object$1({
79998
+ _meta: record(string$2(), unknown()).nullish(),
79999
+ id: zMcpServerAcpId,
80000
+ name: string$2()
80001
+ });
79977
80002
  const zMcpServerHttp = object$1({
79978
80003
  _meta: record(string$2(), unknown()).nullish(),
79979
80004
  headers: array$3(zHttpHeader),
@@ -80000,8 +80025,24 @@ Task description:
80000
80025
  zMcpServerSse.and(object$1({
80001
80026
  type: literal("sse")
80002
80027
  })),
80028
+ zMcpServerAcp.and(object$1({
80029
+ type: literal("acp")
80030
+ })),
80003
80031
  zMcpServerStdio
80004
80032
  ]);
80033
+ const zMessageMcpNotification = object$1({
80034
+ _meta: record(string$2(), unknown()).nullish(),
80035
+ connectionId: zMcpConnectionId,
80036
+ method: string$2(),
80037
+ params: record(string$2(), unknown()).nullish()
80038
+ });
80039
+ const zMessageMcpRequest = object$1({
80040
+ _meta: record(string$2(), unknown()).nullish(),
80041
+ connectionId: zMcpConnectionId,
80042
+ method: string$2(),
80043
+ params: record(string$2(), unknown()).nullish()
80044
+ });
80045
+ const zMessageMcpResponse = unknown();
80005
80046
  const zModelId = string$2();
80006
80047
  const zModelInfo = object$1({
80007
80048
  _meta: record(string$2(), unknown()).nullish(),
@@ -80425,6 +80466,9 @@ Task description:
80425
80466
  _meta: record(string$2(), unknown()).nullish(),
80426
80467
  configOptions: array$3(zSessionConfigOption)
80427
80468
  });
80469
+ const zSessionDeleteCapabilities = object$1({
80470
+ _meta: record(string$2(), unknown()).nullish()
80471
+ });
80428
80472
  const zSessionForkCapabilities = object$1({
80429
80473
  _meta: record(string$2(), unknown()).nullish()
80430
80474
  });
@@ -80455,6 +80499,10 @@ Task description:
80455
80499
  outputByteLimit: number$3().nullish(),
80456
80500
  sessionId: zSessionId
80457
80501
  });
80502
+ const zDeleteSessionRequest = object$1({
80503
+ _meta: record(string$2(), unknown()).nullish(),
80504
+ sessionId: zSessionId
80505
+ });
80458
80506
  const zDidCloseDocumentNotification = object$1({
80459
80507
  _meta: record(string$2(), unknown()).nullish(),
80460
80508
  sessionId: zSessionId,
@@ -80604,6 +80652,7 @@ Task description:
80604
80652
  _meta: record(string$2(), unknown()).nullish(),
80605
80653
  additionalDirectories: zSessionAdditionalDirectoriesCapabilities.nullish(),
80606
80654
  close: zSessionCloseCapabilities.nullish(),
80655
+ delete: zSessionDeleteCapabilities.nullish(),
80607
80656
  fork: zSessionForkCapabilities.nullish(),
80608
80657
  list: zSessionListCapabilities.nullish(),
80609
80658
  resume: zSessionResumeCapabilities.nullish()
@@ -80746,6 +80795,7 @@ Task description:
80746
80795
  zDidFocusDocumentNotification,
80747
80796
  zAcceptNesNotification,
80748
80797
  zRejectNesNotification,
80798
+ zMessageMcpNotification,
80749
80799
  zExtNotification
80750
80800
  ]).nullish()
80751
80801
  });
@@ -80779,6 +80829,7 @@ Task description:
80779
80829
  auth: zAgentAuthCapabilities.optional().default({}),
80780
80830
  loadSession: boolean().optional().default(false),
80781
80831
  mcpCapabilities: zMcpCapabilities.optional().default({
80832
+ acp: false,
80782
80833
  http: false,
80783
80834
  sse: false
80784
80835
  }),
@@ -80798,6 +80849,7 @@ Task description:
80798
80849
  auth: {},
80799
80850
  loadSession: false,
80800
80851
  mcpCapabilities: {
80852
+ acp: false,
80801
80853
  http: false,
80802
80854
  sse: false
80803
80855
  },
@@ -81037,6 +81089,7 @@ Task description:
81037
81089
  zNewSessionResponse,
81038
81090
  zLoadSessionResponse,
81039
81091
  zListSessionsResponse,
81092
+ zDeleteSessionResponse,
81040
81093
  zForkSessionResponse,
81041
81094
  zResumeSessionResponse,
81042
81095
  zCloseSessionResponse,
@@ -81047,7 +81100,8 @@ Task description:
81047
81100
  zStartNesResponse,
81048
81101
  zSuggestNesResponse,
81049
81102
  zCloseNesResponse,
81050
- zExtResponse
81103
+ zExtResponse,
81104
+ zMessageMcpResponse
81051
81105
  ])
81052
81106
  }),
81053
81107
  object$1({
@@ -81106,6 +81160,7 @@ Task description:
81106
81160
  params: union$3([
81107
81161
  zSessionNotification,
81108
81162
  zCompleteElicitationNotification,
81163
+ zMessageMcpNotification,
81109
81164
  zExtNotification
81110
81165
  ]).nullish()
81111
81166
  });
@@ -81144,6 +81199,7 @@ Task description:
81144
81199
  zNewSessionRequest,
81145
81200
  zLoadSessionRequest,
81146
81201
  zListSessionsRequest,
81202
+ zDeleteSessionRequest,
81147
81203
  zForkSessionRequest,
81148
81204
  zResumeSessionRequest,
81149
81205
  zCloseSessionRequest,
@@ -81154,6 +81210,7 @@ Task description:
81154
81210
  zStartNesRequest,
81155
81211
  zSuggestNesRequest,
81156
81212
  zCloseNesRequest,
81213
+ zMessageMcpRequest,
81157
81214
  zExtRequest
81158
81215
  ]).nullish()
81159
81216
  });
@@ -81176,6 +81233,9 @@ Task description:
81176
81233
  zWaitForTerminalExitRequest,
81177
81234
  zKillTerminalRequest,
81178
81235
  zCreateElicitationRequest,
81236
+ zConnectMcpRequest,
81237
+ zMessageMcpRequest,
81238
+ zDisconnectMcpRequest,
81179
81239
  zExtRequest
81180
81240
  ]).nullish()
81181
81241
  });
@@ -81195,7 +81255,10 @@ Task description:
81195
81255
  zWaitForTerminalExitResponse,
81196
81256
  zKillTerminalResponse,
81197
81257
  zCreateElicitationResponse,
81198
- zExtResponse
81258
+ zConnectMcpResponse,
81259
+ zDisconnectMcpResponse,
81260
+ zExtResponse,
81261
+ zMessageMcpResponse
81199
81262
  ])
81200
81263
  }),
81201
81264
  object$1({
@@ -92691,7 +92754,7 @@ ${val.stack}`;
92691
92754
  console.info(prefix, ...args2);
92692
92755
  };
92693
92756
  };
92694
- var ProtocolError$2 = class ProtocolError extends Error {
92757
+ var ProtocolError$1 = class ProtocolError extends Error {
92695
92758
  status;
92696
92759
  detail;
92697
92760
  constructor(message, status, detail) {
@@ -92700,7 +92763,7 @@ ${val.stack}`;
92700
92763
  this.detail = detail;
92701
92764
  }
92702
92765
  };
92703
- var TimeoutError$2 = class TimeoutError extends Error {
92766
+ var TimeoutError$1 = class TimeoutError extends Error {
92704
92767
  phase;
92705
92768
  timeoutMs;
92706
92769
  constructor(phase, timeoutMs) {
@@ -92709,11 +92772,11 @@ ${val.stack}`;
92709
92772
  this.timeoutMs = timeoutMs;
92710
92773
  }
92711
92774
  };
92712
- function isAbortError$1(error2) {
92775
+ function isAbortError(error2) {
92713
92776
  return error2 instanceof DOMException ? error2.name === "AbortError" : typeof error2 === "object" && error2 != null && "name" in error2 && error2.name === "AbortError";
92714
92777
  }
92715
- async function responseToStreamError$1(response, context2) {
92716
- const bodyText = await safeReadBodyText$1(response);
92778
+ async function responseToStreamError(response, context2) {
92779
+ const bodyText = await safeReadBodyText(response);
92717
92780
  const message = bodyText.length > 0 ? `${context2} failed with status ${response.status}: ${bodyText}` : `${context2} failed with status ${response.status}`;
92718
92781
  const presentBody = bodyText.length > 0 ? bodyText : void 0;
92719
92782
  switch (response.status) {
@@ -92737,7 +92800,7 @@ ${val.stack}`;
92737
92800
  status: 403,
92738
92801
  message,
92739
92802
  bodyText: presentBody,
92740
- detail: producerEpochDetail$1(response)
92803
+ detail: producerEpochDetail(response)
92741
92804
  };
92742
92805
  case 404:
92743
92806
  return {
@@ -92752,7 +92815,7 @@ ${val.stack}`;
92752
92815
  status: 409,
92753
92816
  message,
92754
92817
  bodyText: presentBody,
92755
- detail: conflictDetail$1(response, bodyText)
92818
+ detail: conflictDetail(response, bodyText)
92756
92819
  };
92757
92820
  case 410:
92758
92821
  return {
@@ -92774,7 +92837,7 @@ ${val.stack}`;
92774
92837
  message,
92775
92838
  status: response.status,
92776
92839
  statusText: response.statusText,
92777
- headers: headersToObject$1$1(response.headers),
92840
+ headers: headersToObject$1(response.headers),
92778
92841
  bodyText: bodyText.length > 0 ? bodyText : void 0,
92779
92842
  cause: {
92780
92843
  type: "http_response",
@@ -92784,13 +92847,13 @@ ${val.stack}`;
92784
92847
  };
92785
92848
  }
92786
92849
  }
92787
- function thrownToStreamError$1(error2) {
92788
- if (error2 instanceof TimeoutError$2) return {
92850
+ function thrownToStreamError(error2) {
92851
+ if (error2 instanceof TimeoutError$1) return {
92789
92852
  code: "timeout",
92790
92853
  phase: error2.phase,
92791
92854
  message: error2.message
92792
92855
  };
92793
- if (error2 instanceof ProtocolError$2) return {
92856
+ if (error2 instanceof ProtocolError$1) return {
92794
92857
  code: "protocol_error",
92795
92858
  message: error2.message,
92796
92859
  status: error2.status,
@@ -92812,10 +92875,10 @@ ${val.stack}`;
92812
92875
  cause: error2
92813
92876
  };
92814
92877
  }
92815
- function isRetryableLiveError$1(error2) {
92816
- return isRetryableStreamError$1(error2);
92878
+ function isRetryableLiveError(error2) {
92879
+ return isRetryableStreamError(error2);
92817
92880
  }
92818
- function producerEpochDetail$1(response) {
92881
+ function producerEpochDetail(response) {
92819
92882
  const value = response.headers.get("Producer-Epoch");
92820
92883
  if (value == null) return;
92821
92884
  const parsed = Number.parseInt(value, 10);
@@ -92827,16 +92890,16 @@ ${val.stack}`;
92827
92890
  serverEpoch: parsed
92828
92891
  };
92829
92892
  }
92830
- function conflictDetail$1(response, bodyText) {
92831
- if (isTrueHeader$1(response.headers.get("Stream-Closed"))) return {
92893
+ function conflictDetail(response, bodyText) {
92894
+ if (isTrueHeader(response.headers.get("Stream-Closed"))) return {
92832
92895
  kind: "stream_closed",
92833
92896
  nextOffset: response.headers.get("Stream-Next-Offset") ?? void 0
92834
92897
  };
92835
- const expectedSeq = parseOptionalInteger$1$1(response.headers.get("Producer-Expected-Seq"));
92898
+ const expectedSeq = parseOptionalInteger$1(response.headers.get("Producer-Expected-Seq"));
92836
92899
  if (expectedSeq != null) return {
92837
92900
  kind: "producer_seq_gap",
92838
92901
  expectedSeq,
92839
- receivedSeq: parseOptionalInteger$1$1(response.headers.get("Producer-Received-Seq")) ?? void 0
92902
+ receivedSeq: parseOptionalInteger$1(response.headers.get("Producer-Received-Seq")) ?? void 0
92840
92903
  };
92841
92904
  const normalized = bodyText.toLowerCase();
92842
92905
  if (normalized.includes("content type")) return {
@@ -92849,39 +92912,39 @@ ${val.stack}`;
92849
92912
  kind: "other"
92850
92913
  };
92851
92914
  }
92852
- function parseOptionalInteger$1$1(value) {
92915
+ function parseOptionalInteger$1(value) {
92853
92916
  if (value == null) return null;
92854
92917
  const parsed = Number.parseInt(value, 10);
92855
92918
  if (!Number.isFinite(parsed) || parsed < 0) return null;
92856
92919
  return parsed;
92857
92920
  }
92858
- function isTrueHeader$1(value) {
92921
+ function isTrueHeader(value) {
92859
92922
  return value?.trim().toLowerCase() === "true";
92860
92923
  }
92861
- function headersToObject$1$1(headers) {
92924
+ function headersToObject$1(headers) {
92862
92925
  const result = {};
92863
92926
  headers.forEach((value, name2) => {
92864
92927
  result[name2] = value;
92865
92928
  });
92866
92929
  return result;
92867
92930
  }
92868
- async function safeReadBodyText$1(response) {
92931
+ async function safeReadBodyText(response) {
92869
92932
  try {
92870
92933
  return await response.text();
92871
92934
  } catch {
92872
92935
  return "";
92873
92936
  }
92874
92937
  }
92875
- function isRetryableStreamError$1(error2) {
92938
+ function isRetryableStreamError(error2) {
92876
92939
  return error2.code === "network_error" || error2.code === "timeout";
92877
92940
  }
92878
- const DEFAULT_TIMEOUT_CONFIG$1 = {
92941
+ const DEFAULT_TIMEOUT_CONFIG = {
92879
92942
  connectTimeoutMs: 1e4,
92880
92943
  pollTimeoutMs: 3e4
92881
92944
  };
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;
92945
+ function normalizeTimeoutConfig(value) {
92946
+ const connectTimeoutMs = value?.connectTimeoutMs ?? DEFAULT_TIMEOUT_CONFIG.connectTimeoutMs;
92947
+ const pollTimeoutMs = value?.pollTimeoutMs ?? DEFAULT_TIMEOUT_CONFIG.pollTimeoutMs;
92885
92948
  if (!Number.isFinite(connectTimeoutMs) || connectTimeoutMs < 0) throw new Error("timeout.connectTimeoutMs must be a non-negative finite number");
92886
92949
  if (!Number.isFinite(pollTimeoutMs) || pollTimeoutMs < 0) throw new Error("timeout.pollTimeoutMs must be a non-negative finite number");
92887
92950
  return {
@@ -92889,7 +92952,7 @@ ${val.stack}`;
92889
92952
  pollTimeoutMs: Math.floor(pollTimeoutMs)
92890
92953
  };
92891
92954
  }
92892
- function mergeAbortSignals$1$1(...signals2) {
92955
+ function mergeAbortSignals$1(...signals2) {
92893
92956
  const active2 = signals2.filter((signal) => signal != null);
92894
92957
  if (active2.length === 0) return;
92895
92958
  if (active2.length === 1) return active2[0];
@@ -92908,12 +92971,12 @@ ${val.stack}`;
92908
92971
  }
92909
92972
  return controller.signal;
92910
92973
  }
92911
- async function fetchWithTimeout$1(fetchImpl, input2, init2, timeoutMs, phase) {
92974
+ async function fetchWithTimeout(fetchImpl, input2, init2, timeoutMs, phase) {
92912
92975
  if (!(timeoutMs > 0)) return await fetchImpl(input2, init2);
92913
92976
  const controller = new AbortController();
92914
- const signal = mergeAbortSignals$1$1(init2.signal, controller.signal);
92977
+ const signal = mergeAbortSignals$1(init2.signal, controller.signal);
92915
92978
  const timer2 = setTimeout(() => {
92916
- controller.abort(new TimeoutError$2(phase, timeoutMs));
92979
+ controller.abort(new TimeoutError$1(phase, timeoutMs));
92917
92980
  }, timeoutMs);
92918
92981
  try {
92919
92982
  return await fetchImpl(input2, {
@@ -92921,25 +92984,25 @@ ${val.stack}`;
92921
92984
  signal
92922
92985
  });
92923
92986
  } catch (error2) {
92924
- if (controller.signal.aborted && controller.signal.reason instanceof TimeoutError$2) throw controller.signal.reason;
92987
+ if (controller.signal.aborted && controller.signal.reason instanceof TimeoutError$1) throw controller.signal.reason;
92925
92988
  throw error2;
92926
92989
  } finally {
92927
92990
  clearTimeout(timer2);
92928
92991
  }
92929
92992
  }
92930
- var AuthorizedHttpClient$1 = class AuthorizedHttpClient {
92993
+ var AuthorizedHttpClient = class {
92931
92994
  fetchImpl;
92932
92995
  authProvider;
92933
92996
  authRefreshInFlight;
92934
92997
  constructor(options) {
92935
92998
  this.fetchImpl = options.fetchImpl;
92936
- this.authProvider = normalizeAuthProvider$2(options.auth);
92999
+ this.authProvider = normalizeAuthProvider$1(options.auth);
92937
93000
  }
92938
93001
  async fetchAuthorized(input2, init2, timeoutMs, phase, options) {
92939
93002
  const firstToken = await this.resolveToken({
92940
93003
  reason: "request"
92941
93004
  });
92942
- const firstResponse = await fetchWithTimeout$1(this.fetchImpl, input2, {
93005
+ const firstResponse = await fetchWithTimeout(this.fetchImpl, input2, {
92943
93006
  ...init2,
92944
93007
  headers: this.attachAuthorization(init2.headers, firstToken)
92945
93008
  }, timeoutMs, phase);
@@ -92948,7 +93011,7 @@ ${val.stack}`;
92948
93011
  await firstResponse.body?.cancel().catch(() => {
92949
93012
  });
92950
93013
  const refreshedToken = await this.refreshTokenAfterFailure(firstResponse.status, firstToken);
92951
- return await fetchWithTimeout$1(this.fetchImpl, input2, {
93014
+ return await fetchWithTimeout(this.fetchImpl, input2, {
92952
93015
  ...init2,
92953
93016
  headers: this.attachAuthorization(init2.headers, refreshedToken)
92954
93017
  }, timeoutMs, phase);
@@ -92978,7 +93041,7 @@ ${val.stack}`;
92978
93041
  return headers;
92979
93042
  }
92980
93043
  };
92981
- function normalizeAuthProvider$2(auth) {
93044
+ function normalizeAuthProvider$1(auth) {
92982
93045
  if (auth == null) return;
92983
93046
  if (typeof auth === "string") {
92984
93047
  const token2 = auth.trim();
@@ -92989,20 +93052,20 @@ ${val.stack}`;
92989
93052
  return token2.length === 0 ? void 0 : token2;
92990
93053
  };
92991
93054
  }
92992
- function decodeMultipartMixed$1(boundary, data) {
93055
+ function decodeMultipartMixed(boundary, data) {
92993
93056
  const delimiter2 = new TextEncoder().encode(`--${boundary}`);
92994
93057
  const closeDelimiter = new TextEncoder().encode(`--${boundary}--`);
92995
93058
  const crlfCrlf = new TextEncoder().encode("\r\n\r\n");
92996
93059
  const parts2 = [];
92997
93060
  let pos = 0;
92998
- const firstDelimPos = indexOf$1(data, delimiter2, pos);
93061
+ const firstDelimPos = indexOf(data, delimiter2, pos);
92999
93062
  if (firstDelimPos < 0) return parts2;
93000
93063
  pos = firstDelimPos + delimiter2.byteLength;
93001
93064
  if (pos < data.byteLength && data[pos] === 13) pos += 1;
93002
93065
  if (pos < data.byteLength && data[pos] === 10) pos += 1;
93003
93066
  while (pos < data.byteLength) {
93004
- if (startsWith$1(data.subarray(pos), closeDelimiter.subarray(delimiter2.byteLength))) break;
93005
- const headerEnd = indexOf$1(data, crlfCrlf, pos);
93067
+ if (startsWith(data.subarray(pos), closeDelimiter.subarray(delimiter2.byteLength))) break;
93068
+ const headerEnd = indexOf(data, crlfCrlf, pos);
93006
93069
  if (headerEnd < 0) break;
93007
93070
  const headerBytes = data.subarray(pos, headerEnd);
93008
93071
  const headerText = new TextDecoder().decode(headerBytes);
@@ -93014,7 +93077,7 @@ ${val.stack}`;
93014
93077
  contentType = line3.slice(colon + 1).trim();
93015
93078
  }
93016
93079
  const bodyStart = headerEnd + crlfCrlf.byteLength;
93017
- const nextDelimiter = indexOf$1(data, delimiter2, bodyStart);
93080
+ const nextDelimiter = indexOf(data, delimiter2, bodyStart);
93018
93081
  if (nextDelimiter < 0) {
93019
93082
  parts2.push({
93020
93083
  contentType,
@@ -93035,22 +93098,22 @@ ${val.stack}`;
93035
93098
  }
93036
93099
  return parts2;
93037
93100
  }
93038
- function extractBoundary$1(contentType) {
93101
+ function extractBoundary(contentType) {
93039
93102
  return /boundary=("?)([^";,\s]+)\1/i.exec(contentType)?.[2] ?? null;
93040
93103
  }
93041
- function indexOf$1(haystack, needle, from2) {
93104
+ function indexOf(haystack, needle, from2) {
93042
93105
  outer: for (let i2 = from2; i2 <= haystack.byteLength - needle.byteLength; i2 += 1) {
93043
93106
  for (let j = 0; j < needle.byteLength; j += 1) if (haystack[i2 + j] !== needle[j]) continue outer;
93044
93107
  return i2;
93045
93108
  }
93046
93109
  return -1;
93047
93110
  }
93048
- function startsWith$1(data, prefix) {
93111
+ function startsWith(data, prefix) {
93049
93112
  if (data.byteLength < prefix.byteLength) return false;
93050
93113
  for (let i2 = 0; i2 < prefix.byteLength; i2 += 1) if (data[i2] !== prefix[i2]) return false;
93051
93114
  return true;
93052
93115
  }
93053
- const DEFAULT_RETRY_CONFIG$1 = {
93116
+ const DEFAULT_RETRY_CONFIG = {
93054
93117
  delays: [
93055
93118
  0,
93056
93119
  500,
@@ -93063,16 +93126,16 @@ ${val.stack}`;
93063
93126
  jitterFraction: 0.2,
93064
93127
  maxAttempts: 5
93065
93128
  };
93066
- function normalizeRetryConfig$1(value) {
93067
- const delays = value?.delays ?? DEFAULT_RETRY_CONFIG$1.delays;
93129
+ function normalizeRetryConfig(value) {
93130
+ const delays = value?.delays ?? DEFAULT_RETRY_CONFIG.delays;
93068
93131
  if (delays.length === 0) throw new Error("retry.delays must contain at least one entry");
93069
93132
  const normalizedDelays = delays.map((delay2) => {
93070
93133
  if (!Number.isFinite(delay2) || delay2 < 0) throw new Error("retry.delays must contain non-negative finite numbers");
93071
93134
  return Math.floor(delay2);
93072
93135
  });
93073
- const jitterFraction = value?.jitterFraction ?? DEFAULT_RETRY_CONFIG$1.jitterFraction;
93136
+ const jitterFraction = value?.jitterFraction ?? DEFAULT_RETRY_CONFIG.jitterFraction;
93074
93137
  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;
93138
+ const maxAttempts = value?.maxAttempts ?? DEFAULT_RETRY_CONFIG.maxAttempts;
93076
93139
  if (!Number.isInteger(maxAttempts) || maxAttempts < 0) throw new Error("retry.maxAttempts must be a non-negative integer");
93077
93140
  return {
93078
93141
  delays: normalizedDelays,
@@ -93080,16 +93143,16 @@ ${val.stack}`;
93080
93143
  maxAttempts
93081
93144
  };
93082
93145
  }
93083
- function applyJitter$2(baseMs, fraction) {
93146
+ function applyJitter$1(baseMs, fraction) {
93084
93147
  if (baseMs === 0) return 0;
93085
93148
  const jitter = baseMs * fraction * (2 * Math.random() - 1);
93086
93149
  return Math.max(0, Math.round(baseMs + jitter));
93087
93150
  }
93088
- function computeRetryDelay$2(attempt, config2 = DEFAULT_RETRY_CONFIG$1) {
93151
+ function computeRetryDelay$1(attempt, config2 = DEFAULT_RETRY_CONFIG) {
93089
93152
  const index2 = Math.min(attempt, config2.delays.length - 1);
93090
- return applyJitter$2(config2.delays[index2] ?? 0, config2.jitterFraction);
93153
+ return applyJitter$1(config2.delays[index2] ?? 0, config2.jitterFraction);
93091
93154
  }
93092
- async function sleep$3(delayMs, signal) {
93155
+ async function sleep$2(delayMs, signal) {
93093
93156
  if (delayMs <= 0) {
93094
93157
  if (signal?.aborted === true) throw signal.reason;
93095
93158
  return;
@@ -93118,21 +93181,21 @@ ${val.stack}`;
93118
93181
  }
93119
93182
  });
93120
93183
  }
93121
- function getRequiredHeader$1(headers, name2, context2) {
93184
+ function getRequiredHeader(headers, name2, context2) {
93122
93185
  const value = headers.get(name2);
93123
93186
  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)}`);
93187
+ 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
93188
  }
93126
- function hasTrueHeader$1(headers, name2) {
93189
+ function hasTrueHeader(headers, name2) {
93127
93190
  return headers.get(name2)?.trim().toLowerCase() === "true";
93128
93191
  }
93129
- function parseOptionalInteger$2(value) {
93192
+ function parseOptionalInteger(value) {
93130
93193
  if (value == null) return null;
93131
93194
  const parsed = Number.parseInt(value, 10);
93132
93195
  if (!Number.isFinite(parsed) || parsed < 0) return null;
93133
93196
  return parsed;
93134
93197
  }
93135
- function visibleHeaderNames$1(headers) {
93198
+ function visibleHeaderNames(headers) {
93136
93199
  const names2 = [];
93137
93200
  headers.forEach((_value, name2) => {
93138
93201
  names2.push(name2);
@@ -93141,60 +93204,60 @@ ${val.stack}`;
93141
93204
  names2.sort();
93142
93205
  return names2.join(", ");
93143
93206
  }
93144
- const encoder$1 = new TextEncoder();
93145
- const decoder$1 = new TextDecoder();
93146
- function createStreamPart$1(contentType, body) {
93207
+ const encoder = new TextEncoder();
93208
+ const decoder = new TextDecoder();
93209
+ function createStreamPart(contentType, body) {
93147
93210
  return {
93148
93211
  contentType,
93149
93212
  body,
93150
93213
  text() {
93151
- return decoder$1.decode(body);
93214
+ return decoder.decode(body);
93152
93215
  },
93153
93216
  json() {
93154
- return JSON.parse(decoder$1.decode(body));
93217
+ return JSON.parse(decoder.decode(body));
93155
93218
  }
93156
93219
  };
93157
93220
  }
93158
- function normalizeStreamPartLike$1(input2) {
93221
+ function normalizeStreamPartLike(input2) {
93159
93222
  return {
93160
- contentType: normalizeContentType$1(input2.contentType),
93161
- body: normalizeStreamBody$1(input2.body)
93223
+ contentType: normalizeContentType(input2.contentType),
93224
+ body: normalizeStreamBody(input2.body)
93162
93225
  };
93163
93226
  }
93164
- function normalizeContentType$1(contentType) {
93227
+ function normalizeContentType(contentType) {
93165
93228
  const normalized = contentType.trim();
93166
93229
  if (normalized.length === 0) throw new Error("contentType must be a non-empty string");
93167
93230
  return normalized;
93168
93231
  }
93169
- function normalizeOptionalContentType$1(contentType) {
93232
+ function normalizeOptionalContentType(contentType) {
93170
93233
  if (contentType == null) return;
93171
- return normalizeContentType$1(contentType);
93234
+ return normalizeContentType(contentType);
93172
93235
  }
93173
- function normalizeStreamBody$1(body) {
93174
- if (typeof body === "string") return encoder$1.encode(body);
93236
+ function normalizeStreamBody(body) {
93237
+ if (typeof body === "string") return encoder.encode(body);
93175
93238
  if (body instanceof Uint8Array) return body.slice();
93176
93239
  if (body instanceof ArrayBuffer) return new Uint8Array(body.slice(0));
93177
93240
  if (ArrayBuffer.isView(body)) return new Uint8Array(body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength));
93178
93241
  throw new Error("unsupported stream body type");
93179
93242
  }
93180
- function toRequestBody$1(bytes) {
93243
+ function toRequestBody(bytes) {
93181
93244
  return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
93182
93245
  }
93183
- function isSseUnsupportedErrorText$2(message) {
93246
+ function isSseUnsupportedErrorText$1(message) {
93184
93247
  const normalized = message.trim().toLowerCase();
93185
93248
  if (normalized.length === 0) return false;
93186
93249
  const mentionsSse = normalized.includes("sse") || normalized.includes("text/event-stream");
93187
93250
  const mentionsCompatibility = normalized.includes("unsupported") || normalized.includes("not support") || normalized.includes("incompatible") || normalized.includes("content type");
93188
93251
  return mentionsSse && mentionsCompatibility;
93189
93252
  }
93190
- function parseSseControlData$2(data) {
93253
+ function parseSseControlData$1(data) {
93191
93254
  let parsed;
93192
93255
  try {
93193
93256
  parsed = JSON.parse(data);
93194
93257
  } catch {
93195
- throw new ProtocolError$2("invalid sse control event JSON");
93258
+ throw new ProtocolError$1("invalid sse control event JSON");
93196
93259
  }
93197
- if (typeof parsed !== "object" || parsed == null || typeof parsed.streamNextOffset !== "string") throw new ProtocolError$2("sse control event missing streamNextOffset");
93260
+ if (typeof parsed !== "object" || parsed == null || typeof parsed.streamNextOffset !== "string") throw new ProtocolError$1("sse control event missing streamNextOffset");
93198
93261
  const streamClosed = parsed.streamClosed === true;
93199
93262
  const streamCursor = typeof parsed.streamCursor === "string" ? parsed.streamCursor : void 0;
93200
93263
  return {
@@ -93204,13 +93267,13 @@ ${val.stack}`;
93204
93267
  streamCursor
93205
93268
  };
93206
93269
  }
93207
- function decodeSsePayload$1(data, dataEncoding) {
93270
+ function decodeSsePayload(data, dataEncoding) {
93208
93271
  const normalizedEncoding = dataEncoding?.trim().toLowerCase();
93209
93272
  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, ""));
93273
+ if (normalizedEncoding !== "base64") throw new ProtocolError$1(`unsupported stream-sse-data-encoding '${dataEncoding}'`);
93274
+ return decodeBase64Bytes$1(data.replace(/[\r\n]/g, ""));
93212
93275
  }
93213
- async function* readSseEvents$1(stream2, options = {}) {
93276
+ async function* readSseEvents(stream2, options = {}) {
93214
93277
  const reader2 = stream2.getReader();
93215
93278
  const decoder2 = new TextDecoder();
93216
93279
  let pendingText = "";
@@ -93296,7 +93359,7 @@ ${val.stack}`;
93296
93359
  }
93297
93360
  }
93298
93361
  }
93299
- function decodeBase64Bytes$2(encoded) {
93362
+ function decodeBase64Bytes$1(encoded) {
93300
93363
  if (typeof Buffer !== "undefined") return new Uint8Array(Buffer.from(encoded, "base64"));
93301
93364
  if (typeof atob === "function") {
93302
93365
  const binary2 = atob(encoded);
@@ -93306,7 +93369,7 @@ ${val.stack}`;
93306
93369
  }
93307
93370
  throw new Error("base64 decoding is unavailable");
93308
93371
  }
93309
- var StreamsClient$1 = class StreamsClient {
93372
+ var StreamsClient = class {
93310
93373
  streamUrl;
93311
93374
  http;
93312
93375
  defaultHeaders;
@@ -93319,19 +93382,19 @@ ${val.stack}`;
93319
93382
  this.streamUrl = options.url instanceof URL ? new URL(options.url) : new URL(options.url);
93320
93383
  const fetchImpl = options.fetch ?? globalThis.fetch?.bind(globalThis);
93321
93384
  if (typeof fetchImpl !== "function") throw new Error("fetch is unavailable; pass options.fetch explicitly");
93322
- this.http = new AuthorizedHttpClient$1({
93385
+ this.http = new AuthorizedHttpClient({
93323
93386
  fetchImpl,
93324
93387
  auth: options.auth
93325
93388
  });
93326
93389
  this.defaultHeaders = new Headers(options.headers);
93327
- this.retryConfig = normalizeRetryConfig$1(options.retry);
93328
- this.timeoutConfig = normalizeTimeoutConfig$1(options.timeout);
93390
+ this.retryConfig = normalizeRetryConfig(options.retry);
93391
+ this.timeoutConfig = normalizeTimeoutConfig(options.timeout);
93329
93392
  this.onRetry = options.onRetry;
93330
93393
  }
93331
93394
  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;
93395
+ validateCreateInput(input2);
93396
+ const part = input2.part == null ? void 0 : normalizeStreamPartLike(input2.part);
93397
+ const requestedContentType = part?.contentType ?? normalizeOptionalContentType(input2.contentType) ?? void 0;
93335
93398
  try {
93336
93399
  const requestUrl = this.streamEndpoint();
93337
93400
  const headers = this.mergeHeaders(input2.headers);
@@ -93342,14 +93405,14 @@ ${val.stack}`;
93342
93405
  const response = await this.http.fetchAuthorized(requestUrl, {
93343
93406
  method: "PUT",
93344
93407
  headers,
93345
- body: part == null ? void 0 : toRequestBody$1(part.body)
93408
+ body: part == null ? void 0 : toRequestBody(part.body)
93346
93409
  }, this.timeoutConfig.connectTimeoutMs, "connect");
93347
93410
  if (response.status !== 200 && response.status !== 201) return {
93348
93411
  ok: false,
93349
- result: await responseToStreamError$1(response, "create")
93412
+ result: await responseToStreamError(response, "create")
93350
93413
  };
93351
93414
  const contentType = this.resolveContentType(response, "create", requestedContentType ?? "application/octet-stream");
93352
- const nextOffset = getRequiredHeader$1(response.headers, "Stream-Next-Offset", "create");
93415
+ const nextOffset = getRequiredHeader(response.headers, "Stream-Next-Offset", "create");
93353
93416
  this.knownContentType = contentType;
93354
93417
  return {
93355
93418
  ok: true,
@@ -93357,13 +93420,13 @@ ${val.stack}`;
93357
93420
  created: response.status === 201,
93358
93421
  contentType,
93359
93422
  nextOffset,
93360
- closed: hasTrueHeader$1(response.headers, "Stream-Closed")
93423
+ closed: hasTrueHeader(response.headers, "Stream-Closed")
93361
93424
  }, input2, "PUT", requestUrl, response)
93362
93425
  };
93363
93426
  } catch (error2) {
93364
93427
  return {
93365
93428
  ok: false,
93366
- result: thrownToStreamError$1(error2)
93429
+ result: thrownToStreamError(error2)
93367
93430
  };
93368
93431
  }
93369
93432
  }
@@ -93372,7 +93435,8 @@ ${val.stack}`;
93372
93435
  const requestUrl = this.streamEndpoint();
93373
93436
  const response = await this.http.fetchAuthorized(requestUrl, {
93374
93437
  method: "DELETE",
93375
- headers: this.mergeHeaders(input2.headers)
93438
+ headers: this.mergeHeaders(input2.headers),
93439
+ signal: input2.signal
93376
93440
  }, this.timeoutConfig.connectTimeoutMs, "connect");
93377
93441
  if (response.status === 404) return {
93378
93442
  ok: true,
@@ -93382,7 +93446,7 @@ ${val.stack}`;
93382
93446
  };
93383
93447
  if (response.status !== 200 && response.status !== 204) return {
93384
93448
  ok: false,
93385
- result: await responseToStreamError$1(response, "delete")
93449
+ result: await responseToStreamError(response, "delete")
93386
93450
  };
93387
93451
  return {
93388
93452
  ok: true,
@@ -93393,7 +93457,7 @@ ${val.stack}`;
93393
93457
  } catch (error2) {
93394
93458
  return {
93395
93459
  ok: false,
93396
- result: thrownToStreamError$1(error2)
93460
+ result: thrownToStreamError(error2)
93397
93461
  };
93398
93462
  }
93399
93463
  }
@@ -93402,22 +93466,23 @@ ${val.stack}`;
93402
93466
  const requestUrl = this.streamEndpoint();
93403
93467
  const response = await this.http.fetchAuthorized(requestUrl, {
93404
93468
  method: "HEAD",
93405
- headers: this.mergeHeaders(input2.headers)
93469
+ headers: this.mergeHeaders(input2.headers),
93470
+ signal: input2.signal
93406
93471
  }, this.timeoutConfig.connectTimeoutMs, "connect");
93407
93472
  if (!response.ok) return {
93408
93473
  ok: false,
93409
- result: await responseToStreamError$1(response, "head")
93474
+ result: await responseToStreamError(response, "head")
93410
93475
  };
93411
93476
  const contentType = this.resolveContentType(response, "head", this.knownContentType);
93412
- const nextOffset = getRequiredHeader$1(response.headers, "Stream-Next-Offset", "head");
93477
+ const nextOffset = getRequiredHeader(response.headers, "Stream-Next-Offset", "head");
93413
93478
  this.knownContentType = contentType;
93414
93479
  return {
93415
93480
  ok: true,
93416
93481
  result: this.withMeta({
93417
93482
  contentType,
93418
93483
  nextOffset,
93419
- closed: hasTrueHeader$1(response.headers, "Stream-Closed"),
93420
- ttlSeconds: parseOptionalInteger$2(response.headers.get("Stream-TTL")) ?? void 0,
93484
+ closed: hasTrueHeader(response.headers, "Stream-Closed"),
93485
+ ttlSeconds: parseOptionalInteger(response.headers.get("Stream-TTL")) ?? void 0,
93421
93486
  expiresAt: response.headers.get("Stream-Expires-At") ?? void 0,
93422
93487
  snapshotOffset: response.headers.get("Stream-Snapshot-Offset") ?? void 0
93423
93488
  }, input2, "HEAD", requestUrl, response)
@@ -93425,26 +93490,26 @@ ${val.stack}`;
93425
93490
  } catch (error2) {
93426
93491
  return {
93427
93492
  ok: false,
93428
- result: thrownToStreamError$1(error2)
93493
+ result: thrownToStreamError(error2)
93429
93494
  };
93430
93495
  }
93431
93496
  }
93432
93497
  async append(input2) {
93433
- validateAppendInput$1(input2);
93434
- const part = input2.part == null ? void 0 : normalizeStreamPartLike$1(input2.part);
93498
+ validateAppendInput(input2);
93499
+ const part = input2.part == null ? void 0 : normalizeStreamPartLike(input2.part);
93435
93500
  let attempt = 0;
93436
93501
  while (true) try {
93437
93502
  const requestUrl = this.streamEndpoint();
93438
93503
  const response = await this.http.fetchAuthorized(requestUrl, {
93439
93504
  method: "POST",
93440
93505
  headers: this.appendHeaders(input2, part?.contentType),
93441
- body: part == null ? void 0 : toRequestBody$1(part.body)
93506
+ body: part == null ? void 0 : toRequestBody(part.body)
93442
93507
  }, this.timeoutConfig.connectTimeoutMs, "connect", {
93443
93508
  shouldRetryAuthFailure: (nextResponse) => nextResponse.status === 401 || nextResponse.status === 403 && nextResponse.headers.get("Producer-Epoch") == null
93444
93509
  });
93445
93510
  if (response.status !== 200 && response.status !== 204) return {
93446
93511
  ok: false,
93447
- result: await responseToStreamError$1(response, "append")
93512
+ result: await responseToStreamError(response, "append")
93448
93513
  };
93449
93514
  if (part != null) this.knownContentType = part.contentType;
93450
93515
  return {
@@ -93452,12 +93517,12 @@ ${val.stack}`;
93452
93517
  result: this.withMeta(this.parseAppendOutput(response, input2), input2, "POST", requestUrl, response)
93453
93518
  };
93454
93519
  } catch (error2) {
93455
- const result = thrownToStreamError$1(error2);
93456
- if (input2.producer == null || !isAppendRetryable$1(result) || attempt >= this.retryConfig.maxAttempts) return {
93520
+ const result = thrownToStreamError(error2);
93521
+ if (input2.producer == null || !isAppendRetryable(result) || attempt >= this.retryConfig.maxAttempts) return {
93457
93522
  ok: false,
93458
93523
  result
93459
93524
  };
93460
- const delay2 = computeRetryDelay$2(attempt, this.retryConfig);
93525
+ const delay2 = computeRetryDelay$1(attempt, this.retryConfig);
93461
93526
  attempt += 1;
93462
93527
  this.onRetry?.({
93463
93528
  operation: "append",
@@ -93466,7 +93531,7 @@ ${val.stack}`;
93466
93531
  delayMs: delay2,
93467
93532
  maxAttempts: this.retryConfig.maxAttempts
93468
93533
  });
93469
- await sleep$3(delay2);
93534
+ await sleep$2(delay2);
93470
93535
  }
93471
93536
  }
93472
93537
  async close(input2 = {}) {
@@ -93501,7 +93566,7 @@ ${val.stack}`;
93501
93566
  };
93502
93567
  }
93503
93568
  async readOnce(input2 = {}) {
93504
- validateReadOnceInput$1(input2);
93569
+ validateReadOnceInput(input2);
93505
93570
  const requestOffset = input2.offset ?? "-1";
93506
93571
  try {
93507
93572
  const requestUrl = this.readEndpoint({
@@ -93518,12 +93583,12 @@ ${val.stack}`;
93518
93583
  }, timeoutMs, phase);
93519
93584
  if (!response.ok) return {
93520
93585
  ok: false,
93521
- result: await responseToStreamError$1(response, "read once")
93586
+ result: await responseToStreamError(response, "read once")
93522
93587
  };
93523
93588
  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");
93589
+ const nextOffset = getRequiredHeader(response.headers, "Stream-Next-Offset", "read once");
93590
+ if (!hasTrueHeader(response.headers, "Stream-Up-To-Date")) throw new ProtocolError$1("long-poll 204 response missing Stream-Up-To-Date: true");
93591
+ const closed = hasTrueHeader(response.headers, "Stream-Closed");
93527
93592
  const cursor = response.headers.get("Stream-Cursor") ?? void 0;
93528
93593
  return {
93529
93594
  ok: true,
@@ -93549,7 +93614,7 @@ ${val.stack}`;
93549
93614
  } catch (error2) {
93550
93615
  return {
93551
93616
  ok: false,
93552
- result: thrownToStreamError$1(error2)
93617
+ result: thrownToStreamError(error2)
93553
93618
  };
93554
93619
  }
93555
93620
  }
@@ -93558,28 +93623,29 @@ ${val.stack}`;
93558
93623
  const requestUrl = this.subresourceEndpoint("/bootstrap");
93559
93624
  const response = await this.http.fetchAuthorized(requestUrl, {
93560
93625
  method: "GET",
93561
- headers: this.mergeHeaders(input2.headers)
93626
+ headers: this.mergeHeaders(input2.headers),
93627
+ signal: input2.signal
93562
93628
  }, this.timeoutConfig.connectTimeoutMs, "connect");
93563
93629
  if (!response.ok) return {
93564
93630
  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");
93631
+ result: await responseToStreamError(response, "bootstrap")
93632
+ };
93633
+ const boundary = extractBoundary(response.headers.get("Content-Type") ?? "");
93634
+ if (boundary == null) throw new ProtocolError$1("bootstrap response must be multipart/mixed");
93635
+ const nextOffset = getRequiredHeader(response.headers, "Stream-Next-Offset", "bootstrap");
93636
+ const snapshotOffset = getRequiredHeader(response.headers, "Stream-Snapshot-Offset", "bootstrap");
93637
+ const parts2 = decodeMultipartMixed(boundary, new Uint8Array(await response.arrayBuffer()));
93638
+ if (parts2.length === 0) throw new ProtocolError$1("bootstrap response must include at least one MIME part");
93573
93639
  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));
93640
+ const snapshot = snapshotOffset === "-1" && first2?.body.byteLength === 0 ? null : createStreamPart(first2.contentType, first2.body);
93641
+ const updates = parts2.slice(1).map((part) => createStreamPart(part.contentType, part.body));
93576
93642
  if (updates.length > 0) this.knownContentType = updates[0].contentType;
93577
93643
  return {
93578
93644
  ok: true,
93579
93645
  result: this.withMeta({
93580
93646
  snapshotOffset,
93581
93647
  nextOffset,
93582
- upToDate: hasTrueHeader$1(response.headers, "Stream-Up-To-Date"),
93648
+ upToDate: hasTrueHeader(response.headers, "Stream-Up-To-Date"),
93583
93649
  cursor: response.headers.get("Stream-Cursor") ?? void 0,
93584
93650
  snapshot,
93585
93651
  updates
@@ -93588,7 +93654,7 @@ ${val.stack}`;
93588
93654
  } catch (error2) {
93589
93655
  return {
93590
93656
  ok: false,
93591
- result: thrownToStreamError$1(error2)
93657
+ result: thrownToStreamError(error2)
93592
93658
  };
93593
93659
  }
93594
93660
  }
@@ -93597,7 +93663,8 @@ ${val.stack}`;
93597
93663
  const requestUrl = this.subresourceEndpoint("/snapshot");
93598
93664
  const response = await this.http.fetchAuthorized(requestUrl, {
93599
93665
  method: "GET",
93600
- headers: this.mergeHeaders(input2.headers)
93666
+ headers: this.mergeHeaders(input2.headers),
93667
+ signal: input2.signal
93601
93668
  }, this.timeoutConfig.connectTimeoutMs, "connect");
93602
93669
  if (response.status === 404) return {
93603
93670
  ok: true,
@@ -93605,7 +93672,7 @@ ${val.stack}`;
93605
93672
  };
93606
93673
  if (!response.ok) return {
93607
93674
  ok: false,
93608
- result: await responseToStreamError$1(response, "read latest snapshot")
93675
+ result: await responseToStreamError(response, "read latest snapshot")
93609
93676
  };
93610
93677
  return {
93611
93678
  ok: true,
@@ -93614,21 +93681,22 @@ ${val.stack}`;
93614
93681
  } catch (error2) {
93615
93682
  return {
93616
93683
  ok: false,
93617
- result: thrownToStreamError$1(error2)
93684
+ result: thrownToStreamError(error2)
93618
93685
  };
93619
93686
  }
93620
93687
  }
93621
93688
  async readSnapshot(offset2, input2 = {}) {
93622
- assertNonEmptyString$1(offset2, "offset");
93689
+ assertNonEmptyString(offset2, "offset");
93623
93690
  try {
93624
93691
  const requestUrl = this.subresourceEndpoint(`/snapshot/${encodeURIComponent(offset2)}`);
93625
93692
  const response = await this.http.fetchAuthorized(requestUrl, {
93626
93693
  method: "GET",
93627
- headers: this.mergeHeaders(input2.headers)
93694
+ headers: this.mergeHeaders(input2.headers),
93695
+ signal: input2.signal
93628
93696
  }, this.timeoutConfig.connectTimeoutMs, "connect");
93629
93697
  if (!response.ok) return {
93630
93698
  ok: false,
93631
- result: await responseToStreamError$1(response, "read snapshot")
93699
+ result: await responseToStreamError(response, "read snapshot")
93632
93700
  };
93633
93701
  return {
93634
93702
  ok: true,
@@ -93637,13 +93705,13 @@ ${val.stack}`;
93637
93705
  } catch (error2) {
93638
93706
  return {
93639
93707
  ok: false,
93640
- result: thrownToStreamError$1(error2)
93708
+ result: thrownToStreamError(error2)
93641
93709
  };
93642
93710
  }
93643
93711
  }
93644
93712
  async putSnapshot(input2) {
93645
- assertNonEmptyString$1(input2.offset, "offset");
93646
- const part = normalizeStreamPartLike$1(input2.part);
93713
+ assertNonEmptyString(input2.offset, "offset");
93714
+ const part = normalizeStreamPartLike(input2.part);
93647
93715
  try {
93648
93716
  const requestUrl = this.subresourceEndpoint(`/snapshot/${encodeURIComponent(input2.offset)}`);
93649
93717
  const response = await this.http.fetchAuthorized(requestUrl, {
@@ -93651,11 +93719,11 @@ ${val.stack}`;
93651
93719
  headers: this.mergeHeaders(input2.headers, {
93652
93720
  "Content-Type": part.contentType
93653
93721
  }),
93654
- body: toRequestBody$1(part.body)
93722
+ body: toRequestBody(part.body)
93655
93723
  }, this.timeoutConfig.connectTimeoutMs, "connect");
93656
93724
  if (response.status !== 200 && response.status !== 204) return {
93657
93725
  ok: false,
93658
- result: await responseToStreamError$1(response, "put snapshot")
93726
+ result: await responseToStreamError(response, "put snapshot")
93659
93727
  };
93660
93728
  return {
93661
93729
  ok: true,
@@ -93667,17 +93735,18 @@ ${val.stack}`;
93667
93735
  } catch (error2) {
93668
93736
  return {
93669
93737
  ok: false,
93670
- result: thrownToStreamError$1(error2)
93738
+ result: thrownToStreamError(error2)
93671
93739
  };
93672
93740
  }
93673
93741
  }
93674
93742
  async deleteSnapshot(offset2, input2 = {}) {
93675
- assertNonEmptyString$1(offset2, "offset");
93743
+ assertNonEmptyString(offset2, "offset");
93676
93744
  try {
93677
93745
  const requestUrl = this.subresourceEndpoint(`/snapshot/${encodeURIComponent(offset2)}`);
93678
93746
  const response = await this.http.fetchAuthorized(requestUrl, {
93679
93747
  method: "DELETE",
93680
- headers: this.mergeHeaders(input2.headers)
93748
+ headers: this.mergeHeaders(input2.headers),
93749
+ signal: input2.signal
93681
93750
  }, this.timeoutConfig.connectTimeoutMs, "connect");
93682
93751
  if (response.status === 404) return {
93683
93752
  ok: true,
@@ -93687,7 +93756,7 @@ ${val.stack}`;
93687
93756
  };
93688
93757
  if (response.status !== 200 && response.status !== 204) return {
93689
93758
  ok: false,
93690
- result: await responseToStreamError$1(response, "delete snapshot")
93759
+ result: await responseToStreamError(response, "delete snapshot")
93691
93760
  };
93692
93761
  return {
93693
93762
  ok: true,
@@ -93698,19 +93767,19 @@ ${val.stack}`;
93698
93767
  } catch (error2) {
93699
93768
  return {
93700
93769
  ok: false,
93701
- result: thrownToStreamError$1(error2)
93770
+ result: thrownToStreamError(error2)
93702
93771
  };
93703
93772
  }
93704
93773
  }
93705
93774
  async openSseSession(input2) {
93706
- validateOpenSseSessionInput$1(input2);
93775
+ validateOpenSseSessionInput(input2);
93707
93776
  const requestUrl = this.readEndpoint({
93708
93777
  offset: input2.offset,
93709
93778
  cursor: input2.cursor,
93710
93779
  live: "sse"
93711
93780
  });
93712
93781
  const controller = new AbortController();
93713
- const signal = mergeAbortSignals$3(input2.signal, controller.signal);
93782
+ const signal = mergeAbortSignals$2(input2.signal, controller.signal);
93714
93783
  try {
93715
93784
  const response = await this.http.fetchAuthorized(requestUrl, {
93716
93785
  method: "GET",
@@ -93721,11 +93790,11 @@ ${val.stack}`;
93721
93790
  }, this.timeoutConfig.connectTimeoutMs, "connect");
93722
93791
  if (!response.ok) return {
93723
93792
  ok: false,
93724
- result: await responseToStreamError$1(response, "open sse session")
93793
+ result: await responseToStreamError(response, "open sse session")
93725
93794
  };
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);
93795
+ if (response.body == null) throw new ProtocolError$1("sse response missing body");
93796
+ if (!(response.headers.get("Content-Type") ?? "").toLowerCase().includes("text/event-stream")) throw new ProtocolError$1("sse response must use text/event-stream content type");
93797
+ const events = createSessionEvents(response.body, signal, input2.onActivity);
93729
93798
  return {
93730
93799
  ok: true,
93731
93800
  result: {
@@ -93733,7 +93802,7 @@ ${val.stack}`;
93733
93802
  cursor: response.headers.get("Stream-Cursor") ?? void 0,
93734
93803
  dataEncoding: response.headers.get("Stream-SSE-Data-Encoding") ?? void 0,
93735
93804
  events,
93736
- meta: input2.includeMeta === true ? createOperationMeta$1("GET", requestUrl, response) : void 0,
93805
+ meta: input2.includeMeta === true ? createOperationMeta("GET", requestUrl, response) : void 0,
93737
93806
  cancel: async () => {
93738
93807
  controller.abort(new DOMException("Aborted", "AbortError"));
93739
93808
  try {
@@ -93746,12 +93815,12 @@ ${val.stack}`;
93746
93815
  } catch (error2) {
93747
93816
  return {
93748
93817
  ok: false,
93749
- result: thrownToStreamError$1(error2)
93818
+ result: thrownToStreamError(error2)
93750
93819
  };
93751
93820
  }
93752
93821
  }
93753
93822
  live(input2) {
93754
- validateLiveInput$1(input2);
93823
+ validateLiveInput(input2);
93755
93824
  return this.liveInternal({
93756
93825
  offset: input2.offset,
93757
93826
  mode: input2.mode ?? "auto",
@@ -93798,7 +93867,7 @@ ${val.stack}`;
93798
93867
  }, this.timeoutConfig.connectTimeoutMs, "connect");
93799
93868
  if (response.status === 400) {
93800
93869
  const errorText = await response.text();
93801
- if (allowFallback && isSseUnsupportedErrorText$2(errorText)) return "fallback";
93870
+ if (allowFallback && isSseUnsupportedErrorText$1(errorText)) return "fallback";
93802
93871
  yield {
93803
93872
  type: "error",
93804
93873
  mode: "sse",
@@ -93814,12 +93883,12 @@ ${val.stack}`;
93814
93883
  yield {
93815
93884
  type: "error",
93816
93885
  mode: "sse",
93817
- error: await responseToStreamError$1(response, "live sse")
93886
+ error: await responseToStreamError(response, "live sse")
93818
93887
  };
93819
93888
  return "done";
93820
93889
  }
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");
93890
+ if (response.body == null) throw new ProtocolError$1("sse response missing body");
93891
+ 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
93892
  if (reconnectAttempt > 0) yield {
93824
93893
  type: "reconnected",
93825
93894
  mode: "sse",
@@ -93830,15 +93899,15 @@ ${val.stack}`;
93830
93899
  const dataEncoding = response.headers.get("stream-sse-data-encoding");
93831
93900
  let pendingPayloads = [];
93832
93901
  let sawControlEvent = false;
93833
- for await (const event of readSseEvents$1(response.body, {
93902
+ for await (const event of readSseEvents(response.body, {
93834
93903
  signal
93835
93904
  })) {
93836
93905
  if (event.event === "data") {
93837
- pendingPayloads.push(decodeSsePayload$1(event.data, dataEncoding));
93906
+ pendingPayloads.push(decodeSsePayload(event.data, dataEncoding));
93838
93907
  continue;
93839
93908
  }
93840
93909
  if (event.event !== "control") continue;
93841
- const control = parseSseControlData$2(event.data);
93910
+ const control = parseSseControlData$1(event.data);
93842
93911
  sawControlEvent = true;
93843
93912
  state2.offset = control.nextOffset;
93844
93913
  const effectiveCursor = control.streamCursor ?? state2.cursor;
@@ -93848,7 +93917,7 @@ ${val.stack}`;
93848
93917
  mode: "sse",
93849
93918
  nextOffset: control.nextOffset,
93850
93919
  cursor: effectiveCursor,
93851
- payload: createStreamPart$1(state2.contentType, payload)
93920
+ payload: createStreamPart(state2.contentType, payload)
93852
93921
  };
93853
93922
  pendingPayloads = [];
93854
93923
  if (control.streamClosed) {
@@ -93871,10 +93940,10 @@ ${val.stack}`;
93871
93940
  if (sawControlEvent) continue;
93872
93941
  throw new TypeError("sse connection closed");
93873
93942
  } 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;
93943
+ if (signal?.aborted && isAbortError(error2)) return "done";
93944
+ const mapped = thrownToStreamError(error2);
93945
+ if (!isRetryableLiveError(mapped) || attempt >= this.retryConfig.maxAttempts) {
93946
+ const retryExhausted = isRetryableLiveError(mapped) && attempt >= this.retryConfig.maxAttempts;
93878
93947
  yield {
93879
93948
  type: "error",
93880
93949
  mode: "sse",
@@ -93885,7 +93954,7 @@ ${val.stack}`;
93885
93954
  };
93886
93955
  return "done";
93887
93956
  }
93888
- const delayMs = computeRetryDelay$2(attempt, this.retryConfig);
93957
+ const delayMs = computeRetryDelay$1(attempt, this.retryConfig);
93889
93958
  const nextAttempt = attempt + 1;
93890
93959
  this.onRetry?.({
93891
93960
  operation: "live-sse",
@@ -93902,7 +93971,7 @@ ${val.stack}`;
93902
93971
  error: mapped
93903
93972
  };
93904
93973
  try {
93905
- await sleep$3(delayMs, signal);
93974
+ await sleep$2(delayMs, signal);
93906
93975
  } catch {
93907
93976
  return "done";
93908
93977
  }
@@ -93926,9 +93995,9 @@ ${val.stack}`;
93926
93995
  signal
93927
93996
  }, this.timeoutConfig.pollTimeoutMs, "poll");
93928
93997
  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");
93998
+ const nextOffset = getRequiredHeader(response.headers, "Stream-Next-Offset", "live long-poll");
93999
+ if (!hasTrueHeader(response.headers, "Stream-Up-To-Date")) throw new ProtocolError$1("long-poll 204 response missing Stream-Up-To-Date: true");
94000
+ const closed = hasTrueHeader(response.headers, "Stream-Closed");
93932
94001
  const effectiveCursor = response.headers.get("Stream-Cursor") ?? void 0 ?? state2.cursor;
93933
94002
  if (reconnectAttempt > 0) yield {
93934
94003
  type: "reconnected",
@@ -93959,7 +94028,7 @@ ${val.stack}`;
93959
94028
  yield {
93960
94029
  type: "error",
93961
94030
  mode: "long-poll",
93962
- error: await responseToStreamError$1(response, "live long-poll")
94031
+ error: await responseToStreamError(response, "live long-poll")
93963
94032
  };
93964
94033
  return;
93965
94034
  }
@@ -93996,10 +94065,10 @@ ${val.stack}`;
93996
94065
  cursor: outputCursor
93997
94066
  };
93998
94067
  } 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;
94068
+ if (signal?.aborted && isAbortError(error2)) return;
94069
+ const mapped = thrownToStreamError(error2);
94070
+ if (!isRetryableLiveError(mapped) || attempt >= this.retryConfig.maxAttempts) {
94071
+ const retryExhausted = isRetryableLiveError(mapped) && attempt >= this.retryConfig.maxAttempts;
94003
94072
  yield {
94004
94073
  type: "error",
94005
94074
  mode: "long-poll",
@@ -94010,7 +94079,7 @@ ${val.stack}`;
94010
94079
  };
94011
94080
  return;
94012
94081
  }
94013
- const delayMs = computeRetryDelay$2(attempt, this.retryConfig);
94082
+ const delayMs = computeRetryDelay$1(attempt, this.retryConfig);
94014
94083
  const nextAttempt = attempt + 1;
94015
94084
  this.onRetry?.({
94016
94085
  operation: "live-long-poll",
@@ -94027,7 +94096,7 @@ ${val.stack}`;
94027
94096
  error: mapped
94028
94097
  };
94029
94098
  try {
94030
- await sleep$3(delayMs, signal);
94099
+ await sleep$2(delayMs, signal);
94031
94100
  } catch {
94032
94101
  return;
94033
94102
  }
@@ -94062,17 +94131,17 @@ ${val.stack}`;
94062
94131
  if (input2?.includeMeta !== true) return result;
94063
94132
  return {
94064
94133
  ...result,
94065
- meta: createOperationMeta$1(method, url, response)
94134
+ meta: createOperationMeta(method, url, response)
94066
94135
  };
94067
94136
  }
94068
94137
  parseAppendOutput(response, input2) {
94069
94138
  return {
94070
94139
  status: response.status,
94071
- nextOffset: getRequiredHeader$1(response.headers, "Stream-Next-Offset", "append"),
94072
- closed: hasTrueHeader$1(response.headers, "Stream-Closed"),
94140
+ nextOffset: getRequiredHeader(response.headers, "Stream-Next-Offset", "append"),
94141
+ closed: hasTrueHeader(response.headers, "Stream-Closed"),
94073
94142
  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
94143
+ epoch: parseOptionalInteger(response.headers.get("Producer-Epoch")) ?? input2.producer.epoch,
94144
+ seq: parseOptionalInteger(response.headers.get("Producer-Seq")) ?? input2.producer.seq
94076
94145
  }
94077
94146
  };
94078
94147
  }
@@ -94081,20 +94150,20 @@ ${val.stack}`;
94081
94150
  this.knownContentType = contentType;
94082
94151
  return {
94083
94152
  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"),
94153
+ nextOffset: getRequiredHeader(response.headers, "Stream-Next-Offset", context2),
94154
+ upToDate: hasTrueHeader(response.headers, "Stream-Up-To-Date"),
94155
+ closed: hasTrueHeader(response.headers, "Stream-Closed"),
94087
94156
  cursor: response.headers.get("Stream-Cursor") ?? void 0,
94088
- payload: createStreamPart$1(contentType, new Uint8Array(await response.arrayBuffer()))
94157
+ payload: createStreamPart(contentType, new Uint8Array(await response.arrayBuffer()))
94089
94158
  };
94090
94159
  }
94091
94160
  async parseSnapshotReadOutput(response, context2) {
94092
94161
  const contentType = this.resolveContentType(response, context2);
94093
94162
  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()))
94163
+ snapshotOffset: getRequiredHeader(response.headers, "Stream-Snapshot-Offset", context2),
94164
+ nextOffset: getRequiredHeader(response.headers, "Stream-Next-Offset", context2),
94165
+ upToDate: hasTrueHeader(response.headers, "Stream-Up-To-Date"),
94166
+ payload: createStreamPart(contentType, new Uint8Array(await response.arrayBuffer()))
94098
94167
  };
94099
94168
  }
94100
94169
  async ensureKnownContentType() {
@@ -94114,7 +94183,7 @@ ${val.stack}`;
94114
94183
  const headerValue = response.headers.get("Content-Type");
94115
94184
  if (headerValue != null && headerValue.length > 0) return headerValue;
94116
94185
  if (fallback2 != null && fallback2.length > 0) return fallback2;
94117
- throw new ProtocolError$2(`${context2} response missing Content-Type`);
94186
+ throw new ProtocolError$1(`${context2} response missing Content-Type`);
94118
94187
  }
94119
94188
  streamEndpoint() {
94120
94189
  return this.streamUrl.toString();
@@ -94133,50 +94202,50 @@ ${val.stack}`;
94133
94202
  return target.toString();
94134
94203
  }
94135
94204
  };
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");
94205
+ function validateCreateInput(input2) {
94206
+ if (input2.ttlSeconds != null) assertNonNegativeSafeInteger(input2.ttlSeconds, "ttlSeconds");
94207
+ if (input2.expiresAt != null) assertNonEmptyString(input2.expiresAt, "expiresAt");
94139
94208
  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);
94209
+ if (input2.contentType != null) normalizeContentType(input2.contentType);
94141
94210
  }
94142
- function validateAppendInput$1(input2) {
94143
- if (input2.streamSeq != null) assertNonEmptyString$1(input2.streamSeq, "streamSeq");
94211
+ function validateAppendInput(input2) {
94212
+ if (input2.streamSeq != null) assertNonEmptyString(input2.streamSeq, "streamSeq");
94144
94213
  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");
94214
+ assertNonEmptyString(input2.producer.producerId, "producer.producerId");
94215
+ assertNonNegativeSafeInteger(input2.producer.epoch, "producer.epoch");
94216
+ assertNonNegativeSafeInteger(input2.producer.seq, "producer.seq");
94148
94217
  }
94149
94218
  if (input2.part == null) {
94150
94219
  if (input2.close !== true) throw new Error("append requires part unless close is true");
94151
94220
  return;
94152
94221
  }
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");
94222
+ if (normalizeStreamPartLike(input2.part).body.byteLength === 0 && input2.close !== true) throw new Error("append requires a non-empty body unless close is true");
94154
94223
  }
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");
94224
+ function validateReadInput(input2) {
94225
+ if (input2.offset != null) assertNonEmptyString(input2.offset, "offset");
94226
+ if (input2.cursor != null) assertNonEmptyString(input2.cursor, "cursor");
94158
94227
  }
94159
- function validateReadOnceInput$1(input2) {
94160
- validateReadInput$1(input2);
94228
+ function validateReadOnceInput(input2) {
94229
+ validateReadInput(input2);
94161
94230
  if (input2.live != null && input2.live !== "long-poll") throw new Error("readOnce live mode must be long-poll when provided");
94162
94231
  }
94163
- function validateOpenSseSessionInput$1(input2) {
94164
- assertNonEmptyString$1(input2.offset, "offset");
94165
- if (input2.cursor != null) assertNonEmptyString$1(input2.cursor, "cursor");
94232
+ function validateOpenSseSessionInput(input2) {
94233
+ assertNonEmptyString(input2.offset, "offset");
94234
+ if (input2.cursor != null) assertNonEmptyString(input2.cursor, "cursor");
94166
94235
  }
94167
- function validateLiveInput$1(input2) {
94168
- assertNonEmptyString$1(input2.offset, "offset");
94236
+ function validateLiveInput(input2) {
94237
+ assertNonEmptyString(input2.offset, "offset");
94169
94238
  }
94170
- function assertNonEmptyString$1(value, name2) {
94239
+ function assertNonEmptyString(value, name2) {
94171
94240
  if (value.trim().length === 0) throw new Error(`${name2} must be a non-empty string`);
94172
94241
  }
94173
- function assertNonNegativeSafeInteger$1(value, name2) {
94242
+ function assertNonNegativeSafeInteger(value, name2) {
94174
94243
  if (!Number.isSafeInteger(value) || value < 0) throw new Error(`${name2} must be a non-negative safe integer`);
94175
94244
  }
94176
- function isAppendRetryable$1(error2) {
94245
+ function isAppendRetryable(error2) {
94177
94246
  return error2.code === "network_error" || error2.code === "timeout";
94178
94247
  }
94179
- function createOperationMeta$1(method, url, response) {
94248
+ function createOperationMeta(method, url, response) {
94180
94249
  return {
94181
94250
  request: {
94182
94251
  method,
@@ -94185,33 +94254,33 @@ ${val.stack}`;
94185
94254
  response: {
94186
94255
  status: response.status,
94187
94256
  statusText: response.statusText,
94188
- headers: headersToObject$2(response.headers)
94257
+ headers: headersToObject(response.headers)
94189
94258
  }
94190
94259
  };
94191
94260
  }
94192
- function headersToObject$2(headers) {
94261
+ function headersToObject(headers) {
94193
94262
  const result = {};
94194
94263
  headers.forEach((value, name2) => {
94195
94264
  result[name2] = value;
94196
94265
  });
94197
94266
  return result;
94198
94267
  }
94199
- function createSessionEvents$1(stream2, signal, onActivity) {
94268
+ function createSessionEvents(stream2, signal, onActivity) {
94200
94269
  return {
94201
94270
  async *[Symbol.asyncIterator]() {
94202
94271
  try {
94203
- yield* readSseEvents$1(stream2, {
94272
+ yield* readSseEvents(stream2, {
94204
94273
  signal,
94205
94274
  onActivity
94206
94275
  });
94207
94276
  } catch (error2) {
94208
- if (signal?.aborted && isAbortError$1(error2)) return;
94277
+ if (signal?.aborted && isAbortError(error2)) return;
94209
94278
  throw error2;
94210
94279
  }
94211
94280
  }
94212
94281
  };
94213
94282
  }
94214
- function mergeAbortSignals$3(...signals2) {
94283
+ function mergeAbortSignals$2(...signals2) {
94215
94284
  const active2 = signals2.filter((signal) => signal != null);
94216
94285
  if (active2.length === 0) return;
94217
94286
  if (active2.length === 1) return active2[0];
@@ -94366,15 +94435,15 @@ ${val.stack}`;
94366
94435
  pollTimeoutMs: 3e4,
94367
94436
  liveInactivityTimeoutMs: 45e3
94368
94437
  };
94369
- function applyJitter$1(baseMs, fraction) {
94438
+ function applyJitter(baseMs, fraction) {
94370
94439
  if (baseMs === 0) return 0;
94371
94440
  const jitter = baseMs * fraction * (2 * Math.random() - 1);
94372
94441
  return Math.max(0, Math.round(baseMs + jitter));
94373
94442
  }
94374
- function computeRetryDelay$1(attempt, config2 = DEFAULT_RECONNECT_CONFIG, minDelayMs) {
94443
+ function computeRetryDelay(attempt, config2 = DEFAULT_RECONNECT_CONFIG, minDelayMs) {
94375
94444
  const { delays, jitterFraction } = config2;
94376
94445
  const scheduled2 = delays[Math.min(attempt, delays.length - 1)];
94377
- return applyJitter$1(typeof minDelayMs === "number" && minDelayMs > scheduled2 ? minDelayMs : scheduled2, jitterFraction);
94446
+ return applyJitter(typeof minDelayMs === "number" && minDelayMs > scheduled2 ? minDelayMs : scheduled2, jitterFraction);
94378
94447
  }
94379
94448
  const BINARY_CONTENT_TYPE = "application/octet-stream";
94380
94449
  function encodeItems(items2) {
@@ -94725,7 +94794,7 @@ stream:${scope2.streamId}`;
94725
94794
  if (options?.body !== void 0 && options.body.length > 0) this.body = options.body;
94726
94795
  }
94727
94796
  };
94728
- var TimeoutError$1 = class TimeoutError extends Error {
94797
+ var TimeoutError = class extends Error {
94729
94798
  timeoutType;
94730
94799
  timeoutMs;
94731
94800
  constructor(timeoutType, timeoutMs) {
@@ -94734,7 +94803,7 @@ stream:${scope2.streamId}`;
94734
94803
  this.timeoutMs = timeoutMs;
94735
94804
  }
94736
94805
  };
94737
- var ProtocolError$1 = class ProtocolError extends Error {
94806
+ var ProtocolError = class extends Error {
94738
94807
  status;
94739
94808
  constructor(message, status) {
94740
94809
  super(message);
@@ -94751,7 +94820,7 @@ stream:${scope2.streamId}`;
94751
94820
  function isObject$1(value) {
94752
94821
  return typeof value === "object" && value != null;
94753
94822
  }
94754
- function decodeBase64Bytes$1(encoded) {
94823
+ function decodeBase64Bytes(encoded) {
94755
94824
  const normalized = encoded.replace(/[\r\n]/g, "");
94756
94825
  if (typeof Buffer !== "undefined") return new Uint8Array(Buffer.from(normalized, "base64"));
94757
94826
  if (typeof atob === "function") {
@@ -94766,10 +94835,10 @@ stream:${scope2.streamId}`;
94766
94835
  const normalized = dataEncoding?.trim().toLowerCase();
94767
94836
  if (normalized == null || normalized.length === 0) return;
94768
94837
  if (normalized === "base64") return "base64";
94769
- throw new ProtocolError$1(`unsupported stream-sse-data-encoding '${dataEncoding}'`);
94838
+ throw new ProtocolError(`unsupported stream-sse-data-encoding '${dataEncoding}'`);
94770
94839
  }
94771
94840
  function decodeSseRawPayload(data, dataEncoding) {
94772
- if (dataEncoding === "base64") return decodeBase64Bytes$1(data);
94841
+ if (dataEncoding === "base64") return decodeBase64Bytes(data);
94773
94842
  return new TextEncoder().encode(data);
94774
94843
  }
94775
94844
  function decodeSseItemPayloads(data, dataEncoding) {
@@ -94797,14 +94866,14 @@ stream:${scope2.streamId}`;
94797
94866
  ];
94798
94867
  }
94799
94868
  }
94800
- function parseSseControlData$1(data) {
94869
+ function parseSseControlData(data) {
94801
94870
  let parsed;
94802
94871
  try {
94803
94872
  parsed = JSON.parse(data);
94804
94873
  } catch {
94805
- throw new ProtocolError$1("invalid sse control event JSON");
94874
+ throw new ProtocolError("invalid sse control event JSON");
94806
94875
  }
94807
- if (!isObject$1(parsed) || typeof parsed.streamNextOffset !== "string") throw new ProtocolError$1("sse control event missing streamNextOffset");
94876
+ if (!isObject$1(parsed) || typeof parsed.streamNextOffset !== "string") throw new ProtocolError("sse control event missing streamNextOffset");
94808
94877
  const streamCursor = typeof parsed.streamCursor === "string" ? parsed.streamCursor : void 0;
94809
94878
  return {
94810
94879
  nextOffset: parsed.streamNextOffset,
@@ -94812,14 +94881,14 @@ stream:${scope2.streamId}`;
94812
94881
  streamCursor
94813
94882
  };
94814
94883
  }
94815
- function isSseUnsupportedErrorText$1(message) {
94884
+ function isSseUnsupportedErrorText(message) {
94816
94885
  const normalized = message.trim().toLowerCase();
94817
94886
  if (normalized.length === 0) return false;
94818
94887
  const mentionsSse = normalized.includes("sse") || normalized.includes("text/event-stream");
94819
94888
  const mentionsCompatibility = normalized.includes("unsupported") || normalized.includes("not support") || normalized.includes("incompatible") || normalized.includes("content type");
94820
94889
  return mentionsSse && mentionsCompatibility;
94821
94890
  }
94822
- function sleep$2(ms2, signal) {
94891
+ function sleep$1(ms2, signal) {
94823
94892
  if (signal?.aborted) return Promise.resolve();
94824
94893
  return new Promise((resolve2) => {
94825
94894
  const timer2 = setTimeout(resolve2, ms2);
@@ -94831,7 +94900,7 @@ stream:${scope2.streamId}`;
94831
94900
  });
94832
94901
  });
94833
94902
  }
94834
- function mergeAbortSignals$2(...signals2) {
94903
+ function mergeAbortSignals(...signals2) {
94835
94904
  const active2 = signals2.filter((signal) => signal != null);
94836
94905
  if (active2.length === 0) return;
94837
94906
  if (active2.length === 1) return active2[0];
@@ -94889,13 +94958,13 @@ stream:${scope2.streamId}`;
94889
94958
  retriable: true,
94890
94959
  atMs: Date.now()
94891
94960
  };
94892
- if (err2 instanceof ProtocolError$1) return {
94961
+ if (err2 instanceof ProtocolError) return {
94893
94962
  code: "protocol",
94894
94963
  message,
94895
94964
  retriable: false,
94896
94965
  atMs: Date.now()
94897
94966
  };
94898
- if (err2 instanceof TimeoutError$1) return {
94967
+ if (err2 instanceof TimeoutError) return {
94899
94968
  code: "timeout",
94900
94969
  message,
94901
94970
  retriable: true,
@@ -94972,13 +95041,13 @@ stream:${scope2.streamId}`;
94972
95041
  body: error2.body
94973
95042
  }
94974
95043
  };
94975
- if (error2 instanceof ProtocolError$1) return {
95044
+ if (error2 instanceof ProtocolError) return {
94976
95045
  code: "protocol_error",
94977
95046
  retryable: false,
94978
95047
  status: error2.status,
94979
95048
  message: error2.message
94980
95049
  };
94981
- if (error2 instanceof TimeoutError$1) return {
95050
+ if (error2 instanceof TimeoutError) return {
94982
95051
  code: "timeout",
94983
95052
  retryable: true,
94984
95053
  phase: error2.timeoutType,
@@ -95038,7 +95107,7 @@ stream:${scope2.streamId}`;
95038
95107
  return !result.upToDate && result.updates.length === 0 && result.nextOffset === requestOffset;
95039
95108
  }
95040
95109
  function isAuthOrProtocolError(error2) {
95041
- return error2 instanceof ProtocolError$1 || error2 instanceof HttpError && [
95110
+ return error2 instanceof ProtocolError || error2 instanceof HttpError && [
95042
95111
  400,
95043
95112
  401,
95044
95113
  403,
@@ -95046,7 +95115,7 @@ stream:${scope2.streamId}`;
95046
95115
  409
95047
95116
  ].includes(error2.status);
95048
95117
  }
95049
- function normalizeAuthProvider$1(auth) {
95118
+ function normalizeAuthProvider(auth) {
95050
95119
  if (auth == null) return;
95051
95120
  if (typeof auth === "string") {
95052
95121
  const token2 = auth.trim();
@@ -95125,6 +95194,57 @@ stream:${scope2.streamId}`;
95125
95194
  if (current2 != null && incoming != null) return incoming > current2 ? responseNextOffset : currentOffset;
95126
95195
  return currentOffset;
95127
95196
  }
95197
+ const bodySizeEncoder = new TextEncoder();
95198
+ function normalizeShardOrigins(urls, label2) {
95199
+ if (urls == null) return;
95200
+ const out2 = [];
95201
+ for (const raw of urls) {
95202
+ const trimmed = raw.trim();
95203
+ if (trimmed.length === 0) continue;
95204
+ const url = new URL(trimmed);
95205
+ if (url.protocol !== "http:" && url.protocol !== "https:") throw new Error(`${label2} shard URL must use http or https`);
95206
+ if (url.pathname !== "/" || url.search !== "" || url.hash !== "") throw new Error(`${label2} shard URL must be an origin URL`);
95207
+ out2.push(url.origin);
95208
+ }
95209
+ return out2.length === 0 ? void 0 : out2;
95210
+ }
95211
+ function normalizeShardUrlsOptions(options) {
95212
+ if (options == null) return;
95213
+ const largePostMinBytes = options.largePostMinBytes ?? 0;
95214
+ if (!Number.isSafeInteger(largePostMinBytes) || largePostMinBytes < 0) throw new Error("shardUrls.largePostMinBytes must be a non-negative safe integer");
95215
+ const normalized = {
95216
+ bootstrap: normalizeShardOrigins(options.bootstrap, "shardUrls.bootstrap"),
95217
+ catchup: normalizeShardOrigins(options.catchup, "shardUrls.catchup"),
95218
+ largePost: normalizeShardOrigins(options.largePost, "shardUrls.largePost"),
95219
+ largePostMinBytes
95220
+ };
95221
+ if (normalized.bootstrap == null && normalized.catchup == null && normalized.largePost == null) return;
95222
+ return normalized;
95223
+ }
95224
+ function requestBodyByteLength(body) {
95225
+ if (body == null) return 0;
95226
+ if (typeof body === "string") return bodySizeEncoder.encode(body).byteLength;
95227
+ if (body instanceof ArrayBuffer) return body.byteLength;
95228
+ if (ArrayBuffer.isView(body)) return body.byteLength;
95229
+ if (typeof Blob !== "undefined" && body instanceof Blob) return body.size;
95230
+ if (typeof URLSearchParams !== "undefined" && body instanceof URLSearchParams) return bodySizeEncoder.encode(body.toString()).byteLength;
95231
+ }
95232
+ function createRandomShardStart(originCount) {
95233
+ if (originCount <= 1) return 0;
95234
+ try {
95235
+ const crypto2 = globalThis.crypto;
95236
+ if (crypto2 != null) {
95237
+ const values = new Uint32Array(1);
95238
+ crypto2.getRandomValues(values);
95239
+ return (values[0] ?? 0) % originCount;
95240
+ }
95241
+ } catch {
95242
+ }
95243
+ return Math.floor(Math.random() * originCount);
95244
+ }
95245
+ function normalizedStreamPath(streamUrl) {
95246
+ return streamUrl.pathname.endsWith("/") ? streamUrl.pathname.slice(0, -1) : streamUrl.pathname;
95247
+ }
95128
95248
  var StreamsTransportClient = class {
95129
95249
  streamUrl;
95130
95250
  adapter;
@@ -95132,14 +95252,18 @@ stream:${scope2.streamId}`;
95132
95252
  fetchImpl;
95133
95253
  authProvider;
95134
95254
  reconnectConfig;
95255
+ shardUrls;
95256
+ shardCursorIndexes = {};
95135
95257
  authRefreshInFlight;
95136
95258
  constructor(options) {
95137
95259
  this.streamUrl = options.streamUrl;
95138
95260
  this.adapter = options.adapter;
95139
- this.client = new StreamsClient$1({
95261
+ this.fetchImpl = options.fetchImpl;
95262
+ this.shardUrls = normalizeShardUrlsOptions(options.shardUrls);
95263
+ this.client = new StreamsClient({
95140
95264
  url: options.streamUrl,
95141
95265
  auth: options.authProvider,
95142
- fetch: options.fetchImpl,
95266
+ fetch: this.fetchRouted.bind(this),
95143
95267
  retry: {
95144
95268
  maxAttempts: 0
95145
95269
  },
@@ -95148,10 +95272,44 @@ stream:${scope2.streamId}`;
95148
95272
  pollTimeoutMs: options.reconnectConfig.pollTimeoutMs
95149
95273
  }
95150
95274
  });
95151
- this.fetchImpl = options.fetchImpl;
95152
95275
  this.authProvider = options.authProvider;
95153
95276
  this.reconnectConfig = options.reconnectConfig;
95154
95277
  }
95278
+ fetchRouted(input2, init2) {
95279
+ return this.fetchImpl(this.routeRequestUrl(input2, init2), init2);
95280
+ }
95281
+ routeRequestUrl(input2, init2) {
95282
+ const shardUrls = this.shardUrls;
95283
+ if (shardUrls == null) return input2;
95284
+ const operation = this.classifyShardOperation(input2, init2, shardUrls);
95285
+ if (operation == null) return input2;
95286
+ const origins = operation === "bootstrap" ? shardUrls.bootstrap : operation === "catchup" ? shardUrls.catchup : shardUrls.largePost;
95287
+ if (origins == null || origins.length === 0) return input2;
95288
+ const target = new URL(input2);
95289
+ const shardOrigin = new URL(this.nextShardOrigin(operation, origins));
95290
+ target.protocol = shardOrigin.protocol;
95291
+ target.host = shardOrigin.host;
95292
+ target.username = "";
95293
+ target.password = "";
95294
+ return target.toString();
95295
+ }
95296
+ nextShardOrigin(operation, origins) {
95297
+ const currentIndex = this.shardCursorIndexes[operation] ?? createRandomShardStart(origins.length);
95298
+ this.shardCursorIndexes[operation] = (currentIndex + 1) % origins.length;
95299
+ return origins[currentIndex % origins.length];
95300
+ }
95301
+ classifyShardOperation(input2, init2, shardUrls) {
95302
+ const method = (init2?.method ?? "GET").toUpperCase();
95303
+ const requestUrl = new URL(input2);
95304
+ const streamUrl = new URL(this.streamUrl);
95305
+ const streamPath = normalizedStreamPath(streamUrl);
95306
+ if (method === "GET" && requestUrl.pathname === `${streamPath}/bootstrap`) return "bootstrap";
95307
+ if (method === "GET" && requestUrl.pathname === streamUrl.pathname && requestUrl.searchParams.has("offset") && requestUrl.searchParams.get("live") !== "sse") return "catchup";
95308
+ if (method !== "POST" || requestUrl.pathname !== streamUrl.pathname) return;
95309
+ const bodyLength = requestBodyByteLength(init2?.body);
95310
+ if (bodyLength == null || bodyLength === 0 || bodyLength < shardUrls.largePostMinBytes) return;
95311
+ return "large-post";
95312
+ }
95155
95313
  async createStreamRequest() {
95156
95314
  const adapterHeaders = this.adapter.getCreateStreamHeaders ? await this.adapter.getCreateStreamHeaders() : void 0;
95157
95315
  const result = await this.client.create({
@@ -95195,10 +95353,11 @@ stream:${scope2.streamId}`;
95195
95353
  async bootstrap() {
95196
95354
  const result = await this.client.bootstrap();
95197
95355
  if (!result.ok) throw this.toTransportFailure(result.result);
95356
+ const snapshot = result.result.snapshotOffset === "-1" ? new Uint8Array() : result.result.snapshot?.body ?? new Uint8Array();
95198
95357
  return {
95199
95358
  nextOffset: result.result.nextOffset,
95200
95359
  upToDate: result.result.upToDate,
95201
- snapshot: result.result.snapshot?.body ?? new Uint8Array(),
95360
+ snapshot,
95202
95361
  updates: result.result.updates.flatMap((part) => decodeMultipartPartItems(part.body)),
95203
95362
  streamCursor: result.result.cursor
95204
95363
  };
@@ -95289,32 +95448,32 @@ stream:${scope2.streamId}`;
95289
95448
  if (!response.ok) {
95290
95449
  if (response.status === 400) {
95291
95450
  const message = await response.text();
95292
- if (isSseUnsupportedErrorText$1(message)) return {
95451
+ if (isSseUnsupportedErrorText(message)) return {
95293
95452
  kind: "unsupported"
95294
95453
  };
95295
95454
  throw new HttpError(message.length > 0 ? `ephemeral live read failed: ${message}` : "ephemeral live read failed", response.status);
95296
95455
  }
95297
95456
  throw await this.responseToEphemeralFailure(response, "ephemeral live read");
95298
95457
  }
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");
95458
+ if (response.body == null) throw new ProtocolError("ephemeral sse response missing body");
95459
+ 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
95460
  const dataEncoding = response.headers.get("Stream-SSE-Data-Encoding") ?? void 0;
95302
95461
  const consume = async () => {
95303
95462
  let sawBootstrap = false;
95304
- for await (const event of readSseEvents$1(response.body)) {
95463
+ for await (const event of readSseEvents(response.body)) {
95305
95464
  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));
95465
+ if (event.event !== "bootstrap") throw new ProtocolError(`ephemeral sse must start with bootstrap, got '${event.event}'`);
95466
+ await onBootstrap(decodeSsePayload(event.data, dataEncoding));
95308
95467
  sawBootstrap = true;
95309
95468
  continue;
95310
95469
  }
95311
95470
  if (event.event === "data") {
95312
- await onData(decodeSsePayload$1(event.data, dataEncoding));
95471
+ await onData(decodeSsePayload(event.data, dataEncoding));
95313
95472
  continue;
95314
95473
  }
95315
- throw new ProtocolError$1(`unexpected ephemeral sse event '${event.event}'`);
95474
+ throw new ProtocolError(`unexpected ephemeral sse event '${event.event}'`);
95316
95475
  }
95317
- if (!sawBootstrap) throw new ProtocolError$1("ephemeral sse ended before bootstrap");
95476
+ if (!sawBootstrap) throw new ProtocolError("ephemeral sse ended before bootstrap");
95318
95477
  return {
95319
95478
  kind: "ok"
95320
95479
  };
@@ -95363,9 +95522,9 @@ stream:${scope2.streamId}`;
95363
95522
  }
95364
95523
  async fetchWithTimeout(input2, init2, timeoutMs, phase) {
95365
95524
  const controller = new AbortController();
95366
- const signal = mergeAbortSignals$2(init2.signal, controller.signal);
95525
+ const signal = mergeAbortSignals(init2.signal, controller.signal);
95367
95526
  const timer2 = setTimeout(() => {
95368
- controller.abort(new TimeoutError$1(phase, timeoutMs));
95527
+ controller.abort(new TimeoutError(phase, timeoutMs));
95369
95528
  }, timeoutMs);
95370
95529
  try {
95371
95530
  return await this.fetchImpl(input2, {
@@ -95373,7 +95532,7 @@ stream:${scope2.streamId}`;
95373
95532
  signal
95374
95533
  });
95375
95534
  } catch (error2) {
95376
- if (controller.signal.aborted && controller.signal.reason instanceof TimeoutError$1) throw controller.signal.reason;
95535
+ if (controller.signal.aborted && controller.signal.reason instanceof TimeoutError) throw controller.signal.reason;
95377
95536
  throw error2;
95378
95537
  } finally {
95379
95538
  clearTimeout(timer2);
@@ -95428,11 +95587,11 @@ stream:${scope2.streamId}`;
95428
95587
  body: error2.bodyText
95429
95588
  });
95430
95589
  case "timeout":
95431
- return new TimeoutError$1(error2.phase, error2.phase === "poll" ? this.reconnectConfig.pollTimeoutMs : this.reconnectConfig.connectTimeoutMs);
95590
+ return new TimeoutError(error2.phase, error2.phase === "poll" ? this.reconnectConfig.pollTimeoutMs : this.reconnectConfig.connectTimeoutMs);
95432
95591
  case "network_error":
95433
95592
  return error2.cause instanceof TypeError ? error2.cause : new TypeError(error2.message);
95434
95593
  case "protocol_error":
95435
- return new ProtocolError$1(error2.message, error2.status);
95594
+ return new ProtocolError(error2.message, error2.status);
95436
95595
  case "unknown":
95437
95596
  if (typeof error2.status === "number") return new HttpError(error2.message, error2.status, {
95438
95597
  requestId: extractRequestIdFromHeaders(error2.headers),
@@ -95494,7 +95653,7 @@ stream:${scope2.streamId}`;
95494
95653
  if (result.result.code === "not_found") return {
95495
95654
  kind: "not-found"
95496
95655
  };
95497
- if (result.result.code === "bad_request" && isSseUnsupportedErrorText$1(result.result.message)) return {
95656
+ if (result.result.code === "bad_request" && isSseUnsupportedErrorText(result.result.message)) return {
95498
95657
  kind: "unsupported"
95499
95658
  };
95500
95659
  throw this.toTransportFailure(result.result);
@@ -95521,7 +95680,7 @@ stream:${scope2.streamId}`;
95521
95680
  continue;
95522
95681
  }
95523
95682
  if (event.event !== "control") continue;
95524
- const control = parseSseControlData$1(event.data);
95683
+ const control = parseSseControlData(event.data);
95525
95684
  const updates = [];
95526
95685
  for (const eventData of pendingDataEvents) updates.push(...decodeSseItemPayloads(eventData, session.dataEncoding));
95527
95686
  pendingDataEvents = [];
@@ -95636,7 +95795,7 @@ stream:${scope2.streamId}`;
95636
95795
  this.client = new StreamsTransportClient({
95637
95796
  streamUrl: options.streamUrl,
95638
95797
  adapter: createNoopAdapter(),
95639
- authProvider: normalizeAuthProvider$1(options.auth),
95798
+ authProvider: normalizeAuthProvider(options.auth),
95640
95799
  fetchImpl: options.fetch ?? globalThis.fetch.bind(globalThis),
95641
95800
  reconnectConfig: this.reconnectConfig
95642
95801
  });
@@ -95814,7 +95973,7 @@ stream:${scope2.streamId}`;
95814
95973
  if (result.kind === "ok") {
95815
95974
  state2.retryAttempt = 0;
95816
95975
  this.setReadStatus(state2, "reconnecting");
95817
- await sleep$2(0);
95976
+ await sleep$1(0);
95818
95977
  continue;
95819
95978
  }
95820
95979
  if (result.kind === "unsupported") throw new Error("ephemeral stream requires SSE support");
@@ -95846,9 +96005,9 @@ stream:${scope2.streamId}`;
95846
96005
  this.rejectFirstOpen(state2, toError$1(error2));
95847
96006
  return;
95848
96007
  }
95849
- const delay2 = computeRetryDelay$1(state2.retryAttempt, this.reconnectConfig);
96008
+ const delay2 = computeRetryDelay(state2.retryAttempt, this.reconnectConfig);
95850
96009
  state2.retryAttempt += 1;
95851
- await sleep$2(delay2, state2.retrySleepController.signal);
96010
+ await sleep$1(delay2, state2.retrySleepController.signal);
95852
96011
  }
95853
96012
  }
95854
96013
  }
@@ -95884,9 +96043,9 @@ stream:${scope2.streamId}`;
95884
96043
  return;
95885
96044
  }
95886
96045
  this.setWriteStatus(state2, "reconnecting");
95887
- const delay2 = computeRetryDelay$1(attempt, this.reconnectConfig);
96046
+ const delay2 = computeRetryDelay(attempt, this.reconnectConfig);
95888
96047
  attempt += 1;
95889
- await sleep$2(delay2, state2.retrySleepController.signal);
96048
+ await sleep$1(delay2, state2.retrySleepController.signal);
95890
96049
  }
95891
96050
  }
95892
96051
  } finally {
@@ -96273,7 +96432,7 @@ stream:${scope2.streamId}`;
96273
96432
  const MIN_RECONNECT_DELAY_MS = 1e3;
96274
96433
  const MIN_SUCCESSFUL_SSE_DURATION_MS = 5e3;
96275
96434
  function reconnectDelayWithFloor(attempt, config2) {
96276
- return Math.max(computeRetryDelay$1(attempt, config2), MIN_RECONNECT_DELAY_MS);
96435
+ return Math.max(computeRetryDelay(attempt, config2), MIN_RECONNECT_DELAY_MS);
96277
96436
  }
96278
96437
  function fastSseCloseDelay(startedAtMs) {
96279
96438
  const elapsedMs = Math.max(0, Date.now() - startedAtMs);
@@ -96315,7 +96474,7 @@ stream:${scope2.streamId}`;
96315
96474
  constructor(options) {
96316
96475
  this.streamUrl = options.streamUrl;
96317
96476
  this.adapter = options.adapter;
96318
- const authProvider = normalizeAuthProvider$1(options.auth);
96477
+ const authProvider = normalizeAuthProvider(options.auth);
96319
96478
  this.createStreamIfMissing = options.createStreamIfMissing ?? false;
96320
96479
  const fetchImpl = options.fetch ?? globalThis.fetch.bind(globalThis);
96321
96480
  this.remoteCursorStore = options.remoteCursorStore ?? new InMemoryRemoteCursorStore();
@@ -96342,7 +96501,8 @@ stream:${scope2.streamId}`;
96342
96501
  adapter: this.adapter,
96343
96502
  authProvider,
96344
96503
  fetchImpl,
96345
- reconnectConfig: this.reconnectConfig
96504
+ reconnectConfig: this.reconnectConfig,
96505
+ shardUrls: options.shardUrls
96346
96506
  });
96347
96507
  this.cursorManager = this.createCursorManager(this.adapter, (cursor, source) => this.saveRemoteCursor(cursor, source));
96348
96508
  this.volatileCursorManager = this.createCursorManager(this.adapter, async (cursor) => cursor);
@@ -96513,6 +96673,29 @@ stream:${scope2.streamId}`;
96513
96673
  };
96514
96674
  }
96515
96675
  }
96676
+ async catchup(params = {}) {
96677
+ try {
96678
+ this.disableWriteOnlyMode("appendWriteOnly cannot be used after catchup() on the same transport");
96679
+ const state2 = this.joinState;
96680
+ if (state2 != null && !state2.closed) return {
96681
+ ok: true,
96682
+ value: {
96683
+ cursor: await this.catchupJoinState(state2, params)
96684
+ }
96685
+ };
96686
+ return {
96687
+ ok: true,
96688
+ value: {
96689
+ cursor: (await this.resolvePullOnlyRemoteState()).cursor
96690
+ }
96691
+ };
96692
+ } catch (error2) {
96693
+ return {
96694
+ ok: false,
96695
+ error: toTransportError(error2)
96696
+ };
96697
+ }
96698
+ }
96516
96699
  async appendWriteOnly() {
96517
96700
  return await this.enqueueExclusive(async () => {
96518
96701
  try {
@@ -96760,6 +96943,40 @@ stream:${scope2.streamId}`;
96760
96943
  return await this.bootstrapState(this.createInitialCursor());
96761
96944
  }
96762
96945
  }
96946
+ async resolvePullOnlyRemoteState() {
96947
+ const loaded = await this.remoteCursorStore.load(this.streamUrl);
96948
+ const cursor = loaded ?? this.createInitialCursor();
96949
+ try {
96950
+ if (loaded == null) return await this.bootstrapState(cursor);
96951
+ return await this.catchupFromCursor(cursor);
96952
+ } catch (error2) {
96953
+ if (!isStreamNotFoundError(error2) || !this.createStreamIfMissing) throw error2;
96954
+ await this.ensureStreamExists();
96955
+ return await this.bootstrapState(this.createInitialCursor());
96956
+ }
96957
+ }
96958
+ async catchupJoinState(state2, params) {
96959
+ if (state2.readSubStatus === "connecting") {
96960
+ await state2.started;
96961
+ return state2.cursor;
96962
+ }
96963
+ if (state2.readSubStatus === "ok" && params.force !== true) return state2.cursor;
96964
+ const cursor = await this.enqueueExclusive(async () => {
96965
+ if (state2.closed) throw new Error("subscription closed");
96966
+ const caughtUp = await this.catchupFromCursor(state2.cursor, void 0, state2.streamCursor, (previousVersion, nextVersion) => {
96967
+ this.snapshotManager.observeRemoteVersion(state2, previousVersion, nextVersion);
96968
+ });
96969
+ state2.cursor = caughtUp.cursor;
96970
+ state2.streamCursor = caughtUp.streamCursor;
96971
+ return state2.cursor;
96972
+ });
96973
+ if (state2.closed) return cursor;
96974
+ state2.retryAttempt = 0;
96975
+ state2.lastError = void 0;
96976
+ if (state2.readSubStatus !== "ok" || state2.writeSubStatus === "error") this.rejoin();
96977
+ else if (state2.pendingLocal.length > 0) this.flushPendingLocal(state2);
96978
+ return cursor;
96979
+ }
96763
96980
  async bootstrapState(cursor, options = {}) {
96764
96981
  const cursorManager = options.cursorManager ?? this.cursorManager;
96765
96982
  const result = await this.client.bootstrap();
@@ -96779,7 +96996,7 @@ stream:${scope2.streamId}`;
96779
96996
  streamCursor: bootstrapCursor
96780
96997
  };
96781
96998
  }
96782
- async catchup(cursor, live, streamCursor, onRemoteVersionApplied) {
96999
+ async catchupFromCursor(cursor, live, streamCursor, onRemoteVersionApplied) {
96783
97000
  const result = await this.catchupOrGone(cursor, {
96784
97001
  live,
96785
97002
  streamCursor,
@@ -97126,7 +97343,7 @@ stream:${scope2.streamId}`;
97126
97343
  state2.retryAttempt = 0;
97127
97344
  this.setReadSubStatus(state2, "ok");
97128
97345
  if (state2.pendingLocal.length > 0) this.flushPendingLocal(state2);
97129
- await sleep$2(0);
97346
+ await sleep$1(0);
97130
97347
  continue;
97131
97348
  }
97132
97349
  const sseRequestOffset = state2.cursor.nextOffset;
@@ -97180,12 +97397,12 @@ stream:${scope2.streamId}`;
97180
97397
  if (sseResult.kind === "ok") {
97181
97398
  state2.retryAttempt = 0;
97182
97399
  state2.streamCursor = sseResult.latestCursor;
97183
- await sleep$2(fastSseCloseDelay(sseStartedAtMs), state2.retrySleepController.signal);
97400
+ await sleep$1(fastSseCloseDelay(sseStartedAtMs), state2.retrySleepController.signal);
97184
97401
  continue;
97185
97402
  }
97186
97403
  if (sseResult.kind === "unsupported") {
97187
97404
  state2.liveMode = "long-poll";
97188
- await sleep$2(0);
97405
+ await sleep$1(0);
97189
97406
  continue;
97190
97407
  }
97191
97408
  if (sseResult.kind === "not-found") {
@@ -97237,7 +97454,7 @@ stream:${scope2.streamId}`;
97237
97454
  return;
97238
97455
  }
97239
97456
  state2.retryAttempt += 1;
97240
- await sleep$2(reconnectDelayWithFloor(state2.retryAttempt - 1, this.reconnectConfig), state2.retrySleepController.signal);
97457
+ await sleep$1(reconnectDelayWithFloor(state2.retryAttempt - 1, this.reconnectConfig), state2.retrySleepController.signal);
97241
97458
  continue;
97242
97459
  }
97243
97460
  const abortReason = capturedController.signal.reason;
@@ -97284,9 +97501,9 @@ stream:${scope2.streamId}`;
97284
97501
  this.setReadSubStatus(state2, "disconnected");
97285
97502
  return;
97286
97503
  }
97287
- const delay2 = computeRetryDelay$1(state2.retryAttempt, this.reconnectConfig, error2 instanceof HttpError ? error2.retryAfterMs : void 0);
97504
+ const delay2 = computeRetryDelay(state2.retryAttempt, this.reconnectConfig, error2 instanceof HttpError ? error2.retryAfterMs : void 0);
97288
97505
  state2.retryAttempt += 1;
97289
- await sleep$2(delay2, state2.retrySleepController.signal);
97506
+ await sleep$1(delay2, state2.retrySleepController.signal);
97290
97507
  }
97291
97508
  }
97292
97509
  }
@@ -97366,9 +97583,9 @@ stream:${scope2.streamId}`;
97366
97583
  return;
97367
97584
  }
97368
97585
  this.setWriteSubStatus(state2, "reconnecting");
97369
- const delay2 = computeRetryDelay$1(attempts, this.reconnectConfig, error2 instanceof HttpError ? error2.retryAfterMs : void 0);
97586
+ const delay2 = computeRetryDelay(attempts, this.reconnectConfig, error2 instanceof HttpError ? error2.retryAfterMs : void 0);
97370
97587
  attempts += 1;
97371
- await sleep$2(delay2, state2.retrySleepController.signal);
97588
+ await sleep$1(delay2, state2.retrySleepController.signal);
97372
97589
  }
97373
97590
  }
97374
97591
  } finally {
@@ -118352,1737 +118569,203 @@ ${this.stack.split("\n").slice(1).join("\n")}` : this.toString();
118352
118569
  });
118353
118570
  }
118354
118571
  }
118355
- var ProtocolError = class extends Error {
118356
- status;
118357
- detail;
118572
+ const DEFAULT_GATEWAY_BASE_URL = "https://streams-api-proxy.loro.dev";
118573
+ const JSON_RPC_VERSION$1 = "2.0";
118574
+ const LORO_STREAMS_RPC_VERSION = "1";
118575
+ const LORO_STREAMS_RPC_RETENTION_SECONDS = 86400;
118576
+ const LORO_STREAMS_RPC_ERROR_CODES = {
118577
+ rpcVersionMismatch: "rpc_version_mismatch",
118578
+ methodUnavailable: "method_unavailable",
118579
+ internalError: "internal_error"
118580
+ };
118581
+ const LORO_RPC_REQUEST_STREAM_SEGMENT = "rpc:req";
118582
+ const getLoroMachineRpcRequestStreamId = (workspaceId, machineId) => `${workspaceId}:${LORO_RPC_REQUEST_STREAM_SEGMENT}:${machineId}`;
118583
+ const normalizeLoroGatewayBaseUrl = (baseUrl) => {
118584
+ const trimmed = baseUrl?.trim();
118585
+ if (!trimmed) {
118586
+ return DEFAULT_GATEWAY_BASE_URL;
118587
+ }
118588
+ return trimmed.replace(/\/+$/g, "");
118589
+ };
118590
+ const LoroStreamsRpcMethodSchema = _enum$1([
118591
+ "machine/status",
118592
+ "machine/acp-capabilities-refresh",
118593
+ "session/preview-create",
118594
+ "session/preview-revoke",
118595
+ "local-project/git-state",
118596
+ "local-project/control"
118597
+ ]);
118598
+ const LoroStreamsRpcErrorSchema = object$1({
118599
+ code: string$2().trim().min(1),
118600
+ message: string$2().trim().min(1),
118601
+ data: unknown().optional()
118602
+ }).strict();
118603
+ const BaseRpcRequestSchema = object$1({
118604
+ jsonrpc: literal(JSON_RPC_VERSION$1),
118605
+ id: string$2().trim().min(1),
118606
+ method: LoroStreamsRpcMethodSchema,
118607
+ rpcVersion: string$2().trim().min(1),
118608
+ machineId: string$2().trim().min(1),
118609
+ workspaceId: string$2().trim().min(1),
118610
+ replyTo: string$2().trim().min(1),
118611
+ sentAt: number$3().finite().nonnegative(),
118612
+ expiresAt: number$3().finite().positive()
118613
+ }).strict();
118614
+ const LoroMachineStatusRpcRequestSchema = BaseRpcRequestSchema.extend({
118615
+ method: literal("machine/status"),
118616
+ params: object$1({}).strict()
118617
+ }).strict();
118618
+ const LoroMachineAcpCapabilitiesRefreshRpcRequestSchema = BaseRpcRequestSchema.extend({
118619
+ method: literal("machine/acp-capabilities-refresh"),
118620
+ params: object$1({
118621
+ cliType: AgentConfigCliTypeSchema,
118622
+ agentType: string$2().trim().min(1),
118623
+ env: record(string$2(), string$2()).optional()
118624
+ }).strict()
118625
+ }).strict();
118626
+ const LoroSessionPreviewCreateRpcRequestSchema = BaseRpcRequestSchema.extend({
118627
+ method: literal("session/preview-create"),
118628
+ params: object$1({
118629
+ sessionId: string$2().trim().min(1),
118630
+ requestedByUserId: string$2().trim().min(1),
118631
+ replaceExisting: boolean().optional()
118632
+ }).strict()
118633
+ }).strict();
118634
+ const LoroSessionPreviewRevokeRpcRequestSchema = BaseRpcRequestSchema.extend({
118635
+ method: literal("session/preview-revoke"),
118636
+ params: object$1({
118637
+ sessionId: string$2().trim().min(1),
118638
+ requestedByUserId: string$2().trim().min(1),
118639
+ reason: string$2().trim().min(1).optional()
118640
+ }).strict()
118641
+ }).strict();
118642
+ const LoroLocalProjectGitStateRpcRequestSchema = BaseRpcRequestSchema.extend({
118643
+ method: literal("local-project/git-state"),
118644
+ params: object$1({
118645
+ localProjectId: string$2().trim().min(1),
118646
+ requestedByUserId: string$2().trim().min(1)
118647
+ }).strict()
118648
+ }).strict();
118649
+ const LoroLocalProjectControlRpcRequestSchema = BaseRpcRequestSchema.extend({
118650
+ method: literal("local-project/control"),
118651
+ params: object$1({
118652
+ request: LocalProjectControlRequestSchema
118653
+ }).strict()
118654
+ }).strict();
118655
+ const LoroStreamsRpcRequestSchema = discriminatedUnion("method", [
118656
+ LoroMachineStatusRpcRequestSchema,
118657
+ LoroMachineAcpCapabilitiesRefreshRpcRequestSchema,
118658
+ LoroSessionPreviewCreateRpcRequestSchema,
118659
+ LoroSessionPreviewRevokeRpcRequestSchema,
118660
+ LoroLocalProjectGitStateRpcRequestSchema,
118661
+ LoroLocalProjectControlRpcRequestSchema
118662
+ ]);
118663
+ discriminatedUnion("success", [
118664
+ object$1({
118665
+ type: literal("local-project/git-state_response"),
118666
+ machineId: string$2().trim().min(1),
118667
+ workspaceId: string$2().trim().min(1),
118668
+ localProjectId: string$2().trim().min(1),
118669
+ success: literal(true),
118670
+ state: LocalProjectGitStateSchema,
118671
+ observedAtMs: number$3().nonnegative()
118672
+ }).strict(),
118673
+ object$1({
118674
+ type: literal("local-project/git-state_response"),
118675
+ machineId: string$2().trim().min(1),
118676
+ workspaceId: string$2().trim().min(1),
118677
+ localProjectId: string$2().trim().min(1),
118678
+ success: literal(false),
118679
+ error: string$2().trim().min(1),
118680
+ message: string$2().trim().min(1).optional()
118681
+ }).strict()
118682
+ ]);
118683
+ object$1({
118684
+ jsonrpc: literal(JSON_RPC_VERSION$1),
118685
+ id: string$2().trim().min(1),
118686
+ method: LoroStreamsRpcMethodSchema,
118687
+ rpcVersion: string$2().trim().min(1),
118688
+ machineId: string$2().trim().min(1),
118689
+ result: unknown().optional(),
118690
+ error: LoroStreamsRpcErrorSchema.optional()
118691
+ }).strict().superRefine((value, ctx) => {
118692
+ const hasResult = value.result !== void 0;
118693
+ const hasError = value.error !== void 0;
118694
+ if (hasResult === hasError) {
118695
+ ctx.addIssue({
118696
+ code: ZodIssueCode$1.custom,
118697
+ message: "RPC response must contain exactly one of result or error"
118698
+ });
118699
+ }
118700
+ });
118701
+ const JSON_STREAM_CONTENT_TYPE = "application/json";
118702
+ class LoroStreamsGatewayError extends Error {
118358
118703
  constructor(message, status, detail) {
118359
118704
  super(message);
118360
118705
  this.status = status;
118361
118706
  this.detail = detail;
118707
+ this.name = "LoroStreamsGatewayError";
118362
118708
  }
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
118709
  }
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 "";
118710
+ const toLoroGatewayError = (action, streamId, error2) => {
118711
+ if ("status" in error2 && typeof error2.status === "number") {
118712
+ const detail = "detail" in error2 && typeof error2.detail === "string" ? error2.detail : void 0;
118713
+ return new LoroStreamsGatewayError(`Failed to ${action} ${streamId}: ${error2.message}`, error2.status, detail);
118526
118714
  }
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
118715
+ return new Error(`Failed to ${action} ${streamId}: ${error2.message}`);
118534
118716
  };
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
- });
118717
+ const unwrapStreamResult = (action, streamId, result) => {
118718
+ if (result.ok) {
118719
+ return result.result;
118561
118720
  }
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);
118721
+ throw toLoroGatewayError(action, streamId, result.result);
118722
+ };
118723
+ const parseJsonPayload = (payload, streamId, context2) => {
118571
118724
  try {
118572
- return await fetchImpl(input2, {
118573
- ...init2,
118574
- signal
118575
- });
118725
+ return payload.json();
118576
118726
  } catch (error2) {
118577
- if (controller.signal.aborted && controller.signal.reason instanceof TimeoutError) throw controller.signal.reason;
118578
- throw error2;
118579
- } finally {
118580
- clearTimeout(timer2);
118727
+ const message = error2 instanceof Error ? error2.message : String(error2);
118728
+ throw new Error(`Invalid JSON payload for ${streamId} during ${context2}: ${message}`, {
118729
+ cause: error2
118730
+ });
118581
118731
  }
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);
118732
+ };
118733
+ const parseJsonBatchPayload = (payload, streamId, context2) => {
118734
+ const parsed = parseJsonPayload(payload, streamId, context2);
118735
+ if (!Array.isArray(parsed)) {
118736
+ throw new Error(`Invalid JSON payload for ${streamId} during ${context2}: expected array`);
118590
118737
  }
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);
118738
+ return parsed;
118739
+ };
118740
+ const parseJsonLivePayload = (payload, streamId, context2) => {
118741
+ const parsed = parseJsonPayload(payload, streamId, context2);
118742
+ return Array.isArray(parsed) ? parsed : [
118743
+ parsed
118744
+ ];
118745
+ };
118746
+ const normalizeRetentionSeconds = (retentionSeconds) => {
118747
+ if (typeof retentionSeconds !== "number" || retentionSeconds <= 0) {
118748
+ return void 0;
118608
118749
  }
118609
- async resolveToken(context2) {
118610
- if (this.authProvider == null) return;
118611
- return await this.authProvider(context2);
118750
+ return Math.trunc(retentionSeconds);
118751
+ };
118752
+ const isCompatibleExistingJsonStream = (stream2, requestedTtlSeconds) => {
118753
+ if (stream2.contentType !== JSON_STREAM_CONTENT_TYPE || stream2.closed) {
118754
+ return false;
118612
118755
  }
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;
118756
+ if (requestedTtlSeconds === void 0) {
118757
+ return stream2.ttlSeconds === void 0 && stream2.expiresAt === void 0;
118623
118758
  }
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;
118759
+ if (stream2.ttlSeconds === requestedTtlSeconds) {
118760
+ return true;
118632
118761
  }
118762
+ return stream2.ttlSeconds === void 0 && stream2.expiresAt === void 0;
118633
118763
  };
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
- const DEFAULT_GATEWAY_BASE_URL = "https://streams-api-proxy.loro.dev";
119890
- const JSON_RPC_VERSION$1 = "2.0";
119891
- const LORO_STREAMS_RPC_VERSION = "1";
119892
- const LORO_STREAMS_RPC_RETENTION_SECONDS = 86400;
119893
- const LORO_STREAMS_RPC_ERROR_CODES = {
119894
- rpcVersionMismatch: "rpc_version_mismatch",
119895
- methodUnavailable: "method_unavailable",
119896
- internalError: "internal_error"
119897
- };
119898
- const LORO_RPC_REQUEST_STREAM_SEGMENT = "rpc:req";
119899
- const getLoroMachineRpcRequestStreamId = (workspaceId, machineId) => `${workspaceId}:${LORO_RPC_REQUEST_STREAM_SEGMENT}:${machineId}`;
119900
- const normalizeLoroGatewayBaseUrl = (baseUrl) => {
119901
- const trimmed = baseUrl?.trim();
119902
- if (!trimmed) {
119903
- return DEFAULT_GATEWAY_BASE_URL;
119904
- }
119905
- return trimmed.replace(/\/+$/g, "");
119906
- };
119907
- const LoroStreamsRpcMethodSchema = _enum$1([
119908
- "machine/status",
119909
- "machine/acp-capabilities-refresh",
119910
- "session/preview-create",
119911
- "session/preview-revoke",
119912
- "local-project/git-state",
119913
- "local-project/control"
119914
- ]);
119915
- const LoroStreamsRpcErrorSchema = object$1({
119916
- code: string$2().trim().min(1),
119917
- message: string$2().trim().min(1),
119918
- data: unknown().optional()
119919
- }).strict();
119920
- const BaseRpcRequestSchema = object$1({
119921
- jsonrpc: literal(JSON_RPC_VERSION$1),
119922
- id: string$2().trim().min(1),
119923
- method: LoroStreamsRpcMethodSchema,
119924
- rpcVersion: string$2().trim().min(1),
119925
- machineId: string$2().trim().min(1),
119926
- workspaceId: string$2().trim().min(1),
119927
- replyTo: string$2().trim().min(1),
119928
- sentAt: number$3().finite().nonnegative(),
119929
- expiresAt: number$3().finite().positive()
119930
- }).strict();
119931
- const LoroMachineStatusRpcRequestSchema = BaseRpcRequestSchema.extend({
119932
- method: literal("machine/status"),
119933
- params: object$1({}).strict()
119934
- }).strict();
119935
- const LoroMachineAcpCapabilitiesRefreshRpcRequestSchema = BaseRpcRequestSchema.extend({
119936
- method: literal("machine/acp-capabilities-refresh"),
119937
- params: object$1({
119938
- cliType: AgentConfigCliTypeSchema,
119939
- agentType: string$2().trim().min(1),
119940
- env: record(string$2(), string$2()).optional()
119941
- }).strict()
119942
- }).strict();
119943
- const LoroSessionPreviewCreateRpcRequestSchema = BaseRpcRequestSchema.extend({
119944
- method: literal("session/preview-create"),
119945
- params: object$1({
119946
- sessionId: string$2().trim().min(1),
119947
- requestedByUserId: string$2().trim().min(1),
119948
- replaceExisting: boolean().optional()
119949
- }).strict()
119950
- }).strict();
119951
- const LoroSessionPreviewRevokeRpcRequestSchema = BaseRpcRequestSchema.extend({
119952
- method: literal("session/preview-revoke"),
119953
- params: object$1({
119954
- sessionId: string$2().trim().min(1),
119955
- requestedByUserId: string$2().trim().min(1),
119956
- reason: string$2().trim().min(1).optional()
119957
- }).strict()
119958
- }).strict();
119959
- const LoroLocalProjectGitStateRpcRequestSchema = BaseRpcRequestSchema.extend({
119960
- method: literal("local-project/git-state"),
119961
- params: object$1({
119962
- localProjectId: string$2().trim().min(1),
119963
- requestedByUserId: string$2().trim().min(1)
119964
- }).strict()
119965
- }).strict();
119966
- const LoroLocalProjectControlRpcRequestSchema = BaseRpcRequestSchema.extend({
119967
- method: literal("local-project/control"),
119968
- params: object$1({
119969
- request: LocalProjectControlRequestSchema
119970
- }).strict()
119971
- }).strict();
119972
- const LoroStreamsRpcRequestSchema = discriminatedUnion("method", [
119973
- LoroMachineStatusRpcRequestSchema,
119974
- LoroMachineAcpCapabilitiesRefreshRpcRequestSchema,
119975
- LoroSessionPreviewCreateRpcRequestSchema,
119976
- LoroSessionPreviewRevokeRpcRequestSchema,
119977
- LoroLocalProjectGitStateRpcRequestSchema,
119978
- LoroLocalProjectControlRpcRequestSchema
119979
- ]);
119980
- discriminatedUnion("success", [
119981
- object$1({
119982
- type: literal("local-project/git-state_response"),
119983
- machineId: string$2().trim().min(1),
119984
- workspaceId: string$2().trim().min(1),
119985
- localProjectId: string$2().trim().min(1),
119986
- success: literal(true),
119987
- state: LocalProjectGitStateSchema,
119988
- observedAtMs: number$3().nonnegative()
119989
- }).strict(),
119990
- object$1({
119991
- type: literal("local-project/git-state_response"),
119992
- machineId: string$2().trim().min(1),
119993
- workspaceId: string$2().trim().min(1),
119994
- localProjectId: string$2().trim().min(1),
119995
- success: literal(false),
119996
- error: string$2().trim().min(1),
119997
- message: string$2().trim().min(1).optional()
119998
- }).strict()
119999
- ]);
120000
- object$1({
120001
- jsonrpc: literal(JSON_RPC_VERSION$1),
120002
- id: string$2().trim().min(1),
120003
- method: LoroStreamsRpcMethodSchema,
120004
- rpcVersion: string$2().trim().min(1),
120005
- machineId: string$2().trim().min(1),
120006
- result: unknown().optional(),
120007
- error: LoroStreamsRpcErrorSchema.optional()
120008
- }).strict().superRefine((value, ctx) => {
120009
- const hasResult = value.result !== void 0;
120010
- const hasError = value.error !== void 0;
120011
- if (hasResult === hasError) {
120012
- ctx.addIssue({
120013
- code: ZodIssueCode$1.custom,
120014
- message: "RPC response must contain exactly one of result or error"
120015
- });
120016
- }
120017
- });
120018
- const JSON_STREAM_CONTENT_TYPE = "application/json";
120019
- class LoroStreamsGatewayError extends Error {
120020
- constructor(message, status, detail) {
120021
- super(message);
120022
- this.status = status;
120023
- this.detail = detail;
120024
- this.name = "LoroStreamsGatewayError";
120025
- }
120026
- }
120027
- const toLoroGatewayError = (action, streamId, error2) => {
120028
- if ("status" in error2 && typeof error2.status === "number") {
120029
- const detail = "detail" in error2 && typeof error2.detail === "string" ? error2.detail : void 0;
120030
- return new LoroStreamsGatewayError(`Failed to ${action} ${streamId}: ${error2.message}`, error2.status, detail);
120031
- }
120032
- return new Error(`Failed to ${action} ${streamId}: ${error2.message}`);
120033
- };
120034
- const unwrapStreamResult = (action, streamId, result) => {
120035
- if (result.ok) {
120036
- return result.result;
120037
- }
120038
- throw toLoroGatewayError(action, streamId, result.result);
120039
- };
120040
- const parseJsonPayload = (payload, streamId, context2) => {
120041
- try {
120042
- return payload.json();
120043
- } catch (error2) {
120044
- const message = error2 instanceof Error ? error2.message : String(error2);
120045
- throw new Error(`Invalid JSON payload for ${streamId} during ${context2}: ${message}`, {
120046
- cause: error2
120047
- });
120048
- }
120049
- };
120050
- const parseJsonBatchPayload = (payload, streamId, context2) => {
120051
- const parsed = parseJsonPayload(payload, streamId, context2);
120052
- if (!Array.isArray(parsed)) {
120053
- throw new Error(`Invalid JSON payload for ${streamId} during ${context2}: expected array`);
120054
- }
120055
- return parsed;
120056
- };
120057
- const parseJsonLivePayload = (payload, streamId, context2) => {
120058
- const parsed = parseJsonPayload(payload, streamId, context2);
120059
- return Array.isArray(parsed) ? parsed : [
120060
- parsed
120061
- ];
120062
- };
120063
- const normalizeRetentionSeconds = (retentionSeconds) => {
120064
- if (typeof retentionSeconds !== "number" || retentionSeconds <= 0) {
120065
- return void 0;
120066
- }
120067
- return Math.trunc(retentionSeconds);
120068
- };
120069
- const isCompatibleExistingJsonStream = (stream2, requestedTtlSeconds) => {
120070
- if (stream2.contentType !== JSON_STREAM_CONTENT_TYPE || stream2.closed) {
120071
- return false;
120072
- }
120073
- if (requestedTtlSeconds === void 0) {
120074
- return stream2.ttlSeconds === void 0 && stream2.expiresAt === void 0;
120075
- }
120076
- if (stream2.ttlSeconds === requestedTtlSeconds) {
120077
- return true;
120078
- }
120079
- return stream2.ttlSeconds === void 0 && stream2.expiresAt === void 0;
120080
- };
120081
- function createLoroStreamsJsonStreamClient(options) {
120082
- const fetchImpl = options.fetchImpl ?? fetch;
120083
- const getStreamUrl = (streamId) => {
120084
- const baseUrl = normalizeLoroGatewayBaseUrl(options.getBaseUrl?.() ?? options.baseUrl);
120085
- return new URL(`${baseUrl}/ds/${encodeURIComponent(options.bucketId)}/${encodeURIComponent(streamId)}`).toString();
118764
+ function createLoroStreamsJsonStreamClient(options) {
118765
+ const fetchImpl = options.fetchImpl ?? fetch;
118766
+ const getStreamUrl = (streamId) => {
118767
+ const baseUrl = normalizeLoroGatewayBaseUrl(options.getBaseUrl?.() ?? options.baseUrl);
118768
+ return new URL(`${baseUrl}/ds/${encodeURIComponent(options.bucketId)}/${encodeURIComponent(streamId)}`).toString();
120086
118769
  };
120087
118770
  const getStreamClient = (streamId) => new StreamsClient({
120088
118771
  url: getStreamUrl(streamId),
@@ -121797,6 +120480,7 @@ ${this.stack.split("\n").slice(1).join("\n")}` : this.toString();
121797
120480
  providers_set: "providers/set",
121798
120481
  session_cancel: "session/cancel",
121799
120482
  session_close: "session/close",
120483
+ session_delete: "session/delete",
121800
120484
  session_fork: "session/fork",
121801
120485
  session_list: "session/list",
121802
120486
  session_load: "session/load",
@@ -121889,6 +120573,15 @@ ${this.stack.split("\n").slice(1).join("\n")}` : this.toString();
121889
120573
  writable
121890
120574
  };
121891
120575
  }
120576
+ function emptyObjectResponse(response) {
120577
+ return response ?? {};
120578
+ }
120579
+ function rejectedPromise(error2) {
120580
+ const promise = Promise.reject(error2);
120581
+ promise.catch(() => {
120582
+ });
120583
+ return promise;
120584
+ }
121892
120585
  class ClientSideConnection {
121893
120586
  connection;
121894
120587
  constructor(toClient, stream2) {
@@ -121897,7 +120590,8 @@ ${this.stack.split("\n").slice(1).join("\n")}` : this.toString();
121897
120590
  switch (method) {
121898
120591
  case CLIENT_METHODS.fs_write_text_file: {
121899
120592
  const validatedParams = zWriteTextFileRequest.parse(params);
121900
- return client.writeTextFile?.(validatedParams);
120593
+ const result = await client.writeTextFile?.(validatedParams);
120594
+ return result ?? {};
121901
120595
  }
121902
120596
  case CLIENT_METHODS.fs_read_text_file: {
121903
120597
  const validatedParams = zReadTextFileRequest.parse(params);
@@ -121963,92 +120657,95 @@ ${this.stack.split("\n").slice(1).join("\n")}` : this.toString();
121963
120657
  };
121964
120658
  this.connection = new Connection(requestHandler, notificationHandler, stream2);
121965
120659
  }
121966
- async initialize(params) {
121967
- return await this.connection.sendRequest(AGENT_METHODS.initialize, params);
120660
+ initialize(params) {
120661
+ return this.connection.sendRequest(AGENT_METHODS.initialize, params);
121968
120662
  }
121969
- async newSession(params) {
121970
- return await this.connection.sendRequest(AGENT_METHODS.session_new, params);
120663
+ newSession(params) {
120664
+ return this.connection.sendRequest(AGENT_METHODS.session_new, params);
121971
120665
  }
121972
- async loadSession(params) {
121973
- return await this.connection.sendRequest(AGENT_METHODS.session_load, params) ?? {};
120666
+ loadSession(params) {
120667
+ return this.connection.sendRequest(AGENT_METHODS.session_load, params, emptyObjectResponse);
121974
120668
  }
121975
- async unstable_forkSession(params) {
121976
- return await this.connection.sendRequest(AGENT_METHODS.session_fork, params);
120669
+ unstable_forkSession(params) {
120670
+ return this.connection.sendRequest(AGENT_METHODS.session_fork, params);
121977
120671
  }
121978
- async listSessions(params) {
121979
- return await this.connection.sendRequest(AGENT_METHODS.session_list, params);
120672
+ listSessions(params) {
120673
+ return this.connection.sendRequest(AGENT_METHODS.session_list, params);
121980
120674
  }
121981
- async resumeSession(params) {
121982
- return await this.connection.sendRequest(AGENT_METHODS.session_resume, params);
120675
+ unstable_deleteSession(params) {
120676
+ return this.connection.sendRequest(AGENT_METHODS.session_delete, params, emptyObjectResponse);
121983
120677
  }
121984
- async closeSession(params) {
121985
- return await this.connection.sendRequest(AGENT_METHODS.session_close, params);
120678
+ resumeSession(params) {
120679
+ return this.connection.sendRequest(AGENT_METHODS.session_resume, params);
121986
120680
  }
121987
- async setSessionMode(params) {
121988
- return await this.connection.sendRequest(AGENT_METHODS.session_set_mode, params) ?? {};
120681
+ closeSession(params) {
120682
+ return this.connection.sendRequest(AGENT_METHODS.session_close, params);
121989
120683
  }
121990
- async unstable_setSessionModel(params) {
121991
- return await this.connection.sendRequest(AGENT_METHODS.session_set_model, params) ?? {};
120684
+ setSessionMode(params) {
120685
+ return this.connection.sendRequest(AGENT_METHODS.session_set_mode, params, emptyObjectResponse);
121992
120686
  }
121993
- async setSessionConfigOption(params) {
121994
- return await this.connection.sendRequest(AGENT_METHODS.session_set_config_option, params);
120687
+ unstable_setSessionModel(params) {
120688
+ return this.connection.sendRequest(AGENT_METHODS.session_set_model, params, emptyObjectResponse);
121995
120689
  }
121996
- async authenticate(params) {
121997
- return await this.connection.sendRequest(AGENT_METHODS.authenticate, params) ?? {};
120690
+ setSessionConfigOption(params) {
120691
+ return this.connection.sendRequest(AGENT_METHODS.session_set_config_option, params);
121998
120692
  }
121999
- async unstable_listProviders(params) {
122000
- return await this.connection.sendRequest(AGENT_METHODS.providers_list, params);
120693
+ authenticate(params) {
120694
+ return this.connection.sendRequest(AGENT_METHODS.authenticate, params, emptyObjectResponse);
122001
120695
  }
122002
- async unstable_setProvider(params) {
122003
- return await this.connection.sendRequest(AGENT_METHODS.providers_set, params) ?? {};
120696
+ unstable_listProviders(params) {
120697
+ return this.connection.sendRequest(AGENT_METHODS.providers_list, params);
122004
120698
  }
122005
- async unstable_disableProvider(params) {
122006
- return await this.connection.sendRequest(AGENT_METHODS.providers_disable, params) ?? {};
120699
+ unstable_setProvider(params) {
120700
+ return this.connection.sendRequest(AGENT_METHODS.providers_set, params, emptyObjectResponse);
122007
120701
  }
122008
- async unstable_logout(params) {
122009
- return await this.connection.sendRequest(AGENT_METHODS.logout, params) ?? {};
120702
+ unstable_disableProvider(params) {
120703
+ return this.connection.sendRequest(AGENT_METHODS.providers_disable, params, emptyObjectResponse);
122010
120704
  }
122011
- async prompt(params) {
122012
- return await this.connection.sendRequest(AGENT_METHODS.session_prompt, params);
120705
+ unstable_logout(params) {
120706
+ return this.connection.sendRequest(AGENT_METHODS.logout, params, emptyObjectResponse);
122013
120707
  }
122014
- async cancel(params) {
122015
- return await this.connection.sendNotification(AGENT_METHODS.session_cancel, params);
120708
+ prompt(params) {
120709
+ return this.connection.sendRequest(AGENT_METHODS.session_prompt, params);
122016
120710
  }
122017
- async unstable_startNes(params) {
122018
- return await this.connection.sendRequest(AGENT_METHODS.nes_start, params);
120711
+ cancel(params) {
120712
+ return this.connection.sendNotification(AGENT_METHODS.session_cancel, params);
122019
120713
  }
122020
- async unstable_suggestNes(params) {
122021
- return await this.connection.sendRequest(AGENT_METHODS.nes_suggest, params);
120714
+ unstable_startNes(params) {
120715
+ return this.connection.sendRequest(AGENT_METHODS.nes_start, params);
122022
120716
  }
122023
- async unstable_closeNes(params) {
122024
- return await this.connection.sendRequest(AGENT_METHODS.nes_close, params) ?? {};
120717
+ unstable_suggestNes(params) {
120718
+ return this.connection.sendRequest(AGENT_METHODS.nes_suggest, params);
122025
120719
  }
122026
- async unstable_didOpenDocument(params) {
122027
- return await this.connection.sendNotification(AGENT_METHODS.document_did_open, params);
120720
+ unstable_closeNes(params) {
120721
+ return this.connection.sendRequest(AGENT_METHODS.nes_close, params, emptyObjectResponse);
122028
120722
  }
122029
- async unstable_didChangeDocument(params) {
122030
- return await this.connection.sendNotification(AGENT_METHODS.document_did_change, params);
120723
+ unstable_didOpenDocument(params) {
120724
+ return this.connection.sendNotification(AGENT_METHODS.document_did_open, params);
122031
120725
  }
122032
- async unstable_didCloseDocument(params) {
122033
- return await this.connection.sendNotification(AGENT_METHODS.document_did_close, params);
120726
+ unstable_didChangeDocument(params) {
120727
+ return this.connection.sendNotification(AGENT_METHODS.document_did_change, params);
122034
120728
  }
122035
- async unstable_didSaveDocument(params) {
122036
- return await this.connection.sendNotification(AGENT_METHODS.document_did_save, params);
120729
+ unstable_didCloseDocument(params) {
120730
+ return this.connection.sendNotification(AGENT_METHODS.document_did_close, params);
122037
120731
  }
122038
- async unstable_didFocusDocument(params) {
122039
- return await this.connection.sendNotification(AGENT_METHODS.document_did_focus, params);
120732
+ unstable_didSaveDocument(params) {
120733
+ return this.connection.sendNotification(AGENT_METHODS.document_did_save, params);
122040
120734
  }
122041
- async unstable_acceptNes(params) {
122042
- return await this.connection.sendNotification(AGENT_METHODS.nes_accept, params);
120735
+ unstable_didFocusDocument(params) {
120736
+ return this.connection.sendNotification(AGENT_METHODS.document_did_focus, params);
122043
120737
  }
122044
- async unstable_rejectNes(params) {
122045
- return await this.connection.sendNotification(AGENT_METHODS.nes_reject, params);
120738
+ unstable_acceptNes(params) {
120739
+ return this.connection.sendNotification(AGENT_METHODS.nes_accept, params);
122046
120740
  }
122047
- async extMethod(method, params) {
122048
- return await this.connection.sendRequest(method, params);
120741
+ unstable_rejectNes(params) {
120742
+ return this.connection.sendNotification(AGENT_METHODS.nes_reject, params);
122049
120743
  }
122050
- async extNotification(method, params) {
122051
- return await this.connection.sendNotification(method, params);
120744
+ extMethod(method, params) {
120745
+ return this.connection.sendRequest(method, params);
120746
+ }
120747
+ extNotification(method, params) {
120748
+ return this.connection.sendNotification(method, params);
122052
120749
  }
122053
120750
  get signal() {
122054
120751
  return this.connection.signal;
@@ -122224,12 +120921,20 @@ ${this.stack.split("\n").slice(1).join("\n")}` : this.toString();
122224
120921
  console.error("Got response to unknown request", response.id);
122225
120922
  }
122226
120923
  }
122227
- sendRequest(method, params) {
122228
- this.throwIfClosed();
120924
+ sendRequest(method, params, mapResponse) {
120925
+ if (this.abortController.signal.aborted) {
120926
+ return rejectedPromise(this.closedReason());
120927
+ }
122229
120928
  const id2 = this.nextRequestId++;
122230
120929
  const responsePromise = new Promise((resolve2, reject) => {
122231
120930
  this.pendingResponses.set(id2, {
122232
- resolve: resolve2,
120931
+ resolve: (response) => {
120932
+ try {
120933
+ resolve2(mapResponse ? mapResponse(response) : response);
120934
+ } catch (error2) {
120935
+ reject(error2);
120936
+ }
120937
+ },
122233
120938
  reject
122234
120939
  });
122235
120940
  });
@@ -122243,18 +120948,18 @@ ${this.stack.split("\n").slice(1).join("\n")}` : this.toString();
122243
120948
  });
122244
120949
  return responsePromise;
122245
120950
  }
122246
- async sendNotification(method, params) {
122247
- this.throwIfClosed();
122248
- await this.sendMessage({
120951
+ sendNotification(method, params) {
120952
+ if (this.abortController.signal.aborted) {
120953
+ return rejectedPromise(this.closedReason());
120954
+ }
120955
+ return this.sendMessage({
122249
120956
  jsonrpc: "2.0",
122250
120957
  method,
122251
120958
  params
122252
120959
  });
122253
120960
  }
122254
- throwIfClosed() {
122255
- if (this.abortController.signal.aborted) {
122256
- throw this.abortController.signal.reason ?? new Error("ACP connection closed");
122257
- }
120961
+ closedReason() {
120962
+ return this.abortController.signal.reason ?? new Error("ACP connection closed");
122258
120963
  }
122259
120964
  async sendMessage(message) {
122260
120965
  this.writeQueue = this.writeQueue.then(async () => {
@@ -123180,7 +121885,7 @@ ${this.stack.split("\n").slice(1).join("\n")}` : this.toString();
123180
121885
  const BuiltinACPSetting = {
123181
121886
  claude: {
123182
121887
  packageName: "acp-extension-claude",
123183
- version: "0.37.0",
121888
+ version: "0.38.0",
123184
121889
  binName: "acp-extension-claude"
123185
121890
  },
123186
121891
  codex: {