@strapi/upgrade 0.0.0-experimental.d954d57341a6623992a0d211daaec8e245c3517d → 0.0.0-experimental.da0467de7eccc163e893e9b332505a79a5d52ec7

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 (50) hide show
  1. package/LICENSE +19 -4
  2. package/README.md +1 -1
  3. package/dist/chunks/logger-DGi224NW.js +1649 -0
  4. package/dist/chunks/logger-DGi224NW.js.map +1 -0
  5. package/dist/chunks/logger-np_r7rTc.mjs +1599 -0
  6. package/dist/chunks/logger-np_r7rTc.mjs.map +1 -0
  7. package/dist/cli.js +191 -1432
  8. package/dist/cli.js.map +1 -1
  9. package/dist/cli.mjs +211 -0
  10. package/dist/cli.mjs.map +1 -0
  11. package/dist/index.js +133 -1401
  12. package/dist/index.js.map +1 -1
  13. package/dist/index.mjs +130 -1393
  14. package/dist/index.mjs.map +1 -1
  15. package/dist/modules/codemod-repository/constants.d.ts.map +1 -1
  16. package/dist/modules/error/utils.d.ts +8 -0
  17. package/dist/modules/error/utils.d.ts.map +1 -1
  18. package/dist/modules/file-scanner/scanner.d.ts.map +1 -1
  19. package/dist/modules/format/formats.d.ts +2 -1
  20. package/dist/modules/format/formats.d.ts.map +1 -1
  21. package/dist/modules/project/constants.d.ts +6 -5
  22. package/dist/modules/project/constants.d.ts.map +1 -1
  23. package/dist/modules/project/project.d.ts +16 -2
  24. package/dist/modules/project/project.d.ts.map +1 -1
  25. package/dist/modules/project/types.d.ts +3 -0
  26. package/dist/modules/project/types.d.ts.map +1 -1
  27. package/dist/modules/runner/json/transform.d.ts.map +1 -1
  28. package/dist/modules/upgrader/types.d.ts +6 -0
  29. package/dist/modules/upgrader/types.d.ts.map +1 -1
  30. package/dist/modules/upgrader/upgrader.d.ts +4 -0
  31. package/dist/modules/upgrader/upgrader.d.ts.map +1 -1
  32. package/dist/modules/version/range.d.ts.map +1 -1
  33. package/dist/modules/version/types.d.ts +2 -1
  34. package/dist/modules/version/types.d.ts.map +1 -1
  35. package/dist/tasks/codemods/utils.d.ts.map +1 -1
  36. package/dist/tasks/upgrade/prompts/index.d.ts +2 -0
  37. package/dist/tasks/upgrade/prompts/index.d.ts.map +1 -0
  38. package/dist/tasks/upgrade/prompts/latest.d.ts +9 -0
  39. package/dist/tasks/upgrade/prompts/latest.d.ts.map +1 -0
  40. package/dist/tasks/upgrade/requirements/major.d.ts.map +1 -1
  41. package/dist/tasks/upgrade/upgrade.d.ts.map +1 -1
  42. package/package.json +13 -13
  43. package/resources/codemods/5.0.0/comment-out-lifecycle-files.code.ts +63 -0
  44. package/resources/codemods/5.0.0/dependency-upgrade-react-and-react-dom.json.ts +67 -0
  45. package/resources/codemods/5.0.0/dependency-upgrade-styled-components.json.ts +49 -0
  46. package/resources/codemods/5.0.0/deprecate-helper-plugin.code.ts +192 -0
  47. package/resources/codemods/5.0.0/sqlite3-to-better-sqlite3.json.ts +0 -1
  48. package/resources/codemods/5.1.0/dependency-better-sqlite3.json.ts +48 -0
  49. package/resources/utils/change-import.ts +118 -0
  50. package/resources/utils/replace-jsx.ts +49 -0
