lincd-cli 0.2.41 → 0.2.43

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,679 +1,855 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
1
+ 'use strict';
2
+ var __createBinding =
3
+ (this && this.__createBinding) ||
4
+ (Object.create
5
+ ? function (o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ var desc = Object.getOwnPropertyDescriptor(m, k);
8
+ if (!desc || ('get' in desc ? !m.__esModule : desc.writable || desc.configurable)) {
9
+ desc = {
10
+ enumerable: true,
11
+ get: function () {
12
+ return m[k];
13
+ },
14
+ };
15
+ }
16
+ Object.defineProperty(o, k2, desc);
17
+ }
18
+ : function (o, m, k, k2) {
19
+ if (k2 === undefined) k2 = k;
20
+ o[k2] = m[k];
21
+ });
22
+ var __setModuleDefault =
23
+ (this && this.__setModuleDefault) ||
24
+ (Object.create
25
+ ? function (o, v) {
26
+ Object.defineProperty(o, 'default', {enumerable: true, value: v});
27
+ }
28
+ : function (o, v) {
29
+ o['default'] = v;
30
+ });
31
+ var __importStar =
32
+ (this && this.__importStar) ||
33
+ function (mod) {
19
34
  if (mod && mod.__esModule) return mod;
20
35
  var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
36
+ if (mod != null)
37
+ for (var k in mod)
38
+ if (k !== 'default' && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
39
  __setModuleDefault(result, mod);
23
40
  return result;
24
- };
25
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
41
+ };
42
+ var __awaiter =
43
+ (this && this.__awaiter) ||
44
+ function (thisArg, _arguments, P, generator) {
45
+ function adopt(value) {
46
+ return value instanceof P
47
+ ? value
48
+ : new P(function (resolve) {
49
+ resolve(value);
50
+ });
51
+ }
52
+
27
53
  return new (P || (P = Promise))(function (resolve, reject) {
28
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
- step((generator = generator.apply(thisArg, _arguments || [])).next());
54
+ function fulfilled(value) {
55
+ try {
56
+ step(generator.next(value));
57
+ } catch (e) {
58
+ reject(e);
59
+ }
60
+ }
61
+
62
+ function rejected(value) {
63
+ try {
64
+ step(generator['throw'](value));
65
+ } catch (e) {
66
+ reject(e);
67
+ }
68
+ }
69
+
70
+ function step(result) {
71
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
72
+ }
73
+
74
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
32
75
  });
33
- };
34
- var __importDefault = (this && this.__importDefault) || function (mod) {
35
- return (mod && mod.__esModule) ? mod : { "default": mod };
36
- };
37
- Object.defineProperty(exports, "__esModule", { value: true });
38
- exports.executeCommandForPackage = exports.addCapacitor = exports.addLinesToFile = exports.executeCommandForEachPackage = exports.buildUpdated = exports.publishPackage = exports.publishUpdated = exports.buildPackage = exports.buildMetadata = exports.register = exports.createPackage = exports.depCheck = exports.createComponent = exports.createSetComponent = exports.createShape = exports.setNameVariables = exports.createOntology = exports.getLincdPackages = exports.buildAll = exports.developPackage = exports.createApp = void 0;
39
- const path_1 = __importDefault(require("path"));
40
- const fs_extra_1 = __importDefault(require("fs-extra"));
41
- const utils_1 = require("./utils");
42
- const chalk_1 = __importDefault(require("chalk"));
43
- const child_process_1 = require("child_process");
44
- const models_1 = require("lincd/lib/models");
45
- const env_cmd_1 = require("env-cmd");
46
- const JSONLDWriter_1 = require("lincd-jsonld/lib/utils/JSONLDWriter");
47
- const NameSpace_1 = require("lincd/lib/utils/NameSpace");
48
- const Prefix_1 = require("lincd/lib/utils/Prefix");
49
- const get_env_vars_1 = require("env-cmd/dist/get-env-vars");
50
- const depcheck_1 = __importDefault(require("depcheck"));
76
+ };
77
+ var __importDefault =
78
+ (this && this.__importDefault) ||
79
+ function (mod) {
80
+ return mod && mod.__esModule ? mod : {default: mod};
81
+ };
82
+ Object.defineProperty(exports, '__esModule', {value: true});
83
+ exports.executeCommandForPackage =
84
+ exports.addCapacitor =
85
+ exports.addLinesToFile =
86
+ exports.executeCommandForEachPackage =
87
+ exports.buildUpdated =
88
+ exports.publishPackage =
89
+ exports.publishUpdated =
90
+ exports.buildPackage =
91
+ exports.buildMetadata =
92
+ exports.register =
93
+ exports.createPackage =
94
+ exports.depCheck =
95
+ exports.createComponent =
96
+ exports.createSetComponent =
97
+ exports.createShape =
98
+ exports.setNameVariables =
99
+ exports.createOntology =
100
+ exports.getLincdPackages =
101
+ exports.buildAll =
102
+ exports.developPackage =
103
+ exports.createApp =
104
+ void 0;
105
+ const path_1 = __importDefault(require('path'));
106
+ const fs_extra_1 = __importDefault(require('fs-extra'));
107
+ const utils_1 = require('./utils');
108
+ const chalk_1 = __importDefault(require('chalk'));
109
+ const child_process_1 = require('child_process');
110
+ const models_1 = require('lincd/lib/models');
111
+ const env_cmd_1 = require('env-cmd');
112
+ const JSONLDWriter_1 = require('lincd-jsonld/lib/utils/JSONLDWriter');
113
+ const NameSpace_1 = require('lincd/lib/utils/NameSpace');
114
+ const Prefix_1 = require('lincd/lib/utils/Prefix');
115
+ const get_env_vars_1 = require('env-cmd/dist/get-env-vars');
116
+ const depcheck_1 = __importDefault(require('depcheck'));
51
117
  var glob = require('glob');
52
118
  var variables = {};
53
119
  var open = require('open');
54
120
  var gruntConfig;
55
- const createApp = (name, basePath = process.cwd()) => __awaiter(void 0, void 0, void 0, function* () {
121
+ const createApp = (name, basePath = process.cwd()) =>
122
+ __awaiter(void 0, void 0, void 0, function* () {
56
123
  if (!name) {
57
- console.warn('Please provide a name as the first argument');
124
+ console.warn('Please provide a name as the first argument');
58
125
  }
59
- let { hyphenName, camelCaseName, underscoreName } = (0, exports.setNameVariables)(name);
126
+ let {hyphenName, camelCaseName, underscoreName} = (0, exports.setNameVariables)(name);
60
127
  let targetFolder = path_1.default.join(basePath, hyphenName);
61
128
  if (!fs_extra_1.default.existsSync(targetFolder)) {
62
- fs_extra_1.default.mkdirSync(targetFolder);
129
+ fs_extra_1.default.mkdirSync(targetFolder);
63
130
  }
64
131
  fs_extra_1.default.copySync(path_1.default.join(__dirname, '..', 'defaults', 'app-with-backend'), targetFolder);
65
132
  //make sure the data folder exists (even though its empty).. copying empty folders does not work with fs.copySync
66
- fs_extra_1.default.mkdirSync(path_1.default.join(targetFolder, 'data'), { recursive: true });
67
- fs_extra_1.default.mkdirSync(path_1.default.join(targetFolder, 'data/uploads/resized'), { recursive: true });
68
- fs_extra_1.default.renameSync(path_1.default.join(targetFolder, 'gitignore.template'), path_1.default.join(targetFolder, '.gitignore'));
69
- fs_extra_1.default.renameSync(path_1.default.join(targetFolder, 'yarnrc.yml.template'), path_1.default.join(targetFolder, '.yarnrc.yml'));
133
+ fs_extra_1.default.mkdirSync(path_1.default.join(targetFolder, 'data'), {recursive: true});
134
+ fs_extra_1.default.mkdirSync(path_1.default.join(targetFolder, 'data/uploads/resized'), {recursive: true});
135
+ fs_extra_1.default.renameSync(
136
+ path_1.default.join(targetFolder, 'gitignore.template'),
137
+ path_1.default.join(targetFolder, '.gitignore'),
138
+ );
139
+ fs_extra_1.default.renameSync(
140
+ path_1.default.join(targetFolder, 'yarnrc.yml.template'),
141
+ path_1.default.join(targetFolder, '.yarnrc.yml'),
142
+ );
70
143
  // fs.copySync(path.join(__dirname, '..', 'defaults', 'app'), targetFolder);
71
144
  log("Creating new LINCD application '" + name + "'");
72
145
  //replace variables in some copied files
73
146
  yield replaceVariablesInFolder(targetFolder);
74
147
  let hasYarn = yield hasYarnInstalled();
75
148
  let installCommand = hasYarn
76
- ? 'export NODE_OPTIONS="--no-network-family-autoselection" && yarn install'
77
- : 'npm install';
149
+ ? 'export NODE_OPTIONS="--no-network-family-autoselection" && yarn install'
150
+ : 'npm install';
78
151
  yield (0, utils_1.execp)(`cd ${hyphenName} && ${installCommand}`, true).catch((err) => {
79
- console.warn('Could not install dependencies or start application');
152
+ console.warn('Could not install dependencies or start application');
80
153
  });
81
- log(`Your LINCD App is ready at ${chalk_1.default.blueBright(targetFolder)}`, `To start, run\n${chalk_1.default.blueBright(`cd ${hyphenName}`)} and then ${chalk_1.default.blueBright((hasYarn ? 'yarn' : 'npm') + ' start')}`);
82
- });
154
+ log(
155
+ `Your LINCD App is ready at ${chalk_1.default.blueBright(targetFolder)}`,
156
+ `To start, run\n${chalk_1.default.blueBright(`cd ${hyphenName}`)} and then ${chalk_1.default.blueBright(
157
+ (hasYarn ? 'yarn' : 'npm') + ' start',
158
+ )}`,
159
+ );
160
+ });
83
161
  exports.createApp = createApp;
162
+
84
163
  function logHelp() {
85
- (0, utils_1.execp)('yarn exec lincd help');
164
+ (0, utils_1.execp)('yarn exec lincd help');
86
165
  }
166
+
87
167
  function log(...messages) {
88
- messages.forEach((message) => {
89
- console.log(chalk_1.default.cyan('Info: ') + message);
90
- });
168
+ messages.forEach((message) => {
169
+ console.log(chalk_1.default.cyan('Info: ') + message);
170
+ });
91
171
  }
172
+
92
173
  function progressUpdate(message) {
93
- process.stdout.write(' \r');
94
- process.stdout.write(message + '\r');
174
+ process.stdout.write(' \r');
175
+ process.stdout.write(message + '\r');
95
176
  }
177
+
96
178
  function debugInfo(...messages) {
97
- // messages.forEach((message) => {
98
- // console.log(chalk.cyan('Info: ') + message);
99
- // });
100
- //@TODO: let packages also use lincd.config.json? instead of gruntfile...
101
- // that way we can read "analyse" here and see if we need to log debug info
102
- // if(!gruntConfig)
103
- // {
104
- // gruntConfig = getGruntConfig();
105
- // console.log(gruntConfig);
106
- // process.exit();
107
- // }
108
- if (gruntConfig && gruntConfig.analyse === true) {
109
- messages.forEach((message) => {
110
- console.log(chalk_1.default.cyan('Info: ') + message);
111
- });
112
- }
113
- }
114
- function warn(...messages) {
179
+ // messages.forEach((message) => {
180
+ // console.log(chalk.cyan('Info: ') + message);
181
+ // });
182
+ //@TODO: let packages also use lincd.config.json? instead of gruntfile...
183
+ // that way we can read "analyse" here and see if we need to log debug info
184
+ // if(!gruntConfig)
185
+ // {
186
+ // gruntConfig = getGruntConfig();
187
+ // console.log(gruntConfig);
188
+ // process.exit();
189
+ // }
190
+ if (gruntConfig && gruntConfig.analyse === true) {
115
191
  messages.forEach((message) => {
116
- console.log(chalk_1.default.magenta('Warning: ') + message);
117
- // console.log(chalk.red(message));
192
+ console.log(chalk_1.default.cyan('Info: ') + message);
118
193
  });
194
+ }
119
195
  }
196
+
197
+ function warn(...messages) {
198
+ messages.forEach((message) => {
199
+ console.log(chalk_1.default.magenta('Warning: ') + message);
200
+ // console.log(chalk.red(message));
201
+ });
202
+ }
203
+
120
204
  function developPackage(target, mode) {
121
- if (!target)
122
- target = 'es6';
123
- if (mode !== 'production')
124
- mode = '';
125
- else if (target !== 'es6')
126
- log('target must be es6 when developing for production');
127
- if (target == 'es5' || target == 'es6') {
128
- // log('> Starting continuous development build for '+target+' target')
129
- log('starting continuous development build');
130
- log('grunt dev' + (target ? '-' + target : '') + (mode ? '-' + mode : '') + ' --color');
131
- var command = (0, child_process_1.exec)('grunt dev' + (target ? '-' + target : '') + (mode ? '-' + mode : '') + ' --color');
132
- command.stdout.pipe(process.stdout);
133
- command.stderr.pipe(process.stderr);
134
- }
135
- else {
136
- console.warn('unknown build target. Use es5 or es6');
137
- }
205
+ if (!target) target = 'es6';
206
+ if (mode !== 'production') mode = '';
207
+ else if (target !== 'es6') log('target must be es6 when developing for production');
208
+ if (target == 'es5' || target == 'es6') {
209
+ // log('> Starting continuous development build for '+target+' target')
210
+ log('starting continuous development build');
211
+ log('grunt dev' + (target ? '-' + target : '') + (mode ? '-' + mode : '') + ' --color');
212
+ var command = (0, child_process_1.exec)(
213
+ 'grunt dev' + (target ? '-' + target : '') + (mode ? '-' + mode : '') + ' --color',
214
+ );
215
+ command.stdout.pipe(process.stdout);
216
+ command.stderr.pipe(process.stderr);
217
+ } else {
218
+ console.warn('unknown build target. Use es5 or es6');
219
+ }
138
220
  }
221
+
139
222
  exports.developPackage = developPackage;
