@_linked/cli 1.2.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (181) hide show
  1. package/.prettierignore +4 -0
  2. package/.prettierrc.json +24 -0
  3. package/CHANGELOG.md +34 -0
  4. package/LICENSE +373 -0
  5. package/README.md +24 -0
  6. package/babel.config.js +11 -0
  7. package/defaults/app-static/.env-cmdrc.json +17 -0
  8. package/defaults/app-static/capacitor.config.ts +40 -0
  9. package/defaults/app-static/package.json +8 -0
  10. package/defaults/app-static/web/apple-touch-icon-144x144.png +0 -0
  11. package/defaults/app-static/web/apple-touch-icon-57x57.png +0 -0
  12. package/defaults/app-static/web/apple-touch-icon-72x72.png +0 -0
  13. package/defaults/app-static/web/index.html +21 -0
  14. package/defaults/app-with-backend/.env-cmdrc.json +17 -0
  15. package/defaults/app-with-backend/.eslintignore +5 -0
  16. package/defaults/app-with-backend/.eslintrc.json +40 -0
  17. package/defaults/app-with-backend/.husky/post-merge +4 -0
  18. package/defaults/app-with-backend/.husky/pre-commit +4 -0
  19. package/defaults/app-with-backend/.prettierignore +4 -0
  20. package/defaults/app-with-backend/.prettierrc.json +27 -0
  21. package/defaults/app-with-backend/.vscode/launch.json +12 -0
  22. package/defaults/app-with-backend/.yarn/plugins/@yarnpkg/plugin-version.cjs +550 -0
  23. package/defaults/app-with-backend/.yarn/releases/yarn-3.6.1.cjs +874 -0
  24. package/defaults/app-with-backend/gitignore.template +24 -0
  25. package/defaults/app-with-backend/lincd.config.js +5 -0
  26. package/defaults/app-with-backend/mrgit-template.json +3 -0
  27. package/defaults/app-with-backend/package.json +86 -0
  28. package/defaults/app-with-backend/pm2-staging.config.js +12 -0
  29. package/defaults/app-with-backend/pm2.config.js +12 -0
  30. package/defaults/app-with-backend/public/favicon-144x144.png +0 -0
  31. package/defaults/app-with-backend/public/favicon-57x57.png +0 -0
  32. package/defaults/app-with-backend/public/favicon-72x72.png +0 -0
  33. package/defaults/app-with-backend/public/favicon.ico +0 -0
  34. package/defaults/app-with-backend/readme.md +19 -0
  35. package/defaults/app-with-backend/scripts/storage-config.js +12 -0
  36. package/defaults/app-with-backend/yarnrc.yml.template +8 -0
  37. package/defaults/component.scss +3 -0
  38. package/defaults/component.tsx +10 -0
  39. package/defaults/package/package.json +66 -0
  40. package/defaults/package/tsconfig-cjs.json +8 -0
  41. package/defaults/package/tsconfig-esm.json +9 -0
  42. package/defaults/set-component.tsx +13 -0
  43. package/defaults/shape.ts +8 -0
  44. package/lib/cjs/cli-deprecated.d.ts.map +1 -0
  45. package/lib/cjs/cli-deprecated.js +30 -0
  46. package/lib/cjs/cli-deprecated.js.map +1 -0
  47. package/lib/cjs/cli-methods.d.ts.map +1 -0
  48. package/lib/cjs/cli-methods.js +2555 -0
  49. package/lib/cjs/cli-methods.js.map +1 -0
  50. package/lib/cjs/cli.d.ts.map +1 -0
  51. package/lib/cjs/cli.js +289 -0
  52. package/lib/cjs/cli.js.map +1 -0
  53. package/lib/cjs/commands/build-package.d.ts.map +1 -0
  54. package/lib/cjs/commands/build-package.js +56 -0
  55. package/lib/cjs/commands/build-package.js.map +1 -0
  56. package/lib/cjs/commands/safe-yarn.d.ts.map +1 -0
  57. package/lib/cjs/commands/safe-yarn.js +67 -0
  58. package/lib/cjs/commands/safe-yarn.js.map +1 -0
  59. package/lib/cjs/config-webpack-app.d.ts.map +1 -0
  60. package/lib/cjs/config-webpack-app.js +397 -0
  61. package/lib/cjs/config-webpack-app.js.map +1 -0
  62. package/lib/cjs/config-webpack.d.ts.map +1 -0
  63. package/lib/cjs/config-webpack.js +408 -0
  64. package/lib/cjs/config-webpack.js.map +1 -0
  65. package/lib/cjs/defineConfig.d.ts.map +1 -0
  66. package/lib/cjs/defineConfig.js +13 -0
  67. package/lib/cjs/defineConfig.js.map +1 -0
  68. package/lib/cjs/index.d.ts.map +1 -0
  69. package/lib/cjs/index.js +39 -0
  70. package/lib/cjs/index.js.map +1 -0
  71. package/lib/cjs/interfaces.d.ts.map +1 -0
  72. package/lib/cjs/interfaces.js +3 -0
  73. package/lib/cjs/interfaces.js.map +1 -0
  74. package/lib/cjs/loaders/css-loader.d.mts +2 -0
  75. package/lib/cjs/loaders/css-loader.d.mts.map +1 -0
  76. package/lib/cjs/loaders/css-loader.mjs +93 -0
  77. package/lib/cjs/loaders/css-loader.mjs.map +1 -0
  78. package/lib/cjs/loaders/register-css-only.d.ts.map +1 -0
  79. package/lib/cjs/loaders/register-css-only.js +11 -0
  80. package/lib/cjs/loaders/register-css-only.js.map +1 -0
  81. package/lib/cjs/loaders/register.d.ts.map +1 -0
  82. package/lib/cjs/loaders/register.js +11 -0
  83. package/lib/cjs/loaders/register.js.map +1 -0
  84. package/lib/cjs/metadata.d.ts.map +1 -0
  85. package/lib/cjs/metadata.js +155 -0
  86. package/lib/cjs/metadata.js.map +1 -0
  87. package/lib/cjs/package.json +134 -0
  88. package/lib/cjs/plugins/check-imports.d.ts.map +1 -0
  89. package/lib/cjs/plugins/check-imports.js +68 -0
  90. package/lib/cjs/plugins/check-imports.js.map +1 -0
  91. package/lib/cjs/plugins/declaration-plugin.d.ts.map +1 -0
  92. package/lib/cjs/plugins/declaration-plugin.js +275 -0
  93. package/lib/cjs/plugins/declaration-plugin.js.map +1 -0
  94. package/lib/cjs/plugins/externalise-modules.d.ts.map +1 -0
  95. package/lib/cjs/plugins/externalise-modules.js +190 -0
  96. package/lib/cjs/plugins/externalise-modules.js.map +1 -0
  97. package/lib/cjs/plugins/lincd-tailwind-sources.d.ts.map +1 -0
  98. package/lib/cjs/plugins/lincd-tailwind-sources.js +32 -0
  99. package/lib/cjs/plugins/lincd-tailwind-sources.js.map +1 -0
  100. package/lib/cjs/plugins/watch-run.d.ts.map +1 -0
  101. package/lib/cjs/plugins/watch-run.js +45 -0
  102. package/lib/cjs/plugins/watch-run.js.map +1 -0
  103. package/lib/cjs/preflight.css +137 -0
  104. package/lib/cjs/tailwind.config.d.ts.map +1 -0
  105. package/lib/cjs/tailwind.config.js +17 -0
  106. package/lib/cjs/tailwind.config.js.map +1 -0
  107. package/lib/cjs/utils.d.ts.map +1 -0
  108. package/lib/cjs/utils.js +575 -0
  109. package/lib/cjs/utils.js.map +1 -0
  110. package/lib/esm/cli-deprecated.d.ts.map +1 -0
  111. package/lib/esm/cli-deprecated.js +7 -0
  112. package/lib/esm/cli-deprecated.js.map +1 -0
  113. package/lib/esm/cli-methods.d.ts.map +1 -0
  114. package/lib/esm/cli-methods.js +2511 -0
  115. package/lib/esm/cli-methods.js.map +1 -0
  116. package/lib/esm/cli.d.ts.map +1 -0
  117. package/lib/esm/cli.js +270 -0
  118. package/lib/esm/cli.js.map +1 -0
  119. package/lib/esm/commands/build-package.d.ts.map +1 -0
  120. package/lib/esm/commands/build-package.js +60 -0
  121. package/lib/esm/commands/build-package.js.map +1 -0
  122. package/lib/esm/commands/safe-yarn.d.ts.map +1 -0
  123. package/lib/esm/commands/safe-yarn.js +71 -0
  124. package/lib/esm/commands/safe-yarn.js.map +1 -0
  125. package/lib/esm/config-webpack-app.d.ts.map +1 -0
  126. package/lib/esm/config-webpack-app.js +372 -0
  127. package/lib/esm/config-webpack-app.js.map +1 -0
  128. package/lib/esm/config-webpack.d.ts.map +1 -0
  129. package/lib/esm/config-webpack.js +374 -0
  130. package/lib/esm/config-webpack.js.map +1 -0
  131. package/lib/esm/defineConfig.d.ts.map +1 -0
  132. package/lib/esm/defineConfig.js +9 -0
  133. package/lib/esm/defineConfig.js.map +1 -0
  134. package/lib/esm/index.d.ts.map +1 -0
  135. package/lib/esm/index.js +12 -0
  136. package/lib/esm/index.js.map +1 -0
  137. package/lib/esm/interfaces.d.ts.map +1 -0
  138. package/lib/esm/interfaces.js +2 -0
  139. package/lib/esm/interfaces.js.map +1 -0
  140. package/lib/esm/loaders/css-loader.d.mts +2 -0
  141. package/lib/esm/loaders/css-loader.d.mts.map +1 -0
  142. package/lib/esm/loaders/css-loader.mjs +86 -0
  143. package/lib/esm/loaders/css-loader.mjs.map +1 -0
  144. package/lib/esm/loaders/register-css-only.d.ts.map +1 -0
  145. package/lib/esm/loaders/register-css-only.js +9 -0
  146. package/lib/esm/loaders/register-css-only.js.map +1 -0
  147. package/lib/esm/loaders/register.d.ts.map +1 -0
  148. package/lib/esm/loaders/register.js +9 -0
  149. package/lib/esm/loaders/register.js.map +1 -0
  150. package/lib/esm/metadata.d.ts.map +1 -0
  151. package/lib/esm/metadata.js +155 -0
  152. package/lib/esm/metadata.js.map +1 -0
  153. package/lib/esm/package.json +134 -0
  154. package/lib/esm/plugins/check-imports.d.ts.map +1 -0
  155. package/lib/esm/plugins/check-imports.js +65 -0
  156. package/lib/esm/plugins/check-imports.js.map +1 -0
  157. package/lib/esm/plugins/declaration-plugin.d.ts.map +1 -0
  158. package/lib/esm/plugins/declaration-plugin.js +246 -0
  159. package/lib/esm/plugins/declaration-plugin.js.map +1 -0
  160. package/lib/esm/plugins/externalise-modules.d.ts.map +1 -0
  161. package/lib/esm/plugins/externalise-modules.js +185 -0
  162. package/lib/esm/plugins/externalise-modules.js.map +1 -0
  163. package/lib/esm/plugins/lincd-tailwind-sources.d.ts.map +1 -0
  164. package/lib/esm/plugins/lincd-tailwind-sources.js +27 -0
  165. package/lib/esm/plugins/lincd-tailwind-sources.js.map +1 -0
  166. package/lib/esm/plugins/watch-run.d.ts.map +1 -0
  167. package/lib/esm/plugins/watch-run.js +44 -0
  168. package/lib/esm/plugins/watch-run.js.map +1 -0
  169. package/lib/esm/preflight.css +137 -0
  170. package/lib/esm/tailwind.config.d.ts.map +1 -0
  171. package/lib/esm/tailwind.config.js +12 -0
  172. package/lib/esm/tailwind.config.js.map +1 -0
  173. package/lib/esm/utils.d.ts.map +1 -0
  174. package/lib/esm/utils.js +530 -0
  175. package/lib/esm/utils.js.map +1 -0
  176. package/lib-template/cjs/package.json +3 -0
  177. package/lib-template/esm/package.json +3 -0
  178. package/package.json +155 -0
  179. package/preflight.css +137 -0
  180. package/tsconfig-cjs.json +9 -0
  181. package/tsconfig-esm.json +10 -0
