@sanity/plugin-kit 4.0.20 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/assets/inject/semver-workflow/.husky/commit-msg +0 -0
  2. package/assets/inject/semver-workflow/.husky/pre-commit +0 -0
  3. package/assets/inject/ui-workshop/src/__workshop__/props.tsx +2 -1
  4. package/bin/plugin-kit.js +3 -1
  5. package/dist/{_chunks-cjs/cli.js → _chunks-es/index.js} +53 -63
  6. package/dist/_chunks-es/index.js.map +1 -0
  7. package/dist/{_chunks-cjs/init2.js → _chunks-es/init.js} +25 -23
  8. package/dist/_chunks-es/init.js.map +1 -0
  9. package/dist/_chunks-es/init2.js +140 -0
  10. package/dist/_chunks-es/init2.js.map +1 -0
  11. package/{src/cmds/inject.ts → dist/_chunks-es/inject.js} +18 -32
  12. package/dist/{_chunks-cjs → _chunks-es}/inject.js.map +1 -1
  13. package/dist/_chunks-es/link-watch.js +91 -0
  14. package/dist/_chunks-es/link-watch.js.map +1 -0
  15. package/dist/_chunks-es/load-package-config.js +22 -0
  16. package/dist/_chunks-es/load-package-config.js.map +1 -0
  17. package/dist/_chunks-es/package.js +1759 -0
  18. package/dist/_chunks-es/package.js.map +1 -0
  19. package/dist/_chunks-es/package2.js +9 -0
  20. package/dist/{_chunks-cjs → _chunks-es}/package2.js.map +1 -1
  21. package/dist/_chunks-es/ts.js +171 -0
  22. package/dist/_chunks-es/ts.js.map +1 -0
  23. package/dist/_chunks-es/verify-package.js +92 -0
  24. package/dist/_chunks-es/verify-package.js.map +1 -0
  25. package/dist/_chunks-es/verify-studio.js +61 -0
  26. package/dist/_chunks-es/verify-studio.js.map +1 -0
  27. package/dist/_chunks-es/version.js +50 -0
  28. package/dist/_chunks-es/version.js.map +1 -0
  29. package/dist/index.d.ts +4 -1
  30. package/dist/index.d.ts.map +1 -0
  31. package/dist/index.js +4 -1
  32. package/dist/index.js.map +1 -1
  33. package/package.json +40 -98
  34. package/LICENSE +0 -21
  35. package/dist/_chunks-cjs/cli.js.map +0 -1
  36. package/dist/_chunks-cjs/init.js +0 -892
  37. package/dist/_chunks-cjs/init.js.map +0 -1
  38. package/dist/_chunks-cjs/init2.js.map +0 -1
  39. package/dist/_chunks-cjs/inject.js +0 -54
  40. package/dist/_chunks-cjs/link-watch.js +0 -84
  41. package/dist/_chunks-cjs/link-watch.js.map +0 -1
  42. package/dist/_chunks-cjs/package.js +0 -1809
  43. package/dist/_chunks-cjs/package.js.map +0 -1
  44. package/dist/_chunks-cjs/package2.js +0 -8
  45. package/dist/_chunks-cjs/ts.js +0 -160732
  46. package/dist/_chunks-cjs/ts.js.map +0 -1
  47. package/dist/_chunks-cjs/verify-package.js +0 -75
  48. package/dist/_chunks-cjs/verify-package.js.map +0 -1
  49. package/dist/_chunks-cjs/verify-studio.js +0 -57
  50. package/dist/_chunks-cjs/verify-studio.js.map +0 -1
  51. package/dist/_chunks-cjs/version.js +0 -51
  52. package/dist/_chunks-cjs/version.js.map +0 -1
  53. package/dist/cli.d.ts +0 -4
  54. package/dist/cli.js +0 -6
  55. package/dist/cli.js.map +0 -1
  56. package/src/actions/init.ts +0 -95
  57. package/src/actions/inject.ts +0 -399
  58. package/src/actions/link-watch.ts +0 -98
  59. package/src/actions/verify/types.ts +0 -56
  60. package/src/actions/verify/validations.ts +0 -505
  61. package/src/actions/verify/verify-common.ts +0 -93
  62. package/src/actions/verify-package.ts +0 -103
  63. package/src/actions/verify-studio.ts +0 -58
  64. package/src/cli.ts +0 -77
  65. package/src/cmds/index.ts +0 -20
  66. package/src/cmds/init.ts +0 -90
  67. package/src/cmds/link-watch.ts +0 -50
  68. package/src/cmds/verify-package.ts +0 -36
  69. package/src/cmds/verify-studio.ts +0 -36
  70. package/src/cmds/version.ts +0 -67
  71. package/src/configs/banned-packages.ts +0 -27
  72. package/src/configs/buildExtensions.ts +0 -1
  73. package/src/configs/default-source.ts +0 -64
  74. package/src/configs/eslint.ts +0 -51
  75. package/src/configs/forced-package-versions.ts +0 -12
  76. package/src/configs/git.ts +0 -68
  77. package/src/configs/pkg-config.ts +0 -30
  78. package/src/configs/prettier.ts +0 -11
  79. package/src/configs/tsconfig.ts +0 -78
  80. package/src/configs/uselessFiles.ts +0 -29
  81. package/src/constants.ts +0 -15
  82. package/src/dependencies/find.ts +0 -193
  83. package/src/dependencies/import-linter.ts +0 -95
  84. package/src/index.ts +0 -1
  85. package/src/npm/manager.ts +0 -44
  86. package/src/npm/package.ts +0 -427
  87. package/src/npm/publish.ts +0 -9
  88. package/src/npm/resolveLatestVersions.ts +0 -31
  89. package/src/presets/presets.ts +0 -54
  90. package/src/presets/renovatebot.ts +0 -21
  91. package/src/presets/semver-workflow.ts +0 -186
  92. package/src/presets/ui-workshop.ts +0 -97
  93. package/src/presets/ui.ts +0 -67
  94. package/src/sanity/manifest.ts +0 -340
  95. package/src/sharedFlags.ts +0 -14
  96. package/src/util/command-parser.ts +0 -36
  97. package/src/util/errorToUndefined.ts +0 -7
  98. package/src/util/files.ts +0 -260
  99. package/src/util/log.ts +0 -44
  100. package/src/util/prompt.ts +0 -70
  101. package/src/util/readme.ts +0 -88
  102. package/src/util/request.ts +0 -11
  103. package/src/util/ts.ts +0 -19
  104. package/src/util/user.ts +0 -129
