@tearleads/client-sdk 0.1.251 → 0.1.252

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/Tearleads.d.ts +0 -2
  2. package/Tearleads.js +14 -25
  3. package/Tearleads.js.map +1 -1
  4. package/client/organizations/organizationReadModelPresentation.js +7 -4
  5. package/client/organizations/organizationReadModelPresentation.js.map +1 -1
  6. package/client/organizations/organizationReadModels.js +6 -5
  7. package/client/organizations/organizationReadModels.js.map +1 -1
  8. package/client/organizations/organizationWorkflowRuntime.js +1 -1
  9. package/client/organizations/organizationWorkflowRuntime.js.map +1 -1
  10. package/client/runtime/principalMutationApi.d.ts +4 -0
  11. package/client/runtime/principalMutationApi.js +9 -5
  12. package/client/runtime/principalMutationApi.js.map +1 -1
  13. package/client/runtime/runtimeIdentityResolution.js +23 -0
  14. package/client/runtime/runtimeIdentityResolution.js.map +1 -1
  15. package/client/runtime/runtimeSubscription.js +68 -0
  16. package/client/runtime/runtimeSubscription.js.map +1 -0
  17. package/client/runtime/workflowRuntime.d.ts +1 -1
  18. package/client/runtime/workflowRuntime.js +20 -77
  19. package/client/runtime/workflowRuntime.js.map +1 -1
  20. package/client/session/authenticationMachine.js +47 -0
  21. package/client/session/authenticationMachine.js.map +1 -0
  22. package/client/session/index.js +75 -93
  23. package/client/session/index.js.map +1 -1
  24. package/client/session/sessionBlobStore.js +39 -0
  25. package/client/session/sessionBlobStore.js.map +1 -0
  26. package/client/session/sessionContext.js +11 -0
  27. package/client/session/sessionContext.js.map +1 -1
  28. package/client/session/sessionIdentityTrust.d.ts +2 -1
  29. package/client/session/sessionIdentityTrust.js +8 -4
  30. package/client/session/sessionIdentityTrust.js.map +1 -1
  31. package/client/session/sessionLifetime.js +87 -0
  32. package/client/session/sessionLifetime.js.map +1 -0
  33. package/client/session/sessionLogin.js +114 -0
  34. package/client/session/sessionLogin.js.map +1 -0
  35. package/client/session/sessionOrganizationCreation.js +3 -2
  36. package/client/session/sessionOrganizationCreation.js.map +1 -1
  37. package/client/session/sessionPurgeRecovery.js +11 -3
  38. package/client/session/sessionPurgeRecovery.js.map +1 -1
  39. package/client/session/sessionTypes.d.ts +6 -2
  40. package/client/session/sessionTypes.js.map +1 -1
  41. package/data/blobs/blobContracts.d.ts +4 -3
  42. package/data/blobs/blobContracts.js.map +1 -1
  43. package/data/blobs/createBlobStore.js +1 -8
  44. package/data/blobs/createBlobStore.js.map +1 -1
  45. package/data/blobs/encryptedBlobStore.js +17 -12
  46. package/data/blobs/encryptedBlobStore.js.map +1 -1
  47. package/data/blobs/memoryBlobStore.js +8 -5
  48. package/data/blobs/memoryBlobStore.js.map +1 -1
  49. package/data/blobs/opfsBlobFile.js +36 -0
  50. package/data/blobs/opfsBlobFile.js.map +1 -0
  51. package/data/blobs/opfsBlobStore.d.ts +1 -1
  52. package/data/blobs/opfsBlobStore.js +91 -21
  53. package/data/blobs/opfsBlobStore.js.map +1 -1
  54. package/data/principals/principalPolicyCoordinator.js +8 -17
  55. package/data/principals/principalPolicyCoordinator.js.map +1 -1
  56. package/data/shared/domainScope.d.ts +2 -0
  57. package/data/shared/domainScope.js +2 -1
  58. package/data/shared/domainScope.js.map +1 -1
  59. package/data/shared/keyedQueue.js +15 -0
  60. package/data/shared/keyedQueue.js.map +1 -0
  61. package/data/sqlite/migrations/migrateLocalSchema.js +2 -3
  62. package/data/sqlite/migrations/migrateLocalSchema.js.map +1 -1
  63. package/data/sqlite/sqlExec.d.ts +6 -0
  64. package/data/sqlite/sqlExec.js +64 -13
  65. package/data/sqlite/sqlExec.js.map +1 -1
  66. package/data/sqlite/sqlitePersistenceRuntime.js +2 -3
  67. package/data/sqlite/sqlitePersistenceRuntime.js.map +1 -1
  68. package/data/trustedUserIdentity/service.js +2 -1
  69. package/data/trustedUserIdentity/service.js.map +1 -1
  70. package/data/trustedUserIdentity/types.d.ts +1 -1
  71. package/data/trustedUserIdentity/types.js.map +1 -1
  72. package/internal/api-client/ApiClient.d.ts +4 -1
  73. package/internal/api-client/apiRequestRuntime.d.ts +6 -3
  74. package/internal/api-client/apiRequestRuntime.js +86 -101
  75. package/internal/api-client/apiRequestRuntime.js.map +1 -1
  76. package/internal/api-client/binaryRequestOperationTransport.js +2 -1
  77. package/internal/api-client/binaryRequestOperationTransport.js.map +1 -1
  78. package/internal/api-client/binaryResponseOperationTransport.js +6 -2
  79. package/internal/api-client/binaryResponseOperationTransport.js.map +1 -1
  80. package/internal/api-client/client/blobs.d.ts +1 -0
  81. package/internal/api-client/client/blobs.js +12 -3
  82. package/internal/api-client/client/blobs.js.map +1 -1
  83. package/internal/api-client/client/laneListingRequest.js +4 -0
  84. package/internal/api-client/client/laneListingRequest.js.map +1 -1
  85. package/internal/api-client/client/session.d.ts +5 -1
  86. package/internal/api-client/client/session.js +12 -4
  87. package/internal/api-client/client/session.js.map +1 -1
  88. package/internal/api-client/client/writerProjections.js +12 -13
  89. package/internal/api-client/client/writerProjections.js.map +1 -1
  90. package/internal/api-client/operationResponse.d.ts +1 -1
  91. package/internal/api-client/operationResponse.js +10 -23
  92. package/internal/api-client/operationResponse.js.map +1 -1
  93. package/internal/api-client/operationTransport.js +2 -1
  94. package/internal/api-client/operationTransport.js.map +1 -1
  95. package/internal/api-client/principalHistoryRequest.js +25 -20
  96. package/internal/api-client/principalHistoryRequest.js.map +1 -1
  97. package/internal/api-client/principalHistoryRequestContext.js +30 -6
  98. package/internal/api-client/principalHistoryRequestContext.js.map +1 -1
  99. package/internal/api-client/principalPolicyPages.d.ts +4 -1
  100. package/internal/api-client/principalPolicyPages.js +4 -2
  101. package/internal/api-client/principalPolicyPages.js.map +1 -1
  102. package/internal/api-client/projectionPolicyHistoryPages.d.ts +4 -1
  103. package/internal/api-client/projectionPolicyHistoryPages.js +4 -2
  104. package/internal/api-client/projectionPolicyHistoryPages.js.map +1 -1
  105. package/internal/api-client/routes/blobs/blobDownloadBody.js +65 -0
  106. package/internal/api-client/routes/blobs/blobDownloadBody.js.map +1 -0
  107. package/internal/api-client/routes/blobs/get.js +9 -67
  108. package/internal/api-client/routes/blobs/get.js.map +1 -1
  109. package/internal/api-client/routes/blobs/multipartUpload.js +1 -1
  110. package/internal/api-client/routes/blobs/multipartUpload.js.map +1 -1
  111. package/internal/api-client/sessionRefresh.js +1 -1
  112. package/internal/api-client/sessionRefresh.js.map +1 -1
  113. package/internal/api-client/sessionRenewal.d.ts +31 -0
  114. package/internal/api-client/sessionRenewal.js +91 -6
  115. package/internal/api-client/sessionRenewal.js.map +1 -1
  116. package/internal/api-client/sessionRequestInit.js +22 -0
  117. package/internal/api-client/sessionRequestInit.js.map +1 -0
  118. package/internal/api-client/sessionResponse.js +39 -0
  119. package/internal/api-client/sessionResponse.js.map +1 -0
  120. package/internal/api-client/types.d.ts +1 -0
  121. package/internal/api-client/types.js.map +1 -1
  122. package/internal/api-client/webSocketTickets.d.ts +1 -0
  123. package/internal/api-client/webSocketTickets.js +4 -0
  124. package/internal/api-client/webSocketTickets.js.map +1 -1
  125. package/internal/sqlite-worker/client.d.ts +1 -1
  126. package/internal/sqlite-worker/client.js +6 -1
  127. package/internal/sqlite-worker/client.js.map +1 -1
  128. package/internal/sqlite-worker/purgeOpfsDatabase.d.ts +1 -1
  129. package/internal/sqlite-worker/purgeOpfsDatabase.js +3 -2
  130. package/internal/sqlite-worker/purgeOpfsDatabase.js.map +1 -1
  131. package/internal/sqlite-worker/types.d.ts +4 -0
  132. package/internal/sqlite-worker/types.js.map +1 -1
  133. package/package.json +1 -1
  134. package/sqlite/worker.js +1 -1
  135. package/workflows/documents/attachments/blobMutationLock.d.ts +1 -1
  136. package/workflows/documents/attachments/blobMutationLock.js +2 -2
  137. package/workflows/documents/attachments/blobMutationLock.js.map +1 -1
  138. package/workflows/organizations/readModel/readModelProjection.js +2 -0
  139. package/workflows/organizations/readModel/readModelProjection.js.map +1 -1
  140. package/workflows/registration/registerIdentity.js +2 -0
  141. package/workflows/registration/registerIdentity.js.map +1 -1
