payload-live-preview 2.0.0 → 2.0.2

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.
Files changed (92) hide show
  1. package/README.md +41 -34
  2. package/dist/adapters/astro/RichText.astro +1 -1
  3. package/dist/adapters/astro/index.d.ts +8 -8
  4. package/dist/adapters/astro/index.js +1 -1
  5. package/dist/adapters/astro/index.js.map +1 -1
  6. package/dist/adapters/astro/middleware-entry.d.ts +3 -3
  7. package/dist/adapters/astro/middleware-entry.js +1 -1
  8. package/dist/adapters/astro/middleware-entry.js.map +1 -1
  9. package/dist/adapters/nextjs/index.d.ts +2 -2
  10. package/dist/adapters/nextjs/index.js +1 -1
  11. package/dist/adapters/nextjs/index.js.map +1 -1
  12. package/dist/adapters/nuxt/index.d.ts +4 -4
  13. package/dist/adapters/nuxt/index.js +1 -1
  14. package/dist/adapters/nuxt/index.js.map +1 -1
  15. package/dist/adapters/nuxt/module.d.ts +13 -5
  16. package/dist/adapters/nuxt/module.js.map +1 -1
  17. package/dist/adapters/react/index.d.ts +8 -6
  18. package/dist/adapters/react/index.js.map +1 -1
  19. package/dist/adapters/sveltekit/index.d.ts +5 -5
  20. package/dist/adapters/sveltekit/index.js +1 -1
  21. package/dist/adapters/sveltekit/index.js.map +1 -1
  22. package/dist/adapters/vue/index.d.ts +3 -3
  23. package/dist/adapters/vue/index.js.map +1 -1
  24. package/dist/annotate.js +1 -1
  25. package/dist/annotate.js.map +1 -1
  26. package/dist/client.cjs +1 -1
  27. package/dist/client.cjs.map +1 -1
  28. package/dist/client.js +1 -1
  29. package/dist/client.js.map +1 -1
  30. package/dist/codegen-astro.d.ts +4 -1
  31. package/dist/codegen-astro.js.map +1 -1
  32. package/dist/codegen-cli.js +1 -1
  33. package/dist/codegen-cli.js.map +1 -1
  34. package/dist/codegen.cjs +1 -1
  35. package/dist/codegen.cjs.map +1 -1
  36. package/dist/codegen.js +1 -1
  37. package/dist/codegen.js.map +1 -1
  38. package/dist/core.cjs +1 -1
  39. package/dist/core.cjs.map +1 -1
  40. package/dist/core.d.cts +1 -1
  41. package/dist/core.d.ts +1 -1
  42. package/dist/core.js +1 -1
  43. package/dist/core.js.map +1 -1
  44. package/dist/doctor-cli.d.ts +1 -1
  45. package/dist/doctor-cli.js +1 -1
  46. package/dist/doctor-cli.js.map +1 -1
  47. package/dist/doctor.d.ts +4 -2
  48. package/dist/doctor.js +1 -1
  49. package/dist/doctor.js.map +1 -1
  50. package/dist/{fragment-endpoint-3Mlz7GDz.d.ts → fragment-endpoint-DATKU183.d.ts} +2 -2
  51. package/dist/fragment.cjs.map +1 -1
  52. package/dist/fragment.d.cts +6 -3
  53. package/dist/fragment.d.ts +6 -3
  54. package/dist/fragment.js.map +1 -1
  55. package/dist/index.cjs +1 -1
  56. package/dist/index.cjs.map +1 -1
  57. package/dist/index.d.cts +10 -10
  58. package/dist/index.d.ts +10 -10
  59. package/dist/index.js +1 -1
  60. package/dist/index.js.map +1 -1
  61. package/dist/lean.cjs +1 -1
  62. package/dist/lean.cjs.map +1 -1
  63. package/dist/lean.d.cts +3 -3
  64. package/dist/lean.d.ts +3 -3
  65. package/dist/lean.js +1 -1
  66. package/dist/lean.js.map +1 -1
  67. package/dist/lexical.cjs +1 -1
  68. package/dist/lexical.cjs.map +1 -1
  69. package/dist/lexical.d.cts +11 -1
  70. package/dist/lexical.d.ts +11 -1
  71. package/dist/lexical.js +1 -1
  72. package/dist/lexical.js.map +1 -1
  73. package/dist/{locals-DBXDMxOA.d.ts → locals-CNUGYbA_.d.ts} +1 -1
  74. package/dist/{middleware-Bx9I7PXW.d.ts → middleware-CWObDO37.d.ts} +2 -2
  75. package/dist/migrate.d.ts +6 -0
  76. package/dist/migrate.js +1 -1
  77. package/dist/migrate.js.map +1 -1
  78. package/dist/{options-BW1eqXvc.d.ts → options-uHKrDM2U.d.ts} +2 -1
  79. package/dist/plugins.cjs +1 -1
  80. package/dist/plugins.cjs.map +1 -1
  81. package/dist/plugins.js +1 -1
  82. package/dist/plugins.js.map +1 -1
  83. package/dist/{probe-CELeUciC.d.ts → probe-DqaItcwX.d.ts} +15 -0
  84. package/dist/server.cjs.map +1 -1
  85. package/dist/server.d.cts +1 -1
  86. package/dist/server.d.ts +1 -1
  87. package/dist/server.js.map +1 -1
  88. package/dist/structural.cjs +2 -2
  89. package/dist/structural.cjs.map +1 -1
  90. package/dist/structural.js +2 -2
  91. package/dist/structural.js.map +1 -1
  92. package/package.json +6 -4
