@strapi/upgrade 5.8.1 → 5.10.0

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