@@ -72,6 +72,7 @@ export declare class BlobArea {
72
72
  uploadId: string;
73
73
  } | null>;
74
74
  getBlobBytes(blobId: string, options?: RequestResultOptions): Promise<import("../index.js").BlobBytesResponse | null>;
75
+ private transfer;
75
76
  bindBlobAttachment(blobId: string, input: BlobAttachmentBindRequest, options?: RequestResultOptions): Promise<{
76
77
  bindingId: string;
77
78
  blobAccessManifestHash: string;
@@ -75,8 +75,11 @@ export class BlobArea {
75
75
  // An attachment write updates the cached listing from its response; a
76
76
  // refused or failed write leaves every listing unknown, so all are dropped.
77
77
  attachmentWrite(write, cacheResponse) {
78
+ const session = this.context.runtime.responseRequest.sessionSignal?.();
78
79
  return write
79
80
  .then((response) => {
81
+ if (session?.aborted)
82
+ return null;
80
83
  if (response) {
81
84
  cacheResponse(response);
82
85
  }
@@ -86,7 +89,8 @@ export class BlobArea {
86
89
  return response;
87
90
  })
88
91
  .catch((error) => {
89
- this.attachmentLists.clear();
92
+ if (!session?.aborted)
93
+ this.attachmentLists.clear();
90
94
  throw error;
91
95
  });
92
96
  }
@@ -97,10 +101,15 @@ export class BlobArea {
97
101
  return this.context.send(multipartGet, multipartGet.path(stageId), getMultipartBlobStageOperation);
98
102
  }
99
103
  uploadMultipartBlobPartBytes(stageId, partNumber, input, options = {}) {
100
- return uploadMultipartBlobPartBytes(this.context.transport, stageId, partNumber, input, undefined, options);
104
+ return this.transfer(options, (scoped) => uploadMultipartBlobPartBytes(this.context.transport, stageId, partNumber, input, undefined, scoped));
101
105
  }
102
106
  getBlobBytes(blobId, options = {}) {
103
- return getBlobBytes(this.context.transport, blobId, undefined, options);
107
+ return this.transfer(options, (scoped) => getBlobBytes(this.context.transport, blobId, undefined, scoped));
108
+ }
109
+ async transfer(options, run) {
110
+ const scoped = this.context.runtime.withSessionSignal(options);
111
+ const result = await run(scoped);
112
+ return scoped.signal?.aborted ? null : result;
104
113
  }
105
114
  bindBlobAttachment(blobId, input, options = {}) {
106
115
  return this.attachmentWrite(this.context.send(blobAttachmentBind, blobAttachmentBind.path(blobId), bindBlobAttachmentOperation, input, options), (response) => this.cacheBlobAttachmentBindResponse(input, response));
@@ -1 +1 @@
1
- {"version":3,"file":"blobs.js","sourceRoot":"","sources":["blobs.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,2BAA2B,EAC3B,6BAA6B,EAC7B,8BAA8B,EAC9B,mCAAmC,EACnC,gCAAgC,GACjC,MAAM,iCAAiC,CAAC;AAWzC,OAAO,EAAE,mCAAmC,EAAE,MAAM,gCAAgC,CAAC;AACrF,OAAO,EAAE,oBAAoB,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAC1E,OAAO,EACL,kBAAkB,IAAI,kBAAkB,EACxC,oBAAoB,IAAI,oBAAoB,GAC7C,MAAM,6BAA6B,CAAC;AACrC,OAAO,EACL,YAAY,GAEb,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EACL,qBAAqB,IAAI,YAAY,EACrC,0BAA0B,IAAI,iBAAiB,GAChD,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,4BAA4B,EAAE,MAAM,iCAAiC,CAAC;AAC/E,OAAO,EAAE,uBAAuB,IAAI,uBAAuB,EAAE,MAAM,iCAAiC,CAAC;AAMrG;;;GAGG;AACH,MAAM,OAAO,QAAQ;IAGU;IAFZ,eAAe,CAAiE;IAEjG,YAA6B,OAAyB;QAAzB,YAAO,GAAP,OAAO,CAAkB;QACpD,oBAAoB,CAAC,IAAI,EAAE,QAAQ,CAAC,SAAS,CAAC,CAAC;QAC/C,IAAI,CAAC,eAAe,GAAG,OAAO,CAAC,0CAA0C,CAAC;IAC5E,CAAC;IAEO,kCAAkC,CACxC,UAAkB,EAClB,MAAuD;QAEvD,MAAM,MAAM,GAAG,IAAI,CAAC,eAAe,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;QACpD,IAAI,CAAC,MAAM,EAAE,CAAC;YACZ,OAAO;QACT,CAAC;QAED,IAAI,IAAoC,CAAC;QACzC,IAAI,GAAG,MAAM;aACV,IAAI,CAA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C,IAAI,CAAC,UAAU,CAAC,EACxC,gCAAgC,CACjC,CACF,CAAC;IACJ,CAAC;CACF","sourcesContent":["import {\n bindBlobAttachmentOperation,\n detachBlobAttachmentOperation,\n getMultipartBlobStageOperation,\n initiateMultipartBlobStageOperation,\n listDocumentAttachmentsOperation,\n} from \"@tearleads/validators/operation\";\nimport type {\n BlobAttachmentBindRequest,\n BlobAttachmentDetachRequest,\n InitiateMultipartBlobStageRequest,\n} from \"@tearleads/validators/request\";\nimport type {\n BlobAttachmentBindResponse,\n BlobAttachmentDetachResponse,\n ListDocumentAttachmentsResponse,\n} from \"@tearleads/validators/response\";\nimport { blobAttachmentSummaryFromStagedBind } from \"@tearleads/validators/response\";\nimport { bindPrototypeMethods, cachedRequest } from \"../requestInternals\";\nimport {\n bindBlobAttachment as blobAttachmentBind,\n detachBlobAttachment as blobAttachmentDetach,\n} from \"../routes/blobs/attachments\";\nimport {\n getBlobBytes,\n type UploadMultipartBlobPartBytesRequest,\n} from \"../routes/blobs/get\";\nimport {\n getMultipartBlobStage as multipartGet,\n initiateMultipartBlobStage as multipartInitiate,\n} from \"../routes/blobs/multipart\";\nimport { uploadMultipartBlobPartBytes } from \"../routes/blobs/multipartUpload\";\nimport { listDocumentAttachments as documentAttachmentsList } from \"../routes/documents/attachments\";\nimport type { RequestResultOptions } from \"../types\";\nimport type { ApiClientContext } from \"./apiClientContext\";\n\ntype AttachmentList = ListDocumentAttachmentsResponse;\n\n/**\n * Multipart blob staging, blob bytes, and document attachment bindings, with\n * the per-document attachment listing cache they keep current.\n */\nexport class BlobArea {\n private readonly attachmentLists: ApiClientContext[\"documentAttachmentListRequestsByDocumentId\"];\n\n constructor(private readonly context: ApiClientContext) {\n bindPrototypeMethods(this, BlobArea.prototype);\n this.attachmentLists = context.documentAttachmentListRequestsByDocumentId;\n }\n\n private updateCachedDocumentAttachmentList(\n documentId: string,\n update: (attachments: AttachmentList) => AttachmentList,\n ): void {\n const cached = this.attachmentLists.get(documentId);\n if (!cached) {\n return;\n }\n\n let next: Promise<AttachmentList | null>;\n next = cached\n .then((attachments) => {\n if (!attachments) {\n if (this.attachmentLists.get(documentId) === next) {\n this.attachmentLists.delete(documentId);\n }\n return attachments;\n }\n\n return update(attachments);\n })\n .catch(() => {\n // The underlying list fetch failed. Drop this derived cache entry so the\n // next read refetches, and resolve to null (the cache's miss semantics)\n // rather than rethrowing: nothing awaits this derived promise directly,\n // so a rethrow would surface as an unhandled rejection. Callers already\n // awaiting the original request still observe its rejection.\n if (this.attachmentLists.get(documentId) === next) {\n this.attachmentLists.delete(documentId);\n }\n return null;\n });\n this.attachmentLists.set(documentId, next);\n }\n\n /**\n * The bind acknowledges by hash, so the cached listing entry is rebuilt\n * from the request it acknowledged: a staged upload's bind creates the blob,\n * so its one binding's KEK targets are the ones its content-key bundle wraps\n * to, and it stores exactly the signed event, bundle, and write header it\n * carried. Any other bind (no staged blob, or a target set other than the\n * one the bundle names) keeps material the response does not carry, so it\n * drops the cached listing instead.\n */\n private cacheBlobAttachmentBindResponse(\n request: BlobAttachmentBindRequest,\n response: BlobAttachmentBindResponse,\n ): void {\n const { stagedBlob } = request;\n if (\n !stagedBlob ||\n response.blobKeyTargetHash !== request.contentKeyBundle.targetHash\n ) {\n this.attachmentLists.delete(response.documentId);\n return;\n }\n const binding = blobAttachmentSummaryFromStagedBind(\n { ...request, stagedBlob },\n response,\n );\n this.updateCachedDocumentAttachmentList(\n response.documentId,\n (attachments) => [\n ...attachments.filter(\n (cachedBinding) => cachedBinding.slotId !== response.slotId,\n ),\n binding,\n ],\n );\n }\n\n private cacheBlobAttachmentDetachResponse(\n response: BlobAttachmentDetachResponse,\n ): void {\n this.updateCachedDocumentAttachmentList(\n response.documentId,\n (attachments) =>\n attachments.filter(\n (binding) => binding.bindingId !== response.bindingId,\n ),\n );\n }\n\n // An attachment write updates the cached listing from its response; a\n // refused or failed write leaves every listing unknown, so all are dropped.\n private attachmentWrite<R>(\n write: Promise<R | null>,\n cacheResponse: (response: R) => void,\n ): Promise<R | null> {\n return write\n .then((response) => {\n if (response) {\n cacheResponse(response);\n } else {\n this.attachmentLists.clear();\n }\n return response;\n })\n .catch((error: unknown) => {\n this.attachmentLists.clear();\n throw error;\n });\n }\n\n initiateMultipartBlobStage(input: InitiateMultipartBlobStageRequest) {\n return this.context.send(\n multipartInitiate,\n multipartInitiate.path,\n initiateMultipartBlobStageOperation,\n input,\n );\n }\n\n getMultipartBlobStage(stageId: string) {\n return this.context.send(\n multipartGet,\n multipartGet.path(stageId),\n getMultipartBlobStageOperation,\n );\n }\n\n uploadMultipartBlobPartBytes(\n stageId: string,\n partNumber: number,\n input: UploadMultipartBlobPartBytesRequest,\n options: RequestResultOptions = {},\n ) {\n return uploadMultipartBlobPartBytes(\n this.context.transport,\n stageId,\n partNumber,\n input,\n undefined,\n options,\n );\n }\n\n getBlobBytes(blobId: string, options: RequestResultOptions = {}) {\n return getBlobBytes(this.context.transport, blobId, undefined, options);\n }\n\n bindBlobAttachment(\n blobId: string,\n input: BlobAttachmentBindRequest,\n options: RequestResultOptions = {},\n ) {\n return this.attachmentWrite(\n this.context.send(\n blobAttachmentBind,\n blobAttachmentBind.path(blobId),\n bindBlobAttachmentOperation,\n input,\n options,\n ),\n (response) => this.cacheBlobAttachmentBindResponse(input, response),\n );\n }\n\n detachBlobAttachment(\n blobId: string,\n bindingId: string,\n input: BlobAttachmentDetachRequest,\n options: RequestResultOptions = {},\n ) {\n return this.attachmentWrite(\n this.context.send(\n blobAttachmentDetach,\n blobAttachmentDetach.path(blobId, bindingId),\n detachBlobAttachmentOperation,\n input,\n options,\n ),\n this.cacheBlobAttachmentDetachResponse,\n );\n }\n\n listDocumentAttachments(\n documentId: string,\n options: { refresh?: boolean } = {},\n ) {\n if (options.refresh) {\n this.attachmentLists.delete(documentId);\n }\n return cachedRequest(this.attachmentLists, documentId, () =>\n this.context.send(\n documentAttachmentsList,\n documentAttachmentsList.path(documentId),\n listDocumentAttachmentsOperation,\n ),\n );\n }\n}\n"]}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SAAiB,EACjB,KAAkC,EAClC,UAAgC,EAAE;QAElC,OAAO,IAAI,CAAC,eAAe,CACzB,IAAI,CAAC,OAAO,CAAC,IAAI,CACf,oBAAoB,EACpB,oBAAoB,CAAC,IAAI,CAAC,MAAM,EAAE,SAAS,CAAC,EAC5C,6BAA6B,EAC7B,KAAK,EACL,OAAO,CACR,EACD,IAAI,CAAC,iCAAiC,CACvC,CAAC;IACJ,CAAC;IAED,uBAAuB,CACrB,UAAkB,EAClB,UAAiC,EAAE;QAEnC,IAAI,OAAO,CAAC,OAAO,EAAE,CAAC;YACpB,IAAI,CAAC,eAAe,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;QAC1C,CAAC;QACD,OAAO,aAAa,CAAC,IAAI,CAAC,eAAe,EAAE,UAAU,EAAE,GAAG,EAAE,CAC1D,IAAI,CAAC,OAAO,CAAC,IAAI,CACf,uBAAuB,EACvB,uBAAuB,CAAC,IAAI,CAAC,UAAU,CAAC,EACxC,gCAAgC,CACjC,CACF,CAAC;IACJ,CAAC;CACF","sourcesContent":["import {\n bindBlobAttachmentOperation,\n detachBlobAttachmentOperation,\n getMultipartBlobStageOperation,\n initiateMultipartBlobStageOperation,\n listDocumentAttachmentsOperation,\n} from \"@tearleads/validators/operation\";\nimport type {\n BlobAttachmentBindRequest,\n BlobAttachmentDetachRequest,\n InitiateMultipartBlobStageRequest,\n} from \"@tearleads/validators/request\";\nimport type {\n BlobAttachmentBindResponse,\n BlobAttachmentDetachResponse,\n ListDocumentAttachmentsResponse,\n} from \"@tearleads/validators/response\";\nimport { blobAttachmentSummaryFromStagedBind } from \"@tearleads/validators/response\";\nimport { bindPrototypeMethods, cachedRequest } from \"../requestInternals\";\nimport {\n bindBlobAttachment as blobAttachmentBind,\n detachBlobAttachment as blobAttachmentDetach,\n} from \"../routes/blobs/attachments\";\nimport {\n getBlobBytes,\n type UploadMultipartBlobPartBytesRequest,\n} from \"../routes/blobs/get\";\nimport {\n getMultipartBlobStage as multipartGet,\n initiateMultipartBlobStage as multipartInitiate,\n} from \"../routes/blobs/multipart\";\nimport { uploadMultipartBlobPartBytes } from \"../routes/blobs/multipartUpload\";\nimport { listDocumentAttachments as documentAttachmentsList } from \"../routes/documents/attachments\";\nimport type { RequestResultOptions } from \"../types\";\nimport type { ApiClientContext } from \"./apiClientContext\";\n\ntype AttachmentList = ListDocumentAttachmentsResponse;\n\n/**\n * Multipart blob staging, blob bytes, and document attachment bindings, with\n * the per-document attachment listing cache they keep current.\n */\nexport class BlobArea {\n private readonly attachmentLists: ApiClientContext[\"documentAttachmentListRequestsByDocumentId\"];\n\n constructor(private readonly context: ApiClientContext) {\n bindPrototypeMethods(this, BlobArea.prototype);\n this.attachmentLists = context.documentAttachmentListRequestsByDocumentId;\n }\n\n private updateCachedDocumentAttachmentList(\n documentId: string,\n update: (attachments: AttachmentList) => AttachmentList,\n ): void {\n const cached = this.attachmentLists.get(documentId);\n if (!cached) {\n return;\n }\n\n let next: Promise<AttachmentList | null>;\n next = cached\n .then((attachments) => {\n if (!attachments) {\n if (this.attachmentLists.get(documentId) === next) {\n this.attachmentLists.delete(documentId);\n }\n return attachments;\n }\n\n return update(attachments);\n })\n .catch(() => {\n // The underlying list fetch failed. Drop this derived cache entry so the\n // next read refetches, and resolve to null (the cache's miss semantics)\n // rather than rethrowing: nothing awaits this derived promise directly,\n // so a rethrow would surface as an unhandled rejection. Callers already\n // awaiting the original request still observe its rejection.\n if (this.attachmentLists.get(documentId) === next) {\n this.attachmentLists.delete(documentId);\n }\n return null;\n });\n this.attachmentLists.set(documentId, next);\n }\n\n /**\n * The bind acknowledges by hash, so the cached listing entry is rebuilt\n * from the request it acknowledged: a staged upload's bind creates the blob,\n * so its one binding's KEK targets are the ones its content-key bundle wraps\n * to, and it stores exactly the signed event, bundle, and write header it\n * carried. Any other bind (no staged blob, or a target set other than the\n * one the bundle names) keeps material the response does not carry, so it\n * drops the cached listing instead.\n */\n private cacheBlobAttachmentBindResponse(\n request: BlobAttachmentBindRequest,\n response: BlobAttachmentBindResponse,\n ): void {\n const { stagedBlob } = request;\n if (\n !stagedBlob ||\n response.blobKeyTargetHash !== request.contentKeyBundle.targetHash\n ) {\n this.attachmentLists.delete(response.documentId);\n return;\n }\n const binding = blobAttachmentSummaryFromStagedBind(\n { ...request, stagedBlob },\n response,\n );\n this.updateCachedDocumentAttachmentList(\n response.documentId,\n (attachments) => [\n ...attachments.filter(\n (cachedBinding) => cachedBinding.slotId !== response.slotId,\n ),\n binding,\n ],\n );\n }\n\n private cacheBlobAttachmentDetachResponse(\n response: BlobAttachmentDetachResponse,\n ): void {\n this.updateCachedDocumentAttachmentList(\n response.documentId,\n (attachments) =>\n attachments.filter(\n (binding) => binding.bindingId !== response.bindingId,\n ),\n );\n }\n\n // An attachment write updates the cached listing from its response; a\n // refused or failed write leaves every listing unknown, so all are dropped.\n private attachmentWrite<R>(\n write: Promise<R | null>,\n cacheResponse: (response: R) => void,\n ): Promise<R | null> {\n const session = this.context.runtime.responseRequest.sessionSignal?.();\n return write\n .then((response) => {\n if (session?.aborted) return null;\n if (response) {\n cacheResponse(response);\n } else {\n this.attachmentLists.clear();\n }\n return response;\n })\n .catch((error: unknown) => {\n if (!session?.aborted) this.attachmentLists.clear();\n throw error;\n });\n }\n\n initiateMultipartBlobStage(input: InitiateMultipartBlobStageRequest) {\n return this.context.send(\n multipartInitiate,\n multipartInitiate.path,\n initiateMultipartBlobStageOperation,\n input,\n );\n }\n\n getMultipartBlobStage(stageId: string) {\n return this.context.send(\n multipartGet,\n multipartGet.path(stageId),\n getMultipartBlobStageOperation,\n );\n }\n\n uploadMultipartBlobPartBytes(\n stageId: string,\n partNumber: number,\n input: UploadMultipartBlobPartBytesRequest,\n options: RequestResultOptions = {},\n ) {\n return this.transfer(options, (scoped) =>\n uploadMultipartBlobPartBytes(\n this.context.transport,\n stageId,\n partNumber,\n input,\n undefined,\n scoped,\n ),\n );\n }\n\n getBlobBytes(blobId: string, options: RequestResultOptions = {}) {\n return this.transfer(options, (scoped) =>\n getBlobBytes(this.context.transport, blobId, undefined, scoped),\n );\n }\n\n private async transfer<T>(\n options: RequestResultOptions,\n run: (scoped: RequestResultOptions) => Promise<T | null>,\n ): Promise<T | null> {\n const scoped = this.context.runtime.withSessionSignal(options);\n const result = await run(scoped);\n return scoped.signal?.aborted ? null : result;\n }\n\n bindBlobAttachment(\n blobId: string,\n input: BlobAttachmentBindRequest,\n options: RequestResultOptions = {},\n ) {\n return this.attachmentWrite(\n this.context.send(\n blobAttachmentBind,\n blobAttachmentBind.path(blobId),\n bindBlobAttachmentOperation,\n input,\n options,\n ),\n (response) => this.cacheBlobAttachmentBindResponse(input, response),\n );\n }\n\n detachBlobAttachment(\n blobId: string,\n bindingId: string,\n input: BlobAttachmentDetachRequest,\n options: RequestResultOptions = {},\n ) {\n return this.attachmentWrite(\n this.context.send(\n blobAttachmentDetach,\n blobAttachmentDetach.path(blobId, bindingId),\n detachBlobAttachmentOperation,\n input,\n options,\n ),\n this.cacheBlobAttachmentDetachResponse,\n );\n }\n\n listDocumentAttachments(\n documentId: string,\n options: { refresh?: boolean } = {},\n ) {\n if (options.refresh) {\n this.attachmentLists.delete(documentId);\n }\n return cachedRequest(this.attachmentLists, documentId, () =>\n this.context.send(\n documentAttachmentsList,\n documentAttachmentsList.path(documentId),\n listDocumentAttachmentsOperation,\n ),\n );\n }\n}\n"]}
@@ -1,4 +1,5 @@
1
1
  import { requestDeadline } from "../requestDeadline.js";
2
+ import { retiredRequest } from "../sessionResponse.js";
2
3
  /**
3
4
  * A container lane listing with no complete response by now is treated as
4
5
  * lost. Far above a healthy batch, it bounds every sweep and tree crawl that
@@ -15,6 +16,7 @@ export const CONTAINER_LANE_LISTING_TIMEOUT_MS = 60_000;
15
16
  */
16
17
  export async function laneListingRequest(context, input) {
17
18
  const { method, path, reportErrors } = input;
19
+ const signIn = context.runtime.responseRequest.sessionSignal?.();
18
20
  // Report only after classifying: an abort inside the body otherwise
19
21
  // surfaces as a body-read failure before it is known to be the deadline.
20
22
  const deadline = requestDeadline({ reportErrors: false }, CONTAINER_LANE_LISTING_TIMEOUT_MS);
@@ -23,6 +25,8 @@ export async function laneListingRequest(context, input) {
23
25
  // included, so the request has fully settled, and written its last
24
26
  // shared state, by the time the deadline's failure is recorded.
25
27
  const result = await context.requestResult(path, input.validator, method, input.body, deadline.options, input.operation);
28
+ if (signIn?.aborted)
29
+ return retiredRequest(method, path);
26
30
  if (result.ok)
27
31
  return result;
28
32
  if (!deadline.expired()) {
@@ -1 +1 @@
1
- {"version":3,"file":"laneListingRequest.js","sourceRoot":"","sources":["laneListingRequest.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAIrD;;;;;GAKG;AACH,MAAM,CAAC,MAAM,iCAAiC,GAAG,MAAM,CAAC;AAExD;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,kBAAkB,CACtC,OAAyB,EACzB,KAOC;IAED,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,YAAY,EAAE,GAAG,KAAK,CAAC;IAC7C,oEAAoE;IACpE,yEAAyE;IACzE,MAAM,QAAQ,GAAG,eAAe,CAC9B,EAAE,YAAY,EAAE,KAAK,EAAE,EACvB,iCAAiC,CAClC,CAAC;IACF,IAAI,CAAC;QACH,qEAAqE;QACrE,mEAAmE;QACnE,gEAAgE;QAChE,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,aAAa,CACxC,IAAI,EACJ,KAAK,CAAC,SAAS,EACf,MAAM,EACN,KAAK,CAAC,IAAI,EACV,QAAQ,CAAC,OAAO,EAChB,KAAK,CAAC,SAAS,CAChB,CAAC;QACF,IAAI,MAAM,CAAC,EAAE;YAAE,OAAO,MAAM,CAAC;QAC7B,IAAI,CAAC,QAAQ,CAAC,OAAO,EAAE,EAAE,CAAC;YACxB,IAAI,YAAY;gBAAE,MAAM,CAAC,MAAM,EAAE,CAAC;YAClC,OAAO,MAAM,CAAC;QAChB,CAAC;QACD,OAAO,OAAO,CAAC,OAAO,CAAC,eAAe,CAAC,aAAa,CAAC;YACnD,IAAI,EAAE,mBAAmB;YACzB,IAAI,EAAE,SAAS;YACf,OAAO,EAAE,GAAG,MAAM,IAAI,IAAI,wBAAwB,iCAAiC,KAAK;YACxF,MAAM;YACN,OAAO,EAAE,EAAE,YAAY,EAAE;YACzB,IAAI;YACJ,MAAM,EAAE,IAAI;YACZ,UAAU,EAAE,EAAE;SACf,CAAC,CAAC;IACL,CAAC;YAAS,CAAC;QACT,QAAQ,CAAC,OAAO,EAAE,CAAC;IACrB,CAAC;AACH,CAAC","sourcesContent":["import type { HttpOperation } from \"@tearleads/validators/operation\";\nimport { requestDeadline } from \"../requestDeadline\";\nimport type { HttpMethod, RequestResult } from \"../types\";\nimport type { ApiClientContext } from \"./apiClientContext\";\n\n/**\n * A container lane listing with no complete response by now is treated as\n * lost. Far above a healthy batch, it bounds every sweep and tree crawl that\n * waits on one: without it, a request that never settles holds the shared\n * listing, and everything joined to it, indefinitely.\n */\nexport const CONTAINER_LANE_LISTING_TIMEOUT_MS = 60_000;\n\n/**\n * Runs one lane listing under {@link CONTAINER_LANE_LISTING_TIMEOUT_MS}. The\n * deadline belongs to the request, not to a caller, so a de-duplicated\n * listing ends for every caller joined to it. A timeout, before the headers\n * or inside the body, fails as one network failure rather than a cancellation\n * or a body error, so it is reported once and retried like any lost request.\n */\nexport async function laneListingRequest<T>(\n context: ApiClientContext,\n input: {\n readonly body: string;\n readonly method: HttpMethod;\n readonly operation: HttpOperation;\n readonly path: string;\n readonly reportErrors: boolean;\n readonly validator: (value: unknown) => value is T;\n },\n): Promise<RequestResult<T>> {\n const { method, path, reportErrors } = input;\n // Report only after classifying: an abort inside the body otherwise\n // surfaces as a body-read failure before it is known to be the deadline.\n const deadline = requestDeadline(\n { reportErrors: false },\n CONTAINER_LANE_LISTING_TIMEOUT_MS,\n );\n try {\n // Every wait inside the request observes the signal, session renewal\n // included, so the request has fully settled, and written its last\n // shared state, by the time the deadline's failure is recorded.\n const result = await context.requestResult(\n path,\n input.validator,\n method,\n input.body,\n deadline.options,\n input.operation,\n );\n if (result.ok) return result;\n if (!deadline.expired()) {\n if (reportErrors) result.report();\n return result;\n }\n return context.runtime.responseRequest.reportFailure({\n code: \"request_timed_out\",\n kind: \"network\",\n message: `${method} ${path}: no response within ${CONTAINER_LANE_LISTING_TIMEOUT_MS} ms`,\n method,\n options: { reportErrors },\n path,\n status: null,\n statusText: \"\",\n });\n } finally {\n deadline.dispose();\n }\n}\n"]}
1
+ {"version":3,"file":"laneListingRequest.js","sourceRoot":"","sources":["laneListingRequest.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AACrD,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAIpD;;;;;GAKG;AACH,MAAM,CAAC,MAAM,iCAAiC,GAAG,MAAM,CAAC;AAExD;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,kBAAkB,CACtC,OAAyB,EACzB,KAOC;IAED,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,YAAY,EAAE,GAAG,KAAK,CAAC;IAC7C,MAAM,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,eAAe,CAAC,aAAa,EAAE,EAAE,CAAC;IACjE,oEAAoE;IACpE,yEAAyE;IACzE,MAAM,QAAQ,GAAG,eAAe,CAC9B,EAAE,YAAY,EAAE,KAAK,EAAE,EACvB,iCAAiC,CAClC,CAAC;IACF,IAAI,CAAC;QACH,qEAAqE;QACrE,mEAAmE;QACnE,gEAAgE;QAChE,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,aAAa,CACxC,IAAI,EACJ,KAAK,CAAC,SAAS,EACf,MAAM,EACN,KAAK,CAAC,IAAI,EACV,QAAQ,CAAC,OAAO,EAChB,KAAK,CAAC,SAAS,CAChB,CAAC;QACF,IAAI,MAAM,EAAE,OAAO;YAAE,OAAO,cAAc,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;QACzD,IAAI,MAAM,CAAC,EAAE;YAAE,OAAO,MAAM,CAAC;QAC7B,IAAI,CAAC,QAAQ,CAAC,OAAO,EAAE,EAAE,CAAC;YACxB,IAAI,YAAY;gBAAE,MAAM,CAAC,MAAM,EAAE,CAAC;YAClC,OAAO,MAAM,CAAC;QAChB,CAAC;QACD,OAAO,OAAO,CAAC,OAAO,CAAC,eAAe,CAAC,aAAa,CAAC;YACnD,IAAI,EAAE,mBAAmB;YACzB,IAAI,EAAE,SAAS;YACf,OAAO,EAAE,GAAG,MAAM,IAAI,IAAI,wBAAwB,iCAAiC,KAAK;YACxF,MAAM;YACN,OAAO,EAAE,EAAE,YAAY,EAAE;YACzB,IAAI;YACJ,MAAM,EAAE,IAAI;YACZ,UAAU,EAAE,EAAE;SACf,CAAC,CAAC;IACL,CAAC;YAAS,CAAC;QACT,QAAQ,CAAC,OAAO,EAAE,CAAC;IACrB,CAAC;AACH,CAAC","sourcesContent":["import type { HttpOperation } from \"@tearleads/validators/operation\";\nimport { requestDeadline } from \"../requestDeadline\";\nimport { retiredRequest } from \"../sessionResponse\";\nimport type { HttpMethod, RequestResult } from \"../types\";\nimport type { ApiClientContext } from \"./apiClientContext\";\n\n/**\n * A container lane listing with no complete response by now is treated as\n * lost. Far above a healthy batch, it bounds every sweep and tree crawl that\n * waits on one: without it, a request that never settles holds the shared\n * listing, and everything joined to it, indefinitely.\n */\nexport const CONTAINER_LANE_LISTING_TIMEOUT_MS = 60_000;\n\n/**\n * Runs one lane listing under {@link CONTAINER_LANE_LISTING_TIMEOUT_MS}. The\n * deadline belongs to the request, not to a caller, so a de-duplicated\n * listing ends for every caller joined to it. A timeout, before the headers\n * or inside the body, fails as one network failure rather than a cancellation\n * or a body error, so it is reported once and retried like any lost request.\n */\nexport async function laneListingRequest<T>(\n context: ApiClientContext,\n input: {\n readonly body: string;\n readonly method: HttpMethod;\n readonly operation: HttpOperation;\n readonly path: string;\n readonly reportErrors: boolean;\n readonly validator: (value: unknown) => value is T;\n },\n): Promise<RequestResult<T>> {\n const { method, path, reportErrors } = input;\n const signIn = context.runtime.responseRequest.sessionSignal?.();\n // Report only after classifying: an abort inside the body otherwise\n // surfaces as a body-read failure before it is known to be the deadline.\n const deadline = requestDeadline(\n { reportErrors: false },\n CONTAINER_LANE_LISTING_TIMEOUT_MS,\n );\n try {\n // Every wait inside the request observes the signal, session renewal\n // included, so the request has fully settled, and written its last\n // shared state, by the time the deadline's failure is recorded.\n const result = await context.requestResult(\n path,\n input.validator,\n method,\n input.body,\n deadline.options,\n input.operation,\n );\n if (signIn?.aborted) return retiredRequest(method, path);\n if (result.ok) return result;\n if (!deadline.expired()) {\n if (reportErrors) result.report();\n return result;\n }\n return context.runtime.responseRequest.reportFailure({\n code: \"request_timed_out\",\n kind: \"network\",\n message: `${method} ${path}: no response within ${CONTAINER_LANE_LISTING_TIMEOUT_MS} ms`,\n method,\n options: { reportErrors },\n path,\n status: null,\n statusText: \"\",\n });\n } finally {\n deadline.dispose();\n }\n}\n"]}
@@ -1,6 +1,7 @@
1
1
  import type { RegistrationRequest } from "../../validators/request/index.js";
2
2
  import type { VerifySuccessResponse } from "../../validators/response/index.js";
3
3
  import type { ApiNetworkError } from "../networkFailure.js";
4
+ import type { SessionBoundary } from "../sessionRenewal.js";
4
5
  import type { HttpMethod } from "../types.js";
5
6
  import type { VerifiedManifestCitations } from "../verifiedManifestCitations.js";
6
7
  import type { ApiClientContext } from "./apiClientContext.js";
@@ -23,7 +24,10 @@ export declare class SessionArea {
23
24
  setOnPaymentRequired(handler: PaymentRequiredHandler | null): void;
24
25
  /** Verified bundles to cite on projection reads, scoped by their owner. */
25
26
  setVerifiedManifestCitations(source: VerifiedManifestCitations | null): void;
26
- setAuthToken(token: string | null): void;
27
+ setAuthToken(token: string | null, options?: {
28
+ boundary?: SessionBoundary | undefined;
29
+ verifiedTicket?: string | undefined;
30
+ }): void;
27
31
  getAuthToken(): string | null;
28
32
  getRequestFailure(input: {
29
33
  method: HttpMethod;
@@ -42,8 +42,14 @@ export class SessionArea {
42
42
  setVerifiedManifestCitations(source) {
43
43
  this.context.verifiedManifestCitations = source;
44
44
  }
45
- setAuthToken(token) {
46
- if (this.context.runtime.setAuthToken(token)) {
45
+ setAuthToken(token, options) {
46
+ const boundary = options?.boundary ??
47
+ (token === null && this.getAuthToken() !== null
48
+ ? "replacement"
49
+ : undefined);
50
+ if (boundary)
51
+ this.webSocketTickets.retainVerifiedTicket(options?.verifiedTicket);
52
+ if (this.context.runtime.setAuthToken(token, boundary)) {
47
53
  this.context.clearAuthScopedCaches();
48
54
  }
49
55
  }
@@ -82,18 +88,20 @@ export class SessionArea {
82
88
  });
83
89
  }
84
90
  async authenticate(fingerprint, secretKey) {
91
+ const session = this.context.runtime.responseRequest.sessionSignal?.();
85
92
  const challenge = await this.context.transport.request(challengeOperation, { body: { fingerprint }, params: {} }, { retryOnSessionExpired: false });
86
- if (!challenge)
93
+ if (!challenge || session?.aborted)
87
94
  return null;
88
95
  return this.self.authenticateWithChallenge(fingerprint, secretKey, challenge.challenge);
89
96
  }
90
97
  async authenticateWithChallenge(fingerprint, secretKey, challengeHex) {
98
+ const session = this.context.runtime.responseRequest.sessionSignal?.();
91
99
  const signed = sign(this.context.runtime.authChallengeBytes(challengeHex, fingerprint), secretKey);
92
100
  const response = verifiedLogin(await this.context.transport.requestResult(verifyOperation, {
93
101
  body: { fingerprint, signature: bytesToBase64(signed) },
94
102
  params: {},
95
103
  }, { retryOnSessionExpired: false }));
96
- if (!response?.authenticated)
104
+ if (!response?.authenticated || session?.aborted)
97
105
  return null;
98
106
  this.webSocketTickets.rememberLogin(response);
99
107
  return response;
@@ -1 +1 @@
1
- {"version":3,"file":"session.js","sourceRoot":"","sources":["session.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,mBAAmB,CAAC;AACzC,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EACL,kBAAkB,EAClB,uBAAuB,EACvB,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AS,EAAE,aAAa,CAAC,MAAM,CAAC,EAAE;YACvD,MAAM,EAAE,EAAE;SACX,EACD,EAAE,qBAAqB,EAAE,KAAK,EAAE,CACjC,CACF,CAAC;QACF,IAAI,CAAC,QAAQ,EAAE,aAAa;YAAE,OAAO,IAAI,CAAC;QAC1C,IAAI,CAAC,gBAAgB,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC;QAC9C,OAAO,QAAQ,CAAC;IAClB,CAAC;IAED,YAAY;QACV,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CACtB,gBAAgB,EAChB,gBAAgB,CAAC,IAAI,EACrB,qBAAqB,CACtB,CAAC;IACJ,CAAC;IAED,cAAc,CAAC,SAAiB;QAC9B,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CACtB,kBAAkB,EAClB,kBAAkB,CAAC,IAAI,CAAC,SAAS,CAAC,EAClC,uBAAuB,CACxB,CAAC;IACJ,CAAC;IAED,MAAM;QACJ,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CACtB,UAAU,EACV,UAAU,CAAC,IAAI,EACf,eAAe,EACf,SAAS,EACT;YACE,qBAAqB,EAAE,KAAK;SAC7B,CACF,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { sign } from \"@tearleads/crypto\";\nimport { bytesToBase64 } from \"@tearleads/encoding\";\nimport {\n challengeOperation,\n destroySessionOperation,\n getHealthOperation,\n listSessionsOperation,\n logoutOperation,\n registerOperation,\n verifyOperation,\n} from \"@tearleads/validators/operation\";\nimport type { RegistrationRequest } from \"@tearleads/validators/request\";\nimport type { VerifySuccessResponse } from \"@tearleads/validators/response\";\nimport { verifiedLogin } from \"../accountSuspension\";\nimport type { ApiNetworkError } from \"../networkFailure\";\nimport { bindPrototypeMethods } from \"../requestInternals\";\nimport {\n destroySession as authDestroySession,\n listSessions as authListSessions,\n logout as authLogout,\n} from \"../routes/auth/session\";\nimport type { HttpMethod } from \"../types\";\nimport type { VerifiedManifestCitations } from \"../verifiedManifestCitations\";\nimport { WebSocketTickets } from \"../webSocketTickets\";\nimport type { ApiClientContext } from \"./apiClientContext\";\nimport type { ApiClientSelf } from \"./apiClientSelf\";\n\ntype ExpiredHandler = () => boolean | Promise<boolean>;\ntype PaymentRequiredHandler = (organizationId: string | null) => void;\n\n/** Connection hooks, the session token, registration, and login. */\nexport class SessionArea {\n private readonly webSocketTickets: WebSocketTickets;\n\n constructor(\n private readonly context: ApiClientContext,\n private readonly self: Pick<\n ApiClientSelf,\n \"authenticateWithChallenge\" | \"getAuthToken\"\n >,\n ) {\n bindPrototypeMethods(this, SessionArea.prototype);\n this.webSocketTickets = new WebSocketTickets(context.transport, () =>\n self.getAuthToken(),\n );\n }\n\n setOnError(handler: ((message: string) => void) | null): void {\n this.context.runtime.setOnError(handler);\n }\n\n setOnNetworkError(handler: (() => void) | null): void {\n this.context.runtime.setOnNetworkError(handler);\n }\n\n setOnNetworkSuccess(handler: (() => void) | null): void {\n this.context.runtime.setOnNetworkSuccess(handler);\n }\n\n /** Every fetch that threw without a response, except plain cancellations. */\n setOnNetworkFailure(handler: ((e: ApiNetworkError) => void) | null): void {\n this.context.runtime.setOnNetworkFailure(handler);\n }\n\n setOnApiVersion(handler: ((version: number) => void) | null): void {\n this.context.runtime.setOnApiVersion(handler);\n }\n\n setOnSessionExpired(handler: ExpiredHandler | null): void {\n this.context.runtime.setOnSessionExpired(handler);\n }\n\n setOnPaymentRequired(handler: PaymentRequiredHandler | null): void {\n this.context.runtime.setOnPaymentRequired(handler);\n }\n\n /** Verified bundles to cite on projection reads, scoped by their owner. */\n setVerifiedManifestCitations(source: VerifiedManifestCitations | null): void {\n this.context.verifiedManifestCitations = source;\n }\n\n setAuthToken(token: string | null): void {\n if (this.context.runtime.setAuthToken(token)) {\n this.context.clearAuthScopedCaches();\n }\n }\n\n getAuthToken(): string | null {\n return this.context.runtime.getAuthToken();\n }\n\n getRequestFailure(input: { method: HttpMethod; path: string }) {\n return this.context.runtime.getRequestFailure(input);\n }\n\n requestWebSocketTicket(): Promise<string | null> {\n return this.webSocketTickets.next();\n }\n\n getHealth() {\n return this.context.transport.request(getHealthOperation, { params: {} });\n }\n\n registerUser(\n userId: string,\n organizationId: string,\n rootContainerId: string,\n signingPublicKey: Uint8Array,\n encapsulationPublicKey: Uint8Array,\n initialAdminGroup: RegistrationRequest[\"initialAdminGroup\"],\n initialMemberGroup: RegistrationRequest[\"initialMemberGroup\"],\n initialOrganizationPolicy: RegistrationRequest[\"initialOrganizationPolicy\"],\n initialRootContainer: RegistrationRequest[\"initialRootContainer\"],\n initialRootMetadataDocument: RegistrationRequest[\"initialRootMetadataDocument\"],\n initialRosterProfileContainer: RegistrationRequest[\"initialRosterProfileContainer\"],\n initialRosterProfileDocument: RegistrationRequest[\"initialRosterProfileDocument\"],\n initialOrganizationMetadataContainer: RegistrationRequest[\"initialOrganizationMetadataContainer\"],\n initialOrganizationProfileDocument?: RegistrationRequest[\"initialOrganizationProfileDocument\"],\n initialSystemContainers?: RegistrationRequest[\"initialSystemContainers\"],\n ) {\n return this.context.transport.request(registerOperation, {\n body: {\n userId,\n organizationId,\n rootContainerId,\n signingPublicKey: bytesToBase64(signingPublicKey),\n encapsulationPublicKey: bytesToBase64(encapsulationPublicKey),\n initialAdminGroup,\n initialMemberGroup,\n initialOrganizationPolicy,\n initialRootContainer,\n initialRootMetadataDocument,\n initialRosterProfileContainer,\n initialRosterProfileDocument,\n initialOrganizationMetadataContainer,\n initialOrganizationProfileDocument,\n initialSystemContainers,\n },\n params: {},\n });\n }\n\n async authenticate(fingerprint: string, secretKey: Uint8Array) {\n const challenge = await this.context.transport.request(\n challengeOperation,\n { body: { fingerprint }, params: {} },\n { retryOnSessionExpired: false },\n );\n if (!challenge) return null;\n\n return this.self.authenticateWithChallenge(\n fingerprint,\n secretKey,\n challenge.challenge,\n );\n }\n\n async authenticateWithChallenge(\n fingerprint: string,\n secretKey: Uint8Array,\n challengeHex: string,\n ): Promise<VerifySuccessResponse | null> {\n const signed = sign(\n this.context.runtime.authChallengeBytes(challengeHex, fingerprint),\n secretKey,\n );\n const response = verifiedLogin(\n await this.context.transport.requestResult(\n verifyOperation,\n {\n body: { fingerprint, signature: bytesToBase64(signed) },\n params: {},\n },\n { retryOnSessionExpired: false },\n ),\n );\n if (!response?.authenticated) return null;\n this.webSocketTickets.rememberLogin(response);\n return response;\n }\n\n listSessions() {\n return this.context.send(\n authListSessions,\n authListSessions.path,\n listSessionsOperation,\n );\n }\n\n destroySession(sessionId: string) {\n return this.context.send(\n authDestroySession,\n authDestroySession.path(sessionId),\n destroySessionOperation,\n );\n }\n\n logout() {\n return this.context.send(\n authLogout,\n authLogout.path,\n logoutOperation,\n undefined,\n {\n retryOnSessionExpired: false,\n },\n );\n }\n}\n"]}
1
+ {"version":3,"file":"session.js","sourceRoot":"","sources":["session.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,mBAAmB,CAAC;AACzC,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EACL,kBAAkB,EAClB,uBAAuB,EACvB,kBAAkB,EAClB,qBAAqB,EACrB,eAAe,EACf,iBAAiB,EACjB,eAAe,GAChB,MAAM,iCAAiC,CAAC;AAGzC,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAErD,OAAO,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAC3D,OAAO,EACL,cAAc,IAAI,kBAAkB,EACpC,YAAY,IAAI,gBAAgB,EAChC,MAAM,IAAI,UAAU,GACrB,MAAM,wBAAwB,CAAC;AAIhC,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAOvD,oEAAoE;AACpE,MAAM,OAAO,WAAW;IAIH;IACA;IAJF,gBAAgB,CAAmB;IAEpD,YACmB,OAAyB,EACzB,IAGhB;QAJgB,YAAO,GAAP,OAAO,CAAkB;QACzB,SAAI,GAAJ,IAAI,CAGpB;QAED,oBAAoB,CAAC,IAAI,EAAE,WAA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E,EAAE;SACX,EACD,EAAE,qBAAqB,EAAE,KAAK,EAAE,CACjC,CACF,CAAC;QACF,IAAI,CAAC,QAAQ,EAAE,aAAa,IAAI,OAAO,EAAE,OAAO;YAAE,OAAO,IAAI,CAAC;QAC9D,IAAI,CAAC,gBAAgB,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC;QAC9C,OAAO,QAAQ,CAAC;IAClB,CAAC;IAED,YAAY;QACV,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CACtB,gBAAgB,EAChB,gBAAgB,CAAC,IAAI,EACrB,qBAAqB,CACtB,CAAC;IACJ,CAAC;IAED,cAAc,CAAC,SAAiB;QAC9B,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CACtB,kBAAkB,EAClB,kBAAkB,CAAC,IAAI,CAAC,SAAS,CAAC,EAClC,uBAAuB,CACxB,CAAC;IACJ,CAAC;IAED,MAAM;QACJ,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CACtB,UAAU,EACV,UAAU,CAAC,IAAI,EACf,eAAe,EACf,SAAS,EACT;YACE,qBAAqB,EAAE,KAAK;SAC7B,CACF,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { sign } from \"@tearleads/crypto\";\nimport { bytesToBase64 } from \"@tearleads/encoding\";\nimport {\n challengeOperation,\n destroySessionOperation,\n getHealthOperation,\n listSessionsOperation,\n logoutOperation,\n registerOperation,\n verifyOperation,\n} from \"@tearleads/validators/operation\";\nimport type { RegistrationRequest } from \"@tearleads/validators/request\";\nimport type { VerifySuccessResponse } from \"@tearleads/validators/response\";\nimport { verifiedLogin } from \"../accountSuspension\";\nimport type { ApiNetworkError } from \"../networkFailure\";\nimport { bindPrototypeMethods } from \"../requestInternals\";\nimport {\n destroySession as authDestroySession,\n listSessions as authListSessions,\n logout as authLogout,\n} from \"../routes/auth/session\";\nimport type { SessionBoundary } from \"../sessionRenewal\";\nimport type { HttpMethod } from \"../types\";\nimport type { VerifiedManifestCitations } from \"../verifiedManifestCitations\";\nimport { WebSocketTickets } from \"../webSocketTickets\";\nimport type { ApiClientContext } from \"./apiClientContext\";\nimport type { ApiClientSelf } from \"./apiClientSelf\";\n\ntype ExpiredHandler = () => boolean | Promise<boolean>;\ntype PaymentRequiredHandler = (organizationId: string | null) => void;\n\n/** Connection hooks, the session token, registration, and login. */\nexport class SessionArea {\n private readonly webSocketTickets: WebSocketTickets;\n\n constructor(\n private readonly context: ApiClientContext,\n private readonly self: Pick<\n ApiClientSelf,\n \"authenticateWithChallenge\" | \"getAuthToken\"\n >,\n ) {\n bindPrototypeMethods(this, SessionArea.prototype);\n this.webSocketTickets = new WebSocketTickets(context.transport, () =>\n self.getAuthToken(),\n );\n }\n\n setOnError(handler: ((message: string) => void) | null): void {\n this.context.runtime.setOnError(handler);\n }\n\n setOnNetworkError(handler: (() => void) | null): void {\n this.context.runtime.setOnNetworkError(handler);\n }\n\n setOnNetworkSuccess(handler: (() => void) | null): void {\n this.context.runtime.setOnNetworkSuccess(handler);\n }\n\n /** Every fetch that threw without a response, except plain cancellations. */\n setOnNetworkFailure(handler: ((e: ApiNetworkError) => void) | null): void {\n this.context.runtime.setOnNetworkFailure(handler);\n }\n\n setOnApiVersion(handler: ((version: number) => void) | null): void {\n this.context.runtime.setOnApiVersion(handler);\n }\n\n setOnSessionExpired(handler: ExpiredHandler | null): void {\n this.context.runtime.setOnSessionExpired(handler);\n }\n\n setOnPaymentRequired(handler: PaymentRequiredHandler | null): void {\n this.context.runtime.setOnPaymentRequired(handler);\n }\n\n /** Verified bundles to cite on projection reads, scoped by their owner. */\n setVerifiedManifestCitations(source: VerifiedManifestCitations | null): void {\n this.context.verifiedManifestCitations = source;\n }\n\n setAuthToken(\n token: string | null,\n options?: {\n boundary?: SessionBoundary | undefined;\n verifiedTicket?: string | undefined;\n },\n ): void {\n const boundary =\n options?.boundary ??\n (token === null && this.getAuthToken() !== null\n ? \"replacement\"\n : undefined);\n if (boundary)\n this.webSocketTickets.retainVerifiedTicket(options?.verifiedTicket);\n if (this.context.runtime.setAuthToken(token, boundary)) {\n this.context.clearAuthScopedCaches();\n }\n }\n\n getAuthToken(): string | null {\n return this.context.runtime.getAuthToken();\n }\n\n getRequestFailure(input: { method: HttpMethod; path: string }) {\n return this.context.runtime.getRequestFailure(input);\n }\n\n requestWebSocketTicket(): Promise<string | null> {\n return this.webSocketTickets.next();\n }\n\n getHealth() {\n return this.context.transport.request(getHealthOperation, { params: {} });\n }\n\n registerUser(\n userId: string,\n organizationId: string,\n rootContainerId: string,\n signingPublicKey: Uint8Array,\n encapsulationPublicKey: Uint8Array,\n initialAdminGroup: RegistrationRequest[\"initialAdminGroup\"],\n initialMemberGroup: RegistrationRequest[\"initialMemberGroup\"],\n initialOrganizationPolicy: RegistrationRequest[\"initialOrganizationPolicy\"],\n initialRootContainer: RegistrationRequest[\"initialRootContainer\"],\n initialRootMetadataDocument: RegistrationRequest[\"initialRootMetadataDocument\"],\n initialRosterProfileContainer: RegistrationRequest[\"initialRosterProfileContainer\"],\n initialRosterProfileDocument: RegistrationRequest[\"initialRosterProfileDocument\"],\n initialOrganizationMetadataContainer: RegistrationRequest[\"initialOrganizationMetadataContainer\"],\n initialOrganizationProfileDocument?: RegistrationRequest[\"initialOrganizationProfileDocument\"],\n initialSystemContainers?: RegistrationRequest[\"initialSystemContainers\"],\n ) {\n return this.context.transport.request(registerOperation, {\n body: {\n userId,\n organizationId,\n rootContainerId,\n signingPublicKey: bytesToBase64(signingPublicKey),\n encapsulationPublicKey: bytesToBase64(encapsulationPublicKey),\n initialAdminGroup,\n initialMemberGroup,\n initialOrganizationPolicy,\n initialRootContainer,\n initialRootMetadataDocument,\n initialRosterProfileContainer,\n initialRosterProfileDocument,\n initialOrganizationMetadataContainer,\n initialOrganizationProfileDocument,\n initialSystemContainers,\n },\n params: {},\n });\n }\n\n async authenticate(fingerprint: string, secretKey: Uint8Array) {\n const session = this.context.runtime.responseRequest.sessionSignal?.();\n const challenge = await this.context.transport.request(\n challengeOperation,\n { body: { fingerprint }, params: {} },\n { retryOnSessionExpired: false },\n );\n if (!challenge || session?.aborted) return null;\n\n return this.self.authenticateWithChallenge(\n fingerprint,\n secretKey,\n challenge.challenge,\n );\n }\n\n async authenticateWithChallenge(\n fingerprint: string,\n secretKey: Uint8Array,\n challengeHex: string,\n ): Promise<VerifySuccessResponse | null> {\n const session = this.context.runtime.responseRequest.sessionSignal?.();\n const signed = sign(\n this.context.runtime.authChallengeBytes(challengeHex, fingerprint),\n secretKey,\n );\n const response = verifiedLogin(\n await this.context.transport.requestResult(\n verifyOperation,\n {\n body: { fingerprint, signature: bytesToBase64(signed) },\n params: {},\n },\n { retryOnSessionExpired: false },\n ),\n );\n if (!response?.authenticated || session?.aborted) return null;\n this.webSocketTickets.rememberLogin(response);\n return response;\n }\n\n listSessions() {\n return this.context.send(\n authListSessions,\n authListSessions.path,\n listSessionsOperation,\n );\n }\n\n destroySession(sessionId: string) {\n return this.context.send(\n authDestroySession,\n authDestroySession.path(sessionId),\n destroySessionOperation,\n );\n }\n\n logout() {\n return this.context.send(\n authLogout,\n authLogout.path,\n logoutOperation,\n undefined,\n {\n retryOnSessionExpired: false,\n },\n );\n }\n}\n"]}
@@ -1,6 +1,7 @@
1
1
  import { getContainerWriterProjectionOperation, getDocumentWriterProjectionOperation, } from "../../validators/operation/index.js";
2
2
  import { bindPrototypeMethods, cachedRequest } from "../requestInternals.js";
3
3
  import { containerWriterProjection, documentWriterProjection, } from "../routes/writerProjections.js";
4
+ import { retiredRequest } from "../sessionResponse.js";
4
5
  import { primeWriterProjectionSlot } from "../writerProjectionPrime.js";
5
6
  /**
6
7
  * Container and document writer projections: plain cached reads, coalesced
@@ -91,21 +92,17 @@ export class WriterProjectionArea {
91
92
  // so a projection an eviction (e.g. after a revoke) meant to drop is never
92
93
  // re-cached.
93
94
  async fetchWriterProjectionResult(cache, { cacheKey, path, validator, failureOperation }) {
95
+ const session = this.context.runtime.responseRequest.sessionSignal?.();
96
+ const retired = () => retiredRequest("GET", path);
94
97
  let cached = cache.get(cacheKey);
95
98
  while (cached) {
96
- try {
97
- const data = await cached;
98
- if (data) {
99
- return { data, ok: true };
100
- }
101
- }
102
- catch {
103
- // A rejected shared entry is reconciled by its own settle handler;
104
- // fall through either way.
105
- }
106
- // The awaited entry settled empty. Re-read the slot before fetching: a
107
- // newer entry installed while we awaited must be reused, not fetched
108
- // over — the set below would otherwise clobber it.
99
+ // Rejected and empty entries both fall through to the current slot.
100
+ const data = await cached.catch(() => null);
101
+ if (session?.aborted)
102
+ return retired();
103
+ if (data)
104
+ return { data, ok: true };
105
+ // A newer entry installed during the wait must be reused.
109
106
  const current = cache.get(cacheKey);
110
107
  if (current === cached) {
111
108
  break;
@@ -123,6 +120,8 @@ export class WriterProjectionArea {
123
120
  const result = await this.context.requestResult(path, validator, "GET", undefined, {
124
121
  reportErrors: false,
125
122
  }, failureOperation);
123
+ if (session?.aborted)
124
+ return retired();
126
125
  if (result.ok) {
127
126
  // Publish the success unless the slot changed or this id was
128
127
  // invalidated mid-flight. The stamp check is what makes an eviction of
@@ -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,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CAChC,IAAI,CAAC,SAAS,EACd;YACE,QAAQ,EAAE,UAAU;YACpB,IAAI,EAAE,wBAAwB,CAAC,IAAI,CAAC,UAAU,CAAC;YAC/C,SAAS,EAAE,wBAAwB,CAAC,aAAa,CAAC,UAAU,CAAC;YAC7D,gBAAgB,EAAE,oCAAoC;SACvD,EACD,OAAO,CACR,CAAC;IACJ,CAAC;IAED;;;;;;;;;;OAUG;IACH,6BAA6B,CAC3B,UAAkB,EAClB,UAA4C;QAE5C,yBAAyB,CAAC;YACxB,KAAK,EAAE,IAAI,CAAC,SAAS,CAAC,KAAK;YAC3B,SAAS,EAAE,wBAAwB,CAAC,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,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;AACrC,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAGpD,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,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,CAAC,IAAI,CAAC,UAAU,CAAC;YAC/C,SAAS,EAAE,wBAAwB,CAAC,aAAa,CAAC,UAAU,CAAC;YAC7D,gBAAgB,EAAE,oCAAoC;SACvD,EACD,OAAO,CACR,CAAC;IACJ,CAAC;IAED;;;;;;;;;;OAUG;IACH,6BAA6B,CAC3B,UAAkB,EAClB,UAA4C;QAE5C,yBAAyB,CAAC;YACxB,KAAK,EAAE,IAAI,CAAC,SAAS,CAAC,KAAK;YAC3B,SAAS,EAAE,wBAAwB,CAAC,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 { 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 { errorMessage } from "./requestInternals.js";
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 reportBodyReadFailure(request, operation, response, path, options, error) {
37
- const failure = responseBodyFailure(error, errorMessage(error), options.signal?.aborted === true);
38
- return request.reportFailure({
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
- let value;
61
- try {
62
- value = await response.json();
63
- }
64
- catch (error) {
65
- return reportBodyReadFailure(request, operation, response, path, options, error);
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,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAkE5D,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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,IAAI,CAAC;YACH,KAAK,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;QAChC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,qBAAqB,CAC1B,OAAO,EACP,SAAS,EACT,QAAQ,EACR,IAAI,EACJ,OAAO,EACP,KAAK,CACN,CAAC;QACJ,CAAC;QAED,MAAM,MAAM,GAAG,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;QACvC,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;YACpB,OAAO,wBAAwB,CAC7B,OAAO,EACP,SAAS,EACT,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 { errorMessage } from \"./requestInternals\";\nimport { responseBodyFailure } from \"./responseBodyFailure\";\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\nfunction reportBodyReadFailure(\n request: OperationResponseRequestFn,\n operation: JsonResponseOperation,\n response: Response,\n path: string,\n options: RequestResultOptions,\n error: unknown,\n) {\n const failure = responseBodyFailure(\n error,\n errorMessage(error),\n options.signal?.aborted === true,\n );\n return request.reportFailure({\n ...failure,\n message: `${operation.method} ${path}: ${failure.message}`,\n method: operation.method,\n options,\n path,\n status: response.status,\n statusText: response.statusText,\n });\n}\n\nexport async function decodeJsonOperationResponse(\n request: OperationResponseRequestFn,\n operation: JsonResponseOperation,\n response: Response,\n path: string,\n options: RequestResultOptions,\n): Promise<RequestResult<RuntimeJsonOperationResponseEnvelope>> {\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 let value: unknown;\n try {\n value = await response.json();\n } catch (error) {\n return reportBodyReadFailure(\n request,\n operation,\n response,\n path,\n options,\n error,\n );\n }\n\n const parsed = schema.safeParse(value);\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"]}
1
+ {"version":3,"file":"operationResponse.js","sourceRoot":"","sources":["operationResponse.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,4BAA4B,GAC7B,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,eAAe,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AM,MAAM,GAAG,MAAM,eAAe,CAClC,OAAO,EACP,QAAQ,EACR,SAAS,CAAC,MAAM,EAChB,IAAI,EACJ,OAAO,EACP,OAAO,CACR,CAAC;QACF,IAAI,OAAO,EAAE,OAAO;YAAE,OAAO,cAAc,CAAC,SAAS,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;QACpE,IAAI,CAAC,MAAM,CAAC,EAAE;YAAE,OAAO,MAAM,CAAC;QAC9B,MAAM,MAAM,GAAG,MAAM,CAAC,SAAS,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;QAC7C,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;YACpB,OAAO,wBAAwB,CAC7B,OAAO,EACP,SAAS,EACT,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);