ic-mops 0.22.0 → 0.24.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.
@@ -1,5 +1,3 @@
1
- type Version = text;
2
- type Ver = text;
3
1
  type User__1 =
4
2
  record {
5
3
  displayName: text;
@@ -48,7 +46,7 @@ type Result_6 =
48
46
  type Result_5 =
49
47
  variant {
50
48
  err: Err;
51
- ok: Ver;
49
+ ok: PackageVersion;
52
50
  };
53
51
  type Result_4 =
54
52
  variant {
@@ -78,6 +76,7 @@ type Result =
78
76
  type PublishingId = text;
79
77
  type PublishingErr = text;
80
78
  type PageCount = nat;
79
+ type PackageVersion = text;
81
80
  type PackageSummary__1 =
82
81
  record {
83
82
  config: PackageConfigV2__1;
@@ -186,20 +185,21 @@ service : {
186
185
  getAirdropAmount: () -> (nat) query;
187
186
  getAirdropAmountAll: () -> (nat) query;
188
187
  getApiVersion: () -> (Text) query;
189
- getDefaultPackages: (text) -> (vec record {
190
- PackageName__1;
191
- Version;
192
- }) query;
188
+ getDefaultPackages: (text) ->
189
+ (vec record {
190
+ PackageName__1;
191
+ PackageVersion;
192
+ }) query;
193
193
  getDownloadTrendByPackageId: (PackageId) ->
194
194
  (vec DownloadsSnapshot__1) query;
195
195
  getDownloadTrendByPackageName: (PackageName__1) ->
196
196
  (vec DownloadsSnapshot__1) query;
197
- getFileIds: (PackageName__1, Ver) -> (Result_6) query;
197
+ getFileIds: (PackageName__1, PackageVersion) -> (Result_6) query;
198
198
  getHighestVersion: (PackageName__1) -> (Result_5) query;
199
199
  getMostDownloadedPackages: () -> (vec PackageSummary) query;
200
200
  getMostDownloadedPackagesIn7Days: () -> (vec PackageSummary) query;
201
201
  getNewPackages: () -> (vec PackageSummary) query;
202
- getPackageDetails: (PackageName__1, Ver) -> (Result_4) query;
202
+ getPackageDetails: (PackageName__1, PackageVersion) -> (Result_4) query;
203
203
  getPackagesByCategory: () -> (vec record {
204
204
  text;
205
205
  vec PackageSummary;
@@ -212,7 +212,7 @@ service : {
212
212
  getTotalDownloads: () -> (nat) query;
213
213
  getTotalPackages: () -> (nat) query;
214
214
  getUser: (principal) -> (opt User__1) query;
215
- notifyInstall: (PackageName__1, Ver) -> () oneway;
215
+ notifyInstall: (PackageName__1, PackageVersion) -> () oneway;
216
216
  search: (Text, opt nat, opt nat) -> (vec PackageSummary, PageCount) query;
217
217
  setUserProp: (text, text) -> (Result_3);
218
218
  startFileUpload: (PublishingId, Text, nat, blob) -> (Result_2);
@@ -94,6 +94,7 @@ export interface PackageSummary__1 {
94
94
  'config' : PackageConfigV2__1,
95
95
  'publication' : PackagePublication,
96
96
  }
97
+ export type PackageVersion = string;
97
98
  export type PageCount = bigint;
98
99
  export type PublishingErr = string;
99
100
  export type PublishingId = string;
@@ -107,7 +108,7 @@ export type Result_3 = { 'ok' : null } |
107
108
  { 'err' : string };
108
109
  export type Result_4 = { 'ok' : PackageDetails } |
109
110
  { 'err' : Err };
110
- export type Result_5 = { 'ok' : Ver } |
111
+ export type Result_5 = { 'ok' : PackageVersion } |
111
112
  { 'err' : Err };
112
113
  export type Result_6 = { 'ok' : Array<FileId> } |
113
114
  { 'err' : Err };
@@ -144,8 +145,6 @@ export interface User__1 {
144
145
  'githubVerified' : boolean,
145
146
  'github' : string,
146
147
  }
147
- export type Ver = string;
148
- export type Version = string;
149
148
  export interface _SERVICE {
150
149
  'claimAirdrop' : ActorMethod<[Principal], string>,
151
150
  'finishPublish' : ActorMethod<[PublishingId], Result>,
@@ -154,7 +153,7 @@ export interface _SERVICE {
154
153
  'getApiVersion' : ActorMethod<[], Text>,
155
154
  'getDefaultPackages' : ActorMethod<
156
155
  [string],
157
- Array<[PackageName__1, Version]>
156
+ Array<[PackageName__1, PackageVersion]>
158
157
  >,
159
158
  'getDownloadTrendByPackageId' : ActorMethod<
160
159
  [PackageId],
@@ -164,12 +163,12 @@ export interface _SERVICE {
164
163
  [PackageName__1],
165
164
  Array<DownloadsSnapshot__1>
166
165
  >,
167
- 'getFileIds' : ActorMethod<[PackageName__1, Ver], Result_6>,
166
+ 'getFileIds' : ActorMethod<[PackageName__1, PackageVersion], Result_6>,
168
167
  'getHighestVersion' : ActorMethod<[PackageName__1], Result_5>,
169
168
  'getMostDownloadedPackages' : ActorMethod<[], Array<PackageSummary>>,
170
169
  'getMostDownloadedPackagesIn7Days' : ActorMethod<[], Array<PackageSummary>>,
171
170
  'getNewPackages' : ActorMethod<[], Array<PackageSummary>>,
172
- 'getPackageDetails' : ActorMethod<[PackageName__1, Ver], Result_4>,
171
+ 'getPackageDetails' : ActorMethod<[PackageName__1, PackageVersion], Result_4>,
173
172
  'getPackagesByCategory' : ActorMethod<
174
173
  [],
175
174
  Array<[string, Array<PackageSummary>]>
@@ -179,7 +178,7 @@ export interface _SERVICE {
179
178
  'getTotalDownloads' : ActorMethod<[], bigint>,
180
179
  'getTotalPackages' : ActorMethod<[], bigint>,
181
180
  'getUser' : ActorMethod<[Principal], [] | [User__1]>,
182
- 'notifyInstall' : ActorMethod<[PackageName__1, Ver], undefined>,
181
+ 'notifyInstall' : ActorMethod<[PackageName__1, PackageVersion], undefined>,
183
182
  'search' : ActorMethod<
184
183
  [Text, [] | [bigint], [] | [bigint]],
185
184
  [Array<PackageSummary>, PageCount]
@@ -4,7 +4,7 @@ export const idlFactory = ({ IDL }) => {
4
4
  const Result = IDL.Variant({ 'ok' : IDL.Null, 'err' : Err });
5
5
  const Text = IDL.Text;
6
6
  const PackageName__1 = IDL.Text;
7
- const Version = IDL.Text;
7
+ const PackageVersion = IDL.Text;
8
8
  const PackageId = IDL.Text;
9
9
  const Time = IDL.Int;
10
10
  const DownloadsSnapshot__1 = IDL.Record({
@@ -12,10 +12,9 @@ export const idlFactory = ({ IDL }) => {
12
12
  'endTime' : Time,
13
13
  'downloads' : IDL.Nat,
14
14
  });
15
- const Ver = IDL.Text;
16
15
  const FileId = IDL.Text;
17
16
  const Result_6 = IDL.Variant({ 'ok' : IDL.Vec(FileId), 'err' : Err });
18
- const Result_5 = IDL.Variant({ 'ok' : Ver, 'err' : Err });
17
+ const Result_5 = IDL.Variant({ 'ok' : PackageVersion, 'err' : Err });
19
18
  const User = IDL.Record({
20
19
  'id' : IDL.Principal,
21
20
  'emailVerified' : IDL.Bool,
@@ -145,7 +144,7 @@ export const idlFactory = ({ IDL }) => {
145
144
  'getApiVersion' : IDL.Func([], [Text], ['query']),
146
145
  'getDefaultPackages' : IDL.Func(
147
146
  [IDL.Text],
148
- [IDL.Vec(IDL.Tuple(PackageName__1, Version))],
147
+ [IDL.Vec(IDL.Tuple(PackageName__1, PackageVersion))],
149
148
  ['query'],
150
149
  ),
151
150
  'getDownloadTrendByPackageId' : IDL.Func(
@@ -158,7 +157,11 @@ export const idlFactory = ({ IDL }) => {
158
157
  [IDL.Vec(DownloadsSnapshot__1)],
159
158
  ['query'],
160
159
  ),
161
- 'getFileIds' : IDL.Func([PackageName__1, Ver], [Result_6], ['query']),
160
+ 'getFileIds' : IDL.Func(
161
+ [PackageName__1, PackageVersion],
162
+ [Result_6],
163
+ ['query'],
164
+ ),
162
165
  'getHighestVersion' : IDL.Func([PackageName__1], [Result_5], ['query']),
163
166
  'getMostDownloadedPackages' : IDL.Func(
164
167
  [],
@@ -172,7 +175,7 @@ export const idlFactory = ({ IDL }) => {
172
175
  ),
173
176
  'getNewPackages' : IDL.Func([], [IDL.Vec(PackageSummary)], ['query']),
174
177
  'getPackageDetails' : IDL.Func(
175
- [PackageName__1, Ver],
178
+ [PackageName__1, PackageVersion],
176
179
  [Result_4],
177
180
  ['query'],
178
181
  ),
@@ -194,7 +197,11 @@ export const idlFactory = ({ IDL }) => {
194
197
  'getTotalDownloads' : IDL.Func([], [IDL.Nat], ['query']),
195
198
  'getTotalPackages' : IDL.Func([], [IDL.Nat], ['query']),
196
199
  'getUser' : IDL.Func([IDL.Principal], [IDL.Opt(User__1)], ['query']),
197
- 'notifyInstall' : IDL.Func([PackageName__1, Ver], [], ['oneway']),
200
+ 'notifyInstall' : IDL.Func(
201
+ [PackageName__1, PackageVersion],
202
+ [],
203
+ ['oneway'],
204
+ ),
198
205
  'search' : IDL.Func(
199
206
  [Text, IDL.Opt(IDL.Nat), IDL.Opt(IDL.Nat)],
200
207
  [IDL.Vec(PackageSummary), PageCount],
package/dist/cli.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import fs from 'node:fs';
3
- import { program } from 'commander';
3
+ import { program, Argument } from 'commander';
4
4
  import chalk from 'chalk';
5
5
  import { Principal } from '@dfinity/principal';
6
6
  import { init } from './commands/init.js';
@@ -19,6 +19,7 @@ import { selfUpdate } from './commands/self-update.js';
19
19
  import { remove } from './commands/remove.js';
20
20
  import { getUserProp, setUserProp } from './commands/user.js';
21
21
  import { bump } from './commands/bump.js';
22
+ import { sync } from './commands/sync.js';
22
23
  // import {docs} from './commands/docs.js';
23
24
  program.name('mops');
24
25
  // --version
@@ -26,10 +27,11 @@ let packageJson = JSON.parse(fs.readFileSync(new URL('package.json', import.meta
26
27
  program.version(`CLI ${packageJson.version}\nAPI ${apiVersion}`, '-v --version');
27
28
  // init
28
29
  program
29
- .command('init [name]')
30
- .description('Create mops.toml')
31
- .action(async (name) => {
32
- await init(name);
30
+ .command('init')
31
+ .description('Initialize a new project or package in the current directory')
32
+ .option('-y, --yes', 'Accept all defaults')
33
+ .action(async (options) => {
34
+ await init(options);
33
35
  });
34
36
  // add
35
37
  program
@@ -98,7 +100,7 @@ program
98
100
  program
99
101
  .command('set-network <network>')
100
102
  .alias('sn')
101
- .description('Set network local|dev|ic')
103
+ .description('Set network local|staging|ic')
102
104
  .action(async (network) => {
103
105
  await setNetwork(network);
104
106
  console.log(`Selected '${network}' network`);
@@ -148,8 +150,9 @@ program
148
150
  });
149
151
  // cache
150
152
  program
151
- .command('cache [sub-command]')
153
+ .command('cache')
152
154
  .description('Manage cache')
155
+ .addArgument(new Argument('<sub>').choices(['size', 'clean']))
153
156
  .action(async (sub) => {
154
157
  if (sub == 'clean') {
155
158
  await cleanCache();
@@ -159,9 +162,6 @@ program
159
162
  let size = await cacheSize();
160
163
  console.log('Cache size is ' + size);
161
164
  }
162
- else {
163
- console.log('Unknown sub command. Available sub commands: clean, size');
164
- }
165
165
  });
166
166
  // test
167
167
  program
@@ -213,7 +213,10 @@ program
213
213
  });
214
214
  // user
215
215
  program
216
- .command('user set|get <prop> [value]')
216
+ .command('user')
217
+ .addArgument(new Argument('<sub>').choices(['set', 'get']))
218
+ .addArgument(new Argument('<prop>').choices(['name', 'site', 'email', 'github', 'twitter']))
219
+ .addArgument(new Argument('[value]'))
217
220
  .description('User settings')
218
221
  .action(async (sub, prop, value) => {
219
222
  if (sub == 'get') {
@@ -226,9 +229,6 @@ program
226
229
  }
227
230
  await setUserProp(prop, value);
228
231
  }
229
- else {
230
- console.log('Unknown sub command. Available sub commands: set, get');
231
- }
232
232
  });
233
233
  // airdrop
234
234
  program
@@ -268,4 +268,11 @@ program
268
268
  .action(async (part) => {
269
269
  bump(part);
270
270
  });
271
+ // sync
272
+ program
273
+ .command('sync')
274
+ .description('Add missing packages and remove unused packages')
275
+ .action(async () => {
276
+ await sync();
277
+ });
271
278
  program.parse();
@@ -1 +1,3 @@
1
- export declare function init(name?: string): Promise<void>;
1
+ export declare function init({ yes }?: {
2
+ yes?: boolean | undefined;
3
+ }): Promise<void>;
@@ -1,59 +1,169 @@
1
1
  import { execSync } from 'node:child_process';
2
2
  import path from 'node:path';
3
- import fs from 'node:fs';
3
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
4
4
  import chalk from 'chalk';
5
- import { checkApiCompatibility, mainActor, readDfxJson, writeConfig } from '../mops.js';
5
+ import prompts from 'prompts';
6
+ import { checkApiCompatibility, mainActor, writeConfig } from '../mops.js';
6
7
  import { installAll } from './install-all.js';
7
8
  import { readVesselConfig } from '../vessel.js';
8
- export async function init(name = '') {
9
+ import { template } from './template.js';
10
+ export async function init({ yes = false } = {}) {
9
11
  let configFile = path.join(process.cwd(), 'mops.toml');
10
- let exists = fs.existsSync(configFile);
12
+ let exists = existsSync(configFile);
11
13
  if (exists) {
12
14
  console.log(chalk.yellow('mops.toml already exists'));
13
15
  return;
14
16
  }
15
17
  console.log('Initializing...');
16
18
  let config = {};
19
+ if (yes) {
20
+ await applyInit({
21
+ type: 'project',
22
+ config,
23
+ setupWorkflow: true,
24
+ addTest: false,
25
+ copyrightOwner: '',
26
+ });
27
+ return;
28
+ }
29
+ // migrate from vessel
30
+ let vesselFile = path.join(process.cwd(), 'vessel.dhall');
17
31
  let vesselConfig = { dependencies: [], 'dev-dependencies': [] };
18
- let deps = {};
19
- const vesselFile = path.join(process.cwd(), 'vessel.dhall');
20
- if (fs.existsSync(vesselFile)) {
32
+ if (existsSync(vesselFile)) {
21
33
  console.log('Reading vessel.dhall file');
22
- const res = await readVesselConfig(process.cwd(), { cache: false });
34
+ let res = await readVesselConfig(process.cwd(), { cache: false });
23
35
  if (res) {
24
36
  vesselConfig = { ...res };
25
37
  }
26
38
  }
27
39
  if (vesselConfig.dependencies) {
40
+ let deps = {};
28
41
  deps = {};
29
42
  for (const dep of (vesselConfig.dependencies || [])) {
30
43
  deps[dep.name] = dep;
31
44
  }
45
+ if (Object.keys(deps).length) {
46
+ config.dependencies = deps;
47
+ }
32
48
  }
33
- // lib mode
34
- if (name) {
49
+ let promptsConfig = {
50
+ onCancel() {
51
+ console.log('aborted');
52
+ process.exit(0);
53
+ }
54
+ };
55
+ // type
56
+ let { type } = await prompts({
57
+ type: 'select',
58
+ name: 'type',
59
+ message: 'Select type:',
60
+ choices: [
61
+ { title: `Project ${chalk.dim('(I just want to use mops packages in my project)')}`, value: 'project' },
62
+ { title: `Package ${chalk.dim('(I plan to publish this package on mops)')}`, value: 'package' },
63
+ ],
64
+ }, promptsConfig);
65
+ let addTest = false;
66
+ let copyrightOwner = '';
67
+ // package details
68
+ if (type === 'package') {
69
+ let res = await prompts([
70
+ {
71
+ type: 'text',
72
+ name: 'name',
73
+ message: 'Enter package name:',
74
+ initial: '',
75
+ },
76
+ {
77
+ type: 'text',
78
+ name: 'description',
79
+ message: 'Enter package description:',
80
+ initial: '',
81
+ },
82
+ {
83
+ type: 'text',
84
+ name: 'repository',
85
+ message: 'Enter package repository url:',
86
+ initial: '',
87
+ },
88
+ {
89
+ type: 'text',
90
+ name: 'keywords',
91
+ message: 'Enter keywords separated by spaces:',
92
+ initial: '',
93
+ },
94
+ {
95
+ type: 'select',
96
+ name: 'license',
97
+ message: 'Choose a license:',
98
+ choices: [
99
+ { title: 'MIT', value: 'MIT' },
100
+ { title: 'Apache-2.0', value: 'Apache-2.0' },
101
+ ],
102
+ initial: 0,
103
+ },
104
+ {
105
+ type: 'text',
106
+ name: 'copyrightOwner',
107
+ message: 'Enter license copyright owner:',
108
+ initial: '',
109
+ },
110
+ {
111
+ type: 'confirm',
112
+ name: 'addTest',
113
+ message: `Add example test file? ${chalk.dim('(test/lib.test.mo)')}`,
114
+ initial: true,
115
+ },
116
+ ], promptsConfig);
35
117
  config.package = {
36
- name,
37
- version: '0.1.0',
38
- description: '',
39
- repository: '',
118
+ name: (res.name || '').trim(),
119
+ version: '1.0.0',
120
+ description: (res.description || '').trim(),
121
+ repository: (res.repository || '').trim(),
122
+ keywords: [...new Set(res.keywords.split(' ').filter(Boolean))],
123
+ license: (res.license || '').trim(),
40
124
  };
41
- if (deps) {
42
- config.dependencies = deps;
43
- }
44
- writeConfig(config, configFile);
45
- if (Object.keys(config.dependencies || {}).length) {
46
- await installAll({ verbose: true });
125
+ addTest = res.addTest;
126
+ copyrightOwner = res.copyrightOwner;
127
+ }
128
+ // GitHub workflow
129
+ let { setupWorkflow } = await prompts({
130
+ type: 'confirm',
131
+ name: 'setupWorkflow',
132
+ message: `Setup GitHub workflow? ${chalk.dim('(run `mops test` on push)')}`,
133
+ initial: true,
134
+ }, promptsConfig);
135
+ await applyInit({
136
+ type,
137
+ config,
138
+ setupWorkflow,
139
+ addTest,
140
+ copyrightOwner,
141
+ });
142
+ }
143
+ async function applyInit({ type, config, setupWorkflow, addTest, copyrightOwner }) {
144
+ // set packtool in dfx.json
145
+ let dfxJson = path.resolve(process.cwd(), 'dfx.json');
146
+ let dfxJsonData;
147
+ if (existsSync(dfxJson)) {
148
+ let dfxJsonText = readFileSync(dfxJson).toString();
149
+ dfxJsonData = JSON.parse(dfxJsonText);
150
+ console.log('Setting packtool in dfx.json...');
151
+ dfxJsonData.defaults = dfxJsonData.defaults || {};
152
+ dfxJsonData.defaults.build = dfxJsonData.defaults.build || {};
153
+ if (dfxJsonData.defaults.build.packtool !== 'mops sources') {
154
+ dfxJsonData.defaults.build.packtool = 'mops sources';
155
+ let indent = dfxJsonText.match(/([ \t]+)"/)?.[1] || ' ';
156
+ writeFileSync(path.join(process.cwd(), 'dfx.json'), JSON.stringify(dfxJsonData, null, indent));
157
+ console.log(chalk.green('packtool set to "mops sources"'));
47
158
  }
48
159
  }
49
- // project mode
50
- if (!name) {
160
+ // get default packages
161
+ if (type === 'project') {
51
162
  let compatible = await checkApiCompatibility();
52
163
  if (!compatible) {
53
164
  return;
54
165
  }
55
- let dfxJson = readDfxJson();
56
- let dfxVersion = dfxJson?.dfx || '';
166
+ let dfxVersion = dfxJsonData?.dfx || '';
57
167
  if (!dfxVersion) {
58
168
  try {
59
169
  let res = execSync('dfx --version').toString();
@@ -64,19 +174,54 @@ export async function init(name = '') {
64
174
  }
65
175
  catch { }
66
176
  }
177
+ console.log(`Fetching default packages for dfx ${dfxVersion}...`);
67
178
  let actor = await mainActor();
68
179
  let defaultPackages = await actor.getDefaultPackages(dfxVersion);
69
180
  if (!config.dependencies) {
70
181
  config.dependencies = {};
71
182
  }
72
- if (deps) {
73
- config.dependencies = deps;
74
- }
75
183
  for (let [name, version] of defaultPackages) {
76
184
  config.dependencies[name] = { name, version };
77
185
  }
78
- writeConfig(config, configFile);
186
+ }
187
+ // save config
188
+ let configFile = path.join(process.cwd(), 'mops.toml');
189
+ writeConfig(config, configFile);
190
+ console.log(chalk.green('Created'), 'mops.toml');
191
+ // add src/lib.mo
192
+ if (type === 'package' && !existsSync(path.join(process.cwd(), 'src'))) {
193
+ await template('lib.mo');
194
+ }
195
+ // add src/lib.test.mo
196
+ if (addTest && !existsSync(path.join(process.cwd(), 'test'))) {
197
+ await template('lib.test.mo');
198
+ }
199
+ // add license
200
+ if (config.package?.license) {
201
+ await template(`license:${config.package.license}`, { copyrightOwner });
202
+ }
203
+ // add readme
204
+ if (type === 'package') {
205
+ await template('readme');
206
+ }
207
+ // add GitHub workflow
208
+ if (setupWorkflow) {
209
+ await template('github-workflow:mops-test');
210
+ }
211
+ // add .mops to .gitignore
212
+ {
213
+ let gitignore = path.join(process.cwd(), '.gitignore');
214
+ let gitignoreData = existsSync(gitignore) ? readFileSync(gitignore).toString() : '';
215
+ let lf = gitignoreData.endsWith('\n') ? '\n' : '';
216
+ if (!gitignoreData.includes('.mops')) {
217
+ writeFileSync(gitignore, `${gitignoreData}\n.mops${lf}`.trimStart());
218
+ console.log(chalk.green('Added'), '.mops to .gitignore');
219
+ }
220
+ }
221
+ // install deps
222
+ if (Object.keys(config.dependencies || {}).length) {
223
+ console.log('Installing dependencies...');
79
224
  await installAll({ verbose: true });
80
225
  }
81
- console.log(chalk.green('mops.toml has been created'));
226
+ console.log(chalk.green('Done!'));
82
227
  }
@@ -67,7 +67,7 @@ export async function remove(name, { dev = false, verbose = false, dryRun = fals
67
67
  pkgDir = formatDir(dep.name, dep.version);
68
68
  }
69
69
  if (pkgDir && fs.existsSync(pkgDir)) {
70
- dryRun || deleteSync([`${pkgDir}`]);
70
+ dryRun || deleteSync([`${pkgDir}`], { force: true });
71
71
  verbose && console.log(`Removed local cache ${pkgDir}`);
72
72
  }
73
73
  }
@@ -0,0 +1 @@
1
+ export declare function sync(): Promise<void>;
@@ -0,0 +1,84 @@
1
+ import path from 'node:path';
2
+ import { execSync } from 'node:child_process';
3
+ import { globSync } from 'glob';
4
+ import chalk from 'chalk';
5
+ import { checkConfigFile, getRootDir, readConfig } from '../mops.js';
6
+ import { add } from './add.js';
7
+ import { remove } from './remove.js';
8
+ let ignore = [
9
+ '**/node_modules/**',
10
+ '**/.vessel/**',
11
+ '**/.git/**',
12
+ '**/.mops/**',
13
+ '**/test/**',
14
+ '**/*.test.mo',
15
+ ];
16
+ let mocPath = '';
17
+ function getMocPath() {
18
+ if (!mocPath) {
19
+ mocPath = process.env.DFX_MOC_PATH || '';
20
+ }
21
+ if (!mocPath) {
22
+ try {
23
+ mocPath = execSync('dfx cache show').toString().trim() + '/moc';
24
+ }
25
+ catch { }
26
+ }
27
+ if (!mocPath) {
28
+ mocPath = 'moc';
29
+ }
30
+ return mocPath;
31
+ }
32
+ async function getUsedPackages() {
33
+ let rootDir = getRootDir();
34
+ let files = globSync('**/*.mo', {
35
+ cwd: rootDir,
36
+ nocase: true,
37
+ ignore: ignore,
38
+ });
39
+ let packages = new Set;
40
+ for (let file of files) {
41
+ let deps = execSync(`${getMocPath()} --print-deps ${path.join(rootDir, file)}`).toString().trim().split('\n');
42
+ for (let dep of deps) {
43
+ if (dep.startsWith('mo:') && !dep.startsWith('mo:prim') && !dep.startsWith('mo:⛔')) {
44
+ packages.add(dep.replace(/^mo:([^/]+).*$/, '$1'));
45
+ }
46
+ }
47
+ }
48
+ return [...packages];
49
+ }
50
+ async function getMissingPackages() {
51
+ let config = readConfig();
52
+ let allDeps = [...Object.keys(config.dependencies || {}), ...Object.keys(config['dev-dependencies'] || {})];
53
+ let missing = new Set(await getUsedPackages());
54
+ for (let pkg of allDeps) {
55
+ missing.delete(pkg);
56
+ }
57
+ return [...missing];
58
+ }
59
+ async function getUnusedPackages() {
60
+ let config = readConfig();
61
+ let allDeps = new Set([...Object.keys(config.dependencies || {})]);
62
+ let used = await getUsedPackages();
63
+ for (let pkg of used) {
64
+ allDeps.delete(pkg);
65
+ }
66
+ return [...allDeps];
67
+ }
68
+ export async function sync() {
69
+ if (!checkConfigFile()) {
70
+ return;
71
+ }
72
+ let missing = await getMissingPackages();
73
+ let unused = await getUnusedPackages();
74
+ missing.length && console.log(`${chalk.yellow('Missing packages:')} ${missing.join(', ')}`);
75
+ unused.length && console.log(`${chalk.yellow('Unused packages:')} ${unused.join(', ')}`);
76
+ // add missing packages
77
+ for (let pkg of missing) {
78
+ await add(pkg);
79
+ }
80
+ // remove unused packages
81
+ for (let pkg of unused) {
82
+ await remove(pkg);
83
+ }
84
+ }
@@ -1 +1 @@
1
- export declare function template(): Promise<void>;
1
+ export declare function template(templateName?: string, options?: any): Promise<void>;