@tearleads/client-sdk 0.1.251 → 0.1.252
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/Tearleads.d.ts +0 -2
- package/Tearleads.js +14 -25
- package/Tearleads.js.map +1 -1
- package/client/organizations/organizationReadModelPresentation.js +7 -4
- package/client/organizations/organizationReadModelPresentation.js.map +1 -1
- package/client/organizations/organizationReadModels.js +6 -5
- package/client/organizations/organizationReadModels.js.map +1 -1
- package/client/organizations/organizationWorkflowRuntime.js +1 -1
- package/client/organizations/organizationWorkflowRuntime.js.map +1 -1
- package/client/runtime/principalMutationApi.d.ts +4 -0
- package/client/runtime/principalMutationApi.js +9 -5
- package/client/runtime/principalMutationApi.js.map +1 -1
- package/client/runtime/runtimeIdentityResolution.js +23 -0
- package/client/runtime/runtimeIdentityResolution.js.map +1 -1
- package/client/runtime/runtimeSubscription.js +68 -0
- package/client/runtime/runtimeSubscription.js.map +1 -0
- package/client/runtime/workflowRuntime.d.ts +1 -1
- package/client/runtime/workflowRuntime.js +20 -77
- package/client/runtime/workflowRuntime.js.map +1 -1
- package/client/session/authenticationMachine.js +47 -0
- package/client/session/authenticationMachine.js.map +1 -0
- package/client/session/index.js +75 -93
- package/client/session/index.js.map +1 -1
- package/client/session/sessionBlobStore.js +39 -0
- package/client/session/sessionBlobStore.js.map +1 -0
- package/client/session/sessionContext.js +11 -0
- package/client/session/sessionContext.js.map +1 -1
- package/client/session/sessionIdentityTrust.d.ts +2 -1
- package/client/session/sessionIdentityTrust.js +8 -4
- package/client/session/sessionIdentityTrust.js.map +1 -1
- package/client/session/sessionLifetime.js +87 -0
- package/client/session/sessionLifetime.js.map +1 -0
- package/client/session/sessionLogin.js +114 -0
- package/client/session/sessionLogin.js.map +1 -0
- package/client/session/sessionOrganizationCreation.js +3 -2
- package/client/session/sessionOrganizationCreation.js.map +1 -1
- package/client/session/sessionPurgeRecovery.js +11 -3
- package/client/session/sessionPurgeRecovery.js.map +1 -1
- package/client/session/sessionTypes.d.ts +6 -2
- package/client/session/sessionTypes.js.map +1 -1
- package/data/blobs/blobContracts.d.ts +4 -3
- package/data/blobs/blobContracts.js.map +1 -1
- package/data/blobs/createBlobStore.js +1 -8
- package/data/blobs/createBlobStore.js.map +1 -1
- package/data/blobs/encryptedBlobStore.js +17 -12
- package/data/blobs/encryptedBlobStore.js.map +1 -1
- package/data/blobs/memoryBlobStore.js +8 -5
- package/data/blobs/memoryBlobStore.js.map +1 -1
- package/data/blobs/opfsBlobFile.js +36 -0
- package/data/blobs/opfsBlobFile.js.map +1 -0
- package/data/blobs/opfsBlobStore.d.ts +1 -1
- package/data/blobs/opfsBlobStore.js +91 -21
- package/data/blobs/opfsBlobStore.js.map +1 -1
- package/data/principals/principalPolicyCoordinator.js +8 -17
- package/data/principals/principalPolicyCoordinator.js.map +1 -1
- package/data/shared/domainScope.d.ts +2 -0
- package/data/shared/domainScope.js +2 -1
- package/data/shared/domainScope.js.map +1 -1
- package/data/shared/keyedQueue.js +15 -0
- package/data/shared/keyedQueue.js.map +1 -0
- package/data/sqlite/migrations/migrateLocalSchema.js +2 -3
- package/data/sqlite/migrations/migrateLocalSchema.js.map +1 -1
- package/data/sqlite/sqlExec.d.ts +6 -0
- package/data/sqlite/sqlExec.js +64 -13
- package/data/sqlite/sqlExec.js.map +1 -1
- package/data/sqlite/sqlitePersistenceRuntime.js +2 -3
- package/data/sqlite/sqlitePersistenceRuntime.js.map +1 -1
- package/data/trustedUserIdentity/service.js +2 -1
- package/data/trustedUserIdentity/service.js.map +1 -1
- package/data/trustedUserIdentity/types.d.ts +1 -1
- package/data/trustedUserIdentity/types.js.map +1 -1
- package/internal/api-client/ApiClient.d.ts +4 -1
- package/internal/api-client/apiRequestRuntime.d.ts +6 -3
- package/internal/api-client/apiRequestRuntime.js +86 -101
- package/internal/api-client/apiRequestRuntime.js.map +1 -1
- package/internal/api-client/binaryRequestOperationTransport.js +2 -1
- package/internal/api-client/binaryRequestOperationTransport.js.map +1 -1
- package/internal/api-client/binaryResponseOperationTransport.js +6 -2
- package/internal/api-client/binaryResponseOperationTransport.js.map +1 -1
- package/internal/api-client/client/blobs.d.ts +1 -0
- package/internal/api-client/client/blobs.js +12 -3
- package/internal/api-client/client/blobs.js.map +1 -1
- package/internal/api-client/client/laneListingRequest.js +4 -0
- package/internal/api-client/client/laneListingRequest.js.map +1 -1
- package/internal/api-client/client/session.d.ts +5 -1
- package/internal/api-client/client/session.js +12 -4
- package/internal/api-client/client/session.js.map +1 -1
- package/internal/api-client/client/writerProjections.js +12 -13
- package/internal/api-client/client/writerProjections.js.map +1 -1
- package/internal/api-client/operationResponse.d.ts +1 -1
- package/internal/api-client/operationResponse.js +10 -23
- package/internal/api-client/operationResponse.js.map +1 -1
- package/internal/api-client/operationTransport.js +2 -1
- package/internal/api-client/operationTransport.js.map +1 -1
- package/internal/api-client/principalHistoryRequest.js +25 -20
- package/internal/api-client/principalHistoryRequest.js.map +1 -1
- package/internal/api-client/principalHistoryRequestContext.js +30 -6
- package/internal/api-client/principalHistoryRequestContext.js.map +1 -1
- package/internal/api-client/principalPolicyPages.d.ts +4 -1
- package/internal/api-client/principalPolicyPages.js +4 -2
- package/internal/api-client/principalPolicyPages.js.map +1 -1
- package/internal/api-client/projectionPolicyHistoryPages.d.ts +4 -1
- package/internal/api-client/projectionPolicyHistoryPages.js +4 -2
- package/internal/api-client/projectionPolicyHistoryPages.js.map +1 -1
- package/internal/api-client/routes/blobs/blobDownloadBody.js +65 -0
- package/internal/api-client/routes/blobs/blobDownloadBody.js.map +1 -0
- package/internal/api-client/routes/blobs/get.js +9 -67
- package/internal/api-client/routes/blobs/get.js.map +1 -1
- package/internal/api-client/routes/blobs/multipartUpload.js +1 -1
- package/internal/api-client/routes/blobs/multipartUpload.js.map +1 -1
- package/internal/api-client/sessionRefresh.js +1 -1
- package/internal/api-client/sessionRefresh.js.map +1 -1
- package/internal/api-client/sessionRenewal.d.ts +31 -0
- package/internal/api-client/sessionRenewal.js +91 -6
- package/internal/api-client/sessionRenewal.js.map +1 -1
- package/internal/api-client/sessionRequestInit.js +22 -0
- package/internal/api-client/sessionRequestInit.js.map +1 -0
- package/internal/api-client/sessionResponse.js +39 -0
- package/internal/api-client/sessionResponse.js.map +1 -0
- package/internal/api-client/types.d.ts +1 -0
- package/internal/api-client/types.js.map +1 -1
- package/internal/api-client/webSocketTickets.d.ts +1 -0
- package/internal/api-client/webSocketTickets.js +4 -0
- package/internal/api-client/webSocketTickets.js.map +1 -1
- package/internal/sqlite-worker/client.d.ts +1 -1
- package/internal/sqlite-worker/client.js +6 -1
- package/internal/sqlite-worker/client.js.map +1 -1
- package/internal/sqlite-worker/purgeOpfsDatabase.d.ts +1 -1
- package/internal/sqlite-worker/purgeOpfsDatabase.js +3 -2
- package/internal/sqlite-worker/purgeOpfsDatabase.js.map +1 -1
- package/internal/sqlite-worker/types.d.ts +4 -0
- package/internal/sqlite-worker/types.js.map +1 -1
- package/package.json +1 -1
- package/sqlite/worker.js +1 -1
- package/workflows/documents/attachments/blobMutationLock.d.ts +1 -1
- package/workflows/documents/attachments/blobMutationLock.js +2 -2
- package/workflows/documents/attachments/blobMutationLock.js.map +1 -1
- package/workflows/organizations/readModel/readModelProjection.js +2 -0
- package/workflows/organizations/readModel/readModelProjection.js.map +1 -1
- package/workflows/registration/registerIdentity.js +2 -0
- package/workflows/registration/registerIdentity.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"AAEA,MAAM,CAAC,MAAM,oCAAoC,GAAG,CAAC,CAAC;AACtD,MAAM,CAAC,MAAM,mCAAmC,GAAG,WAAW,CAAC;AAC/D,MAAM,CAAC,MAAM,yCAAyC,GAAG,aAAa,CAAC;AAEvE,MAAM,wBAAwB,GAAkB,MAAM,CAAC,qBAAqB,CAAC,CAAC;AAC9E,MAAM,6BAA6B,GAAG,IAAI,CAAC;
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"AAEA,MAAM,CAAC,MAAM,oCAAoC,GAAG,CAAC,CAAC;AACtD,MAAM,CAAC,MAAM,mCAAmC,GAAG,WAAW,CAAC;AAC/D,MAAM,CAAC,MAAM,yCAAyC,GAAG,aAAa,CAAC;AAEvE,MAAM,wBAAwB,GAAkB,MAAM,CAAC,qBAAqB,CAAC,CAAC;AAC9E,MAAM,6BAA6B,GAAG,IAAI,CAAC;AAwJ3C,MAAM,UAAU,wBAAwB,CACtC,KAAqC;IAErC,OAAO;QACL,GAAG,KAAK;QACR,CAAC,wBAAwB,CAAC,EAAE,6BAA6B;KAC1D,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,qBAAqB,CACnC,KAAc;IAEd,OAAO,CACL,OAAO,KAAK,KAAK,QAAQ;QACzB,KAAK,KAAK,IAAI;QACd,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,wBAAwB,CAAC;YAC1C,6BAA6B,CAChC,CAAC;AACJ,CAAC","sourcesContent":["import type { ExecSql } from \"../sqlite/sqlSchema\";\n\nexport const TRUSTED_USER_IDENTITY_FORMAT_VERSION = 1;\nexport const TRUSTED_USER_IDENTITY_SIGNING_SUITE = \"ML-DSA-87\";\nexport const TRUSTED_USER_IDENTITY_ENCAPSULATION_SUITE = \"ML-KEM-1024\";\n\nconst trustedUserIdentityBrand: unique symbol = Symbol(\"trustedUserIdentity\");\nconst trustedUserIdentityBrandValue = true;\n\n/**\n * A complete user identity bundle that has passed strict key validation and\n * the durable pin comparison for its trust domain.\n *\n * The nominal brand keeps raw API and organization response objects from being\n * accepted at cryptographic boundaries by structural typing. Its private\n * symbol and constructor remain package-private to the SDK trust gateway.\n */\nexport interface TrustedUserIdentity {\n readonly [trustedUserIdentityBrand]: true;\n readonly encapsulationKeyFingerprint: string;\n readonly encapsulationPublicKey: Uint8Array;\n readonly identityTrustDomain: string;\n readonly signingKeyFingerprint: string;\n readonly signingPublicKey: Uint8Array;\n readonly userId: string;\n}\n\n/** Strictly decoded and self-consistent, but not yet accepted by durable TOFU. */\nexport interface ValidatedUserIdentityCandidate {\n readonly encapsulationKeyFingerprint: string;\n readonly encapsulationPublicKey: Uint8Array;\n readonly identityTrustDomain: string;\n readonly signingKeyFingerprint: string;\n readonly signingPublicKey: Uint8Array;\n readonly userId: string;\n}\n\nexport interface RemoteUserIdentityCandidate {\n readonly encapsulationKeyFingerprint: string;\n readonly encapsulationPublicKey: string;\n readonly signingKeyFingerprint: string;\n readonly signingPublicKey: string;\n readonly userId: string;\n}\n\nexport interface RemoteUserIdentitySource {\n invalidate(userId: string): void;\n /**\n * `null` only when the server asserts the user does not exist. A transport\n * or non-404 HTTP failure throws a retryable availability error instead.\n */\n load(userId: string): Promise<RemoteUserIdentityCandidate | null>;\n}\n\nexport interface LocalUserIdentityCandidate {\n readonly encapsulationPublicKey: Uint8Array;\n readonly signingKeyFingerprint?: string | null | undefined;\n readonly signingPublicKey: Uint8Array;\n}\n\n/** An existing pin as an admission reads it: never admits by itself. */\nexport interface TrustedUserIdentityAdmissionPin {\n readonly identity: TrustedUserIdentity;\n /** Established by a verified identity link or this device's own keys. */\n readonly verified: boolean;\n}\n\nexport interface TrustedUserIdentityService {\n createLink(appUrl: string): Promise<string>;\n /**\n * Link for `userId` from a pin a verified link or this device's keys\n * established; the local user's own keys for the signed-in user; `null`\n * when no such pin exists (never from an observed pin).\n */\n createLinkFor(userId: string, appUrl: string): Promise<string | null>;\n verifyLink(link: string): Promise<TrustedUserIdentity>;\n /** Any existing pin, including one observed on first sight. Never admits. */\n resolvePinned(userId: string): Promise<TrustedUserIdentity | null>;\n /** An existing pin established by a verified link or this device's keys. */\n resolveVerified(userId: string): Promise<TrustedUserIdentity | null>;\n /**\n * Like `resolveVerified`, but throws `UnverifiedUserIdentityError`. An\n * admission passes the database its mutation captured: a trust store that\n * is not, or stops being, that database fails with `DatabaseUnavailableError`\n * instead of admitting against another scope.\n */\n requireVerified(\n userId: string,\n admittingExecSql: ExecSql | null,\n ): Promise<TrustedUserIdentity>;\n /**\n * Any existing pin and whether a link or this device's keys established it,\n * read with `requireVerified`'s database scoping. Admissions that accept\n * evidence other than a verified pin compare against it.\n */\n loadAdmissionPin(\n userId: string,\n admittingExecSql: ExecSql | null,\n ): Promise<TrustedUserIdentityAdmissionPin | null>;\n /** The user this device's trust store already binds a signing key to. */\n boundUserId(signingKeyFingerprint: string): Promise<string | null>;\n pinLocal(\n userId: string,\n candidate: LocalUserIdentityCandidate,\n assertCurrent?: () => void,\n ): Promise<TrustedUserIdentity>;\n /** Pins on first sight as `observed`; for users signed state references. */\n resolve: TrustedUserIdentityResolver;\n}\n\n/**\n * Within one structural check: an existing pin, this user's own local keys,\n * or a first-sight candidate that is staged rather than pinned.\n */\nexport type StagedUserIdentityResolver = (\n userId: string,\n) => Promise<ValidatedUserIdentityCandidate | null>;\n\nexport interface StagedUserIdentityOptions {\n /**\n * Pin staged first sights as `observed` once `verify` succeeds. Set only\n * when the checked projections' signed states already verified: data an\n * unauthenticated projection names must never reach the durable store.\n */\n readonly publish: boolean;\n /**\n * The calling operation's own lifetime (cancellation, superseded recovery),\n * checked with the trust store's scope at every step and inside each pin's\n * write transaction, so a cancelled operation commits no first sight.\n */\n readonly assertCurrent?: (() => void) | undefined;\n}\n\n/** Callable resolution always compares the candidate with durable pins.\n * Structural commitment verification may reuse validated immutable pins for\n * one scoped operation; this capability never admits users or promotes pins.\n */\nexport type TrustedUserIdentityResolver = ((\n userId: string,\n) => Promise<TrustedUserIdentity | null>) & {\n readonly withPinnedIdentities?: <T>(\n userIds: readonly string[],\n verify: (resolve: StagedUserIdentityResolver) => Promise<T>,\n options: StagedUserIdentityOptions,\n ) => Promise<T>;\n};\n\nexport interface TrustedUserIdentityServiceDependencies {\n readonly getExecSql: () => ExecSql | null;\n readonly getScopeGeneration?: (() => unknown) | undefined;\n readonly getLocalIdentity: (\n userId: string,\n ) => LocalUserIdentityCandidate | null;\n readonly getLocalUserId: () => string | null;\n readonly identityTrustDomain: string | null;\n readonly now?: (() => Date) | undefined;\n readonly remoteSource: RemoteUserIdentitySource;\n}\n\nexport function brandTrustedUserIdentity(\n input: ValidatedUserIdentityCandidate,\n): TrustedUserIdentity {\n return {\n ...input,\n [trustedUserIdentityBrand]: trustedUserIdentityBrandValue,\n };\n}\n\nexport function isTrustedUserIdentity(\n value: unknown,\n): value is TrustedUserIdentity {\n return (\n typeof value === \"object\" &&\n value !== null &&\n Reflect.get(value, trustedUserIdentityBrand) ===\n trustedUserIdentityBrandValue\n );\n}\n"]}
|
|
@@ -14,7 +14,10 @@ export declare class ApiClient extends ApiClientAreas {
|
|
|
14
14
|
setOnSessionExpired: (handler: (() => boolean | Promise<boolean>) | null) => void;
|
|
15
15
|
setOnPaymentRequired: (handler: ((organizationId: string | null) => void) | null) => void;
|
|
16
16
|
setVerifiedManifestCitations: (source: import("./verifiedManifestCitations.js").VerifiedManifestCitations | null) => void;
|
|
17
|
-
setAuthToken: (token: string | null
|
|
17
|
+
setAuthToken: (token: string | null, options?: {
|
|
18
|
+
boundary?: import("./sessionRenewal.js").SessionBoundary | undefined;
|
|
19
|
+
verifiedTicket?: string | undefined;
|
|
20
|
+
}) => void;
|
|
18
21
|
getAuthToken: () => string | null;
|
|
19
22
|
getRequestFailure: (input: {
|
|
20
23
|
method: import("./types.js").HttpMethod;
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { ApiRequestInstrumentation } from "./apiRequestMetrics.js";
|
|
2
2
|
import { type ApiNetworkError } from "./networkFailure.js";
|
|
3
|
-
import
|
|
3
|
+
import { type SessionBoundary } from "./sessionRenewal.js";
|
|
4
|
+
import type { HttpMethod, OperationRequestFn, OperationRequestResultFn, OperationResponseRequestFn, RequestFailure, RequestResultOptions } from "./types.js";
|
|
4
5
|
type ExpiredHandler = () => boolean | Promise<boolean>;
|
|
5
6
|
type PaymentRequiredHandler = (organizationId: string | null) => void;
|
|
6
7
|
export declare class ApiRequestRuntime {
|
|
@@ -37,17 +38,19 @@ export declare class ApiRequestRuntime {
|
|
|
37
38
|
setOnApiVersion(handler: ((version: number) => void) | null): void;
|
|
38
39
|
setOnSessionExpired(handler: ExpiredHandler | null): void;
|
|
39
40
|
setOnPaymentRequired(handler: PaymentRequiredHandler | null): void;
|
|
40
|
-
setAuthToken(token: string | null): boolean;
|
|
41
|
+
setAuthToken(token: string | null, boundary?: SessionBoundary): boolean;
|
|
42
|
+
captureCredential(): () => boolean | Promise<boolean>;
|
|
43
|
+
withSessionSignal(options: RequestResultOptions): RequestResultOptions;
|
|
41
44
|
getAuthToken(): string | null;
|
|
42
45
|
getRequestFailure(input: {
|
|
43
46
|
method: HttpMethod;
|
|
44
47
|
path: string;
|
|
45
48
|
}): RequestFailure | null;
|
|
46
|
-
private buildHeaders;
|
|
47
49
|
private makeRequest;
|
|
48
50
|
private requestFailure;
|
|
49
51
|
private makeRequestResult;
|
|
50
52
|
private makeResponseRequest;
|
|
53
|
+
private retiredResponse;
|
|
51
54
|
private fetchResponseRequest;
|
|
52
55
|
private httpFailure;
|
|
53
56
|
private reportResponseRequestFailure;
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { authChallengeSigningBytes, canonicalAuthOrigin, } from "../crypto/index.js";
|
|
2
1
|
import { apiVersionHeaderName, parseApiVersion, } from "../validators/operation/index.js";
|
|
3
2
|
import { measureApiRequest } from "./measureApiRequest.js";
|
|
4
3
|
import { networkFailureMessage, settleNetworkFailure, } from "./networkFailure.js";
|
|
5
|
-
import { bindPrototypeMethods, describeErrorResponse,
|
|
6
|
-
import { responseBodyFailure } from "./responseBodyFailure.js";
|
|
4
|
+
import { bindPrototypeMethods, describeErrorResponse, isSuccessfulResponse, normalizeApiBaseUrl, requestFailureKey, } from "./requestInternals.js";
|
|
7
5
|
import { shouldRetryAfterSessionExpired } from "./sessionRefresh.js";
|
|
8
|
-
import { SessionRenewalTracker } from "./sessionRenewal.js";
|
|
6
|
+
import { SessionRenewalTracker, sessionAuthChallengeBytes, } from "./sessionRenewal.js";
|
|
7
|
+
import { sessionRequestInit } from "./sessionRequestInit.js";
|
|
8
|
+
import { readSessionJson, retiredRequest } from "./sessionResponse.js";
|
|
9
9
|
export class ApiRequestRuntime {
|
|
10
10
|
instrumentation;
|
|
11
11
|
authToken = null;
|
|
@@ -30,6 +30,7 @@ export class ApiRequestRuntime {
|
|
|
30
30
|
this.requestResult = this.makeRequestResult;
|
|
31
31
|
this.responseRequest = Object.assign(this.makeResponseRequest, {
|
|
32
32
|
reportFailure: this.reportResponseRequestFailure,
|
|
33
|
+
sessionSignal: () => this.sessionRenewals.signal,
|
|
33
34
|
});
|
|
34
35
|
}
|
|
35
36
|
/**
|
|
@@ -38,14 +39,7 @@ export class ApiRequestRuntime {
|
|
|
38
39
|
* do; with neither, there is no API origin to sign for.
|
|
39
40
|
*/
|
|
40
41
|
authChallengeBytes(challengeHex, fingerprint) {
|
|
41
|
-
|
|
42
|
-
try {
|
|
43
|
-
apiOrigin = canonicalAuthOrigin(new URL(this.baseUrl || "/", globalThis.location?.href).href);
|
|
44
|
-
}
|
|
45
|
-
catch {
|
|
46
|
-
throw new Error("The API origin is unavailable for authentication");
|
|
47
|
-
}
|
|
48
|
-
return authChallengeSigningBytes({ apiOrigin, challengeHex, fingerprint });
|
|
42
|
+
return sessionAuthChallengeBytes(this.baseUrl, challengeHex, fingerprint);
|
|
49
43
|
}
|
|
50
44
|
setOnError(handler) {
|
|
51
45
|
this.onError = handler;
|
|
@@ -74,28 +68,27 @@ export class ApiRequestRuntime {
|
|
|
74
68
|
setOnPaymentRequired(handler) {
|
|
75
69
|
this.onPaymentRequired = handler;
|
|
76
70
|
}
|
|
77
|
-
setAuthToken(token) {
|
|
78
|
-
const changed = this.authToken !== token;
|
|
71
|
+
setAuthToken(token, boundary) {
|
|
72
|
+
const changed = Boolean(boundary) || this.authToken !== token;
|
|
73
|
+
if (boundary)
|
|
74
|
+
this.requestFailuresByKey.clear();
|
|
79
75
|
if (changed)
|
|
80
|
-
this.sessionRenewals.tokenChanged();
|
|
76
|
+
this.sessionRenewals.tokenChanged(boundary);
|
|
81
77
|
this.authToken = token;
|
|
82
78
|
return changed;
|
|
83
79
|
}
|
|
80
|
+
captureCredential() {
|
|
81
|
+
return this.sessionRenewals.captureCredential();
|
|
82
|
+
}
|
|
83
|
+
withSessionSignal(options) {
|
|
84
|
+
return this.sessionRenewals.withSessionSignal(options);
|
|
85
|
+
}
|
|
84
86
|
getAuthToken() {
|
|
85
87
|
return this.authToken;
|
|
86
88
|
}
|
|
87
89
|
getRequestFailure(input) {
|
|
88
90
|
return this.requestFailuresByKey.get(requestFailureKey(input)) ?? null;
|
|
89
91
|
}
|
|
90
|
-
buildHeaders(body, headers, authToken) {
|
|
91
|
-
return {
|
|
92
|
-
...(authToken ? { Authorization: `Bearer ${authToken}` } : {}),
|
|
93
|
-
...(typeof body === "string" && !hasHeader(headers, "Content-Type")
|
|
94
|
-
? { "Content-Type": "application/json" }
|
|
95
|
-
: {}),
|
|
96
|
-
...headers,
|
|
97
|
-
};
|
|
98
|
-
}
|
|
99
92
|
async makeRequest(path, validator, method, body, options, failureOperation) {
|
|
100
93
|
const result = await this.makeRequestResult(path, validator, method, body, options, failureOperation);
|
|
101
94
|
return result.ok ? result.data : null;
|
|
@@ -129,31 +122,19 @@ export class ApiRequestRuntime {
|
|
|
129
122
|
return failure;
|
|
130
123
|
}
|
|
131
124
|
async makeRequestResult(path, validator, method, body, options, failureOperation) {
|
|
125
|
+
const session = this.sessionRenewals.signal;
|
|
132
126
|
const responseResult = await this.makeResponseRequest(path, method, body, options ?? {}, [], failureOperation);
|
|
133
127
|
if (!responseResult.ok) {
|
|
134
128
|
return responseResult;
|
|
135
129
|
}
|
|
136
130
|
const response = responseResult.data;
|
|
137
131
|
const reportErrors = options?.reportErrors ?? true;
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
if (failure.kind === "network")
|
|
145
|
-
this.onNetworkError?.();
|
|
146
|
-
return this.requestFailure({
|
|
147
|
-
...failure,
|
|
148
|
-
message: `${method} ${path}: ${failure.message}`,
|
|
149
|
-
method,
|
|
150
|
-
path,
|
|
151
|
-
reportErrors: failure.kind !== "cancelled" && reportErrors,
|
|
152
|
-
stalePrincipalHeads: undefined,
|
|
153
|
-
status: response.status,
|
|
154
|
-
statusText: response.statusText,
|
|
155
|
-
});
|
|
156
|
-
}
|
|
132
|
+
const decoded = await readSessionJson(this.responseRequest, response, method, path, options ?? {}, session);
|
|
133
|
+
if (session.aborted)
|
|
134
|
+
return retiredRequest(method, path);
|
|
135
|
+
if (!decoded.ok)
|
|
136
|
+
return decoded;
|
|
137
|
+
const data = decoded.data;
|
|
157
138
|
if (!validator(data)) {
|
|
158
139
|
return this.requestFailure({
|
|
159
140
|
kind: "shape",
|
|
@@ -168,17 +149,37 @@ export class ApiRequestRuntime {
|
|
|
168
149
|
}
|
|
169
150
|
return { data, ok: true };
|
|
170
151
|
}
|
|
171
|
-
async makeResponseRequest(path, method, body, options, additionalSuccessStatuses, failureOperation) {
|
|
172
|
-
const
|
|
173
|
-
const
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
const
|
|
152
|
+
async makeResponseRequest(path, method, body, options, additionalSuccessStatuses, failureOperation, authToken = this.authToken, attempt = 1) {
|
|
153
|
+
const session = this.sessionRenewals.signal;
|
|
154
|
+
const callerOptions = options;
|
|
155
|
+
const waitOptions = this.sessionRenewals.withRenewalWaitSignal(options);
|
|
156
|
+
options = this.sessionRenewals.withSessionSignal(options);
|
|
157
|
+
const result = await this.fetchResponseRequest(path, method, body, options, authToken, failureOperation, attempt);
|
|
158
|
+
if (!result.ok)
|
|
159
|
+
return result;
|
|
160
|
+
if (session.aborted)
|
|
161
|
+
return this.retiredResponse(session, method, path, result.data);
|
|
162
|
+
const response = result.data;
|
|
177
163
|
if (isSuccessfulResponse(response, additionalSuccessStatuses)) {
|
|
178
164
|
this.requestFailuresByKey.delete(requestFailureKey({ method, path }));
|
|
179
|
-
return
|
|
165
|
+
return result;
|
|
180
166
|
}
|
|
181
167
|
const errorDescription = await describeErrorResponse(response, failureOperation, options.expectedPaymentRequiredOrganizationId);
|
|
168
|
+
const retired = () => this.retiredResponse(session, method, path, response, errorDescription.code);
|
|
169
|
+
if (session.aborted)
|
|
170
|
+
return retired();
|
|
171
|
+
const failure = {
|
|
172
|
+
errorDescription,
|
|
173
|
+
failureOperation,
|
|
174
|
+
method,
|
|
175
|
+
options,
|
|
176
|
+
path,
|
|
177
|
+
response,
|
|
178
|
+
};
|
|
179
|
+
if (attempt === 2)
|
|
180
|
+
return this.httpFailure(failure);
|
|
181
|
+
// An independent replacement or caller cancellation ends this wait. A
|
|
182
|
+
// refusal from the renewal itself must finish reporting its typed error.
|
|
182
183
|
const shouldRetry = await shouldRetryAfterSessionExpired({
|
|
183
184
|
authToken,
|
|
184
185
|
body,
|
|
@@ -186,74 +187,54 @@ export class ApiRequestRuntime {
|
|
|
186
187
|
getCurrentAuthToken: () => this.authToken,
|
|
187
188
|
isKnownSessionRenewal: (from, to) => this.sessionRenewals.isKnown(from, to),
|
|
188
189
|
pendingSessionRenewal: (from) => this.sessionRenewals.pending(from),
|
|
189
|
-
options,
|
|
190
|
+
options: waitOptions,
|
|
190
191
|
refreshSession: () => this.sessionRenewals.renew(this.onSessionExpired),
|
|
191
192
|
reportError: (message) => this.onError?.(message),
|
|
192
193
|
responseStatus: response.status,
|
|
193
194
|
});
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
failureOperation,
|
|
201
|
-
method,
|
|
202
|
-
options: {
|
|
203
|
-
...options,
|
|
204
|
-
reportErrors: method === "GET" ? false : options.reportErrors,
|
|
205
|
-
},
|
|
206
|
-
path,
|
|
207
|
-
response,
|
|
208
|
-
});
|
|
209
|
-
const retryResult = await this.fetchResponseRequest(path, method, body, options, retryAuthToken, failureOperation, 2);
|
|
210
|
-
if (!retryResult.ok)
|
|
211
|
-
return retryResult;
|
|
212
|
-
const retryResponse = retryResult.data;
|
|
213
|
-
if (isSuccessfulResponse(retryResponse, additionalSuccessStatuses)) {
|
|
214
|
-
this.requestFailuresByKey.delete(requestFailureKey({ method, path }));
|
|
215
|
-
return { data: retryResponse, ok: true };
|
|
216
|
-
}
|
|
195
|
+
if (session.aborted)
|
|
196
|
+
return retired();
|
|
197
|
+
const retryToken = this.sessionRenewals.currentToken(authToken);
|
|
198
|
+
if (!shouldRetry || !retryToken)
|
|
199
|
+
return this.httpFailure(failure);
|
|
200
|
+
if (options.retryOnSessionExpired === "renew-only")
|
|
217
201
|
return this.httpFailure({
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
response: retryResponse,
|
|
202
|
+
...failure,
|
|
203
|
+
options: {
|
|
204
|
+
...options,
|
|
205
|
+
reportErrors: method === "GET" ? false : options.reportErrors,
|
|
206
|
+
},
|
|
224
207
|
});
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
208
|
+
return this.makeResponseRequest(path, method, body, callerOptions, additionalSuccessStatuses, failureOperation, retryToken, 2);
|
|
209
|
+
}
|
|
210
|
+
retiredResponse(session, method, path, response, code) {
|
|
211
|
+
const retired = retiredRequest(method, path);
|
|
212
|
+
// Principal writes refused before dispatch have a definitive outcome.
|
|
213
|
+
if (response.status !== 401 || !this.sessionRenewals.refused(session))
|
|
214
|
+
return retired;
|
|
215
|
+
return {
|
|
216
|
+
...retired,
|
|
217
|
+
kind: "http",
|
|
218
|
+
status: 401,
|
|
219
|
+
statusText: response.statusText,
|
|
220
|
+
code: code ?? undefined,
|
|
221
|
+
message: `${method} ${path}: 401 ${response.statusText}`,
|
|
222
|
+
};
|
|
234
223
|
}
|
|
235
224
|
async fetchResponseRequest(path, method, body, options, authToken, operation,
|
|
236
225
|
/** 2 is the retry after a session renewal. */
|
|
237
226
|
attempt = 1) {
|
|
227
|
+
const session = this.sessionRenewals.signal;
|
|
238
228
|
const reportErrors = options.reportErrors ?? true;
|
|
239
|
-
const headers =
|
|
240
|
-
const init = {
|
|
241
|
-
method,
|
|
242
|
-
headers,
|
|
243
|
-
...(options.signal ? { signal: options.signal } : {}),
|
|
244
|
-
};
|
|
245
|
-
if (body !== undefined) {
|
|
246
|
-
init.body = body;
|
|
247
|
-
if (body instanceof ReadableStream) {
|
|
248
|
-
init.duplex = "half";
|
|
249
|
-
}
|
|
250
|
-
}
|
|
229
|
+
const { headers, init } = sessionRequestInit(method, body, options, authToken);
|
|
251
230
|
let response;
|
|
252
231
|
const startedAt = Date.now();
|
|
253
232
|
try {
|
|
254
233
|
response = await measureApiRequest(this.instrumentation, operation, () => fetch(`${this.baseUrl}${path}`, init), options.signal);
|
|
255
234
|
}
|
|
256
235
|
catch (error) {
|
|
236
|
+
if (session.aborted)
|
|
237
|
+
return retiredRequest(method, path);
|
|
257
238
|
const { cancelled, networkError } = await settleNetworkFailure({
|
|
258
239
|
attempt,
|
|
259
240
|
baseUrl: this.baseUrl,
|
|
@@ -268,6 +249,8 @@ export class ApiRequestRuntime {
|
|
|
268
249
|
signal: options.signal,
|
|
269
250
|
onNetworkFailure: (failure) => this.onNetworkFailure?.(failure),
|
|
270
251
|
});
|
|
252
|
+
if (session.aborted)
|
|
253
|
+
return retiredRequest(method, path);
|
|
271
254
|
return this.requestFailure({
|
|
272
255
|
...(cancelled ? { code: "request_aborted" } : {}),
|
|
273
256
|
kind: cancelled ? "cancelled" : "network",
|
|
@@ -281,6 +264,8 @@ export class ApiRequestRuntime {
|
|
|
281
264
|
statusText: "",
|
|
282
265
|
});
|
|
283
266
|
}
|
|
267
|
+
if (session.aborted)
|
|
268
|
+
return this.retiredResponse(session, method, path, response);
|
|
284
269
|
this.onNetworkSuccess?.();
|
|
285
270
|
const apiVersion = parseApiVersion(response.headers.get(apiVersionHeaderName));
|
|
286
271
|
if (apiVersion !== null)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"apiRequestRuntime.js","sourceRoot":"","sources":["apiRequestRuntime.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,yBAAyB,EACzB,mBAAmB,GACpB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,oBAAoB,EACpB,eAAe,GAChB,MAAM,iCAAiC,CAAC;AAEzC,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,EAEL,qBAAqB,EACrB,oBAAoB,GACrB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EACL,oBAAoB,EACpB,qBAAqB,EAErB,YAAY,EACZ,SAAS,EACT,oBAAoB,EACpB,mBAAmB,EACnB,iBAAiB,GAClB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC5D,OAAO,EAAE,8BAA8B,EAAE,MAAM,kBAAkB,CAAC;AAClE,OAAO,EAAE,qBAAqB,EAAE,MAAM,kBAAkB,CAAC;AAiBzD,MAAM,OAAO,iBAAiB;IAoBT;IAnBX,SAAS,GAAkB,IAAI,CAAC;IACvB,eAAe,GAAG,IAAI,qBAAqB,CAC1D,GAAG,EAAE,CAAC,IAAI,CAAC,SAAS,CACrB,CAAC;IACe,OAAO,CAAS;IACzB,OAAO,GAAuC,IAAI,CAAC;IACnD,cAAc,GAAwB,IAAI,CAAC;IAC3C,gBAAgB,GAAwB,IAAI,CAAC;IAC7C,gBAAgB,GAA8C,IAAI,CAAC;IACnE,YAAY,GAAuC,IAAI,CAAC;IACxD,gBAAgB,GAA0B,IAAI,CAAC;IAC/C,iBAAiB,GAAkC,IAAI,CAAC;IAC/C,oBAAoB,GAAG,IAAI,GAAG,EAA0B,CAAC;IACjE,OAAO,CAAqB;IAC5B,aAAa,CAA2B;IACxC,eAAe,CAA6B;IAErD,YACE,OAAuB,EACN,eAA2C;QAA3C,oBAAe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;QAC1B,CAAC;QACD,OAAO,IAAI,CAAC,cAAc,CAAC;YACzB,GAAG,KAAK;YACR,YAAY,EAAE,KAAK,CAAC,OAAO,EAAE,YAAY,IAAI,IAAI;YACjD,mBAAmB,EAAE,SAAS;SAC/B,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import {\n authChallengeSigningBytes,\n canonicalAuthOrigin,\n} from \"@tearleads/crypto\";\nimport {\n apiVersionHeaderName,\n parseApiVersion,\n} from \"@tearleads/validators/operation\";\nimport type { ApiRequestInstrumentation } from \"./apiRequestMetrics\";\nimport { measureApiRequest } from \"./measureApiRequest\";\nimport {\n type ApiNetworkError,\n networkFailureMessage,\n settleNetworkFailure,\n} from \"./networkFailure\";\nimport {\n bindPrototypeMethods,\n describeErrorResponse,\n type ErrorResponseDescription,\n errorMessage,\n hasHeader,\n isSuccessfulResponse,\n normalizeApiBaseUrl,\n requestFailureKey,\n} from \"./requestInternals\";\nimport { responseBodyFailure } from \"./responseBodyFailure\";\nimport { shouldRetryAfterSessionExpired } from \"./sessionRefresh\";\nimport { SessionRenewalTracker } from \"./sessionRenewal\";\nimport type {\n HttpMethod,\n OperationRequestFn,\n OperationRequestResultFn,\n OperationResponseRequestFn,\n RequestBody,\n RequestFailure,\n RequestFailureKind,\n RequestResult,\n RequestResultOptions,\n ResponseRequestValidationFailureInput,\n} from \"./types\";\n\ntype ExpiredHandler = () => boolean | Promise<boolean>;\ntype PaymentRequiredHandler = (organizationId: string | null) => void;\n\nexport class ApiRequestRuntime {\n private authToken: string | null = null;\n private readonly sessionRenewals = new SessionRenewalTracker(\n () => this.authToken,\n );\n private readonly baseUrl: string;\n private onError: ((message: string) => void) | null = null;\n private onNetworkError: (() => void) | null = null;\n private onNetworkSuccess: (() => void) | null = null;\n private onNetworkFailure: ((error: ApiNetworkError) => void) | null = null;\n private onApiVersion: ((version: number) => void) | null = null;\n private onSessionExpired: ExpiredHandler | null = null;\n private onPaymentRequired: PaymentRequiredHandler | null = null;\n private readonly requestFailuresByKey = new Map<string, RequestFailure>();\n readonly request: OperationRequestFn;\n readonly requestResult: OperationRequestResultFn;\n readonly responseRequest: OperationResponseRequestFn;\n\n constructor(\n baseUrl?: string | null,\n private readonly instrumentation?: ApiRequestInstrumentation,\n ) {\n this.baseUrl = normalizeApiBaseUrl(baseUrl);\n bindPrototypeMethods(this, ApiRequestRuntime.prototype);\n this.request = this.makeRequest;\n this.requestResult = this.makeRequestResult;\n this.responseRequest = Object.assign(this.makeResponseRequest, {\n reportFailure: this.reportResponseRequestFailure,\n });\n }\n\n /**\n * The bytes a login challenge is signed as, bound to the API this client\n * addresses. A relative base URL resolves against the page, as its requests\n * do; with neither, there is no API origin to sign for.\n */\n authChallengeBytes(challengeHex: string, fingerprint: string): Uint8Array {\n let apiOrigin: string;\n try {\n apiOrigin = canonicalAuthOrigin(\n new URL(this.baseUrl || \"/\", globalThis.location?.href).href,\n );\n } catch {\n throw new Error(\"The API origin is unavailable for authentication\");\n }\n return authChallengeSigningBytes({ apiOrigin, challengeHex, fingerprint });\n }\n\n setOnError(handler: ((message: string) => void) | null): void {\n this.onError = handler;\n }\n\n /** Reports a failure carried inside a successful batched response. */\n reportError(message: string): void {\n this.onError?.(message);\n }\n\n setOnNetworkError(handler: (() => void) | null): void {\n this.onNetworkError = handler;\n }\n\n setOnNetworkSuccess(handler: (() => void) | null): void {\n this.onNetworkSuccess = handler;\n }\n\n /** Every fetch that threw without a response, except plain cancellations. */\n setOnNetworkFailure(handler: ((e: ApiNetworkError) => void) | null): void {\n this.onNetworkFailure = handler;\n }\n\n /** Receives the build named by each response that carries one. */\n setOnApiVersion(handler: ((version: number) => void) | null): void {\n this.onApiVersion = handler;\n }\n\n setOnSessionExpired(handler: ExpiredHandler | null): void {\n this.onSessionExpired = handler;\n }\n\n setOnPaymentRequired(handler: PaymentRequiredHandler | null): void {\n this.onPaymentRequired = handler;\n }\n\n setAuthToken(token: string | null): boolean {\n const changed = this.authToken !== token;\n if (changed) this.sessionRenewals.tokenChanged();\n this.authToken = token;\n return changed;\n }\n\n getAuthToken(): string | null {\n return this.authToken;\n }\n\n getRequestFailure(input: { method: HttpMethod; path: string }) {\n return this.requestFailuresByKey.get(requestFailureKey(input)) ?? null;\n }\n\n private buildHeaders(\n body: RequestBody | undefined,\n headers: Record<string, string> | undefined,\n authToken: string | null,\n ): Record<string, string> {\n return {\n ...(authToken ? { Authorization: `Bearer ${authToken}` } : {}),\n ...(typeof body === \"string\" && !hasHeader(headers, \"Content-Type\")\n ? { \"Content-Type\": \"application/json\" }\n : {}),\n ...headers,\n };\n }\n\n private async makeRequest<T>(\n path: string,\n validator: (value: unknown) => value is T,\n method: HttpMethod,\n body: RequestBody | undefined,\n options: RequestResultOptions | undefined,\n failureOperation: Parameters<OperationRequestFn>[5],\n ): Promise<T | null> {\n const result = await this.makeRequestResult(\n path,\n validator,\n method,\n body,\n options,\n failureOperation,\n );\n return result.ok ? result.data : null;\n }\n\n private requestFailure(input: {\n code?: string | undefined;\n kind: RequestFailureKind;\n message: string;\n method: HttpMethod;\n networkError?: ApiNetworkError | undefined;\n path: string;\n reportErrors: boolean;\n requiredContainerIds?: RequestFailure[\"requiredContainerIds\"];\n stalePrincipalHeads: RequestFailure[\"stalePrincipalHeads\"];\n status: number | null;\n statusText: string;\n }): RequestFailure {\n const failure: RequestFailure = {\n ...(input.code === undefined ? {} : { code: input.code }),\n kind: input.kind,\n message: input.message,\n method: input.method,\n ...(input.networkError ? { networkError: input.networkError } : {}),\n ok: false,\n path: input.path,\n report: () => {\n if (input.kind !== \"cancelled\") this.onError?.(input.message);\n },\n status: input.status,\n statusText: input.statusText,\n ...(input.stalePrincipalHeads\n ? { stalePrincipalHeads: input.stalePrincipalHeads }\n : {}),\n ...(input.requiredContainerIds\n ? { requiredContainerIds: input.requiredContainerIds }\n : {}),\n };\n this.requestFailuresByKey.set(\n requestFailureKey({ method: input.method, path: input.path }),\n failure,\n );\n\n if (input.reportErrors) {\n failure.report();\n }\n\n return failure;\n }\n\n private async makeRequestResult<T>(\n path: string,\n validator: (value: unknown) => value is T,\n method: HttpMethod,\n body: RequestBody | undefined,\n options: RequestResultOptions | undefined,\n failureOperation: Parameters<OperationRequestFn>[5],\n ): Promise<RequestResult<T>> {\n const responseResult = await this.makeResponseRequest(\n path,\n method,\n body,\n options ?? {},\n [],\n failureOperation,\n );\n if (!responseResult.ok) {\n return responseResult;\n }\n\n const response = responseResult.data;\n const reportErrors = options?.reportErrors ?? true;\n let data: unknown;\n try {\n data = await response.json();\n } catch (error) {\n const failure = responseBodyFailure(\n error,\n errorMessage(error),\n options?.signal?.aborted === true,\n );\n if (failure.kind === \"network\") this.onNetworkError?.();\n return this.requestFailure({\n ...failure,\n message: `${method} ${path}: ${failure.message}`,\n method,\n path,\n reportErrors: failure.kind !== \"cancelled\" && reportErrors,\n stalePrincipalHeads: undefined,\n status: response.status,\n statusText: response.statusText,\n });\n }\n\n if (!validator(data)) {\n return this.requestFailure({\n kind: \"shape\",\n message: `Invalid response shape for ${path}`,\n method,\n path,\n reportErrors,\n stalePrincipalHeads: undefined,\n status: response.status,\n statusText: response.statusText,\n });\n }\n\n return { data, ok: true };\n }\n\n private async makeResponseRequest(\n path: string,\n method: HttpMethod,\n body: RequestBody | undefined,\n options: RequestResultOptions,\n additionalSuccessStatuses: readonly number[],\n failureOperation: Parameters<OperationResponseRequestFn>[5],\n ): Promise<RequestResult<Response>> {\n const authToken = this.authToken;\n const responseResult = await this.fetchResponseRequest(\n path,\n method,\n body,\n options,\n authToken,\n failureOperation,\n );\n if (!responseResult.ok) return responseResult;\n const response = responseResult.data;\n if (isSuccessfulResponse(response, additionalSuccessStatuses)) {\n this.requestFailuresByKey.delete(requestFailureKey({ method, path }));\n return { data: response, ok: true };\n }\n\n const errorDescription = await describeErrorResponse(\n response,\n failureOperation,\n options.expectedPaymentRequiredOrganizationId,\n );\n const shouldRetry = await shouldRetryAfterSessionExpired({\n authToken,\n body,\n code: errorDescription.code,\n getCurrentAuthToken: () => this.authToken,\n isKnownSessionRenewal: (from, to) =>\n this.sessionRenewals.isKnown(from, to),\n pendingSessionRenewal: (from) => this.sessionRenewals.pending(from),\n options,\n refreshSession: () => this.sessionRenewals.renew(this.onSessionExpired),\n reportError: (message) => this.onError?.(message),\n responseStatus: response.status,\n });\n const retryAuthToken = this.sessionRenewals.currentToken(authToken);\n // Recheck after the awaited helper and the host's renewal notification.\n if (shouldRetry && retryAuthToken) {\n if (options.retryOnSessionExpired === \"renew-only\")\n return this.httpFailure({\n errorDescription,\n failureOperation,\n method,\n options: {\n ...options,\n reportErrors: method === \"GET\" ? false : options.reportErrors,\n },\n path,\n response,\n });\n const retryResult = await this.fetchResponseRequest(\n path,\n method,\n body,\n options,\n retryAuthToken,\n failureOperation,\n 2,\n );\n if (!retryResult.ok) return retryResult;\n const retryResponse = retryResult.data;\n if (isSuccessfulResponse(retryResponse, additionalSuccessStatuses)) {\n this.requestFailuresByKey.delete(requestFailureKey({ method, path }));\n return { data: retryResponse, ok: true };\n }\n\n return this.httpFailure({\n errorDescription: await describeErrorResponse(\n retryResponse,\n failureOperation,\n options.expectedPaymentRequiredOrganizationId,\n ),\n failureOperation,\n method,\n options,\n path,\n response: retryResponse,\n });\n }\n\n return this.httpFailure({\n errorDescription,\n failureOperation,\n method,\n options,\n path,\n response,\n });\n }\n\n private async fetchResponseRequest(\n path: string,\n method: HttpMethod,\n body: RequestBody | undefined,\n options: RequestResultOptions,\n authToken: string | null,\n operation: Parameters<OperationResponseRequestFn>[5],\n /** 2 is the retry after a session renewal. */\n attempt = 1,\n ): Promise<RequestResult<Response>> {\n const reportErrors = options.reportErrors ?? true;\n const headers = this.buildHeaders(body, options.headers, authToken);\n const init: RequestInit & { duplex?: \"half\" } = {\n method,\n headers,\n ...(options.signal ? { signal: options.signal } : {}),\n };\n if (body !== undefined) {\n init.body = body;\n if (body instanceof ReadableStream) {\n init.duplex = \"half\";\n }\n }\n\n let response: Response;\n const startedAt = Date.now();\n try {\n response = await measureApiRequest(\n this.instrumentation,\n operation,\n () => fetch(`${this.baseUrl}${path}`, init),\n options.signal,\n );\n } catch (error) {\n const { cancelled, networkError } = await settleNetworkFailure({\n attempt,\n baseUrl: this.baseUrl,\n elapsedMs: Date.now() - startedAt,\n error,\n headers,\n isOnline: this.instrumentation?.isOnline,\n method,\n onNetworkError: () => this.onNetworkError?.(),\n pathTemplate: operation.path,\n probe: this.instrumentation?.networkFailureProbe,\n signal: options.signal,\n onNetworkFailure: (failure) => this.onNetworkFailure?.(failure),\n });\n return this.requestFailure({\n ...(cancelled ? { code: \"request_aborted\" } : {}),\n kind: cancelled ? \"cancelled\" : \"network\",\n message: `${method} ${path}: ${networkFailureMessage(error, networkError)}`,\n method,\n networkError,\n path,\n reportErrors: cancelled ? false : reportErrors,\n stalePrincipalHeads: undefined,\n status: null,\n statusText: \"\",\n });\n }\n\n this.onNetworkSuccess?.();\n const apiVersion = parseApiVersion(\n response.headers.get(apiVersionHeaderName),\n );\n if (apiVersion !== null) this.onApiVersion?.(apiVersion);\n return { data: response, ok: true };\n }\n\n private httpFailure(input: {\n readonly errorDescription: ErrorResponseDescription;\n readonly failureOperation: Parameters<OperationResponseRequestFn>[5];\n readonly method: HttpMethod;\n readonly options: RequestResultOptions;\n readonly path: string;\n readonly response: Response;\n }): RequestFailure {\n const cancelled = input.options.signal?.aborted === true;\n const reportErrors = input.options.reportErrors ?? true;\n if (\n !cancelled &&\n input.response.status === 402 &&\n input.failureOperation.failureResponses?.[402] &&\n input.errorDescription.paymentRequiredOrganizationId !== undefined &&\n input.errorDescription.paymentRequiredOrganizationId ===\n input.options.expectedPaymentRequiredOrganizationId\n ) {\n this.onPaymentRequired?.(\n input.errorDescription.paymentRequiredOrganizationId,\n );\n }\n return this.requestFailure({\n ...(cancelled\n ? { code: \"request_aborted\" }\n : input.errorDescription.code === null\n ? {}\n : { code: input.errorDescription.code }),\n kind: cancelled ? \"cancelled\" : \"http\",\n message: `${input.method} ${input.path}: ${input.response.status} ${input.response.statusText}${input.errorDescription.detail}`,\n method: input.method,\n path: input.path,\n reportErrors: !cancelled && reportErrors,\n requiredContainerIds: input.errorDescription.requiredContainerIds,\n stalePrincipalHeads: input.errorDescription.stalePrincipalHeads,\n status: input.response.status,\n statusText: input.response.statusText,\n });\n }\n\n private reportResponseRequestFailure(\n input: ResponseRequestValidationFailureInput,\n ): RequestFailure {\n if (input.kind === \"network\") {\n this.onNetworkError?.();\n }\n return this.requestFailure({\n ...input,\n reportErrors: input.options?.reportErrors ?? true,\n stalePrincipalHeads: undefined,\n });\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"apiRequestRuntime.js","sourceRoot":"","sources":["apiRequestRuntime.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oBAAoB,EACpB,eAAe,GAChB,MAAM,iCAAiC,CAAC;AAEzC,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,EAEL,qBAAqB,EACrB,oBAAoB,GACrB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EACL,oBAAoB,EACpB,qBAAqB,EAErB,oBAAoB,EACpB,mBAAmB,EACnB,iBAAiB,GAClB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,8BAA8B,EAAE,MAAM,kBAAkB,CAAC;AAClE,OAAO,EAEL,qBAAqB,EACrB,yBAAyB,GAC1B,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAC1D,OAAO,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAiBpE,MAAM,OAAO,iBAAiB;IAoBT;IAnBX,SAAS,GAAkB,IAAI,CAAC;IACvB,eAAe,GAAG,IAAI,qBAAqB,CAC1D,GAAG,EAAE,CAAC,IAAI,CAAC,SAAS,CACrB,CAAC;IACe,OAAO,CAAS;IACzB,OAAO,GAAuC,IAAI,CAAC;IACnD,cAAc,GAAwB,IAAI,CAAC;IAC3C,gBAAgB,GAAwB,IAAI,CAAC;IAC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AAoB;YACjE,mBAAmB,EAAE,KAAK,CAAC,gBAAgB,CAAC,mBAAmB;YAC/D,MAAM,EAAE,KAAK,CAAC,QAAQ,CAAC,MAAM;YAC7B,UAAU,EAAE,KAAK,CAAC,QAAQ,CAAC,UAAU;SACtC,CAAC,CAAC;IACL,CAAC;IAEO,4BAA4B,CAClC,KAA4C;QAE5C,IAAI,KAAK,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;YAC7B,IAAI,CAAC,cAAc,EAAE,EAAE,CAAC;QAC1B,CAAC;QACD,OAAO,IAAI,CAAC,cAAc,CAAC;YACzB,GAAG,KAAK;YACR,YAAY,EAAE,KAAK,CAAC,OAAO,EAAE,YAAY,IAAI,IAAI;YACjD,mBAAmB,EAAE,SAAS;SAC/B,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import {\n apiVersionHeaderName,\n parseApiVersion,\n} from \"@tearleads/validators/operation\";\nimport type { ApiRequestInstrumentation } from \"./apiRequestMetrics\";\nimport { measureApiRequest } from \"./measureApiRequest\";\nimport {\n type ApiNetworkError,\n networkFailureMessage,\n settleNetworkFailure,\n} from \"./networkFailure\";\nimport {\n bindPrototypeMethods,\n describeErrorResponse,\n type ErrorResponseDescription,\n isSuccessfulResponse,\n normalizeApiBaseUrl,\n requestFailureKey,\n} from \"./requestInternals\";\nimport { shouldRetryAfterSessionExpired } from \"./sessionRefresh\";\nimport {\n type SessionBoundary,\n SessionRenewalTracker,\n sessionAuthChallengeBytes,\n} from \"./sessionRenewal\";\nimport { sessionRequestInit } from \"./sessionRequestInit\";\nimport { readSessionJson, retiredRequest } from \"./sessionResponse\";\nimport type {\n HttpMethod,\n OperationRequestFn,\n OperationRequestResultFn,\n OperationResponseRequestFn,\n RequestBody,\n RequestFailure,\n RequestFailureKind,\n RequestResult,\n RequestResultOptions,\n ResponseRequestValidationFailureInput,\n} from \"./types\";\n\ntype ExpiredHandler = () => boolean | Promise<boolean>;\ntype PaymentRequiredHandler = (organizationId: string | null) => void;\n\nexport class ApiRequestRuntime {\n private authToken: string | null = null;\n private readonly sessionRenewals = new SessionRenewalTracker(\n () => this.authToken,\n );\n private readonly baseUrl: string;\n private onError: ((message: string) => void) | null = null;\n private onNetworkError: (() => void) | null = null;\n private onNetworkSuccess: (() => void) | null = null;\n private onNetworkFailure: ((error: ApiNetworkError) => void) | null = null;\n private onApiVersion: ((version: number) => void) | null = null;\n private onSessionExpired: ExpiredHandler | null = null;\n private onPaymentRequired: PaymentRequiredHandler | null = null;\n private readonly requestFailuresByKey = new Map<string, RequestFailure>();\n readonly request: OperationRequestFn;\n readonly requestResult: OperationRequestResultFn;\n readonly responseRequest: OperationResponseRequestFn;\n\n constructor(\n baseUrl?: string | null,\n private readonly instrumentation?: ApiRequestInstrumentation,\n ) {\n this.baseUrl = normalizeApiBaseUrl(baseUrl);\n bindPrototypeMethods(this, ApiRequestRuntime.prototype);\n this.request = this.makeRequest;\n this.requestResult = this.makeRequestResult;\n this.responseRequest = Object.assign(this.makeResponseRequest, {\n reportFailure: this.reportResponseRequestFailure,\n sessionSignal: () => this.sessionRenewals.signal,\n });\n }\n\n /**\n * The bytes a login challenge is signed as, bound to the API this client\n * addresses. A relative base URL resolves against the page, as its requests\n * do; with neither, there is no API origin to sign for.\n */\n authChallengeBytes(challengeHex: string, fingerprint: string): Uint8Array {\n return sessionAuthChallengeBytes(this.baseUrl, challengeHex, fingerprint);\n }\n\n setOnError(handler: ((message: string) => void) | null): void {\n this.onError = handler;\n }\n\n /** Reports a failure carried inside a successful batched response. */\n reportError(message: string): void {\n this.onError?.(message);\n }\n\n setOnNetworkError(handler: (() => void) | null): void {\n this.onNetworkError = handler;\n }\n\n setOnNetworkSuccess(handler: (() => void) | null): void {\n this.onNetworkSuccess = handler;\n }\n\n /** Every fetch that threw without a response, except plain cancellations. */\n setOnNetworkFailure(handler: ((e: ApiNetworkError) => void) | null): void {\n this.onNetworkFailure = handler;\n }\n\n /** Receives the build named by each response that carries one. */\n setOnApiVersion(handler: ((version: number) => void) | null): void {\n this.onApiVersion = handler;\n }\n\n setOnSessionExpired(handler: ExpiredHandler | null): void {\n this.onSessionExpired = handler;\n }\n\n setOnPaymentRequired(handler: PaymentRequiredHandler | null): void {\n this.onPaymentRequired = handler;\n }\n\n setAuthToken(token: string | null, boundary?: SessionBoundary): boolean {\n const changed = Boolean(boundary) || this.authToken !== token;\n if (boundary) this.requestFailuresByKey.clear();\n if (changed) this.sessionRenewals.tokenChanged(boundary);\n this.authToken = token;\n return changed;\n }\n\n captureCredential() {\n return this.sessionRenewals.captureCredential();\n }\n\n withSessionSignal(options: RequestResultOptions): RequestResultOptions {\n return this.sessionRenewals.withSessionSignal(options);\n }\n\n getAuthToken(): string | null {\n return this.authToken;\n }\n\n getRequestFailure(input: { method: HttpMethod; path: string }) {\n return this.requestFailuresByKey.get(requestFailureKey(input)) ?? null;\n }\n\n private async makeRequest<T>(\n path: string,\n validator: (value: unknown) => value is T,\n method: HttpMethod,\n body: RequestBody | undefined,\n options: RequestResultOptions | undefined,\n failureOperation: Parameters<OperationRequestFn>[5],\n ): Promise<T | null> {\n const result = await this.makeRequestResult(\n path,\n validator,\n method,\n body,\n options,\n failureOperation,\n );\n return result.ok ? result.data : null;\n }\n\n private requestFailure(input: {\n code?: string | undefined;\n kind: RequestFailureKind;\n message: string;\n method: HttpMethod;\n networkError?: ApiNetworkError | undefined;\n path: string;\n reportErrors: boolean;\n requiredContainerIds?: RequestFailure[\"requiredContainerIds\"];\n stalePrincipalHeads: RequestFailure[\"stalePrincipalHeads\"];\n status: number | null;\n statusText: string;\n }): RequestFailure {\n const failure: RequestFailure = {\n ...(input.code === undefined ? {} : { code: input.code }),\n kind: input.kind,\n message: input.message,\n method: input.method,\n ...(input.networkError ? { networkError: input.networkError } : {}),\n ok: false,\n path: input.path,\n report: () => {\n if (input.kind !== \"cancelled\") this.onError?.(input.message);\n },\n status: input.status,\n statusText: input.statusText,\n ...(input.stalePrincipalHeads\n ? { stalePrincipalHeads: input.stalePrincipalHeads }\n : {}),\n ...(input.requiredContainerIds\n ? { requiredContainerIds: input.requiredContainerIds }\n : {}),\n };\n this.requestFailuresByKey.set(\n requestFailureKey({ method: input.method, path: input.path }),\n failure,\n );\n\n if (input.reportErrors) {\n failure.report();\n }\n\n return failure;\n }\n\n private async makeRequestResult<T>(\n path: string,\n validator: (value: unknown) => value is T,\n method: HttpMethod,\n body: RequestBody | undefined,\n options: RequestResultOptions | undefined,\n failureOperation: Parameters<OperationRequestFn>[5],\n ): Promise<RequestResult<T>> {\n const session = this.sessionRenewals.signal;\n const responseResult = await this.makeResponseRequest(\n path,\n method,\n body,\n options ?? {},\n [],\n failureOperation,\n );\n if (!responseResult.ok) {\n return responseResult;\n }\n\n const response = responseResult.data;\n const reportErrors = options?.reportErrors ?? true;\n const decoded = await readSessionJson(\n this.responseRequest,\n response,\n method,\n path,\n options ?? {},\n session,\n );\n if (session.aborted) return retiredRequest(method, path);\n if (!decoded.ok) return decoded;\n const data = decoded.data;\n if (!validator(data)) {\n return this.requestFailure({\n kind: \"shape\",\n message: `Invalid response shape for ${path}`,\n method,\n path,\n reportErrors,\n stalePrincipalHeads: undefined,\n status: response.status,\n statusText: response.statusText,\n });\n }\n\n return { data, ok: true };\n }\n\n private async makeResponseRequest(\n path: string,\n method: HttpMethod,\n body: RequestBody | undefined,\n options: RequestResultOptions,\n additionalSuccessStatuses: readonly number[],\n failureOperation: Parameters<OperationResponseRequestFn>[5],\n authToken = this.authToken,\n attempt = 1,\n ): Promise<RequestResult<Response>> {\n const session = this.sessionRenewals.signal;\n const callerOptions = options;\n const waitOptions = this.sessionRenewals.withRenewalWaitSignal(options);\n options = this.sessionRenewals.withSessionSignal(options);\n const result = await this.fetchResponseRequest(\n path,\n method,\n body,\n options,\n authToken,\n failureOperation,\n attempt,\n );\n if (!result.ok) return result;\n if (session.aborted)\n return this.retiredResponse(session, method, path, result.data);\n const response = result.data;\n if (isSuccessfulResponse(response, additionalSuccessStatuses)) {\n this.requestFailuresByKey.delete(requestFailureKey({ method, path }));\n return result;\n }\n const errorDescription = await describeErrorResponse(\n response,\n failureOperation,\n options.expectedPaymentRequiredOrganizationId,\n );\n const retired = () =>\n this.retiredResponse(\n session,\n method,\n path,\n response,\n errorDescription.code,\n );\n if (session.aborted) return retired();\n const failure = {\n errorDescription,\n failureOperation,\n method,\n options,\n path,\n response,\n };\n if (attempt === 2) return this.httpFailure(failure);\n\n // An independent replacement or caller cancellation ends this wait. A\n // refusal from the renewal itself must finish reporting its typed error.\n const shouldRetry = await shouldRetryAfterSessionExpired({\n authToken,\n body,\n code: errorDescription.code,\n getCurrentAuthToken: () => this.authToken,\n isKnownSessionRenewal: (from, to) =>\n this.sessionRenewals.isKnown(from, to),\n pendingSessionRenewal: (from) => this.sessionRenewals.pending(from),\n options: waitOptions,\n refreshSession: () => this.sessionRenewals.renew(this.onSessionExpired),\n reportError: (message) => this.onError?.(message),\n responseStatus: response.status,\n });\n if (session.aborted) return retired();\n const retryToken = this.sessionRenewals.currentToken(authToken);\n if (!shouldRetry || !retryToken) return this.httpFailure(failure);\n if (options.retryOnSessionExpired === \"renew-only\")\n return this.httpFailure({\n ...failure,\n options: {\n ...options,\n reportErrors: method === \"GET\" ? false : options.reportErrors,\n },\n });\n return this.makeResponseRequest(\n path,\n method,\n body,\n callerOptions,\n additionalSuccessStatuses,\n failureOperation,\n retryToken,\n 2,\n );\n }\n\n private retiredResponse(\n session: AbortSignal,\n method: HttpMethod,\n path: string,\n response: Response,\n code?: string | null,\n ): RequestFailure {\n const retired = retiredRequest(method, path);\n // Principal writes refused before dispatch have a definitive outcome.\n if (response.status !== 401 || !this.sessionRenewals.refused(session))\n return retired;\n return {\n ...retired,\n kind: \"http\",\n status: 401,\n statusText: response.statusText,\n code: code ?? undefined,\n message: `${method} ${path}: 401 ${response.statusText}`,\n };\n }\n\n private async fetchResponseRequest(\n path: string,\n method: HttpMethod,\n body: RequestBody | undefined,\n options: RequestResultOptions,\n authToken: string | null,\n operation: Parameters<OperationResponseRequestFn>[5],\n /** 2 is the retry after a session renewal. */\n attempt = 1,\n ): Promise<RequestResult<Response>> {\n const session = this.sessionRenewals.signal;\n const reportErrors = options.reportErrors ?? true;\n const { headers, init } = sessionRequestInit(\n method,\n body,\n options,\n authToken,\n );\n\n let response: Response;\n const startedAt = Date.now();\n try {\n response = await measureApiRequest(\n this.instrumentation,\n operation,\n () => fetch(`${this.baseUrl}${path}`, init),\n options.signal,\n );\n } catch (error) {\n if (session.aborted) return retiredRequest(method, path);\n const { cancelled, networkError } = await settleNetworkFailure({\n attempt,\n baseUrl: this.baseUrl,\n elapsedMs: Date.now() - startedAt,\n error,\n headers,\n isOnline: this.instrumentation?.isOnline,\n method,\n onNetworkError: () => this.onNetworkError?.(),\n pathTemplate: operation.path,\n probe: this.instrumentation?.networkFailureProbe,\n signal: options.signal,\n onNetworkFailure: (failure) => this.onNetworkFailure?.(failure),\n });\n if (session.aborted) return retiredRequest(method, path);\n return this.requestFailure({\n ...(cancelled ? { code: \"request_aborted\" } : {}),\n kind: cancelled ? \"cancelled\" : \"network\",\n message: `${method} ${path}: ${networkFailureMessage(error, networkError)}`,\n method,\n networkError,\n path,\n reportErrors: cancelled ? false : reportErrors,\n stalePrincipalHeads: undefined,\n status: null,\n statusText: \"\",\n });\n }\n\n if (session.aborted)\n return this.retiredResponse(session, method, path, response);\n this.onNetworkSuccess?.();\n const apiVersion = parseApiVersion(\n response.headers.get(apiVersionHeaderName),\n );\n if (apiVersion !== null) this.onApiVersion?.(apiVersion);\n return { data: response, ok: true };\n }\n\n private httpFailure(input: {\n readonly errorDescription: ErrorResponseDescription;\n readonly failureOperation: Parameters<OperationResponseRequestFn>[5];\n readonly method: HttpMethod;\n readonly options: RequestResultOptions;\n readonly path: string;\n readonly response: Response;\n }): RequestFailure {\n const cancelled = input.options.signal?.aborted === true;\n const reportErrors = input.options.reportErrors ?? true;\n if (\n !cancelled &&\n input.response.status === 402 &&\n input.failureOperation.failureResponses?.[402] &&\n input.errorDescription.paymentRequiredOrganizationId !== undefined &&\n input.errorDescription.paymentRequiredOrganizationId ===\n input.options.expectedPaymentRequiredOrganizationId\n ) {\n this.onPaymentRequired?.(\n input.errorDescription.paymentRequiredOrganizationId,\n );\n }\n return this.requestFailure({\n ...(cancelled\n ? { code: \"request_aborted\" }\n : input.errorDescription.code === null\n ? {}\n : { code: input.errorDescription.code }),\n kind: cancelled ? \"cancelled\" : \"http\",\n message: `${input.method} ${input.path}: ${input.response.status} ${input.response.statusText}${input.errorDescription.detail}`,\n method: input.method,\n path: input.path,\n reportErrors: !cancelled && reportErrors,\n requiredContainerIds: input.errorDescription.requiredContainerIds,\n stalePrincipalHeads: input.errorDescription.stalePrincipalHeads,\n status: input.response.status,\n statusText: input.response.statusText,\n });\n }\n\n private reportResponseRequestFailure(\n input: ResponseRequestValidationFailureInput,\n ): RequestFailure {\n if (input.kind === \"network\") {\n this.onNetworkError?.();\n }\n return this.requestFailure({\n ...input,\n reportErrors: input.options?.reportErrors ?? true,\n stalePrincipalHeads: undefined,\n });\n }\n}\n"]}
|
|
@@ -15,11 +15,12 @@ export function createBinaryRequestOperationTransport(responseRequest) {
|
|
|
15
15
|
const derived = deriveRuntimeOperationRequestMetadata(operation, input);
|
|
16
16
|
const body = binaryRequestBody(operation, input, encodeBody);
|
|
17
17
|
const headers = mergeOperationRequestHeaders({ "Content-Type": operation.requestMediaType, ...derived.headers }, requestOptions.headers);
|
|
18
|
+
const session = responseRequest.sessionSignal?.();
|
|
18
19
|
const result = await responseRequest(derived.path, derived.method, body, { ...requestOptions, headers }, additionalOperationSuccessStatuses(operation), operation);
|
|
19
20
|
if (!result.ok) {
|
|
20
21
|
return result;
|
|
21
22
|
}
|
|
22
|
-
return decodeJsonOperationResponse(responseRequest, operation, result.data, derived.path, requestOptions);
|
|
23
|
+
return decodeJsonOperationResponse(responseRequest, operation, result.data, derived.path, requestOptions, session);
|
|
23
24
|
}
|
|
24
25
|
async function requestBinaryRequestResult(operation, input, options) {
|
|
25
26
|
const result = await requestBinaryRequestResponseResult(operation, input, options);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"binaryRequestOperationTransport.js","sourceRoot":"","sources":["binaryRequestOperationTransport.ts"],"names":[],"mappings":"AACA,OAAO,EACL,kCAAkC,EAClC,2BAA2B,GAI5B,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EACL,qCAAqC,EACrC,4BAA4B,GAG7B,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,gCAAgC,EAAE,MAAM,6BAA6B,CAAC;AAuC/E,SAAS,iBAAiB,CACxB,SAAiC,EACjC,KAAmC,EACnC,UAAuD;IAEvD,MAAM,MAAM,GAAG,SAAS,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IACpD,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;QACpB,MAAM,IAAI,SAAS,CAAC,4BAA4B,SAAS,CAAC,EAAE,EAAE,CAAC,CAAC;IAClE,CAAC;IACD,OAAO,UAAU,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;AACjC,CAAC;AAED,MAAM,UAAU,qCAAqC,CACnD,eAA2C;IAS3C,KAAK,UAAU,kCAAkC,CAC/C,SAAiC,EACjC,KAAmC,EACnC,OAAsC;QAEtC,gCAAgC,CAAC,SAAS,EAAE,eAAe,CAAC,CAAC;QAC7D,MAAM,EAAE,UAAU,EAAE,GAAG,cAAc,EAAE,GAAG,OAAO,CAAC;QAClD,MAAM,OAAO,GAAG,qCAAqC,CAAC,SAAS,EAAE,KAAK,CAAC,CAAC;QACxE,MAAM,IAAI,GAAG,iBAAiB,CAAC,SAAS,EAAE,KAAK,EAAE,UAAU,CAAC,CAAC;QAC7D,MAAM,OAAO,GAAG,4BAA4B,CAC1C,EAAE,cAAc,EAAE,SAAS,CAAC,gBAAgB,EAAE,GAAG,OAAO,CAAC,OAAO,EAAE,EAClE,cAAc,CAAC,OAAO,CACvB,CAAC;QACF,MAAM,MAAM,GAAG,MAAM,eAAe,CAClC,OAAO,CAAC,IAAI,EACZ,OAAO,CAAC,MAAM,EACd,IAAI,EACJ,EAAE,GAAG,cAAc,EAAE,OAAO,EAAE,EAC9B,kCAAkC,CAAC,SAAS,CAAC,EAC7C,SAAS,CACV,CAAC;QACF,IAAI,CAAC,MAAM,CAAC,EAAE,EAAE,CAAC;YACf,OAAO,MAAM,CAAC;QAChB,CAAC;QACD,OAAO,2BAA2B,CAChC,eAAe,EACf,SAAS,EACT,MAAM,CAAC,IAAI,EACX,OAAO,CAAC,IAAI,EACZ,cAAc,
|
|
1
|
+
{"version":3,"file":"binaryRequestOperationTransport.js","sourceRoot":"","sources":["binaryRequestOperationTransport.ts"],"names":[],"mappings":"AACA,OAAO,EACL,kCAAkC,EAClC,2BAA2B,GAI5B,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EACL,qCAAqC,EACrC,4BAA4B,GAG7B,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,gCAAgC,EAAE,MAAM,6BAA6B,CAAC;AAuC/E,SAAS,iBAAiB,CACxB,SAAiC,EACjC,KAAmC,EACnC,UAAuD;IAEvD,MAAM,MAAM,GAAG,SAAS,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IACpD,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;QACpB,MAAM,IAAI,SAAS,CAAC,4BAA4B,SAAS,CAAC,EAAE,EAAE,CAAC,CAAC;IAClE,CAAC;IACD,OAAO,UAAU,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;AACjC,CAAC;AAED,MAAM,UAAU,qCAAqC,CACnD,eAA2C;IAS3C,KAAK,UAAU,kCAAkC,CAC/C,SAAiC,EACjC,KAAmC,EACnC,OAAsC;QAEtC,gCAAgC,CAAC,SAAS,EAAE,eAAe,CAAC,CAAC;QAC7D,MAAM,EAAE,UAAU,EAAE,GAAG,cAAc,EAAE,GAAG,OAAO,CAAC;QAClD,MAAM,OAAO,GAAG,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AAM,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC;QACxC,CAAC;QACD,0BAA0B;QAC1B,KAAK,CAAC,4BAA4B,CAAC,SAAS,EAAE,KAAK,EAAE,OAAO;YAC1D,MAAM,MAAM,GAAG,MAAM,kCAAkC,CACrD,SAAS,EACT,KAAK,EACL,OAAO,CACR,CAAC;YACF,OAAO,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC;QACxC,CAAC;QACD,kCAAkC;KACnC,CAAC;AACJ,CAAC","sourcesContent":["import type { BinaryBodySchema } from \"@tearleads/validators/operation\";\nimport {\n additionalOperationSuccessStatuses,\n decodeJsonOperationResponse,\n type JsonOperationResponse,\n type JsonOperationResponseEnvelope,\n type JsonResponseOperation,\n} from \"./operationResponse\";\nimport {\n deriveRuntimeOperationRequestMetadata,\n mergeOperationRequestHeaders,\n type OperationRequestInput,\n type RuntimeOperationRequestInput,\n} from \"./operationTransport\";\nimport { requireOperationTransportSurface } from \"./operationTransportSurface\";\nimport type {\n OperationResponseRequestFn,\n RequestResult,\n RequestResultOptions,\n} from \"./types\";\n\nexport interface BinaryRequestOperation extends JsonResponseOperation {\n readonly body: typeof BinaryBodySchema;\n readonly requestMediaType: \"application/octet-stream\";\n}\n\nexport interface BinaryRequestOperationOptions extends RequestResultOptions {\n readonly encodeBody: (body: Blob | BufferSource) => BodyInit;\n}\n\nexport interface BinaryRequestOperationTransport {\n requestBinaryRequest<Operation extends BinaryRequestOperation>(\n operation: Operation,\n input: OperationRequestInput<Operation>,\n options: BinaryRequestOperationOptions,\n ): Promise<JsonOperationResponse<Operation> | null>;\n requestBinaryRequestResult<Operation extends BinaryRequestOperation>(\n operation: Operation,\n input: OperationRequestInput<Operation>,\n options: BinaryRequestOperationOptions,\n ): Promise<RequestResult<JsonOperationResponse<Operation>>>;\n requestBinaryRequestResponse<Operation extends BinaryRequestOperation>(\n operation: Operation,\n input: OperationRequestInput<Operation>,\n options: BinaryRequestOperationOptions,\n ): Promise<JsonOperationResponseEnvelope<Operation> | null>;\n requestBinaryRequestResponseResult<Operation extends BinaryRequestOperation>(\n operation: Operation,\n input: OperationRequestInput<Operation>,\n options: BinaryRequestOperationOptions,\n ): Promise<RequestResult<JsonOperationResponseEnvelope<Operation>>>;\n}\n\nfunction binaryRequestBody(\n operation: BinaryRequestOperation,\n input: RuntimeOperationRequestInput,\n encodeBody: BinaryRequestOperationOptions[\"encodeBody\"],\n): BodyInit {\n const parsed = operation.body.safeParse(input.body);\n if (!parsed.success) {\n throw new TypeError(`Invalid request body for ${operation.id}`);\n }\n return encodeBody(parsed.data);\n}\n\nexport function createBinaryRequestOperationTransport(\n responseRequest: OperationResponseRequestFn,\n): BinaryRequestOperationTransport {\n function requestBinaryRequestResponseResult<\n Operation extends BinaryRequestOperation,\n >(\n operation: Operation,\n input: OperationRequestInput<Operation>,\n options: BinaryRequestOperationOptions,\n ): Promise<RequestResult<JsonOperationResponseEnvelope<Operation>>>;\n async function requestBinaryRequestResponseResult(\n operation: BinaryRequestOperation,\n input: RuntimeOperationRequestInput,\n options: BinaryRequestOperationOptions,\n ): Promise<RequestResult<unknown>> {\n requireOperationTransportSurface(operation, \"binaryRequest\");\n const { encodeBody, ...requestOptions } = options;\n const derived = deriveRuntimeOperationRequestMetadata(operation, input);\n const body = binaryRequestBody(operation, input, encodeBody);\n const headers = mergeOperationRequestHeaders(\n { \"Content-Type\": operation.requestMediaType, ...derived.headers },\n requestOptions.headers,\n );\n const session = responseRequest.sessionSignal?.();\n const result = await responseRequest(\n derived.path,\n derived.method,\n body,\n { ...requestOptions, headers },\n additionalOperationSuccessStatuses(operation),\n operation,\n );\n if (!result.ok) {\n return result;\n }\n return decodeJsonOperationResponse(\n responseRequest,\n operation,\n result.data,\n derived.path,\n requestOptions,\n session,\n );\n }\n\n async function requestBinaryRequestResult<\n Operation extends BinaryRequestOperation,\n >(\n operation: Operation,\n input: OperationRequestInput<Operation>,\n options: BinaryRequestOperationOptions,\n ): Promise<RequestResult<JsonOperationResponse<Operation>>> {\n const result = await requestBinaryRequestResponseResult(\n operation,\n input,\n options,\n );\n return result.ok ? { data: result.data.data, ok: true } : result;\n }\n\n return {\n async requestBinaryRequest(operation, input, options) {\n const result = await requestBinaryRequestResult(\n operation,\n input,\n options,\n );\n return result.ok ? result.data : null;\n },\n requestBinaryRequestResult,\n async requestBinaryRequestResponse(operation, input, options) {\n const result = await requestBinaryRequestResponseResult(\n operation,\n input,\n options,\n );\n return result.ok ? result.data : null;\n },\n requestBinaryRequestResponseResult,\n };\n}\n"]}
|
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
import { additionalOperationSuccessStatuses, decodeOperationResponseHeaders, operationResponseFailure, } from "./operationResponse.js";
|
|
2
2
|
import { deriveRuntimeOperationRequest, mergeOperationRequestHeaders, } from "./operationTransport.js";
|
|
3
3
|
import { requireOperationTransportSurface } from "./operationTransportSurface.js";
|
|
4
|
-
|
|
4
|
+
import { retiredRequest } from "./sessionResponse.js";
|
|
5
|
+
async function decodeBinaryOperationResponse(request, operation, response, path, options, session) {
|
|
6
|
+
if (session?.aborted)
|
|
7
|
+
return retiredRequest(operation.method, path);
|
|
5
8
|
if (!operation.responses[response.status] ||
|
|
6
9
|
operation.responseMediaTypes[response.status] !== "application/octet-stream") {
|
|
7
10
|
return operationResponseFailure(request, operation, response, path, options, `Invalid binary response status ${response.status} for ${path}`);
|
|
@@ -25,11 +28,12 @@ export function createBinaryResponseOperationTransport(responseRequest) {
|
|
|
25
28
|
const derived = deriveRuntimeOperationRequest(operation, input);
|
|
26
29
|
const headers = mergeOperationRequestHeaders(derived.headers, options.headers);
|
|
27
30
|
const requestOptions = Object.keys(headers).length === 0 ? options : { ...options, headers };
|
|
31
|
+
const session = responseRequest.sessionSignal?.();
|
|
28
32
|
const result = await responseRequest(derived.path, derived.method, derived.body, requestOptions, additionalOperationSuccessStatuses(operation), operation);
|
|
29
33
|
if (!result.ok) {
|
|
30
34
|
return result;
|
|
31
35
|
}
|
|
32
|
-
return decodeBinaryOperationResponse(responseRequest, operation, result.data, derived.path, options);
|
|
36
|
+
return decodeBinaryOperationResponse(responseRequest, operation, result.data, derived.path, options, session);
|
|
33
37
|
}
|
|
34
38
|
return {
|
|
35
39
|
async requestBinaryResponse(operation, input, options) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"binaryResponseOperationTransport.js","sourceRoot":"","sources":["binaryResponseOperationTransport.ts"],"names":[],"mappings":"AACA,OAAO,EACL,kCAAkC,EAClC,8BAA8B,EAE9B,wBAAwB,GACzB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EACL,6BAA6B,EAC7B,4BAA4B,GAG7B,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,gCAAgC,EAAE,MAAM,6BAA6B,CAAC;
|
|
1
|
+
{"version":3,"file":"binaryResponseOperationTransport.js","sourceRoot":"","sources":["binaryResponseOperationTransport.ts"],"names":[],"mappings":"AACA,OAAO,EACL,kCAAkC,EAClC,8BAA8B,EAE9B,wBAAwB,GACzB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EACL,6BAA6B,EAC7B,4BAA4B,GAG7B,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,gCAAgC,EAAE,MAAM,6BAA6B,CAAC;AAC/E,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAgDnD,KAAK,UAAU,6BAA6B,CAC1C,OAAmC,EACnC,SAAkC,EAClC,QAAkB,EAClB,IAAY,EACZ,OAA6B,EAC7B,OAAqB;IAErB,IAAI,OAAO,EAAE,OAAO;QAAE,OAAO,cAAc,CAAC,SAAS,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;IACpE,IACE,CAAC,SAAS,CAAC,SAAS,CAAC,QAAQ,CAAC,MAAM,CAAC;QACrC,SAAS,CAAC,kBAAkB,CAAC,QAAQ,CAAC,MAAM,CAA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,EACd,OAAO,CAAC,IAAI,EACZ,cAAc,EACd,kCAAkC,CAAC,SAAS,CAAC,EAC7C,SAAS,CACV,CAAC;QACF,IAAI,CAAC,MAAM,CAAC,EAAE,EAAE,CAAC;YACf,OAAO,MAAM,CAAC;QAChB,CAAC;QACD,OAAO,6BAA6B,CAClC,eAAe,EACf,SAAS,EACT,MAAM,CAAC,IAAI,EACX,OAAO,CAAC,IAAI,EACZ,OAAO,EACP,OAAO,CACR,CAAC;IACJ,CAAC;IAED,OAAO;QACL,KAAK,CAAC,qBAAqB,CAAC,SAAS,EAAE,KAAK,EAAE,OAAO;YACnD,MAAM,MAAM,GAAG,MAAM,2BAA2B,CAC9C,SAAS,EACT,KAAK,EACL,OAAO,CACR,CAAC;YACF,OAAO,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC;QACxC,CAAC;QACD,2BAA2B;KAC5B,CAAC;AACJ,CAAC","sourcesContent":["import type { HttpOperation } from \"@tearleads/validators/operation\";\nimport {\n additionalOperationSuccessStatuses,\n decodeOperationResponseHeaders,\n type OperationResponseHeadersForStatus,\n operationResponseFailure,\n} from \"./operationResponse\";\nimport {\n deriveRuntimeOperationRequest,\n mergeOperationRequestHeaders,\n type OperationRequestInput,\n type RuntimeOperationRequestInput,\n} from \"./operationTransport\";\nimport { requireOperationTransportSurface } from \"./operationTransportSurface\";\nimport { retiredRequest } from \"./sessionResponse\";\nimport type {\n OperationResponseRequestFn,\n RequestResult,\n RequestResultOptions,\n} from \"./types\";\n\nexport interface BinaryResponseOperation extends HttpOperation {\n readonly requestMediaType?: \"application/json\";\n readonly responseMediaTypes: Readonly<\n Record<number, \"application/octet-stream\">\n >;\n}\n\ntype BinaryResponseStatus<Operation extends BinaryResponseOperation> = Extract<\n keyof Operation[\"responses\"],\n number\n>;\n\nexport type BinaryOperationResponseEnvelope<\n Operation extends BinaryResponseOperation,\n> = {\n [Status in BinaryResponseStatus<Operation>]: {\n readonly headers: OperationResponseHeadersForStatus<Operation, Status>;\n readonly response: Response;\n readonly status: Status;\n };\n}[BinaryResponseStatus<Operation>];\n\ninterface RuntimeBinaryOperationResponseEnvelope {\n readonly headers: unknown;\n readonly response: Response;\n readonly status: number;\n}\n\nexport interface BinaryResponseOperationTransport {\n requestBinaryResponse<Operation extends BinaryResponseOperation>(\n operation: Operation,\n input: OperationRequestInput<Operation>,\n options?: RequestResultOptions,\n ): Promise<BinaryOperationResponseEnvelope<Operation> | null>;\n requestBinaryResponseResult<Operation extends BinaryResponseOperation>(\n operation: Operation,\n input: OperationRequestInput<Operation>,\n options?: RequestResultOptions,\n ): Promise<RequestResult<BinaryOperationResponseEnvelope<Operation>>>;\n}\n\nasync function decodeBinaryOperationResponse(\n request: OperationResponseRequestFn,\n operation: BinaryResponseOperation,\n response: Response,\n path: string,\n options: RequestResultOptions,\n session?: AbortSignal,\n): Promise<RequestResult<RuntimeBinaryOperationResponseEnvelope>> {\n if (session?.aborted) return retiredRequest(operation.method, path);\n if (\n !operation.responses[response.status] ||\n operation.responseMediaTypes[response.status] !== \"application/octet-stream\"\n ) {\n return operationResponseFailure(\n request,\n operation,\n response,\n path,\n options,\n `Invalid binary response status ${response.status} for ${path}`,\n );\n }\n\n const headers = decodeOperationResponseHeaders(operation, response);\n if (!headers.ok) {\n return operationResponseFailure(\n request,\n operation,\n response,\n path,\n options,\n `Invalid response headers for ${path}`,\n );\n }\n\n return {\n data: {\n headers: headers.data,\n response,\n status: response.status,\n },\n ok: true,\n };\n}\n\nexport function createBinaryResponseOperationTransport(\n responseRequest: OperationResponseRequestFn,\n): BinaryResponseOperationTransport {\n function requestBinaryResponseResult<\n Operation extends BinaryResponseOperation,\n >(\n operation: Operation,\n input: OperationRequestInput<Operation>,\n options?: RequestResultOptions,\n ): Promise<RequestResult<BinaryOperationResponseEnvelope<Operation>>>;\n async function requestBinaryResponseResult(\n operation: BinaryResponseOperation,\n input: RuntimeOperationRequestInput,\n options: RequestResultOptions = {},\n ): Promise<RequestResult<RuntimeBinaryOperationResponseEnvelope>> {\n requireOperationTransportSurface(operation, \"binaryResponse\");\n const derived = deriveRuntimeOperationRequest(operation, input);\n const headers = mergeOperationRequestHeaders(\n derived.headers,\n options.headers,\n );\n const requestOptions =\n Object.keys(headers).length === 0 ? options : { ...options, headers };\n const session = responseRequest.sessionSignal?.();\n const result = await responseRequest(\n derived.path,\n derived.method,\n derived.body,\n requestOptions,\n additionalOperationSuccessStatuses(operation),\n operation,\n );\n if (!result.ok) {\n return result;\n }\n return decodeBinaryOperationResponse(\n responseRequest,\n operation,\n result.data,\n derived.path,\n options,\n session,\n );\n }\n\n return {\n async requestBinaryResponse(operation, input, options) {\n const result = await requestBinaryResponseResult(\n operation,\n input,\n options,\n );\n return result.ok ? result.data : null;\n },\n requestBinaryResponseResult,\n };\n}\n"]}
|