@blueprint-ts/core 4.0.0 → 4.1.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,16 @@
1
+ ## 4.1.0-beta.1 - 2026-03-21 (beta)
2
+
3
+ # [4.1.0-beta.1](/compare/v4.0.0...v4.1.0-beta.1) (2026-03-21)
4
+
5
+
6
+ ### Bug Fixes
7
+
8
+ * **requests:** export HeaderValue type 15e55c1
9
+
10
+
11
+ ### Features
12
+
13
+ * **requests:** add XMLHttpRequest upload progress support 19123df
1
14
  ## v4.0.0 - 2026-03-01
2
15
 
3
16
  # [4.0.0](/compare/v4.0.0-beta.10...v4.0.0) (2026-03-01)
@@ -24,6 +24,7 @@ export default defineConfig({
24
24
  { text: 'Drivers', link: '/services/requests/drivers' },
25
25
  { text: 'Responses', link: '/services/requests/responses' },
26
26
  { text: 'Request Bodies', link: '/services/requests/request-bodies' },
27
+ { text: 'File Uploads', link: '/services/requests/file-uploads' },
27
28
  { text: 'Headers', link: '/services/requests/headers' },
28
29
  { text: 'Concurrency', link: '/services/requests/concurrency' },
29
30
  { text: 'Aborting Requests', link: '/services/requests/abort-requests' },
@@ -1,9 +1,9 @@
1
1
  # Drivers
2
2
 
3
- Requests are executed by a request driver. The library includes a default fetch-based driver and lets you provide your
4
- own by implementing `RequestDriverContract`.
3
+ Requests are executed by a request driver. The library includes a `FetchDriver`, an `XMLHttpRequestDriver`, and also
4
+ lets you provide your own by implementing `RequestDriverContract`.
5
5
 
6
- ## Default Fetch Driver
6
+ ## Fetch Driver
7
7
 
8
8
  ```typescript
9
9
  import { BaseRequest, FetchDriver } from '@blueprint-ts/core/requests'
@@ -17,6 +17,71 @@ The `FetchDriver` supports:
17
17
  - `corsWithCredentials` configuration
18
18
  - `AbortSignal` via request config
19
19
 
20
+ ## XMLHttpRequest Driver
21
+
22
+ Use `XMLHttpRequestDriver` when you need upload progress events for file uploads:
23
+
24
+ ```typescript
25
+ import { BaseRequest, XMLHttpRequestDriver } from '@blueprint-ts/core/requests'
26
+
27
+ BaseRequest.setRequestDriver(new XMLHttpRequestDriver())
28
+ ```
29
+
30
+ It supports the same configuration as `FetchDriver` and additionally forwards upload progress through
31
+ `RequestEvents.UPLOAD_PROGRESS`.
32
+
33
+ That includes:
34
+
35
+ - `corsWithCredentials`
36
+ - `headers`
37
+ - dynamic header callbacks such as `() => getCookie('XSRF-TOKEN')`
38
+
39
+ ## Request-Defined Driver
40
+
41
+ If a specific request class should always use a different driver, define it inside the request:
42
+
43
+ ```typescript
44
+ import {
45
+ BaseRequest,
46
+ FetchDriver,
47
+ JsonResponse,
48
+ RequestMethodEnum,
49
+ XMLHttpRequestDriver
50
+ } from '@blueprint-ts/core/requests'
51
+
52
+ BaseRequest.setRequestDriver(new FetchDriver())
53
+
54
+ class UploadAvatarRequest extends BaseRequest<boolean, { message: string }, { ok: true }, JsonResponse<{ ok: true }>> {
55
+ public method(): RequestMethodEnum {
56
+ return RequestMethodEnum.POST
57
+ }
58
+
59
+ public url(): string {
60
+ return '/api/v1/avatar'
61
+ }
62
+
63
+ public getResponse(): JsonResponse<{ ok: true }> {
64
+ return new JsonResponse<{ ok: true }>()
65
+ }
66
+
67
+ protected override getRequestDriver() {
68
+ return new XMLHttpRequestDriver({
69
+ corsWithCredentials: true,
70
+ headers: {
71
+ 'X-XSRF-TOKEN': () => getCookie('XSRF-TOKEN')
72
+ }
73
+ })
74
+ }
75
+ }
76
+ ```
77
+
78
+ This keeps the driver choice encapsulated inside the request class while still allowing the application to keep a
79
+ global default driver for everything else.
80
+
81
+ Important: request-defined drivers do not inherit configuration from the globally registered driver instance. If your
82
+ upload request needs credential support or shared headers, configure them on the `XMLHttpRequestDriver` you return from
83
+ `getRequestDriver()`.
84
+
20
85
  ## Custom Driver
21
86
 
22
87
  To implement your own driver, implement `RequestDriverContract` and return a `ResponseHandlerContract`:
@@ -5,6 +5,7 @@ Requests can emit lifecycle events via `BaseRequest.on(...)`.
5
5
  ## Available Events
6
6
 
7
7
  - `RequestEvents.LOADING`: Emits `true` when a request starts and `false` when it finishes.
8
+ - `RequestEvents.UPLOAD_PROGRESS`: Emits upload progress for drivers that support it, such as `XMLHttpRequestDriver`.
8
9
 
9
10
  ## Loading Event
10
11
 
@@ -29,3 +30,24 @@ request.on<boolean>(RequestEvents.LOADING, (isLoading) => {
29
30
  // isLoading is typed as boolean
30
31
  })
31
32
  ```
33
+
34
+ ## Upload Progress Event
35
+
36
+ Use `RequestEvents.UPLOAD_PROGRESS` to drive file upload progress indicators:
37
+
38
+ ```typescript
39
+ import { RequestEvents, type RequestUploadProgress } from '@blueprint-ts/core/requests'
40
+
41
+ request.on<RequestUploadProgress>(RequestEvents.UPLOAD_PROGRESS, (progress) => {
42
+ console.log(progress.loaded, progress.total, progress.progress)
43
+ })
44
+ ```
45
+
46
+ The payload contains:
47
+
48
+ - `loaded`: Bytes uploaded so far.
49
+ - `total`: Total bytes when the browser can compute it.
50
+ - `lengthComputable`: Whether `total` is reliable.
51
+ - `progress`: A normalized value between `0` and `1` when `total` is known.
52
+
53
+ Note: The default `FetchDriver` does not emit upload progress. Use `XMLHttpRequestDriver` for upload progress support.
@@ -0,0 +1,105 @@
1
+ # File Uploads
2
+
3
+ Use `FormDataFactory` to build multipart payloads, and use `XMLHttpRequestDriver` when the consuming application needs
4
+ upload progress for a progress bar.
5
+
6
+ ## Request Definition
7
+
8
+ ```typescript
9
+ import {
10
+ BaseRequest,
11
+ FormDataFactory,
12
+ JsonResponse,
13
+ RequestMethodEnum,
14
+ XMLHttpRequestDriver
15
+ } from '@blueprint-ts/core/requests'
16
+
17
+ interface UploadAvatarPayload {
18
+ avatar: File
19
+ }
20
+
21
+ interface UploadAvatarResponse {
22
+ id: string
23
+ url: string
24
+ }
25
+
26
+ class UploadAvatarRequest extends BaseRequest<
27
+ boolean,
28
+ { message: string },
29
+ UploadAvatarResponse,
30
+ JsonResponse<UploadAvatarResponse>,
31
+ UploadAvatarPayload
32
+ > {
33
+ public method(): RequestMethodEnum {
34
+ return RequestMethodEnum.POST
35
+ }
36
+
37
+ public url(): string {
38
+ return '/api/v1/avatar'
39
+ }
40
+
41
+ public getResponse(): JsonResponse<UploadAvatarResponse> {
42
+ return new JsonResponse<UploadAvatarResponse>()
43
+ }
44
+
45
+ public override getRequestBodyFactory() {
46
+ return new FormDataFactory<UploadAvatarPayload>()
47
+ }
48
+
49
+ protected override getRequestDriver() {
50
+ return new XMLHttpRequestDriver({
51
+ corsWithCredentials: true,
52
+ headers: {
53
+ 'X-XSRF-TOKEN': () => getCookie('XSRF-TOKEN')
54
+ }
55
+ })
56
+ }
57
+ }
58
+ ```
59
+
60
+ ## Global Default Driver
61
+
62
+ You can keep `FetchDriver` as the application default. The upload request above will still use `XMLHttpRequestDriver`
63
+ because it defines its own driver internally:
64
+
65
+ ```typescript
66
+ import { BaseRequest, FetchDriver } from '@blueprint-ts/core/requests'
67
+
68
+ BaseRequest.setRequestDriver(new FetchDriver())
69
+ ```
70
+
71
+ Important: the upload request's `XMLHttpRequestDriver` does not inherit config from the global `FetchDriver`. If the
72
+ upload request needs credentials or shared headers, define them on the `XMLHttpRequestDriver` returned by
73
+ `getRequestDriver()`.
74
+
75
+ ## Listening for Upload Progress
76
+
77
+ ```typescript
78
+ import { RequestEvents, type RequestUploadProgress } from '@blueprint-ts/core/requests'
79
+
80
+ const request = new UploadAvatarRequest()
81
+
82
+ request.on<RequestUploadProgress>(RequestEvents.UPLOAD_PROGRESS, (progress) => {
83
+ if (!progress.lengthComputable || progress.progress === undefined) {
84
+ return
85
+ }
86
+
87
+ progressBar.value = progress.progress * 100
88
+ })
89
+
90
+ await request.setBody({
91
+ avatar: fileInput.files![0],
92
+ }).send()
93
+ ```
94
+
95
+ ## Notes
96
+
97
+ - Upload progress requires `XMLHttpRequestDriver`. The default `FetchDriver` does not emit upload progress events.
98
+ - Define `XMLHttpRequestDriver` inside the upload request class when that request should always support progress.
99
+ - `XMLHttpRequestDriver` supports the same `corsWithCredentials` and `headers` options as `FetchDriver`, including
100
+ header callbacks.
101
+ - Request-defined drivers do not automatically inherit config from the globally registered driver.
102
+ - Some browsers cannot compute a reliable total size for every upload. Check `lengthComputable` before rendering a
103
+ percentage.
104
+ - Upload event listeners may cause CORS preflight requests on cross-origin uploads. Ensure the server is configured
105
+ accordingly.
@@ -54,6 +54,8 @@ public override getRequestBodyFactory() {
54
54
  }
55
55
  ```
56
56
 
57
+ If you want to show upload progress for multipart file uploads, see [File Uploads](/services/requests/file-uploads).
58
+
57
59
  ## Custom Body Factories
58
60
 
59
61
  You can implement your own body factory by returning a `BodyContract` with custom headers and serialization logic.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blueprint-ts/core",
3
- "version": "4.0.0",
3
+ "version": "4.1.0-beta.1",
4
4
  "license": "MIT",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -7,6 +7,7 @@ import { ResponseException } from './exceptions/ResponseException'
7
7
  import { StaleResponseException } from './exceptions/StaleResponseException'
8
8
  import { type DriverConfigContract } from './contracts/DriverConfigContract'
9
9
  import { type BodyFactoryContract } from './contracts/BodyFactoryContract'
10
+ import { type BodyContract } from './contracts/BodyContract'
10
11
  import { type RequestLoaderContract } from './contracts/RequestLoaderContract'
11
12
  import { type RequestDriverContract } from './contracts/RequestDriverContract'
12
13
  import { type RequestLoaderFactoryContract } from './contracts/RequestLoaderFactoryContract'
@@ -15,6 +16,7 @@ import { type HeadersContract } from './contracts/HeadersContract'
15
16
  import { type ResponseHandlerContract } from './drivers/contracts/ResponseHandlerContract'
16
17
  import { type ResponseContract } from './contracts/ResponseContract'
17
18
  import { type RequestConcurrencyOptions } from './types/RequestConcurrencyOptions'
19
+ import { type RequestUploadProgress } from './types/RequestUploadProgress'
18
20
  import { RequestConcurrencyMode } from './RequestConcurrencyMode.enum'
19
21
  import { mergeDeep } from '../support/helpers'
20
22
  import { v4 as uuidv4 } from 'uuid'
@@ -164,8 +166,9 @@ export abstract class BaseRequest<
164
166
  const responseSkeleton = this.getResponse()
165
167
 
166
168
  const requestBody = this.requestBody === undefined ? undefined : this.getRequestBodyFactory()?.make(this.requestBody)
169
+ const requestConfig = this.buildRequestConfig(requestBody, concurrencyKey, sequence, useLatest)
167
170
 
168
- return BaseRequest.requestDriver
171
+ return this.resolveRequestDriver()
169
172
  .send(
170
173
  this.buildUrl(),
171
174
  this.method(),
@@ -174,7 +177,7 @@ export abstract class BaseRequest<
174
177
  ...this.requestHeaders()
175
178
  },
176
179
  requestBody,
177
- this.getConfig()
180
+ requestConfig
178
181
  )
179
182
  .then(async (responseHandler: ResponseHandlerContract) => {
180
183
  if (useLatest && !this.isLatestSequence(concurrencyKey, sequence)) {
@@ -275,9 +278,44 @@ export abstract class BaseRequest<
275
278
  return undefined
276
279
  }
277
280
 
281
+ protected buildRequestConfig(
282
+ requestBody: BodyContract | undefined,
283
+ concurrencyKey: string,
284
+ sequence: number,
285
+ useLatest: boolean
286
+ ): DriverConfigContract {
287
+ const config = this.getConfig() ?? {}
288
+ const onUploadProgress = config.onUploadProgress
289
+
290
+ if (requestBody === undefined) {
291
+ return config
292
+ }
293
+
294
+ return {
295
+ ...config,
296
+ onUploadProgress: (progress: RequestUploadProgress) => {
297
+ onUploadProgress?.(progress)
298
+
299
+ if (useLatest && !this.isLatestSequence(concurrencyKey, sequence)) {
300
+ return
301
+ }
302
+
303
+ this.dispatch<RequestUploadProgress>(RequestEvents.UPLOAD_PROGRESS, progress)
304
+ }
305
+ }
306
+ }
307
+
278
308
  protected getConfig(): DriverConfigContract | undefined {
279
309
  return {
280
310
  abortSignal: this.abortSignal
281
311
  }
282
312
  }
313
+
314
+ protected resolveRequestDriver(): RequestDriverContract {
315
+ return this.getRequestDriver() ?? BaseRequest.requestDriver
316
+ }
317
+
318
+ protected getRequestDriver(): RequestDriverContract | undefined {
319
+ return undefined
320
+ }
283
321
  }
@@ -1,3 +1,4 @@
1
1
  export enum RequestEvents {
2
- LOADING = 'loading'
2
+ LOADING = 'loading',
3
+ UPLOAD_PROGRESS = 'upload-progress'
3
4
  }
@@ -1,7 +1,9 @@
1
1
  import { type HeadersContract } from './HeadersContract'
2
+ import { type RequestUploadProgress } from '../types/RequestUploadProgress'
2
3
 
3
4
  export interface DriverConfigContract {
4
5
  corsWithCredentials?: boolean | undefined
5
6
  abortSignal?: AbortSignal | undefined
6
7
  headers?: HeadersContract | undefined
8
+ onUploadProgress?: ((progress: RequestUploadProgress) => void) | undefined
7
9
  }
@@ -0,0 +1,138 @@
1
+ import { ResponseException } from '../../exceptions/ResponseException'
2
+ import { RequestMethodEnum } from '../../RequestMethod.enum'
3
+ import { type HeadersContract, type HeaderValue } from '../../contracts/HeadersContract'
4
+ import { type BodyContract } from '../../contracts/BodyContract'
5
+ import { type RequestDriverContract } from '../../contracts/RequestDriverContract'
6
+ import { type DriverConfigContract } from '../../contracts/DriverConfigContract'
7
+ import { type ResponseHandlerContract } from '../contracts/ResponseHandlerContract'
8
+ import { XMLHttpRequestResponse } from './XMLHttpRequestResponse'
9
+
10
+ export class XMLHttpRequestDriver implements RequestDriverContract {
11
+ public constructor(protected config?: DriverConfigContract) {}
12
+
13
+ public async send(
14
+ url: URL | string,
15
+ method: RequestMethodEnum,
16
+ headers: HeadersContract,
17
+ body?: BodyContract,
18
+ requestConfig?: DriverConfigContract
19
+ ): Promise<ResponseHandlerContract> {
20
+ const mergedConfig: DriverConfigContract = {
21
+ ...this.config,
22
+ ...(requestConfig ?? {})
23
+ }
24
+
25
+ const mergedHeaders: HeadersContract = {
26
+ ...this.config?.headers,
27
+ ...headers,
28
+ ...body?.getHeaders()
29
+ }
30
+
31
+ const resolvedHeaders = this.resolveHeaders(mergedHeaders)
32
+
33
+ return await new Promise<ResponseHandlerContract>((resolve, reject) => {
34
+ const request = new XMLHttpRequest()
35
+ const requestUrl = url instanceof URL ? url.toString() : url
36
+ const requestBody = [RequestMethodEnum.GET, RequestMethodEnum.HEAD].includes(method) ? undefined : body?.getContent()
37
+ const abortSignal = mergedConfig.abortSignal
38
+ const handleAbortSignal = () => request.abort()
39
+
40
+ const cleanup = () => {
41
+ request.onload = null
42
+ request.onerror = null
43
+ request.onabort = null
44
+
45
+ if (request.upload) {
46
+ request.upload.onprogress = null
47
+ }
48
+
49
+ abortSignal?.removeEventListener('abort', handleAbortSignal)
50
+ }
51
+
52
+ request.open(method, requestUrl, true)
53
+ request.responseType = 'blob'
54
+ request.withCredentials = this.getCorsWithCredentials(mergedConfig.corsWithCredentials)
55
+
56
+ for (const key in resolvedHeaders) {
57
+ request.setRequestHeader(key, resolvedHeaders[key] as string)
58
+ }
59
+
60
+ request.onload = () => {
61
+ cleanup()
62
+
63
+ if (request.status === 0) {
64
+ reject(new Error('No response received.'))
65
+ return
66
+ }
67
+
68
+ const response = new XMLHttpRequestResponse(request)
69
+
70
+ if (request.status < 200 || request.status >= 300) {
71
+ reject(new ResponseException(response))
72
+ return
73
+ }
74
+
75
+ resolve(response)
76
+ }
77
+
78
+ request.onerror = () => {
79
+ cleanup()
80
+ reject(new Error('Network request failed.'))
81
+ }
82
+
83
+ request.onabort = () => {
84
+ cleanup()
85
+ reject(new DOMException('The operation was aborted.', 'AbortError'))
86
+ }
87
+
88
+ if (request.upload) {
89
+ request.upload.onprogress = (event: ProgressEvent<EventTarget>) => {
90
+ const total = event.lengthComputable ? event.total : undefined
91
+
92
+ mergedConfig.onUploadProgress?.({
93
+ loaded: event.loaded,
94
+ total: total,
95
+ lengthComputable: event.lengthComputable,
96
+ progress: total === undefined || total === 0 ? undefined : event.loaded / total
97
+ })
98
+ }
99
+ }
100
+
101
+ if (abortSignal?.aborted) {
102
+ handleAbortSignal()
103
+ return
104
+ }
105
+
106
+ abortSignal?.addEventListener('abort', handleAbortSignal, { once: true })
107
+ request.send(requestBody)
108
+ })
109
+ }
110
+
111
+ protected getCorsWithCredentials(corsWithCredentials: boolean | undefined): boolean {
112
+ if (corsWithCredentials === true) {
113
+ return true
114
+ }
115
+
116
+ if (corsWithCredentials === false) {
117
+ return false
118
+ }
119
+
120
+ return this.config?.corsWithCredentials ?? false
121
+ }
122
+
123
+ protected resolveHeaders(headers: HeadersContract): HeadersContract {
124
+ const resolved: HeadersContract = {}
125
+
126
+ for (const key in headers) {
127
+ const value: HeaderValue | undefined = headers[key]
128
+
129
+ if (value === undefined) {
130
+ continue
131
+ }
132
+
133
+ resolved[key] = typeof value === 'function' ? value() : value
134
+ }
135
+
136
+ return resolved
137
+ }
138
+ }
@@ -0,0 +1,95 @@
1
+ import { type HeadersContract } from '../../contracts/HeadersContract'
2
+ import { type ResponseHandlerContract } from '../contracts/ResponseHandlerContract'
3
+
4
+ export class XMLHttpRequestResponse implements ResponseHandlerContract {
5
+ protected response: Response
6
+ protected headers: HeadersContract
7
+
8
+ public constructor(protected request: XMLHttpRequest) {
9
+ this.headers = this.parseHeaders(request.getAllResponseHeaders())
10
+ this.response = new Response(this.getResponseBody(), {
11
+ status: request.status,
12
+ statusText: request.statusText,
13
+ headers: Object.entries(this.headers).map(([key, value]) => [key, String(value)])
14
+ })
15
+ }
16
+
17
+ public getStatusCode(): number | undefined {
18
+ return this.request.status
19
+ }
20
+
21
+ public getHeaders(): HeadersContract {
22
+ return this.headers
23
+ }
24
+
25
+ public getRawResponse(): Response {
26
+ return this.response
27
+ }
28
+
29
+ public async json<ResponseBodyInterface>(): Promise<ResponseBodyInterface> {
30
+ return await this.response.json()
31
+ }
32
+
33
+ public async text(): Promise<string> {
34
+ return await this.response.text()
35
+ }
36
+
37
+ public async blob(): Promise<Blob> {
38
+ return await this.response.blob()
39
+ }
40
+
41
+ protected getResponseBody(): Blob | string | null {
42
+ if ([204, 205, 304].includes(this.request.status)) {
43
+ return null
44
+ }
45
+
46
+ if (this.request.response === null || this.request.response === undefined) {
47
+ return null
48
+ }
49
+
50
+ if (this.isBlobLike(this.request.response) || typeof this.request.response === 'string') {
51
+ return this.request.response
52
+ }
53
+
54
+ return new Blob([this.request.response])
55
+ }
56
+
57
+ protected isBlobLike(value: unknown): value is Blob {
58
+ return (
59
+ value instanceof Blob ||
60
+ (typeof value === 'object' &&
61
+ value !== null &&
62
+ typeof (value as Blob).arrayBuffer === 'function' &&
63
+ typeof (value as Blob).stream === 'function' &&
64
+ typeof (value as Blob).text === 'function')
65
+ )
66
+ }
67
+
68
+ protected parseHeaders(rawHeaders: string): HeadersContract {
69
+ const headers: HeadersContract = {}
70
+ const lines = rawHeaders.trim()
71
+
72
+ if (lines.length === 0) {
73
+ return headers
74
+ }
75
+
76
+ for (const line of lines.split(/\r?\n/)) {
77
+ const separatorIndex = line.indexOf(':')
78
+
79
+ if (separatorIndex === -1) {
80
+ continue
81
+ }
82
+
83
+ const key = line.slice(0, separatorIndex).trim()
84
+ const value = line.slice(separatorIndex + 1).trim()
85
+
86
+ if (key.length === 0) {
87
+ continue
88
+ }
89
+
90
+ headers[key] = key in headers ? `${String(headers[key])}, ${value}` : value
91
+ }
92
+
93
+ return headers
94
+ }
95
+ }
@@ -21,8 +21,10 @@ import { type ResponseHandlerContract } from './drivers/contracts/ResponseHandle
21
21
  import { type BaseRequestContract } from './contracts/BaseRequestContract'
22
22
  import { ResponseException } from './exceptions/ResponseException'
23
23
  import { StaleResponseException } from './exceptions/StaleResponseException'
24
- import { type HeadersContract } from './contracts/HeadersContract'
24
+ import { type HeaderValue, type HeadersContract } from './contracts/HeadersContract'
25
25
  import { type RequestConcurrencyOptions } from './types/RequestConcurrencyOptions'
26
+ import { type RequestUploadProgress } from './types/RequestUploadProgress'
27
+ import { XMLHttpRequestDriver } from './drivers/xhr/XMLHttpRequestDriver'
26
28
 
27
29
  export {
28
30
  FetchDriver,
@@ -39,7 +41,8 @@ export {
39
41
  ResponseException,
40
42
  StaleResponseException,
41
43
  JsonBodyFactory,
42
- FormDataFactory
44
+ FormDataFactory,
45
+ XMLHttpRequestDriver
43
46
  }
44
47
 
45
48
  export type {
@@ -51,6 +54,8 @@ export type {
51
54
  BodyFactoryContract,
52
55
  ResponseHandlerContract,
53
56
  BaseRequestContract,
57
+ HeaderValue,
54
58
  HeadersContract,
55
- RequestConcurrencyOptions
59
+ RequestConcurrencyOptions,
60
+ RequestUploadProgress
56
61
  }
@@ -0,0 +1,6 @@
1
+ export interface RequestUploadProgress {
2
+ loaded: number
3
+ total?: number | undefined
4
+ lengthComputable: boolean
5
+ progress?: number | undefined
6
+ }
@@ -118,6 +118,33 @@ describe('BaseRequest', () => {
118
118
  expect(body?.getContent()).toBe('{"name":"Ada"}')
119
119
  })
120
120
 
121
+ it('dispatches upload progress events from the driver config callback', async () => {
122
+ const driver: RequestDriverContract = {
123
+ send: vi.fn().mockImplementation(async (_url, _method, _headers, _body, requestConfig) => {
124
+ requestConfig?.onUploadProgress?.({
125
+ loaded: 5,
126
+ total: 10,
127
+ lengthComputable: true,
128
+ progress: 0.5,
129
+ })
130
+
131
+ return createResponseHandler()
132
+ }),
133
+ }
134
+
135
+ BaseRequest.setRequestDriver(driver)
136
+
137
+ const request = new TestRequest()
138
+ const progressEvents: Array<number | undefined> = []
139
+
140
+ request.on(RequestEvents.UPLOAD_PROGRESS, (value: { progress?: number }) => progressEvents.push(value.progress))
141
+ request.setBody({ name: 'Ada' })
142
+
143
+ await request.send()
144
+
145
+ expect(progressEvents).toEqual([0.5])
146
+ })
147
+
121
148
  it('throws when loading state is requested without a loader', () => {
122
149
  const request = new TestRequest()
123
150
 
@@ -196,4 +223,28 @@ describe('BaseRequest', () => {
196
223
  await expect(request.send()).rejects.toBe(responseException)
197
224
  expect(handleSpy).toHaveBeenCalledTimes(1)
198
225
  })
226
+
227
+ it('uses a request-defined driver when provided', async () => {
228
+ const globalDriver: RequestDriverContract = {
229
+ send: vi.fn().mockResolvedValue(createResponseHandler()),
230
+ }
231
+ const requestDriver: RequestDriverContract = {
232
+ send: vi.fn().mockResolvedValue(createResponseHandler()),
233
+ }
234
+
235
+ BaseRequest.setRequestDriver(globalDriver)
236
+
237
+ class DriverSpecificRequest extends TestRequest {
238
+ protected override getRequestDriver(): RequestDriverContract {
239
+ return requestDriver
240
+ }
241
+ }
242
+
243
+ const request = new DriverSpecificRequest()
244
+
245
+ await request.send()
246
+
247
+ expect(requestDriver.send).toHaveBeenCalledTimes(1)
248
+ expect(globalDriver.send).not.toHaveBeenCalled()
249
+ })
199
250
  })
@@ -9,6 +9,7 @@ describe('Enums', () => {
9
9
  it('exposes expected request enums', () => {
10
10
  expect(RequestMethodEnum.GET).toBe('GET')
11
11
  expect(RequestEvents.LOADING).toBe('loading')
12
+ expect(RequestEvents.UPLOAD_PROGRESS).toBe('upload-progress')
12
13
  expect(RequestConcurrencyMode.REPLACE_LATEST).toBe('replace-latest')
13
14
  })
14
15
 
@@ -0,0 +1,178 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
2
+ import { XMLHttpRequestDriver } from '../../../../src/requests/drivers/xhr/XMLHttpRequestDriver'
3
+ import { XMLHttpRequestResponse } from '../../../../src/requests/drivers/xhr/XMLHttpRequestResponse'
4
+ import { RequestMethodEnum } from '../../../../src/requests/RequestMethod.enum'
5
+ import { ResponseException } from '../../../../src/requests/exceptions/ResponseException'
6
+ import type { BodyContract } from '../../../../src/requests/contracts/BodyContract'
7
+
8
+ const createBody = (content: string): BodyContract => ({
9
+ getHeaders: () => ({ 'Content-Type': 'application/json' }),
10
+ getContent: () => content,
11
+ })
12
+
13
+ class MockXMLHttpRequestUpload {
14
+ public onprogress: ((event: ProgressEvent<EventTarget>) => void) | null = null
15
+ }
16
+
17
+ class MockXMLHttpRequest {
18
+ public static instances: MockXMLHttpRequest[] = []
19
+
20
+ public method?: string
21
+ public url?: string
22
+ public async?: boolean
23
+ public responseType: XMLHttpRequestResponseType = ''
24
+ public withCredentials = false
25
+ public status = 200
26
+ public statusText = 'OK'
27
+ public response: Blob | string | ArrayBuffer | null = '{"ok":true}'
28
+ public onload: (() => void) | null = null
29
+ public onerror: (() => void) | null = null
30
+ public onabort: (() => void) | null = null
31
+ public upload = new MockXMLHttpRequestUpload()
32
+ public headers: Record<string, string> = {}
33
+ public responseHeaders: Record<string, string> = {}
34
+ public sentBody: Document | XMLHttpRequestBodyInit | null | undefined = undefined
35
+ public aborted = false
36
+
37
+ public constructor() {
38
+ MockXMLHttpRequest.instances.push(this)
39
+ }
40
+
41
+ public open(method: string, url: string, async: boolean): void {
42
+ this.method = method
43
+ this.url = url
44
+ this.async = async
45
+ }
46
+
47
+ public setRequestHeader(key: string, value: string): void {
48
+ this.headers[key] = value
49
+ }
50
+
51
+ public send(body?: Document | XMLHttpRequestBodyInit | null): void {
52
+ this.sentBody = body
53
+ }
54
+
55
+ public abort(): void {
56
+ this.aborted = true
57
+ this.onabort?.()
58
+ }
59
+
60
+ public getAllResponseHeaders(): string {
61
+ return Object.entries(this.responseHeaders)
62
+ .map(([key, value]) => `${key}: ${value}`)
63
+ .join('\r\n')
64
+ }
65
+
66
+ public triggerLoad(): void {
67
+ this.onload?.()
68
+ }
69
+
70
+ public triggerError(): void {
71
+ this.onerror?.()
72
+ }
73
+
74
+ public triggerUploadProgress(loaded: number, total: number, lengthComputable: boolean = true): void {
75
+ this.upload.onprogress?.({
76
+ loaded,
77
+ total,
78
+ lengthComputable,
79
+ } as ProgressEvent<EventTarget>)
80
+ }
81
+ }
82
+
83
+ describe('XMLHttpRequestDriver', () => {
84
+ const originalXMLHttpRequest = global.XMLHttpRequest
85
+
86
+ beforeEach(() => {
87
+ MockXMLHttpRequest.instances = []
88
+ global.XMLHttpRequest = MockXMLHttpRequest as unknown as typeof XMLHttpRequest
89
+ })
90
+
91
+ afterEach(() => {
92
+ global.XMLHttpRequest = originalXMLHttpRequest
93
+ vi.restoreAllMocks()
94
+ })
95
+
96
+ it('sends requests with merged headers, body, and upload progress callbacks', async () => {
97
+ const onUploadProgress = vi.fn()
98
+ const driver = new XMLHttpRequestDriver({ headers: { 'X-Global': 'a' }, corsWithCredentials: true })
99
+
100
+ const promise = driver.send(
101
+ 'https://example.com',
102
+ RequestMethodEnum.POST,
103
+ { 'X-Req': 'b', 'X-Fn': () => 'c', 'X-Ignore': undefined },
104
+ createBody('{"name":"test"}'),
105
+ { onUploadProgress }
106
+ )
107
+
108
+ const request = MockXMLHttpRequest.instances[0]
109
+ request.status = 201
110
+ request.responseHeaders = { 'X-Response': 'yes' }
111
+ request.triggerUploadProgress(5, 10)
112
+ request.triggerLoad()
113
+
114
+ const result = await promise
115
+
116
+ expect(result).toBeInstanceOf(XMLHttpRequestResponse)
117
+ expect(request.method).toBe('POST')
118
+ expect(request.url).toBe('https://example.com')
119
+ expect(request.async).toBe(true)
120
+ expect(request.responseType).toBe('blob')
121
+ expect(request.withCredentials).toBe(true)
122
+ expect(request.headers).toEqual({
123
+ 'X-Global': 'a',
124
+ 'X-Req': 'b',
125
+ 'X-Fn': 'c',
126
+ 'Content-Type': 'application/json',
127
+ })
128
+ expect(request.sentBody).toBe('{"name":"test"}')
129
+ expect(onUploadProgress).toHaveBeenCalledWith({
130
+ loaded: 5,
131
+ total: 10,
132
+ lengthComputable: true,
133
+ progress: 0.5,
134
+ })
135
+ await expect(result.json()).resolves.toEqual({ ok: true })
136
+ })
137
+
138
+ it('omits body for GET and HEAD requests', async () => {
139
+ const driver = new XMLHttpRequestDriver()
140
+
141
+ const promise = driver.send('https://example.com', RequestMethodEnum.GET, {}, createBody('data'))
142
+
143
+ const request = MockXMLHttpRequest.instances[0]
144
+ request.triggerLoad()
145
+
146
+ await promise
147
+
148
+ expect(request.sentBody).toBeUndefined()
149
+ })
150
+
151
+ it('throws ResponseException when the response status is not ok', async () => {
152
+ const driver = new XMLHttpRequestDriver()
153
+
154
+ const promise = driver.send('https://example.com', RequestMethodEnum.GET, {})
155
+
156
+ const request = MockXMLHttpRequest.instances[0]
157
+ request.status = 500
158
+ request.response = 'fail'
159
+ request.triggerLoad()
160
+
161
+ await expect(promise).rejects.toBeInstanceOf(ResponseException)
162
+ })
163
+
164
+ it('aborts requests when the AbortSignal is triggered', async () => {
165
+ const controller = new AbortController()
166
+ const driver = new XMLHttpRequestDriver()
167
+
168
+ const promise = driver.send('https://example.com', RequestMethodEnum.POST, {}, createBody('{"name":"test"}'), {
169
+ abortSignal: controller.signal,
170
+ })
171
+
172
+ const request = MockXMLHttpRequest.instances[0]
173
+ controller.abort()
174
+
175
+ await expect(promise).rejects.toMatchObject({ name: 'AbortError' })
176
+ expect(request.aborted).toBe(true)
177
+ })
178
+ })