All files / kernel-errors/src constants.ts

93.75% Statements 15/16
100% Branches 0/0
80% Functions 4/5
90.9% Lines 10/11

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77                                  139x               139x                                   139x   139x 1390x         139x                     139x   1x           139x       2x    
import type { Struct } from '@metamask/superstruct';
import {
  define,
  lazy,
  literal,
  optional,
  string,
  union,
} from '@metamask/superstruct';
import { JsonStruct, object } from '@metamask/utils';
import type { NonEmptyArray } from '@metamask/utils';
 
import type { MarshaledError, MarshaledOcapError } from './types.ts';
 
/**
 * Struct to validate plain {@link Error} objects.
 */
export const ErrorStruct = define<Error>(
  'Error',
  (value) => value instanceof Error,
);
 
/**
 * Enum defining all error codes for Ocap errors.
 */
export const ErrorCode = {
  AbortError: 'ABORT_ERROR',
  DuplicateEndowment: 'DUPLICATE_ENDOWMENT',
  StreamReadError: 'STREAM_READ_ERROR',
  VatAlreadyExists: 'VAT_ALREADY_EXISTS',
  VatDeleted: 'VAT_DELETED',
  VatNotFound: 'VAT_NOT_FOUND',
  SubclusterNotFound: 'SUBCLUSTER_NOT_FOUND',
  SampleGenerationError: 'SAMPLE_GENERATION_ERROR',
  InternalError: 'INTERNAL_ERROR',
  ResourceLimitError: 'RESOURCE_LIMIT_ERROR',
} as const;
 
export type ErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode];
 
/**
 * A sentinel value used to identify marshaled errors.
 */
export const ErrorSentinel = '@@MARSHALED_ERROR';
 
const ErrorCodeStruct = union(
  Object.values(ErrorCode).map((code) => literal(code)) as NonEmptyArray<
    Struct<ErrorCode>
  >,
);
 
export const marshaledErrorSchema = {
  [ErrorSentinel]: literal(true),
  message: string(),
  code: optional(ErrorCodeStruct),
  data: optional(JsonStruct),
  stack: optional(string()),
};
 
/**
 * Struct to validate marshaled errors.
 */
export const MarshaledErrorStruct = object({
  ...marshaledErrorSchema,
  cause: optional(union([string(), lazy(() => MarshaledErrorStruct)])),
}) as Struct<MarshaledError>;
 
/**
 * Struct to validate marshaled ocap errors.
 */
export const MarshaledOcapErrorStruct = object({
  ...marshaledErrorSchema,
  code: ErrorCodeStruct,
  data: JsonStruct,
  cause: optional(union([string(), lazy(() => MarshaledErrorStruct)])),
}) as Struct<MarshaledOcapError>;