dsh-mo-image 0.7.0 → 1.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.
@@ -4,7 +4,7 @@
4
4
  * 原本长在 lib/adapters.js 里;协议变多以后拆出来,供 adapters.js 与
5
5
  * lib/adapters/*.js 共用,避免循环依赖。
6
6
  */
7
- import { request } from './net.js';
7
+ import { createHash } from 'node:crypto';
8
8
  import { localizedError } from './localized-error.js';
9
9
  import { isPng, pngHeaderOf } from './png-scale.js';
10
10
 
@@ -43,37 +43,143 @@ export function nearestAspect(width, height, choices = ASPECT_CHOICES) {
43
43
  return best;
44
44
  }
45
45
 
46
- export function resolutionFor(width, height) {
47
- const pixels = (Number(width) || 1024) * (Number(height) || 1024);
48
- if (pixels >= 2800 * 2800) return '4k';
49
- if (pixels >= 1800 * 1800) return '2k';
50
- return '1k';
51
- }
52
46
 
53
47
  export function baseUrlOf(provider) {
54
- return String((provider && provider.baseUrl) || '').replace(/\/+$/, '');
48
+ return String((provider && provider.baseUrl) || '').trim().replace(/\/+$/, '');
49
+ }
50
+
51
+ /** Protocol routes extend the configured path prefix. Response URLs resolve from the request URL. */
52
+ export function joinEndpoint(base, route) {
53
+ const path = String(route || '').trim();
54
+ const root = String(base || '').trim().replace(/\/+$/, '');
55
+ if (!path || /^https?:\/\//i.test(path) || !root) return path;
56
+ const [withoutHash] = root.split('#');
57
+ const queryAt = withoutHash.indexOf('?');
58
+ const prefix = queryAt === -1 ? withoutHash : withoutHash.slice(0, queryAt);
59
+ const query = queryAt === -1 ? '' : withoutHash.slice(queryAt + 1);
60
+ const target = prefix.replace(/\/+$/, '') + '/' + path.replace(/^\/+/, '');
61
+ if (!query) return target;
62
+ const url = new URL(target);
63
+ const overridden = new Set(url.searchParams.keys());
64
+ for (const [key, value] of new URLSearchParams(query)) {
65
+ if (!overridden.has(key)) url.searchParams.append(key, value);
66
+ }
67
+ return url.toString();
68
+ }
69
+
70
+ export function resolveHttpUrl(value, base) {
71
+ if (typeof value !== 'string' || !value.trim()) return '';
72
+ try {
73
+ const url = new URL(value.trim(), base || undefined);
74
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) return '';
75
+ url.hash = '';
76
+ return url.href;
77
+ } catch (_error) { return ''; }
55
78
  }
56
79
 
