@tearleads/client-sdk 0.1.250 → 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 (190) 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/documents/shared/events.js +2 -1
  55. package/data/documents/shared/events.js.map +1 -1
  56. package/data/principals/principalPolicyCoordinator.js +8 -17
  57. package/data/principals/principalPolicyCoordinator.js.map +1 -1
  58. package/data/shared/domainScope.d.ts +2 -0
  59. package/data/shared/domainScope.js +2 -1
  60. package/data/shared/domainScope.js.map +1 -1
  61. package/data/shared/keyedQueue.js +15 -0
  62. package/data/shared/keyedQueue.js.map +1 -0
  63. package/data/sqlite/migrations/migrateLocalSchema.js +2 -3
  64. package/data/sqlite/migrations/migrateLocalSchema.js.map +1 -1
  65. package/data/sqlite/sqlExec.d.ts +6 -0
  66. package/data/sqlite/sqlExec.js +64 -13
  67. package/data/sqlite/sqlExec.js.map +1 -1
  68. package/data/sqlite/sqlitePersistenceRuntime.js +2 -3
  69. package/data/sqlite/sqlitePersistenceRuntime.js.map +1 -1
  70. package/data/trustedUserIdentity/service.js +2 -1
  71. package/data/trustedUserIdentity/service.js.map +1 -1
  72. package/data/trustedUserIdentity/types.d.ts +1 -1
  73. package/data/trustedUserIdentity/types.js.map +1 -1
  74. package/internal/api-client/ApiClient.d.ts +4 -1
  75. package/internal/api-client/apiRequestRuntime.d.ts +6 -3
  76. package/internal/api-client/apiRequestRuntime.js +86 -101
  77. package/internal/api-client/apiRequestRuntime.js.map +1 -1
  78. package/internal/api-client/binaryRequestOperationTransport.js +2 -1
  79. package/internal/api-client/binaryRequestOperationTransport.js.map +1 -1
  80. package/internal/api-client/binaryResponseOperationTransport.js +6 -2
  81. package/internal/api-client/binaryResponseOperationTransport.js.map +1 -1
  82. package/internal/api-client/client/blobs.d.ts +1 -0
  83. package/internal/api-client/client/blobs.js +12 -3
  84. package/internal/api-client/client/blobs.js.map +1 -1
  85. package/internal/api-client/client/laneListingRequest.js +4 -0
  86. package/internal/api-client/client/laneListingRequest.js.map +1 -1
  87. package/internal/api-client/client/session.d.ts +5 -1
  88. package/internal/api-client/client/session.js +12 -4
  89. package/internal/api-client/client/session.js.map +1 -1
  90. package/internal/api-client/client/writerProjections.js +12 -13
  91. package/internal/api-client/client/writerProjections.js.map +1 -1
  92. package/internal/api-client/operationResponse.d.ts +1 -1
  93. package/internal/api-client/operationResponse.js +10 -23
  94. package/internal/api-client/operationResponse.js.map +1 -1
  95. package/internal/api-client/operationTransport.js +2 -1
  96. package/internal/api-client/operationTransport.js.map +1 -1
  97. package/internal/api-client/principalHistoryRequest.js +25 -20
  98. package/internal/api-client/principalHistoryRequest.js.map +1 -1
  99. package/internal/api-client/principalHistoryRequestContext.js +30 -6
  100. package/internal/api-client/principalHistoryRequestContext.js.map +1 -1
  101. package/internal/api-client/principalPolicyPages.d.ts +4 -1
  102. package/internal/api-client/principalPolicyPages.js +4 -2
  103. package/internal/api-client/principalPolicyPages.js.map +1 -1
  104. package/internal/api-client/projectionPolicyHistoryPages.d.ts +4 -1
  105. package/internal/api-client/projectionPolicyHistoryPages.js +4 -2
  106. package/internal/api-client/projectionPolicyHistoryPages.js.map +1 -1
  107. package/internal/api-client/routes/blobs/blobDownloadBody.js +65 -0
  108. package/internal/api-client/routes/blobs/blobDownloadBody.js.map +1 -0
  109. package/internal/api-client/routes/blobs/get.js +9 -67
  110. package/internal/api-client/routes/blobs/get.js.map +1 -1
  111. package/internal/api-client/routes/blobs/multipartUpload.js +1 -1
  112. package/internal/api-client/routes/blobs/multipartUpload.js.map +1 -1
  113. package/internal/api-client/sessionRefresh.js +1 -1
  114. package/internal/api-client/sessionRefresh.js.map +1 -1
  115. package/internal/api-client/sessionRenewal.d.ts +31 -0
  116. package/internal/api-client/sessionRenewal.js +91 -6
  117. package/internal/api-client/sessionRenewal.js.map +1 -1
  118. package/internal/api-client/sessionRequestInit.js +22 -0
  119. package/internal/api-client/sessionRequestInit.js.map +1 -0
  120. package/internal/api-client/sessionResponse.js +39 -0
  121. package/internal/api-client/sessionResponse.js.map +1 -0
  122. package/internal/api-client/types.d.ts +1 -0
  123. package/internal/api-client/types.js.map +1 -1
  124. package/internal/api-client/webSocketTickets.d.ts +1 -0
  125. package/internal/api-client/webSocketTickets.js +4 -0
  126. package/internal/api-client/webSocketTickets.js.map +1 -1
  127. package/internal/sqlite-worker/client.d.ts +1 -1
  128. package/internal/sqlite-worker/client.js +6 -1
  129. package/internal/sqlite-worker/client.js.map +1 -1
  130. package/internal/sqlite-worker/purgeOpfsDatabase.d.ts +1 -1
  131. package/internal/sqlite-worker/purgeOpfsDatabase.js +3 -2
  132. package/internal/sqlite-worker/purgeOpfsDatabase.js.map +1 -1
  133. package/internal/sqlite-worker/types.d.ts +4 -0
  134. package/internal/sqlite-worker/types.js.map +1 -1
  135. package/internal/validators/documentCreateSeedRefinements.js +2 -2
  136. package/internal/validators/documentCreateSeedRefinements.js.map +1 -1
  137. package/internal/validators/operation/auth.d.ts +50 -1703
  138. package/internal/validators/operation/auth.js +2 -2
  139. package/internal/validators/operation/auth.js.map +1 -1
  140. package/internal/validators/operation/containerMutations.d.ts +1 -294
  141. package/internal/validators/operation/containerMutations.js +2 -2
  142. package/internal/validators/operation/containerMutations.js.map +1 -1
  143. package/internal/validators/operation/documentMutations.d.ts +1 -294
  144. package/internal/validators/operation/documentMutations.js +2 -2
  145. package/internal/validators/operation/documentMutations.js.map +1 -1
  146. package/internal/validators/operation/organizations.d.ts +50 -1703
  147. package/internal/validators/operation/organizations.js +2 -2
  148. package/internal/validators/operation/organizations.js.map +1 -1
  149. package/internal/validators/organizationProvisioningRefinements.js +2 -2
  150. package/internal/validators/organizationProvisioningRefinements.js.map +1 -1
  151. package/internal/validators/request/containerMetadata.d.ts +0 -276
  152. package/internal/validators/request/containerMetadata.js +5 -4
  153. package/internal/validators/request/containerMetadata.js.map +1 -1
  154. package/internal/validators/request/document.d.ts +0 -277
  155. package/internal/validators/request/document.js +8 -4
  156. package/internal/validators/request/document.js.map +1 -1
  157. package/internal/validators/request/documentCreateSeed.d.ts +99 -0
  158. package/internal/validators/request/documentCreateSeed.js +132 -9
  159. package/internal/validators/request/documentCreateSeed.js.map +1 -1
  160. package/internal/validators/request/documentSyncSchema.d.ts +41 -0
  161. package/internal/validators/request/documentSyncSchema.js +1 -1
  162. package/internal/validators/request/documentSyncSchema.js.map +1 -1
  163. package/internal/validators/request/index.d.ts +1 -0
  164. package/internal/validators/request/index.js +1 -0
  165. package/internal/validators/request/index.js.map +1 -1
  166. package/internal/validators/request/organizationProvisioning.d.ts +263 -5567
  167. package/internal/validators/request/organizationProvisioning.js +10 -4
  168. package/internal/validators/request/organizationProvisioning.js.map +1 -1
  169. package/internal/validators/request/registration.d.ts +71 -1703
  170. package/package.json +1 -1
  171. package/sqlite/worker.js +1 -1
  172. package/workflows/container-contents/container-state/create/createWithMetadata.js +6 -3
  173. package/workflows/container-contents/container-state/create/createWithMetadata.js.map +1 -1
  174. package/workflows/documents/attachments/blobMutationLock.d.ts +1 -1
  175. package/workflows/documents/attachments/blobMutationLock.js +2 -2
  176. package/workflows/documents/attachments/blobMutationLock.js.map +1 -1
  177. package/workflows/documents/create/index.js +4 -4
  178. package/workflows/documents/create/index.js.map +1 -1
  179. package/workflows/documents/sync/initialSync.d.ts +26 -11
  180. package/workflows/documents/sync/initialSync.js +32 -12
  181. package/workflows/documents/sync/initialSync.js.map +1 -1
  182. package/workflows/organizations/readModel/readModelProjection.js +2 -0
  183. package/workflows/organizations/readModel/readModelProjection.js.map +1 -1
  184. package/workflows/registration/provisionedProfileDocument.js +2 -2
  185. package/workflows/registration/provisionedProfileDocument.js.map +1 -1
  186. package/workflows/registration/provisioningBootstrapBuilders.d.ts +0 -68
  187. package/workflows/registration/provisioningBootstrapBuilders.js +3 -3
  188. package/workflows/registration/provisioningBootstrapBuilders.js.map +1 -1
  189. package/workflows/registration/registerIdentity.js +2 -0
  190. package/workflows/registration/registerIdentity.js.map +1 -1
@@ -1,4 +1,5 @@
1
1
  import { blobWireHeaderKeys, getBlobBytesOperation, getBlobDownloadOperation, } from "../../../validators/operation/index.js";
2
+ import { blobDownloadBody } from "./blobDownloadBody.js";
2
3
  import { storageFetchOptions } from "./storageFetchOptions.js";
3
4
  /** A server without download descriptors (404) still streams the blob. */
