Skip to content

Commit

Permalink
refactor: support strict: true in @sanity/schema codebase
Browse files Browse the repository at this point in the history
  • Loading branch information
stipsan committed Apr 4, 2024
1 parent 4247e4f commit 30201ad
Show file tree
Hide file tree
Showing 56 changed files with 237 additions and 224 deletions.
4 changes: 3 additions & 1 deletion packages/@sanity/schema/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -81,10 +81,12 @@
"humanize-list": "^1.0.1",
"leven": "^3.1.0",
"lodash": "^4.17.21",
"object-inspect": "^1.6.0"
"object-inspect": "^1.13.1"
},
"devDependencies": {
"@jest/globals": "^29.7.0",
"@types/arrify": "^1.0.1",
"@types/object-inspect": "^1.13.0",
"@sanity/icons": "^2.11.6",
"rimraf": "^3.0.2"
}
Expand Down
8 changes: 4 additions & 4 deletions packages/@sanity/schema/src/core/traverseSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,25 +54,25 @@ export function traverseSchema(
registry[(type && type.name) || `__unnamed_${i}`] = {}
})

function getType(typeName) {
function getType(typeName: any) {
return typeName === 'type'
? TYPE_TYPE
: coreTypesRegistry[typeName] || registry[typeName] || null
}

const duplicateNames = uniq(flatten(getDupes(typeNames)))

function isDuplicate(typeName) {
function isDuplicate(typeName: any) {
return duplicateNames.includes(typeName)
}
function getTypeNames() {
return typeNames.concat(coreTypeNames)
}
function isReserved(typeName) {
function isReserved(typeName: any) {
return typeName === 'type' || reservedTypeNames.includes(typeName)
}

const visitType = (isRoot) => (typeDef, index) => {
const visitType = (isRoot: any) => (typeDef: any, index: any) => {
return visitor(typeDef, {
visit: visitType(false),
isRoot,
Expand Down
12 changes: 6 additions & 6 deletions packages/@sanity/schema/src/legacy/Schema.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import * as types from './types'

function compileRegistry(schemaDef) {
function compileRegistry(schemaDef: any) {
const registry = Object.assign(Object.create(null), types)

const defsByName = schemaDef.types.reduce((acc, def) => {
const defsByName = schemaDef.types.reduce((acc: any, def: any) => {
if (acc[def.name]) {
throw new Error(`Duplicate type name added to schema: ${def.name}`)
}
Expand All @@ -15,7 +15,7 @@ function compileRegistry(schemaDef) {

return registry

function ensure(typeName) {
function ensure(typeName: any) {
if (!registry[typeName]) {
if (!defsByName[typeName]) {
throw new Error(`Unknown type: ${typeName}`)
Expand All @@ -24,12 +24,12 @@ function compileRegistry(schemaDef) {
}
}

function extendMember(memberDef) {
function extendMember(memberDef: any) {
ensure(memberDef.type)
return registry[memberDef.type].extend(memberDef, extendMember).get()
}

function add(typeDef) {
function add(typeDef: any) {
ensure(typeDef.type)
if (registry[typeDef.name]) {
return
Expand Down Expand Up @@ -84,7 +84,7 @@ export class DeprecatedDefaultSchema extends Schema {

const stack = new Error(
'The default export of `@sanity/schema` is deprecated. Use `import {Schema} from "@sanity/schema"` instead.',
).stack.replace(/^Error/, 'Warning')
).stack!.replace(/^Error/, 'Warning')

// eslint-disable-next-line no-console
console.warn(stack)
Expand Down
2 changes: 1 addition & 1 deletion packages/@sanity/schema/src/legacy/actionUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ const readActions = (schemaType: SchemaType): string[] => {
'experimental-actions-replaced-by-document-actions',
)}".
`)
hasWarned[schemaType.name] = true
;(hasWarned as any)[schemaType.name] = true
}

return ACTIONS_FLAG in schemaType ? (schemaType[ACTIONS_FLAG] as string[]) : DEFAULT_ACTIONS
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,16 @@ const CANDIDATES = ['title', 'name', 'label', 'heading', 'header', 'caption', 'd

const PRIMITIVES = ['string', 'boolean', 'number']

const isPrimitive = (field) => PRIMITIVES.includes(field.type)
const isPrimitive = (field: any) => PRIMITIVES.includes(field.type)

export default function guessOrderingConfig(objectTypeDef): SortOrdering[] {
export default function guessOrderingConfig(objectTypeDef: any): SortOrdering[] {
let candidates = CANDIDATES.filter((candidate) =>
objectTypeDef.fields.some((field) => isPrimitive(field) && field.name === candidate),
objectTypeDef.fields.some((field: any) => isPrimitive(field) && field.name === candidate),
)

// None of the candidates were found, fallback to all fields
if (candidates.length === 0) {
candidates = objectTypeDef.fields.filter(isPrimitive).map((field) => field.name)
candidates = objectTypeDef.fields.filter(isPrimitive).map((field: any) => field.name)
}

return candidates.map(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {pick} from 'lodash'

function isEmpty(object) {
function isEmpty(object: any) {
for (const key in object) {
if (object.hasOwnProperty(key)) {
return false
Expand All @@ -9,7 +9,7 @@ function isEmpty(object) {
return true
}

function _stringify(value, options, depth) {
function _stringify(value: any, options: any, depth: any): any {
if (depth > options.maxDepth) {
return '...'
}
Expand All @@ -18,7 +18,7 @@ function _stringify(value, options, depth) {
return '[empty]'
}
const capLength = Math.max(value.length - options.maxBreadth)
const asString = value
const asString: any = value
.slice(0, options.maxBreadth)
.map((item, index) => _stringify(item, options, depth + 1))
.concat(capLength > 0 ? `…+${capLength}` : [])
Expand Down Expand Up @@ -47,7 +47,7 @@ function _stringify(value, options, depth) {
}

export default function stringify(
value,
value: any,
options: {maxDepth?: number; maxBreadth?: number; ignoreKeys?: string[]} = {},
) {
const opts = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@ import {pick} from 'lodash'
import {warnIfPreviewHasFields, warnIfPreviewOnOptions} from './deprecationUtils'
import guessPreviewConfig from './guessPreviewConfig'

function parseSelection(selection) {
return selection.reduce((acc, field) => {
function parseSelection(selection: any) {
return selection.reduce((acc: any, field: any) => {
acc[field] = field
return acc
}, {})
}

function parsePreview(preview) {
function parsePreview(preview: any) {
if (!preview) {
return preview
}
Expand All @@ -27,7 +27,7 @@ function parsePreview(preview) {
}
}

export default function createPreviewGetter(objectTypeDef) {
export default function createPreviewGetter(objectTypeDef: any) {
return function previewGetter() {
warnIfPreviewOnOptions(objectTypeDef)
warnIfPreviewHasFields(objectTypeDef)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export function warnIfPreviewOnOptions(type) {
export function warnIfPreviewOnOptions(type: any) {
if (type.options && type.options.preview) {
// eslint-disable-next-line no-console
console.warn(`Heads up! The preview config is no longer defined on "options", but instead on the type/field itself.
Expand All @@ -7,7 +7,7 @@ Please move {options: {preview: ...}} to {..., preview: ...} on the type/field d
}
}

export function warnIfPreviewHasFields(type) {
export function warnIfPreviewHasFields(type: any) {
const preview = type.preview || (type.options || {}).preview
if (preview && 'fields' in preview) {
// eslint-disable-next-line no-console
Expand Down
4 changes: 2 additions & 2 deletions packages/@sanity/schema/src/legacy/preview/fallbackPrepare.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ const OPTIONS = {
ignoreKeys: ['_id', '_type', '_key', '_ref'],
}

export function createFallbackPrepare(fieldNames) {
return (value) => ({
export function createFallbackPrepare(fieldNames: any) {
return (value: any) => ({
title: stringify(pick(value, fieldNames), OPTIONS),
})
}
30 changes: 15 additions & 15 deletions packages/@sanity/schema/src/legacy/preview/guessPreviewConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,51 +7,51 @@ import {isBlockField} from './portableText'
const TITLE_CANDIDATES = ['title', 'name', 'label', 'heading', 'header', 'caption']
const DESCRIPTION_CANDIDATES = ['description', ...TITLE_CANDIDATES]

function fieldHasReferenceTo(fieldDef, refType) {
return arrify(fieldDef.to || []).some((memberTypeDef) => memberTypeDef.type === refType)
function fieldHasReferenceTo(fieldDef: any, refType: any) {
return arrify(fieldDef.to || []).some((memberTypeDef: any) => memberTypeDef.type === refType)
}

function isImageAssetField(fieldDef) {
function isImageAssetField(fieldDef: any) {
return fieldHasReferenceTo(fieldDef, 'sanity.imageAsset')
}

function resolveImageAssetPath(typeDef) {
function resolveImageAssetPath(typeDef: any) {
const fields = typeDef.fields || []
const imageAssetField = fields.find(isImageAssetField)
if (imageAssetField) {
return imageAssetField.name
}
const fieldWithImageAsset = fields.find((fieldDef) =>
const fieldWithImageAsset = fields.find((fieldDef: any) =>
(fieldDef.fields || []).some(isImageAssetField),
)

return fieldWithImageAsset ? `${fieldWithImageAsset.name}.asset` : undefined
}

function isFileAssetField(fieldDef) {
function isFileAssetField(fieldDef: any) {
return fieldHasReferenceTo(fieldDef, 'sanity.fileAsset')
}

function resolveFileAssetPath(typeDef) {
function resolveFileAssetPath(typeDef: any) {
const fields = typeDef.fields || []
const assetField = fields.find(isFileAssetField)
if (assetField) {
return assetField.name
}
const fieldWithFileAsset = fields.find((fieldDef) =>
const fieldWithFileAsset = fields.find((fieldDef: any) =>
(fieldDef.fields || []).some(isFileAssetField),
)
return fieldWithFileAsset ? `${fieldWithFileAsset.name}.asset` : undefined
}

export default function guessPreviewFields(rawObjectTypeDef) {
export default function guessPreviewFields(rawObjectTypeDef: any) {
const objectTypeDef = {fields: [], ...rawObjectTypeDef}

const stringFieldNames = objectTypeDef.fields
.filter((field) => field.type === 'string')
.map((field) => field.name)
.filter((field: any) => field.type === 'string')
.map((field: any) => field.name)

const blockFieldNames = objectTypeDef.fields.filter(isBlockField).map((field) => field.name)
const blockFieldNames = objectTypeDef.fields.filter(isBlockField).map((field: any) => field.name)

// Check if we have fields with names that is listed in candidate fields
let titleField = TITLE_CANDIDATES.find(
Expand All @@ -71,7 +71,7 @@ export default function guessPreviewFields(rawObjectTypeDef) {
descField = stringFieldNames[1] || blockFieldNames[1]
}

const mediaField = objectTypeDef.fields.find((field) => field.type === 'image')
const mediaField = objectTypeDef.fields.find((field: any) => field.type === 'image')

const imageAssetPath = resolveImageAssetPath(objectTypeDef)

Expand All @@ -87,8 +87,8 @@ export default function guessPreviewFields(rawObjectTypeDef) {

if (!titleField && !imageAssetPath) {
// last resort, pick all fields and concat them
const fieldNames = objectTypeDef.fields.map((field) => field.name)
const fieldMapping = fieldNames.reduce((acc, fieldName) => {
const fieldNames = objectTypeDef.fields.map((field: any) => field.name)
const fieldMapping = fieldNames.reduce((acc: any, fieldName: any) => {
acc[fieldName] = fieldName
return acc
}, {})
Expand Down
5 changes: 4 additions & 1 deletion packages/@sanity/schema/src/legacy/preview/portableText.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,8 @@ type FieldDef = {
}

export function isBlockField(field: FieldDef): boolean {
return field.type === 'array' && field.of && field.of.some((member) => member.type === 'block')
return (
(field.type === 'array' && field.of && field.of.some((member) => member.type === 'block')) ||
false
)
}
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
export default {
prepare: (val) => ({title: String(val)}),
prepare: (val: any) => ({title: String(val)}),
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {isPlainObject, toPath} from 'lodash'

export function normalizeSearchConfigs(configs) {
export function normalizeSearchConfigs(configs: any) {
if (!Array.isArray(configs)) {
throw new Error(
'The search config of a document type must be an array of search config objects',
Expand Down
Loading

0 comments on commit 30201ad

Please sign in to comment.