payload-live-preview 1.8.0 → 2.0.0-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +301 -93
- package/dist/adapters/astro/PreviewBoundary.astro +66 -0
- package/dist/adapters/astro/RichText.astro +6 -0
- package/dist/adapters/astro/index.d.ts +165 -134
- package/dist/adapters/astro/index.js +1 -1
- package/dist/adapters/astro/index.js.map +1 -1
- package/dist/adapters/astro/middleware-entry.d.ts +4 -9
- package/dist/adapters/astro/middleware-entry.js +1 -1
- package/dist/adapters/astro/middleware-entry.js.map +1 -1
- package/dist/adapters/nextjs/index.d.ts +13 -80
- package/dist/adapters/nextjs/index.js +1 -1
- package/dist/adapters/nextjs/index.js.map +1 -1
- package/dist/adapters/nuxt/index.d.ts +46 -106
- package/dist/adapters/nuxt/index.js +1 -1
- package/dist/adapters/nuxt/index.js.map +1 -1
- package/dist/adapters/sveltekit/index.d.ts +10 -75
- package/dist/adapters/sveltekit/index.js +1 -1
- package/dist/adapters/sveltekit/index.js.map +1 -1
- package/dist/client.cjs +2 -0
- package/dist/client.cjs.map +1 -0
- package/dist/client.d.cts +747 -0
- package/dist/client.d.ts +747 -0
- package/dist/client.js +2 -0
- package/dist/client.js.map +1 -0
- package/dist/codegen-astro.d.ts +5 -27
- package/dist/codegen-astro.js +1 -1
- package/dist/codegen-astro.js.map +1 -1
- package/dist/codegen-cli.d.ts +3 -16
- 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 +37 -124
- package/dist/codegen.d.ts +37 -124
- 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 +647 -1100
- package/dist/core.d.ts +647 -1100
- package/dist/core.js +1 -1
- package/dist/core.js.map +1 -1
- package/dist/doctor-cli.d.ts +3 -28
- package/dist/doctor-cli.js +1 -1
- package/dist/doctor-cli.js.map +1 -1
- package/dist/doctor.d.ts +16 -32
- package/dist/doctor.js +1 -1
- package/dist/doctor.js.map +1 -1
- package/dist/fragment.cjs +2 -0
- package/dist/fragment.cjs.map +1 -0
- package/dist/fragment.d.cts +333 -0
- package/dist/fragment.d.ts +333 -0
- package/dist/fragment.js +2 -0
- package/dist/fragment.js.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +885 -1531
- package/dist/index.d.ts +885 -1531
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/lexical.cjs +2 -0
- package/dist/lexical.cjs.map +1 -0
- package/dist/lexical.d.cts +90 -0
- package/dist/lexical.d.ts +90 -0
- package/dist/lexical.js +2 -0
- package/dist/lexical.js.map +1 -0
- package/dist/middleware-CEPsY1P7.d.ts +40 -0
- package/dist/migrate.d.ts +73 -0
- package/dist/migrate.js +2 -0
- package/dist/migrate.js.map +1 -0
- package/dist/options-CEzzfHJu.d.ts +197 -0
- package/dist/payload.cjs +1 -1
- package/dist/payload.cjs.map +1 -1
- package/dist/payload.d.cts +11 -80
- package/dist/payload.d.ts +11 -80
- package/dist/payload.js +1 -1
- package/dist/payload.js.map +1 -1
- package/dist/plugins.cjs +2 -0
- package/dist/plugins.cjs.map +1 -0
- package/dist/plugins.d.cts +509 -0
- package/dist/plugins.d.ts +509 -0
- package/dist/plugins.js +2 -0
- package/dist/plugins.js.map +1 -0
- package/dist/{probe-tMHdim5y.d.ts → probe-CYtvj_Lm.d.ts} +43 -77
- package/dist/server.cjs +2 -0
- package/dist/server.cjs.map +1 -0
- package/dist/server.d.cts +435 -0
- package/dist/server.d.ts +435 -0
- package/dist/server.js +2 -0
- package/dist/server.js.map +1 -0
- package/dist/structural.cjs +3 -0
- package/dist/structural.cjs.map +1 -0
- package/dist/structural.d.cts +243 -0
- package/dist/structural.d.ts +243 -0
- package/dist/structural.js +3 -0
- package/dist/structural.js.map +1 -0
- package/package.json +86 -7
- package/dist/middleware-DD4Hwomt.d.ts +0 -189
package/dist/codegen-astro.d.ts
CHANGED
|
@@ -1,36 +1,11 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Astro integration — regenerates the types file on dev-server start
|
|
3
|
-
* and (optionally) watches `payload.config.ts` for changes.
|
|
4
|
-
*
|
|
5
|
-
* ```ts
|
|
6
|
-
* // astro.config.mjs
|
|
7
|
-
* import { livePreviewCodegen } from 'payload-live-preview/codegen';
|
|
8
|
-
*
|
|
9
|
-
* export default defineConfig({
|
|
10
|
-
* integrations: [
|
|
11
|
-
* livePreviewCodegen({
|
|
12
|
-
* configPath: '../backend/src/payload.config.ts',
|
|
13
|
-
* outPath: 'src/payload-types.ts',
|
|
14
|
-
* watch: true,
|
|
15
|
-
* }),
|
|
16
|
-
* ],
|
|
17
|
-
* });
|
|
18
|
-
* ```
|
|
19
|
-
*
|
|
20
|
-
* The plugin uses Node's `fs.watch` (no chokidar dependency) — Astro
|
|
21
|
-
* already bundles enough watch-mode tooling that we don't need a
|
|
22
|
-
* full-fat library here.
|
|
23
|
-
*
|
|
24
|
-
* @module @codegen/astro-plugin
|
|
25
|
-
*/
|
|
26
1
|
interface AstroCodegenOptions {
|
|
27
2
|
/** Path to `payload.config.ts` (absolute or relative to Astro's root). */
|
|
28
3
|
readonly configPath: string;
|
|
29
4
|
/** Output path for generated types (absolute or relative to Astro's root). */
|
|
30
5
|
readonly outPath: string;
|
|
31
|
-
/** Re-run
|
|
6
|
+
/** Re-run when the config or anything beside it changes during `astro dev`. Default `true`. */
|
|
32
7
|
readonly watch?: boolean;
|
|
33
|
-
/**
|
|
8
|
+
/** Only log errors. Default `false`. */
|
|
34
9
|
readonly quiet?: boolean;
|
|
35
10
|
}
|
|
36
11
|
interface AstroLogger {
|
|
@@ -44,6 +19,9 @@ interface AstroIntegration {
|
|
|
44
19
|
readonly 'astro:config:setup'?: (params: {
|
|
45
20
|
readonly command: string;
|
|
46
21
|
readonly logger?: AstroLogger;
|
|
22
|
+
readonly config?: {
|
|
23
|
+
readonly root?: URL | string;
|
|
24
|
+
};
|
|
47
25
|
}) => Promise<void> | void;
|
|
48
26
|
readonly 'astro:server:start'?: () => void;
|
|
49
27
|
readonly 'astro:build:start'?: () => Promise<void> | void;
|
package/dist/codegen-astro.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{watch as e}from"fs";import{mkdir as t,writeFile as i}from"fs/promises";import{isAbsolute as r,resolve as n,dirname as o}from"path";import{Node as l,SyntaxKind as s,Project as a}from"ts-morph";var u=Object.defineProperty,f=(e,t)=>u(e,"name",{value:t,configurable:!0}),c={text:"string",textarea:"string",email:"string",richText:"unknown",number:"number",checkbox:"boolean",date:"string",code:"string",point:"unknown",ui:"unknown",radio:"string"};function p(e){let t=x(e,"type");if(void 0===t)return;let i=new Set(["tabs","row","collapsible"]),r=x(e,"name");if(void 0===r&&!i.has(t))return;let n={name:r??"__structural",required:k(e,"required")??!1,localized:k(e,"localized")??!1};switch(t){case"array":return{...n,kind:"array",fields:g(e)};case"blocks":return{...n,kind:"blocks",blocks:h(e)};case"group":return{...n,kind:"group",fields:g(e)};case"tabs":case"row":case"collapsible":{let t=d(e);return{...n,kind:"group",fields:t}}case"relationship":return{...n,kind:"relationship",target:y(e),hasMany:k(e,"hasMany")??!1};case"upload":return{...n,kind:"upload",target:m(e)??"media"};case"json":return{...n,kind:"json"};case"select":return{...n,kind:"select",options:b(e),hasMany:k(e,"hasMany")??!1};default:{let e=c[t]??"unknown";return{...n,kind:"scalar",typeRef:e}}}}function g(e){let t=v(e,"fields");if(!t)return[];let i=[];for(let e of t.getElements()){if(!l.isObjectLiteralExpression(e))continue;let t=p(e);t&&("group"===t.kind&&"__structural"===t.name?i.push(...t.fields):i.push(t))}return i}function d(e){let t=v(e,"tabs");if(t){let e=[];for(let i of t.getElements()){if(!l.isObjectLiteralExpression(i))continue;let t=x(i,"name"),r=g(i);void 0!==t?e.push({kind:"group",name:t,required:!1,localized:!1,fields:r}):e.push(...r)}return e}return g(e)}function h(e){let t=v(e,"blocks");if(!t)return[];let i=[];for(let e of t.getElements()){if(!l.isObjectLiteralExpression(e))continue;let t=x(e,"slug");void 0!==t&&i.push({slug:t,typeName:E(t),fields:g(e)})}return i}function y(e){let t=e.getProperty("relationTo");if(!t||!l.isPropertyAssignment(t))return"unknown";let i=t.getInitializer();return i&&l.isStringLiteral(i)?i.getLiteralValue():i&&l.isArrayLiteralExpression(i)?i.getElements().filter(l.isStringLiteral).map(e=>e.getLiteralValue()):"unknown"}function m(e){let t=y(e);return"string"==typeof t?t:t[0]}function b(e){let t=v(e,"options");if(!t)return[];let i=[];for(let e of t.getElements())if(l.isStringLiteral(e))i.push(e.getLiteralValue());else if(l.isObjectLiteralExpression(e)){let t=x(e,"value");void 0!==t&&i.push(t)}return i}function x(e,t){let i=e.getProperty(t);if(!i||!P(i))return;let r=i.getInitializer();return r&&l.isStringLiteral(r)||r&&l.isNoSubstitutionTemplateLiteral(r)?r.getLiteralValue():void 0}function k(e,t){let i=e.getProperty(t);if(!i||!P(i))return;let r=i.getInitializer();if(r){if(r.getKind()===s.TrueKeyword)return!0;if(r.getKind()===s.FalseKeyword)return!1}}function v(e,t){let i=e.getProperty(t);if(!i||!P(i))return;let r=i.getInitializer();return r&&l.isArrayLiteralExpression(r)?r:void 0}function P(e){return l.isPropertyAssignment(e)}function E(e){return e.split(/[-_\s]+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function w(e){let t=e.project??new a(void 0!==e.tsConfigFilePath?{tsConfigFilePath:e.tsConfigFilePath}:{skipAddingFilesFromTsConfig:!0}),i=t.addSourceFileAtPathIfExists(e.configPath);if(!i)return{globals:[],collections:[],diagnostics:[`Could not open ${e.configPath}`]};t.resolveSourceFileDependencies();let r=[],n=$(i,r);return n?{globals:A(n,"globals",r),collections:A(n,"collections",r),diagnostics:r}:{globals:[],collections:[],diagnostics:[...r,"Could not locate a buildConfig({...}) call or `export default {...}` in the config file."]}}function $(e,t){let i=e.getExportSymbols().find(e=>"default"===e.getName());if(!i)return void t.push("payload.config.ts has no default export.");let r=i.getDeclarations();for(let e of r){let t=F(e);if(t)return t}for(let t of e.getDescendantsOfKind(s.CallExpression)){let e=t.getExpression();if(l.isIdentifier(e)&&"buildConfig"===e.getText()){let e=t.getArguments()[0];if(e&&l.isObjectLiteralExpression(e))return e}}}function F(e){if(l.isExportAssignment(e))return L(e.getExpression());if(l.isVariableDeclaration(e)){let t=e.getInitializer();if(t)return L(t)}}function L(e){if(e){if(l.isObjectLiteralExpression(e))return e;if(l.isCallExpression(e)){let t=e.getArguments()[0];if(t&&l.isObjectLiteralExpression(t))return t}if(l.isAsExpression(e)||l.isSatisfiesExpression(e))return L(e.getExpression());if(l.isIdentifier(e))return S(e)}}function S(e){for(let t of e.getDefinitionNodes()){let e=F(t);if(e)return e}}function A(e,t,i){let r=e.getProperty(t);if(!r)return[];if(!l.isPropertyAssignment(r))return[];let n=r.getInitializer();if(!n)return[];let o=T(n);return o?j(o,i):[]}function j(e,t){let i=[];for(let r of e.getElements()){if(l.isSpreadElement(r)){let e=T(r.getExpression());if(!e){t.push(`Could not resolve spread "${r.getText().slice(0,80)}" to an array literal.`);continue}i.push(...j(e,t));continue}let e=N(r);if(!e){t.push(`Could not resolve config entry "${r.getText().slice(0,80)}" to an object literal.`);continue}let n=z(e,"slug");void 0!==n?i.push({slug:n,typeName:E(n),fields:C(e)}):t.push("Skipping a config entry — no string `slug` field found.")}return i}function C(e){let t=e.getProperty("fields");if(!t||!l.isPropertyAssignment(t))return[];let i=t.getInitializer();if(!i||!l.isArrayLiteralExpression(i))return[];let r=[];for(let e of i.getElements()){if(l.isSpreadElement(e)){let t=T(e.getExpression());if(!t)continue;for(let e of t.getElements()){let t=N(e);if(!t)continue;let i=p(t);i&&("group"===i.kind&&"__structural"===i.name?r.push(...i.fields):r.push(i))}continue}let t=N(e);if(!t)continue;let i=p(t);i&&("group"===i.kind&&"__structural"===i.name?r.push(...i.fields):r.push(i))}return r}function N(e){if(l.isObjectLiteralExpression(e))return e;if(l.isIdentifier(e))return S(e);if(l.isAsExpression(e)||l.isSatisfiesExpression(e))return N(e.getExpression());if(l.isCallExpression(e)){let t=e.getArguments()[0];if(t)return N(t)}}function T(e){if(l.isArrayLiteralExpression(e))return e;if(l.isAsExpression(e)||l.isSatisfiesExpression(e))return T(e.getExpression());if(l.isIdentifier(e))for(let t of e.getDefinitionNodes())if(l.isVariableDeclaration(t)){let e=t.getInitializer();if(e){let t=T(e);if(t)return t}}}function z(e,t){let i=e.getProperty(t);if(!i||!l.isPropertyAssignment(i))return;let r=i.getInitializer();return r&&l.isStringLiteral(r)?r.getLiteralValue():void 0}function I(e,t={}){let i=[];i.push(t.header??"// Auto-generated by payload-live-preview/codegen.\n// Do not edit by hand — run `pll-codegen` to regenerate.\n/* eslint-disable */"),i.push(""),i.push('import type { PayloadMedia, PayloadRelationship } from "payload-live-preview";'),i.push("");let r=new Set;for(let n of[...e.globals,...e.collections])O(n,i,r,t),i.push("");if(e.globals.length>0){i.push("export type PayloadGlobals = {");for(let t of e.globals)i.push(` '${t.slug}': ${t.typeName};`);i.push("};"),i.push("")}if(e.collections.length>0){i.push("export type PayloadCollections = {");for(let t of e.collections)i.push(` '${t.slug}': ${t.typeName};`);i.push("};"),i.push("")}let n=[];return e.globals.length>0&&n.push("keyof PayloadGlobals"),e.collections.length>0&&n.push("keyof PayloadCollections"),n.length>0&&(i.push(`export type PayloadSlug = ${n.join(" | ")};`),i.push("")),i.join("\n").replace(/\n{3,}/g,"\n\n")}function O(e,t,i,r){_(e.typeName,e.fields,t,i,r),t.push(`export interface ${e.typeName} {`);for(let i of e.fields)D(i,e.typeName,t,r);t.push("}")}function _(e,t,i,r,n){for(let o of t){let t=V(e,o.name);if("array"===o.kind||"group"===o.kind){if(r.has(t))continue;r.add(t),_(t,o.fields,i,r,n),i.push(`export interface ${t} {`);for(let e of o.fields)D(e,t,i,n);i.push("}"),i.push("")}else if("blocks"===o.kind)for(let e of o.blocks){let o=V(t,e.typeName);r.has(o)||(r.add(o),_(o,e.fields,i,r,n),M(o,e,i,n))}}}function M(e,t,i,r){i.push(`export interface ${e} {`),i.push(` blockType: '${t.slug}';`);for(let n of t.fields)D(n,e,i,r);i.push("}"),i.push("")}function D(e,t,i,r){r.markLocalizedAsDeprecated&&e.localized&&i.push(" /** @localized */");let n=e.required?"":"?";i.push(` ${e.name}${n}: ${q(e,t)};`)}function q(e,t){switch(e.kind){case"scalar":return e.typeRef;case"array":return`${V(t,e.name)}[]`;case"blocks":return 0===e.blocks.length?"unknown[]":`(${e.blocks.map(i=>V(V(t,e.name),i.typeName)).join(" | ")})[]`;case"group":return V(t,e.name);case"relationship":{let t=`PayloadRelationship<${Array.isArray(e.target)?e.target.map(e=>`'${e}'`).join(" | "):`'${e.target}'`}>`;return e.hasMany?`${t}[]`:t}case"upload":return"PayloadMedia";case"json":return"unknown";case"select":{if(0===e.options.length)return e.hasMany?"string[]":"string";let t=e.options.map(e=>`'${e}'`).join(" | ");return e.hasMany?`(${t})[]`:t}}}function V(e,t){return`${e}${E(t)}`}function R(e,t,i){for(let r of e){if("group"===r.kind&&"__structural"===r.name){R(r.fields,t,i);continue}let e=""===t?r.name:`${t}.${r.name}`;if(i.push({path:e,kind:r.kind,localized:r.localized,required:r.required}),"group"===r.kind)R(r.fields,e,i);else if("array"===r.kind)R(r.fields,`${e}.*`,i);else if("blocks"===r.kind)for(let t of r.blocks)R(t.fields,`${e}.*.${t.slug}`,i)}}function K(e){let t=[];return R(e.fields,"",t),{slug:e.slug,typeName:e.typeName,fields:t}}function B(e){return{globals:e.globals.map(K),collections:e.collections.map(K)}}async function G(e){let l=e.cwd??process.cwd(),s=w({configPath:r(e.configPath)?e.configPath:n(l,e.configPath),...void 0!==e.project?{project:e.project}:{},...void 0!==e.tsConfigFilePath?{tsConfigFilePath:e.tsConfigFilePath}:{}}),a=I(s,e),u=B(s),f={code:a,diagnostics:s.diagnostics,schema:s,inventory:u,...void 0!==e.outFile?{outFile:r(e.outFile)?e.outFile:n(l,e.outFile)}:{},...void 0!==e.inventoryFile?{inventoryFile:r(e.inventoryFile)?e.inventoryFile:n(l,e.inventoryFile)}:{}};return f.outFile&&(await t(o(f.outFile),{recursive:!0}),await i(f.outFile,a,"utf8")),f.inventoryFile&&(await t(o(f.inventoryFile),{recursive:!0}),await i(f.inventoryFile,`${JSON.stringify(u,null,2)}\n`,"utf8")),f}function J(t){let i,r=t.watch??!0,n=!1,o=!1;async function l(e){if(n)o=!0;else{n=!0;try{let i=await G({configPath:t.configPath,outFile:t.outPath});if(!t.quiet){e?.info(`pll-codegen: ${i.schema.globals.length} globals, ${i.schema.collections.length} collections → ${t.outPath}`);for(let t of i.diagnostics)e?.warn(`pll-codegen: ${t}`)}}catch(t){let i=t instanceof Error?t.message:String(t);e?.error(`pll-codegen failed: ${i}`)}finally{n=!1,o&&(o=!1,l(e))}}}return f(l,"regenerate"),{name:"payload-live-preview:codegen",hooks:{"astro:config:setup":f(async({command:n,logger:o})=>{if(await l(o),r&&"dev"===n)try{i=e(t.configPath,()=>{l(o)})}catch(e){let t=e instanceof Error?e.message:String(e);o?.warn(`pll-codegen watcher unavailable: ${t}`)}},"astro:config:setup"),"astro:server:start":f(()=>{},"astro:server:start"),"astro:build:start":f(()=>{i?.close(),i=void 0},"astro:build:start")}}}f(p,"extractField"),f(g,"extractNestedFields"),f(d,"extractNestedFieldsFromStructural"),f(h,"extractBlocks"),f(y,"readRelationTarget"),f(m,"readRelationTargetSingle"),f(b,"readSelectOptions"),f(x,"readStringProperty"),f(k,"readBooleanProperty"),f(v,"readArrayProperty"),f(P,"isPropertyAssignment"),f(E,"toPascalCase"),f(w,"extractSchema"),f($,"findConfigLiteral"),f(F,"unwrapToObjectLiteral"),f(L,"unwrapExpression"),f(S,"resolveIdentifierToObjectLiteral"),f(A,"extractSlugList"),f(j,"extractEntries"),f(C,"extractFieldList"),f(N,"resolveToObjectLiteral"),f(T,"resolveToArrayLiteral"),f(z,"readStringProperty"),f(I,"emitTypes"),f(O,"emitSlug"),f(_,"emitAuxiliaries"),f(M,"emitBlockInterface"),f(D,"emitFieldMember"),f(q,"renderFieldType"),f(V,"nestedTypeName"),f(R,"collect"),f(K,"entry"),f(B,"buildPreviewInventory"),f(G,"generateTypes"),f(J,"livePreviewCodegen");export{J as livePreviewCodegen};
|
|
1
|
+
import{watch as e}from"fs";import{dirname as t,resolve as o,sep as n,extname as i,isAbsolute as s}from"path";import{fileURLToPath as r}from"url";import{mkdir as a,writeFile as l}from"fs/promises";import{Project as c,SyntaxKind as u,Node as d}from"ts-morph";function f(e){return e.split(/[-_\s]+/u).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}var p=/^[A-Za-z_$][\w$]*$/u;function g(e,t){return`${e}${f(t)}`}function h(e,t,o,n){!0===n.markLocalizedAsDeprecated&&e.localized&&o.push(" /** @localized */");const i=e.required?"":"?";var s;o.push(` ${s=e.name,p.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`${g(t,e.name)}[]`;case"blocks":return 0===e.blocks.length?"unknown[]":`(${e.blocks.map(o=>g(g(t,e.name),o.typeName)).join(" | ")})[]`;case"group":return g(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 m(e,t,o,n){o.push(`export interface ${e} {`),o.push(` blockType: '${t.slug}';`);for(const i of t.fields)h(i,e,o,n);o.push("}","")}function v(e,t,o,n,i){for(const s of t){const t=g(e,s.name);if("array"===s.kind||"group"===s.kind){if(n.has(t))continue;n.add(t),v(t,s.fields,o,n,i),o.push(`export interface ${t} {`);for(const e of s.fields)h(e,t,o,i);o.push("}","")}else if("blocks"===s.kind)for(const e of s.blocks){const s=g(t,e.typeName);n.has(s)||(n.add(s),v(s,e.fields,o,n,i),m(s,e,o,i))}}}function y(e,t,o,n){v(e.typeName,e.fields,t,o,n),t.push(`export interface ${e.typeName} {`);for(const o of e.fields)h(o,e.typeName,t,n);t.push("}")}function b(e,t,o){if(0!==t.length){o.push(`export type ${e} = {`);for(const e of t)o.push(` '${e.slug}': ${e.typeName};`);o.push("};","")}}function $(e,t,o){for(const n of e){if("group"===n.kind&&"__structural"===n.name){$(n.fields,t,o);continue}const e=""===t?n.name:`${t}.${n.name}`;if(o.push({path:e,kind:n.kind,localized:n.localized,required:n.required}),"group"===n.kind)$(n.fields,e,o);else if("array"===n.kind)$(n.fields,`${e}.*`,o);else if("blocks"===n.kind)for(const t of n.blocks)$(t.fields,`${e}.*.${t.slug}`,o)}}function k(e){const t=[];return $(e.fields,"",t),{slug:e.slug,typeName:e.typeName,fields:t}}function w(e,t,o){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)}: ${o}.`)}function x(e){let t=e;for(;d.isParenthesizedExpression(t)||d.isAsExpression(t)||d.isSatisfiesExpression(t)||d.isNonNullExpression(t)||d.isTypeAssertion(t);)t=t.getExpression();return t}function P(e){if(!(d.isImportSpecifier(e)||d.isImportClause(e)||d.isNamespaceImport(e)||d.isExportSpecifier(e)))return[e];const t=e.getSymbol()?.getAliasedSymbol();return t?.getDeclarations()??[e]}function S(e){const t=e.getDefinitionNodes();return(t.length>0?t:e.getSymbol()?.getDeclarations()??[]).flatMap(P)}function E(e){return d.isVariableDeclaration(e)||d.isPropertyAssignment(e)?e.getInitializer():d.isExportAssignment(e)?e.getExpression():d.isShorthandPropertyAssignment(e)?e.getNameNode():void 0}function N(e,t){const o=e.getProperty(t);if(void 0!==o)return d.isPropertyAssignment(o)?o.getInitializer():d.isShorthandPropertyAssignment(o)?o.getNameNode():void 0}function j(e,t){return void 0!==e.getProperty(t)}function A(e,t=/* @__PURE__ */new Set){if(void 0===e||t.has(e))return;t.add(e);const o=x(e);if(d.isObjectLiteralExpression(o))return o;if(d.isCallExpression(o))return A(o.getArguments()[0],t);if(d.isIdentifier(o))for(const e of S(o)){const o=A(E(e),t);if(void 0!==o)return o}if(d.isPropertyAccessExpression(o)){const e=A(o.getExpression(),t);if(void 0!==e)return A(N(e,o.getName()),t)}}function F(e,t=/* @__PURE__ */new Set){if(void 0===e||t.has(e))return;t.add(e);const o=x(e);if(d.isArrayLiteralExpression(o))return o;if(d.isIdentifier(o))for(const e of S(o)){const o=F(E(e),t);if(void 0!==o)return o}if(d.isPropertyAccessExpression(o)){const e=A(o.getExpression(),t);if(void 0!==e)return F(N(e,o.getName()),t)}}function C(e,t){const o=[];for(const n of e.getElements()){if(!d.isSpreadElement(n)){o.push(n);continue}const e=F(n.getExpression());void 0!==e?o.push(...C(e,t)):w(t,n,"could not resolve the spread to an array literal, so its entries are missing")}return o}function L(e,t){const o=N(e,t);if(void 0===o)return;const n=x(o);return d.isStringLiteral(n)||d.isNoSubstitutionTemplateLiteral(n)?n.getLiteralValue():void 0}function M(e,t){const o=N(e,t);if(void 0===o)return;const n=x(o);return!!d.isTrueLiteral(n)||!d.isFalseLiteral(n)&&void 0}function z(e,t){return F(N(e,t))}function T(e){const t=N(e,"relationTo");if(void 0===t)return"unknown";const o=x(t);if(d.isStringLiteral(o))return o.getLiteralValue();const n=F(o);return void 0===n?"unknown":n.getElements().map(x).filter(e=>d.isStringLiteral(e)).map(e=>e.getLiteralValue())}var D="__structural",I=/* @__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]"},_=/* @__PURE__ */new Set(["text","number"]);function R(e,t){const o=[];for(const n of C(e,t)){const e=A(n);if(void 0===e){w(t,n,"could not resolve the field to an object literal");continue}const i=U(e,t);void 0!==i&&("group"===i.kind&&i.name===D?o.push(...i.fields):o.push(i))}return o}function V(e,t){const o=z(e,"fields");return void 0!==o?R(o,t):(w(t,e,j(e,"fields")?"its `fields` could not be resolved to an array literal":"it has no `fields`"),[])}function O(e,t){const o=z(e,"tabs");if(void 0===o)return w(t,e,"its `tabs` could not be resolved to an array literal"),[];const n=[];for(const e of C(o,t)){const o=A(e);if(void 0===o){w(t,e,"could not resolve the tab to an object literal");continue}const i=L(o,"name"),s=V(o,t);void 0===i?n.push(...s):n.push({kind:"group",name:i,required:!1,localized:!1,fields:s})}return n}function B(e,t){const o=z(e,"blocks");if(void 0===o)return w(t,e,"its `blocks` could not be resolved to an array literal"),[];const n=[];for(const e of C(o,t)){const o=A(e);if(void 0===o){w(t,e,"could not resolve the block to an object literal");continue}const i=L(o,"slug");void 0!==i?n.push({slug:i,typeName:f(i),fields:V(o,t)}):w(t,e,"a block needs a string `slug`")}return n}function G(e,t){const o=z(e,"options");if(void 0===o)return w(t,e,"its `options` could not be resolved to an array literal"),[];const n=[];for(const e of C(o,t)){if(d.isStringLiteral(e)){n.push(e.getLiteralValue());continue}const o=A(e),i=void 0===o?void 0:L(o,"value");void 0===i?w(t,e,"an option needs a string or a `value`"):n.push(i)}return n}function U(e,t){const o=L(e,"type");if(void 0===o)return void w(t,e,"it has no string `type`");if("ui"===o)return;const n=L(e,"name");if(void 0===n&&!I.has(o))return void w(t,e,`a ${o} field needs a string \`name\``);const i={name:n??D,required:M(e,"required")??!1,localized:M(e,"localized")??!1},s=M(e,"hasMany")??!1;switch(o){case"array":return{...i,kind:"array",fields:V(e,t)};case"group":case"row":case"collapsible":return{...i,kind:"group",fields:V(e,t)};case"tabs":return{...i,kind:"group",fields:O(e,t)};case"blocks":return{...i,kind:"blocks",blocks:B(e,t)};case"relationship":return{...i,kind:"relationship",target:T(e),hasMany:s};case"upload":{const t=T(e);return{...i,kind:"upload",target:("string"==typeof t?t:t[0])??"media",hasMany:s}}case"json":return{...i,kind:"json"};case"select":case"radio":return{...i,kind:"select",options:G(e,t),hasMany:"select"===o&&s};default:return{...i,kind:"scalar",typeRef:q[o]??"unknown",hasMany:_.has(o)&&s}}}function J(e){return d.isExportAssignment(e)?e.getExpression():d.isVariableDeclaration(e)?e.getInitializer():void 0}function K(e,t,o){const n=N(e,t);if(void 0===n)return[];const i=F(n);if(void 0===i)return w(o,n,`could not resolve \`${t}\` to an array literal`),[];const s=[];for(const e of C(i,o)){const t=A(e);if(void 0===t){w(o,e,"could not resolve the config entry to an object literal");continue}const n=L(t,"slug");if(void 0===n){w(o,e,"the config entry has no string `slug`");continue}const i=z(t,"fields");void 0===i&&w(o,t,j(t,"fields")?`the \`fields\` of "${n}" could not be resolved to an array literal`:`"${n}" has no \`fields\``),s.push({slug:n,typeName:f(n),fields:void 0===i?[]:R(i,o)})}return s}async function W(e,o){await a(t(e),{recursive:!0}),await l(e,o,"utf8")}async function Z(e){const t=e.cwd??process.cwd(),n=e=>s(e)?e:o(t,e),i=function(e){const t=e.project??new c(void 0!==e.tsConfigFilePath?{tsConfigFilePath:e.tsConfigFilePath}:{skipAddingFilesFromTsConfig:!0}),o=t.addSourceFileAtPathIfExists(e.configPath);if(void 0===o)return{globals:[],collections:[],diagnostics:[`Could not open ${e.configPath}`]};t.resolveSourceFileDependencies();const n={diagnostics:[]},i=function(e,t){const o=e.getDefaultExportSymbol();if(void 0!==o){for(const e of o.getDeclarations()){const t=A(J(e));if(void 0!==t)return t}for(const t of e.getDescendantsOfKind(u.CallExpression)){const e=t.getExpression();if(!d.isIdentifier(e)||"buildConfig"!==e.getText())continue;const o=A(t.getArguments()[0]);if(void 0!==o)return o}}else t.diagnostics.push("payload.config.ts has no default export.")}(o,n);return void 0===i?{globals:[],collections:[],diagnostics:[...n.diagnostics,"Could not locate a buildConfig({...}) call or `export default {...}` in the config file."]}:{globals:K(i,"globals",n),collections:K(i,"collections",n),diagnostics:n.diagnostics}}({configPath:n(e.configPath),...void 0!==e.project?{project:e.project}:{},...void 0!==e.tsConfigFilePath?{tsConfigFilePath:e.tsConfigFilePath}:{}}),r=function(e,t={}){const o=[t.header??"// Auto-generated by payload-live-preview/codegen.\n// Do not edit by hand — run `pll-codegen` to regenerate.\n/* eslint-disable */",""];o.push('import type { PayloadMedia, PayloadRelationship } from "payload-live-preview";',"");const n=/* @__PURE__ */new Set;for(const i of[...e.globals,...e.collections])y(i,o,n,t),o.push("");b("PayloadGlobals",e.globals,o),b("PayloadCollections",e.collections,o);const i=[];return e.globals.length>0&&i.push("keyof PayloadGlobals"),e.collections.length>0&&i.push("keyof PayloadCollections"),i.length>0&&o.push(`export type PayloadSlug = ${i.join(" | ")};`,""),o.join("\n").replace(/\n{3,}/gu,"\n\n")}(i,e),a=function(e){return{globals:e.globals.map(k),collections:e.collections.map(k)}}(i),l=[...i.diagnostics],f=void 0===e.outFile?void 0:n(e.outFile),p=void 0===e.inventoryFile?void 0:n(e.inventoryFile),g=[f,p].filter(e=>void 0!==e),h=i.globals.length+i.collections.length===0;return h&&g.length>0?l.push(`Nothing written: the schema is empty (0 globals, 0 collections), so ${g.join(" and ")} were left as they are.`):(void 0!==f&&await W(f,r),void 0!==p&&await W(p,`${JSON.stringify(a,null,2)}\n`)),{code:r,diagnostics:l,schema:i,inventory:a,...h||void 0===f?{}:{outFile:f},...h||void 0===p?{}:{inventoryFile:p}}}var H=/* @__PURE__ */new Set([".ts",".mts",".cts",".js",".mjs",".cjs",".json"]);function Q(s){const a=s.watch??!0;let l,c,u=process.cwd(),d=!1,f=!1;async function p(e){if(d)f=!0;else{d=!0;try{const t=await Z({configPath:s.configPath,outFile:s.outPath,cwd:u});if(void 0===t.outFile)e?.error(`pll-codegen: nothing written — ${t.diagnostics.join(" ")}`);else if(!0!==s.quiet){e?.info(`pll-codegen: ${String(t.schema.globals.length)} globals, ${String(t.schema.collections.length)} collections → ${s.outPath}`);for(const o of t.diagnostics)e?.warn(`pll-codegen: ${o}`)}}catch(t){e?.error(`pll-codegen failed: ${t instanceof Error?t.message:String(t)}`)}finally{d=!1,f&&(f=!1,p(e))}}}return{name:"payload-live-preview:codegen",hooks:{"astro:config:setup":async({command:d,logger:f,config:g})=>{u=function(e){return void 0===e?process.cwd():e instanceof URL||e.startsWith("file:")?r(e):e}(g?.root),await p(f),a&&"dev"===d&&function(r){const a=t(o(u,s.configPath)),d=o(u,s.outPath);try{l=e(a,{recursive:!0},(e,t)=>{if(null===t)return;const s=o(a,t);s===d||s.includes(`${n}node_modules${n}`)||H.has(i(s))&&(clearTimeout(c),c=setTimeout(()=>{p(r)},100))})}catch(e){r?.warn(`pll-codegen watcher unavailable: ${e instanceof Error?e.message:String(e)}`)}}(f)},"astro:server:start":()=>{},"astro:build:start":()=>{clearTimeout(c),l?.close(),l=void 0}}}}export{Q as livePreviewCodegen};
|
|
2
2
|
//# sourceMappingURL=codegen-astro.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"codegen-astro.js","names":["SCALAR_TYPE_MAP","text","textarea","email","richText","number","checkbox","date","code","point","ui","radio","extractField","literal","type","readStringProperty","STRUCTURAL_TYPES","Set","name","has","base","required","readBooleanProperty","localized","kind","fields","extractNestedFields","blocks","extractBlocks","flattened","extractNestedFieldsFromStructural","target","readRelationTarget","hasMany","readRelationTargetSingle","options","readSelectOptions","typeRef","fieldsLiteral","readArrayProperty","out","element","getElements","Node","isObjectLiteralExpression","f","push","tabsLiteral","tabElement","tabName","tabFields","blocksLiteral","slug","typeName","toPascalCase","property","getProperty","isPropertyAssignment","initialiser","getInitializer","isStringLiteral","getLiteralValue","isArrayLiteralExpression","filter","map","el","optionsLiteral","value","isNoSubstitutionTemplateLiteral","getKind","SyntaxKind","TrueKeyword","FalseKeyword","node","split","Boolean","part","charAt","toUpperCase","slice","join","extractSchema","project","Project","tsConfigFilePath","skipAddingFilesFromTsConfig","sourceFile","addSourceFileAtPathIfExists","configPath","globals","collections","diagnostics","resolveSourceFileDependencies","configLiteral","findConfigLiteral","extractSlugList","defaultExport","getExportSymbols","find","sym","getName","declarations","getDeclarations","decl","candidate","unwrapToObjectLiteral","call","getDescendantsOfKind","CallExpression","expr","getExpression","isIdentifier","getText","arg","getArguments","isExportAssignment","unwrapExpression","isVariableDeclaration","isCallExpression","isAsExpression","isSatisfiesExpression","resolveIdentifierToObjectLiteral","identifier","getDefinitionNodes","result","key","array","resolveToArrayLiteral","extractEntries","isSpreadElement","expandedArray","resolveToObjectLiteral","extractFieldList","configEntry","fieldsProperty","expanded","inner","field","resolved","emitTypes","schema","lines","header","seenAuxNames","emitSlug","length","g","c","slugAliases","replace","emitAuxiliaries","emitFieldMember","prefix","auxName","nestedTypeName","add","block","blockTypeName","emitBlockInterface","parent","markLocalizedAsDeprecated","optional","renderFieldType","b","Array","isArray","t","o","child","collect","basePath","path","entry","buildPreviewInventory","async","generateTypes","cwd","process","isAbsolute","resolve","inventory","outFile","inventoryFile","mkdir","dirname","recursive","writeFile","JSON","stringify","livePreviewCodegen","watcher","watchEnabled","watch","active","queued","regenerate","logger","outPath","quiet","info","diagnostic","warn","err","message","Error","String","error","__name","hooks","command","close","je"],"sources":["../src/codegen/parser/extract-field.ts","../src/codegen/parser/extract-schema.ts","../src/codegen/emit/emit-types.ts","../src/codegen/inventory.ts","../src/codegen/index.ts","../src/codegen/astro-plugin.ts"],"sourcesContent":["/**\n * Field-level extraction from ts-morph object literals.\n *\n * Payload field definitions are TypeScript object literals like:\n *\n * ```ts\n * { name: 'heroTitle', type: 'text', required: true }\n * ```\n *\n * `extractField()` reads one such literal and produces a normalised\n * `ExtractedField`. It is intentionally tolerant — unknown field types\n * collapse to `unknown`, deeply-conditional fields surface as a\n * diagnostic rather than crashing the parser.\n *\n * @module @codegen/parser/extract-field\n */\n\nimport {\n Node,\n SyntaxKind,\n type ArrayLiteralExpression,\n type ObjectLiteralExpression,\n type PropertyAssignment,\n} from 'ts-morph';\nimport type { ExtractedBlock, ExtractedField, ExtractedScalarField } from './types';\n\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: 'unknown',\n ui: 'unknown',\n radio: 'string',\n};\n\nexport function extractField(literal: ObjectLiteralExpression): ExtractedField | undefined {\n const type = readStringProperty(literal, 'type');\n if (type === undefined) return undefined;\n\n // Most fields carry a `name`. Structural containers (`tabs`,\n // `row`, `collapsible`) do not — they flatten into their parent.\n const STRUCTURAL_TYPES = new Set(['tabs', 'row', 'collapsible']);\n const name = readStringProperty(literal, 'name');\n if (name === undefined && !STRUCTURAL_TYPES.has(type)) return undefined;\n\n const required = readBooleanProperty(literal, 'required') ?? false;\n const localized = readBooleanProperty(literal, 'localized') ?? false;\n const base = { name: name ?? '__structural', required, localized };\n\n switch (type) {\n case 'array':\n return {\n ...base,\n kind: 'array',\n fields: extractNestedFields(literal),\n };\n case 'blocks':\n return {\n ...base,\n kind: 'blocks',\n blocks: extractBlocks(literal),\n };\n case 'group':\n return {\n ...base,\n kind: 'group',\n fields: extractNestedFields(literal),\n };\n case 'tabs':\n case 'row':\n case 'collapsible': {\n // Structural containers — flatten their inner fields up so they\n // appear at the parent's level (Payload does the same at runtime).\n const flattened = extractNestedFieldsFromStructural(literal);\n return {\n ...base,\n kind: 'group',\n fields: flattened,\n };\n }\n case 'relationship':\n return {\n ...base,\n kind: 'relationship',\n target: readRelationTarget(literal),\n hasMany: readBooleanProperty(literal, 'hasMany') ?? false,\n };\n case 'upload':\n return {\n ...base,\n kind: 'upload',\n target: readRelationTargetSingle(literal) ?? 'media',\n };\n case 'json':\n return { ...base, kind: 'json' };\n case 'select':\n return {\n ...base,\n kind: 'select',\n options: readSelectOptions(literal),\n hasMany: readBooleanProperty(literal, 'hasMany') ?? false,\n };\n default: {\n const typeRef = SCALAR_TYPE_MAP[type] ?? 'unknown';\n return { ...base, kind: 'scalar', typeRef };\n }\n }\n}\n\nfunction extractNestedFields(literal: ObjectLiteralExpression): readonly ExtractedField[] {\n const fieldsLiteral = readArrayProperty(literal, 'fields');\n if (!fieldsLiteral) return [];\n const out: ExtractedField[] = [];\n for (const element of fieldsLiteral.getElements()) {\n if (!Node.isObjectLiteralExpression(element)) continue;\n const f = extractField(element);\n if (!f) continue;\n // Structural containers carry the magic `__structural` sentinel\n // name — splat their child fields into the parent instead of\n // surfacing them as a nameless property.\n if (f.kind === 'group' && f.name === '__structural') {\n out.push(...f.fields);\n } else {\n out.push(f);\n }\n }\n return out;\n}\n\nfunction extractNestedFieldsFromStructural(\n literal: ObjectLiteralExpression,\n): readonly ExtractedField[] {\n // `tabs` is the awkward one — its inner shape is `tabs: [{ name, fields }, …]`\n // and each tab can either flatten via `name` or expose itself as a group.\n const tabsLiteral = readArrayProperty(literal, 'tabs');\n if (tabsLiteral) {\n const out: ExtractedField[] = [];\n for (const tabElement of tabsLiteral.getElements()) {\n if (!Node.isObjectLiteralExpression(tabElement)) continue;\n const tabName = readStringProperty(tabElement, 'name');\n const tabFields = extractNestedFields(tabElement);\n if (tabName !== undefined) {\n out.push({\n kind: 'group',\n name: tabName,\n required: false,\n localized: false,\n fields: tabFields,\n });\n } else {\n // Named-less tab — flatten its fields into the parent's surface.\n out.push(...tabFields);\n }\n }\n return out;\n }\n // `row` / `collapsible` — fields array sits directly on the literal.\n return extractNestedFields(literal);\n}\n\nfunction extractBlocks(literal: ObjectLiteralExpression): readonly ExtractedBlock[] {\n const blocksLiteral = readArrayProperty(literal, 'blocks');\n if (!blocksLiteral) return [];\n const out: ExtractedBlock[] = [];\n for (const element of blocksLiteral.getElements()) {\n if (!Node.isObjectLiteralExpression(element)) continue;\n const slug = readStringProperty(element, 'slug');\n if (slug === undefined) continue;\n out.push({\n slug,\n typeName: toPascalCase(slug),\n fields: extractNestedFields(element),\n });\n }\n return out;\n}\n\nfunction readRelationTarget(literal: ObjectLiteralExpression): string | readonly string[] {\n const property = literal.getProperty('relationTo');\n if (!property || !Node.isPropertyAssignment(property)) return 'unknown';\n const initialiser = property.getInitializer();\n if (initialiser && Node.isStringLiteral(initialiser)) return initialiser.getLiteralValue();\n if (initialiser && Node.isArrayLiteralExpression(initialiser)) {\n return initialiser\n .getElements()\n .filter(Node.isStringLiteral)\n .map((el) => el.getLiteralValue());\n }\n return 'unknown';\n}\n\nfunction readRelationTargetSingle(literal: ObjectLiteralExpression): string | undefined {\n const target = readRelationTarget(literal);\n if (typeof target === 'string') return target;\n return target[0];\n}\n\nfunction readSelectOptions(literal: ObjectLiteralExpression): readonly string[] {\n const optionsLiteral = readArrayProperty(literal, 'options');\n if (!optionsLiteral) return [];\n const out: string[] = [];\n for (const element of optionsLiteral.getElements()) {\n if (Node.isStringLiteral(element)) {\n out.push(element.getLiteralValue());\n } else if (Node.isObjectLiteralExpression(element)) {\n const value = readStringProperty(element, 'value');\n if (value !== undefined) out.push(value);\n }\n }\n return out;\n}\n\nfunction readStringProperty(literal: ObjectLiteralExpression, name: string): string | undefined {\n const property = literal.getProperty(name);\n if (!property || !isPropertyAssignment(property)) return undefined;\n const initialiser = property.getInitializer();\n if (initialiser && Node.isStringLiteral(initialiser)) return initialiser.getLiteralValue();\n if (initialiser && Node.isNoSubstitutionTemplateLiteral(initialiser)) {\n return initialiser.getLiteralValue();\n }\n return undefined;\n}\n\nfunction readBooleanProperty(literal: ObjectLiteralExpression, name: string): boolean | undefined {\n const property = literal.getProperty(name);\n if (!property || !isPropertyAssignment(property)) return undefined;\n const initialiser = property.getInitializer();\n if (!initialiser) return undefined;\n if (initialiser.getKind() === SyntaxKind.TrueKeyword) return true;\n if (initialiser.getKind() === SyntaxKind.FalseKeyword) return false;\n return undefined;\n}\n\nfunction readArrayProperty(\n literal: ObjectLiteralExpression,\n name: string,\n): ArrayLiteralExpression | undefined {\n const property = literal.getProperty(name);\n if (!property || !isPropertyAssignment(property)) return undefined;\n const initialiser = property.getInitializer();\n if (initialiser && Node.isArrayLiteralExpression(initialiser)) return initialiser;\n return undefined;\n}\n\nfunction isPropertyAssignment(node: Node): node is PropertyAssignment {\n return Node.isPropertyAssignment(node);\n}\n\nfunction toPascalCase(slug: string): string {\n return slug\n .split(/[-_\\s]+/)\n .filter(Boolean)\n .map((part) => part.charAt(0).toUpperCase() + part.slice(1))\n .join('');\n}\n\nexport { toPascalCase };\n","/**\n * Schema-level extraction: open `payload.config.ts`, find every\n * collection and global definition, walk into them.\n *\n * The extractor is deliberately lenient. Payload configurations are\n * full TypeScript programs — a strict parser would have to model\n * conditional types, factory functions, plugin closures. Instead we\n * recognise the *common* shapes (object literal, identifier\n * referencing an imported literal, default export from a sibling\n * file) and emit a diagnostic for anything we can't unwrap.\n *\n * @module @codegen/parser/extract-schema\n */\n\nimport {\n Node,\n Project,\n SyntaxKind,\n type ArrayLiteralExpression,\n type Identifier,\n type ObjectLiteralExpression,\n type SourceFile,\n} from 'ts-morph';\nimport type { ExtractedField, ExtractedSchema, ExtractedSlug } from './types';\nimport { extractField, toPascalCase } from './extract-field';\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 /**\n * Optional path to a `tsconfig.json`. When set, ts-morph loads the\n * project's module-resolution configuration so cross-file imports\n * (Homepage from './globals') can be followed.\n */\n readonly tsConfigFilePath?: string;\n}\n\nexport function extractSchema(options: ExtractSchemaOptions): ExtractedSchema {\n const project =\n options.project ??\n new Project(\n options.tsConfigFilePath !== undefined\n ? { tsConfigFilePath: options.tsConfigFilePath }\n : { skipAddingFilesFromTsConfig: true },\n );\n const sourceFile = project.addSourceFileAtPathIfExists(options.configPath);\n if (!sourceFile) {\n return {\n globals: [],\n collections: [],\n diagnostics: [`Could not open ${options.configPath}`],\n };\n }\n // Pull in every transitively-imported file so cross-file identifier\n // resolution (e.g., `import { Homepage } from './globals'`) can\n // reach the underlying object literal.\n project.resolveSourceFileDependencies();\n const diagnostics: string[] = [];\n\n const configLiteral = findConfigLiteral(sourceFile, diagnostics);\n if (!configLiteral) {\n return {\n globals: [],\n collections: [],\n diagnostics: [\n ...diagnostics,\n 'Could not locate a buildConfig({...}) call or `export default {...}` in the config file.',\n ],\n };\n }\n\n const globals = extractSlugList(configLiteral, 'globals', diagnostics);\n const collections = extractSlugList(configLiteral, 'collections', diagnostics);\n\n return { globals, collections, diagnostics };\n}\n\nfunction findConfigLiteral(\n sourceFile: SourceFile,\n diagnostics: string[],\n): ObjectLiteralExpression | undefined {\n const defaultExport = sourceFile.getExportSymbols().find((sym) => sym.getName() === 'default');\n if (!defaultExport) {\n diagnostics.push('payload.config.ts has no default export.');\n return undefined;\n }\n const declarations = defaultExport.getDeclarations();\n for (const decl of declarations) {\n const candidate = unwrapToObjectLiteral(decl);\n if (candidate) return candidate;\n }\n // Fallback: scan the source file for the first `buildConfig({...})` call.\n for (const call of sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression)) {\n const expr = call.getExpression();\n if (Node.isIdentifier(expr) && expr.getText() === 'buildConfig') {\n const arg = call.getArguments()[0];\n if (arg && Node.isObjectLiteralExpression(arg)) return arg;\n }\n }\n return undefined;\n}\n\nfunction unwrapToObjectLiteral(node: Node): ObjectLiteralExpression | undefined {\n if (Node.isExportAssignment(node)) {\n return unwrapExpression(node.getExpression());\n }\n if (Node.isVariableDeclaration(node)) {\n const initialiser = node.getInitializer();\n if (initialiser) return unwrapExpression(initialiser);\n }\n return undefined;\n}\n\nfunction unwrapExpression(node: Node | undefined): ObjectLiteralExpression | undefined {\n if (!node) return undefined;\n if (Node.isObjectLiteralExpression(node)) return node;\n if (Node.isCallExpression(node)) {\n // `buildConfig({...})` or `defineConfig({...})` — first arg.\n const arg = node.getArguments()[0];\n if (arg && Node.isObjectLiteralExpression(arg)) return arg;\n }\n if (Node.isAsExpression(node)) {\n return unwrapExpression(node.getExpression());\n }\n if (Node.isSatisfiesExpression(node)) {\n return unwrapExpression(node.getExpression());\n }\n if (Node.isIdentifier(node)) {\n return resolveIdentifierToObjectLiteral(node);\n }\n return undefined;\n}\n\nfunction resolveIdentifierToObjectLiteral(\n identifier: Identifier,\n): ObjectLiteralExpression | undefined {\n for (const decl of identifier.getDefinitionNodes()) {\n const result = unwrapToObjectLiteral(decl);\n if (result) return result;\n }\n return undefined;\n}\n\nfunction extractSlugList(\n configLiteral: ObjectLiteralExpression,\n key: 'globals' | 'collections',\n diagnostics: string[],\n): readonly ExtractedSlug[] {\n const property = configLiteral.getProperty(key);\n if (!property) return [];\n if (!Node.isPropertyAssignment(property)) return [];\n const initialiser = property.getInitializer();\n if (!initialiser) return [];\n const array = resolveToArrayLiteral(initialiser);\n if (!array) return [];\n return extractEntries(array, diagnostics);\n}\n\nfunction extractEntries(\n array: ArrayLiteralExpression,\n diagnostics: string[],\n): readonly ExtractedSlug[] {\n const out: ExtractedSlug[] = [];\n for (const element of array.getElements()) {\n // Handle `...someArray` spreads — common pattern in real Payload\n // configs that split globals/collections into named buckets.\n if (Node.isSpreadElement(element)) {\n const expandedArray = resolveToArrayLiteral(element.getExpression());\n if (!expandedArray) {\n diagnostics.push(\n `Could not resolve spread \"${element.getText().slice(0, 80)}\" to an array literal.`,\n );\n continue;\n }\n out.push(...extractEntries(expandedArray, diagnostics));\n continue;\n }\n const literal = resolveToObjectLiteral(element);\n if (!literal) {\n diagnostics.push(\n `Could not resolve config entry \"${element.getText().slice(0, 80)}\" to an object literal.`,\n );\n continue;\n }\n const slug = readStringProperty(literal, 'slug');\n if (slug === undefined) {\n diagnostics.push(`Skipping a config entry — no string \\`slug\\` field found.`);\n continue;\n }\n out.push({\n slug,\n typeName: toPascalCase(slug),\n fields: extractFieldList(literal),\n });\n }\n return out;\n}\n\nfunction extractFieldList(configEntry: ObjectLiteralExpression): readonly ExtractedField[] {\n const fieldsProperty = configEntry.getProperty('fields');\n if (!fieldsProperty || !Node.isPropertyAssignment(fieldsProperty)) return [];\n const initialiser = fieldsProperty.getInitializer();\n if (!initialiser || !Node.isArrayLiteralExpression(initialiser)) return [];\n const out: ExtractedField[] = [];\n for (const element of initialiser.getElements()) {\n // Allow spread elements for users who split fields into reusable\n // arrays (e.g., `...commonSeoFields`).\n if (Node.isSpreadElement(element)) {\n const expanded = resolveToArrayLiteral(element.getExpression());\n if (!expanded) continue;\n for (const inner of expanded.getElements()) {\n const literal = resolveToObjectLiteral(inner);\n if (!literal) continue;\n const field = extractField(literal);\n if (!field) continue;\n if (field.kind === 'group' && field.name === '__structural') {\n out.push(...field.fields);\n } else {\n out.push(field);\n }\n }\n continue;\n }\n const literal = resolveToObjectLiteral(element);\n if (!literal) continue;\n const field = extractField(literal);\n if (!field) continue;\n if (field.kind === 'group' && field.name === '__structural') {\n out.push(...field.fields);\n } else {\n out.push(field);\n }\n }\n return out;\n}\n\nfunction resolveToObjectLiteral(node: Node): ObjectLiteralExpression | undefined {\n if (Node.isObjectLiteralExpression(node)) return node;\n if (Node.isIdentifier(node)) return resolveIdentifierToObjectLiteral(node);\n if (Node.isAsExpression(node)) return resolveToObjectLiteral(node.getExpression());\n if (Node.isSatisfiesExpression(node)) return resolveToObjectLiteral(node.getExpression());\n if (Node.isCallExpression(node)) {\n const arg = node.getArguments()[0];\n if (arg) return resolveToObjectLiteral(arg);\n }\n return undefined;\n}\n\nfunction resolveToArrayLiteral(node: Node): ArrayLiteralExpression | undefined {\n if (Node.isArrayLiteralExpression(node)) return node;\n if (Node.isAsExpression(node)) return resolveToArrayLiteral(node.getExpression());\n if (Node.isSatisfiesExpression(node)) return resolveToArrayLiteral(node.getExpression());\n if (Node.isIdentifier(node)) {\n for (const decl of node.getDefinitionNodes()) {\n if (Node.isVariableDeclaration(decl)) {\n const initialiser = decl.getInitializer();\n if (initialiser) {\n const resolved = resolveToArrayLiteral(initialiser);\n if (resolved) return resolved;\n }\n }\n }\n }\n return undefined;\n}\n\nfunction readStringProperty(literal: ObjectLiteralExpression, name: string): string | undefined {\n const property = literal.getProperty(name);\n if (!property || !Node.isPropertyAssignment(property)) return undefined;\n const initialiser = property.getInitializer();\n if (initialiser && Node.isStringLiteral(initialiser)) return initialiser.getLiteralValue();\n return undefined;\n}\n","/**\n * Render `ExtractedSchema` to a TypeScript source string.\n *\n * The output is one self-contained `.ts` file that ships:\n *\n * - one `interface` per global and per collection,\n * - nested `interface` declarations for `group`/`array`/`blocks`,\n * - discriminated unions for `blocks` fields (one variant per slug),\n * - `PayloadCollections` / `PayloadGlobals` maps for slug-keyed\n * access (`PayloadCollections['posts']`), and\n * - a `PayloadSlug` alias.\n *\n * Nothing in the runtime depends on this output — consumers import\n * what they need by name.\n *\n * @module @codegen/emit/emit-types\n */\n\nimport type {\n ExtractedBlock,\n ExtractedField,\n ExtractedSchema,\n ExtractedSlug,\n} from '../parser/types';\nimport { toPascalCase } from '../parser/extract-field';\n\nexport interface EmitOptions {\n /** When true, includes a `@deprecated` JSDoc on localized fields. */\n readonly markLocalizedAsDeprecated?: boolean;\n /** Header text injected at the top of the output. Defaults sensibly. */\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 */';\n\nexport function emitTypes(schema: ExtractedSchema, options: EmitOptions = {}): string {\n const lines: string[] = [];\n lines.push(options.header ?? DEFAULT_HEADER);\n lines.push('');\n lines.push('import type { PayloadMedia, PayloadRelationship } from \"payload-live-preview\";');\n lines.push('');\n\n // Emit slug interfaces (globals + collections), each potentially\n // accompanied by nested interface declarations.\n const seenAuxNames = new Set<string>();\n for (const slug of [...schema.globals, ...schema.collections]) {\n emitSlug(slug, lines, seenAuxNames, options);\n lines.push('');\n }\n\n // Slug → type maps.\n if (schema.globals.length > 0) {\n lines.push('export type PayloadGlobals = {');\n for (const g of schema.globals) {\n lines.push(` '${g.slug}': ${g.typeName};`);\n }\n lines.push('};');\n lines.push('');\n }\n if (schema.collections.length > 0) {\n lines.push('export type PayloadCollections = {');\n for (const c of schema.collections) {\n lines.push(` '${c.slug}': ${c.typeName};`);\n }\n lines.push('};');\n lines.push('');\n }\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 lines.push('');\n }\n\n return lines.join('\\n').replace(/\\n{3,}/g, '\\n\\n');\n}\n\nfunction emitSlug(\n slug: ExtractedSlug,\n lines: string[],\n seenAuxNames: Set<string>,\n options: EmitOptions,\n): void {\n emitAuxiliaries(slug.typeName, slug.fields, lines, seenAuxNames, options);\n lines.push(`export interface ${slug.typeName} {`);\n for (const field of slug.fields) {\n emitFieldMember(field, slug.typeName, lines, options);\n }\n lines.push('}');\n}\n\nfunction emitAuxiliaries(\n prefix: string,\n fields: readonly ExtractedField[],\n lines: string[],\n seenAuxNames: 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 (seenAuxNames.has(auxName)) continue;\n seenAuxNames.add(auxName);\n emitAuxiliaries(auxName, field.fields, lines, seenAuxNames, options);\n lines.push(`export interface ${auxName} {`);\n for (const inner of field.fields) {\n emitFieldMember(inner, auxName, lines, options);\n }\n lines.push('}');\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 (seenAuxNames.has(blockTypeName)) continue;\n seenAuxNames.add(blockTypeName);\n emitAuxiliaries(blockTypeName, block.fields, lines, seenAuxNames, options);\n emitBlockInterface(blockTypeName, block, lines, options);\n }\n }\n }\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) {\n emitFieldMember(field, typeName, lines, options);\n }\n lines.push('}');\n lines.push('');\n}\n\nfunction emitFieldMember(\n field: ExtractedField,\n parent: string,\n lines: string[],\n options: EmitOptions,\n): void {\n if (options.markLocalizedAsDeprecated && field.localized) {\n lines.push(` /** @localized */`);\n }\n const optional = field.required ? '' : '?';\n lines.push(` ${field.name}${optional}: ${renderFieldType(field, parent)};`);\n}\n\nfunction renderFieldType(field: ExtractedField, parent: string): string {\n switch (field.kind) {\n case 'scalar':\n return 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((b) => nestedTypeName(nestedTypeName(parent, field.name), b.typeName))\n .join(' | ');\n return `(${variants})[]`;\n }\n case 'group':\n return nestedTypeName(parent, field.name);\n case 'relationship': {\n const targetExpr: string = Array.isArray(field.target)\n ? field.target.map((t) => `'${t}'`).join(' | ')\n : `'${field.target as string}'`;\n const base = `PayloadRelationship<${targetExpr}>`;\n return field.hasMany ? `${base}[]` : base;\n }\n case 'upload':\n return '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((o) => `'${o}'`).join(' | ');\n return field.hasMany ? `(${literal})[]` : literal;\n }\n }\n}\n\nfunction nestedTypeName(parent: string, child: string): string {\n return `${parent}${toPascalCase(child)}`;\n}\n","/**\n * Preview inventory — which schema fields a binding can actually address.\n *\n * A live-preview integration has two halves that must agree: the Payload schema\n * and the markup that binds it. Nothing has verified the agreement, so every\n * consumer that cared has built its own inventory and its own scanner, and\n * re-derived a path convention this package already owns.\n *\n * The convention is not obvious, which is the point of publishing it rather\n * than documenting it:\n *\n * - `tabs`, `row` and `collapsible` contribute **no** path segment. The\n * parser marks unnamed ones with a `__structural` sentinel; emitting it\n * would produce `__structural.title` for a field the runtime resolves as\n * `title`.\n * - a `group` contributes its name (`hero.title`),\n * - an `array` addresses its items through `.*` (`slides.*.title`),\n * - a `blocks` field addresses each block through `.*.<slug>`.\n *\n * That is `@schema/walker`'s rule, deliberately: bindings are matched against\n * it at runtime, so an inventory using any other spelling would be wrong in the\n * one place it is supposed to help.\n *\n * @module @codegen/inventory\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. */\nexport function buildPreviewInventory(schema: ExtractedSchema): PreviewInventory {\n return {\n globals: schema.globals.map(entry),\n collections: schema.collections.map(entry),\n };\n}\n\n/** A binding found in consumer markup, however that consumer found it. */\nexport interface PreviewBindingReference {\n readonly kind: 'global' | 'collection';\n readonly slug: string;\n readonly path: string;\n /** Free-form origin for the diagnostic, e.g. `Hero.astro:42`. */\n readonly source?: string;\n}\n\nexport interface PreviewCoverageOptions {\n /**\n * Report schema fields that no binding addresses. Off by default: a page is\n * allowed to render a subset, and most consumers want the unknown-binding\n * half first.\n */\n readonly reportUnbound?: boolean;\n}\n\n/**\n * Cross-check bindings against the inventory.\n *\n * Extraction stays with the consumer — resolving `bind('x')` in Astro, JSX or\n * Svelte markup is framework work this package cannot do generically. What it\n * can do is own the answer to \"is that a real, addressable field\", which is the\n * half that drifts silently when a schema is renamed.\n */\nexport function checkPreviewBindings(\n inventory: PreviewInventory,\n bindings: readonly PreviewBindingReference[],\n options: PreviewCoverageOptions = {},\n): readonly string[] {\n const diagnostics: string[] = [];\n const byKey = new Map<string, ReadonlySet<string>>();\n for (const [kind, entries] of [\n ['global', inventory.globals],\n ['collection', inventory.collections],\n ] as const) {\n for (const item of entries) {\n byKey.set(`${kind}:${item.slug}`, new Set(item.fields.map((f) => f.path)));\n }\n }\n\n const seen = new Map<string, Set<string>>();\n for (const binding of bindings) {\n const key = `${binding.kind}:${binding.slug}`;\n const where = binding.source === undefined ? '' : ` (${binding.source})`;\n const paths = byKey.get(key);\n if (paths === undefined) {\n diagnostics.push(`unknown ${binding.kind} \"${binding.slug}\"${where}`);\n continue;\n }\n if (!paths.has(binding.path)) {\n diagnostics.push(`${key} has no field \"${binding.path}\"${where}`);\n continue;\n }\n let bound = seen.get(key);\n if (bound === undefined) {\n bound = new Set<string>();\n seen.set(key, bound);\n }\n bound.add(binding.path);\n }\n\n if (options.reportUnbound === true) {\n for (const [key, paths] of byKey) {\n const bound = seen.get(key) ?? new Set<string>();\n for (const path of paths) {\n if (!bound.has(path)) diagnostics.push(`${key} field \"${path}\" is never bound`);\n }\n }\n }\n\n return diagnostics;\n}\n","/**\n * Programmatic codegen API.\n *\n * ```ts\n * import { generateTypes } from 'payload-live-preview/codegen';\n * const { code, diagnostics } = await generateTypes({\n * configPath: 'backend/src/payload.config.ts',\n * outFile: 'frontend/src/payload-types.ts',\n * });\n * ```\n *\n * @module @codegen\n */\n\nimport { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, isAbsolute, resolve } from 'node:path';\nimport { extractSchema, type ExtractSchemaOptions } from './parser/extract-schema';\nimport { emitTypes, type EmitOptions } from './emit/emit-types';\nimport type { ExtractedSchema } from './parser/types';\n\nimport { buildPreviewInventory, type PreviewInventory } from './inventory';\n\nexport interface GenerateTypesOptions\n extends Pick<ExtractSchemaOptions, 'configPath' | 'project' | 'tsConfigFilePath'>, EmitOptions {\n /**\n * If set, the generated code is written to this absolute or\n * cwd-relative path. The function still returns the rendered string\n * in `code` so callers can verify before writing.\n */\n readonly outFile?: string;\n /** Working directory used to resolve relative paths. Defaults to `process.cwd()`. */\n readonly cwd?: string;\n /**\n * If set, the preview inventory is written to this path as JSON.\n *\n * Every field a binding can address, spelled the way the runtime resolves it.\n * Consumers have had to re-derive that spelling to check their markup against\n * the schema, and re-deriving it is where the two drift apart.\n */\n readonly inventoryFile?: string;\n}\n\nexport interface GenerateTypesResult {\n readonly code: string;\n readonly diagnostics: readonly string[];\n readonly schema: ExtractedSchema;\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\nexport async function generateTypes(options: GenerateTypesOptions): Promise<GenerateTypesResult> {\n const cwd = options.cwd ?? process.cwd();\n const configPath = isAbsolute(options.configPath)\n ? options.configPath\n : resolve(cwd, options.configPath);\n const schema = extractSchema({\n 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\n const result: GenerateTypesResult = {\n code,\n diagnostics: schema.diagnostics,\n schema,\n inventory,\n ...(options.outFile !== undefined\n ? { outFile: isAbsolute(options.outFile) ? options.outFile : resolve(cwd, options.outFile) }\n : {}),\n ...(options.inventoryFile !== undefined\n ? {\n inventoryFile: isAbsolute(options.inventoryFile)\n ? options.inventoryFile\n : resolve(cwd, options.inventoryFile),\n }\n : {}),\n };\n\n if (result.outFile) {\n await mkdir(dirname(result.outFile), { recursive: true });\n await writeFile(result.outFile, code, 'utf8');\n }\n if (result.inventoryFile) {\n await mkdir(dirname(result.inventoryFile), { recursive: true });\n // Trailing newline and stable key order so the file is diffable and can be\n // committed as a contract rather than regenerated noise.\n await writeFile(result.inventoryFile, `${JSON.stringify(inventory, null, 2)}\\n`, 'utf8');\n }\n\n return result;\n}\n\nexport { buildPreviewInventory, checkPreviewBindings } from './inventory';\nexport type {\n PreviewBindingReference,\n PreviewCoverageOptions,\n PreviewInventory,\n PreviewInventoryEntry,\n PreviewInventoryField,\n} from './inventory';\nexport { extractSchema } from './parser/extract-schema';\nexport { emitTypes } from './emit/emit-types';\nexport type { ExtractedSchema, ExtractedSlug, ExtractedField } from './parser/types';\n","/**\n * Astro integration — regenerates the types file on dev-server start\n * and (optionally) watches `payload.config.ts` for changes.\n *\n * ```ts\n * // astro.config.mjs\n * import { livePreviewCodegen } from 'payload-live-preview/codegen';\n *\n * export default defineConfig({\n * integrations: [\n * livePreviewCodegen({\n * configPath: '../backend/src/payload.config.ts',\n * outPath: 'src/payload-types.ts',\n * watch: true,\n * }),\n * ],\n * });\n * ```\n *\n * The plugin uses Node's `fs.watch` (no chokidar dependency) — Astro\n * already bundles enough watch-mode tooling that we don't need a\n * full-fat library here.\n *\n * @module @codegen/astro-plugin\n */\n\nimport { watch } from 'node:fs';\nimport { generateTypes } from './index';\n\nexport interface AstroCodegenOptions {\n /** Path to `payload.config.ts` (absolute or relative to Astro's root). */\n readonly configPath: string;\n /** Output path for generated types (absolute or relative to Astro's root). */\n readonly outPath: string;\n /** Re-run on `payload.config.ts` changes during `astro dev`. Default `true`. */\n readonly watch?: boolean;\n /** Quiet mode — only error logging. Default `false`. */\n readonly quiet?: boolean;\n}\n\ninterface AstroLogger {\n readonly info: (msg: string) => void;\n readonly warn: (msg: string) => void;\n readonly error: (msg: string) => void;\n}\n\ninterface AstroIntegration {\n readonly name: string;\n readonly hooks: Readonly<{\n readonly 'astro:config:setup'?: (params: {\n readonly command: string;\n readonly logger?: AstroLogger;\n }) => Promise<void> | void;\n readonly 'astro:server:start'?: () => void;\n readonly 'astro:build:start'?: () => Promise<void> | void;\n }>;\n}\n\nexport function livePreviewCodegen(options: AstroCodegenOptions): AstroIntegration {\n const watchEnabled = options.watch ?? true;\n let watcher: ReturnType<typeof watch> | undefined;\n let active = false;\n let queued = false;\n\n async function regenerate(logger: AstroLogger | undefined): Promise<void> {\n if (active) {\n queued = true;\n return;\n }\n active = true;\n try {\n const result = await generateTypes({\n configPath: options.configPath,\n outFile: options.outPath,\n });\n if (!options.quiet) {\n logger?.info(\n `pll-codegen: ${result.schema.globals.length} globals, ${result.schema.collections.length} collections → ${options.outPath}`,\n );\n for (const diagnostic of result.diagnostics) {\n logger?.warn(`pll-codegen: ${diagnostic}`);\n }\n }\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n logger?.error(`pll-codegen failed: ${message}`);\n } finally {\n active = false;\n if (queued) {\n queued = false;\n void regenerate(logger);\n }\n }\n }\n\n return {\n name: 'payload-live-preview:codegen',\n hooks: {\n 'astro:config:setup': async ({ command, logger }) => {\n await regenerate(logger);\n if (watchEnabled && command === 'dev') {\n try {\n watcher = watch(options.configPath, () => {\n void regenerate(logger);\n });\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n logger?.warn(`pll-codegen watcher unavailable: ${message}`);\n }\n }\n },\n 'astro:server:start': () => {\n // No-op — watcher was set up during config:setup. Hook kept so\n // future versions can react to dev-server lifecycle events.\n },\n 'astro:build:start': () => {\n watcher?.close();\n watcher = undefined;\n },\n },\n };\n}\n"],"mappings":"kRA0BMA,EAA6E,CACjFC,KAAM,SACNC,SAAU,SACVC,MAAO,SACPC,SAAU,UACVC,OAAQ,SACRC,SAAU,UACVC,KAAM,SACNC,KAAM,SACNC,MAAO,UACPC,GAAI,UACJC,MAAO,UAGF,SAASC,EAAaC,GAC3B,IAAMC,EAAOC,EAAmBF,EAAS,QACzC,QAAa,IAATC,EAAoB,OAIxB,IAAME,EAAmB,IAAIC,IAAI,CAAC,OAAQ,MAAO,gBAC3CC,EAAOH,EAAmBF,EAAS,QACzC,QAAa,IAATK,IAAuBF,EAAiBG,IAAIL,GAAO,OAEvD,IAEMM,EAAO,CAAEF,KAAMA,GAAQ,eAAgBG,SAF5BC,EAAoBT,EAAS,cAAe,EAENU,UADrCD,EAAoBT,EAAS,eAAgB,GAG/D,OAAQC,GACN,IAAK,QACH,MAAO,IACFM,EACHI,KAAM,QACNC,OAAQC,EAAoBb,IAEhC,IAAK,SACH,MAAO,IACFO,EACHI,KAAM,SACNG,OAAQC,EAAcf,IAE1B,IAAK,QACH,MAAO,IACFO,EACHI,KAAM,QACNC,OAAQC,EAAoBb,IAEhC,IAAK,OACL,IAAK,MACL,IAAK,cAAe,CAGlB,IAAMgB,EAAYC,EAAkCjB,GACpD,MAAO,IACFO,EACHI,KAAM,QACNC,OAAQI,EAEZ,CACA,IAAK,eACH,MAAO,IACFT,EACHI,KAAM,eACNO,OAAQC,EAAmBnB,GAC3BoB,QAASX,EAAoBT,EAAS,aAAc,GAExD,IAAK,SACH,MAAO,IACFO,EACHI,KAAM,SACNO,OAAQG,EAAyBrB,IAAY,SAEjD,IAAK,OACH,MAAO,IAAKO,EAAMI,KAAM,QAC1B,IAAK,SACH,MAAO,IACFJ,EACHI,KAAM,SACNW,QAASC,EAAkBvB,GAC3Bo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L,EAAAnL,EAAA,iBAiBAmL,EAAA/K,EAAA,sBAcA+K,EAAA7K,EAAA,4BAMA6K,EAAA3K,EAAA,qBAeA2K,EAAAhM,EAAA,sBAWAgM,EAAAzL,EAAA,uBAUAyL,EAAAxK,EAAA,qBAWAwK,EAAAtJ,EAAA,wBAIAsJ,EAAAzJ,EAAA,gBCtNOyJ,EAAA9H,EAAA,iBAwCP8H,EAAAjH,EAAA,qBAyBAiH,EAAAtG,EAAA,yBAWAsG,EAAA3F,EAAA,oBAoBA2F,EAAAtF,EAAA,oCAUAsF,EAAAhH,EAAA,mBAeAgH,EAAA/E,EAAA,kBAwCA+E,EAAA3E,EAAA,oBAsCA2E,EAAA5E,EAAA,0BAYA4E,EAAAhF,EAAA,yBAkBAgF,EAAAhM,EAAA,sBCtOOgM,EAAApE,EAAA,aA2CPoE,EAAA/D,EAAA,YAcA+D,EAAAzD,EAAA,mBA+BAyD,EAAAjD,EAAA,sBAeAiD,EAAAxD,EAAA,mBAaAwD,EAAA7C,EAAA,mBAkCA6C,EAAArD,EAAA,kBCxIAqD,EAAAtC,EAAA,WA8BAsC,EAAAnC,EAAA,SAOOmC,EAAAlC,EAAA,yBCrCMkC,EAAAhC,EAAA,iBCMNgC,EAAAlB,EAAA,6BAAAsB","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"codegen-astro.js","names":["toPascalCase","slug","split","filter","Boolean","map","part","charAt","toUpperCase","slice","join","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","collect","basePath","out","path","entry","reportSkip","context","node","why","diagnostics","text","getText","snippet","getSourceFile","getBaseName","String","getStartLineNumber","where","unwrap","current","Node","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","Set","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","async","writeOut","content","mkdir","dirname","recursive","writeFile","generateTypes","cwd","process","absolute","isAbsolute","resolve","schema","project","Project","tsConfigFilePath","skipAddingFilesFromTsConfig","sourceFile","addSourceFileAtPathIfExists","configPath","globals","collections","resolveSourceFileDependencies","defaultExport","getDefaultExportSymbol","call","getDescendantsOfKind","SyntaxKind","CallExpression","callee","findConfigLiteral","extractSchema","header","slugAliases","emitTypes","inventory","buildPreviewInventory","outFile","inventoryFile","targets","empty","JSON","stringify","SOURCE_EXTENSIONS","livePreviewCodegen","watchEnabled","watch","watcher","timer","root","active","queued","regenerate","logger","result","outPath","error","quiet","info","diagnostic","warn","Error","message","hooks","command","config","URL","startsWith","fileURLToPath","rootOf","directory","_event","file","changed","includes","sep","extname","clearTimeout","setTimeout","startWatching","close"],"sources":["../src/codegen/parser/names.ts","../src/codegen/emit/emit-types.ts","../src/codegen/inventory.ts","../src/codegen/parser/resolve.ts","../src/codegen/parser/extract-field.ts","../src/codegen/parser/extract-schema.ts","../src/codegen/index.ts","../src/codegen/astro-plugin.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\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 * 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. */\nexport function buildPreviewInventory(schema: ExtractedSchema): PreviewInventory {\n return {\n globals: schema.globals.map(entry),\n collections: schema.collections.map(entry),\n };\n}\n\n/** A binding found in consumer markup, however that consumer found it. */\nexport interface PreviewBindingReference {\n readonly kind: 'global' | 'collection';\n readonly slug: string;\n readonly path: string;\n /** Free-form origin for the diagnostic, e.g. `Hero.astro:42`. */\n readonly source?: string;\n}\n\nexport interface PreviewCoverageOptions {\n /** Also report schema fields no binding addresses; off, since a page may render a subset. */\n readonly reportUnbound?: boolean;\n}\n\n/** Cross-check bindings the consumer extracted against the inventory. */\nexport function checkPreviewBindings(\n inventory: PreviewInventory,\n bindings: readonly PreviewBindingReference[],\n options: PreviewCoverageOptions = {},\n): readonly string[] {\n const diagnostics: string[] = [];\n const byKey = new Map<string, ReadonlySet<string>>();\n for (const [kind, entries] of [\n ['global', inventory.globals],\n ['collection', inventory.collections],\n ] as const) {\n for (const item of entries) {\n byKey.set(`${kind}:${item.slug}`, new Set(item.fields.map((f) => f.path)));\n }\n }\n\n const seen = new Map<string, Set<string>>();\n for (const binding of bindings) {\n const key = `${binding.kind}:${binding.slug}`;\n const where = binding.source === undefined ? '' : ` (${binding.source})`;\n const paths = byKey.get(key);\n if (paths === undefined) {\n diagnostics.push(`unknown ${binding.kind} \"${binding.slug}\"${where}`);\n continue;\n }\n if (!paths.has(binding.path)) {\n diagnostics.push(`${key} has no field \"${binding.path}\"${where}`);\n continue;\n }\n let bound = seen.get(key);\n if (bound === undefined) {\n bound = new Set<string>();\n seen.set(key, bound);\n }\n bound.add(binding.path);\n }\n\n if (options.reportUnbound === true) {\n for (const [key, paths] of byKey) {\n const bound = seen.get(key) ?? new Set<string>();\n for (const path of paths) {\n if (!bound.has(path)) diagnostics.push(`${key} field \"${path}\" is never bound`);\n }\n }\n }\n\n return diagnostics;\n}\n","/**\n * 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 {\n Node,\n type ArrayLiteralExpression,\n type Identifier,\n type ObjectLiteralExpression,\n} from 'ts-morph';\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 Node.isParenthesizedExpression(current) ||\n Node.isAsExpression(current) ||\n Node.isSatisfiesExpression(current) ||\n Node.isNonNullExpression(current) ||\n Node.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 Node.isImportSpecifier(declaration) ||\n Node.isImportClause(declaration) ||\n Node.isNamespaceImport(declaration) ||\n Node.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 (Node.isVariableDeclaration(declaration) || Node.isPropertyAssignment(declaration)) {\n return declaration.getInitializer();\n }\n if (Node.isExportAssignment(declaration)) return declaration.getExpression();\n if (Node.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 (Node.isPropertyAssignment(property)) return property.getInitializer();\n if (Node.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 (Node.isObjectLiteralExpression(target)) return target;\n // `buildConfig({...})`, `defineConfig({...})`: the literal is the first argument.\n if (Node.isCallExpression(target)) return resolveToObjectLiteral(target.getArguments()[0], seen);\n if (Node.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 (Node.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 (Node.isArrayLiteralExpression(target)) return target;\n if (Node.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 (Node.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 (!Node.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 (Node.isStringLiteral(target) || Node.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 (Node.isTrueLiteral(target)) return true;\n if (Node.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 (Node.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) => Node.isStringLiteral(element))\n .map((element) => element.getLiteralValue());\n}\n","/**\n * Field-level extraction: one Payload field literal → an `ExtractedField`,\n * recursing into groups, arrays, tabs and blocks.\n */\nimport { Node, type ArrayLiteralExpression, type 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 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 (Node.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 { Node, Project, SyntaxKind, type ObjectLiteralExpression, type 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 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\nfunction declaredValue(declaration: Node): Node | undefined {\n if (Node.isExportAssignment(declaration)) return declaration.getExpression();\n if (Node.isVariableDeclaration(declaration)) return declaration.getInitializer();\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(SyntaxKind.CallExpression)) {\n const callee = call.getExpression();\n if (!Node.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\nexport function extractSchema(options: ExtractSchemaOptions): ExtractedSchema {\n const project =\n options.project ??\n new 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 * 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 interface GenerateTypesOptions\n extends Pick<ExtractSchemaOptions, 'configPath' | 'project' | 'tsConfigFilePath'>, EmitOptions {\n /** Where to write the generated code; `code` is returned either way. */\n readonly outFile?: string;\n /** Resolves relative paths. Defaults to `process.cwd()`. */\n readonly cwd?: string;\n /** Where to write the preview inventory as JSON: every path a binding may address. */\n readonly inventoryFile?: string;\n}\n\nexport interface GenerateTypesResult {\n readonly code: string;\n /** Extraction diagnostics, plus a note when nothing was written. */\n readonly diagnostics: readonly string[];\n readonly schema: ExtractedSchema;\n /** The types file actually written; absent when writing was refused. */\n readonly outFile?: string;\n /** Always produced; written to disk only when `inventoryFile` is set. */\n readonly inventory: PreviewInventory;\n readonly inventoryFile?: string;\n}\n\nasync function writeOut(path: string, content: string): Promise<void> {\n await mkdir(dirname(path), { recursive: true });\n await writeFile(path, content, 'utf8');\n}\n\n/** Parse the config and write the types, never writing an empty schema over a consumer's file. */\nexport async function generateTypes(options: GenerateTypesOptions): Promise<GenerateTypesResult> {\n const cwd = options.cwd ?? process.cwd();\n const absolute = (path: string): string => (isAbsolute(path) ? path : resolve(cwd, path));\n const schema = extractSchema({\n configPath: absolute(options.configPath),\n ...(options.project !== undefined ? { project: options.project } : {}),\n ...(options.tsConfigFilePath !== undefined\n ? { tsConfigFilePath: options.tsConfigFilePath }\n : {}),\n });\n const code = emitTypes(schema, options);\n const inventory = buildPreviewInventory(schema);\n const diagnostics = [...schema.diagnostics];\n const outFile = options.outFile === undefined ? undefined : absolute(options.outFile);\n const inventoryFile =\n options.inventoryFile === undefined ? undefined : absolute(options.inventoryFile);\n const targets = [outFile, inventoryFile].filter((path): path is string => path !== undefined);\n const empty = schema.globals.length + schema.collections.length === 0;\n if (empty && targets.length > 0) {\n diagnostics.push(\n `Nothing written: the schema is empty (0 globals, 0 collections), so ${targets.join(' and ')} ` +\n 'were left as they are.',\n );\n } else {\n if (outFile !== undefined) await writeOut(outFile, code);\n // Stable key order and a trailing newline keep the inventory diffable.\n if (inventoryFile !== undefined) {\n await writeOut(inventoryFile, `${JSON.stringify(inventory, null, 2)}\\n`);\n }\n }\n return {\n code,\n diagnostics,\n schema,\n inventory,\n ...(!empty && outFile !== undefined ? { outFile } : {}),\n ...(!empty && inventoryFile !== undefined ? { inventoryFile } : {}),\n };\n}\n\nexport { buildPreviewInventory, checkPreviewBindings } from './inventory';\nexport type {\n PreviewBindingReference,\n PreviewCoverageOptions,\n PreviewInventory,\n PreviewInventoryEntry,\n PreviewInventoryField,\n} from './inventory';\nexport { extractSchema } from './parser/extract-schema';\nexport { emitTypes } from './emit/emit-types';\nexport type { ExtractedSchema, ExtractedSlug, ExtractedField } from './parser/types';\n","/**\n * Astro integration: regenerate the types on startup and, during `astro dev`,\n * whenever anything next to the Payload config changes. Paths are relative to\n * Astro's root. Uses `fs.watch`; no watcher dependency.\n */\nimport { watch, type FSWatcher } from 'node:fs';\nimport { dirname, extname, resolve, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { generateTypes } from './index';\n\nexport interface AstroCodegenOptions {\n /** Path to `payload.config.ts` (absolute or relative to Astro's root). */\n readonly configPath: string;\n /** Output path for generated types (absolute or relative to Astro's root). */\n readonly outPath: string;\n /** Re-run when the config or anything beside it changes during `astro dev`. Default `true`. */\n readonly watch?: boolean;\n /** Only log errors. Default `false`. */\n readonly quiet?: boolean;\n}\n\ninterface AstroLogger {\n readonly info: (msg: string) => void;\n readonly warn: (msg: string) => void;\n readonly error: (msg: string) => void;\n}\n\ninterface AstroIntegration {\n readonly name: string;\n readonly hooks: Readonly<{\n readonly 'astro:config:setup'?: (params: {\n readonly command: string;\n readonly logger?: AstroLogger;\n readonly config?: { readonly root?: URL | string };\n }) => Promise<void> | void;\n readonly 'astro:server:start'?: () => void;\n readonly 'astro:build:start'?: () => Promise<void> | void;\n }>;\n}\n\nconst SOURCE_EXTENSIONS = new Set(['.ts', '.mts', '.cts', '.js', '.mjs', '.cjs', '.json']);\nconst DEBOUNCE_MS = 100;\n\nfunction rootOf(root: URL | string | undefined): string {\n if (root === undefined) return process.cwd();\n if (root instanceof URL) return fileURLToPath(root);\n return root.startsWith('file:') ? fileURLToPath(root) : root;\n}\n\nexport function livePreviewCodegen(options: AstroCodegenOptions): AstroIntegration {\n const watchEnabled = options.watch ?? true;\n let root = process.cwd();\n let watcher: FSWatcher | undefined;\n let timer: ReturnType<typeof setTimeout> | undefined;\n let active = false;\n let queued = false;\n\n async function regenerate(logger: AstroLogger | undefined): Promise<void> {\n if (active) {\n queued = true;\n return;\n }\n active = true;\n try {\n const result = await generateTypes({\n configPath: options.configPath,\n outFile: options.outPath,\n cwd: root,\n });\n if (result.outFile === undefined) {\n logger?.error(`pll-codegen: nothing written — ${result.diagnostics.join(' ')}`);\n } else if (options.quiet !== true) {\n logger?.info(\n `pll-codegen: ${String(result.schema.globals.length)} globals, ${String(result.schema.collections.length)} collections → ${options.outPath}`,\n );\n for (const diagnostic of result.diagnostics) logger?.warn(`pll-codegen: ${diagnostic}`);\n }\n } catch (error) {\n logger?.error(\n `pll-codegen failed: ${error instanceof Error ? error.message : String(error)}`,\n );\n } finally {\n active = false;\n if (queued) {\n queued = false;\n void regenerate(logger);\n }\n }\n }\n\n function startWatching(logger: AstroLogger | undefined): void {\n const directory = dirname(resolve(root, options.configPath));\n const outPath = resolve(root, options.outPath);\n try {\n // The output file may live under the watched directory; writing it must not retrigger.\n watcher = watch(directory, { recursive: true }, (_event, file) => {\n if (file === null) return;\n const changed = resolve(directory, file);\n if (changed === outPath || changed.includes(`${sep}node_modules${sep}`)) return;\n if (!SOURCE_EXTENSIONS.has(extname(changed))) return;\n clearTimeout(timer);\n timer = setTimeout(() => void regenerate(logger), DEBOUNCE_MS);\n });\n } catch (error) {\n logger?.warn(\n `pll-codegen watcher unavailable: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n\n return {\n name: 'payload-live-preview:codegen',\n hooks: {\n 'astro:config:setup': async ({ command, logger, config }) => {\n root = rootOf(config?.root);\n await regenerate(logger);\n if (watchEnabled && command === 'dev') startWatching(logger);\n },\n 'astro:server:start': () => undefined,\n 'astro:build:start': () => {\n clearTimeout(timer);\n watcher?.close();\n watcher = undefined;\n },\n },\n };\n}\n"],"mappings":"iQAEO,SAASA,EAAaC,GAC3B,OAAOA,EACJC,MAAM,YACNC,OAAOC,SACPC,IAAKC,GAASA,EAAKC,OAAO,GAAGC,cAAgBF,EAAKG,MAAM,IACxDC,KAAK,GACV,CCYA,IAIMC,EAAa,sBAOnB,SAASC,EAAeC,EAAgBC,GACtC,MAAO,GAAGD,IAASb,EAAac,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,OACpBzB,IAAK2B,GAAUpB,EAAeA,EAAeC,EAAQG,EAAMQ,MAAOQ,EAAMC,WACxE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,GAA4B,QAAZmB,GA1B1B,SAAuBX,GACrB,MAAMiB,EAAYnE,EAAQQ,EAAQsC,EAAM9L,EAAQgK,aAC1CoC,EAAU5C,EAAQsC,EAAM9L,EAAQoM,SACtC,IAEER,EAAUD,EAAMwB,EAAW,CAAElE,WAAW,GAAQ,CAACmE,EAAQC,KACvD,GAAa,OAATA,EAAe,OACnB,MAAMC,EAAU9D,EAAQ2D,EAAWE,GAC/BC,IAAYlB,GAAWkB,EAAQC,SAAS,GAAGC,gBAAkBA,MAC5DhC,EAAkB7J,IAAI8L,EAAQH,MACnCI,aAAa7B,GACbA,EAAQ8B,WAAW,KAAW1B,EAAWC,IA5D7B,OA8DhB,OAASG,GACPH,GAAQO,KACN,oCAAoCJ,aAAiBK,MAAQL,EAAMM,QAAU1J,OAAOoJ,KAExF,CACF,CAQ6CuB,CAAc1B,IAEvD,qBAAsB,OACtB,oBAAqB,KACnBwB,aAAa7B,GACbD,GAASiC,QACTjC,OAAU,IAIlB,Q","ignoreList":[]}
|
package/dist/codegen-cli.d.ts
CHANGED
|
@@ -1,19 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
/**
|
|
3
|
-
* `pll-codegen` CLI — runs the type generator from the command line.
|
|
4
|
-
*
|
|
5
|
-
* npx pll-codegen \
|
|
6
|
-
* --config backend/src/payload.config.ts \
|
|
7
|
-
* --out frontend/src/payload-types.ts
|
|
8
|
-
*
|
|
9
|
-
* Exit codes:
|
|
10
|
-
* 0 — generation succeeded (warnings ok)
|
|
11
|
-
* 1 — fatal error (config not found, parse error)
|
|
12
|
-
* 2 — generation produced zero globals AND zero collections —
|
|
13
|
-
* almost certainly a configuration mismatch
|
|
14
|
-
*
|
|
15
|
-
* @module @codegen/cli
|
|
16
|
-
*/
|
|
17
2
|
declare function run(argv: readonly string[]): Promise<number>;
|
|
3
|
+
/** Matches the entry's basename only, so a project path containing `pll-codegen` never runs this on import. */
|
|
4
|
+
declare function isCliInvocation(argv?: readonly (string | undefined)[]): boolean;
|
|
18
5
|
|
|
19
|
-
export { run };
|
|
6
|
+
export { isCliInvocation, run };
|
package/dist/codegen-cli.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{mkdir as e,writeFile as t}from"fs/promises";import{isAbsolute as i,resolve as n,dirname as r}from"path";import{Project as o,SyntaxKind as l,Node as s}from"ts-morph";var a=Object.defineProperty,u=(e,t)=>a(e,"name",{value:t,configurable:!0}),c={text:"string",textarea:"string",email:"string",richText:"unknown",number:"number",checkbox:"boolean",date:"string",code:"string",point:"unknown",ui:"unknown",radio:"string"};function f(e){let t=b(e,"type");if(void 0===t)return;let i=new Set(["tabs","row","collapsible"]),n=b(e,"name");if(void 0===n&&!i.has(t))return;let r={name:n??"__structural",required:v(e,"required")??!1,localized:v(e,"localized")??!1};switch(t){case"array":return{...r,kind:"array",fields:p(e)};case"blocks":return{...r,kind:"blocks",blocks:d(e)};case"group":return{...r,kind:"group",fields:p(e)};case"tabs":case"row":case"collapsible":{let t=g(e);return{...r,kind:"group",fields:t}}case"relationship":return{...r,kind:"relationship",target:h(e),hasMany:v(e,"hasMany")??!1};case"upload":return{...r,kind:"upload",target:y(e)??"media"};case"json":return{...r,kind:"json"};case"select":return{...r,kind:"select",options:m(e),hasMany:v(e,"hasMany")??!1};default:{let e=c[t]??"unknown";return{...r,kind:"scalar",typeRef:e}}}}function p(e){let t=x(e,"fields");if(!t)return[];let i=[];for(let e of t.getElements()){if(!s.isObjectLiteralExpression(e))continue;let t=f(e);t&&("group"===t.kind&&"__structural"===t.name?i.push(...t.fields):i.push(t))}return i}function g(e){let t=x(e,"tabs");if(t){let e=[];for(let i of t.getElements()){if(!s.isObjectLiteralExpression(i))continue;let t=b(i,"name"),n=p(i);void 0!==t?e.push({kind:"group",name:t,required:!1,localized:!1,fields:n}):e.push(...n)}return e}return p(e)}function d(e){let t=x(e,"blocks");if(!t)return[];let i=[];for(let e of t.getElements()){if(!s.isObjectLiteralExpression(e))continue;let t=b(e,"slug");void 0!==t&&i.push({slug:t,typeName:F(t),fields:p(e)})}return i}function h(e){let t=e.getProperty("relationTo");if(!t||!s.isPropertyAssignment(t))return"unknown";let i=t.getInitializer();return i&&s.isStringLiteral(i)?i.getLiteralValue():i&&s.isArrayLiteralExpression(i)?i.getElements().filter(s.isStringLiteral).map(e=>e.getLiteralValue()):"unknown"}function y(e){let t=h(e);return"string"==typeof t?t:t[0]}function m(e){let t=x(e,"options");if(!t)return[];let i=[];for(let e of t.getElements())if(s.isStringLiteral(e))i.push(e.getLiteralValue());else if(s.isObjectLiteralExpression(e)){let t=b(e,"value");void 0!==t&&i.push(t)}return i}function b(e,t){let i=e.getProperty(t);if(!i||!P(i))return;let n=i.getInitializer();return n&&s.isStringLiteral(n)||n&&s.isNoSubstitutionTemplateLiteral(n)?n.getLiteralValue():void 0}function v(e,t){let i=e.getProperty(t);if(!i||!P(i))return;let n=i.getInitializer();if(n){if(n.getKind()===l.TrueKeyword)return!0;if(n.getKind()===l.FalseKeyword)return!1}}function x(e,t){let i=e.getProperty(t);if(!i||!P(i))return;let n=i.getInitializer();return n&&s.isArrayLiteralExpression(n)?n:void 0}function P(e){return s.isPropertyAssignment(e)}function F(e){return e.split(/[-_\s]+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function k(e){let t=e.project??new o(void 0!==e.tsConfigFilePath?{tsConfigFilePath:e.tsConfigFilePath}:{skipAddingFilesFromTsConfig:!0}),i=t.addSourceFileAtPathIfExists(e.configPath);if(!i)return{globals:[],collections:[],diagnostics:[`Could not open ${e.configPath}`]};t.resolveSourceFileDependencies();let n=[],r=E(i,n);return r?{globals:L(r,"globals",n),collections:L(r,"collections",n),diagnostics:n}:{globals:[],collections:[],diagnostics:[...n,"Could not locate a buildConfig({...}) call or `export default {...}` in the config file."]}}function E(e,t){let i=e.getExportSymbols().find(e=>"default"===e.getName());if(!i)return void t.push("payload.config.ts has no default export.");let n=i.getDeclarations();for(let e of n){let t=w(e);if(t)return t}for(let t of e.getDescendantsOfKind(l.CallExpression)){let e=t.getExpression();if(s.isIdentifier(e)&&"buildConfig"===e.getText()){let e=t.getArguments()[0];if(e&&s.isObjectLiteralExpression(e))return e}}}function w(e){if(s.isExportAssignment(e))return $(e.getExpression());if(s.isVariableDeclaration(e)){let t=e.getInitializer();if(t)return $(t)}}function $(e){if(e){if(s.isObjectLiteralExpression(e))return e;if(s.isCallExpression(e)){let t=e.getArguments()[0];if(t&&s.isObjectLiteralExpression(t))return t}if(s.isAsExpression(e)||s.isSatisfiesExpression(e))return $(e.getExpression());if(s.isIdentifier(e))return S(e)}}function S(e){for(let t of e.getDefinitionNodes()){let e=w(t);if(e)return e}}function L(e,t,i){let n=e.getProperty(t);if(!n)return[];if(!s.isPropertyAssignment(n))return[];let r=n.getInitializer();if(!r)return[];let o=T(r);return o?A(o,i):[]}function A(e,t){let i=[];for(let n of e.getElements()){if(s.isSpreadElement(n)){let e=T(n.getExpression());if(!e){t.push(`Could not resolve spread "${n.getText().slice(0,80)}" to an array literal.`);continue}i.push(...A(e,t));continue}let e=j(n);if(!e){t.push(`Could not resolve config entry "${n.getText().slice(0,80)}" to an object literal.`);continue}let r=N(e,"slug");void 0!==r?i.push({slug:r,typeName:F(r),fields:C(e)}):t.push("Skipping a config entry — no string `slug` field found.")}return i}function C(e){let t=e.getProperty("fields");if(!t||!s.isPropertyAssignment(t))return[];let i=t.getInitializer();if(!i||!s.isArrayLiteralExpression(i))return[];let n=[];for(let e of i.getElements()){if(s.isSpreadElement(e)){let t=T(e.getExpression());if(!t)continue;for(let e of t.getElements()){let t=j(e);if(!t)continue;let i=f(t);i&&("group"===i.kind&&"__structural"===i.name?n.push(...i.fields):n.push(i))}continue}let t=j(e);if(!t)continue;let i=f(t);i&&("group"===i.kind&&"__structural"===i.name?n.push(...i.fields):n.push(i))}return n}function j(e){if(s.isObjectLiteralExpression(e))return e;if(s.isIdentifier(e))return S(e);if(s.isAsExpression(e)||s.isSatisfiesExpression(e))return j(e.getExpression());if(s.isCallExpression(e)){let t=e.getArguments()[0];if(t)return j(t)}}function T(e){if(s.isArrayLiteralExpression(e))return e;if(s.isAsExpression(e)||s.isSatisfiesExpression(e))return T(e.getExpression());if(s.isIdentifier(e))for(let t of e.getDefinitionNodes())if(s.isVariableDeclaration(t)){let e=t.getInitializer();if(e){let t=T(e);if(t)return t}}}function N(e,t){let i=e.getProperty(t);if(!i||!s.isPropertyAssignment(i))return;let n=i.getInitializer();return n&&s.isStringLiteral(n)?n.getLiteralValue():void 0}function I(e,t={}){let i=[];i.push(t.header??"// Auto-generated by payload-live-preview/codegen.\n// Do not edit by hand — run `pll-codegen` to regenerate.\n/* eslint-disable */"),i.push(""),i.push('import type { PayloadMedia, PayloadRelationship } from "payload-live-preview";'),i.push("");let n=new Set;for(let r of[...e.globals,...e.collections])q(r,i,n,t),i.push("");if(e.globals.length>0){i.push("export type PayloadGlobals = {");for(let t of e.globals)i.push(` '${t.slug}': ${t.typeName};`);i.push("};"),i.push("")}if(e.collections.length>0){i.push("export type PayloadCollections = {");for(let t of e.collections)i.push(` '${t.slug}': ${t.typeName};`);i.push("};"),i.push("")}let r=[];return e.globals.length>0&&r.push("keyof PayloadGlobals"),e.collections.length>0&&r.push("keyof PayloadCollections"),r.length>0&&(i.push(`export type PayloadSlug = ${r.join(" | ")};`),i.push("")),i.join("\n").replace(/\n{3,}/g,"\n\n")}function q(e,t,i,n){z(e.typeName,e.fields,t,i,n),t.push(`export interface ${e.typeName} {`);for(let i of e.fields)_(i,e.typeName,t,n);t.push("}")}function z(e,t,i,n,r){for(let o of t){let t=D(e,o.name);if("array"===o.kind||"group"===o.kind){if(n.has(t))continue;n.add(t),z(t,o.fields,i,n,r),i.push(`export interface ${t} {`);for(let e of o.fields)_(e,t,i,r);i.push("}"),i.push("")}else if("blocks"===o.kind)for(let e of o.blocks){let o=D(t,e.typeName);n.has(o)||(n.add(o),z(o,e.fields,i,n,r),O(o,e,i,r))}}}function O(e,t,i,n){i.push(`export interface ${e} {`),i.push(` blockType: '${t.slug}';`);for(let r of t.fields)_(r,e,i,n);i.push("}"),i.push("")}function _(e,t,i,n){n.markLocalizedAsDeprecated&&e.localized&&i.push(" /** @localized */");let r=e.required?"":"?";i.push(` ${e.name}${r}: ${M(e,t)};`)}function M(e,t){switch(e.kind){case"scalar":return e.typeRef;case"array":return`${D(t,e.name)}[]`;case"blocks":return 0===e.blocks.length?"unknown[]":`(${e.blocks.map(i=>D(D(t,e.name),i.typeName)).join(" | ")})[]`;case"group":return D(t,e.name);case"relationship":{let t=`PayloadRelationship<${Array.isArray(e.target)?e.target.map(e=>`'${e}'`).join(" | "):`'${e.target}'`}>`;return e.hasMany?`${t}[]`:t}case"upload":return"PayloadMedia";case"json":return"unknown";case"select":{if(0===e.options.length)return e.hasMany?"string[]":"string";let t=e.options.map(e=>`'${e}'`).join(" | ");return e.hasMany?`(${t})[]`:t}}}function D(e,t){return`${e}${F(t)}`}function V(e,t,i){for(let n of e){if("group"===n.kind&&"__structural"===n.name){V(n.fields,t,i);continue}let e=""===t?n.name:`${t}.${n.name}`;if(i.push({path:e,kind:n.kind,localized:n.localized,required:n.required}),"group"===n.kind)V(n.fields,e,i);else if("array"===n.kind)V(n.fields,`${e}.*`,i);else if("blocks"===n.kind)for(let t of n.blocks)V(t.fields,`${e}.*.${t.slug}`,i)}}function R(e){let t=[];return V(e.fields,"",t),{slug:e.slug,typeName:e.typeName,fields:t}}function K(e){return{globals:e.globals.map(R),collections:e.collections.map(R)}}async function B(o){let l=o.cwd??process.cwd(),s=k({configPath:i(o.configPath)?o.configPath:n(l,o.configPath),...void 0!==o.project?{project:o.project}:{},...void 0!==o.tsConfigFilePath?{tsConfigFilePath:o.tsConfigFilePath}:{}}),a=I(s,o),u=K(s),c={code:a,diagnostics:s.diagnostics,schema:s,inventory:u,...void 0!==o.outFile?{outFile:i(o.outFile)?o.outFile:n(l,o.outFile)}:{},...void 0!==o.inventoryFile?{inventoryFile:i(o.inventoryFile)?o.inventoryFile:n(l,o.inventoryFile)}:{}};return c.outFile&&(await e(r(c.outFile),{recursive:!0}),await t(c.outFile,a,"utf8")),c.inventoryFile&&(await e(r(c.inventoryFile),{recursive:!0}),await t(c.inventoryFile,`${JSON.stringify(u,null,2)}\n`,"utf8")),c}function W(e){let t={configPath:void 0,outFile:void 0,inventoryFile:void 0,tsConfigFilePath:void 0,showHelp:!1,quiet:!1};for(let i=0;i<e.length;i+=1){let n=e[i];"-h"!==n&&"--help"!==n?"-q"!==n&&"--quiet"!==n?"--config"!==n&&"-c"!==n?"--out"!==n&&"-o"!==n?"--inventory"!==n?"--tsconfig"!==n?n?.startsWith("--config=")?t.configPath=n.slice(9):n?.startsWith("--out=")?t.outFile=n.slice(6):n?.startsWith("--inventory=")?t.inventoryFile=n.slice(12):n?.startsWith("--tsconfig=")&&(t.tsConfigFilePath=n.slice(11)):(t.tsConfigFilePath=e[i+1],i+=1):(t.inventoryFile=e[i+1],i+=1):(t.outFile=e[i+1],i+=1):(t.configPath=e[i+1],i+=1):t.quiet=!0:t.showHelp=!0}return t}async function H(e){let t=W(e);if(t.showHelp)return process.stdout.write("pll-codegen — generate TypeScript types from a Payload config\n\nUsage:\n pll-codegen --config <path> --out <path> [--inventory <path>] [--quiet]\n\nOptions:\n -c, --config <path> Path to payload.config.ts (required)\n -o, --out <path> Output file for generated types (required)\n --tsconfig <path> Use this tsconfig for cross-file import resolution\n -q, --quiet Suppress non-error logging\n -h, --help Show this help\n\nExamples:\n pll-codegen --config backend/src/payload.config.ts --out frontend/src/payload-types.ts\n pll-codegen -c ./payload.config.ts -o ./generated.ts\n"),0;if(!t.configPath||!t.outFile)return process.stderr.write("pll-codegen: --config and --out are required. Try `pll-codegen --help`.\n"),1;try{let e=await B({configPath:t.configPath,outFile:t.outFile,...void 0!==t.inventoryFile?{inventoryFile:t.inventoryFile}:{},...void 0!==t.tsConfigFilePath?{tsConfigFilePath:t.tsConfigFilePath}:{}}),i=e.schema.globals.length+e.schema.collections.length;if(!t.quiet){if(process.stdout.write(`pll-codegen: wrote ${e.outFile} (${e.schema.globals.length} globals, ${e.schema.collections.length} collections)\n`),void 0!==e.inventoryFile){let t=[...e.inventory.globals,...e.inventory.collections].reduce((e,t)=>e+t.fields.length,0);process.stdout.write(`pll-codegen: wrote ${e.inventoryFile} (${String(t)} addressable fields)\n`)}for(let t of e.diagnostics)process.stderr.write(` warning: ${t}\n`)}return 0===i?(process.stderr.write("pll-codegen: no globals or collections found — check that the config path is correct.\n"),2):0}catch(e){let t=e instanceof Error?e.message:String(e);return process.stderr.write(`pll-codegen: ${t}\n`),1}}function U(){if(typeof process>"u")return!1;let e=process.argv[1];return!!e&&(e.includes("pll-codegen")||e.includes("codegen-cli"))}u(f,"extractField"),u(p,"extractNestedFields"),u(g,"extractNestedFieldsFromStructural"),u(d,"extractBlocks"),u(h,"readRelationTarget"),u(y,"readRelationTargetSingle"),u(m,"readSelectOptions"),u(b,"readStringProperty"),u(v,"readBooleanProperty"),u(x,"readArrayProperty"),u(P,"isPropertyAssignment"),u(F,"toPascalCase"),u(k,"extractSchema"),u(E,"findConfigLiteral"),u(w,"unwrapToObjectLiteral"),u($,"unwrapExpression"),u(S,"resolveIdentifierToObjectLiteral"),u(L,"extractSlugList"),u(A,"extractEntries"),u(C,"extractFieldList"),u(j,"resolveToObjectLiteral"),u(T,"resolveToArrayLiteral"),u(N,"readStringProperty"),u(I,"emitTypes"),u(q,"emitSlug"),u(z,"emitAuxiliaries"),u(O,"emitBlockInterface"),u(_,"emitFieldMember"),u(M,"renderFieldType"),u(D,"nestedTypeName"),u(V,"collect"),u(R,"entry"),u(K,"buildPreviewInventory"),u(B,"generateTypes"),u(W,"parseArgs"),u(H,"run"),u(U,"isCliInvocation"),U()&&H(process.argv.slice(2)).then(e=>{process.exit(e)});export{H as run};
|
|
2
|
+
import{mkdir as e,writeFile as t}from"fs/promises";import{isAbsolute as n,resolve as o,dirname as i}from"path";import{Project as s,SyntaxKind as r,Node as a}from"ts-morph";function l(e){return e.split(/[-_\s]+/u).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}var c=/^[A-Za-z_$][\w$]*$/u;function u(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,c.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`${u(t,e.name)}[]`;case"blocks":return 0===e.blocks.length?"unknown[]":`(${e.blocks.map(n=>u(u(t,e.name),n.typeName)).join(" | ")})[]`;case"group":return u(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 f(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 p(e,t,n,o,i){for(const s of t){const t=u(e,s.name);if("array"===s.kind||"group"===s.kind){if(o.has(t))continue;o.add(t),p(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=u(t,e.typeName);o.has(s)||(o.add(s),p(s,e.fields,n,o,i),f(s,e,n,i))}}}function g(e,t,n,o){p(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 h(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,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 v(e){const t=[];return y(e.fields,"",t),{slug:e.slug,typeName:e.typeName,fields:t}}function m(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 b(e){let t=e;for(;a.isParenthesizedExpression(t)||a.isAsExpression(t)||a.isSatisfiesExpression(t)||a.isNonNullExpression(t)||a.isTypeAssertion(t);)t=t.getExpression();return t}function $(e){if(!(a.isImportSpecifier(e)||a.isImportClause(e)||a.isNamespaceImport(e)||a.isExportSpecifier(e)))return[e];const t=e.getSymbol()?.getAliasedSymbol();return t?.getDeclarations()??[e]}function k(e){const t=e.getDefinitionNodes();return(t.length>0?t:e.getSymbol()?.getDeclarations()??[]).flatMap($)}function w(e){return a.isVariableDeclaration(e)||a.isPropertyAssignment(e)?e.getInitializer():a.isExportAssignment(e)?e.getExpression():a.isShorthandPropertyAssignment(e)?e.getNameNode():void 0}function P(e,t){const n=e.getProperty(t);if(void 0!==n)return a.isPropertyAssignment(n)?n.getInitializer():a.isShorthandPropertyAssignment(n)?n.getNameNode():void 0}function x(e,t){return void 0!==e.getProperty(t)}function F(e,t=/* @__PURE__ */new Set){if(void 0===e||t.has(e))return;t.add(e);const n=b(e);if(a.isObjectLiteralExpression(n))return n;if(a.isCallExpression(n))return F(n.getArguments()[0],t);if(a.isIdentifier(n))for(const e of k(n)){const n=F(w(e),t);if(void 0!==n)return n}if(a.isPropertyAccessExpression(n)){const e=F(n.getExpression(),t);if(void 0!==e)return F(P(e,n.getName()),t)}}function S(e,t=/* @__PURE__ */new Set){if(void 0===e||t.has(e))return;t.add(e);const n=b(e);if(a.isArrayLiteralExpression(n))return n;if(a.isIdentifier(n))for(const e of k(n)){const n=S(w(e),t);if(void 0!==n)return n}if(a.isPropertyAccessExpression(n)){const e=F(n.getExpression(),t);if(void 0!==e)return S(P(e,n.getName()),t)}}function E(e,t){const n=[];for(const o of e.getElements()){if(!a.isSpreadElement(o)){n.push(o);continue}const e=S(o.getExpression());void 0!==e?n.push(...E(e,t)):m(t,o,"could not resolve the spread to an array literal, so its entries are missing")}return n}function N(e,t){const n=P(e,t);if(void 0===n)return;const o=b(n);return a.isStringLiteral(o)||a.isNoSubstitutionTemplateLiteral(o)?o.getLiteralValue():void 0}function C(e,t){const n=P(e,t);if(void 0===n)return;const o=b(n);return!!a.isTrueLiteral(o)||!a.isFalseLiteral(o)&&void 0}function A(e,t){return S(P(e,t))}function j(e){const t=P(e,"relationTo");if(void 0===t)return"unknown";const n=b(t);if(a.isStringLiteral(n))return n.getLiteralValue();const o=S(n);return void 0===o?"unknown":o.getElements().map(b).filter(e=>a.isStringLiteral(e)).map(e=>e.getLiteralValue())}var q="__structural",L=/* @__PURE__ */new Set(["tabs","row","collapsible"]),M={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 D(e,t){const n=[];for(const o of E(e,t)){const e=F(o);if(void 0===e){m(t,o,"could not resolve the field to an object literal");continue}const i=_(e,t);void 0!==i&&("group"===i.kind&&i.name===q?n.push(...i.fields):n.push(i))}return n}function T(e,t){const n=A(e,"fields");return void 0!==n?D(n,t):(m(t,e,x(e,"fields")?"its `fields` could not be resolved to an array literal":"it has no `fields`"),[])}function I(e,t){const n=A(e,"tabs");if(void 0===n)return m(t,e,"its `tabs` could not be resolved to an array literal"),[];const o=[];for(const e of E(n,t)){const n=F(e);if(void 0===n){m(t,e,"could not resolve the tab to an object literal");continue}const i=N(n,"name"),s=T(n,t);void 0===i?o.push(...s):o.push({kind:"group",name:i,required:!1,localized:!1,fields:s})}return o}function O(e,t){const n=A(e,"blocks");if(void 0===n)return m(t,e,"its `blocks` could not be resolved to an array literal"),[];const o=[];for(const e of E(n,t)){const n=F(e);if(void 0===n){m(t,e,"could not resolve the block to an object literal");continue}const i=N(n,"slug");void 0!==i?o.push({slug:i,typeName:l(i),fields:T(n,t)}):m(t,e,"a block needs a string `slug`")}return o}function V(e,t){const n=A(e,"options");if(void 0===n)return m(t,e,"its `options` could not be resolved to an array literal"),[];const o=[];for(const e of E(n,t)){if(a.isStringLiteral(e)){o.push(e.getLiteralValue());continue}const n=F(e),i=void 0===n?void 0:N(n,"value");void 0===i?m(t,e,"an option needs a string or a `value`"):o.push(i)}return o}function _(e,t){const n=N(e,"type");if(void 0===n)return void m(t,e,"it has no string `type`");if("ui"===n)return;const o=N(e,"name");if(void 0===o&&!L.has(n))return void m(t,e,`a ${n} field needs a string \`name\``);const i={name:o??q,required:C(e,"required")??!1,localized:C(e,"localized")??!1},s=C(e,"hasMany")??!1;switch(n){case"array":return{...i,kind:"array",fields:T(e,t)};case"group":case"row":case"collapsible":return{...i,kind:"group",fields:T(e,t)};case"tabs":return{...i,kind:"group",fields:I(e,t)};case"blocks":return{...i,kind:"blocks",blocks:O(e,t)};case"relationship":return{...i,kind:"relationship",target:j(e),hasMany:s};case"upload":{const t=j(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:V(e,t),hasMany:"select"===n&&s};default:return{...i,kind:"scalar",typeRef:M[n]??"unknown",hasMany:z.has(n)&&s}}}function R(e){return a.isExportAssignment(e)?e.getExpression():a.isVariableDeclaration(e)?e.getInitializer():void 0}function W(e,t,n){const o=P(e,t);if(void 0===o)return[];const i=S(o);if(void 0===i)return m(n,o,`could not resolve \`${t}\` to an array literal`),[];const s=[];for(const e of E(i,n)){const t=F(e);if(void 0===t){m(n,e,"could not resolve the config entry to an object literal");continue}const o=N(t,"slug");if(void 0===o){m(n,e,"the config entry has no string `slug`");continue}const i=A(t,"fields");void 0===i&&m(n,t,x(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?[]:D(i,n)})}return s}async function H(n,o){await e(i(n),{recursive:!0}),await t(n,o,"utf8")}async function U(e){const t=e.cwd??process.cwd(),i=e=>n(e)?e:o(t,e),l=function(e){const t=e.project??new s(void 0!==e.tsConfigFilePath?{tsConfigFilePath:e.tsConfigFilePath}:{skipAddingFilesFromTsConfig:!0}),n=t.addSourceFileAtPathIfExists(e.configPath);if(void 0===n)return{globals:[],collections:[],diagnostics:[`Could not open ${e.configPath}`]};t.resolveSourceFileDependencies();const o={diagnostics:[]},i=function(e,t){const n=e.getDefaultExportSymbol();if(void 0!==n){for(const e of n.getDeclarations()){const t=F(R(e));if(void 0!==t)return t}for(const t of e.getDescendantsOfKind(r.CallExpression)){const e=t.getExpression();if(!a.isIdentifier(e)||"buildConfig"!==e.getText())continue;const n=F(t.getArguments()[0]);if(void 0!==n)return n}}else t.diagnostics.push("payload.config.ts has no default export.")}(n,o);return void 0===i?{globals:[],collections:[],diagnostics:[...o.diagnostics,"Could not locate a buildConfig({...}) call or `export default {...}` in the config file."]}:{globals:W(i,"globals",o),collections:W(i,"collections",o),diagnostics:o.diagnostics}}({configPath:i(e.configPath),...void 0!==e.project?{project:e.project}:{},...void 0!==e.tsConfigFilePath?{tsConfigFilePath:e.tsConfigFilePath}:{}}),c=function(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("");h("PayloadGlobals",e.globals,n),h("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")}(l,e),u=function(e){return{globals:e.globals.map(v),collections:e.collections.map(v)}}(l),d=[...l.diagnostics],f=void 0===e.outFile?void 0:i(e.outFile),p=void 0===e.inventoryFile?void 0:i(e.inventoryFile),y=[f,p].filter(e=>void 0!==e),m=l.globals.length+l.collections.length===0;return m&&y.length>0?d.push(`Nothing written: the schema is empty (0 globals, 0 collections), so ${y.join(" and ")} were left as they are.`):(void 0!==f&&await H(f,c),void 0!==p&&await H(p,`${JSON.stringify(u,null,2)}\n`)),{code:c,diagnostics:d,schema:l,inventory:u,...m||void 0===f?{}:{outFile:f},...m||void 0===p?{}:{inventoryFile:p}}}async function B(e){const t=function(e){const t={configPath:void 0,outFile:void 0,inventoryFile:void 0,tsConfigFilePath:void 0,showHelp:!1,quiet:!1};for(let n=0;n<e.length;n+=1){const o=e[n];void 0!==o&&("-h"===o||"--help"===o?t.showHelp=!0:"-q"===o||"--quiet"===o?t.quiet=!0:"--config"===o||"-c"===o?(t.configPath=e[n+1],n+=1):"--out"===o||"-o"===o?(t.outFile=e[n+1],n+=1):"--inventory"===o?(t.inventoryFile=e[n+1],n+=1):"--tsconfig"===o?(t.tsConfigFilePath=e[n+1],n+=1):o.startsWith("--config=")?t.configPath=o.slice(9):o.startsWith("--out=")?t.outFile=o.slice(6):o.startsWith("--inventory=")?t.inventoryFile=o.slice(12):o.startsWith("--tsconfig=")&&(t.tsConfigFilePath=o.slice(11)))}return t}(e);if(t.showHelp)return process.stdout.write("pll-codegen — generate TypeScript types from a Payload config\n\nUsage:\n pll-codegen --config <path> --out <path> [--inventory <path>] [--quiet]\n\nOptions:\n -c, --config <path> Path to payload.config.ts (required)\n -o, --out <path> Output file for generated types (required)\n --inventory <path> Also write the preview inventory (JSON) here\n --tsconfig <path> Use this tsconfig for cross-file import resolution\n -q, --quiet Suppress non-error logging\n -h, --help Show this help\n\nExit codes:\n 0 types written (warnings, if any, on stderr)\n 1 fatal error\n 2 no globals or collections found; nothing was written\n\nExamples:\n pll-codegen --config backend/src/payload.config.ts --out frontend/src/payload-types.ts\n pll-codegen -c ./payload.config.ts -o ./generated.ts\n"),0;if(void 0===t.configPath||void 0===t.outFile)return process.stderr.write("pll-codegen: --config and --out are required. Try `pll-codegen --help`.\n"),1;try{const e=await U({configPath:t.configPath,outFile:t.outFile,...void 0!==t.inventoryFile?{inventoryFile:t.inventoryFile}:{},...void 0!==t.tsConfigFilePath?{tsConfigFilePath:t.tsConfigFilePath}:{}}),{globals:n,collections:o}=e.schema,i=n.length+o.length;if(t.quiet||void 0===e.outFile||process.stdout.write(`pll-codegen: wrote ${e.outFile} (${String(n.length)} globals, ${String(o.length)} collections)\n`),!t.quiet&&void 0!==e.inventoryFile){const t=[...e.inventory.globals,...e.inventory.collections].reduce((e,t)=>e+t.fields.length,0);process.stdout.write(`pll-codegen: wrote ${e.inventoryFile} (${String(t)} addressable fields)\n`)}if(!t.quiet||0===i)for(const t of e.diagnostics)process.stderr.write(` warning: ${t}\n`);return 0===i?(process.stderr.write("pll-codegen: no globals or collections found; nothing was written. Check that the config path is correct.\n"),2):0}catch(e){return process.stderr.write(`pll-codegen: ${e instanceof Error?e.message:String(e)}\n`),1}}function G(e=process.argv){if("undefined"==typeof process)return!1;const t=e[1];if(void 0===t||""===t)return!1;const n=t.split(/[\\/]/u).pop()??"";return"pll-codegen"===n||"pll-codegen.cmd"===n||n.startsWith("codegen-cli")}G()&&B(process.argv.slice(2)).then(e=>{process.exit(e)});export{G as isCliInvocation,B as run};
|
|
3
3
|
//# sourceMappingURL=codegen-cli.js.map
|