@sanity/plugin-kit 6.0.3 → 6.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/dist/constants.js +12 -0
  2. package/dist/constants.js.map +1 -0
  3. package/dist/index.js +72 -4
  4. package/dist/index.js.map +1 -1
  5. package/dist/init.js +866 -0
  6. package/dist/init.js.map +1 -0
  7. package/dist/init2.js +99 -0
  8. package/dist/init2.js.map +1 -0
  9. package/dist/{_chunks-es/inject.js → inject.js} +22 -16
  10. package/dist/inject.js.map +1 -0
  11. package/dist/link-watch.js +93 -0
  12. package/dist/link-watch.js.map +1 -0
  13. package/dist/load-package-config.js +31 -0
  14. package/dist/load-package-config.js.map +1 -0
  15. package/dist/log.js +31 -0
  16. package/dist/log.js.map +1 -0
  17. package/dist/package.js +908 -0
  18. package/dist/package.js.map +1 -0
  19. package/dist/package2.js +4 -0
  20. package/dist/package2.js.map +1 -0
  21. package/dist/verify-common.js +145 -0
  22. package/dist/verify-common.js.map +1 -0
  23. package/dist/verify-package.js +89 -0
  24. package/dist/verify-package.js.map +1 -0
  25. package/dist/verify-studio.js +65 -0
  26. package/dist/verify-studio.js.map +1 -0
  27. package/dist/version.js +54 -0
  28. package/dist/version.js.map +1 -0
  29. package/package.json +8 -7
  30. package/dist/_chunks-es/index.js +0 -125
  31. package/dist/_chunks-es/index.js.map +0 -1
  32. package/dist/_chunks-es/init.js +0 -85
  33. package/dist/_chunks-es/init.js.map +0 -1
  34. package/dist/_chunks-es/init2.js +0 -839
  35. package/dist/_chunks-es/init2.js.map +0 -1
  36. package/dist/_chunks-es/inject.js.map +0 -1
  37. package/dist/_chunks-es/link-watch.js +0 -91
  38. package/dist/_chunks-es/link-watch.js.map +0 -1
  39. package/dist/_chunks-es/load-package-config.js +0 -22
  40. package/dist/_chunks-es/load-package-config.js.map +0 -1
  41. package/dist/_chunks-es/package.js +0 -1066
  42. package/dist/_chunks-es/package.js.map +0 -1
  43. package/dist/_chunks-es/package2.js +0 -9
  44. package/dist/_chunks-es/package2.js.map +0 -1
  45. package/dist/_chunks-es/verify-common.js +0 -169
  46. package/dist/_chunks-es/verify-common.js.map +0 -1
  47. package/dist/_chunks-es/verify-package.js +0 -95
  48. package/dist/_chunks-es/verify-package.js.map +0 -1
  49. package/dist/_chunks-es/verify-studio.js +0 -61
  50. package/dist/_chunks-es/verify-studio.js.map +0 -1
  51. package/dist/_chunks-es/version.js +0 -50
  52. package/dist/_chunks-es/version.js.map +0 -1
