@orpc/shared 2.0.0-beta.47 → 2.0.0-beta.49

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 (50) hide show
  1. package/README.md +6 -7
  2. package/dist/args.d.ts +2 -0
  3. package/dist/args.js +3 -0
  4. package/dist/array.d.ts +2 -0
  5. package/dist/array.js +7 -0
  6. package/dist/bigint.d.ts +9 -0
  7. package/dist/bigint.js +19 -0
  8. package/dist/buffer.d.ts +18 -0
  9. package/dist/buffer.js +77 -0
  10. package/dist/compare.d.ts +1 -0
  11. package/dist/compare.js +45 -0
  12. package/dist/consts.d.ts +1 -0
  13. package/dist/consts.js +1 -0
  14. package/dist/error.d.ts +1 -0
  15. package/dist/error.js +3 -0
  16. package/dist/function.d.ts +12 -0
  17. package/dist/function.js +38 -0
  18. package/dist/http.d.ts +29 -0
  19. package/dist/http.js +113 -0
  20. package/dist/id.d.ts +8 -0
  21. package/dist/id.js +13 -0
  22. package/dist/index.d.ts +34 -492
  23. package/dist/index.js +32 -0
  24. package/dist/interceptor.d.ts +60 -0
  25. package/dist/interceptor.js +139 -0
  26. package/dist/iterator.d.ts +56 -0
  27. package/dist/iterator.js +157 -0
  28. package/dist/object.d.ts +60 -0
  29. package/dist/object.js +245 -0
  30. package/dist/plugin.d.ts +12 -0
  31. package/dist/plugin.js +61 -0
  32. package/dist/promise.d.ts +17 -0
  33. package/dist/promise.js +32 -0
  34. package/dist/proxy.d.ts +12 -0
  35. package/dist/proxy.js +24 -0
  36. package/dist/queue.d.ts +16 -0
  37. package/dist/queue.js +79 -0
  38. package/dist/signal.d.ts +18 -0
  39. package/dist/signal.js +85 -0
  40. package/dist/stream.d.ts +48 -0
  41. package/dist/stream.js +155 -0
  42. package/dist/tracing.d.ts +73 -0
  43. package/dist/tracing.js +94 -0
  44. package/dist/types.d.ts +26 -0
  45. package/dist/types.js +1 -0
  46. package/dist/value.d.ts +2 -0
  47. package/dist/value.js +6 -0
  48. package/package.json +17 -20
  49. package/dist/index.d.mts +0 -492
  50. package/dist/index.mjs +0 -1117
package/README.md CHANGED
@@ -5,7 +5,7 @@
5
5
  <img alt="codecov" src="https://codecov.io/gh/middleapi/orpc/branch/main/graph/badge.svg">
6
6
  </a>
7
7
  <a href="https://www.npmjs.com/package/@orpc/shared">
8
- <img alt="weekly downloads" src="https://img.shields.io/npm/dw/%40orpc%2Fshared?logo=npm" />
8
+ <img alt="monthly downloads" src="https://img.shields.io/npm/dm/%40orpc%2Fshared?logo=npm" />
9
9
  </a>
10
10
  <a href="https://app.codspeed.io/middleapi/orpc?utm_source=badge">
11
11
  <img alt="CodSpeed" src="https://img.shields.io/endpoint?url=https://codspeed.io/badge.json" />
