payload-live-preview 2.0.0 → 2.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/README.md +41 -34
  2. package/dist/adapters/astro/RichText.astro +1 -1
  3. package/dist/adapters/astro/index.d.ts +8 -8
  4. package/dist/adapters/astro/index.js +1 -1
  5. package/dist/adapters/astro/index.js.map +1 -1
  6. package/dist/adapters/astro/middleware-entry.d.ts +3 -3
  7. package/dist/adapters/astro/middleware-entry.js +1 -1
  8. package/dist/adapters/astro/middleware-entry.js.map +1 -1
  9. package/dist/adapters/nextjs/index.d.ts +2 -2
  10. package/dist/adapters/nextjs/index.js +1 -1
  11. package/dist/adapters/nextjs/index.js.map +1 -1
  12. package/dist/adapters/nuxt/index.d.ts +4 -4
  13. package/dist/adapters/nuxt/index.js +1 -1
  14. package/dist/adapters/nuxt/index.js.map +1 -1
  15. package/dist/adapters/nuxt/module.d.ts +13 -5
  16. package/dist/adapters/nuxt/module.js.map +1 -1
  17. package/dist/adapters/react/index.d.ts +8 -6
  18. package/dist/adapters/react/index.js.map +1 -1
  19. package/dist/adapters/sveltekit/index.d.ts +5 -5
  20. package/dist/adapters/sveltekit/index.js +1 -1
  21. package/dist/adapters/sveltekit/index.js.map +1 -1
  22. package/dist/adapters/vue/index.d.ts +3 -3
  23. package/dist/adapters/vue/index.js.map +1 -1
  24. package/dist/annotate.js +1 -1
  25. package/dist/annotate.js.map +1 -1
  26. package/dist/client.cjs +1 -1
  27. package/dist/client.cjs.map +1 -1
  28. package/dist/client.js +1 -1
  29. package/dist/client.js.map +1 -1
  30. package/dist/codegen-astro.d.ts +4 -1
  31. package/dist/codegen-astro.js.map +1 -1
  32. package/dist/codegen-cli.js +1 -1
  33. package/dist/codegen-cli.js.map +1 -1
  34. package/dist/codegen.cjs +1 -1
  35. package/dist/codegen.cjs.map +1 -1
  36. package/dist/codegen.js +1 -1
  37. package/dist/codegen.js.map +1 -1
  38. package/dist/core.cjs +1 -1
  39. package/dist/core.cjs.map +1 -1
  40. package/dist/core.d.cts +1 -1
  41. package/dist/core.d.ts +1 -1
  42. package/dist/core.js +1 -1
  43. package/dist/core.js.map +1 -1
  44. package/dist/doctor-cli.d.ts +1 -1
  45. package/dist/doctor-cli.js +1 -1
  46. package/dist/doctor-cli.js.map +1 -1
  47. package/dist/doctor.d.ts +4 -2
  48. package/dist/doctor.js +1 -1
  49. package/dist/doctor.js.map +1 -1
  50. package/dist/{fragment-endpoint-3Mlz7GDz.d.ts → fragment-endpoint-DATKU183.d.ts} +2 -2
  51. package/dist/fragment.cjs.map +1 -1
  52. package/dist/fragment.d.cts +6 -3
  53. package/dist/fragment.d.ts +6 -3
  54. package/dist/fragment.js.map +1 -1
  55. package/dist/index.cjs +1 -1
  56. package/dist/index.cjs.map +1 -1
  57. package/dist/index.d.cts +10 -10
  58. package/dist/index.d.ts +10 -10
  59. package/dist/index.js +1 -1
  60. package/dist/index.js.map +1 -1
  61. package/dist/lean.cjs +1 -1
  62. package/dist/lean.cjs.map +1 -1
  63. package/dist/lean.d.cts +3 -3
  64. package/dist/lean.d.ts +3 -3
  65. package/dist/lean.js +1 -1
  66. package/dist/lean.js.map +1 -1
  67. package/dist/lexical.cjs +1 -1
  68. package/dist/lexical.cjs.map +1 -1
  69. package/dist/lexical.d.cts +11 -1
  70. package/dist/lexical.d.ts +11 -1
  71. package/dist/lexical.js +1 -1
  72. package/dist/lexical.js.map +1 -1
  73. package/dist/{locals-DBXDMxOA.d.ts → locals-CNUGYbA_.d.ts} +1 -1
  74. package/dist/{middleware-Bx9I7PXW.d.ts → middleware-CWObDO37.d.ts} +2 -2
  75. package/dist/migrate.d.ts +6 -0
  76. package/dist/migrate.js +1 -1
  77. package/dist/migrate.js.map +1 -1
  78. package/dist/{options-BW1eqXvc.d.ts → options-uHKrDM2U.d.ts} +2 -1
  79. package/dist/plugins.cjs +1 -1
  80. package/dist/plugins.cjs.map +1 -1
  81. package/dist/plugins.js +1 -1
  82. package/dist/plugins.js.map +1 -1
  83. package/dist/{probe-CELeUciC.d.ts → probe-DqaItcwX.d.ts} +15 -0
  84. package/dist/server.cjs.map +1 -1
  85. package/dist/server.d.cts +1 -1
  86. package/dist/server.d.ts +1 -1
  87. package/dist/server.js.map +1 -1
  88. package/dist/structural.cjs +2 -2
  89. package/dist/structural.cjs.map +1 -1
  90. package/dist/structural.js +2 -2
  91. package/dist/structural.js.map +1 -1
  92. package/package.json +6 -4
