@metamask/snaps-utils 0.37.1-flask.1 → 0.37.2-flask.1

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.
@@ -0,0 +1,230 @@
1
+ import { isObject } from '@metamask/utils';
2
+ import { bold, green, red } from 'chalk';
3
+ import { resolve } from 'path';
4
+ import { Struct, StructError, define, literal as superstructLiteral, union as superstructUnion, create, string, coerce } from 'superstruct';
5
+ import { indent } from './strings';
6
+ /**
7
+ * A wrapper of `superstruct`'s `literal` struct that also defines the name of
8
+ * the struct as the literal value.
9
+ *
10
+ * This is useful for improving the error messages returned by `superstruct`.
11
+ * For example, instead of returning an error like:
12
+ *
13
+ * ```
14
+ * Expected the value to satisfy a union of `literal | literal`, but received: \"baz\"
15
+ * ```
16
+ *
17
+ * This struct will return an error like:
18
+ *
19
+ * ```
20
+ * Expected the value to satisfy a union of `"foo" | "bar"`, but received: \"baz\"
21
+ * ```
22
+ *
23
+ * @param value - The literal value.
24
+ * @returns The `superstruct` struct, which validates that the value is equal
25
+ * to the literal value.
26
+ */ export function literal(value) {
27
+ return define(JSON.stringify(value), superstructLiteral(value).validator);
28
+ }
29
+ /**
30
+ * A wrapper of `superstruct`'s `union` struct that also defines the schema as
31
+ * the union of the schemas of the structs.
32
+ *
33
+ * This is useful for improving the error messages returned by `superstruct`.
34
+ *
35
+ * @param structs - The structs to union.
36
+ * @param structs."0" - The first struct.
37
+ * @param structs."1" - The remaining structs.
38
+ * @returns The `superstruct` struct, which validates that the value satisfies
39
+ * one of the structs.
40
+ */ export function union([head, ...tail]) {
41
+ const struct = superstructUnion([
42
+ head,
43
+ ...tail
44
+ ]);
45
+ return new Struct({
46
+ ...struct,
47
+ schema: [
48
+ head,
49
+ ...tail
50
+ ]
51
+ });
52
+ }
53
+ /**
54
+ * A wrapper of `superstruct`'s `string` struct that coerces a value to a string
55
+ * and resolves it relative to the current working directory. This is useful
56
+ * for specifying file paths in a configuration file, as it allows the user to
57
+ * use both relative and absolute paths.
58
+ *
59
+ * @returns The `superstruct` struct, which validates that the value is a
60
+ * string, and resolves it relative to the current working directory.
61
+ * @example
62
+ * ```ts
63
+ * const config = struct({
64
+ * file: file(),
65
+ * // ...
66
+ * });
67
+ *
68
+ * const value = create({ file: 'path/to/file' }, config);
69
+ * console.log(value.file); // /process/cwd/path/to/file
70
+ * ```
71
+ */ export function file() {
72
+ return coerce(string(), string(), (value)=>{
73
+ return resolve(process.cwd(), value);
74
+ });
75
+ }
76
+ /**
77
+ * Define a struct, and also define the name of the struct as the given name.
78
+ *
79
+ * This is useful for improving the error messages returned by `superstruct`.
80
+ *
81
+ * @param name - The name of the struct.
82
+ * @param struct - The struct.
83
+ * @returns The struct.
84
+ */ export function named(name, struct) {
85
+ return new Struct({
86
+ ...struct,
87
+ type: name
88
+ });
89
+ }
90
+ export class SnapsStructError extends StructError {
91
+ constructor(struct, prefix, suffix, failure, failures){
92
+ super(failure, failures);
93
+ this.name = 'SnapsStructError';
94
+ this.message = `${prefix}.\n\n${getStructErrorMessage(struct, [
95
+ ...failures()
96
+ ])}${suffix ? `\n\n${suffix}` : ''}`;
97
+ }
98
+ }
99
+ /**
100
+ * Converts an array to a generator function that yields the items in the
101
+ * array.
102
+ *
103
+ * @param array - The array.
104
+ * @returns A generator function.
105
+ * @yields The items in the array.
106
+ */ export function* arrayToGenerator(array) {
107
+ for (const item of array){
108
+ yield item;
109
+ }
110
+ }
111
+ /**
112
+ * Returns a `SnapsStructError` with the given prefix and suffix.
113
+ *
114
+ * @param options - The options.
115
+ * @param options.struct - The struct that caused the error.
116
+ * @param options.prefix - The prefix to add to the error message.
117
+ * @param options.suffix - The suffix to add to the error message. Defaults to
118
+ * an empty string.
119
+ * @param options.error - The `superstruct` error to wrap.
120
+ * @returns The `SnapsStructError`.
121
+ */ export function getError({ struct, prefix, suffix = '', error }) {
122
+ return new SnapsStructError(struct, prefix, suffix, error, ()=>arrayToGenerator(error.failures()));
123
+ }
124
+ /**
125
+ * A wrapper of `superstruct`'s `create` function that throws a
126
+ * `SnapsStructError` instead of a `StructError`. This is useful for improving
127
+ * the error messages returned by `superstruct`.
128
+ *
129
+ * @param value - The value to validate.
130
+ * @param struct - The `superstruct` struct to validate the value against.
131
+ * @param prefix - The prefix to add to the error message.
132
+ * @param suffix - The suffix to add to the error message. Defaults to an empty
133
+ * string.
134
+ * @returns The validated value.
135
+ */ export function createFromStruct(value, struct, prefix, suffix = '') {
136
+ try {
137
+ return create(value, struct);
138
+ } catch (error) {
139
+ if (error instanceof StructError) {
140
+ throw getError({
141
+ struct,
142
+ prefix,
143
+ suffix,
144
+ error
145
+ });
146
+ }
147
+ throw error;
148
+ }
149
+ }
150
+ /**
151
+ * Get a struct from a failure path.
152
+ *
153
+ * @param struct - The struct.
154
+ * @param path - The failure path.
155
+ * @returns The struct at the failure path.
156
+ */ export function getStructFromPath(struct, path) {
157
+ return path.reduce((result, key)=>{
158
+ if (isObject(struct.schema) && struct.schema[key]) {
159
+ return struct.schema[key];
160
+ }
161
+ return result;
162
+ }, struct);
163
+ }
164
+ /**
165
+ * Get the union struct names from a struct.
166
+ *
167
+ * @param struct - The struct.
168
+ * @returns The union struct names, or `null` if the struct is not a union
169
+ * struct.
170
+ */ export function getUnionStructNames(struct) {
171
+ if (Array.isArray(struct.schema)) {
172
+ return struct.schema.map(({ type })=>green(type));
173
+ }
174
+ return null;
175
+ }
176
+ /**
177
+ * Get a error prefix from a `superstruct` failure. This is useful for
178
+ * formatting the error message returned by `superstruct`.
179
+ *
180
+ * @param failure - The `superstruct` failure.
181
+ * @returns The error prefix.
182
+ */ export function getStructErrorPrefix(failure) {
183
+ if (failure.type === 'never' || failure.path.length === 0) {
184
+ return '';
185
+ }
186
+ return `At path: ${bold(failure.path.join('.'))} — `;
187
+ }
188
+ /**
189
+ * Get a string describing the failure. This is similar to the `message`
190
+ * property of `superstruct`'s `Failure` type, but formats the value in a more
191
+ * readable way.
192
+ *
193
+ * @param struct - The struct that caused the failure.
194
+ * @param failure - The `superstruct` failure.
195
+ * @returns A string describing the failure.
196
+ */ export function getStructFailureMessage(struct, failure) {
197
+ const received = red(JSON.stringify(failure.value));
198
+ const prefix = getStructErrorPrefix(failure);
199
+ if (failure.type === 'union') {
200
+ const childStruct = getStructFromPath(struct, failure.path);
201
+ const unionNames = getUnionStructNames(childStruct);
202
+ if (unionNames) {
203
+ return `${prefix}Expected the value to be one of: ${unionNames.join(', ')}, but received: ${received}.`;
204
+ }
205
+ return `${prefix}${failure.message}.`;
206
+ }
207
+ if (failure.type === 'literal') {
208
+ // Superstruct's failure does not provide information about which literal
209
+ // value was expected, so we need to parse the message to get the literal.
210
+ const message = failure.message.replace(/the literal `(.+)`,/u, `the value to be \`${green('$1')}\`,`).replace(/, but received: (.+)/u, `, but received: ${red('$1')}`);
211
+ return `${prefix}${message}.`;
212
+ }
213
+ if (failure.type === 'never') {
214
+ return `Unknown key: ${bold(failure.path.join('.'))}, received: ${received}.`;
215
+ }
216
+ return `${prefix}Expected a value of type ${green(failure.type)}, but received: ${received}.`;
217
+ }
218
+ /**
219
+ * Get a string describing the errors. This formats all the errors in a
220
+ * human-readable way.
221
+ *
222
+ * @param struct - The struct that caused the failures.
223
+ * @param failures - The `superstruct` failures.
224
+ * @returns A string describing the errors.
225
+ */ export function getStructErrorMessage(struct, failures) {
226
+ const formattedFailures = failures.map((failure)=>indent(`• ${getStructFailureMessage(struct, failure)}`));
227
+ return formattedFailures.join('\n');
228
+ }
229
+
230
+ //# sourceMappingURL=structs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/structs.ts"],"sourcesContent":["import { isObject } from '@metamask/utils';\nimport { bold, green, red } from 'chalk';\nimport { resolve } from 'path';\nimport type { Failure, Infer } from 'superstruct';\nimport {\n Struct,\n StructError,\n define,\n literal as superstructLiteral,\n union as superstructUnion,\n create,\n string,\n coerce,\n} from 'superstruct';\nimport type { AnyStruct, InferStructTuple } from 'superstruct/dist/utils';\n\nimport { indent } from './strings';\n\n/**\n * A wrapper of `superstruct`'s `literal` struct that also defines the name of\n * the struct as the literal value.\n *\n * This is useful for improving the error messages returned by `superstruct`.\n * For example, instead of returning an error like:\n *\n * ```\n * Expected the value to satisfy a union of `literal | literal`, but received: \\\"baz\\\"\n * ```\n *\n * This struct will return an error like:\n *\n * ```\n * Expected the value to satisfy a union of `\"foo\" | \"bar\"`, but received: \\\"baz\\\"\n * ```\n *\n * @param value - The literal value.\n * @returns The `superstruct` struct, which validates that the value is equal\n * to the literal value.\n */\nexport function literal<Type extends string | number | boolean>(value: Type) {\n return define<Type>(\n JSON.stringify(value),\n superstructLiteral(value).validator,\n );\n}\n\n/**\n * A wrapper of `superstruct`'s `union` struct that also defines the schema as\n * the union of the schemas of the structs.\n *\n * This is useful for improving the error messages returned by `superstruct`.\n *\n * @param structs - The structs to union.\n * @param structs.\"0\" - The first struct.\n * @param structs.\"1\" - The remaining structs.\n * @returns The `superstruct` struct, which validates that the value satisfies\n * one of the structs.\n */\nexport function union<Head extends AnyStruct, Tail extends AnyStruct[]>([\n head,\n ...tail\n]: [head: Head, ...tail: Tail]): Struct<\n Infer<Head> | InferStructTuple<Tail>[number],\n [head: Head, ...tail: Tail]\n> {\n const struct = superstructUnion([head, ...tail]);\n\n return new Struct({\n ...struct,\n schema: [head, ...tail],\n });\n}\n\n/**\n * A wrapper of `superstruct`'s `string` struct that coerces a value to a string\n * and resolves it relative to the current working directory. This is useful\n * for specifying file paths in a configuration file, as it allows the user to\n * use both relative and absolute paths.\n *\n * @returns The `superstruct` struct, which validates that the value is a\n * string, and resolves it relative to the current working directory.\n * @example\n * ```ts\n * const config = struct({\n * file: file(),\n * // ...\n * });\n *\n * const value = create({ file: 'path/to/file' }, config);\n * console.log(value.file); // /process/cwd/path/to/file\n * ```\n */\nexport function file() {\n return coerce(string(), string(), (value) => {\n return resolve(process.cwd(), value);\n });\n}\n\n/**\n * Define a struct, and also define the name of the struct as the given name.\n *\n * This is useful for improving the error messages returned by `superstruct`.\n *\n * @param name - The name of the struct.\n * @param struct - The struct.\n * @returns The struct.\n */\nexport function named<Type, Schema>(\n name: string,\n struct: Struct<Type, Schema>,\n) {\n return new Struct({\n ...struct,\n type: name,\n });\n}\n\nexport class SnapsStructError<Type, Schema> extends StructError {\n constructor(\n struct: Struct<Type, Schema>,\n prefix: string,\n suffix: string,\n failure: StructError,\n failures: () => Generator<Failure>,\n ) {\n super(failure, failures);\n\n this.name = 'SnapsStructError';\n this.message = `${prefix}.\\n\\n${getStructErrorMessage(struct, [\n ...failures(),\n ])}${suffix ? `\\n\\n${suffix}` : ''}`;\n }\n}\n\ntype GetErrorOptions<Type, Schema> = {\n struct: Struct<Type, Schema>;\n prefix: string;\n suffix?: string;\n error: StructError;\n};\n\n/**\n * Converts an array to a generator function that yields the items in the\n * array.\n *\n * @param array - The array.\n * @returns A generator function.\n * @yields The items in the array.\n */\nexport function* arrayToGenerator<Type>(\n array: Type[],\n): Generator<Type, void, undefined> {\n for (const item of array) {\n yield item;\n }\n}\n\n/**\n * Returns a `SnapsStructError` with the given prefix and suffix.\n *\n * @param options - The options.\n * @param options.struct - The struct that caused the error.\n * @param options.prefix - The prefix to add to the error message.\n * @param options.suffix - The suffix to add to the error message. Defaults to\n * an empty string.\n * @param options.error - The `superstruct` error to wrap.\n * @returns The `SnapsStructError`.\n */\nexport function getError<Type, Schema>({\n struct,\n prefix,\n suffix = '',\n error,\n}: GetErrorOptions<Type, Schema>) {\n return new SnapsStructError(struct, prefix, suffix, error, () =>\n arrayToGenerator(error.failures()),\n );\n}\n\n/**\n * A wrapper of `superstruct`'s `create` function that throws a\n * `SnapsStructError` instead of a `StructError`. This is useful for improving\n * the error messages returned by `superstruct`.\n *\n * @param value - The value to validate.\n * @param struct - The `superstruct` struct to validate the value against.\n * @param prefix - The prefix to add to the error message.\n * @param suffix - The suffix to add to the error message. Defaults to an empty\n * string.\n * @returns The validated value.\n */\nexport function createFromStruct<Type, Schema>(\n value: unknown,\n struct: Struct<Type, Schema>,\n prefix: string,\n suffix = '',\n) {\n try {\n return create(value, struct);\n } catch (error) {\n if (error instanceof StructError) {\n throw getError({ struct, prefix, suffix, error });\n }\n\n throw error;\n }\n}\n\n/**\n * Get a struct from a failure path.\n *\n * @param struct - The struct.\n * @param path - The failure path.\n * @returns The struct at the failure path.\n */\nexport function getStructFromPath<Type, Schema>(\n struct: Struct<Type, Schema>,\n path: string[],\n) {\n return path.reduce<AnyStruct>((result, key) => {\n if (isObject(struct.schema) && struct.schema[key]) {\n return struct.schema[key] as AnyStruct;\n }\n\n return result;\n }, struct);\n}\n\n/**\n * Get the union struct names from a struct.\n *\n * @param struct - The struct.\n * @returns The union struct names, or `null` if the struct is not a union\n * struct.\n */\nexport function getUnionStructNames<Type, Schema>(\n struct: Struct<Type, Schema>,\n) {\n if (Array.isArray(struct.schema)) {\n return struct.schema.map(({ type }) => green(type));\n }\n\n return null;\n}\n\n/**\n * Get a error prefix from a `superstruct` failure. This is useful for\n * formatting the error message returned by `superstruct`.\n *\n * @param failure - The `superstruct` failure.\n * @returns The error prefix.\n */\nexport function getStructErrorPrefix(failure: Failure) {\n if (failure.type === 'never' || failure.path.length === 0) {\n return '';\n }\n\n return `At path: ${bold(failure.path.join('.'))} — `;\n}\n\n/**\n * Get a string describing the failure. This is similar to the `message`\n * property of `superstruct`'s `Failure` type, but formats the value in a more\n * readable way.\n *\n * @param struct - The struct that caused the failure.\n * @param failure - The `superstruct` failure.\n * @returns A string describing the failure.\n */\nexport function getStructFailureMessage<Type, Schema>(\n struct: Struct<Type, Schema>,\n failure: Failure,\n) {\n const received = red(JSON.stringify(failure.value));\n const prefix = getStructErrorPrefix(failure);\n\n if (failure.type === 'union') {\n const childStruct = getStructFromPath(struct, failure.path);\n const unionNames = getUnionStructNames(childStruct);\n\n if (unionNames) {\n return `${prefix}Expected the value to be one of: ${unionNames.join(\n ', ',\n )}, but received: ${received}.`;\n }\n\n return `${prefix}${failure.message}.`;\n }\n\n if (failure.type === 'literal') {\n // Superstruct's failure does not provide information about which literal\n // value was expected, so we need to parse the message to get the literal.\n const message = failure.message\n .replace(/the literal `(.+)`,/u, `the value to be \\`${green('$1')}\\`,`)\n .replace(/, but received: (.+)/u, `, but received: ${red('$1')}`);\n\n return `${prefix}${message}.`;\n }\n\n if (failure.type === 'never') {\n return `Unknown key: ${bold(\n failure.path.join('.'),\n )}, received: ${received}.`;\n }\n\n return `${prefix}Expected a value of type ${green(\n failure.type,\n )}, but received: ${received}.`;\n}\n\n/**\n * Get a string describing the errors. This formats all the errors in a\n * human-readable way.\n *\n * @param struct - The struct that caused the failures.\n * @param failures - The `superstruct` failures.\n * @returns A string describing the errors.\n */\nexport function getStructErrorMessage<Type, Schema>(\n struct: Struct<Type, Schema>,\n failures: Failure[],\n) {\n const formattedFailures = failures.map((failure) =>\n indent(`• ${getStructFailureMessage(struct, failure)}`),\n );\n\n return formattedFailures.join('\\n');\n}\n"],"names":["isObject","bold","green","red","resolve","Struct","StructError","define","literal","superstructLiteral","union","superstructUnion","create","string","coerce","indent","value","JSON","stringify","validator","head","tail","struct","schema","file","process","cwd","named","name","type","SnapsStructError","constructor","prefix","suffix","failure","failures","message","getStructErrorMessage","arrayToGenerator","array","item","getError","error","createFromStruct","getStructFromPath","path","reduce","result","key","getUnionStructNames","Array","isArray","map","getStructErrorPrefix","length","join","getStructFailureMessage","received","childStruct","unionNames","replace","formattedFailures"],"mappings":"AAAA,SAASA,QAAQ,QAAQ,kBAAkB;AAC3C,SAASC,IAAI,EAAEC,KAAK,EAAEC,GAAG,QAAQ,QAAQ;AACzC,SAASC,OAAO,QAAQ,OAAO;AAE/B,SACEC,MAAM,EACNC,WAAW,EACXC,MAAM,EACNC,WAAWC,kBAAkB,EAC7BC,SAASC,gBAAgB,EACzBC,MAAM,EACNC,MAAM,EACNC,MAAM,QACD,cAAc;AAGrB,SAASC,MAAM,QAAQ,YAAY;AAEnC;;;;;;;;;;;;;;;;;;;;CAoBC,GACD,OAAO,SAASP,QAAgDQ,KAAW;IACzE,OAAOT,OACLU,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QW,IAAI;QAC1D,MAAMc,aAAaV,oBAAoBS;QAEvC,IAAIC,YAAY;YACd,OAAO,CAAC,EAAE3B,OAAO,iCAAiC,EAAE2B,WAAWJ,IAAI,CACjE,MACA,gBAAgB,EAAEE,SAAS,CAAC,CAAC;QACjC;QAEA,OAAO,CAAC,EAAEzB,OAAO,EAAEE,QAAQE,OAAO,CAAC,CAAC,CAAC;IACvC;IAEA,IAAIF,QAAQL,IAAI,KAAK,WAAW;QAC9B,yEAAyE;QACzE,0EAA0E;QAC1E,MAAMO,UAAUF,QAAQE,OAAO,CAC5BwB,OAAO,CAAC,wBAAwB,CAAC,kBAAkB,EAAE1D,MAAM,MAAM,GAAG,CAAC,EACrE0D,OAAO,CAAC,yBAAyB,CAAC,gBAAgB,EAAEzD,IAAI,MAAM,CAAC;QAElE,OAAO,CAAC,EAAE6B,OAAO,EAAEI,QAAQ,CAAC,CAAC;IAC/B;IAEA,IAAIF,QAAQL,IAAI,KAAK,SAAS;QAC5B,OAAO,CAAC,aAAa,EAAE5B,KACrBiC,QAAQW,IAAI,CAACU,IAAI,CAAC,MAClB,YAAY,EAAEE,SAAS,CAAC,CAAC;IAC7B;IAEA,OAAO,CAAC,EAAEzB,OAAO,yBAAyB,EAAE9B,MAC1CgC,QAAQL,IAAI,EACZ,gBAAgB,EAAE4B,SAAS,CAAC,CAAC;AACjC;AAEA;;;;;;;CAOC,GACD,OAAO,SAASpB,sBACdf,MAA4B,EAC5Ba,QAAmB;IAEnB,MAAM0B,oBAAoB1B,SAASiB,GAAG,CAAC,CAAClB,UACtCnB,OAAO,CAAC,EAAE,EAAEyC,wBAAwBlC,QAAQY,SAAS,CAAC;IAGxD,OAAO2B,kBAAkBN,IAAI,CAAC;AAChC"}
@@ -27,4 +27,4 @@ export declare type EnumToUnion<Type extends string> = `${Type}`;
27
27
  * @param constant - The enum to validate against.
