@baukit/api-runtime 0.18.3 → 0.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/errors.d.ts +49 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +112 -0
- package/dist/errors.js.map +1 -0
- package/dist/fetch.d.ts +13 -0
- package/dist/fetch.d.ts.map +1 -0
- package/dist/fetch.js +224 -0
- package/dist/fetch.js.map +1 -0
- package/dist/headers.d.ts +5 -0
- package/dist/headers.d.ts.map +1 -0
- package/dist/headers.js +5 -0
- package/dist/headers.js.map +1 -0
- package/dist/index.d.ts +3 -52
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -400
- package/dist/index.js.map +1 -1
- package/dist/retry.d.ts +18 -0
- package/dist/retry.d.ts.map +1 -0
- package/dist/retry.js +108 -0
- package/dist/retry.js.map +1 -0
- package/package.json +3 -2
- package/src/errors.ts +153 -0
- package/src/fetch.ts +325 -0
- package/src/headers.ts +5 -0
- package/src/index.ts +17 -515
- package/src/retry.ts +154 -0
package/src/errors.ts
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { isRecord } from '@baukit/type-guards';
|
|
2
|
+
|
|
3
|
+
import { REQUEST_ID_HEADER } from './headers.js';
|
|
4
|
+
|
|
5
|
+
/** JSON values accepted in Baukit error details. */
|
|
6
|
+
export type JsonValue =
|
|
7
|
+
null | boolean | number | string | readonly JsonValue[] | { readonly [key: string]: JsonValue };
|
|
8
|
+
|
|
9
|
+
/** A validated Baukit error envelope. */
|
|
10
|
+
export interface ApiErrorEnvelope<Code extends string = string> {
|
|
11
|
+
readonly error: {
|
|
12
|
+
readonly code: Code;
|
|
13
|
+
readonly message: string;
|
|
14
|
+
readonly requestId: string;
|
|
15
|
+
readonly details: Readonly<Record<string, JsonValue>>;
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** A non-success response using Baukit's standard JSON error envelope. */
|
|
20
|
+
export class ApiError<Code extends string = string> extends Error {
|
|
21
|
+
readonly kind = 'api' as const;
|
|
22
|
+
readonly code: Code;
|
|
23
|
+
readonly requestId: string;
|
|
24
|
+
readonly details: Readonly<Record<string, JsonValue>>;
|
|
25
|
+
readonly status: number;
|
|
26
|
+
|
|
27
|
+
constructor(envelope: ApiErrorEnvelope<Code>, status: number) {
|
|
28
|
+
super(envelope.error.message);
|
|
29
|
+
this.name = 'ApiError';
|
|
30
|
+
this.code = envelope.error.code;
|
|
31
|
+
this.requestId = envelope.error.requestId;
|
|
32
|
+
this.details = envelope.error.details;
|
|
33
|
+
this.status = status;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** A transport failure where no HTTP response was available (including CORS failures). */
|
|
38
|
+
export class NetworkError extends Error {
|
|
39
|
+
readonly kind = 'network' as const;
|
|
40
|
+
readonly requestId: string;
|
|
41
|
+
readonly aborted: boolean;
|
|
42
|
+
|
|
43
|
+
constructor(message: string, requestId: string, cause: unknown, aborted = false) {
|
|
44
|
+
super(message, { cause });
|
|
45
|
+
this.name = 'NetworkError';
|
|
46
|
+
this.requestId = requestId;
|
|
47
|
+
this.aborted = aborted;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** A non-success HTTP response that did not contain a valid Baukit error envelope. */
|
|
52
|
+
export class HttpError extends Error {
|
|
53
|
+
readonly kind = 'http' as const;
|
|
54
|
+
readonly status: number;
|
|
55
|
+
readonly requestId: string | null;
|
|
56
|
+
readonly body: unknown;
|
|
57
|
+
|
|
58
|
+
constructor(response: Response, body: unknown) {
|
|
59
|
+
const suffix = response.statusText === '' ? '' : ` ${response.statusText}`;
|
|
60
|
+
super(`HTTP ${String(response.status)}${suffix}`);
|
|
61
|
+
this.name = 'HttpError';
|
|
62
|
+
this.status = response.status;
|
|
63
|
+
this.requestId = response.headers.get(REQUEST_ID_HEADER);
|
|
64
|
+
this.body = body;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Narrows an unknown value to an ApiError, optionally with one specific code. */
|
|
69
|
+
export function isApiError(value: unknown): value is ApiError;
|
|
70
|
+
export function isApiError<Code extends string>(
|
|
71
|
+
value: unknown,
|
|
72
|
+
code: Code,
|
|
73
|
+
): value is ApiError<Code>;
|
|
74
|
+
export function isApiError(value: unknown, code?: string): value is ApiError {
|
|
75
|
+
return value instanceof ApiError && (code === undefined || value.code === code);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Narrows an unknown value to a NetworkError. */
|
|
79
|
+
export function isNetworkError(value: unknown): value is NetworkError {
|
|
80
|
+
return value instanceof NetworkError;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Narrows an unknown value to an HttpError. */
|
|
84
|
+
export function isHttpError(value: unknown): value is HttpError {
|
|
85
|
+
return value instanceof HttpError;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Parses the exact Baukit error envelope shape, returning null for any other value. */
|
|
89
|
+
export function parseApiErrorEnvelope(value: unknown, status: number): ApiError | null {
|
|
90
|
+
if (!isRecord(value) || !isRecord(value['error'])) {
|
|
91
|
+
return null;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const error = value['error'];
|
|
95
|
+
if (
|
|
96
|
+
typeof error['code'] !== 'string' ||
|
|
97
|
+
typeof error['message'] !== 'string' ||
|
|
98
|
+
typeof error['requestId'] !== 'string' ||
|
|
99
|
+
!isJsonObject(error['details'])
|
|
100
|
+
) {
|
|
101
|
+
return null;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
return new ApiError(
|
|
105
|
+
{
|
|
106
|
+
error: {
|
|
107
|
+
code: error['code'],
|
|
108
|
+
message: error['message'],
|
|
109
|
+
requestId: error['requestId'],
|
|
110
|
+
details: error['details'],
|
|
111
|
+
},
|
|
112
|
+
},
|
|
113
|
+
status,
|
|
114
|
+
);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Converts a non-success HTTP response into an ApiError or HttpError. */
|
|
118
|
+
export async function normalizeResponseError(response: Response): Promise<ApiError | HttpError> {
|
|
119
|
+
let body: unknown;
|
|
120
|
+
try {
|
|
121
|
+
const text = await response.clone().text();
|
|
122
|
+
if (text !== '') {
|
|
123
|
+
try {
|
|
124
|
+
body = JSON.parse(text) as unknown;
|
|
125
|
+
} catch {
|
|
126
|
+
body = text;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
} catch {
|
|
130
|
+
body = undefined;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
return parseApiErrorEnvelope(body, response.status) ?? new HttpError(response, body);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function isJsonObject(value: unknown): value is Readonly<Record<string, JsonValue>> {
|
|
137
|
+
return isRecord(value) && Object.values(value).every(isJsonValue);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function isJsonValue(value: unknown): value is JsonValue {
|
|
141
|
+
if (
|
|
142
|
+
value === null ||
|
|
143
|
+
typeof value === 'string' ||
|
|
144
|
+
typeof value === 'boolean' ||
|
|
145
|
+
(typeof value === 'number' && Number.isFinite(value))
|
|
146
|
+
) {
|
|
147
|
+
return true;
|
|
148
|
+
}
|
|
149
|
+
if (Array.isArray(value)) {
|
|
150
|
+
return value.every(isJsonValue);
|
|
151
|
+
}
|
|
152
|
+
return isJsonObject(value);
|
|
153
|
+
}
|
package/src/fetch.ts
ADDED
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
import { ApiError, HttpError, isApiError, NetworkError, normalizeResponseError } from './errors.js';
|
|
2
|
+
import { REQUEST_ID_HEADER } from './headers.js';
|
|
3
|
+
import type {
|
|
4
|
+
ApiRuntimeOptions,
|
|
5
|
+
FetchImplementation,
|
|
6
|
+
UnauthorizedContext,
|
|
7
|
+
UnauthorizedHandler,
|
|
8
|
+
UnauthorizedRecovery,
|
|
9
|
+
} from './index.js';
|
|
10
|
+
import {
|
|
11
|
+
isAbortError,
|
|
12
|
+
networkError,
|
|
13
|
+
normalizeRetryOptions,
|
|
14
|
+
retryDelay,
|
|
15
|
+
shouldRetryMethod,
|
|
16
|
+
shouldRetryResponse,
|
|
17
|
+
throwIfAborted,
|
|
18
|
+
type NormalizedRetryOptions,
|
|
19
|
+
} from './retry.js';
|
|
20
|
+
|
|
21
|
+
const UNAUTHORIZED_STATUS = 401;
|
|
22
|
+
const RETRY = Symbol('retry');
|
|
23
|
+
type AttemptOutcome = Response | typeof RETRY;
|
|
24
|
+
|
|
25
|
+
export interface FetchSettings {
|
|
26
|
+
readonly baseUrl: string;
|
|
27
|
+
readonly requestConstructor: typeof Request;
|
|
28
|
+
readonly transport: FetchImplementation;
|
|
29
|
+
readonly requestIdFactory: () => string;
|
|
30
|
+
readonly retry: NormalizedRetryOptions;
|
|
31
|
+
readonly options: ApiRuntimeOptions;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
interface FetchContext extends FetchSettings {
|
|
35
|
+
readonly requestId: string;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
interface AttemptState {
|
|
39
|
+
request: Request;
|
|
40
|
+
replaySource: Request | undefined;
|
|
41
|
+
useOriginalRequest: boolean;
|
|
42
|
+
retries: number;
|
|
43
|
+
unauthorizedReplayUsed: boolean;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function fetchSettings(options: ApiRuntimeOptions, baseUrl: string): FetchSettings {
|
|
47
|
+
return {
|
|
48
|
+
baseUrl,
|
|
49
|
+
requestConstructor: options.requestConstructor ?? globalThis.Request,
|
|
50
|
+
transport: options.fetch ?? globalThis.fetch.bind(globalThis),
|
|
51
|
+
requestIdFactory: options.requestIdFactory ?? createUuid,
|
|
52
|
+
retry: normalizeRetryOptions(options.retry),
|
|
53
|
+
options,
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export async function runFetch(
|
|
58
|
+
settings: FetchSettings,
|
|
59
|
+
input: RequestInfo | URL,
|
|
60
|
+
init: RequestInit | undefined,
|
|
61
|
+
): Promise<Response> {
|
|
62
|
+
const context: FetchContext = { ...settings, requestId: settings.requestIdFactory() };
|
|
63
|
+
const request = await prepareRequest(context, input, init);
|
|
64
|
+
const state: AttemptState = {
|
|
65
|
+
request,
|
|
66
|
+
replaySource: cloneRequest(request),
|
|
67
|
+
useOriginalRequest: true,
|
|
68
|
+
retries: 0,
|
|
69
|
+
unauthorizedReplayUsed: false,
|
|
70
|
+
};
|
|
71
|
+
for (;;) {
|
|
72
|
+
throwIfAborted(state.request.signal, context.requestId);
|
|
73
|
+
const outcome = await runAttempt(context, state);
|
|
74
|
+
if (outcome !== RETRY) {
|
|
75
|
+
return outcome;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
async function prepareRequest(
|
|
81
|
+
context: FetchContext,
|
|
82
|
+
input: RequestInfo | URL,
|
|
83
|
+
init: RequestInit | undefined,
|
|
84
|
+
): Promise<Request> {
|
|
85
|
+
try {
|
|
86
|
+
const request = createRequest(input, init, context.baseUrl, context.requestConstructor);
|
|
87
|
+
return await decorateRequest(context, request);
|
|
88
|
+
} catch (cause) {
|
|
89
|
+
if (cause instanceof NetworkError) {
|
|
90
|
+
throw cause;
|
|
91
|
+
}
|
|
92
|
+
throw networkError(cause, context.requestId, init?.signal ?? null);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
async function runAttempt(context: FetchContext, state: AttemptState): Promise<AttemptOutcome> {
|
|
97
|
+
try {
|
|
98
|
+
const response = await sendAttempt(context, state);
|
|
99
|
+
return await handleResponse(context, state, response);
|
|
100
|
+
} catch (cause) {
|
|
101
|
+
return handleFailure(context, state, cause);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
async function sendAttempt(context: FetchContext, state: AttemptState): Promise<Response> {
|
|
106
|
+
const attempt = state.useOriginalRequest ? state.request : state.replaySource?.clone();
|
|
107
|
+
if (attempt === undefined) {
|
|
108
|
+
throw new TypeError('API request body cannot be replayed');
|
|
109
|
+
}
|
|
110
|
+
state.useOriginalRequest = false;
|
|
111
|
+
const response = await context.transport(attempt);
|
|
112
|
+
throwIfAborted(state.request.signal, context.requestId);
|
|
113
|
+
return response;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
async function handleResponse(
|
|
117
|
+
context: FetchContext,
|
|
118
|
+
state: AttemptState,
|
|
119
|
+
response: Response,
|
|
120
|
+
): Promise<AttemptOutcome> {
|
|
121
|
+
if (
|
|
122
|
+
state.replaySource !== undefined &&
|
|
123
|
+
shouldRetryResponse(state.request, response.status, state.retries, context.retry)
|
|
124
|
+
) {
|
|
125
|
+
await backOff(context, state);
|
|
126
|
+
return RETRY;
|
|
127
|
+
}
|
|
128
|
+
if (response.ok) {
|
|
129
|
+
return response;
|
|
130
|
+
}
|
|
131
|
+
const error = await normalizeResponseError(response);
|
|
132
|
+
if (response.status !== UNAUTHORIZED_STATUS) {
|
|
133
|
+
throw error;
|
|
134
|
+
}
|
|
135
|
+
return handleUnauthorized(context, state, { response, error });
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
interface UnauthorizedResponse {
|
|
139
|
+
readonly response: Response;
|
|
140
|
+
readonly error: ApiError | HttpError;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
async function handleUnauthorized(
|
|
144
|
+
context: FetchContext,
|
|
145
|
+
state: AttemptState,
|
|
146
|
+
failure: UnauthorizedResponse,
|
|
147
|
+
): Promise<AttemptOutcome> {
|
|
148
|
+
const { options, requestId } = context;
|
|
149
|
+
const { error } = failure;
|
|
150
|
+
const unauthorizedContext = (canRetry: boolean): UnauthorizedContext => ({
|
|
151
|
+
...failure,
|
|
152
|
+
request: state.replaySource?.clone() ?? state.request,
|
|
153
|
+
canRetry,
|
|
154
|
+
});
|
|
155
|
+
if (isApiError(error, 'profile_erased')) {
|
|
156
|
+
await notifyObserver(() => options.onProfileErased?.(unauthorizedContext(false)));
|
|
157
|
+
throwIfAborted(state.request.signal, requestId);
|
|
158
|
+
throw error;
|
|
159
|
+
}
|
|
160
|
+
if (state.unauthorizedReplayUsed) {
|
|
161
|
+
if (options.onUnauthorizedExhausted !== undefined) {
|
|
162
|
+
const onExhausted = options.onUnauthorizedExhausted;
|
|
163
|
+
await notifyObserver(() => onExhausted(unauthorizedContext(false)));
|
|
164
|
+
throwIfAborted(state.request.signal, requestId);
|
|
165
|
+
}
|
|
166
|
+
throw error;
|
|
167
|
+
}
|
|
168
|
+
if (options.onUnauthorized === undefined) {
|
|
169
|
+
throw error;
|
|
170
|
+
}
|
|
171
|
+
const recovery = await askForRecovery(
|
|
172
|
+
options.onUnauthorized,
|
|
173
|
+
unauthorizedContext(state.replaySource !== undefined),
|
|
174
|
+
);
|
|
175
|
+
throwIfAborted(state.request.signal, requestId);
|
|
176
|
+
if (recovery !== 'retry-once' || state.replaySource === undefined) {
|
|
177
|
+
throw error;
|
|
178
|
+
}
|
|
179
|
+
await replayWithFreshCredentials(context, state, state.replaySource, error);
|
|
180
|
+
return RETRY;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** Observer failures must not replace the normalized API failure. */
|
|
184
|
+
async function notifyObserver(notify: () => void | Promise<void>): Promise<void> {
|
|
185
|
+
try {
|
|
186
|
+
await notify();
|
|
187
|
+
} catch {
|
|
188
|
+
// The caller rethrows the original normalized error.
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
async function askForRecovery(
|
|
193
|
+
onUnauthorized: UnauthorizedHandler,
|
|
194
|
+
context: UnauthorizedContext,
|
|
195
|
+
): Promise<UnauthorizedRecovery | undefined> {
|
|
196
|
+
try {
|
|
197
|
+
const recovery: unknown = await onUnauthorized(context);
|
|
198
|
+
return recovery === 'retry-once' || recovery === 'handled' ? recovery : undefined;
|
|
199
|
+
} catch {
|
|
200
|
+
return undefined;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
async function replayWithFreshCredentials(
|
|
205
|
+
context: FetchContext,
|
|
206
|
+
state: AttemptState,
|
|
207
|
+
replaySource: Request,
|
|
208
|
+
error: ApiError | HttpError,
|
|
209
|
+
): Promise<void> {
|
|
210
|
+
state.unauthorizedReplayUsed = true;
|
|
211
|
+
try {
|
|
212
|
+
state.request = await decorateRequest(context, replaySource.clone());
|
|
213
|
+
} catch (cause) {
|
|
214
|
+
throwIfAborted(state.request.signal, context.requestId);
|
|
215
|
+
if (cause instanceof NetworkError) {
|
|
216
|
+
throw cause;
|
|
217
|
+
}
|
|
218
|
+
throw error;
|
|
219
|
+
}
|
|
220
|
+
state.replaySource = cloneRequest(state.request);
|
|
221
|
+
if (state.replaySource === undefined) {
|
|
222
|
+
throw error;
|
|
223
|
+
}
|
|
224
|
+
state.useOriginalRequest = true;
|
|
225
|
+
state.retries = 0;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
async function handleFailure(
|
|
229
|
+
context: FetchContext,
|
|
230
|
+
state: AttemptState,
|
|
231
|
+
cause: unknown,
|
|
232
|
+
): Promise<AttemptOutcome> {
|
|
233
|
+
if (cause instanceof ApiError || cause instanceof HttpError) {
|
|
234
|
+
throw cause;
|
|
235
|
+
}
|
|
236
|
+
const aborted = state.request.signal.aborted || isAbortError(cause);
|
|
237
|
+
if (
|
|
238
|
+
!aborted &&
|
|
239
|
+
state.replaySource !== undefined &&
|
|
240
|
+
shouldRetryMethod(state.request, context.retry) &&
|
|
241
|
+
state.retries < context.retry.maxRetries
|
|
242
|
+
) {
|
|
243
|
+
await backOff(context, state);
|
|
244
|
+
return RETRY;
|
|
245
|
+
}
|
|
246
|
+
throw new NetworkError(
|
|
247
|
+
aborted ? 'API request was aborted' : 'API network request failed',
|
|
248
|
+
context.requestId,
|
|
249
|
+
cause,
|
|
250
|
+
aborted,
|
|
251
|
+
);
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
async function backOff(context: FetchContext, state: AttemptState): Promise<void> {
|
|
255
|
+
await retryDelay(state.retries, context.retry, state.request.signal, context.requestId);
|
|
256
|
+
state.retries += 1;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
async function decorateRequest(context: FetchContext, request: Request): Promise<Request> {
|
|
260
|
+
const { options, requestId } = context;
|
|
261
|
+
throwIfAborted(request.signal, requestId);
|
|
262
|
+
const headers = new Headers(request.headers);
|
|
263
|
+
headers.set(REQUEST_ID_HEADER, requestId);
|
|
264
|
+
|
|
265
|
+
if (options.tokenProvider !== undefined) {
|
|
266
|
+
const token = await options.tokenProvider();
|
|
267
|
+
throwIfAborted(request.signal, requestId);
|
|
268
|
+
headers.delete('authorization');
|
|
269
|
+
if (token !== null) {
|
|
270
|
+
headers.set('authorization', `Bearer ${token}`);
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
if (options.traceparentProvider !== undefined) {
|
|
275
|
+
const traceparent = await options.traceparentProvider(request);
|
|
276
|
+
throwIfAborted(request.signal, requestId);
|
|
277
|
+
if (traceparent !== null) {
|
|
278
|
+
headers.set('traceparent', traceparent);
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
return new context.requestConstructor(request, { headers });
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
function cloneRequest(request: Request): Request | undefined {
|
|
286
|
+
try {
|
|
287
|
+
return request.clone();
|
|
288
|
+
} catch {
|
|
289
|
+
return undefined;
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
function createRequest(
|
|
294
|
+
input: RequestInfo | URL,
|
|
295
|
+
init: RequestInit | undefined,
|
|
296
|
+
baseUrl: string,
|
|
297
|
+
requestConstructor: typeof Request,
|
|
298
|
+
): Request {
|
|
299
|
+
if (typeof input === 'string' || input instanceof URL) {
|
|
300
|
+
return new requestConstructor(new URL(input.toString(), `${baseUrl}/`), init);
|
|
301
|
+
}
|
|
302
|
+
return new requestConstructor(input, init);
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
function createUuid(): string {
|
|
306
|
+
// Runtime probe: React Native and older runtimes may lack `crypto` despite the DOM lib typing.
|
|
307
|
+
const runtime: { readonly crypto?: Crypto } = globalThis;
|
|
308
|
+
const cryptoApi = runtime.crypto;
|
|
309
|
+
if (typeof cryptoApi?.randomUUID === 'function') {
|
|
310
|
+
return cryptoApi.randomUUID();
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
const bytes = new Uint8Array(16);
|
|
314
|
+
if (typeof cryptoApi?.getRandomValues === 'function') {
|
|
315
|
+
cryptoApi.getRandomValues(bytes);
|
|
316
|
+
} else {
|
|
317
|
+
for (let index = 0; index < bytes.length; index += 1) {
|
|
318
|
+
bytes[index] = Math.floor(Math.random() * 256);
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x40;
|
|
322
|
+
bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80;
|
|
323
|
+
const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
|
|
324
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
325
|
+
}
|
package/src/headers.ts
ADDED