Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/@repo/tsconfig/base.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@

// Settings
"preserveConstEnums": true,
"useUnknownInCatchVariables": false,
"useUnknownInCatchVariables": true,
"isolatedModules": true,
"forceConsistentCasingInFileNames": true,
"allowJs": true,
Expand Down
2 changes: 1 addition & 1 deletion packages/@sanity/cli/src/__tests__/exports.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ async function downloadAndExtractTarball(version: string, destDir: string) {
return
}
} catch (error) {
if (error.code !== 'ENOENT') {
if (!(error instanceof Error) || !('code' in error) || error.code !== 'ENOENT') {
throw error
}
}
Expand Down
2 changes: 1 addition & 1 deletion packages/@sanity/cli/src/actions/build/buildApp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ export async function buildApp(options: BuildOptions): Promise<void> {
trace.complete()
} catch (error) {
spin.fail()
trace.error(error)
trace.error(error instanceof Error ? error : new Error(String(error)))
const message = error instanceof Error ? error.message : String(error)
buildDebug(`Failed to build Sanity application`, {error})
output.error(`Failed to build Sanity application: ${message}`, {exit: 1})
Expand Down
2 changes: 1 addition & 1 deletion packages/@sanity/cli/src/actions/build/buildStudio.ts
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,7 @@ export async function buildStudio(options: BuildOptions): Promise<void> {
}
} catch (error) {
spin.fail()
trace.error(error)
trace.error(error instanceof Error ? error : new Error(String(error)))
const message = error instanceof Error ? error.message : String(error)
buildDebug(`Failed to build Sanity Studio`, {error})
output.error(`Failed to build Sanity Studio: ${message}`, {exit: 1})
Expand Down
2 changes: 1 addition & 1 deletion packages/@sanity/cli/src/actions/build/renderDocument.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ export async function renderDocument(options: RenderDocumentOptions): Promise<st

throw new Error('Unknown message type')
} catch (err) {
buildDebug('Worker errored: %s', err.message)
buildDebug('Worker errored: %s', err instanceof Error ? err.message : String(err))
throw err
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,11 @@ export async function tryLoadDocumentComponent(studioRootPath: string) {
}
} catch (err) {
// Allow "not found" errors
if (err.code !== 'ERR_MODULE_NOT_FOUND') {
buildDebug('Failed to load document component: %s', err.message)
if (!(err instanceof Error) || !('code' in err) || err.code !== 'ERR_MODULE_NOT_FOUND') {
buildDebug(
'Failed to load document component: %s',
err instanceof Error ? err.message : String(err),
)
throw err
}

Expand Down
29 changes: 14 additions & 15 deletions packages/@sanity/cli/src/actions/deploy/checkDir.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,25 +15,24 @@ export async function checkDir(sourceDir: string): Promise<void> {
throw new Error(`Directory ${sourceDir} is not a directory`)
}
} catch (err) {
const error = err.code === 'ENOENT' ? new Error(`Directory "${sourceDir}" does not exist`) : err

throw error
if (err instanceof Error && 'code' in err && err.code === 'ENOENT') {
throw new Error(`Directory "${sourceDir}" does not exist`)
}
throw err
}

try {
await stat(join(sourceDir, 'index.html'))
} catch (err) {
const error =
err.code === 'ENOENT'
? new Error(
[
`"${sourceDir}/index.html" does not exist -`,
'[SOURCE_DIR] must be a directory containing',
'a Sanity studio built using "sanity build"',
].join(' '),
)
: err

throw error
if (err instanceof Error && 'code' in err && err.code === 'ENOENT') {
throw new Error(
[
`"${sourceDir}/index.html" does not exist -`,
'[SOURCE_DIR] must be a directory containing',
'a Sanity studio built using "sanity build"',
].join(' '),
)
}
throw err
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import {CLIError} from '@oclif/core/errors'
import {input} from '@sanity/cli-core/ux'
import {isHttpError} from '@sanity/client'

import {createUserApplication, type UserApplication} from '../../services/userApplications.js'
import {deployDebug} from './deployDebug.js'
Expand Down Expand Up @@ -60,8 +61,16 @@ export async function createStudioUserApplication(options: CreateStudioUserAppli
return true
} catch (e) {
// if the name is taken, it should return a 409 so we relay to the user
if ([402, 409].includes(e?.statusCode)) {
return e?.response?.body?.message || 'Bad request' // just in case
if (isHttpError(e) && [402, 409].includes(e.statusCode)) {
const body = e.response.body
const message =
typeof body === 'object' &&
body !== null &&
'message' in body &&
typeof body.message === 'string'
? body.message
: 'Bad request'
return message
}

deployDebug('Error creating user application', e)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {input, spinner} from '@sanity/cli-core/ux'
import {isHttpError} from '@sanity/client'
import {customAlphabet} from 'nanoid'

import {createUserApplication, type UserApplication} from '../../services/userApplications.js'
Expand Down Expand Up @@ -51,7 +52,7 @@ const tryCreateApp = async (title: string, organizationId: string) => {
return response
} catch (e) {
// if the name is taken, generate a new one and try again
if ([402, 409].includes(e?.statusCode)) {
if (isHttpError(e) && [402, 409].includes(e.statusCode)) {
deployDebug('App host taken, retrying with new host')
return tryCreateApp(title, organizationId)
}
Expand Down
2 changes: 1 addition & 1 deletion packages/@sanity/cli/src/actions/deploy/deployApp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ ${styleText(
} catch (error) {
spin.clear()
// Don't throw generic error if user cancels
if (error.name === 'ExitPromptError') {
if (error instanceof Error && error.name === 'ExitPromptError') {
output.error('Deployment cancelled by user', {exit: 1})
return
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ export async function deployStudioSchemasAndManifests(
)
return result.studioManifest
} catch (err) {
trace.error(err)
trace.error(err instanceof Error ? err : new Error(String(err)))
throw err
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import {type CliConfig, type Output} from '@sanity/cli-core'
import {select, Separator, spinner} from '@sanity/cli-core/ux'
import {isHttpError} from '@sanity/client'

import {
getUserApplication,
Expand Down Expand Up @@ -104,7 +105,7 @@ export async function findUserApplicationForApp(
return userApplications.find((app) => app.appHost === selected)!
} catch (error) {
// User can't access applications for the org
if (error?.statusCode === 403) {
if (isHttpError(error) && error.statusCode === 403) {
spin.clear()
deployDebug(
'User does not have permission to get applications for the org, or the org ID is malformed/doesn’t exist',
Expand All @@ -126,7 +127,7 @@ export async function findUserApplicationForApp(
// We've failed for some other reason
spin.clear()
deployDebug('Error finding user application for app', error)
output.error(error)
output.error(error instanceof Error ? error : String(error))
return null
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,15 @@

import {type Output} from '@sanity/cli-core'
import {select, Separator, spinner, type SpinnerInstance} from '@sanity/cli-core/ux'
import {isHttpError} from '@sanity/client'

import {
createUserApplication,
getUserApplication,
getUserApplications,
type UserApplication,
} from '../../services/userApplications.js'
import {getErrorMessage} from '../../util/getErrorMessage.js'
import {deployDebug} from './deployDebug.js'
import {normalizeUrl, validateUrl} from './urlUtils.js'

Expand Down Expand Up @@ -123,7 +125,7 @@ async function findUserApplication(
} catch (error) {
spin.fail()
deployDebug('Error finding user application', error)
output.error(`Error finding user application: ${error?.message}`, {exit: 1})
output.error(`Error finding user application: ${getErrorMessage(error)}`, {exit: 1})
}
}

Expand Down Expand Up @@ -182,24 +184,28 @@ async function findUserApplication(
} catch (e) {
spin.fail()
// if the name is taken, it should return a 409 so we relay to the user
if ([402, 409].includes(e?.statusCode)) {
output.error(e?.response?.body?.message || 'Bad request', {exit: 1})
if (isHttpError(e) && [402, 409].includes(e.statusCode)) {
const body = e.response.body
const message =
typeof body === 'object' &&
body !== null &&
'message' in body &&
typeof body.message === 'string'
? body.message
: 'Bad request'
output.error(message, {exit: 1})
return null
}
// otherwise, it's a fatal error
deployDebug('Error creating user application from config', e)
output.error(
`Error creating user application from config: ${e instanceof Error ? e.message : e}`,
{exit: 1},
)
output.error(`Error creating user application from config: ${getErrorMessage(e)}`, {
exit: 1,
})
}
} catch (error) {
spin.fail()
deployDebug('Error finding user application', error)
output.error(
`Error finding user application: ${error instanceof Error ? error.message : error.toString()}`,
{exit: 1},
)
output.error(`Error finding user application: ${getErrorMessage(error)}`, {exit: 1})
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ export async function startAppDevServer(
return {close}
} catch (err) {
devDebug('Error starting app dev server', err)
if (!(err instanceof Error)) throw err
throw gracefulServerDeath('dev', config.httpHost, config.httpPort, err)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,7 @@ export async function startStudioDevServer(
return {close}
} catch (err) {
devDebug('Error starting studio dev server', err)
if (!(err instanceof Error)) throw err
throw gracefulServerDeath('dev', config.httpHost, config.httpPort, err)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ export async function bootstrapLocalTemplate(
try {
await fs.writeFile(filePath, content, {flag: 'wx'})
} catch (err) {
if (err.code === 'EEXIST') {
if (err instanceof Error && 'code' in err && err.code === 'EEXIST') {
output.warn(`\n${styleText('yellow', '⚠')} File "${filePath}" already exists, skipping`)
} else {
throw err
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export async function createOrAppendEnvVars({
outputPath,
})
} catch (err) {
output.error(err)
output.error(err instanceof Error ? err : String(err))
throw new CLIError('An error occurred while creating .env', {exit: 1})
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {subdebug} from '@sanity/cli-core'
import {isHttpError} from '@sanity/client'

import {getOrganizationGrants} from '../../services/organizations.js'

Expand All @@ -18,12 +19,16 @@ export async function hasProjectAttachGrant(orgId: string) {
} catch (err) {
// If we get a 401, it means we don't have access to this organization
// probably because of implicit membership
if ('statusCode' in err && err.statusCode === 401) {
if (isHttpError(err) && err.statusCode === 401) {
debug('No access to organization %s (401)', orgId)
return false
}
// For other errors, log them but still return false
debug('Error checking grants for organization %s: %s', orgId, err.message)
debug(
'Error checking grants for organization %s: %s',
orgId,
err instanceof Error ? err.message : err,
)
return false
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export async function previewAction(options: PreviewActionOptions) {
const server = await startPreviewServer(config)
return server
} catch (err) {
if (!(err instanceof Error)) throw err
throw gracefulServerDeath('preview', config.httpHost, config.httpPort, err)
}
}
2 changes: 1 addition & 1 deletion packages/@sanity/cli/src/actions/schema/extractSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ export async function extractSchema(options: ExtractSchemaActionOptions): Promis

trace.complete()
} catch (err) {
trace.error(err)
trace.error(err instanceof Error ? err : new Error(String(err)))
schemasExtractDebug('Failed to extract schema', err)
spin.fail(
enforceRequiredFields
Expand Down
10 changes: 4 additions & 6 deletions packages/@sanity/cli/src/commands/dev.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,12 +60,10 @@ export class DevCommand extends SanityCommand<typeof DevCommand> {
return result
} catch (error) {
devDebug(`Failed to start dev server`, error)
this.output.error(
styleText(['red', 'bgBlack'], `Failed to start dev server: ${error.message}`),
{
exit: 1,
},
)
const message = error instanceof Error ? error.message : String(error)
this.output.error(styleText(['red', 'bgBlack'], `Failed to start dev server: ${message}`), {
exit: 1,
})
}
}
}
3 changes: 2 additions & 1 deletion packages/@sanity/cli/src/commands/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -911,7 +911,8 @@ export class InitCommand extends SanityCommand<typeof InitCommand> {
userAction: 'select',
}
}
this.error(`Failed to communicate with the Sanity API:\n${err.message}`, {exit: 1})
const message = err instanceof Error ? err.message : String(err)
this.error(`Failed to communicate with the Sanity API:\n${message}`, {exit: 1})
}

if (projects.length === 0 && this.isUnattended()) {
Expand Down
7 changes: 4 additions & 3 deletions packages/@sanity/cli/src/commands/undeploy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,21 +104,22 @@ Are you ${styleText('red', 'sure')} you want to undeploy?`
}
} catch (error) {
spin.fail()
if (error.message === NO_APP_ID) {
const message = error instanceof Error ? error.message : String(error)
if (message === NO_APP_ID) {
this.log('No application ID provided.')
this.log('Please set id in `deployment.appId` in sanity.cli.js or sanity.cli.ts.')
this.log('Nothing to undeploy.')
return
}

if (error.message === NO_APP_ID_OR_STUDIO_HOST) {
if (message === NO_APP_ID_OR_STUDIO_HOST) {
this.log('No application ID or studio host provided.')
this.log('Please set id in `deployment.appId` in sanity.cli.js or sanity.cli.ts.')
this.log('Nothing to undeploy.')
return
}

this.error(error)
this.error(error instanceof Error ? error : String(error))
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -323,7 +323,7 @@ export function sanitySchemaExtractionPlugin(options: SchemaExtractionPluginOpti
schemaTypesCount: schema.filter((type) => type.type === 'type').length,
})
} catch (err) {
trace?.error(err)
trace?.error(err instanceof Error ? err : new Error(String(err)))
throw err
} finally {
trace?.complete()
Expand Down
Loading
Loading