@heroku/heroku-fetch 0.1.6 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +19 -21
  2. package/dist/browser.d.ts +2 -3
  3. package/dist/browser.js +1 -2
  4. package/dist/client/browser-environment-defaults.d.ts +13 -1
  5. package/dist/client/browser-environment-defaults.js +14 -0
  6. package/dist/client/http-error-handler.js +2 -1
  7. package/dist/client/http-request-hooks.d.ts +68 -7
  8. package/dist/client/http-request-hooks.js +147 -44
  9. package/dist/client/index.d.ts +10 -3
  10. package/dist/client/index.js +72 -26
  11. package/dist/client/node-environment-defaults.d.ts +40 -6
  12. package/dist/client/node-environment-defaults.js +89 -14
  13. package/dist/client/request-id.d.ts +40 -0
  14. package/dist/client/request-id.js +78 -0
  15. package/dist/client/two-factor-authentication-handler.d.ts +18 -4
  16. package/dist/client/two-factor-authentication-handler.js +22 -18
  17. package/dist/debug-loggers.d.ts +0 -1
  18. package/dist/debug-loggers.js +0 -1
  19. package/dist/host.d.ts +33 -0
  20. package/dist/host.js +38 -0
  21. package/dist/index.d.ts +2 -3
  22. package/dist/index.js +1 -2
  23. package/dist/public-types.d.ts +7 -0
  24. package/dist/public-types.js +7 -0
  25. package/dist/redact.d.ts +26 -0
  26. package/dist/redact.js +158 -0
  27. package/dist/types.d.ts +105 -1
  28. package/package.json +4 -5
  29. package/dist/auth/auth.d.ts +0 -66
  30. package/dist/auth/auth.js +0 -93
  31. package/dist/cli/cli-login.d.ts +0 -7
  32. package/dist/cli/cli-login.js +0 -7
  33. package/dist/cli/login/browser-login.d.ts +0 -8
  34. package/dist/cli/login/browser-login.js +0 -115
  35. package/dist/cli/login/index.d.ts +0 -34
  36. package/dist/cli/login/index.js +0 -193
  37. package/dist/cli/login/interactive-login.d.ts +0 -8
  38. package/dist/cli/login/interactive-login.js +0 -59
  39. package/dist/cli/login/netrc-utils.d.ts +0 -22
  40. package/dist/cli/login/netrc-utils.js +0 -85
  41. package/dist/cli/login/oauth.d.ts +0 -20
  42. package/dist/cli/login/oauth.js +0 -142
  43. package/dist/cli/login/sso-login.d.ts +0 -8
  44. package/dist/cli/login/sso-login.js +0 -41
  45. package/dist/cli/login/types.d.ts +0 -42
  46. package/dist/cli/login/types.js +0 -11
package/README.md CHANGED
@@ -27,7 +27,7 @@ npm install @heroku/heroku-fetch
27
27
  import { HerokuApiClient } from '@heroku/heroku-fetch';
28
28
 
29
29
  // Create a client for the Platform API
30
- // Automatically uses token from HEROKU_API_KEY env var or ~/.netrc
30
+ // Automatically uses token from the HEROKU_API_KEY env var
31
31
  const client = new HerokuApiClient({
32
32
  service: 'platform',
33
33
  });
