@stacksjs/http 0.75.569 → 0.75.571

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/README.md CHANGED
@@ -1,59 +1,130 @@
1
- # Stacks Cache
1
+ # Stacks HTTP
2
2
 
3
- wip
3
+ `@stacksjs/http` provides HTTP status constants, bounded outbound requests and
4
+ transfer observations. It runs on Bun.
4
5
 
5
- ## ☘️ Features
6
+ ## Requests and budgets
6
7
 
7
- wip
8
+ ```ts
9
+ import { Response as HttpStatus, fetchWithBudget } from '@stacksjs/http'
8
10
 
9
- - ⚡️
10
-
11
- wip
12
-
13
- ## 🤖 Usage
14
-
15
- wip
16
-
17
- ```bash
18
- bun install -d @stacksjs/http
11
+ const response = await fetchWithBudget('https://example.com/status', {
12
+ timeoutMs: 5000,
13
+ retry: 2,
14
+ })
15
+ if (response.status === HttpStatus.HTTP_OK)
16
+ console.log(await response.text())
19
17
  ```
20
18
 
21
- Now, you can use it in your project:
22
-
23
- ```js
24
- import * as http from '@stacksjs/http'
25
-
26
- // wip
19
+ `Response` is the status enum. `fetchWithBudget` returns the real Fetch Response;
20
+ non-success status codes remain responses. One deadline covers request attempts
21
+ and retry waits. The helper retries 429/503, honors numeric or HTTP-date
22
+ Retry-After, and cancels discarded bodies. A delay longer than the remaining
23
+ budget ends at the deadline. Streaming uploads and Requests with bodies are
24
+ sent once because they cannot be replayed safely.
25
+
26
+ The deadline ends when final response headers arrive. The caller owns the
27
+ subsequent body read, its cancellation/inactivity/total budget, verification and
28
+ publication. An incoming AbortSignal is composed with the request deadline.
29
+
30
+ ## Observe attempts and response metadata
31
+
32
+ Pass `observer.onAttempt` and/or `observer.onResponse` in the request options.
33
+ Callbacks retain their observer receiver. Attempt notifications precede each
34
+ actual fetch; response notifications precede its retry decision. Fetch follows
35
+ redirects, so a response observation describes the selected final response, not
36
+ an intermediate redirect history.
37
+
38
+ Observations are immutable. They include a one-based attempt number and HTTP(S)
39
+ origins; response observations also include status and optional Content-Length.
40
+ URL credentials, paths, queries, fragments, arbitrary headers and bodies are
41
+ excluded. URL input above 4096 UTF-16 code units or an origin above 512 is omitted
42
+ with an `originOmitted` reason. Invalid and unsupported origins are also omitted.
43
+ Content-Length must fit a nonnegative safe integer, with at most 16 decimal
44
+ digits in a header of at most 32 code units; otherwise it is null.
45
+
46
+ Callbacks are never awaited. Synchronous exceptions, throwing callback getters
47
+ and rejected promises are isolated without logging their contents. Callbacks
48
+ must return promptly; synchronous work they perform still runs on the caller's
49
+ thread. Observation adds no request, timer, body reader, wrapper or tee.
50
+
51
+ ## Record the bytes your caller reads
52
+
53
+ ```ts
54
+ import { createHttpTransferObservation, fetchWithBudget } from '@stacksjs/http'
55
+
56
+ const observation = createHttpTransferObservation()
57
+ const response = await fetchWithBudget('https://example.com/archive', {
58
+ timeoutMs: 5000,
59
+ observer: observation.observer,
60
+ })
61
+ if (!response.body)
62
+ throw new Error('The response has no readable body')
63
+
64
+ const reader = response.body.getReader()
65
+ try {
66
+ for (;;) {
67
+ const chunk = await reader.read()
68
+ if (chunk.done)
69
+ break
70
+ if (chunk.value.byteLength)
71
+ observation.received(chunk.value.byteLength)
72
+ // The caller consumes or verifies the same bytes here.
73
+ }
74
+ }
75
+ catch (error) {
76
+ console.error(observation.finish('unknown'))
77
+ throw error
78
+ }
79
+ finally {
80
+ await reader.cancel().catch(() => {})
81
+ reader.releaseLock()
82
+ }
83
+ console.log(observation.finish('complete'))
27
84
  ```
28
85
 
