@orpc/client 0.0.0-next.2546825 → 0.0.0-next.25532a8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,17 +1,41 @@
1
- import { i as isDefinedError } from './shared/client.DcaJQZfy.mjs';
2
- export { C as COMMON_ORPC_ERROR_DEFS, O as ORPCError, c as createAutoRetryEventIterator, a as fallbackORPCErrorMessage, f as fallbackORPCErrorStatus, m as mapEventIterator, o as onEventIteratorStatusChange, r as registerEventIteratorState, t as toORPCError, u as updateEventIteratorStatus } from './shared/client.DcaJQZfy.mjs';
1
+ import { i as isDefinedError } from './shared/client.jKEwIsRd.mjs';
2
+ export { C as COMMON_ORPC_ERROR_DEFS, O as ORPCError, a as fallbackORPCErrorMessage, f as fallbackORPCErrorStatus, b as isORPCErrorStatus, m as mapEventIterator, t as toORPCError } from './shared/client.jKEwIsRd.mjs';
3
+ export { onError, onFinish, onStart, onSuccess } from '@orpc/shared';
3
4
  export { ErrorEvent } from '@orpc/standard-server';
4
- import '@orpc/shared';
5
+
6
+ async function safe(promise) {
7
+ try {
8
+ const output = await promise;
9
+ return Object.assign(
10
+ [null, output, false, true],
11
+ { error: null, data: output, isDefined: false, isSuccess: true }
12
+ );
13
+ } catch (e) {
14
+ const error = e;
15
+ if (isDefinedError(error)) {
16
+ return Object.assign(
17
+ [error, void 0, true, false],
18
+ { error, data: void 0, isDefined: true, isSuccess: false }
19
+ );
20
+ }
21
+ return Object.assign(
22
+ [error, void 0, false, false],
23
+ { error, data: void 0, isDefined: false, isSuccess: false }
24
+ );
25
+ }
26
+ }
27
+ function resolveFriendlyClientOptions(options) {
28
+ return {
29
+ ...options,
30
+ context: options?.context ?? {}
31
+ // Context only optional if all fields are optional
32
+ };
33
+ }
5
34
 
