@tearleads/client-sdk 0.1.251 → 0.1.253
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 +17 -28
- package/Tearleads.js.map +1 -1
- package/client/containerContents/index.d.ts +2 -0
- package/client/containerContents/index.js +4 -9
- package/client/containerContents/index.js.map +1 -1
- package/client/containerContents/storeRuntime.d.ts +17 -0
- package/client/containerContents/storeRuntime.js +31 -0
- package/client/containerContents/storeRuntime.js.map +1 -0
- package/client/deviceFirst/index.d.ts +2 -3
- package/client/deviceFirst/index.js +44 -22
- package/client/deviceFirst/index.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 +3 -1
- package/client/runtime/workflowRuntime.js +31 -81
- 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/sync/syncCoordinator.js +17 -10
- package/data/sync/syncCoordinator.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/stores/container-contents/containerContentsStore.d.ts +3 -9
- package/stores/container-contents/containerContentsStore.js +24 -21
- package/stores/container-contents/containerContentsStore.js.map +1 -1
- package/stores/container-contents/containerState/storeScope.js +6 -0
- package/stores/container-contents/containerState/storeScope.js.map +1 -0
- package/stores/container-contents/hydration/backgroundHydration.js +2 -1
- package/stores/container-contents/hydration/backgroundHydration.js.map +1 -1
- package/stores/container-contents/hydration/reconnectRefresh.d.ts +10 -0
- package/stores/container-contents/hydration/reconnectRefresh.js +68 -0
- package/stores/container-contents/hydration/reconnectRefresh.js.map +1 -0
- package/stores/container-contents/hydration/reconnectRefreshMachine.js +49 -0
- package/stores/container-contents/hydration/reconnectRefreshMachine.js.map +1 -0
- package/stores/container-contents/hydration/remoteHydrationRefresh.js +4 -1
- package/stores/container-contents/hydration/remoteHydrationRefresh.js.map +1 -1
- package/stores/container-contents/hydration/remoteHydrationRequest.js +79 -10
- package/stores/container-contents/hydration/remoteHydrationRequest.js.map +1 -1
- package/stores/container-contents/hydration/startupHydration.js +2 -9
- package/stores/container-contents/hydration/startupHydration.js.map +1 -1
- package/stores/container-contents/hydration/treeResetMachine.js +61 -0
- package/stores/container-contents/hydration/treeResetMachine.js.map +1 -0
- package/stores/container-contents/localRefresh.js +28 -12
- package/stores/container-contents/localRefresh.js.map +1 -1
- package/stores/container-contents/remoteEvents/remoteContainerIngestion.js +4 -1
- package/stores/container-contents/remoteEvents/remoteContainerIngestion.js.map +1 -1
- package/stores/container-contents/remoteWrites/writeGeneration.js +5 -2
- package/stores/container-contents/remoteWrites/writeGeneration.js.map +1 -1
- package/stores/container-contents/state.d.ts +3 -7
- package/stores/container-contents/state.js +27 -16
- package/stores/container-contents/state.js.map +1 -1
- package/stores/container-contents/syncAgent/index.d.ts +7 -2
- package/stores/container-contents/syncAgent/index.js +77 -49
- package/stores/container-contents/syncAgent/index.js.map +1 -1
- package/stores/container-contents/syncAgent/syncAgentTypes.d.ts +5 -2
- package/stores/container-contents/syncAgent/syncAgentTypes.js.map +1 -1
- package/stores/container-contents/syncAgent/syncLaneIteration.js +6 -3
- package/stores/container-contents/syncAgent/syncLaneIteration.js.map +1 -1
- package/stores/local-projection/localProjectionStore.js +24 -15
- package/stores/local-projection/localProjectionStore.js.map +1 -1
- package/stores/local-projection/registry.js +2 -2
- package/stores/local-projection/registry.js.map +1 -1
- package/workflows/container-contents/container-state/create/createChild.js +3 -15
- package/workflows/container-contents/container-state/create/createChild.js.map +1 -1
- package/workflows/container-contents/containerPersistence.d.ts +4 -8
- package/workflows/container-contents/containerPersistence.js +22 -12
- package/workflows/container-contents/containerPersistence.js.map +1 -1
- package/workflows/container-contents/localState.js +3 -0
- package/workflows/container-contents/localState.js.map +1 -1
- package/workflows/container-contents/remoteHydration/hydrateRemoteContainers.d.ts +12 -0
- package/workflows/container-contents/remoteHydration/hydrateRemoteContainers.js +93 -0
- package/workflows/container-contents/remoteHydration/hydrateRemoteContainers.js.map +1 -0
- package/workflows/container-contents/remoteHydration/index.d.ts +3 -11
- package/workflows/container-contents/remoteHydration/index.js +17 -66
- package/workflows/container-contents/remoteHydration/index.js.map +1 -1
- package/workflows/container-contents/remoteHydration/lanes/parentLaneFetch.js +3 -2
- package/workflows/container-contents/remoteHydration/lanes/parentLaneFetch.js.map +1 -1
- package/workflows/container-contents/remoteHydration/principalPolicyCache.js +57 -5
- package/workflows/container-contents/remoteHydration/principalPolicyCache.js.map +1 -1
- package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js +105 -62
- package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js.map +1 -1
- package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js +15 -5
- package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js.map +1 -1
- package/workflows/container-contents/remoteHydration/types.d.ts +13 -0
- package/workflows/container-contents/remoteHydration/types.js.map +1 -1
- package/workflows/container-contents/runtime.d.ts +3 -0
- package/workflows/container-contents/runtime.js.map +1 -1
- package/workflows/container-contents/storedContainerState.js +17 -7
- package/workflows/container-contents/storedContainerState.js.map +1 -1
- package/workflows/container-contents/syncLane.d.ts +1 -0
- package/workflows/container-contents/syncLane.js +9 -1
- package/workflows/container-contents/syncLane.js.map +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
- package/workflows/shared/runtimeInput.d.ts +2 -0
- package/workflows/shared/runtimeInput.js.map +1 -1
- package/workflows/container-contents/remoteHydration/completeHydration.js +0 -25
- package/workflows/container-contents/remoteHydration/completeHydration.js.map +0 -1
|
@@ -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,gBAAg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;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 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;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G,KAAK,CAAC,gBAAgB,CAAC,MAAM,EAAE;YAC/H,MAAM,EAAE,KAAK,CAAC,MAAM;YACpB,IAAI,EAAE,KAAK,CAAC,IAAI;YAChB,YAAY,EAAE,CAAC,SAAS,IAAI,YAAY;YACxC,oBAAoB,EAAE,KAAK,CAAC,gBAAgB,CAAC,oBAAoB;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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,CAAC,CAAC,MAAM,CAAC;IACnE,CAAC;IAED,OAAO;QACL,KAAK,CAAC,oBAAoB,CAAC,SAAS,EAAE,KAAK,EAAE,OAAO;YAClD,MAAM,MAAM,GAAG,MAAM,0BAA0B,CAC7C,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,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,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O,CAAC,CAAC,CAAC,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE,CAAC;QACxE,MAAM,OAAO,GAAG,eAAe,CAAC,aAAa,EAAE,EAAE,CAAC;QAClD,MAAM,MAAM,GAAG,MAAM,eAAe,CAClC,OAAO,CAAC,IAAI,EACZ,OAAO,CAAC,MAAM,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"]}
|
|
@@ -72,6 +72,7 @@ export declare class BlobArea {
|
|
|
72
72
|
uploadId: string;
|
|
73
73
|
} | null>;
|
|
74
74
|
getBlobBytes(blobId: string, options?: RequestResultOptions): Promise<import("../index.js").BlobBytesResponse | null>;
|
|
75
|
+
private transfer;
|
|
75
76
|
bindBlobAttachment(blobId: string, input: BlobAttachmentBindRequest, options?: RequestResultOptions): Promise<{
|
|
76
77
|
bindingId: string;
|
|
77
78
|
blobAccessManifestHash: string;
|
|
@@ -75,8 +75,11 @@ export class BlobArea {
|
|
|
75
75
|
// An attachment write updates the cached listing from its response; a
|
|
76
76
|
// refused or failed write leaves every listing unknown, so all are dropped.
|
|
77
77
|
attachmentWrite(write, cacheResponse) {
|
|
78
|
+
const session = this.context.runtime.responseRequest.sessionSignal?.();
|
|
78
79
|
return write
|
|
79
80
|
.then((response) => {
|
|
81
|
+
if (session?.aborted)
|
|
82
|
+
return null;
|
|
80
83
|
if (response) {
|
|
81
84
|
cacheResponse(response);
|
|
82
85
|
}
|
|
@@ -86,7 +89,8 @@ export class BlobArea {
|
|
|
86
89
|
return response;
|
|
87
90
|
})
|
|
88
91
|
.catch((error) => {
|
|
89
|
-
|
|
92
|
+
if (!session?.aborted)
|
|
93
|
+
this.attachmentLists.clear();
|
|
90
94
|
throw error;
|
|
91
95
|
});
|
|
92
96
|
}
|
|
@@ -97,10 +101,15 @@ export class BlobArea {
|
|
|
97
101
|
return this.context.send(multipartGet, multipartGet.path(stageId), getMultipartBlobStageOperation);
|
|
98
102
|
}
|
|
99
103
|
uploadMultipartBlobPartBytes(stageId, partNumber, input, options = {}) {
|
|
100
|
-
return uploadMultipartBlobPartBytes(this.context.transport, stageId, partNumber, input, undefined,
|
|
104
|
+
return this.transfer(options, (scoped) => uploadMultipartBlobPartBytes(this.context.transport, stageId, partNumber, input, undefined, scoped));
|
|
101
105
|
}
|
|
102
106
|
getBlobBytes(blobId, options = {}) {
|
|
103
|
-
return getBlobBytes(this.context.transport, blobId, undefined,
|
|
107
|
+
return this.transfer(options, (scoped) => getBlobBytes(this.context.transport, blobId, undefined, scoped));
|
|
108
|
+
}
|
|
109
|
+
async transfer(options, run) {
|
|
110
|
+
const scoped = this.context.runtime.withSessionSignal(options);
|
|
111
|
+
const result = await run(scoped);
|
|
112
|
+
return scoped.signal?.aborted ? null : result;
|
|
104
113
|
}
|
|
105
114
|
bindBlobAttachment(blobId, input, options = {}) {
|
|
106
115
|
return this.attachmentWrite(this.context.send(blobAttachmentBind, blobAttachmentBind.path(blobId), bindBlobAttachmentOperation, input, options), (response) => this.cacheBlobAttachmentBindResponse(input, response));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"blobs.js","sourceRoot":"","sources":["blobs.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,2BAA2B,EAC3B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AAE;QAC7D,OAAO,YAAY,CAAC,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,MAAM,EAAE,SAAS,EAAE,OAAO,CAAC,CAAC;IAC1E,CAAC;IAED,kBAAkB,CAChB,MAAc,EACd,KAAgC,EAChC,UAAgC,EAAE;QAElC,OAAO,IAAI,CAAC,eAAe,CACzB,IAAI,CAAC,OAAO,CAAC,IAAI,CACf,kBAAkB,EAClB,kBAAkB,CAAC,IAAI,CAAC,MAAM,CAAC,EAC/B,2BAA2B,EAC3B,KAAK,EACL,OAAO,CACR,EACD,CAAC,QAAQ,EAAE,EAAE,CAAC,IAAI,CAAC,+BAA+B,CAAC,KAAK,EAAE,QAAQ,CAAC,CACpE,CAAC;IACJ,CAAC;IAED,oBAAoB,CAClB,MAAc,EACd,SAAiB,EACjB,KAAkC,EAClC,UAAgC,EAAE;QAElC,OAAO,IAAI,CAAC,eAAe,CACzB,IAAI,CAAC,OAAO,CAAC,IAAI,CACf,oBAAoB,EACpB,oBAAoB,CAAC,IAAI,CAAC,MAAM,EAAE,SAAS,CAAC,EAC5C,6BAA6B,EAC7B,KAAK,EACL,OAAO,CACR,EACD,IAAI,CAAC,iCAAiC,CACvC,CAAC;IACJ,CAAC;IAED,uBAAuB,CACrB,UAAkB,EAClB,UAAiC,EAAE;QAEnC,IAAI,OAAO,CAAC,OAAO,EAAE,CAAC;YACpB,IAAI,CAAC,eAAe,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;QAC1C,CAAC;QACD,OAAO,aAAa,CAAC,IAAI,CAAC,eAAe,EAAE,UAAU,EAAE,GAAG,EAAE,CAC1D,IAAI,CAAC,OAAO,CAAC,IAAI,CACf,uBAAuB,EACvB,uBAAuB,CAAC,IAAI,CAAC,UAAU,CAAC,EACxC,gCAAgC,CACjC,CACF,CAAC;IACJ,CAAC;CACF","sourcesContent":["import {\n bindBlobAttachmentOperation,\n detachBlobAttachmentOperation,\n getMultipartBlobStageOperation,\n initiateMultipartBlobStageOperation,\n listDocumentAttachmentsOperation,\n} from \"@tearleads/validators/operation\";\nimport type {\n BlobAttachmentBindRequest,\n BlobAttachmentDetachRequest,\n InitiateMultipartBlobStageRequest,\n} from \"@tearleads/validators/request\";\nimport type {\n BlobAttachmentBindResponse,\n BlobAttachmentDetachResponse,\n ListDocumentAttachmentsResponse,\n} from \"@tearleads/validators/response\";\nimport { blobAttachmentSummaryFromStagedBind } from \"@tearleads/validators/response\";\nimport { bindPrototypeMethods, cachedRequest } from \"../requestInternals\";\nimport {\n bindBlobAttachment as blobAttachmentBind,\n detachBlobAttachment as blobAttachmentDetach,\n} from \"../routes/blobs/attachments\";\nimport {\n getBlobBytes,\n type UploadMultipartBlobPartBytesRequest,\n} from \"../routes/blobs/get\";\nimport {\n getMultipartBlobStage as multipartGet,\n initiateMultipartBlobStage as multipartInitiate,\n} from \"../routes/blobs/multipart\";\nimport { uploadMultipartBlobPartBytes } from \"../routes/blobs/multipartUpload\";\nimport { listDocumentAttachments as documentAttachmentsList } from \"../routes/documents/attachments\";\nimport type { RequestResultOptions } from \"../types\";\nimport type { ApiClientContext } from \"./apiClientContext\";\n\ntype AttachmentList = ListDocumentAttachmentsResponse;\n\n/**\n * Multipart blob staging, blob bytes, and document attachment bindings, with\n * the per-document attachment listing cache they keep current.\n */\nexport class BlobArea {\n private readonly attachmentLists: ApiClientContext[\"documentAttachmentListRequestsByDocumentId\"];\n\n constructor(private readonly context: ApiClientContext) {\n bindPrototypeMethods(this, BlobArea.prototype);\n this.attachmentLists = context.documentAttachmentListRequestsByDocumentId;\n }\n\n private updateCachedDocumentAttachmentList(\n documentId: string,\n update: (attachments: AttachmentList) => AttachmentList,\n ): void {\n const cached = this.attachmentLists.get(documentId);\n if (!cached) {\n return;\n }\n\n let next: Promise<AttachmentList | null>;\n next = cached\n .then((attachments) => {\n if (!attachments) {\n if (this.attachmentLists.get(documentId) === next) {\n this.attachmentLists.delete(documentId);\n }\n return attachments;\n }\n\n return update(attachments);\n })\n .catch(() => {\n // The underlying list fetch failed. Drop this derived cache entry so the\n // next read refetches, and resolve to null (the cache's miss semantics)\n // rather than rethrowing: nothing awaits this derived promise directly,\n // so a rethrow would surface as an unhandled rejection. Callers already\n // awaiting the original request still observe its rejection.\n if (this.attachmentLists.get(documentId) === next) {\n this.attachmentLists.delete(documentId);\n }\n return null;\n });\n this.attachmentLists.set(documentId, next);\n }\n\n /**\n * The bind acknowledges by hash, so the cached listing entry is rebuilt\n * from the request it acknowledged: a staged upload's bind creates the blob,\n * so its one binding's KEK targets are the ones its content-key bundle wraps\n * to, and it stores exactly the signed event, bundle, and write header it\n * carried. Any other bind (no staged blob, or a target set other than the\n * one the bundle names) keeps material the response does not carry, so it\n * drops the cached listing instead.\n */\n private cacheBlobAttachmentBindResponse(\n request: BlobAttachmentBindRequest,\n response: BlobAttachmentBindResponse,\n ): void {\n const { stagedBlob } = request;\n if (\n !stagedBlob ||\n response.blobKeyTargetHash !== request.contentKeyBundle.targetHash\n ) {\n this.attachmentLists.delete(response.documentId);\n return;\n }\n const binding = blobAttachmentSummaryFromStagedBind(\n { ...request, stagedBlob },\n response,\n );\n this.updateCachedDocumentAttachmentList(\n response.documentId,\n (attachments) => [\n ...attachments.filter(\n (cachedBinding) => cachedBinding.slotId !== response.slotId,\n ),\n binding,\n ],\n );\n }\n\n private cacheBlobAttachmentDetachResponse(\n response: BlobAttachmentDetachResponse,\n ): void {\n this.updateCachedDocumentAttachmentList(\n response.documentId,\n (attachments) =>\n attachments.filter(\n (binding) => binding.bindingId !== response.bindingId,\n ),\n );\n }\n\n // An attachment write updates the cached listing from its response; a\n // refused or failed write leaves every listing unknown, so all are dropped.\n private attachmentWrite<R>(\n write: Promise<R | null>,\n cacheResponse: (response: R) => void,\n ): Promise<R | null> {\n return write\n .then((response) => {\n if (response) {\n cacheResponse(response);\n } else {\n this.attachmentLists.clear();\n }\n return response;\n })\n .catch((error: unknown) => {\n this.attachmentLists.clear();\n throw error;\n });\n }\n\n initiateMultipartBlobStage(input: InitiateMultipartBlobStageRequest) {\n return this.context.send(\n multipartInitiate,\n multipartInitiate.path,\n initiateMultipartBlobStageOperation,\n input,\n );\n }\n\n getMultipartBlobStage(stageId: string) {\n return this.context.send(\n multipartGet,\n multipartGet.path(stageId),\n getMultipartBlobStageOperation,\n );\n }\n\n uploadMultipartBlobPartBytes(\n stageId: string,\n partNumber: number,\n input: UploadMultipartBlobPartBytesRequest,\n options: RequestResultOptions = {},\n ) {\n return uploadMultipartBlobPartBytes(\n this.context.transport,\n stageId,\n partNumber,\n input,\n undefined,\n options,\n );\n }\n\n getBlobBytes(blobId: string, options: RequestResultOptions = {}) {\n return getBlobBytes(this.context.transport, blobId, undefined, options);\n }\n\n bindBlobAttachment(\n blobId: string,\n input: BlobAttachmentBindRequest,\n options: RequestResultOptions = {},\n ) {\n return this.attachmentWrite(\n this.context.send(\n blobAttachmentBind,\n blobAttachmentBind.path(blobId),\n bindBlobAttachmentOperation,\n input,\n options,\n ),\n (response) => this.cacheBlobAttachmentBindResponse(input, response),\n );\n }\n\n detachBlobAttachment(\n blobId: string,\n bindingId: string,\n input: BlobAttachmentDetachRequest,\n options: RequestResultOptions = {},\n ) {\n return this.attachmentWrite(\n this.context.send(\n blobAttachmentDetach,\n blobAttachmentDetach.path(blobId, bindingId),\n detachBlobAttachmentOperation,\n input,\n options,\n ),\n this.cacheBlobAttachmentDetachResponse,\n );\n }\n\n listDocumentAttachments(\n documentId: string,\n options: { refresh?: boolean } = {},\n ) {\n if (options.refresh) {\n this.attachmentLists.delete(documentId);\n }\n return cachedRequest(this.attachmentLists, documentId, () =>\n this.context.send(\n documentAttachmentsList,\n documentAttachmentsList.path(documentId),\n listDocumentAttachmentsOperation,\n ),\n );\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"blobs.js","sourceRoot":"","sources":["blobs.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,2BAA2B,EAC3B,6BAA6B,EAC7B,8BAA8B,EAC9B,mCAAmC,EACnC,gCAAgC,GACjC,MAAM,iC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AAS,CAAC,EAC5C,6BAA6B,EAC7B,KAAK,EACL,OAAO,CACR,EACD,IAAI,CAAC,iCAAiC,CACvC,CAAC;IACJ,CAAC;IAED,uBAAuB,CACrB,UAAkB,EAClB,UAAiC,EAAE;QAEnC,IAAI,OAAO,CAAC,OAAO,EAAE,CAAC;YACpB,IAAI,CAAC,eAAe,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;QAC1C,CAAC;QACD,OAAO,aAAa,CAAC,IAAI,CAAC,eAAe,EAAE,UAAU,EAAE,GAAG,EAAE,CAC1D,IAAI,CAAC,OAAO,CAAC,IAAI,CACf,uBAAuB,EACvB,uBAAuB,CAAC,IAAI,CAAC,UAAU,CAAC,EACxC,gCAAgC,CACjC,CACF,CAAC;IACJ,CAAC;CACF","sourcesContent":["import {\n bindBlobAttachmentOperation,\n detachBlobAttachmentOperation,\n getMultipartBlobStageOperation,\n initiateMultipartBlobStageOperation,\n listDocumentAttachmentsOperation,\n} from \"@tearleads/validators/operation\";\nimport type {\n BlobAttachmentBindRequest,\n BlobAttachmentDetachRequest,\n InitiateMultipartBlobStageRequest,\n} from \"@tearleads/validators/request\";\nimport type {\n BlobAttachmentBindResponse,\n BlobAttachmentDetachResponse,\n ListDocumentAttachmentsResponse,\n} from \"@tearleads/validators/response\";\nimport { blobAttachmentSummaryFromStagedBind } from \"@tearleads/validators/response\";\nimport { bindPrototypeMethods, cachedRequest } from \"../requestInternals\";\nimport {\n bindBlobAttachment as blobAttachmentBind,\n detachBlobAttachment as blobAttachmentDetach,\n} from \"../routes/blobs/attachments\";\nimport {\n getBlobBytes,\n type UploadMultipartBlobPartBytesRequest,\n} from \"../routes/blobs/get\";\nimport {\n getMultipartBlobStage as multipartGet,\n initiateMultipartBlobStage as multipartInitiate,\n} from \"../routes/blobs/multipart\";\nimport { uploadMultipartBlobPartBytes } from \"../routes/blobs/multipartUpload\";\nimport { listDocumentAttachments as documentAttachmentsList } from \"../routes/documents/attachments\";\nimport type { RequestResultOptions } from \"../types\";\nimport type { ApiClientContext } from \"./apiClientContext\";\n\ntype AttachmentList = ListDocumentAttachmentsResponse;\n\n/**\n * Multipart blob staging, blob bytes, and document attachment bindings, with\n * the per-document attachment listing cache they keep current.\n */\nexport class BlobArea {\n private readonly attachmentLists: ApiClientContext[\"documentAttachmentListRequestsByDocumentId\"];\n\n constructor(private readonly context: ApiClientContext) {\n bindPrototypeMethods(this, BlobArea.prototype);\n this.attachmentLists = context.documentAttachmentListRequestsByDocumentId;\n }\n\n private updateCachedDocumentAttachmentList(\n documentId: string,\n update: (attachments: AttachmentList) => AttachmentList,\n ): void {\n const cached = this.attachmentLists.get(documentId);\n if (!cached) {\n return;\n }\n\n let next: Promise<AttachmentList | null>;\n next = cached\n .then((attachments) => {\n if (!attachments) {\n if (this.attachmentLists.get(documentId) === next) {\n this.attachmentLists.delete(documentId);\n }\n return attachments;\n }\n\n return update(attachments);\n })\n .catch(() => {\n // The underlying list fetch failed. Drop this derived cache entry so the\n // next read refetches, and resolve to null (the cache's miss semantics)\n // rather than rethrowing: nothing awaits this derived promise directly,\n // so a rethrow would surface as an unhandled rejection. Callers already\n // awaiting the original request still observe its rejection.\n if (this.attachmentLists.get(documentId) === next) {\n this.attachmentLists.delete(documentId);\n }\n return null;\n });\n this.attachmentLists.set(documentId, next);\n }\n\n /**\n * The bind acknowledges by hash, so the cached listing entry is rebuilt\n * from the request it acknowledged: a staged upload's bind creates the blob,\n * so its one binding's KEK targets are the ones its content-key bundle wraps\n * to, and it stores exactly the signed event, bundle, and write header it\n * carried. Any other bind (no staged blob, or a target set other than the\n * one the bundle names) keeps material the response does not carry, so it\n * drops the cached listing instead.\n */\n private cacheBlobAttachmentBindResponse(\n request: BlobAttachmentBindRequest,\n response: BlobAttachmentBindResponse,\n ): void {\n const { stagedBlob } = request;\n if (\n !stagedBlob ||\n response.blobKeyTargetHash !== request.contentKeyBundle.targetHash\n ) {\n this.attachmentLists.delete(response.documentId);\n return;\n }\n const binding = blobAttachmentSummaryFromStagedBind(\n { ...request, stagedBlob },\n response,\n );\n this.updateCachedDocumentAttachmentList(\n response.documentId,\n (attachments) => [\n ...attachments.filter(\n (cachedBinding) => cachedBinding.slotId !== response.slotId,\n ),\n binding,\n ],\n );\n }\n\n private cacheBlobAttachmentDetachResponse(\n response: BlobAttachmentDetachResponse,\n ): void {\n this.updateCachedDocumentAttachmentList(\n response.documentId,\n (attachments) =>\n attachments.filter(\n (binding) => binding.bindingId !== response.bindingId,\n ),\n );\n }\n\n // An attachment write updates the cached listing from its response; a\n // refused or failed write leaves every listing unknown, so all are dropped.\n private attachmentWrite<R>(\n write: Promise<R | null>,\n cacheResponse: (response: R) => void,\n ): Promise<R | null> {\n const session = this.context.runtime.responseRequest.sessionSignal?.();\n return write\n .then((response) => {\n if (session?.aborted) return null;\n if (response) {\n cacheResponse(response);\n } else {\n this.attachmentLists.clear();\n }\n return response;\n })\n .catch((error: unknown) => {\n if (!session?.aborted) this.attachmentLists.clear();\n throw error;\n });\n }\n\n initiateMultipartBlobStage(input: InitiateMultipartBlobStageRequest) {\n return this.context.send(\n multipartInitiate,\n multipartInitiate.path,\n initiateMultipartBlobStageOperation,\n input,\n );\n }\n\n getMultipartBlobStage(stageId: string) {\n return this.context.send(\n multipartGet,\n multipartGet.path(stageId),\n getMultipartBlobStageOperation,\n );\n }\n\n uploadMultipartBlobPartBytes(\n stageId: string,\n partNumber: number,\n input: UploadMultipartBlobPartBytesRequest,\n options: RequestResultOptions = {},\n ) {\n return this.transfer(options, (scoped) =>\n uploadMultipartBlobPartBytes(\n this.context.transport,\n stageId,\n partNumber,\n input,\n undefined,\n scoped,\n ),\n );\n }\n\n getBlobBytes(blobId: string, options: RequestResultOptions = {}) {\n return this.transfer(options, (scoped) =>\n getBlobBytes(this.context.transport, blobId, undefined, scoped),\n );\n }\n\n private async transfer<T>(\n options: RequestResultOptions,\n run: (scoped: RequestResultOptions) => Promise<T | null>,\n ): Promise<T | null> {\n const scoped = this.context.runtime.withSessionSignal(options);\n const result = await run(scoped);\n return scoped.signal?.aborted ? null : result;\n }\n\n bindBlobAttachment(\n blobId: string,\n input: BlobAttachmentBindRequest,\n options: RequestResultOptions = {},\n ) {\n return this.attachmentWrite(\n this.context.send(\n blobAttachmentBind,\n blobAttachmentBind.path(blobId),\n bindBlobAttachmentOperation,\n input,\n options,\n ),\n (response) => this.cacheBlobAttachmentBindResponse(input, response),\n );\n }\n\n detachBlobAttachment(\n blobId: string,\n bindingId: string,\n input: BlobAttachmentDetachRequest,\n options: RequestResultOptions = {},\n ) {\n return this.attachmentWrite(\n this.context.send(\n blobAttachmentDetach,\n blobAttachmentDetach.path(blobId, bindingId),\n detachBlobAttachmentOperation,\n input,\n options,\n ),\n this.cacheBlobAttachmentDetachResponse,\n );\n }\n\n listDocumentAttachments(\n documentId: string,\n options: { refresh?: boolean } = {},\n ) {\n if (options.refresh) {\n this.attachmentLists.delete(documentId);\n }\n return cachedRequest(this.attachmentLists, documentId, () =>\n this.context.send(\n documentAttachmentsList,\n documentAttachmentsList.path(documentId),\n listDocumentAttachmentsOperation,\n ),\n );\n }\n}\n"]}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { requestDeadline } from "../requestDeadline.js";
|
|
2
|
+
import { retiredRequest } from "../sessionResponse.js";
|
|
2
3
|
/**
|
|
3
4
|
* A container lane listing with no complete response by now is treated as
|
|
4
5
|
* lost. Far above a healthy batch, it bounds every sweep and tree crawl that
|
|
@@ -15,6 +16,7 @@ export const CONTAINER_LANE_LISTING_TIMEOUT_MS = 60_000;
|
|
|
15
16
|
*/
|
|
16
17
|
export async function laneListingRequest(context, input) {
|
|
17
18
|
const { method, path, reportErrors } = input;
|
|
19
|
+
const signIn = context.runtime.responseRequest.sessionSignal?.();
|
|
18
20
|
// Report only after classifying: an abort inside the body otherwise
|
|
19
21
|
// surfaces as a body-read failure before it is known to be the deadline.
|
|
20
22
|
const deadline = requestDeadline({ reportErrors: false }, CONTAINER_LANE_LISTING_TIMEOUT_MS);
|
|
@@ -23,6 +25,8 @@ export async function laneListingRequest(context, input) {
|
|
|
23
25
|
// included, so the request has fully settled, and written its last
|
|
24
26
|
// shared state, by the time the deadline's failure is recorded.
|
|
25
27
|
const result = await context.requestResult(path, input.validator, method, input.body, deadline.options, input.operation);
|
|
28
|
+
if (signIn?.aborted)
|
|
29
|
+
return retiredRequest(method, path);
|
|
26
30
|
if (result.ok)
|
|
27
31
|
return result;
|
|
28
32
|
if (!deadline.expired()) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"laneListingRequest.js","sourceRoot":"","sources":["laneListingRequest.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;
|
|
1
|
+
{"version":3,"file":"laneListingRequest.js","sourceRoot":"","sources":["laneListingRequest.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AACrD,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAIpD;;;;;GAKG;AACH,MAAM,CAAC,MAAM,iCAAiC,GAAG,MAAM,CAAC;AAExD;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,kBAAkB,CACtC,OAAyB,EACzB,KAOC;IAED,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,YAAY,EAAE,GAAG,KAAK,CAAC;IAC7C,MAAM,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,eAAe,CAAC,aAAa,EAAE,EAAE,CAAC;IACjE,oEAAoE;IACpE,yEAAyE;IACzE,MAAM,QAAQ,GAAG,eAAe,CAC9B,EAAE,YAAY,EAAE,KAAK,EAAE,EACvB,iCAAiC,CAClC,CAAC;IACF,IAAI,CAAC;QACH,qEAAqE;QACrE,mEAAmE;QACnE,gEAAgE;QAChE,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,aAAa,CACxC,IAAI,EACJ,KAAK,CAAC,SAAS,EACf,MAAM,EACN,KAAK,CAAC,IAAI,EACV,QAAQ,CAAC,OAAO,EAChB,KAAK,CAAC,SAAS,CAChB,CAAC;QACF,IAAI,MAAM,EAAE,OAAO;YAAE,OAAO,cAAc,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;QACzD,IAAI,MAAM,CAAC,EAAE;YAAE,OAAO,MAAM,CAAC;QAC7B,IAAI,CAAC,QAAQ,CAAC,OAAO,EAAE,EAAE,CAAC;YACxB,IAAI,YAAY;gBAAE,MAAM,CAAC,MAAM,EAAE,CAAC;YAClC,OAAO,MAAM,CAAC;QAChB,CAAC;QACD,OAAO,OAAO,CAAC,OAAO,CAAC,eAAe,CAAC,aAAa,CAAC;YACnD,IAAI,EAAE,mBAAmB;YACzB,IAAI,EAAE,SAAS;YACf,OAAO,EAAE,GAAG,MAAM,IAAI,IAAI,wBAAwB,iCAAiC,KAAK;YACxF,MAAM;YACN,OAAO,EAAE,EAAE,YAAY,EAAE;YACzB,IAAI;YACJ,MAAM,EAAE,IAAI;YACZ,UAAU,EAAE,EAAE;SACf,CAAC,CAAC;IACL,CAAC;YAAS,CAAC;QACT,QAAQ,CAAC,OAAO,EAAE,CAAC;IACrB,CAAC;AACH,CAAC","sourcesContent":["import type { HttpOperation } from \"@tearleads/validators/operation\";\nimport { requestDeadline } from \"../requestDeadline\";\nimport { retiredRequest } from \"../sessionResponse\";\nimport type { HttpMethod, RequestResult } from \"../types\";\nimport type { ApiClientContext } from \"./apiClientContext\";\n\n/**\n * A container lane listing with no complete response by now is treated as\n * lost. Far above a healthy batch, it bounds every sweep and tree crawl that\n * waits on one: without it, a request that never settles holds the shared\n * listing, and everything joined to it, indefinitely.\n */\nexport const CONTAINER_LANE_LISTING_TIMEOUT_MS = 60_000;\n\n/**\n * Runs one lane listing under {@link CONTAINER_LANE_LISTING_TIMEOUT_MS}. The\n * deadline belongs to the request, not to a caller, so a de-duplicated\n * listing ends for every caller joined to it. A timeout, before the headers\n * or inside the body, fails as one network failure rather than a cancellation\n * or a body error, so it is reported once and retried like any lost request.\n */\nexport async function laneListingRequest<T>(\n context: ApiClientContext,\n input: {\n readonly body: string;\n readonly method: HttpMethod;\n readonly operation: HttpOperation;\n readonly path: string;\n readonly reportErrors: boolean;\n readonly validator: (value: unknown) => value is T;\n },\n): Promise<RequestResult<T>> {\n const { method, path, reportErrors } = input;\n const signIn = context.runtime.responseRequest.sessionSignal?.();\n // Report only after classifying: an abort inside the body otherwise\n // surfaces as a body-read failure before it is known to be the deadline.\n const deadline = requestDeadline(\n { reportErrors: false },\n CONTAINER_LANE_LISTING_TIMEOUT_MS,\n );\n try {\n // Every wait inside the request observes the signal, session renewal\n // included, so the request has fully settled, and written its last\n // shared state, by the time the deadline's failure is recorded.\n const result = await context.requestResult(\n path,\n input.validator,\n method,\n input.body,\n deadline.options,\n input.operation,\n );\n if (signIn?.aborted) return retiredRequest(method, path);\n if (result.ok) return result;\n if (!deadline.expired()) {\n if (reportErrors) result.report();\n return result;\n }\n return context.runtime.responseRequest.reportFailure({\n code: \"request_timed_out\",\n kind: \"network\",\n message: `${method} ${path}: no response within ${CONTAINER_LANE_LISTING_TIMEOUT_MS} ms`,\n method,\n options: { reportErrors },\n path,\n status: null,\n statusText: \"\",\n });\n } finally {\n deadline.dispose();\n }\n}\n"]}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { RegistrationRequest } from "../../validators/request/index.js";
|
|
2
2
|
import type { VerifySuccessResponse } from "../../validators/response/index.js";
|
|
3
3
|
import type { ApiNetworkError } from "../networkFailure.js";
|
|
4
|
+
import type { SessionBoundary } from "../sessionRenewal.js";
|
|
4
5
|
import type { HttpMethod } from "../types.js";
|
|
5
6
|
import type { VerifiedManifestCitations } from "../verifiedManifestCitations.js";
|
|
6
7
|
import type { ApiClientContext } from "./apiClientContext.js";
|
|
@@ -23,7 +24,10 @@ export declare class SessionArea {
|
|
|
23
24
|
setOnPaymentRequired(handler: PaymentRequiredHandler | null): void;
|
|
24
25
|
/** Verified bundles to cite on projection reads, scoped by their owner. */
|
|
25
26
|
setVerifiedManifestCitations(source: VerifiedManifestCitations | null): void;
|
|
26
|
-
setAuthToken(token: string | null
|
|
27
|
+
setAuthToken(token: string | null, options?: {
|
|
28
|
+
boundary?: SessionBoundary | undefined;
|
|
29
|
+
verifiedTicket?: string | undefined;
|
|
30
|
+
}): void;
|
|
27
31
|
getAuthToken(): string | null;
|
|
28
32
|
getRequestFailure(input: {
|
|
29
33
|
method: HttpMethod;
|
|
@@ -42,8 +42,14 @@ export class SessionArea {
|
|
|
42
42
|
setVerifiedManifestCitations(source) {
|
|
43
43
|
this.context.verifiedManifestCitations = source;
|
|
44
44
|
}
|
|
45
|
-
setAuthToken(token) {
|
|
46
|
-
|
|
45
|
+
setAuthToken(token, options) {
|
|
46
|
+
const boundary = options?.boundary ??
|
|
47
|
+
(token === null && this.getAuthToken() !== null
|
|
48
|
+
? "replacement"
|
|
49
|
+
: undefined);
|
|
50
|
+
if (boundary)
|
|
51
|
+
this.webSocketTickets.retainVerifiedTicket(options?.verifiedTicket);
|
|
52
|
+
if (this.context.runtime.setAuthToken(token, boundary)) {
|
|
47
53
|
this.context.clearAuthScopedCaches();
|
|
48
54
|
}
|
|
49
55
|
}
|
|
@@ -82,18 +88,20 @@ export class SessionArea {
|
|
|
82
88
|
});
|
|
83
89
|
}
|
|
84
90
|
async authenticate(fingerprint, secretKey) {
|
|
91
|
+
const session = this.context.runtime.responseRequest.sessionSignal?.();
|
|
85
92
|
const challenge = await this.context.transport.request(challengeOperation, { body: { fingerprint }, params: {} }, { retryOnSessionExpired: false });
|
|
86
|
-
if (!challenge)
|
|
93
|
+
if (!challenge || session?.aborted)
|
|
87
94
|
return null;
|
|
88
95
|
return this.self.authenticateWithChallenge(fingerprint, secretKey, challenge.challenge);
|
|
89
96
|
}
|
|
90
97
|
async authenticateWithChallenge(fingerprint, secretKey, challengeHex) {
|
|
98
|
+
const session = this.context.runtime.responseRequest.sessionSignal?.();
|
|
91
99
|
const signed = sign(this.context.runtime.authChallengeBytes(challengeHex, fingerprint), secretKey);
|
|
92
100
|
const response = verifiedLogin(await this.context.transport.requestResult(verifyOperation, {
|
|
93
101
|
body: { fingerprint, signature: bytesToBase64(signed) },
|
|
94
102
|
params: {},
|
|
95
103
|
}, { retryOnSessionExpired: false }));
|
|
96
|
-
if (!response?.authenticated)
|
|
104
|
+
if (!response?.authenticated || session?.aborted)
|
|
97
105
|
return null;
|
|
98
106
|
this.webSocketTickets.rememberLogin(response);
|
|
99
107
|
return response;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session.js","sourceRoot":"","sources":["session.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,mBAAmB,CAAC;AACzC,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EACL,kBAAkB,EAClB,uBAAuB,EACvB,kBAAkB,EAClB,qBAAqB,EACrB,eAAe,EACf,iBAAiB,EACjB,eAAe,GAChB,MAAM,iCAAiC,CAAC;AAGzC,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAErD,OAAO,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAC3D,OAAO,EACL,cAAc,IAAI,kBAAkB,EACpC,YAAY,IAAI,gBAAgB,EAChC,MAAM,IAAI,UAAU,GACrB,MAAM,wBAAwB,CAAC;AAGhC,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAOvD,oEAAoE;AACpE,MAAM,OAAO,WAAW;IAIH;IACA;IAJF,gBAAgB,CAAmB;IAEpD,YACmB,OAAyB,EACzB,IAGhB;QAJgB,YAAO,GAAP,OAAO,CAAkB;QACzB,SAAI,GAAJ,IAAI,CAGpB;QAED,oBAAoB,CAAC,IAAI,EAAE,WAAW,CAAC,SAAS,CAAC,CAAC;QAClD,IAAI,CAAC,gBAAgB,GAAG,IAAI,gBAAgB,CAAC,OAAO,CAAC,SAAS,EAAE,GAAG,EAAE,CACnE,IAAI,CAAC,YAAY,EAAE,CACpB,CAA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SAC7B,CACF,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { sign } from \"@tearleads/crypto\";\nimport { bytesToBase64 } from \"@tearleads/encoding\";\nimport {\n challengeOperation,\n destroySessionOperation,\n getHealthOperation,\n listSessionsOperation,\n logoutOperation,\n registerOperation,\n verifyOperation,\n} from \"@tearleads/validators/operation\";\nimport type { RegistrationRequest } from \"@tearleads/validators/request\";\nimport type { VerifySuccessResponse } from \"@tearleads/validators/response\";\nimport { verifiedLogin } from \"../accountSuspension\";\nimport type { ApiNetworkError } from \"../networkFailure\";\nimport { bindPrototypeMethods } from \"../requestInternals\";\nimport {\n destroySession as authDestroySession,\n listSessions as authListSessions,\n logout as authLogout,\n} from \"../routes/auth/session\";\nimport type { HttpMethod } from \"../types\";\nimport type { VerifiedManifestCitations } from \"../verifiedManifestCitations\";\nimport { WebSocketTickets } from \"../webSocketTickets\";\nimport type { ApiClientContext } from \"./apiClientContext\";\nimport type { ApiClientSelf } from \"./apiClientSelf\";\n\ntype ExpiredHandler = () => boolean | Promise<boolean>;\ntype PaymentRequiredHandler = (organizationId: string | null) => void;\n\n/** Connection hooks, the session token, registration, and login. */\nexport class SessionArea {\n private readonly webSocketTickets: WebSocketTickets;\n\n constructor(\n private readonly context: ApiClientContext,\n private readonly self: Pick<\n ApiClientSelf,\n \"authenticateWithChallenge\" | \"getAuthToken\"\n >,\n ) {\n bindPrototypeMethods(this, SessionArea.prototype);\n this.webSocketTickets = new WebSocketTickets(context.transport, () =>\n self.getAuthToken(),\n );\n }\n\n setOnError(handler: ((message: string) => void) | null): void {\n this.context.runtime.setOnError(handler);\n }\n\n setOnNetworkError(handler: (() => void) | null): void {\n this.context.runtime.setOnNetworkError(handler);\n }\n\n setOnNetworkSuccess(handler: (() => void) | null): void {\n this.context.runtime.setOnNetworkSuccess(handler);\n }\n\n /** Every fetch that threw without a response, except plain cancellations. */\n setOnNetworkFailure(handler: ((e: ApiNetworkError) => void) | null): void {\n this.context.runtime.setOnNetworkFailure(handler);\n }\n\n setOnApiVersion(handler: ((version: number) => void) | null): void {\n this.context.runtime.setOnApiVersion(handler);\n }\n\n setOnSessionExpired(handler: ExpiredHandler | null): void {\n this.context.runtime.setOnSessionExpired(handler);\n }\n\n setOnPaymentRequired(handler: PaymentRequiredHandler | null): void {\n this.context.runtime.setOnPaymentRequired(handler);\n }\n\n /** Verified bundles to cite on projection reads, scoped by their owner. */\n setVerifiedManifestCitations(source: VerifiedManifestCitations | null): void {\n this.context.verifiedManifestCitations = source;\n }\n\n setAuthToken(token: string | null): void {\n if (this.context.runtime.setAuthToken(token)) {\n this.context.clearAuthScopedCaches();\n }\n }\n\n getAuthToken(): string | null {\n return this.context.runtime.getAuthToken();\n }\n\n getRequestFailure(input: { method: HttpMethod; path: string }) {\n return this.context.runtime.getRequestFailure(input);\n }\n\n requestWebSocketTicket(): Promise<string | null> {\n return this.webSocketTickets.next();\n }\n\n getHealth() {\n return this.context.transport.request(getHealthOperation, { params: {} });\n }\n\n registerUser(\n userId: string,\n organizationId: string,\n rootContainerId: string,\n signingPublicKey: Uint8Array,\n encapsulationPublicKey: Uint8Array,\n initialAdminGroup: RegistrationRequest[\"initialAdminGroup\"],\n initialMemberGroup: RegistrationRequest[\"initialMemberGroup\"],\n initialOrganizationPolicy: RegistrationRequest[\"initialOrganizationPolicy\"],\n initialRootContainer: RegistrationRequest[\"initialRootContainer\"],\n initialRootMetadataDocument: RegistrationRequest[\"initialRootMetadataDocument\"],\n initialRosterProfileContainer: RegistrationRequest[\"initialRosterProfileContainer\"],\n initialRosterProfileDocument: RegistrationRequest[\"initialRosterProfileDocument\"],\n initialOrganizationMetadataContainer: RegistrationRequest[\"initialOrganizationMetadataContainer\"],\n initialOrganizationProfileDocument?: RegistrationRequest[\"initialOrganizationProfileDocument\"],\n initialSystemContainers?: RegistrationRequest[\"initialSystemContainers\"],\n ) {\n return this.context.transport.request(registerOperation, {\n body: {\n userId,\n organizationId,\n rootContainerId,\n signingPublicKey: bytesToBase64(signingPublicKey),\n encapsulationPublicKey: bytesToBase64(encapsulationPublicKey),\n initialAdminGroup,\n initialMemberGroup,\n initialOrganizationPolicy,\n initialRootContainer,\n initialRootMetadataDocument,\n initialRosterProfileContainer,\n initialRosterProfileDocument,\n initialOrganizationMetadataContainer,\n initialOrganizationProfileDocument,\n initialSystemContainers,\n },\n params: {},\n });\n }\n\n async authenticate(fingerprint: string, secretKey: Uint8Array) {\n const challenge = await this.context.transport.request(\n challengeOperation,\n { body: { fingerprint }, params: {} },\n { retryOnSessionExpired: false },\n );\n if (!challenge) return null;\n\n return this.self.authenticateWithChallenge(\n fingerprint,\n secretKey,\n challenge.challenge,\n );\n }\n\n async authenticateWithChallenge(\n fingerprint: string,\n secretKey: Uint8Array,\n challengeHex: string,\n ): Promise<VerifySuccessResponse | null> {\n const signed = sign(\n this.context.runtime.authChallengeBytes(challengeHex, fingerprint),\n secretKey,\n );\n const response = verifiedLogin(\n await this.context.transport.requestResult(\n verifyOperation,\n {\n body: { fingerprint, signature: bytesToBase64(signed) },\n params: {},\n },\n { retryOnSessionExpired: false },\n ),\n );\n if (!response?.authenticated) return null;\n this.webSocketTickets.rememberLogin(response);\n return response;\n }\n\n listSessions() {\n return this.context.send(\n authListSessions,\n authListSessions.path,\n listSessionsOperation,\n );\n }\n\n destroySession(sessionId: string) {\n return this.context.send(\n authDestroySession,\n authDestroySession.path(sessionId),\n destroySessionOperation,\n );\n }\n\n logout() {\n return this.context.send(\n authLogout,\n authLogout.path,\n logoutOperation,\n undefined,\n {\n retryOnSessionExpired: false,\n },\n );\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"session.js","sourceRoot":"","sources":["session.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,mBAAmB,CAAC;AACzC,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EACL,kBAAkB,EAClB,uBAAuB,EACvB,kBAAkB,EAClB,qBAAqB,EACrB,eAAe,EACf,iBAAiB,E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CAAC;CACF","sourcesContent":["import { sign } from \"@tearleads/crypto\";\nimport { bytesToBase64 } from \"@tearleads/encoding\";\nimport {\n challengeOperation,\n destroySessionOperation,\n getHealthOperation,\n listSessionsOperation,\n logoutOperation,\n registerOperation,\n verifyOperation,\n} from \"@tearleads/validators/operation\";\nimport type { RegistrationRequest } from \"@tearleads/validators/request\";\nimport type { VerifySuccessResponse } from \"@tearleads/validators/response\";\nimport { verifiedLogin } from \"../accountSuspension\";\nimport type { ApiNetworkError } from \"../networkFailure\";\nimport { bindPrototypeMethods } from \"../requestInternals\";\nimport {\n destroySession as authDestroySession,\n listSessions as authListSessions,\n logout as authLogout,\n} from \"../routes/auth/session\";\nimport type { SessionBoundary } from \"../sessionRenewal\";\nimport type { HttpMethod } from \"../types\";\nimport type { VerifiedManifestCitations } from \"../verifiedManifestCitations\";\nimport { WebSocketTickets } from \"../webSocketTickets\";\nimport type { ApiClientContext } from \"./apiClientContext\";\nimport type { ApiClientSelf } from \"./apiClientSelf\";\n\ntype ExpiredHandler = () => boolean | Promise<boolean>;\ntype PaymentRequiredHandler = (organizationId: string | null) => void;\n\n/** Connection hooks, the session token, registration, and login. */\nexport class SessionArea {\n private readonly webSocketTickets: WebSocketTickets;\n\n constructor(\n private readonly context: ApiClientContext,\n private readonly self: Pick<\n ApiClientSelf,\n \"authenticateWithChallenge\" | \"getAuthToken\"\n >,\n ) {\n bindPrototypeMethods(this, SessionArea.prototype);\n this.webSocketTickets = new WebSocketTickets(context.transport, () =>\n self.getAuthToken(),\n );\n }\n\n setOnError(handler: ((message: string) => void) | null): void {\n this.context.runtime.setOnError(handler);\n }\n\n setOnNetworkError(handler: (() => void) | null): void {\n this.context.runtime.setOnNetworkError(handler);\n }\n\n setOnNetworkSuccess(handler: (() => void) | null): void {\n this.context.runtime.setOnNetworkSuccess(handler);\n }\n\n /** Every fetch that threw without a response, except plain cancellations. */\n setOnNetworkFailure(handler: ((e: ApiNetworkError) => void) | null): void {\n this.context.runtime.setOnNetworkFailure(handler);\n }\n\n setOnApiVersion(handler: ((version: number) => void) | null): void {\n this.context.runtime.setOnApiVersion(handler);\n }\n\n setOnSessionExpired(handler: ExpiredHandler | null): void {\n this.context.runtime.setOnSessionExpired(handler);\n }\n\n setOnPaymentRequired(handler: PaymentRequiredHandler | null): void {\n this.context.runtime.setOnPaymentRequired(handler);\n }\n\n /** Verified bundles to cite on projection reads, scoped by their owner. */\n setVerifiedManifestCitations(source: VerifiedManifestCitations | null): void {\n this.context.verifiedManifestCitations = source;\n }\n\n setAuthToken(\n token: string | null,\n options?: {\n boundary?: SessionBoundary | undefined;\n verifiedTicket?: string | undefined;\n },\n ): void {\n const boundary =\n options?.boundary ??\n (token === null && this.getAuthToken() !== null\n ? \"replacement\"\n : undefined);\n if (boundary)\n this.webSocketTickets.retainVerifiedTicket(options?.verifiedTicket);\n if (this.context.runtime.setAuthToken(token, boundary)) {\n this.context.clearAuthScopedCaches();\n }\n }\n\n getAuthToken(): string | null {\n return this.context.runtime.getAuthToken();\n }\n\n getRequestFailure(input: { method: HttpMethod; path: string }) {\n return this.context.runtime.getRequestFailure(input);\n }\n\n requestWebSocketTicket(): Promise<string | null> {\n return this.webSocketTickets.next();\n }\n\n getHealth() {\n return this.context.transport.request(getHealthOperation, { params: {} });\n }\n\n registerUser(\n userId: string,\n organizationId: string,\n rootContainerId: string,\n signingPublicKey: Uint8Array,\n encapsulationPublicKey: Uint8Array,\n initialAdminGroup: RegistrationRequest[\"initialAdminGroup\"],\n initialMemberGroup: RegistrationRequest[\"initialMemberGroup\"],\n initialOrganizationPolicy: RegistrationRequest[\"initialOrganizationPolicy\"],\n initialRootContainer: RegistrationRequest[\"initialRootContainer\"],\n initialRootMetadataDocument: RegistrationRequest[\"initialRootMetadataDocument\"],\n initialRosterProfileContainer: RegistrationRequest[\"initialRosterProfileContainer\"],\n initialRosterProfileDocument: RegistrationRequest[\"initialRosterProfileDocument\"],\n initialOrganizationMetadataContainer: RegistrationRequest[\"initialOrganizationMetadataContainer\"],\n initialOrganizationProfileDocument?: RegistrationRequest[\"initialOrganizationProfileDocument\"],\n initialSystemContainers?: RegistrationRequest[\"initialSystemContainers\"],\n ) {\n return this.context.transport.request(registerOperation, {\n body: {\n userId,\n organizationId,\n rootContainerId,\n signingPublicKey: bytesToBase64(signingPublicKey),\n encapsulationPublicKey: bytesToBase64(encapsulationPublicKey),\n initialAdminGroup,\n initialMemberGroup,\n initialOrganizationPolicy,\n initialRootContainer,\n initialRootMetadataDocument,\n initialRosterProfileContainer,\n initialRosterProfileDocument,\n initialOrganizationMetadataContainer,\n initialOrganizationProfileDocument,\n initialSystemContainers,\n },\n params: {},\n });\n }\n\n async authenticate(fingerprint: string, secretKey: Uint8Array) {\n const session = this.context.runtime.responseRequest.sessionSignal?.();\n const challenge = await this.context.transport.request(\n challengeOperation,\n { body: { fingerprint }, params: {} },\n { retryOnSessionExpired: false },\n );\n if (!challenge || session?.aborted) return null;\n\n return this.self.authenticateWithChallenge(\n fingerprint,\n secretKey,\n challenge.challenge,\n );\n }\n\n async authenticateWithChallenge(\n fingerprint: string,\n secretKey: Uint8Array,\n challengeHex: string,\n ): Promise<VerifySuccessResponse | null> {\n const session = this.context.runtime.responseRequest.sessionSignal?.();\n const signed = sign(\n this.context.runtime.authChallengeBytes(challengeHex, fingerprint),\n secretKey,\n );\n const response = verifiedLogin(\n await this.context.transport.requestResult(\n verifyOperation,\n {\n body: { fingerprint, signature: bytesToBase64(signed) },\n params: {},\n },\n { retryOnSessionExpired: false },\n ),\n );\n if (!response?.authenticated || session?.aborted) return null;\n this.webSocketTickets.rememberLogin(response);\n return response;\n }\n\n listSessions() {\n return this.context.send(\n authListSessions,\n authListSessions.path,\n listSessionsOperation,\n );\n }\n\n destroySession(sessionId: string) {\n return this.context.send(\n authDestroySession,\n authDestroySession.path(sessionId),\n destroySessionOperation,\n );\n }\n\n logout() {\n return this.context.send(\n authLogout,\n authLogout.path,\n logoutOperation,\n undefined,\n {\n retryOnSessionExpired: false,\n },\n );\n }\n}\n"]}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { getContainerWriterProjectionOperation, getDocumentWriterProjectionOperation, } from "../../validators/operation/index.js";
|
|
2
2
|
import { bindPrototypeMethods, cachedRequest } from "../requestInternals.js";
|
|
3
3
|
import { containerWriterProjection, documentWriterProjection, } from "../routes/writerProjections.js";
|
|
4
|
+
import { retiredRequest } from "../sessionResponse.js";
|
|
4
5
|
import { primeWriterProjectionSlot } from "../writerProjectionPrime.js";
|
|
5
6
|
/**
|
|
6
7
|
* Container and document writer projections: plain cached reads, coalesced
|
|
@@ -91,21 +92,17 @@ export class WriterProjectionArea {
|
|
|
91
92
|
// so a projection an eviction (e.g. after a revoke) meant to drop is never
|
|
92
93
|
// re-cached.
|
|
93
94
|
async fetchWriterProjectionResult(cache, { cacheKey, path, validator, failureOperation }) {
|
|
95
|
+
const session = this.context.runtime.responseRequest.sessionSignal?.();
|
|
96
|
+
const retired = () => retiredRequest("GET", path);
|
|
94
97
|
let cached = cache.get(cacheKey);
|
|
95
98
|
while (cached) {
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
// A rejected shared entry is reconciled by its own settle handler;
|
|
104
|
-
// fall through either way.
|
|
105
|
-
}
|
|
106
|
-
// The awaited entry settled empty. Re-read the slot before fetching: a
|
|
107
|
-
// newer entry installed while we awaited must be reused, not fetched
|
|
108
|
-
// over — the set below would otherwise clobber it.
|
|
99
|
+
// Rejected and empty entries both fall through to the current slot.
|
|
100
|
+
const data = await cached.catch(() => null);
|
|
101
|
+
if (session?.aborted)
|
|
102
|
+
return retired();
|
|
103
|
+
if (data)
|
|
104
|
+
return { data, ok: true };
|
|
105
|
+
// A newer entry installed during the wait must be reused.
|
|
109
106
|
const current = cache.get(cacheKey);
|
|
110
107
|
if (current === cached) {
|
|
111
108
|
break;
|
|
@@ -123,6 +120,8 @@ export class WriterProjectionArea {
|
|
|
123
120
|
const result = await this.context.requestResult(path, validator, "GET", undefined, {
|
|
124
121
|
reportErrors: false,
|
|
125
122
|
}, failureOperation);
|
|
123
|
+
if (session?.aborted)
|
|
124
|
+
return retired();
|
|
126
125
|
if (result.ok) {
|
|
127
126
|
// Publish the success unless the slot changed or this id was
|
|
128
127
|
// invalidated mid-flight. The stamp check is what makes an eviction of
|