sanity 3.77.2-server-side-schemas.21 → 3.77.2-server-side-schemas.25

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.
@@ -1,33 +1,48 @@
1
1
  "use strict";
2
+ var chalk = require("chalk"), schemaListAction = require("./storeSchemasAction.js");
3
+ function _interopDefaultCompat(e) {
4
+ return e && typeof e == "object" && "default" in e ? e : { default: e };
5
+ }
6
+ var chalk__default = /* @__PURE__ */ _interopDefaultCompat(chalk);
2
7
  async function deleteSchemaAction(args, context) {
3
- const flags = args.extOptions, {
8
+ const flags = args.extOptions;
9
+ if (typeof flags.dataset == "boolean") throw new Error("Dataset is empty");
10
+ if (typeof flags.ids == "boolean") throw new Error("Ids are empty");
11
+ if (typeof flags.path == "boolean") throw new Error("Path is empty");
12
+ const {
4
13
  apiClient,
5
14
  output
6
- } = context;
7
- if (!flags.ids) {
8
- output.error("No schema ids provided");
9
- return;
10
- }
11
- const schemaIds = flags.ids.split(","), client = apiClient({
15
+ } = context, schemaIds = flags.ids.split(","), client = apiClient({
12
16
  requireUser: !0,
13
17
  requireProject: !0
14
18
  }).withConfig({
15
19
  apiVersion: "v2024-08-01"
16
- }), projectId = client.config().projectId, dataset = client.config().dataset;
17
- if (!projectId || !dataset) {
18
- output.error("Project ID and Dataset must be defined.");
20
+ }), projectId = client.config().projectId;
21
+ if (!projectId) {
22
+ output.error("Project ID must be defined.");
19
23
  return;
20
24
  }
21
- schemaIds.forEach(async (schemaId) => {
22
- if (!(await client.withConfig({
23
- dataset,
24
- projectId
25
- }).delete(schemaId.trim())).results.length) {
26
- output.error(`No schema found with id: ${schemaId}`);
27
- return;
25
+ const manifestPath = schemaListAction.getManifestPath(context, flags.path), manifest = schemaListAction.readManifest(manifestPath, output), deletedCount = (await Promise.allSettled(manifest.workspaces.flatMap((workspace) => flags.dataset && workspace.dataset !== flags.dataset ? [] : schemaIds.map(async (schemaId) => {
26
+ if (schemaId.split(".").at(-1) !== workspace.name && !flags.dataset)
27
+ return !1;
28
+ try {
29
+ return schemaListAction.throwIfProjectIdMismatch(workspace, projectId), (await client.withConfig({
30
+ dataset: flags.dataset || workspace.dataset,
31
+ projectId: workspace.projectId
32
+ }).delete(schemaId.trim())).results.length ? (output.success(`Schema ${schemaId} deleted from workspace: ${workspace.name}`), !0) : !1;
33
+ } catch (err) {
34
+ throw output.error(`Failed to delete schema ${schemaId} from workspace ${workspace.name}:
35
+ ${err.message}`), err;
36
+ }
37
+ })))).map((result, index) => {
38
+ if (result.status === "rejected") {
39
+ const schemaId = schemaIds[index];
40
+ return output.error(chalk__default.default.red(`Failed to delete schema '${schemaId}':
41
+ ${result.reason.message}`)), !1;
28
42
  }
29
- output.success(`Schema ${schemaId} deleted`);
30
- });
43
+ return result.value;
44
+ }).filter(Boolean).length;
45
+ output.print(`Successfully deleted ${deletedCount} schemas`);
31
46
  }
32
47
  exports.default = deleteSchemaAction;
33
48
  //# sourceMappingURL=deleteSchemaAction.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"deleteSchemaAction.js","sources":["../../src/_internal/cli/actions/schema/deleteSchemaAction.ts"],"sourcesContent":["import {type CliCommandArguments, type CliCommandContext} from '@sanity/cli'\n\nexport interface DeleteSchemaFlags {\n ids: string\n}\n\nexport default async function deleteSchemaAction(\n args: CliCommandArguments<DeleteSchemaFlags>,\n context: CliCommandContext,\n): Promise<void> {\n const flags = args.extOptions\n const {apiClient, output} = context\n\n if (!flags.ids) {\n output.error('No schema ids provided')\n return\n }\n //split ids by comma\n const schemaIds = flags.ids.split(',')\n\n const client = apiClient({\n requireUser: true,\n requireProject: true,\n }).withConfig({apiVersion: 'v2024-08-01'})\n\n const projectId = client.config().projectId\n const dataset = client.config().dataset\n\n if (!projectId || !dataset) {\n output.error('Project ID and Dataset must be defined.')\n return\n }\n\n schemaIds.forEach(async (schemaId) => {\n const deletedSchema = await client\n .withConfig({\n dataset: dataset,\n projectId: projectId,\n })\n .delete(schemaId.trim())\n\n if (!deletedSchema.results.length) {\n output.error(`No schema found with id: ${schemaId}`)\n return\n }\n\n output.success(`Schema ${schemaId} deleted`)\n })\n}\n"],"names":["deleteSchemaAction","args","context","flags","extOptions","apiClient","output","ids","error","schemaIds","split","client","requireUser","requireProject","withConfig","apiVersion","projectId","config","dataset","forEach","schemaId","delete","trim","results","length","success"],"mappings":";AAM8BA,eAAAA,mBAC5BC,MACAC,SACe;AACTC,QAAAA,QAAQF,KAAKG,YACb;AAAA,IAACC;AAAAA,IAAWC;AAAAA,EAAAA,IAAUJ;AAExB,MAAA,CAACC,MAAMI,KAAK;AACdD,WAAOE,MAAM,wBAAwB;AACrC;AAAA,EAAA;AAGF,QAAMC,YAAYN,MAAMI,IAAIG,MAAM,GAAG,GAE/BC,SAASN,UAAU;AAAA,IACvBO,aAAa;AAAA,IACbC,gBAAgB;AAAA,EACjB,CAAA,EAAEC,WAAW;AAAA,IAACC,YAAY;AAAA,EAAA,CAAc,GAEnCC,YAAYL,OAAOM,SAASD,WAC5BE,UAAUP,OAAOM,OAAAA,EAASC;AAE5B,MAAA,CAACF,aAAa,CAACE,SAAS;AAC1BZ,WAAOE,MAAM,yCAAyC;AACtD;AAAA,EAAA;AAGQW,YAAAA,QAAQ,OAAOC,aAAa;AAQhC,QAAA,EAPkB,MAAMT,OACzBG,WAAW;AAAA,MACVI;AAAAA,MACAF;AAAAA,IAAAA,CACD,EACAK,OAAOD,SAASE,MAAM,GAENC,QAAQC,QAAQ;AAC1BhB,aAAAA,MAAM,4BAA4BY,QAAQ,EAAE;AACnD;AAAA,IAAA;AAGKK,WAAAA,QAAQ,UAAUL,QAAQ,UAAU;AAAA,EAAA,CAC5C;AACH;;"}
1
+ {"version":3,"file":"deleteSchemaAction.js","sources":["../../src/_internal/cli/actions/schema/deleteSchemaAction.ts"],"sourcesContent":["import {type CliCommandArguments, type CliCommandContext} from '@sanity/cli'\nimport chalk from 'chalk'\n\nimport {type ManifestWorkspaceFile} from '../../../manifest/manifestTypes'\nimport {getManifestPath, readManifest, throwIfProjectIdMismatch} from './storeSchemasAction'\n\nexport interface DeleteSchemaFlags {\n ids: string\n path: string\n dataset: string\n}\n\nexport default async function deleteSchemaAction(\n args: CliCommandArguments<DeleteSchemaFlags>,\n context: CliCommandContext,\n): Promise<void> {\n const flags = args.extOptions\n if (typeof flags.dataset === 'boolean') throw new Error('Dataset is empty')\n if (typeof flags.ids === 'boolean') throw new Error('Ids are empty')\n if (typeof flags.path === 'boolean') throw new Error('Path is empty')\n\n const {apiClient, output} = context\n\n //split ids by comma\n const schemaIds = flags.ids.split(',')\n\n const client = apiClient({\n requireUser: true,\n requireProject: true,\n }).withConfig({apiVersion: 'v2024-08-01'})\n\n const projectId = client.config().projectId\n\n if (!projectId) {\n output.error('Project ID must be defined.')\n return\n }\n\n const manifestPath = getManifestPath(context, flags.path)\n const manifest = readManifest(manifestPath, output)\n\n const results = await Promise.allSettled(\n manifest.workspaces.flatMap((workspace: ManifestWorkspaceFile) => {\n if (flags.dataset && workspace.dataset !== flags.dataset) {\n return []\n }\n return schemaIds.map(async (schemaId) => {\n const idWorkspace = schemaId.split('.').at(-1)\n if (idWorkspace !== workspace.name && !flags.dataset) {\n return false\n }\n try {\n throwIfProjectIdMismatch(workspace, projectId)\n const deletedSchema = await client\n .withConfig({\n dataset: flags.dataset || workspace.dataset,\n projectId: workspace.projectId,\n })\n .delete(schemaId.trim())\n\n if (!deletedSchema.results.length) {\n return false\n }\n\n output.success(`Schema ${schemaId} deleted from workspace: ${workspace.name}`)\n return true\n } catch (err) {\n output.error(\n `Failed to delete schema ${schemaId} from workspace ${workspace.name}:\\n ${err.message}`,\n )\n throw err\n }\n })\n }),\n )\n\n // Log errors and collect results\n const deletedCount = results\n .map((result, index) => {\n if (result.status === 'rejected') {\n const schemaId = schemaIds[index]\n output.error(chalk.red(`Failed to delete schema '${schemaId}':\\n${result.reason.message}`))\n return false\n }\n return result.value\n })\n .filter(Boolean).length\n\n output.print(`Successfully deleted ${deletedCount} schemas`)\n}\n"],"names":["deleteSchemaAction","args","context","flags","extOptions","dataset","Error","ids","path","apiClient","output","schemaIds","split","client","requireUser","requireProject","withConfig","apiVersion","projectId","config","error","manifestPath","getManifestPath","manifest","readManifest","deletedCount","Promise","allSettled","workspaces","flatMap","workspace","map","schemaId","at","name","throwIfProjectIdMismatch","delete","trim","results","length","success","err","message","result","index","status","chalk","red","reason","value","filter","Boolean","print"],"mappings":";;;;;;AAY8BA,eAAAA,mBAC5BC,MACAC,SACe;AACf,QAAMC,QAAQF,KAAKG;AACnB,MAAI,OAAOD,MAAME,WAAY,UAAiB,OAAA,IAAIC,MAAM,kBAAkB;AAC1E,MAAI,OAAOH,MAAMI,OAAQ,UAAiB,OAAA,IAAID,MAAM,eAAe;AACnE,MAAI,OAAOH,MAAMK,QAAS,UAAiB,OAAA,IAAIF,MAAM,eAAe;AAE9D,QAAA;AAAA,IAACG;AAAAA,IAAWC;AAAAA,EAAAA,IAAUR,SAGtBS,YAAYR,MAAMI,IAAIK,MAAM,GAAG,GAE/BC,SAASJ,UAAU;AAAA,IACvBK,aAAa;AAAA,IACbC,gBAAgB;AAAA,EACjB,CAAA,EAAEC,WAAW;AAAA,IAACC,YAAY;AAAA,EAAc,CAAA,GAEnCC,YAAYL,OAAOM,OAASD,EAAAA;AAElC,MAAI,CAACA,WAAW;AACdR,WAAOU,MAAM,6BAA6B;AAC1C;AAAA,EAAA;AAGF,QAAMC,eAAeC,iBAAAA,gBAAgBpB,SAASC,MAAMK,IAAI,GAClDe,WAAWC,iBAAAA,aAAaH,cAAcX,MAAM,GAsC5Ce,gBApCU,MAAMC,QAAQC,WAC5BJ,SAASK,WAAWC,QAASC,CAAAA,cACvB3B,MAAME,WAAWyB,UAAUzB,YAAYF,MAAME,UACxC,CAAE,IAEJM,UAAUoB,IAAI,OAAOC,aAAa;AACnBA,QAAAA,SAASpB,MAAM,GAAG,EAAEqB,GAAG,EAAE,MACzBH,UAAUI,QAAQ,CAAC/B,MAAME;AACpC,aAAA;AAEL,QAAA;AASF,aARA8B,iBAAAA,yBAAyBL,WAAWZ,SAAS,IACvB,MAAML,OACzBG,WAAW;AAAA,QACVX,SAASF,MAAME,WAAWyB,UAAUzB;AAAAA,QACpCa,WAAWY,UAAUZ;AAAAA,MAAAA,CACtB,EACAkB,OAAOJ,SAASK,KAAK,CAAC,GAENC,QAAQC,UAI3B7B,OAAO8B,QAAQ,UAAUR,QAAQ,4BAA4BF,UAAUI,IAAI,EAAE,GACtE,MAJE;AAAA,aAKFO,KAAK;AACZ/B,YAAAA,OAAOU,MACL,2BAA2BY,QAAQ,mBAAmBF,UAAUI,IAAI;AAAA,GAAOO,IAAIC,OAAO,EACxF,GACMD;AAAAA,IAAAA;AAAAA,EAET,CAAA,CACF,CACH,GAIGV,IAAI,CAACY,QAAQC,UAAU;AAClBD,QAAAA,OAAOE,WAAW,YAAY;AAC1Bb,YAAAA,WAAWrB,UAAUiC,KAAK;AAChClC,aAAAA,OAAOU,MAAM0B,eAAAA,QAAMC,IAAI,4BAA4Bf,QAAQ;AAAA,EAAOW,OAAOK,OAAON,OAAO,EAAE,CAAC,GACnF;AAAA,IAAA;AAET,WAAOC,OAAOM;AAAAA,EAAAA,CACf,EACAC,OAAOC,OAAO,EAAEZ;AAEZa,SAAAA,MAAM,wBAAwB3B,YAAY,UAAU;AAC7D;;"}
@@ -1,5 +1,5 @@
1
1
  "use strict";
2
- var path = require("node:path"), zlib = require("node:zlib"), tar = require("tar-fs"), buildAction = require("./buildAction.js"), extractManifestAction = require("./extractManifestAction.js"), storeSchemasAction = require("./storeSchemasAction.js"), helpers = require("./helpers.js");
2
+ var path = require("node:path"), zlib = require("node:zlib"), tar = require("tar-fs"), buildAction = require("./buildAction.js"), extractManifestAction = require("./extractManifestAction.js"), schemaListAction = require("./storeSchemasAction.js"), helpers = require("./helpers.js");
3
3
  function _interopDefaultCompat(e) {
4
4
  return e && typeof e == "object" && "default" in e ? e : { default: e };
5
5
  }
@@ -93,7 +93,7 @@ async function deployStudioAction(args, context) {
93
93
  verbose: flags.verbose
94
94
  }
95
95
  };
96
- await storeSchemasAction.default(storeManifestSchemasArgs, context);
96
+ await schemaListAction.storeSchemasAction(storeManifestSchemasArgs, context);
97
97
  }