@@ -1,1066 +0,0 @@
1
- import fs from "fs";
2
- import path from "path";
3
- import util from "util";
4
- import githubUrlToObject from "github-url-to-object";
5
- import validateNpmPackageName from "validate-npm-package-name";
6
- import { createRequire } from "node:module";
7
- import chalk from "chalk";
8
- import outdent from "outdent";
9
- import { log, urls, minPkgUtilsMajor, requiredNodeEngine, incompatiblePluginPackage, cliName } from "./index.js";
10
- import crypto from "crypto";
11
- import json5 from "json5";
12
- import pAny from "p-any";
13
- import { URL } from "url";
14
- import inquirer from "inquirer";
15
- import { pkg } from "./package2.js";
16
- import { getLatestVersion } from "get-latest-version";
17
- import pProps from "p-props";
18
- const mergedPackages = [
19
- "@sanity/base",
20
- "@sanity/core",
21
- "@sanity/types",
22
- "@sanity/data-aspects",
23
- "@sanity/default-layout",
24
- "@sanity/default-login",
25
- "@sanity/desk-tool",
26
- "@sanity/field",
27
- "@sanity/form-builder",
28
- "@sanity/initial-value-templates",
29
- "@sanity/language-filter",
30
- "@sanity/production-preview",
31
- "@sanity/react-hooks",
32
- "@sanity/resolver",
33
- "@sanity/state-router",
34
- "@sanity/structure",
35
- "@sanity/studio-hints"
36
- ].sort(), deprecatedDevDeps = [
37
- "tsdx",
38
- "sanipack",
39
- "parcel",
40
- "@parcel/packager-ts",
41
- "@parcel/transformer-typescript-types"
42
- ], buildExtensions = [".js", ".jsx", ".es6", ".es", ".mjs", ".ts", ".tsx"];
43
- async function prompt(message, options) {
44
- const type = options.choices ? "list" : options.type, result = await inquirer.prompt([{ ...options, type, message, name: "single" }]);
45
- return result && result.single;
46
- }
47
- prompt.separator = () => new inquirer.Separator();
48
- function promptForPackageName({ basePath }, defaultVal) {
49
- return prompt("Plugin name (sanity-plugin-...)", {
50
- default: defaultVal || path.basename(basePath),
51
- filter: (name) => {
52
- const prefixless = name.trim().replace(/^sanity-plugin-/, "");
53
- return name[0] === "@" ? name : `sanity-plugin-${prefixless}`;
54
- },
55
- validate: (name) => {
56
- const valid = validateNpmPackageName(name);
57
- return valid.errors ? valid.errors[0] : name[0] !== "@" && name.endsWith("plugin") ? `Name shouldn't include "plugin" multiple times (${name})` : !0;
58
- }
59
- });
60
- }
61
- function promptForRepoOrigin(_options, defaultVal) {
62
- return prompt("Git repository URL", {
63
- default: defaultVal,
64
- filter: (raw) => {
65
- const url = (raw || "").trim(), gh = githubUrlToObject(url);
66
- return gh ? `git+ssh://git@github.com/${gh.user}/${gh.repo}.git` : url;
67
- },
68
- validate: (url) => {
69
- if (!url)
70
- return !0;
71
- try {
72
- return new URL(url) ? !0 : "Invalid URL";
73
- } catch {
74
- return "Invalid URL";
75
- }
76
- }
77
- });
78
- }
79
- const stat$1 = util.promisify(fs.stat), mkdir = util.promisify(fs.mkdir), readdir = util.promisify(fs.readdir), copyFile = util.promisify(fs.copyFile), readFile$2 = util.promisify(fs.readFile), writeFile = util.promisify(fs.writeFile);
80
- function hasSourceEquivalent(compiledFile, paths) {
81
- if (!paths.source)
82
- return fileExists(
83
- path.isAbsolute(compiledFile) ? compiledFile : path.resolve(paths.basePath, compiledFile)
84
- );
85
- const baseDir = path.dirname(compiledFile.replace(paths.compiled, paths.source)), baseName = path.basename(compiledFile, path.extname(compiledFile)), pathStub = path.join(baseDir, baseName);
86
- return buildCandidateExists(pathStub);
87
- }
88
- async function hasSourceFile(filePath, paths) {
89
- if (!paths?.source)
90
- return fileExists(
91
- path.isAbsolute(filePath) ? filePath : path.resolve(paths?.basePath ?? "", filePath)
92
- );
93
- const pathStub = path.isAbsolute(filePath) ? filePath : path.resolve(paths.source, filePath);
94
- return await fileExists(pathStub) ? !0 : buildCandidateExists(pathStub);
95
- }
96
- function hasCompiledFile(filePath, paths) {
97
- if (!paths?.compiled)
98
- return fileExists(
99
- path.isAbsolute(filePath) ? filePath : path.resolve(paths?.basePath ?? "", filePath)
100
- );
101
- const absPath = path.isAbsolute(filePath) ? filePath : path.resolve(paths.compiled, filePath), withExt = path.extname(absPath) === "" ? `${absPath}.js` : absPath;
102
- return fileExists(withExt);
103
- }
104
- function buildCandidateExists(pathStub) {
105
- const candidates = buildExtensions.map((extCandidate) => `${pathStub}${extCandidate}`);
106
- return pAny(candidates.map((candidate) => stat$1(candidate))).then(() => !0).catch(() => !1);
107
- }
108
- function fileExists(filePath) {
109
- return stat$1(filePath).then(() => !0).catch(() => !1);
110
- }
111
- async function readJsonFile(filePath) {
112
- const content = await readFile$2(filePath, "utf8");
113
- return JSON.parse(content);
114
- }
115
- function writeJsonFile(filePath, content) {
116
- const data = JSON.stringify(content, null, 2) + `
117
- `;
118
- return writeFile(filePath, data, { encoding: "utf8" });
119
- }
120
- async function writeFileWithOverwritePrompt(filePath, content, options) {
121
- const { default: defaultVal, force = !1, ...writeOptions } = options, printablePath = filePath.startsWith(process.cwd()) ? path.relative(process.cwd(), filePath) : filePath;
122
- return await fileEqualsData(filePath, content) || !force && await fileExists(filePath) && !await prompt(`File "${printablePath}" already exists. Overwrite?`, {
123
- type: "confirm",
124
- default: defaultVal
125
- }) ? !1 : (await writeFile(filePath, content, writeOptions), !0);
126
- }
127
- async function copyFileWithOverwritePrompt(from, to, flags) {
128
- const printablePath = to.startsWith(process.cwd()) ? path.relative(process.cwd(), to) : to;
129
- return await filesAreEqual(from, to) || (await ensureDirectoryExists(to), !flags.force && await fileExists(to) && !await prompt(`File "${printablePath}" already exists. Overwrite?`, {
130
- type: "confirm",
131
- default: !1
132
- })) ? !1 : (await copyFile(from, to), !0);
133
- }
134
- async function ensureDirectoryExists(filePath) {
135
- const dirname = path.dirname(filePath);
136
- await fileExists(dirname) || (await ensureDirectoryExists(dirname), await mkdir(dirname));
137
- }
138
- async function fileEqualsData(filePath, content) {
139
- const contentHash = crypto.createHash("sha1").update(content).digest("hex"), remoteHash = await getFileHash(filePath);
140
- return contentHash === remoteHash;
141
- }
142
- async function filesAreEqual(file1, file2) {
143
- const [hash1, hash2] = await Promise.all([getFileHash(file1, !1), getFileHash(file2)]);
144
- return hash1 === hash2;
145
- }
146
- function getFileHash(filePath, allowMissing = !0) {
147
- return new Promise((resolve, reject) => {
148
- const hash = crypto.createHash("sha1"), stream = fs.createReadStream(filePath);
149
- stream.on("error", (err) => {
150
- err.code === "ENOENT" && allowMissing ? resolve(null) : reject(err);
151
- }), stream.on("end", () => resolve(hash.digest("hex"))), stream.on("data", (chunk) => hash.update(chunk));
152
- });
153
- }
154
- async function ensureDir(dirPath) {
155
- try {
156
- await mkdir(dirPath);
157
- } catch (err) {
158
- if (err.code !== "EEXIST")
159
- throw err;
160
- }
161
- }
162
- async function isEmptyish(dirPath) {
163
- const ignoredFiles = [".git", ".gitignore", "license", "readme.md"];
164
- return (await readdir(dirPath).catch(() => [])).filter((file) => !ignoredFiles.includes(file.toLowerCase())).length === 0;
165
- }
166
- async function readFileContent({
167
- filename,
168
- basePath
169
- }) {
170
- const filepath = path.normalize(path.join(basePath, filename));
171
- try {
172
- return await readFile$2(filepath, "utf8");
173
- } catch (err) {
174
- if (err.code === "ENOENT") {
175
- log.debug(`No ${filename} file found.`);
176
- return;
177
- }
178
- throw new Error(`Failed to read "${filepath}": ${err.message}`);
179
- }
180
- }
181
- async function readJson5File({
182
- filename,
183
- basePath
184
- }) {
185
- const content = await readFileContent({ filename, basePath });
186
- if (content)
187
- return parseJson5(content, filename);
188
- }
189
- function parseJson5(content, errorKey) {
190
- try {
191
- return json5.parse(content);
192
- } catch (err) {
193
- throw new Error(`Error parsing "${errorKey}": ${err.message}`);
194
- }
195
- }
196
- const expectedScripts = {
197
- build: "plugin-kit verify-package --silent && pkg-utils build --strict --check --clean",
198
- watch: "pkg-utils watch --strict",
199
- "link-watch": "plugin-kit link-watch",
200
- prepublishOnly: "npm run build"
201
- };
202
- function filesWithSuffixes(fileBases, suffixes) {
203
- return fileBases.flatMap((file) => suffixes.map((suffix) => `${file}.${suffix}`));
204
- }
205
- function validateNodeEngine(packageJson) {
206
- return packageJson.engines?.node !== requiredNodeEngine ? [
207
- outdent`
208
- Expected package.json to contain engines.node: "${requiredNodeEngine}" to match @sanity/pkg-utils,
209
- but it was: ${packageJson.engines?.node}
210
-
211
- Please add the following to package.json:
212
-
213
- "engines": {
214
- "node": "${requiredNodeEngine}"
215
- }`.trimStart()
216
- ] : [];
217
- }
218
- function validateScripts(packageJson) {
219
- const errors = [], divergentScripts = Object.entries(expectedScripts).filter(([key, expectedCommand]) => {
220
- const command = packageJson.scripts?.[key];
221
- return !command || !command.includes(expectedCommand);
222
- });
223
- return divergentScripts.length && errors.push(
224
- outdent`
225
- The following script commands did not contain expected defaults: ${divergentScripts.map(([key]) => key).join(", ")}
226
-
227
- This checks for that the commands-strings includes these terms.
228
-
229
- Please add the following to your package.json "scripts":
230
-
231
- ${divergentScripts.map(([key, value]) => `"${key}": "${value}"`).join(`,
232
- `)}
233
- `.trimStart()
234
- ), errors;
235
- }
236
- async function validateTsConfig(ts, options) {
237
- const { basePath, outDir, tsconfig } = options, errors = [], wrongEntries = Object.entries({
238
- target: "esnext",
239
- jsx: "preserve",
240
- module: "preserve",
241
- rootDir: ".",
242
- outDir,
243
- noEmit: !0
244
- }).filter(([key, value]) => {
245
- let option = ts.options[key];
246
- return key === "rootDir" && typeof option == "string" && (option = path.relative(basePath, option) || "."), key === "outDir" && typeof option == "string" && (option = path.relative(basePath, option) || "."), key === "target" && option === 99 && (option = "esnext"), key === "module" && option === 200 && (option = "preserve"), key === "jsx" && option === 1 && (option = "preserve"), typeof value == "string" && typeof option == "string" ? value.toLowerCase() !== option?.toLowerCase() : value !== option;
247
- });
248
- if (wrongEntries.length) {
249
- const expectedOutput = wrongEntries.map(([key, value]) => `"${key}": ${typeof value == "string" ? `"${value}"` : value},`).join(`
250
- `);
251
- errors.push(
252
- outdent`
253
- Recommended ${tsconfig} compilerOptions missing:
254
-
255
- The following fields had unexpected values: [${wrongEntries.map(([key]) => key).join(", ")}]
256
- Expected to find these values:
257
- ${expectedOutput}
258
-
259
- Please update your ${tsconfig} accordingly.
260
- `.trimStart()
261
- );
262
- }
263
- return errors;
264
- }
265
- function validatePackageType({ type }) {
266
- return type === "module" ? [] : [
267
- outdent`
268
- package.json must set "type": "module" — plugins built with @sanity/plugin-kit are ESM-only.
269
- Found: ${type ? `"type": "${type}"` : 'no "type" field (defaults to "commonjs")'}
270
-
271
- Please add the following to package.json:
272
-
273
- "type": "module"
274
- `.trimStart()
275
- ];
276
- }
277
- function findRequireConditions(node, pathSegments) {
278
- if (Array.isArray(node))
279
- return node.flatMap(
280
- (entry, index) => findRequireConditions(entry, [...pathSegments, String(index)])
281
- );
282
- if (!node || typeof node != "object")
283
- return [];
284
- const found = [];
285
- for (const [key, value] of Object.entries(node))
286
- key === "require" && found.push(formatExportsPath(pathSegments)), found.push(...findRequireConditions(value, [...pathSegments, key]));
287
- return found;
288
- }
289
- function formatExportsPath(segments) {
290
- return `exports${segments.map((segment) => `[${JSON.stringify(segment)}]`).join("")}`;
291
- }
292
- function validateEsmOnly(packageJson) {
293
- const offenders = [];
294
- typeof packageJson.main < "u" && offenders.push(`- the top-level "main" field (${JSON.stringify(packageJson.main)})`), typeof packageJson.module < "u" && offenders.push(`- the top-level "module" field (${JSON.stringify(packageJson.module)})`);
295
- const requireConditions = [...new Set(findRequireConditions(packageJson.exports, []))];
296
- for (const conditionPath of requireConditions)
297
- offenders.push(`- a "require" export condition at ${conditionPath}`);
298
- return offenders.length ? [
299
- outdent`
300
- package.json ships CommonJS (CJS) output, but Sanity plugins target Sanity Studio v5+, which is pure ESM.
301
-
302
- Remove the following so the package stays ESM-only:
303
- ${offenders.join(`
304
- `)}
305
-
306
- Supporting CJS is not worth it:
307
- - It can have unintended side-effects.
308
- - The Node.js versions plugin-kit supports (${requiredNodeEngine}) fully support require(esm), so a
309
- consumer that still uses require() loads the ESM build directly — which is far more predictable.
310
- - Publishing a single format guarantees two copies of the plugin's code (ESM + CJS) can't both end up
311
- in the module tree, bloating bundles and slowing down builds.
312
-
313
- Rely on "exports" together with "type": "module", and drop "main", "module" and any "require" conditions.
314
- `.trimStart()
315
- ] : [];
316
- }
317
- function validatePkgUtilsDependency({ devDependencies }) {
318
- return devDependencies?.["@sanity/pkg-utils"] ? [] : [
319
- outdent`
320
- package.json does not list @sanity/pkg-utils as a devDependency.
321
- @sanity/pkg-utils replaced parcel as the recommended build tool in @sanity/plugin-kit 2.0.0
322
-
323
- Please add it by running 'npm install --save-dev @sanity/pkg-utils'.
324
- `.trimStart()
325
- ];
326
- }
327
- function validatePkgUtilsVersion({ basePath }) {
328
- const require2 = createRequire(path.join(basePath, "package.json"));
329
- let installedVersion;
330
- try {
331
- installedVersion = require2("@sanity/pkg-utils/package.json").version;
332
- } catch {
333
- return [
334
- outdent`
335
- @sanity/pkg-utils is not installed.
336
- plugin-kit loads package.config.ts through @sanity/pkg-utils (a peer dependency).
337
-
338
- Please install it by running 'npm install --save-dev @sanity/pkg-utils'.
339
- `.trimStart()
340
- ];
341
- }
342
- const major = Number.parseInt(installedVersion?.split(".")[0] ?? "", 10);
343
- return !Number.isFinite(major) || major < minPkgUtilsMajor ? [
344
- outdent`
345
- @sanity/pkg-utils ${installedVersion} is too old.
346
- plugin-kit requires @sanity/pkg-utils >=${minPkgUtilsMajor} to load package.config.ts.
347
-
348
- Please upgrade it by running 'npm install --save-dev @sanity/pkg-utils@latest'.
349
- `.trimStart()
350
- ] : [];
351
- }
352
- function validateSanityDependencies(packageJson) {
353
- const { dependencies, devDependencies, peerDependencies } = packageJson, allDependencies = { ...dependencies, ...devDependencies, ...peerDependencies }, illegalDeps = Object.keys(allDependencies).filter((dep) => mergedPackages.includes(dep)), unique = [...new Set(illegalDeps).values()];
354
- return unique.length ? [
355
- outdent`
356
- package.json depends on "@sanity/*" packages that have moved into "sanity" package.
357
-
358
- The following dependencies should be replaced with "sanity":
359
- - ${unique.join(`
360
- - `)}
361
-
362
- Refer to the reference docs to find replacement imports:
363
- ${urls.refDocs}
364
- `.trimStart()
365
- ] : [];
366
- }
367
- function validateDeprecatedDependencies(packageJson) {
368
- const { dependencies, devDependencies, peerDependencies } = packageJson, allDependencies = { ...dependencies, ...devDependencies, ...peerDependencies }, illegalDeps = Object.keys(allDependencies).filter((dep) => deprecatedDevDeps.includes(dep)), unique = [...new Set(illegalDeps).values()];
369
- return unique.length ? [
370
- outdent`
371
- package.json contains deprecated dependencies that should be removed:
372
- - ${unique.join(`
373
- - `)}
374
- `.trimStart()
375
- ] : [];
376
- }
377
- async function validateBabelConfig({ basePath }) {
378
- const filenames = [".babelrc", ...filesWithSuffixes([".babelrc", "babel.config"], ["json", "js", "cjs", "mjs"])], babelFiles = [];
379
- for (const filename of filenames) {
380
- const filepath = path.normalize(path.join(basePath, filename));
381
- await fileExists(filepath) && babelFiles.push(filename);
382
- }
383
- return babelFiles.length ? [
384
- outdent`
385
- Found babel-config file: [${babelFiles.join(
386
- ", "
387
- )}]. When using default @sanity/plugin-kit build command,
388
- this is probably not needed.
389
-
390
- Delete the file, or disable this check.
391
- `.trimStart()
392
- ] : [];
393
- }
394
- async function validateStudioConfig({ basePath }) {
395
- const suffixes = ["ts", "js", "tsx", "jsx"], filenames = filesWithSuffixes(["sanity.config", "sanity.cli"], suffixes), files = {};
396
- for (const filename of filenames) {
397
- const filepath = path.normalize(path.join(basePath, filename));
398
- files[filename] = await fileExists(filepath);
399
- }
400
- const sanityJson = await readJson5File({ basePath, filename: "sanity.json" }), hasConfigFile = (fileBase) => filesWithSuffixes([fileBase], suffixes).some((filename) => files[filename]), hasCliConfig = hasConfigFile("sanity.cli"), hasStudioConfig = hasConfigFile("sanity.config"), errors = [];
401
- if (sanityJson) {
402
- const info = [
403
- outdent`
404
- Found sanity.json. This file is not used by Sanity Studio V3.
405
-
406
- Please consult the Studio V3 migration guide:
407
- ${urls.migrationGuideStudio}
408
- It will detail how to convert sanity.json to sanity.config.ts (or .js) and sanity.cli.ts (or .js) equivalents.
409
- `.trimStart(),
410
- sanityJson.plugins?.length && outdent`
411
- For V3 versions and alternatives to V2 plugins, please refer to the Sanity Exchange:
412
- ${urls.sanityExchange}
413
- `.trimStart()
414
- ].filter((s) => !!s);
415
- errors.push(info.join(`
416
-
417
- `));
418
- }
419
- return hasCliConfig || errors.push(
420
- outdent`
421
- sanity.cli.(${suffixes.join(
422
- " | "
423
- )}) missing. Please create a file named sanity.cli.ts with the following content:
424
-
425
- ${chalk.green(
426
- outdent`
427
- import {createCliConfig} from 'sanity/cli'
428
-
429
- export default createCliConfig({
430
- api: {
431
- projectId: '${sanityJson?.api?.projectId ?? "project-id"}',
432
- dataset: '${sanityJson?.api?.dataset ?? "dataset"}',
433
- }
434
- })`
435
- )}
436
-
437
- Make sure to replace the projectId and dataset fields with your own.
438
-
439
- For more, see ${urls.migrationGuideStudio}
440
- `.trimStart()
441
- ), hasStudioConfig || errors.push(
442
- outdent`
443
- sanity.config.(${suffixes.join(
444
- " | "
445
- )}) missing. At a minimum sanity.config.ts should contain:
446
-
447
- ${chalk.green(
448
- outdent`
449
- import { defineConfig } from "sanity"
450
- import { deskTool } from "sanity/desk"
451
-
452
- export default defineConfig({
453
- name: "default",
454
-
455
- projectId: '${sanityJson?.api?.projectId ?? "project-id"}',
456
- dataset: '${sanityJson?.api?.dataset ?? "dataset"}',
457
-
458
- plugins: [
459
- deskTool(),
460
- ],
461
-
462
- schema: {
463
- types: [
464
- /* put your v2 schema-types here */
465
- ],
466
- },
467
- })`
468
- ).trimStart()}
469
-
470
- Make sure to replace the projectId and dataset fields with your own.
471
-
472
- For more, see ${urls.migrationGuideStudio}
473
- `.trimStart()
474
- ), errors.length ? [errors.join(`
475
-
476
- ---
477
-
478
- `)] : [];
479
- }
480
- async function validateIncompatiblePlugin({
481
- basePath,
482
- packageJson
483
- }) {
484
- const { dependencies, devDependencies, peerDependencies } = packageJson, inDependencies = !!(dependencies?.[incompatiblePluginPackage] || devDependencies?.[incompatiblePluginPackage] || peerDependencies?.[incompatiblePluginPackage]), hasShimFile = await fileExists(path.normalize(path.join(basePath, "v2-incompatible.js"))), sanityJsonReferencesShim = !!(await readJson5File({ basePath, filename: "sanity.json" }))?.parts?.some(
485
- (part) => part?.path?.includes("v2-incompatible")
486
- );
487
- if (!inDependencies && !hasShimFile && !sanityJsonReferencesShim)
488
- return [];
489
- const found = [
490
- inDependencies ? `- "${incompatiblePluginPackage}" listed in package.json` : null,
491
- hasShimFile ? "- the v2-incompatible.js file" : null,
492
- sanityJsonReferencesShim ? "- a sanity.json referencing v2-incompatible.js" : null
493
- ].filter((e) => !!e);
494
- return [
495
- outdent`
496
- ${incompatiblePluginPackage} is no longer used and should be removed.
497
-
498
- It only rendered an error dialog in the long end-of-life Sanity Studio v2 when a v3 plugin was
499
- installed there. That compatibility shim is now obsolete, so plugin-kit no longer adds it.
500
-
501
- Found:
502
- ${found.join(`
503
- `)}
504
-
505
- To fix this:
506
- - Remove "${incompatiblePluginPackage}" from package.json (dependencies/devDependencies/peerDependencies)
507
- - Delete the v2-incompatible.js file
508
- - Delete sanity.json (if it only contains the v2-incompatible "part")
509
- - Remove "sanity.json" and "v2-incompatible.js" from the package.json "files" array
510
-
511
- For more, see ${urls.incompatiblePlugin}
512
- `.trimStart()
513
- ];
514
- }
515
- function validatePackageName$1(packageJson) {
516
- const valid = validateNpmPackageName(packageJson.name ?? "");
517
- return valid.validForNewPackages ? !packageJson.name?.startsWith("@") && !packageJson.name?.startsWith("sanity-plugin-") ? [
518
- 'Invalid package.json: "name" should be prefixed with "sanity-plugin-" (or scoped - @your-company/plugin-name)'
519
- ] : [] : [`Invalid package.json: "name" is invalid: ${(valid.errors ?? valid.warnings ?? []).join(", ")}`];
520
- }
521
- function validateBannedFiles(packageJson) {
522
- const { files } = packageJson;
523
- return Array.isArray(files) ? files.some((entry) => typeof entry != "string" ? !1 : entry.trim().replace(/^\.?\/+/, "").replace(/\/+$/, "") === "src") ? [
524
- outdent`
525
- package.json "files" must not include "src".
526
-
527
- Plugins built with @sanity/plugin-kit publish the compiled output in "dist" (and any v2-compatibility files).
528
- Shipping the "src" directory bloats the published package and can cause bundlers that resolve the
529
- "source" export condition to import raw, uncompiled TypeScript.
530
-
531
- Please remove "src" from the "files" array in package.json.
532
- `.trimStart()
533
- ] : [] : [];
534
- }
535
- async function validateSrcIndexFile(basePath) {
536
- const paths = ["index.js", "index.ts"].map((p) => path.join("src", p)), allowedIndexFiles = paths.map((file) => path.join(basePath, file));
537
- let hasIndex = !1;
538
- for (const indexFile of allowedIndexFiles)
539
- hasIndex = hasIndex || await fileExists(indexFile);
540
- return hasIndex ? [] : [
541
- outdent`
542
- Expected one of [${paths.join(", ")}] to exist.
543
-
544
- @sanity/pkg-utils expects a non-jsx file to be the source entry-point for the plugin.
545
- If you currently have JSX in your index file, extract it into a separate file and import it.
546
- `
547
- ];
548
- }
549
- async function disallowDuplicateConfig({
550
- basePath,
551
- pkgJson,
552
- configKey,
553
- files
554
- }) {
555
- const found = [];
556
- for (const file of files) {
557
- const filePath = path.join(basePath, file);
558
- await fileExists(filePath) && found.push(file);
559
- }
560
- return found.length > 1 ? [
561
- outdent`
562
- Found multiple config files that serve the same purpose: [${found.join(", ")}].
563
-
564
- There should be at most one of these files. Delete the rest.
565
- `
566
- ] : found.length && pkgJson[configKey] ? [
567
- outdent`
568
- package.json contains ${configKey}, but there also exists a config file that serves the same purpose.
569
- Config file: ${found.join("")}]
570
-
571
- Either delete the file or remove ${configKey} entry from package.json.
572
- `
573
- ] : [];
574
- }
575
- async function disallowDuplicateEslintConfig(basePath, pkgJson) {
576
- return disallowDuplicateConfig({
577
- basePath,
578
- pkgJson,
579
- configKey: "eslint",
580
- files: [
581
- ".eslintrc",
582
- ".eslintrc.js",
583
- ".eslintrc.cjs",
584
- ".eslintrc.yaml",
585
- ".eslintrc.yml",
586
- ".eslintrc.json"
587
- ]
588
- });
589
- }
590
- async function disallowDuplicatePrettierConfig(basePath, pkgJson) {
591
- return disallowDuplicateConfig({
592
- basePath,
593
- pkgJson,
594
- configKey: "prettier",
595
- files: [
596
- ".prettierrc",
597
- ".prettierrc.json5",
598
- ".prettierrc.json",
599
- ".prettierrc.yaml",
600
- ".prettierrc.yml",
601
- ".prettierrc.js",
602
- ".prettierrc.cjs",
603
- ".prettier.config,js",
604
- ".prettier.config.cjs",
605
- ".prettierrc.toml"
606
- ]
607
- });
608
- }
609
- const forcedPackageVersions = {}, forcedDevPackageVersions = {}, forcedPeerPackageVersions = {
610
- react: "^18",
611
- "react-dom": "^18",
612
- "@types/react": "^18",
613
- "@types/react-dom": "^18",
614
- sanity: "^5 || ^6.0.0-0",
615
- "styled-components": "^5.2"
616
- };
617
- function errorToUndefined(err) {
618
- if (err instanceof TypeError)
619
- throw err;
620
- }
621
- const stat = util.promisify(fs.stat), readFile$1 = util.promisify(fs.readFile), allowedPartProps = ["name", "implements", "path", "description"], disallowedPluginProps = ["api", "project", "plugins", "env"];
622
- async function getPaths(options) {
623
- const { basePath } = options, manifest = await readManifest(options);
624
- return manifest.paths ? absolutifyPaths(manifest.paths, basePath) : null;
625
- }
626
- function absolutifyPaths(paths, basePath) {
627
- const getPath = (relative) => relative ? path.resolve(path.join(basePath, relative)) : void 0;
628
- return paths ? {
629
- basePath,
630
- compiled: getPath(paths.compiled),
631
- source: getPath(paths.source)
632
- } : { basePath };
633
- }
634
- async function readManifest(options) {
635
- const { basePath, validate = !0 } = options, manifestPath = path.normalize(path.join(basePath, "sanity.json"));
636
- let content;
637
- try {
638
- content = await readFile$1(manifestPath, "utf8");
639
- } catch (err) {
640
- throw err.code === "ENOENT" ? new Error(
641
- `No sanity.json found. sanity.json is required for plugins to function. Use \`${pkg.binname} init\` for a new plugin, or create an empty \`sanity.json\` with an empty object (\`{}\`) for existing ones.`
642
- ) : new Error(`Failed to read "${manifestPath}": ${err.message}`);
643
- }
644
- let parsed;
645
- try {
646
- parsed = JSON.parse(content);
647
- } catch (err) {
648
- throw new Error(`Error parsing "${manifestPath}": ${err.message}`);
649
- }
650
- return validate && await validateManifest(parsed, options), parsed;
651
- }
652
- async function validateManifest(manifest, opts) {
653
- const options = { isPlugin: !0, ...opts };
654
- if (!isObject$1(manifest))
655
- throw new Error("Invalid sanity.json: Root must be an object");
656
- if (options.isPlugin ? await validatePluginManifest(manifest, options) : validateProjectManifest(manifest), "root" in manifest && typeof manifest.root != "boolean")
657
- throw new Error('Invalid sanity.json: "root" property must be a boolean if declared');
658
- await validateParts(manifest, {
659
- ...options,
660
- paths: absolutifyPaths(manifest.paths, options.basePath)
661
- });
662
- }
663
- function validateProjectManifest(manifest) {
664
- if ("paths" in manifest)
665
- throw new Error('Invalid sanity.json: "paths" property has no meaning in a project manifest');
666
- }
667
- async function validatePluginManifest(manifest, options) {
668
- const disallowed = Object.keys(manifest).filter((key) => disallowedPluginProps.includes(key)).map((key) => `"${key}"`);
669
- if (disallowed.length > 0) {
670
- const plural = disallowed.length > 1 ? "s" : "", joined = disallowed.join(", ");
671
- throw new Error(
672
- `Invalid sanity.json: Key${plural} ${joined} ${plural ? "are" : "is"} not allowed in a plugin manifest`
673
- );
674
- }
675
- if (manifest.root)
676
- throw new Error('Invalid sanity.json: "root" cannot be truthy in a plugin manifest');
677
- await validatePaths$1(manifest, options);
678
- }
679
- async function validatePaths$1(manifest, options) {
680
- if (!("paths" in manifest))
681
- return;
682
- if (!isObject$1(manifest.paths))
683
- throw new Error('Invalid sanity.json: "paths" must be an object if declared');
684
- if (typeof manifest.paths.compiled != "string")
685
- throw new Error(
686
- 'Invalid sanity.json: "paths" must have a (string) "compiled" property if declared'
687
- );
688
- if (typeof manifest.paths.source != "string")
689
- throw new Error(
690
- 'Invalid sanity.json: "paths" must have a (string) "source" property if declared'
691
- );
692
- const sourcePath = path.resolve(options.basePath, manifest.paths.source);
693
- let srcStats;
694
- try {
695
- srcStats = await stat(sourcePath);
696
- } catch (err) {
697
- if (err.code === "ENOENT")
698
- throw new Error(`sanity.json references "source" path which does not exist: "${sourcePath}"`);
699
- }
700
- if (!srcStats?.isDirectory())
701
- throw new Error(
702
- `sanity.json references "source" path which is not a directory: "${sourcePath}"`
703
- );
704
- }
705
- async function validateParts(manifest, options) {
706
- if (!("parts" in manifest))
707
- return;
708
- if (!Array.isArray(manifest.parts))
709
- throw new Error('Invalid sanity.json: "parts" must be an array if declared');
710
- let i = 0;
711
- for (const part of manifest.parts)
712
- await validatePart(part, i, options), i++;
713
- }
714
- async function validatePart(part, index, options) {
715
- if (!isObject$1(part))
716
- throw new Error(`Invalid sanity.json: "parts[${index}]" must be an object`);
717
- validateAllowedPartKeys(part, index), validatePartStringValues(part, index), validatePartNames(part, index, options), await validatePartFiles(part, index, options);
718
- }
719
- async function validatePartFiles(part, index, options) {
720
- const { verifyCompiledParts, verifySourceParts, paths } = options;
721
- if (!part?.path)
722
- return;
723
- const ext = path.extname(part.path);
724
- if (paths?.source && ext && ext !== ".js" && buildExtensions.includes(ext))
725
- throw new Error(
726
- `Invalid sanity.json: Part path has extension which is not applicable after compiling. ${ext} becomes .js after compiling. Specify filename without extension (${path.basename(
727
- part.path
728
- )}) (parts[${index}])`
729
- );
730
- if (!verifySourceParts && !verifyCompiledParts)
731
- return;
732
- const [srcExists, outDirExists] = await Promise.all([
733
- hasSourceFile(part.path, paths),
734
- verifyCompiledParts && hasCompiledFile(part.path, paths)
735
- ]);
736
- if (!srcExists)
737
- throw new Error(
738
- `Invalid sanity.json: Part path references file that does not exist in source directory (${paths?.source || paths?.basePath}) (parts[${index}])`
739
- );
740
- if (verifyCompiledParts && !outDirExists)
741
- throw new Error(
742
- `Invalid sanity.json: Part path references file ("${part.path}") that does not exist in compiled directory (${paths?.compiled}) (parts[${index}])`
743
- );
744
- }
745
- function validatePartNames(part, index, options) {
746
- const pluginName = options.pluginName ? options.pluginName.replace(/^sanity-plugin-/, "") : "";
747
- if (!part?.name || !part?.name?.startsWith(`part:${pluginName}/`))
748
- throw new Error(
749
- `Invalid sanity.json: "name" must be prefixed with "part:${pluginName}/" - got "${part?.name}" (parts[${index}])`
750
- );
751
- if (!part?.implements?.startsWith("part:"))
752
- throw new Error(
753
- `Invalid sanity.json: "implements" must be prefixed with "part:" - got "${part?.implements}" (parts[${index}])`
754
- );
755
- }
756
- function validateAllowedPartKeys(part, index) {
757
- const disallowed = Object.keys(part).filter((key) => !allowedPartProps.includes(key)).map((key) => `"${key}"`);
758
- if (disallowed.length > 0) {
759
- const plural = disallowed.length > 1 ? "s" : "", joined = disallowed.join(", ");
760
- throw new Error(
761
- `Invalid sanity.json: Key${plural} ${joined} ${plural ? "are" : "is"} not allowed in a part declaration (parts[${index}])`
762
- );
763
- }
764
- }
765
- function validatePartStringValues(part, index) {
766
- const nonStrings = Object.keys(part).filter((key) => typeof part[key] != "string").map((key) => `"${key}"`);
767
- if (nonStrings.length > 0) {
768
- const plural = nonStrings.length > 1 ? "s" : "", joined = nonStrings.join(", ");
769
- throw new Error(
770
- `Invalid sanity.json: Key${plural} ${joined} should be of type string (parts[${index}])`
771
- );
772
- }
773
- }
774
- function isObject$1(obj) {
775
- return !Array.isArray(obj) && obj !== null && typeof obj == "object";
776
- }
777
- async function hasSanityJson(basePath) {
778
- const file = await readJsonFile(path.join(basePath, "sanity.json")).catch(
779
- errorToUndefined
780
- );
781
- return { exists: !!file, isRoot: !!(file && file.root) };
782
- }
783
- async function findStudioV3Config(basePath) {
784
- const jsFile = "sanity.config.js";
785
- if (await fileExists(path.join(basePath, jsFile)))
786
- return { v3ConfigFile: jsFile };
787
- const tsFile = "sanity.config.ts";
788
- return { v3ConfigFile: await fileExists(path.join(basePath, tsFile)) ? tsFile : void 0 };
789
- }
790
- const lockedDependencies = {
791
- "styled-components": "^6.1",
792
- eslint: "^8.57.0"
793
- };
794
- function resolveLatestVersions(packages) {
795
- const versions = {};
796
- for (const pkgName of packages)
797
- versions[pkgName] = pkgName in lockedDependencies ? lockedDependencies[pkgName] : "latest";
798
- return pProps(
799
- versions,
800
- async (range, pkgName) => {
801
- const version = await getLatestVersion(pkgName, { range });
802
- if (!version)
803
- throw new Error(`Found no version for ${pkgName}`);
804
- return rangeify(version);
805
- },
806
- { concurrency: 8 }
807
- );
808
- }
809
- function rangeify(version) {
810
- return `^${version}`;
811
- }
812
- const defaultDependencies = [], defaultDevDependencies = [
813
- "sanity",
814
- // peer dependencies of `sanity`
815
- "react",
816
- "react-dom",
817
- "styled-components"
818
- ], defaultPeerDependencies = ["react", "sanity"], readFile = util.promisify(fs.readFile), pathKeys = ["main", "module", "browser", "types"];
819
- async function getPackage(opts) {
820
- const options = { flags: {}, ...opts };
821
- validateOptions(options);
822
- const { basePath, validate = !0 } = options, manifestPath = path.normalize(path.join(basePath, "package.json"));
823
- let content;
824
- try {
825
- content = await readFile(manifestPath, "utf8");
826
- } catch (err) {
827
- throw err.code === "ENOENT" ? new Error(
828
- `No package.json found. package.json is required to publish to npm. Use \`${cliName} init\` for a new plugin, or \`npm init\` for an existing one`
829
- ) : new Error(`Failed to read "${manifestPath}": ${err.message}`);
830
- }
831
- let parsed;
832
- try {
833
- parsed = JSON.parse(content);
834
- } catch (err) {
835
- throw new Error(`Error parsing "${manifestPath}": ${err.message}`);
836
- }
837
- if (!isObject(parsed))
838
- throw new Error("Invalid package.json: Root must be an object");
839
- return validate && await validatePackage(parsed, options), parsed;
840
- }
841
- async function validatePackage(manifest, opts) {
842
- validateOptions(opts);
843
- const options = { isPlugin: !0, ...opts };
844
- options.isPlugin && await validatePluginPackage(manifest, options), validateLockFiles(options);
845
- }
846
- function validateOptions(opts) {
847
- const options = opts || {};
848
- if (!isObject(options))
849
- throw new Error("Options must be an object");
850
- if (typeof options.basePath != "string")
851
- throw new Error('"options.basePath" must be a string (path to plugin base path)');
852
- }
853
- async function validatePluginPackage(manifest, options) {
854
- validatePackageName(manifest), await validatePaths(manifest, options);
855
- }
856
- function validatePackageName(manifest) {
857
- if (typeof manifest.name != "string")
858
- throw new Error('Invalid package.json: "name" must be a string');
859
- const valid = validateNpmPackageName(manifest.name);
860
- if (!valid.validForNewPackages)
861
- throw new Error(`Invalid package.json: "name" is invalid: ${(valid.errors ?? []).join(", ")}`);
862
- if (manifest.name[0] !== "@" && !manifest.name.startsWith("sanity-plugin-"))
863
- throw new Error(
864
- 'Invalid package.json: "name" should be prefixed with "sanity-plugin-" (or scoped - @your-company/plugin-name)'
865
- );
866
- }
867
- async function validatePaths(manifest, options) {
868
- const paths = await getPaths({
869
- ...options,
870
- pluginName: manifest.name ?? "unknown",
871
- verifySourceParts: !1,
872
- verifyCompiledParts: !1
873
- }), abs = (file) => path.isAbsolute(file) ? file : path.resolve(path.join(options.basePath, file)), exists = (file) => fs.existsSync(abs(file)), willExist = (file) => paths && hasSourceEquivalent(abs(file), paths), withinSourceDir = (file) => paths?.source && abs(file).startsWith(paths.source), withinTargetDir = (file) => paths?.compiled && abs(file).startsWith(paths.compiled);
874
- for (const key of pathKeys) {
875
- if (!(key in manifest))
876
- continue;
877
- const manifestValue = manifest[key];
878
- if (typeof manifestValue != "string")
879
- throw new Error(`Invalid package.json: "${key}" must be a string if defined`);
880
- if (!options?.flags?.allowSourceTarget && paths && withinSourceDir(manifestValue))
881
- throw new Error(
882
- `Invalid package.json: "${key}" points to file within source (uncompiled) directory. Use --allow-source-target if you really want to do this.`
883
- );
884
- if (exists(manifestValue) && paths && withinTargetDir(manifestValue) && !await willExist(manifestValue))
885
- throw new Error(
886
- `Invalid package.json: "${key}" points to file that will not exist after compiling`
887
- );
888
- if (!exists(manifestValue) && !await willExist(manifestValue)) {
889
- if (!paths)
890
- throw new Error(`Invalid package.json: "${key}" points to file that does not exist`);
891
- const inOutDir = paths.compiled && !abs(manifestValue).startsWith(paths.compiled);
892
- throw new Error(
893
- inOutDir ? `Invalid package.json: "${key}" points to file that does not exist, and "paths" is not configured to compile to this location` : `Invalid package.json: "${key}" points to file that does not exist, and no equivalent is found in source directory`
894
- );
895
- }
896
- }
897
- }
898
- function isObject(obj) {
899
- return !Array.isArray(obj) && obj !== null && typeof obj == "object";
900
- }
901
- function validateLockFiles(options) {
902
- const npm = fs.existsSync(path.join(options.basePath, "package-lock.json")), yarn = fs.existsSync(path.join(options.basePath, "yarn.lock"));
903
- if (npm && yarn)
904
- throw new Error("Invalid plugin: contains both package-lock.json and yarn.lock");
905
- }
906
- async function writePackageJson(data, options) {
907
- const { user, pluginName, license, description, pkg: prevPkg, gitOrigin } = data, {
908
- outDir,
909
- peerDependencies: addPeers,
910
- dependencies: addDeps,
911
- devDependencies: addDevDeps
912
- } = options, { flags } = options, prev = prevPkg || {}, usePrettier = flags.prettier !== !1, useEslint = flags.eslint !== !1, useTypescript = flags.eslint !== !1, newDevDependencies = [cliName, "@sanity/pkg-utils"];
913
- useTypescript && (log.debug("Using TypeScript. Adding to dev dependencies."), newDevDependencies.push("@types/react", "typescript")), usePrettier && (log.debug("Using prettier. Adding to dev dependencies."), newDevDependencies.push("prettier", "prettier-plugin-packagejson")), useEslint && (log.debug("Using eslint. Adding to dev dependencies."), newDevDependencies.push(
914
- "eslint",
915
- "eslint-config-sanity",
916
- "eslint-plugin-react",
917
- "eslint-plugin-react-hooks"
918
- ), usePrettier && newDevDependencies.push("eslint-config-prettier", "eslint-plugin-prettier"), useTypescript && newDevDependencies.push("@typescript-eslint/eslint-plugin", "@typescript-eslint/parser")), log.debug("Resolving latest versions for %s", newDevDependencies.join(", "));
919
- const dependencies = forceDependencyVersions(
920
- {
921
- ...prev.dependencies || {},
922
- ...addDeps || {},
923
- ...await resolveLatestVersions(defaultDependencies)
924
- },
925
- forcedPackageVersions
926
- ), devDependencies = forceDependencyVersions(
927
- {
928
- ...addDevDeps || {},
929
- ...prev.devDependencies || {},
930
- ...await resolveLatestVersions([...newDevDependencies, ...defaultDevDependencies])
931
- },
932
- forcedDevPackageVersions
933
- ), peerDependencies = forceDependencyVersions(
934
- {
935
- ...prev.peerDependencies || {},
936
- ...addPeers || {},
937
- ...await resolveLatestVersions(defaultPeerDependencies)
938
- },
939
- forcedPeerPackageVersions
940
- ), source = flags.typescript ? "./src/index.ts" : "./src/index.js", files = [outDir];
941
- files.sort();
942
- const forcedOrder = {
943
- name: pluginName,
944
- version: prev.version ?? "1.0.0",
945
- description: description || "",
946
- keywords: prev.keywords ?? ["sanity", "sanity-plugin"],
947
- ...urlsFromOrigin(gitOrigin),
948
- ...repoFromOrigin(gitOrigin),
949
- license: license ? license.id : "UNLICENSED",
950
- author: user?.email ? `${user.name} <${user.email}>` : user?.name,
951
- sideEffects: !1,
952
- type: "module",
953
- exports: {
954
- ".": {
955
- source,
956
- default: `./${outDir}/index.js`
957
- },
958
- "./package.json": "./package.json"
959
- },
960
- ...flags.typescript ? { types: `./${outDir}/index.d.ts` } : {},
961
- files,
962
- scripts: { ...prev.scripts },
963
- dependencies: sortKeys(dependencies),
964
- devDependencies: sortKeys(devDependencies),
965
- peerDependencies: sortKeys(peerDependencies),
966
- engines: {
967
- node: requiredNodeEngine
968
- }
969
- }, manifest = {
970
- ...forcedOrder,
971
- // Use already configured values by default (if not otherwise specified)
972
- ...prev || {},
973
- // We're de-declaring properties because of key order in package.json
974
- ...forcedOrder
975
- }, differs = JSON.stringify(prev) !== JSON.stringify(manifest);
976
- return log.debug("Does manifest differ? %s", differs ? "yes" : "no"), differs && await writePackageJsonDirect(manifest, options), differs ? manifest : prev;
977
- }
978
- function urlsFromOrigin(gitOrigin) {
979
- if (!gitOrigin)
980
- return {};
981
- const details = githubUrlToObject(gitOrigin);
982
- return details ? {
983
- homepage: `https://github.com/${details.user}/${details.repo}#readme`,
984
- bugs: {
985
- url: `https://github.com/${details.user}/${details.repo}/issues`
986
- }
987
- } : {};
988
- }
989
- function repoFromOrigin(gitOrigin) {
990
- return gitOrigin ? {
991
- repository: {
992
- type: "git",
993
- url: gitOrigin
994
- }
995
- } : {};
996
- }
997
- function addScript(cmd, existing) {
998
- return existing && existing.includes(cmd) ? existing : cmd;
999
- }
1000
- async function addPackageJsonScripts(manifest, options, updateScripts) {
1001
- const originalScripts = manifest.scripts || {}, scripts = updateScripts({ ...originalScripts }), differs = Object.keys(scripts).some((key) => scripts[key] !== originalScripts[key]);
1002
- return differs && await writePackageJsonDirect({ ...manifest, scripts }, options), differs;
1003
- }
1004
- async function writePackageJsonDirect(manifest, { basePath }) {
1005
- await writeJsonFile(path.join(basePath, "package.json"), manifest);
1006
- }
1007
- async function addBuildScripts(manifest, options) {
1008
- return options.flags.scripts ? addPackageJsonScripts(manifest, options, (scripts) => (scripts.build = addScript(expectedScripts.build, scripts.build), scripts.format = addScript("prettier --write --cache --ignore-unknown .", scripts.format), scripts["link-watch"] = addScript(expectedScripts["link-watch"], scripts["link-watch"]), scripts.lint = addScript("eslint .", scripts.lint), scripts.prepublishOnly = addScript(expectedScripts.prepublishOnly, scripts.prepublishOnly), scripts.watch = addScript(expectedScripts.watch, scripts.watch), scripts)) : !1;
1009
- }
1010
- function sortKeys(unordered) {
1011
- return Object.keys(unordered).sort().reduce((obj, key) => (obj[key] = unordered[key], obj), {});
1012
- }
1013
- function forceDependencyVersions(deps, versions = forcedPackageVersions) {
1014
- const entries = Object.entries(deps).map((entry) => {
1015
- const [pkg2] = entry, forceVersion = versions[pkg2];
1016
- return forceVersion ? [pkg2, forceVersion] : entry;
1017
- });
1018
- return Object.fromEntries(entries);
1019
- }
1020
- export {
1021
- addBuildScripts,
1022
- addPackageJsonScripts,
1023
- addScript,
1024
- copyFileWithOverwritePrompt,
1025
- disallowDuplicateEslintConfig,
1026
- disallowDuplicatePrettierConfig,
1027
- ensureDir,
1028
- errorToUndefined,
1029
- fileExists,
1030
- findStudioV3Config,
1031
- forceDependencyVersions,
1032
- forcedDevPackageVersions,
1033
- forcedPackageVersions,
1034
- getPackage,
1035
- hasSanityJson,
1036
- isEmptyish,
1037
- mergedPackages,
1038
- mkdir,
1039
- prompt,
1040
- promptForPackageName,
1041
- promptForRepoOrigin,
1042
- readFile$2 as readFile,
1043
- readJsonFile,
1044
- resolveLatestVersions,
1045
- sortKeys,
1046
- validateBabelConfig,
1047
- validateBannedFiles,
1048
- validateDeprecatedDependencies,
1049
- validateEsmOnly,
1050
- validateIncompatiblePlugin,
1051
- validateNodeEngine,
1052
- validatePackageName$1 as validatePackageName,
1053
- validatePackageType,
1054
- validatePkgUtilsDependency,
1055
- validatePkgUtilsVersion,
1056
- validateSanityDependencies,
1057
- validateScripts,
1058
- validateSrcIndexFile,
1059
- validateStudioConfig,
1060
- validateTsConfig,
1061
- writeFile,
1062
- writeFileWithOverwritePrompt,
1063
- writePackageJson,
1064
- writePackageJsonDirect
1065
- };
1066
- //# sourceMappingURL=package.js.map