@sanity/plugin-kit 3.1.11 → 3.1.13-canary.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 (61) hide show
  1. package/assets/inject/semver-workflow/.github/workflows/main.yml +6 -6
  2. package/dist/_chunks-cjs/cli.js +135 -0
  3. package/dist/_chunks-cjs/cli.js.map +1 -0
  4. package/dist/_chunks-cjs/init.js +894 -0
  5. package/dist/_chunks-cjs/init.js.map +1 -0
  6. package/dist/_chunks-cjs/init2.js +83 -0
  7. package/dist/_chunks-cjs/init2.js.map +1 -0
  8. package/dist/_chunks-cjs/inject.js +54 -0
  9. package/dist/_chunks-cjs/inject.js.map +1 -0
  10. package/dist/_chunks-cjs/link-watch.js +84 -0
  11. package/dist/_chunks-cjs/link-watch.js.map +1 -0
  12. package/dist/_chunks-cjs/package.js +1808 -0
  13. package/dist/_chunks-cjs/package.js.map +1 -0
  14. package/dist/_chunks-cjs/package2.js +143 -0
  15. package/dist/_chunks-cjs/package2.js.map +1 -0
  16. package/dist/_chunks-cjs/ts.js +162 -0
  17. package/dist/_chunks-cjs/ts.js.map +1 -0
  18. package/dist/_chunks-cjs/verify-package.js +75 -0
  19. package/dist/_chunks-cjs/verify-package.js.map +1 -0
  20. package/dist/_chunks-cjs/verify-studio.js +57 -0
  21. package/dist/_chunks-cjs/verify-studio.js.map +1 -0
  22. package/dist/_chunks-cjs/version.js +51 -0
  23. package/dist/_chunks-cjs/version.js.map +1 -0
  24. package/dist/cli.d.ts +4 -0
  25. package/dist/cli.js +4 -7
  26. package/dist/cli.js.map +1 -1
  27. package/dist/index.js +1 -1
  28. package/package.json +57 -59
  29. package/src/actions/inject.ts +1 -1
  30. package/src/actions/verify/types.ts +0 -1
  31. package/src/actions/verify/validations.ts +13 -69
  32. package/src/actions/verify/verify-common.ts +0 -1
  33. package/src/actions/verify-package.ts +0 -2
  34. package/src/cli.ts +1 -0
  35. package/src/configs/forced-package-versions.ts +0 -1
  36. package/src/configs/pkg-config.ts +0 -1
  37. package/src/configs/tsconfig.ts +20 -21
  38. package/src/npm/package.ts +6 -17
  39. package/src/presets/ui.ts +0 -1
  40. package/dist/_chunks/cli-Wd1KIVDi.js +0 -168
  41. package/dist/_chunks/cli-Wd1KIVDi.js.map +0 -1
  42. package/dist/_chunks/init-5h0qT4Si.js +0 -966
  43. package/dist/_chunks/init-5h0qT4Si.js.map +0 -1
  44. package/dist/_chunks/init-7PO3ckQZ.js +0 -104
  45. package/dist/_chunks/init-7PO3ckQZ.js.map +0 -1
  46. package/dist/_chunks/inject-dEkit_VE.js +0 -49
  47. package/dist/_chunks/inject-dEkit_VE.js.map +0 -1
  48. package/dist/_chunks/link-watch-gjJZIMKf.js +0 -91
  49. package/dist/_chunks/link-watch-gjJZIMKf.js.map +0 -1
  50. package/dist/_chunks/package-esTAlA-W.js +0 -155
  51. package/dist/_chunks/package-esTAlA-W.js.map +0 -1
  52. package/dist/_chunks/package-yXL1pPXe.js +0 -2358
  53. package/dist/_chunks/package-yXL1pPXe.js.map +0 -1
  54. package/dist/_chunks/ts-DjETsLGv.js +0 -165
  55. package/dist/_chunks/ts-DjETsLGv.js.map +0 -1
  56. package/dist/_chunks/verify-package-8RX50rZW.js +0 -97
  57. package/dist/_chunks/verify-package-8RX50rZW.js.map +0 -1
  58. package/dist/_chunks/verify-studio-ybZTH8nM.js +0 -74
  59. package/dist/_chunks/verify-studio-ybZTH8nM.js.map +0 -1
  60. package/dist/_chunks/version-VsJ55gag.js +0 -54
  61. package/dist/_chunks/version-VsJ55gag.js.map +0 -1