57
- /** 按适配器声明的鉴权方式生成头;默认 Bearer。 */
80
+ /* --------------------------------------------------------------- 鉴权方式 */
81
+
82
+ /**
83
+ * 鉴权方式是**提供商自己的字段**(`provider.auth`),不是协议级选项。
84
+ *
85
+ * 维度为什么分开:鉴权回答「这个地址怎么认证」,协议回答「说哪种话」。挂在协议下面时,
86
+ * 切到没声明 auth 的协议(ComfyUI / 百炼 / Gemini …)下拉就消失了,而「本地 ComfyUI 前面
87
+ * 挂了反代、要带 X-API-Key」这种场景照样存在。所以它跟着 provider 走,任何协议下都能设。
88
+ *
89
+ * `adapter.authHeader` 保留为该协议的**默认值**:provider.auth 没设(或认不出)时回落到它,
90
+ * 所以老配置(provider 上没有 auth 字段)行为一字不变。
91
+ */
92
+ export const AUTH_MODES = ['bearer', 'api-key', 'x-key', 'fal-key', 'custom', 'none', 'basic', 'query'];
93
+ const AUTH_MODE_SET = new Set(AUTH_MODES);
94
+ /** HTTP 头名:字母 / 数字 / 连字符,最长 64。够覆盖 X-API-Key、x-goog-api-key 这类写法。 */
95
+ export const AUTH_HEADER_PATTERN = /^[A-Za-z0-9-]{1,64}$/;
96
+ /** 前缀(`Bearer ` / `Token ` / 空)的长度上限;空串与「没写」等价。 */
97
+ export const AUTH_PREFIX_MAX = 64;
98
+
99
+ /**
100
+ * 校验并归一 `provider.auth`;认不出返回 null(= 用户没设,走协议默认)。
101
+ *
102
+ * 这是全套校验的唯一出口:配置落盘(config-store)与出站请求(authHeaders)都用它,
103
+ * 免得「存进去的和发出去的不是一个判据」。老形状的字符串(`auth: 'api-key'`)不收——
104
+ * provider.auth 是新字段,没有老形状要兼容;老配置的 `protocolOptions.auth` 由
105
+ * config-store 迁移时转成这个对象。
106
+ */
107
+ export function normalizeAuthSpec(raw) {
108
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
109
+ const mode = String(raw.mode || '').trim().toLowerCase();
110
+ if (!AUTH_MODE_SET.has(mode)) return null;
111
+ if (mode === 'query') {
112
+ const name = typeof raw.name === 'string' ? raw.name.trim() : '';
113
+ return /^[A-Za-z0-9_.~-]{1,64}$/.test(name) ? { mode, name } : null;
114
+ }
115
+ if (mode !== 'custom') return { mode: mode };
116
+ const header = typeof raw.header === 'string' ? raw.header.trim() : '';
117
+ // custom 没有合法头名就不是一条可用的 custom:宁可回落,也不要发出一个坏请求头。
118
+ if (!AUTH_HEADER_PATTERN.test(header) || /^(?:host|cookie|set-cookie|content-length|content-type|transfer-encoding|connection|upgrade|proxy-.+)$/i.test(header)) return null;
119
+ const out = { mode: mode, header: header };
120
+ // 前缀原样拼在 key 前面(`Bearer ` 结尾的空格有意义,所以不 trim);只挡控制字符。
121
+ const prefix = typeof raw.prefix === 'string'
122
+ ? raw.prefix.replace(/[\u0000-\u001F\u007F]/g, '').slice(0, AUTH_PREFIX_MAX)
123
+ : '';
124
+ if (prefix) out.prefix = prefix;
125
+ return out;
126
+ }
127
+
128
+ /** 这次请求实际用的鉴权形态:provider.auth > 协议默认(adapter.authHeader)> bearer。 */
129
+ export function authSpecOf(provider, adapter) {
130
+ const declared = normalizeAuthSpec(provider && provider.auth);
131
+ if (declared) return declared;
132
+ const native = normalizeAuthSpec(adapter && adapter.defaultAuth);
133
+ if (native) return native;
134
+ const fallback = String((adapter && adapter.authHeader) || '').trim().toLowerCase();
135
+ return { mode: AUTH_MODE_SET.has(fallback) && fallback !== 'custom' ? fallback : 'bearer' };
136
+ }
137
+
138
+ /** 按 provider.auth 生成本次请求的鉴权头;没设就回落到协议的默认形态。 */
58
139
  export function authHeaders(provider, adapter) {
59
140
  const key = String((provider && provider.key) || '').trim();
60
141
  if (!key) return {};
61
- const type = String((adapter && adapter.authHeader) || 'bearer');
62
- if (type === 'api-key') return { 'api-key': key };
63
- if (type === 'x-key') return { 'x-key': key };
64
- if (type === 'fal-key') return { Authorization: 'Key ' + key };
142
+ const spec = authSpecOf(provider, adapter);
143
+ if (spec.mode === 'none' || spec.mode === 'query') return {};
144
+ if (spec.mode === 'basic') return { Authorization: 'Basic ' + Buffer.from(key).toString('base64') };
145
+ if (spec.mode === 'api-key') return { 'api-key': key };
146
+ if (spec.mode === 'x-key') return { 'x-key': key };
147
+ if (spec.mode === 'fal-key') return { Authorization: 'Key ' + key };
148
+ if (spec.mode === 'custom') return { [spec.header]: (spec.prefix || '') + key };
65
149
  return { Authorization: 'Bearer ' + key };
66
150
  }
67
151
 
68
152
  export function headersFor(provider, multipart, extra, adapter) {
69
- const headers = Object.assign({}, extra || {}, authHeaders(provider, adapter));
153
+ const auth = authHeaders(provider, adapter);
154
+ const headerName = authHeaderNameOf(provider, adapter).toLowerCase();
155
+ const headers = Object.fromEntries(Object.entries(extra || {}).filter(([name]) => name.toLowerCase() !== headerName));
156
+ Object.assign(headers, auth);
70
157
  if (!multipart && !headers['Content-Type']) headers['Content-Type'] = 'application/json';
71
158
  return headers;
72
159
  }
73
160
 
