@uniformdev/uniform-mcp 20.55.0 → 20.55.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -94,7 +94,7 @@ See https://reactjs.org/docs/forms.html#controlled-components`),K=R.initialPage?
94
94
  `),r=[];for(let o of n)r.push("> "+o);return r.join(`
95
95
  `)},regExp:One,replace:(t,e,n,r)=>{if(r){let i=t.getPreviousSibling();if(ku(i))return i.splice(i.getChildrenSize(),0,[Wn(),...e]),void t.remove()}let o=V4();o.append(...e),t.replace(o),r||o.select(0,0)},type:"element"},Fne={dependencies:[jl],export:t=>{if(!qm(t))return null;let e=t.getTextContent();return"```"+(t.getLanguage()||"")+(e?`
96
96
  `+e:"")+"\n```"},regExpEnd:{optional:!0,regExp:vO},regExpStart:Ine,replace:(t,e,n,r,o,i)=>{let s,a;if(!e&&o){if(o.length===1)r?(s=Rs(),a=n[1]+o[0]):(s=Rs(n[1]),a=o[0].startsWith(" ")?o[0].slice(1):o[0]);else{if(s=Rs(n[1]),o[0].trim().length===0)for(;o.length>0&&!o[0].length;)o.shift();else o[0]=o[0].startsWith(" ")?o[0].slice(1):o[0];for(;o.length>0&&!o[o.length-1].length;)o.pop();a=o.join(`
97
- `)}let l=mt(a);s.append(l),t.append(s)}else e&&kne(l=>Rs(l?l[1]:void 0))(t,e,n,i)},type:"multiline-element"},Bne={dependencies:[$a,Ta],export:(t,e)=>Gr(t)?AE(t,e,0):null,regExp:Ane,replace:bO("bullet"),type:"element"},LTe={dependencies:[$a,Ta],export:(t,e)=>Gr(t)?AE(t,e,0):null,regExp:Mne,replace:bO("check"),type:"element"},zne={dependencies:[$a,Ta],export:(t,e)=>Gr(t)?AE(t,e,0):null,regExp:Lne,replace:bO("number"),type:"element"},jne={format:["code"],tag:"`",type:"text-format"},Vne={format:["highlight"],tag:"==",type:"text-format"},Une={format:["bold","italic"],tag:"***",type:"text-format"},Hne={format:["bold","italic"],intraword:!1,tag:"___",type:"text-format"},Kne={format:["bold"],tag:"**",type:"text-format"},Wne={format:["bold"],intraword:!1,tag:"__",type:"text-format"},Gne={format:["strikethrough"],tag:"~~",type:"text-format"},Yne={format:["italic"],tag:"*",type:"text-format"},Zne={format:["italic"],intraword:!1,tag:"_",type:"text-format"},qne={dependencies:[SE],export:(t,e,n)=>{if(!CE(t)||xE(t))return null;let r=t.getTitle(),o=e(t);return r?`[${o}](${t.getURL()} "${r}")`:`[${o}](${t.getURL()})`},importRegExp:/(?:\[(.+?)\])(?:\((?:([^()\s]+)(?:\s"((?:[^"]*\\")*[^"]*)"\s*)?)\))/,regExp:/(?:\[(.+?)\])(?:\((?:([^()\s]+)(?:\s"((?:[^"]*\\")*[^"]*)"\s*)?)\))$/,replace:(t,e)=>{let[,n,r,o]=e,i=bE(r,{title:o}),s=n.split("[").length-1,a=n.split("]").length-1,l=n,c="";if(s<a)return;if(s>a){let d=n.split("[");c="["+d[0],l=d.slice(1).join("[")}let u=mt(l);return u.setFormat(t.getFormat()),i.append(u),t.replace(i),c&&i.insertBefore(mt(c)),u},trigger:")",type:"text-match"},Jne=[Rne,Pne,Bne,zne],Xne=[Fne],Qne=[jne,Une,Hne,Kne,Wne,Vne,Yne,Zne,Gne],ere=[qne],ME=[...Jne,...Xne,...Qne,...ere]});var Un,jmt,Vmt,Umt,Hmt,Kmt,Wmt,Gmt,ore,Ymt,ire,Zmt,qmt,Jmt,Xmt,sre,Qmt,are,lre,egt,cre,tgt,ngt,ure,rgt,dre=ue(async()=>{"use strict";Un=await(process.env.NODE_ENV!=="production"?wne().then(()=>Sne):rre().then(()=>nre)),jmt=Un.$convertFromMarkdownString,Vmt=Un.$convertToMarkdownString,Umt=Un.BOLD_ITALIC_STAR,Hmt=Un.BOLD_ITALIC_UNDERSCORE,Kmt=Un.BOLD_STAR,Wmt=Un.BOLD_UNDERSCORE,Gmt=Un.CHECK_LIST,ore=Un.CODE,Ymt=Un.ELEMENT_TRANSFORMERS,ire=Un.HEADING,Zmt=Un.HIGHLIGHT,qmt=Un.INLINE_CODE,Jmt=Un.ITALIC_STAR,Xmt=Un.ITALIC_UNDERSCORE,sre=Un.LINK,Qmt=Un.MULTILINE_ELEMENT_TRANSFORMERS,are=Un.ORDERED_LIST,lre=Un.QUOTE,egt=Un.STRIKETHROUGH,cre=Un.TEXT_FORMAT_TRANSFORMERS,tgt=Un.TEXT_MATCH_TRANSFORMERS,ngt=Un.TRANSFORMERS,ure=Un.UNORDERED_LIST,rgt=Un.registerMarkdownShortcuts});var $ie=_e((gwt,Tie)=>{"use strict";var lLe=Object.prototype.hasOwnProperty,cLe=Object.prototype.toString;Tie.exports=function(e,n,r){if(cLe.call(n)!=="[object Function]")throw new TypeError("iterator must be a function");var o=e.length;if(o===+o)for(var i=0;i<o;i++)n.call(r,e[i],i,e);else for(var s in e)lLe.call(e,s)&&n.call(r,e[s],s,e)}});var ZO=_e((hwt,Nie)=>{"use strict";var uLe=$ie();Nie.exports=Tn;function Tn(t,e,n){if(arguments.length===3)return Tn.set(t,e,n);if(arguments.length===2)return Tn.get(t,e);var r=Tn.bind(Tn,t);for(var o in Tn)Tn.hasOwnProperty(o)&&(r[o]=Tn[o].bind(r,t));return r}Tn.get=function(e,n){for(var r=Array.isArray(n)?n:Tn.parse(n),o=0;o<r.length;++o){var i=r[o];if(!(typeof e=="object"&&i in e))throw new Error("Invalid reference token: "+i);e=e[i]}return e};Tn.set=function(e,n,r){var o=Array.isArray(n)?n:Tn.parse(n),i=o[0];if(o.length===0)throw Error("Can not set the root object");for(var s=0;s<o.length-1;++s){var a=o[s];typeof a!="string"&&typeof a!="number"&&(a=String(a)),!(a==="__proto__"||a==="constructor"||a==="prototype")&&(a==="-"&&Array.isArray(e)&&(a=e.length),i=o[s+1],a in e||(i.match(/^(\d+|-)$/)?e[a]=[]:e[a]={}),e=e[a])}return i==="-"&&Array.isArray(e)&&(i=e.length),e[i]=r,this};Tn.remove=function(t,e){var n=Array.isArray(e)?e:Tn.parse(e),r=n[n.length-1];if(r===void 0)throw new Error('Invalid JSON pointer for remove: "'+e+'"');var o=Tn.get(t,n.slice(0,-1));if(Array.isArray(o)){var i=+r;if(r===""&&isNaN(i))throw new Error('Invalid array index: "'+r+'"');Array.prototype.splice.call(o,i,1)}else delete o[r]};Tn.dict=function(e,n){var r={};return Tn.walk(e,function(o,i){r[i]=o},n),r};Tn.walk=function(e,n,r){var o=[];r=r||function(i){var s=Object.prototype.toString.call(i);return s==="[object Object]"||s==="[object Array]"},function i(s){uLe(s,function(a,l){o.push(String(l)),r(a)?i(a):n(a,Tn.compile(o)),o.pop()})}(e)};Tn.has=function(e,n){try{Tn.get(e,n)}catch{return!1}return!0};Tn.escape=function(e){return e.toString().replace(/~/g,"~0").replace(/\//g,"~1")};Tn.unescape=function(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")};Tn.parse=function(e){if(e==="")return[];if(e.charAt(0)!=="/")throw new Error("Invalid JSON pointer: "+e);return e.substring(1).split(/\//).map(Tn.unescape)};Tn.compile=function(e){return e.length===0?"":"/"+e.map(Tn.escape).join("/")}});import{McpServer as oOe}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as iOe}from"@modelcontextprotocol/sdk/server/stdio.js";var mx={name:"@uniformdev/uniform-mcp",version:"20.55.0",description:"Uniform MCP Server",license:"SEE LICENSE IN LICENSE.txt",bin:{"uniform-mcp":"./dist/index.mjs"},exports:{".":{types:"./dist/index.d.mts",import:"./dist/index.mjs"},"./server":{types:"./dist/server.d.mts",import:"./dist/server.mjs"}},sideEffects:!1,scripts:{build:"run-p build:stdio build:server","build:stdio":"tsup --config tsup.stdio.config.ts","build:server":"tsup --config tsup.server.config.ts",dev:"tsup --watch --config tsup.stdio.config.ts",clean:"rimraf dist",lint:'eslint "src/**/*.{js,ts,tsx}"',format:'prettier --write "src/**/*.{js,ts,tsx}"',mcp:"node dist/index.mjs"},dependencies:{"@modelcontextprotocol/sdk":"1.25.2","@types/uuid":"9.0.4","@uniformdev/canvas":"workspace:*","@uniformdev/project-map":"workspace:*","fast-json-patch":"3.1.1",immer:"10.1.3",linkedom:"0.18.12",uuid:"9.0.1",zod:"3.25.76"},files:["/dist"],publishConfig:{access:"public"},devDependencies:{"@uniformdev/design-system":"workspace:*","@uniformdev/files":"workspace:*","@uniformdev/mesh-edgehancer-sdk":"workspace:*","@uniformdev/richtext":"workspace:*"}};var tk=I(ek());var nk=(0,tk.default)(6),gx=class t extends Error{constructor(n,r,o,i,s,a){super(`${n}
97
+ `)}let l=mt(a);s.append(l),t.append(s)}else e&&kne(l=>Rs(l?l[1]:void 0))(t,e,n,i)},type:"multiline-element"},Bne={dependencies:[$a,Ta],export:(t,e)=>Gr(t)?AE(t,e,0):null,regExp:Ane,replace:bO("bullet"),type:"element"},LTe={dependencies:[$a,Ta],export:(t,e)=>Gr(t)?AE(t,e,0):null,regExp:Mne,replace:bO("check"),type:"element"},zne={dependencies:[$a,Ta],export:(t,e)=>Gr(t)?AE(t,e,0):null,regExp:Lne,replace:bO("number"),type:"element"},jne={format:["code"],tag:"`",type:"text-format"},Vne={format:["highlight"],tag:"==",type:"text-format"},Une={format:["bold","italic"],tag:"***",type:"text-format"},Hne={format:["bold","italic"],intraword:!1,tag:"___",type:"text-format"},Kne={format:["bold"],tag:"**",type:"text-format"},Wne={format:["bold"],intraword:!1,tag:"__",type:"text-format"},Gne={format:["strikethrough"],tag:"~~",type:"text-format"},Yne={format:["italic"],tag:"*",type:"text-format"},Zne={format:["italic"],intraword:!1,tag:"_",type:"text-format"},qne={dependencies:[SE],export:(t,e,n)=>{if(!CE(t)||xE(t))return null;let r=t.getTitle(),o=e(t);return r?`[${o}](${t.getURL()} "${r}")`:`[${o}](${t.getURL()})`},importRegExp:/(?:\[(.+?)\])(?:\((?:([^()\s]+)(?:\s"((?:[^"]*\\")*[^"]*)"\s*)?)\))/,regExp:/(?:\[(.+?)\])(?:\((?:([^()\s]+)(?:\s"((?:[^"]*\\")*[^"]*)"\s*)?)\))$/,replace:(t,e)=>{let[,n,r,o]=e,i=bE(r,{title:o}),s=n.split("[").length-1,a=n.split("]").length-1,l=n,c="";if(s<a)return;if(s>a){let d=n.split("[");c="["+d[0],l=d.slice(1).join("[")}let u=mt(l);return u.setFormat(t.getFormat()),i.append(u),t.replace(i),c&&i.insertBefore(mt(c)),u},trigger:")",type:"text-match"},Jne=[Rne,Pne,Bne,zne],Xne=[Fne],Qne=[jne,Une,Hne,Kne,Wne,Vne,Yne,Zne,Gne],ere=[qne],ME=[...Jne,...Xne,...Qne,...ere]});var Un,jmt,Vmt,Umt,Hmt,Kmt,Wmt,Gmt,ore,Ymt,ire,Zmt,qmt,Jmt,Xmt,sre,Qmt,are,lre,egt,cre,tgt,ngt,ure,rgt,dre=ue(async()=>{"use strict";Un=await(process.env.NODE_ENV!=="production"?wne().then(()=>Sne):rre().then(()=>nre)),jmt=Un.$convertFromMarkdownString,Vmt=Un.$convertToMarkdownString,Umt=Un.BOLD_ITALIC_STAR,Hmt=Un.BOLD_ITALIC_UNDERSCORE,Kmt=Un.BOLD_STAR,Wmt=Un.BOLD_UNDERSCORE,Gmt=Un.CHECK_LIST,ore=Un.CODE,Ymt=Un.ELEMENT_TRANSFORMERS,ire=Un.HEADING,Zmt=Un.HIGHLIGHT,qmt=Un.INLINE_CODE,Jmt=Un.ITALIC_STAR,Xmt=Un.ITALIC_UNDERSCORE,sre=Un.LINK,Qmt=Un.MULTILINE_ELEMENT_TRANSFORMERS,are=Un.ORDERED_LIST,lre=Un.QUOTE,egt=Un.STRIKETHROUGH,cre=Un.TEXT_FORMAT_TRANSFORMERS,tgt=Un.TEXT_MATCH_TRANSFORMERS,ngt=Un.TRANSFORMERS,ure=Un.UNORDERED_LIST,rgt=Un.registerMarkdownShortcuts});var $ie=_e((gwt,Tie)=>{"use strict";var lLe=Object.prototype.hasOwnProperty,cLe=Object.prototype.toString;Tie.exports=function(e,n,r){if(cLe.call(n)!=="[object Function]")throw new TypeError("iterator must be a function");var o=e.length;if(o===+o)for(var i=0;i<o;i++)n.call(r,e[i],i,e);else for(var s in e)lLe.call(e,s)&&n.call(r,e[s],s,e)}});var ZO=_e((hwt,Nie)=>{"use strict";var uLe=$ie();Nie.exports=Tn;function Tn(t,e,n){if(arguments.length===3)return Tn.set(t,e,n);if(arguments.length===2)return Tn.get(t,e);var r=Tn.bind(Tn,t);for(var o in Tn)Tn.hasOwnProperty(o)&&(r[o]=Tn[o].bind(r,t));return r}Tn.get=function(e,n){for(var r=Array.isArray(n)?n:Tn.parse(n),o=0;o<r.length;++o){var i=r[o];if(!(typeof e=="object"&&i in e))throw new Error("Invalid reference token: "+i);e=e[i]}return e};Tn.set=function(e,n,r){var o=Array.isArray(n)?n:Tn.parse(n),i=o[0];if(o.length===0)throw Error("Can not set the root object");for(var s=0;s<o.length-1;++s){var a=o[s];typeof a!="string"&&typeof a!="number"&&(a=String(a)),!(a==="__proto__"||a==="constructor"||a==="prototype")&&(a==="-"&&Array.isArray(e)&&(a=e.length),i=o[s+1],a in e||(i.match(/^(\d+|-)$/)?e[a]=[]:e[a]={}),e=e[a])}return i==="-"&&Array.isArray(e)&&(i=e.length),e[i]=r,this};Tn.remove=function(t,e){var n=Array.isArray(e)?e:Tn.parse(e),r=n[n.length-1];if(r===void 0)throw new Error('Invalid JSON pointer for remove: "'+e+'"');var o=Tn.get(t,n.slice(0,-1));if(Array.isArray(o)){var i=+r;if(r===""&&isNaN(i))throw new Error('Invalid array index: "'+r+'"');Array.prototype.splice.call(o,i,1)}else delete o[r]};Tn.dict=function(e,n){var r={};return Tn.walk(e,function(o,i){r[i]=o},n),r};Tn.walk=function(e,n,r){var o=[];r=r||function(i){var s=Object.prototype.toString.call(i);return s==="[object Object]"||s==="[object Array]"},function i(s){uLe(s,function(a,l){o.push(String(l)),r(a)?i(a):n(a,Tn.compile(o)),o.pop()})}(e)};Tn.has=function(e,n){try{Tn.get(e,n)}catch{return!1}return!0};Tn.escape=function(e){return e.toString().replace(/~/g,"~0").replace(/\//g,"~1")};Tn.unescape=function(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")};Tn.parse=function(e){if(e==="")return[];if(e.charAt(0)!=="/")throw new Error("Invalid JSON pointer: "+e);return e.substring(1).split(/\//).map(Tn.unescape)};Tn.compile=function(e){return e.length===0?"":"/"+e.map(Tn.escape).join("/")}});import{McpServer as oOe}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as iOe}from"@modelcontextprotocol/sdk/server/stdio.js";var mx={name:"@uniformdev/uniform-mcp",version:"20.55.1",description:"Uniform MCP Server",license:"SEE LICENSE IN LICENSE.txt",bin:{"uniform-mcp":"./dist/index.mjs"},exports:{".":{types:"./dist/index.d.mts",import:"./dist/index.mjs"},"./server":{types:"./dist/server.d.mts",import:"./dist/server.mjs"}},sideEffects:!1,scripts:{build:"run-p build:stdio build:server","build:stdio":"tsup --config tsup.stdio.config.ts","build:server":"tsup --config tsup.server.config.ts",dev:"tsup --watch --config tsup.stdio.config.ts",clean:"rimraf dist",lint:'eslint "src/**/*.{js,ts,tsx}"',format:'prettier --write "src/**/*.{js,ts,tsx}"',mcp:"node dist/index.mjs"},dependencies:{"@modelcontextprotocol/sdk":"1.25.2","@types/uuid":"9.0.4","@uniformdev/canvas":"workspace:*","@uniformdev/project-map":"workspace:*","fast-json-patch":"3.1.1",immer:"10.1.3",linkedom:"0.18.12",uuid:"9.0.1",zod:"3.25.76"},files:["/dist"],publishConfig:{access:"public"},devDependencies:{"@uniformdev/design-system":"workspace:*","@uniformdev/files":"workspace:*","@uniformdev/mesh-edgehancer-sdk":"workspace:*","@uniformdev/richtext":"workspace:*"}};var tk=I(ek());var nk=(0,tk.default)(6),gx=class t extends Error{constructor(n,r,o,i,s,a){super(`${n}
98
98
  ${i}${s?" "+s:""} (${r} ${o}${a?` Request ID: ${a}`:""})`);this.errorMessage=n;this.fetchMethod=r;this.fetchUri=o;this.statusCode=i;this.statusText=s;this.requestId=a;Object.setPrototypeOf(this,t.prototype)}};var hx=class t{options;constructor(e){if(!e.apiKey&&!e.bearerToken)throw new Error("You must provide an API key or a bearer token");let n=e.fetch;if(!n)if(typeof window<"u")n=window.fetch.bind(window);else if(typeof fetch<"u")n=fetch;else throw new Error("You must provide or polyfill a fetch implementation when not in a browser");this.options={...e,fetch:n,apiHost:this.ensureApiHost(e.apiHost),apiKey:e.apiKey??null,projectId:e.projectId??null,bearerToken:e.bearerToken??null,limitPolicy:e.limitPolicy??nk,bypassCache:e.bypassCache??!1}}async apiClient(e,n){return(await this.apiClientWithResponse(e,n)).body}async apiClientWithResponse(e,n){return this.options.limitPolicy(async()=>{let r=this.options.apiKey?{"x-api-key":this.options.apiKey}:{Authorization:`Bearer ${this.options.bearerToken}`};this.options.bypassCache&&(r["x-bypass-cache"]="true");let{fetch:o,signal:i}=this.options,a=await vle(()=>o(e.toString(),{...n,signal:i,headers:{...n?.headers,...r}}));if(!a.ok){let l="";try{let c=await a.text();try{let u=JSON.parse(c);u.errorMessage?l=Array.isArray(u.errorMessage)?u.errorMessage.join(", "):u.errorMessage:l=c}catch{l=c}}catch{l="General error"}throw new gx(l,n?.method??"GET",e.toString(),a.status,a.statusText,t.getRequestId(a))}return n?.expectNoContent?{response:a,body:null}:{response:a,body:await a.json()}})}createUrl(e,n,r){let o=new URL(`${r??this.options.apiHost}${e}`);return Object.entries(n??{}).forEach(([i,s])=>{typeof s<"u"&&s!==null&&o.searchParams.append(i,Array.isArray(s)?s.join(","):s?.toString()??"")}),o}ensureApiHost(e){if(!e)return"https://uniform.app";if(!e?.startsWith("http"))throw new Error('Your apiHost must start with "http"');if(e.indexOf("/",8)>-1)throw new Error("Your apiHost must not contain a path element after the domain");if(e.indexOf("?")>-1)throw new Error("Your apiHost must not contain a query string");return e?.endsWith("/")&&(e=e.substring(0,e.length-1)),e}static getRequestId(e){let n=e.headers.get("apigw-requestid");if(n)return n}};async function vle(t){let n=5,r;for(;n>0&&(r=await t(),r.status===429);){let o=0;try{let a=r.clone(),l=a.headers.get("date"),c=l?new Date(l).getTime():void 0,d=(await a.json())?.info?.reset;typeof c=="number"&&typeof d=="number"&&(o=Math.max(0,Math.min(Math.round(1.1*(d-c)),1e4)))}catch{}let i=Math.pow(2,5-n)*333,s=i+Math.round(Math.random()*(i/2))*(Math.random()>.5?1:-1);await new Promise(a=>setTimeout(a,Math.max(0,o+s))),n-=1}return r}var vx=class extends hx{telemetryContext;constructor(e){e.apiHost||(e.apiHost="https://ai.uniform.global"),super(e),this.telemetryContext=e.telemetryContext}async invoke(e,n){let r={};if(this.telemetryContext){let{threadId:i,uniformClient:s,userAgent:a}=this.telemetryContext;i&&(r["x-thread-id"]=i),s&&(r["x-uniform-client"]=s),a&&(r["user-agent"]=a)}return(await this.apiClientWithResponse(new URL(`/projects/${this.options.projectId}/tools/${e}`,this.options.apiHost),{method:"POST",body:n?JSON.stringify(n):void 0,headers:Object.keys(r).length>0?r:void 0})).body}};var ik=process.env.UNIFORM_API_KEY,G5=process.env.UNIFORM_PROJECT_ID,rk=process.env.UNIFORM_API_HOST??"https://uniform.app",yle=process.env.UNIFORM_AI_API_HOST??"https://ai.uniform.global";if(!ik&&process.env.NODE_ENV!=="test")throw new Error("UNIFORM_API_KEY is not set");if(!G5&&process.env.NODE_ENV!=="test")throw new Error("UNIFORM_PROJECT_ID is not set");var ok={apiHost:rk,apiKey:ik,projectId:G5,baseWebUrl:`${rk}/projects/${G5}`},sk={...ok,toolInvoker:new vx({...ok,apiHost:yle,telemetryContext:{userAgent:`uniform-mcp/${mx.version}`,uniformClient:"mcp"}})};import{z as Pp}from"zod";var ak={displayName:"Ask Una",description:"Ask the Uniform Docs assistant, Una, questions about Uniform features, usage, and best practices.",inputSchema:Pp.object({question:Pp.string().describe(`Prompt for the uniform docs AI assistant.
99
99
  The prompt should describe the information you are looking for.
100
100
  You may be detailed but do not use more than 100 words.
@@ -5834,7 +5834,7 @@ to {
5834
5834
  ${p}`:""}`:p??"").split(`
5835
5835
  `);return React.createElement(FE,{title:React.createElement($O,{gap:"sm"},h.map((v,y)=>React.createElement("div",{key:y},v)))},React.createElement("span",null,m))}return m}function ODe({children:t}){return React.createElement("span",{style:{textDecoration:"underline",textDecorationStyle:"wavy",textDecorationColor:"var(--error)"}},t)}function IDe({children:t}){return React.createElement("span",{style:{textDecoration:"underline",textDecorationStyle:"wavy",textDecorationColor:"var(--primary-action-default)"}},t)}function kDe({children:t}){return React.createElement("span",{style:{textDecoration:"underline",textDecorationStyle:"wavy",textDecorationColor:"var(--alert)"}},t)}import{createVariableReference as W3t}from"@uniformdev/canvas";await ut();var Tb=I(V()),RDe=I(Bs());var eSt=bt("uniform:open-insert-variable"),bie=bt("uniform:edit-variable"),tSt=bt("uniform:disconnect-variable"),nSt=bt("uniform:insert-variable");var s0=class t extends gu{constructor(n,r,o){super(o);this.reference=n;this.__variableState=r}__variableState;static getType(){return"variable"}static clone(n){return new t(n.reference,{...n.__variableState},n.__key)}static importJSON(n){return xie(n.reference,{displayName:GO(n.reference),referenceIsValid:!0,isFresh:!1,hasClickEvent:void 0,tooltip:void 0,isLoading:!1})}getState(){return this.getLatest().__variableState}setState(n){this.getWritable().__variableState=n}exportJSON(){return{reference:this.reference,type:t.getType(),version:1}}getTextContent(){return PDe(this.reference)}createDOM(){return document.createElement("span")}updateDOM(){return!1}static importDOM(){return{binding:()=>({conversion:FDe,priority:0})}}decorate(){return React.createElement(zDe,{state:this.__variableState,reference:this.reference,nodeKey:this.__key})}};function FDe(t){let n=t.textContent.replace(gie,"").replace(hie,"");return{node:xie(n,{displayName:GO(n),hasClickEvent:!0,referenceIsValid:!0,tooltip:void 0,isFresh:!0,isLoading:!1})}}function xie(t,e){return new s0(t,e)}function BDe(t){return t instanceof s0}function zDe({state:t,reference:e,nodeKey:n}){let[r]=Lg(),[o,i,s]=gG(n),a=!r.isEditable(),l=(0,qE.useCallback)(c=>{if(o&&qe(H())){c.preventDefault();let u=rt(n);BDe(u)&&u.remove()}return!1},[o,n]);return(0,qE.useEffect)(()=>ot(r.registerCommand(va,l,Ae),r.registerCommand(ha,l,Ae),r.registerCommand(ni,c=>{let u=H();if(qe(u)){let d=u.getNodes();if(d.length>0)return c.preventDefault(),d[0].selectPrevious(),!0}if(!U(u))return!1;if(Rl(u,!0)){let d=c.shiftKey;return c.preventDefault(),kl(u,d,!0),!0}return!1},pe),r.registerCommand(ga,c=>{let u=H();if(qe(u)&&!jDe(c.target)){let f=u.getNodes();if(f.length>0)return c.preventDefault(),f[0].selectNext(0,0),!0}if(!U(u))return!1;let d=c.shiftKey;return Rl(u,!1)?(c.preventDefault(),kl(u,d,!1),!0):!1},pe)),[s,r,o,n,l,i]),React.createElement(yie,{...t,reference:e,displayName:t.isLoading?React.createElement(Boe,{size:"sm"}):t.displayName,selected:o,disabled:a,clickToEdit:t.hasClickEvent,onClick:t.hasClickEvent?()=>{i(!o),r.dispatchCommand(bie,{reference:e,sourceKey:n})}:()=>i(!o)})}function jDe(t){let e=ct(t);return Yn(e)}await ut();await ut();var $b=class t extends gu{__asset;__assetQuery;__upload;__error;getAsset(){return this.getLatest().__asset}setAsset(e){let n=this.getWritable();n.__asset=e}getAssetQuery(){return this.getLatest().__assetQuery}setAssetQuery(e){let n=this.getWritable();n.__assetQuery=e}getUpload(){return this.getLatest().__upload}setUpload(e){let n=this.getWritable();n.__upload=e}getError(){return this.getLatest().__error}setError(e){let n=this.getWritable();n.__error=e}static getType(){return"asset"}constructor(e,n,r,o,i){super(i),this.__asset=e,this.__upload=n,this.__error=o,this.__assetQuery=r}static clone(e){return new t(e.__asset,e.__upload,e.__assetQuery,e.__error,e.__key)}exportJSON(){let e={type:"asset",version:1};if(this.__asset&&(e.__asset=this.__asset),this.__assetQuery&&(e.__assetQuery=this.__assetQuery),this.__upload&&"fileUrl"in this.__upload){let{fileUrl:n,suggestedAltText:r,suggestedCaption:o}=this.__upload;e.__upload={fileUrl:n,suggestedAltText:r,suggestedCaption:o}}return this.__error&&(e.__error=this.__error),e}static importJSON(e){return YO({asset:e.__asset,assetQuery:e.__assetQuery,upload:e.__upload,error:e.__error})}static importDOM(){return{img:()=>({conversion:e=>VDe(e,YO),priority:0}),figure:()=>({conversion:e=>UDe(e,YO),priority:0})}}createDOM(e){let n=document.createElement("span"),o=e.theme.image;return o!==void 0&&(n.className=o),n}updateDOM(){return!1}isInline(){return!1}};function YO({asset:t,upload:e,assetQuery:n,error:r}){return $t(new $b(t,e,n,r))}function Cie(t){return t.parentElement!=null&&t.parentElement.tagName==="LI"&&t.previousSibling===null&&t.getAttribute("aria-roledescription")==="checkbox"}function VDe(t,e){let n=t;if(n.src.startsWith("file:///")||Cie(n))return null;let{alt:r,src:o}=n;return{node:Sie({altText:r,src:o,createAssetNode:e})}}function UDe(t,e){let n=t,r=n.querySelector("img"),o=n.querySelector("figcaption");if(!r||r.src.startsWith("file:///")||Cie(r))return null;let{alt:i,src:s}=r;return s.startsWith("uniform://")?{node:e({assetQuery:{id:r.src.split("uniform://")[1],suggestedAltText:i,suggestedCaption:o?.textContent??void 0}})}:{node:Sie({altText:i,src:s,caption:o?.textContent??void 0,createAssetNode:e})}}function Sie({altText:t,src:e,caption:n,createAssetNode:r}){return r({asset:void 0,upload:{fileUrl:e,suggestedAltText:t,suggestedCaption:n},assetQuery:void 0})}var HDe=t=>new DOMParser().parseFromString(t,"text/html");function wie(t,e=HDe){let n=qV({nodes:[$a,Ta,UO,yg,bg,Fm,VW,jW,UW,jl,$b,s0]}),r=e(t);return n.update(()=>{b7("skip-dom-selection");let o=Xm(n,r);Tt().select(),As(o)},{discrete:!0}),n.getEditorState().toJSON()}function Eie({twee:t,nodeId:e,propertyId:n,propertyType:r,locale:o,propertyEdit:i,conditionIndex:s=-1,definitionIndex:a,domParser:l}){let c=t.getNodeById(e);if(!c)throw new Error(`Node with ID ${e} not found`);if(i.action==="clearValue")t.updateNodeProperty({nodeId:e,property:n,value:null,source:"ai",locale:o,conditionIndex:-1});else if(i.action==="resetOverride")t.resetPatternPropertyOverride(e,n,o);else if(i.action==="setValue"){if(r==="contentReference"){QDe({twee:t,nodeId:e,targetNode:c,propertyId:n,propertyType:r,propertyEdit:i,locale:o,conditionIndex:s,definitionIndex:a});return}let u=XDe({twee:t,targetNode:c,propertyId:n,propertyType:r,propertyEdit:i,domParser:l}),d=t.getNodeProperty(e,n);if(!o&&d?.locales)throw new Error(`The ${n} property is localized in ${Object.keys(d.locales).join(", ")}, but no locale was provided when setting its value. Please provide an explicit locale.`);if(n===GDe){let f=t.getParentInfo(e);if(f?.parentId){let p=t.getNodeProperty(f.parentId,WDe);if(p?.value!==Dk)throw new Error(`Cannot edit personalization criteria when the parent personalization component is not using the Strongest Variation Match selection method. Current selection method: ${p?.value||"Top-down criteria matching"}.`)}}t.updateNodeProperty({nodeId:e,property:n,value:()=>u,source:"ai",locale:o,conditionIndex:s,type:r})}}var XDe=({twee:t,targetNode:e,propertyId:n,propertyType:r,propertyEdit:o,domParser:i})=>{if(r==="richText")return wie(o.newValue??"",i);if(r==="number")return Number(o.newValue);if(n===KDe){if(JDe(e.value.type))throw new Error("Enrichment tags are not allowed in system components.");if(t.getParentInfo(e.nodeId)?.parentId===YDe)throw new Error("Enrichment tags are not allowed in personalization variants.")}return o.treatNewValueAsJson?JSON.parse(o.newValue):o.newValue};function QDe({twee:t,nodeId:e,targetNode:n,propertyId:r,propertyType:o,propertyEdit:i,locale:s,conditionIndex:a,definitionIndex:l}){let c=zp(n.nodeId,r,s,a),u;try{u=i.treatNewValueAsJson?JSON.parse(i.newValue):i.newValue}catch(y){throw new Error(`Invalid reference field data: ${y instanceof Error?y.message:"Unknown error"}`)}if(!u||typeof u!="object"||u.type!==ll)throw new Error("Invalid reference field definition received from AI");let d=u.variables?.entryIds;if(!d||typeof d!="string"||d.length===0){t.updateNode({nodeId:n.nodeId,updateDataResources:[{type:"remove",name:c}]}),t.updateNodeProperty({nodeId:e,property:r,value:null,source:"ai",locale:s,conditionIndex:a,type:o});return}let m=l[n.value.type]?.parameters?.find(({id:y})=>y===r)?.typeConfig?.isMulti??!1,g=Ek(d,{targetLocale:s,enabledLocales:t.getNodeById(t.rootNodeId)?.value._locales??[]});t.updateNode({nodeId:n.nodeId,updateDataResources:[{type:"set",name:c,value:g}]});let h=`/${c}/entries${m?"":"/0"}`,v=qDe(ZDe({syntax:"jptr",pointer:h}));t.updateNodeProperty({nodeId:e,property:r,value:()=>v,source:"ai",locale:s,conditionIndex:a,type:o})}import{validate as eLe}from"uuid";var _ie=t=>eLe(t)?t:btoa(t);function a0(t,e,n="Component instance"){let r=t.getNodeById(e);if(r)return r;let o=[];if(t.visitNodeAndDescendants(t.rootNodeId,i=>{i.nodeId!==e&&i.nodeId.includes(e)&&o.push(i.nodeId)}),o.length>0){let i=o.map(s=>`"${_ie(s)}"`).join(", ");throw new Error(`${n} with ID ${e} not found. You might have meant one of these IDs that does exist: ${i}. Component IDs should be used exactly as provided in the _id field.`)}throw new Error(`${n} with ID ${e} not found`)}async function JE({twee:t,slotUpdates:e,propertyUpdates:n,dataResourceUpdates:r,localeUpdates:o,nameUpdate:i,slugUpdate:s,descriptionUpdate:a,currentEditorLocale:l,referenceData:c,dataSourceVariant:u,onStatusUpdate:d,isEditingPattern:f,domParser:p}){let m=[],g=(i?1:0)+(s?1:0)+(a?1:0)+(e.createComponentInstances?.length??0)+(e.moveComponentInstances?.length??0)+(e.duplicateComponentInstances?.length??0)+(e.deleteComponentInstances?.length??0)+(o?.enableLocales?.length??0)+(o?.disableLocales?.length??0)+n.length,h=0,v=C=>{m.push(C),h++,d?.({completed:h,total:g})};i&&(t.updateRootNode({update:{_name:i}}),v({summary:"Updated name",success:!0})),s&&(t.updateRootNode({update:{_slug:s}}),v({summary:"Updated slug",success:!0})),a&&(t.updateRootMetadata({description:a}),v({summary:"Updated description",success:!0}));let y=await c.fetchDefinitions();await oLe({slotUpdates:e,twee:t,definitions:y,referenceData:c,addResult:v,isEditingPattern:f});let b=m.some(C=>!C.success);if(b?e.moveComponentInstances?.forEach(C=>{m.push({summary:`Skipped moving component ${C.componentId} because previous actions failed`,success:!1})}):await iLe({slotUpdates:e,twee:t,definitions:y,addResult:v,isEditingPattern:f}),b=m.some(C=>!C.success),e.duplicateComponentInstances)for(let C of e.duplicateComponentInstances)if(b)v({summary:`Skipped duplicating component ${C} because previous actions failed`,success:!1});else{let w=await t.duplicateNode(C,c.resolvePatternData);v({summary:`Duplicated component ${C}. The new duplicate has ID ${w} and is placed immediately after the original component in the same slot.`,success:!0})}return b=m.some(C=>!C.success),e.deleteComponentInstances?.forEach(C=>{b?v({summary:`Skipped deleting component ${C} because previous actions failed`,success:!1}):(t.deleteNode(C,!1),v({summary:`Deleted component ${C}`,success:!0}))}),b=m.some(C=>!C.success),o?.enableLocales?.forEach(C=>{b?v({summary:`Skipped enabling locale ${C} because previous actions failed`,success:!1}):(t.enableLocale(C),v({summary:`Enabled locale ${C}`,success:!0}))}),b=m.some(C=>!C.success),o?.disableLocales?.forEach(C=>{b?v({summary:`Skipped disabling locale ${C} because previous actions failed`,success:!1}):(t.disableLocale(C),v({summary:`Disabled locale ${C}`,success:!0}))}),b=m.some(C=>!C.success),b?n.length>0&&v({summary:`Skipped ${n.length} property updates because previous actions failed`,success:!1}):(await sLe({propertyUpdates:n,twee:t,currentEditorLocale:l,referenceData:c,definitions:y,addResult:v})).forEach(w=>{if(!w.result.success)return;let E="componentId"in w.update?w.update.componentId:t.rootNodeId,_=X5({twee:t,nodeId:E,currentEditorLocale:w.currentLocale,definition:w.propertyDefinition}),$=(t.getNodeById(t.rootNodeId)?.value)._locales??[];if(_&&!$.includes(_)){v({summary:`The ${_} locale is not enabled on this entity. Please enable it before setting values in this locale.`,success:!1});return}if(w.result.action!=="nothing")try{Eie({twee:t,nodeId:E,propertyId:w.propertyDefinition.id,propertyType:w.propertyDefinition.type,locale:_,propertyEdit:w.result,definitionIndex:y,domParser:p}),v({summary:`Updated value of ${w.propertyDefinition.id} on ${E}${_?` in ${_}`:""}`,success:!0})}catch(T){v({summary:`Failed to update value of ${w.propertyDefinition.id} on ${E}${_?` in ${_}`:""}: ${T instanceof Error?T.message:"Unknown error"}`,success:!1})}if("overridable"in w.update&&w.update.overridable!==void 0)if(w.propertyDefinition.type===tLe)v({summary:`Cannot set overridability for block property '${w.propertyDefinition.id}' - blocks do not support overrides`,success:!1});else{let T=w.update.overridable;t.updateNode({nodeId:E,updateComponent:N=>{N._overridability??={},N._overridability.parameters??={},N._overridability.parameters[w.propertyDefinition.id]=T}}),v({summary:`Updated overridability for ${E}`,success:!0})}}),b=m.some(C=>!C.success),b?r.length>0&&m.push({summary:`Skipped ${r.length} data resource updates because previous actions failed`,success:!1}):(await aLe({dataResourceUpdates:r,twee:t,referenceData:c,results:m,dataSourceVariant:u})).forEach(w=>{if(!w.result.success)return;let E=w.update.componentId;if(w.result.action==="resetOverride")t.updateNode({nodeId:E,updateDataResources:[{type:"reset",name:w.update.dataResourceName}]}),m.push({summary:`Reset data resource to pattern default for ${w.update.dataResourceName} on ${E}`,success:!0});else if(w.result.action==="setValue")try{_k({twee:t,nodeId:E,dataResourceName:w.update.dataResourceName,dataType:w.dataType,dataResourceEdit:w.result}),m.push({summary:`Updated data resource ${w.update.dataResourceName} on ${E}`,success:!0})}catch(_){m.push({summary:`Failed to update data resource ${w.update.dataResourceName} on ${E}: ${_ instanceof Error?_.message:"Unknown error"}`,success:!1})}}),{success:m.every(C=>C.success),actionsTaken:m}}async function oLe({slotUpdates:t,twee:e,definitions:n,referenceData:r,addResult:o,isEditingPattern:i}){(await Promise.allSettled(t.createComponentInstances?.map(async a=>{let l=a0(e,a.parentComponentId,"Parent component");if(!n[l.value.type])throw new Error(`Definition for parent component type ${l.value.type} not found`);let u=J5({twee:e,parentNodeId:a.parentComponentId,slotName:a.slotName,componentDefinitionsIndex:n});if(!u)throw new Error(`Can't find allowed components for slot ${a.slotName}`);if(a.instanceType==="component"){if(!a.componentType)throw new Error("componentType is required when inserting a component instance");if(!$x({type:a.componentType},u,i))throw new Error(`Component type ${a.componentType} is not allowed in slot ${a.slotName}`);e.insertNode({node:{type:a.componentType},overrideNodeId:a.newComponentInstanceUuid,parentNodeId:a.parentComponentId,parentSlot:a.slotName,targetIndexInSlot:a.slotIndex}),o({summary:`Inserted component ${a.componentType} in slot ${a.slotName} ${a.slotIndex!==void 0?`at index ${a.slotIndex}`:""}`,success:!0})}else{if(!a.componentPatternId)throw new Error("componentPatternId is required when inserting a component pattern instance");let d=await r.resolvePatternData(a.componentPatternId);if(!d)throw new Error(`Pattern definition with ID ${a.componentPatternId} not found`);if(!$x({type:d.type,_pattern:a.componentPatternId},u,!1))throw new Error(`Pattern ${a.componentPatternId} is not allowed in slot ${a.slotName}`);e.insertPattern({pattern:d,patternInstanceId:a.newComponentInstanceUuid,parentNodeId:a.parentComponentId,parentSlot:a.slotName,targetIndexInSlot:a.slotIndex}),o({summary:`Inserted pattern ${d._name} in slot ${a.slotName} ${a.slotIndex!==void 0?`at index ${a.slotIndex}`:""}`,success:!0})}})??[])).forEach((a,l)=>{if(a.status==="rejected"){let c=t.createComponentInstances?.[l];console.error("Error inserting component",a.reason),o({summary:`Failed to insert component ${c?.newComponentInstanceUuid}: ${"message"in a.reason?a.reason.message:"Unknown error"}`,success:!1})}})}async function iLe({slotUpdates:t,twee:e,definitions:n,addResult:r,isEditingPattern:o}){(await Promise.allSettled(t.moveComponentInstances?.map(async s=>{let a=a0(e,s.componentId,"Component to move"),l=a0(e,s.newParentComponentId,"Destination component");if(!n[l.value.type])throw new Error(`Definition for destination component type ${l.value.type} not found`);let u=J5({twee:e,parentNodeId:s.newParentComponentId,slotName:s.newSlotName,componentDefinitionsIndex:n});if(!u)throw new Error(`Can't find allowed components for slot ${s.newSlotName}`);if(!$x({type:a.value.type,_pattern:a.value._pattern},u,o))throw new Error(a.value._pattern?`Pattern ${a.value._pattern} is not allowed in slot ${s.newSlotName}`:`Component ${a.value.type} is not allowed in slot ${s.newSlotName}`);e.moveNode({movedNodeId:s.componentId,parentNodeId:s.newParentComponentId,parentSlot:s.newSlotName,targetIndexInSlot:s.newSlotIndex}),r({summary:`Moved component ${s.componentId} to ${s.newParentComponentId} in slot ${s.newSlotName} at index ${s.newSlotIndex}`,success:!0})})??[])).forEach((s,a)=>{if(s.status==="rejected"){let l=t.moveComponentInstances?.[a];console.error("Error moving component",s.reason),r({summary:`Failed to move component ${l?.componentId}: ${"message"in s.reason?s.reason.message:"Unknown error"}`,success:!1})}})}async function sLe({propertyUpdates:t,twee:e,currentEditorLocale:n,referenceData:r,definitions:o,addResult:i}){if(t.length===0)return[];let[s,a]=await Promise.all([r.fetchProjectGuidance(),r.getToolClient()]),l=await Promise.allSettled(t.map(async c=>(async()=>{let u="componentId"in c?c.componentId:e.rootNodeId,d=a0(e,u),f=o[d.value.type];if(!f)throw new Error(`Definition with ID ${d.value.type} not found`);let p="fieldId"in c?c.fieldId:c.parameterId,m=f.parameters?.find(w=>w.id===p),g=c.fromLocale??c.locale??n,h=c.locale??n,v=m??{id:p,type:"unknown"};if(c.editInstructions===void 0)return{result:{success:!0,newValue:"",treatNewValueAsJson:!1,action:"nothing"},update:c,propertyDefinition:v};if(c.editInstructions==="")return{result:{success:!0,newValue:"",treatNewValueAsJson:!1,action:"clearValue"},update:c,propertyDefinition:v};if(!m)throw new Error(`Property with ID ${p} not found`);if(m.type==="contentReference"){let w=X5({definition:m,twee:e,nodeId:u,currentEditorLocale:n}),E=zp(u,p,w,-1),_=d.value._dataResources?.[E],$=await a.invoke("createDataResourceEdit",{edit:c.editInstructions,dataType:ll,currentValue:_?.variables||{}});if(!$.success)throw new Error($.summary??"Failed to edit reference field data resource");return{result:{success:!0,newValue:JSON.stringify({type:ll,variables:$.newValue}),treatNewValueAsJson:!0,action:"setValue"},update:c,propertyDefinition:m,currentLocale:w}}let y=nLe({property:e.getNodeProperty(u,p),locale:g,conditionIndex:-1}),b,S=e.getNodeProperty(u,rLe);S?.value?.dim&&(b=await r.getDimensionGuidance(S.value.dim));let C=await a.invoke("createPropertyEdit",{edit:c.editInstructions,propertyDefinition:{id:p,name:m.name,type:m.type,guidance:m.guidance,typeConfig:m.typeConfig},outputLocale:h,documentContext:void 0,currentValue:y,projectGuidance:s,componentGuidance:f.description,audienceGuidance:b});if(!C.success)throw new Error(C.summary??"Failed to edit property");return{result:C,update:c,propertyDefinition:m,currentLocale:h}})()));return l.forEach((c,u)=>{if(c.status==="rejected"){let d=t[u],f="fieldId"in d?d.fieldId:d.parameterId;i({summary:`Failed to edit property ${f}: ${"message"in c.reason?c.reason.message:"Unknown error"}`,success:!1})}}),l.filter(c=>c.status==="fulfilled").map(c=>c.value)}async function aLe({dataResourceUpdates:t,twee:e,referenceData:n,results:r,dataSourceVariant:o}){if(t.length===0)return[];let i=await n.getToolClient(),s=await Promise.allSettled(t.map(async a=>(async()=>{let l=a.componentId,c=a0(e,l);if(a.editInstructions===void 0)return{result:{success:!0,newValue:{},action:"nothing"},update:a,dataType:"unknown"};if(a.editInstructions==="")return{result:{success:!0,newValue:{},action:"setValue"},update:a,dataType:"unknown"};let u=c.value._dataResources?.[a.dataResourceName],d=c.value._patternDataResources?.[a.dataResourceName];if(!d)throw new Error(`Pattern data resource ${a.dataResourceName} does not exist on the ${c.value._pattern} pattern`);let f=u?.variables??d.variables,p=d.type,m=await i.invoke("createDataResourceEdit",{edit:a.editInstructions,dataType:p,currentValue:f,dataSourceVariant:o});if(!m.success)throw new Error(m.summary??"Failed to edit data resource");return{result:m,update:a,dataType:p}})()));return s.forEach((a,l)=>{if(a.status==="rejected"){let c=t[l];r.push({summary:`Failed to edit data resource ${c.dataResourceName}: ${"message"in a.reason?a.reason.message:"Unknown error"}`,success:!1})}}),s.filter(a=>a.status==="fulfilled").map(a=>a.value)}import{CANVAS_BLOCK_PARAM_TYPE as Gs,CANVAS_ENRICHMENT_TAG_PARAM as sse,CANVAS_LOCALE_TAG_PARAM as Ab,CANVAS_LOCALIZATION_SLOT as iI,CANVAS_LOCALIZATION_TYPE as JLe,CANVAS_PERSONALIZATION_PARAM as Mb,CANVAS_PERSONALIZE_SLOT as ase,CANVAS_SLOT_SECTION_SLOT as XLe,CANVAS_SLOT_SECTION_TYPE as o5,CANVAS_TEST_SLOT as lse,CANVAS_TEST_VARIANT_PARAM as cse,CANVAS_VIZ_CONTROL_PARAM as Sd,convertToBindExpression as use,createVariableReference as dse,getEffectivePropertyValue as fse,getPropertiesValue as QLe,parseVariableExpression as pse,walkNodeTree as Cc,walkPropertyValues as eAe}from"@uniformdev/canvas";var Lp=I(ZO(),1),gse=I(E0(),1);import{produce as tr}from"immer";import{v4 as wd}from"uuid";import{v4 as dLe}from"uuid";async function Die({projectMapClient:t,compositionId:e,compositionName:n,nodePathSegment:r,parentNodeId:o,localePathSegments:i,allowedQueryStrings:s}){let l=(await t.getProjectMapDefinition({}))?.projectMaps[0]?.id;if(!l)throw new Error("No project map found for this project");let c=r||i?.[0]?.pathSegment,u,d=0;if(o){let h=(await t.getNodes({id:o})).nodes?.[0];if(!h)throw new Error("Parent node not found");let v=h.path;d=((await t.getNodes({path:v,depth:1,expanded:!1})).nodes?.filter(C=>C.path!==v)??[]).reduce((C,w)=>Math.max(C,w.order??0),-1)+100,u=`${v==="/"?"":v}/${c}`}else u=`/${c}`;let f=i?.reduce((g,{locale:h,pathSegment:v})=>(g[h]={pathSegment:v,name:v},g),{}),p=s?.map(({name:g,defaultValue:h})=>({name:g,...h!==void 0&&{value:h}})),m=dLe();return await t.upsertProjectMapNodes({projectMapId:l,nodes:[{node:{id:m,name:n,path:u,type:"composition",compositionId:e,order:d,...f&&{locales:f},...p&&{data:{queryStrings:p}}}}]}),{path:u,nodeId:m}}import{bindVariablesToObject as fLe}from"@uniformdev/canvas";var Nb="Untitled",Lie=60;function Aie({value:t,isNew:e,contentType:n}){let{result:r}=fLe({value:t,handleBinding:()=>"{token}",variables:{}}),o=n.entryName??"",i=(n.fields??[]).find(s=>s.id===o);if(typeof r=="string"){if(i?.type==="image")return r.length>0?`Image: ${mLe(r)}`:`${Nb} image`;if(r.length>0)return i?.type==="date"?hLe(r)?vLe(r):"Invalid date":Np(r)}else{if(typeof r=="number"||typeof r=="boolean")return r.toString();if(typeof r<"u"&&r!==null){if(i?.type==="link")return pLe(r);if(uk(r))return Np(Y5(r.root));if(i?.type==="datetime"&&r){let s=r;return s.datetime&&Mie(s.datetime)?yLe(s.datetime):"Invalid datetime"}else return Np(bLe(r).description)}}return e?`New entry: ${n.name}`:Nb}function pLe(t){return t?t.type==="projectMapNode"?t.path.length>0?`Link to ${Np(t.path)}`:`Link to project map node (${t.nodeId})`:t.path.length>0?`Link to ${Np(t.path)}`:`${Nb} link`:`${Nb} link`}function mLe(t){try{let{pathname:e,hostname:n}=new URL(t),r=e.split("/").filter(o=>o);return r.length>2?`/${r[0]}/.../${r[r.length-1]} (${Np(n)})`:`${e} (${Np(n)})`}catch{return t}}function Np(t){let e=t.split(" ").filter(i=>i).reverse();if(e.length<1)return Nb;let n="",r=e.pop(),o=()=>n.length+(r?.length??0)+(n.length>0?1:0);for(;r&&o()<Lie;)n+=n.length>0?` ${r}`:r,r=e.pop();return n.length<1?`${t.slice(0,Lie)}...`:e.length>0?`${n}...`:n}var gLe=/^[1-9][0-9]{3}-[0-1][0-9]-[0-3][0-9]$/;function hLe(t){return gLe.test(t)?Mie(t):!1}function Mie(t){let e=new Date(t);return e instanceof Date&&!isNaN(Number(e))}function vLe(t){return new Date(t).toLocaleDateString()}function yLe(t){return new Date(t).toLocaleString()}function bLe(t){let e=qO(t);return e?{description:e,named:!0}:{description:xLe(t).valuePreview,named:!1}}function xLe(t){if(typeof t>"u")return{valueIcon:"close-o",valuePreview:"undefined"};if(t===null)return{valueIcon:"close-o",valuePreview:"null"};if(Array.isArray(t))return{valuePreview:`array with ${t.length} item${t.length!==1?"s":""}`,valueIcon:"list"};if(typeof t=="boolean")return{valuePreview:t.toString(),valueIcon:t?"check-r":"close-r"};if(typeof t=="number"||typeof t=="bigint")return{valuePreview:t.toString(10),valueIcon:"number-input"};if(typeof t=="object"){let e=Object.keys(t);return{valuePreview:`object with ${e.length} ${e.length!==1?"properties":"property"}`,valueIcon:"shape-hexagon"}}return{valuePreview:t,valueIcon:"text-input"}}var CLe=["displayName","name","_name","title","heading","label","parameters","fields","properties","entry","slug","_slug","alt","alt_description","description","results","items","entries","hits","value","id","objectID","identifier"];function qO(t){if(typeof t=="string")return t;if(typeof t=="number")return t.toString(10);if(typeof t=="boolean")return t.toString();if(typeof t!="object"||t===null)return;if(Array.isArray(t)){if(t.length===0)return;let r=qO(t[0]);return r?t.length===1?r:`${r} and ${t.length-1} other${t.length>2?"s":""}`:void 0}let n=t;for(let r of CLe)if(r in n){let o=qO(n[r]);if(o)return o}}import{CANVAS_SLOT_SECTION_SLOT as SLe,walkNodeTree as wLe}from"@uniformdev/canvas";import{v4 as Oie}from"uuid";var Db="|";function XE(t,e){if(!t)return e??Oie();let n=t.split(Db),r=(e??Oie()).split(Db);return n.at(-1)===r[0]&&n.pop(),n.concat(r).join(Db)}function kie(t){let e=t.indexOf(Db);if(e<0)throw new Error(`Cannot remove pattern instance ID from ${t}`);return t.substring(e+1)}function QE(t,e,n=!1){wLe(t,({node:r,actions:{setDescendantsContext:o},context:i})=>{let s=!n&&!i?.currentParentPatternInstanceId,a="_pattern"in r&&!!r._pattern;if(i?.currentParentPatternInstanceId){let c=XE(i.currentParentPatternInstanceId,r._id);r._id=c}let l=i?.currentParentPatternInstanceId;a&&(l=r._id),"_overrides"in r&&r._overrides&&Iie(r._overrides,l,s),"_patternOverrides"in r&&r._patternOverrides&&Iie(r._patternOverrides,l,s),a&&o({currentParentPatternInstanceId:r._id})},{initialContext:{currentParentPatternInstanceId:e}})}var Iie=(t,e,n)=>{Object.entries(t).forEach(([r,o])=>{let i=n?r:XE(e,r);Object.entries(o.slots??{}).forEach(([s,a])=>{a.forEach(l=>{let{partOfNestedPattern:c}=e5(r??"");QE(l,s===SLe&&!c?void 0:e,!0)})}),i&&(delete t[r],t[i]=o)})};function e5(t){let e=t.split(Db);return e.length===1?{partOfPattern:void 0,partOfNestedPattern:void 0}:e.length===2?{partOfPattern:e[0],partOfNestedPattern:void 0}:{partOfPattern:e[0],partOfNestedPattern:e[e.length-2]}}import{CANVAS_SLOT_SECTION_SLOT as jie}from"@uniformdev/canvas";import{CANVAS_VIZ_CONTROL_PARAM as NLe}from"@uniformdev/canvas";import{CANVAS_ENRICHMENT_TAG_PARAM as Rie,CANVAS_INTENT_TAG_PARAM as ELe,CANVAS_LOCALE_TAG_PARAM as _Le,CANVAS_PERSONALIZATION_PARAM as Pie,CANVAS_TEST_VARIANT_PARAM as TLe,CANVAS_VIZ_CONTROL_PARAM as Fie}from"@uniformdev/canvas";var $Le="$internal_displayName",Bie=[{id:$Le,name:"Display Name",type:"text"},{id:ELe,name:"Intent Tag",type:"intentTag"},{id:_Le,name:"Locale Visibility",type:"localeSelect"},{id:Pie,name:"Personalization Criteria",type:Pie},{id:Rie,name:"Enrichment Tags",type:Rie,helpText:"Seeing this component will increase a visitor's score in these enrichments."},{id:TLe,name:"A/B Test",type:"testVariant"},{id:Fie,name:"Visibility Control",type:Fie}];var DLe=Bie.reduce((t,e)=>(e.id===NLe||t.add(e.id),t),new Set);function Dp(t,e){return DLe.has(e)?"yes":t?.parameters?.[e]??"no"}function JO(t,e){e&&Object.entries(e).forEach(([n,r])=>{let o=t[n];if(r.parameters||o?.parameters){t[n]??={};let i={...r?.parameters};Object.entries(o?.parameters??{}).forEach(([s,a])=>{let l=i[s];if(!l)i[s]=a;else if(a.locales||a.localesConditions||l.locales||l.localesConditions){let c={...l,...a};(a.locales||l.locales)&&(c.locales={...l.locales,...a.locales}),(a.localesConditions||l.localesConditions)&&(c.localesConditions={...l.localesConditions,...a.localesConditions}),i[s]=c}else i[s]={...l,...a}}),t[n].parameters=i}if((r.dataResources||o?.dataResources)&&(t[n]??={},t[n].dataResources={...r?.dataResources,...o?.dataResources}),r.slots||o?.slots){t[n]??={};let i=Object.entries(o?.slots??{}).reduce((s,[a,l])=>(s[a]&&Array.isArray(s[a])?s[a]=[...l,...s[a]]:s[a]=l,s),r.slots??{});t[n].slots=i}(r.variant!==void 0||o?.variant!==void 0)&&(t[n]=t[n]??{},t[n].variant=o?.variant??r?.variant)})}function zie({applyOverrideToNode:t}){let e=new Set,n={};return{visitNode(r){e.add(r._id),JO(n,r._overrides),JO(n,r._patternOverrides);let o=n[r._id];o&&(o.parameters&&Object.keys(o.parameters).forEach(i=>{Dp(r._overridability,i)==="no"&&(console.log(`[Override] Cleaned override from ${r._id} parameter ${i} because it is not overridable`),delete n[r._id].parameters?.[i])}),o.dataResources&&Object.keys(o.dataResources).forEach(i=>{r._patternDataResources?.[i]?.isPatternParameter||(console.log(`[Override] Cleaned override from ${r._id} data resource ${i} because it is not overridable`),delete n[r._id].dataResources?.[i])}),o.variant!==void 0&&(r._overridability?.variants||delete o.variant),t({node:r,overrides:o}))},overrides:n}}function XO(t){let{beforeApplyParameterOverride:e,beforeApplyDataResourceOverride:n}=t??{};return zie({applyOverrideToNode({node:r,overrides:o}){if(Object.entries(o.parameters??{}).map(([i,s])=>{r.parameters=r.parameters??{},e?.(r,i,s,r.parameters[i]);let a=r.parameters[i]??={type:s.type};s.locales||s.localesConditions?(a.locales??={},delete a.value,delete a.conditions,new Set([...Object.keys(s.locales??{}),...Object.keys(s.localesConditions??{})]).forEach(u=>{delete a.locales?.[u],delete a.localesConditions?.[u];let d=s.locales?.[u],f=s.localesConditions?.[u];d!=null&&(a.locales??={},a.locales[u]=d),f!=null&&(a.localesConditions??={},a.localesConditions[u]=f)}),a.locales&&Object.keys(a.locales).length===0&&delete a.locales,a.localesConditions&&Object.keys(a.localesConditions).length===0&&delete a.localesConditions):(delete a.locales,delete a.localesConditions,delete a.conditions,delete a.value,s.value!==null&&s.value!==void 0&&(a.value=s.value,a.connectedData=s.connectedData),s.conditions!==null&&s.conditions!==void 0&&(a.conditions=s.conditions)),!a.locales&&!a.localesConditions&&!a.conditions&&a.value===void 0&&delete r.parameters[i]}),Object.entries(o.dataResources??{}).forEach(([i,s])=>{n?.(r,i,s,r._dataResources?.[i]),r._dataResources??={},r._dataResources[i]=s}),o.variant!==void 0&&(r.variant=o.variant),o.slots){r.slots??={};let i=Object.keys(o.slots)[0];r.slots[jie]??=[],r.slots[jie]=[...o.slots[i]??[]]}}})}import{CANVAS_SLOT_SECTION_SLOT as LLe,CANVAS_SLOT_SECTION_TYPE as ALe}from"@uniformdev/canvas";var Vie=({preserveOwnSlotSections:t=!1,preserveChildrenSlotSections:e=!1}={})=>n=>{if(n.node.type!==ALe)return;let{partOfPattern:r,partOfNestedPattern:o}=e5(n.node._id??"");!r&&!o&&t||r&&!o&&e||MLe(n)},MLe=({node:t,type:e,actions:n})=>{e!=="entry"&&(n.insertAfter(t.slots?.[LLe]??[]),n.remove())};import{walkNodeTree as RLe}from"@uniformdev/canvas";import{produce as PLe}from"immer";import{v4 as FLe}from"uuid";import{CANVAS_SLOT_SECTION_SLOT as Uie,walkNodeTree as OLe}from"@uniformdev/canvas";import{produce as ILe}from"immer";import{v4 as kLe}from"uuid";function t5(t,e,n,r=kLe()){if(!t._pattern)throw new Error("Not a pattern");let o={};return OLe(t,({node:i,ancestorsAndSelf:s,actions:a})=>{let l=i._id,c=e[l];if(s.length===1)i._id=r;else{let d=s[0];d.type!=="slot"||d.parentSlot!==Uie?(i._id=kie(l),i._id=XE(r,i._id)):(a.replace({...o[l],_id:o[l]._id}),a.stopProcessingDescendants())}if(c){let d=ILe(c,f=>{f.slots&&Object.entries(f.slots).forEach(([p,m])=>{if(p!==Uie)throw new Error("Only slot section items are supported for duplication");m.forEach((g,h)=>{if(!g._id)return;let v=n5(g,e,n);o[g._id]=v,m[h]=v})})});n?.(i._id,d,l)}}),r}function n5(t,e,n){return PLe(t,r=>{RLe(r,({type:o,node:i,actions:{stopProcessingDescendants:s}})=>{o==="component"&&i._pattern?(t5(i,e,n),s()):i._id=FLe()})})}import{produce as BLe}from"immer";import{v4 as zLe}from"uuid";function Hie(t,e=zLe()){return BLe(t,n=>(n._pattern?t5(n,n._overrides??{},(r,o,i)=>{delete n._overrides[i],n._overrides[r]=o},e):n._id=e,n))}import{bindExpressionPrefix as Kie}from"@uniformdev/canvas";var jLe=new Set(["t","a","p","c"]),VLe=new Set(["w","e","i"]);function Wie(t){if(!t.startsWith(Kie))return;let[n,r,...o]=t.substring(Kie.length).split(":");if(n==="jptr"){if(!r)throw new Error(`Missing JSON pointer in dynamic token binding '${t}'`);let i="t",s="w",a;for(let l of o){let[c,u]=l.split("=");if(c==="fa"){if(!jLe.has(u))throw new Error(`Invalid failure action '${u}' in dynamic token binding '${t}'`);i=u}else if(c==="fl"){if(!VLe.has(u))throw new Error(`Invalid failure log level '${u}' in dynamic token binding '${t}'`);s=u}else if(c==="fd")a=HLe(u);else throw new Error(`Unsupported property '${l}' in dynamic token binding '${t}'`)}return{pointer:Gie(ULe(r)),syntax:n,failureAction:i,failureLogLevel:s,failureDefault:i==="t"?a:void 0}}throw new Error(`Unsupported dynamic token binding syntax '${n}'`)}function ULe(t){return t.replace(/\$\[([^}]+)\]/g,"${$1}")}function Gie(t){let e=t.split("\\");return e.map((n,r)=>{if(n==="")return r>0&&e[r-1]===""?"":"\\";let o=n[0],i=n.substring(1);return o===";"&&(o=":"),i?o+i:o}).join("")}function HLe(t){return Gie(t.replace("\\+","="))}function Yie(t){if(!t?.pointer)return;let e=t.pointer.indexOf("/",1);return e<0?{dataResource:t.pointer.substring(1)}:{dataResource:t.pointer.substring(1,e),dataExpression:t.pointer.substring(e)}}function r5({locale:t,conditionIndex:e,property:n}){if(t===void 0)if(e<0){if(delete n.value,!n.conditions?.length)return!1}else n.conditions?.splice(e,1);else e<0?delete n.locales?.[t]:n.localesConditions?.[t]?.splice(e,1);if(n.localesConditions){for(let[r,o]of Object.entries(n.localesConditions))if(o.length===0){delete n.localesConditions[r];break}Object.keys(n.localesConditions).length===0&&delete n.localesConditions}return n.locales&&Object.keys(n.locales).length===0&&delete n.locales,n.conditions&&n.conditions.length===0&&delete n.conditions,!!(n.value!==void 0||n.locales||n.conditions||n.localesConditions)}function QO({locale:t,conditionIndex:e,conditionDefinition:n,property:r,newPropertyValue:o}){t===void 0?e<0?r.value=o:(r.conditions??=[],Zie(r.conditions,e,n,o)):e<0?(r.locales??={},r.locales[t]=o):(r.localesConditions??={},r.localesConditions[t]??=[],Zie(r.localesConditions[t],e,n,o))}function Zie(t,e,n,r){if(e<0)throw new Error("Condition index must be greater than or equal to 0");let o=t[e];t[e]={when:n??o?.when??{clauses:[]},value:r===void 0?null:r,id:o?.id??KLe(t)}}function KLe(t){let e=new Set(t.map(r=>r.id)),n=0;for(;e.has(n);)n++;return n}function qie(t){let e=!1,n={};return"_pattern"in t&&t._patternDataResources&&Object.entries(t._patternDataResources).forEach(([r,o])=>{e=!0,n[r]={...o,source:"patternDataResource"}}),t._dataResources&&Object.entries(t._dataResources).forEach(([r,o])=>{n[r]?n[r].isPatternParameter&&(e=!0,n[r]={...o,source:"dataResource"}):(e=!0,n[r]={...o,source:"dataResource"})}),e?n:void 0}import{CANVAS_DRAFT_STATE as WLe,convertEntryToPutEntry as FEt,getPropertiesValue as jEt}from"@uniformdev/canvas";function Jie(t){let{fields:e,entryName:n,type:r="contentType",thumbnailField:o,...i}=t;return{...i,titleParameter:n,thumbnailParameter:o,parameters:e,canBeComposition:r==="block",permissions:t.permissions,useTeamPermissions:t.useTeamPermissions??!0,workflowId:t.workflowId}}function Xie(t){return{id:t.id,name:t.name,entryName:t.titleParameter,thumbnailField:t.thumbnailParameter,fields:t.parameters,icon:t.icon,description:t.description,slugSettings:t.slugSettings,type:t.canBeComposition?"block":"contentType",created:t.created,updated:t.updated,permissions:t.permissions,useTeamPermissions:t.useTeamPermissions,workflowId:t.workflowId||void 0}}function Lb(t){let{entry:{fields:e,...n},...r}=t;return{created:"",modified:"",composition:{_id:"",...n,_name:t.entry._name??"Untitled",parameters:e,_overridability:t.entry._overridability,_overrides:t.entry._overrides,_pattern:t.entry._pattern,_patternError:t.entry._patternError},pattern:!!t.pattern,previewImageUrl:t.entry._thumbnail,...r}}function Qie(t,e,n,r,o,i,s){let a=s??e.projectId;if(!a)throw new Error("projectId is required in currentEntry or explicitly");return{created:e.created??"",modified:e.modified??"",projectId:a,state:r??e.state??WLe,releaseId:o??e.releaseId,workflowId:n?.workflowId??e.workflowId,workflowStageId:n?.workflowStageId??e.workflowStageId,editionId:i,editionName:n?.editionName??e.editionName,editionPriority:n?.editionPriority??e.editionPriority,pattern:e.pattern,entry:{type:t.type,_id:t._id,_name:t._name,_slug:t._slug??"",fields:t.parameters,_thumbnail:n?.previewImageUrl??void 0,_dataResources:t._dataResources,_pattern:t._pattern,_patternError:t._patternError,_overridability:t._overridability,_overrides:t._overrides,_locales:t._locales,_author:t._author,_authorSubject:t._authorSubject,_creator:t._creator,_creatorSubject:t._creatorSubject,_patternDataResources:t._patternDataResources}}}function eI(t,e){let{parameters:n,...r}=t;return{...r,_id:e??r._id??"unknown",fields:n}}function tI(t){let{fields:e,...n}=t;return{...n,parameters:e}}function nI(t){let e=Wie(t);if(e)switch(e.syntax){case"jptr":return Yie(e);default:throw new Error(`Unsupported dynamic token binding syntax '${e.syntax}'`)}}import{CANVAS_VIZ_LOCALE_RULE as GLe}from"@uniformdev/canvas";import{produce as YLe}from"immer";function ese(t,e,n){let r=YLe(t.criteria,o=>tse(o,e,n));return r&&{...t,criteria:r}}function tse(t,e,n){if(!t)return t;let r=!1;for(let o of t.clauses)if("clauses"in o){let i=tse(o,e,n);if(i===null){if(t.op!=="|")return null;t.clauses.splice(t.clauses.indexOf(o),1),r=!0}else i!==void 0&&(t.clauses[t.clauses.indexOf(o)]=i,r=!0)}else if(o.rule===GLe){let i=Array.isArray(o.value)?o.value:[o.value],s=i.includes(e),a=i.includes(n);if(!s&&!a||s&&a)continue;if(i.length===1&&a&&!s)return null;s&&!a&&(o.value=i.concat(n),r=!0)}return r?t:void 0}var nse=I(ZO(),1);function rI(t,e){try{return(0,nse.get)(t,e)}catch{return}}function oI(t,e,n=0){let r=t.slice(n*4,n*4+4);if(!r)throw new Error("Failed to generate a default variation name");return`${e.startsWith("$")?e.slice(1):e}-${r}`}import{CANVAS_VIZ_LOCALE_RULE as ZLe}from"@uniformdev/canvas";import{produce as qLe}from"immer";function rse(t,e){let n=qLe(t.criteria,r=>ose(r,e));return n&&{...t,criteria:n}}function ose(t,e){if(!t)return t;for(let n=t.clauses.length-1;n>=0;n--){let r=t.clauses[n];if("clauses"in r){let o=ose(r,e);if(o)t.clauses[n]=o;else if(t.clauses.splice(n,1),o===null&&t.op!=="|")return null}else if(r.rule===ZLe){let o=Array.isArray(r.value)?r.value:[r.value],i=o.indexOf(e);if(i!==-1)if(Array.isArray(r.value)&&r.value.length>1)o.splice(i,1);else if(r.op.startsWith("!"))t.clauses.splice(n,1);else return null}}if(t.clauses.length!==0)return t}function ise(t,e){let n=w0();if(process.env.NODE_ENV==="development"&&!e){let r=new Error().stack?.split(`
5836
5836
  `).slice(2).join(`
5837
- `).trimStart();n.on("*",(o,i)=>{console.debug(`\u26A1\uFE0F ${t}:${String(o)}`,{args:i,stack:r,subs:n.all.get(String(o))?.length??0})})}return n}var ps=(0,gse.default)(),tAe=!0,nAe="Twee",ol=class t{#e={};rootNodeId;#r={};#o={};#n;#i={};#t=ise(nAe,tAe);#c;#u;#g;#d;#a;#s;constructor(e,n){let{metadata:r,startDirty:o}=n||{};this.#a=r??{},this.#s={_name:e?._name??"",_slug:e?._slug??null},this.#d=!o;let i=tr(e,s=>{this.#v({composition:s,ignoreRootOverrides:!0,preserveChildrenSlotSections:!0}),delete s._author,delete s._authorSubject,delete s._creator,delete s._creatorSubject});this.rootNodeId=i._id??wd(),this.#c=this.rootNodeId,this.#l({componentTree:i,nodeId:this.rootNodeId}),this.#n=i._overrides??{}}events=this.#t;exportTree(e){return this.exportSubtree(this.rootNodeId,e)}exportMetadata(){return this.#a}exportRootNodeMetadata(){return this.#s}get pristine(){return this.#d}set pristine(e){this.#d!==e&&(this.#d=e,this.#t.emit("pristineChanged",{pristine:e}))}get selectedBlockIdStack(){return this.#u}set selectedBlockIdStack(e){this.#u=e,this.#t.emit("selectedBlockChanged",{selectedBlockIds:this.#u})}get selectedNodeId(){return this.#c}set selectedNodeId(e){this.#c!==e&&(this.#c=e,this.selectedParameterId=void 0,this.#t.emit("selectedNodeChanged",{selectedNodeId:e}))}get selectedParameterId(){return this.#g}set selectedParameterId(e){this.#g!==e&&(this.#g=e,this.#t.emit("selectedParameterChanged",{selectedParameterId:e}))}pushSelectedBlockId(e){this.selectedBlockIdStack=this.selectedBlockIdStack??[],this.selectedBlockIdStack?.push(e),this.#t.emit("selectedBlockChanged",{selectedBlockIds:this.selectedBlockIdStack})}popSelectedBlockId(){this.#u?.pop(),this.#t.emit("selectedBlockChanged",{selectedBlockIds:this.selectedBlockIdStack})}getNodeById(e){return this.#e[e]}getNodesIndex(){return this.#e}getBlockNodeValueById(e){return eI(this.exportSubtree(e),e)}getNodeChildren(e){let n=this.#r[e];if(n)return n}getNodeProperty(e,n){return rI(this.#o,[e,n])}getNodeProperties(e){return this.#o[e]??{}}insertNode({node:e,parentNodeId:n,parentSlot:r,targetIndexInSlot:o,overrideNodeId:i}){let s=i??wd();if(!this.#_(n))throw new Error("Cannot insert component into a read-only pattern slot unless it is within a slot section");let l={nodeId:s,parentId:n,value:t.#E(e),isExpandedInUI:!0,propertyValueLocalizability:{}};return this.#S({node:l,parentNodeId:n,parentSlot:r,targetIndexInSlot:o}),this.#m({nodeId:s,destinationParentId:n,destinationSlotName:r}),this.pristine=!1,this.#t.emit("nodeChanged",{changedNode:l,oldValue:void 0,type:"new"}),this.#t.emit("childrenChanged",{parentId:n,slotOrBlockName:r,newChildIds:this.#r[n][r],type:"slot"}),s}upsertBlockNode({nodeId:e,property:n,index:r,entry:o}){let i=this.#w({nodeId:e,property:n,index:r,entry:o});return this.pristine=!1,this.#t.emit("childrenChanged",{parentId:e,slotOrBlockName:n,newChildIds:this.#o[e]?.[n]?.value,type:"block"}),i}updateRootMetadata(e){let n={...this.#a};this.#a={...this.#a,...e},this.pristine=!1,this.#t.emit("metadataChanged",{metadata:this.#a,oldValue:n})}updateRootNode({update:e,doNotSetDirty:n}){let r={...this.#s};this.#s={...this.#s,...e},n||(this.pristine=!1),this.#t.emit("rootNodeMetadataChanged",{metadata:this.#s,oldValue:r})}insertPattern({parentNodeId:e,parentSlot:n,pattern:r,targetIndexInSlot:o,patternInstanceId:i}){let s=i??wd();if(this.#e[s])throw new Error(`Node with ID '${s}' already exists. Pattern nodes must have unique IDs. Did you mean to move or duplicate this pattern instead?`);let a=this.#b(r,s,!1);return this.#f({nodeId:a,parentNodeId:e,parentSlot:n,targetIndexInSlot:o}),this.#m({nodeId:a,destinationParentId:e,destinationSlotName:n}),this.pristine=!1,this.visitNodeAndDescendants(a,l=>{this.#t.emit("nodeChanged",{changedNode:l,oldValue:void 0,type:"new"})}),this.#t.emit("childrenChanged",{parentId:e,slotOrBlockName:n,newChildIds:this.#r[e][n],type:"slot"}),a}unlinkPattern(e){let n=this.#e[e];if(!n)throw new Error(`Node ${e} does not exist`);if(!n.value._pattern)throw new Error(`Node ${e} is not a pattern`);let r=n.value._patternDataResources||n.value._dataResources,o=qie(n.value),i=a=>{a.partOfNestedPattern||(this.updateNode({nodeId:a.nodeId,updateComponent:l=>{delete l._pattern,delete l._patternError,delete l._overrides},updateMetadata:l=>{delete l.partOfPattern,delete l.partOfNestedPattern},doNotSetDirty:!0,ignoreOverrides:!0}),this.#n[a.nodeId]&&(this.#n=tr(this.#n,l=>{delete l[a.nodeId]})))};this.visitNodeAndDescendants(e,i);let s=a=>{a.partOfNestedPattern&&this.updateNode({nodeId:a.nodeId,updateMetadata:l=>{l.partOfPattern=l.partOfNestedPattern,delete l.partOfNestedPattern},doNotSetDirty:!0,ignoreOverrides:!0})};this.visitNodeAndDescendants(e,s),r&&(this.updateNode({nodeId:this.rootNodeId,updateDataResources:a=>Object.entries(o??{}).filter(([l])=>!(l in(a??{}))).map(([l,c])=>{let{source:u,...d}=c;return{type:"set",name:l,value:d}})}),this.updateNode({nodeId:n.nodeId,updateComponent:a=>{delete a._patternDataResources},updateDataResources:"removeAll",doNotSetDirty:!0,ignoreOverrides:!0})),this.pristine=!1}convertToPattern({existingNodeId:e,pattern:n}){let r=this.#e[e],o=r?.parentId;if(!r)throw new Error(`Node ${e} does not exist`);let i=this.#b(n,e,!0);this.#e[i]=tr(this.#e[i],a=>{a.parentId=o}),this.pristine=!1;let s=this.#e[i];this.#t.emit("nodeChanged",{changedNode:s,oldValue:r,type:"new"}),Object.entries(this.#r[i]??{}).forEach(([a,l])=>{this.#t.emit("childrenChanged",{newChildIds:l,parentId:i,slotOrBlockName:a,type:"slot"})})}copyNodeToClipboard(e){let n=this.exportSubtree(e,{keepPatternData:!1}),r=this.exportSubtree(e,{keepPatternData:!0}),o=[];Cc(r,({node:a})=>{a._id&&o.push(a._id)}),Cc(n,({node:a})=>{a._id&&(a._overrides&&delete a._overrides,"_name"in a&&delete a._name,"_slug"in a&&delete a._slug)});let i=this.#h(),s=Object.entries(i??{}).reduce((a,[l,c])=>(o.some(u=>l.includes(u))&&(a[l]=c),a),{});return{format:"uniform/copied-component-subtree-1.0",componentData:n,overrides:Object.keys(s).length?s:void 0,pasteAs:this.getNodeById(e)?.isBlock?"block":void 0}}async pasteNodeFromClipboard({parentNodeId:e,parentSlot:n,targetIndexInParent:r,clipboard:o,resolvePattern:i}){let s=ps(o),a=async c=>{c._pattern&&l.push((async()=>{let u=await i(c._pattern);if(!u){console.debug(`Pasted pattern ${c._pattern} not found, skipping`);return}let d=this.#x(u,c._id);Object.assign(c,d)})())},l=[];return Cc(s.componentData,({node:c})=>{a(c)}),s.overrides&&Object.values(s.overrides).forEach(c=>{c.slots&&Object.values(c.slots).forEach(u=>{u.forEach(d=>{Cc(d,({node:f})=>{a(f)})})})}),await Promise.all(l),this.#T(s.componentData,{parentId:e,parentName:n,parentType:o.pasteAs==="block"?"block":"slot",targetIndexInParent:r},s.overrides)}enableLocale(e){this.updateNode({nodeId:this.rootNodeId,updateComponent:n=>{let r=n;r._locales??=[];let o=[...new Set([...r._locales,...Array.isArray(e)?e:[e]])];r._locales=o}})}disableLocale(e){this.updateNode({nodeId:this.rootNodeId,updateComponent:o=>{let i=o;i._locales=i._locales?.filter(s=>s!==e)}});let n=[],r=o=>{this.getNodeProperty(o.nodeId,Ab)?.value===e&&!o.partOfPattern&&n.push(o.nodeId);let s=this.getNodeProperties(o.nodeId);Object.entries(s).forEach(([l,c])=>{let u=c;l!==Sd&&(o.partOfPattern?this.isPatternPropertyOverridden(o.nodeId,l,e)&&this.resetPatternPropertyOverride(o.nodeId,l,e):(u?.localesConditions?.[e]?.forEach((d,f)=>{this.updateNodeProperty({nodeId:o.nodeId,property:l,value:void 0,source:"other",locale:e,conditionIndex:f,conditionDefinition:null})}),u?.locales?.[e]!==void 0&&this.updateNodeProperty({nodeId:o.nodeId,property:l,value:void 0,source:"other",locale:e,conditionIndex:-1})))});let a=this.getNodeProperty(o.nodeId,Sd);if(a?.value){let l=rse(a.value,e);if(l===null)n.push(o.nodeId);else if(l===void 0||!$r(a.value,l)){let c=!o.partOfPattern,u=Dp(o.value._overridability,Sd)==="yes";(c||u)&&this.updateNodeProperty({nodeId:o.nodeId,property:Sd,value:l?()=>l:void 0,source:"other",locale:void 0,conditionIndex:-1})}}};this.visitNodeAndDescendants(this.rootNodeId,r),n.forEach(o=>{this.deleteNode(o)})}copyValuesToLocalePlan({sourceLocale:e,destinationLocale:n,doNotCopyDescendants:r=!1,startingNodeId:o=this.rootNodeId,specificPropertyId:i}){let s=new Map,a=c=>{if(c.value.type===JLe&&!c.partOfPattern){let d=this.getNodeChildren(c.nodeId)?.[iI]??[],f=d.map(g=>this.getNodeProperty(g,Ab)),p=f.findIndex(g=>g?.value===n);if(p>=0){let g=d[p];Ed(s,g).actions.push({type:"deleteLocalizedNode"})}let m=f.findIndex(g=>g?.value===e);if(m>=0){let g=d[m];Ed(s,g).actions.push({type:"duplicateLocalizedNode",targetIndexInSlot:p})}}if(s.get(c.nodeId)?.actions.some(d=>d.type==="deleteLocalizedNode"))return;let u=i?{[i]:this.getNodeProperty(c.nodeId,i)}:this.getNodeProperties(c.nodeId);Object.entries(u).forEach(([d,f])=>{if(f===void 0)return;let p=!c.partOfPattern,m=Dp(c.value._overridability,d)==="yes";if(!(p||m))return;if(d===Sd){let w=ese(f.value,e,n);w===null?Ed(s,c.nodeId).actions.push({type:"deleteLocalizedNode"}):w&&Ed(s,c.nodeId).actions.push({type:"updateVisibilityCriteria",targetValue:w})}let h=f.locales?.[e],v=f.locales?.[n];(!h||!v||!$r(h,v))&&(h!==void 0?Ed(s,c.nodeId).actions.push({type:"copyPropertyValue",propertyId:d,sourceValue:h,targetValue:v,conditionIndex:-1}):v!==void 0&&Ed(s,c.nodeId).actions.push({type:"deletePropertyValue",propertyId:d,sourceValue:h,targetValue:v,conditionIndex:-1}));let y=f.localesConditions?.[e],b=f.localesConditions?.[n];y?.forEach((w,E)=>{let _=f.localesConditions?.[n]?.[E];(!w||!_||!$r(w,_))&&Ed(s,c.nodeId).actions.push({type:"copyPropertyValue",propertyId:d,sourceValue:w.value,targetValue:_,conditionIndex:E,conditionDefinition:w.when})});let S=y?.length??0,C=b?.length??0;if(S<C){let w=Ed(s,c.nodeId);for(let E=S;E<C;E++)w.actions.push({type:"deletePropertyValue",propertyId:d,sourceValue:y?.[E],targetValue:b?.[E],conditionIndex:E})}})},l=this.#e[o];if(!l)throw new Error(`Node ${o} does not exist`);return a(l),!i&&!r&&this.visitDescendants(l.nodeId,a),{nodePlans:Array.from(s.values()),sourceLocale:e,destinationLocale:n}}async copyValuesToLocaleExecute({resolvePattern:e,plan:{sourceLocale:n,destinationLocale:r,nodePlans:o}}){let i=`copyLocaleExecute: ${r}`;console.time(i);for(let{nodeId:s,actions:a}of o)for(let l of a)switch(l.type){case"copyPropertyValue":{let c=this.getNodeProperty(s,l.propertyId)?.type,u=l.sourceValue;c==="contentReference"&&(u=this.prepareContentReferenceWrite({nodeId:s,propertyId:l.propertyId,destinationLocale:r,conditionIndex:l.conditionIndex,sourceValue:l.sourceValue})),this.updateNodeProperty({nodeId:s,property:l.propertyId,source:"other",locale:r,value:()=>u,type:c,conditionIndex:l.conditionIndex,conditionDefinition:l.conditionDefinition});break}case"deletePropertyValue":{this.updateNodeProperty({nodeId:s,property:l.propertyId,source:"other",locale:r,value:void 0,conditionIndex:l.conditionIndex,conditionDefinition:null});break}case"deleteLocalizedNode":{this.deleteNode(s);break}case"duplicateLocalizedNode":{let c=await this.duplicateNode(s,e);this.updateNodeProperty({nodeId:c,locale:void 0,conditionIndex:-1,type:"localeSelect",property:Ab,source:"other",value:()=>r});let u=this.copyValuesToLocalePlan({sourceLocale:n,destinationLocale:r,startingNodeId:c});this.copyValuesToLocaleExecute({plan:u,resolvePattern:e}),l.targetIndexInSlot!==void 0&&this.moveNode({movedNodeId:c,parentNodeId:this.#e[s].parentId,parentSlot:iI,targetIndexInSlot:l.targetIndexInSlot});break}case"updateVisibilityCriteria":{this.updateNodeProperty({nodeId:s,property:Sd,source:"other",locale:void 0,conditionIndex:-1,value:()=>l.targetValue});break}default:throw new Error(`Unhandled action type ${l.type}`)}console.timeEnd(i)}updateNode({nodeId:e,updateComponent:n,updateDataResources:r,updateMetadata:o,doNotSetDirty:i,ignoreOverrides:s}){let a=this.#e[e];if(!a)throw new Error(`Update target node ID ${e} did not exist!`);let l=tr(a,f=>{if(o&&(o(f),f.nodeId=e,f.value=a.value,f.parentId=a.parentId),n){if(n(f.value),"slots"in f.value)throw new Error("Do not set `slots` on a Twee node, insert child nodes instead.");if("parameters"in f.value)throw new Error("Do not set `parameters` on a Twee node, use updateProperties option instead.")}if(r){let p=typeof r=="function"?r(f.value._dataResources):r;if(p==="removeAll")delete f.value._dataResources;else for(let m of p){let g=s?!1:f.nodeId!==this.rootNodeId&&f.value._pattern;switch(m.type){case"set":g&&(this.#n=tr(this.#n,h=>{h[e]??={},h[e].dataResources??={},h[e].dataResources[m.name]=m.value})),f.value._dataResources??={},f.value._dataResources[m.name]=m.value;break;case"remove":g&&(this.#n=tr(this.#n,h=>{delete h[e]?.dataResources?.[m.name]})),delete f.value._dataResources?.[m.name];break;case"reset":{let h=this.#i[e]?.dataResources?.[m.name];f.value._dataResources&&(h&&Object.keys(h).length>0?f.value._dataResources[m.name]=h:delete f.value._dataResources[m.name]),this.#n=tr(this.#n,v=>{delete v[e]?.dataResources?.[m.name]})}break;default:throw new Error(`Unhandled data resource action ${m?.type}`)}}}}),c=!!(a.partOfPattern&&!a.value._patternError),u=a.value.variant!==l.value.variant,d=a.value._overridability?.variants??!1;!s&&c&&u&&d&&(this.#n=tr(this.#n,f=>{f[e]??={},f[e].variant=l.value.variant})),this.#e[e]=l,i||(this.pristine=!1),this.#t.emit("nodeChanged",{changedNode:l,type:"update",oldValue:a})}updateNodeProperty({nodeId:e,property:n,value:r,source:o,locale:i,type:s,doNotSetDirty:a=!1,ignoreOverrides:l=!1,conditionIndex:c,conditionDefinition:u}){let d=this.#e[e];if(!d)throw new Error(`Update target node ID ${e} did not exist!`);if(c<0&&u)throw new Error("Condition definition provided for non-conditional value");let f=!!(d.partOfPattern&&!d.value._patternError),p=[e,n],m=rI(this.#o,p);if(!m&&r==null)return;let g=fse({locale:i,property:m,conditionIndex:c}),h=i?m?.localesConditions?.[i]?.[c]:m?.conditions?.[c],v=typeof r=="function"?tr(g,w=>r(w)):r,y=s??m?.type;if(!y)throw new Error(`Cannot add parameter ${n} to node ${e} without specifying a type`);let b={...m,type:y},S=!1;b=tr(b,w=>{v===void 0&&c<0?S=!r5({locale:i,property:w,conditionIndex:c}):u===null&&c>=0?S=!r5({locale:i,property:w,conditionIndex:c}):QO({locale:i,property:w,newPropertyValue:v,conditionIndex:c,conditionDefinition:u??h?.when??{clauses:[]}})}),S&&(b=void 0);let C=f&&Dp(d.value._overridability,n)==="yes";if(f&&!C&&!l)throw new Error(`Cannot override parameter ${n} on node ${e} because it is not marked as overridable on the pattern (${d.partOfPattern})`);if(C&&(this.#i[e]?.parameters?.[n]||(this.#i=tr(this.#i,E=>{E[e]??={parameters:{},dataResources:{}},E[e].parameters[n]=m??{type:y,value:null}}))),!l&&C){let w=this.#n[e]?.parameters?.[n];this.#n=tr(this.#n,E=>{let $=v==null||b===void 0?null:v,T=w??{type:b?.type??m?.type??"unknown",value:m?.value,conditions:m?.conditions,locales:i&&m?.locales?.[i]?{[i]:m.locales[i]}:void 0,localesConditions:i&&m?.localesConditions?.[i]?{[i]:m.localesConditions[i]}:void 0},N=tr(T,P=>{u===null&&c>=0?r5({locale:i,property:P,conditionIndex:c}):QO({locale:i,property:P,newPropertyValue:$,conditionIndex:c,conditionDefinition:u??h?.when??{clauses:[]}})});(0,Lp.set)(E,`/${e}/parameters/${n}`,N)}),w||this.#t.emit("propertyOverrideCreated",{nodeId:e,property:n})}v===null?(0,Lp.remove)(this.#o,p):(this.#o[e]??={},(0,Lp.set)(this.#o,p,b)),a||(this.pristine=!1),this.#t.emit("nodeParameterChanged",{nodeId:e,parameter:n,locale:i,conditionIndex:c,value:b,previousValue:m,type:r?m?"update":"new":"delete",conditionDefinition:u,source:o})}isPatternPropertyOverridden(e,n,r,o){let i=this.getNodeById(e);if(!i||Dp(i.value._overridability,n)==="no")return!1;let s=this.#n[e]?.parameters?.[n];return s?r?(o===void 0||o===!0)&&s.localesConditions?.[r]!==void 0||(o===void 0||o===!1)&&s.locales?.[r]!==void 0:(o===void 0||o===!0)&&s.conditions!==void 0||(o===void 0||o===!1)&&s.value!==void 0:!1}getPatternPropertyOverrideDefaultValue(e,n,r){let o=this.#i[e]?.parameters?.[n];if(!o)return{exists:!1};if(r&&o.locales?.[r])return{exists:!0,value:o,sourceLocale:r};if(o.value!==void 0)return{exists:!0,value:o,sourceLocale:void 0};let i=Object.keys(o.locales??{})[0];return i?{exists:!0,value:o,sourceLocale:i}:{exists:!1}}resetPatternPropertyOverride(e,n,r){let o=[-1];this.#n=tr(this.#n,s=>{let a=s[e]?.parameters?.[n];if(a)if(r){delete a.locales?.[r];let l=a.localesConditions?.[r];l&&(l.forEach((c,u)=>{o.push(u)}),delete a.localesConditions?.[r]),a.locales&&Object.keys(a.locales).length===0&&delete a.locales,a.localesConditions&&Object.keys(a.localesConditions).length===0&&delete a.localesConditions,Object.keys(a.locales??{}).length===0&&Object.keys(a.localesConditions??{}).length===0&&delete s[e]?.parameters?.[n]}else{let l=a.conditions;l&&l.forEach((c,u)=>{o.push(u)}),delete s[e].parameters?.[n]}});let i=this.getPatternPropertyOverrideDefaultValue(e,n,r);!i.exists||i.value===null?this.updateNodeProperty({nodeId:e,property:n,value:void 0,source:"reset",locale:r,ignoreOverrides:!0,doNotSetDirty:!1,conditionIndex:-1}):o.forEach(s=>{let a=fse({locale:i.sourceLocale,property:i.value,conditionIndex:s,strict:!0});this.updateNodeProperty({nodeId:e,property:n,value:a===void 0?void 0:()=>a,source:"reset",locale:r,type:i.value?.type,ignoreOverrides:!0,doNotSetDirty:!1,conditionIndex:s,conditionDefinition:(r?i.value?.localesConditions?.[r]?.[s]?.when:i.value?.conditions?.[s]?.when)??null})}),this.#t.emit("propertyOverrideReset",{nodeId:e,property:n,usedPatternDefault:i!==void 0})}async duplicateNode(e,n){let r=this.getParentInfo(e);if(!r)throw new Error("Cannot duplicate root node or parentless block");let o=this.copyNodeToClipboard(e);return await this.pasteNodeFromClipboard({parentNodeId:r.parentId,parentSlot:r.parentName,resolvePattern:n,targetIndexInParent:r.targetIndexInParent+1,clipboard:o})}moveNode({movedNodeId:e,parentNodeId:n,parentSlot:r,targetIndexInSlot:o}){if(!this.#e[e])throw new Error(`Cannot move node ${e} - it does not exist`);let s=this.getParentInfo(e);if(!s)throw new Error("Cannot move root node");this.#r[s.parentId][s.parentName].splice(s.targetIndexInParent,1),this.#y(s.parentId,e),this.#f({nodeId:e,parentNodeId:n,parentSlot:r,targetIndexInSlot:o}),this.#m({nodeId:e,destinationParentId:n,destinationSlotName:r,sourceSlotName:s.parentName}),this.pristine=!1,this.#t.emit("childrenChanged",{parentId:n,slotOrBlockName:r,newChildIds:this.#r[n][r],type:"slot"}),this.#t.emit("childrenChanged",{parentId:s.parentId,slotOrBlockName:s.parentName,newChildIds:this.#r[s.parentId][s.parentName],type:"slot"})}deleteNode(e,n){let r=this.getParentInfo(e);if(!r&&!n)throw new Error("Cannot delete root node");r&&!n&&(this.#r[r.parentId][r.parentName].splice(r.targetIndexInParent,1),this.#r[r.parentId][r.parentName].length===0&&delete this.#r[r.parentId][r.parentName],this.selectedNodeId===e&&(this.selectedNodeId=r.parentId),this.#y(r.parentId,e),this.#t.emit("childrenChanged",{parentId:r.parentId,slotOrBlockName:r.parentName,newChildIds:this.#r[r.parentId][r.parentName]??[],type:"slot"})),delete this.#e[e],this.#t.emit("nodeDeleted",{deletedNodeId:e}),this.pristine=!1}#y(e,n){this.#n=tr(this.#n,r=>{let o=r[e]?.slots;o&&Object.keys(o).forEach(i=>{o[i]=o[i].filter(({_id:s})=>s!==n),o[i].length===0&&delete o[i]})})}#h(){if(Object.keys(this.#n).length>0){let e=ps(this.#n);return Object.entries(e).forEach(([r,o])=>{let i=!0;if(!this.#e[r]){delete e[r];return}if(o.parameters){let s=Object.entries(o.parameters);s.forEach(([a,l])=>{let c=mse(l);c?(o.parameters[a]=c,i=!1):delete o.parameters[a]}),s.length===0&&delete o.parameters}o.slots&&Object.entries(o.slots).forEach(([a,l])=>{if(l.length){let c=l.filter(u=>u._id).map(u=>this.exportSubtree(u._id));c?(o.slots[a]=c,i=!1):delete o.slots[a]}else delete o.slots[a]}),o.variant!==void 0&&(i=!1),o.dataResources&&Object.keys(o.dataResources).length>0&&(i=!1),i&&delete e[r]}),Object.keys(e).length===0&&(e=void 0),e}}exportSubtree(e,n){let{keepPatternData:r=!1}=n??{},o=this.#e[e];if(!o)throw new Error(`Node ${e} to export is not found`);let i=ps(o);if(e===this.rootNodeId){let l=this.#h();l?i.value._overrides=l:delete i.value._overrides;let c=i.value;c._name=this.#s._name,this.#s._slug&&(c._slug=this.#s._slug)}let s=[i],a=new Set;for(;s.length>0;){let l=s.pop();if(a.has(l.nodeId))throw new Error("Circular reference detected in the composition tree with node ID "+l.nodeId);if(a.add(l.nodeId),l.value._id=l.nodeId,!r&&(delete l.value._patternDataResources,delete l.value._patternOverrides,l.value._pattern&&l.value._dataResources)){let d=!1;Object.keys(l.value._dataResources).forEach(f=>{i.value._overrides?.[l.nodeId]?.dataResources?.[f]?delete l.value._dataResources[f]:d=!0}),d||delete l.value._dataResources}let c=this.#o[l.nodeId];if(c&&(r||!l.partOfPattern)){let d={},f=!1;Object.entries(c).forEach(([p,m])=>{if(m?.type===Gs&&Array.isArray(m.value)){let g=m.value,h=[];g.forEach(v=>{let y=this.exportSubtree(v,n);h.push(eI(y,v))}),d[p]={value:h,type:Gs},f=!0}else{let g=mse(m);g&&(d[p]=g,f=!0)}}),f&&(l.value.parameters=d)}let u=this.#r[l.nodeId];!u||l.partOfPattern&&!r||Object.entries(u).forEach(([d,f])=>{f.forEach((p,m)=>{let g=this.#e[p];if(!g)throw new Error("Insanity detected.");let h=ps(g),v=l.value;v.slots=v.slots||{},(0,Lp.set)(l,["value","slots",d,m.toString(10)],h.value),s.push(h)})})}return this.#D(i.value),i.value}#S({parentNodeId:e,parentSlot:n,targetIndexInSlot:r,node:o}){if(!this.#e[e])throw new Error("Parent ID to insert under did not exist!");if(this.#e[o.nodeId])throw new Error(`Node with ID '${o.nodeId}' already exists. Nodes must have unique IDs. Did you mean to move or duplicate this node instead?`);this.#e[o.nodeId]=o,this.#f({nodeId:o.nodeId,parentNodeId:e,parentSlot:n,targetIndexInSlot:r})}#f({nodeId:e,parentNodeId:n,parentSlot:r,targetIndexInSlot:o}){let i=this.#e[n],s=this.#r[n]??={},a=s[r]??=[];typeof o<"u"?a.splice(o,0,e):a.push(e),i?.value.type===o5&&(this.#n=tr(this.#n,l=>{l[n]=l[n]??{},l[n].slots={[XLe]:a.map(c=>({_id:c,type:this.#e[c].value.type}))}})),this.#e[e]=tr(this.#e[e],l=>{l.parentId=n})}#w({nodeId:e,property:n,index:r,entry:o}){let i=this.getNodeById(e);if(!i)throw new Error("Node doesn't exist");let a={nodeId:o._id??wd(),value:{type:o.type,_dataResources:o._dataResources},isBlock:!0,parentId:e,propertyValueLocalizability:{}},l=this.getNodeProperty(i.nodeId,n);if(l&&l.type!==Gs)throw new Error("Parameter already exists and isn't a block parameter");let c=this.#e[a.nodeId];this.#e[a.nodeId]=a;let u=ps(this.getNodeProperty(i.nodeId,n)?.value?.filter(d=>this.getNodeById(d))??[]);if(typeof r<"u"){if(r<0)throw new Error("parameter index cannot be less than 0");let d=-1;if(u.forEach((f,p)=>{f===a.nodeId&&(d=p)}),r>u.length+(d===-1?1:0))throw new Error(`Parameter index ${r} outside current index bounds.`);d>-1&&d!==r&&(u=u.filter(f=>f!==a.nodeId),u.splice(r,0,a.nodeId))}else u.push(a.nodeId);return Object.entries(o?.fields??{}).forEach(([d,f])=>{if(f.type===Gs&&Array.isArray(f.value)){let p=f.value,m=[];p.forEach(g=>{let h=g._id??wd();this.#l({nodeId:h,componentTree:tI(g)}),this.#e[h].isBlock=!0,this.#e[h].parentId=a.nodeId,m.push(h)}),this.updateNodeProperty({nodeId:a.nodeId,property:d,type:f.type,value:()=>m,source:"other",locale:void 0,conditionIndex:-1})}else this.updateNodeProperty({nodeId:a.nodeId,property:d,type:f.type,value:()=>f.value,source:"other",locale:void 0,conditionIndex:-1})}),this.updateNodeProperty({nodeId:i.nodeId,property:n,type:Gs,value:()=>u,source:"other",locale:void 0,conditionIndex:-1}),this.#t.emit("nodeChanged",{changedNode:i,oldValue:void 0,type:c?"update":"new"}),this.#t.emit("nodeParameterChanged",{nodeId:i.nodeId,parameter:n,previousValue:l,source:"other",type:c?"update":"new",locale:void 0,conditionIndex:-1,conditionDefinition:void 0,value:{type:Gs,value:u}}),{blockIds:u}}#l({componentTree:e,nodeId:n,partOfPattern:r,partOfNestedPattern:o,resetUids:i,isBlock:s,allowReplacement:a}){let{slots:l,parameters:c,_id:u,_overrides:d,...f}=e,p=r??f._pattern,m=f._pattern&&f._pattern!==p?f._pattern:o,g=n??(i?void 0:u)??wd();if(this.#e[g]&&!a)throw new Error(`Node with ID '${g}' already exists. Nodes must have unique IDs.`);let h={nodeId:g,value:f,partOfPattern:p,partOfNestedPattern:m,isBlock:s,propertyValueLocalizability:Object.entries(c??{}).reduce((v,[y,b])=>(v[y]=Dx({definition:void 0,currentValue:b,lastUserChoice:void 0}),v),{})};return p&&(h.partOfPattern=p),this.#e[h.nodeId]=h,c&&Object.entries(c).forEach(([v,y])=>{let{connectedData:b,...S}=y,C=b?dse(use(b)):y.value;if(y?.type===Gs&&Array.isArray(C)){let w=C,E=[];w?.forEach(_=>{let $={..._,_id:i?wd():_._id??wd()};if(this.#e[$._id])throw new Error(`Block node with ID '${$._id}' already exists. Block nodes must have unique IDs.`);return E.push($._id),this.#e[$._id]={nodeId:$._id,value:{type:Gs},propertyValueLocalizability:{}},this.#l({componentTree:tI($),nodeId:$._id,allowReplacement:!0}),this.#e[$._id].isBlock=!0,this.#e[$._id].parentId=h.nodeId,this.#e[$._id]}),C=E}this.#o[h.nodeId]=this.#o[h.nodeId]??{},(0,Lp.set)(this.#o,[h.nodeId,v],{...S,value:C})}),l&&Object.entries(l).forEach(([v,y])=>{let b=y.map(S=>{if(this.#e[S._id??""]?.isBlock)return;let C=this.#l({componentTree:S,partOfPattern:f.type===o5?void 0:p,partOfNestedPattern:f.type===o5?void 0:m,resetUids:i});return this.#e[C].parentId=h.nodeId,C});this.#r[h.nodeId]=this.#r[h.nodeId]??{},this.#r[h.nodeId][v]=b.filter(S=>S)}),h.nodeId}#b(e,n,r){let o=this.#x(e,n);return this.#l({componentTree:o,nodeId:n,allowReplacement:r})}#x(e,n){let r=ps(e);return this.#v({composition:r}),QE(r,n),r._pattern=e._id,delete r._id,delete r._name,delete r._slug,delete r._overrides,delete r._locales,delete r._author,delete r._authorSubject,delete r._creator,delete r._creatorSubject,r._dataResources&&(r._patternDataResources=ps(r._dataResources),delete r._dataResources),r}getParentInfo(e){let{parentId:n,isBlock:r}=this.#e[e]??{};if(!n)return;let o=this.#e[n];if(o)if(r)for(let[i,s]of Object.entries(this.#o[n]??{})){if(s?.type!==Gs)continue;let a=Array.isArray(s.value)?s.value:[],l=a.indexOf(e);if(l>=0)return{value:o.value,parentId:n,parentName:i,targetIndexInParent:l,parentChildIds:a,parentType:"block"}}else{let i=this.#r[n];if(!i&&!r)throw new Error("Sanity failed; parent had no children!");for(let[s,a]of Object.entries(i??{})){let l=a.indexOf(e);if(l>=0)return{value:o.value,parentId:n,parentName:s,targetIndexInParent:l,parentChildIds:a,parentType:"slot"}}return}}static#E(e){return tr(e,r=>{delete r.slots,delete r.parameters})}#_(e){let n=e;for(;n;){let r=this.getNodeById(n);if(!r)break;if(r.value._pattern)return!1;if(r.value.type===o5||!r.partOfPattern)return!0;n=r.parentId}return!0}#T(e,n,r){let i={...this.#h(),...r},s;if(this.#n=tr(this.#n,l=>{this.#i=tr(this.#i,c=>{s=n5(e,i,(u,d,f)=>{l[u]=d,c[u]=this.#i[f]})})}),!s)throw new Error("Failed to duplicate component");s=tr(s,l=>{l._overrides=ps(this.#n),this.#v({composition:l,preserveChildrenSlotSections:!0})});let a=this.#l({componentTree:s,isBlock:n.parentType==="block"});if(n.parentType==="block"){let l=this.getNodeProperty(n.parentId,n.parentName)?.value??[],c=[...l.slice(0,n.targetIndexInParent),a,...l.slice(n.targetIndexInParent)];this.updateNodeProperty({nodeId:n.parentId,property:n.parentName,type:Gs,value:()=>c,locale:void 0,conditionIndex:-1,source:"other"}),this.#e[a].parentId=n.parentId,this.#t.emit("nodeChanged",{changedNode:this.getNodeById(a),type:"new",oldValue:void 0}),this.#t.emit("childrenChanged",{parentId:n.parentId,slotOrBlockName:n.parentName,newChildIds:c,type:"block"})}else{this.#f({nodeId:a,parentNodeId:n.parentId,parentSlot:n.parentName,targetIndexInSlot:n.targetIndexInParent}),this.#m({nodeId:a,destinationParentId:n.parentId,destinationSlotName:n.parentName}),this.#t.emit("childrenChanged",{parentId:n.parentId,slotOrBlockName:n.parentName,newChildIds:this.#r[n.parentId][n.parentName],type:"slot"});let l=c=>{this.#t.emit("nodeChanged",{changedNode:c,type:"new",oldValue:void 0})};this.visitNodeAndDescendants(a,l)}return this.pristine=!1,a}#v({composition:e,ignoreRootOverrides:n,preserveChildrenSlotSections:r}){this.#i=tr(this.#i,i=>{let s=XO({beforeApplyParameterOverride(c,u,d){i[c._id]??={parameters:{},dataResources:{}},i[c._id].parameters[u]=ps(d)},beforeApplyDataResourceOverride(c,u,d){c._dataResources?.[u]?.ignorePatternParameterDefault||(i[c._id]??={parameters:{},dataResources:{}},i[c._id].dataResources[u]=ps(d))}}),a=XO({beforeApplyParameterOverride(c,u,d,f){i[c._id]?.parameters[u]||(i[c._id]??={parameters:{},dataResources:{}},i[c._id].parameters[u]=ps(f??null))},beforeApplyDataResourceOverride(c,u,d,f){c._dataResources?.[u]?.ignorePatternParameterDefault||i[c._id]?.dataResources[u]||(i[c._id]??={parameters:{},dataResources:{}},i[c._id].dataResources[u]=ps(f))}});if(n){let{_overrides:c,...u}=e;Cc(u,({node:d})=>{s.visitNode(d)})}let l=n?a:s;Cc(e,({node:c})=>{l.visitNode(c)})});let o=Vie({preserveOwnSlotSections:!0,preserveChildrenSlotSections:r});Cc(e,i=>{o(i)})}visitNodeAndDescendants(e,n){let r=this.getNodeById(e);if(!r)throw new Error("Insanity detected.");n(r),this.visitDescendants(e,n)}visitDescendants(e,n){let r=this.#p(e,new Set);for(let o of r)n(...o)}async visitDescendantsAsync(e,n){let r=this.#p(e,new Set);for(let o of r)await n(...o)}*#p(e,n){let r=this.#e[e],o=this.#r[e]??{},i=Object.entries(this.#o[e]??{}).filter(([,s])=>s?.type===Gs)??[];if(!r)throw new Error("Insanity detected.");n.add(e);for(let[s,a]of i){let l=a.value??[];for(let c=0;c<l.length;c++){let u=l[c],d=this.#e[u];if(d){if(n.has(u)){console.error(`Detected parent/child cycle in composition, ID ${u} exists more than once. The traversal of descendants will be aborted for the cycle subtree.`);continue}yield[d,r,s,c];for(let f of this.#p(u,n))yield f}}}for(let[s,a]of Object.entries(o))for(let l=0;l<a.length;l++){let c=a[l],u=this.#e[c];if(u){if(n.has(c)){console.error(`Detected parent/child cycle in composition, ID ${c} exists more than once. The traversal of descendants will be aborted for the cycle subtree.`);continue}yield[u,r,s,l];for(let d of this.#p(c,n))yield d}}}#m({nodeId:e,destinationParentId:n,destinationSlotName:r,sourceSlotName:o}){let i=r,s=o===ase,a=i===ase,l=o===lse,c=i===lse,u=i===iI,d=this.getNodeProperty(e,sse);a&&d&&this.updateNodeProperty({nodeId:e,property:sse,value:void 0,source:"other",locale:void 0,conditionIndex:-1});let f=this.getNodeProperty(e,Mb);!a&&f&&this.updateNodeProperty({nodeId:e,property:Mb,value:void 0,source:"other",locale:void 0,conditionIndex:-1}),a&&!s&&this.#C({nodeId:e,siblingIds:this.getNodeChildren(n)?.[r]??[],selectExistingName:g=>this.getNodeProperty(g,Mb)?.value?.name,setName:g=>this.updateNodeProperty({nodeId:e,property:Mb,value:h=>h&&typeof h=="object"&&h!==null?{...h,name:g}:{name:g,crit:[]},source:"other",locale:void 0,conditionIndex:-1,type:Mb})}),c&&!l&&this.#C({nodeId:e,siblingIds:this.getNodeChildren(n)?.[r]??[],selectExistingName:g=>this.getNodeProperty(g,cse)?.value?.id,setName:g=>this.updateNodeProperty({nodeId:e,property:cse,value:h=>h&&typeof h=="object"&&h!==null?{...h,id:g}:{id:g},source:"other",locale:void 0,conditionIndex:-1,type:"testVariant"})});let p=this.getNodeProperty(e,Ab);!u&&p&&this.updateNodeProperty({nodeId:e,property:Ab,value:void 0,source:"other",locale:void 0,conditionIndex:-1});let m=this.getNodeProperty(e,Sd);(a||u||c)&&m&&this.updateNodeProperty({nodeId:e,property:Sd,value:void 0,source:"other",locale:void 0,conditionIndex:-1})}#C({nodeId:e,siblingIds:n,selectExistingName:r,setName:o}){let i=r(e),s=d=>n.some(f=>f===e?!1:r(f)===d),a=i&&s(i);if(i&&!a)return;let l=this.getNodeById(e)?.value.type;if(!l)throw new Error("Insanity detected.");let c=0,u=oI(e,l,c);do u=oI(e,l,c),c++;while(s(u));o(u)}prepareContentReferenceWrite({nodeId:e,propertyId:n,destinationLocale:r,conditionIndex:o,sourceValue:i}){let s=this.#$({value:i,dataResources:this.#e[e]?.value._dataResources});if(!s)return i;let{dataResource:a,isSingleEntryReference:l}=s,c=zp(e,n,r==="${locale}"?void 0:r,o);this.updateNode({nodeId:e,updateDataResources:[{name:c,type:"set",value:{...a,variables:{...a?.variables,locale:r}}}]});let u=`/${c}/entries${l?"/0":""}`;return dse(use({syntax:"jptr",pointer:u}))}#$({value:e,dataResources:n}){if(typeof e!="string")return;let r;pse(e,(a,l)=>{l==="variable"&&(r=a)});let o=r?nI(r):void 0;if(!o)return;let i=o.dataResource,s=n?.[i];if(s)return{dataResource:s,dataResourceName:i,isSingleEntryReference:o.dataExpression?.endsWith("/0")}}#N(e){if(typeof e!="string")return;let n;return pse(e,(o,i)=>{i==="variable"&&(n=o)}),(n?nI(n):void 0)?.dataResource}#D(e){let n=new Set,r=[],o=({node:i})=>{let s=QLe(i),a=i._dataResources;if(a)for(let[l,c]of Object.entries(a))c.type===ll&&r.push({dataResources:a,dataResourceKey:l});if(s)for(let l of Object.values(s))l.type==="contentReference"&&eAe(l,({value:c})=>{let u=this.#N(c);u&&n.add(u)})};if(Cc(e,o),"_overrides"in e&&e._overrides)for(let[,i]of Object.entries(e._overrides))Cc({type:e.type,...i,_dataResources:i.dataResources},o);for(let{dataResources:i,dataResourceKey:s}of r)n.has(s)||delete i[s]}};function mse(t){return t?.value===void 0&&!t?.conditions&&!t?.locales&&!t?.localesConditions?null:t}function Ed(t,e){return rAe(t,e,()=>({nodeId:e,actions:[]}))}function rAe(t,e,n){return t.has(e)||t.set(e,n()),t.get(e)}import{CANVAS_DRAFT_STATE as a5,CanvasClient as aAe}from"@uniformdev/canvas";import{ProjectMapClient as lAe}from"@uniformdev/project-map";import{produce as cAe}from"immer";function hse(t){return t.reduce((e,n)=>(e[n._id]={id:n._id,type:n.type,name:n._name},e),{})}import{CANVAS_DRAFT_STATE as vse,CanvasClient as sI,ContentClient as yse,ProjectClient as bse}from"@uniformdev/canvas";function xse(t){let e,n,r;return{fetchProjectGuidance:async()=>(e!==void 0||(e=(await new bse(t).get({projectId:t.projectId}))?.guidance),e),fetchDefinitions:async()=>{if(n!==void 0)return n;let i=await new sI(t).getComponentDefinitions({limit:1e3,includeSystem:!0});return n=Object.fromEntries(i.componentDefinitions.map(s=>[s.id,s])),n},fetchPatterns:async()=>{if(r!==void 0)return r;let i=await new sI(t).getCompositionList({limit:1e3,pattern:!0,patternType:"component",resolveData:!1,skipPatternResolution:!0,skipOverridesResolution:!0,state:vse});return r=hse(i.compositions.map(s=>s.composition)),r},resolvePatternData:async o=>(await new sI(t).getCompositionById({compositionId:o,state:vse,skipPatternResolution:!1,skipOverridesResolution:!0,withComponentIDs:!0,skipDataResolution:!0,withWorkflowDefinition:!0,releaseId:void 0}))?.composition,getToolClient:async()=>t.toolInvoker,getDimensionGuidance:async()=>{}}}function Cse(t){let e,n;return{fetchProjectGuidance:async()=>(e!==void 0||(e=(await new bse(t).get({projectId:t.projectId}))?.guidance),e),fetchDefinitions:async()=>{if(n!==void 0)return n;let o=await new yse(t).getContentTypes({limit:1e3});return n=Object.fromEntries(o.contentTypes.map(i=>[i.id,Jie(i)])),n},fetchPatterns:async()=>({}),resolvePatternData:async r=>{let i=(await new yse(t).getEntries({entryIDs:[r],skipPatternResolution:!1,skipOverridesResolution:!0,withComponentIDs:!0,skipDataResolution:!0,withWorkflowDefinition:!0,releaseId:void 0}))?.entries[0];return Lb(i).composition},getToolClient:async()=>t.toolInvoker,getDimensionGuidance:async()=>{}}}import{parseHTML as oAe}from"linkedom/worker";function iAe(t){let e=Object.getPrototypeOf(t.body);for(;e&&!Object.getOwnPropertyDescriptor(e,"style");)e=Object.getPrototypeOf(e);let n=e?Object.getOwnPropertyDescriptor(e,"style"):void 0;if(!n?.get||e.__stylePatched)return;let r=n.get;Object.defineProperty(e,"style",{get(){let o=r.call(this);return new Proxy(o,{get(i,s){if(typeof s=="string"){let a=i[s];return typeof a=="function"?a.bind(i):a===void 0?"":a}return i[s]},set(i,s,a){return i[s]=a,!0}})},configurable:!0}),e.__stylePatched=!0}function i5(t){let e=`<!DOCTYPE html><html><body>${t}</body></html>`,{document:n}=oAe(e);return iAe(n),n}import{LocaleClient as sAe}from"@uniformdev/canvas";async function s5(t,e){if(!t||t.length===0)return;let o=(await new sAe(e).get()).results.map(s=>s.locale),i=t.filter(s=>!o.includes(s));if(i.length>0)throw new Error(`The following locales are not registered in your project: ${i.join(", ")}`)}async function l5({action:t,id:e,instructions:n,isPattern:r,patternId:o,projectMapNode:i,getEditUrl:s,env:a}){let l=new aAe(a),c,u,d=t==="update"?e:void 0,f={success:!0,actionsTaken:[]};if(t==="duplicate"){if(u=await l.getCompositionById({compositionId:e,state:a5,skipDataResolution:!0,skipPatternResolution:!1,withComponentIDs:!0,skipOverridesResolution:!0}),!u)throw new Error("Composition not found");let p=crypto.randomUUID(),m=Hie(u.composition,p),g=cAe(m,h=>{h._name=`${h._name} (copy)`,h._slug&&(h._slug=`${h._slug}-copy${h._slug?.endsWith("/")?"/":""}`)});c=new ol(g),e=p}else if(t==="create"){if(!n)throw new Error("Instructions are required for create");if(!n.name)throw new Error("Name is required for create");if(!n.type)throw new Error("Type is required for create");if(!o)c=new ol({_id:e,_name:n.name,type:n.type,_overridability:{hideLockedParameters:!0}});else{let p={composition:{_id:e,_name:n.name,type:n.type,_pattern:o},projectId:a.projectId,state:a5,pattern:!1};await l.updateComposition(p),d=e}}if(d){if(u=await l.getCompositionById({compositionId:e,state:a5,skipDataResolution:!0,skipPatternResolution:!1,withComponentIDs:!0,skipOverridesResolution:!0}),!u)throw new Error("Composition not found");c=new ol(u.composition)}if(t==="delete"&&await l.removeComposition({compositionId:e}),c){await s5(n?.localeUpdates?.enableLocales,a),f=await JE({twee:c,descriptionUpdate:void 0,slugUpdate:void 0,nameUpdate:n?.name,propertyUpdates:n?.parameterUpdates??[],dataResourceUpdates:n?.dataResourceUpdates??[],localeUpdates:n?.localeUpdates,slotUpdates:n??{},currentEditorLocale:void 0,referenceData:xse(a),isEditingPattern:r,domParser:i5});let p=c.exportTree(),m=c.exportMetadata(),g={composition:p,projectId:a.projectId,state:a5,pattern:r,releaseId:u?.releaseId,editionId:u?.editionId,...m};await l.updateComposition(g)}if(t==="create"&&!r&&(i?.nodePathSegment||i?.localePathSegments)&&n?.name){let p=new lAe({apiKey:a.apiKey,apiHost:a.apiHost,projectId:a.projectId}),{path:m,nodeId:g}=await Die({projectMapClient:p,compositionId:e,compositionName:n.name,nodePathSegment:i.nodePathSegment||"",parentNodeId:i.parentNodeId,localePathSegments:i.localePathSegments,allowedQueryStrings:i.allowedQueryStrings});return f.actionsTaken.push({success:!0,summary:`Created project map node at path: ${m}`}),{content:[{type:"text",text:JSON.stringify({...f,editUrl:s(e),projectMapNode:{path:m,nodeId:g}},null,2)}]}}return{content:[{type:"text",text:JSON.stringify({...f,editUrl:s(e)},null,2)}]}}function c5(t,e){return`${e.baseWebUrl}/dashboards/canvas/edit/${t}`}async function u5(t,e,n){return await n.toolInvoker.invoke("createFilterExpression",{...t,entityType:e})}var uAe={action:ro.enum(["create","update","delete","duplicate"]).describe("The action to perform"),id:ro.string().uuid().describe("UUID of the composition instance to create, update, delete, or duplicate"),patternId:ro.string().uuid().describe("Composition pattern ID to create the composition from. Omit when not creating, or when creating a composition without a composition pattern.").optional(),instructions:bk.describe("Modification instructions for the composition. Omit for delete and duplicate.").optional(),projectMapNode:ro.object({parentNodeId:ro.string().uuid().describe("UUID of the parent node from searchProjectMapNodes. If omitted, the node will be a child of the root node.").optional(),nodePathSegment:ro.string().describe('URL path segment for the node (e.g., "about-us", "products", ":productId" for dynamic matching). Use a slugified version of the name unless otherwise requested by the user. Omit if not creating a project map node.').optional(),localePathSegments:ro.array(ro.object({locale:ro.string().describe('Locale code (e.g., "en-US", "fr-FR")'),pathSegment:ro.string().describe("URL path segment for this locale")})).describe("Optional array of locale-specific path segments. Unspecified locales use the nodePathSegment. Do not use these for dynamic path segments.").optional(),allowedQueryStrings:ro.array(ro.object({name:ro.string().describe("Query parameter name"),defaultValue:ro.string().describe("Default value if not provided in the URL").optional()})).describe("Optional array of allowed query string parameters for this node").optional()}).describe("Attaches the new composition to a new node in the project map hierarchy. Omit to avoid creating a project map node, or if action is not create.").optional()};function Sse(t,e){t.tool("compositionAction","Creates, updates, or deletes a Uniform Composition",uAe,async n=>await l5({...n,isPattern:!1,getEditUrl:r=>c5(r,e),patternId:n.patternId,projectMapNode:n.projectMapNode,env:e}))}import*as On from"zod/v3";var dAe=On.object({field:On.string(),operator:On.string(),value:On.string().or(On.array(On.string()))}),fAe=On.object({filter:On.array(dAe),error:On.string().describe("An error message if the filter expression could not be created, otherwise an empty string"),sort:On.array(On.enum(["created_at_ASC","created_at_DESC","updated_at_ASC","updated_at_DESC","author_ASC","author_DESC","creator_ASC","creator_DESC","name_ASC","name_DESC","slug_ASC","slug_DESC"])),limit:On.number().min(1).max(100),offset:On.number().min(0),keyword:On.string(),locale:On.string().optional()}),Sc=On.object({searchExpressionPrompt:On.string().describe(`Describe what you are looking for, for example "created by me in the last week" or "type is article and headline contains breaking news" or "keyword search for breaking news".
5837
+ `).trimStart();n.on("*",(o,i)=>{console.debug(`\u26A1\uFE0F ${t}:${String(o)}`,{args:i,stack:r,subs:n.all.get(String(o))?.length??0})})}return n}var ps=(0,gse.default)(),tAe=!0,nAe="Twee",ol=class t{#e={};rootNodeId;#r={};#o={};#n;#i={};#t=ise(nAe,tAe);#c;#u;#g;#d;#a;#s;constructor(e,n){let{metadata:r,startDirty:o}=n||{};this.#a=r??{},this.#s={_name:e?._name??"",_slug:e?._slug??null},this.#d=!o;let i=tr(e,s=>{this.#v({composition:s,ignoreRootOverrides:!0,preserveChildrenSlotSections:!0}),delete s._author,delete s._authorSubject,delete s._creator,delete s._creatorSubject});this.rootNodeId=i._id??wd(),this.#c=this.rootNodeId,this.#l({componentTree:i,nodeId:this.rootNodeId}),this.#n=i._overrides??{}}events=this.#t;exportTree(e){return this.exportSubtree(this.rootNodeId,e)}exportMetadata(){return this.#a}exportRootNodeMetadata(){return this.#s}get pristine(){return this.#d}set pristine(e){this.#d!==e&&(this.#d=e,this.#t.emit("pristineChanged",{pristine:e}))}get selectedBlockIdStack(){return this.#u}set selectedBlockIdStack(e){this.#u=e,this.#t.emit("selectedBlockChanged",{selectedBlockIds:this.#u})}get selectedNodeId(){return this.#c}set selectedNodeId(e){this.#c!==e&&(this.#c=e,this.selectedParameterId=void 0,this.#t.emit("selectedNodeChanged",{selectedNodeId:e}))}get selectedParameterId(){return this.#g}set selectedParameterId(e){this.#g!==e&&(this.#g=e,this.#t.emit("selectedParameterChanged",{selectedParameterId:e}))}pushSelectedBlockId(e){this.selectedBlockIdStack=this.selectedBlockIdStack??[],this.selectedBlockIdStack?.push(e),this.#t.emit("selectedBlockChanged",{selectedBlockIds:this.selectedBlockIdStack})}popSelectedBlockId(){this.#u?.pop(),this.#t.emit("selectedBlockChanged",{selectedBlockIds:this.selectedBlockIdStack})}getNodeById(e){return this.#e[e]}getNodesIndex(){return this.#e}getBlockNodeValueById(e){return eI(this.exportSubtree(e),e)}getNodeChildren(e){let n=this.#r[e];if(n)return n}getNodeProperty(e,n){return rI(this.#o,[e,n])}getNodeProperties(e){return this.#o[e]??{}}insertNode({node:e,parentNodeId:n,parentSlot:r,targetIndexInSlot:o,overrideNodeId:i}){let s=i??wd();if(!this.#_(n))throw new Error("Cannot insert component into a read-only pattern slot unless it is within a slot section");let l={nodeId:s,parentId:n,value:t.#E(e),isExpandedInUI:!0,propertyValueLocalizability:{}};return this.#S({node:l,parentNodeId:n,parentSlot:r,targetIndexInSlot:o}),this.#m({nodeId:s,destinationParentId:n,destinationSlotName:r}),this.pristine=!1,this.#t.emit("nodeChanged",{changedNode:l,oldValue:void 0,type:"new"}),this.#t.emit("childrenChanged",{parentId:n,slotOrBlockName:r,newChildIds:this.#r[n][r],type:"slot"}),s}upsertBlockNode({nodeId:e,property:n,index:r,entry:o}){let i=this.#w({nodeId:e,property:n,index:r,entry:o});return this.pristine=!1,this.#t.emit("childrenChanged",{parentId:e,slotOrBlockName:n,newChildIds:this.#o[e]?.[n]?.value,type:"block"}),i}updateRootMetadata(e){let n={...this.#a};this.#a={...this.#a,...e},this.pristine=!1,this.#t.emit("metadataChanged",{metadata:this.#a,oldValue:n})}updateRootNode({update:e,doNotSetDirty:n}){let r={...this.#s};this.#s={...this.#s,...e},n||(this.pristine=!1),this.#t.emit("rootNodeMetadataChanged",{metadata:this.#s,oldValue:r})}insertPattern({parentNodeId:e,parentSlot:n,pattern:r,targetIndexInSlot:o,patternInstanceId:i}){let s=i??wd();if(this.#e[s])throw new Error(`Node with ID '${s}' already exists. Pattern nodes must have unique IDs. Did you mean to move or duplicate this pattern instead?`);let a=this.#b(r,s,!1);return this.#f({nodeId:a,parentNodeId:e,parentSlot:n,targetIndexInSlot:o}),this.#m({nodeId:a,destinationParentId:e,destinationSlotName:n}),this.pristine=!1,this.visitNodeAndDescendants(a,l=>{this.#t.emit("nodeChanged",{changedNode:l,oldValue:void 0,type:"new"})}),this.#t.emit("childrenChanged",{parentId:e,slotOrBlockName:n,newChildIds:this.#r[e][n],type:"slot"}),a}unlinkPattern(e){let n=this.#e[e];if(!n)throw new Error(`Node ${e} does not exist`);if(!n.value._pattern)throw new Error(`Node ${e} is not a pattern`);let r=n.value._patternDataResources||n.value._dataResources,o=qie(n.value),i=a=>{a.partOfNestedPattern||(this.updateNode({nodeId:a.nodeId,updateComponent:l=>{delete l._pattern,delete l._patternError,delete l._overrides},updateMetadata:l=>{delete l.partOfPattern,delete l.partOfNestedPattern},doNotSetDirty:!0,ignoreOverrides:!0}),this.#n[a.nodeId]&&(this.#n=tr(this.#n,l=>{delete l[a.nodeId]})))};this.visitNodeAndDescendants(e,i);let s=a=>{a.partOfNestedPattern&&this.updateNode({nodeId:a.nodeId,updateMetadata:l=>{l.partOfPattern=l.partOfNestedPattern,delete l.partOfNestedPattern},doNotSetDirty:!0,ignoreOverrides:!0})};this.visitNodeAndDescendants(e,s),r&&(this.updateNode({nodeId:this.rootNodeId,updateDataResources:a=>Object.entries(o??{}).filter(([l])=>!(l in(a??{}))).map(([l,c])=>{let{source:u,...d}=c;return{type:"set",name:l,value:d}})}),this.updateNode({nodeId:n.nodeId,updateComponent:a=>{delete a._patternDataResources},updateDataResources:"removeAll",doNotSetDirty:!0,ignoreOverrides:!0})),this.pristine=!1}convertToPattern({existingNodeId:e,pattern:n}){let r=this.#e[e],o=r?.parentId;if(!r)throw new Error(`Node ${e} does not exist`);let i=this.#b(n,e,!0);this.#e[i]=tr(this.#e[i],a=>{a.parentId=o}),this.pristine=!1;let s=this.#e[i];this.#t.emit("nodeChanged",{changedNode:s,oldValue:r,type:"new"}),Object.entries(this.#r[i]??{}).forEach(([a,l])=>{this.#t.emit("childrenChanged",{newChildIds:l,parentId:i,slotOrBlockName:a,type:"slot"})})}copyNodeToClipboard(e){let n=this.exportSubtree(e,{keepPatternData:!1}),r=this.exportSubtree(e,{keepPatternData:!0}),o=[];Cc(r,({node:a})=>{a._id&&o.push(a._id)}),Cc(n,({node:a})=>{a._id&&(a._overrides&&delete a._overrides,"_name"in a&&delete a._name,"_slug"in a&&delete a._slug)});let i=this.#h(),s=Object.entries(i??{}).reduce((a,[l,c])=>(o.some(u=>l.includes(u))&&(a[l]=c),a),{});return{format:"uniform/copied-component-subtree-1.0",componentData:n,overrides:Object.keys(s).length?s:void 0,pasteAs:this.getNodeById(e)?.isBlock?"block":void 0}}async pasteNodeFromClipboard({parentNodeId:e,parentSlot:n,targetIndexInParent:r,clipboard:o,resolvePattern:i}){let s=ps(o),a=async c=>{c._pattern&&l.push((async()=>{let u=await i(c._pattern);if(!u){console.debug(`Pasted pattern ${c._pattern} not found, skipping`);return}let d=this.#x(u,c._id);Object.assign(c,d)})())},l=[];return Cc(s.componentData,({node:c})=>{a(c)}),s.overrides&&Object.values(s.overrides).forEach(c=>{c.slots&&Object.values(c.slots).forEach(u=>{u.forEach(d=>{Cc(d,({node:f})=>{a(f)})})})}),await Promise.all(l),this.#T(s.componentData,{parentId:e,parentName:n,parentType:o.pasteAs==="block"?"block":"slot",targetIndexInParent:r},s.overrides)}enableLocale(e){this.updateNode({nodeId:this.rootNodeId,updateComponent:n=>{let r=n;r._locales??=[];let o=[...new Set([...r._locales,...Array.isArray(e)?e:[e]])];r._locales=o}})}disableLocale(e){this.updateNode({nodeId:this.rootNodeId,updateComponent:o=>{let i=o;i._locales=i._locales?.filter(s=>s!==e)}});let n=[],r=o=>{this.getNodeProperty(o.nodeId,Ab)?.value===e&&!o.partOfPattern&&n.push(o.nodeId);let s=this.getNodeProperties(o.nodeId);Object.entries(s).forEach(([l,c])=>{let u=c;l!==Sd&&(o.partOfPattern?this.isPatternPropertyOverridden(o.nodeId,l,e)&&this.resetPatternPropertyOverride(o.nodeId,l,e):(u?.localesConditions?.[e]?.forEach((d,f)=>{this.updateNodeProperty({nodeId:o.nodeId,property:l,value:void 0,source:"other",locale:e,conditionIndex:f,conditionDefinition:null})}),u?.locales?.[e]!==void 0&&this.updateNodeProperty({nodeId:o.nodeId,property:l,value:void 0,source:"other",locale:e,conditionIndex:-1})))});let a=this.getNodeProperty(o.nodeId,Sd);if(a?.value){let l=rse(a.value,e);if(l===null)n.push(o.nodeId);else if(l===void 0||!$r(a.value,l)){let c=!o.partOfPattern,u=Dp(o.value._overridability,Sd)==="yes";(c||u)&&this.updateNodeProperty({nodeId:o.nodeId,property:Sd,value:l?()=>l:void 0,source:"other",locale:void 0,conditionIndex:-1})}}};this.visitNodeAndDescendants(this.rootNodeId,r),n.forEach(o=>{this.deleteNode(o)})}copyValuesToLocalePlan({sourceLocale:e,destinationLocale:n,doNotCopyDescendants:r=!1,startingNodeId:o=this.rootNodeId,specificPropertyId:i}){let s=new Map,a=c=>{if(c.value.type===JLe&&!c.partOfPattern){let d=this.getNodeChildren(c.nodeId)?.[iI]??[],f=d.map(g=>this.getNodeProperty(g,Ab)),p=f.findIndex(g=>g?.value===n);if(p>=0){let g=d[p];Ed(s,g).actions.push({type:"deleteLocalizedNode"})}let m=f.findIndex(g=>g?.value===e);if(m>=0){let g=d[m];Ed(s,g).actions.push({type:"duplicateLocalizedNode",targetIndexInSlot:p})}}if(s.get(c.nodeId)?.actions.some(d=>d.type==="deleteLocalizedNode"))return;let u=i?{[i]:this.getNodeProperty(c.nodeId,i)}:this.getNodeProperties(c.nodeId);Object.entries(u).forEach(([d,f])=>{if(f===void 0)return;let p=!c.partOfPattern,m=Dp(c.value._overridability,d)==="yes";if(!(p||m))return;if(d===Sd){let w=ese(f.value,e,n);w===null?Ed(s,c.nodeId).actions.push({type:"deleteLocalizedNode"}):w&&Ed(s,c.nodeId).actions.push({type:"updateVisibilityCriteria",targetValue:w})}let h=f.locales?.[e],v=f.locales?.[n];(!h||!v||!$r(h,v))&&(h!==void 0?Ed(s,c.nodeId).actions.push({type:"copyPropertyValue",propertyId:d,sourceValue:h,targetValue:v,conditionIndex:-1}):v!==void 0&&Ed(s,c.nodeId).actions.push({type:"deletePropertyValue",propertyId:d,sourceValue:h,targetValue:v,conditionIndex:-1}));let y=f.localesConditions?.[e],b=f.localesConditions?.[n];y?.forEach((w,E)=>{let _=f.localesConditions?.[n]?.[E];(!w||!_||!$r(w,_))&&Ed(s,c.nodeId).actions.push({type:"copyPropertyValue",propertyId:d,sourceValue:w.value,targetValue:_,conditionIndex:E,conditionDefinition:w.when})});let S=y?.length??0,C=b?.length??0;if(S<C){let w=Ed(s,c.nodeId);for(let E=S;E<C;E++)w.actions.push({type:"deletePropertyValue",propertyId:d,sourceValue:y?.[E],targetValue:b?.[E],conditionIndex:E})}})},l=this.#e[o];if(!l)throw new Error(`Node ${o} does not exist`);return a(l),!i&&!r&&this.visitDescendants(l.nodeId,a),{nodePlans:Array.from(s.values()),sourceLocale:e,destinationLocale:n}}async copyValuesToLocaleExecute({resolvePattern:e,plan:{sourceLocale:n,destinationLocale:r,nodePlans:o}}){let i=`copyLocaleExecute: ${r}`;console.time(i);for(let{nodeId:s,actions:a}of o)for(let l of a)switch(l.type){case"copyPropertyValue":{let c=this.getNodeProperty(s,l.propertyId)?.type,u=l.sourceValue;c==="contentReference"&&(u=this.prepareContentReferenceWrite({nodeId:s,propertyId:l.propertyId,destinationLocale:r,conditionIndex:l.conditionIndex,sourceValue:l.sourceValue})),this.updateNodeProperty({nodeId:s,property:l.propertyId,source:"other",locale:r,value:()=>u,type:c,conditionIndex:l.conditionIndex,conditionDefinition:l.conditionDefinition});break}case"deletePropertyValue":{this.updateNodeProperty({nodeId:s,property:l.propertyId,source:"other",locale:r,value:void 0,conditionIndex:l.conditionIndex,conditionDefinition:null});break}case"deleteLocalizedNode":{this.deleteNode(s);break}case"duplicateLocalizedNode":{let c=await this.duplicateNode(s,e);this.updateNodeProperty({nodeId:c,locale:void 0,conditionIndex:-1,type:"localeSelect",property:Ab,source:"other",value:()=>r});let u=this.copyValuesToLocalePlan({sourceLocale:n,destinationLocale:r,startingNodeId:c});this.copyValuesToLocaleExecute({plan:u,resolvePattern:e}),l.targetIndexInSlot!==void 0&&this.moveNode({movedNodeId:c,parentNodeId:this.#e[s].parentId,parentSlot:iI,targetIndexInSlot:l.targetIndexInSlot});break}case"updateVisibilityCriteria":{this.updateNodeProperty({nodeId:s,property:Sd,source:"other",locale:void 0,conditionIndex:-1,value:()=>l.targetValue});break}default:throw new Error(`Unhandled action type ${l.type}`)}console.timeEnd(i)}updateNode({nodeId:e,updateComponent:n,updateDataResources:r,updateMetadata:o,doNotSetDirty:i,ignoreOverrides:s}){let a=this.#e[e];if(!a)throw new Error(`Update target node ID ${e} did not exist!`);let l=tr(a,f=>{if(o&&(o(f),f.nodeId=e,f.value=a.value,f.parentId=a.parentId),n){if(n(f.value),"slots"in f.value)throw new Error("Do not set `slots` on a Twee node, insert child nodes instead.");if("parameters"in f.value)throw new Error("Do not set `parameters` on a Twee node, use updateProperties option instead.")}if(r){let p=typeof r=="function"?r(f.value._dataResources):r;if(p==="removeAll")delete f.value._dataResources;else for(let m of p){let g=s?!1:f.nodeId!==this.rootNodeId&&f.value._pattern;switch(m.type){case"set":g&&(this.#n=tr(this.#n,h=>{h[e]??={},h[e].dataResources??={},h[e].dataResources[m.name]=m.value})),f.value._dataResources??={},f.value._dataResources[m.name]=m.value;break;case"remove":g&&(this.#n=tr(this.#n,h=>{delete h[e]?.dataResources?.[m.name]})),delete f.value._dataResources?.[m.name];break;case"reset":{let h=this.#i[e]?.dataResources?.[m.name];f.value._dataResources&&(h&&Object.keys(h).length>0?f.value._dataResources[m.name]=h:delete f.value._dataResources[m.name]),this.#n=tr(this.#n,v=>{delete v[e]?.dataResources?.[m.name]})}break;default:throw new Error(`Unhandled data resource action ${m?.type}`)}}}}),c=!!(a.partOfPattern&&!a.value._patternError),u=a.value.variant!==l.value.variant,d=a.value._overridability?.variants??!1;!s&&c&&u&&d&&(this.#n=tr(this.#n,f=>{f[e]??={},f[e].variant=l.value.variant})),this.#e[e]=l,i||(this.pristine=!1),this.#t.emit("nodeChanged",{changedNode:l,type:"update",oldValue:a})}updateNodeProperty({nodeId:e,property:n,value:r,source:o,locale:i,type:s,doNotSetDirty:a=!1,ignoreOverrides:l=!1,conditionIndex:c,conditionDefinition:u}){let d=this.#e[e];if(!d)throw new Error(`Update target node ID ${e} did not exist!`);if(c<0&&u)throw new Error("Condition definition provided for non-conditional value");let f=!!(d.partOfPattern&&!d.value._patternError),p=[e,n],m=rI(this.#o,p);if(!m&&r==null)return;let g=fse({locale:i,property:m,conditionIndex:c}),h=i?m?.localesConditions?.[i]?.[c]:m?.conditions?.[c],v=typeof r=="function"?tr(g,w=>r(w)):r,y=s??m?.type;if(!y)throw new Error(`Cannot add parameter ${n} to node ${e} without specifying a type`);let b={...m,type:y},S=!1;b=tr(b,w=>{v===void 0&&c<0?S=!r5({locale:i,property:w,conditionIndex:c}):u===null&&c>=0?S=!r5({locale:i,property:w,conditionIndex:c}):QO({locale:i,property:w,newPropertyValue:v,conditionIndex:c,conditionDefinition:u??h?.when??{clauses:[]}})}),S&&(b=void 0);let C=f&&Dp(d.value._overridability,n)==="yes";if(f&&!C&&!l)throw new Error(`Cannot override parameter ${n} on node ${e} because it is not marked as overridable on the pattern (${d.partOfPattern})`);if(C&&(this.#i[e]?.parameters?.[n]||(this.#i=tr(this.#i,E=>{E[e]??={parameters:{},dataResources:{}},E[e].parameters[n]=m??{type:y,value:null}}))),!l&&C){let w=this.#n[e]?.parameters?.[n];this.#n=tr(this.#n,E=>{let $=v==null||b===void 0?null:v,T=w??{type:b?.type??m?.type??"unknown",value:m?.value,conditions:m?.conditions,locales:i&&m?.locales?.[i]?{[i]:m.locales[i]}:void 0,localesConditions:i&&m?.localesConditions?.[i]?{[i]:m.localesConditions[i]}:void 0},N=tr(T,P=>{u===null&&c>=0?r5({locale:i,property:P,conditionIndex:c}):QO({locale:i,property:P,newPropertyValue:$,conditionIndex:c,conditionDefinition:u??h?.when??{clauses:[]}})});(0,Lp.set)(E,`/${e}/parameters/${n}`,N)}),w||this.#t.emit("propertyOverrideCreated",{nodeId:e,property:n})}v===null?(0,Lp.remove)(this.#o,p):(this.#o[e]??={},(0,Lp.set)(this.#o,p,b)),a||(this.pristine=!1),this.#t.emit("nodeParameterChanged",{nodeId:e,parameter:n,locale:i,conditionIndex:c,value:b,previousValue:m,type:r?m?"update":"new":"delete",conditionDefinition:u,source:o})}isPatternPropertyOverridden(e,n,r,o){let i=this.getNodeById(e);if(!i||Dp(i.value._overridability,n)==="no")return!1;let s=this.#n[e]?.parameters?.[n];return s?r?(o===void 0||o===!0)&&s.localesConditions?.[r]!==void 0||(o===void 0||o===!1)&&s.locales?.[r]!==void 0:(o===void 0||o===!0)&&s.conditions!==void 0||(o===void 0||o===!1)&&s.value!==void 0:!1}getPatternPropertyOverrideDefaultValue(e,n,r){let o=this.#i[e]?.parameters?.[n];if(!o)return{exists:!1};if(r&&o.locales?.[r])return{exists:!0,value:o,sourceLocale:r};if(o.value!==void 0)return{exists:!0,value:o,sourceLocale:void 0};let i=Object.keys(o.locales??{})[0];return i?{exists:!0,value:o,sourceLocale:i}:{exists:!1}}resetPatternPropertyOverride(e,n,r){let o=[-1];this.#n=tr(this.#n,s=>{let a=s[e]?.parameters?.[n];if(a)if(r){delete a.locales?.[r];let l=a.localesConditions?.[r];l&&(l.forEach((c,u)=>{o.push(u)}),delete a.localesConditions?.[r]),a.locales&&Object.keys(a.locales).length===0&&delete a.locales,a.localesConditions&&Object.keys(a.localesConditions).length===0&&delete a.localesConditions,Object.keys(a.locales??{}).length===0&&Object.keys(a.localesConditions??{}).length===0&&delete s[e]?.parameters?.[n]}else{let l=a.conditions;l&&l.forEach((c,u)=>{o.push(u)}),delete s[e].parameters?.[n]}});let i=this.getPatternPropertyOverrideDefaultValue(e,n,r);!i.exists||i.value===null?this.updateNodeProperty({nodeId:e,property:n,value:void 0,source:"reset",locale:r,ignoreOverrides:!0,doNotSetDirty:!1,conditionIndex:-1}):o.forEach(s=>{let a=fse({locale:i.sourceLocale,property:i.value,conditionIndex:s,strict:!0});this.updateNodeProperty({nodeId:e,property:n,value:a===void 0?void 0:()=>a,source:"reset",locale:r,type:i.value?.type,ignoreOverrides:!0,doNotSetDirty:!1,conditionIndex:s,conditionDefinition:(r?i.value?.localesConditions?.[r]?.[s]?.when:i.value?.conditions?.[s]?.when)??null})}),this.#t.emit("propertyOverrideReset",{nodeId:e,property:n,usedPatternDefault:i!==void 0})}async duplicateNode(e,n){let r=this.getParentInfo(e);if(!r)throw new Error("Cannot duplicate root node or parentless block");let o=this.copyNodeToClipboard(e);return await this.pasteNodeFromClipboard({parentNodeId:r.parentId,parentSlot:r.parentName,resolvePattern:n,targetIndexInParent:r.targetIndexInParent+1,clipboard:o})}moveNode({movedNodeId:e,parentNodeId:n,parentSlot:r,targetIndexInSlot:o}){if(!this.#e[e])throw new Error(`Cannot move node ${e} - it does not exist`);let s=this.getParentInfo(e);if(!s)throw new Error("Cannot move root node");this.#r[s.parentId][s.parentName].splice(s.targetIndexInParent,1),this.#y(s.parentId,e),this.#f({nodeId:e,parentNodeId:n,parentSlot:r,targetIndexInSlot:o}),this.#m({nodeId:e,destinationParentId:n,destinationSlotName:r,sourceSlotName:s.parentName}),this.pristine=!1,this.#t.emit("childrenChanged",{parentId:n,slotOrBlockName:r,newChildIds:this.#r[n][r],type:"slot"}),this.#t.emit("childrenChanged",{parentId:s.parentId,slotOrBlockName:s.parentName,newChildIds:this.#r[s.parentId][s.parentName],type:"slot"})}deleteNode(e,n){let r=this.getParentInfo(e);if(!r&&!n)throw new Error("Cannot delete root node");r&&!n&&(this.#r[r.parentId][r.parentName].splice(r.targetIndexInParent,1),this.#r[r.parentId][r.parentName].length===0&&delete this.#r[r.parentId][r.parentName],this.selectedNodeId===e&&(this.selectedNodeId=r.parentId),this.#y(r.parentId,e),this.#t.emit("childrenChanged",{parentId:r.parentId,slotOrBlockName:r.parentName,newChildIds:this.#r[r.parentId][r.parentName]??[],type:"slot"})),delete this.#e[e],this.#t.emit("nodeDeleted",{deletedNodeId:e}),this.pristine=!1}#y(e,n){this.#n=tr(this.#n,r=>{let o=r[e]?.slots;o&&Object.keys(o).forEach(i=>{o[i]=o[i].filter(({_id:s})=>s!==n),o[i].length===0&&delete o[i]})})}#h(){if(Object.keys(this.#n).length>0){let e=ps(this.#n);return Object.entries(e).forEach(([r,o])=>{let i=!0;if(!this.#e[r]){delete e[r];return}if(o.parameters){let s=Object.entries(o.parameters);s.forEach(([a,l])=>{let c=mse(l);c?(o.parameters[a]=c,i=!1):delete o.parameters[a]}),s.length===0&&delete o.parameters}o.slots&&Object.entries(o.slots).forEach(([a,l])=>{if(l.length){let c=l.filter(u=>u._id).map(u=>this.exportSubtree(u._id));c?(o.slots[a]=c,i=!1):delete o.slots[a]}else delete o.slots[a]}),o.variant!==void 0&&(i=!1),o.dataResources&&Object.keys(o.dataResources).length>0&&(i=!1),i&&delete e[r]}),Object.keys(e).length===0&&(e=void 0),e}}exportSubtree(e,n){let{keepPatternData:r=!1}=n??{},o=this.#e[e];if(!o)throw new Error(`Node ${e} to export is not found`);let i=ps(o);if(e===this.rootNodeId){let l=this.#h();l?i.value._overrides=l:delete i.value._overrides;let c=i.value;c._name=this.#s._name,this.#s._slug&&(c._slug=this.#s._slug)}let s=[i],a=new Set;for(;s.length>0;){let l=s.pop();if(a.has(l.nodeId))throw new Error("Circular reference detected in the composition tree with node ID "+l.nodeId);if(a.add(l.nodeId),l.value._id=l.nodeId,!r&&(delete l.value._patternDataResources,delete l.value._patternOverrides,l.value._pattern&&l.value._dataResources)){let d=!1;Object.keys(l.value._dataResources).forEach(f=>{i.value._overrides?.[l.nodeId]?.dataResources?.[f]?delete l.value._dataResources[f]:d=!0}),d||delete l.value._dataResources}let c=this.#o[l.nodeId];if(c&&(r||!l.partOfPattern)){let d={},f=!1;Object.entries(c).forEach(([p,m])=>{if(m?.type===Gs&&Array.isArray(m.value)){let g=m.value,h=[];g.forEach(v=>{let y=this.exportSubtree(v,n);h.push(eI(y,v))}),d[p]={value:h,type:Gs},f=!0}else{let g=mse(m);g&&(d[p]=g,f=!0)}}),f&&(l.value.parameters=d)}let u=this.#r[l.nodeId];!u||l.partOfPattern&&!r||Object.entries(u).forEach(([d,f])=>{f.forEach((p,m)=>{let g=this.#e[p];if(!g)throw new Error("Insanity detected.");let h=ps(g),v=l.value;v.slots=v.slots||{},(0,Lp.set)(l,["value","slots",d,m.toString(10)],h.value),s.push(h)})})}return this.#D(i.value),i.value}#S({parentNodeId:e,parentSlot:n,targetIndexInSlot:r,node:o}){if(!this.#e[e])throw new Error("Parent ID to insert under did not exist!");if(this.#e[o.nodeId])throw new Error(`Node with ID '${o.nodeId}' already exists. Nodes must have unique IDs. Did you mean to move or duplicate this node instead?`);this.#e[o.nodeId]=o,this.#f({nodeId:o.nodeId,parentNodeId:e,parentSlot:n,targetIndexInSlot:r})}#f({nodeId:e,parentNodeId:n,parentSlot:r,targetIndexInSlot:o}){let i=this.#e[n],s=this.#r[n]??={},a=s[r]??=[];typeof o<"u"?a.splice(o,0,e):a.push(e),i?.value.type===o5&&(this.#n=tr(this.#n,l=>{l[n]=l[n]??{},l[n].slots={[XLe]:a.map(c=>({_id:c,type:this.#e[c].value.type}))}})),this.#e[e]=tr(this.#e[e],l=>{l.parentId=n})}#w({nodeId:e,property:n,index:r,entry:o}){let i=this.getNodeById(e);if(!i)throw new Error("Node doesn't exist");let a={nodeId:o._id??wd(),value:{type:o.type,_dataResources:o._dataResources},isBlock:!0,parentId:e,propertyValueLocalizability:{}},l=this.getNodeProperty(i.nodeId,n);if(l&&l.type!==Gs)throw new Error("Parameter already exists and isn't a block parameter");let c=this.#e[a.nodeId];this.#e[a.nodeId]=a;let u=ps(this.getNodeProperty(i.nodeId,n)?.value?.filter(d=>this.getNodeById(d))??[]);if(typeof r<"u"){if(r<0)throw new Error("parameter index cannot be less than 0");let d=-1;if(u.forEach((f,p)=>{f===a.nodeId&&(d=p)}),r>u.length+(d===-1?1:0))throw new Error(`Parameter index ${r} outside current index bounds.`);d>-1&&d!==r&&(u=u.filter(f=>f!==a.nodeId),u.splice(r,0,a.nodeId))}else u.push(a.nodeId);return Object.entries(o?.fields??{}).forEach(([d,f])=>{if(f.type===Gs&&Array.isArray(f.value)){let p=f.value,m=[];p.forEach(g=>{let h=g._id??wd();this.#l({nodeId:h,componentTree:tI(g)}),this.#e[h].isBlock=!0,this.#e[h].parentId=a.nodeId,m.push(h)}),this.updateNodeProperty({nodeId:a.nodeId,property:d,type:f.type,value:()=>m,source:"other",locale:void 0,conditionIndex:-1})}else this.updateNodeProperty({nodeId:a.nodeId,property:d,type:f.type,value:()=>f.value,source:"other",locale:void 0,conditionIndex:-1})}),this.updateNodeProperty({nodeId:i.nodeId,property:n,type:Gs,value:()=>u,source:"other",locale:void 0,conditionIndex:-1}),this.#t.emit("nodeChanged",{changedNode:i,oldValue:void 0,type:c?"update":"new"}),this.#t.emit("nodeParameterChanged",{nodeId:i.nodeId,parameter:n,previousValue:l,source:"other",type:c?"update":"new",locale:void 0,conditionIndex:-1,conditionDefinition:void 0,value:{type:Gs,value:u}}),{blockIds:u}}#l({componentTree:e,nodeId:n,partOfPattern:r,partOfNestedPattern:o,resetUids:i,isBlock:s,allowReplacement:a}){let{slots:l,parameters:c,_id:u,_overrides:d,...f}=e,p=r??f._pattern,m=f._pattern&&f._pattern!==p?f._pattern:o,g=n??(i?void 0:u)??wd();if(this.#e[g]&&!a)throw new Error(`Node with ID '${g}' already exists. Nodes must have unique IDs.`);let h={nodeId:g,value:f,partOfPattern:p,partOfNestedPattern:m,isBlock:s,propertyValueLocalizability:Object.entries(c??{}).reduce((v,[y,b])=>(v[y]=Dx({definition:void 0,currentValue:b,lastUserChoice:void 0}),v),{})};return p&&(h.partOfPattern=p),this.#e[h.nodeId]=h,c&&Object.entries(c).forEach(([v,y])=>{let{connectedData:b,...S}=y,C=b?dse(use(b)):y.value;if(y?.type===Gs&&Array.isArray(C)){let w=C,E=[];w?.forEach(_=>{let $={..._,_id:i?wd():_._id??wd()};if(this.#e[$._id])throw new Error(`Block node with ID '${$._id}' already exists. Block nodes must have unique IDs.`);return E.push($._id),this.#e[$._id]={nodeId:$._id,value:{type:Gs},propertyValueLocalizability:{}},this.#l({componentTree:tI($),nodeId:$._id,allowReplacement:!0,partOfPattern:p,partOfNestedPattern:m}),this.#e[$._id].isBlock=!0,this.#e[$._id].parentId=h.nodeId,this.#e[$._id]}),C=E}this.#o[h.nodeId]=this.#o[h.nodeId]??{},(0,Lp.set)(this.#o,[h.nodeId,v],{...S,value:C})}),l&&Object.entries(l).forEach(([v,y])=>{let b=y.map(S=>{if(this.#e[S._id??""]?.isBlock)return;let C=this.#l({componentTree:S,partOfPattern:f.type===o5?void 0:p,partOfNestedPattern:f.type===o5?void 0:m,resetUids:i});return this.#e[C].parentId=h.nodeId,C});this.#r[h.nodeId]=this.#r[h.nodeId]??{},this.#r[h.nodeId][v]=b.filter(S=>S)}),h.nodeId}#b(e,n,r){let o=this.#x(e,n);return this.#l({componentTree:o,nodeId:n,allowReplacement:r})}#x(e,n){let r=ps(e);return this.#v({composition:r}),QE(r,n),r._pattern=e._id,delete r._id,delete r._name,delete r._slug,delete r._overrides,delete r._locales,delete r._author,delete r._authorSubject,delete r._creator,delete r._creatorSubject,r._dataResources&&(r._patternDataResources=ps(r._dataResources),delete r._dataResources),r}getParentInfo(e){let{parentId:n,isBlock:r}=this.#e[e]??{};if(!n)return;let o=this.#e[n];if(o)if(r)for(let[i,s]of Object.entries(this.#o[n]??{})){if(s?.type!==Gs)continue;let a=Array.isArray(s.value)?s.value:[],l=a.indexOf(e);if(l>=0)return{value:o.value,parentId:n,parentName:i,targetIndexInParent:l,parentChildIds:a,parentType:"block"}}else{let i=this.#r[n];if(!i&&!r)throw new Error("Sanity failed; parent had no children!");for(let[s,a]of Object.entries(i??{})){let l=a.indexOf(e);if(l>=0)return{value:o.value,parentId:n,parentName:s,targetIndexInParent:l,parentChildIds:a,parentType:"slot"}}return}}static#E(e){return tr(e,r=>{delete r.slots,delete r.parameters})}#_(e){let n=e;for(;n;){let r=this.getNodeById(n);if(!r)break;if(r.value._pattern)return!1;if(r.value.type===o5||!r.partOfPattern)return!0;n=r.parentId}return!0}#T(e,n,r){let i={...this.#h(),...r},s;if(this.#n=tr(this.#n,l=>{this.#i=tr(this.#i,c=>{s=n5(e,i,(u,d,f)=>{l[u]=d,c[u]=this.#i[f]})})}),!s)throw new Error("Failed to duplicate component");s=tr(s,l=>{l._overrides=ps(this.#n),this.#v({composition:l,preserveChildrenSlotSections:!0})});let a=this.#l({componentTree:s,isBlock:n.parentType==="block"});if(n.parentType==="block"){let l=this.getNodeProperty(n.parentId,n.parentName)?.value??[],c=[...l.slice(0,n.targetIndexInParent),a,...l.slice(n.targetIndexInParent)];this.updateNodeProperty({nodeId:n.parentId,property:n.parentName,type:Gs,value:()=>c,locale:void 0,conditionIndex:-1,source:"other"}),this.#e[a].parentId=n.parentId,this.#t.emit("nodeChanged",{changedNode:this.getNodeById(a),type:"new",oldValue:void 0}),this.#t.emit("childrenChanged",{parentId:n.parentId,slotOrBlockName:n.parentName,newChildIds:c,type:"block"})}else{this.#f({nodeId:a,parentNodeId:n.parentId,parentSlot:n.parentName,targetIndexInSlot:n.targetIndexInParent}),this.#m({nodeId:a,destinationParentId:n.parentId,destinationSlotName:n.parentName}),this.#t.emit("childrenChanged",{parentId:n.parentId,slotOrBlockName:n.parentName,newChildIds:this.#r[n.parentId][n.parentName],type:"slot"});let l=c=>{this.#t.emit("nodeChanged",{changedNode:c,type:"new",oldValue:void 0})};this.visitNodeAndDescendants(a,l)}return this.pristine=!1,a}#v({composition:e,ignoreRootOverrides:n,preserveChildrenSlotSections:r}){this.#i=tr(this.#i,i=>{let s=XO({beforeApplyParameterOverride(c,u,d){i[c._id]??={parameters:{},dataResources:{}},i[c._id].parameters[u]=ps(d)},beforeApplyDataResourceOverride(c,u,d){c._dataResources?.[u]?.ignorePatternParameterDefault||(i[c._id]??={parameters:{},dataResources:{}},i[c._id].dataResources[u]=ps(d))}}),a=XO({beforeApplyParameterOverride(c,u,d,f){i[c._id]?.parameters[u]||(i[c._id]??={parameters:{},dataResources:{}},i[c._id].parameters[u]=ps(f??null))},beforeApplyDataResourceOverride(c,u,d,f){c._dataResources?.[u]?.ignorePatternParameterDefault||i[c._id]?.dataResources[u]||(i[c._id]??={parameters:{},dataResources:{}},i[c._id].dataResources[u]=ps(f))}});if(n){let{_overrides:c,...u}=e;Cc(u,({node:d})=>{s.visitNode(d)})}let l=n?a:s;Cc(e,({node:c})=>{l.visitNode(c)})});let o=Vie({preserveOwnSlotSections:!0,preserveChildrenSlotSections:r});Cc(e,i=>{o(i)})}visitNodeAndDescendants(e,n){let r=this.getNodeById(e);if(!r)throw new Error("Insanity detected.");n(r),this.visitDescendants(e,n)}visitDescendants(e,n){let r=this.#p(e,new Set);for(let o of r)n(...o)}async visitDescendantsAsync(e,n){let r=this.#p(e,new Set);for(let o of r)await n(...o)}*#p(e,n){let r=this.#e[e],o=this.#r[e]??{},i=Object.entries(this.#o[e]??{}).filter(([,s])=>s?.type===Gs)??[];if(!r)throw new Error("Insanity detected.");n.add(e);for(let[s,a]of i){let l=a.value??[];for(let c=0;c<l.length;c++){let u=l[c],d=this.#e[u];if(d){if(n.has(u)){console.error(`Detected parent/child cycle in composition, ID ${u} exists more than once. The traversal of descendants will be aborted for the cycle subtree.`);continue}yield[d,r,s,c];for(let f of this.#p(u,n))yield f}}}for(let[s,a]of Object.entries(o))for(let l=0;l<a.length;l++){let c=a[l],u=this.#e[c];if(u){if(n.has(c)){console.error(`Detected parent/child cycle in composition, ID ${c} exists more than once. The traversal of descendants will be aborted for the cycle subtree.`);continue}yield[u,r,s,l];for(let d of this.#p(c,n))yield d}}}#m({nodeId:e,destinationParentId:n,destinationSlotName:r,sourceSlotName:o}){let i=r,s=o===ase,a=i===ase,l=o===lse,c=i===lse,u=i===iI,d=this.getNodeProperty(e,sse);a&&d&&this.updateNodeProperty({nodeId:e,property:sse,value:void 0,source:"other",locale:void 0,conditionIndex:-1});let f=this.getNodeProperty(e,Mb);!a&&f&&this.updateNodeProperty({nodeId:e,property:Mb,value:void 0,source:"other",locale:void 0,conditionIndex:-1}),a&&!s&&this.#C({nodeId:e,siblingIds:this.getNodeChildren(n)?.[r]??[],selectExistingName:g=>this.getNodeProperty(g,Mb)?.value?.name,setName:g=>this.updateNodeProperty({nodeId:e,property:Mb,value:h=>h&&typeof h=="object"&&h!==null?{...h,name:g}:{name:g,crit:[]},source:"other",locale:void 0,conditionIndex:-1,type:Mb})}),c&&!l&&this.#C({nodeId:e,siblingIds:this.getNodeChildren(n)?.[r]??[],selectExistingName:g=>this.getNodeProperty(g,cse)?.value?.id,setName:g=>this.updateNodeProperty({nodeId:e,property:cse,value:h=>h&&typeof h=="object"&&h!==null?{...h,id:g}:{id:g},source:"other",locale:void 0,conditionIndex:-1,type:"testVariant"})});let p=this.getNodeProperty(e,Ab);!u&&p&&this.updateNodeProperty({nodeId:e,property:Ab,value:void 0,source:"other",locale:void 0,conditionIndex:-1});let m=this.getNodeProperty(e,Sd);(a||u||c)&&m&&this.updateNodeProperty({nodeId:e,property:Sd,value:void 0,source:"other",locale:void 0,conditionIndex:-1})}#C({nodeId:e,siblingIds:n,selectExistingName:r,setName:o}){let i=r(e),s=d=>n.some(f=>f===e?!1:r(f)===d),a=i&&s(i);if(i&&!a)return;let l=this.getNodeById(e)?.value.type;if(!l)throw new Error("Insanity detected.");let c=0,u=oI(e,l,c);do u=oI(e,l,c),c++;while(s(u));o(u)}prepareContentReferenceWrite({nodeId:e,propertyId:n,destinationLocale:r,conditionIndex:o,sourceValue:i}){let s=this.#$({value:i,dataResources:this.#e[e]?.value._dataResources});if(!s)return i;let{dataResource:a,isSingleEntryReference:l}=s,c=zp(e,n,r==="${locale}"?void 0:r,o);this.updateNode({nodeId:e,updateDataResources:[{name:c,type:"set",value:{...a,variables:{...a?.variables,locale:r}}}]});let u=`/${c}/entries${l?"/0":""}`;return dse(use({syntax:"jptr",pointer:u}))}#$({value:e,dataResources:n}){if(typeof e!="string")return;let r;pse(e,(a,l)=>{l==="variable"&&(r=a)});let o=r?nI(r):void 0;if(!o)return;let i=o.dataResource,s=n?.[i];if(s)return{dataResource:s,dataResourceName:i,isSingleEntryReference:o.dataExpression?.endsWith("/0")}}#N(e){if(typeof e!="string")return;let n;return pse(e,(o,i)=>{i==="variable"&&(n=o)}),(n?nI(n):void 0)?.dataResource}#D(e){let n=new Set,r=[],o=({node:i})=>{let s=QLe(i),a=i._dataResources;if(a)for(let[l,c]of Object.entries(a))c.type===ll&&r.push({dataResources:a,dataResourceKey:l});if(s)for(let l of Object.values(s))l.type==="contentReference"&&eAe(l,({value:c})=>{let u=this.#N(c);u&&n.add(u)})};if(Cc(e,o),"_overrides"in e&&e._overrides)for(let[,i]of Object.entries(e._overrides))Cc({type:e.type,...i,_dataResources:i.dataResources},o);for(let{dataResources:i,dataResourceKey:s}of r)n.has(s)||delete i[s]}};function mse(t){return t?.value===void 0&&!t?.conditions&&!t?.locales&&!t?.localesConditions?null:t}function Ed(t,e){return rAe(t,e,()=>({nodeId:e,actions:[]}))}function rAe(t,e,n){return t.has(e)||t.set(e,n()),t.get(e)}import{CANVAS_DRAFT_STATE as a5,CanvasClient as aAe}from"@uniformdev/canvas";import{ProjectMapClient as lAe}from"@uniformdev/project-map";import{produce as cAe}from"immer";function hse(t){return t.reduce((e,n)=>(e[n._id]={id:n._id,type:n.type,name:n._name},e),{})}import{CANVAS_DRAFT_STATE as vse,CanvasClient as sI,ContentClient as yse,ProjectClient as bse}from"@uniformdev/canvas";function xse(t){let e,n,r;return{fetchProjectGuidance:async()=>(e!==void 0||(e=(await new bse(t).get({projectId:t.projectId}))?.guidance),e),fetchDefinitions:async()=>{if(n!==void 0)return n;let i=await new sI(t).getComponentDefinitions({limit:1e3,includeSystem:!0});return n=Object.fromEntries(i.componentDefinitions.map(s=>[s.id,s])),n},fetchPatterns:async()=>{if(r!==void 0)return r;let i=await new sI(t).getCompositionList({limit:1e3,pattern:!0,patternType:"component",resolveData:!1,skipPatternResolution:!0,skipOverridesResolution:!0,state:vse});return r=hse(i.compositions.map(s=>s.composition)),r},resolvePatternData:async o=>(await new sI(t).getCompositionById({compositionId:o,state:vse,skipPatternResolution:!1,skipOverridesResolution:!0,withComponentIDs:!0,skipDataResolution:!0,withWorkflowDefinition:!0,releaseId:void 0}))?.composition,getToolClient:async()=>t.toolInvoker,getDimensionGuidance:async()=>{}}}function Cse(t){let e,n;return{fetchProjectGuidance:async()=>(e!==void 0||(e=(await new bse(t).get({projectId:t.projectId}))?.guidance),e),fetchDefinitions:async()=>{if(n!==void 0)return n;let o=await new yse(t).getContentTypes({limit:1e3});return n=Object.fromEntries(o.contentTypes.map(i=>[i.id,Jie(i)])),n},fetchPatterns:async()=>({}),resolvePatternData:async r=>{let i=(await new yse(t).getEntries({entryIDs:[r],skipPatternResolution:!1,skipOverridesResolution:!0,withComponentIDs:!0,skipDataResolution:!0,withWorkflowDefinition:!0,releaseId:void 0}))?.entries[0];return Lb(i).composition},getToolClient:async()=>t.toolInvoker,getDimensionGuidance:async()=>{}}}import{parseHTML as oAe}from"linkedom/worker";function iAe(t){let e=Object.getPrototypeOf(t.body);for(;e&&!Object.getOwnPropertyDescriptor(e,"style");)e=Object.getPrototypeOf(e);let n=e?Object.getOwnPropertyDescriptor(e,"style"):void 0;if(!n?.get||e.__stylePatched)return;let r=n.get;Object.defineProperty(e,"style",{get(){let o=r.call(this);return new Proxy(o,{get(i,s){if(typeof s=="string"){let a=i[s];return typeof a=="function"?a.bind(i):a===void 0?"":a}return i[s]},set(i,s,a){return i[s]=a,!0}})},configurable:!0}),e.__stylePatched=!0}function i5(t){let e=`<!DOCTYPE html><html><body>${t}</body></html>`,{document:n}=oAe(e);return iAe(n),n}import{LocaleClient as sAe}from"@uniformdev/canvas";async function s5(t,e){if(!t||t.length===0)return;let o=(await new sAe(e).get()).results.map(s=>s.locale),i=t.filter(s=>!o.includes(s));if(i.length>0)throw new Error(`The following locales are not registered in your project: ${i.join(", ")}`)}async function l5({action:t,id:e,instructions:n,isPattern:r,patternId:o,projectMapNode:i,getEditUrl:s,env:a}){let l=new aAe(a),c,u,d=t==="update"?e:void 0,f={success:!0,actionsTaken:[]};if(t==="duplicate"){if(u=await l.getCompositionById({compositionId:e,state:a5,skipDataResolution:!0,skipPatternResolution:!1,withComponentIDs:!0,skipOverridesResolution:!0}),!u)throw new Error("Composition not found");let p=crypto.randomUUID(),m=Hie(u.composition,p),g=cAe(m,h=>{h._name=`${h._name} (copy)`,h._slug&&(h._slug=`${h._slug}-copy${h._slug?.endsWith("/")?"/":""}`)});c=new ol(g),e=p}else if(t==="create"){if(!n)throw new Error("Instructions are required for create");if(!n.name)throw new Error("Name is required for create");if(!n.type)throw new Error("Type is required for create");if(!o)c=new ol({_id:e,_name:n.name,type:n.type,_overridability:{hideLockedParameters:!0}});else{let p={composition:{_id:e,_name:n.name,type:n.type,_pattern:o},projectId:a.projectId,state:a5,pattern:!1};await l.updateComposition(p),d=e}}if(d){if(u=await l.getCompositionById({compositionId:e,state:a5,skipDataResolution:!0,skipPatternResolution:!1,withComponentIDs:!0,skipOverridesResolution:!0}),!u)throw new Error("Composition not found");c=new ol(u.composition)}if(t==="delete"&&await l.removeComposition({compositionId:e}),c){await s5(n?.localeUpdates?.enableLocales,a),f=await JE({twee:c,descriptionUpdate:void 0,slugUpdate:void 0,nameUpdate:n?.name,propertyUpdates:n?.parameterUpdates??[],dataResourceUpdates:n?.dataResourceUpdates??[],localeUpdates:n?.localeUpdates,slotUpdates:n??{},currentEditorLocale:void 0,referenceData:xse(a),isEditingPattern:r,domParser:i5});let p=c.exportTree(),m=c.exportMetadata(),g={composition:p,projectId:a.projectId,state:a5,pattern:r,releaseId:u?.releaseId,editionId:u?.editionId,...m};await l.updateComposition(g)}if(t==="create"&&!r&&(i?.nodePathSegment||i?.localePathSegments)&&n?.name){let p=new lAe({apiKey:a.apiKey,apiHost:a.apiHost,projectId:a.projectId}),{path:m,nodeId:g}=await Die({projectMapClient:p,compositionId:e,compositionName:n.name,nodePathSegment:i.nodePathSegment||"",parentNodeId:i.parentNodeId,localePathSegments:i.localePathSegments,allowedQueryStrings:i.allowedQueryStrings});return f.actionsTaken.push({success:!0,summary:`Created project map node at path: ${m}`}),{content:[{type:"text",text:JSON.stringify({...f,editUrl:s(e),projectMapNode:{path:m,nodeId:g}},null,2)}]}}return{content:[{type:"text",text:JSON.stringify({...f,editUrl:s(e)},null,2)}]}}function c5(t,e){return`${e.baseWebUrl}/dashboards/canvas/edit/${t}`}async function u5(t,e,n){return await n.toolInvoker.invoke("createFilterExpression",{...t,entityType:e})}var uAe={action:ro.enum(["create","update","delete","duplicate"]).describe("The action to perform"),id:ro.string().uuid().describe("UUID of the composition instance to create, update, delete, or duplicate"),patternId:ro.string().uuid().describe("Composition pattern ID to create the composition from. Omit when not creating, or when creating a composition without a composition pattern.").optional(),instructions:bk.describe("Modification instructions for the composition. Omit for delete and duplicate.").optional(),projectMapNode:ro.object({parentNodeId:ro.string().uuid().describe("UUID of the parent node from searchProjectMapNodes. If omitted, the node will be a child of the root node.").optional(),nodePathSegment:ro.string().describe('URL path segment for the node (e.g., "about-us", "products", ":productId" for dynamic matching). Use a slugified version of the name unless otherwise requested by the user. Omit if not creating a project map node.').optional(),localePathSegments:ro.array(ro.object({locale:ro.string().describe('Locale code (e.g., "en-US", "fr-FR")'),pathSegment:ro.string().describe("URL path segment for this locale")})).describe("Optional array of locale-specific path segments. Unspecified locales use the nodePathSegment. Do not use these for dynamic path segments.").optional(),allowedQueryStrings:ro.array(ro.object({name:ro.string().describe("Query parameter name"),defaultValue:ro.string().describe("Default value if not provided in the URL").optional()})).describe("Optional array of allowed query string parameters for this node").optional()}).describe("Attaches the new composition to a new node in the project map hierarchy. Omit to avoid creating a project map node, or if action is not create.").optional()};function Sse(t,e){t.tool("compositionAction","Creates, updates, or deletes a Uniform Composition",uAe,async n=>await l5({...n,isPattern:!1,getEditUrl:r=>c5(r,e),patternId:n.patternId,projectMapNode:n.projectMapNode,env:e}))}import*as On from"zod/v3";var dAe=On.object({field:On.string(),operator:On.string(),value:On.string().or(On.array(On.string()))}),fAe=On.object({filter:On.array(dAe),error:On.string().describe("An error message if the filter expression could not be created, otherwise an empty string"),sort:On.array(On.enum(["created_at_ASC","created_at_DESC","updated_at_ASC","updated_at_DESC","author_ASC","author_DESC","creator_ASC","creator_DESC","name_ASC","name_DESC","slug_ASC","slug_DESC"])),limit:On.number().min(1).max(100),offset:On.number().min(0),keyword:On.string(),locale:On.string().optional()}),Sc=On.object({searchExpressionPrompt:On.string().describe(`Describe what you are looking for, for example "created by me in the last week" or "type is article and headline contains breaking news" or "keyword search for breaking news".
5838
5838
  You can specify multiple criteria (AND only).
5839
5839
  You can filter by date, number, or string properties on the definition, as well as name, created, modified, author, slug, enabled locales, type, and publish status.`),username:On.string().describe("The username of the current user. If you do not know the username, use an empty string"),locale:On.string().describe("The current locale. If there is no current locale, use an empty string")}),d_t={displayName:"Create filter expression",description:"Creates a Uniform search filter expression for searching entries, patterns, or compositions from a user prompt. Meant to be a callable tool only.",inputSchema:Sc.extend({entityType:On.enum(["composition","entry","componentPattern","compositionPattern","entryPattern"]).describe("The entity type we are creating a filter for")}),outputSchema:fAe,runsAt:"server",timeout:10,callable:!0};import*as Iae from"zod/v3";var wc=class extends Error{},d5=class extends wc{constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}},f5=class extends wc{constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}},p5=class extends wc{constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}},Ys=class extends wc{},l0=class extends wc{constructor(e){super(`Invalid unit ${e}`)}},br=class extends wc{},Zs=class extends wc{constructor(){super("Zone is an abstract class")}};var ge="numeric",qs="short",zi="long",_d={year:ge,month:ge,day:ge},Ob={year:ge,month:qs,day:ge},aI={year:ge,month:qs,day:ge,weekday:qs},Ib={year:ge,month:zi,day:ge},kb={year:ge,month:zi,day:ge,weekday:zi},Rb={hour:ge,minute:ge},Pb={hour:ge,minute:ge,second:ge},Fb={hour:ge,minute:ge,second:ge,timeZoneName:qs},Bb={hour:ge,minute:ge,second:ge,timeZoneName:zi},zb={hour:ge,minute:ge,hourCycle:"h23"},jb={hour:ge,minute:ge,second:ge,hourCycle:"h23"},Vb={hour:ge,minute:ge,second:ge,hourCycle:"h23",timeZoneName:qs},Ub={hour:ge,minute:ge,second:ge,hourCycle:"h23",timeZoneName:zi},Hb={year:ge,month:ge,day:ge,hour:ge,minute:ge},Kb={year:ge,month:ge,day:ge,hour:ge,minute:ge,second:ge},Wb={year:ge,month:qs,day:ge,hour:ge,minute:ge},Gb={year:ge,month:qs,day:ge,hour:ge,minute:ge,second:ge},lI={year:ge,month:qs,day:ge,weekday:qs,hour:ge,minute:ge},Yb={year:ge,month:zi,day:ge,hour:ge,minute:ge,timeZoneName:qs},Zb={year:ge,month:zi,day:ge,hour:ge,minute:ge,second:ge,timeZoneName:qs},qb={year:ge,month:zi,day:ge,weekday:zi,hour:ge,minute:ge,timeZoneName:zi},Jb={year:ge,month:zi,day:ge,weekday:zi,hour:ge,minute:ge,second:ge,timeZoneName:zi};var yi=class{get type(){throw new Zs}get name(){throw new Zs}get ianaName(){return this.name}get isUniversal(){throw new Zs}offsetName(e,n){throw new Zs}formatOffset(e,n){throw new Zs}offset(e){throw new Zs}equals(e){throw new Zs}get isValid(){throw new Zs}};var cI=null,Td=class t extends yi{static get instance(){return cI===null&&(cI=new t),cI}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:n,locale:r}){return g5(e,n,r)}formatOffset(e,n){return $d(this.offset(e),n)}offset(e){return-new Date(e).getTimezoneOffset()}equals(e){return e.type==="system"}get isValid(){return!0}};var v5={};function pAe(t){return v5[t]||(v5[t]=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",era:"short"})),v5[t]}var mAe={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function gAe(t,e){let n=t.format(e).replace(/\u200E/g,""),r=/(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(n),[,o,i,s,a,l,c,u]=r;return[s,o,i,a,l,c,u]}function hAe(t,e){let n=t.formatToParts(e),r=[];for(let o=0;o<n.length;o++){let{type:i,value:s}=n[o],a=mAe[i];i==="era"?r[a]=s:He(a)||(r[a]=parseInt(s,10))}return r}var h5={},No=class t extends yi{static create(e){return h5[e]||(h5[e]=new t(e)),h5[e]}static resetCache(){h5={},v5={}}static isValidSpecifier(e){return this.isValidZone(e)}static isValidZone(e){if(!e)return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:e}).format(),!0}catch{return!1}}constructor(e){super(),this.zoneName=e,this.valid=t.isValidZone(e)}get type(){return"iana"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(e,{format:n,locale:r}){return g5(e,n,r,this.name)}formatOffset(e,n){return $d(this.offset(e),n)}offset(e){let n=new Date(e);if(isNaN(n))return NaN;let r=pAe(this.name),[o,i,s,a,l,c,u]=r.formatToParts?hAe(r,n):gAe(r,n);a==="BC"&&(o=-Math.abs(o)+1);let f=c0({year:o,month:i,day:s,hour:l===24?0:l,minute:c,second:u,millisecond:0}),p=+n,m=p%1e3;return p-=m>=0?m:1e3+m,(f-p)/(60*1e3)}equals(e){return e.type==="iana"&&e.name===this.name}get isValid(){return this.valid}};var wse={};function vAe(t,e={}){let n=JSON.stringify([t,e]),r=wse[n];return r||(r=new Intl.ListFormat(t,e),wse[n]=r),r}var uI={};function dI(t,e={}){let n=JSON.stringify([t,e]),r=uI[n];return r||(r=new Intl.DateTimeFormat(t,e),uI[n]=r),r}var fI={};function yAe(t,e={}){let n=JSON.stringify([t,e]),r=fI[n];return r||(r=new Intl.NumberFormat(t,e),fI[n]=r),r}var pI={};function bAe(t,e={}){let{base:n,...r}=e,o=JSON.stringify([t,r]),i=pI[o];return i||(i=new Intl.RelativeTimeFormat(t,e),pI[o]=i),i}var Xb=null;function xAe(){return Xb||(Xb=new Intl.DateTimeFormat().resolvedOptions().locale,Xb)}var Ese={};function CAe(t){let e=Ese[t];if(!e){let n=new Intl.Locale(t);e="getWeekInfo"in n?n.getWeekInfo():n.weekInfo,Ese[t]=e}return e}function SAe(t){let e=t.indexOf("-x-");e!==-1&&(t=t.substring(0,e));let n=t.indexOf("-u-");if(n===-1)return[t];{let r,o;try{r=dI(t).resolvedOptions(),o=t}catch{let l=t.substring(0,n);r=dI(l).resolvedOptions(),o=l}let{numberingSystem:i,calendar:s}=r;return[o,i,s]}}function wAe(t,e,n){return(n||e)&&(t.includes("-u-")||(t+="-u"),n&&(t+=`-ca-${n}`),e&&(t+=`-nu-${e}`)),t}function EAe(t){let e=[];for(let n=1;n<=12;n++){let r=St.utc(2009,n,1);e.push(t(r))}return e}function _Ae(t){let e=[];for(let n=1;n<=7;n++){let r=St.utc(2016,11,13+n);e.push(t(r))}return e}function y5(t,e,n,r){let o=t.listingMode();return o==="error"?null:o==="en"?n(e):r(e)}function TAe(t){return t.numberingSystem&&t.numberingSystem!=="latn"?!1:t.numberingSystem==="latn"||!t.locale||t.locale.startsWith("en")||new Intl.DateTimeFormat(t.intl).resolvedOptions().numberingSystem==="latn"}var mI=class{constructor(e,n,r){this.padTo=r.padTo||0,this.floor=r.floor||!1;let{padTo:o,floor:i,...s}=r;if(!n||Object.keys(s).length>0){let a={useGrouping:!1,...r};r.padTo>0&&(a.minimumIntegerDigits=r.padTo),this.inf=yAe(e,a)}}format(e){if(this.inf){let n=this.floor?Math.floor(e):e;return this.inf.format(n)}else{let n=this.floor?Math.floor(e):u0(e,3);return Hn(n,this.padTo)}}},gI=class{constructor(e,n,r){this.opts=r,this.originalZone=void 0;let o;if(this.opts.timeZone)this.dt=e;else if(e.zone.type==="fixed"){let s=-1*(e.offset/60),a=s>=0?`Etc/GMT+${s}`:`Etc/GMT${s}`;e.offset!==0&&No.create(a).valid?(o=a,this.dt=e):(o="UTC",this.dt=e.offset===0?e:e.setZone("UTC").plus({minutes:e.offset}),this.originalZone=e.zone)}else e.zone.type==="system"?this.dt=e:e.zone.type==="iana"?(this.dt=e,o=e.zone.name):(o="UTC",this.dt=e.setZone("UTC").plus({minutes:e.offset}),this.originalZone=e.zone);let i={...this.opts};i.timeZone=i.timeZone||o,this.dtf=dI(n,i)}format(){return this.originalZone?this.formatToParts().map(({value:e})=>e).join(""):this.dtf.format(this.dt.toJSDate())}formatToParts(){let e=this.dtf.formatToParts(this.dt.toJSDate());return this.originalZone?e.map(n=>{if(n.type==="timeZoneName"){let r=this.originalZone.offsetName(this.dt.ts,{locale:this.dt.locale,format:this.opts.timeZoneName});return{...n,value:r}}else return n}):e}resolvedOptions(){return this.dtf.resolvedOptions()}},hI=class{constructor(e,n,r){this.opts={style:"long",...r},!n&&b5()&&(this.rtf=bAe(e,r))}format(e,n){return this.rtf?this.rtf.format(e,n):_se(n,e,this.opts.numeric,this.opts.style!=="long")}formatToParts(e,n){return this.rtf?this.rtf.formatToParts(e,n):[]}},$Ae={firstDay:1,minimalDays:4,weekend:[6,7]},tn=class t{static fromOpts(e){return t.create(e.locale,e.numberingSystem,e.outputCalendar,e.weekSettings,e.defaultToEN)}static create(e,n,r,o,i=!1){let s=e||Ut.defaultLocale,a=s||(i?"en-US":xAe()),l=n||Ut.defaultNumberingSystem,c=r||Ut.defaultOutputCalendar,u=Qb(o)||Ut.defaultWeekSettings;return new t(a,l,c,u,s)}static resetCache(){Xb=null,uI={},fI={},pI={}}static fromObject({locale:e,numberingSystem:n,outputCalendar:r,weekSettings:o}={}){return t.create(e,n,r,o)}constructor(e,n,r,o,i){let[s,a,l]=SAe(e);this.locale=s,this.numberingSystem=n||a||null,this.outputCalendar=r||l||null,this.weekSettings=o,this.intl=wAe(this.locale,this.numberingSystem,this.outputCalendar),this.weekdaysCache={format:{},standalone:{}},this.monthsCache={format:{},standalone:{}},this.meridiemCache=null,this.eraCache={},this.specifiedLocale=i,this.fastNumbersCached=null}get fastNumbers(){return this.fastNumbersCached==null&&(this.fastNumbersCached=TAe(this)),this.fastNumbersCached}listingMode(){let e=this.isEnglish(),n=(this.numberingSystem===null||this.numberingSystem==="latn")&&(this.outputCalendar===null||this.outputCalendar==="gregory");return e&&n?"en":"intl"}clone(e){return!e||Object.getOwnPropertyNames(e).length===0?this:t.create(e.locale||this.specifiedLocale,e.numberingSystem||this.numberingSystem,e.outputCalendar||this.outputCalendar,Qb(e.weekSettings)||this.weekSettings,e.defaultToEN||!1)}redefaultToEN(e={}){return this.clone({...e,defaultToEN:!0})}redefaultToSystem(e={}){return this.clone({...e,defaultToEN:!1})}months(e,n=!1){return y5(this,e,vI,()=>{let r=n?{month:e,day:"numeric"}:{month:e},o=n?"format":"standalone";return this.monthsCache[o][e]||(this.monthsCache[o][e]=EAe(i=>this.extract(i,r,"month"))),this.monthsCache[o][e]})}weekdays(e,n=!1){return y5(this,e,yI,()=>{let r=n?{weekday:e,year:"numeric",month:"long",day:"numeric"}:{weekday:e},o=n?"format":"standalone";return this.weekdaysCache[o][e]||(this.weekdaysCache[o][e]=_Ae(i=>this.extract(i,r,"weekday"))),this.weekdaysCache[o][e]})}meridiems(){return y5(this,void 0,()=>bI,()=>{if(!this.meridiemCache){let e={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[St.utc(2016,11,13,9),St.utc(2016,11,13,19)].map(n=>this.extract(n,e,"dayperiod"))}return this.meridiemCache})}eras(e){return y5(this,e,xI,()=>{let n={era:e};return this.eraCache[e]||(this.eraCache[e]=[St.utc(-40,1,1),St.utc(2017,1,1)].map(r=>this.extract(r,n,"era"))),this.eraCache[e]})}extract(e,n,r){let o=this.dtFormatter(e,n),i=o.formatToParts(),s=i.find(a=>a.type.toLowerCase()===r);return s?s.value:null}numberFormatter(e={}){return new mI(this.intl,e.forceSimple||this.fastNumbers,e)}dtFormatter(e,n={}){return new gI(e,this.intl,n)}relFormatter(e={}){return new hI(this.intl,this.isEnglish(),e)}listFormatter(e={}){return vAe(this.intl,e)}isEnglish(){return this.locale==="en"||this.locale.toLowerCase()==="en-us"||new Intl.DateTimeFormat(this.intl).resolvedOptions().locale.startsWith("en-us")}getWeekSettings(){return this.weekSettings?this.weekSettings:x5()?CAe(this.locale):$Ae}getStartOfWeek(){return this.getWeekSettings().firstDay}getMinDaysInFirstWeek(){return this.getWeekSettings().minimalDays}getWeekendDays(){return this.getWeekSettings().weekend}equals(e){return this.locale===e.locale&&this.numberingSystem===e.numberingSystem&&this.outputCalendar===e.outputCalendar}};var SI=null,oo=class t extends yi{static get utcInstance(){return SI===null&&(SI=new t(0)),SI}static instance(e){return e===0?t.utcInstance:new t(e)}static parseSpecifier(e){if(e){let n=e.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(n)return new t(Ap(n[1],n[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${$d(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${$d(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(e,n){return $d(this.fixed,n)}get isUniversal(){return!0}offset(){return this.fixed}equals(e){return e.type==="fixed"&&e.fixed===this.fixed}get isValid(){return!0}};var d0=class extends yi{constructor(e){super(),this.zoneName=e}get type(){return"invalid"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(){return null}formatOffset(){return""}offset(){return NaN}equals(){return!1}get isValid(){return!1}};function Js(t,e){let n;if(He(t)||t===null)return e;if(t instanceof yi)return t;if(Tse(t)){let r=t.toLowerCase();return r==="default"?e:r==="local"||r==="system"?Td.instance:r==="utc"||r==="gmt"?oo.utcInstance:oo.parseSpecifier(r)||No.create(t)}else return il(t)?oo.instance(t):typeof t=="object"&&"offset"in t&&typeof t.offset=="function"?t:new d0(t)}var $se=()=>Date.now(),Nse="system",Dse=null,Lse=null,Ase=null,Mse=60,Ose,Ise=null,Ut=class{static get now(){return $se}static set now(e){$se=e}static set defaultZone(e){Nse=e}static get defaultZone(){return Js(Nse,Td.instance)}static get defaultLocale(){return Dse}static set defaultLocale(e){Dse=e}static get defaultNumberingSystem(){return Lse}static set defaultNumberingSystem(e){Lse=e}static get defaultOutputCalendar(){return Ase}static set defaultOutputCalendar(e){Ase=e}static get defaultWeekSettings(){return Ise}static set defaultWeekSettings(e){Ise=Qb(e)}static get twoDigitCutoffYear(){return Mse}static set twoDigitCutoffYear(e){Mse=e%100}static get throwOnInvalid(){return Ose}static set throwOnInvalid(e){Ose=e}static resetCaches(){tn.resetCache(),No.resetCache()}};var io=class{constructor(e,n){this.reason=e,this.explanation=n}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}};var kse=[0,31,59,90,120,151,181,212,243,273,304,334],Rse=[0,31,60,91,121,152,182,213,244,274,305,335];function ms(t,e){return new io("unit out of range",`you specified ${e} (of type ${typeof e}) as a ${t}, which is invalid`)}function C5(t,e,n){let r=new Date(Date.UTC(t,e-1,n));t<100&&t>=0&&r.setUTCFullYear(r.getUTCFullYear()-1900);let o=r.getUTCDay();return o===0?7:o}function Pse(t,e,n){return n+(Op(t)?Rse:kse)[e-1]}function Fse(t,e){let n=Op(t)?Rse:kse,r=n.findIndex(i=>i<e),o=e-n[r];return{month:r+1,day:o}}function S5(t,e){return(t-e+7)%7+1}function ex(t,e=4,n=1){let{year:r,month:o,day:i}=t,s=Pse(r,o,i),a=S5(C5(r,o,i),n),l=Math.floor((s-a+14-e)/7),c;return l<1?(c=r-1,l=Mp(c,e,n)):l>Mp(r,e,n)?(c=r+1,l=1):c=r,{weekYear:c,weekNumber:l,weekday:a,...nx(t)}}function wI(t,e=4,n=1){let{weekYear:r,weekNumber:o,weekday:i}=t,s=S5(C5(r,1,e),n),a=Nd(r),l=o*7+i-s-7+e,c;l<1?(c=r-1,l+=Nd(c)):l>a?(c=r+1,l-=Nd(r)):c=r;let{month:u,day:d}=Fse(c,l);return{year:c,month:u,day:d,...nx(t)}}function w5(t){let{year:e,month:n,day:r}=t,o=Pse(e,n,r);return{year:e,ordinal:o,...nx(t)}}function EI(t){let{year:e,ordinal:n}=t,{month:r,day:o}=Fse(e,n);return{year:e,month:r,day:o,...nx(t)}}function _I(t,e){if(!He(t.localWeekday)||!He(t.localWeekNumber)||!He(t.localWeekYear)){if(!He(t.weekday)||!He(t.weekNumber)||!He(t.weekYear))throw new Ys("Cannot mix locale-based week fields with ISO-based week fields");return He(t.localWeekday)||(t.weekday=t.localWeekday),He(t.localWeekNumber)||(t.weekNumber=t.localWeekNumber),He(t.localWeekYear)||(t.weekYear=t.localWeekYear),delete t.localWeekday,delete t.localWeekNumber,delete t.localWeekYear,{minDaysInFirstWeek:e.getMinDaysInFirstWeek(),startOfWeek:e.getStartOfWeek()}}else return{minDaysInFirstWeek:4,startOfWeek:1}}function Bse(t,e=4,n=1){let r=tx(t.weekYear),o=ji(t.weekNumber,1,Mp(t.weekYear,e,n)),i=ji(t.weekday,1,7);return r?o?i?!1:ms("weekday",t.weekday):ms("week",t.weekNumber):ms("weekYear",t.weekYear)}function zse(t){let e=tx(t.year),n=ji(t.ordinal,1,Nd(t.year));return e?n?!1:ms("ordinal",t.ordinal):ms("year",t.year)}function TI(t){let e=tx(t.year),n=ji(t.month,1,12),r=ji(t.day,1,f0(t.year,t.month));return e?n?r?!1:ms("day",t.day):ms("month",t.month):ms("year",t.year)}function $I(t){let{hour:e,minute:n,second:r,millisecond:o}=t,i=ji(e,0,23)||e===24&&n===0&&r===0&&o===0,s=ji(n,0,59),a=ji(r,0,59),l=ji(o,0,999);return i?s?a?l?!1:ms("millisecond",o):ms("second",r):ms("minute",n):ms("hour",e)}function He(t){return typeof t>"u"}function il(t){return typeof t=="number"}function tx(t){return typeof t=="number"&&t%1===0}function Tse(t){return typeof t=="string"}function Vse(t){return Object.prototype.toString.call(t)==="[object Date]"}function b5(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}function x5(){try{return typeof Intl<"u"&&!!Intl.Locale&&("weekInfo"in Intl.Locale.prototype||"getWeekInfo"in Intl.Locale.prototype)}catch{return!1}}function Use(t){return Array.isArray(t)?t:[t]}function NI(t,e,n){if(t.length!==0)return t.reduce((r,o)=>{let i=[e(o),o];return r&&n(r[0],i[0])===r[0]?r:i},null)[1]}function Hse(t,e){return e.reduce((n,r)=>(n[r]=t[r],n),{})}function Dd(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function Qb(t){if(t==null)return null;if(typeof t!="object")throw new br("Week settings must be an object");if(!ji(t.firstDay,1,7)||!ji(t.minimalDays,1,7)||!Array.isArray(t.weekend)||t.weekend.some(e=>!ji(e,1,7)))throw new br("Invalid week settings");return{firstDay:t.firstDay,minimalDays:t.minimalDays,weekend:Array.from(t.weekend)}}function ji(t,e,n){return tx(t)&&t>=e&&t<=n}function NAe(t,e){return t-e*Math.floor(t/e)}function Hn(t,e=2){let n=t<0,r;return n?r="-"+(""+-t).padStart(e,"0"):r=(""+t).padStart(e,"0"),r}function Ec(t){if(!(He(t)||t===null||t===""))return parseInt(t,10)}function Ld(t){if(!(He(t)||t===null||t===""))return parseFloat(t)}function rx(t){if(!(He(t)||t===null||t==="")){let e=parseFloat("0."+t)*1e3;return Math.floor(e)}}function u0(t,e,n=!1){let r=10**e;return(n?Math.trunc:Math.round)(t*r)/r}function Op(t){return t%4===0&&(t%100!==0||t%400===0)}function Nd(t){return Op(t)?366:365}function f0(t,e){let n=NAe(e-1,12)+1,r=t+(e-n)/12;return n===2?Op(r)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][n-1]}function c0(t){let e=Date.UTC(t.year,t.month-1,t.day,t.hour,t.minute,t.second,t.millisecond);return t.year<100&&t.year>=0&&(e=new Date(e),e.setUTCFullYear(t.year,t.month-1,t.day)),+e}function jse(t,e,n){return-S5(C5(t,1,e),n)+e-1}function Mp(t,e=4,n=1){let r=jse(t,e,n),o=jse(t+1,e,n);return(Nd(t)-r+o)/7}function ox(t){return t>99?t:t>Ut.twoDigitCutoffYear?1900+t:2e3+t}function g5(t,e,n,r=null){let o=new Date(t),i={hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"};r&&(i.timeZone=r);let s={timeZoneName:e,...i},a=new Intl.DateTimeFormat(n,s).formatToParts(o).find(l=>l.type.toLowerCase()==="timezonename");return a?a.value:null}function Ap(t,e){let n=parseInt(t,10);Number.isNaN(n)&&(n=0);let r=parseInt(e,10)||0,o=n<0||Object.is(n,-0)?-r:r;return n*60+o}function DI(t){let e=Number(t);if(typeof t=="boolean"||t===""||Number.isNaN(e))throw new br(`Invalid unit value ${t}`);return e}function p0(t,e){let n={};for(let r in t)if(Dd(t,r)){let o=t[r];if(o==null)continue;n[e(r)]=DI(o)}return n}function $d(t,e){let n=Math.trunc(Math.abs(t/60)),r=Math.trunc(Math.abs(t%60)),o=t>=0?"+":"-";switch(e){case"short":return`${o}${Hn(n,2)}:${Hn(r,2)}`;case"narrow":return`${o}${n}${r>0?`:${r}`:""}`;case"techie":return`${o}${Hn(n,2)}${Hn(r,2)}`;default:throw new RangeError(`Value format ${e} is out of range for property format`)}}function nx(t){return Hse(t,["hour","minute","second","millisecond"])}var DAe=["January","February","March","April","May","June","July","August","September","October","November","December"],LI=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],LAe=["J","F","M","A","M","J","J","A","S","O","N","D"];function vI(t){switch(t){case"narrow":return[...LAe];case"short":return[...LI];case"long":return[...DAe];case"numeric":return["1","2","3","4","5","6","7","8","9","10","11","12"];case"2-digit":return["01","02","03","04","05","06","07","08","09","10","11","12"];default:return null}}var AI=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],MI=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],AAe=["M","T","W","T","F","S","S"];function yI(t){switch(t){case"narrow":return[...AAe];case"short":return[...MI];case"long":return[...AI];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}var bI=["AM","PM"],MAe=["Before Christ","Anno Domini"],OAe=["BC","AD"],IAe=["B","A"];function xI(t){switch(t){case"narrow":return[...IAe];case"short":return[...OAe];case"long":return[...MAe];default:return null}}function Kse(t){return bI[t.hour<12?0:1]}function Wse(t,e){return yI(e)[t.weekday-1]}function Gse(t,e){return vI(e)[t.month-1]}function Yse(t,e){return xI(e)[t.year<0?0:1]}function _se(t,e,n="always",r=!1){let o={years:["year","yr."],quarters:["quarter","qtr."],months:["month","mo."],weeks:["week","wk."],days:["day","day","days"],hours:["hour","hr."],minutes:["minute","min."],seconds:["second","sec."]},i=["hours","minutes","seconds"].indexOf(t)===-1;if(n==="auto"&&i){let d=t==="days";switch(e){case 1:return d?"tomorrow":`next ${o[t][0]}`;case-1:return d?"yesterday":`last ${o[t][0]}`;case 0:return d?"today":`this ${o[t][0]}`;default:}}let s=Object.is(e,-0)||e<0,a=Math.abs(e),l=a===1,c=o[t],u=r?l?c[1]:c[2]||c[1]:l?o[t][0]:t;return s?`${a} ${u} ago`:`in ${a} ${u}`}function Zse(t,e){let n="";for(let r of t)r.literal?n+=r.val:n+=e(r.val);return n}var kAe={D:_d,DD:Ob,DDD:Ib,DDDD:kb,t:Rb,tt:Pb,ttt:Fb,tttt:Bb,T:zb,TT:jb,TTT:Vb,TTTT:Ub,f:Hb,ff:Wb,fff:Yb,ffff:qb,F:Kb,FF:Gb,FFF:Zb,FFFF:Jb},so=class t{static create(e,n={}){return new t(e,n)}static parseFormat(e){let n=null,r="",o=!1,i=[];for(let s=0;s<e.length;s++){let a=e.charAt(s);a==="'"?(r.length>0&&i.push({literal:o||/^\s+$/.test(r),val:r}),n=null,r="",o=!o):o||a===n?r+=a:(r.length>0&&i.push({literal:/^\s+$/.test(r),val:r}),r=a,n=a)}return r.length>0&&i.push({literal:o||/^\s+$/.test(r),val:r}),i}static macroTokenToFormatOpts(e){return kAe[e]}constructor(e,n){this.opts=n,this.loc=e,this.systemLoc=null}formatWithSystemDefault(e,n){return this.systemLoc===null&&(this.systemLoc=this.loc.redefaultToSystem()),this.systemLoc.dtFormatter(e,{...this.opts,...n}).format()}dtFormatter(e,n={}){return this.loc.dtFormatter(e,{...this.opts,...n})}formatDateTime(e,n){return this.dtFormatter(e,n).format()}formatDateTimeParts(e,n){return this.dtFormatter(e,n).formatToParts()}formatInterval(e,n){return this.dtFormatter(e.start,n).dtf.formatRange(e.start.toJSDate(),e.end.toJSDate())}resolvedOptions(e,n){return this.dtFormatter(e,n).resolvedOptions()}num(e,n=0){if(this.opts.forceSimple)return Hn(e,n);let r={...this.opts};return n>0&&(r.padTo=n),this.loc.numberFormatter(r).format(e)}formatDateTimeFromString(e,n){let r=this.loc.listingMode()==="en",o=this.loc.outputCalendar&&this.loc.outputCalendar!=="gregory",i=(p,m)=>this.loc.extract(e,p,m),s=p=>e.isOffsetFixed&&e.offset===0&&p.allowZ?"Z":e.isValid?e.zone.formatOffset(e.ts,p.format):"",a=()=>r?Kse(e):i({hour:"numeric",hourCycle:"h12"},"dayperiod"),l=(p,m)=>r?Gse(e,p):i(m?{month:p}:{month:p,day:"numeric"},"month"),c=(p,m)=>r?Wse(e,p):i(m?{weekday:p}:{weekday:p,month:"long",day:"numeric"},"weekday"),u=p=>{let m=t.macroTokenToFormatOpts(p);return m?this.formatWithSystemDefault(e,m):p},d=p=>r?Yse(e,p):i({era:p},"era"),f=p=>{switch(p){case"S":return this.num(e.millisecond);case"u":case"SSS":return this.num(e.millisecond,3);case"s":return this.num(e.second);case"ss":return this.num(e.second,2);case"uu":return this.num(Math.floor(e.millisecond/10),2);case"uuu":return this.num(Math.floor(e.millisecond/100));case"m":return this.num(e.minute);case"mm":return this.num(e.minute,2);case"h":return this.num(e.hour%12===0?12:e.hour%12);case"hh":return this.num(e.hour%12===0?12:e.hour%12,2);case"H":return this.num(e.hour);case"HH":return this.num(e.hour,2);case"Z":return s({format:"narrow",allowZ:this.opts.allowZ});case"ZZ":return s({format:"short",allowZ:this.opts.allowZ});case"ZZZ":return s({format:"techie",allowZ:this.opts.allowZ});case"ZZZZ":return e.zone.offsetName(e.ts,{format:"short",locale:this.loc.locale});case"ZZZZZ":return e.zone.offsetName(e.ts,{format:"long",locale:this.loc.locale});case"z":return e.zoneName;case"a":return a();case"d":return o?i({day:"numeric"},"day"):this.num(e.day);case"dd":return o?i({day:"2-digit"},"day"):this.num(e.day,2);case"c":return this.num(e.weekday);case"ccc":return c("short",!0);case"cccc":return c("long",!0);case"ccccc":return c("narrow",!0);case"E":return this.num(e.weekday);case"EEE":return c("short",!1);case"EEEE":return c("long",!1);case"EEEEE":return c("narrow",!1);case"L":return o?i({month:"numeric",day:"numeric"},"month"):this.num(e.month);case"LL":return o?i({month:"2-digit",day:"numeric"},"month"):this.num(e.month,2);case"LLL":return l("short",!0);case"LLLL":return l("long",!0);case"LLLLL":return l("narrow",!0);case"M":return o?i({month:"numeric"},"month"):this.num(e.month);case"MM":return o?i({month:"2-digit"},"month"):this.num(e.month,2);case"MMM":return l("short",!1);case"MMMM":return l("long",!1);case"MMMMM":return l("narrow",!1);case"y":return o?i({year:"numeric"},"year"):this.num(e.year);case"yy":return o?i({year:"2-digit"},"year"):this.num(e.year.toString().slice(-2),2);case"yyyy":return o?i({year:"numeric"},"year"):this.num(e.year,4);case"yyyyyy":return o?i({year:"numeric"},"year"):this.num(e.year,6);case"G":return d("short");case"GG":return d("long");case"GGGGG":return d("narrow");case"kk":return this.num(e.weekYear.toString().slice(-2),2);case"kkkk":return this.num(e.weekYear,4);case"W":return this.num(e.weekNumber);case"WW":return this.num(e.weekNumber,2);case"n":return this.num(e.localWeekNumber);case"nn":return this.num(e.localWeekNumber,2);case"ii":return this.num(e.localWeekYear.toString().slice(-2),2);case"iiii":return this.num(e.localWeekYear,4);case"o":return this.num(e.ordinal);case"ooo":return this.num(e.ordinal,3);case"q":return this.num(e.quarter);case"qq":return this.num(e.quarter,2);case"X":return this.num(Math.floor(e.ts/1e3));case"x":return this.num(e.ts);default:return u(p)}};return Zse(t.parseFormat(n),f)}formatDurationFromString(e,n){let r=l=>{switch(l[0]){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":return"hour";case"d":return"day";case"w":return"week";case"M":return"month";case"y":return"year";default:return null}},o=l=>c=>{let u=r(c);return u?this.num(l.get(u),c.length):c},i=t.parseFormat(n),s=i.reduce((l,{literal:c,val:u})=>c?l:l.concat(u),[]),a=e.shiftTo(...s.map(r).filter(l=>l));return Zse(i,o(a))}};var Jse=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;function g0(...t){let e=t.reduce((n,r)=>n+r.source,"");return RegExp(`^${e}$`)}function h0(...t){return e=>t.reduce(([n,r,o],i)=>{let[s,a,l]=i(e,o);return[{...n,...s},a||r,l]},[{},null,1]).slice(0,2)}function v0(t,...e){if(t==null)return[null,null];for(let[n,r]of e){let o=n.exec(t);if(o)return r(o)}return[null,null]}function Xse(...t){return(e,n)=>{let r={},o;for(o=0;o<t.length;o++)r[t[o]]=Ec(e[n+o]);return[r,null,n+o]}}var Qse=/(?:(Z)|([+-]\d\d)(?::?(\d\d))?)/,RAe=`(?:${Qse.source}?(?:\\[(${Jse.source})\\])?)?`,OI=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,eae=RegExp(`${OI.source}${RAe}`),II=RegExp(`(?:T${eae.source})?`),PAe=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,FAe=/(\d{4})-?W(\d\d)(?:-?(\d))?/,BAe=/(\d{4})-?(\d{3})/,zAe=Xse("weekYear","weekNumber","weekDay"),jAe=Xse("year","ordinal"),VAe=/(\d{4})-(\d\d)-(\d\d)/,tae=RegExp(`${OI.source} ?(?:${Qse.source}|(${Jse.source}))?`),UAe=RegExp(`(?: ${tae.source})?`);function m0(t,e,n){let r=t[e];return He(r)?n:Ec(r)}function HAe(t,e){return[{year:m0(t,e),month:m0(t,e+1,1),day:m0(t,e+2,1)},null,e+3]}function y0(t,e){return[{hours:m0(t,e,0),minutes:m0(t,e+1,0),seconds:m0(t,e+2,0),milliseconds:rx(t[e+3])},null,e+4]}function ix(t,e){let n=!t[e]&&!t[e+1],r=Ap(t[e+1],t[e+2]),o=n?null:oo.instance(r);return[{},o,e+3]}function sx(t,e){let n=t[e]?No.create(t[e]):null;return[{},n,e+1]}var KAe=RegExp(`^T?${OI.source}$`),WAe=/^-?P(?:(?:(-?\d{1,20}(?:\.\d{1,20})?)Y)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20}(?:\.\d{1,20})?)W)?(?:(-?\d{1,20}(?:\.\d{1,20})?)D)?(?:T(?:(-?\d{1,20}(?:\.\d{1,20})?)H)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20})(?:[.,](-?\d{1,20}))?S)?)?)$/;function GAe(t){let[e,n,r,o,i,s,a,l,c]=t,u=e[0]==="-",d=l&&l[0]==="-",f=(p,m=!1)=>p!==void 0&&(m||p&&u)?-p:p;return[{years:f(Ld(n)),months:f(Ld(r)),weeks:f(Ld(o)),days:f(Ld(i)),hours:f(Ld(s)),minutes:f(Ld(a)),seconds:f(Ld(l),l==="-0"),milliseconds:f(rx(c),d)}]}var YAe={GMT:0,EDT:-4*60,EST:-5*60,CDT:-5*60,CST:-6*60,MDT:-6*60,MST:-7*60,PDT:-7*60,PST:-8*60};function kI(t,e,n,r,o,i,s){let a={year:e.length===2?ox(Ec(e)):Ec(e),month:LI.indexOf(n)+1,day:Ec(r),hour:Ec(o),minute:Ec(i)};return s&&(a.second=Ec(s)),t&&(a.weekday=t.length>3?AI.indexOf(t)+1:MI.indexOf(t)+1),a}var ZAe=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/;function qAe(t){let[,e,n,r,o,i,s,a,l,c,u,d]=t,f=kI(e,o,r,n,i,s,a),p;return l?p=YAe[l]:c?p=0:p=Ap(u,d),[f,new oo(p)]}function JAe(t){return t.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}var XAe=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/,QAe=/^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/,eMe=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/;function qse(t){let[,e,n,r,o,i,s,a]=t;return[kI(e,o,r,n,i,s,a),oo.utcInstance]}function tMe(t){let[,e,n,r,o,i,s,a]=t;return[kI(e,a,n,r,o,i,s),oo.utcInstance]}var nMe=g0(PAe,II),rMe=g0(FAe,II),oMe=g0(BAe,II),iMe=g0(eae),nae=h0(HAe,y0,ix,sx),sMe=h0(zAe,y0,ix,sx),aMe=h0(jAe,y0,ix,sx),lMe=h0(y0,ix,sx);function rae(t){return v0(t,[nMe,nae],[rMe,sMe],[oMe,aMe],[iMe,lMe])}function oae(t){return v0(JAe(t),[ZAe,qAe])}function iae(t){return v0(t,[XAe,qse],[QAe,qse],[eMe,tMe])}function sae(t){return v0(t,[WAe,GAe])}var cMe=h0(y0);function aae(t){return v0(t,[KAe,cMe])}var uMe=g0(VAe,UAe),dMe=g0(tae),fMe=h0(y0,ix,sx);function lae(t){return v0(t,[uMe,nae],[dMe,fMe])}var cae="Invalid Duration",dae={weeks:{days:7,hours:7*24,minutes:7*24*60,seconds:7*24*60*60,milliseconds:7*24*60*60*1e3},days:{hours:24,minutes:24*60,seconds:24*60*60,milliseconds:24*60*60*1e3},hours:{minutes:60,seconds:60*60,milliseconds:60*60*1e3},minutes:{seconds:60,milliseconds:60*1e3},seconds:{milliseconds:1e3}},pMe={years:{quarters:4,months:12,weeks:52,days:365,hours:365*24,minutes:365*24*60,seconds:365*24*60*60,milliseconds:365*24*60*60*1e3},quarters:{months:3,weeks:13,days:91,hours:91*24,minutes:91*24*60,seconds:91*24*60*60,milliseconds:91*24*60*60*1e3},months:{weeks:4,days:30,hours:30*24,minutes:30*24*60,seconds:30*24*60*60,milliseconds:30*24*60*60*1e3},...dae},gs=146097/400,b0=146097/4800,mMe={years:{quarters:4,months:12,weeks:gs/7,days:gs,hours:gs*24,minutes:gs*24*60,seconds:gs*24*60*60,milliseconds:gs*24*60*60*1e3},quarters:{months:3,weeks:gs/28,days:gs/4,hours:gs*24/4,minutes:gs*24*60/4,seconds:gs*24*60*60/4,milliseconds:gs*24*60*60*1e3/4},months:{weeks:b0/7,days:b0,hours:b0*24,minutes:b0*24*60,seconds:b0*24*60*60,milliseconds:b0*24*60*60*1e3},...dae},Ip=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],gMe=Ip.slice(0).reverse();function Ad(t,e,n=!1){let r={values:n?e.values:{...t.values,...e.values||{}},loc:t.loc.clone(e.loc),conversionAccuracy:e.conversionAccuracy||t.conversionAccuracy,matrix:e.matrix||t.matrix};return new Kn(r)}function fae(t,e){let n=e.milliseconds??0;for(let r of gMe.slice(1))e[r]&&(n+=e[r]*t[r].milliseconds);return n}function uae(t,e){let n=fae(t,e)<0?-1:1;Ip.reduceRight((r,o)=>{if(He(e[o]))return r;if(r){let i=e[r]*n,s=t[o][r],a=Math.floor(i/s);e[o]+=a*n,e[r]-=a*s*n}return o},null),Ip.reduce((r,o)=>{if(He(e[o]))return r;if(r){let i=e[r]%1;e[r]-=i,e[o]+=i*t[r][o]}return o},null)}function hMe(t){let e={};for(let[n,r]of Object.entries(t))r!==0&&(e[n]=r);return e}var Kn=class t{constructor(e){let n=e.conversionAccuracy==="longterm"||!1,r=n?mMe:pMe;e.matrix&&(r=e.matrix),this.values=e.values,this.loc=e.loc||tn.create(),this.conversionAccuracy=n?"longterm":"casual",this.invalid=e.invalid||null,this.matrix=r,this.isLuxonDuration=!0}static fromMillis(e,n){return t.fromObject({milliseconds:e},n)}static fromObject(e,n={}){if(e==null||typeof e!="object")throw new br(`Duration.fromObject: argument expected to be an object, got ${e===null?"null":typeof e}`);return new t({values:p0(e,t.normalizeUnit),loc:tn.fromObject(n),conversionAccuracy:n.conversionAccuracy,matrix:n.matrix})}static fromDurationLike(e){if(il(e))return t.fromMillis(e);if(t.isDuration(e))return e;if(typeof e=="object")return t.fromObject(e);throw new br(`Unknown duration argument ${e} of type ${typeof e}`)}static fromISO(e,n){let[r]=sae(e);return r?t.fromObject(r,n):t.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static fromISOTime(e,n){let[r]=aae(e);return r?t.fromObject(r,n):t.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static invalid(e,n=null){if(!e)throw new br("need to specify a reason the Duration is invalid");let r=e instanceof io?e:new io(e,n);if(Ut.throwOnInvalid)throw new p5(r);return new t({invalid:r})}static normalizeUnit(e){let n={year:"years",years:"years",quarter:"quarters",quarters:"quarters",month:"months",months:"months",week:"weeks",weeks:"weeks",day:"days",days:"days",hour:"hours",hours:"hours",minute:"minutes",minutes:"minutes",second:"seconds",seconds:"seconds",millisecond:"milliseconds",milliseconds:"milliseconds"}[e&&e.toLowerCase()];if(!n)throw new l0(e);return n}static isDuration(e){return e&&e.isLuxonDuration||!1}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}toFormat(e,n={}){let r={...n,floor:n.round!==!1&&n.floor!==!1};return this.isValid?so.create(this.loc,r).formatDurationFromString(this,e):cae}toHuman(e={}){if(!this.isValid)return cae;let n=Ip.map(r=>{let o=this.values[r];return He(o)?null:this.loc.numberFormatter({style:"unit",unitDisplay:"long",...e,unit:r.slice(0,-1)}).format(o)}).filter(r=>r);return this.loc.listFormatter({type:"conjunction",style:e.listStyle||"narrow",...e}).format(n)}toObject(){return this.isValid?{...this.values}:{}}toISO(){if(!this.isValid)return null;let e="P";return this.years!==0&&(e+=this.years+"Y"),(this.months!==0||this.quarters!==0)&&(e+=this.months+this.quarters*3+"M"),this.weeks!==0&&(e+=this.weeks+"W"),this.days!==0&&(e+=this.days+"D"),(this.hours!==0||this.minutes!==0||this.seconds!==0||this.milliseconds!==0)&&(e+="T"),this.hours!==0&&(e+=this.hours+"H"),this.minutes!==0&&(e+=this.minutes+"M"),(this.seconds!==0||this.milliseconds!==0)&&(e+=u0(this.seconds+this.milliseconds/1e3,3)+"S"),e==="P"&&(e+="T0S"),e}toISOTime(e={}){if(!this.isValid)return null;let n=this.toMillis();return n<0||n>=864e5?null:(e={suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:"extended",...e,includeOffset:!1},St.fromMillis(n,{zone:"UTC"}).toISOTime(e))}toJSON(){return this.toISO()}toString(){return this.toISO()}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`Duration { values: ${JSON.stringify(this.values)} }`:`Duration { Invalid, reason: ${this.invalidReason} }`}toMillis(){return this.isValid?fae(this.matrix,this.values):NaN}valueOf(){return this.toMillis()}plus(e){if(!this.isValid)return this;let n=t.fromDurationLike(e),r={};for(let o of Ip)(Dd(n.values,o)||Dd(this.values,o))&&(r[o]=n.get(o)+this.get(o));return Ad(this,{values:r},!0)}minus(e){if(!this.isValid)return this;let n=t.fromDurationLike(e);return this.plus(n.negate())}mapUnits(e){if(!this.isValid)return this;let n={};for(let r of Object.keys(this.values))n[r]=DI(e(this.values[r],r));return Ad(this,{values:n},!0)}get(e){return this[t.normalizeUnit(e)]}set(e){if(!this.isValid)return this;let n={...this.values,...p0(e,t.normalizeUnit)};return Ad(this,{values:n})}reconfigure({locale:e,numberingSystem:n,conversionAccuracy:r,matrix:o}={}){let s={loc:this.loc.clone({locale:e,numberingSystem:n}),matrix:o,conversionAccuracy:r};return Ad(this,s)}as(e){return this.isValid?this.shiftTo(e).get(e):NaN}normalize(){if(!this.isValid)return this;let e=this.toObject();return uae(this.matrix,e),Ad(this,{values:e},!0)}rescale(){if(!this.isValid)return this;let e=hMe(this.normalize().shiftToAll().toObject());return Ad(this,{values:e},!0)}shiftTo(...e){if(!this.isValid)return this;if(e.length===0)return this;e=e.map(s=>t.normalizeUnit(s));let n={},r={},o=this.toObject(),i;for(let s of Ip)if(e.indexOf(s)>=0){i=s;let a=0;for(let c in r)a+=this.matrix[c][s]*r[c],r[c]=0;il(o[s])&&(a+=o[s]);let l=Math.trunc(a);n[s]=l,r[s]=(a*1e3-l*1e3)/1e3}else il(o[s])&&(r[s]=o[s]);for(let s in r)r[s]!==0&&(n[i]+=s===i?r[s]:r[s]/this.matrix[i][s]);return uae(this.matrix,n),Ad(this,{values:n},!0)}shiftToAll(){return this.isValid?this.shiftTo("years","months","weeks","days","hours","minutes","seconds","milliseconds"):this}negate(){if(!this.isValid)return this;let e={};for(let n of Object.keys(this.values))e[n]=this.values[n]===0?0:-this.values[n];return Ad(this,{values:e},!0)}get years(){return this.isValid?this.values.years||0:NaN}get quarters(){return this.isValid?this.values.quarters||0:NaN}get months(){return this.isValid?this.values.months||0:NaN}get weeks(){return this.isValid?this.values.weeks||0:NaN}get days(){return this.isValid?this.values.days||0:NaN}get hours(){return this.isValid?this.values.hours||0:NaN}get minutes(){return this.isValid?this.values.minutes||0:NaN}get seconds(){return this.isValid?this.values.seconds||0:NaN}get milliseconds(){return this.isValid?this.values.milliseconds||0:NaN}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}equals(e){if(!this.isValid||!e.isValid||!this.loc.equals(e.loc))return!1;function n(r,o){return r===void 0||r===0?o===void 0||o===0:r===o}for(let r of Ip)if(!n(this.values[r],e.values[r]))return!1;return!0}};var x0="Invalid Interval";function vMe(t,e){return!t||!t.isValid?_c.invalid("missing or invalid start"):!e||!e.isValid?_c.invalid("missing or invalid end"):e<t?_c.invalid("end before start",`The end of an interval must be after its start, but you had start=${t.toISO()} and end=${e.toISO()}`):null}var _c=class t{constructor(e){this.s=e.start,this.e=e.end,this.invalid=e.invalid||null,this.isLuxonInterval=!0}static invalid(e,n=null){if(!e)throw new br("need to specify a reason the Interval is invalid");let r=e instanceof io?e:new io(e,n);if(Ut.throwOnInvalid)throw new f5(r);return new t({invalid:r})}static fromDateTimes(e,n){let r=C0(e),o=C0(n),i=vMe(r,o);return i??new t({start:r,end:o})}static after(e,n){let r=Kn.fromDurationLike(n),o=C0(e);return t.fromDateTimes(o,o.plus(r))}static before(e,n){let r=Kn.fromDurationLike(n),o=C0(e);return t.fromDateTimes(o.minus(r),o)}static fromISO(e,n){let[r,o]=(e||"").split("/",2);if(r&&o){let i,s;try{i=St.fromISO(r,n),s=i.isValid}catch{s=!1}let a,l;try{a=St.fromISO(o,n),l=a.isValid}catch{l=!1}if(s&&l)return t.fromDateTimes(i,a);if(s){let c=Kn.fromISO(o,n);if(c.isValid)return t.after(i,c)}else if(l){let c=Kn.fromISO(r,n);if(c.isValid)return t.before(a,c)}}return t.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static isInterval(e){return e&&e.isLuxonInterval||!1}get start(){return this.isValid?this.s:null}get end(){return this.isValid?this.e:null}get isValid(){return this.invalidReason===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}length(e="milliseconds"){return this.isValid?this.toDuration(e).get(e):NaN}count(e="milliseconds",n){if(!this.isValid)return NaN;let r=this.start.startOf(e,n),o;return n?.useLocaleWeeks?o=this.end.reconfigure({locale:r.locale}):o=this.end,o=o.startOf(e,n),Math.floor(o.diff(r,e).get(e))+(o.valueOf()!==this.end.valueOf())}hasSame(e){return this.isValid?this.isEmpty()||this.e.minus(1).hasSame(this.s,e):!1}isEmpty(){return this.s.valueOf()===this.e.valueOf()}isAfter(e){return this.isValid?this.s>e:!1}isBefore(e){return this.isValid?this.e<=e:!1}contains(e){return this.isValid?this.s<=e&&this.e>e:!1}set({start:e,end:n}={}){return this.isValid?t.fromDateTimes(e||this.s,n||this.e):this}splitAt(...e){if(!this.isValid)return[];let n=e.map(C0).filter(s=>this.contains(s)).sort((s,a)=>s.toMillis()-a.toMillis()),r=[],{s:o}=this,i=0;for(;o<this.e;){let s=n[i]||this.e,a=+s>+this.e?this.e:s;r.push(t.fromDateTimes(o,a)),o=a,i+=1}return r}splitBy(e){let n=Kn.fromDurationLike(e);if(!this.isValid||!n.isValid||n.as("milliseconds")===0)return[];let{s:r}=this,o=1,i,s=[];for(;r<this.e;){let a=this.start.plus(n.mapUnits(l=>l*o));i=+a>+this.e?this.e:a,s.push(t.fromDateTimes(r,i)),r=i,o+=1}return s}divideEqually(e){return this.isValid?this.splitBy(this.length()/e).slice(0,e):[]}overlaps(e){return this.e>e.s&&this.s<e.e}abutsStart(e){return this.isValid?+this.e==+e.s:!1}abutsEnd(e){return this.isValid?+e.e==+this.s:!1}engulfs(e){return this.isValid?this.s<=e.s&&this.e>=e.e:!1}equals(e){return!this.isValid||!e.isValid?!1:this.s.equals(e.s)&&this.e.equals(e.e)}intersection(e){if(!this.isValid)return this;let n=this.s>e.s?this.s:e.s,r=this.e<e.e?this.e:e.e;return n>=r?null:t.fromDateTimes(n,r)}union(e){if(!this.isValid)return this;let n=this.s<e.s?this.s:e.s,r=this.e>e.e?this.e:e.e;return t.fromDateTimes(n,r)}static merge(e){let[n,r]=e.sort((o,i)=>o.s-i.s).reduce(([o,i],s)=>i?i.overlaps(s)||i.abutsStart(s)?[o,i.union(s)]:[o.concat([i]),s]:[o,s],[[],null]);return r&&n.push(r),n}static xor(e){let n=null,r=0,o=[],i=e.map(l=>[{time:l.s,type:"s"},{time:l.e,type:"e"}]),s=Array.prototype.concat(...i),a=s.sort((l,c)=>l.time-c.time);for(let l of a)r+=l.type==="s"?1:-1,r===1?n=l.time:(n&&+n!=+l.time&&o.push(t.fromDateTimes(n,l.time)),n=null);return t.merge(o)}difference(...e){return t.xor([this].concat(e)).map(n=>this.intersection(n)).filter(n=>n&&!n.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} \u2013 ${this.e.toISO()})`:x0}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`Interval { start: ${this.s.toISO()}, end: ${this.e.toISO()} }`:`Interval { Invalid, reason: ${this.invalidReason} }`}toLocaleString(e=_d,n={}){return this.isValid?so.create(this.s.loc.clone(n),e).formatInterval(this):x0}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:x0}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:x0}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:x0}toFormat(e,{separator:n=" \u2013 "}={}){return this.isValid?`${this.s.toFormat(e)}${n}${this.e.toFormat(e)}`:x0}toDuration(e,n){return this.isValid?this.e.diff(this.s,e,n):Kn.invalid(this.invalidReason)}mapEndpoints(e){return t.fromDateTimes(e(this.s),e(this.e))}};var Tc=class{static hasDST(e=Ut.defaultZone){let n=St.now().setZone(e).set({month:12});return!e.isUniversal&&n.offset!==n.set({month:6}).offset}static isValidIANAZone(e){return No.isValidZone(e)}static normalizeZone(e){return Js(e,Ut.defaultZone)}static getStartOfWeek({locale:e=null,locObj:n=null}={}){return(n||tn.create(e)).getStartOfWeek()}static getMinimumDaysInFirstWeek({locale:e=null,locObj:n=null}={}){return(n||tn.create(e)).getMinDaysInFirstWeek()}static getWeekendWeekdays({locale:e=null,locObj:n=null}={}){return(n||tn.create(e)).getWeekendDays().slice()}static months(e="long",{locale:n=null,numberingSystem:r=null,locObj:o=null,outputCalendar:i="gregory"}={}){return(o||tn.create(n,r,i)).months(e)}static monthsFormat(e="long",{locale:n=null,numberingSystem:r=null,locObj:o=null,outputCalendar:i="gregory"}={}){return(o||tn.create(n,r,i)).months(e,!0)}static weekdays(e="long",{locale:n=null,numberingSystem:r=null,locObj:o=null}={}){return(o||tn.create(n,r,null)).weekdays(e)}static weekdaysFormat(e="long",{locale:n=null,numberingSystem:r=null,locObj:o=null}={}){return(o||tn.create(n,r,null)).weekdays(e,!0)}static meridiems({locale:e=null}={}){return tn.create(e).meridiems()}static eras(e="short",{locale:n=null}={}){return tn.create(n,null,"gregory").eras(e)}static features(){return{relative:b5(),localeWeek:x5()}}};function pae(t,e){let n=o=>o.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),r=n(e)-n(t);return Math.floor(Kn.fromMillis(r).as("days"))}function yMe(t,e,n){let r=[["years",(l,c)=>c.year-l.year],["quarters",(l,c)=>c.quarter-l.quarter+(c.year-l.year)*4],["months",(l,c)=>c.month-l.month+(c.year-l.year)*12],["weeks",(l,c)=>{let u=pae(l,c);return(u-u%7)/7}],["days",pae]],o={},i=t,s,a;for(let[l,c]of r)n.indexOf(l)>=0&&(s=l,o[l]=c(t,e),a=i.plus(o),a>e?(o[l]--,t=i.plus(o),t>e&&(a=t,o[l]--,t=i.plus(o))):t=a);return[t,o,a,s]}function mae(t,e,n,r){let[o,i,s,a]=yMe(t,e,n),l=e-o,c=n.filter(d=>["hours","minutes","seconds","milliseconds"].indexOf(d)>=0);c.length===0&&(s<e&&(s=o.plus({[a]:1})),s!==o&&(i[a]=(i[a]||0)+l/(s-o)));let u=Kn.fromObject(i,r);return c.length>0?Kn.fromMillis(l,r).shiftTo(...c).plus(u):u}var RI={arab:"[\u0660-\u0669]",arabext:"[\u06F0-\u06F9]",bali:"[\u1B50-\u1B59]",beng:"[\u09E6-\u09EF]",deva:"[\u0966-\u096F]",fullwide:"[\uFF10-\uFF19]",gujr:"[\u0AE6-\u0AEF]",hanidec:"[\u3007|\u4E00|\u4E8C|\u4E09|\u56DB|\u4E94|\u516D|\u4E03|\u516B|\u4E5D]",khmr:"[\u17E0-\u17E9]",knda:"[\u0CE6-\u0CEF]",laoo:"[\u0ED0-\u0ED9]",limb:"[\u1946-\u194F]",mlym:"[\u0D66-\u0D6F]",mong:"[\u1810-\u1819]",mymr:"[\u1040-\u1049]",orya:"[\u0B66-\u0B6F]",tamldec:"[\u0BE6-\u0BEF]",telu:"[\u0C66-\u0C6F]",thai:"[\u0E50-\u0E59]",tibt:"[\u0F20-\u0F29]",latn:"\\d"},gae={arab:[1632,1641],arabext:[1776,1785],bali:[6992,7001],beng:[2534,2543],deva:[2406,2415],fullwide:[65296,65303],gujr:[2790,2799],khmr:[6112,6121],knda:[3302,3311],laoo:[3792,3801],limb:[6470,6479],mlym:[3430,3439],mong:[6160,6169],mymr:[4160,4169],orya:[2918,2927],tamldec:[3046,3055],telu:[3174,3183],thai:[3664,3673],tibt:[3872,3881]},bMe=RI.hanidec.replace(/[\[|\]]/g,"").split("");function hae(t){let e=parseInt(t,10);if(isNaN(e)){e="";for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);if(t[n].search(RI.hanidec)!==-1)e+=bMe.indexOf(t[n]);else for(let o in gae){let[i,s]=gae[o];r>=i&&r<=s&&(e+=r-i)}}return parseInt(e,10)}else return e}function hs({numberingSystem:t},e=""){return new RegExp(`${RI[t||"latn"]}${e}`)}var xMe="missing Intl.DateTimeFormat.formatToParts support";function Ht(t,e=n=>n){return{regex:t,deser:([n])=>e(hae(n))}}var CMe="\xA0",bae=`[ ${CMe}]`,xae=new RegExp(bae,"g");function SMe(t){return t.replace(/\./g,"\\.?").replace(xae,bae)}function vae(t){return t.replace(/\./g,"").replace(xae," ").toLowerCase()}function Xs(t,e){return t===null?null:{regex:RegExp(t.map(SMe).join("|")),deser:([n])=>t.findIndex(r=>vae(n)===vae(r))+e}}function yae(t,e){return{regex:t,deser:([,n,r])=>Ap(n,r),groups:e}}function E5(t){return{regex:t,deser:([e])=>e}}function wMe(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function EMe(t,e){let n=hs(e),r=hs(e,"{2}"),o=hs(e,"{3}"),i=hs(e,"{4}"),s=hs(e,"{6}"),a=hs(e,"{1,2}"),l=hs(e,"{1,3}"),c=hs(e,"{1,6}"),u=hs(e,"{1,9}"),d=hs(e,"{2,4}"),f=hs(e,"{4,6}"),p=h=>({regex:RegExp(wMe(h.val)),deser:([v])=>v,literal:!0}),g=(h=>{if(t.literal)return p(h);switch(h.val){case"G":return Xs(e.eras("short"),0);case"GG":return Xs(e.eras("long"),0);case"y":return Ht(c);case"yy":return Ht(d,ox);case"yyyy":return Ht(i);case"yyyyy":return Ht(f);case"yyyyyy":return Ht(s);case"M":return Ht(a);case"MM":return Ht(r);case"MMM":return Xs(e.months("short",!0),1);case"MMMM":return Xs(e.months("long",!0),1);case"L":return Ht(a);case"LL":return Ht(r);case"LLL":return Xs(e.months("short",!1),1);case"LLLL":return Xs(e.months("long",!1),1);case"d":return Ht(a);case"dd":return Ht(r);case"o":return Ht(l);case"ooo":return Ht(o);case"HH":return Ht(r);case"H":return Ht(a);case"hh":return Ht(r);case"h":return Ht(a);case"mm":return Ht(r);case"m":return Ht(a);case"q":return Ht(a);case"qq":return Ht(r);case"s":return Ht(a);case"ss":return Ht(r);case"S":return Ht(l);case"SSS":return Ht(o);case"u":return E5(u);case"uu":return E5(a);case"uuu":return Ht(n);case"a":return Xs(e.meridiems(),0);case"kkkk":return Ht(i);case"kk":return Ht(d,ox);case"W":return Ht(a);case"WW":return Ht(r);case"E":case"c":return Ht(n);case"EEE":return Xs(e.weekdays("short",!1),1);case"EEEE":return Xs(e.weekdays("long",!1),1);case"ccc":return Xs(e.weekdays("short",!0),1);case"cccc":return Xs(e.weekdays("long",!0),1);case"Z":case"ZZ":return yae(new RegExp(`([+-]${a.source})(?::(${r.source}))?`),2);case"ZZZ":return yae(new RegExp(`([+-]${a.source})(${r.source})?`),2);case"z":return E5(/[a-z_+-/]{1,256}?/i);case" ":return E5(/[^\S\n\r]/);default:return p(h)}})(t)||{invalidReason:xMe};return g.token=t,g}var _Me={year:{"2-digit":"yy",numeric:"yyyyy"},month:{numeric:"M","2-digit":"MM",short:"MMM",long:"MMMM"},day:{numeric:"d","2-digit":"dd"},weekday:{short:"EEE",long:"EEEE"},dayperiod:"a",dayPeriod:"a",hour12:{numeric:"h","2-digit":"hh"},hour24:{numeric:"H","2-digit":"HH"},minute:{numeric:"m","2-digit":"mm"},second:{numeric:"s","2-digit":"ss"},timeZoneName:{long:"ZZZZZ",short:"ZZZ"}};function TMe(t,e,n){let{type:r,value:o}=t;if(r==="literal"){let l=/^\s+$/.test(o);return{literal:!l,val:l?" ":o}}let i=e[r],s=r;r==="hour"&&(e.hour12!=null?s=e.hour12?"hour12":"hour24":e.hourCycle!=null?e.hourCycle==="h11"||e.hourCycle==="h12"?s="hour12":s="hour24":s=n.hour12?"hour12":"hour24");let a=_Me[s];if(typeof a=="object"&&(a=a[i]),a)return{literal:!1,val:a}}function $Me(t){return[`^${t.map(n=>n.regex).reduce((n,r)=>`${n}(${r.source})`,"")}$`,t]}function NMe(t,e,n){let r=t.match(e);if(r){let o={},i=1;for(let s in n)if(Dd(n,s)){let a=n[s],l=a.groups?a.groups+1:1;!a.literal&&a.token&&(o[a.token.val[0]]=a.deser(r.slice(i,i+l))),i+=l}return[r,o]}else return[r,{}]}function DMe(t){let e=i=>{switch(i){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":case"H":return"hour";case"d":return"day";case"o":return"ordinal";case"L":case"M":return"month";case"y":return"year";case"E":case"c":return"weekday";case"W":return"weekNumber";case"k":return"weekYear";case"q":return"quarter";default:return null}},n=null,r;return He(t.z)||(n=No.create(t.z)),He(t.Z)||(n||(n=new oo(t.Z)),r=t.Z),He(t.q)||(t.M=(t.q-1)*3+1),He(t.h)||(t.h<12&&t.a===1?t.h+=12:t.h===12&&t.a===0&&(t.h=0)),t.G===0&&t.y&&(t.y=-t.y),He(t.u)||(t.S=rx(t.u)),[Object.keys(t).reduce((i,s)=>{let a=e(s);return a&&(i[a]=t[s]),i},{}),n,r]}var PI=null;function LMe(){return PI||(PI=St.fromMillis(1555555555555)),PI}function AMe(t,e){if(t.literal)return t;let n=so.macroTokenToFormatOpts(t.val),r=zI(n,e);return r==null||r.includes(void 0)?t:r}function FI(t,e){return Array.prototype.concat(...t.map(n=>AMe(n,e)))}function BI(t,e,n){let r=FI(so.parseFormat(n),t),o=r.map(s=>EMe(s,t)),i=o.find(s=>s.invalidReason);if(i)return{input:e,tokens:r,invalidReason:i.invalidReason};{let[s,a]=$Me(o),l=RegExp(s,"i"),[c,u]=NMe(e,l,a),[d,f,p]=u?DMe(u):[null,null,void 0];if(Dd(u,"a")&&Dd(u,"H"))throw new Ys("Can't include meridiem when specifying 24-hour format");return{input:e,tokens:r,regex:l,rawMatches:c,matches:u,result:d,zone:f,specificOffset:p}}}function Cae(t,e,n){let{result:r,zone:o,specificOffset:i,invalidReason:s}=BI(t,e,n);return[r,o,i,s]}function zI(t,e){if(!t)return null;let r=so.create(e,t).dtFormatter(LMe()),o=r.formatToParts(),i=r.resolvedOptions();return o.map(s=>TMe(s,t,i))}var jI="Invalid DateTime",Sae=864e13;function _5(t){return new io("unsupported zone",`the zone "${t.name}" is not supported`)}function VI(t){return t.weekData===null&&(t.weekData=ex(t.c)),t.weekData}function UI(t){return t.localWeekData===null&&(t.localWeekData=ex(t.c,t.loc.getMinDaysInFirstWeek(),t.loc.getStartOfWeek())),t.localWeekData}function kp(t,e){let n={ts:t.ts,zone:t.zone,c:t.c,o:t.o,loc:t.loc,invalid:t.invalid};return new St({...n,...e,old:n})}function Dae(t,e,n){let r=t-e*60*1e3,o=n.offset(r);if(e===o)return[r,e];r-=(o-e)*60*1e3;let i=n.offset(r);return o===i?[r,o]:[t-Math.min(o,i)*60*1e3,Math.max(o,i)]}function T5(t,e){t+=e*60*1e3;let n=new Date(t);return{year:n.getUTCFullYear(),month:n.getUTCMonth()+1,day:n.getUTCDate(),hour:n.getUTCHours(),minute:n.getUTCMinutes(),second:n.getUTCSeconds(),millisecond:n.getUTCMilliseconds()}}function N5(t,e,n){return Dae(c0(t),e,n)}function wae(t,e){let n=t.o,r=t.c.year+Math.trunc(e.years),o=t.c.month+Math.trunc(e.months)+Math.trunc(e.quarters)*3,i={...t.c,year:r,month:o,day:Math.min(t.c.day,f0(r,o))+Math.trunc(e.days)+Math.trunc(e.weeks)*7},s=Kn.fromObject({years:e.years-Math.trunc(e.years),quarters:e.quarters-Math.trunc(e.quarters),months:e.months-Math.trunc(e.months),weeks:e.weeks-Math.trunc(e.weeks),days:e.days-Math.trunc(e.days),hours:e.hours,minutes:e.minutes,seconds:e.seconds,milliseconds:e.milliseconds}).as("milliseconds"),a=c0(i),[l,c]=Dae(a,n,t.zone);return s!==0&&(l+=s,c=t.zone.offset(l)),{ts:l,o:c}}function ax(t,e,n,r,o,i){let{setZone:s,zone:a}=n;if(t&&Object.keys(t).length!==0||e){let l=e||a,c=St.fromObject(t,{...n,zone:l,specificOffset:i});return s?c:c.setZone(a)}else return St.invalid(new io("unparsable",`the input "${o}" can't be parsed as ${r}`))}function $5(t,e,n=!0){return t.isValid?so.create(tn.create("en-US"),{allowZ:n,forceSimple:!0}).formatDateTimeFromString(t,e):null}function HI(t,e){let n=t.c.year>9999||t.c.year<0,r="";return n&&t.c.year>=0&&(r+="+"),r+=Hn(t.c.year,n?6:4),e?(r+="-",r+=Hn(t.c.month),r+="-",r+=Hn(t.c.day)):(r+=Hn(t.c.month),r+=Hn(t.c.day)),r}function Eae(t,e,n,r,o,i){let s=Hn(t.c.hour);return e?(s+=":",s+=Hn(t.c.minute),(t.c.millisecond!==0||t.c.second!==0||!n)&&(s+=":")):s+=Hn(t.c.minute),(t.c.millisecond!==0||t.c.second!==0||!n)&&(s+=Hn(t.c.second),(t.c.millisecond!==0||!r)&&(s+=".",s+=Hn(t.c.millisecond,3))),o&&(t.isOffsetFixed&&t.offset===0&&!i?s+="Z":t.o<0?(s+="-",s+=Hn(Math.trunc(-t.o/60)),s+=":",s+=Hn(Math.trunc(-t.o%60))):(s+="+",s+=Hn(Math.trunc(t.o/60)),s+=":",s+=Hn(Math.trunc(t.o%60)))),i&&(s+="["+t.zone.ianaName+"]"),s}var Lae={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},MMe={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},OMe={ordinal:1,hour:0,minute:0,second:0,millisecond:0},Aae=["year","month","day","hour","minute","second","millisecond"],IMe=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],kMe=["year","ordinal","hour","minute","second","millisecond"];function RMe(t){let e={year:"year",years:"year",month:"month",months:"month",day:"day",days:"day",hour:"hour",hours:"hour",minute:"minute",minutes:"minute",quarter:"quarter",quarters:"quarter",second:"second",seconds:"second",millisecond:"millisecond",milliseconds:"millisecond",weekday:"weekday",weekdays:"weekday",weeknumber:"weekNumber",weeksnumber:"weekNumber",weeknumbers:"weekNumber",weekyear:"weekYear",weekyears:"weekYear",ordinal:"ordinal"}[t.toLowerCase()];if(!e)throw new l0(t);return e}function _ae(t){switch(t.toLowerCase()){case"localweekday":case"localweekdays":return"localWeekday";case"localweeknumber":case"localweeknumbers":return"localWeekNumber";case"localweekyear":case"localweekyears":return"localWeekYear";default:return RMe(t)}}function Tae(t,e){let n=Js(e.zone,Ut.defaultZone),r=tn.fromObject(e),o=Ut.now(),i,s;if(He(t.year))i=o;else{for(let c of Aae)He(t[c])&&(t[c]=Lae[c]);let a=TI(t)||$I(t);if(a)return St.invalid(a);let l=n.offset(o);[i,s]=N5(t,l,n)}return new St({ts:i,zone:n,loc:r,o:s})}function $ae(t,e,n){let r=He(n.round)?!0:n.round,o=(s,a)=>(s=u0(s,r||n.calendary?0:2,!0),e.loc.clone(n).relFormatter(n).format(s,a)),i=s=>n.calendary?e.hasSame(t,s)?0:e.startOf(s).diff(t.startOf(s),s).get(s):e.diff(t,s).get(s);if(n.unit)return o(i(n.unit),n.unit);for(let s of n.units){let a=i(s);if(Math.abs(a)>=1)return o(a,s)}return o(t>e?-0:0,n.units[n.units.length-1])}function Nae(t){let e={},n;return t.length>0&&typeof t[t.length-1]=="object"?(e=t[t.length-1],n=Array.from(t).slice(0,t.length-1)):n=Array.from(t),[e,n]}var St=class t{constructor(e){let n=e.zone||Ut.defaultZone,r=e.invalid||(Number.isNaN(e.ts)?new io("invalid input"):null)||(n.isValid?null:_5(n));this.ts=He(e.ts)?Ut.now():e.ts;let o=null,i=null;if(!r)if(e.old&&e.old.ts===this.ts&&e.old.zone.equals(n))[o,i]=[e.old.c,e.old.o];else{let a=n.offset(this.ts);o=T5(this.ts,a),r=Number.isNaN(o.year)?new io("invalid input"):null,o=r?null:o,i=r?null:a}this._zone=n,this.loc=e.loc||tn.create(),this.invalid=r,this.weekData=null,this.localWeekData=null,this.c=o,this.o=i,this.isLuxonDateTime=!0}static now(){return new t({})}static local(){let[e,n]=Nae(arguments),[r,o,i,s,a,l,c]=n;return Tae({year:r,month:o,day:i,hour:s,minute:a,second:l,millisecond:c},e)}static utc(){let[e,n]=Nae(arguments),[r,o,i,s,a,l,c]=n;return e.zone=oo.utcInstance,Tae({year:r,month:o,day:i,hour:s,minute:a,second:l,millisecond:c},e)}static fromJSDate(e,n={}){let r=Vse(e)?e.valueOf():NaN;if(Number.isNaN(r))return t.invalid("invalid input");let o=Js(n.zone,Ut.defaultZone);return o.isValid?new t({ts:r,zone:o,loc:tn.fromObject(n)}):t.invalid(_5(o))}static fromMillis(e,n={}){if(il(e))return e<-Sae||e>Sae?t.invalid("Timestamp out of range"):new t({ts:e,zone:Js(n.zone,Ut.defaultZone),loc:tn.fromObject(n)});throw new br(`fromMillis requires a numerical input, but received a ${typeof e} with value ${e}`)}static fromSeconds(e,n={}){if(il(e))return new t({ts:e*1e3,zone:Js(n.zone,Ut.defaultZone),loc:tn.fromObject(n)});throw new br("fromSeconds requires a numerical input")}static fromObject(e,n={}){e=e||{};let r=Js(n.zone,Ut.defaultZone);if(!r.isValid)return t.invalid(_5(r));let o=tn.fromObject(n),i=p0(e,_ae),{minDaysInFirstWeek:s,startOfWeek:a}=_I(i,o),l=Ut.now(),c=He(n.specificOffset)?r.offset(l):n.specificOffset,u=!He(i.ordinal),d=!He(i.year),f=!He(i.month)||!He(i.day),p=d||f,m=i.weekYear||i.weekNumber;if((p||u)&&m)throw new Ys("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(f&&u)throw new Ys("Can't mix ordinal dates with month/day");let g=m||i.weekday&&!p,h,v,y=T5(l,c);g?(h=IMe,v=MMe,y=ex(y,s,a)):u?(h=kMe,v=OMe,y=w5(y)):(h=Aae,v=Lae);let b=!1;for(let T of h){let N=i[T];He(N)?b?i[T]=v[T]:i[T]=y[T]:b=!0}let S=g?Bse(i,s,a):u?zse(i):TI(i),C=S||$I(i);if(C)return t.invalid(C);let w=g?wI(i,s,a):u?EI(i):i,[E,_]=N5(w,c,r),$=new t({ts:E,zone:r,o:_,loc:o});return i.weekday&&p&&e.weekday!==$.weekday?t.invalid("mismatched weekday",`you can't specify both a weekday of ${i.weekday} and a date of ${$.toISO()}`):$}static fromISO(e,n={}){let[r,o]=rae(e);return ax(r,o,n,"ISO 8601",e)}static fromRFC2822(e,n={}){let[r,o]=oae(e);return ax(r,o,n,"RFC 2822",e)}static fromHTTP(e,n={}){let[r,o]=iae(e);return ax(r,o,n,"HTTP",n)}static fromFormat(e,n,r={}){if(He(e)||He(n))throw new br("fromFormat requires an input string and a format");let{locale:o=null,numberingSystem:i=null}=r,s=tn.fromOpts({locale:o,numberingSystem:i,defaultToEN:!0}),[a,l,c,u]=Cae(s,e,n);return u?t.invalid(u):ax(a,l,r,`format ${n}`,e,c)}static fromString(e,n,r={}){return t.fromFormat(e,n,r)}static fromSQL(e,n={}){let[r,o]=lae(e);return ax(r,o,n,"SQL",e)}static invalid(e,n=null){if(!e)throw new br("need to specify a reason the DateTime is invalid");let r=e instanceof io?e:new io(e,n);if(Ut.throwOnInvalid)throw new d5(r);return new t({invalid:r})}static isDateTime(e){return e&&e.isLuxonDateTime||!1}static parseFormatForOpts(e,n={}){let r=zI(e,tn.fromObject(n));return r?r.map(o=>o?o.val:null).join(""):null}static expandFormat(e,n={}){return FI(so.parseFormat(e),tn.fromObject(n)).map(o=>o.val).join("")}get(e){return this[e]}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}get outputCalendar(){return this.isValid?this.loc.outputCalendar:null}get zone(){return this._zone}get zoneName(){return this.isValid?this.zone.name:null}get year(){return this.isValid?this.c.year:NaN}get quarter(){return this.isValid?Math.ceil(this.c.month/3):NaN}get month(){return this.isValid?this.c.month:NaN}get day(){return this.isValid?this.c.day:NaN}get hour(){return this.isValid?this.c.hour:NaN}get minute(){return this.isValid?this.c.minute:NaN}get second(){return this.isValid?this.c.second:NaN}get millisecond(){return this.isValid?this.c.millisecond:NaN}get weekYear(){return this.isValid?VI(this).weekYear:NaN}get weekNumber(){return this.isValid?VI(this).weekNumber:NaN}get weekday(){return this.isValid?VI(this).weekday:NaN}get isWeekend(){return this.isValid&&this.loc.getWeekendDays().includes(this.weekday)}get localWeekday(){return this.isValid?UI(this).weekday:NaN}get localWeekNumber(){return this.isValid?UI(this).weekNumber:NaN}get localWeekYear(){return this.isValid?UI(this).weekYear:NaN}get ordinal(){return this.isValid?w5(this.c).ordinal:NaN}get monthShort(){return this.isValid?Tc.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?Tc.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?Tc.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?Tc.weekdays("long",{locObj:this.loc})[this.weekday-1]:null}get offset(){return this.isValid?+this.o:NaN}get offsetNameShort(){return this.isValid?this.zone.offsetName(this.ts,{format:"short",locale:this.locale}):null}get offsetNameLong(){return this.isValid?this.zone.offsetName(this.ts,{format:"long",locale:this.locale}):null}get isOffsetFixed(){return this.isValid?this.zone.isUniversal:null}get isInDST(){return this.isOffsetFixed?!1:this.offset>this.set({month:1,day:1}).offset||this.offset>this.set({month:5}).offset}getPossibleOffsets(){if(!this.isValid||this.isOffsetFixed)return[this];let e=864e5,n=6e4,r=c0(this.c),o=this.zone.offset(r-e),i=this.zone.offset(r+e),s=this.zone.offset(r-o*n),a=this.zone.offset(r-i*n);if(s===a)return[this];let l=r-s*n,c=r-a*n,u=T5(l,s),d=T5(c,a);return u.hour===d.hour&&u.minute===d.minute&&u.second===d.second&&u.millisecond===d.millisecond?[kp(this,{ts:l}),kp(this,{ts:c})]:[this]}get isInLeapYear(){return Op(this.year)}get daysInMonth(){return f0(this.year,this.month)}get daysInYear(){return this.isValid?Nd(this.year):NaN}get weeksInWeekYear(){return this.isValid?Mp(this.weekYear):NaN}get weeksInLocalWeekYear(){return this.isValid?Mp(this.localWeekYear,this.loc.getMinDaysInFirstWeek(),this.loc.getStartOfWeek()):NaN}resolvedLocaleOptions(e={}){let{locale:n,numberingSystem:r,calendar:o}=so.create(this.loc.clone(e),e).resolvedOptions(this);return{locale:n,numberingSystem:r,outputCalendar:o}}toUTC(e=0,n={}){return this.setZone(oo.instance(e),n)}toLocal(){return this.setZone(Ut.defaultZone)}setZone(e,{keepLocalTime:n=!1,keepCalendarTime:r=!1}={}){if(e=Js(e,Ut.defaultZone),e.equals(this.zone))return this;if(e.isValid){let o=this.ts;if(n||r){let i=e.offset(this.ts),s=this.toObject();[o]=N5(s,i,e)}return kp(this,{ts:o,zone:e})}else return t.invalid(_5(e))}reconfigure({locale:e,numberingSystem:n,outputCalendar:r}={}){let o=this.loc.clone({locale:e,numberingSystem:n,outputCalendar:r});return kp(this,{loc:o})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;let n=p0(e,_ae),{minDaysInFirstWeek:r,startOfWeek:o}=_I(n,this.loc),i=!He(n.weekYear)||!He(n.weekNumber)||!He(n.weekday),s=!He(n.ordinal),a=!He(n.year),l=!He(n.month)||!He(n.day),c=a||l,u=n.weekYear||n.weekNumber;if((c||s)&&u)throw new Ys("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(l&&s)throw new Ys("Can't mix ordinal dates with month/day");let d;i?d=wI({...ex(this.c,r,o),...n},r,o):He(n.ordinal)?(d={...this.toObject(),...n},He(n.day)&&(d.day=Math.min(f0(d.year,d.month),d.day))):d=EI({...w5(this.c),...n});let[f,p]=N5(d,this.o,this.zone);return kp(this,{ts:f,o:p})}plus(e){if(!this.isValid)return this;let n=Kn.fromDurationLike(e);return kp(this,wae(this,n))}minus(e){if(!this.isValid)return this;let n=Kn.fromDurationLike(e).negate();return kp(this,wae(this,n))}startOf(e,{useLocaleWeeks:n=!1}={}){if(!this.isValid)return this;let r={},o=Kn.normalizeUnit(e);switch(o){case"years":r.month=1;case"quarters":case"months":r.day=1;case"weeks":case"days":r.hour=0;case"hours":r.minute=0;case"minutes":r.second=0;case"seconds":r.millisecond=0;break;case"milliseconds":break}if(o==="weeks")if(n){let i=this.loc.getStartOfWeek(),{weekday:s}=this;s<i&&(r.weekNumber=this.weekNumber-1),r.weekday=i}else r.weekday=1;if(o==="quarters"){let i=Math.ceil(this.month/3);r.month=(i-1)*3+1}return this.set(r)}endOf(e,n){return this.isValid?this.plus({[e]:1}).startOf(e,n).minus(1):this}toFormat(e,n={}){return this.isValid?so.create(this.loc.redefaultToEN(n)).formatDateTimeFromString(this,e):jI}toLocaleString(e=_d,n={}){return this.isValid?so.create(this.loc.clone(n),e).formatDateTime(this):jI}toLocaleParts(e={}){return this.isValid?so.create(this.loc.clone(e),e).formatDateTimeParts(this):[]}toISO({format:e="extended",suppressSeconds:n=!1,suppressMilliseconds:r=!1,includeOffset:o=!0,extendedZone:i=!1}={}){if(!this.isValid)return null;let s=e==="extended",a=HI(this,s);return a+="T",a+=Eae(this,s,n,r,o,i),a}toISODate({format:e="extended"}={}){return this.isValid?HI(this,e==="extended"):null}toISOWeekDate(){return $5(this,"kkkk-'W'WW-c")}toISOTime({suppressMilliseconds:e=!1,suppressSeconds:n=!1,includeOffset:r=!0,includePrefix:o=!1,extendedZone:i=!1,format:s="extended"}={}){return this.isValid?(o?"T":"")+Eae(this,s==="extended",n,e,r,i):null}toRFC2822(){return $5(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return $5(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?HI(this,!0):null}toSQLTime({includeOffset:e=!0,includeZone:n=!1,includeOffsetSpace:r=!0}={}){let o="HH:mm:ss.SSS";return(n||e)&&(r&&(o+=" "),n?o+="z":e&&(o+="ZZ")),$5(this,o,!0)}toSQL(e={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(e)}`:null}toString(){return this.isValid?this.toISO():jI}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`DateTime { ts: ${this.toISO()}, zone: ${this.zone.name}, locale: ${this.locale} }`:`DateTime { Invalid, reason: ${this.invalidReason} }`}valueOf(){return this.toMillis()}toMillis(){return this.isValid?this.ts:NaN}toSeconds(){return this.isValid?this.ts/1e3:NaN}toUnixInteger(){return this.isValid?Math.floor(this.ts/1e3):NaN}toJSON(){return this.toISO()}toBSON(){return this.toJSDate()}toObject(e={}){if(!this.isValid)return{};let n={...this.c};return e.includeConfig&&(n.outputCalendar=this.outputCalendar,n.numberingSystem=this.loc.numberingSystem,n.locale=this.loc.locale),n}toJSDate(){return new Date(this.isValid?this.ts:NaN)}diff(e,n="milliseconds",r={}){if(!this.isValid||!e.isValid)return Kn.invalid("created by diffing an invalid DateTime");let o={locale:this.locale,numberingSystem:this.numberingSystem,...r},i=Use(n).map(Kn.normalizeUnit),s=e.valueOf()>this.valueOf(),a=s?this:e,l=s?e:this,c=mae(a,l,i,o);return s?c.negate():c}diffNow(e="milliseconds",n={}){return this.diff(t.now(),e,n)}until(e){return this.isValid?_c.fromDateTimes(this,e):this}hasSame(e,n,r){if(!this.isValid)return!1;let o=e.valueOf(),i=this.setZone(e.zone,{keepLocalTime:!0});return i.startOf(n,r)<=o&&o<=i.endOf(n,r)}equals(e){return this.isValid&&e.isValid&&this.valueOf()===e.valueOf()&&this.zone.equals(e.zone)&&this.loc.equals(e.loc)}toRelative(e={}){if(!this.isValid)return null;let n=e.base||t.fromObject({},{zone:this.zone}),r=e.padding?this<n?-e.padding:e.padding:0,o=["years","months","days","hours","minutes","seconds"],i=e.unit;return Array.isArray(e.unit)&&(o=e.unit,i=void 0),$ae(n,this.plus(r),{...e,numeric:"always",units:o,unit:i})}toRelativeCalendar(e={}){return this.isValid?$ae(e.base||t.fromObject({},{zone:this.zone}),this,{...e,numeric:"auto",units:["years","months","days"],calendary:!0}):null}static min(...e){if(!e.every(t.isDateTime))throw new br("min requires all arguments be DateTimes");return NI(e,n=>n.valueOf(),Math.min)}static max(...e){if(!e.every(t.isDateTime))throw new br("max requires all arguments be DateTimes");return NI(e,n=>n.valueOf(),Math.max)}static fromFormatExplain(e,n,r={}){let{locale:o=null,numberingSystem:i=null}=r,s=tn.fromOpts({locale:o,numberingSystem:i,defaultToEN:!0});return BI(s,e,n)}static fromStringExplain(e,n,r={}){return t.fromFormatExplain(e,n,r)}static get DATE_SHORT(){return _d}static get DATE_MED(){return Ob}static get DATE_MED_WITH_WEEKDAY(){return aI}static get DATE_FULL(){return Ib}static get DATE_HUGE(){return kb}static get TIME_SIMPLE(){return Rb}static get TIME_WITH_SECONDS(){return Pb}static get TIME_WITH_SHORT_OFFSET(){return Fb}static get TIME_WITH_LONG_OFFSET(){return Bb}static get TIME_24_SIMPLE(){return zb}static get TIME_24_WITH_SECONDS(){return jb}static get TIME_24_WITH_SHORT_OFFSET(){return Vb}static get TIME_24_WITH_LONG_OFFSET(){return Ub}static get DATETIME_SHORT(){return Hb}static get DATETIME_SHORT_WITH_SECONDS(){return Kb}static get DATETIME_MED(){return Wb}static get DATETIME_MED_WITH_SECONDS(){return Gb}static get DATETIME_MED_WITH_WEEKDAY(){return lI}static get DATETIME_FULL(){return Yb}static get DATETIME_FULL_WITH_SECONDS(){return Zb}static get DATETIME_HUGE(){return qb}static get DATETIME_HUGE_WITH_SECONDS(){return Jb}};function C0(t){if(St.isDateTime(t))return t;if(t&&t.valueOf&&il(t.valueOf()))return St.fromJSDate(t);if(t&&typeof t=="object")return St.fromObject(t);throw new br(`Unknown datetime argument: ${t}, of type ${typeof t}`)}function D5(t){return t.reduce((e,{field:n,operator:r,value:o})=>{if(!n||!r)return e;if(n==="updated_at"&&(n="modified"),n==="created_at"&&(n="created"),r==="def")return{...e,[`${n}[def]`]:"true"};if(r==="ndef")return{...e,[`${n}[def]`]:"false"};if(r==="checked")return{...e,[`${n}[eq]`]:"true"};if(r==="nchecked")return{...e,[`${n}[eq]`]:"false"};if(typeof o>"u"||o===null||o===""||Array.isArray(o)&&o.length<1)return e;if(r==="between"||r==="sys-date-between")if(Array.isArray(o)&&o.length===2){if(r==="between")return{...e,[`${n}[gte]`]:o[0],[`${n}[lte]`]:o[1]};{let i=St.fromISO(o[0],{zone:"system"}).setZone("utc").toISO(),s=St.fromISO(o[1],{zone:"system"}).plus({day:1}).setZone("utc").toISO();return i&&s?{...e,[`${n}[gte]`]:i,[`${n}[lt]`]:s}:e}}else return e;if(r==="sys-date-eq")if(typeof o=="string"){let i=St.fromISO(o,{zone:"system"}).setZone("utc").toISO(),s=St.fromISO(o,{zone:"system"}).plus({day:1}).setZone("utc").toISO();return i&&s?{...e,[`${n}[gte]`]:i,[`${n}[lt]`]:s}:e}else return e;if(r==="sys-date-gt")if(typeof o=="string"){let i=St.fromISO(o,{zone:"system"}).plus({day:1}).setZone("utc").toISO();return i?{...e,[`${n}[gte]`]:i}:e}else return e;if(r==="sys-date-gte")if(typeof o=="string"){let i=St.fromISO(o,{zone:"system"}).setZone("utc").toISO();return i?{...e,[`${n}[gte]`]:i}:e}else return e;if(r==="sys-date-lt")if(typeof o=="string"){let i=St.fromISO(o,{zone:"system"}).setZone("utc").toISO();return i?{...e,[`${n}[lt]`]:i}:e}else return e;if(r==="sys-date-lte")if(typeof o=="string"){let i=St.fromISO(o,{zone:"system"}).plus({day:1}).setZone("utc").toISO();return i?{...e,[`${n}[lt]`]:i}:e}else return e;if(r==="starts"&&typeof o=="string")return{...e,[`${n}[starts]`]:o.replaceAll(/[^a-zA-Z0-9_.\s-]/g,"").toLowerCase()};if(n==="workflowStageId"){let i=t.some(s=>s.field==="workflowId");if(r==="eq"||r==="neq"){let s=[];return Array.isArray(o)?s=o.map(l=>l.split("_")[1]):s=o.split("_"),{...e,...i?{}:{"workflowId[eq]":s[0]},[`${n}[${r}]`]:s[1]}}if(Array.isArray(o)){let s=o.map(c=>{let u=c.split("_")[0],d=c.split("_")[1];return{workflowId:u,workflowStage:d}}),a=s.map(c=>c.workflowId).join(","),l=s.map(c=>c.workflowStage).join(",");return{...e,...i?{}:{[`workflowId[${r}]`]:a},[`${n}[${r}]`]:l}}}return{...e,[`${n}[${r}]`]:Array.isArray(o)?o.join(","):o}},{})}import{CANVAS_DRAFT_STATE as Mae,CanvasClient as Oae}from"@uniformdev/canvas";async function L5({instanceType:t,searchExpressionPrompt:e,username:n,locale:r,getEditUrl:o,env:i}){let s=new Oae(i),a=await u5({searchExpressionPrompt:e,username:n,locale:r},t,i),{limit:l,offset:c,keyword:u,sort:d,filter:f}=a,m=(await s.getCompositionList({patternType:t==="composition"?void 0:t==="componentPattern"?"component":"composition",pattern:t!=="composition",resolveData:!1,withComponentIDs:!0,skipOverridesResolution:!0,limit:l,offset:c,search:u,filters:f?D5(f):void 0,orderBy:Array.isArray(d)?d:d?[d]:void 0,locale:r,skipPatternResolution:!0,state:Mae})).compositions.map(g=>({id:g.composition._id,name:g.composition._name,componentType:g.composition.type,editUrl:o(g.composition._id)}));return{content:[{type:"text",text:JSON.stringify({results:m,criteria:a},null,2)}]}}async function A5({id:t,env:e}){let r=await new Oae(e).getCompositionById({skipDataResolution:!0,withComponentIDs:!0,skipOverridesResolution:!0,skipPatternResolution:!1,compositionId:t,state:Mae});return{content:[{type:"text",text:JSON.stringify(r,null,2)}]}}var PMe={id:Iae.string()};function kae(t,e){t.tool("compositionList","Lists available Uniform compositions",Sc.shape,async n=>await L5({...n,instanceType:"composition",getEditUrl:r=>c5(r,e),env:e})),t.tool("compositionGet","Gets the full contents of a Uniform composition",PMe,async n=>await A5({...n,env:e}))}import{autoFixParameterGroups as Fae,ContentClient as FMe}from"@uniformdev/canvas";import*as O5 from"zod/v3";import*as Md from"zod/v3";var Rae=Md.object({name:Md.string().describe('Title-cased display name of the component. Ex: "Hero"'),id:Md.string().describe("Public ID of the content type, the camelCase version of name, using only alphanumeric characters"),description:Md.string().describe("Describe the purpose of the content type in 1-2 sentences."),fields:Md.array(Cx).describe("The fields of the content type. The key is the publicId of the field.").optional()});function Pae(t){let e=t.fields?.find(r=>r.type==="asset"&&typeof r.typeConfig=="object"&&r.typeConfig!==null&&"allowedTypes"in r.typeConfig&&Array.isArray(r.typeConfig.allowedTypes)&&r.typeConfig.allowedTypes?.includes("image"))?.id,n=t.fields?.find(r=>r.type==="text")?.id;return{...t,thumbnailField:e,entryName:n}}function M5(t,e){return`${e.baseWebUrl}/dashboards/canvas/content-types/${t}`}var BMe={action:O5.enum(["create","update","delete"]).describe("The action to perform"),publicId:O5.string().describe("Public ID of the component, the camelCase version of name, using only alphanumeric characters"),contentType:Rae.describe("Full content type definition to create. Omit for update or delete.").optional(),patches:bx.describe("JSON patch to apply to the existing component definition. Omit for create or delete.").optional()};function Bae(t,e){t.tool("contentTypeAction","Creates, updates, or deletes a Uniform Content Type definition",BMe,async({publicId:n,action:r,contentType:o,patches:i})=>{let s=new FMe(e),a=!1;if(r==="create"){if(!o)throw new Error("Content type definition is required for create");let l=Pae(o);l.fields&&(a=Fae(l.fields),Fp(l.fields)),await s.upsertContentType({contentType:l})}if(r==="update"){if(!i)throw new Error("Patches are required for update");let c=(await s.getContentTypes()).contentTypes.find(f=>f.id===n);if(!c)throw new Error(`Content Type with public ID ${n} does not exist, try creating it instead`);let u=c.fields?.filter(f=>f.type==="richText").map(f=>f.id),d=yx(c,i);if(d.fields){a=Fae(d.fields);let f=d.fields?.filter(p=>p.type==="richText").map(p=>p.id).filter(p=>!u?.includes(p));Fp(d.fields,f)}await s.upsertContentType({contentType:d})}return r==="delete"&&await s.deleteContentType({contentTypeId:n}),{content:[{type:"text",text:JSON.stringify({success:!0,editUrl:M5(n,e),warning:a?"Issues with field group order were fixed. Ensure definition data is re-fetched before any future updates.":void 0},null,2)}]}})}import{ContentClient as zae}from"@uniformdev/canvas";import*as jae from"zod/v3";var zMe={id:jae.string()};function Vae(t,e){t.tool("contentTypeList","Lists all Uniform Content Type definitions",async()=>{let o=(await new zae(e).getContentTypes()).contentTypes.map(i=>({id:i.id,name:i.name,description:i.description,editUrl:M5(i.id,e)}));return{content:[{type:"text",text:JSON.stringify(o,null,2)}]}}),t.tool("contentTypeGet","Gets a Uniform Content Type definition details (fields, etc.)",zMe,async({id:n})=>{let i=(await new zae(e).getContentTypes()).contentTypes.find(s=>s.id===n);if(!i)throw new Error(`Content Type with ID ${n} not found`);return{content:[{type:"text",text:JSON.stringify(i,null,2)}]}})}import{v4 as jMe}from"uuid";function Uae(t,e){t.tool("createUuid","Creates a new random UUID",async()=>({content:[{type:"text",text:jMe()}]}))}import*as lx from"zod/v3";import{CANVAS_DRAFT_STATE as I5,ContentClient as VMe,convertEntryToPutEntry as UMe,getEffectivePropertyValue as HMe}from"@uniformdev/canvas";async function KMe(t,e,n){let o=(await e.fetchDefinitions())[t.entry.type];if(!o)throw new Error("insanity");let i=Xie(o),s;i.entryName&&(s=t.entry._overrides?.[t.entry._id].parameters?.[i.entryName]??t.entry.fields?.[i.entryName]);let a=HMe({conditionIndex:-1,locale:"__any__",greedyLocaleMatching:!0,property:s}),l=Aie({value:a,isNew:n,contentType:i});t.entry._name=l}async function k5({action:t,id:e,instructions:n,isPattern:r,patternId:o,getEditUrl:i,env:s}){let a=new VMe(s),l,c,u=t==="update"?e:void 0,d={success:!0,actionsTaken:[]};if(t==="duplicate"){let p=(await a.getEntries({entryIDs:[e],pattern:r,state:I5,skipDataResolution:!0,skipPatternResolution:!1,withComponentIDs:!0,skipOverridesResolution:!0})).entries[0];if(!p)throw new Error("Entry not found");let m=crypto.randomUUID(),g={...p.entry,_id:m,_name:`${p.entry._name} (copy)`};g._slug&&(g._slug=`${g._slug}-copy${g._slug?.endsWith("/")?"/":""}`),delete g._thumbnail;let h=Lb({...p,entry:g});l=new ol(h.composition),e=m}else if(t==="create"){if(!n)throw new Error("Instructions are required for create");if(!n.type)throw new Error("Type is required for create");o?(await a.upsertEntry({state:I5,entry:{type:n.type,_id:e,fields:{},_pattern:o}}),u=e):l=new ol({_id:e,_name:"New Entry",type:n.type,_overridability:{hideLockedParameters:!0}})}if(u){if(c=(await a.getEntries({entryIDs:[e],pattern:r,state:I5,skipDataResolution:!0,skipPatternResolution:!1,withComponentIDs:!0,skipOverridesResolution:!0})).entries[0],!c)throw new Error("Entry not found");let p=Lb(c);l=new ol(p.composition)}t==="delete"&&await a.deleteEntry({entryId:e});let f=Cse(s);if(l){t!=="duplicate"&&(await s5(n?.localeUpdates?.enableLocales,s),d=await JE({twee:l,descriptionUpdate:void 0,slugUpdate:n&&"slug"in n?n.slug:void 0,nameUpdate:n&&"name"in n?n.name:void 0,propertyUpdates:n?.fieldUpdates??[],dataResourceUpdates:(n&&"dataResourceUpdates"in n?n.dataResourceUpdates:[])??[],slotUpdates:{},localeUpdates:n?.localeUpdates,currentEditorLocale:void 0,referenceData:f,isEditingPattern:r,domParser:i5}));let p=l.exportTree(),m=l.exportMetadata(),g=UMe(Qie(p,c??{projectId:s.projectId,pattern:r},m,I5,c?.releaseId,c?.editionId));r||await KMe(g,f,t==="create"),await a.upsertEntry(g)}return{content:[{type:"text",text:JSON.stringify({...d,editUrl:i(e)},null,2)}]}}function R5(t,e){return`${e.baseWebUrl}/dashboards/canvas/entries/${t}`}var WMe={action:lx.enum(["create","update","delete","duplicate"]).describe("The action to perform"),id:lx.string().uuid().describe("UUID of the entry to create, update, delete, or duplicate"),patternId:lx.string().uuid().describe("Entry pattern ID to create the entry from. Omit when not creating, or when creating an entry without an entry pattern.").optional(),instructions:xk.describe("Modification instructions for the entry. Omit for delete and duplicate.").optional()};function Hae(t,e){t.tool("entryAction","Creates, updates, or deletes a Uniform Entry",WMe,async n=>await k5({...n,isPattern:!1,getEditUrl:r=>R5(r,e),patternId:n.patternId,env:e}))}import*as Gae from"zod/v3";import{CANVAS_DRAFT_STATE as Kae,ContentClient as Wae}from"@uniformdev/canvas";async function P5({isPattern:t,searchExpressionPrompt:e,username:n,locale:r,getEditUrl:o,env:i}){let s=new Wae(i),a=await u5({searchExpressionPrompt:e,username:n,locale:r},t?"entryPattern":"entry",i),{limit:l,offset:c,keyword:u,sort:d,filter:f}=a,m=(await s.getEntries({limit:l,offset:c,pattern:t,skipDataResolution:!0,withTotalCount:!0,skipPatternResolution:!0,skipOverridesResolution:!0,state:Kae,search:u,filters:f?D5(f):void 0,orderBy:Array.isArray(d)?d:d?[d]:void 0,locale:r})).entries.map(g=>({id:g.entry._id,name:g.entry._name??"",contentType:g.entry.type,editUrl:o(g.entry._id)}));return{content:[{type:"text",text:JSON.stringify({results:m,criteria:a},null,2)}]}}async function F5({id:t,isPattern:e,env:n}){let o=await new Wae(n).getEntries({skipDataResolution:!0,withComponentIDs:!0,skipOverridesResolution:!0,skipPatternResolution:!1,pattern:e,entryIDs:[t],state:Kae});if(o.entries.length===0)throw new Error(`Entry with ID ${t} not found`);return{content:[{type:"text",text:JSON.stringify(o.entries[0],null,2)}]}}var GMe={id:Gae.string()};function Yae(t,e){t.tool("entryList","Lists available Uniform entries",Sc.shape,async n=>await P5({...n,isPattern:!1,getEditUrl:r=>R5(r,e),env:e})),t.tool("entryGet","Gets the full contents of a Uniform entry",GMe,async n=>await F5({...n,isPattern:!1,env:e}))}import*as z5 from"zod/v3";function B5(t,e){return`${e.baseWebUrl}/dashboards/canvas/entry-patterns/${t}`}var YMe={action:z5.enum(["create","update","delete","duplicate"]).describe("The action to perform"),id:z5.string().uuid().describe("UUID of the entry pattern to create, update, delete, or duplicate"),instructions:Ck.describe("Modification instructions for the entry pattern. Omit for delete and duplicate.").optional()};function Zae(t,e){t.tool("entryPatternAction","Creates, updates, or deletes a Uniform Entry Pattern",YMe,async n=>await k5({...n,isPattern:!0,getEditUrl:r=>B5(r,e),patternId:void 0,env:e}))}import*as qae from"zod/v3";var ZMe={id:qae.string()};function Jae(t,e){t.tool("entryPatternList","Lists available Uniform entry patterns",Sc.shape,async n=>await P5({...n,isPattern:!0,getEditUrl:r=>B5(r,e),env:e})),t.tool("entryPatternGet","Gets the full contents of a Uniform entry pattern",ZMe,async n=>await F5({...n,isPattern:!0,env:e}))}import{ProjectClient as qMe}from"@uniformdev/canvas";async function JMe(t){let e=await fetch(`${t.apiHost}/api/v1/member-profile`,{headers:{"x-api-key":t.apiKey,"Content-Type":"application/json"}});if(!e.ok)throw new Error(`Failed to fetch user profile: ${e.status} ${e.statusText}`);return(await e.json()).name}function Xae(t,e){t.tool("getUniformEnvironment","Get the connected Uniform Project name, edit URL, and current user",{},async()=>{try{let n=new qMe(e),[r,o]=await Promise.all([n.get({projectId:e.projectId}),JMe(e)]),i={projectName:r.name,teamName:r.teamName,projectUrl:e.baseWebUrl,currentIdentity:o};return{content:[{type:"text",text:JSON.stringify(i,null,2)}]}}catch(n){return{content:[{type:"text",text:JSON.stringify({error:"Failed to fetch project information",details:n instanceof Error?n.message:"Unknown error"},null,2)}]}}})}import{LocaleClient as XMe}from"@uniformdev/canvas";function Qae(t,e){t.tool("localeList","Lists all registered Uniform locales",async()=>{let r=await new XMe(e).get();return{content:[{type:"text",text:JSON.stringify({locales:r.results,editUrl:`${e.baseWebUrl}/settings/localization`},null,2)}]}})}import*as V5 from"zod/v3";function j5(t,e){return`${e.baseWebUrl}/dashboards/canvas/edit/${t}`}var QMe={action:V5.enum(["create","update","delete","duplicate"]).describe("The action to perform"),id:V5.string().uuid().describe("UUID of the pattern instance to create, update, delete, or duplicate"),instructions:yk.describe("Modification instructions for the pattern. Omit for delete and duplicate.").optional()};function ele(t,e){t.tool("patternAction","Creates, updates, or deletes a Uniform Component Pattern or Composition Pattern",QMe,async n=>await l5({...n,isPattern:!0,getEditUrl:r=>j5(r,e),patternId:void 0,env:e}))}import*as U5 from"zod/v3";var eOe={instanceType:U5.enum(["componentPattern","compositionPattern"]),...Sc.shape},tOe={id:U5.string()};function tle(t,e){t.tool("patternList","Lists available Uniform component patterns or composition patterns",eOe,async n=>await L5({...n,getEditUrl:r=>j5(r,e),env:e})),t.tool("patternGet","Gets the full contents of a Uniform component pattern or composition pattern",tOe,async n=>await A5({...n,env:e}))}import{ProjectMapClient as nOe}from"@uniformdev/project-map";import*as nle from"zod/v3";var rOe={query:nle.string().describe("Keyword to search for in node names and paths.")};function rle(t,e){t.tool("projectMapNodeSearch","Search for project map nodes by keyword. Use this to find the appropriate parent node when you need to create a composition attached to a specific location in the project map hierarchy.",rOe,async({query:n})=>{let r=new nOe({apiKey:e.apiKey,apiHost:e.apiHost,projectId:e.projectId}),i=(await r.getProjectMapDefinition({}))?.projectMaps[0]?.id;if(!i)throw new Error("No project map found for this project");let a=(await r.getNodes({search:n,includeAncestors:!1,expanded:!0,depth:1,projectMapId:i})).nodes?.map(l=>({id:l.id,name:l.name,path:l.path}))??[];return{content:[{type:"text",text:JSON.stringify({matches:a},null,2)}]}})}function ole(t,e){lk(t,e),mk(t,e),vk(t,e),Bae(t,e),Vae(t,e),Hae(t,e),Yae(t,e),Jae(t,e),Zae(t,e),tle(t,e),ele(t,e),Sse(t,e),kae(t,e),Uae(t,e),Xae(t,e),Qae(t,e),rle(t,e)}var ile=new oOe({name:"Uniform MCP",version:mx.version});ole(ile,sk);var sOe=new iOe;await ile.connect(sOe);process.stderr.write(`Uniform MCP server started
5840
5840
  `);
package/dist/server.mjs CHANGED
@@ -5779,7 +5779,7 @@ to {
5779
5779
  ${p}`:""}`:p??"").split(`
5780
5780
  `);return React.createElement(Ry,{title:React.createElement(zw,{gap:"sm"},g.map((v,y)=>React.createElement("div",{key:y},v)))},React.createElement("span",null,m))}return m}function hge({children:t}){return React.createElement("span",{style:{textDecoration:"underline",textDecorationStyle:"wavy",textDecorationColor:"var(--error)"}},t)}function vge({children:t}){return React.createElement("span",{style:{textDecoration:"underline",textDecorationStyle:"wavy",textDecorationColor:"var(--primary-action-default)"}},t)}function bge({children:t}){return React.createElement("span",{style:{textDecoration:"underline",textDecorationStyle:"wavy",textDecorationColor:"var(--alert)"}},t)}import{createVariableReference as eKe}from"@uniformdev/canvas";var Xg=B(z()),yge=B(Zn());var lKe=$e("uniform:open-insert-variable"),mB=$e("uniform:edit-variable"),uKe=$e("uniform:disconnect-variable"),cKe=$e("uniform:insert-variable");var hf=class t extends Na{constructor(r,n,o){super(o);this.reference=r;this.__variableState=n}__variableState;static getType(){return"variable"}static clone(r){return new t(r.reference,{...r.__variableState},r.__key)}static importJSON(r){return gB(r.reference,{displayName:lS(r.reference),referenceIsValid:!0,isFresh:!1,hasClickEvent:void 0,tooltip:void 0,isLoading:!1})}getState(){return this.getLatest().__variableState}setState(r){this.getWritable().__variableState=r}exportJSON(){return{reference:this.reference,type:t.getType(),version:1}}getTextContent(){return xge(this.reference)}createDOM(){return document.createElement("span")}updateDOM(){return!1}static importDOM(){return{binding:()=>({conversion:Cge,priority:0})}}decorate(){return React.createElement(Sge,{state:this.__variableState,reference:this.reference,nodeKey:this.__key})}};function Cge(t){let r=t.textContent.replace(cB,"").replace(dB,"");return{node:gB(r,{displayName:lS(r),hasClickEvent:!0,referenceIsValid:!0,tooltip:void 0,isFresh:!0,isLoading:!1})}}function gB(t,e){return new hf(t,e)}function wge(t){return t instanceof hf}function Sge({state:t,reference:e,nodeKey:r}){let[n]=u1(),[o,a,i]=wI(r),l=!n.isEditable(),s=(0,Ky.useCallback)(u=>{if(o&&Mt(ie())){u.preventDefault();let c=st(r);wge(c)&&c.remove()}return!1},[o,r]);return(0,Ky.useEffect)(()=>Lr(n.registerCommand(Yl,s,lr),n.registerCommand(Ul,s,lr),n.registerCommand(Ci,u=>{let c=ie();if(Mt(c)){let d=c.getNodes();if(d.length>0)return u.preventDefault(),d[0].selectPrevious(),!0}if(!ee(c))return!1;if(Oc(c,!0)){let d=u.shiftKey;return u.preventDefault(),Rc(c,d,!0),!0}return!1},ze),n.registerCommand(Gl,u=>{let c=ie();if(Mt(c)&&!Ege(u.target)){let f=c.getNodes();if(f.length>0)return u.preventDefault(),f[0].selectNext(0,0),!0}if(!ee(c))return!1;let d=u.shiftKey;return Oc(c,!1)?(u.preventDefault(),Rc(c,d,!1),!0):!1},ze)),[i,n,o,r,s,a]),React.createElement(pB,{...t,reference:e,displayName:t.isLoading?React.createElement(kF,{size:"sm"}):t.displayName,selected:o,disabled:l,clickToEdit:t.hasClickEvent,onClick:t.hasClickEvent?()=>{a(!o),n.dispatchCommand(mB,{reference:e,sourceKey:r})}:()=>a(!o)})}function Ege(t){let e=nr(t);return pt(e)}var Jg=class t extends Na{__asset;__assetQuery;__upload;__error;getAsset(){return this.getLatest().__asset}setAsset(e){let r=this.getWritable();r.__asset=e}getAssetQuery(){return this.getLatest().__assetQuery}setAssetQuery(e){let r=this.getWritable();r.__assetQuery=e}getUpload(){return this.getLatest().__upload}setUpload(e){let r=this.getWritable();r.__upload=e}getError(){return this.getLatest().__error}setError(e){let r=this.getWritable();r.__error=e}static getType(){return"asset"}constructor(e,r,n,o,a){super(a),this.__asset=e,this.__upload=r,this.__error=o,this.__assetQuery=n}static clone(e){return new t(e.__asset,e.__upload,e.__assetQuery,e.__error,e.__key)}exportJSON(){let e={type:"asset",version:1};if(this.__asset&&(e.__asset=this.__asset),this.__assetQuery&&(e.__assetQuery=this.__assetQuery),this.__upload&&"fileUrl"in this.__upload){let{fileUrl:r,suggestedAltText:n,suggestedCaption:o}=this.__upload;e.__upload={fileUrl:r,suggestedAltText:n,suggestedCaption:o}}return this.__error&&(e.__error=this.__error),e}static importJSON(e){return uS({asset:e.__asset,assetQuery:e.__assetQuery,upload:e.__upload,error:e.__error})}static importDOM(){return{img:()=>({conversion:e=>$ge(e,uS),priority:0}),figure:()=>({conversion:e=>Tge(e,uS),priority:0})}}createDOM(e){let r=document.createElement("span"),o=e.theme.image;return o!==void 0&&(r.className=o),r}updateDOM(){return!1}isInline(){return!1}};function uS({asset:t,upload:e,assetQuery:r,error:n}){return ur(new Jg(t,e,r,n))}function hB(t){return t.parentElement!=null&&t.parentElement.tagName==="LI"&&t.previousSibling===null&&t.getAttribute("aria-roledescription")==="checkbox"}function $ge(t,e){let r=t;if(r.src.startsWith("file:///")||hB(r))return null;let{alt:n,src:o}=r;return{node:vB({altText:n,src:o,createAssetNode:e})}}function Tge(t,e){let r=t,n=r.querySelector("img"),o=r.querySelector("figcaption");if(!n||n.src.startsWith("file:///")||hB(n))return null;let{alt:a,src:i}=n;return i.startsWith("uniform://")?{node:e({assetQuery:{id:n.src.split("uniform://")[1],suggestedAltText:a,suggestedCaption:o?.textContent??void 0}})}:{node:vB({altText:a,src:i,caption:o?.textContent??void 0,createAssetNode:e})}}function vB({altText:t,src:e,caption:r,createAssetNode:n}){return n({asset:void 0,upload:{fileUrl:e,suggestedAltText:t,suggestedCaption:r},assetQuery:void 0})}var Ige=t=>new DOMParser().parseFromString(t,"text/html");function bB(t,e=Ige){let r=yT({nodes:[ko,lo,oS,Ii,Ti,yi,aa,oa,$s,Mo,Jg,hf]}),n=e(t);return r.update(()=>{R0("skip-dom-selection");let o=Z0(r,n);jt().select(),Mc(o)},{discrete:!0}),r.getEditorState().toJSON()}function yB({twee:t,nodeId:e,propertyId:r,propertyType:n,locale:o,propertyEdit:a,conditionIndex:i=-1,definitionIndex:l,domParser:s}){let u=t.getNodeById(e);if(!u)throw new Error(`Node with ID ${e} not found`);if(a.action==="clearValue")t.updateNodeProperty({nodeId:e,property:r,value:null,source:"ai",locale:o,conditionIndex:-1});else if(a.action==="resetOverride")t.resetPatternPropertyOverride(e,r,o);else if(a.action==="setValue"){if(n==="contentReference"){Oge({twee:t,nodeId:e,targetNode:u,propertyId:r,propertyType:n,propertyEdit:a,locale:o,conditionIndex:i,definitionIndex:l});return}let c=Pge({twee:t,targetNode:u,propertyId:r,propertyType:n,propertyEdit:a,domParser:s}),d=t.getNodeProperty(e,r);if(!o&&d?.locales)throw new Error(`The ${r} property is localized in ${Object.keys(d.locales).join(", ")}, but no locale was provided when setting its value. Please provide an explicit locale.`);if(r===Lge){let f=t.getParentInfo(e);if(f?.parentId){let p=t.getNodeProperty(f.parentId,Age);if(p?.value!==AE)throw new Error(`Cannot edit personalization criteria when the parent personalization component is not using the Strongest Variation Match selection method. Current selection method: ${p?.value||"Top-down criteria matching"}.`)}}t.updateNodeProperty({nodeId:e,property:r,value:()=>c,source:"ai",locale:o,conditionIndex:i,type:n})}}var Pge=({twee:t,targetNode:e,propertyId:r,propertyType:n,propertyEdit:o,domParser:a})=>{if(n==="richText")return bB(o.newValue??"",a);if(n==="number")return Number(o.newValue);if(r===Dge){if(kge(e.value.type))throw new Error("Enrichment tags are not allowed in system components.");if(t.getParentInfo(e.nodeId)?.parentId===_ge)throw new Error("Enrichment tags are not allowed in personalization variants.")}return o.treatNewValueAsJson?JSON.parse(o.newValue):o.newValue};function Oge({twee:t,nodeId:e,targetNode:r,propertyId:n,propertyType:o,propertyEdit:a,locale:i,conditionIndex:l,definitionIndex:s}){let u=mc(r.nodeId,n,i,l),c;try{c=a.treatNewValueAsJson?JSON.parse(a.newValue):a.newValue}catch(y){throw new Error(`Invalid reference field data: ${y instanceof Error?y.message:"Unknown error"}`)}if(!c||typeof c!="object"||c.type!==ci)throw new Error("Invalid reference field definition received from AI");let d=c.variables?.entryIds;if(!d||typeof d!="string"||d.length===0){t.updateNode({nodeId:r.nodeId,updateDataResources:[{type:"remove",name:u}]}),t.updateNodeProperty({nodeId:e,property:n,value:null,source:"ai",locale:i,conditionIndex:l,type:o});return}let m=s[r.value.type]?.parameters?.find(({id:y})=>y===n)?.typeConfig?.isMulti??!1,h=EE(d,{targetLocale:i,enabledLocales:t.getNodeById(t.rootNodeId)?.value._locales??[]});t.updateNode({nodeId:r.nodeId,updateDataResources:[{type:"set",name:u,value:h}]});let g=`/${u}/entries${m?"":"/0"}`,v=Nge(Mge({syntax:"jptr",pointer:g}));t.updateNodeProperty({nodeId:e,property:n,value:()=>v,source:"ai",locale:i,conditionIndex:l,type:o})}import{validate as Rge}from"uuid";var xB=t=>Rge(t)?t:btoa(t);function vf(t,e,r="Component instance"){let n=t.getNodeById(e);if(n)return n;let o=[];if(t.visitNodeAndDescendants(t.rootNodeId,a=>{a.nodeId!==e&&a.nodeId.includes(e)&&o.push(a.nodeId)}),o.length>0){let a=o.map(i=>`"${xB(i)}"`).join(", ");throw new Error(`${r} with ID ${e} not found. You might have meant one of these IDs that does exist: ${a}. Component IDs should be used exactly as provided in the _id field.`)}throw new Error(`${r} with ID ${e} not found`)}async function Xy({twee:t,slotUpdates:e,propertyUpdates:r,dataResourceUpdates:n,localeUpdates:o,nameUpdate:a,slugUpdate:i,descriptionUpdate:l,currentEditorLocale:s,referenceData:u,dataSourceVariant:c,onStatusUpdate:d,isEditingPattern:f,domParser:p}){let m=[],h=(a?1:0)+(i?1:0)+(l?1:0)+(e.createComponentInstances?.length??0)+(e.moveComponentInstances?.length??0)+(e.duplicateComponentInstances?.length??0)+(e.deleteComponentInstances?.length??0)+(o?.enableLocales?.length??0)+(o?.disableLocales?.length??0)+r.length,g=0,v=w=>{m.push(w),g++,d?.({completed:g,total:h})};a&&(t.updateRootNode({update:{_name:a}}),v({summary:"Updated name",success:!0})),i&&(t.updateRootNode({update:{_slug:i}}),v({summary:"Updated slug",success:!0})),l&&(t.updateRootMetadata({description:l}),v({summary:"Updated description",success:!0}));let y=await u.fetchDefinitions();await jge({slotUpdates:e,twee:t,definitions:y,referenceData:u,addResult:v,isEditingPattern:f});let x=m.some(w=>!w.success);if(x?e.moveComponentInstances?.forEach(w=>{m.push({summary:`Skipped moving component ${w.componentId} because previous actions failed`,success:!1})}):await zge({slotUpdates:e,twee:t,definitions:y,addResult:v,isEditingPattern:f}),x=m.some(w=>!w.success),e.duplicateComponentInstances)for(let w of e.duplicateComponentInstances)if(x)v({summary:`Skipped duplicating component ${w} because previous actions failed`,success:!1});else{let S=await t.duplicateNode(w,u.resolvePatternData);v({summary:`Duplicated component ${w}. The new duplicate has ID ${S} and is placed immediately after the original component in the same slot.`,success:!0})}return x=m.some(w=>!w.success),e.deleteComponentInstances?.forEach(w=>{x?v({summary:`Skipped deleting component ${w} because previous actions failed`,success:!1}):(t.deleteNode(w,!1),v({summary:`Deleted component ${w}`,success:!0}))}),x=m.some(w=>!w.success),o?.enableLocales?.forEach(w=>{x?v({summary:`Skipped enabling locale ${w} because previous actions failed`,success:!1}):(t.enableLocale(w),v({summary:`Enabled locale ${w}`,success:!0}))}),x=m.some(w=>!w.success),o?.disableLocales?.forEach(w=>{x?v({summary:`Skipped disabling locale ${w} because previous actions failed`,success:!1}):(t.disableLocale(w),v({summary:`Disabled locale ${w}`,success:!0}))}),x=m.some(w=>!w.success),x?r.length>0&&v({summary:`Skipped ${r.length} property updates because previous actions failed`,success:!1}):(await Hge({propertyUpdates:r,twee:t,currentEditorLocale:s,referenceData:u,definitions:y,addResult:v})).forEach(S=>{if(!S.result.success)return;let E="componentId"in S.update?S.update.componentId:t.rootNodeId,$=Z2({twee:t,nodeId:E,currentEditorLocale:S.currentLocale,definition:S.propertyDefinition}),T=(t.getNodeById(t.rootNodeId)?.value)._locales??[];if($&&!T.includes($)){v({summary:`The ${$} locale is not enabled on this entity. Please enable it before setting values in this locale.`,success:!1});return}if(S.result.action!=="nothing")try{yB({twee:t,nodeId:E,propertyId:S.propertyDefinition.id,propertyType:S.propertyDefinition.type,locale:$,propertyEdit:S.result,definitionIndex:y,domParser:p}),v({summary:`Updated value of ${S.propertyDefinition.id} on ${E}${$?` in ${$}`:""}`,success:!0})}catch(D){v({summary:`Failed to update value of ${S.propertyDefinition.id} on ${E}${$?` in ${$}`:""}: ${D instanceof Error?D.message:"Unknown error"}`,success:!1})}if("overridable"in S.update&&S.update.overridable!==void 0)if(S.propertyDefinition.type===Fge)v({summary:`Cannot set overridability for block property '${S.propertyDefinition.id}' - blocks do not support overrides`,success:!1});else{let D=S.update.overridable;t.updateNode({nodeId:E,updateComponent:L=>{L._overridability??={},L._overridability.parameters??={},L._overridability.parameters[S.propertyDefinition.id]=D}}),v({summary:`Updated overridability for ${E}`,success:!0})}}),x=m.some(w=>!w.success),x?n.length>0&&m.push({summary:`Skipped ${n.length} data resource updates because previous actions failed`,success:!1}):(await Wge({dataResourceUpdates:n,twee:t,referenceData:u,results:m,dataSourceVariant:c})).forEach(S=>{if(!S.result.success)return;let E=S.update.componentId;if(S.result.action==="resetOverride")t.updateNode({nodeId:E,updateDataResources:[{type:"reset",name:S.update.dataResourceName}]}),m.push({summary:`Reset data resource to pattern default for ${S.update.dataResourceName} on ${E}`,success:!0});else if(S.result.action==="setValue")try{$E({twee:t,nodeId:E,dataResourceName:S.update.dataResourceName,dataType:S.dataType,dataResourceEdit:S.result}),m.push({summary:`Updated data resource ${S.update.dataResourceName} on ${E}`,success:!0})}catch($){m.push({summary:`Failed to update data resource ${S.update.dataResourceName} on ${E}: ${$ instanceof Error?$.message:"Unknown error"}`,success:!1})}}),{success:m.every(w=>w.success),actionsTaken:m}}async function jge({slotUpdates:t,twee:e,definitions:r,referenceData:n,addResult:o,isEditingPattern:a}){(await Promise.allSettled(t.createComponentInstances?.map(async l=>{let s=vf(e,l.parentComponentId,"Parent component");if(!r[s.value.type])throw new Error(`Definition for parent component type ${s.value.type} not found`);let c=U2({twee:e,parentNodeId:l.parentComponentId,slotName:l.slotName,componentDefinitionsIndex:r});if(!c)throw new Error(`Can't find allowed components for slot ${l.slotName}`);if(l.instanceType==="component"){if(!l.componentType)throw new Error("componentType is required when inserting a component instance");if(!Hh({type:l.componentType},c,a))throw new Error(`Component type ${l.componentType} is not allowed in slot ${l.slotName}`);e.insertNode({node:{type:l.componentType},overrideNodeId:l.newComponentInstanceUuid,parentNodeId:l.parentComponentId,parentSlot:l.slotName,targetIndexInSlot:l.slotIndex}),o({summary:`Inserted component ${l.componentType} in slot ${l.slotName} ${l.slotIndex!==void 0?`at index ${l.slotIndex}`:""}`,success:!0})}else{if(!l.componentPatternId)throw new Error("componentPatternId is required when inserting a component pattern instance");let d=await n.resolvePatternData(l.componentPatternId);if(!d)throw new Error(`Pattern definition with ID ${l.componentPatternId} not found`);if(!Hh({type:d.type,_pattern:l.componentPatternId},c,!1))throw new Error(`Pattern ${l.componentPatternId} is not allowed in slot ${l.slotName}`);e.insertPattern({pattern:d,patternInstanceId:l.newComponentInstanceUuid,parentNodeId:l.parentComponentId,parentSlot:l.slotName,targetIndexInSlot:l.slotIndex}),o({summary:`Inserted pattern ${d._name} in slot ${l.slotName} ${l.slotIndex!==void 0?`at index ${l.slotIndex}`:""}`,success:!0})}})??[])).forEach((l,s)=>{if(l.status==="rejected"){let u=t.createComponentInstances?.[s];console.error("Error inserting component",l.reason),o({summary:`Failed to insert component ${u?.newComponentInstanceUuid}: ${"message"in l.reason?l.reason.message:"Unknown error"}`,success:!1})}})}async function zge({slotUpdates:t,twee:e,definitions:r,addResult:n,isEditingPattern:o}){(await Promise.allSettled(t.moveComponentInstances?.map(async i=>{let l=vf(e,i.componentId,"Component to move"),s=vf(e,i.newParentComponentId,"Destination component");if(!r[s.value.type])throw new Error(`Definition for destination component type ${s.value.type} not found`);let c=U2({twee:e,parentNodeId:i.newParentComponentId,slotName:i.newSlotName,componentDefinitionsIndex:r});if(!c)throw new Error(`Can't find allowed components for slot ${i.newSlotName}`);if(!Hh({type:l.value.type,_pattern:l.value._pattern},c,o))throw new Error(l.value._pattern?`Pattern ${l.value._pattern} is not allowed in slot ${i.newSlotName}`:`Component ${l.value.type} is not allowed in slot ${i.newSlotName}`);e.moveNode({movedNodeId:i.componentId,parentNodeId:i.newParentComponentId,parentSlot:i.newSlotName,targetIndexInSlot:i.newSlotIndex}),n({summary:`Moved component ${i.componentId} to ${i.newParentComponentId} in slot ${i.newSlotName} at index ${i.newSlotIndex}`,success:!0})})??[])).forEach((i,l)=>{if(i.status==="rejected"){let s=t.moveComponentInstances?.[l];console.error("Error moving component",i.reason),n({summary:`Failed to move component ${s?.componentId}: ${"message"in i.reason?i.reason.message:"Unknown error"}`,success:!1})}})}async function Hge({propertyUpdates:t,twee:e,currentEditorLocale:r,referenceData:n,definitions:o,addResult:a}){if(t.length===0)return[];let[i,l]=await Promise.all([n.fetchProjectGuidance(),n.getToolClient()]),s=await Promise.allSettled(t.map(async u=>(async()=>{let c="componentId"in u?u.componentId:e.rootNodeId,d=vf(e,c),f=o[d.value.type];if(!f)throw new Error(`Definition with ID ${d.value.type} not found`);let p="fieldId"in u?u.fieldId:u.parameterId,m=f.parameters?.find(S=>S.id===p),h=u.fromLocale??u.locale??r,g=u.locale??r,v=m??{id:p,type:"unknown"};if(u.editInstructions===void 0)return{result:{success:!0,newValue:"",treatNewValueAsJson:!1,action:"nothing"},update:u,propertyDefinition:v};if(u.editInstructions==="")return{result:{success:!0,newValue:"",treatNewValueAsJson:!1,action:"clearValue"},update:u,propertyDefinition:v};if(!m)throw new Error(`Property with ID ${p} not found`);if(m.type==="contentReference"){let S=Z2({definition:m,twee:e,nodeId:c,currentEditorLocale:r}),E=mc(c,p,S,-1),$=d.value._dataResources?.[E],T=await l.invoke("createDataResourceEdit",{edit:u.editInstructions,dataType:ci,currentValue:$?.variables||{}});if(!T.success)throw new Error(T.summary??"Failed to edit reference field data resource");return{result:{success:!0,newValue:JSON.stringify({type:ci,variables:T.newValue}),treatNewValueAsJson:!0,action:"setValue"},update:u,propertyDefinition:m,currentLocale:S}}let y=Bge({property:e.getNodeProperty(c,p),locale:h,conditionIndex:-1}),x,C=e.getNodeProperty(c,Vge);C?.value?.dim&&(x=await n.getDimensionGuidance(C.value.dim));let w=await l.invoke("createPropertyEdit",{edit:u.editInstructions,propertyDefinition:{id:p,name:m.name,type:m.type,guidance:m.guidance,typeConfig:m.typeConfig},outputLocale:g,documentContext:void 0,currentValue:y,projectGuidance:i,componentGuidance:f.description,audienceGuidance:x});if(!w.success)throw new Error(w.summary??"Failed to edit property");return{result:w,update:u,propertyDefinition:m,currentLocale:g}})()));return s.forEach((u,c)=>{if(u.status==="rejected"){let d=t[c],f="fieldId"in d?d.fieldId:d.parameterId;a({summary:`Failed to edit property ${f}: ${"message"in u.reason?u.reason.message:"Unknown error"}`,success:!1})}}),s.filter(u=>u.status==="fulfilled").map(u=>u.value)}async function Wge({dataResourceUpdates:t,twee:e,referenceData:r,results:n,dataSourceVariant:o}){if(t.length===0)return[];let a=await r.getToolClient(),i=await Promise.allSettled(t.map(async l=>(async()=>{let s=l.componentId,u=vf(e,s);if(l.editInstructions===void 0)return{result:{success:!0,newValue:{},action:"nothing"},update:l,dataType:"unknown"};if(l.editInstructions==="")return{result:{success:!0,newValue:{},action:"setValue"},update:l,dataType:"unknown"};let c=u.value._dataResources?.[l.dataResourceName],d=u.value._patternDataResources?.[l.dataResourceName];if(!d)throw new Error(`Pattern data resource ${l.dataResourceName} does not exist on the ${u.value._pattern} pattern`);let f=c?.variables??d.variables,p=d.type,m=await a.invoke("createDataResourceEdit",{edit:l.editInstructions,dataType:p,currentValue:f,dataSourceVariant:o});if(!m.success)throw new Error(m.summary??"Failed to edit data resource");return{result:m,update:l,dataType:p}})()));return i.forEach((l,s)=>{if(l.status==="rejected"){let u=t[s];n.push({summary:`Failed to edit data resource ${u.dataResourceName}: ${"message"in l.reason?l.reason.message:"Unknown error"}`,success:!1})}}),i.filter(l=>l.status==="fulfilled").map(l=>l.value)}import{CANVAS_BLOCK_PARAM_TYPE as ba,CANVAS_ENRICHMENT_TAG_PARAM as tV,CANVAS_LOCALE_TAG_PARAM as th,CANVAS_LOCALIZATION_SLOT as xS,CANVAS_LOCALIZATION_TYPE as khe,CANVAS_PERSONALIZATION_PARAM as rh,CANVAS_PERSONALIZE_SLOT as rV,CANVAS_SLOT_SECTION_SLOT as Phe,CANVAS_SLOT_SECTION_TYPE as n2,CANVAS_TEST_SLOT as nV,CANVAS_TEST_VARIANT_PARAM as oV,CANVAS_VIZ_CONTROL_PARAM as fl,convertToBindExpression as aV,createVariableReference as iV,getEffectivePropertyValue as sV,getPropertiesValue as Ohe,parseVariableExpression as lV,walkNodeTree as rs,walkPropertyValues as Rhe}from"@uniformdev/canvas";var ac=B(cS(),1),cV=B(kf(),1);import{produce as wr}from"immer";import{v4 as pl}from"uuid";import{v4 as Yge}from"uuid";async function EB({projectMapClient:t,compositionId:e,compositionName:r,nodePathSegment:n,parentNodeId:o,localePathSegments:a,allowedQueryStrings:i}){let s=(await t.getProjectMapDefinition({}))?.projectMaps[0]?.id;if(!s)throw new Error("No project map found for this project");let u=n||a?.[0]?.pathSegment,c,d=0;if(o){let g=(await t.getNodes({id:o})).nodes?.[0];if(!g)throw new Error("Parent node not found");let v=g.path;d=((await t.getNodes({path:v,depth:1,expanded:!1})).nodes?.filter(w=>w.path!==v)??[]).reduce((w,S)=>Math.max(w,S.order??0),-1)+100,c=`${v==="/"?"":v}/${u}`}else c=`/${u}`;let f=a?.reduce((h,{locale:g,pathSegment:v})=>(h[g]={pathSegment:v,name:v},h),{}),p=i?.map(({name:h,defaultValue:g})=>({name:h,...g!==void 0&&{value:g}})),m=Yge();return await t.upsertProjectMapNodes({projectMapId:s,nodes:[{node:{id:m,name:r,path:c,type:"composition",compositionId:e,order:d,...f&&{locales:f},...p&&{data:{queryStrings:p}}}}]}),{path:c,nodeId:m}}import{bindVariablesToObject as Kge}from"@uniformdev/canvas";var qg="Untitled",$B=60;function TB({value:t,isNew:e,contentType:r}){let{result:n}=Kge({value:t,handleBinding:()=>"{token}",variables:{}}),o=r.entryName??"",a=(r.fields??[]).find(i=>i.id===o);if(typeof n=="string"){if(a?.type==="image")return n.length>0?`Image: ${Jge(n)}`:`${qg} image`;if(n.length>0)return a?.type==="date"?Qge(n)?ehe(n):"Invalid date":nc(n)}else{if(typeof n=="number"||typeof n=="boolean")return n.toString();if(typeof n<"u"&&n!==null){if(a?.type==="link")return Xge(n);if(cE(n))return nc(H2(n.root));if(a?.type==="datetime"&&n){let i=n;return i.datetime&&IB(i.datetime)?the(i.datetime):"Invalid datetime"}else return nc(rhe(n).description)}}return e?`New entry: ${r.name}`:qg}function Xge(t){return t?t.type==="projectMapNode"?t.path.length>0?`Link to ${nc(t.path)}`:`Link to project map node (${t.nodeId})`:t.path.length>0?`Link to ${nc(t.path)}`:`${qg} link`:`${qg} link`}function Jge(t){try{let{pathname:e,hostname:r}=new URL(t),n=e.split("/").filter(o=>o);return n.length>2?`/${n[0]}/.../${n[n.length-1]} (${nc(r)})`:`${e} (${nc(r)})`}catch{return t}}function nc(t){let e=t.split(" ").filter(a=>a).reverse();if(e.length<1)return qg;let r="",n=e.pop(),o=()=>r.length+(n?.length??0)+(r.length>0?1:0);for(;n&&o()<$B;)r+=r.length>0?` ${n}`:n,n=e.pop();return r.length<1?`${t.slice(0,$B)}...`:e.length>0?`${r}...`:r}var qge=/^[1-9][0-9]{3}-[0-1][0-9]-[0-3][0-9]$/;function Qge(t){return qge.test(t)?IB(t):!1}function IB(t){let e=new Date(t);return e instanceof Date&&!isNaN(Number(e))}function ehe(t){return new Date(t).toLocaleDateString()}function the(t){return new Date(t).toLocaleString()}function rhe(t){let e=dS(t);return e?{description:e,named:!0}:{description:nhe(t).valuePreview,named:!1}}function nhe(t){if(typeof t>"u")return{valueIcon:"close-o",valuePreview:"undefined"};if(t===null)return{valueIcon:"close-o",valuePreview:"null"};if(Array.isArray(t))return{valuePreview:`array with ${t.length} item${t.length!==1?"s":""}`,valueIcon:"list"};if(typeof t=="boolean")return{valuePreview:t.toString(),valueIcon:t?"check-r":"close-r"};if(typeof t=="number"||typeof t=="bigint")return{valuePreview:t.toString(10),valueIcon:"number-input"};if(typeof t=="object"){let e=Object.keys(t);return{valuePreview:`object with ${e.length} ${e.length!==1?"properties":"property"}`,valueIcon:"shape-hexagon"}}return{valuePreview:t,valueIcon:"text-input"}}var ohe=["displayName","name","_name","title","heading","label","parameters","fields","properties","entry","slug","_slug","alt","alt_description","description","results","items","entries","hits","value","id","objectID","identifier"];function dS(t){if(typeof t=="string")return t;if(typeof t=="number")return t.toString(10);if(typeof t=="boolean")return t.toString();if(typeof t!="object"||t===null)return;if(Array.isArray(t)){if(t.length===0)return;let n=dS(t[0]);return n?t.length===1?n:`${n} and ${t.length-1} other${t.length>2?"s":""}`:void 0}let r=t;for(let n of ohe)if(n in r){let o=dS(r[n]);if(o)return o}}import{CANVAS_SLOT_SECTION_SLOT as ahe,walkNodeTree as ihe}from"@uniformdev/canvas";import{v4 as DB}from"uuid";var Qg="|";function Jy(t,e){if(!t)return e??DB();let r=t.split(Qg),n=(e??DB()).split(Qg);return r.at(-1)===n[0]&&r.pop(),r.concat(n).join(Qg)}function LB(t){let e=t.indexOf(Qg);if(e<0)throw new Error(`Cannot remove pattern instance ID from ${t}`);return t.substring(e+1)}function qy(t,e,r=!1){ihe(t,({node:n,actions:{setDescendantsContext:o},context:a})=>{let i=!r&&!a?.currentParentPatternInstanceId,l="_pattern"in n&&!!n._pattern;if(a?.currentParentPatternInstanceId){let u=Jy(a.currentParentPatternInstanceId,n._id);n._id=u}let s=a?.currentParentPatternInstanceId;l&&(s=n._id),"_overrides"in n&&n._overrides&&AB(n._overrides,s,i),"_patternOverrides"in n&&n._patternOverrides&&AB(n._patternOverrides,s,i),l&&o({currentParentPatternInstanceId:n._id})},{initialContext:{currentParentPatternInstanceId:e}})}var AB=(t,e,r)=>{Object.entries(t).forEach(([n,o])=>{let a=r?n:Jy(e,n);Object.entries(o.slots??{}).forEach(([i,l])=>{l.forEach(s=>{let{partOfNestedPattern:u}=Qy(n??"");qy(s,i===ahe&&!u?void 0:e,!0)})}),a&&(delete t[n],t[a]=o)})};function Qy(t){let e=t.split(Qg);return e.length===1?{partOfPattern:void 0,partOfNestedPattern:void 0}:e.length===2?{partOfPattern:e[0],partOfNestedPattern:void 0}:{partOfPattern:e[0],partOfNestedPattern:e[e.length-2]}}import{CANVAS_SLOT_SECTION_SLOT as OB}from"@uniformdev/canvas";import{CANVAS_VIZ_CONTROL_PARAM as dhe}from"@uniformdev/canvas";import{CANVAS_ENRICHMENT_TAG_PARAM as _B,CANVAS_INTENT_TAG_PARAM as she,CANVAS_LOCALE_TAG_PARAM as lhe,CANVAS_PERSONALIZATION_PARAM as MB,CANVAS_TEST_VARIANT_PARAM as uhe,CANVAS_VIZ_CONTROL_PARAM as NB}from"@uniformdev/canvas";var che="$internal_displayName",kB=[{id:che,name:"Display Name",type:"text"},{id:she,name:"Intent Tag",type:"intentTag"},{id:lhe,name:"Locale Visibility",type:"localeSelect"},{id:MB,name:"Personalization Criteria",type:MB},{id:_B,name:"Enrichment Tags",type:_B,helpText:"Seeing this component will increase a visitor's score in these enrichments."},{id:uhe,name:"A/B Test",type:"testVariant"},{id:NB,name:"Visibility Control",type:NB}];var fhe=kB.reduce((t,e)=>(e.id===dhe||t.add(e.id),t),new Set);function oc(t,e){return fhe.has(e)?"yes":t?.parameters?.[e]??"no"}function fS(t,e){e&&Object.entries(e).forEach(([r,n])=>{let o=t[r];if(n.parameters||o?.parameters){t[r]??={};let a={...n?.parameters};Object.entries(o?.parameters??{}).forEach(([i,l])=>{let s=a[i];if(!s)a[i]=l;else if(l.locales||l.localesConditions||s.locales||s.localesConditions){let u={...s,...l};(l.locales||s.locales)&&(u.locales={...s.locales,...l.locales}),(l.localesConditions||s.localesConditions)&&(u.localesConditions={...s.localesConditions,...l.localesConditions}),a[i]=u}else a[i]={...s,...l}}),t[r].parameters=a}if((n.dataResources||o?.dataResources)&&(t[r]??={},t[r].dataResources={...n?.dataResources,...o?.dataResources}),n.slots||o?.slots){t[r]??={};let a=Object.entries(o?.slots??{}).reduce((i,[l,s])=>(i[l]&&Array.isArray(i[l])?i[l]=[...s,...i[l]]:i[l]=s,i),n.slots??{});t[r].slots=a}(n.variant!==void 0||o?.variant!==void 0)&&(t[r]=t[r]??{},t[r].variant=o?.variant??n?.variant)})}function PB({applyOverrideToNode:t}){let e=new Set,r={};return{visitNode(n){e.add(n._id),fS(r,n._overrides),fS(r,n._patternOverrides);let o=r[n._id];o&&(o.parameters&&Object.keys(o.parameters).forEach(a=>{oc(n._overridability,a)==="no"&&(console.log(`[Override] Cleaned override from ${n._id} parameter ${a} because it is not overridable`),delete r[n._id].parameters?.[a])}),o.dataResources&&Object.keys(o.dataResources).forEach(a=>{n._patternDataResources?.[a]?.isPatternParameter||(console.log(`[Override] Cleaned override from ${n._id} data resource ${a} because it is not overridable`),delete r[n._id].dataResources?.[a])}),o.variant!==void 0&&(n._overridability?.variants||delete o.variant),t({node:n,overrides:o}))},overrides:r}}function pS(t){let{beforeApplyParameterOverride:e,beforeApplyDataResourceOverride:r}=t??{};return PB({applyOverrideToNode({node:n,overrides:o}){if(Object.entries(o.parameters??{}).map(([a,i])=>{n.parameters=n.parameters??{},e?.(n,a,i,n.parameters[a]);let l=n.parameters[a]??={type:i.type};i.locales||i.localesConditions?(l.locales??={},delete l.value,delete l.conditions,new Set([...Object.keys(i.locales??{}),...Object.keys(i.localesConditions??{})]).forEach(c=>{delete l.locales?.[c],delete l.localesConditions?.[c];let d=i.locales?.[c],f=i.localesConditions?.[c];d!=null&&(l.locales??={},l.locales[c]=d),f!=null&&(l.localesConditions??={},l.localesConditions[c]=f)}),l.locales&&Object.keys(l.locales).length===0&&delete l.locales,l.localesConditions&&Object.keys(l.localesConditions).length===0&&delete l.localesConditions):(delete l.locales,delete l.localesConditions,delete l.conditions,delete l.value,i.value!==null&&i.value!==void 0&&(l.value=i.value,l.connectedData=i.connectedData),i.conditions!==null&&i.conditions!==void 0&&(l.conditions=i.conditions)),!l.locales&&!l.localesConditions&&!l.conditions&&l.value===void 0&&delete n.parameters[a]}),Object.entries(o.dataResources??{}).forEach(([a,i])=>{r?.(n,a,i,n._dataResources?.[a]),n._dataResources??={},n._dataResources[a]=i}),o.variant!==void 0&&(n.variant=o.variant),o.slots){n.slots??={};let a=Object.keys(o.slots)[0];n.slots[OB]??=[],n.slots[OB]=[...o.slots[a]??[]]}}})}import{CANVAS_SLOT_SECTION_SLOT as phe,CANVAS_SLOT_SECTION_TYPE as mhe}from"@uniformdev/canvas";var RB=({preserveOwnSlotSections:t=!1,preserveChildrenSlotSections:e=!1}={})=>r=>{if(r.node.type!==mhe)return;let{partOfPattern:n,partOfNestedPattern:o}=Qy(r.node._id??"");!n&&!o&&t||n&&!o&&e||ghe(r)},ghe=({node:t,type:e,actions:r})=>{e!=="entry"&&(r.insertAfter(t.slots?.[phe]??[]),r.remove())};import{walkNodeTree as yhe}from"@uniformdev/canvas";import{produce as xhe}from"immer";import{v4 as Che}from"uuid";import{CANVAS_SLOT_SECTION_SLOT as FB,walkNodeTree as hhe}from"@uniformdev/canvas";import{produce as vhe}from"immer";import{v4 as bhe}from"uuid";function e2(t,e,r,n=bhe()){if(!t._pattern)throw new Error("Not a pattern");let o={};return hhe(t,({node:a,ancestorsAndSelf:i,actions:l})=>{let s=a._id,u=e[s];if(i.length===1)a._id=n;else{let d=i[0];d.type!=="slot"||d.parentSlot!==FB?(a._id=LB(s),a._id=Jy(n,a._id)):(l.replace({...o[s],_id:o[s]._id}),l.stopProcessingDescendants())}if(u){let d=vhe(u,f=>{f.slots&&Object.entries(f.slots).forEach(([p,m])=>{if(p!==FB)throw new Error("Only slot section items are supported for duplication");m.forEach((h,g)=>{if(!h._id)return;let v=t2(h,e,r);o[h._id]=v,m[g]=v})})});r?.(a._id,d,s)}}),n}function t2(t,e,r){return xhe(t,n=>{yhe(n,({type:o,node:a,actions:{stopProcessingDescendants:i}})=>{o==="component"&&a._pattern?(e2(a,e,r),i()):a._id=Che()})})}import{produce as whe}from"immer";import{v4 as She}from"uuid";function BB(t,e=She()){return whe(t,r=>(r._pattern?e2(r,r._overrides??{},(n,o,a)=>{delete r._overrides[a],r._overrides[n]=o},e):r._id=e,r))}import{bindExpressionPrefix as VB}from"@uniformdev/canvas";var Ehe=new Set(["t","a","p","c"]),$he=new Set(["w","e","i"]);function jB(t){if(!t.startsWith(VB))return;let[r,n,...o]=t.substring(VB.length).split(":");if(r==="jptr"){if(!n)throw new Error(`Missing JSON pointer in dynamic token binding '${t}'`);let a="t",i="w",l;for(let s of o){let[u,c]=s.split("=");if(u==="fa"){if(!Ehe.has(c))throw new Error(`Invalid failure action '${c}' in dynamic token binding '${t}'`);a=c}else if(u==="fl"){if(!$he.has(c))throw new Error(`Invalid failure log level '${c}' in dynamic token binding '${t}'`);i=c}else if(u==="fd")l=Ihe(c);else throw new Error(`Unsupported property '${s}' in dynamic token binding '${t}'`)}return{pointer:zB(The(n)),syntax:r,failureAction:a,failureLogLevel:i,failureDefault:a==="t"?l:void 0}}throw new Error(`Unsupported dynamic token binding syntax '${r}'`)}function The(t){return t.replace(/\$\[([^}]+)\]/g,"${$1}")}function zB(t){let e=t.split("\\");return e.map((r,n)=>{if(r==="")return n>0&&e[n-1]===""?"":"\\";let o=r[0],a=r.substring(1);return o===";"&&(o=":"),a?o+a:o}).join("")}function Ihe(t){return zB(t.replace("\\+","="))}function HB(t){if(!t?.pointer)return;let e=t.pointer.indexOf("/",1);return e<0?{dataResource:t.pointer.substring(1)}:{dataResource:t.pointer.substring(1,e),dataExpression:t.pointer.substring(e)}}function r2({locale:t,conditionIndex:e,property:r}){if(t===void 0)if(e<0){if(delete r.value,!r.conditions?.length)return!1}else r.conditions?.splice(e,1);else e<0?delete r.locales?.[t]:r.localesConditions?.[t]?.splice(e,1);if(r.localesConditions){for(let[n,o]of Object.entries(r.localesConditions))if(o.length===0){delete r.localesConditions[n];break}Object.keys(r.localesConditions).length===0&&delete r.localesConditions}return r.locales&&Object.keys(r.locales).length===0&&delete r.locales,r.conditions&&r.conditions.length===0&&delete r.conditions,!!(r.value!==void 0||r.locales||r.conditions||r.localesConditions)}function mS({locale:t,conditionIndex:e,conditionDefinition:r,property:n,newPropertyValue:o}){t===void 0?e<0?n.value=o:(n.conditions??=[],WB(n.conditions,e,r,o)):e<0?(n.locales??={},n.locales[t]=o):(n.localesConditions??={},n.localesConditions[t]??=[],WB(n.localesConditions[t],e,r,o))}function WB(t,e,r,n){if(e<0)throw new Error("Condition index must be greater than or equal to 0");let o=t[e];t[e]={when:r??o?.when??{clauses:[]},value:n===void 0?null:n,id:o?.id??Dhe(t)}}function Dhe(t){let e=new Set(t.map(n=>n.id)),r=0;for(;e.has(r);)r++;return r}function GB(t){let e=!1,r={};return"_pattern"in t&&t._patternDataResources&&Object.entries(t._patternDataResources).forEach(([n,o])=>{e=!0,r[n]={...o,source:"patternDataResource"}}),t._dataResources&&Object.entries(t._dataResources).forEach(([n,o])=>{r[n]?r[n].isPatternParameter&&(e=!0,r[n]={...o,source:"dataResource"}):(e=!0,r[n]={...o,source:"dataResource"})}),e?r:void 0}import{CANVAS_DRAFT_STATE as Ahe,convertEntryToPutEntry as UJe,getPropertiesValue as KJe}from"@uniformdev/canvas";function UB(t){let{fields:e,entryName:r,type:n="contentType",thumbnailField:o,...a}=t;return{...a,titleParameter:r,thumbnailParameter:o,parameters:e,canBeComposition:n==="block",permissions:t.permissions,useTeamPermissions:t.useTeamPermissions??!0,workflowId:t.workflowId}}function ZB(t){return{id:t.id,name:t.name,entryName:t.titleParameter,thumbnailField:t.thumbnailParameter,fields:t.parameters,icon:t.icon,description:t.description,slugSettings:t.slugSettings,type:t.canBeComposition?"block":"contentType",created:t.created,updated:t.updated,permissions:t.permissions,useTeamPermissions:t.useTeamPermissions,workflowId:t.workflowId||void 0}}function eh(t){let{entry:{fields:e,...r},...n}=t;return{created:"",modified:"",composition:{_id:"",...r,_name:t.entry._name??"Untitled",parameters:e,_overridability:t.entry._overridability,_overrides:t.entry._overrides,_pattern:t.entry._pattern,_patternError:t.entry._patternError},pattern:!!t.pattern,previewImageUrl:t.entry._thumbnail,...n}}function YB(t,e,r,n,o,a,i){let l=i??e.projectId;if(!l)throw new Error("projectId is required in currentEntry or explicitly");return{created:e.created??"",modified:e.modified??"",projectId:l,state:n??e.state??Ahe,releaseId:o??e.releaseId,workflowId:r?.workflowId??e.workflowId,workflowStageId:r?.workflowStageId??e.workflowStageId,editionId:a,editionName:r?.editionName??e.editionName,editionPriority:r?.editionPriority??e.editionPriority,pattern:e.pattern,entry:{type:t.type,_id:t._id,_name:t._name,_slug:t._slug??"",fields:t.parameters,_thumbnail:r?.previewImageUrl??void 0,_dataResources:t._dataResources,_pattern:t._pattern,_patternError:t._patternError,_overridability:t._overridability,_overrides:t._overrides,_locales:t._locales,_author:t._author,_authorSubject:t._authorSubject,_creator:t._creator,_creatorSubject:t._creatorSubject,_patternDataResources:t._patternDataResources}}}function gS(t,e){let{parameters:r,...n}=t;return{...n,_id:e??n._id??"unknown",fields:r}}function hS(t){let{fields:e,...r}=t;return{...r,parameters:e}}function vS(t){let e=jB(t);if(e)switch(e.syntax){case"jptr":return HB(e);default:throw new Error(`Unsupported dynamic token binding syntax '${e.syntax}'`)}}import{CANVAS_VIZ_LOCALE_RULE as Lhe}from"@uniformdev/canvas";import{produce as _he}from"immer";function KB(t,e,r){let n=_he(t.criteria,o=>XB(o,e,r));return n&&{...t,criteria:n}}function XB(t,e,r){if(!t)return t;let n=!1;for(let o of t.clauses)if("clauses"in o){let a=XB(o,e,r);if(a===null){if(t.op!=="|")return null;t.clauses.splice(t.clauses.indexOf(o),1),n=!0}else a!==void 0&&(t.clauses[t.clauses.indexOf(o)]=a,n=!0)}else if(o.rule===Lhe){let a=Array.isArray(o.value)?o.value:[o.value],i=a.includes(e),l=a.includes(r);if(!i&&!l||i&&l)continue;if(a.length===1&&l&&!i)return null;i&&!l&&(o.value=a.concat(r),n=!0)}return n?t:void 0}var JB=B(cS(),1);function bS(t,e){try{return(0,JB.get)(t,e)}catch{return}}function yS(t,e,r=0){let n=t.slice(r*4,r*4+4);if(!n)throw new Error("Failed to generate a default variation name");return`${e.startsWith("$")?e.slice(1):e}-${n}`}import{CANVAS_VIZ_LOCALE_RULE as Mhe}from"@uniformdev/canvas";import{produce as Nhe}from"immer";function qB(t,e){let r=Nhe(t.criteria,n=>QB(n,e));return r&&{...t,criteria:r}}function QB(t,e){if(!t)return t;for(let r=t.clauses.length-1;r>=0;r--){let n=t.clauses[r];if("clauses"in n){let o=QB(n,e);if(o)t.clauses[r]=o;else if(t.clauses.splice(r,1),o===null&&t.op!=="|")return null}else if(n.rule===Mhe){let o=Array.isArray(n.value)?n.value:[n.value],a=o.indexOf(e);if(a!==-1)if(Array.isArray(n.value)&&n.value.length>1)o.splice(a,1);else if(n.op.startsWith("!"))t.clauses.splice(r,1);else return null}}if(t.clauses.length!==0)return t}function eV(t,e){let r=Nf();if(process.env.NODE_ENV==="development"&&!e){let n=new Error().stack?.split(`
5781
5781
  `).slice(2).join(`
5782
- `).trimStart();r.on("*",(o,a)=>{console.debug(`\u26A1\uFE0F ${t}:${String(o)}`,{args:a,stack:n,subs:r.all.get(String(o))?.length??0})})}return r}var Yo=(0,cV.default)(),Fhe=!0,Bhe="Twee",ii=class t{#e={};rootNodeId;#n={};#o={};#r;#a={};#t=eV(Bhe,Fhe);#u;#c;#g;#d;#s;#i;constructor(e,r){let{metadata:n,startDirty:o}=r||{};this.#s=n??{},this.#i={_name:e?._name??"",_slug:e?._slug??null},this.#d=!o;let a=wr(e,i=>{this.#v({composition:i,ignoreRootOverrides:!0,preserveChildrenSlotSections:!0}),delete i._author,delete i._authorSubject,delete i._creator,delete i._creatorSubject});this.rootNodeId=a._id??pl(),this.#u=this.rootNodeId,this.#l({componentTree:a,nodeId:this.rootNodeId}),this.#r=a._overrides??{}}events=this.#t;exportTree(e){return this.exportSubtree(this.rootNodeId,e)}exportMetadata(){return this.#s}exportRootNodeMetadata(){return this.#i}get pristine(){return this.#d}set pristine(e){this.#d!==e&&(this.#d=e,this.#t.emit("pristineChanged",{pristine:e}))}get selectedBlockIdStack(){return this.#c}set selectedBlockIdStack(e){this.#c=e,this.#t.emit("selectedBlockChanged",{selectedBlockIds:this.#c})}get selectedNodeId(){return this.#u}set selectedNodeId(e){this.#u!==e&&(this.#u=e,this.selectedParameterId=void 0,this.#t.emit("selectedNodeChanged",{selectedNodeId:e}))}get selectedParameterId(){return this.#g}set selectedParameterId(e){this.#g!==e&&(this.#g=e,this.#t.emit("selectedParameterChanged",{selectedParameterId:e}))}pushSelectedBlockId(e){this.selectedBlockIdStack=this.selectedBlockIdStack??[],this.selectedBlockIdStack?.push(e),this.#t.emit("selectedBlockChanged",{selectedBlockIds:this.selectedBlockIdStack})}popSelectedBlockId(){this.#c?.pop(),this.#t.emit("selectedBlockChanged",{selectedBlockIds:this.selectedBlockIdStack})}getNodeById(e){return this.#e[e]}getNodesIndex(){return this.#e}getBlockNodeValueById(e){return gS(this.exportSubtree(e),e)}getNodeChildren(e){let r=this.#n[e];if(r)return r}getNodeProperty(e,r){return bS(this.#o,[e,r])}getNodeProperties(e){return this.#o[e]??{}}insertNode({node:e,parentNodeId:r,parentSlot:n,targetIndexInSlot:o,overrideNodeId:a}){let i=a??pl();if(!this.#$(r))throw new Error("Cannot insert component into a read-only pattern slot unless it is within a slot section");let s={nodeId:i,parentId:r,value:t.#E(e),isExpandedInUI:!0,propertyValueLocalizability:{}};return this.#w({node:s,parentNodeId:r,parentSlot:n,targetIndexInSlot:o}),this.#m({nodeId:i,destinationParentId:r,destinationSlotName:n}),this.pristine=!1,this.#t.emit("nodeChanged",{changedNode:s,oldValue:void 0,type:"new"}),this.#t.emit("childrenChanged",{parentId:r,slotOrBlockName:n,newChildIds:this.#n[r][n],type:"slot"}),i}upsertBlockNode({nodeId:e,property:r,index:n,entry:o}){let a=this.#S({nodeId:e,property:r,index:n,entry:o});return this.pristine=!1,this.#t.emit("childrenChanged",{parentId:e,slotOrBlockName:r,newChildIds:this.#o[e]?.[r]?.value,type:"block"}),a}updateRootMetadata(e){let r={...this.#s};this.#s={...this.#s,...e},this.pristine=!1,this.#t.emit("metadataChanged",{metadata:this.#s,oldValue:r})}updateRootNode({update:e,doNotSetDirty:r}){let n={...this.#i};this.#i={...this.#i,...e},r||(this.pristine=!1),this.#t.emit("rootNodeMetadataChanged",{metadata:this.#i,oldValue:n})}insertPattern({parentNodeId:e,parentSlot:r,pattern:n,targetIndexInSlot:o,patternInstanceId:a}){let i=a??pl();if(this.#e[i])throw new Error(`Node with ID '${i}' already exists. Pattern nodes must have unique IDs. Did you mean to move or duplicate this pattern instead?`);let l=this.#y(n,i,!1);return this.#f({nodeId:l,parentNodeId:e,parentSlot:r,targetIndexInSlot:o}),this.#m({nodeId:l,destinationParentId:e,destinationSlotName:r}),this.pristine=!1,this.visitNodeAndDescendants(l,s=>{this.#t.emit("nodeChanged",{changedNode:s,oldValue:void 0,type:"new"})}),this.#t.emit("childrenChanged",{parentId:e,slotOrBlockName:r,newChildIds:this.#n[e][r],type:"slot"}),l}unlinkPattern(e){let r=this.#e[e];if(!r)throw new Error(`Node ${e} does not exist`);if(!r.value._pattern)throw new Error(`Node ${e} is not a pattern`);let n=r.value._patternDataResources||r.value._dataResources,o=GB(r.value),a=l=>{l.partOfNestedPattern||(this.updateNode({nodeId:l.nodeId,updateComponent:s=>{delete s._pattern,delete s._patternError,delete s._overrides},updateMetadata:s=>{delete s.partOfPattern,delete s.partOfNestedPattern},doNotSetDirty:!0,ignoreOverrides:!0}),this.#r[l.nodeId]&&(this.#r=wr(this.#r,s=>{delete s[l.nodeId]})))};this.visitNodeAndDescendants(e,a);let i=l=>{l.partOfNestedPattern&&this.updateNode({nodeId:l.nodeId,updateMetadata:s=>{s.partOfPattern=s.partOfNestedPattern,delete s.partOfNestedPattern},doNotSetDirty:!0,ignoreOverrides:!0})};this.visitNodeAndDescendants(e,i),n&&(this.updateNode({nodeId:this.rootNodeId,updateDataResources:l=>Object.entries(o??{}).filter(([s])=>!(s in(l??{}))).map(([s,u])=>{let{source:c,...d}=u;return{type:"set",name:s,value:d}})}),this.updateNode({nodeId:r.nodeId,updateComponent:l=>{delete l._patternDataResources},updateDataResources:"removeAll",doNotSetDirty:!0,ignoreOverrides:!0})),this.pristine=!1}convertToPattern({existingNodeId:e,pattern:r}){let n=this.#e[e],o=n?.parentId;if(!n)throw new Error(`Node ${e} does not exist`);let a=this.#y(r,e,!0);this.#e[a]=wr(this.#e[a],l=>{l.parentId=o}),this.pristine=!1;let i=this.#e[a];this.#t.emit("nodeChanged",{changedNode:i,oldValue:n,type:"new"}),Object.entries(this.#n[a]??{}).forEach(([l,s])=>{this.#t.emit("childrenChanged",{newChildIds:s,parentId:a,slotOrBlockName:l,type:"slot"})})}copyNodeToClipboard(e){let r=this.exportSubtree(e,{keepPatternData:!1}),n=this.exportSubtree(e,{keepPatternData:!0}),o=[];rs(n,({node:l})=>{l._id&&o.push(l._id)}),rs(r,({node:l})=>{l._id&&(l._overrides&&delete l._overrides,"_name"in l&&delete l._name,"_slug"in l&&delete l._slug)});let a=this.#h(),i=Object.entries(a??{}).reduce((l,[s,u])=>(o.some(c=>s.includes(c))&&(l[s]=u),l),{});return{format:"uniform/copied-component-subtree-1.0",componentData:r,overrides:Object.keys(i).length?i:void 0,pasteAs:this.getNodeById(e)?.isBlock?"block":void 0}}async pasteNodeFromClipboard({parentNodeId:e,parentSlot:r,targetIndexInParent:n,clipboard:o,resolvePattern:a}){let i=Yo(o),l=async u=>{u._pattern&&s.push((async()=>{let c=await a(u._pattern);if(!c){console.debug(`Pasted pattern ${u._pattern} not found, skipping`);return}let d=this.#x(c,u._id);Object.assign(u,d)})())},s=[];return rs(i.componentData,({node:u})=>{l(u)}),i.overrides&&Object.values(i.overrides).forEach(u=>{u.slots&&Object.values(u.slots).forEach(c=>{c.forEach(d=>{rs(d,({node:f})=>{l(f)})})})}),await Promise.all(s),this.#T(i.componentData,{parentId:e,parentName:r,parentType:o.pasteAs==="block"?"block":"slot",targetIndexInParent:n},i.overrides)}enableLocale(e){this.updateNode({nodeId:this.rootNodeId,updateComponent:r=>{let n=r;n._locales??=[];let o=[...new Set([...n._locales,...Array.isArray(e)?e:[e]])];n._locales=o}})}disableLocale(e){this.updateNode({nodeId:this.rootNodeId,updateComponent:o=>{let a=o;a._locales=a._locales?.filter(i=>i!==e)}});let r=[],n=o=>{this.getNodeProperty(o.nodeId,th)?.value===e&&!o.partOfPattern&&r.push(o.nodeId);let i=this.getNodeProperties(o.nodeId);Object.entries(i).forEach(([s,u])=>{let c=u;s!==fl&&(o.partOfPattern?this.isPatternPropertyOverridden(o.nodeId,s,e)&&this.resetPatternPropertyOverride(o.nodeId,s,e):(c?.localesConditions?.[e]?.forEach((d,f)=>{this.updateNodeProperty({nodeId:o.nodeId,property:s,value:void 0,source:"other",locale:e,conditionIndex:f,conditionDefinition:null})}),c?.locales?.[e]!==void 0&&this.updateNodeProperty({nodeId:o.nodeId,property:s,value:void 0,source:"other",locale:e,conditionIndex:-1})))});let l=this.getNodeProperty(o.nodeId,fl);if(l?.value){let s=qB(l.value,e);if(s===null)r.push(o.nodeId);else if(s===void 0||!Vr(l.value,s)){let u=!o.partOfPattern,c=oc(o.value._overridability,fl)==="yes";(u||c)&&this.updateNodeProperty({nodeId:o.nodeId,property:fl,value:s?()=>s:void 0,source:"other",locale:void 0,conditionIndex:-1})}}};this.visitNodeAndDescendants(this.rootNodeId,n),r.forEach(o=>{this.deleteNode(o)})}copyValuesToLocalePlan({sourceLocale:e,destinationLocale:r,doNotCopyDescendants:n=!1,startingNodeId:o=this.rootNodeId,specificPropertyId:a}){let i=new Map,l=u=>{if(u.value.type===khe&&!u.partOfPattern){let d=this.getNodeChildren(u.nodeId)?.[xS]??[],f=d.map(h=>this.getNodeProperty(h,th)),p=f.findIndex(h=>h?.value===r);if(p>=0){let h=d[p];ml(i,h).actions.push({type:"deleteLocalizedNode"})}let m=f.findIndex(h=>h?.value===e);if(m>=0){let h=d[m];ml(i,h).actions.push({type:"duplicateLocalizedNode",targetIndexInSlot:p})}}if(i.get(u.nodeId)?.actions.some(d=>d.type==="deleteLocalizedNode"))return;let c=a?{[a]:this.getNodeProperty(u.nodeId,a)}:this.getNodeProperties(u.nodeId);Object.entries(c).forEach(([d,f])=>{if(f===void 0)return;let p=!u.partOfPattern,m=oc(u.value._overridability,d)==="yes";if(!(p||m))return;if(d===fl){let S=KB(f.value,e,r);S===null?ml(i,u.nodeId).actions.push({type:"deleteLocalizedNode"}):S&&ml(i,u.nodeId).actions.push({type:"updateVisibilityCriteria",targetValue:S})}let g=f.locales?.[e],v=f.locales?.[r];(!g||!v||!Vr(g,v))&&(g!==void 0?ml(i,u.nodeId).actions.push({type:"copyPropertyValue",propertyId:d,sourceValue:g,targetValue:v,conditionIndex:-1}):v!==void 0&&ml(i,u.nodeId).actions.push({type:"deletePropertyValue",propertyId:d,sourceValue:g,targetValue:v,conditionIndex:-1}));let y=f.localesConditions?.[e],x=f.localesConditions?.[r];y?.forEach((S,E)=>{let $=f.localesConditions?.[r]?.[E];(!S||!$||!Vr(S,$))&&ml(i,u.nodeId).actions.push({type:"copyPropertyValue",propertyId:d,sourceValue:S.value,targetValue:$,conditionIndex:E,conditionDefinition:S.when})});let C=y?.length??0,w=x?.length??0;if(C<w){let S=ml(i,u.nodeId);for(let E=C;E<w;E++)S.actions.push({type:"deletePropertyValue",propertyId:d,sourceValue:y?.[E],targetValue:x?.[E],conditionIndex:E})}})},s=this.#e[o];if(!s)throw new Error(`Node ${o} does not exist`);return l(s),!a&&!n&&this.visitDescendants(s.nodeId,l),{nodePlans:Array.from(i.values()),sourceLocale:e,destinationLocale:r}}async copyValuesToLocaleExecute({resolvePattern:e,plan:{sourceLocale:r,destinationLocale:n,nodePlans:o}}){let a=`copyLocaleExecute: ${n}`;console.time(a);for(let{nodeId:i,actions:l}of o)for(let s of l)switch(s.type){case"copyPropertyValue":{let u=this.getNodeProperty(i,s.propertyId)?.type,c=s.sourceValue;u==="contentReference"&&(c=this.prepareContentReferenceWrite({nodeId:i,propertyId:s.propertyId,destinationLocale:n,conditionIndex:s.conditionIndex,sourceValue:s.sourceValue})),this.updateNodeProperty({nodeId:i,property:s.propertyId,source:"other",locale:n,value:()=>c,type:u,conditionIndex:s.conditionIndex,conditionDefinition:s.conditionDefinition});break}case"deletePropertyValue":{this.updateNodeProperty({nodeId:i,property:s.propertyId,source:"other",locale:n,value:void 0,conditionIndex:s.conditionIndex,conditionDefinition:null});break}case"deleteLocalizedNode":{this.deleteNode(i);break}case"duplicateLocalizedNode":{let u=await this.duplicateNode(i,e);this.updateNodeProperty({nodeId:u,locale:void 0,conditionIndex:-1,type:"localeSelect",property:th,source:"other",value:()=>n});let c=this.copyValuesToLocalePlan({sourceLocale:r,destinationLocale:n,startingNodeId:u});this.copyValuesToLocaleExecute({plan:c,resolvePattern:e}),s.targetIndexInSlot!==void 0&&this.moveNode({movedNodeId:u,parentNodeId:this.#e[i].parentId,parentSlot:xS,targetIndexInSlot:s.targetIndexInSlot});break}case"updateVisibilityCriteria":{this.updateNodeProperty({nodeId:i,property:fl,source:"other",locale:void 0,conditionIndex:-1,value:()=>s.targetValue});break}default:throw new Error(`Unhandled action type ${s.type}`)}console.timeEnd(a)}updateNode({nodeId:e,updateComponent:r,updateDataResources:n,updateMetadata:o,doNotSetDirty:a,ignoreOverrides:i}){let l=this.#e[e];if(!l)throw new Error(`Update target node ID ${e} did not exist!`);let s=wr(l,f=>{if(o&&(o(f),f.nodeId=e,f.value=l.value,f.parentId=l.parentId),r){if(r(f.value),"slots"in f.value)throw new Error("Do not set `slots` on a Twee node, insert child nodes instead.");if("parameters"in f.value)throw new Error("Do not set `parameters` on a Twee node, use updateProperties option instead.")}if(n){let p=typeof n=="function"?n(f.value._dataResources):n;if(p==="removeAll")delete f.value._dataResources;else for(let m of p){let h=i?!1:f.nodeId!==this.rootNodeId&&f.value._pattern;switch(m.type){case"set":h&&(this.#r=wr(this.#r,g=>{g[e]??={},g[e].dataResources??={},g[e].dataResources[m.name]=m.value})),f.value._dataResources??={},f.value._dataResources[m.name]=m.value;break;case"remove":h&&(this.#r=wr(this.#r,g=>{delete g[e]?.dataResources?.[m.name]})),delete f.value._dataResources?.[m.name];break;case"reset":{let g=this.#a[e]?.dataResources?.[m.name];f.value._dataResources&&(g&&Object.keys(g).length>0?f.value._dataResources[m.name]=g:delete f.value._dataResources[m.name]),this.#r=wr(this.#r,v=>{delete v[e]?.dataResources?.[m.name]})}break;default:throw new Error(`Unhandled data resource action ${m?.type}`)}}}}),u=!!(l.partOfPattern&&!l.value._patternError),c=l.value.variant!==s.value.variant,d=l.value._overridability?.variants??!1;!i&&u&&c&&d&&(this.#r=wr(this.#r,f=>{f[e]??={},f[e].variant=s.value.variant})),this.#e[e]=s,a||(this.pristine=!1),this.#t.emit("nodeChanged",{changedNode:s,type:"update",oldValue:l})}updateNodeProperty({nodeId:e,property:r,value:n,source:o,locale:a,type:i,doNotSetDirty:l=!1,ignoreOverrides:s=!1,conditionIndex:u,conditionDefinition:c}){let d=this.#e[e];if(!d)throw new Error(`Update target node ID ${e} did not exist!`);if(u<0&&c)throw new Error("Condition definition provided for non-conditional value");let f=!!(d.partOfPattern&&!d.value._patternError),p=[e,r],m=bS(this.#o,p);if(!m&&n==null)return;let h=sV({locale:a,property:m,conditionIndex:u}),g=a?m?.localesConditions?.[a]?.[u]:m?.conditions?.[u],v=typeof n=="function"?wr(h,S=>n(S)):n,y=i??m?.type;if(!y)throw new Error(`Cannot add parameter ${r} to node ${e} without specifying a type`);let x={...m,type:y},C=!1;x=wr(x,S=>{v===void 0&&u<0?C=!r2({locale:a,property:S,conditionIndex:u}):c===null&&u>=0?C=!r2({locale:a,property:S,conditionIndex:u}):mS({locale:a,property:S,newPropertyValue:v,conditionIndex:u,conditionDefinition:c??g?.when??{clauses:[]}})}),C&&(x=void 0);let w=f&&oc(d.value._overridability,r)==="yes";if(f&&!w&&!s)throw new Error(`Cannot override parameter ${r} on node ${e} because it is not marked as overridable on the pattern (${d.partOfPattern})`);if(w&&(this.#a[e]?.parameters?.[r]||(this.#a=wr(this.#a,E=>{E[e]??={parameters:{},dataResources:{}},E[e].parameters[r]=m??{type:y,value:null}}))),!s&&w){let S=this.#r[e]?.parameters?.[r];this.#r=wr(this.#r,E=>{let T=v==null||x===void 0?null:v,D=S??{type:x?.type??m?.type??"unknown",value:m?.value,conditions:m?.conditions,locales:a&&m?.locales?.[a]?{[a]:m.locales[a]}:void 0,localesConditions:a&&m?.localesConditions?.[a]?{[a]:m.localesConditions[a]}:void 0},L=wr(D,k=>{c===null&&u>=0?r2({locale:a,property:k,conditionIndex:u}):mS({locale:a,property:k,newPropertyValue:T,conditionIndex:u,conditionDefinition:c??g?.when??{clauses:[]}})});(0,ac.set)(E,`/${e}/parameters/${r}`,L)}),S||this.#t.emit("propertyOverrideCreated",{nodeId:e,property:r})}v===null?(0,ac.remove)(this.#o,p):(this.#o[e]??={},(0,ac.set)(this.#o,p,x)),l||(this.pristine=!1),this.#t.emit("nodeParameterChanged",{nodeId:e,parameter:r,locale:a,conditionIndex:u,value:x,previousValue:m,type:n?m?"update":"new":"delete",conditionDefinition:c,source:o})}isPatternPropertyOverridden(e,r,n,o){let a=this.getNodeById(e);if(!a||oc(a.value._overridability,r)==="no")return!1;let i=this.#r[e]?.parameters?.[r];return i?n?(o===void 0||o===!0)&&i.localesConditions?.[n]!==void 0||(o===void 0||o===!1)&&i.locales?.[n]!==void 0:(o===void 0||o===!0)&&i.conditions!==void 0||(o===void 0||o===!1)&&i.value!==void 0:!1}getPatternPropertyOverrideDefaultValue(e,r,n){let o=this.#a[e]?.parameters?.[r];if(!o)return{exists:!1};if(n&&o.locales?.[n])return{exists:!0,value:o,sourceLocale:n};if(o.value!==void 0)return{exists:!0,value:o,sourceLocale:void 0};let a=Object.keys(o.locales??{})[0];return a?{exists:!0,value:o,sourceLocale:a}:{exists:!1}}resetPatternPropertyOverride(e,r,n){let o=[-1];this.#r=wr(this.#r,i=>{let l=i[e]?.parameters?.[r];if(l)if(n){delete l.locales?.[n];let s=l.localesConditions?.[n];s&&(s.forEach((u,c)=>{o.push(c)}),delete l.localesConditions?.[n]),l.locales&&Object.keys(l.locales).length===0&&delete l.locales,l.localesConditions&&Object.keys(l.localesConditions).length===0&&delete l.localesConditions,Object.keys(l.locales??{}).length===0&&Object.keys(l.localesConditions??{}).length===0&&delete i[e]?.parameters?.[r]}else{let s=l.conditions;s&&s.forEach((u,c)=>{o.push(c)}),delete i[e].parameters?.[r]}});let a=this.getPatternPropertyOverrideDefaultValue(e,r,n);!a.exists||a.value===null?this.updateNodeProperty({nodeId:e,property:r,value:void 0,source:"reset",locale:n,ignoreOverrides:!0,doNotSetDirty:!1,conditionIndex:-1}):o.forEach(i=>{let l=sV({locale:a.sourceLocale,property:a.value,conditionIndex:i,strict:!0});this.updateNodeProperty({nodeId:e,property:r,value:l===void 0?void 0:()=>l,source:"reset",locale:n,type:a.value?.type,ignoreOverrides:!0,doNotSetDirty:!1,conditionIndex:i,conditionDefinition:(n?a.value?.localesConditions?.[n]?.[i]?.when:a.value?.conditions?.[i]?.when)??null})}),this.#t.emit("propertyOverrideReset",{nodeId:e,property:r,usedPatternDefault:a!==void 0})}async duplicateNode(e,r){let n=this.getParentInfo(e);if(!n)throw new Error("Cannot duplicate root node or parentless block");let o=this.copyNodeToClipboard(e);return await this.pasteNodeFromClipboard({parentNodeId:n.parentId,parentSlot:n.parentName,resolvePattern:r,targetIndexInParent:n.targetIndexInParent+1,clipboard:o})}moveNode({movedNodeId:e,parentNodeId:r,parentSlot:n,targetIndexInSlot:o}){if(!this.#e[e])throw new Error(`Cannot move node ${e} - it does not exist`);let i=this.getParentInfo(e);if(!i)throw new Error("Cannot move root node");this.#n[i.parentId][i.parentName].splice(i.targetIndexInParent,1),this.#b(i.parentId,e),this.#f({nodeId:e,parentNodeId:r,parentSlot:n,targetIndexInSlot:o}),this.#m({nodeId:e,destinationParentId:r,destinationSlotName:n,sourceSlotName:i.parentName}),this.pristine=!1,this.#t.emit("childrenChanged",{parentId:r,slotOrBlockName:n,newChildIds:this.#n[r][n],type:"slot"}),this.#t.emit("childrenChanged",{parentId:i.parentId,slotOrBlockName:i.parentName,newChildIds:this.#n[i.parentId][i.parentName],type:"slot"})}deleteNode(e,r){let n=this.getParentInfo(e);if(!n&&!r)throw new Error("Cannot delete root node");n&&!r&&(this.#n[n.parentId][n.parentName].splice(n.targetIndexInParent,1),this.#n[n.parentId][n.parentName].length===0&&delete this.#n[n.parentId][n.parentName],this.selectedNodeId===e&&(this.selectedNodeId=n.parentId),this.#b(n.parentId,e),this.#t.emit("childrenChanged",{parentId:n.parentId,slotOrBlockName:n.parentName,newChildIds:this.#n[n.parentId][n.parentName]??[],type:"slot"})),delete this.#e[e],this.#t.emit("nodeDeleted",{deletedNodeId:e}),this.pristine=!1}#b(e,r){this.#r=wr(this.#r,n=>{let o=n[e]?.slots;o&&Object.keys(o).forEach(a=>{o[a]=o[a].filter(({_id:i})=>i!==r),o[a].length===0&&delete o[a]})})}#h(){if(Object.keys(this.#r).length>0){let e=Yo(this.#r);return Object.entries(e).forEach(([n,o])=>{let a=!0;if(!this.#e[n]){delete e[n];return}if(o.parameters){let i=Object.entries(o.parameters);i.forEach(([l,s])=>{let u=uV(s);u?(o.parameters[l]=u,a=!1):delete o.parameters[l]}),i.length===0&&delete o.parameters}o.slots&&Object.entries(o.slots).forEach(([l,s])=>{if(s.length){let u=s.filter(c=>c._id).map(c=>this.exportSubtree(c._id));u?(o.slots[l]=u,a=!1):delete o.slots[l]}else delete o.slots[l]}),o.variant!==void 0&&(a=!1),o.dataResources&&Object.keys(o.dataResources).length>0&&(a=!1),a&&delete e[n]}),Object.keys(e).length===0&&(e=void 0),e}}exportSubtree(e,r){let{keepPatternData:n=!1}=r??{},o=this.#e[e];if(!o)throw new Error(`Node ${e} to export is not found`);let a=Yo(o);if(e===this.rootNodeId){let s=this.#h();s?a.value._overrides=s:delete a.value._overrides;let u=a.value;u._name=this.#i._name,this.#i._slug&&(u._slug=this.#i._slug)}let i=[a],l=new Set;for(;i.length>0;){let s=i.pop();if(l.has(s.nodeId))throw new Error("Circular reference detected in the composition tree with node ID "+s.nodeId);if(l.add(s.nodeId),s.value._id=s.nodeId,!n&&(delete s.value._patternDataResources,delete s.value._patternOverrides,s.value._pattern&&s.value._dataResources)){let d=!1;Object.keys(s.value._dataResources).forEach(f=>{a.value._overrides?.[s.nodeId]?.dataResources?.[f]?delete s.value._dataResources[f]:d=!0}),d||delete s.value._dataResources}let u=this.#o[s.nodeId];if(u&&(n||!s.partOfPattern)){let d={},f=!1;Object.entries(u).forEach(([p,m])=>{if(m?.type===ba&&Array.isArray(m.value)){let h=m.value,g=[];h.forEach(v=>{let y=this.exportSubtree(v,r);g.push(gS(y,v))}),d[p]={value:g,type:ba},f=!0}else{let h=uV(m);h&&(d[p]=h,f=!0)}}),f&&(s.value.parameters=d)}let c=this.#n[s.nodeId];!c||s.partOfPattern&&!n||Object.entries(c).forEach(([d,f])=>{f.forEach((p,m)=>{let h=this.#e[p];if(!h)throw new Error("Insanity detected.");let g=Yo(h),v=s.value;v.slots=v.slots||{},(0,ac.set)(s,["value","slots",d,m.toString(10)],g.value),i.push(g)})})}return this.#A(a.value),a.value}#w({parentNodeId:e,parentSlot:r,targetIndexInSlot:n,node:o}){if(!this.#e[e])throw new Error("Parent ID to insert under did not exist!");if(this.#e[o.nodeId])throw new Error(`Node with ID '${o.nodeId}' already exists. Nodes must have unique IDs. Did you mean to move or duplicate this node instead?`);this.#e[o.nodeId]=o,this.#f({nodeId:o.nodeId,parentNodeId:e,parentSlot:r,targetIndexInSlot:n})}#f({nodeId:e,parentNodeId:r,parentSlot:n,targetIndexInSlot:o}){let a=this.#e[r],i=this.#n[r]??={},l=i[n]??=[];typeof o<"u"?l.splice(o,0,e):l.push(e),a?.value.type===n2&&(this.#r=wr(this.#r,s=>{s[r]=s[r]??{},s[r].slots={[Phe]:l.map(u=>({_id:u,type:this.#e[u].value.type}))}})),this.#e[e]=wr(this.#e[e],s=>{s.parentId=r})}#S({nodeId:e,property:r,index:n,entry:o}){let a=this.getNodeById(e);if(!a)throw new Error("Node doesn't exist");let l={nodeId:o._id??pl(),value:{type:o.type,_dataResources:o._dataResources},isBlock:!0,parentId:e,propertyValueLocalizability:{}},s=this.getNodeProperty(a.nodeId,r);if(s&&s.type!==ba)throw new Error("Parameter already exists and isn't a block parameter");let u=this.#e[l.nodeId];this.#e[l.nodeId]=l;let c=Yo(this.getNodeProperty(a.nodeId,r)?.value?.filter(d=>this.getNodeById(d))??[]);if(typeof n<"u"){if(n<0)throw new Error("parameter index cannot be less than 0");let d=-1;if(c.forEach((f,p)=>{f===l.nodeId&&(d=p)}),n>c.length+(d===-1?1:0))throw new Error(`Parameter index ${n} outside current index bounds.`);d>-1&&d!==n&&(c=c.filter(f=>f!==l.nodeId),c.splice(n,0,l.nodeId))}else c.push(l.nodeId);return Object.entries(o?.fields??{}).forEach(([d,f])=>{if(f.type===ba&&Array.isArray(f.value)){let p=f.value,m=[];p.forEach(h=>{let g=h._id??pl();this.#l({nodeId:g,componentTree:hS(h)}),this.#e[g].isBlock=!0,this.#e[g].parentId=l.nodeId,m.push(g)}),this.updateNodeProperty({nodeId:l.nodeId,property:d,type:f.type,value:()=>m,source:"other",locale:void 0,conditionIndex:-1})}else this.updateNodeProperty({nodeId:l.nodeId,property:d,type:f.type,value:()=>f.value,source:"other",locale:void 0,conditionIndex:-1})}),this.updateNodeProperty({nodeId:a.nodeId,property:r,type:ba,value:()=>c,source:"other",locale:void 0,conditionIndex:-1}),this.#t.emit("nodeChanged",{changedNode:a,oldValue:void 0,type:u?"update":"new"}),this.#t.emit("nodeParameterChanged",{nodeId:a.nodeId,parameter:r,previousValue:s,source:"other",type:u?"update":"new",locale:void 0,conditionIndex:-1,conditionDefinition:void 0,value:{type:ba,value:c}}),{blockIds:c}}#l({componentTree:e,nodeId:r,partOfPattern:n,partOfNestedPattern:o,resetUids:a,isBlock:i,allowReplacement:l}){let{slots:s,parameters:u,_id:c,_overrides:d,...f}=e,p=n??f._pattern,m=f._pattern&&f._pattern!==p?f._pattern:o,h=r??(a?void 0:c)??pl();if(this.#e[h]&&!l)throw new Error(`Node with ID '${h}' already exists. Nodes must have unique IDs.`);let g={nodeId:h,value:f,partOfPattern:p,partOfNestedPattern:m,isBlock:i,propertyValueLocalizability:Object.entries(u??{}).reduce((v,[y,x])=>(v[y]=Gh({definition:void 0,currentValue:x,lastUserChoice:void 0}),v),{})};return p&&(g.partOfPattern=p),this.#e[g.nodeId]=g,u&&Object.entries(u).forEach(([v,y])=>{let{connectedData:x,...C}=y,w=x?iV(aV(x)):y.value;if(y?.type===ba&&Array.isArray(w)){let S=w,E=[];S?.forEach($=>{let T={...$,_id:a?pl():$._id??pl()};if(this.#e[T._id])throw new Error(`Block node with ID '${T._id}' already exists. Block nodes must have unique IDs.`);return E.push(T._id),this.#e[T._id]={nodeId:T._id,value:{type:ba},propertyValueLocalizability:{}},this.#l({componentTree:hS(T),nodeId:T._id,allowReplacement:!0}),this.#e[T._id].isBlock=!0,this.#e[T._id].parentId=g.nodeId,this.#e[T._id]}),w=E}this.#o[g.nodeId]=this.#o[g.nodeId]??{},(0,ac.set)(this.#o,[g.nodeId,v],{...C,value:w})}),s&&Object.entries(s).forEach(([v,y])=>{let x=y.map(C=>{if(this.#e[C._id??""]?.isBlock)return;let w=this.#l({componentTree:C,partOfPattern:f.type===n2?void 0:p,partOfNestedPattern:f.type===n2?void 0:m,resetUids:a});return this.#e[w].parentId=g.nodeId,w});this.#n[g.nodeId]=this.#n[g.nodeId]??{},this.#n[g.nodeId][v]=x.filter(C=>C)}),g.nodeId}#y(e,r,n){let o=this.#x(e,r);return this.#l({componentTree:o,nodeId:r,allowReplacement:n})}#x(e,r){let n=Yo(e);return this.#v({composition:n}),qy(n,r),n._pattern=e._id,delete n._id,delete n._name,delete n._slug,delete n._overrides,delete n._locales,delete n._author,delete n._authorSubject,delete n._creator,delete n._creatorSubject,n._dataResources&&(n._patternDataResources=Yo(n._dataResources),delete n._dataResources),n}getParentInfo(e){let{parentId:r,isBlock:n}=this.#e[e]??{};if(!r)return;let o=this.#e[r];if(o)if(n)for(let[a,i]of Object.entries(this.#o[r]??{})){if(i?.type!==ba)continue;let l=Array.isArray(i.value)?i.value:[],s=l.indexOf(e);if(s>=0)return{value:o.value,parentId:r,parentName:a,targetIndexInParent:s,parentChildIds:l,parentType:"block"}}else{let a=this.#n[r];if(!a&&!n)throw new Error("Sanity failed; parent had no children!");for(let[i,l]of Object.entries(a??{})){let s=l.indexOf(e);if(s>=0)return{value:o.value,parentId:r,parentName:i,targetIndexInParent:s,parentChildIds:l,parentType:"slot"}}return}}static#E(e){return wr(e,n=>{delete n.slots,delete n.parameters})}#$(e){let r=e;for(;r;){let n=this.getNodeById(r);if(!n)break;if(n.value._pattern)return!1;if(n.value.type===n2||!n.partOfPattern)return!0;r=n.parentId}return!0}#T(e,r,n){let a={...this.#h(),...n},i;if(this.#r=wr(this.#r,s=>{this.#a=wr(this.#a,u=>{i=t2(e,a,(c,d,f)=>{s[c]=d,u[c]=this.#a[f]})})}),!i)throw new Error("Failed to duplicate component");i=wr(i,s=>{s._overrides=Yo(this.#r),this.#v({composition:s,preserveChildrenSlotSections:!0})});let l=this.#l({componentTree:i,isBlock:r.parentType==="block"});if(r.parentType==="block"){let s=this.getNodeProperty(r.parentId,r.parentName)?.value??[],u=[...s.slice(0,r.targetIndexInParent),l,...s.slice(r.targetIndexInParent)];this.updateNodeProperty({nodeId:r.parentId,property:r.parentName,type:ba,value:()=>u,locale:void 0,conditionIndex:-1,source:"other"}),this.#e[l].parentId=r.parentId,this.#t.emit("nodeChanged",{changedNode:this.getNodeById(l),type:"new",oldValue:void 0}),this.#t.emit("childrenChanged",{parentId:r.parentId,slotOrBlockName:r.parentName,newChildIds:u,type:"block"})}else{this.#f({nodeId:l,parentNodeId:r.parentId,parentSlot:r.parentName,targetIndexInSlot:r.targetIndexInParent}),this.#m({nodeId:l,destinationParentId:r.parentId,destinationSlotName:r.parentName}),this.#t.emit("childrenChanged",{parentId:r.parentId,slotOrBlockName:r.parentName,newChildIds:this.#n[r.parentId][r.parentName],type:"slot"});let s=u=>{this.#t.emit("nodeChanged",{changedNode:u,type:"new",oldValue:void 0})};this.visitNodeAndDescendants(l,s)}return this.pristine=!1,l}#v({composition:e,ignoreRootOverrides:r,preserveChildrenSlotSections:n}){this.#a=wr(this.#a,a=>{let i=pS({beforeApplyParameterOverride(u,c,d){a[u._id]??={parameters:{},dataResources:{}},a[u._id].parameters[c]=Yo(d)},beforeApplyDataResourceOverride(u,c,d){u._dataResources?.[c]?.ignorePatternParameterDefault||(a[u._id]??={parameters:{},dataResources:{}},a[u._id].dataResources[c]=Yo(d))}}),l=pS({beforeApplyParameterOverride(u,c,d,f){a[u._id]?.parameters[c]||(a[u._id]??={parameters:{},dataResources:{}},a[u._id].parameters[c]=Yo(f??null))},beforeApplyDataResourceOverride(u,c,d,f){u._dataResources?.[c]?.ignorePatternParameterDefault||a[u._id]?.dataResources[c]||(a[u._id]??={parameters:{},dataResources:{}},a[u._id].dataResources[c]=Yo(f))}});if(r){let{_overrides:u,...c}=e;rs(c,({node:d})=>{i.visitNode(d)})}let s=r?l:i;rs(e,({node:u})=>{s.visitNode(u)})});let o=RB({preserveOwnSlotSections:!0,preserveChildrenSlotSections:n});rs(e,a=>{o(a)})}visitNodeAndDescendants(e,r){let n=this.getNodeById(e);if(!n)throw new Error("Insanity detected.");r(n),this.visitDescendants(e,r)}visitDescendants(e,r){let n=this.#p(e,new Set);for(let o of n)r(...o)}async visitDescendantsAsync(e,r){let n=this.#p(e,new Set);for(let o of n)await r(...o)}*#p(e,r){let n=this.#e[e],o=this.#n[e]??{},a=Object.entries(this.#o[e]??{}).filter(([,i])=>i?.type===ba)??[];if(!n)throw new Error("Insanity detected.");r.add(e);for(let[i,l]of a){let s=l.value??[];for(let u=0;u<s.length;u++){let c=s[u],d=this.#e[c];if(d){if(r.has(c)){console.error(`Detected parent/child cycle in composition, ID ${c} exists more than once. The traversal of descendants will be aborted for the cycle subtree.`);continue}yield[d,n,i,u];for(let f of this.#p(c,r))yield f}}}for(let[i,l]of Object.entries(o))for(let s=0;s<l.length;s++){let u=l[s],c=this.#e[u];if(c){if(r.has(u)){console.error(`Detected parent/child cycle in composition, ID ${u} exists more than once. The traversal of descendants will be aborted for the cycle subtree.`);continue}yield[c,n,i,s];for(let d of this.#p(u,r))yield d}}}#m({nodeId:e,destinationParentId:r,destinationSlotName:n,sourceSlotName:o}){let a=n,i=o===rV,l=a===rV,s=o===nV,u=a===nV,c=a===xS,d=this.getNodeProperty(e,tV);l&&d&&this.updateNodeProperty({nodeId:e,property:tV,value:void 0,source:"other",locale:void 0,conditionIndex:-1});let f=this.getNodeProperty(e,rh);!l&&f&&this.updateNodeProperty({nodeId:e,property:rh,value:void 0,source:"other",locale:void 0,conditionIndex:-1}),l&&!i&&this.#C({nodeId:e,siblingIds:this.getNodeChildren(r)?.[n]??[],selectExistingName:h=>this.getNodeProperty(h,rh)?.value?.name,setName:h=>this.updateNodeProperty({nodeId:e,property:rh,value:g=>g&&typeof g=="object"&&g!==null?{...g,name:h}:{name:h,crit:[]},source:"other",locale:void 0,conditionIndex:-1,type:rh})}),u&&!s&&this.#C({nodeId:e,siblingIds:this.getNodeChildren(r)?.[n]??[],selectExistingName:h=>this.getNodeProperty(h,oV)?.value?.id,setName:h=>this.updateNodeProperty({nodeId:e,property:oV,value:g=>g&&typeof g=="object"&&g!==null?{...g,id:h}:{id:h},source:"other",locale:void 0,conditionIndex:-1,type:"testVariant"})});let p=this.getNodeProperty(e,th);!c&&p&&this.updateNodeProperty({nodeId:e,property:th,value:void 0,source:"other",locale:void 0,conditionIndex:-1});let m=this.getNodeProperty(e,fl);(l||c||u)&&m&&this.updateNodeProperty({nodeId:e,property:fl,value:void 0,source:"other",locale:void 0,conditionIndex:-1})}#C({nodeId:e,siblingIds:r,selectExistingName:n,setName:o}){let a=n(e),i=d=>r.some(f=>f===e?!1:n(f)===d),l=a&&i(a);if(a&&!l)return;let s=this.getNodeById(e)?.value.type;if(!s)throw new Error("Insanity detected.");let u=0,c=yS(e,s,u);do c=yS(e,s,u),u++;while(i(c));o(c)}prepareContentReferenceWrite({nodeId:e,propertyId:r,destinationLocale:n,conditionIndex:o,sourceValue:a}){let i=this.#I({value:a,dataResources:this.#e[e]?.value._dataResources});if(!i)return a;let{dataResource:l,isSingleEntryReference:s}=i,u=mc(e,r,n==="${locale}"?void 0:n,o);this.updateNode({nodeId:e,updateDataResources:[{name:u,type:"set",value:{...l,variables:{...l?.variables,locale:n}}}]});let c=`/${u}/entries${s?"/0":""}`;return iV(aV({syntax:"jptr",pointer:c}))}#I({value:e,dataResources:r}){if(typeof e!="string")return;let n;lV(e,(l,s)=>{s==="variable"&&(n=l)});let o=n?vS(n):void 0;if(!o)return;let a=o.dataResource,i=r?.[a];if(i)return{dataResource:i,dataResourceName:a,isSingleEntryReference:o.dataExpression?.endsWith("/0")}}#D(e){if(typeof e!="string")return;let r;return lV(e,(o,a)=>{a==="variable"&&(r=o)}),(r?vS(r):void 0)?.dataResource}#A(e){let r=new Set,n=[],o=({node:a})=>{let i=Ohe(a),l=a._dataResources;if(l)for(let[s,u]of Object.entries(l))u.type===ci&&n.push({dataResources:l,dataResourceKey:s});if(i)for(let s of Object.values(i))s.type==="contentReference"&&Rhe(s,({value:u})=>{let c=this.#D(u);c&&r.add(c)})};if(rs(e,o),"_overrides"in e&&e._overrides)for(let[,a]of Object.entries(e._overrides))rs({type:e.type,...a,_dataResources:a.dataResources},o);for(let{dataResources:a,dataResourceKey:i}of n)r.has(i)||delete a[i]}};function uV(t){return t?.value===void 0&&!t?.conditions&&!t?.locales&&!t?.localesConditions?null:t}function ml(t,e){return Vhe(t,e,()=>({nodeId:e,actions:[]}))}function Vhe(t,e,r){return t.has(e)||t.set(e,r()),t.get(e)}import{CANVAS_DRAFT_STATE as i2,CanvasClient as Whe}from"@uniformdev/canvas";import{ProjectMapClient as Ghe}from"@uniformdev/project-map";import{produce as Uhe}from"immer";function dV(t){return t.reduce((e,r)=>(e[r._id]={id:r._id,type:r.type,name:r._name},e),{})}import{CANVAS_DRAFT_STATE as fV,CanvasClient as CS,ContentClient as pV,ProjectClient as mV}from"@uniformdev/canvas";function gV(t){let e,r,n;return{fetchProjectGuidance:async()=>(e!==void 0||(e=(await new mV(t).get({projectId:t.projectId}))?.guidance),e),fetchDefinitions:async()=>{if(r!==void 0)return r;let a=await new CS(t).getComponentDefinitions({limit:1e3,includeSystem:!0});return r=Object.fromEntries(a.componentDefinitions.map(i=>[i.id,i])),r},fetchPatterns:async()=>{if(n!==void 0)return n;let a=await new CS(t).getCompositionList({limit:1e3,pattern:!0,patternType:"component",resolveData:!1,skipPatternResolution:!0,skipOverridesResolution:!0,state:fV});return n=dV(a.compositions.map(i=>i.composition)),n},resolvePatternData:async o=>(await new CS(t).getCompositionById({compositionId:o,state:fV,skipPatternResolution:!1,skipOverridesResolution:!0,withComponentIDs:!0,skipDataResolution:!0,withWorkflowDefinition:!0,releaseId:void 0}))?.composition,getToolClient:async()=>t.toolInvoker,getDimensionGuidance:async()=>{}}}function hV(t){let e,r;return{fetchProjectGuidance:async()=>(e!==void 0||(e=(await new mV(t).get({projectId:t.projectId}))?.guidance),e),fetchDefinitions:async()=>{if(r!==void 0)return r;let o=await new pV(t).getContentTypes({limit:1e3});return r=Object.fromEntries(o.contentTypes.map(a=>[a.id,UB(a)])),r},fetchPatterns:async()=>({}),resolvePatternData:async n=>{let a=(await new pV(t).getEntries({entryIDs:[n],skipPatternResolution:!1,skipOverridesResolution:!0,withComponentIDs:!0,skipDataResolution:!0,withWorkflowDefinition:!0,releaseId:void 0}))?.entries[0];return eh(a).composition},getToolClient:async()=>t.toolInvoker,getDimensionGuidance:async()=>{}}}import{parseHTML as jhe}from"linkedom/worker";function zhe(t){let e=Object.getPrototypeOf(t.body);for(;e&&!Object.getOwnPropertyDescriptor(e,"style");)e=Object.getPrototypeOf(e);let r=e?Object.getOwnPropertyDescriptor(e,"style"):void 0;if(!r?.get||e.__stylePatched)return;let n=r.get;Object.defineProperty(e,"style",{get(){let o=n.call(this);return new Proxy(o,{get(a,i){if(typeof i=="string"){let l=a[i];return typeof l=="function"?l.bind(a):l===void 0?"":l}return a[i]},set(a,i,l){return a[i]=l,!0}})},configurable:!0}),e.__stylePatched=!0}function o2(t){let e=`<!DOCTYPE html><html><body>${t}</body></html>`,{document:r}=jhe(e);return zhe(r),r}import{LocaleClient as Hhe}from"@uniformdev/canvas";async function a2(t,e){if(!t||t.length===0)return;let o=(await new Hhe(e).get()).results.map(i=>i.locale),a=t.filter(i=>!o.includes(i));if(a.length>0)throw new Error(`The following locales are not registered in your project: ${a.join(", ")}`)}async function s2({action:t,id:e,instructions:r,isPattern:n,patternId:o,projectMapNode:a,getEditUrl:i,env:l}){let s=new Whe(l),u,c,d=t==="update"?e:void 0,f={success:!0,actionsTaken:[]};if(t==="duplicate"){if(c=await s.getCompositionById({compositionId:e,state:i2,skipDataResolution:!0,skipPatternResolution:!1,withComponentIDs:!0,skipOverridesResolution:!0}),!c)throw new Error("Composition not found");let p=crypto.randomUUID(),m=BB(c.composition,p),h=Uhe(m,g=>{g._name=`${g._name} (copy)`,g._slug&&(g._slug=`${g._slug}-copy${g._slug?.endsWith("/")?"/":""}`)});u=new ii(h),e=p}else if(t==="create"){if(!r)throw new Error("Instructions are required for create");if(!r.name)throw new Error("Name is required for create");if(!r.type)throw new Error("Type is required for create");if(!o)u=new ii({_id:e,_name:r.name,type:r.type,_overridability:{hideLockedParameters:!0}});else{let p={composition:{_id:e,_name:r.name,type:r.type,_pattern:o},projectId:l.projectId,state:i2,pattern:!1};await s.updateComposition(p),d=e}}if(d){if(c=await s.getCompositionById({compositionId:e,state:i2,skipDataResolution:!0,skipPatternResolution:!1,withComponentIDs:!0,skipOverridesResolution:!0}),!c)throw new Error("Composition not found");u=new ii(c.composition)}if(t==="delete"&&await s.removeComposition({compositionId:e}),u){await a2(r?.localeUpdates?.enableLocales,l),f=await Xy({twee:u,descriptionUpdate:void 0,slugUpdate:void 0,nameUpdate:r?.name,propertyUpdates:r?.parameterUpdates??[],dataResourceUpdates:r?.dataResourceUpdates??[],localeUpdates:r?.localeUpdates,slotUpdates:r??{},currentEditorLocale:void 0,referenceData:gV(l),isEditingPattern:n,domParser:o2});let p=u.exportTree(),m=u.exportMetadata(),h={composition:p,projectId:l.projectId,state:i2,pattern:n,releaseId:c?.releaseId,editionId:c?.editionId,...m};await s.updateComposition(h)}if(t==="create"&&!n&&(a?.nodePathSegment||a?.localePathSegments)&&r?.name){let p=new Ghe({apiKey:l.apiKey,apiHost:l.apiHost,projectId:l.projectId}),{path:m,nodeId:h}=await EB({projectMapClient:p,compositionId:e,compositionName:r.name,nodePathSegment:a.nodePathSegment||"",parentNodeId:a.parentNodeId,localePathSegments:a.localePathSegments,allowedQueryStrings:a.allowedQueryStrings});return f.actionsTaken.push({success:!0,summary:`Created project map node at path: ${m}`}),{content:[{type:"text",text:JSON.stringify({...f,editUrl:i(e),projectMapNode:{path:m,nodeId:h}},null,2)}]}}return{content:[{type:"text",text:JSON.stringify({...f,editUrl:i(e)},null,2)}]}}function l2(t,e){return`${e.baseWebUrl}/dashboards/canvas/edit/${t}`}async function u2(t,e,r){return await r.toolInvoker.invoke("createFilterExpression",{...t,entityType:e})}var Zhe={action:en.enum(["create","update","delete","duplicate"]).describe("The action to perform"),id:en.string().uuid().describe("UUID of the composition instance to create, update, delete, or duplicate"),patternId:en.string().uuid().describe("Composition pattern ID to create the composition from. Omit when not creating, or when creating a composition without a composition pattern.").optional(),instructions:yE.describe("Modification instructions for the composition. Omit for delete and duplicate.").optional(),projectMapNode:en.object({parentNodeId:en.string().uuid().describe("UUID of the parent node from searchProjectMapNodes. If omitted, the node will be a child of the root node.").optional(),nodePathSegment:en.string().describe('URL path segment for the node (e.g., "about-us", "products", ":productId" for dynamic matching). Use a slugified version of the name unless otherwise requested by the user. Omit if not creating a project map node.').optional(),localePathSegments:en.array(en.object({locale:en.string().describe('Locale code (e.g., "en-US", "fr-FR")'),pathSegment:en.string().describe("URL path segment for this locale")})).describe("Optional array of locale-specific path segments. Unspecified locales use the nodePathSegment. Do not use these for dynamic path segments.").optional(),allowedQueryStrings:en.array(en.object({name:en.string().describe("Query parameter name"),defaultValue:en.string().describe("Default value if not provided in the URL").optional()})).describe("Optional array of allowed query string parameters for this node").optional()}).describe("Attaches the new composition to a new node in the project map hierarchy. Omit to avoid creating a project map node, or if action is not create.").optional()};function vV(t,e){t.tool("compositionAction","Creates, updates, or deletes a Uniform Composition",Zhe,async r=>await s2({...r,isPattern:!1,getEditUrl:n=>l2(n,e),patternId:r.patternId,projectMapNode:r.projectMapNode,env:e}))}import*as rr from"zod/v3";var Yhe=rr.object({field:rr.string(),operator:rr.string(),value:rr.string().or(rr.array(rr.string()))}),Khe=rr.object({filter:rr.array(Yhe),error:rr.string().describe("An error message if the filter expression could not be created, otherwise an empty string"),sort:rr.array(rr.enum(["created_at_ASC","created_at_DESC","updated_at_ASC","updated_at_DESC","author_ASC","author_DESC","creator_ASC","creator_DESC","name_ASC","name_DESC","slug_ASC","slug_DESC"])),limit:rr.number().min(1).max(100),offset:rr.number().min(0),keyword:rr.string(),locale:rr.string().optional()}),ns=rr.object({searchExpressionPrompt:rr.string().describe(`Describe what you are looking for, for example "created by me in the last week" or "type is article and headline contains breaking news" or "keyword search for breaking news".
5782
+ `).trimStart();r.on("*",(o,a)=>{console.debug(`\u26A1\uFE0F ${t}:${String(o)}`,{args:a,stack:n,subs:r.all.get(String(o))?.length??0})})}return r}var Yo=(0,cV.default)(),Fhe=!0,Bhe="Twee",ii=class t{#e={};rootNodeId;#n={};#o={};#r;#a={};#t=eV(Bhe,Fhe);#u;#c;#g;#d;#s;#i;constructor(e,r){let{metadata:n,startDirty:o}=r||{};this.#s=n??{},this.#i={_name:e?._name??"",_slug:e?._slug??null},this.#d=!o;let a=wr(e,i=>{this.#v({composition:i,ignoreRootOverrides:!0,preserveChildrenSlotSections:!0}),delete i._author,delete i._authorSubject,delete i._creator,delete i._creatorSubject});this.rootNodeId=a._id??pl(),this.#u=this.rootNodeId,this.#l({componentTree:a,nodeId:this.rootNodeId}),this.#r=a._overrides??{}}events=this.#t;exportTree(e){return this.exportSubtree(this.rootNodeId,e)}exportMetadata(){return this.#s}exportRootNodeMetadata(){return this.#i}get pristine(){return this.#d}set pristine(e){this.#d!==e&&(this.#d=e,this.#t.emit("pristineChanged",{pristine:e}))}get selectedBlockIdStack(){return this.#c}set selectedBlockIdStack(e){this.#c=e,this.#t.emit("selectedBlockChanged",{selectedBlockIds:this.#c})}get selectedNodeId(){return this.#u}set selectedNodeId(e){this.#u!==e&&(this.#u=e,this.selectedParameterId=void 0,this.#t.emit("selectedNodeChanged",{selectedNodeId:e}))}get selectedParameterId(){return this.#g}set selectedParameterId(e){this.#g!==e&&(this.#g=e,this.#t.emit("selectedParameterChanged",{selectedParameterId:e}))}pushSelectedBlockId(e){this.selectedBlockIdStack=this.selectedBlockIdStack??[],this.selectedBlockIdStack?.push(e),this.#t.emit("selectedBlockChanged",{selectedBlockIds:this.selectedBlockIdStack})}popSelectedBlockId(){this.#c?.pop(),this.#t.emit("selectedBlockChanged",{selectedBlockIds:this.selectedBlockIdStack})}getNodeById(e){return this.#e[e]}getNodesIndex(){return this.#e}getBlockNodeValueById(e){return gS(this.exportSubtree(e),e)}getNodeChildren(e){let r=this.#n[e];if(r)return r}getNodeProperty(e,r){return bS(this.#o,[e,r])}getNodeProperties(e){return this.#o[e]??{}}insertNode({node:e,parentNodeId:r,parentSlot:n,targetIndexInSlot:o,overrideNodeId:a}){let i=a??pl();if(!this.#$(r))throw new Error("Cannot insert component into a read-only pattern slot unless it is within a slot section");let s={nodeId:i,parentId:r,value:t.#E(e),isExpandedInUI:!0,propertyValueLocalizability:{}};return this.#w({node:s,parentNodeId:r,parentSlot:n,targetIndexInSlot:o}),this.#m({nodeId:i,destinationParentId:r,destinationSlotName:n}),this.pristine=!1,this.#t.emit("nodeChanged",{changedNode:s,oldValue:void 0,type:"new"}),this.#t.emit("childrenChanged",{parentId:r,slotOrBlockName:n,newChildIds:this.#n[r][n],type:"slot"}),i}upsertBlockNode({nodeId:e,property:r,index:n,entry:o}){let a=this.#S({nodeId:e,property:r,index:n,entry:o});return this.pristine=!1,this.#t.emit("childrenChanged",{parentId:e,slotOrBlockName:r,newChildIds:this.#o[e]?.[r]?.value,type:"block"}),a}updateRootMetadata(e){let r={...this.#s};this.#s={...this.#s,...e},this.pristine=!1,this.#t.emit("metadataChanged",{metadata:this.#s,oldValue:r})}updateRootNode({update:e,doNotSetDirty:r}){let n={...this.#i};this.#i={...this.#i,...e},r||(this.pristine=!1),this.#t.emit("rootNodeMetadataChanged",{metadata:this.#i,oldValue:n})}insertPattern({parentNodeId:e,parentSlot:r,pattern:n,targetIndexInSlot:o,patternInstanceId:a}){let i=a??pl();if(this.#e[i])throw new Error(`Node with ID '${i}' already exists. Pattern nodes must have unique IDs. Did you mean to move or duplicate this pattern instead?`);let l=this.#y(n,i,!1);return this.#f({nodeId:l,parentNodeId:e,parentSlot:r,targetIndexInSlot:o}),this.#m({nodeId:l,destinationParentId:e,destinationSlotName:r}),this.pristine=!1,this.visitNodeAndDescendants(l,s=>{this.#t.emit("nodeChanged",{changedNode:s,oldValue:void 0,type:"new"})}),this.#t.emit("childrenChanged",{parentId:e,slotOrBlockName:r,newChildIds:this.#n[e][r],type:"slot"}),l}unlinkPattern(e){let r=this.#e[e];if(!r)throw new Error(`Node ${e} does not exist`);if(!r.value._pattern)throw new Error(`Node ${e} is not a pattern`);let n=r.value._patternDataResources||r.value._dataResources,o=GB(r.value),a=l=>{l.partOfNestedPattern||(this.updateNode({nodeId:l.nodeId,updateComponent:s=>{delete s._pattern,delete s._patternError,delete s._overrides},updateMetadata:s=>{delete s.partOfPattern,delete s.partOfNestedPattern},doNotSetDirty:!0,ignoreOverrides:!0}),this.#r[l.nodeId]&&(this.#r=wr(this.#r,s=>{delete s[l.nodeId]})))};this.visitNodeAndDescendants(e,a);let i=l=>{l.partOfNestedPattern&&this.updateNode({nodeId:l.nodeId,updateMetadata:s=>{s.partOfPattern=s.partOfNestedPattern,delete s.partOfNestedPattern},doNotSetDirty:!0,ignoreOverrides:!0})};this.visitNodeAndDescendants(e,i),n&&(this.updateNode({nodeId:this.rootNodeId,updateDataResources:l=>Object.entries(o??{}).filter(([s])=>!(s in(l??{}))).map(([s,u])=>{let{source:c,...d}=u;return{type:"set",name:s,value:d}})}),this.updateNode({nodeId:r.nodeId,updateComponent:l=>{delete l._patternDataResources},updateDataResources:"removeAll",doNotSetDirty:!0,ignoreOverrides:!0})),this.pristine=!1}convertToPattern({existingNodeId:e,pattern:r}){let n=this.#e[e],o=n?.parentId;if(!n)throw new Error(`Node ${e} does not exist`);let a=this.#y(r,e,!0);this.#e[a]=wr(this.#e[a],l=>{l.parentId=o}),this.pristine=!1;let i=this.#e[a];this.#t.emit("nodeChanged",{changedNode:i,oldValue:n,type:"new"}),Object.entries(this.#n[a]??{}).forEach(([l,s])=>{this.#t.emit("childrenChanged",{newChildIds:s,parentId:a,slotOrBlockName:l,type:"slot"})})}copyNodeToClipboard(e){let r=this.exportSubtree(e,{keepPatternData:!1}),n=this.exportSubtree(e,{keepPatternData:!0}),o=[];rs(n,({node:l})=>{l._id&&o.push(l._id)}),rs(r,({node:l})=>{l._id&&(l._overrides&&delete l._overrides,"_name"in l&&delete l._name,"_slug"in l&&delete l._slug)});let a=this.#h(),i=Object.entries(a??{}).reduce((l,[s,u])=>(o.some(c=>s.includes(c))&&(l[s]=u),l),{});return{format:"uniform/copied-component-subtree-1.0",componentData:r,overrides:Object.keys(i).length?i:void 0,pasteAs:this.getNodeById(e)?.isBlock?"block":void 0}}async pasteNodeFromClipboard({parentNodeId:e,parentSlot:r,targetIndexInParent:n,clipboard:o,resolvePattern:a}){let i=Yo(o),l=async u=>{u._pattern&&s.push((async()=>{let c=await a(u._pattern);if(!c){console.debug(`Pasted pattern ${u._pattern} not found, skipping`);return}let d=this.#x(c,u._id);Object.assign(u,d)})())},s=[];return rs(i.componentData,({node:u})=>{l(u)}),i.overrides&&Object.values(i.overrides).forEach(u=>{u.slots&&Object.values(u.slots).forEach(c=>{c.forEach(d=>{rs(d,({node:f})=>{l(f)})})})}),await Promise.all(s),this.#T(i.componentData,{parentId:e,parentName:r,parentType:o.pasteAs==="block"?"block":"slot",targetIndexInParent:n},i.overrides)}enableLocale(e){this.updateNode({nodeId:this.rootNodeId,updateComponent:r=>{let n=r;n._locales??=[];let o=[...new Set([...n._locales,...Array.isArray(e)?e:[e]])];n._locales=o}})}disableLocale(e){this.updateNode({nodeId:this.rootNodeId,updateComponent:o=>{let a=o;a._locales=a._locales?.filter(i=>i!==e)}});let r=[],n=o=>{this.getNodeProperty(o.nodeId,th)?.value===e&&!o.partOfPattern&&r.push(o.nodeId);let i=this.getNodeProperties(o.nodeId);Object.entries(i).forEach(([s,u])=>{let c=u;s!==fl&&(o.partOfPattern?this.isPatternPropertyOverridden(o.nodeId,s,e)&&this.resetPatternPropertyOverride(o.nodeId,s,e):(c?.localesConditions?.[e]?.forEach((d,f)=>{this.updateNodeProperty({nodeId:o.nodeId,property:s,value:void 0,source:"other",locale:e,conditionIndex:f,conditionDefinition:null})}),c?.locales?.[e]!==void 0&&this.updateNodeProperty({nodeId:o.nodeId,property:s,value:void 0,source:"other",locale:e,conditionIndex:-1})))});let l=this.getNodeProperty(o.nodeId,fl);if(l?.value){let s=qB(l.value,e);if(s===null)r.push(o.nodeId);else if(s===void 0||!Vr(l.value,s)){let u=!o.partOfPattern,c=oc(o.value._overridability,fl)==="yes";(u||c)&&this.updateNodeProperty({nodeId:o.nodeId,property:fl,value:s?()=>s:void 0,source:"other",locale:void 0,conditionIndex:-1})}}};this.visitNodeAndDescendants(this.rootNodeId,n),r.forEach(o=>{this.deleteNode(o)})}copyValuesToLocalePlan({sourceLocale:e,destinationLocale:r,doNotCopyDescendants:n=!1,startingNodeId:o=this.rootNodeId,specificPropertyId:a}){let i=new Map,l=u=>{if(u.value.type===khe&&!u.partOfPattern){let d=this.getNodeChildren(u.nodeId)?.[xS]??[],f=d.map(h=>this.getNodeProperty(h,th)),p=f.findIndex(h=>h?.value===r);if(p>=0){let h=d[p];ml(i,h).actions.push({type:"deleteLocalizedNode"})}let m=f.findIndex(h=>h?.value===e);if(m>=0){let h=d[m];ml(i,h).actions.push({type:"duplicateLocalizedNode",targetIndexInSlot:p})}}if(i.get(u.nodeId)?.actions.some(d=>d.type==="deleteLocalizedNode"))return;let c=a?{[a]:this.getNodeProperty(u.nodeId,a)}:this.getNodeProperties(u.nodeId);Object.entries(c).forEach(([d,f])=>{if(f===void 0)return;let p=!u.partOfPattern,m=oc(u.value._overridability,d)==="yes";if(!(p||m))return;if(d===fl){let S=KB(f.value,e,r);S===null?ml(i,u.nodeId).actions.push({type:"deleteLocalizedNode"}):S&&ml(i,u.nodeId).actions.push({type:"updateVisibilityCriteria",targetValue:S})}let g=f.locales?.[e],v=f.locales?.[r];(!g||!v||!Vr(g,v))&&(g!==void 0?ml(i,u.nodeId).actions.push({type:"copyPropertyValue",propertyId:d,sourceValue:g,targetValue:v,conditionIndex:-1}):v!==void 0&&ml(i,u.nodeId).actions.push({type:"deletePropertyValue",propertyId:d,sourceValue:g,targetValue:v,conditionIndex:-1}));let y=f.localesConditions?.[e],x=f.localesConditions?.[r];y?.forEach((S,E)=>{let $=f.localesConditions?.[r]?.[E];(!S||!$||!Vr(S,$))&&ml(i,u.nodeId).actions.push({type:"copyPropertyValue",propertyId:d,sourceValue:S.value,targetValue:$,conditionIndex:E,conditionDefinition:S.when})});let C=y?.length??0,w=x?.length??0;if(C<w){let S=ml(i,u.nodeId);for(let E=C;E<w;E++)S.actions.push({type:"deletePropertyValue",propertyId:d,sourceValue:y?.[E],targetValue:x?.[E],conditionIndex:E})}})},s=this.#e[o];if(!s)throw new Error(`Node ${o} does not exist`);return l(s),!a&&!n&&this.visitDescendants(s.nodeId,l),{nodePlans:Array.from(i.values()),sourceLocale:e,destinationLocale:r}}async copyValuesToLocaleExecute({resolvePattern:e,plan:{sourceLocale:r,destinationLocale:n,nodePlans:o}}){let a=`copyLocaleExecute: ${n}`;console.time(a);for(let{nodeId:i,actions:l}of o)for(let s of l)switch(s.type){case"copyPropertyValue":{let u=this.getNodeProperty(i,s.propertyId)?.type,c=s.sourceValue;u==="contentReference"&&(c=this.prepareContentReferenceWrite({nodeId:i,propertyId:s.propertyId,destinationLocale:n,conditionIndex:s.conditionIndex,sourceValue:s.sourceValue})),this.updateNodeProperty({nodeId:i,property:s.propertyId,source:"other",locale:n,value:()=>c,type:u,conditionIndex:s.conditionIndex,conditionDefinition:s.conditionDefinition});break}case"deletePropertyValue":{this.updateNodeProperty({nodeId:i,property:s.propertyId,source:"other",locale:n,value:void 0,conditionIndex:s.conditionIndex,conditionDefinition:null});break}case"deleteLocalizedNode":{this.deleteNode(i);break}case"duplicateLocalizedNode":{let u=await this.duplicateNode(i,e);this.updateNodeProperty({nodeId:u,locale:void 0,conditionIndex:-1,type:"localeSelect",property:th,source:"other",value:()=>n});let c=this.copyValuesToLocalePlan({sourceLocale:r,destinationLocale:n,startingNodeId:u});this.copyValuesToLocaleExecute({plan:c,resolvePattern:e}),s.targetIndexInSlot!==void 0&&this.moveNode({movedNodeId:u,parentNodeId:this.#e[i].parentId,parentSlot:xS,targetIndexInSlot:s.targetIndexInSlot});break}case"updateVisibilityCriteria":{this.updateNodeProperty({nodeId:i,property:fl,source:"other",locale:void 0,conditionIndex:-1,value:()=>s.targetValue});break}default:throw new Error(`Unhandled action type ${s.type}`)}console.timeEnd(a)}updateNode({nodeId:e,updateComponent:r,updateDataResources:n,updateMetadata:o,doNotSetDirty:a,ignoreOverrides:i}){let l=this.#e[e];if(!l)throw new Error(`Update target node ID ${e} did not exist!`);let s=wr(l,f=>{if(o&&(o(f),f.nodeId=e,f.value=l.value,f.parentId=l.parentId),r){if(r(f.value),"slots"in f.value)throw new Error("Do not set `slots` on a Twee node, insert child nodes instead.");if("parameters"in f.value)throw new Error("Do not set `parameters` on a Twee node, use updateProperties option instead.")}if(n){let p=typeof n=="function"?n(f.value._dataResources):n;if(p==="removeAll")delete f.value._dataResources;else for(let m of p){let h=i?!1:f.nodeId!==this.rootNodeId&&f.value._pattern;switch(m.type){case"set":h&&(this.#r=wr(this.#r,g=>{g[e]??={},g[e].dataResources??={},g[e].dataResources[m.name]=m.value})),f.value._dataResources??={},f.value._dataResources[m.name]=m.value;break;case"remove":h&&(this.#r=wr(this.#r,g=>{delete g[e]?.dataResources?.[m.name]})),delete f.value._dataResources?.[m.name];break;case"reset":{let g=this.#a[e]?.dataResources?.[m.name];f.value._dataResources&&(g&&Object.keys(g).length>0?f.value._dataResources[m.name]=g:delete f.value._dataResources[m.name]),this.#r=wr(this.#r,v=>{delete v[e]?.dataResources?.[m.name]})}break;default:throw new Error(`Unhandled data resource action ${m?.type}`)}}}}),u=!!(l.partOfPattern&&!l.value._patternError),c=l.value.variant!==s.value.variant,d=l.value._overridability?.variants??!1;!i&&u&&c&&d&&(this.#r=wr(this.#r,f=>{f[e]??={},f[e].variant=s.value.variant})),this.#e[e]=s,a||(this.pristine=!1),this.#t.emit("nodeChanged",{changedNode:s,type:"update",oldValue:l})}updateNodeProperty({nodeId:e,property:r,value:n,source:o,locale:a,type:i,doNotSetDirty:l=!1,ignoreOverrides:s=!1,conditionIndex:u,conditionDefinition:c}){let d=this.#e[e];if(!d)throw new Error(`Update target node ID ${e} did not exist!`);if(u<0&&c)throw new Error("Condition definition provided for non-conditional value");let f=!!(d.partOfPattern&&!d.value._patternError),p=[e,r],m=bS(this.#o,p);if(!m&&n==null)return;let h=sV({locale:a,property:m,conditionIndex:u}),g=a?m?.localesConditions?.[a]?.[u]:m?.conditions?.[u],v=typeof n=="function"?wr(h,S=>n(S)):n,y=i??m?.type;if(!y)throw new Error(`Cannot add parameter ${r} to node ${e} without specifying a type`);let x={...m,type:y},C=!1;x=wr(x,S=>{v===void 0&&u<0?C=!r2({locale:a,property:S,conditionIndex:u}):c===null&&u>=0?C=!r2({locale:a,property:S,conditionIndex:u}):mS({locale:a,property:S,newPropertyValue:v,conditionIndex:u,conditionDefinition:c??g?.when??{clauses:[]}})}),C&&(x=void 0);let w=f&&oc(d.value._overridability,r)==="yes";if(f&&!w&&!s)throw new Error(`Cannot override parameter ${r} on node ${e} because it is not marked as overridable on the pattern (${d.partOfPattern})`);if(w&&(this.#a[e]?.parameters?.[r]||(this.#a=wr(this.#a,E=>{E[e]??={parameters:{},dataResources:{}},E[e].parameters[r]=m??{type:y,value:null}}))),!s&&w){let S=this.#r[e]?.parameters?.[r];this.#r=wr(this.#r,E=>{let T=v==null||x===void 0?null:v,D=S??{type:x?.type??m?.type??"unknown",value:m?.value,conditions:m?.conditions,locales:a&&m?.locales?.[a]?{[a]:m.locales[a]}:void 0,localesConditions:a&&m?.localesConditions?.[a]?{[a]:m.localesConditions[a]}:void 0},L=wr(D,k=>{c===null&&u>=0?r2({locale:a,property:k,conditionIndex:u}):mS({locale:a,property:k,newPropertyValue:T,conditionIndex:u,conditionDefinition:c??g?.when??{clauses:[]}})});(0,ac.set)(E,`/${e}/parameters/${r}`,L)}),S||this.#t.emit("propertyOverrideCreated",{nodeId:e,property:r})}v===null?(0,ac.remove)(this.#o,p):(this.#o[e]??={},(0,ac.set)(this.#o,p,x)),l||(this.pristine=!1),this.#t.emit("nodeParameterChanged",{nodeId:e,parameter:r,locale:a,conditionIndex:u,value:x,previousValue:m,type:n?m?"update":"new":"delete",conditionDefinition:c,source:o})}isPatternPropertyOverridden(e,r,n,o){let a=this.getNodeById(e);if(!a||oc(a.value._overridability,r)==="no")return!1;let i=this.#r[e]?.parameters?.[r];return i?n?(o===void 0||o===!0)&&i.localesConditions?.[n]!==void 0||(o===void 0||o===!1)&&i.locales?.[n]!==void 0:(o===void 0||o===!0)&&i.conditions!==void 0||(o===void 0||o===!1)&&i.value!==void 0:!1}getPatternPropertyOverrideDefaultValue(e,r,n){let o=this.#a[e]?.parameters?.[r];if(!o)return{exists:!1};if(n&&o.locales?.[n])return{exists:!0,value:o,sourceLocale:n};if(o.value!==void 0)return{exists:!0,value:o,sourceLocale:void 0};let a=Object.keys(o.locales??{})[0];return a?{exists:!0,value:o,sourceLocale:a}:{exists:!1}}resetPatternPropertyOverride(e,r,n){let o=[-1];this.#r=wr(this.#r,i=>{let l=i[e]?.parameters?.[r];if(l)if(n){delete l.locales?.[n];let s=l.localesConditions?.[n];s&&(s.forEach((u,c)=>{o.push(c)}),delete l.localesConditions?.[n]),l.locales&&Object.keys(l.locales).length===0&&delete l.locales,l.localesConditions&&Object.keys(l.localesConditions).length===0&&delete l.localesConditions,Object.keys(l.locales??{}).length===0&&Object.keys(l.localesConditions??{}).length===0&&delete i[e]?.parameters?.[r]}else{let s=l.conditions;s&&s.forEach((u,c)=>{o.push(c)}),delete i[e].parameters?.[r]}});let a=this.getPatternPropertyOverrideDefaultValue(e,r,n);!a.exists||a.value===null?this.updateNodeProperty({nodeId:e,property:r,value:void 0,source:"reset",locale:n,ignoreOverrides:!0,doNotSetDirty:!1,conditionIndex:-1}):o.forEach(i=>{let l=sV({locale:a.sourceLocale,property:a.value,conditionIndex:i,strict:!0});this.updateNodeProperty({nodeId:e,property:r,value:l===void 0?void 0:()=>l,source:"reset",locale:n,type:a.value?.type,ignoreOverrides:!0,doNotSetDirty:!1,conditionIndex:i,conditionDefinition:(n?a.value?.localesConditions?.[n]?.[i]?.when:a.value?.conditions?.[i]?.when)??null})}),this.#t.emit("propertyOverrideReset",{nodeId:e,property:r,usedPatternDefault:a!==void 0})}async duplicateNode(e,r){let n=this.getParentInfo(e);if(!n)throw new Error("Cannot duplicate root node or parentless block");let o=this.copyNodeToClipboard(e);return await this.pasteNodeFromClipboard({parentNodeId:n.parentId,parentSlot:n.parentName,resolvePattern:r,targetIndexInParent:n.targetIndexInParent+1,clipboard:o})}moveNode({movedNodeId:e,parentNodeId:r,parentSlot:n,targetIndexInSlot:o}){if(!this.#e[e])throw new Error(`Cannot move node ${e} - it does not exist`);let i=this.getParentInfo(e);if(!i)throw new Error("Cannot move root node");this.#n[i.parentId][i.parentName].splice(i.targetIndexInParent,1),this.#b(i.parentId,e),this.#f({nodeId:e,parentNodeId:r,parentSlot:n,targetIndexInSlot:o}),this.#m({nodeId:e,destinationParentId:r,destinationSlotName:n,sourceSlotName:i.parentName}),this.pristine=!1,this.#t.emit("childrenChanged",{parentId:r,slotOrBlockName:n,newChildIds:this.#n[r][n],type:"slot"}),this.#t.emit("childrenChanged",{parentId:i.parentId,slotOrBlockName:i.parentName,newChildIds:this.#n[i.parentId][i.parentName],type:"slot"})}deleteNode(e,r){let n=this.getParentInfo(e);if(!n&&!r)throw new Error("Cannot delete root node");n&&!r&&(this.#n[n.parentId][n.parentName].splice(n.targetIndexInParent,1),this.#n[n.parentId][n.parentName].length===0&&delete this.#n[n.parentId][n.parentName],this.selectedNodeId===e&&(this.selectedNodeId=n.parentId),this.#b(n.parentId,e),this.#t.emit("childrenChanged",{parentId:n.parentId,slotOrBlockName:n.parentName,newChildIds:this.#n[n.parentId][n.parentName]??[],type:"slot"})),delete this.#e[e],this.#t.emit("nodeDeleted",{deletedNodeId:e}),this.pristine=!1}#b(e,r){this.#r=wr(this.#r,n=>{let o=n[e]?.slots;o&&Object.keys(o).forEach(a=>{o[a]=o[a].filter(({_id:i})=>i!==r),o[a].length===0&&delete o[a]})})}#h(){if(Object.keys(this.#r).length>0){let e=Yo(this.#r);return Object.entries(e).forEach(([n,o])=>{let a=!0;if(!this.#e[n]){delete e[n];return}if(o.parameters){let i=Object.entries(o.parameters);i.forEach(([l,s])=>{let u=uV(s);u?(o.parameters[l]=u,a=!1):delete o.parameters[l]}),i.length===0&&delete o.parameters}o.slots&&Object.entries(o.slots).forEach(([l,s])=>{if(s.length){let u=s.filter(c=>c._id).map(c=>this.exportSubtree(c._id));u?(o.slots[l]=u,a=!1):delete o.slots[l]}else delete o.slots[l]}),o.variant!==void 0&&(a=!1),o.dataResources&&Object.keys(o.dataResources).length>0&&(a=!1),a&&delete e[n]}),Object.keys(e).length===0&&(e=void 0),e}}exportSubtree(e,r){let{keepPatternData:n=!1}=r??{},o=this.#e[e];if(!o)throw new Error(`Node ${e} to export is not found`);let a=Yo(o);if(e===this.rootNodeId){let s=this.#h();s?a.value._overrides=s:delete a.value._overrides;let u=a.value;u._name=this.#i._name,this.#i._slug&&(u._slug=this.#i._slug)}let i=[a],l=new Set;for(;i.length>0;){let s=i.pop();if(l.has(s.nodeId))throw new Error("Circular reference detected in the composition tree with node ID "+s.nodeId);if(l.add(s.nodeId),s.value._id=s.nodeId,!n&&(delete s.value._patternDataResources,delete s.value._patternOverrides,s.value._pattern&&s.value._dataResources)){let d=!1;Object.keys(s.value._dataResources).forEach(f=>{a.value._overrides?.[s.nodeId]?.dataResources?.[f]?delete s.value._dataResources[f]:d=!0}),d||delete s.value._dataResources}let u=this.#o[s.nodeId];if(u&&(n||!s.partOfPattern)){let d={},f=!1;Object.entries(u).forEach(([p,m])=>{if(m?.type===ba&&Array.isArray(m.value)){let h=m.value,g=[];h.forEach(v=>{let y=this.exportSubtree(v,r);g.push(gS(y,v))}),d[p]={value:g,type:ba},f=!0}else{let h=uV(m);h&&(d[p]=h,f=!0)}}),f&&(s.value.parameters=d)}let c=this.#n[s.nodeId];!c||s.partOfPattern&&!n||Object.entries(c).forEach(([d,f])=>{f.forEach((p,m)=>{let h=this.#e[p];if(!h)throw new Error("Insanity detected.");let g=Yo(h),v=s.value;v.slots=v.slots||{},(0,ac.set)(s,["value","slots",d,m.toString(10)],g.value),i.push(g)})})}return this.#A(a.value),a.value}#w({parentNodeId:e,parentSlot:r,targetIndexInSlot:n,node:o}){if(!this.#e[e])throw new Error("Parent ID to insert under did not exist!");if(this.#e[o.nodeId])throw new Error(`Node with ID '${o.nodeId}' already exists. Nodes must have unique IDs. Did you mean to move or duplicate this node instead?`);this.#e[o.nodeId]=o,this.#f({nodeId:o.nodeId,parentNodeId:e,parentSlot:r,targetIndexInSlot:n})}#f({nodeId:e,parentNodeId:r,parentSlot:n,targetIndexInSlot:o}){let a=this.#e[r],i=this.#n[r]??={},l=i[n]??=[];typeof o<"u"?l.splice(o,0,e):l.push(e),a?.value.type===n2&&(this.#r=wr(this.#r,s=>{s[r]=s[r]??{},s[r].slots={[Phe]:l.map(u=>({_id:u,type:this.#e[u].value.type}))}})),this.#e[e]=wr(this.#e[e],s=>{s.parentId=r})}#S({nodeId:e,property:r,index:n,entry:o}){let a=this.getNodeById(e);if(!a)throw new Error("Node doesn't exist");let l={nodeId:o._id??pl(),value:{type:o.type,_dataResources:o._dataResources},isBlock:!0,parentId:e,propertyValueLocalizability:{}},s=this.getNodeProperty(a.nodeId,r);if(s&&s.type!==ba)throw new Error("Parameter already exists and isn't a block parameter");let u=this.#e[l.nodeId];this.#e[l.nodeId]=l;let c=Yo(this.getNodeProperty(a.nodeId,r)?.value?.filter(d=>this.getNodeById(d))??[]);if(typeof n<"u"){if(n<0)throw new Error("parameter index cannot be less than 0");let d=-1;if(c.forEach((f,p)=>{f===l.nodeId&&(d=p)}),n>c.length+(d===-1?1:0))throw new Error(`Parameter index ${n} outside current index bounds.`);d>-1&&d!==n&&(c=c.filter(f=>f!==l.nodeId),c.splice(n,0,l.nodeId))}else c.push(l.nodeId);return Object.entries(o?.fields??{}).forEach(([d,f])=>{if(f.type===ba&&Array.isArray(f.value)){let p=f.value,m=[];p.forEach(h=>{let g=h._id??pl();this.#l({nodeId:g,componentTree:hS(h)}),this.#e[g].isBlock=!0,this.#e[g].parentId=l.nodeId,m.push(g)}),this.updateNodeProperty({nodeId:l.nodeId,property:d,type:f.type,value:()=>m,source:"other",locale:void 0,conditionIndex:-1})}else this.updateNodeProperty({nodeId:l.nodeId,property:d,type:f.type,value:()=>f.value,source:"other",locale:void 0,conditionIndex:-1})}),this.updateNodeProperty({nodeId:a.nodeId,property:r,type:ba,value:()=>c,source:"other",locale:void 0,conditionIndex:-1}),this.#t.emit("nodeChanged",{changedNode:a,oldValue:void 0,type:u?"update":"new"}),this.#t.emit("nodeParameterChanged",{nodeId:a.nodeId,parameter:r,previousValue:s,source:"other",type:u?"update":"new",locale:void 0,conditionIndex:-1,conditionDefinition:void 0,value:{type:ba,value:c}}),{blockIds:c}}#l({componentTree:e,nodeId:r,partOfPattern:n,partOfNestedPattern:o,resetUids:a,isBlock:i,allowReplacement:l}){let{slots:s,parameters:u,_id:c,_overrides:d,...f}=e,p=n??f._pattern,m=f._pattern&&f._pattern!==p?f._pattern:o,h=r??(a?void 0:c)??pl();if(this.#e[h]&&!l)throw new Error(`Node with ID '${h}' already exists. Nodes must have unique IDs.`);let g={nodeId:h,value:f,partOfPattern:p,partOfNestedPattern:m,isBlock:i,propertyValueLocalizability:Object.entries(u??{}).reduce((v,[y,x])=>(v[y]=Gh({definition:void 0,currentValue:x,lastUserChoice:void 0}),v),{})};return p&&(g.partOfPattern=p),this.#e[g.nodeId]=g,u&&Object.entries(u).forEach(([v,y])=>{let{connectedData:x,...C}=y,w=x?iV(aV(x)):y.value;if(y?.type===ba&&Array.isArray(w)){let S=w,E=[];S?.forEach($=>{let T={...$,_id:a?pl():$._id??pl()};if(this.#e[T._id])throw new Error(`Block node with ID '${T._id}' already exists. Block nodes must have unique IDs.`);return E.push(T._id),this.#e[T._id]={nodeId:T._id,value:{type:ba},propertyValueLocalizability:{}},this.#l({componentTree:hS(T),nodeId:T._id,allowReplacement:!0,partOfPattern:p,partOfNestedPattern:m}),this.#e[T._id].isBlock=!0,this.#e[T._id].parentId=g.nodeId,this.#e[T._id]}),w=E}this.#o[g.nodeId]=this.#o[g.nodeId]??{},(0,ac.set)(this.#o,[g.nodeId,v],{...C,value:w})}),s&&Object.entries(s).forEach(([v,y])=>{let x=y.map(C=>{if(this.#e[C._id??""]?.isBlock)return;let w=this.#l({componentTree:C,partOfPattern:f.type===n2?void 0:p,partOfNestedPattern:f.type===n2?void 0:m,resetUids:a});return this.#e[w].parentId=g.nodeId,w});this.#n[g.nodeId]=this.#n[g.nodeId]??{},this.#n[g.nodeId][v]=x.filter(C=>C)}),g.nodeId}#y(e,r,n){let o=this.#x(e,r);return this.#l({componentTree:o,nodeId:r,allowReplacement:n})}#x(e,r){let n=Yo(e);return this.#v({composition:n}),qy(n,r),n._pattern=e._id,delete n._id,delete n._name,delete n._slug,delete n._overrides,delete n._locales,delete n._author,delete n._authorSubject,delete n._creator,delete n._creatorSubject,n._dataResources&&(n._patternDataResources=Yo(n._dataResources),delete n._dataResources),n}getParentInfo(e){let{parentId:r,isBlock:n}=this.#e[e]??{};if(!r)return;let o=this.#e[r];if(o)if(n)for(let[a,i]of Object.entries(this.#o[r]??{})){if(i?.type!==ba)continue;let l=Array.isArray(i.value)?i.value:[],s=l.indexOf(e);if(s>=0)return{value:o.value,parentId:r,parentName:a,targetIndexInParent:s,parentChildIds:l,parentType:"block"}}else{let a=this.#n[r];if(!a&&!n)throw new Error("Sanity failed; parent had no children!");for(let[i,l]of Object.entries(a??{})){let s=l.indexOf(e);if(s>=0)return{value:o.value,parentId:r,parentName:i,targetIndexInParent:s,parentChildIds:l,parentType:"slot"}}return}}static#E(e){return wr(e,n=>{delete n.slots,delete n.parameters})}#$(e){let r=e;for(;r;){let n=this.getNodeById(r);if(!n)break;if(n.value._pattern)return!1;if(n.value.type===n2||!n.partOfPattern)return!0;r=n.parentId}return!0}#T(e,r,n){let a={...this.#h(),...n},i;if(this.#r=wr(this.#r,s=>{this.#a=wr(this.#a,u=>{i=t2(e,a,(c,d,f)=>{s[c]=d,u[c]=this.#a[f]})})}),!i)throw new Error("Failed to duplicate component");i=wr(i,s=>{s._overrides=Yo(this.#r),this.#v({composition:s,preserveChildrenSlotSections:!0})});let l=this.#l({componentTree:i,isBlock:r.parentType==="block"});if(r.parentType==="block"){let s=this.getNodeProperty(r.parentId,r.parentName)?.value??[],u=[...s.slice(0,r.targetIndexInParent),l,...s.slice(r.targetIndexInParent)];this.updateNodeProperty({nodeId:r.parentId,property:r.parentName,type:ba,value:()=>u,locale:void 0,conditionIndex:-1,source:"other"}),this.#e[l].parentId=r.parentId,this.#t.emit("nodeChanged",{changedNode:this.getNodeById(l),type:"new",oldValue:void 0}),this.#t.emit("childrenChanged",{parentId:r.parentId,slotOrBlockName:r.parentName,newChildIds:u,type:"block"})}else{this.#f({nodeId:l,parentNodeId:r.parentId,parentSlot:r.parentName,targetIndexInSlot:r.targetIndexInParent}),this.#m({nodeId:l,destinationParentId:r.parentId,destinationSlotName:r.parentName}),this.#t.emit("childrenChanged",{parentId:r.parentId,slotOrBlockName:r.parentName,newChildIds:this.#n[r.parentId][r.parentName],type:"slot"});let s=u=>{this.#t.emit("nodeChanged",{changedNode:u,type:"new",oldValue:void 0})};this.visitNodeAndDescendants(l,s)}return this.pristine=!1,l}#v({composition:e,ignoreRootOverrides:r,preserveChildrenSlotSections:n}){this.#a=wr(this.#a,a=>{let i=pS({beforeApplyParameterOverride(u,c,d){a[u._id]??={parameters:{},dataResources:{}},a[u._id].parameters[c]=Yo(d)},beforeApplyDataResourceOverride(u,c,d){u._dataResources?.[c]?.ignorePatternParameterDefault||(a[u._id]??={parameters:{},dataResources:{}},a[u._id].dataResources[c]=Yo(d))}}),l=pS({beforeApplyParameterOverride(u,c,d,f){a[u._id]?.parameters[c]||(a[u._id]??={parameters:{},dataResources:{}},a[u._id].parameters[c]=Yo(f??null))},beforeApplyDataResourceOverride(u,c,d,f){u._dataResources?.[c]?.ignorePatternParameterDefault||a[u._id]?.dataResources[c]||(a[u._id]??={parameters:{},dataResources:{}},a[u._id].dataResources[c]=Yo(f))}});if(r){let{_overrides:u,...c}=e;rs(c,({node:d})=>{i.visitNode(d)})}let s=r?l:i;rs(e,({node:u})=>{s.visitNode(u)})});let o=RB({preserveOwnSlotSections:!0,preserveChildrenSlotSections:n});rs(e,a=>{o(a)})}visitNodeAndDescendants(e,r){let n=this.getNodeById(e);if(!n)throw new Error("Insanity detected.");r(n),this.visitDescendants(e,r)}visitDescendants(e,r){let n=this.#p(e,new Set);for(let o of n)r(...o)}async visitDescendantsAsync(e,r){let n=this.#p(e,new Set);for(let o of n)await r(...o)}*#p(e,r){let n=this.#e[e],o=this.#n[e]??{},a=Object.entries(this.#o[e]??{}).filter(([,i])=>i?.type===ba)??[];if(!n)throw new Error("Insanity detected.");r.add(e);for(let[i,l]of a){let s=l.value??[];for(let u=0;u<s.length;u++){let c=s[u],d=this.#e[c];if(d){if(r.has(c)){console.error(`Detected parent/child cycle in composition, ID ${c} exists more than once. The traversal of descendants will be aborted for the cycle subtree.`);continue}yield[d,n,i,u];for(let f of this.#p(c,r))yield f}}}for(let[i,l]of Object.entries(o))for(let s=0;s<l.length;s++){let u=l[s],c=this.#e[u];if(c){if(r.has(u)){console.error(`Detected parent/child cycle in composition, ID ${u} exists more than once. The traversal of descendants will be aborted for the cycle subtree.`);continue}yield[c,n,i,s];for(let d of this.#p(u,r))yield d}}}#m({nodeId:e,destinationParentId:r,destinationSlotName:n,sourceSlotName:o}){let a=n,i=o===rV,l=a===rV,s=o===nV,u=a===nV,c=a===xS,d=this.getNodeProperty(e,tV);l&&d&&this.updateNodeProperty({nodeId:e,property:tV,value:void 0,source:"other",locale:void 0,conditionIndex:-1});let f=this.getNodeProperty(e,rh);!l&&f&&this.updateNodeProperty({nodeId:e,property:rh,value:void 0,source:"other",locale:void 0,conditionIndex:-1}),l&&!i&&this.#C({nodeId:e,siblingIds:this.getNodeChildren(r)?.[n]??[],selectExistingName:h=>this.getNodeProperty(h,rh)?.value?.name,setName:h=>this.updateNodeProperty({nodeId:e,property:rh,value:g=>g&&typeof g=="object"&&g!==null?{...g,name:h}:{name:h,crit:[]},source:"other",locale:void 0,conditionIndex:-1,type:rh})}),u&&!s&&this.#C({nodeId:e,siblingIds:this.getNodeChildren(r)?.[n]??[],selectExistingName:h=>this.getNodeProperty(h,oV)?.value?.id,setName:h=>this.updateNodeProperty({nodeId:e,property:oV,value:g=>g&&typeof g=="object"&&g!==null?{...g,id:h}:{id:h},source:"other",locale:void 0,conditionIndex:-1,type:"testVariant"})});let p=this.getNodeProperty(e,th);!c&&p&&this.updateNodeProperty({nodeId:e,property:th,value:void 0,source:"other",locale:void 0,conditionIndex:-1});let m=this.getNodeProperty(e,fl);(l||c||u)&&m&&this.updateNodeProperty({nodeId:e,property:fl,value:void 0,source:"other",locale:void 0,conditionIndex:-1})}#C({nodeId:e,siblingIds:r,selectExistingName:n,setName:o}){let a=n(e),i=d=>r.some(f=>f===e?!1:n(f)===d),l=a&&i(a);if(a&&!l)return;let s=this.getNodeById(e)?.value.type;if(!s)throw new Error("Insanity detected.");let u=0,c=yS(e,s,u);do c=yS(e,s,u),u++;while(i(c));o(c)}prepareContentReferenceWrite({nodeId:e,propertyId:r,destinationLocale:n,conditionIndex:o,sourceValue:a}){let i=this.#I({value:a,dataResources:this.#e[e]?.value._dataResources});if(!i)return a;let{dataResource:l,isSingleEntryReference:s}=i,u=mc(e,r,n==="${locale}"?void 0:n,o);this.updateNode({nodeId:e,updateDataResources:[{name:u,type:"set",value:{...l,variables:{...l?.variables,locale:n}}}]});let c=`/${u}/entries${s?"/0":""}`;return iV(aV({syntax:"jptr",pointer:c}))}#I({value:e,dataResources:r}){if(typeof e!="string")return;let n;lV(e,(l,s)=>{s==="variable"&&(n=l)});let o=n?vS(n):void 0;if(!o)return;let a=o.dataResource,i=r?.[a];if(i)return{dataResource:i,dataResourceName:a,isSingleEntryReference:o.dataExpression?.endsWith("/0")}}#D(e){if(typeof e!="string")return;let r;return lV(e,(o,a)=>{a==="variable"&&(r=o)}),(r?vS(r):void 0)?.dataResource}#A(e){let r=new Set,n=[],o=({node:a})=>{let i=Ohe(a),l=a._dataResources;if(l)for(let[s,u]of Object.entries(l))u.type===ci&&n.push({dataResources:l,dataResourceKey:s});if(i)for(let s of Object.values(i))s.type==="contentReference"&&Rhe(s,({value:u})=>{let c=this.#D(u);c&&r.add(c)})};if(rs(e,o),"_overrides"in e&&e._overrides)for(let[,a]of Object.entries(e._overrides))rs({type:e.type,...a,_dataResources:a.dataResources},o);for(let{dataResources:a,dataResourceKey:i}of n)r.has(i)||delete a[i]}};function uV(t){return t?.value===void 0&&!t?.conditions&&!t?.locales&&!t?.localesConditions?null:t}function ml(t,e){return Vhe(t,e,()=>({nodeId:e,actions:[]}))}function Vhe(t,e,r){return t.has(e)||t.set(e,r()),t.get(e)}import{CANVAS_DRAFT_STATE as i2,CanvasClient as Whe}from"@uniformdev/canvas";import{ProjectMapClient as Ghe}from"@uniformdev/project-map";import{produce as Uhe}from"immer";function dV(t){return t.reduce((e,r)=>(e[r._id]={id:r._id,type:r.type,name:r._name},e),{})}import{CANVAS_DRAFT_STATE as fV,CanvasClient as CS,ContentClient as pV,ProjectClient as mV}from"@uniformdev/canvas";function gV(t){let e,r,n;return{fetchProjectGuidance:async()=>(e!==void 0||(e=(await new mV(t).get({projectId:t.projectId}))?.guidance),e),fetchDefinitions:async()=>{if(r!==void 0)return r;let a=await new CS(t).getComponentDefinitions({limit:1e3,includeSystem:!0});return r=Object.fromEntries(a.componentDefinitions.map(i=>[i.id,i])),r},fetchPatterns:async()=>{if(n!==void 0)return n;let a=await new CS(t).getCompositionList({limit:1e3,pattern:!0,patternType:"component",resolveData:!1,skipPatternResolution:!0,skipOverridesResolution:!0,state:fV});return n=dV(a.compositions.map(i=>i.composition)),n},resolvePatternData:async o=>(await new CS(t).getCompositionById({compositionId:o,state:fV,skipPatternResolution:!1,skipOverridesResolution:!0,withComponentIDs:!0,skipDataResolution:!0,withWorkflowDefinition:!0,releaseId:void 0}))?.composition,getToolClient:async()=>t.toolInvoker,getDimensionGuidance:async()=>{}}}function hV(t){let e,r;return{fetchProjectGuidance:async()=>(e!==void 0||(e=(await new mV(t).get({projectId:t.projectId}))?.guidance),e),fetchDefinitions:async()=>{if(r!==void 0)return r;let o=await new pV(t).getContentTypes({limit:1e3});return r=Object.fromEntries(o.contentTypes.map(a=>[a.id,UB(a)])),r},fetchPatterns:async()=>({}),resolvePatternData:async n=>{let a=(await new pV(t).getEntries({entryIDs:[n],skipPatternResolution:!1,skipOverridesResolution:!0,withComponentIDs:!0,skipDataResolution:!0,withWorkflowDefinition:!0,releaseId:void 0}))?.entries[0];return eh(a).composition},getToolClient:async()=>t.toolInvoker,getDimensionGuidance:async()=>{}}}import{parseHTML as jhe}from"linkedom/worker";function zhe(t){let e=Object.getPrototypeOf(t.body);for(;e&&!Object.getOwnPropertyDescriptor(e,"style");)e=Object.getPrototypeOf(e);let r=e?Object.getOwnPropertyDescriptor(e,"style"):void 0;if(!r?.get||e.__stylePatched)return;let n=r.get;Object.defineProperty(e,"style",{get(){let o=n.call(this);return new Proxy(o,{get(a,i){if(typeof i=="string"){let l=a[i];return typeof l=="function"?l.bind(a):l===void 0?"":l}return a[i]},set(a,i,l){return a[i]=l,!0}})},configurable:!0}),e.__stylePatched=!0}function o2(t){let e=`<!DOCTYPE html><html><body>${t}</body></html>`,{document:r}=jhe(e);return zhe(r),r}import{LocaleClient as Hhe}from"@uniformdev/canvas";async function a2(t,e){if(!t||t.length===0)return;let o=(await new Hhe(e).get()).results.map(i=>i.locale),a=t.filter(i=>!o.includes(i));if(a.length>0)throw new Error(`The following locales are not registered in your project: ${a.join(", ")}`)}async function s2({action:t,id:e,instructions:r,isPattern:n,patternId:o,projectMapNode:a,getEditUrl:i,env:l}){let s=new Whe(l),u,c,d=t==="update"?e:void 0,f={success:!0,actionsTaken:[]};if(t==="duplicate"){if(c=await s.getCompositionById({compositionId:e,state:i2,skipDataResolution:!0,skipPatternResolution:!1,withComponentIDs:!0,skipOverridesResolution:!0}),!c)throw new Error("Composition not found");let p=crypto.randomUUID(),m=BB(c.composition,p),h=Uhe(m,g=>{g._name=`${g._name} (copy)`,g._slug&&(g._slug=`${g._slug}-copy${g._slug?.endsWith("/")?"/":""}`)});u=new ii(h),e=p}else if(t==="create"){if(!r)throw new Error("Instructions are required for create");if(!r.name)throw new Error("Name is required for create");if(!r.type)throw new Error("Type is required for create");if(!o)u=new ii({_id:e,_name:r.name,type:r.type,_overridability:{hideLockedParameters:!0}});else{let p={composition:{_id:e,_name:r.name,type:r.type,_pattern:o},projectId:l.projectId,state:i2,pattern:!1};await s.updateComposition(p),d=e}}if(d){if(c=await s.getCompositionById({compositionId:e,state:i2,skipDataResolution:!0,skipPatternResolution:!1,withComponentIDs:!0,skipOverridesResolution:!0}),!c)throw new Error("Composition not found");u=new ii(c.composition)}if(t==="delete"&&await s.removeComposition({compositionId:e}),u){await a2(r?.localeUpdates?.enableLocales,l),f=await Xy({twee:u,descriptionUpdate:void 0,slugUpdate:void 0,nameUpdate:r?.name,propertyUpdates:r?.parameterUpdates??[],dataResourceUpdates:r?.dataResourceUpdates??[],localeUpdates:r?.localeUpdates,slotUpdates:r??{},currentEditorLocale:void 0,referenceData:gV(l),isEditingPattern:n,domParser:o2});let p=u.exportTree(),m=u.exportMetadata(),h={composition:p,projectId:l.projectId,state:i2,pattern:n,releaseId:c?.releaseId,editionId:c?.editionId,...m};await s.updateComposition(h)}if(t==="create"&&!n&&(a?.nodePathSegment||a?.localePathSegments)&&r?.name){let p=new Ghe({apiKey:l.apiKey,apiHost:l.apiHost,projectId:l.projectId}),{path:m,nodeId:h}=await EB({projectMapClient:p,compositionId:e,compositionName:r.name,nodePathSegment:a.nodePathSegment||"",parentNodeId:a.parentNodeId,localePathSegments:a.localePathSegments,allowedQueryStrings:a.allowedQueryStrings});return f.actionsTaken.push({success:!0,summary:`Created project map node at path: ${m}`}),{content:[{type:"text",text:JSON.stringify({...f,editUrl:i(e),projectMapNode:{path:m,nodeId:h}},null,2)}]}}return{content:[{type:"text",text:JSON.stringify({...f,editUrl:i(e)},null,2)}]}}function l2(t,e){return`${e.baseWebUrl}/dashboards/canvas/edit/${t}`}async function u2(t,e,r){return await r.toolInvoker.invoke("createFilterExpression",{...t,entityType:e})}var Zhe={action:en.enum(["create","update","delete","duplicate"]).describe("The action to perform"),id:en.string().uuid().describe("UUID of the composition instance to create, update, delete, or duplicate"),patternId:en.string().uuid().describe("Composition pattern ID to create the composition from. Omit when not creating, or when creating a composition without a composition pattern.").optional(),instructions:yE.describe("Modification instructions for the composition. Omit for delete and duplicate.").optional(),projectMapNode:en.object({parentNodeId:en.string().uuid().describe("UUID of the parent node from searchProjectMapNodes. If omitted, the node will be a child of the root node.").optional(),nodePathSegment:en.string().describe('URL path segment for the node (e.g., "about-us", "products", ":productId" for dynamic matching). Use a slugified version of the name unless otherwise requested by the user. Omit if not creating a project map node.').optional(),localePathSegments:en.array(en.object({locale:en.string().describe('Locale code (e.g., "en-US", "fr-FR")'),pathSegment:en.string().describe("URL path segment for this locale")})).describe("Optional array of locale-specific path segments. Unspecified locales use the nodePathSegment. Do not use these for dynamic path segments.").optional(),allowedQueryStrings:en.array(en.object({name:en.string().describe("Query parameter name"),defaultValue:en.string().describe("Default value if not provided in the URL").optional()})).describe("Optional array of allowed query string parameters for this node").optional()}).describe("Attaches the new composition to a new node in the project map hierarchy. Omit to avoid creating a project map node, or if action is not create.").optional()};function vV(t,e){t.tool("compositionAction","Creates, updates, or deletes a Uniform Composition",Zhe,async r=>await s2({...r,isPattern:!1,getEditUrl:n=>l2(n,e),patternId:r.patternId,projectMapNode:r.projectMapNode,env:e}))}import*as rr from"zod/v3";var Yhe=rr.object({field:rr.string(),operator:rr.string(),value:rr.string().or(rr.array(rr.string()))}),Khe=rr.object({filter:rr.array(Yhe),error:rr.string().describe("An error message if the filter expression could not be created, otherwise an empty string"),sort:rr.array(rr.enum(["created_at_ASC","created_at_DESC","updated_at_ASC","updated_at_DESC","author_ASC","author_DESC","creator_ASC","creator_DESC","name_ASC","name_DESC","slug_ASC","slug_DESC"])),limit:rr.number().min(1).max(100),offset:rr.number().min(0),keyword:rr.string(),locale:rr.string().optional()}),ns=rr.object({searchExpressionPrompt:rr.string().describe(`Describe what you are looking for, for example "created by me in the last week" or "type is article and headline contains breaking news" or "keyword search for breaking news".
5783
5783
  You can specify multiple criteria (AND only).
5784
5784
  You can filter by date, number, or string properties on the definition, as well as name, created, modified, author, slug, enabled locales, type, and publish status.`),username:rr.string().describe("The username of the current user. If you do not know the username, use an empty string"),locale:rr.string().describe("The current locale. If there is no current locale, use an empty string")}),yQe={displayName:"Create filter expression",description:"Creates a Uniform search filter expression for searching entries, patterns, or compositions from a user prompt. Meant to be a callable tool only.",inputSchema:ns.extend({entityType:rr.enum(["composition","entry","componentPattern","compositionPattern","entryPattern"]).describe("The entity type we are creating a filter for")}),outputSchema:Khe,runsAt:"server",timeout:10,callable:!0};import*as Aj from"zod/v3";var os=class extends Error{},c2=class extends os{constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}},d2=class extends os{constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}},f2=class extends os{constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}},ya=class extends os{},bf=class extends os{constructor(e){super(`Invalid unit ${e}`)}},Nr=class extends os{},xa=class extends os{constructor(){super("Zone is an abstract class")}};var Ee="numeric",Ca="short",To="long",gl={year:Ee,month:Ee,day:Ee},nh={year:Ee,month:Ca,day:Ee},wS={year:Ee,month:Ca,day:Ee,weekday:Ca},oh={year:Ee,month:To,day:Ee},ah={year:Ee,month:To,day:Ee,weekday:To},ih={hour:Ee,minute:Ee},sh={hour:Ee,minute:Ee,second:Ee},lh={hour:Ee,minute:Ee,second:Ee,timeZoneName:Ca},uh={hour:Ee,minute:Ee,second:Ee,timeZoneName:To},ch={hour:Ee,minute:Ee,hourCycle:"h23"},dh={hour:Ee,minute:Ee,second:Ee,hourCycle:"h23"},fh={hour:Ee,minute:Ee,second:Ee,hourCycle:"h23",timeZoneName:Ca},ph={hour:Ee,minute:Ee,second:Ee,hourCycle:"h23",timeZoneName:To},mh={year:Ee,month:Ee,day:Ee,hour:Ee,minute:Ee},gh={year:Ee,month:Ee,day:Ee,hour:Ee,minute:Ee,second:Ee},hh={year:Ee,month:Ca,day:Ee,hour:Ee,minute:Ee},vh={year:Ee,month:Ca,day:Ee,hour:Ee,minute:Ee,second:Ee},SS={year:Ee,month:Ca,day:Ee,weekday:Ca,hour:Ee,minute:Ee},bh={year:Ee,month:To,day:Ee,hour:Ee,minute:Ee,timeZoneName:Ca},yh={year:Ee,month:To,day:Ee,hour:Ee,minute:Ee,second:Ee,timeZoneName:Ca},xh={year:Ee,month:To,day:Ee,weekday:To,hour:Ee,minute:Ee,timeZoneName:To},Ch={year:Ee,month:To,day:Ee,weekday:To,hour:Ee,minute:Ee,second:Ee,timeZoneName:To};var no=class{get type(){throw new xa}get name(){throw new xa}get ianaName(){return this.name}get isUniversal(){throw new xa}offsetName(e,r){throw new xa}formatOffset(e,r){throw new xa}offset(e){throw new xa}equals(e){throw new xa}get isValid(){throw new xa}};var ES=null,hl=class t extends no{static get instance(){return ES===null&&(ES=new t),ES}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:r,locale:n}){return m2(e,r,n)}formatOffset(e,r){return vl(this.offset(e),r)}offset(e){return-new Date(e).getTimezoneOffset()}equals(e){return e.type==="system"}get isValid(){return!0}};var h2={};function Xhe(t){return h2[t]||(h2[t]=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",era:"short"})),h2[t]}var Jhe={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function qhe(t,e){let r=t.format(e).replace(/\u200E/g,""),n=/(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(r),[,o,a,i,l,s,u,c]=n;return[i,o,a,l,s,u,c]}function Qhe(t,e){let r=t.formatToParts(e),n=[];for(let o=0;o<r.length;o++){let{type:a,value:i}=r[o],l=Jhe[a];a==="era"?n[l]=i:ke(l)||(n[l]=parseInt(i,10))}return n}var g2={},hn=class t extends no{static create(e){return g2[e]||(g2[e]=new t(e)),g2[e]}static resetCache(){g2={},h2={}}static isValidSpecifier(e){return this.isValidZone(e)}static isValidZone(e){if(!e)return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:e}).format(),!0}catch{return!1}}constructor(e){super(),this.zoneName=e,this.valid=t.isValidZone(e)}get type(){return"iana"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(e,{format:r,locale:n}){return m2(e,r,n,this.name)}formatOffset(e,r){return vl(this.offset(e),r)}offset(e){let r=new Date(e);if(isNaN(r))return NaN;let n=Xhe(this.name),[o,a,i,l,s,u,c]=n.formatToParts?Qhe(n,r):qhe(n,r);l==="BC"&&(o=-Math.abs(o)+1);let f=yf({year:o,month:a,day:i,hour:s===24?0:s,minute:u,second:c,millisecond:0}),p=+r,m=p%1e3;return p-=m>=0?m:1e3+m,(f-p)/(60*1e3)}equals(e){return e.type==="iana"&&e.name===this.name}get isValid(){return this.valid}};var bV={};function e0e(t,e={}){let r=JSON.stringify([t,e]),n=bV[r];return n||(n=new Intl.ListFormat(t,e),bV[r]=n),n}var $S={};function TS(t,e={}){let r=JSON.stringify([t,e]),n=$S[r];return n||(n=new Intl.DateTimeFormat(t,e),$S[r]=n),n}var IS={};function t0e(t,e={}){let r=JSON.stringify([t,e]),n=IS[r];return n||(n=new Intl.NumberFormat(t,e),IS[r]=n),n}var DS={};function r0e(t,e={}){let{base:r,...n}=e,o=JSON.stringify([t,n]),a=DS[o];return a||(a=new Intl.RelativeTimeFormat(t,e),DS[o]=a),a}var wh=null;function n0e(){return wh||(wh=new Intl.DateTimeFormat().resolvedOptions().locale,wh)}var yV={};function o0e(t){let e=yV[t];if(!e){let r=new Intl.Locale(t);e="getWeekInfo"in r?r.getWeekInfo():r.weekInfo,yV[t]=e}return e}function a0e(t){let e=t.indexOf("-x-");e!==-1&&(t=t.substring(0,e));let r=t.indexOf("-u-");if(r===-1)return[t];{let n,o;try{n=TS(t).resolvedOptions(),o=t}catch{let s=t.substring(0,r);n=TS(s).resolvedOptions(),o=s}let{numberingSystem:a,calendar:i}=n;return[o,a,i]}}function i0e(t,e,r){return(r||e)&&(t.includes("-u-")||(t+="-u"),r&&(t+=`-ca-${r}`),e&&(t+=`-nu-${e}`)),t}function s0e(t){let e=[];for(let r=1;r<=12;r++){let n=dt.utc(2009,r,1);e.push(t(n))}return e}function l0e(t){let e=[];for(let r=1;r<=7;r++){let n=dt.utc(2016,11,13+r);e.push(t(n))}return e}function v2(t,e,r,n){let o=t.listingMode();return o==="error"?null:o==="en"?r(e):n(e)}function u0e(t){return t.numberingSystem&&t.numberingSystem!=="latn"?!1:t.numberingSystem==="latn"||!t.locale||t.locale.startsWith("en")||new Intl.DateTimeFormat(t.intl).resolvedOptions().numberingSystem==="latn"}var AS=class{constructor(e,r,n){this.padTo=n.padTo||0,this.floor=n.floor||!1;let{padTo:o,floor:a,...i}=n;if(!r||Object.keys(i).length>0){let l={useGrouping:!1,...n};n.padTo>0&&(l.minimumIntegerDigits=n.padTo),this.inf=t0e(e,l)}}format(e){if(this.inf){let r=this.floor?Math.floor(e):e;return this.inf.format(r)}else{let r=this.floor?Math.floor(e):xf(e,3);return dr(r,this.padTo)}}},LS=class{constructor(e,r,n){this.opts=n,this.originalZone=void 0;let o;if(this.opts.timeZone)this.dt=e;else if(e.zone.type==="fixed"){let i=-1*(e.offset/60),l=i>=0?`Etc/GMT+${i}`:`Etc/GMT${i}`;e.offset!==0&&hn.create(l).valid?(o=l,this.dt=e):(o="UTC",this.dt=e.offset===0?e:e.setZone("UTC").plus({minutes:e.offset}),this.originalZone=e.zone)}else e.zone.type==="system"?this.dt=e:e.zone.type==="iana"?(this.dt=e,o=e.zone.name):(o="UTC",this.dt=e.setZone("UTC").plus({minutes:e.offset}),this.originalZone=e.zone);let a={...this.opts};a.timeZone=a.timeZone||o,this.dtf=TS(r,a)}format(){return this.originalZone?this.formatToParts().map(({value:e})=>e).join(""):this.dtf.format(this.dt.toJSDate())}formatToParts(){let e=this.dtf.formatToParts(this.dt.toJSDate());return this.originalZone?e.map(r=>{if(r.type==="timeZoneName"){let n=this.originalZone.offsetName(this.dt.ts,{locale:this.dt.locale,format:this.opts.timeZoneName});return{...r,value:n}}else return r}):e}resolvedOptions(){return this.dtf.resolvedOptions()}},_S=class{constructor(e,r,n){this.opts={style:"long",...n},!r&&b2()&&(this.rtf=r0e(e,n))}format(e,r){return this.rtf?this.rtf.format(e,r):xV(r,e,this.opts.numeric,this.opts.style!=="long")}formatToParts(e,r){return this.rtf?this.rtf.formatToParts(e,r):[]}},c0e={firstDay:1,minimalDays:4,weekend:[6,7]},At=class t{static fromOpts(e){return t.create(e.locale,e.numberingSystem,e.outputCalendar,e.weekSettings,e.defaultToEN)}static create(e,r,n,o,a=!1){let i=e||St.defaultLocale,l=i||(a?"en-US":n0e()),s=r||St.defaultNumberingSystem,u=n||St.defaultOutputCalendar,c=Sh(o)||St.defaultWeekSettings;return new t(l,s,u,c,i)}static resetCache(){wh=null,$S={},IS={},DS={}}static fromObject({locale:e,numberingSystem:r,outputCalendar:n,weekSettings:o}={}){return t.create(e,r,n,o)}constructor(e,r,n,o,a){let[i,l,s]=a0e(e);this.locale=i,this.numberingSystem=r||l||null,this.outputCalendar=n||s||null,this.weekSettings=o,this.intl=i0e(this.locale,this.numberingSystem,this.outputCalendar),this.weekdaysCache={format:{},standalone:{}},this.monthsCache={format:{},standalone:{}},this.meridiemCache=null,this.eraCache={},this.specifiedLocale=a,this.fastNumbersCached=null}get fastNumbers(){return this.fastNumbersCached==null&&(this.fastNumbersCached=u0e(this)),this.fastNumbersCached}listingMode(){let e=this.isEnglish(),r=(this.numberingSystem===null||this.numberingSystem==="latn")&&(this.outputCalendar===null||this.outputCalendar==="gregory");return e&&r?"en":"intl"}clone(e){return!e||Object.getOwnPropertyNames(e).length===0?this:t.create(e.locale||this.specifiedLocale,e.numberingSystem||this.numberingSystem,e.outputCalendar||this.outputCalendar,Sh(e.weekSettings)||this.weekSettings,e.defaultToEN||!1)}redefaultToEN(e={}){return this.clone({...e,defaultToEN:!0})}redefaultToSystem(e={}){return this.clone({...e,defaultToEN:!1})}months(e,r=!1){return v2(this,e,MS,()=>{let n=r?{month:e,day:"numeric"}:{month:e},o=r?"format":"standalone";return this.monthsCache[o][e]||(this.monthsCache[o][e]=s0e(a=>this.extract(a,n,"month"))),this.monthsCache[o][e]})}weekdays(e,r=!1){return v2(this,e,NS,()=>{let n=r?{weekday:e,year:"numeric",month:"long",day:"numeric"}:{weekday:e},o=r?"format":"standalone";return this.weekdaysCache[o][e]||(this.weekdaysCache[o][e]=l0e(a=>this.extract(a,n,"weekday"))),this.weekdaysCache[o][e]})}meridiems(){return v2(this,void 0,()=>kS,()=>{if(!this.meridiemCache){let e={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[dt.utc(2016,11,13,9),dt.utc(2016,11,13,19)].map(r=>this.extract(r,e,"dayperiod"))}return this.meridiemCache})}eras(e){return v2(this,e,PS,()=>{let r={era:e};return this.eraCache[e]||(this.eraCache[e]=[dt.utc(-40,1,1),dt.utc(2017,1,1)].map(n=>this.extract(n,r,"era"))),this.eraCache[e]})}extract(e,r,n){let o=this.dtFormatter(e,r),a=o.formatToParts(),i=a.find(l=>l.type.toLowerCase()===n);return i?i.value:null}numberFormatter(e={}){return new AS(this.intl,e.forceSimple||this.fastNumbers,e)}dtFormatter(e,r={}){return new LS(e,this.intl,r)}relFormatter(e={}){return new _S(this.intl,this.isEnglish(),e)}listFormatter(e={}){return e0e(this.intl,e)}isEnglish(){return this.locale==="en"||this.locale.toLowerCase()==="en-us"||new Intl.DateTimeFormat(this.intl).resolvedOptions().locale.startsWith("en-us")}getWeekSettings(){return this.weekSettings?this.weekSettings:y2()?o0e(this.locale):c0e}getStartOfWeek(){return this.getWeekSettings().firstDay}getMinDaysInFirstWeek(){return this.getWeekSettings().minimalDays}getWeekendDays(){return this.getWeekSettings().weekend}equals(e){return this.locale===e.locale&&this.numberingSystem===e.numberingSystem&&this.outputCalendar===e.outputCalendar}};var RS=null,tn=class t extends no{static get utcInstance(){return RS===null&&(RS=new t(0)),RS}static instance(e){return e===0?t.utcInstance:new t(e)}static parseSpecifier(e){if(e){let r=e.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(r)return new t(ic(r[1],r[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${vl(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${vl(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(e,r){return vl(this.fixed,r)}get isUniversal(){return!0}offset(){return this.fixed}equals(e){return e.type==="fixed"&&e.fixed===this.fixed}get isValid(){return!0}};var Cf=class extends no{constructor(e){super(),this.zoneName=e}get type(){return"invalid"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(){return null}formatOffset(){return""}offset(){return NaN}equals(){return!1}get isValid(){return!1}};function wa(t,e){let r;if(ke(t)||t===null)return e;if(t instanceof no)return t;if(CV(t)){let n=t.toLowerCase();return n==="default"?e:n==="local"||n==="system"?hl.instance:n==="utc"||n==="gmt"?tn.utcInstance:tn.parseSpecifier(n)||hn.create(t)}else return si(t)?tn.instance(t):typeof t=="object"&&"offset"in t&&typeof t.offset=="function"?t:new Cf(t)}var wV=()=>Date.now(),SV="system",EV=null,$V=null,TV=null,IV=60,DV,AV=null,St=class{static get now(){return wV}static set now(e){wV=e}static set defaultZone(e){SV=e}static get defaultZone(){return wa(SV,hl.instance)}static get defaultLocale(){return EV}static set defaultLocale(e){EV=e}static get defaultNumberingSystem(){return $V}static set defaultNumberingSystem(e){$V=e}static get defaultOutputCalendar(){return TV}static set defaultOutputCalendar(e){TV=e}static get defaultWeekSettings(){return AV}static set defaultWeekSettings(e){AV=Sh(e)}static get twoDigitCutoffYear(){return IV}static set twoDigitCutoffYear(e){IV=e%100}static get throwOnInvalid(){return DV}static set throwOnInvalid(e){DV=e}static resetCaches(){At.resetCache(),hn.resetCache()}};var rn=class{constructor(e,r){this.reason=e,this.explanation=r}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}};var LV=[0,31,59,90,120,151,181,212,243,273,304,334],_V=[0,31,60,91,121,152,182,213,244,274,305,335];function Ko(t,e){return new rn("unit out of range",`you specified ${e} (of type ${typeof e}) as a ${t}, which is invalid`)}function x2(t,e,r){let n=new Date(Date.UTC(t,e-1,r));t<100&&t>=0&&n.setUTCFullYear(n.getUTCFullYear()-1900);let o=n.getUTCDay();return o===0?7:o}function MV(t,e,r){return r+(lc(t)?_V:LV)[e-1]}function NV(t,e){let r=lc(t)?_V:LV,n=r.findIndex(a=>a<e),o=e-r[n];return{month:n+1,day:o}}function C2(t,e){return(t-e+7)%7+1}function Eh(t,e=4,r=1){let{year:n,month:o,day:a}=t,i=MV(n,o,a),l=C2(x2(n,o,a),r),s=Math.floor((i-l+14-e)/7),u;return s<1?(u=n-1,s=sc(u,e,r)):s>sc(n,e,r)?(u=n+1,s=1):u=n,{weekYear:u,weekNumber:s,weekday:l,...Th(t)}}function FS(t,e=4,r=1){let{weekYear:n,weekNumber:o,weekday:a}=t,i=C2(x2(n,1,e),r),l=bl(n),s=o*7+a-i-7+e,u;s<1?(u=n-1,s+=bl(u)):s>l?(u=n+1,s-=bl(n)):u=n;let{month:c,day:d}=NV(u,s);return{year:u,month:c,day:d,...Th(t)}}function w2(t){let{year:e,month:r,day:n}=t,o=MV(e,r,n);return{year:e,ordinal:o,...Th(t)}}function BS(t){let{year:e,ordinal:r}=t,{month:n,day:o}=NV(e,r);return{year:e,month:n,day:o,...Th(t)}}function VS(t,e){if(!ke(t.localWeekday)||!ke(t.localWeekNumber)||!ke(t.localWeekYear)){if(!ke(t.weekday)||!ke(t.weekNumber)||!ke(t.weekYear))throw new ya("Cannot mix locale-based week fields with ISO-based week fields");return ke(t.localWeekday)||(t.weekday=t.localWeekday),ke(t.localWeekNumber)||(t.weekNumber=t.localWeekNumber),ke(t.localWeekYear)||(t.weekYear=t.localWeekYear),delete t.localWeekday,delete t.localWeekNumber,delete t.localWeekYear,{minDaysInFirstWeek:e.getMinDaysInFirstWeek(),startOfWeek:e.getStartOfWeek()}}else return{minDaysInFirstWeek:4,startOfWeek:1}}function kV(t,e=4,r=1){let n=$h(t.weekYear),o=Io(t.weekNumber,1,sc(t.weekYear,e,r)),a=Io(t.weekday,1,7);return n?o?a?!1:Ko("weekday",t.weekday):Ko("week",t.weekNumber):Ko("weekYear",t.weekYear)}function PV(t){let e=$h(t.year),r=Io(t.ordinal,1,bl(t.year));return e?r?!1:Ko("ordinal",t.ordinal):Ko("year",t.year)}function jS(t){let e=$h(t.year),r=Io(t.month,1,12),n=Io(t.day,1,wf(t.year,t.month));return e?r?n?!1:Ko("day",t.day):Ko("month",t.month):Ko("year",t.year)}function zS(t){let{hour:e,minute:r,second:n,millisecond:o}=t,a=Io(e,0,23)||e===24&&r===0&&n===0&&o===0,i=Io(r,0,59),l=Io(n,0,59),s=Io(o,0,999);return a?i?l?s?!1:Ko("millisecond",o):Ko("second",n):Ko("minute",r):Ko("hour",e)}function ke(t){return typeof t>"u"}function si(t){return typeof t=="number"}function $h(t){return typeof t=="number"&&t%1===0}function CV(t){return typeof t=="string"}function RV(t){return Object.prototype.toString.call(t)==="[object Date]"}function b2(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}function y2(){try{return typeof Intl<"u"&&!!Intl.Locale&&("weekInfo"in Intl.Locale.prototype||"getWeekInfo"in Intl.Locale.prototype)}catch{return!1}}function FV(t){return Array.isArray(t)?t:[t]}function HS(t,e,r){if(t.length!==0)return t.reduce((n,o)=>{let a=[e(o),o];return n&&r(n[0],a[0])===n[0]?n:a},null)[1]}function BV(t,e){return e.reduce((r,n)=>(r[n]=t[n],r),{})}function yl(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function Sh(t){if(t==null)return null;if(typeof t!="object")throw new Nr("Week settings must be an object");if(!Io(t.firstDay,1,7)||!Io(t.minimalDays,1,7)||!Array.isArray(t.weekend)||t.weekend.some(e=>!Io(e,1,7)))throw new Nr("Invalid week settings");return{firstDay:t.firstDay,minimalDays:t.minimalDays,weekend:Array.from(t.weekend)}}function Io(t,e,r){return $h(t)&&t>=e&&t<=r}function d0e(t,e){return t-e*Math.floor(t/e)}function dr(t,e=2){let r=t<0,n;return r?n="-"+(""+-t).padStart(e,"0"):n=(""+t).padStart(e,"0"),n}function as(t){if(!(ke(t)||t===null||t===""))return parseInt(t,10)}function xl(t){if(!(ke(t)||t===null||t===""))return parseFloat(t)}function Ih(t){if(!(ke(t)||t===null||t==="")){let e=parseFloat("0."+t)*1e3;return Math.floor(e)}}function xf(t,e,r=!1){let n=10**e;return(r?Math.trunc:Math.round)(t*n)/n}function lc(t){return t%4===0&&(t%100!==0||t%400===0)}function bl(t){return lc(t)?366:365}function wf(t,e){let r=d0e(e-1,12)+1,n=t+(e-r)/12;return r===2?lc(n)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][r-1]}function yf(t){let e=Date.UTC(t.year,t.month-1,t.day,t.hour,t.minute,t.second,t.millisecond);return t.year<100&&t.year>=0&&(e=new Date(e),e.setUTCFullYear(t.year,t.month-1,t.day)),+e}function OV(t,e,r){return-C2(x2(t,1,e),r)+e-1}function sc(t,e=4,r=1){let n=OV(t,e,r),o=OV(t+1,e,r);return(bl(t)-n+o)/7}function Dh(t){return t>99?t:t>St.twoDigitCutoffYear?1900+t:2e3+t}function m2(t,e,r,n=null){let o=new Date(t),a={hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"};n&&(a.timeZone=n);let i={timeZoneName:e,...a},l=new Intl.DateTimeFormat(r,i).formatToParts(o).find(s=>s.type.toLowerCase()==="timezonename");return l?l.value:null}function ic(t,e){let r=parseInt(t,10);Number.isNaN(r)&&(r=0);let n=parseInt(e,10)||0,o=r<0||Object.is(r,-0)?-n:n;return r*60+o}function WS(t){let e=Number(t);if(typeof t=="boolean"||t===""||Number.isNaN(e))throw new Nr(`Invalid unit value ${t}`);return e}function Sf(t,e){let r={};for(let n in t)if(yl(t,n)){let o=t[n];if(o==null)continue;r[e(n)]=WS(o)}return r}function vl(t,e){let r=Math.trunc(Math.abs(t/60)),n=Math.trunc(Math.abs(t%60)),o=t>=0?"+":"-";switch(e){case"short":return`${o}${dr(r,2)}:${dr(n,2)}`;case"narrow":return`${o}${r}${n>0?`:${n}`:""}`;case"techie":return`${o}${dr(r,2)}${dr(n,2)}`;default:throw new RangeError(`Value format ${e} is out of range for property format`)}}function Th(t){return BV(t,["hour","minute","second","millisecond"])}var f0e=["January","February","March","April","May","June","July","August","September","October","November","December"],GS=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],p0e=["J","F","M","A","M","J","J","A","S","O","N","D"];function MS(t){switch(t){case"narrow":return[...p0e];case"short":return[...GS];case"long":return[...f0e];case"numeric":return["1","2","3","4","5","6","7","8","9","10","11","12"];case"2-digit":return["01","02","03","04","05","06","07","08","09","10","11","12"];default:return null}}var US=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],ZS=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],m0e=["M","T","W","T","F","S","S"];function NS(t){switch(t){case"narrow":return[...m0e];case"short":return[...ZS];case"long":return[...US];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}var kS=["AM","PM"],g0e=["Before Christ","Anno Domini"],h0e=["BC","AD"],v0e=["B","A"];function PS(t){switch(t){case"narrow":return[...v0e];case"short":return[...h0e];case"long":return[...g0e];default:return null}}function VV(t){return kS[t.hour<12?0:1]}function jV(t,e){return NS(e)[t.weekday-1]}function zV(t,e){return MS(e)[t.month-1]}function HV(t,e){return PS(e)[t.year<0?0:1]}function xV(t,e,r="always",n=!1){let o={years:["year","yr."],quarters:["quarter","qtr."],months:["month","mo."],weeks:["week","wk."],days:["day","day","days"],hours:["hour","hr."],minutes:["minute","min."],seconds:["second","sec."]},a=["hours","minutes","seconds"].indexOf(t)===-1;if(r==="auto"&&a){let d=t==="days";switch(e){case 1:return d?"tomorrow":`next ${o[t][0]}`;case-1:return d?"yesterday":`last ${o[t][0]}`;case 0:return d?"today":`this ${o[t][0]}`;default:}}let i=Object.is(e,-0)||e<0,l=Math.abs(e),s=l===1,u=o[t],c=n?s?u[1]:u[2]||u[1]:s?o[t][0]:t;return i?`${l} ${c} ago`:`in ${l} ${c}`}function WV(t,e){let r="";for(let n of t)n.literal?r+=n.val:r+=e(n.val);return r}var b0e={D:gl,DD:nh,DDD:oh,DDDD:ah,t:ih,tt:sh,ttt:lh,tttt:uh,T:ch,TT:dh,TTT:fh,TTTT:ph,f:mh,ff:hh,fff:bh,ffff:xh,F:gh,FF:vh,FFF:yh,FFFF:Ch},nn=class t{static create(e,r={}){return new t(e,r)}static parseFormat(e){let r=null,n="",o=!1,a=[];for(let i=0;i<e.length;i++){let l=e.charAt(i);l==="'"?(n.length>0&&a.push({literal:o||/^\s+$/.test(n),val:n}),r=null,n="",o=!o):o||l===r?n+=l:(n.length>0&&a.push({literal:/^\s+$/.test(n),val:n}),n=l,r=l)}return n.length>0&&a.push({literal:o||/^\s+$/.test(n),val:n}),a}static macroTokenToFormatOpts(e){return b0e[e]}constructor(e,r){this.opts=r,this.loc=e,this.systemLoc=null}formatWithSystemDefault(e,r){return this.systemLoc===null&&(this.systemLoc=this.loc.redefaultToSystem()),this.systemLoc.dtFormatter(e,{...this.opts,...r}).format()}dtFormatter(e,r={}){return this.loc.dtFormatter(e,{...this.opts,...r})}formatDateTime(e,r){return this.dtFormatter(e,r).format()}formatDateTimeParts(e,r){return this.dtFormatter(e,r).formatToParts()}formatInterval(e,r){return this.dtFormatter(e.start,r).dtf.formatRange(e.start.toJSDate(),e.end.toJSDate())}resolvedOptions(e,r){return this.dtFormatter(e,r).resolvedOptions()}num(e,r=0){if(this.opts.forceSimple)return dr(e,r);let n={...this.opts};return r>0&&(n.padTo=r),this.loc.numberFormatter(n).format(e)}formatDateTimeFromString(e,r){let n=this.loc.listingMode()==="en",o=this.loc.outputCalendar&&this.loc.outputCalendar!=="gregory",a=(p,m)=>this.loc.extract(e,p,m),i=p=>e.isOffsetFixed&&e.offset===0&&p.allowZ?"Z":e.isValid?e.zone.formatOffset(e.ts,p.format):"",l=()=>n?VV(e):a({hour:"numeric",hourCycle:"h12"},"dayperiod"),s=(p,m)=>n?zV(e,p):a(m?{month:p}:{month:p,day:"numeric"},"month"),u=(p,m)=>n?jV(e,p):a(m?{weekday:p}:{weekday:p,month:"long",day:"numeric"},"weekday"),c=p=>{let m=t.macroTokenToFormatOpts(p);return m?this.formatWithSystemDefault(e,m):p},d=p=>n?HV(e,p):a({era:p},"era"),f=p=>{switch(p){case"S":return this.num(e.millisecond);case"u":case"SSS":return this.num(e.millisecond,3);case"s":return this.num(e.second);case"ss":return this.num(e.second,2);case"uu":return this.num(Math.floor(e.millisecond/10),2);case"uuu":return this.num(Math.floor(e.millisecond/100));case"m":return this.num(e.minute);case"mm":return this.num(e.minute,2);case"h":return this.num(e.hour%12===0?12:e.hour%12);case"hh":return this.num(e.hour%12===0?12:e.hour%12,2);case"H":return this.num(e.hour);case"HH":return this.num(e.hour,2);case"Z":return i({format:"narrow",allowZ:this.opts.allowZ});case"ZZ":return i({format:"short",allowZ:this.opts.allowZ});case"ZZZ":return i({format:"techie",allowZ:this.opts.allowZ});case"ZZZZ":return e.zone.offsetName(e.ts,{format:"short",locale:this.loc.locale});case"ZZZZZ":return e.zone.offsetName(e.ts,{format:"long",locale:this.loc.locale});case"z":return e.zoneName;case"a":return l();case"d":return o?a({day:"numeric"},"day"):this.num(e.day);case"dd":return o?a({day:"2-digit"},"day"):this.num(e.day,2);case"c":return this.num(e.weekday);case"ccc":return u("short",!0);case"cccc":return u("long",!0);case"ccccc":return u("narrow",!0);case"E":return this.num(e.weekday);case"EEE":return u("short",!1);case"EEEE":return u("long",!1);case"EEEEE":return u("narrow",!1);case"L":return o?a({month:"numeric",day:"numeric"},"month"):this.num(e.month);case"LL":return o?a({month:"2-digit",day:"numeric"},"month"):this.num(e.month,2);case"LLL":return s("short",!0);case"LLLL":return s("long",!0);case"LLLLL":return s("narrow",!0);case"M":return o?a({month:"numeric"},"month"):this.num(e.month);case"MM":return o?a({month:"2-digit"},"month"):this.num(e.month,2);case"MMM":return s("short",!1);case"MMMM":return s("long",!1);case"MMMMM":return s("narrow",!1);case"y":return o?a({year:"numeric"},"year"):this.num(e.year);case"yy":return o?a({year:"2-digit"},"year"):this.num(e.year.toString().slice(-2),2);case"yyyy":return o?a({year:"numeric"},"year"):this.num(e.year,4);case"yyyyyy":return o?a({year:"numeric"},"year"):this.num(e.year,6);case"G":return d("short");case"GG":return d("long");case"GGGGG":return d("narrow");case"kk":return this.num(e.weekYear.toString().slice(-2),2);case"kkkk":return this.num(e.weekYear,4);case"W":return this.num(e.weekNumber);case"WW":return this.num(e.weekNumber,2);case"n":return this.num(e.localWeekNumber);case"nn":return this.num(e.localWeekNumber,2);case"ii":return this.num(e.localWeekYear.toString().slice(-2),2);case"iiii":return this.num(e.localWeekYear,4);case"o":return this.num(e.ordinal);case"ooo":return this.num(e.ordinal,3);case"q":return this.num(e.quarter);case"qq":return this.num(e.quarter,2);case"X":return this.num(Math.floor(e.ts/1e3));case"x":return this.num(e.ts);default:return c(p)}};return WV(t.parseFormat(r),f)}formatDurationFromString(e,r){let n=s=>{switch(s[0]){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":return"hour";case"d":return"day";case"w":return"week";case"M":return"month";case"y":return"year";default:return null}},o=s=>u=>{let c=n(u);return c?this.num(s.get(c),u.length):u},a=t.parseFormat(r),i=a.reduce((s,{literal:u,val:c})=>u?s:s.concat(c),[]),l=e.shiftTo(...i.map(n).filter(s=>s));return WV(a,o(l))}};var UV=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;function $f(...t){let e=t.reduce((r,n)=>r+n.source,"");return RegExp(`^${e}$`)}function Tf(...t){return e=>t.reduce(([r,n,o],a)=>{let[i,l,s]=a(e,o);return[{...r,...i},l||n,s]},[{},null,1]).slice(0,2)}function If(t,...e){if(t==null)return[null,null];for(let[r,n]of e){let o=r.exec(t);if(o)return n(o)}return[null,null]}function ZV(...t){return(e,r)=>{let n={},o;for(o=0;o<t.length;o++)n[t[o]]=as(e[r+o]);return[n,null,r+o]}}var YV=/(?:(Z)|([+-]\d\d)(?::?(\d\d))?)/,y0e=`(?:${YV.source}?(?:\\[(${UV.source})\\])?)?`,YS=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,KV=RegExp(`${YS.source}${y0e}`),KS=RegExp(`(?:T${KV.source})?`),x0e=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,C0e=/(\d{4})-?W(\d\d)(?:-?(\d))?/,w0e=/(\d{4})-?(\d{3})/,S0e=ZV("weekYear","weekNumber","weekDay"),E0e=ZV("year","ordinal"),$0e=/(\d{4})-(\d\d)-(\d\d)/,XV=RegExp(`${YS.source} ?(?:${YV.source}|(${UV.source}))?`),T0e=RegExp(`(?: ${XV.source})?`);function Ef(t,e,r){let n=t[e];return ke(n)?r:as(n)}function I0e(t,e){return[{year:Ef(t,e),month:Ef(t,e+1,1),day:Ef(t,e+2,1)},null,e+3]}function Df(t,e){return[{hours:Ef(t,e,0),minutes:Ef(t,e+1,0),seconds:Ef(t,e+2,0),milliseconds:Ih(t[e+3])},null,e+4]}function Ah(t,e){let r=!t[e]&&!t[e+1],n=ic(t[e+1],t[e+2]),o=r?null:tn.instance(n);return[{},o,e+3]}function Lh(t,e){let r=t[e]?hn.create(t[e]):null;return[{},r,e+1]}var D0e=RegExp(`^T?${YS.source}$`),A0e=/^-?P(?:(?:(-?\d{1,20}(?:\.\d{1,20})?)Y)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20}(?:\.\d{1,20})?)W)?(?:(-?\d{1,20}(?:\.\d{1,20})?)D)?(?:T(?:(-?\d{1,20}(?:\.\d{1,20})?)H)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20})(?:[.,](-?\d{1,20}))?S)?)?)$/;function L0e(t){let[e,r,n,o,a,i,l,s,u]=t,c=e[0]==="-",d=s&&s[0]==="-",f=(p,m=!1)=>p!==void 0&&(m||p&&c)?-p:p;return[{years:f(xl(r)),months:f(xl(n)),weeks:f(xl(o)),days:f(xl(a)),hours:f(xl(i)),minutes:f(xl(l)),seconds:f(xl(s),s==="-0"),milliseconds:f(Ih(u),d)}]}var _0e={GMT:0,EDT:-4*60,EST:-5*60,CDT:-5*60,CST:-6*60,MDT:-6*60,MST:-7*60,PDT:-7*60,PST:-8*60};function XS(t,e,r,n,o,a,i){let l={year:e.length===2?Dh(as(e)):as(e),month:GS.indexOf(r)+1,day:as(n),hour:as(o),minute:as(a)};return i&&(l.second=as(i)),t&&(l.weekday=t.length>3?US.indexOf(t)+1:ZS.indexOf(t)+1),l}var M0e=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/;function N0e(t){let[,e,r,n,o,a,i,l,s,u,c,d]=t,f=XS(e,o,n,r,a,i,l),p;return s?p=_0e[s]:u?p=0:p=ic(c,d),[f,new tn(p)]}function k0e(t){return t.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}var P0e=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/,O0e=/^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/,R0e=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/;function GV(t){let[,e,r,n,o,a,i,l]=t;return[XS(e,o,n,r,a,i,l),tn.utcInstance]}function F0e(t){let[,e,r,n,o,a,i,l]=t;return[XS(e,l,r,n,o,a,i),tn.utcInstance]}var B0e=$f(x0e,KS),V0e=$f(C0e,KS),j0e=$f(w0e,KS),z0e=$f(KV),JV=Tf(I0e,Df,Ah,Lh),H0e=Tf(S0e,Df,Ah,Lh),W0e=Tf(E0e,Df,Ah,Lh),G0e=Tf(Df,Ah,Lh);function qV(t){return If(t,[B0e,JV],[V0e,H0e],[j0e,W0e],[z0e,G0e])}function QV(t){return If(k0e(t),[M0e,N0e])}function ej(t){return If(t,[P0e,GV],[O0e,GV],[R0e,F0e])}function tj(t){return If(t,[A0e,L0e])}var U0e=Tf(Df);function rj(t){return If(t,[D0e,U0e])}var Z0e=$f($0e,T0e),Y0e=$f(XV),K0e=Tf(Df,Ah,Lh);function nj(t){return If(t,[Z0e,JV],[Y0e,K0e])}var oj="Invalid Duration",ij={weeks:{days:7,hours:7*24,minutes:7*24*60,seconds:7*24*60*60,milliseconds:7*24*60*60*1e3},days:{hours:24,minutes:24*60,seconds:24*60*60,milliseconds:24*60*60*1e3},hours:{minutes:60,seconds:60*60,milliseconds:60*60*1e3},minutes:{seconds:60,milliseconds:60*1e3},seconds:{milliseconds:1e3}},X0e={years:{quarters:4,months:12,weeks:52,days:365,hours:365*24,minutes:365*24*60,seconds:365*24*60*60,milliseconds:365*24*60*60*1e3},quarters:{months:3,weeks:13,days:91,hours:91*24,minutes:91*24*60,seconds:91*24*60*60,milliseconds:91*24*60*60*1e3},months:{weeks:4,days:30,hours:30*24,minutes:30*24*60,seconds:30*24*60*60,milliseconds:30*24*60*60*1e3},...ij},Xo=146097/400,Af=146097/4800,J0e={years:{quarters:4,months:12,weeks:Xo/7,days:Xo,hours:Xo*24,minutes:Xo*24*60,seconds:Xo*24*60*60,milliseconds:Xo*24*60*60*1e3},quarters:{months:3,weeks:Xo/28,days:Xo/4,hours:Xo*24/4,minutes:Xo*24*60/4,seconds:Xo*24*60*60/4,milliseconds:Xo*24*60*60*1e3/4},months:{weeks:Af/7,days:Af,hours:Af*24,minutes:Af*24*60,seconds:Af*24*60*60,milliseconds:Af*24*60*60*1e3},...ij},uc=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],q0e=uc.slice(0).reverse();function Cl(t,e,r=!1){let n={values:r?e.values:{...t.values,...e.values||{}},loc:t.loc.clone(e.loc),conversionAccuracy:e.conversionAccuracy||t.conversionAccuracy,matrix:e.matrix||t.matrix};return new fr(n)}function sj(t,e){let r=e.milliseconds??0;for(let n of q0e.slice(1))e[n]&&(r+=e[n]*t[n].milliseconds);return r}function aj(t,e){let r=sj(t,e)<0?-1:1;uc.reduceRight((n,o)=>{if(ke(e[o]))return n;if(n){let a=e[n]*r,i=t[o][n],l=Math.floor(a/i);e[o]+=l*r,e[n]-=l*i*r}return o},null),uc.reduce((n,o)=>{if(ke(e[o]))return n;if(n){let a=e[n]%1;e[n]-=a,e[o]+=a*t[n][o]}return o},null)}function Q0e(t){let e={};for(let[r,n]of Object.entries(t))n!==0&&(e[r]=n);return e}var fr=class t{constructor(e){let r=e.conversionAccuracy==="longterm"||!1,n=r?J0e:X0e;e.matrix&&(n=e.matrix),this.values=e.values,this.loc=e.loc||At.create(),this.conversionAccuracy=r?"longterm":"casual",this.invalid=e.invalid||null,this.matrix=n,this.isLuxonDuration=!0}static fromMillis(e,r){return t.fromObject({milliseconds:e},r)}static fromObject(e,r={}){if(e==null||typeof e!="object")throw new Nr(`Duration.fromObject: argument expected to be an object, got ${e===null?"null":typeof e}`);return new t({values:Sf(e,t.normalizeUnit),loc:At.fromObject(r),conversionAccuracy:r.conversionAccuracy,matrix:r.matrix})}static fromDurationLike(e){if(si(e))return t.fromMillis(e);if(t.isDuration(e))return e;if(typeof e=="object")return t.fromObject(e);throw new Nr(`Unknown duration argument ${e} of type ${typeof e}`)}static fromISO(e,r){let[n]=tj(e);return n?t.fromObject(n,r):t.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static fromISOTime(e,r){let[n]=rj(e);return n?t.fromObject(n,r):t.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static invalid(e,r=null){if(!e)throw new Nr("need to specify a reason the Duration is invalid");let n=e instanceof rn?e:new rn(e,r);if(St.throwOnInvalid)throw new f2(n);return new t({invalid:n})}static normalizeUnit(e){let r={year:"years",years:"years",quarter:"quarters",quarters:"quarters",month:"months",months:"months",week:"weeks",weeks:"weeks",day:"days",days:"days",hour:"hours",hours:"hours",minute:"minutes",minutes:"minutes",second:"seconds",seconds:"seconds",millisecond:"milliseconds",milliseconds:"milliseconds"}[e&&e.toLowerCase()];if(!r)throw new bf(e);return r}static isDuration(e){return e&&e.isLuxonDuration||!1}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}toFormat(e,r={}){let n={...r,floor:r.round!==!1&&r.floor!==!1};return this.isValid?nn.create(this.loc,n).formatDurationFromString(this,e):oj}toHuman(e={}){if(!this.isValid)return oj;let r=uc.map(n=>{let o=this.values[n];return ke(o)?null:this.loc.numberFormatter({style:"unit",unitDisplay:"long",...e,unit:n.slice(0,-1)}).format(o)}).filter(n=>n);return this.loc.listFormatter({type:"conjunction",style:e.listStyle||"narrow",...e}).format(r)}toObject(){return this.isValid?{...this.values}:{}}toISO(){if(!this.isValid)return null;let e="P";return this.years!==0&&(e+=this.years+"Y"),(this.months!==0||this.quarters!==0)&&(e+=this.months+this.quarters*3+"M"),this.weeks!==0&&(e+=this.weeks+"W"),this.days!==0&&(e+=this.days+"D"),(this.hours!==0||this.minutes!==0||this.seconds!==0||this.milliseconds!==0)&&(e+="T"),this.hours!==0&&(e+=this.hours+"H"),this.minutes!==0&&(e+=this.minutes+"M"),(this.seconds!==0||this.milliseconds!==0)&&(e+=xf(this.seconds+this.milliseconds/1e3,3)+"S"),e==="P"&&(e+="T0S"),e}toISOTime(e={}){if(!this.isValid)return null;let r=this.toMillis();return r<0||r>=864e5?null:(e={suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:"extended",...e,includeOffset:!1},dt.fromMillis(r,{zone:"UTC"}).toISOTime(e))}toJSON(){return this.toISO()}toString(){return this.toISO()}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`Duration { values: ${JSON.stringify(this.values)} }`:`Duration { Invalid, reason: ${this.invalidReason} }`}toMillis(){return this.isValid?sj(this.matrix,this.values):NaN}valueOf(){return this.toMillis()}plus(e){if(!this.isValid)return this;let r=t.fromDurationLike(e),n={};for(let o of uc)(yl(r.values,o)||yl(this.values,o))&&(n[o]=r.get(o)+this.get(o));return Cl(this,{values:n},!0)}minus(e){if(!this.isValid)return this;let r=t.fromDurationLike(e);return this.plus(r.negate())}mapUnits(e){if(!this.isValid)return this;let r={};for(let n of Object.keys(this.values))r[n]=WS(e(this.values[n],n));return Cl(this,{values:r},!0)}get(e){return this[t.normalizeUnit(e)]}set(e){if(!this.isValid)return this;let r={...this.values,...Sf(e,t.normalizeUnit)};return Cl(this,{values:r})}reconfigure({locale:e,numberingSystem:r,conversionAccuracy:n,matrix:o}={}){let i={loc:this.loc.clone({locale:e,numberingSystem:r}),matrix:o,conversionAccuracy:n};return Cl(this,i)}as(e){return this.isValid?this.shiftTo(e).get(e):NaN}normalize(){if(!this.isValid)return this;let e=this.toObject();return aj(this.matrix,e),Cl(this,{values:e},!0)}rescale(){if(!this.isValid)return this;let e=Q0e(this.normalize().shiftToAll().toObject());return Cl(this,{values:e},!0)}shiftTo(...e){if(!this.isValid)return this;if(e.length===0)return this;e=e.map(i=>t.normalizeUnit(i));let r={},n={},o=this.toObject(),a;for(let i of uc)if(e.indexOf(i)>=0){a=i;let l=0;for(let u in n)l+=this.matrix[u][i]*n[u],n[u]=0;si(o[i])&&(l+=o[i]);let s=Math.trunc(l);r[i]=s,n[i]=(l*1e3-s*1e3)/1e3}else si(o[i])&&(n[i]=o[i]);for(let i in n)n[i]!==0&&(r[a]+=i===a?n[i]:n[i]/this.matrix[a][i]);return aj(this.matrix,r),Cl(this,{values:r},!0)}shiftToAll(){return this.isValid?this.shiftTo("years","months","weeks","days","hours","minutes","seconds","milliseconds"):this}negate(){if(!this.isValid)return this;let e={};for(let r of Object.keys(this.values))e[r]=this.values[r]===0?0:-this.values[r];return Cl(this,{values:e},!0)}get years(){return this.isValid?this.values.years||0:NaN}get quarters(){return this.isValid?this.values.quarters||0:NaN}get months(){return this.isValid?this.values.months||0:NaN}get weeks(){return this.isValid?this.values.weeks||0:NaN}get days(){return this.isValid?this.values.days||0:NaN}get hours(){return this.isValid?this.values.hours||0:NaN}get minutes(){return this.isValid?this.values.minutes||0:NaN}get seconds(){return this.isValid?this.values.seconds||0:NaN}get milliseconds(){return this.isValid?this.values.milliseconds||0:NaN}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}equals(e){if(!this.isValid||!e.isValid||!this.loc.equals(e.loc))return!1;function r(n,o){return n===void 0||n===0?o===void 0||o===0:n===o}for(let n of uc)if(!r(this.values[n],e.values[n]))return!1;return!0}};var Lf="Invalid Interval";function e1e(t,e){return!t||!t.isValid?is.invalid("missing or invalid start"):!e||!e.isValid?is.invalid("missing or invalid end"):e<t?is.invalid("end before start",`The end of an interval must be after its start, but you had start=${t.toISO()} and end=${e.toISO()}`):null}var is=class t{constructor(e){this.s=e.start,this.e=e.end,this.invalid=e.invalid||null,this.isLuxonInterval=!0}static invalid(e,r=null){if(!e)throw new Nr("need to specify a reason the Interval is invalid");let n=e instanceof rn?e:new rn(e,r);if(St.throwOnInvalid)throw new d2(n);return new t({invalid:n})}static fromDateTimes(e,r){let n=_f(e),o=_f(r),a=e1e(n,o);return a??new t({start:n,end:o})}static after(e,r){let n=fr.fromDurationLike(r),o=_f(e);return t.fromDateTimes(o,o.plus(n))}static before(e,r){let n=fr.fromDurationLike(r),o=_f(e);return t.fromDateTimes(o.minus(n),o)}static fromISO(e,r){let[n,o]=(e||"").split("/",2);if(n&&o){let a,i;try{a=dt.fromISO(n,r),i=a.isValid}catch{i=!1}let l,s;try{l=dt.fromISO(o,r),s=l.isValid}catch{s=!1}if(i&&s)return t.fromDateTimes(a,l);if(i){let u=fr.fromISO(o,r);if(u.isValid)return t.after(a,u)}else if(s){let u=fr.fromISO(n,r);if(u.isValid)return t.before(l,u)}}return t.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static isInterval(e){return e&&e.isLuxonInterval||!1}get start(){return this.isValid?this.s:null}get end(){return this.isValid?this.e:null}get isValid(){return this.invalidReason===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}length(e="milliseconds"){return this.isValid?this.toDuration(e).get(e):NaN}count(e="milliseconds",r){if(!this.isValid)return NaN;let n=this.start.startOf(e,r),o;return r?.useLocaleWeeks?o=this.end.reconfigure({locale:n.locale}):o=this.end,o=o.startOf(e,r),Math.floor(o.diff(n,e).get(e))+(o.valueOf()!==this.end.valueOf())}hasSame(e){return this.isValid?this.isEmpty()||this.e.minus(1).hasSame(this.s,e):!1}isEmpty(){return this.s.valueOf()===this.e.valueOf()}isAfter(e){return this.isValid?this.s>e:!1}isBefore(e){return this.isValid?this.e<=e:!1}contains(e){return this.isValid?this.s<=e&&this.e>e:!1}set({start:e,end:r}={}){return this.isValid?t.fromDateTimes(e||this.s,r||this.e):this}splitAt(...e){if(!this.isValid)return[];let r=e.map(_f).filter(i=>this.contains(i)).sort((i,l)=>i.toMillis()-l.toMillis()),n=[],{s:o}=this,a=0;for(;o<this.e;){let i=r[a]||this.e,l=+i>+this.e?this.e:i;n.push(t.fromDateTimes(o,l)),o=l,a+=1}return n}splitBy(e){let r=fr.fromDurationLike(e);if(!this.isValid||!r.isValid||r.as("milliseconds")===0)return[];let{s:n}=this,o=1,a,i=[];for(;n<this.e;){let l=this.start.plus(r.mapUnits(s=>s*o));a=+l>+this.e?this.e:l,i.push(t.fromDateTimes(n,a)),n=a,o+=1}return i}divideEqually(e){return this.isValid?this.splitBy(this.length()/e).slice(0,e):[]}overlaps(e){return this.e>e.s&&this.s<e.e}abutsStart(e){return this.isValid?+this.e==+e.s:!1}abutsEnd(e){return this.isValid?+e.e==+this.s:!1}engulfs(e){return this.isValid?this.s<=e.s&&this.e>=e.e:!1}equals(e){return!this.isValid||!e.isValid?!1:this.s.equals(e.s)&&this.e.equals(e.e)}intersection(e){if(!this.isValid)return this;let r=this.s>e.s?this.s:e.s,n=this.e<e.e?this.e:e.e;return r>=n?null:t.fromDateTimes(r,n)}union(e){if(!this.isValid)return this;let r=this.s<e.s?this.s:e.s,n=this.e>e.e?this.e:e.e;return t.fromDateTimes(r,n)}static merge(e){let[r,n]=e.sort((o,a)=>o.s-a.s).reduce(([o,a],i)=>a?a.overlaps(i)||a.abutsStart(i)?[o,a.union(i)]:[o.concat([a]),i]:[o,i],[[],null]);return n&&r.push(n),r}static xor(e){let r=null,n=0,o=[],a=e.map(s=>[{time:s.s,type:"s"},{time:s.e,type:"e"}]),i=Array.prototype.concat(...a),l=i.sort((s,u)=>s.time-u.time);for(let s of l)n+=s.type==="s"?1:-1,n===1?r=s.time:(r&&+r!=+s.time&&o.push(t.fromDateTimes(r,s.time)),r=null);return t.merge(o)}difference(...e){return t.xor([this].concat(e)).map(r=>this.intersection(r)).filter(r=>r&&!r.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} \u2013 ${this.e.toISO()})`:Lf}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`Interval { start: ${this.s.toISO()}, end: ${this.e.toISO()} }`:`Interval { Invalid, reason: ${this.invalidReason} }`}toLocaleString(e=gl,r={}){return this.isValid?nn.create(this.s.loc.clone(r),e).formatInterval(this):Lf}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:Lf}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:Lf}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:Lf}toFormat(e,{separator:r=" \u2013 "}={}){return this.isValid?`${this.s.toFormat(e)}${r}${this.e.toFormat(e)}`:Lf}toDuration(e,r){return this.isValid?this.e.diff(this.s,e,r):fr.invalid(this.invalidReason)}mapEndpoints(e){return t.fromDateTimes(e(this.s),e(this.e))}};var ss=class{static hasDST(e=St.defaultZone){let r=dt.now().setZone(e).set({month:12});return!e.isUniversal&&r.offset!==r.set({month:6}).offset}static isValidIANAZone(e){return hn.isValidZone(e)}static normalizeZone(e){return wa(e,St.defaultZone)}static getStartOfWeek({locale:e=null,locObj:r=null}={}){return(r||At.create(e)).getStartOfWeek()}static getMinimumDaysInFirstWeek({locale:e=null,locObj:r=null}={}){return(r||At.create(e)).getMinDaysInFirstWeek()}static getWeekendWeekdays({locale:e=null,locObj:r=null}={}){return(r||At.create(e)).getWeekendDays().slice()}static months(e="long",{locale:r=null,numberingSystem:n=null,locObj:o=null,outputCalendar:a="gregory"}={}){return(o||At.create(r,n,a)).months(e)}static monthsFormat(e="long",{locale:r=null,numberingSystem:n=null,locObj:o=null,outputCalendar:a="gregory"}={}){return(o||At.create(r,n,a)).months(e,!0)}static weekdays(e="long",{locale:r=null,numberingSystem:n=null,locObj:o=null}={}){return(o||At.create(r,n,null)).weekdays(e)}static weekdaysFormat(e="long",{locale:r=null,numberingSystem:n=null,locObj:o=null}={}){return(o||At.create(r,n,null)).weekdays(e,!0)}static meridiems({locale:e=null}={}){return At.create(e).meridiems()}static eras(e="short",{locale:r=null}={}){return At.create(r,null,"gregory").eras(e)}static features(){return{relative:b2(),localeWeek:y2()}}};function lj(t,e){let r=o=>o.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),n=r(e)-r(t);return Math.floor(fr.fromMillis(n).as("days"))}function t1e(t,e,r){let n=[["years",(s,u)=>u.year-s.year],["quarters",(s,u)=>u.quarter-s.quarter+(u.year-s.year)*4],["months",(s,u)=>u.month-s.month+(u.year-s.year)*12],["weeks",(s,u)=>{let c=lj(s,u);return(c-c%7)/7}],["days",lj]],o={},a=t,i,l;for(let[s,u]of n)r.indexOf(s)>=0&&(i=s,o[s]=u(t,e),l=a.plus(o),l>e?(o[s]--,t=a.plus(o),t>e&&(l=t,o[s]--,t=a.plus(o))):t=l);return[t,o,l,i]}function uj(t,e,r,n){let[o,a,i,l]=t1e(t,e,r),s=e-o,u=r.filter(d=>["hours","minutes","seconds","milliseconds"].indexOf(d)>=0);u.length===0&&(i<e&&(i=o.plus({[l]:1})),i!==o&&(a[l]=(a[l]||0)+s/(i-o)));let c=fr.fromObject(a,n);return u.length>0?fr.fromMillis(s,n).shiftTo(...u).plus(c):c}var JS={arab:"[\u0660-\u0669]",arabext:"[\u06F0-\u06F9]",bali:"[\u1B50-\u1B59]",beng:"[\u09E6-\u09EF]",deva:"[\u0966-\u096F]",fullwide:"[\uFF10-\uFF19]",gujr:"[\u0AE6-\u0AEF]",hanidec:"[\u3007|\u4E00|\u4E8C|\u4E09|\u56DB|\u4E94|\u516D|\u4E03|\u516B|\u4E5D]",khmr:"[\u17E0-\u17E9]",knda:"[\u0CE6-\u0CEF]",laoo:"[\u0ED0-\u0ED9]",limb:"[\u1946-\u194F]",mlym:"[\u0D66-\u0D6F]",mong:"[\u1810-\u1819]",mymr:"[\u1040-\u1049]",orya:"[\u0B66-\u0B6F]",tamldec:"[\u0BE6-\u0BEF]",telu:"[\u0C66-\u0C6F]",thai:"[\u0E50-\u0E59]",tibt:"[\u0F20-\u0F29]",latn:"\\d"},cj={arab:[1632,1641],arabext:[1776,1785],bali:[6992,7001],beng:[2534,2543],deva:[2406,2415],fullwide:[65296,65303],gujr:[2790,2799],khmr:[6112,6121],knda:[3302,3311],laoo:[3792,3801],limb:[6470,6479],mlym:[3430,3439],mong:[6160,6169],mymr:[4160,4169],orya:[2918,2927],tamldec:[3046,3055],telu:[3174,3183],thai:[3664,3673],tibt:[3872,3881]},r1e=JS.hanidec.replace(/[\[|\]]/g,"").split("");function dj(t){let e=parseInt(t,10);if(isNaN(e)){e="";for(let r=0;r<t.length;r++){let n=t.charCodeAt(r);if(t[r].search(JS.hanidec)!==-1)e+=r1e.indexOf(t[r]);else for(let o in cj){let[a,i]=cj[o];n>=a&&n<=i&&(e+=n-a)}}return parseInt(e,10)}else return e}function Jo({numberingSystem:t},e=""){return new RegExp(`${JS[t||"latn"]}${e}`)}var n1e="missing Intl.DateTimeFormat.formatToParts support";function Et(t,e=r=>r){return{regex:t,deser:([r])=>e(dj(r))}}var o1e="\xA0",mj=`[ ${o1e}]`,gj=new RegExp(mj,"g");function a1e(t){return t.replace(/\./g,"\\.?").replace(gj,mj)}function fj(t){return t.replace(/\./g,"").replace(gj," ").toLowerCase()}function Sa(t,e){return t===null?null:{regex:RegExp(t.map(a1e).join("|")),deser:([r])=>t.findIndex(n=>fj(r)===fj(n))+e}}function pj(t,e){return{regex:t,deser:([,r,n])=>ic(r,n),groups:e}}function S2(t){return{regex:t,deser:([e])=>e}}function i1e(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function s1e(t,e){let r=Jo(e),n=Jo(e,"{2}"),o=Jo(e,"{3}"),a=Jo(e,"{4}"),i=Jo(e,"{6}"),l=Jo(e,"{1,2}"),s=Jo(e,"{1,3}"),u=Jo(e,"{1,6}"),c=Jo(e,"{1,9}"),d=Jo(e,"{2,4}"),f=Jo(e,"{4,6}"),p=g=>({regex:RegExp(i1e(g.val)),deser:([v])=>v,literal:!0}),h=(g=>{if(t.literal)return p(g);switch(g.val){case"G":return Sa(e.eras("short"),0);case"GG":return Sa(e.eras("long"),0);case"y":return Et(u);case"yy":return Et(d,Dh);case"yyyy":return Et(a);case"yyyyy":return Et(f);case"yyyyyy":return Et(i);case"M":return Et(l);case"MM":return Et(n);case"MMM":return Sa(e.months("short",!0),1);case"MMMM":return Sa(e.months("long",!0),1);case"L":return Et(l);case"LL":return Et(n);case"LLL":return Sa(e.months("short",!1),1);case"LLLL":return Sa(e.months("long",!1),1);case"d":return Et(l);case"dd":return Et(n);case"o":return Et(s);case"ooo":return Et(o);case"HH":return Et(n);case"H":return Et(l);case"hh":return Et(n);case"h":return Et(l);case"mm":return Et(n);case"m":return Et(l);case"q":return Et(l);case"qq":return Et(n);case"s":return Et(l);case"ss":return Et(n);case"S":return Et(s);case"SSS":return Et(o);case"u":return S2(c);case"uu":return S2(l);case"uuu":return Et(r);case"a":return Sa(e.meridiems(),0);case"kkkk":return Et(a);case"kk":return Et(d,Dh);case"W":return Et(l);case"WW":return Et(n);case"E":case"c":return Et(r);case"EEE":return Sa(e.weekdays("short",!1),1);case"EEEE":return Sa(e.weekdays("long",!1),1);case"ccc":return Sa(e.weekdays("short",!0),1);case"cccc":return Sa(e.weekdays("long",!0),1);case"Z":case"ZZ":return pj(new RegExp(`([+-]${l.source})(?::(${n.source}))?`),2);case"ZZZ":return pj(new RegExp(`([+-]${l.source})(${n.source})?`),2);case"z":return S2(/[a-z_+-/]{1,256}?/i);case" ":return S2(/[^\S\n\r]/);default:return p(g)}})(t)||{invalidReason:n1e};return h.token=t,h}var l1e={year:{"2-digit":"yy",numeric:"yyyyy"},month:{numeric:"M","2-digit":"MM",short:"MMM",long:"MMMM"},day:{numeric:"d","2-digit":"dd"},weekday:{short:"EEE",long:"EEEE"},dayperiod:"a",dayPeriod:"a",hour12:{numeric:"h","2-digit":"hh"},hour24:{numeric:"H","2-digit":"HH"},minute:{numeric:"m","2-digit":"mm"},second:{numeric:"s","2-digit":"ss"},timeZoneName:{long:"ZZZZZ",short:"ZZZ"}};function u1e(t,e,r){let{type:n,value:o}=t;if(n==="literal"){let s=/^\s+$/.test(o);return{literal:!s,val:s?" ":o}}let a=e[n],i=n;n==="hour"&&(e.hour12!=null?i=e.hour12?"hour12":"hour24":e.hourCycle!=null?e.hourCycle==="h11"||e.hourCycle==="h12"?i="hour12":i="hour24":i=r.hour12?"hour12":"hour24");let l=l1e[i];if(typeof l=="object"&&(l=l[a]),l)return{literal:!1,val:l}}function c1e(t){return[`^${t.map(r=>r.regex).reduce((r,n)=>`${r}(${n.source})`,"")}$`,t]}function d1e(t,e,r){let n=t.match(e);if(n){let o={},a=1;for(let i in r)if(yl(r,i)){let l=r[i],s=l.groups?l.groups+1:1;!l.literal&&l.token&&(o[l.token.val[0]]=l.deser(n.slice(a,a+s))),a+=s}return[n,o]}else return[n,{}]}function f1e(t){let e=a=>{switch(a){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":case"H":return"hour";case"d":return"day";case"o":return"ordinal";case"L":case"M":return"month";case"y":return"year";case"E":case"c":return"weekday";case"W":return"weekNumber";case"k":return"weekYear";case"q":return"quarter";default:return null}},r=null,n;return ke(t.z)||(r=hn.create(t.z)),ke(t.Z)||(r||(r=new tn(t.Z)),n=t.Z),ke(t.q)||(t.M=(t.q-1)*3+1),ke(t.h)||(t.h<12&&t.a===1?t.h+=12:t.h===12&&t.a===0&&(t.h=0)),t.G===0&&t.y&&(t.y=-t.y),ke(t.u)||(t.S=Ih(t.u)),[Object.keys(t).reduce((a,i)=>{let l=e(i);return l&&(a[l]=t[i]),a},{}),r,n]}var qS=null;function p1e(){return qS||(qS=dt.fromMillis(1555555555555)),qS}function m1e(t,e){if(t.literal)return t;let r=nn.macroTokenToFormatOpts(t.val),n=tE(r,e);return n==null||n.includes(void 0)?t:n}function QS(t,e){return Array.prototype.concat(...t.map(r=>m1e(r,e)))}function eE(t,e,r){let n=QS(nn.parseFormat(r),t),o=n.map(i=>s1e(i,t)),a=o.find(i=>i.invalidReason);if(a)return{input:e,tokens:n,invalidReason:a.invalidReason};{let[i,l]=c1e(o),s=RegExp(i,"i"),[u,c]=d1e(e,s,l),[d,f,p]=c?f1e(c):[null,null,void 0];if(yl(c,"a")&&yl(c,"H"))throw new ya("Can't include meridiem when specifying 24-hour format");return{input:e,tokens:n,regex:s,rawMatches:u,matches:c,result:d,zone:f,specificOffset:p}}}function hj(t,e,r){let{result:n,zone:o,specificOffset:a,invalidReason:i}=eE(t,e,r);return[n,o,a,i]}function tE(t,e){if(!t)return null;let n=nn.create(e,t).dtFormatter(p1e()),o=n.formatToParts(),a=n.resolvedOptions();return o.map(i=>u1e(i,t,a))}var rE="Invalid DateTime",vj=864e13;function E2(t){return new rn("unsupported zone",`the zone "${t.name}" is not supported`)}function nE(t){return t.weekData===null&&(t.weekData=Eh(t.c)),t.weekData}function oE(t){return t.localWeekData===null&&(t.localWeekData=Eh(t.c,t.loc.getMinDaysInFirstWeek(),t.loc.getStartOfWeek())),t.localWeekData}function cc(t,e){let r={ts:t.ts,zone:t.zone,c:t.c,o:t.o,loc:t.loc,invalid:t.invalid};return new dt({...r,...e,old:r})}function Ej(t,e,r){let n=t-e*60*1e3,o=r.offset(n);if(e===o)return[n,e];n-=(o-e)*60*1e3;let a=r.offset(n);return o===a?[n,o]:[t-Math.min(o,a)*60*1e3,Math.max(o,a)]}function $2(t,e){t+=e*60*1e3;let r=new Date(t);return{year:r.getUTCFullYear(),month:r.getUTCMonth()+1,day:r.getUTCDate(),hour:r.getUTCHours(),minute:r.getUTCMinutes(),second:r.getUTCSeconds(),millisecond:r.getUTCMilliseconds()}}function I2(t,e,r){return Ej(yf(t),e,r)}function bj(t,e){let r=t.o,n=t.c.year+Math.trunc(e.years),o=t.c.month+Math.trunc(e.months)+Math.trunc(e.quarters)*3,a={...t.c,year:n,month:o,day:Math.min(t.c.day,wf(n,o))+Math.trunc(e.days)+Math.trunc(e.weeks)*7},i=fr.fromObject({years:e.years-Math.trunc(e.years),quarters:e.quarters-Math.trunc(e.quarters),months:e.months-Math.trunc(e.months),weeks:e.weeks-Math.trunc(e.weeks),days:e.days-Math.trunc(e.days),hours:e.hours,minutes:e.minutes,seconds:e.seconds,milliseconds:e.milliseconds}).as("milliseconds"),l=yf(a),[s,u]=Ej(l,r,t.zone);return i!==0&&(s+=i,u=t.zone.offset(s)),{ts:s,o:u}}function _h(t,e,r,n,o,a){let{setZone:i,zone:l}=r;if(t&&Object.keys(t).length!==0||e){let s=e||l,u=dt.fromObject(t,{...r,zone:s,specificOffset:a});return i?u:u.setZone(l)}else return dt.invalid(new rn("unparsable",`the input "${o}" can't be parsed as ${n}`))}function T2(t,e,r=!0){return t.isValid?nn.create(At.create("en-US"),{allowZ:r,forceSimple:!0}).formatDateTimeFromString(t,e):null}function aE(t,e){let r=t.c.year>9999||t.c.year<0,n="";return r&&t.c.year>=0&&(n+="+"),n+=dr(t.c.year,r?6:4),e?(n+="-",n+=dr(t.c.month),n+="-",n+=dr(t.c.day)):(n+=dr(t.c.month),n+=dr(t.c.day)),n}function yj(t,e,r,n,o,a){let i=dr(t.c.hour);return e?(i+=":",i+=dr(t.c.minute),(t.c.millisecond!==0||t.c.second!==0||!r)&&(i+=":")):i+=dr(t.c.minute),(t.c.millisecond!==0||t.c.second!==0||!r)&&(i+=dr(t.c.second),(t.c.millisecond!==0||!n)&&(i+=".",i+=dr(t.c.millisecond,3))),o&&(t.isOffsetFixed&&t.offset===0&&!a?i+="Z":t.o<0?(i+="-",i+=dr(Math.trunc(-t.o/60)),i+=":",i+=dr(Math.trunc(-t.o%60))):(i+="+",i+=dr(Math.trunc(t.o/60)),i+=":",i+=dr(Math.trunc(t.o%60)))),a&&(i+="["+t.zone.ianaName+"]"),i}var $j={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},g1e={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},h1e={ordinal:1,hour:0,minute:0,second:0,millisecond:0},Tj=["year","month","day","hour","minute","second","millisecond"],v1e=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],b1e=["year","ordinal","hour","minute","second","millisecond"];function y1e(t){let e={year:"year",years:"year",month:"month",months:"month",day:"day",days:"day",hour:"hour",hours:"hour",minute:"minute",minutes:"minute",quarter:"quarter",quarters:"quarter",second:"second",seconds:"second",millisecond:"millisecond",milliseconds:"millisecond",weekday:"weekday",weekdays:"weekday",weeknumber:"weekNumber",weeksnumber:"weekNumber",weeknumbers:"weekNumber",weekyear:"weekYear",weekyears:"weekYear",ordinal:"ordinal"}[t.toLowerCase()];if(!e)throw new bf(t);return e}function xj(t){switch(t.toLowerCase()){case"localweekday":case"localweekdays":return"localWeekday";case"localweeknumber":case"localweeknumbers":return"localWeekNumber";case"localweekyear":case"localweekyears":return"localWeekYear";default:return y1e(t)}}function Cj(t,e){let r=wa(e.zone,St.defaultZone),n=At.fromObject(e),o=St.now(),a,i;if(ke(t.year))a=o;else{for(let u of Tj)ke(t[u])&&(t[u]=$j[u]);let l=jS(t)||zS(t);if(l)return dt.invalid(l);let s=r.offset(o);[a,i]=I2(t,s,r)}return new dt({ts:a,zone:r,loc:n,o:i})}function wj(t,e,r){let n=ke(r.round)?!0:r.round,o=(i,l)=>(i=xf(i,n||r.calendary?0:2,!0),e.loc.clone(r).relFormatter(r).format(i,l)),a=i=>r.calendary?e.hasSame(t,i)?0:e.startOf(i).diff(t.startOf(i),i).get(i):e.diff(t,i).get(i);if(r.unit)return o(a(r.unit),r.unit);for(let i of r.units){let l=a(i);if(Math.abs(l)>=1)return o(l,i)}return o(t>e?-0:0,r.units[r.units.length-1])}function Sj(t){let e={},r;return t.length>0&&typeof t[t.length-1]=="object"?(e=t[t.length-1],r=Array.from(t).slice(0,t.length-1)):r=Array.from(t),[e,r]}var dt=class t{constructor(e){let r=e.zone||St.defaultZone,n=e.invalid||(Number.isNaN(e.ts)?new rn("invalid input"):null)||(r.isValid?null:E2(r));this.ts=ke(e.ts)?St.now():e.ts;let o=null,a=null;if(!n)if(e.old&&e.old.ts===this.ts&&e.old.zone.equals(r))[o,a]=[e.old.c,e.old.o];else{let l=r.offset(this.ts);o=$2(this.ts,l),n=Number.isNaN(o.year)?new rn("invalid input"):null,o=n?null:o,a=n?null:l}this._zone=r,this.loc=e.loc||At.create(),this.invalid=n,this.weekData=null,this.localWeekData=null,this.c=o,this.o=a,this.isLuxonDateTime=!0}static now(){return new t({})}static local(){let[e,r]=Sj(arguments),[n,o,a,i,l,s,u]=r;return Cj({year:n,month:o,day:a,hour:i,minute:l,second:s,millisecond:u},e)}static utc(){let[e,r]=Sj(arguments),[n,o,a,i,l,s,u]=r;return e.zone=tn.utcInstance,Cj({year:n,month:o,day:a,hour:i,minute:l,second:s,millisecond:u},e)}static fromJSDate(e,r={}){let n=RV(e)?e.valueOf():NaN;if(Number.isNaN(n))return t.invalid("invalid input");let o=wa(r.zone,St.defaultZone);return o.isValid?new t({ts:n,zone:o,loc:At.fromObject(r)}):t.invalid(E2(o))}static fromMillis(e,r={}){if(si(e))return e<-vj||e>vj?t.invalid("Timestamp out of range"):new t({ts:e,zone:wa(r.zone,St.defaultZone),loc:At.fromObject(r)});throw new Nr(`fromMillis requires a numerical input, but received a ${typeof e} with value ${e}`)}static fromSeconds(e,r={}){if(si(e))return new t({ts:e*1e3,zone:wa(r.zone,St.defaultZone),loc:At.fromObject(r)});throw new Nr("fromSeconds requires a numerical input")}static fromObject(e,r={}){e=e||{};let n=wa(r.zone,St.defaultZone);if(!n.isValid)return t.invalid(E2(n));let o=At.fromObject(r),a=Sf(e,xj),{minDaysInFirstWeek:i,startOfWeek:l}=VS(a,o),s=St.now(),u=ke(r.specificOffset)?n.offset(s):r.specificOffset,c=!ke(a.ordinal),d=!ke(a.year),f=!ke(a.month)||!ke(a.day),p=d||f,m=a.weekYear||a.weekNumber;if((p||c)&&m)throw new ya("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(f&&c)throw new ya("Can't mix ordinal dates with month/day");let h=m||a.weekday&&!p,g,v,y=$2(s,u);h?(g=v1e,v=g1e,y=Eh(y,i,l)):c?(g=b1e,v=h1e,y=w2(y)):(g=Tj,v=$j);let x=!1;for(let D of g){let L=a[D];ke(L)?x?a[D]=v[D]:a[D]=y[D]:x=!0}let C=h?kV(a,i,l):c?PV(a):jS(a),w=C||zS(a);if(w)return t.invalid(w);let S=h?FS(a,i,l):c?BS(a):a,[E,$]=I2(S,u,n),T=new t({ts:E,zone:n,o:$,loc:o});return a.weekday&&p&&e.weekday!==T.weekday?t.invalid("mismatched weekday",`you can't specify both a weekday of ${a.weekday} and a date of ${T.toISO()}`):T}static fromISO(e,r={}){let[n,o]=qV(e);return _h(n,o,r,"ISO 8601",e)}static fromRFC2822(e,r={}){let[n,o]=QV(e);return _h(n,o,r,"RFC 2822",e)}static fromHTTP(e,r={}){let[n,o]=ej(e);return _h(n,o,r,"HTTP",r)}static fromFormat(e,r,n={}){if(ke(e)||ke(r))throw new Nr("fromFormat requires an input string and a format");let{locale:o=null,numberingSystem:a=null}=n,i=At.fromOpts({locale:o,numberingSystem:a,defaultToEN:!0}),[l,s,u,c]=hj(i,e,r);return c?t.invalid(c):_h(l,s,n,`format ${r}`,e,u)}static fromString(e,r,n={}){return t.fromFormat(e,r,n)}static fromSQL(e,r={}){let[n,o]=nj(e);return _h(n,o,r,"SQL",e)}static invalid(e,r=null){if(!e)throw new Nr("need to specify a reason the DateTime is invalid");let n=e instanceof rn?e:new rn(e,r);if(St.throwOnInvalid)throw new c2(n);return new t({invalid:n})}static isDateTime(e){return e&&e.isLuxonDateTime||!1}static parseFormatForOpts(e,r={}){let n=tE(e,At.fromObject(r));return n?n.map(o=>o?o.val:null).join(""):null}static expandFormat(e,r={}){return QS(nn.parseFormat(e),At.fromObject(r)).map(o=>o.val).join("")}get(e){return this[e]}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}get outputCalendar(){return this.isValid?this.loc.outputCalendar:null}get zone(){return this._zone}get zoneName(){return this.isValid?this.zone.name:null}get year(){return this.isValid?this.c.year:NaN}get quarter(){return this.isValid?Math.ceil(this.c.month/3):NaN}get month(){return this.isValid?this.c.month:NaN}get day(){return this.isValid?this.c.day:NaN}get hour(){return this.isValid?this.c.hour:NaN}get minute(){return this.isValid?this.c.minute:NaN}get second(){return this.isValid?this.c.second:NaN}get millisecond(){return this.isValid?this.c.millisecond:NaN}get weekYear(){return this.isValid?nE(this).weekYear:NaN}get weekNumber(){return this.isValid?nE(this).weekNumber:NaN}get weekday(){return this.isValid?nE(this).weekday:NaN}get isWeekend(){return this.isValid&&this.loc.getWeekendDays().includes(this.weekday)}get localWeekday(){return this.isValid?oE(this).weekday:NaN}get localWeekNumber(){return this.isValid?oE(this).weekNumber:NaN}get localWeekYear(){return this.isValid?oE(this).weekYear:NaN}get ordinal(){return this.isValid?w2(this.c).ordinal:NaN}get monthShort(){return this.isValid?ss.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?ss.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?ss.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?ss.weekdays("long",{locObj:this.loc})[this.weekday-1]:null}get offset(){return this.isValid?+this.o:NaN}get offsetNameShort(){return this.isValid?this.zone.offsetName(this.ts,{format:"short",locale:this.locale}):null}get offsetNameLong(){return this.isValid?this.zone.offsetName(this.ts,{format:"long",locale:this.locale}):null}get isOffsetFixed(){return this.isValid?this.zone.isUniversal:null}get isInDST(){return this.isOffsetFixed?!1:this.offset>this.set({month:1,day:1}).offset||this.offset>this.set({month:5}).offset}getPossibleOffsets(){if(!this.isValid||this.isOffsetFixed)return[this];let e=864e5,r=6e4,n=yf(this.c),o=this.zone.offset(n-e),a=this.zone.offset(n+e),i=this.zone.offset(n-o*r),l=this.zone.offset(n-a*r);if(i===l)return[this];let s=n-i*r,u=n-l*r,c=$2(s,i),d=$2(u,l);return c.hour===d.hour&&c.minute===d.minute&&c.second===d.second&&c.millisecond===d.millisecond?[cc(this,{ts:s}),cc(this,{ts:u})]:[this]}get isInLeapYear(){return lc(this.year)}get daysInMonth(){return wf(this.year,this.month)}get daysInYear(){return this.isValid?bl(this.year):NaN}get weeksInWeekYear(){return this.isValid?sc(this.weekYear):NaN}get weeksInLocalWeekYear(){return this.isValid?sc(this.localWeekYear,this.loc.getMinDaysInFirstWeek(),this.loc.getStartOfWeek()):NaN}resolvedLocaleOptions(e={}){let{locale:r,numberingSystem:n,calendar:o}=nn.create(this.loc.clone(e),e).resolvedOptions(this);return{locale:r,numberingSystem:n,outputCalendar:o}}toUTC(e=0,r={}){return this.setZone(tn.instance(e),r)}toLocal(){return this.setZone(St.defaultZone)}setZone(e,{keepLocalTime:r=!1,keepCalendarTime:n=!1}={}){if(e=wa(e,St.defaultZone),e.equals(this.zone))return this;if(e.isValid){let o=this.ts;if(r||n){let a=e.offset(this.ts),i=this.toObject();[o]=I2(i,a,e)}return cc(this,{ts:o,zone:e})}else return t.invalid(E2(e))}reconfigure({locale:e,numberingSystem:r,outputCalendar:n}={}){let o=this.loc.clone({locale:e,numberingSystem:r,outputCalendar:n});return cc(this,{loc:o})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;let r=Sf(e,xj),{minDaysInFirstWeek:n,startOfWeek:o}=VS(r,this.loc),a=!ke(r.weekYear)||!ke(r.weekNumber)||!ke(r.weekday),i=!ke(r.ordinal),l=!ke(r.year),s=!ke(r.month)||!ke(r.day),u=l||s,c=r.weekYear||r.weekNumber;if((u||i)&&c)throw new ya("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(s&&i)throw new ya("Can't mix ordinal dates with month/day");let d;a?d=FS({...Eh(this.c,n,o),...r},n,o):ke(r.ordinal)?(d={...this.toObject(),...r},ke(r.day)&&(d.day=Math.min(wf(d.year,d.month),d.day))):d=BS({...w2(this.c),...r});let[f,p]=I2(d,this.o,this.zone);return cc(this,{ts:f,o:p})}plus(e){if(!this.isValid)return this;let r=fr.fromDurationLike(e);return cc(this,bj(this,r))}minus(e){if(!this.isValid)return this;let r=fr.fromDurationLike(e).negate();return cc(this,bj(this,r))}startOf(e,{useLocaleWeeks:r=!1}={}){if(!this.isValid)return this;let n={},o=fr.normalizeUnit(e);switch(o){case"years":n.month=1;case"quarters":case"months":n.day=1;case"weeks":case"days":n.hour=0;case"hours":n.minute=0;case"minutes":n.second=0;case"seconds":n.millisecond=0;break;case"milliseconds":break}if(o==="weeks")if(r){let a=this.loc.getStartOfWeek(),{weekday:i}=this;i<a&&(n.weekNumber=this.weekNumber-1),n.weekday=a}else n.weekday=1;if(o==="quarters"){let a=Math.ceil(this.month/3);n.month=(a-1)*3+1}return this.set(n)}endOf(e,r){return this.isValid?this.plus({[e]:1}).startOf(e,r).minus(1):this}toFormat(e,r={}){return this.isValid?nn.create(this.loc.redefaultToEN(r)).formatDateTimeFromString(this,e):rE}toLocaleString(e=gl,r={}){return this.isValid?nn.create(this.loc.clone(r),e).formatDateTime(this):rE}toLocaleParts(e={}){return this.isValid?nn.create(this.loc.clone(e),e).formatDateTimeParts(this):[]}toISO({format:e="extended",suppressSeconds:r=!1,suppressMilliseconds:n=!1,includeOffset:o=!0,extendedZone:a=!1}={}){if(!this.isValid)return null;let i=e==="extended",l=aE(this,i);return l+="T",l+=yj(this,i,r,n,o,a),l}toISODate({format:e="extended"}={}){return this.isValid?aE(this,e==="extended"):null}toISOWeekDate(){return T2(this,"kkkk-'W'WW-c")}toISOTime({suppressMilliseconds:e=!1,suppressSeconds:r=!1,includeOffset:n=!0,includePrefix:o=!1,extendedZone:a=!1,format:i="extended"}={}){return this.isValid?(o?"T":"")+yj(this,i==="extended",r,e,n,a):null}toRFC2822(){return T2(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return T2(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?aE(this,!0):null}toSQLTime({includeOffset:e=!0,includeZone:r=!1,includeOffsetSpace:n=!0}={}){let o="HH:mm:ss.SSS";return(r||e)&&(n&&(o+=" "),r?o+="z":e&&(o+="ZZ")),T2(this,o,!0)}toSQL(e={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(e)}`:null}toString(){return this.isValid?this.toISO():rE}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`DateTime { ts: ${this.toISO()}, zone: ${this.zone.name}, locale: ${this.locale} }`:`DateTime { Invalid, reason: ${this.invalidReason} }`}valueOf(){return this.toMillis()}toMillis(){return this.isValid?this.ts:NaN}toSeconds(){return this.isValid?this.ts/1e3:NaN}toUnixInteger(){return this.isValid?Math.floor(this.ts/1e3):NaN}toJSON(){return this.toISO()}toBSON(){return this.toJSDate()}toObject(e={}){if(!this.isValid)return{};let r={...this.c};return e.includeConfig&&(r.outputCalendar=this.outputCalendar,r.numberingSystem=this.loc.numberingSystem,r.locale=this.loc.locale),r}toJSDate(){return new Date(this.isValid?this.ts:NaN)}diff(e,r="milliseconds",n={}){if(!this.isValid||!e.isValid)return fr.invalid("created by diffing an invalid DateTime");let o={locale:this.locale,numberingSystem:this.numberingSystem,...n},a=FV(r).map(fr.normalizeUnit),i=e.valueOf()>this.valueOf(),l=i?this:e,s=i?e:this,u=uj(l,s,a,o);return i?u.negate():u}diffNow(e="milliseconds",r={}){return this.diff(t.now(),e,r)}until(e){return this.isValid?is.fromDateTimes(this,e):this}hasSame(e,r,n){if(!this.isValid)return!1;let o=e.valueOf(),a=this.setZone(e.zone,{keepLocalTime:!0});return a.startOf(r,n)<=o&&o<=a.endOf(r,n)}equals(e){return this.isValid&&e.isValid&&this.valueOf()===e.valueOf()&&this.zone.equals(e.zone)&&this.loc.equals(e.loc)}toRelative(e={}){if(!this.isValid)return null;let r=e.base||t.fromObject({},{zone:this.zone}),n=e.padding?this<r?-e.padding:e.padding:0,o=["years","months","days","hours","minutes","seconds"],a=e.unit;return Array.isArray(e.unit)&&(o=e.unit,a=void 0),wj(r,this.plus(n),{...e,numeric:"always",units:o,unit:a})}toRelativeCalendar(e={}){return this.isValid?wj(e.base||t.fromObject({},{zone:this.zone}),this,{...e,numeric:"auto",units:["years","months","days"],calendary:!0}):null}static min(...e){if(!e.every(t.isDateTime))throw new Nr("min requires all arguments be DateTimes");return HS(e,r=>r.valueOf(),Math.min)}static max(...e){if(!e.every(t.isDateTime))throw new Nr("max requires all arguments be DateTimes");return HS(e,r=>r.valueOf(),Math.max)}static fromFormatExplain(e,r,n={}){let{locale:o=null,numberingSystem:a=null}=n,i=At.fromOpts({locale:o,numberingSystem:a,defaultToEN:!0});return eE(i,e,r)}static fromStringExplain(e,r,n={}){return t.fromFormatExplain(e,r,n)}static get DATE_SHORT(){return gl}static get DATE_MED(){return nh}static get DATE_MED_WITH_WEEKDAY(){return wS}static get DATE_FULL(){return oh}static get DATE_HUGE(){return ah}static get TIME_SIMPLE(){return ih}static get TIME_WITH_SECONDS(){return sh}static get TIME_WITH_SHORT_OFFSET(){return lh}static get TIME_WITH_LONG_OFFSET(){return uh}static get TIME_24_SIMPLE(){return ch}static get TIME_24_WITH_SECONDS(){return dh}static get TIME_24_WITH_SHORT_OFFSET(){return fh}static get TIME_24_WITH_LONG_OFFSET(){return ph}static get DATETIME_SHORT(){return mh}static get DATETIME_SHORT_WITH_SECONDS(){return gh}static get DATETIME_MED(){return hh}static get DATETIME_MED_WITH_SECONDS(){return vh}static get DATETIME_MED_WITH_WEEKDAY(){return SS}static get DATETIME_FULL(){return bh}static get DATETIME_FULL_WITH_SECONDS(){return yh}static get DATETIME_HUGE(){return xh}static get DATETIME_HUGE_WITH_SECONDS(){return Ch}};function _f(t){if(dt.isDateTime(t))return t;if(t&&t.valueOf&&si(t.valueOf()))return dt.fromJSDate(t);if(t&&typeof t=="object")return dt.fromObject(t);throw new Nr(`Unknown datetime argument: ${t}, of type ${typeof t}`)}function D2(t){return t.reduce((e,{field:r,operator:n,value:o})=>{if(!r||!n)return e;if(r==="updated_at"&&(r="modified"),r==="created_at"&&(r="created"),n==="def")return{...e,[`${r}[def]`]:"true"};if(n==="ndef")return{...e,[`${r}[def]`]:"false"};if(n==="checked")return{...e,[`${r}[eq]`]:"true"};if(n==="nchecked")return{...e,[`${r}[eq]`]:"false"};if(typeof o>"u"||o===null||o===""||Array.isArray(o)&&o.length<1)return e;if(n==="between"||n==="sys-date-between")if(Array.isArray(o)&&o.length===2){if(n==="between")return{...e,[`${r}[gte]`]:o[0],[`${r}[lte]`]:o[1]};{let a=dt.fromISO(o[0],{zone:"system"}).setZone("utc").toISO(),i=dt.fromISO(o[1],{zone:"system"}).plus({day:1}).setZone("utc").toISO();return a&&i?{...e,[`${r}[gte]`]:a,[`${r}[lt]`]:i}:e}}else return e;if(n==="sys-date-eq")if(typeof o=="string"){let a=dt.fromISO(o,{zone:"system"}).setZone("utc").toISO(),i=dt.fromISO(o,{zone:"system"}).plus({day:1}).setZone("utc").toISO();return a&&i?{...e,[`${r}[gte]`]:a,[`${r}[lt]`]:i}:e}else return e;if(n==="sys-date-gt")if(typeof o=="string"){let a=dt.fromISO(o,{zone:"system"}).plus({day:1}).setZone("utc").toISO();return a?{...e,[`${r}[gte]`]:a}:e}else return e;if(n==="sys-date-gte")if(typeof o=="string"){let a=dt.fromISO(o,{zone:"system"}).setZone("utc").toISO();return a?{...e,[`${r}[gte]`]:a}:e}else return e;if(n==="sys-date-lt")if(typeof o=="string"){let a=dt.fromISO(o,{zone:"system"}).setZone("utc").toISO();return a?{...e,[`${r}[lt]`]:a}:e}else return e;if(n==="sys-date-lte")if(typeof o=="string"){let a=dt.fromISO(o,{zone:"system"}).plus({day:1}).setZone("utc").toISO();return a?{...e,[`${r}[lt]`]:a}:e}else return e;if(n==="starts"&&typeof o=="string")return{...e,[`${r}[starts]`]:o.replaceAll(/[^a-zA-Z0-9_.\s-]/g,"").toLowerCase()};if(r==="workflowStageId"){let a=t.some(i=>i.field==="workflowId");if(n==="eq"||n==="neq"){let i=[];return Array.isArray(o)?i=o.map(s=>s.split("_")[1]):i=o.split("_"),{...e,...a?{}:{"workflowId[eq]":i[0]},[`${r}[${n}]`]:i[1]}}if(Array.isArray(o)){let i=o.map(u=>{let c=u.split("_")[0],d=u.split("_")[1];return{workflowId:c,workflowStage:d}}),l=i.map(u=>u.workflowId).join(","),s=i.map(u=>u.workflowStage).join(",");return{...e,...a?{}:{[`workflowId[${n}]`]:l},[`${r}[${n}]`]:s}}}return{...e,[`${r}[${n}]`]:Array.isArray(o)?o.join(","):o}},{})}import{CANVAS_DRAFT_STATE as Ij,CanvasClient as Dj}from"@uniformdev/canvas";async function A2({instanceType:t,searchExpressionPrompt:e,username:r,locale:n,getEditUrl:o,env:a}){let i=new Dj(a),l=await u2({searchExpressionPrompt:e,username:r,locale:n},t,a),{limit:s,offset:u,keyword:c,sort:d,filter:f}=l,m=(await i.getCompositionList({patternType:t==="composition"?void 0:t==="componentPattern"?"component":"composition",pattern:t!=="composition",resolveData:!1,withComponentIDs:!0,skipOverridesResolution:!0,limit:s,offset:u,search:c,filters:f?D2(f):void 0,orderBy:Array.isArray(d)?d:d?[d]:void 0,locale:n,skipPatternResolution:!0,state:Ij})).compositions.map(h=>({id:h.composition._id,name:h.composition._name,componentType:h.composition.type,editUrl:o(h.composition._id)}));return{content:[{type:"text",text:JSON.stringify({results:m,criteria:l},null,2)}]}}async function L2({id:t,env:e}){let n=await new Dj(e).getCompositionById({skipDataResolution:!0,withComponentIDs:!0,skipOverridesResolution:!0,skipPatternResolution:!1,compositionId:t,state:Ij});return{content:[{type:"text",text:JSON.stringify(n,null,2)}]}}var x1e={id:Aj.string()};function Lj(t,e){t.tool("compositionList","Lists available Uniform compositions",ns.shape,async r=>await A2({...r,instanceType:"composition",getEditUrl:n=>l2(n,e),env:e})),t.tool("compositionGet","Gets the full contents of a Uniform composition",x1e,async r=>await L2({...r,env:e}))}import{autoFixParameterGroups as Nj,ContentClient as C1e}from"@uniformdev/canvas";import*as M2 from"zod/v3";import*as wl from"zod/v3";var _j=wl.object({name:wl.string().describe('Title-cased display name of the component. Ex: "Hero"'),id:wl.string().describe("Public ID of the content type, the camelCase version of name, using only alphanumeric characters"),description:wl.string().describe("Describe the purpose of the content type in 1-2 sentences."),fields:wl.array(Rh).describe("The fields of the content type. The key is the publicId of the field.").optional()});function Mj(t){let e=t.fields?.find(n=>n.type==="asset"&&typeof n.typeConfig=="object"&&n.typeConfig!==null&&"allowedTypes"in n.typeConfig&&Array.isArray(n.typeConfig.allowedTypes)&&n.typeConfig.allowedTypes?.includes("image"))?.id,r=t.fields?.find(n=>n.type==="text")?.id;return{...t,thumbnailField:e,entryName:r}}function _2(t,e){return`${e.baseWebUrl}/dashboards/canvas/content-types/${t}`}var w1e={action:M2.enum(["create","update","delete"]).describe("The action to perform"),publicId:M2.string().describe("Public ID of the component, the camelCase version of name, using only alphanumeric characters"),contentType:_j.describe("Full content type definition to create. Omit for update or delete.").optional(),patches:Ph.describe("JSON patch to apply to the existing component definition. Omit for create or delete.").optional()};function kj(t,e){t.tool("contentTypeAction","Creates, updates, or deletes a Uniform Content Type definition",w1e,async({publicId:r,action:n,contentType:o,patches:a})=>{let i=new C1e(e),l=!1;if(n==="create"){if(!o)throw new Error("Content type definition is required for create");let s=Mj(o);s.fields&&(l=Nj(s.fields),fc(s.fields)),await i.upsertContentType({contentType:s})}if(n==="update"){if(!a)throw new Error("Patches are required for update");let u=(await i.getContentTypes()).contentTypes.find(f=>f.id===r);if(!u)throw new Error(`Content Type with public ID ${r} does not exist, try creating it instead`);let c=u.fields?.filter(f=>f.type==="richText").map(f=>f.id),d=kh(u,a);if(d.fields){l=Nj(d.fields);let f=d.fields?.filter(p=>p.type==="richText").map(p=>p.id).filter(p=>!c?.includes(p));fc(d.fields,f)}await i.upsertContentType({contentType:d})}return n==="delete"&&await i.deleteContentType({contentTypeId:r}),{content:[{type:"text",text:JSON.stringify({success:!0,editUrl:_2(r,e),warning:l?"Issues with field group order were fixed. Ensure definition data is re-fetched before any future updates.":void 0},null,2)}]}})}import{ContentClient as Pj}from"@uniformdev/canvas";import*as Oj from"zod/v3";var S1e={id:Oj.string()};function Rj(t,e){t.tool("contentTypeList","Lists all Uniform Content Type definitions",async()=>{let o=(await new Pj(e).getContentTypes()).contentTypes.map(a=>({id:a.id,name:a.name,description:a.description,editUrl:_2(a.id,e)}));return{content:[{type:"text",text:JSON.stringify(o,null,2)}]}}),t.tool("contentTypeGet","Gets a Uniform Content Type definition details (fields, etc.)",S1e,async({id:r})=>{let a=(await new Pj(e).getContentTypes()).contentTypes.find(i=>i.id===r);if(!a)throw new Error(`Content Type with ID ${r} not found`);return{content:[{type:"text",text:JSON.stringify(a,null,2)}]}})}import{v4 as E1e}from"uuid";function Fj(t,e){t.tool("createUuid","Creates a new random UUID",async()=>({content:[{type:"text",text:E1e()}]}))}import*as Mh from"zod/v3";import{CANVAS_DRAFT_STATE as N2,ContentClient as $1e,convertEntryToPutEntry as T1e,getEffectivePropertyValue as I1e}from"@uniformdev/canvas";async function D1e(t,e,r){let o=(await e.fetchDefinitions())[t.entry.type];if(!o)throw new Error("insanity");let a=ZB(o),i;a.entryName&&(i=t.entry._overrides?.[t.entry._id].parameters?.[a.entryName]??t.entry.fields?.[a.entryName]);let l=I1e({conditionIndex:-1,locale:"__any__",greedyLocaleMatching:!0,property:i}),s=TB({value:l,isNew:r,contentType:a});t.entry._name=s}async function k2({action:t,id:e,instructions:r,isPattern:n,patternId:o,getEditUrl:a,env:i}){let l=new $1e(i),s,u,c=t==="update"?e:void 0,d={success:!0,actionsTaken:[]};if(t==="duplicate"){let p=(await l.getEntries({entryIDs:[e],pattern:n,state:N2,skipDataResolution:!0,skipPatternResolution:!1,withComponentIDs:!0,skipOverridesResolution:!0})).entries[0];if(!p)throw new Error("Entry not found");let m=crypto.randomUUID(),h={...p.entry,_id:m,_name:`${p.entry._name} (copy)`};h._slug&&(h._slug=`${h._slug}-copy${h._slug?.endsWith("/")?"/":""}`),delete h._thumbnail;let g=eh({...p,entry:h});s=new ii(g.composition),e=m}else if(t==="create"){if(!r)throw new Error("Instructions are required for create");if(!r.type)throw new Error("Type is required for create");o?(await l.upsertEntry({state:N2,entry:{type:r.type,_id:e,fields:{},_pattern:o}}),c=e):s=new ii({_id:e,_name:"New Entry",type:r.type,_overridability:{hideLockedParameters:!0}})}if(c){if(u=(await l.getEntries({entryIDs:[e],pattern:n,state:N2,skipDataResolution:!0,skipPatternResolution:!1,withComponentIDs:!0,skipOverridesResolution:!0})).entries[0],!u)throw new Error("Entry not found");let p=eh(u);s=new ii(p.composition)}t==="delete"&&await l.deleteEntry({entryId:e});let f=hV(i);if(s){t!=="duplicate"&&(await a2(r?.localeUpdates?.enableLocales,i),d=await Xy({twee:s,descriptionUpdate:void 0,slugUpdate:r&&"slug"in r?r.slug:void 0,nameUpdate:r&&"name"in r?r.name:void 0,propertyUpdates:r?.fieldUpdates??[],dataResourceUpdates:(r&&"dataResourceUpdates"in r?r.dataResourceUpdates:[])??[],slotUpdates:{},localeUpdates:r?.localeUpdates,currentEditorLocale:void 0,referenceData:f,isEditingPattern:n,domParser:o2}));let p=s.exportTree(),m=s.exportMetadata(),h=T1e(YB(p,u??{projectId:i.projectId,pattern:n},m,N2,u?.releaseId,u?.editionId));n||await D1e(h,f,t==="create"),await l.upsertEntry(h)}return{content:[{type:"text",text:JSON.stringify({...d,editUrl:a(e)},null,2)}]}}function P2(t,e){return`${e.baseWebUrl}/dashboards/canvas/entries/${t}`}var A1e={action:Mh.enum(["create","update","delete","duplicate"]).describe("The action to perform"),id:Mh.string().uuid().describe("UUID of the entry to create, update, delete, or duplicate"),patternId:Mh.string().uuid().describe("Entry pattern ID to create the entry from. Omit when not creating, or when creating an entry without an entry pattern.").optional(),instructions:xE.describe("Modification instructions for the entry. Omit for delete and duplicate.").optional()};function Bj(t,e){t.tool("entryAction","Creates, updates, or deletes a Uniform Entry",A1e,async r=>await k2({...r,isPattern:!1,getEditUrl:n=>P2(n,e),patternId:r.patternId,env:e}))}import*as zj from"zod/v3";import{CANVAS_DRAFT_STATE as Vj,ContentClient as jj}from"@uniformdev/canvas";async function O2({isPattern:t,searchExpressionPrompt:e,username:r,locale:n,getEditUrl:o,env:a}){let i=new jj(a),l=await u2({searchExpressionPrompt:e,username:r,locale:n},t?"entryPattern":"entry",a),{limit:s,offset:u,keyword:c,sort:d,filter:f}=l,m=(await i.getEntries({limit:s,offset:u,pattern:t,skipDataResolution:!0,withTotalCount:!0,skipPatternResolution:!0,skipOverridesResolution:!0,state:Vj,search:c,filters:f?D2(f):void 0,orderBy:Array.isArray(d)?d:d?[d]:void 0,locale:n})).entries.map(h=>({id:h.entry._id,name:h.entry._name??"",contentType:h.entry.type,editUrl:o(h.entry._id)}));return{content:[{type:"text",text:JSON.stringify({results:m,criteria:l},null,2)}]}}async function R2({id:t,isPattern:e,env:r}){let o=await new jj(r).getEntries({skipDataResolution:!0,withComponentIDs:!0,skipOverridesResolution:!0,skipPatternResolution:!1,pattern:e,entryIDs:[t],state:Vj});if(o.entries.length===0)throw new Error(`Entry with ID ${t} not found`);return{content:[{type:"text",text:JSON.stringify(o.entries[0],null,2)}]}}var L1e={id:zj.string()};function Hj(t,e){t.tool("entryList","Lists available Uniform entries",ns.shape,async r=>await O2({...r,isPattern:!1,getEditUrl:n=>P2(n,e),env:e})),t.tool("entryGet","Gets the full contents of a Uniform entry",L1e,async r=>await R2({...r,isPattern:!1,env:e}))}import*as B2 from"zod/v3";function F2(t,e){return`${e.baseWebUrl}/dashboards/canvas/entry-patterns/${t}`}var _1e={action:B2.enum(["create","update","delete","duplicate"]).describe("The action to perform"),id:B2.string().uuid().describe("UUID of the entry pattern to create, update, delete, or duplicate"),instructions:CE.describe("Modification instructions for the entry pattern. Omit for delete and duplicate.").optional()};function Wj(t,e){t.tool("entryPatternAction","Creates, updates, or deletes a Uniform Entry Pattern",_1e,async r=>await k2({...r,isPattern:!0,getEditUrl:n=>F2(n,e),patternId:void 0,env:e}))}import*as Gj from"zod/v3";var M1e={id:Gj.string()};function Uj(t,e){t.tool("entryPatternList","Lists available Uniform entry patterns",ns.shape,async r=>await O2({...r,isPattern:!0,getEditUrl:n=>F2(n,e),env:e})),t.tool("entryPatternGet","Gets the full contents of a Uniform entry pattern",M1e,async r=>await R2({...r,isPattern:!0,env:e}))}import{ProjectClient as N1e}from"@uniformdev/canvas";async function k1e(t){let e=await fetch(`${t.apiHost}/api/v1/member-profile`,{headers:{"x-api-key":t.apiKey,"Content-Type":"application/json"}});if(!e.ok)throw new Error(`Failed to fetch user profile: ${e.status} ${e.statusText}`);return(await e.json()).name}function Zj(t,e){t.tool("getUniformEnvironment","Get the connected Uniform Project name, edit URL, and current user",{},async()=>{try{let r=new N1e(e),[n,o]=await Promise.all([r.get({projectId:e.projectId}),k1e(e)]),a={projectName:n.name,teamName:n.teamName,projectUrl:e.baseWebUrl,currentIdentity:o};return{content:[{type:"text",text:JSON.stringify(a,null,2)}]}}catch(r){return{content:[{type:"text",text:JSON.stringify({error:"Failed to fetch project information",details:r instanceof Error?r.message:"Unknown error"},null,2)}]}}})}import{LocaleClient as P1e}from"@uniformdev/canvas";function Yj(t,e){t.tool("localeList","Lists all registered Uniform locales",async()=>{let n=await new P1e(e).get();return{content:[{type:"text",text:JSON.stringify({locales:n.results,editUrl:`${e.baseWebUrl}/settings/localization`},null,2)}]}})}import*as j2 from"zod/v3";function V2(t,e){return`${e.baseWebUrl}/dashboards/canvas/edit/${t}`}var O1e={action:j2.enum(["create","update","delete","duplicate"]).describe("The action to perform"),id:j2.string().uuid().describe("UUID of the pattern instance to create, update, delete, or duplicate"),instructions:bE.describe("Modification instructions for the pattern. Omit for delete and duplicate.").optional()};function Kj(t,e){t.tool("patternAction","Creates, updates, or deletes a Uniform Component Pattern or Composition Pattern",O1e,async r=>await s2({...r,isPattern:!0,getEditUrl:n=>V2(n,e),patternId:void 0,env:e}))}import*as z2 from"zod/v3";var R1e={instanceType:z2.enum(["componentPattern","compositionPattern"]),...ns.shape},F1e={id:z2.string()};function Xj(t,e){t.tool("patternList","Lists available Uniform component patterns or composition patterns",R1e,async r=>await A2({...r,getEditUrl:n=>V2(n,e),env:e})),t.tool("patternGet","Gets the full contents of a Uniform component pattern or composition pattern",F1e,async r=>await L2({...r,env:e}))}import{ProjectMapClient as B1e}from"@uniformdev/project-map";import*as Jj from"zod/v3";var V1e={query:Jj.string().describe("Keyword to search for in node names and paths.")};function qj(t,e){t.tool("projectMapNodeSearch","Search for project map nodes by keyword. Use this to find the appropriate parent node when you need to create a composition attached to a specific location in the project map hierarchy.",V1e,async({query:r})=>{let n=new B1e({apiKey:e.apiKey,apiHost:e.apiHost,projectId:e.projectId}),a=(await n.getProjectMapDefinition({}))?.projectMaps[0]?.id;if(!a)throw new Error("No project map found for this project");let l=(await n.getNodes({search:r,includeAncestors:!1,expanded:!0,depth:1,projectMapId:a})).nodes?.map(s=>({id:s.id,name:s.name,path:s.path}))??[];return{content:[{type:"text",text:JSON.stringify({matches:l},null,2)}]}})}function snt(t,e){lE(t,e),mE(t,e),vE(t,e),kj(t,e),Rj(t,e),Bj(t,e),Hj(t,e),Uj(t,e),Wj(t,e),Xj(t,e),Kj(t,e),vV(t,e),Lj(t,e),Fj(t,e),Zj(t,e),Yj(t,e),qj(t,e)}export{snt as configureServer};
5785
5785
  /*! Bundled license information:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uniformdev/uniform-mcp",
3
- "version": "20.55.0",
3
+ "version": "20.55.1",
4
4
  "description": "Uniform MCP Server",
5
5
  "license": "SEE LICENSE IN LICENSE.txt",
6
6
  "bin": {
@@ -30,8 +30,8 @@
30
30
  "dependencies": {
31
31
  "@modelcontextprotocol/sdk": "1.25.2",
32
32
  "@types/uuid": "9.0.4",
33
- "@uniformdev/canvas": "20.55.0",
34
- "@uniformdev/project-map": "20.55.0",
33
+ "@uniformdev/canvas": "20.55.1",
34
+ "@uniformdev/project-map": "20.55.1",
35
35
  "fast-json-patch": "3.1.1",
36
36
  "immer": "10.1.3",
37
37
  "linkedom": "0.18.12",
@@ -45,10 +45,10 @@
45
45
  "access": "public"
46
46
  },
47
47
  "devDependencies": {
48
- "@uniformdev/design-system": "20.55.0",
49
- "@uniformdev/files": "20.55.0",
50
- "@uniformdev/mesh-edgehancer-sdk": "20.55.0",
51
- "@uniformdev/richtext": "20.55.0"
48
+ "@uniformdev/design-system": "20.55.1",
49
+ "@uniformdev/files": "20.55.1",
50
+ "@uniformdev/mesh-edgehancer-sdk": "20.55.1",
51
+ "@uniformdev/richtext": "20.55.1"
52
52
  },
53
- "gitHead": "ef21541bd262e454318a30372f90d22a06183b82"
53
+ "gitHead": "44d778abd699dafbabda982cb3295be043ba3cb0"
54
54
  }