@strapi/upgrade 5.9.0 → 5.10.1

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