diagnostics.mjs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. export function formatError(error, depth = 0) {
  2. if (!(error instanceof Error)) return String(error);
  3. const indent = " ".repeat(depth);
  4. const fields = [];
  5. for (const key of ["code", "status", "statusCode", "type"]) {
  6. if (error[key] !== undefined) fields.push(`${key}: ${String(error[key])}`);
  7. }
  8. if (error.details !== undefined) fields.push(`details: ${truncate(JSON.stringify(error.details))}`);
  9. const head = `${indent}${error.stack ?? error.message}`;
  10. const meta = fields.length > 0 ? `\n${indent}${fields.join(`\n${indent}`)}` : "";
  11. const cause = error.cause ? `\n${indent}cause:\n${formatError(error.cause, depth + 1)}` : "";
  12. return redactSecrets(`${head}${meta}${cause}`);
  13. }
  14. export function formatEventDiagnostics(events) {
  15. const recent = events.slice(-6).map((event) => ({
  16. payload: event.payload ? truncate(JSON.stringify(event.payload), 800) : undefined,
  17. type: event.type,
  18. }));
  19. return redactSecrets(`Captured events:\n${JSON.stringify({ counts: countEventTypes(events), recent }, null, 2)}`);
  20. }
  21. function countEventTypes(events) {
  22. const counts = {};
  23. for (const event of events) {
  24. counts[event.type] = (counts[event.type] ?? 0) + 1;
  25. }
  26. return counts;
  27. }
  28. function truncate(value, maxLength = 2000) {
  29. if (!value || value.length <= maxLength) return value;
  30. return `${value.slice(0, maxLength)}...<truncated>`;
  31. }
  32. function redactSecrets(value) {
  33. let output = value;
  34. for (const secret of [process.env.ZCODE_API_KEY]) {
  35. if (secret && secret.length > 8) {
  36. output = output.split(secret).join(`${secret.slice(0, 4)}...${secret.slice(-4)}`);
  37. }
  38. }
  39. return output;
  40. }