@taqueria/toolkit 0.25.22-rc → 0.25.29-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/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,KAA4B;AAClD,SAAO,OAAO,QAAQ,YAAa,IAAe,eAAe,aAAa;AAC/E;AAEA,eAAe,gBAAgB,KAAa;AAC3C,MAAI;AACH,UAAM,aAAa,YAAAC,QAAK,KAAK,KAAK,MAAM;AACxC,cAAM,uBAAK,UAAU;AACrB,WAAO;AAAA,EACR,QAAE;AACD,UAAM,IAAI,iBAAiB,GAAG,sCAAsC;AAAA,EACrE;AACD;AAEA,SAAS,cAAc,SAAmB,IAAwE;AACjH,MAAI,QAAQ,GAAG,SAAS,MAAM;AAAG,YAAQ,MAAM;AAE/C,QAAM,SAAS,QAAQ,MAAM;AAE7B,QAAM,iBAAa,aAAAC,SAAM,OAAO,EAC9B,OAAO,cAAc;AAAA,IACrB,OAAO;AAAA,IACP,MAAM;AAAA,IACN,aAAa;AAAA,EACd,CAAC,EACA,OAAO,UAAU;AAAA,IACjB,MAAM;AAAA,IACN,aAAa;AAAA,IACb,SAAS;AAAA,EACV,CAAC,EACA,OAAO,CAAC,YAAY,CAAC,EACrB,UAAU;AAEZ,MAAI,WAAW,EAAE,SAAS,KAAK,WAAW,YAAY;AACrD,OAAG,WAAW,YAAY,WAAW,QAAQ,WAAW,EAAE,KAAK,GAAG,CAAC;AAAA,EACpE;AAAO,YAAQ,IAAI,UAAU,gEAAgE;AAC9F;AAEA,SAAS,WAAW,UAAkB,SAAS,IAAI;AAClD,SAAO,GAAG,aAAa,WACrB,QAAQ,SAAS,EAAE,EACnB,QAAQ,QAAQ,GAAG,EACnB,QAAQ,QAAQ,GAAG,EACnB,YAAY;AACf;AAEA,IAAM,iBAAN,cAA6B,UAAU;AAAC;AACxC,eAAe,UAAU,QAAgB,QAAgB;AACxD,MAAI;AACH,UAAM,QAAQ,MAAM,gBAAAC,QAAG,QAAQ,MAAM;AACrC,WAAO,MAAM;AAAA,MACZ,OAAO,QAAQ,SAAS;AACvB,YAAI,CAAC,KAAK,SAAS,OAAO;AAAG,iBAAQ,MAAM;AAC3C,eAAO;AAAA,UACN,GAAI,MAAM;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,14 @@
1
- export declare const getAliasAddress: (config: any, alias: string) => string;
1
+ import * as _taqueria_protocol_types from '@taqueria/protocol/types';
2
+ import * as Config from '@taqueria/protocol/Config';
3
+ import * as Environment from '@taqueria/protocol/Environment';
4
+
5
+ declare class TaqError extends Error {
6
+ isTaqError: boolean;
7
+ }
8
+ declare const isTaqError: (err: unknown) => err is TaqError;
9
+ declare const loadFromEnv: (env: Record<string, string | undefined>, prefix?: string) => _taqueria_protocol_types.Config;
10
+
11
+ declare const getAliasAddress: (config: any, alias: string) => string;
12
+ declare const getCurrentEnv: (config: Config.t) => Environment.t | undefined;
13
+
14
+ export { TaqError, loadFromEnv as default, getAliasAddress, getCurrentEnv, isTaqError, loadFromEnv };
package/index.js CHANGED
@@ -1,2 +1,129 @@
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
+ TaqError: () => TaqError,
30
+ default: () => taqueria_toolkit_default,
31
+ getAliasAddress: () => getAliasAddress,
32
+ getCurrentEnv: () => getCurrentEnv,
33
+ isTaqError: () => isTaqError,
34
+ loadFromEnv: () => loadFromEnv
35
+ });
36
+ module.exports = __toCommonJS(taqueria_toolkit_exports);
37
+ var Config = __toESM(require("@taqueria/protocol/Config"));
38
+ var ConfigEnvironmentFileV2 = __toESM(require("@taqueria/protocol/ConfigEnvironmentFileV2"));
39
+ var ConfigFileV2 = __toESM(require("@taqueria/protocol/ConfigFileV2"));
40
+ var import_types_config_files = require("@taqueria/protocol/types-config-files");
41
+ var V1 = () => {
42
+ const getCurrentEnv2 = (config) => {
43
+ var _a;
44
+ const currentEnv = ((_a = config == null ? void 0 : config.environment) == null ? void 0 : _a.default) ? config.environment.default : "development";
45
+ return config.environment && config.environment[currentEnv] ? config.environment[currentEnv] : void 0;
46
+ };
47
+ const getAliasAddress2 = (config, alias) => {
48
+ var _a, _b;
49
+ const currentEnv = getCurrentEnv2(config);
50
+ if ((_b = (_a = currentEnv == null ? void 0 : currentEnv.aliases) == null ? void 0 : _a[alias]) == null ? void 0 : _b.address)
51
+ return currentEnv.aliases[alias].address;
52
+ alert(`Address for alias, ${alias}, is missing. Please deploy a contract with such alias`);
53
+ return "";
54
+ };
55
+ return {
56
+ getCurrentEnv: getCurrentEnv2,
57
+ getAliasAddress: getAliasAddress2
58
+ };
59
+ };
60
+ var TaqError = class extends Error {
61
+ constructor() {
62
+ super(...arguments);
63
+ this.isTaqError = true;
64
+ }
65
+ };
66
+ var isTaqError = (err) => typeof err === "object" && err.hasOwnProperty("isTaqError");
67
+ var loadFromEnv = (env, prefix = "REACT_APP_") => {
68
+ const getConfigEnvKey = () => `${prefix}TAQ_CONFIG`;
69
+ const getConfig = () => {
70
+ var _a;
71
+ const key = getConfigEnvKey();
72
+ const data = env[key];
73
+ if (!data) {
74
+ throw new TaqError(
75
+ `Could not load config. Please ensure that the environment variable called ${key} is defined and set to the value of your config.json file using Base64 encoding.`
76
+ );
77
+ }
78
+ try {
79
+ const decoded = atob(data);
80
+ const rawConfig = JSON.parse(decoded);
81
+ if (!rawConfig.version || rawConfig.version === "v1")
82
+ return Config.from(rawConfig);
83
+ else if (rawConfig.version === "v2") {
84
+ const config = ConfigFileV2.from(rawConfig);
85
+ const environments = Object.keys((_a = config.environments) != null ? _a : {}).reduce(
86
+ (retval, envName) => ({
87
+ ...retval,
88
+ [envName]: getEnvironmentConfig(envName)
89
+ }),
90
+ {}
91
+ );
92
+ return (0, import_types_config_files.transformConfigFileV2ToConfig)({
93
+ config,
94
+ environments
95
+ });
96
+ }
97
+ throw data;
98
+ } catch (err) {
99
+ throw isTaqError(err) ? err : new TaqError(
100
+ `Could not parse config. Please ensure that the environment variable called ${key} is defined and set to the value of your config.json using Base64 encoding`
101
+ );
102
+ }
103
+ };
104
+ const getEnvironmentConfigKey = (environmentName) => `${prefix}TAQ_CONFIG_LOCAL_${environmentName.toUpperCase()}`;
105
+ const getEnvironmentConfig = (environmentName) => {
106
+ const key = getEnvironmentConfigKey(environmentName);
107
+ const data = env[key];
108
+ if (!data) {
109
+ throw new TaqError(
110
+ `Could not load 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.`
111
+ );
112
+ }
113
+ try {
114
+ const decoded = atob(data);
115
+ const rawConfig = JSON.parse(decoded);
116
+ return ConfigEnvironmentFileV2.from(rawConfig);
117
+ } catch (e) {
118
+ throw new TaqError(
119
+ `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.`
120
+ );
121
+ }
122
+ };
123
+ return getConfig();
124
+ };
125
+ var taqueria_toolkit_default = loadFromEnv;
126
+ var v1 = V1();
127
+ var getAliasAddress = v1.getAliasAddress;
128
+ var getCurrentEnv = v1.getCurrentEnv;
129
+ //# 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"],"sourcesContent":["import * as Config from '@taqueria/protocol/Config';\nimport * as ConfigEnvironmentFileV2 from '@taqueria/protocol/ConfigEnvironmentFileV2';\nimport * as ConfigFileV2 from '@taqueria/protocol/ConfigFileV2';\nimport * as Environment from '@taqueria/protocol/Environment';\nimport { transformConfigFileV2ToConfig } from '@taqueria/protocol/types-config-files';\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 V1 = () => {\n\tconst getCurrentEnv = (config: Config.t): Environment.t | undefined => {\n\t\tconst currentEnv = config?.environment?.default ? config.environment.default as string : 'development';\n\t\treturn config.environment && config.environment[currentEnv]\n\t\t\t? config.environment[currentEnv] as Environment.t | undefined\n\t\t\t: undefined;\n\t};\n\n\tconst getAliasAddress = (config: any, alias: string): string => {\n\t\tconst currentEnv = getCurrentEnv(config);\n\t\tif (currentEnv?.aliases?.[alias]?.address) return currentEnv.aliases[alias].address;\n\t\talert(`Address for alias, ${alias}, is missing. Please deploy a contract with such alias`);\n\t\treturn '';\n\t};\n\n\treturn {\n\t\tgetCurrentEnv,\n\t\tgetAliasAddress,\n\t};\n};\n\nexport 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\nexport const loadFromEnv = (env: Record<string, string | undefined>, prefix = 'REACT_APP_') => {\n\tconst getConfigEnvKey = () => `${prefix}TAQ_CONFIG`;\n\n\tconst getConfig = () => {\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 load 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\n\t\t\t// If version v1, return the config object\n\t\t\tif (!rawConfig.version || rawConfig.version === 'v1') return Config.from(rawConfig);\n\t\t\t// If version v2, return the ConfigFileV2 object\n\t\t\telse if (rawConfig.version === 'v2') {\n\t\t\t\tconst config = ConfigFileV2.from(rawConfig);\n\t\t\t\tconst environments = Object.keys(config.environments ?? {}).reduce(\n\t\t\t\t\t(retval, envName) => ({\n\t\t\t\t\t\t...retval,\n\t\t\t\t\t\t[envName]: getEnvironmentConfig(envName),\n\t\t\t\t\t}),\n\t\t\t\t\t{},\n\t\t\t\t);\n\t\t\t\t// const expandedConfig = expandConfigV2(config)\n\t\t\t\treturn transformConfigFileV2ToConfig({\n\t\t\t\t\tconfig,\n\t\t\t\t\tenvironments,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// Other version handlers go here\n\n\t\t\t// No other versions we're aware of. Time to throw.\n\t\t\tthrow data;\n\t\t} catch (err) {\n\t\t\tthrow isTaqError(err)\n\t\t\t\t? err\n\t\t\t\t: new TaqError(\n\t\t\t\t\t`Could not parse config. Please ensure that the environment variable called ${key} is defined and set to the value of your config.json using Base64 encoding`,\n\t\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\tthrow new TaqError(\n\t\t\t\t`Could not load 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\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\t// const expandConfigV2 = (config: ConfigFileV2.t) => {\n\t// \treturn config.environments\n\t// \t\t?\tObject.entries(config.environments).reduce(\n\t// \t\t\t\t(retval, [envName, envConfig]) => ({\n\t// \t\t\t\t\t...config,\n\t// \t\t\t\t\tenvironments: {\n\t// \t\t\t\t\t\t...config.environments,\n\t// \t\t\t\t\t\t[envName]: {\n\t// \t\t\t\t\t\t\t...envConfig,\n\t// \t\t\t\t\t\t\t...getEnvironmentConfig(envName)\n\t// \t\t\t\t\t\t}\n\t// \t\t\t\t\t}\n\t// \t\t\t\t}),\n\t// \t\t\t\tconfig\n\t// \t\t\t)\n\t// \t\t: config\n\t// }\n\n\treturn getConfig();\n};\n\nexport default loadFromEnv;\n\nconst v1 = V1();\n\nexport const getAliasAddress = v1.getAliasAddress;\n\nexport const getCurrentEnv = v1.getCurrentEnv;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,aAAwB;AACxB,8BAAyC;AACzC,mBAA8B;AAE9B,gCAA8C;AAkD9C,IAAM,KAAK,MAAM;AAChB,QAAMA,iBAAgB,CAAC,WAAgD;AAvDxE;AAwDE,UAAM,eAAa,sCAAQ,gBAAR,mBAAqB,WAAU,OAAO,YAAY,UAAoB;AACzF,WAAO,OAAO,eAAe,OAAO,YAAY,cAC7C,OAAO,YAAY,cACnB;AAAA,EACJ;AAEA,QAAMC,mBAAkB,CAAC,QAAa,UAA0B;AA9DjE;AA+DE,UAAM,aAAaD,eAAc,MAAM;AACvC,SAAI,oDAAY,YAAZ,mBAAsB,WAAtB,mBAA8B;AAAS,aAAO,WAAW,QAAQ,OAAO;AAC5E,UAAM,sBAAsB,6DAA6D;AACzF,WAAO;AAAA,EACR;AAEA,SAAO;AAAA,IACN,eAAAA;AAAA,IACA,iBAAAC;AAAA,EACD;AACD;AAEO,IAAM,WAAN,cAAuB,MAAM;AAAA,EAA7B;AAAA;AACN,SAAO,aAAa;AAAA;AACrB;AACO,IAAM,aAAa,CAAC,QAC1B,OAAO,QAAQ,YAAa,IAAe,eAAe,YAAY;AAEhE,IAAM,cAAc,CAAC,KAAyC,SAAS,iBAAiB;AAC9F,QAAM,kBAAkB,MAAM,GAAG;AAEjC,QAAM,YAAY,MAAM;AApFzB;AAqFE,UAAM,MAAM,gBAAgB;AAC5B,UAAM,OAAO,IAAI;AACjB,QAAI,CAAC,MAAM;AACV,YAAM,IAAI;AAAA,QACT,6EAA6E;AAAA,MAC9E;AAAA,IACD;AACA,QAAI;AACH,YAAM,UAAU,KAAK,IAAI;AACzB,YAAM,YAAY,KAAK,MAAM,OAAO;AAGpC,UAAI,CAAC,UAAU,WAAW,UAAU,YAAY;AAAM,eAAc,YAAK,SAAS;AAAA,eAEzE,UAAU,YAAY,MAAM;AACpC,cAAM,SAAsB,kBAAK,SAAS;AAC1C,cAAM,eAAe,OAAO,MAAK,YAAO,iBAAP,YAAuB,CAAC,CAAC,EAAE;AAAA,UAC3D,CAAC,QAAQ,aAAa;AAAA,YACrB,GAAG;AAAA,YACH,CAAC,UAAU,qBAAqB,OAAO;AAAA,UACxC;AAAA,UACA,CAAC;AAAA,QACF;AAEA,mBAAO,yDAA8B;AAAA,UACpC;AAAA,UACA;AAAA,QACD,CAAC;AAAA,MACF;AAKA,YAAM;AAAA,IACP,SAAS,KAAP;AACD,YAAM,WAAW,GAAG,IACjB,MACA,IAAI;AAAA,QACL,8EAA8E;AAAA,MAC/E;AAAA,IACF;AAAA,EACD;AAEA,QAAM,0BAA0B,CAAC,oBAChC,GAAG,0BAA0B,gBAAgB,YAAY;AAE1D,QAAM,uBAAuB,CAAC,oBAA4B;AACzD,UAAM,MAAM,wBAAwB,eAAe;AACnD,UAAM,OAAO,IAAI;AACjB,QAAI,CAAC,MAAM;AACV,YAAM,IAAI;AAAA,QACT,+DAA+D,uEAAuE;AAAA,MACvI;AAAA,IACD;AACA,QAAI;AACH,YAAM,UAAU,KAAK,IAAI;AACzB,YAAM,YAAY,KAAK,MAAM,OAAO;AACpC,aAA+B,6BAAK,SAAS;AAAA,IAC9C,SAAQ,GAAN;AACD,YAAM,IAAI;AAAA,QACT,gEAAgE,uEAAuE;AAAA,MACxI;AAAA,IACD;AAAA,EACD;AAoBA,SAAO,UAAU;AAClB;AAEA,IAAO,2BAAQ;AAEf,IAAM,KAAK,GAAG;AAEP,IAAM,kBAAkB,GAAG;AAE3B,IAAM,gBAAgB,GAAG;","names":["getCurrentEnv","getAliasAddress"]}
package/index.ts CHANGED
@@ -1,5 +1,8 @@
1
1
  import * as Config from '@taqueria/protocol/Config';
