@taqueria/toolkit 0.27.2-alpha → 0.27.2-rc

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 ADDED
@@ -0,0 +1,92 @@
1
+ # Taqueria Toolkit
2
+
3
+ A client-side package to load Taqueria config and state into a (d)App.
4
+
5
+ ### Quickstart
6
+
7
+ 1. Initialize a taqueria project: `taq init`
8
+ 1. Create an app in `./app`.
9
+ 1. In app, install the toolkit: `npm i -S @taqueria/toolkit`.
10
+ 1. In your app, use the toolkit to get an address of an originated contract:
11
+ ```ts
12
+ import {loadFromEnv, getAliasAddress} from "@taqueria/toolkit"
13
+ const config = await loadFromEnv(process.env)
14
+ const address = getAliasAddress(config, "hello-tacos")
15
+ ```
16
+ 1. Build the app with the needed environment variables: `withTaq --projectdir ./ npm run app:build`.
17
+ > This will populate environment variables needed by the toolkit
18
+
19
+ ### Using with create-react-app
20
+ 1. Initialize a taqueria project: `taq init`
21
+ 1. Create a react app: `npx create-react-app ./app --template typescript`
22
+ 1. In `./app/.env`, add `SKIP_PREFLIGHT_CHECK=true`.
23
+ 1. In `./app`, run: `npm install`
24
+ 1. In `./app`, run: `npm i -S @taqueria/toolkit`.
25
+ 1. In `./app`, edit index.tsx to pass environment variables to the App component:
26
+ ```ts
27
+ <App env={process.env}/>
28
+ ```
29
+ 1. In `./app`, edit App.tsx to include the toolkit:
30
+ ```ts
31
+ import {loadFromEnv, getAliasAddress} from "@taqueria/toolkit"
32
+
33
+ type AppProps = {
34
+ env: Record<string, string|undefined>
35
+ }
36
+
37
+ function App(props: AppProps) {
38
+ const [contractAddress, setContractAddress] = useState<string|undefined>(undefined)
39
+
40
+ useEffect(async ()=>{
41
+ const config = await loadFromEnv(props.env)
42
+ // "hello-tacos" is the name of the contract
43
+ setContractAddress(getAliasAddress(config, "hello-tacos"))
44
+ })
45
+ }
46
+ ```
47
+ 1. Adjust the build and start scripts in `package.json` to use the toolkit to populate the necessary environment variables:
48
+ ```json
49
+ "scripts": {
50
+ "start": "withTaq --projectDir ../ --prefix REACT_APP_ react-scripts start",
51
+ "build": "withTaq --projectDir ../ --prefix REACT_APP_ react-scripts build",
52
+ }
53
+ ```
54
+
55
+ ### How it works
56
+
57
+ The `withTaq` command populates the environment with variables needed by the toolkit. These variables will include your Taqueria & environment configuration:
58
+ ```sh
59
+ TAQ_CONFIG=[base64 encoded data]
60
+ TAQ_CONFIG_LOCAL_DEVELOPMENT=[base64 encoded data]
61
+ TAQ_CONFIG_LOCAL_TESTING=[base64 encoded data]
62
+ ```
63
+
64
+ An environment variable will exist for each environment configuration file that exists in your Taqueria project.
65
+
66
+ These environment variables are then consumed in your app using `loadFromEnv`:
67
+ ```ts
68
+ import loadFromEnv from `@taqueria/toolkit`
69
+ const config = await loadFromEnv(process.env)
70
+ ```
71
+
72
+ Rather than having to set these environment variables manually, you can wrap a command using `withTaq`:
73
+ ```sh
74
+ withTaq --projectDir ../ npm run build
75
+ ```
76
+
77
+ The above command is an example of how you would populate the environment variables needed when running `npm run build`.
78
+
79
+ ### Advanced Usage:
80
+
81
+ In some cases and app frameworks, environment variables need special prefixes to be included in your app's environment context. For instance, apps created using `create-react-app` will only have access to environment variables with the `REACT_APP_` prefix. To handle this, two modifications are required:
82
+
83
+ #### Adjust withTaq to use the prefix
84
+ ```sh
85
+ withTaq --projectDir ../ --prefix "REACT_APP_" npm run build
86
+ ```
87
+
88
+ #### Adjust the loadFromEnv call to use the prefix
89
+ ```ts
90
+ import loadFromEnv from `@taqueria/toolkit`
91
+ const config = await loadFromEnv(process.env, "REACT_APP_")
92
+ ```
package/TaqError.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ export declare class TaqError extends Error {
2
+ isTaqError: boolean;
3
+ }
4
+ export declare const isTaqError: (err: unknown) => err is TaqError;
package/TaqError.ts ADDED
@@ -0,0 +1,5 @@
1
+ export class TaqError extends Error {
2
+ public isTaqError = true;
3
+ }
4
+ export const isTaqError = (err: unknown): err is TaqError =>
5
+ typeof err === 'object' && (err as object).hasOwnProperty('isTaqError');
package/bin/run.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/bin/run.js ADDED
@@ -0,0 +1,115 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
18
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
19
+ mod
20
+ ));
21
+
22
+ // bin/run.ts
23
+ var import_cross_spawn = require("cross-spawn");
24
+ var import_promises = __toESM(require("fs/promises"));
25
+ var import_promises2 = require("fs/promises");
26
+ var import_path = __toESM(require("path"));
27
+ var import_yargs = __toESM(require("yargs"));
28
+ var CustomErr = class extends Error {
29
+ };
30
+ var TaqNotFoundError = class extends CustomErr {
31
+ constructor() {
32
+ super(...arguments);
33
+ this.isCustomErr = true;
34
+ }
35
+ };
36
+ function isCustomError(err) {
37
+ return typeof err === "object" && err.hasOwnProperty("isCustomErr");
38
+ }
39
+ async function checkTaqProject(dir) {
40
+ try {
41
+ const searchPath = import_path.default.join(dir, ".taq");
42
+ await (0, import_promises2.stat)(searchPath);
43
+ return searchPath;
44
+ } catch {
45
+ throw new TaqNotFoundError(`${dir} is not a valid Taqueria project.`);
46
+ }
47
+ }
48
+ function withArguments(cliArgs, fn) {
49
+ if (cliArgs[0].endsWith("node"))
50
+ cliArgs.shift();
51
+ const script = cliArgs.shift();
52
+ const parsedArgs = (0, import_yargs.default)(cliArgs).option("projectDir", {
53
+ alias: "p",
54
+ type: "string",
55
+ requiresArg: true
56
+ }).option("prefix", {
57
+ type: "string",
58
+ requiresArg: true,
59
+ default: ""
60
+ }).global(["projectDir"]).parseSync();
61
+ if (parsedArgs._.length > 0 && parsedArgs.projectDir) {
62
+ fn(parsedArgs.projectDir, parsedArgs.prefix, parsedArgs._.join(" "));
63
+ } else
64
+ console.log(`Usage: ${script} --projectDir <projectDir> [--prefix <prefix>] <command>`);
65
+ }
66
+ function getEnvName(filename, prefix = "") {
67
+ return `${prefix}TAQ_${filename}`.replace(".json", "").replace(/\./mg, "_").replace(/\-/mg, "_").toUpperCase();
68
+ }
69
+ var TaqConfigError = class extends CustomErr {
70
+ };
71
+ async function getConfig(taqDir, prefix) {
72
+ try {
73
+ const files = await import_promises.default.readdir(taqDir);
74
+ return files.reduce(
75
+ async (retval, file) => {
76
+ if (!file.endsWith(".json"))
77
+ return await retval;
78
+ return {
79
+ ...await retval,
80
+ [getEnvName(file, prefix)]: await (0, import_promises2.readFile)(import_path.default.join(taqDir, file), "utf-8")
81
+ };
82
+ },
83
+ Promise.resolve({})
84
+ );
85
+ } catch {
86
+ throw new TaqConfigError(
87
+ `There was a problem reading the config files in ${taqDir}. Please check file permissions are try again.`
88
+ );
89
+ }
90
+ }
91
+ function toCommandWithEnvVars(cmd, config) {
92
+ return Object.entries(config).reduce(
93
+ (retval, [key, value]) => `${key}=${btoa(value)} ${retval}`,
94
+ cmd
95
+ );
96
+ }
97
+ async function run(projectDir, prefix, cmd) {
98
+ try {
99
+ const taqDir = await checkTaqProject(projectDir);
100
+ const config = await getConfig(taqDir, prefix);
101
+ const cmdWithEnvVars = toCommandWithEnvVars(cmd, config);
102
+ (0, import_cross_spawn.spawn)(cmdWithEnvVars, {
103
+ shell: true,
104
+ stdio: "inherit"
105
+ });
106
+ } catch (err) {
107
+ if (isCustomError(err)) {
108
+ console.error(err.message);
109
+ return;
110
+ }
111
+ throw err;
112
+ }
113
+ }
114
+ withArguments(process.argv, run);
115
+ //# sourceMappingURL=run.js.map
package/bin/run.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["run.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { spawn } from 'cross-spawn';\nimport fs from 'fs/promises';\nimport { readFile, stat } from 'fs/promises';\nimport path from 'path';\nimport yargs from 'yargs';\n\nclass CustomErr extends Error {}\n\nclass TaqNotFoundError extends CustomErr {\n\tpublic isCustomErr = true;\n}\n\nfunction isCustomError(err: unknown): err is Error {\n\treturn typeof err === 'object' && (err as object).hasOwnProperty('isCustomErr');\n}\n\nasync function checkTaqProject(dir: string) {\n\ttry {\n\t\tconst searchPath = path.join(dir, '.taq');\n\t\tawait stat(searchPath);\n\t\treturn searchPath;\n\t} catch {\n\t\tthrow new TaqNotFoundError(`${dir} is not a valid Taqueria project.`);\n\t}\n}\n\nfunction withArguments(cliArgs: string[], fn: (projectDir: string, prefix: string, cmd: string) => Promise<void>) {\n\tif (cliArgs[0].endsWith('node')) cliArgs.shift();\n\n\tconst script = cliArgs.shift();\n\n\tconst parsedArgs = yargs(cliArgs)\n\t\t.option('projectDir', {\n\t\t\talias: 'p',\n\t\t\ttype: 'string',\n\t\t\trequiresArg: true,\n\t\t})\n\t\t.option('prefix', {\n\t\t\ttype: 'string',\n\t\t\trequiresArg: true,\n\t\t\tdefault: '',\n\t\t})\n\t\t.global(['projectDir'])\n\t\t.parseSync();\n\n\tif (parsedArgs._.length > 0 && parsedArgs.projectDir) {\n\t\tfn(parsedArgs.projectDir, parsedArgs.prefix, parsedArgs._.join(' '));\n\t} else console.log(`Usage: ${script} --projectDir <projectDir> [--prefix <prefix>] <command>`);\n}\n\nfunction getEnvName(filename: string, prefix = '') {\n\treturn `${prefix}TAQ_${filename}`\n\t\t.replace('.json', '')\n\t\t.replace(/\\./mg, '_')\n\t\t.replace(/\\-/mg, '_')\n\t\t.toUpperCase();\n}\n\nclass TaqConfigError extends CustomErr {}\nasync function getConfig(taqDir: string, prefix: string) {\n\ttry {\n\t\tconst files = await fs.readdir(taqDir);\n\t\treturn files.reduce(\n\t\t\tasync (retval, file) => {\n\t\t\t\tif (!file.endsWith('.json')) return (await retval);\n\t\t\t\treturn {\n\t\t\t\t\t...(await retval),\n\t\t\t\t\t[getEnvName(file, prefix)]: await readFile(path.join(taqDir, file), 'utf-8'),\n\t\t\t\t};\n\t\t\t},\n\t\t\tPromise.resolve({}),\n\t\t);\n\t} catch {\n\t\tthrow new TaqConfigError(\n\t\t\t`There was a problem reading the config files in ${taqDir}. Please check file permissions are try again.`,\n\t\t);\n\t}\n}\n\nfunction toCommandWithEnvVars(cmd: string, config: Record<string, string>) {\n\treturn Object.entries(config).reduce(\n\t\t(retval, [key, value]) => `${key}=${btoa(value)} ${retval}`,\n\t\tcmd,\n\t);\n}\n\nasync function run(projectDir: string, prefix: string, cmd: string) {\n\ttry {\n\t\tconst taqDir = await checkTaqProject(projectDir);\n\t\tconst config = await getConfig(taqDir, prefix);\n\t\tconst cmdWithEnvVars = toCommandWithEnvVars(cmd, config);\n\n\t\tspawn(cmdWithEnvVars, {\n\t\t\tshell: true,\n\t\t\tstdio: 'inherit',\n\t\t});\n\t} catch (err) {\n\t\tif (isCustomError(err)) {\n\t\t\tconsole.error(err.message);\n\t\t\treturn;\n\t\t}\n\t\tthrow err;\n\t}\n}\n\nwithArguments(process.argv, run);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AACA,yBAAsB;AACtB,sBAAe;AACf,IAAAA,mBAA+B;AAC/B,kBAAiB;AACjB,mBAAkB;AAElB,IAAM,YAAN,cAAwB,MAAM;AAAC;AAE/B,IAAM,mBAAN,cAA+B,UAAU;AAAA,EAAzC;AAAA;AACC,SAAO,cAAc;AAAA;AACtB;AAEA,SAAS,cAAc,KAA4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AM;AAAA,UACV,CAAC,WAAW,MAAM,MAAM,IAAI,UAAM,2BAAS,YAAAF,QAAK,KAAK,QAAQ,IAAI,GAAG,OAAO;AAAA,QAC5E;AAAA,MACD;AAAA,MACA,QAAQ,QAAQ,CAAC,CAAC;AAAA,IACnB;AAAA,EACD,QAAE;AACD,UAAM,IAAI;AAAA,MACT,mDAAmD;AAAA,IACpD;AAAA,EACD;AACD;AAEA,SAAS,qBAAqB,KAAa,QAAgC;AAC1E,SAAO,OAAO,QAAQ,MAAM,EAAE;AAAA,IAC7B,CAAC,QAAQ,CAAC,KAAK,KAAK,MAAM,GAAG,OAAO,KAAK,KAAK,KAAK;AAAA,IACnD;AAAA,EACD;AACD;AAEA,eAAe,IAAI,YAAoB,QAAgB,KAAa;AACnE,MAAI;AACH,UAAM,SAAS,MAAM,gBAAgB,UAAU;AAC/C,UAAM,SAAS,MAAM,UAAU,QAAQ,MAAM;AAC7C,UAAM,iBAAiB,qBAAqB,KAAK,MAAM;AAEvD,kCAAM,gBAAgB;AAAA,MACrB,OAAO;AAAA,MACP,OAAO;AAAA,IACR,CAAC;AAAA,EACF,SAAS,KAAP;AACD,QAAI,cAAc,GAAG,GAAG;AACvB,cAAQ,MAAM,IAAI,OAAO;AACzB;AAAA,IACD;AACA,UAAM;AAAA,EACP;AACD;AAEA,cAAc,QAAQ,MAAM,GAAG;","names":["import_promises","path","yargs","fs"]}
package/bin/run.ts ADDED
@@ -0,0 +1,107 @@
1
+ #!/usr/bin/env node
2
+ import { spawn } from 'cross-spawn';
3
+ import fs from 'fs/promises';
4
+ import { readFile, stat } from 'fs/promises';
5
+ import path from 'path';
6
+ import yargs from 'yargs';
7
+
8
+ class CustomErr extends Error {}
9
+
10
+ class TaqNotFoundError extends CustomErr {
11
+ public isCustomErr = true;
12
+ }
13
+
14
+ function isCustomError(err: unknown): err is Error {
15
+ return typeof err === 'object' && (err as object).hasOwnProperty('isCustomErr');
16
+ }
17
+
18
+ async function checkTaqProject(dir: string) {
19
+ try {
20
+ const searchPath = path.join(dir, '.taq');
21
+ await stat(searchPath);
22
+ return searchPath;
23
+ } catch {
24
+ throw new TaqNotFoundError(`${dir} is not a valid Taqueria project.`);
25
+ }
26
+ }
27
+
28
+ function withArguments(cliArgs: string[], fn: (projectDir: string, prefix: string, cmd: string) => Promise<void>) {
29
+ if (cliArgs[0].endsWith('node')) cliArgs.shift();
30
+
31
+ const script = cliArgs.shift();
32
+
33
+ const parsedArgs = yargs(cliArgs)
34
+ .option('projectDir', {
35
+ alias: 'p',
36
+ type: 'string',
37
+ requiresArg: true,
38
+ })
39
+ .option('prefix', {
40
+ type: 'string',
41
+ requiresArg: true,
42
+ default: '',
43
+ })
44
+ .global(['projectDir'])
45
+ .parseSync();
46
+
47
+ if (parsedArgs._.length > 0 && parsedArgs.projectDir) {
48
+ fn(parsedArgs.projectDir, parsedArgs.prefix, parsedArgs._.join(' '));
49
+ } else console.log(`Usage: ${script} --projectDir <projectDir> [--prefix <prefix>] <command>`);
50
+ }
51
+
52
+ function getEnvName(filename: string, prefix = '') {
53
+ return `${prefix}TAQ_${filename}`
54
+ .replace('.json', '')
55
+ .replace(/\./mg, '_')
56
+ .replace(/\-/mg, '_')
57
+ .toUpperCase();
58
+ }
59
+
60
+ class TaqConfigError extends CustomErr {}
61
+ async function getConfig(taqDir: string, prefix: string) {
62
+ try {
63
+ const files = await fs.readdir(taqDir);
64
+ return files.reduce(
65
+ async (retval, file) => {
66
+ if (!file.endsWith('.json')) return (await retval);
67
+ return {
68
+ ...(await retval),
69
+ [getEnvName(file, prefix)]: await readFile(path.join(taqDir, file), 'utf-8'),
70
+ };
71
+ },
72
+ Promise.resolve({}),
73
+ );
74
+ } catch {
75
+ throw new TaqConfigError(
76
+ `There was a problem reading the config files in ${taqDir}. Please check file permissions are try again.`,
77
+ );
78
+ }
79
+ }
80
+
81
+ function toCommandWithEnvVars(cmd: string, config: Record<string, string>) {
82
+ return Object.entries(config).reduce(
83
+ (retval, [key, value]) => `${key}=${btoa(value)} ${retval}`,
84
+ cmd,
85
+ );
86
+ }
87
+
88
+ async function run(projectDir: string, prefix: string, cmd: string) {
89
+ try {
90
+ const taqDir = await checkTaqProject(projectDir);
91
+ const config = await getConfig(taqDir, prefix);
92
+ const cmdWithEnvVars = toCommandWithEnvVars(cmd, config);
93
+
94
+ spawn(cmdWithEnvVars, {
95
+ shell: true,
96
+ stdio: 'inherit',
97
+ });
98
+ } catch (err) {
99
+ if (isCustomError(err)) {
100
+ console.error(err.message);
101
+ return;
102
+ }
103
+ throw err;
104
+ }
105
+ }
106
+
107
+ withArguments(process.argv, run);
package/index.d.ts CHANGED
@@ -1 +1,37 @@
1
- export declare const getAliasAddress: (config: any, alias: string) => string;
1
+ import * as _taqueria_protocol_Environment from '@taqueria/protocol/Environment';
2
+ import * as Config from '@taqueria/protocol/Config';
3
+ export { Config };
4
+ import * as ConfigEnvironmentFileV2 from '@taqueria/protocol/ConfigEnvironmentFileV2';
5
+ import * as transform from '@taqueria/protocol/types-config-files';
6
+ import { ConfigFileSetV2 as ConfigFileSetV2$1 } from '@taqueria/protocol/types-config-files';
7
+
8
+ declare class TaqError extends Error {
9
+ isTaqError: boolean;
10
+ }
11
+ declare const isTaqError: (err: unknown) => err is TaqError;
12
+
13
+ type ExpandedEnv = Record<string, unknown> & ConfigEnvironmentFileV2.t & {
14
+ __type: 'expandedEnv';
15
+ };
16
+ declare function getEnv(envName: string, settings: ConfigFileSetV2$1): ExpandedEnv;
17
+ declare const getCurrentEnv$1: (settings: ConfigFileSetV2$1) => ExpandedEnv;
18
+ declare function getContractAddress(contractName: string, env: ExpandedEnv): string | undefined;
19
+
20
+ declare const v2_getContractAddress: typeof getContractAddress;
21
+ declare const v2_getEnv: typeof getEnv;
22
+ declare namespace v2 {
23
+ export {
24
+ v2_getContractAddress as getContractAddress,
25
+ getCurrentEnv$1 as getCurrentEnv,
26
+ v2_getEnv as getEnv,
27
+ };
28
+ }
29
+
30
+ declare const getConfigAsV1: (env: Record<string, string | undefined>, prefix?: string) => Config.t;
31
+ declare function getConfigV2(env: Record<string, string | undefined>, prefix?: string): transform.ConfigFileSetV2;
32
+ declare const getAliasAddress: (config: any, alias: string) => string;
33
+ declare const getCurrentEnv: (config: Config.Config) => _taqueria_protocol_Environment.Environment | undefined;
34
+
35
+ type ConfigFileSetV2 = transform.ConfigFileSetV2;
36
+
37
+ export { ConfigFileSetV2, TaqError, v2 as V2, getAliasAddress, getConfigAsV1, getConfigV2, getCurrentEnv, isTaqError };
package/index.js CHANGED
@@ -1,2 +1,202 @@
1
- "use strict";var a=Object.defineProperty;var d=Object.getOwnPropertyDescriptor;var i=Object.getOwnPropertyNames;var o=Object.prototype.hasOwnProperty;var m=(e,n)=>{for(var t in n)a(e,t,{get:n[t],enumerable:!0})},u=(e,n,t,s)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of i(n))!o.call(e,r)&&r!==t&&a(e,r,{get:()=>n[r],enumerable:!(s=d(n,r))||s.enumerable});return e};var v=e=>u(a({},"__esModule",{value:!0}),e);var E={};m(E,{getAliasAddress:()=>p});module.exports=v(E);var l=e=>{var t;let n=(t=e==null?void 0:e.environment)!=null&&t.default?e.environment.default:"development";return e.environment&&e.environment[n]?e.environment[n]:void 0},p=(e,n)=>{var s,r;let t=l(e);return(r=(s=t==null?void 0:t.aliases)==null?void 0:s[n])!=null&&r.address?t.aliases[n].address:(alert(`Address for alias, ${n}, is missing. Please deploy a contract with such alias`),"")};0&&(module.exports={getAliasAddress});
2
- //# sourceMappingURL=index.js.map
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from4, except, desc) => {
13
+ if (from4 && typeof from4 === "object" || typeof from4 === "function") {
14
+ for (let key of __getOwnPropNames(from4))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from4[key], enumerable: !(desc = __getOwnPropDesc(from4, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
22
+ mod
23
+ ));
24
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
25
+
26
+ // index.ts
27
+ var taqueria_toolkit_exports = {};
28
+ __export(taqueria_toolkit_exports, {
29
+ Config: () => Config,
30
+ TaqError: () => TaqError,
31
+ V2: () => v2_exports,
32
+ getAliasAddress: () => getAliasAddress2,
33
+ getConfigAsV1: () => getConfigAsV1,
34
+ getConfigV2: () => getConfigV2,
35
+ getCurrentEnv: () => getCurrentEnv3,
36
+ isTaqError: () => isTaqError
37
+ });
38
+ module.exports = __toCommonJS(taqueria_toolkit_exports);
39
+ var Config = __toESM(require("@taqueria/protocol/Config"));
40
+ var ConfigEnvironmentFileV2 = __toESM(require("@taqueria/protocol/ConfigEnvironmentFileV2"));
41
+ var ConfigFileV2 = __toESM(require("@taqueria/protocol/ConfigFileV2"));
42
+
43
+ // TaqError.ts
44
+ var TaqError = class extends Error {
45
+ constructor() {
46
+ super(...arguments);
47
+ this.isTaqError = true;
48
+ }
49
+ };
50
+ var isTaqError = (err) => typeof err === "object" && err.hasOwnProperty("isTaqError");
51
+
52
+ // v1.ts
53
+ var getCurrentEnv = (config) => {
54
+ var _a;
55
+ const currentEnv = ((_a = config == null ? void 0 : config.environment) == null ? void 0 : _a.default) ? config.environment.default : "development";
56
+ return config.environment && config.environment[currentEnv] ? config.environment[currentEnv] : void 0;
57
+ };
58
+ var getAliasAddress = (config, alias) => {
59
+ var _a, _b;
60
+ const currentEnv = getCurrentEnv(config);
61
+ if ((_b = (_a = currentEnv == null ? void 0 : currentEnv.aliases) == null ? void 0 : _a[alias]) == null ? void 0 : _b.address)
62
+ return currentEnv.aliases[alias].address;
63
+ alert(`Address for alias, ${alias}, is missing. Please deploy a contract with such alias`);
64
+ return "";
65
+ };
66
+
67
+ // v2.ts
68
+ var v2_exports = {};
69
+ __export(v2_exports, {
70
+ getContractAddress: () => getContractAddress,
71
+ getCurrentEnv: () => getCurrentEnv2,
72
+ getEnv: () => getEnv
73
+ });
74
+ function getEnv(envName, settings) {
75
+ var _a;
76
+ const mainEnv = (_a = settings.config.environments) == null ? void 0 : _a[envName];
77
+ if (mainEnv) {
78
+ return {
79
+ ...mainEnv,
80
+ ...settings.environments[envName]
81
+ };
82
+ }
83
+ throw new TaqError(`There is no environment configured called ${envName}`);
84
+ }
85
+ var getCurrentEnv2 = (settings) => {
86
+ if (settings.config.environmentDefault) {
87
+ return getEnv(settings.config.environmentDefault, settings);
88
+ }
89
+ throw new TaqError(
90
+ `No default environment has been configured. Please set the "environmentDefault" property in your .taq/config.json.`
91
+ );
92
+ };
93
+ function getContractAddress(contractName, env) {
94
+ var _a, _b;
95
+ return (_b = (_a = env.contracts) == null ? void 0 : _a[contractName]) == null ? void 0 : _b.address;
96
+ }
97
+
98
+ // index.ts
99
+ var transform = __toESM(require("@taqueria/protocol/types-config-files"));
100
+ var DEFAULT_ENV_VAR_PREFIX = "";
101
+ function withEnv(env, prefix = DEFAULT_ENV_VAR_PREFIX) {
102
+ const getConfigEnvKey = () => `${prefix}TAQ_CONFIG`;
103
+ const getRawConfig = () => {
104
+ const key = getConfigEnvKey();
105
+ const data = env[key];
106
+ if (!data) {
107
+ throw new TaqError(
108
+ `Could not find config. Please ensure that the environment variable called ${key} is defined and set to the value of your config.json file using Base64 encoding.`
109
+ );
110
+ }
111
+ try {
112
+ const decoded = atob(data);
113
+ const rawConfig = JSON.parse(decoded);
114
+ return rawConfig;
115
+ } catch (e) {
116
+ throw new TaqError(
117
+ `Could not parse the config. Please ensure that the environment variable called ${key} is defined and set to the value of your config.json file using Base64 encoding.`
118
+ );
119
+ }
120
+ };
121
+ const getEnvironmentConfigKey = (environmentName) => `${prefix}TAQ_CONFIG_LOCAL_${environmentName.toUpperCase()}`;
122
+ const getEnvironmentConfig = (environmentName) => {
123
+ const key = getEnvironmentConfigKey(environmentName);
124
+ const data = env[key];
125
+ if (!data) {
126
+ return ConfigEnvironmentFileV2.from({});
127
+ }
128
+ try {
129
+ const decoded = atob(data);
130
+ const rawConfig = JSON.parse(decoded);
131
+ return ConfigEnvironmentFileV2.from(rawConfig);
132
+ } catch (e) {
133
+ throw new TaqError(
134
+ `Could not parse environment config for an environment called ${environmentName}. Please ensure that the environment variable called ${key} is defined and set to the value of your config.json file using Base64 encoding.`
135
+ );
136
+ }
137
+ };
138
+ return {
139
+ getConfigEnvKey,
140
+ getRawConfig,
141
+ getEnvironmentConfigKey,
142
+ getEnvironmentConfig
143
+ };
144
+ }
145
+ var getConfigAsV1 = (env, prefix = DEFAULT_ENV_VAR_PREFIX) => {
146
+ var _a;
147
+ const { getRawConfig, getEnvironmentConfig } = withEnv(env, prefix);
148
+ const rawConfig = getRawConfig();
149
+ try {
150
+ if (!rawConfig.version || rawConfig.version.toLowerCase() === "v1")
151
+ return Config.from(rawConfig);
152
+ else if (rawConfig.version.toLowerCase() === "v2") {
153
+ const config = ConfigFileV2.from(rawConfig);
154
+ const environments = Object.keys((_a = config.environments) != null ? _a : {}).reduce(
155
+ (retval, envName) => ({
156
+ ...retval,
157
+ [envName]: getEnvironmentConfig(envName)
158
+ }),
159
+ {}
160
+ );
161
+ return Config.create(transform.transformConfigFileV2ToConfig({
162
+ config,
163
+ environments
164
+ }));
165
+ }
166
+ throw new TaqError(`The version of your configuration is not yet supported.`);
167
+ } catch (err) {
168
+ throw isTaqError(err) ? err : new TaqError(
169
+ `Something went wrong trying to parse your configuration. Please report this to the Taqueria Developers: ${err}`
170
+ );
171
+ }
172
+ };
173
+ function getConfigV2(env, prefix = DEFAULT_ENV_VAR_PREFIX) {
174
+ var _a;
175
+ const { getRawConfig, getEnvironmentConfig } = withEnv(env, prefix);
176
+ const rawConfig = getRawConfig();
177
+ try {
178
+ if (!rawConfig.version || rawConfig.version.toLowerCase() === "v1") {
179
+ const configV1 = Config.from(rawConfig);
180
+ return transform.transformConfigToConfigFileV2(configV1);
181
+ } else if (rawConfig.version.toLowerCase() === "v2") {
182
+ const configV2 = ConfigFileV2.from(rawConfig);
183
+ const environments = Object.keys((_a = configV2.environments) != null ? _a : {}).reduce(
184
+ (retval2, envName) => ({ ...retval2, [envName]: getEnvironmentConfig(envName) }),
185
+ {}
186
+ );
187
+ const retval = {
188
+ config: configV2,
189
+ environments
190
+ };
191
+ return retval;
192
+ }
193
+ throw new TaqError(`The version of your configuration is not yet supported.`);
194
+ } catch (err) {
195
+ throw isTaqError(err) ? err : new TaqError(
196
+ `Something went wrong trying to parse your configuration. Please report this to the Taqueria Developers: ${err}`
197
+ );
198
+ }
199
+ }
200
+ var getAliasAddress2 = getAliasAddress;
201
+ var getCurrentEnv3 = getCurrentEnv;
202
+ //# sourceMappingURL=index.js.map
package/index.js.map CHANGED
@@ -1,7 +1 @@
1
- {
2
- "version": 3,
3
- "sources": ["index.ts"],
4
- "sourcesContent": ["import * as Config from '@taqueria/protocol/Config';\nimport * as Environment from '@taqueria/protocol/Environment';\n\n// Copied from state package\n// const getProjectAbsPath = async (search = './'): Promise<string> => {\n// \tconst dir = resolve(search);\n\n// \t// If we've reached / or c:\\, then give up\n// \tif (/^(\\/|[A-Z]:\\\\?)$/.test(dir)) {\n// \t\tthrow 'Could not find project directory';\n// \t}\n\n// \tconst filename = join(dir, '.taq', 'config.json');\n// \ttry {\n// \t\tconst exists = await stat(filename);\n\n// \t\t// TODO: Will this work on Windows?\n// \t\t// ... I might need to use .taq\\config.json\n// \t\treturn filename.replace('.taq/config.json', '');\n// \t} catch {\n// \t\t// TODO: Will this work on Windows?\n// \t\t// I might need to do ..\\\n// \t\treturn await getProjectAbsPath(join(dir, '../'));\n// \t}\n// };\n\n// Copied from state package\n// const getConfig = async (projectAbspath: string): Promise<Config.t> => {\n// \ttry {\n// \t\tconst configAbspath = join(projectAbspath, '.taq', 'config.json');\n// \t\tconst contents = await readFile(configAbspath, 'utf-8');\n// \t\tconst unvalided = JSON.parse(contents);\n// \t\treturn Config.create(unvalided);\n// \t} catch {\n// \t\tthrow 'Could not load .taq/config.json';\n// \t}\n// };\n\n// const sendErr = (msg: string, newline = true) => {\n// \tif (!msg || msg.length === 0) return;\n// \treturn newline\n// \t\t? console.error(msg)\n// \t\t: process.stderr.write(msg) as unknown as void;\n// };\n\n// const getConfigJSON = async (): Promise<Config.t> => {\n// \tconst projectAbspath = await getProjectAbsPath();\n// \tconst config = await getConfig(projectAbspath);\n// \treturn config;\n// };\n\nconst getCurrentEnv = (config: Config.t): Environment.t | undefined => {\n\tconst currentEnv = config?.environment?.default ? config.environment.default as string : 'development';\n\treturn config.environment && config.environment[currentEnv]\n\t\t? config.environment[currentEnv] as Environment.t | undefined\n\t\t: undefined;\n};\n\nexport const getAliasAddress = (config: any, alias: string): string => {\n\tconst currentEnv = getCurrentEnv(config);\n\tif (currentEnv?.aliases?.[alias]?.address) return currentEnv.aliases[alias].address;\n\talert(`Address for alias, ${alias}, is missing. Please deploy a contract with such alias`);\n\treturn '';\n};\n"],
5
- "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,qBAAAE,IAAA,eAAAC,EAAAH,GAmDA,IAAMI,EAAiBC,GAAgD,CAnDvE,IAAAC,EAoDC,IAAMC,GAAaD,EAAAD,GAAA,YAAAA,EAAQ,cAAR,MAAAC,EAAqB,QAAUD,EAAO,YAAY,QAAoB,cACzF,OAAOA,EAAO,aAAeA,EAAO,YAAYE,GAC7CF,EAAO,YAAYE,GACnB,MACJ,EAEaL,EAAkB,CAACG,EAAaG,IAA0B,CA1DvE,IAAAF,EAAAG,EA2DC,IAAMF,EAAaH,EAAcC,CAAM,EACvC,OAAII,GAAAH,EAAAC,GAAA,YAAAA,EAAY,UAAZ,YAAAD,EAAsBE,KAAtB,MAAAC,EAA8B,QAAgBF,EAAW,QAAQC,GAAO,SAC5E,MAAM,sBAAsBA,yDAA6D,EAClF,GACR",
6
- "names": ["taqueria_toolkit_exports", "__export", "getAliasAddress", "__toCommonJS", "getCurrentEnv", "config", "_a", "currentEnv", "alias", "_b"]
7
- }
1
+ {"version":3,"sources":["index.ts","TaqError.ts","v1.ts","v2.ts"],"sourcesContent":["import * as Config from '@taqueria/protocol/Config';\nimport * as ConfigEnvironmentFileV2 from '@taqueria/protocol/ConfigEnvironmentFileV2';\nimport * as ConfigFileV2 from '@taqueria/protocol/ConfigFileV2';\nimport { isTaqError, TaqError } from './TaqError';\nexport { isTaqError, TaqError } from './TaqError';\nimport * as V1 from './v1';\nexport * as V2 from './v2';\nimport * as transform from '@taqueria/protocol/types-config-files';\n\nconst DEFAULT_ENV_VAR_PREFIX = '';\n\nfunction withEnv(env: Record<string, string | undefined>, prefix = DEFAULT_ENV_VAR_PREFIX) {\n\tconst getConfigEnvKey = () => `${prefix}TAQ_CONFIG`;\n\n\tconst getRawConfig = () => {\n\t\tconst key = getConfigEnvKey();\n\t\tconst data = env[key];\n\t\tif (!data) {\n\t\t\tthrow new TaqError(\n\t\t\t\t`Could not find config. Please ensure that the environment variable called ${key} is defined and set to the value of your config.json file using Base64 encoding.`,\n\t\t\t);\n\t\t}\n\t\ttry {\n\t\t\tconst decoded = atob(data);\n\t\t\tconst rawConfig = JSON.parse(decoded);\n\t\t\treturn rawConfig;\n\t\t} catch {\n\t\t\tthrow new TaqError(\n\t\t\t\t`Could not parse the config. Please ensure that the environment variable called ${key} is defined and set to the value of your config.json file using Base64 encoding.`,\n\t\t\t);\n\t\t}\n\t};\n\n\tconst getEnvironmentConfigKey = (environmentName: string) =>\n\t\t`${prefix}TAQ_CONFIG_LOCAL_${environmentName.toUpperCase()}`;\n\n\tconst getEnvironmentConfig = (environmentName: string) => {\n\t\tconst key = getEnvironmentConfigKey(environmentName);\n\t\tconst data = env[key];\n\t\tif (!data) {\n\t\t\treturn ConfigEnvironmentFileV2.from({});\n\t\t}\n\t\ttry {\n\t\t\tconst decoded = atob(data);\n\t\t\tconst rawConfig = JSON.parse(decoded);\n\t\t\treturn ConfigEnvironmentFileV2.from(rawConfig);\n\t\t} catch {\n\t\t\tthrow new TaqError(\n\t\t\t\t`Could not parse environment config for an environment called ${environmentName}. Please ensure that the environment variable called ${key} is defined and set to the value of your config.json file using Base64 encoding.`,\n\t\t\t);\n\t\t}\n\t};\n\n\treturn {\n\t\tgetConfigEnvKey,\n\t\tgetRawConfig,\n\t\tgetEnvironmentConfigKey,\n\t\tgetEnvironmentConfig,\n\t};\n}\n\nexport const getConfigAsV1 = (env: Record<string, string | undefined>, prefix = DEFAULT_ENV_VAR_PREFIX): Config.t => {\n\tconst { getRawConfig, getEnvironmentConfig } = withEnv(env, prefix);\n\n\tconst rawConfig = getRawConfig();\n\n\ttry {\n\t\t// If version v1, return the config object\n\t\tif (!rawConfig.version || rawConfig.version.toLowerCase() === 'v1') return Config.from(rawConfig);\n\t\t// If version v2, transform to V1 and return that\n\t\telse if (rawConfig.version.toLowerCase() === 'v2') {\n\t\t\tconst config = ConfigFileV2.from(rawConfig);\n\t\t\tconst environments = Object.keys(config.environments ?? {}).reduce(\n\t\t\t\t(retval, envName) => ({\n\t\t\t\t\t...retval,\n\t\t\t\t\t[envName]: getEnvironmentConfig(envName),\n\t\t\t\t}),\n\t\t\t\t{},\n\t\t\t);\n\n\t\t\treturn Config.create(transform.transformConfigFileV2ToConfig({\n\t\t\t\tconfig,\n\t\t\t\tenvironments,\n\t\t\t}));\n\t\t}\n\n\t\t// Other version handlers go here\n\t\tthrow new TaqError(`The version of your configuration is not yet supported.`);\n\t} catch (err) {\n\t\tthrow isTaqError(err)\n\t\t\t? err\n\t\t\t: new TaqError(\n\t\t\t\t`Something went wrong trying to parse your configuration. Please report this to the Taqueria Developers: ${err}`,\n\t\t\t);\n\t}\n};\n\nexport function getConfigV2(\n\tenv: Record<string, string | undefined>,\n\tprefix = DEFAULT_ENV_VAR_PREFIX,\n): transform.ConfigFileSetV2 {\n\tconst { getRawConfig, getEnvironmentConfig } = withEnv(env, prefix);\n\n\tconst rawConfig = getRawConfig();\n\n\ttry {\n\t\t// If version v1, return the config object\n\t\tif (!rawConfig.version || rawConfig.version.toLowerCase() === 'v1') {\n\t\t\tconst configV1 = Config.from(rawConfig);\n\t\t\treturn transform.transformConfigToConfigFileV2(configV1);\n\t\t} else if (rawConfig.version.toLowerCase() === 'v2') {\n\t\t\tconst configV2 = ConfigFileV2.from(rawConfig);\n\t\t\tconst environments = Object.keys(configV2.environments ?? {}).reduce(\n\t\t\t\t(retval, envName) => ({ ...retval, [envName]: getEnvironmentConfig(envName) }),\n\t\t\t\t{},\n\t\t\t);\n\t\t\tconst retval: transform.ConfigFileSetV2 = {\n\t\t\t\tconfig: configV2,\n\t\t\t\tenvironments,\n\t\t\t};\n\n\t\t\treturn retval;\n\t\t}\n\t\t// Other version handlers go here\n\t\t// No other versions we're aware of.\n\t\tthrow new TaqError(`The version of your configuration is not yet supported.`);\n\t} catch (err) {\n\t\tthrow isTaqError(err)\n\t\t\t? err\n\t\t\t: new TaqError(\n\t\t\t\t`Something went wrong trying to parse your configuration. Please report this to the Taqueria Developers: ${err}`,\n\t\t\t);\n\t}\n}\n\n// Backwards compatibility\n// Before introducing V1, the toolkit just exported these two functions\nconst getAliasAddress = V1.getAliasAddress;\nconst getCurrentEnv = V1.getCurrentEnv;\nexport { Config, getAliasAddress, getCurrentEnv };\n\n// New exports as of V2\nexport type ConfigFileSetV2 = transform.ConfigFileSetV2;\n","export class TaqError extends Error {\n\tpublic isTaqError = true;\n}\nexport const isTaqError = (err: unknown): err is TaqError =>\n\ttypeof err === 'object' && (err as object).hasOwnProperty('isTaqError');\n","import * as Config from '@taqueria/protocol/Config';\nimport * as Environment from '@taqueria/protocol/Environment';\n\nexport const getCurrentEnv = (config: Config.t): Environment.t | undefined => {\n\tconst currentEnv = config?.environment?.default ? config.environment.default as string : 'development';\n\treturn config.environment && config.environment[currentEnv]\n\t\t? config.environment[currentEnv] as Environment.t | undefined\n\t\t: undefined;\n};\n\nexport const getAliasAddress = (config: any, alias: string): string => {\n\tconst currentEnv = getCurrentEnv(config);\n\tif (currentEnv?.aliases?.[alias]?.address) return currentEnv.aliases[alias].address;\n\talert(`Address for alias, ${alias}, is missing. Please deploy a contract with such alias`);\n\treturn '';\n};\n","// TODO: Write a comprehensive API for V2\nimport * as ConfigEnvironmentFileV2 from '@taqueria/protocol/ConfigEnvironmentFileV2';\nimport * as Config from '@taqueria/protocol/ConfigFileV2';\nimport { ConfigFileSetV2 } from '@taqueria/protocol/types-config-files';\nimport { isTaqError, TaqError } from './TaqError';\n\ntype ExpandedEnv = Record<string, unknown> & ConfigEnvironmentFileV2.t & { __type: 'expandedEnv' };\nexport function getEnv(envName: string, settings: ConfigFileSetV2): ExpandedEnv {\n\tconst mainEnv = settings.config.environments?.[envName];\n\tif (mainEnv) {\n\t\treturn {\n\t\t\t...mainEnv,\n\t\t\t...settings.environments[envName],\n\t\t} as ExpandedEnv;\n\t}\n\tthrow new TaqError(`There is no environment configured called ${envName}`);\n}\n\nexport const getCurrentEnv = (settings: ConfigFileSetV2) => {\n\tif (settings.config.environmentDefault) {\n\t\treturn getEnv(settings.config.environmentDefault, settings);\n\t}\n\tthrow new TaqError(\n\t\t`No default environment has been configured. Please set the \"environmentDefault\" property in your .taq/config.json.`,\n\t);\n};\n\nexport function getContractAddress(contractName: string, env: ExpandedEnv) {\n\treturn env.contracts?.[contractName]?.address;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,yBAAAA;AAAA,EAAA;AAAA;AAAA,uBAAAC;AAAA,EAAA;AAAA;AAAA;AAAA,aAAwB;AACxB,8BAAyC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 -1,64 +1,143 @@
1
1
  import * as Config from '@taqueria/protocol/Config';
2
- import * as Environment from '@taqueria/protocol/Environment';
3
-
4
- // Copied from state package
5
- // const getProjectAbsPath = async (search = './'): Promise<string> => {
6
- // const dir = resolve(search);
7
-
8
- // // If we've reached / or c:\, then give up
9
- // if (/^(\/|[A-Z]:\\?)$/.test(dir)) {
10
- // throw 'Could not find project directory';
11
- // }
12
-
13
- // const filename = join(dir, '.taq', 'config.json');
14
- // try {
15
- // const exists = await stat(filename);
16
-
17
- // // TODO: Will this work on Windows?
18
- // // ... I might need to use .taq\config.json
19
- // return filename.replace('.taq/config.json', '');
20
- // } catch {
21
- // // TODO: Will this work on Windows?
22
- // // I might need to do ..\
23
- // return await getProjectAbsPath(join(dir, '../'));
24
- // }
25
- // };
26
-
27
- // Copied from state package
28
- // const getConfig = async (projectAbspath: string): Promise<Config.t> => {
29
- // try {
30
- // const configAbspath = join(projectAbspath, '.taq', 'config.json');
31
- // const contents = await readFile(configAbspath, 'utf-8');
32
- // const unvalided = JSON.parse(contents);
33
- // return Config.create(unvalided);
34
- // } catch {
35
- // throw 'Could not load .taq/config.json';
36
- // }
37
- // };
38
-
39
- // const sendErr = (msg: string, newline = true) => {
40
- // if (!msg || msg.length === 0) return;
41
- // return newline
42
- // ? console.error(msg)
43
- // : process.stderr.write(msg) as unknown as void;
44
- // };
45
-
46
- // const getConfigJSON = async (): Promise<Config.t> => {
47
- // const projectAbspath = await getProjectAbsPath();
48
- // const config = await getConfig(projectAbspath);
49
- // return config;
50
- // };
51
-
52
- const getCurrentEnv = (config: Config.t): Environment.t | undefined => {
53
- const currentEnv = config?.environment?.default ? config.environment.default as string : 'development';
54
- return config.environment && config.environment[currentEnv]
55
- ? config.environment[currentEnv] as Environment.t | undefined
56
- : undefined;
57
- };
2
+ import * as ConfigEnvironmentFileV2 from '@taqueria/protocol/ConfigEnvironmentFileV2';
3
+ import * as ConfigFileV2 from '@taqueria/protocol/ConfigFileV2';
4
+ import { isTaqError, TaqError } from './TaqError';
5
+ export { isTaqError, TaqError } from './TaqError';
6
+ import * as V1 from './v1';
7
+ export * as V2 from './v2';
8
+ import * as transform from '@taqueria/protocol/types-config-files';
9
+
10
+ const DEFAULT_ENV_VAR_PREFIX = '';
11
+
12
+ function withEnv(env: Record<string, string | undefined>, prefix = DEFAULT_ENV_VAR_PREFIX) {
13
+ const getConfigEnvKey = () => `${prefix}TAQ_CONFIG`;
14
+
15
+ const getRawConfig = () => {
16
+ const key = getConfigEnvKey();
17
+ const data = env[key];
18
+ if (!data) {
19
+ throw new TaqError(
20
+ `Could not find config. Please ensure that the environment variable called ${key} is defined and set to the value of your config.json file using Base64 encoding.`,
21
+ );
22
+ }
23
+ try {
24
+ const decoded = atob(data);
25
+ const rawConfig = JSON.parse(decoded);
26
+ return rawConfig;
27
+ } catch {
28
+ throw new TaqError(
29
+ `Could not parse the config. Please ensure that the environment variable called ${key} is defined and set to the value of your config.json file using Base64 encoding.`,
30
+ );
31
+ }
32
+ };
33
+
34
+ const getEnvironmentConfigKey = (environmentName: string) =>
35
+ `${prefix}TAQ_CONFIG_LOCAL_${environmentName.toUpperCase()}`;
36
+
37
+ const getEnvironmentConfig = (environmentName: string) => {
38
+ const key = getEnvironmentConfigKey(environmentName);
39
+ const data = env[key];
40
+ if (!data) {
41
+ return ConfigEnvironmentFileV2.from({});
42
+ }
43
+ try {
44
+ const decoded = atob(data);
45
+ const rawConfig = JSON.parse(decoded);
46
+ return ConfigEnvironmentFileV2.from(rawConfig);
47
+ } catch {
48
+ throw new TaqError(
49
+ `Could not parse environment config for an environment called ${environmentName}. Please ensure that the environment variable called ${key} is defined and set to the value of your config.json file using Base64 encoding.`,
50
+ );
51
+ }
52
+ };
53
+
54
+ return {
55
+ getConfigEnvKey,
56
+ getRawConfig,
57
+ getEnvironmentConfigKey,
58
+ getEnvironmentConfig,
59
+ };
60
+ }
61
+
62
+ export const getConfigAsV1 = (env: Record<string, string | undefined>, prefix = DEFAULT_ENV_VAR_PREFIX): Config.t => {
63
+ const { getRawConfig, getEnvironmentConfig } = withEnv(env, prefix);
64
+
65
+ const rawConfig = getRawConfig();
58
66
 
59
- export const getAliasAddress = (config: any, alias: string): string => {
60
- const currentEnv = getCurrentEnv(config);
61
- if (currentEnv?.aliases?.[alias]?.address) return currentEnv.aliases[alias].address;
62
- alert(`Address for alias, ${alias}, is missing. Please deploy a contract with such alias`);
63
- return '';
67
+ try {
68
+ // If version v1, return the config object
69
+ if (!rawConfig.version || rawConfig.version.toLowerCase() === 'v1') return Config.from(rawConfig);
70
+ // If version v2, transform to V1 and return that
71
+ else if (rawConfig.version.toLowerCase() === 'v2') {
72
+ const config = ConfigFileV2.from(rawConfig);
73
+ const environments = Object.keys(config.environments ?? {}).reduce(
74
+ (retval, envName) => ({
75
+ ...retval,
76
+ [envName]: getEnvironmentConfig(envName),
77
+ }),
78
+ {},
79
+ );
80
+
81
+ return Config.create(transform.transformConfigFileV2ToConfig({
82
+ config,
83
+ environments,
84
+ }));
85
+ }
86
+
87
+ // Other version handlers go here
88
+ throw new TaqError(`The version of your configuration is not yet supported.`);
89
+ } catch (err) {
90
+ throw isTaqError(err)
91
+ ? err
92
+ : new TaqError(
93
+ `Something went wrong trying to parse your configuration. Please report this to the Taqueria Developers: ${err}`,
94
+ );
95
+ }
64
96
  };
97
+
98
+ export function getConfigV2(
99
+ env: Record<string, string | undefined>,
100
+ prefix = DEFAULT_ENV_VAR_PREFIX,
101
+ ): transform.ConfigFileSetV2 {
102
+ const { getRawConfig, getEnvironmentConfig } = withEnv(env, prefix);
103
+
104
+ const rawConfig = getRawConfig();
105
+
106
+ try {
107
+ // If version v1, return the config object
108
+ if (!rawConfig.version || rawConfig.version.toLowerCase() === 'v1') {
109
+ const configV1 = Config.from(rawConfig);
110
+ return transform.transformConfigToConfigFileV2(configV1);
111
+ } else if (rawConfig.version.toLowerCase() === 'v2') {
112
+ const configV2 = ConfigFileV2.from(rawConfig);
113
+ const environments = Object.keys(configV2.environments ?? {}).reduce(
114
+ (retval, envName) => ({ ...retval, [envName]: getEnvironmentConfig(envName) }),
115
+ {},
116
+ );
117
+ const retval: transform.ConfigFileSetV2 = {
118
+ config: configV2,
119
+ environments,
120
+ };
121
+
122
+ return retval;
123
+ }
124
+ // Other version handlers go here
125
+ // No other versions we're aware of.
126
+ throw new TaqError(`The version of your configuration is not yet supported.`);
127
+ } catch (err) {
128
+ throw isTaqError(err)
129
+ ? err
130
+ : new TaqError(
131
+ `Something went wrong trying to parse your configuration. Please report this to the Taqueria Developers: ${err}`,
132
+ );
133
+ }
134
+ }
135
+
136
+ // Backwards compatibility
137
+ // Before introducing V1, the toolkit just exported these two functions
138
+ const getAliasAddress = V1.getAliasAddress;
139
+ const getCurrentEnv = V1.getCurrentEnv;
140
+ export { Config, getAliasAddress, getCurrentEnv };
141
+
142
+ // New exports as of V2
143
+ export type ConfigFileSetV2 = transform.ConfigFileSetV2;
package/package.json CHANGED
@@ -1,18 +1,14 @@
1
1
  {
2
2
  "name": "@taqueria/toolkit",
3
- "version": "0.27.2-alpha",
3
+ "version": "0.27.2-rc",
4
4
  "description": "A TypeScript library for NodeJS to work with Taqueria projects",
5
- "main": "./index.js",
6
5
  "source": "./index.ts",
7
- "targets": {
8
- "main": {
9
- "context": "node",
10
- "isLibrary": true
11
- }
6
+ "bin": {
7
+ "withTaq": "./bin/run.js"
12
8
  },
13
9
  "scripts": {
14
10
  "test": "echo \"Error: no test specified\" && exit 1",
15
- "build": "npx tsc -p ./tsconfig.json && npx esbuild --bundle ./index.ts --outfile=./index.js --minify --platform=node --sourcemap --target=es6"
11
+ "build": "npx tsc -p ./tsconfig.json && npx tsup"
16
12
  },
17
13
  "types": "./index.d.ts",
18
14
  "keywords": [
@@ -33,8 +29,42 @@
33
29
  },
34
30
  "homepage": "https://github.com/ecadlabs/taqueria#readme",
35
31
  "devDependencies": {
32
+ "@types/cross-spawn": "^6.0.2",
36
33
  "@types/node": "^17.0.12",
37
- "esbuild": "^0.14.39",
34
+ "@types/yargs": "^17.0.19",
35
+ "tsup": "^6.5.0",
38
36
  "typescript": "^4.7.2"
39
- }
37
+ },
38
+ "dependencies": {
39
+ "@taqueria/protocol": "^0.27.2-rc",
40
+ "cross-spawn": "^7.0.3",
41
+ "yargs": "^17.6.2"
42
+ },
43
+ "tsup": [
44
+ {
45
+ "entry": [
46
+ "index.ts"
47
+ ],
48
+ "sourcemap": true,
49
+ "target": "es2018",
50
+ "outDir": "./",
51
+ "dts": true,
52
+ "clean": false,
53
+ "shims": true,
54
+ "skipNodeModulesBundle": false,
55
+ "platform": "browser"
56
+ },
57
+ {
58
+ "entry": [
59
+ "bin/run.ts"
60
+ ],
61
+ "sourcemap": true,
62
+ "target": "node16",
63
+ "outDir": "./bin/",
64
+ "dts": false,
65
+ "clean": false,
66
+ "skipNodeModulesBundle": true,
67
+ "platform": "node"
68
+ }
69
+ ]
40
70
  }
package/tsconfig.json CHANGED
@@ -11,7 +11,7 @@
11
11
  // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
12
12
 
13
13
  /* Language and Environment */
14
- "target": "ES6", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
14
+ "target": "ES2019", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
15
15
  // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
16
16
  // "jsx": "preserve", /* Specify what JSX code is generated. */
17
17
  // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
package/v1.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ import * as Config from '@taqueria/protocol/Config';
2
+ import * as Environment from '@taqueria/protocol/Environment';
3
+ export declare const getCurrentEnv: (config: Config.t) => Environment.t | undefined;
4
+ export declare const getAliasAddress: (config: any, alias: string) => string;
package/v1.ts ADDED
@@ -0,0 +1,16 @@
1
+ import * as Config from '@taqueria/protocol/Config';
2
+ import * as Environment from '@taqueria/protocol/Environment';
3
+
4
+ export const getCurrentEnv = (config: Config.t): Environment.t | undefined => {
5
+ const currentEnv = config?.environment?.default ? config.environment.default as string : 'development';
6
+ return config.environment && config.environment[currentEnv]
7
+ ? config.environment[currentEnv] as Environment.t | undefined
8
+ : undefined;
9
+ };
10
+
11
+ export const getAliasAddress = (config: any, alias: string): string => {
12
+ const currentEnv = getCurrentEnv(config);
13
+ if (currentEnv?.aliases?.[alias]?.address) return currentEnv.aliases[alias].address;
14
+ alert(`Address for alias, ${alias}, is missing. Please deploy a contract with such alias`);
15
+ return '';
16
+ };
package/v2.d.ts ADDED
@@ -0,0 +1,9 @@
1
+ import * as ConfigEnvironmentFileV2 from '@taqueria/protocol/ConfigEnvironmentFileV2';
2
+ import { ConfigFileSetV2 } from '@taqueria/protocol/types-config-files';
3
+ type ExpandedEnv = Record<string, unknown> & ConfigEnvironmentFileV2.t & {
4
+ __type: 'expandedEnv';
5
+ };
6
+ export declare function getEnv(envName: string, settings: ConfigFileSetV2): ExpandedEnv;
7
+ export declare const getCurrentEnv: (settings: ConfigFileSetV2) => ExpandedEnv;
8
+ export declare function getContractAddress(contractName: string, env: ExpandedEnv): string | undefined;
9
+ export {};
package/v2.ts ADDED
@@ -0,0 +1,30 @@
1
+ // TODO: Write a comprehensive API for V2
2
+ import * as ConfigEnvironmentFileV2 from '@taqueria/protocol/ConfigEnvironmentFileV2';
3
+ import * as Config from '@taqueria/protocol/ConfigFileV2';
4
+ import { ConfigFileSetV2 } from '@taqueria/protocol/types-config-files';
5
+ import { isTaqError, TaqError } from './TaqError';
6
+
7
+ type ExpandedEnv = Record<string, unknown> & ConfigEnvironmentFileV2.t & { __type: 'expandedEnv' };
8
+ export function getEnv(envName: string, settings: ConfigFileSetV2): ExpandedEnv {
9
+ const mainEnv = settings.config.environments?.[envName];
10
+ if (mainEnv) {
11
+ return {
12
+ ...mainEnv,
13
+ ...settings.environments[envName],
14
+ } as ExpandedEnv;
15
+ }
16
+ throw new TaqError(`There is no environment configured called ${envName}`);
17
+ }
18
+
19
+ export const getCurrentEnv = (settings: ConfigFileSetV2) => {
20
+ if (settings.config.environmentDefault) {
21
+ return getEnv(settings.config.environmentDefault, settings);
22
+ }
23
+ throw new TaqError(
24
+ `No default environment has been configured. Please set the "environmentDefault" property in your .taq/config.json.`,
25
+ );
26
+ };
27
+
28
+ export function getContractAddress(contractName: string, env: ExpandedEnv) {
29
+ return env.contracts?.[contractName]?.address;
30
+ }