223
+
140
224
  function checkWorkspaces(rootPath, workspaces, res) {
141
- // console.log('checking workspaces at '+rootPath+": "+workspaces.toString());
142
- if (workspaces.packages) {
143
- workspaces = workspaces.packages;
225
+ // console.log('checking workspaces at '+rootPath+": "+workspaces.toString());
226
+ if (workspaces.packages) {
227
+ workspaces = workspaces.packages;
228
+ }
229
+ workspaces.forEach((workspace) => {
230
+ let workspacePath = path_1.default.join(rootPath, workspace.replace('/*', ''));
231
+ if (workspace.indexOf('/*') !== -1) {
232
+ // console.log(workspacePath);
233
+ if (fs_extra_1.default.existsSync(workspacePath)) {
234
+ let folders = fs_extra_1.default.readdirSync(workspacePath);
235
+ folders.forEach((folder) => {
236
+ if (folder !== './' && folder !== '../') {
237
+ checkPackagePath(rootPath, path_1.default.join(workspacePath, folder), res);
238
+ }
239
+ });
240
+ }
241
+ } else {
242
+ checkPackagePath(rootPath, workspacePath, res);
144
243
  }
145
- workspaces.forEach((workspace) => {
146
- let workspacePath = path_1.default.join(rootPath, workspace.replace('/*', ''));
147
- if (workspace.indexOf('/*') !== -1) {
148
- // console.log(workspacePath);
149
- if (fs_extra_1.default.existsSync(workspacePath)) {
150
- let folders = fs_extra_1.default.readdirSync(workspacePath);
151
- folders.forEach((folder) => {
152
- if (folder !== './' && folder !== '../') {
153
- checkPackagePath(rootPath, path_1.default.join(workspacePath, folder), res);
154
- }
155
- });
156
- }
157
- }
158
- else {
159
- checkPackagePath(rootPath, workspacePath, res);
160
- }
161
- });
244
+ });
162
245
  }
246
+
163
247
  function checkPackagePath(rootPath, packagePath, res) {
164
- let packageJsonPath = path_1.default.join(packagePath, 'package.json');
165
- // console.log('checking '+packagePath);
166
- if (fs_extra_1.default.existsSync(packageJsonPath)) {
167
- var pack = JSON.parse(fs_extra_1.default.readFileSync(packageJsonPath, 'utf8'));
168
- //some packages are not true lincd packages, but we still want them to be re-built automatically. This is what lincd_util is for
169
- if (pack && pack.workspaces) {
170
- checkWorkspaces(packagePath, pack.workspaces, res);
171
- }
172
- else if (pack && pack.lincd === true) {
173
- res.push({
174
- path: packagePath,
175
- packageName: pack.name,
176
- });
177
- }
248
+ let packageJsonPath = path_1.default.join(packagePath, 'package.json');
249
+ // console.log('checking '+packagePath);
250
+ if (fs_extra_1.default.existsSync(packageJsonPath)) {
251
+ var pack = JSON.parse(fs_extra_1.default.readFileSync(packageJsonPath, 'utf8'));
252
+ //some packages are not true lincd packages, but we still want them to be re-built automatically. This is what lincd_util is for
253
+ if (pack && pack.workspaces) {
254
+ checkWorkspaces(packagePath, pack.workspaces, res);
255
+ } else if (pack && pack.lincd === true) {
256
+ res.push({
257
+ path: packagePath,
258
+ packageName: pack.name,
259
+ });
178
260
  }
261
+ }
179
262
  }
263
+
180
264
  function runOnPackagesGroupedByDependencies(lincdPackages, onBuildStack, onStackEnd) {
181
- let dependencies = new Map();
182
- //get dependencies of each package
183
- let leastDependentPackage;
184
- lincdPackages.forEach((pkg) => {
185
- var pack = (0, utils_1.getPackageJSON)(pkg.path);
186
- if (pack) {
187
- //get lincd related dependencies and get the actual package details from the package map by removing '@dacore/' from the package name
188
- let packageDependencies = Object.keys(pack.dependencies)
189
- .filter((dependency) => lincdPackages.has(dependency))
190
- .map((dependency) => {
191
- return lincdPackages.has(dependency) ? lincdPackages.get(dependency) : dependency;
192
- });
193
- // console.log(package.packageName,packageDependencies.map())
194
- dependencies.set(pkg, packageDependencies);
195
- }
196
- });
197
- dependencies.forEach((PackageDependencies, pkg) => {
198
- if (!PackageDependencies.some((dependency) => {
199
- return typeof dependency !== 'string' && lincdPackages.has(dependency.packageName);
200
- })) {
201
- leastDependentPackage = pkg;
202
- }
203
- });
204
- let startStack = [leastDependentPackage];
205
- let done = new Set();
206
- let results = [];
207
- let runStack = (stack) => __awaiter(this, void 0, void 0, function* () {
208
- let runFunction = onBuildStack(stack, dependencies);
209
- //build the stack in parallel
210
- let stackPromise = Promise.all(stack.map((pck) => {
211
- // p = p.then(() => {
212
- return runFunction(pck)
213
- .catch(({ error, stdout, stderr }) => {
214
- warn('Uncaught exception whilst running parallel function on ' + pck.packageName, error.message);
215
- // warn(chalk.red(pck.packageName+' failed:'));
216
- // console.log(stdout);
265
+ let dependencies = new Map();
266
+ //get dependencies of each package
267
+ let leastDependentPackage;
268
+ lincdPackages.forEach((pkg) => {
269
+ var pack = (0, utils_1.getPackageJSON)(pkg.path);
270
+ if (pack) {
271
+ //get lincd related dependencies and get the actual package details from the package map by removing '@dacore/' from the package name
272
+ let packageDependencies = Object.keys(pack.dependencies)
273
+ .filter((dependency) => lincdPackages.has(dependency))
274
+ .map((dependency) => {
275
+ return lincdPackages.has(dependency) ? lincdPackages.get(dependency) : dependency;
276
+ });
277
+ // console.log(package.packageName,packageDependencies.map())
278
+ dependencies.set(pkg, packageDependencies);
279
+ }
280
+ });
281
+ dependencies.forEach((PackageDependencies, pkg) => {
282
+ if (
283
+ !PackageDependencies.some((dependency) => {
284
+ return typeof dependency !== 'string' && lincdPackages.has(dependency.packageName);
285
+ })
286
+ ) {
287
+ leastDependentPackage = pkg;
288
+ }
289
+ });
290
+ let startStack = [leastDependentPackage];
291
+ let done = new Set();
292
+ let results = [];
293
+ let runStack = (stack) =>
294
+ __awaiter(this, void 0, void 0, function* () {
295
+ let runFunction = onBuildStack(stack, dependencies);
296
+ //build the stack in parallel
297
+ let stackPromise = Promise.all(
298
+ stack.map((pck) => {
299
+ // p = p.then(() => {
300
+ return runFunction(pck)
301
+ .catch(({error, stdout, stderr}) => {
302
+ warn('Uncaught exception whilst running parallel function on ' + pck.packageName, error.message);
303
+ // warn(chalk.red(pck.packageName+' failed:'));
304
+ // console.log(stdout);
217
305
  })
218
- .then((res) => {
219
- done.add(pck);
220
- return res;
306
+ .then((res) => {
307
+ done.add(pck);
308
+ return res;
221
309
  });
222
- }));
223
- //wait till stack is completed
224
- let stackResults = yield stackPromise;
225
- results = results.concat(stackResults);
226
- //clear stack for next round
227
- stack = [];
228
- //find those packages who have all their dependencies already built and add them to the stack
310
+ }),
311
+ );
312
+ //wait till stack is completed
313
+ let stackResults = yield stackPromise;
314
+ results = results.concat(stackResults);
315
+ //clear stack for next round
316
+ stack = [];
317
+ //find those packages who have all their dependencies already built and add them to the stack
318
+ lincdPackages.forEach((pkg) => {
319
+ let deps = dependencies.get(pkg);
320
+ //if the package is not done yet
321
+ //but every dependency is now done OR was not something we can build (some @dacore dependencies may not be local)
322
+ if (
323
+ !done.has(pkg) &&
324
+ deps.every((dependency) => {
325
+ return (
326
+ typeof dependency !== 'string' && (done.has(dependency) || !lincdPackages.has(dependency.packageName))
327
+ );
328
+ })
329
+ ) {
330
+ stack.push(pkg);
331
+ }
332
+ });
333
+ if (stack.length <= 0 && done.size < lincdPackages.size) {
334
+ console.log(
335
+ chalk_1.default.red('Only ' + done.size + ' out of ' + lincdPackages.size + ' packages have been built'),
336
+ );
337
+ console.log(
338
+ 'ALL remaining packages have dependencies that have not been met. This may point to ' +
339
+ chalk_1.default.red('circular dependencies.'),
340
+ );
341
+ console.log(
342
+ 'Already built: ' +
343
+ Array.from(done)
344
+ .map((p) => chalk_1.default.green(p.packageName))
345
+ .join(', '),
346
+ );
347
+ console.log(
348
+ chalk_1.default.blue('\nTo solve this issue') +
349
+ ': find the circular dependencies below and fix the dependencies:\n\n',
350
+ );
351
+ //TODO: actually find and name the packages that have circular dependencies
352
+ // let circular = [];
353
+ // lincdPackages.forEach((pkg) => {
354
+ // if (!done.has(pkg))
355
+ // {
356
+ // let deps = dependencies.get(pkg);
357
+ // if (deps.some(dependency => {
358
+ // //return true if this dependency (indirectly) depends on the package whos' dependency it is
359
+ // return hasDependency(dependency,pkg,dependencies)
360
+ // }))
361
+ // {
362
+ // circular.push(pkg);
363
+ // }
364
+ // process.exit();
365
+ // }
366
+ // });
229
367
  lincdPackages.forEach((pkg) => {
230
- let deps = dependencies.get(pkg);
231
- //if the package is not done yet
232
- //but every dependency is now done OR was not something we can build (some @dacore dependencies may not be local)
233
- if (!done.has(pkg) &&
234
- deps.every((dependency) => {
235
- return typeof dependency !== 'string' && (done.has(dependency) || !lincdPackages.has(dependency.packageName));
236
- })) {
237
- stack.push(pkg);
238
- }
368
+ let deps = dependencies.get(pkg);
369
+ if (!done.has(pkg)) {
370
+ console.log(
371
+ chalk_1.default.red(pkg.packageName) +
372
+ ' has not been built yet. Unbuilt dependencies:\n' +
373
+ deps
374
+ .filter((dependency) => {
375
+ return !Array.from(done).some((p) => {
376
+ // console.log(p.packageName,dependency.packageName,p===dependency)
377
+ return p === dependency;
378
+ });
379
+ })
380
+ .map((p) =>
381
+ chalk_1.default.red(
382
+ '\t- ' +
383
+ ((p === null || p === void 0 ? void 0 : p.packageName) ? p.packageName : p.toString()) +
384
+ '\n',
385
+ ),
386
+ )
387
+ .join(' '),
388
+ );
389
+ // console.log(chalk.red(pkg.packageName)+' has not been built yet. Built dependencies:\n' + deps.filter(dependency => {
390
+ // return Array.from(done).some(p => p.packageName === pkg.packageName)
391
+ // }).map(p => chalk.green('\t- '+p.packageName+'\n')).join(" "))
392
+ // console.log(chalk.red(pkg.packageName)+' has not been built yet. Built dependencies:\n' + deps.filter(dependency => done.has(pkg)).map(p => chalk.green('\t- '+p.packageName+'\n')).join(" "))
393
+ }
239
394
  });
240
- if (stack.length <= 0 && done.size < lincdPackages.size) {
241
- console.log(chalk_1.default.red('Only ' + done.size + ' out of ' + lincdPackages.size + ' packages have been built'));
242
- console.log('ALL remaining packages have dependencies that have not been met. This may point to ' +
243
- chalk_1.default.red('circular dependencies.'));
244
- console.log('Already built: ' +
245
- Array.from(done)
246
- .map((p) => chalk_1.default.green(p.packageName))
247
- .join(', '));
248
- console.log(chalk_1.default.blue('\nTo solve this issue') + ': find the circular dependencies below and fix the dependencies:\n\n');
249
- //TODO: actually find and name the packages that have circular dependencies
250
- // let circular = [];
251
- // lincdPackages.forEach((pkg) => {
252
- // if (!done.has(pkg))
253
- // {
254
- // let deps = dependencies.get(pkg);
255
- // if (deps.some(dependency => {
256
- // //return true if this dependency (indirectly) depends on the package whos' dependency it is
257
- // return hasDependency(dependency,pkg,dependencies)
258
- // }))
259
- // {
260
- // circular.push(pkg);
261
- // }
262
- // process.exit();
263
- // }
264
- // });
265
- lincdPackages.forEach((pkg) => {
266
- let deps = dependencies.get(pkg);
267
- if (!done.has(pkg)) {
268
- console.log(chalk_1.default.red(pkg.packageName) +
269
- ' has not been built yet. Unbuilt dependencies:\n' +
270
- deps
271
- .filter((dependency) => {
272
- return !Array.from(done).some((p) => {
273
- // console.log(p.packageName,dependency.packageName,p===dependency)
274
- return p === dependency;
275
- });
276
- })
277
- .map((p) => chalk_1.default.red('\t- ' + ((p === null || p === void 0 ? void 0 : p.packageName) ? p.packageName : p.toString()) + '\n'))
278
- .join(' '));
279
- // console.log(chalk.red(pkg.packageName)+' has not been built yet. Built dependencies:\n' + deps.filter(dependency => {
280
- // return Array.from(done).some(p => p.packageName === pkg.packageName)
281
- // }).map(p => chalk.green('\t- '+p.packageName+'\n')).join(" "))
282
- // console.log(chalk.red(pkg.packageName)+' has not been built yet. Built dependencies:\n' + deps.filter(dependency => done.has(pkg)).map(p => chalk.green('\t- '+p.packageName+'\n')).join(" "))
283
- }
284
- });
285
- }
286
- //if more to be built, iterate
287
- if (stack.length > 0) {
288
- return runStack(stack);
289
- }
290
- else {
291
- onStackEnd(dependencies, results.filter(Boolean));
292
- }
395
+ }
396
+ //if more to be built, iterate
397
+ if (stack.length > 0) {
398
+ return runStack(stack);
399
+ } else {
400
+ onStackEnd(dependencies, results.filter(Boolean));
401
+ }
293
402
  });
294
- //starts the process
295
- runStack(startStack);
403
+ //starts the process
404
+ runStack(startStack);
296
405
  }
406
+
297
407
  function hasDependency(pkg, childPkg, dependencies, depth = 1) {
298
- console.log('Does ' + pkg.packageName + ' have dep ' + childPkg.packageName + ' ?');
299
- let deps = dependencies.get(pkg);
300
- if (deps.some((dependency) => {
301
- console.log(dependency.packageName, childPkg.packageName, dependency === childPkg);
302
- if (depth === 2)
303
- return false;
304
- // return dependency === childPkg;
305
- return dependency === childPkg || hasDependency(dependency, childPkg, dependencies, depth++);
306
- })) {
307
- console.log('##YES');
308
- return true;
309
- }
310
- console.log('going up');
311
- return false;
408
+ console.log('Does ' + pkg.packageName + ' have dep ' + childPkg.packageName + ' ?');
409
+ let deps = dependencies.get(pkg);
410
+ if (
411
+ deps.some((dependency) => {
412
+ console.log(dependency.packageName, childPkg.packageName, dependency === childPkg);
413
+ if (depth === 2) return false;
414
+ // return dependency === childPkg;
415
+ return dependency === childPkg || hasDependency(dependency, childPkg, dependencies, depth++);
416
+ })
417
+ ) {
418
+ console.log('##YES');
419
+ return true;
420
+ }
421
+ console.log('going up');
422
+ return false;
312
423
  }
424
+
313
425
  function buildAll(target, target2, target3) {
314
- console.log('Building all LINCD packages of this repository in order of dependencies');
315
- let lincdPackages = getLocalLincdPackageMap();
316
- let startFrom;
317
- //by default start building
318
- let building = true;
319
- //option to start from a specific package in the stack
320
- if (target == 'from') {
321
- startFrom = target2;
322
- //if we have a startFrom, then we havnt started the build process yet
323
- building = startFrom ? false : true;
324
- //clear targets
325
- target = '';
326
- target2 = '';
327
- console.log(chalk_1.default.blue('Will skip builds until ' + startFrom));
328
- // return async (pkg) => {};
329
- }
330
- if (target2 == 'from') {
331
- startFrom = target3;
332
- //if we have a startFrom, then we havnt started the build process yet
333
- building = startFrom ? false : true;
334
- //clear targets
335
- target2 = '';
336
- target3 = '';
337
- console.log(chalk_1.default.blue('Will skip builds until ' + startFrom));
338
- // return async (pkg) => {};
339
- }
340
- let done = new Set();
341
- let failedModules = [];
342
- progressUpdate(lincdPackages.size + ' packages left');
343
- let packagesLeft = lincdPackages.size;
344
- // let packagesLeft = lincdPackages.size - done.size;
345
- runOnPackagesGroupedByDependencies(lincdPackages, (packageGroup, dependencies) => {
346
- if (done.size > 0) {
347
- debugInfo(chalk_1.default.magenta('\n-------\nThese packages are next, since all their dependencies have now been build:'));
348
- // log(stack);
349
- }
350
- debugInfo('Now building: ' + chalk_1.default.blue(packageGroup.map((i) => i.packageName)));
351
- return (pkg) => __awaiter(this, void 0, void 0, function* () {
352
- let command;
353
- let skipping = false;
354
- //if we're skipping builds until a certain package
355
- if (!building) {
356
- //if the package name matches the package we're supposed to start from then start building packages
357
- if (pkg.packageName == startFrom || pkg.packageName == startFrom) {
358
- building = true;
359
- }
360
- //else still waiting for the package
361
- else {
362
- log(chalk_1.default.blue('skipping ' + pkg.packageName));
363
- command = Promise.resolve(true);
364
- skipping = true;
365
- }
426
+ console.log('Building all LINCD packages of this repository in order of dependencies');
427
+ let lincdPackages = getLocalLincdPackageMap();
428
+ let startFrom;
429
+ //by default start building
430
+ let building = true;
431
+ //option to start from a specific package in the stack
432
+ if (target == 'from') {
433
+ startFrom = target2;
434
+ //if we have a startFrom, then we havnt started the build process yet
435
+ building = startFrom ? false : true;
436
+ //clear targets
437
+ target = '';
438
+ target2 = '';
439
+ console.log(chalk_1.default.blue('Will skip builds until ' + startFrom));
440
+ // return async (pkg) => {};
441
+ }
442
+ if (target2 == 'from') {
443
+ startFrom = target3;
444
+ //if we have a startFrom, then we havnt started the build process yet
445
+ building = startFrom ? false : true;
446
+ //clear targets
447
+ target2 = '';
448
+ target3 = '';
449
+ console.log(chalk_1.default.blue('Will skip builds until ' + startFrom));
450
+ // return async (pkg) => {};
451
+ }
452
+ let done = new Set();
453
+ let failedModules = [];
454
+ progressUpdate(lincdPackages.size + ' packages left');
455
+ let packagesLeft = lincdPackages.size;
456
+ // let packagesLeft = lincdPackages.size - done.size;
457
+ runOnPackagesGroupedByDependencies(
458
+ lincdPackages,
459
+ (packageGroup, dependencies) => {
460
+ if (done.size > 0) {
461
+ debugInfo(
462
+ chalk_1.default.magenta(
463
+ '\n-------\nThese packages are next, since all their dependencies have now been build:',
464
+ ),
465
+ );
466
+ // log(stack);
467
+ }
468
+ debugInfo('Now building: ' + chalk_1.default.blue(packageGroup.map((i) => i.packageName)));
469
+ return (pkg) =>
470
+ __awaiter(this, void 0, void 0, function* () {
471
+ let command;
472
+ let skipping = false;
473
+ //if we're skipping builds until a certain package
474
+ if (!building) {
475
+ //if the package name matches the package we're supposed to start from then start building packages
476
+ if (pkg.packageName == startFrom || pkg.packageName == startFrom) {
477
+ building = true;
366
478
  }
367
- //unless told otherwise, build the package
368
- if (!command) {
369
- command = (0, utils_1.execPromise)('cd ' +
370
- pkg.path +
371
- ' && yarn exec lincd build' +
372
- (target ? ' ' + target : '') +
373
- (target2 ? ' ' + target2 : ''), false, false, {}, false);
374
- debugInfo(chalk_1.default.cyan('Building ' + pkg.packageName));
479
+ //else still waiting for the package
480
+ else {
481
+ log(chalk_1.default.blue('skipping ' + pkg.packageName));
482
+ command = Promise.resolve(true);
483
+ skipping = true;
375
484
  }
376
- return command
377
- .catch(({ error, stdout, stderr }) => {
378
- //this prints out the webpack output, including the build errors
379
- warn('Failed to build ' + pkg.packageName);
380
- console.log(stdout);
381
- failedModules.push(pkg.packageName);
382
- let dependentModules = getDependentPackages(dependencies, pkg);
383
- if (dependentModules.length > 0) {
384
- printBuildResults(failedModules, done);
385
- console.log(chalk_1.default.magenta('Stopping build process because an error occurred whilst building ' +
386
- pkg.packageName +
387
- ', which ' +
388
- dependentModules.length +
389
- ' other packages depend on.')); //"+dependentModules.map(d => d.packageName).join(", ")));
390
- console.log(chalk_1.default.cyanBright('tip ') +
391
- 'Run ' +
392
- chalk_1.default.green(`lincd build-all from ${pkg.packageName}`) +
393
- ' to build only the remaining packages'); //"+dependentModules.map(d => d.packageName).join(", ")));
394
- process.exit(1);
395
- }
485
+ }
486
+ //unless told otherwise, build the package
487
+ if (!command) {
488
+ command = (0, utils_1.execPromise)(
489
+ 'cd ' +
490
+ pkg.path +
491
+ ' && yarn exec lincd build' +
492
+ (target ? ' ' + target : '') +
493
+ (target2 ? ' ' + target2 : ''),
494
+ false,
495
+ false,
496
+ {},
497
+ false,
498
+ );
499
+ debugInfo(chalk_1.default.cyan('Building ' + pkg.packageName));
500
+ }
501
+ return command
502
+ .catch(({error, stdout, stderr}) => {
503
+ //this prints out the webpack output, including the build errors
504
+ warn('Failed to build ' + pkg.packageName);
505
+ console.log(stdout);
506
+ failedModules.push(pkg.packageName);
507
+ let dependentModules = getDependentPackages(dependencies, pkg);
508
+ if (dependentModules.length > 0) {
509
+ printBuildResults(failedModules, done);
510
+ console.log(
511
+ chalk_1.default.magenta(
512
+ 'Stopping build process because an error occurred whilst building ' +
513
+ pkg.packageName +
514
+ ', which ' +
515
+ dependentModules.length +
516
+ ' other packages depend on.',
517
+ ),
518
+ ); //"+dependentModules.map(d => d.packageName).join(", ")));
519
+ console.log(
520
+ chalk_1.default.cyanBright('tip ') +
521
+ 'Run ' +
522
+ chalk_1.default.green(`lincd build-all from ${pkg.packageName}`) +
523
+ ' to build only the remaining packages',
524
+ ); //"+dependentModules.map(d => d.packageName).join(", ")));
525
+ process.exit(1);
526
+ }
396
527
  })
397
- .then((res) => {
398
- if (!skipping) {
399
- log(chalk_1.default.green('Built ' + pkg.packageName));
400
- }
401
- done.add(pkg);
402
- packagesLeft--;
403
- // log(chalk.magenta(packagesLeft + ' packages left'));
404
- process.stdout.write(packagesLeft + ' packages left\r');
405
- if (packagesLeft == 0) {
406
- printBuildResults(failedModules, done);
407
- }
408
- return res;
528
+ .then((res) => {
529
+ if (!skipping) {
530
+ log(chalk_1.default.green('Built ' + pkg.packageName));
531
+ }
532
+ done.add(pkg);
533
+ packagesLeft--;
534
+ // log(chalk.magenta(packagesLeft + ' packages left'));
535
+ process.stdout.write(packagesLeft + ' packages left\r');
536
+ if (packagesLeft == 0) {
537
+ printBuildResults(failedModules, done);
538
+ }
539
+ return res;
409
540
  });
410
541
  });
411
- }, (dependencies) => {
412
- //if no more packages to build but we never started building...
413
- if (!building) {
414
- console.log(chalk_1.default.red('Could not find the package to start from. Please provide a correct package name or package name to build from'));
415
- }
416
- else {
417
- //Detecting cyclical dependencies that caused some packages not to be build
418
- let first = true;
419
- lincdPackages.forEach((pkg) => {
420
- if (!done.has(pkg)) {
421
- let deps = dependencies.get(pkg);
422
- if (first) {
423
- console.log(chalk_1.default.red('CYCLICAL DEPENDENCIES? - could not build some packages because they depend on each other.'));
424
- first = false;
425
- }
426
- //print the cyclical dependencies
427
- console.log(chalk_1.default.red(pkg.packageName) +
428
- ' depends on ' +
429
- deps
430
- .filter((dependency) => {
431
- return typeof dependency !== 'string';
432
- })
433
- .map((d) => {
434
- return done.has(d) ? d.packageName : chalk_1.default.red(d.packageName);
435
- })
436
- .join(', '));
437
- //also print some information why these packages have not been moved into the stack
438
- let stringDependencies = deps.filter((d) => typeof d === 'string');
439
- if (stringDependencies.length > 0) {
440
- console.log(chalk_1.default.red('And it depends on these package(s) - which seem not to be proper packages :' +
441
- stringDependencies.join(', ')));
442
- console.log(chalk_1.default.red('Could you remove this from dependencies? Should it be a devDependency?'));
443
- }
444
- }
445
- });
446
- }
447
- });
542
+ },
543
+ (dependencies) => {
544
+ //if no more packages to build but we never started building...
545
+ if (!building) {
546
+ console.log(
547
+ chalk_1.default.red(
548
+ 'Could not find the package to start from. Please provide a correct package name or package name to build from',
549
+ ),
550
+ );
551
+ } else {
552
+ //Detecting cyclical dependencies that caused some packages not to be build
553
+ let first = true;
554
+ lincdPackages.forEach((pkg) => {
555
+ if (!done.has(pkg)) {
556
+ let deps = dependencies.get(pkg);
557
+ if (first) {
558
+ console.log(
559
+ chalk_1.default.red(
560
+ 'CYCLICAL DEPENDENCIES? - could not build some packages because they depend on each other.',
561
+ ),
562
+ );
563
+ first = false;
564
+ }
565
+ //print the cyclical dependencies
566
+ console.log(
567
+ chalk_1.default.red(pkg.packageName) +
568
+ ' depends on ' +
569
+ deps
570
+ .filter((dependency) => {
571
+ return typeof dependency !== 'string';
572
+ })
573
+ .map((d) => {
574
+ return done.has(d) ? d.packageName : chalk_1.default.red(d.packageName);
575
+ })
576
+ .join(', '),
577
+ );
578
+ //also print some information why these packages have not been moved into the stack
579
+ let stringDependencies = deps.filter((d) => typeof d === 'string');
580
+ if (stringDependencies.length > 0) {
581
+ console.log(
582
+ chalk_1.default.red(
583
+ 'And it depends on these package(s) - which seem not to be proper packages :' +
584
+ stringDependencies.join(', '),
585
+ ),
586
+ );
587
+ console.log(
588
+ chalk_1.default.red('Could you remove this from dependencies? Should it be a devDependency?'),
589
+ );
590
+ }
591
+ }
592
+ });
593
+ }
594
+ },
595
+ );
448
596
  }
597
+
449
598
  exports.buildAll = buildAll;
599
+
450
600
  function getDependentPackages(dependencies, pkg) {
451
- let dependentModules = [];
452
- dependencies.forEach((dModuleDependencies, dModule) => {
453
- if (dModuleDependencies.indexOf(pkg) !== -1) {
454
- dependentModules.push(dModule);
455
- }
456
- });
457
- return dependentModules;
601
+ let dependentModules = [];
602
+ dependencies.forEach((dModuleDependencies, dModule) => {
603
+ if (dModuleDependencies.indexOf(pkg) !== -1) {
604
+ dependentModules.push(dModule);
605
+ }
606
+ });
607
+ return dependentModules;
458
608
  }
609
+
459
610
  /**
460
611
  * Returns a map of the packages that this repository manages (so no packages found through the workspaces who's path contains ../ )
461
612
  * @param rootPath
462
613
  */
463
614
  function getLocalLincdPackageMap(rootPath = './') {
464
- let map = new Map();
465
- getLincdPackages(rootPath).forEach((pkg) => {
466
- if (pkg.path.indexOf('../') === -1 && pkg.path.indexOf('..\\') === -1) {
467
- // console.log(package.path);
468
- map.set(pkg.packageName, pkg);
469
- }
470
- });
471
- return map;
615
+ let map = new Map();
616
+ getLincdPackages(rootPath).forEach((pkg) => {
617
+ if (pkg.path.indexOf('../') === -1 && pkg.path.indexOf('..\\') === -1) {
618
+ // console.log(package.path);
619
+ map.set(pkg.packageName, pkg);
620
+ }
621
+ });
622
+ return map;
472
623
  }
624
+
473
625
  function getLocalLincdModules(rootPath = './') {
474
- return getLincdPackages(rootPath).filter((pkg) => {
475
- return pkg.path.indexOf('..\\') === -1;
476
- });
626
+ return getLincdPackages(rootPath).filter((pkg) => {
627
+ return pkg.path.indexOf('..\\') === -1;
628
+ });
477
629
  }
630
+
478
631
  function getLincdPackages(rootPath = process.cwd()) {
479
- let pack = (0, utils_1.getPackageJSON)();
480
- if (!pack || !pack.workspaces) {
481
- for (let i = 0; i <= 3; i++) {
482
- rootPath = path_1.default.join(process.cwd(), ...Array(i).fill('..'));
483
- pack = (0, utils_1.getPackageJSON)(rootPath);
484
- if (pack && pack.workspaces) {
485
- // log('Found workspace at '+packagePath);
486
- break;
487
- }
488
- }
489
- }
490
- if (!pack || !pack.workspaces) {
491
- warn(chalk_1.default.red('Could not find package workspaces. Make sure you run this command from a yarn workspace.'));
492
- logHelp();
493
- process.exit();
632
+ let pack = (0, utils_1.getPackageJSON)();
633
+ if (!pack || !pack.workspaces) {
634
+ for (let i = 0; i <= 3; i++) {
635
+ rootPath = path_1.default.join(process.cwd(), ...Array(i).fill('..'));
636
+ pack = (0, utils_1.getPackageJSON)(rootPath);
637
+ if (pack && pack.workspaces) {
638
+ // log('Found workspace at '+packagePath);
639
+ break;
640
+ }
494
641
  }
495
- // console.log(pack.workspaces);
496
- let res = [];
497
- checkWorkspaces(rootPath, pack.workspaces, res);
498
- return res;
642
+ }
643
+ if (!pack || !pack.workspaces) {
644
+ warn(
645
+ chalk_1.default.red('Could not find package workspaces. Make sure you run this command from a yarn workspace.'),
646
+ );
647
+ logHelp();
648
+ process.exit();
649
+ }
650
+ // console.log(pack.workspaces);
651
+ let res = [];
652
+ checkWorkspaces(rootPath, pack.workspaces, res);
653
+ return res;
499
654
  }
655
+
500
656
  exports.getLincdPackages = getLincdPackages;
657
+
501
658
  function setVariable(name, replacement) {
502
- //prepare name for regexp
503
- name = name.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
504
- variables[name] = replacement;
659
+ //prepare name for regexp
660
+ name = name.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
661
+ variables[name] = replacement;
505
662
  }
506
- var replaceVariablesInFile = (filePath) => __awaiter(void 0, void 0, void 0, function* () {
663
+
664
+ var replaceVariablesInFile = (filePath) =>
665
+ __awaiter(void 0, void 0, void 0, function* () {
507
666
  var fileContent = yield fs_extra_1.default.readFile(filePath, 'utf8').catch((err) => {
508
- console.warn(chalk_1.default.red('Could not read file ' + filePath));
667
+ console.warn(chalk_1.default.red('Could not read file ' + filePath));
509
668
  });
510
669
  if (fileContent) {
511
- var newContent = replaceCurlyVariables(fileContent);
512
- return fs_extra_1.default.writeFile(filePath, newContent);
513
- }
514
- else {
515
- return Promise.resolve();
670
+ var newContent = replaceCurlyVariables(fileContent);
671
+ return fs_extra_1.default.writeFile(filePath, newContent);
672
+ } else {
673
+ return Promise.resolve();
516
674
  }
517
- });
675
+ });
518
676
  var replaceCurlyVariables = function (string) {
519
- // var reg = new RegExp('\\$\\{'+key+'\\}','g');
520
- for (var key in variables) {
521
- string = string.replace(new RegExp('\\$\\{' + key + '\\}', 'g'), variables[key]);
522
- }
523
- return string;
677
+ // var reg = new RegExp('\\$\\{'+key+'\\}','g');
678
+ for (var key in variables) {
679
+ string = string.replace(new RegExp('\\$\\{' + key + '\\}', 'g'), variables[key]);
680
+ }
681
+ return string;
524
682
  };
525
683
  const capitalize = (str) => str.charAt(0).toUpperCase() + str.toLowerCase().slice(1);
526
684
  const camelCase = (str) => {
527
- let string = str.replace(/[^A-Za-z0-9]/g, ' ').split(' ');
528
- if (string.length > 1) {
529
- return string.reduce((result, word) => result + capitalize(word));
530
- }
531
- return str;
685
+ let string = str.replace(/[^A-Za-z0-9]/g, ' ').split(' ');
686
+ if (string.length > 1) {
687
+ return string.reduce((result, word) => result + capitalize(word));
688
+ }
689
+ return str;
532
690
  };
533
- const createOntology = (prefix, uriBase, basePath = process.cwd()) => __awaiter(void 0, void 0, void 0, function* () {
691
+ const createOntology = (prefix, uriBase, basePath = process.cwd()) =>
692
+ __awaiter(void 0, void 0, void 0, function* () {
534
693
  if (!prefix) {
535
- console.warn('Please provide a suggested prefix as the first argument');
536
- return;
694
+ console.warn('Please provide a suggested prefix as the first argument');
695
+ return;
537
696
  }
538
697
  let sourceFolder = getSourceFolder(basePath);
539
698
  let targetFolder = ensureFolderExists(sourceFolder, 'ontologies');
540
699
  if (!uriBase) {
541
- uriBase = 'http://lincd.org/ont/' + prefix + '/';
700
+ uriBase = 'http://lincd.org/ont/' + prefix + '/';
542
701
  }
543
702
  setVariable('uri_base', uriBase);
544
- let { hyphenName, camelCaseName, underscoreName } = (0, exports.setNameVariables)(prefix);
703
+ let {hyphenName, camelCaseName, underscoreName} = (0, exports.setNameVariables)(prefix);
545
704
  //copy ontology accessor file
546
705
  log("Creating files for ontology '" + prefix + "'");
547
706
  let targetFile = path_1.default.join(targetFolder, hyphenName + '.ts');
548
- fs_extra_1.default.copySync(path_1.default.join(__dirname, '..', 'defaults', 'package', 'src', 'ontologies', 'example-ontology.ts'), targetFile);
707
+ fs_extra_1.default.copySync(
708
+ path_1.default.join(__dirname, '..', 'defaults', 'package', 'src', 'ontologies', 'example-ontology.ts'),
709
+ targetFile,
710
+ );
549
711
  //copy data files
550
712
  let targetDataFile = path_1.default.join(targetFolder, '..', 'data', hyphenName + '.json');
551
713
  let targetDataFile2 = path_1.default.join(targetFolder, '..', 'data', hyphenName + '.json.d.ts');
552
- fs_extra_1.default.copySync(path_1.default.join(__dirname, '..', 'defaults', 'package', 'src', 'data', 'example-ontology.json'), targetDataFile);
553
- fs_extra_1.default.copySync(path_1.default.join(__dirname, '..', 'defaults', 'package', 'src', 'data', 'example-ontology.json.d.ts'), targetDataFile2);
714
+ fs_extra_1.default.copySync(
715
+ path_1.default.join(__dirname, '..', 'defaults', 'package', 'src', 'data', 'example-ontology.json'),
716
+ targetDataFile,
717
+ );
718
+ fs_extra_1.default.copySync(
719
+ path_1.default.join(__dirname, '..', 'defaults', 'package', 'src', 'data', 'example-ontology.json.d.ts'),
720
+ targetDataFile2,
721
+ );
554
722
  yield replaceVariablesInFiles(targetFile, targetDataFile, targetDataFile2);
555
- log(`Prepared a new ontology data files in ${chalk_1.default.magenta(targetDataFile.replace(basePath, ''))}`, `And an ontology accessor file in ${chalk_1.default.magenta(targetFile.replace(basePath, ''))}`);
723
+ log(
724
+ `Prepared a new ontology data files in ${chalk_1.default.magenta(targetDataFile.replace(basePath, ''))}`,
725
+ `And an ontology accessor file in ${chalk_1.default.magenta(targetFile.replace(basePath, ''))}`,
726
+ );
556
727
  //if this is not a lincd app (but a lincd package instead)
557
728
  if (!sourceFolder.includes('frontend')) {
558
- //then also add an import to index
559
- let indexPath = addLineToIndex(`import './ontologies/${hyphenName}';`, 'ontologies');
560
- log(`Added an import of this file from ${chalk_1.default.magenta(indexPath)}`);
729
+ //then also add an import to index
730
+ let indexPath = addLineToIndex(`import './ontologies/${hyphenName}';`, 'ontologies');
731
+ log(`Added an import of this file from ${chalk_1.default.magenta(indexPath)}`);
561
732
  }
562
- });
733
+ });
563
734
  exports.createOntology = createOntology;
564
735
  const addLineToIndex = function (line, insertMatchString) {
565
- //import ontology in index
566
- let indexPath = ['index.ts', 'index.tsx']
567
- .map((f) => path_1.default.join('src', f))
568
- .find((indexFileName) => {
569
- return fs_extra_1.default.existsSync(indexFileName);
736
+ //import ontology in index
737
+ let indexPath = ['index.ts', 'index.tsx']
738
+ .map((f) => path_1.default.join('src', f))
739
+ .find((indexFileName) => {
740
+ return fs_extra_1.default.existsSync(indexFileName);
570
741
  });
571
- if (indexPath) {
572
- let indexContents = fs_extra_1.default.readFileSync(indexPath, 'utf-8');
573
- let lines = indexContents.split(/\n/g);
574
- let newContents;
575
- for (var key in lines) {
576
- if (lines[key].indexOf(insertMatchString) !== -1) {
577
- //remove lines after this line and insert new line in its place
578
- lines[key] += `\n${line}`;
579
- newContents = lines.join('\n');
580
- // log("Found at "+key,lines,newContents);
581
- break;
582
- }
583
- }
584
- if (!newContents) {
585
- newContents = indexContents + `\n${line}`;
586
- // log("Added at end",newContents);
587
- }
588
- fs_extra_1.default.writeFileSync(indexPath, newContents);
742
+ if (indexPath) {
743
+ let indexContents = fs_extra_1.default.readFileSync(indexPath, 'utf-8');
744
+ let lines = indexContents.split(/\n/g);
745
+ let newContents;
746
+ for (var key in lines) {
747
+ if (lines[key].indexOf(insertMatchString) !== -1) {
748
+ //remove lines after this line and insert new line in its place
749
+ lines[key] += `\n${line}`;
750
+ newContents = lines.join('\n');
751
+ // log("Found at "+key,lines,newContents);
752
+ break;
753
+ }
754
+ }
755
+ if (!newContents) {
756
+ newContents = indexContents + `\n${line}`;
757
+ // log("Added at end",newContents);
589
758
  }
590
- return indexPath;
759
+ fs_extra_1.default.writeFileSync(indexPath, newContents);
760
+ }
761
+ return indexPath;
591
762
  };
592
763
  const replaceVariablesInFiles = function (...files) {
593
- return Promise.all(files.map((file) => {
594
- return replaceVariablesInFile(file);
595
- }));
764
+ return Promise.all(
765
+ files.map((file) => {
766
+ return replaceVariablesInFile(file);
767
+ }),
768
+ );
596
769
  };
597
770
  const replaceVariablesInFolder = function (folder) {
598
- //get all files in folder, including files that start with a dot
599
- glob(folder + '/**/*', { dot: true, nodir: true }, function (err, files) {
600
- if (err) {
601
- console.log('Error', err);
602
- }
603
- else {
604
- // console.log(files);
605
- return Promise.all(files.map((file) => {
606
- return replaceVariablesInFile(file);
607
- }));
608
- }
609
- });
771
+ //get all files in folder, including files that start with a dot
772
+ glob(folder + '/**/*', {dot: true, nodir: true}, function (err, files) {
773
+ if (err) {
774
+ console.log('Error', err);
775
+ } else {
776
+ // console.log(files);
777
+ return Promise.all(
778
+ files.map((file) => {
779
+ return replaceVariablesInFile(file);
780
+ }),
781
+ );
782
+ }
783
+ });
610
784
  };
611
785
  const replaceVariablesInFilesWithRoot = function (root, ...files) {
612
- return replaceVariablesInFiles(...files.map((f) => path_1.default.join(root, f)));
786
+ return replaceVariablesInFiles(...files.map((f) => path_1.default.join(root, f)));
613
787
  };
614
788
  const hasYarnInstalled = function () {
615
- return __awaiter(this, void 0, void 0, function* () {
616
- let version = (yield (0, utils_1.execPromise)('yarn --version').catch((err) => {
617
- console.log('yarn probably not working');
618
- return '';
619
- }));
620
- return version.toString().match(/[0-9]+/);
789
+ return __awaiter(this, void 0, void 0, function* () {
790
+ let version = yield (0, utils_1.execPromise)('yarn --version').catch((err) => {
791
+ console.log('yarn probably not working');
792
+ return '';
621
793
  });
794
+ return version.toString().match(/[0-9]+/);
795
+ });
622
796
  };
623
797
  const ensureFolderExists = function (...folders) {
624
- let target;
625
- folders.forEach((folder) => {
626
- target = target ? path_1.default.join(target, folder) : path_1.default.join(folder);
627
- if (!fs_extra_1.default.existsSync(target)) {
628
- fs_extra_1.default.mkdirSync(target);
629
- }
630
- });
631
- return target;
632
- /*let targetFolder = path.join(...folders);
633
- let parentDirectory = folders.slice(0, folders.length - 1);
634
- if (!fs.existsSync(targetFolder)) {
635
- if (fs.existsSync(path.join(...parentDirectory))) {
636
- fs.mkdirSync(targetFolder);
637
- } else {
638
- warn(
639
- `Please run this command from the root of your package. This command expects ${parentDirectory.toString()} to exists from that folder`,
640
- );
641
- }
798
+ let target;
799
+ folders.forEach((folder) => {
800
+ target = target ? path_1.default.join(target, folder) : path_1.default.join(folder);
801
+ if (!fs_extra_1.default.existsSync(target)) {
802
+ fs_extra_1.default.mkdirSync(target);
803
+ }
804
+ });
805
+ return target;
806
+ /*let targetFolder = path.join(...folders);
807
+ let parentDirectory = folders.slice(0, folders.length - 1);
808
+ if (!fs.existsSync(targetFolder)) {
809
+ if (fs.existsSync(path.join(...parentDirectory))) {
810
+ fs.mkdirSync(targetFolder);
811
+ } else {
812
+ warn(
813
+ `Please run this command from the root of your package. This command expects ${parentDirectory.toString()} to exists from that folder`,
814
+ );
642
815
  }
643
- return targetFolder;*/
816
+ }
817
+ return targetFolder;*/
644
818
  };
645
819
  const setNameVariables = function (name) {
646
- let hyphenName = name.replace(/[-_\s]+/g, '-');
647
- let camelCaseName = camelCase(name); //some-package --> someModule
648
- let underscoreName = name.replace(/[-\s]+/g, '_');
649
- let plainName = name.replace(/[-\s]+/g, '');
650
- //longer similar variables names should come before the shorter ones
651
- setVariable('underscore_name', underscoreName);
652
- setVariable('hyphen_name', hyphenName);
653
- setVariable('camel_name', camelCaseName);
654
- setVariable('name', name);
655
- setVariable('plain_name', plainName);
656
- return { hyphenName, camelCaseName, underscoreName, plainName };
820
+ let hyphenName = name.replace(/[-_\s]+/g, '-');
821
+ let camelCaseName = camelCase(name); //some-package --> someModule
822
+ let underscoreName = name.replace(/[-\s]+/g, '_');
823
+ let plainName = name.replace(/[-\s]+/g, '');
824
+ //longer similar variables names should come before the shorter ones
825
+ setVariable('underscore_name', underscoreName);
826
+ setVariable('hyphen_name', hyphenName);
827
+ setVariable('camel_name', camelCaseName);
828
+ setVariable('name', name);
829
+ setVariable('plain_name', plainName);
830
+ return {hyphenName, camelCaseName, underscoreName, plainName};
657
831
  };
658
832
  exports.setNameVariables = setNameVariables;
833
+
659
834
  function getSourceFolder(basePath = process.cwd()) {
660
- //LINCD App
661
- if (fs_extra_1.default.existsSync(path_1.default.join(basePath, 'frontend', 'src'))) {
662
- return path_1.default.join(basePath, 'frontend', 'src');
663
- }
664
- //LINCD package
665
- if (fs_extra_1.default.existsSync(path_1.default.join(basePath, 'src'))) {
666
- return path_1.default.join(basePath, 'src');
667
- }
668
- else {
669
- console.warn('Cannot find source folder');
670
- return path_1.default.join(basePath, 'src');
671
- }
835
+ //LINCD App
836
+ if (fs_extra_1.default.existsSync(path_1.default.join(basePath, 'frontend', 'src'))) {
837
+ return path_1.default.join(basePath, 'frontend', 'src');
838
+ }
839
+ //LINCD package
840
+ if (fs_extra_1.default.existsSync(path_1.default.join(basePath, 'src'))) {
841
+ return path_1.default.join(basePath, 'src');
842
+ } else {
843
+ console.warn('Cannot find source folder');
844
+ return path_1.default.join(basePath, 'src');
845
+ }
672
846
  }
673
- const createShape = (name, basePath = process.cwd()) => __awaiter(void 0, void 0, void 0, function* () {
847
+
848
+ const createShape = (name, basePath = process.cwd()) =>
849
+ __awaiter(void 0, void 0, void 0, function* () {
674
850
  let sourceFolder = getSourceFolder(basePath);
675
851
  let targetFolder = ensureFolderExists(sourceFolder, 'shapes');
676
- let { hyphenName, camelCaseName, underscoreName } = (0, exports.setNameVariables)(name);
852
+ let {hyphenName, camelCaseName, underscoreName} = (0, exports.setNameVariables)(name);
677
853
  //copy default shape file
678
854
  // log("Creating files for shape '" + name + "'");
679
855
  let targetFile = path_1.default.join(targetFolder, hyphenName + '.ts');
@@ -684,14 +860,15 @@ const createShape = (name, basePath = process.cwd()) => __awaiter(void 0, void 0
684
860
  //if this is NOT a lincd app (but a lincd package)
685
861
  let indexPath;
686
862
  if (!sourceFolder.includes('frontend')) {
687
- indexPath = addLineToIndex(`import './shapes/${hyphenName}';`, 'shapes');
688
- log(`Added an import of this file from ${chalk_1.default.magenta(indexPath)}`);
863
+ indexPath = addLineToIndex(`import './shapes/${hyphenName}';`, 'shapes');
864
+ log(`Added an import of this file from ${chalk_1.default.magenta(indexPath)}`);
689
865
  }
690
- });
866
+ });
691
867
  exports.createShape = createShape;
692
- const createSetComponent = (name, basePath = process.cwd()) => __awaiter(void 0, void 0, void 0, function* () {
868
+ const createSetComponent = (name, basePath = process.cwd()) =>
869
+ __awaiter(void 0, void 0, void 0, function* () {
693
870
  let targetFolder = ensureFolderExists(basePath, 'src', 'components');
694
- let { hyphenName, camelCaseName, underscoreName } = (0, exports.setNameVariables)(name);
871
+ let {hyphenName, camelCaseName, underscoreName} = (0, exports.setNameVariables)(name);
695
872
  //copy default shape file
696
873
  log("Creating files for set component '" + name + "'");
697
874
  let targetFile = path_1.default.join(targetFolder, hyphenName + '.tsx');
@@ -701,13 +878,18 @@ const createSetComponent = (name, basePath = process.cwd()) => __awaiter(void 0,
701
878
  //replace variables in some of the copied files
702
879
  yield replaceVariablesInFiles(targetFile, targetFile2);
703
880
  let indexPath = addLineToIndex(`import './components/${hyphenName}';`, 'components');
704
- log(`Created a new set component in ${chalk_1.default.magenta(targetFile.replace(basePath, ''))}`, `Created a new stylesheet in ${chalk_1.default.magenta(targetFile2.replace(basePath, ''))}`, `Added an import of this file from ${chalk_1.default.magenta(indexPath)}`);
705
- });
881
+ log(
882
+ `Created a new set component in ${chalk_1.default.magenta(targetFile.replace(basePath, ''))}`,
883
+ `Created a new stylesheet in ${chalk_1.default.magenta(targetFile2.replace(basePath, ''))}`,
884
+ `Added an import of this file from ${chalk_1.default.magenta(indexPath)}`,
885
+ );
886
+ });
706
887
  exports.createSetComponent = createSetComponent;
707
- const createComponent = (name, basePath = process.cwd()) => __awaiter(void 0, void 0, void 0, function* () {
888
+ const createComponent = (name, basePath = process.cwd()) =>
889
+ __awaiter(void 0, void 0, void 0, function* () {
708
890
  let sourceFolder = getSourceFolder(basePath);
709
891
  let targetFolder = ensureFolderExists(sourceFolder, 'components');
710
- let { hyphenName, camelCaseName, underscoreName } = (0, exports.setNameVariables)(name);
892
+ let {hyphenName, camelCaseName, underscoreName} = (0, exports.setNameVariables)(name);
711
893
  //copy default shape file
712
894
  log("Creating files for component '" + name + "'");
713
895
  let targetFile = path_1.default.join(targetFolder, hyphenName + '.tsx');
@@ -716,52 +898,57 @@ const createComponent = (name, basePath = process.cwd()) => __awaiter(void 0, vo
716
898
  fs_extra_1.default.copySync(path_1.default.join(__dirname, '..', 'defaults', 'component.scss'), targetFile2);
717
899
  //replace variables in some of the copied files
718
900
  yield replaceVariablesInFiles(targetFile, targetFile2);
719
- log(`Created a new component template in ${chalk_1.default.magenta(targetFile.replace(basePath, ''))}`, `Created component stylesheet template in ${chalk_1.default.magenta(targetFile2.replace(basePath, ''))}`);
901
+ log(
902
+ `Created a new component template in ${chalk_1.default.magenta(targetFile.replace(basePath, ''))}`,
903
+ `Created component stylesheet template in ${chalk_1.default.magenta(targetFile2.replace(basePath, ''))}`,
904
+ );
720
905
  //if this is not a lincd app (but a lincd package instead)
721
906
  if (!sourceFolder.includes('frontend')) {
722
- //then also add an import to index
723
- let indexPath = addLineToIndex(`import './components/${hyphenName}';`, 'components');
724
- log(`Added an import of this file from ${chalk_1.default.magenta(indexPath)}`);
907
+ //then also add an import to index
908
+ let indexPath = addLineToIndex(`import './components/${hyphenName}';`, 'components');
909
+ log(`Added an import of this file from ${chalk_1.default.magenta(indexPath)}`);
725
910
  }
726
- });
911
+ });
727
912
  exports.createComponent = createComponent;
728
- const depCheck = () => __awaiter(void 0, void 0, void 0, function* () {
913
+ const depCheck = () =>
914
+ __awaiter(void 0, void 0, void 0, function* () {
729
915
  (0, depcheck_1.default)(process.cwd(), {}, (results) => {
730
- if (results.missing) {
731
- let missing = Object.keys(results.missing);
732
- //currently react is not an explicit dependency, but we should add it as a peer dependency
733
- missing.splice(missing.indexOf('react'));
734
- if (missing.length > 0) {
735
- console.warn(chalk_1.default.red('Missing dependencies:\n\t' + missing.join(',\n\t')));
736
- }
916
+ if (results.missing) {
917
+ let missing = Object.keys(results.missing);
918
+ //currently react is not an explicit dependency, but we should add it as a peer dependency
919
+ missing.splice(missing.indexOf('react'));
920
+ if (missing.length > 0) {
921
+ console.warn(chalk_1.default.red('Missing dependencies:\n\t' + missing.join(',\n\t')));
737
922
  }
738
- // if(Object.keys(results.invalidFiles).length > 0) {
739
- // console.warn(chalk.red("Invalid files:\n")+Object.keys(results.invalidFiles).join(",\n"));
740
- // }
741
- // if(Object.keys(results.invalidDirs).length > 0) {
742
- // console.warn(chalk.red("Invalid dirs:\n")+results.invalidDirs.toString());
743
- // }
744
- // if(results.unused) {
745
- // console.warn("Unused dependencies: "+results.missing.join(", "));
746
- // }
923
+ }
924
+ // if(Object.keys(results.invalidFiles).length > 0) {
925
+ // console.warn(chalk.red("Invalid files:\n")+Object.keys(results.invalidFiles).join(",\n"));
926
+ // }
927
+ // if(Object.keys(results.invalidDirs).length > 0) {
928
+ // console.warn(chalk.red("Invalid dirs:\n")+results.invalidDirs.toString());
929
+ // }
930
+ // if(results.unused) {
931
+ // console.warn("Unused dependencies: "+results.missing.join(", "));
932
+ // }
747
933
  });
748
- });
934
+ });
749
935
  exports.depCheck = depCheck;
750
- const createPackage = (name, uriBase, basePath = process.cwd()) => __awaiter(void 0, void 0, void 0, function* () {
936
+ const createPackage = (name, uriBase, basePath = process.cwd()) =>
937
+ __awaiter(void 0, void 0, void 0, function* () {
751
938
  //if ran with npx, basePath will be the root directory of the repository, even if we're executing from a sub folder (the root directory is where node_modules lives and package.json with workspaces)
752
939
  //so we manually find a packages folder, if it exists we go into that.
753
940
  if (fs_extra_1.default.existsSync(path_1.default.join(basePath, 'packages'))) {
754
- basePath = path_1.default.join(basePath, 'packages');
941
+ basePath = path_1.default.join(basePath, 'packages');
755
942
  }
756
943
  if (!name) {
757
- console.warn('Please provide a name as the first argument');
758
- return;
944
+ console.warn('Please provide a name as the first argument');
945
+ return;
759
946
  }
760
947
  //let's remove scope for variable names
761
948
  let [packageName, scope, cleanPackageName] = name.match(/(@[\w\-]+\/)?([\w\-]+)/);
762
949
  let targetFolder = ensureFolderExists(basePath, cleanPackageName);
763
950
  if (!uriBase) {
764
- uriBase = 'http://lincd.org/ont/' + name;
951
+ uriBase = 'http://lincd.org/ont/' + name;
765
952
  }
766
953
  setVariable('uri_base', uriBase + '/');
767
954
  //find @scope and the next part between 2 slashes after
@@ -773,11 +960,12 @@ const createPackage = (name, uriBase, basePath = process.cwd()) => __awaiter(voi
773
960
  setVariable('package_name', name);
774
961
  //extra variable for clarity (will be same as 'name')
775
962
  setVariable('output_file_name', name);
776
- let { hyphenName, camelCaseName, underscoreName } = (0, exports.setNameVariables)(cleanPackageName);
963
+ let {hyphenName, camelCaseName, underscoreName} = (0, exports.setNameVariables)(cleanPackageName);
777
964
  log("Creating new LINCD package '" + name + "'");
778
965
  fs_extra_1.default.copySync(path_1.default.join(__dirname, '..', 'defaults', 'package'), targetFolder);
779
966
  //replace variables in some of the copied files
780
- yield Promise.all([
967
+ yield Promise.all(
968
+ [
781
969
  'src/index.ts',
782
970
  'package.json',
783
971
  'Gruntfile.js',
@@ -785,49 +973,61 @@ const createPackage = (name, uriBase, basePath = process.cwd()) => __awaiter(voi
785
973
  'src/shapes/ExampleShapeClass.ts',
786
974
  'src/ontologies/example-ontology.ts',
787
975
  'src/data/example-ontology.json',
788
- ]
976
+ ]
789
977
  .map((f) => path_1.default.join(targetFolder, f))
790
978
  .map((file) => {
791
- return replaceVariablesInFile(file);
792
- }));
979
+ return replaceVariablesInFile(file);
980
+ }),
981
+ );
793
982
  //rename these to a file name similar to the pkg name
794
983
  [
795
- 'src/ontologies/example-ontology.ts',
796
- 'src/data/example-ontology.json',
797
- 'src/data/example-ontology.json.d.ts',
984
+ 'src/ontologies/example-ontology.ts',
985
+ 'src/data/example-ontology.json',
986
+ 'src/data/example-ontology.json.d.ts',
798
987
  ].forEach((f) => {
799
- let parts = f.split('/');
800
- let newParts = [...parts];
801
- let [name, ...extensions] = newParts.pop().split('.');
802
- let newName = hyphenName + '.' + extensions.join('.');
803
- console.log('rename ', path_1.default.join(targetFolder, f), path_1.default.join(targetFolder, ...newParts, newName));
804
- fs_extra_1.default.renameSync(path_1.default.join(targetFolder, f), path_1.default.join(targetFolder, ...newParts, newName));
988
+ let parts = f.split('/');
989
+ let newParts = [...parts];
990
+ let [name, ...extensions] = newParts.pop().split('.');
991
+ let newName = hyphenName + '.' + extensions.join('.');
992
+ console.log(
993
+ 'rename ',
994
+ path_1.default.join(targetFolder, f),
995
+ path_1.default.join(targetFolder, ...newParts, newName),
996
+ );
997
+ fs_extra_1.default.renameSync(
998
+ path_1.default.join(targetFolder, f),
999
+ path_1.default.join(targetFolder, ...newParts, newName),
1000
+ );
1001
+ });
1002
+ let version = yield (0, utils_1.execPromise)('yarn --version').catch((err) => {
1003
+ console.log('yarn probably not working');
1004
+ return '';
805
1005
  });
806
- let version = (yield (0, utils_1.execPromise)('yarn --version').catch((err) => {
807
- console.log('yarn probably not working');
808
- return '';
809
- }));
810
1006
  let installCommand = version.toString().match(/[0-9]+/) ? 'yarn install' : 'npm install';
811
1007
  yield (0, utils_1.execp)(`cd ${targetFolder} && ${installCommand} && npm exec lincd build`, true).catch((err) => {
812
- console.warn('Could not install dependencies');
1008
+ console.warn('Could not install dependencies');
813
1009
  });
814
- log(`Prepared a new LINCD package in ${chalk_1.default.magenta(targetFolder)}`, `Run ${chalk_1.default.blueBright('yarn build')} from this directory to build once`, `Or ${chalk_1.default.blueBright('yarn dev')} to continuously rebuild on file changes`);
815
- });
1010
+ log(
1011
+ `Prepared a new LINCD package in ${chalk_1.default.magenta(targetFolder)}`,
1012
+ `Run ${chalk_1.default.blueBright('yarn build')} from this directory to build once`,
1013
+ `Or ${chalk_1.default.blueBright('yarn dev')} to continuously rebuild on file changes`,
1014
+ );
1015
+ });
816
1016
  exports.createPackage = createPackage;
817
1017
  var getNextVersion = function (version) {
818
- let parts = version.split('.');
819
- return parts[0] + '.' + parts[1] + '.' + (parseInt(parts[2]) + 1).toString();
1018
+ let parts = version.split('.');
1019
+ return parts[0] + '.' + parts[1] + '.' + (parseInt(parts[2]) + 1).toString();
820
1020
  };
821
1021
  var getNextMajorVersion = function (version) {
822
- let parts = version.split('.');
823
- return (parseInt(parts[0]) + 1).toString() + '.0.0';
1022
+ let parts = version.split('.');
1023
+ return (parseInt(parts[0]) + 1).toString() + '.0.0';
824
1024
  };
825
1025
  var getNextMinorVersion = function (version) {
826
- let parts = version.split('.');
827
- return parts[0] + '.' + (parseInt(parts[1]) + 1).toString() + '.0';
1026
+ let parts = version.split('.');
1027
+ return parts[0] + '.' + (parseInt(parts[1]) + 1).toString() + '.0';
828
1028
  };
829
1029
  var buildFailed = function (output) {
830
- return output.indexOf('Aborted due to warnings') !== -1 && output.indexOf('Command failed') !== -1;
1030
+ return output.indexOf('Aborted due to warnings') !== -1 && output.indexOf('Command failed') !== -1;
831
1031
  };
832
1032
  /*program.command('shapes').action(async () => {
833
1033
  //we've imported require-extensions from npm so that we can use this
@@ -867,67 +1067,67 @@ var buildFailed = function (output) {
867
1067
  }
868
1068
  });*/
869
1069
  const register = function (registryURL) {
870
- if (fs_extra_1.default.existsSync(process.cwd() + '/package.json')) {
871
- var pack = JSON.parse(fs_extra_1.default.readFileSync(process.cwd() + '/package.json', 'utf8'));
872
- let version = pack.version;
873
- let packageName = pack.name;
874
- // let author = pack.author;
875
- // let description = pack.description;
876
- //
877
- // let authorName = pack.author;
878
- // if (pack.author.name) {
879
- // authorName = pack.author.name;
880
- // }
881
- console.log(chalk_1.default.cyan('registering package ' + packageName + ' ' + version + ' in the LINCD registry'));
882
- return fetch(registryURL + '/register', {
883
- method: 'POST',
884
- headers: {
885
- Accept: 'application/json, text/plain, */*',
886
- 'Content-Type': 'application/json',
887
- },
888
- body: JSON.stringify({ package: packageName, version }),
889
- // body: JSON.stringify({package: packageName, version, author}),
890
- })
891
- .then((res) => res.json())
892
- .then((json) => {
893
- if (json.error) {
894
- console.log(chalk_1.default.red('Response: ' + json.error));
895
- }
896
- else if (json.result) {
897
- console.log(chalk_1.default.blueBright('Response: ') + json.result);
898
- if (json.warning) {
899
- console.log(chalk_1.default.red('Warning: ') + json.warning);
900
- }
901
- }
902
- })
903
- .catch((err) => {
904
- console.warn(chalk_1.default.red('Warning: ') + 'Could not connect to LINCD registry');
905
- });
906
- }
907
- else {
908
- console.warn(chalk_1.default.red('Warning:') + ' not found: ' + process.cwd() + '/package.json');
909
- }
1070
+ if (fs_extra_1.default.existsSync(process.cwd() + '/package.json')) {
1071
+ var pack = JSON.parse(fs_extra_1.default.readFileSync(process.cwd() + '/package.json', 'utf8'));
1072
+ let version = pack.version;
1073
+ let packageName = pack.name;
1074
+ // let author = pack.author;
1075
+ // let description = pack.description;
1076
+ //
1077
+ // let authorName = pack.author;
1078
+ // if (pack.author.name) {
1079
+ // authorName = pack.author.name;
1080
+ // }
1081
+ console.log(chalk_1.default.cyan('registering package ' + packageName + ' ' + version + ' in the LINCD registry'));
1082
+ return fetch(registryURL + '/register', {
1083
+ method: 'POST',
1084
+ headers: {
1085
+ Accept: 'application/json, text/plain, */*',
1086
+ 'Content-Type': 'application/json',
1087
+ },
1088
+ body: JSON.stringify({package: packageName, version}),
1089
+ // body: JSON.stringify({package: packageName, version, author}),
1090
+ })
1091
+ .then((res) => res.json())
1092
+ .then((json) => {
1093
+ if (json.error) {
1094
+ console.log(chalk_1.default.red('Response: ' + json.error));
1095
+ } else if (json.result) {
1096
+ console.log(chalk_1.default.blueBright('Response: ') + json.result);
1097
+ if (json.warning) {
1098
+ console.log(chalk_1.default.red('Warning: ') + json.warning);
1099
+ }
1100
+ }
1101
+ })
1102
+ .catch((err) => {
1103
+ console.warn(chalk_1.default.red('Warning: ') + 'Could not connect to LINCD registry');
1104
+ });
1105
+ } else {
1106
+ console.warn(chalk_1.default.red('Warning:') + ' not found: ' + process.cwd() + '/package.json');
1107
+ }
910
1108
  };
911
1109
  exports.register = register;
912
- const buildMetadata = () => __awaiter(void 0, void 0, void 0, function* () {
1110
+ const buildMetadata = () =>
1111
+ __awaiter(void 0, void 0, void 0, function* () {
913
1112
  // require('@babel/register')({extensions: ['js', '.ts', '.tsx']});
914
1113
  //NOTE: we can not rely on the LincdWebApp shape from lincd-server here, because that would make the initial build of all modules a lot trickier
915
1114
  //see, CLI needs to be built as one of the first things in order to build other things. So it cannot rely on lincd-server, which relies on 10 other packages
916
1115
  let app;
917
1116
  //set the URL of the app as the URI of its node
918
1117
  let envVars = yield (0, env_cmd_1.GetEnvVars)({
919
- envFile: {
920
- filePath: '.env-cmdrc.json',
921
- },
1118
+ envFile: {
1119
+ filePath: '.env-cmdrc.json',
1120
+ },
922
1121
  });
923
1122
  if (envVars[process.env.NODE_ENV] && envVars[process.env.NODE_ENV].SITE_ROOT) {
924
- //get the site root of the current environment
925
- app = models_1.NamedNode.getOrCreate(envVars[process.env.NODE_ENV].SITE_ROOT);
926
- }
927
- else {
928
- warn('Cannot find environment variable SITE_ROOT. Make sure SITE_ROOT is set (likely in .env-cmdrc.json) for the current environment: ' +
929
- process.env.NODE_ENV);
930
- app = models_1.NamedNode.create();
1123
+ //get the site root of the current environment
1124
+ app = models_1.NamedNode.getOrCreate(envVars[process.env.NODE_ENV].SITE_ROOT);
1125
+ } else {
1126
+ warn(
1127
+ 'Cannot find environment variable SITE_ROOT. Make sure SITE_ROOT is set (likely in .env-cmdrc.json) for the current environment: ' +
1128
+ process.env.NODE_ENV,
1129
+ );
1130
+ app = models_1.NamedNode.create();
931
1131
  }
932
1132
  let updatedPaths = [];
933
1133
  var localPackagePaths = getLocalPackagePaths();
@@ -935,609 +1135,679 @@ const buildMetadata = () => __awaiter(void 0, void 0, void 0, function* () {
935
1135
  let metadataFolder = path_1.default.join(process.cwd(), 'data', 'metadata');
936
1136
  yield fs_extra_1.default.ensureDir(metadataFolder); //{recursive:true} but not needed with fs-extra
937
1137
  for (const [packageCodeName, packagePath, lincdPackagePath, isAppPackage] of localPackagePaths) {
938
- let errors = false;
939
- //TODO: check if this resolves, if not, skip it (for initial setup)
940
- Promise.resolve().then(() => __importStar(require('lincd-modules/lib/scripts/package-metadata.js'))).then((script) => __awaiter(void 0, void 0, void 0, function* () {
941
- yield script.getPackageMetadata(packagePath, lincdPackagePath).then((response) => __awaiter(void 0, void 0, void 0, function* () {
1138
+ let errors = false;
1139
+ //TODO: check if this resolves, if not, skip it (for initial setup)
1140
+ Promise.resolve()
1141
+ .then(() => __importStar(require('lincd-modules/lib/scripts/package-metadata.js')))
1142
+ .then((script) =>
1143
+ __awaiter(void 0, void 0, void 0, function* () {
1144
+ yield script.getPackageMetadata(packagePath, lincdPackagePath).then((response) =>
1145
+ __awaiter(void 0, void 0, void 0, function* () {
942
1146
  if (response.errors.length > 0) {
943
- // console.log(JSON.stringify(response));
944
- warn('Error processing ' + packagePath + ':\n' + response.errors.join('\n'));
945
- // throw response
946
- errors = true;
1147
+ // console.log(JSON.stringify(response));
1148
+ warn('Error processing ' + packagePath + ':\n' + response.errors.join('\n'));
1149
+ // throw response
1150
+ errors = true;
1151
+ } else {
1152
+ if (!response.packageUri) {
1153
+ console.warn('No package URI from meta data. Not building meta data for this package');
1154
+ return;
1155
+ }
1156
+ let pkgNode = models_1.NamedNode.getOrCreate(response.packageUri);
1157
+ //connect the packages to the app
1158
+ let lincdApp = (0, NameSpace_1.createNameSpace)('http://lincd.org/ont/lincd-app/');
1159
+ Prefix_1.Prefix.add('lincdApp', 'http://lincd.org/ont/lincd-app/');
1160
+ if (isAppPackage) {
1161
+ //Note: this needs to match with LincdWebApp.ownPackage accessor;
1162
+ app.overwrite(lincdApp('ownPackage'), pkgNode);
1163
+ } else {
1164
+ //Note: this needs to match with LincdWebApp.packages accessor;
1165
+ app.set(lincdApp('maintainsPackage'), pkgNode);
1166
+ }
1167
+ //write this graph to a jsonld file
1168
+ let packageMetaData = JSON.stringify(response.result, null, 2);
1169
+ let metadataFile = path_1.default.join(metadataFolder, packageCodeName + '.json');
1170
+ yield fs_extra_1.default.writeFile(metadataFile, packageMetaData).then(() => {
1171
+ updatedPaths.push(metadataFile);
1172
+ });
947
1173
  }
948
- else {
949
- if (!response.packageUri) {
950
- console.warn('No package URI from meta data. Not building meta data for this package');
951
- return;
952
- }
953
- let pkgNode = models_1.NamedNode.getOrCreate(response.packageUri);
954
- //connect the packages to the app
955
- let lincdApp = (0, NameSpace_1.createNameSpace)('http://lincd.org/ont/lincd-app/');
956
- Prefix_1.Prefix.add('lincdApp', 'http://lincd.org/ont/lincd-app/');
957
- if (isAppPackage) {
958
- //Note: this needs to match with LincdWebApp.ownPackage accessor;
959
- app.overwrite(lincdApp('ownPackage'), pkgNode);
960
- }
961
- else {
962
- //Note: this needs to match with LincdWebApp.packages accessor;
963
- app.set(lincdApp('maintainsPackage'), pkgNode);
964
- }
965
- //write this graph to a jsonld file
966
- let packageMetaData = JSON.stringify(response.result, null, 2);
967
- let metadataFile = path_1.default.join(metadataFolder, packageCodeName + '.json');
968
- yield fs_extra_1.default.writeFile(metadataFile, packageMetaData).then(() => {
969
- updatedPaths.push(metadataFile);
970
- });
971
- }
972
- }));
973
- }));
974
- //enable this when testing if you don't want to continue with building other metadata when an errors occur
975
- // if (errors) break;
1174
+ }),
1175
+ );
1176
+ }),
1177
+ );
1178
+ //enable this when testing if you don't want to continue with building other metadata when an errors occur
1179
+ // if (errors) break;
976
1180
  }
977
1181
  let packageMetaData = yield JSONLDWriter_1.JSONLDWriter.stringify(app, process.env.NODE_ENV === 'development');
978
1182
  let metadataFile = path_1.default.join(metadataFolder, '_app.json');
979
1183
  yield fs_extra_1.default.writeFile(metadataFile, packageMetaData).then(() => {
980
- updatedPaths.push(metadataFile);
1184
+ updatedPaths.push(metadataFile);
981
1185
  });
982
1186
  return updatedPaths;
983
- });
1187
+ });
984
1188
  exports.buildMetadata = buildMetadata;
1189
+
985
1190
  function getLocalPackagePaths() {
986
- let packagePaths = [];
987
- //add the APP package itself
988
- let appPackagePath = process.cwd();
989
- let appLincdPackagePath = path_1.default.join(appPackagePath, 'frontend', 'src', 'package.ts');
990
- if (fs_extra_1.default.existsSync(appPackagePath)) {
991
- let packageJSON = (0, utils_1.getPackageJSON)(appPackagePath);
992
- packagePaths.push([packageJSON.name, appPackagePath, appLincdPackagePath, true]);
993
- }
994
- else {
995
- console.log('Not a LINCD app');
996
- }
997
- //NOTE: we could also switch to checking 'workspaces'?
998
- let packagesFolder = path_1.default.join(process.cwd(), 'packages');
999
- if (fs_extra_1.default.existsSync(packagesFolder)) {
1000
- let localPackages = fs_extra_1.default.readdirSync(packagesFolder);
1001
- localPackages.forEach((packageFolderName) => {
1002
- packagePaths.push([
1003
- packageFolderName,
1004
- path_1.default.join(packagesFolder, packageFolderName),
1005
- path_1.default.join(packagesFolder, packageFolderName, 'lib', 'package.js'),
1006
- ]);
1007
- });
1008
- }
1009
- return packagePaths;
1191
+ let packagePaths = [];
1192
+ //add the APP package itself
1193
+ let appPackagePath = process.cwd();
1194
+ let appLincdPackagePath = path_1.default.join(appPackagePath, 'frontend', 'src', 'package.ts');
1195
+ if (fs_extra_1.default.existsSync(appPackagePath)) {
1196
+ let packageJSON = (0, utils_1.getPackageJSON)(appPackagePath);
1197
+ packagePaths.push([packageJSON.name, appPackagePath, appLincdPackagePath, true]);
1198
+ } else {
1199
+ console.log('Not a LINCD app');
1200
+ }
1201
+ //NOTE: we could also switch to checking 'workspaces'?
1202
+ let packagesFolder = path_1.default.join(process.cwd(), 'packages');
1203
+ if (fs_extra_1.default.existsSync(packagesFolder)) {
1204
+ let localPackages = fs_extra_1.default.readdirSync(packagesFolder);
1205
+ localPackages.forEach((packageFolderName) => {
1206
+ packagePaths.push([
1207
+ packageFolderName,
1208
+ path_1.default.join(packagesFolder, packageFolderName),
1209
+ path_1.default.join(packagesFolder, packageFolderName, 'lib', 'package.js'),
1210
+ ]);
1211
+ });
1212
+ }
1213
+ return packagePaths;
1010
1214
  }
1215
+
1011
1216
  const buildPackage = (target, target2, packagePath = process.cwd(), logResults = true) => {
1012
- if (target == 'production' || target == 'es5' || target == 'es6' || !target) {
1013
- if (!fs_extra_1.default.existsSync(path_1.default.join(packagePath, 'Gruntfile.js'))) {
1014
- console.warn(`No Gruntfile found at ${packagePath}\\Gruntfile.js. Cannot build.`);
1015
- return;
1016
- }
1017
- var nodeEnv = '';
1018
- if (target == 'production') {
1019
- if (!(target2 == 'es5' || target2 == 'es6' || typeof target2 == 'undefined')) {
1020
- console.warn('unknown second build target. Use es5 or es6', target2);
1021
- return;
1022
- }
1023
- var isWindows = /^win/.test(process.platform);
1024
- if (isWindows) {
1025
- nodeEnv = 'SET NODE_ENV=production&& ';
1026
- }
1027
- else {
1028
- nodeEnv = "NODE_ENV='production' ";
1029
- }
1030
- }
1031
- if (!target) {
1032
- target = 'es6';
1033
- }
1034
- log('building once: ' +
1035
- nodeEnv +
1036
- 'grunt build' +
1037
- (target ? '-' + target : '') +
1038
- (target2 ? '-' + target2 : '') +
1039
- ' --color');
1040
- let method = logResults ? utils_1.execp : utils_1.execPromise;
1041
- //execute the command to build the method, and provide the current work directory as option
1042
- return method(nodeEnv + 'grunt build' + (target ? '-' + target : '') + (target2 ? '-' + target2 : '') + ' --color', false, false, { cwd: packagePath }).catch((err) => {
1043
- process.exit(1);
1044
- });
1217
+ if (target == 'production' || target == 'es5' || target == 'es6' || !target) {
1218
+ if (!fs_extra_1.default.existsSync(path_1.default.join(packagePath, 'Gruntfile.js'))) {
1219
+ console.warn(`No Gruntfile found at ${packagePath}\\Gruntfile.js. Cannot build.`);
1220
+ return;
1045
1221
  }
1046
- else {
1047
- console.warn('unknown build target. Use es5, es6 or production.');
1222
+ var nodeEnv = '';
1223
+ if (target == 'production') {
1224
+ if (!(target2 == 'es5' || target2 == 'es6' || typeof target2 == 'undefined')) {
1225
+ console.warn('unknown second build target. Use es5 or es6', target2);
1226
+ return;
1227
+ }
1228
+ var isWindows = /^win/.test(process.platform);
1229
+ if (isWindows) {
1230
+ nodeEnv = 'SET NODE_ENV=production&& ';
1231
+ } else {
1232
+ nodeEnv = "NODE_ENV='production' ";
1233
+ }
1234
+ }
1235
+ if (!target) {
1236
+ target = 'es6';
1048
1237
  }
1238
+ log(
1239
+ 'building once: ' +
1240
+ nodeEnv +
1241
+ 'grunt build' +
1242
+ (target ? '-' + target : '') +
1243
+ (target2 ? '-' + target2 : '') +
1244
+ ' --color',
1245
+ );
1246
+ let method = logResults ? utils_1.execp : utils_1.execPromise;
1247
+ //execute the command to build the method, and provide the current work directory as option
1248
+ return method(
1249
+ nodeEnv + 'grunt build' + (target ? '-' + target : '') + (target2 ? '-' + target2 : '') + ' --color',
1250
+ false,
1251
+ false,
1252
+ {cwd: packagePath},
1253
+ ).catch((err) => {
1254
+ process.exit(1);
1255
+ });
1256
+ } else {
1257
+ console.warn('unknown build target. Use es5, es6 or production.');
1258
+ }
1049
1259
  };
1050
1260
  exports.buildPackage = buildPackage;
1051
1261
  const getLastBuildTime = (packagePath) => {
1052
- return getLastModifiedFile(packagePath + '/@(builds|lib|dist)/**/*.js');
1262
+ return getLastModifiedFile(packagePath + '/@(builds|lib|dist)/**/*.js');
1053
1263
  };
1054
1264
  const getLastModifiedSourceTime = (packagePath) => {
1055
- return getLastModifiedFile(packagePath + '/@(src|data|scss)/**/*', {
1056
- ignore: [packagePath + '/**/*.scss.json', packagePath + '/**/*.d.ts'],
1057
- });
1265
+ return getLastModifiedFile(packagePath + '/@(src|data|scss)/**/*', {
1266
+ ignore: [packagePath + '/**/*.scss.json', packagePath + '/**/*.d.ts'],
1267
+ });
1058
1268
  };
1059
1269
  const getLastCommitTime = (packagePath) => {
1060
- // console.log(`git log -1 --format=%ci -- ${packagePath}`);
1061
- // process.exit();
1062
- return (0, utils_1.execPromise)(`git log -1 --format="%h %ci" -- ${packagePath}`)
1063
- .then((result) => __awaiter(void 0, void 0, void 0, function* () {
1270
+ // console.log(`git log -1 --format=%ci -- ${packagePath}`);
1271
+ // process.exit();
1272
+ return (0, utils_1.execPromise)(`git log -1 --format="%h %ci" -- ${packagePath}`)
1273
+ .then((result) =>
1274
+ __awaiter(void 0, void 0, void 0, function* () {
1064
1275
  let commitId = result.substring(0, result.indexOf(' '));
1065
1276
  let date = result.substring(commitId.length + 1);
1066
1277
  let lastCommitDate = new Date(date);
1067
1278
  let changes = yield (0, utils_1.execPromise)(`git show --stat --oneline ${commitId} -- ${packagePath}`);
1068
1279
  // log(packagePath,result,lastCommit);
1069
1280
  // log(changes);
1070
- return { date: lastCommitDate, changes, commitId };
1071
- }))
1072
- .catch(({ error, stdout, stderr }) => {
1073
- debugInfo(chalk_1.default.red('Git error: ') + error.message.toString());
1074
- return null;
1281
+ return {date: lastCommitDate, changes, commitId};
1282
+ }),
1283
+ )
1284
+ .catch(({error, stdout, stderr}) => {
1285
+ debugInfo(chalk_1.default.red('Git error: ') + error.message.toString());
1286
+ return null;
1075
1287
  });
1076
1288
  };
1077
1289
  const getLastModifiedFile = (filePath, config = {}) => {
1078
- var files = glob.sync(filePath, config);
1079
- // console.log(files.join(" - "));
1080
- var lastModifiedName;
1081
- var lastModified;
1082
- var lastModifiedTime = 0;
1083
- files.forEach((fileName) => {
1084
- if (fs_extra_1.default.lstatSync(fileName).isDirectory()) {
1085
- // console.log("skipping directory "+fileName);
1086
- return;
1087
- }
1088
- let mtime = fs_extra_1.default.statSync(path_1.default.join(fileName)).mtime;
1089
- let modifiedTime = mtime.getTime();
1090
- if (modifiedTime > lastModifiedTime) {
1091
- // console.log(fileName,mtime);
1092
- lastModifiedName = fileName;
1093
- lastModified = mtime;
1094
- lastModifiedTime = modifiedTime;
1095
- }
1096
- });
1097
- return { lastModified, lastModifiedName, lastModifiedTime };
1290
+ var files = glob.sync(filePath, config);
1291
+ // console.log(files.join(" - "));
1292
+ var lastModifiedName;
1293
+ var lastModified;
1294
+ var lastModifiedTime = 0;
1295
+ files.forEach((fileName) => {
1296
+ if (fs_extra_1.default.lstatSync(fileName).isDirectory()) {
1297
+ // console.log("skipping directory "+fileName);
1298
+ return;
1299
+ }
1300
+ let mtime = fs_extra_1.default.statSync(path_1.default.join(fileName)).mtime;
1301
+ let modifiedTime = mtime.getTime();
1302
+ if (modifiedTime > lastModifiedTime) {
1303
+ // console.log(fileName,mtime);
1304
+ lastModifiedName = fileName;
1305
+ lastModified = mtime;
1306
+ lastModifiedTime = modifiedTime;
1307
+ }
1308
+ });
1309
+ return {lastModified, lastModifiedName, lastModifiedTime};
1098
1310
  };
1099
1311
  var publishUpdated = function (test = false) {
1100
- let packages = getLocalLincdModules();
1101
- var p = Promise.resolve('');
1102
- let packagesLeft = packages.length;
1103
- let results = [];
1104
- log('Checking which packages need to be published by comparing last published date with last git commit');
1105
- // p = Promise.all(packages.map((pckg) => {
1106
- packages.forEach((pckg) => {
1107
- p = p
1108
- .then((previousResult) => {
1109
- // progressUpdate(packagesLeft-- + ' packages left. Now checking ' + pckg.packageName);
1110
- log('# Checking package ' + pckg.packageName);
1111
- // log('# Requesting ' + 'yarn info '+pkg.packageName+' --json');
1112
- // return execPromise('yarn info '+pkg.packageName+' --json').then((output:string) => {
1113
- // console.log("Will be requesting npm view from this current working directory:\n"+process.cwd());
1114
- // return execPromise('npm view '+pkg.packageName+' --json').then((output:string) => {
1115
- let shouldPublish;
1116
- var pack = (0, utils_1.getPackageJSON)(pckg.path);
1117
- let version = getNextVersion(pack.version);
1118
- if (pack.private) {
1119
- shouldPublish = false;
1120
- debugInfo(chalk_1.default.blue('--> is private, skipping'));
1121
- return chalk_1.default.gray(pckg.packageName + ' is private');
1122
- // return previousResult + ' ' + chalk.gray(pckg.packageName + ' is private\n');
1123
- }
1124
- console.log('testing npm');
1125
- return (0, utils_1.execPromise)('npm info ' + pckg.packageName + ' --json')
1126
- .then((output) => __awaiter(this, void 0, void 0, function* () {
1127
- console.log('testing npm done');
1128
- var info;
1129
- try {
1130
- if (output == '' || output.includes('E404')) {
1131
- debugInfo('Empty or 404 response from `npm info`. This package was probably not published before');
1132
- // throw new Error('Empty response from `yarn info`. This pkg was probably not published before');
1133
- // return;
1134
- shouldPublish = true;
1135
- //don't patch the version number (default, see above), use the current version
1136
- version = pack.version;
1137
- }
1138
- else {
1139
- info = JSON.parse(output);
1312
+ let packages = getLocalLincdModules();
1313
+ var p = Promise.resolve('');
1314
+ let packagesLeft = packages.length;
1315
+ let results = [];
1316
+ log('Checking which packages need to be published by comparing last published date with last git commit');
1317
+ // p = Promise.all(packages.map((pckg) => {
1318
+ packages.forEach((pckg) => {
1319
+ p = p
1320
+ .then((previousResult) => {
1321
+ // progressUpdate(packagesLeft-- + ' packages left. Now checking ' + pckg.packageName);
1322
+ log('# Checking package ' + pckg.packageName);
1323
+ // log('# Requesting ' + 'yarn info '+pkg.packageName+' --json');
1324
+ // return execPromise('yarn info '+pkg.packageName+' --json').then((output:string) => {
1325
+ // console.log("Will be requesting npm view from this current working directory:\n"+process.cwd());
1326
+ // return execPromise('npm view '+pkg.packageName+' --json').then((output:string) => {
1327
+ let shouldPublish;
1328
+ var pack = (0, utils_1.getPackageJSON)(pckg.path);
1329
+ let version = getNextVersion(pack.version);
1330
+ if (pack.private) {
1331
+ shouldPublish = false;
1332
+ debugInfo(chalk_1.default.blue('--> is private, skipping'));
1333
+ return chalk_1.default.gray(pckg.packageName + ' is private');
1334
+ // return previousResult + ' ' + chalk.gray(pckg.packageName + ' is private\n');
1335
+ }
1336
+ console.log('testing npm');
1337
+ return (0, utils_1.execPromise)('npm info ' + pckg.packageName + ' --json')
1338
+ .then((output) =>
1339
+ __awaiter(this, void 0, void 0, function* () {
1340
+ console.log('testing npm done');
1341
+ var info;
1342
+ try {
1343
+ if (output == '' || output.includes('E404')) {
1344
+ debugInfo('Empty or 404 response from `npm info`. This package was probably not published before');
1345
+ // throw new Error('Empty response from `yarn info`. This pkg was probably not published before');
1346
+ // return;
1347
+ shouldPublish = true;
1348
+ //don't patch the version number (default, see above), use the current version
1349
+ version = pack.version;
1350
+ } else {
1351
+ info = JSON.parse(output);
1352
+ }
1353
+ if (info) {
1354
+ let lastPublish;
1355
+ //yarn:
1356
+ // let lastPublish = info.data.time[info.data.version];
1357
+ lastPublish = info.time[info.version];
1358
+ // }
1359
+ // catch (e) {
1360
+ // console.log(info);
1361
+ // console.error(chalk.red("Could not parse response from npm info. Format may have changed?"));
1362
+ // process.exit();
1363
+ // }
1364
+ let lastPublishDate = new Date(lastPublish);
1365
+ // let {lastModifiedTime, lastModifiedName, lastModified} = getLastModifiedSourceTime(pkg.path);
1366
+ let lastCommitInfo = yield getLastCommitTime(pckg.path);
1367
+ if (!lastCommitInfo) {
1368
+ shouldPublish = false;
1369
+ debugInfo('Could not determine last git commit');
1370
+ // return previousResult + ' ' + chalk.red(pckg.packageName + ' - could not determine last commit\n');
1371
+ return chalk_1.default.red(pckg.packageName + ' - could not determine last commit');
1372
+ } else {
1373
+ //NOTE: removed lastModified, because switching branches will say that the file was modified and cause everything to publish
1374
+ //SO: now you NEED TO commit before it picks up that you should publish
1375
+ shouldPublish = lastPublishDate.getTime() < lastCommitInfo.date.getTime();
1376
+ //ignore changes to package.json if that's the only change, because when we publish the version number changes, which is then committed
1377
+ //(note there is always 2 lines for commit info + number of files changed)
1378
+ let changedFiles = lastCommitInfo.changes.split('\n').filter((line) => line.includes('|'));
1379
+ let numberOfFilesChanges = changedFiles.length;
1380
+ // console.log("CHECK "+lastCommitInfo.changes.includes("package.json")+" - "+numberOfFilesChanges)
1381
+ if (
1382
+ shouldPublish &&
1383
+ lastCommitInfo.changes.includes('package.json') &&
1384
+ numberOfFilesChanges === 1
1385
+ ) {
1386
+ shouldPublish = false;
1140
1387
  }
1141
- if (info) {
1142
- let lastPublish;
1143
- //yarn:
1144
- // let lastPublish = info.data.time[info.data.version];
1145
- lastPublish = info.time[info.version];
1146
- // }
1147
- // catch (e) {
1148
- // console.log(info);
1149
- // console.error(chalk.red("Could not parse response from npm info. Format may have changed?"));
1150
- // process.exit();
1151
- // }
1152
- let lastPublishDate = new Date(lastPublish);
1153
- // let {lastModifiedTime, lastModifiedName, lastModified} = getLastModifiedSourceTime(pkg.path);
1154
- let lastCommitInfo = yield getLastCommitTime(pckg.path);
1155
- if (!lastCommitInfo) {
1156
- shouldPublish = false;
1157
- debugInfo('Could not determine last git commit');
1158
- // return previousResult + ' ' + chalk.red(pckg.packageName + ' - could not determine last commit\n');
1159
- return chalk_1.default.red(pckg.packageName + ' - could not determine last commit');
1160
- }
1161
- else {
1162
- //NOTE: removed lastModified, because switching branches will say that the file was modified and cause everything to publish
1163
- //SO: now you NEED TO commit before it picks up that you should publish
1164
- shouldPublish = lastPublishDate.getTime() < lastCommitInfo.date.getTime();
1165
- //ignore changes to package.json if that's the only change, because when we publish the version number changes, which is then committed
1166
- //(note there is always 2 lines for commit info + number of files changed)
1167
- let changedFiles = lastCommitInfo.changes.split('\n').filter((line) => line.includes('|'));
1168
- let numberOfFilesChanges = changedFiles.length;
1169
- // console.log("CHECK "+lastCommitInfo.changes.includes("package.json")+" - "+numberOfFilesChanges)
1170
- if (shouldPublish && lastCommitInfo.changes.includes('package.json') && numberOfFilesChanges === 1) {
1171
- shouldPublish = false;
1172
- }
1173
- if (shouldPublish) {
1174
- log(chalk_1.default.magenta(pckg.packageName) + ' should be published because:');
1175
- log(lastPublishDate.toDateString() +
1176
- ' ' +
1177
- lastPublishDate.toTimeString() +
1178
- ' published ' +
1179
- info.version);
1180
- log(lastCommitInfo.date.toDateString() +
1181
- ' ' +
1182
- new Date(lastCommitInfo.date).toTimeString() +
1183
- ' source last committed:');
1184
- log(lastCommitInfo.changes);
1185
- }
1186
- }
1388
+ if (shouldPublish) {
1389
+ log(chalk_1.default.magenta(pckg.packageName) + ' should be published because:');
1390
+ log(
1391
+ lastPublishDate.toDateString() +
1392
+ ' ' +
1393
+ lastPublishDate.toTimeString() +
1394
+ ' published ' +
1395
+ info.version,
1396
+ );
1397
+ log(
1398
+ lastCommitInfo.date.toDateString() +
1399
+ ' ' +
1400
+ new Date(lastCommitInfo.date).toTimeString() +
1401
+ ' source last committed:',
1402
+ );
1403
+ log(lastCommitInfo.changes);
1187
1404
  }
1405
+ }
1188
1406
  }
1189
- catch (err) {
1190
- // var stats = fs.statSync(path.join(packageDirectory));
1191
- // var files = fs.readdirSync(path.join(packageDirectory,'src'));
1192
- console.log(chalk_1.default.red(pckg.packageName + ' failed: ' + err.message + '\n'));
1193
- console.warn('Returned JSON from npm: ' + output);
1194
- // return previousResult + ' ' + chalk.red(pckg.packageName + ' failed: ' + err.message + '\n');
1195
- return chalk_1.default.red(pckg.packageName + ' failed: ' + err.message);
1196
- }
1197
- if (shouldPublish) {
1198
- return (0, exports.publishPackage)(pckg, test, info, version);
1199
- }
1200
- return chalk_1.default.blue(pckg.packageName) + ' latest version is up to date';
1201
- }))
1202
- .catch(({ error, stdout, stderr }) => {
1203
- if (error) {
1204
- console.log(error.message);
1205
- }
1206
- if (stdout) {
1207
- console.log(stderr);
1208
- }
1209
- if (stderr) {
1210
- console.log(stderr);
1211
- }
1212
- // return previousResult + ' ' + chalk.red(pckg.packageName + ' failed\n');
1213
- console.warn(chalk_1.default.red(pckg.packageName + ' failed'));
1214
- return chalk_1.default.red(pckg.packageName + ' failed');
1215
- });
1216
- })
1217
- .then((res) => {
1218
- log(res);
1219
- results.push(res);
1220
- })
1221
- .catch((err) => {
1222
- console.warn(chalk_1.default.red(pckg.packageName + ' failed: ' + err.toString()));
1223
- results.push(chalk_1.default.red(pckg.packageName + ' failed: ' + err.toString()));
1224
- });
1225
- });
1226
- return p.then(() => {
1227
- // if (messages == '')
1228
- // {
1229
- // console.log('All published packages are already up-to-date.');
1230
- // }
1231
- // else
1232
- // {
1233
- console.log('Summary: \n' + results.join('\n'));
1234
- // }
1235
- });
1407
+ } catch (err) {
1408
+ // var stats = fs.statSync(path.join(packageDirectory));
1409
+ // var files = fs.readdirSync(path.join(packageDirectory,'src'));
1410
+ console.log(chalk_1.default.red(pckg.packageName + ' failed: ' + err.message + '\n'));
1411
+ console.warn('Returned JSON from npm: ' + output);
1412
+ // return previousResult + ' ' + chalk.red(pckg.packageName + ' failed: ' + err.message + '\n');
1413
+ return chalk_1.default.red(pckg.packageName + ' failed: ' + err.message);
1414
+ }
1415
+ if (shouldPublish) {
1416
+ return (0, exports.publishPackage)(pckg, test, info, version);
1417
+ }
1418
+ return chalk_1.default.blue(pckg.packageName) + ' latest version is up to date';
1419
+ }),
1420
+ )
1421
+ .catch(({error, stdout, stderr}) => {
1422
+ if (error) {
1423
+ console.log(error.message);
1424
+ }
1425
+ if (stdout) {
1426
+ console.log(stderr);
1427
+ }
1428
+ if (stderr) {
1429
+ console.log(stderr);
1430
+ }
1431
+ // return previousResult + ' ' + chalk.red(pckg.packageName + ' failed\n');
1432
+ console.warn(chalk_1.default.red(pckg.packageName + ' failed'));
1433
+ return chalk_1.default.red(pckg.packageName + ' failed');
1434
+ });
1435
+ })
1436
+ .then((res) => {
1437
+ log(res);
1438
+ results.push(res);
1439
+ })
1440
+ .catch((err) => {
1441
+ console.warn(chalk_1.default.red(pckg.packageName + ' failed: ' + err.toString()));
1442
+ results.push(chalk_1.default.red(pckg.packageName + ' failed: ' + err.toString()));
1443
+ });
1444
+ });
1445
+ return p.then(() => {
1446
+ // if (messages == '')
1447
+ // {
1448
+ // console.log('All published packages are already up-to-date.');
1449
+ // }
1450
+ // else
1451
+ // {
1452
+ console.log('Summary: \n' + results.join('\n'));
1453
+ // }
1454
+ });
1236
1455
  };
1237
1456
  exports.publishUpdated = publishUpdated;
1457
+
1238
1458
  function getEnvJsonPath(relativeToPath = process.cwd()) {
1239
- return __awaiter(this, void 0, void 0, function* () {
1240
- let path = '';
1241
- if (!relativeToPath.endsWith('/')) {
1242
- relativeToPath += '/';
1243
- }
1244
- // let path = './';
1245
- for (let i = 0; i <= 10; i++) {
1246
- let envFile = yield (0, get_env_vars_1.getEnvFile)({ filePath: relativeToPath + path + '.env.json' }).catch((err) => {
1247
- return null;
1248
- });
1249
- if (envFile) {
1250
- //note: we're getting the actual contents here, so we could also use that more directly?
1251
- return path + '.env.json';
1252
- }
1253
- path += '../';
1254
- }
1255
- });
1459
+ return __awaiter(this, void 0, void 0, function* () {
1460
+ let path = '';
1461
+ if (!relativeToPath.endsWith('/')) {
1462
+ relativeToPath += '/';
1463
+ }
1464
+ // let path = './';
1465
+ for (let i = 0; i <= 10; i++) {
1466
+ let envFile = yield (0, get_env_vars_1.getEnvFile)({filePath: relativeToPath + path + '.env.json'}).catch(
1467
+ (err) => {
1468
+ return null;
1469
+ },
1470
+ );
1471
+ if (envFile) {
1472
+ //note: we're getting the actual contents here, so we could also use that more directly?
1473
+ return path + '.env.json';
1474
+ }
1475
+ path += '../';
1476
+ }
1477
+ });
1256
1478
  }
1479
+
1257
1480
  var publishPackage = function (pkg, test, info, publishVersion) {
1258
- return __awaiter(this, void 0, void 0, function* () {
1259
- if (!pkg) {
1260
- let localPackageJson = (0, utils_1.getPackageJSON)();
1261
- pkg = {
1262
- path: process.cwd(),
1263
- packageName: localPackageJson.name,
1264
- };
1265
- }
1266
- if (!publishVersion) {
1267
- publishVersion = info ? getNextVersion(info.version) : 'patch';
1268
- }
1269
- if (test) {
1270
- debugInfo('should publish ' + pkg.packageName + ' ' + publishVersion);
1271
- //when testing what needs to be published
1272
- return chalk_1.default.blue(pkg.packageName + ' should publish');
1481
+ return __awaiter(this, void 0, void 0, function* () {
1482
+ if (!pkg) {
1483
+ let localPackageJson = (0, utils_1.getPackageJSON)();
1484
+ pkg = {
1485
+ path: process.cwd(),
1486
+ packageName: localPackageJson.name,
1487
+ };
1488
+ }
1489
+ if (!publishVersion) {
1490
+ publishVersion = info ? getNextVersion(info.version) : 'patch';
1491
+ }
1492
+ if (test) {
1493
+ debugInfo('should publish ' + pkg.packageName + ' ' + publishVersion);
1494
+ //when testing what needs to be published
1495
+ return chalk_1.default.blue(pkg.packageName + ' should publish');
1496
+ }
1497
+ console.log(chalk_1.default.blue('publishing ' + pkg.packageName + ' ' + publishVersion));
1498
+ //looking for an .env.json file in our workspace, which may store our NPM AUTH key
1499
+ let envJsonPath = yield getEnvJsonPath(pkg.path);
1500
+ return (0, utils_1.execPromise)(
1501
+ `cd ${pkg.path} && ${
1502
+ envJsonPath ? `env-cmd -f ${envJsonPath} --use-shell "` : ''
1503
+ }yarn version ${publishVersion} && yarn npm publish${envJsonPath ? `"` : ''}`,
1504
+ true,
1505
+ false,
1506
+ {},
1507
+ true,
1508
+ )
1509
+ .then((res) => {
1510
+ if (
1511
+ res.indexOf('Aborted due to warnings') !== -1 ||
1512
+ res.indexOf('Could not publish') !== -1 ||
1513
+ res.indexOf("Couldn't publish") !== -1
1514
+ ) {
1515
+ console.log(res);
1516
+ return chalk_1.default.red(pkg.packageName + ' failed\n');
1273
1517
  }
1274
- console.log(chalk_1.default.blue('publishing ' + pkg.packageName + ' ' + publishVersion));
1275
- //looking for an .env.json file in our workspace, which may store our NPM AUTH key
1276
- let envJsonPath = yield getEnvJsonPath(pkg.path);
1277
- return (0, utils_1.execPromise)(`cd ${pkg.path} && ${envJsonPath ? `env-cmd -f ${envJsonPath} --use-shell "` : ''}yarn version ${publishVersion} && yarn npm publish${envJsonPath ? `"` : ''}`, true, false, {}, true)
1278
- .then((res) => {
1279
- if (res.indexOf('Aborted due to warnings') !== -1 ||
1280
- res.indexOf('Could not publish') !== -1 ||
1281
- res.indexOf("Couldn't publish") !== -1) {
1282
- console.log(res);
1283
- return chalk_1.default.red(pkg.packageName + ' failed\n');
1284
- }
1285
- console.log('Successfully published ' + chalk_1.default.green(pkg.path) + ' ' + chalk_1.default.magenta(publishVersion));
1286
- return chalk_1.default.green(pkg.packageName) + ' published ' + chalk_1.default.magenta(publishVersion);
1287
- })
1288
- .catch(({ error, stdout, stderr }) => {
1289
- console.log(chalk_1.default.red('Failed to publish: ' + error.message));
1290
- return chalk_1.default.red(pkg.packageName + ' failed to publish');
1291
- });
1292
- });
1518
+ console.log(
1519
+ 'Successfully published ' + chalk_1.default.green(pkg.path) + ' ' + chalk_1.default.magenta(publishVersion),
1520
+ );
1521
+ return chalk_1.default.green(pkg.packageName) + ' published ' + chalk_1.default.magenta(publishVersion);
1522
+ })
1523
+ .catch(({error, stdout, stderr}) => {
1524
+ console.log(chalk_1.default.red('Failed to publish: ' + error.message));
1525
+ return chalk_1.default.red(pkg.packageName + ' failed to publish');
1526
+ });
1527
+ });
1293
1528
  };
1294
1529
  exports.publishPackage = publishPackage;
1295
1530
  var buildUpdated = function (back, target, target2, test = false) {
1296
- return __awaiter(this, void 0, void 0, function* () {
1297
- // back = back || 1;
1298
- // return execPromise(`git log -${back} --format=%ci`).then((result) => {
1299
- // let now = new Date();
1300
- let previousResult = '';
1301
- log(test ? 'Checking which packages need to be rebuild' : 'Building updated packages');
1302
- // let packages = getLocalLincdModules();
1303
- let packages = getLocalLincdPackageMap();
1304
- // console.log(packages);
1305
- let jsonldPkgUpdated = needsRebuilding(packages.get('lincd-jsonld'));
1306
- // let cliPkgUpdated = needsRebuilding(packages.get('lincd-cli'));
1307
- //if either cli or jsonldPkg needs to be rebuilt
1308
- // if (jsonldPkgUpdated || cliPkgUpdated) {
1309
- if (jsonldPkgUpdated) {
1310
- yield (0, utils_1.execPromise)('yarn build-core', false, false, {}, true);
1311
- }
1312
- let rebuildAllModules = false;
1313
- // if (cliPkgUpdated) {
1314
- // rebuildAllModules = true;
1315
- // log(chalk.magenta('Rebuilding all packages because the build tools (lincd-cli) got updated'));
1316
- // }
1317
- let packagesLeft = packages.size;
1318
- runOnPackagesGroupedByDependencies(packages, (packageGroup, dependencies) => {
1319
- debugInfo('Now checking: ' + chalk_1.default.blue(packageGroup.map((i) => i.packageName)));
1320
- debugInfo(packagesLeft + ' packages left.');
1321
- packagesLeft = packagesLeft - packageGroup.length;
1322
- return (pkg) => __awaiter(this, void 0, void 0, function* () {
1323
- // debugInfo('# Checking package ' + pkg.packageName);
1324
- let needRebuild = needsRebuilding(pkg, true);
1325
- if (pkg.packageName === 'lincd-jsonld' && jsonldPkgUpdated) {
1326
- needRebuild = true;
1327
- }
1328
- // console.log(pkg.path,lastModifiedSource.lastModifiedTime,lastModifiedBundle.lastModifiedTime);
1329
- // console.log(pkg.path,new Date(lastModifiedSource.lastModified).toString(),new Date(lastModifiedBundle.lastModified).toString());
1330
- if (needRebuild || rebuildAllModules) {
1331
- //TODO: when building a pkg, also rebuild all packages that depend on this package.. and iteratively build packages that depend on those packages..
1332
- // log(packageName+' modified since last commit on '+now.toString());
1333
- if (test) {
1334
- debugInfo('Need to build ' + pkg.packageName);
1335
- return chalk_1.default.blue(pkg.packageName + ' should be build');
1336
- }
1337
- log('Building ' + pkg.packageName);
1338
- return (0, utils_1.execPromise)('cd ' + pkg.path + ' && yarn build' + (target ? ' ' + target : '') + (target2 ? ' ' + target2 : ''))
1339
- .then((res) => {
1340
- debugInfo(chalk_1.default.green(pkg.packageName + ' successfully built'));
1341
- return chalk_1.default.green(pkg.packageName + ' built');
1342
- })
1343
- .catch(({ error, stdout, stderr }) => {
1344
- warn('Failed to build ' + pkg.packageName);
1345
- console.log(stdout);
1346
- let dependentModules = getDependentPackages(dependencies, pkg);
1347
- if (dependentModules.length > 0) {
1348
- // printBuildResults(failedModules, done);
1349
- warn(chalk_1.default.red(pkg.packageName + ' build failed'));
1350
- warn('Stopping build-updated process because ' +
1351
- dependentModules.length +
1352
- ' other packages depend on this package.\n'); //"+dependentModules.map(d => d.packageName).join(", ")));
1353
- process.exit(1);
1354
- }
1355
- });
1356
- }
1357
- });
1358
- }, (results) => {
1359
- if (results.length) {
1360
- log('Summary:');
1361
- log(results.join('\n'));
1531
+ return __awaiter(this, void 0, void 0, function* () {
1532
+ // back = back || 1;
1533
+ // return execPromise(`git log -${back} --format=%ci`).then((result) => {
1534
+ // let now = new Date();
1535
+ let previousResult = '';
1536
+ log(test ? 'Checking which packages need to be rebuild' : 'Building updated packages');
1537
+ // let packages = getLocalLincdModules();
1538
+ let packages = getLocalLincdPackageMap();
1539
+ // console.log(packages);
1540
+ let jsonldPkgUpdated = needsRebuilding(packages.get('lincd-jsonld'));
1541
+ // let cliPkgUpdated = needsRebuilding(packages.get('lincd-cli'));
1542
+ //if either cli or jsonldPkg needs to be rebuilt
1543
+ // if (jsonldPkgUpdated || cliPkgUpdated) {
1544
+ if (jsonldPkgUpdated) {
1545
+ yield (0, utils_1.execPromise)('yarn build-core', false, false, {}, true);
1546
+ }
1547
+ let rebuildAllModules = false;
1548
+ // if (cliPkgUpdated) {
1549
+ // rebuildAllModules = true;
1550
+ // log(chalk.magenta('Rebuilding all packages because the build tools (lincd-cli) got updated'));
1551
+ // }
1552
+ let packagesLeft = packages.size;
1553
+ runOnPackagesGroupedByDependencies(
1554
+ packages,
1555
+ (packageGroup, dependencies) => {
1556
+ debugInfo('Now checking: ' + chalk_1.default.blue(packageGroup.map((i) => i.packageName)));
1557
+ debugInfo(packagesLeft + ' packages left.');
1558
+ packagesLeft = packagesLeft - packageGroup.length;
1559
+ return (pkg) =>
1560
+ __awaiter(this, void 0, void 0, function* () {
1561
+ // debugInfo('# Checking package ' + pkg.packageName);
1562
+ let needRebuild = needsRebuilding(pkg, true);
1563
+ if (pkg.packageName === 'lincd-jsonld' && jsonldPkgUpdated) {
1564
+ needRebuild = true;
1362
1565
  }
1363
- else {
1364
- log(chalk_1.default.green('Nothing to rebuild'));
1566
+ // console.log(pkg.path,lastModifiedSource.lastModifiedTime,lastModifiedBundle.lastModifiedTime);
1567
+ // console.log(pkg.path,new Date(lastModifiedSource.lastModified).toString(),new Date(lastModifiedBundle.lastModified).toString());
1568
+ if (needRebuild || rebuildAllModules) {
1569
+ //TODO: when building a pkg, also rebuild all packages that depend on this package.. and iteratively build packages that depend on those packages..
1570
+ // log(packageName+' modified since last commit on '+now.toString());
1571
+ if (test) {
1572
+ debugInfo('Need to build ' + pkg.packageName);
1573
+ return chalk_1.default.blue(pkg.packageName + ' should be build');
1574
+ }
1575
+ log('Building ' + pkg.packageName);
1576
+ return (0, utils_1.execPromise)(
1577
+ 'cd ' + pkg.path + ' && yarn build' + (target ? ' ' + target : '') + (target2 ? ' ' + target2 : ''),
1578
+ )
1579
+ .then((res) => {
1580
+ debugInfo(chalk_1.default.green(pkg.packageName + ' successfully built'));
1581
+ return chalk_1.default.green(pkg.packageName + ' built');
1582
+ })
1583
+ .catch(({error, stdout, stderr}) => {
1584
+ warn('Failed to build ' + pkg.packageName);
1585
+ console.log(stdout);
1586
+ let dependentModules = getDependentPackages(dependencies, pkg);
1587
+ if (dependentModules.length > 0) {
1588
+ // printBuildResults(failedModules, done);
1589
+ warn(chalk_1.default.red(pkg.packageName + ' build failed'));
1590
+ warn(
1591
+ 'Stopping build-updated process because ' +
1592
+ dependentModules.length +
1593
+ ' other packages depend on this package.\n',
1594
+ ); //"+dependentModules.map(d => d.packageName).join(", ")));
1595
+ process.exit(1);
1596
+ }
1597
+ });
1365
1598
  }
1366
- });
1367
- return;
1368
- var p = Promise.resolve('');
1369
- packages.forEach((pkg) => {
1370
- let packageName = pkg.packageName;
1371
- p = p
1372
- .then((previousResult) => {
1373
- let lastModifiedSource = getLastModifiedSourceTime(pkg.path);
1374
- let lastModifiedBundle = getLastBuildTime(pkg.path);
1375
- // console.log(pkg.path,lastModifiedSource.lastModifiedTime,lastModifiedBundle.lastModifiedTime);
1376
- // console.log(pkg.path,new Date(lastModifiedSource.lastModified).toString(),new Date(lastModifiedBundle.lastModified).toString());
1377
- debugInfo('# Checking package ' + packageName);
1378
- if (lastModifiedSource.lastModifiedTime > lastModifiedBundle.lastModifiedTime) {
1379
- //TODO: when building a pkg, also rebuild all packages that depend on this package.. and iteratively build packages that depend on those packages..
1380
- // log(packageName+' modified since last commit on '+now.toString());
1381
- debugInfo(chalk_1.default.cyan('Last modified source: ' +
1382
- lastModifiedSource.lastModifiedName +
1383
- ' on ' +
1384
- lastModifiedSource.lastModified.toString()));
1385
- debugInfo(chalk_1.default.cyan('Last build: ' +
1386
- (lastModifiedBundle && typeof lastModifiedBundle.lastModified !== 'undefined'
1387
- ? lastModifiedBundle.lastModified.toString()
1388
- : 'never')));
1389
- if (test) {
1390
- debugInfo('need to build ' + packageName);
1391
- }
1392
- else {
1393
- log('building ' + packageName);
1394
- }
1395
- if (!test) {
1396
- return (0, utils_1.execPromise)('cd ' + pkg.path + ' && yarn build' + (target ? ' ' + target : '') + (target2 ? ' ' + target2 : '')).then((res) => {
1397
- if (res.indexOf('Aborted due to warnings') !== -1 || res.indexOf('Fatal error') !== -1) {
1398
- console.log(res);
1399
- return previousResult + ' ' + chalk_1.default.red(packageName + ' failed\n');
1400
- }
1401
- console.log(chalk_1.default.green(packageName + ' successfully built'));
1402
- return previousResult + ' ' + chalk_1.default.green(packageName + ' built\n');
1403
- });
1404
- }
1405
- return previousResult + ' ' + chalk_1.default.blue(packageName + ' should be build\n');
1406
- }
1407
- return previousResult;
1408
- })
1409
- .catch(({ error, stdout, stderr }) => {
1410
- console.log(stdout);
1411
- return previousResult + ' ' + chalk_1.default.red(packageName + ' failed\n');
1412
- });
1413
- });
1414
- return p.then((messages) => {
1415
- if (messages == '') {
1416
- console.log(chalk_1.default.green('Nothing to rebuild.'));
1599
+ });
1600
+ },
1601
+ (results) => {
1602
+ if (results.length) {
1603
+ log('Summary:');
1604
+ log(results.join('\n'));
1605
+ } else {
1606
+ log(chalk_1.default.green('Nothing to rebuild'));
1607
+ }
1608
+ },
1609
+ );
1610
+ return;
1611
+ var p = Promise.resolve('');
1612
+ packages.forEach((pkg) => {
1613
+ let packageName = pkg.packageName;
1614
+ p = p
1615
+ .then((previousResult) => {
1616
+ let lastModifiedSource = getLastModifiedSourceTime(pkg.path);
1617
+ let lastModifiedBundle = getLastBuildTime(pkg.path);
1618
+ // console.log(pkg.path,lastModifiedSource.lastModifiedTime,lastModifiedBundle.lastModifiedTime);
1619
+ // console.log(pkg.path,new Date(lastModifiedSource.lastModified).toString(),new Date(lastModifiedBundle.lastModified).toString());
1620
+ debugInfo('# Checking package ' + packageName);
1621
+ if (lastModifiedSource.lastModifiedTime > lastModifiedBundle.lastModifiedTime) {
1622
+ //TODO: when building a pkg, also rebuild all packages that depend on this package.. and iteratively build packages that depend on those packages..
1623
+ // log(packageName+' modified since last commit on '+now.toString());
1624
+ debugInfo(
1625
+ chalk_1.default.cyan(
1626
+ 'Last modified source: ' +
1627
+ lastModifiedSource.lastModifiedName +
1628
+ ' on ' +
1629
+ lastModifiedSource.lastModified.toString(),
1630
+ ),
1631
+ );
1632
+ debugInfo(
1633
+ chalk_1.default.cyan(
1634
+ 'Last build: ' +
1635
+ (lastModifiedBundle && typeof lastModifiedBundle.lastModified !== 'undefined'
1636
+ ? lastModifiedBundle.lastModified.toString()
1637
+ : 'never'),
1638
+ ),
1639
+ );
1640
+ if (test) {
1641
+ debugInfo('need to build ' + packageName);
1642
+ } else {
1643
+ log('building ' + packageName);
1417
1644
  }
1418
- else {
1419
- console.log('Summary: \n' + messages);
1645
+ if (!test) {
1646
+ return (0, utils_1.execPromise)(
1647
+ 'cd ' + pkg.path + ' && yarn build' + (target ? ' ' + target : '') + (target2 ? ' ' + target2 : ''),
1648
+ ).then((res) => {
1649
+ if (res.indexOf('Aborted due to warnings') !== -1 || res.indexOf('Fatal error') !== -1) {
1650
+ console.log(res);
1651
+ return previousResult + ' ' + chalk_1.default.red(packageName + ' failed\n');
1652
+ }
1653
+ console.log(chalk_1.default.green(packageName + ' successfully built'));
1654
+ return previousResult + ' ' + chalk_1.default.green(packageName + ' built\n');
1655
+ });
1420
1656
  }
1657
+ return previousResult + ' ' + chalk_1.default.blue(packageName + ' should be build\n');
1658
+ }
1659
+ return previousResult;
1660
+ })
1661
+ .catch(({error, stdout, stderr}) => {
1662
+ console.log(stdout);
1663
+ return previousResult + ' ' + chalk_1.default.red(packageName + ' failed\n');
1421
1664
  });
1422
- // });
1423
1665
  });
1666
+ return p.then((messages) => {
1667
+ if (messages == '') {
1668
+ console.log(chalk_1.default.green('Nothing to rebuild.'));
1669
+ } else {
1670
+ console.log('Summary: \n' + messages);
1671
+ }
1672
+ });
1673
+ // });
1674
+ });
1424
1675
  };
1425
1676
  exports.buildUpdated = buildUpdated;
1426
1677
  const needsRebuilding = function (pkg, log = false) {
1427
- let lastModifiedSource = getLastModifiedSourceTime(pkg.path);
1428
- let lastModifiedBundle = getLastBuildTime(pkg.path);
1429
- let result = lastModifiedSource.lastModifiedTime > lastModifiedBundle.lastModifiedTime;
1430
- if (log) {
1431
- debugInfo(chalk_1.default.cyan('Last modified source: ' +
1432
- lastModifiedSource.lastModifiedName +
1433
- ' on ' +
1434
- lastModifiedSource.lastModified.toString()));
1435
- debugInfo(chalk_1.default.cyan('Last build: ' +
1436
- (lastModifiedBundle && typeof lastModifiedBundle.lastModified !== 'undefined'
1437
- ? lastModifiedBundle.lastModified.toString()
1438
- : 'never')));
1439
- }
1440
- return result;
1678
+ let lastModifiedSource = getLastModifiedSourceTime(pkg.path);
1679
+ let lastModifiedBundle = getLastBuildTime(pkg.path);
1680
+ let result = lastModifiedSource.lastModifiedTime > lastModifiedBundle.lastModifiedTime;
1681
+ if (log) {
1682
+ debugInfo(
1683
+ chalk_1.default.cyan(
1684
+ 'Last modified source: ' +
1685
+ lastModifiedSource.lastModifiedName +
1686
+ ' on ' +
1687
+ lastModifiedSource.lastModified.toString(),
1688
+ ),
1689
+ );
1690
+ debugInfo(
1691
+ chalk_1.default.cyan(
1692
+ 'Last build: ' +
1693
+ (lastModifiedBundle && typeof lastModifiedBundle.lastModified !== 'undefined'
1694
+ ? lastModifiedBundle.lastModified.toString()
1695
+ : 'never'),
1696
+ ),
1697
+ );
1698
+ }
1699
+ return result;
1441
1700
  };
1442
1701
  const printBuildResults = function (failed, done) {
1443
- log('Successfully built: ' + chalk_1.default.green([...done].map((m) => m.packageName).join(', ')) + '\n');
1444
- if (failed.length > 0) {
1445
- warn('Failed to build: ' + chalk_1.default.red(failed.join(', ')) + '\n');
1446
- }
1702
+ log('Successfully built: ' + chalk_1.default.green([...done].map((m) => m.packageName).join(', ')) + '\n');
1703
+ if (failed.length > 0) {
1704
+ warn('Failed to build: ' + chalk_1.default.red(failed.join(', ')) + '\n');
1705
+ }
1447
1706
  };
1448
1707
  var executeCommandForEachPackage = function (packages, command, filterMethod, filterValue) {
1449
- //if a specific set of packages is given
1450
- if (filterMethod == 'exclude') {
1451
- //filter packages, so that we only execute on the packages as provided in the command
1452
- log('Excluding ' + filterValue);
1453
- filterValue = filterValue.split(',');
1454
- packages = packages.filter((pkg) => filterValue.indexOf(pkg.packageName) === -1);
1455
- }
1456
- let startFrom;
1457
- //by default start executing, unless 'from' is given
1458
- let executing = true;
1459
- //option to start from a specific pkg in the stack
1460
- if (filterMethod == 'from') {
1461
- startFrom = filterValue;
1462
- if (startFrom) {
1463
- console.log(chalk_1.default.blue('Will skip ahead to ' + startFrom));
1464
- }
1465
- let seen = false;
1466
- packages = packages.filter((pkg) => {
1467
- if (!seen && (pkg.packageName == startFrom || pkg.packageName == startFrom)) {
1468
- seen = true;
1469
- }
1470
- return seen;
1471
- });
1708
+ //if a specific set of packages is given
1709
+ if (filterMethod == 'exclude') {
1710
+ //filter packages, so that we only execute on the packages as provided in the command
1711
+ log('Excluding ' + filterValue);
1712
+ filterValue = filterValue.split(',');
1713
+ packages = packages.filter((pkg) => filterValue.indexOf(pkg.packageName) === -1);
1714
+ }
1715
+ let startFrom;
1716
+ //by default start executing, unless 'from' is given
1717
+ let executing = true;
1718
+ //option to start from a specific pkg in the stack
1719
+ if (filterMethod == 'from') {
1720
+ startFrom = filterValue;
1721
+ if (startFrom) {
1722
+ console.log(chalk_1.default.blue('Will skip ahead to ' + startFrom));
1472
1723
  }
1473
- log("Executing '" +
1474
- chalk_1.default.blueBright(command) +
1475
- "' on packages " +
1476
- chalk_1.default.magenta(packages.map((m) => m.packageName).join(', ')));
1477
- var p = Promise.resolve(true);
1478
- packages.forEach((pkg) => {
1479
- p = p.then(() => {
1480
- log('# Package ' + chalk_1.default.magenta(pkg.packageName));
1481
- return (0, utils_1.execp)('cd ' + pkg.path + ' && ' + command);
1482
- });
1724
+ let seen = false;
1725
+ packages = packages.filter((pkg) => {
1726
+ if (!seen && (pkg.packageName == startFrom || pkg.packageName == startFrom)) {
1727
+ seen = true;
1728
+ }
1729
+ return seen;
1483
1730
  });
1484
- return p;
1731
+ }
1732
+ log(
1733
+ "Executing '" +
1734
+ chalk_1.default.blueBright(command) +
1735
+ "' on packages " +
1736
+ chalk_1.default.magenta(packages.map((m) => m.packageName).join(', ')),
1737
+ );
1738
+ var p = Promise.resolve(true);
1739
+ packages.forEach((pkg) => {
1740
+ p = p.then(() => {
1741
+ log('# Package ' + chalk_1.default.magenta(pkg.packageName));
1742
+ return (0, utils_1.execp)('cd ' + pkg.path + ' && ' + command);
1743
+ });
1744
+ });
1745
+ return p;
1485
1746
  };
1486
1747
  exports.executeCommandForEachPackage = executeCommandForEachPackage;
1487
1748
  var gitIgnore = function (...entries) {
1488
- //add each entry to the .gitignore file
1489
- let gitIgnorePath = path_1.default.resolve(process.cwd(), '.gitignore');
1490
- (0, exports.addLinesToFile)(gitIgnorePath, entries);
1749
+ //add each entry to the .gitignore file
1750
+ let gitIgnorePath = path_1.default.resolve(process.cwd(), '.gitignore');
1751
+ (0, exports.addLinesToFile)(gitIgnorePath, entries);
1491
1752
  };
1492
1753
  var addLinesToFile = function (filePath, entries) {
1493
- let fileContents = fs_extra_1.default.readFileSync(filePath, { encoding: 'utf8' });
1494
- entries.forEach((entry) => {
1495
- fileContents += '\n' + entry;
1496
- });
1497
- fs_extra_1.default.writeFileSync(filePath, fileContents);
1754
+ let fileContents = fs_extra_1.default.readFileSync(filePath, {encoding: 'utf8'});
1755
+ entries.forEach((entry) => {
1756
+ fileContents += '\n' + entry;
1757
+ });
1758
+ fs_extra_1.default.writeFileSync(filePath, fileContents);
1498
1759
  };
1499
1760
  exports.addLinesToFile = addLinesToFile;
1500
1761
  var addCapacitor = function (basePath = process.cwd()) {
1501
- return __awaiter(this, void 0, void 0, function* () {
1502
- let targetFolder = ensureFolderExists(basePath);
1503
- log('Adding capacitor');
1504
- fs_extra_1.default.copySync(path_1.default.join(__dirname, '..', 'defaults', 'app-static'), targetFolder);
1505
- //update .env-cmdrc.json file
1506
- let envCmdPath = path_1.default.resolve(basePath, '.env-cmdrc.json');
1507
- let envCmd = JSON.parse(fs_extra_1.default.readFileSync(envCmdPath, { encoding: 'utf8' }));
1508
- envCmd['static-dev'] = {
1509
- NODE_ENV: 'production',
1510
- SITE_ROOT: 'http://localhost:4000',
1511
- DATA_ROOT: 'http://localhost:4000/data',
1512
- OUTPUT_PATH: './frontend/web/assets',
1513
- ASSET_PATH: './assets/',
1514
- ENTRY_PATH: './frontend/src/index-static.tsx',
1515
- };
1516
- fs_extra_1.default.writeFile(envCmdPath, JSON.stringify(envCmd, null, 2));
1517
- log('Edited .env-cmdrc.json');
1518
- gitIgnore('android/app/build', 'android/**/capacitor.build.gradle', 'ios/App/App/public', 'ios/App/Podfile');
1519
- //update package.json scripts
1520
- let pack = (0, utils_1.getPackageJSON)(basePath);
1521
- pack.scripts['build-static'] = 'env-cmd -e static-dev node frontend/scripts/build.js';
1522
- pack.scripts['cap:android'] = 'yarn cap open android';
1523
- pack.scripts['cap:sync'] = 'yarn cap sync';
1524
- fs_extra_1.default.writeFile(path_1.default.resolve(basePath, 'package.json'), JSON.stringify(pack, null, 2));
1525
- log('Added new run script to package.json');
1526
- yield (0, utils_1.execPromise)(`yarn add -D @capacitor/cli`, true, false, null, true);
1527
- yield (0, utils_1.execPromise)(`yarn add @capacitor/android @capacitor/core @capacitor/geolocation @capacitor/ios @capacitor/push-notifications`, false, false, null, true);
1528
- log(`Done! Run ${chalk_1.default.magenta('yarn build-static')} to generate static bundles. Then run ${chalk_1.default.magenta('yarn cap add android')} and/or ${chalk_1.default.magenta('yarn cap add ios')}')`);
1529
- log(`Also see the app icons in /frontend/web`);
1530
- });
1762
+ return __awaiter(this, void 0, void 0, function* () {
1763
+ let targetFolder = ensureFolderExists(basePath);
1764
+ log('Adding capacitor');
1765
+ fs_extra_1.default.copySync(path_1.default.join(__dirname, '..', 'defaults', 'app-static'), targetFolder);
1766
+ //update .env-cmdrc.json file
1767
+ let envCmdPath = path_1.default.resolve(basePath, '.env-cmdrc.json');
1768
+ let envCmd = JSON.parse(fs_extra_1.default.readFileSync(envCmdPath, {encoding: 'utf8'}));
1769
+ envCmd['static-dev'] = {
1770
+ NODE_ENV: 'production',
1771
+ SITE_ROOT: 'http://localhost:4000',
1772
+ DATA_ROOT: 'http://localhost:4000/data',
1773
+ OUTPUT_PATH: './frontend/web/assets',
1774
+ ASSET_PATH: './assets/',
1775
+ ENTRY_PATH: './frontend/src/index-static.tsx',
1776
+ };
1777
+ fs_extra_1.default.writeFile(envCmdPath, JSON.stringify(envCmd, null, 2));
1778
+ log('Edited .env-cmdrc.json');
1779
+ gitIgnore('android/app/build', 'android/**/capacitor.build.gradle', 'ios/App/App/public', 'ios/App/Podfile');
1780
+ //update package.json scripts
1781
+ let pack = (0, utils_1.getPackageJSON)(basePath);
1782
+ pack.scripts['build-static'] = 'env-cmd -e static-dev node frontend/scripts/build.js';
1783
+ pack.scripts['cap:android'] = 'yarn cap open android';
1784
+ pack.scripts['cap:sync'] = 'yarn cap sync';
1785
+ fs_extra_1.default.writeFile(path_1.default.resolve(basePath, 'package.json'), JSON.stringify(pack, null, 2));
1786
+ log('Added new run script to package.json');
1787
+ yield (0, utils_1.execPromise)(`yarn add -D @capacitor/cli`, true, false, null, true);
1788
+ yield (0,
1789
+ utils_1.execPromise)(`yarn add @capacitor/android @capacitor/core @capacitor/geolocation @capacitor/ios @capacitor/push-notifications`, false, false, null, true);
1790
+ log(
1791
+ `Done! Run ${chalk_1.default.magenta(
1792
+ 'yarn build-static',
1793
+ )} to generate static bundles. Then run ${chalk_1.default.magenta(
1794
+ 'yarn cap add android',
1795
+ )} and/or ${chalk_1.default.magenta('yarn cap add ios')}')`,
1796
+ );
1797
+ log(`Also see the app icons in /frontend/web`);
1798
+ });
1531
1799
  };
1532
1800
  exports.addCapacitor = addCapacitor;
1533
1801
  var executeCommandForPackage = function (packageName, command) {
1534
- let packageDetails = getLincdPackages().find((modDetails) => modDetails.packageName.indexOf(packageName) !== -1 || modDetails.packageName.indexOf(packageName) !== -1);
1535
- if (packageDetails) {
1536
- log("Executing 'cd " + packageDetails.path + ' && yarn exec lincd' + (command ? ' ' + command : '') + "'");
1537
- return (0, utils_1.execp)('cd ' + packageDetails.path + ' && yarn exec lincd' + (command ? ' ' + command : ''));
1538
- }
1539
- else {
1540
- warn("Could not find a pkg who's name (partially) matched " + chalk_1.default.cyan(packageName));
1541
- }
1802
+ let packageDetails = getLincdPackages().find(
1803
+ (modDetails) =>
1804
+ modDetails.packageName.indexOf(packageName) !== -1 || modDetails.packageName.indexOf(packageName) !== -1,
1805
+ );
1806
+ if (packageDetails) {
1807
+ log("Executing 'cd " + packageDetails.path + ' && yarn exec lincd' + (command ? ' ' + command : '') + "'");
1808
+ return (0, utils_1.execp)('cd ' + packageDetails.path + ' && yarn exec lincd' + (command ? ' ' + command : ''));
1809
+ } else {
1810
+ warn("Could not find a pkg who's name (partially) matched " + chalk_1.default.cyan(packageName));
1811
+ }
1542
1812
  };
1543
1813
  exports.executeCommandForPackage = executeCommandForPackage;