@tiptap/cli 3.20.0 → 3.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,58 +1,88 @@
1
1
  #!/usr/bin/env node
2
- import ws from"path";import{Command as xs}from"commander";import{z as Y}from"zod";import{createPrompt as Ar,useState as gt,useKeypress as Rr,usePrefix as $r,usePagination as Nr,useRef as tn,useMemo as ht,useEffect as jr,isBackspaceKey as _r,isEnterKey as Or,isUpKey as yt,isDownKey as nn,isNumberKey as Dr,Separator as Ae,ValidationError as Lr,makeTheme as Fr}from"@inquirer/core";import rn from"yoctocolors-cjs";import Ur from"@inquirer/figures";import Mr from"ansi-escapes";import{Separator as $i}from"@inquirer/core";var Br={icon:{cursor:Ur.pointer},style:{disabled:e=>rn.dim(`- ${e}`),description:e=>rn.cyan(e)},indexMode:"hidden"};function pe(e){return!Ae.isSeparator(e)&&!e.disabled}function Wr(e){return e.map(t=>{if(Ae.isSeparator(t))return t;if(typeof t=="string")return{value:t,name:t,short:t,disabled:!1};let n=t.name??String(t.value),r={value:t.value,name:n,short:t.short??n,disabled:t.disabled??!1};return t.description&&(r.description=t.description),r})}function zr(e,t){let[n="",...r]=e.split(`
3
- `),o=" ".repeat(Kr(t).length);return[`${t}${n}`,...r.map(s=>`${o}${s}`)].join(`
4
- `)}function Kr(e){return e.replace(/\x1b\[[0-9;]*m/g,"")}var we=Ar((e,t)=>{let{loop:n=!0,pageSize:r=7,instructions:o}=e,s=tn(!0),i=Fr(Br,e.theme),[c,l]=gt("idle"),d=$r({status:c,theme:i}),u=tn(),[w,f]=gt(!0),h=ht(()=>Wr(e.choices),[e.choices]),A=ht(()=>{let x=h.findIndex(pe),k=h.findLastIndex(pe);if(x===-1)throw new Lr("[select prompt] No selectable choices. All choices are disabled.");return{first:x,last:k}},[h]),v=ht(()=>"default"in e?h.findIndex(x=>pe(x)&&x.value===e.default):-1,[e.default,h]),[b,S]=gt(v===-1?A.first:v),_=h[b];Rr((x,k)=>{if(clearTimeout(u.current),f(!1),Or(x))l("done"),t(_.value);else if(yt(x)||nn(x)){if(k.clearLine(0),n||yt(x)&&b!==A.first||nn(x)&&b!==A.last){let C=yt(x)?-1:1,F=b;do F=(F+C+h.length)%h.length;while(!pe(h[F]));S(F)}}else if(Dr(x)&&!Number.isNaN(Number(k.line))){let C=Number(k.line)-1,F=h[C];F!=null&&pe(F)&&S(C),u.current=setTimeout(()=>{k.clearLine(0)},700)}else if(_r(x))k.clearLine(0);else{let C=k.line.toLowerCase(),F=h.findIndex(re=>Ae.isSeparator(re)||!pe(re)?!1:re.name.toLowerCase().startsWith(C));F!==-1&&S(F),u.current=setTimeout(()=>{k.clearLine(0)},700)}}),jr(()=>()=>{clearTimeout(u.current)},[]);let T=i.style.message(e.message,c),E="",m="";typeof o=="string"&&(E=o);let y=Nr({items:h,active:b,renderItem({item:x,isActive:k,index:C}){if(Ae.isSeparator(x))return` ${x.separator}`;let F=i.indexMode==="number"?`${C+1}. `:"";if(x.disabled){let ft=typeof x.disabled=="string"?x.disabled:"(disabled)";return i.style.disabled(`${F}${x.name} ${ft}`)}let re=k?i.style.highlight:ft=>ft,Er=k?i.icon.cursor:" ";return re(zr(x.name,`${Er} ${F}`))},pageSize:r,loop:n});if(c==="done")return`${d} ${T} ${i.style.answer(_.short)}`;let P=_.description?`
5
- ${i.style.description(_.description)}`:"";return`${[d,T,E].filter(Boolean).join(" ")}
6
- ${y}${m}${P}${Mr.cursorHide}`});import{Separator as he,input as Ps,confirm as Nl,checkbox as vs}from"@inquirer/prompts";import ro from"path";import N from"path";import{createMatchPath as Vr}from"tsconfig-paths";async function O(e,t){return Vr(t.absoluteBaseUrl,t.paths)(e,void 0,()=>!0,[".ts",".tsx"])}import{cosmiconfig as Yr}from"cosmiconfig";import Hr from"fast-glob";import{loadConfig as Xr}from"tsconfig-paths";import{z as I}from"zod";import sn from"path";var g={"next-app":{name:"next-app",label:"Next.js",links:{installation:"https://tiptap.dev/docs/ui-components/install/next"}},"next-pages":{name:"next-pages",label:"Next.js",links:{installation:"https://tiptap.dev/docs/ui-components/install/next"}},"react-router":{name:"react-router",label:"React Router",links:{installation:"https://tiptap.dev/docs/ui-components/install/react-router"}},vite:{name:"vite",label:"Vite",links:{installation:"https://tiptap.dev/docs/ui-components/install/vite"}},astro:{name:"astro",label:"Astro",links:{installation:"https://tiptap.dev/docs/ui-components/install/astro"}},laravel:{name:"laravel",label:"Laravel",links:{installation:"https://tiptap.dev/docs/ui-components/install/laravel"}},"tanstack-start":{name:"tanstack-start",label:"TanStack Start",links:{installation:"https://tiptap.dev/docs/ui-components/install/tanstack"}},manual:{name:"manual",label:"Manual",links:{installation:"https://tiptap.dev/docs/ui-components/install/next"}}};import $e from"path";import on from"fs-extra";function Ne(e="",t=!0){let n=$e.join(e,"package.json");return on.readJSONSync(n,{throws:t})}function xe(e,t){for(let n=e;;n=$e.dirname(n)){try{let r=JSON.parse(on.readFileSync($e.join(n,"node_modules",t,"package.json"),"utf8"));return typeof r.version=="string"?r.version:null}catch(r){if(r.code!=="ENOENT")throw r}if(n===$e.dirname(n))return null}}import an from"fast-glob";import cn from"fs-extra";import{loadConfig as qr}from"tsconfig-paths";var pn=["**/node_modules/**",".next","public","dist","build"];function wt(e){return["app","src/app"].find(t=>cn.existsSync(sn.join(e,t)))}async function U(e){let[t,n,r,o,s]=await Promise.all([an.glob("**/{next,vite,astro,app}.config.*|gatsby-config.*|composer.json|react-router.config.*",{cwd:e,deep:3,ignore:pn}),cn.pathExists(sn.resolve(e,"src")),Gr(e),Jr(e),Ne(e,!1)]),i={framework:g.manual,isSrcDir:n,isRSC:!1,isTsx:r,aliasPrefix:o};return t.find(c=>c.startsWith("next.config."))?.length?(i.nextAppDir=wt(e),i.framework=i.nextAppDir?g["next-app"]:g["next-pages"],i.isRSC=!!i.nextAppDir,i):t.find(c=>c.startsWith("astro.config."))?.length?(i.framework=g.astro,i):t.find(c=>c.startsWith("composer.json"))?.length?(i.framework=g.laravel,i):t.find(c=>c.startsWith("app.config."))?.length&&[...Object.keys(s?.dependencies??{}),...Object.keys(s?.devDependencies??{})].find(c=>c.startsWith("@tanstack/start"))?(i.framework=g["tanstack-start"],i):t.find(c=>c.startsWith("react-router.config."))?.length?(i.framework=g["react-router"],i):(t.find(c=>c.startsWith("vite.config."))?.length&&(i.framework=g.vite),i)}async function Jr(e){let t=await qr(e);if(t?.resultType==="failed"||!Object.entries(t?.paths).length)return null;for(let[n,r]of Object.entries(t.paths))if(r.includes("./*")||r.includes("./src/*")||r.includes("./app/*")||r.includes("./resources/js/*"))return n.replace(/\/\*$/,"")??null;return Object.keys(t?.paths)?.[0].replace(/\/\*$/,"")??null}async function Gr(e){return(await an.glob("tsconfig.*",{cwd:e,deep:1,ignore:pn})).length>0}async function ln(e,t=null){let[n,r]=await Promise.all([Z(e),t?Promise.resolve(t):U(e)]);if(n)return n;if(!r)return null;let o={rsc:r.isRSC,tsx:r.isTsx,aliases:{components:`${r.aliasPrefix}/components`,contexts:`${r.aliasPrefix}/contexts`,hooks:`${r.aliasPrefix}/hooks`,tiptapIcons:`${r.aliasPrefix}/components/tiptap-icons`,lib:`${r.aliasPrefix}/lib`,tiptapExtensions:`${r.aliasPrefix}/components/tiptap-extensions`,tiptapNodes:`${r.aliasPrefix}/components/tiptap-nodes`,tiptapUi:`${r.aliasPrefix}/components/tiptap-ui`,tiptapUiPrimitives:`${r.aliasPrefix}/components/tiptap-ui-primitives`,tiptapUiUtils:`${r.aliasPrefix}/components/tiptap-ui-utils`,styles:`${r.aliasPrefix}/styles`}};return await oe(e,o)}var Pt="@/components",vt="@/contexts",bt="@/hooks",Tt="@/components/tiptap-icons",je="@/lib",kt="@/components/tiptap-extension",It="@/components/tiptap-node",St="@/components/tiptap-ui",Ct="@/components/tiptap-ui-primitive",Et="@/components/tiptap-ui-utils",At="@/styles",Zr=Yr("components",{searchPlaces:["components.json"]}),se=I.object({rsc:I.coerce.boolean().default(!1),tsx:I.coerce.boolean().default(!0),aliases:I.object({components:I.string(),contexts:I.string().optional(),hooks:I.string().optional(),tiptapIcons:I.string().optional(),lib:I.string().optional(),tiptapExtensions:I.string().optional(),tiptapNodes:I.string().optional(),tiptapUi:I.string().optional(),tiptapUiPrimitives:I.string().optional(),tiptapUiUtils:I.string().optional(),styles:I.string().optional()})}),xt=se.extend({overrideImports:I.object({absoluteBaseUrl:I.string(),paths:I.record(I.string(),I.array(I.string()))}).optional(),resolvedPaths:I.object({cwd:I.string(),components:I.string(),contexts:I.string(),hooks:I.string(),tiptapIcons:I.string(),lib:I.string(),tiptapExtensions:I.string(),tiptapNodes:I.string(),tiptapUi:I.string(),tiptapUiPrimitives:I.string(),tiptapUiUtils:I.string(),styles:I.string()})}),Qr=I.record(I.string(),xt);async function Z(e,t){let n=await Zr.search(e),r=await U(e),o={components:Pt,contexts:vt,hooks:bt,tiptapIcons:Tt,lib:je,tiptapExtensions:kt,tiptapNodes:It,tiptapUi:St,tiptapUiPrimitives:Ct,tiptapUiUtils:Et,styles:At},s=(c,l)=>Object.fromEntries(Object.entries(c).map(([d,u])=>[d,u.replace(/^@/,l)])),i;if(n){let c={...o,...n.config.aliases};r?.aliasPrefix?i=se.parse({...n.config,aliases:s(c,r.aliasPrefix)}):i=se.parse({...n.config,aliases:c})}else{let c=o;r?.aliasPrefix&&(c=s(c,r.aliasPrefix)),i=se.parse({rsc:r?.isRSC??!1,tsx:r?.isTsx??!0,aliases:c})}return await oe(e,i,t)}async function oe(e,t,n){let r=await Xr(e);if(r.resultType==="failed")throw new Error(`Failed to load ${t.tsx?"tsconfig":"jsconfig"}.json. ${r.message??""}`.trim());if(n){let s=N.isAbsolute(n)?n:N.resolve(e,n);return xt.parse({...t,overrideImports:{absoluteBaseUrl:r.absoluteBaseUrl,paths:r.paths},resolvedPaths:{cwd:e,components:s,contexts:N.resolve(s,"..","contexts"),hooks:N.resolve(s,"..","hooks"),tiptapIcons:N.resolve(s,"tiptap-icons"),lib:N.resolve(s,"..","lib"),tiptapExtensions:N.resolve(s,"tiptap-extension"),tiptapNodes:N.resolve(s,"tiptap-node"),tiptapUi:N.resolve(s,"tiptap-ui"),tiptapUiPrimitives:N.resolve(s,"tiptap-ui-primitive"),tiptapUiUtils:N.resolve(s,"tiptap-ui-utils"),styles:N.resolve(s,"..","styles")}})}return xt.parse({...t,resolvedPaths:{cwd:e,components:await O(t.aliases.components,r),contexts:t.aliases.contexts?await O(t.aliases.contexts,r):N.resolve(await O(t.aliases.components,r)??e,"..","contexts"),hooks:t.aliases.hooks?await O(t.aliases.hooks,r):N.resolve(await O(t.aliases.components,r)??e,"..","hooks"),tiptapIcons:t.aliases.tiptapIcons?await O(t.aliases.tiptapIcons,r):N.resolve(await O(t.aliases.components,r)??e,"tiptap-icons"),lib:t.aliases.lib?await O(t.aliases.lib,r):N.resolve(await O(je,r)??e,".."),tiptapExtensions:t.aliases.tiptapExtensions?await O(t.aliases.tiptapExtensions,r):N.resolve(await O(t.aliases.components,r)??e,"tiptap-extension"),tiptapNodes:t.aliases.tiptapNodes?await O(t.aliases.tiptapNodes,r):N.resolve(await O(t.aliases.components,r)??e,"tiptap-node"),tiptapUi:t.aliases.tiptapUi?await O(t.aliases.tiptapUi,r):N.resolve(await O(t.aliases.components,r)??e,"tiptap-ui"),tiptapUiPrimitives:t.aliases.tiptapUiPrimitives?await O(t.aliases.tiptapUiPrimitives,r):N.resolve(await O(t.aliases.components,r)??e,"tiptap-ui-primitive"),tiptapUiUtils:t.aliases.tiptapUiUtils?await O(t.aliases.tiptapUiUtils,r):N.resolve(await O(t.aliases.components,r)??e,"tiptap-ui-utils"),styles:t.aliases.styles?await O(t.aliases.styles,r):N.resolve(e,"styles")}})}async function mn(e){let t={};for(let r of Object.keys(e.aliases)){if(!to(r,e))continue;let o=e.resolvedPaths[r],s=await eo(e.resolvedPaths.cwd,o);if(!s){t[r]=e;continue}t[r]=await Z(s)}let n=Qr.safeParse(t);return n.success?n.data:null}async function eo(e,t){let n=no(e,t),r=N.relative(n,t),s=(await Hr.glob("**/package.json",{cwd:n,deep:3,ignore:["**/node_modules/**","**/dist/**","**/build/**","**/public/**"]})).map(i=>N.dirname(i)).find(i=>r.startsWith(i));return s?N.join(n,s):null}function to(e,t){return Object.keys(t.resolvedPaths).includes(e)}function no(e,t){let n=e.split(N.sep),r=t.split(N.sep),o=[];for(let s=0;s<Math.min(n.length,r.length)&&n[s]===r[s];s++)o.push(n[s]);return o.join(N.sep)}import J from"chalk";var p={cyan:J.cyan,magenta:J.magenta,gray:J.gray,white:J.white,yellow:J.yellow,green:J.green,red:J.red,blue:J.blue,reset:J.reset,dim:J.dim,bold:J.bold,whiteBold:J.white.bold};var Pe=e=>e.map(String).join(" "),a={error(...e){console.log(p.red(Pe(e)))},warn(...e){console.log(p.yellow(Pe(e)))},info(...e){console.log(p.cyan(Pe(e)))},success(...e){console.log(p.green(Pe(e)))},log(...e){console.log(Pe(e))},break(){console.log("")}};import un from"fs-extra";async function dn(e){let t={};if(!un.existsSync(e.cwd)||!un.existsSync(ro.resolve(e.cwd,"package.json")))return t["1"]=!0,{errors:t,config:null};try{let n=await Z(e.cwd,e.path);return{errors:t,config:n}}catch(n){console.log("[preFlightAdd] - ",n),a.break(),a.error(`Make sure you are in a valid project directory. Run ${p.cyan("npx @tiptap/cli init")} to create a new project.`),a.break(),process.exit(1)}}import Me from"node-fetch";import{HttpsProxyAgent as To}from"https-proxy-agent";import oo from"ora";var so={frames:[`${p.cyan("\u2588")}`,`${p.cyan("\u2588")}`,`${p.cyan("\u2588")}`," "," "," "],interval:200};function L(e,t){return oo({text:e,spinner:so,color:"cyan",isSilent:t?.silent})}import io from"conf";import fn from"fs-extra";var _e=class{config;logger;constructor(t){if(this.logger=t,this.config=new io({projectName:"tiptap-cli",configFileMode:384,clearInvalidConfig:!0,schema:{bearerToken:{type:"string"},authToken:{type:"string"},email:{type:"string"},loginDate:{type:"string"},plans:{type:"array",items:{type:"string"},default:[]},licenseAccepted:{type:"boolean"},licenseAcceptedDate:{type:"string"}}}),process.platform!=="win32"&&fn.existsSync(this.config.path))try{fn.chmodSync(this.config.path,384)}catch{throw new Error("Could not protect the CLI credential file")}}safeError(t,n){try{this.logger.error(t)}catch{}}setBearerToken(t,n){try{this.config.set("bearerToken",t),this.config.set("loginDate",new Date().toISOString()),n?.email&&this.config.set("email",n.email),n?.plans&&this.config.set("plans",n.plans)}catch(r){this.safeError("Failed to store bearer token",r)}}getBearerToken(){try{return this.config.get("bearerToken")??null}catch(t){return this.safeError("Failed to retrieve bearer token",t),null}}setAuthToken(t,n){try{this.config.set("authToken",t),this.config.set("loginDate",new Date().toISOString()),n?.email&&this.config.set("email",n.email),n?.plans&&this.config.set("plans",n.plans)}catch(r){this.safeError("Failed to store auth token",r)}}getAuthToken(){try{return this.config.get("authToken")??null}catch(t){return this.safeError("Failed to retrieve auth token",t),null}}getUserInfo(){return{email:this.config.get("email"),plans:this.config.get("plans")??[],loginDate:this.config.get("loginDate")}}getTokenExpiration(){let t=this.config.get("loginDate");if(!t)return null;let n=new Date(t);return n.setMonth(n.getMonth()+11),n.toISOString()}isValidToken(){let t=this.getBearerToken(),n=this.getAuthToken();if(!t&&!n)return!1;let r=this.getTokenExpiration();return r&&new Date(r)<=new Date?(this.clearSession(),!1):!0}clear(){try{this.config.clear()}catch(t){this.safeError("Failed to clear token storage",t)}}clearSession(){try{this.config.delete("bearerToken"),this.config.delete("authToken"),this.config.delete("email"),this.config.delete("loginDate"),this.config.delete("plans")}catch(t){this.safeError("Failed to clear token storage",t)}}hasPlan(t){let n=this.config.get("plans")??[];return Array.isArray(n)&&n.includes(t)}setLicenseAccepted(){try{this.config.set("licenseAccepted",!0),this.config.set("licenseAcceptedDate",new Date().toISOString())}catch(t){this.safeError("Failed to store license acceptance",t)}}hasAcceptedLicense(){try{return this.config.get("licenseAccepted")??!1}catch(t){return this.safeError("Failed to retrieve license acceptance",t),!1}}clearLicenseAcceptance(){try{this.config.delete("licenseAccepted"),this.config.delete("licenseAcceptedDate")}catch(t){this.safeError("Failed to clear license acceptance",t)}}};var j=new _e(a);import B from"fs-extra";import te from"path";import yn from"os";import{execa as le}from"execa";import gn from"yaml";var $t="https://registry.tiptap.dev/",ve="//registry.tiptap.dev/:_authToken",Oe="@tiptap-pro:registry",G=class extends Error{};async function hn(e){try{if(!(await B.lstat(e)).isFile())throw new G(`Refusing non-regular configuration file: ${e}`)}catch(t){if(t.code!=="ENOENT")throw t}}async function Rt(e,t){await hn(te.join(e,t));let n={cwd:e,reject:!1,env:{LC_ALL:"C"}},r=await le("git",["rev-parse","--show-toplevel"],n),o=r.exitCode===0;if(!o&&!(r.exitCode===128&&r.stderr.includes("not a git repository")))throw new G("Could not establish Git protection for registry configuration");if(o){let l=await le("git",["ls-files","--error-unmatch","--",t],n);if(l.exitCode===0)throw new G(`Refusing tracked registry configuration: ${te.join(e,t)}. Configure credentials outside tracked files.`);if(l.exitCode!==1)throw new G("Could not check tracked registry configuration");let d=await le("git",["check-ignore","--quiet","--",t],n);if(d.exitCode===0)return;if(d.exitCode!==1)throw new G("Could not check ignored registry configuration")}let s=te.join(e,".gitignore");await hn(s);let i=await B.pathExists(s)?await B.readFile(s,"utf8"):"",c=`/${t}`;if(!i.trimEnd().endsWith(`
7
- ${c}`)&&i.trim()!==c&&await B.writeFile(s,`${i}${i.endsWith(`
8
- `)||!i?"":`
9
- `}${c}
10
- `),o&&(await le("git",["check-ignore","--quiet","--",t],n)).exitCode!==0)throw new G("Registry configuration is not ignored by Git")}async function De(e,t,n){try{return t==="yarn"?await ao(e,n):(await Rt(n,".npmrc"),await xn(te.join(n,".npmrc"),e)),!0}catch(r){return a.error(r instanceof G?r.message:`Could not safely save registry configuration in ${n}`),!1}}async function wn(e,t){process.platform!=="win32"&&await B.pathExists(e)&&await B.chmod(e,384),await B.writeFile(e,t,{mode:384})}async function ao(e,t){let n=!1;try{let{stdout:r}=await le("yarn",["--version"],{cwd:t});n=!r.startsWith("1.")}catch{}n?(await Rt(t,".yarnrc.yml"),await co(e,t)):(await Rt(t,".npmrc"),await xn(te.join(t,".npmrc"),e))}async function co(e,t){let n=te.join(t,".yarnrc.yml"),r={};if(B.existsSync(n)){let i=await B.readFile(n,"utf8");if(r=gn.parse(i)??{},typeof r!="object"||Array.isArray(r))throw new G(`Invalid Yarn configuration: ${n}`)}if(r.npmScopes||(r.npmScopes={}),typeof r.npmScopes!="object"||Array.isArray(r.npmScopes))throw new G(`Invalid Yarn scopes: ${n}`);let o=r.npmScopes,s=o["tiptap-pro"];if(s!=null&&(typeof s!="object"||Array.isArray(s)))throw new G(`Invalid Tiptap Yarn scope: ${n}`);o["tiptap-pro"]={...s,npmRegistryServer:$t,npmAuthToken:e,npmAlwaysAuth:!0},await wn(n,gn.stringify(r))}async function xn(e,t){let n="";B.existsSync(e)&&(n=await B.readFile(e,"utf8"));let{lines:r,processedKeys:o}=po(n,t);o.has(Oe)||r.push(`${Oe}=${$t}`),o.has(ve)||r.push(`${ve}=${t}`),r.length>0&&r[r.length-1]!==""&&r.push(""),await wn(e,r.join(`
11
- `))}function po(e,t){let n=[],r=new Set,o=e.split(`
12
- `);for(let s of o){let i=s.trim();if(!i){n.push(s);continue}if(i.startsWith("#")){n.push(s);continue}let c=s.indexOf("=");if(c!==-1){let l=s.substring(0,c).trim();l===Oe?(n.push(`${Oe}=${$t}`),r.add(l)):l===ve?(n.push(`${ve}=${t}`),r.add(l)):n.push(s)}else n.push(s)}return{lines:n,processedKeys:r}}async function Pn(e,t){try{let n=await lo(t);if(n)return n;if(e==="npm")return await mo(t);let r=await uo();return r||(e==="yarn"?await fo():null)}catch{return null}}async function lo(e){let t=te.join(e,".npmrc");if(B.existsSync(t)){let n=await B.readFile(t,"utf8");return vn(n)}return null}async function mo(e){let{stdout:t}=await le("npm",["config","get",ve],{cwd:e});return t&&t!=="undefined"?t.trim():null}async function uo(){let e=te.join(yn.homedir(),".npmrc");if(B.existsSync(e)){let t=await B.readFile(e,"utf8");return vn(t)}return null}async function fo(){let e=te.join(yn.homedir(),".yarnrc");return B.existsSync(e)?(await B.readFile(e,"utf8")).split(`
13
- `).map(r=>r.match(/^"\/\/registry\.tiptap\.dev\/:_authToken"\s+"?([^"\s]+)"?/)).find(r=>r!==null)?.[1]??null:null}function vn(e){let t=e.split(`
14
- `).filter(r=>r.startsWith("//registry.tiptap.dev/:_authToken="));return t.length===0?null:t[0].split("=")[1]?.trim()||null}import{z as R}from"zod";var Le=R.enum(["registry:context","registry:extension","registry:hook","registry:icon","registry:lib","registry:node","registry:template","registry:ui-primitive","registry:ui","registry:ui-utils","registry:page","registry:component","registry:style","registry:asset"]),me=["start","team","growth","enterprise","business"],go=["open-source","light"],ho=[...me,...go],yo=R.array(R.enum(ho)).default([]),Nt=R.object({path:R.string(),content:R.string().optional(),type:Le,target:R.string().optional()}),jt=R.object({name:R.string(),type:Le,description:R.string().optional(),dependencies:R.array(R.string()).optional(),devDependencies:R.array(R.string()).optional(),registryDependencies:R.array(R.string()).optional(),files:R.array(Nt).optional(),meta:R.record(R.string(),R.any()).optional(),plans:yo.optional(),hide:R.boolean().default(!1).optional(),isNew:R.boolean().default(!1).optional()}),Fe=jt.extend({files:R.array(Nt.extend({content:R.string()})).optional()}),Ra=R.array(jt),bn=R.array(jt.extend({files:R.array(R.union([R.string(),Nt])).optional()}));import{HttpsProxyAgent as wo}from"https-proxy-agent";import _t from"node-fetch";import{z as ue}from"zod";var Ue="https://template.tiptap.dev";function be(){let e=process.env.TIPTAP_REGISTRY_URL||Ue,t=URL.canParse(e)?new URL(e):null;if(!t||!["http:","https:"].includes(t.protocol)||t.username||t.password||t.search||t.hash)throw new Error("Set TIPTAP_REGISTRY_URL to an HTTP or HTTPS URL without credentials, a query, or a fragment.");return t.href.replace(/\/+$/,"")}var Ot=process.env.https_proxy?new wo(process.env.https_proxy):void 0;async function Q(){let e=await kn("index.json");return bn.parse(e)}function Dt(e,t,n=!1){let r=t?` at ${p.cyan(t)}`:"";switch(e.status){case 400:return new Error(`The registry rejected the request${r}.
2
+ import xa from"path";import{Command as Pa}from"commander";import{z as Q}from"zod";import{createPrompt as oi,useState as an,useKeypress as ii,usePrefix as si,usePagination as ai,useRef as pr,useMemo as cn,useEffect as ci,isBackspaceKey as li,isEnterKey as pi,isUpKey as ln,isDownKey as ur,isNumberKey as ui,Separator as mt,ValidationError as di,makeTheme as mi}from"@inquirer/core";import dr from"yoctocolors-cjs";import fi from"@inquirer/figures";import gi from"ansi-escapes";import{Separator as Nc}from"@inquirer/core";var hi={icon:{cursor:fi.pointer},style:{disabled:e=>dr.dim(`- ${e}`),description:e=>dr.cyan(e)},indexMode:"hidden"};function Ne(e){return!mt.isSeparator(e)&&!e.disabled}function yi(e){return e.map(t=>{if(mt.isSeparator(t))return t;if(typeof t=="string")return{value:t,name:t,short:t,disabled:!1};let n=t.name??String(t.value),r={value:t.value,name:n,short:t.short??n,disabled:t.disabled??!1};return t.description&&(r.description=t.description),r})}function wi(e,t){let[n="",...r]=e.split(`
3
+ `),o=" ".repeat(xi(t).length);return[`${t}${n}`,...r.map(i=>`${o}${i}`)].join(`
4
+ `)}function xi(e){return e.replace(/\x1b\[[0-9;]*m/g,"")}var je=oi((e,t)=>{let{loop:n=!0,pageSize:r=7,instructions:o}=e,i=pr(!0),s=mi(hi,e.theme),[a,c]=an("idle"),p=si({status:a,theme:s}),u=pr(),[m,g]=an(!0),f=cn(()=>yi(e.choices),[e.choices]),y=cn(()=>{let b=f.findIndex(Ne),I=f.findLastIndex(Ne);if(b===-1)throw new di("[select prompt] No selectable choices. All choices are disabled.");return{first:b,last:I}},[f]),S=cn(()=>"default"in e?f.findIndex(b=>Ne(b)&&b.value===e.default):-1,[e.default,f]),[P,v]=an(S===-1?y.first:S),A=f[P];ii((b,I)=>{if(clearTimeout(u.current),g(!1),pi(b))c("done"),t(A.value);else if(ln(b)||ur(b)){if(I.clearLine(0),n||ln(b)&&P!==y.first||ur(b)&&P!==y.last){let R=ln(b)?-1:1,$=P;do $=($+R+f.length)%f.length;while(!Ne(f[$]));v($)}}else if(ui(b)&&!Number.isNaN(Number(I.line))){let R=Number(I.line)-1,$=f[R];$!=null&&Ne($)&&v(R),u.current=setTimeout(()=>{I.clearLine(0)},700)}else if(li(b))I.clearLine(0);else{let R=I.line.toLowerCase(),$=f.findIndex(H=>mt.isSeparator(H)||!Ne(H)?!1:H.name.toLowerCase().startsWith(R));$!==-1&&v($),u.current=setTimeout(()=>{I.clearLine(0)},700)}}),ci(()=>()=>{clearTimeout(u.current)},[]);let w=s.style.message(e.message,a),k="",C="";typeof o=="string"&&(k=o);let h=ai({items:f,active:P,renderItem({item:b,isActive:I,index:R}){if(mt.isSeparator(b))return` ${b.separator}`;let $=s.indexMode==="number"?`${R+1}. `:"";if(b.disabled){let V=typeof b.disabled=="string"?b.disabled:"(disabled)";return s.style.disabled(`${$}${b.name} ${V}`)}let H=I?s.style.highlight:V=>V,$e=I?s.icon.cursor:" ";return H(wi(b.name,`${$e} ${$}`))},pageSize:r,loop:n});if(a==="done")return`${p} ${w} ${s.style.answer(A.short)}`;let x=A.description?`
5
+ ${s.style.description(A.description)}`:"";return`${[p,w,k].filter(Boolean).join(" ")}
6
+ ${h}${C}${x}${gi.cursorHide}`});import{Separator as ze,input as ba,confirm as _m,checkbox as va}from"@inquirer/prompts";import Ni from"path";import{statSync as ki}from"fs";import F from"path";import{createMatchPath as Pi}from"tsconfig-paths";async function D(e,t,n=!0){return Pi(t.absoluteBaseUrl,t.paths,void 0,n)(e,void 0,()=>!0,[".ts",".tsx"])}import{cosmiconfig as Ti}from"cosmiconfig";import Si from"fast-glob";import{loadConfig as Ii}from"tsconfig-paths";import{z as N}from"zod";import gr from"path";var T={"next-app":{name:"next-app",label:"Next.js",links:{installation:"https://tiptap.dev/docs/ui-components/install/next"}},"next-pages":{name:"next-pages",label:"Next.js",links:{installation:"https://tiptap.dev/docs/ui-components/install/next"}},"react-router":{name:"react-router",label:"React Router",links:{installation:"https://tiptap.dev/docs/ui-components/install/react-router"}},vite:{name:"vite",label:"Vite",links:{installation:"https://tiptap.dev/docs/ui-components/install/vite"}},astro:{name:"astro",label:"Astro",links:{installation:"https://tiptap.dev/docs/ui-components/install/astro"}},laravel:{name:"laravel",label:"Laravel",links:{installation:"https://tiptap.dev/docs/ui-components/install/laravel"}},"tanstack-start":{name:"tanstack-start",label:"TanStack Start",links:{installation:"https://tiptap.dev/docs/ui-components/install/manual"}},manual:{name:"manual",label:"Manual",links:{installation:"https://tiptap.dev/docs/ui-components/install/next"}}};import ft from"path";import fr from"fs-extra";function Fe(e="",t=!0){let n=ft.join(e,"package.json");return fr.readJSONSync(n,{throws:t})}function Ye(e,t){for(let n=e;;n=ft.dirname(n)){try{let r=JSON.parse(fr.readFileSync(ft.join(n,"node_modules",t,"package.json"),"utf8"));return typeof r.version=="string"?r.version:null}catch(r){if(r.code!=="ENOENT")throw r}if(n===ft.dirname(n))return null}}import hr from"fast-glob";import yr from"fs-extra";var wr=["**/node_modules/**",".next","public","dist","build"];function pn(e){return["app","src/app"].find(t=>yr.existsSync(gr.join(e,t)))}async function z(e,t={}){let[n,r,o,i,s]=await Promise.all([hr.glob("**/{next,vite,astro,app}.config.*|gatsby-config.*|composer.json|react-router.config.*",{cwd:e,deep:3,ignore:wr}),yr.pathExists(gr.resolve(e,"src")),vi(e),bi(e),Fe(e,!1)]),a={framework:T.manual,isSrcDir:r,isRSC:!1,isTsx:o,aliasPrefix:i};return n.some(c=>c.startsWith("next.config."))||t.forFeature&&(s?.dependencies?.next||s?.devDependencies?.next)?(a.nextAppDir=pn(e),a.framework=a.nextAppDir?T["next-app"]:T["next-pages"],a.isRSC=!!a.nextAppDir,a):n.find(c=>c.startsWith("astro.config."))?.length?(a.framework=T.astro,a):n.find(c=>c.startsWith("composer.json"))?.length?(a.framework=T.laravel,a):n.find(c=>c.startsWith("app.config."))?.length&&[...Object.keys(s?.dependencies??{}),...Object.keys(s?.devDependencies??{})].find(c=>c.startsWith("@tanstack/start"))?(a.framework=T["tanstack-start"],a):n.find(c=>c.startsWith("react-router.config."))?.length?(a.framework=T["react-router"],a):(n.find(c=>c.startsWith("vite.config."))?.length&&(a.framework=T.vite),a)}async function bi(e){let t=gt(e);if(t?.resultType==="failed"||!Object.entries(t?.paths).length)return null;for(let[n,r]of Object.entries(t.paths))if(r.includes("./*")||r.includes("./src/*")||r.includes("./app/*")||r.includes("./resources/js/*"))return n.replace(/\/\*$/,"")??null;return Object.keys(t?.paths)?.[0].replace(/\/\*$/,"")??null}async function vi(e){return(await hr.glob("tsconfig.*",{cwd:e,deep:1,ignore:wr})).length>0}async function xr(e,t=null){let[n,r]=await Promise.all([ne(e),t?Promise.resolve(t):z(e)]);if(n)return n;if(!r)return null;let o={rsc:r.isRSC,tsx:r.isTsx,aliases:{components:`${r.aliasPrefix}/components`,contexts:`${r.aliasPrefix}/contexts`,hooks:`${r.aliasPrefix}/hooks`,tiptapIcons:`${r.aliasPrefix}/components/tiptap-icons`,lib:`${r.aliasPrefix}/lib`,tiptapExtensions:`${r.aliasPrefix}/components/tiptap-extensions`,tiptapNodes:`${r.aliasPrefix}/components/tiptap-nodes`,tiptapUi:`${r.aliasPrefix}/components/tiptap-ui`,tiptapUiPrimitives:`${r.aliasPrefix}/components/tiptap-ui-primitives`,tiptapUiUtils:`${r.aliasPrefix}/components/tiptap-ui-utils`,styles:`${r.aliasPrefix}/styles`}};return await Oe(e,o)}var un="@/components",dn="@/contexts",mn="@/hooks",fn="@/components/tiptap-icons",yt="@/lib",gn="@/components/tiptap-extension",hn="@/components/tiptap-node",yn="@/components/tiptap-ui",wn="@/components/tiptap-ui-primitive",xn="@/components/tiptap-ui-utils",Pn="@/styles",Ei=Ti("components",{searchPlaces:["components.json"]}),fe=N.object({rsc:N.coerce.boolean().default(!1),tsx:N.coerce.boolean().default(!0),aliases:N.object({components:N.string(),contexts:N.string().optional(),hooks:N.string().optional(),tiptapIcons:N.string().optional(),lib:N.string().optional(),tiptapExtensions:N.string().optional(),tiptapNodes:N.string().optional(),tiptapUi:N.string().optional(),tiptapUiPrimitives:N.string().optional(),tiptapUiUtils:N.string().optional(),styles:N.string().optional()})}),ht=fe.extend({overrideImports:N.object({absoluteBaseUrl:N.string(),paths:N.record(N.string(),N.array(N.string()))}).optional(),resolvedPaths:N.object({cwd:N.string(),components:N.string(),contexts:N.string(),hooks:N.string(),tiptapIcons:N.string(),lib:N.string(),tiptapExtensions:N.string(),tiptapNodes:N.string(),tiptapUi:N.string(),tiptapUiPrimitives:N.string(),tiptapUiUtils:N.string(),styles:N.string()})}),Ci=N.record(N.string(),ht);function gt(e){try{return Ii(e)}catch(t){return{resultType:"failed",message:t instanceof Error?t.message:String(t)}}}async function ne(e,t,n={}){let r=await Ei.search(e),o=n.projectInfo!==void 0?n.projectInfo:await z(e,{forFeature:n.featureOnly}),i={components:un,contexts:dn,hooks:mn,tiptapIcons:fn,lib:yt,tiptapExtensions:gn,tiptapNodes:hn,tiptapUi:yn,tiptapUiPrimitives:wn,tiptapUiUtils:xn,styles:Pn},s=(c,p)=>Object.fromEntries(Object.entries(c).map(([u,m])=>[u,m.replace(/^@/,p)]));if(n.featureOnly){let c=gt(e),p=c.resultType==="success"?c.paths:{},u=Object.keys(p).find(y=>/(?:^@?components|\/components)(?:\/\*)?$/.test(y)),m=Object.entries(p).find(([y,S])=>y.endsWith("/*")&&(["@/*","~/*"].includes(y)||S.some(P=>["*","src/*","app/*","resources/js/*"].includes(P.replace(/^\.\//,"")))))?.[0],g=m?s(i,m.slice(0,-2)):{...i};u&&(g.components=u.replace(/\/\*$/,""));let f=fe.parse({rsc:o?.isRSC??!1,tsx:o?.isTsx??!0,...r?.config,aliases:{...g,...r?.config.aliases}});return Oe(e,f,t,F.join(e,o?.isSrcDir?"src":"","components"),r?.config.aliases??{})}let a;if(r){let c={...i,...r.config.aliases};o?.aliasPrefix?a=fe.parse({...r.config,aliases:s(c,o.aliasPrefix)}):a=fe.parse({...r.config,aliases:c})}else{let c=i;o?.aliasPrefix&&(c=s(c,o.aliasPrefix)),a=fe.parse({rsc:o?.isRSC??!1,tsx:o?.isTsx??!0,aliases:c})}return await Oe(e,a,t)}async function Oe(e,t,n,r,o={}){let i=gt(e);if(i.resultType==="failed"&&!r)throw new Error(`Failed to load ${t.tsx?"tsconfig":"jsconfig"}.json. ${i.message??""}`.trim());let s=i.resultType==="success"?{absoluteBaseUrl:i.absoluteBaseUrl,paths:i.paths}:{absoluteBaseUrl:e,paths:{}};if(r){async function c(m,g){let f=Object.hasOwn(s.paths,`${m}/*`);if(!f&&Object.hasOwn(s.paths,m)){let S=await D(m,s,!1);if(S){let P=ki(S,{throwIfNoEntry:!1});if(P?P.isDirectory():!/\.[cm]?[jt]sx?$/i.test(S))return S}}if(n&&!g&&!f)return;let y=await D(`${m}/__tiptap_file__`,s,g);return y&&F.dirname(y)}let p=n?F.resolve(e,n):await c(t.aliases.components,!!o.components)??r,u={cwd:e,components:p};for(let[m,g]of Object.entries(t.aliases)){if(m==="components"||!g)continue;let f=F.posix.basename(g),y=["hooks","lib","styles","contexts"].includes(m)?F.resolve(p,"..",f):F.join(p,f);u[m]=await c(g,!!o[m])??y}return ht.parse({...t,overrideImports:s,resolvedPaths:u})}if(n){let c=F.isAbsolute(n)?n:F.resolve(e,n);return ht.parse({...t,overrideImports:s,resolvedPaths:{cwd:e,components:c,contexts:F.resolve(c,"..","contexts"),hooks:F.resolve(c,"..","hooks"),tiptapIcons:F.resolve(c,"tiptap-icons"),lib:F.resolve(c,"..","lib"),tiptapExtensions:F.resolve(c,"tiptap-extension"),tiptapNodes:F.resolve(c,"tiptap-node"),tiptapUi:F.resolve(c,"tiptap-ui"),tiptapUiPrimitives:F.resolve(c,"tiptap-ui-primitive"),tiptapUiUtils:F.resolve(c,"tiptap-ui-utils"),styles:F.resolve(c,"..","styles")}})}return ht.parse({...t,resolvedPaths:{cwd:e,components:await D(t.aliases.components,s),contexts:t.aliases.contexts?await D(t.aliases.contexts,s):F.resolve(await D(t.aliases.components,s)??e,"..","contexts"),hooks:t.aliases.hooks?await D(t.aliases.hooks,s):F.resolve(await D(t.aliases.components,s)??e,"..","hooks"),tiptapIcons:t.aliases.tiptapIcons?await D(t.aliases.tiptapIcons,s):F.resolve(await D(t.aliases.components,s)??e,"tiptap-icons"),lib:t.aliases.lib?await D(t.aliases.lib,s):F.resolve(await D(yt,s)??e,".."),tiptapExtensions:t.aliases.tiptapExtensions?await D(t.aliases.tiptapExtensions,s):F.resolve(await D(t.aliases.components,s)??e,"tiptap-extension"),tiptapNodes:t.aliases.tiptapNodes?await D(t.aliases.tiptapNodes,s):F.resolve(await D(t.aliases.components,s)??e,"tiptap-node"),tiptapUi:t.aliases.tiptapUi?await D(t.aliases.tiptapUi,s):F.resolve(await D(t.aliases.components,s)??e,"tiptap-ui"),tiptapUiPrimitives:t.aliases.tiptapUiPrimitives?await D(t.aliases.tiptapUiPrimitives,s):F.resolve(await D(t.aliases.components,s)??e,"tiptap-ui-primitive"),tiptapUiUtils:t.aliases.tiptapUiUtils?await D(t.aliases.tiptapUiUtils,s):F.resolve(await D(t.aliases.components,s)??e,"tiptap-ui-utils"),styles:t.aliases.styles?await D(t.aliases.styles,s):F.resolve(e,"styles")}})}async function Pr(e){let t={};for(let r of Object.keys(e.aliases)){if(!Ai(r,e))continue;let o=e.resolvedPaths[r],i=await $i(e.resolvedPaths.cwd,o);if(!i){t[r]=e;continue}t[r]=await ne(i)}let n=Ci.safeParse(t);return n.success?n.data:null}async function $i(e,t){let n=Ri(e,t),r=F.relative(n,t),i=(await Si.glob("**/package.json",{cwd:n,deep:3,ignore:["**/node_modules/**","**/dist/**","**/build/**","**/public/**"]})).map(s=>F.dirname(s)).find(s=>r.startsWith(s));return i?F.join(n,i):null}function Ai(e,t){return Object.keys(t.resolvedPaths).includes(e)}function Ri(e,t){let n=e.split(F.sep),r=t.split(F.sep),o=[];for(let i=0;i<Math.min(n.length,r.length)&&n[i]===r[i];i++)o.push(n[i]);return o.join(F.sep)}import re from"chalk";var d={cyan:re.cyan,magenta:re.magenta,gray:re.gray,white:re.white,yellow:re.yellow,green:re.green,red:re.red,blue:re.blue,reset:re.reset,dim:re.dim,bold:re.bold,whiteBold:re.white.bold};var He=e=>e.map(String).join(" "),l={error(...e){console.log(d.red(He(e)))},warn(...e){console.log(d.yellow(He(e)))},info(...e){console.log(d.cyan(He(e)))},success(...e){console.log(d.green(He(e)))},log(...e){console.log(He(e))},break(){console.log("")}};import br from"fs-extra";async function vr(e,t){let n={};if(!br.existsSync(e.cwd)||!br.existsSync(Ni.resolve(e.cwd,"package.json")))return n["1"]=!0,{errors:n,config:null};try{let r=await ne(e.cwd,e.path,{featureOnly:t!==void 0,projectInfo:t});return{errors:n,config:r}}catch(r){console.log("[preFlightAdd] - ",r),l.break(),l.error(`Make sure you are in a valid project directory. Run ${d.cyan("npx @tiptap/cli init")} to create a new project.`),l.break(),process.exit(1)}}import Hn from"path";import St from"node-fetch";import{HttpsProxyAgent as es}from"https-proxy-agent";import ji from"ora";var Fi={frames:[`${d.cyan("\u2588")}`,`${d.cyan("\u2588")}`,`${d.cyan("\u2588")}`," "," "," "],interval:200};function K(e,t){return ji({text:e,spinner:Fi,color:"cyan",isSilent:t?.silent})}import Oi from"conf";import kr from"fs-extra";function vn(e){if(!e)return;let t=new Date(e);return t.setMonth(t.getMonth()+11),t}var wt=class{config;logger;constructor(t){if(this.logger=t,this.config=new Oi({projectName:"tiptap-cli",configFileMode:384,clearInvalidConfig:!0,schema:{bearerToken:{type:"string"},authToken:{type:"string"},email:{type:"string"},loginDate:{type:"string"},packageLoginDate:{type:"string"},plans:{type:"array",items:{type:"string"},default:[]},licenseAccepted:{type:"boolean"},licenseAcceptedDate:{type:"string"}}}),process.platform!=="win32"&&kr.existsSync(this.config.path))try{kr.chmodSync(this.config.path,384)}catch{throw new Error("Could not protect the CLI credential file")}}safeError(t,n){try{this.logger.error(t)}catch{}}setBearerToken(t,n){try{this.config.has("authToken")&&!this.config.has("packageLoginDate")&&this.config.has("loginDate")&&this.config.set("packageLoginDate",this.config.get("loginDate")),this.config.set("bearerToken",t),this.config.set("loginDate",new Date().toISOString()),n?.email&&this.config.set("email",n.email),n?.plans&&this.config.set("plans",n.plans)}catch(r){this.safeError("Failed to store bearer token",r)}}getBearerToken(){try{return this.config.get("bearerToken")??null}catch(t){return this.safeError("Failed to retrieve bearer token",t),null}}setAuthToken(t,n){try{this.config.set({authToken:t,packageLoginDate:new Date().toISOString()}),n?.email&&this.config.set("email",n.email),n?.plans&&this.config.set("plans",n.plans)}catch(r){this.safeError("Failed to store auth token",r)}}getAuthToken(){try{let t=this.config.get("authToken");if(!t)return null;let n=vn(this.config.get("packageLoginDate")??this.config.get("loginDate"));return n&&n.getTime()<=Date.now()?(this.config.delete("authToken"),this.config.delete("packageLoginDate"),null):t}catch(t){return this.safeError("Failed to retrieve auth token",t),null}}getUserInfo(){return{email:this.config.get("email"),plans:this.config.get("plans")??[],loginDate:this.config.get("loginDate")}}getTokenExpiration(){return vn(this.config.get("loginDate"))?.toISOString()??null}isValidToken(){if(!this.getBearerToken())return!!this.getAuthToken();let t=vn(this.config.get("loginDate"));return!t||t.getTime()>Date.now()?!0:(this.getAuthToken(),this.config.delete("bearerToken"),this.config.delete("email"),this.config.delete("loginDate"),this.config.delete("plans"),!1)}clear(){try{this.config.clear()}catch(t){this.safeError("Failed to clear token storage",t)}}clearSession(){try{this.config.delete("bearerToken"),this.config.delete("authToken"),this.config.delete("packageLoginDate"),this.config.delete("email"),this.config.delete("loginDate"),this.config.delete("plans")}catch(t){this.safeError("Failed to clear token storage",t)}}hasPlan(t){let n=this.config.get("plans")??[];return Array.isArray(n)&&n.includes(t)}setLicenseAccepted(){try{this.config.set("licenseAccepted",!0),this.config.set("licenseAcceptedDate",new Date().toISOString())}catch(t){this.safeError("Failed to store license acceptance",t)}}hasAcceptedLicense(){try{return this.config.get("licenseAccepted")??!1}catch(t){return this.safeError("Failed to retrieve license acceptance",t),!1}}clearLicenseAcceptance(){try{this.config.delete("licenseAccepted"),this.config.delete("licenseAcceptedDate")}catch(t){this.safeError("Failed to clear license acceptance",t)}}};var j=new wt(l);import U from"fs-extra";import B from"path";import Ir from"os";import{execa as Pe}from"execa";import Tr from"yaml";import Di from"@npmcli/map-workspaces";var Tn="https://registry.tiptap.dev/",Xe="//registry.tiptap.dev/:_authToken",xt="@tiptap-pro:registry",oe=class extends Error{};async function Ze(e,t){let n=B.resolve(e);if(t==="bun"){let{stdout:o,stderr:i,exitCode:s}=await Pe("bun",["pm","bin"],{cwd:n,reject:!1});if(s!==0&&i.includes("No package.json was found"))return n;let a=o.trim(),c=B.dirname(a);if(s!==0||!B.isAbsolute(a)||B.basename(a)!==".bin"||B.basename(c)!=="node_modules")throw new Error(`Could not find Bun's project directory from ${n}.`);return B.dirname(c)}if(t!=="npm"&&t!=="pnpm")return n;let r;for(let o=n;;o=B.dirname(o)){if(t==="pnpm"&&await U.pathExists(B.join(o,"pnpm-workspace.yaml")))return o;if(t==="npm"){let i=B.join(o,"package.json"),s=await U.pathExists(i);if(!r&&(s||await U.pathExists(B.join(o,"node_modules"))))r=o;else if(r&&s){let a=await U.readJson(i,{throws:!1}),c=a?.workspaces?.packages??a?.workspaces;if(Array.isArray(c)){let p=await Di({cwd:o,pkg:a});if(Array.from(p.values()).includes(r))return o}}}if(o===B.dirname(o))break}return r??n}async function Sr(e){try{if(!(await U.lstat(e)).isFile())throw new oe(`Refusing non-regular configuration file: ${e}`)}catch(t){if(t.code!=="ENOENT")throw t}}async function kn(e,t){await Sr(B.join(e,t));let n={cwd:e,reject:!1,env:{LC_ALL:"C"}},r=await Pe("git",["rev-parse","--show-toplevel"],n),o=r.exitCode===0;if(!o&&!(r.exitCode===128&&r.stderr.includes("not a git repository")))throw new oe("Could not establish Git protection for registry configuration");if(o){let c=await Pe("git",["ls-files","--error-unmatch","--",t],n);if(c.exitCode===0)throw new oe(`Refusing tracked registry configuration: ${B.join(e,t)}. Configure credentials outside tracked files.`);if(c.exitCode!==1)throw new oe("Could not check tracked registry configuration");let p=await Pe("git",["check-ignore","--quiet","--",t],n);if(p.exitCode===0)return;if(p.exitCode!==1)throw new oe("Could not check ignored registry configuration")}let i=B.join(e,".gitignore");await Sr(i);let s=await U.pathExists(i)?await U.readFile(i,"utf8"):"",a=`/${t}`;if(!s.trimEnd().endsWith(`
7
+ ${a}`)&&s.trim()!==a&&await U.writeFile(i,`${s}${s.endsWith(`
8
+ `)||!s?"":`
9
+ `}${a}
10
+ `),o&&(await Pe("git",["check-ignore","--quiet","--",t],n)).exitCode!==0)throw new oe("Registry configuration is not ignored by Git")}async function De(e,t,n){try{return t==="yarn"?await _i(e,n):(await kn(n,".npmrc"),await Cr(B.join(n,".npmrc"),e)),!0}catch(r){return l.error(r instanceof oe?r.message:`Could not safely save registry configuration in ${n}`),!1}}async function Er(e,t){process.platform!=="win32"&&await U.pathExists(e)&&await U.chmod(e,384),await U.writeFile(e,t,{mode:384})}async function _i(e,t){let n=!1;try{let{stdout:r}=await Pe("yarn",["--version"],{cwd:t});n=!r.startsWith("1.")}catch{}n?(await kn(t,".yarnrc.yml"),await Li(e,t)):(await kn(t,".npmrc"),await Cr(B.join(t,".npmrc"),e))}async function Li(e,t){let n=B.join(t,".yarnrc.yml"),r={};if(U.existsSync(n)){let s=await U.readFile(n,"utf8");if(r=Tr.parse(s)??{},typeof r!="object"||Array.isArray(r))throw new oe(`Invalid Yarn configuration: ${n}`)}if(r.npmScopes||(r.npmScopes={}),typeof r.npmScopes!="object"||Array.isArray(r.npmScopes))throw new oe(`Invalid Yarn scopes: ${n}`);let o=r.npmScopes,i=o["tiptap-pro"];if(i!=null&&(typeof i!="object"||Array.isArray(i)))throw new oe(`Invalid Tiptap Yarn scope: ${n}`);o["tiptap-pro"]={...i,npmRegistryServer:Tn,npmAuthToken:e,npmAlwaysAuth:!0},await Er(n,Tr.stringify(r))}async function Cr(e,t){let n="";U.existsSync(e)&&(n=await U.readFile(e,"utf8"));let{lines:r,processedKeys:o}=Ui(n,t);o.has(xt)||r.push(`${xt}=${Tn}`),o.has(Xe)||r.push(`${Xe}=${t}`),r.length>0&&r[r.length-1]!==""&&r.push(""),await Er(e,r.join(`
11
+ `))}function Ui(e,t){let n=[],r=new Set,o=e.split(`
12
+ `);for(let i of o){let s=i.trim();if(!s){n.push(i);continue}if(s.startsWith("#")){n.push(i);continue}let a=i.indexOf("=");if(a!==-1){let c=i.substring(0,a).trim();c===xt?(n.push(`${xt}=${Tn}`),r.add(c)):c===Xe?(n.push(`${Xe}=${t}`),r.add(c)):n.push(i)}else n.push(i)}return{lines:n,processedKeys:r}}async function $r(e,t){try{let n=await Mi(t);if(n)return n;if(e==="npm")return await Bi(t);let r=await Ki();return r||(e==="yarn"?await Wi():null)}catch{return null}}async function Mi(e){let t=B.join(e,".npmrc");if(U.existsSync(t)){let n=await U.readFile(t,"utf8");return Ar(n)}return null}async function Bi(e){let{stdout:t}=await Pe("npm",["config","get",Xe],{cwd:e});return t&&t!=="undefined"?t.trim():null}async function Ki(){let e=B.join(Ir.homedir(),".npmrc");if(U.existsSync(e)){let t=await U.readFile(e,"utf8");return Ar(t)}return null}async function Wi(){let e=B.join(Ir.homedir(),".yarnrc");return U.existsSync(e)?(await U.readFile(e,"utf8")).split(`
13
+ `).map(r=>r.match(/^"\/\/registry\.tiptap\.dev\/:_authToken"\s+"?([^"\s]+)"?/)).find(r=>r!==null)?.[1]??null:null}function Ar(e){let t=e.split(`
14
+ `).filter(r=>r.startsWith("//registry.tiptap.dev/:_authToken="));return t.length===0?null:t[0].split("=")[1]?.trim()||null}import{z as E}from"zod";var Pt=E.enum(["registry:context","registry:extension","registry:hook","registry:icon","registry:lib","registry:node","registry:template","registry:ui-primitive","registry:ui","registry:ui-utils","registry:page","registry:component","registry:style","registry:asset"]),_e=["start","team","growth","enterprise","business"],Vi=["open-source","light"],zi=[..._e,...Vi],Ji=E.array(E.enum(zi)).default([]),Qe=E.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/).refine(e=>e!=="constructor"),ge=E.string().refine(e=>/\.[jt]sx?$/.test(e)&&!e.endsWith(".d.ts")&&!/[\\:#?]/.test(e)&&e.split("/").every(t=>t&&t!=="."&&t!=="..")&&!/\p{Cc}/u.test(e),"Use a relative registry source path to a JavaScript or TypeScript module."),qi=new Set("arguments await break case catch class const continue debugger default delete do else enum eval export extends false finally for function if implements import in instanceof interface let new null package private protected public return static super switch this throw true try typeof var void while with yield".split(" ")),Gi=E.string().regex(/^[A-Za-z_$][\w$]*$/).refine(e=>!qi.has(e),"Use a named module export."),Sn=E.string().trim().min(1).refine(e=>!/\p{Cc}/u.test(e),"Use single-line text."),Rr=E.array(Qe).min(1),et=E.object({id:Qe,label:Sn,description:Sn,instructions:E.array(Sn),docs:E.string().url().regex(/^https:\/\/[^\s\p{Cc}]+$/u),items:Rr,frameworkItems:E.record(Qe,Rr).optional(),integration:E.discriminatedUnion("kind",[E.object({kind:E.literal("files")}),E.object({kind:E.literal("collaboration"),wrapper:ge,config:ge,tokenRoute:ge}),E.object({kind:E.literal("editor-extension"),extension:ge,exportName:Gi})])}),Nr=et.pick({id:!0}),jr=E.object({version:E.literal(1),features:E.array(E.unknown())}),In=E.object({path:E.string(),content:E.string().optional(),type:Pt,target:E.string().optional()}),En=E.object({name:E.string(),type:Pt,description:E.string().optional(),dependencies:E.array(E.string()).optional(),devDependencies:E.array(E.string()).optional(),registryDependencies:E.array(E.string()).optional(),files:E.array(In).optional(),meta:E.object({editor:E.unknown().optional(),featureSupport:E.unknown().optional(),privateNpmPackages:E.array(E.string().min(1)).optional()}).catchall(E.any()).optional(),plans:Ji.optional(),hide:E.boolean().default(!1).optional(),isNew:E.boolean().default(!1).optional()}),bt=En.extend({files:E.array(In.extend({content:E.string()})).optional()}),Nl=E.array(En),Fr=E.array(En.extend({files:E.array(E.union([E.string(),In])).optional()}));import{HttpsProxyAgent as Yi}from"https-proxy-agent";import vt from"node-fetch";import{z as Le}from"zod";var kt="https://template.tiptap.dev";function Ue(){let e=process.env.TIPTAP_REGISTRY_URL||kt,t=URL.canParse(e)?new URL(e):null;if(!t||!["http:","https:"].includes(t.protocol)||t.username||t.password||t.search||t.hash)throw new Error("Set TIPTAP_REGISTRY_URL to an HTTP or HTTPS URL without credentials, a query, or a fragment.");return t.href.replace(/\/+$/,"")}var Tt=process.env.https_proxy?new Yi(process.env.https_proxy):void 0;async function he(){let e=await Dr("index.json");return Fr.parse(e)}async function Me(){let e=`${Ue()}/r/features.json`,t=AbortSignal.timeout(2e3),n;try{let i=await vt(e,{agent:Tt,signal:t});if(i.status===404)return[];if(!i.ok){let s=i.status>=500?"is temporarily unavailable":"request failed";throw new Error(`The registry feature catalog ${s} with HTTP ${i.status}.`)}n=await i.json()}catch(i){throw t.aborted?new Error("The feature catalog request timed out."):i instanceof SyntaxError?new Error("The registry feature catalog contains invalid JSON."):i}let r=jr.safeParse(n);if(!r.success)throw new Error("This CLI cannot read the registry feature catalog. Check its format or update @tiptap/cli.");let o=[];for(let i of r.data.features){let s=et.safeParse(i);if(s.success)o.push(s.data);else{let a=Nr.safeParse(i);a.success&&o.push(a.data)}}return o}function Cn(e,t,n=!1){let r=t?` at ${d.cyan(t)}`:"";switch(e.status){case 400:return new Error(`The registry rejected the request${r}.
15
15
  Please check the selected components and try again.`);case 401:return n&&j.clearSession(),new Error(`You are not authorized to access the component${r}.
16
- Please run ${p.cyan("@tiptap/cli login")} to log in to your Tiptap Cloud account.`);case 404:return new Error(`The component${r} was not found.
16
+ Please run ${d.cyan("@tiptap/cli login")} to log in to your Tiptap Cloud account.`);case 404:return new Error(`The component${r} was not found.
17
17
  It may not exist at the registry. Please make sure it is a valid component.`);case 403:return new Error(`You do not have access to the component${r}.
18
18
  Your account may not have the required subscription plan for this component.
19
19
  Please upgrade your subscription or use a component available in your current plan.`);case 429:return new Error(`Too many registry requests${r}.
20
20
  Please wait a moment and try again.`);default:return e.status>=500?new Error(`The Tiptap registry is temporarily unavailable${r}.
21
21
  Please try again later.`):new Error(`The registry returned an unexpected response${r}.
22
- Please try again.`)}}function Tn(e){let t={"Content-Type":"application/json"};if(new URL(e).origin===Ue){let n=j.getBearerToken();n&&(t.Authorization=`Bearer ${n}`)}return t}async function kn(e){let t=vo(e),n=e==="index.json"?{}:Tn(t),r="Authorization"in n,o=await _t(t,{agent:Ot,headers:n,redirect:r?"error":"follow"});if(!o.ok)throw Dt(o,t,r);return o.json()}function Lt(e,t){let n=new Set(t),r=[...new Set(e)].filter(o=>!n.has(o));if(r.length)throw new Error(`Registry response is missing required items: ${r.join(", ")}`)}async function xo(e){let t=`${be()}/api/registry/components/batch`,n=Tn(t),r=await _t(t,{method:"POST",agent:Ot,headers:n,redirect:n.Authorization?"error":"follow",body:JSON.stringify({components:e})});if(!r.ok)throw Dt(r,t,!!n.Authorization);let o=ue.array(ue.object({name:ue.string()}).passthrough().nullable()).parse(await r.json()).filter(i=>i!==null),s=o.map(i=>i.name);if(Lt(e,s),o.length!==e.length)throw new Error("The registry returned unexpected or duplicate items.");return o}async function Ft(e){let t=e.map(n=>n.replace(/^.*\//,"").replace(/\.json$/,""));if(t.length>1){let r=[...new Set(t)],o=[];for(let s=0;s<r.length;s+=200){let i=await xo(r.slice(s,s+200));o.push(...i)}return o}return Promise.all(e.map(kn))}async function Po(e){let t=`${be()}/api/registry/dependencies`,n=await _t(t,{method:"POST",agent:Ot,headers:{"Content-Type":"application/json"},body:JSON.stringify({components:e})});if(!n.ok)throw Dt(n,t);let r=ue.array(ue.string()).parse(await n.json());return Lt(e,r),r}async function In(e){let t=await Po(e),n=t.map(s=>`components/${encodeURIComponent(s)}.json`),r=ue.array(Fe).parse(await Ft(n)),o=r.map(s=>s.name);return Lt([...t,...r.flatMap(s=>s.registryDependencies??[])],o),r}function vo(e){if(bo(e))return new URL(e).toString();let t=be();if(e==="index.json")return`${t}/r/${e}`;if(e.startsWith("components/")){let n=e.replace("components/","").replace(".json","");return`${t}/api/registry/components/${n}`}return`${t}/${e}`}function bo(e){try{return new URL(e),!0}catch{return!1}}function Sn(e,t){let n=Array.isArray(e)?e:[];if(!n.length)return[];let r=n.map(o=>String(o));if(t){let o=r.includes("sass"),s=r.includes("sass-embedded");if(o||s){let i=[...r],c=[g.astro.name,g.laravel.name,g.vite.name,g["tanstack-start"].name,g["react-router"].name],l=[g["next-app"].name,g["next-pages"].name];return c.includes(t)?i=i.filter(d=>d!=="sass"):l.includes(t)&&(i=i.filter(d=>d!=="sass-embedded")),i}}return r}var Be=`${Ue}/api/cli/v1`,We=process.env.https_proxy?new To(process.env.https_proxy):void 0;async function Cn(e){try{let t=await e.clone().json();if(t&&typeof t=="object"&&"error"in t&&typeof t.error=="string")return t.error;if(t&&typeof t=="object"&&"message"in t&&typeof t.message=="string")return t.message}catch{return null}return null}function ko(e,t){switch(e.status){case 400:return"The authentication request was not accepted. Please check your email and password, then try again.";case 401:return"Invalid email or password. Please check your credentials and try again.";case 403:return"Your account is not allowed to use registry authentication. Please check your Tiptap Cloud account access.";case 429:return"Too many login attempts. Please wait a moment and try again.";default:return t&&e.status>=500?t:e.status>=500?"Tiptap authentication is temporarily unavailable. Please try again later.":"Authentication failed. Please try again."}}function Io(e,t){switch(e.status){case 401:case 403:return"Your login succeeded, but your session could not be verified. Please run tiptap login again.";case 429:return"Your plans could not be loaded because there were too many requests. Please wait a moment and try again.";default:return t&&e.status>=500?t:e.status>=500?"Your plans could not be loaded because Tiptap Cloud is temporarily unavailable. Please try again later.":"Your plans could not be loaded. Please try again."}}async function En({email:e,password:t,packageManager:n,writeConfig:r=!0,cwd:o}){let s=L("Authenticating with Tiptap registry...")?.start();try{if(!e||!t)return s?.fail("Authentication failed"),{success:!1,error:"Invalid credentials"};let i=await So(e,t),c=[],l=await Me(`${Be}/plans`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i.bearerToken}`},agent:We,redirect:"error"});if(!l.ok){s?.fail("Authentication failed (could not load user plans)");let u=await Cn(l);return{success:!1,error:Io(l,u)}}return c=(await l.json()).map(u=>u.name),c.length?(j.setBearerToken(i.bearerToken,{email:e,plans:c}),j.setAuthToken(i.authToken),r&&!await De(i.authToken,n,o)?(s?.fail("Failed to save authentication token"),{success:!1,error:"Could not save authentication token"}):(s?.stopAndPersist({symbol:p.cyan("\u2714"),text:"Authentication successful"}),{success:!0,tokens:i})):(s?.fail("Authentication failed (no active plans)"),{success:!1,error:"No active plans found for user"})}catch(i){return s?.fail("Authentication failed"),{success:!1,error:i instanceof Error?i.message:"Unknown error during authentication"}}}async function So(e,t){let n=await Me(`${Be}/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e,password:t}),agent:We,redirect:"error"});if(!n.ok){let o=await Cn(n);throw new Error(ko(n,o))}let r=await n.json();return{bearerToken:r.token,authToken:r.authToken}}async function Te(){try{let e=j.getBearerToken();if(!e)return{authenticated:!1};if(!j.isValidToken())return{authenticated:!1};let t=[];try{let o=await Me(`${Be}/plans`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},agent:We,redirect:"error"});if(!o.ok)return o.status===401&&j.clearSession(),{authenticated:!1};t=(await o.json()).map(c=>c.name);let i=j.getUserInfo();j.setBearerToken(e,{email:i.email,plans:t})}catch{return{authenticated:!1}}let n=j.getUserInfo(),r=j.getTokenExpiration();return{authenticated:!0,user:n.email||"unknown user",plans:t,expires:r,token:e}}catch(e){return a.error(`Auth status check error: ${e instanceof Error?e.message:"Unknown error"}`),{authenticated:!1}}}async function An(){try{let e=j.getBearerToken();return e&&((await Me(`${Be}/logout`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},agent:We,redirect:"error"})).ok||a.warn("Logout API call failed, but clearing local tokens anyway")),j.clearSession(),{success:!0}}catch(e){return j.clearSession(),{success:!1,error:e instanceof Error?e.message:"Unknown error during logout"}}}import{detect as Co}from"@antfu/ni";import Rn from"fs-extra";import $n from"path";async function Ut(e,{withFallback:t=!0}={}){let r=(await Co({programmatic:!0,cwd:e}))?.split("@")[0];if(r==="yarn"||r==="pnpm"||r==="bun"||r==="npm")return{name:r,source:"project"};if(t){let o=process.env.npm_config_user_agent?.split("/")[0];if(o==="yarn"||o==="pnpm"||o==="bun"||o==="npm")return{name:o,source:"user-agent"}}return{name:"npm",source:"default"}}async function K(e,t){return(await Ut(e,t)).name}function ze(e){let t=Rn.existsSync($n.join(e,"bun.lock")),n=Rn.existsSync($n.join(e,"bunfig.toml"));return!!(t&&n)}import{Command as ke}from"commander";import{execa as Ao}from"execa";import{z as de}from"zod";import{confirm as Ro,input as $o,password as No}from"@inquirer/prompts";import{z as Eo}from"zod";function W(e){if(a.error("Something went wrong. Please check the error below for more details."),a.error("If the problem persists, please open an issue on GitHub."),a.error(""),typeof e=="string"&&(a.error(e),a.break(),process.exit(1)),e instanceof Eo.ZodError){a.error("Validation failed:");for(let[t,n]of Object.entries(e.flatten().fieldErrors))a.error(`- ${p.cyan(t)}: ${n}`);a.break(),process.exit(1)}e instanceof Error&&(a.error(e.message),a.break(),process.exit(1)),a.break(),process.exit(1)}var Nn=de.object({cwd:de.string(),email:de.string().optional(),password:de.string().optional(),writeConfig:de.boolean().optional(),showMessage:de.boolean().default(!0)}),jo=(e,t={})=>$o({message:p.reset(e),required:t.required??!0,validate:t.validate??(n=>n?!0:"This field is required"),theme:{prefix:{done:p.cyan("\u2714"),idle:"?"}}}),_o=(e,t={})=>No({message:p.reset(e),validate:t.validate??(n=>n?!0:"This field is required"),mask:"*",theme:{prefix:{done:p.cyan("\u2714"),idle:"?"}}}),Ie=(e,t=!0)=>Ro({message:p.reset(e),default:t,theme:{prefix:{done:p.cyan("\u2714"),idle:"?"}}});function Oo(e){switch(e){case"npm":return".npmrc";case"yarn":return".yarnrc.yml or .npmrc (depending on Yarn version)";case"pnpm":case"bun":return".npmrc";default:return"configuration file"}}async function Do(e,t){let n="<registry-auth-token>";a.log(`To use this token, add it to your project's package manager configuration in ${p.cyan(t)}:`),e==="npm"?(a.log("Run these commands in your project directory:"),a.log(" npm config set @tiptap-pro:registry https://registry.tiptap.dev/"),a.log(` npm config set //registry.tiptap.dev/:_authToken ${n}`),a.log(`
23
- Or add to your project's .npmrc file:`),a.log(" @tiptap-pro:registry=https://registry.tiptap.dev/"),a.log(` //registry.tiptap.dev/:_authToken=${n}`)):e==="yarn"?await Lo(t)?(a.log("Run these commands in your project directory:"),a.log(" yarn config set @tiptap-pro:registry https://registry.tiptap.dev/"),a.log(` yarn config set //registry.tiptap.dev/:_authToken ${n}`)):(a.log("Add to your project's .yarnrc.yml file:"),a.log(`npmScopes:
22
+ Please try again.`)}}function Or(e){let t={"Content-Type":"application/json"};if(new URL(e).origin===kt){let n=j.getBearerToken();n&&(t.Authorization=`Bearer ${n}`)}return t}async function Dr(e){let t=Zi(e),n=e==="index.json"?{}:Or(t),r="Authorization"in n,o=await vt(t,{agent:Tt,headers:n,redirect:r?"error":"follow"});if(!o.ok)throw Cn(o,t,r);return o.json()}function $n(e,t){let n=new Set(t),r=[...new Set(e)].filter(o=>!n.has(o));if(r.length)throw new Error(`Registry response is missing required items: ${r.join(", ")}`)}async function Hi(e){let t=`${Ue()}/api/registry/components/batch`,n=Or(t),r=await vt(t,{method:"POST",agent:Tt,headers:n,redirect:n.Authorization?"error":"follow",body:JSON.stringify({components:e})});if(!r.ok)throw Cn(r,t,!!n.Authorization);let o=Le.array(Le.object({name:Le.string()}).passthrough().nullable()).parse(await r.json()).filter(s=>s!==null),i=o.map(s=>s.name);if($n(e,i),o.length!==e.length)throw new Error("The registry returned unexpected or duplicate items.");return o}async function An(e){let t=e.map(n=>n.replace(/^.*\//,"").replace(/\.json$/,""));if(t.length>1){let r=[...new Set(t)],o=[];for(let i=0;i<r.length;i+=200){let s=await Hi(r.slice(i,i+200));o.push(...s)}return o}return Promise.all(e.map(Dr))}async function Xi(e){let t=`${Ue()}/api/registry/dependencies`,n=await vt(t,{method:"POST",agent:Tt,headers:{"Content-Type":"application/json"},body:JSON.stringify({components:e})});if(!n.ok)throw Cn(n,t);let r=Le.array(Le.string()).parse(await n.json());return $n(e,r),r}async function _r(e){let t=await Xi(e),n=t.map(i=>`components/${encodeURIComponent(i)}.json`),r=Le.array(bt).parse(await An(n)),o=r.map(i=>i.name);return $n([...t,...r.flatMap(i=>i.registryDependencies??[])],o),r}function Zi(e){if(Qi(e))return new URL(e).toString();let t=Ue();if(e==="index.json")return`${t}/r/${e}`;if(e.startsWith("components/")){let n=e.replace("components/","").replace(".json","");return`${t}/api/registry/components/${n}`}return`${t}/${e}`}function Qi(e){try{return new URL(e),!0}catch{return!1}}function Lr(e,t){let n=Array.isArray(e)?e:[];if(!n.length)return[];let r=n.map(o=>String(o));if(t){let o=r.includes("sass"),i=r.includes("sass-embedded");if(o||i){let s=[...r],a=[T.astro.name,T.laravel.name,T.vite.name,T["tanstack-start"].name,T["react-router"].name],c=[T["next-app"].name,T["next-pages"].name];return a.includes(t)?s=s.filter(p=>p!=="sass"):c.includes(t)&&(s=s.filter(p=>p!=="sass-embedded")),s}}return r}var It=`${kt}/api/cli/v1`,Et=process.env.https_proxy?new es(process.env.https_proxy):void 0;async function Ur(e){try{let t=await e.clone().json();if(t&&typeof t=="object"&&"error"in t&&typeof t.error=="string")return t.error;if(t&&typeof t=="object"&&"message"in t&&typeof t.message=="string")return t.message}catch{return null}return null}function ts(e,t){switch(e.status){case 400:return"The authentication request was not accepted. Please check your email and password, then try again.";case 401:return"Invalid email or password. Please check your credentials and try again.";case 403:return"Your account is not allowed to use registry authentication. Please check your Tiptap Cloud account access.";case 429:return"Too many login attempts. Please wait a moment and try again.";default:return t&&e.status>=500?t:e.status>=500?"Tiptap authentication is temporarily unavailable. Please try again later.":"Authentication failed. Please try again."}}function ns(e,t){switch(e.status){case 401:case 403:return"Your login succeeded, but your session could not be verified. Please run tiptap login again.";case 429:return"Your plans could not be loaded because there were too many requests. Please wait a moment and try again.";default:return t&&e.status>=500?t:e.status>=500?"Your plans could not be loaded because Tiptap Cloud is temporarily unavailable. Please try again later.":"Your plans could not be loaded. Please try again."}}async function Mr({email:e,password:t,packageManager:n,writeConfig:r=!0,registryOnly:o=!1,cwd:i}){let s=K("Authenticating with Tiptap registry...")?.start();try{if(!e||!t)return s?.fail("Authentication failed"),{success:!1,error:"Invalid credentials"};let a=await rs(e,t);if(o){if(j.getBearerToken()&&j.getUserInfo().email!==e&&(j.clearSession(),j.getBearerToken()))throw new Error("Could not clear the previous template login. Check the CLI credential file permissions before switching accounts.")}else{if(!a.bearerToken)throw new Error("Tiptap did not return a valid source login token.");let c=await St(`${It}/plans`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a.bearerToken}`},agent:Et,redirect:"error"});if(!c.ok){s?.fail("Authentication failed (could not load user plans)");let m=await Ur(c);return{success:!1,error:ns(c,m)}}let u=(await c.json()).map(m=>m.name);if(!u.length)return s?.fail("Authentication failed (no active plans)"),{success:!1,error:"No active plans found for user"};j.setBearerToken(a.bearerToken,{email:e,plans:u})}return j.setAuthToken(a.authToken),r&&!await De(a.authToken,n,i)?(s?.fail("Failed to save authentication token"),{success:!1,error:"Could not save authentication token"}):(s?.stopAndPersist({symbol:d.cyan("\u2714"),text:"Authentication successful"}),{success:!0,tokens:a})}catch(a){return s?.fail("Authentication failed"),{success:!1,error:a instanceof Error?a.message:"Unknown error during authentication"}}}async function rs(e,t){let n=await St(`${It}/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e,password:t}),agent:Et,redirect:"error"});if(!n.ok){let o=await Ur(n);throw new Error(ts(n,o))}let r=await n.json();if(typeof r?.authToken!="string"||!r.authToken||/\s/.test(r.authToken))throw new Error("Tiptap did not return a package registry token.");return{bearerToken:typeof r.token=="string"&&!/\s/.test(r.token)?r.token:void 0,authToken:r.authToken}}async function tt(){try{let e=j.getBearerToken();if(!e)return{authenticated:!1};if(!j.isValidToken())return{authenticated:!1};let t=[];try{let o=await St(`${It}/plans`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},agent:Et,redirect:"error"});if(!o.ok)return o.status===401&&j.clearSession(),{authenticated:!1};t=(await o.json()).map(a=>a.name);let s=j.getUserInfo();j.setBearerToken(e,{email:s.email,plans:t})}catch{return{authenticated:!1}}let n=j.getUserInfo(),r=j.getTokenExpiration();return{authenticated:!0,user:n.email||"unknown user",plans:t,expires:r,token:e}}catch(e){return l.error(`Auth status check error: ${e instanceof Error?e.message:"Unknown error"}`),{authenticated:!1}}}async function Br(){try{let e=j.getBearerToken();return e&&((await St(`${It}/logout`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},agent:Et,redirect:"error"})).ok||l.warn("Logout API call failed, but clearing local tokens anyway")),j.clearSession(),{success:!0}}catch(e){return j.clearSession(),{success:!1,error:e instanceof Error?e.message:"Unknown error during logout"}}}import{detect as os}from"@antfu/ni";import Kr from"fs-extra";import Wr from"path";async function Rn(e,{withFallback:t=!0}={}){let r=(await os({programmatic:!0,cwd:e}))?.split("@")[0];if(r==="yarn"||r==="pnpm"||r==="bun"||r==="npm")return{name:r,source:"project"};if(t){let o=process.env.npm_config_user_agent?.split("/")[0];if(o==="yarn"||o==="pnpm"||o==="bun"||o==="npm")return{name:o,source:"user-agent"}}return{name:"npm",source:"default"}}async function q(e,t){return(await Rn(e,t)).name}async function de(e){let t=await q(e);return t==="pnpm"?"pnpm dlx":t==="bun"?"bunx":"npx"}function Ct(e){let t=Kr.existsSync(Wr.join(e,"bun.lock")),n=Kr.existsSync(Wr.join(e,"bunfig.toml"));return!!(t&&n)}import{Command as nt}from"commander";import{execa as ss}from"execa";import{z as be}from"zod";import{confirm as as,input as cs,password as ls}from"@inquirer/prompts";import{z as is}from"zod";function X(e){if(l.error("Something went wrong. Please check the error below for more details."),l.error("If the problem persists, please open an issue on GitHub."),l.error(""),typeof e=="string"&&(l.error(e),l.break(),process.exit(1)),e instanceof is.ZodError){l.error("Validation failed:");for(let[t,n]of Object.entries(e.flatten().fieldErrors))l.error(`- ${d.cyan(t)}: ${n}`);l.break(),process.exit(1)}e instanceof Error&&(l.error(e.message),l.break(),process.exit(1)),l.break(),process.exit(1)}var Vr=be.object({cwd:be.string(),email:be.string().optional(),password:be.string().optional(),writeConfig:be.boolean().optional(),registryOnly:be.boolean().optional(),showMessage:be.boolean().default(!0)}),ps=(e,t={})=>cs({message:d.reset(e),required:t.required??!0,validate:t.validate??(n=>n?!0:"This field is required"),theme:{prefix:{done:d.cyan("\u2714"),idle:"?"}}}),us=(e,t={})=>ls({message:d.reset(e),validate:t.validate??(n=>n?!0:"This field is required"),mask:"*",theme:{prefix:{done:d.cyan("\u2714"),idle:"?"}}}),ve=(e,t=!0)=>as({message:d.reset(e),default:t,theme:{prefix:{done:d.cyan("\u2714"),idle:"?"}}});function ds(e){switch(e){case"npm":return".npmrc";case"yarn":return".yarnrc.yml or .npmrc (depending on Yarn version)";case"pnpm":case"bun":return".npmrc";default:return"configuration file"}}async function ms(e,t){let n="<registry-auth-token>";l.log(`To use this token, add it to your project's package manager configuration in ${d.cyan(t)}:`),e==="npm"?(l.log("Run these commands in your project directory:"),l.log(" npm config set @tiptap-pro:registry https://registry.tiptap.dev/"),l.log(` npm config set //registry.tiptap.dev/:_authToken ${n}`),l.log(`
23
+ Or add to your project's .npmrc file:`),l.log(" @tiptap-pro:registry=https://registry.tiptap.dev/"),l.log(` //registry.tiptap.dev/:_authToken=${n}`)):e==="yarn"?await fs(t)?(l.log("Run these commands in your project directory:"),l.log(" yarn config set @tiptap-pro:registry https://registry.tiptap.dev/"),l.log(` yarn config set //registry.tiptap.dev/:_authToken ${n}`)):(l.log("Add to your project's .yarnrc.yml file:"),l.log(`npmScopes:
24
24
  tiptap-pro:
25
25
  npmRegistryServer: "https://registry.tiptap.dev/"
26
- npmAuthToken: "${n}"`)):(e==="pnpm"||e==="bun")&&(a.log("Add to your project's .npmrc file:"),a.log(p.cyan(`@tiptap-pro:registry=https://registry.tiptap.dev/
27
- //registry.tiptap.dev/:_authToken=${n}`)))}async function Lo(e){try{return(await Ao("yarn",["--version"],{cwd:e})).stdout.startsWith("1.")}catch{return!1}}async function Mt(e){let{email:t,password:n,writeConfig:r,showMessage:o}=e,{cwd:s}=e;n?a.warn("--password is deprecated. Use TIPTAP_CLI_PASSWORD or the masked prompt."):n=process.env.TIPTAP_CLI_PASSWORD,t||(t=await jo("Email:",{validate:l=>l?!0:"Please enter your email"})),n||(n=await _o("Password:",{validate:l=>l?!0:"Please enter your password"})),(!t||!n)&&(a.error("Authentication cancelled"),process.exit(0));let i=await K(s);if(r===void 0){let l=Oo(i);r=await Ie(`Would you like to save the auth token to your ${l}?`),r===void 0&&(a.error("Authentication cancelled"),process.exit(0))}let c=await En({email:t,password:n,packageManager:i,writeConfig:r??!1,cwd:s});if(c.success&&c.tokens)return r&&o?(a.log(`
28
- Registry auth token saved to project directory for ${p.cyan(i)}`),a.log(`.npmrc file saved at: ${p.cyan(s)}`),a.log(`Project path: ${p.cyan(s)}`)):c.tokens.authToken&&o&&(a.log("Registry auth token saved locally. Use login --write-config to configure this project."),await Do(i,s)),o&&a.log("Bearer token saved globally for CLI authentication"),!0;{let l=c.error?.split(n).join("[redacted]");return a.error("Authentication failed: "+l),!1}}async function Fo(e){let t=await K(e),n=await Te();if(n.authenticated){if(a.success(`Authenticated as ${p.cyan(n.user??"unknown user")}`),n.plans&&n.plans.length>0?n.plans.length===1?a.log(`Plan: ${p.cyan(n.plans[0])}`):a.log(`Plans: ${p.cyan(n.plans.join(", "))}`):a.log(`Plans: ${p.cyan("No active plans")}`),n.expires){let o=new Date(n.expires),s=new Date,i=Math.ceil((o.getTime()-s.getTime())/(1e3*60*60*24));i>30?a.log(`Token expires: ${p.cyan(o.toDateString())} (${i} days)`):i>0?a.log(`Token expires: ${p.yellow(o.toDateString())} (${i} days)`):a.log(`Token expires: ${p.red("Expired")}`)}n.token&&a.log("Bearer token: configured"),await Pn(t,e)?a.log("Registry token: configured"):(a.log(`Registry token: ${p.yellow("Not configured for this project")}`),a.log(`Run ${p.cyan("@tiptap/cli login --write-config")} to configure for this project`))}else a.log("Not authenticated with Tiptap registry"),a.log(`Run ${p.cyan("@tiptap/cli login")} to authenticate`)}var jn=new ke().command("login").description("log in to your Tiptap Cloud account").option("-e, --email <email>","your account email").option("-p, --password <password>","deprecated: use TIPTAP_CLI_PASSWORD or the masked prompt").option("--write-config","write the auth token to your package manager config",void 0).option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).action(async e=>{try{let t=Nn.parse(e);await Mt(t)}catch(t){W(t)}}),_n=new ke().command("status").description("review your Tiptap Cloud authentication status").option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).action(async e=>{let t=Nn.parse(e),{cwd:n}=t;try{await Fo(n)}catch(r){W(r)}}),On=new ke().command("logout").description("log out from your Tiptap registry account").action(async()=>{try{let e=L("Logging out...")?.start(),t=await An();t.success?e?.stopAndPersist({symbol:p.cyan("\u2714"),text:"Successfully logged out"}):(e?.fail("Logout failed"),a.error("Logout failed: "+t.error))}catch(e){W(e)}});async function Uo(){a.log(""),a.log(p.yellow("\u{1F4CB} Tiptap Pro License Information")),a.log("");let e=j.hasAcceptedLicense(),t=j.getUserInfo();e?(a.log(`${p.cyan("\u2714")} Pro License and Terms of Service accepted`),t.email&&a.log(` Accepted by: ${p.cyan(t.email)}`),a.log("")):(a.log(p.yellow("\u26A0 Pro License and Terms of Service not yet accepted")),a.log(" License acceptance is required for using paid components"),a.log("")),a.log("License Details:"),a.log(` \u2022 Pro License: ${p.cyan("https://tiptap.dev/pro-license")}`),a.log(` \u2022 Terms of Service: ${p.cyan("https://tiptap.dev/terms-of-service")}`),a.log(""),a.log("About Paid Components:"),a.log(" Some paid UI components or templates are limited to specific plans."),a.log(" The license is valid during your trial period and active subscription."),a.log(""),e&&(a.log(p.gray("Available commands:")),a.log(p.gray(` \u2022 ${p.cyan("tiptap license forget me")} - Reset license acceptance`)),a.log(""))}async function Mo(){if(!j.hasAcceptedLicense()){a.log(p.yellow("\u26A0 License has not been accepted yet"));return}await Ie("Are you sure you want to reset your license acceptance?",!1)?(j.clearLicenseAcceptance(),a.log(`${p.cyan("\u2714")} License acceptance has been reset`),a.log(" You will need to accept the license again when installing paid components")):a.log("License acceptance reset cancelled")}var Dn=new ke().command("license").description("display Tiptap Pro license information and acceptance status").action(async()=>{try{await Uo()}catch(e){W(e)}}).addCommand(new ke().command("forget me").description("reset license acceptance status").action(async()=>{try{await Mo()}catch(e){W(e)}}));function Ln(e){return e.some(t=>t.plans&&t.plans.some(n=>me.includes(n)))}function ae(e){if(Ln(e)){if(!j.getBearerToken())throw new Error("Run pnpm dlx @tiptap/cli login to view paid component source.");if(!j.hasAcceptedLicense())throw new Error("Accept the Pro license during an interactive installation before previewing paid source.")}}async function Bo(e){if(e.filter(n=>n.plans&&n.plans.some(r=>me.includes(r))).length===0)return!0;if(j.hasAcceptedLicense())return a.log(`${p.cyan("\u2714")} Pro license accepted`),!0;a.log(""),a.log(p.yellow("\u{1F4CB} License Agreement")),a.log(""),a.log("Integrating paid components requires accepting:"),a.log(` \u2022 Pro License: ${p.cyan("https://tiptap.dev/pro-license")}`),a.log(` \u2022 Terms of Service: ${p.cyan("https://tiptap.dev/terms-of-service")}`),a.log(""),a.log(p.gray(" Valid during trial and active subscription")),a.log("");try{return await Ie("Do you accept the Pro license and terms of service?",!1)?(j.setLicenseAccepted(),a.log(`${p.cyan("\u2714")} License accepted`),!0):(a.log(p.gray("License not accepted")),a.log(p.gray("Tip: You can still install free components")),!1)}catch{return a.log(p.gray("License acceptance cancelled")),!1}}async function Se(e,t,{interactive:n=!0}={}){try{if(!Ln(e))return!0;let r=await Te();if(!n&&(!r.authenticated||!j.hasAcceptedLicense()))return a.error("Run tiptap login and accept the Pro license before installing paid components with --defaults."),!1;if(r.authenticated){let s=await K(t);if(!await Wo(s,t))return!1}else{if(a.log(""),a.log(p.yellow("\u{1F510} Authentication Required")),a.log(""),a.log("Pro components require authentication."),a.log(`Run ${p.cyan("tiptap login")} or create an account at ${p.cyan("https://cloud.tiptap.dev")}`),a.log(""),!await Ie("Would you like to login now?",!0))return a.log(""),a.log(p.gray("Authentication cancelled")),a.log(p.gray("Tip: You can still install free components")),!1;if(!await Mt({cwd:t,writeConfig:!0,showMessage:!1}))return!1}return!!await Bo(e)}catch(r){return a.error(`Authentication check failed: ${r instanceof Error?r.message:"Unknown error"}`),!1}}async function Wo(e,t){let n=L("Creating registry configuration...")?.start();try{if(!(await Te()).authenticated)return n?.fail("Cannot create configuration - user not authenticated"),!1;let o=j.getAuthToken();return o?await De(o,e,t)?(n?.stopAndPersist({symbol:p.cyan("\u2714"),text:".npmrc created successfully"}),!0):(n?.fail("Failed to save authentication token"),!1):(n?.fail("No authentication token found"),!1)}catch(r){return n?.fail("Failed to create registry configuration"),a.error(`Configuration error: ${r instanceof Error?r.message:"Unknown error"}`),!1}}import{existsSync as ps}from"fs";import{parse as ls}from"postcss";import{parse as ms}from"postcss-scss";import{promises as fe}from"fs";import z from"path";import ce from"path";var Fn={components:"components",contexts:"contexts",hooks:"hooks",lib:"lib",styles:"styles","tiptap-icons":"tiptapIcons","tiptap-extension":"tiptapExtensions","tiptap-node":"tiptapNodes","tiptap-ui":"tiptapUi","tiptap-ui-primitive":"tiptapUiPrimitives","tiptap-ui-utils":"tiptapUiUtils"};function Bt(e){let t=e.replace(/\\/g,"/").replace(/^\/+|\/+$/g,"").replace(/^registry\//,""),[n,...r]=t.split("/");if(Object.hasOwn(Fn,n))return{key:Fn[n],suffix:r.join("/")}}function zo(e,t){let n=e.match(/^tiptap-templates\/([^/]+)\/(.*)$/);if(n)return ce.join(t.resolvedPaths.components,"tiptap-templates",n[1],n[2].replace(/^components\//,""));let r=Bt(e);if(r)return ce.join(t.resolvedPaths[r.key],r.suffix)}async function Un(e,t,n){let r=t.overrideImports;if(!r)return;let o=zo(e,t);if(!o)return;let s=[];for(let[c,l]of Object.entries(r.paths))for(let d of l){let u=ce.resolve(r.absoluteBaseUrl,d),w=u.indexOf("*");if(w<0){u===o&&!c.includes("*")&&s.push({specifier:c,specificity:u.length});continue}let f=u.slice(0,w),h=u.slice(w+1);if(!c.includes("*")||!o.startsWith(f)||!o.endsWith(h))continue;let A=o.slice(f.length,o.length-h.length),v=c.replace("*",A.split(ce.sep).join("/"));Object.hasOwn(r.paths,v)||s.push({specifier:v,specificity:f.length+h.length})}s.sort((c,l)=>l.specificity-c.specificity);for(let{specifier:c}of s)if(await O(c,r)===o)return c;let i=ce.relative(ce.dirname(n),o).split(ce.sep).join("/");return i.startsWith("../")?i:`./${i}`}import{randomUUID as Zo}from"crypto";var Ke=async({sourceFile:e,config:t,packageManager:n,outputFilename:r})=>{let o=e.getImportDeclarations();for(let s of o){let i=s.getModuleSpecifierValue(),l=(t.overrideImports&&r&&i.startsWith("@/registry/")?await Un(i.slice(11),t,r):void 0)??Ko(i,t);ze(t.resolvedPaths.cwd)&&l.endsWith(".scss")&&(l=l.replace(/\.scss$/,".css")),l&&s.setModuleSpecifier(l)}return e};function Ko(e,t){if(!e.startsWith("@/registry/")){let n=t.aliases.components.split("/")[0];return e.replace(/^@\//,`${n}/`)}return e.match(/@\/registry\/tiptap-templates\/([^/]+)\/components\//)?e.replace(/@\/registry\/tiptap-templates\/([^/]+)\/components\//,`${t.aliases.components}/tiptap-templates/$1/`):e.match(/@\/registry\/tiptap-templates\/([^/]+)\/(?!components\/)/)?e.replace(/@\/registry\/tiptap-templates\/([^/]+)\//,`${t.aliases.components}/tiptap-templates/$1/`):t.aliases.components&&e.match(/@\/registry\/components/)?e.replace(/@\/registry\/components/,t.aliases.components):t.aliases.contexts&&e.match(/@\/registry\/contexts/)?e.replace(/@\/registry\/contexts/,t.aliases.contexts):t.aliases.tiptapExtensions&&e.match(/@\/registry\/tiptap-extension/)?e.replace(/@\/registry\/tiptap-extension/,t.aliases.tiptapExtensions):t.aliases.hooks&&e.match(/@\/registry\/hooks/)?e.replace(/@\/registry\/hooks/,t.aliases.hooks):t.aliases.tiptapIcons&&e.match(/@\/registry\/tiptap-icons/)?e.replace(/@\/registry\/tiptap-icons/,t.aliases.tiptapIcons):t.aliases.lib&&e.match(/@\/registry\/lib/)?e.replace(/@\/registry\/lib/,t.aliases.lib):t.aliases.tiptapNodes&&e.match(/@\/registry\/tiptap-node/)?e.replace(/@\/registry\/tiptap-node/,t.aliases.tiptapNodes):t.aliases.tiptapUiPrimitives&&e.match(/@\/registry\/tiptap-ui-primitive/)?e.replace(/@\/registry\/tiptap-ui-primitive/,t.aliases.tiptapUiPrimitives):t.aliases.tiptapUiUtils&&e.match(/@\/registry\/tiptap-ui-utils/)?e.replace(/@\/registry\/tiptap-ui-utils/,t.aliases.tiptapUiUtils):t.aliases.tiptapUi&&e.match(/@\/registry\/tiptap-ui/)?e.replace(/@\/registry\/tiptap-ui/,t.aliases.tiptapUi):t.aliases.styles&&e.match(/@\/registry\/styles/)?e.replace(/@\/registry\/styles/,t.aliases.styles):e.replace(/^@\/registry\/[^/]+(?:\/.*\/)?/,t.aliases.components+"/")}import{transformFromAstSync as Vo}from"@babel/core";import{parse as qo}from"@babel/parser";import Jo from"@babel/plugin-transform-typescript";import*as Ve from"recast";var Go={sourceType:"module",allowImportExportEverywhere:!0,allowReturnOutsideFunction:!0,startLine:1,tokens:!0,plugins:["asyncGenerators","bigInt","classPrivateMethods","classPrivateProperties","classProperties","classStaticBlock","decimal","decorators-legacy","doExpressions","dynamicImport","exportDefaultFrom","exportNamespaceFrom","functionBind","functionSent","importAssertions","importMeta","nullishCoalescingOperator","numericSeparator","objectRestSpread","optionalCatchBinding","optionalChaining",["pipelineOperator",{proposal:"minimal"}],["recordAndTuple",{syntaxType:"hash"}],"throwExpressions","topLevelAwait","v8intrinsic","typescript","jsx"]},Mn=async({sourceFile:e,config:t})=>{let n=e.getFullText();if(t.tsx)return n;let r=Ve.parse(n,{parser:{parse:s=>qo(s,Go)}}),o=Vo(r,n,{cloneInputAst:!1,code:!1,ast:!0,plugins:[Jo],configFile:!1});if(!o||!o.ast)throw new Error("Failed to transform JSX");return Ve.print(o.ast).code};import{SyntaxKind as Bn}from"ts-morph";var qe=async({sourceFile:e,config:t})=>{if(t.rsc)return e;let n=e.getStatements()[0]?.asKind(Bn.ExpressionStatement);return n?.getExpression().asKind(Bn.StringLiteral)?.getLiteralValue()==="use client"&&n.remove(),e};import{Node as Je,SyntaxKind as $}from"ts-morph";var Yo=[{name:"cta",matchType:"contains",caseSensitive:!1,onlyInFiles:["notion-like-editor.tsx"]},{name:"initialContent",matchType:"exact",caseSensitive:!0,onlyInFiles:["notion-like-editor.tsx"]},{name:"JSONContent",matchType:"exact",caseSensitive:!0,onlyInFiles:["notion-like-editor.tsx"]},{name:"onCreate",matchType:"exact",caseSensitive:!0,onlyInFiles:["notion-like-editor.tsx"]},{name:"getDocumentId",matchType:"exact",caseSensitive:!0,onlyInFiles:["notion-like-editor.tsx"]}];function M(e,t,n){return t.some(r=>{if(r.onlyInFiles&&!r.onlyInFiles.some(i=>n.endsWith(i)))return!1;let o=r.caseSensitive?e:e.toLowerCase(),s=r.caseSensitive?r.name:r.name.toLowerCase();switch(r.matchType){case"exact":return o===s;case"contains":return o.includes(s);case"startsWith":return o.startsWith(s);case"endsWith":return o.endsWith(s);case"regex":return r.pattern?new RegExp(r.pattern,r.caseSensitive?"":"i").test(o):!1;default:return!1}})}function Ho(e,t){let n=t.name;return n===g["next-app"].name||n===g["next-pages"].name?`NEXT_PUBLIC_${e}`:n===g.astro.name?`PUBLIC_${e}`:n===g.vite.name||n===g["tanstack-start"].name||n===g["react-router"].name?`VITE_${e}`:(n===g.laravel.name||n===g.manual.name,e)}function Wn(e){return e.replace(/^(NEXT_PUBLIC_|VITE_|PUBLIC_)/,"")}async function Xo(e,t){let n=await U(t.resolvedPaths.cwd);if(!n)return;let r=[],o=e.getDescendantsOfKind($.BinaryExpression);for(let c of o)if(c.getOperatorToken().getKind()===$.BarBarToken){let d=c.getLeft().getText();if(d.match(/^process\.env\.[A-Z_]+$/)){let u=d.match(/process\.env\.([A-Z_]+)/);if(u&&u[1]){let w=Wn(u[1]),f=n.framework.name,h;f===g.astro.name?h=`import.meta.env.PUBLIC_${w}`:f===g.vite.name||f===g["tanstack-start"].name||f===g["react-router"].name?h=`import.meta.env.VITE_${w}`:f===g["next-app"].name||f===g["next-pages"].name?h=`process.env.NEXT_PUBLIC_${w}`:h=`process.env.${w}`;let A=c.getRight().getText(),v=`${h} || ${A}`;r.push({node:c,newText:v})}}}let s=e.getDescendantsOfKind($.CallExpression);for(let c of s){let d=c.getExpression().getText();if(d.match(/^alert$/)){let u=c.getArguments();if(u.length>0){let f=u[0].getText();if(f.includes("TIPTAP_COLLAB_TOKEN")||f.includes("TIPTAP_COLLAB_DOC_PREFIX")||f.includes("TIPTAP_AI_TOKEN")){let h=f,A=["TIPTAP_COLLAB_DOC_PREFIX","TIPTAP_COLLAB_APP_ID","TIPTAP_COLLAB_TOKEN","TIPTAP_AI_APP_ID","TIPTAP_AI_TOKEN","USE_JWT_TOKEN_API_ENDPOINT"];for(let v of A){let b=Ho(v,n.framework);h=h.replace(new RegExp(v,"g"),b)}if(h!==f){let v=`${d}(${h})`;r.push({node:c,newText:v})}}}}}let i=e.getDescendantsOfKind($.PropertyAccessExpression);for(let c of i){let l=c.getText();if(l.match(/^process\.env\.[A-Z_]+$/)){if(c.getParent()?.getKind()===$.BinaryExpression)continue;let u=l.match(/process\.env\.([A-Z_]+)/);if(u&&u[1]){let w=Wn(u[1]),f=n.framework.name,h;f===g.astro.name?h=`import.meta.env.PUBLIC_${w}`:f===g.vite.name||f===g["tanstack-start"].name||f===g["react-router"].name?h=`import.meta.env.VITE_${w}`:f===g["next-app"].name||f===g["next-pages"].name?h=`process.env.NEXT_PUBLIC_${w}`:h=`process.env.${w}`,r.push({node:c,newText:h})}}}for(let{node:c,newText:l}of r)try{c.replaceWithText(l)}catch(d){console.warn(`Skipping transformation of node: ${d}`)}}var Ge=async({sourceFile:e,config:t})=>{let n=Yo,r=e.getFilePath(),o=[],s=e.getImportDeclarations();for(let m of s){let y=m.getModuleSpecifierValue();if(n.some(C=>M(y,[C],r))){o.push({node:m,action:"remove"});continue}let P=m.getDefaultImport();if(P&&M(P.getText(),n,r)){o.push({node:m,action:"remove"});continue}let x=m.getNamedImports(),k=x.filter(C=>M(C.getName(),n,r));k.length>0&&(k.forEach(F=>o.push({node:F,action:"remove"})),x.filter(F=>!k.includes(F)).length===0&&!P&&o.push({node:m,action:"remove"}))}let i=e.getExportDeclarations();for(let m of i){let y=m.getNamedExports(),P=y.filter(x=>M(x.getName(),n,r));P.length>0&&(P.forEach(k=>o.push({node:k,action:"remove"})),y.filter(k=>!P.includes(k)).length===0&&o.push({node:m,action:"remove"}))}let c=e.getVariableStatements();for(let m of c){let y=m.getDeclarations(),P=y.filter(x=>M(x.getName(),n,r));P.length>0&&(y.length===P.length?o.push({node:m,action:"remove"}):P.forEach(x=>o.push({node:x,action:"remove"})))}let l=e.getFunctions();for(let m of l){let y=m.getName();y&&M(y,n,r)&&o.push({node:m,action:"remove"})}let d=e.getInterfaces();for(let m of d){let y=m.getName();M(y,n,r)&&o.push({node:m,action:"remove"})}let u=e.getTypeAliases();for(let m of u){let y=m.getName();M(y,n,r)&&o.push({node:m,action:"remove"})}let w=e.getDescendantsOfKind($.PropertySignature);for(let m of w){let y=m.getName();y&&M(y,n,r)&&o.push({node:m,action:"remove"})}let f=e.getDescendantsOfKind($.JsxElement);for(let m of f){let y=m.getOpeningElement().getTagNameNode().getText();M(y,n,r)&&o.push({node:m,action:"replace",newText:""})}let h=e.getDescendantsOfKind($.JsxSelfClosingElement);for(let m of h){let y=m.getTagNameNode().getText();M(y,n,r)&&o.push({node:m,action:"replace",newText:""})}let A=e.getDescendantsOfKind($.PropertyAssignment);for(let m of A){let y=m.getName();y&&M(y,n,r)&&o.push({node:m,action:"remove"})}let v=e.getDescendantsOfKind($.JsxAttribute);for(let m of v){let y=m.getNameNode().getText();y&&M(y,n,r)&&o.push({node:m,action:"remove"})}let b=e.getDescendantsOfKind($.Parameter);for(let m of b){let y=m.getName();if(y&&M(y,n,r)){let P=m.getParent();if(P&&(Je.isFunctionDeclaration(P)||Je.isArrowFunction(P)||Je.isFunctionExpression(P)||Je.isMethodDeclaration(P))){let x=P.getParameters(),k=x.indexOf(m);if(k!==-1){if(k===x.length-1&&k>0){let C=m.getPreviousSibling();C?.getKind()===$.CommaToken&&o.push({node:C,action:"remove"})}else{let C=m.getNextSibling();C?.getKind()===$.CommaToken&&o.push({node:C,action:"remove"})}o.push({node:m,action:"remove"})}}}}let S=e.getDescendantsOfKind($.CallExpression);for(let m of S){let y=m.getArguments();for(let P=0;P<y.length;P++){let x=y[P],k=x.getText();if(M(k,n,r)){if(P===y.length-1){let C=x.getPreviousSibling();C&&C.getKind()===$.CommaToken&&o.push({node:C,action:"remove"})}else{let C=x.getNextSibling();C&&C.getKind()===$.CommaToken&&o.push({node:C,action:"remove"})}o.push({node:x,action:"remove"})}}}let _=e.getDescendantsOfKind($.BindingElement);for(let m of _){let y=m.getName();if(y&&M(y,n,r)){let P=m.getParent();if(P){let x=P.getDescendantsOfKind($.BindingElement);if(x.indexOf(m)===x.length-1){let C=m.getPreviousSibling();C?.getKind()===$.CommaToken&&o.push({node:C,action:"remove"})}else{let C=m.getNextSibling();C?.getKind()===$.CommaToken&&o.push({node:C,action:"remove"})}}o.push({node:m,action:"remove"})}}let T=e.getDescendantsOfKind($.Identifier);for(let m of T){let y=m.getText();if(M(y,n,r)){let P=m.getParent();if(P){let x=P.getKind();if(x===$.CallExpression){let k=P;k.getExpression()===m?o.push({node:k,action:"remove"}):k.getArguments().findIndex(re=>re===m)!==-1&&o.push({node:m,action:"remove"})}if(x===$.PropertyAccessExpression){let k=P;k.getName()===y&&o.push({node:k,action:"remove"})}if((x===$.VariableDeclaration||x===$.BinaryExpression||x===$.IfStatement||x===$.ConditionalExpression)&&o.push({node:m,action:"remove"}),x===$.PropertyAssignment){let k=P;k.getInitializer()===m&&o.push({node:k,action:"remove"})}}}}let E=e.getDescendantsOfKind($.ShorthandPropertyAssignment);for(let m of E){let y=m.getName();y&&M(y,n,r)&&o.push({node:m,action:"remove"})}await Xo(e,t),o.sort((m,y)=>{let P=m.node.getStart?.()??0;return(y.node.getStart?.()??0)-P});for(let{node:m,action:y,newText:P}of o)try{if(m.wasForgotten?.()===!0)continue;y==="remove"?typeof m.remove=="function"&&m.remove():y==="replace"&&P!==void 0&&m.replaceWithText(P)}catch{}return e};import{posix as Ye}from"path";function zn(e){let t=new Map;for(let n of e??[])n.path.endsWith(".scss")&&n.content!==void 0&&t.set(new URL(n.path,"registry:/").href,n.content);return{canonicalize(n,{containingUrl:r}){let o=new URL(n,r??"registry:/");if(o.protocol!=="registry:")return null;let s=o.pathname.endsWith(".scss")?[o.pathname]:[o.pathname+".scss",Ye.join(o.pathname,"index.scss")];for(let i of s){let c=Ye.join(Ye.dirname(i),"_"+Ye.basename(i)),l=[i,c].map(d=>new URL(d,o)).filter(d=>t.has(d.href));if(l.length>1)throw new Error(`Ambiguous Sass import: ${n}`);if(l.length===1)return l[0]}return null},load(n){let r=t.get(n.href);return r===void 0?null:{contents:r,syntax:"scss"}}}}async function Kn(e,t,n){try{let{compileString:r}=await import("./sass.cjs");return r(e,{url:new URL(t,"registry:/"),importers:[n],style:"expanded"}).css}catch(r){throw new Error(`Failed to compile SCSS to CSS: ${r instanceof Error?r.message:String(r)}`)}}import{Project as Qo,ScriptKind as es}from"ts-morph";var ts=new Qo({useInMemoryFileSystem:!0});async function Vn(e,t=[Ke,qe,Ge]){if(e.filename.endsWith(".scss")&&e.sassImporter)return await Kn(e.raw,e.filename,e.sassImporter);if(!/\.(?:[cm]?[jt]s|[jt]sx)$/i.test(e.filename))return e.raw;let n=ts.createSourceFile(`/${Zo()}/${e.filename}`,e.raw,{scriptKind:es.TSX});try{for(let r of t)await r({sourceFile:n,...e});return e.transformJsx?await Mn({sourceFile:n,...e}):n.getText()}finally{n.forget()}}import{confirm as ns}from"@inquirer/prompts";var rs="scss.d.ts",os=`declare module "*.scss";
29
- `;async function Xe(e){try{await fe.lstat(e)}catch(t){let n=z.dirname(e);if(t.code!=="ENOENT"||n===e)throw t;let r=await Xe(n);return z.join(r,z.basename(e))}return fe.realpath(e)}function He(e,t){let n=z.relative(e,t);return n!==""&&n!==".."&&!n.startsWith(`..${z.sep}`)&&!z.isAbsolute(n)}async function Ze(e,t){let{cwd:n,...r}=t.resolvedPaths,o=He(n,e)?n:Object.values(r).find(s=>!He(n,s)&&He(s,e));if(o){let[s,i]=await Promise.all([Xe(o),Xe(e)]);if(He(s,i))return i}throw new Error(`File destination is outside the configured install directories: ${e}`)}async function Ce(e){try{return await fe.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return null;throw t}}async function Yn(e,t){let n=t.resolvedPaths.cwd,[r,o]=await Promise.all([U(n),K(n)]),s=ze(n),i=s?zn(e):void 0,c=[];for(let l of e??[]){if(l.content===void 0)continue;let d=cs(l,t,{isSrcDir:l.type==="registry:page"&&r?.nextAppDir?r.nextAppDir==="src/app":r?.isSrcDir,framework:r?.framework.name});if(d){t.tsx||(d=d.replace(/\.ts(x?)$/,".js$1")),s&&(d=d.replace(/\.scss$/,".css"));try{let u=await Ze(d,t),w=await Ce(u),f=await Vn({filename:l.path,outputFilename:d,raw:l.content,sassImporter:i,config:t,transformJsx:!t.tsx,packageManager:o},[Ke,qe,Ge]),h=w===null?"create":await Gn(w)===await Gn(f)?"identical":"conflict";c.push({path:d,realPath:u,before:w,after:f,status:h})}catch(u){throw new Error(`Could not prepare ${d}: ${u instanceof Error?u.message:u}`)}}}if(c.some(l=>l.path.endsWith(".scss"))){let l=z.join(n,r?.isSrcDir?"src":"",rs),d=await Ze(l,t);await Ce(d)===null&&c.push({path:l,realPath:d,before:null,after:os,status:"create"})}return c}async function qn(e){if(await Xe(e.path)!==e.realPath)throw new Error(`The destination of ${e.path} changed. Run add again to review it.`)}async function Jn(e){try{if((await fe.stat(e)).isFile())return}catch(t){if(t.code!=="ENOENT")throw t}throw new Error(`Missing file ${e}. Run add again to restore it.`)}async function Hn(e,t,n){let r={filesCreated:[],filesUpdated:[],filesSkipped:[],errors:[]},o=new Map(e.map(s=>[s.path,s]));for(let s of e){if(s.status==="update"&&r.errors.length)continue;let i=z.relative(t,s.path);try{let c=s.status==="conflict"&&!n.overwrite&&(!(n.interactive??process.stdin.isTTY)||!await ns({message:`Overwrite ${i}?`,default:!1}));if(await qn(s),c){await Jn(s.realPath),r.filesSkipped.push(i);continue}if(s.before!==null&&await Ce(s.realPath)!==s.before)throw new Error("The file changed during installation. Run add again to review it.");if(s.status==="identical"){r.filesSkipped.push(i);continue}for(let l of s.requiredFiles??[]){let d=o.get(l);if(!d)throw new Error(`Missing stylesheet in install plan: ${l}`);await qn(d),await Jn(d.realPath)}await fe.mkdir(z.dirname(s.realPath),{recursive:!0}),await fe.writeFile(s.realPath,s.after,{encoding:"utf8",flag:s.before===null?"wx":"w"}),s.before===null?r.filesCreated.push(i):r.filesUpdated.push(i)}catch(c){r.errors.push({file:i,error:c instanceof Error?c.message:String(c)})}}return r}function ss(e,t,n){return n||(e.type==="registry:ui"?t.resolvedPaths.tiptapUi:e.type==="registry:ui-primitive"?t.resolvedPaths.tiptapUiPrimitives:e.type==="registry:ui-utils"?t.resolvedPaths.tiptapUiUtils:e.type==="registry:extension"?t.resolvedPaths.tiptapExtensions:e.type==="registry:node"?t.resolvedPaths.tiptapNodes:e.type==="registry:icon"?t.resolvedPaths.tiptapIcons:e.type==="registry:hook"?t.resolvedPaths.hooks:e.type==="registry:lib"?t.resolvedPaths.lib:e.type==="registry:context"?t.resolvedPaths.contexts:e.type==="registry:template"||e.type==="registry:component"?t.resolvedPaths.components:e.type==="registry:style"?t.resolvedPaths.styles:t.resolvedPaths.components)}async function Gn(e){return e.replace(/\r\n/g,`
30
- `).trim()}function is(e,t){if(!t)return"";if(t==="next-app")return e;if(t==="next-pages"){let n=e.replace(/^app\//,"pages/");return n=n.replace(/\/page(\.[jt]sx?)$/,"$1"),n}if(t==="react-router"){let n=e.replace(/^app\//,"app/routes/");return n=n.replace(/\/page(\.[jt]sx?)$/,"$1"),n}if(t==="laravel"){let n=e.replace(/^app\//,"resources/js/pages/");return n=n.replace(/\/page(\.[jt]sx?)$/,"$1"),n}return""}function as(e,t){let n=Bt(e);if(n)return n.suffix;let r=e.replace(/^\/|\/$/g,""),o=t.replace(/^\/|\/$/g,""),s=r.split("/"),i=o.split("/"),c=i[i.length-1],l=s.findIndex(d=>d===c);return l===-1?s[s.length-1]:s.slice(l+1).join("/")}function cs(e,t,n){if(!e.target&&e.path.includes("tiptap-templates/")&&e.type!=="registry:page"){let s=e.path.match(/tiptap-templates\/([^/]+)\/(.*)/);if(s){let[,i,c]=s;if(c.startsWith("components/")){let l=c.replace("components/","");return z.join(t.resolvedPaths.components,"tiptap-templates",i,l)}return z.join(t.resolvedPaths.components,"tiptap-templates",i,c)}}if(e.target&&e.path.includes("tiptap-templates/")&&e.target.includes("/data/")){let s=e.path.match(/tiptap-templates\/([^/]+)\//);if(s){let i=s[1],c=e.target.split("/data/")[1];return z.join(t.resolvedPaths.components,"tiptap-templates",i,"data",c)}}if(e.target){if(e.target.startsWith("~/"))return z.join(t.resolvedPaths.cwd,e.target.replace("~/",""));let s=e.target;return e.type==="registry:page"&&(s=is(s,n.framework),!s)?"":n.isSrcDir?z.join(t.resolvedPaths.cwd,"src",s.replace("src/","")):z.join(t.resolvedPaths.cwd,s.replace("src/",""))}let r=ss(e,t),o=as(e.path,r);return z.join(r,o)}import D from"path";function Wt(e,t){let n=e.name,r=t.resolvedPaths.cwd,o=t.resolvedPaths.components?.includes("/src/"),s=t.resolvedPaths.styles?.includes("/src/"),i=[];switch(n){case g["next-app"].name:{let c=wt(r)??"app";i=["globals.css","globals.scss"].map(l=>D.join(r,c,l));break}case g["next-pages"].name:i=(o?["src/styles","styles"]:["styles","src/styles"]).flatMap(c=>["globals.css","globals.scss"].map(l=>D.join(r,c,l)));break;case g.vite.name:case g["react-router"].name:case g["tanstack-start"].name:i=[D.join(r,"src/index.css"),D.join(r,"src/main.css"),D.join(r,"src/App.css")];break;case g.astro.name:i=[D.join(r,"src/styles/main.css"),D.join(r,"src/styles/global.css")];break;case g.laravel.name:i=[D.join(r,"resources/css/app.css")];break;case g.manual.name:default:o||s?i=[D.join(r,"src/index.css"),D.join(r,"src/main.css"),D.join(r,"src/App.css"),D.join(r,"src/styles/main.css")]:i=[D.join(r,"index.css"),D.join(r,"main.css"),D.join(r,"styles/main.css")];break}for(let c of i)if(ps(c))return c;return i[0]||null}async function Xn(e,t,n){let r=new Set(e),o=[...r].filter(T=>{let E=D.basename(T);if(!/^_(variables|keyframe-animations)\.(scss|css)$/.test(E))return!1;let m=D.join(t.resolvedPaths.styles,E);return T===m||!r.has(m)});if(!o.length)return{result:{success:!0,message:"No style files to import"}};let s=n&&Wt(n,t);if(!s)return{result:{success:!1,message:"Could not determine main CSS file location"}};let i=await Ze(s,t),c=await Ce(i);if(c===null)return{result:{success:!1,message:`Main CSS file not found at ${s}`}};let l=s.endsWith(".scss"),d;try{d=(l?ms:ls)(c,{from:s})}catch(T){return{result:{success:!1,message:`Could not read style imports in ${s}: ${T instanceof Error?T.message:T}`}}}let u=new Set,w=c.startsWith("\uFEFF")?1:0,f=w;for(let T of d.nodes){if(T.type!=="atrule")continue;let E=T.name.toLowerCase();if((E==="charset"||l&&(E==="use"||E==="forward"))&&(f=w+T.source.end.offset),E==="import"){let m=T.params.match(/^(?:(["'])(.+?)\1|url\(\s*(?:(["'])(.+?)\3|([^"'()\s]+))\s*\))(?:\s+layer(?:\([^()]+\))?)?(?:\s+all)?$/i);m&&u.add(m[2]??m[4]??m[5])}}let h=[];for(let T of o){let E=D.relative(D.dirname(s),T).split(D.sep).join("/"),m=E.startsWith(".")?E:"./"+E,y=t.aliases.styles&&`${t.aliases.styles}/${D.basename(T)}`,P=y&&u.has(y)?t.overrideImports?await O(y,t.overrideImports):D.join(t.resolvedPaths.styles,D.basename(T)):void 0;!u.has(m)&&!u.has(E)&&P!==T&&h.push(`@import '${m}';`)}if(!h.length)return{result:{success:!0,message:"Style imports already exist",filePath:s}};let A=c.includes(`\r
26
+ npmAuthToken: "${n}"`)):(e==="pnpm"||e==="bun")&&(l.log("Add to your project's .npmrc file:"),l.log(d.cyan(`@tiptap-pro:registry=https://registry.tiptap.dev/
27
+ //registry.tiptap.dev/:_authToken=${n}`)))}async function fs(e){try{return(await ss("yarn",["--version"],{cwd:e})).stdout.startsWith("1.")}catch{return!1}}async function rt(e){let{email:t,password:n,writeConfig:r,showMessage:o}=e,i=await q(e.cwd),s=e.registryOnly?await Ze(e.cwd,i):e.cwd;if(n?l.warn("--password is deprecated. Use TIPTAP_CLI_PASSWORD or the masked prompt."):n=process.env.TIPTAP_CLI_PASSWORD,t||(t=await ps("Email:",{validate:c=>c?!0:"Please enter your email"})),n||(n=await us("Password:",{validate:c=>c?!0:"Please enter your password"})),!t||!n){if(e.registryOnly)return!1;l.error("Authentication cancelled"),process.exit(0)}if(r===void 0){let c=ds(i);r=await ve(`Would you like to save the auth token to your ${c}?`),r===void 0&&(l.error("Authentication cancelled"),process.exit(0))}let a=await Mr({email:t,password:n,packageManager:i,writeConfig:r??!1,registryOnly:e.registryOnly,cwd:s});if(a.success&&a.tokens)return r&&o?(l.log(`
28
+ Registry auth token saved to project directory for ${d.cyan(i)}`),l.log(`Project directory: ${d.cyan(s)}`)):a.tokens.authToken&&o&&(l.log("Registry auth token saved locally. Use login --write-config to configure this project."),await ms(i,s)),o&&!e.registryOnly&&l.log("Bearer token saved globally for CLI authentication"),!0;{let c=a.error?.split(n).join("[redacted]");return l.error("Authentication failed: "+c),!1}}async function gs(e){let t=await q(e),n=await tt();if(n.authenticated){if(l.success(`Authenticated as ${d.cyan(n.user??"unknown user")}`),n.plans&&n.plans.length>0?n.plans.length===1?l.log(`Plan: ${d.cyan(n.plans[0])}`):l.log(`Plans: ${d.cyan(n.plans.join(", "))}`):l.log(`Plans: ${d.cyan("No active plans")}`),n.expires){let o=new Date(n.expires),i=new Date,s=Math.ceil((o.getTime()-i.getTime())/(1e3*60*60*24));s>30?l.log(`Token expires: ${d.cyan(o.toDateString())} (${s} days)`):s>0?l.log(`Token expires: ${d.yellow(o.toDateString())} (${s} days)`):l.log(`Token expires: ${d.red("Expired")}`)}n.token&&l.log("Bearer token: configured"),await $r(t,e)?l.log("Registry token: configured"):(l.log(`Registry token: ${d.yellow("Not configured for this project")}`),l.log(`Run ${d.cyan("@tiptap/cli login --write-config")} to configure for this project`))}else j.getAuthToken()?l.log("Package registry token available for downloads."):(l.log("Not authenticated with Tiptap registry"),l.log(`Run ${d.cyan("@tiptap/cli login")} to authenticate`))}var zr=new nt().command("login").description("log in to your Tiptap Cloud account").option("--registry-only","authenticate package downloads").option("-e, --email <email>","your account email").option("-p, --password <password>","deprecated: use TIPTAP_CLI_PASSWORD or the masked prompt").option("--write-config","write the auth token to your package manager config",void 0).option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).action(async e=>{try{let t=Vr.parse(e);await rt(t)||(process.exitCode=1)}catch(t){X(t)}}),Jr=new nt().command("status").description("review your Tiptap Cloud authentication status").option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).action(async e=>{let t=Vr.parse(e),{cwd:n}=t;try{await gs(n)}catch(r){X(r)}}),qr=new nt().command("logout").description("log out from your Tiptap registry account").action(async()=>{try{let e=K("Logging out...")?.start(),t=await Br();t.success?e?.stopAndPersist({symbol:d.cyan("\u2714"),text:"Successfully logged out"}):(e?.fail("Logout failed"),l.error("Logout failed: "+t.error))}catch(e){X(e)}});async function hs(){l.log(""),l.log(d.yellow("\u{1F4CB} Tiptap Pro License Information")),l.log("");let e=j.hasAcceptedLicense(),t=j.getUserInfo();e?(l.log(`${d.cyan("\u2714")} Pro License and Terms of Service accepted`),t.email&&l.log(` Accepted by: ${d.cyan(t.email)}`),l.log("")):(l.log(d.yellow("\u26A0 Pro License and Terms of Service not yet accepted")),l.log(" License acceptance is required for using paid components"),l.log("")),l.log("License Details:"),l.log(` \u2022 Pro License: ${d.cyan("https://tiptap.dev/pro-license")}`),l.log(` \u2022 Terms of Service: ${d.cyan("https://tiptap.dev/terms-of-service")}`),l.log(""),l.log("About Paid Components:"),l.log(" Some paid UI components or templates are limited to specific plans."),l.log(" The license is valid during your trial period and active subscription."),l.log(""),e&&(l.log(d.gray("Available commands:")),l.log(d.gray(` \u2022 ${d.cyan("tiptap license forget me")} - Reset license acceptance`)),l.log(""))}async function ys(){if(!j.hasAcceptedLicense()){l.log(d.yellow("\u26A0 License has not been accepted yet"));return}await ve("Are you sure you want to reset your license acceptance?",!1)?(j.clearLicenseAcceptance(),l.log(`${d.cyan("\u2714")} License acceptance has been reset`),l.log(" You will need to accept the license again when installing paid components")):l.log("License acceptance reset cancelled")}var Gr=new nt().command("license").description("display Tiptap Pro license information and acceptance status").action(async()=>{try{await hs()}catch(e){X(e)}}).addCommand(new nt().command("forget me").description("reset license acceptance status").action(async()=>{try{await ys()}catch(e){X(e)}}));function ke(e){return e.some(t=>t.plans&&t.plans.some(n=>_e.includes(n)))}function Te(e){if(ke(e)){if(!j.getBearerToken())throw new Error("Run pnpm dlx @tiptap/cli login to view paid component source.");if(!j.hasAcceptedLicense())throw new Error("Accept the Pro license during an interactive installation before previewing paid source.")}}async function ws(e){if(e.filter(n=>n.plans&&n.plans.some(r=>_e.includes(r))).length===0)return!0;if(j.hasAcceptedLicense())return l.log(`${d.cyan("\u2714")} Pro license accepted`),!0;l.log(""),l.log(d.yellow("\u{1F4CB} License Agreement")),l.log(""),l.log("Integrating paid components requires accepting:"),l.log(` \u2022 Pro License: ${d.cyan("https://tiptap.dev/pro-license")}`),l.log(` \u2022 Terms of Service: ${d.cyan("https://tiptap.dev/terms-of-service")}`),l.log(""),l.log(d.gray(" Valid during trial and active subscription")),l.log("");try{return await ve("Do you accept the Pro license and terms of service?",!1)?(j.setLicenseAccepted(),l.log(`${d.cyan("\u2714")} License accepted`),!0):(l.log(d.gray("License not accepted")),l.log(d.gray("Tip: You can still install free components")),!1)}catch{return l.log(d.gray("License acceptance cancelled")),!1}}async function $t(e,t,{interactive:n=!0}={}){try{if(!ke(e))return!0;let r=await tt();if(!n&&(!r.authenticated||!j.hasAcceptedLicense()))return l.error("Run tiptap login and accept the Pro license before installing paid components."),!1;if(r.authenticated){let i=await q(t);if(!await xs(i,t))return!1}else{if(l.log(""),l.log(d.yellow("\u{1F510} Authentication Required")),l.log(""),l.log("Pro components require authentication."),l.log(`Run ${d.cyan("tiptap login")} or create an account at ${d.cyan("https://cloud.tiptap.dev")}`),l.log(""),!await ve("Would you like to login now?",!0))return l.log(""),l.log(d.gray("Authentication cancelled")),l.log(d.gray("Tip: You can still install free components")),!1;if(!await rt({cwd:t,writeConfig:!0,showMessage:!1}))return!1}return!!await ws(e)}catch(r){return l.error(`Authentication check failed: ${r instanceof Error?r.message:"Unknown error"}`),!1}}async function xs(e,t){let n=K("Creating registry configuration...")?.start();try{if(!(await tt()).authenticated)return n?.fail("Cannot create configuration - user not authenticated"),!1;let o=j.getAuthToken();return o?await De(o,e,t)?(n?.stopAndPersist({symbol:d.cyan("\u2714"),text:".npmrc created successfully"}),!0):(n?.fail("Failed to save authentication token"),!1):(n?.fail("No authentication token found"),!1)}catch(r){return n?.fail("Failed to create registry configuration"),l.error(`Configuration error: ${r instanceof Error?r.message:"Unknown error"}`),!1}}import Se from"process";function Yr(){return Se.stdout.columns||80}function se(){return!!(Se.stdin.isTTY&&Se.stdout.isTTY&&!Se.env.CI)}function Hr(e,t,n){let r=n?.borderColor||"gray",o=n?.padding!==!1,i="",s="",a="",c="",p="-",u="",m=Yr(),g=Math.min(m-4,80),f=d[r],y=f(i+p.repeat(g-2)+s),S=f(a+p.repeat(g-2)+c),P=f(u),v=[];o&&v.push(""),v.push(y),v.push(`${P}${" ".repeat(g-2)}${P}`);let A=Math.floor((g-4-Nn(e).length)/2),w=e.padStart(A+Nn(e).length).padEnd(g-4);return v.push(`${P} ${w} ${P}`),v.push(`${P}${" ".repeat(g-2)}${P}`),t.forEach(k=>{let C=Nn(k).length,h=g-4-C,x=k+" ".repeat(Math.max(0,h));v.push(`${P} ${x} ${P}`)}),t.length>0&&v.push(`${P}${" ".repeat(g-2)}${P}`),v.push(S),o&&v.push(""),v}function At(e,t){let n=t?[t]:[];return Hr(`${e}`,n,{borderColor:"gray"})}function Rt(e,t){return Hr(`\u26A0\uFE0F ${e}`,t,{borderColor:"yellow"})}function ye(e){e.forEach(t=>l.log(t))}function Nn(e){return e.replace(/\x1b\[[0-9;]*m/g,"")}function Nt(){Se.stdout.write("\x1B[2J\x1B[0f"),Se.platform==="win32"&&Se.stdout.write("\x1B[2J\x1B[3J\x1B[H")}function jn(){let e=Math.min(Yr()-4,80);return d.gray("-".repeat(e))}import{existsSync as Bs}from"fs";import{parse as Ks}from"postcss";import{parse as Ws}from"postcss-scss";import{promises as Be}from"fs";import G from"path";import Ie from"path";var Xr={components:"components",contexts:"contexts",hooks:"hooks",lib:"lib",styles:"styles","tiptap-icons":"tiptapIcons","tiptap-extension":"tiptapExtensions","tiptap-node":"tiptapNodes","tiptap-ui":"tiptapUi","tiptap-ui-primitive":"tiptapUiPrimitives","tiptap-ui-utils":"tiptapUiUtils"};function Fn(e){let t=e.replace(/\\/g,"/").replace(/^\/+|\/+$/g,"").replace(/^registry\//,""),[n,...r]=t.split("/");if(Object.hasOwn(Xr,n))return{key:Xr[n],suffix:r.join("/")}}function Ps(e,t){let n=e.match(/^tiptap-templates\/([^/]+)\/(.*)$/);if(n)return Ie.join(t.resolvedPaths.components,"tiptap-templates",n[1],n[2].replace(/^components\//,""));let r=Fn(e);if(r)return Ie.join(t.resolvedPaths[r.key],r.suffix)}async function jt(e,t,n){let r=t.overrideImports;if(!r)return;let o=Ps(e,t);if(!o)return;let i=[];for(let[a,c]of Object.entries(r.paths))for(let p of c){let u=Ie.resolve(r.absoluteBaseUrl,p),m=u.indexOf("*");if(m<0){u===o&&!a.includes("*")&&i.push({specifier:a,specificity:u.length});continue}let g=u.slice(0,m),f=u.slice(m+1);if(!a.includes("*")||!o.startsWith(g)||!o.endsWith(f))continue;let y=o.slice(g.length,o.length-f.length),S=a.replace("*",y.split(Ie.sep).join("/"));Object.hasOwn(r.paths,S)||i.push({specifier:S,specificity:g.length+f.length})}i.sort((a,c)=>c.specificity-a.specificity);for(let{specifier:a}of i)if(await D(a,r)===o)return a;let s=Ie.relative(Ie.dirname(n),o).split(Ie.sep).join("/");return s.startsWith("../")?s:`./${s}`}import{randomUUID as $s}from"crypto";var ot=async({sourceFile:e,config:t,packageManager:n,outputFilename:r})=>{let o=e.getImportDeclarations();for(let i of o){let s=i.getModuleSpecifierValue(),c=(t.overrideImports&&r&&s.startsWith("@/registry/")?await jt(s.slice(11),t,r):void 0)??bs(s,t);Ct(t.resolvedPaths.cwd)&&c.endsWith(".scss")&&(c=c.replace(/\.scss$/,".css")),c&&i.setModuleSpecifier(c)}return e};function bs(e,t){if(!e.startsWith("@/registry/")){let n=t.aliases.components.split("/")[0];return e.replace(/^@\//,`${n}/`)}return e.match(/@\/registry\/tiptap-templates\/([^/]+)\/components\//)?e.replace(/@\/registry\/tiptap-templates\/([^/]+)\/components\//,`${t.aliases.components}/tiptap-templates/$1/`):e.match(/@\/registry\/tiptap-templates\/([^/]+)\/(?!components\/)/)?e.replace(/@\/registry\/tiptap-templates\/([^/]+)\//,`${t.aliases.components}/tiptap-templates/$1/`):t.aliases.components&&e.match(/@\/registry\/components/)?e.replace(/@\/registry\/components/,t.aliases.components):t.aliases.contexts&&e.match(/@\/registry\/contexts/)?e.replace(/@\/registry\/contexts/,t.aliases.contexts):t.aliases.tiptapExtensions&&e.match(/@\/registry\/tiptap-extension/)?e.replace(/@\/registry\/tiptap-extension/,t.aliases.tiptapExtensions):t.aliases.hooks&&e.match(/@\/registry\/hooks/)?e.replace(/@\/registry\/hooks/,t.aliases.hooks):t.aliases.tiptapIcons&&e.match(/@\/registry\/tiptap-icons/)?e.replace(/@\/registry\/tiptap-icons/,t.aliases.tiptapIcons):t.aliases.lib&&e.match(/@\/registry\/lib/)?e.replace(/@\/registry\/lib/,t.aliases.lib):t.aliases.tiptapNodes&&e.match(/@\/registry\/tiptap-node/)?e.replace(/@\/registry\/tiptap-node/,t.aliases.tiptapNodes):t.aliases.tiptapUiPrimitives&&e.match(/@\/registry\/tiptap-ui-primitive/)?e.replace(/@\/registry\/tiptap-ui-primitive/,t.aliases.tiptapUiPrimitives):t.aliases.tiptapUiUtils&&e.match(/@\/registry\/tiptap-ui-utils/)?e.replace(/@\/registry\/tiptap-ui-utils/,t.aliases.tiptapUiUtils):t.aliases.tiptapUi&&e.match(/@\/registry\/tiptap-ui/)?e.replace(/@\/registry\/tiptap-ui/,t.aliases.tiptapUi):t.aliases.styles&&e.match(/@\/registry\/styles/)?e.replace(/@\/registry\/styles/,t.aliases.styles):e.replace(/^@\/registry\/[^/]+(?:\/.*\/)?/,t.aliases.components+"/")}import{transformFromAstSync as vs}from"@babel/core";import{parse as ks}from"@babel/parser";import Ts from"@babel/plugin-transform-typescript";import*as Ft from"recast";var Ss={sourceType:"module",allowImportExportEverywhere:!0,allowReturnOutsideFunction:!0,startLine:1,tokens:!0,plugins:["asyncGenerators","bigInt","classPrivateMethods","classPrivateProperties","classProperties","classStaticBlock","decimal","decorators-legacy","doExpressions","dynamicImport","exportDefaultFrom","exportNamespaceFrom","functionBind","functionSent","importAssertions","importMeta","nullishCoalescingOperator","numericSeparator","objectRestSpread","optionalCatchBinding","optionalChaining",["pipelineOperator",{proposal:"minimal"}],["recordAndTuple",{syntaxType:"hash"}],"throwExpressions","topLevelAwait","v8intrinsic","typescript","jsx"]},Zr=async({sourceFile:e,config:t})=>{let n=e.getFullText();if(t.tsx)return n;let r=Ft.parse(n,{parser:{parse:i=>ks(i,Ss)}}),o=vs(r,n,{cloneInputAst:!1,code:!1,ast:!0,plugins:[Ts],configFile:!1});if(!o||!o.ast)throw new Error("Failed to transform JSX");return Ft.print(o.ast).code};import{SyntaxKind as Qr}from"ts-morph";var Ot=async({sourceFile:e,config:t})=>{if(t.rsc)return e;let n=e.getStatements()[0]?.asKind(Qr.ExpressionStatement);return n?.getExpression().asKind(Qr.StringLiteral)?.getLiteralValue()==="use client"&&n.remove(),e};import{Node as Dt,SyntaxKind as O}from"ts-morph";var Is=[{name:"cta",matchType:"contains",caseSensitive:!1,onlyInFiles:["notion-like-editor.tsx"]},{name:"initialContent",matchType:"exact",caseSensitive:!0,onlyInFiles:["notion-like-editor.tsx"]},{name:"JSONContent",matchType:"exact",caseSensitive:!0,onlyInFiles:["notion-like-editor.tsx"]},{name:"onCreate",matchType:"exact",caseSensitive:!0,onlyInFiles:["notion-like-editor.tsx"]},{name:"getDocumentId",matchType:"exact",caseSensitive:!0,onlyInFiles:["notion-like-editor.tsx"]}];function J(e,t,n){return t.some(r=>{if(r.onlyInFiles&&!r.onlyInFiles.some(s=>n.endsWith(s)))return!1;let o=r.caseSensitive?e:e.toLowerCase(),i=r.caseSensitive?r.name:r.name.toLowerCase();switch(r.matchType){case"exact":return o===i;case"contains":return o.includes(i);case"startsWith":return o.startsWith(i);case"endsWith":return o.endsWith(i);case"regex":return r.pattern?new RegExp(r.pattern,r.caseSensitive?"":"i").test(o):!1;default:return!1}})}function Es(e,t){let n=t.name;return n===T["next-app"].name||n===T["next-pages"].name?`NEXT_PUBLIC_${e}`:n===T.astro.name?`PUBLIC_${e}`:n===T.vite.name||n===T["tanstack-start"].name||n===T["react-router"].name?`VITE_${e}`:(n===T.laravel.name||n===T.manual.name,e)}function eo(e){return e.replace(/^(NEXT_PUBLIC_|VITE_|PUBLIC_)/,"")}async function Cs(e,t){if(!t)return;let n=[],r=e.getDescendantsOfKind(O.BinaryExpression);for(let s of r)if(s.getOperatorToken().getKind()===O.BarBarToken){let c=s.getLeft().getText();if(c.match(/^process\.env\.[A-Z_]+$/)){let p=c.match(/process\.env\.([A-Z_]+)/);if(p&&p[1]){let u=eo(p[1]),m=t.framework.name,g;m===T.astro.name?g=`import.meta.env.PUBLIC_${u}`:m===T.vite.name||m===T["tanstack-start"].name||m===T["react-router"].name?g=`import.meta.env.VITE_${u}`:m===T["next-app"].name||m===T["next-pages"].name?g=`process.env.NEXT_PUBLIC_${u}`:g=`process.env.${u}`;let f=s.getRight().getText(),y=`${g} || ${f}`;n.push({node:s,newText:y})}}}let o=e.getDescendantsOfKind(O.CallExpression);for(let s of o){let c=s.getExpression().getText();if(c.match(/^alert$/)){let p=s.getArguments();if(p.length>0){let m=p[0].getText();if(m.includes("TIPTAP_COLLAB_TOKEN")||m.includes("TIPTAP_COLLAB_DOC_PREFIX")||m.includes("TIPTAP_AI_TOKEN")){let g=m,f=["TIPTAP_COLLAB_DOC_PREFIX","TIPTAP_COLLAB_APP_ID","TIPTAP_COLLAB_TOKEN","TIPTAP_AI_APP_ID","TIPTAP_AI_TOKEN","USE_JWT_TOKEN_API_ENDPOINT"];for(let y of f){let S=Es(y,t.framework);g=g.replace(new RegExp(y,"g"),S)}if(g!==m){let y=`${c}(${g})`;n.push({node:s,newText:y})}}}}}let i=e.getDescendantsOfKind(O.PropertyAccessExpression);for(let s of i){let a=s.getText();if(a.match(/^process\.env\.[A-Z_]+$/)){if(s.getParent()?.getKind()===O.BinaryExpression)continue;let p=a.match(/process\.env\.([A-Z_]+)/);if(p&&p[1]){let u=eo(p[1]),m=t.framework.name,g;m===T.astro.name?g=`import.meta.env.PUBLIC_${u}`:m===T.vite.name||m===T["tanstack-start"].name||m===T["react-router"].name?g=`import.meta.env.VITE_${u}`:m===T["next-app"].name||m===T["next-pages"].name?g=`process.env.NEXT_PUBLIC_${u}`:g=`process.env.${u}`,n.push({node:s,newText:g})}}}for(let{node:s,newText:a}of n)try{s.replaceWithText(a)}catch(c){console.warn(`Skipping transformation of node: ${c}`)}}var _t=async({sourceFile:e,config:t,projectInfo:n})=>{let r=Is,o=e.getFilePath(),i=[],s=e.getImportDeclarations();for(let h of s){let x=h.getModuleSpecifierValue();if(r.some($=>J(x,[$],o))){i.push({node:h,action:"remove"});continue}let b=h.getDefaultImport();if(b&&J(b.getText(),r,o)){i.push({node:h,action:"remove"});continue}let I=h.getNamedImports(),R=I.filter($=>J($.getName(),r,o));R.length>0&&(R.forEach(H=>i.push({node:H,action:"remove"})),I.filter(H=>!R.includes(H)).length===0&&!b&&i.push({node:h,action:"remove"}))}let a=e.getExportDeclarations();for(let h of a){let x=h.getNamedExports(),b=x.filter(I=>J(I.getName(),r,o));b.length>0&&(b.forEach(R=>i.push({node:R,action:"remove"})),x.filter(R=>!b.includes(R)).length===0&&i.push({node:h,action:"remove"}))}let c=e.getVariableStatements();for(let h of c){let x=h.getDeclarations(),b=x.filter(I=>J(I.getName(),r,o));b.length>0&&(x.length===b.length?i.push({node:h,action:"remove"}):b.forEach(I=>i.push({node:I,action:"remove"})))}let p=e.getFunctions();for(let h of p){let x=h.getName();x&&J(x,r,o)&&i.push({node:h,action:"remove"})}let u=e.getInterfaces();for(let h of u){let x=h.getName();J(x,r,o)&&i.push({node:h,action:"remove"})}let m=e.getTypeAliases();for(let h of m){let x=h.getName();J(x,r,o)&&i.push({node:h,action:"remove"})}let g=e.getDescendantsOfKind(O.PropertySignature);for(let h of g){let x=h.getName();x&&J(x,r,o)&&i.push({node:h,action:"remove"})}let f=e.getDescendantsOfKind(O.JsxElement);for(let h of f){let x=h.getOpeningElement().getTagNameNode().getText();J(x,r,o)&&i.push({node:h,action:"replace",newText:""})}let y=e.getDescendantsOfKind(O.JsxSelfClosingElement);for(let h of y){let x=h.getTagNameNode().getText();J(x,r,o)&&i.push({node:h,action:"replace",newText:""})}let S=e.getDescendantsOfKind(O.PropertyAssignment);for(let h of S){let x=h.getName();x&&J(x,r,o)&&i.push({node:h,action:"remove"})}let P=e.getDescendantsOfKind(O.JsxAttribute);for(let h of P){let x=h.getNameNode().getText();x&&J(x,r,o)&&i.push({node:h,action:"remove"})}let v=e.getDescendantsOfKind(O.Parameter);for(let h of v){let x=h.getName();if(x&&J(x,r,o)){let b=h.getParent();if(b&&(Dt.isFunctionDeclaration(b)||Dt.isArrowFunction(b)||Dt.isFunctionExpression(b)||Dt.isMethodDeclaration(b))){let I=b.getParameters(),R=I.indexOf(h);if(R!==-1){if(R===I.length-1&&R>0){let $=h.getPreviousSibling();$?.getKind()===O.CommaToken&&i.push({node:$,action:"remove"})}else{let $=h.getNextSibling();$?.getKind()===O.CommaToken&&i.push({node:$,action:"remove"})}i.push({node:h,action:"remove"})}}}}let A=e.getDescendantsOfKind(O.CallExpression);for(let h of A){let x=h.getArguments();for(let b=0;b<x.length;b++){let I=x[b],R=I.getText();if(J(R,r,o)){if(b===x.length-1){let $=I.getPreviousSibling();$&&$.getKind()===O.CommaToken&&i.push({node:$,action:"remove"})}else{let $=I.getNextSibling();$&&$.getKind()===O.CommaToken&&i.push({node:$,action:"remove"})}i.push({node:I,action:"remove"})}}}let w=e.getDescendantsOfKind(O.BindingElement);for(let h of w){let x=h.getName();if(x&&J(x,r,o)){let b=h.getParent();if(b){let I=b.getDescendantsOfKind(O.BindingElement);if(I.indexOf(h)===I.length-1){let $=h.getPreviousSibling();$?.getKind()===O.CommaToken&&i.push({node:$,action:"remove"})}else{let $=h.getNextSibling();$?.getKind()===O.CommaToken&&i.push({node:$,action:"remove"})}}i.push({node:h,action:"remove"})}}let k=e.getDescendantsOfKind(O.Identifier);for(let h of k){let x=h.getText();if(J(x,r,o)){let b=h.getParent();if(b){let I=b.getKind();if(I===O.CallExpression){let R=b;R.getExpression()===h?i.push({node:R,action:"remove"}):R.getArguments().findIndex($e=>$e===h)!==-1&&i.push({node:h,action:"remove"})}if(I===O.PropertyAccessExpression){let R=b;R.getName()===x&&i.push({node:R,action:"remove"})}if((I===O.VariableDeclaration||I===O.BinaryExpression||I===O.IfStatement||I===O.ConditionalExpression)&&i.push({node:h,action:"remove"}),I===O.PropertyAssignment){let R=b;R.getInitializer()===h&&i.push({node:R,action:"remove"})}}}}let C=e.getDescendantsOfKind(O.ShorthandPropertyAssignment);for(let h of C){let x=h.getName();x&&J(x,r,o)&&i.push({node:h,action:"remove"})}await Cs(e,n===void 0?await z(t.resolvedPaths.cwd):n),i.sort((h,x)=>{let b=h.node.getStart?.()??0;return(x.node.getStart?.()??0)-b});for(let{node:h,action:x,newText:b}of i)try{if(h.wasForgotten?.()===!0)continue;x==="remove"?typeof h.remove=="function"&&h.remove():x==="replace"&&b!==void 0&&h.replaceWithText(b)}catch{}return e};import{posix as Lt}from"path";function to(e){let t=new Map;for(let n of e??[])n.path.endsWith(".scss")&&n.content!==void 0&&t.set(new URL(n.path,"registry:/").href,n.content);return{canonicalize(n,{containingUrl:r}){let o=new URL(n,r??"registry:/");if(o.protocol!=="registry:")return null;let i=o.pathname.endsWith(".scss")?[o.pathname]:[o.pathname+".scss",Lt.join(o.pathname,"index.scss")];for(let s of i){let a=Lt.join(Lt.dirname(s),"_"+Lt.basename(s)),c=[s,a].map(p=>new URL(p,o)).filter(p=>t.has(p.href));if(c.length>1)throw new Error(`Ambiguous Sass import: ${n}`);if(c.length===1)return c[0]}return null},load(n){let r=t.get(n.href);return r===void 0?null:{contents:r,syntax:"scss"}}}}async function no(e,t,n){try{let{compileString:r}=await import("./sass.cjs");return r(e,{url:new URL(t,"registry:/"),importers:[n],style:"expanded"}).css}catch(r){throw new Error(`Failed to compile SCSS to CSS: ${r instanceof Error?r.message:String(r)}`)}}import{Project as As,ScriptKind as Rs}from"ts-morph";var Ns=new As({useInMemoryFileSystem:!0});async function ro(e,t=[ot,Ot,_t]){if(e.filename.endsWith(".scss")&&e.sassImporter)return await no(e.raw,e.filename,e.sassImporter);if(!/\.(?:[cm]?[jt]s|[jt]sx)$/i.test(e.filename))return e.raw;let n=Ns.createSourceFile(`/${$s()}/${e.filename}`,e.raw,{scriptKind:Rs.TSX});try{for(let r of t)await r({sourceFile:n,...e});return e.transformJsx?await Zr({sourceFile:n,...e}):n.getText()}finally{n.forget()}}import{confirm as js}from"@inquirer/prompts";var Fs="scss.d.ts",Os=`declare module "*.scss";
29
+ `;function so(e){e.before!==null&&(e.after=e.before,e.status==="conflict"&&(e.status="keep"))}async function Mt(e){try{await Be.lstat(e)}catch(t){let n=G.dirname(e);if(t.code!=="ENOENT"||n===e)throw t;let r=await Mt(n);return G.join(r,G.basename(e))}return Be.realpath(e)}function Ut(e,t){let n=G.relative(e,t);return n!==""&&n!==".."&&!n.startsWith(`..${G.sep}`)&&!G.isAbsolute(n)}async function we(e,t){let{cwd:n,...r}=t.resolvedPaths,o=Ut(n,e)?n:Object.values(r).find(i=>!Ut(n,i)&&Ut(i,e));if(o){let[i,s]=await Promise.all([Mt(o),Mt(e)]);if(Ut(i,s))return s}throw new Error(`File destination is outside the configured install directories: ${e}`)}async function le(e){try{return await Be.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return null;throw t}}async function ao(e,t,n){let r=t.resolvedPaths.cwd,[o,i]=await Promise.all([n===void 0?z(r):n,q(r)]),s=Ct(r),a=s?to(e):void 0,c=[];for(let p of e??[]){if(p.content===void 0)continue;let u=Ms(p,t,{isSrcDir:p.type==="registry:page"&&o?.nextAppDir?o.nextAppDir==="src/app":o?.isSrcDir,framework:o?.framework.name});if(u){t.tsx||(u=u.replace(/\.ts(x?)$/,".js$1")),s&&(u=u.replace(/\.scss$/,".css"));try{let m=await we(u,t),g=await le(m),f=await ro({filename:p.path,outputFilename:u,raw:p.content,sassImporter:a,config:t,projectInfo:o,transformJsx:!t.tsx,packageManager:i},p.type==="registry:page"&&/\/route\.[jt]s$/.test(p.target??"")?[ot]:[ot,Ot,_t]),y=g===null?"create":await io(g)===await io(f)?"identical":"conflict";c.push({registryPath:p.path,path:u,realPath:m,before:g,after:f,status:y})}catch(m){throw new Error(`Could not prepare ${u}: ${m instanceof Error?m.message:m}`)}}}if(c.some(p=>p.path.endsWith(".scss"))){let p=G.join(r,o?.isSrcDir?"src":"",Fs),u=await we(p,t);await le(u)===null&&c.push({path:p,realPath:u,before:null,after:Os,status:"create"})}return c}async function oo(e){if(await Mt(e.path)!==e.realPath)throw new Error(`The destination of ${e.path} changed. Run add again to review it.`)}async function Ds(e){try{if((await Be.stat(e)).isFile())return}catch(t){if(t.code!=="ENOENT")throw t}throw new Error(`Missing file ${e}. Run add again to restore it.`)}async function co(e,t,n){let r={filesCreated:[],filesUpdated:[],filesSkipped:[],errors:[]},o=new Map(e.map(s=>[s.path,s])),i=new Map;for(let s of e){if(s.status==="update"&&r.errors.length)continue;let a=G.relative(t,s.path);try{let c=s.status==="conflict"&&!n.overwrite&&(!(n.interactive??process.stdin.isTTY)||!await js({message:`Overwrite ${a}?`,default:!1}));if(await oo(s),c){await Ds(s.realPath),i.set(s.path,s.before),r.filesSkipped.push(a);continue}if(s.before!==null&&await le(s.realPath)!==s.before)throw new Error("The file changed during installation. Run add again to review it.");if(s.status==="identical"||s.status==="keep"){i.set(s.path,s.before),r.filesSkipped.push(a);continue}for(let p of s.requiredFiles??[]){let u=o.get(p);if(!u)throw new Error(`Missing required file in install plan: ${p}`);let m=i.get(p);if(m==null)throw new Error(`Required file did not pass installation: ${p}`);if(await oo(u),await le(u.realPath)!==m)throw new Error(`Required file changed during installation: ${p}. Run add again to review it.`)}await Be.mkdir(G.dirname(s.realPath),{recursive:!0}),await Be.writeFile(s.realPath,s.after,{encoding:"utf8",flag:s.before===null?"wx":"w"}),i.set(s.path,s.after),s.before===null?r.filesCreated.push(a):r.filesUpdated.push(a)}catch(c){r.errors.push({file:a,error:c instanceof Error?c.message:String(c)})}}return r}function _s(e,t,n){return n||(e.type==="registry:ui"?t.resolvedPaths.tiptapUi:e.type==="registry:ui-primitive"?t.resolvedPaths.tiptapUiPrimitives:e.type==="registry:ui-utils"?t.resolvedPaths.tiptapUiUtils:e.type==="registry:extension"?t.resolvedPaths.tiptapExtensions:e.type==="registry:node"?t.resolvedPaths.tiptapNodes:e.type==="registry:icon"?t.resolvedPaths.tiptapIcons:e.type==="registry:hook"?t.resolvedPaths.hooks:e.type==="registry:lib"?t.resolvedPaths.lib:e.type==="registry:context"?t.resolvedPaths.contexts:e.type==="registry:template"||e.type==="registry:component"?t.resolvedPaths.components:e.type==="registry:style"?t.resolvedPaths.styles:t.resolvedPaths.components)}async function io(e){return e.replace(/\r\n/g,`
30
+ `).trim()}function Ls(e,t){if(!t)return"";if(t==="next-app")return e;if(t==="next-pages"){let n=e.replace(/^app\//,"pages/");return n=n.replace(/\/page(\.[jt]sx?)$/,"$1"),n}if(t==="react-router"){let n=e.replace(/^app\//,"app/routes/");return n=n.replace(/\/page(\.[jt]sx?)$/,"$1"),n}if(t==="laravel"){let n=e.replace(/^app\//,"resources/js/pages/");return n=n.replace(/\/page(\.[jt]sx?)$/,"$1"),n}return""}function Us(e,t){let n=Fn(e);if(n)return n.suffix;let r=e.replace(/^\/|\/$/g,""),o=t.replace(/^\/|\/$/g,""),i=r.split("/"),s=o.split("/"),a=s[s.length-1],c=i.findIndex(p=>p===a);return c===-1?i[i.length-1]:i.slice(c+1).join("/")}function Ms(e,t,n){if(!e.target&&e.path.includes("tiptap-templates/")&&e.type!=="registry:page"){let i=e.path.match(/tiptap-templates\/([^/]+)\/(.*)/);if(i){let[,s,a]=i;if(a.startsWith("components/")){let c=a.replace("components/","");return G.join(t.resolvedPaths.components,"tiptap-templates",s,c)}return G.join(t.resolvedPaths.components,"tiptap-templates",s,a)}}if(e.target&&e.path.includes("tiptap-templates/")&&e.target.includes("/data/")){let i=e.path.match(/tiptap-templates\/([^/]+)\//);if(i){let s=i[1],a=e.target.split("/data/")[1];return G.join(t.resolvedPaths.components,"tiptap-templates",s,"data",a)}}if(e.target){if(e.target.startsWith("~/"))return G.join(t.resolvedPaths.cwd,e.target.replace("~/",""));let i=e.target;return e.type==="registry:page"&&(i=Ls(i,n.framework),!i)?"":n.isSrcDir?G.join(t.resolvedPaths.cwd,"src",i.replace("src/","")):G.join(t.resolvedPaths.cwd,i.replace("src/",""))}let r=_s(e,t),o=Us(e.path,r);return G.join(r,o)}import _ from"path";function On(e,t){let n=e.name,r=t.resolvedPaths.cwd,o=t.resolvedPaths.components?.includes("/src/"),i=t.resolvedPaths.styles?.includes("/src/"),s=[];switch(n){case T["next-app"].name:{let a=pn(r)??"app";s=["globals.css","globals.scss"].map(c=>_.join(r,a,c));break}case T["next-pages"].name:s=(o?["src/styles","styles"]:["styles","src/styles"]).flatMap(a=>["globals.css","globals.scss"].map(c=>_.join(r,a,c)));break;case T.vite.name:case T["react-router"].name:case T["tanstack-start"].name:s=[_.join(r,"src/index.css"),_.join(r,"src/main.css"),_.join(r,"src/App.css")];break;case T.astro.name:s=[_.join(r,"src/styles/main.css"),_.join(r,"src/styles/global.css")];break;case T.laravel.name:s=[_.join(r,"resources/css/app.css")];break;case T.manual.name:default:o||i?s=[_.join(r,"src/index.css"),_.join(r,"src/main.css"),_.join(r,"src/App.css"),_.join(r,"src/styles/main.css")]:s=[_.join(r,"index.css"),_.join(r,"main.css"),_.join(r,"styles/main.css")];break}for(let a of s)if(Bs(a))return a;return s[0]||null}async function lo(e,t,n){let r=new Set(e),o=[...r].filter(w=>{let k=_.basename(w);if(!/^_(variables|keyframe-animations)\.(scss|css)$/.test(k))return!1;let C=_.join(t.resolvedPaths.styles,k);return w===C||!r.has(C)});if(!o.length)return{result:{success:!0,message:"No style files to import"}};let i=n&&On(n,t);if(!i)return{result:{success:!1,message:"Could not determine main CSS file location"}};let s=await we(i,t),a=await le(s);if(a===null)return{result:{success:!1,message:`Main CSS file not found at ${i}`}};let c=i.endsWith(".scss"),p;try{p=(c?Ws:Ks)(a,{from:i})}catch(w){return{result:{success:!1,message:`Could not read style imports in ${i}: ${w instanceof Error?w.message:w}`}}}let u=new Set,m=a.startsWith("\uFEFF")?1:0,g=m;for(let w of p.nodes){if(w.type!=="atrule")continue;let k=w.name.toLowerCase();if((k==="charset"||c&&(k==="use"||k==="forward"))&&(g=m+w.source.end.offset),k==="import"){let C=w.params.match(/^(?:(["'])(.+?)\1|url\(\s*(?:(["'])(.+?)\3|([^"'()\s]+))\s*\))(?:\s+layer(?:\([^()]+\))?)?(?:\s+all)?$/i);C&&u.add(C[2]??C[4]??C[5])}}let f=[];for(let w of o){let k=_.relative(_.dirname(i),w).split(_.sep).join("/"),C=k.startsWith(".")?k:"./"+k,h=t.aliases.styles&&`${t.aliases.styles}/${_.basename(w)}`,x=h&&u.has(h)?t.overrideImports?await D(h,t.overrideImports):_.join(t.resolvedPaths.styles,_.basename(w)):void 0;!u.has(C)&&!u.has(k)&&x!==w&&f.push(`@import '${C}';`)}if(!f.length)return{result:{success:!0,message:"Style imports already exist",filePath:i}};let y=a.includes(`\r
31
31
  `)?`\r
32
32
  `:`
33
- `,v=h.join(A)+A+A,b=c.slice(0,f),S=c.slice(f),_=b+(f>w?A:"")+v+S.replace(/^\r?\n/,"");return{result:{success:!0,message:"Style imports added",filePath:s},change:{path:s,realPath:i,requiredFiles:o,before:c,after:_,status:"update"}}}function Qe(e){if(!e.success){a.warn(p.yellow(`\u26A0 ${e.message}`));return}if(e.message==="No style files to import"||e.message==="Style imports already exist")return;let t=e.filePath?D.relative(process.cwd(),e.filePath):"main CSS file";a.log(`${p.green("\u2714")} Style imports automatically added to ${p.cyan(t)}`),a.log("")}import V from"semver";var zt=/^@tiptap\/(?:core|extensions|extension-[^/]+|pm|react|starter-kit|suggestion)$/,Ee="^3.0.0";function us(e,t){return e===t||!!(V.validRange(e)&&V.validRange(t)&&V.subset(e,t)&&V.subset(t,e))}function Zn(e,t,n){let r=n.resolvedPaths.cwd,o=Ne(r),s={...o?.peerDependencies,...o?.devDependencies,...o?.optionalDependencies,...o?.dependencies},i=new Map;function c(v,b){for(let S of v){let _=/^((?:@[\w.-]+\/)?[\w.-]+)(?:@(.+))?$/.exec(S);if(!_)throw new Error(`Invalid registry dependency "${S}".`);let[,T,E]=_,m=i.get(T);if(m?.version&&E&&!us(m.version,E))throw new Error(`Registry items request both ${T}@${m.version} and ${T}@${E}.`);i.set(T,{version:m?.version??E,dev:b&&(m?.dev??!0)})}}c(e,!1),c(t,!0);let l={dependencies:[],devDependencies:[],promotions:[]},d=[...i.keys()].some(v=>zt.test(v)),u=s["@tiptap/core"]?"@tiptap/core":Object.keys(s).find(v=>zt.test(v)),w=u&&s[u],f=d&&u?xe(r,u):void 0,h=f&&!V.satisfies(f,Ee)?f:w&&V.validRange(w)&&!V.intersects(w,Ee)?w:void 0;if(d&&h)throw new Error(`This template requires Tiptap 3. The project uses ${u}@${h}.`);let A=w&&V.validRange(w)&&V.subset(w,Ee)?w:Ee;for(let[v,{version:b,dev:S}]of i){let _=s[v],T=zt.test(v),E=b??(T?Ee:void 0);if(_){if(E&&_!==E){let P=xe(r,v);if(!(V.validRange(E)&&(P?V.satisfies(P,E):V.validRange(_)&&V.subset(_,E))))throw new Error(`The registry requires ${v}@${E}. Check the project's ${v}@${_} before installing.`)}!S&&o?.devDependencies?.[v]&&!o.dependencies?.[v]&&!o.optionalDependencies?.[v]&&!o.peerDependencies?.[v]&&l.promotions.push({name:v,version:_});continue}let m=S?l.devDependencies:l.dependencies,y=b??(T?f??A:void 0);m.push(y?`${v}@${y}`:v)}return l}import et from"fs";import ds from"path";import{execa as Kt}from"execa";import{applyEdits as Qn,modify as er}from"jsonc-parser";function tr(e,t,n=!1){let r=n?"dependencies":"devDependencies",o=n?"devDependencies":"dependencies",s=JSON.parse(e),i=/^[ \t]+(?=")/m.exec(e)?.[0],c={insertSpaces:!i?.includes(" "),tabSize:i?.length??2,eol:e.includes(`\r
33
+ `,S=f.join(y)+y+y,P=a.slice(0,g),v=a.slice(g),A=P+(g>m?y:"")+S+v.replace(/^\r?\n/,"");return{result:{success:!0,message:"Style imports added",filePath:i},change:{path:i,realPath:s,requiredFiles:o,before:a,after:A,status:"update"}}}function Bt(e){if(!e.success){l.warn(d.yellow(`\u26A0 ${e.message}`));return}if(e.message==="No style files to import"||e.message==="Style imports already exist")return;let t=e.filePath?_.relative(process.cwd(),e.filePath):"main CSS file";l.log(`${d.green("\u2714")} Style imports automatically added to ${d.cyan(t)}`),l.log("")}import uo from"os";import M from"path";import Kt from"fs-extra";import{execa as Wt}from"execa";import po from"semver";var _n="https://tiptap.dev/docs/guides/pro-extensions";async function Vt(e){let n=`${await de(e)} @tiptap/cli login --registry-only --write-config`;return`Run in ${M.resolve(e)}
34
+ ${n}`}var mo=/^@tiptap-pro\/[\w.-]+(?:@[^/]+)?$/;function Ee(e){if(!e||!URL.canParse(e))return"public";let t=new URL(e);return t.origin==="https://registry.tiptap.dev"?"tiptap":["https:","http:"].includes(t.protocol)?["registry.npmjs.org","registry.yarnpkg.com"].includes(t.hostname)?"public":"mirror":"public"}async function Vs(e,t,n){let r=process.env.NPM_CONFIG_USERCONFIG||process.env.npm_config_userconfig,o=M.join(t,".npmrc");if(!r&&!n)return o;let{stdout:i}=await Wt("bun",["--version"],{cwd:e}),s=i.trim();if(r&&po.gte(s,"1.4.4"))return r.startsWith("~/")?M.join(t,r.slice(2)):M.resolve(e,r);if(n){let a=M.join(n,".npmrc");if(po.lt(s,"1.4.0")||await Kt.pathExists(a))return a}return o}async function zs(e,t){let n=uo.homedir(),r=process.env.XDG_CONFIG_HOME,o=r&&M.isAbsolute(r)?r:void 0,i=[M.join(o||n,".bunfig.toml"),M.join(e,"bunfig.toml")],s=[];for(let u of i)await Kt.pathExists(u)&&s.push(u);let a,c;if(s.length){let u=`
35
+ let scope, registry
36
+ for (const file of process.argv.slice(1)) {
37
+ const { install } = (await import(file)).default
38
+ scope = install?.scopes?.["tiptap-pro"] ?? install?.scopes?.["@tiptap-pro"] ?? scope
39
+ registry = install?.registry ?? registry
40
+ }
41
+ const url = value => typeof value === "string" ? value : value?.url
42
+ console.log(JSON.stringify([url(scope), url(registry)]))
43
+ `,{stdout:m}=await Wt("bun",["-e",u,...s],{cwd:e}),[g,f]=JSON.parse(m);a=g,c=f}let p=await fo([await Vs(t,n,o),M.join(e,".npmrc")]);return Dn(a||p.scope||process.env.BUN_CONFIG_REGISTRY||process.env.npm_config_registry||process.env.NPM_CONFIG_REGISTRY||c||p.registry)}function Dn(e){return e?.replace(/^(['"])(.*)\1$/,"$2").replace(/\$\{([^}]+)\}|\$([A-Z_][A-Z_0-9]*)/g,(t,n,r)=>process.env[n||r]??"")}async function fo(e){let t,n;for(let r of e){if(!await Kt.pathExists(r))continue;let o=await Kt.readFile(r,"utf8");for(let i of o.split(`
44
+ `)){let s=/^\s*(@tiptap-pro:registry|registry)\s*=\s*("[^"]*"|'[^']*'|[^;#]*)/.exec(i);s?.[1]==="registry"?n=s[2].trim():s&&(t=s[2].trim())}}return{scope:Dn(t),registry:Dn(n)}}function Js(){let e=M.dirname(process.execPath),t=process.env.PREFIX||(process.platform==="win32"?e:M.join(process.env.DESTDIR||"",M.dirname(e)));return M.join(t,"etc","npmrc")}async function go(e,t,n){let r=async o=>(await Wt(e,o,{cwd:t})).stdout.trim();try{if(e==="bun")return Ee(await zs(t,n));if(e==="yarn"&&!(await r(["--version"])).startsWith("1.")){let s=await Wt(e,["config","get",'npmScopes["tiptap-pro"].npmRegistryServer',"--json"],{cwd:t,reject:!1}),a=s.stdout.trim(),c=s.exitCode===0&&a&&a!=="undefined"?JSON.parse(a):void 0;return Ee(c||JSON.parse(await r(["config","get","npmRegistryServer","--json"])))}let o=await r(["config","get","@tiptap-pro:registry"]),i=o&&o!=="undefined"&&o!=="null"?o:void 0;if(e==="yarn"){let s=[];for(let u=M.dirname(t);u!==M.dirname(u);u=M.dirname(u))s.unshift(M.join(u,".npmrc"));let a=process.env.npm_config_userconfig||process.env.NPM_CONFIG_USERCONFIG||M.join(uo.homedir(),".npmrc"),c=await fo([...s,Js(),a,M.join(t,".npmrc")]),p=c.scope||i||process.env.npm_config_registry||process.env.NPM_CONFIG_REGISTRY||c.registry;if(p)return Ee(p)}if(i)return Ee(i);if(e==="pnpm"){let s=await r(["config","get","registries","--json"]);if(s&&s!=="undefined"&&s!=="null"){let a=JSON.parse(s);if(a["@tiptap-pro"])return Ee(a["@tiptap-pro"]);if(a.default)return Ee(a.default)}}return Ee(await r(["config","get","registry"]))}catch{throw new Error(`Could not read the registry route from ${e} in ${t}. Check the package manager configuration. ${_n}`)}}async function ho(e){let t=await q(e);return go(t,await Ze(e,t),M.resolve(e))}async function yo(e,t,{interactive:n}){let r=e.filter(a=>mo.test(a));if(!r.length)return;let o=await q(t),i=await Ze(t,o);if(await go(o,i,M.resolve(t))!=="public")return;let s=j.getAuthToken();if(s){if(await De(s,o,i))return;throw new Error(`Configure package registry access in ${i}. ${_n}
45
+ ${await Vt(i)}`)}await Ln(r,t,{interactive:n})}async function Ln(e,t,{interactive:n}){let r=e.filter(i=>mo.test(i));if(!r.length)return;let o=`Configure package registry access for ${r.join(", ")}. ${_n}
46
+ ${await Vt(t)}`;if(!n||!await ve(`Sign in and configure this project to download ${r.join(", ")} from the Tiptap registry?`))throw new Error(o);if(!await rt({cwd:t,registryOnly:!0,writeConfig:!0,showMessage:!1}))throw new Error(o)}import Y from"path";import{createTwoFilesPatch as ea}from"diff";import{Node as W,SyntaxKind as L}from"ts-morph";import{Node as me,Project as qs,SyntaxKind as pe}from"ts-morph";function it(e,t,n){let r=e.getImportDeclarations().filter(o=>o.getModuleSpecifierValue()===t&&!o.isTypeOnly()).flatMap(o=>o.getNamedImports()).filter(o=>o.getText()===n);return r.length===1?r[0].getNameNode():void 0}function Un(e){let t=e.getProperties().map(n=>me.isPropertyAssignment(n)||me.isShorthandPropertyAssignment(n)?n.getNameNode().asKind(pe.Identifier)?.getText():void 0);return!t.includes(void 0)&&new Set(t).size===t.length}function st(e,t){let r=e.getDescendantsOfKind(pe.CallExpression).filter(v=>v.getExpression().getText()==="useEditor"),o=r[0],i=e.getImportDeclarations().filter(v=>v.getModuleSpecifierValue()==="@tiptap/react");if(i.some(v=>v.getNamespaceImport())||i.flatMap(v=>v.getNamedImports()).filter(v=>v.getName()==="useEditor").length!==1)return;let s=it(e,"@tiptap/react","useEditor"),a=o?.getParentIfKind(pe.VariableDeclaration);if(!s||r.length!==1||o.getExpression().getSymbol()!==s.getSymbol())return;let c=a?.getVariableStatement()?.getParentIfKind(pe.Block);if(!a||!c||t&&c!==t||o.getArguments().length!==1)return;let p=c.getDescendantsOfKind(pe.JsxSelfClosingElement).filter(v=>v.getTagNameNode().getText()==="EditorContent"),u=p[0],m=c.getStatements().find(me.isReturnStatement),g=u?.getFirstAncestor(v=>!me.isJsxElement(v)&&!me.isJsxFragment(v)&&!me.isJsxExpression(v)&&!me.isParenthesizedExpression(v)),f=it(e,"@tiptap/react","EditorContent");if(!m||g!==m||!f||u?.getTagNameNode().getSymbol()!==f.getSymbol())return;let y=u?.getAttributes().filter(v=>me.isJsxSpreadAttribute(v)||v.getNameNode().getText()==="editor").at(-1)?.asKind(pe.JsxAttribute)?.getInitializer()?.asKind(pe.JsxExpression)?.getExpression();if(p.length!==1||!y||y.getSymbol()!==a.getNameNode().getSymbol())return;let S=o.getArguments()[0]?.asKind(pe.ObjectLiteralExpression);if(!S||!Un(S))return;let P=S.getProperty("extensions")?.asKind(pe.PropertyAssignment)?.getInitializerIfKind(pe.ArrayLiteralExpression);if(P&&!P.getElements().some(me.isSpreadElement))return{options:S,extensions:P}}function ie(e,t="editor.tsx"){let n=new qs({useInMemoryFileSystem:!0,compilerOptions:{noLib:!0,allowJs:!0}}),r=n.createSourceFile(t,e);return n.getProgram().compilerObject.getSyntacticDiagnostics(r.compilerNode).length?null:r}var at="withCollaboration";function Mn(e,t,n=new Set){return n.has(e)?!1:(n.add(e),e.findReferencesAsNodes().some(r=>{if(r===e)return!1;let o=r.getFirstAncestor(c=>W.isSourceFile(c.getParent()));if(!o)return!1;if(W.isFunctionDeclaration(o)){let c=o.getNameNode();return!!c&&Mn(c,t,n)}if(o.getStart()>=t)return!1;let i=r.getFirstAncestorByKind(L.VariableDeclaration),s=i?.getInitializer(),a=i?.getNameNode();return W.isVariableStatement(o)&&W.isIdentifier(a)&&(s===r||W.isArrowFunction(s)||W.isFunctionExpression(s))?Mn(a,t,n):!0}))}function wo(e,t,n){let r=e.getFunction(t),o=e.getVariableDeclaration(t),i=`Collaborative${t}`,s=e.getVariableDeclaration(i);if(r){if(!/^[A-Z][\w$]*$/.test(t)||e.getFunctions().filter(y=>y.getName()===t).length!==1||o||!r.hasExportKeyword()||r.getParameters().length||r.getNameNode()?.findReferencesAsNodes().some(y=>y.getFirstAncestor(S=>S===r.getBody())))return;if(!s)return{fn:r,wrapped:!1};let f=r.getBody()?.asKind(L.Block)?.getStatements();if(f?.length!==1||!W.isReturnStatement(f[0])||f[0].getExpression()?.asKind(L.JsxSelfClosingElement)?.getTagNameNode().getSymbol()!==s.getNameNode().getSymbol())return}let a=r?s:o,c=a?.getVariableStatement(),p=a?.getInitializerIfKind(L.CallExpression),u=p?.getArguments()[0];if(c?.getDeclarationKind()!=="const"||!r&&!c.hasExportKeyword()&&!e.getExportAssignment(f=>f.getExpression().getText()===t))return;let m=it(e,n,at);if(!m||p?.getExpression().getSymbol()!==m.getSymbol()||p?.getExpression().getText()!==at||p.getArguments().length!==1||!W.isFunctionExpression(u)||u.getName()!==t)return;let g=u.getParameters().map(f=>f.getText().replace(/\s/g,""));if(!(g.length!==1||g[0]!=="{collaboration,editable}"))return{fn:u,wrapped:!0}}function Gs(e){return e.getParameters()[0].getNameNode().asKindOrThrow(L.ObjectBindingPattern).getElements().some(n=>{let r=n.getNameNode().asKindOrThrow(L.Identifier);return r.findReferences().some(o=>o.getReferences().some(i=>{let s=i.getNode();return s===r||!i.isWriteAccess()?!1:s.getParentIfKind(L.ShorthandPropertyAssignment)?s.getAncestors().some(a=>W.isForOfStatement(a)||W.isForInStatement(a)?a.getInitializer().containsRange(s.getStart(),s.getEnd()):W.isBinaryExpression(a)&&a.getOperatorToken().getKind()===L.EqualsToken&&a.getLeft().containsRange(s.getStart(),s.getEnd())):!0}))})}function Ys(e){return e.getImportDeclarations().some(t=>{let n=t.getModuleSpecifierValue();return/^(?:@tiptap\/(?:extension-collaboration(?:-caret)?|extension-history|extension-undo-redo|y-tiptap)|@tiptap-pro\/provider|y-prosemirror|yjs)(?:\/|$)/.test(n)?!0:t.getNamedImports().some(r=>["Collaboration","UndoRedo","History"].includes(r.getName()))})}function xo(e,t){let n=st(e,t);if(!n)return;let{options:r,extensions:o}=n,i=e.getImportDeclaration("@tiptap/starter-kit"),s=it(e,"@tiptap/starter-kit","StarterKit")??(!i?.isTypeOnly()&&i?.getDefaultImport()?.getText()==="StarterKit"?i.getDefaultImport():void 0),a=o.getDescendantsOfKind(L.Identifier).filter(m=>m.getText()==="StarterKit"),c=a[0];if(!s||a.length!==1||c.getSymbol()!==s.getSymbol())return;if(c.getParent()===o)return{options:r,extensions:o,kitReference:c};let p=c.getParentIfKind(L.PropertyAccessExpression)?.getParentIfKind(L.CallExpression);if(p?.getParent()!==o||p.getExpression().getText()!=="StarterKit.configure"||p.getArguments().length!==1)return;let u=p.getArguments()[0]?.asKind(L.ObjectLiteralExpression);if(!(!u||!Un(u)||u.getProperty("history")))return{options:r,extensions:o,kitOptions:u}}function Po(e){let{options:t,extensions:n,kitOptions:r}=e;return W.isShorthandPropertyAssignment(t.getProperty("editable"))&&!t.getProperty("content")&&n.getElements().filter(o=>o.getText()==="collaboration").length===1&&r?.getProperty("undoRedo")?.asKind(L.PropertyAssignment)?.getInitializer()?.getKind()===L.FalseKeyword}function bo(e,t){let n=t.getStart(),r=t.getNextSiblingIfKind(L.CommaToken)?.getEnd()??t.getEnd(),o=e.lastIndexOf(`
47
+ `,n-1)+1,i=e.slice(r).match(/^[ \t]*\r?\n/);return i&&e.slice(o,n).trim()===""?{start:o,end:r+i[0].length,text:""}:{start:n,end:r,text:""}}function Hs(e,t,n){let r=t.getProperty("content");if(!r)return[];let o=W.isShorthandPropertyAssignment(r)?r.getNameNode():r.asKind(L.PropertyAssignment)?.getInitializer();if(!W.isIdentifier(o))return null;let i=e.getImportDeclarations().find(u=>u.getModuleSpecifierValue()===n&&u.getDefaultImport()?.getText()===o.getText()),s=i?.getDefaultImport();if(!i||!s)return null;let a=s.findReferencesAsNodes().filter(u=>u.getStart()!==s.getStart());if(!a.some(u=>u.getStart()===o.getStart()))return null;let c=e.getFullText(),p=[bo(c,r)];return a.length===1&&!i.getNamedImports().length&&!i.getNamespaceImport()&&p.push(bo(c,i)),p}function Bn(e){let n=ie(e)?.getDescendantsOfKind(L.CallExpression).filter(o=>o.getExpression().getText()==="useEditor");if(n?.length!==1)return;let r=n[0].getFirstAncestor(o=>W.isFunctionDeclaration(o)||W.isFunctionExpression(o)||W.isArrowFunction(o));return W.isFunctionDeclaration(r)||W.isFunctionExpression(r)?r.getName():r?.getParentIfKind(L.VariableDeclaration)?.getName()}function Kn(e,t,n,r){let o=e.startsWith("\uFEFF")?"\uFEFF":"",i=e.slice(o.length),s=ie(i);if(!s)return{reason:"The editor source contains a syntax error."};let a=wo(s,t,n),c=a?.fn.getBody();if(!a||!c||a.fn.isAsync()||a.fn.isGenerator()||a.fn.getTypeParameters().length)return{reason:"The connector needs an exported, named function component without props or type parameters."};let p=s.getFunction(t),u=p?.getNameNode(),m=`Collaborative${t}`;if(p&&u&&Mn(u,s.getVariableDeclaration(m)?.getStart()??p.getStart()))return{reason:"The module may render the editor before its Collaboration wrapper initializes. Move the first render after the editor declaration."};if(Ys(s))return{reason:"The editor already imports a collaboration, history or provider module. Check how it manages document history before adding Collaboration."};let g=xo(s,c);if(!g)return{reason:"The connector needs one useEditor call with a static extensions array containing StarterKit and an EditorContent that renders the same editor."};let{options:f,extensions:y,kitOptions:S,kitReference:P}=g,v=S?.getProperty("undoRedo");if(v&&v.asKind(L.PropertyAssignment)?.getInitializer()?.getKind()!==L.FalseKeyword)return{reason:"The editor configures StarterKit undoRedo. Disable it when using Collaboration."};let A=f.getProperty("editable"),w=y.getElements().filter(V=>V.getText()==="collaboration");if(a.wrapped)return Gs(a.fn)?{reason:"Pass the wrapper's collaboration and editable values unchanged to useEditor."}:Po(g)?{source:e}:{reason:"The existing wrapper needs editable, one collaboration extension, disabled StarterKit undoRedo and no initial content."};if(A||w.length||s.getDescendantsOfKind(L.Identifier).some(V=>[m,at].includes(V.getText()))||c.getDescendantsOfKind(L.Identifier).some(V=>["collaboration","editable","arguments"].includes(V.getText())))return{reason:"The editor already uses an option or name needed by the Collaboration wrapper."};let k=Hs(s,f,r);if(!k)return{reason:"The editor supplies initial content. To keep it, seed the shared document once before opening the editor."};let C=k.length>0,h=i.includes(`\r
34
48
  `)?`\r
35
49
  `:`
36
- `};for(let{name:l,version:d}of t){if(s[r]?.[l]!==d||s[o]?.[l]!==void 0||!n&&(s.peerDependencies?.[l]||s.optionalDependencies?.[l])){if(n)continue;throw new Error(`The declaration for ${l} changed. Run add again to review it.`)}e=Qn(e,er(e,[o,l],d,{formattingOptions:c})),e=Qn(e,er(e,[r,l],void 0,{formattingOptions:c}))}return e}async function fs(e,t,n){let r=ds.join(e,"package.json"),o=et.readFileSync(r,"utf8"),s=tr(o,n);et.writeFileSync(r,s);try{await Kt(t,t==="pnpm"?["install","--no-frozen-lockfile"]:["install"],{cwd:e,env:t==="yarn"?{YARN_ENABLE_IMMUTABLE_INSTALLS:"false"}:void 0})}catch(i){let c=et.readFileSync(r,"utf8"),l=c===s?o:tr(c,n,!0);if(c!==l&&(et.writeFileSync(r,l),t!=="yarn")){let d=t==="npm"?"--package-lock-only":"--lockfile-only";try{await Kt(t,["install",d,"--ignore-scripts",...t==="pnpm"?["--no-frozen-lockfile"]:[]],{cwd:e})}catch(u){throw new Error(`Dependency promotion failed: ${i instanceof Error?i.message:i}. Run ${t} install in ${e} to sync the restored declarations. Lockfile update failed: ${u instanceof Error?u.message:u}.`)}}throw i}}async function nr(e,t,n,r=[]){if(e=Array.from(new Set(e)),!e.length&&!r.length)return;let o=L("Installing dependencies.",{silent:n.silent}).start(),s=t.resolvedPaths.cwd,i=await K(s);e.length&&await Kt(i,[i==="npm"?"install":"add",...i==="npm"?["--save"]:[],...e],{cwd:s}),r.length&&await fs(s,i,r),o.stopAndPersist({symbol:p.cyan("\u2714")})}import{execa as gs}from"execa";async function rr(e,t,n){if(e=Array.from(new Set(e)),!e?.length)return;n={silent:!1,...n};let r=L("Installing development dependencies.",{silent:n.silent})?.start(),o=await K(t.resolvedPaths.cwd);await gs(o,[o==="npm"?"install":"add",o==="npm"?"--save-dev":"-D",...e],{cwd:t.resolvedPaths.cwd}),r?.stopAndPersist({symbol:p.cyan("\u2714")})}async function hs(e,t){let n=await In(e);ae(n);let o=(t.overrideImports?null:await mn(t))?.tiptapUi,s=new Map(n.map(u=>[u.name,u])),i=new Map;function c(u,w){let f=s.get(u);if(!f)throw new Error(`Registry item ${u} is missing.`);let h=f.type==="registry:ui"&&o?o:w,A=i.get(h);if(A||(A=new Set,i.set(h,A)),!A.has(f)){A.add(f);for(let v of f.registryDependencies??[])c(v,h)}}if(o&&o.resolvedPaths.cwd!==t.resolvedPaths.cwd)for(let u of e)c(u,t);else i.set(t,new Set(n));let l=[];for(let[u,w]of i){let f=[...w];l.push({config:u,files:f.flatMap(h=>h.files??[]),dependencies:f.flatMap(h=>h.dependencies??[]),devDependencies:f.flatMap(h=>h.devDependencies??[])})}let d=await U(t.resolvedPaths.cwd);if(d)for(let u of l)u.devDependencies=Sn(u.devDependencies,d.framework.name);return l}async function Vt(e,t){let n=await hs(e,t),r=new Map,o=[];for(let c of n){let l=await Zn(c.dependencies,c.devDependencies,c.config);o.push({config:c.config,...l});for(let d of await Yn(c.files,c.config)){let u=r.get(d.realPath);if(u&&u.after!==d.after)throw new Error(`Registry items provide different contents for ${d.path}.`);r.set(d.realPath,d)}}let s=await U(t.resolvedPaths.cwd),i=await Xn([...r.values()].map(c=>c.path),t,s?.framework);if(i.change){if(r.has(i.change.realPath))throw new Error(`Registry files and stylesheet imports both target ${i.change.path}.`);r.set(i.change.realPath,i.change)}return{files:[...r.values()],packages:o,styles:i.result}}async function tt(e,t,n){let r=L("Checking registry",{silent:n.silent}).start(),o=await Vt(e,t).finally(()=>r.stop());for(let i of o.packages)await nr(i.dependencies,i.config,n,i.promotions),await rr(i.devDependencies,i.config,n);let s=await Hn(o.files,t.resolvedPaths.cwd,n);if(s.errors.length){let i=s.errors.map(({file:c,error:l})=>` ${c}: ${l}`).join(`
50
+ `,x=(V,Ae)=>k.push({start:V,end:V,text:Ae}),b=(V,Ae)=>{let Re=V.getStart()+1,lr=i.slice(Re).match(/^\s*/)?.[0]??"";i[Re]==="}"?x(Re,` ${Ae} `):x(Re,lr+Ae+(lr?",":", "))};x(s.getImportDeclarations()[0].getStart(),`import { ${at} } from ${JSON.stringify(n)}${h}`),x(c.getStart(),["{",` return <${m} />`,"}","",`const ${m} = ${at}(function ${t}({ collaboration, editable }) `].join(h)),x(a.fn.getEnd(),");"),b(f,"editable"),b(y,"collaboration"),P?x(P.getEnd(),".configure({ undoRedo: false })"):S&&!v&&b(S,"undoRedo: false");let I=i;for(let V of k.sort((Ae,Re)=>Re.start-Ae.start))I=I.slice(0,V.start)+V.text+I.slice(V.end);let R=ie(I),$=R&&wo(R,t,n),H=$?.fn.getBody(),$e=R&&H&&xo(R,H);return!$?.wrapped||!$e||!Po($e)?{reason:"The connector could not verify the edited source."}:{source:o+I,removedDemoContent:C}}import Ke from"path";import{Node as zt,SymbolFlags as Wn,SyntaxKind as Xs,ts as Zs}from"ts-morph";function Vn(e,t){let n=ie(e.after,Ke.basename(e.path))?.getExportSymbols().find(o=>o.getName()===t);if(!n)return!1;let r=n.isAlias()?n.getAliasedSymbol():n;return!r||!(r.getFlags()&Wn.Value)||n.isAlias()&&!n.getDeclarations().some(o=>zt.isExportSpecifier(o)&&!o.isTypeOnly()&&!o.getExportDeclaration().isTypeOnly())?!1:r.getDeclarations().some(o=>!(o.getCombinedModifierFlags()&Zs.ModifierFlags.Ambient)&&(!zt.isFunctionDeclaration(o)||o.getBody()!==void 0))}function Qs(e,t,n){let r=e.startsWith("\uFEFF")?"\uFEFF":"";e=e.slice(r.length);let o=ie(e),i=o&&st(o);if(!o||!i)return null;let{extensions:s}=i,a=o.getImportDeclarations(),c=a.filter(h=>h.getModuleSpecifierValue()===t),p=n;if(c.length){let[h]=c;if(!h||c.length!==1||h.isTypeOnly())return null;let x=h.getNamedImports().filter($=>$.getName()===n);if(x.length!==1||x[0].isTypeOnly())return null;let b=x[0].getAliasNode()??x[0].getNameNode();if(!zt.isIdentifier(b))return null;p=b.getText();let I=b.getSymbol();if(!I||!s.getSymbolsInScope(Wn.Value|Wn.Alias).includes(I))return null;let R=s.getElements().filter($=>zt.isIdentifier($)&&$.getSymbol()===I);if(R.length===1)return r+e;if(R.length||b.findReferencesAsNodes().length)return null}else if(o.getDescendantsOfKind(Xs.Identifier).some(h=>h.getText()===n))return null;let u=s.getStart()+1,m=e.slice(u).match(/^\s*/)?.[0]??"",g=s.getElements().length?m?",":", ":"",f=e.slice(0,u)+m+p+g+e.slice(u),y=a[0].getStart(),S=y>u?y+f.length-e.length:y,P=e.includes(`\r
51
+ `)?`\r
52
+ `:`
53
+ `,v=`import { ${n} } from ${JSON.stringify(t)}${P}`,A=c.length?f:f.slice(0,S)+v+f.slice(S),w=ie(A),k=w?.getImportDeclaration(t)?.getNamedImports().find(h=>h.getName()===n),C=(k?.getAliasNode()??k?.getNameNode())?.getSymbol();return w&&C&&st(w)?.extensions.getElements().some(h=>h.getSymbol()===C)?r+A:null}function Jt(e,t){let n=Ke.relative(Ke.dirname(e),t).split(Ke.sep).join("/").replace(/\.[jt]sx?$/,"");return n.startsWith("../")?n:`./${n}`}function zn(e,t){let n=Jt(e.realPath,t.realPath);return n===Jt(e.path,t.path)?n:void 0}function Jn(e,t,n,r){return t.after=n,t.status=t.before===null?"create":n===t.before?"identical":"update",t.requiredFiles=[...t.requiredFiles??[],r.path],e.delete(t.realPath),e.set(t.realPath,t),t.status==="identical"?"unchanged":"connected"}function vo(e,t,n,r){let{exportName:o}=e,i=[...t.values()].filter(p=>p.registryPath===e.extension);if(i.length!==1)throw new Error(`Expected one installed registry file for ${e.extension}.`);let s=i[0];if(n===s)throw new Error("The editor and its extension must be separate files.");let a={status:"pending",editorPath:n&&Ke.relative(r,n.path),extensionPath:Ke.relative(r,s.path),exportName:o,importPath:n&&zn(n,s)};if(!Vn(s,o)){if(s.before===null)throw new Error(`The registry file ${e.extension} must export ${o}.`);return a.reason=`Export ${o} from ${a.extensionPath} before connecting it to the editor.`,a}if(!n)return a;if(!a.importPath)return a.reason="A symlink changes the relative import. Select the editor at its real path.",a;let c=Qs(n.after,a.importPath,o);return c===null?(a.reason="Register the extension in the extensions array of the editor that EditorContent renders.",a):(a.status=Jn(t,n,c,s),a)}async function ko(e,t,n,r){if(e?.name!=="simple-editor"||t?.registryPath!=="tiptap-templates/simple/components/simple-editor.tsx")return;let o="tiptap-templates/simple/data/content.json",i=n.find(f=>f.registryPath===o);if(!i||i.before!==null&&i.before!==i.after||i.path!==Y.join(Y.dirname(t.path),"data","content.json"))return;let s=e.files?.find(f=>f.path===t.registryPath)?.content,a=s&&ie(s);if(!a)return;let c=a.getImportDeclarations().filter(f=>{let y=f.getModuleSpecifierValue();return y===`@/registry/${o}`||y.startsWith(".")&&Y.posix.join(Y.posix.dirname(t.registryPath),y)===o}),p=c[0]?.getDefaultImport()?.getText();if(c.length!==1||!p)return;let u=ie(t.before??t.after)?.getImportDeclarations().filter(f=>f.getDefaultImport()?.getText()===p),m=u?.[0]?.getModuleSpecifierValue();if(u?.length!==1||!m)return;if(m.startsWith("./")||m.startsWith("../"))return Y.resolve(Y.dirname(t.path),m)===i.path&&Y.resolve(Y.dirname(t.realPath),m)===i.realPath?{specifier:m,path:i.path}:void 0;let g=r.overrideImports?await jt(o,r,t.path):`${r.aliases.components}/${o}`;if(m===g)return{specifier:m,path:i.path}}function To(e,t,n,r,o,i,s){let a=r.resolvedPaths.cwd,c=[...t.values()],p=c.find(v=>v.registryPath===e.config),u=c.find(v=>v.registryPath===e.wrapper),m=c.find(v=>v.registryPath===e.tokenRoute);if(!p||!u)throw new Error("The registry must provide the Collaboration wrapper and configuration.");let g={status:"pending",wrapperPath:Y.relative(a,u.path),configPath:Y.relative(a,p.path),tokenPath:m&&Y.relative(a,m.path),existingTokenRoute:o,customPagePath:i};if(g.editorPath=n&&Y.relative(a,n.path),!Vn(u,"withCollaboration"))return g.reason=`Export withCollaboration as a value from ${g.wrapperPath} before connecting the editor.`,g;if(!n)return g;if([p,u,m].includes(n))throw new Error("Choose an editor outside the Collaboration setup files.");let f=n.after,y=Bn(f),S=zn(n,u);if(g.componentName=y,g.importPath=S,!S)return g.reason="A symlink changes the relative import. Select the editor at its real path.",g;let P=y?Kn(f,y,S,s?.specifier):{reason:"The connector needs one useEditor call inside a named component."};if("reason"in P){g.reason=P.reason,!n.registryPath&&/(?:^|\/)tiptap-templates\/simple\/simple-editor\.[jt]sx$/.test(n.path.split(Y.sep).join("/"))&&(g.suggestedTemplate="simple-editor"),g.reason+=" Adapt the example patch to your editor.";let v=y&&/^[A-Z][\w$]*$/.test(y)?y:"Editor",A=['import { EditorContent, useEditor } from "@tiptap/react"','import { StarterKit } from "@tiptap/starter-kit"',`export function ${v}() {`," const editor = useEditor({"," extensions: [StarterKit],"," })"," return <EditorContent editor={editor} />","}",""].join(`
54
+ `),w=Kn(A,v,S);return"source"in w&&(g.patch=ea("example-editor.tsx","example-editor.tsx",A,w.source)),g}return s&&P.removedDemoContent&&(n.requiredFiles=[...n.requiredFiles??[],s.path]),g.status=Jn(t,n,P.source,u),g}async function So(e,t){let n=e.resolvedPaths.cwd,r=Y.join(n,"src",e.tsx?"App.tsx":"App.jsx"),o=await we(r,e),i=await le(o),s=ie(t.after),a=Bn(t.after),c=s?.getDefaultExportSymbol()?"default":a&&s?.getExportSymbols().some(u=>u.getName()===a)?`${a} as default`:void 0;if(!c)throw new Error("The template editor needs a component export to open in the Vite starter.");let p=`export { ${c} } from ${JSON.stringify(Jt(r,t.path))}
55
+ `;return{path:r,realPath:o,requiredFiles:[t.path],before:i,after:p,status:i===null?"create":p===i?"identical":"update"}}import Z from"semver";var qn=/^@tiptap\/(?:core|extensions|extension-[^/]+|pm|react|starter-kit|suggestion)$/,ct="^3.0.0";function ta(e,t){return e===t||!!(Z.validRange(e)&&Z.validRange(t)&&Z.subset(e,t)&&Z.subset(t,e))}function Io(e,t,n,r="This template"){let o=n.resolvedPaths.cwd,i=Fe(o),s={...i?.peerDependencies,...i?.devDependencies,...i?.optionalDependencies,...i?.dependencies},a=new Map;function c(P,v){for(let A of P){let w=/^((?:@[\w.-]+\/)?[\w.-]+)(?:@(.+))?$/.exec(A);if(!w)throw new Error(`Invalid registry dependency "${A}".`);let[,k,C]=w,h=a.get(k);if(h?.version&&C&&!ta(h.version,C))throw new Error(`Registry items request both ${k}@${h.version} and ${k}@${C}.`);a.set(k,{version:h?.version??C,dev:v&&(h?.dev??!0)})}}c(e,!1),c(t,!0);let p={dependencies:[],devDependencies:[],promotions:[]},u=[...a.keys()].some(P=>qn.test(P)),m=s["@tiptap/core"]?"@tiptap/core":Object.keys(s).find(P=>qn.test(P)),g=m&&s[m],f=u&&m?Ye(o,m):void 0,y=f&&!Z.satisfies(f,ct)?f:g&&Z.validRange(g)&&!Z.intersects(g,ct)?g:void 0;if(u&&y)throw new Error(`${r} requires Tiptap 3. The project uses ${m}@${y}.`);let S=g&&Z.validRange(g)&&Z.subset(g,ct)?g:ct;for(let[P,{version:v,dev:A}]of a){let w=s[P],k=qn.test(P),C=v??(k?ct:void 0);if(w){if(C&&w!==C){let b=Ye(o,P);if(!(Z.validRange(C)&&(b?Z.satisfies(b,C):Z.validRange(w)&&Z.subset(w,C))))throw new Error(`The registry requires ${P}@${C}. Check the project's ${P}@${w} before installing.`)}!A&&i?.devDependencies?.[P]&&!i.dependencies?.[P]&&!i.optionalDependencies?.[P]&&!i.peerDependencies?.[P]&&p.promotions.push({name:P,version:w});continue}let h=A?p.devDependencies:p.dependencies,x=v??(k?f??S:void 0);h.push(x?`${P}@${x}`:P)}return p}import{stripVTControlCharacters as ia}from"util";import qt from"fs";import na from"path";import{execa as Gn}from"execa";import{applyEdits as Eo,modify as Co}from"jsonc-parser";function $o(e,t,n=!1){let r=n?"dependencies":"devDependencies",o=n?"devDependencies":"dependencies",i=JSON.parse(e),s=/^[ \t]+(?=")/m.exec(e)?.[0],a={insertSpaces:!s?.includes(" "),tabSize:s?.length??2,eol:e.includes(`\r
56
+ `)?`\r
57
+ `:`
58
+ `};for(let{name:c,version:p}of t){if(i[r]?.[c]!==p||i[o]?.[c]!==void 0||!n&&(i.peerDependencies?.[c]||i.optionalDependencies?.[c])){if(n)continue;throw new Error(`The declaration for ${c} changed. Run add again to review it.`)}e=Eo(e,Co(e,[o,c],p,{formattingOptions:a})),e=Eo(e,Co(e,[r,c],void 0,{formattingOptions:a}))}return e}async function ra(e,t,n){let r=na.join(e,"package.json"),o=qt.readFileSync(r,"utf8"),i=$o(o,n);qt.writeFileSync(r,i);try{await Gn(t,t==="pnpm"?["install","--no-frozen-lockfile"]:["install"],{cwd:e,env:t==="yarn"?{YARN_ENABLE_IMMUTABLE_INSTALLS:"false"}:void 0})}catch(s){let a=qt.readFileSync(r,"utf8"),c=a===i?o:$o(a,n,!0);if(a!==c&&(qt.writeFileSync(r,c),t!=="yarn")){let p=t==="npm"?"--package-lock-only":"--lockfile-only";try{await Gn(t,["install",p,"--ignore-scripts",...t==="pnpm"?["--no-frozen-lockfile"]:[]],{cwd:e})}catch(u){throw new Error(`Dependency promotion failed: ${s instanceof Error?s.message:s}. Run ${t} install in ${e} to sync the restored declarations. Lockfile update failed: ${u instanceof Error?u.message:u}.`)}}throw s}}async function Yn(e,t,n,r=[]){if(e=Array.from(new Set(e)),!e.length&&!r.length)return;let o=K("Installing dependencies.",{silent:n.silent}).start(),i=t.resolvedPaths.cwd;try{let s=await q(i);e.length&&await Gn(s,[s==="npm"?"install":"add",...s==="npm"?["--save"]:[],...e],{cwd:i}),r.length&&await ra(i,s,r)}catch(s){throw o.stop(),s}o.stopAndPersist({symbol:d.cyan("\u2714")})}import{execa as oa}from"execa";async function Ao(e,t,n){if(e=Array.from(new Set(e)),!e?.length)return;n={silent:!1,...n};let r=K("Installing development dependencies.",{silent:n.silent})?.start();try{let o=await q(t.resolvedPaths.cwd);await oa(o,[o==="npm"?"install":"add",o==="npm"?"--save-dev":"-D",...e],{cwd:t.resolvedPaths.cwd})}catch(o){throw r?.stop(),o}r?.stopAndPersist({symbol:d.cyan("\u2714")})}function Ro(e,t,n,r){if(!URL.canParse(e))return;let o=new URL(e);if(["registry.npmjs.org","registry.yarnpkg.com"].includes(o.hostname))return;let i=o.pathname.replace(/%2f/gi,"/").replace(/%40/gi,"@"),s=/\/(@tiptap-pro\/[\w.-]+)(?=\/-\/|:|\/?$)/.exec(i)?.[1];if(!s||r&&s!==r)return;let a=o.origin==="https://registry.tiptap.dev";if(a||n.includes(s))return{name:s,code:t,route:a?"tiptap":"mirror"}}function sa(e,t){if(!(e instanceof Error))return;let n=["stderr"in e&&e.stderr,"stdout"in e&&e.stdout].filter(i=>typeof i=="string"||Buffer.isBuffer(i)),r=ia(n.map(String).join(`
59
+ `).trim()||e.message);if(/\bELIFECYCLE\b|\bLifecycle script\b|\bnpm (?:ERR!|error) command sh -c\b/i.test(r))return;let o=r.split(/\r?\n/);for(let[i,s]of o.entries()){let a=/\bYN0035: [│ ]*(@tiptap-pro\/[\w.-]+)@npm:/.exec(s)?.[1];if(a){let f=/\bYN0035: [│ ]*Response Code: (401|403)\b/.exec(o[i+1]??"")?.[1],y=/\bYN0035: [│ ]*Request Method: GET$/.test(o[i+2]??""),S=/\bYN0035: [│ ]*Request URL: (https?:\/\/\S+)/.exec(o[i+3]??"")?.[1];if(f&&y&&S){let P=Ro(S,f,t,a);if(P)return P}}if(/Command (?:failed|was killed)\b/i.test(s))continue;let c=/\b(?:E|ERR_PNPM_FETCH_)(401|403)\b|\b(401|403)\s+(?:Unauthorized|Forbidden)\b|\s-\s+(401|403)\b/i.exec(s),p=/\bYN00(?:33|41)\b/i.test(s),u=/^error (?:Error: )?https?:\/\/\S+: (Unauthorized|Forbidden)\s*$/i.exec(s);if(!c&&!p&&!u)continue;let m=u?u[1].toLowerCase()==="forbidden"?"403":"401":c?.slice(1).find(Boolean),g=/https?:\/\/[^\s"'<>]+/i.exec(s)?.[0];if(g){let f=Ro(g,m,t);if(f)return f}else if(p){let f=/\bYN00(?:33|41):\s*(?:│\s*)?(@tiptap-pro\/[\w.-]+)@npm:/.exec(s)?.[1];if(f&&t.includes(f))return{name:f,code:m}}}}async function No(e,t){let{interactive:n}=t,r=!1;for(let o of e){async function i(s){for(;;)try{await s();return}catch(a){let c=sa(a,o.privateNpmPackages);if(!c)throw a;let p=o.config.resolvedPaths.cwd,u=`The package registry rejected access to ${c.name}${c.code?` with HTTP ${c.code}`:""}.`,m=c.route==="mirror"?"mirror":await ho(p);if(!c.route&&m==="public")throw a;if(m==="mirror")throw new Error(`${u} Authenticate with the registry configured for @tiptap-pro in ${p}, check access to this package, then repeat the install.`);let g=`${u} Check that your account can download the package. Sign in again, then repeat the install. https://tiptap.dev/docs/guides/pro-extensions
60
+ ${await Vt(p)}`;if(!n||r)throw new Error(g);r=!0;try{await Ln([c.name],p,{interactive:n})}catch{throw new Error(g)}}}await i(()=>Yn(o.dependencies,o.config,t)),o.promotions.length&&await i(()=>Yn([],o.config,t,o.promotions)),await i(()=>Ao(o.devDependencies,o.config,t))}}async function aa(e,t,n){let r=await _r(e);Te(r);let i=(t.overrideImports?null:await Pr(t))?.tiptapUi,s=new Map(r.map(u=>[u.name,u])),a=new Map;function c(u,m){let g=s.get(u);if(!g)throw new Error(`Registry item ${u} is missing.`);let f=g.type==="registry:ui"&&i?i:m,y=a.get(f);if(y||(y=new Set,a.set(f,y)),!y.has(g)){y.add(g);for(let S of g.registryDependencies??[])c(S,f)}}if(i&&i.resolvedPaths.cwd!==t.resolvedPaths.cwd)for(let u of e)c(u,t);else a.set(t,new Set(r));let p=[];for(let[u,m]of a){let g=[...m];p.push({config:u,items:g,dependencies:g.flatMap(f=>f.dependencies??[]),devDependencies:g.flatMap(f=>f.devDependencies??[]),privateNpmPackages:[...new Set(g.flatMap(f=>f.meta?.privateNpmPackages??[]))]})}if(n)for(let u of p)u.devDependencies=Lr(u.devDependencies,n.framework.name);return p}async function ca(e,t,n,r){if(e){let c=ge.safeParse(e.meta?.editor);if(!c.success)throw new Error(`The registry must declare a valid editor module for ${e.name}.`);let p=c.data;if(!e.files?.some(m=>m.path===p))throw new Error("The template must ship its declared editor.");let u=[...n.values()].find(m=>m.registryPath===p);if(!u)throw new Error("The template editor is missing from the install plan.");return u}if(!t)return;let o=Hn.resolve(r.resolvedPaths.cwd,t);if(!/\.[jt]sx?$/.test(o)||o.endsWith(".d.ts"))throw new Error("Choose a JavaScript or TypeScript editor file.");let i=await we(o,r);if(n.has(i))throw new Error("Choose an editor outside the feature setup files.");let s=await le(i);if(s===null)throw new Error(`Editor file does not exist: ${t}`);let a={path:o,realPath:i,before:s,after:s,status:"identical"};return n.set(i,a),a}async function la(e,t,n,r,o,i,s,a=!1){let c,p;if(!e.length)return{collaboration:c,extensionSetup:p};let u=n.find(w=>w.type==="registry:template"&&t.includes(w.name)),m=e.every(w=>w.integration.kind==="files")?void 0:await ca(u,i,r,o),g=[...r.values()],f=await ko(u,m,g,o),y=g.filter(w=>w.status==="conflict"),S=new Set(e.flatMap(w=>[...w.items,...Object.values(w.frameworkItems??{}).flat()])),P=new Set(n.filter(w=>S.has(w.name)).flatMap(w=>w.files?.map(k=>k.path)??[])),v=new Set(e.flatMap(({integration:w})=>w.kind==="collaboration"?[w.config,w.tokenRoute]:[]));for(let w of g){let k=w.registryPath;w.status==="conflict"&&a&&k&&P.has(k)&&!v.has(k)&&w!==m?w.status="update":(t.length===0||t.length===1&&u||k&&(P.has(k)||u?.files?.some(C=>C.path===k)))&&so(w)}for(let w of e){let{integration:k}=w,C=new Set(n.filter(h=>w.items.includes(h.name)).flatMap(h=>h.files?.map(x=>x.path)??[]));if(k.kind==="editor-extension"){if(!C.has(k.extension))throw new Error("The extension module must belong to the feature.");p=vo(k,r,m,o.resolvedPaths.cwd)}else if(k.kind==="collaboration"){if(!C.has(k.wrapper)||!C.has(k.config))throw new Error("The Collaboration wrapper and configuration must belong to the feature.");let h=y.find(x=>u?.files?.some(b=>b.path===x.registryPath&&b.type==="registry:page"));c=To(k,r,m,o,y.some(x=>x.registryPath===k.tokenRoute),h&&Hn.relative(o.resolvedPaths.cwd,h.path),f)}}let A=c??p;if(s&&u&&m&&A&&A.status!=="pending"){let w=await So(o,m);if(r.has(w.realPath))throw new Error(`Registry files and the Vite editor both target ${w.path}.`);r.set(w.realPath,w),A.entryPath=Hn.relative(o.resolvedPaths.cwd,w.path)}return{collaboration:c,extensionSetup:p}}async function Xn(e,t,n={}){let r=(n.features??[]).map(f=>et.parse(f)),o=n.projectInfo!==void 0?n.projectInfo:await z(t.resolvedPaths.cwd,{forFeature:r.length>0}),i=r.flatMap(f=>[...f.items,...o&&f.frameworkItems?.[o.framework.name]||[]]),s=[...new Set([...e,...i])],a=await aa(s,t,o),c=new Map,p=[];for(let f of a){let y=await Io(f.dependencies,f.devDependencies,f.config,e.length===0?r[0]?.label:void 0),S=y.dependencies.length||y.devDependencies.length||y.promotions.length?f.privateNpmPackages:[];p.push({config:f.config,...y,privateNpmPackages:S});for(let P of await ao(f.items.flatMap(v=>v.files??[]),f.config,f.config.resolvedPaths.cwd===t.resolvedPaths.cwd?o:void 0)){let v=c.get(P.realPath);if(v&&v.after!==P.after)throw new Error(`Registry items provide different contents for ${P.path}.`);c.set(P.realPath,P)}}let{collaboration:u,extensionSetup:m}=await la(r,e,a.flatMap(f=>f.items),c,t,n.editorPath,!!(n.isNewProject&&o?.framework.name==="vite"),n.overwrite),g=await lo([...c.values()].map(f=>f.path),t,o?.framework);if(g.change){if(c.has(g.change.realPath))throw new Error(`Registry files and stylesheet imports both target ${g.change.path}.`);c.set(g.change.realPath,g.change)}return{files:[...c.values()],packages:p,styles:g.result,collaboration:u,extensionSetup:m}}async function Gt(e,t,n){let r=K("Checking registry",{silent:n.silent}).start(),o=await Xn(e,t,n).finally(()=>r.stop()),i=n.interactive??(!n.silent&&se());for(let a of o.packages)a.privateNpmPackages.length&&await yo(a.privateNpmPackages,a.config.resolvedPaths.cwd,{interactive:i});await No(o.packages,{...n,interactive:i});let s=await co(o.files,t.resolvedPaths.cwd,n);if(s.errors.length){let a=s.errors.map(({file:c,error:p})=>` ${c}: ${p}`).join(`
37
61
  `);throw new Error(`Installation incomplete. ${s.filesCreated.length} files created, ${s.filesUpdated.length} updated.
38
- ${i}`)}return{...s,styles:o.styles}}import qt from"path";import{createTwoFilesPatch as ys}from"diff";function or(e,t,n){let r=typeof n=="string"?e.files.filter(o=>o.path===qt.resolve(t,n)):e.files;if(typeof n=="string"&&!r.length)throw new Error(`The installation does not include ${n}. Run add --dry-run to list the target paths.`);for(let o of r){let s=qt.relative(t,o.path);n&&o.status!=="identical"?a.log(ys(o.before===null?"/dev/null":`a/${s}`,`b/${s}`,o.before??"",o.after)):a.log(`${o.status.padEnd(10)} ${s}`)}if(typeof n!="string"){for(let o of e.packages){let s=qt.relative(t,o.config.resolvedPaths.cwd)||".";if(o.dependencies.length&&a.log(`Dependencies in ${s}: ${o.dependencies.join(", ")}`),o.promotions.length){let i=o.promotions.map(({name:c,version:l})=>`${c}@${l}`);a.log(`Move to dependencies in ${s}: ${i.join(", ")}`)}o.devDependencies.length&&a.log(`Dev dependencies in ${s}: ${o.devDependencies.join(", ")}`)}e.styles.success||a.warn(e.styles.message)}}function ge(e){return e.split(/[-_]/).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}import nt from"process";function sr(){return nt.stdout.columns||80}function ir(e,t,n){let r=n?.borderColor||"gray",o=n?.padding!==!1,s="",i="",c="",l="",d="-",u="",w=sr(),f=Math.min(w-4,80),h=p[r],A=h(s+d.repeat(f-2)+i),v=h(c+d.repeat(f-2)+l),b=h(u),S=[];o&&S.push(""),S.push(A),S.push(`${b}${" ".repeat(f-2)}${b}`);let _=Math.floor((f-4-Jt(e).length)/2),T=e.padStart(_+Jt(e).length).padEnd(f-4);return S.push(`${b} ${T} ${b}`),S.push(`${b}${" ".repeat(f-2)}${b}`),t.forEach(E=>{let m=Jt(E).length,y=f-4-m,P=E+" ".repeat(Math.max(0,y));S.push(`${b} ${P} ${b}`)}),t.length>0&&S.push(`${b}${" ".repeat(f-2)}${b}`),S.push(v),o&&S.push(""),S}function rt(e,t){let n=t?[t]:[];return ir(`${e}`,n,{borderColor:"gray"})}function ot(e,t){return ir(`\u26A0\uFE0F ${e}`,t,{borderColor:"yellow"})}function ee(e){e.forEach(t=>a.log(t))}function Jt(e){return e.replace(/\x1b\[[0-9;]*m/g,"")}function st(e,t){let n=[];return n.push(""),n.push(p.cyan(e)),n.push(""),t.forEach(r=>{n.push(` \u2022 ${r}`)}),n.push(""),n}function it(){nt.stdout.write("\x1B[2J\x1B[0f"),nt.platform==="win32"&&nt.stdout.write("\x1B[2J\x1B[3J\x1B[H")}function Gt(){let e=Math.min(sr()-4,80);return p.gray("-".repeat(e))}import{existsSync as ar}from"fs";import cr from"path";function pr(e){let t=e.name;return t===g["next-app"].name||t===g["next-pages"].name?"NEXT_PUBLIC_":t===g.astro.name?"PUBLIC_":t===g.vite.name||t===g["tanstack-start"].name||t===g["react-router"].name?"VITE_":(t===g.laravel.name||t===g.manual.name,"")}function lr(e){if(!e?.resolvedPaths?.styles)return"scss";let t=e.resolvedPaths.styles,n=cr.join(t,"_variables.scss"),r=cr.join(t,"_variables.css");return ar(r)?"css":(ar(n),"scss")}function mr(e,t){let n=e?.name||"unknown",r=t?.resolvedPaths?.styles?.includes("/src/"),o=t?.resolvedPaths?.components?.includes("/src/"),s="your main CSS file",i="./styles/";switch(n){case g["next-app"].name:o?(s="src/app/globals.css",i="../styles/"):r?(s="app/globals.css",i="../src/styles/"):(s="app/globals.css",i="../styles/");break;case g["next-pages"].name:o||r?(s="src/styles/globals.css",i="./"):(s="styles/globals.css",i="./");break;case g.vite.name:s="src/index.css",i="./styles/";break;case g["react-router"].name:s="src/index.css",i="./styles/";break;case g["tanstack-start"].name:s="src/index.css",i="./styles/";break;case g.astro.name:r?(s="src/layouts/Layout.astro",i="../styles/"):(s="src/layouts/Layout.astro",i="../../styles/");break;case g.laravel.name:s="resources/css/app.css",i="../styles/";break;case g.manual.name:default:o||r?(s="src/index.css",i="./styles/"):(s="your main CSS file",i="./styles/");break}return{cssFile:s,importPath:i}}function at(e,t){let n=lr(t),{cssFile:r,importPath:o}=mr(e,t),s=["The editor requires these style imports:","",`Add to ${p.cyan(r)}:`,"",p.yellow(` @import '${o}_variables.${n}';`),p.yellow(` @import '${o}_keyframe-animations.${n}';`),"","Without these imports, the editor will not display correctly.","",`Setup guide: ${p.cyan("https://tiptap.dev/docs/ui-components/getting-started/style")}`],i=ot("Action Required: Import Styles",s);ee(i)}function ct(e){let t=pr(e),n=["The Notion-like template requires environment variables for collaborative features:","",p.yellow(`${t}TIPTAP_COLLAB_DOC_PREFIX`)+" - Document prefix (required)",p.yellow(`${t}TIPTAP_COLLAB_APP_ID`)+" - Document Server App ID (required)",p.yellow(`${t}TIPTAP_COLLAB_TOKEN`)+" - JWT token for collaboration (required)",p.yellow(`${t}TIPTAP_AI_APP_ID`)+" - AI App ID (required)",p.yellow(`${t}TIPTAP_AI_TOKEN`)+" - JWT token for AI (required)","","Get these credentials from your account at cloud.tiptap.dev","",`Setup guide: ${p.cyan("https://tiptap.dev/docs/ui-components/templates/notion-like-editor")}`],r=ot("Action Required: Environment Setup",n);ee(r)}function pt(e,t){let n=pr(e),r=lr(t),{cssFile:o,importPath:s}=mr(e,t),i=["The Notion-like template is a complete editor application that requires","additional configuration before it can be used:","",p.cyan("1. Import Required Styles"),` Add to ${p.yellow(o)}:`,p.gray(` @import '${s}_variables.${r}';`),p.gray(` @import '${s}_keyframe-animations.${r}';`),"",p.cyan("2. Add Environment Variables (for collaborative features)")," Add to your .env file:",p.gray(` ${n}TIPTAP_COLLAB_DOC_PREFIX - Document prefix`),p.gray(` ${n}TIPTAP_COLLAB_APP_ID - Document Server App ID`),p.gray(` ${n}TIPTAP_COLLAB_TOKEN - JWT token for collaboration`),p.gray(` ${n}TIPTAP_AI_APP_ID - AI App ID`),p.gray(` ${n}TIPTAP_AI_TOKEN - JWT token for AI`),"",`Get credentials at ${p.cyan("https://cloud.tiptap.dev")}`,`Setup guide: ${p.cyan("https://tiptap.dev/docs/ui-components/templates/notion-like-editor")}`],c=ot("Next Steps: Configure your Editor",i);ee(c)}function lt(){a.log(""),a.log(p.cyan("\u2192 Table Node integration guide:")),a.log(` ${p.dim("https://tiptap.dev/docs/ui-components/node-components/table-node#usage")}`),a.log("")}var bs=Y.object({components:Y.array(Y.string()).optional(),cwd:Y.string(),path:Y.string().optional(),silent:Y.boolean(),overwrite:Y.boolean(),dryRun:Y.boolean().optional(),diff:Y.union([Y.boolean(),Y.string().min(1,"Provide a path or use bare --diff.")]).optional()}),Ts=1e3,ur=92,ks=48,Is=4,mt={emptyRegistry:p.red("\u274C No components or templates found"),operationCancelled:p.gray("Operation cancelled")},Ht={icon:{cursor:p.cyan("\u25B8"),checked:p.cyan("\u25C9"),unchecked:"\u25CB"},style:{highlight:e=>p.cyan(e),message:e=>e,answer:e=>""},prefix:{done:p.cyan("\u2714"),idle:p.cyan("?")}};function Ss(e){return e?.replace(/\s+/g," ").trim()??""}function Cs(e,t){let n=e.split(" "),r=[],o="";for(let s of n){let i=o?`${o} ${s}`:s;i.length>t&&o?(r.push(o),o=s):o=i}return o&&r.push(o),r}function Es(){let e=process.stdout.columns;return e?Math.max(ks,Math.min(ur,e-Is)):ur}function As(e){let t=Yt(e);return e?.includes("light")||e?.includes("open-source")?"Open Source - MIT":t}function Rs(e){let t=As(e.plans),n=`${p.bold(ge(e.name))} ${p.dim(`(${t})`)}:`,r=Ss(e.description);if(!r)return n;let o=Cs(r,Es()).map(s=>` ${s}`);return[n,...o].join(`
39
- `)}function Yt(e){if(!e?.length)return"Free";if(e.includes("light")||e.includes("open-source"))return"Open source (MIT)";let t=me.find(r=>e.includes(r));if(!t)return"Free";let n=`${t[0].toUpperCase()}${t.slice(1)}`;return t==="start"?`${n} plan \u2022 Trial`:`${n} plan`}function $s(e,t){return t?e.filter(n=>t.includes(n.name)):e}function Xt(e){for(let t=0;t<e;t++)process.stdout.write("\x1B[1A"),process.stdout.write("\x1B[2K")}var Ns=e=>({templates:e.filter(t=>t.type==="registry:template"),newComponents:e.filter(t=>t.isNew===!0),ui:e.filter(t=>t.type==="registry:ui"),primitives:e.filter(t=>t.type==="registry:ui-primitive"),uiUtils:e.filter(t=>t.type==="registry:ui-utils"),nodes:e.filter(t=>t.type==="registry:node")});async function js(e,t=!0){let n="What would you like to integrate?",r=[],o=e.ui.length===0&&e.nodes.length===0&&e.newComponents.length===0;if(e.templates.length===0||r.push({name:"Templates - Full editor applications",value:"templates"}),o||r.push({name:"UI Components - Individual editor building blocks",value:"components"}),r.length===0)return a.break(),console.log(mt.emptyRegistry),null;try{t&&console.log(Gt());let i=await we({message:p.reset(n),pageSize:Ts,theme:Ht,choices:r});return t&&console.log(Gt()),i}catch{return Xt(4),console.log(mt.operationCancelled),null}}async function _s(e,t){let n=[];if(!t)return n;let r=(s,i)=>{let c=s.filter(l=>t.includes(l.name));c.length>0&&(n.push(new he("")),n.push(new he(p.whiteBold(` ${i}`))),c.forEach(l=>{let d=Yt(l.plans),w=ge(l.name).padEnd(35);n.push({name:`${w} ${p.dim(d)}`,value:l.name})}),n.push(new he(" ")))};return((s,i)=>{let c=s.filter(l=>t.includes(l.name));c.length>0&&(n.push(new he("")),n.push(new he(p.whiteBold(` ${i}`))),c.forEach(l=>{let d=Yt(l.plans),w=ge(l.name).padEnd(35),f=l.description?`
40
- ${p.dim(l.description)}`:"";n.push({name:`${w} ${p.dim(d)}${f}`,value:l.name})}),n.push(new he(" ")))})(e.newComponents,"NEW COMPONENTS"),r(e.ui,"UI COMPONENTS"),r(e.nodes,"NODE COMPONENTS"),r(e.primitives,"PRIMITIVES"),n}async function Os(e,t){let n=await _s(e,t);if(n.length===0)return[];try{a.log(""),a.log(p.cyan(" Press Space to select \u2022 A to toggle all \u2022 Enter to confirm"));let r=await vs({message:"Choose UI components to install:",pageSize:20,choices:n,theme:Ht,validate:o=>o.length===0?"Select at least one component (use Space to select, then Enter to confirm)":!0});return r&&r.length>0&&(a.log(""),a.log(p.cyan("Selected components:")),r.forEach(o=>{a.log(` ${p.cyan("\u2022")} ${ge(o)}`)})),a.log(""),r||[]}catch{return Xt(25),console.log(mt.operationCancelled),[]}}async function Ds(e){try{let t=e.map(r=>({name:Rs(r),value:r.name}));a.log("");let n=await we({message:"Choose an editor template to install:",pageSize:20,choices:t,theme:Ht});return n&&(a.log(""),a.log(p.cyan("Selected template:")),a.log(` ${p.cyan("\u2022")} ${ge(n)}`)),a.log(""),n?[n]:[]}catch{return Xt(25),console.log(mt.operationCancelled),[]}}async function Zt(e,t=!0){if(e.components?.length)return e.components;let n;try{n=await Q()}catch(i){if(i instanceof Error&&i.message.includes("You are not authorized")){if(!await Se([{name:"unknown",plans:["start"]}],e.cwd))return a.error("Authentication failed. Cannot proceed with component selection."),[];try{n=await Q()}catch{return a.break(),W(new Error("[prompts] - Failed to fetch registry index after authentication.")),[]}}else return a.break(),W(i),[]}if(!n)return a.break(),W(new Error("[prompts] - Failed to fetch registry index.")),[];let r=Ns(n),o=await js(r,t);if(!o)return[];let s=n.filter(i=>!(i.hide??!1)).map(i=>i.name);switch(o){case"components":return await Os(r,s)||[];case"templates":{let i=$s(r.templates,s);return await Ds(i)||[]}default:return[]}}var dr=new xs().name("add").description("add Tiptap UI components or templates as source code to your project").argument("[components...]","the components to add").option("-o, --overwrite","overwrite existing files.",!1).option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).option("--dry-run","preview files and dependencies without installing them.").option("--diff [path]","show changes to all files or one destination path.").option("-p, --path <path>","the path to add the component to.").option("-s, --silent","mute output.",!1).action(async(e,t)=>{try{let n=bs.parse({...t,components:e,cwd:ws.resolve(t.cwd)}),r=n.dryRun||n.diff!==void 0,{errors:o,config:s}=await dn(n);if(o["1"])throw new Error(`No package.json found in ${n.cwd}. Run tiptap init to create a project before adding or previewing components.`);if(!s)throw new Error(`Failed to read config at ${n.cwd}.`);if(!n.components?.length&&(n.silent||r))throw new Error("Specify the registry items to add.");if(!n.components?.length){it();let u=rt("Tiptap UI Components","Install UI components or templates as editable source code in your project");ee(u);let w=st("What are Tiptap UI Components?",["React UI components that help you develop an editor","They install as source code (not npm packages) in your src/components/","UI components are a foundation for customization rather than a fixed library"]);ee(w),await Ps({message:p.reset(`Press ${p.cyan("Enter")} to add components or templates...`),theme:{prefix:{done:"",idle:""}}}),a.log(""),a.log(""),a.log("")}if(n.components?.length||(n.components=await Zt(n)),!n.components?.length)return;let i=await Q();if(!i)throw new Error("Failed to fetch registry index.");let c=n.components.map(u=>{let w=i.find(f=>f.name===u);return{name:u,plans:w?.plans||[]}});if(r){ae(c);let u=await Vt(n.components,s);or(u,n.cwd,n.diff);return}if(!await Se(c,n.cwd))throw new Error("Authenticate and accept the Pro license before installing paid components.");let l=await tt(n.components,s,n);if(n.silent)return;for(let[u,w]of[["Created",l.filesCreated],["Updated",l.filesUpdated],["Skipped",l.filesSkipped]])if(w.length){a.log(`${u} ${w.length} file${w.length===1?"":"s"}`);for(let f of w)a.log(` ${f}`)}Qe(l.styles);let d=await U(n.cwd);d&&(n.components.includes("notion-like-editor")?l.styles.success?ct(d.framework):pt(d.framework,s):l.styles.success||at(d.framework,s)),n.components.includes("table-node")&&lt()}catch(n){a.break(),W(n)}});import{existsSync as Fs}from"fs";import Us from"path";import{Command as Ms}from"commander";var ut={name:"@tiptap/cli",version:"3.20.0",description:"Tiptap CLI",publishConfig:{access:"public"},author:{name:"tiptap",url:"https://github.com/ueberdosis/tiptap"},files:["dist"],keywords:["cli","components","nextjs","react","templates","tiptap","@tiptap/cli","ui"],license:"SEE LICENSE IN LICENSE.md",type:"module",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"}},bin:"./dist/index.js",scripts:{dev:"tsup --watch",build:"tsup",test:"vitest run","test:watch":"vitest",typecheck:"tsc --noEmit",clean:"rm -rf dist","start:dev":"cross-env TIPTAP_REGISTRY_URL=http://localhost:3000 node dist/index.js","start:prod":"cross-env TIPTAP_REGISTRY_URL=https://template.tiptap.dev node dist/index.js",start:"node dist/index.js","pub:beta":"pnpm build && pnpm publish --no-git-checks --access public --tag beta","pub:release":"pnpm build && pnpm publish --access public"},dependencies:{"@antfu/ni":"^30.6.0","@babel/core":"^7.29.7","@babel/parser":"^7.29.9","@babel/plugin-transform-typescript":"^7.29.9","@inquirer/core":"^11.2.1","@inquirer/figures":"^2.0.9","@inquirer/prompts":"^8.7.3","@inquirer/type":"^4.2.0","ansi-escapes":"^7.3.0",chalk:"^5.6.2",commander:"^14.0.3",conf:"^15.1.0",cosmiconfig:"^9.0.2",diff:"^9.0.0",execa:"^9.6.1","fast-glob":"^3.3.3","fs-extra":"^11.4.1","https-proxy-agent":"^9.1.0","jsonc-parser":"^3.3.1","node-fetch":"^3.3.2",ora:"^9.4.1",postcss:"^8.5.32","postcss-scss":"^4.0.9",recast:"^0.23.21",semver:"^7.8.6","ts-morph":"^28.0.0","tsconfig-paths":"^4.2.0",yaml:"^2.9.1","yoctocolors-cjs":"^2.1.3",zod:"^4.6.5"},devDependencies:{"@babel/plugin-transform-typescript":"^7.26.5","@types/babel__core":"^7.20.5","@types/conf":"^3.0.3","@types/fs-extra":"^11.0.4","@types/prompts":"^2.4.9","@types/semver":"^7.8.0","cross-env":"^10.1.0",sass:"^1.105.1",tsup:"^8.5.1","type-fest":"^5.10.0",typescript:"^5.9.3",vitest:"^4.1.11"}};var fr=new Ms().name("info").description("get information about your project").option("-c, --cwd <cwd>","the working directory",process.cwd()).option("--json","print project diagnostics as JSON").action(async e=>{let t=Us.resolve(e.cwd),n=await U(t),r=await Z(t).catch(()=>null);if(e.json){let o=r&&n&&Wt(n.framework,r);console.log(JSON.stringify({cliVersion:ut.version,cwd:t,project:n,packageManager:await Ut(t,{withFallback:!0}),installedVersions:Object.fromEntries(["next","react","@tiptap/core"].map(s=>[s,xe(t,s)])),stylesheet:o&&Fs(o)?o:null,aliases:r?.aliases??null,registryOrigin:new URL(be()).origin},null,2));return}a.info("> project info"),console.log(n),a.break(),r&&(a.info("> config"),console.log(r))});import{Command as Bs,InvalidArgumentError as hr}from"commander";function Ws(e){let t=e.startsWith("registry:")?e:`registry:${e}`,n=Le.safeParse(t);if(!n.success)throw new hr(`Unknown registry type "${e}".`);return n.data}function gr(e){let t=Number(e);if(!/^\d+$/.test(e)||!Number.isSafeInteger(t))throw new hr("Use a nonnegative integer.");return t}function zs(e,t,n){let r=t.trim().toLowerCase().split(/\s+/),o=e.filter(i=>{if(i.hide||n.type&&i.type!==n.type)return!1;let c=`${i.name} ${i.description??""}`.toLowerCase();return r.every(l=>c.includes(l))}),s=n.limit===void 0?void 0:n.offset+n.limit;return{total:o.length,items:o.slice(n.offset,s).map(i=>({name:i.name,type:i.type,description:i.description??null,plans:i.plans??[],addCommand:`pnpm dlx @tiptap/cli add ${i.name}`}))}}var yr=new Bs("search").description("search public registry entries").argument("[query...]","words to match in the name or description").option("--type <type>","filter by registry type, such as node or template",Ws).option("--limit <count>","maximum number of results",gr).option("--offset <count>","number of matching entries to skip",gr,0).option("--json","print results as JSON").action(async(e,t)=>{let n=zs(await Q(),e.join(" "),{type:t.type,limit:t.limit,offset:t.offset});if(t.json){console.log(JSON.stringify(n,null,2));return}console.log(`${n.items.length} of ${n.total} matching entries`);for(let r of n.items)console.log(`
41
- ${r.name} ${r.type} ${r.plans.join(", ")}`),r.description&&console.log(r.description),console.log(r.addCommand)});import{Command as Ks}from"commander";function Vs(e){let t=(e.files??[]).map(r=>typeof r=="string"?{path:r,type:e.type,target:null}:{path:r.path,type:r.type,target:r.target||null}),n=t.flatMap(({type:r,target:o})=>r!=="registry:page"||!o||!/^(?:src\/)?app\/(?:.*\/)?page\.[jt]sx?$/.test(o)?[]:[o.replace(/^(?:src\/)?app/,"").replace(/\/page\.[jt]sx?$/,"")||"/"]);return{name:e.name,type:e.type,description:e.description??null,plans:e.plans??[],routes:n,links:e.meta?.links??{},dependencies:e.dependencies??[],devDependencies:e.devDependencies??[],registryDependencies:e.registryDependencies??[],files:t,addCommand:`pnpm dlx @tiptap/cli add ${e.name}`}}var wr=new Ks("view").description("inspect a registry item and its direct dependencies").argument("<name>","registry item name").option("--source","retrieve file contents from the component endpoint").option("--json","print item metadata as JSON").action(async(e,t)=>{let n=(await Q()).find(o=>o.name===e&&!o.hide);if(!n)throw new Error(`No public registry entry named "${e}".`);if(t.source){ae([n]);let[o]=await Ft([`components/${encodeURIComponent(e)}.json`]),s=Fe.parse(o);if(s.name!==e)throw new Error(`The registry returned a different item for "${e}".`);ae([s]),console.log(JSON.stringify(s,null,2));return}let r=Vs(n);if(t.json){console.log(JSON.stringify(r,null,2));return}console.log(`${r.name} ${r.type} ${r.plans.join(", ")}`),r.description&&console.log(r.description);for(let[o,s]of[["Routes",r.routes],["Dependencies",r.dependencies],["Development dependencies",r.devDependencies],["Registry dependencies",r.registryDependencies],["Files",r.files.map(i=>i.target?`${i.path} -> ${i.target}`:i.path)]])s.length&&console.log(`
62
+ ${a}`)}return{...s,styles:o.styles,collaboration:o.collaboration,extensionSetup:o.extensionSetup}}import Zn from"path";import{createTwoFilesPatch as pa}from"diff";function jo(e,t,n){let r=typeof n=="string"?e.files.filter(o=>o.path===Zn.resolve(t,n)):e.files;if(typeof n=="string"&&!r.length)throw new Error(`The installation does not include ${n}. Run add --dry-run to list the target paths.`);for(let o of r){let i=Zn.relative(t,o.path);n&&o.status!=="identical"&&o.status!=="keep"?l.log(pa(o.before===null?"/dev/null":`a/${i}`,`b/${i}`,o.before??"",o.after)):l.log(`${o.status.padEnd(10)} ${i}`)}if(typeof n!="string"){for(let o of e.packages){let i=Zn.relative(t,o.config.resolvedPaths.cwd)||".";if(o.dependencies.length&&l.log(`Dependencies in ${i}: ${o.dependencies.join(", ")}`),o.promotions.length){let s=o.promotions.map(({name:a,version:c})=>`${a}@${c}`);l.log(`Move to dependencies in ${i}: ${s.join(", ")}`)}o.devDependencies.length&&l.log(`Dev dependencies in ${i}: ${o.devDependencies.join(", ")}`),o.privateNpmPackages.length&&l.log(`Your package manager needs registry access to install ${o.privateNpmPackages.join(", ")}.`)}e.styles.success||l.warn(e.styles.message)}}function ae(e){return e.split(/[-_]/).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}import{existsSync as Fo}from"fs";import Oo from"path";function Do(e){let t=e.name;return t===T["next-app"].name||t===T["next-pages"].name?"NEXT_PUBLIC_":t===T.astro.name?"PUBLIC_":t===T.vite.name||t===T["tanstack-start"].name||t===T["react-router"].name?"VITE_":(t===T.laravel.name||t===T.manual.name,"")}function _o(e){if(!e?.resolvedPaths?.styles)return"scss";let t=e.resolvedPaths.styles,n=Oo.join(t,"_variables.scss"),r=Oo.join(t,"_variables.css");return Fo(r)?"css":(Fo(n),"scss")}function Lo(e,t){let n=e?.name||"unknown",r=t?.resolvedPaths?.styles?.includes("/src/"),o=t?.resolvedPaths?.components?.includes("/src/"),i="your main CSS file",s="./styles/";switch(n){case T["next-app"].name:o?(i="src/app/globals.css",s="../styles/"):r?(i="app/globals.css",s="../src/styles/"):(i="app/globals.css",s="../styles/");break;case T["next-pages"].name:o||r?(i="src/styles/globals.css",s="./"):(i="styles/globals.css",s="./");break;case T.vite.name:i="src/index.css",s="./styles/";break;case T["react-router"].name:i="src/index.css",s="./styles/";break;case T["tanstack-start"].name:i="src/index.css",s="./styles/";break;case T.astro.name:r?(i="src/layouts/Layout.astro",s="../styles/"):(i="src/layouts/Layout.astro",s="../../styles/");break;case T.laravel.name:i="resources/css/app.css",s="../styles/";break;case T.manual.name:default:o||r?(i="src/index.css",s="./styles/"):(i="your main CSS file",s="./styles/");break}return{cssFile:i,importPath:s}}function Yt(e,t){let n=_o(t),{cssFile:r,importPath:o}=Lo(e,t),i=["The editor requires these style imports:","",`Add to ${d.cyan(r)}:`,"",d.yellow(` @import '${o}_variables.${n}';`),d.yellow(` @import '${o}_keyframe-animations.${n}';`),"","Without these imports, the editor will not display correctly.","",`Setup guide: ${d.cyan("https://tiptap.dev/docs/ui-components/getting-started/style")}`],s=Rt("Action Required: Import Styles",i);ye(s)}function Ht(e){let t=Do(e),n=["The Notion-like template requires environment variables for collaborative features:","",d.yellow(`${t}TIPTAP_COLLAB_DOC_PREFIX`)+" - Document prefix (required)",d.yellow(`${t}TIPTAP_COLLAB_APP_ID`)+" - Document Server App ID (required)",d.yellow(`${t}TIPTAP_COLLAB_TOKEN`)+" - JWT token for collaboration (required)",d.yellow(`${t}TIPTAP_AI_APP_ID`)+" - AI App ID (required)",d.yellow(`${t}TIPTAP_AI_TOKEN`)+" - JWT token for AI (required)","","Get these credentials from your account at cloud.tiptap.dev","",`Setup guide: ${d.cyan("https://tiptap.dev/docs/ui-components/templates/notion-like-editor")}`],r=Rt("Action Required: Environment Setup",n);ye(r)}function Xt(e,t){let n=Do(e),r=_o(t),{cssFile:o,importPath:i}=Lo(e,t),s=["The Notion-like template is a complete editor application that requires","additional configuration before it can be used:","",d.cyan("1. Import Required Styles"),` Add to ${d.yellow(o)}:`,d.gray(` @import '${i}_variables.${r}';`),d.gray(` @import '${i}_keyframe-animations.${r}';`),"",d.cyan("2. Add Environment Variables (for collaborative features)")," Add to your .env file:",d.gray(` ${n}TIPTAP_COLLAB_DOC_PREFIX - Document prefix`),d.gray(` ${n}TIPTAP_COLLAB_APP_ID - Document Server App ID`),d.gray(` ${n}TIPTAP_COLLAB_TOKEN - JWT token for collaboration`),d.gray(` ${n}TIPTAP_AI_APP_ID - AI App ID`),d.gray(` ${n}TIPTAP_AI_TOKEN - JWT token for AI`),"",`Get credentials at ${d.cyan("https://cloud.tiptap.dev")}`,`Setup guide: ${d.cyan("https://tiptap.dev/docs/ui-components/templates/notion-like-editor")}`],a=Rt("Next Steps: Configure your Editor",s);ye(a)}function Zt(){l.log(""),l.log(d.cyan("\u2192 Table Node integration guide:")),l.log(` ${d.dim("https://tiptap.dev/docs/ui-components/node-components/table-node#usage")}`),l.log("")}import Ko from"path";import{confirm as fa,select as ga}from"@inquirer/prompts";import{InvalidArgumentError as ha,Option as ya}from"commander";import{promises as Ce}from"fs";import ue from"path";import{confirm as ua}from"@inquirer/prompts";import da from"fast-glob";import{ts as lt}from"ts-morph";var ma="https://tiptap.dev/docs/editor/getting-started/install/react";function er(e){let t=Fe(e,!1);if(!t)throw new Error(`Run this command in a project with a package.json. Check ${e}.`);if(!t.dependencies?.react&&!t.devDependencies?.react&&!t.peerDependencies?.react&&!t.optionalDependencies?.react)throw new Error(`Install React in this project before adding an editor feature. ${ma}`)}async function Qt(e,t,n){return er(e),ne(e,t,{featureOnly:!0,projectInfo:n})}async function Uo(e,t){let n=await Ce.readFile(ue.resolve(e,t),"utf8");return!n.includes("@tiptap/react")||!n.includes("useEditor")?!1:lt.createSourceFile(t,n,lt.ScriptTarget.Latest).statements.some(o=>{if(!lt.isImportDeclaration(o)||!lt.isStringLiteral(o.moduleSpecifier)||o.moduleSpecifier.text!=="@tiptap/react"||o.importClause?.isTypeOnly)return!1;let i=o.importClause?.namedBindings;return i&&lt.isNamedImports(i)&&i.elements.some(s=>!s.isTypeOnly&&(s.propertyName??s.name).text==="useEditor")})}function Qn(e,t){let n=ue.relative(e,t);return n!==""&&n!==".."&&!n.startsWith(`..${ue.sep}`)&&!ue.isAbsolute(n)}async function Mo(e,t){let n=await Ce.realpath(e),r=ue.dirname(await Ce.realpath(t));for(;Qn(n,r);){if(await Ce.stat(ue.join(r,"package.json")).then(o=>o.isFile(),()=>!1))return r;r=ue.dirname(r)}}async function Bo(e,t,n){if(t!==void 0){let i=ue.resolve(e,t),s=await Ce.realpath(i).catch(c=>{throw c.code!=="ENOENT"?c:new Error(`Cannot find the editor file ${t}.`)});if(!Qn(e,i)||!Qn(await Ce.realpath(e),s)||!/\.[jt]sx?$/i.test(i)||/\.d\.ts$/i.test(i)||!(await Ce.stat(s)).isFile())throw new Error("--editor needs a JavaScript or TypeScript source file inside this project.");let a=await Mo(e,i);if(a)throw new Error(`The editor belongs to a workspace package. Run this command in ${a}.`);if(!await Uo(e,i))throw new Error(`${t} must import useEditor from @tiptap/react.`);return{editorPath:i,candidates:[]}}let r=await da("**/*.{js,jsx,ts,tsx}",{cwd:e,followSymbolicLinks:!1,onlyFiles:!0,ignore:["**/{node_modules,dist,build,coverage,public,out,vendor}/**","**/*.d.ts","**/*.{test,spec,stories}.*","**/{__tests__,__mocks__,e2e,.storybook}/**"]}),o=[];for(let i of r.sort())try{await Uo(e,i)&&!await Mo(e,ue.resolve(e,i))&&o.push(i)}catch(s){if(s.code!=="ENOENT")throw s}if(o.length===1&&n&&se()){let i=o[0];if(await ua({message:`Connect the feature to ${i}?`,default:!1}))return{editorPath:ue.resolve(e,i),candidates:o}}return{candidates:o}}function en(){return new ya("--with <id>","install a feature from the registry").argParser((e,t)=>{if(t!==void 0)throw new ha("Pass --with once per command. To install another feature, run add again.");return e})}function We(e,t="supported"){let n=e.meta?.featureSupport;return!n||typeof n!="object"||Array.isArray(n)?[]:Object.entries(n).filter(([r,o])=>o===t&&Qe.safeParse(r).success).map(([r])=>r)}function tn(e){return"integration"in e}async function pt(){try{return(await Me()).filter(tn)}catch(e){let t=e instanceof Error?e.message:"The catalog is unavailable.";return console.warn(`Could not load editor features. ${t}`),[]}}async function nr(e,t,n=process.cwd()){let r=e.find(i=>i.id===t);if(!r||tn(r))return r;let o=await de(n);throw new Error(`This CLI version cannot install feature "${t}". Run ${o} @tiptap/cli@latest view ${t}.`)}async function Wo(e,t){if(!se())return;let n=We(e);if(!n.length)return;let r=(t??await pt()).filter(i=>n.includes(i.id));if(!r.length)return;if(r.length===1){let i=r[0];return await fa({message:`Add ${i.label} to ${ae(e.name)}?`,default:!1})?i:void 0}let o=await ga({message:`Add an optional feature to ${ae(e.name)}?`,choices:[{name:"Skip optional features",value:""},...r.map(i=>({name:i.label,value:i.id}))],default:""});return r.find(i=>i.id===o)}async function ut(e,t,n=process.cwd()){let r=e.length?await he():[],o=e.map(p=>({name:p,plans:r.find(u=>u.name===p)?.plans??[]})),i=r.filter(p=>p.type==="registry:template"&&e.includes(p.name)),s=i.length===1?i[0]:void 0,a,c;if(t){let p=await Me();if(!p.length)throw new Error("This registry offers no features for this CLI.");if(a=await nr(p,t,n),!a)throw new Error(`Unknown feature "${t}". Available features: ${p.map(u=>u.id).join(", ")}.`);if(e.length&&!s)throw new Error("Choose one template with --with, or omit the positional arguments to install the feature on its own.");if(s)if(We(s,"built-in").includes(t))c=`${ae(s.name)} already includes ${a.label}.`,a=void 0;else if(We(s).includes(t)){if(a.integration.kind!=="files"&&!ge.safeParse(s.meta?.editor).success)throw new Error(`The registry must declare a valid editor module for ${s.name} to install ${a.label}.`)}else{let u=await de(n);throw new Error(`${ae(s.name)} does not declare support for ${a.label}. Run ${u} @tiptap/cli add --with ${t} to install it in your own editor.`)}}return{sources:o,template:s,feature:a,builtIn:c}}async function nn(e,t,n,r){return!e.feature||e.template||e.feature.integration.kind==="files"&&!n?{editorPath:void 0,candidates:[]}:Bo(t,n,r)}function tr(e){return/^[a-zA-Z0-9_./-]+$/.test(e)?e:"'"+e.replaceAll("'","'\\''")+"'"}async function Ve(e,t,n){if(!e)return;let r=n?.preview??!1,o=t.extensionSetup,i=t.collaboration,s=typeof n?.diff=="string";if(n&&typeof n.diff=="string"){let a=o??i;if(a?.status!=="pending"||!a.editorPath||Ko.resolve(n.cwd,a.editorPath)!==Ko.resolve(n.cwd,n.diff))return}if(!s&&n?.candidates&&!(o??i)?.editorPath&&e.integration.kind!=="files"){let a=n.candidates;l.log(a.length?"Choose an editor to connect:":"The CLI found no editor. After you create one, connect it with --editor.");for(let u of a)l.log(` ${u}`);let c=a.length?tr(a[0]):"<path>",p=n.pathOverride?` --path ${tr(n.pathOverride)}`:"";l.log(`${await de(n.cwd)} @tiptap/cli add --with ${e.id} --editor ${c}${p}`)}if(i&&(s?Vo(i):wa(i,r),i.suggestedTemplate)){let a=await de(n?.cwd??process.cwd()),c=n?.pathOverride?` --path ${tr(n.pathOverride)}`:"";l.log(`To connect the template with its original demo content, run ${a} @tiptap/cli add ${i.suggestedTemplate} --with ${e.id}${c}`)}if(o&&(o.editorPath?o.status==="pending"?(l.warn(`${e.label} needs a manual edit in ${o.editorPath}.`),o.reason&&l.log(o.reason),o.importPath&&l.log(`Import { ${o.exportName} } from "${o.importPath}" and add it to the editor's extensions array.`)):o.status==="unchanged"?l.log(`${o.editorPath} already uses ${e.label}.`):l.log(r?`The CLI will connect ${e.label} to ${o.editorPath}.`:`The CLI connected ${e.label} to ${o.editorPath}.`):l.log(`Import { ${o.exportName} } from ${o.extensionPath} and add it to your editor's extensions array.`),s||l.log(`Extension file ${o.extensionPath}`)),!s){for(let a of e.instructions??[])l.log(a);e.docs&&l.log(`Documentation ${e.docs}`)}}function Vo(e){l.warn(`Collaboration needs a manual edit in ${e.editorPath}.`),e.reason&&l.log(e.reason),e.patch&&l.log(e.patch)}function wa(e,t=!1){e.editorPath?e.status==="pending"?Vo(e):e.status==="unchanged"?l.log(`${e.editorPath} already uses Collaboration.`):l.log(t?`The CLI will connect Collaboration to ${e.editorPath}.`:`The CLI connected Collaboration to ${e.editorPath}.`):(e.reason&&l.warn(e.reason),l.log(`Import { withCollaboration } from ${e.wrapperPath} and wrap your editor component. Pass collaboration to its extensions, pass editable to useEditor, and disable StarterKit undoRedo.`)),l.log(`For live sync, set appId to the Document Server ID from your Tiptap Cloud trial or subscription in ${e.configPath}. Set defaultDocumentName to a stable document ID.`),e.customPagePath&&l.log(`Check that your custom route in ${e.customPagePath} renders the connected editor.`),e.tokenPath&&e.existingTokenRoute?l.log(`Check that your existing handler in ${e.tokenPath} authorizes the documentName in the POST body and returns { "token": "..." }.`):e.tokenPath?(l.log(`Connect authorizeDocument to your session and document permissions in ${e.tokenPath}.`),l.log("Set TIPTAP_AUTH_ENVIRONMENT_ID and TIPTAP_AUTH_PRIVATE_KEY on your server.")):(l.log(e.entryPath?`Your app opens the editor from ${e.entryPath}.`:"Render the wrapped editor where your app opens the document."),l.log('Point tokenEndpoint at your backend. It must authorize POST { "documentName": "..." } and return { "token": "..." }.')),l.log("After configuring access, open the same document in two sessions and type in one."),l.log("Document authentication https://tiptap.dev/docs/collaboration/getting-started/authenticate")}var ka=Q.object({components:Q.array(Q.string()).optional(),with:Q.string().min(1).optional(),editor:Q.string().min(1).optional(),cwd:Q.string(),path:Q.string().optional(),silent:Q.boolean(),overwrite:Q.boolean(),dryRun:Q.boolean().optional(),diff:Q.union([Q.boolean(),Q.string().min(1,"Provide a path or use bare --diff.")]).optional()}),Ta=1e3,zo=92,Sa=48,Ia=4,rn={emptyRegistry:d.red("\u274C No components or templates found"),operationCancelled:d.gray("Operation cancelled")},on={icon:{cursor:d.cyan("\u25B8"),checked:d.cyan("\u25C9"),unchecked:"\u25CB"},style:{highlight:e=>d.cyan(e),message:e=>e,answer:e=>""},prefix:{done:d.cyan("\u2714"),idle:d.cyan("?")}};function Ea(e){return e?.replace(/\s+/g," ").trim()??""}function Ca(e,t){let n=e.split(" "),r=[],o="";for(let i of n){let s=o?`${o} ${i}`:i;s.length>t&&o?(r.push(o),o=i):o=s}return o&&r.push(o),r}function $a(){let e=process.stdout.columns;return e?Math.max(Sa,Math.min(zo,e-Ia)):zo}function Aa(e){let t=rr(e);return e?.includes("light")||e?.includes("open-source")?"Open Source - MIT":t}function Ra(e){let t=Aa(e.plans),n=`${d.bold(ae(e.name))} ${d.dim(`(${t})`)}:`,r=Ea(e.description);if(!r)return n;let o=Ca(r,$a()).map(i=>` ${i}`);return[n,...o].join(`
63
+ `)}function rr(e){if(!e?.length)return"Free";if(e.includes("light")||e.includes("open-source"))return"Open source (MIT)";let t=_e.find(r=>e.includes(r));if(!t)return"Free";let n=`${t[0].toUpperCase()}${t.slice(1)}`;return t==="start"?`${n} plan \u2022 Trial`:`${n} plan`}function Na(e,t){return t?e.filter(n=>t.includes(n.name)):e}function or(e){for(let t=0;t<e;t++)process.stdout.write("\x1B[1A"),process.stdout.write("\x1B[2K")}var ja=e=>({templates:e.filter(t=>t.type==="registry:template"),newComponents:e.filter(t=>t.isNew===!0),ui:e.filter(t=>t.type==="registry:ui"),primitives:e.filter(t=>t.type==="registry:ui-primitive"),uiUtils:e.filter(t=>t.type==="registry:ui-utils"),nodes:e.filter(t=>t.type==="registry:node")});async function Fa(e,t,n=!0){let r="What would you like to integrate?",o=[],i=e.ui.length===0&&e.nodes.length===0&&e.newComponents.length===0;if(e.templates.length===0||o.push({name:"Templates - Full editor applications",value:"templates"}),i||o.push({name:"UI Components - Individual editor building blocks",value:"components"}),t&&o.push({name:"Features for your editor",value:"features"}),o.length===0)return l.break(),console.log(rn.emptyRegistry),null;try{n&&console.log(jn());let a=await je({message:d.reset(r),pageSize:Ta,theme:on,choices:o});return n&&console.log(jn()),a}catch{return or(4),console.log(rn.operationCancelled),null}}async function Oa(e,t){let n=[];if(!t)return n;let r=(i,s)=>{let a=i.filter(c=>t.includes(c.name));a.length>0&&(n.push(new ze("")),n.push(new ze(d.whiteBold(` ${s}`))),a.forEach(c=>{let p=rr(c.plans),m=ae(c.name).padEnd(35);n.push({name:`${m} ${d.dim(p)}`,value:c.name})}),n.push(new ze(" ")))};return((i,s)=>{let a=i.filter(c=>t.includes(c.name));a.length>0&&(n.push(new ze("")),n.push(new ze(d.whiteBold(` ${s}`))),a.forEach(c=>{let p=rr(c.plans),m=ae(c.name).padEnd(35),g=c.description?`
64
+ ${d.dim(c.description)}`:"";n.push({name:`${m} ${d.dim(p)}${g}`,value:c.name})}),n.push(new ze(" ")))})(e.newComponents,"NEW COMPONENTS"),r(e.ui,"UI COMPONENTS"),r(e.nodes,"NODE COMPONENTS"),r(e.primitives,"PRIMITIVES"),n}async function Da(e,t){let n=await Oa(e,t);if(n.length===0)return[];try{l.log(""),l.log(d.cyan(" Press Space to select \u2022 A to toggle all \u2022 Enter to confirm"));let r=await va({message:"Choose UI components to install:",pageSize:20,choices:n,theme:on,validate:o=>o.length===0?"Select at least one component (use Space to select, then Enter to confirm)":!0});return r&&r.length>0&&(l.log(""),l.log(d.cyan("Selected components:")),r.forEach(o=>{l.log(` ${d.cyan("\u2022")} ${ae(o)}`)})),l.log(""),r||[]}catch{return or(25),console.log(rn.operationCancelled),[]}}async function _a(e){try{let t=e.map(r=>({name:Ra(r),value:r.name}));l.log("");let n=await je({message:"Choose an editor template to install:",pageSize:20,choices:t,theme:on});return n&&(l.log(""),l.log(d.cyan("Selected template:")),l.log(` ${d.cyan("\u2022")} ${ae(n)}`)),l.log(""),n?[n]:[]}catch{return or(25),console.log(rn.operationCancelled),[]}}async function ir(e,t=!0){if(e.components?.length)return{components:e.components};let[n,r]=await Promise.all([he(),pt()]),o=ja(n),i=await Fa(o,r.length>0,t),s=n.filter(a=>!a.hide).map(a=>a.name);switch(i){case"features":{let a=await je({message:"Choose a feature for your editor",choices:r.map(c=>({name:c.label,value:c.id,description:c.description})),theme:on});return{components:[],feature:r.find(c=>c.id===a)}}case"components":return{components:await Da(o,s)};case"templates":{let a=Na(o.templates,s),c=await _a(a),p=a.find(m=>m.name===c[0]),u=p&&!e.dryRun&&!e.diff?await Wo(p,r):void 0;return{components:c,feature:u}}default:return{components:[]}}}var Jo=new Pa().name("add").description("add features, templates, or UI components to your project").argument("[components...]","the components to add").addOption(en()).option("--editor <path>","connect the feature to an existing editor file").option("-o, --overwrite","overwrite existing files.",!1).option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).option("--dry-run","preview files and dependencies without installing them.").option("--diff [path]","show changes to all files or one destination path.").option("-p, --path <path>","parent directory for installed components and feature files.").option("-s, --silent","mute output.",!1).action(async(e,t)=>{try{let n=ka.parse({...t,components:e,cwd:xa.resolve(t.cwd)}),r=n.dryRun||n.diff!==void 0,o=!n.silent&&se();if(n.editor&&e.length)throw new Error(`Choose either ${e.join(", ")} or --editor ${n.editor}.`);if(n.editor&&!n.with)throw new Error("Use --editor with --with <id>.");if(!n.with&&!e.length&&(!o||r))throw new Error("Specify the registry items to add or pass --with <id>.");let i=n.with,s=n.components??[];if(!s.length&&!i){Nt(),ye(At("Tiptap","Add a feature to your editor, install a template, or choose UI components.")),await ba({message:d.reset(`Press ${d.cyan("Enter")} to add a feature, template, or UI component...`),theme:{prefix:{done:"",idle:""}}}),l.log(""),l.log(""),l.log("");let A=await ir(n);if(s=A.components,i=A.feature?.id,!s.length&&!i)return}let a=await ut(s,i,n.cwd),{sources:c,feature:p,builtIn:u}=a;u&&!n.silent&&l.log(u);let m=!s.length&&!!p,g=await nn(a,n.cwd,n.editor,o&&!r),f=p?await z(n.cwd,{forFeature:!0}):void 0,y;if(m)y=await Qt(n.cwd,n.path,f);else{p&&er(n.cwd);let A=await vr(n,f);if(A.errors["1"])throw new Error(`No package.json found in ${n.cwd}. Run tiptap init to create a project before adding or previewing components.`);if(y=A.config,!y)throw new Error(`Failed to read config at ${n.cwd}.`)}let S={features:p?[p]:[],editorPath:g.editorPath,overwrite:n.overwrite,projectInfo:f};if(r){ke(c)&&Te(c);let A=await Xn(s,y,S);jo(A,n.cwd,n.diff),await Ve(p,A,{candidates:m?g.candidates:void 0,pathOverride:n.path,preview:!0,cwd:n.cwd,diff:n.diff});return}if(ke(c)&&!await $t(c,n.cwd,p?{interactive:o}:void 0))throw new Error("Authenticate and accept the Pro license before installing paid components.");let P=await Gt(s,y,{...n,...S,interactive:p?o:void 0});if(n.silent)return;for(let[A,w]of[["Created",P.filesCreated],["Updated",P.filesUpdated],["Skipped",P.filesSkipped]])if(w.length){l.log(`${A} ${w.length} file${w.length===1?"":"s"}`);for(let k of w)l.log(` ${k}`)}if(m){await Ve(p,P,{cwd:n.cwd,candidates:g.candidates,pathOverride:n.path});return}Bt(P.styles);let v=f??await z(n.cwd);v&&(s.includes("notion-like-editor")?P.styles.success?Ht(v.framework):Xt(v.framework,y):P.styles.success||Yt(v.framework,y)),s.includes("table-node")&&Zt(),await Ve(p,P)}catch(n){l.break(),X(n)}});import{existsSync as Ua}from"fs";import Ma from"path";import{Command as Ba}from"commander";var sn={name:"@tiptap/cli",version:"3.21.0",description:"Tiptap CLI",publishConfig:{access:"public"},author:{name:"tiptap",url:"https://github.com/ueberdosis/tiptap"},files:["dist"],keywords:["cli","components","nextjs","react","templates","tiptap","@tiptap/cli","ui"],license:"SEE LICENSE IN LICENSE.md",type:"module",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"}},bin:"./dist/index.js",scripts:{dev:"tsup --watch",build:"tsup",test:"vitest run","test:watch":"vitest",typecheck:"tsc --noEmit",clean:"rm -rf dist","start:dev":"cross-env TIPTAP_REGISTRY_URL=http://localhost:3000 node dist/index.js","start:prod":"cross-env TIPTAP_REGISTRY_URL=https://template.tiptap.dev node dist/index.js",start:"node dist/index.js","pub:beta":"pnpm build && pnpm publish --no-git-checks --access public --tag beta","pub:release":"pnpm build && pnpm publish --access public"},dependencies:{"@antfu/ni":"^30.6.0","@babel/core":"^7.29.7","@babel/parser":"^7.29.9","@babel/plugin-transform-typescript":"^7.29.9","@inquirer/core":"^11.2.1","@inquirer/figures":"^2.0.9","@inquirer/prompts":"^8.7.3","@inquirer/type":"^4.2.0","@npmcli/map-workspaces":"^5.0.3","ansi-escapes":"^7.3.0",chalk:"^5.6.2",commander:"^14.0.3",conf:"^15.1.0",cosmiconfig:"^9.0.2",diff:"^9.0.0",execa:"^9.6.1","fast-glob":"^3.3.3","fs-extra":"^11.4.1","https-proxy-agent":"^9.1.0","jsonc-parser":"^3.3.1","node-fetch":"^3.3.2",ora:"^9.4.1",postcss:"^8.5.32","postcss-scss":"^4.0.9",recast:"^0.23.21",semver:"^7.8.6","ts-morph":"^28.0.0","tsconfig-paths":"^4.2.0",yaml:"^2.9.1","yoctocolors-cjs":"^2.1.3",zod:"^4.6.5"},devDependencies:{"@babel/plugin-transform-typescript":"^7.26.5","@types/babel__core":"^7.20.5","@types/conf":"^3.0.3","@types/fs-extra":"^11.0.4","@types/prompts":"^2.4.9","@types/semver":"^7.8.0","cross-env":"^10.1.0",sass:"^1.105.1",tsup:"^8.5.1","type-fest":"^5.10.0",typescript:"^5.9.3",vitest:"^4.1.11"}};var qo=new Ba().name("info").description("get information about your project").option("-c, --cwd <cwd>","the working directory",process.cwd()).option("--json","print project diagnostics as JSON").action(async e=>{let t=Ma.resolve(e.cwd),n=await z(t),r=await ne(t).catch(()=>null);if(e.json){let o=r&&n&&On(n.framework,r);console.log(JSON.stringify({cliVersion:sn.version,cwd:t,project:n,packageManager:await Rn(t,{withFallback:!0}),installedVersions:Object.fromEntries(["next","react","@tiptap/core"].map(i=>[i,Ye(t,i)])),stylesheet:o&&Ua(o)?o:null,aliases:r?.aliases??null,registryOrigin:new URL(Ue()).origin},null,2));return}l.info("> project info"),console.log(n),l.break(),r&&(l.info("> config"),console.log(r))});import{Command as Ka,InvalidArgumentError as Yo}from"commander";function Wa(e){let t=e.startsWith("registry:")?e:`registry:${e}`,n=Pt.safeParse(t);if(!n.success)throw new Yo(`Unknown registry type "${e}".`);return n.data}function Go(e){let t=Number(e);if(!/^\d+$/.test(e)||!Number.isSafeInteger(t))throw new Yo("Use a nonnegative integer.");return t}function Va(e,t,n){let r=t.trim().toLowerCase().split(/\s+/),o=e.filter(s=>{if(s.hide||n.type&&s.type!==n.type)return!1;let a=`${s.name} ${s.description??""}`.toLowerCase();return r.every(c=>a.includes(c))}),i=n.limit===void 0?void 0:n.offset+n.limit;return{total:o.length,items:o.slice(n.offset,i).map(s=>({name:s.name,type:s.type,description:s.description??null,plans:s.plans??[],addCommand:`pnpm dlx @tiptap/cli add ${s.name}`}))}}var Ho=new Ka("search").description("search public registry entries").argument("[query...]","words to match in the name or description").option("--type <type>","filter by registry type, such as node or template",Wa).option("--limit <count>","maximum number of results",Go).option("--offset <count>","number of matching entries to skip",Go,0).option("--json","print results as JSON").action(async(e,t)=>{let n=Va(await he(),e.join(" "),{type:t.type,limit:t.limit,offset:t.offset});if(t.json){console.log(JSON.stringify(n,null,2));return}console.log(`${n.items.length} of ${n.total} matching entries`);for(let r of n.items)console.log(`
65
+ ${r.name} ${r.type} ${r.plans.join(", ")}`),r.description&&console.log(r.description),console.log(r.addCommand)});import{Command as za}from"commander";async function Ja(e){let t=We(e),n=t.length?(await pt()).filter(i=>t.includes(i.id)).map(i=>i.id):[],r=(e.files??[]).map(i=>typeof i=="string"?{path:i,type:e.type,target:null}:{path:i.path,type:i.type,target:i.target||null}),o=r.flatMap(({type:i,target:s})=>i!=="registry:page"||!s||!/^(?:src\/)?app\/(?:.*\/)?page\.[jt]sx?$/.test(s)?[]:[s.replace(/^(?:src\/)?app/,"").replace(/\/page\.[jt]sx?$/,"")||"/"]);return{name:e.name,type:e.type,description:e.description??null,plans:e.plans??[],routes:o,links:e.meta?.links??{},dependencies:e.dependencies??[],devDependencies:e.devDependencies??[],registryDependencies:e.registryDependencies??[],features:n,builtInFeatures:We(e,"built-in"),files:r,addCommand:`pnpm dlx @tiptap/cli add ${e.name}`}}var Xo=new za("view").description("inspect a registry item and its direct dependencies").argument("[name]","registry item name or feature id").option("--features","list all feature ids from the registry").option("--source","retrieve file contents from the component endpoint").option("--json","print item metadata as JSON").action(async(e,t)=>{if(t.features){if(e||t.source)throw new Error("Use view --features on its own or with --json.");let o=await Me();t.json?console.log(JSON.stringify(o.map(i=>i.id),null,2)):console.log(o.length?o.map(i=>tn(i)?i.id:`${i.id} (requires a newer CLI)`).join(`
66
+ `):"This registry offers no features for this CLI.");return}if(!e)throw new Error("Name a registry item or feature, or run view --features.");let n=(await he()).find(o=>o.name===e&&!o.hide);if(!n){let o=await Me(),i=await nr(o,e);if(!i)throw new Error(`No public registry entry named "${e}".${o.length?" Available features: "+o.map(a=>a.id).join(", ")+".":""}`);let s=`${await de(process.cwd())} @tiptap/cli add --with ${i.id}`;if(t.source)throw new Error(`To preview the feature files, run ${s} --diff in your React project.`);if(t.json)console.log(JSON.stringify({...i,addCommand:s},null,2));else{console.log(`${i.label} ${i.id}
67
+ ${i.description}`),console.log(`Registry items ${i.items.join(", ")}`);for(let[a,c]of Object.entries(i.frameworkItems??{}))console.log(`${a} ${c.join(", ")}`);for(let a of i.instructions)console.log(a);console.log(`Documentation ${i.docs}
68
+
69
+ ${s}`)}return}if(t.source){Te([n]);let[o]=await An([`components/${encodeURIComponent(e)}.json`]),i=bt.parse(o);if(i.name!==e)throw new Error(`The registry returned a different item for "${e}".`);Te([i]),console.log(JSON.stringify(i,null,2));return}let r=await Ja(n);if(t.json){console.log(JSON.stringify(r,null,2));return}console.log(`${r.name} ${r.type} ${r.plans.join(", ")}`),r.description&&console.log(r.description);for(let[o,i]of[["Routes",r.routes],["Dependencies",r.dependencies],["Development dependencies",r.devDependencies],["Registry dependencies",r.registryDependencies],["Optional features",r.features.map(s=>`--with ${s}`)],["Built-in features",r.builtInFeatures],["Files",r.files.map(s=>s.target?`${s.path} -> ${s.target}`:s.path)]])i.length&&console.log(`
42
70
  ${o}
43
- ${s.join(`
44
- `)}`);for(let[o,s]of Object.entries(r.links))typeof s=="string"&&console.log(`${o} ${s}`);console.log(`
45
- ${r.addCommand}`)});import Sr from"path";import{Command as hi}from"commander";import{confirm as yi,input as wi}from"@inquirer/prompts";import{z as X}from"zod";import Js from"path";import Pr from"fs-extra";async function vr(e){let t={};if(!Pr.existsSync(e.cwd)||!Pr.existsSync(Js.resolve(e.cwd,"package.json")))return t["1"]=!0,{errors:t,projectInfo:null};let n=L("Verifying framework.",{silent:e.silent}).start(),r=await U(e.cwd);(!r||r?.framework.name==="manual")&&(t["7"]=!0,n?.fail(),a.break(),r?.framework.links.installation&&a.error(`We could not detect a supported framework at ${p.cyan(e.cwd)}.
46
- Visit ${p.cyan(r?.framework.links.installation)} to manually configure your project.
47
- Once configured, you can use the cli to add components.`),a.break(),process.exit(1)),n?.stopAndPersist({symbol:p.cyan("\u2714"),text:`Verifying framework. Found ${p.cyan(r.framework.label)}.`});let o=L("Validating import alias.",{silent:e.silent}).start();return r?.aliasPrefix?o?.stopAndPersist({symbol:p.cyan("\u2714")}):(t["6"]=!0,o?.fail()),Object.keys(t).length>0&&(t["6"]&&(a.break(),a.error("No import alias found in your tsconfig.json file."),r?.framework.links.installation&&a.error(`Visit ${p.cyan(r?.framework.links.installation)} to learn how to set an import alias.`)),a.break(),process.exit(1)),{errors:t,projectInfo:r}}import Zs from"os";import ne from"path";import q from"fs-extra";import{execa as H}from"execa";import{parse as Qs}from"jsonc-parser";import{input as ei}from"@inquirer/prompts";import Gs from"path";import Qt from"fs-extra";import{isMap as Ys,isSeq as Hs,parseDocument as Xs}from"yaml";var dt="@parcel/watcher";function br(e){return e===dt||e.startsWith(`${dt}@`)||e.includes("*")}async function Tr(e){let t=Gs.join(e,"pnpm-workspace.yaml");if(!await Qt.pathExists(t))return;let n=Xs(await Qt.readFile(t,"utf8"));if(n.errors.length||["dangerouslyAllowAllBuilds","neverBuiltDependencies","onlyBuiltDependencies","onlyBuiltDependenciesFile","permissions"].some(s=>n.has(s)))return;let r=n.get("allowBuilds"),o=n.get("ignoredBuiltDependencies");if(Ys(r)&&!o){if(r.items.some(({key:s})=>br(String(s))))return;r.set(dt,!1)}else if(!r&&Hs(o)){if(o.items.some(s=>br(String(s))))return;o.add(dt)}else return;await Qt.writeFile(t,n.toString())}var ti="https://codeload.github.com/shadcn-ui/ui/tar.gz/main",ye={next:"next",vite:"vite","next-monorepo":"next-monorepo"},ni=(e,t="")=>ei({message:p.reset(e),default:t,required:!0,validate:n=>n.length>128?"Name should be less than 128 characters.":!0,theme:{prefix:{done:p.cyan("\u2714"),idle:"?"}}}),ri=async(e,t)=>{let n=`
48
- ${p.gray(" Use arrow-keys \u25B2\u25BC / [Return] to submit")}
49
- `;return we({message:p.reset(e),instructions:n,theme:{icon:{cursor:p.cyan("\u276F")},prefix:{done:p.cyan("\u2714"),idle:"?"}},choices:t})};async function kr(e){let t={srcDir:!1,reactCompiler:!1,...e},n=t.framework&&ye[t.framework]?t.framework:"next",r="latest";if(!t.framework&&!t.defaults){let c=`The path ${p.cyan(t.cwd)} does not contain a package.json file. Would you like to start a new project?`;n=await ri(c,[{name:"Next.js",value:"next"},{name:"Vite + React + TypeScript",value:"vite"}]),a.log("")}let o=t.name??(t.defaults?"my-app":await ni("What is your project named?","my-app")),s=await K(t.cwd,{withFallback:!0}),i=ne.join(t.cwd,o);return await oi(t.cwd,o),n===ye.next?await si(i,{version:r,cwd:t.cwd,packageManager:s,srcDir:!!t.srcDir,reactCompiler:!!t.reactCompiler}):n===ye.vite?await ii(i,{cwd:t.cwd,packageManager:s,projectName:o}):n===ye["next-monorepo"]&&await mi(i,{packageManager:s}),{projectPath:i,projectName:o,framework:n}}async function oi(e,t){try{await q.access(e,q.constants.W_OK)}catch{throw new Error(`Cannot create a project in ${e}. Check that the directory exists and is writable.`)}if(q.existsSync(ne.resolve(e,t,"package.json")))throw new Error(`A project named ${t} already exists in ${e}. Choose another name.`)}async function si(e,t){let n=L("Creating a new Next.js project. This may take a few minutes.").start(),r=["--empty","--tailwind","--eslint","--typescript","--app",t.srcDir?"--src-dir":"--no-src-dir","--no-import-alias",t.reactCompiler?"--react-compiler":"--no-react-compiler",`--use-${t.packageManager}`];(t.version.startsWith("15")||t.version.startsWith("latest")||t.version.startsWith("canary"))&&r.push("--turbopack");try{await H("npx",["--yes",`--package=create-next-app@${t.version}`,"--","create-next-app",e,"--silent",...r],{cwd:t.cwd}),t.packageManager==="pnpm"&&await Tr(e),await Ir(e),n.stopAndPersist({symbol:p.cyan("\u2714")})}catch(o){throw n?.fail("Something went wrong creating a new Next.js project."),o}}async function ii(e,t){let n=L("Creating a new Vite + React + TypeScript project. This may take a few minutes.").start();try{await H("npm",["create","vite@latest",t.projectName,"--","--template","react-ts"],{cwd:t.cwd}),await H(t.packageManager,["install"],{cwd:e}),await ai(e,t.packageManager),await Ir(e),n.stopAndPersist({symbol:p.cyan("\u2714")})}catch(r){n?.fail("Something went wrong creating a new Vite project."),W(r)}}async function ai(e,t){try{await pi(e),await li(e),await ci(e,t)}catch{a.warn("Failed to set up TypeScript path aliases, but project creation succeeded")}}async function ci(e,t){try{await H(t,[t==="npm"?"install":"add",t==="npm"?"--save-dev":"-D","@types/node"],{cwd:e})}catch{a.warn("Failed to install @types/node, but project creation succeeded")}}async function pi(e){let t=async n=>{let r=ne.join(e,n);if(!await q.pathExists(r))return;let o=await q.readFile(r,"utf-8"),s=Qs(o);s.compilerOptions={...s.compilerOptions,baseUrl:".",paths:{...s.compilerOptions?.paths||{},"@/*":["./src/*"]}};let i=JSON.stringify(s,null,2);await q.writeFile(r,i)};await t("tsconfig.json"),await t("tsconfig.app.json")}async function li(e){let t=ne.join(e,"vite.config.ts"),r=(await q.readFile(t,"utf-8")).replace("import { defineConfig } from 'vite'",`import { defineConfig } from 'vite'
71
+ ${i.join(`
72
+ `)}`);for(let[o,i]of Object.entries(r.links))typeof i=="string"&&console.log(`${o} ${i}`);console.log(`
73
+ ${r.addCommand}`)});import{existsSync as gc}from"fs";import ar from"path";import{Command as hc}from"commander";import{confirm as yc,input as wc}from"@inquirer/prompts";import{z as te}from"zod";async function Zo(e){let t=K("Verifying framework.",{silent:e.silent}).start(),n=await z(e.cwd);(!n||n?.framework.name==="manual")&&(t?.fail(),l.break(),n?.framework.links.installation&&l.error(`We could not detect a supported framework at ${d.cyan(e.cwd)}.
74
+ Visit ${d.cyan(n?.framework.links.installation)} to manually configure your project.
75
+ Once configured, you can use the cli to add components.`),l.break(),process.exit(1)),t?.stopAndPersist({symbol:d.cyan("\u2714"),text:`Verifying framework. Found ${d.cyan(n.framework.label)}.`});let r=K("Validating import alias.",{silent:e.silent}).start();return n.aliasPrefix||(r?.fail(),l.break(),l.error("No import alias found in your tsconfig.json file."),n.framework.links.installation&&l.error(`Visit ${d.cyan(n.framework.links.installation)} to learn how to set an import alias.`),l.break(),process.exit(1)),r?.stopAndPersist({symbol:d.cyan("\u2714")}),n}import Xa from"os";import xe from"path";import ee from"fs-extra";import{execa as ce}from"execa";import{parse as Za}from"jsonc-parser";import{input as Qa}from"@inquirer/prompts";import Je from"path";import qe from"fs-extra";import{execa as qa}from"execa";import{isMap as Ga,isSeq as Ya,parseDocument as Ha}from"yaml";var dt="@parcel/watcher";function Qo(e){return e===dt||e.startsWith(`${dt}@`)||e.includes("*")}async function sr(e){let t=Je.join(e,"pnpm-workspace.yaml");if(!await qe.pathExists(t))return;let n=Ha(await qe.readFile(t,"utf8"));if(n.errors.length||["dangerouslyAllowAllBuilds","neverBuiltDependencies","onlyBuiltDependencies","onlyBuiltDependenciesFile","permissions"].some(i=>n.has(i)))return;let r=n.get("allowBuilds"),o=n.get("ignoredBuiltDependencies");if(Ga(r)&&!o){if(r.items.some(({key:i})=>Qo(String(i))))return;r.set(dt,!1)}else if(!r&&Ya(o)){if(o.items.some(i=>Qo(String(i))))return;o.add(dt)}else return;await qe.writeFile(t,n.toString())}async function ei(e){let t="pnpm-workspace.yaml",n=Je.join(e,t);if(await qe.pathExists(n))return sr(e);for(let o=Je.dirname(e);;o=Je.dirname(o)){if(await qe.pathExists(Je.join(o,t)))return;if(o===Je.dirname(o))break}let{stdout:r}=await qa("pnpm",["--version"],{cwd:e});Number.parseInt(r,10)>=11&&await qe.writeFile(n,`allowBuilds:
76
+ '${dt}': false
77
+ `,{flag:"wx"})}var ec="https://codeload.github.com/shadcn-ui/ui/tar.gz/main",Ge={next:"next",vite:"vite","next-monorepo":"next-monorepo"},tc=(e,t="")=>Qa({message:d.reset(e),default:t,required:!0,validate:n=>n.length>128?"Name should be less than 128 characters.":!0,theme:{prefix:{done:d.cyan("\u2714"),idle:"?"}}}),nc=async(e,t)=>{let n=`
78
+ ${d.gray(" Use arrow-keys \u25B2\u25BC / [Return] to submit")}
79
+ `;return je({message:d.reset(e),instructions:n,theme:{icon:{cursor:d.cyan("\u276F")},prefix:{done:d.cyan("\u2714"),idle:"?"}},choices:t})};async function ti(e){let t={srcDir:!1,reactCompiler:!1,...e},n=t.framework&&Ge[t.framework]?t.framework:"next",r="latest";if(!t.framework&&!t.defaults){let a=`The path ${d.cyan(t.cwd)} does not contain a package.json file. Would you like to start a new project?`;n=await nc(a,[{name:"Next.js",value:"next"},{name:"Vite + React + TypeScript",value:"vite"}]),l.log("")}let o=t.name??(t.defaults?"my-app":await tc("What is your project named?","my-app")),i=await q(t.cwd,{withFallback:!0}),s=xe.join(t.cwd,o);return await rc(t.cwd,o),n===Ge.next?await oc(s,{version:r,cwd:t.cwd,packageManager:i,srcDir:!!t.srcDir,reactCompiler:!!t.reactCompiler}):n===Ge.vite?await ic(s,{cwd:t.cwd,packageManager:i,projectName:o}):n===Ge["next-monorepo"]&&await pc(s,{packageManager:i}),{projectPath:s,projectName:o,framework:n}}async function rc(e,t){try{await ee.access(e,ee.constants.W_OK)}catch{throw new Error(`Cannot create a project in ${e}. Check that the directory exists and is writable.`)}if(ee.existsSync(xe.resolve(e,t,"package.json")))throw new Error(`A project named ${t} already exists in ${e}. Choose another name.`)}async function oc(e,t){let n=K("Creating a new Next.js project. This may take a few minutes.").start(),r=["--empty","--tailwind","--eslint","--typescript","--app",t.srcDir?"--src-dir":"--no-src-dir","--no-import-alias",t.reactCompiler?"--react-compiler":"--no-react-compiler",`--use-${t.packageManager}`];(t.version.startsWith("15")||t.version.startsWith("latest")||t.version.startsWith("canary"))&&r.push("--turbopack");try{await ce("npx",["--yes",`--package=create-next-app@${t.version}`,"--","create-next-app",e,"--silent",...r],{cwd:t.cwd}),t.packageManager==="pnpm"&&await sr(e),await ni(e),n.stopAndPersist({symbol:d.cyan("\u2714")})}catch(o){throw n?.fail("Something went wrong creating a new Next.js project."),o}}async function ic(e,t){let n=K("Creating a new Vite + React + TypeScript project. This may take a few minutes.").start();try{await ce("npm",["create","vite@latest",t.projectName,"--","--template","react-ts"],{cwd:t.cwd}),t.packageManager==="pnpm"&&await ei(e),await ce(t.packageManager,["install"],{cwd:e}),await sc(e,t.packageManager),await ni(e),n.stopAndPersist({symbol:d.cyan("\u2714")})}catch(r){n?.fail("Something went wrong creating a new Vite project."),X(r)}}async function sc(e,t){try{await cc(e),await lc(e),await ac(e,t)}catch{l.warn("Failed to set up TypeScript path aliases, but project creation succeeded")}}async function ac(e,t){try{await ce(t,[t==="npm"?"install":"add",t==="npm"?"--save-dev":"-D","@types/node"],{cwd:e})}catch{l.warn("Failed to install @types/node, but project creation succeeded")}}async function cc(e){let t=async n=>{let r=xe.join(e,n);if(!await ee.pathExists(r))return;let o=await ee.readFile(r,"utf-8"),i=Za(o);i.compilerOptions={...i.compilerOptions,paths:{...i.compilerOptions?.paths||{},"@/*":["./src/*"]}};let s=JSON.stringify(i,null,2);await ee.writeFile(r,s)};await t("tsconfig.json"),await t("tsconfig.app.json")}async function lc(e){let t=xe.join(e,"vite.config.ts"),r=(await ee.readFile(t,"utf-8")).replace("import { defineConfig } from 'vite'",`import { defineConfig } from 'vite'
50
80
  import path from 'path'`).replace("plugins: [react()]",`plugins: [react()],
51
81
  resolve: {
52
82
  alias: {
53
83
  '@': path.resolve(__dirname, './src')
54
84
  }
55
- }`);await q.writeFile(t,r)}async function mi(e,t){let n=L("Creating a new Next.js monorepo. This may take a few minutes.").start();try{await ui(e),await H(t.packageManager,["install"],{cwd:e}),await di(e),n?.stopAndPersist({symbol:p.cyan("\u2714"),text:`Created a new Next.js monorepo at ${p.cyan(e)}`})}catch(r){n?.fail("Something went wrong creating a new Next.js monorepo."),W(r)}}async function ui(e){let t=ne.join(Zs.tmpdir(),`tiptap-framework-${Date.now()}`);await q.ensureDir(t);let n=await fetch(ti);if(!n.ok)throw new Error("The starter project could not be downloaded. Please check your connection and try again.");let r=ne.resolve(t,"framework.tar.gz");await q.writeFile(r,Buffer.from(await n.arrayBuffer())),await H("tar",["-xzf",r,"-C",t,"--strip-components=2","ui-main/templates/monorepo-next"]);let o=ne.resolve(t,"monorepo-next");await q.move(o,e),await q.remove(t)}async function di(e){let t=process.cwd();try{await H("git",["--version"],{cwd:e}),await H("git",["init"],{cwd:e}),await H("git",["add","-A"],{cwd:e}),await H("git",["commit","-m","Initial commit"],{cwd:e}),await H("cd",[t])}catch{a.warn("Failed to initialize git repository, but project creation succeeded")}}var fi=`# Simple template
85
+ }`);await ee.writeFile(t,r)}async function pc(e,t){let n=K("Creating a new Next.js monorepo. This may take a few minutes.").start();try{await uc(e),await ce(t.packageManager,["install"],{cwd:e}),await dc(e),n?.stopAndPersist({symbol:d.cyan("\u2714"),text:`Created a new Next.js monorepo at ${d.cyan(e)}`})}catch(r){n?.fail("Something went wrong creating a new Next.js monorepo."),X(r)}}async function uc(e){let t=xe.join(Xa.tmpdir(),`tiptap-framework-${Date.now()}`);await ee.ensureDir(t);let n=await fetch(ec);if(!n.ok)throw new Error("The starter project could not be downloaded. Please check your connection and try again.");let r=xe.resolve(t,"framework.tar.gz");await ee.writeFile(r,Buffer.from(await n.arrayBuffer())),await ce("tar",["-xzf",r,"-C",t,"--strip-components=2","ui-main/templates/monorepo-next"]);let o=xe.resolve(t,"monorepo-next");await ee.move(o,e),await ee.remove(t)}async function dc(e){let t=process.cwd();try{await ce("git",["--version"],{cwd:e}),await ce("git",["init"],{cwd:e}),await ce("git",["add","-A"],{cwd:e}),await ce("git",["commit","-m","Initial commit"],{cwd:e}),await ce("cd",[t])}catch{l.warn("Failed to initialize git repository, but project creation succeeded")}}var mc=`# Simple template
56
86
 
57
87
  Integrate the Tiptap open source editor with UI components and open source extensions.
58
88
 
@@ -163,7 +193,7 @@ The Simple Editor Template and all included components are MIT licensed. You're
163
193
 
164
194
  You can extend this template with additional features as your needs grow.
165
195
 
166
- Paid Tiptap Cloud features will have matching UI components that integrate just as easily! No rework needed.`,gi=`# Notion-like Editor
196
+ Paid Tiptap Cloud features will have matching UI components that integrate just as easily! No rework needed.`,fc=`# Notion-like Editor
167
197
 
168
198
  A Notion-style Tiptap editor with collaboration, AI, and rich UI components. Fully customizable and easy to integrate.
169
199
 
@@ -355,5 +385,5 @@ The built-in AI tools let you:
355
385
 
356
386
  ## Extendability
357
387
 
358
- This template is designed to grow with your needs. New Tiptap Cloud features will be seamlessly compatible with the same UI system\u2014no rewrites required.`;async function Ir(e,t){let n=ne.join(e,"README.md"),r={"simple-editor":fi,"notion-like-editor":gi},o=t&&t in r?r[t]:"";try{o.trim()&&await q.writeFile(n,o,"utf-8")}catch{}}var xi=X.object({cwd:X.string(),components:X.array(X.string()).optional(),silent:X.boolean(),isNewProject:X.boolean(),name:X.string().min(1).max(128).regex(/^[a-z0-9][a-z0-9._-]*$/,"Use a project name with lowercase letters, digits, dots, underscores, or hyphens.").optional(),defaults:X.boolean().optional(),srcDir:X.boolean().optional(),reactCompiler:X.boolean().optional(),framework:X.string().optional().refine(e=>!e||ye[e],{message:"Invalid framework. Please use 'next' or 'vite'."})}),en=(e,t=!0)=>yi({message:p.reset(e),default:t,theme:{prefix:{done:p.cyan("\u2714"),idle:"?"}}}),Cr=new hi().name("init").description("initialize your project and install Tiptap UI components as source code").argument("[components...]","the components to add").option("-f, --framework <framework>","the framework to use. (next, vite)").option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).option("--name <name>","name the new project").option("--defaults","use scaffold defaults and install only the named components",!1).option("-s, --silent","mute output.",!1).option("--src-dir","use the src directory when creating a new project (specific to next).",!1).option("--react-compiler","enable React Compiler when creating a new project (specific to next).",!1).action(async(e,t)=>{try{if(!t.defaults&&!t.silent){it();let d=rt("Tiptap UI Components","Install UI components or templates as editable source code in your project");ee(d);let u=st("What are Tiptap UI Components?",["React UI components that help you develop an editor","They install as source code (not npm packages) in your src/components/","UI components are a foundation for customization rather than a fixed library"]);ee(u),await wi({message:p.reset(`Press ${p.cyan("Enter")} to initialize a project...`),theme:{prefix:{done:"",idle:""}}}),a.log("")}let n=xi.parse({...t,cwd:Sr.resolve(t.cwd),isNewProject:!1,components:e}),r=await Pi(n);if(n.silent)return;let o=[...r.filesCreated,...r.filesUpdated,...r.filesSkipped];if(!o.length)return;let s=o.some(d=>d.includes("notion")),i=r.selectedComponents.includes("simple-editor"),c=s?"Notion template":i?"Simple editor template":"Components";a.log(`${p.green("\u2714")} ${c}: ${r.filesCreated.length} created, ${r.filesUpdated.length} updated, ${r.filesSkipped.length} skipped`);let l=r.projectInfo?.framework;l&&r.styles&&(Qe(r.styles),r.styles.success?s&&ct(l):s?pt(l,r.config):at(l,r.config)),r.selectedComponents.includes("table-node")&&lt(),a.break()}catch(n){a.break(),W(n)}});async function Pi(e){let{skipPreflight:t,components:n,silent:r}=e,o={...e},s,i=(b,S,_=[],T)=>({config:b,projectInfo:S,framework:s,selectedComponents:_,filesCreated:T?.filesCreated||[],filesUpdated:T?.filesUpdated||[],filesSkipped:T?.filesSkipped||[],styles:T?.styles}),c=null;if(!t){let b=await vr(e);if(b.errors["1"]){let{projectPath:_,framework:T}=await kr(e);o={...o,cwd:_,isNewProject:!0},s=T,a.log("")}c=b.projectInfo}if(s==="next-monorepo"){let b=Sr.resolve(o.cwd,"apps/web"),S=await Z(b);return i(S,c)}c??=await U(o.cwd);let l=await ln(o.cwd,c),d=l?await bi(l):await vi(await Z(o.cwd),e.defaults);a.log("");let u=n||[];if(!u.length){if(!(!e.defaults&&await en("Would you like to add a template or UI components to your project?"))){let S=await oe(o.cwd,d);return i(S,c)}if(u=await Zt({...o,overwrite:!1},!0),!u.length){let S=await oe(o.cwd,d);return i(S,c)}}let w=await Q(),f=u.map(b=>{let S=w.find(_=>_.name===b);return{name:b,plans:S?.plans||[]}});if(!await Se(f,o.cwd,{interactive:!e.defaults}))throw new Error("Authenticate and accept the Pro license before installing paid components.");let A=await oe(o.cwd,d),v=await tt(u,A,{overwrite:!1,interactive:e.defaults?!1:void 0,silent:r,isNewProject:o.isNewProject||c?.framework.name==="next-app"});return i(A,c,u,v)}async function vi(e,t=!1){a.log(""),a.log(p.cyan("Project Configuration")),a.log("");let n=t?e?.tsx??!0:await en(`Would you like to use ${p.cyan("TypeScript")} (recommended)?`,e?.tsx??!0),r=t?e?.rsc??!0:await en(`Are you using ${p.cyan("React Server Components")}?`,e?.rsc??!0);return se.parse({rsc:r,tsx:n,aliases:{components:Pt,contexts:vt,hooks:bt,tiptapIcons:Tt,lib:je,tiptapExtensions:kt,tiptapNodes:It,tiptapUi:St,tiptapUiPrimitives:Ct,tiptapUiUtils:Et,styles:At}})}async function bi(e){return se.parse({rsc:e?.rsc,tsx:e?.tsx,aliases:e?.aliases})}import{Command as Ti}from"commander";process.on("SIGINT",()=>process.exit(0));process.on("SIGTERM",()=>process.exit(0));async function ki(){let e=new Ti().name("tiptap").description("add components and dependencies to your project").version(ut.version||"1.0.0","-v, --version","display the CLI version number");e.addCommand(Cr).addCommand(dr).addCommand(fr).addCommand(yr).addCommand(wr).addCommand(jn).addCommand(On).addCommand(_n).addCommand(Dn),await e.parseAsync()}ki().catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exitCode=1});
388
+ This template is designed to grow with your needs. New Tiptap Cloud features will be seamlessly compatible with the same UI system\u2014no rewrites required.`;async function ni(e,t){let n=xe.join(e,"README.md"),r={"simple-editor":mc,"notion-like-editor":fc},o=t&&t in r?r[t]:"";try{o.trim()&&await ee.writeFile(n,o,"utf-8")}catch{}}var xc=te.object({cwd:te.string(),components:te.array(te.string()).optional(),with:te.string().min(1).optional(),editor:te.string().min(1).optional(),silent:te.boolean(),isNewProject:te.boolean(),name:te.string().min(1).max(128).regex(/^[a-z0-9][a-z0-9._-]*$/,"Use a project name with lowercase letters, digits, dots, underscores, or hyphens.").optional(),defaults:te.boolean().optional(),srcDir:te.boolean().optional(),reactCompiler:te.boolean().optional(),framework:te.string().optional().refine(e=>!e||Ge[e],{message:"Invalid framework. Please use 'next' or 'vite'."})}),cr=(e,t=!0)=>yc({message:d.reset(e),default:t,theme:{prefix:{done:d.cyan("\u2714"),idle:"?"}}}),ri=new hc().name("init").description("initialize a project and install editor features, templates, or UI components").argument("[components...]","the components to add").addOption(en()).option("--editor <path>","connect the feature to an existing editor file").option("-f, --framework <framework>","the framework to use. (next, vite)").option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).option("--name <name>","name the new project").option("--defaults","use scaffold defaults and install the requested items",!1).option("-s, --silent","mute output.",!1).option("--src-dir","use the src directory when creating a new project (specific to next).",!1).option("--react-compiler","enable React Compiler when creating a new project (specific to next).",!1).action(async(e,t)=>{try{let n=xc.parse({...t,defaults:t.defaults||!!(t.with&&(t.silent||!se())),cwd:ar.resolve(t.cwd),isNewProject:!1,components:e});if(n.editor&&!n.with)throw new Error("Use --editor with --with <id>.");!n.with&&!n.defaults&&!n.silent&&(Nt(),ye(At("Tiptap","Create a project or add a feature, template, or UI component to an existing app.")),await wc({message:d.reset(`Press ${d.cyan("Enter")} to initialize a project...`),theme:{prefix:{done:"",idle:""}}}),l.log(""));let r=await Pc(n);if(!r||n.silent)return;r.framework&&l.log(`Project directory ${r.config.resolvedPaths.cwd}`);let o=[...r.filesCreated,...r.filesUpdated,...r.filesSkipped];if(!o.length&&!r.feature)return;let i=o.some(p=>p.includes("notion")),s=r.selectedComponents.includes("simple-editor"),a=i?"Notion template":s?"Simple editor template":r.feature?.label??"Components";l.log(`${d.green("\u2714")} ${a}: ${r.filesCreated.length} created, ${r.filesUpdated.length} updated, ${r.filesSkipped.length} skipped`);let c=r.projectInfo?.framework;c&&r.styles&&r.selectedComponents.length&&(Bt(r.styles),r.styles.success?i&&Ht(c):i?Xt(c,r.config):Yt(c,r.config)),r.selectedComponents.includes("table-node")&&Zt(),await Ve(r.feature,r,{cwd:r.config.resolvedPaths.cwd,candidates:r.candidates}),l.break()}catch(n){l.break(),X(n)}});async function Pc(e){let{skipPreflight:t,components:n,silent:r}=e;if(e.editor&&n?.length)throw new Error(`Choose either ${n.join(", ")} or --editor ${e.editor}.`);let o=e.with?await ut(n??[],e.with,e.cwd):void 0;o?.builtIn&&!r&&l.log(o.builtIn);let i={...e},s,a=(k,C,h=[],x,b,I)=>({config:k,projectInfo:C,framework:s,selectedComponents:h,filesCreated:x?.filesCreated||[],filesUpdated:x?.filesUpdated||[],filesSkipped:x?.filesSkipped||[],styles:x?.styles,collaboration:x?.collaboration,extensionSetup:x?.extensionSetup,feature:b,candidates:I});if(!t&&!gc(ar.join(e.cwd,"package.json"))){if(e.editor)throw new Error(`Cannot connect --editor ${e.editor} before the project exists in ${e.cwd}.`);let{projectPath:k,framework:C}=await ti(e);i={...i,cwd:k,isNewProject:!0},s=C,l.log("")}if(s==="next-monorepo"){let k=ar.resolve(i.cwd,"apps/web");if(!o&&!n?.length){let C=await ne(k);return a(C,null)}i.cwd=k}let c=n??[],p=e.with,u=!e.defaults&&!r&&se();if(!c.length&&!p&&u&&await cr("Would you like to add a template, feature, or UI components to your project?")){let k=await ir({...i,overwrite:!1});c=k.components,p=k.feature?.id}let m=o??await ut(c,p,i.cwd),{sources:g,feature:f}=m,y=!!f&&!c.length,S=!f&&!t&&!s?await Zo(i):await z(i.cwd,{forFeature:!!f});async function P(){let k=await xr(i.cwd,S),C=k?await vc(k):await bc(await ne(i.cwd),e.defaults);return Oe(i.cwd,C)}let v=await nn(m,i.cwd,e.editor,u),A=f?await Qt(i.cwd,void 0,S):await P();if(!c.length&&!f)return a(A,S);if(ke(g)&&!await $t(g,i.cwd,{interactive:u}))throw new Error("Authenticate and accept the Pro license before installing paid components.");let w=await Gt(c,A,{overwrite:!1,features:f?[f]:[],projectInfo:f?S:void 0,editorPath:v.editorPath,interactive:u,silent:r,isNewProject:i.isNewProject||S?.framework.name==="next-app"});return a(A,S,c,w,f,y?v.candidates:void 0)}async function bc(e,t=!1){l.log(""),l.log(d.cyan("Project Configuration")),l.log("");let n=t?e?.tsx??!0:await cr(`Would you like to use ${d.cyan("TypeScript")} (recommended)?`,e?.tsx??!0),r=t?e?.rsc??!0:await cr(`Are you using ${d.cyan("React Server Components")}?`,e?.rsc??!0);return fe.parse({rsc:r,tsx:n,aliases:{components:un,contexts:dn,hooks:mn,tiptapIcons:fn,lib:yt,tiptapExtensions:gn,tiptapNodes:hn,tiptapUi:yn,tiptapUiPrimitives:wn,tiptapUiUtils:xn,styles:Pn}})}async function vc(e){return fe.parse({rsc:e?.rsc,tsx:e?.tsx,aliases:e?.aliases})}import{Command as kc}from"commander";process.on("SIGINT",()=>process.exit(0));process.on("SIGTERM",()=>process.exit(0));async function Tc(){let e=new kc().name("tiptap").description("add components and dependencies to your project").version(sn.version||"1.0.0","-v, --version","display the CLI version number");e.addCommand(ri).addCommand(Jo).addCommand(qo).addCommand(Ho).addCommand(Xo).addCommand(zr).addCommand(qr).addCommand(Jr).addCommand(Gr),await e.parseAsync()}Tc().catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exitCode=1});
359
389
  //# sourceMappingURL=index.js.map