(error: unknown, maxPayloadBytes: number)
| 497 | } |
| 498 | |
| 499 | function encodeBoundedError(error: unknown, maxPayloadBytes: number) { |
| 500 | const value = error as { code?: unknown; path?: unknown }; |
| 501 | const message = error instanceof Error ? error.message : String(error); |
| 502 | const detailed = JSON.stringify({ |
| 503 | error: { |
| 504 | message, |
| 505 | ...(typeof value?.code === "string" ? { code: value.code } : {}), |
| 506 | ...(typeof value?.path === "string" ? { path: value.path } : {}), |
| 507 | }, |
| 508 | }); |
| 509 | const encoder = new TextEncoder(); |
| 510 | if (encoder.encode(detailed).byteLength <= maxPayloadBytes) return detailed; |
| 511 | |
| 512 | let budget = Math.max(0, maxPayloadBytes - 40); |
| 513 | while (budget >= 0) { |
| 514 | const bounded = JSON.stringify({ error: { message: truncateUtf8(message, budget) } }); |
| 515 | if (encoder.encode(bounded).byteLength <= maxPayloadBytes) return bounded; |
| 516 | budget -= 1; |
| 517 | } |
| 518 | return JSON.stringify({ error: { message: "Capability call failed" } }); |
| 519 | } |
| 520 | |
| 521 | function truncateUtf8(value: string, maxBytes: number) { |
| 522 | const bytes = new TextEncoder().encode(value); |
no test coverage detected