How to use @sanity/util - 10 common examples

To help you get started, we’ve selected a few @sanity/util examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github sanity-io / sanity / packages / @sanity / form-builder / src / inputs / Slug / SlugInput.tsx View on Github external
handleGenerateSlug = () => {
        const {type} = this.props
        const source = get(type, ['options', 'source'])
        if (!source) {
          // eslint-disable-next-line no-console
          console.error(`Source is missing. Check source on type "${type.name}" in schema`)
          return
        }
        const newFromSource = this.getNewFromSource()
        this.setState({loading: true})
        this.slugify(newFromSource || '')
          .then(newSlug => this.updateCurrent(newSlug))
          .catch(err => {
            // eslint-disable-next-line no-console
            console.error(
              `An error occured while slugifying "${newFromSource}":\n${err.message}\n${err.stack}`
            )
          })
          .then(() => this._isMounted && this.setState({loading: false}))
github sanity-io / sanity / packages / @sanity / form-builder / src / FormBuilderInput.tsx View on Github external
handleFocus = nextPath => {
    const {path, onFocus, focusPath} = this.props
    if (!onFocus) {
      // eslint-disable-next-line no-console
      console.warn(
        'FormBuilderInput was used without passing a required onFocus prop. Read more at %s.',
        generateHelpUrl('form-builder-input-missing-required-prop')
      )
      return
    }
    const nextFocusPath = Array.isArray(nextPath) ? [...path, ...nextPath] : path
    if (PathUtils.isEqual(focusPath, nextFocusPath)) {
      // no change
      return
    }
    onFocus(nextFocusPath)
  }
  handleBlur = () => {
github sanity-io / sanity / packages / @sanity / core / src / actions / deploy / deployAction.js View on Github external
output.print('To deploy your Sanity Studio to our hosted Sanity.Studio service,')
    output.print('you will need one. Please enter the part you want to use.')

    studioHostname = await prompt.single({
      type: 'input',
      filter: inp => inp.replace(/\.sanity\.studio$/i, ''),
      message: 'Studio hostname (.sanity.studio):',
      validate: name => validateHostname(name, client)
    })
  }

  // Always build the project, unless --no-build is passed
  const shouldBuild = flags.build
  if (shouldBuild) {
    const overrides = {project: {basePath: undefined}}
    const buildStaticAssets = lazyRequire(require.resolve('../build/buildStaticAssets'))
    const buildArgs = [args.argsWithoutOptions[0]].filter(Boolean)
    await buildStaticAssets({extOptions: flags, argsWithoutOptions: buildArgs, overrides}, context)
  }

  // Ensure that the directory exists, is a directory and seems to have valid content
  spinner = output.spinner('Verifying local content').start()
  try {
    await checkDir(sourceDir)
    spinner.succeed()
  } catch (err) {
    spinner.fail()
    throw err
  }

  // Now create a tarball of the given directory
  const parentDir = path.dirname(sourceDir)
github sanity-io / sanity / packages / @sanity / initial-value-templates / src / validate.ts View on Github external
}

  if (!isPlainObject(value)) {
    return value
  }

  // Apply missing keys is the parent is an array
  const initial: {[key: string]: any} = parentIsArray && !value._key ? {_key: randomKey()} : {}

  // Ensure non-root objects have _type
  if (path.length > 0 && !value._type) {
    if (value._ref) {
      // In the case of references, we know what the type should be, so apply it
      initial._type = 'reference'
    } else {
      throw new Error(`missing "_type" property at path "${pathToString(path)}"`)
    }
  }

  if (value._ref) {
    validateReference(value, path)
  }

  // Validate deeply
  return Object.keys(value).reduce((acc, key) => {
    acc[key] = validateValue(value[key], path.concat([key]))
    return acc
  }, initial)
}
github sanity-io / sanity / packages / @sanity / cli / src / commands / upgrade / upgradeDependencies.js View on Github external
context.output.print(`${chalk.green('✔')} ${specified} Sanity modules are at latest versions`)
    return
  }

  // Forcefully remove non-symlinked module paths to force upgrade
  await Promise.all(
    needsUpdate.map(mod =>
      deleteIfNotSymlink(
        path.join(context.workDir, 'node_modules', mod.name.replace(/\//g, path.sep))
      )
    )
  )

  // Replace versions in `package.json`
  const versionPrefix = saveExact ? '' : '^'
  const oldManifest = await readLocalManifest(workDir)
  const newManifest = needsUpdate.reduce((target, mod) => {
    if (oldManifest.dependencies && oldManifest.dependencies[mod.name]) {
      target.dependencies[mod.name] =
        mod.latest === 'unknown' ? oldManifest.dependencies[mod.name] : versionPrefix + mod.latest
    }

    if (oldManifest.devDependencies && oldManifest.devDependencies[mod.name]) {
      target.devDependencies[mod.name] =
        mod.latest === 'unknown'
          ? oldManifest.devDependencies[mod.name]
          : versionPrefix + mod.latest
    }

    return target
  }, oldManifest)
github sanity-io / sanity / packages / @sanity / webpack-loader / src / partLoader.js View on Github external
const path = require('path')
const loaderUtils = require('loader-utils')
const sanityUtil = require('@sanity/util')
const multiImplementationHandler = require('./multiImplementationHandler')
const reduceConfig = sanityUtil.reduceConfig
const getSanityVersions = sanityUtil.getSanityVersions

/* eslint-disable no-process-env */
const sanityEnv = process.env.SANITY_INTERNAL_ENV
const env = typeof sanityEnv === 'undefined' ? process.env.NODE_ENV : sanityEnv
/* eslint-enable no-process-env */

function sanityPartLoader(input) {
  this.cacheable()

  let buildEnv = sanityEnv
  if (!buildEnv) {
    buildEnv = this.options.devtool ? env : 'production'
  }

  const qs = this.resourceQuery.substring(this.resourceQuery.indexOf('?'))
  const request = (loaderUtils.parseQuery(qs) || {}).sanityPart
github sanity-io / sanity / packages / @sanity / plugin-loader / loader.js View on Github external
const path = require('path')
const Module = require('module')
const interopRequire = require('interop-require')
const cssHook = require('css-modules-require-hook')
const resolver = require('@sanity/resolver')
const util = require('@sanity/util')

const reduceConfig = util.reduceConfig
const getSanityVersions = util.getSanityVersions

/* eslint-disable no-process-env */
const sanityEnv = process.env.SANITY_INTERNAL_ENV
const env = typeof sanityEnv === 'undefined' ? process.env.NODE_ENV : sanityEnv
/* eslint-enable no-process-env */

const configMatcher = /^config:(@?[A-Za-z0-9_-]+\/[A-Za-z0-9_-]+|[A-Za-z0-9_-]+)$/
const resolveParts = resolver.resolveParts
const defaultResult = {
  definitions: {},
  implementations: {},
  plugins: []
}

function registerLoader(options) {
  if (!options) {
github sanity-io / sanity / packages / @sanity / initial-value-templates / src / validate.ts View on Github external
if (Array.isArray(item)) {
        throw new Error(
          `multidimensional arrays are not supported (at path "${pathToString(path)}")`
        )
      }

      return validateValue(item, path.concat(i), true)
    })
  }

  if (!isPlainObject(value)) {
    return value
  }

  // Apply missing keys is the parent is an array
  const initial: {[key: string]: any} = parentIsArray && !value._key ? {_key: randomKey()} : {}

  // Ensure non-root objects have _type
  if (path.length > 0 && !value._type) {
    if (value._ref) {
      // In the case of references, we know what the type should be, so apply it
      initial._type = 'reference'
    } else {
      throw new Error(`missing "_type" property at path "${pathToString(path)}"`)
    }
  }

  if (value._ref) {
    validateReference(value, path)
  }

  // Validate deeply
github sanity-io / sanity / packages / @sanity / cli / src / actions / init-plugin / initPlugin.js View on Github external
async function bootstrapFromUrl(context, url) {
  const {output, prompt, yarn, workDir} = context

  debug('Bootstrapping from URL: %s', url)
  const {name, outputPath, inPluginsPath, dependencies} = await bootstrapFromTemplate(context, url)

  if (inPluginsPath) {
    const addIt = await prompt.single({
      type: 'confirm',
      message: 'Enable plugin in current Sanity installation?',
      default: true
    })

    if (addIt) {
      await addPluginToManifest(workDir, name.replace(/^sanity-plugin-/, ''))
    }
  }

  if (dependencies) {
    const dependencyString = JSON.stringify(dependencies, null, 2)
      .split('\n')
      .slice(1, -1)
      .join('\n')
      .replace(/"/g, '')

    output.print('\nThe following dependencies are required for this template:')
    output.print(`${dependencyString}\n`)
  }

  if (dependencies && inPluginsPath) {
    const addDeps = await prompt.single({
github sanity-io / sanity / packages / @sanity / resolver / src / readManifest.js View on Github external
function parseManifest(rawData, options) {
  const parsedManifest = JSON.parse(rawData)
  const manifest = validateManifest(parsedManifest)
  const reduced = reduceConfig(manifest, options.env, {
    studioRootPath: options.basePath || process.cwd()
  })
  return reduced
}