payload-live-preview 2.2.2 → 2.3.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.
Files changed (100) hide show
  1. package/README.md +20 -17
  2. package/dist/adapters/astro/PreviewBoundary.astro +17 -4
  3. package/dist/adapters/astro/RichText.astro +13 -2
  4. package/dist/adapters/astro/index.d.ts +7 -7
  5. package/dist/adapters/astro/index.js +1 -1
  6. package/dist/adapters/astro/index.js.map +1 -1
  7. package/dist/adapters/astro/middleware-entry.d.ts +3 -3
  8. package/dist/adapters/astro/middleware-entry.js +1 -1
  9. package/dist/adapters/astro/middleware-entry.js.map +1 -1
  10. package/dist/adapters/nextjs/index.d.ts +2 -2
  11. package/dist/adapters/nextjs/index.js +1 -1
  12. package/dist/adapters/nextjs/index.js.map +1 -1
  13. package/dist/adapters/nuxt/index.d.ts +4 -4
  14. package/dist/adapters/nuxt/index.js +1 -1
  15. package/dist/adapters/nuxt/index.js.map +1 -1
  16. package/dist/adapters/nuxt/module.d.ts +1 -1
  17. package/dist/adapters/react/index.d.ts +2 -2
  18. package/dist/adapters/react/index.js +1 -1
  19. package/dist/adapters/react/index.js.map +1 -1
  20. package/dist/adapters/sveltekit/index.d.ts +5 -5
  21. package/dist/adapters/sveltekit/index.js +1 -1
  22. package/dist/adapters/sveltekit/index.js.map +1 -1
  23. package/dist/adapters/vue/index.d.ts +2 -2
  24. package/dist/adapters/vue/index.js +1 -1
  25. package/dist/adapters/vue/index.js.map +1 -1
  26. package/dist/client.cjs +1 -1
  27. package/dist/client.cjs.map +1 -1
  28. package/dist/client.d.cts +15 -3
  29. package/dist/client.d.ts +15 -3
  30. package/dist/client.js +1 -1
  31. package/dist/client.js.map +1 -1
  32. package/dist/codegen-astro.js +1 -1
  33. package/dist/codegen-astro.js.map +1 -1
  34. package/dist/codegen-cli.js +1 -1
  35. package/dist/codegen-cli.js.map +1 -1
  36. package/dist/codegen.cjs +1 -1
  37. package/dist/codegen.cjs.map +1 -1
  38. package/dist/codegen.js +1 -1
  39. package/dist/codegen.js.map +1 -1
  40. package/dist/core.cjs +1 -1
  41. package/dist/core.cjs.map +1 -1
  42. package/dist/core.d.cts +139 -4
  43. package/dist/core.d.ts +139 -4
  44. package/dist/core.js +1 -1
  45. package/dist/core.js.map +1 -1
  46. package/dist/doctor-cli.d.ts +1 -1
  47. package/dist/doctor-cli.js +1 -1
  48. package/dist/doctor-cli.js.map +1 -1
  49. package/dist/doctor.d.ts +2 -2
  50. package/dist/doctor.js +1 -1
  51. package/dist/doctor.js.map +1 -1
  52. package/dist/{document-session-Bkd181PV.d.ts → document-session-BuYuO3ae.d.ts} +27 -2
  53. package/dist/{fragment-endpoint-CLRpNQ3n.d.ts → fragment-endpoint-CQE_7MKi.d.ts} +1 -1
  54. package/dist/fragment.cjs +1 -1
  55. package/dist/fragment.cjs.map +1 -1
  56. package/dist/fragment.d.cts +6 -2
  57. package/dist/fragment.d.ts +6 -2
  58. package/dist/fragment.js +1 -1
  59. package/dist/fragment.js.map +1 -1
  60. package/dist/index.cjs +1 -1
  61. package/dist/index.cjs.map +1 -1
  62. package/dist/index.d.cts +73 -12
  63. package/dist/index.d.ts +73 -12
  64. package/dist/index.js +1 -1
  65. package/dist/index.js.map +1 -1
  66. package/dist/lean.cjs +1 -1
  67. package/dist/lean.cjs.map +1 -1
  68. package/dist/lean.js +1 -1
  69. package/dist/lean.js.map +1 -1
  70. package/dist/lexical.cjs +1 -1
  71. package/dist/lexical.cjs.map +1 -1
  72. package/dist/lexical.d.cts +16 -4
  73. package/dist/lexical.d.ts +16 -4
  74. package/dist/lexical.js +1 -1
  75. package/dist/lexical.js.map +1 -1
  76. package/dist/{locals-zz2gi9dj.d.ts → locals-CyzDKfKU.d.ts} +7 -1
  77. package/dist/{middleware-CI-UTf6R.d.ts → middleware-Dnt6u4nF.d.ts} +2 -2
  78. package/dist/{options-CnYybG51.d.ts → options-DTzhFVJ4.d.ts} +13 -1
  79. package/dist/plugin.cjs +1 -1
  80. package/dist/plugin.cjs.map +1 -1
  81. package/dist/plugin.d.cts +15 -9
  82. package/dist/plugin.d.ts +15 -9
  83. package/dist/plugin.js +1 -1
  84. package/dist/plugin.js.map +1 -1
  85. package/dist/plugins.cjs +1 -1
  86. package/dist/plugins.cjs.map +1 -1
  87. package/dist/plugins.d.cts +8 -2
  88. package/dist/plugins.d.ts +8 -2
  89. package/dist/plugins.js +1 -1
  90. package/dist/plugins.js.map +1 -1
  91. package/dist/{probe-D-IHg9dF.d.ts → probe-afwdYebU.d.ts} +6 -2
  92. package/dist/server.cjs +1 -1
  93. package/dist/server.cjs.map +1 -1
  94. package/dist/server.d.cts +19 -1
  95. package/dist/server.d.ts +19 -1
  96. package/dist/server.js +1 -1
  97. package/dist/server.js.map +1 -1
  98. package/dist/structural.d.cts +2 -0
  99. package/dist/structural.d.ts +2 -0
  100. package/package.json +2 -1
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { D as DoctorFetch } from './probe-D-IHg9dF.js';
2
+ import { D as DoctorFetch } from './probe-afwdYebU.js';
3
3
 
4
4
  /** @param fetchImpl Seam for tests; the bin shim never passes it. */