package/dist/index.js CHANGED
@@ -1,1429 +1,161 @@
1
- "use strict";
2
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const path$1 = require("node:path");
4
- const simpleGit = require("simple-git");
5
- const chalk = require("chalk");
6
- const semver = require("semver");
7
- const utils = require("@strapi/utils");
8
- const fp = require("lodash/fp");
9
- const fse = require("fs-extra");
10
- const assert = require("node:assert");
11
- const glob = require("glob");
12
- const Runner = require("jscodeshift/src/Runner");
13
- const node = require("esbuild-register/dist/node");
14
- const CliTable3 = require("cli-table3");
15
- const _interopDefault = (e) => e && e.__esModule ? e : { default: e };
16
- const path__default = /* @__PURE__ */ _interopDefault(path$1);
17
- const simpleGit__default = /* @__PURE__ */ _interopDefault(simpleGit);
18
- const chalk__default = /* @__PURE__ */ _interopDefault(chalk);
19
- const semver__default = /* @__PURE__ */ _interopDefault(semver);
20
- const fse__default = /* @__PURE__ */ _interopDefault(fse);
21
- const assert__default = /* @__PURE__ */ _interopDefault(assert);
22
- const CliTable3__default = /* @__PURE__ */ _interopDefault(CliTable3);
23
- class Requirement {
24
- isRequired;
25
- name;
26
- testCallback;
27
- children;
28
- constructor(name, testCallback, isRequired) {
29
- this.name = name;
30
- this.testCallback = testCallback;
31
- this.isRequired = isRequired ?? true;
32
- this.children = [];
33
- }
34
- setChildren(children) {
35
- this.children = children;
36
- return this;
37
- }
38
- addChild(child) {
39
- this.children.push(child);
40
- return this;
41
- }
42
- asOptional() {
43
- const newInstance = requirementFactory(this.name, this.testCallback, false);
44
- newInstance.setChildren(this.children);
45
- return newInstance;
46
- }
47
- asRequired() {
48
- const newInstance = requirementFactory(this.name, this.testCallback, true);
49
- newInstance.setChildren(this.children);
50
- return newInstance;
51
- }
52
- async test(context) {
53
- try {
54
- await this.testCallback?.(context);
55
- return ok();
56
- } catch (e) {
57
- if (e instanceof Error) {
58
- return errored(e);
59
- }
60
- if (typeof e === "string") {
61
- return errored(new Error(e));
62
- }
63
- return errored(new Error("Unknown error"));
64
- }
65
- }
66
- }
67
- const ok = () => ({ pass: true, error: null });
68
- const errored = (error) => ({ pass: false, error });
69
- const requirementFactory = (name, testCallback, isRequired) => new Requirement(name, testCallback, isRequired);
70
- const index$g = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
71
- __proto__: null,
72
- requirementFactory
73
- }, Symbol.toStringTag, { value: "Module" }));
74
- const REQUIRE_AVAILABLE_NEXT_MAJOR = requirementFactory(
75
- "REQUIRE_AVAILABLE_NEXT_MAJOR",
76
- (context) => {
77
- const { project, target } = context;
78
- const currentMajor = project.strapiVersion.major;
79
- const targetedMajor = target.major;
80
- if (targetedMajor === currentMajor) {
81
- throw new Error(`You're already on the latest major version (v${currentMajor})`);
82
- }
83
- }
84
- );
85
- const REQUIRE_LATEST_FOR_CURRENT_MAJOR = requirementFactory(
86
- "REQUIRE_LATEST_FOR_CURRENT_MAJOR",
87
- (context) => {
88
- const { project, target, npmVersionsMatches } = context;
89
- if (npmVersionsMatches.length !== 1) {
90
- const invalidVersions = npmVersionsMatches.slice(0, -1);
91
- const invalidVersionsAsSemVer = invalidVersions.map((v) => v.version);
92
- const nbInvalidVersions = npmVersionsMatches.length;
93
- const currentMajor = project.strapiVersion.major;
94
- throw new Error(
95
- `Doing a major upgrade requires to be on the latest v${currentMajor} version, but found ${nbInvalidVersions} versions between the current one and ${target}: ${invalidVersionsAsSemVer}`
96
- );
97
- }
98
- }
99
- );
100
- const REQUIRE_GIT_CLEAN_REPOSITORY = requirementFactory(
101
- "REQUIRE_GIT_CLEAN_REPOSITORY",
102
- async (context) => {
103
- const git = simpleGit__default.default({ baseDir: context.project.cwd });
104
- const status = await git.status();
105
- if (!status.isClean()) {
106
- throw new Error(
107
- "Repository is not clean. Please commit or stash any changes before upgrading"
108
- );
109
- }
110
- }
111
- );
112
- const REQUIRE_GIT_REPOSITORY = requirementFactory(
113
- "REQUIRE_GIT_REPOSITORY",
114
- async (context) => {
115
- const git = simpleGit__default.default({ baseDir: context.project.cwd });
116
- const isRepo = await git.checkIsRepo();
117
- if (!isRepo) {
118
- throw new Error("Not a git repository (or any of the parent directories)");
119
- }
120
- }
121
- ).addChild(REQUIRE_GIT_CLEAN_REPOSITORY.asOptional());
122
- const REQUIRE_GIT_INSTALLED = requirementFactory(
123
- "REQUIRE_GIT_INSTALLED",
124
- async (context) => {
125
- const git = simpleGit__default.default({ baseDir: context.project.cwd });
126
- try {
127
- await git.version();
128
- } catch {
129
- throw new Error("Git is not installed");
130
- }
131
- }
132
- ).addChild(REQUIRE_GIT_REPOSITORY.asOptional());
133
- const REQUIRE_GIT = requirementFactory("REQUIRE_GIT", null).addChild(
134
- REQUIRE_GIT_INSTALLED.asOptional()
135
- );
136
- class Timer {
137
- interval;
138
- constructor() {
139
- this.reset();
140
- }
141
- get elapsedMs() {
142
- const { start, end } = this.interval;
143
- return end ? end - start : Date.now() - start;
144
- }
145
- get end() {
146
- return this.interval.end;
147
- }
148
- get start() {
149
- return this.interval.start;
150
- }
151
- stop() {
152
- this.interval.end = Date.now();
153
- return this.elapsedMs;
154
- }
155
- reset() {
156
- this.interval = { start: Date.now(), end: null };
157
- return this;
158
- }
159
- }
160
- const timerFactory = () => new Timer();
161
- const ONE_SECOND_MS = 1e3;
162
- const constants$4 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
163
- __proto__: null,
164
- ONE_SECOND_MS
165
- }, Symbol.toStringTag, { value: "Module" }));
166
- const index$f = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
167
- __proto__: null,
168
- constants: constants$4,
169
- timerFactory
170
- }, Symbol.toStringTag, { value: "Module" }));
171
- class JSONTransformAPI {
172
- json;
173
- constructor(json) {
174
- this.json = fp.cloneDeep(json);
175
- }
176
- get(path2, defaultValue) {
177
- if (!path2) {
178
- return this.root();
179
- }
180
- return fp.cloneDeep(fp.get(path2, this.json) ?? defaultValue);
181
- }
182
- has(path2) {
183
- return fp.has(path2, this.json);
184
- }
185
- merge(other) {
186
- this.json = fp.merge(other, this.json);
187
- return this;
188
- }
189
- root() {
190
- return fp.cloneDeep(this.json);
191
- }
192
- set(path2, value) {
193
- this.json = fp.set(path2, value, this.json);
194
- return this;
195
- }
196
- remove(path2) {
197
- this.json = fp.omit(path2, this.json);
198
- return this;
199
- }
200
- }
201
- const createJSONTransformAPI = (object) => new JSONTransformAPI(object);
202
- const readJSON = async (path2) => {
203
- const buffer = await fse__default.default.readFile(path2);
204
- return JSON.parse(buffer.toString());
205
- };
206
- const saveJSON = async (path2, json) => {
207
- const jsonAsString = `${JSON.stringify(json, null, 2)}
208
- `;
209
- await fse__default.default.writeFile(path2, jsonAsString);
210
- };
211
- var ReleaseType = /* @__PURE__ */ ((ReleaseType2) => {
212
- ReleaseType2["Major"] = "major";
213
- ReleaseType2["Minor"] = "minor";
214
- ReleaseType2["Patch"] = "patch";
215
- return ReleaseType2;
216
- })(ReleaseType || {});
217
- const types = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
218
- __proto__: null,
219
- ReleaseType
220
- }, Symbol.toStringTag, { value: "Module" }));
221
- const semVerFactory = (version2) => {
222
- return new semver__default.default.SemVer(version2);
223
- };
224
- const isLiteralSemVer = (str) => {
225
- const tokens = str.split(".");
226
- return tokens.length === 3 && tokens.every((token) => !Number.isNaN(+token) && Number.isInteger(+token));
227
- };
228
- const isValidSemVer = (str) => semver__default.default.valid(str) !== null;
229
- const isSemverInstance = (value) => {
230
- return value instanceof semver__default.default.SemVer;
231
- };
232
- const isSemVerReleaseType = (str) => {
233
- return Object.values(ReleaseType).includes(str);
234
- };
235
- const rangeFactory = (range) => {
236
- return new semver__default.default.Range(range);
237
- };
238
- const rangeFromReleaseType = (current, identifier) => {
239
- switch (identifier) {
240
- case ReleaseType.Major: {
241
- const nextMajor = semver__default.default.inc(current, "major");
242
- return rangeFactory(`>${current.raw} <=${nextMajor}`);
243
- }
244
- case ReleaseType.Patch: {
245
- const minor = semver__default.default.inc(current, "minor");
246
- return rangeFactory(`>${current.raw} <${minor}`);
247
- }
248
- case ReleaseType.Minor: {
249
- const major = semver__default.default.inc(current, "major");
250
- return rangeFactory(`>${current.raw} <${major}`);
251
- }
252
- default: {
253
- throw new Error("Not implemented");
254
- }
255
- }
256
- };
257
- const rangeFromVersions = (currentVersion, target) => {
258
- if (isSemverInstance(target)) {
259
- return rangeFactory(`>${currentVersion.raw} <=${target.raw}`);
260
- }
261
- if (isSemVerReleaseType(target)) {
262
- return rangeFromReleaseType(currentVersion, target);
263
- }
264
- throw new Error(`Invalid target set: ${target}`);
265
- };
266
- const isValidStringifiedRange = (str) => semver__default.default.validRange(str) !== null;
267
- const isRangeInstance = (range) => {
268
- return range instanceof semver__default.default.Range;
269
- };
270
- const index$e = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
271
- __proto__: null,
272
- Version: types,
273
- isLiteralSemVer,
274
- isRangeInstance,
275
- isSemVerReleaseType,
276
- isSemverInstance,
277
- isValidSemVer,
278
- isValidStringifiedRange,
279
- rangeFactory,
280
- rangeFromReleaseType,
281
- rangeFromVersions,
282
- semVerFactory
283
- }, Symbol.toStringTag, { value: "Module" }));
284
- class FileScanner {
285
- cwd;
286
- constructor(cwd) {
287
- this.cwd = cwd;
288
- }
289
- scan(patterns) {
290
- const filenames = glob.glob.sync(patterns, { cwd: this.cwd });
291
- return filenames.map((filename) => path__default.default.join(this.cwd, filename));
292
- }
293
- }
294
- const fileScannerFactory = (cwd) => new FileScanner(cwd);
295
- const index$d = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
1
+ 'use strict';
2
+
3
+ var logger = require('./chunks/logger-DGi224NW.js');
4
+ require('semver');
5
+ require('node:path');
6
+ require('node:assert');
7
+ require('chalk');
8
+ require('@strapi/utils');
9
+ require('fs-extra');
10
+ require('fast-glob');
11
+ require('jscodeshift/src/Runner');
12
+ require('lodash/fp');
13
+ require('esbuild-register/dist/node');
14
+ require('simple-git');
15
+ require('cli-table3');
16
+
17
+ var index$g = /*#__PURE__*/Object.freeze({
18
+ __proto__: null,
19
+ constants: logger.constants,
20
+ timerFactory: logger.timerFactory
21
+ });
22
+
23
+ var index$f = /*#__PURE__*/Object.freeze({
24
+ __proto__: null,
25
+ codemodList: logger.codemodList,
26
+ codemodUID: logger.codemodUID,
27
+ durationMs: logger.durationMs,
28
+ highlight: logger.highlight,
29
+ path: logger.path,
30
+ projectDetails: logger.projectDetails,
31
+ projectType: logger.projectType,
32
+ reports: logger.reports,
33
+ transform: logger.transform,
34
+ upgradeStep: logger.upgradeStep,
35
+ version: logger.version,
36
+ versionRange: logger.versionRange
37
+ });
38
+
39
+ var index$e = /*#__PURE__*/Object.freeze({
40
+ __proto__: null,
41
+ Version: logger.types,
42
+ isLiteralSemVer: logger.isLiteralSemVer,
43
+ isRangeInstance: logger.isRangeInstance,
44
+ isSemVerReleaseType: logger.isSemVerReleaseType,
45
+ isSemverInstance: logger.isSemverInstance,
46
+ isValidSemVer: logger.isValidSemVer,
47
+ isValidStringifiedRange: logger.isValidStringifiedRange,
48
+ rangeFactory: logger.rangeFactory,
49
+ rangeFromReleaseType: logger.rangeFromReleaseType,
50
+ rangeFromVersions: logger.rangeFromVersions,
51
+ semVerFactory: logger.semVerFactory
52
+ });
53
+
54
+ var index$d = /*#__PURE__*/Object.freeze({
296
55
  __proto__: null,
297
- fileScannerFactory
298
- }, Symbol.toStringTag, { value: "Module" }));
299
- class AbstractRunner {
300
- paths;
301
- configuration;
302
- constructor(paths, configuration) {
303
- this.paths = paths;
304
- this.configuration = configuration;
305
- }
306
- async run(codemod, configuration) {
307
- const isValidCodemod = this.valid(codemod);
308
- if (!isValidCodemod) {
309
- throw new Error(`Invalid codemod provided to the runner: ${codemod.filename}`);
310
- }
311
- const runConfiguration = { ...this.configuration, ...configuration };
312
- return this.runner(codemod.path, this.paths, runConfiguration);
313
- }
314
- }
315
- class CodeRunner extends AbstractRunner {
316
- runner = Runner.run;
317
- valid(codemod) {
318
- return codemod.kind === "code";
319
- }
320
- }
321
- const codeRunnerFactory = (paths, configuration) => {
322
- return new CodeRunner(paths, configuration);
323
- };
324
- const index$c = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
56
+ fileScannerFactory: logger.fileScannerFactory
57
+ });
58
+
59
+ var index$c = /*#__PURE__*/Object.freeze({
325
60
  __proto__: null,
326
- codeRunnerFactory
327
- }, Symbol.toStringTag, { value: "Module" }));
328
- const transformJSON = async (codemodPath, paths, config) => {
329
- const { dry } = config;
330
- const startTime = process.hrtime();
331
- const report = {
332
- ok: 0,
333
- nochange: 0,
334
- skip: 0,
335
- error: 0,
336
- timeElapsed: "",
337
- stats: {}
338
- };
339
- const esbuildOptions = { extensions: [".js", ".mjs", ".ts"] };
340
- const { unregister } = node.register(esbuildOptions);
341
- const module2 = require(codemodPath);
342
- unregister();
343
- const codemod = typeof module2.default === "function" ? module2.default : module2;
344
- assert__default.default(typeof codemod === "function", `Codemod must be a function. Found ${typeof codemod}`);
345
- for (const path2 of paths) {
346
- try {
347
- const json = await readJSON(path2);
348
- assert__default.default(typeof json === "object" && !Array.isArray(json) && json !== null);
349
- const file = { path: path2, json };
350
- const params = { cwd: config.cwd, json: createJSONTransformAPI };
351
- const out = await codemod(file, params);
352
- if (out === void 0) {
353
- report.error += 1;
354
- } else if (!fp.isEqual(json, out)) {
355
- if (!dry) {
356
- await saveJSON(path2, out);
357
- }
358
- report.ok += 1;
359
- } else {
360
- report.nochange += 1;
361
- }
362
- } catch {
363
- report.error += 1;
364
- }
365
- }
366
- const endTime = process.hrtime(startTime);
367
- report.timeElapsed = (endTime[0] + endTime[1] / 1e9).toFixed(3);
368
- return report;
369
- };
370
- class JSONRunner extends AbstractRunner {
371
- runner = transformJSON;
372
- valid(codemod) {
373
- return codemod.kind === "json";
374
- }
375
- }
376
- const jsonRunnerFactory = (paths, configuration) => {
377
- return new JSONRunner(paths, configuration);
378
- };
379
- const index$b = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
61
+ codeRunnerFactory: logger.codeRunnerFactory
62
+ });
63
+
64
+ var index$b = /*#__PURE__*/Object.freeze({
380
65
  __proto__: null,
381
- jsonRunnerFactory
382
- }, Symbol.toStringTag, { value: "Module" }));
383
- const PROJECT_PACKAGE_JSON = "package.json";
384
- const PROJECT_DEFAULT_ALLOWED_ROOT_PATHS = ["src", "config", "public"];
385
- const PROJECT_DEFAULT_CODE_EXTENSIONS = [
386
- // Source files
387
- "js",
388
- "mjs",
389
- "ts",
390
- // React files
391
- "jsx",
392
- "tsx"
393
- ];
394
- const PROJECT_DEFAULT_JSON_EXTENSIONS = ["json"];
395
- const PROJECT_DEFAULT_ALLOWED_EXTENSIONS = [
396
- ...PROJECT_DEFAULT_CODE_EXTENSIONS,
397
- ...PROJECT_DEFAULT_JSON_EXTENSIONS
398
- ];
399
- const PROJECT_DEFAULT_PATTERNS = ["package.json"];
400
- const SCOPED_STRAPI_PACKAGE_PREFIX = "@strapi/";
401
- const STRAPI_DEPENDENCY_NAME = `${SCOPED_STRAPI_PACKAGE_PREFIX}strapi`;
402
- const constants$3 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
66
+ jsonRunnerFactory: logger.jsonRunnerFactory
67
+ });
68
+
69
+ var index$a = /*#__PURE__*/Object.freeze({
70
+ __proto__: null,
71
+ assertAppProject: logger.assertAppProject,
72
+ assertPluginProject: logger.assertPluginProject,
73
+ constants: logger.constants$1,
74
+ isApplicationProject: logger.isApplicationProject,
75
+ isPluginProject: logger.isPluginProject,
76
+ projectFactory: logger.projectFactory
77
+ });
78
+
79
+ var index$9 = /*#__PURE__*/Object.freeze({
403
80
  __proto__: null,
404
- PROJECT_DEFAULT_ALLOWED_EXTENSIONS,
405
- PROJECT_DEFAULT_ALLOWED_ROOT_PATHS,
406
- PROJECT_DEFAULT_CODE_EXTENSIONS,
407
- PROJECT_DEFAULT_JSON_EXTENSIONS,
408
- PROJECT_DEFAULT_PATTERNS,
409
- PROJECT_PACKAGE_JSON,
410
- SCOPED_STRAPI_PACKAGE_PREFIX,
411
- STRAPI_DEPENDENCY_NAME
412
- }, Symbol.toStringTag, { value: "Module" }));
413
- class Project {
414
- cwd;
415
- // The following properties are assigned during the .refresh() call in the constructor.
416
- files;
417
- packageJSONPath;
418
- packageJSON;
419
- constructor(cwd) {
420
- if (!fse__default.default.pathExistsSync(cwd)) {
421
- throw new Error(`ENOENT: no such file or directory, access '${cwd}'`);
422
- }
423
- this.cwd = cwd;
424
- this.refresh();
425
- }
426
- getFilesByExtensions(extensions) {
427
- return this.files.filter((filePath) => {
428
- const fileExtension = path__default.default.extname(filePath);
429
- return extensions.includes(fileExtension);
430
- });
431
- }
432
- refresh() {
433
- this.refreshPackageJSON();
434
- this.refreshProjectFiles();
435
- return this;
436
- }
437
- async runCodemods(codemods, options) {
438
- const runners = this.createProjectCodemodsRunners(options.dry);
439
- const reports2 = [];
440
- for (const codemod of codemods) {
441
- for (const runner of runners) {
442
- if (runner.valid(codemod)) {
443
- const report = await runner.run(codemod);
444
- reports2.push({ codemod, report });
445
- }
446
- }
447
- }
448
- return reports2;
449
- }
450
- createProjectCodemodsRunners(dry = false) {
451
- const jsonExtensions = PROJECT_DEFAULT_JSON_EXTENSIONS.map(
452
- (ext) => `.${ext}`
453
- );
454
- const codeExtensions = PROJECT_DEFAULT_CODE_EXTENSIONS.map(
455
- (ext) => `.${ext}`
456
- );
457
- const jsonFiles = this.getFilesByExtensions(jsonExtensions);
458
- const codeFiles = this.getFilesByExtensions(codeExtensions);
459
- const codeRunner = codeRunnerFactory(codeFiles, {
460
- dry,
461
- parser: "ts",
462
- runInBand: true,
463
- babel: true,
464
- extensions: PROJECT_DEFAULT_CODE_EXTENSIONS.join(","),
465
- // Don't output any log coming from the runner
466
- print: false,
467
- silent: true,
468
- verbose: 0
469
- });
470
- const jsonRunner = jsonRunnerFactory(jsonFiles, { dry, cwd: this.cwd });
471
- return [codeRunner, jsonRunner];
472
- }
473
- refreshPackageJSON() {
474
- const packageJSONPath = path__default.default.join(this.cwd, PROJECT_PACKAGE_JSON);
475
- try {
476
- fse__default.default.accessSync(packageJSONPath);
477
- } catch {
478
- throw new Error(`Could not find a ${PROJECT_PACKAGE_JSON} file in ${this.cwd}`);
479
- }
480
- const packageJSONBuffer = fse__default.default.readFileSync(packageJSONPath);
481
- this.packageJSONPath = packageJSONPath;
482
- this.packageJSON = JSON.parse(packageJSONBuffer.toString());
483
- }
484
- refreshProjectFiles() {
485
- const allowedRootPaths = formatGlobCollectionPattern(
486
- PROJECT_DEFAULT_ALLOWED_ROOT_PATHS
487
- );
488
- const allowedExtensions = formatGlobCollectionPattern(
489
- PROJECT_DEFAULT_ALLOWED_EXTENSIONS
490
- );
491
- const projectFilesPattern = `./${allowedRootPaths}/**/*.${allowedExtensions}`;
492
- const patterns = [projectFilesPattern, ...PROJECT_DEFAULT_PATTERNS];
493
- const scanner = fileScannerFactory(this.cwd);
494
- this.files = scanner.scan(patterns);
495
- }
496
- }
497
- class AppProject extends Project {
498
- strapiVersion;
499
- type = "application";
500
- constructor(cwd) {
501
- super(cwd);
502
- this.refreshStrapiVersion();
503
- }
504
- refresh() {
505
- super.refresh();
506
- this.refreshStrapiVersion();
507
- return this;
508
- }
509
- refreshStrapiVersion() {
510
- this.strapiVersion = // First try to get the strapi version from the package.json dependencies
511
- this.findStrapiVersionFromProjectPackageJSON() ?? // If the version found is not a valid SemVer, get the Strapi version from the installed package
512
- this.findLocallyInstalledStrapiVersion();
513
- }
514
- findStrapiVersionFromProjectPackageJSON() {
515
- const projectName = this.packageJSON.name;
516
- const version2 = this.packageJSON.dependencies?.[STRAPI_DEPENDENCY_NAME];
517
- if (version2 === void 0) {
518
- throw new Error(
519
- `No version of ${STRAPI_DEPENDENCY_NAME} was found in ${projectName}. Are you in a valid Strapi project?`
520
- );
521
- }
522
- const isValidSemVer2 = isLiteralSemVer(version2) && semver__default.default.valid(version2) === version2;
523
- return isValidSemVer2 ? semVerFactory(version2) : void 0;
524
- }
525
- findLocallyInstalledStrapiVersion() {
526
- const packageSearchText = `${STRAPI_DEPENDENCY_NAME}/package.json`;
527
- let strapiPackageJSONPath;
528
- let strapiPackageJSON;
529
- try {
530
- strapiPackageJSONPath = require.resolve(packageSearchText, { paths: [this.cwd] });
531
- strapiPackageJSON = require(strapiPackageJSONPath);
532
- assert__default.default(typeof strapiPackageJSON === "object");
533
- } catch {
534
- throw new Error(
535
- `Cannot resolve module "${STRAPI_DEPENDENCY_NAME}" from paths [${this.cwd}]`
536
- );
537
- }
538
- const strapiVersion = strapiPackageJSON.version;
539
- if (!isValidSemVer(strapiVersion)) {
540
- throw new Error(
541
- `Invalid ${STRAPI_DEPENDENCY_NAME} version found in ${strapiPackageJSONPath} (${strapiVersion})`
542
- );
543
- }
544
- return semVerFactory(strapiVersion);
545
- }
546
- }
547
- const formatGlobCollectionPattern = (collection) => {
548
- assert__default.default(
549
- collection.length > 0,
550
- "Invalid pattern provided, the given collection needs at least 1 element"
551
- );
552
- return collection.length === 1 ? collection[0] : `{${collection}}`;
553
- };
554
- class PluginProject extends Project {
555
- type = "plugin";
556
- }
557
- const isPlugin = (cwd) => {
558
- const packageJSONPath = path__default.default.join(cwd, PROJECT_PACKAGE_JSON);
559
- try {
560
- fse__default.default.accessSync(packageJSONPath);
561
- } catch {
562
- throw new Error(`Could not find a ${PROJECT_PACKAGE_JSON} file in ${cwd}`);
563
- }
564
- const packageJSONBuffer = fse__default.default.readFileSync(packageJSONPath);
565
- const packageJSON = JSON.parse(packageJSONBuffer.toString());
566
- return packageJSON?.strapi?.kind === "plugin";
567
- };
568
- const projectFactory = (cwd) => {
569
- fse__default.default.accessSync(cwd);
570
- if (isPlugin(cwd)) {
571
- return new PluginProject(cwd);
572
- }
573
- return new AppProject(cwd);
574
- };
575
- const isPluginProject = (project) => {
576
- return project instanceof PluginProject;
577
- };
578
- function assertPluginProject(project) {
579
- if (!isPluginProject(project)) {
580
- throw new Error("Project is not a plugin");
581
- }
582
- }
583
- const isApplicationProject = (project) => {
584
- return project instanceof AppProject;
585
- };
586
- function assertAppProject(project) {
587
- if (!isApplicationProject(project)) {
588
- throw new Error("Project is not an application");
589
- }
590
- }
591
- const index$a = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
81
+ AbortedError: logger.AbortedError,
82
+ NPMCandidateNotFoundError: logger.NPMCandidateNotFoundError,
83
+ UnexpectedError: logger.UnexpectedError,
84
+ unknownToError: logger.unknownToError
85
+ });
86
+
87
+ var index$8 = /*#__PURE__*/Object.freeze({
592
88
  __proto__: null,
593
- assertAppProject,
594
- assertPluginProject,
595
- constants: constants$3,
596
- isApplicationProject,
597
- isPluginProject,
598
- projectFactory
599
- }, Symbol.toStringTag, { value: "Module" }));
600
- class UnexpectedError extends Error {
601
- constructor() {
602
- super("Unexpected Error");
603
- }
604
- }
605
- const unknownToError = (e) => {
606
- if (e instanceof Error) {
607
- return e;
608
- }
609
- if (typeof e === "string") {
610
- return new Error(e);
611
- }
612
- return new UnexpectedError();
613
- };
614
- const index$9 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
89
+ codemodFactory: logger.codemodFactory,
90
+ constants: logger.constants$2
91
+ });
92
+
93
+ var index$7 = /*#__PURE__*/Object.freeze({
615
94
  __proto__: null,
616
- UnexpectedError,
617
- unknownToError
618
- }, Symbol.toStringTag, { value: "Module" }));
619
- const path = (path2) => chalk__default.default.blue(path2);
620
- const version = (version2) => {
621
- return chalk__default.default.italic.yellow(`v${version2}`);
622
- };
623
- const codemodUID = (uid) => {
624
- return chalk__default.default.bold.cyan(uid);
625
- };
626
- const projectType = (type) => chalk__default.default.cyan(type);
627
- const versionRange = (range) => chalk__default.default.italic.yellow(range.raw);
628
- const transform = (transformFilePath) => chalk__default.default.cyan(transformFilePath);
629
- const highlight = (arg) => chalk__default.default.bold.underline(arg);
630
- const upgradeStep = (text, step) => {
631
- return chalk__default.default.bold(`(${step[0]}/${step[1]}) ${text}...`);
632
- };
633
- const reports = (reports2) => {
634
- const rows = reports2.map(({ codemod, report }, i) => {
635
- const fIndex = chalk__default.default.grey(i);
636
- const fVersion = chalk__default.default.magenta(codemod.version);
637
- const fKind = chalk__default.default.yellow(codemod.kind);
638
- const fFormattedTransformPath = chalk__default.default.cyan(codemod.format());
639
- const fTimeElapsed = i === 0 ? `${report.timeElapsed}s ${chalk__default.default.dim.italic("(cold start)")}` : `${report.timeElapsed}s`;
640
- const fAffected = report.ok > 0 ? chalk__default.default.green(report.ok) : chalk__default.default.grey(0);
641
- const fUnchanged = report.ok === 0 ? chalk__default.default.red(report.nochange) : chalk__default.default.grey(report.nochange);
642
- return [fIndex, fVersion, fKind, fFormattedTransformPath, fAffected, fUnchanged, fTimeElapsed];
643
- });
644
- const table = new CliTable3__default.default({
645
- style: { compact: true },
646
- head: [
647
- chalk__default.default.bold.grey("N°"),
648
- chalk__default.default.bold.magenta("Version"),
649
- chalk__default.default.bold.yellow("Kind"),
650
- chalk__default.default.bold.cyan("Name"),
651
- chalk__default.default.bold.green("Affected"),
652
- chalk__default.default.bold.red("Unchanged"),
653
- chalk__default.default.bold.blue("Duration")
654
- ]
655
- });
656
- table.push(...rows);
657
- return table.toString();
658
- };
659
- const codemodList = (codemods) => {
660
- const rows = codemods.map((codemod, index2) => {
661
- const fIndex = chalk__default.default.grey(index2);
662
- const fVersion = chalk__default.default.magenta(codemod.version);
663
- const fKind = chalk__default.default.yellow(codemod.kind);
664
- const fName = chalk__default.default.blue(codemod.format());
665
- const fUID = codemodUID(codemod.uid);
666
- return [fIndex, fVersion, fKind, fName, fUID];
667
- });
668
- const table = new CliTable3__default.default({
669
- style: { compact: true },
670
- head: [
671
- chalk__default.default.bold.grey("N°"),
672
- chalk__default.default.bold.magenta("Version"),
673
- chalk__default.default.bold.yellow("Kind"),
674
- chalk__default.default.bold.blue("Name"),
675
- chalk__default.default.bold.cyan("UID")
676
- ]
677
- });
678
- table.push(...rows);
679
- return table.toString();
680
- };
681
- const durationMs = (elapsedMs) => {
682
- const elapsedSeconds = (elapsedMs / ONE_SECOND_MS).toFixed(3);
683
- return `${elapsedSeconds}s`;
684
- };
685
- const index$8 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
95
+ codemodRepositoryFactory: logger.codemodRepositoryFactory,
96
+ constants: logger.constants$3
97
+ });
98
+
99
+ var index$6 = /*#__PURE__*/Object.freeze({
686
100
  __proto__: null,
687
- codemodList,
688
- codemodUID,
689
- durationMs,
690
- highlight,
691
- path,
692
- projectType,
693
- reports,
694
- transform,
695
- upgradeStep,
696
- version,
697
- versionRange
698
- }, Symbol.toStringTag, { value: "Module" }));
699
- const CODEMOD_CODE_SUFFIX = "code";
700
- const CODEMOD_JSON_SUFFIX = "json";
701
- const CODEMOD_ALLOWED_SUFFIXES = [CODEMOD_CODE_SUFFIX, CODEMOD_JSON_SUFFIX];
702
- const CODEMOD_EXTENSION = "ts";
703
- const CODEMOD_FILE_REGEXP = new RegExp(
704
- `^.+[.](${CODEMOD_ALLOWED_SUFFIXES.join("|")})[.]${CODEMOD_EXTENSION}$`
705
- );
706
- const constants$2 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
101
+ constants: logger.constants$4,
102
+ upgraderFactory: logger.upgraderFactory
103
+ });
104
+
105
+ var index$5 = /*#__PURE__*/Object.freeze({
707
106
  __proto__: null,
708
- CODEMOD_ALLOWED_SUFFIXES,
709
- CODEMOD_CODE_SUFFIX,
710
- CODEMOD_EXTENSION,
711
- CODEMOD_FILE_REGEXP,
712
- CODEMOD_JSON_SUFFIX
713
- }, Symbol.toStringTag, { value: "Module" }));
714
- class Codemod {
715
- uid;
716
- kind;
717
- version;
718
- baseDirectory;
719
- filename;
720
- path;
721
- constructor(options) {
722
- this.kind = options.kind;
723
- this.version = options.version;
724
- this.baseDirectory = options.baseDirectory;
725
- this.filename = options.filename;
726
- this.path = path__default.default.join(this.baseDirectory, this.version.raw, this.filename);
727
- this.uid = this.createUID();
728
- }
729
- createUID() {
730
- const name = this.format({ stripExtension: true, stripKind: true, stripHyphens: false });
731
- const kind = this.kind;
732
- const version2 = this.version.raw;
733
- return `${version2}-${name}-${kind}`;
734
- }
735
- format(options) {
736
- const { stripExtension = true, stripKind = true, stripHyphens = true } = options ?? {};
737
- let formatted = this.filename;
738
- if (stripExtension) {
739
- formatted = formatted.replace(new RegExp(`\\.${CODEMOD_EXTENSION}$`, "i"), "");
740
- }
741
- if (stripKind) {
742
- formatted = formatted.replace(`.${CODEMOD_CODE_SUFFIX}`, "").replace(`.${CODEMOD_JSON_SUFFIX}`, "");
743
- }
744
- if (stripHyphens) {
745
- formatted = formatted.replaceAll("-", " ");
746
- }
747
- return formatted;
748
- }
749
- }
750
- const codemodFactory = (options) => new Codemod(options);
751
- const index$7 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
107
+ requirementFactory: logger.requirementFactory
108
+ });
109
+
110
+ var index$4 = /*#__PURE__*/Object.freeze({
752
111
  __proto__: null,
753
- codemodFactory,
754
- constants: constants$2
755
- }, Symbol.toStringTag, { value: "Module" }));
756
- const INTERNAL_CODEMODS_DIRECTORY = path__default.default.join(
757
- __dirname,
758
- // upgrade/dist
759
- "..",
760
- // upgrade
761
- "resources",
762
- // upgrade/resources
763
- "codemods"
764
- // upgrade/resources/codemods
765
- );
766
- const constants$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
112
+ listCodemods: logger.listCodemods,
113
+ runCodemods: logger.runCodemods,
114
+ upgrade: logger.upgrade
115
+ });
116
+
117
+ var index$3 = /*#__PURE__*/Object.freeze({
767
118
  __proto__: null,
768
- INTERNAL_CODEMODS_DIRECTORY
769
- }, Symbol.toStringTag, { value: "Module" }));
770
- class CodemodRepository {
771
- groups;
772
- versions;
773
- cwd;
774
- constructor(cwd) {
775
- assert__default.default(fse__default.default.existsSync(cwd), `Invalid codemods directory provided "${cwd}"`);
776
- this.cwd = cwd;
777
- this.groups = {};
778
- this.versions = [];
779
- }
780
- refresh() {
781
- this.refreshAvailableVersions();
782
- this.refreshAvailableFiles();
783
- return this;
784
- }
785
- count(version2) {
786
- return this.findByVersion(version2).length;
787
- }
788
- versionExists(version2) {
789
- return version2.raw in this.groups;
790
- }
791
- has(uid) {
792
- const result = this.find({ uids: [uid] });
793
- if (result.length !== 1) {
794
- return false;
795
- }
796
- const { codemods } = result[0];
797
- return codemods.length === 1 && codemods[0].uid === uid;
798
- }
799
- find(q) {
800
- const entries = Object.entries(this.groups);
801
- return entries.filter(maybeFilterByRange).map(([version2, codemods]) => ({
802
- version: semVerFactory(version2),
803
- // Filter by UID if provided in the query
804
- codemods: codemods.filter(maybeFilterByUIDs)
805
- })).filter(({ codemods }) => codemods.length > 0);
806
- function maybeFilterByRange([version2]) {
807
- if (!isRangeInstance(q.range)) {
808
- return true;
809
- }
810
- return q.range.test(version2);
811
- }
812
- function maybeFilterByUIDs(codemod) {
813
- if (q.uids === void 0) {
814
- return true;
815
- }
816
- return q.uids.includes(codemod.uid);
817
- }
818
- }
819
- findByVersion(version2) {
820
- const literalVersion = version2.raw;
821
- const codemods = this.groups[literalVersion];
822
- return codemods ?? [];
823
- }
824
- findAll() {
825
- const entries = Object.entries(this.groups);
826
- return entries.map(([version2, codemods]) => ({
827
- version: semVerFactory(version2),
828
- codemods
829
- }));
830
- }
831
- refreshAvailableVersions() {
832
- this.versions = fse__default.default.readdirSync(this.cwd).filter((filename) => fse__default.default.statSync(path__default.default.join(this.cwd, filename)).isDirectory()).filter((filename) => semver__default.default.valid(filename) !== null).map((version2) => semVerFactory(version2)).sort(semver__default.default.compare);
833
- return this;
834
- }
835
- refreshAvailableFiles() {
836
- this.groups = {};
837
- for (const version2 of this.versions) {
838
- this.refreshAvailableFilesForVersion(version2);
839
- }
840
- }
841
- refreshAvailableFilesForVersion(version2) {
842
- const literalVersion = version2.raw;
843
- const versionDirectory = path__default.default.join(this.cwd, literalVersion);
844
- if (!fse__default.default.existsSync(versionDirectory)) {
845
- return;
846
- }
847
- this.groups[literalVersion] = fse__default.default.readdirSync(versionDirectory).filter((filename) => fse__default.default.statSync(path__default.default.join(versionDirectory, filename)).isFile()).filter((filename) => CODEMOD_FILE_REGEXP.test(filename)).map((filename) => {
848
- const kind = parseCodemodKindFromFilename(filename);
849
- const baseDirectory = this.cwd;
850
- return codemodFactory({ kind, baseDirectory, version: version2, filename });
119
+ loggerFactory: logger.loggerFactory
120
+ });
121
+
122
+ const codemodReportFactory = (codemod, report)=>({
123
+ codemod,
124
+ report
851
125
  });
852
- }
853
- }
854
- const parseCodemodKindFromFilename = (filename) => {
855
- const kind = filename.split(".").at(-2);
856
- assert__default.default(kind !== void 0);
857
- assert__default.default(CODEMOD_ALLOWED_SUFFIXES.includes(kind));
858
- return kind;
859
- };
860
- const codemodRepositoryFactory = (cwd = INTERNAL_CODEMODS_DIRECTORY) => {
861
- return new CodemodRepository(cwd);
862
- };
863
- const index$6 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
864
- __proto__: null,
865
- codemodRepositoryFactory,
866
- constants: constants$1
867
- }, Symbol.toStringTag, { value: "Module" }));
868
- class CodemodRunner {
869
- project;
870
- range;
871
- isDry;
872
- logger;
873
- selectCodemodsCallback;
874
- constructor(project, range) {
875
- this.project = project;
876
- this.range = range;
877
- this.isDry = false;
878
- this.logger = null;
879
- this.selectCodemodsCallback = null;
880
- }
881
- setRange(range) {
882
- this.range = range;
883
- return this;
884
- }
885
- setLogger(logger) {
886
- this.logger = logger;
887
- return this;
888
- }
889
- onSelectCodemods(callback) {
890
- this.selectCodemodsCallback = callback;
891
- return this;
892
- }
893
- dry(enabled = true) {
894
- this.isDry = enabled;
895
- return this;
896
- }
897
- createRepository(codemodsDirectory) {
898
- const repository = codemodRepositoryFactory(
899
- codemodsDirectory ?? INTERNAL_CODEMODS_DIRECTORY
900
- );
901
- repository.refresh();
902
- return repository;
903
- }
904
- async safeRunAndReport(codemods) {
905
- if (this.isDry) {
906
- this.logger?.warn?.(
907
- "Running the codemods in dry mode. No files will be modified during the process."
908
- );
909
- }
910
- try {
911
- const reports$1 = await this.project.runCodemods(codemods, { dry: this.isDry });
912
- this.logger?.raw?.(reports(reports$1));
913
- if (!this.isDry) {
914
- const nbAffectedTotal = reports$1.flatMap((report) => report.report.ok).reduce((acc, nb) => acc + nb, 0);
915
- this.logger?.debug?.(
916
- `Successfully ran ${highlight(codemods.length)} codemod(s), ${highlight(nbAffectedTotal)} change(s) have been detected`
917
- );
918
- }
919
- return successReport$1();
920
- } catch (e) {
921
- return erroredReport$1(unknownToError(e));
922
- }
923
- }
924
- async runByUID(uid, codemodsDirectory) {
925
- const repository = this.createRepository(codemodsDirectory);
926
- if (!repository.has(uid)) {
927
- throw new Error(`Unknown codemod UID provided: ${uid}`);
928
- }
929
- const codemods = repository.find({ uids: [uid] }).flatMap(({ codemods: codemods2 }) => codemods2);
930
- return this.safeRunAndReport(codemods);
931
- }
932
- async run(codemodsDirectory) {
933
- const repository = this.createRepository(codemodsDirectory);
934
- const codemodsInRange = repository.find({ range: this.range });
935
- const selectedCodemods = this.selectCodemodsCallback ? await this.selectCodemodsCallback(codemodsInRange) : codemodsInRange;
936
- if (selectedCodemods.length === 0) {
937
- this.logger?.debug?.(`Found no codemods to run for ${versionRange(this.range)}`);
938
- return successReport$1();
939
- }
940
- const codemods = selectedCodemods.flatMap(({ codemods: codemods2 }) => codemods2);
941
- const codemodsByVersion = fp.groupBy("version", codemods);
942
- const fRange = versionRange(this.range);
943
- this.logger?.debug?.(
944
- `Found ${highlight(codemods.length)} codemods for ${highlight(fp.size(codemodsByVersion))} version(s) using ${fRange}`
945
- );
946
- for (const [version$1, codemods2] of Object.entries(codemodsByVersion)) {
947
- this.logger?.debug?.(`- ${version(semVerFactory(version$1))} (${codemods2.length})`);
948
- }
949
- return this.safeRunAndReport(codemods);
950
- }
951
- }
952
- const codemodRunnerFactory = (project, range) => {
953
- return new CodemodRunner(project, range);
954
- };
955
- const successReport$1 = () => ({ success: true, error: null });
956
- const erroredReport$1 = (error) => ({ success: false, error });
957
- class Upgrader {
958
- project;
959
- npmPackage;
960
- target;
961
- codemodsTarget;
962
- isDry;
963
- logger;
964
- requirements;
965
- confirmationCallback;
966
- constructor(project, target, npmPackage) {
967
- this.project = project;
968
- this.npmPackage = npmPackage;
969
- this.target = target;
970
- this.syncCodemodsTarget();
971
- this.isDry = false;
972
- this.requirements = [];
973
- this.logger = null;
974
- this.confirmationCallback = null;
975
- }
976
- setRequirements(requirements) {
977
- this.requirements = requirements;
978
- return this;
979
- }
980
- setTarget(target) {
981
- this.target = target;
982
- return this;
983
- }
984
- syncCodemodsTarget() {
985
- this.codemodsTarget = semVerFactory(
986
- `${this.target.major}.${this.target.minor}.${this.target.patch}`
987
- );
988
- this.logger?.debug?.(
989
- `The codemods target has been synced with the upgrade target. The codemod runner will now look for ${version(
990
- this.codemodsTarget
991
- )}`
992
- );
993
- return this;
994
- }
995
- overrideCodemodsTarget(target) {
996
- this.codemodsTarget = target;
997
- this.logger?.debug?.(
998
- `Overriding the codemods target. The codemod runner will now look for ${version(target)}`
999
- );
1000
- return this;
1001
- }
1002
- setLogger(logger) {
1003
- this.logger = logger;
1004
- return this;
1005
- }
1006
- onConfirm(callback) {
1007
- this.confirmationCallback = callback;
1008
- return this;
1009
- }
1010
- dry(enabled = true) {
1011
- this.isDry = enabled;
1012
- return this;
1013
- }
1014
- addRequirement(requirement) {
1015
- this.requirements.push(requirement);
1016
- const fRequired = requirement.isRequired ? "(required)" : "(optional)";
1017
- this.logger?.debug?.(
1018
- `Added a new requirement to the upgrade: ${highlight(requirement.name)} ${fRequired}`
1019
- );
1020
- return this;
1021
- }
1022
- async upgrade() {
1023
- this.logger?.info?.(
1024
- `Upgrading from ${version(this.project.strapiVersion)} to ${version(this.target)}`
1025
- );
1026
- if (this.isDry) {
1027
- this.logger?.warn?.(
1028
- "Running the upgrade in dry mode. No files will be modified during the process."
1029
- );
1030
- }
1031
- const range = rangeFromVersions(this.project.strapiVersion, this.target);
1032
- const codemodsRange = rangeFromVersions(this.project.strapiVersion, this.codemodsTarget);
1033
- const npmVersionsMatches = this.npmPackage?.findVersionsInRange(range) ?? [];
1034
- this.logger?.debug?.(
1035
- `Found ${highlight(npmVersionsMatches.length)} versions satisfying ${versionRange(range)}`
1036
- );
1037
- try {
1038
- this.logger?.info?.(upgradeStep("Checking requirement", [1, 4]));
1039
- await this.checkRequirements(this.requirements, {
1040
- npmVersionsMatches,
1041
- project: this.project,
1042
- target: this.target
1043
- });
1044
- this.logger?.info?.(upgradeStep("Applying the latest code modifications", [2, 4]));
1045
- await this.runCodemods(codemodsRange);
1046
- this.logger?.debug?.("Refreshing project information...");
1047
- this.project.refresh();
1048
- this.logger?.info?.(upgradeStep("Upgrading Strapi dependencies", [3, 4]));
1049
- await this.updateDependencies();
1050
- this.logger?.info?.(upgradeStep("Installing dependencies", [4, 4]));
1051
- await this.installDependencies();
1052
- } catch (e) {
1053
- return erroredReport(unknownToError(e));
1054
- }
1055
- return successReport();
1056
- }
1057
- async checkRequirements(requirements, context) {
1058
- for (const requirement of requirements) {
1059
- const { pass, error } = await requirement.test(context);
1060
- if (pass) {
1061
- await this.onSuccessfulRequirement(requirement, context);
1062
- } else {
1063
- await this.onFailedRequirement(requirement, error);
1064
- }
1065
- }
1066
- }
1067
- async onSuccessfulRequirement(requirement, context) {
1068
- const hasChildren = requirement.children.length > 0;
1069
- if (hasChildren) {
1070
- await this.checkRequirements(requirement.children, context);
1071
- }
1072
- }
1073
- async onFailedRequirement(requirement, originalError) {
1074
- const errorMessage = `Requirement failed: ${originalError.message} (${highlight(
1075
- requirement.name
1076
- )})`;
1077
- const warningMessage = originalError.message;
1078
- const confirmationMessage = `Ignore optional requirement "${highlight(requirement.name)}" ?`;
1079
- const error = new Error(errorMessage);
1080
- if (requirement.isRequired) {
1081
- throw error;
1082
- }
1083
- this.logger?.warn?.(warningMessage);
1084
- const response = await this.confirmationCallback?.(confirmationMessage);
1085
- if (!response) {
1086
- throw error;
1087
- }
1088
- }
1089
- async updateDependencies() {
1090
- const { packageJSON, packageJSONPath } = this.project;
1091
- const json = createJSONTransformAPI(packageJSON);
1092
- const dependencies = json.get("dependencies", {});
1093
- const strapiDependencies = this.getScopedStrapiDependencies(dependencies);
1094
- this.logger?.debug?.(
1095
- `Found ${highlight(strapiDependencies.length)} dependency(ies) to update`
1096
- );
1097
- strapiDependencies.forEach(
1098
- (dependency) => this.logger?.debug?.(`- ${dependency[0]} (${dependency[1]} -> ${this.target})`)
1099
- );
1100
- if (strapiDependencies.length === 0) {
1101
- return;
1102
- }
1103
- strapiDependencies.forEach(([name]) => json.set(`dependencies.${name}`, this.target.raw));
1104
- const updatedPackageJSON = json.root();
1105
- if (this.isDry) {
1106
- this.logger?.debug?.(`Skipping dependencies update (${chalk__default.default.italic("dry mode")})`);
1107
- return;
1108
- }
1109
- await saveJSON(packageJSONPath, updatedPackageJSON);
1110
- }
1111
- getScopedStrapiDependencies(dependencies) {
1112
- const { strapiVersion } = this.project;
1113
- const strapiDependencies = [];
1114
- for (const [name, version2] of Object.entries(dependencies)) {
1115
- const isScopedStrapiPackage = name.startsWith(SCOPED_STRAPI_PACKAGE_PREFIX);
1116
- const isOnCurrentStrapiVersion = isValidSemVer(version2) && version2 === strapiVersion.raw;
1117
- if (isScopedStrapiPackage && isOnCurrentStrapiVersion) {
1118
- strapiDependencies.push([name, semVerFactory(version2)]);
1119
- }
1120
- }
1121
- return strapiDependencies;
1122
- }
1123
- async installDependencies() {
1124
- const projectPath = this.project.cwd;
1125
- const packageManagerName = await utils.packageManager.getPreferred(projectPath);
1126
- this.logger?.debug?.(`Using ${highlight(packageManagerName)} as package manager`);
1127
- if (this.isDry) {
1128
- this.logger?.debug?.(`Skipping dependencies installation (${chalk__default.default.italic("dry mode")}`);
1129
- return;
1130
- }
1131
- await utils.packageManager.installDependencies(projectPath, packageManagerName, {
1132
- stdout: this.logger?.stdout,
1133
- stderr: this.logger?.stderr
126
+ const reportFactory = (report)=>({
127
+ ...report
1134
128
  });
1135
- }
1136
- async runCodemods(range) {
1137
- const codemodRunner = codemodRunnerFactory(this.project, range);
1138
- codemodRunner.dry(this.isDry);
1139
- if (this.logger) {
1140
- codemodRunner.setLogger(this.logger);
1141
- }
1142
- await codemodRunner.run();
1143
- }
1144
- }
1145
- const resolveNPMTarget = (project, target, npmPackage) => {
1146
- if (isSemverInstance(target)) {
1147
- return npmPackage.findVersion(target);
1148
- }
1149
- if (isSemVerReleaseType(target)) {
1150
- const range = rangeFromVersions(project.strapiVersion, target);
1151
- const npmVersionsMatches = npmPackage.findVersionsInRange(range);
1152
- return npmVersionsMatches.at(-1);
1153
- }
1154
- return void 0;
1155
- };
1156
- const upgraderFactory = (project, target, npmPackage) => {
1157
- const targetedNPMVersion = resolveNPMTarget(project, target, npmPackage);
1158
- if (!targetedNPMVersion) {
1159
- throw new Error(`Couldn't find a matching version in the NPM registry for "${target}"`);
1160
- }
1161
- const semverTarget = semVerFactory(targetedNPMVersion.version);
1162
- if (semver__default.default.eq(semverTarget, project.strapiVersion)) {
1163
- throw new Error(`The project is already on ${version(semverTarget)}`);
1164
- }
1165
- return new Upgrader(project, semverTarget, npmPackage);
1166
- };
1167
- const successReport = () => ({ success: true, error: null });
1168
- const erroredReport = (error) => ({ success: false, error });
1169
- const STRAPI_PACKAGE_NAME = "@strapi/strapi";
1170
- const constants = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
1171
- __proto__: null,
1172
- STRAPI_PACKAGE_NAME
1173
- }, Symbol.toStringTag, { value: "Module" }));
1174
- const index$5 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
1175
- __proto__: null,
1176
- constants,
1177
- upgraderFactory
1178
- }, Symbol.toStringTag, { value: "Module" }));
1179
- const NPM_REGISTRY_URL = "https://registry.npmjs.org";
1180
- class Package {
1181
- name;
1182
- packageURL;
1183
- npmPackage;
1184
- constructor(name) {
1185
- this.name = name;
1186
- this.packageURL = `${NPM_REGISTRY_URL}/${name}`;
1187
- this.npmPackage = null;
1188
- }
1189
- get isLoaded() {
1190
- return this.npmPackage !== null;
1191
- }
1192
- assertPackageIsLoaded(npmPackage) {
1193
- assert__default.default(this.isLoaded, "The package is not loaded yet");
1194
- }
1195
- getVersionsDict() {
1196
- this.assertPackageIsLoaded(this.npmPackage);
1197
- return this.npmPackage.versions;
1198
- }
1199
- getVersionsAsList() {
1200
- this.assertPackageIsLoaded(this.npmPackage);
1201
- return Object.values(this.npmPackage.versions);
1202
- }
1203
- findVersionsInRange(range) {
1204
- const versions = this.getVersionsAsList();
1205
- return versions.filter((v) => range.test(v.version)).filter((v) => isLiteralSemVer(v.version)).sort((v1, v2) => semver__default.default.compare(v1.version, v2.version));
1206
- }
1207
- findVersion(version2) {
1208
- const versions = this.getVersionsAsList();
1209
- return versions.find((npmVersion) => semver__default.default.eq(npmVersion.version, version2));
1210
- }
1211
- async refresh() {
1212
- const response = await fetch(this.packageURL);
1213
- assert__default.default(response.ok, `Request failed for ${this.packageURL}`);
1214
- this.npmPackage = await response.json();
1215
- return this;
1216
- }
1217
- versionExists(version2) {
1218
- return this.findVersion(version2) !== void 0;
1219
- }
1220
- }
1221
- const npmPackageFactory = (name) => new Package(name);
1222
- const upgrade = async (options) => {
1223
- const timer = timerFactory();
1224
- const { logger, codemodsTarget } = options;
1225
- const cwd = path__default.default.resolve(options.cwd ?? process.cwd());
1226
- const project = projectFactory(cwd);
1227
- if (!isApplicationProject(project)) {
1228
- throw new Error(
1229
- `The "${options.target}" upgrade can only be run on a Strapi project; for plugins, please use "codemods".`
1230
- );
1231
- }
1232
- const npmPackage = npmPackageFactory(STRAPI_PACKAGE_NAME);
1233
- await npmPackage.refresh();
1234
- const upgrader = upgraderFactory(project, options.target, npmPackage).dry(options.dry ?? false).onConfirm(options.confirm ?? null).setLogger(logger);
1235
- if (codemodsTarget !== void 0) {
1236
- upgrader.overrideCodemodsTarget(codemodsTarget);
1237
- }
1238
- if (options.target === ReleaseType.Major) {
1239
- upgrader.addRequirement(REQUIRE_AVAILABLE_NEXT_MAJOR).addRequirement(REQUIRE_LATEST_FOR_CURRENT_MAJOR);
1240
- }
1241
- upgrader.addRequirement(REQUIRE_GIT.asOptional());
1242
- const upgradeReport = await upgrader.upgrade();
1243
- if (!upgradeReport.success) {
1244
- throw upgradeReport.error;
1245
- }
1246
- timer.stop();
1247
- logger.info(`Completed in ${durationMs(timer.elapsedMs)}`);
1248
- };
1249
- const resolvePath = (cwd) => path__default.default.resolve(cwd ?? process.cwd());
1250
- const getRangeFromTarget = (currentVersion, target) => {
1251
- if (isSemverInstance(target)) {
1252
- return rangeFactory(target);
1253
- }
1254
- const { major, minor, patch } = currentVersion;
1255
- switch (target) {
1256
- case ReleaseType.Major:
1257
- return rangeFactory(`${major}`);
1258
- case ReleaseType.Minor:
1259
- return rangeFactory(`${major}.${minor}`);
1260
- case ReleaseType.Patch:
1261
- return rangeFactory(`${major}.${minor}.${patch}`);
1262
- default:
1263
- throw new Error(`Invalid target set: ${target}`);
1264
- }
1265
- };
1266
- const findRangeFromTarget = (project, target) => {
1267
- if (isRangeInstance(target)) {
1268
- return target;
1269
- }
1270
- if (isApplicationProject(project)) {
1271
- return getRangeFromTarget(project.strapiVersion, target);
1272
- }
1273
- return rangeFactory("*");
1274
- };
1275
- const runCodemods = async (options) => {
1276
- const timer = timerFactory();
1277
- const { logger, uid } = options;
1278
- const cwd = resolvePath(options.cwd);
1279
- const project = projectFactory(cwd);
1280
- const range = findRangeFromTarget(project, options.target);
1281
- logger.debug(`Project: ${projectType(project.type)} found in ${path(cwd)}`);
1282
- logger.debug(`Range: set to ${versionRange(range)}`);
1283
- const codemodRunner = codemodRunnerFactory(project, range).dry(options.dry ?? false).onSelectCodemods(options.selectCodemods ?? null).setLogger(logger);
1284
- let report;
1285
- if (uid !== void 0) {
1286
- logger.debug(`Running a single codemod: ${codemodUID(uid)}`);
1287
- report = await codemodRunner.runByUID(uid);
1288
- } else {
1289
- report = await codemodRunner.run();
1290
- }
1291
- if (!report.success) {
1292
- throw report.error;
1293
- }
1294
- timer.stop();
1295
- logger.info(`Completed in ${timer.elapsedMs}`);
1296
- };
1297
- const listCodemods = async (options) => {
1298
- const { logger, target } = options;
1299
- const cwd = resolvePath(options.cwd);
1300
- const project = projectFactory(cwd);
1301
- const range = findRangeFromTarget(project, target);
1302
- logger.debug(`Project: ${projectType(project.type)} found in ${path(cwd)}`);
1303
- logger.debug(`Range: set to ${versionRange(range)}`);
1304
- const repo = codemodRepositoryFactory();
1305
- repo.refresh();
1306
- const groups = repo.find({ range });
1307
- const codemods = groups.flatMap((collection) => collection.codemods);
1308
- logger.debug(`Found ${highlight(codemods.length)} codemods`);
1309
- if (codemods.length === 0) {
1310
- logger.info(`Found no codemods matching ${versionRange(range)}`);
1311
- return;
1312
- }
1313
- const fCodemods = codemodList(codemods);
1314
- logger.raw(fCodemods);
1315
- };
1316
- const index$4 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
1317
- __proto__: null,
1318
- listCodemods,
1319
- runCodemods,
1320
- upgrade
1321
- }, Symbol.toStringTag, { value: "Module" }));
1322
- class Logger {
1323
- isDebug;
1324
- isSilent;
1325
- nbErrorsCalls;
1326
- nbWarningsCalls;
1327
- constructor(options = {}) {
1328
- this.isDebug = options.debug ?? false;
1329
- this.isSilent = options.silent ?? false;
1330
- this.nbErrorsCalls = 0;
1331
- this.nbWarningsCalls = 0;
1332
- }
1333
- get isNotSilent() {
1334
- return !this.isSilent;
1335
- }
1336
- get errors() {
1337
- return this.nbErrorsCalls;
1338
- }
1339
- get warnings() {
1340
- return this.nbWarningsCalls;
1341
- }
1342
- get stdout() {
1343
- return this.isSilent ? void 0 : process.stdout;
1344
- }
1345
- get stderr() {
1346
- return this.isSilent ? void 0 : process.stderr;
1347
- }
1348
- setDebug(debug) {
1349
- this.isDebug = debug;
1350
- return this;
1351
- }
1352
- setSilent(silent) {
1353
- this.isSilent = silent;
1354
- return this;
1355
- }
1356
- debug(...args) {
1357
- const isDebugEnabled = this.isNotSilent && this.isDebug;
1358
- if (isDebugEnabled) {
1359
- console.log(chalk__default.default.cyan(`[DEBUG] [${nowAsISO()}]`), ...args);
1360
- }
1361
- return this;
1362
- }
1363
- error(...args) {
1364
- this.nbErrorsCalls += 1;
1365
- if (this.isNotSilent) {
1366
- console.error(chalk__default.default.red(`[ERROR] [${nowAsISO()}]`), ...args);
1367
- }
1368
- return this;
1369
- }
1370
- info(...args) {
1371
- if (this.isNotSilent) {
1372
- console.info(chalk__default.default.blue(`[INFO] [${(/* @__PURE__ */ new Date()).toISOString()}]`), ...args);
1373
- }
1374
- return this;
1375
- }
1376
- raw(...args) {
1377
- if (this.isNotSilent) {
1378
- console.log(...args);
1379
- }
1380
- return this;
1381
- }
1382
- warn(...args) {
1383
- this.nbWarningsCalls += 1;
1384
- if (this.isNotSilent) {
1385
- console.warn(chalk__default.default.yellow(`[WARN] [${(/* @__PURE__ */ new Date()).toISOString()}]`), ...args);
1386
- }
1387
- return this;
1388
- }
1389
- }
1390
- const nowAsISO = () => (/* @__PURE__ */ new Date()).toISOString();
1391
- const loggerFactory = (options = {}) => new Logger(options);
1392
- const index$3 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
129
+
130
+ var index$2 = /*#__PURE__*/Object.freeze({
1393
131
  __proto__: null,
1394
- loggerFactory
1395
- }, Symbol.toStringTag, { value: "Module" }));
1396
- const codemodReportFactory = (codemod, report) => ({
1397
- codemod,
1398
- report
132
+ codemodReportFactory: codemodReportFactory,
133
+ reportFactory: reportFactory
1399
134
  });
