@vite-hub/source 0.1.0 → 0.3.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.
Files changed (48) hide show
  1. package/README.md +83 -49
  2. package/dist/client.d.ts +1 -1
  3. package/dist/client.js +30 -4
  4. package/dist/{collection-B_4w_J8h.d.ts → collection-B8sgxw5-.d.ts} +52 -19
  5. package/dist/collection-C0Rvrx3p.js +297 -0
  6. package/dist/drizzle.d.ts +11 -4
  7. package/dist/drizzle.js +6 -8
  8. package/dist/error-diagnostics-ClQKdi7c.js +194 -0
  9. package/dist/github-D5S0dEZe.js +1312 -0
  10. package/dist/{glob-BmFqTvJY.js → glob-DmdMVqjx.js} +1 -2
  11. package/dist/index.d.ts +186 -55
  12. package/dist/index.js +152 -207
  13. package/dist/invariant-DolT9EEx.js +22 -0
  14. package/dist/mcp.d.ts +1 -1
  15. package/dist/mcp.js +25 -140
  16. package/dist/object-CtSHeGQO.js +17 -0
  17. package/dist/{path-BS8rYm0n.js → path-DFlSryRA.js} +32 -2
  18. package/dist/root-DJNmqCEW.js +11 -0
  19. package/dist/server.d.ts +7 -244
  20. package/dist/server.js +38 -45
  21. package/dist/{types-BigOktIj.d.ts → types-Ln-FxVFn.d.ts} +6 -1
  22. package/dist/vite.d.ts +77 -10
  23. package/dist/vite.js +619 -713
  24. package/package.json +25 -47
  25. package/dist/auth-B-tX_rp0.js +0 -1426
  26. package/dist/client-BwstxtdY.js +0 -8280
  27. package/dist/collection-cursor-WzV1Jd6v.js +0 -124
  28. package/dist/error-diagnostics-X0kuFjBT.js +0 -51
  29. package/dist/file-BX0FSvgE.js +0 -60
  30. package/dist/file-DadN9dbN.d.ts +0 -19
  31. package/dist/file.d.ts +0 -2
  32. package/dist/file.js +0 -2
  33. package/dist/files.d.ts +0 -15
  34. package/dist/files.js +0 -38
  35. package/dist/github.d.ts +0 -20
  36. package/dist/github.js +0 -1332
  37. package/dist/glob.d.ts +0 -23
  38. package/dist/glob.js +0 -2
  39. package/dist/markdown.d.ts +0 -5
  40. package/dist/markdown.js +0 -10
  41. package/dist/mrmime-40h5OOIp.js +0 -448
  42. package/dist/path-DOBpV8ol.js +0 -32
  43. package/dist/sse-D9gqqNPj.js +0 -448
  44. package/dist/streamableHttp-BL-E7pl5.js +0 -509
  45. package/dist/types-CoWcW8oz.js +0 -7590
  46. package/tsconfig.vite.json +0 -6
  47. package/types/source/fallback.d.ts +0 -1
  48. package/types/source/index.d.ts +0 -1