28
28
  * @returns The superstruct struct.
29
29
  */
30
- export declare function enumValue<Type extends string>(constant: Type): Struct<EnumToUnion<Type>, EnumToUnion<Type>>;
30
+ export declare function enumValue<Type extends string>(constant: Type): Struct<EnumToUnion<Type>, null>;
@@ -1,3 +1,11 @@
1
+ export declare type EvalOutput = {
2
+ stdout: string;
3
+ stderr: string;
4
+ };
5
+ export declare class SnapEvalError extends Error {
6
+ readonly output: EvalOutput;
7
+ constructor(message: string, output: EvalOutput);
8
+ }
1
9
  /**
2
10
  * Spawn a new process to run the provided bundle in.
3
11
  *
@@ -5,4 +13,4 @@
5
13
  * @returns `null` if the worker ran successfully.
6
14
  * @throws If the worker failed to run successfully.
7
15
  */
8
- export declare function evalBundle(bundlePath: string): Promise<null>;
16
+ export declare function evalBundle(bundlePath: string): Promise<EvalOutput>;
@@ -15,6 +15,8 @@ export * from './manifest/index.browser';
15
15
  export * from './namespace';
16
16
  export * from './path';
17
17
  export * from './snaps';
18
+ export * from './strings';
19
+ export * from './structs';
18
20
  export * from './types';
