@metamask/snaps-controllers 0.24.1 → 0.25.0
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/dist/cronjob/CronjobController.d.ts +3 -2
- package/dist/cronjob/CronjobController.js +37 -23
- package/dist/cronjob/CronjobController.js.map +1 -1
- package/dist/fsm.js +1 -1
- package/dist/fsm.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js.map +1 -1
- package/dist/multichain/MultiChainController.d.ts +3 -1
- package/dist/multichain/MultiChainController.js +8 -8
- package/dist/multichain/MultiChainController.js.map +1 -1
- package/dist/multichain/middleware.d.ts +1 -1
- package/dist/multichain/middleware.js +2 -2
- package/dist/multichain/middleware.js.map +1 -1
- package/dist/services/AbstractExecutionService.d.ts +3 -3
- package/dist/services/AbstractExecutionService.js +13 -12
- package/dist/services/AbstractExecutionService.js.map +1 -1
- package/dist/services/ExecutionService.d.ts +1 -1
- package/dist/services/ExecutionService.js.map +1 -1
- package/dist/services/iframe/IframeExecutionService.js +1 -1
- package/dist/services/iframe/IframeExecutionService.js.map +1 -1
- package/dist/services/iframe/test/server.js +6 -6
- package/dist/services/iframe/test/server.js.map +1 -1
- package/dist/services/node/NodeProcessExecutionService.d.ts +1 -1
- package/dist/services/node/NodeProcessExecutionService.js +2 -2
- package/dist/services/node/NodeProcessExecutionService.js.map +1 -1
- package/dist/services/node/NodeThreadExecutionService.d.ts +2 -2
- package/dist/services/node/NodeThreadExecutionService.js +5 -4
- package/dist/services/node/NodeThreadExecutionService.js.map +1 -1
- package/dist/snaps/SnapController.d.ts +18 -16
- package/dist/snaps/SnapController.js +104 -87
- package/dist/snaps/SnapController.js.map +1 -1
- package/dist/snaps/endowments/cronjob.d.ts +2 -2
- package/dist/snaps/endowments/cronjob.js +3 -3
- package/dist/snaps/endowments/cronjob.js.map +1 -1
- package/dist/snaps/endowments/enum.d.ts +2 -1
- package/dist/snaps/endowments/enum.js +1 -0
- package/dist/snaps/endowments/enum.js.map +1 -1
- package/dist/snaps/endowments/ethereum-provider.d.ts +1 -1
- package/dist/snaps/endowments/ethereum-provider.js +2 -2
- package/dist/snaps/endowments/ethereum-provider.js.map +1 -1
- package/dist/snaps/endowments/index.d.ts +33 -19
- package/dist/snaps/endowments/index.js +16 -4
- package/dist/snaps/endowments/index.js.map +1 -1
- package/dist/snaps/endowments/keyring.d.ts +1 -1
- package/dist/snaps/endowments/keyring.js +2 -2
- package/dist/snaps/endowments/keyring.js.map +1 -1
- package/dist/snaps/endowments/long-running.d.ts +1 -1
- package/dist/snaps/endowments/long-running.js +2 -2
- package/dist/snaps/endowments/long-running.js.map +1 -1
- package/dist/snaps/endowments/network-access.d.ts +1 -1
- package/dist/snaps/endowments/network-access.js +2 -2
- package/dist/snaps/endowments/network-access.js.map +1 -1
- package/dist/snaps/endowments/rpc.d.ts +35 -0
- package/dist/snaps/endowments/rpc.js +91 -0
- package/dist/snaps/endowments/rpc.js.map +1 -0
- package/dist/snaps/endowments/transaction-insight.d.ts +3 -3
- package/dist/snaps/endowments/transaction-insight.js +3 -3
- package/dist/snaps/endowments/transaction-insight.js.map +1 -1
- package/dist/snaps/utils/npm.d.ts +2 -2
- package/dist/snaps/utils/npm.js +7 -3
- package/dist/snaps/utils/npm.js.map +1 -1
- package/dist/snaps/utils/stream.d.ts +1 -1
- package/dist/snaps/utils/stream.js +3 -3
- package/dist/snaps/utils/stream.js.map +1 -1
- package/dist/utils.d.ts +3 -3
- package/dist/utils.js.map +1 -1
- package/package.json +25 -20
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transaction-insight.js","sourceRoot":"","sources":["../../../src/snaps/endowments/transaction-insight.ts"],"names":[],"mappings":";;;AAAA,
|
|
1
|
+
{"version":3,"file":"transaction-insight.js","sourceRoot":"","sources":["../../../src/snaps/endowments/transaction-insight.ts"],"names":[],"mappings":";;;AAAA,2EASyC;AACzC,uDAAuD;AACvD,2CAOyB;AACzB,mDAA2C;AAE3C,iCAA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AAE,CAAC,MAA2B,EAAE,EAAE,CAAC,cAAc,CAAC,MAAM,CAAC;KACnE,CAAC;CACH,CAAC","sourcesContent":["import {\n PermissionSpecificationBuilder,\n PermissionType,\n EndowmentGetterParams,\n ValidPermissionSpecification,\n PermissionValidatorConstraint,\n PermissionConstraint,\n CaveatSpecificationConstraint,\n Caveat,\n} from '@metamask/permission-controller';\nimport { SnapCaveatType } from '@metamask/snaps-utils';\nimport {\n assert,\n hasProperty,\n isObject,\n isPlainObject,\n Json,\n NonEmptyArray,\n} from '@metamask/utils';\nimport { ethErrors } from 'eth-rpc-errors';\n\nimport { SnapEndowments } from './enum';\n\nconst permissionName = SnapEndowments.TransactionInsight;\n\ntype TransactionInsightEndowmentSpecification = ValidPermissionSpecification<{\n permissionType: PermissionType.Endowment;\n targetKey: typeof permissionName;\n endowmentGetter: (_options?: EndowmentGetterParams) => undefined;\n allowedCaveats: Readonly<NonEmptyArray<string>> | null;\n validator: PermissionValidatorConstraint;\n}>;\n\n/**\n * `endowment:transaction-insight` returns nothing; it is intended to be used as a flag\n * by the extension to detect whether the snap has the capability to show information on the transaction confirmation screen.\n *\n * @param _builderOptions - Optional specification builder options.\n * @returns The specification for the transaction-insight endowment.\n */\nconst specificationBuilder: PermissionSpecificationBuilder<\n PermissionType.Endowment,\n any,\n TransactionInsightEndowmentSpecification\n> = (_builderOptions?: unknown) => {\n return {\n permissionType: PermissionType.Endowment,\n targetKey: permissionName,\n allowedCaveats: [SnapCaveatType.TransactionOrigin],\n endowmentGetter: (_getterOptions?: EndowmentGetterParams) => undefined,\n validator: ({ caveats }) => {\n if (\n (caveats !== null && caveats?.length > 1) ||\n (caveats?.length === 1 &&\n caveats[0].type !== SnapCaveatType.TransactionOrigin)\n ) {\n throw ethErrors.rpc.invalidParams({\n message: `Expected a single \"${SnapCaveatType.TransactionOrigin}\" caveat.`,\n });\n }\n },\n };\n};\n\nexport const transactionInsightEndowmentBuilder = Object.freeze({\n targetKey: permissionName,\n specificationBuilder,\n} as const);\n\n/**\n * Validates the type of the caveat value.\n *\n * @param caveat - The caveat to validate.\n * @throws If the caveat value is invalid.\n */\nfunction validateCaveat(caveat: Caveat<string, any>): void {\n if (!hasProperty(caveat, 'value') || !isPlainObject(caveat)) {\n throw ethErrors.rpc.invalidParams({\n message: 'Expected a plain object.',\n });\n }\n\n const { value } = caveat;\n\n assert(\n typeof value === 'boolean',\n 'Expected caveat value to have type \"boolean\"',\n );\n}\n\n/**\n * Map a raw value from the `initialPermissions` to a caveat specification.\n * Note that this function does not do any validation, that's handled by the\n * PermissionsController when the permission is requested.\n *\n * @param value - The raw value from the `initialPermissions`.\n * @returns The caveat specification.\n */\nexport function getTransactionInsightCaveatMapper(\n value: Json,\n): Pick<PermissionConstraint, 'caveats'> {\n if (\n !value ||\n !isObject(value) ||\n (isObject(value) && Object.keys(value).length === 0)\n ) {\n return { caveats: null };\n }\n return {\n caveats: [\n {\n type: SnapCaveatType.TransactionOrigin,\n value:\n hasProperty(value, 'allowTransactionOrigin') &&\n value.allowTransactionOrigin,\n },\n ],\n };\n}\n\n/**\n * Getter function to get the transaction origin caveat from a permission.\n *\n * This does basic validation of the caveat, but does not validate the type or\n * value of the namespaces object itself, as this is handled by the\n * `PermissionsController` when the permission is requested.\n *\n * @param permission - The permission to get the transaction origin caveat from.\n * @returns The transaction origin, or `null` if the permission does not have a\n * transaction origin caveat.\n */\nexport function getTransactionOriginCaveat(\n permission?: PermissionConstraint,\n): boolean | null {\n if (!permission?.caveats) {\n return null;\n }\n\n assert(permission.caveats.length === 1);\n assert(permission.caveats[0].type === SnapCaveatType.TransactionOrigin);\n\n const caveat = permission.caveats[0] as Caveat<string, boolean>;\n\n return caveat.value ?? null;\n}\n\nexport const transactionInsightCaveatSpecifications: Record<\n SnapCaveatType.TransactionOrigin,\n CaveatSpecificationConstraint\n> = {\n [SnapCaveatType.TransactionOrigin]: Object.freeze({\n type: SnapCaveatType.TransactionOrigin,\n validator: (caveat: Caveat<string, any>) => validateCaveat(caveat),\n }),\n};\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { SnapFiles } from '@metamask/snaps-utils';
|
|
1
|
+
import { SnapFiles, SemVerRange } from '@metamask/snaps-utils';
|
|
2
2
|
export declare const DEFAULT_NPM_REGISTRY = "https://registry.npmjs.org";
|
|
3
3
|
/**
|
|
4
4
|
* Fetches a Snap from the public npm registry.
|
|
@@ -11,4 +11,4 @@ export declare const DEFAULT_NPM_REGISTRY = "https://registry.npmjs.org";
|
|
|
11
11
|
* {@link fetch}. Useful for Node.js compatibility.
|
|
12
12
|
* @returns A tuple of the Snap manifest object and the Snap source code.
|
|
13
13
|
*/
|
|
14
|
-
export declare function fetchNpmSnap(packageName: string, versionRange:
|
|
14
|
+
export declare function fetchNpmSnap(packageName: string, versionRange: SemVerRange, registryUrl?: string, fetchFunction?: typeof fetch): Promise<SnapFiles>;
|
package/dist/snaps/utils/npm.js
CHANGED
|
@@ -4,10 +4,10 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
6
|
exports.fetchNpmSnap = exports.DEFAULT_NPM_REGISTRY = void 0;
|
|
7
|
+
const snaps_utils_1 = require("@metamask/snaps-utils");
|
|
7
8
|
const utils_1 = require("@metamask/utils");
|
|
8
|
-
const pump_1 = __importDefault(require("pump"));
|
|
9
9
|
const gunzip_maybe_1 = __importDefault(require("gunzip-maybe"));
|
|
10
|
-
const
|
|
10
|
+
const pump_1 = __importDefault(require("pump"));
|
|
11
11
|
const stream_1 = require("./stream");
|
|
12
12
|
exports.DEFAULT_NPM_REGISTRY = 'https://registry.npmjs.org';
|
|
13
13
|
/**
|
|
@@ -57,7 +57,11 @@ async function fetchNpmTarball(packageName, versionRange, registryUrl = exports.
|
|
|
57
57
|
if (!(0, utils_1.isObject)(packageMetadata)) {
|
|
58
58
|
throw new Error(`Failed to fetch package "${packageName}" metadata from npm.`);
|
|
59
59
|
}
|
|
60
|
-
const
|
|
60
|
+
const versions = Object.keys((_a = packageMetadata === null || packageMetadata === void 0 ? void 0 : packageMetadata.versions) !== null && _a !== void 0 ? _a : {}).map((version) => {
|
|
61
|
+
(0, snaps_utils_1.assertIsSemVerVersion)(version);
|
|
62
|
+
return version;
|
|
63
|
+
});
|
|
64
|
+
const targetVersion = (0, snaps_utils_1.getTargetVersion)(versions, versionRange);
|
|
61
65
|
if (targetVersion === null) {
|
|
62
66
|
throw new Error(`Failed to find a matching version in npm metadata for package "${packageName}" and requested semver range "${versionRange}"`);
|
|
63
67
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"npm.js","sourceRoot":"","sources":["../../../src/snaps/utils/npm.ts"],"names":[],"mappings":";;;;;;AAAA,2CAA2C;AAC3C,
|
|
1
|
+
{"version":3,"file":"npm.js","sourceRoot":"","sources":["../../../src/snaps/utils/npm.ts"],"names":[],"mappings":";;;;;;AAAA,uDAS+B;AAC/B,2CAA2C;AAC3C,gEAA8C;AAC9C,gDAAwB;AAExB,qCAAwE;AAE3D,QAAA,oBAAoB,GAAG,4BAA4B,CAAC;AAEjE;;;;;;;;;;GAUG;AACI,KAAK,UAAU,YAAY,CAChC,WAAmB,EACnB,YAAyB,EACzB,WAAW,GAAG,4BAAoB,EAClC,aAAa,GAAG,KAAK;IAErB,MAAM,CAAC,eAAe,EAAE,aAAa,CAAC,GAAG,MAAM,eAAe,CAC5D,WAAW,EACX,YAAY,EACZ,WAAW,EACX,aAAa,CACd,CAAC;IAEF,2DAA2D;IAC3D,MAAM,SAAS,GAAyB,EAAE,CAAC;IAC3C,MAAM,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QAC1C,IAAA,cAAI,EACF,IAAA,sBAAa,EAAC,eAAe,CAAC;QAC9B,4EAA4E;QAC5E,iDAAiD;QACjD,IAAA,sBAAkB,GAAE,EACpB,IAAA,sCAA6B,EAAC,SAAS,CAAC,EACxC,CAAC,KAAK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0CACvE,IAAI,0CAAE,OAAO,CAAC;IAElB,IAAI,CAAC,IAAA,wBAAU,EAAC,gBAAgB,CAAC,IAAI,CAAC,gBAAgB,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE;QACvE,MAAM,IAAI,KAAK,CACb,iEAAiE,WAAW,IAAI,CACjF,CAAC;KACH;IAED,4EAA4E;IAC5E,MAAM,cAAc,GAAG,IAAI,GAAG,CAAC,WAAW,CAAC,CAAC;IAC5C,MAAM,aAAa,GAAG,IAAI,GAAG,CAAC,gBAAgB,CAAC,CAAC;IAChD,aAAa,CAAC,QAAQ,GAAG,cAAc,CAAC,QAAQ,CAAC;IACjD,aAAa,CAAC,QAAQ,GAAG,cAAc,CAAC,QAAQ,CAAC;IAEjD,kEAAkE;IAClE,MAAM,eAAe,GAAG,MAAM,aAAa,CAAC,aAAa,CAAC,QAAQ,EAAE,CAAC,CAAC;IACtE,IAAI,CAAC,eAAe,CAAC,EAAE,EAAE;QACvB,MAAM,IAAI,KAAK,CAAC,wCAAwC,WAAW,IAAI,CAAC,CAAC;KAC1E;IACD,MAAM,MAAM,GAAG,MAAM,eAAe,CAAC,IAAI,EAAE,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC;IAE1E,OAAO,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;AACjC,CAAC","sourcesContent":["import {\n SnapFiles,\n UnvalidatedSnapFiles,\n isValidUrl,\n getTargetVersion,\n validateNpmSnap,\n assertIsSemVerVersion,\n SemVerRange,\n SemVerVersion,\n} from '@metamask/snaps-utils';\nimport { isObject } from '@metamask/utils';\nimport createGunzipStream from 'gunzip-maybe';\nimport pump from 'pump';\n\nimport { createTarballExtractionStream, getNodeStream } from './stream';\n\nexport const DEFAULT_NPM_REGISTRY = 'https://registry.npmjs.org';\n\n/**\n * Fetches a Snap from the public npm registry.\n *\n * @param packageName - The name of the package whose tarball to fetch.\n * @param versionRange - The SemVer range of the package to fetch. The highest\n * version satisfying the range will be fetched.\n * @param registryUrl - The URL of the npm registry to fetch from.\n * @param fetchFunction - The fetch function to use. Defaults to the global\n * {@link fetch}. Useful for Node.js compatibility.\n * @returns A tuple of the Snap manifest object and the Snap source code.\n */\nexport async function fetchNpmSnap(\n packageName: string,\n versionRange: SemVerRange,\n registryUrl = DEFAULT_NPM_REGISTRY,\n fetchFunction = fetch,\n): Promise<SnapFiles> {\n const [tarballResponse, actualVersion] = await fetchNpmTarball(\n packageName,\n versionRange,\n registryUrl,\n fetchFunction,\n );\n\n // Extract the tarball and get the necessary files from it.\n const snapFiles: UnvalidatedSnapFiles = {};\n await new Promise<void>((resolve, reject) => {\n pump(\n getNodeStream(tarballResponse),\n // The \"gz\" in \"tgz\" stands for \"gzip\". The tarball needs to be decompressed\n // before we can actually grab any files from it.\n createGunzipStream(),\n createTarballExtractionStream(snapFiles),\n (error) => {\n error ? reject(error) : resolve();\n },\n );\n });\n\n // At this point, the necessary files will have been added to the snapFiles\n // object if they exist.\n return validateNpmSnap(\n snapFiles,\n `npm Snap \"${packageName}@${actualVersion}\" validation error: ` as `${string}: `,\n );\n}\n\n/**\n * Fetches the tarball (`.tgz` file) of the specified package and version from\n * the public npm registry. Throws an error if fetching fails.\n *\n * @param packageName - The name of the package whose tarball to fetch.\n * @param versionRange - The SemVer range of the package to fetch. The highest\n * version satisfying the range will be fetched.\n * @param registryUrl - The URL of the npm registry to fetch the tarball from.\n * @param fetchFunction - The fetch function to use. Defaults to the global\n * {@link fetch}. Useful for Node.js compatibility.\n * @returns A tuple of the {@link Response} for the package tarball and the\n * actual version of the package.\n */\nasync function fetchNpmTarball(\n packageName: string,\n versionRange: SemVerRange,\n registryUrl = DEFAULT_NPM_REGISTRY,\n fetchFunction = fetch,\n): Promise<[ReadableStream, SemVerVersion]> {\n const packageMetadata = await (\n await fetchFunction(new URL(packageName, registryUrl).toString())\n ).json();\n\n if (!isObject(packageMetadata)) {\n throw new Error(\n `Failed to fetch package \"${packageName}\" metadata from npm.`,\n );\n }\n\n const versions = Object.keys((packageMetadata as any)?.versions ?? {}).map(\n (version) => {\n assertIsSemVerVersion(version);\n return version;\n },\n );\n\n const targetVersion = getTargetVersion(versions, versionRange);\n\n if (targetVersion === null) {\n throw new Error(\n `Failed to find a matching version in npm metadata for package \"${packageName}\" and requested semver range \"${versionRange}\"`,\n );\n }\n\n const tarballUrlString = (packageMetadata as any).versions?.[targetVersion]\n ?.dist?.tarball;\n\n if (!isValidUrl(tarballUrlString) || !tarballUrlString.endsWith('.tgz')) {\n throw new Error(\n `Failed to find valid tarball URL in npm metadata for package \"${packageName}\".`,\n );\n }\n\n // Override the tarball hostname/protocol with registryUrl hostname/protocol\n const newRegistryUrl = new URL(registryUrl);\n const newTarballUrl = new URL(tarballUrlString);\n newTarballUrl.hostname = newRegistryUrl.hostname;\n newTarballUrl.protocol = newRegistryUrl.protocol;\n\n // Perform a raw fetch because we want the Response object itself.\n const tarballResponse = await fetchFunction(newTarballUrl.toString());\n if (!tarballResponse.ok) {\n throw new Error(`Failed to fetch tarball for package \"${packageName}\".`);\n }\n const stream = await tarballResponse.blob().then((blob) => blob.stream());\n\n return [stream, targetVersion];\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/// <reference types="node" />
|
|
2
|
-
import { Readable, Writable } from 'stream';
|
|
3
2
|
import { UnvalidatedSnapFiles } from '@metamask/snaps-utils';
|
|
3
|
+
import { Readable, Writable } from 'stream';
|
|
4
4
|
/**
|
|
5
5
|
* Strips the leading `./` from a string, or does nothing if no string is
|
|
6
6
|
* provided.
|
|
@@ -4,11 +4,11 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
6
|
exports.createTarballExtractionStream = exports.getNodeStream = exports.stripDotSlash = void 0;
|
|
7
|
+
const snaps_utils_1 = require("@metamask/snaps-utils");
|
|
8
|
+
const utils_1 = require("@metamask/utils");
|
|
9
|
+
const concat_stream_1 = __importDefault(require("concat-stream"));
|
|
7
10
|
const readable_web_to_node_stream_1 = require("readable-web-to-node-stream");
|
|
8
11
|
const tar_stream_1 = require("tar-stream");
|
|
9
|
-
const concat_stream_1 = __importDefault(require("concat-stream"));
|
|
10
|
-
const utils_1 = require("@metamask/utils");
|
|
11
|
-
const snaps_utils_1 = require("@metamask/snaps-utils");
|
|
12
12
|
// The paths of files within npm tarballs appear to always be prefixed with
|
|
13
13
|
// "package/".
|
|
14
14
|
const NPM_TARBALL_PATH_PREFIX = /^package\//u;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stream.js","sourceRoot":"","sources":["../../../src/snaps/utils/stream.ts"],"names":[],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"stream.js","sourceRoot":"","sources":["../../../src/snaps/utils/stream.ts"],"names":[],"mappings":";;;;;;AAAA,uDAI+B;AAC/B,2CAA2C;AAC3C,kEAAmC;AACnC,6EAAsE;AAEtE,2CAAmD;AAEnD,2EAA2E;AAC3E,cAAc;AACd,MAAM,uBAAuB,GAAG,aAAa,CAAC;AAE9C;;;;;;;GAOG;AACH,SAAgB,aAAa,CAAC,UAAmB;IAC/C,OAAO,UAAU,aAAV,UAAU,uBAAV,UAAU,CAAE,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;AAC3C,CAAC;AAFD,sCAEC;AAED;;;;;;;;GAQG;AACH,SAAgB,aAAa,CAAC,MAAsB;IAClD,IAAI,OAAO,MAAM,CAAC,SAAS,KAAK,UAAU,EAAE;QAC1C,OAAO,MAA6B,CAAC;KACtC;IAED,OAAO,IAAI,qDAAuB,CAAC,MAAM,CAAC,CAAC;AAC7C,CAAC;AAND,sCAMC;AAED;;;;;;GAMG;AACH,SAAgB,6BAA6B,CAC3C,SAA+B;IAE/B,oEAAoE;IACpE,2CAA2C;IAC3C,MAAM,aAAa,GAAG,IAAA,oBAAU,GAAE,CAAC;IAEnC,yEAAyE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AI,QAAQ,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE;gBAC7D,SAAS,CAAC,OAAO,GAAG,MAAA,WAAW,CAAC,GAAG,CAAC,QAAQ,CAAC,0CAAE,QAAQ,CAAC,MAAM,CAAC,CAAC;aACjE;SACF;QACD,WAAW,CAAC,KAAK,EAAE,CAAC;IACtB,CAAC,CAAC,CAAC;IAEH,OAAO,aAAa,CAAC;AACvB,CAAC;AA5FD,sEA4FC","sourcesContent":["import {\n SnapManifest,\n NpmSnapFileNames,\n UnvalidatedSnapFiles,\n} from '@metamask/snaps-utils';\nimport { isObject } from '@metamask/utils';\nimport concat from 'concat-stream';\nimport { ReadableWebToNodeStream } from 'readable-web-to-node-stream';\nimport { Readable, Writable } from 'stream';\nimport { extract as tarExtract } from 'tar-stream';\n\n// The paths of files within npm tarballs appear to always be prefixed with\n// \"package/\".\nconst NPM_TARBALL_PATH_PREFIX = /^package\\//u;\n\n/**\n * Strips the leading `./` from a string, or does nothing if no string is\n * provided.\n *\n * @param pathString - The path string to normalize.\n * @returns The specified path without a `./` prefix, or `undefined` if no\n * string was provided.\n */\nexport function stripDotSlash(pathString?: string): string | undefined {\n return pathString?.replace(/^\\.\\//u, '');\n}\n\n/**\n * Converts a {@link ReadableStream} to a Node.js {@link Readable}\n * stream. Returns the stream directly if it is already a Node.js stream.\n * We can't use the native Web {@link ReadableStream} directly because the\n * other stream libraries we use expect Node.js streams.\n *\n * @param stream - The stream to convert.\n * @returns The given stream as a Node.js Readable stream.\n */\nexport function getNodeStream(stream: ReadableStream): Readable {\n if (typeof stream.getReader !== 'function') {\n return stream as unknown as Readable;\n }\n\n return new ReadableWebToNodeStream(stream);\n}\n\n/**\n * Creates a `tar-stream` that will get the necessary files from an npm Snap\n * package tarball (`.tgz` file).\n *\n * @param snapFiles - An object to write target file contents to.\n * @returns The {@link Writable} tarball extraction stream.\n */\nexport function createTarballExtractionStream(\n snapFiles: UnvalidatedSnapFiles,\n): Writable {\n // `tar-stream` is pretty old-school, so we create it first and then\n // instrument it by adding event listeners.\n const extractStream = tarExtract();\n\n // `tar-stream` reads every file in the tarball serially. We already know\n // where to look for package.json and the Snap manifest, but we don't know\n // where the source code is. Therefore, we cache the contents of each .js\n // file in the tarball and pick out the correct one when the stream has ended.\n const jsFileCache = new Map<string, Buffer>();\n\n // \"entry\" is fired for every discreet entity in the tarball. This includes\n // files and folders.\n extractStream.on('entry', (header, entryStream, next) => {\n const { name: headerName, type: headerType } = header;\n if (headerType === 'file') {\n // The name is a path if the header type is \"file\".\n const filePath = headerName.replace(NPM_TARBALL_PATH_PREFIX, '');\n\n // Note the use of `concat-stream` since the data for each file may be\n // chunked.\n if (filePath === NpmSnapFileNames.PackageJson) {\n return entryStream.pipe(\n concat((data) => {\n try {\n snapFiles.packageJson = JSON.parse(data.toString());\n } catch (_error) {\n return extractStream.destroy(\n new Error(`Failed to parse \"${NpmSnapFileNames.PackageJson}\".`),\n );\n }\n\n return next();\n }),\n );\n } else if (filePath === NpmSnapFileNames.Manifest) {\n return entryStream.pipe(\n concat((data) => {\n try {\n snapFiles.manifest = JSON.parse(data.toString());\n } catch (_error) {\n return extractStream.destroy(\n new Error(`Failed to parse \"${NpmSnapFileNames.Manifest}\".`),\n );\n }\n\n return next();\n }),\n );\n } else if (/\\w+\\.(?:js|svg)$/u.test(filePath)) {\n return entryStream.pipe(\n concat((data) => {\n jsFileCache.set(filePath, data);\n return next();\n }),\n );\n }\n }\n\n // If we get here, the entry is not a file, and we want to ignore. The entry\n // stream must be drained, or the extractStream will stop reading. This is\n // effectively a no-op for the current entry.\n entryStream.on('end', () => next());\n return entryStream.resume();\n });\n\n // Once we've read the entire tarball, attempt to grab the bundle file\n // contents from the .js file cache.\n extractStream.once('finish', () => {\n if (isObject(snapFiles.manifest)) {\n /* istanbul ignore next: optional chaining */\n const { filePath: _bundlePath, iconPath: _iconPath } =\n (snapFiles.manifest as unknown as Partial<SnapManifest>).source\n ?.location?.npm ?? {};\n\n const bundlePath = stripDotSlash(_bundlePath);\n const iconPath = stripDotSlash(_iconPath);\n\n if (bundlePath) {\n snapFiles.sourceCode = jsFileCache.get(bundlePath)?.toString('utf8');\n }\n\n if (typeof iconPath === 'string' && iconPath.endsWith('.svg')) {\n snapFiles.svgIcon = jsFileCache.get(iconPath)?.toString('utf8');\n }\n }\n jsFileCache.clear();\n });\n\n return extractStream;\n}\n"]}
|
package/dist/utils.d.ts
CHANGED
|
@@ -83,7 +83,7 @@ declare type IsLiteral<T> = T extends string | number | boolean | symbol ? Extra
|
|
|
83
83
|
* ```
|
|
84
84
|
* @see [Literal types]{@link https://www.typescriptlang.org/docs/handbook/literal-types.html}
|
|
85
85
|
*/
|
|
86
|
-
declare type
|
|
86
|
+
declare type LiteralKeys<T> = NonNullable<{
|
|
87
87
|
[Key in keyof T]: IsLiteral<Key> extends true ? Key : never;
|
|
88
88
|
}[keyof T]>;
|
|
89
89
|
/**
|
|
@@ -96,7 +96,7 @@ declare type _LiteralKeys<T> = NonNullable<{
|
|
|
96
96
|
* ```
|
|
97
97
|
* @see [Literal types]{@link https://www.typescriptlang.org/docs/handbook/literal-types.html}
|
|
98
98
|
*/
|
|
99
|
-
declare type
|
|
99
|
+
declare type NonLiteralKeys<T> = NonNullable<{
|
|
100
100
|
[Key in keyof T]: IsLiteral<Key> extends false ? Key : never;
|
|
101
101
|
}[keyof T]>;
|
|
102
102
|
/**
|
|
@@ -113,7 +113,7 @@ declare type _NonLiteralKeys<T> = NonNullable<{
|
|
|
113
113
|
* ```
|
|
114
114
|
* @see {@link setDiff} for the main use-case
|
|
115
115
|
*/
|
|
116
|
-
export declare type Diff<A, B> = Omit<A,
|
|
116
|
+
export declare type Diff<A, B> = Omit<A, LiteralKeys<B>> & Partial<Pick<A, Extract<keyof A, NonLiteralKeys<B>>>>;
|
|
117
117
|
/**
|
|
118
118
|
* Makes every specified property of the specified object type mutable.
|
|
119
119
|
*
|
package/dist/utils.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3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OAAO,CAAC;AACjB,CAAC;AAnBD,wCAmBC;AAED;;;GAGG;AACU,QAAA,WAAW,GAAG,MAAM,CAC/B,sEAAsE,CACvE,CAAC;AAEF;;;;;;;;;;GAUG;AACI,KAAK,UAAU,WAAW,CAC/B,OAA8B,EAC9B,SAAyB;IAEzB,MAAM,KAAK,GACT,OAAO,SAAS,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,aAAK,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IACnE,MAAM,YAAY,GAAG,cAAc,CAAC,KAAK,EAAE,mBAAW,CAAC,CAAC;IACxD,IAAI;QACF,OAAO,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC;KACpD;YAAS;QACR,YAAY,CAAC,MAAM,EAAE,CAAC;KACvB;AACH,CAAC;AAZD,kCAYC","sourcesContent":["import { Timer } from './snaps/Timer';\n\n/**\n * Takes two objects and does a Set Difference of them.\n * Set Difference is generally defined as follows:\n * ```\n * 𝑥 ∈ A ∖ B ⟺ 𝑥 ∈ A ∧ 𝑥 ∉ B\n * ```\n * Meaning that the returned object contains all properties of A expect those that also\n * appear in B. Notice that properties that appear in B, but not in A, have no effect.\n *\n * @see [Set Difference]{@link https://proofwiki.org/wiki/Definition:Set_Difference}\n * @param objectA - The object on which the difference is being calculated.\n * @param objectB - The object whose properties will be removed from objectA.\n * @returns The objectA without properties from objectB.\n */\nexport function setDiff<\n ObjectA extends Record<any, unknown>,\n ObjectB extends Record<any, unknown>,\n>(objectA: ObjectA, objectB: ObjectB): Diff<ObjectA, ObjectB> {\n return Object.entries(objectA).reduce<Record<any, unknown>>(\n (acc, [key, value]) => {\n if (!(key in objectB)) {\n acc[key] = value;\n }\n return acc;\n },\n {},\n ) as Diff<ObjectA, ObjectB>;\n}\n\n/**\n * A Promise that delays it's return for a given amount of milliseconds.\n *\n * @param ms - Milliseconds to delay the execution for.\n * @param result - The result to return from the Promise after delay.\n * @returns A promise that is void if no result provided, result otherwise.\n * @template Result - The `result`.\n */\nexport function delay<Result = void>(\n ms: number,\n result?: Result,\n): Promise<Result> & { cancel: () => void } {\n return delayWithTimer(new Timer(ms), result);\n}\n\n/**\n * A Promise that delays it's return by using a pausable Timer.\n *\n * @param timer - Timer used to control the delay.\n * @param result - The result to return from the Promise after delay.\n * @returns A promise that is void if no result provided, result otherwise.\n * @template Result - The `result`.\n */\nexport function delayWithTimer<Result = void>(\n timer: Timer,\n result?: Result,\n): Promise<Result> & { cancel: () => void } {\n let rejectFunc: (reason: Error) => void;\n const promise: any = new Promise<Result>((resolve: any, reject) => {\n timer.start(() => {\n result === undefined ? resolve() : resolve(result);\n });\n rejectFunc = reject;\n });\n\n promise.cancel = () => {\n if (timer.status !== 'finished') {\n timer.cancel();\n rejectFunc(new Error('The delay has been canceled.'));\n }\n };\n return promise;\n}\n\n/*\n * We use a Symbol instead of rejecting the promise so that Errors thrown\n * by the main promise will propagate.\n */\nexport const hasTimedOut = Symbol(\n 'Used to check if the requested promise has timeout (see withTimeout)',\n);\n\n/**\n * Executes the given Promise, if the Timer expires before the Promise settles, we return earlier.\n *\n * NOTE:** The given Promise is not cancelled or interrupted, and will continue to execute uninterrupted. We will just discard its result if it does not complete before the timeout.\n *\n * @param promise - The promise that you want to execute.\n * @param timerOrMs - The timer controlling the timeout or a ms value.\n * @returns The resolved `PromiseValue`, or the hasTimedOut symbol if\n * returning early.\n * @template PromiseValue- - The value of the Promise.\n */\nexport async function withTimeout<PromiseValue = void>(\n promise: Promise<PromiseValue>,\n timerOrMs: Timer | number,\n): Promise<PromiseValue | typeof hasTimedOut> {\n const timer =\n typeof timerOrMs === 'number' ? new Timer(timerOrMs) : timerOrMs;\n const delayPromise = delayWithTimer(timer, hasTimedOut);\n try {\n return await Promise.race([promise, delayPromise]);\n } finally {\n delayPromise.cancel();\n }\n}\n\n/**\n * Checks whether the type is composed of literal types\n *\n * @returns @type {true} if whole type is composed of literals, @type {false} if whole type is not literals, @type {boolean} if mixed\n * @example\n * ```\n * type t1 = IsLiteral<1 | 2 | \"asd\" | true>;\n * // t1 = true\n *\n * type t2 = IsLiteral<number | string>;\n * // t2 = false\n *\n * type t3 = IsLiteral<1 | string>;\n * // t3 = boolean\n *\n * const s = Symbol();\n * type t4 = IsLiteral<typeof s>;\n * // t4 = true\n *\n * type t5 = IsLiteral<symbol>\n * // t5 = false;\n * ```\n */\ntype IsLiteral<T> = T extends string | number | boolean | symbol\n ? Extract<string | number | boolean | symbol, T> extends never\n ? true\n : false\n : false;\n\n/**\n * Returns all keys of an object, that are literal, as an union\n *\n * @example\n * ```\n * type t1 = _LiteralKeys<{a: number, b: 0, c: 'foo', d: string}>\n * // t1 = 'b' | 'c'\n * ```\n * @see [Literal types]{@link https://www.typescriptlang.org/docs/handbook/literal-types.html}\n */\ntype
|
|
1
|
+
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":";;;AAAA,yCAAsC;AAEtC;;;;;;;;;;;;;GAaG;AACH,SAAgB,OAAO,CAGrB,OAAgB,EAAE,OAAgB;IAClC,OAAO,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,MAAM,CACnC,CAAC,GAAG,EAAE,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,EAAE;QACpB,IAAI,CAAC,CAAC,GAAG,IAAI,OAAO,CAAC,EAAE;YACrB,GAAG,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;SAClB;QACD,OAAO,GAAG,CAAC;IACb,CAAC,EACD,EAAE,CACuB,CAAC;AAC9B,CAAC;AAbD,0BAaC;AAED;;;;;;;GAOG;AACH,SAAgB,KAAK,CACnB,EAAU,EACV,MAAe;IAEf,OAAO,cAAc,CAAC,IAAI,aAAK,CAAC,EAAE,CAAC,EAAE,MAAM,CAAC,CAAC;AAC/C,CAAC;AALD,sBAKC;AAED;;;;;;;GAOG;AACH,SAAgB,cAAc,CAC5B,KAAY,EACZ,MAAe;IAEf,IAAI,UAAmC,CAAC;IACxC,MAAM,OAAO,GAAQ,IAAI,OAAO,CAAS,CAAC,OAAY,EAAE,MAAM,EAAE,EAAE;QAChE,KAAK,CAAC,KAAK,CAAC,GAAG,EAAE;YACf,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;QACrD,CAAC,CAAC,CAAC;QACH,UAAU,GAAG,MAAM,CAAC;IACtB,CAAC,CAAC,CAAC;IAEH,OAAO,CAAC,MAAM,GAAG,GAAG,EAAE;QACpB,IAAI,KAAK,CAAC,MAAM,KAAK,UAAU,EAAE;YAC/B,KAAK,CAAC,MAAM,EAAE,CAAC;YACf,UAAU,CAAC,IAAI,KAAK,CAAC,8BAA8B,CAAC,CAAC,CAAC;SACvD;IACH,CAAC,CAAC;IACF,OAAO,OAAO,CAAC;AACjB,CAAC;AAnBD,wCAmBC;AAED;;;GAGG;AACU,QAAA,WAAW,GAAG,MAAM,CAC/B,sEAAsE,CACvE,CAAC;AAEF;;;;;;;;;;GAUG;AACI,KAAK,UAAU,WAAW,CAC/B,OAA8B,EAC9B,SAAyB;IAEzB,MAAM,KAAK,GACT,OAAO,SAAS,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,aAAK,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IACnE,MAAM,YAAY,GAAG,cAAc,CAAC,KAAK,EAAE,mBAAW,CAAC,CAAC;IACxD,IAAI;QACF,OAAO,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC;KACpD;YAAS;QACR,YAAY,CAAC,MAAM,EAAE,CAAC;KACvB;AACH,CAAC;AAZD,kCAYC","sourcesContent":["import { Timer } from './snaps/Timer';\n\n/**\n * Takes two objects and does a Set Difference of them.\n * Set Difference is generally defined as follows:\n * ```\n * 𝑥 ∈ A ∖ B ⟺ 𝑥 ∈ A ∧ 𝑥 ∉ B\n * ```\n * Meaning that the returned object contains all properties of A expect those that also\n * appear in B. Notice that properties that appear in B, but not in A, have no effect.\n *\n * @see [Set Difference]{@link https://proofwiki.org/wiki/Definition:Set_Difference}\n * @param objectA - The object on which the difference is being calculated.\n * @param objectB - The object whose properties will be removed from objectA.\n * @returns The objectA without properties from objectB.\n */\nexport function setDiff<\n ObjectA extends Record<any, unknown>,\n ObjectB extends Record<any, unknown>,\n>(objectA: ObjectA, objectB: ObjectB): Diff<ObjectA, ObjectB> {\n return Object.entries(objectA).reduce<Record<any, unknown>>(\n (acc, [key, value]) => {\n if (!(key in objectB)) {\n acc[key] = value;\n }\n return acc;\n },\n {},\n ) as Diff<ObjectA, ObjectB>;\n}\n\n/**\n * A Promise that delays it's return for a given amount of milliseconds.\n *\n * @param ms - Milliseconds to delay the execution for.\n * @param result - The result to return from the Promise after delay.\n * @returns A promise that is void if no result provided, result otherwise.\n * @template Result - The `result`.\n */\nexport function delay<Result = void>(\n ms: number,\n result?: Result,\n): Promise<Result> & { cancel: () => void } {\n return delayWithTimer(new Timer(ms), result);\n}\n\n/**\n * A Promise that delays it's return by using a pausable Timer.\n *\n * @param timer - Timer used to control the delay.\n * @param result - The result to return from the Promise after delay.\n * @returns A promise that is void if no result provided, result otherwise.\n * @template Result - The `result`.\n */\nexport function delayWithTimer<Result = void>(\n timer: Timer,\n result?: Result,\n): Promise<Result> & { cancel: () => void } {\n let rejectFunc: (reason: Error) => void;\n const promise: any = new Promise<Result>((resolve: any, reject) => {\n timer.start(() => {\n result === undefined ? resolve() : resolve(result);\n });\n rejectFunc = reject;\n });\n\n promise.cancel = () => {\n if (timer.status !== 'finished') {\n timer.cancel();\n rejectFunc(new Error('The delay has been canceled.'));\n }\n };\n return promise;\n}\n\n/*\n * We use a Symbol instead of rejecting the promise so that Errors thrown\n * by the main promise will propagate.\n */\nexport const hasTimedOut = Symbol(\n 'Used to check if the requested promise has timeout (see withTimeout)',\n);\n\n/**\n * Executes the given Promise, if the Timer expires before the Promise settles, we return earlier.\n *\n * NOTE:** The given Promise is not cancelled or interrupted, and will continue to execute uninterrupted. We will just discard its result if it does not complete before the timeout.\n *\n * @param promise - The promise that you want to execute.\n * @param timerOrMs - The timer controlling the timeout or a ms value.\n * @returns The resolved `PromiseValue`, or the hasTimedOut symbol if\n * returning early.\n * @template PromiseValue- - The value of the Promise.\n */\nexport async function withTimeout<PromiseValue = void>(\n promise: Promise<PromiseValue>,\n timerOrMs: Timer | number,\n): Promise<PromiseValue | typeof hasTimedOut> {\n const timer =\n typeof timerOrMs === 'number' ? new Timer(timerOrMs) : timerOrMs;\n const delayPromise = delayWithTimer(timer, hasTimedOut);\n try {\n return await Promise.race([promise, delayPromise]);\n } finally {\n delayPromise.cancel();\n }\n}\n\n/**\n * Checks whether the type is composed of literal types\n *\n * @returns @type {true} if whole type is composed of literals, @type {false} if whole type is not literals, @type {boolean} if mixed\n * @example\n * ```\n * type t1 = IsLiteral<1 | 2 | \"asd\" | true>;\n * // t1 = true\n *\n * type t2 = IsLiteral<number | string>;\n * // t2 = false\n *\n * type t3 = IsLiteral<1 | string>;\n * // t3 = boolean\n *\n * const s = Symbol();\n * type t4 = IsLiteral<typeof s>;\n * // t4 = true\n *\n * type t5 = IsLiteral<symbol>\n * // t5 = false;\n * ```\n */\ntype IsLiteral<T> = T extends string | number | boolean | symbol\n ? Extract<string | number | boolean | symbol, T> extends never\n ? true\n : false\n : false;\n\n/**\n * Returns all keys of an object, that are literal, as an union\n *\n * @example\n * ```\n * type t1 = _LiteralKeys<{a: number, b: 0, c: 'foo', d: string}>\n * // t1 = 'b' | 'c'\n * ```\n * @see [Literal types]{@link https://www.typescriptlang.org/docs/handbook/literal-types.html}\n */\ntype LiteralKeys<T> = NonNullable<\n {\n [Key in keyof T]: IsLiteral<Key> extends true ? Key : never;\n }[keyof T]\n>;\n\n/**\n * Returns all keys of an object, that are not literal, as an union\n *\n * @example\n * ```\n * type t1 = _NonLiteralKeys<{a: number, b: 0, c: 'foo', d: string}>\n * // t1 = 'a' | 'd'\n * ```\n * @see [Literal types]{@link https://www.typescriptlang.org/docs/handbook/literal-types.html}\n */\ntype NonLiteralKeys<T> = NonNullable<\n {\n [Key in keyof T]: IsLiteral<Key> extends false ? Key : never;\n }[keyof T]\n>;\n\n/**\n * A set difference of two objects based on their keys\n *\n * @example\n * ```\n * type t1 = Diff<{a: string, b: string}, {a: number}>\n * // t1 = {b: string};\n * type t2 = Diff<{a: string, 0: string}, Record<string, unknown>>;\n * // t2 = { a?: string, 0: string};\n * type t3 = Diff<{a: string, 0: string, 1: string}, Record<1 | string, unknown>>;\n * // t3 = {a?: string, 0: string}\n * ```\n * @see {@link setDiff} for the main use-case\n */\nexport type Diff<A, B> = Omit<A, LiteralKeys<B>> &\n Partial<Pick<A, Extract<keyof A, NonLiteralKeys<B>>>>;\n\n/**\n * Makes every specified property of the specified object type mutable.\n *\n * @template T - The object whose readonly properties to make mutable.\n * @template TargetKey - The property key(s) to make mutable.\n */\nexport type Mutable<\n T extends Record<string, unknown>,\n TargetKey extends string,\n> = {\n -readonly [Key in keyof Pick<T, TargetKey>]: T[Key];\n} & {\n [Key in keyof Omit<T, TargetKey>]: T[Key];\n};\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask/snaps-controllers",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.25.0",
|
|
4
4
|
"description": "Controllers for MetaMask Snaps.",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -31,14 +31,17 @@
|
|
|
31
31
|
"publish:package": "../../scripts/publish-package.sh"
|
|
32
32
|
},
|
|
33
33
|
"dependencies": {
|
|
34
|
-
"@metamask/
|
|
35
|
-
"@metamask/
|
|
34
|
+
"@metamask/approval-controller": "^1.0.0",
|
|
35
|
+
"@metamask/base-controller": "^1.0.0",
|
|
36
|
+
"@metamask/browser-passworder": "^4.0.2",
|
|
36
37
|
"@metamask/object-multiplex": "^1.1.0",
|
|
38
|
+
"@metamask/permission-controller": "^1.0.0",
|
|
37
39
|
"@metamask/post-message-stream": "^6.0.0",
|
|
38
|
-
"@metamask/rpc-methods": "^0.
|
|
39
|
-
"@metamask/snaps-execution-environments": "^0.
|
|
40
|
-
"@metamask/snaps-types": "^0.
|
|
41
|
-
"@metamask/snaps-utils": "^0.
|
|
40
|
+
"@metamask/rpc-methods": "^0.25.0",
|
|
41
|
+
"@metamask/snaps-execution-environments": "^0.25.0",
|
|
42
|
+
"@metamask/snaps-types": "^0.25.0",
|
|
43
|
+
"@metamask/snaps-utils": "^0.25.0",
|
|
44
|
+
"@metamask/subject-metadata-controller": "^1.0.0",
|
|
42
45
|
"@metamask/utils": "^3.3.1",
|
|
43
46
|
"@xstate/fsm": "^2.0.0",
|
|
44
47
|
"concat-stream": "^2.0.0",
|
|
@@ -55,11 +58,11 @@
|
|
|
55
58
|
},
|
|
56
59
|
"devDependencies": {
|
|
57
60
|
"@lavamoat/allow-scripts": "^2.0.3",
|
|
58
|
-
"@metamask/auto-changelog": "^
|
|
59
|
-
"@metamask/eslint-config": "^
|
|
60
|
-
"@metamask/eslint-config-jest": "^
|
|
61
|
-
"@metamask/eslint-config-nodejs": "^
|
|
62
|
-
"@metamask/eslint-config-typescript": "^
|
|
61
|
+
"@metamask/auto-changelog": "^3.1.0",
|
|
62
|
+
"@metamask/eslint-config": "^11.0.0",
|
|
63
|
+
"@metamask/eslint-config-jest": "^11.0.0",
|
|
64
|
+
"@metamask/eslint-config-nodejs": "^11.0.1",
|
|
65
|
+
"@metamask/eslint-config-typescript": "^11.0.0",
|
|
63
66
|
"@metamask/template-snap": "^0.7.0",
|
|
64
67
|
"@peculiar/webcrypto": "^1.3.3",
|
|
65
68
|
"@types/concat-stream": "^2.0.0",
|
|
@@ -68,26 +71,28 @@
|
|
|
68
71
|
"@types/pump": "^1.1.1",
|
|
69
72
|
"@types/readable-stream": "^2.3.9",
|
|
70
73
|
"@types/tar-stream": "^2.2.2",
|
|
74
|
+
"@typescript-eslint/eslint-plugin": "^5.42.1",
|
|
75
|
+
"@typescript-eslint/parser": "^5.42.1",
|
|
71
76
|
"deepmerge": "^4.2.2",
|
|
72
|
-
"eslint": "^
|
|
73
|
-
"eslint-config-prettier": "^8.
|
|
74
|
-
"eslint-plugin-import": "^2.
|
|
75
|
-
"eslint-plugin-jest": "^
|
|
76
|
-
"eslint-plugin-jsdoc": "^
|
|
77
|
+
"eslint": "^8.27.0",
|
|
78
|
+
"eslint-config-prettier": "^8.5.0",
|
|
79
|
+
"eslint-plugin-import": "^2.26.0",
|
|
80
|
+
"eslint-plugin-jest": "^27.1.5",
|
|
81
|
+
"eslint-plugin-jsdoc": "^39.6.2",
|
|
77
82
|
"eslint-plugin-node": "^11.1.0",
|
|
78
|
-
"eslint-plugin-prettier": "^
|
|
83
|
+
"eslint-plugin-prettier": "^4.2.1",
|
|
79
84
|
"jest": "^29.0.2",
|
|
80
85
|
"jest-environment-jsdom": "^29.0.2",
|
|
81
86
|
"jest-fetch-mock": "^3.0.3",
|
|
82
87
|
"jest-it-up": "^2.0.0",
|
|
83
88
|
"jsdom": "^19.0.0",
|
|
84
89
|
"mkdirp": "^1.0.4",
|
|
85
|
-
"prettier": "^2.
|
|
90
|
+
"prettier": "^2.7.1",
|
|
86
91
|
"prettier-plugin-packagejson": "^2.2.11",
|
|
87
92
|
"rimraf": "^3.0.2",
|
|
88
93
|
"serve-handler": "^6.1.5",
|
|
89
94
|
"ts-jest": "^29.0.0",
|
|
90
|
-
"typescript": "
|
|
95
|
+
"typescript": "~4.8.4"
|
|
91
96
|
},
|
|
92
97
|
"engines": {
|
|
93
98
|
"node": ">=16.0.0"
|