@@ -1,448 +0,0 @@
1
- import { x as JSONRPCMessageSchema } from "./types-CoWcW8oz.js";
2
- import { a as fetchLeavingRedirects, c as normalizeHeaders, i as createFetchWithInit, l as unfollowedRedirect, n as auth, o as fetchWithinOrigin, r as extractWWWAuthenticateParams, t as UnauthorizedError, u as createParser } from "./auth-B-tX_rp0.js";
3
- //#region ../../node_modules/.pnpm/eventsource@3.0.7/node_modules/eventsource/dist/index.js
4
- var ErrorEvent = class extends Event {
5
- /**
6
- * Constructs a new `ErrorEvent` instance. This is typically not called directly,
7
- * but rather emitted by the `EventSource` object when an error occurs.
8
- *
9
- * @param type - The type of the event (should be "error")
10
- * @param errorEventInitDict - Optional properties to include in the error event
11
- */
12
- constructor(type, errorEventInitDict) {
13
- var _a, _b;
14
- super(type), this.code = (_a = errorEventInitDict == null ? void 0 : errorEventInitDict.code) != null ? _a : void 0, this.message = (_b = errorEventInitDict == null ? void 0 : errorEventInitDict.message) != null ? _b : void 0;
15
- }
16
- /**
17
- * Node.js "hides" the `message` and `code` properties of the `ErrorEvent` instance,
18
- * when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging,
19
- * we explicitly include the properties in the `inspect` method.
20
- *
21
- * This is automatically called by Node.js when you `console.log` an instance of this class.
22
- *
23
- * @param _depth - The current depth
24
- * @param options - The options passed to `util.inspect`
25
- * @param inspect - The inspect function to use (prevents having to import it from `util`)
26
- * @returns A string representation of the error
27
- */
28
- [Symbol.for("nodejs.util.inspect.custom")](_depth, options, inspect) {
29
- return inspect(inspectableError(this), options);
30
- }
31
- /**
32
- * Deno "hides" the `message` and `code` properties of the `ErrorEvent` instance,
33
- * when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging,
34
- * we explicitly include the properties in the `inspect` method.
35
- *
36
- * This is automatically called by Deno when you `console.log` an instance of this class.
37
- *
38
- * @param inspect - The inspect function to use (prevents having to import it from `util`)
39
- * @param options - The options passed to `Deno.inspect`
40
- * @returns A string representation of the error
41
- */
42
- [Symbol.for("Deno.customInspect")](inspect, options) {
43
- return inspect(inspectableError(this), options);
44
- }
45
- };
46
- function syntaxError(message) {
47
- const DomException = globalThis.DOMException;
48
- return typeof DomException == "function" ? new DomException(message, "SyntaxError") : new SyntaxError(message);
49
- }
50
- function flattenError(err) {
51
- return err instanceof Error ? "errors" in err && Array.isArray(err.errors) ? err.errors.map(flattenError).join(", ") : "cause" in err && err.cause instanceof Error ? `${err}: ${flattenError(err.cause)}` : err.message : `${err}`;
52
- }
53
- function inspectableError(err) {
54
- return {
55
- type: err.type,
56
- message: err.message,
57
- code: err.code,
58
- defaultPrevented: err.defaultPrevented,
59
- cancelable: err.cancelable,
60
- timeStamp: err.timeStamp
61
- };
62
- }
63
- var __typeError = (msg) => {
64
- throw TypeError(msg);
65
- };
66
- var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
67
- var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
68
- var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
69
- var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value);
70
- var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
71
- var _readyState;
72
- var _url;
73
- var _redirectUrl;
74
- var _withCredentials;
75
- var _fetch;
76
- var _reconnectInterval;
77
- var _reconnectTimer;
78
- var _lastEventId;
79
- var _controller;
80
- var _parser;
81
- var _onError;
82
- var _onMessage;
83
- var _onOpen;
84
- var _EventSource_instances;
85
- var connect_fn;
86
- var _onFetchResponse;
87
- var _onFetchError;
88
- var getRequestOptions_fn;
89
- var _onEvent;
90
- var _onRetryChange;
91
- var failConnection_fn;
92
- var scheduleReconnect_fn;
93
- var _reconnect;
94
- var EventSource = class extends EventTarget {
95
- constructor(url, eventSourceInitDict) {
96
- var _a, _b;
97
- super(), __privateAdd(this, _EventSource_instances), this.CONNECTING = 0, this.OPEN = 1, this.CLOSED = 2, __privateAdd(this, _readyState), __privateAdd(this, _url), __privateAdd(this, _redirectUrl), __privateAdd(this, _withCredentials), __privateAdd(this, _fetch), __privateAdd(this, _reconnectInterval), __privateAdd(this, _reconnectTimer), __privateAdd(this, _lastEventId, null), __privateAdd(this, _controller), __privateAdd(this, _parser), __privateAdd(this, _onError, null), __privateAdd(this, _onMessage, null), __privateAdd(this, _onOpen, null), __privateAdd(this, _onFetchResponse, async (response) => {
98
- var _a2;
99
- __privateGet(this, _parser).reset();
100
- const { body, redirected, status, headers } = response;
101
- if (status === 204) {
102
- __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, "Server sent HTTP 204, not reconnecting", 204), this.close();
103
- return;
104
- }
105
- if (redirected ? __privateSet(this, _redirectUrl, new URL(response.url)) : __privateSet(this, _redirectUrl, void 0), status !== 200) {
106
- __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, `Non-200 status code (${status})`, status);
107
- return;
108
- }
109
- if (!(headers.get("content-type") || "").startsWith("text/event-stream")) {
110
- __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, "Invalid content type, expected \"text/event-stream\"", status);
111
- return;
112
- }
113
- if (__privateGet(this, _readyState) === this.CLOSED) return;
114
- __privateSet(this, _readyState, this.OPEN);
115
- const openEvent = new Event("open");
116
- if ((_a2 = __privateGet(this, _onOpen)) == null || _a2.call(this, openEvent), this.dispatchEvent(openEvent), typeof body != "object" || !body || !("getReader" in body)) {
117
- __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, "Invalid response body, expected a web ReadableStream", status), this.close();
118
- return;
119
- }
120
- const decoder = new TextDecoder(), reader = body.getReader();
121
- let open = !0;
122
- do {
123
- const { done, value } = await reader.read();
124
- value && __privateGet(this, _parser).feed(decoder.decode(value, { stream: !done })), done && (open = !1, __privateGet(this, _parser).reset(), __privateMethod(this, _EventSource_instances, scheduleReconnect_fn).call(this));
125
- } while (open);
126
- }), __privateAdd(this, _onFetchError, (err) => {
127
- __privateSet(this, _controller, void 0), err.name !== "AbortError" && err.type !== "aborted" && __privateMethod(this, _EventSource_instances, scheduleReconnect_fn).call(this, flattenError(err));
128
- }), __privateAdd(this, _onEvent, (event) => {
129
- typeof event.id == "string" && __privateSet(this, _lastEventId, event.id);
130
- const messageEvent = new MessageEvent(event.event || "message", {
131
- data: event.data,
132
- origin: __privateGet(this, _redirectUrl) ? __privateGet(this, _redirectUrl).origin : __privateGet(this, _url).origin,
133
- lastEventId: event.id || ""
134
- });
135
- __privateGet(this, _onMessage) && (!event.event || event.event === "message") && __privateGet(this, _onMessage).call(this, messageEvent), this.dispatchEvent(messageEvent);
136
- }), __privateAdd(this, _onRetryChange, (value) => {
137
- __privateSet(this, _reconnectInterval, value);
138
- }), __privateAdd(this, _reconnect, () => {
139
- __privateSet(this, _reconnectTimer, void 0), __privateGet(this, _readyState) === this.CONNECTING && __privateMethod(this, _EventSource_instances, connect_fn).call(this);
140
- });
141
- try {
142
- if (url instanceof URL) __privateSet(this, _url, url);
143
- else if (typeof url == "string") __privateSet(this, _url, new URL(url, getBaseURL()));
144
- else throw new Error("Invalid URL");
145
- } catch {
146
- throw syntaxError("An invalid or illegal string was specified");
147
- }
148
- __privateSet(this, _parser, createParser({
149
- onEvent: __privateGet(this, _onEvent),
150
- onRetry: __privateGet(this, _onRetryChange)
151
- })), __privateSet(this, _readyState, this.CONNECTING), __privateSet(this, _reconnectInterval, 3e3), __privateSet(this, _fetch, (_a = eventSourceInitDict == null ? void 0 : eventSourceInitDict.fetch) != null ? _a : globalThis.fetch), __privateSet(this, _withCredentials, (_b = eventSourceInitDict == null ? void 0 : eventSourceInitDict.withCredentials) != null ? _b : !1), __privateMethod(this, _EventSource_instances, connect_fn).call(this);
152
- }
153
- /**
154
- * Returns the state of this EventSource object's connection. It can have the values described below.
155
- *
156
- * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState)
157
- *
158
- * Note: typed as `number` instead of `0 | 1 | 2` for compatibility with the `EventSource` interface,
159
- * defined in the TypeScript `dom` library.
160
- *
161
- * @public
162
- */
163
- get readyState() {
164
- return __privateGet(this, _readyState);
165
- }
166
- /**
167
- * Returns the URL providing the event stream.
168
- *
169
- * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url)
170
- *
171
- * @public
172
- */
173
- get url() {
174
- return __privateGet(this, _url).href;
175
- }
176
- /**
177
- * Returns true if the credentials mode for connection requests to the URL providing the event stream is set to "include", and false otherwise.
178
- *
179
- * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials)
180
- */
181
- get withCredentials() {
182
- return __privateGet(this, _withCredentials);
183
- }
184
- /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */
185
- get onerror() {
186
- return __privateGet(this, _onError);
187
- }
188
- set onerror(value) {
189
- __privateSet(this, _onError, value);
190
- }
191
- /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */
192
- get onmessage() {
193
- return __privateGet(this, _onMessage);
194
- }
195
- set onmessage(value) {
196
- __privateSet(this, _onMessage, value);
197
- }
198
- /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */
199
- get onopen() {
200
- return __privateGet(this, _onOpen);
201
- }
202
- set onopen(value) {
203
- __privateSet(this, _onOpen, value);
204
- }
205
- addEventListener(type, listener, options) {
206
- const listen = listener;
207
- super.addEventListener(type, listen, options);
208
- }
209
- removeEventListener(type, listener, options) {
210
- const listen = listener;
211
- super.removeEventListener(type, listen, options);
212
- }
213
- /**
214
- * Aborts any instances of the fetch algorithm started for this EventSource object, and sets the readyState attribute to CLOSED.
215
- *
216
- * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close)
217
- *
218
- * @public
219
- */
220
- close() {
221
- __privateGet(this, _reconnectTimer) && clearTimeout(__privateGet(this, _reconnectTimer)), __privateGet(this, _readyState) !== this.CLOSED && (__privateGet(this, _controller) && __privateGet(this, _controller).abort(), __privateSet(this, _readyState, this.CLOSED), __privateSet(this, _controller, void 0));
222
- }
223
- };
224
- _readyState = /* @__PURE__ */ new WeakMap(), _url = /* @__PURE__ */ new WeakMap(), _redirectUrl = /* @__PURE__ */ new WeakMap(), _withCredentials = /* @__PURE__ */ new WeakMap(), _fetch = /* @__PURE__ */ new WeakMap(), _reconnectInterval = /* @__PURE__ */ new WeakMap(), _reconnectTimer = /* @__PURE__ */ new WeakMap(), _lastEventId = /* @__PURE__ */ new WeakMap(), _controller = /* @__PURE__ */ new WeakMap(), _parser = /* @__PURE__ */ new WeakMap(), _onError = /* @__PURE__ */ new WeakMap(), _onMessage = /* @__PURE__ */ new WeakMap(), _onOpen = /* @__PURE__ */ new WeakMap(), _EventSource_instances = /* @__PURE__ */ new WeakSet(), connect_fn = function() {
225
- __privateSet(this, _readyState, this.CONNECTING), __privateSet(this, _controller, new AbortController()), __privateGet(this, _fetch)(__privateGet(this, _url), __privateMethod(this, _EventSource_instances, getRequestOptions_fn).call(this)).then(__privateGet(this, _onFetchResponse)).catch(__privateGet(this, _onFetchError));
226
- }, _onFetchResponse = /* @__PURE__ */ new WeakMap(), _onFetchError = /* @__PURE__ */ new WeakMap(), getRequestOptions_fn = function() {
227
- var _a;
228
- const init = {
229
- mode: "cors",
230
- redirect: "follow",
231
- headers: {
232
- Accept: "text/event-stream",
233
- ...__privateGet(this, _lastEventId) ? { "Last-Event-ID": __privateGet(this, _lastEventId) } : void 0
234
- },
235
- cache: "no-store",
236
- signal: (_a = __privateGet(this, _controller)) == null ? void 0 : _a.signal
237
- };
238
- return "window" in globalThis && (init.credentials = this.withCredentials ? "include" : "same-origin"), init;
239
- }, _onEvent = /* @__PURE__ */ new WeakMap(), _onRetryChange = /* @__PURE__ */ new WeakMap(), failConnection_fn = function(message, code) {
240
- var _a;
241
- __privateGet(this, _readyState) !== this.CLOSED && __privateSet(this, _readyState, this.CLOSED);
242
- const errorEvent = new ErrorEvent("error", {
243
- code,
244
- message
245
- });
246
- (_a = __privateGet(this, _onError)) == null || _a.call(this, errorEvent), this.dispatchEvent(errorEvent);
247
- }, scheduleReconnect_fn = function(message, code) {
248
- var _a;
249
- if (__privateGet(this, _readyState) === this.CLOSED) return;
250
- __privateSet(this, _readyState, this.CONNECTING);
251
- const errorEvent = new ErrorEvent("error", {
252
- code,
253
- message
254
- });
255
- (_a = __privateGet(this, _onError)) == null || _a.call(this, errorEvent), this.dispatchEvent(errorEvent), __privateSet(this, _reconnectTimer, setTimeout(__privateGet(this, _reconnect), __privateGet(this, _reconnectInterval)));
256
- }, _reconnect = /* @__PURE__ */ new WeakMap(), EventSource.CONNECTING = 0, EventSource.OPEN = 1, EventSource.CLOSED = 2;
257
- function getBaseURL() {
258
- const doc = "document" in globalThis ? globalThis.document : void 0;
259
- return doc && typeof doc == "object" && "baseURI" in doc && typeof doc.baseURI == "string" ? doc.baseURI : void 0;
260
- }
261
- //#endregion
262
- //#region ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.1_@cfworker+json-schema@4.1.1_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js
263
- var SseError = class extends Error {
264
- constructor(code, message, event) {
265
- super(`SSE error: ${message}`);
266
- this.code = code;
267
- this.event = event;
268
- }
269
- };
270
- /**
271
- * Client transport for SSE: this will connect to a server using Server-Sent Events for receiving
272
- * messages and make separate POST requests for sending messages.
273
- * @deprecated SSEClientTransport is deprecated. Prefer to use StreamableHTTPClientTransport where possible instead. Note that because some servers are still using SSE, clients may need to support both transports during the migration period.
274
- */
275
- var SSEClientTransport = class {
276
- constructor(url, opts) {
277
- this._url = url;
278
- this._resourceMetadataUrl = void 0;
279
- this._scope = void 0;
280
- this._eventSourceInit = opts?.eventSourceInit;
281
- this._requestInit = opts?.requestInit;
282
- this._authProvider = opts?.authProvider;
283
- this._fetch = opts?.fetch;
284
- this._fetchWithInit = createFetchWithInit(opts?.fetch, opts?.requestInit);
285
- this._followRedirects = opts?.redirectPolicy === "follow";
286
- if (this._followRedirects) {
287
- this._fetch = fetchLeavingRedirects(this._fetch);
288
- this._fetchWithInit = fetchLeavingRedirects(this._fetchWithInit);
289
- }
290
- }
291
- /** Error text for a redirect `response` that was not followed, or `undefined` for any other response. */
292
- _unfollowedRedirect(response, url) {
293
- const text = unfollowedRedirect(response, url);
294
- return text && !this._followRedirects ? `${text} (redirectPolicy: 'same-origin')` : text;
295
- }
296
- async _authThenStart() {
297
- if (!this._authProvider) throw new UnauthorizedError("No auth provider");
298
- let result;
299
- try {
300
- result = await auth(this._authProvider, {
301
- serverUrl: this._url,
302
- resourceMetadataUrl: this._resourceMetadataUrl,
303
- scope: this._scope,
304
- fetchFn: this._fetchWithInit
305
- });
306
- } catch (error) {
307
- this.onerror?.(error);
308
- throw error;
309
- }
310
- if (result !== "AUTHORIZED") throw new UnauthorizedError();
311
- return await this._startOrAuth();
312
- }
313
- async _commonHeaders() {
314
- const headers = {};
315
- if (this._authProvider) {
316
- const tokens = await this._authProvider.tokens();
317
- if (tokens) headers["Authorization"] = `Bearer ${tokens.access_token}`;
318
- }
319
- if (this._protocolVersion) headers["mcp-protocol-version"] = this._protocolVersion;
320
- const extraHeaders = normalizeHeaders(this._requestInit?.headers);
321
- return new Headers({
322
- ...headers,
323
- ...extraHeaders
324
- });
325
- }
326
- _startOrAuth() {
327
- const baseFetch = this?._eventSourceInit?.fetch ?? this._fetch ?? fetch;
328
- const fetchImpl = this._followRedirects ? baseFetch : fetchWithinOrigin(baseFetch);
329
- let redirect;
330
- return new Promise((resolve, reject) => {
331
- this._eventSource = new EventSource(this._url.href, {
332
- ...this._eventSourceInit,
333
- fetch: async (url, init) => {
334
- const headers = await this._commonHeaders();
335
- headers.set("Accept", "text/event-stream");
336
- const response = await fetchImpl(url, {
337
- ...init,
338
- headers
339
- });
340
- redirect = this._unfollowedRedirect(response, url);
341
- if (response.status === 401 && response.headers.has("www-authenticate")) {
342
- const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response);
343
- this._resourceMetadataUrl = resourceMetadataUrl;
344
- this._scope = scope;
345
- }
346
- return response;
347
- }
348
- });
349
- this._abortController = new AbortController();
350
- this._eventSource.onerror = (event) => {
351
- if (event.code === 401 && this._authProvider) {
352
- this._authThenStart().then(resolve, reject);
353
- return;
354
- }
355
- const error = new SseError(event.code, redirect ?? event.message, event);
356
- reject(error);
357
- this.onerror?.(error);
358
- };
359
- this._eventSource.onopen = () => {};
360
- this._eventSource.addEventListener("endpoint", (event) => {
361
- const messageEvent = event;
362
- try {
363
- this._endpoint = new URL(messageEvent.data, this._url);
364
- if (this._endpoint.origin !== this._url.origin) throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`);
365
- } catch (error) {
366
- reject(error);
367
- this.onerror?.(error);
368
- this.close();
369
- return;
370
- }
371
- resolve();
372
- });
373
- this._eventSource.onmessage = (event) => {
374
- const messageEvent = event;
375
- let message;
376
- try {
377
- message = JSONRPCMessageSchema.parse(JSON.parse(messageEvent.data));
378
- } catch (error) {
379
- this.onerror?.(error);
380
- return;
381
- }
382
- this.onmessage?.(message);
383
- };
384
- });
385
- }
386
- async start() {
387
- if (this._eventSource) throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");
388
- return await this._startOrAuth();
389
- }
390
- /**
391
- * Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth.
392
- */
393
- async finishAuth(authorizationCode) {
394
- if (!this._authProvider) throw new UnauthorizedError("No auth provider");
395
- if (await auth(this._authProvider, {
396
- serverUrl: this._url,
397
- authorizationCode,
398
- resourceMetadataUrl: this._resourceMetadataUrl,
399
- scope: this._scope,
400
- fetchFn: this._fetchWithInit
401
- }) !== "AUTHORIZED") throw new UnauthorizedError("Failed to authorize");
402
- }
403
- async close() {
404
- this._abortController?.abort();
405
- this._eventSource?.close();
406
- this.onclose?.();
407
- }
408
- async send(message) {
409
- if (!this._endpoint) throw new Error("Not connected");
410
- try {
411
- const headers = await this._commonHeaders();
412
- headers.set("content-type", "application/json");
413
- const init = {
414
- ...this._requestInit,
415
- method: "POST",
416
- headers,
417
- body: JSON.stringify(message),
418
- signal: this._abortController?.signal
419
- };
420
- const response = await fetchWithinOrigin(this._fetch ?? fetch)(this._endpoint, init);
421
- if (!response.ok) {
422
- const text = await response.text().catch(() => null);
423
- if (response.status === 401 && this._authProvider) {
424
- const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response);
425
- this._resourceMetadataUrl = resourceMetadataUrl;
426
- this._scope = scope;
427
- if (await auth(this._authProvider, {
428
- serverUrl: this._url,
429
- resourceMetadataUrl: this._resourceMetadataUrl,
430
- scope: this._scope,
431
- fetchFn: this._fetchWithInit
432
- }) !== "AUTHORIZED") throw new UnauthorizedError();
433
- return this.send(message);
434
- }
435
- throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${this._unfollowedRedirect(response, this._endpoint) ?? text}`);
436
- }
437
- await response.body?.cancel();
438
- } catch (error) {
439
- this.onerror?.(error);
440
- throw error;
441
- }
442
- }
443
- setProtocolVersion(version) {
444
- this._protocolVersion = version;
445
- }
446
- };
447
- //#endregion
448
- export { SSEClientTransport };