@@ -1,505 +0,0 @@
1
- import outdent from 'outdent'
2
- // @ts-expect-error missing types
3
- import validateNpmPackageName from 'validate-npm-package-name'
4
- import {incompatiblePluginPackage, urls} from '../../constants'
5
- import {deprecatedDevDeps, mergedPackages} from '../../configs/banned-packages'
6
- import path from 'path'
7
- import {fileExists, readJson5File} from '../../util/files'
8
- import chalk from 'chalk'
9
- import {PackageJson, SanityStudioJson, SanityV2Json} from './types'
10
- import {ParsedCommandLine} from 'typescript'
11
-
12
- export const expectedScripts = {
13
- build: 'plugin-kit verify-package --silent && pkg-utils build --strict --check --clean',
14
- watch: 'pkg-utils watch --strict',
15
- 'link-watch': 'plugin-kit link-watch',
16
- prepublishOnly: 'npm run build',
17
- }
18
-
19
- function filesWithSuffixes(fileBases: string[], suffixes: string[]): string[] {
20
- return fileBases.flatMap((file) => suffixes.map((suffix) => `${file}.${suffix}`))
21
- }
22
-
23
- export function validateNodeEngine(packageJson: PackageJson) {
24
- const nodeVersionRange = '>=18'
25
- if (!packageJson.engines?.node?.startsWith(nodeVersionRange)) {
26
- return [
27
- outdent`
28
- Expected package.json to contain engines.node: ">=18" to ensure Studio compatible builds,
29
- but it was: ${packageJson.engines?.node}
30
-
31
- Please add the following to package.json:
32
-
33
- "engines": {
34
- "node": "${nodeVersionRange}"
35
- }`.trimStart(),
36
- ]
37
- }
38
- }
39
-
40
- export function validateScripts(packageJson: PackageJson): string[] {
41
- const errors: string[] = []
42
-
43
- const divergentScripts = Object.entries(expectedScripts).filter(([key, expectedCommand]) => {
44
- const command = packageJson.scripts?.[key]
45
- // check for includes instead of equals to give some leniency in command params and such
46
- return !command || !command.includes(expectedCommand)
47
- })
48
-
49
- if (divergentScripts.length) {
50
- errors.push(
51
- outdent`
52
- The following script commands did not contain expected defaults: ${divergentScripts
53
- .map(([key]) => key)
54
- .join(', ')}
55
-
56
- This checks for that the commands-strings includes these terms.
57
-
58
- Please add the following to your package.json "scripts":
59
-
60
- ${divergentScripts.map(([key, value]) => `"${key}": "${value}"`).join(',\n')}
61
- `.trimStart(),
62
- )
63
- }
64
- return errors
65
- }
66
-
67
- export async function validateTsConfig(
68
- ts: ParsedCommandLine,
69
- options: {basePath: string; outDir: string; tsconfig: string},
70
- ) {
71
- const {basePath, outDir, tsconfig} = options
72
-
73
- const errors: string[] = []
74
-
75
- const expectedCompilerOptions = {
76
- target: 'esnext',
77
- jsx: 'preserve',
78
- module: 'preserve',
79
- rootDir: '.',
80
- outDir,
81
- noEmit: true,
82
- }
83
-
84
- const wrongEntries = Object.entries(expectedCompilerOptions).filter(([key, value]) => {
85
- let option: any = ts.options[key]
86
-
87
- if (key === 'rootDir' && typeof option === 'string') {
88
- option = path.relative(basePath, option) || '.'
89
- }
90
-
91
- if (key === 'outDir' && typeof option === 'string') {
92
- option = path.relative(basePath, option) || '.'
93
- }
94
-
95
- if (key === 'target' && option === 99) {
96
- option = 'esnext'
97
- }
98
-
99
- if (key === 'module' && option === 200) {
100
- option = 'preserve'
101
- }
102
-
103
- if (key === 'jsx' && option === 1) {
104
- option = 'preserve'
105
- }
106
-
107
- return typeof value === 'string' && typeof option === 'string'
108
- ? value.toLowerCase() !== option?.toLowerCase()
109
- : value !== option
110
- })
111
-
112
- if (wrongEntries.length) {
113
- const expectedOutput = wrongEntries
114
- .map(([key, value]) => `"${key}": ${typeof value === 'string' ? `"${value}"` : value},`)
115
- .join('\n')
116
-
117
- errors.push(
118
- outdent`
119
- Recommended ${tsconfig} compilerOptions missing:
120
-
121
- The following fields had unexpected values: [${wrongEntries.map(([key]) => key).join(', ')}]
122
- Expected to find these values:
123
- ${expectedOutput}
124
-
125
- Please update your ${tsconfig} accordingly.
126
- `.trimStart(),
127
- )
128
- }
129
-
130
- return errors
131
- }
132
-
133
- export function validatePkgUtilsDependency({devDependencies}: PackageJson): string[] {
134
- if (!devDependencies?.['@sanity/pkg-utils']) {
135
- return [
136
- outdent`
137
- package.json does not list @sanity/pkg-utils as a devDependency.
138
- @sanity/pkg-utils replaced parcel as the recommended build tool in @sanity/plugin-kit 2.0.0
139
-
140
- Please add it by running 'npm install --save-dev @sanity/pkg-utils'.
141
- `.trimStart(),
142
- ]
143
- }
144
- return []
145
- }
146
-
147
- export function validateSanityDependencies(packageJson: PackageJson): string[] {
148
- const {dependencies, devDependencies, peerDependencies} = packageJson
149
- const allDependencies = {...dependencies, ...devDependencies, ...peerDependencies}
150
-
151
- const illegalDeps = Object.keys(allDependencies).filter((dep) => mergedPackages.includes(dep))
152
- const deps = new Set<string>(illegalDeps)
153
- const unique = [...deps.values()]
154
- if (unique.length) {
155
- return [
156
- outdent`
157
- package.json depends on "@sanity/*" packages that have moved into "sanity" package.
158
-
159
- The following dependencies should be replaced with "sanity":
160
- - ${unique.join('\n- ')}
161
-
162
- Refer to the reference docs to find replacement imports:
163
- ${urls.refDocs}
164
- `.trimStart(),
165
- ]
166
- }
167
- return []
168
- }
169
-
170
- export function validateDeprecatedDependencies(packageJson: PackageJson): string[] {
171
- const {dependencies, devDependencies, peerDependencies} = packageJson
172
- const allDependencies = {...dependencies, ...devDependencies, ...peerDependencies}
173
-
174
- const illegalDeps = Object.keys(allDependencies).filter((dep) => deprecatedDevDeps.includes(dep))
175
- const deps = new Set<string>(illegalDeps)
176
- const unique = [...deps.values()]
177
- if (unique.length) {
178
- return [
179
- outdent`
180
- package.json contains deprecated dependencies that should be removed:
181
- - ${unique.join('\n- ')}
182
- `.trimStart(),
183
- ]
184
- }
185
-
186
- return []
187
- }
188
-
189
- export async function validateBabelConfig({basePath}: {basePath: string}) {
190
- const suffixes = ['json', 'js', 'cjs', 'mjs']
191
- const babelFileNames = ['.babelrc', 'babel.config']
192
- const filenames = ['.babelrc', ...filesWithSuffixes(babelFileNames, suffixes)]
193
-
194
- const babelFiles: string[] = []
195
- for (const filename of filenames) {
196
- const filepath = path.normalize(path.join(basePath, filename))
197
- if (await fileExists(filepath)) {
198
- babelFiles.push(filename)
199
- }
200
- }
201
-
202
- if (babelFiles.length) {
203
- return [
204
- outdent`
205
- Found babel-config file: [${babelFiles.join(
206
- ', ',
207
- )}]. When using default @sanity/plugin-kit build command,
208
- this is probably not needed.
209
-
210
- Delete the file, or disable this check.
211
- `.trimStart(),
212
- ]
213
- }
214
- return []
215
- }
216
-
217
- export async function validateStudioConfig({basePath}: {basePath: string}): Promise<string[]> {
218
- const suffixes = ['ts', 'js', 'tsx', 'jsx']
219
-
220
- const filenames = filesWithSuffixes(['sanity.config', 'sanity.cli'], suffixes)
221
-
222
- const files: Record<string, boolean | undefined> = {}
223
-
224
- for (const filename of filenames) {
225
- const filepath = path.normalize(path.join(basePath, filename))
226
- files[filename] = await fileExists(filepath)
227
- }
228
-
229
- const sanityJson = await readJson5File<SanityStudioJson>({basePath, filename: 'sanity.json'})
230
-
231
- const hasConfigFile = (fileBase: string) =>
232
- filesWithSuffixes([fileBase], suffixes).some((filename) => files[filename])
233
- const hasCliConfig = hasConfigFile('sanity.cli')
234
- const hasStudioConfig = hasConfigFile('sanity.config')
235
-
236
- const errors: string[] = []
237
-
238
- if (sanityJson) {
239
- const info = [
240
- outdent`
241
- Found sanity.json. This file is not used by Sanity Studio V3.
242
-
243
- Please consult the Studio V3 migration guide:
244
- ${urls.migrationGuideStudio}
245
- It will detail how to convert sanity.json to sanity.config.ts (or .js) and sanity.cli.ts (or .js) equivalents.
246
- `.trimStart(),
247
- sanityJson.plugins?.length &&
248
- outdent`
249
- For V3 versions and alternatives to V2 plugins, please refer to the Sanity Exchange:
250
- ${urls.sanityExchange}
251
- `.trimStart(),
252
- ].filter((s): s is string => !!s)
253
-
254
- errors.push(info.join('\n\n'))
255
- }
256
-
257
- if (!hasCliConfig) {
258
- errors.push(
259
- outdent`
260
- sanity.cli.(${suffixes.join(
261
- ' | ',
262
- )}) missing. Please create a file named sanity.cli.ts with the following content:
263
-
264
- ${chalk.green(
265
- outdent`
266
- import {createCliConfig} from 'sanity/cli'
267
-
268
- export default createCliConfig({
269
- api: {
270
- projectId: '${sanityJson?.api?.projectId ?? 'project-id'}',
271
- dataset: '${sanityJson?.api?.dataset ?? 'dataset'}',
272
- }
273
- })`,
274
- )}
275
-
276
- Make sure to replace the projectId and dataset fields with your own.
277
-
278
- For more, see ${urls.migrationGuideStudio}
279
- `.trimStart(),
280
- )
281
- }
282
-
283
- if (!hasStudioConfig) {
284
- errors.push(
285
- outdent`
286
- sanity.config.(${suffixes.join(
287
- ' | ',
288
- )}) missing. At a minimum sanity.config.ts should contain:
289
-
290
- ${chalk
291
- .green(
292
- outdent`
293
- import { defineConfig } from "sanity"
294
- import { deskTool } from "sanity/desk"
295
-
296
- export default defineConfig({
297
- name: "default",
298
-
299
- projectId: '${sanityJson?.api?.projectId ?? 'project-id'}',
300
- dataset: '${sanityJson?.api?.dataset ?? 'dataset'}',
301
-
302
- plugins: [
303
- deskTool(),
304
- ],
305
-
306
- schema: {
307
- types: [
308
- /* put your v2 schema-types here */
309
- ],
310
- },
311
- })`,
312
- )
313
- .trimStart()}
314
-
315
- Make sure to replace the projectId and dataset fields with your own.
316
-
317
- For more, see ${urls.migrationGuideStudio}
318
- `.trimStart(),
319
- )
320
- }
321
-
322
- return errors.length ? [errors.join(`\n\n---\n\n`)] : []
323
- }
324
-
325
- export async function validatePluginSanityJson({
326
- basePath,
327
- packageJson,
328
- }: {
329
- basePath: string
330
- packageJson: PackageJson
331
- }) {
332
- const sanityJson = await readJson5File<SanityV2Json>({basePath, filename: 'sanity.json'})
333
-
334
- const expectedDefaults = {
335
- parts: [
336
- {
337
- implements: 'part:@sanity/base/sanity-root',
338
- path: './v2-incompatible.js',
339
- },
340
- ],
341
- }
342
-
343
- const hasSinglePart =
344
- sanityJson &&
345
- Object.keys(sanityJson).length === 1 &&
346
- sanityJson?.parts &&
347
- sanityJson.parts.length === 1
348
-
349
- const firstPart = hasSinglePart ? sanityJson?.parts?.[0] : undefined
350
- const correctImplements = firstPart?.implements === expectedDefaults.parts[0].implements
351
- const pathExists =
352
- firstPart?.path && (await fileExists(path.normalize(path.join(basePath, firstPart.path))))
353
- const hasDependency = !!packageJson.dependencies?.[incompatiblePluginPackage]
354
- const isValid = sanityJson && hasSinglePart && correctImplements && pathExists && hasDependency
355
-
356
- if (!isValid) {
357
- const errors = [
358
- !sanityJson ? 'sanity.json does not exist' : null,
359
- !hasSinglePart ? 'sanity.json should have exactly one entry in "parts", but did not.' : null,
360
- !correctImplements
361
- ? `The part should implement ${expectedDefaults.parts[0].implements}, but did not.`
362
- : null,
363
- firstPart?.path && !pathExists
364
- ? `The file in "path", ${firstPart?.path}, does not exist.`
365
- : null,
366
-
367
- !hasDependency
368
- ? outdent`
369
- package.json should have ${incompatiblePluginPackage} as a dependency, but did not.
370
- Install it with: npm install --save ${incompatiblePluginPackage}
371
- `.trimStart()
372
- : null,
373
- ].filter((e): e is string => !!e)
374
-
375
- return [
376
- outdent`
377
- Invalid sanity.json. It is used for compatibility checking in V2 studios:
378
-
379
- - ${errors.join('\n- ')}
380
-
381
- sanity.json will only be used when incorrectly installing a v3 plugin in a v2 Studio.
382
-
383
- This check ensures that sanity.json conforms with the usage section of
384
- ${urls.incompatiblePlugin}
385
- `.trimStart(),
386
- ]
387
- }
388
- return []
389
- }
390
-
391
- export function validatePackageName(packageJson: PackageJson) {
392
- const valid: {validForNewPackages?: boolean; errors: string[]} = validateNpmPackageName(
393
- packageJson.name,
394
- )
395
- if (!valid.validForNewPackages) {
396
- return [`Invalid package.json: "name" is invalid: ${valid.errors.join(', ')}`]
397
- }
398
-
399
- const isScoped = packageJson.name?.startsWith('@')
400
- if (!isScoped && !packageJson.name?.startsWith('sanity-plugin-')) {
401
- return [
402
- `Invalid package.json: "name" should be prefixed with "sanity-plugin-" (or scoped - @your-company/plugin-name)`,
403
- ]
404
- }
405
- }
406
-
407
- export async function validateSrcIndexFile(basePath: string) {
408
- const paths = ['index.js', 'index.ts'].map((p) => path.join('src', p))
409
- const allowedIndexFiles = paths.map((file) => path.join(basePath, file))
410
-
411
- let hasIndex = false
412
- for (const indexFile of allowedIndexFiles) {
413
- hasIndex = hasIndex || (await fileExists(indexFile))
414
- }
415
- if (!hasIndex) {
416
- return [
417
- outdent`
418
- Expected one of [${paths.join(', ')}] to exist.
419
-
420
- @sanity/pkg-utils expects a non-jsx file to be the source entry-point for the plugin.
421
- If you currently have JSX in your index file, extract it into a separate file and import it.
422
- `,
423
- ]
424
- }
425
-
426
- return []
427
- }
428
-
429
- export async function disallowDuplicateConfig({
430
- basePath,
431
- pkgJson,
432
- configKey,
433
- files,
434
- }: {
435
- basePath: string
436
- pkgJson: PackageJson
437
- configKey: string
438
- files: string[]
439
- }) {
440
- const found: string[] = []
441
- for (const file of files) {
442
- const filePath = path.join(basePath, file)
443
- const exits = await fileExists(filePath)
444
- if (exits) {
445
- found.push(file)
446
- }
447
- }
448
- if (found.length > 1) {
449
- return [
450
- outdent`
451
- Found multiple config files that serve the same purpose: [${found.join(', ')}].
452
-
453
- There should be at most one of these files. Delete the rest.
454
- `,
455
- ]
456
- }
457
- if (found.length && pkgJson[configKey]) {
458
- return [
459
- outdent`
460
- package.json contains ${configKey}, but there also exists a config file that serves the same purpose.
461
- Config file: ${found.join('')}]
462
-
463
- Either delete the file or remove ${configKey} entry from package.json.
464
- `,
465
- ]
466
- }
467
-
468
- return []
469
- }
470
-
471
- export async function disallowDuplicateEslintConfig(basePath: string, pkgJson: PackageJson) {
472
- return disallowDuplicateConfig({
473
- basePath,
474
- pkgJson,
475
- configKey: 'eslint',
476
- files: [
477
- '.eslintrc',
478
- '.eslintrc.js',
479
- '.eslintrc.cjs',
480
- '.eslintrc.yaml',
481
- '.eslintrc.yml',
482
- '.eslintrc.json',
483
- ],
484
- })
485
- }
486
-
487
- export async function disallowDuplicatePrettierConfig(basePath: string, pkgJson: PackageJson) {
488
- return disallowDuplicateConfig({
489
- basePath,
490
- pkgJson,
491
- configKey: 'prettier',
492
- files: [
493
- '.prettierrc',
494
- '.prettierrc.json5',
495
- '.prettierrc.json',
496
- '.prettierrc.yaml',
497
- '.prettierrc.yml',
498
- '.prettierrc.js',
499
- '.prettierrc.cjs',
500
- '.prettier.config,js',
501
- '.prettier.config.cjs',
502
- '.prettierrc.toml',
503
- ],
504
- })
505
- }
@@ -1,93 +0,0 @@
1
- import log from '../../util/log'
2
- import {TypedFlags} from 'meow'
3
- import fs from 'fs'
4
- import sharedFlags from '../../sharedFlags'
5
- import chalk from 'chalk'
6
- import outdent from 'outdent'
7
- import {runCommand} from '../../util/command-parser'
8
- import {ParsedCommandLine} from 'typescript'
9
-
10
- export const readFile = fs.promises.readFile
11
- const splitLine = `\n----------------------------------------------------------`
12
-
13
- export const verifyPackageConfigDefaults = {
14
- packageName: true,
15
- tsconfig: true,
16
- tsc: true,
17
- dependencies: true,
18
- deprecatedDependencies: true,
19
- babelConfig: true,
20
- sanityV2Json: true,
21
- eslintImports: true,
22
- scripts: true,
23
- 'pkg-utils': true,
24
- nodeEngine: true,
25
- studioConfig: true,
26
- srcIndex: true,
27
- duplicateConfig: true,
28
- } as const
29
-
30
- export type VerifyPackageConfig = Partial<Record<keyof typeof verifyPackageConfigDefaults, boolean>>
31
-
32
- export const verifyFlags = {
33
- ...sharedFlags,
34
- single: {
35
- default: false,
36
- type: 'boolean',
37
- },
38
- } as const
39
-
40
- export type VerifyFlags = TypedFlags<typeof verifyFlags>
41
-
42
- export function disableCheckText(checkKey: string) {
43
- return chalk.grey(
44
- outdent`
45
- To skip this validation add the following to your package.json:
46
- "sanityPlugin": {
47
- "verifyPackage": {
48
- "${checkKey}": false
49
- }
50
- }
51
- `.trimStart(),
52
- )
53
- }
54
-
55
- export function createValidator(
56
- verifyConfig: VerifyPackageConfig,
57
- flags: VerifyFlags,
58
- errors: string[],
59
- ) {
60
- return async function validation(
61
- checkKey: keyof VerifyPackageConfig,
62
- task: () => Promise<string[] | undefined>,
63
- ) {
64
- if (verifyConfig[checkKey] !== false) {
65
- const result = await task()
66
- if (result?.length) {
67
- result.push(disableCheckText(checkKey))
68
- const errorMessage = result.join('\n\n')
69
- errors.push(errorMessage)
70
- log.error(`\n` + errorMessage + splitLine)
71
- }
72
- }
73
-
74
- if (flags.single && errors.length) {
75
- throw new Error(
76
- outdent`Detected outstanding upgrade issues.
77
-
78
- Fail-fast (--single) mode enabled, stopping validation here.
79
- `,
80
- )
81
- }
82
- }
83
- }
84
-
85
- export async function runTscMaybe(verifyConfig: VerifyPackageConfig, ts?: ParsedCommandLine) {
86
- if (ts && verifyConfig.tsc !== false) {
87
- log.info('All checks ok, running Typescript compiler.')
88
- const {code} = await runCommand('tsc --build')
89
- if (code !== 0) {
90
- throw new Error('Compilation failed. See output above.\n\n' + disableCheckText('tsc'))
91
- }
92
- }
93
- }
@@ -1,103 +0,0 @@
1
- import {loadConfig as loadPackageConfig} from '@sanity/pkg-utils'
2
- import {getPackage} from '../npm/package'
3
- import log from '../util/log'
4
- import {cliName, defaultOutDir, urls} from '../constants'
5
- import {validateImports} from '../dependencies/import-linter'
6
- import outdent from 'outdent'
7
- import {
8
- createValidator,
9
- runTscMaybe,
10
- VerifyFlags,
11
- VerifyPackageConfig,
12
- } from './verify/verify-common'
13
- import {
14
- validateBabelConfig,
15
- validateNodeEngine,
16
- validatePackageName,
17
- validatePkgUtilsDependency,
18
- validatePluginSanityJson,
19
- validateDeprecatedDependencies,
20
- validateScripts,
21
- validateTsConfig,
22
- validateSanityDependencies,
23
- validateSrcIndexFile,
24
- disallowDuplicateEslintConfig,
25
- disallowDuplicatePrettierConfig,
26
- } from './verify/validations'
27
- import {PackageJson} from './verify/types'
28
- import chalk from 'chalk'
29
- import {readTSConfig} from '../util/ts'
30
-
31
- export async function verifyPackage({basePath, flags}: {basePath: string; flags: VerifyFlags}) {
32
- let errors: string[] = []
33
-
34
- const packageJson: PackageJson = await getPackage({basePath, validate: false})
35
- const verifyConfig: VerifyPackageConfig = packageJson.sanityPlugin?.verifyPackage || {}
36
- const packageConfig = await loadPackageConfig({cwd: basePath})
37
- const outDir = packageConfig?.dist ?? defaultOutDir
38
- const tsconfig = packageConfig?.tsconfig ?? 'tsconfig.json'
39
-
40
- const validation = createValidator(verifyConfig, flags, errors)
41
-
42
- const ts = await readTSConfig({basePath, filename: tsconfig})
43
-
44
- await validation('packageName', async () => validatePackageName(packageJson))
45
- await validation('pkg-utils', async () => validatePkgUtilsDependency(packageJson))
46
- await validation('srcIndex', async () => validateSrcIndexFile(basePath))
47
- await validation('scripts', async () => validateScripts(packageJson))
48
- await validation('nodeEngine', async () => validateNodeEngine(packageJson))
49
- await validation('duplicateConfig', async () =>
50
- disallowDuplicateEslintConfig(basePath, packageJson),
51
- )
52
- await validation('duplicateConfig', async () =>
53
- disallowDuplicatePrettierConfig(basePath, packageJson),
54
- )
55
-
56
- if (ts) {
57
- await validation('tsconfig', async () => validateTsConfig(ts, {basePath, outDir, tsconfig}))
58
- }
59
-
60
- await validation('sanityV2Json', async () => validatePluginSanityJson({basePath, packageJson}))
61
-
62
- await validation('babelConfig', async () => validateBabelConfig({basePath}))
63
-
64
- await validation('dependencies', async () => validateSanityDependencies(packageJson))
65
- await validation('deprecatedDependencies', async () =>
66
- validateDeprecatedDependencies(packageJson),
67
- )
68
- await validation('eslintImports', async () => validateImports({basePath}))
69
-
70
- if (errors.length) {
71
- throw new Error(
72
- outdent`
73
- Detected validation issues!
74
- To make this package Sanity v3 compatible, fix the issues starting from the top, or disable any checks you deem unnecessary.
75
-
76
- These issues assume the package uses @sanity/plugin-kit defaults for development and building.
77
- Refer to ${urls.pluginReadme} for configuration options.
78
-
79
- More information is available here:
80
- - Studio migration guide: ${urls.migrationGuideStudio}
81
- - Plugin migration guide: ${urls.migrationGuidePlugin}
82
- - Reference documentation: ${urls.refDocs}
83
-
84
- ${chalk.grey(
85
- `To fail-fast on first detected issue run:\nnpx ${cliName} verify-package' --single`,
86
- )}
87
- `.trimStart(),
88
- )
89
- }
90
-
91
- await runTscMaybe(verifyConfig, ts)
92
-
93
- log.success(
94
- outdent`
95
- No outstanding upgrade issues detected.
96
-
97
- Suggested next steps:
98
- - Use plugin-kit to build and develop the plugin according to ${urls.pluginReadme}.
99
- - Build the plugin and fix any compilation errors
100
- - Test the plugin using the link-watch command
101
- `.trim(),
102
- )
103
- }