@kivacore/api-client 0.0.0 → 0.3.8

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 ADDED
@@ -0,0 +1,1486 @@
1
+ // src/core/errors.ts
2
+ var ApiError = class _ApiError extends Error {
3
+ status;
4
+ code;
5
+ details;
6
+ action;
7
+ constructor(message, status, code, details, action) {
8
+ super(message);
9
+ this.name = "ApiError";
10
+ this.status = status;
11
+ this.code = code;
12
+ this.details = details;
13
+ this.action = action;
14
+ if (Error.captureStackTrace) {
15
+ Error.captureStackTrace(this, _ApiError);
16
+ }
17
+ }
18
+ toJSON() {
19
+ return {
20
+ name: this.name,
21
+ message: this.message,
22
+ status: this.status,
23
+ code: this.code,
24
+ details: this.details,
25
+ action: this.action
26
+ };
27
+ }
28
+ };
29
+ var NetworkError = class extends ApiError {
30
+ constructor(message, details) {
31
+ super(message, void 0, "NETWORK_ERROR", details);
32
+ this.name = "NetworkError";
33
+ }
34
+ };
35
+ var TimeoutError = class extends ApiError {
36
+ constructor(message, timeout) {
37
+ super(message, void 0, "TIMEOUT_ERROR", { timeout });
38
+ this.name = "TimeoutError";
39
+ }
40
+ };
41
+ var AbortError = class extends ApiError {
42
+ constructor(message = "Request was aborted") {
43
+ super(message, void 0, "ABORT_ERROR");
44
+ this.name = "AbortError";
45
+ }
46
+ };
47
+ var ValidationError = class extends ApiError {
48
+ constructor(message, details) {
49
+ super(message, 400, "VALIDATION_ERROR", details);
50
+ this.name = "ValidationError";
51
+ }
52
+ };
53
+ var AuthenticationError = class extends ApiError {
54
+ constructor(message = "Authentication required") {
55
+ super(message, 401, "AUTH_ERROR");
56
+ this.name = "AuthenticationError";
57
+ }
58
+ };
59
+ var AuthorizationError = class extends ApiError {
60
+ constructor(message = "Insufficient permissions") {
61
+ super(message, 403, "FORBIDDEN");
62
+ this.name = "AuthorizationError";
63
+ }
64
+ };
65
+ var NotFoundError = class extends ApiError {
66
+ constructor(resource) {
67
+ super(`Resource not found: ${resource}`, 404, "NOT_FOUND", { resource });
68
+ this.name = "NotFoundError";
69
+ }
70
+ };
71
+ var ConflictError = class extends ApiError {
72
+ constructor(message, details) {
73
+ super(message, 409, "CONFLICT", details);
74
+ this.name = "ConflictError";
75
+ }
76
+ };
77
+ var RateLimitError = class extends ApiError {
78
+ constructor(retryAfter) {
79
+ super("Rate limit exceeded", 429, "RATE_LIMIT", { retryAfter });
80
+ this.name = "RateLimitError";
81
+ }
82
+ };
83
+ var ServerError = class extends ApiError {
84
+ constructor(message = "Internal server error", status = 500, details) {
85
+ super(message, status, "SERVER_ERROR", details);
86
+ this.name = "ServerError";
87
+ }
88
+ };
89
+ var GenericError = class extends ApiError {
90
+ payload;
91
+ constructor(error, action, payload) {
92
+ super(error.message, void 0, void 0, payload, action);
93
+ this.name = "GenericError";
94
+ this.payload = payload || {};
95
+ }
96
+ };
97
+ var OAuth2Error = class extends ApiError {
98
+ errorCode;
99
+ errorDescription;
100
+ errorUri;
101
+ constructor(errorCode, errorDescription, errorUri) {
102
+ super(errorDescription || errorCode, void 0, errorCode);
103
+ this.name = "OAuth2Error";
104
+ this.errorCode = errorCode;
105
+ this.errorDescription = errorDescription;
106
+ this.errorUri = errorUri;
107
+ }
108
+ };
109
+ var InvalidGrantError = class extends OAuth2Error {
110
+ constructor(description) {
111
+ super("invalid_grant", description || "The authorization code or refresh token is invalid or expired");
112
+ this.name = "InvalidGrantError";
113
+ }
114
+ };
115
+ var InvalidClientError = class extends OAuth2Error {
116
+ constructor(description) {
117
+ super("invalid_client", description || "Client authentication failed");
118
+ this.name = "InvalidClientError";
119
+ }
120
+ };
121
+ var InvalidScopeError = class extends OAuth2Error {
122
+ constructor(description) {
123
+ super("invalid_scope", description || "The requested scope is invalid or unknown");
124
+ this.name = "InvalidScopeError";
125
+ }
126
+ };
127
+ var AuthorizationPendingError = class extends OAuth2Error {
128
+ constructor() {
129
+ super("authorization_pending", "The user has not yet completed the authorization");
130
+ this.name = "AuthorizationPendingError";
131
+ }
132
+ };
133
+ var SlowDownError = class extends OAuth2Error {
134
+ constructor() {
135
+ super("slow_down", "Polling too frequently, please slow down");
136
+ this.name = "SlowDownError";
137
+ }
138
+ };
139
+ var ExpiredTokenError = class extends OAuth2Error {
140
+ constructor() {
141
+ super("expired_token", "The device code or user code has expired");
142
+ this.name = "ExpiredTokenError";
143
+ }
144
+ };
145
+ var AccessDeniedError = class extends OAuth2Error {
146
+ constructor(description) {
147
+ super("access_denied", description || "The user denied the authorization request");
148
+ this.name = "AccessDeniedError";
149
+ }
150
+ };
151
+
152
+ // src/core/utils.ts
153
+ function jsonToQueryString(data) {
154
+ if (!data || Object.keys(data).length === 0) {
155
+ return "";
156
+ }
157
+ const params = new URLSearchParams();
158
+ Object.entries(data).forEach(([key, value]) => {
159
+ if (value === void 0) return;
160
+ if (value !== null && (typeof value === "object" || Array.isArray(value))) {
161
+ params.append(key, JSON.stringify(value));
162
+ } else {
163
+ params.append(key, String(value));
164
+ }
165
+ });
166
+ const queryString = params.toString();
167
+ return queryString ? `?${queryString}` : "";
168
+ }
169
+ async function withRetry(fn, retries = 3, retryDelay = 1e3, retryCondition) {
170
+ let lastError = new Error("All retry attempts failed");
171
+ for (let attempt = 0; attempt <= retries; attempt++) {
172
+ try {
173
+ return await fn();
174
+ } catch (error) {
175
+ lastError = error;
176
+ if (attempt === retries) {
177
+ throw lastError;
178
+ }
179
+ if (retryCondition && !retryCondition(lastError, attempt)) {
180
+ throw lastError;
181
+ }
182
+ if (!retryCondition) {
183
+ const isRetryable = lastError.name === "NetworkError" || lastError.name === "TimeoutError" || lastError.name === "ApiError" && "status" in lastError && typeof lastError.status === "number" && lastError.status >= 500;
184
+ if (!isRetryable) {
185
+ throw lastError;
186
+ }
187
+ }
188
+ const delay = retryDelay * Math.pow(2, attempt);
189
+ await new Promise((resolve) => setTimeout(resolve, delay));
190
+ }
191
+ }
192
+ throw lastError;
193
+ }
194
+ function isAbortError(error) {
195
+ return error instanceof Error && (error.name === "AbortError" || error.message === "The user aborted a request.");
196
+ }
197
+ function parseContentDisposition(header) {
198
+ if (!header) return null;
199
+ const filenameMatch = header.match(/filename\*?=["']?(?:UTF-\d['"]*)?([^;"'\n]*)["']?/i);
200
+ return filenameMatch?.[1] || null;
201
+ }
202
+ function buildUrl(baseURL, path, params) {
203
+ const cleanBase = baseURL.replace(/\/$/, "");
204
+ const cleanPath = path.replace(/^\//, "");
205
+ let url = `${cleanBase}/${cleanPath}`;
206
+ if (params) {
207
+ url += jsonToQueryString(params);
208
+ }
209
+ return url;
210
+ }
211
+ function isFormData(data) {
212
+ return typeof FormData !== "undefined" && data instanceof FormData;
213
+ }
214
+ function isBlob(data) {
215
+ return typeof Blob !== "undefined" && data instanceof Blob;
216
+ }
217
+ function isStream(data) {
218
+ return typeof ReadableStream !== "undefined" && data instanceof ReadableStream;
219
+ }
220
+ function prepareFilterQueryForApi(query) {
221
+ return JSON.stringify(query);
222
+ }
223
+ function createAbortSignal(timeout, signal) {
224
+ const controller = new AbortController();
225
+ let timeoutId = null;
226
+ if (timeout) {
227
+ timeoutId = setTimeout(() => controller.abort(), timeout);
228
+ }
229
+ if (signal) {
230
+ signal.addEventListener("abort", () => controller.abort());
231
+ }
232
+ return {
233
+ signal: controller.signal,
234
+ cleanup: () => {
235
+ if (timeoutId) {
236
+ clearTimeout(timeoutId);
237
+ }
238
+ }
239
+ };
240
+ }
241
+
242
+ // src/core/token-manager.ts
243
+ var MemoryTokenManager = class {
244
+ token = null;
245
+ getToken() {
246
+ return this.token;
247
+ }
248
+ setToken(token) {
249
+ this.token = token;
250
+ }
251
+ clearToken() {
252
+ this.token = null;
253
+ }
254
+ };
255
+ var StorageTokenManager = class {
256
+ constructor(storage = typeof window !== "undefined" ? window.localStorage : null, key = "api_token") {
257
+ this.storage = storage;
258
+ this.key = key;
259
+ }
260
+ storage;
261
+ key;
262
+ getToken() {
263
+ if (!this.storage) return null;
264
+ return this.storage.getItem(this.key);
265
+ }
266
+ setToken(token) {
267
+ if (!this.storage) return;
268
+ this.storage.setItem(this.key, token);
269
+ }
270
+ clearToken() {
271
+ if (!this.storage) return;
272
+ this.storage.removeItem(this.key);
273
+ }
274
+ };
275
+ var AsyncTokenManager = class {
276
+ constructor(getTokenFn, setTokenFn, clearTokenFn, refreshTokenFn) {
277
+ this.getTokenFn = getTokenFn;
278
+ this.setTokenFn = setTokenFn;
279
+ this.clearTokenFn = clearTokenFn;
280
+ this.refreshTokenFn = refreshTokenFn;
281
+ }
282
+ getTokenFn;
283
+ setTokenFn;
284
+ clearTokenFn;
285
+ refreshTokenFn;
286
+ getToken() {
287
+ return this.getTokenFn();
288
+ }
289
+ setToken(token) {
290
+ return this.setTokenFn(token);
291
+ }
292
+ clearToken() {
293
+ return this.clearTokenFn();
294
+ }
295
+ refreshToken() {
296
+ if (!this.refreshTokenFn) {
297
+ return Promise.reject(new Error("Token refresh not supported"));
298
+ }
299
+ return this.refreshTokenFn();
300
+ }
301
+ };
302
+
303
+ // src/clients/base-client.ts
304
+ var BaseApiClient = class {
305
+ baseURL;
306
+ tokenManager;
307
+ interceptors = [];
308
+ defaultHeaders = {};
309
+ fetchImpl;
310
+ FormDataImpl;
311
+ AbortControllerImpl;
312
+ storage;
313
+ defaultTimeout;
314
+ downloadHandler;
315
+ constructor(config = {}) {
316
+ this.baseURL = config.baseURL || "";
317
+ this.tokenManager = config.tokenManager || new MemoryTokenManager();
318
+ this.defaultHeaders = config.headers || {};
319
+ this.defaultTimeout = config.timeout;
320
+ this.downloadHandler = config.downloadHandler;
321
+ const rawFetch = config.fetch || globalThis.fetch;
322
+ if (!rawFetch) {
323
+ throw new Error("Fetch API is not available. Please provide a fetch implementation.");
324
+ }
325
+ this.fetchImpl = rawFetch.bind(globalThis);
326
+ this.FormDataImpl = config.FormData || globalThis.FormData;
327
+ this.AbortControllerImpl = config.AbortController || globalThis.AbortController;
328
+ this.storage = config.storage;
329
+ if (!this.fetchImpl) {
330
+ throw new Error("Fetch API is not available. Please provide a fetch implementation.");
331
+ }
332
+ }
333
+ addInterceptor(interceptor) {
334
+ this.interceptors.push(interceptor);
335
+ }
336
+ removeInterceptor(interceptor) {
337
+ const index = this.interceptors.indexOf(interceptor);
338
+ if (index !== -1) {
339
+ this.interceptors.splice(index, 1);
340
+ }
341
+ }
342
+ async setAccessToken(token) {
343
+ const result = this.tokenManager.setToken(token);
344
+ if (result instanceof Promise) {
345
+ await result;
346
+ }
347
+ }
348
+ async getAccessToken() {
349
+ const result = this.tokenManager.getToken();
350
+ return result instanceof Promise ? await result : result;
351
+ }
352
+ async clearAccessToken() {
353
+ const result = this.tokenManager.clearToken();
354
+ if (result instanceof Promise) {
355
+ await result;
356
+ }
357
+ }
358
+ async applyRequestInterceptors(config) {
359
+ let currentConfig = config;
360
+ for (const interceptor of this.interceptors) {
361
+ if (interceptor.request) {
362
+ currentConfig = await interceptor.request(currentConfig);
363
+ }
364
+ }
365
+ return currentConfig;
366
+ }
367
+ async applyResponseInterceptors(response) {
368
+ let currentResponse = response;
369
+ for (const interceptor of this.interceptors) {
370
+ if (interceptor.response) {
371
+ currentResponse = await interceptor.response(currentResponse);
372
+ }
373
+ }
374
+ return currentResponse;
375
+ }
376
+ async applyErrorInterceptors(error) {
377
+ let currentError = error;
378
+ for (const interceptor of this.interceptors) {
379
+ if (interceptor.error) {
380
+ try {
381
+ const result = await interceptor.error(currentError);
382
+ if (result instanceof Error) {
383
+ currentError = result;
384
+ }
385
+ } catch (e) {
386
+ currentError = e;
387
+ }
388
+ }
389
+ }
390
+ throw currentError;
391
+ }
392
+ async prepareHeaders(config) {
393
+ const headers = new Headers(this.defaultHeaders);
394
+ const token = await this.getAccessToken();
395
+ if (token) {
396
+ headers.set("Authorization", `Bearer ${token}`);
397
+ }
398
+ if (config.headers) {
399
+ const configHeaders = config.headers instanceof Headers ? config.headers : new Headers(config.headers);
400
+ configHeaders.forEach((value, key) => {
401
+ headers.set(key, value);
402
+ });
403
+ }
404
+ if (this.storage && typeof globalThis.sessionStorage !== "undefined") {
405
+ try {
406
+ const tid = globalThis.sessionStorage.getItem("tid");
407
+ if (tid) {
408
+ headers.set("X-Tid", tid);
409
+ }
410
+ } catch {
411
+ }
412
+ }
413
+ return headers;
414
+ }
415
+ prepareBody(data, headers) {
416
+ if (!data) return void 0;
417
+ if (isFormData(data) || isBlob(data) || isStream(data)) {
418
+ return data;
419
+ }
420
+ if (typeof data === "string") {
421
+ headers.set("Content-Type", "text/plain");
422
+ return data;
423
+ }
424
+ headers.set("Content-Type", "application/json");
425
+ return JSON.stringify(data);
426
+ }
427
+ createApiError(response, errorData) {
428
+ const { status } = response;
429
+ let message = errorData?.message || errorData?.error || response.statusText;
430
+ const details = errorData?.details || errorData;
431
+ if (errorData && typeof errorData === "object") {
432
+ if (errorData.error && typeof errorData.error === "object") {
433
+ message = errorData.error.message || JSON.stringify(errorData.error);
434
+ } else if (errorData.message) {
435
+ ({ message } = errorData);
436
+ }
437
+ }
438
+ switch (status) {
439
+ case 400:
440
+ return new ValidationError(message, details);
441
+ case 401:
442
+ return new AuthenticationError(message);
443
+ case 403:
444
+ return new AuthorizationError(message);
445
+ case 404:
446
+ return new NotFoundError(response.url);
447
+ case 409:
448
+ return new ConflictError(message, details);
449
+ case 429:
450
+ return new RateLimitError(details?.retryAfter);
451
+ default:
452
+ if (status >= 500) {
453
+ return new ServerError(message, status, details);
454
+ }
455
+ return new ApiError(message, status, void 0, details);
456
+ }
457
+ }
458
+ async request(method, endpoint, data, config = {}) {
459
+ config = await this.applyRequestInterceptors(config);
460
+ const url = buildUrl(this.baseURL, endpoint, config.params);
461
+ const headers = await this.prepareHeaders(config);
462
+ const body = ["GET", "HEAD"].includes(method) ? void 0 : this.prepareBody(data, headers);
463
+ const { signal, cleanup } = createAbortSignal(
464
+ config.timeout || this.defaultTimeout,
465
+ config.signal || void 0
466
+ );
467
+ const fetchOptions = {
468
+ ...config,
469
+ method,
470
+ headers,
471
+ body,
472
+ signal
473
+ };
474
+ const executeRequest = async () => {
475
+ const response = await this.fetchImpl(url, fetchOptions);
476
+ if (!response.ok) {
477
+ let errorData;
478
+ try {
479
+ const contentType = response.headers.get("Content-Type") || "";
480
+ if (contentType.includes("application/json")) {
481
+ errorData = await response.json();
482
+ } else {
483
+ errorData = await response.text();
484
+ }
485
+ } catch {
486
+ }
487
+ throw this.createApiError(response, errorData);
488
+ }
489
+ const responseType = config.responseType || "json";
490
+ let responseData;
491
+ switch (responseType) {
492
+ case "blob":
493
+ responseData = await response.blob();
494
+ break;
495
+ case "text":
496
+ responseData = await response.text();
497
+ break;
498
+ case "arrayBuffer":
499
+ responseData = await response.arrayBuffer();
500
+ break;
501
+ case "formData":
502
+ responseData = await response.formData();
503
+ break;
504
+ default:
505
+ try {
506
+ responseData = await response.json();
507
+ } catch {
508
+ responseData = null;
509
+ }
510
+ }
511
+ const apiResponse = {
512
+ data: responseData,
513
+ headers: response.headers,
514
+ status: response.status,
515
+ statusText: response.statusText
516
+ };
517
+ return await this.applyResponseInterceptors(apiResponse);
518
+ };
519
+ try {
520
+ if (config.retries !== void 0 && config.retries > 0) {
521
+ return await withRetry(
522
+ executeRequest,
523
+ config.retries,
524
+ config.retryDelay,
525
+ config.retryCondition
526
+ );
527
+ }
528
+ return await executeRequest();
529
+ } catch (error) {
530
+ cleanup();
531
+ if (isAbortError(error)) {
532
+ throw new AbortError();
533
+ }
534
+ if (error instanceof TypeError && error.message === "Failed to fetch") {
535
+ throw new NetworkError("Network request failed");
536
+ }
537
+ if (error instanceof AuthenticationError && this.tokenManager.refreshToken) {
538
+ let refreshSucceeded = false;
539
+ try {
540
+ const newToken = await this.tokenManager.refreshToken();
541
+ headers.set("Authorization", `Bearer ${newToken}`);
542
+ refreshSucceeded = true;
543
+ } catch {
544
+ }
545
+ if (refreshSucceeded) {
546
+ return await executeRequest();
547
+ }
548
+ }
549
+ if (error instanceof ApiError) {
550
+ return this.applyErrorInterceptors(error);
551
+ }
552
+ throw new ApiError(
553
+ error instanceof Error ? error.message : "Unknown error occurred",
554
+ void 0,
555
+ "UNKNOWN_ERROR"
556
+ );
557
+ } finally {
558
+ cleanup();
559
+ }
560
+ }
561
+ async get(endpoint, params, config) {
562
+ const response = await this.request("GET", endpoint, void 0, { ...config, params });
563
+ return response.data;
564
+ }
565
+ async post(endpoint, data, config) {
566
+ const response = await this.request("POST", endpoint, data, config);
567
+ return response.data;
568
+ }
569
+ async put(endpoint, data, config) {
570
+ const response = await this.request("PUT", endpoint, data, config);
571
+ return response.data;
572
+ }
573
+ async runCustomQuery(customQueryId, options, config) {
574
+ return this.put(`reports/custom-queries/${customQueryId}/run`, options, config);
575
+ }
576
+ async patch(endpoint, data, config) {
577
+ const response = await this.request("PATCH", endpoint, data, config);
578
+ return response.data;
579
+ }
580
+ async delete(endpoint, data, config) {
581
+ const response = await this.request("DELETE", endpoint, data, config);
582
+ return response.data;
583
+ }
584
+ async download(endpoint, data, config) {
585
+ const response = await this.request("POST", endpoint, data, {
586
+ ...config,
587
+ responseType: "blob"
588
+ });
589
+ const contentDisposition = response.headers.get("content-disposition");
590
+ let filename = "download";
591
+ if (contentDisposition) {
592
+ const match = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
593
+ if (match && match[1]) {
594
+ filename = match[1].replace(/['"]/g, "");
595
+ }
596
+ }
597
+ if (this.downloadHandler) {
598
+ await this.downloadHandler(response.data, filename);
599
+ return;
600
+ }
601
+ if (typeof document === "undefined" || typeof URL.createObjectURL !== "function") {
602
+ throw new Error("File download requires a browser environment or a custom downloadHandler");
603
+ }
604
+ const url = URL.createObjectURL(response.data);
605
+ const link = document.createElement("a");
606
+ link.href = url;
607
+ link.download = filename;
608
+ document.body.appendChild(link);
609
+ link.click();
610
+ document.body.removeChild(link);
611
+ setTimeout(() => URL.revokeObjectURL(url), 100);
612
+ }
613
+ async *stream(endpoint, options) {
614
+ const {
615
+ method = "POST",
616
+ body,
617
+ headers = {},
618
+ signal,
619
+ onError
620
+ } = options;
621
+ try {
622
+ const authHeader = await this.getAccessToken();
623
+ const response = await this.fetchImpl(buildUrl(this.baseURL, endpoint, {}), {
624
+ method,
625
+ headers: {
626
+ ...headers,
627
+ Accept: "text/event-stream",
628
+ "Cache-Control": "no-cache",
629
+ ...authHeader ? { Authorization: `Bearer ${authHeader}` } : {},
630
+ ...method === "POST" ? { "Content-Type": "application/json" } : {}
631
+ },
632
+ body: method === "POST" && body ? JSON.stringify(body) : void 0,
633
+ signal
634
+ });
635
+ if (!response.ok) {
636
+ throw this.createApiError(response);
637
+ }
638
+ if (!response.body) {
639
+ throw new ApiError("Response body is empty");
640
+ }
641
+ const reader = response.body.getReader();
642
+ const decoder = new TextDecoder();
643
+ let buffer = "";
644
+ try {
645
+ while (true) {
646
+ const { done, value } = await reader.read();
647
+ if (done) break;
648
+ buffer += decoder.decode(value, { stream: true });
649
+ const lines = buffer.split("\n");
650
+ buffer = lines.pop() || "";
651
+ for (const line of lines) {
652
+ if (line.startsWith("data: ")) {
653
+ const data = line.slice(6);
654
+ if (data === "[DONE]") {
655
+ return;
656
+ }
657
+ yield data;
658
+ }
659
+ }
660
+ }
661
+ } finally {
662
+ reader.releaseLock();
663
+ }
664
+ } catch (error) {
665
+ if (onError) {
666
+ onError(error);
667
+ }
668
+ throw error;
669
+ }
670
+ }
671
+ async postStream(endpoint, data, onMessage, onError, onComplete) {
672
+ try {
673
+ const generator = this.stream(endpoint, {
674
+ method: "POST",
675
+ body: data,
676
+ onMessage: onMessage || (() => {
677
+ }),
678
+ onError
679
+ });
680
+ for await (const chunk of generator) {
681
+ if (onMessage) {
682
+ try {
683
+ const parsed = JSON.parse(chunk);
684
+ onMessage(parsed);
685
+ } catch {
686
+ onMessage(chunk);
687
+ }
688
+ }
689
+ }
690
+ if (onComplete) {
691
+ onComplete();
692
+ }
693
+ } catch (error) {
694
+ if (onError) {
695
+ onError(error);
696
+ }
697
+ throw error;
698
+ }
699
+ }
700
+ };
701
+
702
+ // src/clients/rest-client.ts
703
+ var RestApiClient = class extends BaseApiClient {
704
+ constructor(config = {}) {
705
+ if (!config.baseURL) {
706
+ throw new Error("RestApiClient requires a baseURL in the configuration");
707
+ }
708
+ super(config);
709
+ }
710
+ async html2pdf(options = {}) {
711
+ const token = await this.getAccessToken();
712
+ if (!token) {
713
+ throw new ApiError("No access token provided", 401, "AUTH_REQUIRED");
714
+ }
715
+ const url = "https://html2pdf.cf.docyrus.app/";
716
+ try {
717
+ const response = await this.fetchImpl(url, {
718
+ method: "POST",
719
+ headers: {
720
+ "Content-Type": "application/json",
721
+ Authorization: `Bearer ${token}`
722
+ },
723
+ body: JSON.stringify(options)
724
+ });
725
+ if (!response.ok) {
726
+ let errorData = null;
727
+ try {
728
+ errorData = await response.json();
729
+ } catch {
730
+ }
731
+ throw this.createApiError(response, errorData);
732
+ }
733
+ return await response.json();
734
+ } catch (error) {
735
+ if (error instanceof ApiError) {
736
+ throw error;
737
+ }
738
+ throw new ApiError(
739
+ error instanceof Error ? error.message : "PDF generation failed",
740
+ void 0,
741
+ "PDF_GENERATION_ERROR"
742
+ );
743
+ }
744
+ }
745
+ };
746
+
747
+ // src/clients/edge-client.ts
748
+ var EdgeFunctionClient = class extends BaseApiClient {
749
+ constructor(config = {}) {
750
+ if (!config.baseURL) {
751
+ throw new Error("EdgeFunctionClient requires a baseURL in the configuration");
752
+ }
753
+ super(config);
754
+ }
755
+ // Edge functions might have specific streaming capabilities
756
+ async *streamFunction(functionName, data, signal) {
757
+ yield* this.stream(`/${functionName}`, {
758
+ method: "POST",
759
+ body: data,
760
+ signal,
761
+ onMessage: () => {
762
+ }
763
+ });
764
+ }
765
+ // Invoke edge function with typed response
766
+ async invokeFunction(functionName, data, config) {
767
+ return this.post(`/${functionName}`, data, config);
768
+ }
769
+ };
770
+
771
+ // src/clients/cf-client.ts
772
+ var CloudflareWorkerClient = class extends BaseApiClient {
773
+ constructor(config = {}) {
774
+ if (!config.baseURL) {
775
+ throw new Error("CloudflareWorkerClient requires a baseURL in the configuration");
776
+ }
777
+ super(config);
778
+ }
779
+ async request(method, endpoint, data, config = {}) {
780
+ const functionName = endpoint.split("/")[1] || endpoint;
781
+ const remainingPath = endpoint.includes("/") ? endpoint.substring(endpoint.indexOf("/", 1)) : "";
782
+ const originalBaseURL = this.baseURL;
783
+ if (this.baseURL.includes("{{function}}")) {
784
+ this.baseURL = this.baseURL.replace("{{function}}", functionName);
785
+ }
786
+ try {
787
+ return await super.request(method, remainingPath, data, config);
788
+ } finally {
789
+ this.baseURL = originalBaseURL;
790
+ }
791
+ }
792
+ // Worker-specific method to invoke functions
793
+ async invokeWorker(workerName, route = "", data, config) {
794
+ const endpoint = route ? `${workerName}/${route}` : workerName;
795
+ return this.post(endpoint, data, config);
796
+ }
797
+ // Durable Object binding support
798
+ async durableObject(namespace, id, method, data) {
799
+ return this.post(`durable/${namespace}/${id}/${method}`, data);
800
+ }
801
+ // KV namespace support
802
+ async kvGet(namespace, key) {
803
+ return this.get(`kv/${namespace}/${key}`);
804
+ }
805
+ async kvPut(namespace, key, value, metadata) {
806
+ await this.put(`kv/${namespace}/${key}`, { value, metadata });
807
+ }
808
+ async kvDelete(namespace, key) {
809
+ await this.delete(`kv/${namespace}/${key}`);
810
+ }
811
+ async kvList(namespace, options) {
812
+ return this.get(`kv/${namespace}`, options);
813
+ }
814
+ };
815
+
816
+ // src/core/crypto.ts
817
+ var BrowserCryptoProvider = class {
818
+ getRandomValues(buffer) {
819
+ if (typeof crypto === "undefined" || !crypto.getRandomValues) {
820
+ throw new Error("Web Crypto API (crypto.getRandomValues) not available");
821
+ }
822
+ return crypto.getRandomValues(buffer);
823
+ }
824
+ async sha256(data) {
825
+ if (typeof crypto === "undefined" || !crypto.subtle?.digest) {
826
+ throw new Error("Web Crypto API (crypto.subtle.digest) not available");
827
+ }
828
+ return crypto.subtle.digest("SHA-256", data);
829
+ }
830
+ btoa(input) {
831
+ if (typeof globalThis.btoa !== "function") {
832
+ throw new Error("btoa() not available in this environment");
833
+ }
834
+ return globalThis.btoa(input);
835
+ }
836
+ atob(input) {
837
+ if (typeof globalThis.atob !== "function") {
838
+ throw new Error("atob() not available in this environment");
839
+ }
840
+ return globalThis.atob(input);
841
+ }
842
+ };
843
+ var defaultProvider;
844
+ function getDefaultCryptoProvider() {
845
+ if (!defaultProvider) {
846
+ defaultProvider = new BrowserCryptoProvider();
847
+ }
848
+ return defaultProvider;
849
+ }
850
+
851
+ // src/oauth2/pkce.ts
852
+ function generateCodeVerifier(length = 64, cryptoProvider) {
853
+ const provider = cryptoProvider ?? getDefaultCryptoProvider();
854
+ const unreserved = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";
855
+ const randomValues = new Uint8Array(length);
856
+ provider.getRandomValues(randomValues);
857
+ let verifier = "";
858
+ for (let i = 0; i < length; i++) {
859
+ verifier += unreserved[randomValues[i] % unreserved.length];
860
+ }
861
+ return verifier;
862
+ }
863
+ function base64UrlEncode(buffer, cryptoProvider) {
864
+ const provider = cryptoProvider ?? getDefaultCryptoProvider();
865
+ let base64 = "";
866
+ const bytes = new Uint8Array(buffer);
867
+ const len = bytes.byteLength;
868
+ for (let i = 0; i < len; i++) {
869
+ base64 += String.fromCharCode(bytes[i]);
870
+ }
871
+ return provider.btoa(base64).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
872
+ }
873
+ function base64UrlDecode(input, cryptoProvider) {
874
+ const provider = cryptoProvider ?? getDefaultCryptoProvider();
875
+ let base64 = input.replace(/-/g, "+").replace(/_/g, "/");
876
+ while (base64.length % 4) {
877
+ base64 += "=";
878
+ }
879
+ const binary = provider.atob(base64);
880
+ const bytes = new Uint8Array(binary.length);
881
+ for (let i = 0; i < binary.length; i++) {
882
+ bytes[i] = binary.charCodeAt(i);
883
+ }
884
+ return bytes;
885
+ }
886
+ async function generateCodeChallenge(codeVerifier, cryptoProvider) {
887
+ const provider = cryptoProvider ?? getDefaultCryptoProvider();
888
+ const encoder = new TextEncoder();
889
+ const data = encoder.encode(codeVerifier);
890
+ const digest = await provider.sha256(data);
891
+ return base64UrlEncode(new Uint8Array(digest), provider);
892
+ }
893
+ async function generatePKCEChallenge(cryptoProvider) {
894
+ const codeVerifier = generateCodeVerifier(64, cryptoProvider);
895
+ const codeChallenge = await generateCodeChallenge(codeVerifier, cryptoProvider);
896
+ return {
897
+ codeVerifier,
898
+ codeChallenge,
899
+ codeChallengeMethod: "S256"
900
+ };
901
+ }
902
+ function generateState(length = 32, cryptoProvider) {
903
+ return generateCodeVerifier(length, cryptoProvider);
904
+ }
905
+ function generateNonce(length = 32, cryptoProvider) {
906
+ return generateCodeVerifier(length, cryptoProvider);
907
+ }
908
+
909
+ // src/oauth2/oauth2-token-manager.ts
910
+ var MemoryOAuth2TokenStorage = class {
911
+ tokens = null;
912
+ pkceState = null;
913
+ getTokens() {
914
+ return this.tokens;
915
+ }
916
+ setTokens(tokens) {
917
+ this.tokens = tokens;
918
+ }
919
+ clearTokens() {
920
+ this.tokens = null;
921
+ }
922
+ getPKCEState() {
923
+ return this.pkceState;
924
+ }
925
+ setPKCEState(state) {
926
+ this.pkceState = state;
927
+ }
928
+ clearPKCEState() {
929
+ this.pkceState = null;
930
+ }
931
+ };
932
+ var BrowserOAuth2TokenStorage = class {
933
+ tokensKey;
934
+ pkceKey;
935
+ storage;
936
+ constructor(storage, keyPrefix = "docyrus_oauth2") {
937
+ this.storage = storage ?? (typeof window !== "undefined" ? window.localStorage : null);
938
+ this.tokensKey = `${keyPrefix}_tokens`;
939
+ this.pkceKey = `${keyPrefix}_pkce`;
940
+ }
941
+ getTokens() {
942
+ if (!this.storage) return null;
943
+ const data = this.storage.getItem(this.tokensKey);
944
+ return data ? JSON.parse(data) : null;
945
+ }
946
+ setTokens(tokens) {
947
+ if (!this.storage) return;
948
+ this.storage.setItem(this.tokensKey, JSON.stringify(tokens));
949
+ }
950
+ clearTokens() {
951
+ if (!this.storage) return;
952
+ this.storage.removeItem(this.tokensKey);
953
+ }
954
+ getPKCEState() {
955
+ if (!this.storage) return null;
956
+ const data = this.storage.getItem(this.pkceKey);
957
+ return data ? JSON.parse(data) : null;
958
+ }
959
+ setPKCEState(state) {
960
+ if (!this.storage) return;
961
+ this.storage.setItem(this.pkceKey, JSON.stringify(state));
962
+ }
963
+ clearPKCEState() {
964
+ if (!this.storage) return;
965
+ this.storage.removeItem(this.pkceKey);
966
+ }
967
+ };
968
+ var OAuth2TokenManagerAdapter = class {
969
+ constructor(oauth2Storage, onTokenExpired) {
970
+ this.oauth2Storage = oauth2Storage;
971
+ this.onTokenExpired = onTokenExpired;
972
+ }
973
+ oauth2Storage;
974
+ onTokenExpired;
975
+ getToken() {
976
+ const tokens = this.oauth2Storage.getTokens();
977
+ if (tokens instanceof Promise) {
978
+ return tokens.then((t) => this.extractToken(t));
979
+ }
980
+ return this.extractToken(tokens);
981
+ }
982
+ extractToken(tokens) {
983
+ if (!tokens) return null;
984
+ if (tokens.expiresAt && Date.now() >= (tokens.expiresAt - 60) * 1e3) {
985
+ return null;
986
+ }
987
+ return tokens.accessToken;
988
+ }
989
+ setToken(token) {
990
+ const result = this.oauth2Storage.setTokens({
991
+ accessToken: token,
992
+ expiresAt: Math.floor(Date.now() / 1e3) + 3600,
993
+ // Default 1 hour
994
+ scope: ""
995
+ });
996
+ if (result instanceof Promise) {
997
+ return result;
998
+ }
999
+ }
1000
+ clearToken() {
1001
+ return this.oauth2Storage.clearTokens();
1002
+ }
1003
+ refreshToken() {
1004
+ if (!this.onTokenExpired) {
1005
+ return Promise.reject(new Error("Token refresh not configured"));
1006
+ }
1007
+ return this.onTokenExpired();
1008
+ }
1009
+ };
1010
+
1011
+ // src/oauth2/oauth2-client.ts
1012
+ var REFRESHED_ELSEWHERE_MIN_VALIDITY_SECONDS = 30;
1013
+ async function withRefreshLock(name, fn) {
1014
+ const locks = globalThis.navigator?.locks;
1015
+ return locks ? await locks.request(name, fn) : await fn();
1016
+ }
1017
+ var OAuth2Client = class {
1018
+ config;
1019
+ fetchImpl;
1020
+ storage;
1021
+ cryptoProvider;
1022
+ /** Shared in-flight refresh, so concurrent callers don't each spend the refresh token. */
1023
+ refreshInFlight = null;
1024
+ constructor(config) {
1025
+ if (!config.baseURL) {
1026
+ throw new Error("OAuth2Client requires a baseURL");
1027
+ }
1028
+ if (!config.clientId) {
1029
+ throw new Error("OAuth2Client requires a clientId");
1030
+ }
1031
+ this.config = {
1032
+ ...config,
1033
+ baseURL: config.baseURL,
1034
+ clientId: config.clientId,
1035
+ usePKCE: config.usePKCE ?? true,
1036
+ defaultScopes: config.defaultScopes ?? []
1037
+ };
1038
+ const rawFetch = config.fetch || globalThis.fetch;
1039
+ if (!rawFetch) {
1040
+ throw new Error("Fetch API not available");
1041
+ }
1042
+ this.fetchImpl = rawFetch.bind(globalThis);
1043
+ this.storage = config.tokenStorage || new MemoryOAuth2TokenStorage();
1044
+ this.cryptoProvider = config.cryptoProvider;
1045
+ }
1046
+ // ===== Authorization Code Flow =====
1047
+ /**
1048
+ * Generate authorization URL for the authorization code flow
1049
+ * Handles PKCE automatically if enabled
1050
+ */
1051
+ async getAuthorizationUrl(options = {}) {
1052
+ const state = options.state || generateState(32, this.cryptoProvider);
1053
+ const scope = options.scope || this.config.defaultScopes?.join(" ") || "openid";
1054
+ const redirectUri = options.redirectUri || this.config.redirectUri;
1055
+ if (!redirectUri) {
1056
+ throw new Error("redirectUri is required for authorization code flow");
1057
+ }
1058
+ const params = {
1059
+ client_id: this.config.clientId,
1060
+ redirect_uri: redirectUri,
1061
+ response_type: "code",
1062
+ state,
1063
+ scope
1064
+ };
1065
+ if (scope.includes("openid")) {
1066
+ params.nonce = options.nonce || generateNonce(32, this.cryptoProvider);
1067
+ }
1068
+ let codeVerifier;
1069
+ if (this.config.usePKCE) {
1070
+ const pkce = await generatePKCEChallenge(this.cryptoProvider);
1071
+ params.code_challenge = pkce.codeChallenge;
1072
+ params.code_challenge_method = pkce.codeChallengeMethod;
1073
+ ({ codeVerifier } = pkce);
1074
+ if (this.storage.setPKCEState) {
1075
+ await Promise.resolve(this.storage.setPKCEState({
1076
+ codeVerifier,
1077
+ state,
1078
+ nonce: params.nonce
1079
+ }));
1080
+ }
1081
+ }
1082
+ const url = buildUrl(this.config.baseURL, "/v1/oauth2/authorize", params);
1083
+ return { url, state, codeVerifier };
1084
+ }
1085
+ /**
1086
+ * Handle the authorization callback and exchange code for tokens
1087
+ */
1088
+ async handleCallback(callbackUrl, options = {}) {
1089
+ let code;
1090
+ let state;
1091
+ if (typeof callbackUrl === "string") {
1092
+ const url = new URL(callbackUrl);
1093
+ code = url.searchParams.get("code") || "";
1094
+ state = url.searchParams.get("state") || "";
1095
+ const error = url.searchParams.get("error");
1096
+ if (error) {
1097
+ const errorDescription = url.searchParams.get("error_description") || void 0;
1098
+ throw this.createOAuth2Error(error, errorDescription);
1099
+ }
1100
+ } else {
1101
+ ({ code, state } = callbackUrl);
1102
+ }
1103
+ let storedPKCE = null;
1104
+ if (this.storage.getPKCEState) {
1105
+ storedPKCE = await Promise.resolve(this.storage.getPKCEState());
1106
+ }
1107
+ const expectedState = options.expectedState || storedPKCE?.state;
1108
+ if (expectedState && state !== expectedState) {
1109
+ throw new OAuth2Error("invalid_state", "State mismatch - possible CSRF attack");
1110
+ }
1111
+ const codeVerifier = options.codeVerifier || storedPKCE?.codeVerifier;
1112
+ const tokens = await this.exchangeCode(code, codeVerifier);
1113
+ if (this.storage.clearPKCEState) {
1114
+ await Promise.resolve(this.storage.clearPKCEState());
1115
+ }
1116
+ return tokens;
1117
+ }
1118
+ /**
1119
+ * Exchange authorization code for tokens
1120
+ */
1121
+ async exchangeCode(code, codeVerifier, redirectUri) {
1122
+ const body = {
1123
+ grant_type: "authorization_code",
1124
+ client_id: this.config.clientId,
1125
+ code,
1126
+ redirect_uri: redirectUri || this.config.redirectUri
1127
+ };
1128
+ if (codeVerifier) {
1129
+ body.code_verifier = codeVerifier;
1130
+ } else if (this.config.clientSecret) {
1131
+ body.client_secret = this.config.clientSecret;
1132
+ }
1133
+ return this.requestToken(body);
1134
+ }
1135
+ // ===== Refresh Token Flow =====
1136
+ /**
1137
+ * Refresh the access token using a refresh token.
1138
+ *
1139
+ * Concurrent calls share a single in-flight request. Without this, several
1140
+ * requests crossing the expiry buffer at once each fire their own refresh;
1141
+ * with refresh-token rotation only the first succeeds and the losers can
1142
+ * leave the client holding an already-expired token (surfacing as backend
1143
+ * "JWTExpired" errors on subsequent calls).
1144
+ */
1145
+ async refreshAccessToken(refreshToken) {
1146
+ if (this.refreshInFlight) return this.refreshInFlight;
1147
+ this.refreshInFlight = this.performRefresh(refreshToken).finally(() => {
1148
+ this.refreshInFlight = null;
1149
+ });
1150
+ return this.refreshInFlight;
1151
+ }
1152
+ /**
1153
+ * Refresh tokens rotate, and the Docyrus API refuses a rotated refresh token presented again (and can end
1154
+ * the whole sign-in for it). Tabs and windows sharing one token storage therefore refresh one at a time,
1155
+ * under a Web Lock, and with the token as stored *now*: if another tab refreshed while this one waited, its
1156
+ * tokens are used instead of refreshing again. Outside browsers (no Web Locks) only the per-instance
1157
+ * single-flight above applies.
1158
+ */
1159
+ async performRefresh(refreshToken) {
1160
+ const seenRefreshToken = refreshToken || (await Promise.resolve(this.storage.getTokens()))?.refreshToken;
1161
+ return await withRefreshLock(`docyrus-oauth2-refresh:${this.config.baseURL}:${this.config.clientId}`, async () => {
1162
+ const stored = await Promise.resolve(this.storage.getTokens());
1163
+ if (stored?.refreshToken && seenRefreshToken && stored.refreshToken !== seenRefreshToken && !await this.isTokenExpired(REFRESHED_ELSEWHERE_MIN_VALIDITY_SECONDS)) {
1164
+ return stored;
1165
+ }
1166
+ return await this.requestRefresh(stored?.refreshToken || refreshToken);
1167
+ });
1168
+ }
1169
+ async requestRefresh(token) {
1170
+ if (!token) {
1171
+ throw new InvalidGrantError("No refresh token available");
1172
+ }
1173
+ const body = {
1174
+ grant_type: "refresh_token",
1175
+ client_id: this.config.clientId,
1176
+ refresh_token: token
1177
+ };
1178
+ if (this.config.clientSecret) {
1179
+ body.client_secret = this.config.clientSecret;
1180
+ }
1181
+ return this.requestToken(body);
1182
+ }
1183
+ // ===== Client Credentials Flow =====
1184
+ /**
1185
+ * Get access token using client credentials
1186
+ */
1187
+ async getClientCredentialsToken(options) {
1188
+ const body = {
1189
+ grant_type: "client_credentials",
1190
+ client_id: this.config.clientId,
1191
+ scope: options.scope,
1192
+ delegated_user_id: options.delegatedUserId
1193
+ };
1194
+ if (options.clientAssertion) {
1195
+ body.client_assertion_type = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
1196
+ body.client_assertion = options.clientAssertion;
1197
+ } else if (this.config.clientSecret) {
1198
+ body.client_secret = this.config.clientSecret;
1199
+ } else {
1200
+ throw new InvalidClientError("Client credentials flow requires client_secret or client_assertion");
1201
+ }
1202
+ return this.requestToken(body);
1203
+ }
1204
+ // ===== Device Authorization Flow (RFC 8628) =====
1205
+ /**
1206
+ * Start device authorization flow
1207
+ */
1208
+ async startDeviceAuthorization(scope) {
1209
+ const body = {
1210
+ client_id: this.config.clientId,
1211
+ scope: scope || this.config.defaultScopes?.join(" ")
1212
+ };
1213
+ const response = await this.fetchImpl(
1214
+ buildUrl(this.config.baseURL, "/v1/oauth2/device/authorize", {}),
1215
+ {
1216
+ method: "POST",
1217
+ headers: { "Content-Type": "application/json" },
1218
+ body: JSON.stringify(body)
1219
+ }
1220
+ );
1221
+ if (!response.ok) {
1222
+ await this.handleErrorResponse(response);
1223
+ }
1224
+ return response.json();
1225
+ }
1226
+ /**
1227
+ * Poll for device authorization completion
1228
+ * Returns tokens when user completes authorization
1229
+ */
1230
+ async pollDeviceAuthorization(deviceCode, interval = 5, expiresIn = 1800, options = {}) {
1231
+ const startTime = Date.now();
1232
+ const expiresAt = startTime + expiresIn * 1e3;
1233
+ let currentInterval = interval * 1e3;
1234
+ while (Date.now() < expiresAt) {
1235
+ if (options.signal?.aborted) {
1236
+ throw new Error("Device authorization polling was aborted");
1237
+ }
1238
+ await this.sleep(currentInterval);
1239
+ try {
1240
+ const body = {
1241
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
1242
+ client_id: this.config.clientId,
1243
+ device_code: deviceCode
1244
+ };
1245
+ return await this.requestToken(body);
1246
+ } catch (error) {
1247
+ if (error instanceof AuthorizationPendingError) {
1248
+ continue;
1249
+ }
1250
+ if (error instanceof SlowDownError) {
1251
+ currentInterval += 5e3;
1252
+ continue;
1253
+ }
1254
+ if (error instanceof ExpiredTokenError) {
1255
+ options.onExpired?.();
1256
+ throw error;
1257
+ }
1258
+ throw error;
1259
+ }
1260
+ }
1261
+ options.onExpired?.();
1262
+ throw new ExpiredTokenError();
1263
+ }
1264
+ /**
1265
+ * Verify a device user code
1266
+ */
1267
+ async verifyDeviceCode(userCode) {
1268
+ const body = { user_code: userCode };
1269
+ const response = await this.fetchImpl(
1270
+ buildUrl(this.config.baseURL, "/v1/oauth2/device/verify", {}),
1271
+ {
1272
+ method: "POST",
1273
+ headers: { "Content-Type": "application/json" },
1274
+ body: JSON.stringify(body)
1275
+ }
1276
+ );
1277
+ if (!response.ok) {
1278
+ await this.handleErrorResponse(response);
1279
+ }
1280
+ return response.json();
1281
+ }
1282
+ // ===== Token Revocation =====
1283
+ /**
1284
+ * Revoke a refresh token
1285
+ */
1286
+ async revokeToken(refreshToken, clientAssertion) {
1287
+ const body = {
1288
+ client_id: this.config.clientId,
1289
+ refresh_token: refreshToken
1290
+ };
1291
+ if (clientAssertion) {
1292
+ body.client_assertion_type = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
1293
+ body.client_assertion = clientAssertion;
1294
+ } else if (this.config.clientSecret) {
1295
+ body.client_secret = this.config.clientSecret;
1296
+ }
1297
+ const response = await this.fetchImpl(
1298
+ buildUrl(this.config.baseURL, "/v1/oauth2/revoke", {}),
1299
+ {
1300
+ method: "POST",
1301
+ headers: { "Content-Type": "application/json" },
1302
+ body: JSON.stringify(body)
1303
+ }
1304
+ );
1305
+ if (!response.ok && response.status !== 204) {
1306
+ await this.handleErrorResponse(response);
1307
+ }
1308
+ }
1309
+ // ===== Token Introspection =====
1310
+ /**
1311
+ * Introspect a token to check its validity and metadata
1312
+ */
1313
+ async introspectToken(token, tokenTypeHint, clientAssertion) {
1314
+ const body = {
1315
+ token,
1316
+ client_id: this.config.clientId,
1317
+ token_type_hint: tokenTypeHint
1318
+ };
1319
+ if (clientAssertion) {
1320
+ body.client_assertion_type = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
1321
+ body.client_assertion = clientAssertion;
1322
+ } else if (this.config.clientSecret) {
1323
+ body.client_secret = this.config.clientSecret;
1324
+ }
1325
+ const response = await this.fetchImpl(
1326
+ buildUrl(this.config.baseURL, "/v1/oauth2/introspect", {}),
1327
+ {
1328
+ method: "POST",
1329
+ headers: { "Content-Type": "application/json" },
1330
+ body: JSON.stringify(body)
1331
+ }
1332
+ );
1333
+ if (!response.ok) {
1334
+ await this.handleErrorResponse(response);
1335
+ }
1336
+ return response.json();
1337
+ }
1338
+ // ===== Rate Limit Check =====
1339
+ /**
1340
+ * Check rate limit status without consuming units
1341
+ */
1342
+ async checkRateLimit() {
1343
+ const currentTokens = await Promise.resolve(this.storage.getTokens());
1344
+ const headers = {};
1345
+ if (currentTokens?.accessToken) {
1346
+ headers["Authorization"] = `Bearer ${currentTokens.accessToken}`;
1347
+ }
1348
+ const response = await this.fetchImpl(
1349
+ buildUrl(this.config.baseURL, "/v1/oauth2", {}),
1350
+ {
1351
+ method: "HEAD",
1352
+ headers
1353
+ }
1354
+ );
1355
+ return {
1356
+ policy: response.headers.get("RateLimit-Policy") || "",
1357
+ reset: parseInt(response.headers.get("RateLimit-Reset") || "0", 10),
1358
+ remaining: parseInt(response.headers.get("RateLimit-Remaining") || "0", 10),
1359
+ limit: parseInt(response.headers.get("RateLimit-Limit") || "0", 10)
1360
+ };
1361
+ }
1362
+ // ===== Token Management =====
1363
+ /**
1364
+ * Get current stored tokens
1365
+ */
1366
+ async getTokens() {
1367
+ return Promise.resolve(this.storage.getTokens());
1368
+ }
1369
+ /**
1370
+ * Check if the current access token is expired
1371
+ */
1372
+ async isTokenExpired(bufferSeconds = 60) {
1373
+ const tokens = await this.getTokens();
1374
+ if (!tokens) return true;
1375
+ const expiresAt = (tokens.expiresAt || 0) > 0 ? tokens.expiresAt : this.parseJwtExp(tokens.accessToken);
1376
+ if (!expiresAt || !Number.isFinite(expiresAt)) return false;
1377
+ return Date.now() >= (expiresAt - bufferSeconds) * 1e3;
1378
+ }
1379
+ /**
1380
+ * Get a valid access token, refreshing if necessary
1381
+ */
1382
+ async getValidAccessToken() {
1383
+ const tokens = await this.getTokens();
1384
+ if (!tokens) {
1385
+ throw new InvalidGrantError("No tokens available");
1386
+ }
1387
+ if (await this.isTokenExpired()) {
1388
+ if (!tokens.refreshToken) {
1389
+ throw new InvalidGrantError("Access token expired and no refresh token available");
1390
+ }
1391
+ const newTokens = await this.refreshAccessToken(tokens.refreshToken);
1392
+ return newTokens.accessToken;
1393
+ }
1394
+ return tokens.accessToken;
1395
+ }
1396
+ /**
1397
+ * Clear all stored tokens (logout)
1398
+ */
1399
+ async logout() {
1400
+ const tokens = await this.getTokens();
1401
+ if (tokens?.refreshToken) {
1402
+ try {
1403
+ await this.revokeToken(tokens.refreshToken);
1404
+ } catch {
1405
+ }
1406
+ }
1407
+ await Promise.resolve(this.storage.clearTokens());
1408
+ }
1409
+ // ===== Private Methods =====
1410
+ async requestToken(body) {
1411
+ const response = await this.fetchImpl(
1412
+ buildUrl(this.config.baseURL, "/v1/oauth2/token", {}),
1413
+ {
1414
+ method: "POST",
1415
+ headers: { "Content-Type": "application/json" },
1416
+ body: JSON.stringify(body)
1417
+ }
1418
+ );
1419
+ if (!response.ok) {
1420
+ await this.handleErrorResponse(response);
1421
+ }
1422
+ const tokenResponse = await response.json();
1423
+ const expiresIn = tokenResponse.expires_in;
1424
+ const expiresAt = Number.isFinite(expiresIn) && expiresIn > 0 ? Math.floor(Date.now() / 1e3) + expiresIn : this.parseJwtExp(tokenResponse.access_token) ?? 0;
1425
+ const tokens = {
1426
+ accessToken: tokenResponse.access_token,
1427
+ refreshToken: tokenResponse.refresh_token,
1428
+ idToken: tokenResponse.id_token,
1429
+ expiresAt,
1430
+ scope: tokenResponse.scope
1431
+ };
1432
+ await Promise.resolve(this.storage.setTokens(tokens));
1433
+ return tokens;
1434
+ }
1435
+ async handleErrorResponse(response) {
1436
+ let errorData;
1437
+ try {
1438
+ errorData = await response.json();
1439
+ } catch {
1440
+ throw new OAuth2Error("unknown_error", response.statusText);
1441
+ }
1442
+ throw this.createOAuth2Error(
1443
+ errorData.error || "unknown_error",
1444
+ errorData.error_description,
1445
+ errorData.error_uri
1446
+ );
1447
+ }
1448
+ createOAuth2Error(error, description, uri) {
1449
+ switch (error) {
1450
+ case "invalid_grant":
1451
+ return new InvalidGrantError(description);
1452
+ case "invalid_client":
1453
+ return new InvalidClientError(description);
1454
+ case "authorization_pending":
1455
+ return new AuthorizationPendingError();
1456
+ case "slow_down":
1457
+ return new SlowDownError();
1458
+ case "expired_token":
1459
+ return new ExpiredTokenError();
1460
+ case "access_denied":
1461
+ return new AccessDeniedError(description);
1462
+ default:
1463
+ return new OAuth2Error(error, description, uri);
1464
+ }
1465
+ }
1466
+ sleep(ms) {
1467
+ return new Promise((resolve) => setTimeout(resolve, ms));
1468
+ }
1469
+ /** Extract exp claim from a JWT access token as a fallback for expires_in. */
1470
+ parseJwtExp(accessToken) {
1471
+ const parts = accessToken.split(".");
1472
+ if (parts.length < 2) return void 0;
1473
+ try {
1474
+ const payload = JSON.parse(
1475
+ atob(parts[1].replace(/-/g, "+").replace(/_/g, "/"))
1476
+ );
1477
+ return typeof payload["exp"] === "number" ? payload["exp"] : void 0;
1478
+ } catch {
1479
+ return void 0;
1480
+ }
1481
+ }
1482
+ };
1483
+
1484
+ export { AbortError, AccessDeniedError, ApiError, AsyncTokenManager, AuthenticationError, AuthorizationError, AuthorizationPendingError, BaseApiClient, BrowserCryptoProvider, BrowserOAuth2TokenStorage, CloudflareWorkerClient, ConflictError, EdgeFunctionClient, ExpiredTokenError, GenericError, InvalidClientError, InvalidGrantError, InvalidScopeError, MemoryOAuth2TokenStorage, MemoryTokenManager, NetworkError, NotFoundError, OAuth2Client, OAuth2Error, OAuth2TokenManagerAdapter, RateLimitError, RestApiClient, ServerError, SlowDownError, StorageTokenManager, TimeoutError, ValidationError, base64UrlDecode, base64UrlEncode, buildUrl, createAbortSignal, RestApiClient as default, generateCodeChallenge, generateCodeVerifier, generateNonce, generatePKCEChallenge, generateState, getDefaultCryptoProvider, isAbortError, isBlob, isFormData, isStream, jsonToQueryString, parseContentDisposition, prepareFilterQueryForApi, withRetry };
1485
+ //# sourceMappingURL=index.js.map
1486
+ //# sourceMappingURL=index.js.map