@sanity/cli 8.30.0 → 8.32.0
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.
- package/README.md +179 -103
- package/bin/run.js +1 -1
- package/dist/actions/context/waitForSourceSync.js +1 -1
- package/dist/actions/context/waitForSourceSync.js.map +1 -1
- package/dist/actions/cors/filterAndValidateOrigin.js +1 -1
- package/dist/actions/cors/filterAndValidateOrigin.js.map +1 -1
- package/dist/actions/deploy/deployApp.js +12 -6
- package/dist/actions/deploy/deployApp.js.map +1 -1
- package/dist/actions/deploy/deployStudio.js +14 -14
- package/dist/actions/deploy/deployStudio.js.map +1 -1
- package/dist/actions/deploy/deployStudioSchemasAndManifests.js +1 -2
- package/dist/actions/deploy/deployStudioSchemasAndManifests.js.map +1 -1
- package/dist/actions/deploy/deployStudioSchemasAndManifestsWorker.js +13 -1
- package/dist/actions/deploy/deployStudioSchemasAndManifestsWorker.js.map +1 -1
- package/dist/actions/deploy/types.js +0 -1
- package/dist/actions/deploy/types.js.map +1 -1
- package/dist/actions/dev/devAction.js +5 -1
- package/dist/actions/dev/devAction.js.map +1 -1
- package/dist/actions/dev/servers/startAppDevServer.js +3 -3
- package/dist/actions/dev/servers/startAppDevServer.js.map +1 -1
- package/dist/actions/dev/servers/startStudioDevServer.js +12 -13
- package/dist/actions/dev/servers/startStudioDevServer.js.map +1 -1
- package/dist/actions/dev/types.js.map +1 -1
- package/dist/actions/documents/validateDocuments.worker.js +2 -1
- package/dist/actions/documents/validateDocuments.worker.js.map +1 -1
- package/dist/actions/graphql/extractFromSanitySchema.js +1 -1
- package/dist/actions/graphql/extractFromSanitySchema.js.map +1 -1
- package/dist/actions/init/initStudio.js +1 -1
- package/dist/actions/init/initStudio.js.map +1 -1
- package/dist/actions/init/processTemplate.js +1 -1
- package/dist/actions/init/processTemplate.js.map +1 -1
- package/dist/actions/init/remoteTemplate.js +1 -1
- package/dist/actions/init/remoteTemplate.js.map +1 -1
- package/dist/actions/manifest/extractManifest.js +2 -1
- package/dist/actions/manifest/extractManifest.js.map +1 -1
- package/dist/actions/manifest/extractStudioManifest.js +1 -0
- package/dist/actions/manifest/extractStudioManifest.js.map +1 -1
- package/dist/actions/media/pullAspects.js +1 -1
- package/dist/actions/media/pullAspects.js.map +1 -1
- package/dist/actions/organizations/readOrganizationLogo.js +49 -0
- package/dist/actions/organizations/readOrganizationLogo.js.map +1 -0
- package/dist/actions/preview/previewAction.js +1 -1
- package/dist/actions/preview/previewAction.js.map +1 -1
- package/dist/actions/skills/readSkillState.js +1 -1
- package/dist/actions/skills/readSkillState.js.map +1 -1
- package/dist/actions/skills/setupSkills.js +1 -1
- package/dist/actions/skills/setupSkills.js.map +1 -1
- package/dist/commands/organizations/create.js +43 -3
- package/dist/commands/organizations/create.js.map +1 -1
- package/dist/commands/organizations/update.js +67 -14
- package/dist/commands/organizations/update.js.map +1 -1
- package/dist/exports/invokeSanityCli/commandPolicies/mcpPolicy.js +7 -2
- package/dist/exports/invokeSanityCli/commandPolicies/mcpPolicy.js.map +1 -1
- package/dist/generated/contextOperations.js +2 -2
- package/dist/generated/contextOperations.js.map +1 -1
- package/dist/hooks/commandNotFound/topicAliases.js +1 -1
- package/dist/hooks/commandNotFound/topicAliases.js.map +1 -1
- package/dist/server/devServer.js +8 -10
- package/dist/server/devServer.js.map +1 -1
- package/dist/services/organizations.js +30 -0
- package/dist/services/organizations.js.map +1 -1
- package/dist/util/telemetry/cliCommandIdentity.js +3 -2
- package/dist/util/telemetry/cliCommandIdentity.js.map +1 -1
- package/dist/util/update/updateChecker.js +1 -1
- package/dist/util/update/updateChecker.js.map +1 -1
- package/oclif.config.js +1 -1
- package/oclif.manifest.json +2892 -2850
- package/package.json +28 -29
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/graphql/extractFromSanitySchema.ts"],"sourcesContent":["/* eslint-disable unicorn/consistent-function-scoping */\nimport {generateHelpUrl} from '@sanity/generate-help-url'\nimport {Schema} from '@sanity/schema'\nimport {\n type ArraySchemaType,\n type Schema as CompiledSchema,\n type CrossDatasetReferenceSchemaType,\n type IntrinsicTypeName,\n isDeprecationConfiguration,\n type ObjectField,\n type ObjectFieldType,\n type ObjectSchemaType,\n type ReferenceSchemaType,\n type SchemaType,\n} from '@sanity/types'\nimport startCase from 'lodash-es/startCase.js'\nimport uniqBy from 'lodash-es/uniqBy.js'\nimport {oneline} from 'oneline'\n\nimport {SCHEMA_LIFT_ANONYMOUS_OBJECT_TYPE} from './helpUrls.js'\nimport {SchemaError} from './SchemaError.js'\nimport {\n type ApiSpecification,\n type ConvertedFieldDefinition,\n type ConvertedInterface,\n type ConvertedType,\n type ConvertedUnion,\n type Deprecation,\n} from './types.js'\n\nconst skipTypes = new Set(['document', 'reference'])\nconst allowedJsonTypes = new Set(['array', 'object'])\nconst disallowedCustomizedMembers = new Set(['array', 'block', 'file', 'image', 'object'])\nconst disabledBlockFields = new Set(['markDefs'])\nconst scalars = new Set(['boolean', 'number', 'string'])\n\nfunction getBaseType(baseSchema: CompiledSchema, typeName: IntrinsicTypeName): SchemaType {\n if (typeName === 'crossDatasetReference') {\n return Schema.compile({\n parent: baseSchema,\n types: [\n {\n name: `__placeholder__`,\n // Just needs _something_ to refer to, doesn't matter what\n to: [{type: 'sanity.imageAsset'}],\n type: 'crossDatasetReference',\n },\n ],\n }).get('__placeholder__')\n }\n if (typeName === 'globalDocumentReference') {\n return Schema.compile({\n parent: baseSchema,\n types: [\n {\n name: `__placeholder__`,\n // Just needs _something_ to refer to, doesn't matter what\n to: [{type: 'sanity.imageAsset'}],\n type: 'globalDocumentReference',\n },\n ],\n }).get('__placeholder__')\n }\n\n return Schema.compile({\n parent: baseSchema,\n types: [{name: `__placeholder__`, options: {hotspot: true}, type: typeName}],\n }).get('__placeholder__')\n}\n\nfunction getTypeName(str: string): string {\n const name = startCase(str).replaceAll(/\\s+/g, '')\n return name === 'Number' ? 'Float' : name\n}\n\nfunction isBaseType(type: SchemaType): boolean {\n return (\n type.name !== type.jsonType &&\n allowedJsonTypes.has(type.jsonType) &&\n !skipTypes.has(type.name) &&\n !isReference(type)\n )\n}\n\nfunction isBlockType(typeDef: ObjectField | SchemaType): boolean {\n if (typeDef.name === 'block') {\n return true\n }\n\n if (typeDef.type) {\n return isBlockType(typeDef.type)\n }\n\n return false\n}\n\nfunction hasBlockParent(typeDef: SchemaType): boolean {\n if (typeDef.type && typeDef.type.name === 'block' && !typeDef.type.type) {\n return true\n }\n\n return Boolean(typeDef.type && hasBlockParent(typeDef.type))\n}\n\nfunction isArrayOfBlocks(typeDef: ObjectField | SchemaType): boolean {\n const type = typeDef.type || typeDef\n if (!('jsonType' in type) || type.jsonType !== 'array') {\n return false\n }\n\n return (type.of || []).some((item) => hasBlockParent(item))\n}\n\nfunction isType(typeDef: ObjectField | ObjectFieldType | SchemaType, typeName: string): boolean {\n let type: ObjectField | ObjectFieldType | SchemaType | undefined = typeDef\n while (type) {\n if (type.name === typeName || (type.type && type.type.name === typeName)) {\n return true\n }\n\n type = type.type\n }\n return false\n}\n\nfunction isReference(\n typeDef: ObjectField | ObjectFieldType | SchemaType,\n): typeDef is ReferenceSchemaType {\n return isType(typeDef, 'reference')\n}\n\nfunction isCrossDatasetReference(\n typeDef: CrossDatasetReferenceSchemaType | ObjectField | ObjectFieldType | SchemaType,\n) {\n return isType(typeDef, 'crossDatasetReference')\n}\n\nfunction getCrossDatasetReferenceMetadata(\n typeDef: CrossDatasetReferenceSchemaType | ObjectField | ObjectFieldType | SchemaType,\n) {\n if (!isCrossDatasetReference(typeDef)) return\n\n function getTypeNames(\n type: CrossDatasetReferenceSchemaType | ObjectField | ObjectFieldType | SchemaType | undefined,\n ) {\n if (!type) return\n if (!('to' in type)) return getTypeNames(type.type)\n return type.to.map((t) => t.type).filter((t): t is string => typeof t === 'string')\n }\n\n function getDataset(\n type: CrossDatasetReferenceSchemaType | ObjectField | ObjectFieldType | SchemaType | undefined,\n ) {\n if (!type) return\n if ('dataset' in type && typeof type.dataset === 'string') return type.dataset\n if (type.type) return getDataset(type.type)\n }\n\n const typeNames = getTypeNames(typeDef)\n if (!typeNames) return\n\n const dataset = getDataset(typeDef)\n if (typeof dataset !== 'string') return\n\n return {dataset, typeNames}\n}\n\nexport function extractFromSanitySchema(\n sanitySchema: CompiledSchema,\n extractOptions: {nonNullDocumentFields?: boolean; withUnionCache?: boolean} = {},\n): ApiSpecification {\n const {nonNullDocumentFields, withUnionCache} = extractOptions\n const unionRecursionGuards = new Set<string>()\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const unionDefinitionCache = new Map<string, any>()\n const hasErrors =\n sanitySchema._validation &&\n sanitySchema._validation.some((group) =>\n group.problems.some((problem) => problem.severity === 'error'),\n )\n\n if (hasErrors && Array.isArray(sanitySchema._validation)) {\n throw new SchemaError(sanitySchema._validation)\n }\n\n const sanityTypes = sanitySchema._original?.types || []\n const typeNames = sanitySchema.getTypeNames()\n const unionTypes: ConvertedUnion[] = []\n const types: ConvertedType[] = []\n\n for (const typeName of typeNames) {\n const schemaType = sanitySchema.get(typeName)\n if (schemaType === undefined) {\n continue\n }\n if (!isBaseType(schemaType)) {\n continue\n }\n\n const convertedType = convertType(schemaType)\n types.push(convertedType)\n }\n\n const withUnions = [...types, ...unionTypes]\n return {interfaces: [getDocumentInterfaceDefinition()], types: withUnions}\n\n function isTopLevelType(typeName: string): boolean {\n return typeNames.includes(typeName)\n }\n\n function mapFieldType(field: ObjectField | ObjectFieldType | SchemaType): string {\n if (!field.type) {\n throw new Error('Field has no type!')\n }\n\n const jsonType = 'jsonType' in field ? field.jsonType : ''\n const isScalar = scalars.has(jsonType)\n if (isScalar && jsonType === 'number') {\n return hasValidationFlag(field, 'integer') ? 'Int' : 'Float'\n } else if (isScalar) {\n return getTypeName(jsonType)\n }\n\n const type = field.type.type || field.type\n\n // In the case of nested scalars, recurse (markdown -> longText -> text -> string)\n if (type.type) {\n return mapFieldType(type)\n }\n\n switch (type.name) {\n case 'number': {\n return hasValidationFlag(field, 'integer') ? 'Int' : 'Float'\n }\n default: {\n return getTypeName(type.name)\n }\n }\n }\n\n function isArrayType(type: ObjectField | SchemaType): type is ArraySchemaType {\n return Boolean(\n ('jsonType' in type && type.jsonType === 'array') ||\n (type.type && type.type.jsonType === 'array'),\n )\n }\n\n function _convertType(\n type: ObjectField | SchemaType,\n parent: string,\n options: {isField?: boolean},\n ): ConvertedType {\n let name: string | undefined\n if (type.type) {\n name = type.type.name\n } else if ('jsonType' in type) {\n name = type.jsonType\n }\n\n if (isReference(type)) {\n return getReferenceDefinition(type)\n }\n\n if (isArrayType(type)) {\n return getArrayDefinition(type, parent, options)\n }\n\n if (name === 'document') {\n return getDocumentDefinition(type as ObjectSchemaType)\n }\n\n if (name === 'block' || name === 'object') {\n return getObjectDefinition(type, parent)\n }\n\n if (hasFields(type)) {\n return getObjectDefinition(type, parent)\n }\n\n return {\n description: getDescription(type),\n type: mapFieldType(type),\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any\n }\n\n function convertType(\n type: ObjectField | SchemaType,\n parent?: string,\n props: Partial<Deprecation> & {fieldName?: string} = {},\n ): ConvertedType {\n const mapped = _convertType(type, parent || '', {isField: Boolean(props.fieldName)})\n const gqlName = props.fieldName || mapped.name\n const originalName = type.name\n const original = gqlName === originalName ? {} : {originalName: originalName}\n const crossDatasetReferenceMetadata = getCrossDatasetReferenceMetadata(type)\n\n return {\n ...getDeprecation(type.type),\n ...props,\n ...mapped,\n ...original,\n ...(crossDatasetReferenceMetadata && {crossDatasetReferenceMetadata}),\n }\n }\n\n function isField(def: ObjectField | SchemaType): def is ObjectField {\n return !('jsonType' in def) || !def.jsonType\n }\n\n function getObjectDefinition(def: ObjectField | SchemaType, parent?: string): ConvertedType {\n const isInline = isField(def)\n const isDocument = def.type ? def.type.name === 'document' : false\n const actualType = isInline ? def.type : def\n\n if (typeNeedsHoisting(actualType)) {\n throw createLiftTypeError(def.name, parent || '', actualType.name)\n }\n\n if (isInline && parent && def.type.name === 'object') {\n throw createLiftTypeError(def.name, parent)\n }\n\n if (parent && def.type && isTopLevelType(def.type.name)) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return {type: getTypeName(def.type.name)} as any\n }\n\n const name = `${parent || ''}${getTypeName(def.name)}`\n const fields = collectFields(def)\n const firstUnprefixed = Math.max(\n 0,\n fields.findIndex((field) => field.name[0] !== '_'),\n )\n\n const keyField = createStringField('_key')\n\n fields.splice(firstUnprefixed, 0, keyField)\n\n if (!isDocument) {\n fields.splice(firstUnprefixed + 1, 0, createStringField('_type'))\n }\n\n const objectIsBlock = isBlockType(def)\n const objectFields = objectIsBlock\n ? fields.filter((field) => !disabledBlockFields.has(field.name))\n : fields\n\n return {\n _internal: {\n ...getDeprecation(def),\n },\n description: getDescription(def),\n fields: objectFields.map((field) =>\n isArrayOfBlocks(field)\n ? buildRawField(field, name)\n : (convertType(field, name, {\n fieldName: field.name,\n ...getDeprecation(def),\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n }) as any),\n ),\n kind: 'Type',\n name,\n type: 'Object',\n }\n }\n\n function buildRawField(field: ObjectField, parentName: string) {\n return {\n ...convertType(field, parentName, {fieldName: `${field.name}Raw`}),\n isRawAlias: true,\n type: 'JSON',\n }\n }\n\n function createStringField(name: string): ObjectField {\n return {\n name,\n type: {\n jsonType: 'string',\n name: 'string',\n type: {jsonType: 'string', name: 'string', type: undefined},\n },\n }\n }\n\n function collectFields(def: ObjectField | SchemaType) {\n const fields = gatherAllFields(def)\n if (fields.length > 0) {\n return fields\n }\n\n const extended = getBaseType(sanitySchema, def.name as IntrinsicTypeName)\n return gatherAllFields(extended)\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n function getReferenceDefinition(def: SchemaType): any {\n const base = {description: getDescription(def), isReference: true}\n const candidates = arrayify(gatherAllReferenceCandidates(def))\n if (candidates.length === 0) {\n throw new Error('No candidates for reference')\n }\n\n if (candidates.length === 1) {\n return {type: getTypeName(candidates[0].type.name), ...base}\n }\n\n const allTypeNames = candidates.map((c) => getTypeName(c.type.name))\n const targetTypes = [...new Set(allTypeNames)].toSorted()\n const name = targetTypes.join('Or')\n\n // Register the union type if we haven't seen it before\n if (!unionTypes.some((item) => item.name === name)) {\n unionTypes.push({\n kind: 'Union',\n name,\n types: targetTypes,\n })\n }\n\n return {\n type: name,\n ...base,\n }\n }\n\n function getArrayDefinition(\n def: ArraySchemaType,\n parent: string,\n options: {isField?: boolean} = {},\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): any {\n const base = {description: getDescription(def), kind: 'List'}\n const name = !options.isField && def.name ? {name: getTypeName(def.name)} : {}\n const candidates = def.type?.type && 'of' in def.type ? arrayify(def.type.of) : def.of\n\n return candidates.length === 1\n ? {\n children: getArrayChildDefinition(candidates[0], def),\n ...base,\n ...name,\n }\n : {\n children: getUnionDefinition(candidates, def, {grandParent: parent}),\n ...base,\n ...name,\n }\n }\n\n function getArrayChildDefinition(child: SchemaType, arrayDef: SchemaType) {\n if (typeNeedsHoisting(child)) {\n // Seems to be inline? Should be hoisted?\n throw createLiftTypeError(child.name, arrayDef.name)\n }\n\n if (isReference(child)) {\n return getReferenceDefinition(child)\n }\n\n // In the case of nested scalars, recurse (markdown -> longText -> text -> string)\n if (scalars.has(child.jsonType) && !scalars.has(child.name)) {\n return {type: mapFieldType(child)}\n }\n\n return {type: getTypeName(child.name)}\n }\n\n function typeNeedsHoisting(type: SchemaType & {isCustomized?: boolean}): boolean {\n if (type.name === 'object') {\n return true\n }\n\n if (type.jsonType === 'object' && !isTopLevelType(type.name)) {\n return true\n }\n\n if (type.isCustomized && !isTopLevelType(type.name)) {\n return true\n }\n\n if (type.isCustomized && disallowedCustomizedMembers.has(type.name)) {\n return true\n }\n\n return false\n }\n\n function getUnionDefinition(\n candidates: ObjectSchemaType[],\n parent: SchemaType,\n options: {grandParent?: string} = {},\n ) {\n if (candidates.length < 2) {\n throw new Error('Not enough candidates for a union type')\n }\n\n // #1482: When creating union definition do not get caught in recursion loop\n // for types that reference themselves\n const guardPathName = `${typeof parent === 'object' ? parent.name : parent}`\n if (unionRecursionGuards.has(guardPathName)) {\n return {}\n }\n\n const unionCacheKey = `${options.grandParent}-${guardPathName}-${candidates\n .map((c) => c.type?.name)\n .join('-')}`\n if (withUnionCache && unionDefinitionCache.has(unionCacheKey)) {\n return unionDefinitionCache.get(unionCacheKey)\n }\n\n try {\n unionRecursionGuards.add(guardPathName)\n\n for (const [i, def] of candidates.entries()) {\n if (typeNeedsHoisting(def)) {\n throw createLiftTypeArrayError(\n i,\n parent.name,\n def.type ? def.type.name : def.name,\n options.grandParent,\n )\n }\n }\n\n const converted = candidates.map((def) => convertType(def))\n\n const getName = (def: {type: string | {name: string}}): string =>\n typeof def.type === 'string' ? def.type : def.type.name\n\n // We might end up with union types being returned - these needs to be flattened\n // so that an ImageOr(PersonOrPet) becomes ImageOrPersonOrPet\n // eslint-disable-next-line unicorn/no-array-reduce\n const flattened = converted.reduce(\n (acc, candidate) => {\n const union = unionTypes.find((item) => item.name === candidate.type)\n return union\n ? // eslint-disable-next-line unicorn/prefer-spread\n acc.concat(union.types.map((type) => ({isReference: candidate.isReference, type})))\n : [...acc, candidate]\n },\n [] as {isReference?: boolean; name?: string; type: string | {name: string}}[],\n )\n\n let allCandidatesAreDocuments = true\n const refs: (string | {name: string})[] = []\n const inlineObjs: string[] = []\n const allTypeNames: string[] = []\n for (const def of flattened) {\n if (def.isReference) {\n refs.push(def.type)\n }\n if (!isReference) {\n inlineObjs.push(def.name || '')\n }\n\n const typeName = typeof def.type === 'string' ? def.type : def.type.name\n\n // Here we remove duplicates, as they might appear twice due to in-line usage of types as well as references\n if (def.name || def.type) {\n allTypeNames.push(def.isReference ? typeName : def.name || '')\n }\n\n const typeDef = sanityTypes.find((type) => type.name === getName(def))\n if (!typeDef || typeDef.type !== 'document') {\n allCandidatesAreDocuments = false\n }\n }\n\n const interfaces = allCandidatesAreDocuments ? ['Document'] : undefined\n const possibleTypes = [...new Set(allTypeNames)].toSorted()\n\n if (possibleTypes.length < 2) {\n throw new Error(`Not enough types for a union type. Parent: ${parent.name}`)\n }\n\n const name = possibleTypes.join('Or')\n\n if (!unionTypes.some((item) => item.name === name)) {\n unionTypes.push({\n interfaces,\n kind: 'Union',\n name,\n types: possibleTypes,\n })\n }\n\n const references = refs.length > 0 ? refs : undefined\n const inlineObjects = inlineObjs.length > 0 ? inlineObjs : undefined\n\n const unionDefinition = isReference(parent)\n ? {references, type: name}\n : {inlineObjects, references, type: name}\n\n unionDefinitionCache.set(unionCacheKey, unionDefinition)\n return unionDefinition\n } finally {\n unionRecursionGuards.delete(guardPathName)\n }\n }\n\n function getDocumentDefinition(def: ObjectSchemaType) {\n const objectDef = getObjectDefinition(def)\n const fields = [...getDocumentInterfaceFields(def), ...objectDef.fields]\n\n return {...objectDef, fields, interfaces: ['Document']}\n }\n\n function getDocumentInterfaceDefinition(): ConvertedInterface {\n return {\n description: 'A Sanity document',\n fields: getDocumentInterfaceFields(),\n kind: 'Interface',\n name: 'Document',\n }\n }\n\n function getDocumentInterfaceFields(type?: ObjectSchemaType): ConvertedFieldDefinition[] {\n const isNullable = typeof nonNullDocumentFields === 'boolean' ? !nonNullDocumentFields : true\n return [\n {\n description: 'Document ID',\n fieldName: '_id',\n isNullable,\n type: 'ID',\n ...getDeprecation(type),\n },\n {\n description: 'Document type',\n fieldName: '_type',\n isNullable,\n type: 'String',\n ...getDeprecation(type),\n },\n {\n description: 'Date the document was created',\n fieldName: '_createdAt',\n isNullable,\n type: 'Datetime',\n ...getDeprecation(type),\n },\n {\n description: 'Date the document was last modified',\n fieldName: '_updatedAt',\n isNullable,\n type: 'Datetime',\n ...getDeprecation(type),\n },\n {\n description: 'Current document revision',\n fieldName: '_rev',\n isNullable,\n type: 'String',\n ...getDeprecation(type),\n },\n ]\n }\n\n function arrayify(thing: unknown) {\n if (Array.isArray(thing)) {\n return thing\n }\n\n return thing === null || thing === undefined ? [] : [thing]\n }\n\n function hasValidationFlag(\n field: ObjectField | ObjectFieldType | SchemaType,\n flag: string,\n ): boolean {\n return (\n 'validation' in field &&\n Array.isArray(field.validation) &&\n field.validation.some(\n (rule) => rule && '_rules' in rule && rule._rules.some((item) => item.flag === flag),\n )\n )\n }\n\n function getDescription(type: ObjectField | SchemaType): string | undefined {\n const description = type.type && type.type.description\n return typeof description === 'string' ? description : undefined\n }\n\n function gatherAllReferenceCandidates(type: SchemaType): ObjectSchemaType[] {\n const allFields = gatherReferenceCandidates(type)\n return uniqBy(allFields, 'name')\n }\n\n function gatherReferenceCandidates(type: SchemaType): ObjectSchemaType[] {\n const refTo = 'to' in type ? type.to : []\n return 'type' in type && type.type ? [...gatherReferenceCandidates(type.type), ...refTo] : refTo\n }\n\n function gatherAllFields(type: ObjectField | SchemaType) {\n const allFields = gatherFields(type)\n return uniqBy(allFields, 'name')\n }\n\n function gatherFields(type: ObjectField | SchemaType): ObjectField[] {\n if ('fields' in type) {\n return type.type ? [...gatherFields(type.type), ...type.fields] : type.fields\n }\n\n return []\n }\n\n function hasFieldsLikeShape(type: unknown): type is {fields: unknown} {\n return typeof type === 'object' && type !== null && 'fields' in type\n }\n\n function hasArrayOfFields(type: unknown): type is {fields: ObjectField[]} {\n return hasFieldsLikeShape(type) && Array.isArray(type.fields)\n }\n\n function hasFields(type: ObjectField | SchemaType): boolean {\n if (hasArrayOfFields(type)) {\n return gatherAllFields(type).length > 0\n }\n\n return 'type' in type && type.type ? hasFields(type.type) : false\n }\n}\n\nfunction createLiftTypeArrayError(\n index: number,\n parent: string,\n inlineType = 'object',\n grandParent = '',\n) {\n const helpUrl = generateHelpUrl(SCHEMA_LIFT_ANONYMOUS_OBJECT_TYPE)\n const context = [grandParent, parent].filter(Boolean).join('/')\n return new HelpfulError(\n oneline`\n Encountered anonymous inline ${inlineType} at index ${index} for type/field ${context}.\n To use this type with GraphQL you will need to create a top-level schema type for it.\n See ${helpUrl}`,\n helpUrl,\n )\n}\n\nfunction createLiftTypeError(typeName: string, parent: string, inlineType = 'object') {\n const helpUrl = generateHelpUrl(SCHEMA_LIFT_ANONYMOUS_OBJECT_TYPE)\n return new HelpfulError(\n oneline`\n Encountered anonymous inline ${inlineType} \"${typeName}\" for field/type \"${parent}\".\n To use this field with GraphQL you will need to create a top-level schema type for it.\n See ${helpUrl}`,\n helpUrl,\n )\n}\n\nclass HelpfulError extends Error {\n helpUrl?: string\n\n constructor(message: string, helpUrl?: string) {\n super(message)\n this.name = 'HelpfulError'\n this.helpUrl = helpUrl\n }\n}\n\nfunction getDeprecation(type?: ObjectField | ObjectFieldType | SchemaType): Partial<Deprecation> {\n return isDeprecationConfiguration(type)\n ? {\n deprecationReason: type.deprecated.reason,\n }\n : {}\n}\n"],"names":["generateHelpUrl","Schema","isDeprecationConfiguration","startCase","uniqBy","oneline","SCHEMA_LIFT_ANONYMOUS_OBJECT_TYPE","SchemaError","skipTypes","Set","allowedJsonTypes","disallowedCustomizedMembers","disabledBlockFields","scalars","getBaseType","baseSchema","typeName","compile","parent","types","name","to","type","get","options","hotspot","getTypeName","str","replaceAll","isBaseType","jsonType","has","isReference","isBlockType","typeDef","hasBlockParent","Boolean","isArrayOfBlocks","of","some","item","isType","isCrossDatasetReference","getCrossDatasetReferenceMetadata","getTypeNames","map","t","filter","getDataset","dataset","typeNames","extractFromSanitySchema","sanitySchema","extractOptions","nonNullDocumentFields","withUnionCache","unionRecursionGuards","unionDefinitionCache","Map","hasErrors","_validation","group","problems","problem","severity","Array","isArray","sanityTypes","_original","unionTypes","schemaType","undefined","convertedType","convertType","push","withUnions","interfaces","getDocumentInterfaceDefinition","isTopLevelType","includes","mapFieldType","field","Error","isScalar","hasValidationFlag","isArrayType","_convertType","getReferenceDefinition","getArrayDefinition","getDocumentDefinition","getObjectDefinition","hasFields","description","getDescription","props","mapped","isField","fieldName","gqlName","originalName","original","crossDatasetReferenceMetadata","getDeprecation","def","isInline","isDocument","actualType","typeNeedsHoisting","createLiftTypeError","fields","collectFields","firstUnprefixed","Math","max","findIndex","keyField","createStringField","splice","objectIsBlock","objectFields","_internal","buildRawField","kind","parentName","isRawAlias","gatherAllFields","length","extended","base","candidates","arrayify","gatherAllReferenceCandidates","allTypeNames","c","targetTypes","toSorted","join","children","getArrayChildDefinition","getUnionDefinition","grandParent","child","arrayDef","isCustomized","guardPathName","unionCacheKey","add","i","entries","createLiftTypeArrayError","converted","getName","flattened","reduce","acc","candidate","union","find","concat","allCandidatesAreDocuments","refs","inlineObjs","possibleTypes","references","inlineObjects","unionDefinition","set","delete","objectDef","getDocumentInterfaceFields","isNullable","thing","flag","validation","rule","_rules","allFields","gatherReferenceCandidates","refTo","gatherFields","hasFieldsLikeShape","hasArrayOfFields","index","inlineType","helpUrl","context","HelpfulError","message","deprecationReason","deprecated","reason"],"mappings":"AAAA,sDAAsD,GACtD,SAAQA,eAAe,QAAO,4BAA2B;AACzD,SAAQC,MAAM,QAAO,iBAAgB;AACrC,SAKEC,0BAA0B,QAMrB,gBAAe;AACtB,OAAOC,eAAe,yBAAwB;AAC9C,OAAOC,YAAY,sBAAqB;AACxC,SAAQC,OAAO,QAAO,UAAS;AAE/B,SAAQC,iCAAiC,QAAO,gBAAe;AAC/D,SAAQC,WAAW,QAAO,mBAAkB;AAU5C,MAAMC,YAAY,IAAIC,IAAI;IAAC;IAAY;CAAY;AACnD,MAAMC,mBAAmB,IAAID,IAAI;IAAC;IAAS;CAAS;AACpD,MAAME,8BAA8B,IAAIF,IAAI;IAAC;IAAS;IAAS;IAAQ;IAAS;CAAS;AACzF,MAAMG,sBAAsB,IAAIH,IAAI;IAAC;CAAW;AAChD,MAAMI,UAAU,IAAIJ,IAAI;IAAC;IAAW;IAAU;CAAS;AAEvD,SAASK,YAAYC,UAA0B,EAAEC,QAA2B;IAC1E,IAAIA,aAAa,yBAAyB;QACxC,OAAOf,OAAOgB,OAAO,CAAC;YACpBC,QAAQH;YACRI,OAAO;gBACL;oBACEC,MAAM,CAAC,eAAe,CAAC;oBACvB,0DAA0D;oBAC1DC,IAAI;wBAAC;4BAACC,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AC7C,KAAK,CAACG;QACN,IAAI,CAACvK,IAAI,GAAG;QACZ,IAAI,CAACoK,OAAO,GAAGA;IACjB;AACF;AAEA,SAASlF,eAAehF,IAAiD;IACvE,OAAOpB,2BAA2BoB,QAC9B;QACEsK,mBAAmBtK,KAAKuK,UAAU,CAACC,MAAM;IAC3C,IACA,CAAC;AACP"}
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/graphql/extractFromSanitySchema.ts"],"sourcesContent":["/* eslint-disable unicorn-js/consistent-function-scoping */\nimport {generateHelpUrl} from '@sanity/generate-help-url'\nimport {Schema} from '@sanity/schema'\nimport {\n type ArraySchemaType,\n type Schema as CompiledSchema,\n type CrossDatasetReferenceSchemaType,\n type IntrinsicTypeName,\n isDeprecationConfiguration,\n type ObjectField,\n type ObjectFieldType,\n type ObjectSchemaType,\n type ReferenceSchemaType,\n type SchemaType,\n} from '@sanity/types'\nimport startCase from 'lodash-es/startCase.js'\nimport uniqBy from 'lodash-es/uniqBy.js'\nimport {oneline} from 'oneline'\n\nimport {SCHEMA_LIFT_ANONYMOUS_OBJECT_TYPE} from './helpUrls.js'\nimport {SchemaError} from './SchemaError.js'\nimport {\n type ApiSpecification,\n type ConvertedFieldDefinition,\n type ConvertedInterface,\n type ConvertedType,\n type ConvertedUnion,\n type Deprecation,\n} from './types.js'\n\nconst skipTypes = new Set(['document', 'reference'])\nconst allowedJsonTypes = new Set(['array', 'object'])\nconst disallowedCustomizedMembers = new Set(['array', 'block', 'file', 'image', 'object'])\nconst disabledBlockFields = new Set(['markDefs'])\nconst scalars = new Set(['boolean', 'number', 'string'])\n\nfunction getBaseType(baseSchema: CompiledSchema, typeName: IntrinsicTypeName): SchemaType {\n if (typeName === 'crossDatasetReference') {\n return Schema.compile({\n parent: baseSchema,\n types: [\n {\n name: `__placeholder__`,\n // Just needs _something_ to refer to, doesn't matter what\n to: [{type: 'sanity.imageAsset'}],\n type: 'crossDatasetReference',\n },\n ],\n }).get('__placeholder__')\n }\n if (typeName === 'globalDocumentReference') {\n return Schema.compile({\n parent: baseSchema,\n types: [\n {\n name: `__placeholder__`,\n // Just needs _something_ to refer to, doesn't matter what\n to: [{type: 'sanity.imageAsset'}],\n type: 'globalDocumentReference',\n },\n ],\n }).get('__placeholder__')\n }\n\n return Schema.compile({\n parent: baseSchema,\n types: [{name: `__placeholder__`, options: {hotspot: true}, type: typeName}],\n }).get('__placeholder__')\n}\n\nfunction getTypeName(str: string): string {\n const name = startCase(str).replaceAll(/\\s+/g, '')\n return name === 'Number' ? 'Float' : name\n}\n\nfunction isBaseType(type: SchemaType): boolean {\n return (\n type.name !== type.jsonType &&\n allowedJsonTypes.has(type.jsonType) &&\n !skipTypes.has(type.name) &&\n !isReference(type)\n )\n}\n\nfunction isBlockType(typeDef: ObjectField | SchemaType): boolean {\n if (typeDef.name === 'block') {\n return true\n }\n\n if (typeDef.type) {\n return isBlockType(typeDef.type)\n }\n\n return false\n}\n\nfunction hasBlockParent(typeDef: SchemaType): boolean {\n if (typeDef.type && typeDef.type.name === 'block' && !typeDef.type.type) {\n return true\n }\n\n return Boolean(typeDef.type && hasBlockParent(typeDef.type))\n}\n\nfunction isArrayOfBlocks(typeDef: ObjectField | SchemaType): boolean {\n const type = typeDef.type || typeDef\n if (!('jsonType' in type) || type.jsonType !== 'array') {\n return false\n }\n\n return (type.of || []).some((item) => hasBlockParent(item))\n}\n\nfunction isType(typeDef: ObjectField | ObjectFieldType | SchemaType, typeName: string): boolean {\n let type: ObjectField | ObjectFieldType | SchemaType | undefined = typeDef\n while (type) {\n if (type.name === typeName || (type.type && type.type.name === typeName)) {\n return true\n }\n\n type = type.type\n }\n return false\n}\n\nfunction isReference(\n typeDef: ObjectField | ObjectFieldType | SchemaType,\n): typeDef is ReferenceSchemaType {\n return isType(typeDef, 'reference')\n}\n\nfunction isCrossDatasetReference(\n typeDef: CrossDatasetReferenceSchemaType | ObjectField | ObjectFieldType | SchemaType,\n) {\n return isType(typeDef, 'crossDatasetReference')\n}\n\nfunction getCrossDatasetReferenceMetadata(\n typeDef: CrossDatasetReferenceSchemaType | ObjectField | ObjectFieldType | SchemaType,\n) {\n if (!isCrossDatasetReference(typeDef)) return\n\n function getTypeNames(\n type: CrossDatasetReferenceSchemaType | ObjectField | ObjectFieldType | SchemaType | undefined,\n ) {\n if (!type) return\n if (!('to' in type)) return getTypeNames(type.type)\n return type.to.map((t) => t.type).filter((t): t is string => typeof t === 'string')\n }\n\n function getDataset(\n type: CrossDatasetReferenceSchemaType | ObjectField | ObjectFieldType | SchemaType | undefined,\n ) {\n if (!type) return\n if ('dataset' in type && typeof type.dataset === 'string') return type.dataset\n if (type.type) return getDataset(type.type)\n }\n\n const typeNames = getTypeNames(typeDef)\n if (!typeNames) return\n\n const dataset = getDataset(typeDef)\n if (typeof dataset !== 'string') return\n\n return {dataset, typeNames}\n}\n\nexport function extractFromSanitySchema(\n sanitySchema: CompiledSchema,\n extractOptions: {nonNullDocumentFields?: boolean; withUnionCache?: boolean} = {},\n): ApiSpecification {\n const {nonNullDocumentFields, withUnionCache} = extractOptions\n const unionRecursionGuards = new Set<string>()\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const unionDefinitionCache = new Map<string, any>()\n const hasErrors =\n sanitySchema._validation &&\n sanitySchema._validation.some((group) =>\n group.problems.some((problem) => problem.severity === 'error'),\n )\n\n if (hasErrors && Array.isArray(sanitySchema._validation)) {\n throw new SchemaError(sanitySchema._validation)\n }\n\n const sanityTypes = sanitySchema._original?.types || []\n const typeNames = sanitySchema.getTypeNames()\n const unionTypes: ConvertedUnion[] = []\n const types: ConvertedType[] = []\n\n for (const typeName of typeNames) {\n const schemaType = sanitySchema.get(typeName)\n if (schemaType === undefined) {\n continue\n }\n if (!isBaseType(schemaType)) {\n continue\n }\n\n const convertedType = convertType(schemaType)\n types.push(convertedType)\n }\n\n const withUnions = [...types, ...unionTypes]\n return {interfaces: [getDocumentInterfaceDefinition()], types: withUnions}\n\n function isTopLevelType(typeName: string): boolean {\n return typeNames.includes(typeName)\n }\n\n function mapFieldType(field: ObjectField | ObjectFieldType | SchemaType): string {\n if (!field.type) {\n throw new Error('Field has no type!')\n }\n\n const jsonType = 'jsonType' in field ? field.jsonType : ''\n const isScalar = scalars.has(jsonType)\n if (isScalar && jsonType === 'number') {\n return hasValidationFlag(field, 'integer') ? 'Int' : 'Float'\n } else if (isScalar) {\n return getTypeName(jsonType)\n }\n\n const type = field.type.type || field.type\n\n // In the case of nested scalars, recurse (markdown -> longText -> text -> string)\n if (type.type) {\n return mapFieldType(type)\n }\n\n switch (type.name) {\n case 'number': {\n return hasValidationFlag(field, 'integer') ? 'Int' : 'Float'\n }\n default: {\n return getTypeName(type.name)\n }\n }\n }\n\n function isArrayType(type: ObjectField | SchemaType): type is ArraySchemaType {\n return Boolean(\n ('jsonType' in type && type.jsonType === 'array') ||\n (type.type && type.type.jsonType === 'array'),\n )\n }\n\n function _convertType(\n type: ObjectField | SchemaType,\n parent: string,\n options: {isField?: boolean},\n ): ConvertedType {\n let name: string | undefined\n if (type.type) {\n name = type.type.name\n } else if ('jsonType' in type) {\n name = type.jsonType\n }\n\n if (isReference(type)) {\n return getReferenceDefinition(type)\n }\n\n if (isArrayType(type)) {\n return getArrayDefinition(type, parent, options)\n }\n\n if (name === 'document') {\n return getDocumentDefinition(type as ObjectSchemaType)\n }\n\n if (name === 'block' || name === 'object') {\n return getObjectDefinition(type, parent)\n }\n\n if (hasFields(type)) {\n return getObjectDefinition(type, parent)\n }\n\n return {\n description: getDescription(type),\n type: mapFieldType(type),\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any\n }\n\n function convertType(\n type: ObjectField | SchemaType,\n parent?: string,\n props: Partial<Deprecation> & {fieldName?: string} = {},\n ): ConvertedType {\n const mapped = _convertType(type, parent || '', {isField: Boolean(props.fieldName)})\n const gqlName = props.fieldName || mapped.name\n const originalName = type.name\n const original = gqlName === originalName ? {} : {originalName: originalName}\n const crossDatasetReferenceMetadata = getCrossDatasetReferenceMetadata(type)\n\n return {\n ...getDeprecation(type.type),\n ...props,\n ...mapped,\n ...original,\n ...(crossDatasetReferenceMetadata && {crossDatasetReferenceMetadata}),\n }\n }\n\n function isField(def: ObjectField | SchemaType): def is ObjectField {\n return !('jsonType' in def) || !def.jsonType\n }\n\n function getObjectDefinition(def: ObjectField | SchemaType, parent?: string): ConvertedType {\n const isInline = isField(def)\n const isDocument = def.type ? def.type.name === 'document' : false\n const actualType = isInline ? def.type : def\n\n if (typeNeedsHoisting(actualType)) {\n throw createLiftTypeError(def.name, parent || '', actualType.name)\n }\n\n if (isInline && parent && def.type.name === 'object') {\n throw createLiftTypeError(def.name, parent)\n }\n\n if (parent && def.type && isTopLevelType(def.type.name)) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return {type: getTypeName(def.type.name)} as any\n }\n\n const name = `${parent || ''}${getTypeName(def.name)}`\n const fields = collectFields(def)\n const firstUnprefixed = Math.max(\n 0,\n fields.findIndex((field) => field.name[0] !== '_'),\n )\n\n const keyField = createStringField('_key')\n\n fields.splice(firstUnprefixed, 0, keyField)\n\n if (!isDocument) {\n fields.splice(firstUnprefixed + 1, 0, createStringField('_type'))\n }\n\n const objectIsBlock = isBlockType(def)\n const objectFields = objectIsBlock\n ? fields.filter((field) => !disabledBlockFields.has(field.name))\n : fields\n\n return {\n _internal: {\n ...getDeprecation(def),\n },\n description: getDescription(def),\n fields: objectFields.map((field) =>\n isArrayOfBlocks(field)\n ? buildRawField(field, name)\n : (convertType(field, name, {\n fieldName: field.name,\n ...getDeprecation(def),\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n }) as any),\n ),\n kind: 'Type',\n name,\n type: 'Object',\n }\n }\n\n function buildRawField(field: ObjectField, parentName: string) {\n return {\n ...convertType(field, parentName, {fieldName: `${field.name}Raw`}),\n isRawAlias: true,\n type: 'JSON',\n }\n }\n\n function createStringField(name: string): ObjectField {\n return {\n name,\n type: {\n jsonType: 'string',\n name: 'string',\n type: {jsonType: 'string', name: 'string', type: undefined},\n },\n }\n }\n\n function collectFields(def: ObjectField | SchemaType) {\n const fields = gatherAllFields(def)\n if (fields.length > 0) {\n return fields\n }\n\n const extended = getBaseType(sanitySchema, def.name as IntrinsicTypeName)\n return gatherAllFields(extended)\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n function getReferenceDefinition(def: SchemaType): any {\n const base = {description: getDescription(def), isReference: true}\n const candidates = arrayify(gatherAllReferenceCandidates(def))\n if (candidates.length === 0) {\n throw new Error('No candidates for reference')\n }\n\n if (candidates.length === 1) {\n return {type: getTypeName(candidates[0].type.name), ...base}\n }\n\n const allTypeNames = candidates.map((c) => getTypeName(c.type.name))\n const targetTypes = [...new Set(allTypeNames)].toSorted()\n const name = targetTypes.join('Or')\n\n // Register the union type if we haven't seen it before\n if (!unionTypes.some((item) => item.name === name)) {\n unionTypes.push({\n kind: 'Union',\n name,\n types: targetTypes,\n })\n }\n\n return {\n type: name,\n ...base,\n }\n }\n\n function getArrayDefinition(\n def: ArraySchemaType,\n parent: string,\n options: {isField?: boolean} = {},\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): any {\n const base = {description: getDescription(def), kind: 'List'}\n const name = !options.isField && def.name ? {name: getTypeName(def.name)} : {}\n const candidates = def.type?.type && 'of' in def.type ? arrayify(def.type.of) : def.of\n\n return candidates.length === 1\n ? {\n children: getArrayChildDefinition(candidates[0], def),\n ...base,\n ...name,\n }\n : {\n children: getUnionDefinition(candidates, def, {grandParent: parent}),\n ...base,\n ...name,\n }\n }\n\n function getArrayChildDefinition(child: SchemaType, arrayDef: SchemaType) {\n if (typeNeedsHoisting(child)) {\n // Seems to be inline? Should be hoisted?\n throw createLiftTypeError(child.name, arrayDef.name)\n }\n\n if (isReference(child)) {\n return getReferenceDefinition(child)\n }\n\n // In the case of nested scalars, recurse (markdown -> longText -> text -> string)\n if (scalars.has(child.jsonType) && !scalars.has(child.name)) {\n return {type: mapFieldType(child)}\n }\n\n return {type: getTypeName(child.name)}\n }\n\n function typeNeedsHoisting(type: SchemaType & {isCustomized?: boolean}): boolean {\n if (type.name === 'object') {\n return true\n }\n\n if (type.jsonType === 'object' && !isTopLevelType(type.name)) {\n return true\n }\n\n if (type.isCustomized && !isTopLevelType(type.name)) {\n return true\n }\n\n if (type.isCustomized && disallowedCustomizedMembers.has(type.name)) {\n return true\n }\n\n return false\n }\n\n function getUnionDefinition(\n candidates: ObjectSchemaType[],\n parent: SchemaType,\n options: {grandParent?: string} = {},\n ) {\n if (candidates.length < 2) {\n throw new Error('Not enough candidates for a union type')\n }\n\n // #1482: When creating union definition do not get caught in recursion loop\n // for types that reference themselves\n const guardPathName = `${typeof parent === 'object' ? parent.name : parent}`\n if (unionRecursionGuards.has(guardPathName)) {\n return {}\n }\n\n const unionCacheKey = `${options.grandParent}-${guardPathName}-${candidates\n .map((c) => c.type?.name)\n .join('-')}`\n if (withUnionCache && unionDefinitionCache.has(unionCacheKey)) {\n return unionDefinitionCache.get(unionCacheKey)\n }\n\n try {\n unionRecursionGuards.add(guardPathName)\n\n for (const [i, def] of candidates.entries()) {\n if (typeNeedsHoisting(def)) {\n throw createLiftTypeArrayError(\n i,\n parent.name,\n def.type ? def.type.name : def.name,\n options.grandParent,\n )\n }\n }\n\n const converted = candidates.map((def) => convertType(def))\n\n const getName = (def: {type: string | {name: string}}): string =>\n typeof def.type === 'string' ? def.type : def.type.name\n\n // We might end up with union types being returned - these needs to be flattened\n // so that an ImageOr(PersonOrPet) becomes ImageOrPersonOrPet\n // eslint-disable-next-line unicorn/no-array-reduce\n const flattened = converted.reduce(\n (acc, candidate) => {\n const union = unionTypes.find((item) => item.name === candidate.type)\n return union\n ? // eslint-disable-next-line unicorn/prefer-spread\n acc.concat(union.types.map((type) => ({isReference: candidate.isReference, type})))\n : [...acc, candidate]\n },\n [] as {isReference?: boolean; name?: string; type: string | {name: string}}[],\n )\n\n let allCandidatesAreDocuments = true\n const refs: (string | {name: string})[] = []\n const inlineObjs: string[] = []\n const allTypeNames: string[] = []\n for (const def of flattened) {\n if (def.isReference) {\n refs.push(def.type)\n }\n if (!isReference) {\n inlineObjs.push(def.name || '')\n }\n\n const typeName = typeof def.type === 'string' ? def.type : def.type.name\n\n // Here we remove duplicates, as they might appear twice due to in-line usage of types as well as references\n if (def.name || def.type) {\n allTypeNames.push(def.isReference ? typeName : def.name || '')\n }\n\n const typeDef = sanityTypes.find((type) => type.name === getName(def))\n if (!typeDef || typeDef.type !== 'document') {\n allCandidatesAreDocuments = false\n }\n }\n\n const interfaces = allCandidatesAreDocuments ? ['Document'] : undefined\n const possibleTypes = [...new Set(allTypeNames)].toSorted()\n\n if (possibleTypes.length < 2) {\n throw new Error(`Not enough types for a union type. Parent: ${parent.name}`)\n }\n\n const name = possibleTypes.join('Or')\n\n if (!unionTypes.some((item) => item.name === name)) {\n unionTypes.push({\n interfaces,\n kind: 'Union',\n name,\n types: possibleTypes,\n })\n }\n\n const references = refs.length > 0 ? refs : undefined\n const inlineObjects = inlineObjs.length > 0 ? inlineObjs : undefined\n\n const unionDefinition = isReference(parent)\n ? {references, type: name}\n : {inlineObjects, references, type: name}\n\n unionDefinitionCache.set(unionCacheKey, unionDefinition)\n return unionDefinition\n } finally {\n unionRecursionGuards.delete(guardPathName)\n }\n }\n\n function getDocumentDefinition(def: ObjectSchemaType) {\n const objectDef = getObjectDefinition(def)\n const fields = [...getDocumentInterfaceFields(def), ...objectDef.fields]\n\n return {...objectDef, fields, interfaces: ['Document']}\n }\n\n function getDocumentInterfaceDefinition(): ConvertedInterface {\n return {\n description: 'A Sanity document',\n fields: getDocumentInterfaceFields(),\n kind: 'Interface',\n name: 'Document',\n }\n }\n\n function getDocumentInterfaceFields(type?: ObjectSchemaType): ConvertedFieldDefinition[] {\n const isNullable = typeof nonNullDocumentFields === 'boolean' ? !nonNullDocumentFields : true\n return [\n {\n description: 'Document ID',\n fieldName: '_id',\n isNullable,\n type: 'ID',\n ...getDeprecation(type),\n },\n {\n description: 'Document type',\n fieldName: '_type',\n isNullable,\n type: 'String',\n ...getDeprecation(type),\n },\n {\n description: 'Date the document was created',\n fieldName: '_createdAt',\n isNullable,\n type: 'Datetime',\n ...getDeprecation(type),\n },\n {\n description: 'Date the document was last modified',\n fieldName: '_updatedAt',\n isNullable,\n type: 'Datetime',\n ...getDeprecation(type),\n },\n {\n description: 'Current document revision',\n fieldName: '_rev',\n isNullable,\n type: 'String',\n ...getDeprecation(type),\n },\n ]\n }\n\n function arrayify(thing: unknown) {\n if (Array.isArray(thing)) {\n return thing\n }\n\n return thing === null || thing === undefined ? [] : [thing]\n }\n\n function hasValidationFlag(\n field: ObjectField | ObjectFieldType | SchemaType,\n flag: string,\n ): boolean {\n return (\n 'validation' in field &&\n Array.isArray(field.validation) &&\n field.validation.some(\n (rule) => rule && '_rules' in rule && rule._rules.some((item) => item.flag === flag),\n )\n )\n }\n\n function getDescription(type: ObjectField | SchemaType): string | undefined {\n const description = type.type && type.type.description\n return typeof description === 'string' ? description : undefined\n }\n\n function gatherAllReferenceCandidates(type: SchemaType): ObjectSchemaType[] {\n const allFields = gatherReferenceCandidates(type)\n return uniqBy(allFields, 'name')\n }\n\n function gatherReferenceCandidates(type: SchemaType): ObjectSchemaType[] {\n const refTo = 'to' in type ? type.to : []\n return 'type' in type && type.type ? [...gatherReferenceCandidates(type.type), ...refTo] : refTo\n }\n\n function gatherAllFields(type: ObjectField | SchemaType) {\n const allFields = gatherFields(type)\n return uniqBy(allFields, 'name')\n }\n\n function gatherFields(type: ObjectField | SchemaType): ObjectField[] {\n if ('fields' in type) {\n return type.type ? [...gatherFields(type.type), ...type.fields] : type.fields\n }\n\n return []\n }\n\n function hasFieldsLikeShape(type: unknown): type is {fields: unknown} {\n return typeof type === 'object' && type !== null && 'fields' in type\n }\n\n function hasArrayOfFields(type: unknown): type is {fields: ObjectField[]} {\n return hasFieldsLikeShape(type) && Array.isArray(type.fields)\n }\n\n function hasFields(type: ObjectField | SchemaType): boolean {\n if (hasArrayOfFields(type)) {\n return gatherAllFields(type).length > 0\n }\n\n return 'type' in type && type.type ? hasFields(type.type) : false\n }\n}\n\nfunction createLiftTypeArrayError(\n index: number,\n parent: string,\n inlineType = 'object',\n grandParent = '',\n) {\n const helpUrl = generateHelpUrl(SCHEMA_LIFT_ANONYMOUS_OBJECT_TYPE)\n const context = [grandParent, parent].filter(Boolean).join('/')\n return new HelpfulError(\n oneline`\n Encountered anonymous inline ${inlineType} at index ${index} for type/field ${context}.\n To use this type with GraphQL you will need to create a top-level schema type for it.\n See ${helpUrl}`,\n helpUrl,\n )\n}\n\nfunction createLiftTypeError(typeName: string, parent: string, inlineType = 'object') {\n const helpUrl = generateHelpUrl(SCHEMA_LIFT_ANONYMOUS_OBJECT_TYPE)\n return new HelpfulError(\n oneline`\n Encountered anonymous inline ${inlineType} \"${typeName}\" for field/type \"${parent}\".\n To use this field with GraphQL you will need to create a top-level schema type for it.\n See ${helpUrl}`,\n helpUrl,\n )\n}\n\nclass HelpfulError extends Error {\n helpUrl?: string\n\n constructor(message: string, helpUrl?: string) {\n super(message)\n this.name = 'HelpfulError'\n this.helpUrl = helpUrl\n }\n}\n\nfunction getDeprecation(type?: ObjectField | ObjectFieldType | SchemaType): Partial<Deprecation> {\n return isDeprecationConfiguration(type)\n ? {\n deprecationReason: type.deprecated.reason,\n }\n : {}\n}\n"],"names":["generateHelpUrl","Schema","isDeprecationConfiguration","startCase","uniqBy","oneline","SCHEMA_LIFT_ANONYMOUS_OBJECT_TYPE","SchemaError","skipTypes","Set","allowedJsonTypes","disallowedCustomizedMembers","disabledBlockFields","scalars","getBaseType","baseSchema","typeName","compile","parent","types","name","to","type","get","options","hotspot","getTypeName","str","replaceAll","isBaseType","jsonType","has","isReference","isBlockType","typeDef","hasBlockParent","Boolean","isArrayOfBlocks","of","some","item","isType","isCrossDatasetReference","getCrossDatasetReferenceMetadata","getTypeNames","map","t","filter","getDataset","dataset","typeNames","extractFromSanitySchema","sanitySchema","extractOptions","nonNullDocumentFields","withUnionCache","unionRecursionGuards","unionDefinitionCache","Map","hasErrors","_validation","group","problems","problem","severity","Array","isArray","sanityTypes","_original","unionTypes","schemaType","undefined","convertedType","convertType","push","withUnions","interfaces","getDocumentInterfaceDefinition","isTopLevelType","includes","mapFieldType","field","Error","isScalar","hasValidationFlag","isArrayType","_convertType","getReferenceDefinition","getArrayDefinition","getDocumentDefinition","getObjectDefinition","hasFields","description","getDescription","props","mapped","isField","fieldName","gqlName","originalName","original","crossDatasetReferenceMetadata","getDeprecation","def","isInline","isDocument","actualType","typeNeedsHoisting","createLiftTypeError","fields","collectFields","firstUnprefixed","Math","max","findIndex","keyField","createStringField","splice","objectIsBlock","objectFields","_internal","buildRawField","kind","parentName","isRawAlias","gatherAllFields","length","extended","base","candidates","arrayify","gatherAllReferenceCandidates","allTypeNames","c","targetTypes","toSorted","join","children","getArrayChildDefinition","getUnionDefinition","grandParent","child","arrayDef","isCustomized","guardPathName","unionCacheKey","add","i","entries","createLiftTypeArrayError","converted","getName","flattened","reduce","acc","candidate","union","find","concat","allCandidatesAreDocuments","refs","inlineObjs","possibleTypes","references","inlineObjects","unionDefinition","set","delete","objectDef","getDocumentInterfaceFields","isNullable","thing","flag","validation","rule","_rules","allFields","gatherReferenceCandidates","refTo","gatherFields","hasFieldsLikeShape","hasArrayOfFields","index","inlineType","helpUrl","context","HelpfulError","message","deprecationReason","deprecated","reason"],"mappings":"AAAA,yDAAyD,GACzD,SAAQA,eAAe,QAAO,4BAA2B;AACzD,SAAQC,MAAM,QAAO,iBAAgB;AACrC,SAKEC,0BAA0B,QAMrB,gBAAe;AACtB,OAAOC,eAAe,yBAAwB;AAC9C,OAAOC,YAAY,sBAAqB;AACxC,SAAQC,OAAO,QAAO,UAAS;AAE/B,SAAQC,iCAAiC,QAAO,gBAAe;AAC/D,SAAQC,WAAW,QAAO,mBAAkB;AAU5C,MAAMC,YAAY,IAAIC,IAAI;IAAC;IAAY;CAAY;AACnD,MAAMC,mBAAmB,IAAID,IAAI;IAAC;IAAS;CAAS;AACpD,MAAME,8BAA8B,IAAI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QAElF,EAAED,QAAQ,CAAC,EACfA;AAEJ;AAEA,SAAS5E,oBAAoB5F,QAAgB,EAAEE,MAAc,EAAEqK,aAAa,QAAQ;IAClF,MAAMC,UAAUxL,gBAAgBM;IAChC,OAAO,IAAIoL,aACTrL,OAAO,CAAC;iCACqB,EAAEkL,WAAW,EAAE,EAAEvK,SAAS,kBAAkB,EAAEE,OAAO;;QAE9E,EAAEsK,QAAQ,CAAC,EACfA;AAEJ;AAEA,MAAME,qBAAqBxG;IACzBsG,QAAgB;IAEhB,YAAYG,OAAe,EAAEH,OAAgB,CAAE;QAC7C,KAAK,CAACG;QACN,IAAI,CAACvK,IAAI,GAAG;QACZ,IAAI,CAACoK,OAAO,GAAGA;IACjB;AACF;AAEA,SAASlF,eAAehF,IAAiD;IACvE,OAAOpB,2BAA2BoB,QAC9B;QACEsK,mBAAmBtK,KAAKuK,UAAU,CAACC,MAAM;IAC3C,IACA,CAAC;AACP"}
|
|
@@ -60,7 +60,7 @@ export async function initStudio({ datasetName, defaults, displayName, isFirstPr
|
|
|
60
60
|
if (!token) {
|
|
61
61
|
throw new InitError('Authentication required to import dataset', 1);
|
|
62
62
|
}
|
|
63
|
-
// eslint-disable-next-line no-restricted-syntax
|
|
63
|
+
// eslint-disable-next-line eslint-js/no-restricted-syntax
|
|
64
64
|
const { ImportDatasetCommand } = await import('../../commands/datasets/import.js');
|
|
65
65
|
await ImportDatasetCommand.run([
|
|
66
66
|
resolvedTemplate.datasetUrl,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/init/initStudio.ts"],"sourcesContent":["import {styleText} from 'node:util'\n\nimport {getCliToken, type Output, subdebug, type TelemetryUserProperties} from '@sanity/cli-core'\nimport {confirm} from '@sanity/cli-core/ux'\nimport {type TelemetryTrace} from '@sanity/telemetry'\n\nimport {updateProjectInitializedAt} from '../../services/projects.js'\nimport {type InitStepResult} from '../../telemetry/init.telemetry.js'\nimport {getInstallCommand} from '../../util/packageManager/installPackages.js'\nimport {type PackageManager} from '../../util/packageManager/packageManagerChoice.js'\nimport {type EditorName} from '../mcp/editorConfigs.js'\nimport {InitError} from './initError.js'\nimport {getPostInitMCPPrompt} from './initHelpers.js'\nimport {type RepoInfo} from './remoteTemplate.js'\nimport {scaffoldAndInstall, selectTemplate} from './scaffoldTemplate.js'\nimport {type InitOptions} from './types.js'\n\nconst debug = subdebug('init')\n\nasync function promptForDatasetImport(message?: string): Promise<boolean> {\n return confirm({\n default: true,\n message: message || 'This template includes a sample dataset, would you like to use it?',\n })\n}\n\nexport async function initStudio({\n datasetName,\n defaults,\n displayName,\n isFirstProject,\n mcpConfigured,\n options,\n organizationId,\n output,\n outputPath,\n preclaim = false,\n projectId,\n remoteTemplateInfo,\n sluggedName,\n trace,\n workbench,\n workDir,\n}: {\n datasetName: string\n defaults: {projectName: string}\n displayName: string\n isFirstProject: boolean\n mcpConfigured: EditorName[]\n options: InitOptions\n organizationId: string | undefined\n output: Output\n outputPath: string\n preclaim?: boolean\n projectId: string\n remoteTemplateInfo: RepoInfo | undefined\n sluggedName: string\n trace: TelemetryTrace<TelemetryUserProperties, InitStepResult>\n workbench: boolean\n workDir: string\n}): Promise<void> {\n const {importDataset, install, unattended} = options\n const {\n template: resolvedTemplate,\n templateName,\n useTypeScript,\n } = await selectTemplate({\n options,\n remoteTemplateInfo,\n trace,\n })\n\n if (!remoteTemplateInfo && !resolvedTemplate) {\n throw new InitError(`Template \"${templateName}\" not found`, 1)\n }\n\n // If the template has a sample dataset, prompt the user whether or not we should import it\n const shouldImport =\n resolvedTemplate?.datasetUrl &&\n (importDataset ??\n (!unattended && (await promptForDatasetImport(resolvedTemplate.importPrompt))))\n\n trace.log({\n selectedOption: shouldImport ? 'yes' : 'no',\n step: 'importTemplateDataset',\n })\n\n if (!preclaim) {\n try {\n await updateProjectInitializedAt(projectId)\n } catch (err) {\n // Non-critical update\n debug('Failed to update cliInitializedAt metadata', err)\n }\n }\n\n const {pkgManager} = await scaffoldAndInstall({\n datasetName,\n defaults,\n displayName,\n options,\n organizationId,\n output,\n outputPath,\n projectId,\n remoteTemplateInfo,\n sluggedName,\n templateName,\n trace,\n useTypeScript,\n workbench,\n workDir,\n })\n\n // Prompt for dataset import (if a dataset is defined)\n if (shouldImport && resolvedTemplate?.datasetUrl) {\n const token = await getCliToken()\n if (!token) {\n throw new InitError('Authentication required to import dataset', 1)\n }\n // eslint-disable-next-line no-restricted-syntax\n const {ImportDatasetCommand} = await import('../../commands/datasets/import.js')\n await ImportDatasetCommand.run(\n [\n resolvedTemplate.datasetUrl,\n '--project',\n projectId,\n '--dataset',\n datasetName,\n '--token',\n token,\n '--missing',\n ],\n {\n root: outputPath,\n },\n )\n\n output.log('')\n output.log('If you want to delete the imported data, use')\n output.log(` ${styleText('cyan', `npx sanity dataset delete ${datasetName}`)}`)\n output.log('and create a new clean dataset with')\n output.log(` ${styleText('cyan', `npx sanity dataset create <name>`)}\\n`)\n }\n\n // `sanity new` owns the combined Studio/frontend outro.\n if (preclaim) return\n\n const devCommandMap: Record<PackageManager, string> = {\n bun: 'bun dev',\n manual: 'npm run dev',\n npm: 'npm run dev',\n pnpm: 'pnpm dev',\n yarn: 'yarn dev',\n }\n const devCommand = devCommandMap[pkgManager]\n\n const isCurrentDir = outputPath === workDir\n const goToProjectDir = `\\n(${styleText('cyan', `cd ${outputPath}`)} to navigate to your new project directory)`\n\n //output for Studios here\n output.log(`\\u2705 ${styleText(['green', 'bold'], 'Success!')} Your Studio has been created.`)\n if (!isCurrentDir) output.log(goToProjectDir)\n const startupCommands = install\n ? styleText('cyan', devCommand)\n : `${styleText('cyan', getInstallCommand(pkgManager))}, then ${styleText('cyan', devCommand)}`\n output.log(\n `\\nGet started by running ${startupCommands} to launch your Studio's development server`,\n )\n if (mcpConfigured && mcpConfigured.length > 0) {\n const message = await getPostInitMCPPrompt(mcpConfigured)\n output.log(`\\n${message}`)\n output.log(`\\nLearn more: ${styleText('cyan', 'https://mcp.sanity.io')}`)\n output.log(\n `\\nHave feedback? Tell us in the community: ${styleText('cyan', 'https://www.sanity.io/community/join')}`,\n )\n }\n output.log('\\n')\n output.log(`Other helpful commands:`)\n output.log(`npx sanity docs browse to open the documentation in a browser`)\n output.log(`npx sanity manage to open the project settings in a browser`)\n output.log(`npx sanity help to explore the CLI manual`)\n\n if (isFirstProject) {\n trace.log({selectedOption: 'yes', step: 'sendCommunityInvite'})\n\n const DISCORD_INVITE_LINK = 'https://www.sanity.io/community/join'\n\n output.log(`\\nJoin the Sanity community: ${styleText('cyan', DISCORD_INVITE_LINK)}`)\n output.log('We look forward to seeing you there!\\n')\n }\n}\n"],"names":["styleText","getCliToken","subdebug","confirm","updateProjectInitializedAt","getInstallCommand","InitError","getPostInitMCPPrompt","scaffoldAndInstall","selectTemplate","debug","promptForDatasetImport","message","default","initStudio","datasetName","defaults","displayName","isFirstProject","mcpConfigured","options","organizationId","output","outputPath","preclaim","projectId","remoteTemplateInfo","sluggedName","trace","workbench","workDir","importDataset","install","unattended","template","resolvedTemplate","templateName","useTypeScript","shouldImport","datasetUrl","importPrompt","log","selectedOption","step","err","pkgManager","token","ImportDatasetCommand","run","root","devCommandMap","bun","manual","npm","pnpm","yarn","devCommand","isCurrentDir","goToProjectDir","startupCommands","length","DISCORD_INVITE_LINK"],"mappings":"AAAA,SAAQA,SAAS,QAAO,YAAW;AAEnC,SAAQC,WAAW,EAAeC,QAAQ,QAAqC,mBAAkB;AACjG,SAAQC,OAAO,QAAO,sBAAqB;AAG3C,SAAQC,0BAA0B,QAAO,6BAA4B;AAErE,SAAQC,iBAAiB,QAAO,+CAA8C;AAG9E,SAAQC,SAAS,QAAO,iBAAgB;AACxC,SAAQC,oBAAoB,QAAO,mBAAkB;AAErD,SAAQC,kBAAkB,EAAEC,cAAc,QAAO,wBAAuB;AAGxE,MAAMC,QAAQR,SAAS;AAEvB,eAAeS,uBAAuBC,OAAgB;IACpD,OAAOT,QAAQ;QACbU,SAAS;QACTD,SAASA,WAAW;IACtB;AACF;AAEA,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BU,OAAOmB,GAAG,CAAC,CAAC,cAAc,EAAEzC,UAAU,QAAQ,0BAA0B;QACxEsB,OAAOmB,GAAG,CACR,CAAC,2CAA2C,EAAEzC,UAAU,QAAQ,yCAAyC;IAE7G;IACAsB,OAAOmB,GAAG,CAAC;IACXnB,OAAOmB,GAAG,CAAC,CAAC,uBAAuB,CAAC;IACpCnB,OAAOmB,GAAG,CAAC,CAAC,iEAAiE,CAAC;IAC9EnB,OAAOmB,GAAG,CAAC,CAAC,oEAAoE,CAAC;IACjFnB,OAAOmB,GAAG,CAAC,CAAC,oDAAoD,CAAC;IAEjE,IAAIvB,gBAAgB;QAClBU,MAAMa,GAAG,CAAC;YAACC,gBAAgB;YAAOC,MAAM;QAAqB;QAE7D,MAAMkB,sBAAsB;QAE5BvC,OAAOmB,GAAG,CAAC,CAAC,6BAA6B,EAAEzC,UAAU,QAAQ6D,sBAAsB;QACnFvC,OAAOmB,GAAG,CAAC;IACb;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/init/initStudio.ts"],"sourcesContent":["import {styleText} from 'node:util'\n\nimport {getCliToken, type Output, subdebug, type TelemetryUserProperties} from '@sanity/cli-core'\nimport {confirm} from '@sanity/cli-core/ux'\nimport {type TelemetryTrace} from '@sanity/telemetry'\n\nimport {updateProjectInitializedAt} from '../../services/projects.js'\nimport {type InitStepResult} from '../../telemetry/init.telemetry.js'\nimport {getInstallCommand} from '../../util/packageManager/installPackages.js'\nimport {type PackageManager} from '../../util/packageManager/packageManagerChoice.js'\nimport {type EditorName} from '../mcp/editorConfigs.js'\nimport {InitError} from './initError.js'\nimport {getPostInitMCPPrompt} from './initHelpers.js'\nimport {type RepoInfo} from './remoteTemplate.js'\nimport {scaffoldAndInstall, selectTemplate} from './scaffoldTemplate.js'\nimport {type InitOptions} from './types.js'\n\nconst debug = subdebug('init')\n\nasync function promptForDatasetImport(message?: string): Promise<boolean> {\n return confirm({\n default: true,\n message: message || 'This template includes a sample dataset, would you like to use it?',\n })\n}\n\nexport async function initStudio({\n datasetName,\n defaults,\n displayName,\n isFirstProject,\n mcpConfigured,\n options,\n organizationId,\n output,\n outputPath,\n preclaim = false,\n projectId,\n remoteTemplateInfo,\n sluggedName,\n trace,\n workbench,\n workDir,\n}: {\n datasetName: string\n defaults: {projectName: string}\n displayName: string\n isFirstProject: boolean\n mcpConfigured: EditorName[]\n options: InitOptions\n organizationId: string | undefined\n output: Output\n outputPath: string\n preclaim?: boolean\n projectId: string\n remoteTemplateInfo: RepoInfo | undefined\n sluggedName: string\n trace: TelemetryTrace<TelemetryUserProperties, InitStepResult>\n workbench: boolean\n workDir: string\n}): Promise<void> {\n const {importDataset, install, unattended} = options\n const {\n template: resolvedTemplate,\n templateName,\n useTypeScript,\n } = await selectTemplate({\n options,\n remoteTemplateInfo,\n trace,\n })\n\n if (!remoteTemplateInfo && !resolvedTemplate) {\n throw new InitError(`Template \"${templateName}\" not found`, 1)\n }\n\n // If the template has a sample dataset, prompt the user whether or not we should import it\n const shouldImport =\n resolvedTemplate?.datasetUrl &&\n (importDataset ??\n (!unattended && (await promptForDatasetImport(resolvedTemplate.importPrompt))))\n\n trace.log({\n selectedOption: shouldImport ? 'yes' : 'no',\n step: 'importTemplateDataset',\n })\n\n if (!preclaim) {\n try {\n await updateProjectInitializedAt(projectId)\n } catch (err) {\n // Non-critical update\n debug('Failed to update cliInitializedAt metadata', err)\n }\n }\n\n const {pkgManager} = await scaffoldAndInstall({\n datasetName,\n defaults,\n displayName,\n options,\n organizationId,\n output,\n outputPath,\n projectId,\n remoteTemplateInfo,\n sluggedName,\n templateName,\n trace,\n useTypeScript,\n workbench,\n workDir,\n })\n\n // Prompt for dataset import (if a dataset is defined)\n if (shouldImport && resolvedTemplate?.datasetUrl) {\n const token = await getCliToken()\n if (!token) {\n throw new InitError('Authentication required to import dataset', 1)\n }\n // eslint-disable-next-line eslint-js/no-restricted-syntax\n const {ImportDatasetCommand} = await import('../../commands/datasets/import.js')\n await ImportDatasetCommand.run(\n [\n resolvedTemplate.datasetUrl,\n '--project',\n projectId,\n '--dataset',\n datasetName,\n '--token',\n token,\n '--missing',\n ],\n {\n root: outputPath,\n },\n )\n\n output.log('')\n output.log('If you want to delete the imported data, use')\n output.log(` ${styleText('cyan', `npx sanity dataset delete ${datasetName}`)}`)\n output.log('and create a new clean dataset with')\n output.log(` ${styleText('cyan', `npx sanity dataset create <name>`)}\\n`)\n }\n\n // `sanity new` owns the combined Studio/frontend outro.\n if (preclaim) return\n\n const devCommandMap: Record<PackageManager, string> = {\n bun: 'bun dev',\n manual: 'npm run dev',\n npm: 'npm run dev',\n pnpm: 'pnpm dev',\n yarn: 'yarn dev',\n }\n const devCommand = devCommandMap[pkgManager]\n\n const isCurrentDir = outputPath === workDir\n const goToProjectDir = `\\n(${styleText('cyan', `cd ${outputPath}`)} to navigate to your new project directory)`\n\n //output for Studios here\n output.log(`\\u2705 ${styleText(['green', 'bold'], 'Success!')} Your Studio has been created.`)\n if (!isCurrentDir) output.log(goToProjectDir)\n const startupCommands = install\n ? styleText('cyan', devCommand)\n : `${styleText('cyan', getInstallCommand(pkgManager))}, then ${styleText('cyan', devCommand)}`\n output.log(\n `\\nGet started by running ${startupCommands} to launch your Studio's development server`,\n )\n if (mcpConfigured && mcpConfigured.length > 0) {\n const message = await getPostInitMCPPrompt(mcpConfigured)\n output.log(`\\n${message}`)\n output.log(`\\nLearn more: ${styleText('cyan', 'https://mcp.sanity.io')}`)\n output.log(\n `\\nHave feedback? Tell us in the community: ${styleText('cyan', 'https://www.sanity.io/community/join')}`,\n )\n }\n output.log('\\n')\n output.log(`Other helpful commands:`)\n output.log(`npx sanity docs browse to open the documentation in a browser`)\n output.log(`npx sanity manage to open the project settings in a browser`)\n output.log(`npx sanity help to explore the CLI manual`)\n\n if (isFirstProject) {\n trace.log({selectedOption: 'yes', step: 'sendCommunityInvite'})\n\n const DISCORD_INVITE_LINK = 'https://www.sanity.io/community/join'\n\n output.log(`\\nJoin the Sanity community: ${styleText('cyan', DISCORD_INVITE_LINK)}`)\n output.log('We look forward to seeing you there!\\n')\n }\n}\n"],"names":["styleText","getCliToken","subdebug","confirm","updateProjectInitializedAt","getInstallCommand","InitError","getPostInitMCPPrompt","scaffoldAndInstall","selectTemplate","debug","promptForDatasetImport","message","default","initStudio","datasetName","defaults","displayName","isFirstProject","mcpConfigured","options","organizationId","output","outputPath","preclaim","projectId","remoteTemplateInfo","sluggedName","trace","workbench","workDir","importDataset","install","unattended","template","resolvedTemplate","templateName","useTypeScript","shouldImport","datasetUrl","importPrompt","log","selectedOption","step","err","pkgManager","token","ImportDatasetCommand","run","root","devCommandMap","bun","manual","npm","pnpm","yarn","devCommand","isCurrentDir","goToProjectDir","startupCommands","length","DISCORD_INVITE_LINK"],"mappings":"AAAA,SAAQA,SAAS,QAAO,YAAW;AAEnC,SAAQC,WAAW,EAAeC,QAAQ,QAAqC,mBAAkB;AACjG,SAAQC,OAAO,QAAO,sBAAqB;AAG3C,SAAQC,0BAA0B,QAAO,6BAA4B;AAErE,SAAQC,iBAAiB,QAAO,+CAA8C;AAG9E,SAAQC,SAAS,QAAO,iBAAgB;AACxC,SAAQC,oBAAoB,QAAO,mBAAkB;AAErD,SAAQC,kBAAkB,EAAEC,cAAc,QAAO,wBAAuB;AAGxE,MAAMC,QAAQR,SAAS;AAEvB,eAAeS,uBAAuBC,OAAgB;IACpD,OAAOT,QAAQ;QACbU,SAAS;QACTD,SAASA,WAAW;IACtB;AACF;AAEA,OAAO,eAAeE,WAAW,EAC/BC,WAAW,EACXC,QAAQ,EACRC,WAAW,EACXC,cAAc,EACdC,aAAa,EACbC,OAAO,EACPC,cAAc,EACdC,MAAM,EACNC,UAAU,EACVC,WAAW,KAAK,EAChBC,SAAS,EACTC,kBAAkB,EAClBC,WAAW,EACXC,KAAK,EACLC,SAAS,EACTC,OAAO,EAkBR;IACC,MAAM,EAACC,aAAa,EAAEC,OAAO,EAAEC,UAAU,EAAC,GAAGb;IAC7C,MAAM,EACJc,UAAUC,gBAAgB,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OAAOmB,GAAG,CAAC,CAAC,oDAAoD,CAAC;IAEjE,IAAIvB,gBAAgB;QAClBU,MAAMa,GAAG,CAAC;YAACC,gBAAgB;YAAOC,MAAM;QAAqB;QAE7D,MAAMkB,sBAAsB;QAE5BvC,OAAOmB,GAAG,CAAC,CAAC,6BAA6B,EAAEzC,UAAU,QAAQ6D,sBAAsB;QACnFvC,OAAOmB,GAAG,CAAC;IACb;AACF"}
|
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
}
|
|
13
13
|
const newValue = typeof variables[variableName] === 'string' ? variables[variableName] : '';
|
|
14
14
|
// Escape backslashes first, then the surrounding quote character
|
|
15
|
-
const escaped = newValue.replaceAll('\\',
|
|
15
|
+
const escaped = newValue.replaceAll('\\', String.raw`\\`).replaceAll(quote, `\\${quote}`);
|
|
16
16
|
return `${quote}${escaped}${quote}`;
|
|
17
17
|
});
|
|
18
18
|
// Replace boolean placeholders: __BOOL__variableName__
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/init/processTemplate.ts"],"sourcesContent":["interface TemplateOptions<T> {\n template: string\n variables: T\n\n includeBooleanTransform?: boolean\n}\n\n/**\n * Process a template string by replacing placeholder variables with actual values.\n *\n * String variables use the format `'%variableName%'` (inside string literals).\n * Boolean variables use the format `__BOOL__variableName__` (as bare identifiers).\n */\nexport function processTemplate<T extends object>(options: TemplateOptions<T>): string {\n const {includeBooleanTransform = false, template, variables} = options\n\n // Replace string placeholders: '%variableName%' or \"%variableName%\"\n let result = template\n .trimStart()\n .replaceAll(/(['\"])%([\\w]+)%\\1/g, (_match, quote: string, variableName: string) => {\n if (!(variableName in variables)) {\n throw new Error(`Template variable '%${variableName}%' not defined`)\n }\n const newValue =\n typeof variables[variableName as keyof T] === 'string'\n ? variables[variableName as keyof T]\n : ''\n // Escape backslashes first, then the surrounding quote character\n const escaped = (newValue as string).replaceAll('\\\\',
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/init/processTemplate.ts"],"sourcesContent":["interface TemplateOptions<T> {\n template: string\n variables: T\n\n includeBooleanTransform?: boolean\n}\n\n/**\n * Process a template string by replacing placeholder variables with actual values.\n *\n * String variables use the format `'%variableName%'` (inside string literals).\n * Boolean variables use the format `__BOOL__variableName__` (as bare identifiers).\n */\nexport function processTemplate<T extends object>(options: TemplateOptions<T>): string {\n const {includeBooleanTransform = false, template, variables} = options\n\n // Replace string placeholders: '%variableName%' or \"%variableName%\"\n let result = template\n .trimStart()\n .replaceAll(/(['\"])%([\\w]+)%\\1/g, (_match, quote: string, variableName: string) => {\n if (!(variableName in variables)) {\n throw new Error(`Template variable '%${variableName}%' not defined`)\n }\n const newValue =\n typeof variables[variableName as keyof T] === 'string'\n ? variables[variableName as keyof T]\n : ''\n // Escape backslashes first, then the surrounding quote character\n const escaped = (newValue as string)\n .replaceAll('\\\\', String.raw`\\\\`)\n .replaceAll(quote, `\\\\${quote}`)\n return `${quote}${escaped}${quote}`\n })\n\n // Replace boolean placeholders: __BOOL__variableName__\n if (includeBooleanTransform) {\n result = result.replaceAll(/__BOOL__(\\w+)__/g, (_match, variableName: string) => {\n if (!(variableName in variables)) {\n throw new Error(`Template variable '${variableName}' not defined`)\n }\n const value = variables[variableName as keyof T]\n if (typeof value !== 'boolean') {\n throw new TypeError(`Expected boolean value for '${variableName}'`)\n }\n return String(value)\n })\n }\n\n return result\n}\n"],"names":["processTemplate","options","includeBooleanTransform","template","variables","result","trimStart","replaceAll","_match","quote","variableName","Error","newValue","escaped","String","raw","value","TypeError"],"mappings":"AAOA;;;;;CAKC,GACD,OAAO,SAASA,gBAAkCC,OAA2B;IAC3E,MAAM,EAACC,0BAA0B,KAAK,EAAEC,QAAQ,EAAEC,SAAS,EAAC,GAAGH;IAE/D,oEAAoE;IACpE,IAAII,SAASF,SACVG,SAAS,GACTC,UAAU,CAAC,sBAAsB,CAACC,QAAQC,OAAeC;QACxD,IAAI,CAAEA,CAAAA,gBAAgBN,SAAQ,GAAI;YAChC,MAAM,IAAIO,MAAM,CAAC,oBAAoB,EAAED,aAAa,cAAc,CAAC;QACrE;QACA,MAAME,WACJ,OAAOR,SAAS,CAACM,aAAwB,KAAK,WAC1CN,SAAS,CAACM,aAAwB,GAClC;QACN,iEAAiE;QACjE,MAAMG,UAAU,AAACD,SACdL,UAAU,CAAC,MAAMO,OAAOC,GAAG,CAAC,EAAE,CAAC,EAC/BR,UAAU,CAACE,OAAO,CAAC,EAAE,EAAEA,OAAO;QACjC,OAAO,GAAGA,QAAQI,UAAUJ,OAAO;IACrC;IAEF,uDAAuD;IACvD,IAAIP,yBAAyB;QAC3BG,SAASA,OAAOE,UAAU,CAAC,oBAAoB,CAACC,QAAQE;YACtD,IAAI,CAAEA,CAAAA,gBAAgBN,SAAQ,GAAI;gBAChC,MAAM,IAAIO,MAAM,CAAC,mBAAmB,EAAED,aAAa,aAAa,CAAC;YACnE;YACA,MAAMM,QAAQZ,SAAS,CAACM,aAAwB;YAChD,IAAI,OAAOM,UAAU,WAAW;gBAC9B,MAAM,IAAIC,UAAU,CAAC,4BAA4B,EAAEP,aAAa,CAAC,CAAC;YACpE;YACA,OAAOI,OAAOE;QAChB;IACF;IAEA,OAAOX;AACT"}
|
|
@@ -53,7 +53,7 @@ async function downloadTarStream(url, bearerToken) {
|
|
|
53
53
|
if (!res.body) {
|
|
54
54
|
throw new Error(`Failed to download: ${url}`);
|
|
55
55
|
}
|
|
56
|
-
// eslint-disable-next-line n/no-unsupported-features/node-builtins
|
|
56
|
+
// eslint-disable-next-line n-js/no-unsupported-features/node-builtins
|
|
57
57
|
return Readable.fromWeb(res.body);
|
|
58
58
|
}
|
|
59
59
|
export function checkIsRemoteTemplate(templateName) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/init/remoteTemplate.ts"],"sourcesContent":["import {access, readFile, writeFile} from 'node:fs/promises'\nimport {join, posix, sep} from 'node:path'\nimport {Readable} from 'node:stream'\nimport {pipeline} from 'node:stream/promises'\n\nimport {readPackageJson, subdebug} from '@sanity/cli-core'\nimport {ENV_TEMPLATE_FILES, REQUIRED_ENV_VAR} from '@sanity/template-validator'\nimport {x} from 'tar'\n\nconst debug = subdebug('remoteTemplate')\n\nconst DISALLOWED_PATHS = [\n // Prevent security risks from unknown GitHub Actions\n '/.github/',\n]\n\nconst ENV_VAR = {\n ...REQUIRED_ENV_VAR,\n READ_TOKEN: 'SANITY_API_READ_TOKEN',\n WRITE_TOKEN: 'SANITY_API_WRITE_TOKEN',\n} as const\n\ntype EnvData = {\n dataset: string\n projectId: string\n readToken?: string\n writeToken?: string\n}\n\ntype GitHubUrlString =\n | `https://github.com/${string}/${string}`\n | `https://www.github.com/${string}/${string}`\n\nexport type RepoInfo = {\n branch: string\n filePath: string\n name: string\n username: string\n}\n\nexport function getGitHubRawContentUrl(repoInfo: RepoInfo): string {\n const {branch, filePath, name, username} = repoInfo\n return `https://raw.githubusercontent.com/${username}/${name}/${branch}/${filePath}`\n}\n\nfunction isGitHubRepoShorthand(value: string): boolean {\n if (URL.canParse(value)) {\n return false\n }\n // This supports :owner/:repo and :owner/:repo/nested/path, e.g.\n // sanity-io/sanity\n // sanity-io/sanity/templates/next-js\n // sanity-io/templates/live-content-api\n // sanity-io/sanity/packages/@sanity/cli/test/test-template\n return /^[\\w-]+\\/[\\w-.]+(\\/[@\\w-.]+)*$/.test(value)\n}\n\nfunction isGitHubRepoUrl(value: string | URL): value is GitHubUrlString | URL {\n if (!URL.canParse(value)) {\n return false\n }\n const url = new URL(value)\n const pathSegments = url.pathname.slice(1).split('/')\n\n return (\n url.protocol === 'https:' &&\n url.hostname === 'github.com' &&\n // The pathname must have at least 2 segments. If it has more than 2, the\n // third must be \"tree\" and it must have at least 4 segments.\n // https://github.com/:owner/:repo\n // https://github.com/:owner/:repo/tree/:ref\n pathSegments.length >= 2 &&\n (pathSegments.length > 2 ? pathSegments[2] === 'tree' && pathSegments.length >= 4 : true)\n )\n}\n\nasync function downloadTarStream(url: string, bearerToken?: string): Promise<Readable> {\n const headers: Record<string, string> = {}\n if (bearerToken) {\n headers.Authorization = `Bearer ${bearerToken}`\n }\n\n const res = await fetch(url, {headers})\n\n if (!res.body) {\n throw new Error(`Failed to download: ${url}`)\n }\n\n // eslint-disable-next-line n/no-unsupported-features/node-builtins\n return Readable.fromWeb(res.body as Parameters<typeof Readable.fromWeb>[0])\n}\n\nexport function checkIsRemoteTemplate(templateName?: string): boolean {\n return templateName?.includes('/') ?? false\n}\n\nexport async function getGitHubRepoInfo(value: string, bearerToken?: string): Promise<RepoInfo> {\n let username = ''\n let name = ''\n let branch = ''\n let filePath = ''\n\n if (isGitHubRepoShorthand(value)) {\n const parts = value.split('/')\n username = parts[0]\n name = parts[1]\n // If there are more segments after owner/repo, they form the file path\n if (parts.length > 2) {\n filePath = parts.slice(2).join('/')\n }\n }\n\n if (isGitHubRepoUrl(value)) {\n const url = new URL(value)\n const pathSegments = url.pathname.slice(1).split('/')\n username = pathSegments[0]\n name = pathSegments[1]\n\n // If we have a \"tree\" segment, everything after branch is the file path\n if (pathSegments[2] === 'tree') {\n branch = pathSegments[3]\n if (pathSegments.length > 4) {\n filePath = pathSegments.slice(4).join('/')\n }\n }\n }\n\n if (!username || !name) {\n throw new Error('Invalid GitHub repository format')\n }\n\n const tokenMessage =\n 'GitHub repository not found. For private repositories, use --template-token to provide an access token.\\n\\n' +\n 'You can generate a new token at https://github.com/settings/personal-access-tokens/new\\n' +\n 'Set the token to \"read-only\" with repository access and a short expiry (e.g. 7 days) for security.'\n\n try {\n const headers: Record<string, string> = {}\n if (bearerToken) {\n headers.Authorization = `Bearer ${bearerToken}`\n }\n\n const infoResponse = await fetch(`https://api.github.com/repos/${username}/${name}`, {\n headers,\n })\n\n if (infoResponse.status !== 200) {\n if (infoResponse.status === 404) {\n throw new Error(tokenMessage)\n }\n throw new Error('GitHub repository not found')\n }\n\n const info = await infoResponse.json()\n\n return {\n branch: branch || info.default_branch,\n filePath,\n name,\n username,\n }\n } catch {\n throw new Error(tokenMessage)\n }\n}\n\nexport async function downloadAndExtractRepo(\n root: string,\n {branch, filePath, name, username}: RepoInfo,\n bearerToken?: string,\n): Promise<void> {\n let rootPath: string | null = null\n await pipeline(\n await downloadTarStream(\n `https://codeload.github.com/${username}/${name}/tar.gz/${branch}`,\n bearerToken,\n ),\n x({\n cwd: root,\n filter: (p: string) => {\n const posixPath = p.split(sep).join(posix.sep)\n if (rootPath === null) {\n const pathSegments = posixPath.split(posix.sep)\n rootPath = pathSegments.length > 0 ? pathSegments[0] : null\n }\n for (const disallowedPath of DISALLOWED_PATHS) {\n if (posixPath.includes(disallowedPath)) return false\n }\n return posixPath.startsWith(`${rootPath}${filePath ? `/${filePath}/` : '/'}`)\n },\n strip: filePath ? filePath.split('/').length + 1 : 1,\n }),\n )\n}\n\nexport async function checkIfNeedsApiToken(root: string, type: 'read' | 'write'): Promise<boolean> {\n try {\n const templatePath = await Promise.any(\n ENV_TEMPLATE_FILES.map(async (file) => {\n await access(join(root, file))\n return file\n }),\n )\n const templateContent = await readFile(join(root, templatePath), 'utf8')\n return templateContent.includes(type === 'read' ? ENV_VAR.READ_TOKEN : ENV_VAR.WRITE_TOKEN)\n } catch {\n return false\n }\n}\n\nexport async function applyEnvVariables(\n root: string,\n envData: EnvData,\n targetName = '.env',\n): Promise<void> {\n const templatePath = await Promise.any(\n ENV_TEMPLATE_FILES.map(async (file) => {\n await access(join(root, file))\n return file\n }),\n ).catch(() => {})\n\n if (!templatePath) {\n return // No template .env file found, skip\n }\n\n try {\n const templateContent = await readFile(join(root, templatePath), 'utf8')\n const {dataset, projectId, readToken = '', writeToken = ''} = envData\n\n const findAndReplaceVariable = (\n content: string,\n varRegex: RegExp | string,\n value: string,\n useQuotes: boolean,\n ) => {\n const varPattern = typeof varRegex === 'string' ? varRegex : varRegex.source\n const pattern = new RegExp(`.*${varPattern}=.*$`, 'gm')\n const matches = content.matchAll(pattern)\n\n let result = content\n for (const match of matches) {\n if (!match[0]) continue\n const varName = match[0].split('=')[0].trim()\n result = result.replaceAll(\n new RegExp(`${varName}=.*$`, 'gm'),\n `${varName}=${useQuotes ? `\"${value}\"` : value}`,\n )\n }\n\n return result\n }\n\n let envContent = templateContent\n const vars = [\n {pattern: ENV_VAR.PROJECT_ID, value: projectId},\n {pattern: ENV_VAR.DATASET, value: dataset},\n {pattern: ENV_VAR.READ_TOKEN, value: readToken},\n {pattern: ENV_VAR.WRITE_TOKEN, value: writeToken},\n ]\n const useQuotes = templateContent.includes('=\"')\n\n for (const {pattern, value} of vars) {\n envContent = findAndReplaceVariable(envContent, pattern, value, useQuotes)\n }\n\n await writeFile(join(root, targetName), envContent)\n } catch (err) {\n debug(`Error setting environment variables: ${err}`)\n throw new Error(\n 'Failed to set environment variables. This could be due to file permissions or the .env file format. See https://www.sanity.io/docs/environment-variables for details on environment variable setup.',\n {cause: err},\n )\n }\n}\n\nexport async function tryApplyPackageName(root: string, name: string): Promise<void> {\n try {\n const pkg = await readPackageJson(join(root, 'package.json'))\n pkg.name = name\n\n await writeFile(join(root, 'package.json'), JSON.stringify(pkg, null, 2))\n } catch {\n // noop\n }\n}\n"],"names":["access","readFile","writeFile","join","posix","sep","Readable","pipeline","readPackageJson","subdebug","ENV_TEMPLATE_FILES","REQUIRED_ENV_VAR","x","debug","DISALLOWED_PATHS","ENV_VAR","READ_TOKEN","WRITE_TOKEN","getGitHubRawContentUrl","repoInfo","branch","filePath","name","username","isGitHubRepoShorthand","value","URL","canParse","test","isGitHubRepoUrl","url","pathSegments","pathname","slice","split","protocol","hostname","length","downloadTarStream","bearerToken","headers","Authorization","res","fetch","body","Error","fromWeb","checkIsRemoteTemplate","templateName","includes","getGitHubRepoInfo","parts","tokenMessage","infoResponse","status","info","json","default_branch","downloadAndExtractRepo","root","rootPath","cwd","filter","p","posixPath","disallowedPath","startsWith","strip","checkIfNeedsApiToken","type","templatePath","Promise","any","map","file","templateContent","applyEnvVariables","envData","targetName","catch","dataset","projectId","readToken","writeToken","findAndReplaceVariable","content","varRegex","useQuotes","varPattern","source","pattern","RegExp","matches","matchAll","result","match","varName","trim","replaceAll","envContent","vars","PROJECT_ID","DATASET","err","cause","tryApplyPackageName","pkg","JSON","stringify"],"mappings":"AAAA,SAAQA,MAAM,EAAEC,QAAQ,EAAEC,SAAS,QAAO,mBAAkB;AAC5D,SAAQC,IAAI,EAAEC,KAAK,EAAEC,GAAG,QAAO,YAAW;AAC1C,SAAQC,QAAQ,QAAO,cAAa;AACpC,SAAQC,QAAQ,QAAO,uBAAsB;AAE7C,SAAQC,eAAe,EAAEC,QAAQ,QAAO,mBAAkB;AAC1D,SAAQC,kBAAkB,EAAEC,gBAAgB,QAAO,6BAA4B;AAC/E,SAAQC,CAAC,QAAO,MAAK;AAErB,MAAMC,QAAQJ,SAAS;AAEvB,MAAMK,mBAAmB;IACvB,qDAAqD;IACrD;CACD;AAED,MAAMC,UAAU;IACd,GAAGJ,gBAAgB;IACnBK,YAAY;IACZC,aAAa;AACf;AAoBA,OAAO,SAASC,uBAAuBC,QAAkB;IACvD,MAAM,EAACC,MAAM,EAAEC,QAAQ,EAAEC,IAAI,EAAEC,QAAQ,EAAC,GAAGJ;IAC3C,OAAO,CAAC,kCAAkC,EAAEI,SAAS,CAAC,EAAED,KAAK,CAAC,EAAEF,OAAO,CAAC,EAAEC,UAAU;AACtF;AAEA,SAASG,sBAAsBC,KAAa;IAC1C,IAAIC,IAAIC,QAAQ,CAACF,QAAQ;QACvB,OAAO;IACT;IACA,gEAAgE;IAChE,mBAAmB;IACnB,qCAAqC;IACrC,uCAAuC;IACvC,2DAA2D;IAC3D,OAAO,iCAAiCG,IAAI,CAACH;AAC/C;AAEA,SAASI,gBAAgBJ,KAAmB;IAC1C,IAAI,CAACC,IAAIC,QAAQ,CAACF,QAAQ;QACxB,OAAO;IACT;IACA,MAAMK,MAAM,IAAIJ,IAAID;IACpB,MAAMM,eAAeD,IAAIE,QAAQ,CAACC,KAAK,CAAC,GAAGC,KAAK,CAAC;IAEjD,OACEJ,IAAIK,QAAQ,K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AAI1D,MACR,uMACA;YAAC2D,OAAOD;QAAG;IAEf;AACF;AAEA,OAAO,eAAeE,oBAAoB9C,IAAY,EAAErC,IAAY;IAClE,IAAI;QACF,MAAMoF,MAAM,MAAMlG,gBAAgBL,KAAKwD,MAAM;QAC7C+C,IAAIpF,IAAI,GAAGA;QAEX,MAAMpB,UAAUC,KAAKwD,MAAM,iBAAiBgD,KAAKC,SAAS,CAACF,KAAK,MAAM;IACxE,EAAE,OAAM;IACN,OAAO;IACT;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/init/remoteTemplate.ts"],"sourcesContent":["import {access, readFile, writeFile} from 'node:fs/promises'\nimport {join, posix, sep} from 'node:path'\nimport {Readable} from 'node:stream'\nimport {pipeline} from 'node:stream/promises'\n\nimport {readPackageJson, subdebug} from '@sanity/cli-core'\nimport {ENV_TEMPLATE_FILES, REQUIRED_ENV_VAR} from '@sanity/template-validator'\nimport {x} from 'tar'\n\nconst debug = subdebug('remoteTemplate')\n\nconst DISALLOWED_PATHS = [\n // Prevent security risks from unknown GitHub Actions\n '/.github/',\n]\n\nconst ENV_VAR = {\n ...REQUIRED_ENV_VAR,\n READ_TOKEN: 'SANITY_API_READ_TOKEN',\n WRITE_TOKEN: 'SANITY_API_WRITE_TOKEN',\n} as const\n\ntype EnvData = {\n dataset: string\n projectId: string\n readToken?: string\n writeToken?: string\n}\n\ntype GitHubUrlString =\n | `https://github.com/${string}/${string}`\n | `https://www.github.com/${string}/${string}`\n\nexport type RepoInfo = {\n branch: string\n filePath: string\n name: string\n username: string\n}\n\nexport function getGitHubRawContentUrl(repoInfo: RepoInfo): string {\n const {branch, filePath, name, username} = repoInfo\n return `https://raw.githubusercontent.com/${username}/${name}/${branch}/${filePath}`\n}\n\nfunction isGitHubRepoShorthand(value: string): boolean {\n if (URL.canParse(value)) {\n return false\n }\n // This supports :owner/:repo and :owner/:repo/nested/path, e.g.\n // sanity-io/sanity\n // sanity-io/sanity/templates/next-js\n // sanity-io/templates/live-content-api\n // sanity-io/sanity/packages/@sanity/cli/test/test-template\n return /^[\\w-]+\\/[\\w-.]+(\\/[@\\w-.]+)*$/.test(value)\n}\n\nfunction isGitHubRepoUrl(value: string | URL): value is GitHubUrlString | URL {\n if (!URL.canParse(value)) {\n return false\n }\n const url = new URL(value)\n const pathSegments = url.pathname.slice(1).split('/')\n\n return (\n url.protocol === 'https:' &&\n url.hostname === 'github.com' &&\n // The pathname must have at least 2 segments. If it has more than 2, the\n // third must be \"tree\" and it must have at least 4 segments.\n // https://github.com/:owner/:repo\n // https://github.com/:owner/:repo/tree/:ref\n pathSegments.length >= 2 &&\n (pathSegments.length > 2 ? pathSegments[2] === 'tree' && pathSegments.length >= 4 : true)\n )\n}\n\nasync function downloadTarStream(url: string, bearerToken?: string): Promise<Readable> {\n const headers: Record<string, string> = {}\n if (bearerToken) {\n headers.Authorization = `Bearer ${bearerToken}`\n }\n\n const res = await fetch(url, {headers})\n\n if (!res.body) {\n throw new Error(`Failed to download: ${url}`)\n }\n\n // eslint-disable-next-line n-js/no-unsupported-features/node-builtins\n return Readable.fromWeb(res.body as Parameters<typeof Readable.fromWeb>[0])\n}\n\nexport function checkIsRemoteTemplate(templateName?: string): boolean {\n return templateName?.includes('/') ?? false\n}\n\nexport async function getGitHubRepoInfo(value: string, bearerToken?: string): Promise<RepoInfo> {\n let username = ''\n let name = ''\n let branch = ''\n let filePath = ''\n\n if (isGitHubRepoShorthand(value)) {\n const parts = value.split('/')\n username = parts[0]\n name = parts[1]\n // If there are more segments after owner/repo, they form the file path\n if (parts.length > 2) {\n filePath = parts.slice(2).join('/')\n }\n }\n\n if (isGitHubRepoUrl(value)) {\n const url = new URL(value)\n const pathSegments = url.pathname.slice(1).split('/')\n username = pathSegments[0]\n name = pathSegments[1]\n\n // If we have a \"tree\" segment, everything after branch is the file path\n if (pathSegments[2] === 'tree') {\n branch = pathSegments[3]\n if (pathSegments.length > 4) {\n filePath = pathSegments.slice(4).join('/')\n }\n }\n }\n\n if (!username || !name) {\n throw new Error('Invalid GitHub repository format')\n }\n\n const tokenMessage =\n 'GitHub repository not found. For private repositories, use --template-token to provide an access token.\\n\\n' +\n 'You can generate a new token at https://github.com/settings/personal-access-tokens/new\\n' +\n 'Set the token to \"read-only\" with repository access and a short expiry (e.g. 7 days) for security.'\n\n try {\n const headers: Record<string, string> = {}\n if (bearerToken) {\n headers.Authorization = `Bearer ${bearerToken}`\n }\n\n const infoResponse = await fetch(`https://api.github.com/repos/${username}/${name}`, {\n headers,\n })\n\n if (infoResponse.status !== 200) {\n if (infoResponse.status === 404) {\n throw new Error(tokenMessage)\n }\n throw new Error('GitHub repository not found')\n }\n\n const info = await infoResponse.json()\n\n return {\n branch: branch || info.default_branch,\n filePath,\n name,\n username,\n }\n } catch {\n throw new Error(tokenMessage)\n }\n}\n\nexport async function downloadAndExtractRepo(\n root: string,\n {branch, filePath, name, username}: RepoInfo,\n bearerToken?: string,\n): Promise<void> {\n let rootPath: string | null = null\n await pipeline(\n await downloadTarStream(\n `https://codeload.github.com/${username}/${name}/tar.gz/${branch}`,\n bearerToken,\n ),\n x({\n cwd: root,\n filter: (p: string) => {\n const posixPath = p.split(sep).join(posix.sep)\n if (rootPath === null) {\n const pathSegments = posixPath.split(posix.sep)\n rootPath = pathSegments.length > 0 ? pathSegments[0] : null\n }\n for (const disallowedPath of DISALLOWED_PATHS) {\n if (posixPath.includes(disallowedPath)) return false\n }\n return posixPath.startsWith(`${rootPath}${filePath ? `/${filePath}/` : '/'}`)\n },\n strip: filePath ? filePath.split('/').length + 1 : 1,\n }),\n )\n}\n\nexport async function checkIfNeedsApiToken(root: string, type: 'read' | 'write'): Promise<boolean> {\n try {\n const templatePath = await Promise.any(\n ENV_TEMPLATE_FILES.map(async (file) => {\n await access(join(root, file))\n return file\n }),\n )\n const templateContent = await readFile(join(root, templatePath), 'utf8')\n return templateContent.includes(type === 'read' ? ENV_VAR.READ_TOKEN : ENV_VAR.WRITE_TOKEN)\n } catch {\n return false\n }\n}\n\nexport async function applyEnvVariables(\n root: string,\n envData: EnvData,\n targetName = '.env',\n): Promise<void> {\n const templatePath = await Promise.any(\n ENV_TEMPLATE_FILES.map(async (file) => {\n await access(join(root, file))\n return file\n }),\n ).catch(() => {})\n\n if (!templatePath) {\n return // No template .env file found, skip\n }\n\n try {\n const templateContent = await readFile(join(root, templatePath), 'utf8')\n const {dataset, projectId, readToken = '', writeToken = ''} = envData\n\n const findAndReplaceVariable = (\n content: string,\n varRegex: RegExp | string,\n value: string,\n useQuotes: boolean,\n ) => {\n const varPattern = typeof varRegex === 'string' ? varRegex : varRegex.source\n const pattern = new RegExp(`.*${varPattern}=.*$`, 'gm')\n const matches = content.matchAll(pattern)\n\n let result = content\n for (const match of matches) {\n if (!match[0]) continue\n const varName = match[0].split('=')[0].trim()\n result = result.replaceAll(\n new RegExp(`${varName}=.*$`, 'gm'),\n `${varName}=${useQuotes ? `\"${value}\"` : value}`,\n )\n }\n\n return result\n }\n\n let envContent = templateContent\n const vars = [\n {pattern: ENV_VAR.PROJECT_ID, value: projectId},\n {pattern: ENV_VAR.DATASET, value: dataset},\n {pattern: ENV_VAR.READ_TOKEN, value: readToken},\n {pattern: ENV_VAR.WRITE_TOKEN, value: writeToken},\n ]\n const useQuotes = templateContent.includes('=\"')\n\n for (const {pattern, value} of vars) {\n envContent = findAndReplaceVariable(envContent, pattern, value, useQuotes)\n }\n\n await writeFile(join(root, targetName), envContent)\n } catch (err) {\n debug(`Error setting environment variables: ${err}`)\n throw new Error(\n 'Failed to set environment variables. This could be due to file permissions or the .env file format. See https://www.sanity.io/docs/environment-variables for details on environment variable setup.',\n {cause: err},\n )\n }\n}\n\nexport async function tryApplyPackageName(root: string, name: string): Promise<void> {\n try {\n const pkg = await readPackageJson(join(root, 'package.json'))\n pkg.name = name\n\n await writeFile(join(root, 'package.json'), JSON.stringify(pkg, null, 2))\n } catch {\n // noop\n }\n}\n"],"names":["access","readFile","writeFile","join","posix","sep","Readable","pipeline","readPackageJson","subdebug","ENV_TEMPLATE_FILES","REQUIRED_ENV_VAR","x","debug","DISALLOWED_PATHS","ENV_VAR","READ_TOKEN","WRITE_TOKEN","getGitHubRawContentUrl","repoInfo","branch","filePath","name","username","isGitHubRepoShorthand","value","URL","canParse","test","isGitHubRepoUrl","url","pathSegments","pathname","slice","split","protocol","hostname","length","downloadTarStream","bearerToken","headers","Authorization","res","fetch","body","Error","fromWeb","checkIsRemoteTemplate","templateName","includes","getGitHubRepoInfo","parts","tokenMessage","infoResponse","status","info","json","default_branch","downloadAndExtractRepo","root","rootPath","cwd","filter","p","posixPath","disallowedPath","startsWith","strip","checkIfNeedsApiToken","type","templatePath","Promise","any","map","file","templateContent","applyEnvVariables","envData","targetName","catch","dataset","projectId","readToken","writeToken","findAndReplaceVariable","content","varRegex","useQuotes","varPattern","source","pattern","RegExp","matches","matchAll","result","match","varName","trim","replaceAll","envContent","vars","PROJECT_ID","DATASET","err","cause","tryApplyPackageName","pkg","JSON","stringify"],"mappings":"AAAA,SAAQA,MAAM,EAAEC,QAAQ,EAAEC,SAAS,QAAO,mBAAkB;AAC5D,SAAQC,IAAI,EAAEC,KAAK,EAAEC,GAAG,QAAO,YAAW;AAC1C,SAAQC,QAAQ,QAAO,cAAa;AACpC,SAAQC,QAAQ,QAAO,uBAAsB;AAE7C,SAAQC,eAAe,EAAEC,QAAQ,QAAO,mBAAkB;AAC1D,SAAQC,kBAAkB,EAAEC,gBAAgB,QAAO,6BAA4B;AAC/E,SAAQC,CAAC,QAAO,MAAK;AAErB,MAAMC,QAAQJ,SAAS;AAEvB,MAAMK,mBAAmB;IACvB,qDAAqD;IACrD;CACD;AAED,MAAMC,UAAU;IACd,GAAGJ,gBAAgB;IACnBK,YAAY;IACZC,aAAa;AACf;AAoBA,OAAO,SAASC,uBAAuBC,QAAkB;IACvD,MAAM,EAACC,MAAM,EAAEC,QAAQ,EAAEC,IAAI,EAAEC,QAAQ,EAAC,GAAGJ;IAC3C,OAAO,CAAC,kCAAkC,EAAEI,SAAS,CA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D;YAAS;YAC9C;gBAACS,SAAS3E,QAAQuF,OAAO;gBAAE7E,OAAOuD;YAAO;YACzC;gBAACU,SAAS3E,QAAQC,UAAU;gBAAES,OAAOyD;YAAS;YAC9C;gBAACQ,SAAS3E,QAAQE,WAAW;gBAAEQ,OAAO0D;YAAU;SACjD;QACD,MAAMI,YAAYZ,gBAAgB1B,QAAQ,CAAC;QAE3C,KAAK,MAAM,EAACyC,OAAO,EAAEjE,KAAK,EAAC,IAAI2E,KAAM;YACnCD,aAAaf,uBAAuBe,YAAYT,SAASjE,OAAO8D;QAClE;QAEA,MAAMrF,UAAUC,KAAKwD,MAAMmB,aAAaqB;IAC1C,EAAE,OAAOI,KAAK;QACZ1F,MAAM,CAAC,qCAAqC,EAAE0F,KAAK;QACnD,MAAM,IAAI1D,MACR,uMACA;YAAC2D,OAAOD;QAAG;IAEf;AACF;AAEA,OAAO,eAAeE,oBAAoB9C,IAAY,EAAErC,IAAY;IAClE,IAAI;QACF,MAAMoF,MAAM,MAAMlG,gBAAgBL,KAAKwD,MAAM;QAC7C+C,IAAIpF,IAAI,GAAGA;QAEX,MAAMpB,UAAUC,KAAKwD,MAAM,iBAAiBgD,KAAKC,SAAS,CAACF,KAAK,MAAM;IACxE,EAAE,OAAM;IACN,OAAO;IACT;AACF"}
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { extractManifest as internalExtractManifest } from '@sanity/cli-build/_internal/manifest';
|
|
2
|
-
export async function extractManifest({ applicationId, outPath, path, workDir }) {
|
|
2
|
+
export async function extractManifest({ applicationId, outPath, path, silent, workDir }) {
|
|
3
3
|
await internalExtractManifest({
|
|
4
4
|
applicationId,
|
|
5
5
|
outPath,
|
|
6
6
|
path,
|
|
7
|
+
silent,
|
|
7
8
|
workDir
|
|
8
9
|
});
|
|
9
10
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/manifest/extractManifest.ts"],"sourcesContent":["import {extractManifest as internalExtractManifest} from '@sanity/cli-build/_internal/manifest'\n\ntype ExtractManifestOptions = Parameters<typeof internalExtractManifest>[0]\n\nexport async function extractManifest({\n applicationId,\n outPath,\n path,\n workDir,\n}: ExtractManifestOptions): Promise<void> {\n await internalExtractManifest({applicationId, outPath, path, workDir})\n}\n"],"names":["extractManifest","internalExtractManifest","applicationId","outPath","path","workDir"],"mappings":"AAAA,SAAQA,mBAAmBC,uBAAuB,QAAO,uCAAsC;AAI/F,OAAO,eAAeD,gBAAgB,EACpCE,aAAa,EACbC,OAAO,EACPC,IAAI,EACJC,OAAO,EACgB;IACvB,
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/manifest/extractManifest.ts"],"sourcesContent":["import {extractManifest as internalExtractManifest} from '@sanity/cli-build/_internal/manifest'\n\ntype ExtractManifestOptions = Parameters<typeof internalExtractManifest>[0]\n\nexport async function extractManifest({\n applicationId,\n outPath,\n path,\n silent,\n workDir,\n}: ExtractManifestOptions): Promise<void> {\n await internalExtractManifest({applicationId, outPath, path, silent, workDir})\n}\n"],"names":["extractManifest","internalExtractManifest","applicationId","outPath","path","silent","workDir"],"mappings":"AAAA,SAAQA,mBAAmBC,uBAAuB,QAAO,uCAAsC;AAI/F,OAAO,eAAeD,gBAAgB,EACpCE,aAAa,EACbC,OAAO,EACPC,IAAI,EACJC,MAAM,EACNC,OAAO,EACgB;IACvB,MAAML,wBAAwB;QAACC;QAAeC;QAASC;QAAMC;QAAQC;IAAO;AAC9E"}
|
|
@@ -22,6 +22,7 @@ import { extractManifest } from './extractManifest.js';
|
|
|
22
22
|
applicationId: options.applicationId,
|
|
23
23
|
outPath,
|
|
24
24
|
path: options.configPath,
|
|
25
|
+
silent: options.silent,
|
|
25
26
|
workDir: options.workDir
|
|
26
27
|
});
|
|
27
28
|
const raw = await readFile(join(outPath, MANIFEST_FILENAME), 'utf8');
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/manifest/extractStudioManifest.ts"],"sourcesContent":["import {readFile} from 'node:fs/promises'\nimport {join, resolve} from 'node:path'\n\nimport {SANITY_CACHE_DIR} from '@sanity/cli-build/_internal/build'\nimport {MANIFEST_FILENAME, type StudioManifest} from '@sanity/cli-build/_internal/manifest'\n\nimport {extractManifest} from './extractManifest.js'\n\n/**\n * Dev-time manifest output directory, relative to the studio working\n * directory. Sibling of Vite's `cacheDir` so it stays out of `dist` and is\n * ignored by default in typical `.gitignore` files.\n */\nconst MANIFEST_DIR = `${SANITY_CACHE_DIR}/manifest`\n\n/**\n * Run the worker-based studio schema extraction, write the resulting manifest\n * to `MANIFEST_DIR`, then read it back so the caller can inline it into the\n * registry.\n *\n * `configPath` must be the resolved `sanity.config.(ts|js)` path — passing it\n * in (e.g. from `findProjectRoot`) avoids re-traversing the filesystem on\n * every call.\n */\nexport async function extractStudioManifest(options: {\n applicationId?: string\n configPath: string\n workDir: string\n}): Promise<StudioManifest | undefined> {\n const outPath = resolve(options.workDir, MANIFEST_DIR)\n await extractManifest({\n applicationId: options.applicationId,\n outPath,\n path: options.configPath,\n workDir: options.workDir,\n })\n const raw = await readFile(join(outPath, MANIFEST_FILENAME), 'utf8')\n return JSON.parse(raw)\n}\n"],"names":["readFile","join","resolve","SANITY_CACHE_DIR","MANIFEST_FILENAME","extractManifest","MANIFEST_DIR","extractStudioManifest","options","outPath","workDir","applicationId","path","configPath","raw","JSON","parse"],"mappings":"AAAA,SAAQA,QAAQ,QAAO,mBAAkB;AACzC,SAAQC,IAAI,EAAEC,OAAO,QAAO,YAAW;AAEvC,SAAQC,gBAAgB,QAAO,oCAAmC;AAClE,SAAQC,iBAAiB,QAA4B,uCAAsC;AAE3F,SAAQC,eAAe,QAAO,uBAAsB;AAEpD;;;;CAIC,GACD,MAAMC,eAAe,GAAGH,iBAAiB,SAAS,CAAC;AAEnD;;;;;;;;CAQC,GACD,OAAO,eAAeI,sBAAsBC,
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/manifest/extractStudioManifest.ts"],"sourcesContent":["import {readFile} from 'node:fs/promises'\nimport {join, resolve} from 'node:path'\n\nimport {SANITY_CACHE_DIR} from '@sanity/cli-build/_internal/build'\nimport {MANIFEST_FILENAME, type StudioManifest} from '@sanity/cli-build/_internal/manifest'\n\nimport {extractManifest} from './extractManifest.js'\n\n/**\n * Dev-time manifest output directory, relative to the studio working\n * directory. Sibling of Vite's `cacheDir` so it stays out of `dist` and is\n * ignored by default in typical `.gitignore` files.\n */\nconst MANIFEST_DIR = `${SANITY_CACHE_DIR}/manifest`\n\n/**\n * Run the worker-based studio schema extraction, write the resulting manifest\n * to `MANIFEST_DIR`, then read it back so the caller can inline it into the\n * registry.\n *\n * `configPath` must be the resolved `sanity.config.(ts|js)` path — passing it\n * in (e.g. from `findProjectRoot`) avoids re-traversing the filesystem on\n * every call.\n */\nexport async function extractStudioManifest(options: {\n applicationId?: string\n configPath: string\n silent?: boolean\n\n workDir: string\n}): Promise<StudioManifest | undefined> {\n const outPath = resolve(options.workDir, MANIFEST_DIR)\n await extractManifest({\n applicationId: options.applicationId,\n outPath,\n path: options.configPath,\n silent: options.silent,\n workDir: options.workDir,\n })\n const raw = await readFile(join(outPath, MANIFEST_FILENAME), 'utf8')\n return JSON.parse(raw)\n}\n"],"names":["readFile","join","resolve","SANITY_CACHE_DIR","MANIFEST_FILENAME","extractManifest","MANIFEST_DIR","extractStudioManifest","options","outPath","workDir","applicationId","path","configPath","silent","raw","JSON","parse"],"mappings":"AAAA,SAAQA,QAAQ,QAAO,mBAAkB;AACzC,SAAQC,IAAI,EAAEC,OAAO,QAAO,YAAW;AAEvC,SAAQC,gBAAgB,QAAO,oCAAmC;AAClE,SAAQC,iBAAiB,QAA4B,uCAAsC;AAE3F,SAAQC,eAAe,QAAO,uBAAsB;AAEpD;;;;CAIC,GACD,MAAMC,eAAe,GAAGH,iBAAiB,SAAS,CAAC;AAEnD;;;;;;;;CAQC,GACD,OAAO,eAAeI,sBAAsBC,OAM3C;IACC,MAAMC,UAAUP,QAAQM,QAAQE,OAAO,EAAEJ;IACzC,MAAMD,gBAAgB;QACpBM,eAAeH,QAAQG,aAAa;QACpCF;QACAG,MAAMJ,QAAQK,UAAU;QACxBC,QAAQN,QAAQM,MAAM;QACtBJ,SAASF,QAAQE,OAAO;IAC1B;IACA,MAAMK,MAAM,MAAMf,SAASC,KAAKQ,SAASL,oBAAoB;IAC7D,OAAOY,KAAKC,KAAK,CAACF;AACpB"}
|
|
@@ -177,7 +177,7 @@ function printFieldModule(definition) {
|
|
|
177
177
|
return `import {${imports}} from 'sanity'\n\nexport default defineField(${literal})\n`;
|
|
178
178
|
}
|
|
179
179
|
function quote(value) {
|
|
180
|
-
const escaped = value.replaceAll('\\',
|
|
180
|
+
const escaped = value.replaceAll('\\', String.raw`\\`).replaceAll("'", String.raw`\'`).replaceAll('\n', String.raw`\n`).replaceAll('\r', String.raw`\r`).replaceAll('\t', String.raw`\t`);
|
|
181
181
|
return `'${escaped}'`;
|
|
182
182
|
}
|
|
183
183
|
function printKey(key) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/media/pullAspects.ts"],"sourcesContent":["import {validateMediaLibraryAssetAspect} from '@sanity/schema/_internal'\nimport {type SchemaValidationProblem} from '@sanity/types'\nimport startCase from 'lodash-es/startCase.js'\n\nimport {type StoredAspectDocument} from '../../services/mediaLibraries.js'\nimport {VALID_ASPECT_NAME} from './aspectName.js'\n\n/** Keys whose object members are schema definitions, printed wrapped in a definer call. */\nconst DEFINER_BY_PARENT_KEY: Record<string, string> = {\n fields: 'defineField',\n of: 'defineArrayMember',\n}\n\nconst IDENTIFIER_KEY = /^[A-Za-z_$][A-Za-z0-9_$]*$/\n\n/** Scalar arrays shorter than this print inline (e.g. `options.list`). */\nconst INLINE_ARRAY_MAX_WIDTH = 60\n\n/**\n * The stored `sanity.asset.aspect` document shape this migration reads.\n * Deliberately loose: documents may predate the config model (authored via\n * `sanity media deploy-aspect` or by hand) and carry fields the model has no\n * equivalent for.\n */\nexport type PullableAspectDocument = StoredAspectDocument\n\nexport interface GeneratedFieldModule {\n filename: string\n /** The `aspects.<name>` data key — module filename and config entry name. */\n name: string\n source: string\n status: 'generated'\n title: string\n warnings: string[]\n\n public?: boolean\n}\n\nexport interface SkippedAspect {\n id: string\n reasons: string[]\n status: 'skipped'\n validationErrors: SchemaValidationProblem[][]\n}\n\nexport type PullAspectOutcome = GeneratedFieldModule | SkippedAspect\n\n/**\n * Convert a page of stored aspect documents into field modules, one per field\n * name. Two stored documents can resolve to the same name (a legacy document\n * whose `_id` predates its `definition.name`), which would otherwise produce\n * the same module twice — the document whose `_id` matches the name wins, the\n * rest are reported as skipped. Shared by `sanity media pull-aspects` and the\n * init-time pull offer.\n *\n * @internal\n */\nexport function convertAspectDocuments(documents: PullableAspectDocument[]): {\n modules: GeneratedFieldModule[]\n skipped: SkippedAspect[]\n} {\n const skipped: SkippedAspect[] = []\n\n // First pass: convert every stored document.\n const candidates: Array<{module: GeneratedFieldModule; sourceId: string}> = []\n for (const doc of documents) {\n const outcome = aspectDocumentToFieldModule(doc)\n if (outcome.status === 'skipped') {\n skipped.push(outcome)\n } else {\n candidates.push({module: outcome, sourceId: String(doc._id)})\n }\n }\n\n // Second pass: pick one winner per name.\n const byName = new Map<string, Array<{module: GeneratedFieldModule; sourceId: string}>>()\n for (const candidate of candidates) {\n const group = byName.get(candidate.module.name) ?? []\n group.push(candidate)\n byName.set(candidate.module.name, group)\n }\n const modules: GeneratedFieldModule[] = []\n for (const [name, group] of byName) {\n const winner = group.find((candidate) => candidate.sourceId === name) ?? group[0]\n modules.push(winner.module)\n for (const loser of group) {\n if (loser === winner) continue\n skipped.push({\n id: loser.sourceId,\n reasons: [`Also defines \"${name}\" — generated from \"${winner.sourceId}\" instead`],\n status: 'skipped',\n validationErrors: [],\n })\n }\n }\n\n return {modules, skipped}\n}\n\n/**\n * Codegen one stored aspect document into a `src/fields/<name>.tsx` field\n * module for a Media Library config app.\n *\n * Stored aspects are migration-ready by construction: `definition` is the\n * JSON-serialized `defineField(...)` value with functions and component\n * references already stripped, so generation is mechanical pretty-printing\n * into a `defineField({...})` call (nested `fields`/`of` members wrapped in\n * `defineField`/`defineArrayMember`, matching hand-authored style).\n *\n * Edge cases handled here, not silently:\n *\n * - `_id` vs `definition.name` mismatch: the module is generated under\n * `definition.name` — the `aspects.<name>` key existing asset data lives\n * under. Normalizing onto `_id` instead would silently orphan that data.\n * The old document (keyed `_id`) is reported for manual deletion.\n * - `assetType` has no equivalent in the config model; a document carrying it\n * generates with a warning that the scoping is lost.\n * - Definitions failing current schema validation are skipped with the\n * validation errors, mirroring `sanity media deploy-aspect`.\n *\n * Pure (no I/O): the command decides where modules are written.\n *\n * @internal\n */\nexport function aspectDocumentToFieldModule(doc: PullableAspectDocument): PullAspectOutcome {\n const {_id} = doc\n\n if (!isRecord(doc.definition)) {\n return {\n id: _id,\n reasons: ['The stored document has no field definition object'],\n status: 'skipped',\n validationErrors: [],\n }\n }\n\n const definitionName = typeof doc.definition.name === 'string' ? doc.definition.name : undefined\n const name = definitionName ?? _id\n\n if (!VALID_ASPECT_NAME.test(name)) {\n return {\n id: _id,\n reasons: [\n `\"${name}\" is not a valid field name (${VALID_ASPECT_NAME}) — it becomes the module name and the aspects.<name> key on assets`,\n ],\n status: 'skipped',\n validationErrors: [],\n }\n }\n\n const warnings: string[] = []\n\n if (definitionName === undefined) {\n warnings.push(`The stored definition has no name — using the document _id \"${_id}\"`)\n } else if (definitionName !== _id) {\n warnings.push(\n `Stored _id \"${_id}\" and definition name \"${definitionName}\" differ. Generated as ` +\n `\"${definitionName}\" — the aspects.<name> key existing asset data lives under; using ` +\n `\"${_id}\" would orphan that data. Deploying the config creates \"${definitionName}\" ` +\n `and deletes the old \"${_id}\" document.`,\n )\n }\n\n if (doc.assetType !== undefined && doc.assetType !== null) {\n warnings.push(\n `The stored document scopes the aspect by assetType (${JSON.stringify(doc.assetType)}), ` +\n `which has no equivalent in the config model — the generated field applies to all ` +\n `asset types, and syncing the config drops the scoping.`,\n )\n }\n\n // Normalize the name in before validating, so a document that only carries\n // its name as `_id` isn't rejected for the missing property.\n const definition: Record<string, unknown> = definitionName\n ? doc.definition\n : {name, ...doc.definition}\n\n const [valid, validationErrors] = validateMediaLibraryAssetAspect(definition)\n if (!valid) {\n return {\n id: _id,\n reasons: ['The stored definition fails schema validation'],\n status: 'skipped',\n validationErrors,\n }\n }\n\n return {\n // .tsx although the generated content has no JSX: field modules are\n // expected to grow custom input components (the one thing the stored\n // aspect could not carry), and a later rename would also mean fixing the\n // `src:` entry in sanity.cli.ts. Matches the template's example modules.\n filename: `${name}.tsx`,\n name,\n ...(typeof doc.public === 'boolean' ? {public: doc.public} : {}),\n source: printFieldModule(definition),\n status: 'generated',\n title: typeof definition.title === 'string' ? definition.title : startCase(name),\n warnings,\n }\n}\n\n/**\n * The paste-ready `fields: [...]` entries for `sanity.cli.ts`, one line per\n * generated module. When `writtenPaths` (module name to root-relative path)\n * has an entry for a module, that path wins — the module may have replaced an\n * existing file (e.g. a `.tsx` variant) rather than landing at the default\n * `<srcDir>/<filename>` location.\n *\n * @internal\n */\nexport function formatFieldEntries(\n modules: GeneratedFieldModule[],\n srcDir: string,\n writtenPaths?: Map<string, string>,\n): string {\n const dir = srcDir.replaceAll('\\\\', '/').replace(/\\/+$/, '')\n return modules\n .map((module) => {\n const src =\n writtenPaths?.get(module.name)?.replaceAll('\\\\', '/') ?? `${dir}/${module.filename}`\n const publicPart = module.public === undefined ? '' : `, public: ${module.public}`\n return `{name: '${module.name}', src: './${src}', title: ${quote(module.title)}${publicPart}},`\n })\n .join('\\n')\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\ninterface PrinterState {\n usesDefineArrayMember: boolean\n}\n\nfunction printFieldModule(definition: Record<string, unknown>): string {\n const state: PrinterState = {usesDefineArrayMember: false}\n const literal = printObject(definition, '', state)\n const imports = state.usesDefineArrayMember ? 'defineArrayMember, defineField' : 'defineField'\n\n return `import {${imports}} from 'sanity'\\n\\nexport default defineField(${literal})\\n`\n}\n\nfunction quote(value: string): string {\n const escaped = value\n .replaceAll('\\\\', '\\\\\\\\')\n .replaceAll(\"'\", String.raw`\\'`)\n .replaceAll('\\n', String.raw`\\n`)\n .replaceAll('\\r', String.raw`\\r`)\n .replaceAll('\\t', String.raw`\\t`)\n return `'${escaped}'`\n}\n\nfunction printKey(key: string): string {\n return IDENTIFIER_KEY.test(key) ? key : quote(key)\n}\n\nfunction printValue(\n value: unknown,\n indent: string,\n parentKey: string | null,\n state: PrinterState,\n): string {\n if (value === null) return 'null'\n if (typeof value === 'string') return quote(value)\n if (typeof value === 'number' || typeof value === 'boolean') return String(value)\n if (Array.isArray(value)) return printArray(value, indent, parentKey, state)\n if (isRecord(value)) return printObject(value, indent, state)\n // Stored definitions are JSON documents; anything else cannot occur.\n throw new TypeError(`Cannot print value of type ${typeof value}`)\n}\n\nfunction printArray(\n items: unknown[],\n indent: string,\n parentKey: string | null,\n state: PrinterState,\n): string {\n if (items.length === 0) return '[]'\n\n const allScalar = items.every(\n (item) => item === null || ['boolean', 'number', 'string'].includes(typeof item),\n )\n if (allScalar) {\n const inline = `[${items.map((item) => printValue(item, indent, null, state)).join(', ')}]`\n if (inline.length <= INLINE_ARRAY_MAX_WIDTH) return inline\n }\n\n const definer = parentKey === null ? undefined : DEFINER_BY_PARENT_KEY[parentKey]\n const innerIndent = `${indent} `\n const lines = items.map((item) => {\n if (definer !== undefined && isRecord(item)) {\n if (definer === 'defineArrayMember') state.usesDefineArrayMember = true\n return `${innerIndent}${definer}(${printObject(item, innerIndent, state)}),`\n }\n return `${innerIndent}${printValue(item, innerIndent, null, state)},`\n })\n return `[\\n${lines.join('\\n')}\\n${indent}]`\n}\n\nfunction printObject(obj: Record<string, unknown>, indent: string, state: PrinterState): string {\n const entries = Object.entries(obj).filter(([, value]) => value !== undefined)\n if (entries.length === 0) return '{}'\n\n const innerIndent = `${indent} `\n const lines = entries.map(\n ([key, value]) =>\n `${innerIndent}${printKey(key)}: ${printValue(value, innerIndent, key, state)},`,\n )\n return `{\\n${lines.join('\\n')}\\n${indent}}`\n}\n"],"names":["validateMediaLibraryAssetAspect","startCase","VALID_ASPECT_NAME","DEFINER_BY_PARENT_KEY","fields","of","IDENTIFIER_KEY","INLINE_ARRAY_MAX_WIDTH","convertAspectDocuments","documents","skipped","candidates","doc","outcome","aspectDocumentToFieldModule","status","push","module","sourceId","String","_id","byName","Map","candidate","group","get","name","set","modules","winner","find","loser","id","reasons","validationErrors","isRecord","definition","definitionName","undefined","test","warnings","assetType","JSON","stringify","valid","filename","public","source","printFieldModule","title","formatFieldEntries","srcDir","writtenPaths","dir","replaceAll","replace","map","src","publicPart","quote","join","value","Array","isArray","state","usesDefineArrayMember","literal","printObject","imports","escaped","raw","printKey","key","printValue","indent","parentKey","printArray","TypeError","items","length","allScalar","every","item","includes","inline","definer","innerIndent","lines","obj","entries","Object","filter"],"mappings":"AAAA,SAAQA,+BAA+B,QAAO,2BAA0B;AAExE,OAAOC,eAAe,yBAAwB;AAG9C,SAAQC,iBAAiB,QAAO,kBAAiB;AAEjD,yFAAyF,GACzF,MAAMC,wBAAgD;IACpDC,QAAQ;IACRC,IAAI;AACN;AAEA,MAAMC,iBAAiB;AAEvB,wEAAwE,GACxE,MAAMC,yBAAyB;AA+B/B;;;;;;;;;CASC,GACD,OAAO,SAASC,uBAAuBC,SAAmC;IAIxE,MAAMC,UAA2B,EAAE;IAEnC,6CAA6C;IAC7C,MAAMC,aAAsE,EAAE;IAC9E,KAAK,MAAMC,OAAOH,UAAW;QAC3B,MAAMI,UAAUC,4BAA4BF;QAC5C,IAAIC,QAAQE,MAAM,KAAK,WAAW;YAChCL,QAAQM,IAAI,CAACH;QACf,OAAO;YACLF,WAAWK,IAAI,CAAC;gBAACC,QAAQJ;gBAASK,UAAUC,OAAOP,IAAIQ,GAAG;YAAC;QAC7D;IACF;IAEA,yCAAyC;IACzC,MAAMC,SAAS,IAAIC;IACnB,KAAK,M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OrC,YAAYnC,qBAAqB,CAACwE,UAAU;IACjF,MAAMW,cAAc,GAAGZ,OAAO,EAAE,CAAC;IACjC,MAAMa,QAAQT,MAAMtB,GAAG,CAAC,CAAC0B;QACvB,IAAIG,YAAY/C,aAAaH,SAAS+C,OAAO;YAC3C,IAAIG,YAAY,qBAAqBrB,MAAMC,qBAAqB,GAAG;YACnE,OAAO,GAAGqB,cAAcD,QAAQ,CAAC,EAAElB,YAAYe,MAAMI,aAAatB,OAAO,EAAE,CAAC;QAC9E;QACA,OAAO,GAAGsB,cAAcb,WAAWS,MAAMI,aAAa,MAAMtB,OAAO,CAAC,CAAC;IACvE;IACA,OAAO,CAAC,GAAG,EAAEuB,MAAM3B,IAAI,CAAC,MAAM,EAAE,EAAEc,OAAO,CAAC,CAAC;AAC7C;AAEA,SAASP,YAAYqB,GAA4B,EAAEd,MAAc,EAAEV,KAAmB;IACpF,MAAMyB,UAAUC,OAAOD,OAAO,CAACD,KAAKG,MAAM,CAAC,CAAC,GAAG9B,MAAM,GAAKA,UAAUvB;IACpE,IAAImD,QAAQV,MAAM,KAAK,GAAG,OAAO;IAEjC,MAAMO,cAAc,GAAGZ,OAAO,EAAE,CAAC;IACjC,MAAMa,QAAQE,QAAQjC,GAAG,CACvB,CAAC,CAACgB,KAAKX,MAAM,GACX,GAAGyB,cAAcf,SAASC,KAAK,EAAE,EAAEC,WAAWZ,OAAOyB,aAAad,KAAKR,OAAO,CAAC,CAAC;IAEpF,OAAO,CAAC,GAAG,EAAEuB,MAAM3B,IAAI,CAAC,MAAM,EAAE,EAAEc,OAAO,CAAC,CAAC;AAC7C"}
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/media/pullAspects.ts"],"sourcesContent":["import {validateMediaLibraryAssetAspect} from '@sanity/schema/_internal'\nimport {type SchemaValidationProblem} from '@sanity/types'\nimport startCase from 'lodash-es/startCase.js'\n\nimport {type StoredAspectDocument} from '../../services/mediaLibraries.js'\nimport {VALID_ASPECT_NAME} from './aspectName.js'\n\n/** Keys whose object members are schema definitions, printed wrapped in a definer call. */\nconst DEFINER_BY_PARENT_KEY: Record<string, string> = {\n fields: 'defineField',\n of: 'defineArrayMember',\n}\n\nconst IDENTIFIER_KEY = /^[A-Za-z_$][A-Za-z0-9_$]*$/\n\n/** Scalar arrays shorter than this print inline (e.g. `options.list`). */\nconst INLINE_ARRAY_MAX_WIDTH = 60\n\n/**\n * The stored `sanity.asset.aspect` document shape this migration reads.\n * Deliberately loose: documents may predate the config model (authored via\n * `sanity media deploy-aspect` or by hand) and carry fields the model has no\n * equivalent for.\n */\nexport type PullableAspectDocument = StoredAspectDocument\n\nexport interface GeneratedFieldModule {\n filename: string\n /** The `aspects.<name>` data key — module filename and config entry name. */\n name: string\n source: string\n status: 'generated'\n title: string\n warnings: string[]\n\n public?: boolean\n}\n\nexport interface SkippedAspect {\n id: string\n reasons: string[]\n status: 'skipped'\n validationErrors: SchemaValidationProblem[][]\n}\n\nexport type PullAspectOutcome = GeneratedFieldModule | SkippedAspect\n\n/**\n * Convert a page of stored aspect documents into field modules, one per field\n * name. Two stored documents can resolve to the same name (a legacy document\n * whose `_id` predates its `definition.name`), which would otherwise produce\n * the same module twice — the document whose `_id` matches the name wins, the\n * rest are reported as skipped. Shared by `sanity media pull-aspects` and the\n * init-time pull offer.\n *\n * @internal\n */\nexport function convertAspectDocuments(documents: PullableAspectDocument[]): {\n modules: GeneratedFieldModule[]\n skipped: SkippedAspect[]\n} {\n const skipped: SkippedAspect[] = []\n\n // First pass: convert every stored document.\n const candidates: Array<{module: GeneratedFieldModule; sourceId: string}> = []\n for (const doc of documents) {\n const outcome = aspectDocumentToFieldModule(doc)\n if (outcome.status === 'skipped') {\n skipped.push(outcome)\n } else {\n candidates.push({module: outcome, sourceId: String(doc._id)})\n }\n }\n\n // Second pass: pick one winner per name.\n const byName = new Map<string, Array<{module: GeneratedFieldModule; sourceId: string}>>()\n for (const candidate of candidates) {\n const group = byName.get(candidate.module.name) ?? []\n group.push(candidate)\n byName.set(candidate.module.name, group)\n }\n const modules: GeneratedFieldModule[] = []\n for (const [name, group] of byName) {\n const winner = group.find((candidate) => candidate.sourceId === name) ?? group[0]\n modules.push(winner.module)\n for (const loser of group) {\n if (loser === winner) continue\n skipped.push({\n id: loser.sourceId,\n reasons: [`Also defines \"${name}\" — generated from \"${winner.sourceId}\" instead`],\n status: 'skipped',\n validationErrors: [],\n })\n }\n }\n\n return {modules, skipped}\n}\n\n/**\n * Codegen one stored aspect document into a `src/fields/<name>.tsx` field\n * module for a Media Library config app.\n *\n * Stored aspects are migration-ready by construction: `definition` is the\n * JSON-serialized `defineField(...)` value with functions and component\n * references already stripped, so generation is mechanical pretty-printing\n * into a `defineField({...})` call (nested `fields`/`of` members wrapped in\n * `defineField`/`defineArrayMember`, matching hand-authored style).\n *\n * Edge cases handled here, not silently:\n *\n * - `_id` vs `definition.name` mismatch: the module is generated under\n * `definition.name` — the `aspects.<name>` key existing asset data lives\n * under. Normalizing onto `_id` instead would silently orphan that data.\n * The old document (keyed `_id`) is reported for manual deletion.\n * - `assetType` has no equivalent in the config model; a document carrying it\n * generates with a warning that the scoping is lost.\n * - Definitions failing current schema validation are skipped with the\n * validation errors, mirroring `sanity media deploy-aspect`.\n *\n * Pure (no I/O): the command decides where modules are written.\n *\n * @internal\n */\nexport function aspectDocumentToFieldModule(doc: PullableAspectDocument): PullAspectOutcome {\n const {_id} = doc\n\n if (!isRecord(doc.definition)) {\n return {\n id: _id,\n reasons: ['The stored document has no field definition object'],\n status: 'skipped',\n validationErrors: [],\n }\n }\n\n const definitionName = typeof doc.definition.name === 'string' ? doc.definition.name : undefined\n const name = definitionName ?? _id\n\n if (!VALID_ASPECT_NAME.test(name)) {\n return {\n id: _id,\n reasons: [\n `\"${name}\" is not a valid field name (${VALID_ASPECT_NAME}) — it becomes the module name and the aspects.<name> key on assets`,\n ],\n status: 'skipped',\n validationErrors: [],\n }\n }\n\n const warnings: string[] = []\n\n if (definitionName === undefined) {\n warnings.push(`The stored definition has no name — using the document _id \"${_id}\"`)\n } else if (definitionName !== _id) {\n warnings.push(\n `Stored _id \"${_id}\" and definition name \"${definitionName}\" differ. Generated as ` +\n `\"${definitionName}\" — the aspects.<name> key existing asset data lives under; using ` +\n `\"${_id}\" would orphan that data. Deploying the config creates \"${definitionName}\" ` +\n `and deletes the old \"${_id}\" document.`,\n )\n }\n\n if (doc.assetType !== undefined && doc.assetType !== null) {\n warnings.push(\n `The stored document scopes the aspect by assetType (${JSON.stringify(doc.assetType)}), ` +\n `which has no equivalent in the config model — the generated field applies to all ` +\n `asset types, and syncing the config drops the scoping.`,\n )\n }\n\n // Normalize the name in before validating, so a document that only carries\n // its name as `_id` isn't rejected for the missing property.\n const definition: Record<string, unknown> = definitionName\n ? doc.definition\n : {name, ...doc.definition}\n\n const [valid, validationErrors] = validateMediaLibraryAssetAspect(definition)\n if (!valid) {\n return {\n id: _id,\n reasons: ['The stored definition fails schema validation'],\n status: 'skipped',\n validationErrors,\n }\n }\n\n return {\n // .tsx although the generated content has no JSX: field modules are\n // expected to grow custom input components (the one thing the stored\n // aspect could not carry), and a later rename would also mean fixing the\n // `src:` entry in sanity.cli.ts. Matches the template's example modules.\n filename: `${name}.tsx`,\n name,\n ...(typeof doc.public === 'boolean' ? {public: doc.public} : {}),\n source: printFieldModule(definition),\n status: 'generated',\n title: typeof definition.title === 'string' ? definition.title : startCase(name),\n warnings,\n }\n}\n\n/**\n * The paste-ready `fields: [...]` entries for `sanity.cli.ts`, one line per\n * generated module. When `writtenPaths` (module name to root-relative path)\n * has an entry for a module, that path wins — the module may have replaced an\n * existing file (e.g. a `.tsx` variant) rather than landing at the default\n * `<srcDir>/<filename>` location.\n *\n * @internal\n */\nexport function formatFieldEntries(\n modules: GeneratedFieldModule[],\n srcDir: string,\n writtenPaths?: Map<string, string>,\n): string {\n const dir = srcDir.replaceAll('\\\\', '/').replace(/\\/+$/, '')\n return modules\n .map((module) => {\n const src =\n writtenPaths?.get(module.name)?.replaceAll('\\\\', '/') ?? `${dir}/${module.filename}`\n const publicPart = module.public === undefined ? '' : `, public: ${module.public}`\n return `{name: '${module.name}', src: './${src}', title: ${quote(module.title)}${publicPart}},`\n })\n .join('\\n')\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\ninterface PrinterState {\n usesDefineArrayMember: boolean\n}\n\nfunction printFieldModule(definition: Record<string, unknown>): string {\n const state: PrinterState = {usesDefineArrayMember: false}\n const literal = printObject(definition, '', state)\n const imports = state.usesDefineArrayMember ? 'defineArrayMember, defineField' : 'defineField'\n\n return `import {${imports}} from 'sanity'\\n\\nexport default defineField(${literal})\\n`\n}\n\nfunction quote(value: string): string {\n const escaped = value\n .replaceAll('\\\\', String.raw`\\\\`)\n .replaceAll(\"'\", String.raw`\\'`)\n .replaceAll('\\n', String.raw`\\n`)\n .replaceAll('\\r', String.raw`\\r`)\n .replaceAll('\\t', String.raw`\\t`)\n return `'${escaped}'`\n}\n\nfunction printKey(key: string): string {\n return IDENTIFIER_KEY.test(key) ? key : quote(key)\n}\n\nfunction printValue(\n value: unknown,\n indent: string,\n parentKey: string | null,\n state: PrinterState,\n): string {\n if (value === null) return 'null'\n if (typeof value === 'string') return quote(value)\n if (typeof value === 'number' || typeof value === 'boolean') return String(value)\n if (Array.isArray(value)) return printArray(value, indent, parentKey, state)\n if (isRecord(value)) return printObject(value, indent, state)\n // Stored definitions are JSON documents; anything else cannot occur.\n throw new TypeError(`Cannot print value of type ${typeof value}`)\n}\n\nfunction printArray(\n items: unknown[],\n indent: string,\n parentKey: string | null,\n state: PrinterState,\n): string {\n if (items.length === 0) return '[]'\n\n const allScalar = items.every(\n (item) => item === null || ['boolean', 'number', 'string'].includes(typeof item),\n )\n if (allScalar) {\n const inline = `[${items.map((item) => printValue(item, indent, null, state)).join(', ')}]`\n if (inline.length <= INLINE_ARRAY_MAX_WIDTH) return inline\n }\n\n const definer = parentKey === null ? undefined : DEFINER_BY_PARENT_KEY[parentKey]\n const innerIndent = `${indent} `\n const lines = items.map((item) => {\n if (definer !== undefined && isRecord(item)) {\n if (definer === 'defineArrayMember') state.usesDefineArrayMember = true\n return `${innerIndent}${definer}(${printObject(item, innerIndent, state)}),`\n }\n return `${innerIndent}${printValue(item, innerIndent, null, state)},`\n })\n return `[\\n${lines.join('\\n')}\\n${indent}]`\n}\n\nfunction printObject(obj: Record<string, unknown>, indent: string, state: PrinterState): string {\n const entries = Object.entries(obj).filter(([, value]) => value !== undefined)\n if (entries.length === 0) return '{}'\n\n const innerIndent = `${indent} `\n const lines = entries.map(\n ([key, value]) =>\n `${innerIndent}${printKey(key)}: ${printValue(value, innerIndent, key, state)},`,\n )\n return `{\\n${lines.join('\\n')}\\n${indent}}`\n}\n"],"names":["validateMediaLibraryAssetAspect","startCase","VALID_ASPECT_NAME","DEFINER_BY_PARENT_KEY","fields","of","IDENTIFIER_KEY","INLINE_ARRAY_MAX_WIDTH","convertAspectDocuments","documents","skipped","candidates","doc","outcome","aspectDocumentToFieldModule","status","push","module","sourceId","String","_id","byName","Map","candidate","group","get","name","set","modules","winner","find","loser","id","reasons","validationErrors","isRecord","definition","definitionName","undefined","test","warnings","assetType","JSON","stringify","valid","filename","public","source","printFieldModule","title","formatFieldEntries","srcDir","writtenPaths","dir","replaceAll","replace","map","src","publicPart","quote","join","value","Array","isArray","state","usesDefineArrayMember","literal","printObject","imports","escaped","raw","printKey","key","printValue","indent","parentKey","printArray","TypeError","items","length","allScalar","every","item","includes","inline","definer","innerIndent","lines","obj","entries","Object","filter"],"mappings":"AAAA,SAAQA,+BAA+B,QAAO,2BAA0B;AAExE,OAAOC,eAAe,yBAAwB;AAG9C,SAAQC,iBAAiB,QAAO,kBAAiB;AAEjD,yFAAyF,GACzF,MAAMC,wBAAgD;IACpDC,QAAQ;IACRC,IAAI;AACN;AAEA,MAAMC,iBAAiB;AAEvB,wEAAwE,GACxE,MAAMC,yBAAyB;AA+B/B;;;;;;;;;CASC,GACD,OAAO,SAASC,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