@@ -0,0 +1,894 @@
1
+ "use strict";
2
+ var path = require("path"), licenses = require("@rexxars/choosealicense-list"), gitRemoteOriginUrl = require("git-remote-origin-url"), cli = require("./cli.js"), xdgBasedir = require("xdg-basedir"), gitUserInfo = require("git-user-info"), emailValidator = require("email-validator"), _package$1 = require("./package.js"), getIt = require("get-it"), middleware = require("get-it/middleware"), _package = require("./package2.js"), outdent = require("outdent"), chalk = require("chalk");
3
+ function _interopDefaultCompat(e) {
4
+ return e && typeof e == "object" && "default" in e ? e : { default: e };
5
+ }
6
+ var path__default = /* @__PURE__ */ _interopDefaultCompat(path), licenses__default = /* @__PURE__ */ _interopDefaultCompat(licenses), gitRemoteOriginUrl__default = /* @__PURE__ */ _interopDefaultCompat(gitRemoteOriginUrl), xdgBasedir__default = /* @__PURE__ */ _interopDefaultCompat(xdgBasedir), outdent__default = /* @__PURE__ */ _interopDefaultCompat(outdent), chalk__default = /* @__PURE__ */ _interopDefaultCompat(chalk);
7
+ const request = getIt.getIt([
8
+ middleware.promise({ onlyBody: !0 }),
9
+ middleware.jsonRequest(),
10
+ middleware.jsonResponse(),
11
+ middleware.httpErrors(),
12
+ middleware.headers({ "User-Agent": `${_package.pkg.name}@${_package.pkg.version}` })
13
+ ]);
14
+ async function getUserInfo({ requireUserConfirmation, flags }, pkg) {
15
+ const userInfo = getPackageUserInfo({ author: flags.author ?? pkg?.author }) || await getSanityUserInfo() || await getGitUserInfo();
16
+ return requireUserConfirmation ? promptForInfo(userInfo) : userInfo;
17
+ }
18
+ function getPackageUserInfo(pkg) {
19
+ let author = pkg?.author;
20
+ if (!author)
21
+ return;
22
+ if (author && typeof author != "string")
23
+ return author;
24
+ if (!author.includes("@"))
25
+ return { name: author };
26
+ const [pre, ...post] = author.replace(/[<>[\]]/g, "").split(/@/), nameParts = pre.split(/\s+/), email = [nameParts[nameParts.length - 1], ...post].join("@");
27
+ return { name: nameParts.slice(0, -1).join(" "), email };
28
+ }
29
+ async function promptForInfo(defValue) {
30
+ const name = await _package$1.prompt("Author name", {
31
+ filter: filterString,
32
+ default: defValue && defValue.name,
33
+ validate: requiredString
34
+ }), email = await _package$1.prompt("Author email", {
35
+ filter: filterString,
36
+ default: defValue && defValue.email,
37
+ validate: validOrEmptyEmail
38
+ });
39
+ return { name, email };
40
+ }
41
+ async function getSanityUserInfo() {
42
+ try {
43
+ const token = (await _package$1.readJsonFile(
44
+ path__default.default.join(xdgBasedir__default.default.config ?? "", "sanity", "config.json")
45
+ ))?.authToken;
46
+ if (!token)
47
+ return;
48
+ const user = await request({
49
+ url: "https://api.sanity.io/v1/users/me",
50
+ headers: { Authorization: `Bearer ${token}` }
51
+ });
52
+ if (!user)
53
+ return;
54
+ const { name, email } = user;
55
+ return { name, email };
56
+ } catch {
57
+ return;
58
+ }
59
+ }
60
+ async function getGitUserInfo() {
61
+ const user = await gitUserInfo.getGitUserInfo();
62
+ return user ? { name: user.name, email: user.email } : void 0;
63
+ }
64
+ function filterString(val) {
65
+ return (val || "").trim();
66
+ }
67
+ function requiredString(value) {
68
+ return value.length > 1 ? !0 : "Required";
69
+ }
70
+ function validOrEmptyEmail(value) {
71
+ return value ? emailValidator.validate(value) ? !0 : "Must either be a valid email or empty" : !0;
72
+ }
73
+ function generateReadme(data) {
74
+ const { user, pluginName, license, description } = data;
75
+ return outdent__default.default`
76
+ # ${pluginName}
77
+
78
+ ${v3BannerNotice()}
79
+
80
+ ${installationSnippet(pluginName ?? "unknown")}
81
+
82
+ ## Usage
83
+
84
+ Add it as a plugin in \`sanity.config.ts\` (or .js):
85
+
86
+ \`\`\`ts
87
+ import {defineConfig} from 'sanity'
88
+ import {myPlugin} from '${pluginName}'
89
+
90
+ export default defineConfig({
91
+ //...
92
+ plugins: [myPlugin({})],
93
+ })
94
+ \`\`\`
95
+
96
+ ${getLicenseText(license?.id, user?.name ? user : void 0)}
97
+ ${developTestSnippet()}
98
+ ` + `
99
+ `;
100
+ }
101
+ function v3BannerNotice() {
102
+ return "> This is a **Sanity Studio v3** plugin.";
103
+ }
104
+ function installationSnippet(packageName) {
105
+ return outdent__default.default`
106
+ ## Installation
107
+
108
+ \`\`\`sh
109
+ npm install ${packageName}
110
+ \`\`\`
111
+ `;
112
+ }
113
+ function developTestSnippet() {
114
+ return outdent__default.default`
115
+ ## Develop & test
116
+
117
+ This plugin uses [@sanity/plugin-kit](https://github.com/sanity-io/plugin-kit)
118
+ with default configuration for build & watch scripts.
119
+
120
+ See [Testing a plugin in Sanity Studio](https://github.com/sanity-io/plugin-kit#testing-a-plugin-in-sanity-studio)
121
+ on how to run this plugin with hotreload in the studio.
122
+ `;
123
+ }
124
+ function getLicenseText(licenseId, user) {
125
+ if (!licenseId)
126
+ return "";
127
+ let licenseName = licenses__default.default.find(licenseId).title;
128
+ licenseName = licenseName?.replace(/\s+license$/i, "");
129
+ let licenseText = `## License
130
+ `;
131
+ return licenseName && user?.name ? licenseText = `${licenseText}
132
+ [${licenseName}](LICENSE) \xA9 ${user?.name}
133
+ ` : licenseName ? licenseText = `${licenseText}
134
+ [${licenseName}](LICENSE)
135
+ ` : licenseText = `${licenseText}
136
+ See [LICENSE](LICENSE)`, licenseText;
137
+ }
138
+ function isDefaultGitHubReadme(readme) {
139
+ if (!readme)
140
+ return !1;
141
+ const lines = readme.split(`
142
+ `, 20).filter(Boolean);
143
+ return lines.length <= 2 && lines[0].startsWith("#");
144
+ }
145
+ const semverWorkflowPreset = {
146
+ name: "semver-workflow",
147
+ description: "Files and dependencies for conventional-commits, github workflow and semantic-release.",
148
+ apply: applyPreset$3
149
+ }, info = (write, msg, ...args) => write && cli.log.info(msg, ...args);
150
+ async function applyPreset$3(options) {
151
+ await writeAssets(semverWorkflowFiles(), options), await addPrepareScript(options), await addDevDependencies$2(options), await updateReadme(options);
152
+ }
153
+ async function addPrepareScript(options) {
154
+ const pkg = await _package$1.getPackage(options), didWrite = await _package$1.addPackageJsonScripts(pkg, options, (scripts) => (scripts.prepare = _package$1.addScript("husky install", scripts.prepare), scripts));
155
+ info(didWrite, "Added prepare script to package.json");
156
+ }
157
+ async function addDevDependencies$2(options) {
158
+ const pkg = await _package$1.getPackage(options), devDeps = _package$1.sortKeys({
159
+ ...pkg.devDependencies,
160
+ ...await semverWorkflowDependencies()
161
+ }), newPkg = { ...pkg };
162
+ newPkg.devDependencies = devDeps, await _package$1.writePackageJsonDirect(newPkg, options), cli.log.info("Updated devDependencies."), cli.log.info(
163
+ chalk__default.default.green(
164
+ outdent__default.default`
165
+ semantic-release preset injected.
166
+
167
+ Please confer
168
+ https://github.com/sanity-io/plugin-kit/blob/main/docs/semver-workflow.md#manual-steps-after-inject
169
+ to finalize configuration for this preset.
170
+ `.trim()
171
+ )
172
+ );
173
+ }
174
+ async function updateReadme(options) {
175
+ const { basePath } = options, readmePath = path__default.default.join(basePath, "README.md"), readme = await _package$1.readFile(readmePath, "utf8").catch(_package$1.errorToUndefined) ?? "", { v3Banner, install, usage, developTest, license, releaseSnippet } = await readmeSnippets(options), prependSections = missingSections(readme, [v3Banner, install, usage]), appendSections = missingSections(readme, [license, developTest, releaseSnippet]);
176
+ if (prependSections.length || appendSections.length) {
177
+ const updatedReadme = [...prependSections, readme, ...appendSections].filter(Boolean).join(`
178
+
179
+ `);
180
+ await _package$1.writeFile(readmePath, updatedReadme, { encoding: "utf8" }), cli.log.info("Updated README. Please review the changes.");
181
+ }
182
+ }
183
+ async function readmeSnippets(options) {
184
+ const pkg = await _package$1.getPackage(options), user = await getUserInfo(options, pkg), bestEffortUrl = readmeBaseurl(pkg), install = installationSnippet(pkg.name ?? "unknown"), usage = outdent__default.default`
185
+ ## Usage
186
+ `, license = getLicenseText(typeof pkg.license == "string" ? pkg.license : void 0, user), releaseSnippet = outdent__default.default`
187
+ ### Release new version
188
+
189
+ Run ["CI & Release" workflow](${bestEffortUrl}/actions/workflows/main.yml).
190
+ Make sure to select the main branch and check "Release new version".
191
+
192
+ Semantic release will only release on configured branches, so it is safe to run release on any branch.
193
+ `;
194
+ return {
195
+ v3Banner: v3BannerNotice(),
196
+ install,
197
+ usage,
198
+ license,
199
+ developTest: developTestSnippet(),
200
+ releaseSnippet
201
+ };
202
+ }
203
+ function missingSections(readme, sections) {
204
+ return sections.filter((section) => !closeEnough(section, readme));
205
+ }
206
+ function closeEnough(a, b) {
207
+ const aLines = a.split(`
208
+ `), bLines = b.split(`
209
+ `);
210
+ return aLines.filter((line) => bLines.find((bLine) => bLine === line)).length >= aLines.length * 0.5;
211
+ }
212
+ function semverWorkflowFiles() {
213
+ return [
214
+ {
215
+ type: "copy",
216
+ from: [".github", "workflows", "main.yml"],
217
+ to: [".github", "workflows", "main.yml"]
218
+ },
219
+ { type: "copy", from: [".husky", "commit-msg"], to: [".husky", "commit-msg"] },
220
+ { type: "copy", from: [".husky", "pre-commit"], to: [".husky", "pre-commit"] },
221
+ { type: "copy", from: [".releaserc.json"], to: ".releaserc.json" },
222
+ { type: "copy", from: ["commitlint.template.js"], to: "commitlint.config.js" },
223
+ { type: "copy", from: ["lint-staged.template.js"], to: "lint-staged.config.js" }
224
+ ].map((fromTo) => fromTo.type === "copy" ? {
225
+ ...fromTo,
226
+ from: ["semver-workflow", ...fromTo.from]
227
+ } : fromTo);
228
+ }
229
+ async function semverWorkflowDependencies() {
230
+ return _package$1.resolveLatestVersions([
231
+ "@commitlint/cli",
232
+ "@commitlint/config-conventional",
233
+ "@sanity/semantic-release-preset",
234
+ "husky",
235
+ "lint-staged"
236
+ ]);
237
+ }
238
+ function readmeBaseurl(pkg) {
239
+ return (pkg.repository?.url ?? pkg.homepage ?? "TODO").replace(/.+:\/\//g, "https://").replace(/\.git/g, "").replace(/git@github.com\//g, "github.com/").replace(/git@github.com:/g, "https://github.com/").replace(/#.+/g, "");
240
+ }
241
+ const renovatePreset = {
242
+ name: "renovatebot",
243
+ description: "Files to enable renovatebot.",
244
+ apply: applyPreset$2
245
+ };
246
+ async function applyPreset$2(options) {
247
+ await writeAssets(
248
+ [
249
+ {
250
+ type: "copy",
251
+ from: ["renovatebot", "renovate.json"],
252
+ to: "renovate.json"
253
+ }
254
+ ],
255
+ options
256
+ );
257
+ }
258
+ const ui = {
259
+ name: "ui",
260
+ description: "`@sanity/ui` and dependencies",
261
+ apply: applyPreset$1
262
+ };
263
+ async function applyPreset$1(options) {
264
+ await addDependencies(options), await addDevDependencies$1(options), cli.log.info(chalk__default.default.green("ui preset injected"));
265
+ }
266
+ async function addDependencies(options) {
267
+ const pkg = await _package$1.getPackage(options), newDeps = _package$1.sortKeys(
268
+ _package$1.forceDependencyVersions(
269
+ {
270
+ ...pkg.dependencies,
271
+ ...await resolveDependencyList()
272
+ },
273
+ _package$1.forcedPackageVersions
274
+ )
275
+ ), newPkg = { ...pkg };
276
+ newPkg.dependencies = newDeps, await _package$1.writePackageJsonDirect(newPkg, options), cli.log.info("Updated dependencies.");
277
+ }
278
+ async function addDevDependencies$1(options) {
279
+ const pkg = await _package$1.getPackage(options), newDeps = _package$1.sortKeys(
280
+ _package$1.forceDependencyVersions(
281
+ {
282
+ ...pkg.devDependencies,
283
+ ...await resolveDevDependencyList()
284
+ },
285
+ _package$1.forcedDevPackageVersions
286
+ )
287
+ ), newPkg = { ...pkg };
288
+ newPkg.devDependencies = newDeps, await _package$1.writePackageJsonDirect(newPkg, options), cli.log.info("Updated devDependencies.");
289
+ }
290
+ async function resolveDependencyList() {
291
+ return _package$1.resolveLatestVersions(["@sanity/icons", "@sanity/ui"]);
292
+ }
293
+ async function resolveDevDependencyList() {
294
+ return _package$1.resolveLatestVersions([
295
+ // install the peer dependencies of `@sanity/ui` as dev dependencies
296
+ "react",
297
+ "react-dom",
298
+ "styled-components"
299
+ ]);
300
+ }
301
+ const uiWorkshop = {
302
+ name: "ui-workshop",
303
+ description: "Files for testing custom components with @sanity/ui-workshop",
304
+ apply: applyPreset
305
+ };
306
+ async function applyPreset(options) {
307
+ await writeAssets(files(), options), await addDevDependencies(options), await updateGitIgnore(options), cli.log.info(
308
+ chalk__default.default.green(
309
+ outdent__default.default`
310
+ ui-workshop preset injected.
311
+
312
+ Please confer
313
+ https://github.com/sanity-io/plugin-kit/blob/main/docs/ui-workshop.md#manual-steps-after-inject
314
+ to finalize configuration for this preset.
315
+ `.trim()
316
+ )
317
+ );
318
+ }
319
+ function files() {
320
+ return [
321
+ { type: "copy", from: ["workshop.config.ts"], to: ["workshop.config.ts"] },
322
+ { type: "copy", from: ["src", "CustomField.tsx"], to: ["src", "CustomField.tsx"] },
323
+ {
324
+ type: "copy",
325
+ from: ["src", "__workshop__", "index.tsx"],
326
+ to: ["src", "__workshop__", "index.tsx"]
327
+ },
328
+ {
329
+ type: "copy",
330
+ from: ["src", "__workshop__", "props.tsx"],
331
+ to: ["src", "__workshop__", "props.tsx"]
332
+ }
333
+ ].map((fromTo) => fromTo.type === "copy" ? {
334
+ ...fromTo,
335
+ from: ["ui-workshop", ...fromTo.from]
336
+ } : fromTo);
337
+ }
338
+ async function updateGitIgnore(options) {
339
+ const { basePath } = options, gitignorePath = path__default.default.join(basePath, ".gitignore");
340
+ let gitignore = await _package$1.readFile(gitignorePath, "utf8").catch(_package$1.errorToUndefined) ?? "";
341
+ const value = ".workshop";
342
+ gitignore.includes(value) || (gitignore += `
343
+
344
+ ${value}`, await _package$1.writeFile(gitignorePath, gitignore, { encoding: "utf8" }));
345
+ }
346
+ async function addDevDependencies(options) {
347
+ const pkg = await _package$1.getPackage(options), devDeps = _package$1.sortKeys({
348
+ ...pkg.devDependencies,
349
+ ...await devDependencies()
350
+ }), newPkg = { ...pkg };
351
+ newPkg.devDependencies = devDeps, await _package$1.writePackageJsonDirect(newPkg, options), cli.log.info("Updated devDependencies.");
352
+ }
353
+ async function devDependencies() {
354
+ return _package$1.resolveLatestVersions([
355
+ "@sanity/ui-workshop",
356
+ "@sanity/icons",
357
+ "@sanity/ui",
358
+ "react",
359
+ "react-dom",
360
+ "styled-components"
361
+ ]);
362
+ }
363
+ const presets = [semverWorkflowPreset, renovatePreset, ui, uiWorkshop], presetNames = presets.map((p) => p?.name);
364
+ function presetHelpList(padStart) {
365
+ return presets.map((p) => `${"".padStart(padStart)}${p.name.padEnd(20)}${p.description}`).join(`
366
+ `);
367
+ }
368
+ async function injectPresets(options) {
369
+ if (options.flags.presetOnly && !options.flags.preset?.length)
370
+ throw new Error("--preset-only, but no --preset [preset-name] was provided.");
371
+ const applyPresets = presetsFromInput(options.flags.preset);
372
+ for (const preset of applyPresets)
373
+ await preset.apply(options);
374
+ }
375
+ function presetsFromInput(inputPresets) {
376
+ if (!inputPresets)
377
+ return [];
378
+ const unknownPresets = inputPresets.filter((p) => !presetNames.includes(p));
379
+ if (unknownPresets.length)
380
+ throw new Error(
381
+ `Unknown --preset(s): [${unknownPresets.join(", ")}]. Must be one of: [${presetNames.join(
382
+ ", "
383
+ )}]`
384
+ );
385
+ return inputPresets.filter(onlyUnique).map((presetName) => presets.find((p) => p.name === presetName)).filter((p) => !!p);
386
+ }
387
+ function onlyUnique(value, index, arr) {
388
+ return arr.indexOf(value) === index;
389
+ }
390
+ function tsconfigTemplate(options) {
391
+ const { flags } = options;
392
+ return {
393
+ type: "template",
394
+ force: flags.force,
395
+ to: "tsconfig.json",
396
+ value: outdent.outdent`
397
+ {
398
+ "extends": "./tsconfig.settings",
399
+ "include": ["./src", "./package.config.ts"]
400
+ }
401
+ `
402
+ };
403
+ }
404
+ function tsconfigTemplateDist(options) {
405
+ const { flags, outDir } = options;
406
+ return {
407
+ type: "template",
408
+ force: flags.force,
409
+ to: `tsconfig.${outDir}.json`,
410
+ value: outdent.outdent`
411
+ {
412
+ "extends": "./tsconfig.settings",
413
+ "include": ["./src"],
414
+ "exclude": [
415
+ "./src/**/__fixtures__",
416
+ "./src/**/__mocks__",
417
+ "./src/**/*.test.ts",
418
+ "./src/**/*.test.tsx"
419
+ ]
420
+ }
421
+ `
422
+ };
423
+ }
424
+ function tsconfigTemplateSettings(options) {
425
+ const { flags, outDir } = options;
426
+ return {
427
+ type: "template",
428
+ force: flags.force,
429
+ to: "tsconfig.settings.json",
430
+ value: outdent.outdent`
431
+ {
432
+ "compilerOptions": {
433
+ "rootDir": ".",
434
+ "outDir": "./${outDir}",
435
+
436
+ "target": "esnext",
437
+ "jsx": "preserve",
438
+ "module": "preserve",
439
+ "moduleResolution": "bundler",
440
+ "esModuleInterop": true,
441
+ "resolveJsonModule": true,
442
+ "moduleDetection": "force",
443
+ "strict": true,
444
+ "allowSyntheticDefaultImports": true,
445
+ "skipLibCheck": true,
446
+ "forceConsistentCasingInFileNames": true,
447
+ "isolatedModules": true,
448
+
449
+ // Don't emit by default, pkg-utils will ignore this when generating .d.ts files
450
+ "noEmit": true
451
+ }
452
+ }
453
+ `
454
+ };
455
+ }
456
+ function pkgConfigTemplate(options) {
457
+ const { flags, outDir } = options;
458
+ return {
459
+ type: "template",
460
+ force: flags.force,
461
+ to: flags.typescript ? "package.config.ts" : "package.config.js",
462
+ value: outdent.outdent`
463
+ import {defineConfig} from '@sanity/pkg-utils'
464
+
465
+ export default defineConfig({
466
+ dist: '${outDir}',
467
+ tsconfig: 'tsconfig.${outDir}.json',
468
+
469
+ // Remove this block to enable strict export validation
470
+ extract: {
471
+ rules: {
472
+ 'ae-forgotten-export': 'off',
473
+ 'ae-incompatible-release-tags': 'off',
474
+ 'ae-internal-missing-underscore': 'off',
475
+ 'ae-missing-release-tag': 'off',
476
+ },
477
+ },
478
+ })
479
+ `
480
+ };
481
+ }
482
+ function gitignoreTemplate() {
483
+ return {
484
+ type: "template",
485
+ to: ".gitignore",
486
+ value: outdent.outdent`
487
+ # Logs
488
+ logs
489
+ *.log
490
+ npm-debug.log*
491
+
492
+ # Runtime data
493
+ pids
494
+ *.pid
495
+ *.seed
496
+
497
+ # Directory for instrumented libs generated by jscoverage/JSCover
498
+ lib-cov
499
+
500
+ # Coverage directory used by tools like istanbul
501
+ coverage
502
+
503
+ # nyc test coverage
504
+ .nyc_output
505
+
506
+ # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
507
+ .grunt
508
+
509
+ # node-waf configuration
510
+ .lock-wscript
511
+
512
+ # Compiled binary addons (http://nodejs.org/api/addons.html)
513
+ build/Release
514
+
515
+ # Dependency directories
516
+ node_modules
517
+ jspm_packages
518
+
519
+ # Optional npm cache directory
520
+ .npm
521
+
522
+ # Optional REPL history
523
+ .node_repl_history
524
+
525
+ # macOS finder cache file
526
+ .DS_Store
527
+
528
+ # VS Code settings
529
+ .vscode
530
+
531
+ # IntelliJ
532
+ .idea
533
+ *.iml
534
+
535
+ # Cache
536
+ .cache
537
+
538
+ # Yalc
539
+ .yalc
540
+ yalc.lock
541
+
542
+ # npm package zips
543
+ *.tgz
544
+ `
545
+ };
546
+ }
547
+ function eslintrcTemplate(options) {
548
+ const { flags } = options, eslintConfig = {
549
+ root: !0,
550
+ env: {
551
+ node: !0,
552
+ browser: !0
553
+ },
554
+ extends: [
555
+ "sanity",
556
+ flags.typescript && "sanity/typescript",
557
+ "sanity/react",
558
+ "plugin:react-hooks/recommended",
559
+ flags.prettier && "plugin:prettier/recommended",
560
+ "plugin:react/jsx-runtime"
561
+ ].filter(Boolean)
562
+ };
563
+ return {
564
+ type: "template",
565
+ force: flags.force,
566
+ to: ".eslintrc",
567
+ value: JSON.stringify(eslintConfig, null, 2)
568
+ };
569
+ }
570
+ function eslintignoreTemplate(options) {
571
+ const { flags, outDir } = options, patterns = [
572
+ ".eslintrc.js",
573
+ "commitlint.config.js",
574
+ outDir,
575
+ "lint-staged.config.js",
576
+ flags.typescript ? "package.config.ts" : "package.config.js",
577
+ flags.typescript ? "*.js" : ""
578
+ ].filter(Boolean);
579
+ return patterns.sort(), {
580
+ type: "template",
581
+ force: flags.force,
582
+ to: ".eslintignore",
583
+ value: patterns.join(`
584
+ `)
585
+ };
586
+ }
587
+ function prettierignoreTemplate(options) {
588
+ const { outDir } = options;
589
+ return {
590
+ type: "template",
591
+ to: ".prettierignore",
592
+ value: [outDir, "pnpm-lock.yaml", "yarn.lock", "package-lock.json"].join(`
593
+ `)
594
+ };
595
+ }
596
+ const bannedFields = ["login", "description", "projecturl", "email"], preferredLicenses = ["MIT", "ISC", "BSD-3-Clause"], otherLicenses = Object.keys(licenses__default.default.list).filter((id) => {
597
+ const license = licenses__default.default.list[id];
598
+ return !preferredLicenses.includes(id) && !bannedFields.some((field) => license.body.includes(`[${field}]`));
599
+ });
600
+ async function inject(options) {
601
+ options.flags.presetOnly ? cli.log.info("Only apply presets, skipping default inject.") : await injectBase(options), await injectPresets(options);
602
+ }
603
+ async function injectBase(options) {
604
+ const { basePath, flags, requireUserConfirmation } = options, info2 = (write, msg, ...args) => write && cli.log.info(msg, ...args), pkg = await _package$1.getPackage(options).catch(_package$1.errorToUndefined);
605
+ cli.log.debug("Plugin has package.json: %s", pkg ? "yes" : "no");
606
+ const user = await getUserInfo(options, pkg);
607
+ cli.log.debug("User information: %o", user);
608
+ const pkgName = flags.name ?? pkg?.name, pluginName = requireUserConfirmation || !pkgName ? await _package$1.promptForPackageName(options, pkgName) : pkgName;
609
+ cli.log.debug("Plugin name: %s", pluginName);
610
+ const license = await getLicense(flags, { user, pluginName, pkg, requireUserConfirmation }), licenseChanged = (pkg && pkg.license) !== (license && license.id);
611
+ cli.log.debug("License: %s", license ? license.id : "<none>");
612
+ const description = await getProjectDescription(basePath, pkg, requireUserConfirmation);
613
+ cli.log.debug("Description: %s", description || "<none>");
614
+ const repoUrl = flags.repo ?? (await gitRemoteOriginUrl__default.default(basePath).catch(_package$1.errorToUndefined) || pkg?.repository?.url), gitOrigin = requireUserConfirmation ? await _package$1.promptForRepoOrigin(options, repoUrl) : repoUrl;
615
+ cli.log.debug("Remote origin: %s", gitOrigin || "<none>");
616
+ const data = { user, pluginName, license, description, pkg, gitOrigin };
617
+ let didWrite;
618
+ const newPkg = await _package$1.writePackageJson(data, options);
619
+ info2(newPkg !== pkg, "Wrote package.json"), data.pkg = newPkg, didWrite = await writeLicense(data, options, licenseChanged), info2(didWrite, "Wrote license file (LICENSE)"), didWrite = await writeReadme(data, options), info2(didWrite, "Wrote readme file (README.md)"), didWrite = await writeStaticAssets(options), info2(didWrite.length > 0, "Wrote static asset files: %s", didWrite.join(", ")), didWrite = await _package$1.addBuildScripts(newPkg, options), info2(didWrite, "Added build scripts to package.json"), didWrite = await addCompileDirToGitIgnore(data, options), info2(didWrite, "Added compilation output directory to .gitignore");
620
+ }
621
+ async function writeReadme(data, options) {
622
+ const { basePath } = options, readmePath = path__default.default.join(basePath, "README.md"), readme = await _package$1.readFile(readmePath, "utf8").catch(_package$1.errorToUndefined);
623
+ return readme && !isDefaultGitHubReadme(readme) ? !1 : (await _package$1.writeFileWithOverwritePrompt(readmePath, generateReadme(data), {
624
+ encoding: "utf8",
625
+ force: options.flags.force
626
+ }), !0);
627
+ }
628
+ async function writeLicense({ license }, options, licenseChanged) {
629
+ const { basePath, flags } = options;
630
+ if (flags.license === !1 || !license)
631
+ return !1;
632
+ const hasLicenseMdFile = await _package$1.fileExists(path__default.default.join(basePath, "LICENSE.md")), licensePath = path__default.default.join(basePath, hasLicenseMdFile ? "LICENSE.md" : "LICENSE");
633
+ return await _package$1.writeFileWithOverwritePrompt(licensePath, license.text, {
634
+ encoding: "utf8",
635
+ default: licenseChanged,
636
+ force: flags.force
637
+ }), !0;
638
+ }
639
+ async function getLicense(flags, {
640
+ user,
641
+ pluginName,
642
+ pkg,
643
+ requireUserConfirmation
644
+ }) {
645
+ const license = await getLicenseIdentifier(flags, pkg, requireUserConfirmation);
646
+ if (!license)
647
+ return;
648
+ const text = license.body.replace(/\[fullname\]/g, user?.name).replace(/\[project\]/g, pluginName).replace(/\[year\]/g, (/* @__PURE__ */ new Date()).getFullYear());
649
+ return { id: license.id, text };
650
+ }
651
+ async function getLicenseIdentifier(flags, pkg, requireUserConfirmation = !1) {
652
+ if (flags.license === !1)
653
+ return null;
654
+ if (typeof flags.license == "string") {
655
+ const license = licenses__default.default.find(`${flags.license}`);
656
+ if (!license)
657
+ throw new Error(`License "${flags.license}" not found`);
658
+ return license;
659
+ }
660
+ if (pkg && pkg.license && !requireUserConfirmation) {
661
+ const license = licenses__default.default.find(`${pkg.license}`);
662
+ if (license)
663
+ return license;
664
+ cli.log.warn(`package.json contains license "${pkg.license}", which is not recognized`);
665
+ }
666
+ const licenseId = await _package$1.prompt("Which license do you want to use?", {
667
+ default: pkg && pkg.license && licenses__default.default.find(pkg.license) ? pkg.license : preferredLicenses[0],
668
+ choices: [
669
+ _package$1.prompt.separator(),
670
+ ...preferredLicenses.map((value) => ({ value, name: licenses__default.default.list[value].title })),
671
+ _package$1.prompt.separator(),
672
+ ...otherLicenses.map((value) => ({ value, name: licenses__default.default.list[value].title }))
673
+ ]
674
+ });
675
+ return licenses__default.default.find(licenseId);
676
+ }
677
+ async function getProjectDescription(basePath, pkg, requireUserConfirmation = !1) {
678
+ let description = await resolveProjectDescription(basePath, pkg);
679
+ return requireUserConfirmation && (description = await _package$1.prompt("Plugin description", { default: description || "" })), description ?? "";
680
+ }
681
+ async function resolveProjectDescription(basePath, pkg) {
682
+ if (pkg && typeof pkg.description == "string" && pkg.description.length > 5)
683
+ return pkg.description;
684
+ try {
685
+ const readmePath = path__default.default.join(basePath, "README.md"), readme = await _package$1.readFile(readmePath, "utf8"), [title, description] = readme.split(`
686
+ `).filter(Boolean);
687
+ if (!title || !description || !title.match(/^#\s+\w+/))
688
+ return null;
689
+ const unlinked = description.replace(/\[(.*?)\]\(.*?\)/g, "$1");
690
+ return /^[^#]/.test(unlinked) ? unlinked : null;
691
+ } catch (err) {
692
+ return _package$1.errorToUndefined(err);
693
+ }
694
+ }
695
+ async function writeAssets(injectables, { basePath, flags }) {
696
+ const assetsDir = await findAssetsDir(), from = (...segments) => path__default.default.join(assetsDir, "inject", ...segments), to = (...segments) => path__default.default.join(basePath, ...segments), writes = [];
697
+ for (const injectable of injectables) {
698
+ if (injectable.type === "copy") {
699
+ const fromPath = asArray(injectable.from), toPath = asArray(injectable.to);
700
+ await _package$1.copyFileWithOverwritePrompt(from(...fromPath), to(...toPath), flags) && writes.push(path__default.default.join(...toPath));
701
+ continue;
702
+ }
703
+ if (injectable.type === "template") {
704
+ const toPath = asArray(injectable.to);
705
+ await _package$1.writeFileWithOverwritePrompt(to(...toPath), `${injectable.value.trim()}
706
+ `, {
707
+ default: "n",
708
+ force: injectable.force || flags.force
709
+ }), writes.push(path__default.default.join(...toPath));
710
+ continue;
711
+ }
712
+ throw new Error(`Unknown operation type "${injectable.type}"`);
713
+ }
714
+ return writes;
715
+ }
716
+ async function writeStaticAssets(options) {
717
+ const { outDir, flags } = options, files2 = [
718
+ flags.eslint && eslintrcTemplate({ flags: options.flags }),
719
+ flags.eslint && eslintignoreTemplate({ outDir, flags: options.flags }),
720
+ { type: "copy", from: "editorconfig", to: ".editorconfig" },
721
+ { type: "copy", from: "sanity.json", to: "sanity.json" },
722
+ { type: "copy", from: "v2-incompatible.js.template", to: "v2-incompatible.js" },
723
+ pkgConfigTemplate({ outDir, flags: options.flags }),
724
+ flags.gitignore && gitignoreTemplate(),
725
+ flags.typescript && tsconfigTemplate({ flags: options.flags }),
726
+ flags.typescript && tsconfigTemplateDist({ outDir, flags: options.flags }),
727
+ flags.typescript && tsconfigTemplateSettings({ outDir, flags: options.flags }),
728
+ flags.prettier && prettierignoreTemplate({ outDir }),
729
+ flags.prettier && { type: "copy", from: "prettierrc.json", to: ".prettierrc" }
730
+ ].map((f) => f || void 0).filter((f) => !!f);
731
+ return writeAssets(files2, options);
732
+ }
733
+ function asArray(input) {
734
+ return typeof input == "string" ? [input] : input;
735
+ }
736
+ async function findAssetsDir() {
737
+ let maxBackpaddle = 3, currDir = __dirname, assetsDir = "";
738
+ for (; !assetsDir && maxBackpaddle; ) {
739
+ currDir = path__default.default.join(currDir, "..");
740
+ const assets = path__default.default.join(currDir, "assets");
741
+ await _package$1.fileExists(assets) ? assetsDir = assets : maxBackpaddle--;
742
+ }
743
+ if (!assetsDir)
744
+ throw new Error("Could not find assets directory!");
745
+ return assetsDir;
746
+ }
747
+ async function addCompileDirToGitIgnore(data, options) {
748
+ const gitIgnorePath = path__default.default.join(options.basePath, ".gitignore"), gitignore = await _package$1.readFile(gitIgnorePath, "utf8").catch(_package$1.errorToUndefined);
749
+ if (!gitignore)
750
+ return !1;
751
+ const output = data.pkg?.main ?? data.pkg?.module;
752
+ if (!output)
753
+ return !1;
754
+ const ignore = output.replace(/^[./]+/, "").split("/")[0];
755
+ if (!ignore)
756
+ return !1;
757
+ const lines = gitignore.trim().split(`
758
+ `);
759
+ return lines.includes(ignore) ? !1 : (lines.push("", "# Compiled plugin", ignore), await _package$1.writeFile(gitIgnorePath, lines.join(`
760
+ `) + `
761
+ `, { encoding: "utf8" }), !0);
762
+ }
763
+ function defaultSourceJs(pkg) {
764
+ return outdent__default.default`
765
+ import {definePlugin} from 'sanity'
766
+
767
+ /**
768
+ * Usage in sanity.config.js (or .ts)
769
+ *
770
+ * \`\`\`js
771
+ * import {defineConfig} from 'sanity'
772
+ * import {myPlugin} from '${pkg.name}'
773
+ *
774
+ * export default defineConfig({
775
+ * // ...
776
+ * plugins: [myPlugin({})],
777
+ * })
778
+ * \`\`\`
779
+ */
780
+ export const myPlugin = definePlugin((config = {}) => {
781
+ // eslint-disable-next-line no-console
782
+ console.log(\`hello from ${pkg.name}\`)
783
+ return {
784
+ name: '${pkg.name}',
785
+ }
786
+ })
787
+ `.trimStart() + `
788
+ `;
789
+ }
790
+ function defaultSourceTs(pkg) {
791
+ return outdent__default.default`
792
+ import {definePlugin} from 'sanity'
793
+
794
+ interface MyPluginConfig {
795
+ /* nothing here yet */
796
+ }
797
+
798
+ /**
799
+ * Usage in \`sanity.config.ts\` (or .js)
800
+ *
801
+ * \`\`\`ts
802
+ * import {defineConfig} from 'sanity'
803
+ * import {myPlugin} from '${pkg.name}'
804
+ *
805
+ * export default defineConfig({
806
+ * // ...
807
+ * plugins: [myPlugin()],
808
+ * })
809
+ * \`\`\`
810
+ */
811
+ export const myPlugin = definePlugin<MyPluginConfig | void>((config = {}) => {
812
+ // eslint-disable-next-line no-console
813
+ console.log('hello from ${pkg.name}')
814
+ return {
815
+ name: '${pkg.name}',
816
+ }
817
+ })
818
+ `.trimStart() + `
819
+ `;
820
+ }
821
+ const initFlags = {
822
+ ...cli.sharedFlags,
823
+ scripts: {
824
+ type: "boolean",
825
+ default: !0
826
+ },
827
+ eslint: {
828
+ type: "boolean",
829
+ default: !0
830
+ },
831
+ typescript: {
832
+ type: "boolean",
833
+ default: !0
834
+ },
835
+ prettier: {
836
+ type: "boolean",
837
+ default: !0
838
+ },
839
+ license: {
840
+ type: "string"
841
+ },
842
+ editorconfig: {
843
+ type: "boolean",
844
+ default: !0
845
+ },
846
+ gitignore: {
847
+ type: "boolean",
848
+ default: !0
849
+ },
850
+ force: {
851
+ type: "boolean",
852
+ default: !1
853
+ },
854
+ install: {
855
+ type: "boolean",
856
+ default: !0
857
+ },
858
+ name: {
859
+ type: "string"
860
+ },
861
+ author: {
862
+ type: "string"
863
+ },
864
+ repo: {
865
+ type: "string"
866
+ },
867
+ presetOnly: {
868
+ type: "boolean",
869
+ default: !1
870
+ },
871
+ preset: {
872
+ type: "string",
873
+ isMultiple: !0
874
+ }
875
+ };
876
+ async function init(options) {
877
+ let dependencies = {}, devDependencies2 = {}, peerDependencies = {};
878
+ await inject({
879
+ ...options,
880
+ outDir: cli.defaultOutDir,
881
+ requireUserConfirmation: !options.flags.force,
882
+ dependencies,
883
+ devDependencies: devDependencies2,
884
+ peerDependencies,
885
+ validate: !1
886
+ });
887
+ const packageJson = await _package$1.getPackage({ basePath: options.basePath, validate: !1 }), typescript = options.flags.typescript, source = typescript ? defaultSourceTs(packageJson) : defaultSourceJs(packageJson), filename = typescript ? "index.ts" : "index.js", srcDir = path__default.default.resolve(options.basePath, "src");
888
+ await _package$1.ensureDir(srcDir), await _package$1.writeFile(path__default.default.join(srcDir, filename), source, { encoding: "utf8" });
889
+ }
890
+ exports.init = init;
891
+ exports.initFlags = initFlags;
892
+ exports.inject = inject;
893
+ exports.presetHelpList = presetHelpList;
894
+ //# sourceMappingURL=init.js.map