29
- Learn more in the docs.
30
-
31
- ## 🧪 Testing
32
-
33
- ```bash
34
- bun test
35
- ```
36
-
37
- ## 📈 Changelog
38
-
39
- Please see our [releases](https://github.com/stacksjs/stacks/releases) page for more information on what has changed recently.
86
+ This example does not add a body deadline. A downloader must keep its own shared
87
+ deadline/inactivity signal active through body consumption and preserve its
88
+ existing retry, integrity and publication rules. Choose the terminal reason from
89
+ that caller's actual outcome: `complete`, `total-deadline`, `idle`, `transport`,
90
+ `http-status`, `checksum` or `unknown`. The collector does not infer a failure
91
+ cause from a status or arbitrary error message.
40
92
 
41
- ## 🚜 Contributing
93
+ The report contains the latest copied attempt/response metadata, byte/chunk
94
+ totals, header/first-byte/last-byte elapsed times, terminal elapsed time,
95
+ last-byte age and maximum gap between nonempty chunks. Before any bytes arrive,
96
+ byte timestamps and last-byte age are null.
42
97
 
43
- Please review the [Contributing Guide](https://github.com/stacksjs/contributing) for details.
98
+ Retention is fixed at 12 ten-second buckets. Bytes at or after 120000 ms merge
99
+ into the last bucket, whose `throughMs` records the actual last observation;
100
+ `coalesced` becomes true. This retention boundary creates no transfer deadline.
101
+ There is no configurable clock, interval, bucket count or history size.
44
102
 
45
- ## 🏝 Community
103
+ Feed positive safe-integer byte lengths. Invalid counts or metadata are ignored
104
+ and set `invalidObservation`. Counters saturate at Number.MAX_SAFE_INTEGER with
105
+ `overflowed`; invalid/backward clock samples keep the previous finite elapsed
106
+ time. `finish` returns one deeply frozen report. Repeated finishes return the
107
+ same object and later observations have no effect.
46
108
 
47
- For help, discussion about best practices, or any other conversation that would benefit from being searchable:
109
+ These are caller-supplied observations. The collector does not independently
110
+ measure socket traffic, enforce a byte limit, hash content or publish files.
48
111
 
49
- [Discussions on GitHub](https://github.com/stacksjs/stacks/discussions)
112
+ ## Evidence and limits
50
113
 
51
- For casual chit-chat with others using this package:
114
+ `tests/fetch-budget.test.ts` uses real loopback HTTP for redirect metadata,
115
+ receiver/error isolation, URL/Content-Length boundaries, retry chronology,
116
+ cancellation, request budgets and intact caller-owned bodies.
117
+ `tests/transfer-observation.test.ts` covers real caller-read bytes plus supplied
118
+ counter boundaries, immutable/idempotent reports and metadata privacy. Its
119
+ worked monotonic timelines use an external clock spy and restore it in finally;
120
+ they establish aggregation behavior, not network latency or remote throughput.
52
121
 
53
- [Join the Stacks Discord Server](https://stacksjs.com/discord)
122
+ These tests do not establish a provider SLA, a remote download cause, an
123
+ application's body-timeout policy or acceptance of a published package. Validate
124
+ public declarations and the actual consumer when releasing changes.
54
125
 
55
- ## 📄 License
126
+ Run this package's suite from its directory with `bun test ./tests`.
56
127
 
57
- The MIT License (MIT). Please see [LICENSE](https://github.com/stacksjs/stacks/tree/main/LICENSE.md) for more information.
128
+ ## License
58
129
 
59
- Made with 💙
130
+ MIT. See the repository [license](https://github.com/stacksjs/stacks/blob/main/LICENSE.md).
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { retryAfterMilliseconds } from './retry-after';
2
+ export type { HttpTransferBucket, HttpTransferObservation, HttpTransferReason, HttpTransferReport } from './transfer-observation';
2
3
  /**
3
4
  * `fetch` wrapper with one budget for requests and retry waits. Honors
4
5
  * numeric and HTTP-date `Retry-After` on 429/503 responses.
@@ -11,7 +12,7 @@ import { retryAfterMilliseconds } from './retry-after';
11
12
  * budget so failure modes stay bounded.
12
13
  *
13
14
  * @param input URL or Request, exactly like fetch
14
- * @param init RequestInit + { timeoutMs?: number, retry?: number }
15
+ * @param init RequestInit + { timeoutMs?: number, retry?: number, observer?: HttpTransferObserver }
15
16
  * - timeoutMs (default 30_000): overall request budget
16
17
  * - retry (default 0): retry count on 429/503
17
18
  *
@@ -19,6 +20,8 @@ import { retryAfterMilliseconds } from './retry-after';
19
20
  * body consumption. Streaming request bodies are sent once, because replaying
20
21
  * a consumed stream cannot reproduce the upload. Use buffered bytes for an
21
22
  * idempotent upload that needs retries. A Request with a body is also one-shot.
23
+ * Observer callbacks receive immutable origin-only metadata. They add no body
24
+ * reader and are never awaited; their exceptions and rejections are ignored.
22
25
  *
23
26
  * @example
24
27
  * ```ts
@@ -30,7 +33,24 @@ import { retryAfterMilliseconds } from './retry-after';
30
33
  * })
31
34
  * ```
32
35
  */
33
- export declare function fetchWithBudget(input: RequestInfo | URL, init?: RequestInit & { timeoutMs?: number, retry?: number }): Promise<globalThis.Response>;
36
+ export declare function fetchWithBudget(input: RequestInfo | URL, init?: RequestInit & { timeoutMs?: number, retry?: number, observer?: HttpTransferObserver }): Promise<globalThis.Response>;
37
+ export declare interface HttpAttemptObservation {
38
+ readonly attempt: number
39
+ readonly requestedOrigin: string | null
40
+ readonly originOmitted: HttpOriginOmission
41
+ }
42
+ export declare interface HttpResponseObservation {
43
+ readonly attempt: number
44
+ readonly responseOrigin: string | null
45
+ readonly originOmitted: HttpOriginOmission
46
+ readonly status: number
47
+ readonly contentLength: number | null
48
+ }
49
+ export declare interface HttpTransferObserver {
50
+ onAttempt?: (value: Readonly<HttpAttemptObservation>) => void | Promise<void>
51
+ onResponse?: (value: Readonly<HttpResponseObservation>) => void | Promise<void>
52
+ }
53
+ export type HttpOriginOmission = 'invalid' | 'oversized' | 'unsupported' | null;
34
54
  export declare enum Response {
35
55
  // 1xx Informational
36
56
  HTTP_CONTINUE = 100,
@@ -101,3 +121,4 @@ export declare enum Response {
101
121
  HTTP_NETWORK_AUTHENTICATION_REQUIRED = 511,
102
122
  }
103
123
  export { retryAfterMilliseconds } from './retry-after';
124
+ export { createHttpTransferObservation } from './transfer-observation';
package/dist/index.js CHANGED
@@ -1,2 +1 @@
1
- // @bun
2
- function I(r,_=Date.now()){let E=r?.trim();if(!E||!Number.isFinite(_))return null;if(/^\d+(?:\.\d+)?$/.test(E)){let t=Number(E)*1000;return Number.isFinite(t)&&t<=Number.MAX_SAFE_INTEGER?Math.ceil(t):null}if(!/^(?:[a-z]{3}, \d{2} [a-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT|[a-z]+, \d{2}-[a-z]{3}-\d{2} \d{2}:\d{2}:\d{2} GMT|[a-z]{3} [a-z]{3} [ \d]\d \d{2}:\d{2}:\d{2} \d{4})$/i.test(E))return null;let P=Date.parse(E);return Number.isFinite(P)?Math.max(0,P-_):null}var u;((T)=>{T[T.HTTP_CONTINUE=100]="HTTP_CONTINUE";T[T.HTTP_SWITCHING_PROTOCOLS=101]="HTTP_SWITCHING_PROTOCOLS";T[T.HTTP_OK=200]="HTTP_OK";T[T.HTTP_CREATED=201]="HTTP_CREATED";T[T.HTTP_ACCEPTED=202]="HTTP_ACCEPTED";T[T.HTTP_NON_AUTHORITATIVE_INFORMATION=203]="HTTP_NON_AUTHORITATIVE_INFORMATION";T[T.HTTP_NO_CONTENT=204]="HTTP_NO_CONTENT";T[T.HTTP_RESET_CONTENT=205]="HTTP_RESET_CONTENT";T[T.HTTP_PARTIAL_CONTENT=206]="HTTP_PARTIAL_CONTENT";T[T.HTTP_MULTIPLE_CHOICES=300]="HTTP_MULTIPLE_CHOICES";T[T.HTTP_MOVED_PERMANENTLY=301]="HTTP_MOVED_PERMANENTLY";T[T.HTTP_FOUND=302]="HTTP_FOUND";T[T.HTTP_SEE_OTHER=303]="HTTP_SEE_OTHER";T[T.HTTP_NOT_MODIFIED=304]="HTTP_NOT_MODIFIED";T[T.HTTP_USE_PROXY=305]="HTTP_USE_PROXY";T[T.HTTP_UNUSED=306]="HTTP_UNUSED";T[T.HTTP_TEMPORARY_REDIRECT=307]="HTTP_TEMPORARY_REDIRECT";T[T.HTTP_PERMANENT_REDIRECT=308]="HTTP_PERMANENT_REDIRECT";T[T.HTTP_BAD_REQUEST=400]="HTTP_BAD_REQUEST";T[T.HTTP_UNAUTHORIZED=401]="HTTP_UNAUTHORIZED";T[T.HTTP_PAYMENT_REQUIRED=402]="HTTP_PAYMENT_REQUIRED";T[T.HTTP_FORBIDDEN=403]="HTTP_FORBIDDEN";T[T.HTTP_NOT_FOUND=404]="HTTP_NOT_FOUND";T[T.HTTP_METHOD_NOT_ALLOWED=405]="HTTP_METHOD_NOT_ALLOWED";T[T.HTTP_NOT_ACCEPTABLE=406]="HTTP_NOT_ACCEPTABLE";T[T.HTTP_PROXY_AUTHENTICATION_REQUIRED=407]="HTTP_PROXY_AUTHENTICATION_REQUIRED";T[T.HTTP_REQUEST_TIMEOUT=408]="HTTP_REQUEST_TIMEOUT";T[T.HTTP_CONFLICT=409]="HTTP_CONFLICT";T[T.HTTP_GONE=410]="HTTP_GONE";T[T.HTTP_LENGTH_REQUIRED=411]="HTTP_LENGTH_REQUIRED";T[T.HTTP_PRECONDITION_FAILED=412]="HTTP_PRECONDITION_FAILED";T[T.HTTP_REQUEST_ENTITY_TOO_LARGE=413]="HTTP_REQUEST_ENTITY_TOO_LARGE";T[T.HTTP_REQUEST_URI_TOO_LONG=414]="HTTP_REQUEST_URI_TOO_LONG";T[T.HTTP_UNSUPPORTED_MEDIA_TYPE=415]="HTTP_UNSUPPORTED_MEDIA_TYPE";T[T.HTTP_REQUESTED_RANGE_NOT_SATISFIABLE=416]="HTTP_REQUESTED_RANGE_NOT_SATISFIABLE";T[T.HTTP_EXPECTATION_FAILED=417]="HTTP_EXPECTATION_FAILED";T[T.HTTP_I_AM_A_TEAPOT=418]="HTTP_I_AM_A_TEAPOT";T[T.HTTP_MISDIRECTED_REQUEST=421]="HTTP_MISDIRECTED_REQUEST";T[T.HTTP_UNPROCESSABLE_ENTITY=422]="HTTP_UNPROCESSABLE_ENTITY";T[T.HTTP_LOCKED=423]="HTTP_LOCKED";T[T.HTTP_FAILED_DEPENDENCY=424]="HTTP_FAILED_DEPENDENCY";T[T.HTTP_RESERVED_FOR_WEBDAV_ADVANCED_COLLECTIONS_EXPIRED_PROPOSAL=425]="HTTP_RESERVED_FOR_WEBDAV_ADVANCED_COLLECTIONS_EXPIRED_PROPOSAL";T[T.HTTP_UPGRADE_REQUIRED=426]="HTTP_UPGRADE_REQUIRED";T[T.HTTP_PRECONDITION_REQUIRED=428]="HTTP_PRECONDITION_REQUIRED";T[T.HTTP_TOO_MANY_REQUESTS=429]="HTTP_TOO_MANY_REQUESTS";T[T.HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE=431]="HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE";T[T.HTTP_UNAVAILABLE_FOR_LEGAL_REASONS=451]="HTTP_UNAVAILABLE_FOR_LEGAL_REASONS";T[T.HTTP_INTERNAL_SERVER_ERROR=500]="HTTP_INTERNAL_SERVER_ERROR";T[T.HTTP_NOT_IMPLEMENTED=501]="HTTP_NOT_IMPLEMENTED";T[T.HTTP_BAD_GATEWAY=502]="HTTP_BAD_GATEWAY";T[T.HTTP_SERVICE_UNAVAILABLE=503]="HTTP_SERVICE_UNAVAILABLE";T[T.HTTP_GATEWAY_TIMEOUT=504]="HTTP_GATEWAY_TIMEOUT";T[T.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED";T[T.HTTP_VARIANT_ALSO_NEGOTIATES_EXPERIMENTAL=506]="HTTP_VARIANT_ALSO_NEGOTIATES_EXPERIMENTAL";T[T.HTTP_INSUFFICIENT_STORAGE=507]="HTTP_INSUFFICIENT_STORAGE";T[T.HTTP_LOOP_DETECTED=508]="HTTP_LOOP_DETECTED";T[T.HTTP_NOT_EXTENDED=510]="HTTP_NOT_EXTENDED";T[T.HTTP_NETWORK_AUTHENTICATION_REQUIRED=511]="HTTP_NETWORK_AUTHENTICATION_REQUIRED"})(u||={});async function U(r,_={}){let{timeoutMs:E=30000,retry:P=0,...t}=_;if(!Number.isFinite(E)||E<=0||E>2147483647)throw RangeError("timeoutMs must be positive and within the platform timer range");if(!Number.isSafeInteger(P)||P<0)throw RangeError("retry must be a non-negative safe integer");let i=new AbortController,N=t.signal??(r instanceof Request?r.signal:void 0),A=N?AbortSignal.any([N,i.signal]):i.signal,a=!(t.body instanceof ReadableStream)&&!(r instanceof Request&&r.body!==null),D=setTimeout(()=>i.abort(Error(`Request timed out after ${E}ms`)),E);try{for(let H=0;;H++){A.throwIfAborted();let O=await fetch(r,{...t,signal:A});if(!a||![429,503].includes(O.status)||H>=P)return O;let l=I(O.headers.get("retry-after"))??Math.min(2**H*1000,30000);await O.body?.cancel(),await d(l,A)}}finally{clearTimeout(D)}}function d(r,_){return _.throwIfAborted(),new Promise((E,P)=>{let t=()=>{clearTimeout(N),_.removeEventListener("abort",i)},i=()=>{t(),P(_.reason)},N=setTimeout(()=>{t(),E()},Math.min(r,2147483647));if(_.addEventListener("abort",i,{once:!0}),_.aborted)i()})}export{u as Response,U as fetchWithBudget,I as retryAfterMilliseconds};
1
+ export{retryAfterMilliseconds}from"./retry-after";export{createHttpTransferObservation}from"./transfer-observation";import{retryAfterMilliseconds}from"./retry-after";export var Response;((Response)=>{Response[Response["HTTP_CONTINUE"]=100]="HTTP_CONTINUE";Response[Response["HTTP_SWITCHING_PROTOCOLS"]=101]="HTTP_SWITCHING_PROTOCOLS";Response[Response["HTTP_OK"]=200]="HTTP_OK";Response[Response["HTTP_CREATED"]=201]="HTTP_CREATED";Response[Response["HTTP_ACCEPTED"]=202]="HTTP_ACCEPTED";Response[Response["HTTP_NON_AUTHORITATIVE_INFORMATION"]=203]="HTTP_NON_AUTHORITATIVE_INFORMATION";Response[Response["HTTP_NO_CONTENT"]=204]="HTTP_NO_CONTENT";Response[Response["HTTP_RESET_CONTENT"]=205]="HTTP_RESET_CONTENT";Response[Response["HTTP_PARTIAL_CONTENT"]=206]="HTTP_PARTIAL_CONTENT";Response[Response["HTTP_MULTIPLE_CHOICES"]=300]="HTTP_MULTIPLE_CHOICES";Response[Response["HTTP_MOVED_PERMANENTLY"]=301]="HTTP_MOVED_PERMANENTLY";Response[Response["HTTP_FOUND"]=302]="HTTP_FOUND";Response[Response["HTTP_SEE_OTHER"]=303]="HTTP_SEE_OTHER";Response[Response["HTTP_NOT_MODIFIED"]=304]="HTTP_NOT_MODIFIED";Response[Response["HTTP_USE_PROXY"]=305]="HTTP_USE_PROXY";Response[Response["HTTP_UNUSED"]=306]="HTTP_UNUSED";Response[Response["HTTP_TEMPORARY_REDIRECT"]=307]="HTTP_TEMPORARY_REDIRECT";Response[Response["HTTP_PERMANENT_REDIRECT"]=308]="HTTP_PERMANENT_REDIRECT";Response[Response["HTTP_BAD_REQUEST"]=400]="HTTP_BAD_REQUEST";Response[Response["HTTP_UNAUTHORIZED"]=401]="HTTP_UNAUTHORIZED";Response[Response["HTTP_PAYMENT_REQUIRED"]=402]="HTTP_PAYMENT_REQUIRED";Response[Response["HTTP_FORBIDDEN"]=403]="HTTP_FORBIDDEN";Response[Response["HTTP_NOT_FOUND"]=404]="HTTP_NOT_FOUND";Response[Response["HTTP_METHOD_NOT_ALLOWED"]=405]="HTTP_METHOD_NOT_ALLOWED";Response[Response["HTTP_NOT_ACCEPTABLE"]=406]="HTTP_NOT_ACCEPTABLE";Response[Response["HTTP_PROXY_AUTHENTICATION_REQUIRED"]=407]="HTTP_PROXY_AUTHENTICATION_REQUIRED";Response[Response["HTTP_REQUEST_TIMEOUT"]=408]="HTTP_REQUEST_TIMEOUT";Response[Response["HTTP_CONFLICT"]=409]="HTTP_CONFLICT";Response[Response["HTTP_GONE"]=410]="HTTP_GONE";Response[Response["HTTP_LENGTH_REQUIRED"]=411]="HTTP_LENGTH_REQUIRED";Response[Response["HTTP_PRECONDITION_FAILED"]=412]="HTTP_PRECONDITION_FAILED";Response[Response["HTTP_REQUEST_ENTITY_TOO_LARGE"]=413]="HTTP_REQUEST_ENTITY_TOO_LARGE";Response[Response["HTTP_REQUEST_URI_TOO_LONG"]=414]="HTTP_REQUEST_URI_TOO_LONG";Response[Response["HTTP_UNSUPPORTED_MEDIA_TYPE"]=415]="HTTP_UNSUPPORTED_MEDIA_TYPE";Response[Response["HTTP_REQUESTED_RANGE_NOT_SATISFIABLE"]=416]="HTTP_REQUESTED_RANGE_NOT_SATISFIABLE";Response[Response["HTTP_EXPECTATION_FAILED"]=417]="HTTP_EXPECTATION_FAILED";Response[Response["HTTP_I_AM_A_TEAPOT"]=418]="HTTP_I_AM_A_TEAPOT";Response[Response["HTTP_MISDIRECTED_REQUEST"]=421]="HTTP_MISDIRECTED_REQUEST";Response[Response["HTTP_UNPROCESSABLE_ENTITY"]=422]="HTTP_UNPROCESSABLE_ENTITY";Response[Response["HTTP_LOCKED"]=423]="HTTP_LOCKED";Response[Response["HTTP_FAILED_DEPENDENCY"]=424]="HTTP_FAILED_DEPENDENCY";Response[Response["HTTP_RESERVED_FOR_WEBDAV_ADVANCED_COLLECTIONS_EXPIRED_PROPOSAL"]=425]="HTTP_RESERVED_FOR_WEBDAV_ADVANCED_COLLECTIONS_EXPIRED_PROPOSAL";Response[Response["HTTP_UPGRADE_REQUIRED"]=426]="HTTP_UPGRADE_REQUIRED";Response[Response["HTTP_PRECONDITION_REQUIRED"]=428]="HTTP_PRECONDITION_REQUIRED";Response[Response["HTTP_TOO_MANY_REQUESTS"]=429]="HTTP_TOO_MANY_REQUESTS";Response[Response["HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE"]=431]="HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE";Response[Response["HTTP_UNAVAILABLE_FOR_LEGAL_REASONS"]=451]="HTTP_UNAVAILABLE_FOR_LEGAL_REASONS";Response[Response["HTTP_INTERNAL_SERVER_ERROR"]=500]="HTTP_INTERNAL_SERVER_ERROR";Response[Response["HTTP_NOT_IMPLEMENTED"]=501]="HTTP_NOT_IMPLEMENTED";Response[Response["HTTP_BAD_GATEWAY"]=502]="HTTP_BAD_GATEWAY";Response[Response["HTTP_SERVICE_UNAVAILABLE"]=503]="HTTP_SERVICE_UNAVAILABLE";Response[Response["HTTP_GATEWAY_TIMEOUT"]=504]="HTTP_GATEWAY_TIMEOUT";Response[Response["HTTP_VERSION_NOT_SUPPORTED"]=505]="HTTP_VERSION_NOT_SUPPORTED";Response[Response["HTTP_VARIANT_ALSO_NEGOTIATES_EXPERIMENTAL"]=506]="HTTP_VARIANT_ALSO_NEGOTIATES_EXPERIMENTAL";Response[Response["HTTP_INSUFFICIENT_STORAGE"]=507]="HTTP_INSUFFICIENT_STORAGE";Response[Response["HTTP_LOOP_DETECTED"]=508]="HTTP_LOOP_DETECTED";Response[Response["HTTP_NOT_EXTENDED"]=510]="HTTP_NOT_EXTENDED";Response[Response["HTTP_NETWORK_AUTHENTICATION_REQUIRED"]=511]="HTTP_NETWORK_AUTHENTICATION_REQUIRED"})(Response||={});function observationOrigin(value){if(value.length>4096)return{origin:null,omitted:"oversized"};try{const url=new URL(value);if(url.protocol!=="http:"&&url.protocol!=="https:")return{origin:null,omitted:"unsupported"};if(url.origin.length>512)return{origin:null,omitted:"oversized"};return{origin:url.origin,omitted:null}}catch{return{origin:null,omitted:"invalid"}}}function observationLength(response){const header=response.headers.get("content-length");if(header===null||header.length>32)return null;const digits=header.trim();if(!/^\d{1,16}$/.test(digits))return null;const length=Number(digits);return Number.isSafeInteger(length)?length:null}function observe(receiver,callback,value){try{const notify=callback();if(!notify)return;const result=notify.call(receiver,value());if(result){const promise=result instanceof Promise?result:Promise.resolve(result);Promise.prototype.then.call(promise,undefined,()=>{})}}catch{}}export async function fetchWithBudget(input,init={}){const{timeoutMs=30000,retry=0,observer,...rest}=init;if(!Number.isFinite(timeoutMs)||timeoutMs<=0||timeoutMs>2147483647)throw new RangeError("timeoutMs must be positive and within the platform timer range");if(!Number.isSafeInteger(retry)||retry<0)throw new RangeError("retry must be a non-negative safe integer");const ac=new AbortController;const caller=rest.signal??(input instanceof Request?input.signal:undefined);const signal=caller?AbortSignal.any([caller,ac.signal]):ac.signal;const replayable=!(rest.body instanceof ReadableStream)&&!(input instanceof Request&&input.body!==null);const timeoutHandle=setTimeout(()=>ac.abort(new Error(`Request timed out after ${timeoutMs}ms`)),timeoutMs);try{for(let attempt=0;;attempt++){signal.throwIfAborted();observe(observer,()=>observer?.onAttempt,()=>{const url=input instanceof Request?input.url:input instanceof URL?input.href:input;const origin=observationOrigin(url);return Object.freeze({attempt:Math.min(attempt+1,Number.MAX_SAFE_INTEGER),requestedOrigin:origin.origin,originOmitted:origin.omitted})});const response=await fetch(input,{...rest,signal});observe(observer,()=>observer?.onResponse,()=>{const origin=observationOrigin(response.url);return Object.freeze({attempt:Math.min(attempt+1,Number.MAX_SAFE_INTEGER),responseOrigin:origin.origin,originOmitted:origin.omitted,status:response.status,contentLength:observationLength(response)})});if(!replayable||![429,503].includes(response.status)||attempt>=retry)return response;const delay=retryAfterMilliseconds(response.headers.get("retry-after"))??Math.min(2**attempt*1000,30000);await response.body?.cancel();await waitForRetry(delay,signal)}}finally{clearTimeout(timeoutHandle)}}function waitForRetry(delay,signal){signal.throwIfAborted();return new Promise((resolve,reject)=>{const finish=()=>{clearTimeout(timer);signal.removeEventListener("abort",abort)};const abort=()=>{finish();reject(signal.reason)};const timer=setTimeout(()=>{finish();resolve()},Math.min(delay,2147483647));signal.addEventListener("abort",abort,{once:true});if(signal.aborted)abort()})}
@@ -0,0 +1 @@
1
+ export function retryAfterMilliseconds(value,now=Date.now()){const text=value?.trim();if(!text||!Number.isFinite(now))return null;if(/^\d+(?:\.\d+)?$/.test(text)){const milliseconds=Number(text)*1000;return Number.isFinite(milliseconds)&&milliseconds<=Number.MAX_SAFE_INTEGER?Math.ceil(milliseconds):null}if(!/^(?:[a-z]{3}, \d{2} [a-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT|[a-z]+, \d{2}-[a-z]{3}-\d{2} \d{2}:\d{2}:\d{2} GMT|[a-z]{3} [a-z]{3} [ \d]\d \d{2}:\d{2}:\d{2} \d{4})$/i.test(text))return null;const deadline=Date.parse(text);return Number.isFinite(deadline)?Math.max(0,deadline-now):null}
@@ -0,0 +1,32 @@
1
+ import type { HttpAttemptObservation, HttpResponseObservation, HttpTransferObserver } from './index';
2
+ /** Records caller-owned reads. It performs no I/O, retries or scheduling. */
3
+ export declare function createHttpTransferObservation(): Readonly<HttpTransferObservation>;
4
+ export declare interface HttpTransferBucket {
5
+ readonly fromMs: number
6
+ readonly throughMs: number | null
7
+ readonly bytes: number
8
+ readonly chunks: number
9
+ }
10
+ export declare interface HttpTransferReport {
11
+ readonly reason: HttpTransferReason
12
+ readonly attempt: Readonly<HttpAttemptObservation> | null
13
+ readonly response: Readonly<HttpResponseObservation> | null
14
+ readonly bytesReceived: number
15
+ readonly chunksReceived: number
16
+ readonly headersElapsedMs: number | null
17
+ readonly firstByteElapsedMs: number | null
18
+ readonly lastByteElapsedMs: number | null
19
+ readonly elapsedMs: number
20
+ readonly lastByteAgeMs: number | null
21
+ readonly maxInterChunkGapMs: number
22
+ readonly buckets: readonly Readonly<HttpTransferBucket>[]
23
+ readonly coalesced: boolean
24
+ readonly overflowed: boolean
25
+ readonly invalidObservation: boolean
26
+ }
27
+ export declare interface HttpTransferObservation {
28
+ readonly observer: Readonly<HttpTransferObserver>
29
+ readonly received: (byteLength: number) => void
30
+ readonly finish: (reason: HttpTransferReason) => Readonly<HttpTransferReport>
31
+ }
32
+ export type HttpTransferReason = 'complete' | 'total-deadline' | 'idle' | 'transport' | 'http-status' | 'checksum' | 'unknown';
@@ -0,0 +1 @@
1
+ export function createHttpTransferObservation(){let invalidObservation=false;let overflowed=false;let coalesced=false;let start=null;try{const value=performance.now();if(Number.isFinite(value))start=value;else invalidObservation=true}catch{invalidObservation=true}let elapsed=0;let attempt=null;let response=null;let bytesReceived=0;let chunksReceived=0;let headersElapsedMs=null;let firstByteElapsedMs=null;let lastByteElapsedMs=null;let maxInterChunkGapMs=0;let terminal;const buckets=Array.from({length:12},(_,index)=>({fromMs:index*1e4,throughMs:null,bytes:0,chunks:0}));const now=()=>{try{const value=start===null?Number.NaN:performance.now()-start;if(!Number.isFinite(value)||value<elapsed)invalidObservation=true;else if(value>Number.MAX_SAFE_INTEGER){elapsed=Number.MAX_SAFE_INTEGER;overflowed=true}else elapsed=value}catch{invalidObservation=true}return elapsed};const add=(current,incoming)=>{if(incoming>Number.MAX_SAFE_INTEGER-current){overflowed=true;return Number.MAX_SAFE_INTEGER}return current+incoming};const validAttempt=(value)=>Number.isSafeInteger(value)&&value>=1;const validOrigin=(origin,omitted)=>{if(!["invalid","oversized","unsupported",null].includes(omitted))return false;if(origin===null)return omitted!==null;if(typeof origin!=="string"||origin.length>512||omitted!==null)return false;const parsed=new URL(origin);return(parsed.protocol==="http:"||parsed.protocol==="https:")&&parsed.origin===origin};const observer=Object.freeze({onAttempt(value){if(terminal)return;try{const{attempt:number,requestedOrigin,originOmitted}=value;if(!validAttempt(number)||!validOrigin(requestedOrigin,originOmitted)){invalidObservation=true;return}now();attempt=Object.freeze({attempt:number,requestedOrigin,originOmitted})}catch{invalidObservation=true}},onResponse(value){if(terminal)return;try{const{attempt:number,responseOrigin,originOmitted,status,contentLength}=value;if(!validAttempt(number)||!validOrigin(responseOrigin,originOmitted)||!Number.isInteger(status)||status<0||status>599||contentLength!==null&&(!Number.isSafeInteger(contentLength)||contentLength<0)){invalidObservation=true;return}headersElapsedMs=now();response=Object.freeze({attempt:number,responseOrigin,originOmitted,status,contentLength})}catch{invalidObservation=true}}});const received=(byteLength)=>{if(terminal)return;if(!Number.isSafeInteger(byteLength)||byteLength<1){invalidObservation=true;return}const time=now();if(firstByteElapsedMs===null)firstByteElapsedMs=time;if(lastByteElapsedMs!==null)maxInterChunkGapMs=Math.max(maxInterChunkGapMs,time-lastByteElapsedMs);lastByteElapsedMs=time;bytesReceived=add(bytesReceived,byteLength);chunksReceived=add(chunksReceived,1);if(time>=120000)coalesced=true;const bucket=buckets[Math.min(Math.floor(time/1e4),11)];bucket.throughMs=time;bucket.bytes=add(bucket.bytes,byteLength);bucket.chunks=add(bucket.chunks,1)};const finish=(reason)=>{if(terminal)return terminal;if(!["complete","total-deadline","idle","transport","http-status","checksum","unknown"].includes(reason)){invalidObservation=true;reason="unknown"}const time=now();terminal=Object.freeze({reason,attempt,response,bytesReceived,chunksReceived,headersElapsedMs,firstByteElapsedMs,lastByteElapsedMs,elapsedMs:time,lastByteAgeMs:lastByteElapsedMs===null?null:time-lastByteElapsedMs,maxInterChunkGapMs,buckets:Object.freeze(buckets.map((bucket)=>Object.freeze({...bucket}))),coalesced,overflowed,invalidObservation});return terminal};return Object.freeze({observer,received,finish})}
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/http",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.75.569",
5
+ "version": "0.75.571",
6
6
  "description": "Stacks HTTP methods.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [