@venizia/ignis-helpers 0.4.8 → 0.5.0-0

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 (87) hide show
  1. package/dist/esm/common/constants/http.d.ts +3 -0
  2. package/dist/esm/common/constants/http.js +3 -0
  3. package/dist/esm/common/constants/http.js.map +1 -1
  4. package/dist/esm/common/redact.js +2 -0
  5. package/dist/esm/common/redact.js.map +1 -1
  6. package/dist/esm/core.d.ts +5 -2
  7. package/dist/esm/core.js +5 -2
  8. package/dist/esm/core.js.map +1 -1
  9. package/dist/esm/modules/network/http-request/base-network-request.helper.d.ts +5 -0
  10. package/dist/esm/modules/network/http-request/base-network-request.helper.js +14 -17
  11. package/dist/esm/modules/network/http-request/base-network-request.helper.js.map +1 -1
  12. package/dist/esm/modules/network/http-request/common/constants.d.ts +2 -1
  13. package/dist/esm/modules/network/http-request/common/constants.js +2 -1
  14. package/dist/esm/modules/network/http-request/common/constants.js.map +1 -1
  15. package/dist/esm/modules/network/http-request/fetcher/axios-fetcher.d.ts +37 -11
  16. package/dist/esm/modules/network/http-request/fetcher/axios-fetcher.js +181 -38
  17. package/dist/esm/modules/network/http-request/fetcher/axios-fetcher.js.map +1 -1
  18. package/dist/esm/modules/network/http-request/fetcher/base-fetcher.d.ts +204 -18
  19. package/dist/esm/modules/network/http-request/fetcher/base-fetcher.js +433 -13
  20. package/dist/esm/modules/network/http-request/fetcher/base-fetcher.js.map +1 -1
  21. package/dist/esm/modules/network/http-request/fetcher/common/body-limit.d.ts +36 -0
  22. package/dist/esm/modules/network/http-request/fetcher/common/body-limit.js +119 -0
  23. package/dist/esm/modules/network/http-request/fetcher/common/body-limit.js.map +1 -0
  24. package/dist/esm/modules/network/http-request/fetcher/common/errors.d.ts +40 -0
  25. package/dist/esm/modules/network/http-request/fetcher/common/errors.js +37 -0
  26. package/dist/esm/modules/network/http-request/fetcher/common/errors.js.map +1 -0
  27. package/dist/esm/modules/network/http-request/fetcher/common/guard.d.ts +27 -0
  28. package/dist/esm/modules/network/http-request/fetcher/common/guard.js +2 -0
  29. package/dist/esm/modules/network/http-request/fetcher/common/guard.js.map +1 -0
  30. package/dist/esm/modules/network/http-request/fetcher/common/index.d.ts +6 -0
  31. package/dist/esm/modules/network/http-request/fetcher/common/index.js +6 -0
  32. package/dist/esm/modules/network/http-request/fetcher/common/index.js.map +1 -1
  33. package/dist/esm/modules/network/http-request/fetcher/common/request-context.d.ts +15 -0
  34. package/dist/esm/modules/network/http-request/fetcher/common/request-context.js +11 -0
  35. package/dist/esm/modules/network/http-request/fetcher/common/request-context.js.map +1 -0
  36. package/dist/esm/modules/network/http-request/fetcher/common/response-reader.d.ts +9 -0
  37. package/dist/esm/modules/network/http-request/fetcher/common/response-reader.js +14 -0
  38. package/dist/esm/modules/network/http-request/fetcher/common/response-reader.js.map +1 -0
  39. package/dist/esm/modules/network/http-request/fetcher/common/types.d.ts +65 -1
  40. package/dist/esm/modules/network/http-request/fetcher/common/types.js.map +1 -1
  41. package/dist/esm/modules/network/http-request/fetcher/common/utilities.d.ts +68 -0
  42. package/dist/esm/modules/network/http-request/fetcher/common/utilities.js +143 -0
  43. package/dist/esm/modules/network/http-request/fetcher/common/utilities.js.map +1 -0
  44. package/dist/esm/modules/network/http-request/fetcher/index.d.ts +2 -1
  45. package/dist/esm/modules/network/http-request/fetcher/index.js +2 -1
  46. package/dist/esm/modules/network/http-request/fetcher/index.js.map +1 -1
  47. package/dist/esm/modules/network/http-request/fetcher/native-fetcher.d.ts +83 -0
  48. package/dist/esm/modules/network/http-request/fetcher/native-fetcher.js +221 -0
  49. package/dist/esm/modules/network/http-request/fetcher/native-fetcher.js.map +1 -0
  50. package/dist/esm/modules/network/utilities/index.d.ts +1 -0
  51. package/dist/esm/modules/network/utilities/index.js +1 -0
  52. package/dist/esm/modules/network/utilities/index.js.map +1 -1
  53. package/dist/esm/modules/network/utilities/query-string.d.ts +6 -23
  54. package/dist/esm/modules/network/utilities/query-string.js +3 -17
  55. package/dist/esm/modules/network/utilities/query-string.js.map +1 -1
  56. package/dist/esm/modules/network/utilities/url-builder.d.ts +39 -0
  57. package/dist/esm/modules/network/utilities/url-builder.js +102 -0
  58. package/dist/esm/modules/network/utilities/url-builder.js.map +1 -0
  59. package/dist/esm/modules/network/utilities/url-safety/common/constants.d.ts +0 -3
  60. package/dist/esm/modules/network/utilities/url-safety/common/constants.js.map +1 -1
  61. package/dist/esm/modules/network/utilities/url-safety/common/errors.d.ts +38 -0
  62. package/dist/esm/modules/network/utilities/url-safety/common/errors.js +33 -1
  63. package/dist/esm/modules/network/utilities/url-safety/common/errors.js.map +1 -1
  64. package/dist/esm/modules/network/utilities/url-safety/common/types.d.ts +26 -3
  65. package/dist/esm/modules/network/utilities/url-safety/common/types.js.map +1 -1
  66. package/dist/esm/modules/network/utilities/url-safety/guard.d.ts +46 -0
  67. package/dist/esm/modules/network/utilities/url-safety/guard.js +145 -0
  68. package/dist/esm/modules/network/utilities/url-safety/guard.js.map +1 -0
  69. package/dist/esm/modules/network/utilities/url-safety/index.d.ts +1 -1
  70. package/dist/esm/modules/network/utilities/url-safety/index.js +1 -1
  71. package/dist/esm/modules/network/utilities/url-safety/index.js.map +1 -1
  72. package/dist/esm/modules/network/utilities/url-safety/policy.d.ts +52 -2
  73. package/dist/esm/modules/network/utilities/url-safety/policy.js +161 -14
  74. package/dist/esm/modules/network/utilities/url-safety/policy.js.map +1 -1
  75. package/dist/esm/modules/queue/bullmq/helper.d.ts +43 -7
  76. package/dist/esm/modules/queue/bullmq/helper.js +70 -2
  77. package/dist/esm/modules/queue/bullmq/helper.js.map +1 -1
  78. package/dist/esm/modules/retry/helper.d.ts +3 -1
  79. package/dist/esm/modules/retry/helper.js +8 -4
  80. package/dist/esm/modules/retry/helper.js.map +1 -1
  81. package/package.json +3 -3
  82. package/dist/esm/modules/network/http-request/fetcher/node-fetcher.d.ts +0 -41
  83. package/dist/esm/modules/network/http-request/fetcher/node-fetcher.js +0 -111
  84. package/dist/esm/modules/network/http-request/fetcher/node-fetcher.js.map +0 -1
  85. package/dist/esm/modules/network/utilities/url-safety/ingest.d.ts +0 -95
  86. package/dist/esm/modules/network/utilities/url-safety/ingest.js +0 -328
  87. package/dist/esm/modules/network/utilities/url-safety/ingest.js.map +0 -1
@@ -0,0 +1,119 @@
1
+ import { HTTP } from '../../../../../common/constants/http.js';
2
+ import { getError } from '../../../../error/index.js';
3
+ import { UrlSafetyErrors } from '../../../utilities/url-safety/common/errors.js';
4
+ import { UrlSafetyDefaults } from '../../../utilities/url-safety/common/constants.js';
5
+ /** The largest body a call accepts when it names no `maxBytes` of its own. */
6
+ const DEFAULT_MAX_BYTES = UrlSafetyDefaults.MAX_BYTES;
7
+ /** A cap on a body, for a stream piped onward or a body read into memory. Browser-pure: streams and typed arrays only. */
8
+ export class BodyLimit {
9
+ /** The one refusal of a body over the cap; `detail` says how it was found (declared, received, a client's own words). */
10
+ static refuse(opts) {
11
+ return getError({
12
+ error: UrlSafetyErrors.URL_REFUSED,
13
+ message: `[fetch] Body exceeds the cap | ${opts.detail}`,
14
+ });
15
+ }
16
+ /** Enforces `maxBytes` on a stream nothing reads into this process: the cap fails the stream the moment the bytes cross it. */
17
+ static capStream(opts) {
18
+ const { source } = opts;
19
+ const maxBytes = opts.maxBytes ?? DEFAULT_MAX_BYTES;
20
+ let received = 0;
21
+ return source.pipeThrough(new TransformStream({
22
+ transform(chunk, controller) {
23
+ received += chunk.byteLength;
24
+ if (received > maxBytes) {
25
+ controller.error(BodyLimit.refuse({ detail: `received: ${received} | max: ${maxBytes}` }));
26
+ return;
27
+ }
28
+ controller.enqueue(chunk);
29
+ },
30
+ }));
31
+ }
32
+ /** The size a response declares, or `0` when it declares none or an unreadable one. */
33
+ static readDeclaredLength(opts) {
34
+ const declared = Number(opts.headers.get(HTTP.Headers.CONTENT_LENGTH) ?? 0);
35
+ return Number.isFinite(declared) ? declared : 0;
36
+ }
37
+ /** At most `maxBytes` of the body, then the rest released; a body that fails halfway answers what arrived. Never throws on size: a refused status must still say what it was. */
38
+ static async readPrefix(opts) {
39
+ const { response, maxBytes } = opts;
40
+ const reader = response.body?.getReader();
41
+ const chunks = [];
42
+ let received = 0;
43
+ if (!reader) {
44
+ return new Uint8Array();
45
+ }
46
+ try {
47
+ while (received < maxBytes) {
48
+ const { done, value } = await reader.read();
49
+ if (done) {
50
+ break;
51
+ }
52
+ chunks.push(value.subarray(0, maxBytes - received));
53
+ received += chunks[chunks.length - 1].length;
54
+ }
55
+ // eslint-disable-next-line venizia/no-silent-catch -- the status is the answer; a body that broke off is reported as the shorter body it was
56
+ }
57
+ catch {
58
+ // The chunks that arrived stand.
59
+ }
60
+ try {
61
+ await reader.cancel();
62
+ // eslint-disable-next-line venizia/no-silent-catch -- the stream is released as far as it can be; nothing is left to report
63
+ }
64
+ catch {
65
+ // Already closed or errored.
66
+ }
67
+ const bytes = new Uint8Array(received);
68
+ let offset = 0;
69
+ for (const chunk of chunks) {
70
+ bytes.set(chunk, offset);
71
+ offset += chunk.length;
72
+ }
73
+ return bytes;
74
+ }
75
+ /** `readBytes`, decoded as UTF-8 text. */
76
+ static async readText(opts) {
77
+ const bytes = await BodyLimit.readBytes(opts);
78
+ return new TextDecoder().decode(bytes);
79
+ }
80
+ /**
81
+ * Reads a body that must not exceed `maxBytes`, cancelling the moment it does. `content-length` is checked first
82
+ * because it is free, and counted anyway because it may be absent or lie.
83
+ */
84
+ static async readBytes(opts) {
85
+ const { response } = opts;
86
+ const maxBytes = opts.maxBytes ?? DEFAULT_MAX_BYTES;
87
+ const declaredLength = BodyLimit.readDeclaredLength({ headers: response.headers });
88
+ if (declaredLength > maxBytes) {
89
+ await response.body?.cancel();
90
+ throw BodyLimit.refuse({ detail: `declared: ${declaredLength} | max: ${maxBytes}` });
91
+ }
92
+ const reader = response.body?.getReader();
93
+ if (!reader) {
94
+ throw getError({ message: '[readBytes] Response carried no body' });
95
+ }
96
+ const chunks = [];
97
+ let received = 0;
98
+ for (;;) {
99
+ const { done, value } = await reader.read();
100
+ if (done) {
101
+ break;
102
+ }
103
+ received += value.length;
104
+ if (received > maxBytes) {
105
+ await reader.cancel();
106
+ throw BodyLimit.refuse({ detail: `received: ${received} | max: ${maxBytes}` });
107
+ }
108
+ chunks.push(value);
109
+ }
110
+ const bytes = new Uint8Array(received);
111
+ let offset = 0;
112
+ for (const chunk of chunks) {
113
+ bytes.set(chunk, offset);
114
+ offset += chunk.length;
115
+ }
116
+ return bytes;
117
+ }
118
+ }
119
+ //# sourceMappingURL=body-limit.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"body-limit.js","sourceRoot":"","sources":["../../../../../../../src/modules/network/http-request/fetcher/common/body-limit.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,yBAAyB,CAAC;AAC/C,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAE3C,OAAO,EAAE,eAAe,EAAE,MAAM,sDAAsD,CAAC;AACvF,OAAO,EAAE,iBAAiB,EAAE,MAAM,yDAAyD,CAAC;AAE5F,8EAA8E;AAC9E,MAAM,iBAAiB,GAAG,iBAAiB,CAAC,SAAS,CAAC;AAEtD,0HAA0H;AAC1H,MAAM,OAAO,SAAS;IACpB,yHAAyH;IACzH,MAAM,CAAC,MAAM,CAAC,IAAwB;QACpC,OAAO,QAAQ,CAAC;YACd,KAAK,EAAE,eAAe,CAAC,WAAW;YAClC,OAAO,EAAE,kCAAkC,IAAI,CAAC,MAAM,EAAE;SACzD,CAAC,CAAC;IACL,CAAC;IAED,+HAA+H;IAC/H,MAAM,CAAC,SAAS,CAAC,IAGhB;QACC,MAAM,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC;QACxB,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,IAAI,iBAAiB,CAAC;QACpD,IAAI,QAAQ,GAAG,CAAC,CAAC;QAEjB,OAAO,MAAM,CAAC,WAAW,CACvB,IAAI,eAAe,CAAyB;YAC1C,SAAS,CAAC,K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getError } from '@/modules/error';\nimport type { ApplicationError } from '@venizia/ignis-inversion';\nimport { UrlSafetyErrors } from '@/modules/network/utilities/url-safety/common/errors';\nimport { UrlSafetyDefaults } from '@/modules/network/utilities/url-safety/common/constants';\n\n/** The largest body a call accepts when it names no `maxBytes` of its own. */\nconst DEFAULT_MAX_BYTES = UrlSafetyDefaults.MAX_BYTES;\n\n/** A cap on a body, for a stream piped onward or a body read into memory. Browser-pure: streams and typed arrays only. */\nexport class BodyLimit {\n /** The one refusal of a body over the cap; `detail` says how it was found (declared, received, a client's own words). */\n static refuse(opts: { detail: string }): ApplicationError {\n return getError({\n error: UrlSafetyErrors.URL_REFUSED,\n message: `[fetch] Body exceeds the cap | ${opts.detail}`,\n });\n }\n\n /** Enforces `maxBytes` on a stream nothing reads into this process: the cap fails the stream the moment the bytes cross it. */\n static capStream(opts: {\n source: ReadableStream<Uint8Array>;\n maxBytes?: number;\n }): ReadableStream<Uint8Array> {\n const { source } = opts;\n const maxBytes = opts.maxBytes ?? DEFAULT_MAX_BYTES;\n let received = 0;\n\n return source.pipeThrough(\n new TransformStream<Uint8Array, Uint8Array>({\n transform(chunk, controller) {\n received += chunk.byteLength;\n\n if (received > maxBytes) {\n controller.error(\n BodyLimit.refuse({ detail: `received: ${received} | max: ${maxBytes}` }),\n );\n\n return;\n }\n\n controller.enqueue(chunk);\n },\n }),\n );\n }\n\n /** The size a response declares, or `0` when it declares none or an unreadable one. */\n static readDeclaredLength(opts: { headers: Headers }): number {\n const declared = Number(opts.headers.get(HTTP.Headers.CONTENT_LENGTH) ?? 0);\n\n return Number.isFinite(declared) ? declared : 0;\n }\n\n /** At most `maxBytes` of the body, then the rest released; a body that fails halfway answers what arrived. Never throws on size: a refused status must still say what it was. */\n static async readPrefix(opts: { response: Response; maxBytes: number }): Promise<Uint8Array> {\n const { response, maxBytes } = opts;\n const reader = response.body?.getReader();\n const chunks: Uint8Array[] = [];\n let received = 0;\n\n if (!reader) {\n return new Uint8Array();\n }\n\n try {\n while (received < maxBytes) {\n const { done, value } = await reader.read();\n\n if (done) {\n break;\n }\n\n chunks.push(value.subarray(0, maxBytes - received));\n received += chunks[chunks.length - 1].length;\n }\n // eslint-disable-next-line venizia/no-silent-catch -- the status is the answer; a body that broke off is reported as the shorter body it was\n } catch {\n // The chunks that arrived stand.\n }\n\n try {\n await reader.cancel();\n // eslint-disable-next-line venizia/no-silent-catch -- the stream is released as far as it can be; nothing is left to report\n } catch {\n // Already closed or errored.\n }\n\n const bytes = new Uint8Array(received);\n let offset = 0;\n\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.length;\n }\n\n return bytes;\n }\n\n /** `readBytes`, decoded as UTF-8 text. */\n static async readText(opts: { response: Response; maxBytes?: number }): Promise<string> {\n const bytes = await BodyLimit.readBytes(opts);\n\n return new TextDecoder().decode(bytes);\n }\n\n /**\n * Reads a body that must not exceed `maxBytes`, cancelling the moment it does. `content-length` is checked first\n * because it is free, and counted anyway because it may be absent or lie.\n */\n static async readBytes(opts: { response: Response; maxBytes?: number }): Promise<Uint8Array> {\n const { response } = opts;\n const maxBytes = opts.maxBytes ?? DEFAULT_MAX_BYTES;\n const declaredLength = BodyLimit.readDeclaredLength({ headers: response.headers });\n\n if (declaredLength > maxBytes) {\n await response.body?.cancel();\n throw BodyLimit.refuse({ detail: `declared: ${declaredLength} | max: ${maxBytes}` });\n }\n\n const reader = response.body?.getReader();\n\n if (!reader) {\n throw getError({ message: '[readBytes] Response carried no body' });\n }\n\n const chunks: Uint8Array[] = [];\n let received = 0;\n\n for (;;) {\n const { done, value } = await reader.read();\n\n if (done) {\n break;\n }\n\n received += value.length;\n\n if (received > maxBytes) {\n await reader.cancel();\n throw BodyLimit.refuse({ detail: `received: ${received} | max: ${maxBytes}` });\n }\n\n chunks.push(value);\n }\n\n const bytes = new Uint8Array(received);\n let offset = 0;\n\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.length;\n }\n\n return bytes;\n }\n}\n"]}
@@ -0,0 +1,40 @@
1
+ import type { TRegisterErrors } from '@venizia/ignis-inversion';
2
+ import { ApplicationError } from '@venizia/ignis-inversion';
3
+ /** Errors a fetcher raises that are not a refusal of the url guard. */
4
+ declare const FetchErrors: {
5
+ readonly SCHEMA_MISMATCH: {
6
+ readonly message: {
7
+ readonly text: "The upstream answered something else than the schema describes";
8
+ readonly code: "core.fetch.schema_mismatch";
9
+ };
10
+ readonly statusCode: 502;
11
+ readonly category: "integration";
12
+ };
13
+ };
14
+ /** One place a body failed its schema: where, and which rule. Never the value found there. */
15
+ export interface IFetchSchemaIssue {
16
+ path: Array<string | number>;
17
+ code: string;
18
+ }
19
+ /**
20
+ * The body parsed, but it is not what the schema says: the upstream answered something else (502). The message and the
21
+ * issues name paths and rules only, so no part of the body leaves with the error.
22
+ */
23
+ export declare class FetchSchemaError extends ApplicationError {
24
+ /** The status the upstream answered with. */
25
+ readonly status: number;
26
+ readonly url: string;
27
+ readonly issues: IFetchSchemaIssue[];
28
+ constructor(opts: {
29
+ status: number;
30
+ url: string;
31
+ issues: IFetchSchemaIssue[];
32
+ });
33
+ static is(error: unknown): error is FetchSchemaError;
34
+ }
35
+ declare module '@venizia/ignis-inversion' {
36
+ interface IErrorKeyRegistry extends TRegisterErrors<typeof FetchErrors> {
37
+ }
38
+ }
39
+ export {};
40
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1,37 @@
1
+ import { HTTP } from '../../../../../common/constants/index.js';
2
+ import { ApplicationError, ErrorScopes } from '@venizia/ignis-inversion';
3
+ /** Errors a fetcher raises that are not a refusal of the url guard. */
4
+ const FetchErrors = {
5
+ SCHEMA_MISMATCH: {
6
+ message: {
7
+ text: 'The upstream answered something else than the schema describes',
8
+ code: 'core.fetch.schema_mismatch',
9
+ },
10
+ statusCode: HTTP.ResultCodes.RS_5.BadGateway,
11
+ category: ErrorScopes.INTEGRATION,
12
+ },
13
+ };
14
+ /**
15
+ * The body parsed, but it is not what the schema says: the upstream answered something else (502). The message and the
16
+ * issues name paths and rules only, so no part of the body leaves with the error.
17
+ */
18
+ export class FetchSchemaError extends ApplicationError {
19
+ constructor(opts) {
20
+ const where = opts.issues
21
+ .slice(0, 5)
22
+ .map((issue) => `${issue.path.join('.') || '(body)'}: ${issue.code}`)
23
+ .join(', ');
24
+ super({
25
+ error: FetchErrors.SCHEMA_MISMATCH,
26
+ message: `[fetch] The response does not match the schema | status: ${opts.status} | url: ${opts.url} | issues: ${where}`,
27
+ });
28
+ this.name = 'FetchSchemaError';
29
+ this.status = opts.status;
30
+ this.url = opts.url;
31
+ this.issues = opts.issues;
32
+ }
33
+ static is(error) {
34
+ return error instanceof FetchSchemaError;
35
+ }
36
+ }
37
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../../../../../../src/modules/network/http-request/fetcher/common/errors.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAE1C,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAEzE,uEAAuE;AACvE,MAAM,WAAW,GAAG;IAClB,eAAe,EAAE;QACf,OAAO,EAAE;YACP,IAAI,EAAE,gEAAgE;YACtE,IAAI,EAAE,4BAA4B;SACnC;QACD,UAAU,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,UAAU;QAC5C,QAAQ,EAAE,WAAW,CAAC,WAAW;KAClC;CACkD,CAAC;AAQtD;;;GAGG;AACH,MAAM,OAAO,gBAAiB,SAAQ,gBAAgB;IAMpD,YAAY,IAAkE;QAC5E,MAAM,KAAK,GAAG,IAAI,CAAC,MAAM;aACtB,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC;aACX,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,QAAQ,KAAK,KAAK,CAAC,IAAI,EAAE,CAAC;aACpE,IAAI,CAAC,IAAI,CAAC,CAAC;QAEd,KAAK,CAAC;YACJ,KAAK,EAAE,WAAW,CAAC,eAAe;YAClC,OAAO,EAAE,4DAA4D,IAAI,CAAC,MAAM,WAAW,IAAI,CAAC,GAAG,cAAc,KAAK,EAAE;SACzH,CAAC,CAAC;QAEH,IAAI,CAAC,IAAI,GAAG,kBAAkB,CAAC;QAC/B,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC;QAC1B,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC;QACpB,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC;IAC5B,CAAC;IAED,MAAM,CAAC,EAAE,CAAC,KAAc;QACtB,OAAO,KAAK,YAAY,gBAAgB,CAAC;IAC3C,CAAC;CACF","sourcesContent":["import { HTTP } from '@/common/constants';\nimport type { TErrorDefinition, TRegisterErrors } from '@venizia/ignis-inversion';\nimport { ApplicationError, ErrorScopes } from '@venizia/ignis-inversion';\n\n/** Errors a fetcher raises that are not a refusal of the url guard. */\nconst FetchErrors = {\n SCHEMA_MISMATCH: {\n message: {\n text: 'The upstream answered something else than the schema describes',\n code: 'core.fetch.schema_mismatch',\n },\n statusCode: HTTP.ResultCodes.RS_5.BadGateway,\n category: ErrorScopes.INTEGRATION,\n },\n} as const satisfies Record<string, TErrorDefinition>;\n\n/** One place a body failed its schema: where, and which rule. Never the value found there. */\nexport interface IFetchSchemaIssue {\n path: Array<string | number>;\n code: string;\n}\n\n/**\n * The body parsed, but it is not what the schema says: the upstream answered something else (502). The message and the\n * issues name paths and rules only, so no part of the body leaves with the error.\n */\nexport class FetchSchemaError extends ApplicationError {\n /** The status the upstream answered with. */\n readonly status: number;\n readonly url: string;\n readonly issues: IFetchSchemaIssue[];\n\n constructor(opts: { status: number; url: string; issues: IFetchSchemaIssue[] }) {\n const where = opts.issues\n .slice(0, 5)\n .map((issue) => `${issue.path.join('.') || '(body)'}: ${issue.code}`)\n .join(', ');\n\n super({\n error: FetchErrors.SCHEMA_MISMATCH,\n message: `[fetch] The response does not match the schema | status: ${opts.status} | url: ${opts.url} | issues: ${where}`,\n });\n\n this.name = 'FetchSchemaError';\n this.status = opts.status;\n this.url = opts.url;\n this.issues = opts.issues;\n }\n\n static is(error: unknown): error is FetchSchemaError {\n return error instanceof FetchSchemaError;\n }\n}\n\ndeclare module '@venizia/ignis-inversion' {\n interface IErrorKeyRegistry extends TRegisterErrors<typeof FetchErrors> {}\n}\n"]}
@@ -0,0 +1,27 @@
1
+ import type { IUrlSafetyPolicy } from '../../../utilities/url-safety/common/types.js';
2
+ /** One hop the guard vetted: the url to send to, and the addresses to connect to (empty: connect as the client would). */
3
+ export interface IFetchGuardHop {
4
+ url: URL;
5
+ addresses: string[];
6
+ /** The name an https connection to `addresses` verifies the certificate for; unset for a literal address or http. */
7
+ tlsServerName?: string;
8
+ }
9
+ /** A guarded call: vets the first url and every redirect target, one hop at a time. */
10
+ export interface IFetchGuardRoute {
11
+ /** The policy's `timeout` in milliseconds, when it names one: the guard owns the duration units, so a browser bundle does not carry them. */
12
+ readonly timeoutMs?: number;
13
+ vet(opts: {
14
+ url: string;
15
+ signal?: AbortSignal;
16
+ }): Promise<IFetchGuardHop>;
17
+ }
18
+ /**
19
+ * The seam between a fetcher, which is browser-pure, and the url guard, which resolves names with `node:dns`. The server
20
+ * half is `UrlGuard`; a fetcher is handed it as `guardEngine`, so a browser bundle never reaches the resolver.
21
+ */
22
+ export interface IFetchGuard {
23
+ createRoute(opts: {
24
+ policy: IUrlSafetyPolicy;
25
+ }): IFetchGuardRoute;
26
+ }
27
+ //# sourceMappingURL=guard.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=guard.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"guard.js","sourceRoot":"","sources":["../../../../../../../src/modules/network/http-request/fetcher/common/guard.ts"],"names":[],"mappings":"","sourcesContent":["import type { IUrlSafetyPolicy } from '@/modules/network/utilities/url-safety/common/types';\n\n/** One hop the guard vetted: the url to send to, and the addresses to connect to (empty: connect as the client would). */\nexport interface IFetchGuardHop {\n url: URL;\n addresses: string[];\n /** The name an https connection to `addresses` verifies the certificate for; unset for a literal address or http. */\n tlsServerName?: string;\n}\n\n/** A guarded call: vets the first url and every redirect target, one hop at a time. */\nexport interface IFetchGuardRoute {\n /** The policy's `timeout` in milliseconds, when it names one: the guard owns the duration units, so a browser bundle does not carry them. */\n readonly timeoutMs?: number;\n vet(opts: { url: string; signal?: AbortSignal }): Promise<IFetchGuardHop>;\n}\n\n/**\n * The seam between a fetcher, which is browser-pure, and the url guard, which resolves names with `node:dns`. The server\n * half is `UrlGuard`; a fetcher is handed it as `guardEngine`, so a browser bundle never reaches the resolver.\n */\nexport interface IFetchGuard {\n createRoute(opts: { policy: IUrlSafetyPolicy }): IFetchGuardRoute;\n}\n"]}
@@ -1,2 +1,8 @@
1
+ export * from './body-limit.js';
2
+ export * from './errors.js';
3
+ export * from './guard.js';
4
+ export * from './request-context.js';
5
+ export * from './response-reader.js';
1
6
  export * from './types.js';
7
+ export * from './utilities.js';
2
8
  //# sourceMappingURL=index.d.ts.map
@@ -1,2 +1,8 @@
1
+ export * from './body-limit.js';
2
+ export * from './errors.js';
3
+ export * from './guard.js';
4
+ export * from './request-context.js';
5
+ export * from './response-reader.js';
1
6
  export * from './types.js';
7
+ export * from './utilities.js';
2
8
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../../src/modules/network/http-request/fetcher/common/index.ts"],"names":[],"mappings":"AAAA,cAAc,SAAS,CAAC","sourcesContent":["export * from './types';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../../src/modules/network/http-request/fetcher/common/index.ts"],"names":[],"mappings":"AAAA,cAAc,cAAc,CAAC;AAC7B,cAAc,UAAU,CAAC;AACzB,cAAc,SAAS,CAAC;AACxB,cAAc,mBAAmB,CAAC;AAClC,cAAc,mBAAmB,CAAC;AAClC,cAAc,SAAS,CAAC;AACxB,cAAc,aAAa,CAAC","sourcesContent":["export * from './body-limit';\nexport * from './errors';\nexport * from './guard';\nexport * from './request-context';\nexport * from './response-reader';\nexport * from './types';\nexport * from './utilities';\n"]}
@@ -0,0 +1,15 @@
1
+ import type { IFetchRequestContext } from './types.js';
2
+ /** The request a hook sees, frozen so that its url, method and attempt cannot be assigned: only the headers are for the hook to change. */
3
+ export declare class FetchRequestContext implements IFetchRequestContext {
4
+ readonly method: string;
5
+ readonly url: string;
6
+ readonly headers: Headers;
7
+ readonly attempt: number;
8
+ constructor(opts: {
9
+ method: string;
10
+ url: string;
11
+ headers: Headers;
12
+ attempt: number;
13
+ });
14
+ }
15
+ //# sourceMappingURL=request-context.d.ts.map
@@ -0,0 +1,11 @@
1
+ /** The request a hook sees, frozen so that its url, method and attempt cannot be assigned: only the headers are for the hook to change. */
2
+ export class FetchRequestContext {
3
+ constructor(opts) {
4
+ this.method = opts.method;
5
+ this.url = opts.url;
6
+ this.headers = opts.headers;
7
+ this.attempt = opts.attempt;
8
+ Object.freeze(this);
9
+ }
10
+ }
11
+ //# sourceMappingURL=request-context.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"request-context.js","sourceRoot":"","sources":["../../../../../../../src/modules/network/http-request/fetcher/common/request-context.ts"],"names":[],"mappings":"AAEA,2IAA2I;AAC3I,MAAM,OAAO,mBAAmB;IAM9B,YAAY,IAAwE;QAClF,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC;QAC1B,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC;QACpB,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;QAC5B,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;QAE5B,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IACtB,CAAC;CACF","sourcesContent":["import type { IFetchRequestContext } from './types';\n\n/** The request a hook sees, frozen so that its url, method and attempt cannot be assigned: only the headers are for the hook to change. */\nexport class FetchRequestContext implements IFetchRequestContext {\n readonly method: string;\n readonly url: string;\n readonly headers: Headers;\n readonly attempt: number;\n\n constructor(opts: { method: string; url: string; headers: Headers; attempt: number }) {\n this.method = opts.method;\n this.url = opts.url;\n this.headers = opts.headers;\n this.attempt = opts.attempt;\n\n Object.freeze(this);\n }\n}\n"]}
@@ -0,0 +1,9 @@
1
+ /** Turning a `Response` into text, the one way every reader does it. */
2
+ export declare class ResponseReader {
3
+ /** The body as text: `''` for a 204, an empty body or no body; with `maxBytes` the read stops and fails at the cap. */
4
+ static readText(opts: {
5
+ response: Response;
6
+ maxBytes?: number;
7
+ }): Promise<string>;
8
+ }
9
+ //# sourceMappingURL=response-reader.d.ts.map
@@ -0,0 +1,14 @@
1
+ import { HTTP } from '../../../../../common/constants/http.js';
2
+ import { BodyLimit } from './body-limit.js';
3
+ /** Turning a `Response` into text, the one way every reader does it. */
4
+ export class ResponseReader {
5
+ /** The body as text: `''` for a 204, an empty body or no body; with `maxBytes` the read stops and fails at the cap. */
6
+ static async readText(opts) {
7
+ const { response, maxBytes } = opts;
8
+ if (response.status === HTTP.ResultCodes.RS_2.NoContent || response.body === null) {
9
+ return '';
10
+ }
11
+ return maxBytes === undefined ? response.text() : BodyLimit.readText({ response, maxBytes });
12
+ }
13
+ }
14
+ //# sourceMappingURL=response-reader.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"response-reader.js","sourceRoot":"","sources":["../../../../../../../src/modules/network/http-request/fetcher/common/response-reader.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,yBAAyB,CAAC;AAC/C,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC,wEAAwE;AACxE,MAAM,OAAO,cAAc;IACzB,uHAAuH;IACvH,MAAM,CAAC,KAAK,CAAC,QAAQ,CAAC,IAA+C;QACnE,MAAM,EAAE,QAAQ,EAAE,QAAQ,EAAE,GAAG,IAAI,CAAC;QAEpC,IAAI,QAAQ,CAAC,MAAM,KAAK,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,SAAS,IAAI,QAAQ,CAAC,IAAI,KAAK,IAAI,EAAE,CAAC;YAClF,OAAO,EAAE,CAAC;QACZ,CAAC;QAED,OAAO,QAAQ,KAAK,SAAS,CAAC,CAAC,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC,QAAQ,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,CAAC,CAAC;IAC/F,CAAC;CACF","sourcesContent":["import { HTTP } from '@/common/constants/http';\nimport { BodyLimit } from './body-limit';\n\n/** Turning a `Response` into text, the one way every reader does it. */\nexport class ResponseReader {\n /** The body as text: `''` for a 204, an empty body or no body; with `maxBytes` the read stops and fails at the cap. */\n static async readText(opts: { response: Response; maxBytes?: number }): Promise<string> {\n const { response, maxBytes } = opts;\n\n if (response.status === HTTP.ResultCodes.RS_2.NoContent || response.body === null) {\n return '';\n }\n\n return maxBytes === undefined ? response.text() : BodyLimit.readText({ response, maxBytes });\n }\n}\n"]}
@@ -1,5 +1,69 @@
1
+ import type { ValueOrPromise } from '../../../../../common/index.js';
2
+ import type { IRetryBackoffOptions, IRetryContext } from '../../../../retry/common/types.js';
3
+ import type { IUrlSafetyPolicy } from '../../../utilities/url-safety/common/types.js';
1
4
  import type { AxiosInstance, AxiosResponse } from 'axios';
2
5
  import type { TFetcherVariant } from '../../common/index.js';
3
- export type TFetcherResponse<T extends TFetcherVariant> = T extends 'node-fetch' ? Response : AxiosResponse<unknown>;
6
+ /** What a fetcher of this variant answers: a `Response` for `'native'`, an `AxiosResponse` for `'axios'`. */
7
+ export type TFetcherResponse<T extends TFetcherVariant> = T extends 'native' ? Response : AxiosResponse<unknown>;
8
+ /** The client a fetcher of this variant wraps (`getWorker()`): `fetch` or an axios instance. */
4
9
  export type TFetcherWorker<T extends TFetcherVariant> = T extends 'axios' ? AxiosInstance : typeof fetch;
10
+ /** A header map as a call or a default writes it: a `null` or `undefined` value removes that header (a default included). */
11
+ export type TFetchHeaders = Headers | Record<string, string | null | undefined>;
12
+ /** What a fetcher answers when the call passes a `schema`: the parsed body beside the raw response. */
13
+ export interface IFetchParsed<D, RS> {
14
+ data: D;
15
+ status: number;
16
+ headers: Headers;
17
+ response: RS;
18
+ }
19
+ /** Retry settings of a call; the presence of the object turns retrying on. They are `RetryHelper.executeWithRetry`'s. */
20
+ export interface IFetchRetryOptions {
21
+ /** @default 3 */
22
+ maxAttempts?: number;
23
+ /** The budget across every attempt and wait, in milliseconds; a `Retry-After` that does not fit ends the retries. */
24
+ maxTotalMs?: number;
25
+ backoff?: IRetryBackoffOptions;
26
+ /** Replaces the default decision (network error, timeout, 5xx and 429 retry; any other 4xx, a 3xx, a guard refusal, a schema mismatch and a caller abort do not). */
27
+ shouldRetry?: (context: IRetryContext) => ValueOrPromise<boolean>;
28
+ onRetry?: (context: IRetryContext & {
29
+ nextDelayMs: number;
30
+ }) => ValueOrPromise<void>;
31
+ }
32
+ /** What a fetcher applies to every call unless the call says otherwise. */
33
+ export interface IFetcherDefaults {
34
+ /** Per attempt, in milliseconds. */
35
+ timeout?: number;
36
+ headers?: TFetchHeaders;
37
+ retry?: IFetchRetryOptions;
38
+ maxBytes?: number;
39
+ /** A call may replace this policy with its own; it cannot switch the guard off. */
40
+ guard?: IUrlSafetyPolicy;
41
+ }
42
+ /** The request a hook sees. The url is read-only: a hook cannot send the call elsewhere, so the guard vets what is sent. */
43
+ export interface IFetchRequestContext {
44
+ readonly method: string;
45
+ readonly url: string;
46
+ /** Mutable: `onRequest` signs or stamps the request here. */
47
+ readonly headers: Headers;
48
+ /** 1 for the first attempt, then one more per retry. */
49
+ readonly attempt: number;
50
+ }
51
+ /** One function per moment; none returns a value. */
52
+ export interface IFetcherHooks {
53
+ /** Before EVERY send, each retry attempt included, so a signature is fresh. */
54
+ onRequest?: (context: IFetchRequestContext) => ValueOrPromise<void>;
55
+ /** An answer arrived, BEFORE the status check and the schema parse. Once per attempt. */
56
+ onResponse?: (context: {
57
+ request: IFetchRequestContext;
58
+ status: number;
59
+ headers: Headers;
60
+ durationMs: number;
61
+ }) => ValueOrPromise<void>;
62
+ /** The call failed (a timeout, the network, a refused status, a schema mismatch, a guard refusal); once, with the final error, which is then rethrown. */
63
+ onError?: (context: {
64
+ request: IFetchRequestContext;
65
+ error: unknown;
66
+ attempt: number;
67
+ }) => ValueOrPromise<void>;
68
+ }
5
69
  //# sourceMappingURL=types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../../../src/modules/network/http-request/fetcher/common/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { AxiosInstance, AxiosResponse } from 'axios';\nimport type { TFetcherVariant } from '../../common';\n\nexport type TFetcherResponse<T extends TFetcherVariant> = T extends 'node-fetch'\n ? Response\n : AxiosResponse<unknown>;\n\nexport type TFetcherWorker<T extends TFetcherVariant> = T extends 'axios'\n ? AxiosInstance\n : typeof fetch;\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../../../src/modules/network/http-request/fetcher/common/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { ValueOrPromise } from '@/common';\nimport type { IRetryBackoffOptions, IRetryContext } from '@/modules/retry/common/types';\nimport type { IUrlSafetyPolicy } from '@/modules/network/utilities/url-safety/common/types';\nimport type { AxiosInstance, AxiosResponse } from 'axios';\nimport type { TFetcherVariant } from '../../common';\n\n/** What a fetcher of this variant answers: a `Response` for `'native'`, an `AxiosResponse` for `'axios'`. */\nexport type TFetcherResponse<T extends TFetcherVariant> = T extends 'native'\n ? Response\n : AxiosResponse<unknown>;\n\n/** The client a fetcher of this variant wraps (`getWorker()`): `fetch` or an axios instance. */\nexport type TFetcherWorker<T extends TFetcherVariant> = T extends 'axios'\n ? AxiosInstance\n : typeof fetch;\n\n/** A header map as a call or a default writes it: a `null` or `undefined` value removes that header (a default included). */\nexport type TFetchHeaders = Headers | Record<string, string | null | undefined>;\n\n/** What a fetcher answers when the call passes a `schema`: the parsed body beside the raw response. */\nexport interface IFetchParsed<D, RS> {\n data: D;\n status: number;\n headers: Headers;\n response: RS;\n}\n\n/** Retry settings of a call; the presence of the object turns retrying on. They are `RetryHelper.executeWithRetry`'s. */\nexport interface IFetchRetryOptions {\n /** @default 3 */\n maxAttempts?: number;\n /** The budget across every attempt and wait, in milliseconds; a `Retry-After` that does not fit ends the retries. */\n maxTotalMs?: number;\n backoff?: IRetryBackoffOptions;\n /** Replaces the default decision (network error, timeout, 5xx and 429 retry; any other 4xx, a 3xx, a guard refusal, a schema mismatch and a caller abort do not). */\n shouldRetry?: (context: IRetryContext) => ValueOrPromise<boolean>;\n onRetry?: (context: IRetryContext & { nextDelayMs: number }) => ValueOrPromise<void>;\n}\n\n/** What a fetcher applies to every call unless the call says otherwise. */\nexport interface IFetcherDefaults {\n /** Per attempt, in milliseconds. */\n timeout?: number;\n headers?: TFetchHeaders;\n retry?: IFetchRetryOptions;\n maxBytes?: number;\n /** A call may replace this policy with its own; it cannot switch the guard off. */\n guard?: IUrlSafetyPolicy;\n}\n\n/** The request a hook sees. The url is read-only: a hook cannot send the call elsewhere, so the guard vets what is sent. */\nexport interface IFetchRequestContext {\n readonly method: string;\n readonly url: string;\n /** Mutable: `onRequest` signs or stamps the request here. */\n readonly headers: Headers;\n /** 1 for the first attempt, then one more per retry. */\n readonly attempt: number;\n}\n\n/** One function per moment; none returns a value. */\nexport interface IFetcherHooks {\n /** Before EVERY send, each retry attempt included, so a signature is fresh. */\n onRequest?: (context: IFetchRequestContext) => ValueOrPromise<void>;\n /** An answer arrived, BEFORE the status check and the schema parse. Once per attempt. */\n onResponse?: (context: {\n request: IFetchRequestContext;\n status: number;\n headers: Headers;\n durationMs: number;\n }) => ValueOrPromise<void>;\n /** The call failed (a timeout, the network, a refused status, a schema mismatch, a guard refusal); once, with the final error, which is then rethrown. */\n onError?: (context: {\n request: IFetchRequestContext;\n error: unknown;\n attempt: number;\n }) => ValueOrPromise<void>;\n}\n"]}
@@ -0,0 +1,68 @@
1
+ import type { TFetchHeaders } from './types.js';
2
+ /** Header maps: merged per header, the call winning, a `null` or `undefined` value removing a header. */
3
+ export declare class FetchHeaders {
4
+ /** The headers of `layers` in order, later layers over earlier ones, as one `Headers`. */
5
+ static merge(opts: {
6
+ layers: ReadonlyArray<TFetchHeaders | undefined>;
7
+ }): Headers;
8
+ /** `merge` under a JSON content type: the layers may replace it (any case) or remove it with `null`. */
9
+ static withJsonDefault(opts: {
10
+ layers: ReadonlyArray<TFetchHeaders | undefined>;
11
+ }): Headers;
12
+ /** A copy of `headers` keeping only the names in `names`. */
13
+ static only(opts: {
14
+ headers: Headers;
15
+ names: ReadonlyArray<string>;
16
+ }): Headers;
17
+ /** A copy of `headers` without the names in `names`. */
18
+ static without(opts: {
19
+ headers: Headers;
20
+ names: ReadonlyArray<string>;
21
+ }): Headers;
22
+ }
23
+ /** Which statuses a fetcher takes as an answer. */
24
+ export declare class FetchStatus {
25
+ /** Whether `status` is 2xx. */
26
+ private static isSuccess;
27
+ /** The one place `acceptStatus` becomes a decision: a list adds to 2xx, a function replaces it, unset is 2xx. */
28
+ static toPredicate(opts: {
29
+ accept: ReadonlyArray<number> | ((status: number) => boolean) | undefined;
30
+ }): (status: number) => boolean;
31
+ }
32
+ /** The redirect rules of a fetcher that walks redirects by hand. */
33
+ export declare class FetchRedirects {
34
+ /** Request headers that name the body; they go when a redirect turns the request into a GET. */
35
+ static readonly BODY_HEADERS: ReadonlyArray<string>;
36
+ /**
37
+ * The only caller headers a cross-origin redirect keeps. Every other one is dropped: a tenant's webhook secret
38
+ * (`x-api-key`, a signature) must not follow a redirect to a host that tenant did not name.
39
+ */
40
+ static readonly CROSS_ORIGIN_HEADERS: ReadonlyArray<string>;
41
+ static isRedirect(opts: {
42
+ status: number;
43
+ }): boolean;
44
+ /** 303, and a POST answered 301 or 302, continue as a GET without the body. */
45
+ static becomesGet(opts: {
46
+ status: number;
47
+ method: string;
48
+ }): boolean;
49
+ }
50
+ /** What a retried call retries, and for how long a server asks it to wait. */
51
+ export declare class FetchRetry {
52
+ /** The longest wait a call takes between two attempts unless `backoff.maxDelayMs` says otherwise; the retry helper's own default. */
53
+ static readonly DEFAULT_MAX_DELAY_MS = 30000;
54
+ /**
55
+ * The default decision: a network error, a timeout, a 5xx and a 429 are worth another attempt. Any other 4xx, a 3xx, a
56
+ * url the guard refused (refused forever), a schema mismatch and a caller's own abort are not.
57
+ */
58
+ static isRetryable(opts: {
59
+ error: unknown;
60
+ signal?: AbortSignal;
61
+ }): boolean;
62
+ /** The wait a 429 or 503 asks for in `Retry-After`, in milliseconds: seconds, or an HTTP date. `undefined` when there is none. */
63
+ static readRetryAfterMs(opts: {
64
+ error: unknown;
65
+ now?: number;
66
+ }): number | undefined;
67
+ }
68
+ //# sourceMappingURL=utilities.d.ts.map