19
21
  export * from './validation';
20
22
  export * from './versions';
@@ -20,6 +20,8 @@ export * from './npm';
20
20
  export * from './path';
21
21
  export * from './post-process';
22
22
  export * from './snaps';
23
+ export * from './strings';
24
+ export * from './structs';
23
25
  export * from './types';
24
26
  export * from './validation';
25
27
  export * from './versions';
@@ -23,6 +23,7 @@ export declare type CheckManifestResult = {
23
23
  warnings: string[];
24
24
  errors: string[];
25
25
  };
26
+ export declare type WriteFileFunction = (path: string, data: string) => Promise<void>;
26
27
  /**
27
28
  * Validates a snap.manifest.json file. Attempts to fix the manifest and write
28
29
  * the fixed version to disk if `writeManifest` is true. Throws if validation
@@ -31,10 +32,11 @@ export declare type CheckManifestResult = {
31
32
  * @param basePath - The path to the folder with the manifest files.
32
33
  * @param writeManifest - Whether to write the fixed manifest to disk.
33
34
  * @param sourceCode - The source code of the Snap.
35
+ * @param writeFileFn - The function to use to write the manifest to disk.
34
36
  * @returns Whether the manifest was updated, and an array of warnings that
35
37
  * were encountered during processing of the manifest files.
36
38
  */
