@sanity/cli 8.30.0 → 8.32.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +179 -103
- package/bin/run.js +1 -1
- package/dist/actions/context/waitForSourceSync.js +1 -1
- package/dist/actions/context/waitForSourceSync.js.map +1 -1
- package/dist/actions/cors/filterAndValidateOrigin.js +1 -1
- package/dist/actions/cors/filterAndValidateOrigin.js.map +1 -1
- package/dist/actions/deploy/deployApp.js +12 -6
- package/dist/actions/deploy/deployApp.js.map +1 -1
- package/dist/actions/deploy/deployStudio.js +14 -14
- package/dist/actions/deploy/deployStudio.js.map +1 -1
- package/dist/actions/deploy/deployStudioSchemasAndManifests.js +1 -2
- package/dist/actions/deploy/deployStudioSchemasAndManifests.js.map +1 -1
- package/dist/actions/deploy/deployStudioSchemasAndManifestsWorker.js +13 -1
- package/dist/actions/deploy/deployStudioSchemasAndManifestsWorker.js.map +1 -1
- package/dist/actions/deploy/types.js +0 -1
- package/dist/actions/deploy/types.js.map +1 -1
- package/dist/actions/dev/devAction.js +5 -1
- package/dist/actions/dev/devAction.js.map +1 -1
- package/dist/actions/dev/servers/startAppDevServer.js +3 -3
- package/dist/actions/dev/servers/startAppDevServer.js.map +1 -1
- package/dist/actions/dev/servers/startStudioDevServer.js +12 -13
- package/dist/actions/dev/servers/startStudioDevServer.js.map +1 -1
- package/dist/actions/dev/types.js.map +1 -1
- package/dist/actions/documents/validateDocuments.worker.js +2 -1
- package/dist/actions/documents/validateDocuments.worker.js.map +1 -1
- package/dist/actions/graphql/extractFromSanitySchema.js +1 -1
- package/dist/actions/graphql/extractFromSanitySchema.js.map +1 -1
- package/dist/actions/init/initStudio.js +1 -1
- package/dist/actions/init/initStudio.js.map +1 -1
- package/dist/actions/init/processTemplate.js +1 -1
- package/dist/actions/init/processTemplate.js.map +1 -1
- package/dist/actions/init/remoteTemplate.js +1 -1
- package/dist/actions/init/remoteTemplate.js.map +1 -1
- package/dist/actions/manifest/extractManifest.js +2 -1
- package/dist/actions/manifest/extractManifest.js.map +1 -1
- package/dist/actions/manifest/extractStudioManifest.js +1 -0
- package/dist/actions/manifest/extractStudioManifest.js.map +1 -1
- package/dist/actions/media/pullAspects.js +1 -1
- package/dist/actions/media/pullAspects.js.map +1 -1
- package/dist/actions/organizations/readOrganizationLogo.js +49 -0
- package/dist/actions/organizations/readOrganizationLogo.js.map +1 -0
- package/dist/actions/preview/previewAction.js +1 -1
- package/dist/actions/preview/previewAction.js.map +1 -1
- package/dist/actions/skills/readSkillState.js +1 -1
- package/dist/actions/skills/readSkillState.js.map +1 -1
- package/dist/actions/skills/setupSkills.js +1 -1
- package/dist/actions/skills/setupSkills.js.map +1 -1
- package/dist/commands/organizations/create.js +43 -3
- package/dist/commands/organizations/create.js.map +1 -1
- package/dist/commands/organizations/update.js +67 -14
- package/dist/commands/organizations/update.js.map +1 -1
- package/dist/exports/invokeSanityCli/commandPolicies/mcpPolicy.js +7 -2
- package/dist/exports/invokeSanityCli/commandPolicies/mcpPolicy.js.map +1 -1
- package/dist/generated/contextOperations.js +2 -2
- package/dist/generated/contextOperations.js.map +1 -1
- package/dist/hooks/commandNotFound/topicAliases.js +1 -1
- package/dist/hooks/commandNotFound/topicAliases.js.map +1 -1
- package/dist/server/devServer.js +8 -10
- package/dist/server/devServer.js.map +1 -1
- package/dist/services/organizations.js +30 -0
- package/dist/services/organizations.js.map +1 -1
- package/dist/util/telemetry/cliCommandIdentity.js +3 -2
- package/dist/util/telemetry/cliCommandIdentity.js.map +1 -1
- package/dist/util/update/updateChecker.js +1 -1
- package/dist/util/update/updateChecker.js.map +1 -1
- package/oclif.config.js +1 -1
- package/oclif.manifest.json +2892 -2850
- package/package.json +28 -29
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { readFile, stat } from 'node:fs/promises';
|
|
2
|
+
import { extname } from 'node:path';
|
|
3
|
+
// The image formats populus accepts as an organization logo. It needs an image Content-Type, and
|
|
4
|
+
// the CLI has no other source for one.
|
|
5
|
+
const LOGO_CONTENT_TYPES = {
|
|
6
|
+
'.avif': 'image/avif',
|
|
7
|
+
'.bmp': 'image/bmp',
|
|
8
|
+
'.gif': 'image/gif',
|
|
9
|
+
'.heic': 'image/heic',
|
|
10
|
+
'.heif': 'image/heif',
|
|
11
|
+
'.jpeg': 'image/jpeg',
|
|
12
|
+
'.jpg': 'image/jpeg',
|
|
13
|
+
'.png': 'image/png',
|
|
14
|
+
'.svg': 'image/svg+xml',
|
|
15
|
+
'.tif': 'image/tiff',
|
|
16
|
+
'.tiff': 'image/tiff',
|
|
17
|
+
'.webp': 'image/webp'
|
|
18
|
+
};
|
|
19
|
+
// Matches populus's limit, so a large file fails here instead of after uploading it.
|
|
20
|
+
const MAX_LOGO_BYTES = 5 * 1024 * 1024;
|
|
21
|
+
/**
|
|
22
|
+
* Read an image file to upload as an organization's logo. Throws an error a user can act on when
|
|
23
|
+
* the file is missing, isn't a supported image type, or is over 5 MB.
|
|
24
|
+
*/ export async function readOrganizationLogo(filePath) {
|
|
25
|
+
const contentType = LOGO_CONTENT_TYPES[extname(filePath).toLowerCase()];
|
|
26
|
+
if (!contentType) {
|
|
27
|
+
throw new Error(`"${filePath}" isn't a supported image type. Use a PNG, JPEG, GIF, WebP, SVG, BMP, TIFF, HEIF or AVIF file.`);
|
|
28
|
+
}
|
|
29
|
+
let stats;
|
|
30
|
+
try {
|
|
31
|
+
stats = await stat(filePath);
|
|
32
|
+
} catch (error) {
|
|
33
|
+
if (error instanceof Error && 'code' in error && error.code === 'ENOENT') {
|
|
34
|
+
throw new Error(`Couldn't find "${filePath}". Check the path and try again.`, {
|
|
35
|
+
cause: error
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
throw error;
|
|
39
|
+
}
|
|
40
|
+
if (stats.size > MAX_LOGO_BYTES) {
|
|
41
|
+
throw new Error(`"${filePath}" is larger than 5 MB, the limit for a logo. Use a smaller image.`);
|
|
42
|
+
}
|
|
43
|
+
return {
|
|
44
|
+
contentType,
|
|
45
|
+
image: await readFile(filePath)
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
//# sourceMappingURL=readOrganizationLogo.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/organizations/readOrganizationLogo.ts"],"sourcesContent":["import {type Stats} from 'node:fs'\nimport {readFile, stat} from 'node:fs/promises'\nimport {extname} from 'node:path'\n\n// The image formats populus accepts as an organization logo. It needs an image Content-Type, and\n// the CLI has no other source for one.\nconst LOGO_CONTENT_TYPES: Record<string, string> = {\n '.avif': 'image/avif',\n '.bmp': 'image/bmp',\n '.gif': 'image/gif',\n '.heic': 'image/heic',\n '.heif': 'image/heif',\n '.jpeg': 'image/jpeg',\n '.jpg': 'image/jpeg',\n '.png': 'image/png',\n '.svg': 'image/svg+xml',\n '.tif': 'image/tiff',\n '.tiff': 'image/tiff',\n '.webp': 'image/webp',\n}\n\n// Matches populus's limit, so a large file fails here instead of after uploading it.\nconst MAX_LOGO_BYTES = 5 * 1024 * 1024\n\nexport interface OrganizationLogo {\n contentType: string\n image: Buffer\n}\n\n/**\n * Read an image file to upload as an organization's logo. Throws an error a user can act on when\n * the file is missing, isn't a supported image type, or is over 5 MB.\n */\nexport async function readOrganizationLogo(filePath: string): Promise<OrganizationLogo> {\n const contentType = LOGO_CONTENT_TYPES[extname(filePath).toLowerCase()]\n if (!contentType) {\n throw new Error(\n `\"${filePath}\" isn't a supported image type. Use a PNG, JPEG, GIF, WebP, SVG, BMP, TIFF, HEIF or AVIF file.`,\n )\n }\n\n let stats: Stats\n try {\n stats = await stat(filePath)\n } catch (error) {\n if (error instanceof Error && 'code' in error && error.code === 'ENOENT') {\n throw new Error(`Couldn't find \"${filePath}\". Check the path and try again.`, {cause: error})\n }\n throw error\n }\n\n if (stats.size > MAX_LOGO_BYTES) {\n throw new Error(`\"${filePath}\" is larger than 5 MB, the limit for a logo. Use a smaller image.`)\n }\n\n return {contentType, image: await readFile(filePath)}\n}\n"],"names":["readFile","stat","extname","LOGO_CONTENT_TYPES","MAX_LOGO_BYTES","readOrganizationLogo","filePath","contentType","toLowerCase","Error","stats","error","code","cause","size","image"],"mappings":"AACA,SAAQA,QAAQ,EAAEC,IAAI,QAAO,mBAAkB;AAC/C,SAAQC,OAAO,QAAO,YAAW;AAEjC,iGAAiG;AACjG,uCAAuC;AACvC,MAAMC,qBAA6C;IACjD,SAAS;IACT,QAAQ;IACR,QAAQ;IACR,SAAS;IACT,SAAS;IACT,SAAS;IACT,QAAQ;IACR,QAAQ;IACR,QAAQ;IACR,QAAQ;IACR,SAAS;IACT,SAAS;AACX;AAEA,qFAAqF;AACrF,MAAMC,iBAAiB,IAAI,OAAO;AAOlC;;;CAGC,GACD,OAAO,eAAeC,qBAAqBC,QAAgB;IACzD,MAAMC,cAAcJ,kBAAkB,CAACD,QAAQI,UAAUE,WAAW,GAAG;IACvE,IAAI,CAACD,aAAa;QAChB,MAAM,IAAIE,MACR,CAAC,CAAC,EAAEH,SAAS,8FAA8F,CAAC;IAEhH;IAEA,IAAII;IACJ,IAAI;QACFA,QAAQ,MAAMT,KAAKK;IACrB,EAAE,OAAOK,OAAO;QACd,IAAIA,iBAAiBF,SAAS,UAAUE,SAASA,MAAMC,IAAI,KAAK,UAAU;YACxE,MAAM,IAAIH,MAAM,CAAC,eAAe,EAAEH,SAAS,gCAAgC,CAAC,EAAE;gBAACO,OAAOF;YAAK;QAC7F;QACA,MAAMA;IACR;IAEA,IAAID,MAAMI,IAAI,GAAGV,gBAAgB;QAC/B,MAAM,IAAIK,MAAM,CAAC,CAAC,EAAEH,SAAS,iEAAiE,CAAC;IACjG;IAEA,OAAO;QAACC;QAAaQ,OAAO,MAAMf,SAASM;IAAS;AACtD"}
|
|
@@ -20,7 +20,7 @@ export async function previewAction(options) {
|
|
|
20
20
|
const isApp = determineIsApp(cliConfig);
|
|
21
21
|
// Lazy so a non-workbench `sanity start` never loads the package. `doImport`
|
|
22
22
|
// is path-based and doesn't apply to a bare specifier.
|
|
23
|
-
// eslint-disable-next-line no-restricted-syntax
|
|
23
|
+
// eslint-disable-next-line eslint-js/no-restricted-syntax
|
|
24
24
|
const { startWorkbenchPreview } = await import('@sanity/workbench-cli/preview');
|
|
25
25
|
return startWorkbenchPreview({
|
|
26
26
|
cacheDir: `${SANITY_CACHE_DIR}/vite`,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/preview/previewAction.ts"],"sourcesContent":["import {SANITY_CACHE_DIR} from '@sanity/cli-build/_internal/build'\nimport {extractCoreAppManifest} from '@sanity/cli-build/_internal/manifest'\nimport {type CliConfig, type Output} from '@sanity/cli-core'\nimport {isWorkbenchApp} from '@sanity/workbench-cli'\n\nimport {gracefulServerDeath} from '../../server/gracefulServerDeath.js'\nimport {type PreviewServer, startPreviewServer} from '../../server/previewServer.js'\nimport {checkForDeprecatedAppId} from '../../util/appId.js'\nimport {determineIsApp} from '../../util/determineIsApp.js'\nimport {resolveReactStrictMode} from '../../util/resolveReactStrictMode.js'\nimport {extractStudioManifest} from '../manifest/extractStudioManifest.js'\nimport {getPreviewServerConfig} from './getPreviewServerConfig.js'\nimport {type PreviewFlags} from './types.js'\n\ninterface PreviewActionOptions {\n cliConfig: CliConfig\n flags: PreviewFlags\n outDir: string\n output: Output\n workDir: string\n}\n\nexport async function previewAction(\n options: PreviewActionOptions,\n): Promise<PreviewServer | {close: () => Promise<void>}> {\n const {cliConfig, flags, outDir, output, workDir} = options\n\n const config = getPreviewServerConfig({cliConfig, flags, rootDir: outDir, workDir})\n\n if (isWorkbenchApp(cliConfig?.app)) {\n const isApp = determineIsApp(cliConfig)\n // Lazy so a non-workbench `sanity start` never loads the package. `doImport`\n // is path-based and doesn't apply to a bare specifier.\n // eslint-disable-next-line no-restricted-syntax\n const {startWorkbenchPreview} = await import('@sanity/workbench-cli/preview')\n return startWorkbenchPreview({\n cacheDir: `${SANITY_CACHE_DIR}/vite`,\n checkForDeprecatedAppId: () => checkForDeprecatedAppId({cliConfig, output}),\n cliConfig,\n extractManifest: isApp\n ? ({workDir: wd}) => extractCoreAppManifest({workDir: wd})\n : (params) => extractStudioManifest(params),\n httpHost: config.httpHost,\n httpPort: config.httpPort,\n isApp,\n outDir,\n output,\n reactStrictMode: resolveReactStrictMode(cliConfig) ?? false,\n workDir,\n })\n }\n\n try {\n const server = await startPreviewServer(config)\n return server\n } catch (err) {\n throw gracefulServerDeath('preview', config.httpHost, config.httpPort, err)\n }\n}\n"],"names":["SANITY_CACHE_DIR","extractCoreAppManifest","isWorkbenchApp","gracefulServerDeath","startPreviewServer","checkForDeprecatedAppId","determineIsApp","resolveReactStrictMode","extractStudioManifest","getPreviewServerConfig","previewAction","options","cliConfig","flags","outDir","output","workDir","config","rootDir","app","isApp","startWorkbenchPreview","cacheDir","extractManifest","wd","params","httpHost","httpPort","reactStrictMode","server","err"],"mappings":"AAAA,SAAQA,gBAAgB,QAAO,oCAAmC;AAClE,SAAQC,sBAAsB,QAAO,uCAAsC;AAE3E,SAAQC,cAAc,QAAO,wBAAuB;AAEpD,SAAQC,mBAAmB,QAAO,sCAAqC;AACvE,SAA4BC,kBAAkB,QAAO,gCAA+B;AACpF,SAAQC,uBAAuB,QAAO,sBAAqB;AAC3D,SAAQC,cAAc,QAAO,+BAA8B;AAC3D,SAAQC,sBAAsB,QAAO,uCAAsC;AAC3E,SAAQC,qBAAqB,QAAO,uCAAsC;AAC1E,SAAQC,sBAAsB,QAAO,8BAA6B;AAWlE,OAAO,eAAeC,cACpBC,OAA6B;IAE7B,MAAM,EAACC,SAAS,EAAEC,KAAK,EAAEC,MAAM,EAAEC,MAAM,EAAEC,OAAO,EAAC,GAAGL;IAEpD,MAAMM,SAASR,uBAAuB;QAACG;QAAWC;QAAOK,SAASJ;QAAQE;IAAO;IAEjF,IAAId,eAAeU,WAAWO,MAAM;QAClC,MAAMC,QAAQd,eAAeM;QAC7B,6EAA6E;QAC7E,uDAAuD;QACvD,
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/preview/previewAction.ts"],"sourcesContent":["import {SANITY_CACHE_DIR} from '@sanity/cli-build/_internal/build'\nimport {extractCoreAppManifest} from '@sanity/cli-build/_internal/manifest'\nimport {type CliConfig, type Output} from '@sanity/cli-core'\nimport {isWorkbenchApp} from '@sanity/workbench-cli'\n\nimport {gracefulServerDeath} from '../../server/gracefulServerDeath.js'\nimport {type PreviewServer, startPreviewServer} from '../../server/previewServer.js'\nimport {checkForDeprecatedAppId} from '../../util/appId.js'\nimport {determineIsApp} from '../../util/determineIsApp.js'\nimport {resolveReactStrictMode} from '../../util/resolveReactStrictMode.js'\nimport {extractStudioManifest} from '../manifest/extractStudioManifest.js'\nimport {getPreviewServerConfig} from './getPreviewServerConfig.js'\nimport {type PreviewFlags} from './types.js'\n\ninterface PreviewActionOptions {\n cliConfig: CliConfig\n flags: PreviewFlags\n outDir: string\n output: Output\n workDir: string\n}\n\nexport async function previewAction(\n options: PreviewActionOptions,\n): Promise<PreviewServer | {close: () => Promise<void>}> {\n const {cliConfig, flags, outDir, output, workDir} = options\n\n const config = getPreviewServerConfig({cliConfig, flags, rootDir: outDir, workDir})\n\n if (isWorkbenchApp(cliConfig?.app)) {\n const isApp = determineIsApp(cliConfig)\n // Lazy so a non-workbench `sanity start` never loads the package. `doImport`\n // is path-based and doesn't apply to a bare specifier.\n // eslint-disable-next-line eslint-js/no-restricted-syntax\n const {startWorkbenchPreview} = await import('@sanity/workbench-cli/preview')\n return startWorkbenchPreview({\n cacheDir: `${SANITY_CACHE_DIR}/vite`,\n checkForDeprecatedAppId: () => checkForDeprecatedAppId({cliConfig, output}),\n cliConfig,\n extractManifest: isApp\n ? ({workDir: wd}) => extractCoreAppManifest({workDir: wd})\n : (params) => extractStudioManifest(params),\n httpHost: config.httpHost,\n httpPort: config.httpPort,\n isApp,\n outDir,\n output,\n reactStrictMode: resolveReactStrictMode(cliConfig) ?? false,\n workDir,\n })\n }\n\n try {\n const server = await startPreviewServer(config)\n return server\n } catch (err) {\n throw gracefulServerDeath('preview', config.httpHost, config.httpPort, err)\n }\n}\n"],"names":["SANITY_CACHE_DIR","extractCoreAppManifest","isWorkbenchApp","gracefulServerDeath","startPreviewServer","checkForDeprecatedAppId","determineIsApp","resolveReactStrictMode","extractStudioManifest","getPreviewServerConfig","previewAction","options","cliConfig","flags","outDir","output","workDir","config","rootDir","app","isApp","startWorkbenchPreview","cacheDir","extractManifest","wd","params","httpHost","httpPort","reactStrictMode","server","err"],"mappings":"AAAA,SAAQA,gBAAgB,QAAO,oCAAmC;AAClE,SAAQC,sBAAsB,QAAO,uCAAsC;AAE3E,SAAQC,cAAc,QAAO,wBAAuB;AAEpD,SAAQC,mBAAmB,QAAO,sCAAqC;AACvE,SAA4BC,kBAAkB,QAAO,gCAA+B;AACpF,SAAQC,uBAAuB,QAAO,sBAAqB;AAC3D,SAAQC,cAAc,QAAO,+BAA8B;AAC3D,SAAQC,sBAAsB,QAAO,uCAAsC;AAC3E,SAAQC,qBAAqB,QAAO,uCAAsC;AAC1E,SAAQC,sBAAsB,QAAO,8BAA6B;AAWlE,OAAO,eAAeC,cACpBC,OAA6B;IAE7B,MAAM,EAACC,SAAS,EAAEC,KAAK,EAAEC,MAAM,EAAEC,MAAM,EAAEC,OAAO,EAAC,GAAGL;IAEpD,MAAMM,SAASR,uBAAuB;QAACG;QAAWC;QAAOK,SAASJ;QAAQE;IAAO;IAEjF,IAAId,eAAeU,WAAWO,MAAM;QAClC,MAAMC,QAAQd,eAAeM;QAC7B,6EAA6E;QAC7E,uDAAuD;QACvD,0DAA0D;QAC1D,MAAM,EAACS,qBAAqB,EAAC,GAAG,MAAM,MAAM,CAAC;QAC7C,OAAOA,sBAAsB;YAC3BC,UAAU,GAAGtB,iBAAiB,KAAK,CAAC;YACpCK,yBAAyB,IAAMA,wBAAwB;oBAACO;oBAAWG;gBAAM;YACzEH;YACAW,iBAAiBH,QACb,CAAC,EAACJ,SAASQ,EAAE,EAAC,GAAKvB,uBAAuB;oBAACe,SAASQ;gBAAE,KACtD,CAACC,SAAWjB,sBAAsBiB;YACtCC,UAAUT,OAAOS,QAAQ;YACzBC,UAAUV,OAAOU,QAAQ;YACzBP;YACAN;YACAC;YACAa,iBAAiBrB,uBAAuBK,cAAc;YACtDI;QACF;IACF;IAEA,IAAI;QACF,MAAMa,SAAS,MAAMzB,mBAAmBa;QACxC,OAAOY;IACT,EAAE,OAAOC,KAAK;QACZ,MAAM3B,oBAAoB,WAAWc,OAAOS,QAAQ,EAAET,OAAOU,QAAQ,EAAEG;IACzE;AACF"}
|
|
@@ -38,7 +38,7 @@ const debug = subdebug('skills:state');
|
|
|
38
38
|
try {
|
|
39
39
|
// Loaded lazily so a problem with the `skills` package only affects this
|
|
40
40
|
// best-effort probe, not every command that imports this module.
|
|
41
|
-
// eslint-disable-next-line no-restricted-syntax -- package import, not a file path
|
|
41
|
+
// eslint-disable-next-line eslint-js/no-restricted-syntax -- package import, not a file path
|
|
42
42
|
const { listSkills } = await import('skills');
|
|
43
43
|
const result = await listSkills({
|
|
44
44
|
scope: 'global',
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/skills/readSkillState.ts"],"sourcesContent":["import {subdebug} from '@sanity/cli-core'\nimport {type InstalledSkillInfo} from 'skills'\n\nimport {\n getSkillsCliAgentDisplayName,\n getSkillsCliAgentDisplayNameById,\n isUniversalSkillsCliAgentByEditorName,\n UNIVERSAL_SKILLS_DIR,\n} from '../mcp/editorConfigs.js'\nimport {type Editor} from '../mcp/types.js'\n\nconst debug = subdebug('skills:state')\n\ninterface ReadSkillStateOptions {\n /**\n * Detected editors. Used to credit \"universal\" agents (those that read from\n * the shared `.agents/skills` directory) when the skills live there — see\n * note in `readSkillState`.\n */\n editors: Editor[]\n /** Names of the skills to look up (match the `name` of `listSkills()` entries). */\n skillNames: string[]\n}\n\ninterface SkillState {\n /** Display names of agents that have all of these skills installed globally. */\n installedAgentDisplayNames: Set<string>\n}\n\n/** Upper bound for reading the global skill state (checked between steps). */\nconst LIST_TIMEOUT_MS = 10_000\n\n/** Normalizes path separators to `/` so comparisons are OS-agnostic. */\nfunction toPosixPath(value: string): string {\n return value.replaceAll('\\\\', '/')\n}\n\n/**\n * A skill lives in the shared universal skills directory when its canonical\n * path is under `.agents/skills`. The `skills` CLI installs universal-agent\n * skills there directly (rather than under an agent-specific directory).\n */\nfunction isUniversalSkillPath(skillPath: string): boolean {\n return toPosixPath(skillPath).includes(`${UNIVERSAL_SKILLS_DIR}/`)\n}\n\n/**\n * Lists global skills via the bundled `skills` package's `listSkills` and\n * returns the set of agent display names that have every skill in\n * `skillNames` installed globally.\n * Agents missing any of the skills are excluded, so they get a (idempotent)\n * re-install that fills the gap.\n *\n * \"Universal\" agents (those whose `skillsDir` is the shared `.agents/skills`\n * directory) are credited whenever every requested skill lives in that shared\n * directory. `listSkills` only attributes a skill to agents it independently\n * detects, so a universal editor we detected may be absent from the output even\n * though it reads from the shared directory and already has the skills.\n *\n * Any failure (import, read, timeout) is debug-logged and\n * resolved with an empty set. Callers should treat that as \"treat all agents\n * as not installed\" — re-installing is idempotent, so over-installing is\n * safer than skipping based on a flaky probe.\n */\nexport async function readSkillState(opts: ReadSkillStateOptions): Promise<SkillState> {\n const {editors, skillNames} = opts\n const empty: SkillState = {installedAgentDisplayNames: new Set()}\n\n let entries: readonly InstalledSkillInfo[]\n try {\n // Loaded lazily so a problem with the `skills` package only affects this\n // best-effort probe, not every command that imports this module.\n // eslint-disable-next-line no-restricted-syntax -- package import, not a file path\n const {listSkills} = await import('skills')\n const result = await listSkills({\n scope: 'global',\n signal: AbortSignal.timeout(LIST_TIMEOUT_MS),\n })\n entries = result.skills\n } catch (error) {\n debug('skills list failed: %O', error)\n return empty\n }\n\n const agentSets = skillNames.map((skillName) => {\n const match = entries.find((entry) => entry.name === skillName)\n if (!match) {\n return new Set<string>()\n }\n // `listSkills` reports agent IDs; callers match on display names.\n return new Set(\n match.agents.map((agentId) => getSkillsCliAgentDisplayNameById(agentId) ?? agentId),\n )\n })\n\n const installed = new Set(\n [...(agentSets[0] ?? [])].filter((agent) => agentSets.every((set) => set.has(agent))),\n )\n\n // Universal agents share the `.agents/skills` directory. If every requested\n // skill lives there, credit each detected universal editor — otherwise a\n // detected universal editor that the `skills` CLI didn't independently detect\n // would be treated as missing and trigger a redundant re-install.\n const allSkillsInUniversalDir =\n skillNames.length > 0 &&\n skillNames.every((skillName) => {\n const match = entries.find((entry) => entry.name === skillName)\n return match ? isUniversalSkillPath(match.path) : false\n })\n\n if (allSkillsInUniversalDir) {\n for (const editor of editors) {\n if (!isUniversalSkillsCliAgentByEditorName(editor.name)) continue\n const displayName = getSkillsCliAgentDisplayName(editor.name)\n if (displayName) installed.add(displayName)\n }\n }\n\n return {installedAgentDisplayNames: installed}\n}\n"],"names":["subdebug","getSkillsCliAgentDisplayName","getSkillsCliAgentDisplayNameById","isUniversalSkillsCliAgentByEditorName","UNIVERSAL_SKILLS_DIR","debug","LIST_TIMEOUT_MS","toPosixPath","value","replaceAll","isUniversalSkillPath","skillPath","includes","readSkillState","opts","editors","skillNames","empty","installedAgentDisplayNames","Set","entries","listSkills","result","scope","signal","AbortSignal","timeout","skills","error","agentSets","map","skillName","match","find","entry","name","agents","agentId","installed","filter","agent","every","set","has","allSkillsInUniversalDir","length","path","editor","displayName","add"],"mappings":"AAAA,SAAQA,QAAQ,QAAO,mBAAkB;AAGzC,SACEC,4BAA4B,EAC5BC,gCAAgC,EAChCC,qCAAqC,EACrCC,oBAAoB,QACf,0BAAyB;AAGhC,MAAMC,QAAQL,SAAS;AAkBvB,4EAA4E,GAC5E,MAAMM,kBAAkB;AAExB,sEAAsE,GACtE,SAASC,YAAYC,KAAa;IAChC,OAAOA,MAAMC,UAAU,CAAC,MAAM;AAChC;AAEA;;;;CAIC,GACD,SAASC,qBAAqBC,SAAiB;IAC7C,OAAOJ,YAAYI,WAAWC,QAAQ,CAAC,GAAGR,qBAAqB,CAAC,CAAC;AACnE;AAEA;;;;;;;;;;;;;;;;;CAiBC,GACD,OAAO,eAAeS,eAAeC,IAA2B;IAC9D,MAAM,EAACC,OAAO,EAAEC,UAAU,EAAC,GAAGF;IAC9B,MAAMG,QAAoB;QAACC,4BAA4B,IAAIC;IAAK;IAEhE,IAAIC;IACJ,IAAI;QACF,yEAAyE;QACzE,iEAAiE;QACjE,
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/skills/readSkillState.ts"],"sourcesContent":["import {subdebug} from '@sanity/cli-core'\nimport {type InstalledSkillInfo} from 'skills'\n\nimport {\n getSkillsCliAgentDisplayName,\n getSkillsCliAgentDisplayNameById,\n isUniversalSkillsCliAgentByEditorName,\n UNIVERSAL_SKILLS_DIR,\n} from '../mcp/editorConfigs.js'\nimport {type Editor} from '../mcp/types.js'\n\nconst debug = subdebug('skills:state')\n\ninterface ReadSkillStateOptions {\n /**\n * Detected editors. Used to credit \"universal\" agents (those that read from\n * the shared `.agents/skills` directory) when the skills live there — see\n * note in `readSkillState`.\n */\n editors: Editor[]\n /** Names of the skills to look up (match the `name` of `listSkills()` entries). */\n skillNames: string[]\n}\n\ninterface SkillState {\n /** Display names of agents that have all of these skills installed globally. */\n installedAgentDisplayNames: Set<string>\n}\n\n/** Upper bound for reading the global skill state (checked between steps). */\nconst LIST_TIMEOUT_MS = 10_000\n\n/** Normalizes path separators to `/` so comparisons are OS-agnostic. */\nfunction toPosixPath(value: string): string {\n return value.replaceAll('\\\\', '/')\n}\n\n/**\n * A skill lives in the shared universal skills directory when its canonical\n * path is under `.agents/skills`. The `skills` CLI installs universal-agent\n * skills there directly (rather than under an agent-specific directory).\n */\nfunction isUniversalSkillPath(skillPath: string): boolean {\n return toPosixPath(skillPath).includes(`${UNIVERSAL_SKILLS_DIR}/`)\n}\n\n/**\n * Lists global skills via the bundled `skills` package's `listSkills` and\n * returns the set of agent display names that have every skill in\n * `skillNames` installed globally.\n * Agents missing any of the skills are excluded, so they get a (idempotent)\n * re-install that fills the gap.\n *\n * \"Universal\" agents (those whose `skillsDir` is the shared `.agents/skills`\n * directory) are credited whenever every requested skill lives in that shared\n * directory. `listSkills` only attributes a skill to agents it independently\n * detects, so a universal editor we detected may be absent from the output even\n * though it reads from the shared directory and already has the skills.\n *\n * Any failure (import, read, timeout) is debug-logged and\n * resolved with an empty set. Callers should treat that as \"treat all agents\n * as not installed\" — re-installing is idempotent, so over-installing is\n * safer than skipping based on a flaky probe.\n */\nexport async function readSkillState(opts: ReadSkillStateOptions): Promise<SkillState> {\n const {editors, skillNames} = opts\n const empty: SkillState = {installedAgentDisplayNames: new Set()}\n\n let entries: readonly InstalledSkillInfo[]\n try {\n // Loaded lazily so a problem with the `skills` package only affects this\n // best-effort probe, not every command that imports this module.\n // eslint-disable-next-line eslint-js/no-restricted-syntax -- package import, not a file path\n const {listSkills} = await import('skills')\n const result = await listSkills({\n scope: 'global',\n signal: AbortSignal.timeout(LIST_TIMEOUT_MS),\n })\n entries = result.skills\n } catch (error) {\n debug('skills list failed: %O', error)\n return empty\n }\n\n const agentSets = skillNames.map((skillName) => {\n const match = entries.find((entry) => entry.name === skillName)\n if (!match) {\n return new Set<string>()\n }\n // `listSkills` reports agent IDs; callers match on display names.\n return new Set(\n match.agents.map((agentId) => getSkillsCliAgentDisplayNameById(agentId) ?? agentId),\n )\n })\n\n const installed = new Set(\n [...(agentSets[0] ?? [])].filter((agent) => agentSets.every((set) => set.has(agent))),\n )\n\n // Universal agents share the `.agents/skills` directory. If every requested\n // skill lives there, credit each detected universal editor — otherwise a\n // detected universal editor that the `skills` CLI didn't independently detect\n // would be treated as missing and trigger a redundant re-install.\n const allSkillsInUniversalDir =\n skillNames.length > 0 &&\n skillNames.every((skillName) => {\n const match = entries.find((entry) => entry.name === skillName)\n return match ? isUniversalSkillPath(match.path) : false\n })\n\n if (allSkillsInUniversalDir) {\n for (const editor of editors) {\n if (!isUniversalSkillsCliAgentByEditorName(editor.name)) continue\n const displayName = getSkillsCliAgentDisplayName(editor.name)\n if (displayName) installed.add(displayName)\n }\n }\n\n return {installedAgentDisplayNames: installed}\n}\n"],"names":["subdebug","getSkillsCliAgentDisplayName","getSkillsCliAgentDisplayNameById","isUniversalSkillsCliAgentByEditorName","UNIVERSAL_SKILLS_DIR","debug","LIST_TIMEOUT_MS","toPosixPath","value","replaceAll","isUniversalSkillPath","skillPath","includes","readSkillState","opts","editors","skillNames","empty","installedAgentDisplayNames","Set","entries","listSkills","result","scope","signal","AbortSignal","timeout","skills","error","agentSets","map","skillName","match","find","entry","name","agents","agentId","installed","filter","agent","every","set","has","allSkillsInUniversalDir","length","path","editor","displayName","add"],"mappings":"AAAA,SAAQA,QAAQ,QAAO,mBAAkB;AAGzC,SACEC,4BAA4B,EAC5BC,gCAAgC,EAChCC,qCAAqC,EACrCC,oBAAoB,QACf,0BAAyB;AAGhC,MAAMC,QAAQL,SAAS;AAkBvB,4EAA4E,GAC5E,MAAMM,kBAAkB;AAExB,sEAAsE,GACtE,SAASC,YAAYC,KAAa;IAChC,OAAOA,MAAMC,UAAU,CAAC,MAAM;AAChC;AAEA;;;;CAIC,GACD,SAASC,qBAAqBC,SAAiB;IAC7C,OAAOJ,YAAYI,WAAWC,QAAQ,CAAC,GAAGR,qBAAqB,CAAC,CAAC;AACnE;AAEA;;;;;;;;;;;;;;;;;CAiBC,GACD,OAAO,eAAeS,eAAeC,IAA2B;IAC9D,MAAM,EAACC,OAAO,EAAEC,UAAU,EAAC,GAAGF;IAC9B,MAAMG,QAAoB;QAACC,4BAA4B,IAAIC;IAAK;IAEhE,IAAIC;IACJ,IAAI;QACF,yEAAyE;QACzE,iEAAiE;QACjE,6FAA6F;QAC7F,MAAM,EAACC,UAAU,EAAC,GAAG,MAAM,MAAM,CAAC;QAClC,MAAMC,SAAS,MAAMD,WAAW;YAC9BE,OAAO;YACPC,QAAQC,YAAYC,OAAO,CAACpB;QAC9B;QACAc,UAAUE,OAAOK,MAAM;IACzB,EAAE,OAAOC,OAAO;QACdvB,MAAM,0BAA0BuB;QAChC,OAAOX;IACT;IAEA,MAAMY,YAAYb,WAAWc,GAAG,CAAC,CAACC;QAChC,MAAMC,QAAQZ,QAAQa,IAAI,CAAC,CAACC,QAAUA,MAAMC,IAAI,KAAKJ;QACrD,IAAI,CAACC,OAAO;YACV,OAAO,IAAIb;QACb;QACA,kEAAkE;QAClE,OAAO,IAAIA,IACTa,MAAMI,MAAM,CAACN,GAAG,CAAC,CAACO,UAAYnC,iCAAiCmC,YAAYA;IAE/E;IAEA,MAAMC,YAAY,IAAInB,IACpB;WAAKU,SAAS,CAAC,EAAE,IAAI,EAAE;KAAE,CAACU,MAAM,CAAC,CAACC,QAAUX,UAAUY,KAAK,CAAC,CAACC,MAAQA,IAAIC,GAAG,CAACH;IAG/E,4EAA4E;IAC5E,yEAAyE;IACzE,8EAA8E;IAC9E,kEAAkE;IAClE,MAAMI,0BACJ5B,WAAW6B,MAAM,GAAG,KACpB7B,WAAWyB,KAAK,CAAC,CAACV;QAChB,MAAMC,QAAQZ,QAAQa,IAAI,CAAC,CAACC,QAAUA,MAAMC,IAAI,KAAKJ;QACrD,OAAOC,QAAQtB,qBAAqBsB,MAAMc,IAAI,IAAI;IACpD;IAEF,IAAIF,yBAAyB;QAC3B,KAAK,MAAMG,UAAUhC,QAAS;YAC5B,IAAI,CAACZ,sCAAsC4C,OAAOZ,IAAI,GAAG;YACzD,MAAMa,cAAc/C,6BAA6B8C,OAAOZ,IAAI;YAC5D,IAAIa,aAAaV,UAAUW,GAAG,CAACD;QACjC;IACF;IAEA,OAAO;QAAC9B,4BAA4BoB;IAAS;AAC/C"}
|
|
@@ -68,7 +68,7 @@ const skillsDebug = subdebug('skills:setup');
|
|
|
68
68
|
try {
|
|
69
69
|
// Loaded lazily so a problem with the `skills` package only affects this
|
|
70
70
|
// best-effort step, not every command that imports this module.
|
|
71
|
-
// eslint-disable-next-line no-restricted-syntax -- package import, not a file path
|
|
71
|
+
// eslint-disable-next-line eslint-js/no-restricted-syntax -- package import, not a file path
|
|
72
72
|
const { installSkills } = await import('skills');
|
|
73
73
|
const result = await installSkills(SANITY_SKILLS_REPO, {
|
|
74
74
|
agents: uniqueAgents,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/skills/setupSkills.ts"],"sourcesContent":["import {styleText} from 'node:util'\n\nimport {type Output, subdebug} from '@sanity/cli-core'\nimport {getErrorMessage, toError} from '@sanity/cli-core/errors'\nimport {logSymbols, spinner} from '@sanity/cli-core/ux'\n\nimport {\n getSkillsCliAgentDisplayNameById,\n getSkillsCliAgentSkillsDir,\n UNIVERSAL_SKILLS_DIR,\n} from '../mcp/editorConfigs.js'\n\nconst skillsDebug = subdebug('skills:setup')\n\n/** Source repo for the bundled `skills` package. See https://www.sanity.io/docs/ai/skills. */\nexport const SANITY_SKILLS_REPO = 'sanity-io/agent-toolkit'\n\n/** Names of the skills we install — must match the entries in the source repo. */\nexport const SANITY_SKILL_NAMES = ['sanity-best-practices', 'sanity-migration']\n\n/** Upper bound for fetching and installing the skills (checked between steps). */\nconst INSTALL_TIMEOUT_MS = 90_000\n\ninterface SetupSkillsOptions {\n /** Skills-CLI agent IDs (e.g. 'cursor', 'claude-code') to install for. */\n agents: string[]\n\n /**\n * Output to use for user-facing messages, so they go through the calling\n * command rather than directly to stdout/stderr.\n */\n output: Output\n}\n\ninterface SetupSkillsResult {\n /** Deduplicated agent IDs the skills were installed for. */\n installedAgents: string[]\n skipped: boolean\n\n error?: Error\n}\n\n/**\n * Prints a short summary beneath the success line: the skills that were\n * installed, grouped by where they live. Universal agents share\n * `~/.agents/skills`, so they're listed together under one header; any agent\n * with its own directory (e.g. Claude Code) is listed separately with its\n * location. Global (`-g`) installs are home-anchored, so locations show `~/`.\n */\nfunction printInstallSummary(agents: string[], output: Output): void {\n const universal: string[] = []\n const additional: {dir: string; name: string}[] = []\n\n for (const agent of agents) {\n const name = getSkillsCliAgentDisplayNameById(agent) ?? agent\n const dir = getSkillsCliAgentSkillsDir(agent)\n if (dir && dir !== UNIVERSAL_SKILLS_DIR) {\n additional.push({dir, name})\n } else {\n universal.push(name)\n }\n }\n\n if (universal.length > 0) {\n output.log('')\n output.log(styleText('dim', ` Universal (~/${UNIVERSAL_SKILLS_DIR})`))\n output.log(styleText('dim', ` ${universal.join(', ')}`))\n }\n\n if (additional.length > 0) {\n output.log('')\n output.log(styleText('dim', ' Additional agents'))\n for (const {dir, name} of additional) {\n output.log(styleText('dim', ` ${name} (~/${dir})`))\n }\n }\n output.log('')\n}\n\n/**\n * Installs the Sanity skills globally for the given agents using the bundled\n * `skills` package's programmatic API (equivalent to\n * `skills add <repo> --skill <names> -g -a <agent>... -y`). Failures are\n * surfaced as warnings and never throw — skills install is best-effort and\n * must not abort `sanity init`.\n */\nexport async function setupSkills(options: SetupSkillsOptions): Promise<SetupSkillsResult> {\n const {output} = options\n const uniqueAgents = [...new Set(options.agents)]\n\n if (uniqueAgents.length === 0) {\n skillsDebug('No agents passed — skipping skills install')\n return {installedAgents: [], skipped: true}\n }\n\n skillsDebug(\n 'Installing %s from %s globally for agents: %s',\n SANITY_SKILL_NAMES.join(', '),\n SANITY_SKILLS_REPO,\n uniqueAgents.join(', '),\n )\n\n const spin = spinner('Installing Sanity agent skills').start()\n\n try {\n // Loaded lazily so a problem with the `skills` package only affects this\n // best-effort step, not every command that imports this module.\n // eslint-disable-next-line no-restricted-syntax -- package import, not a file path\n const {installSkills} = await import('skills')\n const result = await installSkills(SANITY_SKILLS_REPO, {\n agents: uniqueAgents,\n onWarning: (warning) => skillsDebug('skills warning: %s', warning.message),\n scope: 'global',\n signal: AbortSignal.timeout(INSTALL_TIMEOUT_MS),\n skills: SANITY_SKILL_NAMES,\n })\n skillsDebug('skills install result: %O', result)\n spin.stop()\n\n const failedAgents = new Set(result.failed.map((failure) => failure.agent))\n const installedAgents = uniqueAgents.filter((agent) => !failedAgents.has(agent))\n\n if (installedAgents.length > 0) {\n output.log(\n `${logSymbols.success} Sanity agent skills installed: [${SANITY_SKILL_NAMES.join(', ')}]`,\n )\n printInstallSummary(installedAgents, output)\n }\n\n if (result.failed.length === 0) {\n return {installedAgents, skipped: false}\n }\n\n const failureMessages = result.failed.map((failure) => failure.message)\n output.warn(\n installedAgents.length > 0\n ? 'Could not install Sanity agent skills for some agents:'\n : 'Could not install Sanity agent skills:',\n )\n for (const message of failureMessages) output.warn(message)\n return {error: new Error(failureMessages.join('\\n')), installedAgents, skipped: false}\n } catch (error) {\n skillsDebug('Error installing skills %O', error)\n const err = toError(error)\n spin.stop()\n output.warn(`Could not install Sanity agent skills: ${getErrorMessage(error)}`)\n const fix = (error as {fix?: unknown} | null)?.fix\n if (typeof fix === 'string' && fix) output.warn(fix)\n return {error: err, installedAgents: [], skipped: false}\n }\n}\n"],"names":["styleText","subdebug","getErrorMessage","toError","logSymbols","spinner","getSkillsCliAgentDisplayNameById","getSkillsCliAgentSkillsDir","UNIVERSAL_SKILLS_DIR","skillsDebug","SANITY_SKILLS_REPO","SANITY_SKILL_NAMES","INSTALL_TIMEOUT_MS","printInstallSummary","agents","output","universal","additional","agent","name","dir","push","length","log","join","setupSkills","options","uniqueAgents","Set","installedAgents","skipped","spin","start","installSkills","result","onWarning","warning","message","scope","signal","AbortSignal","timeout","skills","stop","failedAgents","failed","map","failure","filter","has","success","failureMessages","warn","error","Error","err","fix"],"mappings":"AAAA,SAAQA,SAAS,QAAO,YAAW;AAEnC,SAAqBC,QAAQ,QAAO,mBAAkB;AACtD,SAAQC,eAAe,EAAEC,OAAO,QAAO,0BAAyB;AAChE,SAAQC,UAAU,EAAEC,OAAO,QAAO,sBAAqB;AAEvD,SACEC,gCAAgC,EAChCC,0BAA0B,EAC1BC,oBAAoB,QACf,0BAAyB;AAEhC,MAAMC,cAAcR,SAAS;AAE7B,4FAA4F,GAC5F,OAAO,MAAMS,qBAAqB,0BAAyB;AAE3D,gFAAgF,GAChF,OAAO,MAAMC,qBAAqB;IAAC;IAAyB;CAAmB,CAAA;AAE/E,gFAAgF,GAChF,MAAMC,qBAAqB;AAqB3B;;;;;;CAMC,G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MAAMO,OAAO1B,QAAQ,kCAAkC2B,KAAK;IAE5D,IAAI;QACF,yEAAyE;QACzE,gEAAgE;QAChE,
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/skills/setupSkills.ts"],"sourcesContent":["import {styleText} from 'node:util'\n\nimport {type Output, subdebug} from '@sanity/cli-core'\nimport {getErrorMessage, toError} from '@sanity/cli-core/errors'\nimport {logSymbols, spinner} from '@sanity/cli-core/ux'\n\nimport {\n getSkillsCliAgentDisplayNameById,\n getSkillsCliAgentSkillsDir,\n UNIVERSAL_SKILLS_DIR,\n} from '../mcp/editorConfigs.js'\n\nconst skillsDebug = subdebug('skills:setup')\n\n/** Source repo for the bundled `skills` package. See https://www.sanity.io/docs/ai/skills. */\nexport const SANITY_SKILLS_REPO = 'sanity-io/agent-toolkit'\n\n/** Names of the skills we install — must match the entries in the source repo. */\nexport const SANITY_SKILL_NAMES = ['sanity-best-practices', 'sanity-migration']\n\n/** Upper bound for fetching and installing the skills (checked between steps). */\nconst INSTALL_TIMEOUT_MS = 90_000\n\ninterface SetupSkillsOptions {\n /** Skills-CLI agent IDs (e.g. 'cursor', 'claude-code') to install for. */\n agents: string[]\n\n /**\n * Output to use for user-facing messages, so they go through the calling\n * command rather than directly to stdout/stderr.\n */\n output: Output\n}\n\ninterface SetupSkillsResult {\n /** Deduplicated agent IDs the skills were installed for. */\n installedAgents: string[]\n skipped: boolean\n\n error?: Error\n}\n\n/**\n * Prints a short summary beneath the success line: the skills that were\n * installed, grouped by where they live. Universal agents share\n * `~/.agents/skills`, so they're listed together under one header; any agent\n * with its own directory (e.g. Claude Code) is listed separately with its\n * location. Global (`-g`) installs are home-anchored, so locations show `~/`.\n */\nfunction printInstallSummary(agents: string[], output: Output): void {\n const universal: string[] = []\n const additional: {dir: string; name: string}[] = []\n\n for (const agent of agents) {\n const name = getSkillsCliAgentDisplayNameById(agent) ?? agent\n const dir = getSkillsCliAgentSkillsDir(agent)\n if (dir && dir !== UNIVERSAL_SKILLS_DIR) {\n additional.push({dir, name})\n } else {\n universal.push(name)\n }\n }\n\n if (universal.length > 0) {\n output.log('')\n output.log(styleText('dim', ` Universal (~/${UNIVERSAL_SKILLS_DIR})`))\n output.log(styleText('dim', ` ${universal.join(', ')}`))\n }\n\n if (additional.length > 0) {\n output.log('')\n output.log(styleText('dim', ' Additional agents'))\n for (const {dir, name} of additional) {\n output.log(styleText('dim', ` ${name} (~/${dir})`))\n }\n }\n output.log('')\n}\n\n/**\n * Installs the Sanity skills globally for the given agents using the bundled\n * `skills` package's programmatic API (equivalent to\n * `skills add <repo> --skill <names> -g -a <agent>... -y`). Failures are\n * surfaced as warnings and never throw — skills install is best-effort and\n * must not abort `sanity init`.\n */\nexport async function setupSkills(options: SetupSkillsOptions): Promise<SetupSkillsResult> {\n const {output} = options\n const uniqueAgents = [...new Set(options.agents)]\n\n if (uniqueAgents.length === 0) {\n skillsDebug('No agents passed — skipping skills install')\n return {installedAgents: [], skipped: true}\n }\n\n skillsDebug(\n 'Installing %s from %s globally for agents: %s',\n SANITY_SKILL_NAMES.join(', '),\n SANITY_SKILLS_REPO,\n uniqueAgents.join(', '),\n )\n\n const spin = spinner('Installing Sanity agent skills').start()\n\n try {\n // Loaded lazily so a problem with the `skills` package only affects this\n // best-effort step, not every command that imports this module.\n // eslint-disable-next-line eslint-js/no-restricted-syntax -- package import, not a file path\n const {installSkills} = await import('skills')\n const result = await installSkills(SANITY_SKILLS_REPO, {\n agents: uniqueAgents,\n onWarning: (warning) => skillsDebug('skills warning: %s', warning.message),\n scope: 'global',\n signal: AbortSignal.timeout(INSTALL_TIMEOUT_MS),\n skills: SANITY_SKILL_NAMES,\n })\n skillsDebug('skills install result: %O', result)\n spin.stop()\n\n const failedAgents = new Set(result.failed.map((failure) => failure.agent))\n const installedAgents = uniqueAgents.filter((agent) => !failedAgents.has(agent))\n\n if (installedAgents.length > 0) {\n output.log(\n `${logSymbols.success} Sanity agent skills installed: [${SANITY_SKILL_NAMES.join(', ')}]`,\n )\n printInstallSummary(installedAgents, output)\n }\n\n if (result.failed.length === 0) {\n return {installedAgents, skipped: false}\n }\n\n const failureMessages = result.failed.map((failure) => failure.message)\n output.warn(\n installedAgents.length > 0\n ? 'Could not install Sanity agent skills for some agents:'\n : 'Could not install Sanity agent skills:',\n )\n for (const message of failureMessages) output.warn(message)\n return {error: new Error(failureMessages.join('\\n')), installedAgents, skipped: false}\n } catch (error) {\n skillsDebug('Error installing skills %O', error)\n const err = toError(error)\n spin.stop()\n output.warn(`Could not install Sanity agent skills: ${getErrorMessage(error)}`)\n const fix = (error as {fix?: unknown} | null)?.fix\n if (typeof fix === 'string' && fix) output.warn(fix)\n return {error: err, installedAgents: [], skipped: false}\n }\n}\n"],"names":["styleText","subdebug","getErrorMessage","toError","logSymbols","spinner","getSkillsCliAgentDisplayNameById","getSkillsCliAgentSkillsDir","UNIVERSAL_SKILLS_DIR","skillsDebug","SANITY_SKILLS_REPO","SANITY_SKILL_NAMES","INSTALL_TIMEOUT_MS","printInstallSummary","agents","output","universal","additional","agent","name","dir","push","length","log","join","setupSkills","options","uniqueAgents","Set","installedAgents","skipped","spin","start","installSkills","result","onWarning","warning","message","scope","signal","AbortSignal","timeout","skills","stop","failedAgents","failed","map","failure","filter","has","success","failureMessages","warn","error","Error","err","fix"],"mappings":"AAAA,SAAQA,SAAS,QAAO,YAAW;AAEnC,SAAqBC,QAAQ,QAAO,mBAAkB;AACtD,SAAQC,eAAe,EAAEC,OAAO,QAAO,0BAAyB;AAChE,SAAQC,UAAU,EAAEC,OAAO,QAAO,sBAAqB;AAEvD,SACEC,gCAAgC,EAChCC,0BAA0B,EAC1BC,oBAAoB,QACf,0BAAyB;AAEhC,MAAMC,cAAcR,SAAS;AAE7B,4FAA4F,GAC5F,OAAO,MAAMS,qBAAqB,0BAAyB;AAE3D,gFAAgF,GAChF,OAAO,MAAMC,qBAAqB;IAAC;IAAyB;CAAmB,CAAA;AAE/E,gFAAgF,GAChF,MAAMC,qBAAqB;AAqB3B;;;;;;CA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;QACpBtB,KAAKY,IAAI;QACT5B,OAAOqC,IAAI,CAAC,CAAC,uCAAuC,EAAElD,gBAAgBmD,QAAQ;QAC9E,MAAMG,MAAOH,OAAkCG;QAC/C,IAAI,OAAOA,QAAQ,YAAYA,KAAKzC,OAAOqC,IAAI,CAACI;QAChD,OAAO;YAACH,OAAOE;YAAK1B,iBAAiB,EAAE;YAAEC,SAAS;QAAK;IACzD;AACF"}
|
|
@@ -3,9 +3,10 @@ import { exitCodes, SanityCommand, subdebug } from '@sanity/cli-core';
|
|
|
3
3
|
import { getErrorMessage } from '@sanity/cli-core/errors';
|
|
4
4
|
import { requiredWhenUnattended } from '@sanity/cli-core/flags';
|
|
5
5
|
import { spinner } from '@sanity/cli-core/ux';
|
|
6
|
+
import { readOrganizationLogo } from '../../actions/organizations/readOrganizationLogo.js';
|
|
6
7
|
import { validateOrganizationName } from '../../actions/organizations/validateOrganizationName.js';
|
|
7
8
|
import { promptForOrganizationName } from '../../prompts/promptForOrganizationName.js';
|
|
8
|
-
import { createOrganization } from '../../services/organizations.js';
|
|
9
|
+
import { createOrganization, setOrganizationLogo } from '../../services/organizations.js';
|
|
9
10
|
import { organizationAliases } from '../../util/organizationAliases.js';
|
|
10
11
|
import { defineCommandTelemetry } from '../../util/telemetry/commandTelemetry.js';
|
|
11
12
|
const createOrgDebug = subdebug('organizations:create');
|
|
@@ -23,6 +24,10 @@ export class CreateOrganizationCommand extends SanityCommand {
|
|
|
23
24
|
{
|
|
24
25
|
command: '<%= config.bin %> <%= command.id %> --name "Acme Corp" --default-role member',
|
|
25
26
|
description: 'Create an organization with a default member role'
|
|
27
|
+
},
|
|
28
|
+
{
|
|
29
|
+
command: '<%= config.bin %> <%= command.id %> --name "Acme Corp" --logo ./logo.png',
|
|
30
|
+
description: 'Create an organization with a logo'
|
|
26
31
|
}
|
|
27
32
|
];
|
|
28
33
|
static flags = {
|
|
@@ -30,6 +35,11 @@ export class CreateOrganizationCommand extends SanityCommand {
|
|
|
30
35
|
description: 'Default role assigned to new members',
|
|
31
36
|
required: false
|
|
32
37
|
}),
|
|
38
|
+
logo: Flags.string({
|
|
39
|
+
description: 'Image file to use as the logo: PNG, JPEG, GIF, WebP, SVG, BMP, TIFF, HEIF or AVIF, at most 5 MB',
|
|
40
|
+
helpValue: '<path>',
|
|
41
|
+
required: false
|
|
42
|
+
}),
|
|
33
43
|
name: requiredWhenUnattended(Flags.string({
|
|
34
44
|
description: 'Organization name'
|
|
35
45
|
}))
|
|
@@ -37,17 +47,33 @@ export class CreateOrganizationCommand extends SanityCommand {
|
|
|
37
47
|
static hiddenAliases = organizationAliases('create');
|
|
38
48
|
static telemetry = defineCommandTelemetry(this.flags, {
|
|
39
49
|
redact: [
|
|
50
|
+
'logo',
|
|
40
51
|
'name'
|
|
41
52
|
]
|
|
42
53
|
});
|
|
43
54
|
async run() {
|
|
44
|
-
const { 'default-role': defaultRoleFlag, name: nameFlag } = this.flags;
|
|
55
|
+
const { 'default-role': defaultRoleFlag, logo: logoPath, name: nameFlag } = this.flags;
|
|
45
56
|
const defaultRole = defaultRoleFlag?.trim();
|
|
46
57
|
if (defaultRole === '') {
|
|
47
58
|
this.error('Default role cannot be empty', {
|
|
48
59
|
exit: exitCodes.RUNTIME_ERROR
|
|
49
60
|
});
|
|
50
61
|
}
|
|
62
|
+
// Read the logo before creating anything, so a bad file doesn't leave an organization without it.
|
|
63
|
+
let logo;
|
|
64
|
+
if (logoPath === '') {
|
|
65
|
+
this.error('--logo needs the path to an image file. To create the organization without a logo, leave out --logo.', {
|
|
66
|
+
exit: exitCodes.RUNTIME_ERROR
|
|
67
|
+
});
|
|
68
|
+
} else if (logoPath !== undefined) {
|
|
69
|
+
try {
|
|
70
|
+
logo = await readOrganizationLogo(logoPath);
|
|
71
|
+
} catch (error) {
|
|
72
|
+
this.error(getErrorMessage(error), {
|
|
73
|
+
exit: exitCodes.RUNTIME_ERROR
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
}
|
|
51
77
|
let name;
|
|
52
78
|
if (nameFlag === undefined) {
|
|
53
79
|
name = await promptForOrganizationName();
|
|
@@ -62,8 +88,9 @@ export class CreateOrganizationCommand extends SanityCommand {
|
|
|
62
88
|
name = trimmedName;
|
|
63
89
|
}
|
|
64
90
|
const spin = spinner('Creating organization').start();
|
|
91
|
+
let org;
|
|
65
92
|
try {
|
|
66
|
-
|
|
93
|
+
org = await createOrganization(name, defaultRole);
|
|
67
94
|
spin.succeed('Organization created');
|
|
68
95
|
this.log(`ID: ${org.id}`);
|
|
69
96
|
this.log(`Name: ${org.name}`);
|
|
@@ -74,6 +101,19 @@ export class CreateOrganizationCommand extends SanityCommand {
|
|
|
74
101
|
exit: exitCodes.RUNTIME_ERROR
|
|
75
102
|
});
|
|
76
103
|
}
|
|
104
|
+
if (!logo) return;
|
|
105
|
+
const logoSpin = spinner('Setting logo').start();
|
|
106
|
+
try {
|
|
107
|
+
const { logoUrl } = await setOrganizationLogo(org.id, logo);
|
|
108
|
+
logoSpin.succeed();
|
|
109
|
+
this.log(`Logo: ${logoUrl}`);
|
|
110
|
+
} catch (error) {
|
|
111
|
+
logoSpin.fail();
|
|
112
|
+
createOrgDebug('Error setting organization logo', error);
|
|
113
|
+
this.error(`The organization was created, but its logo wasn't set: ${getErrorMessage(error)}\nTo try again, run: ${this.config.bin} organizations update ${org.id} --logo "${logoPath}"`, {
|
|
114
|
+
exit: exitCodes.RUNTIME_ERROR
|
|
115
|
+
});
|
|
116
|
+
}
|
|
77
117
|
}
|
|
78
118
|
}
|
|
79
119
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/commands/organizations/create.ts"],"sourcesContent":["import {Flags} from '@oclif/core'\nimport {type FlagInput} from '@oclif/core/interfaces'\nimport {exitCodes, SanityCommand, subdebug} from '@sanity/cli-core'\nimport {getErrorMessage} from '@sanity/cli-core/errors'\nimport {requiredWhenUnattended} from '@sanity/cli-core/flags'\nimport {spinner} from '@sanity/cli-core/ux'\n\nimport {validateOrganizationName} from '../../actions/organizations/validateOrganizationName.js'\nimport {promptForOrganizationName} from '../../prompts/promptForOrganizationName.js'\nimport {createOrganization} from '../../services/organizations.js'\nimport {organizationAliases} from '../../util/organizationAliases.js'\nimport {defineCommandTelemetry} from '../../util/telemetry/commandTelemetry.js'\n\nconst createOrgDebug = subdebug('organizations:create')\n\nexport class CreateOrganizationCommand extends SanityCommand<typeof CreateOrganizationCommand> {\n static override description = 'Create a new organization'\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %>',\n description: 'Interactively create an organization',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --name \"Acme Corp\"',\n description: 'Create an organization named \"Acme Corp\"',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --name \"Acme Corp\" --default-role member',\n description: 'Create an organization with a default member role',\n },\n ]\n\n static override flags = {\n 'default-role': Flags.string({\n description: 'Default role assigned to new members',\n required: false,\n }),\n name: requiredWhenUnattended(\n Flags.string({\n description: 'Organization name',\n }),\n ),\n } satisfies FlagInput\n\n static override hiddenAliases = organizationAliases('create')\n\n static telemetry = defineCommandTelemetry(this.flags, {redact: ['name']})\n\n public async run(): Promise<void> {\n const {'default-role': defaultRoleFlag, name: nameFlag} = this.flags\n\n const defaultRole = defaultRoleFlag?.trim()\n if (defaultRole === '') {\n this.error('Default role cannot be empty', {exit: exitCodes.RUNTIME_ERROR})\n }\n\n let name: string\n if (nameFlag === undefined) {\n name = await promptForOrganizationName()\n } else {\n const trimmedName = nameFlag.trim()\n const validation = validateOrganizationName(trimmedName)\n if (validation !== true) {\n this.error(validation, {exit: exitCodes.RUNTIME_ERROR})\n }\n name = trimmedName\n }\n\n const spin = spinner('Creating organization').start()\n try {\n
|
|
1
|
+
{"version":3,"sources":["../../../src/commands/organizations/create.ts"],"sourcesContent":["import {Flags} from '@oclif/core'\nimport {type FlagInput} from '@oclif/core/interfaces'\nimport {exitCodes, SanityCommand, subdebug} from '@sanity/cli-core'\nimport {getErrorMessage} from '@sanity/cli-core/errors'\nimport {requiredWhenUnattended} from '@sanity/cli-core/flags'\nimport {spinner} from '@sanity/cli-core/ux'\n\nimport {\n type OrganizationLogo,\n readOrganizationLogo,\n} from '../../actions/organizations/readOrganizationLogo.js'\nimport {validateOrganizationName} from '../../actions/organizations/validateOrganizationName.js'\nimport {promptForOrganizationName} from '../../prompts/promptForOrganizationName.js'\nimport {\n createOrganization,\n type OrganizationCreateResponse,\n setOrganizationLogo,\n} from '../../services/organizations.js'\nimport {organizationAliases} from '../../util/organizationAliases.js'\nimport {defineCommandTelemetry} from '../../util/telemetry/commandTelemetry.js'\n\nconst createOrgDebug = subdebug('organizations:create')\n\nexport class CreateOrganizationCommand extends SanityCommand<typeof CreateOrganizationCommand> {\n static override description = 'Create a new organization'\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %>',\n description: 'Interactively create an organization',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --name \"Acme Corp\"',\n description: 'Create an organization named \"Acme Corp\"',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --name \"Acme Corp\" --default-role member',\n description: 'Create an organization with a default member role',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --name \"Acme Corp\" --logo ./logo.png',\n description: 'Create an organization with a logo',\n },\n ]\n\n static override flags = {\n 'default-role': Flags.string({\n description: 'Default role assigned to new members',\n required: false,\n }),\n logo: Flags.string({\n description:\n 'Image file to use as the logo: PNG, JPEG, GIF, WebP, SVG, BMP, TIFF, HEIF or AVIF, at most 5 MB',\n helpValue: '<path>',\n required: false,\n }),\n name: requiredWhenUnattended(\n Flags.string({\n description: 'Organization name',\n }),\n ),\n } satisfies FlagInput\n\n static override hiddenAliases = organizationAliases('create')\n\n static telemetry = defineCommandTelemetry(this.flags, {redact: ['logo', 'name']})\n\n public async run(): Promise<void> {\n const {'default-role': defaultRoleFlag, logo: logoPath, name: nameFlag} = this.flags\n\n const defaultRole = defaultRoleFlag?.trim()\n if (defaultRole === '') {\n this.error('Default role cannot be empty', {exit: exitCodes.RUNTIME_ERROR})\n }\n\n // Read the logo before creating anything, so a bad file doesn't leave an organization without it.\n let logo: OrganizationLogo | undefined\n if (logoPath === '') {\n this.error(\n '--logo needs the path to an image file. To create the organization without a logo, leave out --logo.',\n {exit: exitCodes.RUNTIME_ERROR},\n )\n } else if (logoPath !== undefined) {\n try {\n logo = await readOrganizationLogo(logoPath)\n } catch (error) {\n this.error(getErrorMessage(error), {exit: exitCodes.RUNTIME_ERROR})\n }\n }\n\n let name: string\n if (nameFlag === undefined) {\n name = await promptForOrganizationName()\n } else {\n const trimmedName = nameFlag.trim()\n const validation = validateOrganizationName(trimmedName)\n if (validation !== true) {\n this.error(validation, {exit: exitCodes.RUNTIME_ERROR})\n }\n name = trimmedName\n }\n\n const spin = spinner('Creating organization').start()\n let org: OrganizationCreateResponse\n try {\n org = await createOrganization(name, defaultRole)\n spin.succeed('Organization created')\n this.log(`ID: ${org.id}`)\n this.log(`Name: ${org.name}`)\n } catch (error) {\n spin.fail()\n createOrgDebug('Error creating organization', error)\n this.error(`Failed to create organization: ${getErrorMessage(error)}`, {\n exit: exitCodes.RUNTIME_ERROR,\n })\n }\n\n if (!logo) return\n\n const logoSpin = spinner('Setting logo').start()\n try {\n const {logoUrl} = await setOrganizationLogo(org.id, logo)\n logoSpin.succeed()\n this.log(`Logo: ${logoUrl}`)\n } catch (error) {\n logoSpin.fail()\n createOrgDebug('Error setting organization logo', error)\n this.error(\n `The organization was created, but its logo wasn't set: ${getErrorMessage(error)}\\nTo try again, run: ${this.config.bin} organizations update ${org.id} --logo \"${logoPath}\"`,\n {exit: exitCodes.RUNTIME_ERROR},\n )\n }\n }\n}\n"],"names":["Flags","exitCodes","SanityCommand","subdebug","getErrorMessage","requiredWhenUnattended","spinner","readOrganizationLogo","validateOrganizationName","promptForOrganizationName","createOrganization","setOrganizationLogo","organizationAliases","defineCommandTelemetry","createOrgDebug","CreateOrganizationCommand","description","examples","command","flags","string","required","logo","helpValue","name","hiddenAliases","telemetry","redact","run","defaultRoleFlag","logoPath","nameFlag","defaultRole","trim","error","exit","RUNTIME_ERROR","undefined","trimmedName","validation","spin","start","org","succeed","log","id","fail","logoSpin","logoUrl","config","bin"],"mappings":"AAAA,SAAQA,KAAK,QAAO,cAAa;AAEjC,SAAQC,SAAS,EAAEC,aAAa,EAAEC,QAAQ,QAAO,mBAAkB;AACnE,SAAQC,eAAe,QAAO,0BAAyB;AACvD,SAAQC,sBAAsB,QAAO,yBAAwB;AAC7D,SAAQC,OAAO,QAAO,sBAAqB;AAE3C,SAEEC,oBAAoB,QACf,sDAAqD;AAC5D,SAAQC,wBAAwB,QAAO,0DAAyD;AAChG,SAAQC,yBAAyB,QAAO,6CAA4C;AACpF,SACEC,kBAAkB,EAElBC,mBAAmB,QACd,kCAAiC;AACxC,SAAQC,mBAAmB,QAAO,oCAAmC;AACrE,SAAQC,sBAAsB,QAAO,2CAA0C;AAE/E,MAAMC,iBAAiBX,SAAS;AAEhC,OAAO,MAAMY,kCAAkCb;IAC7C,OAAgBc,cAAc,4BAA2B;IAEzD,OAAgBC,WAAW;QACzB;YACEC,SAAS;YACTF,aAAa;QACf;QACA;YACEE,SAAS;YACTF,aAAa;QACf;QACA;YACEE,SAAS;YACTF,aAAa;QACf;QACA;YACEE,SAAS;YACTF,aAAa;QACf;KACD,CAAA;IAED,OAAgBG,QAAQ;QACtB,gBAAgBnB,MAAMoB,MAAM,CAAC;YAC3BJ,aAAa;YACbK,UAAU;QACZ;QACAC,MAAMtB,MAAMoB,MAAM,CAAC;YACjBJ,aACE;YACFO,WAAW;YACXF,UAAU;QACZ;QACAG,MAAMnB,uBACJL,MAAMoB,MAAM,CAAC;YACXJ,aAAa;QACf;IAEJ,EAAqB;IAErB,OAAgBS,gBAAgBb,oBAAoB,UAAS;IAE7D,OAAOc,YAAYb,uBAAuB,IAAI,CAACM,KAAK,EAAE;QAACQ,QAAQ;YAAC;YAAQ;SAAO;IAAA,GAAE;IAEjF,MAAaC,MAAqB;QAChC,MAAM,EAAC,gBAAg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AAE;gBACrEC,MAAMlC,UAAUmC,aAAa;YAC/B;QACF;QAEA,IAAI,CAACd,MAAM;QAEX,MAAMyB,WAAWzC,QAAQ,gBAAgBmC,KAAK;QAC9C,IAAI;YACF,MAAM,EAACO,OAAO,EAAC,GAAG,MAAMrC,oBAAoB+B,IAAIG,EAAE,EAAEvB;YACpDyB,SAASJ,OAAO;YAChB,IAAI,CAACC,GAAG,CAAC,CAAC,MAAM,EAAEI,SAAS;QAC7B,EAAE,OAAOd,OAAO;YACda,SAASD,IAAI;YACbhC,eAAe,mCAAmCoB;YAClD,IAAI,CAACA,KAAK,CACR,CAAC,uDAAuD,EAAE9B,gBAAgB8B,OAAO,qBAAqB,EAAE,IAAI,CAACe,MAAM,CAACC,GAAG,CAAC,sBAAsB,EAAER,IAAIG,EAAE,CAAC,SAAS,EAAEf,SAAS,CAAC,CAAC,EAC7K;gBAACK,MAAMlC,UAAUmC,aAAa;YAAA;QAElC;IACF;AACF"}
|
|
@@ -3,16 +3,18 @@ import { exitCodes, SanityCommand, subdebug } from '@sanity/cli-core';
|
|
|
3
3
|
import { getErrorMessage } from '@sanity/cli-core/errors';
|
|
4
4
|
import { spinner } from '@sanity/cli-core/ux';
|
|
5
5
|
import { isHttpError } from '@sanity/client';
|
|
6
|
+
import { readOrganizationLogo } from '../../actions/organizations/readOrganizationLogo.js';
|
|
6
7
|
import { validateOrganizationName } from '../../actions/organizations/validateOrganizationName.js';
|
|
7
8
|
import { validateOrganizationSlug } from '../../actions/organizations/validateOrganizationSlug.js';
|
|
8
|
-
import { updateOrganization } from '../../services/organizations.js';
|
|
9
|
+
import { removeOrganizationLogo, setOrganizationLogo, updateOrganization } from '../../services/organizations.js';
|
|
9
10
|
import { organizationAliases } from '../../util/organizationAliases.js';
|
|
10
11
|
import { defineCommandTelemetry } from '../../util/telemetry/commandTelemetry.js';
|
|
11
12
|
const updateOrgDebug = subdebug('organizations:update');
|
|
12
13
|
const UPDATE_FLAGS = [
|
|
13
14
|
'name',
|
|
14
15
|
'slug',
|
|
15
|
-
'default-role'
|
|
16
|
+
'default-role',
|
|
17
|
+
'logo'
|
|
16
18
|
];
|
|
17
19
|
export class UpdateOrganizationCommand extends SanityCommand {
|
|
18
20
|
static args = {
|
|
@@ -34,6 +36,14 @@ export class UpdateOrganizationCommand extends SanityCommand {
|
|
|
34
36
|
{
|
|
35
37
|
command: '<%= config.bin %> <%= command.id %> org-abc123 --default-role viewer',
|
|
36
38
|
description: 'Change the default member role'
|
|
39
|
+
},
|
|
40
|
+
{
|
|
41
|
+
command: '<%= config.bin %> <%= command.id %> org-abc123 --logo ./logo.png',
|
|
42
|
+
description: 'Set or replace the organization logo'
|
|
43
|
+
},
|
|
44
|
+
{
|
|
45
|
+
command: '<%= config.bin %> <%= command.id %> org-abc123 --logo ""',
|
|
46
|
+
description: 'Remove the organization logo'
|
|
37
47
|
}
|
|
38
48
|
];
|
|
39
49
|
static flags = {
|
|
@@ -44,6 +54,14 @@ export class UpdateOrganizationCommand extends SanityCommand {
|
|
|
44
54
|
description: 'New default role for new members',
|
|
45
55
|
required: false
|
|
46
56
|
}),
|
|
57
|
+
logo: Flags.string({
|
|
58
|
+
atLeastOne: [
|
|
59
|
+
...UPDATE_FLAGS
|
|
60
|
+
],
|
|
61
|
+
description: 'Image file to use as the logo: PNG, JPEG, GIF, WebP, SVG, BMP, TIFF, HEIF or AVIF, at most 5 MB ("" removes it)',
|
|
62
|
+
helpValue: '<path>',
|
|
63
|
+
required: false
|
|
64
|
+
}),
|
|
47
65
|
name: Flags.string({
|
|
48
66
|
atLeastOne: [
|
|
49
67
|
...UPDATE_FLAGS
|
|
@@ -62,12 +80,13 @@ export class UpdateOrganizationCommand extends SanityCommand {
|
|
|
62
80
|
static hiddenAliases = organizationAliases('update');
|
|
63
81
|
static telemetry = defineCommandTelemetry(this.flags, {
|
|
64
82
|
redact: [
|
|
83
|
+
'logo',
|
|
65
84
|
'name'
|
|
66
85
|
]
|
|
67
86
|
});
|
|
68
87
|
async run() {
|
|
69
88
|
const { organizationId } = this.args;
|
|
70
|
-
const { 'default-role': defaultRole, name, slug } = this.flags;
|
|
89
|
+
const { 'default-role': defaultRole, logo: logoPath, name, slug } = this.flags;
|
|
71
90
|
const params = {};
|
|
72
91
|
if (name !== undefined) {
|
|
73
92
|
const trimmedName = name.trim();
|
|
@@ -98,23 +117,57 @@ export class UpdateOrganizationCommand extends SanityCommand {
|
|
|
98
117
|
}
|
|
99
118
|
params.defaultRoleName = trimmedRole;
|
|
100
119
|
}
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
this.error(`Organization "${organizationId}" not found`, {
|
|
120
|
+
// undefined leaves the logo as it is, null removes it.
|
|
121
|
+
let logo;
|
|
122
|
+
if (logoPath === '') {
|
|
123
|
+
logo = null;
|
|
124
|
+
} else if (logoPath !== undefined) {
|
|
125
|
+
try {
|
|
126
|
+
logo = await readOrganizationLogo(logoPath);
|
|
127
|
+
} catch (error) {
|
|
128
|
+
this.error(getErrorMessage(error), {
|
|
111
129
|
exit: exitCodes.RUNTIME_ERROR
|
|
112
130
|
});
|
|
113
131
|
}
|
|
114
|
-
|
|
132
|
+
}
|
|
133
|
+
const spin = spinner('Updating organization').start();
|
|
134
|
+
const updatesFields = Object.keys(params).length > 0;
|
|
135
|
+
if (updatesFields) {
|
|
136
|
+
try {
|
|
137
|
+
await updateOrganization(organizationId, params);
|
|
138
|
+
} catch (error) {
|
|
139
|
+
spin.fail();
|
|
140
|
+
this.failRequest(error, 'Failed to update organization');
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
let logoUrl = null;
|
|
144
|
+
if (logo !== undefined) {
|
|
145
|
+
try {
|
|
146
|
+
const response = logo ? await setOrganizationLogo(organizationId, logo) : await removeOrganizationLogo(organizationId);
|
|
147
|
+
logoUrl = response.logoUrl;
|
|
148
|
+
} catch (error) {
|
|
149
|
+
spin.fail();
|
|
150
|
+
this.failRequest(error, updatesFields ? `The organization was updated, but its logo wasn't ${logo ? 'set' : 'removed'}` : `Failed to ${logo ? 'set' : 'remove'} the organization's logo`);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
spin.succeed();
|
|
154
|
+
this.log('Organization updated');
|
|
155
|
+
if (logo) {
|
|
156
|
+
this.log(`Logo: ${logoUrl}`);
|
|
157
|
+
} else if (logo === null) {
|
|
158
|
+
this.log('Logo removed');
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
failRequest(error, message) {
|
|
162
|
+
updateOrgDebug(message, error);
|
|
163
|
+
if (isHttpError(error) && error.statusCode === 404) {
|
|
164
|
+
this.error(`Organization "${this.args.organizationId}" not found`, {
|
|
115
165
|
exit: exitCodes.RUNTIME_ERROR
|
|
116
166
|
});
|
|
117
167
|
}
|
|
168
|
+
this.error(`${message}: ${getErrorMessage(error)}`, {
|
|
169
|
+
exit: exitCodes.RUNTIME_ERROR
|
|
170
|
+
});
|
|
118
171
|
}
|
|
119
172
|
}
|
|
120
173
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/commands/organizations/update.ts"],"sourcesContent":["import {Args, Flags} from '@oclif/core'\nimport {type FlagInput} from '@oclif/core/interfaces'\nimport {exitCodes, SanityCommand, subdebug} from '@sanity/cli-core'\nimport {getErrorMessage} from '@sanity/cli-core/errors'\nimport {spinner} from '@sanity/cli-core/ux'\nimport {isHttpError} from '@sanity/client'\n\nimport {validateOrganizationName} from '../../actions/organizations/validateOrganizationName.js'\nimport {validateOrganizationSlug} from '../../actions/organizations/validateOrganizationSlug.js'\nimport {type OrganizationUpdateParams, updateOrganization} from '../../services/organizations.js'\nimport {organizationAliases} from '../../util/organizationAliases.js'\nimport {defineCommandTelemetry} from '../../util/telemetry/commandTelemetry.js'\n\nconst updateOrgDebug = subdebug('organizations:update')\n\nconst UPDATE_FLAGS = ['name', 'slug', 'default-role'] as const\n\nexport class UpdateOrganizationCommand extends SanityCommand<typeof UpdateOrganizationCommand> {\n static override args = {\n organizationId: Args.string({\n description: 'Organization ID',\n required: true,\n }),\n }\n\n static override description = 'Update an organization'\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %> org-abc123 --name \"New Name\"',\n description: 'Rename an organization',\n },\n {\n command: '<%= config.bin %> <%= command.id %> org-abc123 --slug new-slug',\n description: 'Set the organization slug (requires authSAML feature)',\n },\n {\n command: '<%= config.bin %> <%= command.id %> org-abc123 --default-role viewer',\n description: 'Change the default member role',\n },\n ]\n\n static override flags = {\n 'default-role': Flags.string({\n atLeastOne: [...UPDATE_FLAGS],\n description: 'New default role for new members',\n required: false,\n }),\n name: Flags.string({\n atLeastOne: [...UPDATE_FLAGS],\n description: 'New organization name',\n required: false,\n }),\n slug: Flags.string({\n atLeastOne: [...UPDATE_FLAGS],\n description: 'New URL slug (requires authSAML feature on the organization)',\n required: false,\n }),\n } satisfies FlagInput\n\n static override hiddenAliases = organizationAliases('update')\n\n static telemetry = defineCommandTelemetry(this.flags, {redact: ['name']})\n\n public async run(): Promise<void> {\n const {organizationId} = this.args\n const {'default-role': defaultRole, name, slug} = this.flags\n\n const params: OrganizationUpdateParams = {}\n if (name !== undefined) {\n const trimmedName = name.trim()\n const validation = validateOrganizationName(trimmedName)\n if (validation !== true) {\n this.error(validation, {exit: exitCodes.RUNTIME_ERROR})\n }\n params.name = trimmedName\n }\n if (slug !== undefined) {\n const trimmedSlug = slug.trim()\n const slugValidation = validateOrganizationSlug(trimmedSlug)\n if (slugValidation !== true) {\n this.error(slugValidation, {exit: exitCodes.RUNTIME_ERROR})\n }\n params.slug = trimmedSlug\n }\n if (defaultRole !== undefined) {\n const trimmedRole = defaultRole.trim()\n if (trimmedRole === '') {\n this.error('Default role cannot be empty', {exit: exitCodes.RUNTIME_ERROR})\n }\n params.defaultRoleName = trimmedRole\n }\n\n const spin = spinner('Updating organization').start()\n try {\n await updateOrganization(organizationId, params)\n spin.succeed()\n this.log('Organization updated')\n } catch (error) {\n spin.fail()\n updateOrgDebug('Error updating organization', error)\n if (isHttpError(error) && error.statusCode === 404) {\n this.error(`Organization \"${organizationId}\" not found`, {exit: exitCodes.RUNTIME_ERROR})\n }\n this.error(`Failed to update organization: ${getErrorMessage(error)}`, {\n exit: exitCodes.RUNTIME_ERROR,\n })\n }\n }\n}\n"],"names":["Args","Flags","exitCodes","SanityCommand","subdebug","getErrorMessage","spinner","isHttpError","validateOrganizationName","validateOrganizationSlug","updateOrganization","organizationAliases","defineCommandTelemetry","updateOrgDebug","UPDATE_FLAGS","UpdateOrganizationCommand","args","organizationId","string","description","required","examples","command","flags","atLeastOne","name","slug","hiddenAliases","telemetry","redact","run","defaultRole","params","undefined","trimmedName","trim","validation","error","exit","RUNTIME_ERROR","trimmedSlug","slugValidation","trimmedRole","defaultRoleName","spin","start","succeed","log","fail","statusCode"],"mappings":"AAAA,SAAQA,IAAI,EAAEC,KAAK,QAAO,cAAa;AAEvC,SAAQC,SAAS,EAAEC,aAAa,EAAEC,QAAQ,QAAO,mBAAkB;AACnE,SAAQC,eAAe,QAAO,0BAAyB;AACvD,SAAQC,OAAO,QAAO,sBAAqB;AAC3C,SAAQC,WAAW,QAAO,iBAAgB;AAE1C,SAAQC,wBAAwB,QAAO,0DAAyD;AAChG,SAAQC,wBAAwB,QAAO,0DAAyD;AAChG,SAAuCC,kBAAkB,QAAO,kCAAiC;AACjG,SAAQC,mBAAmB,QAAO,oCAAmC;AACrE,SAAQC,sBAAsB,QAAO,2CAA0C;AAE/E,MAAMC,iBAAiBT,SAAS;AAEhC,MAAMU,eAAe;IAAC;IAAQ;IAAQ;CAAe;AAErD,OAAO,MAAMC,kCAAkCZ;IAC7C,OAAgBa,OAAO;QACrBC,gBAAgBjB,KAAKkB,MAAM,CAAC;YAC1BC,aAAa;YACbC,UAAU;QACZ;IACF,EAAC;IAED,OAAgBD,cAAc,yBAAwB;IAEtD,OAAgBE,WAAW;QACzB;YACEC,SAAS;YACTH,a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WAAW;YAC7B,MAAMS,cAAcX,YAAYI,IAAI;YACpC,IAAIO,gBAAgB,IAAI;gBACtB,IAAI,CAACL,KAAK,CAAC,gCAAgC;oBAACC,MAAMpC,UAAUqC,aAAa;gBAAA;YAC3E;YACAP,OAAOW,eAAe,GAAGD;QAC3B;QAEA,MAAME,OAAOtC,QAAQ,yBAAyBuC,KAAK;QACnD,IAAI;YACF,MAAMnC,mBAAmBO,gBAAgBe;YACzCY,KAAKE,OAAO;YACZ,IAAI,CAACC,GAAG,CAAC;QACX,EAAE,OAAOV,OAAO;YACdO,KAAKI,IAAI;YACTnC,eAAe,+BAA+BwB;YAC9C,IAAI9B,YAAY8B,UAAUA,MAAMY,UAAU,KAAK,KAAK;gBAClD,IAAI,CAACZ,KAAK,CAAC,CAAC,cAAc,EAAEpB,eAAe,WAAW,CAAC,EAAE;oBAACqB,MAAMpC,UAAUqC,aAAa;gBAAA;YACzF;YACA,IAAI,CAACF,KAAK,CAAC,CAAC,+BAA+B,EAAEhC,gBAAgBgC,QAAQ,EAAE;gBACrEC,MAAMpC,UAAUqC,aAAa;YAC/B;QACF;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../src/commands/organizations/update.ts"],"sourcesContent":["import {Args, Flags} from '@oclif/core'\nimport {type FlagInput} from '@oclif/core/interfaces'\nimport {exitCodes, SanityCommand, subdebug} from '@sanity/cli-core'\nimport {getErrorMessage} from '@sanity/cli-core/errors'\nimport {spinner} from '@sanity/cli-core/ux'\nimport {isHttpError} from '@sanity/client'\n\nimport {\n type OrganizationLogo,\n readOrganizationLogo,\n} from '../../actions/organizations/readOrganizationLogo.js'\nimport {validateOrganizationName} from '../../actions/organizations/validateOrganizationName.js'\nimport {validateOrganizationSlug} from '../../actions/organizations/validateOrganizationSlug.js'\nimport {\n type OrganizationUpdateParams,\n removeOrganizationLogo,\n setOrganizationLogo,\n updateOrganization,\n} from '../../services/organizations.js'\nimport {organizationAliases} from '../../util/organizationAliases.js'\nimport {defineCommandTelemetry} from '../../util/telemetry/commandTelemetry.js'\n\nconst updateOrgDebug = subdebug('organizations:update')\n\nconst UPDATE_FLAGS = ['name', 'slug', 'default-role', 'logo'] as const\n\nexport class UpdateOrganizationCommand extends SanityCommand<typeof UpdateOrganizationCommand> {\n static override args = {\n organizationId: Args.string({\n description: 'Organization ID',\n required: true,\n }),\n }\n\n static override description = 'Update an organization'\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %> org-abc123 --name \"New Name\"',\n description: 'Rename an organization',\n },\n {\n command: '<%= config.bin %> <%= command.id %> org-abc123 --slug new-slug',\n description: 'Set the organization slug (requires authSAML feature)',\n },\n {\n command: '<%= config.bin %> <%= command.id %> org-abc123 --default-role viewer',\n description: 'Change the default member role',\n },\n {\n command: '<%= config.bin %> <%= command.id %> org-abc123 --logo ./logo.png',\n description: 'Set or replace the organization logo',\n },\n {\n command: '<%= config.bin %> <%= command.id %> org-abc123 --logo \"\"',\n description: 'Remove the organization logo',\n },\n ]\n\n static override flags = {\n 'default-role': Flags.string({\n atLeastOne: [...UPDATE_FLAGS],\n description: 'New default role for new members',\n required: false,\n }),\n logo: Flags.string({\n atLeastOne: [...UPDATE_FLAGS],\n description:\n 'Image file to use as the logo: PNG, JPEG, GIF, WebP, SVG, BMP, TIFF, HEIF or AVIF, at most 5 MB (\"\" removes it)',\n helpValue: '<path>',\n required: false,\n }),\n name: Flags.string({\n atLeastOne: [...UPDATE_FLAGS],\n description: 'New organization name',\n required: false,\n }),\n slug: Flags.string({\n atLeastOne: [...UPDATE_FLAGS],\n description: 'New URL slug (requires authSAML feature on the organization)',\n required: false,\n }),\n } satisfies FlagInput\n\n static override hiddenAliases = organizationAliases('update')\n\n static telemetry = defineCommandTelemetry(this.flags, {redact: ['logo', 'name']})\n\n public async run(): Promise<void> {\n const {organizationId} = this.args\n const {'default-role': defaultRole, logo: logoPath, name, slug} = this.flags\n\n const params: OrganizationUpdateParams = {}\n if (name !== undefined) {\n const trimmedName = name.trim()\n const validation = validateOrganizationName(trimmedName)\n if (validation !== true) {\n this.error(validation, {exit: exitCodes.RUNTIME_ERROR})\n }\n params.name = trimmedName\n }\n if (slug !== undefined) {\n const trimmedSlug = slug.trim()\n const slugValidation = validateOrganizationSlug(trimmedSlug)\n if (slugValidation !== true) {\n this.error(slugValidation, {exit: exitCodes.RUNTIME_ERROR})\n }\n params.slug = trimmedSlug\n }\n if (defaultRole !== undefined) {\n const trimmedRole = defaultRole.trim()\n if (trimmedRole === '') {\n this.error('Default role cannot be empty', {exit: exitCodes.RUNTIME_ERROR})\n }\n params.defaultRoleName = trimmedRole\n }\n\n // undefined leaves the logo as it is, null removes it.\n let logo: OrganizationLogo | null | undefined\n if (logoPath === '') {\n logo = null\n } else if (logoPath !== undefined) {\n try {\n logo = await readOrganizationLogo(logoPath)\n } catch (error) {\n this.error(getErrorMessage(error), {exit: exitCodes.RUNTIME_ERROR})\n }\n }\n\n const spin = spinner('Updating organization').start()\n\n const updatesFields = Object.keys(params).length > 0\n if (updatesFields) {\n try {\n await updateOrganization(organizationId, params)\n } catch (error) {\n spin.fail()\n this.failRequest(error, 'Failed to update organization')\n }\n }\n\n let logoUrl: string | null = null\n if (logo !== undefined) {\n try {\n const response = logo\n ? await setOrganizationLogo(organizationId, logo)\n : await removeOrganizationLogo(organizationId)\n logoUrl = response.logoUrl\n } catch (error) {\n spin.fail()\n this.failRequest(\n error,\n updatesFields\n ? `The organization was updated, but its logo wasn't ${logo ? 'set' : 'removed'}`\n : `Failed to ${logo ? 'set' : 'remove'} the organization's logo`,\n )\n }\n }\n\n spin.succeed()\n this.log('Organization updated')\n if (logo) {\n this.log(`Logo: ${logoUrl}`)\n } else if (logo === null) {\n this.log('Logo removed')\n }\n }\n\n private failRequest(error: unknown, message: string): never {\n updateOrgDebug(message, error)\n if (isHttpError(error) && error.statusCode === 404) {\n this.error(`Organization \"${this.args.organizationId}\" not found`, {\n exit: exitCodes.RUNTIME_ERROR,\n })\n }\n this.error(`${message}: ${getErrorMessage(error)}`, {exit: exitCodes.RUNTIME_ERROR})\n }\n}\n"],"names":["Args","Flags","exitCodes","SanityCommand","subdebug","getErrorMessage","spinner","isHttpError","readOrganizationLogo","validateOrganizationName","validateOrganizationSlug","removeOrganizationLogo","setOrganizationLogo","updateOrganization","organizationAliases","defineCommandTelemetry","updateOrgDebug","UPDATE_FLAGS","UpdateOrganizationCommand","args","organizationId","string","description","required","examples","command","flags","atLeastOne","logo","helpValue","name","slug","hiddenAliases","telemetry","redact","run","defaultRole","logoPath","params","undefined","trimmedName","trim","validation","error","exit","RUNTIME_ERROR","trimmedSlug","slugValidation","trimmedRole","defaultRoleName","spin","start","updatesFields","Object","keys","length","fail","failRequest","logoUrl","response","succeed","log","message","statusCode"],"mappings":"AAAA,SAAQA,IAAI,EAAEC,KAAK,QAAO,cAAa;AAEvC,SAAQC,SAAS,EAAEC,aAAa,EAAEC,QAAQ,QAAO,mBAAkB;AACnE,SAAQC,eAAe,QAAO,0BAAyB;AACvD,SAAQC,OAAO,QAAO,sBAAqB;AAC3C,SAAQC,WAAW,QAAO,iBAAgB;AAE1C,SAEEC,oBAAoB,QACf,sDAAqD;AAC5D,SAAQC,wBAAwB,QAAO,0DAAyD;AAChG,SAAQC,wBAAwB,QAAO,0DAAyD;AAChG,SAEEC,sBAAsB,EACtBC,mBAAmB,EACnBC,kBAAkB,QACb,kCAAiC;AACxC,SAAQC,mBAAmB,QAAO,oCAAmC;AACrE,SAAQC,sBAAsB,QAAO,2CAA0C;AAE/E,MAAMC,iBAAiBZ,SAAS;AAEhC,MAAMa,eAAe;IAAC;IAAQ;IAAQ;IAAgB;CAAO;AAE7D,OAAO,MAAMC,kCAAkCf;IAC7C,OAAgBgB,OAAO;QACrBC,gBAAgBpB,KAAKqB,MAAM,CAAC;YAC1BC,aAAa;YACbC,UAAU;QACZ;IACF,EAAC;IAED,OAAgBD,cAAc,yBAAwB;IAEtD,OAAgBE,WAAW;QACzB;YACEC,SAAS;YACTH,aAAa;QACf;QACA;YACEG,SA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EA,OAAO,QAAQ,SAAS,wBAAwB,CAAC;YAEtE;QACF;QAEAsB,KAAKU,OAAO;QACZ,IAAI,CAACC,GAAG,CAAC;QACT,IAAIjC,MAAM;YACR,IAAI,CAACiC,GAAG,CAAC,CAAC,MAAM,EAAEH,SAAS;QAC7B,OAAO,IAAI9B,SAAS,MAAM;YACxB,IAAI,CAACiC,GAAG,CAAC;QACX;IACF;IAEQJ,YAAYd,KAAc,EAAEmB,OAAe,EAAS;QAC1D9C,eAAe8C,SAASnB;QACxB,IAAIpC,YAAYoC,UAAUA,MAAMoB,UAAU,KAAK,KAAK;YAClD,IAAI,CAACpB,KAAK,CAAC,CAAC,cAAc,EAAE,IAAI,CAACxB,IAAI,CAACC,cAAc,CAAC,WAAW,CAAC,EAAE;gBACjEwB,MAAM1C,UAAU2C,aAAa;YAC/B;QACF;QACA,IAAI,CAACF,KAAK,CAAC,GAAGmB,QAAQ,EAAE,EAAEzD,gBAAgBsC,QAAQ,EAAE;YAACC,MAAM1C,UAAU2C,aAAa;QAAA;IACpF;AACF"}
|
|
@@ -219,11 +219,16 @@ function apiValidator({ args, flags }) {
|
|
|
219
219
|
// --web opens a browser on the machine running the MCP server.
|
|
220
220
|
'openapi:get': conditionalDenyFlags('web'),
|
|
221
221
|
'openapi:list': conditionalDenyFlags('web'),
|
|
222
|
-
|
|
222
|
+
// --logo reads an image from the machine running the command.
|
|
223
|
+
'organizations:create': conditionalDenyFlags('logo'),
|
|
223
224
|
'organizations:delete': allow,
|
|
224
225
|
'organizations:get': allow,
|
|
225
226
|
'organizations:list': allow,
|
|
226
|
-
|
|
227
|
+
// --logo reads an image from the machine running the command, except --logo "", which removes
|
|
228
|
+
// the logo and reads nothing.
|
|
229
|
+
'organizations:update': conditionalPolicy({
|
|
230
|
+
validate: ({ flags })=>flags.logo === undefined || flags.logo === ''
|
|
231
|
+
}),
|
|
227
232
|
// Serves a local production build.
|
|
228
233
|
preview: deny,
|
|
229
234
|
'projects:create': allow,
|