ic-mops 0.19.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/.gitignore +3 -0
  2. package/{cache.js → cache.ts} +8 -8
  3. package/{cli.js → cli.ts} +5 -5
  4. package/commands/{add.js → add.ts} +16 -8
  5. package/commands/{bump.js → bump.ts} +5 -5
  6. package/commands/{docs.js → docs.ts} +10 -10
  7. package/commands/{import-identity.js → import-identity.ts} +7 -7
  8. package/commands/{init.js → init.ts} +20 -17
  9. package/commands/{install-all.js → install-all.ts} +1 -1
  10. package/commands/{install.js → install.ts} +11 -11
  11. package/commands/{mmf1.js → mmf1.ts} +20 -18
  12. package/commands/{publish.js → publish.ts} +28 -15
  13. package/commands/{remove.js → remove.ts} +23 -16
  14. package/commands/{search.js → search.ts} +2 -2
  15. package/commands/self-update.ts +6 -0
  16. package/commands/{sources.js → sources.ts} +30 -24
  17. package/commands/{template.js → template.ts} +2 -2
  18. package/commands/{test.js → test.ts} +24 -19
  19. package/commands/{user.js → user.ts} +7 -2
  20. package/declarations/main/index.js +0 -2
  21. package/declarations/main/main.did +4 -1
  22. package/declarations/main/main.did.d.ts +4 -4
  23. package/declarations/main/main.did.js +20 -20
  24. package/declarations/storage/index.d.ts +50 -0
  25. package/declarations/storage/index.js +3 -11
  26. package/dist/cache.d.ts +5 -0
  27. package/dist/cache.js +46 -0
  28. package/dist/cli.d.ts +2 -0
  29. package/dist/cli.js +265 -0
  30. package/dist/commands/add.d.ts +4 -0
  31. package/dist/commands/add.js +82 -0
  32. package/dist/commands/bump.d.ts +1 -0
  33. package/dist/commands/bump.js +50 -0
  34. package/dist/commands/docs.d.ts +3 -0
  35. package/dist/commands/docs.js +78 -0
  36. package/dist/commands/import-identity.d.ts +1 -0
  37. package/dist/commands/import-identity.js +47 -0
  38. package/dist/commands/init.d.ts +1 -0
  39. package/dist/commands/init.js +82 -0
  40. package/dist/commands/install-all.d.ts +4 -0
  41. package/dist/commands/install-all.js +29 -0
  42. package/dist/commands/install.d.ts +5 -0
  43. package/dist/commands/install.js +110 -0
  44. package/dist/commands/mmf1.d.ts +21 -0
  45. package/dist/commands/mmf1.js +93 -0
  46. package/dist/commands/publish.d.ts +3 -0
  47. package/dist/commands/publish.js +254 -0
  48. package/dist/commands/remove.d.ts +5 -0
  49. package/dist/commands/remove.js +83 -0
  50. package/dist/commands/search.d.ts +1 -0
  51. package/dist/commands/search.js +36 -0
  52. package/dist/commands/self-update.d.ts +3 -0
  53. package/dist/commands/self-update.js +5 -0
  54. package/dist/commands/sources.d.ts +3 -0
  55. package/dist/commands/sources.js +124 -0
  56. package/dist/commands/template.d.ts +1 -0
  57. package/dist/commands/template.js +28 -0
  58. package/dist/commands/test.d.ts +4 -0
  59. package/dist/commands/test.js +201 -0
  60. package/dist/commands/user.d.ts +2 -0
  61. package/dist/commands/user.js +23 -0
  62. package/dist/commands/whoami.d.ts +1 -0
  63. package/dist/commands/whoami.js +11 -0
  64. package/dist/declarations/main/index.d.ts +50 -0
  65. package/dist/declarations/main/index.js +41 -0
  66. package/dist/declarations/main/main.did +222 -0
  67. package/dist/declarations/main/main.did.d.ts +198 -0
  68. package/dist/declarations/main/main.did.js +218 -0
  69. package/dist/declarations/storage/index.d.ts +50 -0
  70. package/dist/declarations/storage/index.js +30 -0
  71. package/dist/declarations/storage/storage.did +46 -0
  72. package/dist/declarations/storage/storage.did.d.ts +37 -0
  73. package/dist/declarations/storage/storage.did.js +38 -0
  74. package/dist/mops.d.ts +33 -0
  75. package/dist/mops.js +259 -0
  76. package/dist/package.json +79 -0
  77. package/dist/parallel.d.ts +1 -0
  78. package/dist/parallel.js +24 -0
  79. package/dist/pem.d.ts +5 -0
  80. package/dist/pem.js +49 -0
  81. package/dist/templates/mops-test.yml +30 -0
  82. package/dist/types.d.ts +27 -0
  83. package/dist/types.js +1 -0
  84. package/dist/vessel.d.ts +19 -0
  85. package/dist/vessel.js +154 -0
  86. package/global.d.ts +2 -0
  87. package/{mops.js → mops.ts} +58 -47
  88. package/package.json +44 -19
  89. package/{parallel.js → parallel.ts} +2 -2
  90. package/{pem.js → pem.ts} +12 -11
  91. package/templates/mops-test.yml +1 -1
  92. package/tsconfig.json +16 -0
  93. package/types.ts +29 -0
  94. package/{vessel.js → vessel.ts} +37 -25
  95. package/commands/self-update.js +0 -6
  96. /package/commands/{whoami.js → whoami.ts} +0 -0