37
- export declare function checkManifest(basePath: string, writeManifest?: boolean, sourceCode?: string): Promise<CheckManifestResult>;
39
+ export declare function checkManifest(basePath: string, writeManifest?: boolean, sourceCode?: string, writeFileFn?: WriteFileFunction): Promise<CheckManifestResult>;
38
40
  /**
39
41
  * Given the relevant Snap files (manifest, `package.json`, and bundle) and a
40
42
  * Snap manifest validation error, fixes the fault in the manifest that caused
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Indent a message by adding a number of spaces to the beginning of each line.
3
+ *
4
+ * @param message - The message to indent.
5
+ * @param spaces - The number of spaces to indent by. Defaults to 2.
6
+ * @returns The indented message.
7
+ */
8
+ export declare function indent(message: string, spaces?: number): string;
@@ -0,0 +1,158 @@
1
+ import type { Failure, Infer } from 'superstruct';
2
+ import { Struct, StructError } from 'superstruct';
3
+ import type { AnyStruct, InferStructTuple } from 'superstruct/dist/utils';
4
+ /**
5
+ * A wrapper of `superstruct`'s `literal` struct that also defines the name of
6
+ * the struct as the literal value.
7
+ *
8
+ * This is useful for improving the error messages returned by `superstruct`.
9
+ * For example, instead of returning an error like:
10
+ *
11
+ * ```
12
+ * Expected the value to satisfy a union of `literal | literal`, but received: \"baz\"
13
+ * ```
14
+ *
15
+ * This struct will return an error like:
16
+ *
17
+ * ```
18
+ * Expected the value to satisfy a union of `"foo" | "bar"`, but received: \"baz\"
19
+ * ```
20
+ *
21
+ * @param value - The literal value.
22
+ * @returns The `superstruct` struct, which validates that the value is equal
23
+ * to the literal value.
24
+ */
25
+ export declare function literal<Type extends string | number | boolean>(value: Type): Struct<Type, null>;
26
+ /**
27
+ * A wrapper of `superstruct`'s `union` struct that also defines the schema as
28
+ * the union of the schemas of the structs.
29
+ *
30
+ * This is useful for improving the error messages returned by `superstruct`.
31
+ *
32
+ * @param structs - The structs to union.
33
+ * @param structs."0" - The first struct.
34
+ * @param structs."1" - The remaining structs.
35
+ * @returns The `superstruct` struct, which validates that the value satisfies
36
+ * one of the structs.
37
+ */
38
+ export declare function union<Head extends AnyStruct, Tail extends AnyStruct[]>([head, ...tail]: [head: Head, ...tail: Tail]): Struct<Infer<Head> | InferStructTuple<Tail>[number], [
39
+ head: Head,
40
+ ...tail: Tail
41
+ ]>;
42
+ /**
43
+ * A wrapper of `superstruct`'s `string` struct that coerces a value to a string
44
+ * and resolves it relative to the current working directory. This is useful
45
+ * for specifying file paths in a configuration file, as it allows the user to
46
+ * use both relative and absolute paths.
47
+ *
48
+ * @returns The `superstruct` struct, which validates that the value is a
49
+ * string, and resolves it relative to the current working directory.
50
+ * @example
51
+ * ```ts
52
+ * const config = struct({
53
+ * file: file(),
54
+ * // ...
55
+ * });
56
+ *
57
+ * const value = create({ file: 'path/to/file' }, config);
58
+ * console.log(value.file); // /process/cwd/path/to/file
59
+ * ```
60
+ */
61
+ export declare function file(): Struct<string, null>;
62
+ /**
63
+ * Define a struct, and also define the name of the struct as the given name.
64
+ *
65
+ * This is useful for improving the error messages returned by `superstruct`.
66
+ *
67
+ * @param name - The name of the struct.
68
+ * @param struct - The struct.
69
+ * @returns The struct.
70
+ */
71
+ export declare function named<Type, Schema>(name: string, struct: Struct<Type, Schema>): Struct<Type, Schema>;
72
+ export declare class SnapsStructError<Type, Schema> extends StructError {
73
+ constructor(struct: Struct<Type, Schema>, prefix: string, suffix: string, failure: StructError, failures: () => Generator<Failure>);
74
+ }
75
+ declare type GetErrorOptions<Type, Schema> = {
76
+ struct: Struct<Type, Schema>;
77
+ prefix: string;
78
+ suffix?: string;
79
+ error: StructError;
80
+ };
81
+ /**
82
+ * Converts an array to a generator function that yields the items in the
83
+ * array.
84
+ *
85
+ * @param array - The array.
86
+ * @returns A generator function.
87
+ * @yields The items in the array.
88
+ */
89
+ export declare function arrayToGenerator<Type>(array: Type[]): Generator<Type, void, undefined>;
90
+ /**
91
+ * Returns a `SnapsStructError` with the given prefix and suffix.
92
+ *
93
+ * @param options - The options.
94
+ * @param options.struct - The struct that caused the error.
95
+ * @param options.prefix - The prefix to add to the error message.
96
+ * @param options.suffix - The suffix to add to the error message. Defaults to
97
+ * an empty string.
98
+ * @param options.error - The `superstruct` error to wrap.
99
+ * @returns The `SnapsStructError`.
100
+ */
101
+ export declare function getError<Type, Schema>({ struct, prefix, suffix, error, }: GetErrorOptions<Type, Schema>): SnapsStructError<Type, Schema>;
102
+ /**
103
+ * A wrapper of `superstruct`'s `create` function that throws a
104
+ * `SnapsStructError` instead of a `StructError`. This is useful for improving
105
+ * the error messages returned by `superstruct`.
106
+ *
107
+ * @param value - The value to validate.
108
+ * @param struct - The `superstruct` struct to validate the value against.
109
+ * @param prefix - The prefix to add to the error message.
110
+ * @param suffix - The suffix to add to the error message. Defaults to an empty
111
+ * string.
112
+ * @returns The validated value.
113
+ */
114
+ export declare function createFromStruct<Type, Schema>(value: unknown, struct: Struct<Type, Schema>, prefix: string, suffix?: string): Type;
115
+ /**
116
+ * Get a struct from a failure path.
117
+ *
118
+ * @param struct - The struct.
119
+ * @param path - The failure path.
120
+ * @returns The struct at the failure path.
121
+ */
122
+ export declare function getStructFromPath<Type, Schema>(struct: Struct<Type, Schema>, path: string[]): AnyStruct;
123
+ /**
124
+ * Get the union struct names from a struct.
125
+ *
126
+ * @param struct - The struct.
127
+ * @returns The union struct names, or `null` if the struct is not a union
128
+ * struct.
129
+ */
130
+ export declare function getUnionStructNames<Type, Schema>(struct: Struct<Type, Schema>): string[] | null;
131
+ /**
132
+ * Get a error prefix from a `superstruct` failure. This is useful for
133
+ * formatting the error message returned by `superstruct`.
134
+ *
135
+ * @param failure - The `superstruct` failure.
136
+ * @returns The error prefix.
137
+ */
138
+ export declare function getStructErrorPrefix(failure: Failure): string;
139
+ /**
140
+ * Get a string describing the failure. This is similar to the `message`
141
+ * property of `superstruct`'s `Failure` type, but formats the value in a more
142
+ * readable way.
143
+ *
144
+ * @param struct - The struct that caused the failure.
145
+ * @param failure - The `superstruct` failure.
146
+ * @returns A string describing the failure.
147
+ */
148
+ export declare function getStructFailureMessage<Type, Schema>(struct: Struct<Type, Schema>, failure: Failure): string;
149
+ /**
150
+ * Get a string describing the errors. This formats all the errors in a
151
+ * human-readable way.
152
+ *
153
+ * @param struct - The struct that caused the failures.
154
+ * @param failures - The `superstruct` failures.
155
+ * @returns A string describing the errors.
156
+ */
157
+ export declare function getStructErrorMessage<Type, Schema>(struct: Struct<Type, Schema>, failures: Failure[]): string;
158
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask/snaps-utils",
3
- "version": "0.37.1-flask.1",
3
+ "version": "0.37.2-flask.1",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/MetaMask/snaps.git"
@@ -52,7 +52,7 @@
52
52
  "lint:misc": "prettier --no-error-on-unmatched-pattern --loglevel warn \"**/*.json\" \"**/*.md\" \"**/*.html\" \"!CHANGELOG.md\" --ignore-path ../../.gitignore",
