@_linked/cli 1.8.1 → 1.9.0

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