1400
- const reportFactory = (report) => ({ ...report });
1401
- const index$2 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
1402
- __proto__: null,
1403
- codemodReportFactory,
1404
- reportFactory
1405
- }, Symbol.toStringTag, { value: "Module" }));
1406
- const index$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
135
+
136
+ var index$1 = /*#__PURE__*/Object.freeze({
1407
137
  __proto__: null,
1408
138
  code: index$c,
1409
139
  json: index$b
1410
- }, Symbol.toStringTag, { value: "Module" }));
1411
- const index = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
140
+ });
141
+
142
+ var index = /*#__PURE__*/Object.freeze({
1412
143
  __proto__: null,
1413
- codemod: index$7,
1414
- codemodRepository: index$6,
144
+ codemod: index$8,
145
+ codemodRepository: index$7,
1415
146
  error: index$9,
1416
- f: index$8,
147
+ f: index$f,
1417
148
  fileScanner: index$d,
1418
149
  logger: index$3,
1419
150
  project: index$a,
1420
151
  report: index$2,
1421
- requirement: index$g,
152
+ requirement: index$5,
1422
153
  runner: index$1,
1423
- timer: index$f,
1424
- upgrader: index$5,
154
+ timer: index$g,
155
+ upgrader: index$6,
1425
156
  version: index$e
1426
- }, Symbol.toStringTag, { value: "Module" }));
157
+ });
158
+
1427
159
  exports.modules = index;
1428
160
  exports.tasks = index$4;
1429
161
  //# sourceMappingURL=index.js.map