package/dist/migrate.js CHANGED
@@ -1,2 +1,2 @@
1
- import{createRequire as e}from"module";import{extname as t}from"path";var n,i,o="payload-live-preview";function r(){if(void 0===n)try{n=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 n}function s(e,t){const n=r();return i??=new n.Project({useInMemoryFileSystem:!0,skipLoadingLibFiles:!0,skipFileDependencyResolution:!0,compilerOptions:{allowJs:!0,noLib:!0}}),i.createSourceFile(`/script.${t}`,e,{overwrite:!0})}function a(e){return e===o||e.startsWith(`${o}/`)}function d(e){const{Node:t,SyntaxKind:n}=r(),i=[];for(const t of e.getImportDeclarations()){const e=t.getModuleSpecifierValue();if(a(e))for(const n of t.getNamedImports()){const o=n.getAliasNode(),r=o??n.getNameNode();i.push({imported:n.getName(),local:r.getText(),specifier:e,kind:"import",importedNode:n.getNameNode(),aliased:void 0!==o,symbol:r.getSymbol(),declaration:t})}}for(const o of e.getDescendantsOfKind(n.VariableDeclaration)){const e=c(o.getInitializer()),n=o.getNameNode();if(void 0!==e&&a(e)&&t.isObjectBindingPattern(n))for(const r of n.getElements()){const n=r.getNameNode();if(!t.isIdentifier(n))continue;const s=r.getPropertyNameNode();i.push({imported:void 0===s?n.getText():l(s),local:n.getText(),specifier:e,kind:"require",importedNode:s??n,aliased:void 0!==s,symbol:n.getSymbol(),declaration:o})}}return i}function c(e){const{Node:t,SyntaxKind:n}=r(),i=void 0!==e&&t.isAwaitExpression(e)?e.getExpression():e;if(void 0===i||!t.isCallExpression(i))return;const o=i.getExpression();if((!t.isIdentifier(o)||"require"!==o.getText())&&o.getKind()!==n.ImportKeyword)return;const[s]=i.getArguments();return void 0!==s&&t.isStringLiteral(s)?s.getLiteralText():void 0}function l(e){const{Node:t}=r();return t.isStringLiteral(e)||t.isNoSubstitutionTemplateLiteral(e)?e.getLiteralText():e.getText()}function u(e){const{Node:t}=r();if(t.isSpreadAssignment(e))return;const n=e.getNameNode();return t.isComputedPropertyName(n)?void 0:l(n)}function p(e,t){const{Node:n,SyntaxKind:i}=r(),o=t.symbol?.compilerSymbol;if(void 0===o)return[];const s=e.getProject().getTypeChecker(),a=[];for(const r of e.getDescendantsOfKind(i.Identifier)){if(r.getText()!==t.local||f(r,t.declaration))continue;const e=r.getParent();n.isShorthandPropertyAssignment(e)?s.getShorthandAssignmentValueSymbol(e)?.compilerSymbol===o&&a.push({node:r,kind:"shorthand"}):n.isExportSpecifier(e)?e.getNameNode()===r&&e.getLocalTargetSymbol()?.compilerSymbol===o&&a.push({node:r,kind:"export"}):r.getSymbol()?.compilerSymbol===o&&a.push({node:r,kind:"reference"})}return a}function f(e,t){return void 0!==e.getFirstAncestor(e=>e===t)}function m(e,t,n=[]){const{SyntaxKind:i}=r();for(const o of e.getDescendantsOfKind(i.Identifier)){if(o.getText()!==t)continue;const e=o.getParent();if(g(e,o)&&!n.some(t=>t===e||f(e,t)))return e}}function g(e,t){const{Node:n}=r();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 h(e,t){return{start:e.getStart(),end:e.getEnd(),text:t}}function v(e,t){const n=[...t].sort((e,t)=>t.start-e.start);let i=e,o=Number.POSITIVE_INFINITY;for(const e of n){if(e.end>o)throw new Error("overlapping codemod edits");i=`${i.slice(0,e.start)}${e.text}${i.slice(e.end)}`,o=e.start}return i}var w="move-fetch-preview-helpers",y=`${o}/server`,$={fetchPreviewDocument:"fetchDocument",fetchPreviewGlobal:"fetchGlobal"},N=/* @__PURE__ */new Set(["serverURL","apiRoute","depth"]),b=/* @__PURE__ */new Set(["draft","fetchFn"]),x=["authorization","locale","headers","signal","errorMode"],S={fetchPreviewDocument:["collection","where",...x],fetchPreviewGlobal:["global",...x]};function P(e,t){return{codemod:w,reason:t,line:e}}function I(e,t,n){const i=[],o=[],r=[],s=/* @__PURE__ */new Set;for(const e of t.getProperties()){const t=u(e);void 0!==t&&s.add(t),void 0!==t&&N.has(t)?i.push(e.getText()):void 0!==t&&b.has(t)?r.push(t):o.push(e.getText())}s.has("depth")||i.push("depth: 1 /* TODO(pll migrate): the 1.x default; match the runtime mergeDepth */"),s.has("authorization")||o.push("authorization: null /* TODO(pll migrate): pass the verdict from authorizePreviewRequest(); null reads the published document */");const a=S[n]??[],d=[...s].filter(e=>!N.has(e)&&!b.has(e)&&!a.includes(e)),c=e.getTypeArguments().map(e=>e.getText()),l=0===c.length?"":`<${c.join(", ")}>`,p=$[n]??n,f=`definePreview({ ${i.join(", ")} }).${p}${l}({ ${o.join(", ")} })`,m=0===r.length?"":`, and ${r.join("/")} was dropped`,g=e.getStartLineNumber(),h=[P(g,`${n}() was rewritten onto definePreview().${p}(); it now returns a PreviewFetchResult (check ok/data) and needs a real authorization for drafts${m}`)];return d.length>0&&h.push(P(g,`${n}() was passed ${d.map(e=>`\`${e}\``).join(", ")}, which .${p}() 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:f},notes:h}}function T(e,t,n){return`import { ${t.join(", ")} } from ${e}${n}${e};`}var k={id:w,summary:"`fetchPreviewDocument`/`fetchPreviewGlobal` from the root → `definePreview().fetchDocument`/`.fetchGlobal` (payload-live-preview/server)",ledgerEntry:9,apply(e){const t=d(e).filter(e=>e.specifier===o&&e.imported in $);return 0===t.length?{edits:[],conflicts:[]}:function(e,t){const{Node:n}=r(),i=[],s=[],a=[];for(const o of t)if("require"!==o.kind)for(const t of p(e,o)){const e=t.node.getStartLineNumber(),r=t.node.getParent();if("reference"!==t.kind||!n.isCallExpression(r)||r.getExpression()!==t.node){i.push(P(e,`${o.local} is used other than as a direct call; rewrite it onto definePreview() by hand`));continue}const[d]=r.getArguments();if(void 0===d||!n.isObjectLiteralExpression(d)||d.getProperties().some(e=>n.isSpreadAssignment(e))){i.push(P(e,`${o.imported}() options are not a plain object literal, so serverURL/depth cannot be split out; rewrite it onto definePreview() by hand`));continue}const c=I(r,d,o.imported);a.push(c.edit),s.push(...c.notes)}else i.push(P(o.declaration.getStartLineNumber(),`${o.imported} is bound with require(); rewrite it onto definePreview() from ${y} by hand`));const d=e.getImportDeclarations().filter(e=>e.getModuleSpecifierValue()===y),c=m(e,"definePreview",d);return void 0!==c&&i.push(P(c.getStartLineNumber(),`this module already binds a definePreview that is not ${y}'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}=r(),i=[],s=/* @__PURE__ */new Set;for(const e of t)n.isImportDeclaration(e.declaration)&&s.add(e.declaration);const a=e.getImportDeclarations().find(e=>e.getModuleSpecifierValue()===y&&!e.isTypeOnly()),d=!0===a?.getNamedImports().some(e=>"definePreview"===e.getName());let c;if(void 0!==a&&!d){const e=a.getModuleSpecifier().getQuoteKind(),t=[...a.getNamedImports().map(e=>e.getText()),"definePreview"],n=a.getDefaultImport()?.getText(),o=void 0===n?t.join(", "):`${n}, { ${t.join(", ")} }`,r=void 0===n?T(e,t,y):`import ${o} from ${e}${y}${e};`;i.push({start:a.getStart(),end:a.getEnd(),text:r})}for(const t of s){const n=t.getModuleSpecifier().getQuoteKind(),r=t.getNamedImports().filter(e=>!(e.getName()in $)).map(e=>e.getText()),s=t.getDefaultImport()?.getText(),d=[s,0===r.length?void 0:`{ ${r.join(", ")} }`].filter(e=>void 0!==e),l=t.isTypeOnly()?"type ":"",u=0===d.length?"":`import ${l}${d.join(", ")} from ${n}${o}${n};`;if(void 0===a&&void 0===c)c=T(n,["definePreview"],y),i.push({start:t.getStart(),end:t.getEnd(),text:""===u?c:`${u}\n${c}`});else{const n=t.getEnd(),o=""===u&&"\n"===e.getFullText()[n]?1:0;i.push({start:t.getStart(),end:n+o,text:u})}}return i}(e,t)),{edits:a,conflicts:s})}(e,t)}},E="rename-admin-origins-option",L="hasPreviewIntent",j="adminOrigins",D="allowedOrigins",O=`if they carry \`${j}\`, rename it to \`${D}\``,A={id:E,summary:"`hasPreviewIntent(request, { adminOrigins })` → `{ allowedOrigins }`",ledgerEntry:13,apply(e){const{Node:t}=r(),n=[],i=[],o=d(e).filter(e=>e.imported===L);for(const r of o)for(const o of p(e,r)){const e=o.node.getParent();if("reference"!==o.kind||!t.isCallExpression(e))continue;if(e.getExpression()!==o.node)continue;const r=e.getArguments()[1];if(void 0===r)continue;const s=r.getStartLineNumber();if(!t.isObjectLiteralExpression(r)){i.push({codemod:E,line:s,reason:`${L}() options are not a literal; ${O}`});continue}const a=r.getProperties(),d=a.map(e=>u(e));if(d.includes(j)&&d.includes(D))i.push({codemod:E,line:s,reason:`${L}() is given both ${j} and ${D}; ${D} wins, drop ${j} by hand`});else for(const e of a)if(t.isSpreadAssignment(e))i.push({codemod:E,line:e.getStartLineNumber(),reason:`${L}() spreads its options; ${O}`});else{if(u(e)!==j)continue;t.isShorthandPropertyAssignment(e)?n.push(h(e,`${D}: ${j}`)):t.isPropertyAssignment(e)&&n.push(h(e.getNameNode(),D))}}return{edits:n,conflicts:i}}},z="rename-bindings-authorized-option",K="authorized",q="authorization",F=`if they carry \`${K}\`, rename it to \`${q}\` and pass the verdict from authorizePreviewRequest()`,R=`\`${q}\` 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`,C={id:z,summary:"`createPreviewBindings({ authorized })` → `{ authorization }`",ledgerEntry:7,apply(e){const{Node:t}=r(),n=[],i=[],o=d(e).filter(e=>"createPreviewBindings"===e.imported);for(const r of o)for(const o of p(e,r)){const e=o.node.getParent();if("reference"!==o.kind||!t.isCallExpression(e))continue;if(e.getExpression()!==o.node)continue;const[r]=e.getArguments();if(void 0===r)continue;const s=r.getStartLineNumber();if(t.isObjectLiteralExpression(r))for(const e of r.getProperties())if(t.isSpreadAssignment(e))i.push({codemod:z,line:e.getStartLineNumber(),reason:`createPreviewBindings() spreads its options; ${F}`});else{if(u(e)!==K)continue;if(t.isShorthandPropertyAssignment(e))n.push(h(e,`${q}: ${K}`)),i.push({codemod:z,line:e.getStartLineNumber(),reason:R});else if(t.isPropertyAssignment(e)){const o=e.getInitializer();if(void 0!==o&&t.isFalseLiteral(o)){n.push(h(e,`${q}: null`));continue}n.push(h(e.getNameNode(),q)),i.push({codemod:z,line:e.getStartLineNumber(),reason:R})}}else i.push({codemod:z,line:s,reason:`createPreviewBindings() options are not a literal; ${F}`})}return{edits:n,conflicts:i}}},M="rename-is-preview-request",V="isPreviewRequest",B="hasPreviewIntent";function G(e,t){return{codemod:M,reason:t,line:e}}function Q(e){return e.aliased&&e.local===B?h(e.importedNode.getParentOrThrow(),B):h(e.importedNode,B)}var U={id:M,summary:"`isPreviewRequest()` → `hasPreviewIntent()` (same signature)",ledgerEntry:1,apply(e){const t=d(e).filter(e=>e.imported===V);return 0===t.length?{edits:[],conflicts:[]}:function(e,t){const n=[],i=[],o=m(t,B,e.map(e=>e.declaration));void 0!==o&&n.push(G(o.getStartLineNumber(),`this module already binds ${B}; rename it (or drop the wrapper and import the package's ${B} directly), then rename ${V} by hand`));for(const o of e)if(i.push(Q(o)),!o.aliased)for(const e of p(t,o))"reference"===e.kind?i.push(h(e.node,B)):"shorthand"===e.kind?n.push(G(e.node.getStartLineNumber(),`{ ${V} } keeps the old key for whoever reads it; write { ${V}: ${B} } or rename the key and its readers by hand`)):n.push(G(e.node.getStartLineNumber(),`${V} is re-exported under its old name; rename the export and its importers, or write export { ${B} as ${V} }`));const s=function(e,t){const{Node:n,SyntaxKind:i}=r();return e.getDescendantsOfKind(i.Identifier).filter(e=>{const i=e.getParent();return e.getText()===t&&n.isPropertyAccessExpression(i)&&i.getNameNode()===e})}(t,V).map(e=>G(e.getStartLineNumber(),`.${V} 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 n.length>0?{edits:[],conflicts:[...n,...s]}:{edits:i,conflicts:s}}(t,e)}},J={".ts":"ts",".mts":"ts",".cts":"ts",".tsx":"tsx",".js":"js",".mjs":"js",".cjs":"js",".jsx":"jsx"},W=/* @__PURE__ */new Set([".astro",".vue",".svelte"]),Y=/^---\r?\n([\s\S]*?)\r?\n---/u,_=/<script(?:\s[^>]*)?>([\s\S]*?)<\/script\b[^>]*>/giu,H=/(?:\bfrom\s*|\bimport\s*\(?\s*|\brequire\s*\(\s*)['"]payload-live-preview(?:\/[^'"]*)?['"]/u;function X(e){return H.test(e)}var Z=[U,A,C,k],ee=Z;function te(e,t){let n=1;for(let i=0;i<t;i+=1)"\n"===e[i]&&(n+=1);return n}function ne(e,t,n){const i=e.split("\n"),o=t.split("\n");let r=0;for(;r<i.length&&r<o.length&&i[r]===o[r];)r+=1;let s=0;for(;s<i.length-r&&s<o.length-r&&i[i.length-1-s]===o[o.length-1-s];)s+=1;const a=i.slice(r,i.length-s),d=o.slice(r,o.length-s),c=[];for(let e=0;e<Math.max(a.length,d.length);e+=1){const t=a[e]??"",i=d[e]??"";t!==i&&c.push({line:n+r+e,before:t,after:i})}return c}function ie(e,n={}){const i=void 0===n.only?Z:Z.filter(e=>n.only?.includes(e.id));if(0===i.length||!X(e))return{output:e,edits:[],conflicts:[]};const o=/* @__PURE__ */new Map,r=[];let a="",d=0;for(const c of function(e,n){const i=t(n).toLowerCase();if(!W.has(i))return[{start:0,end:e.length,kind:J[i]??"ts"}];const o=[],r=".astro"===i?Y.exec(e):null;if(void 0!==r?.[1]){const e=r.index+r[0].indexOf("\n")+1;o.push({start:e,end:e+r[1].length,kind:"ts"})}for(const t of e.matchAll(_)){const e=t[1]??"";if(""===e.trim())continue;const n=t.index+t[0].lastIndexOf(e);o.push({start:n,end:n+e.length,kind:"ts"})}return o}(e,n.fileName??"source.ts")){a+=e.slice(d,c.start);const t=te(e,c.start);let n=e.slice(c.start,c.end);for(const e of i){const i=e.apply(s(n,c.kind));for(const e of i.conflicts)r.push(void 0===e.line?e:{...e,line:e.line+t-1});if(0===i.edits.length)continue;const a=v(n,i.edits),d=o.get(e.id)??[];d.push(...ne(n,a,t)),o.set(e.id,d),n=a}a+=n,d=c.end}return a+=e.slice(d),{output:a,edits:[...o].map(([e,t])=>({codemod:e,count:t.length,lines:t})),conflicts:r}}export{ee as CODEMODS,X as importsThisPackage,ie as migrateSource};
1
+ import{createRequire as e}from"module";import{extname as t}from"path";var n,i,o="payload-live-preview";function r(){if(void 0===n)try{n=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 n}function s(e,t){const n=r();return i??=new n.Project({useInMemoryFileSystem:!0,skipLoadingLibFiles:!0,skipFileDependencyResolution:!0,compilerOptions:{allowJs:!0,noLib:!0}}),i.createSourceFile(`/script.${t}`,e,{overwrite:!0})}function a(e){return e===o||e.startsWith(`${o}/`)}function d(e){const{Node:t,SyntaxKind:n}=r(),i=[];for(const t of e.getImportDeclarations()){const e=t.getModuleSpecifierValue();if(a(e))for(const n of t.getNamedImports()){const o=n.getAliasNode(),r=o??n.getNameNode();i.push({imported:n.getName(),local:r.getText(),specifier:e,kind:"import",importedNode:n.getNameNode(),aliased:void 0!==o,symbol:r.getSymbol(),declaration:t})}}for(const o of e.getDescendantsOfKind(n.VariableDeclaration)){const e=c(o.getInitializer()),n=o.getNameNode();if(void 0!==e&&a(e)&&t.isObjectBindingPattern(n))for(const r of n.getElements()){const n=r.getNameNode();if(!t.isIdentifier(n))continue;const s=r.getPropertyNameNode();i.push({imported:void 0===s?n.getText():l(s),local:n.getText(),specifier:e,kind:"require",importedNode:s??n,aliased:void 0!==s,symbol:n.getSymbol(),declaration:o})}}return i}function c(e){const{Node:t,SyntaxKind:n}=r(),i=void 0!==e&&t.isAwaitExpression(e)?e.getExpression():e;if(void 0===i||!t.isCallExpression(i))return;const o=i.getExpression();if((!t.isIdentifier(o)||"require"!==o.getText())&&o.getKind()!==n.ImportKeyword)return;const[s]=i.getArguments();return void 0!==s&&t.isStringLiteral(s)?s.getLiteralText():void 0}function l(e){const{Node:t}=r();return t.isStringLiteral(e)||t.isNoSubstitutionTemplateLiteral(e)?e.getLiteralText():e.getText()}function u(e){const{Node:t}=r();if(t.isSpreadAssignment(e))return;const n=e.getNameNode();return t.isComputedPropertyName(n)?void 0:l(n)}function p(e,t){const{Node:n,SyntaxKind:i}=r(),o=t.symbol?.compilerSymbol;if(void 0===o)return[];const s=e.getProject().getTypeChecker(),a=[];for(const r of e.getDescendantsOfKind(i.Identifier)){if(r.getText()!==t.local||f(r,t.declaration))continue;const e=r.getParent();n.isShorthandPropertyAssignment(e)?s.getShorthandAssignmentValueSymbol(e)?.compilerSymbol===o&&a.push({node:r,kind:"shorthand"}):n.isExportSpecifier(e)?e.getNameNode()===r&&e.getLocalTargetSymbol()?.compilerSymbol===o&&a.push({node:r,kind:"export"}):r.getSymbol()?.compilerSymbol===o&&a.push({node:r,kind:"reference"})}return a}function f(e,t){return void 0!==e.getFirstAncestor(e=>e===t)}function m(e,t,n=[]){const{SyntaxKind:i}=r();for(const o of e.getDescendantsOfKind(i.Identifier)){if(o.getText()!==t)continue;const e=o.getParent();if(h(e,o)&&!n.some(t=>t===e||f(e,t)))return e}}function h(e,t){const{Node:n}=r();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 g(e,t){return{start:e.getStart(),end:e.getEnd(),text:t}}function v(e,t){const n=[...t].sort((e,t)=>t.start-e.start);let i=e,o=Number.POSITIVE_INFINITY;for(const e of n){if(e.end>o)throw new Error("overlapping codemod edits");i=`${i.slice(0,e.start)}${e.text}${i.slice(e.end)}`,o=e.start}return i}var w="move-fetch-preview-helpers",y=`${o}/server`,$={fetchPreviewDocument:"fetchDocument",fetchPreviewGlobal:"fetchGlobal"},N=/* @__PURE__ */new Set(["serverURL","apiRoute","depth"]),b=/* @__PURE__ */new Set(["draft","fetchFn"]),x=["authorization","locale","headers","signal","errorMode"],S={fetchPreviewDocument:["collection","where",...x],fetchPreviewGlobal:["global",...x]};function P(e,t){return{codemod:w,reason:t,line:e}}function I(e,t,n){const i=[],o=[],r=[],s=/* @__PURE__ */new Set;for(const e of t.getProperties()){const t=u(e);void 0!==t&&s.add(t),void 0!==t&&N.has(t)?i.push(e.getText()):void 0!==t&&b.has(t)?r.push(t):o.push(e.getText())}s.has("depth")||i.push("depth: 1 /* TODO(pll migrate): the 1.x default; match the runtime mergeDepth */"),s.has("authorization")||o.push("authorization: null /* TODO(pll migrate): pass the verdict from authorizePreviewRequest(); null reads the published document */");const a=S[n]??[],d=[...s].filter(e=>!N.has(e)&&!b.has(e)&&!a.includes(e)),c=e.getTypeArguments().map(e=>e.getText()),l=0===c.length?"":`<${c.join(", ")}>`,p=$[n]??n,f=`definePreview({ ${i.join(", ")} }).${p}${l}({ ${o.join(", ")} })`,m=0===r.length?"":`, and ${r.join("/")} was dropped`,h=e.getStartLineNumber(),g=[P(h,`${n}() was rewritten onto definePreview().${p}(); it now returns a PreviewFetchResult (check ok/data) and needs a real authorization for drafts${m}`)];return d.length>0&&g.push(P(h,`${n}() was passed ${d.map(e=>`\`${e}\``).join(", ")}, which .${p}() 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:f},notes:g}}function k(e,t,n){return`import { ${t.join(", ")} } from ${e}${n}${e};`}var T={id:w,summary:"`fetchPreviewDocument`/`fetchPreviewGlobal` from the root → `definePreview().fetchDocument`/`.fetchGlobal` (payload-live-preview/server)",ledgerEntry:9,apply(e){const t=d(e).filter(e=>e.specifier===o&&e.imported in $);return 0===t.length?{edits:[],conflicts:[]}:function(e,t){const{Node:n}=r(),i=[],s=[],a=[];for(const o of t)if("require"!==o.kind)for(const t of p(e,o)){const e=t.node.getStartLineNumber(),r=t.node.getParent();if("reference"!==t.kind||!n.isCallExpression(r)||r.getExpression()!==t.node){i.push(P(e,`${o.local} is used other than as a direct call; rewrite it onto definePreview() by hand`));continue}const[d]=r.getArguments();if(void 0===d||!n.isObjectLiteralExpression(d)||d.getProperties().some(e=>n.isSpreadAssignment(e))){i.push(P(e,`${o.imported}() options are not a plain object literal, so serverURL/depth cannot be split out; rewrite it onto definePreview() by hand`));continue}const c=I(r,d,o.imported);a.push(c.edit),s.push(...c.notes)}else i.push(P(o.declaration.getStartLineNumber(),`${o.imported} is bound with require(); rewrite it onto definePreview() from ${y} by hand`));const d=e.getImportDeclarations().filter(e=>e.getModuleSpecifierValue()===y),c=m(e,"definePreview",d);return void 0!==c&&i.push(P(c.getStartLineNumber(),`this module already binds a definePreview that is not ${y}'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}=r(),i=[],s=/* @__PURE__ */new Set;for(const e of t)n.isImportDeclaration(e.declaration)&&s.add(e.declaration);const a=e.getImportDeclarations().find(e=>e.getModuleSpecifierValue()===y&&!e.isTypeOnly()),d=!0===a?.getNamedImports().some(e=>"definePreview"===e.getName());let c;if(void 0!==a&&!d){const e=a.getModuleSpecifier().getQuoteKind(),t=[...a.getNamedImports().map(e=>e.getText()),"definePreview"],n=a.getDefaultImport()?.getText(),o=void 0===n?t.join(", "):`${n}, { ${t.join(", ")} }`,r=void 0===n?k(e,t,y):`import ${o} from ${e}${y}${e};`;i.push({start:a.getStart(),end:a.getEnd(),text:r})}for(const t of s){const n=t.getModuleSpecifier().getQuoteKind(),r=t.getNamedImports().filter(e=>!(e.getName()in $)).map(e=>e.getText()),s=t.getDefaultImport()?.getText(),d=[s,0===r.length?void 0:`{ ${r.join(", ")} }`].filter(e=>void 0!==e),l=t.isTypeOnly()?"type ":"",u=0===d.length?"":`import ${l}${d.join(", ")} from ${n}${o}${n};`;if(void 0===a&&void 0===c)c=k(n,["definePreview"],y),i.push({start:t.getStart(),end:t.getEnd(),text:""===u?c:`${u}\n${c}`});else{const n=t.getEnd(),o=""===u&&"\n"===e.getFullText()[n]?1:0;i.push({start:t.getStart(),end:n+o,text:u})}}return i}(e,t)),{edits:a,conflicts:s})}(e,t)}},E="rename-admin-origins-option",L="hasPreviewIntent",j="adminOrigins",D="allowedOrigins",O=`if they carry \`${j}\`, rename it to \`${D}\``,A={id:E,summary:"`hasPreviewIntent(request, { adminOrigins })` → `{ allowedOrigins }`",ledgerEntry:13,apply(e){const{Node:t}=r(),n=[],i=[],o=d(e).filter(e=>e.imported===L);for(const r of o)for(const o of p(e,r)){const e=o.node.getParent();if("reference"!==o.kind||!t.isCallExpression(e))continue;if(e.getExpression()!==o.node)continue;const r=e.getArguments()[1];if(void 0===r)continue;const s=r.getStartLineNumber();if(!t.isObjectLiteralExpression(r)){i.push({codemod:E,line:s,reason:`${L}() options are not a literal; ${O}`});continue}const a=r.getProperties(),d=a.map(e=>u(e));if(d.includes(j)&&d.includes(D))i.push({codemod:E,line:s,reason:`${L}() is given both ${j} and ${D}; ${D} wins, drop ${j} by hand`});else for(const e of a)if(t.isSpreadAssignment(e))i.push({codemod:E,line:e.getStartLineNumber(),reason:`${L}() spreads its options; ${O}`});else{if(u(e)!==j)continue;t.isShorthandPropertyAssignment(e)?n.push(g(e,`${D}: ${j}`)):t.isPropertyAssignment(e)&&n.push(g(e.getNameNode(),D))}}return{edits:n,conflicts:i}}},q="rename-bindings-authorized-option",z="authorized",K="authorization",F=`if they carry \`${z}\`, rename it to \`${K}\` and pass the verdict from authorizePreviewRequest()`,R=`\`${K}\` 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`,C={id:q,summary:"`createPreviewBindings({ authorized })` → `{ authorization }`",ledgerEntry:7,apply(e){const{Node:t}=r(),n=[],i=[],o=d(e).filter(e=>"createPreviewBindings"===e.imported);for(const r of o)for(const o of p(e,r)){const e=o.node.getParent();if("reference"!==o.kind||!t.isCallExpression(e))continue;if(e.getExpression()!==o.node)continue;const[r]=e.getArguments();if(void 0===r)continue;const s=r.getStartLineNumber();if(t.isObjectLiteralExpression(r))for(const e of r.getProperties())if(t.isSpreadAssignment(e))i.push({codemod:q,line:e.getStartLineNumber(),reason:`createPreviewBindings() spreads its options; ${F}`});else{if(u(e)!==z)continue;if(t.isShorthandPropertyAssignment(e))n.push(g(e,`${K}: ${z}`)),i.push({codemod:q,line:e.getStartLineNumber(),reason:R});else if(t.isPropertyAssignment(e)){const o=e.getInitializer();if(void 0!==o&&t.isFalseLiteral(o)){n.push(g(e,`${K}: null`));continue}n.push(g(e.getNameNode(),K)),i.push({codemod:q,line:e.getStartLineNumber(),reason:R})}}else i.push({codemod:q,line:s,reason:`createPreviewBindings() options are not a literal; ${F}`})}return{edits:n,conflicts:i}}},M="rename-is-preview-request",V="isPreviewRequest",B="hasPreviewIntent";function G(e,t){return{codemod:M,reason:t,line:e}}function Q(e){return e.aliased&&e.local===B?g(e.importedNode.getParentOrThrow(),B):g(e.importedNode,B)}var U={id:M,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=d(e).filter(e=>e.imported===V);return 0===t.length?{edits:[],conflicts:[]}:function(e,t){const n=[],i=[],o=m(t,B,e.map(e=>e.declaration));void 0!==o&&n.push(G(o.getStartLineNumber(),`this module already binds ${B}; rename it (or drop the wrapper and import the package's ${B} directly), then rename ${V} by hand`));for(const o of e)if(i.push(Q(o)),!o.aliased)for(const e of p(t,o))"reference"===e.kind?i.push(g(e.node,B)):"shorthand"===e.kind?n.push(G(e.node.getStartLineNumber(),`{ ${V} } keeps the old key for whoever reads it; write { ${V}: ${B} } or rename the key and its readers by hand`)):n.push(G(e.node.getStartLineNumber(),`${V} is re-exported under its old name; rename the export and its importers, or write export { ${B} as ${V} }`));const s=function(e,t){const{Node:n,SyntaxKind:i}=r();return e.getDescendantsOfKind(i.Identifier).filter(e=>{const i=e.getParent();return e.getText()===t&&n.isPropertyAccessExpression(i)&&i.getNameNode()===e})}(t,V).map(e=>G(e.getStartLineNumber(),`.${V} 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 n.length>0?{edits:[],conflicts:[...n,...s]}:{edits:i,conflicts:s}}(t,e)}},J={".ts":"ts",".mts":"ts",".cts":"ts",".tsx":"tsx",".js":"js",".mjs":"js",".cjs":"js",".jsx":"jsx"},W=/* @__PURE__ */new Set([".astro",".vue",".svelte"]),Y=/^---\r?\n([\s\S]*?)\r?\n---/u,_=/<script(?:\s[^>]*)?>([\s\S]*?)<\/script\b[^>]*>/giu,H=/(?:\bfrom\s*|\bimport\s*\(?\s*|\brequire\s*\(\s*)['"]payload-live-preview(?:\/[^'"]*)?['"]/u;function X(e){return H.test(e)}var Z=[U,A,C,T],ee=Z;function te(e,t){let n=1;for(let i=0;i<t;i+=1)"\n"===e[i]&&(n+=1);return n}function ne(e,t,n){const i=e.split("\n"),o=t.split("\n");let r=0;for(;r<i.length&&r<o.length&&i[r]===o[r];)r+=1;let s=0;for(;s<i.length-r&&s<o.length-r&&i[i.length-1-s]===o[o.length-1-s];)s+=1;const a=i.slice(r,i.length-s),d=o.slice(r,o.length-s),c=[];for(let e=0;e<Math.max(a.length,d.length);e+=1){const t=a[e]??"",i=d[e]??"";t!==i&&c.push({line:n+r+e,before:t,after:i})}return c}function ie(e,n={}){const i=void 0===n.only?Z:Z.filter(e=>n.only?.includes(e.id));if(0===i.length||!X(e))return{output:e,edits:[],conflicts:[]};const o=/* @__PURE__ */new Map,r=[];let a="",d=0;for(const c of function(e,n){const i=t(n).toLowerCase();if(!W.has(i))return[{start:0,end:e.length,kind:J[i]??"ts"}];const o=[],r=".astro"===i?Y.exec(e):null;if(void 0!==r?.[1]){const e=r.index+r[0].indexOf("\n")+1;o.push({start:e,end:e+r[1].length,kind:"ts"})}for(const t of e.matchAll(_)){const e=t[1]??"";if(""===e.trim())continue;const n=t.index+t[0].lastIndexOf(e);o.push({start:n,end:n+e.length,kind:"ts"})}return o}(e,n.fileName??"source.ts")){a+=e.slice(d,c.start);const t=te(e,c.start);let n=e.slice(c.start,c.end);for(const e of i){const i=e.apply(s(n,c.kind));for(const e of i.conflicts)r.push(void 0===e.line?e:{...e,line:e.line+t-1});if(0===i.edits.length)continue;const a=v(n,i.edits),d=o.get(e.id)??[];d.push(...ne(n,a,t)),o.set(e.id,d),n=a}a+=n,d=c.end}return a+=e.slice(d),{output:a,edits:[...o].map(([e,t])=>({codemod:e,count:t.length,lines:t})),conflicts:r}}export{ee as CODEMODS,X as importsThisPackage,ie as migrateSource};
2
2
  //# sourceMappingURL=migrate.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"migrate.js","names":["tsMorph","project","PACKAGE_NAME","loadTsMorph","createRequire","url","error","Error","cause","parseScript","text","kind","morph","Project","useInMemoryFileSystem","skipLoadingLibFiles","skipFileDependencyResolution","compilerOptions","allowJs","noLib","createSourceFile","overwrite","isPackageSpecifier","specifier","startsWith","packageBindings","script","Node","SyntaxKind","out","declaration","getImportDeclarations","getModuleSpecifierValue","spec","getNamedImports","alias","getAliasNode","localNode","getNameNode","push","imported","getName","local","getText","importedNode","aliased","symbol","getSymbol","getDescendantsOfKind","VariableDeclaration","requiredSpecifier","getInitializer","pattern","isObjectBindingPattern","element","getElements","nameNode","isIdentifier","propertyName","getPropertyNameNode","literalName","initializer","call","isAwaitExpression","getExpression","isCallExpression","callee","getKind","ImportKeyword","argument","getArguments","isStringLiteral","getLiteralText","node","isNoSubstitutionTemplateLiteral","propertyKey","property","isSpreadAssignment","isComputedPropertyName","referencesTo","binding","target","compilerSymbol","checker","getProject","getTypeChecker","Identifier","isInside","parent","getParent","isShorthandPropertyAssignment","getShorthandAssignmentValueSymbol","isExportSpecifier","getLocalTargetSymbol","ancestor","getFirstAncestor","candidate","declaresName","name","except","bindsIdentifier","some","skip","isVariableDeclaration","isBindingElement","isFunctionDeclaration","isClassDeclaration","isParameterDeclaration","isEnumDeclaration","isImportSpecifier","isImportClause","getDefaultImport","isNamespaceImport","replaceNode","start","getStart","end","getEnd","applyTextEdits","edits","ordered","sort","left","right","output","floor","Number","POSITIVE_INFINITY","edit","slice","ID","SERVER_SPECIFIER","METHOD","fetchPreviewDocument","fetchPreviewGlobal","SERVER_OPTIONS","Set","DROPPED_OPTIONS","SHARED_READ_OPTIONS","READ_OPTIONS","conflict","line","reason","codemod","rewriteCall","options","server","read","dropped","keys","getProperties","key","add","has","accepted","unplaceable","filter","includes","typeArguments","getTypeArguments","map","generic","length","join","method","droppedNote","getStartLineNumber","notes","importLine","quote","names","moveFetchPreviewHelpers","id","summary","ledgerEntry","apply","bindings","conflicts","blocking","reference","isObjectLiteralExpression","rewritten","serverDeclaration","foreign","declarations","isImportDeclaration","serverImport","find","isTypeOnly","hasDefinePreview","serverLine","getModuleSpecifier","getQuoteKind","defaultImport","clauses","remaining","clause","typeOnly","kept","trailingNewline","getFullText","rewriteImports","plan","CALLEE","OLD_KEY","NEW_KEY","BY_HAND","renameAdminOriginsOption","properties","isPropertyAssignment","BOOLEAN_REFUSED","renameBindingsAuthorizedOption","value","isFalseLiteral","OLD_NAME","NEW_NAME","renameBinding","getParentOrThrow","renameIsPreviewRequest","existing","isPropertyAccessExpression","memberAccesses","WHOLE_FILE","COMPONENT_EXTENSIONS","FRONTMATTER","SCRIPT_TAG","PACKAGE_REFERENCE","importsThisPackage","source","test","IMPLEMENTATIONS","CODEMODS","lineNumberAt","offset","index","lineEdits","before","after","firstLine","oldLines","split","newLines","prefix","suffix","oldMiddle","newMiddle","changed","Math","max","migrateSource","chosen","only","byCodemod","Map","cursor","block","fileName","extension","extname","toLowerCase","blocks","frontmatter","exec","indexOf","match","matchAll","body","trim","lastIndexOf","scriptBlocks","item","next","lines","get","set","count"],"sources":["../src/migrate/ast.ts","../src/migrate/codemods/move-fetch-preview-helpers.ts","../src/migrate/codemods/rename-admin-origins-option.ts","../src/migrate/codemods/rename-bindings-authorized-option.ts","../src/migrate/codemods/rename-is-preview-request.ts","../src/migrate/script-blocks.ts","../src/migrate/index.ts"],"sourcesContent":["/**\n * ts-morph access for the codemods: parsing, the package's bindings in a\n * script and the references those bindings have. ts-morph is loaded on first\n * use so the entry stays importable without the optional peer.\n */\nimport { createRequire } from 'node:module';\nimport type * as TsMorphModule from 'ts-morph';\nimport type {\n Identifier,\n Node,\n ObjectLiteralElementLike,\n Project,\n SourceFile,\n Symbol as TsSymbol,\n} from 'ts-morph';\nimport type { TextEdit } from './types';\n\ntype TsMorph = typeof TsMorphModule;\n\nexport type ScriptKind = 'ts' | 'tsx' | 'js' | 'jsx';\n\nexport const PACKAGE_NAME = 'payload-live-preview';\n\nlet tsMorph: TsMorph | undefined;\nlet project: Project | undefined;\n\nexport function loadTsMorph(): TsMorph {\n if (tsMorph === undefined) {\n try {\n tsMorph = createRequire(import.meta.url)('ts-morph') as TsMorph;\n } catch (error) {\n throw new Error('pll migrate needs ts-morph: npm install --save-dev ts-morph', {\n cause: error,\n });\n }\n }\n return tsMorph;\n}\n\n/** Parse one script into a throwaway in-memory project; the previous script is discarded. */\nexport function parseScript(text: string, kind: ScriptKind): SourceFile {\n const morph = loadTsMorph();\n project ??= new morph.Project({\n useInMemoryFileSystem: true,\n skipLoadingLibFiles: true,\n skipFileDependencyResolution: true,\n compilerOptions: { allowJs: true, noLib: true },\n });\n return project.createSourceFile(`/script.${kind}`, text, { overwrite: true });\n}\n\nexport function isPackageSpecifier(specifier: string): boolean {\n return specifier === PACKAGE_NAME || specifier.startsWith(`${PACKAGE_NAME}/`);\n}\n\n/** A name the script binds from the package, by `import` or by destructuring `require()`/`import()`. */\nexport interface PackageBinding {\n /** The exported name, as the package spells it. */\n readonly imported: string;\n /** The name the script uses; equals `imported` unless aliased. */\n readonly local: string;\n readonly specifier: string;\n readonly kind: 'import' | 'require';\n /** The node spelling the exported name; rewritten when the export is renamed. */\n readonly importedNode: Node;\n readonly aliased: boolean;\n readonly symbol: TsSymbol | undefined;\n /** The import declaration or variable declaration that binds it. */\n readonly declaration: Node;\n}\n\nexport function packageBindings(script: SourceFile): readonly PackageBinding[] {\n const { Node, SyntaxKind } = loadTsMorph();\n const out: PackageBinding[] = [];\n for (const declaration of script.getImportDeclarations()) {\n const specifier = declaration.getModuleSpecifierValue();\n if (!isPackageSpecifier(specifier)) continue;\n for (const spec of declaration.getNamedImports()) {\n const alias = spec.getAliasNode();\n const localNode = alias ?? spec.getNameNode();\n out.push({\n imported: spec.getName(),\n local: localNode.getText(),\n specifier,\n kind: 'import',\n importedNode: spec.getNameNode(),\n aliased: alias !== undefined,\n symbol: localNode.getSymbol(),\n declaration,\n });\n }\n }\n for (const declaration of script.getDescendantsOfKind(SyntaxKind.VariableDeclaration)) {\n const specifier = requiredSpecifier(declaration.getInitializer());\n const pattern = declaration.getNameNode();\n if (specifier === undefined || !isPackageSpecifier(specifier)) continue;\n if (!Node.isObjectBindingPattern(pattern)) continue;\n for (const element of pattern.getElements()) {\n const nameNode = element.getNameNode();\n if (!Node.isIdentifier(nameNode)) continue;\n const propertyName = element.getPropertyNameNode();\n out.push({\n imported: propertyName === undefined ? nameNode.getText() : literalName(propertyName),\n local: nameNode.getText(),\n specifier,\n kind: 'require',\n importedNode: propertyName ?? nameNode,\n aliased: propertyName !== undefined,\n symbol: nameNode.getSymbol(),\n declaration,\n });\n }\n }\n return out;\n}\n\nfunction requiredSpecifier(initializer: Node | undefined): string | undefined {\n const { Node, SyntaxKind } = loadTsMorph();\n const call =\n initializer !== undefined && Node.isAwaitExpression(initializer)\n ? initializer.getExpression()\n : initializer;\n if (call === undefined || !Node.isCallExpression(call)) return undefined;\n const callee = call.getExpression();\n const isRequire = Node.isIdentifier(callee) && callee.getText() === 'require';\n if (!isRequire && callee.getKind() !== SyntaxKind.ImportKeyword) return undefined;\n const [argument] = call.getArguments();\n return argument !== undefined && Node.isStringLiteral(argument)\n ? argument.getLiteralText()\n : undefined;\n}\n\nfunction literalName(node: Node): string {\n const { Node } = loadTsMorph();\n if (Node.isStringLiteral(node) || Node.isNoSubstitutionTemplateLiteral(node)) {\n return node.getLiteralText();\n }\n return node.getText();\n}\n\n/** The key of an object-literal member, or `undefined` when it is computed. */\nexport function propertyKey(property: ObjectLiteralElementLike): string | undefined {\n const { Node } = loadTsMorph();\n if (Node.isSpreadAssignment(property)) return undefined;\n const nameNode = property.getNameNode();\n if (Node.isComputedPropertyName(nameNode)) return undefined;\n return literalName(nameNode);\n}\n\nexport type ReferenceKind = 'reference' | 'shorthand' | 'export';\n\nexport interface BindingReference {\n readonly node: Identifier;\n /** `shorthand` is `{ name }`, `export` is `export { name }`; both keep the old key visible. */\n readonly kind: ReferenceKind;\n}\n\n/** Every use of the binding outside its own declaration, resolved by symbol so shadowing is respected. */\nexport function referencesTo(\n script: SourceFile,\n binding: PackageBinding,\n): readonly BindingReference[] {\n const { Node, SyntaxKind } = loadTsMorph();\n const target = binding.symbol?.compilerSymbol;\n if (target === undefined) return [];\n const checker = script.getProject().getTypeChecker();\n const out: BindingReference[] = [];\n for (const node of script.getDescendantsOfKind(SyntaxKind.Identifier)) {\n if (node.getText() !== binding.local || isInside(node, binding.declaration)) continue;\n const parent = node.getParent();\n if (Node.isShorthandPropertyAssignment(parent)) {\n if (checker.getShorthandAssignmentValueSymbol(parent)?.compilerSymbol === target) {\n out.push({ node, kind: 'shorthand' });\n }\n continue;\n }\n if (Node.isExportSpecifier(parent)) {\n if (\n parent.getNameNode() === node &&\n parent.getLocalTargetSymbol()?.compilerSymbol === target\n ) {\n out.push({ node, kind: 'export' });\n }\n continue;\n }\n if (node.getSymbol()?.compilerSymbol === target) out.push({ node, kind: 'reference' });\n }\n return out;\n}\n\nfunction isInside(node: Node, ancestor: Node): boolean {\n return node.getFirstAncestor((candidate) => candidate === ancestor) !== undefined;\n}\n\n/** The declaration that binds `name` anywhere in the script, ignoring those in `except`. */\nexport function declaresName(\n script: SourceFile,\n name: string,\n except: readonly Node[] = [],\n): Node | undefined {\n const { SyntaxKind } = loadTsMorph();\n for (const node of script.getDescendantsOfKind(SyntaxKind.Identifier)) {\n if (node.getText() !== name) continue;\n const parent = node.getParent();\n if (!bindsIdentifier(parent, node)) continue;\n if (except.some((skip) => skip === parent || isInside(parent, skip))) continue;\n return parent;\n }\n return undefined;\n}\n\nfunction bindsIdentifier(parent: Node, node: Identifier): boolean {\n const { Node } = loadTsMorph();\n if (\n Node.isVariableDeclaration(parent) ||\n Node.isBindingElement(parent) ||\n Node.isFunctionDeclaration(parent) ||\n Node.isClassDeclaration(parent) ||\n Node.isParameterDeclaration(parent) ||\n Node.isEnumDeclaration(parent)\n ) {\n return parent.getNameNode() === node;\n }\n if (Node.isImportSpecifier(parent)) {\n return (parent.getAliasNode() ?? parent.getNameNode()) === node;\n }\n if (Node.isImportClause(parent)) return parent.getDefaultImport() === node;\n if (Node.isNamespaceImport(parent)) return parent.getNameNode() === node;\n return false;\n}\n\n/** Identifiers spelled `name` that are member names (`x.name`), never the package's binding. */\nexport function memberAccesses(script: SourceFile, name: string): readonly Identifier[] {\n const { Node, SyntaxKind } = loadTsMorph();\n return script.getDescendantsOfKind(SyntaxKind.Identifier).filter((node) => {\n const parent = node.getParent();\n return (\n node.getText() === name &&\n Node.isPropertyAccessExpression(parent) &&\n parent.getNameNode() === node\n );\n });\n}\n\nexport function replaceNode(node: Node, text: string): TextEdit {\n return { start: node.getStart(), end: node.getEnd(), text };\n}\n\n/** Splice non-overlapping edits into `text`. */\nexport function applyTextEdits(text: string, edits: readonly TextEdit[]): string {\n const ordered = [...edits].sort((left, right) => right.start - left.start);\n let output = text;\n let floor = Number.POSITIVE_INFINITY;\n for (const edit of ordered) {\n if (edit.end > floor) throw new Error('overlapping codemod edits');\n output = `${output.slice(0, edit.start)}${edit.text}${output.slice(edit.end)}`;\n floor = edit.start;\n }\n return output;\n}\n","/**\n * Ledger entry 9: `fetchPreviewDocument()`/`fetchPreviewGlobal()` on the root\n * entry → `definePreview({ serverURL, depth }).fetchDocument()`/`.fetchGlobal()`\n * on `payload-live-preview/server`.\n */\nimport {\n PACKAGE_NAME,\n declaresName,\n loadTsMorph,\n packageBindings,\n propertyKey,\n referencesTo,\n type PackageBinding,\n} from '../ast';\nimport type { CodemodImplementation, CodemodConflict, CodemodPlan, TextEdit } from '../types';\nimport type {\n CallExpression,\n ImportDeclaration,\n ObjectLiteralExpression,\n SourceFile,\n} from 'ts-morph';\n\nconst ID = 'move-fetch-preview-helpers';\nconst SERVER_SPECIFIER = `${PACKAGE_NAME}/server`;\nconst METHOD: Readonly<Record<string, string>> = {\n fetchPreviewDocument: 'fetchDocument',\n fetchPreviewGlobal: 'fetchGlobal',\n};\nconst SERVER_OPTIONS = new Set(['serverURL', 'apiRoute', 'depth']);\nconst DROPPED_OPTIONS = new Set(['draft', 'fetchFn']);\n/**\n * What `ReadDocumentOptions`/`ReadGlobalOptions` accept (src/server/preview.ts).\n * 1.x spelled the target `collection` and `global` too, so there is no rename to\n * make here — a key that is in neither set is one this codemod cannot place, and\n * passing it through unannounced produces a file that does not compile.\n */\nconst SHARED_READ_OPTIONS = ['authorization', 'locale', 'headers', 'signal', 'errorMode'];\nconst READ_OPTIONS: Readonly<Record<string, readonly string[]>> = {\n fetchPreviewDocument: ['collection', 'where', ...SHARED_READ_OPTIONS],\n fetchPreviewGlobal: ['global', ...SHARED_READ_OPTIONS],\n};\nconst DEPTH_TODO =\n 'depth: 1 /* TODO(pll migrate): the 1.x default; match the runtime mergeDepth */';\nconst AUTHORIZATION_TODO =\n 'authorization: null /* TODO(pll migrate): pass the verdict from authorizePreviewRequest(); ' +\n 'null reads the published document */';\n\nfunction conflict(line: number, reason: string): CodemodConflict {\n return { codemod: ID, reason, line };\n}\n\ninterface RewrittenCall {\n readonly edit: TextEdit;\n readonly notes: readonly CodemodConflict[];\n}\n\nfunction rewriteCall(\n call: CallExpression,\n options: ObjectLiteralExpression,\n imported: string,\n): RewrittenCall {\n const server: string[] = [];\n const read: string[] = [];\n const dropped: string[] = [];\n const keys = new Set<string>();\n for (const property of options.getProperties()) {\n const key = propertyKey(property);\n if (key !== undefined) keys.add(key);\n if (key !== undefined && SERVER_OPTIONS.has(key)) server.push(property.getText());\n else if (key !== undefined && DROPPED_OPTIONS.has(key)) dropped.push(key);\n else read.push(property.getText());\n }\n if (!keys.has('depth')) server.push(DEPTH_TODO);\n if (!keys.has('authorization')) read.push(AUTHORIZATION_TODO);\n const accepted = READ_OPTIONS[imported] ?? [];\n const unplaceable = [...keys].filter(\n (key) => !SERVER_OPTIONS.has(key) && !DROPPED_OPTIONS.has(key) && !accepted.includes(key),\n );\n const typeArguments = call.getTypeArguments().map((argument) => argument.getText());\n const generic = typeArguments.length === 0 ? '' : `<${typeArguments.join(', ')}>`;\n const method = METHOD[imported] ?? imported;\n const text = `definePreview({ ${server.join(', ')} }).${method}${generic}({ ${read.join(', ')} })`;\n const droppedNote = dropped.length === 0 ? '' : `, and ${dropped.join('/')} was dropped`;\n const line = call.getStartLineNumber();\n const notes = [\n conflict(\n line,\n `${imported}() was rewritten onto definePreview().${method}(); it now returns a ` +\n `PreviewFetchResult (check ok/data) and needs a real authorization for drafts${droppedNote}`,\n ),\n ];\n if (unplaceable.length > 0) {\n notes.push(\n conflict(\n line,\n `${imported}() was passed ${unplaceable.map((key) => `\\`${key}\\``).join(', ')}, which ` +\n `.${method}() does not accept; it takes ${accepted.join(', ')}. The key was carried ` +\n 'over unchanged and will not compile — place it by hand',\n ),\n );\n }\n return { edit: { start: call.getStart(), end: call.getEnd(), text }, notes };\n}\n\nfunction importLine(quote: string, names: readonly string[], specifier: string): string {\n return `import { ${names.join(', ')} } from ${quote}${specifier}${quote};`;\n}\n\n/** Drop the moved names from their root imports and make sure `definePreview` is imported from the server entry. */\nfunction rewriteImports(script: SourceFile, bindings: readonly PackageBinding[]): TextEdit[] {\n const { Node } = loadTsMorph();\n const edits: TextEdit[] = [];\n const declarations = new Set<ImportDeclaration>();\n for (const binding of bindings) {\n if (Node.isImportDeclaration(binding.declaration)) declarations.add(binding.declaration);\n }\n const serverImport = script\n .getImportDeclarations()\n .find(\n (declaration) =>\n declaration.getModuleSpecifierValue() === SERVER_SPECIFIER && !declaration.isTypeOnly(),\n );\n const hasDefinePreview =\n serverImport?.getNamedImports().some((spec) => spec.getName() === 'definePreview') === true;\n let serverLine: string | undefined;\n if (serverImport !== undefined && !hasDefinePreview) {\n const quote = serverImport.getModuleSpecifier().getQuoteKind();\n const names = [\n ...serverImport.getNamedImports().map((spec) => spec.getText()),\n 'definePreview',\n ];\n const defaultImport = serverImport.getDefaultImport()?.getText();\n const clauses =\n defaultImport === undefined ? names.join(', ') : `${defaultImport}, { ${names.join(', ')} }`;\n const text =\n defaultImport === undefined\n ? importLine(quote, names, SERVER_SPECIFIER)\n : `import ${clauses} from ${quote}${SERVER_SPECIFIER}${quote};`;\n edits.push({ start: serverImport.getStart(), end: serverImport.getEnd(), text });\n }\n for (const declaration of declarations) {\n const quote = declaration.getModuleSpecifier().getQuoteKind();\n const remaining = declaration\n .getNamedImports()\n .filter((spec) => !(spec.getName() in METHOD))\n .map((spec) => spec.getText());\n const defaultImport = declaration.getDefaultImport()?.getText();\n const clauses = [\n defaultImport,\n remaining.length === 0 ? undefined : `{ ${remaining.join(', ')} }`,\n ].filter((clause): clause is string => clause !== undefined);\n const typeOnly = declaration.isTypeOnly() ? 'type ' : '';\n const kept =\n clauses.length === 0\n ? ''\n : `import ${typeOnly}${clauses.join(', ')} from ${quote}${PACKAGE_NAME}${quote};`;\n if (serverImport === undefined && serverLine === undefined) {\n serverLine = importLine(quote, ['definePreview'], SERVER_SPECIFIER);\n edits.push({\n start: declaration.getStart(),\n end: declaration.getEnd(),\n text: kept === '' ? serverLine : `${kept}\\n${serverLine}`,\n });\n } else {\n // A removed declaration takes its line break with it.\n const end = declaration.getEnd();\n const trailingNewline = kept === '' && script.getFullText()[end] === '\\n' ? 1 : 0;\n edits.push({ start: declaration.getStart(), end: end + trailingNewline, text: kept });\n }\n }\n return edits;\n}\n\nfunction plan(script: SourceFile, bindings: readonly PackageBinding[]): CodemodPlan {\n const { Node } = loadTsMorph();\n const blocking: CodemodConflict[] = [];\n const notes: CodemodConflict[] = [];\n const edits: TextEdit[] = [];\n for (const binding of bindings) {\n if (binding.kind === 'require') {\n blocking.push(\n conflict(\n binding.declaration.getStartLineNumber(),\n `${binding.imported} is bound with require(); rewrite it onto definePreview() from ` +\n `${SERVER_SPECIFIER} by hand`,\n ),\n );\n continue;\n }\n for (const reference of referencesTo(script, binding)) {\n const line = reference.node.getStartLineNumber();\n const call = reference.node.getParent();\n const isCall =\n reference.kind === 'reference' &&\n Node.isCallExpression(call) &&\n call.getExpression() === reference.node;\n if (!isCall) {\n blocking.push(\n conflict(\n line,\n `${binding.local} is used other than as a direct call; rewrite it onto definePreview() by hand`,\n ),\n );\n continue;\n }\n const [options] = call.getArguments();\n if (\n options === undefined ||\n !Node.isObjectLiteralExpression(options) ||\n options.getProperties().some((property) => Node.isSpreadAssignment(property))\n ) {\n blocking.push(\n conflict(\n line,\n `${binding.imported}() options are not a plain object literal, so serverURL/depth ` +\n 'cannot be split out; rewrite it onto definePreview() by hand',\n ),\n );\n continue;\n }\n const rewritten = rewriteCall(call, options, binding.imported);\n edits.push(rewritten.edit);\n notes.push(...rewritten.notes);\n }\n }\n const serverDeclaration = script\n .getImportDeclarations()\n .filter((declaration) => declaration.getModuleSpecifierValue() === SERVER_SPECIFIER);\n const foreign = declaresName(script, 'definePreview', serverDeclaration);\n if (foreign !== undefined) {\n blocking.push(\n conflict(\n foreign.getStartLineNumber(),\n `this module already binds a definePreview that is not ${SERVER_SPECIFIER}'s; rename it, ` +\n 'then move the fetch helpers by hand',\n ),\n );\n }\n if (blocking.length > 0) return { edits: [], conflicts: [...blocking, ...notes] };\n edits.push(...rewriteImports(script, bindings));\n return { edits, conflicts: notes };\n}\n\nexport const moveFetchPreviewHelpers: CodemodImplementation = {\n id: ID,\n summary:\n '`fetchPreviewDocument`/`fetchPreviewGlobal` from the root → `definePreview().fetchDocument`/`.fetchGlobal` (payload-live-preview/server)',\n ledgerEntry: 9,\n apply(script) {\n const bindings = packageBindings(script).filter(\n (binding) => binding.specifier === PACKAGE_NAME && binding.imported in METHOD,\n );\n if (bindings.length === 0) return { edits: [], conflicts: [] };\n return plan(script, bindings);\n },\n};\n","/** Ledger entry 13: `hasPreviewIntent(request, { adminOrigins })` → `{ allowedOrigins }`. */\nimport { loadTsMorph, packageBindings, propertyKey, referencesTo, replaceNode } from '../ast';\nimport type { CodemodImplementation, CodemodConflict, TextEdit } from '../types';\n\nconst ID = 'rename-admin-origins-option';\nconst CALLEE = 'hasPreviewIntent';\nconst OLD_KEY = 'adminOrigins';\nconst NEW_KEY = 'allowedOrigins';\nconst BY_HAND = `if they carry \\`${OLD_KEY}\\`, rename it to \\`${NEW_KEY}\\``;\n\nexport const renameAdminOriginsOption: CodemodImplementation = {\n id: ID,\n summary: '`hasPreviewIntent(request, { adminOrigins })` → `{ allowedOrigins }`',\n ledgerEntry: 13,\n apply(script) {\n const { Node } = loadTsMorph();\n const edits: TextEdit[] = [];\n const conflicts: CodemodConflict[] = [];\n const bindings = packageBindings(script).filter((binding) => binding.imported === CALLEE);\n for (const binding of bindings) {\n for (const reference of referencesTo(script, binding)) {\n const call = reference.node.getParent();\n if (reference.kind !== 'reference' || !Node.isCallExpression(call)) continue;\n if (call.getExpression() !== reference.node) continue;\n const options = call.getArguments()[1];\n if (options === undefined) continue;\n const line = options.getStartLineNumber();\n if (!Node.isObjectLiteralExpression(options)) {\n conflicts.push({\n codemod: ID,\n line,\n reason: `${CALLEE}() options are not a literal; ${BY_HAND}`,\n });\n continue;\n }\n const properties = options.getProperties();\n const keys = properties.map((property) => propertyKey(property));\n // With both names the package reads `allowedOrigins` and ignores the\n // alias; renamed, the later key would win instead.\n if (keys.includes(OLD_KEY) && keys.includes(NEW_KEY)) {\n conflicts.push({\n codemod: ID,\n line,\n reason: `${CALLEE}() is given both ${OLD_KEY} and ${NEW_KEY}; ${NEW_KEY} wins, drop ${OLD_KEY} by hand`,\n });\n continue;\n }\n for (const property of properties) {\n if (Node.isSpreadAssignment(property)) {\n conflicts.push({\n codemod: ID,\n line: property.getStartLineNumber(),\n reason: `${CALLEE}() spreads its options; ${BY_HAND}`,\n });\n } else if (propertyKey(property) !== OLD_KEY) {\n continue;\n } else if (Node.isShorthandPropertyAssignment(property)) {\n edits.push(replaceNode(property, `${NEW_KEY}: ${OLD_KEY}`));\n } else if (Node.isPropertyAssignment(property)) {\n edits.push(replaceNode(property.getNameNode(), NEW_KEY));\n }\n }\n }\n }\n return { edits, conflicts };\n },\n};\n","/** Ledger entry 7: `createPreviewBindings({ authorized })` → `{ authorization }`. */\nimport { loadTsMorph, packageBindings, propertyKey, referencesTo, replaceNode } from '../ast';\nimport type { CodemodImplementation, CodemodConflict, TextEdit } from '../types';\n\nconst ID = 'rename-bindings-authorized-option';\nconst OLD_KEY = 'authorized';\nconst NEW_KEY = 'authorization';\nconst BY_HAND =\n `if they carry \\`${OLD_KEY}\\`, rename it to \\`${NEW_KEY}\\` and pass the verdict from ` +\n 'authorizePreviewRequest()';\n/**\n * `false` has an exact equivalent — an unauthorized response suppresses every\n * binding, which is what `null` means — so it is rewritten. Nothing else does:\n * only a real context from `authorizePreviewRequest()` authorizes emission, and\n * a boolean left under the new name does not compile (TS2322).\n */\nconst BOOLEAN_REFUSED =\n `\\`${NEW_KEY}\\` takes the context from authorizePreviewRequest(); the boolean 1.x ` +\n 'accepted is not. The key was renamed and its value left as it stands — pass the ' +\n 'verdict, or `null` for a public response';\n\nexport const renameBindingsAuthorizedOption: CodemodImplementation = {\n id: ID,\n summary: '`createPreviewBindings({ authorized })` → `{ authorization }`',\n ledgerEntry: 7,\n apply(script) {\n const { Node } = loadTsMorph();\n const edits: TextEdit[] = [];\n const conflicts: CodemodConflict[] = [];\n const bindings = packageBindings(script).filter(\n (binding) => binding.imported === 'createPreviewBindings',\n );\n for (const binding of bindings) {\n for (const reference of referencesTo(script, binding)) {\n const call = reference.node.getParent();\n if (reference.kind !== 'reference' || !Node.isCallExpression(call)) continue;\n if (call.getExpression() !== reference.node) continue;\n const [options] = call.getArguments();\n if (options === undefined) continue;\n const line = options.getStartLineNumber();\n if (!Node.isObjectLiteralExpression(options)) {\n conflicts.push({\n codemod: ID,\n line,\n reason: `createPreviewBindings() options are not a literal; ${BY_HAND}`,\n });\n continue;\n }\n for (const property of options.getProperties()) {\n if (Node.isSpreadAssignment(property)) {\n conflicts.push({\n codemod: ID,\n line: property.getStartLineNumber(),\n reason: `createPreviewBindings() spreads its options; ${BY_HAND}`,\n });\n } else if (propertyKey(property) !== OLD_KEY) {\n continue;\n } else if (Node.isShorthandPropertyAssignment(property)) {\n edits.push(replaceNode(property, `${NEW_KEY}: ${OLD_KEY}`));\n conflicts.push({\n codemod: ID,\n line: property.getStartLineNumber(),\n reason: BOOLEAN_REFUSED,\n });\n } else if (Node.isPropertyAssignment(property)) {\n const value = property.getInitializer();\n if (value !== undefined && Node.isFalseLiteral(value)) {\n edits.push(replaceNode(property, `${NEW_KEY}: null`));\n continue;\n }\n edits.push(replaceNode(property.getNameNode(), NEW_KEY));\n conflicts.push({\n codemod: ID,\n line: property.getStartLineNumber(),\n reason: BOOLEAN_REFUSED,\n });\n }\n }\n }\n }\n return { edits, conflicts };\n },\n};\n","/** Ledger entry 1: `isPreviewRequest()` → `hasPreviewIntent()`, same signature. */\nimport {\n declaresName,\n memberAccesses,\n packageBindings,\n referencesTo,\n replaceNode,\n type PackageBinding,\n} from '../ast';\nimport type { CodemodImplementation, CodemodConflict, CodemodPlan, TextEdit } from '../types';\n\nconst ID = 'rename-is-preview-request';\nconst OLD_NAME = 'isPreviewRequest';\nconst NEW_NAME = 'hasPreviewIntent';\n\nfunction conflict(line: number, reason: string): CodemodConflict {\n return { codemod: ID, reason, line };\n}\n\nfunction renameBinding(binding: PackageBinding): TextEdit {\n // `import { isPreviewRequest as hasPreviewIntent }` collapses to the bare name.\n if (binding.aliased && binding.local === NEW_NAME) {\n return replaceNode(binding.importedNode.getParentOrThrow(), NEW_NAME);\n }\n return replaceNode(binding.importedNode, NEW_NAME);\n}\n\nfunction plan(\n bindings: readonly PackageBinding[],\n script: Parameters<CodemodImplementation['apply']>[0],\n): CodemodPlan {\n const blocking: CodemodConflict[] = [];\n const edits: TextEdit[] = [];\n const existing = declaresName(\n script,\n NEW_NAME,\n bindings.map((binding) => binding.declaration),\n );\n if (existing !== undefined) {\n blocking.push(\n conflict(\n existing.getStartLineNumber(),\n `this module already binds ${NEW_NAME}; rename it (or drop the wrapper and import the ` +\n `package's ${NEW_NAME} directly), then rename ${OLD_NAME} by hand`,\n ),\n );\n }\n for (const binding of bindings) {\n edits.push(renameBinding(binding));\n if (binding.aliased) continue;\n for (const reference of referencesTo(script, binding)) {\n if (reference.kind === 'reference') {\n edits.push(replaceNode(reference.node, NEW_NAME));\n } else if (reference.kind === 'shorthand') {\n blocking.push(\n conflict(\n reference.node.getStartLineNumber(),\n `{ ${OLD_NAME} } keeps the old key for whoever reads it; write ` +\n `{ ${OLD_NAME}: ${NEW_NAME} } or rename the key and its readers by hand`,\n ),\n );\n } else {\n blocking.push(\n conflict(\n reference.node.getStartLineNumber(),\n `${OLD_NAME} is re-exported under its old name; rename the export and its ` +\n `importers, or write export { ${NEW_NAME} as ${OLD_NAME} }`,\n ),\n );\n }\n }\n }\n const notes = memberAccesses(script, OLD_NAME).map((node) =>\n conflict(\n node.getStartLineNumber(),\n `.${OLD_NAME} is a member of this module's own object, not the package import, and was ` +\n 'left alone; check that it does not wrap the removed API',\n ),\n );\n if (blocking.length > 0) return { edits: [], conflicts: [...blocking, ...notes] };\n return { edits, conflicts: notes };\n}\n\nexport const renameIsPreviewRequest: CodemodImplementation = {\n id: ID,\n summary: '`isPreviewRequest()` → `hasPreviewIntent()` (same signature)',\n ledgerEntry: 1,\n apply(script) {\n const bindings = packageBindings(script).filter((binding) => binding.imported === OLD_NAME);\n if (bindings.length === 0) return { edits: [], conflicts: [] };\n return plan(bindings, script);\n },\n};\n","/** Where the script lives in a file: the whole file, or the script blocks of a component. */\nimport { extname } from 'node:path';\nimport type { ScriptKind } from './ast';\n\nexport interface ScriptBlock {\n readonly start: number;\n readonly end: number;\n readonly kind: ScriptKind;\n}\n\nconst WHOLE_FILE: Readonly<Record<string, ScriptKind>> = {\n '.ts': 'ts',\n '.mts': 'ts',\n '.cts': 'ts',\n '.tsx': 'tsx',\n '.js': 'js',\n '.mjs': 'js',\n '.cjs': 'js',\n '.jsx': 'jsx',\n};\nconst COMPONENT_EXTENSIONS = new Set(['.astro', '.vue', '.svelte']);\nconst FRONTMATTER = /^---\\r?\\n([\\s\\S]*?)\\r?\\n---/u;\n// Browsers close a script on `</script` followed by anything up to `>`, so the\n// end tag must accept that too, or a stray `</script foo>` would swallow the\n// rest of the file into one block.\nconst SCRIPT_TAG = /<script(?:\\s[^>]*)?>([\\s\\S]*?)<\\/script\\b[^>]*>/giu;\n\nexport function scriptBlocks(source: string, fileName: string): readonly ScriptBlock[] {\n const extension = extname(fileName).toLowerCase();\n if (!COMPONENT_EXTENSIONS.has(extension)) {\n return [{ start: 0, end: source.length, kind: WHOLE_FILE[extension] ?? 'ts' }];\n }\n const blocks: ScriptBlock[] = [];\n const frontmatter = extension === '.astro' ? FRONTMATTER.exec(source) : null;\n if (frontmatter?.[1] !== undefined) {\n const start = frontmatter.index + frontmatter[0].indexOf('\\n') + 1;\n blocks.push({ start, end: start + frontmatter[1].length, kind: 'ts' });\n }\n for (const match of source.matchAll(SCRIPT_TAG)) {\n const body = match[1] ?? '';\n if (body.trim() === '') continue;\n const start = match.index + match[0].lastIndexOf(body);\n blocks.push({ start, end: start + body.length, kind: 'ts' });\n }\n return blocks;\n}\n","/**\n * `pll migrate`: the 1.x → 2.0 codemods and the driver that applies them to one\n * source string. Rewrites are planned on the AST (ts-morph) so only names the\n * package binds are touched; see ADR 0007.\n */\nimport { applyTextEdits, parseScript } from './ast';\nimport { moveFetchPreviewHelpers } from './codemods/move-fetch-preview-helpers';\nimport { renameAdminOriginsOption } from './codemods/rename-admin-origins-option';\nimport { renameBindingsAuthorizedOption } from './codemods/rename-bindings-authorized-option';\nimport { renameIsPreviewRequest } from './codemods/rename-is-preview-request';\nimport { scriptBlocks } from './script-blocks';\nimport type {\n Codemod,\n CodemodConflict,\n CodemodEdit,\n CodemodImplementation,\n CodemodLineEdit,\n} from './types';\n\nexport type {\n Codemod,\n CodemodConflict,\n CodemodEdit,\n CodemodLineEdit,\n CodemodPlan,\n TextEdit,\n} from './types';\n\nconst PACKAGE_REFERENCE =\n /(?:\\bfrom\\s*|\\bimport\\s*\\(?\\s*|\\brequire\\s*\\(\\s*)['\"]payload-live-preview(?:\\/[^'\"]*)?['\"]/u;\n\n/** Whether the source names the package in an `import`, `import()` or `require()`. @internal */\nexport function importsThisPackage(source: string): boolean {\n return PACKAGE_REFERENCE.test(source);\n}\n\n// The option rename follows the function rename so it sees the new binding.\nconst IMPLEMENTATIONS: readonly CodemodImplementation[] = [\n renameIsPreviewRequest,\n renameAdminOriginsOption,\n renameBindingsAuthorizedOption,\n moveFetchPreviewHelpers,\n];\n\n/**\n * The codemods in the order they run. Each is idempotent. Metadata only: the\n * rewrite is internal, so importing this entry's types does not require\n * `ts-morph`, which is needed only to run `pll migrate`.\n * @internal\n */\nexport const CODEMODS: readonly Codemod[] = IMPLEMENTATIONS;\n\nexport interface MigrateSourceOptions {\n /** Restrict to these codemod ids. */\n readonly only?: readonly string[];\n /**\n * Decides how the source is parsed: `.astro`, `.vue` and `.svelte` by script\n * block, JSX by extension. Defaults to a `.ts` module.\n */\n readonly fileName?: string;\n}\n\nexport interface MigrateSourceResult {\n readonly output: string;\n readonly edits: readonly CodemodEdit[];\n readonly conflicts: readonly CodemodConflict[];\n}\n\nfunction lineNumberAt(source: string, offset: number): number {\n let line = 1;\n for (let index = 0; index < offset; index += 1) if (source[index] === '\\n') line += 1;\n return line;\n}\n\n/** The changed lines between two versions, trimmed to the differing middle. */\nfunction lineEdits(before: string, after: string, firstLine: number): CodemodLineEdit[] {\n const oldLines = before.split('\\n');\n const newLines = after.split('\\n');\n let prefix = 0;\n while (\n prefix < oldLines.length &&\n prefix < newLines.length &&\n oldLines[prefix] === newLines[prefix]\n ) {\n prefix += 1;\n }\n let suffix = 0;\n while (\n suffix < oldLines.length - prefix &&\n suffix < newLines.length - prefix &&\n oldLines[oldLines.length - 1 - suffix] === newLines[newLines.length - 1 - suffix]\n ) {\n suffix += 1;\n }\n const oldMiddle = oldLines.slice(prefix, oldLines.length - suffix);\n const newMiddle = newLines.slice(prefix, newLines.length - suffix);\n const changed: CodemodLineEdit[] = [];\n for (let index = 0; index < Math.max(oldMiddle.length, newMiddle.length); index += 1) {\n const before = oldMiddle[index] ?? '';\n const after = newMiddle[index] ?? '';\n if (before !== after) changed.push({ line: firstLine + prefix + index, before, after });\n }\n return changed;\n}\n\n/** Apply every codemod (or the chosen subset) to one source string. */\nexport function migrateSource(\n source: string,\n options: MigrateSourceOptions = {},\n): MigrateSourceResult {\n const chosen =\n options.only === undefined\n ? IMPLEMENTATIONS\n : IMPLEMENTATIONS.filter((codemod) => options.only?.includes(codemod.id));\n if (chosen.length === 0 || !importsThisPackage(source)) {\n return { output: source, edits: [], conflicts: [] };\n }\n const byCodemod = new Map<string, CodemodLineEdit[]>();\n const conflicts: CodemodConflict[] = [];\n let output = '';\n let cursor = 0;\n for (const block of scriptBlocks(source, options.fileName ?? 'source.ts')) {\n output += source.slice(cursor, block.start);\n const firstLine = lineNumberAt(source, block.start);\n let text = source.slice(block.start, block.end);\n for (const codemod of chosen) {\n const plan = codemod.apply(parseScript(text, block.kind));\n for (const item of plan.conflicts) {\n conflicts.push(\n item.line === undefined ? item : { ...item, line: item.line + firstLine - 1 },\n );\n }\n if (plan.edits.length === 0) continue;\n const next = applyTextEdits(text, plan.edits);\n const lines = byCodemod.get(codemod.id) ?? [];\n lines.push(...lineEdits(text, next, firstLine));\n byCodemod.set(codemod.id, lines);\n text = next;\n }\n output += text;\n cursor = block.end;\n }\n output += source.slice(cursor);\n const edits = [...byCodemod].map(([codemod, lines]) => ({ codemod, count: lines.length, lines }));\n return { output, edits, conflicts };\n}\n"],"mappings":"sEAqBO,IAEHA,EACAC,EAHSC,EAAe,uBAKrB,SAASC,IACd,QAAgB,IAAZH,EACF,IACEA,EAAUI,cAA0BC,IAA1BD,CAA+B,WAC3C,OAASE,GACP,MAAM,IAAIC,MAAM,8DAA+D,CAC7EC,MAAOF,GAEX,CAEF,OAAON,CACT,CAGO,SAASS,EAAYC,EAAcC,GACxC,MAAMC,EAAQT,IAOd,OANAF,IAAY,IAAIW,EAAMC,QAAQ,CAC5BC,uBAAuB,EACvBC,qBAAqB,EACrBC,8BAA8B,EAC9BC,gBAAiB,CAAEC,SAAS,EAAMC,OAAO,KAEpClB,EAAQmB,iBAAiB,WAAWT,IAAQD,EAAM,CAAEW,WAAW,GACxE,CAEO,SAASC,EAAmBC,GACjC,OAAOA,IAAcrB,GAAgBqB,EAAUC,WAAW,GAAGtB,KAC/D,CAkBO,SAASuB,EAAgBC,GAC9B,MAAMC,KAAEA,EAAAC,WAAMA,GAAezB,IACvB0B,EAAwB,GAC9B,UAAWC,KAAeJ,EAAOK,wBAAyB,CACxD,MAAMR,EAAYO,EA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AUwG,EAAOnG,MAAM6H,GAEhB,CAAElI,SAAQL,MADH,IAAIqI,GAAW5F,IAAI,EAAEjB,EAASiI,MAAK,CAASjI,UAASoI,MAAOH,EAAM9G,OAAQ8G,WAChE/F,YAC1B,Q","ignoreList":[]}
1
+ {"version":3,"file":"migrate.js","names":["tsMorph","project","PACKAGE_NAME","loadTsMorph","createRequire","url","error","Error","cause","parseScript","text","kind","morph","Project","useInMemoryFileSystem","skipLoadingLibFiles","skipFileDependencyResolution","compilerOptions","allowJs","noLib","createSourceFile","overwrite","isPackageSpecifier","specifier","startsWith","packageBindings","script","Node","SyntaxKind","out","declaration","getImportDeclarations","getModuleSpecifierValue","spec","getNamedImports","alias","getAliasNode","localNode","getNameNode","push","imported","getName","local","getText","importedNode","aliased","symbol","getSymbol","getDescendantsOfKind","VariableDeclaration","requiredSpecifier","getInitializer","pattern","isObjectBindingPattern","element","getElements","nameNode","isIdentifier","propertyName","getPropertyNameNode","literalName","initializer","call","isAwaitExpression","getExpression","isCallExpression","callee","getKind","ImportKeyword","argument","getArguments","isStringLiteral","getLiteralText","node","isNoSubstitutionTemplateLiteral","propertyKey","property","isSpreadAssignment","isComputedPropertyName","referencesTo","binding","target","compilerSymbol","checker","getProject","getTypeChecker","Identifier","isInside","parent","getParent","isShorthandPropertyAssignment","getShorthandAssignmentValueSymbol","isExportSpecifier","getLocalTargetSymbol","ancestor","getFirstAncestor","candidate","declaresName","name","except","bindsIdentifier","some","skip","isVariableDeclaration","isBindingElement","isFunctionDeclaration","isClassDeclaration","isParameterDeclaration","isEnumDeclaration","isImportSpecifier","isImportClause","getDefaultImport","isNamespaceImport","replaceNode","start","getStart","end","getEnd","applyTextEdits","edits","ordered","sort","left","right","output","floor","Number","POSITIVE_INFINITY","edit","slice","ID","SERVER_SPECIFIER","METHOD","fetchPreviewDocument","fetchPreviewGlobal","SERVER_OPTIONS","Set","DROPPED_OPTIONS","SHARED_READ_OPTIONS","READ_OPTIONS","conflict","line","reason","codemod","rewriteCall","options","server","read","dropped","keys","getProperties","key","add","has","accepted","unplaceable","filter","includes","typeArguments","getTypeArguments","map","generic","length","join","method","droppedNote","getStartLineNumber","notes","importLine","quote","names","moveFetchPreviewHelpers","id","summary","ledgerEntry","apply","bindings","conflicts","blocking","reference","isObjectLiteralExpression","rewritten","serverDeclaration","foreign","declarations","isImportDeclaration","serverImport","find","isTypeOnly","hasDefinePreview","serverLine","getModuleSpecifier","getQuoteKind","defaultImport","clauses","remaining","clause","typeOnly","kept","trailingNewline","getFullText","rewriteImports","plan","CALLEE","OLD_KEY","NEW_KEY","BY_HAND","renameAdminOriginsOption","properties","isPropertyAssignment","BOOLEAN_REFUSED","renameBindingsAuthorizedOption","value","isFalseLiteral","OLD_NAME","NEW_NAME","renameBinding","getParentOrThrow","renameIsPreviewRequest","notice","existing","isPropertyAccessExpression","memberAccesses","WHOLE_FILE","COMPONENT_EXTENSIONS","FRONTMATTER","SCRIPT_TAG","PACKAGE_REFERENCE","importsThisPackage","source","test","IMPLEMENTATIONS","CODEMODS","lineNumberAt","offset","index","lineEdits","before","after","firstLine","oldLines","split","newLines","prefix","suffix","oldMiddle","newMiddle","changed","Math","max","migrateSource","chosen","only","byCodemod","Map","cursor","block","fileName","extension","extname","toLowerCase","blocks","frontmatter","exec","indexOf","match","matchAll","body","trim","lastIndexOf","scriptBlocks","item","next","lines","get","set","count"],"sources":["../src/migrate/ast.ts","../src/migrate/codemods/move-fetch-preview-helpers.ts","../src/migrate/codemods/rename-admin-origins-option.ts","../src/migrate/codemods/rename-bindings-authorized-option.ts","../src/migrate/codemods/rename-is-preview-request.ts","../src/migrate/script-blocks.ts","../src/migrate/index.ts"],"sourcesContent":["/**\n * ts-morph access for the codemods: parsing, the package's bindings in a\n * script and the references those bindings have. ts-morph is loaded on first\n * use so the entry stays importable without the optional peer.\n */\nimport { createRequire } from 'node:module';\nimport type * as TsMorphModule from 'ts-morph';\nimport type {\n Identifier,\n Node,\n ObjectLiteralElementLike,\n Project,\n SourceFile,\n Symbol as TsSymbol,\n} from 'ts-morph';\nimport type { TextEdit } from './types';\n\ntype TsMorph = typeof TsMorphModule;\n\nexport type ScriptKind = 'ts' | 'tsx' | 'js' | 'jsx';\n\nexport const PACKAGE_NAME = 'payload-live-preview';\n\nlet tsMorph: TsMorph | undefined;\nlet project: Project | undefined;\n\nexport function loadTsMorph(): TsMorph {\n if (tsMorph === undefined) {\n try {\n tsMorph = createRequire(import.meta.url)('ts-morph') as TsMorph;\n } catch (error) {\n throw new Error('pll migrate needs ts-morph: npm install --save-dev ts-morph', {\n cause: error,\n });\n }\n }\n return tsMorph;\n}\n\n/** Parse one script into a throwaway in-memory project; the previous script is discarded. */\nexport function parseScript(text: string, kind: ScriptKind): SourceFile {\n const morph = loadTsMorph();\n project ??= new morph.Project({\n useInMemoryFileSystem: true,\n skipLoadingLibFiles: true,\n skipFileDependencyResolution: true,\n compilerOptions: { allowJs: true, noLib: true },\n });\n return project.createSourceFile(`/script.${kind}`, text, { overwrite: true });\n}\n\nexport function isPackageSpecifier(specifier: string): boolean {\n return specifier === PACKAGE_NAME || specifier.startsWith(`${PACKAGE_NAME}/`);\n}\n\n/** A name the script binds from the package, by `import` or by destructuring `require()`/`import()`. */\nexport interface PackageBinding {\n /** The exported name, as the package spells it. */\n readonly imported: string;\n /** The name the script uses; equals `imported` unless aliased. */\n readonly local: string;\n readonly specifier: string;\n readonly kind: 'import' | 'require';\n /** The node spelling the exported name; rewritten when the export is renamed. */\n readonly importedNode: Node;\n readonly aliased: boolean;\n readonly symbol: TsSymbol | undefined;\n /** The import declaration or variable declaration that binds it. */\n readonly declaration: Node;\n}\n\nexport function packageBindings(script: SourceFile): readonly PackageBinding[] {\n const { Node, SyntaxKind } = loadTsMorph();\n const out: PackageBinding[] = [];\n for (const declaration of script.getImportDeclarations()) {\n const specifier = declaration.getModuleSpecifierValue();\n if (!isPackageSpecifier(specifier)) continue;\n for (const spec of declaration.getNamedImports()) {\n const alias = spec.getAliasNode();\n const localNode = alias ?? spec.getNameNode();\n out.push({\n imported: spec.getName(),\n local: localNode.getText(),\n specifier,\n kind: 'import',\n importedNode: spec.getNameNode(),\n aliased: alias !== undefined,\n symbol: localNode.getSymbol(),\n declaration,\n });\n }\n }\n for (const declaration of script.getDescendantsOfKind(SyntaxKind.VariableDeclaration)) {\n const specifier = requiredSpecifier(declaration.getInitializer());\n const pattern = declaration.getNameNode();\n if (specifier === undefined || !isPackageSpecifier(specifier)) continue;\n if (!Node.isObjectBindingPattern(pattern)) continue;\n for (const element of pattern.getElements()) {\n const nameNode = element.getNameNode();\n if (!Node.isIdentifier(nameNode)) continue;\n const propertyName = element.getPropertyNameNode();\n out.push({\n imported: propertyName === undefined ? nameNode.getText() : literalName(propertyName),\n local: nameNode.getText(),\n specifier,\n kind: 'require',\n importedNode: propertyName ?? nameNode,\n aliased: propertyName !== undefined,\n symbol: nameNode.getSymbol(),\n declaration,\n });\n }\n }\n return out;\n}\n\nfunction requiredSpecifier(initializer: Node | undefined): string | undefined {\n const { Node, SyntaxKind } = loadTsMorph();\n const call =\n initializer !== undefined && Node.isAwaitExpression(initializer)\n ? initializer.getExpression()\n : initializer;\n if (call === undefined || !Node.isCallExpression(call)) return undefined;\n const callee = call.getExpression();\n const isRequire = Node.isIdentifier(callee) && callee.getText() === 'require';\n if (!isRequire && callee.getKind() !== SyntaxKind.ImportKeyword) return undefined;\n const [argument] = call.getArguments();\n return argument !== undefined && Node.isStringLiteral(argument)\n ? argument.getLiteralText()\n : undefined;\n}\n\nfunction literalName(node: Node): string {\n const { Node } = loadTsMorph();\n if (Node.isStringLiteral(node) || Node.isNoSubstitutionTemplateLiteral(node)) {\n return node.getLiteralText();\n }\n return node.getText();\n}\n\n/** The key of an object-literal member, or `undefined` when it is computed. */\nexport function propertyKey(property: ObjectLiteralElementLike): string | undefined {\n const { Node } = loadTsMorph();\n if (Node.isSpreadAssignment(property)) return undefined;\n const nameNode = property.getNameNode();\n if (Node.isComputedPropertyName(nameNode)) return undefined;\n return literalName(nameNode);\n}\n\nexport type ReferenceKind = 'reference' | 'shorthand' | 'export';\n\nexport interface BindingReference {\n readonly node: Identifier;\n /** `shorthand` is `{ name }`, `export` is `export { name }`; both keep the old key visible. */\n readonly kind: ReferenceKind;\n}\n\n/** Every use of the binding outside its own declaration, resolved by symbol so shadowing is respected. */\nexport function referencesTo(\n script: SourceFile,\n binding: PackageBinding,\n): readonly BindingReference[] {\n const { Node, SyntaxKind } = loadTsMorph();\n const target = binding.symbol?.compilerSymbol;\n if (target === undefined) return [];\n const checker = script.getProject().getTypeChecker();\n const out: BindingReference[] = [];\n for (const node of script.getDescendantsOfKind(SyntaxKind.Identifier)) {\n if (node.getText() !== binding.local || isInside(node, binding.declaration)) continue;\n const parent = node.getParent();\n if (Node.isShorthandPropertyAssignment(parent)) {\n if (checker.getShorthandAssignmentValueSymbol(parent)?.compilerSymbol === target) {\n out.push({ node, kind: 'shorthand' });\n }\n continue;\n }\n if (Node.isExportSpecifier(parent)) {\n if (\n parent.getNameNode() === node &&\n parent.getLocalTargetSymbol()?.compilerSymbol === target\n ) {\n out.push({ node, kind: 'export' });\n }\n continue;\n }\n if (node.getSymbol()?.compilerSymbol === target) out.push({ node, kind: 'reference' });\n }\n return out;\n}\n\nfunction isInside(node: Node, ancestor: Node): boolean {\n return node.getFirstAncestor((candidate) => candidate === ancestor) !== undefined;\n}\n\n/** The declaration that binds `name` anywhere in the script, ignoring those in `except`. */\nexport function declaresName(\n script: SourceFile,\n name: string,\n except: readonly Node[] = [],\n): Node | undefined {\n const { SyntaxKind } = loadTsMorph();\n for (const node of script.getDescendantsOfKind(SyntaxKind.Identifier)) {\n if (node.getText() !== name) continue;\n const parent = node.getParent();\n if (!bindsIdentifier(parent, node)) continue;\n if (except.some((skip) => skip === parent || isInside(parent, skip))) continue;\n return parent;\n }\n return undefined;\n}\n\nfunction bindsIdentifier(parent: Node, node: Identifier): boolean {\n const { Node } = loadTsMorph();\n if (\n Node.isVariableDeclaration(parent) ||\n Node.isBindingElement(parent) ||\n Node.isFunctionDeclaration(parent) ||\n Node.isClassDeclaration(parent) ||\n Node.isParameterDeclaration(parent) ||\n Node.isEnumDeclaration(parent)\n ) {\n return parent.getNameNode() === node;\n }\n if (Node.isImportSpecifier(parent)) {\n return (parent.getAliasNode() ?? parent.getNameNode()) === node;\n }\n if (Node.isImportClause(parent)) return parent.getDefaultImport() === node;\n if (Node.isNamespaceImport(parent)) return parent.getNameNode() === node;\n return false;\n}\n\n/** Identifiers spelled `name` that are member names (`x.name`), never the package's binding. */\nexport function memberAccesses(script: SourceFile, name: string): readonly Identifier[] {\n const { Node, SyntaxKind } = loadTsMorph();\n return script.getDescendantsOfKind(SyntaxKind.Identifier).filter((node) => {\n const parent = node.getParent();\n return (\n node.getText() === name &&\n Node.isPropertyAccessExpression(parent) &&\n parent.getNameNode() === node\n );\n });\n}\n\nexport function replaceNode(node: Node, text: string): TextEdit {\n return { start: node.getStart(), end: node.getEnd(), text };\n}\n\n/** Splice non-overlapping edits into `text`. */\nexport function applyTextEdits(text: string, edits: readonly TextEdit[]): string {\n const ordered = [...edits].sort((left, right) => right.start - left.start);\n let output = text;\n let floor = Number.POSITIVE_INFINITY;\n for (const edit of ordered) {\n if (edit.end > floor) throw new Error('overlapping codemod edits');\n output = `${output.slice(0, edit.start)}${edit.text}${output.slice(edit.end)}`;\n floor = edit.start;\n }\n return output;\n}\n","/**\n * Ledger entry 9: `fetchPreviewDocument()`/`fetchPreviewGlobal()` on the root\n * entry → `definePreview({ serverURL, depth }).fetchDocument()`/`.fetchGlobal()`\n * on `payload-live-preview/server`.\n */\nimport {\n PACKAGE_NAME,\n declaresName,\n loadTsMorph,\n packageBindings,\n propertyKey,\n referencesTo,\n type PackageBinding,\n} from '../ast';\nimport type { CodemodImplementation, CodemodConflict, CodemodPlan, TextEdit } from '../types';\nimport type {\n CallExpression,\n ImportDeclaration,\n ObjectLiteralExpression,\n SourceFile,\n} from 'ts-morph';\n\nconst ID = 'move-fetch-preview-helpers';\nconst SERVER_SPECIFIER = `${PACKAGE_NAME}/server`;\nconst METHOD: Readonly<Record<string, string>> = {\n fetchPreviewDocument: 'fetchDocument',\n fetchPreviewGlobal: 'fetchGlobal',\n};\nconst SERVER_OPTIONS = new Set(['serverURL', 'apiRoute', 'depth']);\nconst DROPPED_OPTIONS = new Set(['draft', 'fetchFn']);\n/**\n * What `ReadDocumentOptions`/`ReadGlobalOptions` accept (src/server/preview.ts).\n * 1.x spelled the target `collection` and `global` too, so there is no rename to\n * make here — a key that is in neither set is one this codemod cannot place, and\n * passing it through unannounced produces a file that does not compile.\n */\nconst SHARED_READ_OPTIONS = ['authorization', 'locale', 'headers', 'signal', 'errorMode'];\nconst READ_OPTIONS: Readonly<Record<string, readonly string[]>> = {\n fetchPreviewDocument: ['collection', 'where', ...SHARED_READ_OPTIONS],\n fetchPreviewGlobal: ['global', ...SHARED_READ_OPTIONS],\n};\nconst DEPTH_TODO =\n 'depth: 1 /* TODO(pll migrate): the 1.x default; match the runtime mergeDepth */';\nconst AUTHORIZATION_TODO =\n 'authorization: null /* TODO(pll migrate): pass the verdict from authorizePreviewRequest(); ' +\n 'null reads the published document */';\n\nfunction conflict(line: number, reason: string): CodemodConflict {\n return { codemod: ID, reason, line };\n}\n\ninterface RewrittenCall {\n readonly edit: TextEdit;\n readonly notes: readonly CodemodConflict[];\n}\n\nfunction rewriteCall(\n call: CallExpression,\n options: ObjectLiteralExpression,\n imported: string,\n): RewrittenCall {\n const server: string[] = [];\n const read: string[] = [];\n const dropped: string[] = [];\n const keys = new Set<string>();\n for (const property of options.getProperties()) {\n const key = propertyKey(property);\n if (key !== undefined) keys.add(key);\n if (key !== undefined && SERVER_OPTIONS.has(key)) server.push(property.getText());\n else if (key !== undefined && DROPPED_OPTIONS.has(key)) dropped.push(key);\n else read.push(property.getText());\n }\n if (!keys.has('depth')) server.push(DEPTH_TODO);\n if (!keys.has('authorization')) read.push(AUTHORIZATION_TODO);\n const accepted = READ_OPTIONS[imported] ?? [];\n const unplaceable = [...keys].filter(\n (key) => !SERVER_OPTIONS.has(key) && !DROPPED_OPTIONS.has(key) && !accepted.includes(key),\n );\n const typeArguments = call.getTypeArguments().map((argument) => argument.getText());\n const generic = typeArguments.length === 0 ? '' : `<${typeArguments.join(', ')}>`;\n const method = METHOD[imported] ?? imported;\n const text = `definePreview({ ${server.join(', ')} }).${method}${generic}({ ${read.join(', ')} })`;\n const droppedNote = dropped.length === 0 ? '' : `, and ${dropped.join('/')} was dropped`;\n const line = call.getStartLineNumber();\n const notes = [\n conflict(\n line,\n `${imported}() was rewritten onto definePreview().${method}(); it now returns a ` +\n `PreviewFetchResult (check ok/data) and needs a real authorization for drafts${droppedNote}`,\n ),\n ];\n if (unplaceable.length > 0) {\n notes.push(\n conflict(\n line,\n `${imported}() was passed ${unplaceable.map((key) => `\\`${key}\\``).join(', ')}, which ` +\n `.${method}() does not accept; it takes ${accepted.join(', ')}. The key was carried ` +\n 'over unchanged and will not compile — place it by hand',\n ),\n );\n }\n return { edit: { start: call.getStart(), end: call.getEnd(), text }, notes };\n}\n\nfunction importLine(quote: string, names: readonly string[], specifier: string): string {\n return `import { ${names.join(', ')} } from ${quote}${specifier}${quote};`;\n}\n\n/** Drop the moved names from their root imports and make sure `definePreview` is imported from the server entry. */\nfunction rewriteImports(script: SourceFile, bindings: readonly PackageBinding[]): TextEdit[] {\n const { Node } = loadTsMorph();\n const edits: TextEdit[] = [];\n const declarations = new Set<ImportDeclaration>();\n for (const binding of bindings) {\n if (Node.isImportDeclaration(binding.declaration)) declarations.add(binding.declaration);\n }\n const serverImport = script\n .getImportDeclarations()\n .find(\n (declaration) =>\n declaration.getModuleSpecifierValue() === SERVER_SPECIFIER && !declaration.isTypeOnly(),\n );\n const hasDefinePreview =\n serverImport?.getNamedImports().some((spec) => spec.getName() === 'definePreview') === true;\n let serverLine: string | undefined;\n if (serverImport !== undefined && !hasDefinePreview) {\n const quote = serverImport.getModuleSpecifier().getQuoteKind();\n const names = [\n ...serverImport.getNamedImports().map((spec) => spec.getText()),\n 'definePreview',\n ];\n const defaultImport = serverImport.getDefaultImport()?.getText();\n const clauses =\n defaultImport === undefined ? names.join(', ') : `${defaultImport}, { ${names.join(', ')} }`;\n const text =\n defaultImport === undefined\n ? importLine(quote, names, SERVER_SPECIFIER)\n : `import ${clauses} from ${quote}${SERVER_SPECIFIER}${quote};`;\n edits.push({ start: serverImport.getStart(), end: serverImport.getEnd(), text });\n }\n for (const declaration of declarations) {\n const quote = declaration.getModuleSpecifier().getQuoteKind();\n const remaining = declaration\n .getNamedImports()\n .filter((spec) => !(spec.getName() in METHOD))\n .map((spec) => spec.getText());\n const defaultImport = declaration.getDefaultImport()?.getText();\n const clauses = [\n defaultImport,\n remaining.length === 0 ? undefined : `{ ${remaining.join(', ')} }`,\n ].filter((clause): clause is string => clause !== undefined);\n const typeOnly = declaration.isTypeOnly() ? 'type ' : '';\n const kept =\n clauses.length === 0\n ? ''\n : `import ${typeOnly}${clauses.join(', ')} from ${quote}${PACKAGE_NAME}${quote};`;\n if (serverImport === undefined && serverLine === undefined) {\n serverLine = importLine(quote, ['definePreview'], SERVER_SPECIFIER);\n edits.push({\n start: declaration.getStart(),\n end: declaration.getEnd(),\n text: kept === '' ? serverLine : `${kept}\\n${serverLine}`,\n });\n } else {\n // A removed declaration takes its line break with it.\n const end = declaration.getEnd();\n const trailingNewline = kept === '' && script.getFullText()[end] === '\\n' ? 1 : 0;\n edits.push({ start: declaration.getStart(), end: end + trailingNewline, text: kept });\n }\n }\n return edits;\n}\n\nfunction plan(script: SourceFile, bindings: readonly PackageBinding[]): CodemodPlan {\n const { Node } = loadTsMorph();\n const blocking: CodemodConflict[] = [];\n const notes: CodemodConflict[] = [];\n const edits: TextEdit[] = [];\n for (const binding of bindings) {\n if (binding.kind === 'require') {\n blocking.push(\n conflict(\n binding.declaration.getStartLineNumber(),\n `${binding.imported} is bound with require(); rewrite it onto definePreview() from ` +\n `${SERVER_SPECIFIER} by hand`,\n ),\n );\n continue;\n }\n for (const reference of referencesTo(script, binding)) {\n const line = reference.node.getStartLineNumber();\n const call = reference.node.getParent();\n const isCall =\n reference.kind === 'reference' &&\n Node.isCallExpression(call) &&\n call.getExpression() === reference.node;\n if (!isCall) {\n blocking.push(\n conflict(\n line,\n `${binding.local} is used other than as a direct call; rewrite it onto definePreview() by hand`,\n ),\n );\n continue;\n }\n const [options] = call.getArguments();\n if (\n options === undefined ||\n !Node.isObjectLiteralExpression(options) ||\n options.getProperties().some((property) => Node.isSpreadAssignment(property))\n ) {\n blocking.push(\n conflict(\n line,\n `${binding.imported}() options are not a plain object literal, so serverURL/depth ` +\n 'cannot be split out; rewrite it onto definePreview() by hand',\n ),\n );\n continue;\n }\n const rewritten = rewriteCall(call, options, binding.imported);\n edits.push(rewritten.edit);\n notes.push(...rewritten.notes);\n }\n }\n const serverDeclaration = script\n .getImportDeclarations()\n .filter((declaration) => declaration.getModuleSpecifierValue() === SERVER_SPECIFIER);\n const foreign = declaresName(script, 'definePreview', serverDeclaration);\n if (foreign !== undefined) {\n blocking.push(\n conflict(\n foreign.getStartLineNumber(),\n `this module already binds a definePreview that is not ${SERVER_SPECIFIER}'s; rename it, ` +\n 'then move the fetch helpers by hand',\n ),\n );\n }\n if (blocking.length > 0) return { edits: [], conflicts: [...blocking, ...notes] };\n edits.push(...rewriteImports(script, bindings));\n return { edits, conflicts: notes };\n}\n\nexport const moveFetchPreviewHelpers: CodemodImplementation = {\n id: ID,\n summary:\n '`fetchPreviewDocument`/`fetchPreviewGlobal` from the root → `definePreview().fetchDocument`/`.fetchGlobal` (payload-live-preview/server)',\n ledgerEntry: 9,\n apply(script) {\n const bindings = packageBindings(script).filter(\n (binding) => binding.specifier === PACKAGE_NAME && binding.imported in METHOD,\n );\n if (bindings.length === 0) return { edits: [], conflicts: [] };\n return plan(script, bindings);\n },\n};\n","/** Ledger entry 13: `hasPreviewIntent(request, { adminOrigins })` → `{ allowedOrigins }`. */\nimport { loadTsMorph, packageBindings, propertyKey, referencesTo, replaceNode } from '../ast';\nimport type { CodemodImplementation, CodemodConflict, TextEdit } from '../types';\n\nconst ID = 'rename-admin-origins-option';\nconst CALLEE = 'hasPreviewIntent';\nconst OLD_KEY = 'adminOrigins';\nconst NEW_KEY = 'allowedOrigins';\nconst BY_HAND = `if they carry \\`${OLD_KEY}\\`, rename it to \\`${NEW_KEY}\\``;\n\nexport const renameAdminOriginsOption: CodemodImplementation = {\n id: ID,\n summary: '`hasPreviewIntent(request, { adminOrigins })` → `{ allowedOrigins }`',\n ledgerEntry: 13,\n apply(script) {\n const { Node } = loadTsMorph();\n const edits: TextEdit[] = [];\n const conflicts: CodemodConflict[] = [];\n const bindings = packageBindings(script).filter((binding) => binding.imported === CALLEE);\n for (const binding of bindings) {\n for (const reference of referencesTo(script, binding)) {\n const call = reference.node.getParent();\n if (reference.kind !== 'reference' || !Node.isCallExpression(call)) continue;\n if (call.getExpression() !== reference.node) continue;\n const options = call.getArguments()[1];\n if (options === undefined) continue;\n const line = options.getStartLineNumber();\n if (!Node.isObjectLiteralExpression(options)) {\n conflicts.push({\n codemod: ID,\n line,\n reason: `${CALLEE}() options are not a literal; ${BY_HAND}`,\n });\n continue;\n }\n const properties = options.getProperties();\n const keys = properties.map((property) => propertyKey(property));\n // With both names the package reads `allowedOrigins` and ignores the\n // alias; renamed, the later key would win instead.\n if (keys.includes(OLD_KEY) && keys.includes(NEW_KEY)) {\n conflicts.push({\n codemod: ID,\n line,\n reason: `${CALLEE}() is given both ${OLD_KEY} and ${NEW_KEY}; ${NEW_KEY} wins, drop ${OLD_KEY} by hand`,\n });\n continue;\n }\n for (const property of properties) {\n if (Node.isSpreadAssignment(property)) {\n conflicts.push({\n codemod: ID,\n line: property.getStartLineNumber(),\n reason: `${CALLEE}() spreads its options; ${BY_HAND}`,\n });\n } else if (propertyKey(property) !== OLD_KEY) {\n continue;\n } else if (Node.isShorthandPropertyAssignment(property)) {\n edits.push(replaceNode(property, `${NEW_KEY}: ${OLD_KEY}`));\n } else if (Node.isPropertyAssignment(property)) {\n edits.push(replaceNode(property.getNameNode(), NEW_KEY));\n }\n }\n }\n }\n return { edits, conflicts };\n },\n};\n","/** Ledger entry 7: `createPreviewBindings({ authorized })` → `{ authorization }`. */\nimport { loadTsMorph, packageBindings, propertyKey, referencesTo, replaceNode } from '../ast';\nimport type { CodemodImplementation, CodemodConflict, TextEdit } from '../types';\n\nconst ID = 'rename-bindings-authorized-option';\nconst OLD_KEY = 'authorized';\nconst NEW_KEY = 'authorization';\nconst BY_HAND =\n `if they carry \\`${OLD_KEY}\\`, rename it to \\`${NEW_KEY}\\` and pass the verdict from ` +\n 'authorizePreviewRequest()';\n/**\n * `false` has an exact equivalent — an unauthorized response suppresses every\n * binding, which is what `null` means — so it is rewritten. Nothing else does:\n * only a real context from `authorizePreviewRequest()` authorizes emission, and\n * a boolean left under the new name does not compile (TS2322).\n */\nconst BOOLEAN_REFUSED =\n `\\`${NEW_KEY}\\` takes the context from authorizePreviewRequest(); the boolean 1.x ` +\n 'accepted is not. The key was renamed and its value left as it stands — pass the ' +\n 'verdict, or `null` for a public response';\n\nexport const renameBindingsAuthorizedOption: CodemodImplementation = {\n id: ID,\n summary: '`createPreviewBindings({ authorized })` → `{ authorization }`',\n ledgerEntry: 7,\n apply(script) {\n const { Node } = loadTsMorph();\n const edits: TextEdit[] = [];\n const conflicts: CodemodConflict[] = [];\n const bindings = packageBindings(script).filter(\n (binding) => binding.imported === 'createPreviewBindings',\n );\n for (const binding of bindings) {\n for (const reference of referencesTo(script, binding)) {\n const call = reference.node.getParent();\n if (reference.kind !== 'reference' || !Node.isCallExpression(call)) continue;\n if (call.getExpression() !== reference.node) continue;\n const [options] = call.getArguments();\n if (options === undefined) continue;\n const line = options.getStartLineNumber();\n if (!Node.isObjectLiteralExpression(options)) {\n conflicts.push({\n codemod: ID,\n line,\n reason: `createPreviewBindings() options are not a literal; ${BY_HAND}`,\n });\n continue;\n }\n for (const property of options.getProperties()) {\n if (Node.isSpreadAssignment(property)) {\n conflicts.push({\n codemod: ID,\n line: property.getStartLineNumber(),\n reason: `createPreviewBindings() spreads its options; ${BY_HAND}`,\n });\n } else if (propertyKey(property) !== OLD_KEY) {\n continue;\n } else if (Node.isShorthandPropertyAssignment(property)) {\n edits.push(replaceNode(property, `${NEW_KEY}: ${OLD_KEY}`));\n conflicts.push({\n codemod: ID,\n line: property.getStartLineNumber(),\n reason: BOOLEAN_REFUSED,\n });\n } else if (Node.isPropertyAssignment(property)) {\n const value = property.getInitializer();\n if (value !== undefined && Node.isFalseLiteral(value)) {\n edits.push(replaceNode(property, `${NEW_KEY}: null`));\n continue;\n }\n edits.push(replaceNode(property.getNameNode(), NEW_KEY));\n conflicts.push({\n codemod: ID,\n line: property.getStartLineNumber(),\n reason: BOOLEAN_REFUSED,\n });\n }\n }\n }\n }\n return { edits, conflicts };\n },\n};\n","/** Ledger entry 1: `isPreviewRequest()` → `hasPreviewIntent()`, same signature. */\nimport {\n declaresName,\n memberAccesses,\n packageBindings,\n referencesTo,\n replaceNode,\n type PackageBinding,\n} from '../ast';\nimport type { CodemodImplementation, CodemodConflict, CodemodPlan, TextEdit } from '../types';\n\nconst ID = 'rename-is-preview-request';\nconst OLD_NAME = 'isPreviewRequest';\nconst NEW_NAME = 'hasPreviewIntent';\n\nfunction conflict(line: number, reason: string): CodemodConflict {\n return { codemod: ID, reason, line };\n}\n\nfunction renameBinding(binding: PackageBinding): TextEdit {\n // `import { isPreviewRequest as hasPreviewIntent }` collapses to the bare name.\n if (binding.aliased && binding.local === NEW_NAME) {\n return replaceNode(binding.importedNode.getParentOrThrow(), NEW_NAME);\n }\n return replaceNode(binding.importedNode, NEW_NAME);\n}\n\nfunction plan(\n bindings: readonly PackageBinding[],\n script: Parameters<CodemodImplementation['apply']>[0],\n): CodemodPlan {\n const blocking: CodemodConflict[] = [];\n const edits: TextEdit[] = [];\n const existing = declaresName(\n script,\n NEW_NAME,\n bindings.map((binding) => binding.declaration),\n );\n if (existing !== undefined) {\n blocking.push(\n conflict(\n existing.getStartLineNumber(),\n `this module already binds ${NEW_NAME}; rename it (or drop the wrapper and import the ` +\n `package's ${NEW_NAME} directly), then rename ${OLD_NAME} by hand`,\n ),\n );\n }\n for (const binding of bindings) {\n edits.push(renameBinding(binding));\n if (binding.aliased) continue;\n for (const reference of referencesTo(script, binding)) {\n if (reference.kind === 'reference') {\n edits.push(replaceNode(reference.node, NEW_NAME));\n } else if (reference.kind === 'shorthand') {\n blocking.push(\n conflict(\n reference.node.getStartLineNumber(),\n `{ ${OLD_NAME} } keeps the old key for whoever reads it; write ` +\n `{ ${OLD_NAME}: ${NEW_NAME} } or rename the key and its readers by hand`,\n ),\n );\n } else {\n blocking.push(\n conflict(\n reference.node.getStartLineNumber(),\n `${OLD_NAME} is re-exported under its old name; rename the export and its ` +\n `importers, or write export { ${NEW_NAME} as ${OLD_NAME} }`,\n ),\n );\n }\n }\n }\n const notes = memberAccesses(script, OLD_NAME).map((node) =>\n conflict(\n node.getStartLineNumber(),\n `.${OLD_NAME} is a member of this module's own object, not the package import, and was ` +\n 'left alone; check that it does not wrap the removed API',\n ),\n );\n if (blocking.length > 0) return { edits: [], conflicts: [...blocking, ...notes] };\n return { edits, conflicts: notes };\n}\n\nexport const renameIsPreviewRequest: CodemodImplementation = {\n id: ID,\n summary: '`isPreviewRequest()` → `hasPreviewIntent()` (same signature)',\n ledgerEntry: 1,\n // The rename keeps behaviour, and that is the part worth saying: the 2.0\n // adapters count only the query, and a renamed call silently does not.\n notice:\n 'hasPreviewIntent() takes the options isPreviewRequest() took and, without `signals`, counts ' +\n 'the same three: a preview query parameter, Sec-Fetch-Dest: iframe and an admin Referer. The ' +\n \"2.0 adapters count only the query; where a call should agree with them, pass { signals: ['query'] } \" +\n '(docs/migration.md).',\n apply(script) {\n const bindings = packageBindings(script).filter((binding) => binding.imported === OLD_NAME);\n if (bindings.length === 0) return { edits: [], conflicts: [] };\n return plan(bindings, script);\n },\n};\n","/** Where the script lives in a file: the whole file, or the script blocks of a component. */\nimport { extname } from 'node:path';\nimport type { ScriptKind } from './ast';\n\nexport interface ScriptBlock {\n readonly start: number;\n readonly end: number;\n readonly kind: ScriptKind;\n}\n\nconst WHOLE_FILE: Readonly<Record<string, ScriptKind>> = {\n '.ts': 'ts',\n '.mts': 'ts',\n '.cts': 'ts',\n '.tsx': 'tsx',\n '.js': 'js',\n '.mjs': 'js',\n '.cjs': 'js',\n '.jsx': 'jsx',\n};\nconst COMPONENT_EXTENSIONS = new Set(['.astro', '.vue', '.svelte']);\nconst FRONTMATTER = /^---\\r?\\n([\\s\\S]*?)\\r?\\n---/u;\n// Browsers close a script on `</script` followed by anything up to `>`, so the\n// end tag must accept that too, or a stray `</script foo>` would swallow the\n// rest of the file into one block.\nconst SCRIPT_TAG = /<script(?:\\s[^>]*)?>([\\s\\S]*?)<\\/script\\b[^>]*>/giu;\n\nexport function scriptBlocks(source: string, fileName: string): readonly ScriptBlock[] {\n const extension = extname(fileName).toLowerCase();\n if (!COMPONENT_EXTENSIONS.has(extension)) {\n return [{ start: 0, end: source.length, kind: WHOLE_FILE[extension] ?? 'ts' }];\n }\n const blocks: ScriptBlock[] = [];\n const frontmatter = extension === '.astro' ? FRONTMATTER.exec(source) : null;\n if (frontmatter?.[1] !== undefined) {\n const start = frontmatter.index + frontmatter[0].indexOf('\\n') + 1;\n blocks.push({ start, end: start + frontmatter[1].length, kind: 'ts' });\n }\n for (const match of source.matchAll(SCRIPT_TAG)) {\n const body = match[1] ?? '';\n if (body.trim() === '') continue;\n const start = match.index + match[0].lastIndexOf(body);\n blocks.push({ start, end: start + body.length, kind: 'ts' });\n }\n return blocks;\n}\n","/**\n * `pll migrate`: the 1.x → 2.0 codemods and the driver that applies them to one\n * source string. Rewrites are planned on the AST (ts-morph) so only names the\n * package binds are touched; see ADR 0007.\n */\nimport { applyTextEdits, parseScript } from './ast';\nimport { moveFetchPreviewHelpers } from './codemods/move-fetch-preview-helpers';\nimport { renameAdminOriginsOption } from './codemods/rename-admin-origins-option';\nimport { renameBindingsAuthorizedOption } from './codemods/rename-bindings-authorized-option';\nimport { renameIsPreviewRequest } from './codemods/rename-is-preview-request';\nimport { scriptBlocks } from './script-blocks';\nimport type {\n Codemod,\n CodemodConflict,\n CodemodEdit,\n CodemodImplementation,\n CodemodLineEdit,\n} from './types';\n\nexport type {\n Codemod,\n CodemodConflict,\n CodemodEdit,\n CodemodLineEdit,\n CodemodPlan,\n TextEdit,\n} from './types';\n\nconst PACKAGE_REFERENCE =\n /(?:\\bfrom\\s*|\\bimport\\s*\\(?\\s*|\\brequire\\s*\\(\\s*)['\"]payload-live-preview(?:\\/[^'\"]*)?['\"]/u;\n\n/** Whether the source names the package in an `import`, `import()` or `require()`. @internal */\nexport function importsThisPackage(source: string): boolean {\n return PACKAGE_REFERENCE.test(source);\n}\n\n// The option rename follows the function rename so it sees the new binding.\nconst IMPLEMENTATIONS: readonly CodemodImplementation[] = [\n renameIsPreviewRequest,\n renameAdminOriginsOption,\n renameBindingsAuthorizedOption,\n moveFetchPreviewHelpers,\n];\n\n/**\n * The codemods in the order they run. Each is idempotent. Metadata only: the\n * rewrite is internal, so importing this entry's types does not require\n * `ts-morph`, which is needed only to run `pll migrate`.\n * @internal\n */\nexport const CODEMODS: readonly Codemod[] = IMPLEMENTATIONS;\n\nexport interface MigrateSourceOptions {\n /** Restrict to these codemod ids. */\n readonly only?: readonly string[];\n /**\n * Decides how the source is parsed: `.astro`, `.vue` and `.svelte` by script\n * block, JSX by extension. Defaults to a `.ts` module.\n */\n readonly fileName?: string;\n}\n\nexport interface MigrateSourceResult {\n readonly output: string;\n readonly edits: readonly CodemodEdit[];\n readonly conflicts: readonly CodemodConflict[];\n}\n\nfunction lineNumberAt(source: string, offset: number): number {\n let line = 1;\n for (let index = 0; index < offset; index += 1) if (source[index] === '\\n') line += 1;\n return line;\n}\n\n/** The changed lines between two versions, trimmed to the differing middle. */\nfunction lineEdits(before: string, after: string, firstLine: number): CodemodLineEdit[] {\n const oldLines = before.split('\\n');\n const newLines = after.split('\\n');\n let prefix = 0;\n while (\n prefix < oldLines.length &&\n prefix < newLines.length &&\n oldLines[prefix] === newLines[prefix]\n ) {\n prefix += 1;\n }\n let suffix = 0;\n while (\n suffix < oldLines.length - prefix &&\n suffix < newLines.length - prefix &&\n oldLines[oldLines.length - 1 - suffix] === newLines[newLines.length - 1 - suffix]\n ) {\n suffix += 1;\n }\n const oldMiddle = oldLines.slice(prefix, oldLines.length - suffix);\n const newMiddle = newLines.slice(prefix, newLines.length - suffix);\n const changed: CodemodLineEdit[] = [];\n for (let index = 0; index < Math.max(oldMiddle.length, newMiddle.length); index += 1) {\n const before = oldMiddle[index] ?? '';\n const after = newMiddle[index] ?? '';\n if (before !== after) changed.push({ line: firstLine + prefix + index, before, after });\n }\n return changed;\n}\n\n/** Apply every codemod (or the chosen subset) to one source string. */\nexport function migrateSource(\n source: string,\n options: MigrateSourceOptions = {},\n): MigrateSourceResult {\n const chosen =\n options.only === undefined\n ? IMPLEMENTATIONS\n : IMPLEMENTATIONS.filter((codemod) => options.only?.includes(codemod.id));\n if (chosen.length === 0 || !importsThisPackage(source)) {\n return { output: source, edits: [], conflicts: [] };\n }\n const byCodemod = new Map<string, CodemodLineEdit[]>();\n const conflicts: CodemodConflict[] = [];\n let output = '';\n let cursor = 0;\n for (const block of scriptBlocks(source, options.fileName ?? 'source.ts')) {\n output += source.slice(cursor, block.start);\n const firstLine = lineNumberAt(source, block.start);\n let text = source.slice(block.start, block.end);\n for (const codemod of chosen) {\n const plan = codemod.apply(parseScript(text, block.kind));\n for (const item of plan.conflicts) {\n conflicts.push(\n item.line === undefined ? item : { ...item, line: item.line + firstLine - 1 },\n );\n }\n if (plan.edits.length === 0) continue;\n const next = applyTextEdits(text, plan.edits);\n const lines = byCodemod.get(codemod.id) ?? [];\n lines.push(...lineEdits(text, next, firstLine));\n byCodemod.set(codemod.id, lines);\n text = next;\n }\n output += text;\n cursor = block.end;\n }\n output += source.slice(cursor);\n const edits = [...byCodemod].map(([codemod, lines]) => ({ codemod, count: lines.length,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UyG,EAAOpG,MAAM8H,EAAQC,EAAM9I,OACrC,MAAM6H,EAAYN,GAAaJ,EAAQ2B,EAAM9I,OAC7C,IAAIxG,EAAO2N,EAAOpG,MAAM+H,EAAM9I,MAAO8I,EAAM5I,KAC3C,UAAW2B,KAAW4G,EAAQ,CAC5B,MAAMjD,EAAO3D,EAAQgC,MAAMtK,EAAYC,EAAMsP,EAAMrP,OACnD,UAAWoQ,KAAQrE,EAAKzB,UACtBA,EAAU1I,UACM,IAAdwO,EAAKlI,KAAqBkI,EAAO,IAAKA,EAAMlI,KAAMkI,EAAKlI,KAAOkG,EAAY,IAG9E,GAA0B,IAAtBrC,EAAKnF,MAAM2C,OAAc,SAC7B,MAAM8G,EAAO1J,EAAe5G,EAAMgM,EAAKnF,OACjC0J,EAAQpB,EAAUqB,IAAInI,EAAQ6B,KAAO,GAC3CqG,EAAM1O,QAAQqM,GAAUlO,EAAMsQ,EAAMjC,IACpCc,EAAUsB,IAAIpI,EAAQ6B,GAAIqG,GAC1BvQ,EAAOsQ,CACT,CACApJ,GAAUlH,EACVqP,EAASC,EAAM5I,GACjB,CAGA,OAFAQ,GAAUyG,EAAOpG,MAAM8H,GAEhB,CAAEnI,SAAQL,MADH,IAAIsI,GAAW7F,IAAI,EAAEjB,EAASkI,MAAK,CAASlI,UAASqI,MAAOH,EAAM/G,OAAQ+G,WAChEhG,YAC1B,Q","ignoreList":[]}
@@ -215,7 +215,8 @@ interface PreviewAdapterOptions<Req = Request> {
215
215
  readonly assetPath?: string;
216
216
  /**
217
217
  * A runtime artifact to inject instead of the full one — `LEAN_RUNTIME` from
218
- * `payload-live-preview/lean`, which is about 5.5 KB gzip smaller and reports
218
+ * `payload-live-preview/lean`, which is several KB gzip smaller (measured in
219
+ * docs/options.md) and reports
219
220
  * LP0104 when a page needs a feature it left out (docs/options.md). Importing
220
221
  * it is what puts those bytes in your build; the default costs nothing.
221
222
  */
package/dist/plugins.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";function e(e){return("object"==typeof e&&null!==e||"function"==typeof e)&&"function"==typeof e.then&&(Promise.resolve(e).catch(()=>{}),!0)}function t(t){return(...n)=>{try{e(t(...n))}catch{}}}var n=t((...e)=>console.error(...e)),i=()=>{},r=class{#e;#t;#n=/* @__PURE__ */new Set;#i="staging";constructor(e,t){this.#e=e,this.#t=t}assertOpen(){if("closed"===this.#i)throw new Error(`Plugin context for "${this.#e}" is no longer active`)}get active(){return"active"===this.#i}eligible(){return"closed"!==this.#i}own(e){return this.assertOpen(),this.#r({kind:"cleanup",acquire:void 0,finalize:void 0,cleanup:e,disposed:!1})}stage(e,t,n){this.assertOpen();const i={kind:e,acquire:t,finalize:n,cleanup:void 0,disposed:!1},r=this.#r(i);if("active"===this.#i)try{this.#o(i)}catch(e){throw this.#s(i),e}return r}counts(){const e={transform:0,renderer:0,subscription:0,cleanup:0};for(const t of this.#n)e[t.kind]+=1;return e}commit(){if("staging"!==this.#i)throw new Error(`Plugin context for "${this.#e}" cannot be committed`);this.#i="committing";try{for(const e of this.#n)this.#o(e);this.#i="active"}catch(e){throw this.close(),e}}close(){if("closed"!==this.#i){this.#i="closed";for(const e of[...this.#n].reverse())this.#s(e);this.#n.clear()}}#r(e){return this.#n.add(e),()=>{this.#s(e)}}#o(e){if(e.disposed||void 0!==e.cleanup||void 0===e.acquire)return;const t=e.acquire();e.cleanup=t??i}#s(t){if(t.disposed)return;t.disposed=!0,this.#n.delete(t);const n=t.cleanup;if(t.cleanup=void 0,void 0!==n)try{e(n())&&this.#t(`plugin "${this.#e}" cleanup returned a Promise/thenable; cleanups must be synchronous`)}catch(e){this.#t(`plugin "${this.#e}" cleanup failed:`,e)}try{t.finalize?.()}catch(e){this.#t(`plugin "${this.#e}" cleanup failed:`,e)}}},o=class{#a;#l;#u=/* @__PURE__ */new Set;constructor(e,t){this.#a=e,this.#l=t}on(e,t){return this.#c("on",e,t)}once(e,t){return this.#c("once",e,t)}off(e,t){const n=t;for(const t of[...this.#u])t.event===e&&t.handler===n&&t.dispose()}emit(e,t){return this.#l.assertOpen(),this.#a.emit(e,t)}emitWhile(e,t,n){return this.#l.assertOpen(),this.#a.emitWhile(e,t,()=>{if(!this.#l.eligible())return!1;const e=n();return!!this.#l.eligible()&&e})}listenerCount(e){let t=0;for(const n of this.#u)n.event===e&&(t+=1);return t}removeAllListeners(e){for(const t of[...this.#u])void 0!==e&&t.event!==e||t.dispose()}eventNames(){const e=/* @__PURE__ */new Set;for(const t of this.#u)e.add(t.event);return[...e]}#c(e,t,n){this.#l.assertOpen();const r=n,o=[...this.#u].find(n=>n.kind===e&&n.event===t&&n.handler===r);if(void 0!==o)return o.dispose;let s=i,a=!0;const l=async t=>{this.#l.active&&a&&("once"===e&&s(),await n(t))},u={kind:e,event:t,handler:r,dispose:i};return s=this.#l.stage("subscription",()=>this.#a[e](t,l),()=>{a=!1,this.#u.delete(u)}),u.dispose=s,this.#u.add(u),s}},s="payload-live-preview-highlight",a=/* @__PURE__ */new WeakMap,l=/* @__PURE__ */new WeakMap,u={name:"highlight",version:"1.0.0",init:e=>{if("undefined"==typeof document||"undefined"==typeof window)return;const t="function"==typeof window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,n=function(e,t){let n=a.get(e);void 0===n||n.connected()||(a.delete(e),n=void 0),void 0===n&&(n=function(e,t){const n=e.getElementById(s);if(n instanceof HTMLStyleElement)return{pluginOwned:!1,connected:()=>n.isConnected,remove:()=>{},owners:0};const i=function(e,t){try{if(!Array.isArray(e.adoptedStyleSheets)||"function"!=typeof CSSStyleSheet)return;const n=new CSSStyleSheet;if("function"!=typeof n.replaceSync)return;return n.replaceSync(t),e.adoptedStyleSheets=[...e.adoptedStyleSheets,n],n}catch{return}}(e,t);if(void 0!==i)return{pluginOwned:!0,connected:()=>e.adoptedStyleSheets.includes(i),remove:()=>{e.adoptedStyleSheets=e.adoptedStyleSheets.filter(e=>e!==i)},owners:0};const r=e.createElement("style");return r.id=s,r.textContent=t,e.head.appendChild(r),{pluginOwned:!0,connected:()=>r.isConnected,remove:()=>{r.remove()},owners:0}}(e,t?".lp-highlight{outline:2px solid rgba(0,102,204,0.85);outline-offset:2px;}":"@keyframes lp-highlight{0%{outline:2px solid rgba(0,102,204,0.85);outline-offset:2px}100%{outline:2px solid transparent;outline-offset:2px}}.lp-highlight{animation:lp-highlight 0.6s ease-out;}"),a.set(e,n));const i=n;i.owners+=1;let r=!0;return()=>{r&&(r=!1,i.owners-=1,i.owners>0||(a.get(e)===i&&a.delete(e),i.pluginOwned&&i.remove()))}}(document,t),i=t?1e3:600,r=/* @__PURE__ */new WeakMap,o=/* @__PURE__ */new Set;e.registerCleanup?.(()=>{for(const e of[...o])e();n()}),e.events.on("elementUpdate",e=>{const t=e.element;r.get(t)?.();const n=function(e){let t=l.get(e);void 0===t&&(t={owners:0,pluginAdded:!e.classList.contains("lp-highlight")},l.set(e,t));const n=t;n.owners+=1,e.classList.add("lp-highlight");let i=!0;return()=>{i&&(i=!1,n.owners-=1,n.owners>0||(l.delete(e),n.pluginAdded&&e.classList.remove("lp-highlight")))}}(t);let s=!1;const a=()=>{s||(s=!0,window.clearTimeout(u),r.get(t)===a&&r.delete(t),o.delete(a),n())},u=window.setTimeout(a,i);o.add(a),r.set(t,a)})}},c={name:"debug",version:"1.0.0",init:e=>{e.events.on("init",()=>{e.log("init")}),e.events.on("connect",t=>{e.log("connect ←",t.origin)}),e.events.on("disconnect",t=>{e.log("disconnect (",t.reason,")")}),e.events.on("cacheRefresh",t=>{e.log("cacheRefresh",t.elementCount,"elements,",t.fieldCount,"fields")}),e.events.on("beforeUpdate",t=>{e.log("beforeUpdate",Object.keys(t.data.fields).length,"fields")}),e.events.on("afterUpdate",t=>{e.log("afterUpdate",t.updatedCount,"in",t.durationMs.toFixed(2),"ms")}),e.events.on("error",t=>{e.log("error in",t.context,":",t.error.message)})}},d="payload-live-preview:scroll";function h(){"undefined"!=typeof window&&(function(){if("undefined"!=typeof window)try{sessionStorage.setItem(d,JSON.stringify({href:window.location.href,x:window.scrollX,y:window.scrollY}))}catch{}}(),window.location.reload())}var f="data-payload-field",p="data-payload-guessed",g=/* @__PURE__ */new Set(["id","_id","createdAt","updatedAt","createdBy","updatedBy","_status","globalType","collection","locale","localized"]),m="payload-live-preview-unbound",v={"bottom-right":"bottom:12px;right:12px;","bottom-left":"bottom:12px;left:12px;","top-right":"top:12px;right:12px;","top-left":"top:12px;left:12px;"};function y(e,t,n){const i=function(e,t){const n=new Set(e),i=e=>{if(n.has(e))return!0;const t=`${e}.`;for(const e of n)if(e.startsWith(t))return!0;return!1};return e=>{if(i(e))return!0;const n=function(e,t){if(void 0===t||0===t.length)return e;const n=`_${t}`;return e.endsWith(n)?e.slice(0,-n.length):e}(e,t);return n!==e&&i(n)}}(t,n);return Object.keys(e).filter(e=>!g.has(e)&&!i(e)).sort((e,t)=>e.localeCompare(t))}function w(e,t){const n=e.createElement("textarea");n.value=t,n.setAttribute("readonly",""),n.setAttribute("style","position:fixed;opacity:0;pointer-events:none;"),e.body.append(n),n.select(),n.remove()}function b(e,t,n){const i=e.createElement("button");return i.type="button",i.textContent=n,i.setAttribute("style","display:block;width:100%;text-align:left;margin:2px 0;padding:2px 4px;border:0;border-radius:3px;background:#222;color:#7fd1ff;font:inherit;cursor:pointer;"),i.title=`Copy ${f}="${t}"`,i.addEventListener("click",()=>{!function(e,t){const n=e.defaultView?.navigator.clipboard;null==n?w(e,t):n.writeText(t).catch(()=>{w(e,t)})}(e,`${f}="${t}"`),i.textContent=`${n} ✓`}),i}var P=Object.freeze({NoTrustedOrigin:"LP0101",ReferrerOnlyTrust:"LP0102",PluginIncompatible:"LP0103",ProfileFeatureOmitted:"LP0104",OrphanField:"LP0201",UnattributableUpdate:"LP0202",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",V2ReadinessGap:"LP0709",RuntimeOnPublicPage:"LP0710"});exports.DIAGNOSTIC_CODES=P,exports.EventEmitter=class{#d=/* @__PURE__ */new Map;#h=/* @__PURE__ */new Map;on(e,t){return this.#f(this.#d,e,t)}once(e,t){return this.#f(this.#h,e,t)}off(e,t){this.#p(this.#d,e,t),this.#p(this.#h,e,t)}async emit(e,t){await this.#g(e,t)}async emitWhile(e,t,n){return this.#g(e,t,n)}async#g(e,t,n){const i=()=>n?.()??!0;if(!i())return!1;const r=this.#d.get(e);if(r)for(const n of[...r]){if(!i())return!1;if(await this.#m(n,t,e),!i())return!1}if(!i())return!1;const o=this.#h.get(e);if(o&&o.size>0){const n=[...o];this.#h.delete(e);for(const r of n){if(!i())return!1;if(await this.#m(r,t,e),!i())return!1}}return i()}listenerCount(e){return(this.#d.get(e)?.size??0)+(this.#h.get(e)?.size??0)}removeAllListeners(e){if(void 0===e)return this.#d.clear(),void this.#h.clear();this.#d.delete(e),this.#h.delete(e)}eventNames(){const e=/* @__PURE__ */new Set;for(const t of this.#d.keys())e.add(t);for(const t of this.#h.keys())e.add(t);return[...e]}#f(e,t,n){let i=e.get(t);return i||(i=/* @__PURE__ */new Set,e.set(t,i)),i.add(n),()=>{this.#p(e,t,n)}}#p(e,t,n){const i=e.get(t);void 0!==i&&(i.delete(n),0===i.size&&e.delete(t))}async#m(e,t,i){try{await e(t)}catch(e){const t="string"==typeof i||"number"==typeof i?String(i):"<event>";n(`[live-preview] LP0601: handler for "${t}" threw:`,e)}}},exports.PluginManager=class{#a;#v;#y;#w;#t;#b=/* @__PURE__ */new Map;#P=/* @__PURE__ */new Map;#S=/* @__PURE__ */new Map;#x=/* @__PURE__ */new Set;#L=/* @__PURE__ */new Map;#k=Promise.resolve();#A=0;constructor(e){this.#a=e.events,this.#v=e.config,this.#y=e.registerFieldRenderer,this.#t=t(e.log);const n=e.onTransformError;this.#w=void 0===n?void 0:t((...e)=>{const t=e[0];try{return n(t)}catch(e){return void this.#t("transform error reporter failed:",e)}})}register(e){return this.#A>0?this.#N(e,!1):this.#C(()=>this.#N(e,!0))}unregister(e){return this.#A>0?this.#$(e,!1):this.#C(async()=>{await this.#$(e,!0)})}destroyAll(){return this.#A>0?this.#T(!1):this.#C(async()=>{await this.#T(!0)})}applyTransforms(t,n,i,r){const o=this.#L.get(t);if(void 0===o||0===o.length)return n;let s=n;for(const a of[...o]){if(!a.active)continue;const{transform:o}=a;if(!1===r?.())return n;try{s=o(s,{fieldName:t,element:i.element,allFields:i.allFields});const a=e(s);if(!1===r?.())return n;if(a)throw new TypeError(`Transform for "${t}" returned a Promise/thenable; transforms must be synchronous`)}catch(e){if(!1===r?.())return n;const i=e instanceof Error?e:new Error(String(e));return this.#t(`transform for "${t}" failed:`,i),this.#w?.(i),n}}return s}list(){return[...this.#b.keys()]}snapshot(){const e=[],t=(e,t,n,i)=>{const r=i.counts();return{name:e,version:t,state:n,registrations:{transforms:r.transform,renderers:r.renderer,subscriptions:r.subscription,cleanups:r.cleanup}}};for(const[n,i]of this.#P)e.push(t(n,void 0,"initializing",i.scope));for(const[n,i]of this.#b)e.push(t(n,i.plugin.version,"active",i.scope));for(const t of this.#S.keys())e.push({name:t,version:void 0,state:"tearing-down",registrations:{transforms:0,renderers:0,subscriptions:0,cleanups:0}});return e}get size(){return this.#b.size}async#N(e,t){if(this.#b.has(e.name)||this.#P.has(e.name)||this.#S.has(e.name))return void this.#t(`plugin "${e.name}" already registered`);const n=function(e,t){if(void 0!==e){if(void 0!==e.runtime&&!function(e,t){const n=function(e){const t=/^v?(\d+)\.(\d+)\.(\d+)/.exec(e.trim());if(null!==t)return[Number(t[1]),Number(t[2]),Number(t[3])]}(e);return void 0!==n&&t.split("||").some(e=>{const i=e.trim().split(/\s+/).filter(e=>e.length>0);return 0===i.length?""===e.trim()&&""===t.trim():i.every(e=>function(e,t){const n=t.trim();if(""===n||"*"===n)return!0;const i=/^(\^|~|>=|<=|>|<|=)?\s*v?(\d+)\.(\d+)\.(\d+)/.exec(n);if(null===i)return!1;const r=i[1]??"=",o=[Number(i[2]),Number(i[3]),Number(i[4])],s=function(e,t){for(let n=0;n<3;n+=1){const i=(e[n]??0)-(t[n]??0);if(0!==i)return i}return 0}(e,o);switch(r){case"=":return 0===s;case">":return s>0;case">=":return s>=0;case"<":return s<0;case"<=":return s<=0;case"~":return s>=0&&e[0]===o[0]&&e[1]===o[1];case"^":return!(s<0)&&(o[0]>0?e[0]===o[0]:o[1]>0?0===e[0]&&e[1]===o[1]:0===e[0]&&0===e[1]&&e[2]===o[2]);default:return!1}}(n,e))})}(t,e.runtime))return`declares runtime ${e.runtime}, this runtime is ${t}`;if(void 0!==e.protocol){if(!Number.isInteger(e.protocol)||e.protocol<1)return`declares an invalid protocol version ${String(e.protocol)}`;if(e.protocol<4)return`declares protocol ${String(e.protocol)}, this runtime speaks ${String(4)}`}}}(e.compat,"2.0.0");if(void 0!==n)return void this.#O(e.name,n);const i=new r(e.name,this.#t),o=this.#E(e.name,i),s={scope:i,cancelled:!1};this.#P.set(e.name,s);try{if(await this.#U(()=>e.init(o),t),s.cancelled)return;i.commit()}catch(t){return i.close(),void(s.cancelled||this.#t(`plugin "${e.name}" init failed:`,t))}finally{this.#P.get(e.name)===s&&this.#P.delete(e.name)}this.#b.set(e.name,{plugin:e,scope:i}),this.#t(`plugin "${e.name}" registered`)}#O(e,t){const n=`plugin "${e}" refused: ${t}`;this.#t(n),this.#a.emit("error",{error:new Error(n),context:"plugin",code:"LP0103"})}#E(e,t){return{events:new o(this.#a,t),registerFieldRenderer:e=>{t.stage("renderer",()=>{const t=this.#y(e);return"function"==typeof t?t:void 0})},registerTransform:(e,n)=>{const i={transform:n,active:!1};t.stage("transform",()=>{i.active=!0;const t=this.#L.get(e);return void 0===t?this.#L.set(e,[i]):t.push(i),()=>{i.active=!1;const t=this.#L.get(e);if(void 0===t)return;const n=t.indexOf(i);n>=0&&t.splice(n,1),0===t.length&&this.#L.delete(e)}})},registerCleanup:e=>{t.own(e)},getConfig:()=>this.#v,log:(...t)=>{this.#t(`[${e}]`,...t)}}}#$(e,t){const n=this.#P.get(e);if(void 0!==n)return n.cancelled=!0,n.scope.close(),Promise.resolve();const i=this.#S.get(e);if(void 0!==i)return this.#x.has(e)?Promise.resolve():t?this.#z(i):i;const r=this.#b.get(e);if(void 0===r)return Promise.resolve();this.#b.delete(e),r.scope.close();const o=Promise.resolve().then(()=>this.#F(e,r.plugin,t));return this.#S.set(e,o),o.then(()=>{this.#S.get(e)===o&&this.#S.delete(e)}),o}async#F(e,t,n){if(void 0!==t.destroy){this.#x.add(e);try{await this.#U(()=>t.destroy?.(),n)}catch(t){this.#t(`plugin "${e}" destroy failed:`,t)}finally{this.#x.delete(e)}}}async#T(e){for(const e of this.#P.values())e.cancelled=!0,e.scope.close();const t=[...this.#b.keys()];for(const n of t)await this.#$(n,e)}async#U(e,t){t?await this.#z(Promise.resolve().then(e)):await e()}async#z(e){this.#A+=1;try{await e}finally{this.#A-=1}}#C(e){const t=this.#k.then(e);return this.#k=t.catch(e=>{this.#t("plugin manager mutation failed:",e)}),t}},exports.createAnalyticsPlugin=function(){let e=0,t=0,n=0;return{name:"analytics",version:"1.0.0",init:i=>{i.events.on("afterUpdate",i=>{e+=1,t+=i.updatedCount,n+=i.durationMs})},getStats:()=>({updateCount:e,totalElements:t,totalDurationMs:n,averageDurationMs:0===e?0:n/e})}},exports.createUnboundFieldsOverlayPlugin=function(e={}){return{name:"unbound-fields",version:"1.0.0",init:t=>{const n=e.root??("undefined"==typeof document?void 0:document);if(void 0===n)return;if((e.onlyWithDebug??1)&&!0!==t.getConfig().debug)return void t.log("not mounted: the client runs without `debug: true`");const i=function(e,t){const n=function(e){return 9===e.nodeType?e:e.ownerDocument}(e);if(null==n?.body)return null;const i=n.createElement("aside");i.id=m,i.setAttribute("style","position:fixed;z-index:2147483646;max-width:280px;max-height:40vh;overflow:auto;font:12px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace;background:#111;color:#eee;border:1px solid #333;border-radius:6px;padding:8px 10px;box-shadow:0 4px 16px rgba(0,0,0,0.4);"+t),i.setAttribute("aria-hidden","true"),i.hidden=!0;const r=e=>{const t=n.createElement("div");return t.textContent=e,t.setAttribute("style","font-weight:600;margin-bottom:4px;"),t},o=r("Unbound fields"),s=n.createElement("div"),a=r("Guessed bindings");a.setAttribute("data-testid","guessed-bindings");const l=n.createElement("div");return i.append(o,s,a,l),n.body.append(i),{update:(e,t)=>{i.isConnected||(n.getElementById(m)?.remove(),n.body.append(i)),i.hidden=0===e.length&&0===t.length,o.hidden=0===e.length,s.replaceChildren(...e.map(e=>b(n,e,e))),a.hidden=0===t.length,l.replaceChildren(...t.map(({field:e,matched:t})=>b(n,e,`${e} ← ${JSON.stringify(t)}`)))},destroy:()=>{i.remove()}}}(n,v[e.position??"bottom-right"]);null!==i&&(t.registerCleanup?.(i.destroy),t.events.on("afterUpdate",e=>{const r=y(e.data.fields,function(e){const t=[];for(const n of e.querySelectorAll(`[${f}]`)){const e=n.getAttribute(f);null!==e&&e.length>0&&t.push(e)}return t}(n),e.data.locale),o=function(e){const t=[];for(const n of e.querySelectorAll(`[${p}]`)){const e=n.getAttribute(f);null!==e&&0!==e.length&&t.push({field:e,matched:n.getAttribute(p)??""})}return t}(n);i.update(r,o),r.length>0&&t.log("unbound:",r.join(", ")),o.length>0&&t.log("guessed:",o.map(e=>e.field).join(", "))}))}}},exports.debugPlugin=c,exports.documentSavePlugin=function(e={}){const t=e.strategy??"silent";return{name:"document-save",version:"1.1.0",init:n=>{let i=!0;const r=/* @__PURE__ */new Set;n.registerCleanup?.(()=>{i=!1;for(const e of r)e.abort();r.clear()}),function(){if("undefined"!=typeof window)try{const e=sessionStorage.getItem(d);if(null===e)return;sessionStorage.removeItem(d);const t=JSON.parse(e);if(t.href!==window.location.href)return;window.scrollTo(t.x??0,t.y??0)}catch{}}(),n.events.on("documentSave",()=>{if(!i)return;if("silent"===t)return;if("reload"===t)return void h();const o=new AbortController;r.add(o);const s="fetch"===t?async function(e,t,n){if(e.handler)try{await e.handler(n)}catch(e){if(!i||n.aborted)return;t("document-save handler threw:",e)}else t("document-save: fetch strategy selected but no handler supplied")}(e,n.log,o.signal):async function(e,t,n,i){if("undefined"==typeof fetch)return void t("document-save: revalidate strategy needs fetch — not available");const r=e.revalidateUrl??"/api/revalidate";let o=!1;try{const s=await fetch(r,{method:"POST",signal:n,headers:{"Content-Type":"application/json",...e.revalidateHeaders??{}},body:JSON.stringify({source:"payload-live-preview"})});if(!i()||n.aborted)return;o=s.ok,o||t("document-save revalidate non-2xx:",s.status)}catch(e){if(!i()||n.aborted)return;t("document-save revalidate failed:",e)}o||"reload"!==e.onRevalidateFailure||h()}(e,n.log,o.signal,()=>i);s.finally(()=>{r.delete(o)})})}}},exports.highlightPlugin=u,exports.unboundFieldNames=y;
1
+ "use strict";function e(e){return("object"==typeof e&&null!==e||"function"==typeof e)&&"function"==typeof e.then&&(Promise.resolve(e).catch(()=>{}),!0)}function t(t){return(...n)=>{try{e(t(...n))}catch{}}}var n=t((...e)=>console.error(...e)),i=()=>{},r=class{#e;#t;#n=/* @__PURE__ */new Set;#i="staging";constructor(e,t){this.#e=e,this.#t=t}assertOpen(){if("closed"===this.#i)throw new Error(`Plugin context for "${this.#e}" is no longer active`)}get active(){return"active"===this.#i}eligible(){return"closed"!==this.#i}own(e){return this.assertOpen(),this.#r({kind:"cleanup",acquire:void 0,finalize:void 0,cleanup:e,disposed:!1})}stage(e,t,n){this.assertOpen();const i={kind:e,acquire:t,finalize:n,cleanup:void 0,disposed:!1},r=this.#r(i);if("active"===this.#i)try{this.#o(i)}catch(e){throw this.#s(i),e}return r}counts(){const e={transform:0,renderer:0,subscription:0,cleanup:0};for(const t of this.#n)e[t.kind]+=1;return e}commit(){if("staging"!==this.#i)throw new Error(`Plugin context for "${this.#e}" cannot be committed`);this.#i="committing";try{for(const e of this.#n)this.#o(e);this.#i="active"}catch(e){throw this.close(),e}}close(){if("closed"!==this.#i){this.#i="closed";for(const e of[...this.#n].reverse())this.#s(e);this.#n.clear()}}#r(e){return this.#n.add(e),()=>{this.#s(e)}}#o(e){if(e.disposed||void 0!==e.cleanup||void 0===e.acquire)return;const t=e.acquire();e.cleanup=t??i}#s(t){if(t.disposed)return;t.disposed=!0,this.#n.delete(t);const n=t.cleanup;if(t.cleanup=void 0,void 0!==n)try{e(n())&&this.#t(`plugin "${this.#e}" cleanup returned a Promise/thenable; cleanups must be synchronous`)}catch(e){this.#t(`plugin "${this.#e}" cleanup failed:`,e)}try{t.finalize?.()}catch(e){this.#t(`plugin "${this.#e}" cleanup failed:`,e)}}},o=class{#a;#l;#u=/* @__PURE__ */new Set;constructor(e,t){this.#a=e,this.#l=t}on(e,t){return this.#c("on",e,t)}once(e,t){return this.#c("once",e,t)}off(e,t){const n=t;for(const t of[...this.#u])t.event===e&&t.handler===n&&t.dispose()}emit(e,t){return this.#l.assertOpen(),this.#a.emit(e,t)}emitWhile(e,t,n){return this.#l.assertOpen(),this.#a.emitWhile(e,t,()=>{if(!this.#l.eligible())return!1;const e=n();return!!this.#l.eligible()&&e})}listenerCount(e){let t=0;for(const n of this.#u)n.event===e&&(t+=1);return t}removeAllListeners(e){for(const t of[...this.#u])void 0!==e&&t.event!==e||t.dispose()}eventNames(){const e=/* @__PURE__ */new Set;for(const t of this.#u)e.add(t.event);return[...e]}#c(e,t,n){this.#l.assertOpen();const r=n,o=[...this.#u].find(n=>n.kind===e&&n.event===t&&n.handler===r);if(void 0!==o)return o.dispose;let s=i,a=!0;const l=async t=>{this.#l.active&&a&&("once"===e&&s(),await n(t))},u={kind:e,event:t,handler:r,dispose:i};return s=this.#l.stage("subscription",()=>this.#a[e](t,l),()=>{a=!1,this.#u.delete(u)}),u.dispose=s,this.#u.add(u),s}},s="payload-live-preview-highlight",a=/* @__PURE__ */new WeakMap,l=/* @__PURE__ */new WeakMap,u={name:"highlight",version:"1.0.0",init:e=>{if("undefined"==typeof document||"undefined"==typeof window)return;const t="function"==typeof window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,n=function(e,t){let n=a.get(e);void 0===n||n.connected()||(a.delete(e),n=void 0),void 0===n&&(n=function(e,t){const n=e.getElementById(s);if(n instanceof HTMLStyleElement)return{pluginOwned:!1,connected:()=>n.isConnected,remove:()=>{},owners:0};const i=function(e,t){try{if(!Array.isArray(e.adoptedStyleSheets)||"function"!=typeof CSSStyleSheet)return;const n=new CSSStyleSheet;if("function"!=typeof n.replaceSync)return;return n.replaceSync(t),e.adoptedStyleSheets=[...e.adoptedStyleSheets,n],n}catch{return}}(e,t);if(void 0!==i)return{pluginOwned:!0,connected:()=>e.adoptedStyleSheets.includes(i),remove:()=>{e.adoptedStyleSheets=e.adoptedStyleSheets.filter(e=>e!==i)},owners:0};const r=e.createElement("style");return r.id=s,r.textContent=t,e.head.appendChild(r),{pluginOwned:!0,connected:()=>r.isConnected,remove:()=>{r.remove()},owners:0}}(e,t?".lp-highlight{outline:2px solid rgba(0,102,204,0.85);outline-offset:2px;}":"@keyframes lp-highlight{0%{outline:2px solid rgba(0,102,204,0.85);outline-offset:2px}100%{outline:2px solid transparent;outline-offset:2px}}.lp-highlight{animation:lp-highlight 0.6s ease-out;}"),a.set(e,n));const i=n;i.owners+=1;let r=!0;return()=>{r&&(r=!1,i.owners-=1,i.owners>0||(a.get(e)===i&&a.delete(e),i.pluginOwned&&i.remove()))}}(document,t),i=t?1e3:600,r=/* @__PURE__ */new WeakMap,o=/* @__PURE__ */new Set;e.registerCleanup?.(()=>{for(const e of[...o])e();n()}),e.events.on("elementUpdate",e=>{const t=e.element;r.get(t)?.();const n=function(e){let t=l.get(e);void 0===t&&(t={owners:0,pluginAdded:!e.classList.contains("lp-highlight")},l.set(e,t));const n=t;n.owners+=1,e.classList.add("lp-highlight");let i=!0;return()=>{i&&(i=!1,n.owners-=1,n.owners>0||(l.delete(e),n.pluginAdded&&e.classList.remove("lp-highlight")))}}(t);let s=!1;const a=()=>{s||(s=!0,window.clearTimeout(u),r.get(t)===a&&r.delete(t),o.delete(a),n())},u=window.setTimeout(a,i);o.add(a),r.set(t,a)})}},c={name:"debug",version:"1.0.0",init:e=>{e.events.on("init",()=>{e.log("init")}),e.events.on("connect",t=>{e.log("connect ←",t.origin)}),e.events.on("disconnect",t=>{e.log("disconnect (",t.reason,")")}),e.events.on("cacheRefresh",t=>{e.log("cacheRefresh",t.elementCount,"elements,",t.fieldCount,"fields")}),e.events.on("beforeUpdate",t=>{e.log("beforeUpdate",Object.keys(t.data.fields).length,"fields")}),e.events.on("afterUpdate",t=>{e.log("afterUpdate",t.updatedCount,"in",t.durationMs.toFixed(2),"ms")}),e.events.on("error",t=>{e.log("error in",t.context,":",t.error.message)})}},d="payload-live-preview:scroll";function h(){"undefined"!=typeof window&&(function(){if("undefined"!=typeof window)try{sessionStorage.setItem(d,JSON.stringify({href:window.location.href,x:window.scrollX,y:window.scrollY}))}catch{}}(),window.location.reload())}var f="data-payload-field",p="data-payload-guessed",g=/* @__PURE__ */new Set(["id","_id","createdAt","updatedAt","createdBy","updatedBy","_status","globalType","collection","locale","localized"]),m="payload-live-preview-unbound",v={"bottom-right":"bottom:12px;right:12px;","bottom-left":"bottom:12px;left:12px;","top-right":"top:12px;right:12px;","top-left":"top:12px;left:12px;"};function y(e,t,n){const i=function(e,t){const n=new Set(e),i=e=>{if(n.has(e))return!0;const t=`${e}.`;for(const e of n)if(e.startsWith(t))return!0;return!1};return e=>{if(i(e))return!0;const n=function(e,t){if(void 0===t||0===t.length)return e;const n=`_${t}`;return e.endsWith(n)?e.slice(0,-n.length):e}(e,t);return n!==e&&i(n)}}(t,n);return Object.keys(e).filter(e=>!g.has(e)&&!i(e)).sort((e,t)=>e.localeCompare(t))}function w(e,t){const n=e.createElement("textarea");n.value=t,n.setAttribute("readonly",""),n.setAttribute("style","position:fixed;opacity:0;pointer-events:none;"),e.body.append(n),n.select(),n.remove()}function b(e,t,n){const i=e.createElement("button");return i.type="button",i.textContent=n,i.setAttribute("style","display:block;width:100%;text-align:left;margin:2px 0;padding:2px 4px;border:0;border-radius:3px;background:#222;color:#7fd1ff;font:inherit;cursor:pointer;"),i.title=`Copy ${f}="${t}"`,i.addEventListener("click",()=>{!function(e,t){const n=e.defaultView?.navigator.clipboard;null==n?w(e,t):n.writeText(t).catch(()=>{w(e,t)})}(e,`${f}="${t}"`),i.textContent=`${n} ✓`}),i}var P=Object.freeze({NoTrustedOrigin:"LP0101",ReferrerOnlyTrust:"LP0102",PluginIncompatible:"LP0103",ProfileFeatureOmitted:"LP0104",OrphanField:"LP0201",UnattributableUpdate:"LP0202",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",V2ReadinessGap:"LP0709",RuntimeOnPublicPage:"LP0710"});exports.DIAGNOSTIC_CODES=P,exports.EventEmitter=class{#d=/* @__PURE__ */new Map;#h=/* @__PURE__ */new Map;on(e,t){return this.#f(this.#d,e,t)}once(e,t){return this.#f(this.#h,e,t)}off(e,t){this.#p(this.#d,e,t),this.#p(this.#h,e,t)}async emit(e,t){await this.#g(e,t)}async emitWhile(e,t,n){return this.#g(e,t,n)}async#g(e,t,n){const i=()=>n?.()??!0;if(!i())return!1;const r=this.#d.get(e);if(r)for(const n of[...r]){if(!i())return!1;if(await this.#m(n,t,e),!i())return!1}if(!i())return!1;const o=this.#h.get(e);if(o&&o.size>0){const n=[...o];this.#h.delete(e);for(const r of n){if(!i())return!1;if(await this.#m(r,t,e),!i())return!1}}return i()}listenerCount(e){return(this.#d.get(e)?.size??0)+(this.#h.get(e)?.size??0)}removeAllListeners(e){if(void 0===e)return this.#d.clear(),void this.#h.clear();this.#d.delete(e),this.#h.delete(e)}eventNames(){const e=/* @__PURE__ */new Set;for(const t of this.#d.keys())e.add(t);for(const t of this.#h.keys())e.add(t);return[...e]}#f(e,t,n){let i=e.get(t);return i||(i=/* @__PURE__ */new Set,e.set(t,i)),i.add(n),()=>{this.#p(e,t,n)}}#p(e,t,n){const i=e.get(t);void 0!==i&&(i.delete(n),0===i.size&&e.delete(t))}async#m(e,t,i){try{await e(t)}catch(e){const t="string"==typeof i||"number"==typeof i?String(i):"<event>";n(`[live-preview] LP0601: handler for "${t}" threw:`,e)}}},exports.PluginManager=class{#a;#v;#y;#w;#t;#b=/* @__PURE__ */new Map;#P=/* @__PURE__ */new Map;#S=/* @__PURE__ */new Map;#x=/* @__PURE__ */new Set;#L=/* @__PURE__ */new Map;#k=Promise.resolve();#A=0;constructor(e){this.#a=e.events,this.#v=e.config,this.#y=e.registerFieldRenderer,this.#t=t(e.log);const n=e.onTransformError;this.#w=void 0===n?void 0:t((...e)=>{const t=e[0];try{return n(t)}catch(e){return void this.#t("transform error reporter failed:",e)}})}register(e){return this.#A>0?this.#N(e,!1):this.#C(()=>this.#N(e,!0))}unregister(e){return this.#A>0?this.#$(e,!1):this.#C(async()=>{await this.#$(e,!0)})}destroyAll(){return this.#A>0?this.#T(!1):this.#C(async()=>{await this.#T(!0)})}applyTransforms(t,n,i,r){const o=this.#L.get(t);if(void 0===o||0===o.length)return n;let s=n;for(const a of[...o]){if(!a.active)continue;const{transform:o}=a;if(!1===r?.())return n;try{s=o(s,{fieldName:t,element:i.element,allFields:i.allFields});const a=e(s);if(!1===r?.())return n;if(a)throw new TypeError(`Transform for "${t}" returned a Promise/thenable; transforms must be synchronous`)}catch(e){if(!1===r?.())return n;const i=e instanceof Error?e:new Error(String(e));return this.#t(`transform for "${t}" failed:`,i),this.#w?.(i),n}}return s}list(){return[...this.#b.keys()]}snapshot(){const e=[],t=(e,t,n,i)=>{const r=i.counts();return{name:e,version:t,state:n,registrations:{transforms:r.transform,renderers:r.renderer,subscriptions:r.subscription,cleanups:r.cleanup}}};for(const[n,i]of this.#P)e.push(t(n,void 0,"initializing",i.scope));for(const[n,i]of this.#b)e.push(t(n,i.plugin.version,"active",i.scope));for(const t of this.#S.keys())e.push({name:t,version:void 0,state:"tearing-down",registrations:{transforms:0,renderers:0,subscriptions:0,cleanups:0}});return e}get size(){return this.#b.size}async#N(e,t){if(this.#b.has(e.name)||this.#P.has(e.name)||this.#S.has(e.name))return void this.#t(`plugin "${e.name}" already registered`);const n=function(e,t){if(void 0!==e){if(void 0!==e.runtime&&!function(e,t){const n=function(e){const t=/^v?(\d+)\.(\d+)\.(\d+)/.exec(e.trim());if(null!==t)return[Number(t[1]),Number(t[2]),Number(t[3])]}(e);return void 0!==n&&t.split("||").some(e=>{const i=e.trim().split(/\s+/).filter(e=>e.length>0);return 0===i.length?""===e.trim()&&""===t.trim():i.every(e=>function(e,t){const n=t.trim();if(""===n||"*"===n)return!0;const i=/^(\^|~|>=|<=|>|<|=)?\s*v?(\d+)\.(\d+)\.(\d+)/.exec(n);if(null===i)return!1;const r=i[1]??"=",o=[Number(i[2]),Number(i[3]),Number(i[4])],s=function(e,t){for(let n=0;n<3;n+=1){const i=(e[n]??0)-(t[n]??0);if(0!==i)return i}return 0}(e,o);switch(r){case"=":return 0===s;case">":return s>0;case">=":return s>=0;case"<":return s<0;case"<=":return s<=0;case"~":return s>=0&&e[0]===o[0]&&e[1]===o[1];case"^":return!(s<0)&&(o[0]>0?e[0]===o[0]:o[1]>0?0===e[0]&&e[1]===o[1]:0===e[0]&&0===e[1]&&e[2]===o[2]);default:return!1}}(n,e))})}(t,e.runtime))return`declares runtime ${e.runtime}, this runtime is ${t}`;if(void 0!==e.protocol){if(!Number.isInteger(e.protocol)||e.protocol<1)return`declares an invalid protocol version ${String(e.protocol)}`;if(e.protocol<4)return`declares protocol ${String(e.protocol)}, this runtime speaks ${String(4)}`}}}(e.compat,"2.0.2");if(void 0!==n)return void this.#O(e.name,n);const i=new r(e.name,this.#t),o=this.#E(e.name,i),s={scope:i,cancelled:!1};this.#P.set(e.name,s);try{if(await this.#U(()=>e.init(o),t),s.cancelled)return;i.commit()}catch(t){return i.close(),void(s.cancelled||this.#t(`plugin "${e.name}" init failed:`,t))}finally{this.#P.get(e.name)===s&&this.#P.delete(e.name)}this.#b.set(e.name,{plugin:e,scope:i}),this.#t(`plugin "${e.name}" registered`)}#O(e,t){const n=`plugin "${e}" refused: ${t}`;this.#t(n),this.#a.emit("error",{error:new Error(n),context:"plugin",code:"LP0103"})}#E(e,t){return{events:new o(this.#a,t),registerFieldRenderer:e=>{t.stage("renderer",()=>{const t=this.#y(e);return"function"==typeof t?t:void 0})},registerTransform:(e,n)=>{const i={transform:n,active:!1};t.stage("transform",()=>{i.active=!0;const t=this.#L.get(e);return void 0===t?this.#L.set(e,[i]):t.push(i),()=>{i.active=!1;const t=this.#L.get(e);if(void 0===t)return;const n=t.indexOf(i);n>=0&&t.splice(n,1),0===t.length&&this.#L.delete(e)}})},registerCleanup:e=>{t.own(e)},getConfig:()=>this.#v,log:(...t)=>{this.#t(`[${e}]`,...t)}}}#$(e,t){const n=this.#P.get(e);if(void 0!==n)return n.cancelled=!0,n.scope.close(),Promise.resolve();const i=this.#S.get(e);if(void 0!==i)return this.#x.has(e)?Promise.resolve():t?this.#z(i):i;const r=this.#b.get(e);if(void 0===r)return Promise.resolve();this.#b.delete(e),r.scope.close();const o=Promise.resolve().then(()=>this.#F(e,r.plugin,t));return this.#S.set(e,o),o.then(()=>{this.#S.get(e)===o&&this.#S.delete(e)}),o}async#F(e,t,n){if(void 0!==t.destroy){this.#x.add(e);try{await this.#U(()=>t.destroy?.(),n)}catch(t){this.#t(`plugin "${e}" destroy failed:`,t)}finally{this.#x.delete(e)}}}async#T(e){for(const e of this.#P.values())e.cancelled=!0,e.scope.close();const t=[...this.#b.keys()];for(const n of t)await this.#$(n,e)}async#U(e,t){t?await this.#z(Promise.resolve().then(e)):await e()}async#z(e){this.#A+=1;try{await e}finally{this.#A-=1}}#C(e){const t=this.#k.then(e);return this.#k=t.catch(e=>{this.#t("plugin manager mutation failed:",e)}),t}},exports.createAnalyticsPlugin=function(){let e=0,t=0,n=0;return{name:"analytics",version:"1.0.0",init:i=>{i.events.on("afterUpdate",i=>{e+=1,t+=i.updatedCount,n+=i.durationMs})},getStats:()=>({updateCount:e,totalElements:t,totalDurationMs:n,averageDurationMs:0===e?0:n/e})}},exports.createUnboundFieldsOverlayPlugin=function(e={}){return{name:"unbound-fields",version:"1.0.0",init:t=>{const n=e.root??("undefined"==typeof document?void 0:document);if(void 0===n)return;if((e.onlyWithDebug??1)&&!0!==t.getConfig().debug)return void t.log("not mounted: the client runs without `debug: true`");const i=function(e,t){const n=function(e){return 9===e.nodeType?e:e.ownerDocument}(e);if(null==n?.body)return null;const i=n.createElement("aside");i.id=m,i.setAttribute("style","position:fixed;z-index:2147483646;max-width:280px;max-height:40vh;overflow:auto;font:12px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace;background:#111;color:#eee;border:1px solid #333;border-radius:6px;padding:8px 10px;box-shadow:0 4px 16px rgba(0,0,0,0.4);"+t),i.setAttribute("aria-hidden","true"),i.hidden=!0;const r=e=>{const t=n.createElement("div");return t.textContent=e,t.setAttribute("style","font-weight:600;margin-bottom:4px;"),t},o=r("Unbound fields"),s=n.createElement("div"),a=r("Guessed bindings");a.setAttribute("data-testid","guessed-bindings");const l=n.createElement("div");return i.append(o,s,a,l),n.body.append(i),{update:(e,t)=>{i.isConnected||(n.getElementById(m)?.remove(),n.body.append(i)),i.hidden=0===e.length&&0===t.length,o.hidden=0===e.length,s.replaceChildren(...e.map(e=>b(n,e,e))),a.hidden=0===t.length,l.replaceChildren(...t.map(({field:e,matched:t})=>b(n,e,`${e} ← ${JSON.stringify(t)}`)))},destroy:()=>{i.remove()}}}(n,v[e.position??"bottom-right"]);null!==i&&(t.registerCleanup?.(i.destroy),t.events.on("afterUpdate",e=>{const r=y(e.data.fields,function(e){const t=[];for(const n of e.querySelectorAll(`[${f}]`)){const e=n.getAttribute(f);null!==e&&e.length>0&&t.push(e)}return t}(n),e.data.locale),o=function(e){const t=[];for(const n of e.querySelectorAll(`[${p}]`)){const e=n.getAttribute(f);null!==e&&0!==e.length&&t.push({field:e,matched:n.getAttribute(p)??""})}return t}(n);i.update(r,o),r.length>0&&t.log("unbound:",r.join(", ")),o.length>0&&t.log("guessed:",o.map(e=>e.field).join(", "))}))}}},exports.debugPlugin=c,exports.documentSavePlugin=function(e={}){const t=e.strategy??"silent";return{name:"document-save",version:"1.1.0",init:n=>{let i=!0;const r=/* @__PURE__ */new Set;n.registerCleanup?.(()=>{i=!1;for(const e of r)e.abort();r.clear()}),function(){if("undefined"!=typeof window)try{const e=sessionStorage.getItem(d);if(null===e)return;sessionStorage.removeItem(d);const t=JSON.parse(e);if(t.href!==window.location.href)return;window.scrollTo(t.x??0,t.y??0)}catch{}}(),n.events.on("documentSave",()=>{if(!i)return;if("silent"===t)return;if("reload"===t)return void h();const o=new AbortController;r.add(o);const s="fetch"===t?async function(e,t,n){if(e.handler)try{await e.handler(n)}catch(e){if(!i||n.aborted)return;t("document-save handler threw:",e)}else t("document-save: fetch strategy selected but no handler supplied")}(e,n.log,o.signal):async function(e,t,n,i){if("undefined"==typeof fetch)return void t("document-save: revalidate strategy needs fetch — not available");const r=e.revalidateUrl??"/api/revalidate";let o=!1;try{const s=await fetch(r,{method:"POST",signal:n,headers:{"Content-Type":"application/json",...e.revalidateHeaders??{}},body:JSON.stringify({source:"payload-live-preview"})});if(!i()||n.aborted)return;o=s.ok,o||t("document-save revalidate non-2xx:",s.status)}catch(e){if(!i()||n.aborted)return;t("document-save revalidate failed:",e)}o||"reload"!==e.onRevalidateFailure||h()}(e,n.log,o.signal,()=>i);s.finally(()=>{r.delete(o)})})}}},exports.highlightPlugin=u,exports.unboundFieldNames=y;
2
2
  //# sourceMappingURL=plugins.cjs.map