@@ -78,29 +78,36 @@ const customClient = new HerokuApiClient({
78
78
 
79
79
  ## Authentication
80
80
 
81
- ### Automatic Token from Environment or Netrc (Default)
81
+ ### Automatic Token from Environment (Default)
82
82
 
83
- By default, the client automatically fetches tokens from `HEROKU_API_KEY` environment variable or `~/.netrc` file. **No manual token management required!**
83
+ By default, the client reads the token from the `HEROKU_API_KEY` environment variable:
84
84
 
85
85
  ```typescript
86
86
  import { HerokuApiClient } from '@heroku/heroku-fetch';
87
87
 
88
- // Token automatically loaded from HEROKU_API_KEY or ~/.netrc
88
+ // Token automatically loaded from HEROKU_API_KEY
89
89
  const client = new HerokuApiClient({
90
90
  service: 'platform',
91
91
  });
92
92
  ```
93
93
 
94
- The token priority is:
95
- 1. `HEROKU_API_KEY` environment variable
96
- 2. `~/.netrc` file (api.heroku.com machine)
97
-
98
- If you need to manually retrieve the token for other purposes, you can use `getAuthToken()`:
94
+ heroku-fetch does not read stored CLI credentials. To authenticate with
95
+ credentials saved by the Heroku CLI (native credential store or `~/.netrc`),
96
+ resolve a token with [`@heroku/heroku-credential-manager`](https://github.com/heroku/heroku-credential-manager)
97
+ and pass it to the client:
99
98
 
100
99
  ```typescript
101
- import { getAuthToken } from '@heroku/heroku-fetch';
100
+ import { HerokuApiClient } from '@heroku/heroku-fetch';
101
+ import { getAuth } from '@heroku/heroku-credential-manager';
102
102
 
103
- const token = getAuthToken(); // Returns string | undefined
103
+ // Pass the account to read the native credential store (Keychain, libsecret,
104
+ // Windows Credential Manager). Passing `undefined` reads `~/.netrc` by host
105
+ // only — it will not find credentials stored solely in the native store.
106
+ const { token } = await getAuth('your-account@example.com', 'api.heroku.com');
107
+ const client = new HerokuApiClient({
108
+ service: 'platform',
109
+ token,
110
+ });
104
111
  ```
105
112
 
106
113
  ### Static Bearer Token
@@ -117,15 +124,6 @@ const client = new HerokuApiClient({
117
124
  Use a function to dynamically retrieve or refresh tokens:
118
125
 
119
126
  ```typescript
120
- import { getAuthTokenProvider } from '@heroku/heroku-fetch';
121
-
122
- // Option 1: Use the built-in provider for dynamic token fetching
123
- const client = new HerokuApiClient({
124
- service: 'platform',
125
- token: getAuthTokenProvider(), // Returns a function that fetches token each time
126
- });
127
-
128
- // Option 2: Provide your own custom token function
129
127
  const client = new HerokuApiClient({
130
128
  service: 'platform',
131
129
  token: async () => {
@@ -487,7 +485,7 @@ import { HerokuApiClient } from '@heroku/heroku-fetch';
487
485
 
488
486
  export default class AppsList extends Command {
489
487
  async run() {
490
- // Client automatically uses token from env or netrc
488
+ // Client automatically uses token from the HEROKU_API_KEY env var
491
489
  const client = new HerokuApiClient({
492
490
  service: 'platform',
493
491
  });
package/dist/browser.d.ts CHANGED
@@ -2,12 +2,11 @@
2
2
  * Browser-specific entry point for @heroku/heroku-fetch
3
3
  *
4
4
  * This entry point excludes Node.js-specific features like:
5
- * - CLI utilities (login, 2FA prompts)
6
- * - File system access (netrc)
5
+ * - CLI utilities (2FA prompts)
7
6
  * - Process environment variables
8
7
  *
9
8
  * Use this entry point when bundling for browser environments.
10
9
  */
11
10
  export { HerokuApiClient } from './client/index.js';
12
11
  export { AuthenticationError, HerokuApiError, NotFoundError, RateLimitError, TwoFactorRequiredError, } from './errors.js';
13
- export type { HerokuApiClientOptions, HerokuError, HerokuErrorResponse, HerokuService, RequestOptions, ServiceConfig, TokenProvider, TwoFactorOptions, } from './types.js';
12
+ export type * from './public-types.js';
package/dist/browser.js CHANGED
@@ -2,8 +2,7 @@
2
2
  * Browser-specific entry point for @heroku/heroku-fetch
3
3
  *
4
4
  * This entry point excludes Node.js-specific features like:
5
- * - CLI utilities (login, 2FA prompts)
6
- * - File system access (netrc)
5
+ * - CLI utilities (2FA prompts)
7
6
  * - Process environment variables
8
7
  *
9
8
  * Use this entry point when bundling for browser environments.
@@ -2,7 +2,7 @@
2
2
  * Default providers for browser environments
3
3
  * These are minimal since browsers don't have file system or CLI access
4
4
  */
5
- import type { TokenProvider, TwoFactorOptions } from '../types.js';
5
+ import type { FetchLike, TokenProvider, TwoFactorOptions } from '../types.js';
6
6
  /**
7
7
  * Get default token provider for browsers (none - must be explicitly provided)
8
8
  */
@@ -20,3 +20,15 @@ export declare function getDefaultTwoFactorOptions(): TwoFactorOptions | undefin
20
20
  * a TypeError in some bundlers.
21
21
  */
22
22
  export declare function getDefaultDispatcher(): Promise<undefined>;
23
+ /**
24
+ * Get a default `fetch` for the browser: the global `fetch`, with no
25
+ * dispatcher. Browsers route through their own proxy stack, so there is
26
+ * nothing to pair. Mirrors the Node `getDefaultFetch()` so consumers can call
27
+ * it uniformly across environments.
28
+ *
29
+ * Bound to `globalThis` because the browser `fetch` is a WebIDL method that
30
+ * brand-checks its receiver: a detached reference (`const f = fetch; f(...)`)
31
+ * throws `Illegal invocation`, and consumers call this returned reference
32
+ * detached.
33
+ */
34
+ export declare function getDefaultFetch(): Promise<FetchLike>;
@@ -25,3 +25,17 @@ export function getDefaultTwoFactorOptions() {
25
25
  export async function getDefaultDispatcher() {
26
26
  return undefined;
27
27
  }
28
+ /**
29
+ * Get a default `fetch` for the browser: the global `fetch`, with no
30
+ * dispatcher. Browsers route through their own proxy stack, so there is
31
+ * nothing to pair. Mirrors the Node `getDefaultFetch()` so consumers can call
32
+ * it uniformly across environments.
33
+ *
34
+ * Bound to `globalThis` because the browser `fetch` is a WebIDL method that
35
+ * brand-checks its receiver: a detached reference (`const f = fetch; f(...)`)
36
+ * throws `Illegal invocation`, and consumers call this returned reference
37
+ * detached.
38
+ */
39
+ export async function getDefaultFetch() {
40
+ return globalThis.fetch.bind(globalThis);
41
+ }
@@ -5,6 +5,7 @@
5
5
  */
6
6
  import { debugError } from '../debug-loggers.js';
7
7
  import { AuthenticationError, HerokuApiError, NotFoundError, RateLimitError, TwoFactorRequiredError, } from '../errors.js';
8
+ import { logScrubbed } from '../redact.js';
8
9
  /**
9
10
  * Parse and handle an error response from the API
10
11
  * Throws appropriate typed error based on status code
@@ -20,7 +21,7 @@ export async function handleErrorResponse(response) {
20
21
  catch {
21
22
  // Failed to parse error body, continue without it
22
23
  }
23
- debugError('Error response: %d %O', response.status, errorBody);
24
+ await logScrubbed(debugError, 'Error response: %d %O', response.status, errorBody);
24
25
  // Check for 2FA error (can be 403 or 412)
25
26
  if (response.status === 412
26
27
  || (response.status === 403 && errorBody?.id === 'two_factor')) {
@@ -5,14 +5,75 @@
5
5
  * used by the ky HTTP client.
6
6
  */
7
7
  import type { AfterResponseHook, BeforeRequestHook } from 'ky';
8
- import type { TwoFactorOptions } from '../types.js';
8
+ import type { ResponseMetadata, TwoFactorOptions } from '../types.js';
9
+ import { type RequestIdStore } from './request-id.js';
9
10
  /**
10
- * Create a beforeRequest hook that adds authentication and custom headers
11
+ * Create a beforeRequest hook that attaches the bearer token.
12
+ *
13
+ * Static headers (the `Accept` default and any consumer-supplied custom
14
+ * headers) are set on the ky instance via its `headers` option, so ky merges
15
+ * them with per-call headers (per-call winning) before this hook runs. Only the
16
+ * token is resolved here, since it comes from an async provider and so can't be
17
+ * a static instance header.
18
+ */
19
+ export declare function createBeforeRequestHook(getToken: () => Promise<string | undefined>, debug?: boolean): BeforeRequestHook;
20
+ /**
21
+ * Create a beforeRequest hook that sets the accumulating `Request-Id`
22
+ * correlation header (with the 7KB overflow guard).
11
23
  */
12
- export declare function createBeforeRequestHook(getToken: () => Promise<string | undefined>, defaultAccept: string | undefined, customHeaders?: Record<string, string>, debug?: boolean): BeforeRequestHook;
24
+ export declare function createRequestIdBeforeHook(store: RequestIdStore): BeforeRequestHook;
13
25
  /**
14
- * Create an afterResponse hook that handles 2FA challenges and errors
26
+ * Create an afterResponse hook that feeds the server's echoed `Request-Id`s
27
+ * back into the accumulating store so later requests carry the full chain.
28
+ *
29
+ * Runs only on the success path: it is registered after the error-handling
30
+ * hook, which throws on a non-ok response and stops the chain.
31
+ */
32
+ export declare function createRequestIdAfterHook(store: RequestIdStore): AfterResponseHook;
33
+ /**
34
+ * Create an afterResponse hook that surfaces server warning headers to the
35
+ * user via the injected `warn` callback, deduped per client.
36
+ *
37
+ * Reads `x-heroku-warning` first, then `warning-message`. Each value is
38
+ * normalized (a leading `warning:` prefix stripped, then trimmed) and emitted
39
+ * at most once per unique normalized string over the client's lifetime.
40
+ *
41
+ * Note: the Fetch `Headers` API collapses repeated values of a header into one
42
+ * comma-joined string, so this reads a single string per header.
43
+ */
44
+ export declare function createWarningAfterHook(shownWarnings: Set<string>, warn: (message: string) => void): AfterResponseHook;
45
+ /**
46
+ * Create an afterResponse hook that surfaces structured success-path metadata
47
+ * (request-id, warnings) via the injected callback, so consumers get request
48
+ * correlation and warnings without re-parsing headers. Registered after the
49
+ * error-handling hook, so it only sees responses the client accepted.
50
+ */
51
+ export declare function createMetadataAfterHook(onMetadata: (metadata: ResponseMetadata) => void): AfterResponseHook;
52
+ /**
53
+ * Create an afterResponse hook that detects a 2FA challenge (a 412, or a 403
54
+ * carrying the `two_factor` error id) and, when a 2FA handler is configured and
55
+ * the request isn't already carrying a code, prompts for one and forces a
56
+ * retry.
57
+ *
58
+ * Registered before {@link createErrorAfterHook} so it sees the challenge
59
+ * response before it is thrown as an error. The retry is driven by ky's
60
+ * `ky.retry` (returned from {@link handle2FAChallenge}), which re-issues the
61
+ * request through this same client; the retried response then runs back through
62
+ * the full afterResponse chain — error handling, Request-Id, warnings,
63
+ * metadata, consumer hooks — exactly once.
64
+ *
65
+ * The `Heroku-Two-Factor-Code` header the retry carries is also the loop guard:
66
+ * if a request already bears a code and is still challenged (e.g. a wrong
67
+ * code), it is left to {@link createErrorAfterHook} to throw rather than
68
+ * retried again. This is per-request state, so concurrent requests on one
69
+ * client don't interfere. Returns the original response untouched when it isn't
70
+ * a handleable 2FA challenge.
71
+ */
72
+ export declare function create2FAAfterHook(twoFactorOptions: TwoFactorOptions | undefined): AfterResponseHook;
73
+ /**
74
+ * Create an afterResponse hook that throws a typed error on a non-ok response.
75
+ *
76
+ * Registered before the Request-Id, warning, metadata, and consumer hooks, so
77
+ * those run only on the success path (this throws and stops the chain first).
15
78
  */
16
- export declare function createAfterResponseHook(twoFactorOptions: TwoFactorOptions | undefined, twoFactorAttemptedRef: {
17
- value: boolean;
18
- }): AfterResponseHook;
79
+ export declare function createErrorAfterHook(): AfterResponseHook;
@@ -5,49 +5,28 @@
5
5
  * used by the ky HTTP client.
6
6
  */
7
7
  import { debugAuth, debugRequest, debugResponse } from '../debug-loggers.js';
8
+ import { logScrubbed } from '../redact.js';
8
9
  import { handleErrorResponse } from './http-error-handler.js';
10
+ import { REQUEST_ID_HEADER } from './request-id.js';
9
11
  import { handle2FAChallenge, is2FAError } from './two-factor-authentication-handler.js';
10
12
  /**
11
- * Headers whose values must never appear in debug output. Compared
12
- * case-insensitively. Mirrors the redaction in http-call so tokens
13
- * aren't leaked when `debug` is enabled.
13
+ * Upper bound on the per-client set of already-surfaced warnings. Dedupe stays
14
+ * a sliding window of the most recent warnings rather than the client's entire
15
+ * lifetime, so a long-lived client with many distinct warnings can't grow the
16
+ * set without limit.
14
17
  */
15
- const SENSITIVE_HEADERS = new Set([
16
- 'authorization',
17
- 'cookie',
18
- 'heroku-two-factor-code',
19
- 'proxy-authorization',
20
- 'x-addon-sso',
21
- ]);
18
+ const MAX_SHOWN_WARNINGS = 256;
22
19
  /**
23
- * Build a plain object of a request's headers with sensitive values
24
- * replaced by `[REDACTED]`, safe for debug logging.
25
- */
26
- function redactHeaders(headers) {
27
- const result = {};
28
- // eslint-disable-next-line unicorn/no-array-for-each
29
- headers.forEach((value, key) => {
30
- result[key] = SENSITIVE_HEADERS.has(key.toLowerCase()) ? '[REDACTED]' : value;
31
- });
32
- return result;
33
- }
34
- /**
35
- * Create a beforeRequest hook that adds authentication and custom headers
20
+ * Create a beforeRequest hook that attaches the bearer token.
21
+ *
22
+ * Static headers (the `Accept` default and any consumer-supplied custom
23
+ * headers) are set on the ky instance via its `headers` option, so ky merges
24
+ * them with per-call headers (per-call winning) before this hook runs. Only the
25
+ * token is resolved here, since it comes from an async provider and so can't be
26
+ * a static instance header.
36
27
  */
37
- export function createBeforeRequestHook(getToken, defaultAccept, customHeaders, debug) {
28
+ export function createBeforeRequestHook(getToken, debug) {
38
29
  return async ({ request }) => {
39
- // Apply the service's default Accept header when the caller
40
- // hasn't set one. Services that don't declare one (e.g. `custom`)
41
- // skip this entirely.
42
- if (defaultAccept && !request.headers.has('Accept')) {
43
- request.headers.set('Accept', defaultAccept);
44
- }
45
- // Add custom headers from options
46
- if (customHeaders) {
47
- for (const [key, value] of Object.entries(customHeaders)) {
48
- request.headers.set(key, value);
49
- }
50
- }
51
30
  // Add authorization header.
52
31
  //
53
32
  // We deliberately don't strip this on cross-origin redirects: the
@@ -65,23 +44,147 @@ export function createBeforeRequestHook(getToken, defaultAccept, customHeaders,
65
44
  }
66
45
  debugRequest('%s %s', request.method, request.url);
67
46
  if (debug) {
68
- debugRequest('Headers: %O', redactHeaders(request.headers));
47
+ await logScrubbed(debugRequest, 'Headers: %O', request.headers);
69
48
  }
70
49
  };
71
50
  }
72
51
  /**
73
- * Create an afterResponse hook that handles 2FA challenges and errors
52
+ * Create a beforeRequest hook that sets the accumulating `Request-Id`
53
+ * correlation header (with the 7KB overflow guard).
74
54
  */
75
- export function createAfterResponseHook(twoFactorOptions, twoFactorAttemptedRef) {
55
+ export function createRequestIdBeforeHook(store) {
56
+ return ({ request }) => {
57
+ request.headers.set(REQUEST_ID_HEADER, store.nextHeaderValue());
58
+ };
59
+ }
60
+ /**
61
+ * Create an afterResponse hook that feeds the server's echoed `Request-Id`s
62
+ * back into the accumulating store so later requests carry the full chain.
63
+ *
64
+ * Runs only on the success path: it is registered after the error-handling
65
+ * hook, which throws on a non-ok response and stops the chain.
66
+ */
67
+ export function createRequestIdAfterHook(store) {
68
+ return ({ response }) => {
69
+ const header = response.headers.get(REQUEST_ID_HEADER);
70
+ if (header) {
71
+ store.track(...splitRequestIds(header));
72
+ }
73
+ };
74
+ }
75
+ /**
76
+ * Split a `Request-Id` header into its individual ids, trimming surrounding
77
+ * whitespace and dropping empty segments, so a server that joins with `", "`
78
+ * (or leaves a trailing comma) doesn't produce padded or empty ids.
79
+ */
80
+ function splitRequestIds(header) {
81
+ return header.split(',').map(id => id.trim()).filter(Boolean);
82
+ }
83
+ /**
84
+ * Create an afterResponse hook that surfaces server warning headers to the
85
+ * user via the injected `warn` callback, deduped per client.
86
+ *
87
+ * Reads `x-heroku-warning` first, then `warning-message`. Each value is
88
+ * normalized (a leading `warning:` prefix stripped, then trimmed) and emitted
89
+ * at most once per unique normalized string over the client's lifetime.
90
+ *
91
+ * Note: the Fetch `Headers` API collapses repeated values of a header into one
92
+ * comma-joined string, so this reads a single string per header.
93
+ */
94
+ export function createWarningAfterHook(shownWarnings, warn) {
95
+ return ({ response }) => {
96
+ const normalized = normalizedWarning(response);
97
+ // The `has` check gates the `warn()` emission below, not the set insertion
98
+ // (which is already idempotent): it's what makes a repeat warning silent.
99
+ if (!normalized || shownWarnings.has(normalized))
100
+ return;
101
+ if (shownWarnings.size >= MAX_SHOWN_WARNINGS) {
102
+ // Bound memory on a long-lived client: evict the oldest surfaced warning
103
+ // (Sets iterate in insertion order) so dedupe becomes a sliding window
104
+ // rather than growing unbounded for the client's whole lifetime.
105
+ const oldest = shownWarnings.values().next().value;
106
+ if (oldest !== undefined)
107
+ shownWarnings.delete(oldest);
108
+ }
109
+ shownWarnings.add(normalized);
110
+ warn(normalized);
111
+ };
112
+ }
113
+ /**
114
+ * Create an afterResponse hook that surfaces structured success-path metadata
115
+ * (request-id, warnings) via the injected callback, so consumers get request
116
+ * correlation and warnings without re-parsing headers. Registered after the
117
+ * error-handling hook, so it only sees responses the client accepted.
118
+ */
119
+ export function createMetadataAfterHook(onMetadata) {
120
+ return ({ request, response }) => {
121
+ const normalized = normalizedWarning(response);
122
+ const requestIdHeader = response.headers.get(REQUEST_ID_HEADER);
123
+ onMetadata({
124
+ requestIds: requestIdHeader ? splitRequestIds(requestIdHeader) : [],
125
+ status: response.status,
126
+ url: request.url,
127
+ warnings: normalized ? [normalized] : [],
128
+ });
129
+ };
130
+ }
131
+ /**
132
+ * The warning a response carries, normalized (leading `warning:` prefix
133
+ * stripped, trimmed), or `undefined` if none. Reads `x-heroku-warning` first,
134
+ * then `warning-message`. Shared by the warn-surfacing and metadata hooks so
135
+ * both apply the same normalization.
136
+ */
137
+ function normalizedWarning(response) {
138
+ const raw = response.headers.get('x-heroku-warning') ?? response.headers.get('warning-message');
139
+ if (!raw)
140
+ return undefined;
141
+ return raw.replace(/^\s*warning:?\s*/i, '').trim() || undefined;
142
+ }
143
+ /**
144
+ * Create an afterResponse hook that detects a 2FA challenge (a 412, or a 403
145
+ * carrying the `two_factor` error id) and, when a 2FA handler is configured and
146
+ * the request isn't already carrying a code, prompts for one and forces a
147
+ * retry.
148
+ *
149
+ * Registered before {@link createErrorAfterHook} so it sees the challenge
150
+ * response before it is thrown as an error. The retry is driven by ky's
151
+ * `ky.retry` (returned from {@link handle2FAChallenge}), which re-issues the
152
+ * request through this same client; the retried response then runs back through
153
+ * the full afterResponse chain — error handling, Request-Id, warnings,
154
+ * metadata, consumer hooks — exactly once.
155
+ *
156
+ * The `Heroku-Two-Factor-Code` header the retry carries is also the loop guard:
157
+ * if a request already bears a code and is still challenged (e.g. a wrong
158
+ * code), it is left to {@link createErrorAfterHook} to throw rather than
159
+ * retried again. This is per-request state, so concurrent requests on one
160
+ * client don't interfere. Returns the original response untouched when it isn't
161
+ * a handleable 2FA challenge.
162
+ */
163
+ export function create2FAAfterHook(twoFactorOptions) {
76
164
  return async ({ request, response }) => {
77
- debugResponse('%s %s -> %d', request.method, request.url, response.status);
78
- // Handle 2FA challenge (can be 403 or 412)
165
+ // Cheap guards first, so the body-reading is2FAError() probe below is only
166
+ // reached when it can matter: skip when no 2FA handler is configured, or
167
+ // when the request already carries a code (the retry — also the loop guard).
168
+ if (!twoFactorOptions || request.headers.has('Heroku-Two-Factor-Code')) {
169
+ return response;
170
+ }
79
171
  const is2FAChallenge = response.status === 412
80
172
  || (response.status === 403 && await is2FAError(response));
81
- if (is2FAChallenge && twoFactorOptions && !twoFactorAttemptedRef.value) {
82
- return handle2FAChallenge(request, twoFactorOptions, twoFactorAttemptedRef);
173
+ if (is2FAChallenge) {
174
+ return handle2FAChallenge(request, twoFactorOptions);
83
175
  }
84
- // Handle errors
176
+ return response;
177
+ };
178
+ }
179
+ /**
180
+ * Create an afterResponse hook that throws a typed error on a non-ok response.
181
+ *
182
+ * Registered before the Request-Id, warning, metadata, and consumer hooks, so
183
+ * those run only on the success path (this throws and stops the chain first).
184
+ */
185
+ export function createErrorAfterHook() {
186
+ return async ({ request, response }) => {
187
+ debugResponse('%s %s -> %d', request.method, request.url, response.status);
85
188
  if (!response.ok) {
86
189
  await handleErrorResponse(response);
87
190
  }
@@ -10,8 +10,9 @@ export declare class HerokuApiClient {
10
10
  private clientPromise;
11
11
  private kyOptions;
12
12
  private options;
13
+ private readonly requestIds;
14
+ private readonly shownWarnings;
13
15
  private tokenProvider?;
14
- private twoFactorAttempted;
15
16
  constructor(options?: HerokuApiClientOptions);
16
17
  /**
17
18
  * Make a DELETE request
@@ -42,8 +43,14 @@ export declare class HerokuApiClient {
42
43
  */
43
44
  stream(path: string, options?: RequestOptions): Promise<Response>;
44
45
  /**
45
- * Lazily construct ky with an env-aware undici dispatcher (Node)
46
- * or no dispatcher (browser). Cached after the first call.
46
+ * Lazily construct ky over a fetch that is proxy-aware on Node (undici's own
47
+ * fetch paired with an env-var dispatcher) and the global fetch in the
48
+ * browser. Cached after the first call.
49
+ *
50
+ * We drive ky through `fetch` rather than ky's `dispatcher` option because
51
+ * ky calls the global `fetch`, which on Node 22 is backed by a different
52
+ * undici than our dispatcher and rejects it (`invalid onRequestStart
53
+ * method`). `getDefaultFetch()` returns a fetch from the matching undici.
47
54
  */
48
55
  private getClient;
49
56
  /**