datocms-plugin-ai-translations 3.5.4 → 3.5.5
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.
|
@@ -74,8 +74,8 @@ ${JSON.stringify(this.errors,null,2)}`),this.message=n,this.preCallStack&&(this.
|
|
|
74
74
|
Caused By:
|
|
75
75
|
${this.preCallStack}`)}get errors(){return NG(this.response.body)?this.response.body.data:[]}findError(e,n){const i=Array.isArray(e)?e:[e];return this.errors.find(r=>i.includes(r.attributes.code)&&(!n||(typeof n=="function"?n(r.attributes.details):Object.entries(n).every(([l,u])=>r.attributes.details[l]===u))))}}class Nl extends Error{constructor(){super("Promise canceled!"),Object.setPrototypeOf(this,new.target.prototype)}}function Il(t,e){let n=null;const i=new Promise((r,l)=>{n=()=>{try{e&&e(),l(new Nl)}catch(d){l(d)}},(typeof t=="function"?t():t).then(r,l)});return n&&(i.cancel=n),i}function od(t){return new Promise(e=>{setTimeout(e,t)})}var PG=function(t,e,n,i){function r(l){return l instanceof n?l:new n(function(u){u(l)})}return new(n||(n=Promise))(function(l,u){function d(g){try{h(i.next(g))}catch(p){u(p)}}function f(g){try{h(i.throw(g))}catch(p){u(p)}}function h(g){g.done?l(g.value):r(g.value).then(d,f)}h((i=i.apply(t,e||[])).next())})};function jG(t){return PG(this,void 0,void 0,function*(){let e,n=0;do try{n+=1,yield od(n*1e3),e=yield t()}catch(i){if(!(i instanceof Es)||i.response.status!==404)throw i}while(!e);return e})}var al={},Li={},xm={},jw;function PA(){return jw||(jw=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.TaskCollisionStrategy=void 0,(function(e){e[e.DEFAULT=0]="DEFAULT",e[e.KEEP_THIS=1]="KEEP_THIS",e[e.KEEP_OTHER=2]="KEEP_OTHER",e[e.KEEP_BOTH=3]="KEEP_BOTH",e[e.RESOLVE_THIS=4]="RESOLVE_THIS",e[e.RESOLVE_OTHER=5]="RESOLVE_OTHER"})(t.TaskCollisionStrategy||(t.TaskCollisionStrategy={}))})(xm)),xm}var Pc={},zw;function jA(){if(zw)return Pc;zw=1,Object.defineProperty(Pc,"__esModule",{value:!0});let t=class{constructor(n,i){this._code=n,this._message=i}get code(){return this._code}get message(){return this._message}};return Pc.default=t,Pc}var fs={},Fw;function zA(){if(Fw)return fs;Fw=1,Object.defineProperty(fs,"__esModule",{value:!0}),fs.mutexEquality=fs.mutexBitwiseAnd=void 0;function t(n,i){return(n&i)!==0}fs.mutexBitwiseAnd=t;function e(n,i){return n===i}return fs.mutexEquality=e,fs}var jc={},Uw;function zG(){if(Uw)return jc;Uw=1,Object.defineProperty(jc,"__esModule",{value:!0});let t=class{constructor(n,i){this._meta=void 0,this._task=n,this._scheduler=i}withDescriptor(n){return this._descriptor=n,this}withMutex(n){return this._mutex=n,this}withMeta(n){return this._meta=n,this}runBeforeExecuting(n){return this._onPreExecute=n,this}handleCollisions(n){return this._onTaskCollision=n,this}execute(n){return this._scheduler.enqueue({priority:n,mutex:this._mutex,descriptor:this._descriptor,meta:this._meta,execute:this._task,onPreExecute:this._onPreExecute,onTaskCollision:this._onTaskCollision})}};return jc.default=t,jc}var Vw;function FG(){if(Vw)return Li;Vw=1;var t=Li&&Li.__awaiter||function(h,g,p,v){function b(S){return S instanceof p?S:new p(function(w){w(S)})}return new(p||(p=Promise))(function(S,w){function T(O){try{C(v.next(O))}catch(L){w(L)}}function E(O){try{C(v.throw(O))}catch(L){w(L)}}function C(O){O.done?S(O.value):b(O.value).then(T,E)}C((v=v.apply(h,g||[])).next())})},e=Li&&Li.__importDefault||function(h){return h&&h.__esModule?h:{default:h}};Object.defineProperty(Li,"__esModule",{value:!0});const n=PA(),i=e(jA()),r=zA(),l=e(zG());var u;(function(h){h[h.PENDING=0]="PENDING",h[h.EXECUTING=1]="EXECUTING",h[h.TERMINATED=2]="TERMINATED"})(u||(u={}));function d(h,g){for(let p of h.listeners)p.reject(g)}let f=class{constructor(g,p={}){this._queue=[],this._isExecuting=!1,this._idleListeners=[],this._maxConcurrentTasks=g,this._samePriorityMutex=!!p.samePriorityMutex,this._mutexStrategy=p.mutexStrategy||r.mutexEquality,p.disableLogging?this._errorLog=()=>{}:this._errorLog=console.error}enqueue(g){return new Promise((p,v)=>{typeof g=="function"&&(g={priority:0,execute:g});const b=this._checkMutexes(g,p,v);b.task?this._addTask(b.task):b.canceled&&v(this.createCanceledError())})}prepare(g){return new l.default(g,this)}_addTask(g){this._queue.push(g),this._applyPriorities(),this._isExecuting||(this._isExecuting=!0,setTimeout(this._executeNextTasks.bind(this)))}get executingTasks(){return this._queue.reduce((g,p)=>p.state===u.EXECUTING?g+1:g,0)}createCanceledError(){return new i.default(50,"Task has been canceled in favor of another task")}_findFirstPendingTask(){return this._queue.find(g=>g.state===u.PENDING)}_isIdle(){return this._queue.length===0||!this._queue.find(g=>g.state!==u.TERMINATED)}_removeTaskAt(g){this._queue.splice(g,1)}_executeTask(g){return t(this,void 0,void 0,function*(){try{return g.task.onPreExecute&&g.task.onPreExecute(),yield g.task.execute()}catch(p){throw p}finally{g.state=u.TERMINATED;let p=this._queue.indexOf(g);this._removeTaskAt(p),this._executeNextTasks()}})}_executeNextTasks(){let g=this.executingTasks;if(g>=this._maxConcurrentTasks)return;let p=this._maxConcurrentTasks-g;for(let v=0;v<p;v++){const b=this._findFirstPendingTask();if(!b){this._isIdle()&&this._switchToIdle();return}b.state=u.EXECUTING,this._executeTask(b).then(S=>{for(const{resolve:w}of b.listeners)try{w(S)}catch(T){this._errorLog("An error occurred while resolving listener",T)}}).catch(S=>{for(const{reject:w}of b.listeners)try{w(S)}catch(T){this._errorLog("An error occurred while rejecting listener",T)}})}}_switchToIdle(){this._isExecuting=!1;const g=this._idleListeners;this._idleListeners=[];for(const{resolve:p}of g)try{p()}catch{}}waitForIdle(){return this._isExecuting?new Promise((g,p)=>{this._idleListeners.push({resolve:g,reject:p})}):Promise.resolve()}_applyPriorities(){this._queue.sort((g,p)=>p.task.priority-g.task.priority)}_checkMutexes(g,p,v){for(let b=0;b<this._queue.length;b++){let S=this._queue[b];if(S.state===u.TERMINATED||this._samePriorityMutex&&S.task.priority!=g.priority||!S.task.mutex||!g.mutex||!this._mutexStrategy(S.task.mutex,g.mutex))continue;let w,T;if(S.task.onTaskCollision)if(w=S.task.onTaskCollision(g),w===n.TaskCollisionStrategy.KEEP_OTHER&&S.state!==u.EXECUTING){this._removeTaskAt(b--),d(S,this.createCanceledError());continue}else{if(w===n.TaskCollisionStrategy.KEEP_THIS)return{canceled:!0};if(w===n.TaskCollisionStrategy.RESOLVE_OTHER)return this._removeTaskAt(b--),{canceled:!1,task:{task:g,state:u.PENDING,listeners:[{resolve:p,reject:v},...S.listeners]}};if(w===n.TaskCollisionStrategy.RESOLVE_THIS)return S.listeners=[...S.listeners,{resolve:p,reject:v}],{canceled:!1}}if(g.onTaskCollision){if(T=g.onTaskCollision(S.task),T===n.TaskCollisionStrategy.KEEP_OTHER)return{canceled:!0};if(T===n.TaskCollisionStrategy.KEEP_THIS){this._removeTaskAt(b--),d(S,this.createCanceledError());continue}else{if(T===n.TaskCollisionStrategy.RESOLVE_OTHER)return S.listeners=[...S.listeners,{resolve:p,reject:v}],{canceled:!1};if(T===n.TaskCollisionStrategy.RESOLVE_THIS)return this._removeTaskAt(b--),{canceled:!1,task:{task:g,state:u.PENDING,listeners:[{resolve:p,reject:v},...S.listeners]}}}}if(!(w===n.TaskCollisionStrategy.KEEP_BOTH&&T===n.TaskCollisionStrategy.KEEP_BOTH))return{canceled:!0}}return{canceled:!1,task:{task:g,state:u.PENDING,listeners:[{resolve:p,reject:v}]}}}};return Li.default=f,Li}var $w;function UG(){return $w||($w=1,(function(t){var e=al&&al.__importDefault||function(u){return u&&u.__esModule?u:{default:u}};Object.defineProperty(t,"__esModule",{value:!0}),t.mutexEquality=t.mutexBitwiseAnd=t.SchedulerError=t.TaskCollisionStrategy=t.Scheduler=void 0;const n=e(FG());t.Scheduler=n.default;const i=PA();Object.defineProperty(t,"TaskCollisionStrategy",{enumerable:!0,get:function(){return i.TaskCollisionStrategy}});const r=e(jA());t.SchedulerError=r.default;const l=zA();Object.defineProperty(t,"mutexBitwiseAnd",{enumerable:!0,get:function(){return l.mutexBitwiseAnd}}),Object.defineProperty(t,"mutexEquality",{enumerable:!0,get:function(){return l.mutexEquality}})})(al)),al}var VG=UG(),_s=function(t){return this instanceof _s?(this.v=t,this):new _s(t)},$G=function(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=n.apply(t,e||[]),r,l=[];return r={},u("next"),u("throw"),u("return"),r[Symbol.asyncIterator]=function(){return this},r;function u(v){i[v]&&(r[v]=function(b){return new Promise(function(S,w){l.push([v,b,S,w])>1||d(v,b)})})}function d(v,b){try{f(i[v](b))}catch(S){p(l[0][3],S)}}function f(v){v.value instanceof _s?Promise.resolve(v.value.v).then(h,g):p(l[0][2],v)}function h(v){d("next",v)}function g(v){d("throw",v)}function p(v,b){v(b),l.shift(),l.length&&d(l[0][0],l[0][1])}};function ni(t,e,n,i){return $G(this,arguments,function*(){const l=n?.perPage||t.defaultLimit;if(l>t.maxLimit)throw new Error(`perPage option cannot exceed maximum value of ${t.maxLimit}`);const u=n?.concurrency||1;if(u>10)throw new Error("concurrency option cannot exceed maximum value of 10");const d=yield _s(e({limit:l,offset:0}));for(const p of d.data)yield yield _s(p);const f=d.meta.total_count,h=new VG.Scheduler(u),g=[];for(let p=l;p<f;p+=l)g.push(h.enqueue(()=>e({limit:l,offset:p})));for(;g.length>0;){const p=yield _s(g.shift());for(const v of p.data)yield yield _s(i?_l(v):v)}})}function ai(t){t&&"page"in t&&console.warn("Passing a `page` query param on paged iterators has no effect: use the `perPage` option instead.")}const FA="__ARRAY_INDEX__";function qG(t){return t.reduce((e,n,i)=>i===0?n:n===FA?`${e}[]`:`${e}[${n}]`,"")}function GG(t){if(typeof t=="number"||typeof t=="string")return t.toString();if(t===!0)return"true";if(t===!1)return"false";throw`Don't know how to serialize param value ${JSON.stringify(t)}`}function Bp(t,e=[]){const n=[];if(typeof t=="number"||typeof t=="string"||typeof t=="boolean")n.push([qG(e),GG(t)]);else if(typeof t=="object"){if(Array.isArray(t))for(const i of t)for(const r of Bp(i,[...e,FA]))n.push(r);else if(t)for(const[i,r]of Object.entries(t))for(const l of Bp(r,[...e,i]))n.push(l)}return n}var KG=function(t,e,n,i){function r(l){return l instanceof n?l:new n(function(u){u(l)})}return new(n||(n=Promise))(function(l,u){function d(g){try{h(i.next(g))}catch(p){u(p)}}function f(g){try{h(i.throw(g))}catch(p){u(p)}}function h(g){g.done?l(g.value):r(g.value).then(d,f)}h((i=i.apply(t,e||[])).next())})};const HG=typeof window<"u"&&typeof window.document<"u",YG=5;var jn;(function(t){t[t.NONE=0]="NONE",t[t.BASIC=1]="BASIC",t[t.BODY=2]="BODY",t[t.BODY_AND_HEADERS=3]="BODY_AND_HEADERS"})(jn||(jn={}));function XG(t){const e={};return t.forEach((n,i)=>{e[i]=n}),e}function qw(t,e,n,i,r,l,u){return{request:{url:e,method:t,headers:n,body:i},response:{status:r.status,statusText:r.statusText,headers:XG(r.headers),body:l},preCallStack:u}}function WG(t,e,n,i,r){return{request:{url:e,method:t,headers:n,body:i},preCallStack:r}}function ZG(t,e,n,i,r,l,u){return{request:{url:e,method:t,headers:n,body:i},response:{status:r,statusText:"N/A",headers:{},body:l},preCallStack:u}}function JG(t){return typeof t=="object"&&!!t&&"code"in t}function QG(t){return Object.fromEntries(Object.entries(t).map(([e,n])=>[e.toLowerCase(),n]))}let Gw=1;function e7(t){const e=t||(typeof fetch>"u"?void 0:fetch)||(typeof globalThis>"u"?void 0:globalThis.fetch);if(typeof e>"u")throw new Error("fetch() is not available: either polyfill it globally, or provide it as fetchFn option.");return e}function ld(t){var e;return KG(this,void 0,void 0,function*(){const n=Gw;Gw+=1;const i=e7(t.fetchFn),r=t.preCallStack,l=t.userAgent||"@datocms/rest-client-utils",u=t.retryCount||1,d=t.logLevel||jn.NONE,f="autoRetry"in t?t.autoRetry:!0,h=t.logFn||(()=>!0),g=Object.assign({"content-type":"application/json",accept:"application/json",authorization:`Bearer ${t.apiToken}`,"user-agent":l},t.extraHeaders?QG(t.extraHeaders):{});HG&&delete g["user-agent"];const p=t.baseUrl.replace(/\/$/,""),v=t.body?JSON.stringify(t.body,null,2):void 0,b=t.queryParams&&Object.keys(t.queryParams).length>0?`?${new URLSearchParams(Bp(t.queryParams)).toString()}`:"",S=`${p}${t.url}${b}`;if(d>=jn.BASIC){if(h(`[${n}] ${t.method} ${S}`),d>=jn.BODY_AND_HEADERS)for(const[w,T]of Object.entries(g||{}))h(`[${n}] ${w}: ${T}`);d>=jn.BODY&&v&&h(`[${n}] ${v}`)}try{const w=Il(i(S,{method:t.method,headers:g,body:v})),T=setTimeout(()=>{w.cancel()},t.requestTimeout||3e4),E=yield w;clearTimeout(T);const C=E.headers.get("Content-Type"),O=C&&!C.includes("application/json");if(E.status===429||O){if(!f||O&&t.method!=="GET")throw new Es(qw(t.method,S,g,t.body,E,void 0,r));const D=E.headers.has("X-RateLimit-Reset")?Number.parseInt(E.headers.get("X-RateLimit-Reset"),10):u;return d>=jn.BASIC&&(E.status===429?h(`[${n}] Rate limit exceeded, wait ${D} seconds then retry...`):h(`[${n}] Invalid response content type "${C}" (status ${E.status}). Wait ${D} seconds then retry...`)),yield od(D*1e3),ld(Object.assign(Object.assign({},t),{retryCount:u+1}))}if(d>=jn.BASIC&&(h(`[${n}] Status: ${E.status} (${E.statusText})`),d>=jn.BODY_AND_HEADERS))for(const D of["x-api-version","x-environment","x-queue-time","x-ratelimit-remaining","x-request-id","cf-ray"]){const j=E.headers.get(D);j&&h(`[${n}] ${D}: ${j}`)}let L=E.status===204?void 0:yield E.json();if(d>=jn.BODY&&L&&h(`[${n}] ${JSON.stringify(L,null,2)}`),E.status===202){const D=yield t.fetchJobResult(L.data.id);if(D.status<200||D.status>=300)throw new Es(ZG(t.method,S,g,t.body,D.status,D.payload,r));L=D.payload}if(E.status>=200&&E.status<300)return L;const M=new Es(qw(t.method,S,g,t.body,E,L,r)),N=(e=M.errors.find(D=>D.attributes.transient))===null||e===void 0?void 0:e.attributes.code;if(f&&N)return d>=jn.BASIC&&h(`[${n}] ${N}, wait ${u} seconds then retry...`),yield od(u*1e3),ld(Object.assign(Object.assign({},t),{retryCount:u+1}));throw M}catch(w){if(w instanceof Nl||JG(w)&&w.code.includes("ETIMEDOUT")){if(f&&u<YG)return d>=jn.BASIC&&h(`[${n}] Timeout error, wait ${u} seconds then retry...`),yield od(u*1e3),ld(Object.assign(Object.assign({},t),{retryCount:u+1}));throw new IG(WG(t.method,S,g,t.body,r))}throw w}})}var UA=function(t,e){var n={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(n[i]=t[i]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,i=Object.getOwnPropertySymbols(t);r<i.length;r++)e.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(t,i[r])&&(n[i[r]]=t[i[r]]);return n};function ud(t){return typeof t=="object"&&!!t&&"id"in t&&"type"in t}function Mm(t){return Array.isArray(t)&&t.every(ud)}function he(t,e){if(typeof t!="object"||!t)throw new Error("Invalid body!");if(Array.isArray(t))return{data:t.map(h=>{var g;return(g=he(h,e))===null||g===void 0?void 0:g.data})};const n=t,{id:i,type:r,meta:l}=n,u=UA(n,["id","type","meta"]),d={},f={};if(e.attributes==="*")for(const[h,g]of Object.entries(u))if(e.relationships.includes(h))if(ud(g)){const{id:p,type:v}=g;f[h]={data:{id:p,type:v}}}else Mm(g)?f[h]={data:g.map(({id:p,type:v})=>({id:p,type:v}))}:f[h]={data:null};else d[h]=g;else if(e.relationships==="*")for(const[h,g]of Object.entries(u))if(e.attributes.includes(h))d[h]=g;else if(ud(g)){const{id:p,type:v}=g;f[h]={data:{id:p,type:v}}}else Mm(g)?f[h]={data:g.map(({id:p,type:v})=>({id:p,type:v}))}:f[h]={data:null};else{for(const[h,g]of Object.entries(u))if(e.attributes.includes(h))d[h]=g;else if(e.relationships.includes(h))if(ud(g)){const{id:p,type:v}=g;f[h]={data:{id:p,type:v}}}else Mm(g)?f[h]={data:g.map(({id:p,type:v})=>({id:p,type:v}))}:f[h]={data:null};e.attributes.includes("type")&&(d.type=r)}return{data:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},i||e.id?{id:i||e.id}:{}),{type:e.type}),Object.keys(d).length>0?{attributes:d}:{}),Object.keys(f).length>0?{relationships:f}:{}),l?{meta:l}:{})}}function Np(t){if(Array.isArray(t))return t.map(Np);if(t&&typeof t=="object"){const e={};for(const[n,i]of Object.entries(t))n!=="__itemTypeId"&&(e[n]=Np(i));return e}return t}function Kw(t){if(!t||typeof t!="object")return t;const{__itemTypeId:e}=t,n=UA(t,["__itemTypeId"]),i={};for(const[r,l]of Object.entries(n))i[r]=Np(l);return i}function zc(t){return!t||!("data"in t)?t:Array.isArray(t.data)?Object.assign(Object.assign({},t),{data:t.data.map(Kw)}):Object.assign(Object.assign({},t),{data:Kw(t.data)})}function J(t){return typeof t=="string"?t:t.id}class xe{constructor(e){this.client=e}}class VA extends xe{create(e){return this.rawCreate(he(e,{type:"role",attributes:["name","can_edit_favicon","can_edit_site","can_edit_schema","can_manage_menu","can_edit_environment","can_promote_environments","environments_access","can_manage_users","can_manage_shared_filters","can_manage_search_indexes","can_manage_upload_collections","can_manage_build_triggers","can_manage_webhooks","can_manage_environments","can_manage_sso","can_access_audit_log","can_manage_workflows","can_manage_access_tokens","can_perform_site_search","can_access_build_events_log","can_access_search_index_events_log","positive_item_type_permissions","negative_item_type_permissions","positive_upload_permissions","negative_upload_permissions","positive_build_trigger_permissions","negative_build_trigger_permissions","positive_search_index_permissions","negative_search_index_permissions"],relationships:["inherits_permissions_from"]})).then(n=>P(n))}rawCreate(e){return this.client.request({method:"POST",url:"/roles",body:e})}update(e,n){return this.rawUpdate(J(e),he(n,{id:J(e),type:"role",attributes:["name","can_edit_favicon","can_edit_site","can_edit_schema","can_manage_menu","can_edit_environment","can_promote_environments","environments_access","can_manage_users","can_manage_shared_filters","can_manage_search_indexes","can_manage_upload_collections","can_manage_build_triggers","can_manage_webhooks","can_manage_environments","can_manage_sso","can_access_audit_log","can_manage_workflows","can_manage_access_tokens","can_perform_site_search","can_access_build_events_log","can_access_search_index_events_log","positive_item_type_permissions","negative_item_type_permissions","positive_upload_permissions","negative_upload_permissions","positive_build_trigger_permissions","negative_build_trigger_permissions","positive_search_index_permissions","negative_search_index_permissions"],relationships:["inherits_permissions_from"]})).then(i=>P(i))}rawUpdate(e,n){return this.client.request({method:"PUT",url:`/roles/${e}`,body:n})}list(){return this.rawList().then(e=>P(e))}rawList(){return this.client.request({method:"GET",url:"/roles"})}find(e){return this.rawFind(J(e)).then(n=>P(n))}rawFind(e){return this.client.request({method:"GET",url:`/roles/${e}`})}destroy(e){return this.rawDestroy(J(e)).then(n=>P(n))}rawDestroy(e){return this.client.request({method:"DELETE",url:`/roles/${e}`})}duplicate(e){return this.rawDuplicate(J(e)).then(n=>P(n))}rawDuplicate(e){return this.client.request({method:"POST",url:`/roles/${e}/duplicate`})}}VA.TYPE="role";var t7=function(t,e,n,i){function r(l){return l instanceof n?l:new n(function(u){u(l)})}return new(n||(n=Promise))(function(l,u){function d(g){try{h(i.next(g))}catch(p){u(p)}}function f(g){try{h(i.throw(g))}catch(p){u(p)}}function h(g){g.done?l(g.value):r(g.value).then(d,f)}h((i=i.apply(t,e||[])).next())})};function Hw(t,e){return t==null&&e==null?!0:t===e}function n7(t,e){for(const n in t)if(!Hw(t[n],e[n]))return!1;for(const n in e)if(!Hw(t[n],e[n]))return!1;return!0}function Fc(t,e,n,i){if(!e)return t;const{add:r,remove:l}=e;return[...l?l.reduce((u,d)=>{const f=Object.assign(Object.assign({},d),{environment:n}),h=u.find(g=>n7(g,f));if(!h)throw new Error(`Cannot find rule ${JSON.stringify(f)} to remove in ${i}!`);return u.filter(g=>g!==h)},t):t,...r?r.map(u=>Object.assign({environment:n},u)):[]]}class a7 extends VA{updateCurrentEnvironmentPermissions(e,n){return t7(this,void 0,void 0,function*(){const i=this.client.config.environment||(yield this.client.environments.list()).find(f=>f.meta.primary).id,r=yield this.find(e),l=!!(n.positive_item_type_permissions||n.negative_item_type_permissions),u=!!(n.positive_upload_permissions||n.negative_upload_permissions),d=Object.assign(Object.assign({},l?{positive_item_type_permissions:Fc(r.positive_item_type_permissions,n.positive_item_type_permissions,i,"positive_item_type_permissions"),negative_item_type_permissions:Fc(r.negative_item_type_permissions,n.negative_item_type_permissions,i,"negative_item_type_permissions")}:{}),u?{positive_upload_permissions:Fc(r.positive_upload_permissions,n.positive_upload_permissions,i,"positive_upload_permissions"),negative_upload_permissions:Fc(r.negative_upload_permissions,n.negative_upload_permissions,i,"negative_upload_permissions")}:{});return this.update(e,d)})}}class $A extends xe{update(e,n){return this.rawUpdate(J(e),he(n,{id:J(e),type:"user",attributes:["is_active"],relationships:["role"]})).then(i=>P(i))}rawUpdate(e,n){return this.client.request({method:"PUT",url:`/users/${e}`,body:n})}list(){return this.rawList().then(e=>P(e))}rawList(){return this.client.request({method:"GET",url:"/users"})}find(e,n){return this.rawFind(J(e),n).then(i=>P(i))}rawFind(e,n){return this.client.request({method:"GET",url:`/users/${e}`,queryParams:n})}findMe(e){return this.rawFindMe(e).then(n=>P(n))}rawFindMe(e){return this.client.request({method:"GET",url:"/users/me",queryParams:e})}destroy(e,n){return this.rawDestroy(J(e),n).then(i=>P(i))}rawDestroy(e,n){return this.client.request({method:"DELETE",url:`/users/${e}`,queryParams:n})}}$A.TYPE="user";class qA extends xe{list(){return this.rawList().then(e=>P(e))}rawList(){return this.client.request({method:"GET",url:"/sso-users"})}find(e){return this.rawFind(J(e)).then(n=>P(n))}rawFind(e){return this.client.request({method:"GET",url:`/sso-users/${e}`})}copyUsers(){return this.rawCopyUsers().then(e=>P(e))}rawCopyUsers(){return this.client.request({method:"POST",url:"/sso-users/copy-users"})}destroy(e,n){return this.rawDestroy(J(e),n).then(i=>P(i))}rawDestroy(e,n){return this.client.request({method:"DELETE",url:`/sso-users/${e}`,queryParams:n})}}qA.TYPE="sso_user";class GA extends xe{query(e){return this.rawQuery(he(e,{type:"audit_log_query",attributes:["filter","next_token","detailed_log"],relationships:[]})).then(n=>P(n))}rawQuery(e){return this.client.request({method:"POST",url:"/audit-log-events/query",body:e})}}GA.TYPE="audit_log_event";class KA extends xe{create(e){return this.rawCreate(he(e,{type:"menu_item",attributes:["label","external_url","position","open_in_new_tab"],relationships:["item_type","item_type_filter","parent"]})).then(n=>P(n))}rawCreate(e){return this.client.request({method:"POST",url:"/menu-items",body:e})}update(e,n){return this.rawUpdate(J(e),he(n,{id:J(e),type:"menu_item",attributes:["label","external_url","position","open_in_new_tab"],relationships:["item_type","item_type_filter","parent"]})).then(i=>P(i))}rawUpdate(e,n){return this.client.request({method:"PUT",url:`/menu-items/${e}`,body:n})}list(e){return this.rawList(e).then(n=>P(n))}rawList(e){return this.client.request({method:"GET",url:"/menu-items",queryParams:e})}find(e){return this.rawFind(J(e)).then(n=>P(n))}rawFind(e){return this.client.request({method:"GET",url:`/menu-items/${e}`})}destroy(e){return this.rawDestroy(J(e)).then(n=>P(n))}rawDestroy(e){return this.client.request({method:"DELETE",url:`/menu-items/${e}`})}reorder(e){return this.rawReorder(he(e,{type:"menu_item",attributes:["position"],relationships:["parent"]})).then(n=>P(n))}rawReorder(e){return this.client.request({method:"POST",url:"/menu-items/reorder",body:e})}}KA.TYPE="menu_item";class HA extends xe{create(e){return this.rawCreate(he(e,{type:"schema_menu_item",attributes:["label","position","kind"],relationships:["item_type","parent"]})).then(n=>P(n))}rawCreate(e){return this.client.request({method:"POST",url:"/schema-menu-items",body:e})}update(e,n){return this.rawUpdate(J(e),he(n,{id:J(e),type:"schema_menu_item",attributes:["label","position","kind"],relationships:["item_type","parent","children"]})).then(i=>P(i))}rawUpdate(e,n){return this.client.request({method:"PUT",url:`/schema-menu-items/${e}`,body:n})}list(e){return this.rawList(e).then(n=>P(n))}rawList(e){return this.client.request({method:"GET",url:"/schema-menu-items",queryParams:e})}find(e){return this.rawFind(J(e)).then(n=>P(n))}rawFind(e){return this.client.request({method:"GET",url:`/schema-menu-items/${e}`})}destroy(e){return this.rawDestroy(J(e)).then(n=>P(n))}rawDestroy(e){return this.client.request({method:"DELETE",url:`/schema-menu-items/${e}`})}reorder(e){return this.rawReorder(he(e,{type:"schema_menu_item",attributes:["position"],relationships:["parent"]})).then(n=>P(n))}rawReorder(e){return this.client.request({method:"POST",url:"/schema-menu-items/reorder",body:e})}}HA.TYPE="schema_menu_item";class YA extends xe{create(e){return this.rawCreate(he(e,{type:"upload_collection",attributes:["label","position"],relationships:["parent"]})).then(n=>P(n))}rawCreate(e){return this.client.request({method:"POST",url:"/upload-collections",body:e})}update(e,n){return this.rawUpdate(J(e),he(n,{id:J(e),type:"upload_collection",attributes:["label","position"],relationships:["parent","children"]})).then(i=>P(i))}rawUpdate(e,n){return this.client.request({method:"PUT",url:`/upload-collections/${e}`,body:n})}list(e){return this.rawList(e).then(n=>P(n))}rawList(e){return this.client.request({method:"GET",url:"/upload-collections",queryParams:e})}find(e){return this.rawFind(J(e)).then(n=>P(n))}rawFind(e){return this.client.request({method:"GET",url:`/upload-collections/${e}`})}destroy(e){return this.rawDestroy(J(e)).then(n=>P(n))}rawDestroy(e){return this.client.request({method:"DELETE",url:`/upload-collections/${e}`})}reorder(e){return this.rawReorder(he(e,{type:"upload_collection",attributes:["position"],relationships:["parent"]})).then(n=>P(n))}rawReorder(e){return this.client.request({method:"POST",url:"/upload-collections/reorder",body:e})}}YA.TYPE="upload_collection";class XA extends xe{create(e,n){return this.rawCreate(he(e,{type:"item_type",attributes:["name","api_key","singleton","all_locales_required","sortable","modular_block","draft_mode_active","draft_saving_active","tree","ordering_direction","ordering_meta","collection_appeareance","collection_appearance","hint","inverse_relationships_enabled"],relationships:["ordering_field","presentation_title_field","presentation_image_field","title_field","image_preview_field","excerpt_field","workflow"]}),n).then(i=>P(i))}rawCreate(e,n){return this.client.request({method:"POST",url:"/item-types",body:e,queryParams:n})}update(e,n){return this.rawUpdate(J(e),he(n,{id:J(e),type:"item_type",attributes:["name","api_key","collection_appeareance","collection_appearance","singleton","all_locales_required","sortable","modular_block","draft_mode_active","draft_saving_active","tree","ordering_direction","ordering_meta","has_singleton_item","hint","inverse_relationships_enabled"],relationships:["ordering_field","presentation_title_field","presentation_image_field","title_field","image_preview_field","excerpt_field","workflow"]})).then(i=>P(i))}rawUpdate(e,n){return this.client.request({method:"PUT",url:`/item-types/${e}`,body:n})}list(){return this.rawList().then(e=>P(e))}rawList(){return this.client.request({method:"GET",url:"/item-types"})}find(e){return this.rawFind(J(e)).then(n=>P(n))}rawFind(e){return this.client.request({method:"GET",url:`/item-types/${e}`})}duplicate(e){return this.rawDuplicate(J(e)).then(n=>P(n))}rawDuplicate(e){return this.client.request({method:"POST",url:`/item-types/${e}/duplicate`})}destroy(e,n){return this.rawDestroy(J(e),n).then(i=>P(i))}rawDestroy(e,n){return this.client.request({method:"DELETE",url:`/item-types/${e}`,queryParams:n})}referencing(e){return this.rawReferencing(J(e)).then(n=>P(n))}rawReferencing(e){return this.client.request({method:"GET",url:`/item-types/${e}/referencing`})}rawReorderFieldsAndFieldsets(e,n){return this.client.request({method:"POST",url:`/item-types/${e}/reorder-fields-and-fieldsets`,body:n})}}XA.TYPE="item_type";class WA extends xe{create(e,n){return this.rawCreate(J(e),he(n,{type:"field",attributes:["label","field_type","api_key","localized","validators","appeareance","appearance","position","hint","default_value","deep_filtering_enabled"],relationships:["fieldset"]})).then(i=>P(i))}rawCreate(e,n){return this.client.request({method:"POST",url:`/item-types/${e}/fields`,body:n})}update(e,n){return this.rawUpdate(J(e),he(n,{id:J(e),type:"field",attributes:["default_value","label","api_key","localized","validators","appeareance","appearance","position","field_type","hint","deep_filtering_enabled"],relationships:["fieldset"]})).then(i=>P(i))}rawUpdate(e,n){return this.client.request({method:"PUT",url:`/fields/${e}`,body:n})}list(e){return this.rawList(J(e)).then(n=>P(n))}rawList(e){return this.client.request({method:"GET",url:`/item-types/${e}/fields`})}referencing(e){return this.rawReferencing(J(e)).then(n=>P(n))}rawReferencing(e){return this.client.request({method:"GET",url:`/item-types/${e}/fields/referencing`})}related(e){return this.rawRelated(J(e)).then(n=>P(n))}rawRelated(e){return this.client.request({method:"GET",url:`/item-types/${e}/fields/related`})}find(e){return this.rawFind(J(e)).then(n=>P(n))}rawFind(e){return this.client.request({method:"GET",url:`/fields/${e}`})}destroy(e){return this.rawDestroy(J(e)).then(n=>P(n))}rawDestroy(e){return this.client.request({method:"DELETE",url:`/fields/${e}`})}duplicate(e){return this.rawDuplicate(J(e)).then(n=>P(n))}rawDuplicate(e){return this.client.request({method:"POST",url:`/fields/${e}/duplicate`})}}WA.TYPE="field";class ZA extends xe{create(e,n){return this.rawCreate(J(e),he(n,{type:"fieldset",attributes:["title","hint","position","collapsible","start_collapsed"],relationships:[]})).then(i=>P(i))}rawCreate(e,n){return this.client.request({method:"POST",url:`/item-types/${e}/fieldsets`,body:n})}update(e,n){return this.rawUpdate(J(e),he(n,{id:J(e),type:"fieldset",attributes:["title","hint","position","collapsible","start_collapsed"],relationships:[]})).then(i=>P(i))}rawUpdate(e,n){return this.client.request({method:"PUT",url:`/fieldsets/${e}`,body:n})}list(e){return this.rawList(J(e)).then(n=>P(n))}rawList(e){return this.client.request({method:"GET",url:`/item-types/${e}/fieldsets`})}find(e){return this.rawFind(J(e)).then(n=>P(n))}rawFind(e){return this.client.request({method:"GET",url:`/fieldsets/${e}`})}destroy(e){return this.rawDestroy(J(e)).then(n=>P(n))}rawDestroy(e){return this.client.request({method:"DELETE",url:`/fieldsets/${e}`})}}ZA.TYPE="fieldset";class JA extends xe{create(e){return this.rawCreate(he(e,{type:"email_credentials",attributes:["email","password","otp_code"],relationships:[]})).then(n=>P(n))}rawCreate(e){return this.client.request({method:"POST",url:"/sessions",body:e})}}JA.TYPE="session";class QA extends xe{create(e){return this.rawCreate(he(e,{type:"access_token",attributes:["name","can_access_cda","can_access_cda_preview","can_access_cma"],relationships:["role"]})).then(n=>P(n))}rawCreate(e){return this.client.request({method:"POST",url:"/access_tokens",body:e})}update(e,n){return this.rawUpdate(J(e),he(n,{id:J(e),type:"access_token",attributes:["name","can_access_cda","can_access_cda_preview","can_access_cma"],relationships:["role"]})).then(i=>P(i))}rawUpdate(e,n){return this.client.request({method:"PUT",url:`/access_tokens/${e}`,body:n})}list(){return this.rawList().then(e=>P(e))}rawList(){return this.client.request({method:"GET",url:"/access_tokens"})}find(e){return this.rawFind(J(e)).then(n=>P(n))}rawFind(e){return this.client.request({method:"GET",url:`/access_tokens/${e}`})}regenerateToken(e){return this.rawRegenerateToken(J(e)).then(n=>P(n))}rawRegenerateToken(e){return this.client.request({method:"POST",url:`/access_tokens/${e}/regenerate_token`})}destroy(e,n){return this.rawDestroy(J(e),n).then(i=>P(i))}rawDestroy(e,n){return this.client.request({method:"DELETE",url:`/access_tokens/${e}`,queryParams:n})}}QA.TYPE="access_token";class eC extends xe{create(e){return this.rawCreate(he(e,{type:"plugin",attributes:["package_name","name","description","url","permissions","plugin_type","field_types","parameter_definitions","package_version"],relationships:[]})).then(n=>P(n))}rawCreate(e){return this.client.request({method:"POST",url:"/plugins",body:e})}update(e,n){return this.rawUpdate(J(e),he(n,{id:J(e),type:"plugin",attributes:["name","description","url","parameters","package_version","permissions"],relationships:[]})).then(i=>P(i))}rawUpdate(e,n){return this.client.request({method:"PUT",url:`/plugins/${e}`,body:n})}list(){return this.rawList().then(e=>P(e))}rawList(){return this.client.request({method:"GET",url:"/plugins"})}find(e){return this.rawFind(J(e)).then(n=>P(n))}rawFind(e){return this.client.request({method:"GET",url:`/plugins/${e}`})}destroy(e){return this.rawDestroy(J(e)).then(n=>P(n))}rawDestroy(e){return this.client.request({method:"DELETE",url:`/plugins/${e}`})}fields(e){return this.rawFields(J(e)).then(n=>P(n))}rawFields(e){return this.client.request({method:"GET",url:`/plugins/${e}/fields`})}}eC.TYPE="plugin";class tC extends xe{find(e){return this.rawFind(J(e)).then(n=>P(n))}rawFind(e){return this.client.request({method:"GET",url:`/job-results/${e}`})}}tC.TYPE="job_result";class nC extends xe{list(){return this.rawList().then(e=>P(e))}rawList(){return this.client.request({method:"GET",url:"/subscription-limits"})}find(e){return this.rawFind(J(e)).then(n=>P(n))}rawFind(e){return this.client.request({method:"GET",url:`/subscription-limits/${e}`})}}nC.TYPE="subscription_limit";class aC extends xe{list(){return this.rawList().then(e=>P(e))}rawList(){return this.client.request({method:"GET",url:"/subscription-features"})}}aC.TYPE="subscription_feature";var i7=function(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],n;return e?e.call(t):(t=typeof __values=="function"?__values(t):t[Symbol.iterator](),n={},i("next"),i("throw"),i("return"),n[Symbol.asyncIterator]=function(){return this},n);function i(l){n[l]=t[l]&&function(u){return new Promise(function(d,f){u=t[l](u),r(d,f,u.done,u.value)})}}function r(l,u,d,f){Promise.resolve(f).then(function(h){l({value:h,done:d})},u)}},Fr=function(t){return this instanceof Fr?(this.v=t,this):new Fr(t)},s7=function(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=n.apply(t,e||[]),r,l=[];return r={},u("next"),u("throw"),u("return"),r[Symbol.asyncIterator]=function(){return this},r;function u(v){i[v]&&(r[v]=function(b){return new Promise(function(S,w){l.push([v,b,S,w])>1||d(v,b)})})}function d(v,b){try{f(i[v](b))}catch(S){p(l[0][3],S)}}function f(v){v.value instanceof Fr?Promise.resolve(v.value.v).then(h,g):p(l[0][2],v)}function h(v){d("next",v)}function g(v){d("throw",v)}function p(v,b){v(b),l.shift(),l.length&&d(l[0][0],l[0][1])}};class iC extends xe{list(e){return this.rawList(e).then(n=>P(n))}rawList(e){return this.client.request({method:"GET",url:"/build-events",queryParams:e})}listPagedIterator(e,n){return s7(this,arguments,function*(){var r,l,u,d;try{for(var f=!0,h=i7(this.rawListPagedIterator(e,n)),g;g=yield Fr(h.next()),r=g.done,!r;){d=g.value,f=!1;try{yield yield Fr(ia(d))}finally{f=!0}}}catch(p){l={error:p}}finally{try{!f&&!r&&(u=h.return)&&(yield Fr(u.call(h)))}finally{if(l)throw l.error}}})}rawListPagedIterator(e,n){return ai(e),ni({defaultLimit:30,maxLimit:500},i=>this.rawList(Object.assign(Object.assign({},e),{page:i})),n)}find(e){return this.rawFind(J(e)).then(n=>P(n))}rawFind(e){return this.client.request({method:"GET",url:`/build-events/${e}`})}}iC.TYPE="build_event";var r7=function(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],n;return e?e.call(t):(t=typeof __values=="function"?__values(t):t[Symbol.iterator](),n={},i("next"),i("throw"),i("return"),n[Symbol.asyncIterator]=function(){return this},n);function i(l){n[l]=t[l]&&function(u){return new Promise(function(d,f){u=t[l](u),r(d,f,u.done,u.value)})}}function r(l,u,d,f){Promise.resolve(f).then(function(h){l({value:h,done:d})},u)}},Ur=function(t){return this instanceof Ur?(this.v=t,this):new Ur(t)},o7=function(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=n.apply(t,e||[]),r,l=[];return r={},u("next"),u("throw"),u("return"),r[Symbol.asyncIterator]=function(){return this},r;function u(v){i[v]&&(r[v]=function(b){return new Promise(function(S,w){l.push([v,b,S,w])>1||d(v,b)})})}function d(v,b){try{f(i[v](b))}catch(S){p(l[0][3],S)}}function f(v){v.value instanceof Ur?Promise.resolve(v.value.v).then(h,g):p(l[0][2],v)}function h(v){d("next",v)}function g(v){d("throw",v)}function p(v,b){v(b),l.shift(),l.length&&d(l[0][0],l[0][1])}};class sC extends xe{list(e){return this.rawList(e).then(n=>P(n))}rawList(e){return this.client.request({method:"GET",url:"/search-index-events",queryParams:e})}listPagedIterator(e,n){return o7(this,arguments,function*(){var r,l,u,d;try{for(var f=!0,h=r7(this.rawListPagedIterator(e,n)),g;g=yield Ur(h.next()),r=g.done,!r;){d=g.value,f=!1;try{yield yield Ur(ia(d))}finally{f=!0}}}catch(p){l={error:p}}finally{try{!f&&!r&&(u=h.return)&&(yield Ur(u.call(h)))}finally{if(l)throw l.error}}})}rawListPagedIterator(e,n){return ai(e),ni({defaultLimit:30,maxLimit:500},i=>this.rawList(Object.assign(Object.assign({},e),{page:i})),n)}find(e){return this.rawFind(J(e)).then(n=>P(n))}rawFind(e){return this.client.request({method:"GET",url:`/search-index-events/${e}`})}}sC.TYPE="search_index_event";var l7=function(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],n;return e?e.call(t):(t=typeof __values=="function"?__values(t):t[Symbol.iterator](),n={},i("next"),i("throw"),i("return"),n[Symbol.asyncIterator]=function(){return this},n);function i(l){n[l]=t[l]&&function(u){return new Promise(function(d,f){u=t[l](u),r(d,f,u.done,u.value)})}}function r(l,u,d,f){Promise.resolve(f).then(function(h){l({value:h,done:d})},u)}},Vr=function(t){return this instanceof Vr?(this.v=t,this):new Vr(t)},u7=function(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=n.apply(t,e||[]),r,l=[];return r={},u("next"),u("throw"),u("return"),r[Symbol.asyncIterator]=function(){return this},r;function u(v){i[v]&&(r[v]=function(b){return new Promise(function(S,w){l.push([v,b,S,w])>1||d(v,b)})})}function d(v,b){try{f(i[v](b))}catch(S){p(l[0][3],S)}}function f(v){v.value instanceof Vr?Promise.resolve(v.value.v).then(h,g):p(l[0][2],v)}function h(v){d("next",v)}function g(v){d("throw",v)}function p(v,b){v(b),l.shift(),l.length&&d(l[0][0],l[0][1])}};class rC extends xe{list(e){return this.rawList(e).then(n=>P(n))}rawList(e){return this.client.request({method:"GET",url:"/items",queryParams:e}).then(zn)}listPagedIterator(e,n){return u7(this,arguments,function*(){var r,l,u,d;try{for(var f=!0,h=l7(this.rawListPagedIterator(e,n)),g;g=yield Vr(h.next()),r=g.done,!r;){d=g.value,f=!1;try{yield yield Vr(ia(d))}finally{f=!0}}}catch(p){l={error:p}}finally{try{!f&&!r&&(u=h.return)&&(yield Vr(u.call(h)))}finally{if(l)throw l.error}}})}rawListPagedIterator(e,n){return ai(e),ni({defaultLimit:30,maxLimit:500},i=>this.rawList(Object.assign(Object.assign({},e),{page:i})),n,!0)}validateExisting(e,n){return this.rawValidateExisting(J(e),he(n,{id:J(e),type:"item",attributes:"*",relationships:["item_type","creator"]}))}rawValidateExisting(e,n){return this.client.request({method:"POST",url:`/items/${e}/validate`,body:zc(n)})}validateNew(e){return this.rawValidateNew(he(e,{type:"item",attributes:"*",relationships:["item_type","creator"]}))}rawValidateNew(e){return this.client.request({method:"POST",url:"/items/validate",body:zc(e)})}create(e){return this.rawCreate(he(e,{type:"item",attributes:"*",relationships:["item_type","creator"]})).then(n=>P(n))}rawCreate(e){return this.client.request({method:"POST",url:"/items",body:zc(e)}).then(zn)}duplicate(e){return this.rawDuplicate(J(e)).then(n=>P(n))}rawDuplicate(e){return this.client.request({method:"POST",url:`/items/${e}/duplicate`}).then(zn)}update(e,n){return this.rawUpdate(J(e),he(n,{id:J(e),type:"item",attributes:"*",relationships:["item_type","creator"]})).then(i=>P(i))}rawUpdate(e,n){return this.client.request({method:"PUT",url:`/items/${e}`,body:zc(n)}).then(zn)}references(e,n){return this.rawReferences(J(e),n).then(i=>P(i))}rawReferences(e,n){return this.client.request({method:"GET",url:`/items/${e}/references`,queryParams:n}).then(zn)}find(e,n){return this.rawFind(J(e),n).then(i=>P(i))}rawFind(e,n){return this.client.request({method:"GET",url:`/items/${e}`,queryParams:n}).then(zn)}currentVsPublishedState(e){return this.rawCurrentVsPublishedState(J(e)).then(n=>P(n))}rawCurrentVsPublishedState(e){return this.client.request({method:"GET",url:`/items/${e}/current-vs-published-state`})}destroy(e){return this.rawDestroy(J(e)).then(n=>P(n))}rawDestroy(e){return this.client.request({method:"DELETE",url:`/items/${e}`}).then(zn)}publish(e,n,i){return this.rawPublish(J(e),n?he(n,{type:"selective_publish_operation",attributes:["content_in_locales","non_localized_content"],relationships:[]}):null,i).then(r=>P(r))}rawPublish(e,n,i){return this.client.request({method:"PUT",url:`/items/${e}/publish`,body:n,queryParams:i}).then(zn)}unpublish(e,n,i){return this.rawUnpublish(J(e),n?he(n,{type:"selective_unpublish_operation",attributes:["content_in_locales"],relationships:[]}):null,i).then(r=>P(r))}rawUnpublish(e,n,i){return this.client.request({method:"PUT",url:`/items/${e}/unpublish`,body:n,queryParams:i}).then(zn)}bulkPublish(e){return this.rawBulkPublish(he(e,{type:"item_bulk_publish_operation",attributes:[],relationships:["items"]})).then(n=>P(n))}rawBulkPublish(e){return this.client.request({method:"POST",url:"/items/bulk/publish",body:e})}bulkUnpublish(e){return this.rawBulkUnpublish(he(e,{type:"item_bulk_unpublish_operation",attributes:[],relationships:["items"]})).then(n=>P(n))}rawBulkUnpublish(e){return this.client.request({method:"POST",url:"/items/bulk/unpublish",body:e})}bulkDestroy(e){return this.rawBulkDestroy(he(e,{type:"item_bulk_destroy_operation",attributes:[],relationships:["items"]})).then(n=>P(n))}rawBulkDestroy(e){return this.client.request({method:"POST",url:"/items/bulk/destroy",body:e})}bulkMoveToStage(e){return this.rawBulkMoveToStage(he(e,{type:"item_bulk_move_to_stage_operation",attributes:["stage"],relationships:["items"]})).then(n=>P(n))}rawBulkMoveToStage(e){return this.client.request({method:"POST",url:"/items/bulk/move-to-stage",body:e})}}rC.TYPE="item";var c7=function(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],n;return e?e.call(t):(t=typeof __values=="function"?__values(t):t[Symbol.iterator](),n={},i("next"),i("throw"),i("return"),n[Symbol.asyncIterator]=function(){return this},n);function i(l){n[l]=t[l]&&function(u){return new Promise(function(d,f){u=t[l](u),r(d,f,u.done,u.value)})}}function r(l,u,d,f){Promise.resolve(f).then(function(h){l({value:h,done:d})},u)}},$r=function(t){return this instanceof $r?(this.v=t,this):new $r(t)},d7=function(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=n.apply(t,e||[]),r,l=[];return r={},u("next"),u("throw"),u("return"),r[Symbol.asyncIterator]=function(){return this},r;function u(v){i[v]&&(r[v]=function(b){return new Promise(function(S,w){l.push([v,b,S,w])>1||d(v,b)})})}function d(v,b){try{f(i[v](b))}catch(S){p(l[0][3],S)}}function f(v){v.value instanceof $r?Promise.resolve(v.value.v).then(h,g):p(l[0][2],v)}function h(v){d("next",v)}function g(v){d("throw",v)}function p(v,b){v(b),l.shift(),l.length&&d(l[0][0],l[0][1])}};class oC extends xe{restore(e){return this.rawRestore(J(e)).then(n=>P(n))}rawRestore(e){return this.client.request({method:"POST",url:`/versions/${e}/restore`})}list(e,n){return this.rawList(J(e),n).then(i=>P(i))}rawList(e,n){return this.client.request({method:"GET",url:`/items/${e}/versions`,queryParams:n})}listPagedIterator(e,n,i){return d7(this,arguments,function*(){var l,u,d,f;try{for(var h=!0,g=c7(this.rawListPagedIterator(J(e),n,i)),p;p=yield $r(g.next()),l=p.done,!l;){f=p.value,h=!1;try{yield yield $r(ia(f))}finally{h=!0}}}catch(v){u={error:v}}finally{try{!h&&!l&&(d=g.return)&&(yield $r(d.call(g)))}finally{if(u)throw u.error}}})}rawListPagedIterator(e,n,i){return ai(n),ni({defaultLimit:15,maxLimit:50},r=>this.rawList(e,Object.assign(Object.assign({},n),{page:r})),i)}find(e,n){return this.rawFind(J(e),n).then(i=>P(i))}rawFind(e,n){return this.client.request({method:"GET",url:`/versions/${e}`,queryParams:n})}}oC.TYPE="item_version";var f7=function(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],n;return e?e.call(t):(t=typeof __values=="function"?__values(t):t[Symbol.iterator](),n={},i("next"),i("throw"),i("return"),n[Symbol.asyncIterator]=function(){return this},n);function i(l){n[l]=t[l]&&function(u){return new Promise(function(d,f){u=t[l](u),r(d,f,u.done,u.value)})}}function r(l,u,d,f){Promise.resolve(f).then(function(h){l({value:h,done:d})},u)}},qr=function(t){return this instanceof qr?(this.v=t,this):new qr(t)},h7=function(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=n.apply(t,e||[]),r,l=[];return r={},u("next"),u("throw"),u("return"),r[Symbol.asyncIterator]=function(){return this},r;function u(v){i[v]&&(r[v]=function(b){return new Promise(function(S,w){l.push([v,b,S,w])>1||d(v,b)})})}function d(v,b){try{f(i[v](b))}catch(S){p(l[0][3],S)}}function f(v){v.value instanceof qr?Promise.resolve(v.value.v).then(h,g):p(l[0][2],v)}function h(v){d("next",v)}function g(v){d("throw",v)}function p(v,b){v(b),l.shift(),l.length&&d(l[0][0],l[0][1])}};let av=class extends xe{create(e){return this.rawCreate(he(e,{type:"upload",attributes:["path","copyright","author","notes","default_field_metadata","tags"],relationships:["upload_collection"]})).then(n=>P(n))}rawCreate(e){return this.client.request({method:"POST",url:"/uploads",body:e})}list(e){return this.rawList(e).then(n=>P(n))}rawList(e){return this.client.request({method:"GET",url:"/uploads",queryParams:e})}listPagedIterator(e,n){return h7(this,arguments,function*(){var r,l,u,d;try{for(var f=!0,h=f7(this.rawListPagedIterator(e,n)),g;g=yield qr(h.next()),r=g.done,!r;){d=g.value,f=!1;try{yield yield qr(ia(d))}finally{f=!0}}}catch(p){l={error:p}}finally{try{!f&&!r&&(u=h.return)&&(yield qr(u.call(h)))}finally{if(l)throw l.error}}})}rawListPagedIterator(e,n){return ai(e),ni({defaultLimit:30,maxLimit:500},i=>this.rawList(Object.assign(Object.assign({},e),{page:i})),n)}find(e){return this.rawFind(J(e)).then(n=>P(n))}rawFind(e){return this.client.request({method:"GET",url:`/uploads/${e}`})}destroy(e){return this.rawDestroy(J(e)).then(n=>P(n))}rawDestroy(e){return this.client.request({method:"DELETE",url:`/uploads/${e}`})}update(e,n,i){return this.rawUpdate(J(e),he(n,{id:J(e),type:"upload",attributes:["path","basename","copyright","author","notes","tags","default_field_metadata"],relationships:["creator","upload_collection"]}),i).then(r=>P(r))}rawUpdate(e,n,i){return this.client.request({method:"PUT",url:`/uploads/${e}`,body:n,queryParams:i})}references(e,n){return this.rawReferences(J(e),n).then(i=>P(i))}rawReferences(e,n){return this.client.request({method:"GET",url:`/uploads/${e}/references`,queryParams:n}).then(zn)}bulkTag(e){return this.rawBulkTag(he(e,{type:"upload_bulk_tag_operation",attributes:["tags"],relationships:["uploads"]})).then(n=>P(n))}rawBulkTag(e){return this.client.request({method:"POST",url:"/uploads/bulk/tag",body:e})}bulkSetUploadCollection(e){return this.rawBulkSetUploadCollection(he(e,{type:"upload_bulk_set_upload_collection_operation",attributes:[],relationships:["upload_collection","uploads"]})).then(n=>P(n))}rawBulkSetUploadCollection(e){return this.client.request({method:"POST",url:"/uploads/bulk/set-upload-collection",body:e})}bulkDestroy(e){return this.rawBulkDestroy(he(e,{type:"upload_bulk_destroy_operation",attributes:[],relationships:["uploads"]})).then(n=>P(n))}rawBulkDestroy(e){return this.client.request({method:"POST",url:"/uploads/bulk/destroy",body:e})}};av.TYPE="upload";class lC extends xe{create(e){return this.rawCreate(he(e,{type:"upload_request",attributes:["filename"],relationships:["upload_collection"]})).then(n=>P(n))}rawCreate(e){return this.client.request({method:"POST",url:"/upload-requests",body:e})}}lC.TYPE="upload_request";class uC extends xe{create(e,n){return this.rawCreate(J(e),he(n,{type:"upload_track",attributes:["url_or_upload_request_id","type","name","language_code","closed_captions"],relationships:[]})).then(i=>P(i))}rawCreate(e,n){return this.client.request({method:"POST",url:`/uploads/${e}/tracks`,body:n})}list(e){return this.rawList(J(e)).then(n=>P(n))}rawList(e){return this.client.request({method:"GET",url:`/uploads/${e}/tracks`})}destroy(e,n){return this.rawDestroy(J(e),J(n)).then(i=>P(i))}rawDestroy(e,n){return this.client.request({method:"DELETE",url:`/uploads/${e}/tracks/${n}`})}generateSubtitles(e,n){return this.rawGenerateSubtitles(J(e),he(n,{type:"upload_track",attributes:["name","language_code"],relationships:[]})).then(i=>P(i))}rawGenerateSubtitles(e,n){return this.client.request({method:"POST",url:`/uploads/${e}/tracks/generate-subtitles`,body:n})}}uC.TYPE="upload_track";class cC extends xe{create(e,n){return this.rawCreate(J(e),he(n,{type:"scheduled_publication",attributes:["publication_scheduled_at","selective_publication"],relationships:[]})).then(i=>P(i))}rawCreate(e,n){return this.client.request({method:"POST",url:`/items/${e}/scheduled-publication`,body:n})}destroy(e){return this.rawDestroy(J(e)).then(n=>P(n))}rawDestroy(e){return this.client.request({method:"DELETE",url:`/items/${e}/scheduled-publication`}).then(zn)}}cC.TYPE="scheduled_publication";class dC extends xe{create(e,n){return this.rawCreate(J(e),he(n,{type:"scheduled_unpublishing",attributes:["unpublishing_scheduled_at","content_in_locales"],relationships:[]})).then(i=>P(i))}rawCreate(e,n){return this.client.request({method:"POST",url:`/items/${e}/scheduled-unpublishing`,body:n})}destroy(e){return this.rawDestroy(J(e)).then(n=>P(n))}rawDestroy(e){return this.client.request({method:"DELETE",url:`/items/${e}/scheduled-unpublishing`}).then(zn)}}dC.TYPE="scheduled_unpublishing";var g7=function(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],n;return e?e.call(t):(t=typeof __values=="function"?__values(t):t[Symbol.iterator](),n={},i("next"),i("throw"),i("return"),n[Symbol.asyncIterator]=function(){return this},n);function i(l){n[l]=t[l]&&function(u){return new Promise(function(d,f){u=t[l](u),r(d,f,u.done,u.value)})}}function r(l,u,d,f){Promise.resolve(f).then(function(h){l({value:h,done:d})},u)}},Gr=function(t){return this instanceof Gr?(this.v=t,this):new Gr(t)},m7=function(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=n.apply(t,e||[]),r,l=[];return r={},u("next"),u("throw"),u("return"),r[Symbol.asyncIterator]=function(){return this},r;function u(v){i[v]&&(r[v]=function(b){return new Promise(function(S,w){l.push([v,b,S,w])>1||d(v,b)})})}function d(v,b){try{f(i[v](b))}catch(S){p(l[0][3],S)}}function f(v){v.value instanceof Gr?Promise.resolve(v.value.v).then(h,g):p(l[0][2],v)}function h(v){d("next",v)}function g(v){d("throw",v)}function p(v,b){v(b),l.shift(),l.length&&d(l[0][0],l[0][1])}};class fC extends xe{list(e){return this.rawList(e).then(n=>P(n))}rawList(e){return this.client.request({method:"GET",url:"/search-results",queryParams:e})}listPagedIterator(e,n){return m7(this,arguments,function*(){var r,l,u,d;try{for(var f=!0,h=g7(this.rawListPagedIterator(e,n)),g;g=yield Gr(h.next()),r=g.done,!r;){d=g.value,f=!1;try{yield yield Gr(ia(d))}finally{f=!0}}}catch(p){l={error:p}}finally{try{!f&&!r&&(u=h.return)&&(yield Gr(u.call(h)))}finally{if(l)throw l.error}}})}rawListPagedIterator(e,n){return ai(e),ni({defaultLimit:20,maxLimit:100},i=>this.rawList(Object.assign(Object.assign({},e),{page:i})),n)}}fC.TYPE="search_result";class hC extends xe{fork(e,n,i){return this.rawFork(J(e),he(n,{id:J(e),type:"environment",attributes:[],relationships:[]}),i).then(r=>P(r))}rawFork(e,n,i){return this.client.request({method:"POST",url:`/environments/${e}/fork`,body:n,queryParams:i})}promote(e){return this.rawPromote(J(e)).then(n=>P(n))}rawPromote(e){return this.client.request({method:"PUT",url:`/environments/${e}/promote`})}rename(e,n){return this.rawRename(J(e),he(n,{id:J(e),type:"environment",attributes:[],relationships:[]})).then(i=>P(i))}rawRename(e,n){return this.client.request({method:"PUT",url:`/environments/${e}/rename`,body:n})}list(){return this.rawList().then(e=>P(e))}rawList(){return this.client.request({method:"GET",url:"/environments"})}find(e){return this.rawFind(J(e)).then(n=>P(n))}rawFind(e){return this.client.request({method:"GET",url:`/environments/${e}`})}destroy(e){return this.rawDestroy(J(e)).then(n=>P(n))}rawDestroy(e){return this.client.request({method:"DELETE",url:`/environments/${e}`})}}hC.TYPE="environment";class gC extends xe{find(){return this.rawFind().then(e=>P(e))}rawFind(){return this.client.request({method:"GET",url:"/maintenance-mode"})}activate(e){return this.rawActivate(e).then(n=>P(n))}rawActivate(e){return this.client.request({method:"PUT",url:"/maintenance-mode/activate",queryParams:e})}deactivate(){return this.rawDeactivate().then(e=>P(e))}rawDeactivate(){return this.client.request({method:"PUT",url:"/maintenance-mode/deactivate"})}}gC.TYPE="maintenance_mode";class mC extends xe{create(e){return this.rawCreate(he(e,{type:"webhook",attributes:["name","url","custom_payload","headers","events","http_basic_user","http_basic_password","enabled","payload_api_version","nested_items_in_payload","auto_retry"],relationships:[]})).then(n=>P(n))}rawCreate(e){return this.client.request({method:"POST",url:"/webhooks",body:e})}update(e,n){return this.rawUpdate(J(e),he(n,{id:J(e),type:"webhook",attributes:["name","url","custom_payload","headers","events","http_basic_user","http_basic_password","enabled","payload_api_version","nested_items_in_payload","auto_retry"],relationships:[]})).then(i=>P(i))}rawUpdate(e,n){return this.client.request({method:"PUT",url:`/webhooks/${e}`,body:n})}list(){return this.rawList().then(e=>P(e))}rawList(){return this.client.request({method:"GET",url:"/webhooks"})}find(e){return this.rawFind(J(e)).then(n=>P(n))}rawFind(e){return this.client.request({method:"GET",url:`/webhooks/${e}`})}destroy(e){return this.rawDestroy(J(e)).then(n=>P(n))}rawDestroy(e){return this.client.request({method:"DELETE",url:`/webhooks/${e}`})}}mC.TYPE="webhook";var p7=function(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],n;return e?e.call(t):(t=typeof __values=="function"?__values(t):t[Symbol.iterator](),n={},i("next"),i("throw"),i("return"),n[Symbol.asyncIterator]=function(){return this},n);function i(l){n[l]=t[l]&&function(u){return new Promise(function(d,f){u=t[l](u),r(d,f,u.done,u.value)})}}function r(l,u,d,f){Promise.resolve(f).then(function(h){l({value:h,done:d})},u)}},Kr=function(t){return this instanceof Kr?(this.v=t,this):new Kr(t)},y7=function(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=n.apply(t,e||[]),r,l=[];return r={},u("next"),u("throw"),u("return"),r[Symbol.asyncIterator]=function(){return this},r;function u(v){i[v]&&(r[v]=function(b){return new Promise(function(S,w){l.push([v,b,S,w])>1||d(v,b)})})}function d(v,b){try{f(i[v](b))}catch(S){p(l[0][3],S)}}function f(v){v.value instanceof Kr?Promise.resolve(v.value.v).then(h,g):p(l[0][2],v)}function h(v){d("next",v)}function g(v){d("throw",v)}function p(v,b){v(b),l.shift(),l.length&&d(l[0][0],l[0][1])}};class pC extends xe{list(e){return this.rawList(e).then(n=>P(n))}rawList(e){return this.client.request({method:"GET",url:"/webhook_calls",queryParams:e})}listPagedIterator(e,n){return y7(this,arguments,function*(){var r,l,u,d;try{for(var f=!0,h=p7(this.rawListPagedIterator(e,n)),g;g=yield Kr(h.next()),r=g.done,!r;){d=g.value,f=!1;try{yield yield Kr(ia(d))}finally{f=!0}}}catch(p){l={error:p}}finally{try{!f&&!r&&(u=h.return)&&(yield Kr(u.call(h)))}finally{if(l)throw l.error}}})}rawListPagedIterator(e,n){return ai(e),ni({defaultLimit:30,maxLimit:500},i=>this.rawList(Object.assign(Object.assign({},e),{page:i})),n)}find(e){return this.rawFind(J(e)).then(n=>P(n))}rawFind(e){return this.client.request({method:"GET",url:`/webhook_calls/${e}`})}resendWebhook(e){return this.rawResendWebhook(J(e))}rawResendWebhook(e){return this.client.request({method:"POST",url:`/webhook_calls/${e}/resend_webhook`})}}pC.TYPE="webhook_call";class yC extends xe{list(){return this.rawList().then(e=>P(e))}rawList(){return this.client.request({method:"GET",url:"/build-triggers"})}find(e){return this.rawFind(J(e)).then(n=>P(n))}rawFind(e){return this.client.request({method:"GET",url:`/build-triggers/${e}`})}create(e){return this.rawCreate(he(e,{type:"build_trigger",attributes:["name","webhook_token","adapter","indexing_enabled","enabled","frontend_url","autotrigger_on_scheduled_publications","adapter_settings"],relationships:[]})).then(n=>P(n))}rawCreate(e){return this.client.request({method:"POST",url:"/build-triggers",body:e})}update(e,n){return this.rawUpdate(J(e),he(n,{id:J(e),type:"build_trigger",attributes:["name","adapter","indexing_enabled","enabled","frontend_url","autotrigger_on_scheduled_publications","adapter_settings"],relationships:[]})).then(i=>P(i))}rawUpdate(e,n){return this.client.request({method:"PUT",url:`/build-triggers/${e}`,body:n})}trigger(e){return this.rawTrigger(J(e))}rawTrigger(e){return this.client.request({method:"POST",url:`/build-triggers/${e}/trigger`})}abort(e){return this.rawAbort(J(e))}rawAbort(e){return this.client.request({method:"DELETE",url:`/build-triggers/${e}/abort`})}abortIndexing(e){return this.rawAbortIndexing(J(e))}rawAbortIndexing(e){return this.client.request({method:"DELETE",url:`/build-triggers/${e}/abort_indexing`})}reindex(e){return this.rawReindex(J(e))}rawReindex(e){return this.client.request({method:"PUT",url:`/build-triggers/${e}/reindex`})}destroy(e){return this.rawDestroy(J(e)).then(n=>P(n))}rawDestroy(e){return this.client.request({method:"DELETE",url:`/build-triggers/${e}`})}}yC.TYPE="build_trigger";class vC extends xe{list(){return this.rawList().then(e=>P(e))}rawList(){return this.client.request({method:"GET",url:"/search-indexes"})}find(e){return this.rawFind(J(e)).then(n=>P(n))}rawFind(e){return this.client.request({method:"GET",url:`/search-indexes/${e}`})}create(e){return this.rawCreate(he(e,{type:"search_index",attributes:["name","enabled","frontend_url","user_agent_suffix"],relationships:["build_triggers"]})).then(n=>P(n))}rawCreate(e){return this.client.request({method:"POST",url:"/search-indexes",body:e})}update(e,n){return this.rawUpdate(J(e),he(n,{id:J(e),type:"search_index",attributes:["name","enabled","frontend_url","user_agent_suffix"],relationships:["build_triggers"]})).then(i=>P(i))}rawUpdate(e,n){return this.client.request({method:"PUT",url:`/search-indexes/${e}`,body:n})}trigger(e){return this.rawTrigger(J(e))}rawTrigger(e){return this.client.request({method:"POST",url:`/search-indexes/${e}/trigger`})}abort(e){return this.rawAbort(J(e))}rawAbort(e){return this.client.request({method:"DELETE",url:`/search-indexes/${e}/abort`})}destroy(e){return this.rawDestroy(J(e)).then(n=>P(n))}rawDestroy(e){return this.client.request({method:"DELETE",url:`/search-indexes/${e}`})}}vC.TYPE="search_index";class bC extends xe{create(e){return this.rawCreate(he(e,{type:"item_type_filter",attributes:["name","filter","columns","order_by","shared"],relationships:["item_type"]})).then(n=>P(n))}rawCreate(e){return this.client.request({method:"POST",url:"/item-type-filters",body:e})}update(e,n){return this.rawUpdate(J(e),he(n,{id:J(e),type:"item_type_filter",attributes:["name","columns","order_by","shared","filter"],relationships:["item_type"]})).then(i=>P(i))}rawUpdate(e,n){return this.client.request({method:"PUT",url:`/item-type-filters/${e}`,body:n})}list(){return this.rawList().then(e=>P(e))}rawList(){return this.client.request({method:"GET",url:"/item-type-filters"})}find(e){return this.rawFind(J(e)).then(n=>P(n))}rawFind(e){return this.client.request({method:"GET",url:`/item-type-filters/${e}`})}destroy(e){return this.rawDestroy(J(e)).then(n=>P(n))}rawDestroy(e){return this.client.request({method:"DELETE",url:`/item-type-filters/${e}`})}}bC.TYPE="item_type_filter";class SC extends xe{create(e){return this.rawCreate(he(e,{type:"upload_filter",attributes:["name","filter","shared"],relationships:[]})).then(n=>P(n))}rawCreate(e){return this.client.request({method:"POST",url:"/upload-filters",body:e})}update(e,n){return this.rawUpdate(J(e),he(n,{id:J(e),type:"upload_filter",attributes:["name","shared","filter"],relationships:[]})).then(i=>P(i))}rawUpdate(e,n){return this.client.request({method:"PUT",url:`/upload-filters/${e}`,body:n})}list(){return this.rawList().then(e=>P(e))}rawList(){return this.client.request({method:"GET",url:"/upload-filters"})}find(e){return this.rawFind(J(e)).then(n=>P(n))}rawFind(e){return this.client.request({method:"GET",url:`/upload-filters/${e}`})}destroy(e){return this.rawDestroy(J(e)).then(n=>P(n))}rawDestroy(e){return this.client.request({method:"DELETE",url:`/upload-filters/${e}`})}}SC.TYPE="upload_filter";class _C extends xe{create(e){return this.rawCreate(he(e,{type:"site_invitation",attributes:["email"],relationships:["role"]})).then(n=>P(n))}rawCreate(e){return this.client.request({method:"POST",url:"/site-invitations",body:e})}update(e,n){return this.rawUpdate(J(e),he(n,{id:J(e),type:"site_invitation",attributes:[],relationships:["role"]})).then(i=>P(i))}rawUpdate(e,n){return this.client.request({method:"PUT",url:`/site-invitations/${e}`,body:n})}list(){return this.rawList().then(e=>P(e))}rawList(){return this.client.request({method:"GET",url:"/site-invitations"})}find(e){return this.rawFind(J(e)).then(n=>P(n))}rawFind(e){return this.client.request({method:"GET",url:`/site-invitations/${e}`})}destroy(e){return this.rawDestroy(J(e)).then(n=>P(n))}rawDestroy(e){return this.client.request({method:"DELETE",url:`/site-invitations/${e}`})}resend(e){return this.rawResend(J(e)).then(n=>P(n))}rawResend(e){return this.client.request({method:"POST",url:`/site-invitations/${e}/resend`})}}_C.TYPE="site_invitation";class wC extends xe{list(){return this.rawList().then(e=>P(e))}rawList(){return this.client.request({method:"GET",url:"/editing-sessions"})}rawUpdate(e,n){return this.client.request({method:"PUT",url:`/editing-sessions/${e}`,body:n})}destroy(e){return this.rawDestroy(J(e)).then(n=>P(n))}rawDestroy(e){return this.client.request({method:"DELETE",url:`/editing-sessions/${e}`})}}wC.TYPE="editing_session";class TC extends xe{list(){return this.rawList().then(e=>P(e))}rawList(){return this.client.request({method:"GET",url:"/sso-groups"})}copyRoles(e){return this.rawCopyRoles(J(e)).then(n=>P(n))}rawCopyRoles(e){return this.client.request({method:"POST",url:`/sso-groups/${e}/copy-roles`})}update(e,n){return this.rawUpdate(J(e),he(n,{id:J(e),type:"sso_group",attributes:["priority"],relationships:["role"]})).then(i=>P(i))}rawUpdate(e,n){return this.client.request({method:"PUT",url:`/sso-groups/${e}`,body:n})}destroy(e){return this.rawDestroy(J(e)).then(n=>P(n))}rawDestroy(e){return this.client.request({method:"DELETE",url:`/sso-groups/${e}`})}}TC.TYPE="sso_group";class EC extends xe{find(){return this.rawFind().then(e=>P(e))}rawFind(){return this.client.request({method:"GET",url:"/sso-settings"})}generateToken(){return this.rawGenerateToken().then(e=>P(e))}rawGenerateToken(){return this.client.request({method:"PUT",url:"/sso-settings/generate-token"})}update(e){return this.rawUpdate(he(e,{type:"sso_settings",attributes:["idp_saml_metadata_url","idp_saml_metadata_xml"],relationships:["default_role"]})).then(n=>P(n))}rawUpdate(e){return this.client.request({method:"PUT",url:"/sso-settings",body:e})}}EC.TYPE="sso_settings";class RC extends xe{find(e){return this.rawFind(e).then(n=>P(n))}rawFind(e){return this.client.request({method:"GET",url:"/emoji-suggestions",queryParams:e})}}RC.TYPE="emoji_suggestions";class AC extends xe{find(){return this.rawFind().then(e=>P(e))}rawFind(){return this.client.request({method:"GET",url:"/white-label-settings"})}update(e){return this.rawUpdate(he(e,{type:"white_label_settings",attributes:["custom_i18n_messages_template_url"],relationships:[]})).then(n=>P(n))}rawUpdate(e){return this.client.request({method:"PUT",url:"/white-label-settings",body:e})}}AC.TYPE="white_label_settings";class CC extends xe{find(){return this.rawFind().then(e=>P(e))}rawFind(){return this.client.request({method:"GET",url:"/public-info"})}}CC.TYPE="public_info";class xC extends xe{list(){return this.rawList().then(e=>P(e))}rawList(){return this.client.request({method:"GET",url:"/daily-site-usages"})}}xC.TYPE="daily_usage";class MC extends xe{find(e,n){return this.rawFind(J(e),n).then(i=>P(i))}rawFind(e,n){return this.client.request({method:"GET",url:`/usage-log-counters/${e}`,queryParams:n})}}MC.TYPE="usage_counter";var v7=function(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],n;return e?e.call(t):(t=typeof __values=="function"?__values(t):t[Symbol.iterator](),n={},i("next"),i("throw"),i("return"),n[Symbol.asyncIterator]=function(){return this},n);function i(l){n[l]=t[l]&&function(u){return new Promise(function(d,f){u=t[l](u),r(d,f,u.done,u.value)})}}function r(l,u,d,f){Promise.resolve(f).then(function(h){l({value:h,done:d})},u)}},Hr=function(t){return this instanceof Hr?(this.v=t,this):new Hr(t)},b7=function(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=n.apply(t,e||[]),r,l=[];return r={},u("next"),u("throw"),u("return"),r[Symbol.asyncIterator]=function(){return this},r;function u(v){i[v]&&(r[v]=function(b){return new Promise(function(S,w){l.push([v,b,S,w])>1||d(v,b)})})}function d(v,b){try{f(i[v](b))}catch(S){p(l[0][3],S)}}function f(v){v.value instanceof Hr?Promise.resolve(v.value.v).then(h,g):p(l[0][2],v)}function h(v){d("next",v)}function g(v){d("throw",v)}function p(v,b){v(b),l.shift(),l.length&&d(l[0][0],l[0][1])}};class OC extends xe{list(e){return this.rawList(e).then(n=>P(n))}rawList(e){return this.client.request({method:"GET",url:"/upload-tags",queryParams:e})}listPagedIterator(e,n){return b7(this,arguments,function*(){var r,l,u,d;try{for(var f=!0,h=v7(this.rawListPagedIterator(e,n)),g;g=yield Hr(h.next()),r=g.done,!r;){d=g.value,f=!1;try{yield yield Hr(ia(d))}finally{f=!0}}}catch(p){l={error:p}}finally{try{!f&&!r&&(u=h.return)&&(yield Hr(u.call(h)))}finally{if(l)throw l.error}}})}rawListPagedIterator(e,n){return ai(e),ni({defaultLimit:50,maxLimit:500},i=>this.rawList(Object.assign(Object.assign({},e),{page:i})),n)}create(e){return this.rawCreate(he(e,{type:"upload_tag",attributes:["name"],relationships:[]})).then(n=>P(n))}rawCreate(e){return this.client.request({method:"POST",url:"/upload-tags",body:e})}}OC.TYPE="upload_tag";var S7=function(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],n;return e?e.call(t):(t=typeof __values=="function"?__values(t):t[Symbol.iterator](),n={},i("next"),i("throw"),i("return"),n[Symbol.asyncIterator]=function(){return this},n);function i(l){n[l]=t[l]&&function(u){return new Promise(function(d,f){u=t[l](u),r(d,f,u.done,u.value)})}}function r(l,u,d,f){Promise.resolve(f).then(function(h){l({value:h,done:d})},u)}},Yr=function(t){return this instanceof Yr?(this.v=t,this):new Yr(t)},_7=function(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=n.apply(t,e||[]),r,l=[];return r={},u("next"),u("throw"),u("return"),r[Symbol.asyncIterator]=function(){return this},r;function u(v){i[v]&&(r[v]=function(b){return new Promise(function(S,w){l.push([v,b,S,w])>1||d(v,b)})})}function d(v,b){try{f(i[v](b))}catch(S){p(l[0][3],S)}}function f(v){v.value instanceof Yr?Promise.resolve(v.value.v).then(h,g):p(l[0][2],v)}function h(v){d("next",v)}function g(v){d("throw",v)}function p(v,b){v(b),l.shift(),l.length&&d(l[0][0],l[0][1])}};class kC extends xe{list(e){return this.rawList(e).then(n=>P(n))}rawList(e){return this.client.request({method:"GET",url:"/upload-smart-tags",queryParams:e})}listPagedIterator(e,n){return _7(this,arguments,function*(){var r,l,u,d;try{for(var f=!0,h=S7(this.rawListPagedIterator(e,n)),g;g=yield Yr(h.next()),r=g.done,!r;){d=g.value,f=!1;try{yield yield Yr(ia(d))}finally{f=!0}}}catch(p){l={error:p}}finally{try{!f&&!r&&(u=h.return)&&(yield Yr(u.call(h)))}finally{if(l)throw l.error}}})}rawListPagedIterator(e,n){return ai(e),ni({defaultLimit:50,maxLimit:500},i=>this.rawList(Object.assign(Object.assign({},e),{page:i})),n)}}kC.TYPE="upload_smart_tag";class LC extends xe{find(e){return this.rawFind(e).then(n=>P(n))}rawFind(e){return this.client.request({method:"GET",url:"/site",queryParams:e})}update(e){return this.rawUpdate(he(e,{type:"site",attributes:["no_index","favicon","global_seo","name","theme","locales","timezone","require_2fa","ip_tracking_enabled","force_use_of_sandbox_environments"],relationships:["sso_default_role"]})).then(n=>P(n))}rawUpdate(e){return this.client.request({method:"PUT",url:"/site",body:e})}activateImprovedTimezoneManagement(){return this.rawActivateImprovedTimezoneManagement().then(e=>P(e))}rawActivateImprovedTimezoneManagement(){return this.client.request({method:"PUT",url:"/site/activate-improved-timezone-management"})}activateImprovedHexManagement(){return this.rawActivateImprovedHexManagement().then(e=>P(e))}rawActivateImprovedHexManagement(){return this.client.request({method:"PUT",url:"/site/activate-improved-hex-management"})}activateImprovedGqlMultilocaleFields(){return this.rawActivateImprovedGqlMultilocaleFields().then(e=>P(e))}rawActivateImprovedGqlMultilocaleFields(){return this.client.request({method:"PUT",url:"/site/activate-improved-gql-multilocale-fields"})}activateImprovedGqlVisibilityControl(){return this.rawActivateImprovedGqlVisibilityControl().then(e=>P(e))}rawActivateImprovedGqlVisibilityControl(){return this.client.request({method:"PUT",url:"/site/activate-improved-gql-visibility-control"})}activateImprovedBooleanFields(){return this.rawActivateImprovedBooleanFields().then(e=>P(e))}rawActivateImprovedBooleanFields(){return this.client.request({method:"PUT",url:"/site/activate-improved-boolean-fields"})}activateDraftModeAsDefault(){return this.rawActivateDraftModeAsDefault().then(e=>P(e))}rawActivateDraftModeAsDefault(){return this.client.request({method:"PUT",url:"/site/activate-draft-mode-as-default"})}activateImprovedValidationAtPublishing(){return this.rawActivateImprovedValidationAtPublishing().then(e=>P(e))}rawActivateImprovedValidationAtPublishing(){return this.client.request({method:"PUT",url:"/site/activate-improved-validation-at-publishing"})}activateImprovedExposureOfInlineBlocksInCda(){return this.rawActivateImprovedExposureOfInlineBlocksInCda().then(e=>P(e))}rawActivateImprovedExposureOfInlineBlocksInCda(){return this.client.request({method:"PUT",url:"/site/activate-improved-exposure-of-inline-blocks-in-cda"})}activateImprovedItemsListing(){return this.rawActivateImprovedItemsListing().then(e=>P(e))}rawActivateImprovedItemsListing(){return this.client.request({method:"PUT",url:"/site/activate-improved-items-listing"})}activateMillisecondsInDatetime(){return this.rawActivateMillisecondsInDatetime().then(e=>P(e))}rawActivateMillisecondsInDatetime(){return this.client.request({method:"PUT",url:"/site/activate-milliseconds-in-datetime"})}updateAssetsCdnDefaultSettings(e){return this.rawUpdateAssetsCdnDefaultSettings(he(e,{type:"assets-cdn-default-settings",attributes:["assets_cdn_default_settings"],relationships:[]})).then(n=>P(n))}rawUpdateAssetsCdnDefaultSettings(e){return this.client.request({method:"PUT",url:"/site/assets-cdn-default-settings",body:e})}}LC.TYPE="site";class DC extends xe{create(e){return this.rawCreate(he(e,{type:"workflow",attributes:["name","api_key","stages"],relationships:[]})).then(n=>P(n))}rawCreate(e){return this.client.request({method:"POST",url:"/workflows",body:e})}update(e,n){return this.rawUpdate(J(e),he(n,{id:J(e),type:"workflow",attributes:["name","api_key","stages"],relationships:[]})).then(i=>P(i))}rawUpdate(e,n){return this.client.request({method:"PUT",url:`/workflows/${e}`,body:n})}list(){return this.rawList().then(e=>P(e))}rawList(){return this.client.request({method:"GET",url:"/workflows"})}find(e){return this.rawFind(J(e)).then(n=>P(n))}rawFind(e){return this.client.request({method:"GET",url:`/workflows/${e}`})}destroy(e){return this.rawDestroy(J(e))}rawDestroy(e){return this.client.request({method:"DELETE",url:`/workflows/${e}`})}}DC.TYPE="workflow";var w7=function(t,e,n,i){function r(l){return l instanceof n?l:new n(function(u){u(l)})}return new(n||(n=Promise))(function(l,u){function d(g){try{h(i.next(g))}catch(p){u(p)}}function f(g){try{h(i.throw(g))}catch(p){u(p)}}function h(g){g.done?l(g.value):r(g.value).then(d,f)}h((i=i.apply(t,e||[])).next())})};let BC=class NC{constructor(e){this.config=e,this.roles=new a7(this),this.users=new $A(this),this.ssoUsers=new qA(this),this.auditLogEvents=new GA(this),this.menuItems=new KA(this),this.schemaMenuItems=new HA(this),this.uploadCollections=new YA(this),this.itemTypes=new XA(this),this.fields=new WA(this),this.fieldsets=new ZA(this),this.session=new JA(this),this.accessTokens=new QA(this),this.plugins=new eC(this),this.jobResults=new tC(this),this.subscriptionLimits=new nC(this),this.subscriptionFeatures=new aC(this),this.buildEvents=new iC(this),this.searchIndexEvents=new sC(this),this.items=new rC(this),this.itemVersions=new oC(this),this.uploads=new av(this),this.uploadRequest=new lC(this),this.uploadTracks=new uC(this),this.scheduledPublication=new cC(this),this.scheduledUnpublishing=new dC(this),this.searchResults=new fC(this),this.environments=new hC(this),this.maintenanceMode=new gC(this),this.webhooks=new mC(this),this.webhookCalls=new pC(this),this.buildTriggers=new yC(this),this.searchIndexes=new vC(this),this.itemTypeFilters=new bC(this),this.uploadFilters=new SC(this),this.siteInvitations=new _C(this),this.editingSessions=new wC(this),this.ssoGroups=new TC(this),this.ssoSettings=new EC(this),this.emojiSuggestions=new RC(this),this.whiteLabelSettings=new AC(this),this.publicInfo=new CC(this),this.dailyUsages=new xC(this),this.usageCounters=new MC(this),this.uploadTags=new OC(this),this.uploadSmartTags=new kC(this),this.site=new LC(this),this.workflows=new DC(this)}get baseUrl(){return this.config.baseUrl||NC.defaultBaseUrl}request(e){return ld(Object.assign(Object.assign(Object.assign({},this.config),e),{logFn:this.config.logFn||console.log,userAgent:"@datocms/cma-client v5.3.0",baseUrl:this.baseUrl,preCallStack:new Error().stack,extraHeaders:Object.assign(Object.assign(Object.assign({},this.config.extraHeaders||{}),this.config.environment?{"X-Environment":this.config.environment}:{}),{"X-API-Version":"3"}),fetchJobResult:n=>this.jobResultsFetcher?this.jobResultsFetcher(n):jG(()=>this.jobResults.find(n))}))}eventsChannelName(){return w7(this,void 0,void 0,function*(){if(this.cachedEventsChannelName)return this.cachedEventsChannelName;const{data:e}=yield this.site.rawFind();return this.cachedEventsChannelName=this.config.environment?`private-site-${e.id}-environment-${this.config.environment}`:`private-site-${e.id}`,this.cachedEventsChannelName})}};BC.defaultBaseUrl="https://site-api.datocms.com";function T7(t){const e="attributes"in t?t.attributes:t;switch(e.field_type){case"link":return e.validators.item_item_type.item_types;case"links":return e.validators.items_item_type.item_types;case"structured_text":return e.validators.structured_text_links.item_types;default:return[]}}function Om(t){const e="attributes"in t?t.attributes:t;switch(e.field_type){case"single_block":return e.validators.single_block_blocks.item_types;case"rich_text":return e.validators.rich_text_blocks.item_types;case"structured_text":return[...e.validators.structured_text_blocks.item_types,...e.validators.structured_text_inline_blocks?e.validators.structured_text_inline_blocks.item_types:[]];default:return[]}}var Ue=function(t,e,n,i){function r(l){return l instanceof n?l:new n(function(u){u(l)})}return new(n||(n=Promise))(function(l,u){function d(g){try{h(i.next(g))}catch(p){u(p)}}function f(g){try{h(i.throw(g))}catch(p){u(p)}}function h(g){g.done?l(g.value):r(g.value).then(d,f)}h((i=i.apply(t,e||[])).next())})};class E7{constructor(e){this.itemTypesPromise=null,this.itemTypesByApiKey=new Map,this.itemTypesById=new Map,this.fieldsByItemType=new Map,this.fieldsetsByItemType=new Map,this.pluginsPromise=null,this.pluginsById=new Map,this.pluginsByPackageName=new Map,this.prefetchPromise=null,this.client=e}loadItemTypes(){return Ue(this,void 0,void 0,function*(){return this.itemTypesPromise||(this.itemTypesPromise=Ue(this,void 0,void 0,function*(){const{data:e}=yield this.client.itemTypes.rawList();for(const n of e)this.itemTypesByApiKey.set(n.attributes.api_key,n),this.itemTypesById.set(n.id,n);return e})),this.itemTypesPromise})}getAllItemTypes(){return Ue(this,void 0,void 0,function*(){const e=yield this.getAllRawItemTypes();return P({data:e})})}getAllRawItemTypes(){return Ue(this,void 0,void 0,function*(){return yield this.loadItemTypes()})}getAllModels(){return Ue(this,void 0,void 0,function*(){const e=yield this.getAllRawModels();return P({data:e})})}getAllRawModels(){return Ue(this,void 0,void 0,function*(){return(yield this.loadItemTypes()).filter(n=>!n.attributes.modular_block)})}getAllBlockModels(){return Ue(this,void 0,void 0,function*(){const e=yield this.getAllRawBlockModels();return P({data:e})})}getAllRawBlockModels(){return Ue(this,void 0,void 0,function*(){return(yield this.loadItemTypes()).filter(n=>n.attributes.modular_block)})}getItemTypeByApiKey(e){return Ue(this,void 0,void 0,function*(){const n=yield this.getRawItemTypeByApiKey(e);return P({data:n})})}getRawItemTypeByApiKey(e){return Ue(this,void 0,void 0,function*(){yield this.loadItemTypes();const n=this.itemTypesByApiKey.get(e);if(!n)throw new Error(`Item type with API key '${e}' not found`);return n})}getItemTypeById(e){return Ue(this,void 0,void 0,function*(){const n=yield this.getRawItemTypeById(e);return P({data:n})})}getRawItemTypeById(e){return Ue(this,void 0,void 0,function*(){yield this.loadItemTypes();const n=this.itemTypesById.get(e);if(!n)throw new Error(`Item type with ID '${e}' not found`);return n})}getItemTypeFields(e){return Ue(this,void 0,void 0,function*(){const n=yield this.getRawItemTypeFields(e);return P({data:n})})}getRawItemTypeFields(e){return Ue(this,void 0,void 0,function*(){const n=this.fieldsByItemType.get(e.id);if(n)return n;const{data:i}=yield this.client.fields.rawList(e.id);return this.fieldsByItemType.set(e.id,i),i})}getItemTypeFieldsets(e){return Ue(this,void 0,void 0,function*(){const n=yield this.getRawItemTypeFieldsets(e);return P({data:n})})}getRawItemTypeFieldsets(e){return Ue(this,void 0,void 0,function*(){const n=this.fieldsetsByItemType.get(e.id);if(n)return n;const{data:i}=yield this.client.fieldsets.rawList(e.id);return this.fieldsetsByItemType.set(e.id,i),i})}loadPlugins(){return Ue(this,void 0,void 0,function*(){return this.pluginsPromise||(this.pluginsPromise=Ue(this,void 0,void 0,function*(){const{data:e}=yield this.client.plugins.rawList();for(const n of e)this.pluginsById.set(n.id,n),n.attributes.package_name&&this.pluginsByPackageName.set(n.attributes.package_name,n);return e})),this.pluginsPromise})}getAllPlugins(){return Ue(this,void 0,void 0,function*(){const e=yield this.getAllRawPlugins();return P({data:e})})}getAllRawPlugins(){return Ue(this,void 0,void 0,function*(){return yield this.loadPlugins()})}getPluginById(e){return Ue(this,void 0,void 0,function*(){const n=yield this.getRawPluginById(e);return P({data:n})})}getRawPluginById(e){return Ue(this,void 0,void 0,function*(){yield this.loadPlugins();const n=this.pluginsById.get(e);if(!n)throw new Error(`Plugin with ID '${e}' not found`);return n})}getPluginByPackageName(e){return Ue(this,void 0,void 0,function*(){const n=yield this.getRawPluginByPackageName(e);return P({data:n})})}getRawPluginByPackageName(e){return Ue(this,void 0,void 0,function*(){yield this.loadPlugins();const n=this.pluginsByPackageName.get(e);if(!n)throw new Error(`Plugin with package name '${e}' not found`);return n})}prefetchAllModelsAndFields(){return Ue(this,void 0,void 0,function*(){if(this.prefetchPromise)return this.prefetchPromise;const e=()=>Ue(this,void 0,void 0,function*(){const{included:n}=yield this.client.site.rawFind({include:"item_types,item_types.fields"});if(!n)return;const i=n.filter(u=>u.type==="item_type"),r=n.filter(u=>u.type==="field");this.itemTypesPromise=Promise.resolve(i);for(const u of i)this.itemTypesByApiKey.set(u.attributes.api_key,u),this.itemTypesById.set(u.id,u);const l=new Map;for(const u of r){const d=u.relationships.item_type.data.id;l.has(d)||l.set(d,[]),l.get(d).push(u)}for(const[u,d]of l)this.fieldsByItemType.set(u,d)});return this.prefetchPromise=e(),this.prefetchPromise})}getRawModelsEmbeddingBlocks(e){return Ue(this,void 0,void 0,function*(){yield this.prefetchAllModelsAndFields();const n=yield this.getAllRawItemTypes(),i=new Set(e.map(u=>u.id)),r=[],l=(u,d=new Set)=>Ue(this,void 0,void 0,function*(){if(d.has(u.id))return!1;d.add(u.id);const f=yield this.getRawItemTypeFields(u);for(const h of f){const g=Om(h);if(g.some(v=>i.has(v)))return!0;const p=g.map(v=>n.find(b=>b.id===v));for(const v of p)if(yield l(v,new Set(d)))return!0}return!1});for(const u of n)(yield l(u))&&r.push(u);return r})}getModelsEmbeddingBlocks(e){return Ue(this,void 0,void 0,function*(){const n=yield this.getRawModelsEmbeddingBlocks(e);return P({data:n})})}getRawNestedBlocks(e){return Ue(this,void 0,void 0,function*(){yield this.prefetchAllModelsAndFields();const n=yield this.getAllRawItemTypes(),i=new Set,r=[],l=(u,d=new Set)=>Ue(this,void 0,void 0,function*(){if(d.has(u.id))return;d.add(u.id);const f=yield this.getRawItemTypeFields(u);for(const h of f){const g=Om(h);for(const p of g)if(!i.has(p)){i.add(p);const v=n.find(b=>b.id===p);v&&(r.push(v),yield l(v,new Set(d)))}}});for(const u of e)yield l(u);return r})}getNestedBlocks(e){return Ue(this,void 0,void 0,function*(){const n=yield this.getRawNestedBlocks(e);return P({data:n})})}getRawNestedModels(e){return Ue(this,void 0,void 0,function*(){yield this.prefetchAllModelsAndFields();const n=yield this.getAllRawItemTypes(),i=new Set,r=[],l=(u,d=new Set)=>Ue(this,void 0,void 0,function*(){if(d.has(u.id))return;d.add(u.id);const f=yield this.getRawItemTypeFields(u);for(const h of f){const g=T7(h);for(const v of g)if(!i.has(v)){i.add(v);const b=n.find(S=>S.id===v);b&&r.push(b)}const p=Om(h);for(const v of p){const b=n.find(S=>S.id===v);b&&(yield l(b,new Set(d)))}}});for(const u of e)yield l(u);return r})}getNestedModels(e){return Ue(this,void 0,void 0,function*(){const n=yield this.getRawNestedModels(e);return P({data:n})})}}function R7(t,e,{onProgress:n,additionalHeaders:i}={}){const r=new XMLHttpRequest;return Il(new Promise((l,u)=>{if(n&&r.upload&&(r.upload.onprogress=d=>{d.lengthComputable&&n({type:"UPLOADING_FILE",payload:{progress:Math.round(d.loaded/d.total*100)}})}),r.onreadystatechange=()=>{r.readyState===4&&(r.status===200?l():u(new Error(`Status ${r.status}`)))},r.addEventListener("error",u,!1),r.open("PUT",e,!0),i)for(const[d,f]of Object.entries(i))r.setRequestHeader(d,f);r.send(t)}),()=>{r.onreadystatechange=null,r.abort()})}var A7=function(t,e,n,i){function r(l){return l instanceof n?l:new n(function(u){u(l)})}return new(n||(n=Promise))(function(l,u){function d(g){try{h(i.next(g))}catch(p){u(p)}}function f(g){try{h(i.throw(g))}catch(p){u(p)}}function h(g){g.done?l(g.value):r(g.value).then(d,f)}h((i=i.apply(t,e||[])).next())})};function Yw(t,e,n={}){const i=n.filename||("name"in e?e.name:void 0);if(!i)throw new Error("Missing filename, please provide it as an option!");let r=!1,l;return Il(()=>A7(this,void 0,void 0,function*(){n.onProgress&&n?.onProgress({type:"REQUESTING_UPLOAD_URL",payload:{filename:i}});const{id:u,url:d,request_headers:f}=yield t.uploadRequest.create({filename:i});if(r)throw new Nl;return n.onProgress&&n.onProgress({type:"UPLOADING_FILE",payload:{progress:0}}),l=R7(e,d,Object.assign(Object.assign({},n),{additionalHeaders:f})),yield l,u}),()=>{l?l.cancel():r=!0})}var Xw=function(t,e,n,i){function r(l){return l instanceof n?l:new n(function(u){u(l)})}return new(n||(n=Promise))(function(l,u){function d(g){try{h(i.next(g))}catch(p){u(p)}}function f(g){try{h(i.throw(g))}catch(p){u(p)}}function h(g){g.done?l(g.value):r(g.value).then(d,f)}h((i=i.apply(t,e||[])).next())})},Ww=function(t,e){var n={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(n[i]=t[i]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,i=Object.getOwnPropertySymbols(t);r<i.length;r++)e.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(t,i[r])&&(n[i[r]]=t[i[r]]);return n};class C7 extends av{createFromFileOrBlob(e){let n=!1,i;return Il(()=>Xw(this,void 0,void 0,function*(){if(n)throw new Nl;const{fileOrBlob:r,filename:l,onProgress:u}=e,d=Ww(e,["fileOrBlob","filename","onProgress"]);i=Yw(this.client,r,{filename:l,onProgress:u});const f=yield i;return u&&u({type:"CREATING_UPLOAD_OBJECT"}),this.create(Object.assign(Object.assign({},d),{path:f}))}),()=>{i?i.cancel():n=!0})}updateFromFileOrBlob(e,n){let i=!1,r;return Il(()=>Xw(this,void 0,void 0,function*(){if(i)throw new Nl;const{fileOrBlob:l,filename:u,onProgress:d}=n,f=Ww(n,["fileOrBlob","filename","onProgress"]);r=Yw(this.client,l,{filename:u,onProgress:d});const h=yield r;return d&&d({type:"CREATING_UPLOAD_OBJECT"}),this.update(e,Object.assign(Object.assign({},f),{path:h}))}),()=>{r?r.cancel():i=!0})}}class x7 extends BC{constructor(e){super(e),this.uploads=new C7(this)}}function Cf(t){return new x7(t)}function Ip(t,e,n){return Cf({apiToken:t,environment:e,baseUrl:n})}function M7(t){return new E7(t)}async function O7(t,e){const n=await t.getItemTypeById(e);return(await t.getItemTypeFields(n)).reduce((r,l)=>(r[l.api_key]={editor:l.appearance.editor,id:l.id,localized:l.localized,validators:l.validators},r),{})}async function k7(t,e){const n=await t.getItemTypeById(e);return(await t.getItemTypeFields(n)).reduce((r,l)=>(r[l.api_key]={editor:l.appearance.editor,id:l.id,isLocalized:l.localized,validators:l.validators},r),{})}const iv=[["provider","Translation provider error"],["datocms","DatoCMS error"],["plugin","Plugin error"]],wa=(t,...e)=>typeof t=="string"&&e.some(n=>t.toLowerCase().includes(n.toLowerCase()));function L7(t){const e=t.trim();for(const[n,i]of iv){const r=`${i}:`;if(e.startsWith(r))return{source:n,message:e.slice(r.length).trim()}}return{message:e}}function D7(t){return iv.some(([,e])=>t.trim().startsWith(`${e}:`))}function Zw(t){if(typeof t=="number"||typeof t=="string")return t}function B7(t){const e=Zw(t.status);if(e!==void 0)return e;const n=Zw(t.code);if(n!==void 0)return n;if(t.response&&typeof t.response=="object"){const i=t.response;if(typeof i.status=="number")return i.status}}function N7(t){if(G2(t)||n$(t))return t.status;if(t!==null&&typeof t=="object")return B7(t)}function I7(t){if(t instanceof Error)return t.message;if(t!==null&&typeof t=="object"){const e=t;if(typeof e.message=="string")return e.message;if(e.error&&typeof e.error=="object"){const n=e.error;if(typeof n.message=="string")return n.message}}return String(t||"Unknown error")}function Vd(t,e){let n=t;for(const i of e){if(n===null||typeof n!="object")return;n=n[i]}if(!(n===null||typeof n!="object"))return n}function IC(t){if(t===null||typeof t!="object")return[];const i=Vd(t,["response","body"])?.data;return Array.isArray(i)?i.filter(r=>r===null||typeof r!="object"?!1:r.type==="api_error"):[]}function P7(t){if(t===null||typeof t!="object")return null;const n=t.attributes;if(n===null||typeof n!="object")return null;const i=n.code;return typeof i=="string"?i:null}function j7(t){if(t===null||typeof t!="object")return!1;const e=t,n=Vd(e,["request"]),i=Vd(e,["response"]),r=n?.url;return!!n&&(!!i||IC(t).length>0||typeof r=="string")}function z7(t){return t.length===0?"":` (${t.join(", ")})`}function F7(t,e){if(!j7(t))return null;const i=Vd(t,["response"]),r=typeof i?.status=="number"?i.status:null,l=typeof i?.statusText=="string"?i.statusText:"",d=IC(t).map(P7).filter(g=>g!==null),f=z7(d);return d.includes("ITEM_LOCKED")?{source:"datocms",code:"datocms",message:"Cannot save translations because the record is locked for editing.",hint:"Close other tabs editing the record, wait for the lock to clear, then try again."}:r===401||r===403?{source:"datocms",code:"auth",message:`DatoCMS authorization failed${f}.`,hint:"Check the current user token permissions for this project."}:r===404?{source:"datocms",code:"datocms",message:`DatoCMS could not find the requested record or schema${f}.`,hint:"Refresh the page and try again."}:r===422?{source:"datocms",code:"datocms",message:`DatoCMS rejected the record update${f}.`,hint:"Check field validations, required locales, and record locks."}:r===429?{source:"datocms",code:"rate_limit",message:"DatoCMS rate limit reached while reading or saving records. Please wait and try again."}:wa(e,"timeout")?{source:"datocms",code:"network",message:"DatoCMS request timed out while reading or saving records. Please wait and try again."}:{source:"datocms",code:"datocms",message:`DatoCMS request failed${r===null?"":` (${r}${l?` ${l}`:""})`}${f}.`}}function U7(t){if(t!==null&&typeof t=="object"){const e=t;if(e.error&&typeof e.error=="object"){const n=e.error;return{code:typeof n.code=="string"?n.code:void 0,param:typeof n.param=="string"?n.param:void 0}}}return{}}function V7(t){return t==="openai"?"Reduce concurrency, switch to a more available model, or increase limits.":t==="google"?"Reduce request rate or increase quota in Google Cloud console.":t==="anthropic"?"Reduce request rate or increase Anthropic rate limits.":"Reduce concurrency or batch size; check DeepL plan limits."}function $7(t){return t==="openai"?"Check selected provider usage and billing; switch to a smaller model if needed.":t==="google"?"Verify Google project quotas and billing for Generative Language API.":t==="anthropic"?"Check Anthropic usage limits and billing.":"Check DeepL usage limits and plan."}function q7(t){return t==="openai"?"Ensure the model exists on your account and is spelled correctly.":t==="google"?"Ensure the Gemini model id is correct and available in your region.":t==="anthropic"?"Ensure the Claude model id is correct and you have access.":"Ensure the language pair is valid for DeepL; check target code."}function G7(t,e,n,i){if(t!=="openai")return!1;const r=i.code==="unsupported_value"||e===400,l=i.param==="stream"||wa(n,"stream");return r&&l&&wa(n,"must be verified to stream this model")}function K7(t,e,n){return t==="deepl"&&(e===403||wa(n,"wrong endpoint"))}function H7(t,e){return t==="datocms"?{source:"datocms",code:"datocms",message:e}:t==="plugin"?{source:"plugin",code:"plugin",message:e}:null}function Y7(t,e,n,i){return G7(t,e,n,i)?{source:"provider",code:"auth",message:n,hint:"Verify your organization with the provider or choose a different model."}:e===401||wa(n,"unauthorized","invalid api key","invalid authentication","not valid api key","permission_denied")?{source:"provider",code:"auth",message:"Authentication failed for the selected translation provider.",hint:t==="openai"?"Check the provider API key and organization access in settings.":"Check Google API key and that Generative Language API is enabled."}:e===429||wa(n,"rate limit","too many requests")?{source:"provider",code:"rate_limit",message:"Rate limit reached. Please wait and try again.",hint:V7(t)}:X7(t,e,n)}function X7(t,e,n){return wa(n,"insufficient_quota","quota exceeded","resource has been exhausted","out of quota")?{source:"provider",code:"quota",message:"Quota exceeded for the selected translation provider.",hint:$7(t)}:e===404||wa(n,"model not found","no such model","unsupported model","not found: model")?{source:"provider",code:"model",message:"The selected model is unavailable or not accessible.",hint:q7(t)}:wa(n,"failed to fetch","fetch failed","network","ecconn","enotfound","timeout")?{source:"provider",code:"network",message:n,hint:"This often indicates CORS/proxy issues or connectivity problems."}:K7(t,e,n)?{source:"provider",code:"auth",message:'DeepL: wrong endpoint for your API key. If your key ends with :fx, enable "Use DeepL Free endpoint (api-free.deepl.com)" in Settings. Otherwise, disable it to use api.deepl.com.',hint:"Match the endpoint to your plan: Free (:fx) → api-free.deepl.com; Pro → api.deepl.com."}:wa(n,"did not return a json array")?{source:"provider",code:"model",message:"The translation provider returned an unexpected response.",hint:"Please try again. If it continues, choose a different model."}:null}function ta(t,e){const n=N7(t),i=I7(t),r=F7(t,i);if(r)return r;const l=L7(i),u=U7(t),d=l.message,f=H7(l.source,d);if(f)return f;const h=Y7(e,n,d,u);return h||{source:l.source||(G2(t)||a$(t)?"provider":"plugin"),code:"unknown",message:d}}function na(t){const e=t.hint?`${t.message} ${t.hint}`:t.message;if(D7(e))return e;const n=iv.find(([i])=>i===t.source)?.[1];return n?`${n}: ${e}`:e}function Hl(t,e,n,i="Translation error"){const r=ta(t,e);throw n.error(i,{message:r.message,code:r.code,source:r.source,hint:r.hint}),new Error(na(r),{cause:t})}function sv(t,e,n,i){if(t instanceof Error&&t.name==="AbortError"){n.notice("Operation was cancelled");return}const r=ta(t,e??"openai");n.alert(na(r))}class W7{enabled;source;secrets=[];constructor(e,n){this.enabled=e.enableDebugging??!1,this.source=n;const i=[e.apiKey,e.googleApiKey,e.anthropicApiKey,e.deeplApiKey].filter(r=>typeof r=="string"&&r.length>0);this.secrets=i.filter(r=>typeof r=="string"&&r.length>=8)}redactString(e){let n=e;for(const i of this.secrets){if(!i)continue;const r=i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");n=n.replace(new RegExp(r,"g"),"[REDACTED]")}return n}isSensitiveKey(e){const n=e.toLowerCase().replace(/[_-]/g,"");return n==="fieldapikey"?!1:n==="apikey"||n.endsWith("apikey")||n.includes("authorization")||n==="token"||n.endsWith("token")||n.includes("secret")}sanitizeObjectEntry(e,n,i){return this.isSensitiveKey(e)?typeof n=="string"&&n.length>4?`${n.slice(0,3)}…[REDACTED]`:"[REDACTED]":typeof n=="string"?this.redactString(n):this.sanitize(n,i)}sanitizeArray(e,n){if(n.has(e))return"[Circular]";n.add(e);const i=e.map(r=>this.sanitize(r,n));return n.delete(e),i}sanitizeRecord(e,n){if(n.has(e))return"[Circular]";n.add(e);const i={};for(const[r,l]of Object.entries(e))i[r]=this.sanitizeObjectEntry(r,l,n);return n.delete(e),i}sanitize(e,n=new WeakSet){return typeof e=="string"?this.redactString(e):e==null?e:typeof e=="bigint"||typeof e=="symbol"?e.toString():typeof e=="function"?e.name?`[Function ${e.name}]`:"[Function]":e instanceof Date?e.toISOString():e instanceof Error?this.sanitizeError(e,n):Array.isArray(e)?this.sanitizeArray(e,n):typeof e=="object"?this.sanitizeRecord(e,n):e}sanitizeError(e,n){if(n.has(e))return"[Circular]";n.add(e);const i={name:this.redactString(e.name),message:this.redactString(e.message)};e.stack&&(i.stack=this.redactString(e.stack));const r=e.cause;r!==void 0&&(i.cause=this.sanitize(r,n));for(const[l,u]of Object.entries(e))i[l]=this.sanitizeObjectEntry(l,u,n);return n.delete(e),i}payloadToJson(e){return JSON.stringify(this.sanitize(e),null,2)}buildPayload(e,n,i){const r={timestamp:new Date().toISOString(),level:e,source:this.source,message:this.redactString(n)};return i&&(r[i.key]=i.payload),r}log(e,n,i){this.enabled&&console.log(this.payloadToJson(this.buildPayload(e,n,i===void 0?void 0:{key:"data",payload:i})))}info(e,n){this.log("INFO",e,n)}logPrompt(e,n){this.log("PROMPT",e,n)}logRequest(e,n){this.log("REQUEST",e,n)}logResponse(e,n){this.log("RESPONSE",e,n)}warning(e,n){this.log("WARNING",e,n)}error(e,n){console.error(this.payloadToJson(this.buildPayload("ERROR",e,n===void 0?void 0:{key:"error",payload:n})))}}function sa(t,e){return new W7(t,e)}const Z7=new Set(["DE","FR","IT","ES","NL","PL","PT-PT","PT-BR"]),J7=[["zh","ZH"],["pt-br","PT-BR"],["pt-pt","PT-PT"],["pt","PT-PT"],["en-us","EN-US"],["en-gb","EN-GB"],["en","EN"],["es","ES"],["fr","FR"],["it","IT"],["de","DE"],["nl","NL"],["pl","PL"],["ja","JA"],["ru","RU"]];function $d(t,e){if(!t)return"EN";const n=t.toLowerCase();for(const[r,l]of J7)if(n.startsWith(r)||n===r)return l;const i=n.split("-")[0].toUpperCase();return i.length===2?i:"EN"}function Q7(t){return Z7.has(t.toUpperCase())}function eK(t){const e={};if(!t)return e;const n=String(t).split(/\r?\n|[;,]+/).map(i=>i.trim()).filter(Boolean);for(const i of n){const r=i.match(/^(.*?)\s*(?:=|:|\s)\s*((?:gls-)?[A-Za-z0-9_-]+)\s*$/i);if(!r)continue;const l=r[1].replace(/\s/g,""),u=r[2];let d=l.replace(/–|—|→|⇒/g,"->");d.includes("->")||(d=`*->${d}`);const[f,h]=d.split(/->/);if(!f||!h)continue;const g=`${f}:${h}`.toUpperCase();e[g]=u}return e}function tK(t,e,n){const i=t?.deeplGlossaryId,r=t?.deeplGlossaryPairs;if(!r&&!i)return;const l=$d(n).toUpperCase(),u=e?$d(e).toUpperCase():"",d=`${u}:${l}`,f=eK(r);if(f[d])return f[d];if(e){const v=`${e}:${n}`.toUpperCase();if(f[v])return f[v]}const h=`*:${l}`;if(f[h])return f[h];const g=`*:${n.toUpperCase()}`;if(f[g])return f[g];if(u){const v=`${u}:*`;if(f[v])return f[v];const b=`${e?.toUpperCase()}:*`;if(f[b])return f[b]}if(!(Object.keys(f).length>0))return i}const km=25;function nK(t){return{request:(e,n)=>t.logRequest(e,n),response:(e,n)=>t.logResponse(e,n)}}function aK(t){const e=[/\{\{[^}]+\}\}/g,/\{[\w.-]+\}/g,/%[0-9]*\$?[sd]/g,/:[a-zA-Z_][a-zA-Z0-9_-]*/g],n=[];let i=t,r=0;for(const l of e)i=i.replace(l,u=>{const d=`⟦PH_${r++}⟧`;return n.push({safe:d,orig:u}),d});return{safe:i,map:n}}function iK(t,e){let n=t;for(const{safe:i,orig:r}of e)n=n.split(i).join(r);return n}function sK(t,e,n){const i=t.indexOf("["),r=t.lastIndexOf("]");if(i<0||r<=i)return e.warning("Response repair skipped",{...n,reason:"missing-array-brackets",rawResponse:t}),null;try{const l=JSON.parse(t.slice(i,r+1));if(Array.isArray(l))return e.info("Response repaired by extracting array brackets",{...n,rawResponse:t,extractedRange:[i,r],repairedArray:l}),l}catch(l){e.warning("Response repair failed",{...n,originalLength:t.length,extractedRange:[i,r],rawResponse:t,error:l})}return null}function rK(t,e,n){if(t.length===0)return e.warning("Response was empty; falling back by length repair",{...n,rawResponse:t}),{array:[],repaired:!1};try{const r=JSON.parse(t);if(Array.isArray(r))return e.info("Parsed response array",{...n,rawResponse:t,parsedArray:r}),{array:r,repaired:!1};e.warning("Parsed response was not an array",{...n,rawResponse:t,parsed:r})}catch(r){e.warning("Response JSON parse failed",{...n,rawResponse:t,error:r})}const i=sK(t,e,n);if(i)return e.info("Parsed response array after repair",{...n,rawResponse:t,repairedArray:i,repairedLength:i.length}),{array:i,repaired:!0,repairedArray:i};throw new Error("Model did not return a JSON array")}function Jw(t,e,n,i){const r=(t||"").trim(),l=rK(r,n,i),u=l.array,d=[];for(let f=0;f<e.length;f++){const h=u[f];d.push(typeof h=="string"?h:String(e[f]??""))}return n.info("Final parsed response array",{...i,rawResponse:t,parsedArray:u,repaired:l.repaired,repairedArray:l.repairedArray,originalSegments:e,finalArray:d}),d}async function oK(t,e,n,i,r,l,u,d){const f=$d(r),h=i?$d(i):void 0,g=l.formality&&Q7(f)?l.formality:void 0,p={sourceLang:h,targetLang:f,isHTML:!!l.isHTML,formality:g,preserveFormatting:e?.deeplPreserveFormatting!==!1,ignoreTags:["notranslate","ph"],nonSplittingTags:["a","code","pre","strong","em","ph","notranslate"],splittingTags:[],glossaryId:tK(e,i,r),originalSourceLocale:i,originalTargetLocale:r,debug:d};u.logRequest("Native batch translation request",{provider:t.vendor,fromLocale:i,toLocale:r,segments:n,options:p});const v=await t.translateArray(n,p);return u.logResponse("Native batch translation response",{provider:t.vendor,fromLocale:i,toLocale:r,responseArray:v}),v}async function lK(t,e,n,i,r,l){const u=`Translate the following array of strings from ${n} to ${i}. Return ONLY a valid JSON array of the exact same length, preserving placeholders like {foo}, {{bar}}, and tokens like ⟦PH_0⟧. You may encounter ICU Message Format strings (e.g., {gender, select, male {He said} female {She said}}). You MUST preserve the structure, keywords, and variable keys exactly. ONLY translate the human-readable content inside the brackets. Do not explain.`;if(e.length<=km){const h=`${u}
|
|
76
76
|
${JSON.stringify(e)}`;r.logPrompt("Prompt request",h),r.logRequest("Provider text request input",{provider:t.vendor,fromLocale:n,toLocale:i,chunkStart:0,chunkSize:e.length,prompt:h,protectedSegments:e});const g=await t.completeText(h,{debug:l});return r.logResponse("Raw provider response",{provider:t.vendor,fromLocale:n,toLocale:i,chunkStart:0,chunkSize:e.length,rawResponse:g}),Jw(g,e,r,{provider:t.vendor,fromLocale:n,toLocale:i,chunkStart:0,chunkSize:e.length})}const d=async h=>{const g=e.slice(h,h+km),p=`${u}
|
|
77
|
-
${JSON.stringify(g)}`;r.logPrompt("Prompt request",p),r.logRequest("Provider text request input",{provider:t.vendor,fromLocale:n,toLocale:i,chunkStart:h,chunkSize:g.length,prompt:p,protectedSegments:g});const v=await t.completeText(p,{debug:l});return r.logResponse("Raw provider response",{provider:t.vendor,fromLocale:n,toLocale:i,chunkStart:h,chunkSize:g.length,rawResponse:v}),Jw(v,g,r,{provider:t.vendor,fromLocale:n,toLocale:i,chunkStart:h,chunkSize:g.length})},f=[];for(let h=0;h<e.length;h+=km)f.push(h);return f.reduce(async(h,g)=>{const p=await h,v=await d(g);return[...p,...v]},Promise.resolve([]))}async function xf(t,e,n,i,r,l={}){if(!Array.isArray(n)||n.length===0)return n;const u=sa(e,"translateArray"),d=nK(u),f=[],h=n.map(g=>{const{safe:p,map:v}=aK(String(g??""));return f.push(v),p});u.info("Translation batch payload",{provider:t.vendor,fromLocale:i,toLocale:r,options:l,originalSegments:n,protectedSegments:h,tokenMaps:f});try{let g;t.translateArray?g=await oK(t,e,h,i,r,l,u,d):g=await lK(t,h,i,r,u,d);const p=g.map((v,b)=>{const S=f[b]??[];return iK(String(v??""),S)});return u.info("Translation batch output",{provider:t.vendor,fromLocale:i,toLocale:r,translatedSegments:g,finalSegments:p,tokenMaps:f}),p}catch(g){const p=ta(g,t.vendor);throw new Error(na(p),{cause:g})}}async function uK(t,e,n,i,r,l,u=""){if(t==null||t==="")return t;const
|
|
78
|
-
${l}`;f.info("Formatted prompt prepared for translation"),f.logPrompt("SEO translation prompt",S);const[w,T]=await xf(r,e,[h,g],i,n,{isHTML:!1,recordContext:d}),E={...t};let C=w||h;C.length>Lm&&(f.info(`SEO title exceeds ${Lm} character limit (${C.length}). Truncating...`),C=`${C.substring(0,Lm-nT)}...`);let O=T||g;return O.length>Dm&&(f.info(`SEO description exceeds ${Dm} character limit (${O.length}). Truncating...`),O=`${O.substring(0,Dm-nT)}...`),E.title=C,E.description=O,f.info("SEO translation completed successfully"),E}catch(p){Hl(p,r.vendor,f,"SEO translation error")}}function SK(t){if(Array.isArray(t))return t;if(t&&typeof t=="object"){const e=t.document;if(e&&typeof e=="object"){const n=e.children;if(Array.isArray(n))return n}}return null}function _K(t){const e=typeof t.type=="string"?t.type:void 0;return typeof t.text=="string"&&t.text.trim().length>0||e==="span"&&typeof t.value=="string"&&t.value.trim().length>0}function Pp(t,e){if(e.hasVisibleText||e.hasBlocks)return;if(Array.isArray(t)){for(const r of t)Pp(r,e);return}if(!t||typeof t!="object")return;const n=t;if((typeof n.type=="string"?n.type:void 0)==="block"){e.hasBlocks=!0;return}if(_K(n)){e.hasVisibleText=!0;return}if(Array.isArray(n.children))for(const r of n.children)Pp(r,e)}function jp(t){const e=SK(t);if(!e)return!1;if(e.length===0)return!0;const n={hasVisibleText:!1,hasBlocks:!1};return Pp(e,n),!n.hasVisibleText&&!n.hasBlocks}function zp(t){if(Array.isArray(t))return t.map(zp);if(typeof t=="object"&&t!==null){const e={};for(const[n,i]of Object.entries(t)){if(n==="data"){e[n]=i;continue}n==="id"&&t.value!==void 0&&Object.keys(t).length===2?e[n]=i:n!=="id"&&(e[n]=zp(i))}return e}return t}function wK(t,e,n){return[...t.slice(0,n),e,...t.slice(n)]}function TK(t){if(t===null||typeof t!="object")return!1;const e=t;if(!e.document||typeof e.document!="object")return!1;const n=e.document;return Array.isArray(n.children)&&n.children.length>0}const EK=/^[\s\u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]+$/;function qd(t){return t===""||EK.test(t)}function RK(t){return t?{bypassFieldTypeAllowlist:!0,cmaBaseUrl:t}:{bypassFieldTypeAllowlist:!0}}function Fp(t){return Array.isArray(t)?t.map(e=>Fp(e)):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).map(([e,n])=>[e,Fp(n)])):t}function Up(t,e=[]){if(Array.isArray(t))return t.flatMap((r,l)=>Up(r,[...e,l]));if(!t||typeof t!="object")return[];const n=t,i=typeof n.type=="string"?n.type:void 0;return typeof n.text=="string"?[{path:[...e,"text"],value:n.text}]:i==="span"&&typeof n.value=="string"?[{path:[...e,"value"],value:n.value}]:i==="block"?[]:Array.isArray(n.children)?Up(n.children,[...e,"children"]):[]}function AK(t,e,n){let i=t;for(let r=0;r<e.length-1;r++){if(i===null||typeof i!="object")return;i=i[e[r]]}i!==null&&typeof i=="object"&&(i[e[e.length-1]]=n)}function CK(t,e,n){const i=Fp(t);return e.forEach((r,l)=>{const u=n[l];u!==void 0&&AK(i,r.path,u)}),i}function xK(t,e){return t.length===e.length?e:e.length<t.length?[...e,...t.slice(e.length)]:e.slice(0,t.length)}function MK(t,e){const n=new Array(e.length);for(let i=0;i<e.length;i++){const r=String(t[i]??""),l=String(e[i]??"");if(qd(r)){n[i]=r;continue}const u=(r.match(/^\s+/)||[""])[0],d=(r.match(/\s+$/)||[""])[0];let f=l;u&&!/^\s/.test(f)&&(f=`${u}${f}`),d&&!/\s$/.test(f)&&(f=`${f}${d}`),n[i]=f}return n}function OK(t,e){const n=[];let i=0;for(let r=0;r<t.length;r++){const l=String(t[r]??"");if(qd(l))n.push(l);else{const u=i<e.length?String(e[i++]):l;n.push(u)}}return n}function kK(t,e){const n=e.slice();for(let i=0;i<t.length-1;i++){const r=String(t[i]??""),l=String(t[i+1]??"");if(qd(r)||qd(l)||!(/[\s\u00A0]$/.test(r)||/^[\s\u00A0]/.test(l)))continue;const d=String(n[i]??""),f=String(n[i+1]??""),h=/[\s\u00A0]$/.test(d),g=/^[\s\u00A0]/.test(f);!h&&!g&&(n[i]=`${d} `)}return n}function LK(t,e){const n=e.slice();for(let i=0;i<t.length-1;i++){const r=String(t[i]??""),l=String(t[i+1]??""),u=/[.,;:!?]$/.test(r.trimEnd()),d=/^[.,;:!?]/.test(l.trimStart());if(!u&&!d)continue;const f=String(n[i]??""),h=String(n[i+1]??""),g=/[\s\u00A0]$/.test(f)||/^[\s\u00A0]/.test(h),p=/[.,;:!?]$/.test(f)||/^[.,;:!?]/.test(h);!g&&!p&&(n[i]=`${f} `)}return n}async function DK({provider:t,pluginParams:e,textValues:n,textLeaves:i,fieldValueWithoutBlocks:r,fromLocale:l,toLocale:u,recordContext:d,logger:f}){const h=await xf(t,e,n,l,u,{isHTML:!1,recordContext:d});let g=h;return h.length!==n.length&&(f.warning(`Translation mismatch: got ${h.length} values, expected ${n.length}`,{original:n,translated:h}),g=OK(n,h),g.length!==n.length&&(g=xK(n,g)),f.info("Adjusted translated values to match original length",{adjustedLength:g.length})),g=MK(n,g),g=kK(n,g),g=LK(n,g),CK(r,i,g)}function BK({logger:t,textValues:e,textLeaves:n,blockNodeCount:i,fromLocale:r,toLocale:l}){if(e.length>0){t.info(`Found ${e.length} text nodes to translate`),t.info("Structured text inline source payload",{fromLocale:r,toLocale:l,textLeaves:n,textValues:e});return}t.info("No inline text values found; translating block nodes only",{fromLocale:r,toLocale:l,blockNodeCount:i})}async function NK(t,e,n,i,r,l,u,d,f="",h,g){const p=sa(e,"StructuredTextTranslation");let v=t,b=!1;if(TK(t)&&(v=t.document.children,b=!0),p.info("Structured text source payload",{fromLocale:i,toLocale:n,isAPIResponse:b,value:t,workingValue:v}),!v||!Array.isArray(v)||v.length===0)return p.info("Invalid structured text value",v),v;p.info("Translating structured text field",{nodeCount:v.length});const S=zp(v),w=S.reduce((O,L,M)=>(L?.type==="block"&&O.push({...L,originalIndex:M}),O),[]),T=S.filter(O=>O?.type!=="block"),E=Up(T),C=E.map(O=>O.value);if(C.length===0&&w.length===0)return p.info("No text values or block nodes found to translate"),v;BK({logger:p,textValues:C,textLeaves:E,blockNodeCount:w.length,fromLocale:i,toLocale:n});try{let O=T;if(C.length>0&&(O=await DK({provider:r,pluginParams:e,textValues:C,textLeaves:E,fieldValueWithoutBlocks:T,fromLocale:i,toLocale:n,recordContext:f,logger:p})),w.length>0){p.info(`Translating ${w.length} block nodes`,{fromLocale:i,toLocale:n,blockNodes:w});const M=await Yl(w,e,n,i,"rich_text",r,"",l,"",u,d,f,h,RK(g));p.info("Structured text translated block payload",{fromLocale:i,toLocale:n,translatedBlockNodes:M});for(const N of M)N.originalIndex!==void 0&&(O=wK(O,N,N.originalIndex))}const L=O.map(({originalIndex:M,...N})=>N);if(b){const M={document:{children:L,type:"root"},schema:"dast"};return p.info("Structured text translated payload",{fromLocale:i,toLocale:n,value:M}),M}return p.info("Successfully translated structured text",{fromLocale:i,toLocale:n,value:L}),L}catch(O){Hl(O,r.vendor,p,"Error during structured text translation")}}function IK(t){return t.item!==void 0&&typeof t.item=="object"&&t.item!==null&&"attributes"in t.item&&typeof t.item.attributes=="object"}function PK(t){if(t.itemTypeId)return String(t.itemTypeId);if(t.blockModelId)return String(t.blockModelId);const e=t.relationships?.item_type?.data?.id;if(e)return e;const n=t.item?.relationships?.item_type?.data?.id;if(n)return n}class jK extends Error{constructor(){super("Operation cancelled"),this.name="CancellationError"}}function Gd(t){return Array.isArray(t)?t.map(e=>Gd(e)):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).map(([e,n])=>[e,Gd(n)])):t}function zK(t){const e=Gd(t),n=e;return delete n.id,delete n.itemId,n.item&&typeof n.item=="object"&&(delete n.item.id,delete n.item.itemId),e}async function FK(t,e,n){const i=t.map((g,p)=>({index:p,completed:!1}));let r=0,l=!1;async function u(){if(l||r>=t.length)return;const g=r++;try{n?.()}catch{l=!0;return}try{const p=await t[g]();i[g]={index:g,result:p,completed:!0}}catch(p){if(p instanceof jK){l=!0;return}throw p}return u()}const d=()=>u(),f=Math.min(e,t.length),h=Array(f).fill(null).map(()=>d());return await Promise.all(h),i}async function Yl(t,e,n,i,r,l,u,d,f,h,g,p="",v,b={}){const S=sa(e,"translateFieldValue");if(S.info(`Translating field of type: ${r}`,{fromLocale:i,toLocale:n}),S.info("Source field payload",{fieldType:r,fieldId:f,fieldApiKey:b.fieldApiKey,fromLocale:i,toLocale:n,recordContext:p,value:t}),gf(e.apiKeysToBeExcludedFromThisPlugin,[f,b.fieldApiKey]))return S.info("Skipping field translation",{reason:"excluded",fieldType:r,fieldId:f,fieldApiKey:b.fieldApiKey,fromLocale:i,toLocale:n,value:t}),t;if(!hf(r,e.translationFields,df)&&!b.bypassFieldTypeAllowlist||!t)return S.info("Skipping field translation",{reason:t?"field-type-not-enabled":"empty-value",fieldType:r,fieldId:f,fieldApiKey:b.fieldApiKey,fromLocale:i,toLocale:n,value:t}),t;let T;switch(r){case"seo":T=await bK(t,e,n,i,l,u,g,p);break;case"structured_text":T=await NK(t,e,n,i,l,d,h,g,p,v,b.cmaBaseUrl);break;case"rich_text":case"framed_single_block":case"frameless_single_block":T=await XK(t,e,n,i,l,d,r,h,g,p,v,b.cmaBaseUrl);break;case"file":case"gallery":T=await dK(t,e,n,i,l,d,h,g,p,b.cmaBaseUrl);break;default:T=await uK(t,e,n,i,l,g,p);break}if(r==="slug"){const E=JV(T);if(!E)throw new Error("Translated slug is empty after normalization");return S.info("Translated field payload",{fieldType:r,fieldId:f,fieldApiKey:b.fieldApiKey,fromLocale:i,toLocale:n,value:E}),E}return S.info("Translated field payload",{fieldType:r,fieldId:f,fieldApiKey:b.fieldApiKey,fromLocale:i,toLocale:n,value:T}),T}const UK=100,VK=3,Lr=new Map;function $K(t,e){if(Lr.size>=UK){const n=Lr.keys().next().value;n&&Lr.delete(n)}Lr.set(t,e)}async function Vp(t,e,n,i,r){if(i)return O7(i,n);const l=`${r??""}:${e}:${n}`,u=Lr.get(l);if(u)return u;const d=(async()=>(await Cf({apiToken:t,environment:e,baseUrl:r}).fields.list(n)).reduce((g,p)=>(g[p.api_key]={editor:p.appearance.editor,id:p.id,localized:p.localized,validators:p.validators},g),{}))();$K(l,d);try{return await d}catch(f){throw Lr.delete(l),f}}const qK=["itemTypeId","originalIndex","blockModelId","type","children","relationships","attributes"];function PC(t){if(!t||typeof t!="object")return;const n=t.single_block_blocks;if(!n||typeof n!="object")return;const i=n.item_types;if(!(!Array.isArray(i)||i.length===0))return String(i[0])}function GK(t,e){return ff(t,e)??e}async function KK(t,e,n){if(!t||typeof t!="object"||Array.isArray(t))return t;const i=PC(e?.validators);if(!i)return n.logger.warning("Frameless single block missing item type validators",e),t;const r=await Vp(n.apiToken,n.environment,i,n.schemaRepository,n.cmaBaseUrl),l=Gd(t);return delete l.id,delete l.itemId,await jC(l,r,n),l}function HK(t,e,n,i){if(!e||!t||typeof t!="object"||Array.isArray(t))return{valueToTranslate:t,localizedContainer:null,targetLocaleKey:null,skip:!1};const r=Wr(t,n);if(r==null||r==="")return{valueToTranslate:t,localizedContainer:null,targetLocaleKey:null,skip:!0};const l={...t},u=GK(l,i);return{valueToTranslate:r,localizedContainer:l,targetLocaleKey:u,skip:!1}}async function YK(t,e,n,i){const r=e?.editor||"text";if(r==="frameless_single_block")return KK(n,e,i);const l=" Return the response in the format of "+(xy[r]||"");return Yl(n,i.pluginParams,i.toLocale,i.fromLocale,r,i.provider,l,i.apiToken,e?.id||"",i.environment,i.streamCallbacks,i.recordContext,i.schemaRepository,{fieldApiKey:t,cmaBaseUrl:i.cmaBaseUrl})}async function jC(t,e,n){const i=[];for(const d of Object.keys(t)){if(qK.includes(d)){n.logger.info("Block field skipped",{fieldKey:d,reason:"metadata-field",value:t[d]});continue}i.push(d)}if(i.length===0){n.logger.info("Block processing skipped",{reason:"no-translatable-fields",source:t});return}const r=i.map(d=>async()=>{n.streamCallbacks?.onStream?.(`Translating block field: ${d}...`);const f=e[d],h=f?.localized===!0,g=f?.editor||"text";n.logger.info("Block field source payload",{fieldKey:d,fieldId:f?.id,editor:g,localized:h,fromLocale:n.fromLocale,toLocale:n.toLocale,value:t[d]});const p=HK(t[d],h,n.fromLocale,n.toLocale);if(p.skip)return n.logger.info("Block field skipped",{fieldKey:d,fieldId:f?.id,editor:g,localized:h,reason:"missing-source-locale-value",fromLocale:n.fromLocale,toLocale:n.toLocale,value:t[d]}),{field:d,value:t[d]};n.logger.info("Block field translation input",{fieldKey:d,fieldId:f?.id,editor:g,localized:h,fromLocale:n.fromLocale,toLocale:n.toLocale,value:p.valueToTranslate});const v=await YK(d,f,p.valueToTranslate,n);return p.localizedContainer&&p.targetLocaleKey?(p.localizedContainer[p.targetLocaleKey]=v,n.logger.info("Block field translated payload",{fieldKey:d,fieldId:f?.id,editor:g,localized:h,targetLocaleKey:p.targetLocaleKey,fromLocale:n.fromLocale,toLocale:n.toLocale,translatedValue:v,writtenValue:p.localizedContainer}),{field:d,value:p.localizedContainer}):(n.logger.info("Block field translated payload",{fieldKey:d,fieldId:f?.id,editor:g,localized:h,fromLocale:n.fromLocale,toLocale:n.toLocale,translatedValue:v,writtenValue:v}),{field:d,value:v})}),l=await FK(r,VK,n.streamCallbacks?.checkCancellation);for(const d of l)d.completed&&d.result&&(t[d.result.field]=d.result.value);const u=l.filter(d=>d.completed).length;u<i.length&&n.logger.info(`Translation cancelled: ${u}/${i.length} fields translated`)}async function XK(t,e,n,i,r,l,u,d,f,h="",g,p){const v=sa(e,"translateBlockValue");v.info("Translating block value",{fieldType:u,fromLocale:i,toLocale:n,value:t});const b=u==="framed_single_block"||u==="frameless_single_block",S=b?[t]:t,w=S.map(zK);v.info("Block payload before processing",{fieldType:u,fromLocale:i,toLocale:n,rawBlocks:S,cleanedFieldValue:w});const T={pluginParams:e,toLocale:n,fromLocale:i,provider:r,apiToken:l,environment:d,cmaBaseUrl:p,streamCallbacks:f,recordContext:h,logger:v,schemaRepository:g};async function E(L,M,N,D,j){if(L in N)return;const K=PC(M.validators);if(!K){v.warning("Frameless single block missing validators",{fieldKey:L,blockModelId:D});return}const X=await Vp(l,d,K,g,p);for(const[z,ee]of Object.entries(X))z in j||(j[z]=ee)}async function C(L){const M=PK(L);if(!M){v.warning("Block model ID not found",L);return}v.info("Block processing started",{blockModelId:M,block:L});const N=await Vp(l,d,M,g,p),D=L.attributes?L.attributes:IK(L)?L.item.attributes:L;let j=N;const K=Object.entries(N).filter(([,X])=>X.editor==="frameless_single_block");if(K.length>0){const X={...N};await K.reduce(async(z,[ee,ne])=>{await z,await E(ee,ne,D,M,X)},Promise.resolve()),j=X}await jC(D,j,T),v.info("Block processing completed",{blockModelId:M,block:L,sourceObject:D})}await w.reduce((L,M)=>L.then(()=>C(M)),Promise.resolve());const O=b?w[0]:w;return v.info("Block translation completed",{fieldType:u,fromLocale:i,toLocale:n,value:O}),O}async function Bm(t,e,n,i,r,l,u,d,f=""){const h=await e.currentUserAccessToken,g=jr(n),p=sa(n,"TranslateField");try{p.info("Starting field translation",{fieldType:l,fromLocale:r,toLocale:i});const v=e.formValues&&!f?rv(e.formValues,r):f;d?.onStream;const b=e.field.attributes.api_key??"",S=e.field.id??e.fieldPath??"";p.info("Dropdown source payload",{fieldType:l,fieldId:S,fieldApiKey:b,fieldPath:e.fieldPath,fromLocale:r,toLocale:i,value:t});let w="Return the response in the format of ";const T=xy;l!=="structured_text"&&l!=="rich_text"&&(w+=(T||{})[l]||"");const C=await Yl(t,n,i,r,l,g,w,h,S,u,d,v,void 0,{fieldApiKey:b,cmaBaseUrl:e.cmaBaseUrl});return p.info("Dropdown translated payload",{fieldType:l,fieldId:S,fieldApiKey:b,fieldPath:e.fieldPath,fromLocale:r,toLocale:i,value:C}),p.info("Field translation completed"),C}catch(v){Hl(v,g.vendor,p,"Translation failed")}}const WK=["title","name","content","description"];function ZK(t){const e=t.toLowerCase();return WK.some(n=>e.includes(n))}function JK(t,e){if(typeof t!="object"||t===null)return null;const i=t[e];return typeof i!="string"||!i||i.length>=300?null:i}function rv(t,e){if(!t)return"";let n="Content context: ",i=!1;for(const r in t){if(!ZK(r))continue;const l=JK(t[r],e);l&&(n+=`${r}: ${l}. `,i=!0)}return i?n:""}const aT=64,QK=15,iT=3e5,eH=33,sT=10,tH=1e3,nH=1e4,aH=50,iH=200;function zC(t,e,n,i){const r=hf(t,n.translationFields,df),l=gf(n.apiKeysToBeExcludedFromThisPlugin,[e,i]);return r&&!l}function ov(t,e){return e==null||e===""?!1:t==="structured_text"?!jp(e):!(Array.isArray(e)&&e.length===0)}function sH(t){const e=t.vendor??"openai",n=e==="google"?String(t.geminiModel??"").toLowerCase():String(t.gptModel??"").toLowerCase();return e==="google"?/(^|[-])nano\b/.test(n)||/flash|lite/.test(n)?3:(/pro/.test(n),2):/(^|[-])nano\b/.test(n)||/flash|mini|lite/.test(n)?6:/mini/.test(n)||/1\.5/.test(n)?5:/pro/.test(n)?3:4}function rH(t){return(t.vendor??"openai")==="google"?iH:aH}function oH(t){const e=tH*2**(t-1);return Math.min(e,nH)}function lH(t){if(t===null||typeof t!="object")return!1;const e=t;return e?.status===429||e?.code==="rate_limit_exceeded"||/\b429\b|rate limit|Too Many Requests/i.test(String(e?.message??""))}function uH(t){return t instanceof DOMException&&t.name==="AbortError"}function rT(t){return new Promise(e=>setTimeout(e,t))}const cH=["title","name","headline","heading","label","internal_name","internalName","slug"];function dH(t,e){const n=Wr(t,e);if(typeof n=="string"&&n.trim())return n;for(const i of Object.values(t))if(typeof i=="string"&&i.trim())return i;return null}function fH(t,e){return t==null?null:typeof t=="string"?t:typeof t=="number"?String(t):Array.isArray(t)?t.filter(n=>typeof n=="string")[0]??null:typeof t=="object"?dH(t,e):null}function hH(t,e){for(const n of cH)if(t[n]!==void 0){const i=fH(t[n],e);if(i?.trim()){const r=i.trim();return r.length>80?`${r.slice(0,77)}…`:r}}return`Record ${t.id}`}async function gH(t,e){const n=[],r=e.join(",");async function l(u){const d=await t.items.list({filter:{ids:r},nested:!0,version:"current",page:{offset:(u-1)*30,limit:30}});n.push(...d),d.length===30&&await l(u+1)}return await l(1),n}function FC(t,e){if(!t||typeof t!="object")return!1;const n=e.toLowerCase();for(const i in t)if(i.toLowerCase()===n)return!0;return Object.values(t).some(i=>typeof i=="object"&&i!==null?FC(i,e):!1)}function mH(t){if(t===null||typeof t!="object")return;const e=t;return Nm(e,["response","data","errors"])||Nm(e,["response","errors"])||Nm(e,["data","errors"])||(Array.isArray(e.errors)?e.errors:void 0)}function Nm(t,e){let n=t;for(const i of e){if(n===null||typeof n!="object")return;n=n[i]}return Array.isArray(n)?n:void 0}function pH(t){if(t===null||typeof t!="object")return null;const e=t;if(e.attributes&&typeof e.attributes=="object"){const n=e.attributes;if(typeof n.code=="string")return n.code}return typeof e.code=="string"?e.code:null}function yH(t){if(t instanceof Error)return t.message;if(t!==null&&typeof t=="object"){const e=t;if(typeof e.message=="string")return e.message}}function vH(t,e){try{const n=mH(t);if(Array.isArray(n)&&n.map(pH).includes("ITEM_LOCKED"))return`DatoCMS error: Cannot save translations for record ${e}: the record is locked because it is being edited. Please ensure no one (including you in another tab) is editing the record in DatoCMS, then try again.`;if(yH(t)?.includes("ITEM_LOCKED"))return`DatoCMS error: Cannot save translations for record ${e}: the record is locked because it is being edited. Please ensure no one is editing the record, then try again.`}catch{}return null}async function bH(t,e,n,i,r,l,u,d,f,h={},g){const p=T=>{T.status==="processing"&&typeof T.message=="string"&&(T={...T,message:T.message.replace(/\s*fields…$/,"…")}),h.onProgress?.(T)};function v(T,E){for(const[C,O]of Object.entries(E))T[C]={...T[C]??{},...O}}async function b(T,E,C){const O=await l(T.item_type.id),L={},M=[];let N=0;async function D(j){p({recordIndex:E,recordId:T.id,status:"processing",message:`Translating "${C}" (#${T.id}) to ${ga(j)}…`});const K=await _H(T,i,j,O,n,u,f,d.environment,{abortSignal:h.abortSignal,checkCancellation:h.checkCancellation,selectedFieldsByModel:h.selectedFieldsByModel},g,d.cmaBaseUrl);v(L,K.payload),M.push(...K.warnings),N+=K.translatedFieldCount}return await r.reduce((j,K)=>j.then(()=>D(K)),Promise.resolve()),Object.keys(L).length>0&&(p({recordIndex:E,recordId:T.id,status:"processing",message:`Saving "${C}" (#${T.id})…`}),await e.items.update(T.id,L)),{payload:L,translatedFieldCount:N,warnings:M}}function S(T,E,C,O){const L=T.warnings.length>0?` Warnings: ${T.warnings.join(" ")}`:"";if(T.translatedFieldCount===0&&T.warnings.length>0)return p({recordIndex:E,recordId:C,status:"error",message:`No fields were updated for "${O}" (#${C}).${L}`}),"continue";const M=T.translatedFieldCount===0?`No eligible fields to translate for "${O}" (#${C}).`:`Translated "${O}" (#${C}).${L}`;return p({recordIndex:E,recordId:C,status:"completed",message:M}),"done"}async function w(T,E){const C=hH(T,i);if(h.checkCancellation?.())return p({recordIndex:E,recordId:T.id,status:"error",message:`Translation cancelled for "${C}" (#${T.id}).`}),"cancelled";p({recordIndex:E,recordId:T.id,status:"processing",message:`Translating "${C}" (#${T.id})…`});try{if(!FC(T,i)){const L=`Record "${C}" (#${T.id}) does not have the source locale ${ga(i)}`;return console.error(`Record ${T.id} ${L}`),d.alert(`Error: Record ID ${T.id} ${L}`),p({recordIndex:E,recordId:T.id,status:"error",message:L}),"continue"}const O=await b(T,E,C);return S(O,E,T.id,C)}catch(O){const L=vH(O,T.id),M=ta(O,n.vendor),N=na(M),D=O instanceof Error?O.message:String(O);return console.error(`Error translating record ${T.id}:`,D),p({recordIndex:E,recordId:T.id,status:"error",message:L??`Failed "${C}" (#${T.id}): ${N}`}),"continue"}}await t.reduce(async(T,E,C)=>await T==="cancelled"?"cancelled":w(E,C),Promise.resolve("done"))}function $p(t){if(t==null)return t;if(Array.isArray(t))return t.map($p);if(typeof t=="object"){const e=t,n=e.type==="item"&&typeof e.id=="string",i={};for(const[r,l]of Object.entries(e))n&&r==="id"||(i[r]=$p(l));return i}return t}const SH=new Set(["rich_text","structured_text","framed_single_block","frameless_single_block"]);async function _H(t,e,n,i,r,l,u,d,f={},h,g){const p={},v=[];let b=0;const S=rv(t,e),w=Object.keys(t).filter(E=>i[E]?.isLocalized&&wH(E,t,e,i,l,f.selectedFieldsByModel));async function T(E){const C=Wr(t[E],e),O=i[E].editor,L=z2(O);if(ov(O,C))try{const M=await Yl(C,l,n,e,O,r,L,u,i[E].id,d,{abortSignal:f.abortSignal,checkCancellation:f.checkCancellation},S,h,{fieldApiKey:E,...g?{cmaBaseUrl:g}:{}});p[E]={...t[E]||{},[n]:M},b+=1}catch(M){const N=ta(M,r.vendor),D=na(N);console.error(`Error translating field ${E} → ${n} for record ${t.id}: ${D}`);const j=D.endsWith(".")?"":".";v.push(`Field "${E}" to ${ga(n)} was skipped: ${D}${j}`)}}await w.reduce((E,C)=>E.then(()=>T(C)),Promise.resolve());for(const[E,C]of Object.entries(i)){if(!C.isLocalized||p[E])continue;const O=t[E]??{};if(ff(O,n)!==void 0)continue;const M=Wr(O,e),N=ZV(C.validators)&&M!=null,D=SH.has(C.editor);let j=null;N&&D?j=$p(M):N&&(j=M),p[E]={...O,[n]:j}}return{payload:p,translatedFieldCount:b,warnings:v}}function wH(t,e,n,i,r,l){if(["id","creator","meta","type","item_type"].includes(t)||!e[t]||!i[t]?.isLocalized)return!1;const u=i[t];if(!zC(u.editor,u.id,r,t)||!e$(e.item_type.id,t,l))return!1;const d=Wr(e[t],n);return!!ov(u.editor,d)}async function TH(t,e){return k7(t,e)}function EH(t){return t==="completed"?"Completed":t==="processing"?"Processing...":t==="error"?"Error":""}function RH({update:t}){const e=t.message??EH(t.status);return x.jsxs("li",{className:`TranslationProgressModal__update-item TranslationProgressModal__update-item--${t.status}`,children:[x.jsxs("span",{className:"TranslationProgressModal__update-status",children:[t.status==="completed"&&"✓",t.status==="processing"&&x.jsx(cf,{size:16}),t.status==="error"&&"✗"]}),x.jsx("span",{className:"TranslationProgressModal__update-message",children:e})]},t.recordId)}function AH(t,e){return na(ta(t,e??"openai"))}function CH({ctx:t,parameters:e}){const{totalRecords:n,fromLocale:i,toLocales:r,accessToken:l,pluginParams:u,itemIds:d,selectedFieldsByModel:f}=e,[h,g]=A.useState([]),[p,v]=A.useState(!1),b=A.useRef(!1),[S,w]=A.useState(!1),[T,E]=A.useState(!1),C=A.useRef(null),O=A.useRef(null),L=A.useRef(!1),M=A.useCallback(z=>{b.current||g(ee=>[...ee.filter(le=>le.recordIndex!==z.recordIndex),z])},[]);A.useEffect(()=>{let z=!0;return(async()=>{if(!(!z||L.current)){L.current=!0,w(!0);try{const ne=Ip(l,t.environment,t.cmaBaseUrl),le=await gH(ne,d),ue=jr(u),F=M7(ne),W=async ce=>TH(F,ce),ae=new AbortController;C.current=ae,await bH(le,ne,ue,i,r,W,u,t,l,{onProgress:M,checkCancellation:()=>b.current,abortSignal:ae.signal,selectedFieldsByModel:f},F),z&&w(!1)}catch(ne){z&&(E(!0),w(!1),M({recordIndex:-1,recordId:"fatal",status:"error",message:`Translation failed: ${AH(ne,u.vendor)}`}))}}})(),()=>{z=!1}},[l,M,t,i,d,u,f,r]);const N=Object.values(h.reduce((z,ee)=>(z[ee.recordIndex]=ee,z),{})),D=N.filter(z=>z.status==="completed"||z.status==="error").length,j=n>0?Math.round(D/n*100):0;A.useEffect(()=>{D>=n&&n>0&&(v(!0),w(!1))},[D,n]),A.useEffect(()=>{const z=O.current;z&&z.scrollTop<=8&&(z.scrollTop=0)},[]);const K=()=>{const z=T||N.some(ee=>ee.status==="error");t.resolve({completed:p&&!z,canceled:!1,progress:h})},X=()=>{b.current=!0,C.current?.abort(),t.resolve({completed:!1,canceled:!0})};return x.jsx(Un,{ctx:t,children:x.jsxs("div",{className:"TranslationProgressModal",children:[x.jsxs("div",{className:"TranslationProgressModal__intro",children:[x.jsxs("div",{className:"TranslationProgressModal__languages",children:[x.jsxs("div",{className:"TranslationProgressModal__lang-row",children:[x.jsx("span",{className:"TranslationProgressModal__lang-label",children:"From"}),x.jsx(Ud,{locale:i})]}),x.jsxs("div",{className:"TranslationProgressModal__lang-row",children:[x.jsx("span",{className:"TranslationProgressModal__lang-label",children:"To"}),x.jsx("div",{className:"TranslationProgressModal__lang-chips",children:r.map(z=>x.jsx(Ud,{locale:z},z))})]}),x.jsxs("p",{className:"TranslationProgressModal__progress-text",children:["Progress: ",D," of ",n," records processed (",j,"%)"]}),x.jsxs("p",{className:"TranslationProgressModal__stats",children:[N.filter(z=>z.status==="completed").length," ","successful,"," ",N.filter(z=>z.status==="error").length," ","failed"]})]}),x.jsx("div",{className:"TranslationProgressModal__progress-bar",children:x.jsx("div",{className:"TranslationProgressModal__progress-bar-fill",style:{width:`${j}%`}})})]}),x.jsx("div",{className:"TranslationProgressModal__updates",ref:O,"aria-live":"polite",children:h.length>0?x.jsx("ul",{className:"TranslationProgressModal__update-list",children:h.slice().sort((z,ee)=>ee.recordIndex-z.recordIndex).map(z=>x.jsx(RH,{update:z},z.recordId))}):x.jsx("div",{className:"TranslationProgressModal__initializing",children:x.jsxs("div",{className:"TranslationProgressModal__spinner-container",children:[x.jsx(cf,{size:20}),x.jsx("span",{children:"Initializing translation..."})]})})}),x.jsxs("div",{className:"TranslationProgressModal__footer",children:[!p&&S&&x.jsx(wt,{type:"button",buttonType:"negative",onClick:X,buttonSize:"s",children:"Cancel"}),x.jsx(wt,{type:"button",buttonType:"primary",onClick:K,disabled:S&&!p,buttonSize:"s",children:p?"Close":S?"Please wait...":"Close"})]})]})})}var xH=function(e){var n=we.useRef(e);return Ad(function(){n.current=e}),n},oT=function(e,n){if(typeof e=="function"){e(n);return}e.current=n},MH=function(e,n){var i=we.useRef();return we.useCallback(function(r){e.current=r,i.current&&oT(i.current,null),i.current=n,n&&oT(n,r)},[n])},lT={"min-height":"0","max-height":"none",height:"0",visibility:"hidden",overflow:"hidden",position:"absolute","z-index":"-1000",top:"0",right:"0",display:"block"},OH=function(e){Object.keys(lT).forEach(function(n){e.style.setProperty(n,lT[n],"important")})},uT=OH,Qt=null,cT=function(e,n){var i=e.scrollHeight;return n.sizingStyle.boxSizing==="border-box"?i+n.borderSize:i-n.paddingSize};function kH(t,e,n,i){n===void 0&&(n=1),i===void 0&&(i=1/0),Qt||(Qt=document.createElement("textarea"),Qt.setAttribute("tabindex","-1"),Qt.setAttribute("aria-hidden","true"),uT(Qt)),Qt.parentNode===null&&document.body.appendChild(Qt);var r=t.paddingSize,l=t.borderSize,u=t.sizingStyle,d=u.boxSizing;Object.keys(u).forEach(function(v){var b=v;Qt.style[b]=u[b]}),uT(Qt),Qt.value=e;var f=cT(Qt,t);Qt.value=e,f=cT(Qt,t),Qt.value="x";var h=Qt.scrollHeight-r,g=h*n;d==="border-box"&&(g=g+r+l),f=Math.max(g,f);var p=h*i;return d==="border-box"&&(p=p+r+l),f=Math.min(p,f),[f,h]}var dT=function(){},LH=function(e,n){return e.reduce(function(i,r){return i[r]=n[r],i},{})},DH=["borderBottomWidth","borderLeftWidth","borderRightWidth","borderTopWidth","boxSizing","fontFamily","fontSize","fontStyle","fontWeight","letterSpacing","lineHeight","paddingBottom","paddingLeft","paddingRight","paddingTop","tabSize","textIndent","textRendering","textTransform","width","wordBreak","wordSpacing","scrollbarGutter"],BH=!!document.documentElement.currentStyle,NH=function(e){var n=window.getComputedStyle(e);if(n===null)return null;var i=LH(DH,n),r=i.boxSizing;if(r==="")return null;BH&&r==="border-box"&&(i.width=parseFloat(i.width)+parseFloat(i.borderRightWidth)+parseFloat(i.borderLeftWidth)+parseFloat(i.paddingRight)+parseFloat(i.paddingLeft)+"px");var l=parseFloat(i.paddingBottom)+parseFloat(i.paddingTop),u=parseFloat(i.borderBottomWidth)+parseFloat(i.borderTopWidth);return{sizingStyle:i,paddingSize:l,borderSize:u}},IH=NH;function lv(t,e,n){var i=xH(n);A.useLayoutEffect(function(){var r=function(u){return i.current(u)};if(t)return t.addEventListener(e,r),function(){return t.removeEventListener(e,r)}},[])}var PH=function(e,n){lv(document.body,"reset",function(i){e.current.form===i.target&&n(i)})},jH=function(e){lv(window,"resize",e)},zH=function(e){lv(document.fonts,"loadingdone",e)},FH=["cacheMeasurements","maxRows","minRows","onChange","onHeightChange"],UH=function(e,n){var i=e.cacheMeasurements,r=e.maxRows,l=e.minRows,u=e.onChange,d=u===void 0?dT:u,f=e.onHeightChange,h=f===void 0?dT:f,g=JE(e,FH),p=g.value!==void 0,v=A.useRef(null),b=MH(v,n),S=A.useRef(0),w=A.useRef(),T=function(){var O=v.current,L=i&&w.current?w.current:IH(O);if(L){w.current=L;var M=kH(L,O.value||O.placeholder||"x",l,r),N=M[0],D=M[1];S.current!==N&&(S.current=N,O.style.setProperty("height",N+"px","important"),h(N,{rowHeight:D}))}},E=function(O){p||T(),d(O)};return A.useLayoutEffect(T),PH(v,function(){if(!p){var C=v.current.value;requestAnimationFrame(function(){var O=v.current;O&&C!==O.value&&T()})}}),jH(T),zH(T),A.createElement("textarea",Ae({},g,{onChange:E,ref:b}))},VH=A.forwardRef(UH);function $H(t){const e=t.toLowerCase();return!(!e.startsWith("claude")||e.includes("embed"))}function fT(t){const e=t.toLowerCase();let n=0;return e.includes("3.5")&&(n+=1e3),e.includes("haiku")&&(n+=100),e.includes("sonnet")&&(n+=60),e.includes("opus")&&(n+=20),e.endsWith("-latest")&&(n+=30),n}async function qH(t){try{const e=await fetch("https://api.anthropic.com/v1/models",{headers:{"x-api-key":t,"anthropic-version":"2023-06-01"}});if(!e.ok)throw new Error(String(e.status));const n=await e.json(),r=(Array.isArray(n?.data)?n.data:[]).map(u=>u.id).filter(u=>typeof u=="string"&&$H(u));return Array.from(new Set(r)).sort((u,d)=>{const f=fT(d)-fT(u);return f!==0?f:u.localeCompare(d)})}catch(e){return console.error("Failed to fetch Anthropic models:",e),[]}}function UC(t){return t.startsWith("models/")?t.slice(7):t}function GH(t){const e=UC(t.name).toLowerCase();return t.supportedGenerationMethods&&!t.supportedGenerationMethods.includes("generateContent")||["embedding","embed","text-embedding","moderation"].some(i=>e.includes(i))?!1:/^(gemini-)/.test(e)}function hT(t){const e=t.toLowerCase();let n=0;return/^gemini-2\.5/.test(e)?n=1200:/^gemini-2\.0/.test(e)?n=900:/^gemini-1\.5/.test(e)?n=700:/^gemini-1\.0/.test(e)&&(n=500),e.includes("flash")&&(n+=20),e.includes("pro")&&(n+=10),n}async function KH(t){try{const e=await fetch("https://generativelanguage.googleapis.com/v1beta/models",{headers:{"x-goog-api-key":t}});if(!e.ok)throw new Error(`Failed to list Gemini models (${e.status})`);const n=await e.json();return(Array.isArray(n.models)?n.models:[]).filter(GH).map(u=>UC(u.name)).sort((u,d)=>{const f=hT(d)-hT(u);return f!==0?f:u.localeCompare(d)}).filter((u,d,f)=>f.indexOf(u)===d)}catch(e){return console.error("Failed to fetch Gemini models:",e),[]}}function gT(t){const e=t.toLowerCase(),n=/(^|[.-])mini\b/.test(e),i=/(^|[.-])nano\b/.test(e);let r=0;/^gpt-5(\b|[.-])/.test(e)?r=900:/^gpt-4\.1(\b|[.-])/.test(e)?r=500:/^gpt-4o(\b|[.-])/.test(e)?r=450:/^gpt-4-turbo(\b|[.-])/.test(e)?r=400:/^gpt-4(\b|[.-])/.test(e)?r=350:/^gpt-3\.5(\b|[.-])/.test(e)?r=150:/^ft:gpt-/.test(e)?r=125:r=50;let l=r;return n&&(l+=20),i&&(l-=30),/thinking|reasoning/.test(e)&&(l-=60),/preview/.test(e)&&(l-=10),l}function HH(t){const e=t.toLowerCase();return!(!(/^gpt-/.test(e)||/^ft:gpt-/.test(e))||["whisper","tts","audio","speech","dall-e","image","omni-moderation","moderation","text-embedding","embedding","realtime","vision"].some(r=>e.includes(r)))}async function YH(t){const e=new ke({apiKey:t,dangerouslyAllowBrowser:!0}),{data:n}=await e.models.list();return n.map(u=>u.id).filter(HH).sort((u,d)=>{const f=gT(d)-gT(u);return f!==0?f:u.localeCompare(d)}).filter((u,d,f)=>f.indexOf(u)===d)}const XH="_buttons_1ojt3_32",WH="_inlineStatus_1ojt3_89",ZH="_textarea_1ojt3_143",JH="_label_1ojt3_164",QH="_sectionSpacing_1ojt3_192",eY="_buttonRow_1ojt3_196",tY="_exclusionRules_1ojt3_202",nY="_promptContainer_1ojt3_208",aY="_tooltipContainer_1ojt3_216",iY="_warningTooltip_1ojt3_223",sY="_tooltipText_1ojt3_232",rY="_imageTooltip_1ojt3_266",oY="_leftAnchorTooltip_1ojt3_271",Xe={buttons:XH,inlineStatus:WH,textarea:ZH,label:JH,sectionSpacing:QH,buttonRow:eY,exclusionRules:tY,promptContainer:nY,tooltipContainer:aY,warningTooltip:iY,tooltipText:sY,imageTooltip:rY,leftAnchorTooltip:oY};function lY({showExclusionRules:t,setShowExclusionRules:e,hasExclusionRules:n,modelsToBeExcluded:i,setModelsToBeExcluded:r,rolesToBeExcluded:l,setRolesToBeExcluded:u,apiKeysToBeExcluded:d,setApiKeysToBeExcluded:f,availableModels:h,roles:g,listOfFields:p}){return x.jsxs(x.Fragment,{children:[x.jsxs("div",{style:{position:"relative"},children:[x.jsx(Pr,{name:"showExclusionRules",id:"showExclusionRules",label:"Show exclusion rules",value:t,onChange:v=>e(v)}),n&&x.jsxs("div",{className:Xe.warningTooltip,children:["ⓘ",x.jsx("div",{className:Xe.tooltipText,children:"There are exclusion rules present. If the plugin is not being displayed in a model or field where you expect it, please review them."})]})]}),t&&x.jsx("div",{className:Xe.exclusionRules,children:x.jsxs(Ii,{children:[x.jsx(xt,{name:"modelsToBeExcludedFromTranslation",id:"modelsToBeExcludedFromTranslation",label:"Models to be excluded from this plugin",value:i.map(v=>({label:h.find(S=>S.apiKey===v)?.name??v,value:v})),selectInputProps:{isMulti:!0,options:h.map(v=>({label:v.name??"",value:v.apiKey??""}))},onChange:v=>{const b=v.map(S=>S.value);r(b)}}),x.jsx(xt,{name:"rolesToBeExcludedFromTranslation",id:"rolesToBeExcludedFromTranslation",label:"Roles to be excluded from using this plugin",value:l.map(v=>({label:g.find(S=>S.id===v)?.name??v,value:v})),selectInputProps:{isMulti:!0,options:g.map(v=>({label:v.name??"",value:v.id??""}))},onChange:v=>{const b=v.map(S=>S.value);u(b)}}),x.jsx(xt,{name:"apiKeysToBeExcludedFromTranslation",id:"apiKeysToBeExcludedFromTranslation",label:"Fields to be excluded from translation",value:d.map(v=>({label:`${p.find(b=>b.id===v)?.name} (${p.find(b=>b.id===v)?.model})`,value:v})),selectInputProps:{isMulti:!0,options:p.map(v=>({label:`${v.name} (${v.model})`,value:v.id}))},onChange:v=>{const b=v.map(S=>S.value);f(b)}})]})})]})}function uY(t){const[e,n]=A.useState(t.modelsToBeExcludedFromThisPlugin??[]),[i,r]=A.useState(t.rolesToBeExcludedFromThisPlugin??[]),[l,u]=A.useState(t.apiKeysToBeExcludedFromThisPlugin??[]),[d,f]=A.useState(!1),h=A.useMemo(()=>e.length>0||i.length>0||l.length>0,[e,i,l]);A.useEffect(()=>{h&&f(!0)},[h]);const g={modelsToBeExcluded:e,rolesToBeExcluded:i,apiKeysToBeExcluded:l,showExclusionRules:d,hasExclusionRules:h},p={setModelsToBeExcluded:A.useCallback(v=>n(v),[]),setRolesToBeExcluded:A.useCallback(v=>r(v),[]),setApiKeysToBeExcluded:A.useCallback(v=>u(v),[]),setShowExclusionRules:A.useCallback(v=>f(v),[]),resetExclusionRules:A.useCallback(()=>{n([]),r([]),u([])},[])};return[g,p]}function cY(t,e){const[n,i]=A.useState(Array.isArray(t.translationFields)?t.translationFields:Object.keys(Pi)),[r,l]=A.useState(typeof t.translateWholeRecord=="boolean"?t.translateWholeRecord:!0),[u,d]=A.useState(typeof t.translateBulkRecords=="boolean"?t.translateBulkRecords:!0),[f,h]=A.useState(t.prompt??e),[g,p]=A.useState(typeof t.enableDebugging=="boolean"?t.enableDebugging:!1),v={translationFields:n,translateWholeRecord:r,translateBulkRecords:u,prompt:f,enableDebugging:g},b={setTranslationFields:A.useCallback(S=>i(S),[]),setTranslateWholeRecord:A.useCallback(S=>l(S),[]),setTranslateBulkRecords:A.useCallback(S=>d(S),[]),setPrompt:A.useCallback(S=>h(S),[]),setEnableDebugging:A.useCallback(S=>p(S),[]),resetToDefaults:A.useCallback(()=>{i(Object.keys(Pi)),l(!0),d(!0),h(e)},[e])};return[v,b]}function dY(t){return{deeplApiKey:t.deeplApiKey??"",deeplUseFree:t.deeplUseFree??!1,deeplFormality:t.deeplFormality??"default",deeplPreserveFormatting:t.deeplPreserveFormatting??!0,deeplIgnoreTags:t.deeplIgnoreTags??"notranslate,ph",deeplNonSplittingTags:t.deeplNonSplittingTags??"a,code,pre,strong,em,ph,notranslate",deeplSplittingTags:t.deeplSplittingTags??"",deeplGlossaryId:t.deeplGlossaryId??"",deeplGlossaryPairs:t.deeplGlossaryPairs??""}}function fY(t){return{vendor:t.vendor??"openai",apiKey:t.apiKey??"",gptModel:t.gptModel??"None",googleApiKey:t.googleApiKey??"",geminiModel:t.geminiModel??"gemini-2.5-flash",anthropicApiKey:t.anthropicApiKey??"",anthropicModel:t.anthropicModel??"claude-haiku-4-5-latest",...dY(t)}}function hY(t){const e=fY(t),[n,i]=A.useState(e.vendor),[r,l]=A.useState(e.apiKey),[u,d]=A.useState(e.gptModel),[f,h]=A.useState(e.googleApiKey),[g,p]=A.useState(e.geminiModel),[v,b]=A.useState(e.anthropicApiKey),[S,w]=A.useState(e.anthropicModel),[T,E]=A.useState(e.deeplApiKey),[C,O]=A.useState(e.deeplUseFree),[L,M]=A.useState(e.deeplFormality),[N,D]=A.useState(e.deeplPreserveFormatting),[j,K]=A.useState(e.deeplIgnoreTags),[X,z]=A.useState(e.deeplNonSplittingTags),[ee,ne]=A.useState(e.deeplSplittingTags),[le,ue]=A.useState(e.deeplGlossaryId),[F,W]=A.useState(e.deeplGlossaryPairs),ae={vendor:n,apiKey:r,gptModel:u,googleApiKey:f,geminiModel:g,anthropicApiKey:v,anthropicModel:S,deeplApiKey:T,deeplUseFree:C,deeplFormality:L,deeplPreserveFormatting:N,deeplIgnoreTags:j,deeplNonSplittingTags:X,deeplSplittingTags:ee,deeplGlossaryId:le,deeplGlossaryPairs:F},ce={setVendor:A.useCallback($=>i($),[]),setApiKey:A.useCallback($=>l($),[]),setGptModel:A.useCallback($=>d($),[]),setGoogleApiKey:A.useCallback($=>h($),[]),setGeminiModel:A.useCallback($=>p($),[]),setAnthropicApiKey:A.useCallback($=>b($),[]),setAnthropicModel:A.useCallback($=>w($),[]),setDeeplApiKey:A.useCallback($=>E($),[]),setDeeplUseFree:A.useCallback($=>O($),[]),setDeeplFormality:A.useCallback($=>M($),[]),setDeeplPreserveFormatting:A.useCallback($=>D($),[]),setDeeplIgnoreTags:A.useCallback($=>K($),[]),setDeeplNonSplittingTags:A.useCallback($=>z($),[]),setDeeplSplittingTags:A.useCallback($=>ne($),[]),setDeeplGlossaryId:A.useCallback($=>ue($),[]),setDeeplGlossaryPairs:A.useCallback($=>W($),[])};return[ae,ce]}function uv({id:t,label:e,value:n,onChange:i,models:r,hint:l,isLoading:u=!1}){const d=A.useMemo(()=>r.map(g=>({label:g,value:g})),[r]),f=g=>{Array.isArray(g)||i(g?.value||n)},h=u?{label:"Loading models...",value:"Loading models..."}:{label:n,value:n};return x.jsx(xt,{name:t,id:t,label:e,required:!0,hint:l,placeholder:u?"Loading models...":void 0,value:h,selectInputProps:{isDisabled:u,isLoading:u,options:d},onChange:f})}function gY({anthropicApiKey:t,setAnthropicApiKey:e,anthropicModel:n,setAnthropicModel:i,listOfAnthropicModels:r}){return x.jsxs(Ii,{children:[x.jsx(vs,{required:!0,name:"anthropicApiKey",id:"anthropicApiKey",label:"Anthropic API Key",value:t,onChange:l=>e(l),placeholder:"sk-ant-..."}),x.jsx(uv,{id:"anthropicModel",label:"Claude Model",hint:"Recommended: claude-haiku-4-5-latest",value:n,onChange:i,models:r})]})}let mT=0;function mY(t){if(!t.trim())return[];const e=t.split(/\r?\n|[;,]+/).map(i=>i.trim()).filter(Boolean),n=[];for(const i of e){const l=i.replace(/[→⇒–—]/g,"->").replace(/\s+/g,"").match(/^([a-zA-Z*]{1,5}(?:-[a-zA-Z]{2,4})?)->([a-zA-Z*]{1,5}(?:-[a-zA-Z]{2,4})?)(?:=|:)([\w-]+)$/);l&&n.push({source:l[1],target:l[2],glossaryId:l[3]})}return n}function pY(t){return t.filter(e=>e.source&&e.target&&e.glossaryId).map(e=>`${e.source}->${e.target}=${e.glossaryId}`).join(`
|
|
77
|
+
${JSON.stringify(g)}`;r.logPrompt("Prompt request",p),r.logRequest("Provider text request input",{provider:t.vendor,fromLocale:n,toLocale:i,chunkStart:h,chunkSize:g.length,prompt:p,protectedSegments:g});const v=await t.completeText(p,{debug:l});return r.logResponse("Raw provider response",{provider:t.vendor,fromLocale:n,toLocale:i,chunkStart:h,chunkSize:g.length,rawResponse:v}),Jw(v,g,r,{provider:t.vendor,fromLocale:n,toLocale:i,chunkStart:h,chunkSize:g.length})},f=[];for(let h=0;h<e.length;h+=km)f.push(h);return f.reduce(async(h,g)=>{const p=await h,v=await d(g);return[...p,...v]},Promise.resolve([]))}async function xf(t,e,n,i,r,l={}){if(!Array.isArray(n)||n.length===0)return n;const u=sa(e,"translateArray"),d=nK(u),f=[],h=n.map(g=>{const{safe:p,map:v}=aK(String(g??""));return f.push(v),p});u.info("Translation batch payload",{provider:t.vendor,fromLocale:i,toLocale:r,options:l,originalSegments:n,protectedSegments:h,tokenMaps:f});try{let g;t.translateArray?g=await oK(t,e,h,i,r,l,u,d):g=await lK(t,h,i,r,u,d);const p=g.map((v,b)=>{const S=f[b]??[];return iK(String(v??""),S)});return u.info("Translation batch output",{provider:t.vendor,fromLocale:i,toLocale:r,translatedSegments:g,finalSegments:p,tokenMaps:f}),p}catch(g){const p=ta(g,t.vendor);throw new Error(na(p),{cause:g})}}async function uK(t,e,n,i,r,l,u="",d={}){if(t==null||t==="")return t;const f=sa(e,"DefaultTranslation");try{const[h]=await xf(r,e,[String(t)],i,n,{isHTML:d.isHTML===!0,recordContext:u});return h}catch(h){Hl(h,r.vendor,f,"Translation error")}}const Qw=new Map;async function cK(t,e,n,i,r){const l=`${i??""}:${n}:${t}`,u=Qw.get(l);if(u)return u;const d=(async()=>{try{const g=(await Cf({apiToken:e,environment:n,baseUrl:i}).uploads.find(t)).default_field_metadata;return!g||typeof g!="object"?void 0:g}catch(f){r.warning("Failed to fetch upload default metadata",{uploadId:t,error:f});return}})();return Qw.set(l,d),d}async function dK(t,e,n,i,r,l,u,d,f="",h){const g=sa(e,"FileFieldTranslation");return t?Array.isArray(t)?t.length===0?(g.info("Empty array, nothing to translate"),t):(g.info(`Translating gallery with ${t.length} files`),await Promise.all(t.map(async v=>tT(v,e,n,i,r,l,u,d,f,h)))):(g.info("Translating single file metadata"),tT(t,e,n,i,r,l,u,d,f,h)):(g.info("No field value to translate"),t)}function eT(t,e){if(t?.trim())return t;if(e?.trim())return e}async function fK(t,e,n,i,r,l,u,d){const f=await cK(n,r,l,u,d);if(!f)return{altSource:t,titleSource:e};const h=ff(f,i),g=h?f[h]:void 0;if(!g||typeof g!="object")return{altSource:t,titleSource:e};const p=!t&&typeof g.alt=="string"&&g.alt.trim()?g.alt:t,v=!e&&typeof g.title=="string"&&g.title.trim()?g.title:e;return{altSource:p,titleSource:v}}function hK(t,e,n){const i=[];for(const[r,l]of Object.entries(t))r==="alt"&&e||r==="title"&&n||l&&typeof l=="string"&&i.push({kind:"metadata",key:r,value:l});return i}function gK(t,e,n){const i=[];if(e&&i.push({kind:"alt",value:e}),n&&i.push({kind:"title",value:n}),t){const r=hK(t,e!==void 0,n!==void 0);i.push(...r)}return i}function mK(t,e,n,i){if(t.kind==="alt")n.alt=e,i&&"alt"in i&&(i.alt=e);else if(t.kind==="title")n.title=e,i&&"title"in i&&(i.title=e);else if(t.kind==="metadata"&&t.key){const r=i??{};return r[t.key]=e,r}return i}function pK(t,e,n,i){let r=i?{...i}:void 0;const l={...n};for(let u=0;u<t.length;u++){const d=t[u],f=e[u];!d||f===void 0||(r=mK(d,f,l,r))}return r&&(l.metadata=r),l}function yK(t){if(typeof t.upload_id=="string")return t.upload_id;if(typeof t.uploadId=="string")return t.uploadId}async function vK(t,e,n,i,r,l,u){let d=eT(typeof t.alt=="string"?t.alt:void 0,typeof e?.alt=="string"?e.alt:void 0),f=eT(typeof t.title=="string"?t.title:void 0,typeof e?.title=="string"?e.title:void 0);const h=yK(t);if((!d||!f)&&h&&i&&r){const g=await fK(d,f,h,n,i,r,l,u);d=g.altSource,f=g.titleSource}return{altSource:d,titleSource:f}}async function tT(t,e,n,i,r,l,u,d,f="",h){const g=sa(e,"FileFieldTranslation.translateSingleFileMetadata");if(!t||typeof t!="object")return g.info("No valid file object to translate"),t;const p=t,v=p.metadata&&typeof p.metadata=="object"&&!Array.isArray(p.metadata)?p.metadata:void 0,{altSource:b,titleSource:S}=await vK(p,v,i,l,u,h,g),w=gK(v,typeof b=="string"?b:void 0,typeof S=="string"?S:void 0);if(w.length===0)return g.info("No translatable alt/title or metadata found"),t;g.info("Translating file metadata",{alt:b,title:S,metadataKeys:v?Object.keys(v):[]});try{const T=w.map(C=>C.value),E=await xf(r,e,T,i,n,{isHTML:!1,recordContext:f});return pK(w,E,p,v)}catch(T){Hl(T,r.vendor,g,"File metadata translation error")}}const Lm=60,Dm=160,nT=3;async function bK(t,e,n,i,r,l,u,d=""){const f=sa(e,"translateSeoFieldValue");if(f.info("Starting SEO field translation",{fromLocale:i,toLocale:n}),!t)return{title:"",description:""};const h=t.title||"",g=t.description||"";f.info("SEO object to translate",{title:h,description:g});try{const p=pp.getByTag(i)?.name||i,v=pp.getByTag(n)?.name||n;f.info(`Translating from ${p} to ${v}`);const S=`${(e.prompt||"").replace("{fieldValue}",JSON.stringify({title:h,description:g})).replace("{fromLocale}",p).replace("{toLocale}",v).replace("{recordContext}",d||"Record context: No additional context available.")}
|
|
78
|
+
${l}`;f.info("Formatted prompt prepared for translation"),f.logPrompt("SEO translation prompt",S);const[w,T]=await xf(r,e,[h,g],i,n,{isHTML:!1,recordContext:d}),E={...t};let C=w||h;C.length>Lm&&(f.info(`SEO title exceeds ${Lm} character limit (${C.length}). Truncating...`),C=`${C.substring(0,Lm-nT)}...`);let O=T||g;return O.length>Dm&&(f.info(`SEO description exceeds ${Dm} character limit (${O.length}). Truncating...`),O=`${O.substring(0,Dm-nT)}...`),E.title=C,E.description=O,f.info("SEO translation completed successfully"),E}catch(p){Hl(p,r.vendor,f,"SEO translation error")}}function SK(t){if(Array.isArray(t))return t;if(t&&typeof t=="object"){const e=t.document;if(e&&typeof e=="object"){const n=e.children;if(Array.isArray(n))return n}}return null}function _K(t){const e=typeof t.type=="string"?t.type:void 0;return typeof t.text=="string"&&t.text.trim().length>0||e==="span"&&typeof t.value=="string"&&t.value.trim().length>0}function Pp(t,e){if(e.hasVisibleText||e.hasBlocks)return;if(Array.isArray(t)){for(const r of t)Pp(r,e);return}if(!t||typeof t!="object")return;const n=t;if((typeof n.type=="string"?n.type:void 0)==="block"){e.hasBlocks=!0;return}if(_K(n)){e.hasVisibleText=!0;return}if(Array.isArray(n.children))for(const r of n.children)Pp(r,e)}function jp(t){const e=SK(t);if(!e)return!1;if(e.length===0)return!0;const n={hasVisibleText:!1,hasBlocks:!1};return Pp(e,n),!n.hasVisibleText&&!n.hasBlocks}function zp(t){if(Array.isArray(t))return t.map(zp);if(typeof t=="object"&&t!==null){const e={};for(const[n,i]of Object.entries(t)){if(n==="data"){e[n]=i;continue}n==="id"&&t.value!==void 0&&Object.keys(t).length===2?e[n]=i:n!=="id"&&(e[n]=zp(i))}return e}return t}function wK(t,e,n){return[...t.slice(0,n),e,...t.slice(n)]}function TK(t){if(t===null||typeof t!="object")return!1;const e=t;if(!e.document||typeof e.document!="object")return!1;const n=e.document;return Array.isArray(n.children)&&n.children.length>0}const EK=/^[\s\u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]+$/;function qd(t){return t===""||EK.test(t)}function RK(t){return t?{bypassFieldTypeAllowlist:!0,cmaBaseUrl:t}:{bypassFieldTypeAllowlist:!0}}function Fp(t){return Array.isArray(t)?t.map(e=>Fp(e)):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).map(([e,n])=>[e,Fp(n)])):t}function Up(t,e=[]){if(Array.isArray(t))return t.flatMap((r,l)=>Up(r,[...e,l]));if(!t||typeof t!="object")return[];const n=t,i=typeof n.type=="string"?n.type:void 0;return typeof n.text=="string"?[{path:[...e,"text"],value:n.text}]:i==="span"&&typeof n.value=="string"?[{path:[...e,"value"],value:n.value}]:i==="block"?[]:Array.isArray(n.children)?Up(n.children,[...e,"children"]):[]}function AK(t,e,n){let i=t;for(let r=0;r<e.length-1;r++){if(i===null||typeof i!="object")return;i=i[e[r]]}i!==null&&typeof i=="object"&&(i[e[e.length-1]]=n)}function CK(t,e,n){const i=Fp(t);return e.forEach((r,l)=>{const u=n[l];u!==void 0&&AK(i,r.path,u)}),i}function xK(t,e){return t.length===e.length?e:e.length<t.length?[...e,...t.slice(e.length)]:e.slice(0,t.length)}function MK(t,e){const n=new Array(e.length);for(let i=0;i<e.length;i++){const r=String(t[i]??""),l=String(e[i]??"");if(qd(r)){n[i]=r;continue}const u=(r.match(/^\s+/)||[""])[0],d=(r.match(/\s+$/)||[""])[0];let f=l;u&&!/^\s/.test(f)&&(f=`${u}${f}`),d&&!/\s$/.test(f)&&(f=`${f}${d}`),n[i]=f}return n}function OK(t,e){const n=[];let i=0;for(let r=0;r<t.length;r++){const l=String(t[r]??"");if(qd(l))n.push(l);else{const u=i<e.length?String(e[i++]):l;n.push(u)}}return n}function kK(t,e){const n=e.slice();for(let i=0;i<t.length-1;i++){const r=String(t[i]??""),l=String(t[i+1]??"");if(qd(r)||qd(l)||!(/[\s\u00A0]$/.test(r)||/^[\s\u00A0]/.test(l)))continue;const d=String(n[i]??""),f=String(n[i+1]??""),h=/[\s\u00A0]$/.test(d),g=/^[\s\u00A0]/.test(f);!h&&!g&&(n[i]=`${d} `)}return n}function LK(t,e){const n=e.slice();for(let i=0;i<t.length-1;i++){const r=String(t[i]??""),l=String(t[i+1]??""),u=/[.,;:!?]$/.test(r.trimEnd()),d=/^[.,;:!?]/.test(l.trimStart());if(!u&&!d)continue;const f=String(n[i]??""),h=String(n[i+1]??""),g=/[\s\u00A0]$/.test(f)||/^[\s\u00A0]/.test(h),p=/[.,;:!?]$/.test(f)||/^[.,;:!?]/.test(h);!g&&!p&&(n[i]=`${f} `)}return n}async function DK({provider:t,pluginParams:e,textValues:n,textLeaves:i,fieldValueWithoutBlocks:r,fromLocale:l,toLocale:u,recordContext:d,logger:f}){const h=await xf(t,e,n,l,u,{isHTML:!1,recordContext:d});let g=h;return h.length!==n.length&&(f.warning(`Translation mismatch: got ${h.length} values, expected ${n.length}`,{original:n,translated:h}),g=OK(n,h),g.length!==n.length&&(g=xK(n,g)),f.info("Adjusted translated values to match original length",{adjustedLength:g.length})),g=MK(n,g),g=kK(n,g),g=LK(n,g),CK(r,i,g)}function BK({logger:t,textValues:e,textLeaves:n,blockNodeCount:i,fromLocale:r,toLocale:l}){if(e.length>0){t.info(`Found ${e.length} text nodes to translate`),t.info("Structured text inline source payload",{fromLocale:r,toLocale:l,textLeaves:n,textValues:e});return}t.info("No inline text values found; translating block nodes only",{fromLocale:r,toLocale:l,blockNodeCount:i})}async function NK(t,e,n,i,r,l,u,d,f="",h,g){const p=sa(e,"StructuredTextTranslation");let v=t,b=!1;if(TK(t)&&(v=t.document.children,b=!0),p.info("Structured text source payload",{fromLocale:i,toLocale:n,isAPIResponse:b,value:t,workingValue:v}),!v||!Array.isArray(v)||v.length===0)return p.info("Invalid structured text value",v),v;p.info("Translating structured text field",{nodeCount:v.length});const S=zp(v),w=S.reduce((O,L,M)=>(L?.type==="block"&&O.push({...L,originalIndex:M}),O),[]),T=S.filter(O=>O?.type!=="block"),E=Up(T),C=E.map(O=>O.value);if(C.length===0&&w.length===0)return p.info("No text values or block nodes found to translate"),v;BK({logger:p,textValues:C,textLeaves:E,blockNodeCount:w.length,fromLocale:i,toLocale:n});try{let O=T;if(C.length>0&&(O=await DK({provider:r,pluginParams:e,textValues:C,textLeaves:E,fieldValueWithoutBlocks:T,fromLocale:i,toLocale:n,recordContext:f,logger:p})),w.length>0){p.info(`Translating ${w.length} block nodes`,{fromLocale:i,toLocale:n,blockNodes:w});const M=await Yl(w,e,n,i,"rich_text",r,"",l,"",u,d,f,h,RK(g));p.info("Structured text translated block payload",{fromLocale:i,toLocale:n,translatedBlockNodes:M});for(const N of M)N.originalIndex!==void 0&&(O=wK(O,N,N.originalIndex))}const L=O.map(({originalIndex:M,...N})=>N);if(b){const M={document:{children:L,type:"root"},schema:"dast"};return p.info("Structured text translated payload",{fromLocale:i,toLocale:n,value:M}),M}return p.info("Successfully translated structured text",{fromLocale:i,toLocale:n,value:L}),L}catch(O){Hl(O,r.vendor,p,"Error during structured text translation")}}function IK(t){return t.item!==void 0&&typeof t.item=="object"&&t.item!==null&&"attributes"in t.item&&typeof t.item.attributes=="object"}function PK(t){if(t.itemTypeId)return String(t.itemTypeId);if(t.blockModelId)return String(t.blockModelId);const e=t.relationships?.item_type?.data?.id;if(e)return e;const n=t.item?.relationships?.item_type?.data?.id;if(n)return n}class jK extends Error{constructor(){super("Operation cancelled"),this.name="CancellationError"}}function Gd(t){return Array.isArray(t)?t.map(e=>Gd(e)):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).map(([e,n])=>[e,Gd(n)])):t}function zK(t){const e=Gd(t),n=e;return delete n.id,delete n.itemId,n.item&&typeof n.item=="object"&&(delete n.item.id,delete n.item.itemId),e}async function FK(t,e,n){const i=t.map((g,p)=>({index:p,completed:!1}));let r=0,l=!1;async function u(){if(l||r>=t.length)return;const g=r++;try{n?.()}catch{l=!0;return}try{const p=await t[g]();i[g]={index:g,result:p,completed:!0}}catch(p){if(p instanceof jK){l=!0;return}throw p}return u()}const d=()=>u(),f=Math.min(e,t.length),h=Array(f).fill(null).map(()=>d());return await Promise.all(h),i}async function Yl(t,e,n,i,r,l,u,d,f,h,g,p="",v,b={}){const S=sa(e,"translateFieldValue");if(S.info(`Translating field of type: ${r}`,{fromLocale:i,toLocale:n}),S.info("Source field payload",{fieldType:r,fieldId:f,fieldApiKey:b.fieldApiKey,fromLocale:i,toLocale:n,recordContext:p,value:t}),gf(e.apiKeysToBeExcludedFromThisPlugin,[f,b.fieldApiKey]))return S.info("Skipping field translation",{reason:"excluded",fieldType:r,fieldId:f,fieldApiKey:b.fieldApiKey,fromLocale:i,toLocale:n,value:t}),t;if(!hf(r,e.translationFields,df)&&!b.bypassFieldTypeAllowlist||!t)return S.info("Skipping field translation",{reason:t?"field-type-not-enabled":"empty-value",fieldType:r,fieldId:f,fieldApiKey:b.fieldApiKey,fromLocale:i,toLocale:n,value:t}),t;let T;switch(r){case"seo":T=await bK(t,e,n,i,l,u,g,p);break;case"structured_text":T=await NK(t,e,n,i,l,d,h,g,p,v,b.cmaBaseUrl);break;case"rich_text":case"framed_single_block":case"frameless_single_block":T=await XK(t,e,n,i,l,d,r,h,g,p,v,b.cmaBaseUrl);break;case"file":case"gallery":T=await dK(t,e,n,i,l,d,h,g,p,b.cmaBaseUrl);break;default:T=await uK(t,e,n,i,l,g,p,{isHTML:r==="wysiwyg"});break}if(r==="slug"){const E=JV(T);if(!E)throw new Error("Translated slug is empty after normalization");return S.info("Translated field payload",{fieldType:r,fieldId:f,fieldApiKey:b.fieldApiKey,fromLocale:i,toLocale:n,value:E}),E}return S.info("Translated field payload",{fieldType:r,fieldId:f,fieldApiKey:b.fieldApiKey,fromLocale:i,toLocale:n,value:T}),T}const UK=100,VK=3,Lr=new Map;function $K(t,e){if(Lr.size>=UK){const n=Lr.keys().next().value;n&&Lr.delete(n)}Lr.set(t,e)}async function Vp(t,e,n,i,r){if(i)return O7(i,n);const l=`${r??""}:${e}:${n}`,u=Lr.get(l);if(u)return u;const d=(async()=>(await Cf({apiToken:t,environment:e,baseUrl:r}).fields.list(n)).reduce((g,p)=>(g[p.api_key]={editor:p.appearance.editor,id:p.id,localized:p.localized,validators:p.validators},g),{}))();$K(l,d);try{return await d}catch(f){throw Lr.delete(l),f}}const qK=["itemTypeId","originalIndex","blockModelId","type","children","relationships","attributes"];function PC(t){if(!t||typeof t!="object")return;const n=t.single_block_blocks;if(!n||typeof n!="object")return;const i=n.item_types;if(!(!Array.isArray(i)||i.length===0))return String(i[0])}function GK(t,e){return ff(t,e)??e}async function KK(t,e,n){if(!t||typeof t!="object"||Array.isArray(t))return t;const i=PC(e?.validators);if(!i)return n.logger.warning("Frameless single block missing item type validators",e),t;const r=await Vp(n.apiToken,n.environment,i,n.schemaRepository,n.cmaBaseUrl),l=Gd(t);return delete l.id,delete l.itemId,await jC(l,r,n),l}function HK(t,e,n,i){if(!e||!t||typeof t!="object"||Array.isArray(t))return{valueToTranslate:t,localizedContainer:null,targetLocaleKey:null,skip:!1};const r=Wr(t,n);if(r==null||r==="")return{valueToTranslate:t,localizedContainer:null,targetLocaleKey:null,skip:!0};const l={...t},u=GK(l,i);return{valueToTranslate:r,localizedContainer:l,targetLocaleKey:u,skip:!1}}async function YK(t,e,n,i){const r=e?.editor||"text";if(r==="frameless_single_block")return KK(n,e,i);const l=" Return the response in the format of "+(xy[r]||"");return Yl(n,i.pluginParams,i.toLocale,i.fromLocale,r,i.provider,l,i.apiToken,e?.id||"",i.environment,i.streamCallbacks,i.recordContext,i.schemaRepository,{fieldApiKey:t,cmaBaseUrl:i.cmaBaseUrl})}async function jC(t,e,n){const i=[];for(const d of Object.keys(t)){if(qK.includes(d)){n.logger.info("Block field skipped",{fieldKey:d,reason:"metadata-field",value:t[d]});continue}i.push(d)}if(i.length===0){n.logger.info("Block processing skipped",{reason:"no-translatable-fields",source:t});return}const r=i.map(d=>async()=>{n.streamCallbacks?.onStream?.(`Translating block field: ${d}...`);const f=e[d],h=f?.localized===!0,g=f?.editor||"text";n.logger.info("Block field source payload",{fieldKey:d,fieldId:f?.id,editor:g,localized:h,fromLocale:n.fromLocale,toLocale:n.toLocale,value:t[d]});const p=HK(t[d],h,n.fromLocale,n.toLocale);if(p.skip)return n.logger.info("Block field skipped",{fieldKey:d,fieldId:f?.id,editor:g,localized:h,reason:"missing-source-locale-value",fromLocale:n.fromLocale,toLocale:n.toLocale,value:t[d]}),{field:d,value:t[d]};n.logger.info("Block field translation input",{fieldKey:d,fieldId:f?.id,editor:g,localized:h,fromLocale:n.fromLocale,toLocale:n.toLocale,value:p.valueToTranslate});const v=await YK(d,f,p.valueToTranslate,n);return p.localizedContainer&&p.targetLocaleKey?(p.localizedContainer[p.targetLocaleKey]=v,n.logger.info("Block field translated payload",{fieldKey:d,fieldId:f?.id,editor:g,localized:h,targetLocaleKey:p.targetLocaleKey,fromLocale:n.fromLocale,toLocale:n.toLocale,translatedValue:v,writtenValue:p.localizedContainer}),{field:d,value:p.localizedContainer}):(n.logger.info("Block field translated payload",{fieldKey:d,fieldId:f?.id,editor:g,localized:h,fromLocale:n.fromLocale,toLocale:n.toLocale,translatedValue:v,writtenValue:v}),{field:d,value:v})}),l=await FK(r,VK,n.streamCallbacks?.checkCancellation);for(const d of l)d.completed&&d.result&&(t[d.result.field]=d.result.value);const u=l.filter(d=>d.completed).length;u<i.length&&n.logger.info(`Translation cancelled: ${u}/${i.length} fields translated`)}async function XK(t,e,n,i,r,l,u,d,f,h="",g,p){const v=sa(e,"translateBlockValue");v.info("Translating block value",{fieldType:u,fromLocale:i,toLocale:n,value:t});const b=u==="framed_single_block"||u==="frameless_single_block",S=b?[t]:t,w=S.map(zK);v.info("Block payload before processing",{fieldType:u,fromLocale:i,toLocale:n,rawBlocks:S,cleanedFieldValue:w});const T={pluginParams:e,toLocale:n,fromLocale:i,provider:r,apiToken:l,environment:d,cmaBaseUrl:p,streamCallbacks:f,recordContext:h,logger:v,schemaRepository:g};async function E(L,M,N,D,j){if(L in N)return;const K=PC(M.validators);if(!K){v.warning("Frameless single block missing validators",{fieldKey:L,blockModelId:D});return}const X=await Vp(l,d,K,g,p);for(const[z,ee]of Object.entries(X))z in j||(j[z]=ee)}async function C(L){const M=PK(L);if(!M){v.warning("Block model ID not found",L);return}v.info("Block processing started",{blockModelId:M,block:L});const N=await Vp(l,d,M,g,p),D=L.attributes?L.attributes:IK(L)?L.item.attributes:L;let j=N;const K=Object.entries(N).filter(([,X])=>X.editor==="frameless_single_block");if(K.length>0){const X={...N};await K.reduce(async(z,[ee,ne])=>{await z,await E(ee,ne,D,M,X)},Promise.resolve()),j=X}await jC(D,j,T),v.info("Block processing completed",{blockModelId:M,block:L,sourceObject:D})}await w.reduce((L,M)=>L.then(()=>C(M)),Promise.resolve());const O=b?w[0]:w;return v.info("Block translation completed",{fieldType:u,fromLocale:i,toLocale:n,value:O}),O}async function Bm(t,e,n,i,r,l,u,d,f=""){const h=await e.currentUserAccessToken,g=jr(n),p=sa(n,"TranslateField");try{p.info("Starting field translation",{fieldType:l,fromLocale:r,toLocale:i});const v=e.formValues&&!f?rv(e.formValues,r):f;d?.onStream;const b=e.field.attributes.api_key??"",S=e.field.id??e.fieldPath??"";p.info("Dropdown source payload",{fieldType:l,fieldId:S,fieldApiKey:b,fieldPath:e.fieldPath,fromLocale:r,toLocale:i,value:t});let w="Return the response in the format of ";const T=xy;l!=="structured_text"&&l!=="rich_text"&&(w+=(T||{})[l]||"");const C=await Yl(t,n,i,r,l,g,w,h,S,u,d,v,void 0,{fieldApiKey:b,cmaBaseUrl:e.cmaBaseUrl});return p.info("Dropdown translated payload",{fieldType:l,fieldId:S,fieldApiKey:b,fieldPath:e.fieldPath,fromLocale:r,toLocale:i,value:C}),p.info("Field translation completed"),C}catch(v){Hl(v,g.vendor,p,"Translation failed")}}const WK=["title","name","content","description"];function ZK(t){const e=t.toLowerCase();return WK.some(n=>e.includes(n))}function JK(t,e){if(typeof t!="object"||t===null)return null;const i=t[e];return typeof i!="string"||!i||i.length>=300?null:i}function rv(t,e){if(!t)return"";let n="Content context: ",i=!1;for(const r in t){if(!ZK(r))continue;const l=JK(t[r],e);l&&(n+=`${r}: ${l}. `,i=!0)}return i?n:""}const aT=64,QK=15,iT=3e5,eH=33,sT=10,tH=1e3,nH=1e4,aH=50,iH=200;function zC(t,e,n,i){const r=hf(t,n.translationFields,df),l=gf(n.apiKeysToBeExcludedFromThisPlugin,[e,i]);return r&&!l}function ov(t,e){return e==null||e===""?!1:t==="structured_text"?!jp(e):!(Array.isArray(e)&&e.length===0)}function sH(t){const e=t.vendor??"openai",n=e==="google"?String(t.geminiModel??"").toLowerCase():String(t.gptModel??"").toLowerCase();return e==="google"?/(^|[-])nano\b/.test(n)||/flash|lite/.test(n)?3:(/pro/.test(n),2):/(^|[-])nano\b/.test(n)||/flash|mini|lite/.test(n)?6:/mini/.test(n)||/1\.5/.test(n)?5:/pro/.test(n)?3:4}function rH(t){return(t.vendor??"openai")==="google"?iH:aH}function oH(t){const e=tH*2**(t-1);return Math.min(e,nH)}function lH(t){if(t===null||typeof t!="object")return!1;const e=t;return e?.status===429||e?.code==="rate_limit_exceeded"||/\b429\b|rate limit|Too Many Requests/i.test(String(e?.message??""))}function uH(t){return t instanceof DOMException&&t.name==="AbortError"}function rT(t){return new Promise(e=>setTimeout(e,t))}const cH=["title","name","headline","heading","label","internal_name","internalName","slug"];function dH(t,e){const n=Wr(t,e);if(typeof n=="string"&&n.trim())return n;for(const i of Object.values(t))if(typeof i=="string"&&i.trim())return i;return null}function fH(t,e){return t==null?null:typeof t=="string"?t:typeof t=="number"?String(t):Array.isArray(t)?t.filter(n=>typeof n=="string")[0]??null:typeof t=="object"?dH(t,e):null}function hH(t,e){for(const n of cH)if(t[n]!==void 0){const i=fH(t[n],e);if(i?.trim()){const r=i.trim();return r.length>80?`${r.slice(0,77)}…`:r}}return`Record ${t.id}`}async function gH(t,e){const n=[],r=e.join(",");async function l(u){const d=await t.items.list({filter:{ids:r},nested:!0,version:"current",page:{offset:(u-1)*30,limit:30}});n.push(...d),d.length===30&&await l(u+1)}return await l(1),n}function FC(t,e){if(!t||typeof t!="object")return!1;const n=e.toLowerCase();for(const i in t)if(i.toLowerCase()===n)return!0;return Object.values(t).some(i=>typeof i=="object"&&i!==null?FC(i,e):!1)}function mH(t){if(t===null||typeof t!="object")return;const e=t;return Nm(e,["response","data","errors"])||Nm(e,["response","errors"])||Nm(e,["data","errors"])||(Array.isArray(e.errors)?e.errors:void 0)}function Nm(t,e){let n=t;for(const i of e){if(n===null||typeof n!="object")return;n=n[i]}return Array.isArray(n)?n:void 0}function pH(t){if(t===null||typeof t!="object")return null;const e=t;if(e.attributes&&typeof e.attributes=="object"){const n=e.attributes;if(typeof n.code=="string")return n.code}return typeof e.code=="string"?e.code:null}function yH(t){if(t instanceof Error)return t.message;if(t!==null&&typeof t=="object"){const e=t;if(typeof e.message=="string")return e.message}}function vH(t,e){try{const n=mH(t);if(Array.isArray(n)&&n.map(pH).includes("ITEM_LOCKED"))return`DatoCMS error: Cannot save translations for record ${e}: the record is locked because it is being edited. Please ensure no one (including you in another tab) is editing the record in DatoCMS, then try again.`;if(yH(t)?.includes("ITEM_LOCKED"))return`DatoCMS error: Cannot save translations for record ${e}: the record is locked because it is being edited. Please ensure no one is editing the record, then try again.`}catch{}return null}async function bH(t,e,n,i,r,l,u,d,f,h={},g){const p=T=>{T.status==="processing"&&typeof T.message=="string"&&(T={...T,message:T.message.replace(/\s*fields…$/,"…")}),h.onProgress?.(T)};function v(T,E){for(const[C,O]of Object.entries(E))T[C]={...T[C]??{},...O}}async function b(T,E,C){const O=await l(T.item_type.id),L={},M=[];let N=0;async function D(j){p({recordIndex:E,recordId:T.id,status:"processing",message:`Translating "${C}" (#${T.id}) to ${ga(j)}…`});const K=await _H(T,i,j,O,n,u,f,d.environment,{abortSignal:h.abortSignal,checkCancellation:h.checkCancellation,selectedFieldsByModel:h.selectedFieldsByModel},g,d.cmaBaseUrl);v(L,K.payload),M.push(...K.warnings),N+=K.translatedFieldCount}return await r.reduce((j,K)=>j.then(()=>D(K)),Promise.resolve()),Object.keys(L).length>0&&(p({recordIndex:E,recordId:T.id,status:"processing",message:`Saving "${C}" (#${T.id})…`}),await e.items.update(T.id,L)),{payload:L,translatedFieldCount:N,warnings:M}}function S(T,E,C,O){const L=T.warnings.length>0?` Warnings: ${T.warnings.join(" ")}`:"";if(T.translatedFieldCount===0&&T.warnings.length>0)return p({recordIndex:E,recordId:C,status:"error",message:`No fields were updated for "${O}" (#${C}).${L}`}),"continue";const M=T.translatedFieldCount===0?`No eligible fields to translate for "${O}" (#${C}).`:`Translated "${O}" (#${C}).${L}`;return p({recordIndex:E,recordId:C,status:"completed",message:M}),"done"}async function w(T,E){const C=hH(T,i);if(h.checkCancellation?.())return p({recordIndex:E,recordId:T.id,status:"error",message:`Translation cancelled for "${C}" (#${T.id}).`}),"cancelled";p({recordIndex:E,recordId:T.id,status:"processing",message:`Translating "${C}" (#${T.id})…`});try{if(!FC(T,i)){const L=`Record "${C}" (#${T.id}) does not have the source locale ${ga(i)}`;return console.error(`Record ${T.id} ${L}`),d.alert(`Error: Record ID ${T.id} ${L}`),p({recordIndex:E,recordId:T.id,status:"error",message:L}),"continue"}const O=await b(T,E,C);return S(O,E,T.id,C)}catch(O){const L=vH(O,T.id),M=ta(O,n.vendor),N=na(M),D=O instanceof Error?O.message:String(O);return console.error(`Error translating record ${T.id}:`,D),p({recordIndex:E,recordId:T.id,status:"error",message:L??`Failed "${C}" (#${T.id}): ${N}`}),"continue"}}await t.reduce(async(T,E,C)=>await T==="cancelled"?"cancelled":w(E,C),Promise.resolve("done"))}function $p(t){if(t==null)return t;if(Array.isArray(t))return t.map($p);if(typeof t=="object"){const e=t,n=e.type==="item"&&typeof e.id=="string",i={};for(const[r,l]of Object.entries(e))n&&r==="id"||(i[r]=$p(l));return i}return t}const SH=new Set(["rich_text","structured_text","framed_single_block","frameless_single_block"]);async function _H(t,e,n,i,r,l,u,d,f={},h,g){const p={},v=[];let b=0;const S=rv(t,e),w=Object.keys(t).filter(E=>i[E]?.isLocalized&&wH(E,t,e,i,l,f.selectedFieldsByModel));async function T(E){const C=Wr(t[E],e),O=i[E].editor,L=z2(O);if(ov(O,C))try{const M=await Yl(C,l,n,e,O,r,L,u,i[E].id,d,{abortSignal:f.abortSignal,checkCancellation:f.checkCancellation},S,h,{fieldApiKey:E,...g?{cmaBaseUrl:g}:{}});p[E]={...t[E]||{},[n]:M},b+=1}catch(M){const N=ta(M,r.vendor),D=na(N);console.error(`Error translating field ${E} → ${n} for record ${t.id}: ${D}`);const j=D.endsWith(".")?"":".";v.push(`Field "${E}" to ${ga(n)} was skipped: ${D}${j}`)}}await w.reduce((E,C)=>E.then(()=>T(C)),Promise.resolve());for(const[E,C]of Object.entries(i)){if(!C.isLocalized||p[E])continue;const O=t[E]??{};if(ff(O,n)!==void 0)continue;const M=Wr(O,e),N=ZV(C.validators)&&M!=null,D=SH.has(C.editor);let j=null;N&&D?j=$p(M):N&&(j=M),p[E]={...O,[n]:j}}return{payload:p,translatedFieldCount:b,warnings:v}}function wH(t,e,n,i,r,l){if(["id","creator","meta","type","item_type"].includes(t)||!e[t]||!i[t]?.isLocalized)return!1;const u=i[t];if(!zC(u.editor,u.id,r,t)||!e$(e.item_type.id,t,l))return!1;const d=Wr(e[t],n);return!!ov(u.editor,d)}async function TH(t,e){return k7(t,e)}function EH(t){return t==="completed"?"Completed":t==="processing"?"Processing...":t==="error"?"Error":""}function RH({update:t}){const e=t.message??EH(t.status);return x.jsxs("li",{className:`TranslationProgressModal__update-item TranslationProgressModal__update-item--${t.status}`,children:[x.jsxs("span",{className:"TranslationProgressModal__update-status",children:[t.status==="completed"&&"✓",t.status==="processing"&&x.jsx(cf,{size:16}),t.status==="error"&&"✗"]}),x.jsx("span",{className:"TranslationProgressModal__update-message",children:e})]},t.recordId)}function AH(t,e){return na(ta(t,e??"openai"))}function CH({ctx:t,parameters:e}){const{totalRecords:n,fromLocale:i,toLocales:r,accessToken:l,pluginParams:u,itemIds:d,selectedFieldsByModel:f}=e,[h,g]=A.useState([]),[p,v]=A.useState(!1),b=A.useRef(!1),[S,w]=A.useState(!1),[T,E]=A.useState(!1),C=A.useRef(null),O=A.useRef(null),L=A.useRef(!1),M=A.useCallback(z=>{b.current||g(ee=>[...ee.filter(le=>le.recordIndex!==z.recordIndex),z])},[]);A.useEffect(()=>{let z=!0;return(async()=>{if(!(!z||L.current)){L.current=!0,w(!0);try{const ne=Ip(l,t.environment,t.cmaBaseUrl),le=await gH(ne,d),ue=jr(u),F=M7(ne),W=async ce=>TH(F,ce),ae=new AbortController;C.current=ae,await bH(le,ne,ue,i,r,W,u,t,l,{onProgress:M,checkCancellation:()=>b.current,abortSignal:ae.signal,selectedFieldsByModel:f},F),z&&w(!1)}catch(ne){z&&(E(!0),w(!1),M({recordIndex:-1,recordId:"fatal",status:"error",message:`Translation failed: ${AH(ne,u.vendor)}`}))}}})(),()=>{z=!1}},[l,M,t,i,d,u,f,r]);const N=Object.values(h.reduce((z,ee)=>(z[ee.recordIndex]=ee,z),{})),D=N.filter(z=>z.status==="completed"||z.status==="error").length,j=n>0?Math.round(D/n*100):0;A.useEffect(()=>{D>=n&&n>0&&(v(!0),w(!1))},[D,n]),A.useEffect(()=>{const z=O.current;z&&z.scrollTop<=8&&(z.scrollTop=0)},[]);const K=()=>{const z=T||N.some(ee=>ee.status==="error");t.resolve({completed:p&&!z,canceled:!1,progress:h})},X=()=>{b.current=!0,C.current?.abort(),t.resolve({completed:!1,canceled:!0})};return x.jsx(Un,{ctx:t,children:x.jsxs("div",{className:"TranslationProgressModal",children:[x.jsxs("div",{className:"TranslationProgressModal__intro",children:[x.jsxs("div",{className:"TranslationProgressModal__languages",children:[x.jsxs("div",{className:"TranslationProgressModal__lang-row",children:[x.jsx("span",{className:"TranslationProgressModal__lang-label",children:"From"}),x.jsx(Ud,{locale:i})]}),x.jsxs("div",{className:"TranslationProgressModal__lang-row",children:[x.jsx("span",{className:"TranslationProgressModal__lang-label",children:"To"}),x.jsx("div",{className:"TranslationProgressModal__lang-chips",children:r.map(z=>x.jsx(Ud,{locale:z},z))})]}),x.jsxs("p",{className:"TranslationProgressModal__progress-text",children:["Progress: ",D," of ",n," records processed (",j,"%)"]}),x.jsxs("p",{className:"TranslationProgressModal__stats",children:[N.filter(z=>z.status==="completed").length," ","successful,"," ",N.filter(z=>z.status==="error").length," ","failed"]})]}),x.jsx("div",{className:"TranslationProgressModal__progress-bar",children:x.jsx("div",{className:"TranslationProgressModal__progress-bar-fill",style:{width:`${j}%`}})})]}),x.jsx("div",{className:"TranslationProgressModal__updates",ref:O,"aria-live":"polite",children:h.length>0?x.jsx("ul",{className:"TranslationProgressModal__update-list",children:h.slice().sort((z,ee)=>ee.recordIndex-z.recordIndex).map(z=>x.jsx(RH,{update:z},z.recordId))}):x.jsx("div",{className:"TranslationProgressModal__initializing",children:x.jsxs("div",{className:"TranslationProgressModal__spinner-container",children:[x.jsx(cf,{size:20}),x.jsx("span",{children:"Initializing translation..."})]})})}),x.jsxs("div",{className:"TranslationProgressModal__footer",children:[!p&&S&&x.jsx(wt,{type:"button",buttonType:"negative",onClick:X,buttonSize:"s",children:"Cancel"}),x.jsx(wt,{type:"button",buttonType:"primary",onClick:K,disabled:S&&!p,buttonSize:"s",children:p?"Close":S?"Please wait...":"Close"})]})]})})}var xH=function(e){var n=we.useRef(e);return Ad(function(){n.current=e}),n},oT=function(e,n){if(typeof e=="function"){e(n);return}e.current=n},MH=function(e,n){var i=we.useRef();return we.useCallback(function(r){e.current=r,i.current&&oT(i.current,null),i.current=n,n&&oT(n,r)},[n])},lT={"min-height":"0","max-height":"none",height:"0",visibility:"hidden",overflow:"hidden",position:"absolute","z-index":"-1000",top:"0",right:"0",display:"block"},OH=function(e){Object.keys(lT).forEach(function(n){e.style.setProperty(n,lT[n],"important")})},uT=OH,Qt=null,cT=function(e,n){var i=e.scrollHeight;return n.sizingStyle.boxSizing==="border-box"?i+n.borderSize:i-n.paddingSize};function kH(t,e,n,i){n===void 0&&(n=1),i===void 0&&(i=1/0),Qt||(Qt=document.createElement("textarea"),Qt.setAttribute("tabindex","-1"),Qt.setAttribute("aria-hidden","true"),uT(Qt)),Qt.parentNode===null&&document.body.appendChild(Qt);var r=t.paddingSize,l=t.borderSize,u=t.sizingStyle,d=u.boxSizing;Object.keys(u).forEach(function(v){var b=v;Qt.style[b]=u[b]}),uT(Qt),Qt.value=e;var f=cT(Qt,t);Qt.value=e,f=cT(Qt,t),Qt.value="x";var h=Qt.scrollHeight-r,g=h*n;d==="border-box"&&(g=g+r+l),f=Math.max(g,f);var p=h*i;return d==="border-box"&&(p=p+r+l),f=Math.min(p,f),[f,h]}var dT=function(){},LH=function(e,n){return e.reduce(function(i,r){return i[r]=n[r],i},{})},DH=["borderBottomWidth","borderLeftWidth","borderRightWidth","borderTopWidth","boxSizing","fontFamily","fontSize","fontStyle","fontWeight","letterSpacing","lineHeight","paddingBottom","paddingLeft","paddingRight","paddingTop","tabSize","textIndent","textRendering","textTransform","width","wordBreak","wordSpacing","scrollbarGutter"],BH=!!document.documentElement.currentStyle,NH=function(e){var n=window.getComputedStyle(e);if(n===null)return null;var i=LH(DH,n),r=i.boxSizing;if(r==="")return null;BH&&r==="border-box"&&(i.width=parseFloat(i.width)+parseFloat(i.borderRightWidth)+parseFloat(i.borderLeftWidth)+parseFloat(i.paddingRight)+parseFloat(i.paddingLeft)+"px");var l=parseFloat(i.paddingBottom)+parseFloat(i.paddingTop),u=parseFloat(i.borderBottomWidth)+parseFloat(i.borderTopWidth);return{sizingStyle:i,paddingSize:l,borderSize:u}},IH=NH;function lv(t,e,n){var i=xH(n);A.useLayoutEffect(function(){var r=function(u){return i.current(u)};if(t)return t.addEventListener(e,r),function(){return t.removeEventListener(e,r)}},[])}var PH=function(e,n){lv(document.body,"reset",function(i){e.current.form===i.target&&n(i)})},jH=function(e){lv(window,"resize",e)},zH=function(e){lv(document.fonts,"loadingdone",e)},FH=["cacheMeasurements","maxRows","minRows","onChange","onHeightChange"],UH=function(e,n){var i=e.cacheMeasurements,r=e.maxRows,l=e.minRows,u=e.onChange,d=u===void 0?dT:u,f=e.onHeightChange,h=f===void 0?dT:f,g=JE(e,FH),p=g.value!==void 0,v=A.useRef(null),b=MH(v,n),S=A.useRef(0),w=A.useRef(),T=function(){var O=v.current,L=i&&w.current?w.current:IH(O);if(L){w.current=L;var M=kH(L,O.value||O.placeholder||"x",l,r),N=M[0],D=M[1];S.current!==N&&(S.current=N,O.style.setProperty("height",N+"px","important"),h(N,{rowHeight:D}))}},E=function(O){p||T(),d(O)};return A.useLayoutEffect(T),PH(v,function(){if(!p){var C=v.current.value;requestAnimationFrame(function(){var O=v.current;O&&C!==O.value&&T()})}}),jH(T),zH(T),A.createElement("textarea",Ae({},g,{onChange:E,ref:b}))},VH=A.forwardRef(UH);function $H(t){const e=t.toLowerCase();return!(!e.startsWith("claude")||e.includes("embed"))}function fT(t){const e=t.toLowerCase();let n=0;return e.includes("3.5")&&(n+=1e3),e.includes("haiku")&&(n+=100),e.includes("sonnet")&&(n+=60),e.includes("opus")&&(n+=20),e.endsWith("-latest")&&(n+=30),n}async function qH(t){try{const e=await fetch("https://api.anthropic.com/v1/models",{headers:{"x-api-key":t,"anthropic-version":"2023-06-01"}});if(!e.ok)throw new Error(String(e.status));const n=await e.json(),r=(Array.isArray(n?.data)?n.data:[]).map(u=>u.id).filter(u=>typeof u=="string"&&$H(u));return Array.from(new Set(r)).sort((u,d)=>{const f=fT(d)-fT(u);return f!==0?f:u.localeCompare(d)})}catch(e){return console.error("Failed to fetch Anthropic models:",e),[]}}function UC(t){return t.startsWith("models/")?t.slice(7):t}function GH(t){const e=UC(t.name).toLowerCase();return t.supportedGenerationMethods&&!t.supportedGenerationMethods.includes("generateContent")||["embedding","embed","text-embedding","moderation"].some(i=>e.includes(i))?!1:/^(gemini-)/.test(e)}function hT(t){const e=t.toLowerCase();let n=0;return/^gemini-2\.5/.test(e)?n=1200:/^gemini-2\.0/.test(e)?n=900:/^gemini-1\.5/.test(e)?n=700:/^gemini-1\.0/.test(e)&&(n=500),e.includes("flash")&&(n+=20),e.includes("pro")&&(n+=10),n}async function KH(t){try{const e=await fetch("https://generativelanguage.googleapis.com/v1beta/models",{headers:{"x-goog-api-key":t}});if(!e.ok)throw new Error(`Failed to list Gemini models (${e.status})`);const n=await e.json();return(Array.isArray(n.models)?n.models:[]).filter(GH).map(u=>UC(u.name)).sort((u,d)=>{const f=hT(d)-hT(u);return f!==0?f:u.localeCompare(d)}).filter((u,d,f)=>f.indexOf(u)===d)}catch(e){return console.error("Failed to fetch Gemini models:",e),[]}}function gT(t){const e=t.toLowerCase(),n=/(^|[.-])mini\b/.test(e),i=/(^|[.-])nano\b/.test(e);let r=0;/^gpt-5(\b|[.-])/.test(e)?r=900:/^gpt-4\.1(\b|[.-])/.test(e)?r=500:/^gpt-4o(\b|[.-])/.test(e)?r=450:/^gpt-4-turbo(\b|[.-])/.test(e)?r=400:/^gpt-4(\b|[.-])/.test(e)?r=350:/^gpt-3\.5(\b|[.-])/.test(e)?r=150:/^ft:gpt-/.test(e)?r=125:r=50;let l=r;return n&&(l+=20),i&&(l-=30),/thinking|reasoning/.test(e)&&(l-=60),/preview/.test(e)&&(l-=10),l}function HH(t){const e=t.toLowerCase();return!(!(/^gpt-/.test(e)||/^ft:gpt-/.test(e))||["whisper","tts","audio","speech","dall-e","image","omni-moderation","moderation","text-embedding","embedding","realtime","vision"].some(r=>e.includes(r)))}async function YH(t){const e=new ke({apiKey:t,dangerouslyAllowBrowser:!0}),{data:n}=await e.models.list();return n.map(u=>u.id).filter(HH).sort((u,d)=>{const f=gT(d)-gT(u);return f!==0?f:u.localeCompare(d)}).filter((u,d,f)=>f.indexOf(u)===d)}const XH="_buttons_1ojt3_32",WH="_inlineStatus_1ojt3_89",ZH="_textarea_1ojt3_143",JH="_label_1ojt3_164",QH="_sectionSpacing_1ojt3_192",eY="_buttonRow_1ojt3_196",tY="_exclusionRules_1ojt3_202",nY="_promptContainer_1ojt3_208",aY="_tooltipContainer_1ojt3_216",iY="_warningTooltip_1ojt3_223",sY="_tooltipText_1ojt3_232",rY="_imageTooltip_1ojt3_266",oY="_leftAnchorTooltip_1ojt3_271",Xe={buttons:XH,inlineStatus:WH,textarea:ZH,label:JH,sectionSpacing:QH,buttonRow:eY,exclusionRules:tY,promptContainer:nY,tooltipContainer:aY,warningTooltip:iY,tooltipText:sY,imageTooltip:rY,leftAnchorTooltip:oY};function lY({showExclusionRules:t,setShowExclusionRules:e,hasExclusionRules:n,modelsToBeExcluded:i,setModelsToBeExcluded:r,rolesToBeExcluded:l,setRolesToBeExcluded:u,apiKeysToBeExcluded:d,setApiKeysToBeExcluded:f,availableModels:h,roles:g,listOfFields:p}){return x.jsxs(x.Fragment,{children:[x.jsxs("div",{style:{position:"relative"},children:[x.jsx(Pr,{name:"showExclusionRules",id:"showExclusionRules",label:"Show exclusion rules",value:t,onChange:v=>e(v)}),n&&x.jsxs("div",{className:Xe.warningTooltip,children:["ⓘ",x.jsx("div",{className:Xe.tooltipText,children:"There are exclusion rules present. If the plugin is not being displayed in a model or field where you expect it, please review them."})]})]}),t&&x.jsx("div",{className:Xe.exclusionRules,children:x.jsxs(Ii,{children:[x.jsx(xt,{name:"modelsToBeExcludedFromTranslation",id:"modelsToBeExcludedFromTranslation",label:"Models to be excluded from this plugin",value:i.map(v=>({label:h.find(S=>S.apiKey===v)?.name??v,value:v})),selectInputProps:{isMulti:!0,options:h.map(v=>({label:v.name??"",value:v.apiKey??""}))},onChange:v=>{const b=v.map(S=>S.value);r(b)}}),x.jsx(xt,{name:"rolesToBeExcludedFromTranslation",id:"rolesToBeExcludedFromTranslation",label:"Roles to be excluded from using this plugin",value:l.map(v=>({label:g.find(S=>S.id===v)?.name??v,value:v})),selectInputProps:{isMulti:!0,options:g.map(v=>({label:v.name??"",value:v.id??""}))},onChange:v=>{const b=v.map(S=>S.value);u(b)}}),x.jsx(xt,{name:"apiKeysToBeExcludedFromTranslation",id:"apiKeysToBeExcludedFromTranslation",label:"Fields to be excluded from translation",value:d.map(v=>({label:`${p.find(b=>b.id===v)?.name} (${p.find(b=>b.id===v)?.model})`,value:v})),selectInputProps:{isMulti:!0,options:p.map(v=>({label:`${v.name} (${v.model})`,value:v.id}))},onChange:v=>{const b=v.map(S=>S.value);f(b)}})]})})]})}function uY(t){const[e,n]=A.useState(t.modelsToBeExcludedFromThisPlugin??[]),[i,r]=A.useState(t.rolesToBeExcludedFromThisPlugin??[]),[l,u]=A.useState(t.apiKeysToBeExcludedFromThisPlugin??[]),[d,f]=A.useState(!1),h=A.useMemo(()=>e.length>0||i.length>0||l.length>0,[e,i,l]);A.useEffect(()=>{h&&f(!0)},[h]);const g={modelsToBeExcluded:e,rolesToBeExcluded:i,apiKeysToBeExcluded:l,showExclusionRules:d,hasExclusionRules:h},p={setModelsToBeExcluded:A.useCallback(v=>n(v),[]),setRolesToBeExcluded:A.useCallback(v=>r(v),[]),setApiKeysToBeExcluded:A.useCallback(v=>u(v),[]),setShowExclusionRules:A.useCallback(v=>f(v),[]),resetExclusionRules:A.useCallback(()=>{n([]),r([]),u([])},[])};return[g,p]}function cY(t,e){const[n,i]=A.useState(Array.isArray(t.translationFields)?t.translationFields:Object.keys(Pi)),[r,l]=A.useState(typeof t.translateWholeRecord=="boolean"?t.translateWholeRecord:!0),[u,d]=A.useState(typeof t.translateBulkRecords=="boolean"?t.translateBulkRecords:!0),[f,h]=A.useState(t.prompt??e),[g,p]=A.useState(typeof t.enableDebugging=="boolean"?t.enableDebugging:!1),v={translationFields:n,translateWholeRecord:r,translateBulkRecords:u,prompt:f,enableDebugging:g},b={setTranslationFields:A.useCallback(S=>i(S),[]),setTranslateWholeRecord:A.useCallback(S=>l(S),[]),setTranslateBulkRecords:A.useCallback(S=>d(S),[]),setPrompt:A.useCallback(S=>h(S),[]),setEnableDebugging:A.useCallback(S=>p(S),[]),resetToDefaults:A.useCallback(()=>{i(Object.keys(Pi)),l(!0),d(!0),h(e)},[e])};return[v,b]}function dY(t){return{deeplApiKey:t.deeplApiKey??"",deeplUseFree:t.deeplUseFree??!1,deeplFormality:t.deeplFormality??"default",deeplPreserveFormatting:t.deeplPreserveFormatting??!0,deeplIgnoreTags:t.deeplIgnoreTags??"notranslate,ph",deeplNonSplittingTags:t.deeplNonSplittingTags??"a,code,pre,strong,em,ph,notranslate",deeplSplittingTags:t.deeplSplittingTags??"",deeplGlossaryId:t.deeplGlossaryId??"",deeplGlossaryPairs:t.deeplGlossaryPairs??""}}function fY(t){return{vendor:t.vendor??"openai",apiKey:t.apiKey??"",gptModel:t.gptModel??"None",googleApiKey:t.googleApiKey??"",geminiModel:t.geminiModel??"gemini-2.5-flash",anthropicApiKey:t.anthropicApiKey??"",anthropicModel:t.anthropicModel??"claude-haiku-4-5-latest",...dY(t)}}function hY(t){const e=fY(t),[n,i]=A.useState(e.vendor),[r,l]=A.useState(e.apiKey),[u,d]=A.useState(e.gptModel),[f,h]=A.useState(e.googleApiKey),[g,p]=A.useState(e.geminiModel),[v,b]=A.useState(e.anthropicApiKey),[S,w]=A.useState(e.anthropicModel),[T,E]=A.useState(e.deeplApiKey),[C,O]=A.useState(e.deeplUseFree),[L,M]=A.useState(e.deeplFormality),[N,D]=A.useState(e.deeplPreserveFormatting),[j,K]=A.useState(e.deeplIgnoreTags),[X,z]=A.useState(e.deeplNonSplittingTags),[ee,ne]=A.useState(e.deeplSplittingTags),[le,ue]=A.useState(e.deeplGlossaryId),[F,W]=A.useState(e.deeplGlossaryPairs),ae={vendor:n,apiKey:r,gptModel:u,googleApiKey:f,geminiModel:g,anthropicApiKey:v,anthropicModel:S,deeplApiKey:T,deeplUseFree:C,deeplFormality:L,deeplPreserveFormatting:N,deeplIgnoreTags:j,deeplNonSplittingTags:X,deeplSplittingTags:ee,deeplGlossaryId:le,deeplGlossaryPairs:F},ce={setVendor:A.useCallback($=>i($),[]),setApiKey:A.useCallback($=>l($),[]),setGptModel:A.useCallback($=>d($),[]),setGoogleApiKey:A.useCallback($=>h($),[]),setGeminiModel:A.useCallback($=>p($),[]),setAnthropicApiKey:A.useCallback($=>b($),[]),setAnthropicModel:A.useCallback($=>w($),[]),setDeeplApiKey:A.useCallback($=>E($),[]),setDeeplUseFree:A.useCallback($=>O($),[]),setDeeplFormality:A.useCallback($=>M($),[]),setDeeplPreserveFormatting:A.useCallback($=>D($),[]),setDeeplIgnoreTags:A.useCallback($=>K($),[]),setDeeplNonSplittingTags:A.useCallback($=>z($),[]),setDeeplSplittingTags:A.useCallback($=>ne($),[]),setDeeplGlossaryId:A.useCallback($=>ue($),[]),setDeeplGlossaryPairs:A.useCallback($=>W($),[])};return[ae,ce]}function uv({id:t,label:e,value:n,onChange:i,models:r,hint:l,isLoading:u=!1}){const d=A.useMemo(()=>r.map(g=>({label:g,value:g})),[r]),f=g=>{Array.isArray(g)||i(g?.value||n)},h=u?{label:"Loading models...",value:"Loading models..."}:{label:n,value:n};return x.jsx(xt,{name:t,id:t,label:e,required:!0,hint:l,placeholder:u?"Loading models...":void 0,value:h,selectInputProps:{isDisabled:u,isLoading:u,options:d},onChange:f})}function gY({anthropicApiKey:t,setAnthropicApiKey:e,anthropicModel:n,setAnthropicModel:i,listOfAnthropicModels:r}){return x.jsxs(Ii,{children:[x.jsx(vs,{required:!0,name:"anthropicApiKey",id:"anthropicApiKey",label:"Anthropic API Key",value:t,onChange:l=>e(l),placeholder:"sk-ant-..."}),x.jsx(uv,{id:"anthropicModel",label:"Claude Model",hint:"Recommended: claude-haiku-4-5-latest",value:n,onChange:i,models:r})]})}let mT=0;function mY(t){if(!t.trim())return[];const e=t.split(/\r?\n|[;,]+/).map(i=>i.trim()).filter(Boolean),n=[];for(const i of e){const l=i.replace(/[→⇒–—]/g,"->").replace(/\s+/g,"").match(/^([a-zA-Z*]{1,5}(?:-[a-zA-Z]{2,4})?)->([a-zA-Z*]{1,5}(?:-[a-zA-Z]{2,4})?)(?:=|:)([\w-]+)$/);l&&n.push({source:l[1],target:l[2],glossaryId:l[3]})}return n}function pY(t){return t.filter(e=>e.source&&e.target&&e.glossaryId).map(e=>`${e.source}->${e.target}=${e.glossaryId}`).join(`
|
|
79
79
|
`)}function VC(t){return mT+=1,{...t,rowId:`glossary-row-${mT}`}}function pT(t){return mY(t).map(VC)}function yY({value:t,onChange:e,siteLocales:n,glossaries:i,fetchStatus:r,fetchError:l,openConfirm:u}){const[d,f]=A.useState(()=>pT(t)),h=A.useRef(t);A.useEffect(()=>{t!==h.current&&(h.current=t,f(pT(t)))},[t]);const g=A.useCallback(M=>{f(M);const N=pY(M);h.current=N,e(N)},[e]),p=A.useMemo(()=>[{label:"All (*)",value:"*"},...n.map(M=>({label:M,value:M}))],[n]),v=A.useMemo(()=>i.map(M=>({label:`${M.name} (${M.source_lang}→${M.target_lang}, ${M.entry_count} entries)`,value:M.glossary_id})),[i]),b=A.useMemo(()=>new Set(i.map(M=>M.glossary_id)),[i]),S=A.useMemo(()=>new Set(n),[n]);function w(M){if(!(!M||M==="*")&&n.length>0&&!S.has(M))return`"${M}" is not a locale in this project`}function T(M){if(M&&r==="success"&&!b.has(M))return`"${M}" is not a valid glossary in your DeepL account`}const E=(M,N)=>{const D=d.map((j,K)=>K===M?{...j,...N}:j);g(D)},C=M=>{g(d.filter((N,D)=>D!==M))},O=async M=>{const N=d[M];if(!(N.source||N.target||N.glossaryId)){C(M);return}const j=N.source||"?",K=N.target||"?",X=i.find(ne=>ne.glossary_id===N.glossaryId),z=X?X.name:N.glossaryId||"?";await u({title:"Remove glossary?",content:`Are you sure you wish to remove the glossary from ${j} to ${K} using the glossary "${z}"?`,choices:[{label:"Remove",value:!0,intent:"negative"}],cancel:{label:"Cancel",value:!1}})&&C(M)},L=()=>{g([...d,VC({source:"",target:"",glossaryId:""})])};return x.jsxs("div",{children:[x.jsx("div",{style:{display:"flex",alignItems:"center",marginBottom:8},children:x.jsxs("label",{className:Xe.label,style:{display:"flex",alignItems:"center",margin:0},children:["Glossaries by language pair",x.jsxs("div",{className:Xe.tooltipContainer,children:["ⓘ",x.jsx("div",{className:`${Xe.tooltipText} ${Xe.leftAnchorTooltip}`,children:'Map specific language pairs to DeepL glossaries. Use "All (*)" as a wildcard to match any source or target locale.'})]})]})}),r==="error"&&l&&x.jsx("div",{className:Xe.inlineStatus,style:{color:"var(--color--ink-danger)",marginBottom:8},children:l}),d.map((M,N)=>{const D=w(M.source),j=w(M.target),K=T(M.glossaryId),X=M.glossaryId?v.find(ne=>ne.value===M.glossaryId)??{label:M.glossaryId,value:M.glossaryId}:null,z=M.source?p.find(ne=>ne.value===M.source)??{label:M.source,value:M.source}:null,ee=M.target?p.find(ne=>ne.value===M.target)??{label:M.target,value:M.target}:null;return x.jsxs("div",{style:{display:"flex",gap:8,alignItems:"start",marginBottom:8},children:[x.jsxs("div",{style:{flex:1,minWidth:0,border:"1px solid var(--color--border)",borderRadius:4,padding:"10px 12px"},children:[x.jsxs("div",{style:{display:"flex",gap:8},children:[x.jsx("div",{style:{flex:1,minWidth:0},children:x.jsx(xt,{id:`glossarySource-${N}`,name:`glossarySource-${N}`,label:"From",placeholder:"Source",value:z,error:D,selectInputProps:{options:p},onChange:ne=>{Array.isArray(ne)||E(N,{source:ne?.value??""})}})}),x.jsx("div",{style:{flex:1,minWidth:0},children:x.jsx(xt,{id:`glossaryTarget-${N}`,name:`glossaryTarget-${N}`,label:"To",placeholder:"Target",value:ee,error:j,selectInputProps:{options:p},onChange:ne=>{Array.isArray(ne)||E(N,{target:ne?.value??""})}})})]}),x.jsx("div",{style:{marginTop:6},children:x.jsx(xt,{id:`glossaryId-${N}`,name:`glossaryId-${N}`,label:"Glossary",placeholder:r==="loading"?"Loading glossaries...":"Select glossary",value:X,error:K,selectInputProps:{options:v,isLoading:r==="loading"},onChange:ne=>{Array.isArray(ne)||E(N,{glossaryId:ne?.value??""})}})})]}),x.jsx("div",{style:{paddingTop:24,flexShrink:0},children:x.jsx(wt,{type:"button",buttonType:"negative",buttonSize:"xxs",onClick:()=>O(N),children:"×"})})]},M.rowId)}),x.jsx("div",{style:{display:"flex",gap:8,marginTop:8},children:x.jsx(wt,{type:"button",buttonType:"muted",buttonSize:"xs",onClick:L,children:"+ Add language pair"})})]})}const vY="https://cors-proxy.datocms.com";async function bY(t,e){const r=`${vY}/?url=${encodeURIComponent(`${e?"https://api-free.deepl.com":"https://api.deepl.com"}/v2/glossaries`)}`,l=await fetch(r,{method:"GET",headers:{Authorization:`DeepL-Auth-Key ${t}`}}),u=await l.json(),d=u&&typeof u=="object"?u:null;return d&&typeof d.message=="string"?{kind:"error",message:`Could not load glossaries: ${d.message}`}:l.ok?!d||!Array.isArray(d.glossaries)?{kind:"error",message:"Unexpected response from DeepL glossaries endpoint."}:{kind:"success",glossaries:d.glossaries.filter(h=>h.ready)}:{kind:"error",message:`Could not load glossaries (HTTP ${l.status}). Check your API key.`}}function SY(t,e){const[n,i]=A.useState([]),[r,l]=A.useState("idle"),[u,d]=A.useState(""),f=A.useRef(""),h=A.useRef(null),g=A.useCallback(async()=>{if(!t){i([]),l("idle");return}const p=`${t}:${e}`,v=p===f.current,b=p===h.current;if(!(v||b)){h.current=p,l("loading"),d("");try{const S=await bY(t,e);S.kind==="success"?(i(S.glossaries),l("success"),f.current=p):(i([]),l("error"),d(S.message),f.current="")}catch(S){i([]),l("error"),d(S instanceof Error?S.message:"Failed to fetch glossaries."),f.current=""}finally{h.current=null}}},[t,e]);return A.useEffect(()=>{const p=`${t}:${e}`;t&&p!==f.current&&g()},[t,e,g]),{glossaries:n,fetchStatus:r,fetchError:u,refetch:g}}function _Y(t){return t?"https://api-free.deepl.com":"https://api.deepl.com"}function wY(t){return t&&typeof t=="object"?t:null}async function TY(t,e){const n=`${_Y(e)}/v2/translate`,i=`https://cors-proxy.datocms.com/?url=${encodeURIComponent(n)}`,r=await fetch(i,{method:"POST",headers:{"content-type":"application/json",Authorization:`DeepL-Auth-Key ${t}`},body:JSON.stringify({text:["Hello world"],target_lang:"DE"})});try{return{body:wY(await r.json()),parseFailed:!1,status:r.status,ok:r.ok}}catch{return{body:null,parseFailed:!0,status:r.status,ok:r.ok}}}function EY(t){if(!t||typeof t.message!="string")return;const e=t.message.toLowerCase();return e.includes("wrong endpoint")?'Your API key requires the DeepL Free endpoint. Enable "Use DeepL Free endpoint (api-free.deepl.com)" below, then try again.':e.includes("forbidden")?"The DeepL API key is invalid. Please check that you entered the correct key.":`DeepL error: ${t.message}`}function RY(t){const e=t?.translations;return!Array.isArray(e)||e.length===0||typeof e[0]?.text!="string"?null:e[0].text}function AY(t){return t?`API Key OK. DeepL responded: ${t.slice(0,aT)}${t.length>aT?"…":""}`:"API Key OK. DeepL responded (empty body)."}function CY(t){if(t.parseFailed)return{status:"error",message:`DeepL returned a non-JSON response (HTTP ${t.status}).`};const e=EY(t.body);if(e)return{status:"error",message:e};if(!t.ok)return{status:"error",message:`DeepL returned an error (HTTP ${t.status}). Verify your API key and endpoint settings.`};const n=RY(t.body);return n===null?{status:"error",message:"DeepL returned an unexpected response. The API key or endpoint may be misconfigured."}:{status:"success",message:AY(n)}}async function xY(t,e){return CY(await TY(t,e))}function MY({deeplApiKey:t,setDeeplApiKey:e,deeplUseFree:n,setDeeplUseFree:i,deeplFormality:r,setDeeplFormality:l,deeplPreserveFormatting:u,setDeeplPreserveFormatting:d,deeplIgnoreTags:f,setDeeplIgnoreTags:h,deeplNonSplittingTags:g,setDeeplNonSplittingTags:p,deeplSplittingTags:v,setDeeplSplittingTags:b,deeplGlossaryId:S,setDeeplGlossaryId:w,deeplGlossaryPairs:T,setDeeplGlossaryPairs:E,siteLocales:C,openConfirm:O}){const[L,M]=A.useState(!1),[N,D]=A.useState(!1),[j,K]=A.useState(!1),[X,z]=A.useState(""),[ee,ne]=A.useState("idle"),[le,ue]=A.useState(!1),{glossaries:F,fetchStatus:W,fetchError:ae}=SY(t,n),ce=A.useMemo(()=>F.map(Q=>({label:`${Q.name} (${Q.source_lang}→${Q.target_lang}, ${Q.entry_count} entries)`,value:Q.glossary_id})),[F]),$=S?ce.find(Q=>Q.value===S)??{label:S,value:S}:null,k=S&&W==="success"&&!F.some(Q=>Q.glossary_id===S)?`"${S}" is not a valid glossary in your DeepL account`:void 0,V=Q=>{e(Q),ee==="error"&&(ne("idle"),z("")),Q.endsWith(":fx")&&!n?(i(!0),ue(!0)):!Q.endsWith(":fx")&&le&&ue(!1)},re=async()=>{if(!t){ne("error"),z("Enter a DeepL API Key first.");return}z(""),ne("idle"),K(!0);try{const Q=await xY(t,n);ne(Q.status),z(Q.message)}catch(Q){ne("error"),z(Q instanceof Error?Q.message:"An unexpected error occurred while testing the API key.")}finally{K(!1)}};return x.jsxs(x.Fragment,{children:[x.jsxs(Ii,{children:[x.jsx(vs,{required:!0,name:"deeplApiKey",id:"deeplApiKey",label:"DeepL API Key",value:t,onChange:V,placeholder:"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:fx",error:ee==="error"?X:void 0}),x.jsx("div",{className:Xe.buttonRow,children:x.jsx(wt,{buttonType:"muted",disabled:j,onClick:re,children:j?"Testing…":"Test API Key"})}),ee==="success"&&X&&x.jsx("div",{className:Xe.inlineStatus,style:{color:"var(--color--ink-success)"},children:X}),x.jsx(Pr,{name:"deeplUseFree",id:"deeplUseFree",label:"Use DeepL Free endpoint (api-free.deepl.com)",hint:le?"We toggled this on automatically for you because it looks like you're using a free key ending in :fx":"You must use this if you're on the DeepL free plan",value:n,onChange:Q=>i(Q)}),x.jsx(xt,{name:"deeplFormality",id:"deeplFormality",label:"Formality",value:{label:r,value:r},selectInputProps:{options:[{label:"default",value:"default"},{label:"more",value:"more"},{label:"less",value:"less"}]},onChange:Q=>{if(!Array.isArray(Q)){const fe=Q;fe?.value&&l(fe.value)}}})]}),x.jsx("div",{className:Xe.sectionSpacing,children:x.jsx(Sd,{title:"Tag Settings",collapsible:{isOpen:L,onToggle:()=>M(Q=>!Q)},children:x.jsxs(Ii,{children:[x.jsx(Pr,{name:"deeplPreserveFormatting",id:"deeplPreserveFormatting",label:"Preserve formatting",value:u,onChange:d}),x.jsx(vs,{name:"deeplIgnoreTags",id:"deeplIgnoreTags",label:"Ignore tags (CSV)",value:f,onChange:h}),x.jsx(vs,{name:"deeplNonSplittingTags",id:"deeplNonSplittingTags",label:"Non-splitting tags (CSV)",value:g,onChange:p}),x.jsx(vs,{name:"deeplSplittingTags",id:"deeplSplittingTags",label:"Splitting tags (CSV)",value:v,onChange:b})]})})}),x.jsx("div",{className:Xe.sectionSpacing,children:x.jsx(Sd,{title:"Glossary Settings",collapsible:{isOpen:N,onToggle:()=>D(Q=>!Q)},children:x.jsxs(Ii,{children:[x.jsx(xt,{name:"deeplGlossaryId",id:"deeplGlossaryId",label:"Default glossary",hint:"Applied to all translations unless overridden by a language pair mapping below",placeholder:W==="loading"?"Loading glossaries...":"None (no default glossary)",value:$,error:k,selectInputProps:{options:ce,isClearable:!0,isLoading:W==="loading"},onChange:Q=>{Array.isArray(Q)||w(Q?.value??"")}}),W==="error"&&ae&&x.jsx("div",{className:Xe.inlineStatus,style:{color:"var(--color--ink-danger)"},children:ae}),x.jsx(yY,{value:T,onChange:E,siteLocales:C,glossaries:F,fetchStatus:W,fetchError:ae,openConfirm:O})]})})})]})}function OY({googleApiKey:t,setGoogleApiKey:e,geminiModel:n,setGeminiModel:i,listOfGeminiModels:r}){return x.jsxs(Ii,{children:[x.jsx(vs,{required:!0,name:"googleApiKey",id:"googleApiKey",label:"Google API Key",value:t,onChange:l=>e(l),placeholder:"AIza..."}),x.jsx(uv,{id:"geminiModel",label:"Gemini Model",hint:"Recommended: gemini-2.5-flash",value:n,onChange:i,models:r})]})}function kY({apiKey:t,setApiKey:e,gptModel:n,setGptModel:i,listOfModels:r,isModelListLoading:l}){return x.jsxs(Ii,{children:[x.jsx(vs,{required:!0,name:"openAIAPIKey",id:"openAIAPIKey",label:"OpenAI API Key",value:t,onChange:u=>e(u),placeholder:"sk-..."}),x.jsx(uv,{id:"gptModel",label:"GPT Model",hint:"Recommended: gpt-5.4-mini",value:n,onChange:i,models:r,isLoading:l})]})}const LY=["openai","google","anthropic","deepl"];function DY(t){if(!t||typeof t!="object")return!1;const e=t;return!(typeof e.gptModel!="string"||typeof e.apiKey!="string"||typeof e.prompt!="string"||typeof e.translateWholeRecord!="boolean"||typeof e.enableDebugging!="boolean"||!Array.isArray(e.translationFields)||!Array.isArray(e.modelsToBeExcludedFromThisPlugin)||!Array.isArray(e.rolesToBeExcludedFromThisPlugin)||!Array.isArray(e.apiKeysToBeExcludedFromThisPlugin)||e.vendor!==void 0&&!LY.includes(e.vendor))}async function BY(t,e,n,i){try{const r=await YH(t);e(r.length>0?r:["No compatible models found"]),r.length>0&&(i==="None"||!i)&&n(r[0])}catch(r){console.error("Error fetching OpenAI models:",r),e(["Invalid API Key"]),n("None")}}async function NY(t,e,n,i,r){if(t==="google"){if(!e){n(["Insert a valid Google API Key"]);return}try{const l=await KH(e);n(l.length>0?l:["No compatible models found"]),l.length>0&&!r&&i(l[0])}catch(l){console.error("Error fetching Gemini models:",l),n(["Invalid API Key"])}}}async function IY(t,e,n,i,r){if(t==="anthropic"){if(!e){n(["Insert a valid Anthropic API Key"]);return}try{const l=await qH(e);n(l.length>0?l:["No compatible models found"]),l.length>0&&!r&&i(l[0])}catch(l){console.error("Error fetching Claude models:",l),n(["Invalid API Key"])}}}function PY(t,e){const n=new Set(t.map(r=>r.id)),i=e.filter(r=>!n.has(r.id));return[...t,...i]}function jY(t,e,n){e.loadItemTypeFields(t).then(i=>{n(r=>{const l=e.itemTypes[t],u=l?.attributes.modular_block,d=l?.attributes.name,f=i.map(h=>({id:h.id,name:h.attributes.label,model:u?`${d} block`:d??""}));return PY(r,f)})}).catch(i=>{console.error(`Failed to load fields for item type ${t}:`,i)})}const zY=async({ctx:t,params:e,setIsLoading:n})=>{n(!0);try{await t.updatePluginParameters(e),t.notice("Plugin options updated successfully!").then()}catch(i){console.error("Error updating plugin parameters:",i),t.alert("Failed to update plugin options. Please try again.")}finally{n(!1)}};function FY(t,e,n,i,r,l,u,d){return t==="openai"?n==="None"||!e:t==="google"?!i||!r:t==="anthropic"?!l||!u:t==="deepl"?!d:!1}function UY(t,e,n,i,r,l,u){return[...t].sort().join(",")===Object.keys(Pi).sort().join(",")&&e===!0&&n===!0&&i===Ml&&r.length===0&&l.length===0&&u.length===0}function yT(t){return t==="openai"?"OpenAI (ChatGPT)":t==="google"?"Google (Gemini)":t==="anthropic"?"Anthropic (Claude)":"DeepL"}function VY(t){const e=Array.isArray(t)?t[0]:t;if(!e||typeof e!="object"||!("value"in e))return;const n=e.value;if(n==="openai"||n==="google"||n==="anthropic"||n==="deepl")return n}function $Y(t){const{vendor:e,apiKey:n,googleApiKey:i,geminiModel:r,anthropicApiKey:l,anthropicModel:u,gptModel:d,deeplUseFree:f,deeplFormality:h,deeplPreserveFormatting:g,deeplIgnoreTags:p,deeplNonSplittingTags:v,deeplSplittingTags:b,deeplApiKey:S,deeplGlossaryId:w,deeplGlossaryPairs:T,translationFields:E,translateWholeRecord:C,translateBulkRecords:O,prompt:L,enableDebugging:M,modelsToBeExcluded:N,rolesToBeExcluded:D,apiKeysToBeExcluded:j,pluginParams:K,normalizeList:X}=t,z=[...E].sort().join(","),ee=K.translationFields?[...K.translationFields].sort().join(","):Object.keys(Pi).sort().join(","),ne=qY({vendor:e,apiKey:n,googleApiKey:i,geminiModel:r,anthropicApiKey:l,anthropicModel:u,gptModel:d},K),le=GY({deeplUseFree:f,deeplFormality:h,deeplPreserveFormatting:g,deeplIgnoreTags:p,deeplNonSplittingTags:v,deeplSplittingTags:b,deeplApiKey:S,deeplGlossaryId:w,deeplGlossaryPairs:T},K),ue=z!==ee||C!==(K.translateWholeRecord??!0)||O!==(K.translateBulkRecords??!0)||L!==(K.prompt??Ml)||M!==(K.enableDebugging??!1),F=[...N].sort().join(",")!==X(K.modelsToBeExcludedFromThisPlugin)||[...D].sort().join(",")!==X(K.rolesToBeExcludedFromThisPlugin)||[...j].sort().join(",")!==X(K.apiKeysToBeExcludedFromThisPlugin);return ne||le||ue||F}function qY(t,e){return t.vendor!==(e.vendor??"openai")||t.apiKey!==(e.apiKey??"")||t.googleApiKey!==(e.googleApiKey??"")||t.geminiModel!==(e.geminiModel??"gemini-2.5-flash")||t.anthropicApiKey!==(e.anthropicApiKey??"")||t.anthropicModel!==(e.anthropicModel??"claude-haiku-4-5-latest")||t.gptModel!==(e.gptModel??"None")}function GY(t,e){return t.deeplUseFree!==(e.deeplUseFree??!1)||t.deeplFormality!==(e.deeplFormality??"default")||t.deeplPreserveFormatting!==(e.deeplPreserveFormatting??!0)||t.deeplIgnoreTags!==(e.deeplIgnoreTags??"notranslate,ph")||t.deeplNonSplittingTags!==(e.deeplNonSplittingTags??"a,code,pre,strong,em,ph,notranslate")||t.deeplSplittingTags!==(e.deeplSplittingTags??"")||t.deeplApiKey!==(e.deeplApiKey??"")||t.deeplGlossaryId!==(e.deeplGlossaryId??"")||t.deeplGlossaryPairs!==(e.deeplGlossaryPairs??"")}function KY({ctx:t}){const e=t.plugin.attributes.parameters,[n,i]=hY(e),[r,l]=cY(e,Ml),[u,d]=uY(e),{vendor:f,apiKey:h,gptModel:g,googleApiKey:p,geminiModel:v,anthropicApiKey:b,anthropicModel:S,deeplApiKey:w,deeplUseFree:T,deeplFormality:E,deeplPreserveFormatting:C,deeplIgnoreTags:O,deeplNonSplittingTags:L,deeplSplittingTags:M,deeplGlossaryId:N,deeplGlossaryPairs:D}=n,{setVendor:j,setApiKey:K,setGptModel:X,setGoogleApiKey:z,setGeminiModel:ee,setAnthropicApiKey:ne,setAnthropicModel:le,setDeeplApiKey:ue,setDeeplUseFree:F,setDeeplFormality:W,setDeeplPreserveFormatting:ae,setDeeplIgnoreTags:ce,setDeeplNonSplittingTags:$,setDeeplSplittingTags:k,setDeeplGlossaryId:V,setDeeplGlossaryPairs:re}=i,{translationFields:Q,translateWholeRecord:fe,translateBulkRecords:de,prompt:be,enableDebugging:Le}=r,{setTranslationFields:Ne,setTranslateWholeRecord:Rn,setTranslateBulkRecords:ra,setPrompt:Ma,setEnableDebugging:Ms}=l,{modelsToBeExcluded:$t,rolesToBeExcluded:Gn,apiKeysToBeExcluded:Oa,showExclusionRules:Nf,hasExclusionRules:Ql}=u,{setModelsToBeExcluded:Os,setRolesToBeExcluded:ks,setApiKeysToBeExcluded:Ls,setShowExclusionRules:If}=d,[ro,Xt]=A.useState(!1),[Pf,$i]=A.useState(!1),ii=A.useRef(0),qi=A.useRef(g),[eu,Ds]=A.useState(["Insert a valid OpenAI API Key"]),[jf,zf]=A.useState(["Insert a valid Google API Key"]),[Gi,Wt]=A.useState(["Insert a valid Anthropic API Key"]),[oa,Zt]=A.useState([]);A.useEffect(()=>{qi.current=g},[g]),A.useEffect(()=>{if(!(f!=="openai"||!h))for(const Be in t.itemTypes)jY(Be,t,Zt)},[t,h,f]),A.useEffect(()=>{ii.current+=1;const Be=ii.current;if(f!=="openai"){$i(!1);return}if(!h){$i(!1),Ds(["Insert a valid OpenAI API Key"]),X("None");return}$i(!0),Ds(["Loading models..."]),BY(h,lt=>{ii.current===Be&&Ds(lt)},lt=>{ii.current===Be&&X(lt)},qi.current).catch(console.error).finally(()=>{ii.current===Be&&$i(!1)})},[h,f,X]),A.useEffect(()=>{NY(f,p,zf,ee,e.geminiModel).catch(console.error)},[f,p,e.geminiModel,ee]),A.useEffect(()=>{IY(f,b,Wt,le,e.anthropicModel).catch(console.error)},[f,b,e.anthropicModel,le]);const tu=A.useCallback(Be=>Array.isArray(Be)?[...Be].sort().join(","):"",[]),Ff=A.useMemo(()=>$Y({vendor:f,apiKey:h,googleApiKey:p,geminiModel:v,anthropicApiKey:b,anthropicModel:S,gptModel:g,deeplUseFree:T,deeplFormality:E,deeplPreserveFormatting:C,deeplIgnoreTags:O,deeplNonSplittingTags:L,deeplSplittingTags:M,deeplApiKey:w,deeplGlossaryId:N,deeplGlossaryPairs:D,translationFields:Q,translateWholeRecord:fe,translateBulkRecords:de,prompt:be,enableDebugging:Le,modelsToBeExcluded:$t,rolesToBeExcluded:Gn,apiKeysToBeExcluded:Oa,pluginParams:e,normalizeList:tu}),[f,h,p,v,b,S,g,Q,fe,de,be,T,E,C,O,L,M,w,N,D,$t,Gn,Oa,Le,tu,e]),Uf=A.useMemo(()=>Object.entries(t.itemTypes).map(([Be,lt])=>({apiKey:lt?.attributes.api_key,name:lt?.attributes.name,isBlock:lt?.attributes.modular_block})).filter(Be=>!Be.isBlock),[t.itemTypes]),[Bs,Ns]=A.useState([]),[Is]=A.useState(t.site.attributes.locales);A.useEffect(()=>{Cf({apiToken:t.currentUserAccessToken,environment:t.environment,baseUrl:t.cmaBaseUrl}).roles.list().then(lt=>{Ns(lt.map(Ps=>({id:Ps.id,name:Ps.name})))})},[t.currentUserAccessToken,t.environment,t.cmaBaseUrl]);const ka=FY(f,h,g,p,v,b,S,w)||UY(Q,fe,de,be,$t,Gn,Oa);return x.jsx(Un,{ctx:t,children:x.jsxs("div",{children:[x.jsx(xt,{name:"vendor",id:"vendor",label:"AI Vendor",value:{label:yT(f),value:f},selectInputProps:{options:[{label:"OpenAI (ChatGPT)",value:"openai"},{label:"Google (Gemini)",value:"google"},{label:"Anthropic (Claude)",value:"anthropic"},{label:"DeepL",value:"deepl"}]},onChange:Be=>{const lt=VY(Be);lt&&j(lt)}}),x.jsx("div",{className:Xe.sectionSpacing,children:x.jsx(Sd,{title:`Vendor-specific settings for ${yT(f)}`,children:f==="openai"?x.jsx(kY,{apiKey:h,setApiKey:K,gptModel:g,setGptModel:X,listOfModels:eu,isModelListLoading:Pf}):f==="google"?x.jsx(OY,{googleApiKey:p,setGoogleApiKey:z,geminiModel:v,setGeminiModel:ee,listOfGeminiModels:jf}):f==="anthropic"?x.jsx(gY,{anthropicApiKey:b,setAnthropicApiKey:ne,anthropicModel:S,setAnthropicModel:le,listOfAnthropicModels:Gi}):x.jsx(MY,{deeplApiKey:w,setDeeplApiKey:ue,deeplUseFree:T,setDeeplUseFree:F,deeplFormality:E,setDeeplFormality:W,deeplPreserveFormatting:C,setDeeplPreserveFormatting:ae,deeplIgnoreTags:O,setDeeplIgnoreTags:ce,deeplNonSplittingTags:L,setDeeplNonSplittingTags:$,deeplSplittingTags:M,setDeeplSplittingTags:k,deeplGlossaryId:N,setDeeplGlossaryId:V,deeplGlossaryPairs:D,setDeeplGlossaryPairs:re,siteLocales:Is,openConfirm:t.openConfirm})})}),x.jsx("div",{className:Xe.sectionSpacing,children:x.jsxs(Sd,{title:"General translation settings",children:[f!=="deepl"&&x.jsxs("div",{className:Xe.promptContainer,children:[x.jsxs("label",{className:Xe.label,style:{display:"flex",alignItems:"center"},htmlFor:"translation-prompt",children:["Translation prompt*",x.jsxs("div",{className:Xe.tooltipContainer,children:["ⓘ",x.jsx("div",{className:`${Xe.tooltipText} ${Xe.leftAnchorTooltip}`,children:"Use {fieldValue}, {fromLocale}, and {toLocale} in your prompt to reference the content and source/target languages. Changing the prompt can break the plugin, so proceed with caution."})]})]}),x.jsx(VH,{required:!0,className:Xe.textarea,placeholder:"Enter your prompt here",value:be,onChange:Be=>Ma(Be.target.value),id:"translation-prompt","aria-labelledby":"translation-prompt"})]}),x.jsx(xt,{name:"fieldsWithTranslationOption",id:"fieldsWithTranslationOption",label:"Fields that can be translated",value:Q.map(Be=>({label:Pi[Be],value:Be})),selectInputProps:{isMulti:!0,options:Object.entries(Pi).map(([Be,lt])=>({label:lt,value:Be}))},onChange:Be=>{const lt=Be.map(Ps=>Ps.value);Ne(lt)}}),x.jsxs(Ii,{children:[x.jsxs("div",{style:{display:"flex",alignItems:"center"},children:[x.jsx(Pr,{name:"translateWholeRecord",id:"translateWholeRecord",label:"Allow translation of the whole record from the sidebar",value:fe,onChange:Be=>Rn(Be)}),x.jsxs("div",{className:Xe.tooltipContainer,children:[x.jsx("span",{role:"img","aria-label":"Information about sidebar translation",children:"ⓘ"}),x.jsxs("div",{className:`${Xe.tooltipText} ${Xe.imageTooltip}`,children:[x.jsx("img",{src:"/public/assets/sidebar-translation-example.png",alt:"Screenshot showing the sidebar translation feature with locale selection and translate button",style:{width:"100%",maxWidth:"420px"}}),x.jsx("div",{style:{marginTop:"10px",fontWeight:"bold"},children:"Sidebar Translation"}),x.jsx("div",{style:{fontSize:"12px"},children:"Translate an entire record from the sidebar panel"})]})]})]}),x.jsxs("div",{style:{display:"flex",alignItems:"center"},children:[x.jsx(Pr,{name:"translateBulkRecords",id:"translateBulkRecords",label:"Allow bulk records translation in tabular view",value:de,onChange:Be=>ra(Be)}),x.jsxs("div",{className:Xe.tooltipContainer,children:[x.jsx("span",{role:"img","aria-label":"Information about bulk translation",children:"ⓘ"}),x.jsxs("div",{className:`${Xe.tooltipText} ${Xe.imageTooltip}`,children:[x.jsx("img",{src:"/public/assets/bulk-translation-example.png",alt:"Screenshot showing bulk translation of multiple records in tabular view",style:{width:"100%",maxWidth:"420px"}}),x.jsx("div",{style:{marginTop:"10px",fontWeight:"bold"},children:"Bulk Translation"}),x.jsx("div",{style:{fontSize:"12px"},children:"Translate multiple records at once in the tabular view"})]})]})]}),x.jsxs("div",{style:{display:"flex",alignItems:"center"},children:[x.jsx(Pr,{name:"enableDebugging",id:"enableDebugging",label:"Enable debug logging",value:Le,onChange:Be=>Ms(Be)}),x.jsxs("div",{className:Xe.tooltipContainer,children:["ⓘ",x.jsx("div",{className:Xe.tooltipText,children:"When enabled, detailed logs of translation requests and responses will be displayed in the browser console. This helps with troubleshooting and understanding how the plugin processes content."})]})]})]}),x.jsx(lY,{showExclusionRules:Nf,setShowExclusionRules:If,hasExclusionRules:Ql,modelsToBeExcluded:$t,setModelsToBeExcluded:Os,rolesToBeExcluded:Gn,setRolesToBeExcluded:ks,apiKeysToBeExcluded:Oa,setApiKeysToBeExcluded:Ls,availableModels:Uf,roles:Bs,listOfFields:oa})]})}),x.jsxs("div",{className:Xe.buttons,children:[x.jsx(wt,{fullWidth:!0,disabled:ka,buttonType:"muted",onClick:()=>{j("openai");const Be=eu[0];X(Be&&Be!=="Insert a valid OpenAI API Key"&&Be!=="Invalid API Key"?Be:"None"),Ne(Object.keys(Pi)),Rn(!0),ra(!0),Ma(Ml),Os([]),ks([]),Ls([]),t.notice(`<h1>Plugin options restored to defaults</h1>
|
|
80
80
|
<p>Save to apply changes</p>`)},children:"Restore to defaults"}),x.jsxs(wt,{disabled:!Ff||ro,fullWidth:!0,buttonType:"primary",onClick:()=>zY({ctx:t,params:{vendor:f,apiKey:h,gptModel:g,googleApiKey:p,geminiModel:v,anthropicApiKey:b,anthropicModel:S,deeplApiKey:w,deeplEndpoint:e.deeplEndpoint??"auto",deeplUseFree:T,deeplFormality:E,deeplPreserveFormatting:C,deeplIgnoreTags:O,deeplNonSplittingTags:L,deeplSplittingTags:M,deeplGlossaryId:N,deeplGlossaryPairs:D,translationFields:Q,translateWholeRecord:fe,translateBulkRecords:de,prompt:be,modelsToBeExcludedFromThisPlugin:$t,rolesToBeExcludedFromThisPlugin:Gn,apiKeysToBeExcludedFromThisPlugin:Oa,enableDebugging:Le},setIsLoading:Xt}),children:[ro?"Saving...":"Save",ro&&x.jsx(cf,{size:24})]})]})]})})}const HY="_page_boh28_1",YY="_container_boh28_12",XY="_card_boh28_17",WY="_cardHeader_boh28_39",ZY="_cardTitle_boh28_45",JY="_cardCaption_boh28_52",QY="_section_boh28_59",eX="_localeRow_boh28_73",tX="_localeArrow_boh28_80",nX="_actions_boh28_109",aX="_helperText_boh28_115",iX="_statusReady_boh28_121",sX="_blockers_boh28_132",rX="_blockersTitle_boh28_140",oX="_blockerList_boh28_146",lX="_loadingOverlay_boh28_155",uX="_loadingText_boh28_168",cX="_footerNote_boh28_173",dX="_subsectionHeader_boh28_182",fX="_subsectionLabel_boh28_189",hX="_subsectionHint_boh28_195",gX="_modelFieldList_boh28_200",ot={page:HY,container:YY,card:XY,cardHeader:WY,cardTitle:ZY,cardCaption:JY,section:QY,localeRow:eX,localeArrow:tX,actions:nX,helperText:aX,statusReady:iX,blockers:sX,blockersTitle:rX,blockerList:oX,loadingOverlay:lX,loadingText:uX,footerNote:cX,subsectionHeader:dX,subsectionLabel:fX,subsectionHint:hX,modelFieldList:gX},Im={label:"All other locales",value:Ra};function mX({ctx:t}){const[e,n]=A.useState([]),[i,r]=A.useState([]),[l,u]=A.useState([]),[d,f]=A.useState(null),[h,g]=A.useState([Im]),[p,v]=A.useState({}),[b,S]=A.useState({}),[w,T]=A.useState(new Set),[E,C]=A.useState(!0),[O,L]=A.useState(!1);A.useEffect(()=>{async function $(){if(!t.currentUserAccessToken){t.alert("No access token found"),C(!1);return}try{const k=Ip(t.currentUserAccessToken,t.environment,t.cmaBaseUrl),re=(await k.itemTypes.list()).filter(de=>!de.modular_block);n(re.map(de=>({label:de.name,value:de.id,code:de.api_key})));const fe=(await k.site.find()).locales.map(de=>({label:eo(de),value:de,code:de}));u(fe),fe.length>0&&f(fe[0]),C(!1)}catch(k){console.error("Error loading data:",k),t.alert(`Error loading data: ${k instanceof Error?k.message:String(k)}`),C(!1)}}$()},[t]);const M=t.plugin.attributes.parameters,N=A.useCallback(async $=>{if(!(p[$]||w.has($))){T(k=>{const V=new Set(k);return V.add($),V});try{const k=await t.loadItemTypeFields($),V=F2(k),re=U2(V,{translationFields:M.translationFields??[],apiKeysToBeExcludedFromThisPlugin:M.apiKeysToBeExcludedFromThisPlugin??[]});v(Q=>({...Q,[$]:re})),S(Q=>Q[$]?Q:{...Q,[$]:q2(re)})}catch(k){console.error(`Error loading fields for model ${$}:`,k),t.alert(`Error loading fields: ${k instanceof Error?k.message:String(k)}`)}finally{T(k=>{const V=new Set(k);return V.delete($),V})}}},[t,p,w,M.apiKeysToBeExcludedFromThisPlugin,M.translationFields]);A.useEffect(()=>{for(const $ of i)N($.value)},[i,N]),A.useEffect(()=>{const $=i.map(k=>k.value);v(k=>j_(k,$)),S(k=>j_(k,$))},[i]);const D=A.useMemo(()=>l.map($=>$.value),[l]),j=A.useMemo(()=>d?V2(h.map($=>$.value),D,d.value):[],[d,h,D]),K=A.useMemo(()=>i.map($=>$.value),[i]),X=A.useMemo(()=>$2({sourceLocale:d?.value??null,targetLocales:j,selectedModelIds:K,selectedFieldsByModel:b}),[d,j,K,b]),z=X.isReady,ee=$=>{const k=Array.isArray($)?[...$]:$?[$]:[],V=h.some(Q=>Q.value===Ra),re=k.some(Q=>Q.value===Ra);if(!V&&re){g([Im]);return}if(V&&re&&k.length>1){g(k.filter(Q=>Q.value!==Ra));return}g(k)},ne=$=>{$&&!Array.isArray($)&&f($)},le=$=>{Array.isArray($)&&r([...$])},ue=($,k)=>{S(V=>({...V,[$]:k}))},F=$=>{r(k=>k.filter(V=>V.value!==$))},W=$=>{const k=p[$];return k!==void 0&&k.length===0},ae=async()=>{if(z){if(!t.currentUserAccessToken){t.alert("No access token found");return}if(d){if(!zr(M)){t.alert("Please configure valid credentials for the selected AI vendor in the plugin settings");return}L(!0);try{const $=Ip(t.currentUserAccessToken,t.environment,t.cmaBaseUrl),k=[];if(await Promise.all(K.map(async be=>{const Le=$.items.listPagedIterator({filter:{type:be},version:"current"});for await(const Ne of Le)k.push(Ne.id)})),k.length===0){t.alert("No records found in the selected models");return}const V={recordCount:k.length,fromLocale:d.value,toLocales:j,models:i.map(be=>{const Le=new Set(b[be.value]??[]);return{label:be.label,code:be.code,fields:(p[be.value]??[]).filter(Ne=>Le.has(Ne.apiKey)).map(Ne=>({label:Ne.label,apiKey:Ne.apiKey}))}})};if(await t.openModal({id:"translationConfirmModal",title:"Start bulk translation?",width:"m",parameters:V})!==!0)return;const fe=await t.openModal({id:"translationProgressModal",title:"Translation Progress",width:"l",parameters:{totalRecords:k.length,fromLocale:d.value,toLocales:j,accessToken:t.currentUserAccessToken,pluginParams:M,itemIds:k,selectedFieldsByModel:b}}),de=j.length;fe?.canceled?await t.notice("Bulk translation was canceled"):fe?.completed?await t.notice(`Successfully translated ${k.length} record(s) to ${de} locale(s)`):await t.alert("Bulk translation finished with errors; review the modal output above.")}catch($){sv($,M.vendor,t)}finally{L(!1)}}}},ce=A.useMemo(()=>[Im,...l.filter($=>$.value!==d?.value)],[l,d]);return x.jsx(Un,{ctx:t,children:x.jsxs("div",{className:ot.page,children:[x.jsx("div",{className:ot.container,children:x.jsxs("div",{className:ot.card,children:[x.jsxs("div",{className:ot.cardHeader,children:[x.jsx("h1",{className:ot.cardTitle,children:"AI Bulk Translations"}),x.jsx("p",{className:ot.cardCaption,children:"Pick the source and target languages, the models, and the fields you want translated."})]}),E&&x.jsxs("div",{className:ot.loadingOverlay,children:[x.jsx(cf,{size:40}),x.jsx("div",{className:ot.loadingText,children:"Loading languages and models..."})]}),x.jsx("div",{className:ot.section,children:x.jsxs("div",{className:ot.localeRow,children:[x.jsx("div",{children:x.jsx(xt,{name:"sourceLocale",id:"sourceLocale",label:"Source language",hint:"Translate from",value:d,selectInputProps:{options:l,formatOptionLabel:Aa,classNamePrefix:zi},onChange:ne})}),x.jsx("div",{className:ot.localeArrow,"aria-hidden":!0,children:"→"}),x.jsx("div",{children:x.jsx(xt,{name:"targetLocales",id:"targetLocales",label:"Target languages",hint:"Pick one or more, or “All other locales”",value:h,selectInputProps:{isMulti:!0,options:ce,formatOptionLabel:Aa,classNamePrefix:zi},onChange:ee})})]})}),x.jsx("div",{className:ot.section,children:x.jsx(xt,{name:"selectedModels",id:"selectedModels",label:"Models",hint:"Records of these models will be translated",value:i,selectInputProps:{isMulti:!0,options:e,formatOptionLabel:Aa,classNamePrefix:zi},onChange:le})}),i.length>0&&x.jsxs("div",{className:ot.section,children:[x.jsxs("div",{className:ot.subsectionHeader,children:[x.jsx("div",{className:ot.subsectionLabel,children:"Fields to translate"}),x.jsx("div",{className:ot.subsectionHint,children:"Defaults to every translatable field. Remove any you want to leave alone, per model."})]}),x.jsx("div",{className:ot.modelFieldList,children:i.map($=>x.jsx(BA,{model:$,fields:p[$.value],isLoading:w.has($.value),selectedApiKeys:b[$.value]??[],onChange:k=>ue($.value,k),onRemove:()=>F($.value),validationMessage:X.modelsMissingFields.includes($.value)&&!W($.value)?"Select at least one field to translate this model.":void 0},$.value))})]}),x.jsxs("div",{className:ot.actions,children:[x.jsx(wt,{buttonType:"primary",onClick:ae,disabled:!z||O,fullWidth:!0,children:O?"Collecting records…":"Start bulk translation"}),!z&&!O&&x.jsxs("div",{className:ot.blockers,children:[x.jsx("div",{className:ot.blockersTitle,children:"Before you can translate:"}),x.jsxs("ul",{className:ot.blockerList,children:[X.missingSourceLocale&&x.jsx("li",{children:"Pick a source language."}),X.missingTargetLocales&&x.jsx("li",{children:"Pick at least one target language."}),X.missingModels&&x.jsx("li",{children:"Pick at least one model to translate."}),X.modelsMissingFields.map($=>{const k=i.find(V=>V.value===$)?.label??"A selected model";return x.jsx("li",{children:W($)?`${k} has no translatable fields — remove it.`:`${k}: select at least one field.`},$)})]})]}),z&&!O&&x.jsxs("div",{className:`${ot.helperText} ${ot.statusReady}`,children:["Ready to translate to ",j.length," locale",j.length===1?"":"s"]})]})]})}),x.jsx("div",{className:ot.footerNote,children:"Translations are performed using AI. Review content after translation."})]})})}function pX({ctx:t}){return x.jsx(Un,{ctx:t,children:"Loading..."})}const cv=A.createContext({});function dv(t){const e=A.useRef(null);return e.current===null&&(e.current=t()),e.current}const yX=typeof window<"u",$C=yX?A.useLayoutEffect:A.useEffect,Mf=A.createContext(null);function fv(t,e){t.indexOf(e)===-1&&t.push(e)}function Kd(t,e){const n=t.indexOf(e);n>-1&&t.splice(n,1)}const xa=(t,e,n)=>n>e?e:n<t?t:n;let hv=()=>{};const Fi={},qC=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function GC(t){return typeof t=="object"&&t!==null}const KC=t=>/^0[^.\s]+$/u.test(t);function HC(t){let e;return()=>(e===void 0&&(e=t()),e)}const qn=t=>t,vX=(t,e)=>n=>e(t(n)),Xl=(...t)=>t.reduce(vX),Pl=(t,e,n)=>{const i=e-t;return i===0?1:(n-t)/i};class gv{constructor(){this.subscriptions=[]}add(e){return fv(this.subscriptions,e),()=>Kd(this.subscriptions,e)}notify(e,n,i){const r=this.subscriptions.length;if(r)if(r===1)this.subscriptions[0](e,n,i);else for(let l=0;l<r;l++){const u=this.subscriptions[l];u&&u(e,n,i)}}getSize(){return this.subscriptions.length}clear(){this.subscriptions.length=0}}const En=t=>t*1e3,$n=t=>t/1e3;function YC(t,e){return e?t*(1e3/e):0}const XC=(t,e,n)=>(((1-3*n+3*e)*t+(3*n-6*e))*t+3*e)*t,bX=1e-7,SX=12;function _X(t,e,n,i,r){let l,u,d=0;do u=e+(n-e)/2,l=XC(u,i,r)-t,l>0?n=u:e=u;while(Math.abs(l)>bX&&++d<SX);return u}function Wl(t,e,n,i){if(t===e&&n===i)return qn;const r=l=>_X(l,0,1,t,n);return l=>l===0||l===1?l:XC(r(l),e,i)}const WC=t=>e=>e<=.5?t(2*e)/2:(2-t(2*(1-e)))/2,ZC=t=>e=>1-t(1-e),JC=Wl(.33,1.53,.69,.99),mv=ZC(JC),QC=WC(mv),e3=t=>t>=1?1:(t*=2)<1?.5*mv(t):.5*(2-Math.pow(2,-10*(t-1))),pv=t=>1-Math.sin(Math.acos(t)),t3=ZC(pv),n3=WC(pv),wX=Wl(.42,0,1,1),TX=Wl(0,0,.58,1),a3=Wl(.42,0,.58,1),EX=t=>Array.isArray(t)&&typeof t[0]!="number",i3=t=>Array.isArray(t)&&typeof t[0]=="number",RX={linear:qn,easeIn:wX,easeInOut:a3,easeOut:TX,circIn:pv,circInOut:n3,circOut:t3,backIn:mv,backInOut:QC,backOut:JC,anticipate:e3},AX=t=>typeof t=="string",vT=t=>{if(i3(t)){hv(t.length===4);const[e,n,i,r]=t;return Wl(e,n,i,r)}else if(AX(t))return RX[t];return t},Uc=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function CX(t,e){let n=new Set,i=new Set,r=!1,l=!1;const u=new WeakSet;let d={delta:0,timestamp:0,isProcessing:!1};function f(g){u.has(g)&&(h.schedule(g),t()),g(d)}const h={schedule:(g,p=!1,v=!1)=>{const S=v&&r?n:i;return p&&u.add(g),S.add(g),g},cancel:g=>{i.delete(g),u.delete(g)},process:g=>{if(d=g,r){l=!0;return}r=!0;const p=n;n=i,i=p,n.forEach(f),n.clear(),r=!1,l&&(l=!1,h.process(g))}};return h}const xX=40;function s3(t,e){let n=!1,i=!0;const r={delta:0,timestamp:0,isProcessing:!1},l=()=>n=!0,u=Uc.reduce((O,L)=>(O[L]=CX(l),O),{}),{setup:d,read:f,resolveKeyframes:h,preUpdate:g,update:p,preRender:v,render:b,postRender:S}=u,w=()=>{const O=Fi.useManualTiming,L=O?r.timestamp:performance.now();n=!1,O||(r.delta=i?1e3/60:Math.max(Math.min(L-r.timestamp,xX),1)),r.timestamp=L,r.isProcessing=!0,d.process(r),f.process(r),h.process(r),g.process(r),p.process(r),v.process(r),b.process(r),S.process(r),r.isProcessing=!1,n&&e&&(i=!1,t(w))},T=()=>{n=!0,i=!0,r.isProcessing||t(w)};return{schedule:Uc.reduce((O,L)=>{const M=u[L];return O[L]=(N,D=!1,j=!1)=>(n||T(),M.schedule(N,D,j)),O},{}),cancel:O=>{for(let L=0;L<Uc.length;L++)u[Uc[L]].cancel(O)},state:r,steps:u}}const{schedule:nt,cancel:Ui,state:jt,steps:Pm}=s3(typeof requestAnimationFrame<"u"?requestAnimationFrame:qn,!0);let cd;function MX(){cd=void 0}const tn={now:()=>(cd===void 0&&tn.set(jt.isProcessing||Fi.useManualTiming?jt.timestamp:performance.now()),cd),set:t=>{cd=t,queueMicrotask(MX)}},r3=t=>e=>typeof e=="string"&&e.startsWith(t),o3=r3("--"),OX=r3("var(--"),yv=t=>OX(t)?kX.test(t.split("/*")[0].trim()):!1,kX=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu;function bT(t){return typeof t!="string"?!1:t.split("/*")[0].includes("var(--")}const ao={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},jl={...ao,transform:t=>xa(0,1,t)},Vc={...ao,default:1},wl=t=>Math.round(t*1e5)/1e5,vv=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function LX(t){return t==null}const DX=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,bv=(t,e)=>n=>!!(typeof n=="string"&&DX.test(n)&&n.startsWith(t)||e&&!LX(n)&&Object.prototype.hasOwnProperty.call(n,e)),l3=(t,e,n)=>i=>{if(typeof i!="string")return i;const[r,l,u,d]=i.match(vv);return{[t]:parseFloat(r),[e]:parseFloat(l),[n]:parseFloat(u),alpha:d!==void 0?parseFloat(d):1}},BX=t=>xa(0,255,t),jm={...ao,transform:t=>Math.round(BX(t))},ws={test:bv("rgb","red"),parse:l3("red","green","blue"),transform:({red:t,green:e,blue:n,alpha:i=1})=>"rgba("+jm.transform(t)+", "+jm.transform(e)+", "+jm.transform(n)+", "+wl(jl.transform(i))+")"};function NX(t){let e="",n="",i="",r="";return t.length>5?(e=t.substring(1,3),n=t.substring(3,5),i=t.substring(5,7),r=t.substring(7,9)):(e=t.substring(1,2),n=t.substring(2,3),i=t.substring(3,4),r=t.substring(4,5),e+=e,n+=n,i+=i,r+=r),{red:parseInt(e,16),green:parseInt(n,16),blue:parseInt(i,16),alpha:r?parseInt(r,16)/255:1}}const qp={test:bv("#"),parse:NX,transform:ws.transform},Zl=t=>({test:e=>typeof e=="string"&&e.endsWith(t)&&e.split(" ").length===1,parse:parseFloat,transform:e=>`${e}${t}`}),Di=Zl("deg"),Ca=Zl("%"),pe=Zl("px"),IX=Zl("vh"),PX=Zl("vw"),ST={...Ca,parse:t=>Ca.parse(t)/100,transform:t=>Ca.transform(t*100)},Dr={test:bv("hsl","hue"),parse:l3("hue","saturation","lightness"),transform:({hue:t,saturation:e,lightness:n,alpha:i=1})=>"hsla("+Math.round(t)+", "+Ca.transform(wl(e))+", "+Ca.transform(wl(n))+", "+wl(jl.transform(i))+")"},St={test:t=>ws.test(t)||qp.test(t)||Dr.test(t),parse:t=>ws.test(t)?ws.parse(t):Dr.test(t)?Dr.parse(t):qp.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?ws.transform(t):Dr.transform(t),getAnimatableNone:t=>{const e=St.parse(t);return e.alpha=0,St.transform(e)}},jX=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function zX(t){return isNaN(t)&&typeof t=="string"&&(t.match(vv)?.length||0)+(t.match(jX)?.length||0)>0}const u3="number",c3="color",FX="var",UX="var(",_T="${}",VX=/var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu;function Zr(t){const e=t.toString(),n=[],i={color:[],number:[],var:[]},r=[];let l=0;const d=e.replace(VX,f=>(St.test(f)?(i.color.push(l),r.push(c3),n.push(St.parse(f))):f.startsWith(UX)?(i.var.push(l),r.push(FX),n.push(f)):(i.number.push(l),r.push(u3),n.push(parseFloat(f))),++l,_T)).split(_T);return{values:n,split:d,indexes:i,types:r}}function $X(t){return Zr(t).values}function d3({split:t,types:e}){const n=t.length;return i=>{let r="";for(let l=0;l<n;l++)if(r+=t[l],i[l]!==void 0){const u=e[l];u===u3?r+=wl(i[l]):u===c3?r+=St.transform(i[l]):r+=i[l]}return r}}function qX(t){return d3(Zr(t))}const GX=t=>typeof t=="number"?0:St.test(t)?St.getAnimatableNone(t):t,KX=(t,e)=>typeof t=="number"?e?.trim().endsWith("/")?t:0:GX(t);function HX(t){const e=Zr(t);return d3(e)(e.values.map((i,r)=>KX(i,e.split[r])))}const aa={test:zX,parse:$X,createTransformer:qX,getAnimatableNone:HX};function zm(t,e,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?t+(e-t)*6*n:n<1/2?e:n<2/3?t+(e-t)*(2/3-n)*6:t}function YX({hue:t,saturation:e,lightness:n,alpha:i}){t/=360,e/=100,n/=100;let r=0,l=0,u=0;if(!e)r=l=u=n;else{const d=n<.5?n*(1+e):n+e-n*e,f=2*n-d;r=zm(f,d,t+1/3),l=zm(f,d,t),u=zm(f,d,t-1/3)}return{red:Math.round(r*255),green:Math.round(l*255),blue:Math.round(u*255),alpha:i}}function Hd(t,e){return n=>n>0?e:t}const st=(t,e,n)=>t+(e-t)*n,Fm=(t,e,n)=>{const i=t*t,r=n*(e*e-i)+i;return r<0?0:Math.sqrt(r)},XX=[qp,ws,Dr],WX=t=>XX.find(e=>e.test(t));function wT(t){const e=WX(t);if(!e)return!1;let n=e.parse(t);return e===Dr&&(n=YX(n)),n}const TT=(t,e)=>{const n=wT(t),i=wT(e);if(!n||!i)return Hd(t,e);const r={...n};return l=>(r.red=Fm(n.red,i.red,l),r.green=Fm(n.green,i.green,l),r.blue=Fm(n.blue,i.blue,l),r.alpha=st(n.alpha,i.alpha,l),ws.transform(r))},Gp=new Set(["none","hidden"]);function ZX(t,e){return Gp.has(t)?n=>n<=0?t:e:n=>n>=1?e:t}function JX(t,e){return n=>st(t,e,n)}function Sv(t){return typeof t=="number"?JX:typeof t=="string"?yv(t)?Hd:St.test(t)?TT:tW:Array.isArray(t)?f3:typeof t=="object"?St.test(t)?TT:QX:Hd}function f3(t,e){const n=[...t],i=n.length,r=t.map((l,u)=>Sv(l)(l,e[u]));return l=>{for(let u=0;u<i;u++)n[u]=r[u](l);return n}}function QX(t,e){const n={...t,...e},i={};for(const r in n)t[r]!==void 0&&e[r]!==void 0&&(i[r]=Sv(t[r])(t[r],e[r]));return r=>{for(const l in i)n[l]=i[l](r);return n}}function eW(t,e){const n=[],i={color:0,var:0,number:0};for(let r=0;r<e.values.length;r++){const l=e.types[r],u=t.indexes[l][i[l]],d=t.values[u]??0;n[r]=d,i[l]++}return n}const tW=(t,e)=>{const n=aa.createTransformer(e),i=Zr(t),r=Zr(e);return i.indexes.var.length===r.indexes.var.length&&i.indexes.color.length===r.indexes.color.length&&i.indexes.number.length>=r.indexes.number.length?Gp.has(t)&&!r.values.length||Gp.has(e)&&!i.values.length?ZX(t,e):Xl(f3(eW(i,r),r.values),n):Hd(t,e)};function h3(t,e,n){return typeof t=="number"&&typeof e=="number"&&typeof n=="number"?st(t,e,n):Sv(t)(t,e)}const nW=t=>{const e=({timestamp:n})=>t(n);return{start:(n=!0)=>nt.update(e,n),stop:()=>Ui(e),now:()=>jt.isProcessing?jt.timestamp:tn.now()}},g3=(t,e,n=10)=>{let i="";const r=Math.max(Math.round(e/n),2);for(let l=0;l<r;l++)i+=Math.round(t(l/(r-1))*1e4)/1e4+", ";return`linear(${i.substring(0,i.length-2)})`},Yd=2e4;function _v(t){let e=0;const n=50;let i=t.next(e);for(;!i.done&&e<Yd;)e+=n,i=t.next(e);return e>=Yd?1/0:e}function aW(t,e=100,n){const i=n({...t,keyframes:[0,e]}),r=Math.min(_v(i),Yd);return{type:"keyframes",ease:l=>i.next(r*l).value/e,duration:$n(r)}}const dt={stiffness:100,damping:10,mass:1,velocity:0,duration:800,bounce:.3,visualDuration:.3,restSpeed:{granular:.01,default:2},restDelta:{granular:.005,default:.5},minDuration:.01,maxDuration:10,minDamping:.05,maxDamping:1};function Kp(t,e){return t*Math.sqrt(1-e*e)}const iW=12;function sW(t,e,n){let i=n;for(let r=1;r<iW;r++)i=i-t(i)/e(i);return i}const Um=.001;function rW({duration:t=dt.duration,bounce:e=dt.bounce,velocity:n=dt.velocity,mass:i=dt.mass}){let r,l,u=1-e;u=xa(dt.minDamping,dt.maxDamping,u),t=xa(dt.minDuration,dt.maxDuration,$n(t)),u<1?(r=h=>{const g=h*u,p=g*t,v=g-n,b=Kp(h,u),S=Math.exp(-p);return Um-v/b*S},l=h=>{const p=h*u*t,v=p*n+n,b=Math.pow(u,2)*Math.pow(h,2)*t,S=Math.exp(-p),w=Kp(Math.pow(h,2),u);return(-r(h)+Um>0?-1:1)*((v-b)*S)/w}):(r=h=>{const g=Math.exp(-h*t),p=(h-n)*t+1;return-Um+g*p},l=h=>{const g=Math.exp(-h*t),p=(n-h)*(t*t);return g*p});const d=5/t,f=sW(r,l,d);if(t=En(t),isNaN(f))return{stiffness:dt.stiffness,damping:dt.damping,duration:t};{const h=Math.pow(f,2)*i;return{stiffness:h,damping:u*2*Math.sqrt(i*h),duration:t}}}const oW=["duration","bounce"],lW=["stiffness","damping","mass"];function ET(t,e){return e.some(n=>t[n]!==void 0)}function uW(t){let e={velocity:dt.velocity,stiffness:dt.stiffness,damping:dt.damping,mass:dt.mass,isResolvedFromDuration:!1,...t};if(!ET(t,lW)&&ET(t,oW))if(e.velocity=0,t.visualDuration){const n=t.visualDuration,i=2*Math.PI/(n*1.2),r=i*i,l=2*xa(.05,1,1-(t.bounce||0))*Math.sqrt(r);e={...e,mass:dt.mass,stiffness:r,damping:l}}else{const n=rW({...t,velocity:0});e={...e,...n,mass:dt.mass},e.isResolvedFromDuration=!0}return e}function Xd(t=dt.visualDuration,e=dt.bounce){const n=typeof t!="object"?{visualDuration:t,keyframes:[0,1],bounce:e}:t;let{restSpeed:i,restDelta:r}=n;const l=n.keyframes[0],u=n.keyframes[n.keyframes.length-1],d={done:!1,value:l},{stiffness:f,damping:h,mass:g,duration:p,velocity:v,isResolvedFromDuration:b}=uW({...n,velocity:-$n(n.velocity||0)}),S=v||0,w=h/(2*Math.sqrt(f*g)),T=u-l,E=$n(Math.sqrt(f/g)),C=Math.abs(T)<5;i||(i=C?dt.restSpeed.granular:dt.restSpeed.default),r||(r=C?dt.restDelta.granular:dt.restDelta.default);let O,L,M,N,D,j;if(w<1)M=Kp(E,w),N=(S+w*E*T)/M,O=X=>{const z=Math.exp(-w*E*X);return u-z*(N*Math.sin(M*X)+T*Math.cos(M*X))},D=w*E*N+T*M,j=w*E*T-N*M,L=X=>Math.exp(-w*E*X)*(D*Math.sin(M*X)+j*Math.cos(M*X));else if(w===1){O=z=>u-Math.exp(-E*z)*(T+(S+E*T)*z);const X=S+E*T;L=z=>Math.exp(-E*z)*(E*X*z-S)}else{const X=E*Math.sqrt(w*w-1);O=le=>{const ue=Math.exp(-w*E*le),F=Math.min(X*le,300);return u-ue*((S+w*E*T)*Math.sinh(F)+X*T*Math.cosh(F))/X};const z=(S+w*E*T)/X,ee=w*E*z-T*X,ne=w*E*T-z*X;L=le=>{const ue=Math.exp(-w*E*le),F=Math.min(X*le,300);return ue*(ee*Math.sinh(F)+ne*Math.cosh(F))}}const K={calculatedDuration:b&&p||null,velocity:X=>En(L(X)),next:X=>{if(!b&&w<1){const ee=Math.exp(-w*E*X),ne=Math.sin(M*X),le=Math.cos(M*X),ue=u-ee*(N*ne+T*le),F=En(ee*(D*ne+j*le));return d.done=Math.abs(F)<=i&&Math.abs(u-ue)<=r,d.value=d.done?u:ue,d}const z=O(X);if(b)d.done=X>=p;else{const ee=En(L(X));d.done=Math.abs(ee)<=i&&Math.abs(u-z)<=r}return d.value=d.done?u:z,d},toString:()=>{const X=Math.min(_v(K),Yd),z=g3(ee=>K.next(X*ee).value,X,30);return X+"ms "+z},toTransition:()=>{}};return K}Xd.applyToOptions=t=>{const e=aW(t,100,Xd);return t.ease=e.ease,t.duration=En(e.duration),t.type="keyframes",t};const cW=5;function m3(t,e,n){const i=Math.max(e-cW,0);return YC(n-t(i),e-i)}function Hp({keyframes:t,velocity:e=0,power:n=.8,timeConstant:i=325,bounceDamping:r=10,bounceStiffness:l=500,modifyTarget:u,min:d,max:f,restDelta:h=.5,restSpeed:g}){const p=t[0],v={done:!1,value:p},b=j=>d!==void 0&&j<d||f!==void 0&&j>f,S=j=>d===void 0?f:f===void 0||Math.abs(d-j)<Math.abs(f-j)?d:f;let w=n*e;const T=p+w,E=u===void 0?T:u(T);E!==T&&(w=E-p);const C=j=>-w*Math.exp(-j/i),O=j=>E+C(j),L=j=>{const K=C(j),X=O(j);v.done=Math.abs(K)<=h,v.value=v.done?E:X};let M,N;const D=j=>{b(v.value)&&(M=j,N=Xd({keyframes:[v.value,S(v.value)],velocity:m3(O,j,v.value),damping:r,stiffness:l,restDelta:h,restSpeed:g}))};return D(0),{calculatedDuration:null,next:j=>{let K=!1;return!N&&M===void 0&&(K=!0,L(j),D(j)),M!==void 0&&j>=M?N.next(j-M):(!K&&L(j),v)}}}function dW(t,e,n){const i=[],r=n||Fi.mix||h3,l=t.length-1;for(let u=0;u<l;u++){let d=r(t[u],t[u+1]);if(e){const f=Array.isArray(e)?e[u]||qn:e;d=Xl(f,d)}i.push(d)}return i}function fW(t,e,{clamp:n=!0,ease:i,mixer:r}={}){const l=t.length;if(hv(l===e.length),l===1)return()=>e[0];if(l===2&&e[0]===e[1])return()=>e[1];const u=t[0]===t[1];t[0]>t[l-1]&&(t=[...t].reverse(),e=[...e].reverse());const d=dW(e,i,r),f=d.length,h=g=>{if(u&&g<t[0])return e[0];let p=0;if(f>1)for(;p<t.length-2&&!(g<t[p+1]);p++);const v=Pl(t[p],t[p+1],g);return d[p](v)};return n?g=>h(xa(t[0],t[l-1],g)):h}function hW(t,e){const n=t[t.length-1];for(let i=1;i<=e;i++){const r=Pl(0,e,i);t.push(st(n,1,r))}}function gW(t){const e=[0];return hW(e,t.length-1),e}function mW(t,e){return t.map(n=>n*e)}function pW(t,e){return t.map(()=>e||a3).splice(0,t.length-1)}function Tl({duration:t=300,keyframes:e,times:n,ease:i="easeInOut"}){const r=EX(i)?i.map(vT):vT(i),l={done:!1,value:e[0]},u=mW(n&&n.length===e.length?n:gW(e),t),d=fW(u,e,{ease:Array.isArray(r)?r:pW(e,r)});return{calculatedDuration:t,next:f=>(l.value=d(f),l.done=f>=t,l)}}const yW=t=>t!==null;function Of(t,{repeat:e,repeatType:n="loop"},i,r=1){const l=t.filter(yW),d=r<0||e&&n!=="loop"&&e%2===1?0:l.length-1;return!d||i===void 0?l[d]:i}const vW={decay:Hp,inertia:Hp,tween:Tl,keyframes:Tl,spring:Xd};function p3(t){typeof t.type=="string"&&(t.type=vW[t.type])}class wv{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(e=>{this.resolve=e})}notifyFinished(){this.resolve()}then(e,n){return this.finished.then(e,n)}}const bW=t=>t/100;class Wd extends wv{constructor(e){super(),this.state="idle",this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.delayState={done:!1,value:void 0},this.stop=()=>{const{motionValue:n}=this.options;n&&n.updatedAt!==tn.now()&&this.tick(tn.now()),this.isStopped=!0,this.state!=="idle"&&(this.teardown(),this.options.onStop?.())},this.options=e,this.initAnimation(),this.play(),e.autoplay===!1&&this.pause()}initAnimation(){const{options:e}=this;p3(e);const{type:n=Tl,repeat:i=0,repeatDelay:r=0,repeatType:l,velocity:u=0}=e;let{keyframes:d}=e;const f=n||Tl;f!==Tl&&typeof d[0]!="number"&&(this.mixKeyframes=Xl(bW,h3(d[0],d[1])),d=[0,100]);const h=f({...e,keyframes:d});l==="mirror"&&(this.mirroredGenerator=f({...e,keyframes:[...d].reverse(),velocity:-u})),h.calculatedDuration===null&&(h.calculatedDuration=_v(h));const{calculatedDuration:g}=h;this.calculatedDuration=g,this.resolvedDuration=g+r,this.totalDuration=this.resolvedDuration*(i+1)-r,this.generator=h}updateTime(e){const n=Math.round(e-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=n}tick(e,n=!1){const{generator:i,totalDuration:r,mixKeyframes:l,mirroredGenerator:u,resolvedDuration:d,calculatedDuration:f}=this;if(this.startTime===null)return i.next(0);const{delay:h=0,keyframes:g,repeat:p,repeatType:v,repeatDelay:b,type:S,onUpdate:w,finalKeyframe:T}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,e):this.speed<0&&(this.startTime=Math.min(e-r/this.speed,this.startTime)),n?this.currentTime=e:this.updateTime(e);const E=this.currentTime-h*(this.playbackSpeed>=0?1:-1),C=this.playbackSpeed>=0?E<0:E>r;this.currentTime=Math.max(E,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=r);let O=this.currentTime,L=i;if(p){const j=Math.min(this.currentTime,r)/d;let K=Math.floor(j),X=j%1;!X&&j>=1&&(X=1),X===1&&K--,K=Math.min(K,p+1),K%2&&(v==="reverse"?(X=1-X,b&&(X-=b/d)):v==="mirror"&&(L=u)),O=xa(0,1,X)*d}let M;C?(this.delayState.value=g[0],M=this.delayState):M=L.next(O),l&&!C&&(M.value=l(M.value));let{done:N}=M;!C&&f!==null&&(N=this.playbackSpeed>=0?this.currentTime>=r:this.currentTime<=0);const D=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&N);return D&&S!==Hp&&(M.value=Of(g,this.options,T,this.speed)),w&&w(M.value),D&&this.finish(),M}then(e,n){return this.finished.then(e,n)}get duration(){return $n(this.calculatedDuration)}get iterationDuration(){const{delay:e=0}=this.options||{};return this.duration+$n(e)}get time(){return $n(this.currentTime)}set time(e){e=En(e),this.currentTime=e,this.startTime===null||this.holdTime!==null||this.playbackSpeed===0?this.holdTime=e:this.driver&&(this.startTime=this.driver.now()-e/this.playbackSpeed),this.driver?this.driver.start(!1):(this.startTime=0,this.state="paused",this.holdTime=e,this.tick(e))}getGeneratorVelocity(){const e=this.currentTime;if(e<=0)return this.options.velocity||0;if(this.generator.velocity)return this.generator.velocity(e);const n=this.generator.next(e).value;return m3(i=>this.generator.next(i).value,e,n)}get speed(){return this.playbackSpeed}set speed(e){const n=this.playbackSpeed!==e;n&&this.driver&&this.updateTime(tn.now()),this.playbackSpeed=e,n&&this.driver&&(this.time=$n(this.currentTime))}play(){if(this.isStopped)return;const{driver:e=nW,startTime:n}=this.options;this.driver||(this.driver=e(r=>this.tick(r))),this.options.onPlay?.();const i=this.driver.now();this.state==="finished"?(this.updateFinished(),this.startTime=i):this.holdTime!==null?this.startTime=i-this.holdTime:this.startTime||(this.startTime=n??i),this.state==="finished"&&this.speed<0&&(this.startTime+=this.calculatedDuration),this.holdTime=null,this.state="running",this.driver.start()}pause(){this.state="paused",this.updateTime(tn.now()),this.holdTime=this.currentTime}complete(){this.state!=="running"&&this.play(),this.state="finished",this.holdTime=null}finish(){this.notifyFinished(),this.teardown(),this.state="finished",this.options.onComplete?.()}cancel(){this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),this.options.onCancel?.()}teardown(){this.state="idle",this.stopDriver(),this.startTime=this.holdTime=null}stopDriver(){this.driver&&(this.driver.stop(),this.driver=void 0)}sample(e){return this.startTime=0,this.tick(e,!0)}attachTimeline(e){return this.options.allowFlatten&&(this.options.type="keyframes",this.options.ease="linear",this.initAnimation()),this.driver?.stop(),e.observe(this)}}function SW(t){for(let e=1;e<t.length;e++)t[e]??(t[e]=t[e-1])}const Ts=t=>t*180/Math.PI,Yp=t=>{const e=Ts(Math.atan2(t[1],t[0]));return Xp(e)},_W={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:Yp,rotateZ:Yp,skewX:t=>Ts(Math.atan(t[1])),skewY:t=>Ts(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},Xp=t=>(t=t%360,t<0&&(t+=360),t),RT=Yp,AT=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),CT=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),wW={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:AT,scaleY:CT,scale:t=>(AT(t)+CT(t))/2,rotateX:t=>Xp(Ts(Math.atan2(t[6],t[5]))),rotateY:t=>Xp(Ts(Math.atan2(-t[2],t[0]))),rotateZ:RT,rotate:RT,skewX:t=>Ts(Math.atan(t[4])),skewY:t=>Ts(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function Wp(t){return t.includes("scale")?1:0}function Zp(t,e){if(!t||t==="none")return Wp(e);const n=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let i,r;if(n)i=wW,r=n;else{const d=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);i=_W,r=d}if(!r)return Wp(e);const l=i[e],u=r[1].split(",").map(EW);return typeof l=="function"?l(u):u[l]}const TW=(t,e)=>{const{transform:n="none"}=getComputedStyle(t);return Zp(n,e)};function EW(t){return parseFloat(t.trim())}const io=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],so=new Set(io),xT=t=>t===ao||t===pe,RW=new Set(["x","y","z"]),AW=io.filter(t=>!RW.has(t));function CW(t){const e=[];return AW.forEach(n=>{const i=t.getValue(n);i!==void 0&&(e.push([n,i.get()]),i.set(n.startsWith("scale")?1:0))}),e}const Ni={width:({x:t},{paddingLeft:e="0",paddingRight:n="0",boxSizing:i})=>{const r=t.max-t.min;return i==="border-box"?r:r-parseFloat(e)-parseFloat(n)},height:({y:t},{paddingTop:e="0",paddingBottom:n="0",boxSizing:i})=>{const r=t.max-t.min;return i==="border-box"?r:r-parseFloat(e)-parseFloat(n)},top:(t,{top:e})=>parseFloat(e),left:(t,{left:e})=>parseFloat(e),bottom:({y:t},{top:e})=>parseFloat(e)+(t.max-t.min),right:({x:t},{left:e})=>parseFloat(e)+(t.max-t.min),x:(t,{transform:e})=>Zp(e,"x"),y:(t,{transform:e})=>Zp(e,"y")};Ni.translateX=Ni.x;Ni.translateY=Ni.y;const Rs=new Set;let Jp=!1,Qp=!1,ey=!1;function y3(){if(Qp){const t=Array.from(Rs).filter(i=>i.needsMeasurement),e=new Set(t.map(i=>i.element)),n=new Map;e.forEach(i=>{const r=CW(i);r.length&&(n.set(i,r),i.render())}),t.forEach(i=>i.measureInitialState()),e.forEach(i=>{i.render();const r=n.get(i);r&&r.forEach(([l,u])=>{i.getValue(l)?.set(u)})}),t.forEach(i=>i.measureEndState()),t.forEach(i=>{i.suspendedScrollY!==void 0&&window.scrollTo(0,i.suspendedScrollY)})}Qp=!1,Jp=!1,Rs.forEach(t=>t.complete(ey)),Rs.clear()}function v3(){Rs.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(Qp=!0)})}function xW(){ey=!0,v3(),y3(),ey=!1}class Tv{constructor(e,n,i,r,l,u=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...e],this.onComplete=n,this.name=i,this.motionValue=r,this.element=l,this.isAsync=u}scheduleResolve(){this.state="scheduled",this.isAsync?(Rs.add(this),Jp||(Jp=!0,nt.read(v3),nt.resolveKeyframes(y3))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:e,name:n,element:i,motionValue:r}=this;if(e[0]===null){const l=r?.get(),u=e[e.length-1];if(l!==void 0)e[0]=l;else if(i&&n){const d=i.readValue(n,u);d!=null&&(e[0]=d)}e[0]===void 0&&(e[0]=u),r&&l===void 0&&r.set(e[0])}SW(e)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(e=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,e),Rs.delete(this)}cancel(){this.state==="scheduled"&&(Rs.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const MW=t=>t.startsWith("--");function b3(t,e,n){MW(e)?t.style.setProperty(e,n):t.style[e]=n}const OW={};function S3(t,e){const n=HC(t);return()=>OW[e]??n()}const kW=S3(()=>window.ScrollTimeline!==void 0,"scrollTimeline"),_3=S3(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),pl=([t,e,n,i])=>`cubic-bezier(${t}, ${e}, ${n}, ${i})`,MT={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:pl([0,.65,.55,1]),circOut:pl([.55,0,1,.45]),backIn:pl([.31,.01,.66,-.59]),backOut:pl([.33,1.53,.69,.99])};function w3(t,e){if(t)return typeof t=="function"?_3()?g3(t,e):"ease-out":i3(t)?pl(t):Array.isArray(t)?t.map(n=>w3(n,e)||MT.easeOut):MT[t]}function LW(t,e,n,{delay:i=0,duration:r=300,repeat:l=0,repeatType:u="loop",ease:d="easeOut",times:f}={},h=void 0){const g={[e]:n};f&&(g.offset=f);const p=w3(d,r);Array.isArray(p)&&(g.easing=p);const v={delay:i,duration:r,easing:Array.isArray(p)?"linear":p,fill:"both",iterations:l+1,direction:u==="reverse"?"alternate":"normal"};return h&&(v.pseudoElement=h),t.animate(g,v)}function T3(t){return typeof t=="function"&&"applyToOptions"in t}function DW({type:t,...e}){return T3(t)&&_3()?t.applyToOptions(e):(e.duration??(e.duration=300),e.ease??(e.ease="easeOut"),e)}class E3 extends wv{constructor(e){if(super(),this.finishedTime=null,this.isStopped=!1,this.manualStartTime=null,!e)return;const{element:n,name:i,keyframes:r,pseudoElement:l,allowFlatten:u=!1,finalKeyframe:d,onComplete:f}=e;this.isPseudoElement=!!l,this.allowFlatten=u,this.options=e,hv(typeof e.type!="string");const h=DW(e);this.animation=LW(n,i,r,h,l),h.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!l){const g=Of(r,this.options,d,this.speed);this.updateMotionValue&&this.updateMotionValue(g),b3(n,i,g),this.animation.cancel()}f?.(),this.notifyFinished()}}play(){this.isStopped||(this.manualStartTime=null,this.animation.play(),this.state==="finished"&&this.updateFinished())}pause(){this.animation.pause()}complete(){this.animation.finish?.()}cancel(){try{this.animation.cancel()}catch{}}stop(){if(this.isStopped)return;this.isStopped=!0;const{state:e}=this;e==="idle"||e==="finished"||(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){const e=this.options?.element;!this.isPseudoElement&&e?.isConnected&&this.animation.commitStyles?.()}get duration(){const e=this.animation.effect?.getComputedTiming?.().duration||0;return $n(Number(e))}get iterationDuration(){const{delay:e=0}=this.options||{};return this.duration+$n(e)}get time(){return $n(Number(this.animation.currentTime)||0)}set time(e){const n=this.finishedTime!==null;this.manualStartTime=null,this.finishedTime=null,this.animation.currentTime=En(e),n&&this.animation.pause()}get speed(){return this.animation.playbackRate}set speed(e){e<0&&(this.finishedTime=null),this.animation.playbackRate=e}get state(){return this.finishedTime!==null?"finished":this.animation.playState}get startTime(){return this.manualStartTime??Number(this.animation.startTime)}set startTime(e){this.manualStartTime=this.animation.startTime=e}attachTimeline({timeline:e,rangeStart:n,rangeEnd:i,observe:r}){return this.allowFlatten&&this.animation.effect?.updateTiming({easing:"linear"}),this.animation.onfinish=null,e&&kW()?(this.animation.timeline=e,n&&(this.animation.rangeStart=n),i&&(this.animation.rangeEnd=i),qn):r(this)}}const R3={anticipate:e3,backInOut:QC,circInOut:n3};function BW(t){return t in R3}function NW(t){typeof t.ease=="string"&&BW(t.ease)&&(t.ease=R3[t.ease])}const Vm=10;class IW extends E3{constructor(e){NW(e),p3(e),super(e),e.startTime!==void 0&&e.autoplay!==!1&&(this.startTime=e.startTime),this.options=e}updateMotionValue(e){const{motionValue:n,onUpdate:i,onComplete:r,element:l,...u}=this.options;if(!n)return;if(e!==void 0){n.set(e);return}const d=new Wd({...u,autoplay:!1}),f=Math.max(Vm,tn.now()-this.startTime),h=xa(0,Vm,f-Vm),g=d.sample(f).value,{name:p}=this.options;l&&p&&b3(l,p,g),n.setWithVelocity(d.sample(Math.max(0,f-h)).value,g,h),d.stop()}}const OT=(t,e)=>e==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&(aa.test(t)||t==="0")&&!t.startsWith("url("));function PW(t){const e=t[0];if(t.length===1)return!0;for(let n=0;n<t.length;n++)if(t[n]!==e)return!0}function jW(t,e,n,i){const r=t[0];if(r===null)return!1;if(e==="display"||e==="visibility")return!0;const l=t[t.length-1],u=OT(r,e),d=OT(l,e);return!u||!d?!1:PW(t)||(n==="spring"||T3(n))&&i}function ty(t){t.duration=0,t.type="keyframes"}const A3=new Set(["opacity","clipPath","filter","transform"]),zW=/^(?:oklch|oklab|lab|lch|color|color-mix|light-dark)\(/;function FW(t){for(let e=0;e<t.length;e++)if(typeof t[e]=="string"&&zW.test(t[e]))return!0;return!1}const UW=new Set(["color","backgroundColor","outlineColor","fill","stroke","borderColor","borderTopColor","borderRightColor","borderBottomColor","borderLeftColor"]),VW=HC(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function $W(t){const{motionValue:e,name:n,repeatDelay:i,repeatType:r,damping:l,type:u,keyframes:d}=t;if(!(e?.owner?.current instanceof HTMLElement))return!1;const{onUpdate:h,transformTemplate:g}=e.owner.getProps();return VW()&&n&&(A3.has(n)||UW.has(n)&&FW(d))&&(n!=="transform"||!g)&&!h&&!i&&r!=="mirror"&&l!==0&&u!=="inertia"}const qW=40;class GW extends wv{constructor({autoplay:e=!0,delay:n=0,type:i="keyframes",repeat:r=0,repeatDelay:l=0,repeatType:u="loop",keyframes:d,name:f,motionValue:h,element:g,...p}){super(),this.stop=()=>{this._animation&&(this._animation.stop(),this.stopTimeline?.()),this.keyframeResolver?.cancel()},this.createdAt=tn.now();const v={autoplay:e,delay:n,type:i,repeat:r,repeatDelay:l,repeatType:u,name:f,motionValue:h,element:g,...p},b=g?.KeyframeResolver||Tv;this.keyframeResolver=new b(d,(S,w,T)=>this.onKeyframesResolved(S,w,v,!T),f,h,g),this.keyframeResolver?.scheduleResolve()}onKeyframesResolved(e,n,i,r){this.keyframeResolver=void 0;const{name:l,type:u,velocity:d,delay:f,isHandoff:h,onUpdate:g}=i;this.resolvedAt=tn.now();let p=!0;jW(e,l,u,d)||(p=!1,(Fi.instantAnimations||!f)&&g?.(Of(e,i,n)),e[0]=e[e.length-1],ty(i),i.repeat=0);const b={startTime:r?this.resolvedAt?this.resolvedAt-this.createdAt>qW?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...i,keyframes:e},S=p&&!h&&$W(b),w=b.motionValue?.owner?.current;let T;if(S)try{T=new IW({...b,element:w})}catch{T=new Wd(b)}else T=new Wd(b);T.finished.then(()=>{this.notifyFinished()}).catch(qn),this.pendingTimeline&&(this.stopTimeline=T.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=T}get finished(){return this._animation?this.animation.finished:this._finished}then(e,n){return this.finished.finally(e).then(()=>{})}get animation(){return this._animation||(this.keyframeResolver?.resume(),xW()),this._animation}get duration(){return this.animation.duration}get iterationDuration(){return this.animation.iterationDuration}get time(){return this.animation.time}set time(e){this.animation.time=e}get speed(){return this.animation.speed}get state(){return this.animation.state}set speed(e){this.animation.speed=e}get startTime(){return this.animation.startTime}attachTimeline(e){return this._animation?this.stopTimeline=this.animation.attachTimeline(e):this.pendingTimeline=e,()=>this.stop()}play(){this.animation.play()}pause(){this.animation.pause()}complete(){this.animation.complete()}cancel(){this._animation&&this.animation.cancel(),this.keyframeResolver?.cancel()}}function C3(t,e,n,i=0,r=1){const l=Array.from(t).sort((h,g)=>h.sortNodePosition(g)).indexOf(e),u=t.size,d=(u-1)*i;return typeof n=="function"?n(l,u):r===1?l*i:d-l*i}const KW=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function HW(t){const e=KW.exec(t);if(!e)return[,];const[,n,i,r]=e;return[`--${n??i}`,r]}function x3(t,e,n=1){const[i,r]=HW(t);if(!i)return;const l=window.getComputedStyle(e).getPropertyValue(i);if(l){const u=l.trim();return qC(u)?parseFloat(u):u}return yv(r)?x3(r,e,n+1):r}const YW={type:"spring",stiffness:500,damping:25,restSpeed:10},XW=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),WW={type:"keyframes",duration:.8},ZW={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},JW=(t,{keyframes:e})=>e.length>2?WW:so.has(t)?t.startsWith("scale")?XW(e[1]):YW:ZW;function M3(t,e){if(t?.inherit&&e){const{inherit:n,...i}=t;return{...e,...i}}return t}function Ev(t,e){const n=t?.[e]??t?.default??t;return n!==t?M3(n,t):n}const QW=new Set(["when","delay","delayChildren","staggerChildren","staggerDirection","repeat","repeatType","repeatDelay","from","elapsed"]);function eZ(t){for(const e in t)if(!QW.has(e))return!0;return!1}const Rv=(t,e,n,i={},r,l)=>u=>{const d=Ev(i,t)||{},f=d.delay||i.delay||0;let{elapsed:h=0}=i;h=h-En(f);const g={keyframes:Array.isArray(n)?n:[null,n],ease:"easeOut",velocity:e.getVelocity(),...d,delay:-h,onUpdate:v=>{e.set(v),d.onUpdate&&d.onUpdate(v)},onComplete:()=>{u(),d.onComplete&&d.onComplete()},name:t,motionValue:e,element:l?void 0:r};eZ(d)||Object.assign(g,JW(t,g)),g.duration&&(g.duration=En(g.duration)),g.repeatDelay&&(g.repeatDelay=En(g.repeatDelay)),g.from!==void 0&&(g.keyframes[0]=g.from);let p=!1;if((g.type===!1||g.duration===0&&!g.repeatDelay)&&(ty(g),g.delay===0&&(p=!0)),(Fi.instantAnimations||Fi.skipAnimations||r?.shouldSkipAnimations)&&(p=!0,ty(g),g.delay=0),g.allowFlatten=!d.type&&!d.ease,p&&!l&&e.get()!==void 0){const v=Of(g.keyframes,d);if(v!==void 0){nt.update(()=>{g.onUpdate(v),g.onComplete()});return}}return d.isSync?new Wd(g):new GW(g)};function kT(t){const e=[{},{}];return t?.values.forEach((n,i)=>{e[0][i]=n.get(),e[1][i]=n.getVelocity()}),e}function Av(t,e,n,i){if(typeof e=="function"){const[r,l]=kT(i);e=e(n!==void 0?n:t.custom,r,l)}if(typeof e=="string"&&(e=t.variants&&t.variants[e]),typeof e=="function"){const[r,l]=kT(i);e=e(n!==void 0?n:t.custom,r,l)}return e}function As(t,e,n){const i=t.getProps();return Av(i,e,n!==void 0?n:i.custom,t)}const O3=new Set(["width","height","top","left","right","bottom",...io]),LT=30,tZ=t=>!isNaN(parseFloat(t));class nZ{constructor(e,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=i=>{const r=tn.now();if(this.updatedAt!==r&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(i),this.current!==this.prev&&(this.events.change?.notify(this.current),this.dependents))for(const l of this.dependents)l.dirty()},this.hasAnimated=!1,this.setCurrent(e),this.owner=n.owner}setCurrent(e){this.current=e,this.updatedAt=tn.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=tZ(this.current))}setPrevFrameValue(e=this.current){this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt}onChange(e){return this.on("change",e)}on(e,n){this.events[e]||(this.events[e]=new gv);const i=this.events[e].add(n);return e==="change"?()=>{i(),nt.read(()=>{this.events.change.getSize()||this.stop()})}:i}clearListeners(){for(const e in this.events)this.events[e].clear()}attach(e,n){this.passiveEffect=e,this.stopPassiveEffect=n}set(e){this.passiveEffect?this.passiveEffect(e,this.updateAndNotify):this.updateAndNotify(e)}setWithVelocity(e,n,i){this.set(n),this.prev=void 0,this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt-i}jump(e,n=!0){this.updateAndNotify(e),this.prev=e,this.prevUpdatedAt=this.prevFrameValue=void 0,n&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}dirty(){this.events.change?.notify(this.current)}addDependent(e){this.dependents||(this.dependents=new Set),this.dependents.add(e)}removeDependent(e){this.dependents&&this.dependents.delete(e)}get(){return this.current}getPrevious(){return this.prev}getVelocity(){const e=tn.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>LT)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,LT);return YC(parseFloat(this.current)-parseFloat(this.prevFrameValue),n)}start(e){return this.stop(),new Promise(n=>{this.hasAnimated=!0,this.animation=e(n),this.events.animationStart&&this.events.animationStart.notify()}).then(()=>{this.events.animationComplete&&this.events.animationComplete.notify(),this.clearAnimation()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){delete this.animation}destroy(){this.dependents?.clear(),this.events.destroy?.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function Jr(t,e){return new nZ(t,e)}const ny=t=>Array.isArray(t);function aZ(t,e,n){t.hasValue(e)?t.getValue(e).set(n):t.addValue(e,Jr(n))}function iZ(t){return ny(t)?t[t.length-1]||0:t}function sZ(t,e){const n=As(t,e);let{transitionEnd:i={},transition:r={},...l}=n||{};l={...l,...i};for(const u in l){const d=iZ(l[u]);aZ(t,u,d)}}const Ut=t=>!!(t&&t.getVelocity);function rZ(t){return!!(Ut(t)&&t.add)}function ay(t,e){const n=t.getValue("willChange");if(rZ(n))return n.add(e);if(!n&&Fi.WillChange){const i=new Fi.WillChange("auto");t.addValue("willChange",i),i.add(e)}}function Cv(t){return t.replace(/([A-Z])/g,e=>`-${e.toLowerCase()}`)}const oZ="framerAppearId",k3="data-"+Cv(oZ);function L3(t){return t.props[k3]}function lZ({protectedKeys:t,needsAnimating:e},n){const i=t.hasOwnProperty(n)&&e[n]!==!0;return e[n]=!1,i}function D3(t,e,{delay:n=0,transitionOverride:i,type:r}={}){let{transition:l,transitionEnd:u,...d}=e;const f=t.getDefaultTransition();l=l?M3(l,f):f;const h=l?.reduceMotion;i&&(l=i);const g=[],p=r&&t.animationState&&t.animationState.getState()[r];for(const v in d){const b=t.getValue(v,t.latestValues[v]??null),S=d[v];if(S===void 0||p&&lZ(p,v))continue;const w={delay:n,...Ev(l||{},v)},T=b.get();if(T!==void 0&&!b.isAnimating()&&!Array.isArray(S)&&S===T&&!w.velocity){nt.update(()=>b.set(S));continue}let E=!1;if(window.MotionHandoffAnimation){const L=L3(t);if(L){const M=window.MotionHandoffAnimation(L,v,nt);M!==null&&(w.startTime=M,E=!0)}}ay(t,v);const C=h??t.shouldReduceMotion;b.start(Rv(v,b,S,C&&O3.has(v)?{type:!1}:w,t,E));const O=b.animation;O&&g.push(O)}if(u){const v=()=>nt.update(()=>{u&&sZ(t,u)});g.length?Promise.all(g).then(v):v()}return g}function iy(t,e,n={}){const i=As(t,e,n.type==="exit"?t.presenceContext?.custom:void 0);let{transition:r=t.getDefaultTransition()||{}}=i||{};n.transitionOverride&&(r=n.transitionOverride);const l=i?()=>Promise.all(D3(t,i,n)):()=>Promise.resolve(),u=t.variantChildren&&t.variantChildren.size?(f=0)=>{const{delayChildren:h=0,staggerChildren:g,staggerDirection:p}=r;return uZ(t,e,f,h,g,p,n)}:()=>Promise.resolve(),{when:d}=r;if(d){const[f,h]=d==="beforeChildren"?[l,u]:[u,l];return f().then(()=>h())}else return Promise.all([l(),u(n.delay)])}function uZ(t,e,n=0,i=0,r=0,l=1,u){const d=[];for(const f of t.variantChildren)f.notify("AnimationStart",e),d.push(iy(f,e,{...u,delay:n+(typeof i=="function"?0:i)+C3(t.variantChildren,f,i,r,l)}).then(()=>f.notify("AnimationComplete",e)));return Promise.all(d)}function cZ(t,e,n={}){t.notify("AnimationStart",e);let i;if(Array.isArray(e)){const r=e.map(l=>iy(t,l,n));i=Promise.all(r)}else if(typeof e=="string")i=iy(t,e,n);else{const r=typeof e=="function"?As(t,e,n.custom):e;i=Promise.all(D3(t,r,n))}return i.then(()=>{t.notify("AnimationComplete",e)})}const dZ={test:t=>t==="auto",parse:t=>t},B3=t=>e=>e.test(t),N3=[ao,pe,Ca,Di,PX,IX,dZ],DT=t=>N3.find(B3(t));function fZ(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||KC(t):!0}const hZ=new Set(["brightness","contrast","saturate","opacity"]);function gZ(t){const[e,n]=t.slice(0,-1).split("(");if(e==="drop-shadow")return t;const[i]=n.match(vv)||[];if(!i)return t;const r=n.replace(i,"");let l=hZ.has(e)?1:0;return i!==n&&(l*=100),e+"("+l+r+")"}const mZ=/\b([a-z-]*)\(.*?\)/gu,sy={...aa,getAnimatableNone:t=>{const e=t.match(mZ);return e?e.map(gZ).join(" "):t}},ry={...aa,getAnimatableNone:t=>{const e=aa.parse(t);return aa.createTransformer(t)(e.map(i=>typeof i=="number"?0:typeof i=="object"?{...i,alpha:1}:i))}},BT={...ao,transform:Math.round},pZ={rotate:Di,rotateX:Di,rotateY:Di,rotateZ:Di,scale:Vc,scaleX:Vc,scaleY:Vc,scaleZ:Vc,skew:Di,skewX:Di,skewY:Di,distance:pe,translateX:pe,translateY:pe,translateZ:pe,x:pe,y:pe,z:pe,perspective:pe,transformPerspective:pe,opacity:jl,originX:ST,originY:ST,originZ:pe},xv={borderWidth:pe,borderTopWidth:pe,borderRightWidth:pe,borderBottomWidth:pe,borderLeftWidth:pe,borderRadius:pe,borderTopLeftRadius:pe,borderTopRightRadius:pe,borderBottomRightRadius:pe,borderBottomLeftRadius:pe,width:pe,maxWidth:pe,height:pe,maxHeight:pe,top:pe,right:pe,bottom:pe,left:pe,inset:pe,insetBlock:pe,insetBlockStart:pe,insetBlockEnd:pe,insetInline:pe,insetInlineStart:pe,insetInlineEnd:pe,padding:pe,paddingTop:pe,paddingRight:pe,paddingBottom:pe,paddingLeft:pe,paddingBlock:pe,paddingBlockStart:pe,paddingBlockEnd:pe,paddingInline:pe,paddingInlineStart:pe,paddingInlineEnd:pe,margin:pe,marginTop:pe,marginRight:pe,marginBottom:pe,marginLeft:pe,marginBlock:pe,marginBlockStart:pe,marginBlockEnd:pe,marginInline:pe,marginInlineStart:pe,marginInlineEnd:pe,fontSize:pe,backgroundPositionX:pe,backgroundPositionY:pe,...pZ,zIndex:BT,fillOpacity:jl,strokeOpacity:jl,numOctaves:BT},yZ={...xv,color:St,backgroundColor:St,outlineColor:St,fill:St,stroke:St,borderColor:St,borderTopColor:St,borderRightColor:St,borderBottomColor:St,borderLeftColor:St,filter:sy,WebkitFilter:sy,mask:ry,WebkitMask:ry},I3=t=>yZ[t],vZ=new Set([sy,ry]);function P3(t,e){let n=I3(t);return vZ.has(n)||(n=aa),n.getAnimatableNone?n.getAnimatableNone(e):void 0}const bZ=new Set(["auto","none","0"]);function SZ(t,e,n){let i=0,r;for(;i<t.length&&!r;){const l=t[i];typeof l=="string"&&!bZ.has(l)&&Zr(l).values.length&&(r=t[i]),i++}if(r&&n)for(const l of e)t[l]=P3(n,r)}class _Z extends Tv{constructor(e,n,i,r,l){super(e,n,i,r,l,!0)}readKeyframes(){const{unresolvedKeyframes:e,element:n,name:i}=this;if(!n||!n.current)return;super.readKeyframes();for(let g=0;g<e.length;g++){let p=e[g];if(typeof p=="string"&&(p=p.trim(),yv(p))){const v=x3(p,n.current);v!==void 0&&(e[g]=v),g===e.length-1&&(this.finalKeyframe=p)}}if(this.resolveNoneKeyframes(),!O3.has(i)||e.length!==2)return;const[r,l]=e,u=DT(r),d=DT(l),f=bT(r),h=bT(l);if(f!==h&&Ni[i]){this.needsMeasurement=!0;return}if(u!==d)if(xT(u)&&xT(d))for(let g=0;g<e.length;g++){const p=e[g];typeof p=="string"&&(e[g]=parseFloat(p))}else Ni[i]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:e,name:n}=this,i=[];for(let r=0;r<e.length;r++)(e[r]===null||fZ(e[r]))&&i.push(r);i.length&&SZ(e,i,n)}measureInitialState(){const{element:e,unresolvedKeyframes:n,name:i}=this;if(!e||!e.current)return;i==="height"&&(this.suspendedScrollY=window.pageYOffset),this.measuredOrigin=Ni[i](e.measureViewportBox(),window.getComputedStyle(e.current)),n[0]=this.measuredOrigin;const r=n[n.length-1];r!==void 0&&e.getValue(i,r).jump(r,!1)}measureEndState(){const{element:e,name:n,unresolvedKeyframes:i}=this;if(!e||!e.current)return;const r=e.getValue(n);r&&r.jump(this.measuredOrigin,!1);const l=i.length-1,u=i[l];i[l]=Ni[n](e.measureViewportBox(),window.getComputedStyle(e.current)),u!==null&&this.finalKeyframe===void 0&&(this.finalKeyframe=u),this.removedTransforms?.length&&this.removedTransforms.forEach(([d,f])=>{e.getValue(d).set(f)}),this.resolveNoneKeyframes()}}function j3(t,e,n){if(t==null)return[];if(t instanceof EventTarget)return[t];if(typeof t=="string"){let i=document;const r=n?.[t]??i.querySelectorAll(t);return r?Array.from(r):[]}return Array.from(t).filter(i=>i!=null)}const z3=(t,e)=>e&&typeof t=="number"?e.transform(t):t;function dd(t){return GC(t)&&"offsetHeight"in t&&!("ownerSVGElement"in t)}const{schedule:Mv}=s3(queueMicrotask,!1),Qn={x:!1,y:!1};function F3(){return Qn.x||Qn.y}function wZ(t){return t==="x"||t==="y"?Qn[t]?null:(Qn[t]=!0,()=>{Qn[t]=!1}):Qn.x||Qn.y?null:(Qn.x=Qn.y=!0,()=>{Qn.x=Qn.y=!1})}function U3(t,e){const n=j3(t),i=new AbortController,r={passive:!0,...e,signal:i.signal};return[n,r,()=>i.abort()]}function TZ(t){return!(t.pointerType==="touch"||F3())}function EZ(t,e,n={}){const[i,r,l]=U3(t,n);return i.forEach(u=>{let d=!1,f=!1,h;const g=()=>{u.removeEventListener("pointerleave",S)},p=T=>{h&&(h(T),h=void 0),g()},v=T=>{d=!1,window.removeEventListener("pointerup",v),window.removeEventListener("pointercancel",v),f&&(f=!1,p(T))},b=()=>{d=!0,window.addEventListener("pointerup",v,r),window.addEventListener("pointercancel",v,r)},S=T=>{if(T.pointerType!=="touch"){if(d){f=!0;return}p(T)}},w=T=>{if(!TZ(T))return;f=!1;const E=e(u,T);typeof E=="function"&&(h=E,u.addEventListener("pointerleave",S,r))};u.addEventListener("pointerenter",w,r),u.addEventListener("pointerdown",b,r)}),l}const V3=(t,e)=>e?t===e?!0:V3(t,e.parentElement):!1,Ov=t=>t.pointerType==="mouse"?typeof t.button!="number"||t.button<=0:t.isPrimary!==!1,RZ=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function AZ(t){return RZ.has(t.tagName)||t.isContentEditable===!0}const CZ=new Set(["INPUT","SELECT","TEXTAREA"]);function xZ(t){return CZ.has(t.tagName)||t.isContentEditable===!0}const fd=new WeakSet;function NT(t){return e=>{e.key==="Enter"&&t(e)}}function $m(t,e){t.dispatchEvent(new PointerEvent("pointer"+e,{isPrimary:!0,bubbles:!0}))}const MZ=(t,e)=>{const n=t.currentTarget;if(!n)return;const i=NT(()=>{if(fd.has(n))return;$m(n,"down");const r=NT(()=>{$m(n,"up")}),l=()=>$m(n,"cancel");n.addEventListener("keyup",r,e),n.addEventListener("blur",l,e)});n.addEventListener("keydown",i,e),n.addEventListener("blur",()=>n.removeEventListener("keydown",i),e)};function IT(t){return Ov(t)&&!F3()}const PT=new WeakSet;function OZ(t,e,n={}){const[i,r,l]=U3(t,n),u=d=>{const f=d.currentTarget;if(!IT(d)||PT.has(d))return;fd.add(f),n.stopPropagation&&PT.add(d);const h=e(f,d),g=(b,S)=>{window.removeEventListener("pointerup",p),window.removeEventListener("pointercancel",v),fd.has(f)&&fd.delete(f),IT(b)&&typeof h=="function"&&h(b,{success:S})},p=b=>{g(b,f===window||f===document||n.useGlobalTarget||V3(f,b.target))},v=b=>{g(b,!1)};window.addEventListener("pointerup",p,r),window.addEventListener("pointercancel",v,r)};return i.forEach(d=>{(n.useGlobalTarget?window:d).addEventListener("pointerdown",u,r),dd(d)&&(d.addEventListener("focus",h=>MZ(h,r)),!AZ(d)&&!d.hasAttribute("tabindex")&&(d.tabIndex=0))}),l}function kv(t){return GC(t)&&"ownerSVGElement"in t}const hd=new WeakMap;let gd;const $3=(t,e,n)=>(i,r)=>r&&r[0]?r[0][t+"Size"]:kv(i)&&"getBBox"in i?i.getBBox()[e]:i[n],kZ=$3("inline","width","offsetWidth"),LZ=$3("block","height","offsetHeight");function DZ({target:t,borderBoxSize:e}){hd.get(t)?.forEach(n=>{n(t,{get width(){return kZ(t,e)},get height(){return LZ(t,e)}})})}function BZ(t){t.forEach(DZ)}function NZ(){typeof ResizeObserver>"u"||(gd=new ResizeObserver(BZ))}function IZ(t,e){gd||NZ();const n=j3(t);return n.forEach(i=>{let r=hd.get(i);r||(r=new Set,hd.set(i,r)),r.add(e),gd?.observe(i)}),()=>{n.forEach(i=>{const r=hd.get(i);r?.delete(e),r?.size||gd?.unobserve(i)})}}const md=new Set;let Br;function PZ(){Br=()=>{const t={get width(){return window.innerWidth},get height(){return window.innerHeight}};md.forEach(e=>e(t))},window.addEventListener("resize",Br)}function jZ(t){return md.add(t),Br||PZ(),()=>{md.delete(t),!md.size&&typeof Br=="function"&&(window.removeEventListener("resize",Br),Br=void 0)}}function jT(t,e){return typeof t=="function"?jZ(t):IZ(t,e)}function zZ(t){return kv(t)&&t.tagName==="svg"}const FZ=[...N3,St,aa],UZ=t=>FZ.find(B3(t)),zT=()=>({translate:0,scale:1,origin:0,originPoint:0}),Nr=()=>({x:zT(),y:zT()}),FT=()=>({min:0,max:0}),Ct=()=>({x:FT(),y:FT()}),VZ=new WeakMap;function kf(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function zl(t){return typeof t=="string"||Array.isArray(t)}const Lv=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],Dv=["initial",...Lv];function Lf(t){return kf(t.animate)||Dv.some(e=>zl(t[e]))}function q3(t){return!!(Lf(t)||t.variants)}function $Z(t,e,n){for(const i in e){const r=e[i],l=n[i];if(Ut(r))t.addValue(i,r);else if(Ut(l))t.addValue(i,Jr(r,{owner:t}));else if(l!==r)if(t.hasValue(i)){const u=t.getValue(i);u.liveStyle===!0?u.jump(r):u.hasAnimated||u.set(r)}else{const u=t.getStaticValue(i);t.addValue(i,Jr(u!==void 0?u:r,{owner:t}))}}for(const i in n)e[i]===void 0&&t.removeValue(i);return e}const oy={current:null},G3={current:!1},qZ=typeof window<"u";function GZ(){if(G3.current=!0,!!qZ)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),e=()=>oy.current=t.matches;t.addEventListener("change",e),e()}else oy.current=!1}const UT=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];let Zd={};function K3(t){Zd=t}function KZ(){return Zd}class HZ{scrapeMotionValuesFromProps(e,n,i){return{}}constructor({parent:e,props:n,presenceContext:i,reducedMotionConfig:r,skipAnimations:l,blockInitialAnimation:u,visualState:d},f={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.shouldSkipAnimations=!1,this.values=new Map,this.KeyframeResolver=Tv,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.hasBeenMounted=!1,this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const b=tn.now();this.renderScheduledAt<b&&(this.renderScheduledAt=b,nt.render(this.render,!1,!0))};const{latestValues:h,renderState:g}=d;this.latestValues=h,this.baseTarget={...h},this.initialValues=n.initial?{...h}:{},this.renderState=g,this.parent=e,this.props=n,this.presenceContext=i,this.depth=e?e.depth+1:0,this.reducedMotionConfig=r,this.skipAnimationsConfig=l,this.options=f,this.blockInitialAnimation=!!u,this.isControllingVariants=Lf(n),this.isVariantNode=q3(n),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(e&&e.current);const{willChange:p,...v}=this.scrapeMotionValuesFromProps(n,{},this);for(const b in v){const S=v[b];h[b]!==void 0&&Ut(S)&&S.set(h[b])}}mount(e){if(this.hasBeenMounted)for(const n in this.initialValues)this.values.get(n)?.jump(this.initialValues[n]),this.latestValues[n]=this.initialValues[n];this.current=e,VZ.set(e,this),this.projection&&!this.projection.instance&&this.projection.mount(e),this.parent&&this.isVariantNode&&!this.isControllingVariants&&(this.removeFromVariantTree=this.parent.addVariantChild(this)),this.values.forEach((n,i)=>this.bindToMotionValue(i,n)),this.reducedMotionConfig==="never"?this.shouldReduceMotion=!1:this.reducedMotionConfig==="always"?this.shouldReduceMotion=!0:(G3.current||GZ(),this.shouldReduceMotion=oy.current),this.shouldSkipAnimations=this.skipAnimationsConfig??!1,this.parent?.addChild(this),this.update(this.props,this.presenceContext),this.hasBeenMounted=!0}unmount(){this.projection&&this.projection.unmount(),Ui(this.notifyUpdate),Ui(this.render),this.valueSubscriptions.forEach(e=>e()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),this.parent?.removeChild(this);for(const e in this.events)this.events[e].clear();for(const e in this.features){const n=this.features[e];n&&(n.unmount(),n.isMounted=!1)}this.current=null}addChild(e){this.children.add(e),this.enteringChildren??(this.enteringChildren=new Set),this.enteringChildren.add(e)}removeChild(e){this.children.delete(e),this.enteringChildren&&this.enteringChildren.delete(e)}bindToMotionValue(e,n){if(this.valueSubscriptions.has(e)&&this.valueSubscriptions.get(e)(),n.accelerate&&A3.has(e)&&this.current instanceof HTMLElement){const{factory:u,keyframes:d,times:f,ease:h,duration:g}=n.accelerate,p=new E3({element:this.current,name:e,keyframes:d,times:f,ease:h,duration:En(g)}),v=u(p);this.valueSubscriptions.set(e,()=>{v(),p.cancel()});return}const i=so.has(e);i&&this.onBindTransform&&this.onBindTransform();const r=n.on("change",u=>{this.latestValues[e]=u,this.props.onUpdate&&nt.preRender(this.notifyUpdate),i&&this.projection&&(this.projection.isTransformDirty=!0),this.scheduleRender()});let l;typeof window<"u"&&window.MotionCheckAppearSync&&(l=window.MotionCheckAppearSync(this,e,n)),this.valueSubscriptions.set(e,()=>{r(),l&&l(),n.owner&&n.stop()})}sortNodePosition(e){return!this.current||!this.sortInstanceNodePosition||this.type!==e.type?0:this.sortInstanceNodePosition(this.current,e.current)}updateFeatures(){let e="animation";for(e in Zd){const n=Zd[e];if(!n)continue;const{isEnabled:i,Feature:r}=n;if(!this.features[e]&&r&&i(this.props)&&(this.features[e]=new r(this)),this.features[e]){const l=this.features[e];l.isMounted?l.update():(l.mount(),l.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):Ct()}getStaticValue(e){return this.latestValues[e]}setStaticValue(e,n){this.latestValues[e]=n}update(e,n){(e.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=e,this.prevPresenceContext=this.presenceContext,this.presenceContext=n;for(let i=0;i<UT.length;i++){const r=UT[i];this.propEventSubscriptions[r]&&(this.propEventSubscriptions[r](),delete this.propEventSubscriptions[r]);const l="on"+r,u=e[l];u&&(this.propEventSubscriptions[r]=this.on(r,u))}this.prevMotionValues=$Z(this,this.scrapeMotionValuesFromProps(e,this.prevProps||{},this),this.prevMotionValues),this.handleChildMotionValue&&this.handleChildMotionValue()}getProps(){return this.props}getVariant(e){return this.props.variants?this.props.variants[e]:void 0}getDefaultTransition(){return this.props.transition}getTransformPagePoint(){return this.props.transformPagePoint}getClosestVariantNode(){return this.isVariantNode?this:this.parent?this.parent.getClosestVariantNode():void 0}addVariantChild(e){const n=this.getClosestVariantNode();if(n)return n.variantChildren&&n.variantChildren.add(e),()=>n.variantChildren.delete(e)}addValue(e,n){const i=this.values.get(e);n!==i&&(i&&this.removeValue(e),this.bindToMotionValue(e,n),this.values.set(e,n),this.latestValues[e]=n.get())}removeValue(e){this.values.delete(e);const n=this.valueSubscriptions.get(e);n&&(n(),this.valueSubscriptions.delete(e)),delete this.latestValues[e],this.removeValueFromRenderState(e,this.renderState)}hasValue(e){return this.values.has(e)}getValue(e,n){if(this.props.values&&this.props.values[e])return this.props.values[e];let i=this.values.get(e);return i===void 0&&n!==void 0&&(i=Jr(n===null?void 0:n,{owner:this}),this.addValue(e,i)),i}readValue(e,n){let i=this.latestValues[e]!==void 0||!this.current?this.latestValues[e]:this.getBaseTargetFromProps(this.props,e)??this.readValueFromInstance(this.current,e,this.options);return i!=null&&(typeof i=="string"&&(qC(i)||KC(i))?i=parseFloat(i):!UZ(i)&&aa.test(n)&&(i=P3(e,n)),this.setBaseTarget(e,Ut(i)?i.get():i)),Ut(i)?i.get():i}setBaseTarget(e,n){this.baseTarget[e]=n}getBaseTarget(e){const{initial:n}=this.props;let i;if(typeof n=="string"||typeof n=="object"){const l=Av(this.props,n,this.presenceContext?.custom);l&&(i=l[e])}if(n&&i!==void 0)return i;const r=this.getBaseTargetFromProps(this.props,e);return r!==void 0&&!Ut(r)?r:this.initialValues[e]!==void 0&&i===void 0?void 0:this.baseTarget[e]}on(e,n){return this.events[e]||(this.events[e]=new gv),this.events[e].add(n)}notify(e,...n){this.events[e]&&this.events[e].notify(...n)}scheduleRenderMicrotask(){Mv.render(this.render)}}class H3 extends HZ{constructor(){super(...arguments),this.KeyframeResolver=_Z}sortInstanceNodePosition(e,n){return e.compareDocumentPosition(n)&2?1:-1}getBaseTargetFromProps(e,n){const i=e.style;return i?i[n]:void 0}removeValueFromRenderState(e,{vars:n,style:i}){delete n[e],delete i[e]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:e}=this.props;Ut(e)&&(this.childSubscription=e.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}class Vi{constructor(e){this.isMounted=!1,this.node=e}update(){}}function Y3({top:t,left:e,right:n,bottom:i}){return{x:{min:e,max:n},y:{min:t,max:i}}}function YZ({x:t,y:e}){return{top:e.min,right:t.max,bottom:e.max,left:t.min}}function XZ(t,e){if(!e)return t;const n=e({x:t.left,y:t.top}),i=e({x:t.right,y:t.bottom});return{top:n.y,left:n.x,bottom:i.y,right:i.x}}function qm(t){return t===void 0||t===1}function ly({scale:t,scaleX:e,scaleY:n}){return!qm(t)||!qm(e)||!qm(n)}function ps(t){return ly(t)||X3(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function X3(t){return VT(t.x)||VT(t.y)}function VT(t){return t&&t!=="0%"}function Jd(t,e,n){const i=t-n,r=e*i;return n+r}function $T(t,e,n,i,r){return r!==void 0&&(t=Jd(t,r,i)),Jd(t,n,i)+e}function uy(t,e=0,n=1,i,r){t.min=$T(t.min,e,n,i,r),t.max=$T(t.max,e,n,i,r)}function W3(t,{x:e,y:n}){uy(t.x,e.translate,e.scale,e.originPoint),uy(t.y,n.translate,n.scale,n.originPoint)}const qT=.999999999999,GT=1.0000000000001;function WZ(t,e,n,i=!1){const r=n.length;if(!r)return;e.x=e.y=1;let l,u;for(let d=0;d<r;d++){l=n[d],u=l.projectionDelta;const{visualElement:f}=l.options;f&&f.props.style&&f.props.style.display==="contents"||(i&&l.options.layoutScroll&&l.scroll&&l!==l.root&&(va(t.x,-l.scroll.offset.x),va(t.y,-l.scroll.offset.y)),u&&(e.x*=u.x.scale,e.y*=u.y.scale,W3(t,u)),i&&ps(l.latestValues)&&pd(t,l.latestValues,l.layout?.layoutBox))}e.x<GT&&e.x>qT&&(e.x=1),e.y<GT&&e.y>qT&&(e.y=1)}function va(t,e){t.min+=e,t.max+=e}function KT(t,e,n,i,r=.5){const l=st(t.min,t.max,r);uy(t,e,n,l,i)}function HT(t,e){return typeof t=="string"?parseFloat(t)/100*(e.max-e.min):t}function pd(t,e,n){const i=n??t;KT(t.x,HT(e.x,i.x),e.scaleX,e.scale,e.originX),KT(t.y,HT(e.y,i.y),e.scaleY,e.scale,e.originY)}function Z3(t,e){return Y3(XZ(t.getBoundingClientRect(),e))}function ZZ(t,e,n){const i=Z3(t,n),{scroll:r}=e;return r&&(va(i.x,r.offset.x),va(i.y,r.offset.y)),i}const JZ={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},QZ=io.length;function eJ(t,e,n){let i="",r=!0;for(let l=0;l<QZ;l++){const u=io[l],d=t[u];if(d===void 0)continue;let f=!0;if(typeof d=="number")f=d===(u.startsWith("scale")?1:0);else{const h=parseFloat(d);f=u.startsWith("scale")?h===1:h===0}if(!f||n){const h=z3(d,xv[u]);if(!f){r=!1;const g=JZ[u]||u;i+=`${g}(${h}) `}n&&(e[u]=h)}}return i=i.trim(),n?i=n(e,r?"":i):r&&(i="none"),i}function Bv(t,e,n){const{style:i,vars:r,transformOrigin:l}=t;let u=!1,d=!1;for(const f in e){const h=e[f];if(so.has(f)){u=!0;continue}else if(o3(f)){r[f]=h;continue}else{const g=z3(h,xv[f]);f.startsWith("origin")?(d=!0,l[f]=g):i[f]=g}}if(e.transform||(u||n?i.transform=eJ(e,t.transform,n):i.transform&&(i.transform="none")),d){const{originX:f="50%",originY:h="50%",originZ:g=0}=l;i.transformOrigin=`${f} ${h} ${g}`}}function J3(t,{style:e,vars:n},i,r){const l=t.style;let u;for(u in e)l[u]=e[u];r?.applyProjectionStyles(l,i);for(u in n)l.setProperty(u,n[u])}function YT(t,e){return e.max===e.min?0:t/(e.max-e.min)*100}const il={correct:(t,e)=>{if(!e.target)return t;if(typeof t=="string")if(pe.test(t))t=parseFloat(t);else return t;const n=YT(t,e.target.x),i=YT(t,e.target.y);return`${n}% ${i}%`}},tJ={correct:(t,{treeScale:e,projectionDelta:n})=>{const i=t,r=aa.parse(t);if(r.length>5)return i;const l=aa.createTransformer(t),u=typeof r[0]!="number"?1:0,d=n.x.scale*e.x,f=n.y.scale*e.y;r[0+u]/=d,r[1+u]/=f;const h=st(d,f,.5);return typeof r[2+u]=="number"&&(r[2+u]/=h),typeof r[3+u]=="number"&&(r[3+u]/=h),l(r)}},cy={borderRadius:{...il,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:il,borderTopRightRadius:il,borderBottomLeftRadius:il,borderBottomRightRadius:il,boxShadow:tJ};function Q3(t,{layout:e,layoutId:n}){return so.has(t)||t.startsWith("origin")||(e||n!==void 0)&&(!!cy[t]||t==="opacity")}function Nv(t,e,n){const i=t.style,r=e?.style,l={};if(!i)return l;for(const u in i)(Ut(i[u])||r&&Ut(r[u])||Q3(u,t)||n?.getValue(u)?.liveStyle!==void 0)&&(l[u]=i[u]);return l}function nJ(t){return window.getComputedStyle(t)}class aJ extends H3{constructor(){super(...arguments),this.type="html",this.renderInstance=J3}readValueFromInstance(e,n){if(so.has(n))return this.projection?.isProjecting?Wp(n):TW(e,n);{const i=nJ(e),r=(o3(n)?i.getPropertyValue(n):i[n])||0;return typeof r=="string"?r.trim():r}}measureInstanceViewportBox(e,{transformPagePoint:n}){return Z3(e,n)}build(e,n,i){Bv(e,n,i.transformTemplate)}scrapeMotionValuesFromProps(e,n,i){return Nv(e,n,i)}}const iJ={offset:"stroke-dashoffset",array:"stroke-dasharray"},sJ={offset:"strokeDashoffset",array:"strokeDasharray"};function rJ(t,e,n=1,i=0,r=!0){t.pathLength=1;const l=r?iJ:sJ;t[l.offset]=`${-i}`,t[l.array]=`${e} ${n}`}const oJ=["offsetDistance","offsetPath","offsetRotate","offsetAnchor"];function e6(t,{attrX:e,attrY:n,attrScale:i,pathLength:r,pathSpacing:l=1,pathOffset:u=0,...d},f,h,g){if(Bv(t,d,h),f){t.style.viewBox&&(t.attrs.viewBox=t.style.viewBox);return}t.attrs=t.style,t.style={};const{attrs:p,style:v}=t;p.transform&&(v.transform=p.transform,delete p.transform),(v.transform||p.transformOrigin)&&(v.transformOrigin=p.transformOrigin??"50% 50%",delete p.transformOrigin),v.transform&&(v.transformBox=g?.transformBox??"fill-box",delete p.transformBox);for(const b of oJ)p[b]!==void 0&&(v[b]=p[b],delete p[b]);e!==void 0&&(p.x=e),n!==void 0&&(p.y=n),i!==void 0&&(p.scale=i),r!==void 0&&rJ(p,r,l,u,!1)}const t6=new Set(["baseFrequency","diffuseConstant","kernelMatrix","kernelUnitLength","keySplines","keyTimes","limitingConeAngle","markerHeight","markerWidth","numOctaves","targetX","targetY","surfaceScale","specularConstant","specularExponent","stdDeviation","tableValues","viewBox","gradientTransform","pathLength","startOffset","textLength","lengthAdjust"]),n6=t=>typeof t=="string"&&t.toLowerCase()==="svg";function lJ(t,e,n,i){J3(t,e,void 0,i);for(const r in e.attrs)t.setAttribute(t6.has(r)?r:Cv(r),e.attrs[r])}function a6(t,e,n){const i=Nv(t,e,n);for(const r in t)if(Ut(t[r])||Ut(e[r])){const l=io.indexOf(r)!==-1?"attr"+r.charAt(0).toUpperCase()+r.substring(1):r;i[l]=t[r]}return i}class uJ extends H3{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=Ct}getBaseTargetFromProps(e,n){return e[n]}readValueFromInstance(e,n){if(so.has(n)){const i=I3(n);return i&&i.default||0}return n=t6.has(n)?n:Cv(n),e.getAttribute(n)}scrapeMotionValuesFromProps(e,n,i){return a6(e,n,i)}build(e,n,i){e6(e,n,this.isSVGTag,i.transformTemplate,i.style)}renderInstance(e,n,i,r){lJ(e,n,i,r)}mount(e){this.isSVGTag=n6(e.tagName),super.mount(e)}}const cJ=Dv.length;function i6(t){if(!t)return;if(!t.isControllingVariants){const n=t.parent?i6(t.parent)||{}:{};return t.props.initial!==void 0&&(n.initial=t.props.initial),n}const e={};for(let n=0;n<cJ;n++){const i=Dv[n],r=t.props[i];(zl(r)||r===!1)&&(e[i]=r)}return e}function s6(t,e){if(!Array.isArray(e))return!1;const n=e.length;if(n!==t.length)return!1;for(let i=0;i<n;i++)if(e[i]!==t[i])return!1;return!0}const dJ=[...Lv].reverse(),fJ=Lv.length;function hJ(t){return e=>Promise.all(e.map(({animation:n,options:i})=>cZ(t,n,i)))}function gJ(t){let e=hJ(t),n=XT(),i=!0,r=!1;const l=h=>(g,p)=>{const v=As(t,p,h==="exit"?t.presenceContext?.custom:void 0);if(v){const{transition:b,transitionEnd:S,...w}=v;g={...g,...w,...S}}return g};function u(h){e=h(t)}function d(h){const{props:g}=t,p=i6(t.parent)||{},v=[],b=new Set;let S={},w=1/0;for(let E=0;E<fJ;E++){const C=dJ[E],O=n[C],L=g[C]!==void 0?g[C]:p[C],M=zl(L),N=C===h?O.isActive:null;N===!1&&(w=E);let D=L===p[C]&&L!==g[C]&&M;if(D&&(i||r)&&t.manuallyAnimateOnMount&&(D=!1),O.protectedKeys={...S},!O.isActive&&N===null||!L&&!O.prevProp||kf(L)||typeof L=="boolean")continue;if(C==="exit"&&O.isActive&&N!==!0){O.prevResolvedValues&&(S={...S,...O.prevResolvedValues});continue}const j=mJ(O.prevProp,L);let K=j||C===h&&O.isActive&&!D&&M||E>w&&M,X=!1;const z=Array.isArray(L)?L:[L];let ee=z.reduce(l(C),{});N===!1&&(ee={});const{prevResolvedValues:ne={}}=O,le={...ne,...ee},ue=ae=>{K=!0,b.has(ae)&&(X=!0,b.delete(ae)),O.needsAnimating[ae]=!0;const ce=t.getValue(ae);ce&&(ce.liveStyle=!1)};for(const ae in le){const ce=ee[ae],$=ne[ae];if(S.hasOwnProperty(ae))continue;let k=!1;ny(ce)&&ny($)?k=!s6(ce,$):k=ce!==$,k?ce!=null?ue(ae):b.add(ae):ce!==void 0&&b.has(ae)?ue(ae):O.protectedKeys[ae]=!0}O.prevProp=L,O.prevResolvedValues=ee,O.isActive&&(S={...S,...ee}),(i||r)&&t.blockInitialAnimation&&(K=!1);const F=D&&j;K&&(!F||X)&&v.push(...z.map(ae=>{const ce={type:C};if(typeof ae=="string"&&(i||r)&&!F&&t.manuallyAnimateOnMount&&t.parent){const{parent:$}=t,k=As($,ae);if($.enteringChildren&&k){const{delayChildren:V}=k.transition||{};ce.delay=C3($.enteringChildren,t,V)}}return{animation:ae,options:ce}}))}if(b.size){const E={};if(typeof g.initial!="boolean"){const C=As(t,Array.isArray(g.initial)?g.initial[0]:g.initial);C&&C.transition&&(E.transition=C.transition)}b.forEach(C=>{const O=t.getBaseTarget(C),L=t.getValue(C);L&&(L.liveStyle=!0),E[C]=O??null}),v.push({animation:E})}let T=!!v.length;return i&&(g.initial===!1||g.initial===g.animate)&&!t.manuallyAnimateOnMount&&(T=!1),i=!1,r=!1,T?e(v):Promise.resolve()}function f(h,g){if(n[h].isActive===g)return Promise.resolve();t.variantChildren?.forEach(v=>v.animationState?.setActive(h,g)),n[h].isActive=g;const p=d(h);for(const v in n)n[v].protectedKeys={};return p}return{animateChanges:d,setActive:f,setAnimateFunction:u,getState:()=>n,reset:()=>{n=XT(),r=!0}}}function mJ(t,e){return typeof e=="string"?e!==t:Array.isArray(e)?!s6(e,t):!1}function hs(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function XT(){return{animate:hs(!0),whileInView:hs(),whileHover:hs(),whileTap:hs(),whileDrag:hs(),whileFocus:hs(),exit:hs()}}function dy(t,e){t.min=e.min,t.max=e.max}function Zn(t,e){dy(t.x,e.x),dy(t.y,e.y)}function WT(t,e){t.translate=e.translate,t.scale=e.scale,t.originPoint=e.originPoint,t.origin=e.origin}const r6=1e-4,pJ=1-r6,yJ=1+r6,o6=.01,vJ=0-o6,bJ=0+o6;function nn(t){return t.max-t.min}function SJ(t,e,n){return Math.abs(t-e)<=n}function ZT(t,e,n,i=.5){t.origin=i,t.originPoint=st(e.min,e.max,t.origin),t.scale=nn(n)/nn(e),t.translate=st(n.min,n.max,t.origin)-t.originPoint,(t.scale>=pJ&&t.scale<=yJ||isNaN(t.scale))&&(t.scale=1),(t.translate>=vJ&&t.translate<=bJ||isNaN(t.translate))&&(t.translate=0)}function El(t,e,n,i){ZT(t.x,e.x,n.x,i?i.originX:void 0),ZT(t.y,e.y,n.y,i?i.originY:void 0)}function JT(t,e,n,i=0){const r=i?st(n.min,n.max,i):n.min;t.min=r+e.min,t.max=t.min+nn(e)}function _J(t,e,n,i){JT(t.x,e.x,n.x,i?.x),JT(t.y,e.y,n.y,i?.y)}function QT(t,e,n,i=0){const r=i?st(n.min,n.max,i):n.min;t.min=e.min-r,t.max=t.min+nn(e)}function Qd(t,e,n,i){QT(t.x,e.x,n.x,i?.x),QT(t.y,e.y,n.y,i?.y)}function eE(t,e,n,i,r){return t-=e,t=Jd(t,1/n,i),r!==void 0&&(t=Jd(t,1/r,i)),t}function wJ(t,e=0,n=1,i=.5,r,l=t,u=t){if(Ca.test(e)&&(e=parseFloat(e),e=st(u.min,u.max,e/100)-u.min),typeof e!="number")return;let d=st(l.min,l.max,i);t===l&&(d-=e),t.min=eE(t.min,e,n,d,r),t.max=eE(t.max,e,n,d,r)}function tE(t,e,[n,i,r],l,u){wJ(t,e[n],e[i],e[r],e.scale,l,u)}const TJ=["x","scaleX","originX"],EJ=["y","scaleY","originY"];function nE(t,e,n,i){tE(t.x,e,TJ,n?n.x:void 0,i?i.x:void 0),tE(t.y,e,EJ,n?n.y:void 0,i?i.y:void 0)}function aE(t){return t.translate===0&&t.scale===1}function l6(t){return aE(t.x)&&aE(t.y)}function iE(t,e){return t.min===e.min&&t.max===e.max}function RJ(t,e){return iE(t.x,e.x)&&iE(t.y,e.y)}function sE(t,e){return Math.round(t.min)===Math.round(e.min)&&Math.round(t.max)===Math.round(e.max)}function u6(t,e){return sE(t.x,e.x)&&sE(t.y,e.y)}function rE(t){return nn(t.x)/nn(t.y)}function oE(t,e){return t.translate===e.translate&&t.scale===e.scale&&t.originPoint===e.originPoint}function ha(t){return[t("x"),t("y")]}function AJ(t,e,n){let i="";const r=t.x.translate/e.x,l=t.y.translate/e.y,u=n?.z||0;if((r||l||u)&&(i=`translate3d(${r}px, ${l}px, ${u}px) `),(e.x!==1||e.y!==1)&&(i+=`scale(${1/e.x}, ${1/e.y}) `),n){const{transformPerspective:h,rotate:g,rotateX:p,rotateY:v,skewX:b,skewY:S}=n;h&&(i=`perspective(${h}px) ${i}`),g&&(i+=`rotate(${g}deg) `),p&&(i+=`rotateX(${p}deg) `),v&&(i+=`rotateY(${v}deg) `),b&&(i+=`skewX(${b}deg) `),S&&(i+=`skewY(${S}deg) `)}const d=t.x.scale*e.x,f=t.y.scale*e.y;return(d!==1||f!==1)&&(i+=`scale(${d}, ${f})`),i||"none"}const c6=["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"],CJ=c6.length,lE=t=>typeof t=="string"?parseFloat(t):t,uE=t=>typeof t=="number"||pe.test(t);function xJ(t,e,n,i,r,l){r?(t.opacity=st(0,n.opacity??1,MJ(i)),t.opacityExit=st(e.opacity??1,0,OJ(i))):l&&(t.opacity=st(e.opacity??1,n.opacity??1,i));for(let u=0;u<CJ;u++){const d=c6[u];let f=cE(e,d),h=cE(n,d);if(f===void 0&&h===void 0)continue;f||(f=0),h||(h=0),f===0||h===0||uE(f)===uE(h)?(t[d]=Math.max(st(lE(f),lE(h),i),0),(Ca.test(h)||Ca.test(f))&&(t[d]+="%")):t[d]=h}(e.rotate||n.rotate)&&(t.rotate=st(e.rotate||0,n.rotate||0,i))}function cE(t,e){return t[e]!==void 0?t[e]:t.borderRadius}const MJ=d6(0,.5,t3),OJ=d6(.5,.95,qn);function d6(t,e,n){return i=>i<t?0:i>e?1:n(Pl(t,e,i))}function kJ(t,e,n){const i=Ut(t)?t:Jr(t);return i.start(Rv("",i,e,n)),i.animation}function Fl(t,e,n,i={passive:!0}){return t.addEventListener(e,n,i),()=>t.removeEventListener(e,n)}const LJ=(t,e)=>t.depth-e.depth;class DJ{constructor(){this.children=[],this.isDirty=!1}add(e){fv(this.children,e),this.isDirty=!0}remove(e){Kd(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort(LJ),this.isDirty=!1,this.children.forEach(e)}}function BJ(t,e){const n=tn.now(),i=({timestamp:r})=>{const l=r-n;l>=e&&(Ui(i),t(l-e))};return nt.setup(i,!0),()=>Ui(i)}function yd(t){return Ut(t)?t.get():t}class NJ{constructor(){this.members=[]}add(e){fv(this.members,e);for(let n=this.members.length-1;n>=0;n--){const i=this.members[n];if(i===e||i===this.lead||i===this.prevLead)continue;const r=i.instance;(!r||r.isConnected===!1)&&!i.snapshot&&(Kd(this.members,i),i.unmount())}e.scheduleRender()}remove(e){if(Kd(this.members,e),e===this.prevLead&&(this.prevLead=void 0),e===this.lead){const n=this.members[this.members.length-1];n&&this.promote(n)}}relegate(e){for(let n=this.members.indexOf(e)-1;n>=0;n--){const i=this.members[n];if(i.isPresent!==!1&&i.instance?.isConnected!==!1)return this.promote(i),!0}return!1}promote(e,n){const i=this.lead;if(e!==i&&(this.prevLead=i,this.lead=e,e.show(),i)){i.updateSnapshot(),e.scheduleRender();const{layoutDependency:r}=i.options,{layoutDependency:l}=e.options;(r===void 0||r!==l)&&(e.resumeFrom=i,n&&(i.preserveOpacity=!0),i.snapshot&&(e.snapshot=i.snapshot,e.snapshot.latestValues=i.animationValues||i.latestValues),e.root?.isUpdating&&(e.isLayoutDirty=!0)),e.options.crossfade===!1&&i.hide()}}exitAnimationComplete(){this.members.forEach(e=>{e.options.onExitComplete?.(),e.resumingFrom?.options.onExitComplete?.()})}scheduleRender(){this.members.forEach(e=>e.instance&&e.scheduleRender(!1))}removeLeadSnapshot(){this.lead?.snapshot&&(this.lead.snapshot=void 0)}}const vd={hasAnimatedSinceResize:!0,hasEverUpdated:!1},Gm=["","X","Y","Z"],IJ=1e3;let PJ=0;function Km(t,e,n,i){const{latestValues:r}=e;r[t]&&(n[t]=r[t],e.setStaticValue(t,0),i&&(i[t]=0))}function f6(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:e}=t.options;if(!e)return;const n=L3(e);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:r,layoutId:l}=t.options;window.MotionCancelOptimisedAnimation(n,"transform",nt,!(r||l))}const{parent:i}=t;i&&!i.hasCheckedOptimisedAppear&&f6(i)}function h6({attachResizeListener:t,defaultParent:e,measureScroll:n,checkIsScrollRoot:i,resetTransform:r}){return class{constructor(u={},d=e?.()){this.id=PJ++,this.animationId=0,this.animationCommitId=0,this.children=new Set,this.options={},this.isTreeAnimating=!1,this.isAnimationBlocked=!1,this.isLayoutDirty=!1,this.isProjectionDirty=!1,this.isSharedProjectionDirty=!1,this.isTransformDirty=!1,this.updateManuallyBlocked=!1,this.updateBlockedByResize=!1,this.isUpdating=!1,this.isSVG=!1,this.needsReset=!1,this.shouldResetTransform=!1,this.hasCheckedOptimisedAppear=!1,this.treeScale={x:1,y:1},this.eventHandlers=new Map,this.hasTreeAnimated=!1,this.layoutVersion=0,this.updateScheduled=!1,this.scheduleUpdate=()=>this.update(),this.projectionUpdateScheduled=!1,this.checkUpdateFailed=()=>{this.isUpdating&&(this.isUpdating=!1,this.clearAllSnapshots())},this.updateProjection=()=>{this.projectionUpdateScheduled=!1,this.nodes.forEach(FJ),this.nodes.forEach(KJ),this.nodes.forEach(HJ),this.nodes.forEach(UJ)},this.resolvedRelativeTargetAt=0,this.linkedParentVersion=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=u,this.root=d?d.root||d:this,this.path=d?[...d.path,d]:[],this.parent=d,this.depth=d?d.depth+1:0;for(let f=0;f<this.path.length;f++)this.path[f].shouldResetTransform=!0;this.root===this&&(this.nodes=new DJ)}addEventListener(u,d){return this.eventHandlers.has(u)||this.eventHandlers.set(u,new gv),this.eventHandlers.get(u).add(d)}notifyListeners(u,...d){const f=this.eventHandlers.get(u);f&&f.notify(...d)}hasListeners(u){return this.eventHandlers.has(u)}mount(u){if(this.instance)return;this.isSVG=kv(u)&&!zZ(u),this.instance=u;const{layoutId:d,layout:f,visualElement:h}=this.options;if(h&&!h.current&&h.mount(u),this.root.nodes.add(this),this.parent&&this.parent.children.add(this),this.root.hasTreeAnimated&&(f||d)&&(this.isLayoutDirty=!0),t){let g,p=0;const v=()=>this.root.updateBlockedByResize=!1;nt.read(()=>{p=window.innerWidth}),t(u,()=>{const b=window.innerWidth;b!==p&&(p=b,this.root.updateBlockedByResize=!0,g&&g(),g=BJ(v,250),vd.hasAnimatedSinceResize&&(vd.hasAnimatedSinceResize=!1,this.nodes.forEach(hE)))})}d&&this.root.registerSharedNode(d,this),this.options.animate!==!1&&h&&(d||f)&&this.addEventListener("didUpdate",({delta:g,hasLayoutChanged:p,hasRelativeLayoutChanged:v,layout:b})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const S=this.options.transition||h.getDefaultTransition()||JJ,{onLayoutAnimationStart:w,onLayoutAnimationComplete:T}=h.getProps(),E=!this.targetLayout||!u6(this.targetLayout,b),C=!p&&v;if(this.options.layoutRoot||this.resumeFrom||C||p&&(E||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const O={...Ev(S,"layout"),onPlay:w,onComplete:T};(h.shouldReduceMotion||this.options.layoutRoot)&&(O.delay=0,O.type=!1),this.startAnimation(O),this.setAnimationOrigin(g,C)}else p||hE(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=b})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const u=this.getStack();u&&u.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),Ui(this.updateProjection)}blockUpdate(){this.updateManuallyBlocked=!0}unblockUpdate(){this.updateManuallyBlocked=!1}isUpdateBlocked(){return this.updateManuallyBlocked||this.updateBlockedByResize}isTreeAnimationBlocked(){return this.isAnimationBlocked||this.parent&&this.parent.isTreeAnimationBlocked()||!1}startUpdate(){this.isUpdateBlocked()||(this.isUpdating=!0,this.nodes&&this.nodes.forEach(YJ),this.animationId++)}getTransformTemplate(){const{visualElement:u}=this.options;return u&&u.getProps().transformTemplate}willUpdate(u=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked()){this.options.onExitComplete&&this.options.onExitComplete();return}if(window.MotionCancelOptimisedAnimation&&!this.hasCheckedOptimisedAppear&&f6(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let g=0;g<this.path.length;g++){const p=this.path[g];p.shouldResetTransform=!0,(typeof p.latestValues.x=="string"||typeof p.latestValues.y=="string")&&(p.isLayoutDirty=!0),p.updateScroll("snapshot"),p.options.layoutRoot&&p.willUpdate(!1)}const{layoutId:d,layout:f}=this.options;if(d===void 0&&!f)return;const h=this.getTransformTemplate();this.prevTransformTemplateValue=h?h(this.latestValues,""):void 0,this.updateSnapshot(),u&&this.notifyListeners("willUpdate")}update(){if(this.updateScheduled=!1,this.isUpdateBlocked()){const f=this.updateBlockedByResize;this.unblockUpdate(),this.updateBlockedByResize=!1,this.clearAllSnapshots(),f&&this.nodes.forEach($J),this.nodes.forEach(dE);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(fE);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(qJ),this.nodes.forEach(GJ),this.nodes.forEach(jJ),this.nodes.forEach(zJ)):this.nodes.forEach(fE),this.clearAllSnapshots();const d=tn.now();jt.delta=xa(0,1e3/60,d-jt.timestamp),jt.timestamp=d,jt.isProcessing=!0,Pm.update.process(jt),Pm.preRender.process(jt),Pm.render.process(jt),jt.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,Mv.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(VJ),this.sharedNodes.forEach(XJ)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,nt.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){nt.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!nn(this.snapshot.measuredBox.x)&&!nn(this.snapshot.measuredBox.y)&&(this.snapshot=void 0))}updateLayout(){if(!this.instance||(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead())&&!this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let f=0;f<this.path.length;f++)this.path[f].updateScroll();const u=this.layout;this.layout=this.measure(!1),this.layoutVersion++,this.layoutCorrected||(this.layoutCorrected=Ct()),this.isLayoutDirty=!1,this.projectionDelta=void 0,this.notifyListeners("measure",this.layout.layoutBox);const{visualElement:d}=this.options;d&&d.notify("LayoutMeasure",this.layout.layoutBox,u?u.layoutBox:void 0)}updateScroll(u="measure"){let d=!!(this.options.layoutScroll&&this.instance);if(this.scroll&&this.scroll.animationId===this.root.animationId&&this.scroll.phase===u&&(d=!1),d&&this.instance){const f=i(this.instance);this.scroll={animationId:this.root.animationId,phase:u,isRoot:f,offset:n(this.instance),wasRoot:this.scroll?this.scroll.isRoot:f}}}resetTransform(){if(!r)return;const u=this.isLayoutDirty||this.shouldResetTransform||this.options.alwaysMeasureLayout,d=this.projectionDelta&&!l6(this.projectionDelta),f=this.getTransformTemplate(),h=f?f(this.latestValues,""):void 0,g=h!==this.prevTransformTemplateValue;u&&this.instance&&(d||ps(this.latestValues)||g)&&(r(this.instance,h),this.shouldResetTransform=!1,this.scheduleRender())}measure(u=!0){const d=this.measurePageBox();let f=this.removeElementScroll(d);return u&&(f=this.removeTransform(f)),QJ(f),{animationId:this.root.animationId,measuredBox:d,layoutBox:f,latestValues:{},source:this.id}}measurePageBox(){const{visualElement:u}=this.options;if(!u)return Ct();const d=u.measureViewportBox();if(!(this.scroll?.wasRoot||this.path.some(eQ))){const{scroll:h}=this.root;h&&(va(d.x,h.offset.x),va(d.y,h.offset.y))}return d}removeElementScroll(u){const d=Ct();if(Zn(d,u),this.scroll?.wasRoot)return d;for(let f=0;f<this.path.length;f++){const h=this.path[f],{scroll:g,options:p}=h;h!==this.root&&g&&p.layoutScroll&&(g.wasRoot&&Zn(d,u),va(d.x,g.offset.x),va(d.y,g.offset.y))}return d}applyTransform(u,d=!1,f){const h=f||Ct();Zn(h,u);for(let g=0;g<this.path.length;g++){const p=this.path[g];!d&&p.options.layoutScroll&&p.scroll&&p!==p.root&&(va(h.x,-p.scroll.offset.x),va(h.y,-p.scroll.offset.y)),ps(p.latestValues)&&pd(h,p.latestValues,p.layout?.layoutBox)}return ps(this.latestValues)&&pd(h,this.latestValues,this.layout?.layoutBox),h}removeTransform(u){const d=Ct();Zn(d,u);for(let f=0;f<this.path.length;f++){const h=this.path[f];if(!ps(h.latestValues))continue;let g;h.instance&&(ly(h.latestValues)&&h.updateSnapshot(),g=Ct(),Zn(g,h.measurePageBox())),nE(d,h.latestValues,h.snapshot?.layoutBox,g)}return ps(this.latestValues)&&nE(d,this.latestValues),d}setTargetDelta(u){this.targetDelta=u,this.root.scheduleUpdateProjection(),this.isProjectionDirty=!0}setOptions(u){this.options={...this.options,...u,crossfade:u.crossfade!==void 0?u.crossfade:!0}}clearMeasurements(){this.scroll=void 0,this.layout=void 0,this.snapshot=void 0,this.prevTransformTemplateValue=void 0,this.targetDelta=void 0,this.target=void 0,this.isLayoutDirty=!1}forceRelativeParentToResolveTarget(){this.relativeParent&&this.relativeParent.resolvedRelativeTargetAt!==jt.timestamp&&this.relativeParent.resolveTargetDelta(!0)}resolveTargetDelta(u=!1){const d=this.getLead();this.isProjectionDirty||(this.isProjectionDirty=d.isProjectionDirty),this.isTransformDirty||(this.isTransformDirty=d.isTransformDirty),this.isSharedProjectionDirty||(this.isSharedProjectionDirty=d.isSharedProjectionDirty);const f=!!this.resumingFrom||this!==d;if(!(u||f&&this.isSharedProjectionDirty||this.isProjectionDirty||this.parent?.isProjectionDirty||this.attemptToResolveRelativeTarget||this.root.updateBlockedByResize))return;const{layout:g,layoutId:p}=this.options;if(!this.layout||!(g||p))return;this.resolvedRelativeTargetAt=jt.timestamp;const v=this.getClosestProjectingParent();v&&this.linkedParentVersion!==v.layoutVersion&&!v.options.layoutRoot&&this.removeRelativeTarget(),!this.targetDelta&&!this.relativeTarget&&(this.options.layoutAnchor!==!1&&v&&v.layout?this.createRelativeTarget(v,this.layout.layoutBox,v.layout.layoutBox):this.removeRelativeTarget()),!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=Ct(),this.targetWithTransforms=Ct()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),_J(this.target,this.relativeTarget,this.relativeParent.target,this.options.layoutAnchor||void 0)):this.targetDelta?(this.resumingFrom?this.applyTransform(this.layout.layoutBox,!1,this.target):Zn(this.target,this.layout.layoutBox),W3(this.target,this.targetDelta)):Zn(this.target,this.layout.layoutBox),this.attemptToResolveRelativeTarget&&(this.attemptToResolveRelativeTarget=!1,this.options.layoutAnchor!==!1&&v&&!!v.resumingFrom==!!this.resumingFrom&&!v.options.layoutScroll&&v.target&&this.animationProgress!==1?this.createRelativeTarget(v,this.target,v.target):this.relativeParent=this.relativeTarget=void 0))}getClosestProjectingParent(){if(!(!this.parent||ly(this.parent.latestValues)||X3(this.parent.latestValues)))return this.parent.isProjecting()?this.parent:this.parent.getClosestProjectingParent()}isProjecting(){return!!((this.relativeTarget||this.targetDelta||this.options.layoutRoot)&&this.layout)}createRelativeTarget(u,d,f){this.relativeParent=u,this.linkedParentVersion=u.layoutVersion,this.forceRelativeParentToResolveTarget(),this.relativeTarget=Ct(),this.relativeTargetOrigin=Ct(),Qd(this.relativeTargetOrigin,d,f,this.options.layoutAnchor||void 0),Zn(this.relativeTarget,this.relativeTargetOrigin)}removeRelativeTarget(){this.relativeParent=this.relativeTarget=void 0}calcProjection(){const u=this.getLead(),d=!!this.resumingFrom||this!==u;let f=!0;if((this.isProjectionDirty||this.parent?.isProjectionDirty)&&(f=!1),d&&(this.isSharedProjectionDirty||this.isTransformDirty)&&(f=!1),this.resolvedRelativeTargetAt===jt.timestamp&&(f=!1),f)return;const{layout:h,layoutId:g}=this.options;if(this.isTreeAnimating=!!(this.parent&&this.parent.isTreeAnimating||this.currentAnimation||this.pendingAnimation),this.isTreeAnimating||(this.targetDelta=this.relativeTarget=void 0),!this.layout||!(h||g))return;Zn(this.layoutCorrected,this.layout.layoutBox);const p=this.treeScale.x,v=this.treeScale.y;WZ(this.layoutCorrected,this.treeScale,this.path,d),u.layout&&!u.target&&(this.treeScale.x!==1||this.treeScale.y!==1)&&(u.target=u.layout.layoutBox,u.targetWithTransforms=Ct());const{target:b}=u;if(!b){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(WT(this.prevProjectionDelta.x,this.projectionDelta.x),WT(this.prevProjectionDelta.y,this.projectionDelta.y)),El(this.projectionDelta,this.layoutCorrected,b,this.latestValues),(this.treeScale.x!==p||this.treeScale.y!==v||!oE(this.projectionDelta.x,this.prevProjectionDelta.x)||!oE(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners("projectionUpdate",b))}hide(){this.isVisible=!1}show(){this.isVisible=!0}scheduleRender(u=!0){if(this.options.visualElement?.scheduleRender(),u){const d=this.getStack();d&&d.scheduleRender()}this.resumingFrom&&!this.resumingFrom.instance&&(this.resumingFrom=void 0)}createProjectionDeltas(){this.prevProjectionDelta=Nr(),this.projectionDelta=Nr(),this.projectionDeltaWithTransform=Nr()}setAnimationOrigin(u,d=!1){const f=this.snapshot,h=f?f.latestValues:{},g={...this.latestValues},p=Nr();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!d;const v=Ct(),b=f?f.source:void 0,S=this.layout?this.layout.source:void 0,w=b!==S,T=this.getStack(),E=!T||T.members.length<=1,C=!!(w&&!E&&this.options.crossfade===!0&&!this.path.some(ZJ));this.animationProgress=0;let O;this.mixTargetDelta=L=>{const M=L/1e3;gE(p.x,u.x,M),gE(p.y,u.y,M),this.setTargetDelta(p),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(Qd(v,this.layout.layoutBox,this.relativeParent.layout.layoutBox,this.options.layoutAnchor||void 0),WJ(this.relativeTarget,this.relativeTargetOrigin,v,M),O&&RJ(this.relativeTarget,O)&&(this.isProjectionDirty=!1),O||(O=Ct()),Zn(O,this.relativeTarget)),w&&(this.animationValues=g,xJ(g,h,this.latestValues,M,C,E)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=M},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(u){this.notifyListeners("animationStart"),this.currentAnimation?.stop(),this.resumingFrom?.currentAnimation?.stop(),this.pendingAnimation&&(Ui(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=nt.update(()=>{vd.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=Jr(0)),this.motionValue.jump(0,!1),this.currentAnimation=kJ(this.motionValue,[0,1e3],{...u,velocity:0,isSync:!0,onUpdate:d=>{this.mixTargetDelta(d),u.onUpdate&&u.onUpdate(d)},onStop:()=>{},onComplete:()=>{u.onComplete&&u.onComplete(),this.completeAnimation()}}),this.resumingFrom&&(this.resumingFrom.currentAnimation=this.currentAnimation),this.pendingAnimation=void 0})}completeAnimation(){this.resumingFrom&&(this.resumingFrom.currentAnimation=void 0,this.resumingFrom.preserveOpacity=void 0);const u=this.getStack();u&&u.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners("animationComplete")}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(IJ),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const u=this.getLead();let{targetWithTransforms:d,target:f,layout:h,latestValues:g}=u;if(!(!d||!f||!h)){if(this!==u&&this.layout&&h&&g6(this.options.animationType,this.layout.layoutBox,h.layoutBox)){f=this.target||Ct();const p=nn(this.layout.layoutBox.x);f.x.min=u.target.x.min,f.x.max=f.x.min+p;const v=nn(this.layout.layoutBox.y);f.y.min=u.target.y.min,f.y.max=f.y.min+v}Zn(d,f),pd(d,g),El(this.projectionDeltaWithTransform,this.layoutCorrected,d,g)}}registerSharedNode(u,d){this.sharedNodes.has(u)||this.sharedNodes.set(u,new NJ),this.sharedNodes.get(u).add(d);const h=d.options.initialPromotionConfig;d.promote({transition:h?h.transition:void 0,preserveFollowOpacity:h&&h.shouldPreserveFollowOpacity?h.shouldPreserveFollowOpacity(d):void 0})}isLead(){const u=this.getStack();return u?u.lead===this:!0}getLead(){const{layoutId:u}=this.options;return u?this.getStack()?.lead||this:this}getPrevLead(){const{layoutId:u}=this.options;return u?this.getStack()?.prevLead:void 0}getStack(){const{layoutId:u}=this.options;if(u)return this.root.sharedNodes.get(u)}promote({needsReset:u,transition:d,preserveFollowOpacity:f}={}){const h=this.getStack();h&&h.promote(this,f),u&&(this.projectionDelta=void 0,this.needsReset=!0),d&&this.setOptions({transition:d})}relegate(){const u=this.getStack();return u?u.relegate(this):!1}resetSkewAndRotation(){const{visualElement:u}=this.options;if(!u)return;let d=!1;const{latestValues:f}=u;if((f.z||f.rotate||f.rotateX||f.rotateY||f.rotateZ||f.skewX||f.skewY)&&(d=!0),!d)return;const h={};f.z&&Km("z",u,h,this.animationValues);for(let g=0;g<Gm.length;g++)Km(`rotate${Gm[g]}`,u,h,this.animationValues),Km(`skew${Gm[g]}`,u,h,this.animationValues);u.render();for(const g in h)u.setStaticValue(g,h[g]),this.animationValues&&(this.animationValues[g]=h[g]);u.scheduleRender()}applyProjectionStyles(u,d){if(!this.instance||this.isSVG)return;if(!this.isVisible){u.visibility="hidden";return}const f=this.getTransformTemplate();if(this.needsReset){this.needsReset=!1,u.visibility="",u.opacity="",u.pointerEvents=yd(d?.pointerEvents)||"",u.transform=f?f(this.latestValues,""):"none";return}const h=this.getLead();if(!this.projectionDelta||!this.layout||!h.target){this.options.layoutId&&(u.opacity=this.latestValues.opacity!==void 0?this.latestValues.opacity:1,u.pointerEvents=yd(d?.pointerEvents)||""),this.hasProjected&&!ps(this.latestValues)&&(u.transform=f?f({},""):"none",this.hasProjected=!1);return}u.visibility="";const g=h.animationValues||h.latestValues;this.applyTransformsToTarget();let p=AJ(this.projectionDeltaWithTransform,this.treeScale,g);f&&(p=f(g,p)),u.transform=p;const{x:v,y:b}=this.projectionDelta;u.transformOrigin=`${v.origin*100}% ${b.origin*100}% 0`,h.animationValues?u.opacity=h===this?g.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:g.opacityExit:u.opacity=h===this?g.opacity!==void 0?g.opacity:"":g.opacityExit!==void 0?g.opacityExit:0;for(const S in cy){if(g[S]===void 0)continue;const{correct:w,applyTo:T,isCSSVariable:E}=cy[S],C=p==="none"?g[S]:w(g[S],h);if(T){const O=T.length;for(let L=0;L<O;L++)u[T[L]]=C}else E?this.options.visualElement.renderState.vars[S]=C:u[S]=C}this.options.layoutId&&(u.pointerEvents=h===this?yd(d?.pointerEvents)||"":"none")}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(u=>u.currentAnimation?.stop()),this.root.nodes.forEach(dE),this.root.sharedNodes.clear()}}}function jJ(t){t.updateLayout()}function zJ(t){const e=t.resumeFrom?.snapshot||t.snapshot;if(t.isLead()&&t.layout&&e&&t.hasListeners("didUpdate")){const{layoutBox:n,measuredBox:i}=t.layout,{animationType:r}=t.options,l=e.source!==t.layout.source;if(r==="size")ha(g=>{const p=l?e.measuredBox[g]:e.layoutBox[g],v=nn(p);p.min=n[g].min,p.max=p.min+v});else if(r==="x"||r==="y"){const g=r==="x"?"y":"x";dy(l?e.measuredBox[g]:e.layoutBox[g],n[g])}else g6(r,e.layoutBox,n)&&ha(g=>{const p=l?e.measuredBox[g]:e.layoutBox[g],v=nn(n[g]);p.max=p.min+v,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[g].max=t.relativeTarget[g].min+v)});const u=Nr();El(u,n,e.layoutBox);const d=Nr();l?El(d,t.applyTransform(i,!0),e.measuredBox):El(d,n,e.layoutBox);const f=!l6(u);let h=!1;if(!t.resumeFrom){const g=t.getClosestProjectingParent();if(g&&!g.resumeFrom){const{snapshot:p,layout:v}=g;if(p&&v){const b=t.options.layoutAnchor||void 0,S=Ct();Qd(S,e.layoutBox,p.layoutBox,b);const w=Ct();Qd(w,n,v.layoutBox,b),u6(S,w)||(h=!0),g.options.layoutRoot&&(t.relativeTarget=w,t.relativeTargetOrigin=S,t.relativeParent=g)}}}t.notifyListeners("didUpdate",{layout:n,snapshot:e,delta:d,layoutDelta:u,hasLayoutChanged:f,hasRelativeLayoutChanged:h})}else if(t.isLead()){const{onExitComplete:n}=t.options;n&&n()}t.options.transition=void 0}function FJ(t){t.parent&&(t.isProjecting()||(t.isProjectionDirty=t.parent.isProjectionDirty),t.isSharedProjectionDirty||(t.isSharedProjectionDirty=!!(t.isProjectionDirty||t.parent.isProjectionDirty||t.parent.isSharedProjectionDirty)),t.isTransformDirty||(t.isTransformDirty=t.parent.isTransformDirty))}function UJ(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function VJ(t){t.clearSnapshot()}function dE(t){t.clearMeasurements()}function $J(t){t.isLayoutDirty=!0,t.updateLayout()}function fE(t){t.isLayoutDirty=!1}function qJ(t){t.isAnimationBlocked&&t.layout&&!t.isLayoutDirty&&(t.snapshot=t.layout,t.isLayoutDirty=!0)}function GJ(t){const{visualElement:e}=t.options;e&&e.getProps().onBeforeLayoutMeasure&&e.notify("BeforeLayoutMeasure"),t.resetTransform()}function hE(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function KJ(t){t.resolveTargetDelta()}function HJ(t){t.calcProjection()}function YJ(t){t.resetSkewAndRotation()}function XJ(t){t.removeLeadSnapshot()}function gE(t,e,n){t.translate=st(e.translate,0,n),t.scale=st(e.scale,1,n),t.origin=e.origin,t.originPoint=e.originPoint}function mE(t,e,n,i){t.min=st(e.min,n.min,i),t.max=st(e.max,n.max,i)}function WJ(t,e,n,i){mE(t.x,e.x,n.x,i),mE(t.y,e.y,n.y,i)}function ZJ(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const JJ={duration:.45,ease:[.4,0,.1,1]},pE=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),yE=pE("applewebkit/")&&!pE("chrome/")?Math.round:qn;function vE(t){t.min=yE(t.min),t.max=yE(t.max)}function QJ(t){vE(t.x),vE(t.y)}function g6(t,e,n){return t==="position"||t==="preserve-aspect"&&!SJ(rE(e),rE(n),.2)}function eQ(t){return t!==t.root&&t.scroll?.wasRoot}const tQ=h6({attachResizeListener:(t,e)=>Fl(t,"resize",e),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body?.scrollLeft||0,y:document.documentElement.scrollTop||document.body?.scrollTop||0}),checkIsScrollRoot:()=>!0}),Hm={current:void 0},m6=h6({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!Hm.current){const t=new tQ({});t.mount(window),t.setOptions({layoutScroll:!0}),Hm.current=t}return Hm.current},resetTransform:(t,e)=>{t.style.transform=e!==void 0?e:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),Iv=A.createContext({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});function bE(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function nQ(...t){return e=>{let n=!1;const i=t.map(r=>{const l=bE(r,e);return!n&&typeof l=="function"&&(n=!0),l});if(n)return()=>{for(let r=0;r<i.length;r++){const l=i[r];typeof l=="function"?l():bE(t[r],null)}}}}function aQ(...t){return A.useCallback(nQ(...t),t)}class iQ extends A.Component{getSnapshotBeforeUpdate(e){const n=this.props.childRef.current;if(dd(n)&&e.isPresent&&!this.props.isPresent&&this.props.pop!==!1){const i=n.offsetParent,r=dd(i)&&i.offsetWidth||0,l=dd(i)&&i.offsetHeight||0,u=getComputedStyle(n),d=this.props.sizeRef.current;d.height=parseFloat(u.height),d.width=parseFloat(u.width),d.top=n.offsetTop,d.left=n.offsetLeft,d.right=r-d.width-d.left,d.bottom=l-d.height-d.top}return null}componentDidUpdate(){}render(){return this.props.children}}function sQ({children:t,isPresent:e,anchorX:n,anchorY:i,root:r,pop:l}){const u=A.useId(),d=A.useRef(null),f=A.useRef({width:0,height:0,top:0,left:0,right:0,bottom:0}),{nonce:h}=A.useContext(Iv),g=t.props?.ref??t?.ref,p=aQ(d,g);return A.useInsertionEffect(()=>{const{width:v,height:b,top:S,left:w,right:T,bottom:E}=f.current;if(e||l===!1||!d.current||!v||!b)return;const C=n==="left"?`left: ${w}`:`right: ${T}`,O=i==="bottom"?`bottom: ${E}`:`top: ${S}`;d.current.dataset.motionPopId=u;const L=document.createElement("style");h&&(L.nonce=h);const M=r??document.head;return M.appendChild(L),L.sheet&&L.sheet.insertRule(`
|
|
81
81
|
[data-motion-pop-id="${u}"] {
|
package/dist/index.html
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
<meta charset="UTF-8" />
|
|
6
6
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
7
7
|
<title>DatoCMS Plugin</title>
|
|
8
|
-
<script type="module" crossorigin src="./assets/index-
|
|
8
|
+
<script type="module" crossorigin src="./assets/index-BrvLeyFo.js"></script>
|
|
9
9
|
<link rel="stylesheet" crossorigin href="./assets/index-O55BoPJj.css">
|
|
10
10
|
</head>
|
|
11
11
|
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "datocms-plugin-ai-translations",
|
|
3
3
|
"homepage": "https://github.com/datocms/plugins/tree/master/ai-translations#readme",
|
|
4
|
-
"version": "3.5.
|
|
4
|
+
"version": "3.5.5",
|
|
5
5
|
"author": "DatoCMS <support@datocms.com>",
|
|
6
6
|
"description": "Translate fields and records directly on DatoCMS using AI",
|
|
7
7
|
"keywords": [
|