Skip to content

Commit

Permalink
refactor: switch ternary to isCoreApp
Browse files Browse the repository at this point in the history
  • Loading branch information
cngonzalez committed Feb 4, 2025
1 parent c017d47 commit 2014f8d
Show file tree
Hide file tree
Showing 18 changed files with 79 additions and 88 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import {createCliConfig} from './createCliConfig'
import {createCoreAppCliConfig} from './createCoreAppCliConfig'
import {createPackageManifest} from './createPackageManifest'
import {createStudioConfig, type GenerateConfigOptions} from './createStudioConfig'
import {determineStudioTemplate} from './determineStudioTemplate'
import {determineCoreAppTemplate} from './determineCoreAppTemplate'
import {type ProjectTemplate} from './initProject'
import templates from './templates'
import {updateInitialTemplateMetadata} from './updateInitialTemplateMetadata'
Expand All @@ -40,7 +40,7 @@ export async function bootstrapLocalTemplate(
const {outputPath, templateName, useTypeScript, packageName, variables} = opts
const sourceDir = path.join(templatesDir, templateName)
const sharedDir = path.join(templatesDir, 'shared')
const isStudioTemplate = determineStudioTemplate(templateName)
const isCoreAppTemplate = determineCoreAppTemplate(templateName)

// Check that we have a template info file (dependencies, plugins etc)
const template = templates[templateName]
Expand Down Expand Up @@ -83,16 +83,16 @@ export async function bootstrapLocalTemplate(
// Resolve latest versions of Sanity-dependencies
spinner = output.spinner('Resolving latest module versions').start()
const dependencyVersions = await resolveLatestVersions({
...(isStudioTemplate ? studioDependencies.dependencies : {}),
...(isStudioTemplate ? studioDependencies.devDependencies : {}),
...(isCoreAppTemplate ? {} : studioDependencies.dependencies),
...(isCoreAppTemplate ? {} : studioDependencies.devDependencies),
...(template.dependencies || {}),
...(template.devDependencies || {}),
})
spinner.succeed()

// Use the resolved version for the given dependency
const dependencies = Object.keys({
...(isStudioTemplate ? studioDependencies.dependencies : {}),
...(isCoreAppTemplate ? {} : studioDependencies.dependencies),
...template.dependencies,
}).reduce(
(deps, dependency) => {
Expand All @@ -103,7 +103,7 @@ export async function bootstrapLocalTemplate(
)

const devDependencies = Object.keys({
...(isStudioTemplate ? studioDependencies.devDependencies : {}),
...(isCoreAppTemplate ? {} : studioDependencies.devDependencies),
...template.devDependencies,
}).reduce(
(deps, dependency) => {
Expand All @@ -128,22 +128,22 @@ export async function bootstrapLocalTemplate(
})

// ...and a CLI config (`sanity.cli.[ts|js]`)
const cliConfig = isStudioTemplate
? createCliConfig({
const cliConfig = isCoreAppTemplate
? createCoreAppCliConfig({appLocation: template.appLocation!})
: createCliConfig({
projectId: variables.projectId,
dataset: variables.dataset,
autoUpdates: variables.autoUpdates,
})
: createCoreAppCliConfig({appLocation: template.appLocation!})

// Write non-template files to disc
const codeExt = useTypeScript ? 'ts' : 'js'
await Promise.all(
[
...[
isStudioTemplate
? writeFileIfNotExists(`sanity.config.${codeExt}`, studioConfig)
: Promise.resolve(null),
isCoreAppTemplate
? Promise.resolve(null)
: writeFileIfNotExists(`sanity.config.${codeExt}`, studioConfig),
],
writeFileIfNotExists(`sanity.cli.${codeExt}`, cliConfig),
writeFileIfNotExists('package.json', packageManifest),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const nonStudioTemplates = ['core-app']
const coreAppTemplates = ['core-app']

/**
* Determine if a given template is a studio template.
Expand All @@ -8,6 +8,6 @@ const nonStudioTemplates = ['core-app']
* @param templateName - Name of the template
* @returns boolean indicating if the template is a studio template
*/
export function determineStudioTemplate(templateName: string): boolean {
return !nonStudioTemplates.includes(templateName)
export function determineCoreAppTemplate(templateName: string): boolean {
return coreAppTemplates.includes(templateName)
}
11 changes: 5 additions & 6 deletions packages/@sanity/cli/src/actions/init-project/initProject.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ import {createProject} from '../project/createProject'
import {bootstrapLocalTemplate} from './bootstrapLocalTemplate'
import {bootstrapRemoteTemplate} from './bootstrapRemoteTemplate'
import {type GenerateConfigOptions} from './createStudioConfig'
import {determineStudioTemplate} from './determineStudioTemplate'
import {determineCoreAppTemplate} from './determineCoreAppTemplate'
import {absolutify, validateEmptyPath} from './fsUtils'
import {tryGitInit} from './git'
import {promptForDatasetName} from './promptForDatasetName'
Expand Down Expand Up @@ -274,7 +274,7 @@ export default async function initSanity(

const flags = await prepareFlags()
// skip project / dataset prompting
const isStudioTemplate = cliFlags.template ? determineStudioTemplate(cliFlags.template) : true // Default to true
const isCoreAppTemplate = cliFlags.template ? determineCoreAppTemplate(cliFlags.template) : false // Default to false

// We're authenticated, now lets select or create a project
const {projectId, displayName, isFirstProject, datasetName, schemaUrl} = await getProjectDetails()
Expand Down Expand Up @@ -661,13 +661,13 @@ export default async function initSanity(
if (isCurrentDir) {
print(`\n${chalk.green('Success!')} Now, use this command to continue:\n`)
print(
`${chalk.cyan(devCommand)} - to run ${isStudioTemplate ? 'Sanity Studio' : 'your Sanity application'}\n`,
`${chalk.cyan(devCommand)} - to run ${isCoreAppTemplate ? 'your Sanity application' : 'Sanity Studio'}\n`,
)
} else {
print(`\n${chalk.green('Success!')} Now, use these commands to continue:\n`)
print(`First: ${chalk.cyan(`cd ${outputPath}`)} - to enter project’s directory`)
print(
`Then: ${chalk.cyan(devCommand)} -to run ${isStudioTemplate ? 'Sanity Studio' : 'your Sanity application'}\n`,
`Then: ${chalk.cyan(devCommand)} -to run ${isCoreAppTemplate ? 'your Sanity application' : 'Sanity Studio'}\n`,
)
}

Expand Down Expand Up @@ -729,8 +729,7 @@ export default async function initSanity(
return data
}

// For non-studio templates, return empty strings but maintain the structure
if (!isStudioTemplate) {
if (isCoreAppTemplate) {
return {
projectId: '',
displayName: '',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,11 @@ const coreAppTemplate: ProjectTemplate = {
* eslint.config generation will be a fast follow
*/
'@sanity/eslint-config-studio': '^5.0.1',
'sanity': '^3',
'@vitejs/plugin-react': '^4.3.4',
'@types/react': '^18.0.25',
'eslint': '^9.9.0',
'prettier': '^3.0.2',
'sanity': '^3',
'typescript': '^5.1.6',
'vite': '^6',
},
appLocation: './src/App.tsx',
}
Expand Down
4 changes: 2 additions & 2 deletions packages/@sanity/cli/test/init.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@ import path from 'node:path'

import {describe, expect} from 'vitest'

import {determineStudioTemplate} from '../src/actions/init-project/determineStudioTemplate'
import {determineCoreAppTemplate} from '../src/actions/init-project/determineCoreAppTemplate'
import templates from '../src/actions/init-project/templates'
import {describeCliTest, testConcurrent} from './shared/describe'
import {baseTestPath, cliProjectId, getTestRunArgs, runSanityCmdCommand} from './shared/environment'

describeCliTest('CLI: `sanity init v3`', () => {
// filter out non-studio apps for now, until we add things they can auto-update
describe.each(Object.keys(templates).filter(determineStudioTemplate))(
describe.each(Object.keys(templates).filter((template) => !determineCoreAppTemplate(template)))(
'for template %s',
(template) => {
testConcurrent('adds autoUpdates: true to cli config', async () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ export default async function buildSanityStudio(
const unattendedMode = Boolean(flags.yes || flags.y)
const defaultOutputDir = path.resolve(path.join(workDir, 'dist'))
const outputDir = path.resolve(args.argsWithoutOptions[0] || defaultOutputDir)
const isCoreApp = cliConfig && '__experimental_coreAppConfiguration' in cliConfig

await checkStudioDependencyVersions(workDir)

Expand All @@ -57,7 +58,6 @@ export default async function buildSanityStudio(
}

const autoUpdatesEnabled = shouldAutoUpdate({flags, cliConfig})
const isStudioApp = !(cliConfig && '__experimental_coreAppConfiguration' in cliConfig)

// Get the version without any tags if any
const coercedSanityVersion = semver.coerce(installedSanityVersion)?.version
Expand Down Expand Up @@ -147,7 +147,7 @@ export default async function buildSanityStudio(
spin.succeed()
}

spin = output.spinner(`Build Sanity ${isStudioApp ? 'Studio' : 'application'}`).start()
spin = output.spinner(`Build Sanity ${isCoreApp ? 'application' : 'Studio'}`).start()

const trace = telemetry.trace(BuildTrace)
trace.start()
Expand Down Expand Up @@ -180,7 +180,7 @@ export default async function buildSanityStudio(
cliConfig && '__experimental_coreAppConfiguration' in cliConfig
? cliConfig.__experimental_coreAppConfiguration?.appLocation
: undefined,
isStudioApp,
isCoreApp,
})

trace.log({
Expand All @@ -190,7 +190,7 @@ export default async function buildSanityStudio(
})
const buildDuration = timer.end('bundleStudio')

spin.text = `Build Sanity ${isStudioApp ? 'Studio' : 'application'} (${buildDuration.toFixed()}ms)`
spin.text = `Build Sanity ${isCoreApp ? 'application' : 'Studio'} (${buildDuration.toFixed()}ms)`
spin.succeed()

trace.complete()
Expand Down
8 changes: 3 additions & 5 deletions packages/sanity/src/_internal/cli/actions/dev/devAction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,9 @@ export default async function startSanityDevServer(
timers.end('checkStudioDependencyVersions')

// If the check resulted in a dependency install, the CLI command will be re-run,
// thus we want to exit early (only for studios)
if (!(cliConfig && '__experimental_coreAppConfiguration' in cliConfig)) {
if ((await checkRequiredDependencies(context)).didInstall) {
return
}
// thus we want to exit early
if ((await checkRequiredDependencies(context)).didInstall) {
return
}

// Try to load CLI configuration from sanity.cli.(js|ts)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,11 @@ const startCommand: CliCommandDefinition = {
const {output, chalk, prompt} = context
const previewAction = await getPreviewAction()
const {cliConfig} = context
const isStudioApp = !(cliConfig && '__experimental_coreAppConfiguration' in cliConfig)
const isCoreApp = cliConfig && '__experimental_coreAppConfiguration' in cliConfig

const warn = (msg: string) => output.warn(chalk.yellow.bgBlack(msg))
const error = (msg: string) => output.warn(chalk.red.bgBlack(msg))
if (isStudioApp) {
if (!isCoreApp) {
warn('╭───────────────────────────────────────────────────────────╮')
warn('│ │')
warn("│ You're running Sanity Studio v3. In this version the │")
Expand Down
8 changes: 4 additions & 4 deletions packages/sanity/src/_internal/cli/server/buildStaticFiles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ export interface StaticBuildOptions {
vite?: UserViteConfig
reactCompiler: ReactCompilerConfig | undefined
appLocation?: string
isStudioApp?: boolean
isCoreApp?: boolean
}

export async function buildStaticFiles(
Expand All @@ -51,7 +51,7 @@ export async function buildStaticFiles(
importMap,
reactCompiler,
appLocation,
isStudioApp = true,
isCoreApp,
} = options

debug('Writing Sanity runtime files')
Expand All @@ -61,7 +61,7 @@ export async function buildStaticFiles(
watch: false,
basePath,
appLocation,
isStudioApp,
isCoreApp,
})

debug('Resolving vite config')
Expand All @@ -75,7 +75,7 @@ export async function buildStaticFiles(
mode,
importMap,
reactCompiler,
isStudioApp,
isCoreApp,
})

// Extend Vite configuration with user-provided config
Expand Down
10 changes: 5 additions & 5 deletions packages/sanity/src/_internal/cli/server/devServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export interface DevServerOptions {
reactCompiler: ReactCompilerConfig | undefined
vite?: UserViteConfig
appLocation?: string
isStudioApp?: boolean
isCoreApp?: boolean
}

export interface DevServer {
Expand All @@ -35,12 +35,12 @@ export async function startDevServer(options: DevServerOptions): Promise<DevServ
vite: extendViteConfig,
reactCompiler,
appLocation,
isStudioApp = true,
isCoreApp,
} = options

const startTime = Date.now()
debug('Writing Sanity runtime files')
await writeSanityRuntime({cwd, reactStrictMode, watch: true, basePath, appLocation, isStudioApp})
await writeSanityRuntime({cwd, reactStrictMode, watch: true, basePath, appLocation, isCoreApp})

debug('Resolving vite config')
const mode = 'development'
Expand All @@ -51,7 +51,7 @@ export async function startDevServer(options: DevServerOptions): Promise<DevServ
server: {port: httpPort, host: httpHost},
cwd,
reactCompiler,
isStudioApp,
isCoreApp,
})

// Extend Vite configuration with user-provided config
Expand All @@ -73,7 +73,7 @@ export async function startDevServer(options: DevServerOptions): Promise<DevServ

const startupDuration = Date.now() - startTime
const url = `http://${httpHost || 'localhost'}:${httpPort || '3333'}${basePath}`
const appType = isStudioApp ? 'Sanity Studio' : 'Application'
const appType = isCoreApp ? 'Sanity application' : 'Sanity Studio'
info(
`${appType} ` +
`using ${chalk.cyan(`vite@${require('vite/package.json').version}`)} ` +
Expand Down
12 changes: 3 additions & 9 deletions packages/sanity/src/_internal/cli/server/getEntryModule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,17 +42,11 @@ export function getEntryModule(options: {
relativeConfigLocation: string | null
basePath?: string
appLocation?: string
isStudioApp?: boolean
isCoreApp?: boolean
}): string {
const {
reactStrictMode,
relativeConfigLocation,
basePath,
appLocation,
isStudioApp = true,
} = options
const {reactStrictMode, relativeConfigLocation, basePath, appLocation, isCoreApp} = options

if (!isStudioApp) {
if (isCoreApp) {
return coreAppEntryModule.replace(/%APP_LOCATION%/, JSON.stringify(appLocation || './src/App'))
}

Expand Down
8 changes: 4 additions & 4 deletions packages/sanity/src/_internal/cli/server/getViteConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ export interface ViteOptions {

importMap?: {imports?: Record<string, string>}
reactCompiler: ReactCompilerConfig | undefined
isStudioApp?: boolean
isCoreApp?: boolean
}

/**
Expand All @@ -73,7 +73,7 @@ export async function getViteConfig(options: ViteOptions): Promise<InlineConfig>
basePath: rawBasePath = '/',
importMap,
reactCompiler,
isStudioApp = true,
isCoreApp,
} = options

const monorepo = await loadSanityMonorepo(cwd)
Expand Down Expand Up @@ -112,9 +112,9 @@ export async function getViteConfig(options: ViteOptions): Promise<InlineConfig>
),
sanityFaviconsPlugin({defaultFaviconsPath, customFaviconsPath, staticUrlPath: staticPath}),
sanityRuntimeRewritePlugin(),
sanityBuildEntries({basePath, cwd, monorepo, importMap, isStudioApp}),
sanityBuildEntries({basePath, cwd, monorepo, importMap, isCoreApp}),
],
envPrefix: isStudioApp ? 'SANITY_STUDIO_' : 'VITE_',
envPrefix: isCoreApp ? 'VITE_' : 'SANITY_STUDIO_',
logLevel: mode === 'production' ? 'silent' : 'info',
resolve: {
alias: monorepo?.path
Expand Down
8 changes: 4 additions & 4 deletions packages/sanity/src/_internal/cli/server/previewServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,11 @@ export interface PreviewServerOptions {
httpHost?: string

vite?: UserViteConfig
isStudioApp?: boolean
isCoreApp?: boolean
}

export async function startPreviewServer(options: PreviewServerOptions): Promise<PreviewServer> {
const {httpPort, httpHost, root, vite: extendViteConfig, isStudioApp = true} = options
const {httpPort, httpHost, root, vite: extendViteConfig, isCoreApp = true} = options
const startTime = Date.now()

const indexPath = path.join(root, 'index.html')
Expand All @@ -42,7 +42,7 @@ export async function startPreviewServer(options: PreviewServerOptions): Promise
}

const error = new Error(
`Could not find a production build in the '${root}' directory.\nTry building your ${isStudioApp ? 'studio ' : ''}app with 'sanity build' before starting the preview server.`,
`Could not find a production build in the '${root}' directory.\nTry building your ${isCoreApp ? '' : 'studio '}app with 'sanity build' before starting the preview server.`,
)
error.name = 'BUILD_NOT_FOUND'
throw error
Expand Down Expand Up @@ -91,7 +91,7 @@ export async function startPreviewServer(options: PreviewServerOptions): Promise
const startupDuration = Date.now() - startTime

info(
`Sanity ${isStudioApp ? 'Studio' : 'application'} ` +
`Sanity ${isCoreApp ? 'application' : 'Studio'} ` +
`using ${chalk.cyan(`vite@${require('vite/package.json').version}`)} ` +
`ready in ${chalk.cyan(`${Math.ceil(startupDuration)}ms`)} ` +
`and running at ${chalk.cyan(url)} (production preview mode)`,
Expand Down
Loading

0 comments on commit 2014f8d

Please sign in to comment.