53
53
  "lint": "yarn lint:eslint && yarn lint:misc --check && yarn lint:changelog",
54
54
  "lint:fix": "yarn lint:eslint --fix && yarn lint:misc --write",
55
- "lint:changelog": "yarn auto-changelog validate",
55
+ "lint:changelog": "../../scripts/validate-changelog.sh @metamask/snaps-utils",
56
56
  "build": "yarn build:source && yarn build:types",
57
57
  "build:source": "yarn build:esm && yarn build:cjs",
58
58
  "build:types": "tsc --project tsconfig.build.json",
@@ -72,10 +72,11 @@
72
72
  "@metamask/permission-controller": "^4.0.0",
73
73
  "@metamask/providers": "^11.0.0",
74
74
  "@metamask/snaps-registry": "^1.2.1",
75
- "@metamask/snaps-ui": "^0.37.1-flask.1",
75
+ "@metamask/snaps-ui": "^0.37.2-flask.1",
76
76
  "@metamask/utils": "^6.0.1",
77
77
  "@noble/hashes": "^1.3.1",
78
78
  "@scure/base": "^1.1.1",
79
+ "chalk": "^4.1.2",
79
80
  "cron-parser": "^4.5.0",
80
81
  "eth-rpc-errors": "^4.0.3",
81
82
  "fast-deep-equal": "^3.1.3",