@@ -41,10 +41,11 @@ export const router = {
41
41
  Then call them from a client that knows every input and output, without generating anything:
42
42
 
43
43
  ```ts
44
- import type { RouterClient } from '@orpc/server'
45
- import type { router } from './router'
46
44
  import { createORPCClient } from '@orpc/client'
47
45
  import { RPCLink } from '@orpc/client/fetch'
46
+ import type { RouterClient } from '@orpc/server'
47
+
48
+ import type { router } from './router'
48
49
 
49
50
  const link = new RPCLink({ origin: 'http://localhost:3000', url: '/rpc' })
50
51
  const client: RouterClient<typeof router> = createORPCClient(link)
@@ -191,15 +192,14 @@ Like what we build over at [middleapi](https://github.com/middleapi)? You can he
191
192
  <td align="center"><a href="https://kellychan.im/?ref=middleapi&amp;utm_source=middleapi&amp;utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="Kelly Peilin Chan"><img src="https://avatars.githubusercontent.com/u/520852?u=6b0f7105f694e7b5cacf410a3f04c7044b469dc8&amp;v=4" width="139" alt="Kelly Peilin Chan"/><br />Kelly Peilin Chan</a></td>
192
193
  <td align="center"><a href="https://guyariely.com/?ref=middleapi&amp;utm_source=middleapi&amp;utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="Guy Ariely"><img src="https://avatars.githubusercontent.com/u/42813496?u=edb6b7f563bf28e160a290832e7da57c0506f8ca&amp;v=4" width="139" alt="Guy Ariely"/><br />Guy Ariely</a></td>
193
194
  <td align="center"><a href="https://paulsenon.com/?ref=middleapi&amp;utm_source=middleapi&amp;utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="PaulSenon"><img src="https://avatars.githubusercontent.com/u/19531087?u=6385741eb91d200b8c513ec6045482e301767ca6&amp;v=4" width="139" alt="PaulSenon"/><br />PaulSenon</a></td>
194
- <td align="center"><a href="https://nakasyou.how/?ref=middleapi&amp;utm_source=middleapi&amp;utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="Shotaro Nakamura"><img src="https://avatars.githubusercontent.com/u/79000684?u=f644df3f29f0e8677a90967115774564f1d9d6ab&amp;v=4" width="139" alt="Shotaro Nakamura"/><br />Shotaro Nakamura</a></td>
195
+ <td align="center"><a href="https://piscis.dev/?ref=middleapi&amp;utm_source=middleapi&amp;utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="Alex"><img src="https://avatars.githubusercontent.com/u/326163?u=b245f368bd940cf51d08c0b6bf55f8257f359437&amp;v=4" width="139" alt="Alex"/><br />Alex</a></td>
195
196
  </tr>
196
197
  <tr>
197
- <td align="center"><a href="https://piscis.dev/?ref=middleapi&amp;utm_source=middleapi&amp;utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="Alex"><img src="https://avatars.githubusercontent.com/u/326163?u=b245f368bd940cf51d08c0b6bf55f8257f359437&amp;v=4" width="139" alt="Alex"/><br />Alex</a></td>
198
198
  <td align="center"><a href="https://opensource.gubanov.eu/?ref=middleapi&amp;utm_source=middleapi&amp;utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="Andrey Gubanov"><img src="https://avatars.githubusercontent.com/u/1082083?u=c5f2daf7ebece498e85c83367bb37b4e10e2649d&amp;v=4" width="139" alt="Andrey Gubanov"/><br />Andrey Gubanov</a></td>
199
199
  </tr>
200
200
  </table>
201
201
 
202
- With thanks to [39 past sponsors](https://orpc.dev/sponsors#past-sponsors) who helped get oRPC here.
202
+ With thanks to [40 past sponsors](https://orpc.dev/sponsors#past-sponsors) who helped get oRPC here.
203
203
 
204
204
  ## Open Source Programs
205
205
 
@@ -209,7 +209,6 @@ With thanks to [39 past sponsors](https://orpc.dev/sponsors#past-sponsors) who h
209
209
  <tr>
210
210
  <td align="center"><a href="https://claude.com/contact-sales/claude-for-oss" target="_blank" rel="noopener" title="Claude for Open Source"><img src="https://cdn.simpleicons.org/claude" width="64" alt="Claude"/><br />Claude</a></td>
211
211
  <td align="center"><a href="https://pullfrog.com/for-oss" target="_blank" rel="noopener" title="Pullfrog for OSS"><img src="https://avatars.githubusercontent.com/in/1768019?s=128&amp;v=4" width="64" alt="Pullfrog"/><br />Pullfrog</a></td>
212
- <td align="center"><a href="https://macroscope.com/open-source" target="_blank" rel="noopener" title="Macroscope for Open Source"><img src="https://avatars.githubusercontent.com/in/900172?s=128&amp;v=4" width="64" alt="Macroscope"/><br />Macroscope</a></td>
213
212
  </tr>
214
213
  </table>
215
214
 
package/dist/args.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ export type MaybeOptionalOptions<TOptions> = object extends TOptions ? [options?: TOptions] : [options: TOptions];
2
+ export declare function resolveMaybeOptionalOptions<T>(rest: MaybeOptionalOptions<T>): T;
package/dist/args.js ADDED
@@ -0,0 +1,3 @@
1
+ export function resolveMaybeOptionalOptions(rest) {
2
+ return rest[0] ?? {}; // 0 only undefined when all fields are optional
3
+ }
@@ -0,0 +1,2 @@
1
+ export declare function toArray<T>(value: T): T extends readonly any[] ? T : Exclude<T, undefined | null>[];
2
+ export declare function splitInHalf<T>(arr: readonly T[]): [T[], T[]];
package/dist/array.js ADDED
@@ -0,0 +1,7 @@
1
+ export function toArray(value) {
2
+ return (Array.isArray(value) ? value : value === undefined || value === null ? [] : [value]);
3
+ }
4
+ export function splitInHalf(arr) {
5
+ const half = Math.ceil(arr.length / 2);
6
+ return [arr.slice(0, half), arr.slice(half)];
7
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Default maximum digits, excluding a leading `-`, when parsing a `bigint` from a string.
3
+ */
4
+ export declare const DEFAULT_MAX_BIGINT_DIGITS = 4300;
5
+ /**
6
+ * Parses a `bigint.toString()` string, or returns `undefined` if it is invalid or has more than `maxDigits` digits.
7
+ * The length is checked first, since `BigInt()` is super-linear in the digit count.
8
+ */
9
+ export declare function parseBigIntString(value: string, maxDigits: number): bigint | undefined;
package/dist/bigint.js ADDED
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Default maximum digits, excluding a leading `-`, when parsing a `bigint` from a string.
3
+ */
4
+ export const DEFAULT_MAX_BIGINT_DIGITS = 4300;
5
+ /**
6
+ * Matches `bigint.toString()` output only.
7
+ */
8
+ const BIGINT_PATTERN = /^-?(?:0|[1-9]\d*)$/;
9
+ /**
10
+ * Parses a `bigint.toString()` string, or returns `undefined` if it is invalid or has more than `maxDigits` digits.
11
+ * The length is checked first, since `BigInt()` is super-linear in the digit count.
12
+ */
13
+ export function parseBigIntString(value, maxDigits) {
14
+ const digits = value.startsWith('-') ? value.length - 1 : value.length;
15
+ if (digits > maxDigits || !BIGINT_PATTERN.test(value)) {
16
+ return undefined;
17
+ }
18
+ return BigInt(value);
19
+ }
@@ -0,0 +1,18 @@
1
+ import type { Arrayable } from 'type-fest';
2
+ /**
3
+ * Load Request/Response/Blob/File/.. to a buffer (Uint8Array<ArrayBuffer>).
4
+ *
5
+ * Prefers the newer `.bytes` method when available as it more efficient but not widely supported yet.
6
+ */
7
+ export declare function loadBytes(source: Pick<Blob, 'arrayBuffer' | 'bytes'>): ReturnType<Blob['bytes']>;
8
+ /**
9
+ * Normalize text or binary-like inputs to either:
10
+ * - the original string value, or
11
+ * - a Uint8Array view over the source bytes.
12
+ */
13
+ export declare function toStringOrBytes(source: Arrayable<string | ArrayBuffer | Pick<Uint8Array<ArrayBuffer>, 'buffer' | 'byteOffset' | 'byteLength'>>): string | Awaited<ReturnType<Blob['bytes']>>;
14
+ /**
15
+ * Encodes bytes to standard, padded base64, as data URLs and many protocols require.
16
+ * Prefers the native `toBase64` or `Buffer`, which are far faster for large outputs.
17
+ */
18
+ export declare function encodeBase64(bytes: Uint8Array): string;
package/dist/buffer.js ADDED
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Load Request/Response/Blob/File/.. to a buffer (Uint8Array<ArrayBuffer>).
3
+ *
4
+ * Prefers the newer `.bytes` method when available as it more efficient but not widely supported yet.
5
+ */
6
+ export async function loadBytes(source) {
7
+ // oxlint-disable-next-line no-restricted-properties
8
+ if (typeof source.bytes === 'function') {
9
+ // oxlint-disable-next-line no-restricted-properties
10
+ return source.bytes();
11
+ }
12
+ return new Uint8Array(await source.arrayBuffer());
13
+ }
14
+ /**
15
+ * Normalize text or binary-like inputs to either:
16
+ * - the original string value, or
17
+ * - a Uint8Array view over the source bytes.
18
+ */
19
+ export function toStringOrBytes(source) {
20
+ if (typeof source === 'string') {
21
+ return source;
22
+ }
23
+ if (source instanceof ArrayBuffer) {
24
+ return new Uint8Array(source);
25
+ }
26
+ if (Array.isArray(source)) {
27
+ return concatBytes(source);
28
+ }
29
+ if (source instanceof Uint8Array) {
30
+ return source;
31
+ }
32
+ return new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
33
+ }
34
+ function toBytes(item) {
35
+ if (typeof item === 'string') {
36
+ return new TextEncoder().encode(item);
37
+ }
38
+ if (item instanceof ArrayBuffer) {
39
+ return new Uint8Array(item);
40
+ }
41
+ if (item instanceof Uint8Array) {
42
+ return item;
43
+ }
44
+ return new Uint8Array(item.buffer, item.byteOffset, item.byteLength);
45
+ }
46
+ function concatBytes(items) {
47
+ const chunks = items.map(toBytes);
48
+ const totalLength = chunks.reduce((sum, chunk) => sum + chunk.byteLength, 0);
49
+ const result = new Uint8Array(totalLength);
50
+ let offset = 0;
51
+ for (const chunk of chunks) {
52
+ result.set(chunk, offset);
53
+ offset += chunk.byteLength;
54
+ }
55
+ return result;
56
+ }
57
+ /**
58
+ * Encodes bytes to standard, padded base64, as data URLs and many protocols require.
59
+ * Prefers the native `toBase64` or `Buffer`, which are far faster for large outputs.
60
+ */
61
+ export function encodeBase64(bytes) {
62
+ const native = bytes;
63
+ if (typeof native.toBase64 === 'function') {
64
+ return native.toBase64();
65
+ }
66
+ // loaded at runtime, so the package keeps working on runtimes without Node.js built-ins
67
+ const NodeBuffer = globalThis.process?.getBuiltinModule?.('node:buffer')?.Buffer;
68
+ if (NodeBuffer !== undefined) {
69
+ return NodeBuffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString('base64');
70
+ }
71
+ const chunkSize = 8192; // 8KB chunks to stay well below call stack limits
72
+ let binaryString = '';
73
+ for (let i = 0; i < bytes.length; i += chunkSize) {
74
+ binaryString += String.fromCharCode(...bytes.subarray(i, i + chunkSize));
75
+ }
76
+ return btoa(binaryString);
77
+ }
@@ -0,0 +1 @@
1
+ export declare function isDeepEqual(a: unknown, b: unknown): boolean;
@@ -0,0 +1,45 @@
1
+ import { isPlainObject } from './object.js';
2
+ export function isDeepEqual(a, b) {
3
+ return isDeepEqualInternal(a, b, new WeakMap());
4
+ }
5
+ function isDeepEqualInternal(a, b, visited) {
6
+ if (Object.is(a, b)) {
7
+ return true;
8
+ }
9
+ if (Array.isArray(a)) {
10
+ if (!Array.isArray(b) || a.length !== b.length) {
11
+ return false;
12
+ }
13
+ }
14
+ else if (!isPlainObject(a) || !isPlainObject(b)) {
15
+ // Anything else (primitives, Date, RegExp, Map, Set, class instances, ...) is only equal when Object.is above matched:
16
+ // non-plain objects keep their state outside own enumerable keys, so they cannot be compared structurally
17
+ return false;
18
+ }
19
+ const aRecord = a;
20
+ const bRecord = b;
21
+ const visitedMatches = visited.get(a);
22
+ if (visitedMatches?.has(b)) {
23
+ return true;
24
+ }
25
+ if (visitedMatches) {
26
+ visitedMatches.add(b);
27
+ }
28
+ else {
29
+ visited.set(a, new WeakSet([b]));
30
+ }
31
+ const aKeys = Object.keys(aRecord).filter((k) => aRecord[k] !== undefined);
32
+ const bKeys = Object.keys(bRecord).filter((k) => bRecord[k] !== undefined);
33
+ if (aKeys.length !== bKeys.length) {
34
+ return false;
35
+ }
36
+ for (const key of aKeys) {
37
+ if (!Object.hasOwn(bRecord, key)) {
38
+ return false;
39
+ }
40
+ if (!isDeepEqualInternal(aRecord[key], bRecord[key], visited)) {
41
+ return false;
42
+ }
43
+ }
44
+ return true;
45
+ }
@@ -0,0 +1 @@
1
+ export declare const ORPC_NAME = "orpc";
package/dist/consts.js ADDED
@@ -0,0 +1 @@
1
+ export const ORPC_NAME = 'orpc';
@@ -0,0 +1 @@
1
+ export declare function isAbortError(error: unknown): error is Error;
package/dist/error.js ADDED
@@ -0,0 +1,3 @@
1
+ export function isAbortError(error) {
2
+ return error instanceof Error && error.name.includes('Abort');
3
+ }
@@ -0,0 +1,12 @@
1
+ export type AnyFunction = (...args: any[]) => any;
2
+ /**
3
+ * Checks whether a value is an async generator function (`async function*`).
4
+ */
5
+ export declare function isAsyncGeneratorFunction(value: unknown): value is (...args: any[]) => AsyncGenerator;
6
+ export declare function once<T>(fn: () => T): () => T;
7
+ /**
8
+ * Executes the callback function after the current call stack has been cleared,
9
+ * waiting at least `delay` ms when `setTimeout` is available.
10
+ */
11
+ export declare function defer(callback: () => void, delay?: number): void;
12
+ export declare function tryOrUndefined<T>(fn: () => T): undefined | T;
@@ -0,0 +1,38 @@
1
+ const AsyncGeneratorFunction = /* @__PURE__ */ (() => Object.getPrototypeOf(async function* () { }).constructor)();
2
+ /**
3
+ * Checks whether a value is an async generator function (`async function*`).
4
+ */
5
+ export function isAsyncGeneratorFunction(value) {
6
+ return value instanceof AsyncGeneratorFunction;
7
+ }
8
+ export function once(fn) {
9
+ let cached;
10
+ return () => {
11
+ if (cached) {
12
+ return cached.result;
13
+ }
14
+ const result = fn();
15
+ cached = { result };
16
+ return result;
17
+ };
18
+ }
19
+ /**
20
+ * Executes the callback function after the current call stack has been cleared,
21
+ * waiting at least `delay` ms when `setTimeout` is available.
22
+ */
23
+ export function defer(callback, delay = 0) {
24
+ if (typeof setTimeout === 'function') {
25
+ setTimeout(callback, delay);
26
+ }
27
+ else {
28
+ void Promise.resolve().then(() => Promise.resolve().then(() => Promise.resolve().then(callback)));
29
+ }
30
+ }
31
+ export function tryOrUndefined(fn) {
32
+ try {
33
+ return fn();
34
+ }
35
+ catch {
36
+ return undefined;
37
+ }
38
+ }
package/dist/http.d.ts ADDED
@@ -0,0 +1,29 @@
1
+ export declare function pathToHttpPath(path: readonly string[]): `/${string}`;
2
+ export declare function normalizeHttpPath(path: string): `/${string}`;
3
+ export declare function mergeHttpPath(a: `/${string}`, b: `/${string}`): `/${string}`;
4
+ export declare function matchesHttpPathPrefix(url: `/${string}`, prefix: `/${string}`): boolean;
5
+ export declare function matchesHttpPath(url: `/${string}`, path: `/${string}`): boolean;
6
+ /**
7
+ * Parse Accept-Encoding into each coding's q-value, where `0` means the coding is explicitly
8
+ * unacceptable. The `*` wildcard is kept under its own key; use {@link isAcceptableEncoding}
9
+ * to decide whether a coding is acceptable.
10
+ *
11
+ * @see https://www.rfc-editor.org/rfc/rfc9110.html#name-accept-encoding
12
+ */
13
+ export declare function parseAcceptEncodingQualities(header: string | undefined): Map<string, number>;
14
+ /**
15
+ * Whether the client accepts a coding, given qualities from {@link parseAcceptEncodingQualities}.
16
+ * An explicit q-value takes precedence over the `*` wildcard, so `gzip;q=0, *` never accepts gzip.
17
+ *
18
+ * @see https://www.rfc-editor.org/rfc/rfc9110.html#name-accept-encoding
19
+ */
20
+ export declare function isAcceptableEncoding(qualities: Map<string, number>, coding: string): boolean;
21
+ /**
22
+ * Add `accept-encoding` to a Vary header value. The encoding is chosen from the request, so a
23
+ * shared cache must key on it or it will hand a compressed body to a client that cannot decode it.
24
+ *
25
+ * @see https://www.rfc-editor.org/rfc/rfc9110.html#name-vary
26
+ */
27
+ export declare function varyByAcceptEncoding(vary: string | undefined): string;
28
+ export declare function isNoTransformCacheControl(cacheControl: string | undefined): boolean;
29
+ export declare function isCompressibleContentType(contentType: string | null | undefined): boolean;
package/dist/http.js ADDED
@@ -0,0 +1,113 @@
1
+ import { safeDecodeURIComponent, safeEncodeURIComponent } from '@standard-server/shared';
2
+ export function pathToHttpPath(path) {
3
+ return `/${path.map(safeEncodeURIComponent).join('/')}`;
4
+ }
5
+ export function normalizeHttpPath(path) {
6
+ const paths = path.split('/');
7
+ if (paths.at(0) === '') {
8
+ paths.shift();
9
+ }
10
+ return pathToHttpPath(paths.map(safeDecodeURIComponent));
11
+ }
12
+ export function mergeHttpPath(a, b) {
13
+ return `${a.endsWith('/') ? a.slice(0, -1) : a}${b}`;
14
+ }
15
+ export function matchesHttpPathPrefix(url, prefix) {
16
+ if (!url.startsWith(prefix)) {
17
+ return false;
18
+ }
19
+ const charAfterPrefix = url[prefix.length];
20
+ // order by most common cases for better performance
21
+ return (charAfterPrefix === '/' ||
22
+ charAfterPrefix === '?' ||
23
+ charAfterPrefix === '#' ||
24
+ charAfterPrefix === undefined ||
25
+ prefix[prefix.length - 1] === '/');
26
+ }
27
+ export function matchesHttpPath(url, path) {
28
+ const pathWithoutEndSlash = path.endsWith('/') ? path.slice(0, path.length - 1) : path;
29
+ if (!url.startsWith(pathWithoutEndSlash)) {
30
+ return false;
31
+ }
32
+ let charAfterPrefix = url[pathWithoutEndSlash.length];
33
+ if (charAfterPrefix === '/') {
34
+ charAfterPrefix = url[pathWithoutEndSlash.length + 1];
35
+ }
36
+ // order by most common cases for better performance
37
+ return charAfterPrefix === undefined || charAfterPrefix === '?' || charAfterPrefix === '#';
38
+ }
39
+ const ACCEPT_ENCODING_QUALITY_REGEX = /^\s*q=([\d.]+)\s*$/i;
40
+ /**
41
+ * Parse Accept-Encoding into each coding's q-value, where `0` means the coding is explicitly
42
+ * unacceptable. The `*` wildcard is kept under its own key; use {@link isAcceptableEncoding}
43
+ * to decide whether a coding is acceptable.
44
+ *
45
+ * @see https://www.rfc-editor.org/rfc/rfc9110.html#name-accept-encoding
46
+ */
47
+ export function parseAcceptEncodingQualities(header) {
48
+ const qualities = new Map();
49
+ for (const part of header?.split(',') ?? []) {
50
+ const [rawCoding, ...params] = part.split(';');
51
+ const coding = rawCoding.trim().toLowerCase();
52
+ if (coding === '') {
53
+ continue;
54
+ }
55
+ const quality = params
56
+ .map((param) => ACCEPT_ENCODING_QUALITY_REGEX.exec(param)?.[1])
57
+ .find((value) => value !== undefined);
58
+ qualities.set(coding, quality === undefined ? 1 : Number(quality));
59
+ }
60
+ return qualities;
61
+ }
62
+ /**
63
+ * Whether the client accepts a coding, given qualities from {@link parseAcceptEncodingQualities}.
64
+ * An explicit q-value takes precedence over the `*` wildcard, so `gzip;q=0, *` never accepts gzip.
65
+ *
66
+ * @see https://www.rfc-editor.org/rfc/rfc9110.html#name-accept-encoding
67
+ */
68
+ export function isAcceptableEncoding(qualities, coding) {
69
+ return (qualities.get(coding) ?? qualities.get('*') ?? 0) > 0;
70
+ }
71
+ /**
72
+ * Add `accept-encoding` to a Vary header value. The encoding is chosen from the request, so a
73
+ * shared cache must key on it or it will hand a compressed body to a client that cannot decode it.
74
+ *
75
+ * @see https://www.rfc-editor.org/rfc/rfc9110.html#name-vary
76
+ */
77
+ export function varyByAcceptEncoding(vary) {
78
+ if (vary === undefined) {
79
+ return 'accept-encoding';
80
+ }
81
+ const fields = vary.split(',').map((field) => field.trim().toLowerCase());
82
+ // `*` already forbids reuse across requests, so narrowing it would be a downgrade
83
+ return fields.includes('accept-encoding') || fields.includes('*')
84
+ ? vary
85
+ : `${vary}, accept-encoding`;
86
+ }
87
+ /**
88
+ * Whether Cache-Control includes the no-transform directive, which forbids transforming the body.
89
+ *
90
+ * @see https://www.rfc-editor.org/rfc/rfc9111.html#name-no-transform
91
+ */
92
+ const CACHE_CONTROL_NO_TRANSFORM_REGEX = /(?:^|,)\s*no-transform\s*(?:,|$)/i;
93
+ export function isNoTransformCacheControl(cacheControl) {
94
+ if (cacheControl === undefined) {
95
+ return false;
96
+ }
97
+ return CACHE_CONTROL_NO_TRANSFORM_REGEX.test(cacheControl);
98
+ }
99
+ /**
100
+ * inspired from Hono Compression Plugin
101
+ */
102
+ const COMPRESSIBLE_CONTENT_TYPE_REGEX = /^\s*(?:text\/(?!event-stream(?:[;\s]|$))[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i;
103
+ // Cap length to skip the regex on pathological inputs.
104
+ const MAX_COMPRESSIBLE_CONTENT_TYPE_LENGTH = 1024;
105
+ export function isCompressibleContentType(contentType) {
106
+ if (contentType === null || contentType === undefined) {
107
+ return false;
108
+ }
109
+ if (contentType.length > MAX_COMPRESSIBLE_CONTENT_TYPE_LENGTH) {
110
+ return false;
111
+ }
112
+ return COMPRESSIBLE_CONTENT_TYPE_REGEX.test(contentType);
113
+ }
package/dist/id.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Compares two sequential IDs.
3
+ * Returns:
4
+ * - negative if `a` < `b`
5
+ * - positive if `a` > `b`
6
+ * - 0 if equal
7
+ */
8
+ export declare function compareSequentialIds(a: string, b: string): number;
package/dist/id.js ADDED
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Compares two sequential IDs.
3
+ * Returns:
4
+ * - negative if `a` < `b`
5
+ * - positive if `a` > `b`
6
+ * - 0 if equal
7
+ */
8
+ export function compareSequentialIds(a, b) {
9
+ if (a.length !== b.length) {
10
+ return a.length - b.length;
11
+ }
12
+ return a < b ? -1 : a > b ? 1 : 0;
13
+ }