6
35
  function createORPCClient(link, options) {
7
36
  const path = options?.path ?? [];
8
- const procedureClient = async (...[input, options2]) => {
9
- const optionsOut = {
10
- ...options2,
11
- context: options2?.context ?? {}
12
- // options.context can be undefined when all field is optional
13
- };
14
- return await link.call(path, input, optionsOut);
37
+ const procedureClient = async (...[input, options2 = {}]) => {
38
+ return await link.call(path, input, resolveFriendlyClientOptions(options2));
15
39
  };
16
40
  const recursive = new Proxy(procedureClient, {
17
41
  get(target, key) {
@@ -38,26 +62,4 @@ class DynamicLink {
38
62
  }
39
63
  }
40
64
 
41
- async function safe(promise) {
42
- try {
43
- const output = await promise;
44
- return Object.assign(
45
- [null, output, false],
46
- { error: null, data: output, isDefined: false }
47
- );
48
- } catch (e) {
49
- const error = e;
50
- if (isDefinedError(error)) {
51
- return Object.assign(
52
- [error, void 0, true],
53
- { error, data: void 0, isDefined: true }
54
- );
55
- }
56
- return Object.assign(
57
- [error, void 0, false],
58
- { error, data: void 0, isDefined: false }
59
- );
60
- }
61
- }
62
-
63
- export { DynamicLink, createORPCClient, isDefinedError, safe };
65
+ export { DynamicLink, createORPCClient, isDefinedError, resolveFriendlyClientOptions, safe };
@@ -0,0 +1,50 @@
1
+ import { Value } from '@orpc/shared';
2
+ import { S as StandardLinkInterceptorOptions, a as StandardLinkPlugin, b as StandardLinkOptions } from '../shared/client.C486S9aU.mjs';
3
+ import { a as ClientContext } from '../shared/client.CipPQkhk.mjs';
4
+ import '@orpc/standard-server';
5
+
6
+ interface ClientRetryPluginAttemptOptions<T extends ClientContext> extends StandardLinkInterceptorOptions<T> {
7
+ lastEventRetry: number | undefined;
8
+ attemptIndex: number;
9
+ error: unknown;
10
+ }
11
+ interface ClientRetryPluginContext {
12
+ /**
13
+ * Maximum retry attempts before throwing
14
+ * Use `Number.POSITIVE_INFINITY` for infinite retries (e.g., when handling Server-Sent Events).
15
+ *
16
+ * @default 0
17
+ */
18
+ retry?: Value<number, [StandardLinkInterceptorOptions<ClientRetryPluginContext>]>;
19
+ /**
20
+ * Delay (in ms) before retrying.
21
+ *
22
+ * @default (o) => o.lastEventRetry ?? 2000
23
+ */
24
+ retryDelay?: Value<number, [ClientRetryPluginAttemptOptions<ClientRetryPluginContext>]>;
25
+ /**
26
+ * Determine should retry or not.
27
+ *
28
+ * @default true
29
+ */
30
+ shouldRetry?: Value<boolean, [ClientRetryPluginAttemptOptions<ClientRetryPluginContext>]>;
31
+ /**
32
+ * The hook called when retrying, and return the unsubscribe function.
33
+ */
34
+ onRetry?: (options: ClientRetryPluginAttemptOptions<ClientRetryPluginContext>) => void | (() => void);
35
+ }
36
+ declare class ClientRetryPluginInvalidEventIteratorRetryResponse extends Error {
37
+ }
38
+ interface ClientRetryPluginOptions {
39
+ default?: ClientRetryPluginContext;
40
+ }
41
+ declare class ClientRetryPlugin<T extends ClientRetryPluginContext> implements StandardLinkPlugin<T> {
42
+ private readonly defaultRetry;
43
+ private readonly defaultRetryDelay;
44
+ private readonly defaultShouldRetry;
45
+ private readonly defaultOnRetry;
46
+ constructor(options?: ClientRetryPluginOptions);
47
+ init(options: StandardLinkOptions<T>): void;
48
+ }
49
+
50
+ export { ClientRetryPlugin, type ClientRetryPluginAttemptOptions, type ClientRetryPluginContext, ClientRetryPluginInvalidEventIteratorRetryResponse, type ClientRetryPluginOptions };
@@ -0,0 +1,50 @@
1
+ import { Value } from '@orpc/shared';
2
+ import { S as StandardLinkInterceptorOptions, a as StandardLinkPlugin, b as StandardLinkOptions } from '../shared/client.qdWq4aGG.js';
3
+ import { a as ClientContext } from '../shared/client.CipPQkhk.js';
4
+ import '@orpc/standard-server';
5
+
6
+ interface ClientRetryPluginAttemptOptions<T extends ClientContext> extends StandardLinkInterceptorOptions<T> {
7
+ lastEventRetry: number | undefined;
8
+ attemptIndex: number;
9
+ error: unknown;
10
+ }
11
+ interface ClientRetryPluginContext {
12
+ /**
13
+ * Maximum retry attempts before throwing
14
+ * Use `Number.POSITIVE_INFINITY` for infinite retries (e.g., when handling Server-Sent Events).
15
+ *
16
+ * @default 0
17
+ */
18
+ retry?: Value<number, [StandardLinkInterceptorOptions<ClientRetryPluginContext>]>;
19
+ /**
20
+ * Delay (in ms) before retrying.
21
+ *
22
+ * @default (o) => o.lastEventRetry ?? 2000
23
+ */
24
+ retryDelay?: Value<number, [ClientRetryPluginAttemptOptions<ClientRetryPluginContext>]>;
25
+ /**
26
+ * Determine should retry or not.
27
+ *
28
+ * @default true
29
+ */
30
+ shouldRetry?: Value<boolean, [ClientRetryPluginAttemptOptions<ClientRetryPluginContext>]>;
31
+ /**
32
+ * The hook called when retrying, and return the unsubscribe function.
33
+ */
34
+ onRetry?: (options: ClientRetryPluginAttemptOptions<ClientRetryPluginContext>) => void | (() => void);
35
+ }
36
+ declare class ClientRetryPluginInvalidEventIteratorRetryResponse extends Error {
37
+ }
38
+ interface ClientRetryPluginOptions {
39
+ default?: ClientRetryPluginContext;
40
+ }
41
+ declare class ClientRetryPlugin<T extends ClientRetryPluginContext> implements StandardLinkPlugin<T> {
42
+ private readonly defaultRetry;
43
+ private readonly defaultRetryDelay;
44
+ private readonly defaultShouldRetry;
45
+ private readonly defaultOnRetry;
46
+ constructor(options?: ClientRetryPluginOptions);
47
+ init(options: StandardLinkOptions<T>): void;
48
+ }
49
+
50
+ export { ClientRetryPlugin, type ClientRetryPluginAttemptOptions, type ClientRetryPluginContext, ClientRetryPluginInvalidEventIteratorRetryResponse, type ClientRetryPluginOptions };
@@ -0,0 +1,111 @@
1
+ import { value, isAsyncIteratorObject } from '@orpc/shared';
2
+ import { getEventMeta } from '@orpc/standard-server';
3
+
4
+ class ClientRetryPluginInvalidEventIteratorRetryResponse extends Error {
5
+ }
6
+ class ClientRetryPlugin {
7
+ defaultRetry;
8
+ defaultRetryDelay;
9
+ defaultShouldRetry;
10
+ defaultOnRetry;
11
+ constructor(options = {}) {
12
+ this.defaultRetry = options.default?.retry ?? 0;
13
+ this.defaultRetryDelay = options.default?.retryDelay ?? ((o) => o.lastEventRetry ?? 2e3);
14
+ this.defaultShouldRetry = options.default?.shouldRetry ?? true;
15
+ this.defaultOnRetry = options.default?.onRetry;
16
+ }
17
+ init(options) {
18
+ options.interceptors ??= [];
19
+ options.interceptors.push(async (interceptorOptions) => {
20
+ const maxAttempts = await value(
21
+ interceptorOptions.context.retry ?? this.defaultRetry,
22
+ interceptorOptions
23
+ );
24
+ const retryDelay = interceptorOptions.context.retryDelay ?? this.defaultRetryDelay;
25
+ const shouldRetry = interceptorOptions.context.shouldRetry ?? this.defaultShouldRetry;
26
+ const onRetry = interceptorOptions.context.onRetry ?? this.defaultOnRetry;
27
+ if (maxAttempts <= 0) {
28
+ return interceptorOptions.next();
29
+ }
30
+ let lastEventId = interceptorOptions.lastEventId;
31
+ let lastEventRetry;
32
+ let unsubscribe;
33
+ let attemptIndex = 0;
34
+ const next = async (initial) => {
35
+ let current = initial;
36
+ while (true) {
37
+ const updatedInterceptorOptions = { ...interceptorOptions, lastEventId };
38
+ if (current) {
39
+ if (attemptIndex >= maxAttempts) {
40
+ throw current.error;
41
+ }
42
+ const attemptOptions = {
43
+ ...updatedInterceptorOptions,
44
+ attemptIndex,
45
+ error: current.error,
46
+ lastEventRetry
47
+ };
48
+ const shouldRetryBool = await value(
49
+ shouldRetry,
50
+ attemptOptions
51
+ );
52
+ if (!shouldRetryBool) {
53
+ throw current.error;
54
+ }
55
+ unsubscribe = onRetry?.(attemptOptions);
56
+ const retryDelayMs = await value(retryDelay, attemptOptions);
57
+ await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
58
+ attemptIndex++;
59
+ }
60
+ try {
61
+ return await interceptorOptions.next(updatedInterceptorOptions);
62
+ } catch (error) {
63
+ if (updatedInterceptorOptions.signal?.aborted === true) {
64
+ throw error;
65
+ }
66
+ current = { error };
67
+ } finally {
68
+ unsubscribe?.();
69
+ unsubscribe = void 0;
70
+ }
71
+ }
72
+ };
73
+ const output = await next();
74
+ if (!isAsyncIteratorObject(output)) {
75
+ return output;
76
+ }
77
+ return async function* () {
78
+ let current = output;
79
+ try {
80
+ while (true) {
81
+ try {
82
+ const item = await current.next();
83
+ const meta = getEventMeta(item.value);
84
+ lastEventId = meta?.id ?? lastEventId;
85
+ lastEventRetry = meta?.retry ?? lastEventRetry;
86
+ if (item.done) {
87
+ return item.value;
88
+ }
89
+ yield item.value;
90
+ } catch (error) {
91
+ const meta = getEventMeta(error);
92
+ lastEventId = meta?.id ?? lastEventId;
93
+ lastEventRetry = meta?.retry ?? lastEventRetry;
94
+ const maybeEventIterator = await next({ error });
95
+ if (!isAsyncIteratorObject(maybeEventIterator)) {
96
+ throw new ClientRetryPluginInvalidEventIteratorRetryResponse(
97
+ "RetryPlugin: Expected an Event Iterator, got a non-Event Iterator"
98
+ );
99
+ }
100
+ current = maybeEventIterator;
101
+ }
102
+ }
103
+ } finally {
104
+ await current.return?.();
105
+ }
106
+ }();
107
+ });
108
+ }
109
+ }
110
+
111
+ export { ClientRetryPlugin, ClientRetryPluginInvalidEventIteratorRetryResponse };
@@ -1,106 +1,107 @@
1
- import { intercept, isAsyncIteratorObject, value, isObject, trim, stringifyJSON } from '@orpc/shared';
2
- import { c as createAutoRetryEventIterator, O as ORPCError, m as mapEventIterator, t as toORPCError } from './client.DcaJQZfy.mjs';
3
- import { ErrorEvent } from '@orpc/standard-server';
1
+ import { toArray, intercept, isObject, value, isAsyncIteratorObject, stringifyJSON } from '@orpc/shared';
2
+ import { mergeStandardHeaders, ErrorEvent } from '@orpc/standard-server';
3
+ import { C as COMMON_ORPC_ERROR_DEFS, b as isORPCErrorStatus, O as ORPCError, m as mapEventIterator, t as toORPCError } from './client.jKEwIsRd.mjs';
4
4
 
5
5
  class InvalidEventIteratorRetryResponse extends Error {
6
6
  }
7
7
  class StandardLink {
8
- constructor(codec, sender, options) {
8
+ constructor(codec, sender, options = {}) {
9
9
  this.codec = codec;
10
10
  this.sender = sender;
11
- this.eventIteratorMaxRetries = options.eventIteratorMaxRetries ?? 5;
12
- this.eventIteratorRetryDelay = options.eventIteratorRetryDelay ?? ((o) => o.lastRetry ?? 1e3 * 2 ** o.retryTimes);
13
- this.eventIteratorShouldRetry = options.eventIteratorShouldRetry ?? true;
14
- this.interceptors = options.interceptors ?? [];
15
- this.clientInterceptors = options.clientInterceptors ?? [];
11
+ for (const plugin of toArray(options.plugins)) {
12
+ plugin.init?.(options);
13
+ }
14
+ this.interceptors = toArray(options.interceptors);
15
+ this.clientInterceptors = toArray(options.clientInterceptors);
16
16
  }
17
- eventIteratorMaxRetries;
18
- eventIteratorRetryDelay;
19
- eventIteratorShouldRetry;
20
17
  interceptors;
21
18
  clientInterceptors;
22
19
  call(path, input, options) {
23
- return intercept(this.interceptors, { path, input, options }, async ({ path: path2, input: input2, options: options2 }) => {
20
+ return intercept(this.interceptors, { ...options, path, input }, async ({ path: path2, input: input2, ...options2 }) => {
24
21
  const output = await this.#call(path2, input2, options2);
25
- if (!isAsyncIteratorObject(output)) {
26
- return output;
27
- }
28
- return createAutoRetryEventIterator(output, async (reconnectOptions) => {
29
- const maxRetries = await value(this.eventIteratorMaxRetries, reconnectOptions, options2, path2, input2);
30
- if (options2.signal?.aborted || reconnectOptions.retryTimes > maxRetries) {
31
- return null;
32
- }
33
- const shouldRetry = await value(this.eventIteratorShouldRetry, reconnectOptions, options2, path2, input2);
34
- if (!shouldRetry) {
35
- return null;
36
- }
37
- const retryDelay = await value(this.eventIteratorRetryDelay, reconnectOptions, options2, path2, input2);
38
- await new Promise((resolve) => setTimeout(resolve, retryDelay));
39
- const updatedOptions = { ...options2, lastEventId: reconnectOptions.lastEventId };
40
- const maybeIterator = await this.#call(path2, input2, updatedOptions);
41
- if (!isAsyncIteratorObject(maybeIterator)) {
42
- throw new InvalidEventIteratorRetryResponse("Invalid Event Iterator retry response");
43
- }
44
- return maybeIterator;
45
- }, options2.lastEventId);
22
+ return output;
46
23
  });
47
24
  }
48
25
  async #call(path, input, options) {
49
26
  const request = await this.codec.encode(path, input, options);
50
27
  const response = await intercept(
51
28
  this.clientInterceptors,
52
- { request },
53
- ({ request: request2 }) => this.sender.call(request2, options, path, input)
29
+ { ...options, input, path, request },
30
+ ({ input: input2, path: path2, request: request2, ...options2 }) => this.sender.call(request2, options2, path2, input2)
54
31
  );
55
32
  const output = await this.codec.decode(response, options, path, input);
56
33
  return output;
57
34
  }
58
35
  }
59
36
 
60
- class RPCJsonSerializer {
37
+ const STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES = {
38
+ BIGINT: 0,
39
+ DATE: 1,
40
+ NAN: 2,
41
+ UNDEFINED: 3,
42
+ URL: 4,
43
+ REGEXP: 5,
44
+ SET: 6,
45
+ MAP: 7
46
+ };
47
+ class StandardRPCJsonSerializer {
48
+ customSerializers;
49
+ constructor(options = {}) {
50
+ this.customSerializers = options.customJsonSerializers ?? [];
51
+ if (this.customSerializers.length !== new Set(this.customSerializers.map((custom) => custom.type)).size) {
52
+ throw new Error("Custom serializer type must be unique.");
53
+ }
54
+ }
61
55
  serialize(data, segments = [], meta = [], maps = [], blobs = []) {
56
+ for (const custom of this.customSerializers) {
57
+ if (custom.condition(data)) {
58
+ const result = this.serialize(custom.serialize(data), segments, meta, maps, blobs);
59
+ meta.push([custom.type, ...segments]);
60
+ return result;
61
+ }
62
+ }
62
63
  if (data instanceof Blob) {
63
64
  maps.push(segments);
64
65
  blobs.push(data);
65
66
  return [data, meta, maps, blobs];
66
67
  }
67
68
  if (typeof data === "bigint") {
68
- meta.push([0, segments]);
69
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.BIGINT, ...segments]);
69
70
  return [data.toString(), meta, maps, blobs];
70
71
  }
71
72
  if (data instanceof Date) {
72
- meta.push([1, segments]);
73
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.DATE, ...segments]);
73
74
  if (Number.isNaN(data.getTime())) {
74
75
  return [null, meta, maps, blobs];
75
76
  }
76
77
  return [data.toISOString(), meta, maps, blobs];
77
78
  }
78
79
  if (Number.isNaN(data)) {
79
- meta.push([2, segments]);
80
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.NAN, ...segments]);
80
81
  return [null, meta, maps, blobs];
81
82
  }
82
83
  if (data instanceof URL) {
83
- meta.push([4, segments]);
84
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.URL, ...segments]);
84
85
  return [data.toString(), meta, maps, blobs];
85
86
  }
86
87
  if (data instanceof RegExp) {
87
- meta.push([5, segments]);
88
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.REGEXP, ...segments]);
88
89
  return [data.toString(), meta, maps, blobs];