74
- export function keyedHeaders(provider, name, multipart) {
161
+ /** Add query credentials at dispatch time, after the caller has selected a trusted target. */
162
+ export function authenticatedUrl(url, provider, adapter) {
163
+ const spec = authSpecOf(provider, adapter);
75
164
  const key = String((provider && provider.key) || '').trim();
76
- return headersFor(Object.assign({}, provider, { key: '' }), multipart, key ? { [name]: key } : {});
165
+ if (spec.mode !== 'query' || !key) return url;
166
+ const target = new URL(url);
167
+ target.searchParams.set(spec.name, key);
168
+ return target.href;
169
+ }
170
+
171
+ export function authHeaderNameOf(provider, adapter) {
172
+ const spec = authSpecOf(provider, adapter);
173
+ if (spec.mode === 'custom') return spec.header;
174
+ if (spec.mode === 'api-key' || spec.mode === 'x-key') return spec.mode;
175
+ return spec.mode === 'none' || spec.mode === 'query' ? '' : 'authorization';
176
+ }
177
+
178
+ /** Cache metadata only within the same effective authentication scope. */
179
+ export function credentialRef(provider, adapter) {
180
+ const auth = authSpecOf(provider, adapter);
181
+ const key = auth.mode === 'none' ? '' : String(provider?.key || '').trim();
182
+ return createHash('sha256').update(JSON.stringify([auth, key])).digest('hex');
77
183
  }
78
184
 
79
185
  export function sleep(ms) {
@@ -85,7 +191,7 @@ export function dataUrlOf(image) {
85
191
  return 'data:' + image.contentType + ';base64,' + image.buffer.toString('base64');
86
192
  }
87
193
 
88
- export async function readJsonResponse(response, maxBytes = 10 * 1024 * 1024) {
194
+ export async function readJsonResponse(response, maxBytes = 10 * 1024 * 1024, provider, adapter) {
89
195
  const buffer = await readResponseBytes(response, maxBytes);
90
196
  const text = buffer.toString('utf8');
91
197
  if (!response.ok) {
@@ -97,6 +203,7 @@ export async function readJsonResponse(response, maxBytes = 10 * 1024 * 1024) {
97
203
  } catch (_error) {
98
204
  detail = text.slice(0, 300);
99
205
  }
206
+ detail = credentialText(detail, provider, adapter).slice(0, 600);
100
207
  throw localizedError(
101
208
  new Error('本地生图服务返回 HTTP ' + response.status + (detail ? ':' + detail : '')),
102
209
  detail ? 'upstream.http' : 'upstream.httpNoDetail',
@@ -118,12 +225,22 @@ export function getPath(node, path) {
118
225
  if (!path) return node;
119
226
  let current = node;
120
227
  for (const key of String(path).split('.')) {
121
- if (current === null || current === undefined) return null;
228
+ if (current === null || current === undefined || !Object.hasOwn(current, key)) return null;
122
229
  current = current[key];
123
230
  }
124
231
  return current === undefined ? null : current;
125
232
  }
126
233
 
234
+ export function credentialText(text, provider, adapter) {
235
+ const key = String(provider?.key || '').trim();
236
+ const value = String(text || '');
237
+ if (!key) return value;
238
+ const variants = new Set([key, encodeURIComponent(key), new URLSearchParams({ k: key }).toString().slice(2)]);
239
+ if (authSpecOf(provider, adapter).mode === 'basic') variants.add(Buffer.from(key).toString('base64'));
240
+ return [...variants].reduce((result, secret) => result.includes(secret) && (secret.length >= 4 || result === secret)
241
+ ? result.split(secret).join('[redacted]') : result, value);
242
+ }
243
+
127
244
  /** 统一成可安全读写的 Buffer;其它类型(包括 Uint8Array 视图)也兼容。 */
128
245
  function asBuffer(value) {
129
246
  if (Buffer.isBuffer(value)) return value;
@@ -358,138 +475,18 @@ export async function readResponseBytes(response, maxBytes) {
358
475
 
359
476
  export const MAX_IMAGE_BYTES = 32 * 1024 * 1024;
360
477
 
361
- export async function fetchImageUrl(url, signal, maxBytes = MAX_IMAGE_BYTES) {
362
- const response = await request(url, { signal: signal });
363
- if (!response.ok) throw new Error('下载生成图失败:HTTP ' + response.status);
364
- const bytes = await readResponseBytes(response, maxBytes);
365
- if (!looksLikeImage(bytes)) throw new Error('下载生成图失败:返回内容不是有效图片');
366
- return { bytes: bytes, contentType: sniffType(bytes) };
367
- }
368
-
369
- /* ---------------------------------------------------------- 通用异步任务 */
370
-
371
- /**
372
- * 通用「提交拿任务 → 轮询拿图」形状的识别与轮询辅助,不绑定任何厂商。
373
- *
374
- * 覆盖的是 OpenAI 兼容网关里最常见的那套约定:
375
- * - 任务 id:task_id / taskId / job_id / request_id / generation_id / prediction_id / id
376
- * - 轮询地址:polling_url / status_url / task_url / get_url / urls.get ...
377
- * - 状态词:SUCCEEDED / SUCCESS / COMPLETED / READY ...;FAILED / ERROR / CANCELED ...
378
- * - 结果图:output_images / images / data / output / result 里的 url / b64_json
478
+ /* ---------------------------------------------------------- 结果图下载 */
479
+ /*
480
+ * 结果图(data[0].url / output[].url / CDN 链接)**只有一个下载入口**:
481
+ * lib/request-auth.js 的 fetchResultImage()。它按目标域决定带不带凭据——
482
+ * 同源带、跨源默认不带、适配器声明过的 resultAuthOrigins 才带。
379
483
  *
380
- * 认不出来时不猜:调用方按同步响应处理,或者报「格式不认识」。
381
- */
382
- const TASK_ID_KEYS = [
383
- 'task_id', 'taskId', 'job_id', 'jobId', 'request_id', 'requestId',
384
- 'generation_id', 'generationId', 'prediction_id', 'predictionId', 'id'
385
- ];
386
- const TASK_URL_KEYS = [
387
- 'polling_url', 'pollingUrl', 'poll_url', 'pollUrl', 'status_url', 'statusUrl',
388
- 'task_url', 'taskUrl', 'get_url', 'getUrl', 'result_url', 'resultUrl'
389
- ];
390
- const TASK_IMAGE_KEYS = [
391
- 'output_images', 'outputImages', 'images', 'image_urls', 'data', 'outputs', 'output',
392
- 'result', 'results', 'artifacts', 'files', 'url', 'image_url', 'imageUrl', 'b64_json', 'base64', 'image'
393
- ];
394
- const TASK_SUCCESS = new Set([
395
- 'SUCCEED', 'SUCCEEDED', 'SUCCESS', 'SUCCESSFUL', 'COMPLETED', 'COMPLETE', 'DONE', 'FINISHED', 'READY'
396
- ]);
397
- const TASK_FAILURE = new Set([
398
- 'FAILED', 'FAILURE', 'ERROR', 'CANCELED', 'CANCELLED', 'ABORTED', 'REJECTED', 'EXPIRED', 'MODERATED'
399
- ]);
400
-
401
- /** 任务载荷的常见嵌套层:顶层、data、output、result(数组不算,避免把结果图当任务)。 */
402
- function taskNodes(payload) {
403
- const nodes = [];
404
- const visit = (node, depth) => {
405
- if (!node || typeof node !== 'object' || Array.isArray(node) || depth > 2) return;
406
- nodes.push(node);
407
- for (const key of ['data', 'output', 'result']) visit(node[key], depth + 1);
408
- };
409
- visit(payload, 0);
410
- return nodes;
411
- }
412
-
413
- function firstTaskString(nodes, keys) {
414
- // 字段名的优先级高于层级:嵌套的 task_id 应该压过顶层的通用 id。
415
- for (const key of keys) {
416
- for (const node of nodes) {
417
- if (typeof node[key] === 'string' && node[key].trim()) return node[key].trim();
418
- }
419
- }
420
- return '';
421
- }
422
-
423
- function urlsGetOf(nodes) {
424
- for (const node of nodes) {
425
- if (node.urls && typeof node.urls.get === 'string' && node.urls.get.trim()) return node.urls.get.trim();
426
- }
427
- return '';
428
- }
429
-
430
- /** 从提交响应里认任务:只要拿到任务 id 或轮询地址,就当异步任务。 */
431
- export function readTaskEnvelope(payload) {
432
- if (!payload || typeof payload !== 'object' || Array.isArray(payload)) return null;
433
- const nodes = taskNodes(payload);
434
- const pollUrl = firstTaskString(nodes, TASK_URL_KEYS) || urlsGetOf(nodes);
435
- const taskId = firstTaskString(nodes, TASK_ID_KEYS);
436
- if (!pollUrl && !taskId) return null;
437
- return { taskId: taskId, pollUrl: pollUrl };
438
- }
439
-
440
- function absoluteTaskUrl(value, base) {
441
- const text = String(value || '').trim();
442
- if (!text) return '';
443
- if (/^https?:\/\//i.test(text)) return text;
444
- try {
445
- return new URL(text, base.endsWith('/') ? base : base + '/').toString();
446
- } catch (_error) {
447
- return '';
448
- }
449
- }
450
-
451
- /**
452
- * 轮询候选地址:响应里给的优先;没给就按常见约定推两个,最后再试提交地址 + 任务 id。
453
- * base 以 /v1 结尾时是 /v1/tasks/{id},只有站点根时补 /v1。
454
- */
455
- export function taskPollUrls(provider, submission, submitUrl) {
456
- const base = baseUrlOf(provider);
457
- const nodes = taskNodes(submission || {});
458
- const raw = [];
459
- const direct = firstTaskString(nodes, TASK_URL_KEYS) || urlsGetOf(nodes);
460
- if (direct) raw.push(direct);
461
- const taskId = firstTaskString(nodes, TASK_ID_KEYS);
462
- if (taskId) {
463
- const id = encodeURIComponent(taskId);
464
- const root = base.replace(/\/v\d+[a-z0-9]*$/i, '');
465
- raw.push(root + '/v1/tasks/' + id);
466
- raw.push(base + '/tasks/' + id);
467
- if (submitUrl) raw.push(String(submitUrl).replace(/\/+$/, '') + '/' + id);
468
- }
469
- const urls = [];
470
- for (const item of raw) {
471
- const resolved = absoluteTaskUrl(item, base);
472
- if (resolved && !urls.includes(resolved)) urls.push(resolved);
473
- }
474
- return urls;
475
- }
476
-
477
- function statusTextOf(nodes) {
478
- // 任务专用状态词优先:顶层 status 可能只是「请求成功」,不能当成任务完成。
479
- for (const key of ['task_status', 'taskStatus', 'status', 'state']) {
480
- for (const node of nodes) {
481
- const value = node[key];
482
- if (typeof value === 'string' && value.trim()) return value.trim().toUpperCase();
483
- if (value && typeof value === 'object') {
484
- const nested = value.status || value.state;
485
- if (typeof nested === 'string' && nested.trim()) return nested.trim().toUpperCase();
486
- }
487
- }
488
- }
489
- return '';
490
- }
484
+ * 这里原本还有一个「裸下载」的 fetchImageUrl(),被 12 条走 execute() 的协议用着;
485
+ * 同一个 data[0].url 在 execute() 路径上不带鉴权、在异步/通用路径上带,二义性就出在这。
486
+ * 现在两条路径都走 fetchResultImage(),判定只有一份(downloadRequestHeaders)。 */
491
487
 
492
- function errorTextOf(value, depth = 0) {
488
+ /** 从对象/数组里深挖第一句可读文本(message / detail / error / errors …)。 */
489
+ export function errorTextOf(value, depth = 0) {
493
490
  if (depth > 4 || value === null || value === undefined) return '';
494
491
  if (typeof value === 'string') return value.trim();
495
492
  if (Array.isArray(value)) {
@@ -508,106 +505,6 @@ function errorTextOf(value, depth = 0) {
508
505
  return '';
509
506
  }
510
507
 
511
- /** 明确的错误字段;没有状态词时用它判断任务失败,不去猜普通的 message。 */
512
- export function taskErrorOf(payload) {
513
- if (!payload || typeof payload !== 'object') return '';
514
- for (const node of taskNodes(payload)) {
515
- for (const key of ['error', 'errors', 'fail_reason', 'error_message']) {
516
- if (node[key] === undefined || node[key] === null) continue;
517
- const text = errorTextOf(node[key]);
518
- if (text) return text;
519
- }
520
- }
521
- return '';
522
- }
523
-
524
- /** 失败任务的人话原因:先找错误字段,再退到 message / detail / logs。 */
525
- export function taskMessageOf(payload) {
526
- if (!payload || typeof payload !== 'object') return '';
527
- const error = taskErrorOf(payload);
528
- if (error) return error;
529
- for (const node of taskNodes(payload)) {
530
- for (const key of ['message', 'msg', 'detail', 'logs', 'reason']) {
531
- if (node[key] === undefined || node[key] === null) continue;
532
- const text = errorTextOf(node[key]);
533
- if (text) return text;
534
- }
535
- }
536
- return '';
537
- }
538
-
539
- function imageFromValue(value, depth = 0) {
540
- if (depth > 6 || value === null || value === undefined) return null;
541
- if (typeof value === 'string') {
542
- const text = value.trim();
543
- if (!text) return null;
544
- const decoded = base64ToImage(text);
545
- if (decoded) return { bytes: decoded.bytes, contentType: decoded.contentType };
546
- if (/^https?:\/\//i.test(text)) return { url: text };
547
- return null;
548
- }
549
- if (Array.isArray(value)) {
550
- for (const item of value) {
551
- const hit = imageFromValue(item, depth + 1);
552
- if (hit) return hit;
553
- }
554
- return null;
555
- }
556
- if (typeof value === 'object') {
557
- for (const key of TASK_IMAGE_KEYS) {
558
- if (value[key] === undefined) continue;
559
- const hit = imageFromValue(value[key], depth + 1);
560
- if (hit) return hit;
561
- }
562
- }
563
- return null;
564
- }
565
-
566
- function containerImageOf(payload) {
567
- for (const key of ['output_images', 'outputImages', 'images', 'image_urls', 'data', 'outputs', 'output', 'result', 'results', 'artifacts', 'files']) {
568
- if (payload[key] === undefined) continue;
569
- const hit = imageFromValue(payload[key], 1);
570
- if (hit) return hit;
571
- }
572
- return null;
573
- }
574
-
575
- /**
576
- * 只看约定的结果字段,避免把回显的参考图或状态地址当结果。
577
- * containersOnly 用于「任务还在跑」的载荷:连顶层的 url / image 都不认,
578
- * 免得把任务详情地址当成生成图去下载。
579
- */
580
- export function taskImageOf(payload, options) {
581
- if (!payload || typeof payload !== 'object') return null;
582
- if (options && options.containersOnly) return containerImageOf(payload);
583
- return imageFromValue(payload);
584
- }
585
-
586
- /** 任务已成功但形状不常见时,再按「任意位置的图片」兜底扫一遍。 */
587
- export function looseImageOf(payload) {
588
- try {
589
- return decodeImagePayload(payload, null) || null;
590
- } catch (_error) {
591
- return null;
592
- }
593
- }
594
-
595
- /** 把任务载荷收敛成三态:成功词、失败词、其余都算进行中。 */
596
- export function taskStatusOf(payload) {
597
- const nodes = taskNodes(payload);
598
- const status = statusTextOf(nodes);
599
- if (status) {
600
- if (TASK_SUCCESS.has(status)) return { state: 'success', status: status };
601
- if (TASK_FAILURE.has(status)) {
602
- return { state: 'failure', status: status, message: taskMessageOf(payload) || status };
603
- }
604
- return { state: 'pending', status: status };
605
- }
606
- const error = taskErrorOf(payload);
607
- if (error) return { state: 'failure', status: '', message: error };
608
- return { state: 'pending', status: '' };
609
- }
610
-
611
508
  export function extractMessage(text) {
612
509
  const raw = String(text || '').trim();
613
510
  if (!raw) return '';
@@ -656,15 +553,15 @@ function extractErrorParam(text) {
656
553
  */
657
554
  export function classifyFailure(status, text) {
658
555
  const message = extractMessage(text) || ('HTTP ' + status);
556
+ if (status === 401 || status === 403) return { kind: 'auth', message: message };
557
+ if (status === 404 || status === 405) return { kind: 'endpoint', message: message };
558
+ if (status === 413) return { kind: 'payload', message: message };
559
+ if (status === 429) return { kind: 'rate', message: message, retryable: true };
560
+ if (status === 408 || status >= 500) return { kind: 'upstream', message: message, retryable: true };
659
561
  const drop = detectDroppableField(message) || extractErrorParam(text);
660
562
  if (drop) return { kind: 'param', drop: drop, message: message };
661
563
  if (/size/i.test(message) && /(invalid|unsupported|below|minimum|maximum|too small|too large|budget)/i.test(message)) {
662
564
  return { kind: 'size', message: message };
663
565
  }
664
- if (status === 401 || status === 403) return { kind: 'auth', message: message };
665
- if (status === 404) return { kind: 'endpoint', message: message };
666
- if (status === 413) return { kind: 'payload', message: message };
667
- if (status === 429) return { kind: 'rate', message: message, retryable: true };
668
- if (status >= 500) return { kind: 'upstream', message: message, retryable: true };
669
566
  return { kind: 'unknown', message: message };
670
567
  }