@@ -0,0 +1,124 @@
1
+ import path from 'node:path';
2
+ import fs from 'node:fs';
3
+ import chalk from 'chalk';
4
+ import { checkConfigFile, formatDir, formatGithubDir, parseGithubURL, readConfig } from '../mops.js';
5
+ import { readVesselConfig } from '../vessel.js';
6
+ // TODO: resolve conflicts
7
+ export async function sources({ verbose = false } = {}) {
8
+ if (!checkConfigFile()) {
9
+ return [];
10
+ }
11
+ let packages = {};
12
+ let versions = {};
13
+ let compareVersions = (a = '0.0.0', b = '0.0.0') => {
14
+ let ap = a.split('.').map((x) => parseInt(x));
15
+ let bp = b.split('.').map((x) => parseInt(x));
16
+ if (ap[0] - bp[0]) {
17
+ return Math.sign(ap[0] - bp[0]);
18
+ }
19
+ if (ap[0] === bp[0] && ap[1] - bp[1]) {
20
+ return Math.sign(ap[1] - bp[1]);
21
+ }
22
+ if (ap[0] === bp[0] && ap[1] === bp[1] && ap[2] - bp[2]) {
23
+ return Math.sign(ap[2] - bp[2]);
24
+ }
25
+ return 0;
26
+ };
27
+ const gitVerRegex = new RegExp(/v(\d{1,2}\.\d{1,2}\.\d{1,2})(-.*)?$/);
28
+ const compareGitVersions = (repoA, repoB) => {
29
+ const { branch: a } = parseGithubURL(repoA);
30
+ const { branch: b } = parseGithubURL(repoB);
31
+ if (gitVerRegex.test(a) && gitVerRegex.test(b)) {
32
+ return compareVersions(a.substring(1), b.substring(1));
33
+ }
34
+ else if (!gitVerRegex.test(a)) {
35
+ return -1;
36
+ }
37
+ else {
38
+ return 1;
39
+ }
40
+ };
41
+ let collectDeps = async (config, isRoot = false) => {
42
+ let allDeps = [...Object.values(config.dependencies || {})];
43
+ if (isRoot) {
44
+ allDeps = [...allDeps, ...Object.values(config['dev-dependencies'] || {})];
45
+ }
46
+ for (const pkgDetails of allDeps) {
47
+ const { name, repo, version } = pkgDetails;
48
+ // take root dep version or bigger one
49
+ if (isRoot
50
+ || !packages[name]
51
+ || !packages[name]?.isRoot
52
+ && (repo && packages[name]?.repo && compareGitVersions(packages[name]?.repo || '', repo) === -1
53
+ || compareVersions(packages[name]?.version, version) === -1)) {
54
+ packages[name] = {
55
+ ...pkgDetails,
56
+ isRoot,
57
+ };
58
+ }
59
+ let nestedConfig;
60
+ if (repo) {
61
+ const dir = formatGithubDir(name, repo);
62
+ nestedConfig = await readVesselConfig(dir) || {};
63
+ }
64
+ else if (!pkgDetails.path && version) {
65
+ const file = formatDir(name, version) + '/mops.toml';
66
+ nestedConfig = readConfig(file);
67
+ }
68
+ if (nestedConfig && !pkgDetails.path) {
69
+ await collectDeps(nestedConfig);
70
+ }
71
+ if (!versions[name]) {
72
+ versions[name] = [];
73
+ }
74
+ if (repo) {
75
+ const { branch } = parseGithubURL(repo);
76
+ versions[name]?.push(branch);
77
+ }
78
+ else if (version) {
79
+ versions[name]?.push(version);
80
+ }
81
+ }
82
+ };
83
+ let config = readConfig();
84
+ await collectDeps(config, true);
85
+ // show conflicts
86
+ if (verbose) {
87
+ for (let [dep, vers] of Object.entries(versions)) {
88
+ if (vers.length > 1) {
89
+ console.log(chalk.yellow('WARN:'), `Conflicting package versions "${dep}" - ${vers.join(', ')}`);
90
+ }
91
+ }
92
+ }
93
+ // sources
94
+ return Object.entries(packages).map(([name, pkg]) => {
95
+ let pkgDir;
96
+ if (pkg.path) {
97
+ pkgDir = path.relative(process.cwd(), path.resolve(pkg.path));
98
+ pkgDir = pkgDir.replaceAll('{MOPS_ENV}', process.env.MOPS_ENV || 'local');
99
+ }
100
+ else if (pkg.repo) {
101
+ pkgDir = path.relative(process.cwd(), formatGithubDir(name, pkg.repo));
102
+ }
103
+ else if (pkg.version) {
104
+ pkgDir = path.relative(process.cwd(), formatDir(name, pkg.version));
105
+ }
106
+ else {
107
+ return;
108
+ }
109
+ // append baseDir
110
+ let pkgBaseDir;
111
+ if (fs.existsSync(path.join(pkgDir, 'mops.toml'))) {
112
+ let config = readConfig(path.join(pkgDir, 'mops.toml'));
113
+ pkgBaseDir = path.join(pkgDir, config.package?.baseDir || 'src');
114
+ }
115
+ else {
116
+ pkgBaseDir = path.join(pkgDir, 'src');
117
+ }
118
+ // use pkgDir if baseDir doesn't exist for local packages
119
+ if (pkg.path && !fs.existsSync(pkgBaseDir)) {
120
+ pkgBaseDir = pkgDir;
121
+ }
122
+ return `--package ${name} ${pkgBaseDir}`;
123
+ });
124
+ }
@@ -0,0 +1 @@
1
+ export declare function template(): Promise<void>;
@@ -0,0 +1,28 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import chalk from 'chalk';
4
+ import prompts from 'prompts';
5
+ import { getRootDir } from '../mops.js';
6
+ export async function template() {
7
+ let res = await prompts({
8
+ type: 'select',
9
+ name: 'value',
10
+ message: 'Select template:',
11
+ choices: [
12
+ { title: 'GitHub Workflow to run \'mops test\'', value: 'github-workflow:mops-test' },
13
+ { title: '× Cancel', value: '' },
14
+ ],
15
+ initial: 0,
16
+ });
17
+ if (res.value === 'github-workflow:mops-test') {
18
+ let dest = path.resolve(getRootDir(), '.github/workflows/mops-test.yml');
19
+ if (fs.existsSync(dest)) {
20
+ console.log(chalk.yellow('Workflow already exists:'), dest);
21
+ return;
22
+ }
23
+ let mopsTestYml = new URL('../templates/mops-test.yml', import.meta.url);
24
+ fs.mkdirSync(path.resolve(getRootDir(), '.github/workflows'), { recursive: true });
25
+ fs.copyFileSync(mopsTestYml, dest);
26
+ console.log(chalk.green('Workflow created:'), dest);
27
+ }
28
+ }
@@ -0,0 +1,4 @@
1
+ export declare function test(filter?: string, { watch }?: {
2
+ watch?: boolean | undefined;
3
+ }): Promise<void>;
4
+ export declare function runAll(filter?: string): Promise<boolean | undefined>;
@@ -0,0 +1,201 @@
1
+ import { spawn, execSync } from 'node:child_process';
2
+ import path from 'node:path';
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import chalk from 'chalk';
6
+ import { globSync } from 'glob';
7
+ import chokidar from 'chokidar';
8
+ import debounce from 'debounce';
9
+ import { MMF1 } from './mmf1.js';
10
+ import { sources } from './sources.js';
11
+ import { getRootDir } from '../mops.js';
12
+ import { parallel } from '../parallel.js';
13
+ let ignore = [
14
+ '**/node_modules/**',
15
+ '**/.mops/**',
16
+ '**/.vessel/**',
17
+ '**/.git/**',
18
+ ];
19
+ let globConfig = {
20
+ nocase: true,
21
+ ignore: ignore,
22
+ };
23
+ export async function test(filter = '', { watch = false } = {}) {
24
+ let rootDir = getRootDir();
25
+ if (watch) {
26
+ // todo: run only changed for *.test.mo?
27
+ // todo: run all for *.mo?
28
+ let run = debounce(async () => {
29
+ console.clear();
30
+ process.stdout.write('\x1Bc');
31
+ await runAll(filter);
32
+ console.log('-'.repeat(50));
33
+ console.log('Waiting for file changes...');
34
+ console.log(chalk.gray((`Press ${chalk.gray('Ctrl+C')} to exit.`)));
35
+ }, 200);
36
+ let watcher = chokidar.watch([
37
+ path.join(rootDir, '**/*.mo'),
38
+ path.join(rootDir, 'mops.toml'),
39
+ ], {
40
+ ignored: ignore,
41
+ ignoreInitial: true,
42
+ });
43
+ watcher.on('all', () => {
44
+ run();
45
+ });
46
+ run();
47
+ }
48
+ else {
49
+ let passed = await runAll(filter);
50
+ if (!passed) {
51
+ process.exit(1);
52
+ }
53
+ }
54
+ }
55
+ let mocPath = process.env.DFX_MOC_PATH;
56
+ export async function runAll(filter = '') {
57
+ let start = Date.now();
58
+ let rootDir = getRootDir();
59
+ let files = [];
60
+ let libFiles = globSync('**/test?(s)/lib.mo', globConfig);
61
+ if (libFiles[0]) {
62
+ files = [libFiles[0]];
63
+ }
64
+ else {
65
+ let globStr = '**/test?(s)/**/*.test.mo';
66
+ if (filter) {
67
+ globStr = `**/test?(s)/**/*${filter}*.mo`;
68
+ }
69
+ files = globSync(path.join(rootDir, globStr), globConfig);
70
+ }
71
+ if (!files.length) {
72
+ if (filter) {
73
+ console.log(`No test files found for filter '${filter}'`);
74
+ return;
75
+ }
76
+ console.log('No test files found');
77
+ console.log('Put your tests in \'test\' directory in *.test.mo files');
78
+ return;
79
+ }
80
+ console.log('Test files:');
81
+ for (let file of files) {
82
+ console.log(chalk.gray(`• ${absToRel(file)}`));
83
+ }
84
+ console.log('='.repeat(50));
85
+ let failed = 0;
86
+ let passed = 0;
87
+ let skipped = 0;
88
+ let sourcesArr = await sources();
89
+ if (!mocPath) {
90
+ mocPath = execSync('dfx cache show').toString().trim() + '/moc';
91
+ }
92
+ let wasmDir = `${getRootDir()}/.mops/.test/`;
93
+ fs.mkdirSync(wasmDir, { recursive: true });
94
+ let i = 0;
95
+ await parallel(os.cpus().length, files, async (file) => {
96
+ if (!mocPath) {
97
+ mocPath = 'moc';
98
+ }
99
+ let mmf = new MMF1('store');
100
+ let wasiMode = fs.readFileSync(file, 'utf8').startsWith('// @testmode wasi');
101
+ let mocArgs = ['--hide-warnings', '--error-detail=2', ...sourcesArr.join(' ').split(' '), file].filter(x => x);
102
+ // build and run wasm
103
+ if (wasiMode) {
104
+ let wasmFile = `${path.join(wasmDir, path.parse(file).name)}.wasm`;
105
+ // build
106
+ let buildProc = spawn(mocPath, [`-o=${wasmFile}`, '-wasi-system-api', ...mocArgs]);
107
+ await pipeMMF(buildProc, mmf).then(async () => {
108
+ if (mmf.failed > 0) {
109
+ return;
110
+ }
111
+ // run
112
+ let proc = spawn('wasmtime', [wasmFile]);
113
+ await pipeMMF(proc, mmf);
114
+ }).finally(() => {
115
+ fs.rmSync(wasmFile, { force: true });
116
+ });
117
+ }
118
+ // interpret
119
+ else {
120
+ let proc = spawn(mocPath, ['-r', '-ref-system-api', ...mocArgs]);
121
+ await pipeMMF(proc, mmf);
122
+ }
123
+ passed += mmf.passed;
124
+ failed += mmf.failed;
125
+ skipped += mmf.skipped;
126
+ i++ && console.log('-'.repeat(50));
127
+ console.log(`Running ${chalk.gray(path.relative(rootDir, file))} ${wasiMode ? chalk.gray('(wasi)') : ''}`);
128
+ mmf.flush();
129
+ });
130
+ fs.rmSync(wasmDir, { recursive: true, force: true });
131
+ console.log('='.repeat(50));
132
+ if (failed) {
133
+ console.log(chalk.redBright('Tests failed'));
134
+ }
135
+ else {
136
+ console.log(chalk.greenBright('Tests passed'));
137
+ }
138
+ console.log(`Done in ${chalk.gray(((Date.now() - start) / 1000).toFixed(2) + 's')}`
139
+ + `, passed ${chalk.greenBright(passed)}`
140
+ + (skipped ? `, skipped ${chalk[skipped ? 'yellowBright' : 'gray'](skipped)}` : '')
141
+ + (failed ? `, failed ${chalk[failed ? 'redBright' : 'gray'](failed)}` : ''));
142
+ return failed === 0;
143
+ }
144
+ function absToRel(p) {
145
+ let rootDir = getRootDir();
146
+ return path.relative(rootDir, path.resolve(p));
147
+ }
148
+ function pipeMMF(proc, mmf) {
149
+ return new Promise((resolve) => {
150
+ // stdout
151
+ proc.stdout.on('data', (data) => {
152
+ for (let line of data.toString().split('\n')) {
153
+ line = line.trim();
154
+ if (line) {
155
+ mmf.parseLine(line);
156
+ }
157
+ }
158
+ });
159
+ // stderr
160
+ proc.stderr.on('data', (data) => {
161
+ let text = data.toString().trim();
162
+ let failedLine = '';
163
+ text = text.replace(/([\w+._/-]+):(\d+).(\d+)(-\d+.\d+)/g, (_m0, m1, m2, m3) => {
164
+ // change absolute file path to relative
165
+ // change :line:col-line:col to :line:col to work in vscode
166
+ let res = `${absToRel(m1)}:${m2}:${m3}`;
167
+ if (!fs.existsSync(m1)) {
168
+ return res;
169
+ }
170
+ // show failed line
171
+ let content = fs.readFileSync(m1);
172
+ let lines = content.toString().split('\n') || [];
173
+ failedLine += chalk.dim `\n ...`;
174
+ let lineBefore = lines[+m2 - 2];
175
+ if (lineBefore) {
176
+ failedLine += chalk.dim `\n ${+m2 - 1}\t| ${lineBefore.replaceAll('\t', ' ')}`;
177
+ }
178
+ failedLine += `\n${chalk.redBright `->`} ${m2}\t| ${lines[+m2 - 1]?.replaceAll('\t', ' ')}`;
179
+ if (lines.length > +m2) {
180
+ failedLine += chalk.dim `\n ${+m2 + 1}\t| ${lines[+m2]?.replaceAll('\t', ' ')}`;
181
+ }
182
+ failedLine += chalk.dim `\n ...`;
183
+ return res;
184
+ });
185
+ if (failedLine) {
186
+ text += failedLine;
187
+ }
188
+ mmf.fail(text);
189
+ });
190
+ // exit
191
+ proc.on('close', (code) => {
192
+ if (code === 0) {
193
+ mmf.pass();
194
+ }
195
+ else if (code !== 1) {
196
+ mmf.fail(`unknown exit code: ${code}`);
197
+ }
198
+ resolve(mmf);
199
+ });
200
+ });
201
+ }
@@ -0,0 +1,2 @@
1
+ export declare function getUserProp(prop: string): Promise<void>;
2
+ export declare function setUserProp(prop: string, value: string): Promise<void>;
@@ -0,0 +1,23 @@
1
+ import chalk from 'chalk';
2
+ import { getIdentity, mainActor } from '../mops.js';
3
+ export async function getUserProp(prop) {
4
+ let actor = await mainActor();
5
+ let identity = await getIdentity();
6
+ if (!identity) {
7
+ console.log(chalk.red('Error: ') + 'No identity found');
8
+ process.exit(1);
9
+ }
10
+ let res = await actor.getUser(identity.getPrincipal());
11
+ // @ts-ignore
12
+ console.log(res[0]?.[prop] || '');
13
+ }
14
+ export async function setUserProp(prop, value) {
15
+ let actor = await mainActor(true);
16
+ let res = await actor.setUserProp(prop, value);
17
+ if ('ok' in res) {
18
+ console.log(chalk.green('Success!'));
19
+ }
20
+ else {
21
+ console.log(chalk.red('Error: ') + res.err);
22
+ }
23
+ }
@@ -0,0 +1 @@
1
+ export declare function whoami(): Promise<void>;
@@ -0,0 +1,11 @@
1
+ import chalk from 'chalk';
2
+ import { getIdentity } from '../mops.js';
3
+ export async function whoami() {
4
+ let identity = await getIdentity();
5
+ if (identity) {
6
+ console.log(identity.getPrincipal().toText());
7
+ }
8
+ else {
9
+ console.log(chalk.red('Error: ') + 'identity not found. Run ' + chalk.greenBright('mops import-identity') + ' command.');
10
+ }
11
+ }
@@ -0,0 +1,50 @@
1
+ import type {
2
+ ActorSubclass,
3
+ HttpAgentOptions,
4
+ ActorConfig,
5
+ Agent,
6
+ } from "@dfinity/agent";
7
+ import type { Principal } from "@dfinity/principal";
8
+ import type { IDL } from "@dfinity/candid";
9
+
10
+ import { _SERVICE } from './main.did';
11
+
12
+ export declare const idlFactory: IDL.InterfaceFactory;
13
+ export declare const canisterId: string;
14
+
15
+ export declare interface CreateActorOptions {
16
+ /**
17
+ * @see {@link Agent}
18
+ */
19
+ agent?: Agent;
20
+ /**
21
+ * @see {@link HttpAgentOptions}
22
+ */
23
+ agentOptions?: HttpAgentOptions;
24
+ /**
25
+ * @see {@link ActorConfig}
26
+ */
27
+ actorOptions?: ActorConfig;
28
+ }
29
+
30
+ /**
31
+ * Intializes an {@link ActorSubclass}, configured with the provided SERVICE interface of a canister.
32
+ * @constructs {@link ActorSubClass}
33
+ * @param {string | Principal} canisterId - ID of the canister the {@link Actor} will talk to
34
+ * @param {CreateActorOptions} options - see {@link CreateActorOptions}
35
+ * @param {CreateActorOptions["agent"]} options.agent - a pre-configured agent you'd like to use. Supercedes agentOptions
36
+ * @param {CreateActorOptions["agentOptions"]} options.agentOptions - options to set up a new agent
37
+ * @see {@link HttpAgentOptions}
38
+ * @param {CreateActorOptions["actorOptions"]} options.actorOptions - options for the Actor
39
+ * @see {@link ActorConfig}
40
+ */
41
+ export declare const createActor: (
42
+ canisterId: string | Principal,
43
+ options?: CreateActorOptions
44
+ ) => ActorSubclass<_SERVICE>;
45
+
46
+ /**
47
+ * Intialized Actor using default settings, ready to talk to a canister using its candid interface
48
+ * @constructs {@link ActorSubClass}
49
+ */
50
+ export declare const main: ActorSubclass<_SERVICE>;
@@ -0,0 +1,41 @@
1
+ import { Actor, HttpAgent } from "@dfinity/agent";
2
+
3
+ // Imports and re-exports candid interface
4
+ import { idlFactory } from "./main.did.js";
5
+ export { idlFactory } from "./main.did.js";
6
+
7
+ /* CANISTER_ID is replaced by webpack based on node environment
8
+ * Note: canister environment variable will be standardized as
9
+ * process.env.CANISTER_ID_<CANISTER_NAME_UPPERCASE>
10
+ * beginning in dfx 0.15.0
11
+ */
12
+ export const canisterId =
13
+ process.env.CANISTER_ID_MAIN ||
14
+ process.env.MAIN_CANISTER_ID;
15
+
16
+ export const createActor = (canisterId, options = {}) => {
17
+ const agent = options.agent || new HttpAgent({ ...options.agentOptions });
18
+
19
+ if (options.agent && options.agentOptions) {
20
+ console.warn(
21
+ "Detected both agent and agentOptions passed to createActor. Ignoring agentOptions and proceeding with the provided agent."
22
+ );
23
+ }
24
+
25
+ // Fetch root key for certificate validation during development
26
+ if (process.env.DFX_NETWORK !== "ic") {
27
+ agent.fetchRootKey().catch((err) => {
28
+ console.warn(
29
+ "Unable to fetch root key. Check to ensure that your local replica is running"
30
+ );
31
+ console.error(err);
32
+ });
33
+ }
34
+
35
+ // Creates an actor with using the candid interface and the HttpAgent
36
+ return Actor.createActor(idlFactory, {
37
+ agent,
38
+ canisterId,
39
+ ...options.actorOptions,
40
+ });
41
+ };