89
90
  }
90
91
  if (data instanceof Set) {
91
92
  const result = this.serialize(Array.from(data), segments, meta, maps, blobs);
92
- meta.push([6, segments]);
93
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.SET, ...segments]);
93
94
  return result;
94
95
  }
95
96
  if (data instanceof Map) {
96
97
  const result = this.serialize(Array.from(data.entries()), segments, meta, maps, blobs);
97
- meta.push([7, segments]);
98
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.MAP, ...segments]);
98
99
  return result;
99
100
  }
100
101
  if (Array.isArray(data)) {
101
102
  const json = data.map((v, i) => {
102
103
  if (v === void 0) {
103
- meta.push([3, [...segments, i]]);
104
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.UNDEFINED, ...segments, i]);
104
105
  return v;
105
106
  }
106
107
  return this.serialize(v, [...segments, i], meta, maps, blobs)[0];
@@ -110,6 +111,9 @@ class RPCJsonSerializer {
110
111
  if (isObject(data)) {
111
112
  const json = {};
112
113
  for (const k in data) {
114
+ if (k === "toJSON" && typeof data[k] === "function") {
115
+ continue;
116
+ }
113
117
  json[k] = this.serialize(data[k], [...segments, k], meta, maps, blobs)[0];
114
118
  }
115
119
  return [json, meta, maps, blobs];
@@ -129,38 +133,45 @@ class RPCJsonSerializer {
129
133
  currentRef[preSegment] = getBlob(i);
130
134
  });
131
135
  }
132
- for (const [type, segments] of meta) {
136
+ for (const item of meta) {
137
+ const type = item[0];
133
138
  let currentRef = ref;
134
139
  let preSegment = "data";
135
- segments.forEach((segment) => {
140
+ for (let i = 1; i < item.length; i++) {
136
141
  currentRef = currentRef[preSegment];
137
- preSegment = segment;
138
- });
142
+ preSegment = item[i];
143
+ }
144
+ for (const custom of this.customSerializers) {
145
+ if (custom.type === type) {
146
+ currentRef[preSegment] = custom.deserialize(currentRef[preSegment]);
147
+ break;
148
+ }
149
+ }
139
150
  switch (type) {
140
- case 0:
151
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.BIGINT:
141
152
  currentRef[preSegment] = BigInt(currentRef[preSegment]);
142
153
  break;
143
- case 1:
154
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.DATE:
144
155
  currentRef[preSegment] = new Date(currentRef[preSegment] ?? "Invalid Date");
145
156
  break;
146
- case 2:
157
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.NAN:
147
158
  currentRef[preSegment] = Number.NaN;
148
159
  break;
149
- case 3:
160
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.UNDEFINED:
150
161
  currentRef[preSegment] = void 0;
151
162
  break;
152
- case 4:
163
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.URL:
153
164
  currentRef[preSegment] = new URL(currentRef[preSegment]);
154
165
  break;
155
- case 5: {
166
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.REGEXP: {
156
167
  const [, pattern, flags] = currentRef[preSegment].match(/^\/(.*)\/([a-z]*)$/);
157
168
  currentRef[preSegment] = new RegExp(pattern, flags);
158
169
  break;
159
170
  }
160
- case 6:
171
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.SET:
161
172
  currentRef[preSegment] = new Set(currentRef[preSegment]);
162
173
  break;
163
- case 7:
174
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.MAP:
164
175
  currentRef[preSegment] = new Map(currentRef[preSegment]);
165
176
  break;
166
177
  }
@@ -169,6 +180,13 @@ class RPCJsonSerializer {
169
180
  }
170
181
  }
171
182
 
183
+ function toHttpPath(path) {
184
+ return `/${path.map(encodeURIComponent).join("/")}`;
185
+ }
186
+ function getMalformedResponseErrorCode(status) {
187
+ return Object.entries(COMMON_ORPC_ERROR_DEFS).find(([, def]) => def.status === status)?.[0] ?? "MALFORMED_ORPC_ERROR_RESPONSE";
188
+ }
189
+
172
190
  class StandardRPCLinkCodec {
173
191
  constructor(serializer, options) {
174
192
  this.serializer = serializer;
@@ -184,15 +202,20 @@ class StandardRPCLinkCodec {
184
202
  expectedMethod;
185
203
  headers;
186
204
  async encode(path, input, options) {
187
- const expectedMethod = await value(this.expectedMethod, options, path, input);
188
- const headers = await value(this.headers, options, path, input);
189
- const baseUrl = await value(this.baseUrl, options, path, input);
190
- const url = new URL(`${trim(baseUrl.toString(), "/")}/${path.map(encodeURIComponent).join("/")}`);
205
+ const generalOptions = { ...options, path, input };
206
+ const expectedMethod = await value(this.expectedMethod, generalOptions);
207
+ let headers = await value(this.headers, generalOptions);
208
+ const baseUrl = await value(this.baseUrl, generalOptions);
209
+ const url = new URL(baseUrl);
210
+ url.pathname = `${url.pathname.replace(/\/$/, "")}${toHttpPath(path)}`;
211
+ if (options.lastEventId !== void 0) {
212
+ headers = mergeStandardHeaders(headers, { "last-event-id": options.lastEventId });
213
+ }
191
214
  const serialized = this.serializer.serialize(input);
192
- if (expectedMethod === "GET" && !(serialized instanceof FormData) && !(serialized instanceof Blob) && !isAsyncIteratorObject(serialized)) {
193
- const maxUrlLength = await value(this.maxUrlLength, options, path, input);
215
+ if (expectedMethod === "GET" && !(serialized instanceof FormData) && !isAsyncIteratorObject(serialized)) {
216
+ const maxUrlLength = await value(this.maxUrlLength, generalOptions);
194
217
  const getUrl = new URL(url);
195
- getUrl.searchParams.append("data", stringifyJSON(serialized) ?? "");
218
+ getUrl.searchParams.append("data", stringifyJSON(serialized));
196
219
  if (getUrl.toString().length <= maxUrlLength) {
197
220
  return {
198
221
  body: void 0,
@@ -212,7 +235,7 @@ class StandardRPCLinkCodec {
212
235
  };
213
236
  }
214
237
  async decode(response) {
215
- const isOk = response.status >= 200 && response.status < 300;
238
+ const isOk = !isORPCErrorStatus(response.status);
216
239
  const deserialized = await (async () => {
217
240
  let isBodyOk = false;
218
241
  try {
@@ -234,16 +257,17 @@ class StandardRPCLinkCodec {
234
257
  if (ORPCError.isValidJSON(deserialized)) {
235
258
  throw ORPCError.fromJSON(deserialized);
236
259
  }
237
- throw new Error("Invalid RPC error response format.", {
238
- cause: deserialized
260
+ throw new ORPCError(getMalformedResponseErrorCode(response.status), {
261
+ status: response.status,
262
+ data: deserialized
239
263
  });
240
264
  }
241
265
  return deserialized;
242
266
  }
243
267
  }
244
268
 
245
- class RPCSerializer {
246
- constructor(jsonSerializer = new RPCJsonSerializer()) {
269
+ class StandardRPCSerializer {
270
+ constructor(jsonSerializer) {
247
271
  this.jsonSerializer = jsonSerializer;
248
272
  }
249
273
  serialize(data) {
@@ -261,9 +285,6 @@ class RPCSerializer {
261
285
  return this.#serialize(data, true);
262
286
  }
263
287
  #serialize(data, enableFormData) {
264
- if (data === void 0 || data instanceof Blob) {
265
- return data;
266
- }
267
288
  const [json, meta_, maps, blobs] = this.jsonSerializer.serialize(data);
268
289
  const meta = meta_.length === 0 ? void 0 : meta_;
269
290
  if (!enableFormData || blobs.length === 0) {
@@ -301,9 +322,6 @@ class RPCSerializer {
301
322
  return this.#deserialize(data);
302
323
  }
303
324
  #deserialize(data) {
304
- if (data === void 0 || data instanceof Blob) {
305
- return data;
306
- }
307
325
  if (!(data instanceof FormData)) {
308
326
  return this.jsonSerializer.deserialize(data.json, data.meta ?? []);
309
327
  }
@@ -317,4 +335,4 @@ class RPCSerializer {
317
335
  }
318
336
  }
319
337
 
320
- export { InvalidEventIteratorRetryResponse as I, RPCJsonSerializer as R, StandardLink as S, StandardRPCLinkCodec as a, RPCSerializer as b };
338
+ export { InvalidEventIteratorRetryResponse as I, StandardLink as S, STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES as a, StandardRPCJsonSerializer as b, StandardRPCLinkCodec as c, StandardRPCSerializer as d, getMalformedResponseErrorCode as g, toHttpPath as t };