2
+ import * as ConfigEnvironmentFileV2 from '@taqueria/protocol/ConfigEnvironmentFileV2';
3
+ import * as ConfigFileV2 from '@taqueria/protocol/ConfigFileV2';
2
4
  import * as Environment from '@taqueria/protocol/Environment';
5
+ import { transformConfigFileV2ToConfig } from '@taqueria/protocol/types-config-files';
3
6
 
4
7
  // Copied from state package
5
8
  // const getProjectAbsPath = async (search = './'): Promise<string> => {
@@ -49,16 +52,127 @@ import * as Environment from '@taqueria/protocol/Environment';
49
52
  // return config;
50
53
  // };
51
54
 
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;
55
+ const V1 = () => {
56
+ const getCurrentEnv = (config: Config.t): Environment.t | undefined => {
57
+ const currentEnv = config?.environment?.default ? config.environment.default as string : 'development';
58
+ return config.environment && config.environment[currentEnv]
59
+ ? config.environment[currentEnv] as Environment.t | undefined
60
+ : undefined;
61
+ };
62
+
63
+ const getAliasAddress = (config: any, alias: string): string => {
64
+ const currentEnv = getCurrentEnv(config);
65
+ if (currentEnv?.aliases?.[alias]?.address) return currentEnv.aliases[alias].address;
66
+ alert(`Address for alias, ${alias}, is missing. Please deploy a contract with such alias`);
67
+ return '';
68
+ };
69
+
70
+ return {
71
+ getCurrentEnv,
72
+ getAliasAddress,
73
+ };
57
74
  };