@@ -1 +1 @@
1
- {"version":3,"file":"codegen.cjs","names":["toPascalCase","slug","split","filter","Boolean","map","part","charAt","toUpperCase","slice","join","tsMorph","IDENTIFIER","nestedTypeName","parent","child","emitFieldMember","field","lines","options","markLocalizedAsDeprecated","localized","push","optional","required","name","test","replace","kind","hasMany","typeRef","blocks","length","block","typeName","base","target","literal","option","renderFieldType","emitBlockInterface","fields","emitAuxiliaries","prefix","seen","auxName","has","add","inner","blockTypeName","emitSlug","emitMap","slugs","emitTypes","schema","header","Set","globals","collections","slugAliases","collect","basePath","out","path","entry","buildPreviewInventory","loadTsMorph","createRequire","document","require","pathToFileURL","__filename","href","_documentCurrentScript","tagName","src","URL","baseURI","error","Error","cause","tsNode","Node","reportSkip","context","node","why","diagnostics","text","getText","snippet","getSourceFile","getBaseName","String","getStartLineNumber","where","unwrap","current","isParenthesizedExpression","isAsExpression","isSatisfiesExpression","isNonNullExpression","isTypeAssertion","getExpression","followAlias","declaration","isImportSpecifier","isImportClause","isNamespaceImport","isExportSpecifier","aliased","getSymbol","getAliasedSymbol","getDeclarations","definitionsOf","identifier","definitions","getDefinitionNodes","flatMap","valueOf","isVariableDeclaration","isPropertyAssignment","getInitializer","isExportAssignment","isShorthandPropertyAssignment","getNameNode","propertyValue","property","getProperty","hasProperty","resolveToObjectLiteral","isObjectLiteralExpression","isCallExpression","getArguments","isIdentifier","resolved","isPropertyAccessExpression","owner","getName","resolveToArrayLiteral","isArrayLiteralExpression","expandElements","array","element","getElements","isSpreadElement","expanded","readStringProperty","value","isStringLiteral","isNoSubstitutionTemplateLiteral","getLiteralValue","readBooleanProperty","isTrueLiteral","isFalseLiteral","readArrayProperty","readRelationTarget","STRUCTURAL_SENTINEL","STRUCTURAL_TYPES","SCALAR_TYPE_MAP","textarea","email","richText","number","checkbox","date","code","point","HAS_MANY_SCALARS","extractFields","extractField","nestedFields","extractTabs","tabs","tab","extractBlocks","readOptions","type","declaredValue","extractSlugList","configLiteral","key","extractSchema","project","Project","tsConfigFilePath","skipAddingFilesFromTsConfig","sourceFile","addSourceFileAtPathIfExists","configPath","resolveSourceFileDependencies","defaultExport","getDefaultExportSymbol","call","getDescendantsOfKind","SyntaxKind","CallExpression","callee","findConfigLiteral","ELEMENT","ONLY_INTERPOLATION","ANY_INTERPOLATION","MEMBER_CHAIN","FIELD_ATTRIBUTE","lineAt","source","index","line","position","charCodeAt","pathOf","chain","indexOf","describe","expression","flat","trim","refusalReason","paths","trimmed","scanTemplate","candidates","refusals","match","matchAll","tag","attributes","content","includes","only","exec","reason","insertAt","fieldAttribute","candidate","applyAnnotations","render","sort","a","b","annotatablePaths","inventory","async","writeOut","mkdir","dirname","recursive","writeFile","read","io","readFile","write","root","cwd","process","files","file","changed","relative","annotations","annotationCount","reduce","total","refusalCount","written","bindings","byKey","Map","entries","item","set","f","binding","get","bound","reportUnbound","result","annotation","refusal","verb","absolute","isAbsolute","resolve","outFile","inventoryFile","targets","empty","JSON","stringify"],"sources":["../src/codegen/parser/names.ts","../src/codegen/emit/emit-types.ts","../src/codegen/parser/resolve.ts","../src/codegen/inventory.ts","../src/codegen/parser/extract-field.ts","../src/codegen/parser/extract-schema.ts","../src/codegen/annotate/scan.ts","../src/codegen/annotate/index.ts","../src/codegen/index.ts"],"sourcesContent":["/** Naming shared by the parser and the emitter. */\n\nexport function toPascalCase(slug: string): string {\n return slug\n .split(/[-_\\s]+/u)\n .filter(Boolean)\n .map((part) => part.charAt(0).toUpperCase() + part.slice(1))\n .join('');\n}\n","/**\n * Render an `ExtractedSchema` as one self-contained TypeScript file: an\n * interface per global and collection, nested interfaces for groups, arrays\n * and blocks, and the `PayloadGlobals`/`PayloadCollections`/`PayloadSlug` maps.\n */\nimport { toPascalCase } from '../parser/names';\nimport type {\n ExtractedBlock,\n ExtractedField,\n ExtractedSchema,\n ExtractedSlug,\n} from '../parser/types';\n\nexport interface EmitOptions {\n /** When true, localized fields carry a `@localized` JSDoc marker. */\n readonly markLocalizedAsDeprecated?: boolean;\n /** Header text at the top of the output. */\n readonly header?: string;\n}\n\nconst DEFAULT_HEADER =\n '// Auto-generated by payload-live-preview/codegen.\\n' +\n '// Do not edit by hand — run `pll-codegen` to regenerate.\\n' +\n '/* eslint-disable */';\nconst IDENTIFIER = /^[A-Za-z_$][\\w$]*$/u;\n\nfunction memberName(name: string): string {\n if (IDENTIFIER.test(name)) return name;\n return `'${name.replace(/\\\\/gu, '\\\\\\\\').replace(/'/gu, \"\\\\'\")}'`;\n}\n\nfunction nestedTypeName(parent: string, child: string): string {\n return `${parent}${toPascalCase(child)}`;\n}\n\nfunction renderFieldType(field: ExtractedField, parent: string): string {\n switch (field.kind) {\n case 'scalar':\n return field.hasMany === true ? `${field.typeRef}[]` : field.typeRef;\n case 'array':\n return `${nestedTypeName(parent, field.name)}[]`;\n case 'blocks': {\n if (field.blocks.length === 0) return 'unknown[]';\n const variants = field.blocks\n .map((block) => nestedTypeName(nestedTypeName(parent, field.name), block.typeName))\n .join(' | ');\n return `(${variants})[]`;\n }\n case 'group':\n return nestedTypeName(parent, field.name);\n case 'relationship': {\n const target =\n typeof field.target === 'string'\n ? `'${field.target}'`\n : field.target.map((slug) => `'${slug}'`).join(' | ');\n const base = `PayloadRelationship<${target}>`;\n return field.hasMany ? `${base}[]` : base;\n }\n case 'upload':\n return field.hasMany === true ? 'PayloadMedia[]' : 'PayloadMedia';\n case 'json':\n return 'unknown';\n case 'select': {\n if (field.options.length === 0) return field.hasMany ? 'string[]' : 'string';\n const literal = field.options.map((option) => `'${option}'`).join(' | ');\n return field.hasMany ? `(${literal})[]` : literal;\n }\n }\n}\n\nfunction emitFieldMember(\n field: ExtractedField,\n parent: string,\n lines: string[],\n options: EmitOptions,\n): void {\n if (options.markLocalizedAsDeprecated === true && field.localized) {\n lines.push(' /** @localized */');\n }\n const optional = field.required ? '' : '?';\n lines.push(` ${memberName(field.name)}${optional}: ${renderFieldType(field, parent)};`);\n}\n\nfunction emitBlockInterface(\n typeName: string,\n block: ExtractedBlock,\n lines: string[],\n options: EmitOptions,\n): void {\n lines.push(`export interface ${typeName} {`);\n lines.push(` blockType: '${block.slug}';`);\n for (const field of block.fields) emitFieldMember(field, typeName, lines, options);\n lines.push('}', '');\n}\n\nfunction emitAuxiliaries(\n prefix: string,\n fields: readonly ExtractedField[],\n lines: string[],\n seen: Set<string>,\n options: EmitOptions,\n): void {\n for (const field of fields) {\n const auxName = nestedTypeName(prefix, field.name);\n if (field.kind === 'array' || field.kind === 'group') {\n if (seen.has(auxName)) continue;\n seen.add(auxName);\n emitAuxiliaries(auxName, field.fields, lines, seen, options);\n lines.push(`export interface ${auxName} {`);\n for (const inner of field.fields) emitFieldMember(inner, auxName, lines, options);\n lines.push('}', '');\n } else if (field.kind === 'blocks') {\n for (const block of field.blocks) {\n const blockTypeName = nestedTypeName(auxName, block.typeName);\n if (seen.has(blockTypeName)) continue;\n seen.add(blockTypeName);\n emitAuxiliaries(blockTypeName, block.fields, lines, seen, options);\n emitBlockInterface(blockTypeName, block, lines, options);\n }\n }\n }\n}\n\nfunction emitSlug(\n slug: ExtractedSlug,\n lines: string[],\n seen: Set<string>,\n options: EmitOptions,\n): void {\n emitAuxiliaries(slug.typeName, slug.fields, lines, seen, options);\n lines.push(`export interface ${slug.typeName} {`);\n for (const field of slug.fields) emitFieldMember(field, slug.typeName, lines, options);\n lines.push('}');\n}\n\nfunction emitMap(name: string, slugs: readonly ExtractedSlug[], lines: string[]): void {\n if (slugs.length === 0) return;\n lines.push(`export type ${name} = {`);\n for (const slug of slugs) lines.push(` '${slug.slug}': ${slug.typeName};`);\n lines.push('};', '');\n}\n\n/** @internal */\nexport function emitTypes(schema: ExtractedSchema, options: EmitOptions = {}): string {\n const lines: string[] = [options.header ?? DEFAULT_HEADER, ''];\n lines.push('import type { PayloadMedia, PayloadRelationship } from \"payload-live-preview\";', '');\n const seen = new Set<string>();\n for (const slug of [...schema.globals, ...schema.collections]) {\n emitSlug(slug, lines, seen, options);\n lines.push('');\n }\n emitMap('PayloadGlobals', schema.globals, lines);\n emitMap('PayloadCollections', schema.collections, lines);\n const slugAliases: string[] = [];\n if (schema.globals.length > 0) slugAliases.push('keyof PayloadGlobals');\n if (schema.collections.length > 0) slugAliases.push('keyof PayloadCollections');\n if (slugAliases.length > 0) {\n lines.push(`export type PayloadSlug = ${slugAliases.join(' | ')};`, '');\n }\n return lines.join('\\n').replace(/\\n{3,}/gu, '\\n\\n');\n}\n","/**\n * Resolving the shapes a Payload config takes — literals, identifiers,\n * imports, wrappers, spreads — to the literals the extractors read. Every\n * shape that cannot be resolved becomes a diagnostic, never a silent gap.\n */\nimport { createRequire } from 'node:module';\nimport type * as TsMorphModule from 'ts-morph';\nimport type { ArrayLiteralExpression, Identifier, Node, ObjectLiteralExpression } from 'ts-morph';\n\nlet tsMorph: typeof TsMorphModule | undefined;\n\n/**\n * ts-morph on first use. It is an optional peer because it reads a Payload\n * config, and nothing else here needs a TypeScript compiler: an entry that only\n * prints its help, or refuses a usage error, must load without it. A static\n * import would not allow that — esbuild hoists an external import to the top of\n * the bundle even out of a dynamically imported module, so the binary would\n * resolve the peer before parsing its first flag. `pll migrate` loads it the\n * same way (src/migrate/ast.ts).\n */\nexport function loadTsMorph(): typeof TsMorphModule {\n if (tsMorph === undefined) {\n try {\n tsMorph = createRequire(import.meta.url)('ts-morph') as typeof TsMorphModule;\n } catch (error) {\n throw new Error('pll-codegen needs ts-morph: npm install --save-dev ts-morph', {\n cause: error,\n });\n }\n }\n return tsMorph;\n}\n\n/** The `Node` type guards, which every extractor reaches for. */\nexport function tsNode(): typeof TsMorphModule.Node {\n return loadTsMorph().Node;\n}\n\nexport interface ExtractContext {\n readonly diagnostics: string[];\n}\n\nfunction where(node: Node): string {\n return `${node.getSourceFile().getBaseName()}:${String(node.getStartLineNumber())}`;\n}\n\nfunction snippet(node: Node): string {\n const text = node.getText().replace(/\\s+/gu, ' ');\n return text.length > 60 ? `${text.slice(0, 57)}...` : text;\n}\n\nexport function reportSkip(context: ExtractContext, node: Node, why: string): void {\n context.diagnostics.push(`Skipped \"${snippet(node)}\" at ${where(node)}: ${why}.`);\n}\n\nfunction unwrap(node: Node): Node {\n let current = node;\n while (\n tsNode().isParenthesizedExpression(current) ||\n tsNode().isAsExpression(current) ||\n tsNode().isSatisfiesExpression(current) ||\n tsNode().isNonNullExpression(current) ||\n tsNode().isTypeAssertion(current)\n ) {\n current = current.getExpression();\n }\n return current;\n}\n\n/** An import or re-export binds a name but holds no value; the value is in the module it names. */\nfunction followAlias(declaration: Node): readonly Node[] {\n const isAlias =\n tsNode().isImportSpecifier(declaration) ||\n tsNode().isImportClause(declaration) ||\n tsNode().isNamespaceImport(declaration) ||\n tsNode().isExportSpecifier(declaration);\n if (!isAlias) return [declaration];\n const aliased = declaration.getSymbol()?.getAliasedSymbol();\n return aliased?.getDeclarations() ?? [declaration];\n}\n\n/** Follows imports through the language service; the binder is the fallback for what it cannot see. */\nfunction definitionsOf(identifier: Identifier): readonly Node[] {\n const definitions = identifier.getDefinitionNodes();\n const found =\n definitions.length > 0 ? definitions : (identifier.getSymbol()?.getDeclarations() ?? []);\n return found.flatMap(followAlias);\n}\n\nfunction valueOf(declaration: Node): Node | undefined {\n if (tsNode().isVariableDeclaration(declaration) || tsNode().isPropertyAssignment(declaration)) {\n return declaration.getInitializer();\n }\n if (tsNode().isExportAssignment(declaration)) return declaration.getExpression();\n if (tsNode().isShorthandPropertyAssignment(declaration)) return declaration.getNameNode();\n return undefined;\n}\n\n/** The value of a property, treating `{ fields }` shorthand as a reference to resolve. */\nexport function propertyValue(literal: ObjectLiteralExpression, name: string): Node | undefined {\n const property = literal.getProperty(name);\n if (property === undefined) return undefined;\n if (tsNode().isPropertyAssignment(property)) return property.getInitializer();\n if (tsNode().isShorthandPropertyAssignment(property)) return property.getNameNode();\n return undefined;\n}\n\nexport function hasProperty(literal: ObjectLiteralExpression, name: string): boolean {\n return literal.getProperty(name) !== undefined;\n}\n\nexport function resolveToObjectLiteral(\n node: Node | undefined,\n seen = new Set<Node>(),\n): ObjectLiteralExpression | undefined {\n if (node === undefined || seen.has(node)) return undefined;\n seen.add(node);\n const target = unwrap(node);\n if (tsNode().isObjectLiteralExpression(target)) return target;\n // `buildConfig({...})`, `defineConfig({...})`: the literal is the first argument.\n if (tsNode().isCallExpression(target)) {\n return resolveToObjectLiteral(target.getArguments()[0], seen);\n }\n if (tsNode().isIdentifier(target)) {\n for (const declaration of definitionsOf(target)) {\n const resolved = resolveToObjectLiteral(valueOf(declaration), seen);\n if (resolved !== undefined) return resolved;\n }\n }\n if (tsNode().isPropertyAccessExpression(target)) {\n const owner = resolveToObjectLiteral(target.getExpression(), seen);\n if (owner !== undefined) {\n return resolveToObjectLiteral(propertyValue(owner, target.getName()), seen);\n }\n }\n return undefined;\n}\n\nexport function resolveToArrayLiteral(\n node: Node | undefined,\n seen = new Set<Node>(),\n): ArrayLiteralExpression | undefined {\n if (node === undefined || seen.has(node)) return undefined;\n seen.add(node);\n const target = unwrap(node);\n if (tsNode().isArrayLiteralExpression(target)) return target;\n if (tsNode().isIdentifier(target)) {\n for (const declaration of definitionsOf(target)) {\n const resolved = resolveToArrayLiteral(valueOf(declaration), seen);\n if (resolved !== undefined) return resolved;\n }\n }\n if (tsNode().isPropertyAccessExpression(target)) {\n const owner = resolveToObjectLiteral(target.getExpression(), seen);\n if (owner !== undefined) {\n return resolveToArrayLiteral(propertyValue(owner, target.getName()), seen);\n }\n }\n return undefined;\n}\n\n/** The elements of an array with every spread expanded; a spread that cannot be resolved is reported and dropped. */\nexport function expandElements(array: ArrayLiteralExpression, context: ExtractContext): Node[] {\n const out: Node[] = [];\n for (const element of array.getElements()) {\n if (!tsNode().isSpreadElement(element)) {\n out.push(element);\n continue;\n }\n const expanded = resolveToArrayLiteral(element.getExpression());\n if (expanded === undefined) {\n reportSkip(\n context,\n element,\n 'could not resolve the spread to an array literal, so its entries are missing',\n );\n continue;\n }\n out.push(...expandElements(expanded, context));\n }\n return out;\n}\n\nexport function readStringProperty(\n literal: ObjectLiteralExpression,\n name: string,\n): string | undefined {\n const value = propertyValue(literal, name);\n if (value === undefined) return undefined;\n const target = unwrap(value);\n if (tsNode().isStringLiteral(target) || tsNode().isNoSubstitutionTemplateLiteral(target)) {\n return target.getLiteralValue();\n }\n return undefined;\n}\n\nexport function readBooleanProperty(\n literal: ObjectLiteralExpression,\n name: string,\n): boolean | undefined {\n const value = propertyValue(literal, name);\n if (value === undefined) return undefined;\n const target = unwrap(value);\n if (tsNode().isTrueLiteral(target)) return true;\n if (tsNode().isFalseLiteral(target)) return false;\n return undefined;\n}\n\nexport function readArrayProperty(\n literal: ObjectLiteralExpression,\n name: string,\n): ArrayLiteralExpression | undefined {\n return resolveToArrayLiteral(propertyValue(literal, name));\n}\n\n/** `relationTo`: one slug, several, or `'unknown'` when it is not a literal. */\nexport function readRelationTarget(literal: ObjectLiteralExpression): string | readonly string[] {\n const value = propertyValue(literal, 'relationTo');\n if (value === undefined) return 'unknown';\n const target = unwrap(value);\n if (tsNode().isStringLiteral(target)) return target.getLiteralValue();\n const array = resolveToArrayLiteral(target);\n if (array === undefined) return 'unknown';\n return array\n .getElements()\n .map(unwrap)\n .filter((element) => tsNode().isStringLiteral(element))\n .map((element) => element.getLiteralValue());\n}\n","/**\n * Which schema fields a binding can address, spelled the way the runtime\n * resolves them. Paths follow `@schema/walker` exactly — bindings are matched\n * against that rule at runtime, so any other spelling would be wrong here.\n */\n\nimport type { ExtractedField, ExtractedSchema, ExtractedSlug } from './parser/types';\n\n/** Sentinel the parser gives an unnamed structural container. */\nconst STRUCTURAL_SENTINEL = '__structural';\n\n/** One addressable field, spelled the way a binding must spell it. */\nexport interface PreviewInventoryField {\n /** Runtime binding path, e.g. `hero.title` or `slides.*.caption`. */\n readonly path: string;\n /** Extracted field kind: `scalar`, `array`, `blocks`, `group`, … */\n readonly kind: ExtractedField['kind'];\n readonly localized: boolean;\n readonly required: boolean;\n}\n\nexport interface PreviewInventoryEntry {\n readonly slug: string;\n readonly typeName: string;\n readonly fields: readonly PreviewInventoryField[];\n}\n\nexport interface PreviewInventory {\n readonly globals: readonly PreviewInventoryEntry[];\n readonly collections: readonly PreviewInventoryEntry[];\n}\n\nfunction collect(\n fields: readonly ExtractedField[],\n basePath: string,\n out: PreviewInventoryField[],\n): void {\n for (const field of fields) {\n // No segment, but its children still belong to the parent's surface.\n if (field.kind === 'group' && field.name === STRUCTURAL_SENTINEL) {\n collect(field.fields, basePath, out);\n continue;\n }\n const path = basePath === '' ? field.name : `${basePath}.${field.name}`;\n out.push({\n path,\n kind: field.kind,\n localized: field.localized,\n required: field.required,\n });\n if (field.kind === 'group') {\n collect(field.fields, path, out);\n } else if (field.kind === 'array') {\n collect(field.fields, `${path}.*`, out);\n } else if (field.kind === 'blocks') {\n for (const block of field.blocks) {\n collect(block.fields, `${path}.*.${block.slug}`, out);\n }\n }\n }\n}\n\nfunction entry(slug: ExtractedSlug): PreviewInventoryEntry {\n const fields: PreviewInventoryField[] = [];\n collect(slug.fields, '', fields);\n return { slug: slug.slug, typeName: slug.typeName, fields };\n}\n\n/** Flatten an extracted schema into every path a binding may address. @internal */\nexport function buildPreviewInventory(schema: ExtractedSchema): PreviewInventory {\n return {\n globals: schema.globals.map(entry),\n collections: schema.collections.map(entry),\n };\n}\n\n/** A binding found in consumer markup, however that consumer found it. @internal */\nexport interface PreviewBindingReference {\n readonly kind: 'global' | 'collection';\n readonly slug: string;\n readonly path: string;\n /** Free-form origin for the diagnostic, e.g. `Hero.astro:42`. */\n readonly source?: string;\n}\n\n/** @internal */\nexport interface PreviewCoverageOptions {\n /** Also report schema fields no binding addresses; off, since a page may render a subset. */\n readonly reportUnbound?: boolean;\n}\n\n/** Cross-check bindings the consumer extracted against the inventory. @internal */\nexport function checkPreviewBindings(\n inventory: PreviewInventory,\n bindings: readonly PreviewBindingReference[],\n options: PreviewCoverageOptions = {},\n): readonly string[] {\n const diagnostics: string[] = [];\n const byKey = new Map<string, ReadonlySet<string>>();\n for (const [kind, entries] of [\n ['global', inventory.globals],\n ['collection', inventory.collections],\n ] as const) {\n for (const item of entries) {\n byKey.set(`${kind}:${item.slug}`, new Set(item.fields.map((f) => f.path)));\n }\n }\n\n const seen = new Map<string, Set<string>>();\n for (const binding of bindings) {\n const key = `${binding.kind}:${binding.slug}`;\n const where = binding.source === undefined ? '' : ` (${binding.source})`;\n const paths = byKey.get(key);\n if (paths === undefined) {\n diagnostics.push(`unknown ${binding.kind} \"${binding.slug}\"${where}`);\n continue;\n }\n if (!paths.has(binding.path)) {\n diagnostics.push(`${key} has no field \"${binding.path}\"${where}`);\n continue;\n }\n let bound = seen.get(key);\n if (bound === undefined) {\n bound = new Set<string>();\n seen.set(key, bound);\n }\n bound.add(binding.path);\n }\n\n if (options.reportUnbound === true) {\n for (const [key, paths] of byKey) {\n const bound = seen.get(key) ?? new Set<string>();\n for (const path of paths) {\n if (!bound.has(path)) diagnostics.push(`${key} field \"${path}\" is never bound`);\n }\n }\n }\n\n return diagnostics;\n}\n","/**\n * Field-level extraction: one Payload field literal → an `ExtractedField`,\n * recursing into groups, arrays, tabs and blocks.\n */\nimport type { ArrayLiteralExpression, ObjectLiteralExpression } from 'ts-morph';\nimport { toPascalCase } from './names';\nimport {\n expandElements,\n hasProperty,\n readArrayProperty,\n readBooleanProperty,\n readRelationTarget,\n readStringProperty,\n reportSkip,\n resolveToObjectLiteral,\n tsNode,\n type ExtractContext,\n} from './resolve';\nimport type { ExtractedBlock, ExtractedField, ExtractedScalarField } from './types';\n\n/** Name of an unnamed structural container; its fields flatten into the parent. */\nexport const STRUCTURAL_SENTINEL = '__structural';\nconst STRUCTURAL_TYPES = new Set(['tabs', 'row', 'collapsible']);\nconst SCALAR_TYPE_MAP: Readonly<Record<string, ExtractedScalarField['typeRef']>> = {\n text: 'string',\n textarea: 'string',\n email: 'string',\n richText: 'unknown',\n number: 'number',\n checkbox: 'boolean',\n date: 'string',\n code: 'string',\n point: '[number, number]',\n};\nconst HAS_MANY_SCALARS = new Set(['text', 'number']);\n\n/** Every field in `array`, spreads expanded and structural containers flattened. */\nexport function extractFields(\n array: ArrayLiteralExpression,\n context: ExtractContext,\n): ExtractedField[] {\n const out: ExtractedField[] = [];\n for (const element of expandElements(array, context)) {\n const literal = resolveToObjectLiteral(element);\n if (literal === undefined) {\n reportSkip(context, element, 'could not resolve the field to an object literal');\n continue;\n }\n const field = extractField(literal, context);\n if (field === undefined) continue;\n if (field.kind === 'group' && field.name === STRUCTURAL_SENTINEL) out.push(...field.fields);\n else out.push(field);\n }\n return out;\n}\n\nfunction nestedFields(literal: ObjectLiteralExpression, context: ExtractContext): ExtractedField[] {\n const array = readArrayProperty(literal, 'fields');\n if (array !== undefined) return extractFields(array, context);\n reportSkip(\n context,\n literal,\n hasProperty(literal, 'fields')\n ? 'its `fields` could not be resolved to an array literal'\n : 'it has no `fields`',\n );\n return [];\n}\n\nfunction extractTabs(literal: ObjectLiteralExpression, context: ExtractContext): ExtractedField[] {\n const tabs = readArrayProperty(literal, 'tabs');\n if (tabs === undefined) {\n reportSkip(context, literal, 'its `tabs` could not be resolved to an array literal');\n return [];\n }\n const out: ExtractedField[] = [];\n for (const element of expandElements(tabs, context)) {\n const tab = resolveToObjectLiteral(element);\n if (tab === undefined) {\n reportSkip(context, element, 'could not resolve the tab to an object literal');\n continue;\n }\n const name = readStringProperty(tab, 'name');\n const fields = nestedFields(tab, context);\n if (name === undefined) out.push(...fields);\n else out.push({ kind: 'group', name, required: false, localized: false, fields });\n }\n return out;\n}\n\nfunction extractBlocks(\n literal: ObjectLiteralExpression,\n context: ExtractContext,\n): ExtractedBlock[] {\n const blocks = readArrayProperty(literal, 'blocks');\n if (blocks === undefined) {\n reportSkip(context, literal, 'its `blocks` could not be resolved to an array literal');\n return [];\n }\n const out: ExtractedBlock[] = [];\n for (const element of expandElements(blocks, context)) {\n const block = resolveToObjectLiteral(element);\n if (block === undefined) {\n reportSkip(context, element, 'could not resolve the block to an object literal');\n continue;\n }\n const slug = readStringProperty(block, 'slug');\n if (slug === undefined) {\n reportSkip(context, element, 'a block needs a string `slug`');\n continue;\n }\n out.push({ slug, typeName: toPascalCase(slug), fields: nestedFields(block, context) });\n }\n return out;\n}\n\nfunction readOptions(literal: ObjectLiteralExpression, context: ExtractContext): string[] {\n const options = readArrayProperty(literal, 'options');\n if (options === undefined) {\n reportSkip(context, literal, 'its `options` could not be resolved to an array literal');\n return [];\n }\n const out: string[] = [];\n for (const element of expandElements(options, context)) {\n if (tsNode().isStringLiteral(element)) {\n out.push(element.getLiteralValue());\n continue;\n }\n const option = resolveToObjectLiteral(element);\n const value = option === undefined ? undefined : readStringProperty(option, 'value');\n if (value === undefined) reportSkip(context, element, 'an option needs a string or a `value`');\n else out.push(value);\n }\n return out;\n}\n\n/** One field, or `undefined` for a `ui` field (nothing to type) and for shapes reported as skipped. */\nexport function extractField(\n literal: ObjectLiteralExpression,\n context: ExtractContext,\n): ExtractedField | undefined {\n const type = readStringProperty(literal, 'type');\n if (type === undefined) {\n reportSkip(context, literal, 'it has no string `type`');\n return undefined;\n }\n if (type === 'ui') return undefined;\n const name = readStringProperty(literal, 'name');\n if (name === undefined && !STRUCTURAL_TYPES.has(type)) {\n reportSkip(context, literal, `a ${type} field needs a string \\`name\\``);\n return undefined;\n }\n const base = {\n name: name ?? STRUCTURAL_SENTINEL,\n required: readBooleanProperty(literal, 'required') ?? false,\n localized: readBooleanProperty(literal, 'localized') ?? false,\n };\n const hasMany = readBooleanProperty(literal, 'hasMany') ?? false;\n switch (type) {\n case 'array':\n return { ...base, kind: 'array', fields: nestedFields(literal, context) };\n case 'group':\n case 'row':\n case 'collapsible':\n return { ...base, kind: 'group', fields: nestedFields(literal, context) };\n case 'tabs':\n return { ...base, kind: 'group', fields: extractTabs(literal, context) };\n case 'blocks':\n return { ...base, kind: 'blocks', blocks: extractBlocks(literal, context) };\n case 'relationship':\n return { ...base, kind: 'relationship', target: readRelationTarget(literal), hasMany };\n case 'upload': {\n const target = readRelationTarget(literal);\n return {\n ...base,\n kind: 'upload',\n target: (typeof target === 'string' ? target : target[0]) ?? 'media',\n hasMany,\n };\n }\n case 'json':\n return { ...base, kind: 'json' };\n case 'select':\n case 'radio':\n return {\n ...base,\n kind: 'select',\n options: readOptions(literal, context),\n hasMany: type === 'select' && hasMany,\n };\n default:\n return {\n ...base,\n kind: 'scalar',\n typeRef: SCALAR_TYPE_MAP[type] ?? 'unknown',\n hasMany: HAS_MANY_SCALARS.has(type) && hasMany,\n };\n }\n}\n","/**\n * Schema-level extraction: open the config, find every collection and global,\n * walk into them. Lenient by design — a Payload config is a full TypeScript\n * program, so the common shapes are recognised and everything else becomes a\n * diagnostic rather than a silently empty type.\n */\nimport type { Node, ObjectLiteralExpression, Project, SourceFile } from 'ts-morph';\nimport { extractFields } from './extract-field';\nimport { toPascalCase } from './names';\nimport {\n expandElements,\n hasProperty,\n propertyValue,\n readArrayProperty,\n readStringProperty,\n reportSkip,\n resolveToArrayLiteral,\n resolveToObjectLiteral,\n loadTsMorph,\n tsNode,\n type ExtractContext,\n} from './resolve';\nimport type { ExtractedSchema, ExtractedSlug } from './types';\n\nexport interface ExtractSchemaOptions {\n /** Absolute or relative path to `payload.config.ts`. */\n readonly configPath: string;\n /** When provided, used instead of constructing a fresh ts-morph project. */\n readonly project?: Project;\n /** A `tsconfig.json` whose module resolution lets cross-file imports be followed. */\n readonly tsConfigFilePath?: string;\n}\n\n/**\n * What a default export declaration holds. TypeScript only ever declares the\n * `default` export as an export assignment, an export specifier, or a function\n * or class declaration — `export default config` keeps the variable's own\n * declaration out of it — so a variable declaration never arrives here.\n */\nfunction declaredValue(declaration: Node): Node | undefined {\n if (tsNode().isExportAssignment(declaration)) return declaration.getExpression();\n return undefined;\n}\n\nfunction findConfigLiteral(\n sourceFile: SourceFile,\n context: ExtractContext,\n): ObjectLiteralExpression | undefined {\n const defaultExport = sourceFile.getDefaultExportSymbol();\n if (defaultExport === undefined) {\n context.diagnostics.push('payload.config.ts has no default export.');\n return undefined;\n }\n for (const declaration of defaultExport.getDeclarations()) {\n const literal = resolveToObjectLiteral(declaredValue(declaration));\n if (literal !== undefined) return literal;\n }\n for (const call of sourceFile.getDescendantsOfKind(loadTsMorph().SyntaxKind.CallExpression)) {\n const callee = call.getExpression();\n if (!tsNode().isIdentifier(callee) || callee.getText() !== 'buildConfig') continue;\n const literal = resolveToObjectLiteral(call.getArguments()[0]);\n if (literal !== undefined) return literal;\n }\n return undefined;\n}\n\nfunction extractSlugList(\n configLiteral: ObjectLiteralExpression,\n key: 'globals' | 'collections',\n context: ExtractContext,\n): ExtractedSlug[] {\n const value = propertyValue(configLiteral, key);\n if (value === undefined) return [];\n const array = resolveToArrayLiteral(value);\n if (array === undefined) {\n reportSkip(context, value, `could not resolve \\`${key}\\` to an array literal`);\n return [];\n }\n const out: ExtractedSlug[] = [];\n for (const element of expandElements(array, context)) {\n const literal = resolveToObjectLiteral(element);\n if (literal === undefined) {\n reportSkip(context, element, 'could not resolve the config entry to an object literal');\n continue;\n }\n const slug = readStringProperty(literal, 'slug');\n if (slug === undefined) {\n reportSkip(context, element, 'the config entry has no string `slug`');\n continue;\n }\n const fields = readArrayProperty(literal, 'fields');\n if (fields === undefined) {\n reportSkip(\n context,\n literal,\n hasProperty(literal, 'fields')\n ? `the \\`fields\\` of \"${slug}\" could not be resolved to an array literal`\n : `\"${slug}\" has no \\`fields\\``,\n );\n }\n out.push({\n slug,\n typeName: toPascalCase(slug),\n fields: fields === undefined ? [] : extractFields(fields, context),\n });\n }\n return out;\n}\n\n/** @internal */\nexport function extractSchema(options: ExtractSchemaOptions): ExtractedSchema {\n const project =\n options.project ??\n new (loadTsMorph().Project)(\n options.tsConfigFilePath !== undefined\n ? { tsConfigFilePath: options.tsConfigFilePath }\n : { skipAddingFilesFromTsConfig: true },\n );\n const sourceFile = project.addSourceFileAtPathIfExists(options.configPath);\n if (sourceFile === undefined) {\n return { globals: [], collections: [], diagnostics: [`Could not open ${options.configPath}`] };\n }\n project.resolveSourceFileDependencies();\n const context: ExtractContext = { diagnostics: [] };\n const configLiteral = findConfigLiteral(sourceFile, context);\n if (configLiteral === undefined) {\n return {\n globals: [],\n collections: [],\n diagnostics: [\n ...context.diagnostics,\n 'Could not locate a buildConfig({...}) call or `export default {...}` in the config file.',\n ],\n };\n }\n const globals = extractSlugList(configLiteral, 'globals', context);\n const collections = extractSlugList(configLiteral, 'collections', context);\n return { globals, collections, diagnostics: context.diagnostics };\n}\n","/**\n * Find the places in a template where a field value is printed on its own, and\n * decide — never guess — which of them can carry a binding.\n *\n * The shape this recognises is deliberately narrow, and it is the same in every\n * template language the package adapts:\n *\n * ```\n * <h1>{page.title}</h1> Astro, JSX, Svelte\n * ```\n *\n * An element whose entire content is one member expression, rooted at some\n * variable, whose remaining path is a field the schema actually has. Everything\n * else — an interpolation next to text, a call, a ternary, a path the schema\n * does not know, a component instead of an element — is reported instead, with\n * the reason. A wrong `data-payload-field` is worse than a missing one: it makes\n * the runtime write a value into markup that was never meant for it.\n *\n * Markup rather than an AST on purpose. Astro and Svelte templates are not\n * TypeScript, so ts-morph would only cover the JSX third of the problem, and\n * three parsers would be three chances to disagree about which shape is safe.\n * The shape above is unambiguous enough to scan for.\n */\n\n/** A place that can carry a binding, with the attribute it should get. @internal */\nexport interface AnnotationCandidate {\n /** Offset where the attribute is inserted, inside the opening tag. */\n readonly insertAt: number;\n /** The binding path, as `data-payload-field` must spell it. */\n readonly path: string;\n /** 1-based line, for the report. */\n readonly line: number;\n readonly tag: string;\n}\n\n/** A place that looks like an output but was left alone, and why. */\nexport interface AnnotationRefusal {\n readonly line: number;\n readonly reason: string;\n /** The source of the interpolation, trimmed, for the report. */\n readonly expression: string;\n}\n\nexport interface ScanResult {\n readonly candidates: readonly AnnotationCandidate[];\n readonly refusals: readonly AnnotationRefusal[];\n}\n\nexport interface ScanOptions {\n /** Field paths the schema has, exactly as a binding must spell them. */\n readonly paths: ReadonlySet<string>;\n}\n\n/**\n * `<tag attrs>content</tag>` with no element inside it, the closing tag\n * repeating the name. Only lowercase tags: an uppercase one is a component,\n * whose children are its own business.\n */\nconst ELEMENT = /<([a-z][a-z0-9-]*)((?:\"[^\"]*\"|'[^']*'|[^>\"'])*)>([^<]*)<\\/\\1\\s*>/gu;\n\n/** The whole content is one interpolation, and nothing else. */\nconst ONLY_INTERPOLATION = /^\\s*\\{([^{}]*)\\}\\s*$/u;\n\n/** An interpolation somewhere in the content, which is a different case. */\nconst ANY_INTERPOLATION = /\\{([^{}]*)\\}/u;\n\n/** A plain member chain: `page.title`, `data.hero.eyebrow`. Nothing callable, nothing indexed. */\nconst MEMBER_CHAIN = /^[A-Za-z_$][\\w$]*(?:\\.[A-Za-z_$][\\w$]*)+$/u;\n\nconst FIELD_ATTRIBUTE = 'data-payload-field';\n\nfunction lineAt(source: string, index: number): number {\n let line = 1;\n for (let position = 0; position < index; position += 1) {\n if (source.charCodeAt(position) === 10) line += 1;\n }\n return line;\n}\n\n/**\n * The binding path a chain would address: everything after the root variable.\n * `page.hero.title` → `hero.title`, and a lone `title` is not a chain at all —\n * a bare identifier says nothing about which document it came from.\n */\nfunction pathOf(chain: string): string {\n return chain.slice(chain.indexOf('.') + 1);\n}\n\nfunction describe(expression: string): string {\n const flat = expression.replace(/\\s+/gu, ' ').trim();\n return flat.length > 60 ? `${flat.slice(0, 57)}…` : flat;\n}\n\n/** Why this interpolation cannot become a binding, in the words of the report. */\nfunction refusalReason(expression: string, paths: ReadonlySet<string>): string | undefined {\n const trimmed = expression.trim();\n if (trimmed.length === 0) return 'the element is empty';\n if (!MEMBER_CHAIN.test(trimmed)) {\n return 'not a plain field access — a call, an operator or an index cannot be traced to one field';\n }\n const path = pathOf(trimmed);\n if (!paths.has(path)) {\n return `the schema has no field \\`${path}\\`; the binding would name something that never arrives`;\n }\n return undefined;\n}\n\nexport function scanTemplate(source: string, options: ScanOptions): ScanResult {\n const candidates: AnnotationCandidate[] = [];\n const refusals: AnnotationRefusal[] = [];\n for (const match of source.matchAll(ELEMENT)) {\n const [, tag = '', attributes = '', content = ''] = match;\n const line = lineAt(source, match.index);\n if (attributes.includes(FIELD_ATTRIBUTE)) continue;\n const only = ONLY_INTERPOLATION.exec(content);\n if (only === null) {\n // A value printed beside a label — `Published {page.publishedAt}`. The\n // runtime writes an element's whole text, so a binding here would eat the\n // label; splitting the markup is a decision for whoever wrote it.\n const beside = ANY_INTERPOLATION.exec(content);\n if (beside !== null) {\n refusals.push({\n line,\n reason:\n 'the value is printed beside other content — a binding replaces the whole text, so the markup has to be split first',\n expression: describe(content),\n });\n }\n continue;\n }\n const expression = only[1] ?? '';\n const reason = refusalReason(expression, options.paths);\n if (reason !== undefined) {\n refusals.push({ line, reason, expression: describe(expression) });\n continue;\n }\n candidates.push({\n // After `<tag`, before whatever the element already carries.\n insertAt: match.index + 1 + tag.length,\n path: pathOf(expression.trim()),\n line,\n tag,\n });\n }\n return { candidates, refusals };\n}\n\n/** The attribute a candidate becomes: what `pll-codegen annotate` writes into a file. */\nexport function fieldAttribute(candidate: AnnotationCandidate): string {\n return `${FIELD_ATTRIBUTE}=\"${candidate.path}\"`;\n}\n\n/**\n * Apply the candidates back-to-front, so every earlier offset still holds.\n *\n * `render` decides what a candidate becomes, because the two callers write\n * different things from the same decision: the codemod writes the attribute\n * into the file a person reads, and the build-time annotator writes a call to\n * the authorization-bound helper. What may be annotated at all is decided in\n * one place — above — and never here.\n */\nexport function applyAnnotations(\n source: string,\n candidates: readonly AnnotationCandidate[],\n render: (candidate: AnnotationCandidate) => string = fieldAttribute,\n): string {\n let out = source;\n for (const candidate of [...candidates].sort((a, b) => b.insertAt - a.insertAt)) {\n out = `${out.slice(0, candidate.insertAt)} ${render(candidate)}${out.slice(candidate.insertAt)}`;\n }\n return out;\n}\n","/**\n * `pll-codegen annotate`: put `data-payload-field` where a template already\n * prints a field, and report every place it would have had to guess.\n *\n * The schema decides what exists — the same inventory `--inventory` writes, so\n * an annotation and a runtime binding spell a path the same way. What the tool\n * cannot attribute is listed, never invented: an unbound field costs an editor\n * one invisible edit, a wrongly bound one writes a value into the wrong element\n * on every keystroke.\n */\n\nimport { readFile, writeFile } from 'node:fs/promises';\nimport { relative } from 'node:path';\nimport type { PreviewInventory } from '../inventory';\nimport {\n applyAnnotations,\n scanTemplate,\n type AnnotationCandidate,\n type AnnotationRefusal,\n} from './scan';\n\nexport type { AnnotationCandidate, AnnotationRefusal } from './scan';\n\n/** Templates this scanner understands; a `.vue` template uses `{{ … }}` and is not one yet. @internal */\nexport const ANNOTATABLE_EXTENSIONS: readonly string[] = ['.astro', '.jsx', '.tsx', '.svelte'];\n\n/** @internal */\nexport interface AnnotateFileResult {\n readonly file: string;\n /** The annotated source; identical to the input when nothing was added. */\n readonly code: string;\n readonly annotations: readonly AnnotationCandidate[];\n readonly refusals: readonly AnnotationRefusal[];\n readonly changed: boolean;\n}\n\n/** @internal */\nexport interface AnnotateResult {\n readonly files: readonly AnnotateFileResult[];\n readonly annotationCount: number;\n readonly refusalCount: number;\n /** Whether the files were written; `false` is a dry run. */\n readonly written: boolean;\n}\n\n/** @internal */\nexport interface AnnotateOptions {\n /** Template files to read. */\n readonly files: readonly string[];\n /** The schema's addressable paths, from `generateTypes().inventory`. */\n readonly inventory: PreviewInventory;\n /** Write the annotated sources back. Without it nothing is touched. */\n readonly write?: boolean;\n /** Resolves the paths in the report. Defaults to `process.cwd()`. */\n readonly cwd?: string;\n /** Reader/writer injection for tests. */\n readonly io?: {\n readonly read: (path: string) => Promise<string>;\n readonly write: (path: string, content: string) => Promise<void>;\n };\n}\n\n/**\n * The part of an inventory the annotator reads: the paths, and nothing else.\n *\n * `PreviewInventory` from `generateTypes()` satisfies it, and so does an object\n * a project writes by hand. Naming the minimum keeps the build plugin's public\n * surface free of the extracted-field union behind the full inventory — a dozen\n * types a consumer of a Vite plugin has no reason to meet.\n */\nexport interface AnnotatableSchema {\n readonly globals: readonly { readonly fields: readonly { readonly path: string }[] }[];\n readonly collections: readonly { readonly fields: readonly { readonly path: string }[] }[];\n}\n\n/**\n * Every path the schema can address, in one set.\n *\n * An array's items are spelled `slides.*.caption` in the inventory because that\n * is how the runtime resolves them; a template writes `slide.caption` inside a\n * loop, where nothing connects `slide` to `slides`. Those paths are therefore\n * kept out: the scanner would otherwise match a name that only looks right.\n * @internal\n */\nexport function annotatablePaths(inventory: AnnotatableSchema): ReadonlySet<string> {\n const paths = new Set<string>();\n for (const entry of [...inventory.globals, ...inventory.collections]) {\n for (const field of entry.fields) {\n if (!field.path.includes('*')) paths.add(field.path);\n }\n }\n return paths;\n}\n\n/** @internal */\nexport async function annotateTemplates(options: AnnotateOptions): Promise<AnnotateResult> {\n const read = options.io?.read ?? ((path: string) => readFile(path, 'utf8'));\n const write =\n options.io?.write ?? ((path: string, content: string) => writeFile(path, content, 'utf8'));\n const root = options.cwd ?? process.cwd();\n const paths = annotatablePaths(options.inventory);\n const files: AnnotateFileResult[] = [];\n\n for (const file of options.files) {\n const source = await read(file);\n const { candidates, refusals } = scanTemplate(source, { paths });\n const code = candidates.length === 0 ? source : applyAnnotations(source, candidates);\n const changed = code !== source;\n if (changed && options.write === true) await write(file, code);\n files.push({\n file: relative(root, file) || file,\n code,\n annotations: candidates,\n refusals,\n changed,\n });\n }\n\n return {\n files,\n annotationCount: files.reduce((total, file) => total + file.annotations.length, 0),\n refusalCount: files.reduce((total, file) => total + file.refusals.length, 0),\n written: options.write === true,\n };\n}\n\n/** The report, one line per annotation and per refusal, in file order. @internal */\nexport function formatAnnotateReport(result: AnnotateResult): string {\n const lines: string[] = [];\n for (const file of result.files) {\n if (file.annotations.length === 0 && file.refusals.length === 0) continue;\n lines.push(file.file);\n for (const annotation of file.annotations) {\n lines.push(` ${String(annotation.line)}: <${annotation.tag}> → ${annotation.path}`);\n }\n for (const refusal of file.refusals) {\n lines.push(\n ` ${String(refusal.line)}: left alone — ${refusal.reason} (${refusal.expression})`,\n );\n }\n }\n const verb = result.written ? 'annotated' : 'would annotate';\n lines.push(\n `${verb} ${String(result.annotationCount)} element(s); ` +\n `${String(result.refusalCount)} left for a human`,\n );\n return `${lines.join('\\n')}\\n`;\n}\n","/**\n * Programmatic codegen API: `generateTypes({ configPath, outFile })` parses a\n * Payload config and writes the TypeScript types and, optionally, the preview\n * inventory. Requires ts-morph.\n */\nimport { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, isAbsolute, resolve } from 'node:path';\nimport { emitTypes, type EmitOptions } from './emit/emit-types';\nimport { buildPreviewInventory, type PreviewInventory } from './inventory';\nimport { extractSchema, type ExtractSchemaOptions } from './parser/extract-schema';\nimport type { ExtractedSchema } from './parser/types';\n\nexport {\n annotateTemplates,\n annotatablePaths,\n formatAnnotateReport,\n ANNOTATABLE_EXTENSIONS,\n type AnnotateOptions,\n type AnnotateResult,\n type AnnotateFileResult,\n type AnnotationCandidate,\n type AnnotationRefusal,\n type AnnotatableSchema,\n} from './annotate/index';\n\nexport interface GenerateTypesOptions\n extends Pick<ExtractSchemaOptions, 'configPath' | 'project' | 'tsConfigFilePath'>, EmitOptions {\n /** Where to write the generated code; `code` is returned either way. */\n readonly outFile?: string;\n /** Resolves relative paths. Defaults to `process.cwd()`. */\n readonly cwd?: string;\n /** Where to write the preview inventory as JSON: every path a binding may address. */\n readonly inventoryFile?: string;\n}\n\nexport interface GenerateTypesResult {\n readonly code: string;\n /** Extraction diagnostics, plus a note when nothing was written. */\n readonly diagnostics: readonly string[];\n readonly schema: ExtractedSchema;\n /** The types file actually written; absent when writing was refused. */\n readonly outFile?: string;\n /** Always produced; written to disk only when `inventoryFile` is set. */\n readonly inventory: PreviewInventory;\n readonly inventoryFile?: string;\n}\n\nasync function writeOut(path: string, content: string): Promise<void> {\n await mkdir(dirname(path), { recursive: true });\n await writeFile(path, content, 'utf8');\n}\n\n/** Parse the config and write the types, never writing an empty schema over a consumer's file. */\nexport async function generateTypes(options: GenerateTypesOptions): Promise<GenerateTypesResult> {\n const cwd = options.cwd ?? process.cwd();\n const absolute = (path: string): string => (isAbsolute(path) ? path : resolve(cwd, path));\n const schema = extractSchema({\n configPath: absolute(options.configPath),\n ...(options.project !== undefined ? { project: options.project } : {}),\n ...(options.tsConfigFilePath !== undefined\n ? { tsConfigFilePath: options.tsConfigFilePath }\n : {}),\n });\n const code = emitTypes(schema, options);\n const inventory = buildPreviewInventory(schema);\n const diagnostics = [...schema.diagnostics];\n const outFile = options.outFile === undefined ? undefined : absolute(options.outFile);\n const inventoryFile =\n options.inventoryFile === undefined ? undefined : absolute(options.inventoryFile);\n const targets = [outFile, inventoryFile].filter((path): path is string => path !== undefined);\n const empty = schema.globals.length + schema.collections.length === 0;\n if (empty && targets.length > 0) {\n diagnostics.push(\n `Nothing written: the schema is empty (0 globals, 0 collections), so ${targets.join(' and ')} ` +\n 'were left as they are.',\n );\n } else {\n if (outFile !== undefined) await writeOut(outFile, code);\n // Stable key order and a trailing newline keep the inventory diffable.\n if (inventoryFile !== undefined) {\n await writeOut(inventoryFile, `${JSON.stringify(inventory, null, 2)}\\n`);\n }\n }\n return {\n code,\n diagnostics,\n schema,\n inventory,\n ...(!empty && outFile !== undefined ? { outFile } : {}),\n ...(!empty && inventoryFile !== undefined ? { inventoryFile } : {}),\n };\n}\n\nexport { buildPreviewInventory, checkPreviewBindings } from './inventory';\nexport type {\n PreviewBindingReference,\n PreviewCoverageOptions,\n PreviewInventory,\n PreviewInventoryEntry,\n PreviewInventoryField,\n} from './inventory';\nexport { extractSchema } from './parser/extract-schema';\nexport { emitTypes } from './emit/emit-types';\nexport type { ExtractedSchema, ExtractedSlug, ExtractedField } from './parser/types';\n"],"mappings":"2IAEO,SAASA,EAAaC,GAC3B,OAAOA,EACJC,MAAM,YACNC,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,QAAQD,MAC7B2B,EAAYzN,GAA0B0N,aAAW1N,GAAQA,EAAO2N,UAAQ7B,EAAK9L,GAC7ET,EAASgI,EAAc,CAC3BO,WAAY2F,EAASrQ,EAAQ0K,oBACL,IAApB1K,EAAQoK,QAAwB,CAAEA,QAASpK,EAAQoK,SAAY,WAClC,IAA7BpK,EAAQsK,iBACR,CAAEA,iBAAkBtK,EAAQsK,kBAC5B,KAEAnB,EAAOjH,EAAUC,EAAQnC,GACzB8N,EAAYhL,EAAsBX,GAClCiC,EAAc,IAAIjC,EAAOiC,aACzBoM,OAA8B,IAApBxQ,EAAQwQ,aAAwB,EAAYH,EAASrQ,EAAQwQ,SACvEC,OACsB,IAA1BzQ,EAAQyQ,mBAA8B,EAAYJ,EAASrQ,EAAQyQ,eAC/DC,EAAU,CAACF,EAASC,GAAezR,OAAQ4D,QAAkC,IAATA,GACpE+N,EAAQxO,EAAOG,QAAQzB,OAASsB,EAAOI,YAAY1B,SAAW,EAapE,OAZI8P,GAASD,EAAQ7P,OAAS,EAC5BuD,EAAYjE,KACV,uEAAuEuQ,EAAQnR,KAAK,yCAItE,IAAZiR,SAA6BxC,GAASwC,EAASrH,QAE7B,IAAlBsH,SACIzC,GAASyC,EAAe,GAAGG,KAAKC,UAAU/C,EAAW,KAAM,SAG9D,CACL3E,OACA/E,cACAjC,SACA2L,eACK6C,QAAqB,IAAZH,EAAsC,GAAd,CAAEA,cACnCG,QAA2B,IAAlBF,EAAkD,GAApB,CAAEA,iBAElD","ignoreList":[]}
1
+ {"version":3,"file":"codegen.cjs","names":["toPascalCase","slug","split","filter","Boolean","map","part","charAt","toUpperCase","slice","join","tsMorph","IDENTIFIER","nestedTypeName","parent","child","emitFieldMember","field","lines","options","markLocalizedAsDeprecated","localized","push","optional","required","name","test","replace","kind","hasMany","typeRef","blocks","length","block","typeName","base","target","literal","option","renderFieldType","emitBlockInterface","fields","emitAuxiliaries","prefix","seen","auxName","has","add","inner","blockTypeName","emitSlug","emitMap","slugs","emitTypes","schema","header","Set","globals","collections","slugAliases","collect","basePath","out","path","entry","buildPreviewInventory","loadTsMorph","createRequire","document","require","pathToFileURL","__filename","href","_documentCurrentScript","tagName","src","URL","baseURI","error","Error","cause","tsNode","Node","reportSkip","context","node","why","diagnostics","text","getText","snippet","getSourceFile","getBaseName","String","getStartLineNumber","where","unwrap","current","isParenthesizedExpression","isAsExpression","isSatisfiesExpression","isNonNullExpression","isTypeAssertion","getExpression","followAlias","declaration","isImportSpecifier","isImportClause","isNamespaceImport","isExportSpecifier","aliased","getSymbol","getAliasedSymbol","getDeclarations","definitionsOf","identifier","definitions","getDefinitionNodes","flatMap","valueOf","isVariableDeclaration","isPropertyAssignment","getInitializer","isExportAssignment","isShorthandPropertyAssignment","getNameNode","propertyValue","property","getProperty","hasProperty","resolveToObjectLiteral","isObjectLiteralExpression","isCallExpression","getArguments","isIdentifier","resolved","isPropertyAccessExpression","owner","getName","resolveToArrayLiteral","isArrayLiteralExpression","expandElements","array","element","getElements","isSpreadElement","expanded","readStringProperty","value","isStringLiteral","isNoSubstitutionTemplateLiteral","getLiteralValue","readBooleanProperty","isTrueLiteral","isFalseLiteral","readArrayProperty","readRelationTarget","STRUCTURAL_SENTINEL","STRUCTURAL_TYPES","SCALAR_TYPE_MAP","textarea","email","richText","number","checkbox","date","code","point","HAS_MANY_SCALARS","extractFields","extractField","nestedFields","extractTabs","tabs","tab","extractBlocks","readOptions","type","declaredValue","extractSlugList","configLiteral","key","extractSchema","project","Project","tsConfigFilePath","skipAddingFilesFromTsConfig","sourceFile","addSourceFileAtPathIfExists","configPath","resolveSourceFileDependencies","defaultExport","getDefaultExportSymbol","call","getDescendantsOfKind","SyntaxKind","CallExpression","callee","findConfigLiteral","ELEMENT","ONLY_INTERPOLATION","ANY_INTERPOLATION","MEMBER_CHAIN","FIELD_ATTRIBUTE","LOOP_VARIABLES","lineAt","source","index","line","position","charCodeAt","pathOf","chain","indexOf","describe","expression","flat","trim","refusalReason","paths","items","trimmed","root","scanTemplate","candidates","refusals","names","pattern","match","matchAll","loopVariables","tag","attributes","content","includes","only","exec","reason","insertAt","fieldAttribute","candidate","applyAnnotations","render","sort","a","b","annotatablePaths","inventory","async","writeOut","mkdir","dirname","recursive","writeFile","read","io","readFile","write","cwd","process","files","file","changed","relative","annotations","annotationCount","reduce","total","refusalCount","written","bindings","byKey","Map","entries","item","set","f","binding","get","bound","reportUnbound","result","annotation","refusal","verb","absolute","isAbsolute","resolve","outFile","inventoryFile","targets","empty","JSON","stringify"],"sources":["../src/codegen/parser/names.ts","../src/codegen/emit/emit-types.ts","../src/codegen/parser/resolve.ts","../src/codegen/inventory.ts","../src/codegen/parser/extract-field.ts","../src/codegen/parser/extract-schema.ts","../src/codegen/annotate/scan.ts","../src/codegen/annotate/index.ts","../src/codegen/index.ts"],"sourcesContent":["/** Naming shared by the parser and the emitter. */\n\nexport function toPascalCase(slug: string): string {\n return slug\n .split(/[-_\\s]+/u)\n .filter(Boolean)\n .map((part) => part.charAt(0).toUpperCase() + part.slice(1))\n .join('');\n}\n","/**\n * Render an `ExtractedSchema` as one self-contained TypeScript file: an\n * interface per global and collection, nested interfaces for groups, arrays\n * and blocks, and the `PayloadGlobals`/`PayloadCollections`/`PayloadSlug` maps.\n */\nimport { toPascalCase } from '../parser/names';\nimport type {\n ExtractedBlock,\n ExtractedField,\n ExtractedSchema,\n ExtractedSlug,\n} from '../parser/types';\n\nexport interface EmitOptions {\n /** When true, localized fields carry a `@localized` JSDoc marker. */\n readonly markLocalizedAsDeprecated?: boolean;\n /** Header text at the top of the output. */\n readonly header?: string;\n}\n\nconst DEFAULT_HEADER =\n '// Auto-generated by payload-live-preview/codegen.\\n' +\n '// Do not edit by hand — run `pll-codegen` to regenerate.\\n' +\n '/* eslint-disable */';\nconst IDENTIFIER = /^[A-Za-z_$][\\w$]*$/u;\n\nfunction memberName(name: string): string {\n if (IDENTIFIER.test(name)) return name;\n return `'${name.replace(/\\\\/gu, '\\\\\\\\').replace(/'/gu, \"\\\\'\")}'`;\n}\n\nfunction nestedTypeName(parent: string, child: string): string {\n return `${parent}${toPascalCase(child)}`;\n}\n\nfunction renderFieldType(field: ExtractedField, parent: string): string {\n switch (field.kind) {\n case 'scalar':\n return field.hasMany === true ? `${field.typeRef}[]` : field.typeRef;\n case 'array':\n return `${nestedTypeName(parent, field.name)}[]`;\n case 'blocks': {\n if (field.blocks.length === 0) return 'unknown[]';\n const variants = field.blocks\n .map((block) => nestedTypeName(nestedTypeName(parent, field.name), block.typeName))\n .join(' | ');\n return `(${variants})[]`;\n }\n case 'group':\n return nestedTypeName(parent, field.name);\n case 'relationship': {\n const target =\n typeof field.target === 'string'\n ? `'${field.target}'`\n : field.target.map((slug) => `'${slug}'`).join(' | ');\n const base = `PayloadRelationship<${target}>`;\n return field.hasMany ? `${base}[]` : base;\n }\n case 'upload':\n return field.hasMany === true ? 'PayloadMedia[]' : 'PayloadMedia';\n case 'json':\n return 'unknown';\n case 'select': {\n if (field.options.length === 0) return field.hasMany ? 'string[]' : 'string';\n const literal = field.options.map((option) => `'${option}'`).join(' | ');\n return field.hasMany ? `(${literal})[]` : literal;\n }\n }\n}\n\nfunction emitFieldMember(\n field: ExtractedField,\n parent: string,\n lines: string[],\n options: EmitOptions,\n): void {\n if (options.markLocalizedAsDeprecated === true && field.localized) {\n lines.push(' /** @localized */');\n }\n const optional = field.required ? '' : '?';\n lines.push(` ${memberName(field.name)}${optional}: ${renderFieldType(field, parent)};`);\n}\n\nfunction emitBlockInterface(\n typeName: string,\n block: ExtractedBlock,\n lines: string[],\n options: EmitOptions,\n): void {\n lines.push(`export interface ${typeName} {`);\n lines.push(` blockType: '${block.slug}';`);\n for (const field of block.fields) emitFieldMember(field, typeName, lines, options);\n lines.push('}', '');\n}\n\nfunction emitAuxiliaries(\n prefix: string,\n fields: readonly ExtractedField[],\n lines: string[],\n seen: Set<string>,\n options: EmitOptions,\n): void {\n for (const field of fields) {\n const auxName = nestedTypeName(prefix, field.name);\n if (field.kind === 'array' || field.kind === 'group') {\n if (seen.has(auxName)) continue;\n seen.add(auxName);\n emitAuxiliaries(auxName, field.fields, lines, seen, options);\n lines.push(`export interface ${auxName} {`);\n for (const inner of field.fields) emitFieldMember(inner, auxName, lines, options);\n lines.push('}', '');\n } else if (field.kind === 'blocks') {\n for (const block of field.blocks) {\n const blockTypeName = nestedTypeName(auxName, block.typeName);\n if (seen.has(blockTypeName)) continue;\n seen.add(blockTypeName);\n emitAuxiliaries(blockTypeName, block.fields, lines, seen, options);\n emitBlockInterface(blockTypeName, block, lines, options);\n }\n }\n }\n}\n\nfunction emitSlug(\n slug: ExtractedSlug,\n lines: string[],\n seen: Set<string>,\n options: EmitOptions,\n): void {\n emitAuxiliaries(slug.typeName, slug.fields, lines, seen, options);\n lines.push(`export interface ${slug.typeName} {`);\n for (const field of slug.fields) emitFieldMember(field, slug.typeName, lines, options);\n lines.push('}');\n}\n\nfunction emitMap(name: string, slugs: readonly ExtractedSlug[], lines: string[]): void {\n if (slugs.length === 0) return;\n lines.push(`export type ${name} = {`);\n for (const slug of slugs) lines.push(` '${slug.slug}': ${slug.typeName};`);\n lines.push('};', '');\n}\n\n/** @internal */\nexport function emitTypes(schema: ExtractedSchema, options: EmitOptions = {}): string {\n const lines: string[] = [options.header ?? DEFAULT_HEADER, ''];\n lines.push('import type { PayloadMedia, PayloadRelationship } from \"payload-live-preview\";', '');\n const seen = new Set<string>();\n for (const slug of [...schema.globals, ...schema.collections]) {\n emitSlug(slug, lines, seen, options);\n lines.push('');\n }\n emitMap('PayloadGlobals', schema.globals, lines);\n emitMap('PayloadCollections', schema.collections, lines);\n const slugAliases: string[] = [];\n if (schema.globals.length > 0) slugAliases.push('keyof PayloadGlobals');\n if (schema.collections.length > 0) slugAliases.push('keyof PayloadCollections');\n if (slugAliases.length > 0) {\n lines.push(`export type PayloadSlug = ${slugAliases.join(' | ')};`, '');\n }\n return lines.join('\\n').replace(/\\n{3,}/gu, '\\n\\n');\n}\n","/**\n * Resolving the shapes a Payload config takes — literals, identifiers,\n * imports, wrappers, spreads — to the literals the extractors read. Every\n * shape that cannot be resolved becomes a diagnostic, never a silent gap.\n */\nimport { createRequire } from 'node:module';\nimport type * as TsMorphModule from 'ts-morph';\nimport type { ArrayLiteralExpression, Identifier, Node, ObjectLiteralExpression } from 'ts-morph';\n\nlet tsMorph: typeof TsMorphModule | undefined;\n\n/**\n * ts-morph on first use. It is an optional peer because it reads a Payload\n * config, and nothing else here needs a TypeScript compiler: an entry that only\n * prints its help, or refuses a usage error, must load without it. A static\n * import would not allow that — esbuild hoists an external import to the top of\n * the bundle even out of a dynamically imported module, so the binary would\n * resolve the peer before parsing its first flag. `pll migrate` loads it the\n * same way (src/migrate/ast.ts).\n */\nexport function loadTsMorph(): typeof TsMorphModule {\n if (tsMorph === undefined) {\n try {\n tsMorph = createRequire(import.meta.url)('ts-morph') as typeof TsMorphModule;\n } catch (error) {\n throw new Error('pll-codegen needs ts-morph: npm install --save-dev ts-morph', {\n cause: error,\n });\n }\n }\n return tsMorph;\n}\n\n/** The `Node` type guards, which every extractor reaches for. */\nexport function tsNode(): typeof TsMorphModule.Node {\n return loadTsMorph().Node;\n}\n\nexport interface ExtractContext {\n readonly diagnostics: string[];\n}\n\nfunction where(node: Node): string {\n return `${node.getSourceFile().getBaseName()}:${String(node.getStartLineNumber())}`;\n}\n\nfunction snippet(node: Node): string {\n const text = node.getText().replace(/\\s+/gu, ' ');\n return text.length > 60 ? `${text.slice(0, 57)}...` : text;\n}\n\nexport function reportSkip(context: ExtractContext, node: Node, why: string): void {\n context.diagnostics.push(`Skipped \"${snippet(node)}\" at ${where(node)}: ${why}.`);\n}\n\nfunction unwrap(node: Node): Node {\n let current = node;\n while (\n tsNode().isParenthesizedExpression(current) ||\n tsNode().isAsExpression(current) ||\n tsNode().isSatisfiesExpression(current) ||\n tsNode().isNonNullExpression(current) ||\n tsNode().isTypeAssertion(current)\n ) {\n current = current.getExpression();\n }\n return current;\n}\n\n/** An import or re-export binds a name but holds no value; the value is in the module it names. */\nfunction followAlias(declaration: Node): readonly Node[] {\n const isAlias =\n tsNode().isImportSpecifier(declaration) ||\n tsNode().isImportClause(declaration) ||\n tsNode().isNamespaceImport(declaration) ||\n tsNode().isExportSpecifier(declaration);\n if (!isAlias) return [declaration];\n const aliased = declaration.getSymbol()?.getAliasedSymbol();\n return aliased?.getDeclarations() ?? [declaration];\n}\n\n/** Follows imports through the language service; the binder is the fallback for what it cannot see. */\nfunction definitionsOf(identifier: Identifier): readonly Node[] {\n const definitions = identifier.getDefinitionNodes();\n const found =\n definitions.length > 0 ? definitions : (identifier.getSymbol()?.getDeclarations() ?? []);\n return found.flatMap(followAlias);\n}\n\nfunction valueOf(declaration: Node): Node | undefined {\n if (tsNode().isVariableDeclaration(declaration) || tsNode().isPropertyAssignment(declaration)) {\n return declaration.getInitializer();\n }\n if (tsNode().isExportAssignment(declaration)) return declaration.getExpression();\n if (tsNode().isShorthandPropertyAssignment(declaration)) return declaration.getNameNode();\n return undefined;\n}\n\n/** The value of a property, treating `{ fields }` shorthand as a reference to resolve. */\nexport function propertyValue(literal: ObjectLiteralExpression, name: string): Node | undefined {\n const property = literal.getProperty(name);\n if (property === undefined) return undefined;\n if (tsNode().isPropertyAssignment(property)) return property.getInitializer();\n if (tsNode().isShorthandPropertyAssignment(property)) return property.getNameNode();\n return undefined;\n}\n\nexport function hasProperty(literal: ObjectLiteralExpression, name: string): boolean {\n return literal.getProperty(name) !== undefined;\n}\n\nexport function resolveToObjectLiteral(\n node: Node | undefined,\n seen = new Set<Node>(),\n): ObjectLiteralExpression | undefined {\n if (node === undefined || seen.has(node)) return undefined;\n seen.add(node);\n const target = unwrap(node);\n if (tsNode().isObjectLiteralExpression(target)) return target;\n // `buildConfig({...})`, `defineConfig({...})`: the literal is the first argument.\n if (tsNode().isCallExpression(target)) {\n return resolveToObjectLiteral(target.getArguments()[0], seen);\n }\n if (tsNode().isIdentifier(target)) {\n for (const declaration of definitionsOf(target)) {\n const resolved = resolveToObjectLiteral(valueOf(declaration), seen);\n if (resolved !== undefined) return resolved;\n }\n }\n if (tsNode().isPropertyAccessExpression(target)) {\n const owner = resolveToObjectLiteral(target.getExpression(), seen);\n if (owner !== undefined) {\n return resolveToObjectLiteral(propertyValue(owner, target.getName()), seen);\n }\n }\n return undefined;\n}\n\nexport function resolveToArrayLiteral(\n node: Node | undefined,\n seen = new Set<Node>(),\n): ArrayLiteralExpression | undefined {\n if (node === undefined || seen.has(node)) return undefined;\n seen.add(node);\n const target = unwrap(node);\n if (tsNode().isArrayLiteralExpression(target)) return target;\n if (tsNode().isIdentifier(target)) {\n for (const declaration of definitionsOf(target)) {\n const resolved = resolveToArrayLiteral(valueOf(declaration), seen);\n if (resolved !== undefined) return resolved;\n }\n }\n if (tsNode().isPropertyAccessExpression(target)) {\n const owner = resolveToObjectLiteral(target.getExpression(), seen);\n if (owner !== undefined) {\n return resolveToArrayLiteral(propertyValue(owner, target.getName()), seen);\n }\n }\n return undefined;\n}\n\n/** The elements of an array with every spread expanded; a spread that cannot be resolved is reported and dropped. */\nexport function expandElements(array: ArrayLiteralExpression, context: ExtractContext): Node[] {\n const out: Node[] = [];\n for (const element of array.getElements()) {\n if (!tsNode().isSpreadElement(element)) {\n out.push(element);\n continue;\n }\n const expanded = resolveToArrayLiteral(element.getExpression());\n if (expanded === undefined) {\n reportSkip(\n context,\n element,\n 'could not resolve the spread to an array literal, so its entries are missing',\n );\n continue;\n }\n out.push(...expandElements(expanded, context));\n }\n return out;\n}\n\nexport function readStringProperty(\n literal: ObjectLiteralExpression,\n name: string,\n): string | undefined {\n const value = propertyValue(literal, name);\n if (value === undefined) return undefined;\n const target = unwrap(value);\n if (tsNode().isStringLiteral(target) || tsNode().isNoSubstitutionTemplateLiteral(target)) {\n return target.getLiteralValue();\n }\n return undefined;\n}\n\nexport function readBooleanProperty(\n literal: ObjectLiteralExpression,\n name: string,\n): boolean | undefined {\n const value = propertyValue(literal, name);\n if (value === undefined) return undefined;\n const target = unwrap(value);\n if (tsNode().isTrueLiteral(target)) return true;\n if (tsNode().isFalseLiteral(target)) return false;\n return undefined;\n}\n\nexport function readArrayProperty(\n literal: ObjectLiteralExpression,\n name: string,\n): ArrayLiteralExpression | undefined {\n return resolveToArrayLiteral(propertyValue(literal, name));\n}\n\n/** `relationTo`: one slug, several, or `'unknown'` when it is not a literal. */\nexport function readRelationTarget(literal: ObjectLiteralExpression): string | readonly string[] {\n const value = propertyValue(literal, 'relationTo');\n if (value === undefined) return 'unknown';\n const target = unwrap(value);\n if (tsNode().isStringLiteral(target)) return target.getLiteralValue();\n const array = resolveToArrayLiteral(target);\n if (array === undefined) return 'unknown';\n return array\n .getElements()\n .map(unwrap)\n .filter((element) => tsNode().isStringLiteral(element))\n .map((element) => element.getLiteralValue());\n}\n","/**\n * Which schema fields a binding can address, spelled the way the runtime\n * resolves them. Paths follow `@schema/walker` exactly — bindings are matched\n * against that rule at runtime, so any other spelling would be wrong here.\n */\n\nimport type { ExtractedField, ExtractedSchema, ExtractedSlug } from './parser/types';\n\n/** Sentinel the parser gives an unnamed structural container. */\nconst STRUCTURAL_SENTINEL = '__structural';\n\n/** One addressable field, spelled the way a binding must spell it. */\nexport interface PreviewInventoryField {\n /** Runtime binding path, e.g. `hero.title` or `slides.*.caption`. */\n readonly path: string;\n /** Extracted field kind: `scalar`, `array`, `blocks`, `group`, … */\n readonly kind: ExtractedField['kind'];\n readonly localized: boolean;\n readonly required: boolean;\n}\n\nexport interface PreviewInventoryEntry {\n readonly slug: string;\n readonly typeName: string;\n readonly fields: readonly PreviewInventoryField[];\n}\n\nexport interface PreviewInventory {\n readonly globals: readonly PreviewInventoryEntry[];\n readonly collections: readonly PreviewInventoryEntry[];\n}\n\nfunction collect(\n fields: readonly ExtractedField[],\n basePath: string,\n out: PreviewInventoryField[],\n): void {\n for (const field of fields) {\n // No segment, but its children still belong to the parent's surface.\n if (field.kind === 'group' && field.name === STRUCTURAL_SENTINEL) {\n collect(field.fields, basePath, out);\n continue;\n }\n const path = basePath === '' ? field.name : `${basePath}.${field.name}`;\n out.push({\n path,\n kind: field.kind,\n localized: field.localized,\n required: field.required,\n });\n if (field.kind === 'group') {\n collect(field.fields, path, out);\n } else if (field.kind === 'array') {\n collect(field.fields, `${path}.*`, out);\n } else if (field.kind === 'blocks') {\n for (const block of field.blocks) {\n collect(block.fields, `${path}.*.${block.slug}`, out);\n }\n }\n }\n}\n\nfunction entry(slug: ExtractedSlug): PreviewInventoryEntry {\n const fields: PreviewInventoryField[] = [];\n collect(slug.fields, '', fields);\n return { slug: slug.slug, typeName: slug.typeName, fields };\n}\n\n/** Flatten an extracted schema into every path a binding may address. @internal */\nexport function buildPreviewInventory(schema: ExtractedSchema): PreviewInventory {\n return {\n globals: schema.globals.map(entry),\n collections: schema.collections.map(entry),\n };\n}\n\n/** A binding found in consumer markup, however that consumer found it. @internal */\nexport interface PreviewBindingReference {\n readonly kind: 'global' | 'collection';\n readonly slug: string;\n readonly path: string;\n /** Free-form origin for the diagnostic, e.g. `Hero.astro:42`. */\n readonly source?: string;\n}\n\n/** @internal */\nexport interface PreviewCoverageOptions {\n /** Also report schema fields no binding addresses; off, since a page may render a subset. */\n readonly reportUnbound?: boolean;\n}\n\n/** Cross-check bindings the consumer extracted against the inventory. @internal */\nexport function checkPreviewBindings(\n inventory: PreviewInventory,\n bindings: readonly PreviewBindingReference[],\n options: PreviewCoverageOptions = {},\n): readonly string[] {\n const diagnostics: string[] = [];\n const byKey = new Map<string, ReadonlySet<string>>();\n for (const [kind, entries] of [\n ['global', inventory.globals],\n ['collection', inventory.collections],\n ] as const) {\n for (const item of entries) {\n byKey.set(`${kind}:${item.slug}`, new Set(item.fields.map((f) => f.path)));\n }\n }\n\n const seen = new Map<string, Set<string>>();\n for (const binding of bindings) {\n const key = `${binding.kind}:${binding.slug}`;\n const where = binding.source === undefined ? '' : ` (${binding.source})`;\n const paths = byKey.get(key);\n if (paths === undefined) {\n diagnostics.push(`unknown ${binding.kind} \"${binding.slug}\"${where}`);\n continue;\n }\n if (!paths.has(binding.path)) {\n diagnostics.push(`${key} has no field \"${binding.path}\"${where}`);\n continue;\n }\n let bound = seen.get(key);\n if (bound === undefined) {\n bound = new Set<string>();\n seen.set(key, bound);\n }\n bound.add(binding.path);\n }\n\n if (options.reportUnbound === true) {\n for (const [key, paths] of byKey) {\n const bound = seen.get(key) ?? new Set<string>();\n for (const path of paths) {\n if (!bound.has(path)) diagnostics.push(`${key} field \"${path}\" is never bound`);\n }\n }\n }\n\n return diagnostics;\n}\n","/**\n * Field-level extraction: one Payload field literal → an `ExtractedField`,\n * recursing into groups, arrays, tabs and blocks.\n */\nimport type { ArrayLiteralExpression, ObjectLiteralExpression } from 'ts-morph';\nimport { toPascalCase } from './names';\nimport {\n expandElements,\n hasProperty,\n readArrayProperty,\n readBooleanProperty,\n readRelationTarget,\n readStringProperty,\n reportSkip,\n resolveToObjectLiteral,\n tsNode,\n type ExtractContext,\n} from './resolve';\nimport type { ExtractedBlock, ExtractedField, ExtractedScalarField } from './types';\n\n/** Name of an unnamed structural container; its fields flatten into the parent. */\nexport const STRUCTURAL_SENTINEL = '__structural';\nconst STRUCTURAL_TYPES = new Set(['tabs', 'row', 'collapsible']);\nconst SCALAR_TYPE_MAP: Readonly<Record<string, ExtractedScalarField['typeRef']>> = {\n text: 'string',\n textarea: 'string',\n email: 'string',\n richText: 'unknown',\n number: 'number',\n checkbox: 'boolean',\n date: 'string',\n code: 'string',\n point: '[number, number]',\n};\nconst HAS_MANY_SCALARS = new Set(['text', 'number']);\n\n/** Every field in `array`, spreads expanded and structural containers flattened. */\nexport function extractFields(\n array: ArrayLiteralExpression,\n context: ExtractContext,\n): ExtractedField[] {\n const out: ExtractedField[] = [];\n for (const element of expandElements(array, context)) {\n const literal = resolveToObjectLiteral(element);\n if (literal === undefined) {\n reportSkip(context, element, 'could not resolve the field to an object literal');\n continue;\n }\n const field = extractField(literal, context);\n if (field === undefined) continue;\n if (field.kind === 'group' && field.name === STRUCTURAL_SENTINEL) out.push(...field.fields);\n else out.push(field);\n }\n return out;\n}\n\nfunction nestedFields(literal: ObjectLiteralExpression, context: ExtractContext): ExtractedField[] {\n const array = readArrayProperty(literal, 'fields');\n if (array !== undefined) return extractFields(array, context);\n reportSkip(\n context,\n literal,\n hasProperty(literal, 'fields')\n ? 'its `fields` could not be resolved to an array literal'\n : 'it has no `fields`',\n );\n return [];\n}\n\nfunction extractTabs(literal: ObjectLiteralExpression, context: ExtractContext): ExtractedField[] {\n const tabs = readArrayProperty(literal, 'tabs');\n if (tabs === undefined) {\n reportSkip(context, literal, 'its `tabs` could not be resolved to an array literal');\n return [];\n }\n const out: ExtractedField[] = [];\n for (const element of expandElements(tabs, context)) {\n const tab = resolveToObjectLiteral(element);\n if (tab === undefined) {\n reportSkip(context, element, 'could not resolve the tab to an object literal');\n continue;\n }\n const name = readStringProperty(tab, 'name');\n const fields = nestedFields(tab, context);\n if (name === undefined) out.push(...fields);\n else out.push({ kind: 'group', name, required: false, localized: false, fields });\n }\n return out;\n}\n\nfunction extractBlocks(\n literal: ObjectLiteralExpression,\n context: ExtractContext,\n): ExtractedBlock[] {\n const blocks = readArrayProperty(literal, 'blocks');\n if (blocks === undefined) {\n reportSkip(context, literal, 'its `blocks` could not be resolved to an array literal');\n return [];\n }\n const out: ExtractedBlock[] = [];\n for (const element of expandElements(blocks, context)) {\n const block = resolveToObjectLiteral(element);\n if (block === undefined) {\n reportSkip(context, element, 'could not resolve the block to an object literal');\n continue;\n }\n const slug = readStringProperty(block, 'slug');\n if (slug === undefined) {\n reportSkip(context, element, 'a block needs a string `slug`');\n continue;\n }\n out.push({ slug, typeName: toPascalCase(slug), fields: nestedFields(block, context) });\n }\n return out;\n}\n\nfunction readOptions(literal: ObjectLiteralExpression, context: ExtractContext): string[] {\n const options = readArrayProperty(literal, 'options');\n if (options === undefined) {\n reportSkip(context, literal, 'its `options` could not be resolved to an array literal');\n return [];\n }\n const out: string[] = [];\n for (const element of expandElements(options, context)) {\n if (tsNode().isStringLiteral(element)) {\n out.push(element.getLiteralValue());\n continue;\n }\n const option = resolveToObjectLiteral(element);\n const value = option === undefined ? undefined : readStringProperty(option, 'value');\n if (value === undefined) reportSkip(context, element, 'an option needs a string or a `value`');\n else out.push(value);\n }\n return out;\n}\n\n/** One field, or `undefined` for a `ui` field (nothing to type) and for shapes reported as skipped. */\nexport function extractField(\n literal: ObjectLiteralExpression,\n context: ExtractContext,\n): ExtractedField | undefined {\n const type = readStringProperty(literal, 'type');\n if (type === undefined) {\n reportSkip(context, literal, 'it has no string `type`');\n return undefined;\n }\n if (type === 'ui') return undefined;\n const name = readStringProperty(literal, 'name');\n if (name === undefined && !STRUCTURAL_TYPES.has(type)) {\n reportSkip(context, literal, `a ${type} field needs a string \\`name\\``);\n return undefined;\n }\n const base = {\n name: name ?? STRUCTURAL_SENTINEL,\n required: readBooleanProperty(literal, 'required') ?? false,\n localized: readBooleanProperty(literal, 'localized') ?? false,\n };\n const hasMany = readBooleanProperty(literal, 'hasMany') ?? false;\n switch (type) {\n case 'array':\n return { ...base, kind: 'array', fields: nestedFields(literal, context) };\n case 'group':\n case 'row':\n case 'collapsible':\n return { ...base, kind: 'group', fields: nestedFields(literal, context) };\n case 'tabs':\n return { ...base, kind: 'group', fields: extractTabs(literal, context) };\n case 'blocks':\n return { ...base, kind: 'blocks', blocks: extractBlocks(literal, context) };\n case 'relationship':\n return { ...base, kind: 'relationship', target: readRelationTarget(literal), hasMany };\n case 'upload': {\n const target = readRelationTarget(literal);\n return {\n ...base,\n kind: 'upload',\n target: (typeof target === 'string' ? target : target[0]) ?? 'media',\n hasMany,\n };\n }\n case 'json':\n return { ...base, kind: 'json' };\n case 'select':\n case 'radio':\n return {\n ...base,\n kind: 'select',\n options: readOptions(literal, context),\n hasMany: type === 'select' && hasMany,\n };\n default:\n return {\n ...base,\n kind: 'scalar',\n typeRef: SCALAR_TYPE_MAP[type] ?? 'unknown',\n hasMany: HAS_MANY_SCALARS.has(type) && hasMany,\n };\n }\n}\n","/**\n * Schema-level extraction: open the config, find every collection and global,\n * walk into them. Lenient by design — a Payload config is a full TypeScript\n * program, so the common shapes are recognised and everything else becomes a\n * diagnostic rather than a silently empty type.\n */\nimport type { Node, ObjectLiteralExpression, Project, SourceFile } from 'ts-morph';\nimport { extractFields } from './extract-field';\nimport { toPascalCase } from './names';\nimport {\n expandElements,\n hasProperty,\n propertyValue,\n readArrayProperty,\n readStringProperty,\n reportSkip,\n resolveToArrayLiteral,\n resolveToObjectLiteral,\n loadTsMorph,\n tsNode,\n type ExtractContext,\n} from './resolve';\nimport type { ExtractedSchema, ExtractedSlug } from './types';\n\nexport interface ExtractSchemaOptions {\n /** Absolute or relative path to `payload.config.ts`. */\n readonly configPath: string;\n /** When provided, used instead of constructing a fresh ts-morph project. */\n readonly project?: Project;\n /** A `tsconfig.json` whose module resolution lets cross-file imports be followed. */\n readonly tsConfigFilePath?: string;\n}\n\n/**\n * What a default export declaration holds. TypeScript only ever declares the\n * `default` export as an export assignment, an export specifier, or a function\n * or class declaration — `export default config` keeps the variable's own\n * declaration out of it — so a variable declaration never arrives here.\n */\nfunction declaredValue(declaration: Node): Node | undefined {\n if (tsNode().isExportAssignment(declaration)) return declaration.getExpression();\n return undefined;\n}\n\nfunction findConfigLiteral(\n sourceFile: SourceFile,\n context: ExtractContext,\n): ObjectLiteralExpression | undefined {\n const defaultExport = sourceFile.getDefaultExportSymbol();\n if (defaultExport === undefined) {\n context.diagnostics.push('payload.config.ts has no default export.');\n return undefined;\n }\n for (const declaration of defaultExport.getDeclarations()) {\n const literal = resolveToObjectLiteral(declaredValue(declaration));\n if (literal !== undefined) return literal;\n }\n for (const call of sourceFile.getDescendantsOfKind(loadTsMorph().SyntaxKind.CallExpression)) {\n const callee = call.getExpression();\n if (!tsNode().isIdentifier(callee) || callee.getText() !== 'buildConfig') continue;\n const literal = resolveToObjectLiteral(call.getArguments()[0]);\n if (literal !== undefined) return literal;\n }\n return undefined;\n}\n\nfunction extractSlugList(\n configLiteral: ObjectLiteralExpression,\n key: 'globals' | 'collections',\n context: ExtractContext,\n): ExtractedSlug[] {\n const value = propertyValue(configLiteral, key);\n if (value === undefined) return [];\n const array = resolveToArrayLiteral(value);\n if (array === undefined) {\n reportSkip(context, value, `could not resolve \\`${key}\\` to an array literal`);\n return [];\n }\n const out: ExtractedSlug[] = [];\n for (const element of expandElements(array, context)) {\n const literal = resolveToObjectLiteral(element);\n if (literal === undefined) {\n reportSkip(context, element, 'could not resolve the config entry to an object literal');\n continue;\n }\n const slug = readStringProperty(literal, 'slug');\n if (slug === undefined) {\n reportSkip(context, element, 'the config entry has no string `slug`');\n continue;\n }\n const fields = readArrayProperty(literal, 'fields');\n if (fields === undefined) {\n reportSkip(\n context,\n literal,\n hasProperty(literal, 'fields')\n ? `the \\`fields\\` of \"${slug}\" could not be resolved to an array literal`\n : `\"${slug}\" has no \\`fields\\``,\n );\n }\n out.push({\n slug,\n typeName: toPascalCase(slug),\n fields: fields === undefined ? [] : extractFields(fields, context),\n });\n }\n return out;\n}\n\n/** @internal */\nexport function extractSchema(options: ExtractSchemaOptions): ExtractedSchema {\n const project =\n options.project ??\n new (loadTsMorph().Project)(\n options.tsConfigFilePath !== undefined\n ? { tsConfigFilePath: options.tsConfigFilePath }\n : { skipAddingFilesFromTsConfig: true },\n );\n const sourceFile = project.addSourceFileAtPathIfExists(options.configPath);\n if (sourceFile === undefined) {\n return { globals: [], collections: [], diagnostics: [`Could not open ${options.configPath}`] };\n }\n project.resolveSourceFileDependencies();\n const context: ExtractContext = { diagnostics: [] };\n const configLiteral = findConfigLiteral(sourceFile, context);\n if (configLiteral === undefined) {\n return {\n globals: [],\n collections: [],\n diagnostics: [\n ...context.diagnostics,\n 'Could not locate a buildConfig({...}) call or `export default {...}` in the config file.',\n ],\n };\n }\n const globals = extractSlugList(configLiteral, 'globals', context);\n const collections = extractSlugList(configLiteral, 'collections', context);\n return { globals, collections, diagnostics: context.diagnostics };\n}\n","/**\n * Find the places in a template where a field value is printed on its own, and\n * decide — never guess — which of them can carry a binding.\n *\n * The shape this recognises is deliberately narrow, and it is the same in every\n * template language the package adapts:\n *\n * ```\n * <h1>{page.title}</h1> Astro, JSX, Svelte\n * ```\n *\n * An element whose entire content is one member expression, rooted at some\n * variable, whose remaining path is a field the schema actually has. Everything\n * else — an interpolation next to text, a call, a ternary, a path the schema\n * does not know, a component instead of an element — is reported instead, with\n * the reason. A wrong `data-payload-field` is worse than a missing one: it makes\n * the runtime write a value into markup that was never meant for it.\n *\n * Markup rather than an AST on purpose. Astro and Svelte templates are not\n * TypeScript, so ts-morph would only cover the JSX third of the problem, and\n * three parsers would be three chances to disagree about which shape is safe.\n * The shape above is unambiguous enough to scan for.\n */\n\n/** A place that can carry a binding, with the attribute it should get. @internal */\nexport interface AnnotationCandidate {\n /** Offset where the attribute is inserted, inside the opening tag. */\n readonly insertAt: number;\n /** The binding path, as `data-payload-field` must spell it. */\n readonly path: string;\n /** 1-based line, for the report. */\n readonly line: number;\n readonly tag: string;\n}\n\n/** A place that looks like an output but was left alone, and why. */\nexport interface AnnotationRefusal {\n readonly line: number;\n readonly reason: string;\n /** The source of the interpolation, trimmed, for the report. */\n readonly expression: string;\n}\n\nexport interface ScanResult {\n readonly candidates: readonly AnnotationCandidate[];\n readonly refusals: readonly AnnotationRefusal[];\n}\n\nexport interface ScanOptions {\n /** Field paths the schema has, exactly as a binding must spell them. */\n readonly paths: ReadonlySet<string>;\n}\n\n/**\n * `<tag attrs>content</tag>` with no element inside it, the closing tag\n * repeating the name. Only lowercase tags: an uppercase one is a component,\n * whose children are its own business.\n */\nconst ELEMENT = /<([a-z][a-z0-9-]*)((?:\"[^\"]*\"|'[^']*'|[^>\"'])*)>([^<]*)<\\/\\1\\s*>/gu;\n\n/** The whole content is one interpolation, and nothing else. */\nconst ONLY_INTERPOLATION = /^\\s*\\{([^{}]*)\\}\\s*$/u;\n\n/** An interpolation somewhere in the content, which is a different case. */\nconst ANY_INTERPOLATION = /\\{([^{}]*)\\}/u;\n\n/** A plain member chain: `page.title`, `data.hero.eyebrow`. Nothing callable, nothing indexed. */\nconst MEMBER_CHAIN = /^[A-Za-z_$][\\w$]*(?:\\.[A-Za-z_$][\\w$]*)+$/u;\n\nconst FIELD_ATTRIBUTE = 'data-payload-field';\n\n/**\n * Where a template names one array item at a time: a `.map`, `.flatMap` or\n * `.forEach` callback's first parameter, a `for … of` variable, a Svelte\n * `{#each … as item}`. A chain rooted at such a name prints an item, and the\n * item's `title` is not the document's `title`, however alike the paths look.\n * A name bound this way anywhere in the file is treated as an item everywhere:\n * refusing one real field access costs a line in the report, binding an item\n * costs the preview.\n */\nconst LOOP_VARIABLES: readonly RegExp[] = [\n /\\.(?:map|flatMap|forEach)\\(\\s*(?:async\\s+)?\\(?\\s*([A-Za-z_$][\\w$]*)/gu,\n /\\bfor\\s*\\(\\s*(?:const|let|var)\\s+([A-Za-z_$][\\w$]*)\\s+of\\b/gu,\n /\\{#each\\s[^}]*?\\sas\\s+([A-Za-z_$][\\w$]*)/gu,\n];\n\nfunction loopVariables(source: string): ReadonlySet<string> {\n const names = new Set<string>();\n for (const pattern of LOOP_VARIABLES) {\n for (const match of source.matchAll(pattern)) {\n if (match[1] !== undefined) names.add(match[1]);\n }\n }\n return names;\n}\n\nfunction lineAt(source: string, index: number): number {\n let line = 1;\n for (let position = 0; position < index; position += 1) {\n if (source.charCodeAt(position) === 10) line += 1;\n }\n return line;\n}\n\n/**\n * The binding path a chain would address: everything after the root variable.\n * `page.hero.title` → `hero.title`, and a lone `title` is not a chain at all —\n * a bare identifier says nothing about which document it came from.\n */\nfunction pathOf(chain: string): string {\n return chain.slice(chain.indexOf('.') + 1);\n}\n\nfunction describe(expression: string): string {\n const flat = expression.replace(/\\s+/gu, ' ').trim();\n return flat.length > 60 ? `${flat.slice(0, 57)}…` : flat;\n}\n\n/** Why this interpolation cannot become a binding, in the words of the report. */\nfunction refusalReason(\n expression: string,\n paths: ReadonlySet<string>,\n items: ReadonlySet<string>,\n): string | undefined {\n const trimmed = expression.trim();\n if (trimmed.length === 0) return 'the element is empty';\n if (!MEMBER_CHAIN.test(trimmed)) {\n return 'not a plain field access — a call, an operator or an index cannot be traced to one field';\n }\n const path = pathOf(trimmed);\n const root = trimmed.slice(0, trimmed.indexOf('.'));\n if (items.has(root)) {\n return `\\`${root}\\` is a loop item — a binding names a field of the document, and \\`${path}\\` there is a different value, or none`;\n }\n if (!paths.has(path)) {\n return `the schema has no field \\`${path}\\`; the binding would name something that never arrives`;\n }\n return undefined;\n}\n\nexport function scanTemplate(source: string, options: ScanOptions): ScanResult {\n const candidates: AnnotationCandidate[] = [];\n const refusals: AnnotationRefusal[] = [];\n const items = loopVariables(source);\n for (const match of source.matchAll(ELEMENT)) {\n const [, tag = '', attributes = '', content = ''] = match;\n const line = lineAt(source, match.index);\n if (attributes.includes(FIELD_ATTRIBUTE)) continue;\n const only = ONLY_INTERPOLATION.exec(content);\n if (only === null) {\n // A value printed beside a label — `Published {page.publishedAt}`. The\n // runtime writes an element's whole text, so a binding here would eat the\n // label; splitting the markup is a decision for whoever wrote it.\n const beside = ANY_INTERPOLATION.exec(content);\n if (beside !== null) {\n refusals.push({\n line,\n reason:\n 'the value is printed beside other content — a binding replaces the whole text, so the markup has to be split first',\n expression: describe(content),\n });\n }\n continue;\n }\n const expression = only[1] ?? '';\n const reason = refusalReason(expression, options.paths, items);\n if (reason !== undefined) {\n refusals.push({ line, reason, expression: describe(expression) });\n continue;\n }\n candidates.push({\n // After `<tag`, before whatever the element already carries.\n insertAt: match.index + 1 + tag.length,\n path: pathOf(expression.trim()),\n line,\n tag,\n });\n }\n return { candidates, refusals };\n}\n\n/** The attribute a candidate becomes: what `pll-codegen annotate` writes into a file. */\nexport function fieldAttribute(candidate: AnnotationCandidate): string {\n return `${FIELD_ATTRIBUTE}=\"${candidate.path}\"`;\n}\n\n/**\n * Apply the candidates back-to-front, so every earlier offset still holds.\n *\n * `render` decides what a candidate becomes, because the two callers write\n * different things from the same decision: the codemod writes the attribute\n * into the file a person reads, and the build-time annotator writes a call to\n * the authorization-bound helper. What may be annotated at all is decided in\n * one place — above — and never here.\n */\nexport function applyAnnotations(\n source: string,\n candidates: readonly AnnotationCandidate[],\n render: (candidate: AnnotationCandidate) => string = fieldAttribute,\n): string {\n let out = source;\n for (const candidate of [...candidates].sort((a, b) => b.insertAt - a.insertAt)) {\n out = `${out.slice(0, candidate.insertAt)} ${render(candidate)}${out.slice(candidate.insertAt)}`;\n }\n return out;\n}\n","/**\n * `pll-codegen annotate`: put `data-payload-field` where a template already\n * prints a field, and report every place it would have had to guess.\n *\n * The schema decides what exists — the same inventory `--inventory` writes, so\n * an annotation and a runtime binding spell a path the same way. What the tool\n * cannot attribute is listed, never invented: an unbound field costs an editor\n * one invisible edit, a wrongly bound one writes a value into the wrong element\n * on every keystroke.\n */\n\nimport { readFile, writeFile } from 'node:fs/promises';\nimport { relative } from 'node:path';\nimport type { PreviewInventory } from '../inventory';\nimport {\n applyAnnotations,\n scanTemplate,\n type AnnotationCandidate,\n type AnnotationRefusal,\n} from './scan';\n\nexport type { AnnotationCandidate, AnnotationRefusal } from './scan';\n\n/** Templates this scanner understands; a `.vue` template uses `{{ … }}` and is not one yet. @internal */\nexport const ANNOTATABLE_EXTENSIONS: readonly string[] = ['.astro', '.jsx', '.tsx', '.svelte'];\n\n/** @internal */\nexport interface AnnotateFileResult {\n readonly file: string;\n /** The annotated source; identical to the input when nothing was added. */\n readonly code: string;\n readonly annotations: readonly AnnotationCandidate[];\n readonly refusals: readonly AnnotationRefusal[];\n readonly changed: boolean;\n}\n\n/** @internal */\nexport interface AnnotateResult {\n readonly files: readonly AnnotateFileResult[];\n readonly annotationCount: number;\n readonly refusalCount: number;\n /** Whether the files were written; `false` is a dry run. */\n readonly written: boolean;\n}\n\n/** @internal */\nexport interface AnnotateOptions {\n /** Template files to read. */\n readonly files: readonly string[];\n /** The schema's addressable paths, from `generateTypes().inventory`. */\n readonly inventory: PreviewInventory;\n /** Write the annotated sources back. Without it nothing is touched. */\n readonly write?: boolean;\n /** Resolves the paths in the report. Defaults to `process.cwd()`. */\n readonly cwd?: string;\n /** Reader/writer injection for tests. */\n readonly io?: {\n readonly read: (path: string) => Promise<string>;\n readonly write: (path: string, content: string) => Promise<void>;\n };\n}\n\n/**\n * The part of an inventory the annotator reads: the paths, and nothing else.\n *\n * `PreviewInventory` from `generateTypes()` satisfies it, and so does an object\n * a project writes by hand. Naming the minimum keeps the build plugin's public\n * surface free of the extracted-field union behind the full inventory — a dozen\n * types a consumer of a Vite plugin has no reason to meet.\n */\nexport interface AnnotatableSchema {\n readonly globals: readonly { readonly fields: readonly { readonly path: string }[] }[];\n readonly collections: readonly { readonly fields: readonly { readonly path: string }[] }[];\n}\n\n/**\n * Every path the schema can address, in one set.\n *\n * An array's items are spelled `slides.*.caption` in the inventory because that\n * is how the runtime resolves them; a template writes `slide.caption` inside a\n * loop, where nothing connects `slide` to `slides`. Those paths are therefore\n * kept out: the scanner would otherwise match a name that only looks right.\n * @internal\n */\nexport function annotatablePaths(inventory: AnnotatableSchema): ReadonlySet<string> {\n const paths = new Set<string>();\n for (const entry of [...inventory.globals, ...inventory.collections]) {\n for (const field of entry.fields) {\n if (!field.path.includes('*')) paths.add(field.path);\n }\n }\n return paths;\n}\n\n/** @internal */\nexport async function annotateTemplates(options: AnnotateOptions): Promise<AnnotateResult> {\n const read = options.io?.read ?? ((path: string) => readFile(path, 'utf8'));\n const write =\n options.io?.write ?? ((path: string, content: string) => writeFile(path, content, 'utf8'));\n const root = options.cwd ?? process.cwd();\n const paths = annotatablePaths(options.inventory);\n const files: AnnotateFileResult[] = [];\n\n for (const file of options.files) {\n const source = await read(file);\n const { candidates, refusals } = scanTemplate(source, { paths });\n const code = candidates.length === 0 ? source : applyAnnotations(source, candidates);\n const changed = code !== source;\n if (changed && options.write === true) await write(file, code);\n files.push({\n file: relative(root, file) || file,\n code,\n annotations: candidates,\n refusals,\n changed,\n });\n }\n\n return {\n files,\n annotationCount: files.reduce((total, file) => total + file.annotations.length, 0),\n refusalCount: files.reduce((total, file) => total + file.refusals.length, 0),\n written: options.write === true,\n };\n}\n\n/** The report, one line per annotation and per refusal, in file order. @internal */\nexport function formatAnnotateReport(result: AnnotateResult): string {\n const lines: string[] = [];\n for (const file of result.files) {\n if (file.annotations.length === 0 && file.refusals.length === 0) continue;\n lines.push(file.file);\n for (const annotation of file.annotations) {\n lines.push(` ${String(annotation.line)}: <${annotation.tag}> → ${annotation.path}`);\n }\n for (const refusal of file.refusals) {\n lines.push(\n ` ${String(refusal.line)}: left alone — ${refusal.reason} (${refusal.expression})`,\n );\n }\n }\n const verb = result.written ? 'annotated' : 'would annotate';\n lines.push(\n `${verb} ${String(result.annotationCount)} element(s); ` +\n `${String(result.refusalCount)} left for a human`,\n );\n return `${lines.join('\\n')}\\n`;\n}\n","/**\n * Programmatic codegen API: `generateTypes({ configPath, outFile })` parses a\n * Payload config and writes the TypeScript types and, optionally, the preview\n * inventory. Requires ts-morph.\n */\nimport { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, isAbsolute, resolve } from 'node:path';\nimport { emitTypes, type EmitOptions } from './emit/emit-types';\nimport { buildPreviewInventory, type PreviewInventory } from './inventory';\nimport { extractSchema, type ExtractSchemaOptions } from './parser/extract-schema';\nimport type { ExtractedSchema } from './parser/types';\n\nexport {\n annotateTemplates,\n annotatablePaths,\n formatAnnotateReport,\n ANNOTATABLE_EXTENSIONS,\n type AnnotateOptions,\n type AnnotateResult,\n type AnnotateFileResult,\n type AnnotationCandidate,\n type AnnotationRefusal,\n type AnnotatableSchema,\n} from './annotate/index';\n\nexport interface GenerateTypesOptions\n extends Pick<ExtractSchemaOptions, 'configPath' | 'project' | 'tsConfigFilePath'>, EmitOptions {\n /** Where to write the generated code; `code` is returned either way. */\n readonly outFile?: string;\n /** Resolves relative paths. Defaults to `process.cwd()`. */\n readonly cwd?: string;\n /** Where to write the preview inventory as JSON: every path a binding may address. */\n readonly inventoryFile?: string;\n}\n\nexport interface GenerateTypesResult {\n readonly code: string;\n /** Extraction diagnostics, plus a note when nothing was written. */\n readonly diagnostics: readonly string[];\n readonly schema: ExtractedSchema;\n /** The types file actually written; absent when writing was refused. */\n readonly outFile?: string;\n /** Always produced; written to disk only when `inventoryFile` is set. */\n readonly inventory: PreviewInventory;\n readonly inventoryFile?: string;\n}\n\nasync function writeOut(path: string, content: string): Promise<void> {\n await mkdir(dirname(path), { recursive: true });\n await writeFile(path, content, 'utf8');\n}\n\n/** Parse the config and write the types, never writing an empty schema over a consumer's file. */\nexport async function generateTypes(options: GenerateTypesOptions): Promise<GenerateTypesResult> {\n const cwd = options.cwd ?? process.cwd();\n const absolute = (path: string): string => (isAbsolute(path) ? path : resolve(cwd, path));\n const schema = extractSchema({\n configPath: absolute(options.configPath),\n ...(options.project !== undefined ? { project: options.project } : {}),\n ...(options.tsConfigFilePath !== undefined\n ? { tsConfigFilePath: options.tsConfigFilePath }\n : {}),\n });\n const code = emitTypes(schema, options);\n const inventory = buildPreviewInventory(schema);\n const diagnostics = [...schema.diagnostics];\n const outFile = options.outFile === undefined ? undefined : absolute(options.outFile);\n const inventoryFile =\n options.inventoryFile === undefined ? undefined : absolute(options.inventoryFile);\n const targets = [outFile, inventoryFile].filter((path): path is string => path !== undefined);\n const empty = schema.globals.length + schema.collections.length === 0;\n if (empty && targets.length > 0) {\n diagnostics.push(\n `Nothing written: the schema is empty (0 globals, 0 collections), so ${targets.join(' and ')} ` +\n 'were left as they are.',\n );\n } else {\n if (outFile !== undefined) await writeOut(outFile, code);\n // Stable key order and a trailing newline keep the inventory diffable.\n if (inventoryFile !== undefined) {\n await writeOut(inventoryFile, `${JSON.stringify(inventory, null, 2)}\\n`);\n }\n }\n return {\n code,\n diagnostics,\n schema,\n inventory,\n ...(!empty && outFile !== undefined ? { outFile } : {}),\n ...(!empty && inventoryFile !== undefined ? { inventoryFile } : {}),\n };\n}\n\nexport { buildPreviewInventory, checkPreviewBindings } from './inventory';\nexport type {\n PreviewBindingReference,\n PreviewCoverageOptions,\n PreviewInventory,\n PreviewInventoryEntry,\n PreviewInventoryField,\n} from './inventory';\nexport { extractSchema } from './parser/extract-schema';\nexport { emitTypes } from './emit/emit-types';\nexport type { ExtractedSchema, ExtractedSlug, ExtractedField } from './parser/types';\n"],"mappings":"2IAEO,SAASA,EAAaC,GAC3B,OAAOA,EACJC,MAAM,YACNC,OAAOC,SACPC,IAAKC,GAASA,EAAKC,OAAO,GAAGC,cAAgBF,EAAKG,MAAM,IACxDC,KAAK,GACV,CCYA,ICXIC,EDeEC,EAAa,sBAOnB,SAASC,EAAeC,EAAgBC,GACtC,MAAO,GAAGD,IAASd,EAAae,IAClC,CAqCA,SAASC,EACPC,EACAH,EACAI,EACAC,IAE0C,IAAtCA,EAAQC,2BAAsCH,EAAMI,WACtDH,EAAMI,KAAK,uBAEb,MAAMC,EAAWN,EAAMO,SAAW,GAAK,IArDzC,IAAoBC,EAsDlBP,EAAMI,KAAK,KAtDOG,EAsDSR,EAAMQ,KArD7Bb,EAAWc,KAAKD,GAAcA,EAC3B,IAAIA,EAAKE,QAAQ,OAAQ,QAAQA,QAAQ,MAAO,YAoDdJ,MA7C3C,SAAyBN,EAAuBH,GAC9C,OAAQG,EAAMW,MACZ,IAAK,SACH,OAAyB,IAAlBX,EAAMY,QAAmB,GAAGZ,EAAMa,YAAcb,EAAMa,QAC/D,IAAK,QACH,MAAO,GAAGjB,EAAeC,EAAQG,EAAMQ,UACzC,IAAK,SACH,OAA4B,IAAxBR,EAAMc,OAAOC,OAAqB,YAI/B,IAHUf,EAAMc,OACpB1B,IAAK4B,GAAUpB,EAAeA,EAAeC,EAAQG,EAAMQ,MAAOQ,EAAMC,WACxExB,KAAK,YAGV,IAAK,QACH,OAAOG,EAAeC,EAAQG,EAAMQ,MACtC,IAAK,eAAgB,CACnB,MAIMU,EAAO,uBAHa,iBAAjBlB,EAAMmB,OACT,IAAInB,EAAMmB,UACVnB,EAAMmB,OAAO/B,IAAKJ,GAAS,IAAIA,MAASS,KAAK,UAEnD,OAAOO,EAAMY,QAAU,GAA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,EAAQxR,KAAK,yCAItE,IAAZsR,SAA6BvC,GAASuC,EAAS1H,QAE7B,IAAlB2H,SACIxC,GAASwC,EAAe,GAAGG,KAAKC,UAAU9C,EAAW,KAAM,SAG9D,CACLjF,OACA/E,cACAjC,SACAiM,eACK4C,QAAqB,IAAZH,EAAsC,GAAd,CAAEA,cACnCG,QAA2B,IAAlBF,EAAkD,GAApB,CAAEA,iBAElD","ignoreList":[]}
package/dist/codegen.js CHANGED
@@ -1,2 +1,2 @@
1
- import{readFile as e,writeFile as t,mkdir as n}from"fs/promises";import{relative as o,isAbsolute as i,resolve as s,dirname as r}from"path";import{createRequire as a}from"module";function l(e){return e.split(/[-_\s]+/u).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}var c,u=/^[A-Za-z_$][\w$]*$/u;function f(e,t){return`${e}${l(t)}`}function d(e,t,n,o){!0===o.markLocalizedAsDeprecated&&e.localized&&n.push(" /** @localized */");const i=e.required?"":"?";var s;n.push(` ${s=e.name,u.test(s)?s:`'${s.replace(/\\/gu,"\\\\").replace(/'/gu,"\\'")}'`}${i}: ${function(e,t){switch(e.kind){case"scalar":return!0===e.hasMany?`${e.typeRef}[]`:e.typeRef;case"array":return`${f(t,e.name)}[]`;case"blocks":return 0===e.blocks.length?"unknown[]":`(${e.blocks.map(n=>f(f(t,e.name),n.typeName)).join(" | ")})[]`;case"group":return f(t,e.name);case"relationship":{const t=`PayloadRelationship<${"string"==typeof e.target?`'${e.target}'`:e.target.map(e=>`'${e}'`).join(" | ")}>`;return e.hasMany?`${t}[]`:t}case"upload":return!0===e.hasMany?"PayloadMedia[]":"PayloadMedia";case"json":return"unknown";case"select":{if(0===e.options.length)return e.hasMany?"string[]":"string";const t=e.options.map(e=>`'${e}'`).join(" | ");return e.hasMany?`(${t})[]`:t}}}(e,t)};`)}function p(e,t,n,o){n.push(`export interface ${e} {`),n.push(` blockType: '${t.slug}';`);for(const i of t.fields)d(i,e,n,o);n.push("}","")}function g(e,t,n,o,i){for(const s of t){const t=f(e,s.name);if("array"===s.kind||"group"===s.kind){if(o.has(t))continue;o.add(t),g(t,s.fields,n,o,i),n.push(`export interface ${t} {`);for(const e of s.fields)d(e,t,n,i);n.push("}","")}else if("blocks"===s.kind)for(const e of s.blocks){const s=f(t,e.typeName);o.has(s)||(o.add(s),g(s,e.fields,n,o,i),p(s,e,n,i))}}}function h(e,t,n,o){g(e.typeName,e.fields,t,n,o),t.push(`export interface ${e.typeName} {`);for(const n of e.fields)d(n,e.typeName,t,o);t.push("}")}function m(e,t,n){if(0!==t.length){n.push(`export type ${e} = {`);for(const e of t)n.push(` '${e.slug}': ${e.typeName};`);n.push("};","")}}function v(e,t={}){const n=[t.header??"// Auto-generated by payload-live-preview/codegen.\n// Do not edit by hand — run `pll-codegen` to regenerate.\n/* eslint-disable */",""];n.push('import type { PayloadMedia, PayloadRelationship } from "payload-live-preview";',"");const o=/* @__PURE__ */new Set;for(const i of[...e.globals,...e.collections])h(i,n,o,t),n.push("");m("PayloadGlobals",e.globals,n),m("PayloadCollections",e.collections,n);const i=[];return e.globals.length>0&&i.push("keyof PayloadGlobals"),e.collections.length>0&&i.push("keyof PayloadCollections"),i.length>0&&n.push(`export type PayloadSlug = ${i.join(" | ")};`,""),n.join("\n").replace(/\n{3,}/gu,"\n\n")}function y(e,t,n){for(const o of e){if("group"===o.kind&&"__structural"===o.name){y(o.fields,t,n);continue}const e=""===t?o.name:`${t}.${o.name}`;if(n.push({path:e,kind:o.kind,localized:o.localized,required:o.required}),"group"===o.kind)y(o.fields,e,n);else if("array"===o.kind)y(o.fields,`${e}.*`,n);else if("blocks"===o.kind)for(const t of o.blocks)y(t.fields,`${e}.*.${t.slug}`,n)}}function $(e){const t=[];return y(e.fields,"",t),{slug:e.slug,typeName:e.typeName,fields:t}}function b(e){return{globals:e.globals.map($),collections:e.collections.map($)}}function k(e,t,n={}){const o=[],i=/* @__PURE__ */new Map;for(const[t,n]of[["global",e.globals],["collection",e.collections]])for(const e of n)i.set(`${t}:${e.slug}`,new Set(e.fields.map(e=>e.path)));const s=/* @__PURE__ */new Map;for(const e of t){const t=`${e.kind}:${e.slug}`,n=void 0===e.source?"":` (${e.source})`,r=i.get(t);if(void 0===r){o.push(`unknown ${e.kind} "${e.slug}"${n}`);continue}if(!r.has(e.path)){o.push(`${t} has no field "${e.path}"${n}`);continue}let a=s.get(t);void 0===a&&(a=/* @__PURE__ */new Set,s.set(t,a)),a.add(e.path)}if(!0===n.reportUnbound)for(const[e,t]of i){const n=s.get(e)??/* @__PURE__ */new Set;for(const i of t)n.has(i)||o.push(`${e} field "${i}" is never bound`)}return o}function w(){if(void 0===c)try{c=a(import.meta.url)("ts-morph")}catch(e){throw new Error("pll-codegen needs ts-morph: npm install --save-dev ts-morph",{cause:e})}return c}function x(){return w().Node}function S(e,t,n){e.diagnostics.push(`Skipped "${function(e){const t=e.getText().replace(/\s+/gu," ");return t.length>60?`${t.slice(0,57)}...`:t}(t)}" at ${function(e){return`${e.getSourceFile().getBaseName()}:${String(e.getStartLineNumber())}`}(t)}: ${n}.`)}function P(e){let t=e;for(;x().isParenthesizedExpression(t)||x().isAsExpression(t)||x().isSatisfiesExpression(t)||x().isNonNullExpression(t)||x().isTypeAssertion(t);)t=t.getExpression();return t}function A(e){if(!(x().isImportSpecifier(e)||x().isImportClause(e)||x().isNamespaceImport(e)||x().isExportSpecifier(e)))return[e];const t=e.getSymbol()?.getAliasedSymbol();return t?.getDeclarations()??[e]}function E(e){const t=e.getDefinitionNodes();return(t.length>0?t:e.getSymbol()?.getDeclarations()??[]).flatMap(A)}function N(e){return x().isVariableDeclaration(e)||x().isPropertyAssignment(e)?e.getInitializer():x().isExportAssignment(e)?e.getExpression():x().isShorthandPropertyAssignment(e)?e.getNameNode():void 0}function j(e,t){const n=e.getProperty(t);if(void 0!==n)return x().isPropertyAssignment(n)?n.getInitializer():x().isShorthandPropertyAssignment(n)?n.getNameNode():void 0}function C(e,t){return void 0!==e.getProperty(t)}function F(e,t=/* @__PURE__ */new Set){if(void 0===e||t.has(e))return;t.add(e);const n=P(e);if(x().isObjectLiteralExpression(n))return n;if(x().isCallExpression(n))return F(n.getArguments()[0],t);if(x().isIdentifier(n))for(const e of E(n)){const n=F(N(e),t);if(void 0!==n)return n}if(x().isPropertyAccessExpression(n)){const e=F(n.getExpression(),t);if(void 0!==e)return F(j(e,n.getName()),t)}}function z(e,t=/* @__PURE__ */new Set){if(void 0===e||t.has(e))return;t.add(e);const n=P(e);if(x().isArrayLiteralExpression(n))return n;if(x().isIdentifier(n))for(const e of E(n)){const n=z(N(e),t);if(void 0!==n)return n}if(x().isPropertyAccessExpression(n)){const e=F(n.getExpression(),t);if(void 0!==e)return z(j(e,n.getName()),t)}}function M(e,t){const n=[];for(const o of e.getElements()){if(!x().isSpreadElement(o)){n.push(o);continue}const e=z(o.getExpression());void 0!==e?n.push(...M(e,t)):S(t,o,"could not resolve the spread to an array literal, so its entries are missing")}return n}function L(e,t){const n=j(e,t);if(void 0===n)return;const o=P(n);return x().isStringLiteral(o)||x().isNoSubstitutionTemplateLiteral(o)?o.getLiteralValue():void 0}function D(e,t){const n=j(e,t);if(void 0===n)return;const o=P(n);return!!x().isTrueLiteral(o)||!x().isFalseLiteral(o)&&void 0}function I(e,t){return z(j(e,t))}function T(e){const t=j(e,"relationTo");if(void 0===t)return"unknown";const n=P(t);if(x().isStringLiteral(n))return n.getLiteralValue();const o=z(n);return void 0===o?"unknown":o.getElements().map(P).filter(e=>x().isStringLiteral(e)).map(e=>e.getLiteralValue())}var _="__structural",q=/* @__PURE__ */new Set(["tabs","row","collapsible"]),R={text:"string",textarea:"string",email:"string",richText:"unknown",number:"number",checkbox:"boolean",date:"string",code:"string",point:"[number, number]"},V=/* @__PURE__ */new Set(["text","number"]);function O(e,t){const n=[];for(const o of M(e,t)){const e=F(o);if(void 0===e){S(t,o,"could not resolve the field to an object literal");continue}const i=U(e,t);void 0!==i&&("group"===i.kind&&i.name===_?n.push(...i.fields):n.push(i))}return n}function Z(e,t){const n=I(e,"fields");return void 0!==n?O(n,t):(S(t,e,C(e,"fields")?"its `fields` could not be resolved to an array literal":"it has no `fields`"),[])}function B(e,t){const n=I(e,"tabs");if(void 0===n)return S(t,e,"its `tabs` could not be resolved to an array literal"),[];const o=[];for(const e of M(n,t)){const n=F(e);if(void 0===n){S(t,e,"could not resolve the tab to an object literal");continue}const i=L(n,"name"),s=Z(n,t);void 0===i?o.push(...s):o.push({kind:"group",name:i,required:!1,localized:!1,fields:s})}return o}function G(e,t){const n=I(e,"blocks");if(void 0===n)return S(t,e,"its `blocks` could not be resolved to an array literal"),[];const o=[];for(const e of M(n,t)){const n=F(e);if(void 0===n){S(t,e,"could not resolve the block to an object literal");continue}const i=L(n,"slug");void 0!==i?o.push({slug:i,typeName:l(i),fields:Z(n,t)}):S(t,e,"a block needs a string `slug`")}return o}function K(e,t){const n=I(e,"options");if(void 0===n)return S(t,e,"its `options` could not be resolved to an array literal"),[];const o=[];for(const e of M(n,t)){if(x().isStringLiteral(e)){o.push(e.getLiteralValue());continue}const n=F(e),i=void 0===n?void 0:L(n,"value");void 0===i?S(t,e,"an option needs a string or a `value`"):o.push(i)}return o}function U(e,t){const n=L(e,"type");if(void 0===n)return void S(t,e,"it has no string `type`");if("ui"===n)return;const o=L(e,"name");if(void 0===o&&!q.has(n))return void S(t,e,`a ${n} field needs a string \`name\``);const i={name:o??_,required:D(e,"required")??!1,localized:D(e,"localized")??!1},s=D(e,"hasMany")??!1;switch(n){case"array":return{...i,kind:"array",fields:Z(e,t)};case"group":case"row":case"collapsible":return{...i,kind:"group",fields:Z(e,t)};case"tabs":return{...i,kind:"group",fields:B(e,t)};case"blocks":return{...i,kind:"blocks",blocks:G(e,t)};case"relationship":return{...i,kind:"relationship",target:T(e),hasMany:s};case"upload":{const t=T(e);return{...i,kind:"upload",target:("string"==typeof t?t:t[0])??"media",hasMany:s}}case"json":return{...i,kind:"json"};case"select":case"radio":return{...i,kind:"select",options:K(e,t),hasMany:"select"===n&&s};default:return{...i,kind:"scalar",typeRef:R[n]??"unknown",hasMany:V.has(n)&&s}}}function J(e){if(x().isExportAssignment(e))return e.getExpression()}function H(e,t,n){const o=j(e,t);if(void 0===o)return[];const i=z(o);if(void 0===i)return S(n,o,`could not resolve \`${t}\` to an array literal`),[];const s=[];for(const e of M(i,n)){const t=F(e);if(void 0===t){S(n,e,"could not resolve the config entry to an object literal");continue}const o=L(t,"slug");if(void 0===o){S(n,e,"the config entry has no string `slug`");continue}const i=I(t,"fields");void 0===i&&S(n,t,C(t,"fields")?`the \`fields\` of "${o}" could not be resolved to an array literal`:`"${o}" has no \`fields\``),s.push({slug:o,typeName:l(o),fields:void 0===i?[]:O(i,n)})}return s}function Q(e){const t=e.project??new(w().Project)(void 0!==e.tsConfigFilePath?{tsConfigFilePath:e.tsConfigFilePath}:{skipAddingFilesFromTsConfig:!0}),n=t.addSourceFileAtPathIfExists(e.configPath);if(void 0===n)return{globals:[],collections:[],diagnostics:[`Could not open ${e.configPath}`]};t.resolveSourceFileDependencies();const o={diagnostics:[]},i=function(e,t){const n=e.getDefaultExportSymbol();if(void 0!==n){for(const e of n.getDeclarations()){const t=F(J(e));if(void 0!==t)return t}for(const t of e.getDescendantsOfKind(w().SyntaxKind.CallExpression)){const e=t.getExpression();if(!x().isIdentifier(e)||"buildConfig"!==e.getText())continue;const n=F(t.getArguments()[0]);if(void 0!==n)return n}}else t.diagnostics.push("payload.config.ts has no default export.")}(n,o);return void 0===i?{globals:[],collections:[],diagnostics:[...o.diagnostics,"Could not locate a buildConfig({...}) call or `export default {...}` in the config file."]}:{globals:H(i,"globals",o),collections:H(i,"collections",o),diagnostics:o.diagnostics}}var W=/<([a-z][a-z0-9-]*)((?:"[^"]*"|'[^']*'|[^>"'])*)>([^<]*)<\/\1\s*>/gu,X=/^\s*\{([^{}]*)\}\s*$/u,Y=/\{([^{}]*)\}/u,ee=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+$/u,te="data-payload-field";function ne(e,t){let n=1;for(let o=0;o<t;o+=1)10===e.charCodeAt(o)&&(n+=1);return n}function oe(e){return e.slice(e.indexOf(".")+1)}function ie(e){const t=e.replace(/\s+/gu," ").trim();return t.length>60?`${t.slice(0,57)}…`:t}function se(e,t){const n=e.trim();if(0===n.length)return"the element is empty";if(!ee.test(n))return"not a plain field access — a call, an operator or an index cannot be traced to one field";const o=oe(n);return t.has(o)?void 0:`the schema has no field \`${o}\`; the binding would name something that never arrives`}function re(e,t){const n=[],o=[];for(const i of e.matchAll(W)){const[,s="",r="",a=""]=i,l=ne(e,i.index);if(r.includes(te))continue;const c=X.exec(a);if(null===c){null!==Y.exec(a)&&o.push({line:l,reason:"the value is printed beside other content — a binding replaces the whole text, so the markup has to be split first",expression:ie(a)});continue}const u=c[1]??"",f=se(u,t.paths);void 0===f?n.push({insertAt:i.index+1+s.length,path:oe(u.trim()),line:l,tag:s}):o.push({line:l,reason:f,expression:ie(u)})}return{candidates:n,refusals:o}}function ae(e){return`${te}="${e.path}"`}function le(e,t,n=ae){let o=e;for(const e of[...t].sort((e,t)=>t.insertAt-e.insertAt))o=`${o.slice(0,e.insertAt)} ${n(e)}${o.slice(e.insertAt)}`;return o}var ce=[".astro",".jsx",".tsx",".svelte"];function ue(e){const t=/* @__PURE__ */new Set;for(const n of[...e.globals,...e.collections])for(const e of n.fields)e.path.includes("*")||t.add(e.path);return t}async function fe(n){const i=n.io?.read??(t=>e(t,"utf8")),s=n.io?.write??((e,n)=>t(e,n,"utf8")),r=n.cwd??process.cwd(),a=ue(n.inventory),l=[];for(const e of n.files){const t=await i(e),{candidates:c,refusals:u}=re(t,{paths:a}),f=0===c.length?t:le(t,c),d=f!==t;d&&!0===n.write&&await s(e,f),l.push({file:o(r,e)||e,code:f,annotations:c,refusals:u,changed:d})}return{files:l,annotationCount:l.reduce((e,t)=>e+t.annotations.length,0),refusalCount:l.reduce((e,t)=>e+t.refusals.length,0),written:!0===n.write}}function de(e){const t=[];for(const n of e.files)if(0!==n.annotations.length||0!==n.refusals.length){t.push(n.file);for(const e of n.annotations)t.push(` ${String(e.line)}: <${e.tag}> → ${e.path}`);for(const e of n.refusals)t.push(` ${String(e.line)}: left alone — ${e.reason} (${e.expression})`)}const n=e.written?"annotated":"would annotate";return t.push(`${n} ${String(e.annotationCount)} element(s); ${String(e.refusalCount)} left for a human`),`${t.join("\n")}\n`}async function pe(e,o){await n(r(e),{recursive:!0}),await t(e,o,"utf8")}async function ge(e){const t=e.cwd??process.cwd(),n=e=>i(e)?e:s(t,e),o=Q({configPath:n(e.configPath),...void 0!==e.project?{project:e.project}:{},...void 0!==e.tsConfigFilePath?{tsConfigFilePath:e.tsConfigFilePath}:{}}),r=v(o,e),a=b(o),l=[...o.diagnostics],c=void 0===e.outFile?void 0:n(e.outFile),u=void 0===e.inventoryFile?void 0:n(e.inventoryFile),f=[c,u].filter(e=>void 0!==e),d=o.globals.length+o.collections.length===0;return d&&f.length>0?l.push(`Nothing written: the schema is empty (0 globals, 0 collections), so ${f.join(" and ")} were left as they are.`):(void 0!==c&&await pe(c,r),void 0!==u&&await pe(u,`${JSON.stringify(a,null,2)}\n`)),{code:r,diagnostics:l,schema:o,inventory:a,...d||void 0===c?{}:{outFile:c},...d||void 0===u?{}:{inventoryFile:u}}}export{ce as ANNOTATABLE_EXTENSIONS,ue as annotatablePaths,fe as annotateTemplates,b as buildPreviewInventory,k as checkPreviewBindings,v as emitTypes,Q as extractSchema,de as formatAnnotateReport,ge as generateTypes};
1
+ import{readFile as e,writeFile as t,mkdir as n}from"fs/promises";import{relative as o,isAbsolute as i,resolve as s,dirname as r}from"path";import{createRequire as a}from"module";function l(e){return e.split(/[-_\s]+/u).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}var c,u=/^[A-Za-z_$][\w$]*$/u;function f(e,t){return`${e}${l(t)}`}function d(e,t,n,o){!0===o.markLocalizedAsDeprecated&&e.localized&&n.push(" /** @localized */");const i=e.required?"":"?";var s;n.push(` ${s=e.name,u.test(s)?s:`'${s.replace(/\\/gu,"\\\\").replace(/'/gu,"\\'")}'`}${i}: ${function(e,t){switch(e.kind){case"scalar":return!0===e.hasMany?`${e.typeRef}[]`:e.typeRef;case"array":return`${f(t,e.name)}[]`;case"blocks":return 0===e.blocks.length?"unknown[]":`(${e.blocks.map(n=>f(f(t,e.name),n.typeName)).join(" | ")})[]`;case"group":return f(t,e.name);case"relationship":{const t=`PayloadRelationship<${"string"==typeof e.target?`'${e.target}'`:e.target.map(e=>`'${e}'`).join(" | ")}>`;return e.hasMany?`${t}[]`:t}case"upload":return!0===e.hasMany?"PayloadMedia[]":"PayloadMedia";case"json":return"unknown";case"select":{if(0===e.options.length)return e.hasMany?"string[]":"string";const t=e.options.map(e=>`'${e}'`).join(" | ");return e.hasMany?`(${t})[]`:t}}}(e,t)};`)}function p(e,t,n,o){n.push(`export interface ${e} {`),n.push(` blockType: '${t.slug}';`);for(const i of t.fields)d(i,e,n,o);n.push("}","")}function g(e,t,n,o,i){for(const s of t){const t=f(e,s.name);if("array"===s.kind||"group"===s.kind){if(o.has(t))continue;o.add(t),g(t,s.fields,n,o,i),n.push(`export interface ${t} {`);for(const e of s.fields)d(e,t,n,i);n.push("}","")}else if("blocks"===s.kind)for(const e of s.blocks){const s=f(t,e.typeName);o.has(s)||(o.add(s),g(s,e.fields,n,o,i),p(s,e,n,i))}}}function h(e,t,n,o){g(e.typeName,e.fields,t,n,o),t.push(`export interface ${e.typeName} {`);for(const n of e.fields)d(n,e.typeName,t,o);t.push("}")}function m(e,t,n){if(0!==t.length){n.push(`export type ${e} = {`);for(const e of t)n.push(` '${e.slug}': ${e.typeName};`);n.push("};","")}}function v(e,t={}){const n=[t.header??"// Auto-generated by payload-live-preview/codegen.\n// Do not edit by hand — run `pll-codegen` to regenerate.\n/* eslint-disable */",""];n.push('import type { PayloadMedia, PayloadRelationship } from "payload-live-preview";',"");const o=/* @__PURE__ */new Set;for(const i of[...e.globals,...e.collections])h(i,n,o,t),n.push("");m("PayloadGlobals",e.globals,n),m("PayloadCollections",e.collections,n);const i=[];return e.globals.length>0&&i.push("keyof PayloadGlobals"),e.collections.length>0&&i.push("keyof PayloadCollections"),i.length>0&&n.push(`export type PayloadSlug = ${i.join(" | ")};`,""),n.join("\n").replace(/\n{3,}/gu,"\n\n")}function y(e,t,n){for(const o of e){if("group"===o.kind&&"__structural"===o.name){y(o.fields,t,n);continue}const e=""===t?o.name:`${t}.${o.name}`;if(n.push({path:e,kind:o.kind,localized:o.localized,required:o.required}),"group"===o.kind)y(o.fields,e,n);else if("array"===o.kind)y(o.fields,`${e}.*`,n);else if("blocks"===o.kind)for(const t of o.blocks)y(t.fields,`${e}.*.${t.slug}`,n)}}function $(e){const t=[];return y(e.fields,"",t),{slug:e.slug,typeName:e.typeName,fields:t}}function b(e){return{globals:e.globals.map($),collections:e.collections.map($)}}function w(e,t,n={}){const o=[],i=/* @__PURE__ */new Map;for(const[t,n]of[["global",e.globals],["collection",e.collections]])for(const e of n)i.set(`${t}:${e.slug}`,new Set(e.fields.map(e=>e.path)));const s=/* @__PURE__ */new Map;for(const e of t){const t=`${e.kind}:${e.slug}`,n=void 0===e.source?"":` (${e.source})`,r=i.get(t);if(void 0===r){o.push(`unknown ${e.kind} "${e.slug}"${n}`);continue}if(!r.has(e.path)){o.push(`${t} has no field "${e.path}"${n}`);continue}let a=s.get(t);void 0===a&&(a=/* @__PURE__ */new Set,s.set(t,a)),a.add(e.path)}if(!0===n.reportUnbound)for(const[e,t]of i){const n=s.get(e)??/* @__PURE__ */new Set;for(const i of t)n.has(i)||o.push(`${e} field "${i}" is never bound`)}return o}function k(){if(void 0===c)try{c=a(import.meta.url)("ts-morph")}catch(e){throw new Error("pll-codegen needs ts-morph: npm install --save-dev ts-morph",{cause:e})}return c}function x(){return k().Node}function S(e,t,n){e.diagnostics.push(`Skipped "${function(e){const t=e.getText().replace(/\s+/gu," ");return t.length>60?`${t.slice(0,57)}...`:t}(t)}" at ${function(e){return`${e.getSourceFile().getBaseName()}:${String(e.getStartLineNumber())}`}(t)}: ${n}.`)}function A(e){let t=e;for(;x().isParenthesizedExpression(t)||x().isAsExpression(t)||x().isSatisfiesExpression(t)||x().isNonNullExpression(t)||x().isTypeAssertion(t);)t=t.getExpression();return t}function P(e){if(!(x().isImportSpecifier(e)||x().isImportClause(e)||x().isNamespaceImport(e)||x().isExportSpecifier(e)))return[e];const t=e.getSymbol()?.getAliasedSymbol();return t?.getDeclarations()??[e]}function E(e){const t=e.getDefinitionNodes();return(t.length>0?t:e.getSymbol()?.getDeclarations()??[]).flatMap(P)}function N(e){return x().isVariableDeclaration(e)||x().isPropertyAssignment(e)?e.getInitializer():x().isExportAssignment(e)?e.getExpression():x().isShorthandPropertyAssignment(e)?e.getNameNode():void 0}function j(e,t){const n=e.getProperty(t);if(void 0!==n)return x().isPropertyAssignment(n)?n.getInitializer():x().isShorthandPropertyAssignment(n)?n.getNameNode():void 0}function C(e,t){return void 0!==e.getProperty(t)}function z(e,t=/* @__PURE__ */new Set){if(void 0===e||t.has(e))return;t.add(e);const n=A(e);if(x().isObjectLiteralExpression(n))return n;if(x().isCallExpression(n))return z(n.getArguments()[0],t);if(x().isIdentifier(n))for(const e of E(n)){const n=z(N(e),t);if(void 0!==n)return n}if(x().isPropertyAccessExpression(n)){const e=z(n.getExpression(),t);if(void 0!==e)return z(j(e,n.getName()),t)}}function F(e,t=/* @__PURE__ */new Set){if(void 0===e||t.has(e))return;t.add(e);const n=A(e);if(x().isArrayLiteralExpression(n))return n;if(x().isIdentifier(n))for(const e of E(n)){const n=F(N(e),t);if(void 0!==n)return n}if(x().isPropertyAccessExpression(n)){const e=z(n.getExpression(),t);if(void 0!==e)return F(j(e,n.getName()),t)}}function M(e,t){const n=[];for(const o of e.getElements()){if(!x().isSpreadElement(o)){n.push(o);continue}const e=F(o.getExpression());void 0!==e?n.push(...M(e,t)):S(t,o,"could not resolve the spread to an array literal, so its entries are missing")}return n}function L(e,t){const n=j(e,t);if(void 0===n)return;const o=A(n);return x().isStringLiteral(o)||x().isNoSubstitutionTemplateLiteral(o)?o.getLiteralValue():void 0}function _(e,t){const n=j(e,t);if(void 0===n)return;const o=A(n);return!!x().isTrueLiteral(o)||!x().isFalseLiteral(o)&&void 0}function D(e,t){return F(j(e,t))}function I(e){const t=j(e,"relationTo");if(void 0===t)return"unknown";const n=A(t);if(x().isStringLiteral(n))return n.getLiteralValue();const o=F(n);return void 0===o?"unknown":o.getElements().map(A).filter(e=>x().isStringLiteral(e)).map(e=>e.getLiteralValue())}var T="__structural",q=/* @__PURE__ */new Set(["tabs","row","collapsible"]),Z={text:"string",textarea:"string",email:"string",richText:"unknown",number:"number",checkbox:"boolean",date:"string",code:"string",point:"[number, number]"},O=/* @__PURE__ */new Set(["text","number"]);function R(e,t){const n=[];for(const o of M(e,t)){const e=z(o);if(void 0===e){S(t,o,"could not resolve the field to an object literal");continue}const i=U(e,t);void 0!==i&&("group"===i.kind&&i.name===T?n.push(...i.fields):n.push(i))}return n}function V(e,t){const n=D(e,"fields");return void 0!==n?R(n,t):(S(t,e,C(e,"fields")?"its `fields` could not be resolved to an array literal":"it has no `fields`"),[])}function B(e,t){const n=D(e,"tabs");if(void 0===n)return S(t,e,"its `tabs` could not be resolved to an array literal"),[];const o=[];for(const e of M(n,t)){const n=z(e);if(void 0===n){S(t,e,"could not resolve the tab to an object literal");continue}const i=L(n,"name"),s=V(n,t);void 0===i?o.push(...s):o.push({kind:"group",name:i,required:!1,localized:!1,fields:s})}return o}function G(e,t){const n=D(e,"blocks");if(void 0===n)return S(t,e,"its `blocks` could not be resolved to an array literal"),[];const o=[];for(const e of M(n,t)){const n=z(e);if(void 0===n){S(t,e,"could not resolve the block to an object literal");continue}const i=L(n,"slug");void 0!==i?o.push({slug:i,typeName:l(i),fields:V(n,t)}):S(t,e,"a block needs a string `slug`")}return o}function K(e,t){const n=D(e,"options");if(void 0===n)return S(t,e,"its `options` could not be resolved to an array literal"),[];const o=[];for(const e of M(n,t)){if(x().isStringLiteral(e)){o.push(e.getLiteralValue());continue}const n=z(e),i=void 0===n?void 0:L(n,"value");void 0===i?S(t,e,"an option needs a string or a `value`"):o.push(i)}return o}function U(e,t){const n=L(e,"type");if(void 0===n)return void S(t,e,"it has no string `type`");if("ui"===n)return;const o=L(e,"name");if(void 0===o&&!q.has(n))return void S(t,e,`a ${n} field needs a string \`name\``);const i={name:o??T,required:_(e,"required")??!1,localized:_(e,"localized")??!1},s=_(e,"hasMany")??!1;switch(n){case"array":return{...i,kind:"array",fields:V(e,t)};case"group":case"row":case"collapsible":return{...i,kind:"group",fields:V(e,t)};case"tabs":return{...i,kind:"group",fields:B(e,t)};case"blocks":return{...i,kind:"blocks",blocks:G(e,t)};case"relationship":return{...i,kind:"relationship",target:I(e),hasMany:s};case"upload":{const t=I(e);return{...i,kind:"upload",target:("string"==typeof t?t:t[0])??"media",hasMany:s}}case"json":return{...i,kind:"json"};case"select":case"radio":return{...i,kind:"select",options:K(e,t),hasMany:"select"===n&&s};default:return{...i,kind:"scalar",typeRef:Z[n]??"unknown",hasMany:O.has(n)&&s}}}function J(e){if(x().isExportAssignment(e))return e.getExpression()}function H(e,t,n){const o=j(e,t);if(void 0===o)return[];const i=F(o);if(void 0===i)return S(n,o,`could not resolve \`${t}\` to an array literal`),[];const s=[];for(const e of M(i,n)){const t=z(e);if(void 0===t){S(n,e,"could not resolve the config entry to an object literal");continue}const o=L(t,"slug");if(void 0===o){S(n,e,"the config entry has no string `slug`");continue}const i=D(t,"fields");void 0===i&&S(n,t,C(t,"fields")?`the \`fields\` of "${o}" could not be resolved to an array literal`:`"${o}" has no \`fields\``),s.push({slug:o,typeName:l(o),fields:void 0===i?[]:R(i,n)})}return s}function Q(e){const t=e.project??new(k().Project)(void 0!==e.tsConfigFilePath?{tsConfigFilePath:e.tsConfigFilePath}:{skipAddingFilesFromTsConfig:!0}),n=t.addSourceFileAtPathIfExists(e.configPath);if(void 0===n)return{globals:[],collections:[],diagnostics:[`Could not open ${e.configPath}`]};t.resolveSourceFileDependencies();const o={diagnostics:[]},i=function(e,t){const n=e.getDefaultExportSymbol();if(void 0!==n){for(const e of n.getDeclarations()){const t=z(J(e));if(void 0!==t)return t}for(const t of e.getDescendantsOfKind(k().SyntaxKind.CallExpression)){const e=t.getExpression();if(!x().isIdentifier(e)||"buildConfig"!==e.getText())continue;const n=z(t.getArguments()[0]);if(void 0!==n)return n}}else t.diagnostics.push("payload.config.ts has no default export.")}(n,o);return void 0===i?{globals:[],collections:[],diagnostics:[...o.diagnostics,"Could not locate a buildConfig({...}) call or `export default {...}` in the config file."]}:{globals:H(i,"globals",o),collections:H(i,"collections",o),diagnostics:o.diagnostics}}var W=/<([a-z][a-z0-9-]*)((?:"[^"]*"|'[^']*'|[^>"'])*)>([^<]*)<\/\1\s*>/gu,X=/^\s*\{([^{}]*)\}\s*$/u,Y=/\{([^{}]*)\}/u,ee=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+$/u,te="data-payload-field",ne=[/\.(?:map|flatMap|forEach)\(\s*(?:async\s+)?\(?\s*([A-Za-z_$][\w$]*)/gu,/\bfor\s*\(\s*(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s+of\b/gu,/\{#each\s[^}]*?\sas\s+([A-Za-z_$][\w$]*)/gu];function oe(e,t){let n=1;for(let o=0;o<t;o+=1)10===e.charCodeAt(o)&&(n+=1);return n}function ie(e){return e.slice(e.indexOf(".")+1)}function se(e){const t=e.replace(/\s+/gu," ").trim();return t.length>60?`${t.slice(0,57)}…`:t}function re(e,t,n){const o=e.trim();if(0===o.length)return"the element is empty";if(!ee.test(o))return"not a plain field access — a call, an operator or an index cannot be traced to one field";const i=ie(o),s=o.slice(0,o.indexOf("."));return n.has(s)?`\`${s}\` is a loop item — a binding names a field of the document, and \`${i}\` there is a different value, or none`:t.has(i)?void 0:`the schema has no field \`${i}\`; the binding would name something that never arrives`}function ae(e,t){const n=[],o=[],i=function(e){const t=/* @__PURE__ */new Set;for(const n of ne)for(const o of e.matchAll(n))void 0!==o[1]&&t.add(o[1]);return t}(e);for(const s of e.matchAll(W)){const[,r="",a="",l=""]=s,c=oe(e,s.index);if(a.includes(te))continue;const u=X.exec(l);if(null===u){null!==Y.exec(l)&&o.push({line:c,reason:"the value is printed beside other content — a binding replaces the whole text, so the markup has to be split first",expression:se(l)});continue}const f=u[1]??"",d=re(f,t.paths,i);void 0===d?n.push({insertAt:s.index+1+r.length,path:ie(f.trim()),line:c,tag:r}):o.push({line:c,reason:d,expression:se(f)})}return{candidates:n,refusals:o}}function le(e){return`${te}="${e.path}"`}function ce(e,t,n=le){let o=e;for(const e of[...t].sort((e,t)=>t.insertAt-e.insertAt))o=`${o.slice(0,e.insertAt)} ${n(e)}${o.slice(e.insertAt)}`;return o}var ue=[".astro",".jsx",".tsx",".svelte"];function fe(e){const t=/* @__PURE__ */new Set;for(const n of[...e.globals,...e.collections])for(const e of n.fields)e.path.includes("*")||t.add(e.path);return t}async function de(n){const i=n.io?.read??(t=>e(t,"utf8")),s=n.io?.write??((e,n)=>t(e,n,"utf8")),r=n.cwd??process.cwd(),a=fe(n.inventory),l=[];for(const e of n.files){const t=await i(e),{candidates:c,refusals:u}=ae(t,{paths:a}),f=0===c.length?t:ce(t,c),d=f!==t;d&&!0===n.write&&await s(e,f),l.push({file:o(r,e)||e,code:f,annotations:c,refusals:u,changed:d})}return{files:l,annotationCount:l.reduce((e,t)=>e+t.annotations.length,0),refusalCount:l.reduce((e,t)=>e+t.refusals.length,0),written:!0===n.write}}function pe(e){const t=[];for(const n of e.files)if(0!==n.annotations.length||0!==n.refusals.length){t.push(n.file);for(const e of n.annotations)t.push(` ${String(e.line)}: <${e.tag}> → ${e.path}`);for(const e of n.refusals)t.push(` ${String(e.line)}: left alone — ${e.reason} (${e.expression})`)}const n=e.written?"annotated":"would annotate";return t.push(`${n} ${String(e.annotationCount)} element(s); ${String(e.refusalCount)} left for a human`),`${t.join("\n")}\n`}async function ge(e,o){await n(r(e),{recursive:!0}),await t(e,o,"utf8")}async function he(e){const t=e.cwd??process.cwd(),n=e=>i(e)?e:s(t,e),o=Q({configPath:n(e.configPath),...void 0!==e.project?{project:e.project}:{},...void 0!==e.tsConfigFilePath?{tsConfigFilePath:e.tsConfigFilePath}:{}}),r=v(o,e),a=b(o),l=[...o.diagnostics],c=void 0===e.outFile?void 0:n(e.outFile),u=void 0===e.inventoryFile?void 0:n(e.inventoryFile),f=[c,u].filter(e=>void 0!==e),d=o.globals.length+o.collections.length===0;return d&&f.length>0?l.push(`Nothing written: the schema is empty (0 globals, 0 collections), so ${f.join(" and ")} were left as they are.`):(void 0!==c&&await ge(c,r),void 0!==u&&await ge(u,`${JSON.stringify(a,null,2)}\n`)),{code:r,diagnostics:l,schema:o,inventory:a,...d||void 0===c?{}:{outFile:c},...d||void 0===u?{}:{inventoryFile:u}}}export{ue as ANNOTATABLE_EXTENSIONS,fe as annotatablePaths,de as annotateTemplates,b as buildPreviewInventory,w as checkPreviewBindings,v as emitTypes,Q as extractSchema,pe as formatAnnotateReport,he as generateTypes};
2
2
  //# sourceMappingURL=codegen.js.map