@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":"writerProjections.js","sourceRoot":"","sources":["writerProjections.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,qCAAqC,EACrC,oCAAoC,GAErC,MAAM,iCAAiC,CAAC;AAMzC,OAAO,EAAE,oBAAoB,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAC1E,OAAO,EACL,yBAAyB,EACzB,wBAAwB,GACzB,MAAM,6BAA6B,CAAC;AAGrC,OAAO,EAAE,yBAAyB,EAAE,MAAM,0BAA0B,CAAC;AAkBrE;;;GAGG;AACH,MAAM,OAAO,oBAAoB;IAIF;IAHZ,UAAU,CAAqD;IAC/D,SAAS,CAAoD;IAE9E,YAA6B,OAAyB;QAAzB,YAAO,GAAP,OAAO,CAAkB;QACpD,oBAAoB,CAAC,IAAI,EAAE,oBAAoB,CAAC,SAAS,CAAC,CAAC;QAC3D,IAAI,CAAC,UAAU,GAAG;YAChB,KAAK,EAAE,OAAO,CAAC,8CAA8C;YAC7D,eAAe,EACb,OAAO,CAAC,qDAAqD;SAChE,CAAC;QACF,IAAI,CAAC,SAAS,GAAG;YACf,KAAK,EAAE,OAAO,CAAC,4CAA4C;YAC3D,eAAe,EACb,OAAO,CAAC,mDAAmD;SAC9D,CAAC;IACJ,CAAC;IAED,uEAAuE;IACvE,2EAA2E;IAC3E,6EAA6E;IAC7E,8CAA8C;IACtC,sBAAsB,CAC5B,EAAE,KAAK,EAAE,eAAe,EAAsB,EAC9C,IAAuB,EACvB,OAA6B;QAE7B,MAAM,EAAE,QAAQ,EAAE,IAAI,EAAE,SAAS,EAA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C,aAAa,CAAC,UAAU,CAAC;YAC7D,EAAE,EAAE,UAAU;YACd,eAAe,EAAE,IAAI,CAAC,SAAS,CAAC,eAAe;YAC/C,KAAK,EAAE,UAAU;YACjB,UAAU;SACX,CAAC,CAAC;IACL,CAAC;IAED;;;;;;;;;;;;;OAaG;IACH,8BAA8B,CAC5B,WAAmB,EACnB,UAA6C;QAE7C,yBAAyB,CAAC;YACxB,KAAK,EAAE,IAAI,CAAC,UAAU,CAAC,KAAK;YAC5B,SAAS,EAAE,yBAAyB,CAAC,aAAa,CAAC,WAAW,CAAC;YAC/D,EAAE,EAAE,WAAW;YACf,eAAe,EAAE,IAAI,CAAC,UAAU,CAAC,eAAe;YAChD,KAAK,EAAE,WAAW;YAClB,UAAU;SACX,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import {\n getContainerWriterProjectionOperation,\n getDocumentWriterProjectionOperation,\n type HttpOperation,\n} from \"@tearleads/validators/operation\";\nimport type {\n ContainerWriterProjectionResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport type { BoundedCache } from \"../ApiCache\";\nimport { bindPrototypeMethods, cachedRequest } from \"../requestInternals\";\nimport {\n containerWriterProjection,\n documentWriterProjection,\n} from \"../routes/writerProjections\";\nimport type { RequestResult, RequestResultOptions } from \"../types\";\nimport type { WriterProjectionListing } from \"../verifiedManifestCitations\";\nimport { primeWriterProjectionSlot } from \"../writerProjectionPrime\";\nimport type {\n ApiClientContext,\n InFlightWriterProjectionResult,\n} from \"./apiClientContext\";\n\ninterface ProjectionSlots<T> {\n readonly cache: BoundedCache<Promise<T | null>>;\n readonly inFlightResults: Map<string, InFlightWriterProjectionResult<T>>;\n}\n\ninterface ProjectionRead<T> {\n readonly cacheKey: string;\n readonly path: string;\n readonly validator: (value: unknown) => value is T;\n readonly failureOperation: HttpOperation;\n}\n\n/**\n * Container and document writer projections: plain cached reads, coalesced\n * status-bearing reads, and primes from just-authored mutation material.\n */\nexport class WriterProjectionArea {\n private readonly containers: ProjectionSlots<ContainerWriterProjectionResponse>;\n private readonly documents: ProjectionSlots<DocumentWriterProjectionResponse>;\n\n constructor(private readonly context: ApiClientContext) {\n bindPrototypeMethods(this, WriterProjectionArea.prototype);\n this.containers = {\n cache: context.containerWriterProjectionRequestsByContainerId,\n inFlightResults:\n context.containerWriterProjectionResultsInFlightByContainerId,\n };\n this.documents = {\n cache: context.documentWriterProjectionRequestsByDocumentId,\n inFlightResults:\n context.documentWriterProjectionResultsInFlightByDocumentId,\n };\n }\n\n // Shared by the writer-projection result variants: coalesce concurrent\n // result callers onto one in-flight fetch, reuse a cached success, fetch a\n // result otherwise, and reconcile the cache without ever clobbering an entry\n // that changed while the fetch was in flight.\n private writerProjectionResult<T>(\n { cache, inFlightResults }: ProjectionSlots<T>,\n read: ProjectionRead<T>,\n options: RequestResultOptions,\n ): Promise<RequestResult<T>> {\n const { cacheKey, path, validator, failureOperation } = read;\n // Request-affecting options make the response caller-specific: run the\n // request directly with the caller's options, join no shared fetch, and\n // never publish the outcome to the shared caches. Only reporting-only\n // callers below participate in coalescing and cache warming.\n if (\n options.headers !== undefined ||\n options.retryOnSessionExpired !== undefined\n ) {\n return this.context.requestResult(\n path,\n validator,\n \"GET\",\n undefined,\n options,\n failureOperation,\n );\n }\n\n // A concurrent burst shares one fetch — failure included — so it cannot\n // repeat the HTTP request or the 402 billing signal. The entry lives only\n // while the fetch is in flight: failures are shared, never cached, so a\n // later retry refetches. An in-flight fetch is joinable only while the\n // value slot and per-key invalidation stamp it started against are\n // unchanged: a prime, a completed plain GET, or an eviction of THIS id\n // that lands mid-flight makes the older fetch unadoptable, so a later\n // caller reads the current cache state (or fetches fresh) instead of\n // joining a fetch that predates it — while invalidations of other ids\n // leave the coalescing intact. Eviction and priming also delete the\n // entry outright; the identity guard keeps a late settle from deleting a\n // successor's entry.\n //\n // The shared fetch itself is always silent; each caller applies its OWN\n // reporting policy to the shared outcome below. Coalescing therefore\n // never lets one caller's reportErrors suppress (or force) another's,\n // and caller options never reach the request — the fetch takes none.\n const slot = cache.get(cacheKey);\n const invalidationStamp = cache.invalidationStamp(cacheKey);\n const inFlight = inFlightResults.get(cacheKey);\n let shared: Promise<RequestResult<T>>;\n if (\n inFlight &&\n inFlight.slot === slot &&\n inFlight.invalidationStamp === invalidationStamp\n ) {\n shared = inFlight.resultPromise;\n } else {\n const entry: InFlightWriterProjectionResult<T> = {\n invalidationStamp,\n resultPromise: this.fetchWriterProjectionResult(cache, read).finally(\n () => {\n if (inFlightResults.get(cacheKey) === entry) {\n inFlightResults.delete(cacheKey);\n }\n },\n ),\n slot,\n };\n inFlightResults.set(cacheKey, entry);\n shared = entry.resultPromise;\n }\n\n if (options.reportErrors === false) {\n return shared;\n }\n return shared.then((result) => {\n if (!result.ok) {\n result.report();\n }\n return result;\n });\n }\n\n // The fetch half of writerProjectionResult. Cache reconciliation guards\n // against both mid-flight slot replacement (identity comparison) and\n // mid-flight eviction of an empty slot (the per-key invalidation stamp),\n // so a projection an eviction (e.g. after a revoke) meant to drop is never\n // re-cached.\n private async fetchWriterProjectionResult<T>(\n cache: BoundedCache<Promise<T | null>>,\n { cacheKey, path, validator, failureOperation }: ProjectionRead<T>,\n ): Promise<RequestResult<T>> {\n let cached = cache.get(cacheKey);\n while (cached) {\n try {\n const data = await cached;\n if (data) {\n return { data, ok: true };\n }\n } catch {\n // A rejected shared entry is reconciled by its own settle handler;\n // fall through either way.\n }\n // The awaited entry settled empty. Re-read the slot before fetching: a\n // newer entry installed while we awaited must be reused, not fetched\n // over — the set below would otherwise clobber it.\n const current = cache.get(cacheKey);\n if (current === cached) {\n break;\n }\n cached = current;\n }\n\n // The plain value cache never sees this fetch while it is in flight: a\n // published always-silent entry would hand a concurrent PLAIN caller a\n // null without its normal error reporting. Plain callers keep their own\n // fetch-and-report behavior instead, and only a success is published.\n // Always silent here: reporting is per-caller in writerProjectionResult,\n // and taking no caller options is what guarantees nothing\n // request-affecting can be smuggled into the shared fetch.\n const invalidationStamp = cache.invalidationStamp(cacheKey);\n const result = await this.context.requestResult(\n path,\n validator,\n \"GET\",\n undefined,\n {\n reportErrors: false,\n },\n failureOperation,\n );\n\n if (result.ok) {\n // Publish the success unless the slot changed or this id was\n // invalidated mid-flight. The stamp check is what makes an eviction of\n // THIS id visible even when the slot was empty before and after the\n // flight — the case the identity comparison alone cannot see — and it\n // never caches a projection an eviction meant to drop.\n if (\n cache.get(cacheKey) === cached &&\n cache.invalidationStamp(cacheKey) === invalidationStamp\n ) {\n cache.set(cacheKey, Promise.resolve(result.data));\n }\n } else if (cached && cache.get(cacheKey) === cached) {\n // The adopted entry settled empty and the fetch confirmed there is\n // nothing to serve: drop it so a later read refetches.\n cache.delete(cacheKey);\n }\n\n return result;\n }\n\n /** `listing` only picks which held bytes an unstored container cites. */\n getContainerWriterProjection(\n containerId: string,\n listing?: WriterProjectionListing,\n ) {\n return cachedRequest(this.containers.cache, containerId, () =>\n this.context.request(\n containerWriterProjection.path(containerId),\n containerWriterProjection.isResponseFor(containerId),\n containerWriterProjection.method,\n undefined,\n listing ? { projectionListing: listing } : undefined,\n getContainerWriterProjectionOperation,\n ),\n );\n }\n\n getContainerWriterProjectionResult(\n containerId: string,\n options: RequestResultOptions = {},\n ): Promise<RequestResult<ContainerWriterProjectionResponse>> {\n return this.writerProjectionResult(\n this.containers,\n {\n cacheKey: containerId,\n path: containerWriterProjection.path(containerId),\n validator: containerWriterProjection.isResponseFor(containerId),\n failureOperation: getContainerWriterProjectionOperation,\n },\n options,\n );\n }\n\n getDocumentWriterProjection(documentId: string) {\n return cachedRequest(this.documents.cache, documentId, () =>\n this.context.request(\n documentWriterProjection.path(documentId),\n documentWriterProjection.isResponseFor(documentId),\n documentWriterProjection.method,\n undefined,\n undefined,\n getDocumentWriterProjectionOperation,\n ),\n );\n }\n\n getDocumentWriterProjectionResult(\n documentId: string,\n options: RequestResultOptions = {},\n ): Promise<RequestResult<DocumentWriterProjectionResponse>> {\n return this.writerProjectionResult(\n this.documents,\n {\n cacheKey: documentId,\n path: documentWriterProjection.path(documentId),\n validator: documentWriterProjection.isResponseFor(documentId),\n failureOperation: getDocumentWriterProjectionOperation,\n },\n options,\n );\n }\n\n /**\n * Seed the writer-projection cache from a mutation response the client just\n * authored, so the next read resolves locally instead of a cold\n * `GET /documents/:documentId/writer-projection`. The seed is the same\n * material a fresh fetch returns (create/link/sync responses carry the\n * manifest, content-key bundle, and KEK targets; authorizing paths are the\n * projection the client supplied). No-op when a fetch is in flight or the\n * slot is primed — never clobber an existing entry. The existing invalidation\n * paths (sync-change, share/rekey/move, link/unlink) evict a primed\n * projection that later goes stale, exactly as they evict a fetched one.\n */\n primeDocumentWriterProjection(\n documentId: string,\n projection: DocumentWriterProjectionResponse,\n ): void {\n primeWriterProjectionSlot({\n cache: this.documents.cache,\n describes: documentWriterProjection.isResponseFor(documentId),\n id: documentId,\n inFlightResults: this.documents.inFlightResults,\n label: \"Document\",\n projection,\n });\n }\n\n /**\n * Container counterpart of {@link primeDocumentWriterProjection}: seed the\n * container writer-projection cache from a create the client just authored so\n * the next write under that container (a child folder, a document) resolves\n * locally instead of a cold `GET /containers/:containerId/writer-projection`.\n * The seed is the same material a fresh fetch returns — the create plan's\n * authorizing path and container KEKs — validated by the caller against the\n * create response before priming. No-op when a fetch is in flight or the slot\n * is already primed, so it never clobbers a newer entry. The existing\n * invalidation (share/revoke/rekey/move/delete -> clearWriterProjectionCaches)\n * evicts a primed projection that later goes stale exactly as it evicts a\n * fetched one, so a subsequent write on stale access still fails closed and\n * retries with a fresh projection.\n */\n primeContainerWriterProjection(\n containerId: string,\n projection: ContainerWriterProjectionResponse,\n ): void {\n primeWriterProjectionSlot({\n cache: this.containers.cache,\n describes: containerWriterProjection.isResponseFor(containerId),\n id: containerId,\n inFlightResults: this.containers.inFlightResults,\n label: \"Container\",\n projection,\n });\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"writerProjections.js","sourceRoot":"","sources":["writerProjections.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,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AI,CAAC,SAAS,CAAC,eAAe;YAC/C,KAAK,EAAE,UAAU;YACjB,UAAU;SACX,CAAC,CAAC;IACL,CAAC;IAED;;;;;;;;;;;;;OAaG;IACH,8BAA8B,CAC5B,WAAmB,EACnB,UAA6C;QAE7C,yBAAyB,CAAC;YACxB,KAAK,EAAE,IAAI,CAAC,UAAU,CAAC,KAAK;YAC5B,SAAS,EAAE,yBAAyB,CAAC,aAAa,CAAC,WAAW,CAAC;YAC/D,EAAE,EAAE,WAAW;YACf,eAAe,EAAE,IAAI,CAAC,UAAU,CAAC,eAAe;YAChD,KAAK,EAAE,WAAW;YAClB,UAAU;SACX,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import {\n getContainerWriterProjectionOperation,\n getDocumentWriterProjectionOperation,\n type HttpOperation,\n} from \"@tearleads/validators/operation\";\nimport type {\n ContainerWriterProjectionResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport type { BoundedCache } from \"../ApiCache\";\nimport { bindPrototypeMethods, cachedRequest } from \"../requestInternals\";\nimport {\n containerWriterProjection,\n documentWriterProjection,\n} from \"../routes/writerProjections\";\nimport { retiredRequest } from \"../sessionResponse\";\nimport type { RequestResult, RequestResultOptions } from \"../types\";\nimport type { WriterProjectionListing } from \"../verifiedManifestCitations\";\nimport { primeWriterProjectionSlot } from \"../writerProjectionPrime\";\nimport type {\n ApiClientContext,\n InFlightWriterProjectionResult,\n} from \"./apiClientContext\";\n\ninterface ProjectionSlots<T> {\n readonly cache: BoundedCache<Promise<T | null>>;\n readonly inFlightResults: Map<string, InFlightWriterProjectionResult<T>>;\n}\n\ninterface ProjectionRead<T> {\n readonly cacheKey: string;\n readonly path: string;\n readonly validator: (value: unknown) => value is T;\n readonly failureOperation: HttpOperation;\n}\n\n/**\n * Container and document writer projections: plain cached reads, coalesced\n * status-bearing reads, and primes from just-authored mutation material.\n */\nexport class WriterProjectionArea {\n private readonly containers: ProjectionSlots<ContainerWriterProjectionResponse>;\n private readonly documents: ProjectionSlots<DocumentWriterProjectionResponse>;\n\n constructor(private readonly context: ApiClientContext) {\n bindPrototypeMethods(this, WriterProjectionArea.prototype);\n this.containers = {\n cache: context.containerWriterProjectionRequestsByContainerId,\n inFlightResults:\n context.containerWriterProjectionResultsInFlightByContainerId,\n };\n this.documents = {\n cache: context.documentWriterProjectionRequestsByDocumentId,\n inFlightResults:\n context.documentWriterProjectionResultsInFlightByDocumentId,\n };\n }\n\n // Shared by the writer-projection result variants: coalesce concurrent\n // result callers onto one in-flight fetch, reuse a cached success, fetch a\n // result otherwise, and reconcile the cache without ever clobbering an entry\n // that changed while the fetch was in flight.\n private writerProjectionResult<T>(\n { cache, inFlightResults }: ProjectionSlots<T>,\n read: ProjectionRead<T>,\n options: RequestResultOptions,\n ): Promise<RequestResult<T>> {\n const { cacheKey, path, validator, failureOperation } = read;\n // Request-affecting options make the response caller-specific: run the\n // request directly with the caller's options, join no shared fetch, and\n // never publish the outcome to the shared caches. Only reporting-only\n // callers below participate in coalescing and cache warming.\n if (\n options.headers !== undefined ||\n options.retryOnSessionExpired !== undefined\n ) {\n return this.context.requestResult(\n path,\n validator,\n \"GET\",\n undefined,\n options,\n failureOperation,\n );\n }\n\n // A concurrent burst shares one fetch — failure included — so it cannot\n // repeat the HTTP request or the 402 billing signal. The entry lives only\n // while the fetch is in flight: failures are shared, never cached, so a\n // later retry refetches. An in-flight fetch is joinable only while the\n // value slot and per-key invalidation stamp it started against are\n // unchanged: a prime, a completed plain GET, or an eviction of THIS id\n // that lands mid-flight makes the older fetch unadoptable, so a later\n // caller reads the current cache state (or fetches fresh) instead of\n // joining a fetch that predates it — while invalidations of other ids\n // leave the coalescing intact. Eviction and priming also delete the\n // entry outright; the identity guard keeps a late settle from deleting a\n // successor's entry.\n //\n // The shared fetch itself is always silent; each caller applies its OWN\n // reporting policy to the shared outcome below. Coalescing therefore\n // never lets one caller's reportErrors suppress (or force) another's,\n // and caller options never reach the request — the fetch takes none.\n const slot = cache.get(cacheKey);\n const invalidationStamp = cache.invalidationStamp(cacheKey);\n const inFlight = inFlightResults.get(cacheKey);\n let shared: Promise<RequestResult<T>>;\n if (\n inFlight &&\n inFlight.slot === slot &&\n inFlight.invalidationStamp === invalidationStamp\n ) {\n shared = inFlight.resultPromise;\n } else {\n const entry: InFlightWriterProjectionResult<T> = {\n invalidationStamp,\n resultPromise: this.fetchWriterProjectionResult(cache, read).finally(\n () => {\n if (inFlightResults.get(cacheKey) === entry) {\n inFlightResults.delete(cacheKey);\n }\n },\n ),\n slot,\n };\n inFlightResults.set(cacheKey, entry);\n shared = entry.resultPromise;\n }\n\n if (options.reportErrors === false) {\n return shared;\n }\n return shared.then((result) => {\n if (!result.ok) {\n result.report();\n }\n return result;\n });\n }\n\n // The fetch half of writerProjectionResult. Cache reconciliation guards\n // against both mid-flight slot replacement (identity comparison) and\n // mid-flight eviction of an empty slot (the per-key invalidation stamp),\n // so a projection an eviction (e.g. after a revoke) meant to drop is never\n // re-cached.\n private async fetchWriterProjectionResult<T>(\n cache: BoundedCache<Promise<T | null>>,\n { cacheKey, path, validator, failureOperation }: ProjectionRead<T>,\n ): Promise<RequestResult<T>> {\n const session = this.context.runtime.responseRequest.sessionSignal?.();\n const retired = () => retiredRequest(\"GET\", path);\n let cached = cache.get(cacheKey);\n while (cached) {\n // Rejected and empty entries both fall through to the current slot.\n const data = await cached.catch(() => null);\n if (session?.aborted) return retired();\n if (data) return { data, ok: true };\n // A newer entry installed during the wait must be reused.\n const current = cache.get(cacheKey);\n if (current === cached) {\n break;\n }\n cached = current;\n }\n\n // The plain value cache never sees this fetch while it is in flight: a\n // published always-silent entry would hand a concurrent PLAIN caller a\n // null without its normal error reporting. Plain callers keep their own\n // fetch-and-report behavior instead, and only a success is published.\n // Always silent here: reporting is per-caller in writerProjectionResult,\n // and taking no caller options is what guarantees nothing\n // request-affecting can be smuggled into the shared fetch.\n const invalidationStamp = cache.invalidationStamp(cacheKey);\n const result = await this.context.requestResult(\n path,\n validator,\n \"GET\",\n undefined,\n {\n reportErrors: false,\n },\n failureOperation,\n );\n\n if (session?.aborted) return retired();\n if (result.ok) {\n // Publish the success unless the slot changed or this id was\n // invalidated mid-flight. The stamp check is what makes an eviction of\n // THIS id visible even when the slot was empty before and after the\n // flight — the case the identity comparison alone cannot see — and it\n // never caches a projection an eviction meant to drop.\n if (\n cache.get(cacheKey) === cached &&\n cache.invalidationStamp(cacheKey) === invalidationStamp\n ) {\n cache.set(cacheKey, Promise.resolve(result.data));\n }\n } else if (cached && cache.get(cacheKey) === cached) {\n // The adopted entry settled empty and the fetch confirmed there is\n // nothing to serve: drop it so a later read refetches.\n cache.delete(cacheKey);\n }\n\n return result;\n }\n\n /** `listing` only picks which held bytes an unstored container cites. */\n getContainerWriterProjection(\n containerId: string,\n listing?: WriterProjectionListing,\n ) {\n return cachedRequest(this.containers.cache, containerId, () =>\n this.context.request(\n containerWriterProjection.path(containerId),\n containerWriterProjection.isResponseFor(containerId),\n containerWriterProjection.method,\n undefined,\n listing ? { projectionListing: listing } : undefined,\n getContainerWriterProjectionOperation,\n ),\n );\n }\n\n getContainerWriterProjectionResult(\n containerId: string,\n options: RequestResultOptions = {},\n ): Promise<RequestResult<ContainerWriterProjectionResponse>> {\n return this.writerProjectionResult(\n this.containers,\n {\n cacheKey: containerId,\n path: containerWriterProjection.path(containerId),\n validator: containerWriterProjection.isResponseFor(containerId),\n failureOperation: getContainerWriterProjectionOperation,\n },\n options,\n );\n }\n\n getDocumentWriterProjection(documentId: string) {\n return cachedRequest(this.documents.cache, documentId, () =>\n this.context.request(\n documentWriterProjection.path(documentId),\n documentWriterProjection.isResponseFor(documentId),\n documentWriterProjection.method,\n undefined,\n undefined,\n getDocumentWriterProjectionOperation,\n ),\n );\n }\n\n getDocumentWriterProjectionResult(\n documentId: string,\n options: RequestResultOptions = {},\n ): Promise<RequestResult<DocumentWriterProjectionResponse>> {\n return this.writerProjectionResult(\n this.documents,\n {\n cacheKey: documentId,\n path: documentWriterProjection.path(documentId),\n validator: documentWriterProjection.isResponseFor(documentId),\n failureOperation: getDocumentWriterProjectionOperation,\n },\n options,\n );\n }\n\n /**\n * Seed the writer-projection cache from a mutation response the client just\n * authored, so the next read resolves locally instead of a cold\n * `GET /documents/:documentId/writer-projection`. The seed is the same\n * material a fresh fetch returns (create/link/sync responses carry the\n * manifest, content-key bundle, and KEK targets; authorizing paths are the\n * projection the client supplied). No-op when a fetch is in flight or the\n * slot is primed — never clobber an existing entry. The existing invalidation\n * paths (sync-change, share/rekey/move, link/unlink) evict a primed\n * projection that later goes stale, exactly as they evict a fetched one.\n */\n primeDocumentWriterProjection(\n documentId: string,\n projection: DocumentWriterProjectionResponse,\n ): void {\n primeWriterProjectionSlot({\n cache: this.documents.cache,\n describes: documentWriterProjection.isResponseFor(documentId),\n id: documentId,\n inFlightResults: this.documents.inFlightResults,\n label: \"Document\",\n projection,\n });\n }\n\n /**\n * Container counterpart of {@link primeDocumentWriterProjection}: seed the\n * container writer-projection cache from a create the client just authored so\n * the next write under that container (a child folder, a document) resolves\n * locally instead of a cold `GET /containers/:containerId/writer-projection`.\n * The seed is the same material a fresh fetch returns — the create plan's\n * authorizing path and container KEKs — validated by the caller against the\n * create response before priming. No-op when a fetch is in flight or the slot\n * is already primed, so it never clobbers a newer entry. The existing\n * invalidation (share/revoke/rekey/move/delete -> clearWriterProjectionCaches)\n * evicts a primed projection that later goes stale exactly as it evicts a\n * fetched one, so a subsequent write on stale access still fails closed and\n * retries with a fresh projection.\n */\n primeContainerWriterProjection(\n containerId: string,\n projection: ContainerWriterProjectionResponse,\n ): void {\n primeWriterProjectionSlot({\n cache: this.containers.cache,\n describes: containerWriterProjection.isResponseFor(containerId),\n id: containerId,\n inFlightResults: this.containers.inFlightResults,\n label: \"Container\",\n projection,\n });\n }\n}\n"]}
|
|
@@ -35,5 +35,5 @@ export declare function decodeOperationResponseHeaders(operation: HttpOperation,
|
|
|
35
35
|
} | {
|
|
36
36
|
readonly ok: false;
|
|
37
37
|
};
|
|
38
|
-
export declare function decodeJsonOperationResponse(request: OperationResponseRequestFn, operation: JsonResponseOperation, response: Response, path: string, options: RequestResultOptions): Promise<RequestResult<RuntimeJsonOperationResponseEnvelope>>;
|
|
38
|
+
export declare function decodeJsonOperationResponse(request: OperationResponseRequestFn, operation: JsonResponseOperation, response: Response, path: string, options: RequestResultOptions, session?: AbortSignal): Promise<RequestResult<RuntimeJsonOperationResponseEnvelope>>;
|
|
39
39
|
export {};
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { operationResponseHeaderNames, } from "../validators/operation/index.js";
|
|
2
|
-
import {
|
|
3
|
-
import { responseBodyFailure } from "./responseBodyFailure.js";
|
|
2
|
+
import { readSessionJson, retiredRequest } from "./sessionResponse.js";
|
|
4
3
|
export function additionalOperationSuccessStatuses(operation) {
|
|
5
4
|
return [
|
|
6
5
|
...Object.keys(operation.responses).map(Number),
|
|
@@ -33,19 +32,9 @@ export function decodeOperationResponseHeaders(operation, response) {
|
|
|
33
32
|
const parsed = schema.safeParse(values);
|
|
34
33
|
return parsed.success ? { data: parsed.data, ok: true } : { ok: false };
|
|
35
34
|
}
|
|
36
|
-
function
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
...failure,
|
|
40
|
-
message: `${operation.method} ${path}: ${failure.message}`,
|
|
41
|
-
method: operation.method,
|
|
42
|
-
options,
|
|
43
|
-
path,
|
|
44
|
-
status: response.status,
|
|
45
|
-
statusText: response.statusText,
|
|
46
|
-
});
|
|
47
|
-
}
|
|
48
|
-
export async function decodeJsonOperationResponse(request, operation, response, path, options) {
|
|
35
|
+
export async function decodeJsonOperationResponse(request, operation, response, path, options, session) {
|
|
36
|
+
if (session?.aborted)
|
|
37
|
+
return retiredRequest(operation.method, path);
|
|
49
38
|
const schema = operation.responses[response.status];
|
|
50
39
|
const isEmpty = operation.emptyResponseStatuses?.includes(response.status) ?? false;
|
|
51
40
|
if (!schema && !isEmpty) {
|
|
@@ -57,14 +46,12 @@ export async function decodeJsonOperationResponse(request, operation, response,
|
|
|
57
46
|
}
|
|
58
47
|
let data;
|
|
59
48
|
if (!isEmpty && schema) {
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
}
|
|
67
|
-
const parsed = schema.safeParse(value);
|
|
49
|
+
const result = await readSessionJson(request, response, operation.method, path, options, session);
|
|
50
|
+
if (session?.aborted)
|
|
51
|
+
return retiredRequest(operation.method, path);
|
|
52
|
+
if (!result.ok)
|
|
53
|
+
return result;
|
|
54
|
+
const parsed = schema.safeParse(result.data);
|
|
68
55
|
if (!parsed.success) {
|
|
69
56
|
return operationResponseFailure(request, operation, response, path, options, `Invalid response shape for ${path}`);
|
|
70
57
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"operationResponse.js","sourceRoot":"","sources":["operationResponse.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,4BAA4B,GAC7B,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"operationResponse.js","sourceRoot":"","sources":["operationResponse.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,4BAA4B,GAC7B,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAkEpE,MAAM,UAAU,kCAAkC,CAChD,SAAwB;IAExB,OAAO;QACL,GAAG,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC;QAC/C,GAAG,CAAC,SAAS,CAAC,qBAAqB,IAAI,EAAE,CAAC;KAC3C,CAAC,MAAM,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,GAAG,GAAG,IAAI,MAAM,IAAI,GAAG,CAAC,CAAC;AACtD,CAAC;AAQD,MAAM,UAAU,wBAAwB,CACtC,OAAmC,EACnC,SAAwB,EACxB,QAAkB,EAClB,IAAY,EACZ,OAA6B,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,QAAQ,EACR,IAAI,EACJ,OAAO,EACP,8BAA8B,IAAI,EAAE,CACrC,CAAC;QACJ,CAAC;QACD,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC;IACrB,CAAC;IAED,OAAO;QACL,IAAI,EAAE,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,CAAC,MAAM,EAAE;QAC9D,EAAE,EAAE,IAAI;KACT,CAAC;AACJ,CAAC","sourcesContent":["import {\n type HttpOperation,\n type OperationSchemaOutput,\n operationResponseHeaderNames,\n} from \"@tearleads/validators/operation\";\nimport { readSessionJson, retiredRequest } from \"./sessionResponse\";\nimport type {\n OperationResponseRequestFn,\n RequestResult,\n RequestResultOptions,\n} from \"./types\";\n\nexport interface JsonResponseOperation extends HttpOperation {\n readonly responseMediaTypes?: Readonly<Record<number, \"application/json\">>;\n}\n\ntype BodyResponseStatus<Operation extends JsonResponseOperation> = Extract<\n keyof Operation[\"responses\"],\n number\n>;\n\ntype EmptyResponseStatus<Operation extends JsonResponseOperation> =\n Operation extends {\n readonly emptyResponseStatuses: readonly (infer Status)[];\n }\n ? Extract<Status, number>\n : never;\n\ntype SuccessStatus<Operation extends JsonResponseOperation> =\n | BodyResponseStatus<Operation>\n | EmptyResponseStatus<Operation>;\n\ntype ResponseBodyForStatus<\n Operation extends JsonResponseOperation,\n Status extends number,\n> = Status extends keyof Operation[\"responses\"]\n ? OperationSchemaOutput<\n Extract<Operation[\"responses\"][Status], HttpOperation[\"params\"]>\n >\n : undefined;\n\nexport type OperationResponseHeadersForStatus<\n Operation extends HttpOperation,\n Status extends number,\n> = Operation extends {\n readonly responseHeaders: infer Headers extends Readonly<\n Record<number, HttpOperation[\"params\"]>\n >;\n}\n ? Status extends keyof Headers\n ? OperationSchemaOutput<Extract<Headers[Status], HttpOperation[\"params\"]>>\n : undefined\n : undefined;\n\nexport type JsonOperationResponseEnvelope<\n Operation extends JsonResponseOperation,\n> = {\n [Status in SuccessStatus<Operation>]: {\n readonly data: ResponseBodyForStatus<Operation, Status>;\n readonly headers: OperationResponseHeadersForStatus<Operation, Status>;\n readonly status: Status;\n };\n}[SuccessStatus<Operation>];\n\nexport type JsonOperationResponse<Operation extends JsonResponseOperation> = {\n [Status in SuccessStatus<Operation>]: ResponseBodyForStatus<\n Operation,\n Status\n >;\n}[SuccessStatus<Operation>];\n\nexport function additionalOperationSuccessStatuses(\n operation: HttpOperation,\n): readonly number[] {\n return [\n ...Object.keys(operation.responses).map(Number),\n ...(operation.emptyResponseStatuses ?? []),\n ].filter((status) => status < 200 || status >= 300);\n}\n\ninterface RuntimeJsonOperationResponseEnvelope {\n readonly data: unknown;\n readonly headers: unknown;\n readonly status: number;\n}\n\nexport function operationResponseFailure(\n request: OperationResponseRequestFn,\n operation: HttpOperation,\n response: Response,\n path: string,\n options: RequestResultOptions,\n message: string,\n) {\n return request.reportFailure({\n kind: \"shape\",\n message,\n method: operation.method,\n options,\n path,\n status: response.status,\n statusText: response.statusText,\n });\n}\n\nexport function decodeOperationResponseHeaders(\n operation: HttpOperation,\n response: Response,\n): { readonly data: unknown; readonly ok: true } | { readonly ok: false } {\n const schema = operation.responseHeaders?.[response.status];\n if (!schema) {\n return { data: undefined, ok: true };\n }\n\n const values: Record<string, string> = {};\n for (const name of operationResponseHeaderNames(operation, response.status)) {\n const value = response.headers.get(name);\n if (value !== null) {\n values[name] = value;\n }\n }\n\n const parsed = schema.safeParse(values);\n return parsed.success ? { data: parsed.data, ok: true } : { ok: false };\n}\n\nexport async function decodeJsonOperationResponse(\n request: OperationResponseRequestFn,\n operation: JsonResponseOperation,\n response: Response,\n path: string,\n options: RequestResultOptions,\n session?: AbortSignal,\n): Promise<RequestResult<RuntimeJsonOperationResponseEnvelope>> {\n if (session?.aborted) return retiredRequest(operation.method, path);\n const schema = operation.responses[response.status];\n const isEmpty =\n operation.emptyResponseStatuses?.includes(response.status) ?? false;\n if (!schema && !isEmpty) {\n return operationResponseFailure(\n request,\n operation,\n response,\n path,\n options,\n `Invalid 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 let data: unknown;\n if (!isEmpty && schema) {\n const result = await readSessionJson(\n request,\n response,\n operation.method,\n path,\n options,\n session,\n );\n if (session?.aborted) return retiredRequest(operation.method, path);\n if (!result.ok) return result;\n const parsed = schema.safeParse(result.data);\n if (!parsed.success) {\n return operationResponseFailure(\n request,\n operation,\n response,\n path,\n options,\n `Invalid response shape for ${path}`,\n );\n }\n data = parsed.data;\n }\n\n return {\n data: { data, headers: headers.data, status: response.status },\n ok: true,\n };\n}\n"]}
|
|
@@ -92,11 +92,12 @@ export function createJsonOperationTransport(responseRequest) {
|
|
|
92
92
|
const derived = deriveRuntimeOperationRequest(operation, input);
|
|
93
93
|
const headers = mergeOperationRequestHeaders(derived.headers, options.headers);
|
|
94
94
|
const requestOptions = Object.keys(headers).length === 0 ? options : { ...options, headers };
|
|
95
|
+
const session = responseRequest.sessionSignal?.();
|
|
95
96
|
const result = await responseRequest(derived.path, derived.method, derived.body, requestOptions, additionalOperationSuccessStatuses(operation), operation);
|
|
96
97
|
if (!result.ok) {
|
|
97
98
|
return result;
|
|
98
99
|
}
|
|
99
|
-
return decodeJsonOperationResponse(responseRequest, operation, result.data, derived.path, options);
|
|
100
|
+
return decodeJsonOperationResponse(responseRequest, operation, result.data, derived.path, options, session);
|
|
100
101
|
}
|
|
101
102
|
async function requestResult(operation, input, options) {
|
|
102
103
|
const result = await requestResponseResult(operation, input, options);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"operationTransport.js","sourceRoot":"","sources":["operationTransport.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,4BAA4B,GAC7B,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACL,kCAAkC,EAClC,2BAA2B,GAG5B,MAAM,qBAA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AAO;QACL,KAAK,CAAC,OAAO,CAAC,SAAS,EAAE,KAAK,EAAE,OAAO;YACrC,MAAM,MAAM,GAAG,MAAM,aAAa,CAAC,SAAS,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC;YAC9D,OAAO,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC;QACxC,CAAC;QACD,aAAa;QACb,KAAK,CAAC,eAAe,CAAC,SAAS,EAAE,KAAK,EAAE,OAAO;YAC7C,MAAM,MAAM,GAAG,MAAM,qBAAqB,CAAC,SAAS,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC;YACtE,OAAO,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC;QACxC,CAAC;QACD,qBAAqB;KACtB,CAAC;AACJ,CAAC","sourcesContent":["import {\n type HttpOperation,\n type JsonOperation,\n type OperationSchemaInput,\n operationRequestPathForInput,\n} from \"@tearleads/validators/operation\";\nimport {\n additionalOperationSuccessStatuses,\n decodeJsonOperationResponse,\n type JsonOperationResponse,\n type JsonOperationResponseEnvelope,\n} from \"./operationResponse\";\nimport { requireOperationTransportSurface } from \"./operationTransportSurface\";\nimport type {\n OperationResponseRequestFn,\n RequestResult,\n RequestResultOptions,\n} from \"./types\";\n\nexport interface RuntimeOperationRequestInput {\n readonly body?: unknown;\n readonly headers?: unknown;\n readonly params: unknown;\n readonly query?: unknown;\n}\n\ntype SchemaInputProperty<Operation, Key extends \"body\" | \"headers\" | \"query\"> =\n Operation extends Record<Key, infer Schema>\n ? {\n readonly [Property in Key]: OperationSchemaInput<\n Extract<Schema, HttpOperation[\"params\"]>\n >;\n }\n : { readonly [Property in Key]?: never };\n\nexport type OperationRequestInput<Operation extends HttpOperation> = {\n readonly params: OperationSchemaInput<Operation[\"params\"]>;\n} & SchemaInputProperty<Operation, \"body\"> &\n SchemaInputProperty<Operation, \"headers\"> &\n SchemaInputProperty<Operation, \"query\">;\n\nexport type JsonOperationRequestInput<Operation extends JsonOperation> =\n OperationRequestInput<Operation>;\n\nexport type { JsonOperationResponseEnvelope } from \"./operationResponse\";\n\ninterface DerivedOperationRequestMetadata {\n readonly headers?: Record<string, string> | undefined;\n readonly method: HttpOperation[\"method\"];\n readonly path: string;\n}\n\ninterface DerivedOperationRequest extends DerivedOperationRequestMetadata {\n readonly body?: BodyInit | undefined;\n}\n\nexport interface JsonOperationTransport {\n request<Operation extends JsonOperation>(\n operation: Operation,\n input: JsonOperationRequestInput<Operation>,\n options?: RequestResultOptions,\n ): Promise<JsonOperationResponse<Operation> | null>;\n requestResult<Operation extends JsonOperation>(\n operation: Operation,\n input: JsonOperationRequestInput<Operation>,\n options?: RequestResultOptions,\n ): Promise<RequestResult<JsonOperationResponse<Operation>>>;\n requestResponse<Operation extends JsonOperation>(\n operation: Operation,\n input: JsonOperationRequestInput<Operation>,\n options?: RequestResultOptions,\n ): Promise<JsonOperationResponseEnvelope<Operation> | null>;\n requestResponseResult<Operation extends JsonOperation>(\n operation: Operation,\n input: JsonOperationRequestInput<Operation>,\n options?: RequestResultOptions,\n ): Promise<RequestResult<JsonOperationResponseEnvelope<Operation>>>;\n}\n\nfunction invalidRequest(operation: HttpOperation, component: string): never {\n throw new TypeError(`Invalid ${component} for ${operation.id}`);\n}\n\nfunction requestHeaders(\n operation: HttpOperation,\n input: RuntimeOperationRequestInput,\n): Record<string, string> | undefined {\n const supplied = input.headers;\n if (!operation.headers) {\n if (supplied !== undefined) {\n invalidRequest(operation, \"request headers\");\n }\n return undefined;\n }\n\n const parsed = operation.headers.safeParse(supplied);\n if (!parsed.success || typeof parsed.data !== \"object\" || !parsed.data) {\n invalidRequest(operation, \"request headers\");\n }\n\n const headers: Record<string, string> = {};\n for (const [name, value] of Object.entries(parsed.data)) {\n if (value === undefined) {\n continue;\n }\n if (typeof value !== \"string\") {\n invalidRequest(operation, `request header \"${name}\"`);\n }\n headers[name] = value;\n }\n return headers;\n}\n\nfunction requestBody(\n operation: HttpOperation,\n input: RuntimeOperationRequestInput,\n): string | undefined {\n const supplied = input.body;\n if (!operation.body) {\n if (supplied !== undefined) {\n invalidRequest(operation, \"request body\");\n }\n return undefined;\n }\n\n const parsed = operation.body.safeParse(supplied);\n if (!parsed.success) {\n invalidRequest(operation, \"request body\");\n }\n const encoded = JSON.stringify(parsed.data);\n if (encoded === undefined) {\n invalidRequest(operation, \"request body\");\n }\n return encoded;\n}\n\nexport function deriveJsonOperationRequest<Operation extends JsonOperation>(\n operation: Operation,\n input: JsonOperationRequestInput<Operation>,\n): DerivedOperationRequest {\n return deriveRuntimeOperationRequest(operation, input);\n}\n\nexport function deriveRuntimeOperationRequest(\n operation: HttpOperation,\n input: RuntimeOperationRequestInput,\n): DerivedOperationRequest {\n const metadata = deriveRuntimeOperationRequestMetadata(operation, input);\n const body = requestBody(operation, input);\n const headers =\n body === undefined && metadata.headers === undefined\n ? undefined\n : {\n ...(body === undefined ? {} : { \"Content-Type\": \"application/json\" }),\n ...metadata.headers,\n };\n return {\n ...metadata,\n ...(body === undefined ? {} : { body }),\n ...(headers === undefined ? {} : { headers }),\n };\n}\n\nexport function deriveRuntimeOperationRequestMetadata(\n operation: HttpOperation,\n input: RuntimeOperationRequestInput,\n): DerivedOperationRequestMetadata {\n const path = operationRequestPathForInput(\n operation,\n input.params,\n input.query,\n );\n const declaredHeaders = requestHeaders(operation, input);\n return {\n ...(declaredHeaders === undefined ? {} : { headers: declaredHeaders }),\n method: operation.method,\n path,\n };\n}\n\nexport function mergeOperationRequestHeaders(\n derived: Record<string, string> | undefined,\n overrides: Record<string, string> | undefined,\n): Record<string, string> {\n const merged = { ...derived };\n for (const [name, value] of Object.entries(overrides ?? {})) {\n const normalizedName = name.toLowerCase();\n for (const existingName of Object.keys(merged)) {\n if (existingName.toLowerCase() === normalizedName) {\n delete merged[existingName];\n }\n }\n merged[name] = value;\n }\n return merged;\n}\n\nexport function createJsonOperationTransport(\n responseRequest: OperationResponseRequestFn,\n): JsonOperationTransport {\n function requestResponseResult<Operation extends JsonOperation>(\n operation: Operation,\n input: JsonOperationRequestInput<Operation>,\n options?: RequestResultOptions,\n ): Promise<RequestResult<JsonOperationResponseEnvelope<Operation>>>;\n async function requestResponseResult(\n operation: JsonOperation,\n input: RuntimeOperationRequestInput,\n options: RequestResultOptions = {},\n ): Promise<RequestResult<unknown>> {\n requireOperationTransportSurface(operation, \"json\");\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 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 decodeJsonOperationResponse(\n responseRequest,\n operation,\n result.data,\n derived.path,\n options,\n );\n }\n\n async function requestResult<Operation extends JsonOperation>(\n operation: Operation,\n input: JsonOperationRequestInput<Operation>,\n options?: RequestResultOptions,\n ): Promise<RequestResult<JsonOperationResponse<Operation>>> {\n const result = await requestResponseResult(operation, input, options);\n return result.ok ? { data: result.data.data, ok: true } : result;\n }\n\n return {\n async request(operation, input, options) {\n const result = await requestResult(operation, input, options);\n return result.ok ? result.data : null;\n },\n requestResult,\n async requestResponse(operation, input, options) {\n const result = await requestResponseResult(operation, input, options);\n return result.ok ? result.data : null;\n },\n requestResponseResult,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"operationTransport.js","sourceRoot":"","sources":["operationTransport.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,4BAA4B,GAC7B,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACL,kCAAkC,EAClC,2BAA2B,GAG5B,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,gCAAgC,EAAE,MAAM,6BAA6B,CAAC;AAmE/E,SAAS,cAAc,CAAC,SAAwB,EAAE,SAAiB;IACjE,MAAM,IAAI,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OAAO;YACrC,MAAM,MAAM,GAAG,MAAM,aAAa,CAAC,SAAS,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC;YAC9D,OAAO,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC;QACxC,CAAC;QACD,aAAa;QACb,KAAK,CAAC,eAAe,CAAC,SAAS,EAAE,KAAK,EAAE,OAAO;YAC7C,MAAM,MAAM,GAAG,MAAM,qBAAqB,CAAC,SAAS,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC;YACtE,OAAO,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC;QACxC,CAAC;QACD,qBAAqB;KACtB,CAAC;AACJ,CAAC","sourcesContent":["import {\n type HttpOperation,\n type JsonOperation,\n type OperationSchemaInput,\n operationRequestPathForInput,\n} from \"@tearleads/validators/operation\";\nimport {\n additionalOperationSuccessStatuses,\n decodeJsonOperationResponse,\n type JsonOperationResponse,\n type JsonOperationResponseEnvelope,\n} from \"./operationResponse\";\nimport { requireOperationTransportSurface } from \"./operationTransportSurface\";\nimport type {\n OperationResponseRequestFn,\n RequestResult,\n RequestResultOptions,\n} from \"./types\";\n\nexport interface RuntimeOperationRequestInput {\n readonly body?: unknown;\n readonly headers?: unknown;\n readonly params: unknown;\n readonly query?: unknown;\n}\n\ntype SchemaInputProperty<Operation, Key extends \"body\" | \"headers\" | \"query\"> =\n Operation extends Record<Key, infer Schema>\n ? {\n readonly [Property in Key]: OperationSchemaInput<\n Extract<Schema, HttpOperation[\"params\"]>\n >;\n }\n : { readonly [Property in Key]?: never };\n\nexport type OperationRequestInput<Operation extends HttpOperation> = {\n readonly params: OperationSchemaInput<Operation[\"params\"]>;\n} & SchemaInputProperty<Operation, \"body\"> &\n SchemaInputProperty<Operation, \"headers\"> &\n SchemaInputProperty<Operation, \"query\">;\n\nexport type JsonOperationRequestInput<Operation extends JsonOperation> =\n OperationRequestInput<Operation>;\n\nexport type { JsonOperationResponseEnvelope } from \"./operationResponse\";\n\ninterface DerivedOperationRequestMetadata {\n readonly headers?: Record<string, string> | undefined;\n readonly method: HttpOperation[\"method\"];\n readonly path: string;\n}\n\ninterface DerivedOperationRequest extends DerivedOperationRequestMetadata {\n readonly body?: BodyInit | undefined;\n}\n\nexport interface JsonOperationTransport {\n request<Operation extends JsonOperation>(\n operation: Operation,\n input: JsonOperationRequestInput<Operation>,\n options?: RequestResultOptions,\n ): Promise<JsonOperationResponse<Operation> | null>;\n requestResult<Operation extends JsonOperation>(\n operation: Operation,\n input: JsonOperationRequestInput<Operation>,\n options?: RequestResultOptions,\n ): Promise<RequestResult<JsonOperationResponse<Operation>>>;\n requestResponse<Operation extends JsonOperation>(\n operation: Operation,\n input: JsonOperationRequestInput<Operation>,\n options?: RequestResultOptions,\n ): Promise<JsonOperationResponseEnvelope<Operation> | null>;\n requestResponseResult<Operation extends JsonOperation>(\n operation: Operation,\n input: JsonOperationRequestInput<Operation>,\n options?: RequestResultOptions,\n ): Promise<RequestResult<JsonOperationResponseEnvelope<Operation>>>;\n}\n\nfunction invalidRequest(operation: HttpOperation, component: string): never {\n throw new TypeError(`Invalid ${component} for ${operation.id}`);\n}\n\nfunction requestHeaders(\n operation: HttpOperation,\n input: RuntimeOperationRequestInput,\n): Record<string, string> | undefined {\n const supplied = input.headers;\n if (!operation.headers) {\n if (supplied !== undefined) {\n invalidRequest(operation, \"request headers\");\n }\n return undefined;\n }\n\n const parsed = operation.headers.safeParse(supplied);\n if (!parsed.success || typeof parsed.data !== \"object\" || !parsed.data) {\n invalidRequest(operation, \"request headers\");\n }\n\n const headers: Record<string, string> = {};\n for (const [name, value] of Object.entries(parsed.data)) {\n if (value === undefined) {\n continue;\n }\n if (typeof value !== \"string\") {\n invalidRequest(operation, `request header \"${name}\"`);\n }\n headers[name] = value;\n }\n return headers;\n}\n\nfunction requestBody(\n operation: HttpOperation,\n input: RuntimeOperationRequestInput,\n): string | undefined {\n const supplied = input.body;\n if (!operation.body) {\n if (supplied !== undefined) {\n invalidRequest(operation, \"request body\");\n }\n return undefined;\n }\n\n const parsed = operation.body.safeParse(supplied);\n if (!parsed.success) {\n invalidRequest(operation, \"request body\");\n }\n const encoded = JSON.stringify(parsed.data);\n if (encoded === undefined) {\n invalidRequest(operation, \"request body\");\n }\n return encoded;\n}\n\nexport function deriveJsonOperationRequest<Operation extends JsonOperation>(\n operation: Operation,\n input: JsonOperationRequestInput<Operation>,\n): DerivedOperationRequest {\n return deriveRuntimeOperationRequest(operation, input);\n}\n\nexport function deriveRuntimeOperationRequest(\n operation: HttpOperation,\n input: RuntimeOperationRequestInput,\n): DerivedOperationRequest {\n const metadata = deriveRuntimeOperationRequestMetadata(operation, input);\n const body = requestBody(operation, input);\n const headers =\n body === undefined && metadata.headers === undefined\n ? undefined\n : {\n ...(body === undefined ? {} : { \"Content-Type\": \"application/json\" }),\n ...metadata.headers,\n };\n return {\n ...metadata,\n ...(body === undefined ? {} : { body }),\n ...(headers === undefined ? {} : { headers }),\n };\n}\n\nexport function deriveRuntimeOperationRequestMetadata(\n operation: HttpOperation,\n input: RuntimeOperationRequestInput,\n): DerivedOperationRequestMetadata {\n const path = operationRequestPathForInput(\n operation,\n input.params,\n input.query,\n );\n const declaredHeaders = requestHeaders(operation, input);\n return {\n ...(declaredHeaders === undefined ? {} : { headers: declaredHeaders }),\n method: operation.method,\n path,\n };\n}\n\nexport function mergeOperationRequestHeaders(\n derived: Record<string, string> | undefined,\n overrides: Record<string, string> | undefined,\n): Record<string, string> {\n const merged = { ...derived };\n for (const [name, value] of Object.entries(overrides ?? {})) {\n const normalizedName = name.toLowerCase();\n for (const existingName of Object.keys(merged)) {\n if (existingName.toLowerCase() === normalizedName) {\n delete merged[existingName];\n }\n }\n merged[name] = value;\n }\n return merged;\n}\n\nexport function createJsonOperationTransport(\n responseRequest: OperationResponseRequestFn,\n): JsonOperationTransport {\n function requestResponseResult<Operation extends JsonOperation>(\n operation: Operation,\n input: JsonOperationRequestInput<Operation>,\n options?: RequestResultOptions,\n ): Promise<RequestResult<JsonOperationResponseEnvelope<Operation>>>;\n async function requestResponseResult(\n operation: JsonOperation,\n input: RuntimeOperationRequestInput,\n options: RequestResultOptions = {},\n ): Promise<RequestResult<unknown>> {\n requireOperationTransportSurface(operation, \"json\");\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 decodeJsonOperationResponse(\n responseRequest,\n operation,\n result.data,\n derived.path,\n options,\n session,\n );\n }\n\n async function requestResult<Operation extends JsonOperation>(\n operation: Operation,\n input: JsonOperationRequestInput<Operation>,\n options?: RequestResultOptions,\n ): Promise<RequestResult<JsonOperationResponse<Operation>>> {\n const result = await requestResponseResult(operation, input, options);\n return result.ok ? { data: result.data.data, ok: true } : result;\n }\n\n return {\n async request(operation, input, options) {\n const result = await requestResult(operation, input, options);\n return result.ok ? result.data : null;\n },\n requestResult,\n async requestResponse(operation, input, options) {\n const result = await requestResponseResult(operation, input, options);\n return result.ok ? result.data : null;\n },\n requestResponseResult,\n };\n}\n"]}
|
|
@@ -15,7 +15,6 @@ export async function principalHistoryRequest(runtime, input) {
|
|
|
15
15
|
while (true) {
|
|
16
16
|
if (context.cancelled())
|
|
17
17
|
return context.failure();
|
|
18
|
-
context.beforeRequest();
|
|
19
18
|
const decoded = await readResponse(runtime, context, input);
|
|
20
19
|
if (!decoded.ok && context.restartReadAfterRenewal())
|
|
21
20
|
continue;
|
|
@@ -100,25 +99,31 @@ async function readResponse(runtime, context, input) {
|
|
|
100
99
|
? deadline.options
|
|
101
100
|
: { ...deadline.options, reportErrors: false };
|
|
102
101
|
try {
|
|
103
|
-
const
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
102
|
+
const session = runtime.responseRequest.sessionSignal?.();
|
|
103
|
+
const response = await context.withCredential(options.signal, () => {
|
|
104
|
+
context.beforeRequest();
|
|
105
|
+
return runtime.responseRequest(input.path, input.method, input.body, options, [], input.operation);
|
|
106
|
+
});
|
|
107
|
+
if (!response)
|
|
108
|
+
return interruptedFailure(context, deadline, undefined);
|
|
109
|
+
if (!response.ok) {
|
|
110
|
+
// Authentication rejection precedes the workflow and remains definitive.
|
|
111
|
+
if (response.kind === "http" && response.status === 401)
|
|
112
|
+
return response;
|
|
113
|
+
return ((await context.withCredential(options.signal, () => response)) ??
|
|
114
|
+
interruptedFailure(context, deadline, undefined));
|
|
115
|
+
}
|
|
116
|
+
const body = response.data;
|
|
117
|
+
const decoded = await context.withCredential(options.signal, () => decodeJsonOperationResponse(runtime.responseRequest, input.operation, body, input.path, options, session));
|
|
118
|
+
if (!decoded)
|
|
119
|
+
return interruptedFailure(context, deadline, body);
|
|
120
|
+
const result = await context.withCredential(options.signal, () => decoded.ok
|
|
121
|
+
? {
|
|
122
|
+
ok: true,
|
|
123
|
+
data: { ...decoded.data, statusText: body.statusText },
|
|
124
|
+
}
|
|
125
|
+
: decoded);
|
|
126
|
+
return result ?? interruptedFailure(context, deadline, body);
|
|
122
127
|
}
|
|
123
128
|
finally {
|
|
124
129
|
deadline.dispose();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"principalHistoryRequest.js","sourceRoot":"","sources":["principalHistoryRequest.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,2BAA2B,EAAE,MAAM,qBAAqB,CAAC;AAClE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AQ,CAAC,CAAC,CAAC,QAAQ,CAAC,SAAS,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAC9E,QAAQ,CAAC,QAAQ,GAAG,KAAK,CAAC;IAC1B,IAAI,QAAQ,CAAC,SAAS,IAAI,CAAC;QACzB,OAAO;YACL,IAAI,EAAE,uCAAuC;YAC7C,IAAI,EAAE,MAAM;YACZ,OAAO,EAAE,4DAA4D;SACtE,CAAC;IACJ,4EAA4E;IAC5E,MAAM,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,EAAE,CAClC,UAAU,CAAC,OAAO,EAAE,QAAQ,CAAC,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CACnD,CAAC;IACF,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import type { JsonOperation } from \"@tearleads/validators/operation\";\nimport type { ApiRequestRuntime } from \"./apiRequestRuntime\";\nimport { decodeJsonOperationResponse } from \"./operationResponse\";\nimport { PrincipalHistoryRequestContext } from \"./principalHistoryRequestContext\";\nimport { requestDeadline } from \"./requestDeadline\";\nimport type {\n HttpMethod,\n RequestFailure,\n RequestResult,\n RequestResultOptions,\n} from \"./types\";\n\nconst PRINCIPAL_HISTORY_READ_TIMEOUT_MS = 15_000;\n\nfunction requestContext(\n runtime: ApiRequestRuntime,\n input: {\n readonly path: string;\n readonly method: HttpMethod;\n readonly options?: RequestResultOptions;\n readonly context?: PrincipalHistoryRequestContext;\n },\n): PrincipalHistoryRequestContext {\n return (\n input.context ??\n new PrincipalHistoryRequestContext(\n runtime,\n input.method,\n input.path,\n input.options,\n )\n );\n}\n\n/** Retry only an explicit, validated response proving the operation rolled back. */\nexport async function principalHistoryRequest<T>(\n runtime: ApiRequestRuntime,\n input: {\n readonly path: string;\n readonly validator: (value: unknown) => value is T;\n /** Maps a schema-valid 200 body to the value the validator checks. */\n readonly decode?: (value: unknown) => unknown;\n readonly method: HttpMethod;\n readonly body?: string;\n readonly options?: RequestResultOptions;\n readonly operation: JsonOperation;\n readonly context?: PrincipalHistoryRequestContext;\n readonly requestTimeoutMs?: number;\n },\n): Promise<RequestResult<T>> {\n const { path, method } = input;\n const context = requestContext(runtime, input);\n const options = context.options;\n const progress: PreparationProgress = { previous: undefined, unchanged: 0 };\n while (true) {\n if (context.cancelled()) return context.failure();\n context.beforeRequest();\n const decoded = await readResponse(runtime, context, input);\n if (!decoded.ok && context.restartReadAfterRenewal()) continue;\n if (!decoded.ok) return preserveCommitUncertainty(method, context, decoded);\n if (decoded.data.status === 202) {\n context.afterPreparation();\n const failure = await continuePreparation(decoded.data.data, progress);\n if (failure)\n return runtime.responseRequest.reportFailure({\n ...failure,\n method,\n options,\n path,\n status: 202,\n statusText: decoded.data.statusText,\n });\n continue;\n }\n const valid = validatedSuccess(decoded.data, input);\n return valid\n ? { ok: true, data: valid.data }\n : invalidResponseFailure(runtime, context, input, decoded.data);\n }\n}\n\nfunction invalidResponseFailure(\n runtime: ApiRequestRuntime,\n context: PrincipalHistoryRequestContext,\n input: { readonly path: string; readonly method: HttpMethod },\n response: { readonly status: number; readonly statusText: string },\n): RequestFailure {\n const { path, method } = input;\n const options = context.options;\n const failure = runtime.responseRequest.reportFailure({\n kind: \"shape\",\n message: `Invalid principal policy response for ${path}`,\n method,\n options: method === \"GET\" ? options : { ...options, reportErrors: false },\n path,\n status: response.status,\n statusText: response.statusText,\n });\n return preserveCommitUncertainty(method, context, failure);\n}\n\nfunction decodeSuccess(\n response: { readonly data: unknown; readonly status: number },\n decode: ((value: unknown) => unknown) | undefined,\n): unknown {\n return response.status === 200 && decode\n ? decode(response.data)\n : response.data;\n}\n\nfunction validatedSuccess<T>(\n response: { readonly data: unknown; readonly status: number },\n input: {\n readonly validator: (value: unknown) => value is T;\n readonly decode?: (value: unknown) => unknown;\n },\n): { readonly data: T } | null {\n const data = decodeSuccess(response, input.decode);\n return response.status === 200 && input.validator(data) ? { data } : null;\n}\n\nfunction preserveCommitUncertainty(\n method: HttpMethod,\n context: PrincipalHistoryRequestContext,\n failure: RequestFailure,\n): RequestFailure {\n if (method === \"GET\") return failure;\n // A network/decode failure or intermediary 5xx says nothing about commit.\n // Inner write errors are silent until this final classification is known.\n const ambiguous =\n failure.kind !== \"http\" ||\n ((failure.status ?? 0) >= 500 &&\n // The declared 503 schema requires the exact code and committed:false.\n // Unvalidated codes never reach RequestFailure.code.\n !(\n failure.status === 503 &&\n failure.code === \"principal_history_preparation_unavailable\"\n )) ||\n failure.status === 408 ||\n failure.status === 499;\n const result =\n ambiguous && failure.kind !== \"outcome-unknown\"\n ? context.failure()\n : failure;\n if (\n context.options.reportErrors !== false &&\n (result.kind === \"http\" || !context.cancelled())\n )\n result.report();\n return result;\n}\n\n/** A cancelled request is not a timeout, even if its deadline also passed. */\nfunction interruptedFailure(\n context: PrincipalHistoryRequestContext,\n deadline: { readonly expired: () => boolean },\n response: Response | undefined,\n): RequestFailure {\n return context.failure(response, deadline.expired() && !context.cancelled());\n}\n\nasync function readResponse(\n runtime: ApiRequestRuntime,\n context: PrincipalHistoryRequestContext,\n input: {\n readonly path: string;\n readonly method: HttpMethod;\n readonly body?: string;\n readonly operation: JsonOperation;\n readonly requestTimeoutMs?: number;\n },\n) {\n // A fresh timer per response, so preparation continuations reset it.\n const deadline = requestDeadline(\n context.options,\n // Writes await acknowledgement unless the caller supplies a deadline.\n // Aborting a committed write cannot be repaired by the continuation loop.\n input.requestTimeoutMs ??\n (input.method === \"GET\" ? PRINCIPAL_HISTORY_READ_TIMEOUT_MS : null),\n );\n const options =\n input.method === \"GET\"\n ? deadline.options\n : { ...deadline.options, reportErrors: false };\n try {\n const response = await runtime.responseRequest(\n input.path,\n input.method,\n input.body,\n options,\n [],\n input.operation,\n );\n // Authentication rejection precedes the workflow, so renewal does not make\n // this write's outcome uncertain. Reads may restart after a known renewal.\n if (!response.ok && response.kind === \"http\" && response.status === 401)\n return response;\n // An expired write remains uncertain even if a failure status arrived.\n if (context.cancelled() || deadline.expired())\n return interruptedFailure(\n context,\n deadline,\n response.ok ? response.data : undefined,\n );\n if (!response.ok) return response;\n const decoded = await decodeJsonOperationResponse(\n runtime.responseRequest,\n input.operation,\n response.data,\n input.path,\n options,\n );\n if (context.cancelled() || deadline.expired())\n return interruptedFailure(context, deadline, response.data);\n if (!decoded.ok) return decoded;\n return {\n ok: true as const,\n data: { ...decoded.data, statusText: response.data.statusText },\n };\n } finally {\n deadline.dispose();\n }\n}\n\ninterface PreparationProgress {\n previous: string | undefined;\n unchanged: number;\n}\n\nasync function continuePreparation(\n data: unknown,\n progress: PreparationProgress,\n): Promise<{\n readonly kind: \"shape\" | \"http\";\n readonly message: string;\n readonly code?: string;\n} | null> {\n const token =\n typeof data === \"object\" &&\n data !== null &&\n \"progressToken\" in data &&\n typeof data.progressToken === \"string\"\n ? data.progressToken\n : undefined;\n if (token === undefined)\n return {\n kind: \"shape\",\n message: \"Principal preparation progress is missing\",\n };\n progress.unchanged = token === progress.previous ? progress.unchanged + 1 : 0;\n progress.previous = token;\n if (progress.unchanged >= 2)\n return {\n code: \"principal_history_preparation_stalled\",\n kind: \"http\",\n message: \"Principal history preparation did not advance; retry later\",\n };\n // The next round checks cancellation and identity again before any request.\n await new Promise<void>((resolve) =>\n setTimeout(resolve, progress.unchanged ? 250 : 25),\n );\n return null;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"principalHistoryRequest.js","sourceRoot":"","sources":["principalHistoryRequest.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,2BAA2B,EAAE,MAAM,qBAAqB,CAAC;AAClE,OAAO,EAAE,8BAA8B,EAAE,MAAM,kCAAkC,CAAC;AAClF,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAQpD,MAAM,iCAAiC,GAAG,MAAM,CAAC;AAEjD,SAAS,cAAc,CACrB,OAA0B,EAC1B,KAKC;IAED,OAAO,CACL,KAAK,CAAC,OAAO;QACb,IAAI,8BAA8B,CAChC,OAAO,EACP,KAAK,CAAC,MAAM,EACZ,KAA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,IAAI,EAAE,OAAO;YACb,OAAO,EAAE,2CAA2C;SACrD,CAAC;IACJ,QAAQ,CAAC,SAAS,GAAG,KAAK,KAAK,QAAQ,CAAC,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,SAAS,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAC9E,QAAQ,CAAC,QAAQ,GAAG,KAAK,CAAC;IAC1B,IAAI,QAAQ,CAAC,SAAS,IAAI,CAAC;QACzB,OAAO;YACL,IAAI,EAAE,uCAAuC;YAC7C,IAAI,EAAE,MAAM;YACZ,OAAO,EAAE,4DAA4D;SACtE,CAAC;IACJ,4EAA4E;IAC5E,MAAM,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,EAAE,CAClC,UAAU,CAAC,OAAO,EAAE,QAAQ,CAAC,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CACnD,CAAC;IACF,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import type { JsonOperation } from \"@tearleads/validators/operation\";\nimport type { ApiRequestRuntime } from \"./apiRequestRuntime\";\nimport { decodeJsonOperationResponse } from \"./operationResponse\";\nimport { PrincipalHistoryRequestContext } from \"./principalHistoryRequestContext\";\nimport { requestDeadline } from \"./requestDeadline\";\nimport type {\n HttpMethod,\n RequestFailure,\n RequestResult,\n RequestResultOptions,\n} from \"./types\";\n\nconst PRINCIPAL_HISTORY_READ_TIMEOUT_MS = 15_000;\n\nfunction requestContext(\n runtime: ApiRequestRuntime,\n input: {\n readonly path: string;\n readonly method: HttpMethod;\n readonly options?: RequestResultOptions;\n readonly context?: PrincipalHistoryRequestContext;\n },\n): PrincipalHistoryRequestContext {\n return (\n input.context ??\n new PrincipalHistoryRequestContext(\n runtime,\n input.method,\n input.path,\n input.options,\n )\n );\n}\n\n/** Retry only an explicit, validated response proving the operation rolled back. */\nexport async function principalHistoryRequest<T>(\n runtime: ApiRequestRuntime,\n input: {\n readonly path: string;\n readonly validator: (value: unknown) => value is T;\n /** Maps a schema-valid 200 body to the value the validator checks. */\n readonly decode?: (value: unknown) => unknown;\n readonly method: HttpMethod;\n readonly body?: string;\n readonly options?: RequestResultOptions;\n readonly operation: JsonOperation;\n readonly context?: PrincipalHistoryRequestContext;\n readonly requestTimeoutMs?: number;\n },\n): Promise<RequestResult<T>> {\n const { path, method } = input;\n const context = requestContext(runtime, input);\n const options = context.options;\n const progress: PreparationProgress = { previous: undefined, unchanged: 0 };\n while (true) {\n if (context.cancelled()) return context.failure();\n const decoded = await readResponse(runtime, context, input);\n if (!decoded.ok && context.restartReadAfterRenewal()) continue;\n if (!decoded.ok) return preserveCommitUncertainty(method, context, decoded);\n if (decoded.data.status === 202) {\n context.afterPreparation();\n const failure = await continuePreparation(decoded.data.data, progress);\n if (failure)\n return runtime.responseRequest.reportFailure({\n ...failure,\n method,\n options,\n path,\n status: 202,\n statusText: decoded.data.statusText,\n });\n continue;\n }\n const valid = validatedSuccess(decoded.data, input);\n return valid\n ? { ok: true, data: valid.data }\n : invalidResponseFailure(runtime, context, input, decoded.data);\n }\n}\n\nfunction invalidResponseFailure(\n runtime: ApiRequestRuntime,\n context: PrincipalHistoryRequestContext,\n input: { readonly path: string; readonly method: HttpMethod },\n response: { readonly status: number; readonly statusText: string },\n): RequestFailure {\n const { path, method } = input;\n const options = context.options;\n const failure = runtime.responseRequest.reportFailure({\n kind: \"shape\",\n message: `Invalid principal policy response for ${path}`,\n method,\n options: method === \"GET\" ? options : { ...options, reportErrors: false },\n path,\n status: response.status,\n statusText: response.statusText,\n });\n return preserveCommitUncertainty(method, context, failure);\n}\n\nfunction decodeSuccess(\n response: { readonly data: unknown; readonly status: number },\n decode: ((value: unknown) => unknown) | undefined,\n): unknown {\n return response.status === 200 && decode\n ? decode(response.data)\n : response.data;\n}\n\nfunction validatedSuccess<T>(\n response: { readonly data: unknown; readonly status: number },\n input: {\n readonly validator: (value: unknown) => value is T;\n readonly decode?: (value: unknown) => unknown;\n },\n): { readonly data: T } | null {\n const data = decodeSuccess(response, input.decode);\n return response.status === 200 && input.validator(data) ? { data } : null;\n}\n\nfunction preserveCommitUncertainty(\n method: HttpMethod,\n context: PrincipalHistoryRequestContext,\n failure: RequestFailure,\n): RequestFailure {\n if (method === \"GET\") return failure;\n // A network/decode failure or intermediary 5xx says nothing about commit.\n // Inner write errors are silent until this final classification is known.\n const ambiguous =\n failure.kind !== \"http\" ||\n ((failure.status ?? 0) >= 500 &&\n // The declared 503 schema requires the exact code and committed:false.\n // Unvalidated codes never reach RequestFailure.code.\n !(\n failure.status === 503 &&\n failure.code === \"principal_history_preparation_unavailable\"\n )) ||\n failure.status === 408 ||\n failure.status === 499;\n const result =\n ambiguous && failure.kind !== \"outcome-unknown\"\n ? context.failure()\n : failure;\n if (\n context.options.reportErrors !== false &&\n (result.kind === \"http\" || !context.cancelled())\n )\n result.report();\n return result;\n}\n\n/** A cancelled request is not a timeout, even if its deadline also passed. */\nfunction interruptedFailure(\n context: PrincipalHistoryRequestContext,\n deadline: { readonly expired: () => boolean },\n response: Response | undefined,\n): RequestFailure {\n return context.failure(response, deadline.expired() && !context.cancelled());\n}\n\nasync function readResponse(\n runtime: ApiRequestRuntime,\n context: PrincipalHistoryRequestContext,\n input: {\n readonly path: string;\n readonly method: HttpMethod;\n readonly body?: string;\n readonly operation: JsonOperation;\n readonly requestTimeoutMs?: number;\n },\n) {\n // A fresh timer per response, so preparation continuations reset it.\n const deadline = requestDeadline(\n context.options,\n // Writes await acknowledgement unless the caller supplies a deadline.\n // Aborting a committed write cannot be repaired by the continuation loop.\n input.requestTimeoutMs ??\n (input.method === \"GET\" ? PRINCIPAL_HISTORY_READ_TIMEOUT_MS : null),\n );\n const options =\n input.method === \"GET\"\n ? deadline.options\n : { ...deadline.options, reportErrors: false };\n try {\n const session = runtime.responseRequest.sessionSignal?.();\n const response = await context.withCredential(options.signal, () => {\n context.beforeRequest();\n return runtime.responseRequest(\n input.path,\n input.method,\n input.body,\n options,\n [],\n input.operation,\n );\n });\n if (!response) return interruptedFailure(context, deadline, undefined);\n if (!response.ok) {\n // Authentication rejection precedes the workflow and remains definitive.\n if (response.kind === \"http\" && response.status === 401) return response;\n return (\n (await context.withCredential(options.signal, () => response)) ??\n interruptedFailure(context, deadline, undefined)\n );\n }\n const body = response.data;\n const decoded = await context.withCredential(options.signal, () =>\n decodeJsonOperationResponse(\n runtime.responseRequest,\n input.operation,\n body,\n input.path,\n options,\n session,\n ),\n );\n if (!decoded) return interruptedFailure(context, deadline, body);\n const result = await context.withCredential(options.signal, () =>\n decoded.ok\n ? {\n ok: true as const,\n data: { ...decoded.data, statusText: body.statusText },\n }\n : decoded,\n );\n return result ?? interruptedFailure(context, deadline, body);\n } finally {\n deadline.dispose();\n }\n}\n\ninterface PreparationProgress {\n previous: string | undefined;\n unchanged: number;\n}\n\nasync function continuePreparation(\n data: unknown,\n progress: PreparationProgress,\n): Promise<{\n readonly kind: \"shape\" | \"http\";\n readonly message: string;\n readonly code?: string;\n} | null> {\n const token =\n typeof data === \"object\" &&\n data !== null &&\n \"progressToken\" in data &&\n typeof data.progressToken === \"string\"\n ? data.progressToken\n : undefined;\n if (token === undefined)\n return {\n kind: \"shape\",\n message: \"Principal preparation progress is missing\",\n };\n progress.unchanged = token === progress.previous ? progress.unchanged + 1 : 0;\n progress.previous = token;\n if (progress.unchanged >= 2)\n return {\n code: \"principal_history_preparation_stalled\",\n kind: \"http\",\n message: \"Principal history preparation did not advance; retry later\",\n };\n // The next round checks cancellation and identity again before any request.\n await new Promise<void>((resolve) =>\n setTimeout(resolve, progress.unchanged ? 250 : 25),\n );\n return null;\n}\n"]}
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { renewalUnlessAborted } from "./sessionRefresh.js";
|
|
2
|
+
import { retiredRequest } from "./sessionResponse.js";
|
|
1
3
|
/** Keep continuations within their authentication context without hiding commit uncertainty. */
|
|
2
4
|
export class PrincipalHistoryRequestContext {
|
|
3
5
|
runtime;
|
|
@@ -8,9 +10,15 @@ export class PrincipalHistoryRequestContext {
|
|
|
8
10
|
submitted = false;
|
|
9
11
|
renewedRead = false;
|
|
10
12
|
restartedRead = false;
|
|
13
|
+
static captureIdentity(runtime) {
|
|
14
|
+
return {
|
|
15
|
+
credentialCurrent: runtime.captureCredential(),
|
|
16
|
+
session: runtime.responseRequest.sessionSignal?.(),
|
|
17
|
+
};
|
|
18
|
+
}
|
|
11
19
|
constructor(runtime, method, path, options,
|
|
12
20
|
// Requests of one operation share the identity they started under.
|
|
13
|
-
identity =
|
|
21
|
+
identity = PrincipalHistoryRequestContext.captureIdentity(runtime)) {
|
|
14
22
|
this.runtime = runtime;
|
|
15
23
|
this.method = method;
|
|
16
24
|
this.path = path;
|
|
@@ -20,7 +28,6 @@ export class PrincipalHistoryRequestContext {
|
|
|
20
28
|
retryOnSessionExpired: options?.retryOnSessionExpired === false ? false : "renew-only",
|
|
21
29
|
onSessionRenewed: () => {
|
|
22
30
|
if (method === "GET" && !options?.signal?.aborted) {
|
|
23
|
-
this.identity.token = runtime.getAuthToken();
|
|
24
31
|
this.renewedRead = true;
|
|
25
32
|
}
|
|
26
33
|
},
|
|
@@ -35,8 +42,22 @@ export class PrincipalHistoryRequestContext {
|
|
|
35
42
|
return new PrincipalHistoryRequestContext(this.runtime, this.method, this.path, options, this.identity);
|
|
36
43
|
}
|
|
37
44
|
cancelled() {
|
|
38
|
-
return (this.
|
|
39
|
-
this.
|
|
45
|
+
return (this.identity.session?.aborted === true ||
|
|
46
|
+
this.options.signal?.aborted === true ||
|
|
47
|
+
this.identity.credentialCurrent() === false);
|
|
48
|
+
}
|
|
49
|
+
async withCredential(signal, run) {
|
|
50
|
+
const owner = this.identity.session;
|
|
51
|
+
const cancellation = owner && signal ? AbortSignal.any([owner, signal]) : (owner ?? signal);
|
|
52
|
+
while (!cancellation?.aborted) {
|
|
53
|
+
const state = this.identity.credentialCurrent();
|
|
54
|
+
// Capture the verified bearer for dispatch in this same turn. A provisional
|
|
55
|
+
// installation must finish verification before a continuation can use it.
|
|
56
|
+
if (typeof state === "boolean")
|
|
57
|
+
return state ? run() : null;
|
|
58
|
+
await renewalUnlessAborted(state, cancellation).catch(() => false);
|
|
59
|
+
}
|
|
60
|
+
return null;
|
|
40
61
|
}
|
|
41
62
|
beforeRequest() {
|
|
42
63
|
this.submitted = this.method !== "GET";
|
|
@@ -58,7 +79,7 @@ export class PrincipalHistoryRequestContext {
|
|
|
58
79
|
}
|
|
59
80
|
failure(response, timedOut = false) {
|
|
60
81
|
void response?.body?.cancel().catch(() => { });
|
|
61
|
-
|
|
82
|
+
const failure = {
|
|
62
83
|
code: this.submitted
|
|
63
84
|
? "principal_history_outcome_unknown"
|
|
64
85
|
: timedOut
|
|
@@ -84,7 +105,10 @@ export class PrincipalHistoryRequestContext {
|
|
|
84
105
|
path: this.path,
|
|
85
106
|
status: null,
|
|
86
107
|
statusText: "",
|
|
87
|
-
}
|
|
108
|
+
};
|
|
109
|
+
return this.identity.session?.aborted
|
|
110
|
+
? { ...retiredRequest(this.method, this.path), ...failure }
|
|
111
|
+
: this.runtime.responseRequest.reportFailure(failure);
|
|
88
112
|
}
|
|
89
113
|
}
|
|
90
114
|
//# sourceMappingURL=principalHistoryRequestContext.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"principalHistoryRequestContext.js","sourceRoot":"","sources":["principalHistoryRequestContext.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"principalHistoryRequestContext.js","sourceRoot":"","sources":["principalHistoryRequestContext.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAC;AACxD,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAGnD,gGAAgG;AAChG,MAAM,OAAO,8BAA8B;IActB;IACA;IACA;IAGA;IAlBV,OAAO,CAAuB;IAC/B,SAAS,GAAG,KAAK,CAAC;IAClB,WAAW,GAAG,KAAK,CAAC;IACpB,aAAa,GAAG,KAAK,CAAC;I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,KAAK,QAAQ,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;QAC9C,MAAM,OAAO,GAAG;YACd,IAAI,EAAE,IAAI,CAAC,SAAS;gBAClB,CAAC,CAAC,mCAAmC;gBACrC,CAAC,CAAC,QAAQ;oBACR,CAAC,CAAC,qCAAqC;oBACvC,CAAC,CAAC,mCAAmC;YACzC,IAAI,EAAE,IAAI,CAAC,SAAS;gBAClB,CAAC,CAAC,iBAAiB;gBACnB,CAAC,CAAC,QAAQ;oBACR,CAAC,CAAC,SAAS;oBACX,CAAC,CAAC,WAAW;YACjB,OAAO,EAAE,IAAI,CAAC,SAAS;gBACrB,CAAC,CAAC,4DAA4D;gBAC9D,CAAC,CAAC,QAAQ;oBACR,CAAC,CAAC,qCAAqC;oBACvC,CAAC,CAAC,yCAAyC;YAC/C,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,OAAO,EAAE;gBACP,GAAG,IAAI,CAAC,OAAO;gBACf,YAAY,EACV,QAAQ;oBACR,IAAI,CAAC,MAAM,KAAK,KAAK;oBACrB,IAAI,CAAC,OAAO,CAAC,YAAY,KAAK,KAAK;aACtC;YACD,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,MAAM,EAAE,IAAI;YACZ,UAAU,EAAE,EAAE;SACN,CAAC;QACX,OAAO,IAAI,CAAC,QAAQ,CAAC,OAAO,EAAE,OAAO;YACnC,CAAC,CAAC,EAAE,GAAG,cAAc,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,IAAI,CAAC,EAAE,GAAG,OAAO,EAAE;YAC3D,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,eAAe,CAAC,aAAa,CAAC,OAAO,CAAC,CAAC;IAC1D,CAAC;CACF","sourcesContent":["import type { ApiRequestRuntime } from \"./apiRequestRuntime\";\nimport { renewalUnlessAborted } from \"./sessionRefresh\";\nimport { retiredRequest } from \"./sessionResponse\";\nimport type { HttpMethod, RequestFailure, RequestResultOptions } from \"./types\";\n\n/** Keep continuations within their authentication context without hiding commit uncertainty. */\nexport class PrincipalHistoryRequestContext {\n readonly options: RequestResultOptions;\n private submitted = false;\n private renewedRead = false;\n private restartedRead = false;\n\n static captureIdentity(runtime: ApiRequestRuntime) {\n return {\n credentialCurrent: runtime.captureCredential(),\n session: runtime.responseRequest.sessionSignal?.(),\n };\n }\n\n constructor(\n private readonly runtime: ApiRequestRuntime,\n private readonly method: HttpMethod,\n private readonly path: string,\n options: RequestResultOptions | undefined,\n // Requests of one operation share the identity they started under.\n private readonly identity = PrincipalHistoryRequestContext.captureIdentity(\n runtime,\n ),\n ) {\n this.options = {\n ...options,\n retryOnSessionExpired:\n options?.retryOnSessionExpired === false ? false : \"renew-only\",\n onSessionRenewed: () => {\n if (method === \"GET\" && !options?.signal?.aborted) {\n this.renewedRead = true;\n }\n },\n };\n }\n\n /**\n * Another request of the same operation, with its own options: an account\n * switch at any point cancels both, while a session renewal in either\n * carries over.\n */\n derive(options: RequestResultOptions): PrincipalHistoryRequestContext {\n return new PrincipalHistoryRequestContext(\n this.runtime,\n this.method,\n this.path,\n options,\n this.identity,\n );\n }\n\n cancelled(): boolean {\n return (\n this.identity.session?.aborted === true ||\n this.options.signal?.aborted === true ||\n this.identity.credentialCurrent() === false\n );\n }\n\n async withCredential<T>(\n signal: AbortSignal | undefined,\n run: () => T | Promise<T>,\n ): Promise<T | null> {\n const owner = this.identity.session;\n const cancellation =\n owner && signal ? AbortSignal.any([owner, signal]) : (owner ?? signal);\n while (!cancellation?.aborted) {\n const state = this.identity.credentialCurrent();\n // Capture the verified bearer for dispatch in this same turn. A provisional\n // installation must finish verification before a continuation can use it.\n if (typeof state === \"boolean\") return state ? run() : null;\n await renewalUnlessAborted(state, cancellation).catch(() => false);\n }\n return null;\n }\n\n beforeRequest(): void {\n this.submitted = this.method !== \"GET\";\n }\n\n afterPreparation(): void {\n this.submitted = false;\n }\n\n afterReadPage(): void {\n // A completed page is forward progress. A later page may renew again,\n // while repeated 401s within one page still cannot loop indefinitely.\n this.renewedRead = false;\n this.restartedRead = false;\n }\n\n restartReadAfterRenewal(): boolean {\n if (!this.renewedRead || this.restartedRead || this.cancelled())\n return false;\n this.restartedRead = true;\n return true;\n }\n\n failure(response?: Response, timedOut = false): RequestFailure {\n void response?.body?.cancel().catch(() => {});\n const failure = {\n code: this.submitted\n ? \"principal_history_outcome_unknown\"\n : timedOut\n ? \"principal_history_request_timed_out\"\n : \"principal_history_context_changed\",\n kind: this.submitted\n ? \"outcome-unknown\"\n : timedOut\n ? \"network\"\n : \"cancelled\",\n message: this.submitted\n ? \"Policy request may have committed; refresh before retrying\"\n : timedOut\n ? \"Principal history request timed out\"\n : \"Principal history request was cancelled\",\n method: this.method,\n options: {\n ...this.options,\n reportErrors:\n timedOut &&\n this.method === \"GET\" &&\n this.options.reportErrors !== false,\n },\n path: this.path,\n status: null,\n statusText: \"\",\n } as const;\n return this.identity.session?.aborted\n ? { ...retiredRequest(this.method, this.path), ...failure }\n : this.runtime.responseRequest.reportFailure(failure);\n }\n}\n"]}
|
|
@@ -15,7 +15,10 @@ export interface PrincipalPolicyPageReadOptions extends RequestResultOptions {
|
|
|
15
15
|
readonly resume?: PrincipalPolicyPageResume | undefined;
|
|
16
16
|
}
|
|
17
17
|
/** Pull one page at a time; the caller owns verification and durable admission. */
|
|
18
|
-
export declare function readPrincipalPolicyPages(runtime: ApiRequestRuntime, principalType: "group" | "organization", principalId: string, options: PrincipalPolicyPageReadOptions
|
|
18
|
+
export declare function readPrincipalPolicyPages(runtime: ApiRequestRuntime, principalType: "group" | "organization", principalId: string, options: PrincipalPolicyPageReadOptions, identity?: {
|
|
19
|
+
credentialCurrent: () => boolean | Promise<boolean>;
|
|
20
|
+
session: AbortSignal | undefined;
|
|
21
|
+
}): AsyncGenerator<RequestResult<PrincipalPolicyPageResponse>, void>;
|
|
19
22
|
/** A head the caller already holds and has authenticated. */
|
|
20
23
|
export interface PrincipalPolicyHeldHead {
|
|
21
24
|
readonly version: number;
|
|
@@ -96,14 +96,16 @@ function preparePrincipalPolicyRead(runtime, principalType, principalId, options
|
|
|
96
96
|
};
|
|
97
97
|
}
|
|
98
98
|
/** Pull one page at a time; the caller owns verification and durable admission. */
|
|
99
|
-
export async function* readPrincipalPolicyPages(runtime, principalType, principalId, options
|
|
99
|
+
export async function* readPrincipalPolicyPages(runtime, principalType, principalId, options,
|
|
100
|
+
// Default parameters run when the iterator is created, before its first pull.
|
|
101
|
+
identity = PrincipalHistoryRequestContext.captureIdentity(runtime)) {
|
|
100
102
|
const position = preparePrincipalPolicyRead(runtime, principalType, principalId, options);
|
|
101
103
|
if (!position.ok) {
|
|
102
104
|
yield position.failure;
|
|
103
105
|
return;
|
|
104
106
|
}
|
|
105
107
|
const { firstPath, resume } = position;
|
|
106
|
-
const context = new PrincipalHistoryRequestContext(runtime, "GET", firstPath, options);
|
|
108
|
+
const context = new PrincipalHistoryRequestContext(runtime, "GET", firstPath, options, identity);
|
|
107
109
|
let pinned = resume?.current;
|
|
108
110
|
let pinnedBytes = resume?.bytes;
|
|
109
111
|
let afterVersion = resume?.afterVersion ?? position.afterVersion;
|