payload-live-preview 2.2.0 → 2.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +32 -18
- package/dist/adapters/astro/index.js +1 -1
- package/dist/adapters/astro/index.js.map +1 -1
- package/dist/adapters/astro/middleware-entry.js +1 -1
- package/dist/adapters/astro/middleware-entry.js.map +1 -1
- package/dist/adapters/nextjs/index.js +1 -1
- package/dist/adapters/nextjs/index.js.map +1 -1
- package/dist/adapters/nuxt/index.js +1 -1
- package/dist/adapters/nuxt/index.js.map +1 -1
- package/dist/adapters/react/index.d.ts +2 -2
- package/dist/adapters/react/index.js +1 -1
- package/dist/adapters/react/index.js.map +1 -1
- package/dist/adapters/sveltekit/index.js +1 -1
- package/dist/adapters/sveltekit/index.js.map +1 -1
- package/dist/adapters/vue/index.d.ts +2 -2
- package/dist/adapters/vue/index.js +1 -1
- package/dist/adapters/vue/index.js.map +1 -1
- package/dist/annotate.d.ts +22 -15
- package/dist/annotate.js +1 -1
- package/dist/annotate.js.map +1 -1
- package/dist/client.cjs +1 -1
- package/dist/client.cjs.map +1 -1
- package/dist/client.d.cts +112 -112
- package/dist/client.d.ts +112 -112
- package/dist/client.js +1 -1
- package/dist/client.js.map +1 -1
- package/dist/codegen-cli.js +1 -1
- package/dist/codegen-cli.js.map +1 -1
- package/dist/codegen.cjs +1 -1
- package/dist/codegen.cjs.map +1 -1
- package/dist/codegen.d.cts +14 -16
- package/dist/codegen.d.ts +14 -16
- package/dist/codegen.js +1 -1
- package/dist/codegen.js.map +1 -1
- package/dist/core.cjs +1 -1
- package/dist/core.cjs.map +1 -1
- package/dist/core.d.cts +176 -170
- package/dist/core.d.ts +176 -170
- package/dist/core.js +1 -1
- package/dist/core.js.map +1 -1
- package/dist/doctor-cli.d.ts +1 -1
- package/dist/doctor-cli.js +1 -1
- package/dist/doctor-cli.js.map +1 -1
- package/dist/doctor.d.ts +2 -2
- package/dist/doctor.js +1 -1
- package/dist/doctor.js.map +1 -1
- package/dist/{document-session-DWi9H3Qk.d.ts → document-session-Bkd181PV.d.ts} +3 -2
- package/dist/fragment.cjs.map +1 -1
- package/dist/fragment.d.cts +1 -1
- package/dist/fragment.d.ts +1 -1
- package/dist/fragment.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +181 -175
- package/dist/index.d.ts +181 -175
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/lean.cjs +1 -1
- package/dist/lean.cjs.map +1 -1
- package/dist/lean.js +1 -1
- package/dist/lean.js.map +1 -1
- package/dist/lexical.cjs +1 -1
- package/dist/lexical.cjs.map +1 -1
- package/dist/lexical.js +1 -1
- package/dist/lexical.js.map +1 -1
- package/dist/plugins.cjs +1 -1
- package/dist/plugins.cjs.map +1 -1
- package/dist/plugins.d.cts +1 -1
- package/dist/plugins.d.ts +1 -1
- package/dist/plugins.js +1 -1
- package/dist/plugins.js.map +1 -1
- package/dist/{probe-DpMZ4fOS.d.ts → probe-D-IHg9dF.d.ts} +1 -1
- package/dist/structural.cjs +2 -2
- package/dist/structural.cjs.map +1 -1
- package/dist/structural.d.cts +27 -27
- package/dist/structural.d.ts +27 -27
- package/dist/structural.js +2 -2
- package/dist/structural.js.map +1 -1
- package/package.json +7 -6
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 x(){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 k(){return x().Node}function w(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 S(e){let t=e;for(;k().isParenthesizedExpression(t)||k().isAsExpression(t)||k().isSatisfiesExpression(t)||k().isNonNullExpression(t)||k().isTypeAssertion(t);)t=t.getExpression();return t}function A(e){if(!(k().isImportSpecifier(e)||k().isImportClause(e)||k().isNamespaceImport(e)||k().isExportSpecifier(e)))return[e];const t=e.getSymbol()?.getAliasedSymbol();return t?.getDeclarations()??[e]}function P(e){const t=e.getDefinitionNodes();return(t.length>0?t:e.getSymbol()?.getDeclarations()??[]).flatMap(A)}function E(e){return k().isVariableDeclaration(e)||k().isPropertyAssignment(e)?e.getInitializer():k().isExportAssignment(e)?e.getExpression():k().isShorthandPropertyAssignment(e)?e.getNameNode():void 0}function N(e,t){const n=e.getProperty(t);if(void 0!==n)return k().isPropertyAssignment(n)?n.getInitializer():k().isShorthandPropertyAssignment(n)?n.getNameNode():void 0}function j(e,t){return void 0!==e.getProperty(t)}function C(e,t=/* @__PURE__ */new Set){if(void 0===e||t.has(e))return;t.add(e);const n=S(e);if(k().isObjectLiteralExpression(n))return n;if(k().isCallExpression(n))return C(n.getArguments()[0],t);if(k().isIdentifier(n))for(const e of P(n)){const n=C(E(e),t);if(void 0!==n)return n}if(k().isPropertyAccessExpression(n)){const e=C(n.getExpression(),t);if(void 0!==e)return C(N(e,n.getName()),t)}}function z(e,t=/* @__PURE__ */new Set){if(void 0===e||t.has(e))return;t.add(e);const n=S(e);if(k().isArrayLiteralExpression(n))return n;if(k().isIdentifier(n))for(const e of P(n)){const n=z(E(e),t);if(void 0!==n)return n}if(k().isPropertyAccessExpression(n)){const e=C(n.getExpression(),t);if(void 0!==e)return z(N(e,n.getName()),t)}}function F(e,t){const n=[];for(const o of e.getElements()){if(!k().isSpreadElement(o)){n.push(o);continue}const e=z(o.getExpression());void 0!==e?n.push(...F(e,t)):w(t,o,"could not resolve the spread to an array literal, so its entries are missing")}return n}function L(e,t){const n=N(e,t);if(void 0===n)return;const o=S(n);return k().isStringLiteral(o)||k().isNoSubstitutionTemplateLiteral(o)?o.getLiteralValue():void 0}function M(e,t){const n=N(e,t);if(void 0===n)return;const o=S(n);return!!k().isTrueLiteral(o)||!k().isFalseLiteral(o)&&void 0}function _(e,t){return z(N(e,t))}function D(e){const t=N(e,"relationTo");if(void 0===t)return"unknown";const n=S(t);if(k().isStringLiteral(n))return n.getLiteralValue();const o=z(n);return void 0===o?"unknown":o.getElements().map(S).filter(e=>k().isStringLiteral(e)).map(e=>e.getLiteralValue())}var I="__structural",T=/* @__PURE__ */new Set(["tabs","row","collapsible"]),q={text:"string",textarea:"string",email:"string",richText:"unknown",number:"number",checkbox:"boolean",date:"string",code:"string",point:"[number, number]"},Z=/* @__PURE__ */new Set(["text","number"]);function O(e,t){const n=[];for(const o of F(e,t)){const e=C(o);if(void 0===e){w(t,o,"could not resolve the field to an object literal");continue}const i=K(e,t);void 0!==i&&("group"===i.kind&&i.name===I?n.push(...i.fields):n.push(i))}return n}function R(e,t){const n=_(e,"fields");return void 0!==n?O(n,t):(w(t,e,j(e,"fields")?"its `fields` could not be resolved to an array literal":"it has no `fields`"),[])}function V(e,t){const n=_(e,"tabs");if(void 0===n)return w(t,e,"its `tabs` could not be resolved to an array literal"),[];const o=[];for(const e of F(n,t)){const n=C(e);if(void 0===n){w(t,e,"could not resolve the tab to an object literal");continue}const i=L(n,"name"),s=R(n,t);void 0===i?o.push(...s):o.push({kind:"group",name:i,required:!1,localized:!1,fields:s})}return o}function B(e,t){const n=_(e,"blocks");if(void 0===n)return w(t,e,"its `blocks` could not be resolved to an array literal"),[];const o=[];for(const e of F(n,t)){const n=C(e);if(void 0===n){w(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:R(n,t)}):w(t,e,"a block needs a string `slug`")}return o}function G(e,t){const n=_(e,"options");if(void 0===n)return w(t,e,"its `options` could not be resolved to an array literal"),[];const o=[];for(const e of F(n,t)){if(k().isStringLiteral(e)){o.push(e.getLiteralValue());continue}const n=C(e),i=void 0===n?void 0:L(n,"value");void 0===i?w(t,e,"an option needs a string or a `value`"):o.push(i)}return o}function K(e,t){const n=L(e,"type");if(void 0===n)return void w(t,e,"it has no string `type`");if("ui"===n)return;const o=L(e,"name");if(void 0===o&&!T.has(n))return void w(t,e,`a ${n} field needs a string \`name\``);const i={name:o??I,required:M(e,"required")??!1,localized:M(e,"localized")??!1},s=M(e,"hasMany")??!1;switch(n){case"array":return{...i,kind:"array",fields:R(e,t)};case"group":case"row":case"collapsible":return{...i,kind:"group",fields:R(e,t)};case"tabs":return{...i,kind:"group",fields:V(e,t)};case"blocks":return{...i,kind:"blocks",blocks:B(e,t)};case"relationship":return{...i,kind:"relationship",target:D(e),hasMany:s};case"upload":{const t=D(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:G(e,t),hasMany:"select"===n&&s};default:return{...i,kind:"scalar",typeRef:q[n]??"unknown",hasMany:Z.has(n)&&s}}}function J(e){if(k().isExportAssignment(e))return e.getExpression()}function U(e,t,n){const o=N(e,t);if(void 0===o)return[];const i=z(o);if(void 0===i)return w(n,o,`could not resolve \`${t}\` to an array literal`),[];const s=[];for(const e of F(i,n)){const t=C(e);if(void 0===t){w(n,e,"could not resolve the config entry to an object literal");continue}const o=L(t,"slug");if(void 0===o){w(n,e,"the config entry has no string `slug`");continue}const i=_(t,"fields");void 0===i&&w(n,t,j(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 H(e){const t=e.project??new(x().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=C(J(e));if(void 0!==t)return t}for(const t of e.getDescendantsOfKind(x().SyntaxKind.CallExpression)){const e=t.getExpression();if(!k().isIdentifier(e)||"buildConfig"!==e.getText())continue;const n=C(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:U(i,"globals",o),collections:U(i,"collections",o),diagnostics:o.diagnostics}}var Q=/<([a-z][a-z0-9-]*)((?:"[^"]*"|'[^']*'|[^>"'])*)>([^<]*)<\/\1\s*>/gu,W=/^\s*\{([^{}]*)\}\s*$/u,X=/\{([^{}]*)\}/u,Y=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+$/u,ee="data-payload-field",te=[/\.(?: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 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,n){const o=e.trim();if(0===o.length)return"the element is empty";if(!Y.test(o))return"not a plain field access — a call, an operator or an index cannot be traced to one field";const i=oe(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 re(e,t){const n=[],o=[],i=function(e){const t=/* @__PURE__ */new Set;for(const n of te)for(const o of e.matchAll(n))void 0!==o[1]&&t.add(o[1]);return t}(e);for(const s of e.matchAll(Q)){const[,r="",a="",l=""]=s,c=ne(e,s.index);if(a.includes(ee))continue;const u=W.exec(l);if(null===u){null!==X.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:ie(l)});continue}const f=u[1]??"",d=se(f,t.paths,i);void 0===d?n.push({insertAt:s.index+1+r.length,path:oe(f.trim()),line:c,tag:r}):o.push({line:c,reason:d,expression:ie(f)})}return{candidates:n,refusals:o}}function ae(e){return`${ee}="${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=H({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,v as emitTypes,H 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 h(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),h(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),h(s,e.fields,n,o,i),p(s,e,n,i))}}}function g(e,t,n,o){h(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 y(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])g(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 v(e,t,n){for(const o of e){if("group"===o.kind&&"__structural"===o.name){v(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)v(o.fields,e,n);else if("array"===o.kind)v(o.fields,`${e}.*`,n);else if("blocks"===o.kind)for(const t of o.blocks)v(t.fields,`${e}.*.${t.slug}`,n)}}function b(e){const t=[];return v(e.fields,"",t),{slug:e.slug,typeName:e.typeName,fields:t}}function $(e){return{globals:e.globals.map(b),collections:e.collections.map(b)}}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 k(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 S(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 P(e){const t=e.getDefinitionNodes();return(t.length>0?t:e.getSymbol()?.getDeclarations()??[]).flatMap(A)}function E(e){return x().isVariableDeclaration(e)||x().isPropertyAssignment(e)?e.getInitializer():x().isExportAssignment(e)?e.getExpression():x().isShorthandPropertyAssignment(e)?e.getNameNode():void 0}function N(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 j(e,t){return void 0!==e.getProperty(t)}function C(e,t=/* @__PURE__ */new Set){if(void 0===e||t.has(e))return;t.add(e);const n=S(e);if(x().isObjectLiteralExpression(n))return n;if(x().isCallExpression(n))return C(n.getArguments()[0],t);if(x().isIdentifier(n))for(const e of P(n)){const n=C(E(e),t);if(void 0!==n)return n}if(x().isPropertyAccessExpression(n)){const e=C(n.getExpression(),t);if(void 0!==e)return C(N(e,n.getName()),t)}}function z(e,t=/* @__PURE__ */new Set){if(void 0===e||t.has(e))return;t.add(e);const n=S(e);if(x().isArrayLiteralExpression(n))return n;if(x().isIdentifier(n))for(const e of P(n)){const n=z(E(e),t);if(void 0!==n)return n}if(x().isPropertyAccessExpression(n)){const e=C(n.getExpression(),t);if(void 0!==e)return z(N(e,n.getName()),t)}}function F(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(...F(e,t)):k(t,o,"could not resolve the spread to an array literal, so its entries are missing")}return n}function M(e,t){const n=N(e,t);if(void 0===n)return;const o=S(n);return x().isStringLiteral(o)||x().isNoSubstitutionTemplateLiteral(o)?o.getLiteralValue():void 0}function L(e,t){const n=N(e,t);if(void 0===n)return;const o=S(n);return!!x().isTrueLiteral(o)||!x().isFalseLiteral(o)&&void 0}function _(e,t){return z(N(e,t))}function D(e){const t=N(e,"relationTo");if(void 0===t)return"unknown";const n=S(t);if(x().isStringLiteral(n))return n.getLiteralValue();const o=z(n);return void 0===o?"unknown":o.getElements().map(S).filter(e=>x().isStringLiteral(e)).map(e=>e.getLiteralValue())}var O="__structural",I=/* @__PURE__ */new Set(["tabs","row","collapsible"]),T={text:"string",textarea:"string",email:"string",richText:"unknown",number:"number",checkbox:"boolean",date:"string",code:"string",point:"[number, number]"},q=/* @__PURE__ */new Set(["text","number"]);function Z(e,t){const n=[];for(const o of F(e,t)){const e=C(o);if(void 0===e){k(t,o,"could not resolve the field to an object literal");continue}const i=K(e,t);void 0!==i&&("group"===i.kind&&i.name===O?n.push(...i.fields):n.push(i))}return n}function R(e,t){const n=_(e,"fields");return void 0!==n?Z(n,t):(k(t,e,j(e,"fields")?"its `fields` could not be resolved to an array literal":"it has no `fields`"),[])}function V(e,t){const n=_(e,"tabs");if(void 0===n)return k(t,e,"its `tabs` could not be resolved to an array literal"),[];const o=[];for(const e of F(n,t)){const n=C(e);if(void 0===n){k(t,e,"could not resolve the tab to an object literal");continue}const i=M(n,"name"),s=R(n,t);void 0===i?o.push(...s):o.push({kind:"group",name:i,required:!1,localized:!1,fields:s})}return o}function B(e,t){const n=_(e,"blocks");if(void 0===n)return k(t,e,"its `blocks` could not be resolved to an array literal"),[];const o=[];for(const e of F(n,t)){const n=C(e);if(void 0===n){k(t,e,"could not resolve the block to an object literal");continue}const i=M(n,"slug");void 0!==i?o.push({slug:i,typeName:l(i),fields:R(n,t)}):k(t,e,"a block needs a string `slug`")}return o}function G(e,t){const n=_(e,"options");if(void 0===n)return k(t,e,"its `options` could not be resolved to an array literal"),[];const o=[];for(const e of F(n,t)){if(x().isStringLiteral(e)){o.push(e.getLiteralValue());continue}const n=C(e),i=void 0===n?void 0:M(n,"value");void 0===i?k(t,e,"an option needs a string or a `value`"):o.push(i)}return o}function K(e,t){const n=M(e,"type");if(void 0===n)return void k(t,e,"it has no string `type`");if("ui"===n)return;const o=M(e,"name");if(void 0===o&&!I.has(n))return void k(t,e,`a ${n} field needs a string \`name\``);const i={name:o??O,required:L(e,"required")??!1,localized:L(e,"localized")??!1},s=L(e,"hasMany")??!1;switch(n){case"array":return{...i,kind:"array",fields:R(e,t)};case"group":case"row":case"collapsible":return{...i,kind:"group",fields:R(e,t)};case"tabs":return{...i,kind:"group",fields:V(e,t)};case"blocks":return{...i,kind:"blocks",blocks:B(e,t)};case"relationship":return{...i,kind:"relationship",target:D(e),hasMany:s};case"upload":{const t=D(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:G(e,t),hasMany:"select"===n&&s};default:return{...i,kind:"scalar",typeRef:T[n]??"unknown",hasMany:q.has(n)&&s}}}function J(e){if(x().isExportAssignment(e))return e.getExpression()}function U(e,t,n){const o=N(e,t);if(void 0===o)return[];const i=z(o);if(void 0===i)return k(n,o,`could not resolve \`${t}\` to an array literal`),[];const s=[];for(const e of F(i,n)){const t=C(e);if(void 0===t){k(n,e,"could not resolve the config entry to an object literal");continue}const o=M(t,"slug");if(void 0===o){k(n,e,"the config entry has no string `slug`");continue}const i=_(t,"fields");void 0===i&&k(n,t,j(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?[]:Z(i,n)})}return s}function W(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=C(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=C(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:U(i,"globals",o),collections:U(i,"collections",o),diagnostics:o.diagnostics}}var H=/<([a-z][a-z0-9-]*)((?:"[^"]*"|'[^']*'|\{(?:[^{}]|\{[^{}]*\})*\}|[^>"'{])*)>([^<]*)<\/\1\s*>/gu,Q=/<script\b[^>]*>[\s\S]*?<\/script\b[^>]*>|<style\b[^>]*>[\s\S]*?<\/style\b[^>]*>|<!--[\s\S]*?-->/giu,X=/^\s*\{([^{}]*)\}\s*$/u,Y=/\{([^{}]*)\}/u,ee=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+$/u,te="data-payload-field",ne=/\bdata-payload-field\s*=\s*(?:"([^"]*)"|'([^']*)'|\{\s*(["'`])([^"'`]*)\3\s*\})/u,oe=/\{\s*\.\.\.\s*(?:[\w$]+\s*\.\s*)*(?:bind|bindByPath)\s*(?:<[^>]*>)?\s*\(\s*(?:(["'`])([^"'`]*)\1)?/u,ie=/\{\s*\.\.\./u,se=[/\.(?: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 re(e){return e.replace(/[^\n]/gu," ")}function ae(e){const{bodyOffset:t}=function(e){if(!e.startsWith("---"))return{frontmatter:"",bodyOffset:0};const t=e.indexOf("\n---",3);if(-1===t)return{frontmatter:"",bodyOffset:0};const n=t+1+3;return{frontmatter:e.slice(3,t),bodyOffset:n}}(e),n=e.slice(t).replace(Q,re);return`${re(e.slice(0,t))}${n}`}function le(e,t){let n=1;for(let o=0;o<t;o+=1)10===e.charCodeAt(o)&&(n+=1);return n}function ce(e){return e.slice(e.indexOf(".")+1)}function ue(e){return e.slice(0,e.indexOf("."))}function fe(e){const t=e.replace(/\s+/gu," ").trim();return t.length>60?`${t.slice(0,57)}…`:t}function de(e){if(e.includes(te)){const t=ne.exec(e);return{path:t?.[1]??t?.[2]??t?.[4]}}const t=oe.exec(e);return null===t?null:{path:t[2]}}function pe(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=ce(n),i=ue(n);if(t.items.has(i))return`\`${i}\` is a loop item — a binding names a field of the document, and \`${o}\` there is a different value, or none`;if(!t.known.has(o))return`the schema has no field \`${o}\`; the binding would name something that never arrives`;const s=t.anchors.get(i);if(void 0===s)return`this file binds no field of \`${i}\` by hand, so nothing says it holds the previewed document rather than another one — bind one of its fields and the rest can follow`;const r=[...s,o];return t.entities.some(e=>r.every(t=>e.has(t)))?void 0:`no single collection or global has \`${o}\` and what this file binds on \`${i}\` (${[...s].map(e=>`\`${e}\``).join(", ")}) — one variable holds one document`}function he(e,t){return"title"===e?"`<title>` belongs to the document head, which only a route refresh updates, and usually carries more than the field":"a"===e?'an `<a>` binding writes the value into `href` as well as the text — bind the label on an element inside the link, or set data-payload-type="text" by hand':ie.test(t)?"the element spreads attributes the scan cannot read, and one of them may already bind it":void 0}function ge(e,t){const n=/* @__PURE__ */new Map;for(const[,,o="",i=""]of e){const e=de(o)?.path,s=X.exec(i)?.[1]?.trim();if(void 0===e||void 0===s||!ee.test(s))continue;const r=ue(s);if(ce(s)!==e||t.has(r))continue;const a=n.get(r)??/* @__PURE__ */new Set;a.add(e),n.set(r,a)}return n}function me(e,t){const n=[],o=[],i=function(e){const t=/* @__PURE__ */new Set;for(const n of se)for(const o of e.matchAll(n))void 0!==o[1]&&t.add(o[1]);return t}(e),s=[...ae(e).matchAll(H)],r={known:new Set(t.entities.flatMap(e=>[...e])),entities:t.entities,items:i,anchors:ge(s,i)};for(const t of s){const[,i="",s="",a=""]=t,l=le(e,t.index);if(null!==de(s))continue;if(null===Y.exec(a))continue;const c=he(i,s);if(void 0!==c){o.push({line:l,reason:c,expression:fe(a)});continue}const u=X.exec(a);if(null===u){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:fe(a)});continue}const f=u[1]??"",d=pe(f,r);void 0===d?n.push({insertAt:t.index+1+i.length,path:ce(f.trim()),line:l,tag:i}):o.push({line:l,reason:d,expression:fe(f)})}return{candidates:n,refusals:o}}function ye(e){return`${te}="${e.path}"`}function ve(e,t,n=ye){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 be=[".astro",".jsx",".tsx",".svelte"];function $e(e){return[...e.globals,...e.collections].map(e=>new Set(e.fields.map(e=>e.path).filter(e=>!e.includes("*"))))}function we(e){return new Set($e(e).flatMap(e=>[...e]))}async function xe(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=$e(n.inventory),l=[];for(const e of n.files){const t=await i(e),{candidates:c,refusals:u}=me(t,{entities:a}),f=0===c.length?t:ve(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 ke(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 Se(e,o){await n(r(e),{recursive:!0}),await t(e,o,"utf8")}async function Ae(e){const t=e.cwd??process.cwd(),n=e=>i(e)?e:s(t,e),o=W({configPath:n(e.configPath),...void 0!==e.project?{project:e.project}:{},...void 0!==e.tsConfigFilePath?{tsConfigFilePath:e.tsConfigFilePath}:{}}),r=y(o,e),a=$(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 Se(c,r),void 0!==u&&await Se(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{be as ANNOTATABLE_EXTENSIONS,we as annotatablePaths,xe as annotateTemplates,$ as buildPreviewInventory,y as emitTypes,W as extractSchema,ke as formatAnnotateReport,Ae as generateTypes};
|
|
2
2
|
//# sourceMappingURL=codegen.js.map
|
package/dist/codegen.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"codegen.js","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","url","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","ANNOTATABLE_EXTENSIONS","annotatablePaths","inventory","async","annotateTemplates","read","io","readFile","write","writeFile","cwd","process","files","file","changed","relative","annotations","annotationCount","reduce","total","refusalCount","written","formatAnnotateReport","result","annotation","refusal","verb","writeOut","mkdir","dirname","recursive","generateTypes","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 * 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/**\n * A place that looks like an output but was left alone, and why.\n *\n * @beta\n */\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 *\n * @beta\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 } from './inventory';\nexport type { PreviewInventory, PreviewInventoryEntry, PreviewInventoryField } from './inventory';\nexport { extractSchema } from './parser/extract-schema';\nexport { emitTypes } from './emit/emit-types';\nexport type { ExtractedSchema, ExtractedSlug, ExtractedField } from './parser/types';\n"],"mappings":"kLAEO,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,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,IAAZsQ,SAA6BR,GAASQ,EAASnH,QAE7B,IAAlBoH,SACIT,GAASS,EAAe,GAAGG,KAAKC,UAAUtC,EAAW,KAAM,SAG9D,CACLlF,OACA/E,cACAxB,SACAyL,eACKoC,QAAqB,IAAZH,EAAsC,GAAd,CAAEA,cACnCG,QAA2B,IAAlBF,EAAkD,GAApB,CAAEA,iBAElD,Q","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"codegen.js","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","url","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","NOT_TEMPLATE","ONLY_INTERPOLATION","ANY_INTERPOLATION","MEMBER_CHAIN","FIELD_ATTRIBUTE","FIELD_LITERAL","BINDING_SPREAD","ANY_SPREAD","LOOP_VARIABLES","blank","templateOnly","source","bodyOffset","startsWith","frontmatter","end","indexOf","FENCE","splitFrontmatter","body","lineAt","index","line","position","charCodeAt","pathOf","chain","rootOf","describe","expression","flat","trim","bindingOf","attributes","includes","exec","spread","refusalReason","file","trimmed","root","items","known","anchored","anchors","get","together","entities","some","entity","every","each","elementRefusal","tag","anchorsOf","elements","Map","content","paths","set","scanTemplate","candidates","refusals","names","pattern","match","matchAll","loopVariables","refusedElement","reason","only","insertAt","fieldAttribute","candidate","applyAnnotations","render","sort","a","b","ANNOTATABLE_EXTENSIONS","annotatableEntities","inventory","annotatablePaths","async","annotateTemplates","read","io","readFile","write","writeFile","cwd","process","files","changed","relative","annotations","annotationCount","reduce","total","refusalCount","written","formatAnnotateReport","result","annotation","refusal","verb","writeOut","mkdir","dirname","recursive","generateTypes","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 * 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 data-payload-field=\"title\">{page.title}</h1> bound by hand\n * <p>{page.subtitle}</p> → subtitle\n * ```\n *\n * An element whose entire content is one member expression, rooted at a\n * variable the file already binds a field of by hand, whose remaining path a\n * collection or global has together with those hand-bound fields. The hand\n * binding is the only thing in a template that says which variable holds the\n * previewed document: `post` in a card, `settings` in a footer and `page` in a\n * route look alike, and on four sites 16 of the 17 bindings proposed without\n * it were wrong, most of them a field of some other document. Everything\n * else — an interpolation next to text, a call, a path the schema does not\n * know, a link, 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\n * makes 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/**\n * A place that looks like an output but was left alone, and why.\n *\n * @beta\n */\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 /**\n * The paths of each collection and global, one set per entity, exactly as a\n * binding must spell them. Kept apart because one variable holds one\n * document: a path is only bindable on a variable whose hand-bound fields\n * the same entity has.\n */\n readonly entities: readonly 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. An attribute in braces is read as one\n * unit, two levels deep, so the `>` of `bind<Page>(…)` or of an arrow function\n * does not end the tag.\n */\nconst ELEMENT =\n /<([a-z][a-z0-9-]*)((?:\"[^\"]*\"|'[^']*'|\\{(?:[^{}]|\\{[^{}]*\\})*\\}|[^>\"'{])*)>([^<]*)<\\/\\1\\s*>/gu;\n\n/**\n * Code inside a template: a script, a style sheet and a comment. Their braces\n * are JavaScript and CSS, and markup in them is a string, so the element scan\n * never reads them — the same three the doctor strips before it counts.\n */\nconst NOT_TEMPLATE =\n /<script\\b[^>]*>[\\s\\S]*?<\\/script\\b[^>]*>|<style\\b[^>]*>[\\s\\S]*?<\\/style\\b[^>]*>|<!--[\\s\\S]*?-->/giu;\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/** The path a hand-written attribute names: `=\"title\"`, `='title'` or `={'title'}`. */\nconst FIELD_LITERAL =\n /\\bdata-payload-field\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)'|\\{\\s*([\"'`])([^\"'`]*)\\3\\s*\\})/u;\n\n/**\n * A spread of a binding helper: `{...preview.bind('title')}`,\n * `{...bind<Page>(\"title\")}`, `{...bindByPath((d) => d.title)}`. The path is\n * captured when it is a string literal.\n */\nconst BINDING_SPREAD =\n /\\{\\s*\\.\\.\\.\\s*(?:[\\w$]+\\s*\\.\\s*)*(?:bind|bindByPath)\\s*(?:<[^>]*>)?\\s*\\(\\s*(?:([\"'`])([^\"'`]*)\\1)?/u;\n\n/** Any other spread: attributes the scan cannot see, a binding among them or not. */\nconst ANY_SPREAD = /\\{\\s*\\.\\.\\./u;\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\nconst FENCE = '---';\n\n/** Everything before the second `---`, and where the template starts. @internal */\nexport function splitFrontmatter(code: string): {\n readonly frontmatter: string;\n readonly bodyOffset: number;\n} {\n if (!code.startsWith(FENCE)) return { frontmatter: '', bodyOffset: 0 };\n const end = code.indexOf(`\\n${FENCE}`, FENCE.length);\n if (end === -1) return { frontmatter: '', bodyOffset: 0 };\n const bodyOffset = end + 1 + FENCE.length;\n return { frontmatter: code.slice(FENCE.length, end), bodyOffset };\n}\n\n/** Every character but a line break as a space, so offsets and lines stay the file's own. */\nfunction blank(text: string): string {\n return text.replace(/[^\\n]/gu, ' ');\n}\n\n/**\n * The source as the element scan reads it: Astro's frontmatter — TypeScript,\n * where a template in a string is not the document — and the code blocks\n * blanked out. A source that does not open with a fence has none, so this\n * holds for every template language.\n */\nfunction templateOnly(source: string): string {\n const { bodyOffset } = splitFrontmatter(source);\n const body = source.slice(bodyOffset).replace(NOT_TEMPLATE, blank);\n return `${blank(source.slice(0, bodyOffset))}${body}`;\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 rootOf(chain: string): string {\n return chain.slice(0, chain.indexOf('.'));\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/**\n * How an element is bound already, or `null`. `path` is the field when the\n * binding spells it as a literal, which is what lets it name its variable.\n */\nfunction bindingOf(attributes: string): { readonly path: string | undefined } | null {\n if (attributes.includes(FIELD_ATTRIBUTE)) {\n const literal = FIELD_LITERAL.exec(attributes);\n return { path: literal?.[1] ?? literal?.[2] ?? literal?.[4] };\n }\n const spread = BINDING_SPREAD.exec(attributes);\n return spread === null ? null : { path: spread[2] };\n}\n\n/** What a file says about its variables, read from the bindings written by hand. */\ninterface FileContext {\n /** Every path the schema has, whichever entity. */\n readonly known: ReadonlySet<string>;\n readonly entities: readonly ReadonlySet<string>[];\n readonly items: ReadonlySet<string>;\n /** A variable whose field is bound by hand, with the paths bound on it. */\n readonly anchors: ReadonlyMap<string, ReadonlySet<string>>;\n}\n\n/** Why this interpolation cannot become a binding, in the words of the report. */\nfunction refusalReason(expression: string, file: FileContext): 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 = rootOf(trimmed);\n if (file.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 (!file.known.has(path)) {\n return `the schema has no field \\`${path}\\`; the binding would name something that never arrives`;\n }\n const anchored = file.anchors.get(root);\n if (anchored === undefined) {\n return `this file binds no field of \\`${root}\\` by hand, so nothing says it holds the previewed document rather than another one — bind one of its fields and the rest can follow`;\n }\n const together = [...anchored, path];\n if (!file.entities.some((entity) => together.every((each) => entity.has(each)))) {\n const bound = [...anchored].map((each) => `\\`${each}\\``).join(', ');\n return `no single collection or global has \\`${path}\\` and what this file binds on \\`${root}\\` (${bound}) — one variable holds one document`;\n }\n return undefined;\n}\n\n/**\n * Why this element cannot carry a binding whatever it prints: its tag or its\n * attributes decide, before the content is read.\n */\nfunction elementRefusal(tag: string, attributes: string): string | undefined {\n if (tag === 'title') {\n return '`<title>` belongs to the document head, which only a route refresh updates, and usually carries more than the field';\n }\n if (tag === 'a') {\n return 'an `<a>` binding writes the value into `href` as well as the text — bind the label on an element inside the link, or set data-payload-type=\"text\" by hand';\n }\n if (ANY_SPREAD.test(attributes)) {\n return 'the element spreads attributes the scan cannot read, and one of them may already bind it';\n }\n return undefined;\n}\n\n/**\n * The variables a file binds by hand: an element bound to `P` whose content\n * is `{v.P}` says that `v` holds the document. A loop item never does — its\n * binding names the field of one item, which is a different statement.\n */\nfunction anchorsOf(\n elements: readonly RegExpMatchArray[],\n items: ReadonlySet<string>,\n): ReadonlyMap<string, ReadonlySet<string>> {\n const anchors = new Map<string, Set<string>>();\n for (const [, , attributes = '', content = ''] of elements) {\n const path = bindingOf(attributes)?.path;\n const chain = ONLY_INTERPOLATION.exec(content)?.[1]?.trim();\n if (path === undefined || chain === undefined || !MEMBER_CHAIN.test(chain)) continue;\n const root = rootOf(chain);\n if (pathOf(chain) !== path || items.has(root)) continue;\n const paths = anchors.get(root) ?? new Set<string>();\n paths.add(path);\n anchors.set(root, paths);\n }\n return anchors;\n}\n\nexport function scanTemplate(source: string, options: ScanOptions): ScanResult {\n const candidates: AnnotationCandidate[] = [];\n const refusals: AnnotationRefusal[] = [];\n const items = loopVariables(source);\n const elements = [...templateOnly(source).matchAll(ELEMENT)];\n const file: FileContext = {\n known: new Set(options.entities.flatMap((entity) => [...entity])),\n entities: options.entities,\n items,\n anchors: anchorsOf(elements, items),\n };\n for (const match of elements) {\n const [, tag = '', attributes = '', content = ''] = match;\n const line = lineAt(source, match.index);\n // Bound already, by an attribute or a helper's spread: yours wins, always.\n if (bindingOf(attributes) !== null) continue;\n if (ANY_INTERPOLATION.exec(content) === null) continue;\n const refusedElement = elementRefusal(tag, attributes);\n if (refusedElement !== undefined) {\n refusals.push({ line, reason: refusedElement, expression: describe(content) });\n continue;\n }\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 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 continue;\n }\n const expression = only[1] ?? '';\n const reason = refusalReason(expression, file);\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 *\n * @beta\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 * The paths each collection and global can address, one set per entity.\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 * The sets stay apart because one template variable holds one document, so a\n * path is only bindable together with the fields bound by hand on the same\n * variable.\n * @internal\n */\nexport function annotatableEntities(inventory: AnnotatableSchema): readonly ReadonlySet<string>[] {\n return [...inventory.globals, ...inventory.collections].map(\n (entry) =>\n new Set(entry.fields.map((field) => field.path).filter((path) => !path.includes('*'))),\n );\n}\n\n/** Every path of every collection and global, in one set: the same paths, not kept apart. @internal */\nexport function annotatablePaths(inventory: AnnotatableSchema): ReadonlySet<string> {\n return new Set(annotatableEntities(inventory).flatMap((paths) => [...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 entities = annotatableEntities(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, { entities });\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 } from './inventory';\nexport type { PreviewInventory, PreviewInventoryEntry, PreviewInventoryField } from './inventory';\nexport { extractSchema } from './parser/extract-schema';\nexport { emitTypes } from './emit/emit-types';\nexport type { ExtractedSchema, ExtractedSlug, ExtractedField } from './parser/types';\n"],"mappings":"kLAEO,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,EAC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