@securitydept/client 0.3.0-beta.3 → 0.3.0-beta.5

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 (58) hide show
  1. package/README.md +6 -0
  2. package/dist/create-Bm-XRA3G.mjs +1573 -0
  3. package/dist/create-Bm-XRA3G.mjs.map +1 -0
  4. package/dist/index-BT-u3qNI.d.mts +133 -0
  5. package/dist/index-Ch8lrE44.d.mts +625 -0
  6. package/dist/index-D5mW18cM.d.mts +1648 -0
  7. package/dist/index.d.mts +3 -353
  8. package/dist/index.mjs +1124 -362
  9. package/dist/index.mjs.map +1 -1
  10. package/dist/router-BJ8LqNJ1.mjs +245 -0
  11. package/dist/router-BJ8LqNJ1.mjs.map +1 -0
  12. package/dist/rx/index.d.mts +69 -0
  13. package/dist/rx/index.mjs +2 -0
  14. package/dist/rx-BoB32Dzg.mjs +1106 -0
  15. package/dist/rx-BoB32Dzg.mjs.map +1 -0
  16. package/dist/server/index.d.mts +21 -0
  17. package/dist/server/index.mjs +29 -0
  18. package/dist/server/index.mjs.map +1 -0
  19. package/dist/test/index.d.mts +102 -0
  20. package/dist/test/index.mjs +270 -0
  21. package/dist/test/index.mjs.map +1 -0
  22. package/dist/uri-string-BfnIT4gJ.mjs +298 -0
  23. package/dist/uri-string-BfnIT4gJ.mjs.map +1 -0
  24. package/dist/web/index.d.mts +82 -364
  25. package/dist/web/index.mjs +329 -428
  26. package/dist/web/index.mjs.map +1 -1
  27. package/dist/webext/index.d.mts +74 -0
  28. package/dist/webext/index.mjs +229 -0
  29. package/dist/webext/index.mjs.map +1 -0
  30. package/package.json +28 -21
  31. package/dist/auth-coordination/index.d.mts +0 -198
  32. package/dist/auth-coordination/index.mjs +0 -107
  33. package/dist/auth-coordination/index.mjs.map +0 -1
  34. package/dist/client-environment-CaumNmir.mjs +0 -812
  35. package/dist/client-environment-CaumNmir.mjs.map +0 -1
  36. package/dist/client-environment-CdHtVxKW.d.mts +0 -401
  37. package/dist/events/index.d.mts +0 -2
  38. package/dist/events/index.mjs +0 -2
  39. package/dist/events-BUlfsRfl.mjs +0 -127
  40. package/dist/events-BUlfsRfl.mjs.map +0 -1
  41. package/dist/index-C4xlKhG7.d.mts +0 -102
  42. package/dist/index-COUt5x9Z.d.mts +0 -39
  43. package/dist/persistence/index.d.mts +0 -3
  44. package/dist/persistence/index.mjs +0 -2
  45. package/dist/persistence/web/index.d.mts +0 -16
  46. package/dist/persistence/web/index.mjs +0 -2
  47. package/dist/persistence-CSB8770k.mjs +0 -108
  48. package/dist/persistence-CSB8770k.mjs.map +0 -1
  49. package/dist/planner-host-BTWie0lo.mjs +0 -197
  50. package/dist/planner-host-BTWie0lo.mjs.map +0 -1
  51. package/dist/planner-host-DN9dRsQx.d.mts +0 -190
  52. package/dist/types-BJqUdH2e.d.mts +0 -32
  53. package/dist/types-BwcnUGNl.d.mts +0 -52
  54. package/dist/web-DQmMqZnR.mjs +0 -51
  55. package/dist/web-DQmMqZnR.mjs.map +0 -1
  56. package/dist/web-router/index.d.mts +0 -259
  57. package/dist/web-router/index.mjs +0 -395
  58. package/dist/web-router/index.mjs.map +0 -1
