@strapi/upgrade 0.0.0-next.bec3f8cddf61be32ee5516609a1d4d6032933972 → 0.0.0-next.c22d1aa5024dc77092c3df7e990ad89dcd79e7b0

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