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