4
5
  function descriptorFailureFallback(transport, blobId, failure, options) {
@@ -15,6 +16,8 @@ export async function getBlobBytes(transport, blobId, downloadFetch = (url, init
15
16
  if (options.signal?.aborted)
16
17
  return null;
17
18
  const result = await transport.requestResult(getBlobDownloadOperation, { params: { blobId } }, { ...options, reportErrors: false });
19
+ if (options.signal?.aborted)
20
+ return null;
18
21
  if (!result.ok) {
19
22
  return descriptorFailureFallback(transport, blobId, result, options);
20
23
  }
@@ -57,7 +60,7 @@ async function fetchSignedBlob(descriptor, url, downloadFetch, options) {
57
60
  await response.body?.cancel().catch(() => { });
58
61
  return response.status === 403 ? "retry" : "fallback";
59
62
  }
60
- return await signedBlobResponse(descriptor, response);
63
+ return await signedBlobResponse(descriptor, response, options.signal);
61
64
  }
62
65
  catch {
63
66
  // The downstream SDK still verifies length, hash and authenticated
@@ -65,50 +68,14 @@ async function fetchSignedBlob(descriptor, url, downloadFetch, options) {
65
68
  return "retry";
66
69
  }
67
70
  }
68
- async function signedBlobResponse(descriptor, response) {
71
+ async function signedBlobResponse(descriptor, response, signal) {
69
72
  return {
70
73
  blobId: descriptor.blobId,
71
74
  byteLength: descriptor.byteLength,
72
75
  sha256: descriptor.sha256,
73
- encryptedBytes: response.body
74
- ? signedDownloadBodyStream(response.body)
75
- : bufferedResponseBodyStream(await response.arrayBuffer()),
76
+ encryptedBytes: await blobDownloadBody(response, signal, true),
76
77
  };
77
78
  }
78
- function signedDownloadBodyStream(stream) {
79
- const reader = stream.getReader();
80
- // Native network errors may contain the bearer URL. Keep failures generic
81
- // before downstream readers log them, without buffering or eager reads.
82
- return new ReadableStream({
83
- async pull(controller) {
84
- try {
85
- const { done, value } = await reader.read();
86
- if (done) {
87
- controller.close();
88
- reader.releaseLock();
89
- }
90
- else {
91
- controller.enqueue(value);
92
- }
93
- }
94
- catch {
95
- controller.error(new Error("Blob download interrupted"));
96
- reader.releaseLock();
97
- }
98
- },
99
- async cancel(reason) {
100
- try {
101
- await reader.cancel(reason);
102
- }
103
- catch {
104
- throw new Error("Blob download cancellation failed");
105
- }
106
- finally {
107
- reader.releaseLock();
108
- }
109
- },
110
- }, { highWaterMark: 0 });
111
- }
112
79
  async function getBlobStream(transport, blobId, options) {
113
80
  if (options.signal?.aborted)
114
81
  return null;
@@ -120,18 +87,9 @@ async function getBlobStream(transport, blobId, options) {
120
87
  }
121
88
  const { headers, response } = result;
122
89
  const byteLength = Number(headers[blobWireHeaderKeys.blobByteLength]);
123
- // On the browser / WKWebView-fetch path the body is streamed, so
124
- // `response.body` is a live ReadableStream. Under a native HTTP bridge
125
- // (CapacitorHttp — which the Capacitor iOS/Android builds enable so cross-origin
126
- // API requests reach the backend at all; the WKWebView's own fetch fails from
127
- // the app's https://localhost origin) the response is buffered natively and
128
- // `response.body` is null even for a valid 200. So take the bytes either way:
129
- // the stream when present, otherwise buffer the response and re-wrap it as a
130
- // one-shot ReadableStream so callers keep a single streaming interface. This
131
- // does not weaken validation — a truncated or corrupted body is still caught
132
- // downstream by the X-Tearleads-Blob-Sha256 integrity check; it only stops a
133
- // buffered-but-valid response from being rejected here as malformed.
134
- const encryptedBytes = response.body ?? bufferedResponseBodyStream(await response.arrayBuffer());
90
+ const encryptedBytes = await blobDownloadBody(response, options.signal);
91
+ if (options.signal?.aborted)
92
+ return null;
135
93
  return {
136
94
  blobId: headers[blobWireHeaderKeys.blobId],
137
95
  byteLength,
@@ -139,20 +97,4 @@ async function getBlobStream(transport, blobId, options) {
139
97
  sha256: headers[blobWireHeaderKeys.blobSha256],
140
98
  };
141
99
  }
142
- // Wraps a fully-buffered response body as a single-chunk ReadableStream, so a
143
- // native HTTP bridge that only exposes the buffered bytes (no WHATWG
144
- // `response.body` stream) can still satisfy the streaming
145
- // `BlobBytesResponse.encryptedBytes` contract. An empty buffer yields an
146
- // immediately-closed, zero-chunk stream.
147
- function bufferedResponseBodyStream(buffer) {
148
- const bytes = new Uint8Array(buffer);
149
- return new ReadableStream({
150
- start(controller) {
151
- if (bytes.byteLength > 0) {
152
- controller.enqueue(bytes);
153
- }
154
- controller.close();
155
- },
156
- });
157
- }
158
100
  //# sourceMappingURL=get.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"get.js","sourceRoot":"","sources":["get.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,qBAAqB,EACrB,wBAAwB,GACzB,MAAM,iCAAiC,CAAC;AASzC,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AA4B5D,0EAA0E;AAC1E,SAAS,yBAAyB,CAChC,SAAgC,EAChC,MAAc,EACd,OAAuB,EACvB,OAA6B;IAE7B,IAAI,OAAO,CAAC,IAAI,KAAK,MAAM,IAAI,OAAO,CAAC,MAAM,KAAK,GAAG,EAAE,CAAC;QACtD,OAAO,aAAa,CAAC,SAAS,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;IACnD,CAAC;IACD,OAAO,CAAC,MAAM,EAAE,CAAC;IACjB,OAAO,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eys,\n getBlobBytesOperation,\n getBlobDownloadOperation,\n} from \"@tearleads/validators/operation\";\nimport type { MultipartBlobPartUploadSource } from \"@tearleads/validators/util\";\nimport type { BinaryResponseOperationTransport } from \"../../binaryResponseOperationTransport\";\nimport type { JsonOperationTransport } from \"../../operationTransport\";\nimport type {\n OperationResponseRequestFn,\n RequestFailure,\n RequestResultOptions,\n} from \"../../types\";\nimport { storageFetchOptions } from \"./storageFetchOptions\";\n\nexport interface BlobBytesResponse {\n readonly blobId: string;\n readonly byteLength: number;\n readonly encryptedBytes: ReadableStream<Uint8Array>;\n readonly sha256: string;\n}\n\nexport interface UploadMultipartBlobPartBytesRequest {\n readonly byteLength: number;\n readonly encryptedBytes: Blob | BufferSource;\n readonly sha256: string;\n /**\n * An upload source the stage initiation already issued for this part. The\n * first attempt uses it instead of authorizing; a failed attempt still\n * reauthorizes once, exactly as when no source was issued.\n */\n readonly source?: MultipartBlobPartUploadSource | undefined;\n readonly uploadId: string;\n}\n\ntype BlobDownloadTransport = Pick<JsonOperationTransport, \"requestResult\"> &\n Pick<BinaryResponseOperationTransport, \"requestBinaryResponse\"> &\n Pick<OperationResponseRequestFn, \"reportFailure\">;\n\ntype DownloadFetch = (url: string, init: RequestInit) => Promise<Response>;\n\n/** A server without download descriptors (404) still streams the blob. */\nfunction descriptorFailureFallback(\n transport: BlobDownloadTransport,\n blobId: string,\n failure: RequestFailure,\n options: RequestResultOptions,\n): Promise<BlobBytesResponse | null> | null {\n if (failure.kind === \"http\" && failure.status === 404) {\n return getBlobStream(transport, blobId, options);\n }\n failure.report();\n return null;\n}\n\nexport async function getBlobBytes(\n transport: BlobDownloadTransport,\n blobId: string,\n downloadFetch: DownloadFetch = (url, init) => fetch(url, init),\n options: RequestResultOptions = {},\n): Promise<BlobBytesResponse | null> {\n // Refresh at most once. R2 expiration errors can appear as CORS/network\n // failures in browsers, so both rejected fetches and 403s need a fresh URL.\n for (let attempt = 0; attempt < 2; attempt += 1) {\n if (options.signal?.aborted) return null;\n const result = await transport.requestResult(\n getBlobDownloadOperation,\n { params: { blobId } },\n { ...options, reportErrors: false },\n );\n if (!result.ok) {\n return descriptorFailureFallback(transport, blobId, result, options);\n }\n const descriptor = result.data;\n if (descriptor.blobId !== blobId) {\n transport.reportFailure({\n kind: \"shape\",\n method: \"GET\",\n path: `/blobs/${blobId}/download`,\n status: 200,\n statusText: \"\",\n message: `Blob ${blobId} download descriptor has the wrong identity`,\n });\n return null;\n }\n if (descriptor.source.kind === \"api\") {\n return getBlobStream(transport, blobId, options);\n }\n const outcome = await fetchSignedBlob(\n descriptor,\n descriptor.source.url,\n downloadFetch,\n options,\n );\n if (outcome === \"fallback\") break;\n if (outcome !== \"retry\") return outcome;\n }\n // Preserve downloads when storage is unreachable or a native HTTP bridge\n // cannot use the signed URL. This endpoint checks current access again.\n // A storage failure alone must not signal that the API is offline.\n return getBlobStream(transport, blobId, options);\n}\n\n/**\n * One signed-URL attempt: the bytes, `\"retry\"` with a fresh URL (403 or a\n * rejected fetch), or `\"fallback\"` to the API stream (any other status).\n */\nasync function fetchSignedBlob(\n descriptor: Pick<BlobBytesResponse, \"blobId\" | \"byteLength\" | \"sha256\">,\n url: string,\n downloadFetch: DownloadFetch,\n options: RequestResultOptions,\n): Promise<BlobBytesResponse | \"retry\" | \"fallback\"> {\n try {\n // Never send the application's session or cookies to the object store.\n // Reject redirects and keep bearer URLs out of referrers and errors.\n const response = await downloadFetch(url, storageFetchOptions(options));\n if (response.status !== 200) {\n await response.body?.cancel().catch(() => {});\n return response.status === 403 ? \"retry\" : \"fallback\";\n }\n return await signedBlobResponse(descriptor, response);\n } catch {\n // The downstream SDK still verifies length, hash and authenticated\n // encryption. An error after streaming begins propagates to that reader.\n return \"retry\";\n }\n}\n\nasync function signedBlobResponse(\n descriptor: Pick<BlobBytesResponse, \"blobId\" | \"byteLength\" | \"sha256\">,\n response: Response,\n): Promise<BlobBytesResponse> {\n return {\n blobId: descriptor.blobId,\n byteLength: descriptor.byteLength,\n sha256: descriptor.sha256,\n encryptedBytes: response.body\n ? signedDownloadBodyStream(response.body)\n : bufferedResponseBodyStream(await response.arrayBuffer()),\n };\n}\n\nfunction signedDownloadBodyStream(\n stream: ReadableStream<Uint8Array>,\n): ReadableStream<Uint8Array> {\n const reader = stream.getReader();\n // Native network errors may contain the bearer URL. Keep failures generic\n // before downstream readers log them, without buffering or eager reads.\n return new ReadableStream<Uint8Array>(\n {\n async pull(controller) {\n try {\n const { done, value } = await reader.read();\n if (done) {\n controller.close();\n reader.releaseLock();\n } else {\n controller.enqueue(value);\n }\n } catch {\n controller.error(new Error(\"Blob download interrupted\"));\n reader.releaseLock();\n }\n },\n async cancel(reason) {\n try {\n await reader.cancel(reason);\n } catch {\n throw new Error(\"Blob download cancellation failed\");\n } finally {\n reader.releaseLock();\n }\n },\n },\n { highWaterMark: 0 },\n );\n}\n\nasync function getBlobStream(\n transport: Pick<BinaryResponseOperationTransport, \"requestBinaryResponse\">,\n blobId: string,\n options: RequestResultOptions,\n): Promise<BlobBytesResponse | null> {\n if (options.signal?.aborted) return null;\n const result = await transport.requestBinaryResponse(\n getBlobBytesOperation,\n {\n params: { blobId },\n },\n options,\n );\n if (!result) {\n return null;\n }\n\n const { headers, response } = result;\n const byteLength = Number(headers[blobWireHeaderKeys.blobByteLength]);\n\n // On the browser / WKWebView-fetch path the body is streamed, so\n // `response.body` is a live ReadableStream. Under a native HTTP bridge\n // (CapacitorHttp — which the Capacitor iOS/Android builds enable so cross-origin\n // API requests reach the backend at all; the WKWebView's own fetch fails from\n // the app's https://localhost origin) the response is buffered natively and\n // `response.body` is null even for a valid 200. So take the bytes either way:\n // the stream when present, otherwise buffer the response and re-wrap it as a\n // one-shot ReadableStream so callers keep a single streaming interface. This\n // does not weaken validation — a truncated or corrupted body is still caught\n // downstream by the X-Tearleads-Blob-Sha256 integrity check; it only stops a\n // buffered-but-valid response from being rejected here as malformed.\n const encryptedBytes =\n response.body ?? bufferedResponseBodyStream(await response.arrayBuffer());\n\n return {\n blobId: headers[blobWireHeaderKeys.blobId],\n byteLength,\n encryptedBytes,\n sha256: headers[blobWireHeaderKeys.blobSha256],\n };\n}\n\n// Wraps a fully-buffered response body as a single-chunk ReadableStream, so a\n// native HTTP bridge that only exposes the buffered bytes (no WHATWG\n// `response.body` stream) can still satisfy the streaming\n// `BlobBytesResponse.encryptedBytes` contract. An empty buffer yields an\n// immediately-closed, zero-chunk stream.\nfunction bufferedResponseBodyStream(\n buffer: ArrayBuffer,\n): ReadableStream<Uint8Array> {\n const bytes = new Uint8Array(buffer);\n return new ReadableStream<Uint8Array>({\n start(controller) {\n if (bytes.byteLength > 0) {\n controller.enqueue(bytes);\n }\n controller.close();\n },\n });\n}\n"]}
1
+ {"version":3,"file":"get.js","sourceRoot":"","sources":["get.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,qBAAqB,EACrB,wBAAwB,GACzB,MAAM,iCAAiC,CAAC;AASzC,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AA4B5D,0EAA0E;AAC1E,SAAS,yBAAyB,CAChC,SAAgC,EAChC,MAAc,EACd,OAAuB,EACvB,OAA6B;IAE7B,IAAI,OAAO,CAAC,IAAI,KAAK,MAAM,IAAI,OAAO,CAAC,MAAM,KAAK,GAAG,EAAE,CAAC;QACtD,OAAO,aAAa,CAAC,SAAS,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;IACnD,CAAC;IACD,OAAO,CAAC,MAAM,EAAE,CAAC;IACjB,OAAO,IAAI,CAAC;AACd,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,YAAY,CAChC,SAAgC,EAChC,MAAc,EACd,gBAA+B,CAAC,GAAG,EAAE,IAAI,EAAE,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,IAAI,CAAC,EAC9D,UAAgC,EAAE;IAElC,wEAAwE;IACxE,4EAA4E;IAC5E,KAAK,IAAI,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OAAO,IAAI,CAAC;IACzC,MAAM,MAAM,GAAG,MAAM,SAAS,CAAC,qBAAqB,CAClD,qBAAqB,EACrB;QACE,MAAM,EAAE,EAAE,MAAM,EAAE;KACnB,EACD,OAAO,CACR,CAAC;IACF,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,OAAO,IAAI,CAAC;IACd,CAAC;IAED,MAAM,EAAE,OAAO,EAAE,QAAQ,EAAE,GAAG,MAAM,CAAC;IACrC,MAAM,UAAU,GAAG,MAAM,CAAC,OAAO,CAAC,kBAAkB,CAAC,cAAc,CAAC,CAAC,CAAC;IAEtE,MAAM,cAAc,GAAG,MAAM,gBAAgB,CAAC,QAAQ,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC;IAExE,IAAI,OAAO,CAAC,MAAM,EAAE,OAAO;QAAE,OAAO,IAAI,CAAC;IACzC,OAAO;QACL,MAAM,EAAE,OAAO,CAAC,kBAAkB,CAAC,MAAM,CAAC;QAC1C,UAAU;QACV,cAAc;QACd,MAAM,EAAE,OAAO,CAAC,kBAAkB,CAAC,UAAU,CAAC;KAC/C,CAAC;AACJ,CAAC","sourcesContent":["import {\n blobWireHeaderKeys,\n getBlobBytesOperation,\n getBlobDownloadOperation,\n} from \"@tearleads/validators/operation\";\nimport type { MultipartBlobPartUploadSource } from \"@tearleads/validators/util\";\nimport type { BinaryResponseOperationTransport } from \"../../binaryResponseOperationTransport\";\nimport type { JsonOperationTransport } from \"../../operationTransport\";\nimport type {\n OperationResponseRequestFn,\n RequestFailure,\n RequestResultOptions,\n} from \"../../types\";\nimport { blobDownloadBody } from \"./blobDownloadBody\";\nimport { storageFetchOptions } from \"./storageFetchOptions\";\n\nexport interface BlobBytesResponse {\n readonly blobId: string;\n readonly byteLength: number;\n readonly encryptedBytes: ReadableStream<Uint8Array>;\n readonly sha256: string;\n}\n\nexport interface UploadMultipartBlobPartBytesRequest {\n readonly byteLength: number;\n readonly encryptedBytes: Blob | BufferSource;\n readonly sha256: string;\n /**\n * An upload source the stage initiation already issued for this part. The\n * first attempt uses it instead of authorizing; a failed attempt still\n * reauthorizes once, exactly as when no source was issued.\n */\n readonly source?: MultipartBlobPartUploadSource | undefined;\n readonly uploadId: string;\n}\n\ntype BlobDownloadTransport = Pick<JsonOperationTransport, \"requestResult\"> &\n Pick<BinaryResponseOperationTransport, \"requestBinaryResponse\"> &\n Pick<OperationResponseRequestFn, \"reportFailure\">;\n\ntype DownloadFetch = (url: string, init: RequestInit) => Promise<Response>;\n\n/** A server without download descriptors (404) still streams the blob. */\nfunction descriptorFailureFallback(\n transport: BlobDownloadTransport,\n blobId: string,\n failure: RequestFailure,\n options: RequestResultOptions,\n): Promise<BlobBytesResponse | null> | null {\n if (failure.kind === \"http\" && failure.status === 404) {\n return getBlobStream(transport, blobId, options);\n }\n failure.report();\n return null;\n}\n\nexport async function getBlobBytes(\n transport: BlobDownloadTransport,\n blobId: string,\n downloadFetch: DownloadFetch = (url, init) => fetch(url, init),\n options: RequestResultOptions = {},\n): Promise<BlobBytesResponse | null> {\n // Refresh at most once. R2 expiration errors can appear as CORS/network\n // failures in browsers, so both rejected fetches and 403s need a fresh URL.\n for (let attempt = 0; attempt < 2; attempt += 1) {\n if (options.signal?.aborted) return null;\n const result = await transport.requestResult(\n getBlobDownloadOperation,\n { params: { blobId } },\n { ...options, reportErrors: false },\n );\n if (options.signal?.aborted) return null;\n if (!result.ok) {\n return descriptorFailureFallback(transport, blobId, result, options);\n }\n const descriptor = result.data;\n if (descriptor.blobId !== blobId) {\n transport.reportFailure({\n kind: \"shape\",\n method: \"GET\",\n path: `/blobs/${blobId}/download`,\n status: 200,\n statusText: \"\",\n message: `Blob ${blobId} download descriptor has the wrong identity`,\n });\n return null;\n }\n if (descriptor.source.kind === \"api\") {\n return getBlobStream(transport, blobId, options);\n }\n const outcome = await fetchSignedBlob(\n descriptor,\n descriptor.source.url,\n downloadFetch,\n options,\n );\n if (outcome === \"fallback\") break;\n if (outcome !== \"retry\") return outcome;\n }\n // Preserve downloads when storage is unreachable or a native HTTP bridge\n // cannot use the signed URL. This endpoint checks current access again.\n // A storage failure alone must not signal that the API is offline.\n return getBlobStream(transport, blobId, options);\n}\n\n/**\n * One signed-URL attempt: the bytes, `\"retry\"` with a fresh URL (403 or a\n * rejected fetch), or `\"fallback\"` to the API stream (any other status).\n */\nasync function fetchSignedBlob(\n descriptor: Pick<BlobBytesResponse, \"blobId\" | \"byteLength\" | \"sha256\">,\n url: string,\n downloadFetch: DownloadFetch,\n options: RequestResultOptions,\n): Promise<BlobBytesResponse | \"retry\" | \"fallback\"> {\n try {\n // Never send the application's session or cookies to the object store.\n // Reject redirects and keep bearer URLs out of referrers and errors.\n const response = await downloadFetch(url, storageFetchOptions(options));\n if (response.status !== 200) {\n await response.body?.cancel().catch(() => {});\n return response.status === 403 ? \"retry\" : \"fallback\";\n }\n return await signedBlobResponse(descriptor, response, options.signal);\n } catch {\n // The downstream SDK still verifies length, hash and authenticated\n // encryption. An error after streaming begins propagates to that reader.\n return \"retry\";\n }\n}\n\nasync function signedBlobResponse(\n descriptor: Pick<BlobBytesResponse, \"blobId\" | \"byteLength\" | \"sha256\">,\n response: Response,\n signal: AbortSignal | undefined,\n): Promise<BlobBytesResponse> {\n return {\n blobId: descriptor.blobId,\n byteLength: descriptor.byteLength,\n sha256: descriptor.sha256,\n encryptedBytes: await blobDownloadBody(response, signal, true),\n };\n}\n\nasync function getBlobStream(\n transport: Pick<BinaryResponseOperationTransport, \"requestBinaryResponse\">,\n blobId: string,\n options: RequestResultOptions,\n): Promise<BlobBytesResponse | null> {\n if (options.signal?.aborted) return null;\n const result = await transport.requestBinaryResponse(\n getBlobBytesOperation,\n {\n params: { blobId },\n },\n options,\n );\n if (!result) {\n return null;\n }\n\n const { headers, response } = result;\n const byteLength = Number(headers[blobWireHeaderKeys.blobByteLength]);\n\n const encryptedBytes = await blobDownloadBody(response, options.signal);\n\n if (options.signal?.aborted) return null;\n return {\n blobId: headers[blobWireHeaderKeys.blobId],\n byteLength,\n encryptedBytes,\n sha256: headers[blobWireHeaderKeys.blobSha256],\n };\n}\n"]}
@@ -147,7 +147,7 @@ export async function uploadMultipartBlobPartBytes(transport, stageId, partNumbe
147
147
  return null;
148
148
  const source = firstAttemptSource(attempt, input.source) ??
149
149
  (await authorizePart(context));
150
- if (!source)
150
+ if (!source || options.signal?.aborted)
151
151
  return null;
152
152
  if (source.kind === "api")
153
153
  return uploadThroughApi(context, file);
@@ -1 +1 @@
1
- {"version":3,"file":"multipartUpload.js","sourceRoot":"","sources":["multipartUpload.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,yBAAyB,CAAC;AAC9C,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAC/C,OAAO,EACL,yCAAyC,EACzC,kBAAkB,EAClB,oBAAoB,EACpB,qCAAqC,GACtC,MAAM,iCAAiC,CAAC;AAEzC,OAAO,EACL,6BAA6B,GAG9B,MAAM,4BAA4B,CAAC;AAIpC,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAI5D,SAAS,WAAW,CAAC,SAA6B,EAAE,IAAY;IAC9D,SAAS,CAAC,aAAa,CAAC;QACtB,IAAI,EAAE,OAAO;QACb,MAAM,EAAE,yCAAyC,CAAC,MAAM;QACxD,IAAI;QACJ,MAAM,EAAE,IAAI;QACZ,UAAU,EAAE,EAAE;QACd,OAAO,EAAE,kEAAkE;KAC5E,CAAC,CAAC;IACH,OAAO,IAAI,CAAC;AACd,CAAC;AAED,KAAK,UAAU,kBAAkB,CAAC,MAAc,EAAE,OAAe;IAC/D,IAAI,MAAM,KAAK,GAAG;QAAE,OAAO,IAAI,CAAC;IAChC,MAAM,SAAS,GAAG,MAAM,KAAK,GAAG,IAAI,CAAC,MAAM,IAAI,GAAG,IAAI,MAAM,IAAI,GAAG,CAAC,CAAC;IACrE,IAAI,SAAS,IAAI,OAAO,KAAK,CAAC,EAAE,CAAC;QAC/B,MAAM,IAAI,OAAO,CAAO,CAA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,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;QAC9C,IAAI,MAAM,KAAK,GAAG,IAAI,IAAI,EAAE,CAAC;YAC3B,OAAO;gBACL,IAAI,EAAE,UAAU;gBAChB,QAAQ,EAAE;oBACR,OAAO,EAAE,OAAO,CAAC,OAAO;oBACxB,QAAQ,EAAE,KAAK,CAAC,QAAQ;oBACxB,IAAI,EAAE,EAAE,UAAU,EAAE,KAAK,CAAC,UAAU,EAAE,UAAU,EAAE,IAAI,EAAE;iBACzD;aACF,CAAC;QACJ,CAAC;QACD,MAAM,KAAK,GAAG,MAAM,kBAAkB,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;QACxD,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC;IAC3C,CAAC;IAAC,MAAM,CAAC;QACP,4EAA4E;QAC5E,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC;IACvD,CAAC;AACH,CAAC;AAED,SAAS,oBAAoB,CAC3B,SAA6B,EAC7B,IAAY,EACZ,UAAkB,EAClB,MAAqB;IAErB,SAAS,CAAC,aAAa,CAAC;QACtB,IAAI,EAAE,SAAS;QACf,MAAM,EAAE,yCAAyC,CAAC,MAAM;QACxD,IAAI;QACJ,MAAM;QACN,UAAU,EAAE,EAAE;QACd,OAAO,EACL,MAAM,KAAK,GAAG;YACZ,CAAC,CAAC,kBAAkB,UAAU,gEAAgE;YAC9F,CAAC,CAAC,kBAAkB,UAAU,yBAAyB,MAAM,KAAK,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,UAAU,MAAM,GAAG,EAAE;KACxG,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { md5 } from \"@noble/hashes/legacy.js\";\nimport { bytesToHex } from \"@tearleads/crypto\";\nimport {\n authorizeMultipartBlobPartUploadOperation,\n blobWireHeaderKeys,\n operationRequestPath,\n uploadMultipartBlobPartBytesOperation,\n} from \"@tearleads/validators/operation\";\nimport type { UploadMultipartBlobPartResponse } from \"@tearleads/validators/response\";\nimport {\n MAX_MULTIPART_BLOB_PART_BYTES,\n type MultipartBlobPartDescriptor,\n type MultipartBlobPartUploadSource,\n} from \"@tearleads/validators/util\";\nimport type { OperationTransport } from \"../../operationTransportFactory\";\nimport type { RequestResultOptions } from \"../../types\";\nimport type { UploadMultipartBlobPartBytesRequest } from \"./get\";\nimport { storageFetchOptions } from \"./storageFetchOptions\";\n\ntype UploadFetch = (url: string, init: RequestInit) => Promise<Response>;\n\nfunction invalidPart(transport: OperationTransport, path: string) {\n transport.reportFailure({\n kind: \"shape\",\n method: authorizeMultipartBlobPartUploadOperation.method,\n path,\n status: null,\n statusText: \"\",\n message: \"Multipart part bytes do not match the declared length or SHA-256\",\n });\n return null;\n}\n\nasync function retryStorageStatus(status: number, attempt: number) {\n if (status === 403) return true;\n const transient = status === 429 || (status >= 500 && status <= 599);\n if (transient && attempt === 0) {\n await new Promise<void>((resolve) => setTimeout(resolve, 250));\n }\n return transient;\n}\n\nfunction contentMd5Base64(bytes: Uint8Array): string {\n return btoa(String.fromCharCode(...md5(bytes)));\n}\n\n/**\n * Describe an encrypted part the way a stage initiation lists the parts it\n * will send first: number, exact length, and the Content-MD5 a signed upload\n * URL binds.\n */\nexport function describeMultipartBlobPart(\n partNumber: number,\n encryptedBytes: Uint8Array,\n): MultipartBlobPartDescriptor {\n return {\n byteLength: encryptedBytes.byteLength,\n contentMd5: contentMd5Base64(encryptedBytes),\n partNumber,\n };\n}\n\nasync function preparePart(input: UploadMultipartBlobPartBytesRequest) {\n // File snapshots mutable buffers and preserves ciphertext across Capacitor's\n // native HTTP bridge. Uint8Array is UTF-8 decoded there; a plain Blob becomes\n // JSON. File's base64 bridge path is byte-for-byte, including non-UTF-8 data.\n const file =\n input.encryptedBytes instanceof File\n ? input.encryptedBytes\n : new File([input.encryptedBytes], \"encrypted-blob-part\", {\n type: \"application/octet-stream\",\n });\n if (\n file.size !== input.byteLength ||\n file.size < 1 ||\n file.size > MAX_MULTIPART_BLOB_PART_BYTES\n ) {\n throw new TypeError(\"Invalid multipart part byte length\");\n }\n const bytes = await file.arrayBuffer();\n if (\n bytesToHex(new Uint8Array(await crypto.subtle.digest(\"SHA-256\", bytes))) !==\n input.sha256\n ) {\n throw new TypeError(\"Multipart part SHA-256 does not match its bytes\");\n }\n return { file, contentMd5: contentMd5Base64(new Uint8Array(bytes)) };\n}\n\ninterface PartUploadContext {\n readonly contentMd5: string;\n readonly input: UploadMultipartBlobPartBytesRequest;\n readonly options: RequestResultOptions;\n readonly partNumber: number;\n readonly path: string;\n readonly stageId: string;\n readonly transport: OperationTransport;\n}\n\n// Sign just in time for this part. The returned descriptor must name exactly\n// the part, upload, length, and checksum that were requested.\nasync function authorizePart(\n context: PartUploadContext,\n): Promise<MultipartBlobPartUploadSource | null> {\n const operation = authorizeMultipartBlobPartUploadOperation;\n const { input, partNumber, stageId } = context;\n const result = await context.transport.requestResult(\n operation,\n {\n params: { stageId, partNumber },\n body: {\n byteLength: input.byteLength,\n contentMd5: context.contentMd5,\n uploadId: input.uploadId,\n },\n },\n context.options,\n );\n if (!result.ok) return null;\n const descriptor = result.data;\n if (\n descriptor.stageId !== stageId ||\n descriptor.uploadId !== input.uploadId ||\n descriptor.partNumber !== partNumber ||\n descriptor.byteLength !== input.byteLength ||\n descriptor.contentMd5 !== context.contentMd5\n ) {\n context.transport.reportFailure({\n kind: \"shape\",\n method: operation.method,\n path: context.path,\n status: 200,\n statusText: \"\",\n message: \"Multipart upload descriptor does not match its part\",\n });\n return null;\n }\n return descriptor.source;\n}\n\n// Parts can wait behind other transfers in the shared pool. An issued URL that\n// is about to lapse would only spend this part's retry on a certain 403, so\n// authorize afresh instead; a skewed clock errs toward authorizing.\nconst ISSUED_URL_MIN_REMAINING_MS = 30_000;\n\nfunction isUsableIssuedSource(\n source: MultipartBlobPartUploadSource | undefined,\n): source is MultipartBlobPartUploadSource {\n return (\n source !== undefined &&\n (source.kind === \"api\" ||\n Date.parse(source.expiresAt) - Date.now() > ISSUED_URL_MIN_REMAINING_MS)\n );\n}\n\n// A capability path for memory/custom stores; S3/R2 never proxy parts.\nfunction uploadThroughApi(context: PartUploadContext, file: File) {\n const { input } = context;\n return context.transport.requestBinaryRequest(\n uploadMultipartBlobPartBytesOperation,\n {\n params: { stageId: context.stageId, partNumber: context.partNumber },\n body: input.encryptedBytes,\n headers: {\n [blobWireHeaderKeys.partByteLength]: input.byteLength.toString(),\n [blobWireHeaderKeys.partSha256]: input.sha256,\n [blobWireHeaderKeys.partUploadId]: input.uploadId,\n },\n },\n { ...context.options, encodeBody: () => file },\n );\n}\n\nfunction firstAttemptSource(\n attempt: number,\n source: MultipartBlobPartUploadSource | undefined,\n): MultipartBlobPartUploadSource | null {\n return attempt === 0 && isUsableIssuedSource(source) ? source : null;\n}\n\nexport async function uploadMultipartBlobPartBytes(\n transport: OperationTransport,\n stageId: string,\n partNumber: number,\n input: UploadMultipartBlobPartBytesRequest,\n uploadFetch: UploadFetch = (url, init) => fetch(url, init),\n options: RequestResultOptions = {},\n): Promise<UploadMultipartBlobPartResponse | null> {\n if (options.signal?.aborted) return null;\n const path = operationRequestPath(authorizeMultipartBlobPartUploadOperation, {\n stageId,\n partNumber,\n });\n const prepared = await preparePart(input).catch(() =>\n invalidPart(transport, path),\n );\n if (!prepared) return null;\n const { file, contentMd5 } = prepared;\n const context: PartUploadContext = {\n contentMd5,\n input,\n options,\n partNumber,\n path,\n stageId,\n transport,\n };\n let status: number | null = null;\n // The first attempt uses the source the stage initiation issued, if any. A\n // network failure may be an expired URL hidden by R2 CORS, or a lost success\n // response; reauthorize once and send the same immutable bytes to the same\n // part number.\n for (let attempt = 0; attempt < 2; attempt += 1) {\n if (options.signal?.aborted) return null;\n const source =\n firstAttemptSource(attempt, input.source) ??\n (await authorizePart(context));\n if (!source) return null;\n if (source.kind === \"api\") return uploadThroughApi(context, file);\n const outcome = await putStoragePart(\n context,\n file,\n source.url,\n uploadFetch,\n attempt,\n );\n if (outcome.kind === \"uploaded\") return outcome.response;\n status = outcome.status;\n if (!outcome.retry) break;\n }\n reportStorageFailureUnlessAborted(context, status);\n return null;\n}\n\nfunction reportStorageFailureUnlessAborted(\n context: PartUploadContext,\n status: number | null,\n): void {\n if (context.options.signal?.aborted) return;\n reportStorageFailure(\n context.transport,\n context.path,\n context.partNumber,\n status,\n );\n}\n\ntype StoragePartAttempt =\n | {\n readonly kind: \"uploaded\";\n readonly response: UploadMultipartBlobPartResponse;\n }\n | {\n readonly kind: \"failed\";\n readonly retry: boolean;\n readonly status: number | null;\n };\n\nasync function putStoragePart(\n context: PartUploadContext,\n file: File,\n url: string,\n uploadFetch: UploadFetch,\n attempt: number,\n): Promise<StoragePartAttempt> {\n const { input, partNumber } = context;\n try {\n const response = await uploadFetch(url, {\n method: \"PUT\",\n body: file,\n headers: {\n \"Content-Type\": \"application/octet-stream\",\n \"Content-MD5\": context.contentMd5,\n },\n ...storageFetchOptions(context.options),\n });\n const status = response.status;\n const etag = response.headers.get(\"ETag\")?.trim();\n await response.body?.cancel().catch(() => {});\n if (status === 200 && etag) {\n return {\n kind: \"uploaded\",\n response: {\n stageId: context.stageId,\n uploadId: input.uploadId,\n part: { byteLength: input.byteLength, partNumber, etag },\n },\n };\n }\n const retry = await retryStorageStatus(status, attempt);\n return { kind: \"failed\", retry, status };\n } catch {\n // Never expose a provider exception or body: it may contain the bearer URL.\n return { kind: \"failed\", retry: true, status: null };\n }\n}\n\nfunction reportStorageFailure(\n transport: OperationTransport,\n path: string,\n partNumber: number,\n status: number | null,\n) {\n transport.reportFailure({\n kind: \"storage\",\n method: authorizeMultipartBlobPartUploadOperation.method,\n path,\n status,\n statusText: \"\",\n message:\n status === 200\n ? `Multipart part ${partNumber} storage response is missing ETag; check storage CORS exposure`\n : `Multipart part ${partNumber} storage upload failed${status === null ? \"\" : ` (HTTP ${status})`}`,\n });\n}\n"]}
1
+ {"version":3,"file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,EAAE,KAAK,CAAC,UAAU,EAAE,UAAU,EAAE,IAAI,EAAE;iBACzD;aACF,CAAC;QACJ,CAAC;QACD,MAAM,KAAK,GAAG,MAAM,kBAAkB,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;QACxD,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC;IAC3C,CAAC;IAAC,MAAM,CAAC;QACP,4EAA4E;QAC5E,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC;IACvD,CAAC;AACH,CAAC;AAED,SAAS,oBAAoB,CAC3B,SAA6B,EAC7B,IAAY,EACZ,UAAkB,EAClB,MAAqB;IAErB,SAAS,CAAC,aAAa,CAAC;QACtB,IAAI,EAAE,SAAS;QACf,MAAM,EAAE,yCAAyC,CAAC,MAAM;QACxD,IAAI;QACJ,MAAM;QACN,UAAU,EAAE,EAAE;QACd,OAAO,EACL,MAAM,KAAK,GAAG;YACZ,CAAC,CAAC,kBAAkB,UAAU,gEAAgE;YAC9F,CAAC,CAAC,kBAAkB,UAAU,yBAAyB,MAAM,KAAK,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,UAAU,MAAM,GAAG,EAAE;KACxG,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { md5 } from \"@noble/hashes/legacy.js\";\nimport { bytesToHex } from \"@tearleads/crypto\";\nimport {\n authorizeMultipartBlobPartUploadOperation,\n blobWireHeaderKeys,\n operationRequestPath,\n uploadMultipartBlobPartBytesOperation,\n} from \"@tearleads/validators/operation\";\nimport type { UploadMultipartBlobPartResponse } from \"@tearleads/validators/response\";\nimport {\n MAX_MULTIPART_BLOB_PART_BYTES,\n type MultipartBlobPartDescriptor,\n type MultipartBlobPartUploadSource,\n} from \"@tearleads/validators/util\";\nimport type { OperationTransport } from \"../../operationTransportFactory\";\nimport type { RequestResultOptions } from \"../../types\";\nimport type { UploadMultipartBlobPartBytesRequest } from \"./get\";\nimport { storageFetchOptions } from \"./storageFetchOptions\";\n\ntype UploadFetch = (url: string, init: RequestInit) => Promise<Response>;\n\nfunction invalidPart(transport: OperationTransport, path: string) {\n transport.reportFailure({\n kind: \"shape\",\n method: authorizeMultipartBlobPartUploadOperation.method,\n path,\n status: null,\n statusText: \"\",\n message: \"Multipart part bytes do not match the declared length or SHA-256\",\n });\n return null;\n}\n\nasync function retryStorageStatus(status: number, attempt: number) {\n if (status === 403) return true;\n const transient = status === 429 || (status >= 500 && status <= 599);\n if (transient && attempt === 0) {\n await new Promise<void>((resolve) => setTimeout(resolve, 250));\n }\n return transient;\n}\n\nfunction contentMd5Base64(bytes: Uint8Array): string {\n return btoa(String.fromCharCode(...md5(bytes)));\n}\n\n/**\n * Describe an encrypted part the way a stage initiation lists the parts it\n * will send first: number, exact length, and the Content-MD5 a signed upload\n * URL binds.\n */\nexport function describeMultipartBlobPart(\n partNumber: number,\n encryptedBytes: Uint8Array,\n): MultipartBlobPartDescriptor {\n return {\n byteLength: encryptedBytes.byteLength,\n contentMd5: contentMd5Base64(encryptedBytes),\n partNumber,\n };\n}\n\nasync function preparePart(input: UploadMultipartBlobPartBytesRequest) {\n // File snapshots mutable buffers and preserves ciphertext across Capacitor's\n // native HTTP bridge. Uint8Array is UTF-8 decoded there; a plain Blob becomes\n // JSON. File's base64 bridge path is byte-for-byte, including non-UTF-8 data.\n const file =\n input.encryptedBytes instanceof File\n ? input.encryptedBytes\n : new File([input.encryptedBytes], \"encrypted-blob-part\", {\n type: \"application/octet-stream\",\n });\n if (\n file.size !== input.byteLength ||\n file.size < 1 ||\n file.size > MAX_MULTIPART_BLOB_PART_BYTES\n ) {\n throw new TypeError(\"Invalid multipart part byte length\");\n }\n const bytes = await file.arrayBuffer();\n if (\n bytesToHex(new Uint8Array(await crypto.subtle.digest(\"SHA-256\", bytes))) !==\n input.sha256\n ) {\n throw new TypeError(\"Multipart part SHA-256 does not match its bytes\");\n }\n return { file, contentMd5: contentMd5Base64(new Uint8Array(bytes)) };\n}\n\ninterface PartUploadContext {\n readonly contentMd5: string;\n readonly input: UploadMultipartBlobPartBytesRequest;\n readonly options: RequestResultOptions;\n readonly partNumber: number;\n readonly path: string;\n readonly stageId: string;\n readonly transport: OperationTransport;\n}\n\n// Sign just in time for this part. The returned descriptor must name exactly\n// the part, upload, length, and checksum that were requested.\nasync function authorizePart(\n context: PartUploadContext,\n): Promise<MultipartBlobPartUploadSource | null> {\n const operation = authorizeMultipartBlobPartUploadOperation;\n const { input, partNumber, stageId } = context;\n const result = await context.transport.requestResult(\n operation,\n {\n params: { stageId, partNumber },\n body: {\n byteLength: input.byteLength,\n contentMd5: context.contentMd5,\n uploadId: input.uploadId,\n },\n },\n context.options,\n );\n if (!result.ok) return null;\n const descriptor = result.data;\n if (\n descriptor.stageId !== stageId ||\n descriptor.uploadId !== input.uploadId ||\n descriptor.partNumber !== partNumber ||\n descriptor.byteLength !== input.byteLength ||\n descriptor.contentMd5 !== context.contentMd5\n ) {\n context.transport.reportFailure({\n kind: \"shape\",\n method: operation.method,\n path: context.path,\n status: 200,\n statusText: \"\",\n message: \"Multipart upload descriptor does not match its part\",\n });\n return null;\n }\n return descriptor.source;\n}\n\n// Parts can wait behind other transfers in the shared pool. An issued URL that\n// is about to lapse would only spend this part's retry on a certain 403, so\n// authorize afresh instead; a skewed clock errs toward authorizing.\nconst ISSUED_URL_MIN_REMAINING_MS = 30_000;\n\nfunction isUsableIssuedSource(\n source: MultipartBlobPartUploadSource | undefined,\n): source is MultipartBlobPartUploadSource {\n return (\n source !== undefined &&\n (source.kind === \"api\" ||\n Date.parse(source.expiresAt) - Date.now() > ISSUED_URL_MIN_REMAINING_MS)\n );\n}\n\n// A capability path for memory/custom stores; S3/R2 never proxy parts.\nfunction uploadThroughApi(context: PartUploadContext, file: File) {\n const { input } = context;\n return context.transport.requestBinaryRequest(\n uploadMultipartBlobPartBytesOperation,\n {\n params: { stageId: context.stageId, partNumber: context.partNumber },\n body: input.encryptedBytes,\n headers: {\n [blobWireHeaderKeys.partByteLength]: input.byteLength.toString(),\n [blobWireHeaderKeys.partSha256]: input.sha256,\n [blobWireHeaderKeys.partUploadId]: input.uploadId,\n },\n },\n { ...context.options, encodeBody: () => file },\n );\n}\n\nfunction firstAttemptSource(\n attempt: number,\n source: MultipartBlobPartUploadSource | undefined,\n): MultipartBlobPartUploadSource | null {\n return attempt === 0 && isUsableIssuedSource(source) ? source : null;\n}\n\nexport async function uploadMultipartBlobPartBytes(\n transport: OperationTransport,\n stageId: string,\n partNumber: number,\n input: UploadMultipartBlobPartBytesRequest,\n uploadFetch: UploadFetch = (url, init) => fetch(url, init),\n options: RequestResultOptions = {},\n): Promise<UploadMultipartBlobPartResponse | null> {\n if (options.signal?.aborted) return null;\n const path = operationRequestPath(authorizeMultipartBlobPartUploadOperation, {\n stageId,\n partNumber,\n });\n const prepared = await preparePart(input).catch(() =>\n invalidPart(transport, path),\n );\n if (!prepared) return null;\n const { file, contentMd5 } = prepared;\n const context: PartUploadContext = {\n contentMd5,\n input,\n options,\n partNumber,\n path,\n stageId,\n transport,\n };\n let status: number | null = null;\n // The first attempt uses the source the stage initiation issued, if any. A\n // network failure may be an expired URL hidden by R2 CORS, or a lost success\n // response; reauthorize once and send the same immutable bytes to the same\n // part number.\n for (let attempt = 0; attempt < 2; attempt += 1) {\n if (options.signal?.aborted) return null;\n const source =\n firstAttemptSource(attempt, input.source) ??\n (await authorizePart(context));\n if (!source || options.signal?.aborted) return null;\n if (source.kind === \"api\") return uploadThroughApi(context, file);\n const outcome = await putStoragePart(\n context,\n file,\n source.url,\n uploadFetch,\n attempt,\n );\n if (outcome.kind === \"uploaded\") return outcome.response;\n status = outcome.status;\n if (!outcome.retry) break;\n }\n reportStorageFailureUnlessAborted(context, status);\n return null;\n}\n\nfunction reportStorageFailureUnlessAborted(\n context: PartUploadContext,\n status: number | null,\n): void {\n if (context.options.signal?.aborted) return;\n reportStorageFailure(\n context.transport,\n context.path,\n context.partNumber,\n status,\n );\n}\n\ntype StoragePartAttempt =\n | {\n readonly kind: \"uploaded\";\n readonly response: UploadMultipartBlobPartResponse;\n }\n | {\n readonly kind: \"failed\";\n readonly retry: boolean;\n readonly status: number | null;\n };\n\nasync function putStoragePart(\n context: PartUploadContext,\n file: File,\n url: string,\n uploadFetch: UploadFetch,\n attempt: number,\n): Promise<StoragePartAttempt> {\n const { input, partNumber } = context;\n try {\n const response = await uploadFetch(url, {\n method: \"PUT\",\n body: file,\n headers: {\n \"Content-Type\": \"application/octet-stream\",\n \"Content-MD5\": context.contentMd5,\n },\n ...storageFetchOptions(context.options),\n });\n const status = response.status;\n const etag = response.headers.get(\"ETag\")?.trim();\n await response.body?.cancel().catch(() => {});\n if (status === 200 && etag) {\n return {\n kind: \"uploaded\",\n response: {\n stageId: context.stageId,\n uploadId: input.uploadId,\n part: { byteLength: input.byteLength, partNumber, etag },\n },\n };\n }\n const retry = await retryStorageStatus(status, attempt);\n return { kind: \"failed\", retry, status };\n } catch {\n // Never expose a provider exception or body: it may contain the bearer URL.\n return { kind: \"failed\", retry: true, status: null };\n }\n}\n\nfunction reportStorageFailure(\n transport: OperationTransport,\n path: string,\n partNumber: number,\n status: number | null,\n) {\n transport.reportFailure({\n kind: \"storage\",\n method: authorizeMultipartBlobPartUploadOperation.method,\n path,\n status,\n statusText: \"\",\n message:\n status === 200\n ? `Multipart part ${partNumber} storage response is missing ETag; check storage CORS exposure`\n : `Multipart part ${partNumber} storage upload failed${status === null ? \"\" : ` (HTTP ${status})`}`,\n });\n}\n"]}
@@ -24,7 +24,7 @@ function concurrentRenewal(input, authToken) {
24
24
  * ends: the renewal is shared with other requests and keeps running, and a
25
25
  * rejection it settles with later is still delivered to them.
26
26
  */
27
- function renewalUnlessAborted(renewal, signal) {
27
+ export function renewalUnlessAborted(renewal, signal) {
28
28
  if (!signal)
29
29
  return Promise.resolve(renewal);
30
30
  // Starting the renewal can abort the signal before a listener exists. The
@@ -1 +1 @@
1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ACtB,IAAI,CAAC;QACH,SAAS,GAAG,MAAM,oBAAoB,CACpC,OAAO,IAAI,KAAK,CAAC,cAAc,EAAE,EACjC,KAAK,CAAC,OAAO,CAAC,MAAM,CACrB,CAAC;IACJ,CAAC;IAAC,OAAO,KAAc,EAAE,CAAC;QACxB,IAAI,KAAK,YAAY,uBAAuB,EAAE,CAAC;YAC7C,MAAM,KAAK,CAAC;QACd,CAAC;QACD,IAAI,KAAK,CAAC,OAAO,CAAC,YAAY,IAAI,IAAI,EAAE,CAAC;YACvC,KAAK,CAAC,WAAW,CAAC,2BAA2B,YAAY,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QACtE,CAAC;IACH,CAAC;IAED,MAAM,cAAc,GAAG,KAAK,CAAC,mBAAmB,EAAE,CAAC;IACnD,MAAM,OAAO,GAAG,OAAO,CACrB,SAAS;QACP,cAAc;QACd,KAAK,CAAC,qBAAqB,CAAC,KAAK,CAAC,SAAS,EAAE,cAAc,CAAC,CAC/D,CAAC;IACF,IAAI,OAAO;QAAE,KAAK,CAAC,OAAO,CAAC,gBAAgB,EAAE,EAAE,CAAC;IAChD,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport {\n errorMessage,\n isRefreshableSessionError,\n isReplayableRequestBody,\n} from \"./requestInternals\";\nimport type { RequestBody, RequestResultOptions } from \"./types\";\n\ninterface SessionRefreshInput {\n readonly authToken: string | null;\n readonly body: RequestBody | undefined;\n readonly code: string | null;\n readonly getCurrentAuthToken: () => string | null;\n readonly isKnownSessionRenewal: (from: string, to: string) => boolean;\n readonly options: RequestResultOptions;\n readonly pendingSessionRenewal: (from: string) => Promise<boolean> | null;\n readonly refreshSession: () => boolean | Promise<boolean>;\n readonly reportError: (message: string) => void;\n readonly responseStatus: number;\n}\n\n/**\n * Checks for a renewal that another request already started or finished: a\n * boolean is the final answer, otherwise `pending` (null when none) is awaited.\n */\nfunction concurrentRenewal(\n input: SessionRefreshInput,\n authToken: string,\n): boolean | { readonly pending: Promise<boolean> | null } {\n const currentAuthToken = input.getCurrentAuthToken();\n if (currentAuthToken === authToken) return { pending: null };\n const renewed =\n currentAuthToken !== null &&\n input.isKnownSessionRenewal(authToken, currentAuthToken);\n if (renewed) {\n input.options.onSessionRenewed?.();\n return true;\n }\n const pending = input.pendingSessionRenewal(authToken);\n if (!currentAuthToken || !pending) return false;\n return { pending };\n}\n\n/**\n * Ends a request's wait for a renewal when its signal aborts. Only the wait\n * ends: the renewal is shared with other requests and keeps running, and a\n * rejection it settles with later is still delivered to them.\n */\nfunction renewalUnlessAborted(\n renewal: boolean | Promise<boolean>,\n signal: AbortSignal | undefined,\n): Promise<boolean> {\n if (!signal) return Promise.resolve(renewal);\n // Starting the renewal can abort the signal before a listener exists. The\n // renewal is still consumed, so a later rejection is never unhandled.\n if (signal.aborted) {\n Promise.resolve(renewal).catch(() => undefined);\n return Promise.resolve(false);\n }\n return new Promise<boolean>((resolve, reject) => {\n const abandon = () => resolve(false);\n signal.addEventListener(\"abort\", abandon, { once: true });\n Promise.resolve(renewal).then(\n (renewed) => {\n signal.removeEventListener(\"abort\", abandon);\n resolve(renewed);\n },\n (error: unknown) => {\n signal.removeEventListener(\"abort\", abandon);\n reject(error);\n },\n );\n });\n}\n\n/**\n * Decides whether a failed request can be replayed after session renewal.\n * Identity-integrity failures are terminal and must retain their typed error.\n */\nexport async function shouldRetryAfterSessionExpired(\n input: SessionRefreshInput,\n): Promise<boolean> {\n if (\n input.options.retryOnSessionExpired === false ||\n !input.authToken ||\n !isReplayableRequestBody(input.body) ||\n !isRefreshableSessionError(input.responseStatus, input.code)\n ) {\n return false;\n }\n\n const concurrent = concurrentRenewal(input, input.authToken);\n if (typeof concurrent === \"boolean\") return concurrent;\n const pending = concurrent.pending;\n // An aborted request has no use for a renewal and must not start one.\n if (input.options.signal?.aborted) return false;\n\n let refreshed = false;\n try {\n refreshed = await renewalUnlessAborted(\n pending ?? input.refreshSession(),\n input.options.signal,\n );\n } catch (error: unknown) {\n if (error instanceof KeyingVerificationError) {\n throw error;\n }\n if (input.options.reportErrors ?? true) {\n input.reportError(`Session refresh failed: ${errorMessage(error)}`);\n }\n }\n\n const refreshedToken = input.getCurrentAuthToken();\n const renewed = Boolean(\n refreshed &&\n refreshedToken &&\n input.isKnownSessionRenewal(input.authToken, refreshedToken),\n );\n if (renewed) input.options.onSessionRenewed?.();\n return renewed;\n}\n"]}
1
+ {"version":3,"file":"sessionRefresh.js","sourceRoot":"","sources":["sessionRefresh.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EACL,YAAY,EACZ,yBAAyB,EACzB,uBAAuB,GACxB,MAAM,oBAAoB,CAAC;AAgB5B;;;GAGG;AACH,SAAS,iBAAiB,CACxB,KAA0B,EAC1B,SAAiB;IAEjB,MAAM,gBAAgB,GAAG,KAAK,CAAC,mBAAmB,EAAE,CAAC;IACrD,IAAI,gBAAgB,KAAK,SAAS;QAAE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAC7D,MAAM,OAAO,GACX,gBAAgB,KAAK,IAAI;QACzB,KAAK,CAAC,qBAAqB,CAAC,SAAS,EAAE,gBAAgB,CAAC,CAAC;IAC3D,IAAI,OAAO,EAAE,CAAC;QACZ,KAAK,CAAC,OAAO,CAAC,gBAAgB,EAAE,EAAE,CAAC;QACnC,OAAO,IAAI,CAAC;IACd,CAAC;IACD,MAAM,OAAO,GAAG,KAAK,CAAC,qBAAqB,CAAC,SAAS,CAAC,CAAC;IACvD,IAAI,CAAC,gBAAgB,IAAI,CAAC,OAAO;QAAE,OAAO,KAAK,CAAC;IAChD,OAAO,EAAE,OAAO,EAAE,CAAC;AACrB,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,oBAAoB,CAClC,OAAmC,EACnC,MAA+B;IAE/B,IAAI,CAAC,MAAM;QAAE,OAAO,OAAO,CAAC,OAAO,CAAC,OAAO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AAK,EAAE,KAAK,CAAC,SAAS,CAAC,CAAC;IAC7D,IAAI,OAAO,UAAU,KAAK,SAAS;QAAE,OAAO,UAAU,CAAC;IACvD,MAAM,OAAO,GAAG,UAAU,CAAC,OAAO,CAAC;IACnC,sEAAsE;IACtE,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,EAAE,OAAO;QAAE,OAAO,KAAK,CAAC;IAEhD,IAAI,SAAS,GAAG,KAAK,CAAC;IACtB,IAAI,CAAC;QACH,SAAS,GAAG,MAAM,oBAAoB,CACpC,OAAO,IAAI,KAAK,CAAC,cAAc,EAAE,EACjC,KAAK,CAAC,OAAO,CAAC,MAAM,CACrB,CAAC;IACJ,CAAC;IAAC,OAAO,KAAc,EAAE,CAAC;QACxB,IAAI,KAAK,YAAY,uBAAuB,EAAE,CAAC;YAC7C,MAAM,KAAK,CAAC;QACd,CAAC;QACD,IAAI,KAAK,CAAC,OAAO,CAAC,YAAY,IAAI,IAAI,EAAE,CAAC;YACvC,KAAK,CAAC,WAAW,CAAC,2BAA2B,YAAY,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QACtE,CAAC;IACH,CAAC;IAED,MAAM,cAAc,GAAG,KAAK,CAAC,mBAAmB,EAAE,CAAC;IACnD,MAAM,OAAO,GAAG,OAAO,CACrB,SAAS;QACP,cAAc;QACd,KAAK,CAAC,qBAAqB,CAAC,KAAK,CAAC,SAAS,EAAE,cAAc,CAAC,CAC/D,CAAC;IACF,IAAI,OAAO;QAAE,KAAK,CAAC,OAAO,CAAC,gBAAgB,EAAE,EAAE,CAAC;IAChD,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport {\n errorMessage,\n isRefreshableSessionError,\n isReplayableRequestBody,\n} from \"./requestInternals\";\nimport type { RequestBody, RequestResultOptions } from \"./types\";\n\ninterface SessionRefreshInput {\n readonly authToken: string | null;\n readonly body: RequestBody | undefined;\n readonly code: string | null;\n readonly getCurrentAuthToken: () => string | null;\n readonly isKnownSessionRenewal: (from: string, to: string) => boolean;\n readonly options: RequestResultOptions;\n readonly pendingSessionRenewal: (from: string) => Promise<boolean> | null;\n readonly refreshSession: () => boolean | Promise<boolean>;\n readonly reportError: (message: string) => void;\n readonly responseStatus: number;\n}\n\n/**\n * Checks for a renewal that another request already started or finished: a\n * boolean is the final answer, otherwise `pending` (null when none) is awaited.\n */\nfunction concurrentRenewal(\n input: SessionRefreshInput,\n authToken: string,\n): boolean | { readonly pending: Promise<boolean> | null } {\n const currentAuthToken = input.getCurrentAuthToken();\n if (currentAuthToken === authToken) return { pending: null };\n const renewed =\n currentAuthToken !== null &&\n input.isKnownSessionRenewal(authToken, currentAuthToken);\n if (renewed) {\n input.options.onSessionRenewed?.();\n return true;\n }\n const pending = input.pendingSessionRenewal(authToken);\n if (!currentAuthToken || !pending) return false;\n return { pending };\n}\n\n/**\n * Ends a request's wait for a renewal when its signal aborts. Only the wait\n * ends: the renewal is shared with other requests and keeps running, and a\n * rejection it settles with later is still delivered to them.\n */\nexport function renewalUnlessAborted(\n renewal: boolean | Promise<boolean>,\n signal: AbortSignal | undefined,\n): Promise<boolean> {\n if (!signal) return Promise.resolve(renewal);\n // Starting the renewal can abort the signal before a listener exists. The\n // renewal is still consumed, so a later rejection is never unhandled.\n if (signal.aborted) {\n Promise.resolve(renewal).catch(() => undefined);\n return Promise.resolve(false);\n }\n return new Promise<boolean>((resolve, reject) => {\n const abandon = () => resolve(false);\n signal.addEventListener(\"abort\", abandon, { once: true });\n Promise.resolve(renewal).then(\n (renewed) => {\n signal.removeEventListener(\"abort\", abandon);\n resolve(renewed);\n },\n (error: unknown) => {\n signal.removeEventListener(\"abort\", abandon);\n reject(error);\n },\n );\n });\n}\n\n/**\n * Decides whether a failed request can be replayed after session renewal.\n * Identity-integrity failures are terminal and must retain their typed error.\n */\nexport async function shouldRetryAfterSessionExpired(\n input: SessionRefreshInput,\n): Promise<boolean> {\n if (\n input.options.retryOnSessionExpired === false ||\n !input.authToken ||\n !isReplayableRequestBody(input.body) ||\n !isRefreshableSessionError(input.responseStatus, input.code)\n ) {\n return false;\n }\n\n const concurrent = concurrentRenewal(input, input.authToken);\n if (typeof concurrent === \"boolean\") return concurrent;\n const pending = concurrent.pending;\n // An aborted request has no use for a renewal and must not start one.\n if (input.options.signal?.aborted) return false;\n\n let refreshed = false;\n try {\n refreshed = await renewalUnlessAborted(\n pending ?? input.refreshSession(),\n input.options.signal,\n );\n } catch (error: unknown) {\n if (error instanceof KeyingVerificationError) {\n throw error;\n }\n if (input.options.reportErrors ?? true) {\n input.reportError(`Session refresh failed: ${errorMessage(error)}`);\n }\n }\n\n const refreshedToken = input.getCurrentAuthToken();\n const renewed = Boolean(\n refreshed &&\n refreshedToken &&\n input.isKnownSessionRenewal(input.authToken, refreshedToken),\n );\n if (renewed) input.options.onSessionRenewed?.();\n return renewed;\n}\n"]}
@@ -0,0 +1,31 @@
1
+ import type { RequestResultOptions } from "./types.js";
2
+ export declare function sessionAuthChallengeBytes(baseUrl: string, challengeHex: string, fingerprint: string): Uint8Array;
3
+ export type SessionBoundary = "replacement" | "renewal-refused";
4
+ type RenewSession = (() => boolean | Promise<boolean>) | null;
5
+ /** An identity change invalidates renewal evidence, including an awaited callback. */
6
+ export declare class SessionRenewalTracker {
7
+ private readonly readToken;
8
+ private revision;
9
+ private lastUnverifiedChange;
10
+ private sessionRequests;
11
+ private renewalWaiters;
12
+ private readonly sourceSignals;
13
+ private readonly refusedSessions;
14
+ private known;
15
+ private inFlight;
16
+ constructor(readToken: () => string | null);
17
+ private provisionalRenewal;
18
+ captureCredential(): () => boolean | Promise<boolean>;
19
+ get signal(): AbortSignal;
20
+ withSessionSignal(options: RequestResultOptions): RequestResultOptions;
21
+ withRenewalWaitSignal(options: RequestResultOptions): RequestResultOptions;
22
+ private callerSignal;
23
+ refused(session: AbortSignal): boolean;
24
+ tokenChanged(boundary?: SessionBoundary): void;
25
+ isKnown(from: string, to: string): boolean;
26
+ currentToken(from: string | null): string | null;
27
+ pending(from: string): Promise<boolean> | null;
28
+ renew(handler: RenewSession): Promise<boolean>;
29
+ private complete;
30
+ }
31
+ export {};
@@ -1,14 +1,78 @@
1
+ import { authChallengeSigningBytes, canonicalAuthOrigin, } from "../crypto/index.js";
2
+ export function sessionAuthChallengeBytes(baseUrl, challengeHex, fingerprint) {
3
+ let apiOrigin;
4
+ try {
5
+ apiOrigin = canonicalAuthOrigin(new URL(baseUrl || "/", globalThis.location?.href).href);
6
+ }
7
+ catch {
8
+ throw new Error("The API origin is unavailable for authentication");
9
+ }
10
+ return authChallengeSigningBytes({ apiOrigin, challengeHex, fingerprint });
11
+ }
1
12
  /** An identity change invalidates renewal evidence, including an awaited callback. */
2
13
  export class SessionRenewalTracker {
3
14
  readToken;
4
15
  revision = 0;
16
+ lastUnverifiedChange = 0;
17
+ sessionRequests = new AbortController();
18
+ renewalWaiters = new AbortController();
19
+ sourceSignals = new WeakMap();
20
+ refusedSessions = new WeakSet();
5
21
  known = null;
6
22
  inFlight = null;
7
23
  constructor(readToken) {
8
24
  this.readToken = readToken;
9
25
  }
10
- tokenChanged() {
26
+ provisionalRenewal() {
27
+ const renewal = this.inFlight;
28
+ return renewal && this.revision === renewal.revision + 1 ? renewal : null;
29
+ }
30
+ captureCredential() {
31
+ // A request born after the handler installs a candidate still belongs to
32
+ // the last verified credential until that handler confirms the change.
33
+ const revision = this.inFlight?.revision ?? this.revision;
34
+ return () => {
35
+ const renewal = this.provisionalRenewal();
36
+ if (renewal && renewal.previousUnverifiedChange <= revision)
37
+ return renewal.promise;
38
+ return this.lastUnverifiedChange <= revision;
39
+ };
40
+ }
41
+ get signal() {
42
+ return this.sessionRequests.signal;
43
+ }
44
+ withSessionSignal(options) {
45
+ const scoped = withSignal(options, this.sessionRequests.signal);
46
+ this.sourceSignals.set(scoped.signal, this.callerSignal(options));
47
+ return scoped;
48
+ }
49
+ withRenewalWaitSignal(options) {
50
+ return withSignal({ ...options, signal: this.callerSignal(options) }, this.renewalWaiters.signal);
51
+ }
52
+ callerSignal(options) {
53
+ const signal = options.signal;
54
+ return signal && this.sourceSignals.has(signal)
55
+ ? this.sourceSignals.get(signal)
56
+ : signal;
57
+ }
58
+ refused(session) {
59
+ return this.refusedSessions.has(session);
60
+ }
61
+ tokenChanged(boundary) {
62
+ if (boundary) {
63
+ if (boundary === "renewal-refused") {
64
+ this.refusedSessions.add(this.sessionRequests.signal);
65
+ }
66
+ else {
67
+ this.renewalWaiters.abort();
68
+ this.renewalWaiters = new AbortController();
69
+ }
70
+ this.sessionRequests.abort();
71
+ this.sessionRequests = new AbortController();
72
+ this.inFlight = null;
73
+ }
11
74
  this.revision += 1;
75
+ this.lastUnverifiedChange = this.revision;
12
76
  this.known = null;
13
77
  }
14
78
  isKnown(from, to) {
@@ -25,15 +89,20 @@ export class SessionRenewalTracker {
25
89
  const from = this.readToken();
26
90
  if (!from)
27
91
  return false;
28
- const existing = this.pending(from);
29
- if (existing)
30
- return existing;
92
+ // An expiry on the candidate bearer joins its outstanding verification.
93
+ // Only a sign-in boundary can release the slot before that callback settles.
94
+ if (this.inFlight)
95
+ return this.inFlight.promise;
96
+ const confirmation = Promise.withResolvers();
31
97
  const pending = {
32
98
  from,
33
- promise: this.complete(from, this.revision, handler),
99
+ revision: this.revision,
100
+ previousUnverifiedChange: this.lastUnverifiedChange,
101
+ promise: confirmation.promise,
34
102
  };
35
103
  this.inFlight = pending;
36
104
  try {
105
+ confirmation.resolve(this.complete(from, pending.revision, handler));
37
106
  return await pending.promise;
38
107
  }
39
108
  finally {
@@ -42,13 +111,29 @@ export class SessionRenewalTracker {
42
111
  }
43
112
  }
44
113
  async complete(from, revision, handler) {
114
+ const session = this.sessionRequests;
115
+ const previousUnverifiedChange = this.lastUnverifiedChange;
45
116
  const renewed = await (handler?.() ?? false);
117
+ if (session !== this.sessionRequests)
118
+ return false;
46
119
  const to = this.readToken();
47
120
  // The trusted callback authenticates the same identity and installs one
48
121
  // replacement token. A second transition cannot borrow that renewal.
49
- if (renewed && to && from !== to && this.revision === revision + 1)
122
+ if (renewed && to && from !== to && this.revision === revision + 1) {
50
123
  this.known = { from, to };
124
+ // Requests keep their original ownership through consecutive verified
125
+ // renewals without retaining a history of bearer tokens.
126
+ this.lastUnverifiedChange = previousUnverifiedChange;
127
+ }
51
128
  return renewed;
52
129
  }
53
130
  }
131
+ function withSignal(options, sessionSignal) {
132
+ return {
133
+ ...options,
134
+ signal: options.signal
135
+ ? AbortSignal.any([options.signal, sessionSignal])
136
+ : sessionSignal,
137
+ };
138
+ }
54
139
  //# sourceMappingURL=sessionRenewal.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"sessionRenewal.js","sourceRoot":"","sources":["sessionRenewal.ts"],"names":[],"mappings":"AAEA,sFAAsF;AACtF,MAAM,OAAO,qBAAqB;IAKH;IAJrB,QAAQ,GAAG,CAAC,CAAC;IACb,KAAK,GAAwC,IAAI,CAAC;IAClD,QAAQ,GAAuD,IAAI,CAAC;IAE5E,YAA6B,SAA8B;QAA9B,cAAS,GAAT,SAAS,CAAqB;IAAG,CAAC;IAE/D,YAAY;QACV,IAAI,CAAC,QAAQ,IAAI,CAAC,CAAC;QACnB,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;IACpB,CAAC;IAED,OAAO,CAAC,IAAY,EAAE,EAAU;QAC9B,OAAO,IAAI,CAAC,KAAK,EAAE,IAAI,KAAK,IAAI,IAAI,IAAI,CAAC,KAAK,CAAC,EAAE,KAAK,EAAE,CAAC;IAC3D,CAAC;IAED,YAAY,CAAC,IAAmB;QAC9B,MAAM,KAAK,GAAG,IAAI,CAAC,SAAS,EAAE,CAAC;QAC/B,OAAO,IAAI,IAAI,KAAK,IAAI,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC;IACnE,CAAC;IAED,OAAO,CAAC,IAAY;QAClB,OAAO,IAAI,CAAC,QAAQ,EAAE,IAAI,K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ewal evidence, including an awaited callback. */\nexport class SessionRenewalTracker {\n private revision = 0;\n private known: { from: string; to: string } | null = null;\n private inFlight: { from: string; promise: Promise<boolean> } | null = null;\n\n constructor(private readonly readToken: () => string | null) {}\n\n tokenChanged(): void {\n this.revision += 1;\n this.known = null;\n }\n\n isKnown(from: string, to: string): boolean {\n return this.known?.from === from && this.known.to === to;\n }\n\n currentToken(from: string | null): string | null {\n const token = this.readToken();\n return from && token && this.isKnown(from, token) ? token : null;\n }\n\n pending(from: string): Promise<boolean> | null {\n return this.inFlight?.from === from ? this.inFlight.promise : null;\n }\n\n async renew(handler: RenewSession): Promise<boolean> {\n const from = this.readToken();\n if (!from) return false;\n const existing = this.pending(from);\n if (existing) return existing;\n const pending = {\n from,\n promise: this.complete(from, this.revision, handler),\n };\n this.inFlight = pending;\n try {\n return await pending.promise;\n } finally {\n if (this.inFlight === pending) this.inFlight = null;\n }\n }\n\n private async complete(\n from: string,\n revision: number,\n handler: RenewSession,\n ): Promise<boolean> {\n const renewed = await (handler?.() ?? false);\n const to = this.readToken();\n // The trusted callback authenticates the same identity and installs one\n // replacement token. A second transition cannot borrow that renewal.\n if (renewed && to && from !== to && this.revision === revision + 1)\n this.known = { from, to };\n return renewed;\n }\n}\n"]}
1
+ {"version":3,"file":"sessionRenewal.js","sourceRoot":"","sources":["sessionRenewal.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,yBAAyB,EACzB,mBAAmB,GACpB,MAAM,mBAAmB,CAAC;AAG3B,MAAM,UAAU,yBAAyB,CACvC,OAAe,EACf,YAAoB,EACpB,WAAmB;IAEnB,IAAI,SAAiB,CAAC;IACtB,IAAI,CAAC;QACH,SAAS,GAAG,mBAAmB,CAC7B,IAAI,GAAG,CAAC,OAAO,IAAI,GAAG,EAAE,UAAU,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC,IAAI,CACxD,CAAC;IACJ,CAAC;IAAC,MAAM,CAAC;QACP,MAAM,IAAI,KAAK,CAAC,kDAAkD,CAAC,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E,aAAa,CAAC,CAAC;YAClD,CAAC,CAAC,aAAa;KAClB,CAAC;AACJ,CAAC","sourcesContent":["import {\n authChallengeSigningBytes,\n canonicalAuthOrigin,\n} from \"@tearleads/crypto\";\nimport type { RequestResultOptions } from \"./types\";\n\nexport function sessionAuthChallengeBytes(\n baseUrl: string,\n challengeHex: string,\n fingerprint: string,\n): Uint8Array {\n let apiOrigin: string;\n try {\n apiOrigin = canonicalAuthOrigin(\n new URL(baseUrl || \"/\", globalThis.location?.href).href,\n );\n } catch {\n throw new Error(\"The API origin is unavailable for authentication\");\n }\n return authChallengeSigningBytes({ apiOrigin, challengeHex, fingerprint });\n}\n\nexport type SessionBoundary = \"replacement\" | \"renewal-refused\";\n\ntype RenewSession = (() => boolean | Promise<boolean>) | null;\n\n/** An identity change invalidates renewal evidence, including an awaited callback. */\nexport class SessionRenewalTracker {\n private revision = 0;\n private lastUnverifiedChange = 0;\n private sessionRequests = new AbortController();\n private renewalWaiters = new AbortController();\n private readonly sourceSignals = new WeakMap<\n AbortSignal,\n AbortSignal | undefined\n >();\n private readonly refusedSessions = new WeakSet<AbortSignal>();\n private known: { from: string; to: string } | null = null;\n private inFlight: {\n from: string;\n revision: number;\n previousUnverifiedChange: number;\n promise: Promise<boolean>;\n } | null = null;\n\n constructor(private readonly readToken: () => string | null) {}\n\n private provisionalRenewal() {\n const renewal = this.inFlight;\n return renewal && this.revision === renewal.revision + 1 ? renewal : null;\n }\n\n captureCredential(): () => boolean | Promise<boolean> {\n // A request born after the handler installs a candidate still belongs to\n // the last verified credential until that handler confirms the change.\n const revision = this.inFlight?.revision ?? this.revision;\n return () => {\n const renewal = this.provisionalRenewal();\n if (renewal && renewal.previousUnverifiedChange <= revision)\n return renewal.promise;\n return this.lastUnverifiedChange <= revision;\n };\n }\n\n get signal(): AbortSignal {\n return this.sessionRequests.signal;\n }\n\n withSessionSignal(options: RequestResultOptions): RequestResultOptions {\n const scoped = withSignal(options, this.sessionRequests.signal);\n this.sourceSignals.set(scoped.signal, this.callerSignal(options));\n return scoped;\n }\n\n withRenewalWaitSignal(options: RequestResultOptions): RequestResultOptions {\n return withSignal(\n { ...options, signal: this.callerSignal(options) },\n this.renewalWaiters.signal,\n );\n }\n\n private callerSignal(options: RequestResultOptions): AbortSignal | undefined {\n const signal = options.signal;\n return signal && this.sourceSignals.has(signal)\n ? this.sourceSignals.get(signal)\n : signal;\n }\n\n refused(session: AbortSignal): boolean {\n return this.refusedSessions.has(session);\n }\n\n tokenChanged(boundary?: SessionBoundary): void {\n if (boundary) {\n if (boundary === \"renewal-refused\") {\n this.refusedSessions.add(this.sessionRequests.signal);\n } else {\n this.renewalWaiters.abort();\n this.renewalWaiters = new AbortController();\n }\n this.sessionRequests.abort();\n this.sessionRequests = new AbortController();\n this.inFlight = null;\n }\n this.revision += 1;\n this.lastUnverifiedChange = this.revision;\n this.known = null;\n }\n\n isKnown(from: string, to: string): boolean {\n return this.known?.from === from && this.known.to === to;\n }\n\n currentToken(from: string | null): string | null {\n const token = this.readToken();\n return from && token && this.isKnown(from, token) ? token : null;\n }\n\n pending(from: string): Promise<boolean> | null {\n return this.inFlight?.from === from ? this.inFlight.promise : null;\n }\n\n async renew(handler: RenewSession): Promise<boolean> {\n const from = this.readToken();\n if (!from) return false;\n // An expiry on the candidate bearer joins its outstanding verification.\n // Only a sign-in boundary can release the slot before that callback settles.\n if (this.inFlight) return this.inFlight.promise;\n const confirmation = Promise.withResolvers<boolean>();\n const pending = {\n from,\n revision: this.revision,\n previousUnverifiedChange: this.lastUnverifiedChange,\n promise: confirmation.promise,\n };\n this.inFlight = pending;\n try {\n confirmation.resolve(this.complete(from, pending.revision, handler));\n return await pending.promise;\n } finally {\n if (this.inFlight === pending) this.inFlight = null;\n }\n }\n\n private async complete(\n from: string,\n revision: number,\n handler: RenewSession,\n ): Promise<boolean> {\n const session = this.sessionRequests;\n const previousUnverifiedChange = this.lastUnverifiedChange;\n const renewed = await (handler?.() ?? false);\n if (session !== this.sessionRequests) return false;\n const to = this.readToken();\n // The trusted callback authenticates the same identity and installs one\n // replacement token. A second transition cannot borrow that renewal.\n if (renewed && to && from !== to && this.revision === revision + 1) {\n this.known = { from, to };\n // Requests keep their original ownership through consecutive verified\n // renewals without retaining a history of bearer tokens.\n this.lastUnverifiedChange = previousUnverifiedChange;\n }\n return renewed;\n }\n}\n\nfunction withSignal(options: RequestResultOptions, sessionSignal: AbortSignal) {\n return {\n ...options,\n signal: options.signal\n ? AbortSignal.any([options.signal, sessionSignal])\n : sessionSignal,\n };\n}\n"]}
@@ -0,0 +1,22 @@
1
+ import { hasHeader } from "./requestInternals.js";
2
+ export function sessionRequestInit(method, body, options, authToken) {
3
+ const headers = {
4
+ ...(authToken ? { Authorization: `Bearer ${authToken}` } : {}),
5
+ ...(typeof body === "string" && !hasHeader(options.headers, "Content-Type")
6
+ ? { "Content-Type": "application/json" }
7
+ : {}),
8
+ ...options.headers,
9
+ };
10
+ const init = {
11
+ method,
12
+ headers,
13
+ ...(options.signal ? { signal: options.signal } : {}),
14
+ };
15
+ if (body !== undefined) {
16
+ init.body = body;
17
+ if (body instanceof ReadableStream)
18
+ init.duplex = "half";
19
+ }
20
+ return { headers, init };
21
+ }
22
+ //# sourceMappingURL=sessionRequestInit.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sessionRequestInit.js","sourceRoot":"","sources":["sessionRequestInit.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAG/C,MAAM,UAAU,kBAAkB,CAChC,MAAkB,EAClB,IAA6B,EAC7B,OAA6B,EAC7B,SAAwB;IAExB,MAAM,OAAO,GAAG;QACd,GAAG,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,aAAa,EAAE,UAAU,SAAS,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAC9D,GAAG,CAAC,OAAO,IAAI,KAAK,QAAQ,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,OAAO,EAAE,cAAc,CAAC;YACzE,CAAC,CAAC,EAAE,cAAc,EAAE,kBAAkB,EAAE;YACxC,CAAC,CAAC,EAAE,CAAC;QACP,GAAG,OAAO,CAAC,OAAO;KACnB,CAAC;IACF,MAAM,IAAI,GAAsC;QAC9C,MAAM;QACN,OAAO;QACP,GAAG,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KACtD,CAAC;IACF,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;QACvB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,IAAI,YAAY,cAAc;YAAE,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IAC3D,CAAC;IACD,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;AAC3B,CAAC","sourcesContent":["import { hasHeader } from \"./requestInternals\";\nimport type { HttpMethod, RequestBody, RequestResultOptions } from \"./types\";\n\nexport function sessionRequestInit(\n method: HttpMethod,\n body: RequestBody | undefined,\n options: RequestResultOptions,\n authToken: string | null,\n) {\n const headers = {\n ...(authToken ? { Authorization: `Bearer ${authToken}` } : {}),\n ...(typeof body === \"string\" && !hasHeader(options.headers, \"Content-Type\")\n ? { \"Content-Type\": \"application/json\" }\n : {}),\n ...options.headers,\n };\n const init: RequestInit & { duplex?: \"half\" } = {\n method,\n headers,\n ...(options.signal ? { signal: options.signal } : {}),\n };\n if (body !== undefined) {\n init.body = body;\n if (body instanceof ReadableStream) init.duplex = \"half\";\n }\n return { headers, init };\n}\n"]}
@@ -0,0 +1,39 @@
1
+ import { errorMessage } from "./requestInternals.js";
2
+ import { responseBodyFailure } from "./responseBodyFailure.js";
3
+ /** A retired request cannot overwrite the active session's failure cache. */
4
+ export function retiredRequest(method, path) {
5
+ return {
6
+ code: "request_aborted",
7
+ kind: "cancelled",
8
+ message: `${method} ${path}: Sign-in ended`,
9
+ method,
10
+ ok: false,
11
+ path,
12
+ report: () => { },
13
+ status: null,
14
+ statusText: "",
15
+ };
16
+ }
17
+ export async function readSessionJson(request, response, method, path, options, session) {
18
+ try {
19
+ const data = await response.json();
20
+ if (session?.aborted)
21
+ return retiredRequest(method, path);
22
+ return { ok: true, data };
23
+ }
24
+ catch (error) {
25
+ if (session?.aborted)
26
+ return retiredRequest(method, path);
27
+ const failure = responseBodyFailure(error, errorMessage(error), options.signal?.aborted === true);
28
+ return request.reportFailure({
29
+ ...failure,
30
+ message: `${method} ${path}: ${failure.message}`,
31
+ method,
32
+ options,
33
+ path,
34
+ status: response.status,
35
+ statusText: response.statusText,
36
+ });
37
+ }
38
+ }
39
+ //# sourceMappingURL=sessionResponse.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sessionResponse.js","sourceRoot":"","sources":["sessionResponse.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAS5D,6EAA6E;AAC7E,MAAM,UAAU,cAAc,CAC5B,MAAkB,EAClB,IAAY;IAEZ,OAAO;QACL,IAAI,EAAE,iBAAiB;QACvB,IAAI,EAAE,WAAW;QACjB,OAAO,EAAE,GAAG,MAAM,IAAI,IAAI,iBAAiB;QAC3C,MAAM;QACN,EAAE,EAAE,KAAK;QACT,IAAI;QACJ,MAAM,EAAE,GAAG,EAAE,GAAE,CAAC;QAChB,MAAM,EAAE,IAAI;QACZ,UAAU,EAAE,EAAE;KACf,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,eAAe,CACnC,OAAmC,EACnC,QAAkB,EAClB,MAAkB,EAClB,IAAY,EACZ,OAA6B,EAC7B,OAAgC;IAEhC,IAAI,CAAC;QACH,MAAM,IAAI,GAAY,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;QAC5C,IAAI,OAAO,EAAE,OAAO;YAAE,OAAO,cAAc,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;QAC1D,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;IAC5B,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,OAAO,EAAE,OAAO;YAAE,OAAO,cAAc,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;QAC1D,MAAM,OAAO,GAAG,mBAAmB,CACjC,KAAK,EACL,YAAY,CAAC,KAAK,CAAC,EACnB,OAAO,CAAC,MAAM,EAAE,OAAO,KAAK,IAAI,CACjC,CAAC;QACF,OAAO,OAAO,CAAC,aAAa,CAAC;YAC3B,GAAG,OAAO;YACV,OAAO,EAAE,GAAG,MAAM,IAAI,IAAI,KAAK,OAAO,CAAC,OAAO,EAAE;YAChD,MAAM;YACN,OAAO;YACP,IAAI;YACJ,MAAM,EAAE,QAAQ,CAAC,MAAM;YACvB,UAAU,EAAE,QAAQ,CAAC,UAAU;SAChC,CAAC,CAAC;IACL,CAAC;AACH,CAAC","sourcesContent":["import { errorMessage } from \"./requestInternals\";\nimport { responseBodyFailure } from \"./responseBodyFailure\";\nimport type {\n HttpMethod,\n OperationResponseRequestFn,\n RequestFailure,\n RequestResult,\n RequestResultOptions,\n} from \"./types\";\n\n/** A retired request cannot overwrite the active session's failure cache. */\nexport function retiredRequest(\n method: HttpMethod,\n path: string,\n): RequestFailure {\n return {\n code: \"request_aborted\",\n kind: \"cancelled\",\n message: `${method} ${path}: Sign-in ended`,\n method,\n ok: false,\n path,\n report: () => {},\n status: null,\n statusText: \"\",\n };\n}\n\nexport async function readSessionJson(\n request: OperationResponseRequestFn,\n response: Response,\n method: HttpMethod,\n path: string,\n options: RequestResultOptions,\n session: AbortSignal | undefined,\n): Promise<RequestResult<unknown>> {\n try {\n const data: unknown = await response.json();\n if (session?.aborted) return retiredRequest(method, path);\n return { ok: true, data };\n } catch (error) {\n if (session?.aborted) return retiredRequest(method, path);\n const failure = responseBodyFailure(\n error,\n errorMessage(error),\n options.signal?.aborted === true,\n );\n return request.reportFailure({\n ...failure,\n message: `${method} ${path}: ${failure.message}`,\n method,\n options,\n path,\n status: response.status,\n statusText: response.statusText,\n });\n }\n}\n"]}
@@ -69,5 +69,6 @@ export interface ResponseRequestValidationFailureInput {
69
69
  }
70
70
  export interface OperationResponseRequestFn {
71
71
  (path: string, method: HttpMethod, body: RequestBody | undefined, options: RequestResultOptions, additionalSuccessStatuses: readonly number[], failureOperation: HttpOperation): Promise<RequestResult<Response>>;
72
+ readonly sessionSignal?: () => AbortSignal;
72
73
  readonly reportFailure: (input: ResponseRequestValidationFailureInput) => RequestFailure;
73
74
  }