@vltpkg/error-cause 0.0.0-0.1730239248325 → 0.0.0-10

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.
package/README.md CHANGED
@@ -1,9 +1,28 @@
1
- # `@vltpkg/error-cause`
1
+ ![error-cause](https://github.com/user-attachments/assets/5fa00d7e-19dd-400e-9a77-6d37ded3fe2d)
2
+
3
+ # @vltpkg/error-cause
2
4
 
3
5
  Utility functions for `Error` creation to help enforce vlt's
4
6
  `Error.cause` conventions.
5
7
 
6
- ## USAGE
8
+ **[Usage](#usage)** ·
9
+ **[Error Reporting](#challenges-of-error-reporting)** ·
10
+ **[Conventions](#conventions)** · **[Error Types](#error-types)**
11
+
12
+ ## Why
13
+
14
+ Most node programs have a mishmash of error codes and various `Error`
15
+ subtypes, all in different shapes, making error handling and reporting
16
+ more difficult at the top level. This negatively impacts debugging and
17
+ user experience.
18
+
19
+ The JavaScript `Error` constructor has a
20
+ [`cause` option](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/cause)
21
+ which is supported since Node 16.9. We should use it!
22
+
23
+ This module makes that easy.
24
+
25
+ ## Usage
7
26
 
8
27
  ```js
9
28
  import { error, typeError } from '@vltpkg/error-cause'
@@ -46,75 +65,60 @@ const checkBar = () => {
46
65
  }
47
66
  ```
48
67
 
49
- The functions will create an error object with a `cause` property
50
- if set, and the type checks will ensure that the `cause` object
51
- matches vlt's conventions.
52
-
53
- ## Why
54
-
55
- Most node programs have a mishmash of error codes and various
56
- `Error` subtypes, all in different shapes, making error handling
57
- and reporting more difficult at the top level. This negatively
58
- impacts debugging and user experience.
59
-
60
- The JavaScript `Error` constructor has a [`cause`
61
- option](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/cause)
62
- which is supported since Node 16.9. We should use it!
63
-
64
- This module makes that easy.
68
+ The functions will create an error object with a `cause` property if
69
+ set, and the type checks will ensure that the `cause` object matches
70
+ vlt's conventions.
65
71
 
66
72
  ## Challenges of Error Reporting
67
73
 
68
74
  - Provide enough information to be useful. On full inspection, we
69
- should ideally always get back to not just the initial error
70
- that was thrown, but also all locations where the error might
71
- have been caught and handled in some way.
75
+ should ideally always get back to not just the initial error that
76
+ was thrown, but also all locations where the error might have been
77
+ caught and handled in some way.
72
78
  - Do not provide more information than is useful. Eg,
73
- `console.error(er)` should not fill the entire scrollback
74
- buffer.
75
- - New modules and libraries should have minimal friction in
76
- creating a new style of error when needed. This means, minimize
77
- the amount that any module needs to know about the errors
78
- raised by any other module, including especially top-level
79
- error handling.
80
- - _Some_ information about the error must be known to our
81
- top-level error handler, so that it can usefully report errors
82
- and suggest corrections.
79
+ `console.error(er)` should not fill the entire scrollback buffer.
80
+ - New modules and libraries should have minimal friction in creating a
81
+ new style of error when needed. This means, minimize the amount that
82
+ any module needs to know about the errors raised by any other
83
+ module, including especially top-level error handling.
84
+ - _Some_ information about the error must be known to our top-level
85
+ error handler, so that it can usefully report errors and suggest
86
+ corrections.
83
87
 
84
88
  ## Solution
85
89
 
86
90
  - A strictly upheld convention of Error object creation using the
87
91
  `cause` property.
88
- - Top level error handler can have special logic where necessary
89
- for known error codes, but will still be able to do something
90
- more useful when an Error object follows our conventions, even
91
- if it's not a code that it knows.
92
+ - Top level error handler can have special logic where necessary for
93
+ known error codes, but will still be able to do something more
94
+ useful when an Error object follows our conventions, even if it's
95
+ not a code that it knows.
92
96
 
93
97
  ## Conventions
94
98
 
95
- The following conventions should be followed for all `Error`
96
- creation and handling throughout the vlt codebase.
99
+ The following conventions should be followed for all `Error` creation
100
+ and handling throughout the vlt codebase.
97
101
 
98
102
  - **If you can't help, get out of the way.** Just let throws pass
99
103
  through to the top when nothing can be done to assist.
100
104
  - **Add information by using thrown error as `cause`.** Use a
101
105
  previously-thrown error as the `cause` option.
102
- - **Add even more info with a double-`cause`.** If more info can
103
- be added to a prior throw, nest the `cause` properties like
106
+ - **Add even more info with a double-`cause`.** If more info can be
107
+ added to a prior throw, nest the `cause` properties like
104
108
  `{ some, other, info, cause: priorError }`.
105
109
  - **Always set `cause`, even if no prior error.** Use a plain-old
106
110
  JavaScript object following our field conventions.
107
111
  - **Rare exception: synthetic ErrnoException style errors.** If we are
108
112
  doing something that is similar to a system operation, it's
109
113
  sometimes ok to mimic node's pattern.
110
- - **Do not subclass `Error`.** Just create a plain old Error, and
111
- set the `cause` with additional information.
114
+ - **Do not subclass `Error`.** Just create a plain old Error, and set
115
+ the `cause` with additional information.
112
116
 
113
117
  ### If you can't help, don't get in the way.
114
118
 
115
- Whenever possible, if no remediation or extra information can
116
- usefully be added, it's best to just not handle errors and let
117
- them be raised at the higher level. For example, instead of this:
119
+ Whenever possible, if no remediation or extra information can usefully
120
+ be added, it's best to just not handle errors and let them be raised
121
+ at the higher level. For example, instead of this:
118
122
 
119
123
  ```
120
124
  let data
@@ -133,9 +137,9 @@ const data = await readFile(someFile)
133
137
 
134
138
  ### Add information by using thrown error as `cause`.
135
139
 
136
- If we can add information or do something else useful for the
137
- user in understanding the problem, do so by creating a new
138
- `Error` and setting the original thrown error as the `cause`.
140
+ If we can add information or do something else useful for the user in
141
+ understanding the problem, do so by creating a new `Error` and setting
142
+ the original thrown error as the `cause`.
139
143
 
140
144
  ```js
141
145
  let data
@@ -149,9 +153,9 @@ try {
149
153
 
150
154
  ### Add even more info with a double-`cause`.
151
155
 
152
- If we can add even more information, that should ideally _not_ be
153
- put on the Error we throw, but on a `cause` object. Because
154
- `cause` objects can nest, we can do something like this:
156
+ If we can add even more information, that should ideally _not_ be put
157
+ on the Error we throw, but on a `cause` object. Because `cause`
158
+ objects can nest, we can do something like this:
155
159
 
156
160
  ```js
157
161
  let data
@@ -195,27 +199,25 @@ throw error('could not resolve', {
195
199
  })
196
200
  ```
197
201
 
198
- This makes any big objects easily skipped if we want to just
199
- output the error with `console.error()` or something, but still
200
- preserves any debugging information that might be useful all the
201
- way down the chain.
202
+ This makes any big objects easily skipped if we want to just output
203
+ the error with `console.error()` or something, but still preserves any
204
+ debugging information that might be useful all the way down the chain.
202
205
 
203
206
  ### Rare exception: synthetic ErrnoException style errors.
204
207
 
205
- In some rare low-level cases, there are operations we perform
206
- that are very similar to a node filesystem operation.
208
+ In some rare low-level cases, there are operations we perform that are
209
+ very similar to a node filesystem operation.
207
210
 
208
211
  For example, the `@vltpkg/which` module raises an error that is
209
- intentionally similar to node's filesystem `ENOENT` errors,
210
- because that is semantically sensible.
212
+ intentionally similar to node's filesystem `ENOENT` errors, because
213
+ that is semantically sensible.
211
214
 
212
- In those cases, the error _must_ follow node's conventions as
213
- close as possible. If we feel the need to add additional
214
- information beyond a known system error code, string path, etc.,
215
- or if the message isn't one that is typically raised by the
216
- underlying system, then it's a good sign that we ought to be
217
- creating an `Error` with a `cause` so that it can be reported
218
- more usefully.
215
+ In those cases, the error _must_ follow node's conventions as close as
216
+ possible. If we feel the need to add additional information beyond a
217
+ known system error code, string path, etc., or if the message isn't
218
+ one that is typically raised by the underlying system, then it's a
219
+ good sign that we ought to be creating an `Error` with a `cause` so
220
+ that it can be reported more usefully.
219
221
 
220
222
  In such cases, this is fine:
221
223
 
@@ -237,11 +239,11 @@ throw Object.assign(new Error('could not resolve'), {
237
239
  })
238
240
  ```
239
241
 
240
- **Do not** copy properties from a lower-level error or cause onto
241
- the new cause object. That is unnecessary, and obscures the
242
- origin of problems. Instead, just include the lower-level error
243
- as the `cause` property. If you already have a low-level error,
244
- you don't need to invent a synthetic one!
242
+ **Do not** copy properties from a lower-level error or cause onto the
243
+ new cause object. That is unnecessary, and obscures the origin of
244
+ problems. Instead, just include the lower-level error as the `cause`
245
+ property. If you already have a low-level error, you don't need to
246
+ invent a synthetic one!
245
247
 
246
248
  For example, do not do this:
247
249
 
@@ -271,10 +273,10 @@ try {
271
273
  ### Do not subclass `Error`.
272
274
 
273
275
  Just use the `Error` classes defined in the language. Additional
274
- information about error causes should be on the `cause` property,
275
- not implicit in the constructor type.
276
+ information about error causes should be on the `cause` property, not
277
+ implicit in the constructor type.
276
278
 
277
- Ie, do not do this:
279
+ I.e. do not do this:
278
280
 
279
281
  ```
280
282
  class VersionError extends Error {
@@ -299,33 +301,33 @@ throw error('Could not version', { version })
299
301
  All of these are optional. Additional fields may be used where
300
302
  appropriate, and should be added to this list over time.
301
303
 
302
- - `cause` - The `cause` field within a `cause` object should
303
- always be an `Error` object that was previously thrown. Note
304
- that the `cause` on an Error itself might _also_ be a
305
- previously thrown error, if no additional information could be
306
- usefully added beyond improving the message.
304
+ - `cause` - The `cause` field within a `cause` object should always be
305
+ an `Error` object that was previously thrown. Note that the `cause`
306
+ on an Error itself might _also_ be a previously thrown error, if no
307
+ additional information could be usefully added beyond improving the
308
+ message.
307
309
  - `name` - String. The name of something.
308
310
  - `offset` - Number. The offset in a Buffer or file where we are
309
311
  trying to read or write.
310
312
  - `registry` - String or URL. A package registry.
311
- - `code` - This must be a string if set, and should
312
- only be present if it's one of our creation, not a code raised
313
- on a system error. Eg, `ERESOLVE`, not `ENOENT`.
313
+ - `code` - This must be a string if set, and should only be present if
314
+ it's one of our creation, not a code raised on a system error. Eg,
315
+ `ERESOLVE`, not `ENOENT`.
314
316
  - `path` - The target of a file system operation.
315
317
  - `target` - path on disk that is being written or extracted to
316
- - `spec` - a `@vltpkg/spec.Spec` object relevant to the operation
317
- that failed.
318
- - `from` - string. The file path origin of a resolution that
319
- failed, for example in the case of relative `file:` specifiers.
320
- - `status` - Number or null. Either the exit code of a process or
321
- an HTTP response status code.
322
- - `signal` - `NodeJS.Signals` string or null, indicating the
323
- signal that terminated a process.
318
+ - `spec` - a `@vltpkg/spec.Spec` object relevant to the operation that
319
+ failed.
320
+ - `from` - string. The file path origin of a resolution that failed,
321
+ for example in the case of relative `file:` specifiers.
322
+ - `status` - Number or null. Either the exit code of a process or an
323
+ HTTP response status code.
324
+ - `signal` - `NodeJS.Signals` string or null, indicating the signal
325
+ that terminated a process.
324
326
  - `validOptions` - Array of valid options when something is not a
325
327
  valid option. (For use in `did you mean X?` output.)
326
- - `todo` - String message indicating what bit of work this might
327
- be a part of, what feature needs to be implemented, etc. Eg, `{
328
- todo: 'nested workspace support' }`.
328
+ - `todo` - String message indicating what bit of work this might be a
329
+ part of, what feature needs to be implemented, etc. Eg,
330
+ `{ todo: 'nested workspace support' }`.
329
331
  - `wanted` - A desired value that was not found, or a regular
330
332
  expression or other pattern describing it.
331
333
  - `found` - The actual value, which was not wanted.
@@ -345,9 +347,9 @@ todo: 'nested workspace support' }`.
345
347
 
346
348
  - If there is a _type_ problem with an argument, for example a
347
349
  `string` was expected and a `number` was provided, throw a
348
- `TypeError`. **Do not** use it for a value that is the correct
349
- type but otherwise invalid, such as a `string` argument that is
350
- actually a `string` but does not match an expected pattern.
350
+ `TypeError`. **Do not** use it for a value that is the correct type
351
+ but otherwise invalid, such as a `string` argument that is actually
352
+ a `string` but does not match an expected pattern.
351
353
  - If the type is fine, but a parsed string is invalid and not
352
354
  parseable, use `SyntaxError`.
353
355
  - In all other cases, use `Error`.
@@ -1,4 +1,4 @@
1
- import type { IncomingMessage } from 'http';
1
+ import type { IncomingHttpHeaders, IncomingMessage } from 'http';
2
2
  /**
3
3
  * Codification of vlt's Error.cause conventions
4
4
  *
@@ -7,15 +7,17 @@ import type { IncomingMessage } from 'http';
7
7
  * Several of these types are just very basic duck-typing, because referencing
8
8
  * internal types directly would create a workspace dependency cycle.
9
9
  */
10
- export type ErrorCauseObject = {
10
+ export type ErrorCauseOptions = {
11
11
  /**
12
12
  * The `cause` field within a `cause` object should
13
13
  * always be an `Error` object that was previously thrown. Note
14
14
  * that the `cause` on an Error itself might _also_ be a
15
15
  * previously thrown error, if no additional information could be
16
- * usefully added beyond improving the message.
16
+ * usefully added beyond improving the message. It is typed as `unknown`
17
+ * because we use `useUnknownInCatchVariables` so this makes it easier
18
+ * to rethrow a caught error without recasting it.
17
19
  */
18
- cause?: ErrorCause;
20
+ cause?: unknown;
19
21
  /** the name of something */
20
22
  name?: string;
21
23
  /** byte offset in a Buffer or file */
@@ -61,7 +63,7 @@ export type ErrorCauseObject = {
61
63
  * Array of valid options when something is not a valid option.
62
64
  * (For use in `did you mean X?` output.)
63
65
  */
64
- validOptions?: any[];
66
+ validOptions?: unknown[];
65
67
  /**
66
68
  * message indicating what bit of work this might be a part of, what feature
67
69
  * needs to be implemented, etc. Eg, `{ todo: 'nested workspace support' }`.
@@ -71,18 +73,20 @@ export type ErrorCauseObject = {
71
73
  * A desired value that was not found, or a regular expression or other
72
74
  * pattern describing it.
73
75
  */
74
- wanted?: any;
76
+ wanted?: unknown;
75
77
  /** actual value, which was not wanted */
76
- found?: any;
78
+ found?: unknown;
77
79
  /** HTTP message, fetch.Response, or `@vltpkg/registry-client.CacheEntry` */
78
80
  response?: IncomingMessage | Response | {
79
81
  statusCode: number;
80
- headers: Buffer[] | Record<string, string[] | string>;
81
- text: () => string;
82
+ headers: Buffer[] | Record<string, string[] | string> | IncomingHttpHeaders;
83
+ text?: () => string;
82
84
  [k: number | string | symbol]: any;
83
85
  };
84
86
  /** string or URL object */
85
87
  url?: URL | string;
88
+ /** HTTP method */
89
+ method?: string;
86
90
  /** git repository remote or path */
87
91
  repository?: string;
88
92
  /** string or `@vltpkg/semver.Version` object */
@@ -110,9 +114,9 @@ export type ErrorCauseObject = {
110
114
  time?: Record<string, string>;
111
115
  };
112
116
  /** maximum value, which was exceeded */
113
- max?: any;
117
+ max?: unknown;
114
118
  /** minimum value, which was not met */
115
- min?: any;
119
+ min?: unknown;
116
120
  };
117
121
  export type DuckTypeManifest = Record<string, any> & {
118
122
  name?: string;
@@ -133,13 +137,75 @@ export type DuckTypeManifest = Record<string, any> & {
133
137
  }[];
134
138
  };
135
139
  };
136
- export type ErrorCause = Error | ErrorCauseObject;
140
+ /**
141
+ * The input cause for the {@link error} functions. Can either be a plain error
142
+ * or an error cause options object.
143
+ */
144
+ export type ErrorCause = Error | ErrorCauseOptions;
145
+ /**
146
+ * The same as {@link ErrorCauseOptions} except where `cause` has been
147
+ * converted to an Error.
148
+ */
149
+ export type ErrorCauseResult = Omit<ErrorCauseOptions, 'cause'> & {
150
+ cause?: Error;
151
+ };
152
+ /**
153
+ * An error with a cause property. Cause defaults to `unknown`.
154
+ */
155
+ export type ErrorWithCause<T extends Error = Error, U = unknown> = T & {
156
+ cause: U;
157
+ };
158
+ /**
159
+ * An error with a cause property that is an Error.
160
+ */
161
+ export type ErrorWithCauseError<T extends Error = Error> = ErrorWithCause<T, Error>;
162
+ /**
163
+ * An error with a cause property that is an {@link ErrorCauseResult}.
164
+ */
165
+ export type ErrorWithCauseObject<T extends Error = Error> = ErrorWithCause<T, ErrorCauseResult>;
166
+ /**
167
+ * Helper util to convert unknown to a plain error. Not specifically
168
+ * related to error causes, but useful for error handling in general.
169
+ */
170
+ export declare const asError: (er: unknown, fallbackMessage?: string) => Error;
171
+ /**
172
+ * Helper util to check if an error has any type of cause property.
173
+ * Note that this does not mean it is a cause from this library,
174
+ * just that it has a cause property.
175
+ */
176
+ export declare const isErrorWithCause: (er: unknown) => er is ErrorWithCause;
177
+ export declare const errorCodes: readonly ["EEXIST", "EINTEGRITY", "EINVAL", "ELIFECYCLE", "EMAXREDIRECT", "ENEEDAUTH", "ENOENT", "ENOGIT", "ERESOLVE", "EUNKNOWN", "EUSAGE", "EREQUEST"];
137
178
  /**
138
179
  * Valid properties for the 'code' field in an Error cause.
139
180
  * Add new options to this list as needed.
140
181
  */
141
- export type Codes = 'EEXIST' | 'EINTEGRITY' | 'EINVAL' | 'ELIFECYCLE' | 'EMAXREDIRECT' | 'ENEEDAUTH' | 'ENOENT' | 'ENOGIT' | 'ERESOLVE' | 'EUNKNOWN';
142
- export declare const error: (message: string, cause?: ErrorCause, from?: ((...a: any[]) => any) | (new (...a: any[]) => any)) => Error;
143
- export declare const typeError: (message: string, cause?: ErrorCause, from?: ((...a: any[]) => any) | (new (...a: any[]) => any)) => Error;
144
- export declare const syntaxError: (message: string, cause?: ErrorCause, from?: ((...a: any[]) => any) | (new (...a: any[]) => any)) => Error;
182
+ export type Codes = (typeof errorCodes)[number];
183
+ /**
184
+ * An error with a cause property that is an {@link ErrorCauseResult}
185
+ * and has a code property that is a {@link Codes}.
186
+ */
187
+ export type ErrorWithCode<T extends Error = Error> = ErrorWithCause<T, Omit<ErrorCauseResult, 'code'> & {
188
+ code: Exclude<ErrorCauseResult['code'], undefined>;
189
+ }>;
190
+ /**
191
+ * Type guard to check if an error has one of our error code properties.
192
+ * Note that the type check only checks for the code property and value,
193
+ * but since every property on {@link ErrorCauseOptions} is optional, this should
194
+ * be sufficient to know the shape of the cause and use it in printing.
195
+ */
196
+ export declare const isErrorWithCode: (er: unknown) => er is ErrorWithCode;
197
+ export type From = Function;
198
+ export type ErrorCtor<T extends Error> = new (message: string, options?: {
199
+ cause: Error | ErrorCauseResult;
200
+ }) => T;
201
+ export type ErrorResult<T extends Error = Error> = T | ErrorWithCauseError<TypeError> | ErrorWithCauseObject<TypeError>;
202
+ export declare function error(message: string, cause?: undefined, from?: From): Error;
203
+ export declare function error(message: string, cause: Error, from?: From): ErrorWithCauseError;
204
+ export declare function error(message: string, cause: ErrorCauseOptions, from?: From): ErrorWithCauseObject;
205
+ export declare function typeError(message: string, cause?: undefined, from?: From): TypeError;
206
+ export declare function typeError(message: string, cause: Error, from?: From): ErrorWithCauseError<TypeError>;
207
+ export declare function typeError(message: string, cause: ErrorCauseOptions, from?: From): ErrorWithCauseObject<TypeError>;
208
+ export declare function syntaxError(message: string, cause?: undefined, from?: From): SyntaxError;
209
+ export declare function syntaxError(message: string, cause: Error, from?: From): ErrorWithCauseError<SyntaxError>;
210
+ export declare function syntaxError(message: string, cause: ErrorCauseOptions, from?: From): ErrorWithCauseObject<SyntaxError>;
145
211
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,MAAM,CAAA;AAE3C;;;;;;;GAOG;AACH,MAAM,MAAM,gB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AAE,IAAI,GACV,mBAAmB,CAAC,SAAS,CAAC,CAAA;AACjC,wBAAgB,SAAS,CACvB,OAAO,EAAE,MAAM,EACf,KAAK,EAAE,iBAAiB,EACxB,IAAI,CAAC,EAAE,IAAI,GACV,oBAAoB,CAAC,SAAS,CAAC,CAAA;AASlC,wBAAgB,WAAW,CACzB,OAAO,EAAE,MAAM,EACf,KAAK,CAAC,EAAE,SAAS,EACjB,IAAI,CAAC,EAAE,IAAI,GACV,WAAW,CAAA;AACd,wBAAgB,WAAW,CACzB,OAAO,EAAE,MAAM,EACf,KAAK,EAAE,KAAK,EACZ,IAAI,CAAC,EAAE,IAAI,GACV,mBAAmB,CAAC,WAAW,CAAC,CAAA;AACnC,wBAAgB,WAAW,CACzB,OAAO,EAAE,MAAM,EACf,KAAK,EAAE,iBAAiB,EACxB,IAAI,CAAC,EAAE,IAAI,GACV,oBAAoB,CAAC,WAAW,CAAC,CAAA"}
package/dist/esm/index.js CHANGED
@@ -1,10 +1,70 @@
1
- const create = (cls, defaultFrom, message, cause, from = defaultFrom) => {
2
- const er = new cls(message, cause ? { cause } : undefined);
3
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
4
- Error.captureStackTrace?.(er, from);
1
+ /**
2
+ * Helper util to convert unknown to a plain error. Not specifically
3
+ * related to error causes, but useful for error handling in general.
4
+ */
5
+ export const asError = (er, fallbackMessage = 'Unknown error') => er instanceof Error ? er : new Error(String(er) || fallbackMessage);
6
+ /**
7
+ * Helper util to check if an error has any type of cause property.
8
+ * Note that this does not mean it is a cause from this library,
9
+ * just that it has a cause property.
10
+ */
11
+ export const isErrorWithCause = (er) => er instanceof Error && 'cause' in er;
12
+ export const errorCodes = [
13
+ 'EEXIST',
14
+ 'EINTEGRITY',
15
+ 'EINVAL',
16
+ 'ELIFECYCLE',
17
+ 'EMAXREDIRECT',
18
+ 'ENEEDAUTH',
19
+ 'ENOENT',
20
+ 'ENOGIT',
21
+ 'ERESOLVE',
22
+ 'EUNKNOWN',
23
+ 'EUSAGE',
24
+ 'EREQUEST',
25
+ ];
26
+ const errorCodesSet = new Set(errorCodes);
27
+ /**
28
+ * Type guard to check if an error has one of our error code properties.
29
+ * Note that the type check only checks for the code property and value,
30
+ * but since every property on {@link ErrorCauseOptions} is optional, this should
31
+ * be sufficient to know the shape of the cause and use it in printing.
32
+ */
33
+ export const isErrorWithCode = (er) => isErrorWithCause(er) &&
34
+ !!er.cause &&
35
+ typeof er.cause === 'object' &&
36
+ 'code' in er.cause &&
37
+ typeof er.cause.code === 'string' &&
38
+ errorCodesSet.has(er.cause.code);
39
+ // `captureStackTrace` is non-standard so explicitly type it as possibly
40
+ // undefined since it might be in browsers.
41
+ const { captureStackTrace } = Error;
42
+ function create(cls, defaultFrom, message, cause, from = defaultFrom) {
43
+ let er = null;
44
+ if (cause instanceof Error) {
45
+ er = new cls(message, { cause });
46
+ }
47
+ else if (cause && typeof cause === 'object') {
48
+ if ('cause' in cause) {
49
+ cause.cause = asError(cause.cause);
50
+ }
51
+ er = new cls(message, {
52
+ cause: cause,
53
+ });
54
+ }
55
+ else {
56
+ er = new cls(message);
57
+ }
58
+ captureStackTrace?.(er, from);
5
59
  return er;
6
- };
7
- export const error = (message, cause, from) => create(Error, error, message, cause, from);
8
- export const typeError = (message, cause, from) => create(TypeError, typeError, message, cause, from);
9
- export const syntaxError = (message, cause, from) => create(SyntaxError, syntaxError, message, cause, from);
60
+ }
61
+ export function error(message, cause, from) {
62
+ return create(Error, error, message, cause, from);
63
+ }
64
+ export function typeError(message, cause, from) {
65
+ return create(TypeError, typeError, message, cause, from);
66
+ }
67
+ export function syntaxError(message, cause, from) {
68
+ return create(SyntaxError, syntaxError, message, cause, from);
69
+ }
10
70
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAiMA,MAAM,MAAM,GAAG,CACb,GAAiB,EACjB,WAAgE,EAChE,OAAe,EACf,KAAkB,EAClB,OAEiC,WAAW,EAC5C,EAAE;IACF,MAAM,EAAE,GAAG,IAAI,GAAG,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC,CAAA;IAC1D,uEAAuE;IACvE,KAAK,CAAC,iBAAiB,EAAE,CAAC,EAAE,EAAE,IAAI,CAAC,CAAA;IACnC,OAAO,EAAE,CAAA;AACX,CAAC,CAAA;AAED,MAAM,CAAC,MAAM,KAAK,GAAG,CACnB,OAAe,EACf,KAAkB,EAClB,IAA0D,EAC1D,EAAE,CAAC,MAAM,CAAC,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC,CAAA;AAE/C,MAAM,CAAC,MAAM,SAAS,GAAG,CACvB,OAAe,EACf,KAAkB,EAClB,IAA0D,EAC1D,EAAE,CAAC,MAAM,CAAC,SAAS,EAAE,SAAS,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC,CAAA;AAEvD,MAAM,CAAC,MAAM,WAAW,GAAG,CACzB,OAAe,EACf,KAAkB,EAClB,IAA0D,EAC1D,EAAE,CAAC,MAAM,CAAC,WAAW,EAAE,WAAW,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC,CAAA","sourcesContent":["import type { IncomingMessage } from 'http'\n\n/**\n * Codification of vlt's Error.cause conventions\n *\n * Add new properties to this list as needed.\n *\n * Several of these types are just very basic duck-typing, because referencing\n * internal types directly would create a workspace dependency cycle.\n */\nexport type ErrorCauseObject = {\n /**\n * The `cause` field within a `cause` object should\n * always be an `Error` object that was previously thrown. Note\n * that the `cause` on an Error itself might _also_ be a\n * previously thrown error, if no additional information could be\n * usefully added beyond improving the message.\n */\n cause?: ErrorCause\n\n /** the name of something */\n name?: string\n\n /** byte offset in a Buffer or file */\n offset?: number\n\n /**\n * This should only be a string code that we set. See {@link Codes} for\n * the supported options. Lower-level system codes like `ENOENT` should\n * remain on the errors that generated them.\n */\n code?: Codes\n\n /** target of a file system operation */\n path?: string\n\n /**\n * file path origin of a resolution that failed, for example in the case\n * of `file://` specifiers.\n */\n from?: string\n\n /** path on disk that is being written, linked, or extracted to */\n target?: string\n\n /** Spec object/string relevant to an operation that failed */\n spec?:\n | string\n | {\n type: 'file' | 'git' | 'registry' | 'remote' | 'workspace'\n spec: string\n [k: number | string | symbol]: any\n }\n\n /** exit code of a process, or HTTP response status code */\n status?: number | null\n\n /** null or a signal that a process received */\n signal?: NodeJS.Signals | null\n\n /** the root of a project */\n projectRoot?: string\n\n /** the current working directory of a process */\n cwd?: string\n\n /** a command being run in a child process */\n command?: string\n\n /** the arguments passed to a process */\n args?: string[]\n\n /** standard output from a process */\n stdout?: Buffer | string | null\n\n /** standard error from a process */\n stderr?: Buffer | string | null\n\n /**\n * Array of valid options when something is not a valid option.\n * (For use in `did you mean X?` output.)\n */\n validOptions?: any[]\n\n /**\n * message indicating what bit of work this might be a part of, what feature\n * needs to be implemented, etc. Eg, `{ todo: 'nested workspace support' }`.\n */\n todo?: string\n\n /**\n * A desired value that was not found, or a regular expression or other\n * pattern describing it.\n */\n wanted?: any\n\n /** actual value, which was not wanted */\n found?: any\n\n /** HTTP message, fetch.Response, or `@vltpkg/registry-client.CacheEntry` */\n response?:\n | IncomingMessage\n | Response\n | {\n statusCode: number\n headers: Buffer[] | Record<string, string[] | string>\n text: () => string\n [k: number | string | symbol]: any\n }\n\n /** string or URL object */\n url?: URL | string\n\n /** git repository remote or path */\n repository?: string\n\n /** string or `@vltpkg/semver.Version` object */\n version?:\n | string\n | {\n raw: string\n major: number\n minor: number\n patch: number\n [k: number | string | symbol]: any\n }\n\n /** string or `@vltpkg/semver.Range` object */\n range?:\n | string\n | {\n raw: string\n isAny: boolean\n includePrerelease: boolean\n [k: number | string | symbol]: any\n }\n\n /** a package manifest, either from `package.json` or a registry */\n manifest?: DuckTypeManifest\n\n /** registry top-level package document */\n packument?: {\n name: string\n 'dist-tags': Record<string, string>\n versions: Record<string, DuckTypeManifest>\n time?: Record<string, string>\n }\n\n /** maximum value, which was exceeded */\n max?: any\n\n /** minimum value, which was not met */\n min?: any\n}\n\nexport type DuckTypeManifest = Record<string, any> & {\n name?: string\n version?: string\n deprecated?: string\n engines?: Record<string, string>\n os?: string[] | string\n arch?: string[] | string\n dist?: {\n integrity?: string\n shasum?: string\n tarball?: string\n fileCount?: number\n unpackedSize?: number\n signatures?: {\n keyid: string\n sig: string\n }[]\n }\n}\n\nexport type ErrorCause = Error | ErrorCauseObject\n\n/**\n * Valid properties for the 'code' field in an Error cause.\n * Add new options to this list as needed.\n */\nexport type Codes =\n | 'EEXIST'\n | 'EINTEGRITY'\n | 'EINVAL'\n | 'ELIFECYCLE'\n | 'EMAXREDIRECT'\n | 'ENEEDAUTH'\n | 'ENOENT'\n | 'ENOGIT'\n | 'ERESOLVE'\n | 'EUNKNOWN'\n\nconst create = (\n cls: typeof Error,\n defaultFrom: ((...a: any[]) => any) | (new (...a: any[]) => any),\n message: string,\n cause?: ErrorCause,\n from:\n | ((...a: any[]) => any)\n | (new (...a: any[]) => any) = defaultFrom,\n) => {\n const er = new cls(message, cause ? { cause } : undefined)\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n Error.captureStackTrace?.(er, from)\n return er\n}\n\nexport const error = (\n message: string,\n cause?: ErrorCause,\n from?: ((...a: any[]) => any) | (new (...a: any[]) => any),\n) => create(Error, error, message, cause, from)\n\nexport const typeError = (\n message: string,\n cause?: ErrorCause,\n from?: ((...a: any[]) => any) | (new (...a: any[]) => any),\n) => create(TypeError, typeError, message, cause, from)\n\nexport const syntaxError = (\n message: string,\n cause?: ErrorCause,\n from?: ((...a: any[]) => any) | (new (...a: any[]) => any),\n) => create(SyntaxError, syntaxError, message, cause, from)\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAyNA;;;GAGG;AACH,MAAM,CAAC,MAAM,OAAO,GAAG,CACrB,EAAW,EACX,eAA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;SAAM,IAAI,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QAC9C,IAAI,OAAO,IAAI,KAAK,EAAE,CAAC;YACrB,KAAK,CAAC,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAA;QACpC,CAAC;QACD,EAAE,GAAG,IAAI,GAAG,CAAC,OAAO,EAAE;YACpB,KAAK,EAAE,KAAyB;SACjC,CAAC,CAAA;IACJ,CAAC;SAAM,CAAC;QACN,EAAE,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,CAAA;IACvB,CAAC;IACD,iBAAiB,EAAE,CAAC,EAAE,EAAE,IAAI,CAAC,CAAA;IAC7B,OAAO,EAAE,CAAA;AACX,CAAC;AAiBD,MAAM,UAAU,KAAK,CACnB,OAAe,EACf,KAAkB,EAClB,IAAW;IAEX,OAAO,MAAM,CAAC,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC,CAAA;AACnD,CAAC;AAiBD,MAAM,UAAU,SAAS,CACvB,OAAe,EACf,KAAkB,EAClB,IAAW;IAEX,OAAO,MAAM,CAAY,SAAS,EAAE,SAAS,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC,CAAA;AACtE,CAAC;AAiBD,MAAM,UAAU,WAAW,CACzB,OAAe,EACf,KAAkB,EAClB,IAAW;IAEX,OAAO,MAAM,CACX,WAAW,EACX,WAAW,EACX,OAAO,EACP,KAAK,EACL,IAAI,CACL,CAAA;AACH,CAAC","sourcesContent":["import type { IncomingHttpHeaders, IncomingMessage } from 'http'\n\n/**\n * Codification of vlt's Error.cause conventions\n *\n * Add new properties to this list as needed.\n *\n * Several of these types are just very basic duck-typing, because referencing\n * internal types directly would create a workspace dependency cycle.\n */\nexport type ErrorCauseOptions = {\n /**\n * The `cause` field within a `cause` object should\n * always be an `Error` object that was previously thrown. Note\n * that the `cause` on an Error itself might _also_ be a\n * previously thrown error, if no additional information could be\n * usefully added beyond improving the message. It is typed as `unknown`\n * because we use `useUnknownInCatchVariables` so this makes it easier\n * to rethrow a caught error without recasting it.\n */\n cause?: unknown\n\n /** the name of something */\n name?: string\n\n /** byte offset in a Buffer or file */\n offset?: number\n\n /**\n * This should only be a string code that we set. See {@link Codes} for\n * the supported options. Lower-level system codes like `ENOENT` should\n * remain on the errors that generated them.\n */\n code?: Codes\n\n /** target of a file system operation */\n path?: string\n\n /**\n * file path origin of a resolution that failed, for example in the case\n * of `file://` specifiers.\n */\n from?: string\n\n /** path on disk that is being written, linked, or extracted to */\n target?: string\n\n /** Spec object/string relevant to an operation that failed */\n spec?:\n | string\n | {\n type: 'file' | 'git' | 'registry' | 'remote' | 'workspace'\n spec: string\n [k: number | string | symbol]: any\n }\n\n /** exit code of a process, or HTTP response status code */\n status?: number | null\n\n /** null or a signal that a process received */\n signal?: NodeJS.Signals | null\n\n /** the root of a project */\n projectRoot?: string\n\n /** the current working directory of a process */\n cwd?: string\n\n /** a command being run in a child process */\n command?: string\n\n /** the arguments passed to a process */\n args?: string[]\n\n /** standard output from a process */\n stdout?: Buffer | string | null\n\n /** standard error from a process */\n stderr?: Buffer | string | null\n\n /**\n * Array of valid options when something is not a valid option.\n * (For use in `did you mean X?` output.)\n */\n validOptions?: unknown[]\n\n /**\n * message indicating what bit of work this might be a part of, what feature\n * needs to be implemented, etc. Eg, `{ todo: 'nested workspace support' }`.\n */\n todo?: string\n\n /**\n * A desired value that was not found, or a regular expression or other\n * pattern describing it.\n */\n wanted?: unknown\n\n /** actual value, which was not wanted */\n found?: unknown\n\n /** HTTP message, fetch.Response, or `@vltpkg/registry-client.CacheEntry` */\n response?:\n | IncomingMessage\n | Response\n | {\n statusCode: number\n headers:\n | Buffer[]\n | Record<string, string[] | string>\n | IncomingHttpHeaders\n text?: () => string\n [k: number | string | symbol]: any\n }\n\n /** string or URL object */\n url?: URL | string\n\n /** HTTP method */\n method?: string\n\n /** git repository remote or path */\n repository?: string\n\n /** string or `@vltpkg/semver.Version` object */\n version?:\n | string\n | {\n raw: string\n major: number\n minor: number\n patch: number\n [k: number | string | symbol]: any\n }\n\n /** string or `@vltpkg/semver.Range` object */\n range?:\n | string\n | {\n raw: string\n isAny: boolean\n includePrerelease: boolean\n [k: number | string | symbol]: any\n }\n\n /** a package manifest, either from `package.json` or a registry */\n manifest?: DuckTypeManifest\n\n /** registry top-level package document */\n packument?: {\n name: string\n 'dist-tags': Record<string, string>\n versions: Record<string, DuckTypeManifest>\n time?: Record<string, string>\n }\n\n /** maximum value, which was exceeded */\n max?: unknown\n\n /** minimum value, which was not met */\n min?: unknown\n}\n\nexport type DuckTypeManifest = Record<string, any> & {\n name?: string\n version?: string\n deprecated?: string\n engines?: Record<string, string>\n os?: string[] | string\n arch?: string[] | string\n dist?: {\n integrity?: string\n shasum?: string\n tarball?: string\n fileCount?: number\n unpackedSize?: number\n signatures?: {\n keyid: string\n sig: string\n }[]\n }\n}\n\n/**\n * The input cause for the {@link error} functions. Can either be a plain error\n * or an error cause options object.\n */\nexport type ErrorCause = Error | ErrorCauseOptions\n\n/**\n * The same as {@link ErrorCauseOptions} except where `cause` has been\n * converted to an Error.\n */\nexport type ErrorCauseResult = Omit<ErrorCauseOptions, 'cause'> & {\n cause?: Error\n}\n\n/**\n * An error with a cause property. Cause defaults to `unknown`.\n */\nexport type ErrorWithCause<\n T extends Error = Error,\n U = unknown,\n> = T & { cause: U }\n\n/**\n * An error with a cause property that is an Error.\n */\nexport type ErrorWithCauseError<T extends Error = Error> =\n ErrorWithCause<T, Error>\n\n/**\n * An error with a cause property that is an {@link ErrorCauseResult}.\n */\nexport type ErrorWithCauseObject<T extends Error = Error> =\n ErrorWithCause<T, ErrorCauseResult>\n\n/**\n * Helper util to convert unknown to a plain error. Not specifically\n * related to error causes, but useful for error handling in general.\n */\nexport const asError = (\n er: unknown,\n fallbackMessage = 'Unknown error',\n): Error =>\n er instanceof Error ? er : new Error(String(er) || fallbackMessage)\n\n/**\n * Helper util to check if an error has any type of cause property.\n * Note that this does not mean it is a cause from this library,\n * just that it has a cause property.\n */\nexport const isErrorWithCause = (er: unknown): er is ErrorWithCause =>\n er instanceof Error && 'cause' in er\n\nexport const errorCodes = [\n 'EEXIST',\n 'EINTEGRITY',\n 'EINVAL',\n 'ELIFECYCLE',\n 'EMAXREDIRECT',\n 'ENEEDAUTH',\n 'ENOENT',\n 'ENOGIT',\n 'ERESOLVE',\n 'EUNKNOWN',\n 'EUSAGE',\n 'EREQUEST',\n] as const\n\nconst errorCodesSet = new Set(errorCodes)\n\n/**\n * Valid properties for the 'code' field in an Error cause.\n * Add new options to this list as needed.\n */\nexport type Codes = (typeof errorCodes)[number]\n\n/**\n * An error with a cause property that is an {@link ErrorCauseResult}\n * and has a code property that is a {@link Codes}.\n */\nexport type ErrorWithCode<T extends Error = Error> = ErrorWithCause<\n T,\n Omit<ErrorCauseResult, 'code'> & {\n code: Exclude<ErrorCauseResult['code'], undefined>\n }\n>\n\n/**\n * Type guard to check if an error has one of our error code properties.\n * Note that the type check only checks for the code property and value,\n * but since every property on {@link ErrorCauseOptions} is optional, this should\n * be sufficient to know the shape of the cause and use it in printing.\n */\nexport const isErrorWithCode = (er: unknown): er is ErrorWithCode =>\n isErrorWithCause(er) &&\n !!er.cause &&\n typeof er.cause === 'object' &&\n 'code' in er.cause &&\n typeof er.cause.code === 'string' &&\n errorCodesSet.has(er.cause.code as Codes)\n\n// Use `Function` because that is the same type as `Error.captureStackTrace`\n// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\nexport type From = Function\n\n// `captureStackTrace` is non-standard so explicitly type it as possibly\n// undefined since it might be in browsers.\nconst { captureStackTrace } = Error as {\n captureStackTrace?: ErrorConstructor['captureStackTrace']\n}\n\nexport type ErrorCtor<T extends Error> = new (\n message: string,\n options?: { cause: Error | ErrorCauseResult },\n) => T\n\nexport type ErrorResult<T extends Error = Error> =\n | T\n | ErrorWithCauseError<TypeError>\n | ErrorWithCauseObject<TypeError>\n\nfunction create<T extends Error>(\n cls: ErrorCtor<T>,\n defaultFrom: From,\n message: string,\n cause?: undefined,\n from?: From,\n): T\nfunction create<T extends Error>(\n cls: ErrorCtor<T>,\n defaultFrom: From,\n message: string,\n cause?: Error,\n from?: From,\n): ErrorWithCauseError<T>\nfunction create<T extends Error>(\n cls: ErrorCtor<T>,\n defaultFrom: From,\n message: string,\n cause?: ErrorCauseOptions,\n from?: From,\n): ErrorWithCauseObject<T>\nfunction create<T extends Error>(\n cls: ErrorCtor<T>,\n defaultFrom: From,\n message: string,\n cause?: ErrorCause,\n from: From = defaultFrom,\n) {\n let er: T | null = null\n if (cause instanceof Error) {\n er = new cls(message, { cause })\n } else if (cause && typeof cause === 'object') {\n if ('cause' in cause) {\n cause.cause = asError(cause.cause)\n }\n er = new cls(message, {\n cause: cause as ErrorCauseResult,\n })\n } else {\n er = new cls(message)\n }\n captureStackTrace?.(er, from)\n return er\n}\n\nexport function error(\n message: string,\n cause?: undefined,\n from?: From,\n): Error\nexport function error(\n message: string,\n cause: Error,\n from?: From,\n): ErrorWithCauseError\nexport function error(\n message: string,\n cause: ErrorCauseOptions,\n from?: From,\n): ErrorWithCauseObject\nexport function error(\n message: string,\n cause?: ErrorCause,\n from?: From,\n): ErrorResult {\n return create(Error, error, message, cause, from)\n}\n\nexport function typeError(\n message: string,\n cause?: undefined,\n from?: From,\n): TypeError\nexport function typeError(\n message: string,\n cause: Error,\n from?: From,\n): ErrorWithCauseError<TypeError>\nexport function typeError(\n message: string,\n cause: ErrorCauseOptions,\n from?: From,\n): ErrorWithCauseObject<TypeError>\nexport function typeError(\n message: string,\n cause?: ErrorCause,\n from?: From,\n): ErrorResult<TypeError> {\n return create<TypeError>(TypeError, typeError, message, cause, from)\n}\n\nexport function syntaxError(\n message: string,\n cause?: undefined,\n from?: From,\n): SyntaxError\nexport function syntaxError(\n message: string,\n cause: Error,\n from?: From,\n): ErrorWithCauseError<SyntaxError>\nexport function syntaxError(\n message: string,\n cause: ErrorCauseOptions,\n from?: From,\n): ErrorWithCauseObject<SyntaxError>\nexport function syntaxError(\n message: string,\n cause?: ErrorCause,\n from?: From,\n): ErrorResult<SyntaxError> {\n return create<SyntaxError>(\n SyntaxError,\n syntaxError,\n message,\n cause,\n from,\n )\n}\n"]}
package/package.json CHANGED
@@ -1,9 +1,15 @@
1
1
  {
2
2
  "name": "@vltpkg/error-cause",
3
3
  "description": "vlts Error.cause convention",
4
- "version": "0.0.0-0.1730239248325",
4
+ "version": "0.0.0-10",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/vltpkg/vltpkg.git",
8
+ "directory": "src/error-cause"
9
+ },
5
10
  "tshy": {
6
11
  "selfLink": false,
12
+ "liveDev": true,
7
13
  "dialects": [
8
14
  "esm"
9
15
  ],
@@ -13,19 +19,19 @@
13
19
  }
14
20
  },
15
21
  "devDependencies": {
16
- "@eslint/js": "^9.8.0",
17
- "@types/eslint__js": "^8.42.3",
18
- "@types/node": "^22.4.1",
19
- "eslint": "^9.8.0",
20
- "prettier": "^3.3.2",
21
- "tap": "^21.0.1",
22
+ "@eslint/js": "^9.25.0",
23
+ "@types/node": "^22.14.1",
24
+ "eslint": "^9.25.0",
25
+ "prettier": "^3.5.3",
26
+ "tap": "^21.1.0",
22
27
  "tshy": "^3.0.2",
23
- "typescript": "^5.5.4",
24
- "typescript-eslint": "^8.0.1"
28
+ "typedoc": "~0.27.6",
29
+ "typescript": "5.7.3",
30
+ "typescript-eslint": "^8.30.1"
25
31
  },
26
32
  "license": "BSD-2-Clause-Patent",
27
33
  "engines": {
28
- "node": "20 || >=22"
34
+ "node": ">=22"
29
35
  },
30
36
  "tap": {
31
37
  "extends": "../../tap-config.yaml"
@@ -50,9 +56,9 @@
50
56
  "format:check": "prettier --check . --ignore-path ../../.prettierignore --cache",
51
57
  "lint": "eslint . --fix",
52
58
  "lint:check": "eslint .",
53
- "presnap": "tshy",
54
59
  "snap": "tap",
55
- "pretest": "tshy",
56
- "test": "tap"
60
+ "test": "tap",
61
+ "posttest": "tsc --noEmit",
62
+ "typecheck": "tsc --noEmit"
57
63
  }
58
64
  }