@@ -0,0 +1,2555 @@
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) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.removeOldFiles = exports.executeCommandForPackage = exports.addCapacitor = exports.addLinesToFile = exports.executeCommandForEachPackage = exports.buildUpdated = exports.publishPackage = exports.publishUpdated = exports.compilePackageCJS = exports.compilePackageESM = exports.compilePackage = exports.buildPackage = exports.register = exports.createPackage = exports.upgradePackages = exports.buildBackend = exports.buildFrontend = exports.buildApp = exports.startServer = exports.runMethod = exports.runScript = exports.ensureEnvironmentLoaded = exports.depCheck = exports.depCheckStaged = exports.checkImports = exports.createComponent = exports.createSetComponent = exports.createShape = exports.getScriptDir = exports.setNameVariables = exports.createOntology = exports.getLincdPackages = exports.buildAll = exports.runOnPackagesGroupedByDependencies = exports.developPackage = exports.logError = exports.warn = exports.createApp = void 0;
30
+ const chalk_1 = __importDefault(require("chalk"));
31
+ const child_process_1 = require("child_process");
32
+ const depcheck_1 = __importDefault(require("depcheck"));
33
+ const get_env_vars_js_1 = require("env-cmd/dist/get-env-vars.js");
34
+ const fs_extra_1 = __importDefault(require("fs-extra"));
35
+ const path_1 = __importStar(require("path"));
36
+ const readline_1 = require("readline");
37
+ const utils_js_1 = require("./utils.js");
38
+ const child_process_2 = require("child_process");
39
+ const find_nearest_package_json_1 = require("find-nearest-package-json");
40
+ const fs_1 = require("fs");
41
+ const LinkedFileStorage_1 = require("@_linked/core/utils/LinkedFileStorage");
42
+ // import pkg from 'lincd/utils/LinkedFileStorage';
43
+ // const { LinkedFileStorage } = pkg;
44
+ // const config = require('lincd-server/site.webpack.config');
45
+ const glob_1 = require("glob");
46
+ const webpack_1 = __importDefault(require("webpack"));
47
+ const ora_1 = __importDefault(require("ora"));
48
+ const staged_git_files_1 = __importDefault(require("staged-git-files"));
49
+ let dirname__ = typeof __dirname !== 'undefined'
50
+ ? __dirname
51
+ : //@ts-ignore
52
+ (0, path_1.dirname)(import.meta.url).replace('file:/', '');
53
+ var variables = {};
54
+ /**
55
+ * Prompt user for input
56
+ */
57
+ function promptUser(question) {
58
+ const rl = (0, readline_1.createInterface)({
59
+ input: process.stdin,
60
+ output: process.stdout,
61
+ });
62
+ return new Promise((resolve) => {
63
+ rl.question(chalk_1.default.cyan(question), (answer) => {
64
+ rl.close();
65
+ resolve(answer.trim());
66
+ });
67
+ });
68
+ }
69
+ const createApp = async (name, basePath = process.cwd(), options = {}) => {
70
+ // If no name provided, prompt for folder name first
71
+ if (!name) {
72
+ console.log(chalk_1.default.blue('\n📁 Folder name for your app:\n'));
73
+ const folderNameInput = await promptUser('Folder name (e.g., "my-app"): ');
74
+ if (!folderNameInput || !folderNameInput.trim()) {
75
+ console.warn(chalk_1.default.red('Folder name is required. Aborting.'));
76
+ return;
77
+ }
78
+ name = folderNameInput.trim();
79
+ }
80
+ let { hyphenName, camelCaseName, underscoreName } = (0, exports.setNameVariables)(name);
81
+ const defaultAppName = name
82
+ .split(/[-_\s]+/)
83
+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
84
+ .join(' ');
85
+ const defaultAppPrefix = underscoreName;
86
+ const defaultAppDomain = hyphenName + '.com';
87
+ let appName;
88
+ let appPrefix;
89
+ let appDomain;
90
+ // If any options provided, skip interactive prompts
91
+ if (options.appName || options.appPrefix || options.appDomain) {
92
+ appName = options.appName || defaultAppName;
93
+ appPrefix = options.appPrefix || defaultAppPrefix;
94
+ appDomain = options.appDomain || defaultAppDomain;
95
+ }
96
+ else {
97
+ // Prompt user for app configuration
98
+ console.log(chalk_1.default.blue('\n📝 Please provide the following information:\n'));
99
+ console.log(chalk_1.default.gray('(Press Enter to use defaults based on folder name)\n'));
100
+ const appNameInput = await promptUser(`App Name (display name) [${chalk_1.default.gray(defaultAppName)}]: `);
101
+ const appPrefixInput = await promptUser(`App Prefix (short code for data files, e.g., "myapp") [${chalk_1.default.gray(defaultAppPrefix)}]: `);
102
+ const appDomainInput = await promptUser(`App Domain [${chalk_1.default.gray(defaultAppDomain)}]: `);
103
+ appName = appNameInput || defaultAppName;
104
+ appPrefix = appPrefixInput || defaultAppPrefix;
105
+ appDomain = appDomainInput || defaultAppDomain;
106
+ }
107
+ // Set new variables for app configuration
108
+ setVariable('app_name', appName);
109
+ setVariable('app_prefix', appPrefix);
110
+ setVariable('app_domain', appDomain);
111
+ let targetFolder = path_1.default.join(basePath, hyphenName);
112
+ if (!fs_extra_1.default.existsSync(targetFolder)) {
113
+ fs_extra_1.default.mkdirSync(targetFolder);
114
+ }
115
+ fs_extra_1.default.copySync(path_1.default.join(dirname__, '..', '..', 'defaults', 'app-with-backend'), targetFolder);
116
+ //make sure the data folder exists (even though its empty).. copying empty folders does not work with fs.copySync
117
+ fs_extra_1.default.mkdirSync(path_1.default.join(targetFolder, 'data'), { recursive: true });
118
+ fs_extra_1.default.mkdirSync(path_1.default.join(targetFolder, 'data/uploads/resized'), {
119
+ recursive: true,
120
+ });
121
+ fs_extra_1.default.renameSync(path_1.default.join(targetFolder, 'gitignore.template'), path_1.default.join(targetFolder, '.gitignore'));
122
+ fs_extra_1.default.renameSync(path_1.default.join(targetFolder, 'yarnrc.yml.template'), path_1.default.join(targetFolder, '.yarnrc.yml'));
123
+ // fs.copySync(path.join(__dirname, '..', 'defaults', 'app'), targetFolder);
124
+ log("Creating new LINCD application '" + appName + "'");
125
+ //replace variables in some copied files
126
+ await replaceVariablesInFolder(targetFolder);
127
+ if (!options.skipInstall) {
128
+ let hasYarn = await hasYarnInstalled();
129
+ let installCommand = hasYarn
130
+ ? 'export NODE_OPTIONS="--no-network-family-autoselection" && yarn install'
131
+ : 'npm install';
132
+ await (0, utils_js_1.execp)(`cd ${hyphenName} && ${installCommand}`, true).catch((err) => {
133
+ console.warn('Could not install dependencies or start application');
134
+ });
135
+ }
136
+ 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('yarn start')}`);
137
+ };
138
+ exports.createApp = createApp;
139
+ function logHelp() {
140
+ (0, utils_js_1.execp)('yarn exec lincd help');
141
+ }
142
+ function log(...messages) {
143
+ messages.forEach((message) => {
144
+ console.log(chalk_1.default.cyan('Info: ') + message);
145
+ });
146
+ }
147
+ function progressUpdate(message) {
148
+ process.stdout.write(' \r');
149
+ process.stdout.write(message + '\r');
150
+ }
151
+ function warn(...messages) {
152
+ messages.forEach((message) => {
153
+ console.warn(chalk_1.default.redBright('Warning: ') + message);
154
+ // console.log(chalk.red(message));
155
+ });
156
+ }
157
+ exports.warn = warn;
158
+ function logError(...errors) {
159
+ errors.forEach((error) => {
160
+ console.error(chalk_1.default.redBright('Error: ') + error);
161
+ });
162
+ }
163
+ exports.logError = logError;
164
+ function developPackage(target, mode) {
165
+ if (!target)
166
+ target = 'es6';
167
+ if (mode !== 'production')
168
+ mode = '';
169
+ else if (target !== 'es6')
170
+ log('target must be es6 when developing for production');
171
+ if (target == 'es5' || target == 'es6') {
172
+ // log('> Starting continuous development build for '+target+' target')
173
+ log('starting continuous development build');
174
+ log('grunt dev' +
175
+ (target ? '-' + target : '') +
176
+ (mode ? '-' + mode : '') +
177
+ ' --color');
178
+ var command = (0, child_process_1.exec)('grunt dev' +
179
+ (target ? '-' + target : '') +
180
+ (mode ? '-' + mode : '') +
181
+ ' --color');
182
+ command.stdout.pipe(process.stdout);
183
+ command.stderr.pipe(process.stderr);
184
+ }
185
+ else {
186
+ console.warn('unknown build target. Use es5 or es6');
187
+ }
188
+ }
189
+ exports.developPackage = developPackage;
190
+ function checkWorkspaces(rootPath, workspaces, res) {
191
+ // console.log('checking workspaces at '+rootPath+": "+workspaces.toString());
192
+ if (workspaces.packages) {
193
+ workspaces = workspaces.packages;
194
+ }
195
+ workspaces.forEach((workspace) => {
196
+ let workspacePath = path_1.default.join(rootPath, workspace.replace('/*', ''));
197
+ if (workspace.indexOf('/*') !== -1) {
198
+ // console.log(workspacePath);
199
+ if (fs_extra_1.default.existsSync(workspacePath)) {
200
+ let folders = fs_extra_1.default.readdirSync(workspacePath);
201
+ folders.forEach((folder) => {
202
+ if (folder !== './' && folder !== '../') {
203
+ checkPackagePath(rootPath, path_1.default.join(workspacePath, folder), res);
204
+ }
205
+ });
206
+ }
207
+ }
208
+ else {
209
+ checkPackagePath(rootPath, workspacePath, res);
210
+ }
211
+ });
212
+ }
213
+ function checkPackagePath(rootPath, packagePath, res) {
214
+ let packageJsonPath = path_1.default.join(packagePath, 'package.json');
215
+ // console.log('checking '+packagePath);
216
+ if (fs_extra_1.default.existsSync(packageJsonPath)) {
217
+ var pack = JSON.parse(fs_extra_1.default.readFileSync(packageJsonPath, 'utf8'));
218
+ //some packages are not true lincd packages, but we still want them to be re-built automatically. This is what lincd_util is for
219
+ if (pack && pack.workspaces) {
220
+ checkWorkspaces(packagePath, pack.workspaces, res);
221
+ }
222
+ else if (pack && (pack.linkedPackage === true || pack.lincd === true)) {
223
+ res.push({
224
+ path: packagePath,
225
+ packageName: pack.name,
226
+ });
227
+ }
228
+ }
229
+ }
230
+ function runOnPackagesGroupedByDependencies(lincdPackages, onBuildStack, onStackEnd, sync = false) {
231
+ let dependencies = new Map();
232
+ let res, rej;
233
+ const deferredPromise = new Promise((resolve, reject) => {
234
+ res = resolve;
235
+ rej = reject;
236
+ });
237
+ //get dependencies of each package
238
+ let leastDependentPackage;
239
+ lincdPackages.forEach((pkg) => {
240
+ var pack = (0, utils_js_1.getPackageJSON)(pkg.path);
241
+ if (pack) {
242
+ //get lincd related dependencies and get the actual package details from the package map by removing '@dacore/' from the package name
243
+ let packageDependencies = Object.keys(pack.dependencies)
244
+ .filter((dependency) => lincdPackages.has(dependency))
245
+ .map((dependency) => {
246
+ return lincdPackages.has(dependency)
247
+ ? lincdPackages.get(dependency)
248
+ : dependency;
249
+ });
250
+ // console.log(package.packageName,packageDependencies.map())
251
+ dependencies.set(pkg, packageDependencies);
252
+ }
253
+ });
254
+ dependencies.forEach((PackageDependencies, pkg) => {
255
+ if (!PackageDependencies.some((dependency) => {
256
+ return (typeof dependency !== 'string' &&
257
+ lincdPackages.has(dependency.packageName));
258
+ })) {
259
+ leastDependentPackage = pkg;
260
+ }
261
+ });
262
+ let startStack = leastDependentPackage
263
+ ? [leastDependentPackage]
264
+ : [];
265
+ const runPackage = async (runFunction, pck) => {
266
+ try {
267
+ const result = await runFunction(pck);
268
+ done.add(pck);
269
+ return result;
270
+ }
271
+ catch (errorObj) {
272
+ if (errorObj.error) {
273
+ let { error, stdout, stderr } = errorObj;
274
+ warn('Uncaught exception whilst running parallel function on ' +
275
+ pck.packageName, (error === null || error === void 0 ? void 0 : error.message) ? error.message : error === null || error === void 0 ? void 0 : error.toString());
276
+ }
277
+ else {
278
+ warn('Uncaught exception whilst running parallel function on ' +
279
+ pck.packageName, errorObj === null || errorObj === void 0 ? void 0 : errorObj.toString());
280
+ process.exit();
281
+ }
282
+ // warn(chalk.red(pck.packageName+' failed:'));
283
+ // console.log(stdout);
284
+ done.add(pck);
285
+ return undefined;
286
+ }
287
+ };
288
+ let done = new Set();
289
+ let results = [];
290
+ let runStack = async (stack) => {
291
+ let runFunction = onBuildStack(stack, dependencies);
292
+ let stackPromise;
293
+ if (sync) {
294
+ //build the stack in parallel
295
+ stackPromise = Promise.resolve(true);
296
+ stack.forEach((pck) => {
297
+ stackPromise = stackPromise.then(() => {
298
+ return runPackage(runFunction, pck);
299
+ });
300
+ });
301
+ }
302
+ else {
303
+ //build the stack in parallel
304
+ stackPromise = Promise.all(stack.map((pck) => {
305
+ return runPackage(runFunction, pck);
306
+ }));
307
+ }
308
+ //wait till stack is completed
309
+ let stackResults = await stackPromise;
310
+ results = results.concat(stackResults);
311
+ //clear stack for next round
312
+ stack = [];
313
+ //find those packages who have all their dependencies already built and add them to the stack
314
+ lincdPackages.forEach((pkg) => {
315
+ let deps = dependencies.get(pkg);
316
+ //if the package is not done yet
317
+ //but every dependency is now done OR was not something we can build (some @dacore dependencies may not be local)
318
+ if (!done.has(pkg) &&
319
+ deps.every((dependency) => {
320
+ return (typeof dependency !== 'string' &&
321
+ (done.has(dependency) || !lincdPackages.has(dependency.packageName)));
322
+ })) {
323
+ stack.push(pkg);
324
+ }
325
+ });
326
+ if (stack.length <= 0 && done.size < lincdPackages.size) {
327
+ console.log(chalk_1.default.red('Only ' +
328
+ done.size +
329
+ ' out of ' +
330
+ lincdPackages.size +
331
+ ' packages have been built'));
332
+ console.log('ALL remaining packages have dependencies that have not been met. This may point to ' +
333
+ chalk_1.default.red('circular dependencies.'));
334
+ console.log('Already built: ' +
335
+ Array.from(done)
336
+ .map((p) => chalk_1.default.green(p.packageName))
337
+ .join(', '));
338
+ console.log(chalk_1.default.blue('\nTo solve this issue') +
339
+ ': find the circular dependencies below and fix the dependencies:\n\n');
340
+ //TODO: actually find and name the packages that have circular dependencies
341
+ // let circular = [];
342
+ // lincdPackages.forEach((pkg) => {
343
+ // if (!done.has(pkg))
344
+ // {
345
+ // let deps = dependencies.get(pkg);
346
+ // if (deps.some(dependency => {
347
+ // //return true if this dependency (indirectly) depends on the package whos' dependency it is
348
+ // return hasDependency(dependency,pkg,dependencies)
349
+ // }))
350
+ // {
351
+ // circular.push(pkg);
352
+ // }
353
+ // process.exit();
354
+ // }
355
+ // });
356
+ lincdPackages.forEach((pkg) => {
357
+ let deps = dependencies.get(pkg);
358
+ if (!done.has(pkg)) {
359
+ console.log(chalk_1.default.red(pkg.packageName) +
360
+ ' has not been built yet. Unbuilt dependencies:\n' +
361
+ deps
362
+ .filter((dependency) => {
363
+ return !Array.from(done).some((p) => {
364
+ // console.log(p.packageName,dependency.packageName,p===dependency)
365
+ return p === dependency;
366
+ });
367
+ })
368
+ .map((p) => chalk_1.default.red('\t- ' +
369
+ ((p === null || p === void 0 ? void 0 : p.packageName) ? p.packageName : p.toString()) +
370
+ '\n'))
371
+ .join(' '));
372
+ // console.log(chalk.red(pkg.packageName)+' has not been built yet. Built dependencies:\n' + deps.filter(dependency => {
373
+ // return Array.from(done).some(p => p.packageName === pkg.packageName)
374
+ // }).map(p => chalk.green('\t- '+p.packageName+'\n')).join(" "))
375
+ // 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(" "))
376
+ }
377
+ });
378
+ }
379
+ //if more to be built, iterate
380
+ if (stack.length > 0) {
381
+ return runStack(stack);
382
+ }
383
+ else {
384
+ onStackEnd(dependencies, results.filter(Boolean));
385
+ res();
386
+ }
387
+ };
388
+ //starts the process
389
+ if (startStack.length === 0) {
390
+ // No packages to build, resolve immediately
391
+ onStackEnd(dependencies, []);
392
+ res();
393
+ }
394
+ else {
395
+ runStack(startStack).catch((err) => {
396
+ rej(err);
397
+ });
398
+ }
399
+ return deferredPromise;
400
+ }
401
+ exports.runOnPackagesGroupedByDependencies = runOnPackagesGroupedByDependencies;
402
+ function hasDependency(pkg, childPkg, dependencies, depth = 1) {
403
+ console.log('Does ' + pkg.packageName + ' have dep ' + childPkg.packageName + ' ?');
404
+ let deps = dependencies.get(pkg);
405
+ if (deps.some((dependency) => {
406
+ console.log(dependency.packageName, childPkg.packageName, dependency === childPkg);
407
+ if (depth === 2)
408
+ return false;
409
+ // return dependency === childPkg;
410
+ return (dependency === childPkg ||
411
+ hasDependency(dependency, childPkg, dependencies, depth++));
412
+ })) {
413
+ console.log('##YES');
414
+ return true;
415
+ }
416
+ console.log('going up');
417
+ return false;
418
+ }
419
+ /**
420
+ * Finds the topmost package.json that could be an APP_ROOT
421
+ * Returns null if no app root is found (standalone repo case)
422
+ */
423
+ function findAppRoot(startPath = process.cwd()) {
424
+ let currentPath = startPath;
425
+ let candidateRoots = [];
426
+ // Walk up the directory tree
427
+ for (let i = 0; i < 10; i++) {
428
+ const packageJsonPath = path_1.default.join(currentPath, 'package.json');
429
+ if (fs_extra_1.default.existsSync(packageJsonPath)) {
430
+ const packageJson = JSON.parse(fs_extra_1.default.readFileSync(packageJsonPath, 'utf8'));
431
+ candidateRoots.push({
432
+ path: currentPath,
433
+ hasWorkspaces: !!packageJson.workspaces,
434
+ isLincd: packageJson.linkedPackage === true || packageJson.lincd === true,
435
+ });
436
+ }
437
+ const parentPath = path_1.default.join(currentPath, '..');
438
+ // If we've reached the root or haven't moved up
439
+ if (parentPath === currentPath) {
440
+ break;
441
+ }
442
+ currentPath = parentPath;
443
+ }
444
+ // Find the topmost package.json that has workspaces
445
+ // Prefer non-lincd packages (app roots) over lincd packages
446
+ let appRoot = null;
447
+ for (let i = candidateRoots.length - 1; i >= 0; i--) {
448
+ const candidate = candidateRoots[i];
449
+ if (candidate.hasWorkspaces && !candidate.isLincd) {
450
+ appRoot = candidate.path;
451
+ break;
452
+ }
453
+ }
454
+ // If no non-lincd workspace found, use the topmost workspace
455
+ if (!appRoot) {
456
+ for (let i = candidateRoots.length - 1; i >= 0; i--) {
457
+ if (candidateRoots[i].hasWorkspaces) {
458
+ appRoot = candidateRoots[i].path;
459
+ break;
460
+ }
461
+ }
462
+ }
463
+ return appRoot;
464
+ }
465
+ /**
466
+ * Filters packages to only include those in the dependency tree of the app root
467
+ */
468
+ function filterPackagesByDependencyTree(allPackages, appRootPath) {
469
+ const appPackageJson = (0, utils_js_1.getPackageJSON)(appRootPath);
470
+ if (!appPackageJson) {
471
+ return allPackages;
472
+ }
473
+ const relevantPackages = new Map();
474
+ const packagesToCheck = new Set();
475
+ // Start with direct dependencies from app root
476
+ if (appPackageJson.dependencies) {
477
+ Object.keys(appPackageJson.dependencies).forEach((dep) => {
478
+ if (allPackages.has(dep)) {
479
+ packagesToCheck.add(dep);
480
+ }
481
+ });
482
+ }
483
+ // Recursively add dependencies
484
+ const processedPackages = new Set();
485
+ while (packagesToCheck.size > 0) {
486
+ const packageName = Array.from(packagesToCheck)[0];
487
+ packagesToCheck.delete(packageName);
488
+ if (processedPackages.has(packageName)) {
489
+ continue;
490
+ }
491
+ processedPackages.add(packageName);
492
+ const packageDetails = allPackages.get(packageName);
493
+ if (packageDetails) {
494
+ relevantPackages.set(packageName, packageDetails);
495
+ // Get this package's dependencies
496
+ const packageJson = (0, utils_js_1.getPackageJSON)(packageDetails.path);
497
+ if (packageJson && packageJson.dependencies) {
498
+ Object.keys(packageJson.dependencies).forEach((dep) => {
499
+ if (allPackages.has(dep) && !processedPackages.has(dep)) {
500
+ packagesToCheck.add(dep);
501
+ }
502
+ });
503
+ }
504
+ }
505
+ }
506
+ return relevantPackages;
507
+ }
508
+ function buildAll(options) {
509
+ console.log('Building all LINCD packages of this repository in order of dependencies');
510
+ let lincdPackages = getLocalLincdPackageMap();
511
+ const originalPackageCount = lincdPackages.size;
512
+ // Check if we're in an app context and filter packages accordingly
513
+ const appRoot = findAppRoot();
514
+ if (appRoot) {
515
+ const appPackageJson = (0, utils_js_1.getPackageJSON)(appRoot);
516
+ // Check if this is an app (not a lincd package itself) with lincd dependencies
517
+ const isAppWithLincdDeps = appPackageJson &&
518
+ appPackageJson.lincd !== true &&
519
+ appPackageJson.dependencies &&
520
+ Object.keys(appPackageJson.dependencies).some((dep) => lincdPackages.has(dep));
521
+ if (isAppWithLincdDeps) {
522
+ (0, utils_js_1.debugInfo)(chalk_1.default.blue(`Found app root at: ${appRoot}`));
523
+ const filteredPackages = filterPackagesByDependencyTree(lincdPackages, appRoot);
524
+ console.log(chalk_1.default.magenta(`Found ${filteredPackages.size} total LINCD packages in use by this app`));
525
+ lincdPackages = filteredPackages;
526
+ }
527
+ else {
528
+ (0, utils_js_1.debugInfo)(chalk_1.default.blue(`Building all ${originalPackageCount} packages from workspace`));
529
+ }
530
+ }
531
+ else {
532
+ (0, utils_js_1.debugInfo)(chalk_1.default.blue(`No workspace root found, building all ${originalPackageCount} packages`));
533
+ }
534
+ let startFrom;
535
+ //by default start building
536
+ let building = true;
537
+ let from = options === null || options === void 0 ? void 0 : options.from;
538
+ let sync = (options === null || options === void 0 ? void 0 : options.sync) || false;
539
+ // console.log('from', from);
540
+ // console.log('sync', sync);
541
+ // process.exit();
542
+ //option to start from a specific package in the stack
543
+ if (from) {
544
+ startFrom = from;
545
+ //if we have a startFrom, then we havnt started the build process yet
546
+ building = startFrom ? false : true;
547
+ //clear targets
548
+ // target = '';
549
+ // target2 = '';
550
+ console.log(chalk_1.default.blue('Will skip builds until ' + startFrom));
551
+ // return async (pkg) => {};
552
+ }
553
+ // if (target2 == 'from') {
554
+ // startFrom = target3;
555
+ // //if we have a startFrom, then we havnt started the build process yet
556
+ // building = startFrom ? false : true;
557
+ //
558
+ // //clear targets
559
+ // target2 = '';
560
+ // target3 = '';
561
+ // console.log(chalk.blue('Will skip builds until ' + startFrom));
562
+ //
563
+ // // return async (pkg) => {};
564
+ // }
565
+ let done = new Set();
566
+ let failedModules = [];
567
+ progressUpdate(lincdPackages.size + ' packages left');
568
+ let packagesLeft = lincdPackages.size;
569
+ // let packagesLeft = lincdPackages.size - done.size;
570
+ runOnPackagesGroupedByDependencies(lincdPackages, (packageGroup, dependencies) => {
571
+ if (done.size > 0) {
572
+ (0, utils_js_1.debugInfo)(chalk_1.default.magenta('\n-------\nThese packages are next, since all their dependencies have now been build:'));
573
+ // log(stack);
574
+ }
575
+ (0, utils_js_1.debugInfo)('Now building: ' + chalk_1.default.blue(packageGroup.map((i) => i.packageName)));
576
+ return async (pkg) => {
577
+ let command;
578
+ let skipping = false;
579
+ //if we're skipping builds until a certain package
580
+ if (!building) {
581
+ //if the package name matches the package we're supposed to start from then start building packages
582
+ if (pkg.packageName == startFrom || pkg.packageName == startFrom) {
583
+ building = true;
584
+ }
585
+ //else still waiting for the package
586
+ else {
587
+ log(chalk_1.default.blue('skipping ' + pkg.packageName));
588
+ command = Promise.resolve(true);
589
+ skipping = true;
590
+ }
591
+ }
592
+ //unless told otherwise, build the package
593
+ if (!command) {
594
+ command = (0, exports.buildPackage)(null, null, path_1.default.join(process.cwd(), pkg.path), false);
595
+ // command = execPromise(
596
+ // 'cd ' + pkg.path + ' && yarn exec lincd build',
597
+ // // (target ? ' ' + target : '') +
598
+ // // (target2 ? ' ' + target2 : ''),
599
+ // false,
600
+ // false,
601
+ // {},
602
+ // false,
603
+ // );
604
+ log(chalk_1.default.cyan('Building ' + pkg.packageName));
605
+ process.stdout.write(packagesLeft + ' packages left\r');
606
+ }
607
+ return command
608
+ .then((res) => {
609
+ //empty string or true is success
610
+ //false is success with warnings
611
+ //any other string is the build error text
612
+ //undefined result means it failed
613
+ // if (res !== '' && res !== true && res !== false) {
614
+ if (typeof res === 'undefined') {
615
+ failedModules.push(pkg.packageName);
616
+ let dependentModules = getDependentPackages(dependencies, pkg);
617
+ if (dependentModules.length > 0) {
618
+ printBuildResults(failedModules, done);
619
+ console.log('Stopping build process because an error occurred whilst building ' +
620
+ pkg.packageName +
621
+ ', which ' +
622
+ dependentModules.length +
623
+ ' other packages depend on.'); //"+dependentModules.map(d => d.packageName).join(", ")));
624
+ log('Run ' +
625
+ chalk_1.default.greenBright(`lincd build-all --from=${pkg.packageName}`) +
626
+ ' to build only the remaining packages'); //"+dependentModules.map(d => d.packageName).join(", ")));
627
+ process.exit(1);
628
+ }
629
+ }
630
+ else {
631
+ if (!skipping) {
632
+ log(chalk_1.default.green('Built ' + pkg.packageName) +
633
+ (res === false ? chalk_1.default.redBright(' (with warnings)') : ''));
634
+ }
635
+ done.add(pkg);
636
+ packagesLeft--;
637
+ // log(chalk.magenta(packagesLeft + ' packages left'));
638
+ process.stdout.write(packagesLeft + ' packages left\r');
639
+ if (packagesLeft == 0) {
640
+ printBuildResults(failedModules, done);
641
+ if (failedModules.length > 0) {
642
+ process.exit(1);
643
+ }
644
+ }
645
+ return res;
646
+ }
647
+ })
648
+ .catch(({ error, stdout, stderr }) => {
649
+ logError(chalk_1.default.red('Failed to build ' + pkg.packageName));
650
+ console.log(stdout);
651
+ process.exit(1);
652
+ // let dependentModules = getDependentP
653
+ });
654
+ //undefined result means it failed
655
+ /*if (typeof res === 'undefined')
656
+ {
657
+ // .catch(({ error,stdout,stderr }) => {
658
+ //this prints out the webpack output, including the build errors
659
+ // warn('Failed to build ' + pkg.packageName);
660
+ // console.log(stdout);
661
+ failedModules.push(pkg.packageName);
662
+ let dependentModules = getDependentPackages(dependencies,pkg);
663
+ if (dependentModules.length > 0)
664
+ {
665
+ printBuildResults(failedModules,done);
666
+ console.log(
667
+ 'Stopping build process because an error occurred whilst building ' +
668
+ pkg.packageName +
669
+ ', which ' +
670
+ dependentModules.length +
671
+ ' other packages depend on.',
672
+ ); //"+dependentModules.map(d => d.packageName).join(", ")));
673
+ log(
674
+ 'Run ' +
675
+ chalk.greenBright(`lincd build-all --from=${pkg.packageName}`) +
676
+ ' to build only the remaining packages',
677
+ ); //"+dependentModules.map(d => d.packageName).join(", ")));
678
+ process.exit(1);
679
+ }
680
+ }
681
+ else //true is successful build, false is successful but with warnings
682
+ {
683
+ //successful build
684
+ // })
685
+ // .then((res) => {
686
+ if (!skipping)
687
+ {
688
+ log(chalk.green('Built ' + pkg.packageName)+(res === false ? chalk.redBright(' (with warnings)') : ''));
689
+ }
690
+ done.add(pkg);
691
+
692
+ packagesLeft--;
693
+ // log(chalk.magenta(packagesLeft + ' packages left'));
694
+ process.stdout.write(packagesLeft + ' packages left\r');
695
+ if (packagesLeft == 0)
696
+ {
697
+ printBuildResults(failedModules,done);
698
+ if (failedModules.length > 0)
699
+ {
700
+ process.exit(1);
701
+ }
702
+ }
703
+
704
+ return res;
705
+ }*/
706
+ // }).catch(err => {
707
+ // console.log(err);
708
+ // })
709
+ };
710
+ }, (dependencies) => {
711
+ //if no more packages to build but we never started building...
712
+ if (!building) {
713
+ 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'));
714
+ }
715
+ else {
716
+ //Detecting cyclical dependencies that caused some packages not to be build
717
+ let first = true;
718
+ lincdPackages.forEach((pkg) => {
719
+ if (!done.has(pkg)) {
720
+ let deps = dependencies.get(pkg);
721
+ if (first) {
722
+ console.log(chalk_1.default.red('CYCLICAL DEPENDENCIES? - could not build some packages because they depend on each other.'));
723
+ first = false;
724
+ }
725
+ //print the cyclical dependencies
726
+ console.log(chalk_1.default.red(pkg.packageName) +
727
+ ' depends on ' +
728
+ deps
729
+ .filter((dependency) => {
730
+ return typeof dependency !== 'string';
731
+ })
732
+ .map((d) => {
733
+ return done.has(d)
734
+ ? d.packageName
735
+ : chalk_1.default.red(d.packageName);
736
+ })
737
+ .join(', '));
738
+ //also print some information why these packages have not been moved into the stack
739
+ let stringDependencies = deps.filter((d) => typeof d === 'string');
740
+ if (stringDependencies.length > 0) {
741
+ console.log(chalk_1.default.red('And it depends on these package(s) - which seem not to be proper packages :' +
742
+ stringDependencies.join(', ')));
743
+ console.log(chalk_1.default.red('Could you remove this from dependencies? Should it be a devDependency?'));
744
+ }
745
+ }
746
+ });
747
+ }
748
+ }, sync);
749
+ }
750
+ exports.buildAll = buildAll;
751
+ function getDependentPackages(dependencies, pkg) {
752
+ let dependentModules = [];
753
+ dependencies.forEach((dModuleDependencies, dModule) => {
754
+ if (dModuleDependencies.indexOf(pkg) !== -1) {
755
+ dependentModules.push(dModule);
756
+ }
757
+ });
758
+ return dependentModules;
759
+ }
760
+ /**
761
+ * Returns a map of the packages that this repository manages (so no packages found through the workspaces who's path contains ../ )
762
+ * @param rootPath
763
+ */
764
+ function getLocalLincdPackageMap(rootPath = './') {
765
+ let map = new Map();
766
+ getLincdPackages(rootPath).forEach((pkg) => {
767
+ if (pkg.path.indexOf('../') === -1 && pkg.path.indexOf('..\\') === -1) {
768
+ // console.log(package.path);
769
+ map.set(pkg.packageName, pkg);
770
+ }
771
+ });
772
+ return map;
773
+ }
774
+ function getLocalLincdModules(rootPath = './') {
775
+ return getLincdPackages(rootPath).filter((pkg) => {
776
+ return pkg.path.indexOf('..\\') === -1;
777
+ });
778
+ }
779
+ function getLincdPackages(rootPath = process.cwd()) {
780
+ let pack = (0, utils_js_1.getPackageJSON)(rootPath);
781
+ if (!pack || !pack.workspaces) {
782
+ const originalRoot = rootPath;
783
+ for (let i = 0; i <= 3; i++) {
784
+ rootPath = path_1.default.join(originalRoot, ...Array(i).fill('..'));
785
+ pack = (0, utils_js_1.getPackageJSON)(rootPath);
786
+ if (pack && pack.workspaces) {
787
+ // log('Found workspace at '+packagePath);
788
+ break;
789
+ }
790
+ }
791
+ }
792
+ if (!pack || !pack.workspaces) {
793
+ warn(chalk_1.default.red('Could not find package workspaces. Make sure you run this command from a yarn workspace.'));
794
+ logHelp();
795
+ process.exit();
796
+ }
797
+ // console.log(pack.workspaces);
798
+ let res = [];
799
+ checkWorkspaces(rootPath, pack.workspaces, res);
800
+ return res;
801
+ }
802
+ exports.getLincdPackages = getLincdPackages;
803
+ function setVariable(name, replacement) {
804
+ //prepare name for regexp
805
+ name = name.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
806
+ variables[name] = replacement;
807
+ }
808
+ var replaceVariablesInFile = async (filePath) => {
809
+ var fileContent = await fs_extra_1.default.readFile(filePath, 'utf8').catch((err) => {
810
+ console.warn(chalk_1.default.red('Could not read file ' + filePath));
811
+ });
812
+ if (fileContent) {
813
+ var newContent = replaceCurlyVariables(fileContent);
814
+ return fs_extra_1.default.writeFile(filePath, newContent);
815
+ }
816
+ else {
817
+ return Promise.resolve();
818
+ }
819
+ };
820
+ var replaceCurlyVariables = function (string) {
821
+ // var reg = new RegExp('\\$\\{'+key+'\\}','g');
822
+ for (var key in variables) {
823
+ string = string.replace(new RegExp('\\$\\{' + key + '\\}', 'g'), variables[key]);
824
+ }
825
+ return string;
826
+ };
827
+ const capitalize = (str) => str.charAt(0).toUpperCase() + str.toLowerCase().slice(1);
828
+ const camelCase = (str) => {
829
+ let string = str.replace(/[^A-Za-z0-9]/g, ' ').split(' ');
830
+ if (string.length > 1) {
831
+ return string.reduce((result, word) => result + capitalize(word));
832
+ }
833
+ return str;
834
+ };
835
+ const createOntology = async (prefix, uriBase, basePath = process.cwd()) => {
836
+ if (!prefix) {
837
+ console.warn('Please provide a suggested prefix as the first argument');
838
+ return;
839
+ }
840
+ let sourceFolder = getSourceFolder(basePath);
841
+ let targetFolder = ensureFolderExists(sourceFolder, 'ontologies');
842
+ if (!uriBase) {
843
+ uriBase = 'http://lincd.org/ont/' + prefix + '/';
844
+ }
845
+ setVariable('uri_base', uriBase);
846
+ let { hyphenName, camelCaseName, underscoreName } = (0, exports.setNameVariables)(prefix);
847
+ //copy ontology accessor file
848
+ log("Creating files for ontology '" + prefix + "'");
849
+ let targetFile = path_1.default.join(targetFolder, hyphenName + '.ts');
850
+ fs_extra_1.default.copySync(path_1.default.join(dirname__, '..', '..', 'defaults', 'package', 'src', 'ontologies', 'example-ontology.ts'), targetFile);
851
+ //copy data files
852
+ let targetDataFile = path_1.default.join(targetFolder, '..', 'data', hyphenName + '.json');
853
+ let targetDataFile2 = path_1.default.join(targetFolder, '..', 'data', hyphenName + '.json.d.ts');
854
+ fs_extra_1.default.copySync(path_1.default.join(dirname__, '..', '..', 'defaults', 'package', 'src', 'data', 'example-ontology.json'), targetDataFile);
855
+ fs_extra_1.default.copySync(path_1.default.join(dirname__, '..', '..', 'defaults', 'package', 'src', 'data', 'example-ontology.json.d.ts'), targetDataFile2);
856
+ await replaceVariablesInFiles(targetFile, targetDataFile, targetDataFile2);
857
+ 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, ''))}`);
858
+ //if this is not a lincd app (but a lincd package instead)
859
+ if (!sourceFolder.includes('frontend')) {
860
+ //then also add an import to index
861
+ let indexPath = addLineToIndex(`import './ontologies/${hyphenName}.js';`, 'ontologies');
862
+ log(`Added an import of this file from ${chalk_1.default.magenta(indexPath)}`);
863
+ }
864
+ };
865
+ exports.createOntology = createOntology;
866
+ const addLineToIndex = function (line, insertMatchString, root = process.cwd(), insertAtStart = false) {
867
+ //import ontology in index
868
+ let indexPath = ['index.ts', 'index.tsx']
869
+ .map((f) => path_1.default.join(root, 'src', f))
870
+ .find((indexFileName) => {
871
+ return fs_extra_1.default.existsSync(indexFileName);
872
+ });
873
+ if (indexPath) {
874
+ let indexContents = fs_extra_1.default.readFileSync(indexPath, 'utf-8');
875
+ let lines = indexContents.split(/\n/g);
876
+ let newContents;
877
+ for (var key in lines) {
878
+ //if the match string is found
879
+ if (lines[key].indexOf(insertMatchString) !== -1) {
880
+ //add the new line after this line
881
+ lines[key] += `\n${line}`;
882
+ newContents = lines.join('\n');
883
+ // log("Found at "+key,lines,newContents);
884
+ break;
885
+ }
886
+ }
887
+ if (!newContents) {
888
+ if (insertAtStart) {
889
+ newContents = `${line}\n${indexContents}`;
890
+ }
891
+ else {
892
+ newContents = `${indexContents}\n${line}`;
893
+ }
894
+ // log("Added at end",newContents);
895
+ }
896
+ fs_extra_1.default.writeFileSync(indexPath, newContents);
897
+ }
898
+ return indexPath;
899
+ };
900
+ const replaceVariablesInFiles = function (...files) {
901
+ return Promise.all(files.map((file) => {
902
+ return replaceVariablesInFile(file);
903
+ }));
904
+ };
905
+ const replaceVariablesInFolder = async function (folder) {
906
+ //get all files in folder, including files that start with a dot
907
+ try {
908
+ const files = await (0, glob_1.glob)(folder + '/**/*', { dot: true, nodir: true });
909
+ console.log('Replacing variables in files', files.join(', '));
910
+ await Promise.all(files.map((file) => {
911
+ return replaceVariablesInFile(file);
912
+ }));
913
+ }
914
+ catch (err) {
915
+ console.log('Error', err);
916
+ throw err;
917
+ }
918
+ };
919
+ const replaceVariablesInFilesWithRoot = function (root, ...files) {
920
+ return replaceVariablesInFiles(...files.map((f) => path_1.default.join(root, f)));
921
+ };
922
+ const hasYarnInstalled = async function () {
923
+ let version = (await (0, utils_js_1.execPromise)('yarn --version').catch((err) => {
924
+ console.log('yarn probably not working');
925
+ return '';
926
+ }));
927
+ return version.toString().match(/[0-9]+/);
928
+ };
929
+ const ensureFolderExists = function (...folders) {
930
+ let target;
931
+ folders.forEach((folder) => {
932
+ target = target ? path_1.default.join(target, folder) : path_1.default.join(folder);
933
+ if (!fs_extra_1.default.existsSync(target)) {
934
+ fs_extra_1.default.mkdirSync(target);
935
+ }
936
+ });
937
+ return target;
938
+ /*let targetFolder = path.join(...folders);
939
+ let parentDirectory = folders.slice(0, folders.length - 1);
940
+ if (!fs.existsSync(targetFolder)) {
941
+ if (fs.existsSync(path.join(...parentDirectory))) {
942
+ fs.mkdirSync(targetFolder);
943
+ } else {
944
+ warn(
945
+ `Please run this command from the root of your package. This command expects ${parentDirectory.toString()} to exists from that folder`,
946
+ );
947
+ }
948
+ }
949
+ return targetFolder;*/
950
+ };
951
+ const setNameVariables = function (name) {
952
+ let hyphenName = name.toLowerCase().replace(/[-_\s]+/g, '-');
953
+ let camelCaseName = camelCase(name); //some-package --> someModule
954
+ let underscoreName = name.replace(/[-\s]+/g, '_');
955
+ let plainName = name.replace(/[-\s]+/g, '');
956
+ //longer similar variables names should come before the shorter ones
957
+ setVariable('underscore_name', underscoreName);
958
+ setVariable('hyphen_name', hyphenName);
959
+ setVariable('camel_name', camelCaseName);
960
+ setVariable('name', name);
961
+ setVariable('plain_name', plainName);
962
+ return { hyphenName, camelCaseName, underscoreName, plainName };
963
+ };
964
+ exports.setNameVariables = setNameVariables;
965
+ function getSourceFolder(basePath = process.cwd()) {
966
+ //LINCD App
967
+ if (fs_extra_1.default.existsSync(path_1.default.join(basePath, 'frontend', 'src'))) {
968
+ return path_1.default.join(basePath, 'frontend', 'src');
969
+ }
970
+ //LINCD package
971
+ if (fs_extra_1.default.existsSync(path_1.default.join(basePath, 'src'))) {
972
+ return path_1.default.join(basePath, 'src');
973
+ }
974
+ else {
975
+ console.warn('Cannot find source folder');
976
+ return path_1.default.join(basePath, 'src');
977
+ }
978
+ }
979
+ /**
980
+ * get __dirname for either ESM/CJS
981
+ */
982
+ const getScriptDir = () => {
983
+ return dirname__;
984
+ // // @ts-ignore
985
+ // if (typeof __dirname !== 'undefined')
986
+ // {
987
+ // // @ts-ignore
988
+ // return __dirname;
989
+ // }
990
+ // else
991
+ // {
992
+ // // @ts-ignore
993
+ // return dirname(import.meta.url).replace('file:/','');
994
+ // }
995
+ };
996
+ exports.getScriptDir = getScriptDir;
997
+ const createShape = async (name, basePath = process.cwd()) => {
998
+ let sourceFolder = getSourceFolder(basePath);
999
+ let targetFolder = ensureFolderExists(sourceFolder, 'shapes');
1000
+ let { hyphenName, camelCaseName, underscoreName } = (0, exports.setNameVariables)(name);
1001
+ //copy default shape file
1002
+ // log("Creating files for shape '" + name + "'");
1003
+ let targetFile = path_1.default.join(targetFolder, hyphenName + '.ts');
1004
+ fs_extra_1.default.copySync(path_1.default.join((0, exports.getScriptDir)(), '..', '..', 'defaults', 'shape.ts'), targetFile);
1005
+ //replace variables in some of the copied files
1006
+ await replaceVariablesInFiles(targetFile);
1007
+ log(`Created a new shape class template in ${chalk_1.default.magenta(targetFile.replace(basePath, ''))}`);
1008
+ //if this is NOT a lincd app (but a lincd package)
1009
+ let indexPath;
1010
+ if (!sourceFolder.includes('frontend')) {
1011
+ indexPath = addLineToIndex(`import './shapes/${hyphenName}.js';`, 'shapes');
1012
+ log(`Added an import of this file from ${chalk_1.default.magenta(indexPath)}`);
1013
+ }
1014
+ };
1015
+ exports.createShape = createShape;
1016
+ const createSetComponent = async (name, basePath = process.cwd()) => {
1017
+ let targetFolder = ensureFolderExists(basePath, 'src', 'components');
1018
+ let { hyphenName, camelCaseName, underscoreName } = (0, exports.setNameVariables)(name);
1019
+ //copy default shape file
1020
+ log("Creating files for set component '" + name + "'");
1021
+ let targetFile = path_1.default.join(targetFolder, hyphenName + '.tsx');
1022
+ fs_extra_1.default.copySync(path_1.default.join((0, exports.getScriptDir)(), '..', '..', 'defaults', 'set-component.tsx'), targetFile);
1023
+ let targetFile2 = path_1.default.join(targetFolder, hyphenName + '.scss');
1024
+ fs_extra_1.default.copySync(path_1.default.join((0, exports.getScriptDir)(), '..', '..', 'defaults', 'component.scss'), targetFile2);
1025
+ //replace variables in some of the copied files
1026
+ await replaceVariablesInFiles(targetFile, targetFile2);
1027
+ let indexPath = addLineToIndex(`import './components/${hyphenName}.js';`, 'components');
1028
+ 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)}`);
1029
+ };
1030
+ exports.createSetComponent = createSetComponent;
1031
+ const createComponent = async (name, basePath = process.cwd()) => {
1032
+ let sourceFolder = getSourceFolder(basePath);
1033
+ let targetFolder = ensureFolderExists(sourceFolder, 'components');
1034
+ let { hyphenName, camelCaseName, underscoreName } = (0, exports.setNameVariables)(name);
1035
+ //copy default shape file
1036
+ log("Creating files for component '" + name + "'");
1037
+ let targetFile = path_1.default.join(targetFolder, hyphenName + '.tsx');
1038
+ fs_extra_1.default.copySync(path_1.default.join((0, exports.getScriptDir)(), '..', 'defaults', 'component.tsx'), targetFile);
1039
+ let targetFile2 = path_1.default.join(targetFolder, hyphenName + '.scss');
1040
+ fs_extra_1.default.copySync(path_1.default.join((0, exports.getScriptDir)(), '..', 'defaults', 'component.scss'), targetFile2);
1041
+ //replace variables in some of the copied files
1042
+ await replaceVariablesInFiles(targetFile, targetFile2);
1043
+ 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, ''))}`);
1044
+ //if this is not a lincd app (but a lincd package instead)
1045
+ if (!sourceFolder.includes('frontend')) {
1046
+ //then also add an import to index
1047
+ let indexPath = addLineToIndex(`import './components/${hyphenName}.js';`, 'components');
1048
+ log(`Added an import of this file from ${chalk_1.default.magenta(indexPath)}`);
1049
+ }
1050
+ };
1051
+ exports.createComponent = createComponent;
1052
+ //read the source of all ts/tsx files in the src folder
1053
+ //if there is an import that imports a lincd package with /src/ in it, then warn
1054
+ //if there is an import that imports something from outside the src folder, then warn
1055
+ const checkImports = async (sourceFolder = getSourceFolder(), depth = 0, // Used to check if the import is outside the src folder
1056
+ invalidImports = new Map()) => {
1057
+ const dir = fs_extra_1.default.readdirSync(sourceFolder);
1058
+ // Start checking each file in the source folder
1059
+ for (const file of dir) {
1060
+ const filename = path_1.default.join(sourceFolder, file);
1061
+ // File is either a directory, or not a .ts(x)
1062
+ // INFO: For future use - if this part fails, it could be due to user permissions
1063
+ // i.e. the program not having access to check the file metadata
1064
+ if (!filename.match(/\.tsx?$/)) {
1065
+ try {
1066
+ if ((0, fs_1.statSync)(filename).isDirectory()) {
1067
+ await (0, exports.checkImports)(filename, depth + 1, invalidImports);
1068
+ }
1069
+ else {
1070
+ // Ignore all files that aren't one of the following:
1071
+ // - .ts
1072
+ // - .tsx
1073
+ continue;
1074
+ }
1075
+ }
1076
+ catch (e) {
1077
+ console.log(e);
1078
+ }
1079
+ }
1080
+ const allImports = await (0, utils_js_1.getFileImports)(filename);
1081
+ if (!invalidImports.has(filename)) {
1082
+ invalidImports.set(filename, []);
1083
+ }
1084
+ allImports.forEach((i) => {
1085
+ if ((0, utils_js_1.isImportOutsideOfPackage)(i, depth)) {
1086
+ invalidImports.get(filename).push({
1087
+ type: 'outside_package',
1088
+ importPath: i,
1089
+ });
1090
+ }
1091
+ if ((0, utils_js_1.isInvalidLINCDImport)(i, depth)) {
1092
+ invalidImports.get(filename).push({
1093
+ type: 'lincd',
1094
+ importPath: i,
1095
+ });
1096
+ }
1097
+ if ((0, utils_js_1.isImportWithMissingExtension)(i)) {
1098
+ invalidImports.get(filename).push({
1099
+ type: 'missing_extension',
1100
+ importPath: i,
1101
+ });
1102
+ }
1103
+ });
1104
+ }
1105
+ let res = '';
1106
+ //check if invalidImports has any
1107
+ let flat = [...invalidImports.values()].flat();
1108
+ // All recursion must have finished, display any errors
1109
+ if (depth === 0 && flat.length > 0) {
1110
+ res += chalk_1.default.red('Invalid imports found.\n');
1111
+ invalidImports.forEach((value, key) => {
1112
+ // res += '- '+chalk.blueBright(key.split('/').pop()) + ':\n';
1113
+ value.forEach(({ type, importPath }) => {
1114
+ let message = key.split('/').pop() + " imports from '" + importPath + "'";
1115
+ if (type === 'outside_package') {
1116
+ message += ' which is outside the package source root';
1117
+ }
1118
+ if (type === 'lincd') {
1119
+ message +=
1120
+ ' which should not contain /src/ or /lib/ in the import path';
1121
+ }
1122
+ if (type === 'missing_extension') {
1123
+ message +=
1124
+ ' which should end with a file extension. Like .js or .scss';
1125
+ }
1126
+ res += chalk_1.default.red(message + '\n');
1127
+ });
1128
+ });
1129
+ throw res;
1130
+ // process.exit(1);
1131
+ }
1132
+ else if (depth === 0 && invalidImports.size === 0) {
1133
+ // console.info('All imports OK');
1134
+ // process.exit(0);
1135
+ return true;
1136
+ }
1137
+ };
1138
+ exports.checkImports = checkImports;
1139
+ const depCheckStaged = async () => {
1140
+ console.log('Checking dependencies of staged files');
1141
+ (0, staged_git_files_1.default)(async function (err, results) {
1142
+ const packages = new Set();
1143
+ await Promise.all(results.map(async (file) => {
1144
+ // console.log('STAGED: ', file.filename);
1145
+ let root = await (0, find_nearest_package_json_1.findNearestPackageJson)(file.filename);
1146
+ packages.add(root.path);
1147
+ }));
1148
+ [...packages].forEach((packageRoot) => {
1149
+ const pack = JSON.parse(fs_extra_1.default.readFileSync(packageRoot, 'utf8'));
1150
+ const srcPath = packageRoot.replace('package.json', '');
1151
+ console.log('Checking dependencies of ' + chalk_1.default.blue(pack.name) + ':');
1152
+ return (0, exports.depCheck)(process.cwd() + '/' + srcPath);
1153
+ // console.log('check dependencies of ' + pack.name);
1154
+ //
1155
+ // console.log('ROOT of ' + file.filename + ': ' + root.path);
1156
+ // console.log('ROOT of ' + file.filename + ': ' + root.data);
1157
+ });
1158
+ });
1159
+ };
1160
+ exports.depCheckStaged = depCheckStaged;
1161
+ const depCheck = async (packagePath = process.cwd()) => {
1162
+ // log('Checking depencies of ' + chalk.cyan(packagePath));
1163
+ return new Promise((resolve, reject) => {
1164
+ (0, depcheck_1.default)(packagePath, {}, (results) => {
1165
+ if (results.missing) {
1166
+ let lincdPackages = getLocalLincdModules(packagePath);
1167
+ let missing = Object.keys(results.missing);
1168
+ //filter out missing types, if it builds we're not too concerned about that at the moment?
1169
+ //especially things like @types/react, @types/react-dom, @types/node (they are added elsewhere?)
1170
+ // missing = missing.filter(m => m.indexOf('@types/') === 0);
1171
+ //currently react is not an explicit dependency, but we should add it as a peer dependency
1172
+ missing.splice(missing.indexOf('react'), 1);
1173
+ let missingLincdPackages = missing.filter((missingDep) => {
1174
+ return lincdPackages.some((lincdPackage) => {
1175
+ return lincdPackage.packageName === missingDep;
1176
+ });
1177
+ });
1178
+ //currently just missing LINCD packages cause a hard failure exit code
1179
+ if (missingLincdPackages.length > 0) {
1180
+ reject(chalk_1.default.red(packagePath.split('/').pop() +
1181
+ '\n[ERROR] These LINCD packages are imported but they are not listed in package.json:\n- ' +
1182
+ missingLincdPackages
1183
+ .map((missedKey) => {
1184
+ const files = results.missing[missedKey];
1185
+ return `${missedKey} (${files.length} files: ${files.join(', ')})`;
1186
+ })
1187
+ .join(',\n- ')));
1188
+ }
1189
+ else if (missing.length > 0) {
1190
+ resolve(chalk_1.default.redBright('warning: ' +
1191
+ packagePath.split('/').pop() +
1192
+ ' is missing dependencies:\n - ' +
1193
+ missing.join('\n - ')));
1194
+ }
1195
+ else {
1196
+ resolve(true);
1197
+ }
1198
+ }
1199
+ // if(Object.keys(results.invalidFiles).length > 0) {
1200
+ // console.warn(chalk.red("Invalid files:\n")+Object.keys(results.invalidFiles).join(",\n"));
1201
+ // }
1202
+ // if(Object.keys(results.invalidDirs).length > 0) {
1203
+ // console.warn(chalk.red("Invalid dirs:\n")+results.invalidDirs.toString());
1204
+ // }
1205
+ // if(results.unused) {
1206
+ // console.warn("Unused dependencies: "+results.missing.join(", "));
1207
+ // }
1208
+ });
1209
+ });
1210
+ };
1211
+ exports.depCheck = depCheck;
1212
+ const ensureEnvironmentLoaded = async () => {
1213
+ if (!process.env.ENV_VARS_LOADED) {
1214
+ //load env-cmd for development environment
1215
+ let { GetEnvVars } = await Promise.resolve().then(() => __importStar(require('env-cmd')));
1216
+ let envCmdrcPath = path_1.default.join(process.cwd(), '.env-cmdrc.json');
1217
+ if (!fs_extra_1.default.existsSync(envCmdrcPath)) {
1218
+ console.warn('No .env-cmdrc.json found in this folder. Are you running this command from the root of a LINCD app?');
1219
+ process.exit();
1220
+ }
1221
+ let vars = await GetEnvVars({
1222
+ envFile: {
1223
+ filePath: envCmdrcPath,
1224
+ },
1225
+ });
1226
+ let environments = Object.keys(vars);
1227
+ // Snapshot the original shell environment so it always takes highest priority
1228
+ let shellEnv = { ...process.env };
1229
+ //if _main is present, load it first
1230
+ if (environments.includes('_main')) {
1231
+ process.env = { ...process.env, ...vars._main };
1232
+ }
1233
+ //if --env is passed, load that environment
1234
+ let args = process.argv.splice(2);
1235
+ if (args.includes('--env')) {
1236
+ let envIndex = args.indexOf('--env');
1237
+ let env = args[envIndex + 1];
1238
+ env.split(',').forEach((singleEnvironment) => {
1239
+ if (environments.includes(singleEnvironment)) {
1240
+ console.log('Environment: ' + singleEnvironment);
1241
+ process.env = { ...process.env, ...vars[singleEnvironment] };
1242
+ }
1243
+ else {
1244
+ console.warn('Environment ' +
1245
+ singleEnvironment +
1246
+ ' not found in .env-cmdrc.json. Available environments: ' +
1247
+ environments.join(', '));
1248
+ }
1249
+ });
1250
+ }
1251
+ else {
1252
+ //chose development by default
1253
+ process.env = { ...process.env, ...vars.development };
1254
+ console.log('No environment specified, using development');
1255
+ }
1256
+ // Re-apply original shell env vars so they always win over .env-cmdrc.json
1257
+ process.env = { ...process.env, ...shellEnv };
1258
+ process.env.ENV_VARS_LOADED = 'true';
1259
+ }
1260
+ };
1261
+ exports.ensureEnvironmentLoaded = ensureEnvironmentLoaded;
1262
+ const runScript = async (scriptName, options) => {
1263
+ //if spawn is not defined, default to true
1264
+ const spawn = options.spawn !== undefined ? options.spawn : true;
1265
+ await (0, exports.ensureEnvironmentLoaded)();
1266
+ if (spawn) {
1267
+ await (0, exports.startServer)(true);
1268
+ }
1269
+ log('Running script ' + scriptName);
1270
+ const scriptPath = path_1.default.join(process.cwd(), 'scripts', scriptName);
1271
+ const script = await Promise.resolve(`${scriptPath}`).then(s => __importStar(require(s)));
1272
+ await script.default().catch((error) => {
1273
+ log('Script ' + scriptName + ' finished with errors');
1274
+ logError(error);
1275
+ process.exit(1);
1276
+ });
1277
+ log('Script ' + scriptName + ' finished');
1278
+ process.exit(0);
1279
+ };
1280
+ exports.runScript = runScript;
1281
+ const runMethod = async (packageName, method, options) => {
1282
+ await (0, exports.ensureEnvironmentLoaded)();
1283
+ if (options.spawn) {
1284
+ let lincdConfig = (await Promise.resolve(`${path_1.default.join(process.cwd(), 'lincd.config.js')}`).then(s => __importStar(require(s)))).default;
1285
+ // Set default loadAppComponent if not provided
1286
+ if (!lincdConfig.server) {
1287
+ lincdConfig.server = {};
1288
+ }
1289
+ if (!lincdConfig.server.loadAppComponent) {
1290
+ lincdConfig.server.loadAppComponent = async () => (await Promise.resolve(`${path_1.default.join(process.cwd(), 'src', 'App')}`).then(s => __importStar(require(s)))).default;
1291
+ }
1292
+ // Set default loadRoutes if not provided
1293
+ if (!lincdConfig.server.loadRoutes) {
1294
+ lincdConfig.server.loadRoutes = async () => await Promise.resolve(`${path_1.default.join(process.cwd(), 'src', 'routes.tsx')}`).then(s => __importStar(require(s)));
1295
+ }
1296
+ //@ts-ignore
1297
+ const ServerClass = (await Promise.resolve().then(() => __importStar(require('lincd-server/shapes/LincdServer'))))
1298
+ .LincdServer;
1299
+ await Promise.resolve(`${path_1.default.join(process.cwd(), 'scripts', 'storage-config.js')}`).then(s => __importStar(require(s)));
1300
+ let server = new ServerClass(lincdConfig);
1301
+ //init the server
1302
+ console.log('Initializing server...');
1303
+ server.initOnly().then(() => {
1304
+ //process the backend method call
1305
+ console.log('Running method ' + method);
1306
+ //mock the request and response objects
1307
+ let request = {
1308
+ body: {},
1309
+ query: {},
1310
+ params: {},
1311
+ headers: {},
1312
+ method: 'POST',
1313
+ url: '/' + packageName + '/' + method,
1314
+ };
1315
+ let response = {
1316
+ status: (statusCode) => {
1317
+ console.log('Response status code:', statusCode);
1318
+ return response;
1319
+ },
1320
+ json: (data) => {
1321
+ console.log('Response data:', data);
1322
+ },
1323
+ send: (data) => {
1324
+ console.log('Response data:', data);
1325
+ },
1326
+ };
1327
+ //TODO; allow sending args
1328
+ server
1329
+ .callBackendMethod(packageName, method, [], request, response)
1330
+ .then(() => {
1331
+ console.log('Done');
1332
+ process.exit();
1333
+ });
1334
+ });
1335
+ }
1336
+ else {
1337
+ //reuse the existing running LincdServer instance.
1338
+ //make a HTTP call
1339
+ //'/call/:pkg/:method',
1340
+ fetch(process.env.SITE_ROOT + '/call/' + packageName + '/' + method, {
1341
+ method: 'POST',
1342
+ headers: {
1343
+ 'Content-Type': 'application/json',
1344
+ },
1345
+ })
1346
+ .then((response) => {
1347
+ if (!response.ok) {
1348
+ throw new Error('Network response was not ok');
1349
+ }
1350
+ return response.json();
1351
+ })
1352
+ .then((data) => {
1353
+ console.log('Response data:', data);
1354
+ process.exit();
1355
+ })
1356
+ .catch((error) => {
1357
+ var _a;
1358
+ if (error.code === 'ECONNREFUSED' ||
1359
+ ((_a = error.cause) === null || _a === void 0 ? void 0 : _a.code) === 'ECONNREFUSED') {
1360
+ console.error(chalk_1.default.red('Could not connect to the backend server. Is it running?'));
1361
+ console.error(`Make sure you ${chalk_1.default.magenta('run "yarn start" in a separate process')} before calling this method.`);
1362
+ }
1363
+ else {
1364
+ console.error('Error during backend call:', error);
1365
+ }
1366
+ process.exit(1);
1367
+ });
1368
+ }
1369
+ };
1370
+ exports.runMethod = runMethod;
1371
+ const startServer = async (initOnly = false, ServerClass = null) => {
1372
+ await (0, exports.ensureEnvironmentLoaded)();
1373
+ let lincdConfig = (await Promise.resolve(`${path_1.default.join(process.cwd(), 'lincd.config.js')}`).then(s => __importStar(require(s))))
1374
+ .default;
1375
+ // function scssLoadcall(source, filename) {
1376
+ // return 'console.log("SCSS CALL: ' + filename + '");\n' + source;
1377
+ // process.exit();
1378
+ // }
1379
+ // hook.hook('.scss', scssLoadcall);
1380
+ // hook.hook('.css', scssLoadcall);
1381
+ // import.meta.
1382
+ // // hook.hook('*.css', scssLoadcall);
1383
+ // // hook.hook('Body.module.css', scssLoadcall);
1384
+ // hook.hook('.module.css', scssLoadcall);
1385
+ if (!ServerClass) {
1386
+ //@ts-ignore
1387
+ ServerClass = (await Promise.resolve().then(() => __importStar(require('lincd-server/shapes/LincdServer')))).LincdServer;
1388
+ }
1389
+ await Promise.resolve(`${path_1.default.join(process.cwd(), 'scripts', 'storage-config.js')}`).then(s => __importStar(require(s)));
1390
+ // Set default loadAppComponent if not provided
1391
+ if (!lincdConfig.server) {
1392
+ lincdConfig.server = {};
1393
+ }
1394
+ if (!lincdConfig.server.loadAppComponent) {
1395
+ let appPromise;
1396
+ if (process.env.NODE_ENV !== 'development') {
1397
+ appPromise = (await Promise.resolve(`${path_1.default.join(process.cwd(), 'lib', 'App.js')}`).then(s => __importStar(require(s))))
1398
+ .default;
1399
+ }
1400
+ else {
1401
+ appPromise = (await Promise.resolve(`${path_1.default.join(process.cwd(), 'src', 'App.tsx')}`).then(s => __importStar(require(s))))
1402
+ .default;
1403
+ }
1404
+ lincdConfig.server.loadAppComponent = async () => {
1405
+ return appPromise;
1406
+ };
1407
+ }
1408
+ // Set default loadRoutes if not provided
1409
+ if (!lincdConfig.server.loadRoutes) {
1410
+ lincdConfig.server.loadRoutes = async () => {
1411
+ if (process.env.NODE_ENV !== 'development') {
1412
+ return await Promise.resolve(`${path_1.default.join(process.cwd(), 'lib', 'routes.js')}`).then(s => __importStar(require(s)));
1413
+ }
1414
+ else {
1415
+ return await Promise.resolve(`${path_1.default.join(process.cwd(), 'src', 'routes.tsx')}`).then(s => __importStar(require(s)));
1416
+ }
1417
+ };
1418
+ }
1419
+ let server = new ServerClass(lincdConfig);
1420
+ //Important to use slice, because when using clusers, child processes need to be able to read the same arguments
1421
+ let args = process.argv.slice(2);
1422
+ //if --initOnly is passed, only initialize the server and don't start it
1423
+ if (args.includes('--initOnly') || initOnly) {
1424
+ return server.initOnly();
1425
+ }
1426
+ else {
1427
+ return server.start();
1428
+ }
1429
+ };
1430
+ exports.startServer = startServer;
1431
+ const buildApp = async () => {
1432
+ await (0, exports.buildFrontend)();
1433
+ await (0, exports.buildBackend)();
1434
+ console.log(chalk_1.default.magenta(`✅ ${process.env.NODE_ENV} app build finished`));
1435
+ process.exit(0);
1436
+ };
1437
+ exports.buildApp = buildApp;
1438
+ const buildFrontend = async () => {
1439
+ await (0, exports.ensureEnvironmentLoaded)();
1440
+ const webpackAppConfig = await (await Promise.resolve().then(() => __importStar(require('./config-webpack-app.js')))).getWebpackAppConfig();
1441
+ console.log(chalk_1.default.magenta(`🛠 Building ${process.env.NODE_ENV} frontend bundles`));
1442
+ await new Promise((resolve, reject) => {
1443
+ (0, webpack_1.default)(webpackAppConfig, async (err, stats) => {
1444
+ if (err) {
1445
+ console.error(err.stack || err);
1446
+ process.exit(1);
1447
+ }
1448
+ const info = stats.toJson();
1449
+ if (stats.hasErrors()) {
1450
+ console.log('Finished running webpack with errors.');
1451
+ info.errors.forEach((e) => console.error(e));
1452
+ // process.exit(1);
1453
+ reject();
1454
+ }
1455
+ else {
1456
+ console.log(stats.toString({
1457
+ chunks: false,
1458
+ assets: true,
1459
+ entrypoints: false,
1460
+ modules: false,
1461
+ moduleAssets: false,
1462
+ colors: true,
1463
+ }));
1464
+ console.log('App build process finished');
1465
+ resolve(true);
1466
+ // console.log(
1467
+ // chalk.green('\t'+Object.keys(stats.compilation.assets).join('\n\t')),
1468
+ // );
1469
+ //build metadata (JSON-LD files containing metadata about the lincd components, shapes & ontologies in this app or its packages)
1470
+ // let updatedPaths = await buildMetadata();
1471
+ // console.log(chalk.green("Updated metadata:\n")+" - "+updatedPaths.map(p => chalk.magenta(p.replace(process.cwd(),''))).join("\n - "));
1472
+ }
1473
+ // process.exit();
1474
+ });
1475
+ }).then(async () => {
1476
+ // make sure environment is not development for storage config
1477
+ // and if we want to upload to storage, we need set S3_BUCKET_ENDPOINT
1478
+ if (process.env.NODE_ENV === 'development' ||
1479
+ !process.env.S3_BUCKET_ENDPOINT) {
1480
+ console.warn('Upload build to storage skip in development environment or S3_BUCKET_ENDPOINT is not set');
1481
+ return;
1482
+ // process.exit();
1483
+ }
1484
+ if (process.env.APP_ENV) {
1485
+ console.warn('Not uploading to CDN for app builds');
1486
+ return;
1487
+ // process.exit();
1488
+ }
1489
+ // load the storage config
1490
+ const storageConfig = await Promise.resolve(`${path_1.default.join(process.cwd(), 'scripts', 'storage-config.js')}`).then(s => __importStar(require(s)));
1491
+ // check if LincdFileStorage has a default FileStore
1492
+ // if yes: copy all the files in the build folder over with LincdFileStorage
1493
+ if (LinkedFileStorage_1.LinkedFileStorage.getDefaultStore()) {
1494
+ // get public directory
1495
+ const rootDirectory = 'public';
1496
+ const pathDir = path_1.default.join(process.cwd(), rootDirectory);
1497
+ if (!fs_extra_1.default.existsSync(pathDir)) {
1498
+ console.warn('No public directory found. Please create a public directory in the root of your project');
1499
+ return;
1500
+ }
1501
+ // get all files in the web directory and then upload them to the storage
1502
+ const files = await (0, utils_js_1.getFiles)(pathDir);
1503
+ console.log(chalk_1.default.magenta(`🕊 Publishing ${files.length} public files to linked file storage`));
1504
+ const clearSpinner = (0, ora_1.default)({
1505
+ discardStdin: true,
1506
+ text: `Publishing ${files.length} public files`,
1507
+ }).start();
1508
+ let counter = 0;
1509
+ const uploads = files.map(async (filePath) => {
1510
+ // read file content
1511
+ const fileContent = await fs_extra_1.default.promises.readFile(filePath);
1512
+ // replace pathDir with rootDirectory in filePath to get pathname
1513
+ // example: /Users/username/project/www/index.html -> /project/www/index.html
1514
+ const pathname = filePath.replace(pathDir, `/${rootDirectory}`);
1515
+ // upload file to storage
1516
+ await LinkedFileStorage_1.LinkedFileStorage.saveFile(pathname, fileContent)
1517
+ .then(() => {
1518
+ clearSpinner.text = `${counter++}/${files.length}: - Published ${pathname} `;
1519
+ })
1520
+ .catch(console.error);
1521
+ });
1522
+ const urls = await Promise.all(uploads);
1523
+ clearSpinner.succeed(`${urls.length} files uploaded to storage`);
1524
+ }
1525
+ });
1526
+ };
1527
+ exports.buildFrontend = buildFrontend;
1528
+ const buildBackend = async () => {
1529
+ console.log(chalk_1.default.magenta(`🛠 Preparing ${process.env.NODE_ENV} backend`));
1530
+ //run tsc in the backend folder
1531
+ await (0, exports.ensureEnvironmentLoaded)();
1532
+ const sourceFolder = path_1.default.join(process.cwd(), 'src');
1533
+ const targetFolder = path_1.default.join(process.cwd(), 'lib');
1534
+ // Step 1: Clear lib folder
1535
+ const clearSpinner = (0, ora_1.default)({
1536
+ discardStdin: true,
1537
+ text: 'Clearing lib folder',
1538
+ }).start();
1539
+ try {
1540
+ if (fs_extra_1.default.existsSync(targetFolder)) {
1541
+ await fs_extra_1.default.remove(targetFolder);
1542
+ }
1543
+ clearSpinner.succeed('Lib folder cleared');
1544
+ }
1545
+ catch (e) {
1546
+ console.error(e);
1547
+ clearSpinner.fail('Failed to clear lib folder');
1548
+ return;
1549
+ }
1550
+ // Step 2: Compile TS files
1551
+ const compileSpinner = (0, ora_1.default)({
1552
+ discardStdin: true,
1553
+ text: 'Compiling backend TS files',
1554
+ }).start();
1555
+ try {
1556
+ await (0, utils_js_1.execPromise)(`yarn exec tsc`);
1557
+ compileSpinner.succeed('Backend TS files compiled');
1558
+ }
1559
+ catch (e) {
1560
+ console.error(e);
1561
+ compileSpinner.fail('Failed to compile backend TS files');
1562
+ return;
1563
+ }
1564
+ // Step 3: Copy CSS files
1565
+ const copySpinner = (0, ora_1.default)({
1566
+ discardStdin: true,
1567
+ text: 'Copying CSS files',
1568
+ }).start();
1569
+ try {
1570
+ const cssFiles = await (0, utils_js_1.getFiles)(sourceFolder, '.css');
1571
+ await Promise.all(cssFiles.map((file) => {
1572
+ const targetFile = file.replace(sourceFolder, targetFolder);
1573
+ //ensure the target folder exists
1574
+ const targetDir = path_1.default.dirname(targetFile);
1575
+ if (!fs_extra_1.default.existsSync(targetDir)) {
1576
+ fs_extra_1.default.mkdirSync(targetDir, { recursive: true });
1577
+ }
1578
+ return fs_extra_1.default.copyFile(file, targetFile);
1579
+ }));
1580
+ copySpinner.succeed(`${cssFiles.length} CSS files copied`);
1581
+ }
1582
+ catch (e) {
1583
+ console.error(e);
1584
+ copySpinner.fail('Failed to copy CSS files');
1585
+ }
1586
+ return true;
1587
+ };
1588
+ exports.buildBackend = buildBackend;
1589
+ const upgradePackages = async () => {
1590
+ await (0, exports.ensureEnvironmentLoaded)();
1591
+ // let packages = getLincdPackages();
1592
+ // let packages = getLocalLincdModules();
1593
+ let packages = getLocalLincdPackageMap();
1594
+ let dirname = (0, exports.getScriptDir)();
1595
+ const tsConfigCJS = path_1.default.join(dirname, '../../defaults/package', 'tsconfig-cjs.json');
1596
+ const tsConfigESM = path_1.default.join(dirname, '../../defaults/package', 'tsconfig-esm.json');
1597
+ const typesFile = path_1.default.join(dirname, '../../defaults/package/src', 'types.d.ts');
1598
+ const tsConfigTemplate = await fs_extra_1.default
1599
+ .readJson(path_1.default.join(dirname, '../../defaults/package', 'tsconfig.json'))
1600
+ .catch((err) => {
1601
+ console.log(err);
1602
+ });
1603
+ runOnPackagesGroupedByDependencies(packages, (packageGroup, dependencies) => {
1604
+ // packageGroup.forEach((pkg) => {
1605
+ // console.log(' Upgrading ' + pkg.packageName);
1606
+ console.log('-----');
1607
+ return async (pkg) => {
1608
+ if (pkg.packageName === 'lincd')
1609
+ return;
1610
+ // await execPromise(`cd ${pkg.path} && yarn upgrade`);
1611
+ console.log('Upgrading ' + pkg.packageName);
1612
+ //
1613
+ // //create a new file src/tsconfig-cjs.json
1614
+ // //copy the contents of tsconfig.json into it
1615
+ // if (!fs.existsSync(path.join(pkg.path,'tsconfig-cjs.json')))
1616
+ // {
1617
+ // await fs.copy(tsConfigCJS,path.join(pkg.path,'tsconfig-cjs.json'));
1618
+ // await fs.copy(tsConfigESM,path.join(pkg.path,'tsconfig-esm.json'));
1619
+ // console.log('Copied new tsconfig to ' + pkg.packageName);
1620
+ // }
1621
+ //
1622
+ // //read tsconfig
1623
+ // await fs.readJson(path.join(pkg.path,'tsconfig.json')).then((tsconfig) => {
1624
+ // let oldCompilerOpts = tsconfig.compilerOptions;
1625
+ // tsconfig.compilerOptions = tsConfigTemplate.compilerOptions;
1626
+ // tsconfig.compilerOptions.types = oldCompilerOpts.types;
1627
+ // tsconfig.compilerOptions.plugins = [{"name": "typescript-plugin-css-modules"}];
1628
+ //
1629
+ // console.log('Upgraded tsconfig for ' + pkg.packageName);
1630
+ // return fs.writeJson(path.join(pkg.path,'tsconfig.json'),tsconfig,{spaces: 2});
1631
+ // });
1632
+ // //import types at the beginning of index.ts
1633
+ // addLineToIndex(`import './types';`,null,pkg.path,true);
1634
+ // //copy over the types file
1635
+ // await fs.copy(typesFile,path.join(pkg.path,'src','types.d.ts'));
1636
+ // await fs.readJson(path.join(pkg.path,'package.json')).then((packageJson) => {
1637
+ // let version = packageJson.version;
1638
+ // let nextVersion;
1639
+ // if (version.split('.').shift() === '0')
1640
+ // {
1641
+ // nextVersion = getNextMajorVersion(version);
1642
+ // }
1643
+ // else
1644
+ // {
1645
+ // nextVersion = getNextMinorVersion(version);
1646
+ // }
1647
+ // console.log('Upgraded version for ' + pkg.packageName + ' to ' + nextVersion);
1648
+ //
1649
+ // packageJson.version = nextVersion;
1650
+ // packageJson.devDependencies['tsconfig-to-dual-package'] = '^1.2.0';
1651
+ // packageJson.devDependencies['typescript-plugin-css-modules'] = '^5.1.0';
1652
+ //
1653
+ // packageJson.main = 'lib/cjs/index.js';
1654
+ // packageJson.module = 'lib/esm/index.js';
1655
+ // packageJson.exports = {
1656
+ // '.': {
1657
+ // 'types': './lib/esm/index.d.ts',
1658
+ // 'import': './lib/esm/index.js',
1659
+ // 'require': './lib/cjs/index.js',
1660
+ // },
1661
+ // './*': {
1662
+ // 'types': './lib/esm/*.d.ts',
1663
+ // 'import': './lib/esm/*.js',
1664
+ // 'require': './lib/cjs/*.js',
1665
+ // },
1666
+ // };
1667
+ // packageJson.typesVersions = {
1668
+ // '*': {
1669
+ // '*': [
1670
+ // 'lib/esm/*',
1671
+ // ],
1672
+ // },
1673
+ // };
1674
+ //
1675
+ // return fs.writeJson(path.join(pkg.path,'package.json'),packageJson,{ spaces: 2 });
1676
+ // });
1677
+ //change .css files and .scss files to .module.css and .module.scss
1678
+ let files = await (0, utils_js_1.getFiles)(path_1.default.join(pkg.path, 'src'));
1679
+ // let tsFiles = files.filter(f => f.match(/\.(ts|tsx)$/));
1680
+ // let cssFiles = files.filter(f => f.match(/\.(css|scss)$/)).filter(f => !f.match(/\.module\.(css|scss)$/));
1681
+ // cssFiles.forEach(cssFile => {
1682
+ // let cssFileName = path.basename(cssFile);
1683
+ // let newFile = cssFileName.replace(/\.s?css$/,'.module$&');
1684
+ // let newFilePath = cssFile.replace(/\.s?css$/,'.module$&');
1685
+ // let jsonFile = cssFileName.replace(/\.s?css$/,'$&.json');
1686
+ // fs.renameSync(cssFile,newFilePath);
1687
+ // console.log('Renaming ' + cssFileName + ' to ' + newFilePath);
1688
+ // //find other files that import this file and update them
1689
+ // tsFiles.forEach(tsFile => {
1690
+ // //read contents of f2
1691
+ // let contents = fs.readFileSync(tsFile,'utf8');
1692
+ // //if it imports f
1693
+ // if (contents.indexOf(cssFileName) !== -1)
1694
+ // {
1695
+ // //find the whole line that imports f
1696
+ // let line = contents.split('\n').find(l => l.indexOf(cssFileName) !== -1);
1697
+ // // console.log("OLD: "+line);
1698
+ // let jsonLine = contents.split('\n').find(l => l.indexOf(jsonFile) !== -1);
1699
+ // // console.log("JSON: "+jsonLine);
1700
+ // //if not commented out
1701
+ // if(line.indexOf('//') === -1) {
1702
+ // let previousImportPath = line.match(/['"](.*)['"]/)[1];
1703
+ // let newImportPath = previousImportPath.replace(cssFileName,newFile);
1704
+ // let newContents = contents.replace(line,`import style from '${newImportPath}';`)
1705
+ // .replace(jsonLine+'\n','');
1706
+ // // console.log("\n");
1707
+ // fs.writeFileSync(tsFile,newContents);
1708
+ // console.log('Updated imports in ' + tsFile);
1709
+ // // fs.writeFileSync
1710
+ // // fs.writeFileSync(i,fs.readFileSync(i,'utf8').replace(f,newFile));
1711
+ // }
1712
+ // }
1713
+ // })
1714
+ // });
1715
+ files
1716
+ .filter((f) => f.match(/\.(scss\.json|css\.json)$/))
1717
+ .forEach((cssJsonFile) => {
1718
+ console.log('Removing ' + cssJsonFile);
1719
+ fs_extra_1.default.unlinkSync(cssJsonFile);
1720
+ });
1721
+ };
1722
+ // });
1723
+ }, () => {
1724
+ console.log('Finished upgrading packages');
1725
+ });
1726
+ // packages.forEach((pkg,key) => {
1727
+ // console.log(key+' Upgrading ' + pkg.packageName);
1728
+ // execPromise(`cd ${pkg.path} && yarn upgrade`).then(() => {
1729
+ // console.log('Upgraded ' + pkg.packageName);
1730
+ // }).catch(err => {
1731
+ // console.warn(err);
1732
+ // })
1733
+ // });
1734
+ };
1735
+ exports.upgradePackages = upgradePackages;
1736
+ const createPackage = async (name, uriBase, basePath = process.cwd()) => {
1737
+ if (!name) {
1738
+ console.warn('Please provide a name as the first argument');
1739
+ return;
1740
+ }
1741
+ //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)
1742
+ //so we manually find a packages folder, if it exists we go into that.
1743
+ if (fs_extra_1.default.existsSync(path_1.default.join(basePath, 'packages'))) {
1744
+ basePath = path_1.default.join(basePath, 'packages');
1745
+ }
1746
+ //for lincd.org currently packages are stored in the modules folder
1747
+ else if (fs_extra_1.default.existsSync(path_1.default.join(basePath, 'modules'))) {
1748
+ basePath = path_1.default.join(basePath, 'modules');
1749
+ }
1750
+ //let's remove scope for variable names
1751
+ let [packageName, scope, cleanPackageName] = name.match(/(@[\w\-]+\/)?([\w\-]+)/);
1752
+ let targetFolder = ensureFolderExists(basePath, cleanPackageName);
1753
+ if (!uriBase) {
1754
+ uriBase = 'http://lincd.org/ont/' + name;
1755
+ }
1756
+ setVariable('uri_base', uriBase + '/');
1757
+ //find @scope and the next part between 2 slashes after
1758
+ //so @dacore/some-mod/lib/file.js
1759
+ // --> match[0] = @dacore/some-mod
1760
+ // --> match[1] = @dacore
1761
+ // --> match[2] = some-mod
1762
+ //but save full scoped package name under ${package_name}
1763
+ setVariable('package_name', name);
1764
+ //extra variable for clarity (will be same as 'name')
1765
+ setVariable('output_file_name', name);
1766
+ let { hyphenName, camelCaseName, underscoreName } = (0, exports.setNameVariables)(cleanPackageName);
1767
+ log("Creating new LINCD package '" + name + "'");
1768
+ fs_extra_1.default.copySync(path_1.default.join((0, exports.getScriptDir)(), '..', '..', 'defaults', 'package'), targetFolder);
1769
+ //replace variables in some of the copied files
1770
+ await Promise.all([
1771
+ 'src/index.ts',
1772
+ 'package.json',
1773
+ 'Gruntfile.js',
1774
+ 'src/package.ts',
1775
+ 'src/ontologies/example-ontology.ts',
1776
+ 'src/data/example-ontology.json',
1777
+ ]
1778
+ .map((f) => path_1.default.join(targetFolder, f))
1779
+ .map((file) => {
1780
+ return replaceVariablesInFile(file);
1781
+ }));
1782
+ //rename these to a file name similar to the pkg name
1783
+ [
1784
+ 'src/ontologies/example-ontology.ts',
1785
+ 'src/data/example-ontology.json',
1786
+ 'src/data/example-ontology.json.d.ts',
1787
+ ].forEach((f) => {
1788
+ let parts = f.split('/');
1789
+ let newParts = [...parts];
1790
+ let [name, ...extensions] = newParts.pop().split('.');
1791
+ let newName = hyphenName + '.' + extensions.join('.');
1792
+ console.log('rename ', path_1.default.join(targetFolder, f), path_1.default.join(targetFolder, ...newParts, newName));
1793
+ fs_extra_1.default.renameSync(path_1.default.join(targetFolder, f), path_1.default.join(targetFolder, ...newParts, newName));
1794
+ });
1795
+ let version = (await (0, utils_js_1.execPromise)('yarn --version').catch((err) => {
1796
+ console.log('yarn probably not working');
1797
+ return '';
1798
+ }));
1799
+ let installCommand = version.toString().match(/[0-9]+/)
1800
+ ? 'yarn install'
1801
+ : 'npm install';
1802
+ await (0, utils_js_1.execp)(`cd ${targetFolder} && ${installCommand} && npm exec lincd build`, true).catch((err) => {
1803
+ console.warn('Could not install dependencies');
1804
+ });
1805
+ 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`);
1806
+ };
1807
+ exports.createPackage = createPackage;
1808
+ var getNextVersion = function (version) {
1809
+ let parts = version.split('.');
1810
+ return parts[0] + '.' + parts[1] + '.' + (parseInt(parts[2]) + 1).toString();
1811
+ };
1812
+ var getNextMajorVersion = function (version) {
1813
+ let parts = version.split('.');
1814
+ return (parseInt(parts[0]) + 1).toString() + '.0.0';
1815
+ };
1816
+ var getNextMinorVersion = function (version) {
1817
+ let parts = version.split('.');
1818
+ return parts[0] + '.' + (parseInt(parts[1]) + 1).toString() + '.0';
1819
+ };
1820
+ var buildFailed = function (output) {
1821
+ return (output.indexOf('Aborted due to warnings') !== -1 &&
1822
+ output.indexOf('Command failed') !== -1);
1823
+ };
1824
+ const register = function (registryURL) {
1825
+ if (fs_extra_1.default.existsSync(process.cwd() + '/package.json')) {
1826
+ var pack = JSON.parse(fs_extra_1.default.readFileSync(process.cwd() + '/package.json', 'utf8'));
1827
+ let version = pack.version;
1828
+ let packageName = pack.name;
1829
+ // let author = pack.author;
1830
+ // let description = pack.description;
1831
+ //
1832
+ // let authorName = pack.author;
1833
+ // if (pack.author.name) {
1834
+ // authorName = pack.author.name;
1835
+ // }
1836
+ console.log(chalk_1.default.cyan('registering package ' +
1837
+ packageName +
1838
+ ' ' +
1839
+ version +
1840
+ ' in the LINCD registry'));
1841
+ return fetch(registryURL + '/register', {
1842
+ method: 'POST',
1843
+ headers: {
1844
+ Accept: 'application/json, text/plain, */*',
1845
+ 'Content-Type': 'application/json',
1846
+ },
1847
+ body: JSON.stringify({ package: packageName, version }),
1848
+ // body: JSON.stringify({package: packageName, version, author}),
1849
+ })
1850
+ .then((res) => res.json())
1851
+ .then((json) => {
1852
+ if (json.error) {
1853
+ console.log(chalk_1.default.red('Response: ' + json.error));
1854
+ }
1855
+ else if (json.result) {
1856
+ console.log(chalk_1.default.blueBright('Response: ') + json.result);
1857
+ if (json.warning) {
1858
+ console.log(chalk_1.default.red('Warning: ') + json.warning);
1859
+ }
1860
+ }
1861
+ })
1862
+ .catch((err) => {
1863
+ console.warn(chalk_1.default.red('Warning: ') + 'Could not connect to LINCD registry');
1864
+ });
1865
+ }
1866
+ else {
1867
+ console.warn(chalk_1.default.red('Warning:') + ' not found: ' + process.cwd() + '/package.json');
1868
+ }
1869
+ };
1870
+ exports.register = register;
1871
+ const buildPackage = async (target, target2, packagePath = process.cwd(), logResults = true) => {
1872
+ // Ensure packagePath is absolute and points to a directory containing package.json; if not, go up until we find one
1873
+ // First, resolve to absolute path
1874
+ let currentPath = path_1.default.isAbsolute(packagePath)
1875
+ ? packagePath
1876
+ : path_1.default.resolve(process.cwd(), packagePath);
1877
+ while (!fs_extra_1.default.existsSync(path_1.default.join(currentPath, 'package.json'))) {
1878
+ const parentPath = path_1.default.dirname(currentPath);
1879
+ if (parentPath === currentPath) {
1880
+ // Reached root and didn't find package.json. Optionally, handle this error.
1881
+ console.error('No package.json found in ' +
1882
+ packagePath +
1883
+ ' or any parent directories');
1884
+ return false;
1885
+ }
1886
+ currentPath = parentPath;
1887
+ }
1888
+ // Always use the resolved absolute path
1889
+ packagePath = currentPath;
1890
+ let spinner;
1891
+ if (logResults) {
1892
+ //TODO: replace with listr so we can show multiple processes at once
1893
+ spinner = (0, ora_1.default)({
1894
+ discardStdin: true,
1895
+ text: 'Compiling ESM',
1896
+ }).start();
1897
+ }
1898
+ let buildProcess = Promise.resolve(true);
1899
+ let buildStep = (step) => {
1900
+ buildProcess = buildProcess.then((previousResult) => {
1901
+ if (!previousResult) {
1902
+ return false;
1903
+ }
1904
+ if (logResults) {
1905
+ spinner.text = step.name;
1906
+ spinner.start();
1907
+ }
1908
+ return step.apply().then((stepResult) => {
1909
+ //if a build step returns a string,
1910
+ //a warning is shown but the build is still successful with warnings
1911
+ if (typeof stepResult === 'string') {
1912
+ // spinner.text = step.name + ' - ' + stepResult;
1913
+ if (logResults) {
1914
+ spinner.warn(step.name + ' - ' + stepResult);
1915
+ spinner.stop();
1916
+ }
1917
+ //can still continue
1918
+ return true;
1919
+ }
1920
+ else if (stepResult === true || typeof stepResult === 'undefined') {
1921
+ if (logResults) {
1922
+ spinner.succeed();
1923
+ }
1924
+ return previousResult && true;
1925
+ }
1926
+ else if (typeof stepResult === 'object' && stepResult.error) {
1927
+ if (logResults) {
1928
+ spinner.fail(step.name + ' - ' + stepResult.error);
1929
+ spinner.stop();
1930
+ }
1931
+ //failed and should stop
1932
+ return false;
1933
+ }
1934
+ });
1935
+ });
1936
+ };
1937
+ buildStep({
1938
+ name: 'Checking imports',
1939
+ apply: () => (0, exports.checkImports)(packagePath + '/src'),
1940
+ });
1941
+ buildStep({
1942
+ name: 'Compiling ESM',
1943
+ apply: async () => {
1944
+ return (0, exports.compilePackageESM)(packagePath);
1945
+ },
1946
+ });
1947
+ buildStep({
1948
+ name: 'Compiling CJS',
1949
+ apply: async () => {
1950
+ return (0, exports.compilePackageCJS)(packagePath);
1951
+ },
1952
+ });
1953
+ buildStep({
1954
+ name: 'Copying files to lib folder',
1955
+ apply: async () => {
1956
+ const files = await (0, glob_1.glob)(packagePath + '/src/**/*.{json,d.ts,css,scss}');
1957
+ return Promise.all(files.map(async (file) => {
1958
+ try {
1959
+ await fs_extra_1.default.copy(file, packagePath +
1960
+ '/lib/esm/' +
1961
+ file.replace(packagePath + '/src/', ''));
1962
+ await fs_extra_1.default.copy(file, packagePath +
1963
+ '/lib/cjs/' +
1964
+ file.replace(packagePath + '/src/', ''));
1965
+ return true;
1966
+ }
1967
+ catch (err) {
1968
+ console.warn(err);
1969
+ return false;
1970
+ }
1971
+ })).then((allResults) => {
1972
+ return allResults.every((r) => r === true);
1973
+ });
1974
+ },
1975
+ });
1976
+ buildStep({
1977
+ name: 'Dual package support',
1978
+ apply: () => {
1979
+ return (0, utils_js_1.execPromise)('yarn tsconfig-to-dual-package ./tsconfig-cjs.json ./tsconfig-esm.json', false, false, { cwd: packagePath }).then((res) => {
1980
+ return res === '';
1981
+ });
1982
+ },
1983
+ });
1984
+ buildStep({
1985
+ name: 'Removing old files from lib folder',
1986
+ apply: async () => {
1987
+ return (0, exports.removeOldFiles)(packagePath);
1988
+ },
1989
+ });
1990
+ buildStep({
1991
+ name: 'Checking dependencies',
1992
+ apply: () => (0, exports.depCheck)(packagePath),
1993
+ });
1994
+ let success = await buildProcess.catch((err) => {
1995
+ let msg = typeof err === 'string' || err instanceof Error
1996
+ ? err.toString()
1997
+ : err.error && !err.error.toString().includes('Command failed:')
1998
+ ? err.error
1999
+ : err.stdout + '\n' + err.stderr;
2000
+ if (logResults) {
2001
+ spinner.stopAndPersist({
2002
+ symbol: chalk_1.default.red('✖'),
2003
+ // text: 'Build failed',
2004
+ });
2005
+ }
2006
+ else {
2007
+ console.error(chalk_1.default.red(packagePath.split('/').pop(), ' - Build failed:'));
2008
+ console.error(err);
2009
+ return msg;
2010
+ }
2011
+ console.log(msg);
2012
+ });
2013
+ //will be undefined if there was an error
2014
+ if (typeof success !== 'undefined' && success !== false) {
2015
+ if (logResults) {
2016
+ spinner.stopAndPersist({
2017
+ symbol: chalk_1.default.greenBright('✔'),
2018
+ text: success === true
2019
+ ? 'Build successful'
2020
+ : 'Build successful with warnings',
2021
+ });
2022
+ }
2023
+ }
2024
+ else {
2025
+ if (logResults) {
2026
+ spinner.stopAndPersist({
2027
+ symbol: chalk_1.default.red('✖'),
2028
+ text: 'Build failed',
2029
+ });
2030
+ }
2031
+ }
2032
+ return success;
2033
+ };
2034
+ exports.buildPackage = buildPackage;
2035
+ const compilePackage = async (packagePath = process.cwd()) => {
2036
+ //echo 'compiling CJS' && tsc -p tsconfig-cjs.json && echo 'compiling ESM' && tsc -p tsconfig-esm.json
2037
+ // let cjsConfig = fs.existsSync(path.join(packagePath,'tsconfig-cjs.json'));
2038
+ // let esmConfig = fs.existsSync(path.join(packagePath,'tsconfig-esm.json'));
2039
+ // let compileCJS = `yarn exec tsc -p tsconfig-cjs.json`;
2040
+ // let compileESM = `yarn exec tsc -p tsconfig-esm.json`;
2041
+ // let compileCommand;
2042
+ // if (cjsConfig && esmConfig)
2043
+ // {
2044
+ // compileCommand = `${compileCJS} && ${compileESM}`;
2045
+ // }
2046
+ // else if (cjsConfig)
2047
+ // {
2048
+ // compileCommand = compileCJS;
2049
+ // }
2050
+ // else if (esmConfig)
2051
+ // {
2052
+ // compileCommand = compileESM;
2053
+ // }
2054
+ // else
2055
+ // {
2056
+ // compileCommand = `yarn exec tsc`;
2057
+ // }
2058
+ await (0, exports.compilePackageESM)(packagePath);
2059
+ await (0, exports.compilePackageCJS)(packagePath);
2060
+ };
2061
+ exports.compilePackage = compilePackage;
2062
+ const compilePackageESM = async (packagePath = process.cwd()) => {
2063
+ //echo 'compiling CJS' && tsc -p tsconfig-cjs.json && echo 'compiling ESM' && tsc -p tsconfig-esm.json
2064
+ let compileCommand = `yarn exec tsc -p tsconfig-esm.json`;
2065
+ return (0, utils_js_1.execPromise)(compileCommand, false, false, { cwd: packagePath }).then((res) => {
2066
+ return res === '';
2067
+ });
2068
+ };
2069
+ exports.compilePackageESM = compilePackageESM;
2070
+ const compilePackageCJS = async (packagePath = process.cwd()) => {
2071
+ let compileCommand = `yarn exec tsc -p tsconfig-cjs.json`;
2072
+ return (0, utils_js_1.execPromise)(compileCommand, false, false, { cwd: packagePath })
2073
+ .then((res) => {
2074
+ return res === '';
2075
+ })
2076
+ .catch((err) => {
2077
+ return {
2078
+ error: err.stdout,
2079
+ };
2080
+ });
2081
+ };
2082
+ exports.compilePackageCJS = compilePackageCJS;
2083
+ var publishUpdated = function (test = false) {
2084
+ let packages = getLocalLincdModules();
2085
+ var p = Promise.resolve('');
2086
+ let packagesLeft = packages.length;
2087
+ let results = [];
2088
+ log('Checking which packages need to be published by comparing last published date with last git commit');
2089
+ // p = Promise.all(packages.map((pckg) => {
2090
+ packages.forEach((pckg) => {
2091
+ p = p
2092
+ .then((previousResult) => {
2093
+ // progressUpdate(packagesLeft-- + ' packages left. Now checking ' + pckg.packageName);
2094
+ log('# Checking package ' + pckg.packageName);
2095
+ // log('# Requesting ' + 'yarn info '+pkg.packageName+' --json');
2096
+ // return execPromise('yarn info '+pkg.packageName+' --json').then((output:string) => {
2097
+ // console.log("Will be requesting npm view from this current working directory:\n"+process.cwd());
2098
+ // return execPromise('npm view '+pkg.packageName+' --json').then((output:string) => {
2099
+ let shouldPublish;
2100
+ var pack = (0, utils_js_1.getPackageJSON)(pckg.path);
2101
+ let version = getNextVersion(pack.version);
2102
+ if (pack.private) {
2103
+ shouldPublish = false;
2104
+ (0, utils_js_1.debugInfo)(chalk_1.default.blue('--> is private, skipping'));
2105
+ return chalk_1.default.gray(pckg.packageName + ' is private');
2106
+ // return previousResult + ' ' + chalk.gray(pckg.packageName + ' is private\n');
2107
+ }
2108
+ console.log('testing npm');
2109
+ return (0, utils_js_1.execPromise)('npm info ' + pckg.packageName + ' --json')
2110
+ .then(async (output) => {
2111
+ console.log('testing npm done');
2112
+ var info;
2113
+ try {
2114
+ if (output == '' || output.includes('E404')) {
2115
+ (0, utils_js_1.debugInfo)('Empty or 404 response from `npm info`. This package was probably not published before');
2116
+ // throw new Error('Empty response from `yarn info`. This pkg was probably not published before');
2117
+ // return;
2118
+ shouldPublish = true;
2119
+ //don't patch the version number (default, see above), use the current version
2120
+ version = pack.version;
2121
+ }
2122
+ else {
2123
+ info = JSON.parse(output);
2124
+ }
2125
+ if (info) {
2126
+ let lastPublish;
2127
+ //yarn:
2128
+ // let lastPublish = info.data.time[info.data.version];
2129
+ lastPublish = info.time[info.version];
2130
+ // }
2131
+ // catch (e) {
2132
+ // console.log(info);
2133
+ // console.error(chalk.red("Could not parse response from npm info. Format may have changed?"));
2134
+ // process.exit();
2135
+ // }
2136
+ let lastPublishDate = new Date(lastPublish);
2137
+ // let {lastModifiedTime, lastModifiedName, lastModified} = getLastModifiedSourceTime(pkg.path);
2138
+ let lastCommitInfo = await (0, utils_js_1.getLastCommitTime)(pckg.path);
2139
+ if (!lastCommitInfo) {
2140
+ shouldPublish = false;
2141
+ (0, utils_js_1.debugInfo)('Could not determine last git commit');
2142
+ // return previousResult + ' ' + chalk.red(pckg.packageName + ' - could not determine last commit\n');
2143
+ return chalk_1.default.red(pckg.packageName + ' - could not determine last commit');
2144
+ }
2145
+ else {
2146
+ //NOTE: removed lastModified, because switching branches will say that the file was modified and cause everything to publish
2147
+ //SO: now you NEED TO commit before it picks up that you should publish
2148
+ shouldPublish =
2149
+ lastPublishDate.getTime() < lastCommitInfo.date.getTime();
2150
+ //ignore changes to package.json if that's the only change, because when we publish the version number changes, which is then committed
2151
+ //(note there is always 2 lines for commit info + number of files changed)
2152
+ let changedFiles = lastCommitInfo.changes
2153
+ .split('\n')
2154
+ .filter((line) => line.includes('|'));
2155
+ let numberOfFilesChanges = changedFiles.length;
2156
+ // console.log("CHECK "+lastCommitInfo.changes.includes("package.json")+" - "+numberOfFilesChanges)
2157
+ if (shouldPublish &&
2158
+ lastCommitInfo.changes.includes('package.json') &&
2159
+ numberOfFilesChanges === 1) {
2160
+ shouldPublish = false;
2161
+ }
2162
+ if (shouldPublish) {
2163
+ log(chalk_1.default.magenta(pckg.packageName) +
2164
+ ' should be published because:');
2165
+ log(lastPublishDate.toDateString() +
2166
+ ' ' +
2167
+ lastPublishDate.toTimeString() +
2168
+ ' published ' +
2169
+ info.version);
2170
+ log(lastCommitInfo.date.toDateString() +
2171
+ ' ' +
2172
+ new Date(lastCommitInfo.date).toTimeString() +
2173
+ ' source last committed:');
2174
+ log(lastCommitInfo.changes);
2175
+ }
2176
+ }
2177
+ }
2178
+ }
2179
+ catch (err) {
2180
+ // var stats = fs.statSync(path.join(packageDirectory));
2181
+ // var files = fs.readdirSync(path.join(packageDirectory,'src'));
2182
+ console.log(chalk_1.default.red(pckg.packageName + ' failed: ' + err.message + '\n'));
2183
+ console.warn('Returned JSON from npm: ' + output);
2184
+ // return previousResult + ' ' + chalk.red(pckg.packageName + ' failed: ' + err.message + '\n');
2185
+ return chalk_1.default.red(pckg.packageName + ' failed: ' + err.message);
2186
+ }
2187
+ if (shouldPublish) {
2188
+ return (0, exports.publishPackage)(pckg, test, info, version);
2189
+ }
2190
+ return (chalk_1.default.blue(pckg.packageName) + ' latest version is up to date');
2191
+ })
2192
+ .catch(({ error, stdout, stderr }) => {
2193
+ if (error) {
2194
+ console.error(error.message);
2195
+ }
2196
+ if (stdout) {
2197
+ console.log(stderr);
2198
+ }
2199
+ if (stderr) {
2200
+ console.log(stderr);
2201
+ }
2202
+ // return previousResult + ' ' + chalk.red(pckg.packageName + ' failed\n');
2203
+ console.warn(chalk_1.default.red(pckg.packageName + ' failed'));
2204
+ return chalk_1.default.red(pckg.packageName + ' failed');
2205
+ });
2206
+ })
2207
+ .then((res) => {
2208
+ log(res);
2209
+ results.push(res);
2210
+ })
2211
+ .catch((err) => {
2212
+ console.warn(chalk_1.default.red(pckg.packageName + ' failed: ' + err.toString()));
2213
+ results.push(chalk_1.default.red(pckg.packageName + ' failed: ' + err.toString()));
2214
+ });
2215
+ });
2216
+ return p.then(() => {
2217
+ // if (messages == '')
2218
+ // {
2219
+ // console.log('All published packages are already up-to-date.');
2220
+ // }
2221
+ // else
2222
+ // {
2223
+ console.log('Summary: \n' + results.join('\n'));
2224
+ // }
2225
+ });
2226
+ };
2227
+ exports.publishUpdated = publishUpdated;
2228
+ async function getEnvJsonPath(relativeToPath = process.cwd()) {
2229
+ let path = '';
2230
+ if (!relativeToPath.endsWith('/')) {
2231
+ relativeToPath += '/';
2232
+ }
2233
+ // let path = './';
2234
+ for (let i = 0; i <= 10; i++) {
2235
+ let envFile = await (0, get_env_vars_js_1.getEnvFile)({
2236
+ filePath: relativeToPath + path + '.env.json',
2237
+ }).catch((err) => {
2238
+ return null;
2239
+ });
2240
+ if (envFile) {
2241
+ //note: we're getting the actual contents here, so we could also use that more directly?
2242
+ return path + '.env.json';
2243
+ }
2244
+ path += '../';
2245
+ }
2246
+ }
2247
+ var publishPackage = async function (pkg, test, info, publishVersion) {
2248
+ if (!pkg) {
2249
+ let localPackageJson = (0, utils_js_1.getPackageJSON)();
2250
+ pkg = {
2251
+ path: process.cwd(),
2252
+ packageName: localPackageJson.name,
2253
+ };
2254
+ }
2255
+ if (!publishVersion) {
2256
+ publishVersion = info ? getNextVersion(info.version) : 'patch';
2257
+ }
2258
+ if (test) {
2259
+ (0, utils_js_1.debugInfo)('should publish ' + pkg.packageName + ' ' + publishVersion);
2260
+ //when testing what needs to be published
2261
+ return chalk_1.default.blue(pkg.packageName + ' should publish');
2262
+ }
2263
+ console.log(chalk_1.default.blue('publishing ' + pkg.packageName + ' ' + publishVersion));
2264
+ //looking for an .env.json file in our workspace, which may store our NPM AUTH key
2265
+ let envJsonPath = await getEnvJsonPath(pkg.path);
2266
+ return (0, utils_js_1.execPromise)(`cd ${pkg.path} && ${envJsonPath ? `env-cmd -f ${envJsonPath} --use-shell "` : ''}yarn version ${publishVersion} && yarn npm publish${envJsonPath ? `"` : ''}`, true, false, {}, true)
2267
+ .then((res) => {
2268
+ if (res.indexOf('Aborted due to warnings') !== -1 ||
2269
+ res.indexOf('Could not publish') !== -1 ||
2270
+ res.indexOf("Couldn't publish") !== -1) {
2271
+ console.log(res);
2272
+ return chalk_1.default.red(pkg.packageName + ' failed\n');
2273
+ }
2274
+ console.log('Successfully published ' +
2275
+ chalk_1.default.green(pkg.path) +
2276
+ ' ' +
2277
+ chalk_1.default.magenta(publishVersion));
2278
+ return (chalk_1.default.green(pkg.packageName) +
2279
+ ' published ' +
2280
+ chalk_1.default.magenta(publishVersion));
2281
+ })
2282
+ .catch(({ error, stdout, stderr }) => {
2283
+ logError('Failed to publish: ' + error.message);
2284
+ return chalk_1.default.red(pkg.packageName + ' failed to publish');
2285
+ });
2286
+ };
2287
+ exports.publishPackage = publishPackage;
2288
+ var buildUpdated = async function (back, target, target2, useGitForLastModified = false, test = false) {
2289
+ // back = back || 1;
2290
+ // return execPromise(`git log -${back} --format=%ci`).then((result) => {
2291
+ // let now = new Date();
2292
+ let previousResult = '';
2293
+ log(test
2294
+ ? 'Checking which packages need to be rebuild'
2295
+ : 'Building updated packages');
2296
+ // let packages = getLocalLincdModules();
2297
+ let packages = getLocalLincdPackageMap();
2298
+ // console.log(packages);
2299
+ // let jsonldPkgUpdated = await needsRebuilding(
2300
+ // packages.get('lincd-jsonld'),
2301
+ // useGitForLastModified,
2302
+ // );
2303
+ // let cliPkgUpdated = await needsRebuilding(packages.get('lincd-cli'), useGitForLastModified);
2304
+ //if either cli or jsonldPkg needs to be rebuilt
2305
+ // if (jsonldPkgUpdated || cliPkgUpdated) {
2306
+ // if (jsonldPkgUpdated)
2307
+ // {
2308
+ // await execPromise(
2309
+ // 'yarn exec tsc && echo "compiled lincd-jsonld"',
2310
+ // false,
2311
+ // false,
2312
+ // {
2313
+ // cwd: packages.get('lincd-jsonld').path,
2314
+ // },
2315
+ // true,
2316
+ // );
2317
+ // // await execPromise('yarn build-core', false, false, {}, true);
2318
+ // }
2319
+ let rebuildAllModules = false;
2320
+ // if (cliPkgUpdated) {
2321
+ // rebuildAllModules = true;
2322
+ // log(chalk.magenta('Rebuilding all packages because the build tools (lincd-cli) got updated'));
2323
+ // }
2324
+ let packagesLeft = packages.size;
2325
+ runOnPackagesGroupedByDependencies(packages, (packageGroup, dependencies) => {
2326
+ (0, utils_js_1.debugInfo)('Now checking: ' + chalk_1.default.blue(packageGroup.map((i) => i.packageName)));
2327
+ (0, utils_js_1.debugInfo)(packagesLeft + ' packages left.');
2328
+ packagesLeft = packagesLeft - packageGroup.length;
2329
+ return async (pkg) => {
2330
+ // debugInfo('# Checking package ' + pkg.packageName);
2331
+ let needRebuild = await (0, utils_js_1.needsRebuilding)(pkg, useGitForLastModified);
2332
+ // if (pkg.packageName === 'lincd-jsonld' && jsonldPkgUpdated)
2333
+ // {
2334
+ // needRebuild = true;
2335
+ // }
2336
+ if (needRebuild || rebuildAllModules) {
2337
+ //TODO: when building a pkg, also rebuild all packages that depend on this package.. and iteratively build packages that depend on those packages..
2338
+ // log(packageName+' modified since last commit on '+now.toString());
2339
+ if (test) {
2340
+ (0, utils_js_1.debugInfo)('Need to build ' + pkg.packageName);
2341
+ return chalk_1.default.blue(pkg.packageName + ' should be build');
2342
+ }
2343
+ log('Building ' + pkg.packageName);
2344
+ const pathToBuild = pkg.path.startsWith('.')
2345
+ ? path_1.default.join(process.cwd(), pkg.path)
2346
+ : pkg.path;
2347
+ //if the path is relative,
2348
+ // log('path: ' + pathToBuild);
2349
+ return (0, exports.buildPackage)(null, null, pathToBuild, false)
2350
+ .then((res) => {
2351
+ //empty string or true is success
2352
+ //false is success with warnings
2353
+ //any other string is the build error text
2354
+ //undefined result means it failed
2355
+ if (typeof res === 'undefined' || typeof res === 'string') {
2356
+ logError('Failed to build ' + pkg.packageName + '. ' + res ? res : '');
2357
+ process.exit(1);
2358
+ }
2359
+ else {
2360
+ (0, utils_js_1.debugInfo)(chalk_1.default.green(pkg.packageName + ' successfully built'));
2361
+ return chalk_1.default.green(pkg.packageName + ' built');
2362
+ }
2363
+ })
2364
+ .catch((err) => {
2365
+ logError('Failed to build ' + pkg.packageName + '. ' + err.message);
2366
+ //console.error(err);
2367
+ process.exit(1);
2368
+ });
2369
+ }
2370
+ };
2371
+ }, (dependencies, results) => {
2372
+ if (results.length) {
2373
+ log(chalk_1.default.green('Changed packages have been rebuilt'));
2374
+ log('Summary:');
2375
+ log(results.join('\n'));
2376
+ }
2377
+ else {
2378
+ log(chalk_1.default.green('Nothing to rebuild'));
2379
+ }
2380
+ });
2381
+ return;
2382
+ };
2383
+ exports.buildUpdated = buildUpdated;
2384
+ const printBuildResults = function (failed, done) {
2385
+ if (done.size > 0 || done.length > 0) {
2386
+ log('Successfully built: ' +
2387
+ chalk_1.default.green([...done].map((m) => m.packageName).join(', ')) +
2388
+ '\n');
2389
+ }
2390
+ if (failed.length > 0) {
2391
+ warn('Failed to build: ' + chalk_1.default.red(failed.join(', ')) + '\n');
2392
+ }
2393
+ };
2394
+ var executeCommandForEachPackage = function (packages, command, filterMethod, filterValue) {
2395
+ //if a specific set of packages is given
2396
+ if (filterMethod == 'exclude') {
2397
+ //filter packages, so that we only execute on the packages as provided in the command
2398
+ log('Excluding ' + filterValue);
2399
+ filterValue = filterValue.split(',');
2400
+ packages = packages.filter((pkg) => filterValue.indexOf(pkg.packageName) === -1);
2401
+ }
2402
+ let startFrom;
2403
+ //by default start executing, unless 'from' is given
2404
+ let executing = true;
2405
+ //option to start from a specific pkg in the stack
2406
+ if (filterMethod == 'from') {
2407
+ startFrom = filterValue;
2408
+ if (startFrom) {
2409
+ console.log(chalk_1.default.blue('Will skip ahead to ' + startFrom));
2410
+ }
2411
+ let seen = false;
2412
+ packages = packages.filter((pkg) => {
2413
+ if (!seen && pkg.packageName.includes(startFrom)) {
2414
+ seen = true;
2415
+ }
2416
+ return seen;
2417
+ });
2418
+ }
2419
+ log("Executing '" +
2420
+ chalk_1.default.blueBright(command) +
2421
+ "' on packages " +
2422
+ chalk_1.default.magenta(packages.map((m) => m.packageName).join(', ')));
2423
+ var p = Promise.resolve(true);
2424
+ packages.forEach((pkg) => {
2425
+ p = p.then(() => {
2426
+ log('# Package ' + chalk_1.default.magenta(pkg.packageName));
2427
+ return (0, utils_js_1.execp)('cd ' + pkg.path + ' && ' + command);
2428
+ });
2429
+ });
2430
+ return p;
2431
+ };
2432
+ exports.executeCommandForEachPackage = executeCommandForEachPackage;
2433
+ var gitIgnore = function (...entries) {
2434
+ //add each entry to the .gitignore file
2435
+ let gitIgnorePath = path_1.default.resolve(process.cwd(), '.gitignore');
2436
+ (0, exports.addLinesToFile)(gitIgnorePath, entries);
2437
+ };
2438
+ var addLinesToFile = function (filePath, entries) {
2439
+ let fileContents = fs_extra_1.default.readFileSync(filePath, { encoding: 'utf8' });
2440
+ entries.forEach((entry) => {
2441
+ fileContents += '\n' + entry;
2442
+ });
2443
+ fs_extra_1.default.writeFileSync(filePath, fileContents);
2444
+ };
2445
+ exports.addLinesToFile = addLinesToFile;
2446
+ var addCapacitor = async function (basePath = process.cwd()) {
2447
+ let targetFolder = ensureFolderExists(basePath);
2448
+ log('Adding capacitor');
2449
+ fs_extra_1.default.copySync(path_1.default.join((0, exports.getScriptDir)(), '..', '..', 'defaults', 'app-static'), targetFolder);
2450
+ fs_extra_1.default.copySync(path_1.default.join((0, exports.getScriptDir)(), '..', '..', 'defaults', 'capacitor', 'scripts'), path_1.default.join(targetFolder, 'scripts'));
2451
+ //update .env-cmdrc.json file
2452
+ let envCmdPath = path_1.default.resolve(basePath, '.env-cmdrc.json');
2453
+ let envCmd = JSON.parse(fs_extra_1.default.readFileSync(envCmdPath, { encoding: 'utf8' }));
2454
+ envCmd['app-main'] = {
2455
+ APP_ENV: true,
2456
+ OUTPUT_PATH: './public/assets',
2457
+ ASSET_PATH: './assets/',
2458
+ ENTRY_PATH: './src/index-static.tsx',
2459
+ };
2460
+ envCmd['app-local-android'] = {
2461
+ NODE_ENV: 'app',
2462
+ SITE_ROOT: 'http://10.0.2.2:4000',
2463
+ };
2464
+ envCmd['app-local-ios'] = {
2465
+ NODE_ENV: 'app',
2466
+ SITE_ROOT: 'http://localhost:4000',
2467
+ };
2468
+ fs_extra_1.default.writeFile(envCmdPath, JSON.stringify(envCmd, null, 2));
2469
+ log('Edited .env-cmdrc.json');
2470
+ gitIgnore('android/app/build', 'android/**/capacitor.build.gradle', 'ios/App/App/public');
2471
+ //update package.json scripts
2472
+ let pack = (0, utils_js_1.getPackageJSON)(basePath);
2473
+ pack.scripts['build-staging'] =
2474
+ 'env-cmd -e _main, staging node scripts/build.js';
2475
+ pack.scripts['fix-app'] = 'node scripts/fix-namespace.js';
2476
+ pack.scripts['app'] =
2477
+ 'env-cmd -e _main,production,app-main node scripts/build.js && npx cap sync && yarn run fix-app';
2478
+ pack.scripts['app-local-ios'] =
2479
+ 'env-cmd -e _main,development,app-main,app-local-ios node scripts/build.js && npx cap sync && yarn run fix-app';
2480
+ pack.scripts['app-local-android'] =
2481
+ 'env-cmd -e _main,development,app-main,app-local-android node scripts/build.js && npx cap sync && yarn run fix-app';
2482
+ pack.scripts['cap:android'] = 'yarn cap open android';
2483
+ pack.scripts['cap:ios'] = 'yarn cap open ios';
2484
+ pack.scripts['cap:sync'] = 'yarn cap sync';
2485
+ fs_extra_1.default.writeFile(path_1.default.resolve(basePath, 'package.json'), JSON.stringify(pack, null, 2));
2486
+ log('Added new run script to package.json');
2487
+ await (0, utils_js_1.execPromise)(`yarn add -D @capacitor/cli`, true, false, null, true);
2488
+ await (0, utils_js_1.execPromise)(`yarn add @capacitor/android @capacitor/core @capacitor/app @capacitor/ios`, false, false, null, true);
2489
+ // TODO: Do we need to add `npx cap init`? If yes, we should not copy capacitor config.ts yet
2490
+ // await execPromise(`npx cap init`, true, false, null, true);
2491
+ // got error:
2492
+ // [error] Non-interactive shell detected.
2493
+ // Run the command with --help to see a list of arguments that must be provided.
2494
+ // [error] Non-interactive shell detected.
2495
+ // Run the command with --help to see a list of arguments that must be provided.
2496
+ log(`Done! Now update your Capacitor configuration by providing an app name, app ID, and web directory at ${chalk_1.default.blue('capacitor.config.ts')}`);
2497
+ log(`And then run ${chalk_1.default.magenta('yarn cap add android')} and/or ${chalk_1.default.magenta('yarn cap add ios')}')`);
2498
+ log(`Last, run ${chalk_1.default.magenta('yarn app')} or ${chalk_1.default.magenta('yarn app-local-ios')} or ${chalk_1.default.magenta('yarn app-local-android')}`);
2499
+ };
2500
+ exports.addCapacitor = addCapacitor;
2501
+ var executeCommandForPackage = function (packageName, command) {
2502
+ let packageDetails = getLincdPackages().find((modDetails) => modDetails.packageName.indexOf(packageName) !== -1 ||
2503
+ modDetails.packageName.indexOf(packageName) !== -1);
2504
+ if (packageDetails) {
2505
+ log("Executing 'cd " +
2506
+ packageDetails.path +
2507
+ ' && yarn lincd' +
2508
+ (command ? ' ' + command : '') +
2509
+ "'");
2510
+ (0, child_process_2.spawn)(process.platform === 'win32' ? 'yarn.cmd' : 'yarn', // Windows quirk
2511
+ ['lincd', command || null], {
2512
+ cwd: packageDetails.path,
2513
+ stdio: 'inherit',
2514
+ });
2515
+ }
2516
+ else {
2517
+ warn("Could not find a pkg who's name (partially) matched " +
2518
+ chalk_1.default.cyan(packageName));
2519
+ }
2520
+ };
2521
+ exports.executeCommandForPackage = executeCommandForPackage;
2522
+ /**
2523
+ * Function to remove files older than 10 seconds from the 'lib' folder.
2524
+ * @param {string} packagePath - The path to the package directory.
2525
+ */
2526
+ const removeOldFiles = async (packagePath) => {
2527
+ const libPath = path_1.default.join(packagePath, 'lib');
2528
+ try {
2529
+ // Read all files in the 'lib' folder asynchronously
2530
+ const files = await (0, glob_1.glob)(packagePath + '/lib/**/*.*');
2531
+ // Iterate through each file
2532
+ for (const file of files) {
2533
+ // const filePath = path.join(libPath, file);
2534
+ // Check if the file exists before attempting to delete it
2535
+ // if (await fs.pathExists(filePath)) {
2536
+ const stats = await fs_extra_1.default.stat(file);
2537
+ const currentTime = new Date().getTime();
2538
+ const lastModifiedTime = stats.mtime.getTime();
2539
+ // Check if the difference between the current time and last modified time is greater than 120 seconds
2540
+ if (currentTime - lastModifiedTime > 120000) {
2541
+ // Attempt to delete the file
2542
+ await fs_extra_1.default.unlink(file);
2543
+ // console.log(`Removed: ${file}`);
2544
+ }
2545
+ // }
2546
+ }
2547
+ return true;
2548
+ }
2549
+ catch (error) {
2550
+ console.error(`Error removing files: ${error.message}`);
2551
+ return false;
2552
+ }
2553
+ };
2554
+ exports.removeOldFiles = removeOldFiles;
2555
+ //# sourceMappingURL=cli-methods.js.map