@@ -1,812 +0,0 @@
1
- import { n as createSessionStorageStore, t as createLocalStorageStore } from "./web-DQmMqZnR.mjs";
2
- //#region src/errors/types.ts
3
- /** Recovery actions the user might take. Aligned with server-side `UserRecovery`. */
4
- const UserRecovery = {
5
- None: "none",
6
- Retry: "retry",
7
- RestartFlow: "restart_flow",
8
- Reauthenticate: "reauthenticate",
9
- ContactSupport: "contact_support"
10
- };
11
- const ErrorPresentationTone = {
12
- Neutral: "neutral",
13
- Warning: "warning",
14
- Danger: "danger"
15
- };
16
- /** Machine-facing error kind discriminator. */
17
- const ClientErrorKind = {
18
- Authorization: "authorization",
19
- Transport: "transport",
20
- Server: "server",
21
- Protocol: "protocol",
22
- Presentation: "presentation",
23
- Validation: "validation",
24
- Storage: "storage",
25
- Scheduler: "scheduler",
26
- Configuration: "configuration",
27
- Unauthenticated: "unauthenticated",
28
- Unauthorized: "unauthorized",
29
- RedirectRequired: "redirect_required",
30
- Cancelled: "cancelled",
31
- Timeout: "timeout",
32
- Internal: "internal"
33
- };
34
- /** Stable source vocabulary for common client error producers. */
35
- const ClientErrorSource = {
36
- Transport: "transport",
37
- Server: "server",
38
- ClientEnvironment: "client_environment"
39
- };
40
- //#endregion
41
- //#region src/errors/client-error.ts
42
- function mapServerErrorKind(kind, status) {
43
- switch (kind) {
44
- case "unauthenticated": return ClientErrorKind.Unauthenticated;
45
- case "unauthorized": return ClientErrorKind.Unauthorized;
46
- case "unavailable":
47
- case "internal": return ClientErrorKind.Server;
48
- case "invalid_request":
49
- case "conflict": return ClientErrorKind.Protocol;
50
- default: return status === 401 ? ClientErrorKind.Unauthenticated : status === 403 ? ClientErrorKind.Unauthorized : status >= 500 ? ClientErrorKind.Server : ClientErrorKind.Protocol;
51
- }
52
- }
53
- function readServerErrorBody(body) {
54
- if (!body || typeof body !== "object") return void 0;
55
- const record = body;
56
- const error = record.error && typeof record.error === "object" ? record.error : record;
57
- return {
58
- kind: typeof error.kind === "string" ? error.kind : void 0,
59
- code: typeof error.code === "string" ? error.code : void 0,
60
- message: typeof error.message === "string" ? error.message : void 0,
61
- recovery: typeof error.recovery === "string" ? error.recovery : void 0,
62
- presentation: error.presentation && typeof error.presentation === "object" ? {
63
- code: typeof error.presentation.code === "string" ? error.presentation.code : void 0,
64
- message: typeof error.presentation.message === "string" ? error.presentation.message : void 0,
65
- recovery: typeof error.presentation.recovery === "string" ? error.presentation.recovery : void 0
66
- } : void 0
67
- };
68
- }
69
- /**
70
- * Base client error carrying both machine-facing context and an optional
71
- * user-facing presentation layer.
72
- *
73
- * Top-level `code` and `recovery` provide stable machine contracts for
74
- * policy decisions without requiring callers to unwrap `presentation`.
75
- */
76
- var ClientError = class ClientError extends Error {
77
- kind;
78
- /**
79
- * Stable machine-readable error code.
80
- * Matches `presentation.code` when present, otherwise a default
81
- * derived from `kind`.
82
- */
83
- code;
84
- /** Recovery hint at the machine level. */
85
- recovery;
86
- /** Whether this error is safe to retry. */
87
- retryable;
88
- /** Structured user-facing error presentation from the server. */
89
- presentation;
90
- /** Source subsystem or component that produced the error. */
91
- source;
92
- constructor(options) {
93
- super(options.message, { cause: options.cause });
94
- this.name = "ClientError";
95
- this.kind = options.kind;
96
- this.code = options.code ?? options.presentation?.code ?? `client.${options.kind}`;
97
- this.recovery = options.recovery ?? options.presentation?.recovery ?? UserRecovery.None;
98
- this.retryable = options.retryable ?? this.recovery === UserRecovery.Retry;
99
- this.presentation = options.presentation;
100
- this.source = options.source;
101
- }
102
- /** Create a `ClientError` from a server error response body. */
103
- static fromServerError(body, overrides) {
104
- const rawPresentation = body.presentation;
105
- const presentation = (rawPresentation?.code ?? body.code) && (rawPresentation?.message ?? body.message) ? {
106
- code: rawPresentation?.code ?? body.code ?? "unknown_server_error",
107
- message: rawPresentation?.message ?? body.message ?? "Unknown server error",
108
- recovery: rawPresentation?.recovery ?? body.recovery ?? UserRecovery.None
109
- } : void 0;
110
- return new ClientError({
111
- kind: overrides?.kind ?? mapServerErrorKind(body.kind, 400),
112
- message: presentation?.message ?? body.message ?? "Unknown server error",
113
- presentation,
114
- source: overrides?.source
115
- });
116
- }
117
- /**
118
- * Create a `ClientError` from an HTTP response status and optional body.
119
- * Used when a non-success status is unexpected.
120
- */
121
- static fromHttpResponse(status, body) {
122
- const serverBody = readServerErrorBody(body);
123
- const kind = mapServerErrorKind(serverBody?.kind, status);
124
- const source = status >= 500 ? ClientErrorSource.Server : ClientErrorSource.ClientEnvironment;
125
- if (serverBody?.code && serverBody?.message) return ClientError.fromServerError(serverBody, {
126
- kind,
127
- source
128
- });
129
- const recovery = kind === ClientErrorKind.Unauthenticated ? UserRecovery.Reauthenticate : status >= 500 ? UserRecovery.Retry : UserRecovery.None;
130
- return new ClientError({
131
- kind,
132
- message: serverBody?.message ?? `HTTP ${status}`,
133
- code: serverBody?.code ?? `http.${status}`,
134
- recovery,
135
- retryable: status >= 500,
136
- source
137
- });
138
- }
139
- };
140
- //#endregion
141
- //#region src/logging/types.ts
142
- const LogLevel = {
143
- Debug: "debug",
144
- Info: "info",
145
- Warn: "warn",
146
- Error: "error"
147
- };
148
- const OperationTraceEventType = {
149
- Started: "operation.started",
150
- Event: "operation.event",
151
- Error: "operation.error",
152
- Ended: "operation.ended"
153
- };
154
- //#endregion
155
- //#region src/logging/operation-tracer.ts
156
- const defaultClock = { now: () => Date.now() };
157
- function createDefaultOperationId() {
158
- return `op_${Math.random().toString(36).slice(2, 10)}`;
159
- }
160
- var DefaultOperationScope = class {
161
- _name;
162
- _clock;
163
- _traceSink;
164
- _logger;
165
- _scope;
166
- _source;
167
- id;
168
- _attributes;
169
- _ended = false;
170
- constructor(_name, _clock, _traceSink, _logger, _scope, _source, idFactory, attributes) {
171
- this._name = _name;
172
- this._clock = _clock;
173
- this._traceSink = _traceSink;
174
- this._logger = _logger;
175
- this._scope = _scope;
176
- this._source = _source;
177
- this.id = idFactory();
178
- this._attributes = { ...attributes ?? {} };
179
- this._recordTrace(OperationTraceEventType.Started, {
180
- operationName: this._name,
181
- ...this._attributes
182
- });
183
- }
184
- addEvent(type, attributes) {
185
- this._recordTrace(OperationTraceEventType.Event, {
186
- operationName: this._name,
187
- eventType: type,
188
- ...this._attributes,
189
- ...attributes ?? {}
190
- });
191
- }
192
- setAttribute(key, value) {
193
- this._attributes[key] = value;
194
- }
195
- recordError(error, attributes) {
196
- const errorAttributes = describeError(error);
197
- this._recordTrace(OperationTraceEventType.Error, {
198
- operationName: this._name,
199
- ...this._attributes,
200
- ...errorAttributes,
201
- ...attributes ?? {}
202
- });
203
- this._logger?.log({
204
- level: LogLevel.Error,
205
- message: `Operation failed: ${this._name}`,
206
- scope: this._scope,
207
- attributes: {
208
- operationId: this.id,
209
- operationName: this._name,
210
- ...this._attributes,
211
- ...errorAttributes,
212
- ...attributes ?? {}
213
- },
214
- error,
215
- at: this._clock.now()
216
- });
217
- }
218
- end(attributes) {
219
- if (this._ended) return;
220
- this._ended = true;
221
- this._recordTrace(OperationTraceEventType.Ended, {
222
- operationName: this._name,
223
- ...this._attributes,
224
- ...attributes ?? {}
225
- });
226
- }
227
- _recordTrace(type, attributes) {
228
- this._traceSink?.record({
229
- type,
230
- at: this._clock.now(),
231
- scope: this._scope,
232
- source: this._source,
233
- operationId: this.id,
234
- attributes
235
- });
236
- }
237
- };
238
- function createOperationTracer(options = {}) {
239
- const clock = options.clock ?? defaultClock;
240
- const idFactory = options.idFactory ?? createDefaultOperationId;
241
- return { startOperation(name, attributes) {
242
- return new DefaultOperationScope(name, clock, options.traceSink, options.logger, options.scope, options.source, idFactory, attributes);
243
- } };
244
- }
245
- function describeError(error) {
246
- if (typeof error === "object" && error !== null && "name" in error && "message" in error) {
247
- const genericError = error;
248
- return {
249
- errorName: genericError.name,
250
- errorMessage: genericError.message
251
- };
252
- }
253
- return { errorValue: String(error) };
254
- }
255
- //#endregion
256
- //#region src/scheduling/default-clock.ts
257
- /** Default clock backed by `Date.now()`. */
258
- function createDefaultClock() {
259
- return { now() {
260
- return Date.now();
261
- } };
262
- }
263
- //#endregion
264
- //#region src/scheduling/default-scheduler.ts
265
- /** Default scheduler backed by platform `setTimeout`. */
266
- function createDefaultScheduler() {
267
- return { setTimeout(delayMs, fn) {
268
- const id = globalThis.setTimeout(fn, delayMs);
269
- return { cancel() {
270
- globalThis.clearTimeout(id);
271
- } };
272
- } };
273
- }
274
- //#endregion
275
- //#region src/runtime/create-runtime.ts
276
- /**
277
- * Create a `ClientEnvironment` with non-host-specific defaults filled in for
278
- * convenience.
279
- *
280
- * Host-specific capabilities such as browser `fetch` should be supplied
281
- * explicitly or composed via adapter-specific helpers such as
282
- * `@securitydept/client/web`.
283
- */
284
- function createClientEnvironment(overrides) {
285
- const clock = overrides.clock ?? createDefaultClock();
286
- const traceSink = overrides.traceSink;
287
- const logger = overrides.logger;
288
- return {
289
- transport: overrides.transport,
290
- scheduler: overrides.scheduler ?? createDefaultScheduler(),
291
- clock,
292
- logger,
293
- traceSink,
294
- operationTracer: overrides.operationTracer ?? createOperationTracer({
295
- clock,
296
- logger,
297
- traceSink
298
- }),
299
- persistentStore: overrides.persistentStore,
300
- sessionStore: overrides.sessionStore
301
- };
302
- }
303
- //#endregion
304
- //#region src/scheduling/helpers.ts
305
- const PromiseSettlementKind = {
306
- Fulfilled: "fulfilled",
307
- Rejected: "rejected"
308
- };
309
- /**
310
- * Schedule a one-shot callback after a delay.
311
- *
312
- * Returns a {@link CancelableHandle} that can cancel the pending timer.
313
- *
314
- * @example
315
- * ```ts
316
- * const handle = timer({
317
- * scheduler: runtime.scheduler,
318
- * delayMs: 5000,
319
- * callback: () => console.log("fired"),
320
- * });
321
- * // Cancel before it fires:
322
- * handle.cancel();
323
- * ```
324
- */
325
- function timer(options) {
326
- return options.scheduler.setTimeout(options.delayMs, options.callback);
327
- }
328
- /**
329
- * Schedule a repeating callback at a fixed interval.
330
- *
331
- * Built on top of `Scheduler.setTimeout` so it works with deterministic
332
- * test schedulers. Returns a {@link CancelableHandle} to stop the interval.
333
- *
334
- * @example
335
- * ```ts
336
- * const handle = interval({
337
- * scheduler: runtime.scheduler,
338
- * periodMs: 30_000,
339
- * callback: () => refreshTokens(),
340
- * });
341
- * // Stop:
342
- * handle.cancel();
343
- * ```
344
- */
345
- function interval(options) {
346
- let canceled = false;
347
- let currentHandle = null;
348
- function tick() {
349
- if (canceled) return;
350
- options.callback();
351
- scheduleNext();
352
- }
353
- function scheduleNext() {
354
- if (canceled) return;
355
- currentHandle = options.scheduler.setTimeout(options.periodMs, tick);
356
- }
357
- scheduleNext();
358
- return { cancel() {
359
- canceled = true;
360
- currentHandle?.cancel();
361
- currentHandle = null;
362
- } };
363
- }
364
- /**
365
- * Schedule a callback at a specific wall-clock time.
366
- *
367
- * Computes the delay from `clock.now()` to `atMs` and delegates to
368
- * `Scheduler.setTimeout`. If the target time is already in the past,
369
- * the callback fires on the next scheduler tick (delay 0).
370
- *
371
- * @example
372
- * ```ts
373
- * const handle = scheduleAt({
374
- * scheduler: runtime.scheduler,
375
- * clock: runtime.clock,
376
- * atMs: tokenExpiresAtMs - 30_000,
377
- * callback: () => refreshToken(),
378
- * });
379
- * ```
380
- */
381
- function scheduleAt(options) {
382
- const delay = Math.max(0, options.atMs - options.clock.now());
383
- return options.scheduler.setTimeout(delay, options.callback);
384
- }
385
- /**
386
- * Adapt an SDK signal into the shared {@link Subscription} callback model.
387
- *
388
- * @example
389
- * ```ts
390
- * const sub = fromSignal({
391
- * signal: authState,
392
- * callback: (snapshot) => console.log(snapshot),
393
- * });
394
- * sub.unsubscribe();
395
- * ```
396
- */
397
- function fromSignal(options) {
398
- if (options.emitInitialValue) options.callback(options.signal.get());
399
- const unsubscribe = options.signal.subscribe(() => {
400
- options.callback(options.signal.get());
401
- });
402
- return { unsubscribe() {
403
- unsubscribe();
404
- } };
405
- }
406
- /**
407
- * Adapt a promise settlement into the shared {@link Subscription} callback model.
408
- *
409
- * This helper is intentionally thin: it reports one settlement and lets the
410
- * consumer decide how to model pending/fulfilled/error state.
411
- *
412
- * @example
413
- * ```ts
414
- * const sub = fromPromise({
415
- * promise: fetchConfig(),
416
- * callback: (settlement) => {
417
- * if (settlement.kind === PromiseSettlementKind.Fulfilled) {
418
- * console.log(settlement.value);
419
- * }
420
- * },
421
- * });
422
- * sub.unsubscribe();
423
- * ```
424
- */
425
- function fromPromise(options) {
426
- let active = true;
427
- Promise.resolve(options.promise).then((value) => {
428
- if (!active) return;
429
- options.callback({
430
- kind: PromiseSettlementKind.Fulfilled,
431
- value
432
- });
433
- }, (reason) => {
434
- if (!active) return;
435
- options.callback({
436
- kind: PromiseSettlementKind.Rejected,
437
- reason
438
- });
439
- });
440
- return { unsubscribe() {
441
- active = false;
442
- } };
443
- }
444
- /**
445
- * Adapt an arbitrary add/remove event pattern into a {@link Subscription}.
446
- *
447
- * This is a thin bridge between imperative event APIs (e.g. `addEventListener`
448
- * / `removeEventListener`) and the SDK's subscription model.
449
- *
450
- * @example
451
- * ```ts
452
- * const sub = fromEventPattern<Event>({
453
- * addHandler: (h) => document.addEventListener("visibilitychange", h),
454
- * removeHandler: (h) => document.removeEventListener("visibilitychange", h),
455
- * callback: () => onVisibilityChange(),
456
- * });
457
- * // Cleanup:
458
- * sub.unsubscribe();
459
- * ```
460
- */
461
- function fromEventPattern(options) {
462
- const handler = (value) => {
463
- options.callback(value);
464
- };
465
- options.addHandler(handler);
466
- return { unsubscribe() {
467
- options.removeHandler(handler);
468
- } };
469
- }
470
- //#endregion
471
- //#region src/web/input-sources.ts
472
- /**
473
- * Adapt a browser AbortSignal into the shared Subscription model.
474
- */
475
- function fromAbortSignal(options) {
476
- const signal = options.signal;
477
- if (!signal) return { unsubscribe() {} };
478
- if (options.emitIfAborted && signal.aborted) options.callback(signal.reason);
479
- return fromEventPattern({
480
- addHandler: (handler) => {
481
- signal.addEventListener("abort", handler);
482
- },
483
- removeHandler: (handler) => {
484
- signal.removeEventListener("abort", handler);
485
- },
486
- callback: () => {
487
- options.callback(signal.reason);
488
- }
489
- });
490
- }
491
- /**
492
- * Adapt browser `storage` events into the shared Subscription model.
493
- */
494
- function fromStorageEvent(options) {
495
- const target = options.target ?? globalThis;
496
- return fromEventPattern({
497
- addHandler: (handler) => {
498
- target.addEventListener("storage", handler);
499
- },
500
- removeHandler: (handler) => {
501
- target.removeEventListener("storage", handler);
502
- },
503
- callback: (event) => {
504
- options.callback(event);
505
- }
506
- });
507
- }
508
- //#endregion
509
- //#region src/web/cancellation.ts
510
- /**
511
- * Bridge a web `AbortSignal` back into the foundation cancellation contract.
512
- *
513
- * This is the canonical consumer-side path for browser hosts that receive an
514
- * `AbortSignal` from framework/runtime APIs (for example React Query queryFns)
515
- * but need to call SDK surfaces that accept `CancellationTokenTrait`.
516
- */
517
- function createCancellationTokenFromAbortSignal(signal) {
518
- if (!signal) return;
519
- return {
520
- get isCancellationRequested() {
521
- return signal.aborted;
522
- },
523
- get reason() {
524
- return signal.reason;
525
- },
526
- onCancellationRequested(listener) {
527
- const subscription = fromAbortSignal({
528
- signal,
529
- callback: listener,
530
- emitIfAborted: true
531
- });
532
- return { dispose() {
533
- subscription.unsubscribe();
534
- } };
535
- },
536
- throwIfCancellationRequested() {
537
- if (signal.aborted) throw new ClientError({
538
- kind: ClientErrorKind.Cancelled,
539
- message: "Request was cancelled via AbortSignal",
540
- code: "client.cancelled",
541
- source: ClientErrorSource.Transport,
542
- cause: signal.reason
543
- });
544
- }
545
- };
546
- }
547
- /**
548
- * Bridge foundation cancellation to web `AbortSignal` without exposing
549
- * `AbortSignal` in core contracts.
550
- */
551
- function createAbortSignalBridge(token) {
552
- if (!token) return {
553
- signal: void 0,
554
- dispose() {}
555
- };
556
- const controller = new AbortController();
557
- let subscription = token.onCancellationRequested((reason) => {
558
- controller.abort(reason);
559
- });
560
- if (token.isCancellationRequested) controller.abort(token.reason);
561
- return {
562
- signal: controller.signal,
563
- dispose() {
564
- subscription?.dispose();
565
- subscription = null;
566
- }
567
- };
568
- }
569
- function normalizeAbortError(token, error) {
570
- if (!isAbortError(error) && !token?.isCancellationRequested) return error;
571
- const reason = token?.reason;
572
- if (reason instanceof ClientError) return reason;
573
- if (reason instanceof Error) return new ClientError({
574
- kind: ClientErrorKind.Cancelled,
575
- message: reason.message,
576
- code: "client.cancelled",
577
- source: ClientErrorSource.Transport,
578
- cause: reason
579
- });
580
- return new ClientError({
581
- kind: ClientErrorKind.Cancelled,
582
- message: "HTTP request was cancelled",
583
- code: "client.cancelled",
584
- source: ClientErrorSource.Transport,
585
- cause: reason ?? error
586
- });
587
- }
588
- function isAbortError(error) {
589
- return typeof error === "object" && error !== null && "name" in error && error.name === "AbortError";
590
- }
591
- //#endregion
592
- //#region src/transport/fetch-transport.ts
593
- const FetchTransportRedirectKind = {
594
- Follow: "follow",
595
- Manual: "manual"
596
- };
597
- /**
598
- * Default `HttpTransport` backed by the global `fetch` API.
599
- *
600
- * The caller is responsible for ensuring `fetch` is available in the runtime.
601
- * No polyfill is injected — see the polyfill strategy in the design guide.
602
- */
603
- function createFetchTransport(options = {}) {
604
- const redirect = options.redirect ?? FetchTransportRedirectKind.Manual;
605
- return { async execute(request) {
606
- const abortBridge = createAbortSignalBridge(request.cancellationToken);
607
- const init = {
608
- method: request.method,
609
- headers: request.headers,
610
- redirect,
611
- signal: abortBridge.signal
612
- };
613
- if (request.body !== void 0 && request.method !== "GET" && request.method !== "HEAD") init.body = typeof request.body === "string" ? request.body : JSON.stringify(request.body);
614
- try {
615
- const res = await fetch(request.url, init);
616
- const responseHeaders = {};
617
- res.headers.forEach((value, key) => {
618
- responseHeaders[key] = value;
619
- });
620
- let body;
621
- if (res.headers.get("content-type")?.includes("application/json")) body = await res.json();
622
- else if (res.status !== 302 && res.status !== 303 && res.status !== 301) body = await res.text();
623
- return {
624
- status: res.status,
625
- headers: responseHeaders,
626
- body
627
- };
628
- } catch (error) {
629
- throw normalizeAbortError(request.cancellationToken, error);
630
- } finally {
631
- abortBridge.dispose();
632
- }
633
- } };
634
- }
635
- //#endregion
636
- //#region src/web/runtime.ts
637
- /**
638
- * Create a `ClientEnvironment` for browser/Web-capable environments.
639
- */
640
- function createWebClientEnvironmentDependencies(overrides = {}) {
641
- const { fetchTransport, transport, ...environment } = overrides;
642
- return createClientEnvironment({
643
- ...environment,
644
- transport: transport ?? createFetchTransport(fetchTransport)
645
- });
646
- }
647
- //#endregion
648
- //#region src/web/client-environment.ts
649
- const ClientEnvironmentPreset = {
650
- BrowserPage: "browser_page",
651
- BrowserWorker: "browser_worker",
652
- ServiceWorker: "service_worker",
653
- BrowserExtensionBackground: "browser_extension_background"
654
- };
655
- const PAGE_LOCATION_ERROR_MESSAGE = "browser redirect helpers require a page-like window.location.\nFor extension background or service worker hosts, keep redirects in a real page context or pass explicit location capability.";
656
- const PAGE_LOCATION_HISTORY_ERROR_MESSAGE = "backend-oidc page callback bootstrap requires a page-like window.location and window.history.\nFor extension background or service worker hosts, use restore-only flow or pass explicit location/history/store capabilities.";
657
- const EXPLICIT_PAGE_ENVIRONMENT_ERROR_MESSAGE = "page helpers require an explicit page environment.\nCreate one in your composition root with createBrowserPageClientEnvironment(...).\nFor worker, service worker, or extension background hosts, keep page-only redirects and callbacks in a real page context.";
658
- const EXPLICIT_PAGE_LOCATION_HISTORY_CAPABILITY_ERROR_MESSAGE = "page helpers require an explicit page environment with location and history.\nCreate one in your composition root with createBrowserPageClientEnvironment(...), or pass an explicit pageCapability override.";
659
- const BROWSER_PERSISTENT_PREFIX = "securitydept.web.client:";
660
- const BROWSER_SESSION_PREFIX = "securitydept.web.client:";
661
- function createWebClientEnvironment(options = {}) {
662
- const { preset, ...environmentOptions } = options;
663
- return {
664
- ...createWebClientEnvironmentDependencies(environmentOptions),
665
- preset
666
- };
667
- }
668
- function deriveClientEnvironment(environment) {
669
- return {
670
- transport: environment.transport,
671
- scheduler: environment.scheduler,
672
- clock: environment.clock,
673
- logger: environment.logger,
674
- traceSink: environment.traceSink,
675
- operationTracer: environment.operationTracer,
676
- persistentStore: environment.persistentStore,
677
- sessionStore: environment.sessionStore
678
- };
679
- }
680
- function createBrowserPageClientEnvironment(options = {}) {
681
- const pageCapability = options.pageCapability ? assertPageLocationHistoryCapability(options.pageCapability) : requireDefaultPageLocationHistoryCapability();
682
- return {
683
- ...createWebClientEnvironment({
684
- ...withDefaultBrowserStores(options),
685
- preset: ClientEnvironmentPreset.BrowserPage
686
- }),
687
- ...pageCapability
688
- };
689
- }
690
- function readDefaultPageLocationCapability() {
691
- const windowLike = globalThis.window;
692
- if (!isObject(windowLike)) return null;
693
- const location = windowLike.location;
694
- return readPageLocationCapability({ location });
695
- }
696
- function requireDefaultPageLocationCapability() {
697
- const pageCapability = readDefaultPageLocationCapability();
698
- if (!pageCapability) throw new Error(PAGE_LOCATION_ERROR_MESSAGE);
699
- return pageCapability;
700
- }
701
- function createBrowserWorkerClientEnvironment(options = {}) {
702
- return createWebClientEnvironment({
703
- ...options,
704
- preset: ClientEnvironmentPreset.BrowserWorker
705
- });
706
- }
707
- function createServiceWorkerClientEnvironment(options = {}) {
708
- return createWebClientEnvironment({
709
- ...options,
710
- preset: ClientEnvironmentPreset.ServiceWorker
711
- });
712
- }
713
- function createBrowserExtensionBackgroundClientEnvironment(options = {}) {
714
- return createWebClientEnvironment({
715
- ...options,
716
- preset: ClientEnvironmentPreset.BrowserExtensionBackground
717
- });
718
- }
719
- function assertResolveEnvironment(environment, onResolvingEnvironmentFail) {
720
- if (environment === null || environment === void 0) return onResolvingEnvironmentFail();
721
- return environment;
722
- }
723
- function assertResolveFromEnvironment(environment, select, onResolvingCapabilityFail) {
724
- const resolvedValue = select(assertResolveEnvironment(environment, onResolvingCapabilityFail));
725
- if (resolvedValue === null || resolvedValue === void 0) return onResolvingCapabilityFail();
726
- return resolvedValue;
727
- }
728
- function requirePageClientEnvironment(environmentOrOptions) {
729
- const options = normalizeRequirePageClientEnvironmentOptions(environmentOrOptions);
730
- const environment = assertResolveEnvironment(options.environment, failMissingPageEnvironment);
731
- const pageCapability = resolvePageLocationHistoryCapability(options, environment);
732
- return {
733
- ...environment,
734
- ...pageCapability
735
- };
736
- }
737
- function readDefaultPageLocationHistoryCapability() {
738
- const windowLike = globalThis.window;
739
- if (!isObject(windowLike)) return null;
740
- const location = windowLike.location;
741
- const history = windowLike.history;
742
- return readPageLocationHistoryCapability({
743
- location,
744
- history
745
- });
746
- }
747
- function requireDefaultPageLocationHistoryCapability() {
748
- const pageCapability = readDefaultPageLocationHistoryCapability();
749
- if (!pageCapability) throw new Error(PAGE_LOCATION_HISTORY_ERROR_MESSAGE);
750
- return pageCapability;
751
- }
752
- function readPageLocationCapability(input) {
753
- const location = input.location;
754
- if (!isPageLocationLike(location)) return null;
755
- return { location };
756
- }
757
- function readPageLocationHistoryCapability(input) {
758
- const pageCapability = readPageLocationCapability(input);
759
- const history = input.history;
760
- if (!pageCapability || !isPageHistoryLike(history)) return null;
761
- return {
762
- ...pageCapability,
763
- history
764
- };
765
- }
766
- function assertPageLocationCapability(pageCapability, fieldName = "environment") {
767
- if (!isObject(pageCapability)) throw new Error(`${fieldName} must include location.href and location.hash.\n${PAGE_LOCATION_ERROR_MESSAGE}`);
768
- const normalized = readPageLocationCapability(pageCapability);
769
- if (!normalized) throw new Error(`${fieldName} must include location.href and location.hash.\n${PAGE_LOCATION_ERROR_MESSAGE}`);
770
- return normalized;
771
- }
772
- function assertPageLocationHistoryCapability(pageCapability, fieldName = "pageCapability") {
773
- if (!isObject(pageCapability)) throw new Error(`${fieldName} must include location.href, location.hash, and history.replaceState.\n${PAGE_LOCATION_HISTORY_ERROR_MESSAGE}`);
774
- const normalized = readPageLocationHistoryCapability(pageCapability);
775
- if (!normalized) throw new Error(`${fieldName} must include location.href, location.hash, and history.replaceState.\n${PAGE_LOCATION_HISTORY_ERROR_MESSAGE}`);
776
- return normalized;
777
- }
778
- function normalizeRequirePageClientEnvironmentOptions(environmentOrOptions) {
779
- if (!environmentOrOptions) return {};
780
- if ("transport" in environmentOrOptions) return { environment: environmentOrOptions };
781
- return environmentOrOptions;
782
- }
783
- function resolvePageLocationHistoryCapability(options, environment) {
784
- if (options.pageCapability !== void 0) return assertPageLocationHistoryCapability(options.pageCapability, "pageCapability");
785
- return assertResolveFromEnvironment(environment, (candidateEnvironment) => readPageLocationHistoryCapability(candidateEnvironment), failMissingPageLocationHistoryCapability);
786
- }
787
- function failMissingPageEnvironment() {
788
- throw new Error(EXPLICIT_PAGE_ENVIRONMENT_ERROR_MESSAGE);
789
- }
790
- function failMissingPageLocationHistoryCapability() {
791
- throw new Error(EXPLICIT_PAGE_LOCATION_HISTORY_CAPABILITY_ERROR_MESSAGE);
792
- }
793
- function withDefaultBrowserStores(options) {
794
- return {
795
- ...options,
796
- persistentStore: options.persistentStore ?? createLocalStorageStore(BROWSER_PERSISTENT_PREFIX),
797
- sessionStore: options.sessionStore ?? createSessionStorageStore(BROWSER_SESSION_PREFIX)
798
- };
799
- }
800
- function isObject(value) {
801
- return typeof value === "object" && value !== null;
802
- }
803
- function isPageLocationLike(value) {
804
- return isObject(value) && typeof value.href === "string" && typeof value.hash === "string";
805
- }
806
- function isPageHistoryLike(value) {
807
- return isObject(value) && typeof value.replaceState === "function";
808
- }
809
- //#endregion
810
- export { interval as A, ClientErrorKind as B, normalizeAbortError as C, fromEventPattern as D, PromiseSettlementKind as E, createDefaultClock as F, ErrorPresentationTone as H, createOperationTracer as I, LogLevel as L, timer as M, createClientEnvironment as N, fromPromise as O, createDefaultScheduler as P, OperationTraceEventType as R, createCancellationTokenFromAbortSignal as S, fromStorageEvent as T, UserRecovery as U, ClientErrorSource as V, requireDefaultPageLocationHistoryCapability as _, assertResolveFromEnvironment as a, createFetchTransport as b, createBrowserWorkerClientEnvironment as c, deriveClientEnvironment as d, readDefaultPageLocationCapability as f, requireDefaultPageLocationCapability as g, readPageLocationHistoryCapability as h, assertResolveEnvironment as i, scheduleAt as j, fromSignal as k, createServiceWorkerClientEnvironment as l, readPageLocationCapability as m, assertPageLocationCapability as n, createBrowserExtensionBackgroundClientEnvironment as o, readDefaultPageLocationHistoryCapability as p, assertPageLocationHistoryCapability as r, createBrowserPageClientEnvironment as s, ClientEnvironmentPreset as t, createWebClientEnvironment as u, requirePageClientEnvironment as v, fromAbortSignal as w, createAbortSignalBridge as x, FetchTransportRedirectKind as y, ClientError as z };
811
-
812
- //# sourceMappingURL=client-environment-CaumNmir.mjs.map