58
75
 
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 '';
76
+ export class TaqError extends Error {
77
+ public isTaqError = true;
78
+ }
79
+ export const isTaqError = (err: unknown): err is TaqError =>
80
+ typeof err === 'object' && (err as object).hasOwnProperty('isTaqError');
81
+
82
+ export const loadFromEnv = (env: Record<string, string | undefined>, prefix = 'REACT_APP_') => {
83
+ const getConfigEnvKey = () => `${prefix}TAQ_CONFIG`;
84
+
85
+ const getConfig = () => {
86
+ const key = getConfigEnvKey();
87
+ const data = env[key];
88
+ if (!data) {
89
+ throw new TaqError(
90
+ `Could not load config. Please ensure that the environment variable called ${key} is defined and set to the value of your config.json file using Base64 encoding.`,
91
+ );
92
+ }
93
+ try {
94
+ const decoded = atob(data);
95
+ const rawConfig = JSON.parse(decoded);
96
+
97
+ // If version v1, return the config object
98
+ if (!rawConfig.version || rawConfig.version === 'v1') return Config.from(rawConfig);
99
+ // If version v2, return the ConfigFileV2 object
100
+ else if (rawConfig.version === 'v2') {
101
+ const config = ConfigFileV2.from(rawConfig);
102
+ const environments = Object.keys(config.environments ?? {}).reduce(
103
+ (retval, envName) => ({
104
+ ...retval,
105
+ [envName]: getEnvironmentConfig(envName),
106
+ }),
107
+ {},
108
+ );
109
+ // const expandedConfig = expandConfigV2(config)
110
+ return transformConfigFileV2ToConfig({
111
+ config,
112
+ environments,
113
+ });
114
+ }
115
+
116
+ // Other version handlers go here
117
+
118
+ // No other versions we're aware of. Time to throw.
119
+ throw data;
120
+ } catch (err) {
121
+ throw isTaqError(err)
122
+ ? err
123
+ : new TaqError(
124
+ `Could not parse config. Please ensure that the environment variable called ${key} is defined and set to the value of your config.json using Base64 encoding`,
125
+ );
126
+ }
127
+ };
128
+
129
+ const getEnvironmentConfigKey = (environmentName: string) =>
130
+ `${prefix}TAQ_CONFIG_LOCAL_${environmentName.toUpperCase()}`;
131
+
132
+ const getEnvironmentConfig = (environmentName: string) => {
133
+ const key = getEnvironmentConfigKey(environmentName);
134
+ const data = env[key];
135
+ if (!data) {
136
+ throw new TaqError(
137
+ `Could not load 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.`,
138
+ );
139
+ }
140
+ try {
141
+ const decoded = atob(data);
142
+ const rawConfig = JSON.parse(decoded);
143
+ return ConfigEnvironmentFileV2.from(rawConfig);
144
+ } catch {
145
+ throw new TaqError(
146
+ `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.`,
147
+ );
148
+ }
149
+ };
150
+
151
+ // const expandConfigV2 = (config: ConfigFileV2.t) => {
152
+ // return config.environments
153
+ // ? Object.entries(config.environments).reduce(
154
+ // (retval, [envName, envConfig]) => ({
155
+ // ...config,
156
+ // environments: {
157
+ // ...config.environments,
158
+ // [envName]: {
159
+ // ...envConfig,
160
+ // ...getEnvironmentConfig(envName)
161
+ // }
162
+ // }
163
+ // }),
164
+ // config
165
+ // )
166
+ // : config
167
+ // }
168
+
169
+ return getConfig();
64
170
  };
171
+
172
+ export default loadFromEnv;
173
+
174
+ const v1 = V1();
175
+
176
+ export const getAliasAddress = v1.getAliasAddress;
177
+
178
+ export const getCurrentEnv = v1.getCurrentEnv;
package/package.json CHANGED
@@ -1,18 +1,14 @@
1
1
  {
2
2
  "name": "@taqueria/toolkit",
3
- "version": "0.25.22-rc",
3
+ "version": "0.25.29-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.25.29-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. */