5
5
  declare function run(argv: readonly string[], fetchImpl?: DoctorFetch): Promise<number>;
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import{createRequire as e}from"module";import{relative as t,join as n,extname as r}from"path";import{writeFile as i,readFile as o,stat as s,readdir as a}from"fs/promises";var d,l,c="payload-live-preview";function u(){if(void 0===d)try{d=e(import.meta.url)("ts-morph")}catch(e){throw new Error("pll migrate needs ts-morph: npm install --save-dev ts-morph",{cause:e})}return d}function h(e,t){const n=u();return l??=new n.Project({useInMemoryFileSystem:!0,skipLoadingLibFiles:!0,skipFileDependencyResolution:!0,compilerOptions:{allowJs:!0,noLib:!0}}),l.createSourceFile(`/script.${t}`,e,{overwrite:!0})}function p(e){return e===c||e.startsWith(`${c}/`)}function f(e){const t=[];for(const n of e.getExportDeclarations()){const e=n.getModuleSpecifierValue();if(void 0!==e&&p(e))for(const r of n.getNamedExports())t.push({imported:r.getName(),specifier:e,importedNode:r.getNameNode(),alias:r.getAliasNode()?.getText(),line:r.getStartLineNumber()})}return t}function m(e){const{Node:t,SyntaxKind:n}=u(),r=[];for(const t of e.getImportDeclarations()){const e=t.getModuleSpecifierValue();if(p(e))for(const n of t.getNamedImports()){const i=n.getAliasNode(),o=i??n.getNameNode();r.push({imported:n.getName(),local:o.getText(),specifier:e,kind:"import",importedNode:n.getNameNode(),aliased:void 0!==i,symbol:o.getSymbol(),declaration:t})}}for(const i of e.getDescendantsOfKind(n.VariableDeclaration)){const e=g(i.getInitializer()),n=i.getNameNode();if(void 0!==e&&p(e)&&t.isObjectBindingPattern(n))for(const o of n.getElements()){const n=o.getNameNode();if(!t.isIdentifier(n))continue;const s=o.getPropertyNameNode();r.push({imported:void 0===s?n.getText():v(s),local:n.getText(),specifier:e,kind:"require",importedNode:s??n,aliased:void 0!==s,symbol:n.getSymbol(),declaration:i})}}return r}function g(e){const{Node:t,SyntaxKind:n}=u(),r=void 0!==e&&t.isAwaitExpression(e)?e.getExpression():e;if(void 0===r||!t.isCallExpression(r))return;const i=r.getExpression();if((!t.isIdentifier(i)||"require"!==i.getText())&&i.getKind()!==n.ImportKeyword)return;const[o]=r.getArguments();return void 0!==o&&t.isStringLiteral(o)?o.getLiteralText():void 0}function v(e){const{Node:t}=u();return t.isStringLiteral(e)||t.isNoSubstitutionTemplateLiteral(e)?e.getLiteralText():e.getText()}function w(e){const{Node:t}=u();if(t.isSpreadAssignment(e))return;const n=e.getNameNode();return t.isComputedPropertyName(n)?void 0:v(n)}function y(e,t){const{Node:n,SyntaxKind:r}=u(),i=t.symbol?.compilerSymbol;if(void 0===i)return[];const o=e.getProject().getTypeChecker(),s=[];for(const a of e.getDescendantsOfKind(r.Identifier)){if(a.getText()!==t.local||b(a,t.declaration))continue;const e=a.getParent();n.isShorthandPropertyAssignment(e)?o.getShorthandAssignmentValueSymbol(e)?.compilerSymbol===i&&s.push({node:a,kind:"shorthand"}):n.isExportSpecifier(e)?e.getNameNode()===a&&e.getLocalTargetSymbol()?.compilerSymbol===i&&s.push({node:a,kind:"export"}):a.getSymbol()?.compilerSymbol===i&&s.push({node:a,kind:"reference"})}return s}function b(e,t){return void 0!==e.getFirstAncestor(e=>e===t)}function $(e,t,n=[]){const{SyntaxKind:r}=u();for(const i of e.getDescendantsOfKind(r.Identifier)){if(i.getText()!==t)continue;const e=i.getParent();if(P(e,i)&&!n.some(t=>t===e||b(e,t)))return e}}function P(e,t){const{Node:n}=u();return n.isVariableDeclaration(e)||n.isBindingElement(e)||n.isFunctionDeclaration(e)||n.isClassDeclaration(e)||n.isParameterDeclaration(e)||n.isEnumDeclaration(e)?e.getNameNode()===t:n.isImportSpecifier(e)?(e.getAliasNode()??e.getNameNode())===t:n.isImportClause(e)?e.getDefaultImport()===t:!!n.isNamespaceImport(e)&&e.getNameNode()===t}function x(e,t){return{start:e.getStart(),end:e.getEnd(),text:t}}function S(e,t){const n=[...t].sort((e,t)=>t.start-e.start);let r=e,i=Number.POSITIVE_INFINITY;for(const e of n){if(e.end>i)throw new Error("overlapping codemod edits");r=`${r.slice(0,e.start)}${e.text}${r.slice(e.end)}`,i=e.start}return r}var k=new Set(["astro","nextjs","sveltekit","nuxt","nuxt-module"].map(e=>`payload-live-preview/${e}`));function L(e){const{Node:t}=u(),n=/* @__PURE__ */new Map,r=(e,t)=>{const r=n.get(e)??[];r.some(e=>e.outer===t.outer&&e.at===t.at&&e.kind===t.kind)||r.push(t),n.set(e,r)},i=(e,n)=>{r(e,{kind:n,outer:e}),e.getProperties().forEach((i,o)=>{if(!t.isSpreadAssignment(i))return;const s=O(i.getExpression());void 0!==s&&r(s,{kind:n,outer:e,at:o})})};for(const n of m(e)){const r=k.has(n.specifier)?"adapter":"runtime";for(const o of y(e,n)){const e=o.node.getParent();if("reference"===o.kind&&(t.isCallExpression(e)||t.isNewExpression(e))&&e.getExpression()===o.node)for(const n of e.getArguments()){const e=E(n),o=t.isObjectLiteralExpression(e)?e:O(e);void 0!==o&&i(o,r)}}}return n}function N(e,t){const{Node:n,SyntaxKind:r}=u(),i=new Set(m(e).map(e=>e.local));return e.getDescendantsOfKind(r.JsxAttribute).filter(e=>{const r=e.getParent().getParent();return(n.isJsxOpeningElement(r)||n.isJsxSelfClosingElement(r))&&i.has(r.getTagNameNode().getText())&&e.getNameNode().getText()===t})}function T(e,t){return e.getProperties().find(e=>w(e)===t)}function O(e){const{Node:t,VariableDeclarationKind:n}=u(),r=E(e);if(t.isIdentifier(r))for(const e of r.getSymbol()?.getDeclarations()??[]){if(!t.isVariableDeclaration(e))continue;if(e.getVariableStatement()?.getDeclarationKind()!==n.Const)continue;const r=e.getInitializer(),i=void 0===r?void 0:E(r);if(void 0!==i&&t.isObjectLiteralExpression(i))return i}}function E(e){const{Node:t}=u();let n=e;for(;t.isParenthesizedExpression(n)||t.isAsExpression(n)||t.isSatisfiesExpression(n)||t.isTypeAssertion(n);)n=n.getExpression();return n}var A="expand-defaults-v1",R="defaults",j=[["disableReferrerDetection",()=>"false"],["eventSourcePolicy",e=>`${e}any${e}`],["skipUnchanged",()=>"false"],["sanitizerPolicy",e=>`${e}compat${e}`]],I={adapter:[["strict",()=>"false"],["previewSignals",e=>`[${[`${e}query${e}`,`${e}fetch-dest${e}`,`${e}referer${e}`].join(", ")}]`],...j],runtime:j},C=new Set(I.adapter.map(([e])=>e)),U="write the rows `defaults: 'v1'` stands for by hand (docs/migration.md)",D={id:A,summary:"`defaults: 'v1'` → the 1.x rows as explicit options",ledgerEntry:21,notice:"The rows keep the 1.x values `defaults: 'v1'` gave; `pll doctor --v2` names each one to drop once the page is ready for 2.0's.",apply(e){const{Node:t}=u(),n=[],r=[];for(const[i,o]of L(e)){const e=T(i,R);if(void 0===e)continue;const s=e.getStartLineNumber(),a=e=>{r.push({codemod:A,line:s,reason:`${e}; ${U}`})},d=t.isPropertyAssignment(e)?e.getInitializer():void 0;if(void 0===d||!t.isStringLiteral(d)){a("`defaults` is not a literal");continue}if("v1"!==d.getLiteralText())continue;const l=q(i,e,o);void 0===l?n.push(F(i,e,o,d.getText().charAt(0))):a(l)}for(const t of N(e,R))r.push({codemod:A,line:t.getStartLineNumber(),reason:`a JSX attribute; ${U} as attributes`});return{edits:n,conflicts:r}}};function q(e,t,n){const{Node:r}=u();if(new Set(n.map(e=>e.kind)).size>1)return"the object is shared by an adapter and a client, which take different rows";const i=e.getProperties(),o=i.findIndex(e=>e===t);if(i.slice(0,o).some(e=>r.isSpreadAssignment(e)))return"a spread before `defaults` may set a row the expansion would override";for(const{outer:e,at:t}of n){if(void 0===t)continue;if(void 0!==T(e,R))return"a call that spreads it names its own defaults";const n=e=>r.isSpreadAssignment(e)||C.has(w(e)??"");if(e.getProperties().slice(0,t).some(n))return"a call sets a row before spreading the object, and the expansion would override it"}}function F(e,t,n,r){const{Node:i}=u(),o=n[0]?.kind??"runtime",s=new Set(e.getProperties().map(e=>w(e))),a=[e,...n.map(e=>e.outer)],d=e=>a.some(t=>void 0!==T(t,e)),l=new Set(n.map(e=>void 0===e.at?void 0:e.outer.getProperties()[e.at])),c=a.some(e=>e.getProperties().some(e=>i.isSpreadAssignment(e)&&!l.has(e))),h=I[o].filter(([e])=>!s.has(e)).map(([e,t])=>`${e}: ${t(r)}`);d("mergeDepth")||!d("serverURL")&&!c||h.push("mergeDepth: 1");const p=t.getSourceFile().getFullText();if(0===h.length){const n=e.getProperties().find(e=>e.getStart()>t.getStart());return{start:t.getStart(),end:n?.getStart()??t.getEnd(),text:""}}const f=p.lastIndexOf("\n",t.getStart())+1,m=p.slice(f,t.getStart()),g=/^\s*$/u.test(m)?`,\n${m}`:", ";return{start:t.getStart(),end:t.getEnd(),text:h.join(g)}}var z="move-fetch-preview-helpers",M=`${c}/server`,_={fetchPreviewDocument:"fetchDocument",fetchPreviewGlobal:"fetchGlobal"},V=/* @__PURE__ */new Set(["serverURL","apiRoute","depth"]),W=/* @__PURE__ */new Set(["draft","fetchFn"]),B=["authorization","locale","headers","signal","errorMode"],G={fetchPreviewDocument:["collection","where",...B],fetchPreviewGlobal:["global",...B]};function K(e,t){return{codemod:z,reason:t,line:e}}function J(e,t,n){const r=[],i=[],o=[],s=/* @__PURE__ */new Set;for(const e of t.getProperties()){const t=w(e);void 0!==t&&s.add(t),void 0!==t&&V.has(t)?r.push(e.getText()):void 0!==t&&W.has(t)?o.push(t):i.push(e.getText())}s.has("depth")||r.push("depth: 1 /* TODO(pll migrate): the 1.x default; match the runtime mergeDepth */"),s.has("authorization")||i.push("authorization: null /* TODO(pll migrate): pass the verdict from authorizePreviewRequest(); null reads the published document */");const a=G[n]??[],d=[...s].filter(e=>!V.has(e)&&!W.has(e)&&!a.includes(e)),l=e.getTypeArguments().map(e=>e.getText()),c=0===l.length?"":`<${l.join(", ")}>`,u=_[n]??n,h=`definePreview({ ${r.join(", ")} }).${u}${c}({ ${i.join(", ")} })`,p=0===o.length?"":`, and ${o.join("/")} was dropped`,f=e.getStartLineNumber(),m=K(f,`${n}() was rewritten onto definePreview().${u}(); it now returns a PreviewFetchResult (check ok/data) and needs a real authorization for drafts${p}`),g=[];return d.length>0&&g.push(K(f,`${n}() was passed ${d.map(e=>`\`${e}\``).join(", ")}, which .${u}() does not accept; it takes ${a.join(", ")}. The key was carried over unchanged and will not compile — place it by hand`)),{edit:{start:e.getStart(),end:e.getEnd(),text:h},done:m,advice:g}}function H(e,t,n){return`import { ${t.join(", ")} } from ${e}${n}${e};`}var Q={id:z,summary:"`fetchPreviewDocument`/`fetchPreviewGlobal` from the root → `definePreview().fetchDocument`/`.fetchGlobal` (payload-live-preview/server)",ledgerEntry:9,apply(e){const t=m(e).filter(e=>e.specifier===c&&e.imported in _),n=f(e).filter(e=>e.specifier===c&&e.imported in _);return 0===t.length&&0===n.length?{edits:[],conflicts:[]}:function(e,t,n){const{Node:r}=u(),i=n.map(e=>K(e.line,`${e.imported} is re-exported straight from the package; it became definePreview().${_[e.imported]??e.imported}() on ${M}, so rewrite the re-export and its importers by hand`)),o=[],s=[],a=[];for(const n of t)if("require"!==n.kind)for(const t of y(e,n)){const e=t.node.getStartLineNumber(),d=t.node.getParent();if("reference"!==t.kind||!r.isCallExpression(d)||d.getExpression()!==t.node){i.push(K(e,`${n.local} is used other than as a direct call; rewrite it onto definePreview() by hand`));continue}const[l]=d.getArguments();if(void 0===l||!r.isObjectLiteralExpression(l)||l.getProperties().some(e=>r.isSpreadAssignment(e))){i.push(K(e,`${n.imported}() options are not a plain object literal, so serverURL/depth cannot be split out; rewrite it onto definePreview() by hand`));continue}const c=J(d,l,n.imported);a.push(c.edit),o.push(c.done,...c.advice),s.push(...c.advice)}else i.push(K(n.declaration.getStartLineNumber(),`${n.imported} is bound with require(); rewrite it onto definePreview() from ${M} by hand`));const d=e.getImportDeclarations().filter(e=>e.getModuleSpecifierValue()===M),l=$(e,"definePreview",d);return void 0!==l&&i.push(K(l.getStartLineNumber(),`this module already binds a definePreview that is not ${M}'s; rename it, then move the fetch helpers by hand`)),i.length>0?{edits:[],conflicts:[...i,...s]}:(a.push(...function(e,t){const{Node:n}=u(),r=[],i=/* @__PURE__ */new Set;for(const e of t)n.isImportDeclaration(e.declaration)&&i.add(e.declaration);const o=e.getImportDeclarations().find(e=>e.getModuleSpecifierValue()===M&&!e.isTypeOnly()),s=!0===o?.getNamedImports().some(e=>"definePreview"===e.getName());let a;if(void 0!==o&&!s){const e=o.getModuleSpecifier().getQuoteKind(),t=[...o.getNamedImports().map(e=>e.getText()),"definePreview"],n=o.getDefaultImport()?.getText(),i=void 0===n?t.join(", "):`${n}, { ${t.join(", ")} }`,s=void 0===n?H(e,t,M):`import ${i} from ${e}${M}${e};`;r.push({start:o.getStart(),end:o.getEnd(),text:s})}for(const t of i){const n=t.getModuleSpecifier().getQuoteKind(),i=t.getNamedImports().filter(e=>!(e.getName()in _)).map(e=>e.getText()),s=t.getDefaultImport()?.getText(),d=[s,0===i.length?void 0:`{ ${i.join(", ")} }`].filter(e=>void 0!==e),l=t.isTypeOnly()?"type ":"",u=0===d.length?"":`import ${l}${d.join(", ")} from ${n}${c}${n};`;if(void 0===o&&void 0===a)a=H(n,["definePreview"],M),r.push({start:t.getStart(),end:t.getEnd(),text:""===u?a:`${u}\n${a}`});else{const n=t.getEnd(),i=""===u&&"\n"===e.getFullText()[n]?1:0;r.push({start:t.getStart(),end:n+i,text:u})}}return r}(e,t)),{edits:a,conflicts:o})}(e,t,n)}},X="rename-admin-origins-option",Y="hasPreviewIntent",Z="adminOrigins",ee="allowedOrigins",te=`if they carry \`${Z}\`, rename it to \`${ee}\``,ne={id:X,summary:"`hasPreviewIntent(request, { adminOrigins })` → `{ allowedOrigins }`",ledgerEntry:13,apply(e){const{Node:t}=u(),n=[],r=[],i=m(e).filter(e=>e.imported===Y);for(const o of i)for(const i of y(e,o)){const e=i.node.getParent();if("reference"!==i.kind||!t.isCallExpression(e))continue;if(e.getExpression()!==i.node)continue;const o=e.getArguments()[1];if(void 0===o)continue;const s=o.getStartLineNumber();if(!t.isObjectLiteralExpression(o)){r.push({codemod:X,line:s,reason:`${Y}() options are not a literal; ${te}`});continue}const a=o.getProperties(),d=a.map(e=>w(e));if(d.includes(Z)&&d.includes(ee))r.push({codemod:X,line:s,reason:`${Y}() is given both ${Z} and ${ee}; ${ee} wins, drop ${Z} by hand`});else for(const e of a)if(t.isSpreadAssignment(e))r.push({codemod:X,line:e.getStartLineNumber(),reason:`${Y}() spreads its options; ${te}`});else{if(w(e)!==Z)continue;t.isShorthandPropertyAssignment(e)?n.push(x(e,`${ee}: ${Z}`)):t.isPropertyAssignment(e)&&n.push(x(e.getNameNode(),ee))}}return{edits:n,conflicts:r}}},re="rename-bindings-authorized-option",ie="authorized",oe="authorization",se=`if they carry \`${ie}\`, rename it to \`${oe}\` and pass the verdict from authorizePreviewRequest()`,ae=`\`${oe}\` takes the context from authorizePreviewRequest(); the boolean 1.x accepted is not. The key was renamed and its value left as it stands — pass the verdict, or \`null\` for a public response`,de={id:re,summary:"`createPreviewBindings({ authorized })` → `{ authorization }`",ledgerEntry:7,apply(e){const{Node:t}=u(),n=[],r=[],i=m(e).filter(e=>"createPreviewBindings"===e.imported);for(const o of i)for(const i of y(e,o)){const e=i.node.getParent();if("reference"!==i.kind||!t.isCallExpression(e))continue;if(e.getExpression()!==i.node)continue;const[o]=e.getArguments();if(void 0===o)continue;const s=o.getStartLineNumber();if(t.isObjectLiteralExpression(o))for(const e of o.getProperties())if(t.isSpreadAssignment(e))r.push({codemod:re,line:e.getStartLineNumber(),reason:`createPreviewBindings() spreads its options; ${se}`});else{if(w(e)!==ie)continue;if(t.isShorthandPropertyAssignment(e))n.push(x(e,`${oe}: ${ie}`)),r.push({codemod:re,line:e.getStartLineNumber(),reason:ae});else if(t.isPropertyAssignment(e)){const i=e.getInitializer();if(void 0!==i&&t.isFalseLiteral(i)){n.push(x(e,`${oe}: null`));continue}n.push(x(e.getNameNode(),oe)),r.push({codemod:re,line:e.getStartLineNumber(),reason:ae})}}else r.push({codemod:re,line:s,reason:`createPreviewBindings() options are not a literal; ${se}`})}return{edits:n,conflicts:r}}},le="rename-is-preview-request",ce="isPreviewRequest",ue="hasPreviewIntent";function he(e,t){return{codemod:le,reason:t,line:e}}function pe(e){return e.aliased&&e.local===ue?x(e.importedNode.getParentOrThrow(),ue):x(e.importedNode,ue)}var fe={id:le,summary:"`isPreviewRequest()` → `hasPreviewIntent()` (same signature)",ledgerEntry:1,notice:"hasPreviewIntent() takes the options isPreviewRequest() took and, without `signals`, counts the same three: a preview query parameter, Sec-Fetch-Dest: iframe and an admin Referer. The 2.0 adapters count only the query; where a call should agree with them, pass { signals: ['query'] } (docs/migration.md).",apply(e){const t=m(e).filter(e=>e.imported===ce),n=f(e).filter(e=>e.imported===ce);return 0===t.length&&0===n.length?{edits:[],conflicts:[]}:function(e,t,n){const r=[],i=[];for(const e of t)void 0===e.alias?r.push(he(e.line,`${ce} is re-exported straight from the package under its old name; write export { ${ue} as ${ce} } from '${e.specifier}', or rename it and its importers by hand`)):e.alias===ue?i.push(x(e.importedNode.getParentOrThrow(),ue)):i.push(x(e.importedNode,ue));const o=$(n,ue,e.map(e=>e.declaration));void 0!==o&&r.push(he(o.getStartLineNumber(),`this module already binds ${ue}; rename it (or drop the wrapper and import the package's ${ue} directly), then rename ${ce} by hand`));for(const t of e)if(i.push(pe(t)),!t.aliased)for(const e of y(n,t))"reference"===e.kind?i.push(x(e.node,ue)):"shorthand"===e.kind?r.push(he(e.node.getStartLineNumber(),`{ ${ce} } keeps the old key for whoever reads it; write { ${ce}: ${ue} } or rename the key and its readers by hand`)):r.push(he(e.node.getStartLineNumber(),`${ce} is re-exported under its old name; rename the export and its importers, or write export { ${ue} as ${ce} }`));const s=function(e,t){const{Node:n,SyntaxKind:r}=u();return e.getDescendantsOfKind(r.Identifier).filter(e=>{const r=e.getParent();return e.getText()===t&&n.isPropertyAccessExpression(r)&&r.getNameNode()===e})}(n,ce).map(e=>he(e.getStartLineNumber(),`.${ce} is a member of this module's own object, not the package import, and was left alone; check that it does not wrap the removed API`));return r.length>0?{edits:[],conflicts:[...r,...s]}:{edits:i,conflicts:s}}(t,n,e)}},me="rename-on-unbound-change",ge="onUnboundChange",ve="onUnfaithfulPatch",we={route:"escalate",ignore:"ignore"},ye={id:me,summary:"`onUnboundChange: 'route'` → `onUnfaithfulPatch: 'escalate'`",ledgerEntry:19,apply(e){const{Node:t}=u(),n=[],r=[];for(const[i,o]of L(e)){const e=T(i,ge);if(void 0===e)continue;const s=e.getStartLineNumber();if([i,...o.map(e=>e.outer)].some(e=>void 0!==T(e,ve))){r.push({codemod:me,line:s,reason:`both ${ge} and ${ve} are given; ${ve} wins, drop ${ge} by hand`});continue}const a=t.isPropertyAssignment(e)?e.getInitializer():void 0,d=void 0!==a&&t.isStringLiteral(a)?a.getLiteralText():"",l=we[d];if(void 0===a||void 0===l){r.push({codemod:me,line:s,reason:`${ge} is not a literal 'route' or 'ignore'; rename it to ${ve} by hand ('route' is 'escalate')`});continue}const c=a.getText().charAt(0);n.push(x(e,`${ve}: ${c}${l}${c}`))}for(const t of N(e,ge))r.push({codemod:me,line:t.getStartLineNumber(),reason:`a JSX attribute; rename ${ge} to ${ve} by hand ('route' is 'escalate')`});return{edits:n,conflicts:r}}},be={".ts":"ts",".mts":"ts",".cts":"ts",".tsx":"tsx",".js":"js",".mjs":"js",".cjs":"js",".jsx":"jsx"},$e=/* @__PURE__ */new Set([".astro",".vue",".svelte"]),Pe=/^---\r?\n([\s\S]*?)\r?\n---/u,xe=/<script(?:\s[^>]*)?>([\s\S]*?)<\/script\b[^>]*>/giu,Se=/(?:\bfrom\s*|\bimport\s*\(?\s*|\brequire\s*\(\s*)['"]payload-live-preview(?:\/[^'"]*)?['"]/u,ke=[fe,ne,de,Q,ye,D],Le=ke;function Ne(e,t){let n=1;for(let r=0;r<t;r+=1)"\n"===e[r]&&(n+=1);return n}function Te(e,t,n){const r=e.split("\n"),i=t.split("\n");let o=0;for(;o<r.length&&o<i.length&&r[o]===i[o];)o+=1;let s=0;for(;s<r.length-o&&s<i.length-o&&r[r.length-1-s]===i[i.length-1-s];)s+=1;const a=r.slice(o,r.length-s),d=i.slice(o,i.length-s),l=[];for(let e=0;e<Math.max(a.length,d.length);e+=1){const t=a[e]??"",r=d[e]??"";t!==r&&l.push({line:n+o+e,before:t,after:r})}return l}function Oe(e,t={}){const n=void 0===t.only?ke:ke.filter(e=>t.only?.includes(e.id));if(0===n.length||!function(e){return Se.test(e)}(e))return{output:e,edits:[],conflicts:[]};const i=/* @__PURE__ */new Map,o=[];let s="",a=0;for(const d of function(e,t){const n=r(t).toLowerCase();if(!$e.has(n))return[{start:0,end:e.length,kind:be[n]??"ts"}];const i=[],o=".astro"===n?Pe.exec(e):null;if(void 0!==o?.[1]){const e=o.index+o[0].indexOf("\n")+1;i.push({start:e,end:e+o[1].length,kind:"ts"})}for(const t of e.matchAll(xe)){const e=t[1]??"";if(""===e.trim())continue;const n=t.index+t[0].lastIndexOf(e);i.push({start:n,end:n+e.length,kind:"ts"})}return i}(e,t.fileName??"source.ts")){s+=e.slice(a,d.start);const t=Ne(e,d.start);let r=e.slice(d.start,d.end);for(const e of n){const n=e.apply(h(r,d.kind));for(const e of n.conflicts)o.push(void 0===e.line?e:{...e,line:e.line+t-1});if(0===n.edits.length)continue;const s=S(r,n.edits),a=i.get(e.id)??[];a.push(...Te(r,s,t)),i.set(e.id,a),r=s}s+=r,a=d.end}return s+=e.slice(a),{output:s,edits:[...i].map(([e,t])=>({codemod:e,count:t.length,lines:t})),conflicts:o}}var Ee=/* @__PURE__ */new Set([".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".astro",".svelte",".vue"]),Ae=/\.d\.[cm]?ts$/u,Re=/* @__PURE__ */new Set(["node_modules","dist",".git",".astro",".svelte-kit",".next",".nuxt","coverage"]);function je(e){return Ee.has(r(e))&&!Ae.test(e)}async function Ie(e){const t=[];return(await s(e)).isDirectory()?await async function e(r){for(const i of await a(r,{withFileTypes:!0})){const o=n(r,i.name);i.isDirectory()?Re.has(i.name)||await e(o):je(i.name)&&t.push(o)}}(e):je(e)&&t.push(e),t.sort()}function Ce(e,n){const r=t(e,n);return 0===r.length?n:r}var Ue=`pll migrate — rewrite 1.x APIs to their 2.0 names and homes (ADR 0007)\n\nUsage:\n pll migrate <path> [--write] [--only <id,id>]\n\nWithout --write the run only reports what it would change. Codemods touch\nonly names bound from payload-live-preview; anything they cannot rewrite\nsafely is listed as needing manual attention. Requires ts-morph.\n\nOptions:\n --write Apply the changes (otherwise dry-run)\n --only <ids> Run only these codemods (comma-separated); an id not\n listed below runs nothing\n -h, --help Show this help\n\nCodemods, in the order they run:\n${Le.map(e=>` ${e.id}`).join("\n")}\n\nExit codes:\n 0 nothing needs a human (changes applied, or would be with --write)\n 1 usage error, unreadable path, or ts-morph is not installed\n 3 at least one file needs manual attention\n`;function De(e){return e.edits.map(e=>`${e.codemod}: ${String(e.count)} line(s)`).join(", ")}var qe={error:"ERROR",warning:"WARN ",info:"INFO "},Fe=Object.freeze({NoTrustedOrigin:"LP0101",ReferrerOnlyTrust:"LP0102",PluginIncompatible:"LP0103",ProfileFeatureOmitted:"LP0104",OrphanField:"LP0201",UnattributableUpdate:"LP0202",UnboundField:"LP0203",VisibilityGateDeferred:"LP0301",UnsafeAttributeWrite:"LP0401",TextTargetHasChildren:"LP0402",MissingArrayTemplate:"LP0403",StructuralItemUnkeyed:"LP0404",StructuralDuplicateKey:"LP0405",StructuralUnstableKeys:"LP0406",UnsupportedStrategy:"LP0407",UnknownValueFormat:"LP0408",SanitizerDroppedAttribute:"LP0409",UnrenderedBlockKept:"LP0410",UnfaithfulPatch:"LP0411",ServerFormatReplaced:"LP0412",UnrenderedBlockLost:"LP0413",MessageRejected:"LP0501",TokenRejected:"LP0502",ProtocolShapeUnknown:"LP0503",HandlerThrew:"LP0601",TransformThrew:"LP0602",RendererThrew:"LP0603",StartupFailed:"LP0605",ReadyFailed:"LP0606",HydrationWaitTimedOut:"LP0607",AuditRuntimeMissing:"LP0701",AuditNoFrameAncestors:"LP0702",AuditFrameOptionsBlocks:"LP0703",AuditBindingsExposed:"LP0704",AuditGateThresholdExceeded:"LP0705",AuditUnownedBindings:"LP0706",AuditNoBindings:"LP0707",AuditNotAPage:"LP0708",FragmentRequestFailed:"LP0801",FragmentResponseInvalid:"LP0802",FragmentUnauthorized:"LP0803",FragmentSuperseded:"LP0804",RouteRefreshLoop:"LP0805",FragmentStrategyUnavailable:"LP0806",UnboundChangeRefresh:"LP0807",EscalationUnavailable:"LP0808",IslandStartUnavailable:"LP0809",RouteRefreshUnconfirmed:"LP0810",V2ReadinessGap:"LP0709",RuntimeOnPublicPage:"LP0710"}),ze={http:"80",https:"443",ws:"80",wss:"443"},Me=/^([a-z][a-z0-9+.-]*):$/u,_e=/^(?:([a-z][a-z0-9+.-]*):\/\/)?(\*|(?:\*\.)?[a-z0-9-]+(?:\.[a-z0-9-]+)*\.?)(?::(\*|\d+))?(?:\/.*)?$/u;function Ve(e){return e.protocol.slice(0,-1).toLowerCase()}function We(e){return""===e.port?ze[Ve(e)]??"":e.port}function Be(e,t){return e===t||"http"===e&&"https"===t||"ws"===e&&"wss"===t}function Ge(e,t){if(e.hostname!==t.hostname)return!1;const n=Ve(e),r=Ve(t);return(n===r||"http"===r&&"https"===n)&&(We(e)===We(t)||""===e.port&&""===t.port)}function Ke(e,t,n){const r=Me.exec(e);if(void 0!==r?.[1])return Be(r[1],Ve(t));const i=_e.exec(e);if(null===i)return!1;const o=i[1],s=i[2]??"",a=i[3];return!!Be(o??Ve(n),Ve(t))&&!!function(e,t){if("*"===e)return!0;const n=e.replace(/\.$/u,""),r=t.replace(/\.$/u,"");return n.startsWith("*.")?r.endsWith(n.slice(1))&&r.length>n.length-1:n===r}(s,t.hostname)&&(void 0===a?""===t.port:"*"===a||a===We(t))}var Je=["allowedOrigins","serverURL","apiRoute","mergeDepth","debug","debounceMs","enableA11y","heartbeatMs","disableVisibilityGate","visibilityGateThreshold","intersectionRootMargin","disableReferrerDetection","disableLocalhostMatching","scopeBindingsByOwner","skipUnchanged","eventSourcePolicy","sanitizerPolicy","fragmentEndpoint","revealEditedField","routeStrategy","onUnboundChange","onUnfaithfulPatch","autoBind","hydration","defaults","softNavigationEvents","subfieldCoverage"],He=Object.freeze({disableReferrerDetection:!0,eventSourcePolicy:"parent-or-opener",skipUnchanged:!0,sanitizerPolicy:"strict"}),Qe=Object.freeze({disableReferrerDetection:!1,eventSourcePolicy:"any",skipUnchanged:!1,sanitizerPolicy:"compat"}),Xe="__LIVE_PREVIEW_CONFIG__",Ye=`var ${Xe}=`,Ze=/<!--[\s\S]*?-->|<script\b((?:[^>"']|"[^"]*"|'[^']*')*)>([\s\S]*?)<\/script\b[^>]*>/giu,et=/(?:^|\s)[iI][dD]\s*=\s*["']?__LIVE_PREVIEW_CONFIG__(?=["'\s]|$)/u,tt=/(?:^|\s)type\s*=\s*["']?application\/json(?=["'\s;]|$)/iu,nt=[{key:"disableReferrerDetection",title:"Referrer trust is still on",effect:"the runtime accepts the admin referer as a preview signal.",condition:"no preview flow relies on the admin referer alone"},{key:"eventSourcePolicy",title:"Messages are accepted from any window",effect:"any window that passes the origin check may post updates.",condition:"no window but the parent or opener posts updates"},{key:"sanitizerPolicy",title:"Sanitizer is in compat mode",effect:"id and every data-* pass.",condition:"rich text no longer relies on `id` or `data-*`"},{key:"skipUnchanged",title:"Unchanged bindings are re-applied every message",effect:"every binding is written again on every message.",condition:"no renderer relies on running again for a value that did not change"}],rt={profile:"The script was generated with `defaults: 'v1'`.",explicit:"The script sets it explicitly.",unmarked:"The script names no defaults, so its empty slot is read as the 1.x value."},it={code:"LP0709",level:"info",title:"Could not read the inline configuration for a v2 readiness check",detail:"The preview response carried no readable `__LIVE_PREVIEW_CONFIG__` inline script or JSON configuration element.",remedy:"Run this against a page with the inline runtime (not loader mode without a preview context). A preview behind authorizePreview serves it only to a request with credentials: pass them with --header, or a signed token as ?previewToken=… in the URL."},ot={code:"LP0709",level:"info",title:"The inline configuration does not say which defaults it was generated against",detail:"Scripts carry a `defaults` marker from 2.0.0-rc.1 on; this one has none, so a 1.x or 2.0.0-beta.0 generator wrote it. An empty slot is read as its 1.x value, which is what a 1.x runtime runs.",remedy:"On 1.x the warnings stand as written. On 2.0.0-beta.0 an empty slot already runs its 2.0 value, so a warning about one does not apply there; upgrade and run `pll doctor --v2` again to read the marker."};function st(e){if(!e.includes(Xe))return;const t=function(e){const t=[];for(const[,n,r]of e.matchAll(Ze))void 0!==n&&void 0!==r&&t.push({attributes:n,text:r});return t}(e),n=t.find(({text:e})=>e.includes(Ye)),r=void 0===n?void 0:function(e){const t=e.indexOf(Ye);if(-1===t)return;const n=t+Ye.length;if("["!==e[n])return;let r=0,i=!1,o="",s="";for(let t=n;t<e.length;t+=1){const n=e[t]??"";if(i)s+=n,"\\"===n?(s+=e[t+1]??"",t+=1):'"'===n&&(i=!1,o='"');else if('"'!==n){if(!/\s/u.test(n)&&((","===n&&(","===o||"["===o)||"]"===n&&","===o)&&(s+="null"),s+=n,o=n,"["===n&&(r+=1),"]"===n&&(r-=1,0===r)))break}else i=!0,s+=n}if(0===r)try{const e=JSON.parse(s);return Array.isArray(e)?e:void 0}catch{return}}(n.text);if(void 0!==r)return{source:"inline",value:e=>r[Je.indexOf(e)]??void 0};const i=function(e){for(const{attributes:t,text:n}of e)if(et.test(t)){if(!tt.test(t))return;try{const e=JSON.parse(n);return"object"!=typeof e||null===e||Array.isArray(e)?void 0:e}catch{return}}}(t);return void 0!==i?{source:"element",value:e=>Object.hasOwn(i,e)?i[e]??void 0:void 0}:void 0}function at(e){return"string"==typeof e?`'${e}'`:JSON.stringify(e)}function dt(e,t,n){const r=`\`${t.key}: ${at(He[t.key])}\``;switch(e){case"profile":return`Set ${r} or drop \`defaults: 'v1'\` once ${t.condition}. 3.0 removes the profile; \`pll migrate\` writes its rows out, so each can go on its own.`;case"explicit":return`Drop the explicit \`${t.key}: ${at(n)}\` once ${t.condition}; 2.0 defaults to ${r}.`;case"unmarked":return`Upgrading to 2.0 sets ${r}; check first that ${t.condition}.`}}function lt(e,t,n){return{code:"LP0709",level:"warning",title:e.title,detail:`${e.key} is ${at(t)}: ${e.effect} ${rt[n]}`,remedy:dt(n,e,t)}}function ct(e){return{code:"LP0709",level:"info",title:"The inline configuration names defaults this doctor does not know",detail:`Its \`defaults\` marker is ${JSON.stringify(e)}; this version reads 'v1' and 'v2', so no row was judged.`,remedy:"Run the `pll doctor` of the package version that generated the page."}}var ut="__LIVE_PREVIEW_CONFIG__",ht=/<[a-zA-Z](?:"[^"]*"|'[^']*'|[^"'<>])*>/gu,pt=/([^\s"'>/=]+)(\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/gu,ft={error:0,warning:1,info:2},mt=/<script\b[^>]*>[\s\S]*?<\/script\b[^>]*>|<style\b[^>]*>[\s\S]*?<\/style\b[^>]*>|<!--[\s\S]*?-->/giu;function gt(e){let t=e;for(;;){const e=t.replace(mt,"");if(e===t)return t;t=e}}function vt(e){const t=[];for(const n of e.matchAll(ht))for(const[,e="",r,i,o,s]of n[0].matchAll(pt))void 0!==r&&t.push({name:e.toLowerCase(),value:i??o??s??"",at:n.index});return t}function wt(e,t){return e.filter(e=>e.name===t)}function yt(e){if(void 0!==e)try{return new URL(e)}catch{return}}function bt(e,t){const{publicResponse:n,previewResponse:r}=e,i=function(e){if(e.status>=300&&e.status<=399){const t=e.headers.location;return{code:"LP0708",level:"error",title:`The preview request was redirected (${String(e.status)})${void 0===t?"":` to ${t}`}`,detail:"The audit does not follow redirects: the page at the end of one is a different resource, usually a login or a canonical host, and judging it would say nothing about this URL.",remedy:"The request carried the intent parameter (?preview=true, or the --param name), the way the admin's iframe loads the page, so a rule that redirects on that query redirects the iframe too. A redirect to a login means the route needs authentication that a plain probe cannot supply: pass an editor's credentials with --header, or a signed token as ?previewToken=… in the URL. Probe the final URL directly only when the redirect has nothing to do with either."}}if(e.status<200||e.status>299)return{code:"LP0708",level:"error",title:`The preview request returned ${String(e.status)}, not a page`,detail:"Nothing below this can be judged: a status outside 2xx means the body is an error page or empty.",remedy:"Check the URL."};if(""===e.body.trim())return{code:"LP0708",level:"error",title:`The preview request returned ${String(e.status)} with an empty body`,detail:"A 2xx status with nothing in it — 204 and 205 are defined that way — is not a page, so its missing runtime and missing bindings say nothing.",remedy:"Point the audit at a route that renders a document."};const t=e.headers["content-type"];return void 0===t||t.toLowerCase().includes("html")?void 0:{code:"LP0708",level:"error",title:`The preview request returned ${t}, not HTML`,detail:"The audit reads a rendered page. A non-HTML response has no runtime and no bindings by definition, so reporting their absence would say nothing.",remedy:"Point the audit at a page route rather than an API or an asset."}}(r);if(void 0!==i)return{url:t.url,findings:[i],errors:1,warnings:0};const o=r.body.includes(ut),s=[];if(o||s.push(!0===t.credentials?{code:"LP0701",level:"warning",title:"No inline runtime in the preview response",detail:`The preview request returned ${String(r.status)} without the inline runtime, although it carried credentials (--header, or ?previewToken= in the URL). Three readings: those credentials were not accepted — expired, issued for another page, or not what authorizePreview reads — an adapter that did not recognise the request as a preview, or a consumer that starts LivePreviewClient itself.`,remedy:"Check that the credentials are current and are the ones authorizePreview reads; if you use an adapter, check its inject mode and previewSignals. If you start the client yourself, this line is expected."}:{code:"LP0701",level:"warning",title:"No inline runtime in the preview response",detail:`The preview request returned ${String(r.status)} without the inline runtime. Three readings, and this audit cannot tell them apart from the response alone: a preview behind authorizePreview — the strict 2.0 default — which answers a request without credentials exactly like this, an adapter that did not recognise the request as a preview, or a consumer that starts LivePreviewClient itself.`,remedy:"To audit a gated preview, send what an editor's browser sends: --header 'Cookie: payload-token=…' for a Payload session; for a signed token, the URL with ?previewToken=… (the default transport, dropped from the visitor request), or --header 'x-preview-token: …' where the strategy sets transport: { kind: 'header' }. Otherwise check the adapter's inject mode and previewSignals; if you start the client yourself, this line is expected."}),s.push(...function(e,t,n){const r=[],i=yt(n.url),o=yt(n.adminOrigin),s=void 0!==o&&i?.origin===o.origin,a=function(e){if(void 0!==e)for(const t of e.split(";")){const e=t.trim();if(/^frame-ancestors(?:\s|$)/iu.test(e))return e}}(e.headers["content-security-policy"]);if(t&&void 0===a)r.push({code:"LP0702",level:"warning",title:"Preview response declares no frame-ancestors",detail:"The runtime is injected but the response carries no frame-ancestors directive, so nothing states which origins may embed this page.",remedy:"Let the adapter manage CSP, or set frame-ancestors yourself to the admin origin. Without it you are relying on the absence of a policy."});else if(void 0!==a&&void 0!==n.adminOrigin){const e=void 0!==o&&void 0!==i&&function(e,t,n){const r=e.split(/\s+/u).slice(1).filter(e=>e.length>0).map(e=>e.toLowerCase());if(0===r.length||1===r.length&&"'none'"===r[0])return!1;for(const e of r)if("'self'"===e){if(Ge(t,n))return!0}else{if("*"===e)return!0;if(!e.startsWith("'")&&Ke(e,t,n))return!0}return!1}(a,o,i);e||r.push({code:"LP0702",level:"error",title:"frame-ancestors does not admit the admin origin",detail:void 0===o?`"${n.adminOrigin}" is not an absolute URL, so no source expression can admit it.`:`Served: "${a}". Expected it to allow ${o.origin}.`,remedy:"Add the admin origin to allowedOrigins so the adapter merges it into frame-ancestors, or add it to your own policy."})}const d=e.headers["x-frame-options"];if(void 0!==d&&void 0===a&&(/deny/iu.test(d)||/sameorigin/iu.test(d)&&!s)){const e=void 0!==o||/deny/iu.test(d);r.push(e?{code:"LP0703",level:"error",title:`X-Frame-Options: ${d} blocks the preview iframe`,detail:"This header is older than CSP. A browser applies it to a response that has no frame-ancestors directive, and this response has no frame-ancestors.",remedy:"Remove X-Frame-Options for preview responses, or serve a frame-ancestors directive that admits the admin: the header is then ignored. It is usually set by a proxy or a security middleware rather than by the app."}:{code:"LP0703",level:"warning",title:`X-Frame-Options: ${d} blocks every frame from another origin`,detail:"This header is older than CSP. A browser applies it to a response that has no frame-ancestors directive, and this response has no frame-ancestors. SAMEORIGIN refuses a frame from another origin only, and no admin origin was given: whether it blocks this preview depends on where the admin is served, which this probe cannot see.",remedy:"Re-run with --admin <origin> to have it judged. If the admin is on another origin, remove X-Frame-Options for preview responses or serve a frame-ancestors directive that admits it; a proxy or a security middleware usually sets the header."})}return r}(r,o,t)),s.push(...function(e,t,n,r){const i=[],o=vt(e),s=wt(o,"data-payload-field").length,a=wt(vt(t),"data-payload-field").length,d=wt(o,"data-payload-owner").length,l=wt(o,"data-payload-fragment").filter(e=>e.value.length>0).length;a>0&&i.push({code:"LP0704",level:"warning",title:`${String(a)} binding attribute(s) served to anonymous visitors`,detail:"A request with no preview intent received data-payload-field attributes. These disclose the CMS field taxonomy, and any CSS keyed on them changes public layout the moment emission is gated.",remedy:"Gate binding emission on an authorized preview context — see createPreviewBindings(), whose suppressed form emits nothing at all."}),void 0!==r.threshold&&s>r.threshold&&i.push({code:"LP0705",level:"warning",title:`${String(s)} bindings exceed the ${r.configured?"configured":"default"} visibility gate`,detail:`Above visibilityGateThreshold (${String(r.threshold)}) the scheduler stops writing offscreen elements and buffers them until they scroll into view. On a page nobody scrolls, that is never.`,remedy:"Raise visibilityGateThreshold, or set disableVisibilityGate, on the adapter, LivePreviewClient or generateInlineScript() if the whole page must stay live, or confirm that deferring below the fold is acceptable here."}),n&&0===s&&0===l&&i.push({code:"LP0707",level:"error",title:"Preview response carries no bindings",detail:"The runtime is present but there is not one data-payload-field element for it to write into and not one data-payload-fragment boundary for a server to render, so no edit can ever be visible on this page.",remedy:"Add binding attributes or fragment boundaries to the markup. pll-codegen --inventory lists every field the schema makes addressable."});const c=function(e){const t=wt(e,"data-payload-owner")[0];return void 0===t?0:wt(e,"data-payload-field").filter(e=>e.at<t.at).length}(o);return d>0&&c>0&&i.push({code:"LP0706",level:"warning",title:`${String(c)} binding(s) outside every owner marker`,detail:`The page declares ${String(d)} owner marker(s), so owner scoping is in use. Bindings that belong to no owner receive nothing once scopeBindingsByOwner is on — they fail closed.`,remedy:"Give every binding an owning ancestor, or leave scopeBindingsByOwner off until they all have one. Counted before the first owner marker only, so the real number may be higher."}),i}(gt(r.body),gt(n.body),o,function(e){const t=st(e);if(!0===t?.value("disableVisibilityGate"))return{threshold:void 0,configured:!0};const n=t?.value("visibilityGateThreshold");return"number"==typeof n?{threshold:n,configured:!0}:{threshold:50,configured:!1}}(r.body))),n.body.includes(ut)){const e=n.body.includes(`var ${ut}=`);s.push({code:Fe.RuntimeOnPublicPage,level:"info",title:e?"Runtime is also served to anonymous visitors":"Preview configuration is also served to anonymous visitors",detail:e?"A request with no preview intent received the inline runtime. That is correct for inject: 'always' and unintended for 'preview-only'.":"A request with no preview intent received the configuration element a page writes for a client it starts itself. That is correct if the page starts the client for every request, and unintended if it writes the element only for a preview.",remedy:""})}return!0===t.v2&&s.push(...function(e){const t=st(e.previewResponse.body);if(void 0===t)return[it];const n=t.value("defaults");if(void 0!==n&&"v1"!==n&&"v2"!==n)return[ct(n)];const r=n??("element"===t.source?"v2":void 0),i="v2"===r?He:Qe,o=nt.flatMap(e=>{const n=t.value(e.key),o=n??i[e.key];return o===He[e.key]?[]:[lt(e,o,"v1"===r?"profile":void 0===n?"unmarked":"explicit")]});return void 0===r?[...o,ot]:o}(e)),s.sort((e,t)=>ft[e.level]-ft[t.level]),{url:t.url,findings:s,errors:s.filter(e=>"error"===e.level).length,warnings:s.filter(e=>"warning"===e.level).length}}var $t=["preview","draft","livePreview"];function Pt(e){const t=e.indexOf("#"),n=-1===t?"":e.slice(t),r=-1===t?e:e.slice(0,t),i=r.indexOf("?");return-1===i?{base:r,parts:[],hash:n}:{base:r.slice(0,i),parts:r.slice(i+1).split("&"),hash:n}}function xt(e){const t=e.indexOf("="),n=e=>{try{return decodeURIComponent(e.replace(/\+/gu," "))}catch{return e}};return-1===t?[n(e),""]:[n(e.slice(0,t)),n(e.slice(t+1))]}var St="previewToken";function kt(e,t=St){const{base:n,parts:r,hash:i}=Pt(e),o=r.map(e=>{const n=e.indexOf("=");return-1===n||xt(e)[0]!==t?e:`${e.slice(0,n)}=…`});return o.some((e,t)=>e!==r[t])?`${n}?${o.join("&")}${i}`:e}function Lt(e,t){return Pt(e).parts.some(e=>{const[n,r]=xt(e);return n===t&&""!==r})}function Nt(e){const t={};return e.forEach((e,n)=>{t[n.toLowerCase()]=e}),t}async function Tt(e,t){const n=e.body?.getReader();if(void 0===n)return e.text();const r=new TextDecoder;let i=0,o="";for(;;){const{done:e,value:s}=await n.read();if(e)break;if(i+=s.byteLength,i>t)throw await n.cancel(),new Error(`the response body exceeds ${String(t)} bytes, which is not a page the audit can judge`);o+=r.decode(s,{stream:!0})}return o+r.decode()}function Ot(e){try{return new URL(e).href}catch{return`${e.replace(/\/+$/u,"")}/`}}var Et=/^[^\s&=#?-][^\s&=#]*$/u,At=/^([!#$%&'*+.^_`|~0-9A-Za-z-]+):[ \t]*(.*)$/u;function Rt(e,t){const n=void 0===t||t.startsWith("-")||Ut(t)?null:At.exec(t),r=n?.[1],i=n?.[2];void 0!==r&&void 0!==i?Object.keys(e.headers).some(e=>e.toLowerCase()===r.toLowerCase())?e.usageError??=`pll doctor: --header "${r}" is given twice; join the values into one header`:e.headers[r]=i:e.usageError??='pll doctor: --header takes "Name: value", such as --header "Cookie: payload-token=…"'}function jt(e,t){void 0!==t&&Et.test(t)?e.params.push(t):e.usageError??="pll doctor: --param takes a query parameter name, such as --param draft"}function It(e,t){void 0!==t&&Et.test(t)?e.tokenParam=t:e.usageError??="pll doctor: --token-param takes a query parameter name, such as --token-param lpt"}var Ct='pll doctor — audit what a live-preview deployment actually serves\npll migrate — rewrite 1.x APIs to their 2.0 names and homes\n\nUsage:\n pll doctor <url> [--admin <origin>] [--header <name: value>]... [--param <name>]...\n [--token-param <name>] [--json] [--v2]\n pll migrate <path> [--write] [--only <id,id>]\n\nThe URL is fetched twice: once as an ordinary visitor, without any intent\nparameter, and once the way the Payload admin\'s iframe loads it, with\n?preview=true and the iframe\'s headers.\nMost findings come from the difference between the two responses. Redirects\nare reported, not followed.\n\nOptions of pll doctor:\n -a, --admin <origin> Admin origin the preview is embedded from. Enables the\n frame-ancestors check to verify the origin is admitted,\n not merely that a policy exists.\n -H, --header <h> A header for the preview request only, as "Name: value";\n repeat it for more. A preview behind authorizePreview\n needs an editor\'s credentials: a Payload session Cookie,\n or an x-preview-token where the token strategy sets\n transport: { kind: \'header\' }. A signed token travels in\n the URL by default, as ?previewToken=…, which the visitor\n request drops. The visitor request stays anonymous and\n values are never printed, but a shell keeps them in its\n history, so prefer a short-lived token.\n --param <name> A query parameter the deployment reads as preview intent,\n for an adapter whose previewQueryParams replaces the\n default preview, draft and livePreview; repeat it for\n more. The first one is what the preview request carries\n as <name>=true; none of them reaches the visitor request.\n --token-param <n> The query parameter the signed-token strategy reads,\n where its transport names one other than previewToken.\n Treated like previewToken: dropped from the visitor\n request, counted as the credential, never printed.\n --json Emit the report as JSON instead of text\n --v2 Also check the page against the 2.0 readiness table\n -h, --help Show this help\n\nExit codes of pll doctor:\n 0 no error-level findings\n 1 usage error, or the URL could not be fetched\n 2 at least one error-level finding\n\npll migrate has its own options and exit codes: pll migrate --help\n\nExamples:\n pll doctor https://example.com/\n pll doctor https://example.com/blog/hello --admin https://cms.example.com\n pll doctor "https://example.com/?previewToken=$PREVIEW_TOKEN" --v2\n pll doctor https://example.com/ --header "Cookie: payload-token=$PAYLOAD_TOKEN"\n';function Ut(e){try{return"null"!==new URL(e).origin}catch{return!1}}async function Dt(e,t){const[n,...r]=e;if(void 0===n||"-h"===n||"--help"===n)return process.stdout.write(Ct),void 0===n?1:0;if("migrate"===n)return async function(e){const t=function(e){let t,n,r,i=!1,o=!1;const s=e=>e.split(",").filter(e=>e.length>0);for(let a=0;a<e.length;a+=1){const d=e[a];void 0!==d&&("-h"===d||"--help"===d?o=!0:"--write"===d?i=!0:"--only"===d?(n=s(e[a+1]??""),a+=1):d.startsWith("--only=")?n=s(d.slice(7)):d.startsWith("-")?r??=d:t??=d)}return{target:t,write:i,only:n,help:o,unknown:r}}(e);if(t.help)return process.stdout.write(Ue),0;if(void 0!==t.unknown)return process.stderr.write(`pll migrate: unknown option ${t.unknown}\n`),1;if(void 0===t.target)return process.stderr.write("pll migrate: a path is required. Try `pll migrate --help`.\n"),1;let n;try{n=await async function(e,t={}){const n=t.io??{read:e=>o(e,"utf8"),write:(e,t)=>i(e,t,"utf8"),list:Ie},r=[],s={};for(const i of await n.list(e)){const o=await n.read(i),{output:a,edits:d,conflicts:l}=Oe(o,{fileName:i,...void 0===t.only?{}:{only:t.only}}),c=a!==o;if(c&&!0===t.write&&await n.write(i,a),c)for(const e of d)s[e.codemod]=(s[e.codemod]??0)+1;r.push({file:Ce(e,i),edits:d,changed:c,conflicts:l})}return{files:r,changedCount:r.filter(e=>e.changed).length,byCodemod:s,conflictCount:r.filter(e=>e.conflicts.length>0).length}}(t.target,{write:t.write,...void 0===t.only?{}:{only:t.only}})}catch(e){return process.stderr.write(`pll migrate: ${e instanceof Error?e.message:String(e)}\n`),1}for(const e of n.files)e.changed&&process.stdout.write(`${t.write?"migrated":"would migrate"} ${e.file} (${De(e)})\n`);process.stdout.write(`\n${t.write?"Migrated":"Would migrate"} ${String(n.changedCount)} file(s).${t.write?"":" Re-run with --write to apply."}\n`);for(const{id:e,notice:t}of Le)void 0!==t&&(n.byCodemod[e]??0)>0&&process.stdout.write(`\nNote (${e}): ${t}\n`);const r=n.files.filter(e=>e.conflicts.length>0);if(0===r.length)return 0;process.stdout.write(`\n${String(r.length)} file(s) need manual attention:\n`);for(const e of r)for(const t of e.conflicts){const n=void 0===t.line?e.file:`${e.file}:${String(t.line)}`;process.stdout.write(` ${n}: ${t.reason}\n`)}return 3}(r);if("doctor"!==n)return process.stderr.write(`pll: unknown command "${n}". Try \`pll --help\`.\n`),1;const s=function(e){const t={url:void 0,adminOrigin:void 0,json:!1,v2:!1,showHelp:!1,unknown:[],headers:{},usageError:void 0,params:[],tokenParam:void 0};for(let n=0;n<e.length;n+=1){const r=e[n];void 0!==r&&("-h"===r||"--help"===r?t.showHelp=!0:"--json"===r?t.json=!0:"--v2"===r?t.v2=!0:"--admin"===r||"-a"===r?(t.adminOrigin=e[n+1],n+=1):r.startsWith("--admin=")?t.adminOrigin=r.slice(8):"--header"===r||"-H"===r?(Rt(t,e[n+1]),n+=1):r.startsWith("--header=")?Rt(t,r.slice(9)):"--param"===r?(jt(t,e[n+1]),n+=1):r.startsWith("--param=")?jt(t,r.slice(8)):"--token-param"===r?(It(t,e[n+1]),n+=1):r.startsWith("--token-param=")?It(t,r.slice(14)):r.startsWith("-")?t.unknown.push(r):t.url??=r)}return t}(r);if(s.showHelp)return process.stdout.write(Ct),0;if(s.unknown.length>0)return process.stderr.write(`pll doctor: unknown option ${s.unknown.join(", ")}\n`),1;if(void 0===s.url)return process.stderr.write("pll doctor: a URL is required. Try `pll doctor --help`.\n"),1;if(void 0!==s.usageError)return process.stderr.write(`${s.usageError}\n`),1;if(void 0!==s.adminOrigin&&!Ut(s.adminOrigin))return process.stderr.write(`pll doctor: --admin must be an absolute URL such as https://cms.example.com (got "${s.adminOrigin}")\n`),1;let a;try{a=await async function(e){const t=e.fetchImpl??function(e={}){const t=e.timeoutMs??15e3,n=e.maxBodyBytes??10485760;return async(r,i)=>{const o=e.fetchFn??globalThis.fetch;let s;try{s=await o(r,{headers:i.headers,redirect:"manual",signal:AbortSignal.timeout(t)})}catch(e){if(e instanceof Error&&"TimeoutError"===e.name)throw new Error(`no response within ${String(t/1e3)} s`,{cause:e});throw e}return{status:s.status,headers:Nt(s.headers),body:await Tt(s,n)}}}(),n=void 0===e.previewQueryParams||0===e.previewQueryParams.length?$t:e.previewQueryParams,r=e.tokenQueryParam??St,i=await t(function(e,t,n){const{base:r,parts:i,hash:o}=Pt(e),s=/* @__PURE__ */new Set([...t,n]),a=i.filter(e=>!s.has(xt(e)[0]));return a.length===i.length?e:`${r}${0===a.length?"":`?${a.join("&")}`}${o}`}(e.url,n,r),{headers:{Accept:"text/html","Sec-Fetch-Dest":"document","Sec-Fetch-Mode":"navigate"}}),o={Accept:"text/html","Sec-Fetch-Dest":"iframe","Sec-Fetch-Mode":"navigate",...void 0===e.adminOrigin?{}:{Referer:Ot(e.adminOrigin)}},s=function(e,t){const n=new Set(Object.keys(t).map(e=>e.toLowerCase()));return Object.fromEntries(Object.entries(e??{}).filter(([e])=>!n.has(e.toLowerCase())))}(e.previewHeaders,o),a=await t(function(e,t){const{base:n,parts:r,hash:i}=Pt(e);if(r.some(e=>{const[n,r]=xt(e);return t.includes(n)&&function(e){return"true"===e||"1"===e}(r)}))return e;const o=r.join("&"),s=""===o?"?":o.endsWith("&")?"":"&",a=`${encodeURIComponent(t[0]??"preview")}=true`;return`${n}${0===r.length?"?":`?${o}${s}`}${a}${i}`}(e.url,n),{headers:{...s,...o}});return bt({publicResponse:i,previewResponse:a},{url:kt(e.url,r),adminOrigin:e.adminOrigin,...!0===e.v2?{v2:!0}:{},...Object.keys(s).length>0||Lt(e.url,r)?{credentials:!0}:{}})}({url:s.url,...void 0!==s.adminOrigin?{adminOrigin:s.adminOrigin}:{},...s.v2?{v2:!0}:{},...Object.keys(s.headers).length>0?{previewHeaders:s.headers}:{},...s.params.length>0?{previewQueryParams:s.params}:{},...void 0===s.tokenParam?{}:{tokenQueryParam:s.tokenParam},...void 0!==t?{fetchImpl:t}:{}})}catch(e){const t=function(e){if(!(e instanceof Error))return String(e);const t=e.cause;return t instanceof Error&&""!==t.message&&!e.message.includes(t.message)?`${e.message} (${t.message})`:e.message}(e),n=kt(s.url,s.tokenParam);return s.json?process.stdout.write(`${JSON.stringify({url:n,error:t},void 0,2)}\n`):process.stderr.write(`pll doctor: could not probe ${n}: ${t}\n`),1}return process.stdout.write(s.json?`${JSON.stringify(a,void 0,2)}\n`:function(e){const t=[`pll doctor — ${e.url}`,""];if(0===e.findings.length)return t.push("No findings. The preview response carries the runtime, a frame-ancestors"),t.push("policy, and bindings; the public response carries none of them.",""),t.join("\n");for(const n of e.findings)t.push(`${qe[n.level]} ${n.code} ${n.title}`),t.push(` ${n.detail}`),""!==n.remedy&&t.push(` → ${n.remedy}`),t.push("");return t.push(`${String(e.errors)} error(s), ${String(e.warnings)} warning(s).`,""),t.join("\n")}(a)),a.errors>0?2:0}function qt(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"===n||"pll.cmd"===n||n.startsWith("doctor-cli")}qt()&&Dt(process.argv.slice(2)).then(e=>{process.exit(e)});export{qt as isCliInvocation,Dt as run};
2
+ import{createRequire as e}from"module";import{relative as t,join as n,extname as r}from"path";import{writeFile as i,readFile as o,stat as s,readdir as a}from"fs/promises";var d,l,c="payload-live-preview";function u(){if(void 0===d)try{d=e(import.meta.url)("ts-morph")}catch(e){throw new Error("pll migrate needs ts-morph: npm install --save-dev ts-morph",{cause:e})}return d}function h(e,t){const n=u();return l??=new n.Project({useInMemoryFileSystem:!0,skipLoadingLibFiles:!0,skipFileDependencyResolution:!0,compilerOptions:{allowJs:!0,noLib:!0}}),l.createSourceFile(`/script.${t}`,e,{overwrite:!0})}function p(e){return e===c||e.startsWith(`${c}/`)}function f(e){const t=[];for(const n of e.getExportDeclarations()){const e=n.getModuleSpecifierValue();if(void 0!==e&&p(e))for(const r of n.getNamedExports())t.push({imported:r.getName(),specifier:e,importedNode:r.getNameNode(),alias:r.getAliasNode()?.getText(),line:r.getStartLineNumber()})}return t}function m(e){const{Node:t,SyntaxKind:n}=u(),r=[];for(const t of e.getImportDeclarations()){const e=t.getModuleSpecifierValue();if(p(e))for(const n of t.getNamedImports()){const i=n.getAliasNode(),o=i??n.getNameNode();r.push({imported:n.getName(),local:o.getText(),specifier:e,kind:"import",importedNode:n.getNameNode(),aliased:void 0!==i,symbol:o.getSymbol(),declaration:t})}}for(const i of e.getDescendantsOfKind(n.VariableDeclaration)){const e=g(i.getInitializer()),n=i.getNameNode();if(void 0!==e&&p(e)&&t.isObjectBindingPattern(n))for(const o of n.getElements()){const n=o.getNameNode();if(!t.isIdentifier(n))continue;const s=o.getPropertyNameNode();r.push({imported:void 0===s?n.getText():v(s),local:n.getText(),specifier:e,kind:"require",importedNode:s??n,aliased:void 0!==s,symbol:n.getSymbol(),declaration:i})}}return r}function g(e){const{Node:t,SyntaxKind:n}=u(),r=void 0!==e&&t.isAwaitExpression(e)?e.getExpression():e;if(void 0===r||!t.isCallExpression(r))return;const i=r.getExpression();if((!t.isIdentifier(i)||"require"!==i.getText())&&i.getKind()!==n.ImportKeyword)return;const[o]=r.getArguments();return void 0!==o&&t.isStringLiteral(o)?o.getLiteralText():void 0}function v(e){const{Node:t}=u();return t.isStringLiteral(e)||t.isNoSubstitutionTemplateLiteral(e)?e.getLiteralText():e.getText()}function w(e){const{Node:t}=u();if(t.isSpreadAssignment(e))return;const n=e.getNameNode();return t.isComputedPropertyName(n)?void 0:v(n)}function y(e,t){const{Node:n,SyntaxKind:r}=u(),i=t.symbol?.compilerSymbol;if(void 0===i)return[];const o=e.getProject().getTypeChecker(),s=[];for(const a of e.getDescendantsOfKind(r.Identifier)){if(a.getText()!==t.local||b(a,t.declaration))continue;const e=a.getParent();n.isShorthandPropertyAssignment(e)?o.getShorthandAssignmentValueSymbol(e)?.compilerSymbol===i&&s.push({node:a,kind:"shorthand"}):n.isExportSpecifier(e)?e.getNameNode()===a&&e.getLocalTargetSymbol()?.compilerSymbol===i&&s.push({node:a,kind:"export"}):a.getSymbol()?.compilerSymbol===i&&s.push({node:a,kind:"reference"})}return s}function b(e,t){return void 0!==e.getFirstAncestor(e=>e===t)}function $(e,t,n=[]){const{SyntaxKind:r}=u();for(const i of e.getDescendantsOfKind(r.Identifier)){if(i.getText()!==t)continue;const e=i.getParent();if(P(e,i)&&!n.some(t=>t===e||b(e,t)))return e}}function P(e,t){const{Node:n}=u();return n.isVariableDeclaration(e)||n.isBindingElement(e)||n.isFunctionDeclaration(e)||n.isClassDeclaration(e)||n.isParameterDeclaration(e)||n.isEnumDeclaration(e)?e.getNameNode()===t:n.isImportSpecifier(e)?(e.getAliasNode()??e.getNameNode())===t:n.isImportClause(e)?e.getDefaultImport()===t:!!n.isNamespaceImport(e)&&e.getNameNode()===t}function x(e,t){return{start:e.getStart(),end:e.getEnd(),text:t}}function S(e,t){const n=[...t].sort((e,t)=>t.start-e.start);let r=e,i=Number.POSITIVE_INFINITY;for(const e of n){if(e.end>i)throw new Error("overlapping codemod edits");r=`${r.slice(0,e.start)}${e.text}${r.slice(e.end)}`,i=e.start}return r}var k=new Set(["astro","nextjs","sveltekit","nuxt","nuxt-module"].map(e=>`payload-live-preview/${e}`));function L(e){const{Node:t}=u(),n=/* @__PURE__ */new Map,r=(e,t)=>{const r=n.get(e)??[];r.some(e=>e.outer===t.outer&&e.at===t.at&&e.kind===t.kind)||r.push(t),n.set(e,r)},i=(e,n)=>{r(e,{kind:n,outer:e}),e.getProperties().forEach((i,o)=>{if(!t.isSpreadAssignment(i))return;const s=O(i.getExpression());void 0!==s&&r(s,{kind:n,outer:e,at:o})})};for(const n of m(e)){const r=k.has(n.specifier)?"adapter":"runtime";for(const o of y(e,n)){const e=o.node.getParent();if("reference"===o.kind&&(t.isCallExpression(e)||t.isNewExpression(e))&&e.getExpression()===o.node)for(const n of e.getArguments()){const e=E(n),o=t.isObjectLiteralExpression(e)?e:O(e);void 0!==o&&i(o,r)}}}return n}function N(e,t){const{Node:n,SyntaxKind:r}=u(),i=new Set(m(e).map(e=>e.local));return e.getDescendantsOfKind(r.JsxAttribute).filter(e=>{const r=e.getParent().getParent();return(n.isJsxOpeningElement(r)||n.isJsxSelfClosingElement(r))&&i.has(r.getTagNameNode().getText())&&e.getNameNode().getText()===t})}function T(e,t){return e.getProperties().find(e=>w(e)===t)}function O(e){const{Node:t,VariableDeclarationKind:n}=u(),r=E(e);if(t.isIdentifier(r))for(const e of r.getSymbol()?.getDeclarations()??[]){if(!t.isVariableDeclaration(e))continue;if(e.getVariableStatement()?.getDeclarationKind()!==n.Const)continue;const r=e.getInitializer(),i=void 0===r?void 0:E(r);if(void 0!==i&&t.isObjectLiteralExpression(i))return i}}function E(e){const{Node:t}=u();let n=e;for(;t.isParenthesizedExpression(n)||t.isAsExpression(n)||t.isSatisfiesExpression(n)||t.isTypeAssertion(n);)n=n.getExpression();return n}var A="expand-defaults-v1",R="defaults",j=[["disableReferrerDetection",()=>"false"],["eventSourcePolicy",e=>`${e}any${e}`],["skipUnchanged",()=>"false"],["sanitizerPolicy",e=>`${e}compat${e}`]],I={adapter:[["strict",()=>"false"],["previewSignals",e=>`[${[`${e}query${e}`,`${e}fetch-dest${e}`,`${e}referer${e}`].join(", ")}]`],...j],runtime:j},C=new Set(I.adapter.map(([e])=>e)),D="write the rows `defaults: 'v1'` stands for by hand (docs/migration.md)",U={id:A,summary:"`defaults: 'v1'` → the 1.x rows as explicit options",ledgerEntry:21,notice:"The rows keep the 1.x values `defaults: 'v1'` gave; `pll doctor --v2` names each one to drop once the page is ready for 2.0's.",apply(e){const{Node:t}=u(),n=[],r=[];for(const[i,o]of L(e)){const e=T(i,R);if(void 0===e)continue;const s=e.getStartLineNumber(),a=e=>{r.push({codemod:A,line:s,reason:`${e}; ${D}`})},d=t.isPropertyAssignment(e)?e.getInitializer():void 0;if(void 0===d||!t.isStringLiteral(d)){a("`defaults` is not a literal");continue}if("v1"!==d.getLiteralText())continue;const l=q(i,e,o);void 0===l?n.push(z(i,e,o,d.getText().charAt(0))):a(l)}for(const t of N(e,R))r.push({codemod:A,line:t.getStartLineNumber(),reason:`a JSX attribute; ${D} as attributes`});return{edits:n,conflicts:r}}};function q(e,t,n){const{Node:r}=u();if(new Set(n.map(e=>e.kind)).size>1)return"the object is shared by an adapter and a client, which take different rows";const i=e.getProperties(),o=i.findIndex(e=>e===t);if(i.slice(0,o).some(e=>r.isSpreadAssignment(e)))return"a spread before `defaults` may set a row the expansion would override";for(const{outer:e,at:t}of n){if(void 0===t)continue;if(void 0!==T(e,R))return"a call that spreads it names its own defaults";const n=e=>r.isSpreadAssignment(e)||C.has(w(e)??"");if(e.getProperties().slice(0,t).some(n))return"a call sets a row before spreading the object, and the expansion would override it"}}function z(e,t,n,r){const{Node:i}=u(),o=n[0]?.kind??"runtime",s=new Set(e.getProperties().map(e=>w(e))),a=[e,...n.map(e=>e.outer)],d=e=>a.some(t=>void 0!==T(t,e)),l=new Set(n.map(e=>void 0===e.at?void 0:e.outer.getProperties()[e.at])),c=a.some(e=>e.getProperties().some(e=>i.isSpreadAssignment(e)&&!l.has(e))),h=I[o].filter(([e])=>!s.has(e)).map(([e,t])=>`${e}: ${t(r)}`);d("mergeDepth")||!d("serverURL")&&!c||h.push("mergeDepth: 1");const p=t.getSourceFile().getFullText();if(0===h.length){const n=e.getProperties().find(e=>e.getStart()>t.getStart());return{start:t.getStart(),end:n?.getStart()??t.getEnd(),text:""}}const f=p.lastIndexOf("\n",t.getStart())+1,m=p.slice(f,t.getStart()),g=/^\s*$/u.test(m)?`,\n${m}`:", ";return{start:t.getStart(),end:t.getEnd(),text:h.join(g)}}var F="move-fetch-preview-helpers",_=`${c}/server`,M={fetchPreviewDocument:"fetchDocument",fetchPreviewGlobal:"fetchGlobal"},W=/* @__PURE__ */new Set(["serverURL","apiRoute","depth"]),V=/* @__PURE__ */new Set(["draft","fetchFn"]),B=["authorization","locale","headers","signal","errorMode"],K={fetchPreviewDocument:["collection","where",...B],fetchPreviewGlobal:["global",...B]};function G(e,t){return{codemod:F,reason:t,line:e}}function H(e,t,n){const r=[],i=[],o=[],s=/* @__PURE__ */new Set;for(const e of t.getProperties()){const t=w(e);void 0!==t&&s.add(t),void 0!==t&&W.has(t)?r.push(e.getText()):void 0!==t&&V.has(t)?o.push(t):i.push(e.getText())}s.has("depth")||r.push("depth: 1 /* TODO(pll migrate): the 1.x default; match the runtime mergeDepth */"),s.has("authorization")||i.push("authorization: null /* TODO(pll migrate): pass the verdict from authorizePreviewRequest(); null reads the published document */");const a=K[n]??[],d=[...s].filter(e=>!W.has(e)&&!V.has(e)&&!a.includes(e)),l=e.getTypeArguments().map(e=>e.getText()),c=0===l.length?"":`<${l.join(", ")}>`,u=M[n]??n,h=`definePreview({ ${r.join(", ")} }).${u}${c}({ ${i.join(", ")} })`,p=0===o.length?"":`, and ${o.join("/")} was dropped`,f=e.getStartLineNumber(),m=G(f,`${n}() was rewritten onto definePreview().${u}(); it now returns a PreviewFetchResult (check ok/data) and needs a real authorization for drafts${p}`),g=[];return d.length>0&&g.push(G(f,`${n}() was passed ${d.map(e=>`\`${e}\``).join(", ")}, which .${u}() does not accept; it takes ${a.join(", ")}. The key was carried over unchanged and will not compile — place it by hand`)),{edit:{start:e.getStart(),end:e.getEnd(),text:h},done:m,advice:g}}function J(e,t,n){return`import { ${t.join(", ")} } from ${e}${n}${e};`}var Q={id:F,summary:"`fetchPreviewDocument`/`fetchPreviewGlobal` from the root → `definePreview().fetchDocument`/`.fetchGlobal` (payload-live-preview/server)",ledgerEntry:9,apply(e){const t=m(e).filter(e=>e.specifier===c&&e.imported in M),n=f(e).filter(e=>e.specifier===c&&e.imported in M);return 0===t.length&&0===n.length?{edits:[],conflicts:[]}:function(e,t,n){const{Node:r}=u(),i=n.map(e=>G(e.line,`${e.imported} is re-exported straight from the package; it became definePreview().${M[e.imported]??e.imported}() on ${_}, so rewrite the re-export and its importers by hand`)),o=[],s=[],a=[];for(const n of t)if("require"!==n.kind)for(const t of y(e,n)){const e=t.node.getStartLineNumber(),d=t.node.getParent();if("reference"!==t.kind||!r.isCallExpression(d)||d.getExpression()!==t.node){i.push(G(e,`${n.local} is used other than as a direct call; rewrite it onto definePreview() by hand`));continue}const[l]=d.getArguments();if(void 0===l||!r.isObjectLiteralExpression(l)||l.getProperties().some(e=>r.isSpreadAssignment(e))){i.push(G(e,`${n.imported}() options are not a plain object literal, so serverURL/depth cannot be split out; rewrite it onto definePreview() by hand`));continue}const c=H(d,l,n.imported);a.push(c.edit),o.push(c.done,...c.advice),s.push(...c.advice)}else i.push(G(n.declaration.getStartLineNumber(),`${n.imported} is bound with require(); rewrite it onto definePreview() from ${_} by hand`));const d=e.getImportDeclarations().filter(e=>e.getModuleSpecifierValue()===_),l=$(e,"definePreview",d);return void 0!==l&&i.push(G(l.getStartLineNumber(),`this module already binds a definePreview that is not ${_}'s; rename it, then move the fetch helpers by hand`)),i.length>0?{edits:[],conflicts:[...i,...s]}:(a.push(...function(e,t){const{Node:n}=u(),r=[],i=/* @__PURE__ */new Set;for(const e of t)n.isImportDeclaration(e.declaration)&&i.add(e.declaration);const o=e.getImportDeclarations().find(e=>e.getModuleSpecifierValue()===_&&!e.isTypeOnly()),s=!0===o?.getNamedImports().some(e=>"definePreview"===e.getName());let a;if(void 0!==o&&!s){const e=o.getModuleSpecifier().getQuoteKind(),t=[...o.getNamedImports().map(e=>e.getText()),"definePreview"],n=o.getDefaultImport()?.getText(),i=void 0===n?t.join(", "):`${n}, { ${t.join(", ")} }`,s=void 0===n?J(e,t,_):`import ${i} from ${e}${_}${e};`;r.push({start:o.getStart(),end:o.getEnd(),text:s})}for(const t of i){const n=t.getModuleSpecifier().getQuoteKind(),i=t.getNamedImports().filter(e=>!(e.getName()in M)).map(e=>e.getText()),s=t.getDefaultImport()?.getText(),d=[s,0===i.length?void 0:`{ ${i.join(", ")} }`].filter(e=>void 0!==e),l=t.isTypeOnly()?"type ":"",u=0===d.length?"":`import ${l}${d.join(", ")} from ${n}${c}${n};`;if(void 0===o&&void 0===a)a=J(n,["definePreview"],_),r.push({start:t.getStart(),end:t.getEnd(),text:""===u?a:`${u}\n${a}`});else{const n=t.getEnd(),i=""===u&&"\n"===e.getFullText()[n]?1:0;r.push({start:t.getStart(),end:n+i,text:u})}}return r}(e,t)),{edits:a,conflicts:o})}(e,t,n)}},X="rename-admin-origins-option",Z="hasPreviewIntent",Y="adminOrigins",ee="allowedOrigins",te=`if they carry \`${Y}\`, rename it to \`${ee}\``,ne={id:X,summary:"`hasPreviewIntent(request, { adminOrigins })` → `{ allowedOrigins }`",ledgerEntry:13,apply(e){const{Node:t}=u(),n=[],r=[],i=m(e).filter(e=>e.imported===Z);for(const o of i)for(const i of y(e,o)){const e=i.node.getParent();if("reference"!==i.kind||!t.isCallExpression(e))continue;if(e.getExpression()!==i.node)continue;const o=e.getArguments()[1];if(void 0===o)continue;const s=o.getStartLineNumber();if(!t.isObjectLiteralExpression(o)){r.push({codemod:X,line:s,reason:`${Z}() options are not a literal; ${te}`});continue}const a=o.getProperties(),d=a.map(e=>w(e));if(d.includes(Y)&&d.includes(ee))r.push({codemod:X,line:s,reason:`${Z}() is given both ${Y} and ${ee}; ${ee} wins, drop ${Y} by hand`});else for(const e of a)if(t.isSpreadAssignment(e))r.push({codemod:X,line:e.getStartLineNumber(),reason:`${Z}() spreads its options; ${te}`});else{if(w(e)!==Y)continue;t.isShorthandPropertyAssignment(e)?n.push(x(e,`${ee}: ${Y}`)):t.isPropertyAssignment(e)&&n.push(x(e.getNameNode(),ee))}}return{edits:n,conflicts:r}}},re="rename-bindings-authorized-option",ie="authorized",oe="authorization",se=`if they carry \`${ie}\`, rename it to \`${oe}\` and pass the verdict from authorizePreviewRequest()`,ae=`\`${oe}\` takes the context from authorizePreviewRequest(); the boolean 1.x accepted is not. The key was renamed and its value left as it stands — pass the verdict, or \`null\` for a public response`,de={id:re,summary:"`createPreviewBindings({ authorized })` → `{ authorization }`",ledgerEntry:7,apply(e){const{Node:t}=u(),n=[],r=[],i=m(e).filter(e=>"createPreviewBindings"===e.imported);for(const o of i)for(const i of y(e,o)){const e=i.node.getParent();if("reference"!==i.kind||!t.isCallExpression(e))continue;if(e.getExpression()!==i.node)continue;const[o]=e.getArguments();if(void 0===o)continue;const s=o.getStartLineNumber();if(t.isObjectLiteralExpression(o))for(const e of o.getProperties())if(t.isSpreadAssignment(e))r.push({codemod:re,line:e.getStartLineNumber(),reason:`createPreviewBindings() spreads its options; ${se}`});else{if(w(e)!==ie)continue;if(t.isShorthandPropertyAssignment(e))n.push(x(e,`${oe}: ${ie}`)),r.push({codemod:re,line:e.getStartLineNumber(),reason:ae});else if(t.isPropertyAssignment(e)){const i=e.getInitializer();if(void 0!==i&&t.isFalseLiteral(i)){n.push(x(e,`${oe}: null`));continue}n.push(x(e.getNameNode(),oe)),r.push({codemod:re,line:e.getStartLineNumber(),reason:ae})}}else r.push({codemod:re,line:s,reason:`createPreviewBindings() options are not a literal; ${se}`})}return{edits:n,conflicts:r}}},le="rename-is-preview-request",ce="isPreviewRequest",ue="hasPreviewIntent";function he(e,t){return{codemod:le,reason:t,line:e}}function pe(e){return e.aliased&&e.local===ue?x(e.importedNode.getParentOrThrow(),ue):x(e.importedNode,ue)}var fe={id:le,summary:"`isPreviewRequest()` → `hasPreviewIntent()` (same signature)",ledgerEntry:1,notice:"hasPreviewIntent() takes the options isPreviewRequest() took and, without `signals`, counts the same three: a preview query parameter, Sec-Fetch-Dest: iframe and an admin Referer. The 2.0 adapters count only the query; where a call should agree with them, pass { signals: ['query'] } (docs/migration.md).",apply(e){const t=m(e).filter(e=>e.imported===ce),n=f(e).filter(e=>e.imported===ce);return 0===t.length&&0===n.length?{edits:[],conflicts:[]}:function(e,t,n){const r=[],i=[];for(const e of t)void 0===e.alias?r.push(he(e.line,`${ce} is re-exported straight from the package under its old name; write export { ${ue} as ${ce} } from '${e.specifier}', or rename it and its importers by hand`)):e.alias===ue?i.push(x(e.importedNode.getParentOrThrow(),ue)):i.push(x(e.importedNode,ue));const o=$(n,ue,e.map(e=>e.declaration));void 0!==o&&r.push(he(o.getStartLineNumber(),`this module already binds ${ue}; rename it (or drop the wrapper and import the package's ${ue} directly), then rename ${ce} by hand`));for(const t of e)if(i.push(pe(t)),!t.aliased)for(const e of y(n,t))"reference"===e.kind?i.push(x(e.node,ue)):"shorthand"===e.kind?r.push(he(e.node.getStartLineNumber(),`{ ${ce} } keeps the old key for whoever reads it; write { ${ce}: ${ue} } or rename the key and its readers by hand`)):r.push(he(e.node.getStartLineNumber(),`${ce} is re-exported under its old name; rename the export and its importers, or write export { ${ue} as ${ce} }`));const s=function(e,t){const{Node:n,SyntaxKind:r}=u();return e.getDescendantsOfKind(r.Identifier).filter(e=>{const r=e.getParent();return e.getText()===t&&n.isPropertyAccessExpression(r)&&r.getNameNode()===e})}(n,ce).map(e=>he(e.getStartLineNumber(),`.${ce} is a member of this module's own object, not the package import, and was left alone; check that it does not wrap the removed API`));return r.length>0?{edits:[],conflicts:[...r,...s]}:{edits:i,conflicts:s}}(t,n,e)}},me="rename-on-unbound-change",ge="onUnboundChange",ve="onUnfaithfulPatch",we={route:"escalate",ignore:"ignore"},ye={id:me,summary:"`onUnboundChange: 'route'` → `onUnfaithfulPatch: 'escalate'`",ledgerEntry:19,apply(e){const{Node:t}=u(),n=[],r=[];for(const[i,o]of L(e)){const e=T(i,ge);if(void 0===e)continue;const s=e.getStartLineNumber();if([i,...o.map(e=>e.outer)].some(e=>void 0!==T(e,ve))){r.push({codemod:me,line:s,reason:`both ${ge} and ${ve} are given; ${ve} wins, drop ${ge} by hand`});continue}const a=t.isPropertyAssignment(e)?e.getInitializer():void 0,d=void 0!==a&&t.isStringLiteral(a)?a.getLiteralText():"",l=we[d];if(void 0===a||void 0===l){r.push({codemod:me,line:s,reason:`${ge} is not a literal 'route' or 'ignore'; rename it to ${ve} by hand ('route' is 'escalate')`});continue}const c=a.getText().charAt(0);n.push(x(e,`${ve}: ${c}${l}${c}`))}for(const t of N(e,ge))r.push({codemod:me,line:t.getStartLineNumber(),reason:`a JSX attribute; rename ${ge} to ${ve} by hand ('route' is 'escalate')`});return{edits:n,conflicts:r}}},be={".ts":"ts",".mts":"ts",".cts":"ts",".tsx":"tsx",".js":"js",".mjs":"js",".cjs":"js",".jsx":"jsx"},$e=/* @__PURE__ */new Set([".astro",".vue",".svelte"]),Pe=/^---\r?\n([\s\S]*?)\r?\n---/u,xe=/<script(?:\s[^>]*)?>([\s\S]*?)<\/script\b[^>]*>/giu,Se=/(?:\bfrom\s*|\bimport\s*\(?\s*|\brequire\s*\(\s*)['"]payload-live-preview(?:\/[^'"]*)?['"]/u,ke=[fe,ne,de,Q,ye,U],Le=ke;function Ne(e,t){let n=1;for(let r=0;r<t;r+=1)"\n"===e[r]&&(n+=1);return n}function Te(e,t,n){const r=e.split("\n"),i=t.split("\n");let o=0;for(;o<r.length&&o<i.length&&r[o]===i[o];)o+=1;let s=0;for(;s<r.length-o&&s<i.length-o&&r[r.length-1-s]===i[i.length-1-s];)s+=1;const a=r.slice(o,r.length-s),d=i.slice(o,i.length-s),l=[];for(let e=0;e<Math.max(a.length,d.length);e+=1){const t=a[e]??"",r=d[e]??"";t!==r&&l.push({line:n+o+e,before:t,after:r})}return l}function Oe(e,t={}){const n=void 0===t.only?ke:ke.filter(e=>t.only?.includes(e.id));if(0===n.length||!function(e){return Se.test(e)}(e))return{output:e,edits:[],conflicts:[]};const i=/* @__PURE__ */new Map,o=[];let s="",a=0;for(const d of function(e,t){const n=r(t).toLowerCase();if(!$e.has(n))return[{start:0,end:e.length,kind:be[n]??"ts"}];const i=[],o=".astro"===n?Pe.exec(e):null;if(void 0!==o?.[1]){const e=o.index+o[0].indexOf("\n")+1;i.push({start:e,end:e+o[1].length,kind:"ts"})}for(const t of e.matchAll(xe)){const e=t[1]??"";if(""===e.trim())continue;const n=t.index+t[0].lastIndexOf(e);i.push({start:n,end:n+e.length,kind:"ts"})}return i}(e,t.fileName??"source.ts")){s+=e.slice(a,d.start);const t=Ne(e,d.start);let r=e.slice(d.start,d.end);for(const e of n){const n=e.apply(h(r,d.kind));for(const e of n.conflicts)o.push(void 0===e.line?e:{...e,line:e.line+t-1});if(0===n.edits.length)continue;const s=S(r,n.edits),a=i.get(e.id)??[];a.push(...Te(r,s,t)),i.set(e.id,a),r=s}s+=r,a=d.end}return s+=e.slice(a),{output:s,edits:[...i].map(([e,t])=>({codemod:e,count:t.length,lines:t})),conflicts:o}}var Ee=/* @__PURE__ */new Set([".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".astro",".svelte",".vue"]),Ae=/\.d\.[cm]?ts$/u,Re=/* @__PURE__ */new Set(["node_modules","dist",".git",".astro",".svelte-kit",".next",".nuxt","coverage"]);function je(e){return Ee.has(r(e))&&!Ae.test(e)}async function Ie(e){const t=[];return(await s(e)).isDirectory()?await async function e(r){for(const i of await a(r,{withFileTypes:!0})){const o=n(r,i.name);i.isDirectory()?Re.has(i.name)||await e(o):je(i.name)&&t.push(o)}}(e):je(e)&&t.push(e),t.sort()}function Ce(e,n){const r=t(e,n);return 0===r.length?n:r}var De=`pll migrate — rewrite 1.x APIs to their 2.0 names and homes (ADR 0007)\n\nUsage:\n pll migrate <path> [--write] [--only <id,id>]\n\nWithout --write the run only reports what it would change. Codemods touch\nonly names bound from payload-live-preview; anything they cannot rewrite\nsafely is listed as needing manual attention. Requires ts-morph.\n\nOptions:\n --write Apply the changes (otherwise dry-run)\n --only <ids> Run only these codemods (comma-separated); an id not\n listed below runs nothing\n -h, --help Show this help\n\nCodemods, in the order they run:\n${Le.map(e=>` ${e.id}`).join("\n")}\n\nExit codes:\n 0 nothing needs a human (changes applied, or would be with --write)\n 1 usage error, unreadable path, or ts-morph is not installed\n 3 at least one file needs manual attention\n`;function Ue(e){return e.edits.map(e=>`${e.codemod}: ${String(e.count)} line(s)`).join(", ")}var qe={error:"ERROR",warning:"WARN ",info:"INFO "},ze=Object.freeze({NoTrustedOrigin:"LP0101",ReferrerOnlyTrust:"LP0102",PluginIncompatible:"LP0103",ProfileFeatureOmitted:"LP0104",OrphanField:"LP0201",UnattributableUpdate:"LP0202",UnboundField:"LP0203",CoverageDefaultChanges:"LP0204",VisibilityGateDeferred:"LP0301",UnsafeAttributeWrite:"LP0401",TextTargetHasChildren:"LP0402",MissingArrayTemplate:"LP0403",StructuralItemUnkeyed:"LP0404",StructuralDuplicateKey:"LP0405",StructuralUnstableKeys:"LP0406",UnsupportedStrategy:"LP0407",UnknownValueFormat:"LP0408",SanitizerDroppedAttribute:"LP0409",UnrenderedBlockKept:"LP0410",UnfaithfulPatch:"LP0411",ServerFormatReplaced:"LP0412",UnrenderedBlockLost:"LP0413",MessageRejected:"LP0501",TokenRejected:"LP0502",ProtocolShapeUnknown:"LP0503",HandlerThrew:"LP0601",TransformThrew:"LP0602",RendererThrew:"LP0603",StartupFailed:"LP0605",ReadyFailed:"LP0606",HydrationWaitTimedOut:"LP0607",AuditRuntimeMissing:"LP0701",AuditNoFrameAncestors:"LP0702",AuditFrameOptionsBlocks:"LP0703",AuditBindingsExposed:"LP0704",AuditGateThresholdExceeded:"LP0705",AuditUnownedBindings:"LP0706",AuditNoBindings:"LP0707",AuditNotAPage:"LP0708",FragmentRequestFailed:"LP0801",FragmentResponseInvalid:"LP0802",FragmentUnauthorized:"LP0803",FragmentSuperseded:"LP0804",RouteRefreshLoop:"LP0805",FragmentStrategyUnavailable:"LP0806",UnboundChangeRefresh:"LP0807",EscalationUnavailable:"LP0808",IslandStartUnavailable:"LP0809",RouteRefreshUnconfirmed:"LP0810",V2ReadinessGap:"LP0709",RuntimeOnPublicPage:"LP0710",AuditModifierWithoutField:"LP0711"}),Fe={http:"80",https:"443",ws:"80",wss:"443"},_e=/^([a-z][a-z0-9+.-]*):$/u,Me=/^(?:([a-z][a-z0-9+.-]*):\/\/)?(\*|(?:\*\.)?[a-z0-9-]+(?:\.[a-z0-9-]+)*\.?)(?::(\*|\d+))?(?:\/.*)?$/u;function We(e){return e.protocol.slice(0,-1).toLowerCase()}function Ve(e){return""===e.port?Fe[We(e)]??"":e.port}function Be(e,t){return e===t||"http"===e&&"https"===t||"ws"===e&&"wss"===t}function Ke(e,t){if(e.hostname!==t.hostname)return!1;const n=We(e),r=We(t);return(n===r||"http"===r&&"https"===n)&&(Ve(e)===Ve(t)||""===e.port&&""===t.port)}function Ge(e,t,n){const r=_e.exec(e);if(void 0!==r?.[1])return Be(r[1],We(t));const i=Me.exec(e);if(null===i)return!1;const o=i[1],s=i[2]??"",a=i[3];return!!Be(o??We(n),We(t))&&!!function(e,t){if("*"===e)return!0;const n=e.replace(/\.$/u,""),r=t.replace(/\.$/u,"");return n.startsWith("*.")?r.endsWith(n.slice(1))&&r.length>n.length-1:n===r}(s,t.hostname)&&(void 0===a?""===t.port:"*"===a||a===Ve(t))}var He=["allowedOrigins","serverURL","apiRoute","mergeDepth","debug","debounceMs","enableA11y","heartbeatMs","disableVisibilityGate","visibilityGateThreshold","intersectionRootMargin","disableReferrerDetection","disableLocalhostMatching","scopeBindingsByOwner","skipUnchanged","eventSourcePolicy","sanitizerPolicy","fragmentEndpoint","revealEditedField","routeStrategy","onUnboundChange","onUnfaithfulPatch","autoBind","hydration","defaults","softNavigationEvents","subfieldCoverage","mergeTimeoutMs","internalLinkPattern"],Je=Object.freeze({disableReferrerDetection:!0,eventSourcePolicy:"parent-or-opener",skipUnchanged:!0,sanitizerPolicy:"strict"}),Qe=Object.freeze({disableReferrerDetection:!1,eventSourcePolicy:"any",skipUnchanged:!1,sanitizerPolicy:"compat"}),Xe="__LIVE_PREVIEW_CONFIG__",Ze=`var ${Xe}=`,Ye=/<!--[\s\S]*?-->|<script\b((?:[^>"']|"[^"]*"|'[^']*')*)>([\s\S]*?)<\/script\b[^>]*>/giu,et=/(?:^|\s)[iI][dD]\s*=\s*["']?__LIVE_PREVIEW_CONFIG__(?=["'\s]|$)/u,tt=/(?:^|\s)type\s*=\s*["']?application\/json(?=["'\s;]|$)/iu,nt=[{key:"disableReferrerDetection",title:"Referrer trust is still on",effect:"the runtime accepts the admin referer as a preview signal.",condition:"no preview flow relies on the admin referer alone"},{key:"eventSourcePolicy",title:"Messages are accepted from any window",effect:"any window that passes the origin check may post updates.",condition:"no window but the parent or opener posts updates"},{key:"sanitizerPolicy",title:"Sanitizer is in compat mode",effect:"id and every data-* pass.",condition:"rich text no longer relies on `id` or `data-*`"},{key:"skipUnchanged",title:"Unchanged bindings are re-applied every message",effect:"every binding is written again on every message.",condition:"no renderer relies on running again for a value that did not change"}],rt={profile:"The script was generated with `defaults: 'v1'`.",explicit:"The script sets it explicitly.",unmarked:"The script names no defaults, so its empty slot is read as the 1.x value."},it={code:"LP0709",level:"info",title:"Could not read the inline configuration for a v2 readiness check",detail:"The preview response carried no readable `__LIVE_PREVIEW_CONFIG__` inline script or JSON configuration element.",remedy:"Run this against a page with the inline runtime (not loader mode without a preview context). A preview behind authorizePreview serves it only to a request with credentials: pass them with --header, or a signed token as ?previewToken=… in the URL."},ot={code:"LP0709",level:"info",title:"The inline configuration does not say which defaults it was generated against",detail:"Scripts carry a `defaults` marker from 2.0.0-rc.1 on; this one has none, so a 1.x or 2.0.0-beta.0 generator wrote it. An empty slot is read as its 1.x value, which is what a 1.x runtime runs.",remedy:"On 1.x the warnings stand as written. On 2.0.0-beta.0 an empty slot already runs its 2.0 value, so a warning about one does not apply there; upgrade and run `pll doctor --v2` again to read the marker."};function st(e){if(!e.includes(Xe))return;const t=function(e){const t=[];for(const[,n,r]of e.matchAll(Ye))void 0!==n&&void 0!==r&&t.push({attributes:n,text:r});return t}(e),n=t.find(({text:e})=>e.includes(Ze)),r=void 0===n?void 0:function(e){const t=e.indexOf(Ze);if(-1===t)return;const n=t+Ze.length;if("["!==e[n])return;let r=0,i=!1,o="",s="";for(let t=n;t<e.length;t+=1){const n=e[t]??"";if(i)s+=n,"\\"===n?(s+=e[t+1]??"",t+=1):'"'===n&&(i=!1,o='"');else if('"'!==n){if(!/\s/u.test(n)&&((","===n&&(","===o||"["===o)||"]"===n&&","===o)&&(s+="null"),s+=n,o=n,"["===n&&(r+=1),"]"===n&&(r-=1,0===r)))break}else i=!0,s+=n}if(0===r)try{const e=JSON.parse(s);return Array.isArray(e)?e:void 0}catch{return}}(n.text);if(void 0!==r)return{source:"inline",value:e=>r[He.indexOf(e)]??void 0};const i=function(e){for(const{attributes:t,text:n}of e)if(et.test(t)){if(!tt.test(t))return;try{const e=JSON.parse(n);return"object"!=typeof e||null===e||Array.isArray(e)?void 0:e}catch{return}}}(t);return void 0!==i?{source:"element",value:e=>Object.hasOwn(i,e)?i[e]??void 0:void 0}:void 0}function at(e){return"string"==typeof e?`'${e}'`:JSON.stringify(e)}function dt(e,t,n){const r=`\`${t.key}: ${at(Je[t.key])}\``;switch(e){case"profile":return`Set ${r} or drop \`defaults: 'v1'\` once ${t.condition}. 3.0 removes the profile; \`pll migrate\` writes its rows out, so each can go on its own.`;case"explicit":return`Drop the explicit \`${t.key}: ${at(n)}\` once ${t.condition}; 2.0 defaults to ${r}.`;case"unmarked":return`Upgrading to 2.0 sets ${r}; check first that ${t.condition}.`}}function lt(e,t,n){return{code:"LP0709",level:"warning",title:e.title,detail:`${e.key} is ${at(t)}: ${e.effect} ${rt[n]}`,remedy:dt(n,e,t)}}function ct(e){return{code:"LP0709",level:"info",title:"The inline configuration names defaults this doctor does not know",detail:`Its \`defaults\` marker is ${JSON.stringify(e)}; this version reads 'v1' and 'v2', so no row was judged.`,remedy:"Run the `pll doctor` of the package version that generated the page."}}var ut="__LIVE_PREVIEW_CONFIG__",ht=/<[a-zA-Z](?:"[^"]*"|'[^']*'|[^"'<>])*>/gu,pt=/([^\s"'>/=]+)(\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/gu,ft={error:0,warning:1,info:2},mt=/<script\b[^>]*>[\s\S]*?<\/script\b[^>]*>|<style\b[^>]*>[\s\S]*?<\/style\b[^>]*>|<!--[\s\S]*?-->/giu;function gt(e){let t=e;for(;;){const e=t.replace(mt,"");if(e===t)return t;t=e}}var vt=new Set(["type","attribute","href","src","alt","richtext","html","text","array","array-template","array-separator","structural","locale","format","boundary"].map(e=>`data-payload-${e}`));function wt(e){const t=[];for(const n of e.matchAll(ht))for(const[,e="",r,i,o,s]of n[0].matchAll(pt))void 0!==r&&t.push({name:e.toLowerCase(),value:i??o??s??"",at:n.index});return t}function yt(e,t){return e.filter(e=>e.name===t)}function bt(e){if(void 0!==e)try{return new URL(e)}catch{return}}function $t(e,t){const{publicResponse:n,previewResponse:r}=e,i=function(e){if(e.status>=300&&e.status<=399){const t=e.headers.location;return{code:"LP0708",level:"error",title:`The preview request was redirected (${String(e.status)})${void 0===t?"":` to ${t}`}`,detail:"The audit does not follow redirects: the page at the end of one is a different resource, usually a login or a canonical host, and judging it would say nothing about this URL.",remedy:"The request carried the intent parameter (?preview=true, or the --param name), the way the admin's iframe loads the page, so a rule that redirects on that query redirects the iframe too. A redirect to a login means the route needs authentication that a plain probe cannot supply: pass an editor's credentials with --header, or a signed token as ?previewToken=… in the URL. Probe the final URL directly only when the redirect has nothing to do with either."}}if(e.status<200||e.status>299)return{code:"LP0708",level:"error",title:`The preview request returned ${String(e.status)}, not a page`,detail:"Nothing below this can be judged: a status outside 2xx means the body is an error page or empty.",remedy:"Check the URL."};if(""===e.body.trim())return{code:"LP0708",level:"error",title:`The preview request returned ${String(e.status)} with an empty body`,detail:"A 2xx status with nothing in it — 204 and 205 are defined that way — is not a page, so its missing runtime and missing bindings say nothing.",remedy:"Point the audit at a route that renders a document."};const t=e.headers["content-type"];return void 0===t||t.toLowerCase().includes("html")?void 0:{code:"LP0708",level:"error",title:`The preview request returned ${t}, not HTML`,detail:"The audit reads a rendered page. A non-HTML response has no runtime and no bindings by definition, so reporting their absence would say nothing.",remedy:"Point the audit at a page route rather than an API or an asset."}}(r);if(void 0!==i)return{url:t.url,findings:[i],errors:1,warnings:0};const o=r.body.includes(ut),s=[];if(o||s.push(!0===t.credentials?{code:"LP0701",level:"warning",title:"No inline runtime in the preview response",detail:`The preview request returned ${String(r.status)} without the inline runtime, although it carried credentials (--header, or ?previewToken= in the URL). Three readings: those credentials were not accepted — expired, issued for another page, or not what authorizePreview reads — an adapter that did not recognise the request as a preview, or a consumer that starts LivePreviewClient itself.`,remedy:"Check that the credentials are current and are the ones authorizePreview reads; if you use an adapter, check its inject mode and previewSignals. If you start the client yourself, this line is expected."}:{code:"LP0701",level:"warning",title:"No inline runtime in the preview response",detail:`The preview request returned ${String(r.status)} without the inline runtime. Three readings, and this audit cannot tell them apart from the response alone: a preview behind authorizePreview — the strict 2.0 default — which answers a request without credentials exactly like this, an adapter that did not recognise the request as a preview, or a consumer that starts LivePreviewClient itself.`,remedy:"To audit a gated preview, send what an editor's browser sends: --header 'Cookie: payload-token=…' for a Payload session; for a signed token, the URL with ?previewToken=… (the default transport, dropped from the visitor request), or --header 'x-preview-token: …' where the strategy sets transport: { kind: 'header' }. Otherwise check the adapter's inject mode and previewSignals; if you start the client yourself, this line is expected."}),s.push(...function(e,t,n){const r=[],i=bt(n.url),o=bt(n.adminOrigin),s=void 0!==o&&i?.origin===o.origin,a=function(e){if(void 0!==e)for(const t of e.split(";")){const e=t.trim();if(/^frame-ancestors(?:\s|$)/iu.test(e))return e}}(e.headers["content-security-policy"]);if(t&&void 0===a)r.push({code:"LP0702",level:"warning",title:"Preview response declares no frame-ancestors",detail:"The runtime is injected but the response carries no frame-ancestors directive, so nothing states which origins may embed this page.",remedy:"Let the adapter manage CSP, or set frame-ancestors yourself to the admin origin. Without it you are relying on the absence of a policy."});else if(void 0!==a&&void 0!==n.adminOrigin){const e=void 0!==o&&void 0!==i&&function(e,t,n){const r=e.split(/\s+/u).slice(1).filter(e=>e.length>0).map(e=>e.toLowerCase());if(0===r.length||1===r.length&&"'none'"===r[0])return!1;for(const e of r)if("'self'"===e){if(Ke(t,n))return!0}else{if("*"===e)return!0;if(!e.startsWith("'")&&Ge(e,t,n))return!0}return!1}(a,o,i);e||r.push({code:"LP0702",level:"error",title:"frame-ancestors does not admit the admin origin",detail:void 0===o?`"${n.adminOrigin}" is not an absolute URL, so no source expression can admit it.`:`Served: "${a}". Expected it to allow ${o.origin}.`,remedy:"Add the admin origin to allowedOrigins so the adapter merges it into frame-ancestors, or add it to your own policy."})}const d=e.headers["x-frame-options"];if(void 0!==d&&void 0===a&&(/deny/iu.test(d)||/sameorigin/iu.test(d)&&!s)){const e=void 0!==o||/deny/iu.test(d);r.push(e?{code:"LP0703",level:"error",title:`X-Frame-Options: ${d} blocks the preview iframe`,detail:"This header is older than CSP. A browser applies it to a response that has no frame-ancestors directive, and this response has no frame-ancestors.",remedy:"Remove X-Frame-Options for preview responses, or serve a frame-ancestors directive that admits the admin: the header is then ignored. It is usually set by a proxy or a security middleware rather than by the app."}:{code:"LP0703",level:"warning",title:`X-Frame-Options: ${d} blocks every frame from another origin`,detail:"This header is older than CSP. A browser applies it to a response that has no frame-ancestors directive, and this response has no frame-ancestors. SAMEORIGIN refuses a frame from another origin only, and no admin origin was given: whether it blocks this preview depends on where the admin is served, which this probe cannot see.",remedy:"Re-run with --admin <origin> to have it judged. If the admin is on another origin, remove X-Frame-Options for preview responses or serve a frame-ancestors directive that admits it; a proxy or a security middleware usually sets the header."})}return r}(r,o,t)),s.push(...function(e,t,n,r){const i=[],o=wt(e),s=yt(o,"data-payload-field").length,a=yt(wt(t),"data-payload-field").length,d=yt(o,"data-payload-owner").length,l=yt(o,"data-payload-fragment").filter(e=>e.value.length>0).length;a>0&&i.push({code:"LP0704",level:"warning",title:`${String(a)} binding attribute(s) served to anonymous visitors`,detail:"A request with no preview intent received data-payload-field attributes. These disclose the CMS field taxonomy, and any CSS keyed on them changes public layout the moment emission is gated.",remedy:"Gate binding emission on an authorized preview context — see createPreviewBindings(), whose suppressed form emits nothing at all."});const c=function(e){const t=new Set(yt(e,"data-payload-field").map(e=>e.at)),n=/* @__PURE__ */new Map;for(const{name:r,at:i}of e)!vt.has(r)||t.has(i)||n.has(i)||n.set(i,r);return[...n.values()]}(o);c.length>0&&i.push({code:"LP0711",level:"warning",title:`${String(c.length)} element(s) carry ${c[0]??""} or the like without a field`,detail:"The runtime reads these attributes only on a bound element, so they do nothing here, and it says nothing about them either.",remedy:"Add data-payload-field to the element, or remove them."}),void 0!==r.threshold&&s>r.threshold&&i.push({code:"LP0705",level:"warning",title:`${String(s)} bindings exceed the ${r.configured?"configured":"default"} visibility gate`,detail:`Above visibilityGateThreshold (${String(r.threshold)}) the scheduler stops writing offscreen elements and buffers them until they scroll into view. On a page nobody scrolls, that is never.`,remedy:"Raise visibilityGateThreshold, or set disableVisibilityGate, on the adapter, LivePreviewClient or generateInlineScript() if the whole page must stay live, or confirm that deferring below the fold is acceptable here."}),n&&0===s&&0===l&&i.push({code:"LP0707",level:"error",title:"Preview response carries no bindings",detail:"The runtime is present but there is not one data-payload-field element for it to write into and not one data-payload-fragment boundary for a server to render, so no edit can ever be visible on this page.",remedy:"Add binding attributes or fragment boundaries to the markup. pll-codegen --inventory lists every field the schema makes addressable."});const u=function(e){const t=yt(e,"data-payload-owner")[0];return void 0===t?0:yt(e,"data-payload-field").filter(e=>e.at<t.at).length}(o);return d>0&&u>0&&i.push({code:"LP0706",level:"warning",title:`${String(u)} binding(s) outside every owner marker`,detail:`The page declares ${String(d)} owner marker(s), so owner scoping is in use. Bindings that belong to no owner receive nothing once scopeBindingsByOwner is on — they fail closed.`,remedy:"Give every binding an owning ancestor, or leave scopeBindingsByOwner off until they all have one. Counted before the first owner marker only, so the real number may be higher."}),i}(gt(r.body),gt(n.body),o,function(e){const t=st(e);if(!0===t?.value("disableVisibilityGate"))return{threshold:void 0,configured:!0};const n=t?.value("visibilityGateThreshold");return"number"==typeof n?{threshold:n,configured:!0}:{threshold:50,configured:!1}}(r.body))),n.body.includes(ut)){const e=n.body.includes(`var ${ut}=`);s.push({code:ze.RuntimeOnPublicPage,level:"info",title:e?"Runtime is also served to anonymous visitors":"Preview configuration is also served to anonymous visitors",detail:e?"A request with no preview intent received the inline runtime. That is correct for inject: 'always' and unintended for 'preview-only'.":"A request with no preview intent received the configuration element a page writes for a client it starts itself. That is correct if the page starts the client for every request, and unintended if it writes the element only for a preview.",remedy:""})}return!0===t.v2&&s.push(...function(e){const t=st(e.previewResponse.body);if(void 0===t)return[it];const n=t.value("defaults");if(void 0!==n&&"v1"!==n&&"v2"!==n)return[ct(n)];const r=n??("element"===t.source?"v2":void 0),i="v2"===r?Je:Qe,o=nt.flatMap(e=>{const n=t.value(e.key),o=n??i[e.key];return o===Je[e.key]?[]:[lt(e,o,"v1"===r?"profile":void 0===n?"unmarked":"explicit")]});return void 0===r?[...o,ot]:o}(e)),s.sort((e,t)=>ft[e.level]-ft[t.level]),{url:t.url,findings:s,errors:s.filter(e=>"error"===e.level).length,warnings:s.filter(e=>"warning"===e.level).length}}var Pt=["preview","draft","livePreview"];function xt(e){const t=e.indexOf("#"),n=-1===t?"":e.slice(t),r=-1===t?e:e.slice(0,t),i=r.indexOf("?");return-1===i?{base:r,parts:[],hash:n}:{base:r.slice(0,i),parts:r.slice(i+1).split("&"),hash:n}}function St(e){const t=e.indexOf("="),n=e=>{try{return decodeURIComponent(e.replace(/\+/gu," "))}catch{return e}};return-1===t?[n(e),""]:[n(e.slice(0,t)),n(e.slice(t+1))]}var kt="previewToken";function Lt(e,t=kt){const{base:n,parts:r,hash:i}=xt(e),o=r.map(e=>{const n=e.indexOf("=");return-1===n||St(e)[0]!==t?e:`${e.slice(0,n)}=…`});return o.some((e,t)=>e!==r[t])?`${n}?${o.join("&")}${i}`:e}function Nt(e,t){return xt(e).parts.some(e=>{const[n,r]=St(e);return n===t&&""!==r})}function Tt(e){const t={};return e.forEach((e,n)=>{t[n.toLowerCase()]=e}),t}async function Ot(e,t){const n=e.body?.getReader();if(void 0===n)return e.text();const r=new TextDecoder;let i=0,o="";for(;;){const{done:e,value:s}=await n.read();if(e)break;if(i+=s.byteLength,i>t)throw await n.cancel(),new Error(`the response body exceeds ${String(t)} bytes, which is not a page the audit can judge`);o+=r.decode(s,{stream:!0})}return o+r.decode()}function Et(e){try{return new URL(e).href}catch{return`${e.replace(/\/+$/u,"")}/`}}var At=/^[^\s&=#?-][^\s&=#]*$/u,Rt=/^([!#$%&'*+.^_`|~0-9A-Za-z-]+):[ \t]*(.*)$/u,jt=/^[A-Za-z_][A-Za-z0-9_]*$/u;function It(e,t,n='pll doctor: --header takes "Name: value", such as --header "Cookie: payload-token=…"'){const r=void 0===t||t.startsWith("-")||zt(t)?null:Rt.exec(t),i=r?.[1],o=r?.[2];void 0!==i&&void 0!==o?Object.keys(e.headers).some(e=>e.toLowerCase()===i.toLowerCase())?e.usageError??=`pll doctor: --header "${i}" is given twice; join the values into one header`:e.headers[i]=o:e.usageError??=n}function Ct(e,t){if(void 0===t||!jt.test(t))return void(e.usageError??='pll doctor: --header-env takes the name of an environment variable that holds "Name: value", such as --header-env PLP_DOCTOR_HEADER');const n=process.env[t];void 0!==n&&""!==n?It(e,n,`pll doctor: --header-env ${t} must hold "Name: value", such as "Cookie: payload-token=…"`):e.usageError??=`pll doctor: --header-env ${t}: the variable is not set`}function Dt(e,t){void 0!==t&&At.test(t)?e.params.push(t):e.usageError??="pll doctor: --param takes a query parameter name, such as --param draft"}function Ut(e,t){void 0!==t&&At.test(t)?e.tokenParam=t:e.usageError??="pll doctor: --token-param takes a query parameter name, such as --token-param lpt"}var qt='pll doctor — audit what a live-preview deployment actually serves\npll migrate — rewrite 1.x APIs to their 2.0 names and homes\n\nUsage:\n pll doctor <url> [--admin <origin>] [--header <name: value>]... [--header-env <var>]...\n [--param <name>]... [--token-param <name>] [--json] [--v2]\n pll migrate <path> [--write] [--only <id,id>]\n\nThe URL is fetched twice: once as an ordinary visitor, without any intent\nparameter, and once the way the Payload admin\'s iframe loads it, with\n?preview=true and the iframe\'s headers.\nMost findings come from the difference between the two responses. Redirects\nare reported, not followed.\n\nOptions of pll doctor:\n -a, --admin <origin> Admin origin the preview is embedded from. Enables the\n frame-ancestors check to verify the origin is admitted,\n not merely that a policy exists.\n -H, --header <h> A header for the preview request only, as "Name: value";\n repeat it for more. A preview behind authorizePreview\n needs an editor\'s credentials: a Payload session Cookie,\n or an x-preview-token where the token strategy sets\n transport: { kind: \'header\' }. A signed token travels in\n the URL by default, as ?previewToken=…, which the visitor\n request drops. The visitor request stays anonymous and\n values are never printed, but a shell keeps them in its\n history, so prefer a short-lived token.\n --header-env <var>\n Like --header, with "Name: value" read from the\n environment variable <var>; repeat it for more. The\n shell puts a --header value into the doctor\'s command\n line, which other users of the host can read while it\n runs; the environment only the doctor\'s owner can.\n --param <name> A query parameter the deployment reads as preview intent,\n for an adapter whose previewQueryParams replaces the\n default preview, draft and livePreview; repeat it for\n more. The first one is what the preview request carries\n as <name>=true; none of them reaches the visitor request.\n --token-param <n> The query parameter the signed-token strategy reads,\n where its transport names one other than previewToken.\n Treated like previewToken: dropped from the visitor\n request, counted as the credential, never printed.\n --json Emit the report as JSON instead of text\n --v2 Also check the page against the 2.0 readiness table\n -h, --help Show this help\n\nExit codes of pll doctor:\n 0 no error-level findings\n 1 usage error, or the URL could not be fetched\n 2 at least one error-level finding\n\npll migrate has its own options and exit codes: pll migrate --help\n\nExamples:\n pll doctor https://example.com/\n pll doctor https://example.com/blog/hello --admin https://cms.example.com\n pll doctor "https://example.com/?previewToken=$PREVIEW_TOKEN" --v2\n pll doctor https://example.com/ --header "Cookie: payload-token=$PAYLOAD_TOKEN"\n PLP_DOCTOR_HEADER="Cookie: payload-token=$PAYLOAD_TOKEN" \\\n pll doctor https://example.com/ --header-env PLP_DOCTOR_HEADER\n';function zt(e){try{return"null"!==new URL(e).origin}catch{return!1}}async function Ft(e,t){const[n,...r]=e;if(void 0===n||"-h"===n||"--help"===n)return process.stdout.write(qt),void 0===n?1:0;if("migrate"===n)return async function(e){const t=function(e){let t,n,r,i=!1,o=!1;const s=e=>e.split(",").filter(e=>e.length>0);for(let a=0;a<e.length;a+=1){const d=e[a];void 0!==d&&("-h"===d||"--help"===d?o=!0:"--write"===d?i=!0:"--only"===d?(n=s(e[a+1]??""),a+=1):d.startsWith("--only=")?n=s(d.slice(7)):d.startsWith("-")?r??=d:t??=d)}return{target:t,write:i,only:n,help:o,unknown:r}}(e);if(t.help)return process.stdout.write(De),0;if(void 0!==t.unknown)return process.stderr.write(`pll migrate: unknown option ${t.unknown}\n`),1;if(void 0===t.target)return process.stderr.write("pll migrate: a path is required. Try `pll migrate --help`.\n"),1;let n;try{n=await async function(e,t={}){const n=t.io??{read:e=>o(e,"utf8"),write:(e,t)=>i(e,t,"utf8"),list:Ie},r=[],s={};for(const i of await n.list(e)){const o=await n.read(i),{output:a,edits:d,conflicts:l}=Oe(o,{fileName:i,...void 0===t.only?{}:{only:t.only}}),c=a!==o;if(c&&!0===t.write&&await n.write(i,a),c)for(const e of d)s[e.codemod]=(s[e.codemod]??0)+1;r.push({file:Ce(e,i),edits:d,changed:c,conflicts:l})}return{files:r,changedCount:r.filter(e=>e.changed).length,byCodemod:s,conflictCount:r.filter(e=>e.conflicts.length>0).length}}(t.target,{write:t.write,...void 0===t.only?{}:{only:t.only}})}catch(e){return process.stderr.write(`pll migrate: ${e instanceof Error?e.message:String(e)}\n`),1}for(const e of n.files)e.changed&&process.stdout.write(`${t.write?"migrated":"would migrate"} ${e.file} (${Ue(e)})\n`);process.stdout.write(`\n${t.write?"Migrated":"Would migrate"} ${String(n.changedCount)} file(s).${t.write?"":" Re-run with --write to apply."}\n`);for(const{id:e,notice:t}of Le)void 0!==t&&(n.byCodemod[e]??0)>0&&process.stdout.write(`\nNote (${e}): ${t}\n`);const r=n.files.filter(e=>e.conflicts.length>0);if(0===r.length)return 0;process.stdout.write(`\n${String(r.length)} file(s) need manual attention:\n`);for(const e of r)for(const t of e.conflicts){const n=void 0===t.line?e.file:`${e.file}:${String(t.line)}`;process.stdout.write(` ${n}: ${t.reason}\n`)}return 3}(r);if("doctor"!==n)return process.stderr.write(`pll: unknown command "${n}". Try \`pll --help\`.\n`),1;const s=function(e){const t={url:void 0,adminOrigin:void 0,json:!1,v2:!1,showHelp:!1,unknown:[],headers:{},usageError:void 0,params:[],tokenParam:void 0};for(let n=0;n<e.length;n+=1){const r=e[n];void 0!==r&&("-h"===r||"--help"===r?t.showHelp=!0:"--json"===r?t.json=!0:"--v2"===r?t.v2=!0:"--admin"===r||"-a"===r?(t.adminOrigin=e[n+1],n+=1):r.startsWith("--admin=")?t.adminOrigin=r.slice(8):"--header"===r||"-H"===r?(It(t,e[n+1]),n+=1):r.startsWith("--header=")?It(t,r.slice(9)):"--header-env"===r?(Ct(t,e[n+1]),n+=1):r.startsWith("--header-env=")?Ct(t,r.slice(13)):"--param"===r?(Dt(t,e[n+1]),n+=1):r.startsWith("--param=")?Dt(t,r.slice(8)):"--token-param"===r?(Ut(t,e[n+1]),n+=1):r.startsWith("--token-param=")?Ut(t,r.slice(14)):r.startsWith("-")?t.unknown.push(r):t.url??=r)}return t}(r);if(s.showHelp)return process.stdout.write(qt),0;if(s.unknown.length>0)return process.stderr.write(`pll doctor: unknown option ${s.unknown.join(", ")}\n`),1;if(void 0===s.url)return process.stderr.write("pll doctor: a URL is required. Try `pll doctor --help`.\n"),1;if(void 0!==s.usageError)return process.stderr.write(`${s.usageError}\n`),1;if(void 0!==s.adminOrigin&&!zt(s.adminOrigin))return process.stderr.write(`pll doctor: --admin must be an absolute URL such as https://cms.example.com (got "${s.adminOrigin}")\n`),1;let a;try{a=await async function(e){const t=e.fetchImpl??function(e={}){const t=e.timeoutMs??15e3,n=e.maxBodyBytes??10485760;return async(r,i)=>{const o=e.fetchFn??globalThis.fetch;let s;try{s=await o(r,{headers:i.headers,redirect:"manual",signal:AbortSignal.timeout(t)})}catch(e){if(e instanceof Error&&"TimeoutError"===e.name)throw new Error(`no response within ${String(t/1e3)} s`,{cause:e});throw e}return{status:s.status,headers:Tt(s.headers),body:await Ot(s,n)}}}(),n=void 0===e.previewQueryParams||0===e.previewQueryParams.length?Pt:e.previewQueryParams,r=e.tokenQueryParam??kt,i=await t(function(e,t,n){const{base:r,parts:i,hash:o}=xt(e),s=/* @__PURE__ */new Set([...t,n]),a=i.filter(e=>!s.has(St(e)[0]));return a.length===i.length?e:`${r}${0===a.length?"":`?${a.join("&")}`}${o}`}(e.url,n,r),{headers:{Accept:"text/html","Sec-Fetch-Dest":"document","Sec-Fetch-Mode":"navigate"}}),o={Accept:"text/html","Sec-Fetch-Dest":"iframe","Sec-Fetch-Mode":"navigate",...void 0===e.adminOrigin?{}:{Referer:Et(e.adminOrigin)}},s=function(e,t){const n=new Set(Object.keys(t).map(e=>e.toLowerCase()));return Object.fromEntries(Object.entries(e??{}).filter(([e])=>!n.has(e.toLowerCase())))}(e.previewHeaders,o),a=await t(function(e,t){const{base:n,parts:r,hash:i}=xt(e);if(r.some(e=>{const[n,r]=St(e);return t.includes(n)&&function(e){return"true"===e||"1"===e}(r)}))return e;const o=r.join("&"),s=""===o?"?":o.endsWith("&")?"":"&",a=`${encodeURIComponent(t[0]??"preview")}=true`;return`${n}${0===r.length?"?":`?${o}${s}`}${a}${i}`}(e.url,n),{headers:{...s,...o}});return $t({publicResponse:i,previewResponse:a},{url:Lt(e.url,r),adminOrigin:e.adminOrigin,...!0===e.v2?{v2:!0}:{},...Object.keys(s).length>0||Nt(e.url,r)?{credentials:!0}:{}})}({url:s.url,...void 0!==s.adminOrigin?{adminOrigin:s.adminOrigin}:{},...s.v2?{v2:!0}:{},...Object.keys(s.headers).length>0?{previewHeaders:s.headers}:{},...s.params.length>0?{previewQueryParams:s.params}:{},...void 0===s.tokenParam?{}:{tokenQueryParam:s.tokenParam},...void 0!==t?{fetchImpl:t}:{}})}catch(e){const t=function(e){if(!(e instanceof Error))return String(e);const t=e.cause;return t instanceof Error&&""!==t.message&&!e.message.includes(t.message)?`${e.message} (${t.message})`:e.message}(e),n=Lt(s.url,s.tokenParam);return s.json?process.stdout.write(`${JSON.stringify({url:n,error:t},void 0,2)}\n`):process.stderr.write(`pll doctor: could not probe ${n}: ${t}\n`),1}return process.stdout.write(s.json?`${JSON.stringify(a,void 0,2)}\n`:function(e){const t=[`pll doctor — ${e.url}`,""];if(0===e.findings.length)return t.push("No findings. The preview response carries the runtime, a frame-ancestors"),t.push("policy, and bindings; the public response carries none of them.",""),t.join("\n");for(const n of e.findings)t.push(`${qe[n.level]} ${n.code} ${n.title}`),t.push(` ${n.detail}`),""!==n.remedy&&t.push(` → ${n.remedy}`),t.push("");return t.push(`${String(e.errors)} error(s), ${String(e.warnings)} warning(s).`,""),t.join("\n")}(a)),a.errors>0?2:0}function _t(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"===n||"pll.cmd"===n||n.startsWith("doctor-cli")}_t()&&Ft(process.argv.slice(2)).then(e=>{process.exit(e)});export{_t as isCliInvocation,Ft as run};
3
3
  //# sourceMappingURL=doctor-cli.js.map