98
98
  spinner = output.spinner("Verifying local content").start();
99
99
  try {
@@ -1 +1 @@
1
- {"version":3,"file":"deployAction.js","sources":["../../src/_internal/cli/actions/deploy/deployAction.ts"],"sourcesContent":["/* eslint-disable max-statements */\nimport path from 'node:path'\nimport zlib from 'node:zlib'\n\nimport {type CliCommandArguments, type CliCommandContext} from '@sanity/cli'\nimport tar from 'tar-fs'\n\nimport {shouldAutoUpdate} from '../../util/shouldAutoUpdate'\nimport buildSanityStudio, {type BuildSanityStudioCommandFlags} from '../build/buildAction'\nimport {extractManifestSafe} from '../manifest/extractManifestAction'\nimport storeManifestSchemas from '../schema/storeSchemasAction'\nimport {\n type BaseConfigOptions,\n checkDir,\n createDeployment,\n debug,\n dirIsEmptyOrNonExistent,\n getInstalledSanityVersion,\n getOrCreateCoreApplication,\n getOrCreateStudio,\n getOrCreateUserApplicationFromConfig,\n type UserApplication,\n} from './helpers'\n\nexport interface DeployStudioActionFlags extends BuildSanityStudioCommandFlags {\n 'build'?: boolean\n 'schema-required'?: boolean\n 'verbose'?: boolean\n}\n\n// eslint-disable-next-line complexity\nexport default async function deployStudioAction(\n args: CliCommandArguments<DeployStudioActionFlags>,\n context: CliCommandContext,\n): Promise<void> {\n const {apiClient, workDir, chalk, output, prompt, cliConfig} = context\n const flags = {build: true, ...args.extOptions}\n const customSourceDir = args.argsWithoutOptions[0]\n const sourceDir = path.resolve(process.cwd(), customSourceDir || path.join(workDir, 'dist'))\n const isAutoUpdating = shouldAutoUpdate({flags, cliConfig})\n const isCoreApp = cliConfig && '__experimental_coreAppConfiguration' in cliConfig\n\n const installedSanityVersion = await getInstalledSanityVersion()\n const configStudioHost = cliConfig && 'studioHost' in cliConfig && cliConfig.studioHost\n const appId =\n cliConfig &&\n '__experimental_coreAppConfiguration' in cliConfig &&\n cliConfig.__experimental_coreAppConfiguration?.appId\n\n const client = apiClient({\n requireUser: true,\n requireProject: !isCoreApp, // core apps are not project-specific\n }).withConfig({apiVersion: 'v2024-08-01'})\n\n if (customSourceDir === 'graphql') {\n throw new Error('Did you mean `sanity graphql deploy`?')\n }\n\n if (customSourceDir) {\n let relativeOutput = path.relative(process.cwd(), sourceDir)\n if (relativeOutput[0] !== '.') {\n relativeOutput = `./${relativeOutput}`\n }\n\n const isEmpty = await dirIsEmptyOrNonExistent(sourceDir)\n const shouldProceed =\n isEmpty ||\n (await prompt.single({\n type: 'confirm',\n message: `\"${relativeOutput}\" is not empty, do you want to proceed?`,\n default: false,\n }))\n\n if (!shouldProceed) {\n output.print('Cancelled.')\n return\n }\n\n output.print(`Building to ${relativeOutput}\\n`)\n }\n\n // Check that the project has a studio hostname\n let spinner = output.spinner('Checking project info').start()\n\n let userApplication: UserApplication\n\n try {\n const configParams: BaseConfigOptions & {\n appHost?: string\n appId?: string\n } = {\n client,\n context,\n spinner,\n }\n\n if (isCoreApp && appId) {\n configParams.appId = appId\n } else if (configStudioHost) {\n configParams.appHost = configStudioHost\n }\n // If the user has provided a studioHost / appId in the config, use that\n if (configStudioHost || appId) {\n userApplication = await getOrCreateUserApplicationFromConfig(configParams)\n } else {\n userApplication = isCoreApp\n ? await getOrCreateCoreApplication({client, context, spinner})\n : await getOrCreateStudio({client, context, spinner})\n }\n } catch (err) {\n if (err.message) {\n output.error(chalk.red(err.message))\n return\n }\n\n debug('Error creating user application', err)\n throw err\n }\n\n // Always build the project, unless --no-build is passed\n const shouldBuild = flags.build\n if (shouldBuild) {\n const buildArgs = {\n ...args,\n extOptions: flags,\n argsWithoutOptions: [customSourceDir].filter(Boolean),\n }\n const {didCompile} = await buildSanityStudio(buildArgs, context, {basePath: '/'})\n\n if (!didCompile) {\n return\n }\n\n if (!isCoreApp) {\n const extractManifestError = await extractManifestSafe(\n {\n ...buildArgs,\n extOptions: {},\n extraArguments: [],\n },\n context,\n )\n\n if (flags['schema-required'] && extractManifestError) {\n output.error(`Schema extraction error: ${extractManifestError.message}`)\n throw extractManifestError\n }\n }\n }\n\n if (!isCoreApp) {\n const storeManifestSchemasArgs = {\n ...args,\n extOptions: {\n 'path': `${sourceDir}/static`,\n 'schema-required': flags['schema-required'],\n 'verbose': flags.verbose,\n },\n extraArguments: [],\n }\n\n await storeManifestSchemas(storeManifestSchemasArgs, context)\n }\n\n // Ensure that the directory exists, is a directory and seems to have valid content\n spinner = output.spinner('Verifying local content').start()\n try {\n await checkDir(sourceDir)\n spinner.succeed()\n } catch (err) {\n spinner.fail()\n debug('Error checking directory', err)\n throw err\n }\n\n // Now create a tarball of the given directory\n const parentDir = path.dirname(sourceDir)\n const base = path.basename(sourceDir)\n const tarball = tar.pack(parentDir, {entries: [base]}).pipe(zlib.createGzip())\n\n spinner = output.spinner(`Deploying to ${isCoreApp ? 'CORE' : 'Sanity.Studio'}`).start()\n try {\n const {location} = await createDeployment({\n client,\n applicationId: userApplication.id,\n version: installedSanityVersion,\n isAutoUpdating,\n tarball,\n isCoreApp,\n })\n\n spinner.succeed()\n\n output.print()\n\n // And let the user know we're done\n output.print(\n `\\nSuccess! ${isCoreApp ? 'Application deployed' : `Studio deployed to ${chalk.cyan(location)}`}`,\n )\n\n if ((isCoreApp && !appId) || (!isCoreApp && !configStudioHost)) {\n output.print(\n `\\nAdd ${chalk.cyan(isCoreApp ? `appId: '${userApplication.id}'` : `studioHost: '${userApplication.appHost}'`)}`,\n )\n output.print(\n `to ${isCoreApp ? '__experimental_coreAppConfiguration' : 'defineCliConfig root properties'} in sanity.cli.js or sanity.cli.ts`,\n )\n output.print(`to avoid prompting ${isCoreApp ? '' : 'for hostname'} on next deploy.`)\n }\n } catch (err) {\n spinner.fail()\n debug('Error deploying studio', err)\n throw err\n }\n}\n"],"names":["deployStudioAction","args","context","apiClient","workDir","chalk","output","prompt","cliConfig","flags","build","extOptions","customSourceDir","argsWithoutOptions","sourceDir","path","resolve","process","cwd","join","isAutoUpdating","shouldAutoUpdate","isCoreApp","installedSanityVersion","getInstalledSanityVersion","configStudioHost","studioHost","appId","__experimental_coreAppConfiguration","client","requireUser","requireProject","withConfig","apiVersion","Error","relativeOutput","relative","dirIsEmptyOrNonExistent","single","type","message","default","print","spinner","start","userApplication","configParams","appHost","getOrCreateUserApplicationFromConfig","getOrCreateCoreApplication","getOrCreateStudio","err","error","red","debug","buildArgs","filter","Boolean","didCompile","buildSanityStudio","basePath","extractManifestError","extractManifestSafe","extraArguments","storeManifestSchemasArgs","verbose","storeManifestSchemas","checkDir","succeed","fail","parentDir","dirname","base","basename","tarball","tar","pack","entries","pipe","zlib","createGzip","location","createDeployment","applicationId","id","version","cyan"],"mappings":";;;;;;AA+B8BA,eAAAA,mBAC5BC,MACAC,SACe;AACT,QAAA;AAAA,IAACC;AAAAA,IAAWC;AAAAA,IAASC;AAAAA,IAAOC;AAAAA,IAAQC;AAAAA,IAAQC;AAAAA,EAAAA,IAAaN,SACzDO,QAAQ;AAAA,IAACC,OAAO;AAAA,IAAM,GAAGT,KAAKU;AAAAA,EAAAA,GAC9BC,kBAAkBX,KAAKY,mBAAmB,CAAC,GAC3CC,YAAYC,cAAAA,QAAKC,QAAQC,QAAQC,OAAON,mBAAmBG,sBAAKI,KAAKf,SAAS,MAAM,CAAC,GACrFgB,iBAAiBC,6BAAiB;AAAA,IAACZ;AAAAA,IAAOD;AAAAA,EAAU,CAAA,GACpDc,YAAYd,aAAa,yCAAyCA,WAElEe,yBAAyB,MAAMC,kCAA0B,GACzDC,mBAAmBjB,aAAa,gBAAgBA,aAAaA,UAAUkB,YACvEC,QACJnB,aACA,yCAAyCA,aACzCA,UAAUoB,qCAAqCD,OAE3CE,SAAS1B,UAAU;AAAA,IACvB2B,aAAa;AAAA,IACbC,gBAAgB,CAACT;AAAAA;AAAAA,EAClB,CAAA,EAAEU,WAAW;AAAA,IAACC,YAAY;AAAA,EAAA,CAAc;AAEzC,MAAIrB,oBAAoB;AAChB,UAA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AE,EAAEsB,MAAM;AACnF,MAAA;AACI,UAAA;AAAA,MAACqC;AAAAA,IAAQ,IAAI,MAAMC,QAAAA,iBAAiB;AAAA,MACxCrD;AAAAA,MACAsD,eAAetC,gBAAgBuC;AAAAA,MAC/BC,SAAS9D;AAAAA,MACTH;AAAAA,MACAsD;AAAAA,MACApD;AAAAA,IAAAA,CACD;AAEDqB,YAAQyB,WAER9D,OAAOoC,MAAM,GAGbpC,OAAOoC,MACL;AAAA,WAAcpB,YAAY,yBAAyB,sBAAsBjB,MAAMiF,KAAKL,QAAQ,CAAC,EAAE,EACjG,IAEK3D,aAAa,CAACK,SAAW,CAACL,aAAa,CAACG,sBAC3CnB,OAAOoC,MACL;AAAA,MAASrC,MAAMiF,KAAKhE,YAAY,WAAWuB,gBAAgBuC,EAAE,MAAM,gBAAgBvC,gBAAgBE,OAAO,GAAG,CAAC,EAChH,GACAzC,OAAOoC,MACL,MAAMpB,YAAY,wCAAwC,iCAAiC,oCAC7F,GACAhB,OAAOoC,MAAM,sBAAsBpB,YAAY,KAAK,cAAc,kBAAkB;AAAA,WAE/E6B,KAAK;AACZR,UAAAA,QAAQ0B,KAAK,GACbf,QAAM,MAAA,0BAA0BH,GAAG,GAC7BA;AAAAA,EAAAA;AAEV;;"}
1
+ {"version":3,"file":"deployAction.js","sources":["../../src/_internal/cli/actions/deploy/deployAction.ts"],"sourcesContent":["/* eslint-disable max-statements */\nimport path from 'node:path'\nimport zlib from 'node:zlib'\n\nimport {type CliCommandArguments, type CliCommandContext} from '@sanity/cli'\nimport tar from 'tar-fs'\n\nimport {shouldAutoUpdate} from '../../util/shouldAutoUpdate'\nimport buildSanityStudio, {type BuildSanityStudioCommandFlags} from '../build/buildAction'\nimport {extractManifestSafe} from '../manifest/extractManifestAction'\nimport storeManifestSchemas from '../schema/storeSchemasAction'\nimport {\n type BaseConfigOptions,\n checkDir,\n createDeployment,\n debug,\n dirIsEmptyOrNonExistent,\n getInstalledSanityVersion,\n getOrCreateCoreApplication,\n getOrCreateStudio,\n getOrCreateUserApplicationFromConfig,\n type UserApplication,\n} from './helpers'\n\nexport interface DeployStudioActionFlags extends BuildSanityStudioCommandFlags {\n 'build'?: boolean\n 'schema-required'?: boolean\n 'verbose'?: boolean\n}\n\n// eslint-disable-next-line complexity\nexport default async function deployStudioAction(\n args: CliCommandArguments<DeployStudioActionFlags>,\n context: CliCommandContext,\n): Promise<void> {\n const {apiClient, workDir, chalk, output, prompt, cliConfig} = context\n const flags = {build: true, ...args.extOptions}\n const customSourceDir = args.argsWithoutOptions[0]\n const sourceDir = path.resolve(process.cwd(), customSourceDir || path.join(workDir, 'dist'))\n const isAutoUpdating = shouldAutoUpdate({flags, cliConfig})\n const isCoreApp = cliConfig && '__experimental_coreAppConfiguration' in cliConfig\n\n const installedSanityVersion = await getInstalledSanityVersion()\n const configStudioHost = cliConfig && 'studioHost' in cliConfig && cliConfig.studioHost\n const appId =\n cliConfig &&\n '__experimental_coreAppConfiguration' in cliConfig &&\n cliConfig.__experimental_coreAppConfiguration?.appId\n\n const client = apiClient({\n requireUser: true,\n requireProject: !isCoreApp, // core apps are not project-specific\n }).withConfig({apiVersion: 'v2024-08-01'})\n\n if (customSourceDir === 'graphql') {\n throw new Error('Did you mean `sanity graphql deploy`?')\n }\n\n if (customSourceDir) {\n let relativeOutput = path.relative(process.cwd(), sourceDir)\n if (relativeOutput[0] !== '.') {\n relativeOutput = `./${relativeOutput}`\n }\n\n const isEmpty = await dirIsEmptyOrNonExistent(sourceDir)\n const shouldProceed =\n isEmpty ||\n (await prompt.single({\n type: 'confirm',\n message: `\"${relativeOutput}\" is not empty, do you want to proceed?`,\n default: false,\n }))\n\n if (!shouldProceed) {\n output.print('Cancelled.')\n return\n }\n\n output.print(`Building to ${relativeOutput}\\n`)\n }\n\n // Check that the project has a studio hostname\n let spinner = output.spinner('Checking project info').start()\n\n let userApplication: UserApplication\n\n try {\n const configParams: BaseConfigOptions & {\n appHost?: string\n appId?: string\n } = {\n client,\n context,\n spinner,\n }\n\n if (isCoreApp && appId) {\n configParams.appId = appId\n } else if (configStudioHost) {\n configParams.appHost = configStudioHost\n }\n // If the user has provided a studioHost / appId in the config, use that\n if (configStudioHost || appId) {\n userApplication = await getOrCreateUserApplicationFromConfig(configParams)\n } else {\n userApplication = isCoreApp\n ? await getOrCreateCoreApplication({client, context, spinner})\n : await getOrCreateStudio({client, context, spinner})\n }\n } catch (err) {\n if (err.message) {\n output.error(chalk.red(err.message))\n return\n }\n\n debug('Error creating user application', err)\n throw err\n }\n\n // Always build the project, unless --no-build is passed\n const shouldBuild = flags.build\n if (shouldBuild) {\n const buildArgs = {\n ...args,\n extOptions: flags,\n argsWithoutOptions: [customSourceDir].filter(Boolean),\n }\n const {didCompile} = await buildSanityStudio(buildArgs, context, {basePath: '/'})\n\n if (!didCompile) {\n return\n }\n\n if (!isCoreApp) {\n const extractManifestError = await extractManifestSafe(\n {\n ...buildArgs,\n extOptions: {},\n extraArguments: [],\n },\n context,\n )\n\n if (flags['schema-required'] && extractManifestError) {\n output.error(`Schema extraction error: ${extractManifestError.message}`)\n throw extractManifestError\n }\n }\n }\n\n if (!isCoreApp) {\n const storeManifestSchemasArgs = {\n ...args,\n extOptions: {\n 'path': `${sourceDir}/static`,\n 'schema-required': flags['schema-required'],\n 'verbose': flags.verbose,\n },\n extraArguments: [],\n }\n\n await storeManifestSchemas(storeManifestSchemasArgs, context)\n }\n\n // Ensure that the directory exists, is a directory and seems to have valid content\n spinner = output.spinner('Verifying local content').start()\n try {\n await checkDir(sourceDir)\n spinner.succeed()\n } catch (err) {\n spinner.fail()\n debug('Error checking directory', err)\n throw err\n }\n\n // Now create a tarball of the given directory\n const parentDir = path.dirname(sourceDir)\n const base = path.basename(sourceDir)\n const tarball = tar.pack(parentDir, {entries: [base]}).pipe(zlib.createGzip())\n\n spinner = output.spinner(`Deploying to ${isCoreApp ? 'CORE' : 'Sanity.Studio'}`).start()\n try {\n const {location} = await createDeployment({\n client,\n applicationId: userApplication.id,\n version: installedSanityVersion,\n isAutoUpdating,\n tarball,\n isCoreApp,\n })\n\n spinner.succeed()\n\n output.print()\n\n // And let the user know we're done\n output.print(\n `\\nSuccess! ${isCoreApp ? 'Application deployed' : `Studio deployed to ${chalk.cyan(location)}`}`,\n )\n\n if ((isCoreApp && !appId) || (!isCoreApp && !configStudioHost)) {\n output.print(\n `\\nAdd ${chalk.cyan(isCoreApp ? `appId: '${userApplication.id}'` : `studioHost: '${userApplication.appHost}'`)}`,\n )\n output.print(\n `to ${isCoreApp ? '__experimental_coreAppConfiguration' : 'defineCliConfig root properties'} in sanity.cli.js or sanity.cli.ts`,\n )\n output.print(`to avoid prompting ${isCoreApp ? '' : 'for hostname'} on next deploy.`)\n }\n } catch (err) {\n spinner.fail()\n debug('Error deploying studio', err)\n throw err\n }\n}\n"],"names":["deployStudioAction","args","context","apiClient","workDir","chalk","output","prompt","cliConfig","flags","build","extOptions","customSourceDir","argsWithoutOptions","sourceDir","path","resolve","process","cwd","join","isAutoUpdating","shouldAutoUpdate","isCoreApp","installedSanityVersion","getInstalledSanityVersion","configStudioHost","studioHost","appId","__experimental_coreAppConfiguration","client","requireUser","requireProject","withConfig","apiVersion","Error","relativeOutput","relative","dirIsEmptyOrNonExistent","single","type","message","default","print","spinner","start","userApplication","configParams","appHost","getOrCreateUserApplicationFromConfig","getOrCreateCoreApplication","getOrCreateStudio","err","error","red","debug","buildArgs","filter","Boolean","didCompile","buildSanityStudio","basePath","extractManifestError","extractManifestSafe","extraArguments","storeManifestSchemasArgs","verbose","storeManifestSchemas","checkDir","succeed","fail","parentDir","dirname","base","basename","tarball","tar","pack","entries","pipe","zlib","createGzip","location","createDeployment","applicationId","id","version","cyan"],"mappings":";;;;;;AA+B8BA,eAAAA,mBAC5BC,MACAC,SACe;AACT,QAAA;AAAA,IAACC;AAAAA,IAAWC;AAAAA,IAASC;AAAAA,IAAOC;AAAAA,IAAQC;AAAAA,IAAQC;AAAAA,EAAAA,IAAaN,SACzDO,QAAQ;AAAA,I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AM,sBAAsBpB,YAAY,KAAK,cAAc,kBAAkB;AAAA,WAE/E6B,KAAK;AACZR,UAAAA,QAAQ0B,KAAK,GACbf,QAAM,MAAA,0BAA0BH,GAAG,GAC7BA;AAAAA,EAAAA;AAEV;;"}
@@ -1,44 +1,107 @@
1
1
  "use strict";
2
- var fs = require("node:fs"), path = require("node:path"), chalk = require("chalk"), extractManifestAction = require("./extractManifestAction.js"), schemaListAction = require("./schemaListAction.js");
2
+ var fs = require("node:fs"), path = require("node:path"), chalk = require("chalk"), extractManifestAction = require("./extractManifestAction.js"), size = require("lodash/size.js"), sortBy = require("lodash/sortBy.js"), uniqBy = require("lodash/uniqBy.js");
3
3
  function _interopDefaultCompat(e) {
4
4
  return e && typeof e == "object" && "default" in e ? e : { default: e };
5
5
  }
6
- var path__default = /* @__PURE__ */ _interopDefaultCompat(path), chalk__default = /* @__PURE__ */ _interopDefaultCompat(chalk);
6
+ var path__default = /* @__PURE__ */ _interopDefaultCompat(path), chalk__default = /* @__PURE__ */ _interopDefaultCompat(chalk), size__default = /* @__PURE__ */ _interopDefaultCompat(size), sortBy__default = /* @__PURE__ */ _interopDefaultCompat(sortBy), uniqBy__default = /* @__PURE__ */ _interopDefaultCompat(uniqBy);
7
+ const SANITY_WORKSPACE_SCHEMA_TYPE = "sanity.workspace.schema", printSchemaList = ({
8
+ schemas,
9
+ output
10
+ }) => {
11
+ const ordered = sortBy__default.default(schemas.map(({
12
+ _createdAt: createdAt,
13
+ _id: id,
14
+ workspace
15
+ }) => [id, workspace.name, workspace.dataset, workspace.projectId, createdAt].map(String)), ["createdAt"]), headings = ["Id", "Workspace", "Dataset", "ProjectId", "CreatedAt"], rows = ordered.reverse(), maxWidths = rows.reduce((max, row) => row.map((current, index) => Math.max(size__default.default(current), max[index])), headings.map((str) => size__default.default(str))), printRow = (row) => row.map((col, i) => `${col}`.padEnd(maxWidths[i])).join(" ");
16
+ output.print(chalk__default.default.cyan(printRow(headings))), rows.forEach((row) => output.print(printRow(row)));
17
+ };
18
+ async function fetchSchemaAction(args, context) {
19
+ const flags = args.extOptions, {
20
+ apiClient,
21
+ output
22
+ } = context, client = apiClient({
23
+ requireUser: !0,
24
+ requireProject: !0
25
+ }).withConfig({
26
+ apiVersion: "v2024-08-01"
27
+ }), projectId = client.config().projectId;
28
+ if (!projectId) {
29
+ output.error("Project ID must be defined.");
30
+ return;
31
+ }
32
+ const manifestPath = getManifestPath(context, flags.path), manifest = readManifest(manifestPath, output), schemas = (await Promise.allSettled(uniqBy__default.default(manifest.workspaces, "dataset").map(async (workspace) => (throwIfProjectIdMismatch(workspace, projectId), flags.id ? await client.withConfig({
33
+ dataset: workspace.dataset,
34
+ projectId: workspace.projectId
35
+ }).getDocument(flags.id) : await client.withConfig({
36
+ dataset: workspace.dataset,
37
+ projectId: workspace.projectId,
38
+ useCdn: !1
39
+ }).fetch("*[_type == $type]", {
40
+ type: SANITY_WORKSPACE_SCHEMA_TYPE
41
+ }))))).map((result, index) => {
42
+ if (result.status === "rejected") {
43
+ const workspace = manifest.workspaces[index];
44
+ return output.error(chalk__default.default.red(`Failed to fetch schemas for workspace '${workspace.name}': ${result.reason.message}`)), [];
45
+ }
46
+ return result.value;
47
+ }).flat();
48
+ if (schemas.length === 0) {
49
+ output.error("No schemas found");
50
+ return;
51
+ }
52
+ flags.json ? output.print(`${JSON.stringify(schemas, null, 2)}`) : printSchemaList({
53
+ schemas,
54
+ output
55
+ });
56
+ }
57
+ var schemaListAction = /* @__PURE__ */ Object.freeze({
58
+ __proto__: null,
59
+ SANITY_WORKSPACE_SCHEMA_TYPE,
60
+ default: fetchSchemaAction
61
+ });
62
+ const getManifestPath = (context, customPath) => {
63
+ const defaultOutputDir = path.resolve(path.join(context.workDir, "dist")), outputDir = path.resolve(defaultOutputDir), defaultStaticPath = path.join(outputDir, "static"), staticPath = customPath ?? defaultStaticPath;
64
+ return path__default.default.resolve(process.cwd(), staticPath);
65
+ }, readManifest = (readPath, output, spinner) => {
66
+ try {
67
+ return JSON.parse(fs.readFileSync(`${readPath}/${extractManifestAction.MANIFEST_FILENAME}`, "utf-8"));
68
+ } catch (error) {
69
+ const errorMessage = `Manifest not found at ${readPath}/${extractManifestAction.MANIFEST_FILENAME}`;
70
+ throw spinner && spinner.fail(errorMessage), output && output.error(errorMessage), error;
71
+ }
72
+ }, throwIfProjectIdMismatch = (workspace, projectId) => {
73
+ if (workspace.projectId !== projectId)
74
+ throw new Error(`\u21B3 No permissions to store schema for workspace ${workspace.name} with projectId: ${workspace.projectId}`);
75
+ };
7
76
  async function storeSchemasAction(args, context) {
8
- const flags = args.extOptions;
77
+ const flags = args.extOptions, schemaRequired = flags["schema-required"], workspaceName = flags.workspace, idPrefix = flags["id-prefix"], verbose = flags.verbose;
9
78
  if (typeof flags.path == "boolean") throw new Error("Path is empty");
10
- if (typeof flags["id-prefix"] == "boolean") throw new Error("Id prefix is empty");
11
- if (typeof flags.workspace == "boolean") throw new Error("Workspace is empty");
12
- const schemaRequired = flags["schema-required"], workspaceName = flags.workspace, idPrefix = flags["id-prefix"], verbose = flags.verbose, {
79
+ if (typeof idPrefix == "boolean") throw new Error("Id prefix is empty");
80
+ if (typeof workspaceName == "boolean") throw new Error("Workspace is empty");
81
+ const {
13
82
  output,
14
- workDir,
15
83
  apiClient
16
- } = context, defaultOutputDir = path.resolve(path.join(workDir, "dist")), outputDir = path.resolve(defaultOutputDir), defaultStaticPath = path.join(outputDir, "static"), staticPath = flags.path ?? defaultStaticPath, spinner = output.spinner({}).start("Storing schemas");
84
+ } = context, spinner = output.spinner({}).start("Storing schemas"), manifestPath = getManifestPath(context, flags.path);
17
85
  try {
18
- const manifestPath = path__default.default.resolve(process.cwd(), staticPath), client = apiClient({
86
+ const client = apiClient({
19
87
  requireUser: !0,
20
88
  requireProject: !0
21
89
  }).withConfig({
22
90
  apiVersion: "v2024-08-01"
23
91
  }), projectId = client.config().projectId;
24
- let manifest;
25
- try {
26
- manifest = JSON.parse(fs.readFileSync(`${manifestPath}/${extractManifestAction.MANIFEST_FILENAME}`, "utf-8"));
27
- } catch (error2) {
28
- throw spinner.fail(`Manifest not found at ${manifestPath}/${extractManifestAction.MANIFEST_FILENAME}`), output.error(error2), error2;
29
- }
92
+ if (!projectId) throw new Error("Project ID is not defined");
93
+ const manifest = readManifest(manifestPath, output, spinner);
30
94
  let storedCount = 0, error;
31
95
  const saveSchema = async (workspace) => {
32
- const id = `${idPrefix ? `${idPrefix}.` : ""}${schemaListAction.SANITY_WORKSPACE_SCHEMA_ID}.${workspace.name}`;
96
+ const id = `${idPrefix ? `${idPrefix}.` : ""}${SANITY_WORKSPACE_SCHEMA_TYPE}.${workspace.name}`;
33
97
  try {
34
- if (workspace.projectId !== projectId)
35
- throw new Error(`\u21B3 No permissions to store schema for workspace ${workspace.name} with projectId: ${workspace.projectId}`);
98
+ throwIfProjectIdMismatch(workspace, projectId);
36
99
  const schema = JSON.parse(fs.readFileSync(`${manifestPath}/${workspace.schema}`, "utf-8"));
37
100
  await client.withConfig({
38
101
  dataset: workspace.dataset,
39
102
  projectId: workspace.projectId
40
103
  }).transaction().createOrReplace({
41
- _type: schemaListAction.SANITY_WORKSPACE_SCHEMA_ID,
104
+ _type: SANITY_WORKSPACE_SCHEMA_TYPE,
42
105
  _id: id,
43
106
  workspace,
44
107
  schema
@@ -68,5 +131,17 @@ ${chalk__default.default.red(`${err.message}`)}`), schemaRequired) throw err;
68
131
  output.print(`${chalk__default.default.gray("\u21B3 List stored schemas with:")} ${chalk__default.default.cyan("sanity schema list")}`);
69
132
  }
70
133
  }
71
- exports.default = storeSchemasAction;
134
+ var storeSchemasAction$1 = /* @__PURE__ */ Object.freeze({
135
+ __proto__: null,
136
+ default: storeSchemasAction,
137
+ getManifestPath,
138
+ readManifest,
139
+ throwIfProjectIdMismatch
140
+ });
141
+ exports.getManifestPath = getManifestPath;
142
+ exports.readManifest = readManifest;
143
+ exports.schemaListAction = schemaListAction;
144
+ exports.storeSchemasAction = storeSchemasAction;
145
+ exports.storeSchemasAction$1 = storeSchemasAction$1;
146
+ exports.throwIfProjectIdMismatch = throwIfProjectIdMismatch;
72
147
  //# sourceMappingURL=storeSchemasAction.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"storeSchemasAction.js","sources":["../../src/_internal/cli/actions/schema/storeSchemasAction.ts"],"sourcesContent":["import {readFileSync} from 'node:fs'\nimport path, {join, resolve} from 'node:path'\n\nimport {type CliCommandArguments, type CliCommandContext} from '@sanity/cli'\nimport chalk from 'chalk'\n\nimport {\n type CreateManifest,\n type ManifestSchemaType,\n type ManifestWorkspaceFile,\n} from '../../../manifest/manifestTypes'\nimport {MANIFEST_FILENAME} from '../manifest/extractManifestAction'\nimport {SANITY_WORKSPACE_SCHEMA_ID} from './schemaListAction'\n\nexport interface StoreManifestSchemasFlags {\n 'path'?: string\n 'workspace'?: string\n 'id-prefix'?: string\n 'schema-required'?: boolean\n 'verbose'?: boolean\n}\n\nexport default async function storeSchemasAction(\n args: CliCommandArguments<StoreManifestSchemasFlags>,\n context: CliCommandContext,\n): Promise<Error | undefined> {\n const flags = args.extOptions\n if (typeof flags.path === 'boolean') throw new Error('Path is empty')\n if (typeof flags['id-prefix'] === 'boolean') throw new Error('Id prefix is empty')\n if (typeof flags.workspace === 'boolean') throw new Error('Workspace is empty')\n\n const schemaRequired = flags['schema-required']\n const workspaceName = flags.workspace\n const idPrefix = flags['id-prefix']\n const verbose = flags.verbose\n const {output, workDir, apiClient} = context\n\n const defaultOutputDir = resolve(join(workDir, 'dist'))\n\n const outputDir = resolve(defaultOutputDir)\n const defaultStaticPath = join(outputDir, 'static')\n\n const staticPath = flags.path ?? defaultStaticPath\n\n const spinner = output.spinner({}).start('Storing schemas')\n\n try {\n const manifestPath = path.resolve(process.cwd(), staticPath)\n const client = apiClient({\n requireUser: true,\n requireProject: true,\n }).withConfig({apiVersion: 'v2024-08-01'})\n\n const projectId = client.config().projectId\n\n let manifest: CreateManifest\n\n try {\n manifest = JSON.parse(readFileSync(`${manifestPath}/${MANIFEST_FILENAME}`, 'utf-8'))\n } catch (error) {\n spinner.fail(`Manifest not found at ${manifestPath}/${MANIFEST_FILENAME}`)\n output.error(error)\n throw error\n }\n\n let storedCount = 0\n\n let error: Error | undefined\n\n const saveSchema = async (workspace: ManifestWorkspaceFile) => {\n const id = `${idPrefix ? `${idPrefix}.` : ''}${SANITY_WORKSPACE_SCHEMA_ID}.${workspace.name}`\n try {\n if (workspace.projectId !== projectId) {\n throw new Error(\n `↳ No permissions to store schema for workspace ${workspace.name} with projectId: ${workspace.projectId}`,\n )\n }\n const schema = JSON.parse(\n readFileSync(`${manifestPath}/${workspace.schema}`, 'utf-8'),\n ) as ManifestSchemaType\n await client\n .withConfig({\n dataset: workspace.dataset,\n projectId: workspace.projectId,\n })\n .transaction()\n .createOrReplace({_type: SANITY_WORKSPACE_SCHEMA_ID, _id: id, workspace, schema})\n .commit()\n storedCount++\n spinner.text = `Stored ${storedCount} schemas so far...`\n if (verbose) spinner.succeed(`Schema stored for workspace '${workspace.name}'`)\n } catch (err) {\n error = err\n spinner.fail(\n `Error storing schema for workspace '${workspace.name}':\\n${chalk.red(`${err.message}`)}`,\n )\n if (schemaRequired) throw err\n } finally {\n if (verbose) {\n output.print(\n chalk.gray(`↳ schemaId: ${id}, projectId: ${projectId}, dataset: ${workspace.dataset}`),\n )\n }\n }\n }\n\n // If a workspace name is provided, only save the schema for that workspace\n if (workspaceName) {\n const workspaceToSave = manifest.workspaces.find(\n (workspace) => workspace.name === workspaceName,\n )\n if (!workspaceToSave) {\n spinner.fail(`Workspace ${workspaceName} not found in manifest`)\n throw new Error(`Workspace ${workspaceName} not found in manifest: projectID: ${projectId}`)\n }\n await saveSchema(workspaceToSave as ManifestWorkspaceFile)\n spinner.succeed(`Stored 1 schemas`)\n } else {\n await Promise.all(\n manifest.workspaces.map(async (workspace): Promise<void> => {\n await saveSchema(workspace)\n }),\n )\n spinner.succeed(`Stored ${storedCount}/${manifest.workspaces.length} schemas`)\n }\n\n if (error) throw error\n return undefined\n } catch (err) {\n // if this flag is set, throw the error and exit without deploying otherwise just log the error\n if (schemaRequired) throw err\n return err\n } finally {\n output.print(`${chalk.gray('↳ List stored schemas with:')} ${chalk.cyan('sanity schema list')}`)\n }\n}\n"],"names":["storeSchemasAction","args","context","flags","extOptions","path","Error","workspace","schemaRequired","workspaceName","idPrefix","verbose","output","workDir","apiClient","defaultOutputDir","resolve","join","outputDir","defaultStaticPath","staticPath","spinner","start","manifestPath","process","cwd","client","requireUser","requireProject","withConfig","apiVersion","projectId","config","manifest","JSON","parse","readFileSync","MANIFEST_FILENAME","error","fail","storedCount","saveSchema","id","SANITY_WORKSPACE_SCHEMA_ID","name","schema","dataset","transaction","createOrReplace","_type","_id","commit","text","succeed","err","chalk","red","message","print","gray","workspaceToSave","workspaces","find","Promise","all","map","length","cyan"],"mappings":";;;;;;AAsB8BA,eAAAA,mBAC5BC,MACAC,SAC4B;AAC5B,QAAMC,QAAQF,KAAKG;AACnB,MAAI,OAAOD,MAAME,QAAS,UAAiB,OAAA,IAAIC,MAAM,eAAe;AAChE,MAAA,OAAOH,MAAM,WAAW,KAAM,UAAiB,OAAA,IAAIG,MAAM,oBAAoB;AACjF,MAAI,OAAOH,MAAMI,aAAc,UAAiB,OAAA,IAAID,MAAM,oBAAoB;AAE9E,QAAME,iBAAiBL,MAAM,iBAAiB,GACxCM,gBAAgBN,MAAMI,WACtBG,WAAWP,MAAM,WAAW,GAC5BQ,UAAUR,MAAMQ,SAChB;AAAA,IAACC;AAAAA,IAAQC;AAAAA,IAASC;AAAAA,EAAaZ,IAAAA,SAE/Ba,mBAAmBC,KAAAA,QAAQC,KAAKJ,KAAAA,SAAS,MAAM,CAAC,GAEhDK,YAAYF,KAAAA,QAAQD,gBAAgB,GACpCI,oBAAoBF,KAAAA,KAAKC,WAAW,QAAQ,GAE5CE,aAAajB,MAAME,QAAQc,mBAE3BE,UAAUT,OAAOS,QAAQ,CAAA,CAAE,EAAEC,MAAM,iBAAiB;AAEtD,MAAA;AACIC,UAAA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U,KAAK;AAKZ,YAJAhB,QAAQgB,KACRjC,QAAQkB,KACN,uCAAuChC,UAAUqC,IAAI;AAAA,EAAOW,uBAAMC,IAAI,GAAGF,IAAIG,OAAO,EAAE,CAAC,EACzF,GACIjD,eAAsB8C,OAAAA;AAAAA,MAAAA,UAClB;AACJ3C,mBACFC,OAAO8C,MACLH,eAAAA,QAAMI,KAAK,oBAAejB,EAAE,gBAAgBX,SAAS,cAAcxB,UAAUuC,OAAO,EAAE,CACxF;AAAA,MAAA;AAAA,IAGN;AAGA,QAAIrC,eAAe;AACjB,YAAMmD,kBAAkB3B,SAAS4B,WAAWC,KACzCvD,CAAcA,cAAAA,UAAUqC,SAASnC,aACpC;AACA,UAAI,CAACmD;AACKrB,cAAAA,QAAAA,KAAK,aAAa9B,aAAa,wBAAwB,GACzD,IAAIH,MAAM,aAAaG,aAAa,sCAAsCsB,SAAS,EAAE;AAE7F,YAAMU,WAAWmB,eAAwC,GACzDvC,QAAQgC,QAAQ,kBAAkB;AAAA,IACpC;AACE,YAAMU,QAAQC,IACZ/B,SAAS4B,WAAWI,IAAI,OAAO1D,cAA6B;AAC1D,cAAMkC,WAAWlC,SAAS;AAAA,MAC3B,CAAA,CACH,GACAc,QAAQgC,QAAQ,UAAUb,WAAW,IAAIP,SAAS4B,WAAWK,MAAM,UAAU;AAG/E,QAAI5B,MAAaA,OAAAA;AACjB;AAAA,WACOgB,KAAK;AAEZ,QAAI9C,eAAsB8C,OAAAA;AACnBA,WAAAA;AAAAA,EAAAA,UACC;AACDI,WAAAA,MAAM,GAAGH,eAAAA,QAAMI,KAAK,kCAA6B,CAAC,IAAIJ,eAAAA,QAAMY,KAAK,oBAAoB,CAAC,EAAE;AAAA,EAAA;AAEnG;;"}
1
+ {"version":3,"file":"storeSchemasAction.js","sources":["../../src/_internal/cli/actions/schema/schemaListAction.ts","../../src/_internal/cli/actions/schema/storeSchemasAction.ts"],"sourcesContent":["import {type CliCommandArguments, type CliCommandContext, type CliOutputter} from '@sanity/cli'\nimport {type SanityDocument} from '@sanity/client'\nimport chalk from 'chalk'\nimport {size, sortBy, uniqBy} from 'lodash'\n\nimport {type ManifestWorkspaceFile} from '../../../manifest/manifestTypes'\nimport {getManifestPath, readManifest, throwIfProjectIdMismatch} from './storeSchemasAction'\n\nexport interface SchemaListFlags {\n json: boolean\n id: string\n path: string\n}\n\ntype PrintSchemaListArgs = {\n schemas: SanityDocument[]\n output: CliOutputter\n dataset: string\n projectId: string\n path: string\n}\n\nexport const SANITY_WORKSPACE_SCHEMA_TYPE = 'sanity.workspace.schema'\n\nconst printSchemaList = ({\n schemas,\n output,\n}: Omit<PrintSchemaListArgs, 'path' | 'dataset' | 'projectId'>) => {\n const ordered = sortBy(\n schemas.map(({_createdAt: createdAt, _id: id, workspace}) => {\n return [id, workspace.name, workspace.dataset, workspace.projectId, createdAt].map(String)\n }),\n ['createdAt'],\n )\n const headings = ['Id', 'Workspace', 'Dataset', 'ProjectId', 'CreatedAt']\n const rows = ordered.reverse()\n\n const maxWidths = rows.reduce(\n (max, row) => row.map((current, index) => Math.max(size(current), max[index])),\n headings.map((str) => size(str)),\n )\n\n const printRow = (row: string[]) => row.map((col, i) => `${col}`.padEnd(maxWidths[i])).join(' ')\n\n output.print(chalk.cyan(printRow(headings)))\n rows.forEach((row) => output.print(printRow(row)))\n}\n\nexport default async function fetchSchemaAction(\n args: CliCommandArguments<SchemaListFlags>,\n context: CliCommandContext,\n): Promise<void> {\n const flags = args.extOptions\n const {apiClient, output} = context\n const client = apiClient({\n requireUser: true,\n requireProject: true,\n }).withConfig({apiVersion: 'v2024-08-01'})\n\n const projectId = client.config().projectId\n\n if (!projectId) {\n output.error('Project ID must be defined.')\n return\n }\n\n const manifestPath = getManifestPath(context, flags.path)\n const manifest = readManifest(manifestPath, output)\n\n // Gather all schemas\n const results = await Promise.allSettled(\n uniqBy<ManifestWorkspaceFile>(manifest.workspaces, 'dataset').map(async (workspace) => {\n throwIfProjectIdMismatch(workspace, projectId)\n if (flags.id) {\n // Fetch a specific schema by id\n return await client\n .withConfig({\n dataset: workspace.dataset,\n projectId: workspace.projectId,\n })\n .getDocument(flags.id)\n }\n // Fetch all schemas\n return await client\n .withConfig({\n dataset: workspace.dataset,\n projectId: workspace.projectId,\n useCdn: false,\n })\n .fetch<SanityDocument[]>(`*[_type == $type]`, {\n type: SANITY_WORKSPACE_SCHEMA_TYPE,\n })\n }),\n )\n\n // Log errors and collect successful results\n const schemas = results\n .map((result, index) => {\n if (result.status === 'rejected') {\n const workspace = manifest.workspaces[index]\n output.error(\n chalk.red(\n `Failed to fetch schemas for workspace '${workspace.name}': ${result.reason.message}`,\n ),\n )\n return []\n }\n return result.value\n })\n .flat()\n\n if (schemas.length === 0) {\n output.error(`No schemas found`)\n return\n }\n\n if (flags.json) {\n output.print(`${JSON.stringify(schemas, null, 2)}`)\n } else {\n printSchemaList({schemas: schemas as SanityDocument[], output})\n }\n}\n","import {readFileSync} from 'node:fs'\nimport path, {join, resolve} from 'node:path'\n\nimport {type CliCommandArguments, type CliCommandContext, type CliOutputter} from '@sanity/cli'\nimport chalk from 'chalk'\nimport {type Ora} from 'ora'\n\nimport {type ManifestSchemaType, type ManifestWorkspaceFile} from '../../../manifest/manifestTypes'\nimport {MANIFEST_FILENAME} from '../manifest/extractManifestAction'\nimport {SANITY_WORKSPACE_SCHEMA_TYPE} from './schemaListAction'\n\nexport interface StoreManifestSchemasFlags {\n 'path'?: string\n 'workspace'?: string\n 'id-prefix'?: string\n 'schema-required'?: boolean\n 'verbose'?: boolean\n}\n\nexport const getManifestPath = (context: CliCommandContext, customPath?: string) => {\n const defaultOutputDir = resolve(join(context.workDir, 'dist'))\n\n const outputDir = resolve(defaultOutputDir)\n const defaultStaticPath = join(outputDir, 'static')\n\n const staticPath = customPath ?? defaultStaticPath\n const manifestPath = path.resolve(process.cwd(), staticPath)\n return manifestPath\n}\n\nexport const readManifest = (readPath: string, output?: CliOutputter, spinner?: Ora) => {\n try {\n return JSON.parse(readFileSync(`${readPath}/${MANIFEST_FILENAME}`, 'utf-8'))\n } catch (error) {\n const errorMessage = `Manifest not found at ${readPath}/${MANIFEST_FILENAME}`\n if (spinner) spinner.fail(errorMessage)\n if (output) output.error(errorMessage)\n throw error\n }\n}\n\n// At the moment schema store deos not support studios where workspaces have multiple projects\nexport const throwIfProjectIdMismatch = (\n workspace: ManifestWorkspaceFile,\n projectId: string,\n): void => {\n if (workspace.projectId !== projectId) {\n throw new Error(\n `↳ No permissions to store schema for workspace ${workspace.name} with projectId: ${workspace.projectId}`,\n )\n }\n}\n\nexport default async function storeSchemasAction(\n args: CliCommandArguments<StoreManifestSchemasFlags>,\n context: CliCommandContext,\n): Promise<Error | undefined> {\n const flags = args.extOptions\n\n const schemaRequired = flags['schema-required']\n const workspaceName = flags.workspace\n const idPrefix = flags['id-prefix']\n const verbose = flags.verbose\n\n if (typeof flags.path === 'boolean') throw new Error('Path is empty')\n if (typeof idPrefix === 'boolean') throw new Error('Id prefix is empty')\n if (typeof workspaceName === 'boolean') throw new Error('Workspace is empty')\n\n const {output, apiClient} = context\n\n const spinner = output.spinner({}).start('Storing schemas')\n\n const manifestPath = getManifestPath(context, flags.path)\n\n try {\n const client = apiClient({\n requireUser: true,\n requireProject: true,\n }).withConfig({apiVersion: 'v2024-08-01'})\n\n const projectId = client.config().projectId\n if (!projectId) throw new Error('Project ID is not defined')\n\n const manifest = readManifest(manifestPath, output, spinner)\n\n let storedCount = 0\n\n let error: Error | undefined\n\n const saveSchema = async (workspace: ManifestWorkspaceFile) => {\n const id = `${idPrefix ? `${idPrefix}.` : ''}${SANITY_WORKSPACE_SCHEMA_TYPE}.${workspace.name}`\n try {\n throwIfProjectIdMismatch(workspace, projectId)\n const schema = JSON.parse(\n readFileSync(`${manifestPath}/${workspace.schema}`, 'utf-8'),\n ) as ManifestSchemaType\n await client\n .withConfig({\n dataset: workspace.dataset,\n projectId: workspace.projectId,\n })\n .transaction()\n .createOrReplace({_type: SANITY_WORKSPACE_SCHEMA_TYPE, _id: id, workspace, schema})\n .commit()\n storedCount++\n spinner.text = `Stored ${storedCount} schemas so far...`\n if (verbose) spinner.succeed(`Schema stored for workspace '${workspace.name}'`)\n } catch (err) {\n error = err\n spinner.fail(\n `Error storing schema for workspace '${workspace.name}':\\n${chalk.red(`${err.message}`)}`,\n )\n if (schemaRequired) throw err\n } finally {\n if (verbose) {\n output.print(\n chalk.gray(`↳ schemaId: ${id}, projectId: ${projectId}, dataset: ${workspace.dataset}`),\n )\n }\n }\n }\n\n // If a workspace name is provided, only save the schema for that workspace\n if (workspaceName) {\n const workspaceToSave = manifest.workspaces.find(\n (workspace: ManifestWorkspaceFile) => workspace.name === workspaceName,\n )\n if (!workspaceToSave) {\n spinner.fail(`Workspace ${workspaceName} not found in manifest`)\n throw new Error(`Workspace ${workspaceName} not found in manifest: projectID: ${projectId}`)\n }\n await saveSchema(workspaceToSave as ManifestWorkspaceFile)\n spinner.succeed(`Stored 1 schemas`)\n } else {\n await Promise.all(\n manifest.workspaces.map(async (workspace: ManifestWorkspaceFile): Promise<void> => {\n await saveSchema(workspace)\n }),\n )\n spinner.succeed(`Stored ${storedCount}/${manifest.workspaces.length} schemas`)\n }\n\n if (error) throw error\n return undefined\n } catch (err) {\n // if this flag is set, throw the error and exit without deploying otherwise just log the error\n if (schemaRequired) throw err\n return err\n } finally {\n output.print(`${chalk.gray('↳ List stored schemas with:')} ${chalk.cyan('sanity schema list')}`)\n }\n}\n"],"names":["SANITY_WORKSPACE_SCHEMA_TYPE","printSchemaList","schemas","output","ordered","sortBy","map","_createdAt","createdAt","_id","id","workspace","name","dataset","projectId","String","headings","rows","reverse","maxWidths","reduce","max","row","current","index","Math","size","str","printRow","col","i","padEnd","join","print","chalk","cyan","forEach","fetchSchemaAction","args","context","flags","extOptions","apiClient","client","requireUser","requireProject","withConfig","apiVersion","config","error","manifestPath","getManifestPath","path","manifest","readManifest","Promise","allSettled","uniqBy","workspaces","throwIfProjectIdMismatch","getDocument","useCdn","fetch","type","result","status","red","reason","message","value","flat","length","json","JSON","stringify","customPath","defaultOutputDir","resolve","workDir","outputDir","defaultStaticPath","staticPath","process","cwd","readPath","spinner","parse","readFileSync","MANIFEST_FILENAME","errorMessage","fail","Error","storeSchemasAction","schemaRequired","workspaceName","idPrefix","verbose","start","storedCount","saveSchema","schema","transaction","createOrReplace","_type","commit","text","succeed","err","gray","workspaceToSave","find","all"],"mappings":";;;;;;AAsBO,MAAMA,+BAA+B,2BAEtCC,kBAAkBA,CAAC;AAAA,EACvBC;AAAAA,EACAC;AAC2D,MAAM;AACjE,QAAMC,UAAUC,gBAAAA,QACdH,QAAQI,IAAI,CAAC;AAAA,IAACC,YAAYC;AAAAA,IAAWC,KAAKC;AAAAA,IAAIC;AAAAA,EAAAA,MACrC,CAACD,IAAIC,UAAUC,MAAMD,UAAUE,SAASF,UAAUG,WAAWN,SAAS,EAAEF,IAAIS,MAAM,CAC1F,GACD,CAAC,WAAW,CACd,GACMC,WAAW,CAAC,MAAM,aAAa,WAAW,aAAa,WAAW,GAClEC,OAAOb,QAAQc,WAEfC,YAAYF,KAAKG,OACrB,CAACC,KAAKC,QAAQA,IAAIhB,IAAI,CAACiB,SAASC,UAAUC,KAAKJ,IAAIK,cAAAA,QAAKH,OAAO,GAAGF,IAAIG,KAAK,CAAC,CAAC,GAC7ER,SAASV,IAAKqB,CAAAA,QAAQD,cAAAA,QAAKC,GAAG,CAAC,CACjC,GAEMC,WAAYN,CAAkBA,QAAAA,IAAIhB,IAAI,CAACuB,KAAKC,MAAM,GAAGD,GAAG,GAAGE,OAAOZ,UAAUW,CAAC,CAAC,CAAC,EAAEE,KAAK,KAAK;AAEjG7B,SAAO8B,MAAMC,eAAMC,QAAAA,KAAKP,SAASZ,QAAQ,CAAC,CAAC,GAC3CC,KAAKmB,QAASd,SAAQnB,OAAO8B,MAAML,SAASN,GAAG,CAAC,CAAC;AACnD;AAE8Be,eAAAA,kBAC5BC,MACAC,SACe;AACTC,QAAAA,QAAQF,KAAKG,YACb;AAAA,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exports.SANITY_VERSION = SANITY_VERSION;
4
4
  //# sourceMappingURL=version.js.map
@@ -1,4 +1,4 @@
1
- const SANITY_VERSION = "3.77.2-server-side-schemas.21+15f4ca087f";
1
+ const SANITY_VERSION = "3.77.2-server-side-schemas.25+7bad107ad4";
2
2
  export {
3
3
  SANITY_VERSION
4
4
  };
@@ -1,4 +1,4 @@
1
- const SANITY_VERSION = "3.77.2-server-side-schemas.21+15f4ca087f";
1
+ const SANITY_VERSION = "3.77.2-server-side-schemas.25+7bad107ad4";
2
2
  export {
3
3
  SANITY_VERSION
4
4
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sanity",
3
- "version": "3.77.2-server-side-schemas.21+15f4ca087f",
3
+ "version": "3.77.2-server-side-schemas.25+7bad107ad4",
4
4
  "description": "Sanity is a real-time content infrastructure with a scalable, hosted backend featuring a Graph Oriented Query Language (GROQ), asset pipelines and fast edge caches",
5
5
  "keywords": [
6
6
  "sanity",
@@ -160,11 +160,11 @@
160
160
  "@rexxars/react-json-inspector": "^9.0.1",
161
161
  "@sanity/asset-utils": "^2.0.6",
162
162
  "@sanity/bifur-client": "^0.4.1",
163
- "@sanity/cli": "3.77.2-server-side-schemas.21+15f4ca087f",
163
+ "@sanity/cli": "3.77.2-server-side-schemas.25+7bad107ad4",
164
164
  "@sanity/client": "^6.28.1",
165
165
  "@sanity/color": "^3.0.0",
166
166
  "@sanity/comlink": "^3.0.1",
167
- "@sanity/diff": "3.77.2-server-side-schemas.21+15f4ca087f",
167
+ "@sanity/diff": "3.77.2-server-side-schemas.25+7bad107ad4",
168
168
  "@sanity/diff-match-patch": "^3.1.1",
169
169
  "@sanity/diff-patch": "^5.0.0",
170
170
  "@sanity/eventsource": "^5.0.0",
@@ -174,15 +174,15 @@
174
174
  "@sanity/import": "^3.37.9",
175
175
  "@sanity/insert-menu": "^1.1.3",
176
176
  "@sanity/logos": "^2.1.13",
177
- "@sanity/migrate": "3.77.2-server-side-schemas.21+15f4ca087f",
178
- "@sanity/mutator": "3.77.2-server-side-schemas.21+15f4ca087f",
177
+ "@sanity/migrate": "3.77.2-server-side-schemas.25+7bad107ad4",
178
+ "@sanity/mutator": "3.77.2-server-side-schemas.25+7bad107ad4",
179
179
  "@sanity/presentation-comlink": "^1.0.8",
180
180
  "@sanity/preview-url-secret": "^2.1.4",
181
- "@sanity/schema": "3.77.2-server-side-schemas.21+15f4ca087f",
181
+ "@sanity/schema": "3.77.2-server-side-schemas.25+7bad107ad4",
182
182
  "@sanity/telemetry": "^0.7.7",
183
- "@sanity/types": "3.77.2-server-side-schemas.21+15f4ca087f",
183
+ "@sanity/types": "3.77.2-server-side-schemas.25+7bad107ad4",
184
184
  "@sanity/ui": "^2.14.3",
185
- "@sanity/util": "3.77.2-server-side-schemas.21+15f4ca087f",
185
+ "@sanity/util": "3.77.2-server-side-schemas.25+7bad107ad4",
186
186
  "@sanity/uuid": "^3.0.2",
187
187
  "@sentry/react": "^8.33.0",
188
188
  "@tanstack/react-table": "^8.16.0",
@@ -280,7 +280,7 @@
280
280
  "@repo/dev-aliases": "3.77.1",
281
281
  "@repo/package.config": "3.77.1",
282
282
  "@repo/test-config": "3.77.1",
283
- "@sanity/codegen": "3.77.2-server-side-schemas.21+15f4ca087f",
283
+ "@sanity/codegen": "3.77.2-server-side-schemas.25+7bad107ad4",
284
284
  "@sanity/generate-help-url": "^3.0.0",
285
285
  "@sanity/pkg-utils": "6.13.4",
286
286
  "@sanity/tsdoc": "1.0.169",
@@ -325,5 +325,5 @@
325
325
  "engines": {
326
326
  "node": ">=18"
327
327
  },
328
- "gitHead": "15f4ca087f91a9b547e7d8e79d0abe3020273898"
328
+ "gitHead": "7bad107ad4a5af3e753d27c254b6f621b6c877cb"
329
329
  }
@@ -1,7 +1,13 @@
1
1
  import {type CliCommandArguments, type CliCommandContext} from '@sanity/cli'
2
+ import chalk from 'chalk'
3
+
4
+ import {type ManifestWorkspaceFile} from '../../../manifest/manifestTypes'
5
+ import {getManifestPath, readManifest, throwIfProjectIdMismatch} from './storeSchemasAction'
2
6
 
3
7
  export interface DeleteSchemaFlags {
4
8
  ids: string
9
+ path: string
10
+ dataset: string
5
11
  }
6
12
 
7
13
  export default async function deleteSchemaAction(
@@ -9,12 +15,12 @@ export default async function deleteSchemaAction(
9
15
  context: CliCommandContext,
10
16
  ): Promise<void> {
11
17
  const flags = args.extOptions
18
+ if (typeof flags.dataset === 'boolean') throw new Error('Dataset is empty')
19
+ if (typeof flags.ids === 'boolean') throw new Error('Ids are empty')
20
+ if (typeof flags.path === 'boolean') throw new Error('Path is empty')
21
+
12
22
  const {apiClient, output} = context
13
23
 
14
- if (!flags.ids) {
15
- output.error('No schema ids provided')
16
- return
17
- }
18
24
  //split ids by comma
19
25
  const schemaIds = flags.ids.split(',')
20
26
 
@@ -24,26 +30,61 @@ export default async function deleteSchemaAction(
24
30
  }).withConfig({apiVersion: 'v2024-08-01'})
25
31
 
26
32
  const projectId = client.config().projectId
27
- const dataset = client.config().dataset
28
33
 
29
- if (!projectId || !dataset) {
30
- output.error('Project ID and Dataset must be defined.')
34
+ if (!projectId) {
35
+ output.error('Project ID must be defined.')
31
36
  return
32
37
  }
33
38
 
34
- schemaIds.forEach(async (schemaId) => {
35
- const deletedSchema = await client
36
- .withConfig({
37
- dataset: dataset,
38
- projectId: projectId,
39
+ const manifestPath = getManifestPath(context, flags.path)
40
+ const manifest = readManifest(manifestPath, output)
41
+
42
+ const results = await Promise.allSettled(
43
+ manifest.workspaces.flatMap((workspace: ManifestWorkspaceFile) => {
44
+ if (flags.dataset && workspace.dataset !== flags.dataset) {
45
+ return []
46
+ }
47
+ return schemaIds.map(async (schemaId) => {
48
+ const idWorkspace = schemaId.split('.').at(-1)
49
+ if (idWorkspace !== workspace.name && !flags.dataset) {
50
+ return false
51
+ }
52
+ try {
53
+ throwIfProjectIdMismatch(workspace, projectId)
54
+ const deletedSchema = await client
55
+ .withConfig({
56
+ dataset: flags.dataset || workspace.dataset,
57
+ projectId: workspace.projectId,
58
+ })
59
+ .delete(schemaId.trim())
60
+
61
+ if (!deletedSchema.results.length) {
62
+ return false
63
+ }
64
+
65
+ output.success(`Schema ${schemaId} deleted from workspace: ${workspace.name}`)
66
+ return true
67
+ } catch (err) {
68
+ output.error(
69
+ `Failed to delete schema ${schemaId} from workspace ${workspace.name}:\n ${err.message}`,
70
+ )
71
+ throw err
72
+ }
39
73
  })
40
- .delete(schemaId.trim())
74
+ }),
75
+ )
41
76
 
42
- if (!deletedSchema.results.length) {
43
- output.error(`No schema found with id: ${schemaId}`)
44
- return
45
- }
77
+ // Log errors and collect results
78
+ const deletedCount = results
79
+ .map((result, index) => {
80
+ if (result.status === 'rejected') {
81
+ const schemaId = schemaIds[index]
82
+ output.error(chalk.red(`Failed to delete schema '${schemaId}':\n${result.reason.message}`))
83
+ return false
84
+ }
85
+ return result.value
86
+ })
87
+ .filter(Boolean).length
46
88
 
47
- output.success(`Schema ${schemaId} deleted`)
48
- })
89
+ output.print(`Successfully deleted ${deletedCount} schemas`)
49
90
  }