@univerjs-pro/bases 1.6.1 → 1.7.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
1
  import{BASE_RECORD_ID_FIELD_ID as e,BaseConditionalColorOperator as t,BaseConditionalDateMode as n,BaseFieldType as r,BaseFilterConjunction as i,BaseHierarchyInvalidReason as a,BaseRecordLinkRole as o,BaseSortDirection as s,BaseViewType as c,CellValueType as l,CommandType as u,DateSystem as d,Disposable as f,IUniverInstanceService as p,Inject as m,JSON1 as h,Tools as g,UniverInstanceType as _,createIdentifier as v,dateKit as y,excelDateTimeSerial as ee,excelSerialToDateTime as te,isValidBaseRecordId as ne,toDisposable as b}from"@univerjs/core";function x(e){let t=e.config.targetTableId,n=e.config.multiple,r=e.config.displayFieldId,i=e.config.pickerFieldIds,a=e.config.relationRole;return typeof t!=`string`||!t||typeof n!=`boolean`||r!==void 0&&(typeof r!=`string`||!r)||a!==void 0&&a!==o.Parent||i!==void 0&&(!Array.isArray(i)||i.some(e=>typeof e!=`string`||!e)||new Set(i).size!==i.length)?null:{targetTableId:t,multiple:n,...r?{displayFieldId:r}:{},...i?{pickerFieldIds:[...i]}:{},...a?{relationRole:a}:{}}}function S(e){return typeof e!=`string`||e===``?[]:e.split(`,`)}function re(e){return Array.from(new Set(e)).join(`,`)}function ie(e,t){if(typeof e!=`string`)return{valid:!1,reason:`[RecordLink]: value must be a canonical string.`};if(e===``)return{valid:!0};let n=e.split(`,`);return!t&&n.length>1?{valid:!1,reason:`[RecordLink]: a single link accepts only one record id.`}:n.some(e=>!ne(e))||new Set(n).size!==n.length||re(n)!==e?{valid:!1,reason:`[RecordLink]: value is not a canonical record id list.`}:{valid:!0}}function ae(e,t){if(t.type!==r.RecordLink)return{valid:!0};let n=x(t),i=n?e.tables[n.targetTableId]:void 0;if(!n||!i)return{valid:!1,reason:`[RecordLink]: target table does not exist in this Base.`};let a=[...n.displayFieldId?[n.displayFieldId]:[],...n.pickerFieldIds??[]].find(e=>{let t=i.fields[e];return!t||t.system===!0||t.type===r.RecordId});return a?{valid:!1,reason:`[RecordLink]: display field "${a}" must be a non-system field in the target table.`}:{valid:!0}}function oe(e,t,n,i={}){let a=x(t);if(t.type!==r.RecordLink||!a)return{valid:!1,reason:`[RecordLink]: field config is invalid.`};let o=ie(n,a.multiple);if(!o.valid||i.allowDangling)return o;let s=e.tables[a.targetTableId];if(!s)return{valid:!1,reason:`[RecordLink]: target table does not exist in this Base.`};let c=S(n).find(e=>!s.records[e]);return c?{valid:!1,reason:`[RecordLink]: target record "${c}" does not exist.`}:{valid:!0}}function se(e,t){return Object.values(e.tables).flatMap(e=>Object.values(e.fields).flatMap(n=>{let i=n.type===r.RecordLink?x(n):null;return(i==null?void 0:i.targetTableId)===t?[{tableId:e.id,fieldId:n.id}]:[]}))}function ce(e,t,n){let r=[e],i=/* @__PURE__ */ new Set;for(;r.length;){let e=r.pop();if(e===t)return!0;if(!i.has(e)){i.add(e);for(let t of S(n(e)))r.push(t)}}return!1}function le(e,t){return(t==null?void 0:t.type)===r.RecordLink&&!t.system&&!t.readonly&&t.config.targetTableId===e&&t.config.multiple===!0&&t.config.relationRole===void 0}const ue=5,de=`__base_hierarchy_parent__`;let fe=/* @__PURE__ */ function(e){return e.InvalidField=`invalidField`,e.MissingRecord=`missingRecord`,e.SelfParent=`selfParent`,e.Cycle=`cycle`,e.MaxDepth=`maxDepth`,e.SortedView=`sortedView`,e}({});var pe=class extends Error{constructor(e,t=`[BaseHierarchy]: ${e}`){super(t),this.code=e,this.name=`BaseHierarchyError`}};let me=/* @__PURE__ */ function(e){return e.UI=`ui`,e.Facade=`facade`,e.Remote=`remote`,e.Undo=`undo`,e.Redo=`redo`,e.Import=`import`,e}({});function C(e,t){if(!t)return!1;let n=e.fields[t];if(!n||n.type!==r.RecordLink)return!1;let i=x(n);return i?i.targetTableId===e.id&&i.multiple===!1:!1}function w(e){return[...e.fieldOrder,...Object.keys(e.fields).filter(t=>!e.fieldOrder.includes(t)).sort()].find(t=>{var n;return C(e,t)?((n=x(e.fields[t]))==null?void 0:n.relationRole)===o.Parent:!1})??null}function T(e){let t=w(e);if(t)return t;let n=de,r=2;for(;e.fields[n];)n=`${de}_${r++}`;return n}function he(e,t=T(e),n=`Parent Items`){return{id:t,name:n,type:r.RecordLink,config:{targetTableId:e.id,multiple:!1,displayFieldId:e.primaryFieldId,pickerFieldIds:[e.primaryFieldId],relationRole:o.Parent}}}function E(e){let t=w(e);return t?[t]:[]}function ge(e,t){let n=[...E(e)].filter(e=>t.some(t=>Object.prototype.hasOwnProperty.call(t.values,e)));if(!n.length)return[];let r={...e.records};t.forEach(e=>{let t=r[e.recordId];t&&(r[e.recordId]={...t,values:{...t.values,...e.values}})});let i={...e,records:r},a=[];return n.forEach(n=>{let r=D(e,n),o=D(i,n);for(let[e,i]of o.invalidReasonByRecordId){let a=t.some(t=>t.recordId===e&&Object.prototype.hasOwnProperty.call(t.values,n));if(r.invalidReasonByRecordId.get(e)!==i||a)throw new pe(ve(i))}t.forEach(t=>{if(!Object.prototype.hasOwnProperty.call(t.values,n))return;let i=r.parentByRecordId.get(t.recordId)??null,s=o.parentByRecordId.get(t.recordId)??null;i!==s&&a.push({tableId:e.id,fieldId:n,recordId:t.recordId,oldParentRecordId:i,parentRecordId:s})})}),a}function _e(e,t){let n=t.map(e=>e.id);if(new Set(n).size!==n.length||n.some(t=>e.records[t]))return[];let r=E(e),i=r.length?null:T(e),a=[...r,...i&&t.some(e=>Object.prototype.hasOwnProperty.call(e.values,i))?[i]:[]].filter(e=>t.some(t=>Object.prototype.hasOwnProperty.call(t.values,e)));if(!a.length)return[];let o={...e,records:{...e.records,...Object.fromEntries(t.map(e=>[e.id,e]))},recordOrder:[...e.recordOrder??[],...t.map(e=>e.id)]},s=[];return a.forEach(n=>{let r=D(o,n);t.forEach(t=>{let i=r.invalidReasonByRecordId.get(t.id);if(i)throw new pe(ve(i));let a=r.parentByRecordId.get(t.id)??null;a&&s.push({tableId:e.id,fieldId:n,recordId:t.id,oldParentRecordId:null,parentRecordId:a})})}),s}function ve(e){switch(e){case a.MissingParent:return`missingRecord`;case a.SelfParent:return`selfParent`;case a.Cycle:return`cycle`;case a.MaxDepth:return`maxDepth`}}function ye(e,t){let n=new Set(t),r=E(e);return Object.values(e.records).flatMap(t=>n.has(t.id)?[]:Array.from(r).flatMap(r=>{let i=S(t.values[r])[0]??null;return i&&n.has(i)?[{tableId:e.id,fieldId:r,recordId:t.id,oldParentRecordId:i,parentRecordId:null}]:[]}))}function D(e,t,n=e.recordOrder??Object.keys(e.records)){if((e.fields[t]||t!==T(e))&&!C(e,t))throw Error(`[BaseHierarchy]: field "${t}" must be a same-table, single-value RecordLink.`);let r=Ce(e,n),i=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Map;for(let n of r){var s;let r=S((s=e.records[n])==null?void 0:s.values[t])[0]??null;r?r===n?(i.set(n,null),o.set(n,a.SelfParent)):e.records[r]?i.set(n,r):(i.set(n,null),o.set(n,a.MissingParent)):i.set(n,null)}we(i,o,r),Te(i,o,r);let c=new Map(r.map((e,t)=>[e,t])),l=/* @__PURE__ */ new Map;for(let e of r){let t=i.get(e)??null,n=l.get(t)??[];n.push(e),l.set(t,n)}l.forEach(e=>e.sort((e,t)=>(c.get(e)??0)-(c.get(t)??0)));let u=l.get(null)??[],d=/* @__PURE__ */ new Map,f=/* @__PURE__ */ new Map,p=[],m=(e,t)=>{d.set(e,t),p.push(e);let n=0;for(let r of l.get(e)??[])n=Math.max(n,1+m(r,t+1));return f.set(e,n),n};return u.forEach(e=>m(e,0)),{fieldId:t,parentByRecordId:i,childrenByParentId:l,depthByRecordId:d,subtreeHeightByRecordId:f,invalidReasonByRecordId:o,rootRecordIds:u,orderedRecordIds:p}}function be(e,t,n=new Set(t.map(e=>e.recordId))){let r=new Set(n);for(let t of n){let n=e.parentByRecordId.get(t)??null;for(;n;)r.add(n),n=e.parentByRecordId.get(n)??null}let i=new Map(t.map(e=>[e.recordId,e])),a=e.orderedRecordIds.filter(e=>r.has(e)),o=a.flatMap(e=>{let t=i.get(e);return t?[t]:[]}),s={};for(let t=0;t<a.length;t++){let n=a[t];s[n]={recordId:n,parentRecordId:e.parentByRecordId.get(n)??null,depth:e.depthByRecordId.get(n)??0,directChildCount:(e.childrenByParentId.get(n)??[]).length,subtreeHeight:e.subtreeHeightByRecordId.get(n)??0,subtreeEndIndex:t,invalidReason:e.invalidReasonByRecordId.get(n)}}let c=[];for(let e=0;e<a.length;e++){let t=a[e],n=s[t].depth;for(;c.length&&c[c.length-1].depth>=n;){let t=c.pop();s[t.recordId].subtreeEndIndex=e-1}c.push({recordId:t,depth:n})}return c.forEach(({recordId:e})=>{s[e].subtreeEndIndex=a.length-1}),{rows:o,hierarchy:{fieldId:e.fieldId,rootRecordIds:e.rootRecordIds.filter(e=>r.has(e)),orderedRecordIds:a,nodes:s}}}function xe(e,t){if(!e.hierarchy||!(t!=null&&t.size))return e.rows;let n=[],r=0;for(;r<e.rows.length;){let i=e.rows[r];n.push(i);let a=e.hierarchy.nodes[i.recordId];r=t.has(i.recordId)&&a?a.subtreeEndIndex+1:r+1}return n}function Se(e,t,n){if(!n)return{valid:!0};if(t===n)return{valid:!1,reason:a.SelfParent};let r=n;for(;r;){if(r===t)return{valid:!1,reason:a.Cycle};r=e.parentByRecordId.get(r)??null}return(e.depthByRecordId.get(n)??0)+1+(e.subtreeHeightByRecordId.get(t)??0)>=5?{valid:!1,reason:a.MaxDepth}:{valid:!0}}function Ce(e,t){let n=/* @__PURE__ */ new Set,r=[];for(let i of t)e.records[i]&&!n.has(i)&&(n.add(i),r.push(i));return Object.keys(e.records).sort().forEach(e=>{n.has(e)||r.push(e)}),r}function we(e,t,n){let r=/* @__PURE__ */ new Set;for(let i of n){if(r.has(i))continue;let n=[],o=/* @__PURE__ */ new Map,s=i;for(;s&&!r.has(s);){let r=o.get(s);if(r!=null){let i=[...n.slice(r)].sort().pop();e.set(i,null),t.set(i,a.Cycle);break}o.set(s,n.length),n.push(s),s=e.get(s)??null}n.forEach(e=>r.add(e))}}function Te(e,t,n){let r=/* @__PURE__ */ new Map,i=n=>{let o=r.get(n);if(o!=null)return o;let s=e.get(n)??null;if(!s)return r.set(n,0),0;let c=i(s)+1;return c>=5?(e.set(n,null),t.set(n,a.MaxDepth),r.set(n,0),0):(r.set(n,c),c)};n.forEach(i)}let Ee=0;function De(){if(globalThis.__UNIVER_BASE_PERF__===!0)return!0;try{let e=typeof location>`u`?``:location.search,t=new URLSearchParams(e);if(t.get(`basePerf`)===`1`||t.get(`basePerf`)===`true`||t.get(`base-perf`)===`1`)return!0}catch{}try{let e=typeof localStorage>`u`?null:localStorage.getItem(`univer.basePerf`);return e===`1`||e===`true`}catch{return!1}}function O(e,t,n){if(!De())return t();let r=ke(),i=`base-perf-${Ee++}`;Ae(`${i}:start`);try{return t()}finally{let t=ke()-r;Ae(`${i}:end`),je(e,`${i}:start`,`${i}:end`),Oe(e,t,n)}}function Oe(e,t,n){if(!De())return;let r=Math.round(t*100)/100,i=n&&Object.keys(n).length?` ${JSON.stringify(n)}`:``;console.info(`[BasePerf] ${e}: ${r}ms${i}`)}function ke(){return typeof performance<`u`&&typeof performance.now==`function`?performance.now():Date.now()}function Ae(e){try{if(typeof performance<`u`){var t,n;(t=(n=performance).mark)==null||t.call(n,e)}}catch{}}function je(e,t,n){try{if(typeof performance<`u`){var r,i;(r=(i=performance).measure)==null||r.call(i,`[BasePerf] ${e}`,t,n)}}catch{}}function k(e){var t;return De()?O(`IBaseCellData.ensureTableCellLayout`,()=>Me(e),{tableId:e.id,records:Object.keys(e.records??{}).length,fields:e.fieldOrder.length,hasRecordOrder:!!((t=e.recordOrder)!=null&&t.length)}):Me(e)}function Me(t){var n;let i=t.records??{},a=t.fields??{},o=((n=t.recordOrder)==null?void 0:n.filter(e=>i[e]))??[],s=new Set(o),c=[];for(let e of Object.values(i))s.has(e.id)||c.push(e);let u=c.length?[...o,...Je(c)]:o,d=t.fieldOrder.filter(e=>a[e]),f={...t.rowId??{}},p={...t.colId??{}},m={...t.cellData??{}};t.recordOrder=u,t.rowIndex={},t.rowId={},t.colIndex={},t.colId={},t.cellData={},t.resources={...t.resources??{}},t.resources.attachmentSets={...t.resources.attachmentSets??{}},t.resources.attachments={...t.resources.attachments??{}};let h=t.rowIndex,g=t.rowId,_=t.colIndex,v=t.colId,y=t.cellData;return u.forEach((e,t)=>{h[e]=t,g[t]=e}),d.forEach((e,t)=>{_[e]=t,v[t]=e}),Object.entries(m).forEach(([e,t])=>{let n=Number(e),r=f[n]??u[n],i=r?h[r]:void 0;i!=null&&(y[i]={...y[i]??{}},Object.entries(t??{}).forEach(([e,t])=>{let n=Number(e),r=p[n]??d[n],a=r?_[r]:void 0;a!=null&&(y[i][a]=ze(t))}))}),Object.values(i).forEach(n=>{let i=h[n.id];i!=null&&(n.values={...n.values??{},[e]:n.id},y[i]={...y[i]??{},0:{v:n.id,t:l.STRING}},Object.entries(n.values??{}).forEach(([e,o])=>{let s=a[e];(s==null?void 0:s.type)===r.Attachment&&He(t,n.id,e,o);let c=_[e];if(c==null)return;let l=y[i][c];(l==null||Ge(l,s,o))&&(y[i][c]=Re(o,s))}))}),t}function Ne(t,n){return t.records=Object.fromEntries(Object.entries(t.records).map(([e,t])=>[e,{...t}])),k(t),Object.entries(t.rowId??{}).forEach(([r,i])=>{var a;let o=Number(r),s=t.records[i];s&&(s.values={...s.values??{}},Object.entries(((a=t.cellData)==null?void 0:a[o])??{}).forEach(([r,a])=>{var o;let c=(o=t.colId)==null?void 0:o[Number(r)];c&&n&&!n(i,c)||(c===e?s.values[e]=s.id:c&&(s.values[c]=j(a,t.fields[c],t,i)))}))}),t}function Pe(t,n){for(let{row:o,col:s}of n){var r,i,a;let n=(r=t.rowId)==null?void 0:r[o],c=(i=t.colId)==null?void 0:i[s],l=n?t.records[n]:void 0;if(!l||!c)continue;if(c===e){l.values[e]=l.id;continue}let u=(a=t.cellData)==null||(a=a[o])==null?void 0:a[s];(u!=null||Object.prototype.hasOwnProperty.call(l.values??{},c))&&(l.values={...l.values??{}},l.values[c]=j(u,t.fields[c],t,n))}return t}function Fe(e,t,n){var r,i,a,o,s,c;let l=(r=e.rowIndex)==null?void 0:r[t],u=(i=e.colIndex)==null?void 0:i[n];if(l!=null&&u!=null&&((a=e.rowId)==null?void 0:a[l])===t&&((o=e.colId)==null?void 0:o[u])===n)return{row:l,col:u};let d=k(e),f=(s=d.rowIndex)==null?void 0:s[t],p=(c=d.colIndex)==null?void 0:c[n];return f==null||p==null?null:{row:f,col:p}}function Ie(e,t,n){var r;let i=Fe(e,t,n);if(i)return(r=e.cellData)==null||(r=r[i.row])==null?void 0:r[i.col]}function A(e,t,n){var i;let a=Ie(e,t,n),o=e.fields[n];if((o==null?void 0:o.type)===r.Attachment){var s;return Ue(e,t,n)??N((s=e.records[t])==null||(s=s.values)==null?void 0:s[n])}if(P(o)||F(o)||(o==null?void 0:o.type)===r.Link){var c;let r=(c=e.records[t])==null||(c=c.values)==null?void 0:c[n];return r!=null&&r!==``?We(r,o):j(a,o,e,t)}return a&&Object.prototype.hasOwnProperty.call(a,`v`)?a.v??null:((i=e.records[t])==null||(i=i.values)==null?void 0:i[n])??null}function Le(e,t,n){var r;let i=Ie(e,t,n);if(i&&Object.prototype.hasOwnProperty.call(i,`v`))return i.v??null;let a=e.fields[n];return Re(((r=e.records[t])==null||(r=r.values)==null?void 0:r[n])??null,a).v??null}function Re(e,t){if(M(e))return(t==null?void 0:t.type)===r.Attachment?{...e,v:``,t:l.STRING}:ze(e);if((t==null?void 0:t.type)===r.Attachment)return{v:``,t:l.STRING};if(F(t)){let t=I(e);return{v:t,t:qe(t)}}if(P(t))return{v:L(e).join(`, `),t:l.STRING};if((t==null?void 0:t.type)===r.Link&&e&&typeof e==`object`&&!Array.isArray(e)){let t=e;return{v:String(t.text??t.url??``),t:l.STRING}}return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`?{v:e,t:qe(e)}:{v:null,t:null}}function ze(e){let t=Ye(e.t,e.v);if(t===void 0){let{t,...n}=e;return n}return{...e,t}}function j(e,t,n,i){if(!e)return null;if((t==null?void 0:t.type)===r.Attachment)return n&&i?Ue(n,i,t.id)??[]:[];if(P(t))return L(e.v);if((t==null?void 0:t.type)===r.Link&&n&&i){var a;let e=(a=n.records[i])==null||(a=a.values)==null?void 0:a[t.id];if(e&&typeof e==`object`&&!Array.isArray(e))return e}return Object.prototype.hasOwnProperty.call(e,`v`)?e.v??null:null}function Be(e,t,n,i,a){return(n==null?void 0:n.type)===r.Attachment?N(e):F(n)?I(e):P(n)?L(e):(n==null?void 0:n.type)===r.Link&&(e==null||e===``)?null:(n==null?void 0:n.type)===r.Link&&e&&typeof e==`object`&&!Array.isArray(e)&&!M(e)?e:j(t,n,i,a)}function M(e){return!!e&&typeof e==`object`&&(Object.prototype.hasOwnProperty.call(e,`v`)||Object.prototype.hasOwnProperty.call(e,`t`)||Object.prototype.hasOwnProperty.call(e,`p`)||Object.prototype.hasOwnProperty.call(e,`f`)||Object.prototype.hasOwnProperty.call(e,`si`))}function Ve(e,t){return`${e}${t}`}function He(e,t,n,r){let i=N(r);e.resources={...e.resources??{}},e.resources.attachmentSets={...e.resources.attachmentSets??{}},e.resources.attachments={...e.resources.attachments??{}};let a=Ve(n,t),o=[];for(let t=0;t<i.length;t++){if(!(t in i))continue;let n=i[t],r=String(n.id??`${a}${t}`),s={...n,id:r};e.resources.attachments[r]=s,o.push(r)}e.resources.attachmentSets[a]=o}function Ue(e,t,n){var r;let i=Ve(n,t),a=(r=e.resources)==null||(r=r.attachmentSets)==null?void 0:r[i];if(!a)return null;let o=[];for(let t=0;t<a.length;t++){var s;if(!(t in a))continue;let n=(s=e.resources)==null||(s=s.attachments)==null?void 0:s[a[t]];n&&o.push({...n})}return o}function N(e){if(e==null||e===``||M(e)&&!(`id`in e)&&!(`name`in e))return[];let t=Array.isArray(e)?e:[e],n=[];for(let e=0;e<t.length;e++){if(!(e in t))continue;let r=t[e],i=r&&typeof r==`object`?{...r}:{id:`attachment-${e}`,name:String(r)};Object.keys(i).length>0&&n.push(i)}return n}function We(e,t){return(t==null?void 0:t.type)===r.Attachment?N(e):F(t)?I(e):P(t)?L(e):e}function Ge(e,t,n){return(t==null?void 0:t.type)===r.Attachment?e.v!==``:F(t)?e.v!==I(n):P(t)?Array.isArray(n)&&(e.v==null||e.v===``):!1}function P(e){return(e==null?void 0:e.type)===r.MultiSelect||(e==null?void 0:e.type)===r.Group||(e==null?void 0:e.type)===r.Person&&e.config.allowMultiple===!0}function F(e){return(e==null?void 0:e.type)===r.Person&&e.config.allowMultiple!==!0}function I(e){let t=M(e)?e.v:e,n=Array.isArray(t)?t[0]:t;return n==null||n===``?null:String(n)}function L(e){if(e==null||e===``)return[];let t=[];if(Array.isArray(e)){for(let n=0;n<e.length;n++){if(!(n in e))continue;let r=Ke(e[n]);r&&t.push(r)}return t}for(let n of String(e).split(`,`)){let e=n.trim();e&&t.push(e)}return t}function Ke(e){if(e==null)return``;if(typeof e==`string`||typeof e==`number`||typeof e==`boolean`)return String(e);if(typeof e==`object`){let t=e;return String(t.id??t.name??t.text??``)}return String(e)}function qe(e){return e==null?null:typeof e==`number`?l.NUMBER:typeof e==`boolean`?l.BOOLEAN:l.STRING}function Je(e){e.sort((e,t)=>e.orderKey.localeCompare(t.orderKey));let t=[];for(let n of e)t.push(n.id);return t}function Ye(e,t){return e===l.STRING||e===l.NUMBER||e===l.BOOLEAN||e===l.FORCE_STRING||e==null?e:qe(t??null)}function Xe(e){let t=null;for(let n of e)t=t===null?n:h.type.compose(t,n);return t}var Ze=class e{static tryMaterializeSnapshot(t,n){let r=[];for(let e of n){let n=Qe(e);if(!n||n.unitId!==t.id)return null;r.push(n.op)}try{let n=Xe(r);return n===null?t:new e().applyOp(t,n)}catch{return null}}applyOp(e,t){let n=this.getAffectedRanges(t),r=O(`BaseJson1.cloneForOp`,()=>ct(e,t),{invalidations:n.length}),i=O(`BaseJson1.json1Apply`,()=>h.type.apply(r,t),{invalidations:n.length}),a=et(i,n);return O(`BaseJson1.syncCellInvalidations`,()=>$e(i,n),{invalidations:n.length})?(tt(i,a),i):(O(`BaseJson1.normalizeTables`,()=>{this._getTablesToNormalize(i,n).forEach(t=>{let r=n.filter(e=>e.tableId===t.id),i=r.length>0&&r.every(e=>e.reason===`field`||e.reason===`view`||e.reason===`cell`||e.reason===`record`)?new Set(r.flatMap(n=>{var r;if(n.reason!==`field`||!n.fieldId)return[];let i=(r=e.tables[t.id])==null?void 0:r.fields[n.fieldId],a=t.fields[n.fieldId];return(i==null?void 0:i.type)!==(a==null?void 0:a.type)||(i==null?void 0:i.config.allowMultiple)!==(a==null?void 0:a.config.allowMultiple)?[n.fieldId]:[]})):void 0,a=new Set(r.flatMap(e=>{var n,r;return e.reason!==`cell`||e.row==null||e.column==null?[]:[JSON.stringify([(n=t.rowId)==null?void 0:n[e.row],(r=t.colId)==null?void 0:r[e.column]])]}));Ne(t,i?(e,t)=>i.has(t)||a.has(JSON.stringify([e,t])):void 0)})},{invalidations:n.length}),tt(i,a),i)}invertOp(e,t){return h.type.invertWithDoc(t,e)}getAffectedRanges(e){let t=at(e);return t.length?ot(t.flatMap(e=>this.getAffectedRanges(e))):nt(e)}_getTablesToNormalize(e,t){let n=t.filter(e=>e.reason!==`view`);return n.length?n.some(e=>!e.tableId)?Object.values(e.tables??{}):Array.from(new Set(n.map(e=>e.tableId))).flatMap(t=>{var n;let r=(n=e.tables)==null?void 0:n[t];return r?[r]:[]}):[]}};function Qe(e){let t=e.params;return e.id!==`base.mutation.apply-base-json1`||typeof t!=`object`||!t||!(`unitId`in t)||typeof t.unitId!=`string`||!(`op`in t)||t.op!==null&&!Array.isArray(t.op)?null:{unitId:t.unitId,op:t.op}}function $e(e,t){if(!t.length||t.some(e=>e.reason!==`cell`))return!1;let n=/* @__PURE__ */ new Map;for(let e of t){if(!e.tableId||e.row==null||e.column==null)continue;let t=n.get(e.tableId)??[];t.push({row:e.row,col:e.column}),n.set(e.tableId,t)}return n.forEach((t,n)=>{var r;let i=(r=e.tables)==null?void 0:r[n];i&&Pe(i,t)}),!0}function et(e,t){let n=/* @__PURE__ */ new Set;return t.flatMap(t=>{var r;if(!t.tableId||!t.recordId||!t.fieldId)return[];let i=`${t.tableId}\u001F${t.recordId}\u001F${t.fieldId}`;if(n.has(i))return[];n.add(i);let a=(r=e.tables[t.tableId])==null||(r=r.records[t.recordId])==null?void 0:r.values;return a?[{tableId:t.tableId,recordId:t.recordId,fieldId:t.fieldId,exists:Object.prototype.hasOwnProperty.call(a,t.fieldId),value:a[t.fieldId]}]:[]})}function tt(e,t){t.forEach(t=>{var n;let r=(n=e.tables[t.tableId])==null||(n=n.records[t.recordId])==null?void 0:n.values;r&&(t.exists?r[t.fieldId]=t.value:delete r[t.fieldId])})}function nt(e){if(!Array.isArray(e)||e.length<2)return[{tableId:``,reason:`unknown`}];let t=e,n=t.indexOf(`tables`);return n===-1||typeof t[n+1]!=`string`?t[0]===`tableOrder`?[]:[{tableId:``,reason:`unknown`}]:rt(t,n,String(t[n+1]))}function rt(e,t,n){let r=e[t+2];return r===`records`&&typeof e[t+3]==`string`?it(e,t,n,String(e[t+3])):r===`cellData`&&e[t+3]!=null&&e[t+4]!=null?[{tableId:n,reason:`cell`,row:Number(e[t+3]),column:Number(e[t+4])}]:r===`fields`&&typeof e[t+3]==`string`?[{tableId:n,reason:`field`,fieldId:String(e[t+3])}]:r===`fieldOrder`?[{tableId:n,reason:`field`}]:r===`recordOrder`?[{tableId:n,reason:`record`}]:r===`views`&&typeof e[t+3]==`string`?[{tableId:n,reason:`view`,viewId:String(e[t+3])}]:r===`viewOrder`?[{tableId:n,reason:`view`}]:r===`resources`?[{tableId:n,reason:`cell`}]:[{tableId:n,reason:r===void 0?`table`:`unknown`}]}function it(e,t,n,r){return e[t+4]===`values`&&typeof e[t+5]==`string`?[{tableId:n,reason:`cell`,recordId:r,fieldId:String(e[t+5])}]:e[t+4]===`updatedAt`||e[t+4]===`updatedBy`?[]:[{tableId:n,reason:`record`,recordId:r}]}function at(e){if(!Array.isArray(e))return[];let t=e.filter(Array.isArray);if(t.length>1&&t.length===e.length)return t;let n=e.findIndex(Array.isArray);if(n>0&&e.slice(n).every(Array.isArray)){let t=e.slice(0,n);return e.slice(n).map(e=>[...t,...e])}let r=e.indexOf(`tables`);if(r===-1||typeof e[r+1]!=`string`)return[];let i=String(e[r+1]),a=e.slice(r+2).filter(Array.isArray);return a.length<=1?[]:a.map(e=>[`tables`,i,...e])}function ot(e){let t=/* @__PURE__ */ new Set;return e.filter(e=>{let n=JSON.stringify(e);return!t.has(n)&&(t.add(n),!0)})}function st(e){return g.deepClone(e)}function ct(e,t){let n=lt(t);if(!n.length)return st(e);let r=gt(e),i=/* @__PURE__ */ new Set;for(let e of n)ft(r,e,i);return r}function lt(e){let t=[];return ut(e,[],t),t}function ut(e,t,n){if(!Array.isArray(e))return;let r=[];for(let i of e)Array.isArray(i)?ut(i,[...t,...r],n):dt(i)?n.push([...t,...r]):(typeof i==`string`||typeof i==`number`)&&r.push(i)}function dt(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return`i`in t||`r`in t||`p`in t||`d`in t||`es`in t||`ena`in t||`et`in t}function ft(e,t,n){let r=e,i=[];for(let e=0;e<t.length-1;e++){let a=t[e];i.push(a);let o=pt(r,a);if(!ht(o))return;let s=JSON.stringify(i);n.has(s)||(mt(r,a,gt(o)),n.add(s));let c=pt(r,a);if(!ht(c))return;r=c}}function pt(e,t){return Array.isArray(e)?typeof t==`number`?e[t]:void 0:Reflect.get(e,t)}function mt(e,t,n){Array.isArray(e)?typeof t==`number`&&(e[t]=n):Reflect.set(e,t,n)}function ht(e){return!!e&&typeof e==`object`}function gt(e){return Array.isArray(e)?e.slice():{...e}}const R=`yyyy/mm/dd`,_t=/\s+hh:mm\s*$/i,vt={"yyyy/mm/dd":`YYYY/MM/DD`,"yyyy-mm-dd":`YYYY-MM-DD`,"mm-dd":`MM-DD`,"mm/dd/yyyy":`MM/DD/YYYY`,"dd/mm/yyyy":`DD/MM/YYYY`,"mmm d, yyyy":`MMM D, YYYY`};function z(e,t=d.Date1900){let n=y(e).valueOf();return ee(new Date(n),t)}function yt(e,t=d.Date1900){return te(e,t).getTime()}function B(e,t=d.Date1900){if(e==null||e===``)return null;if(e instanceof Date)return z(e,t);if(typeof e==`number`)return Number.isFinite(e)?e>1e6?z(e,t):e:null;let n=Date.parse(String(e));return Number.isNaN(n)?null:z(n,t)}function V(e,t=d.Date1900){let n=B(e,t);return n==null?null:yt(n,t)}function bt(e={}){let t=String(e.pattern??e.format??e.dateFormat??R).trim()||R,n=_t.test(t);return{pattern:t.replace(_t,``)||R,includeTime:typeof e.includeTime==`boolean`?e.includeTime:n,hourCycle:e.hourCycle===`h12`?`h12`:`h24`}}function xt(e={}){let{format:t,dateFormat:n,...r}=e;return{...r,...bt(e)}}function St(e,t={}){let n=V(e);if(n==null||!Number.isFinite(n))return``;let r=bt(t);return y(n).format(Ct(r))}function Ct(e){let{pattern:t,includeTime:n,hourCycle:r}=e,i=vt[t]??vt[R];return n?`${i} ${r===`h12`?`h:mm a`:`HH:mm`}`:i}const wt={editable:!0,sortable:!0,filterable:!0,groupable:!1,usableAsKanbanGroup:!1,usableAsCalendarDate:!1,usableAsGanttStart:!1,usableAsGanttEnd:!1,usableAsGanttProgress:!1,usableAsCardCover:!1,usableAsTitle:!1},Tt=/* @__PURE__ */ new Set([r.RecordId]);function Et(e){switch(e){case r.Number:case r.Currency:case r.Progress:case r.Rating:return[t.IS,t.IS_NOT,t.GREATER_THAN,t.LESS_THAN,t.IS_EMPTY,t.IS_NOT_EMPTY];case r.Date:case r.CreatedAt:case r.UpdatedAt:return[t.IS,t.IS_NOT,t.BEFORE,t.AFTER,t.IS_EMPTY,t.IS_NOT_EMPTY];case r.Checkbox:return[t.IS,t.IS_NOT];default:return[t.IS,t.IS_NOT,t.CONTAINS,t.NOT_CONTAINS,t.IS_EMPTY,t.IS_NOT_EMPTY]}}function Dt(e){return e===r.Date||e===r.CreatedAt||e===r.UpdatedAt}function Ot(e,t){return e==null&&t==null?0:e==null?-1:t==null?1:typeof e==`number`&&typeof t==`number`?e-t:String(e).localeCompare(String(t))}function kt(e,t,n,i,a={}){if(t===`isEmpty`)return At(e);if(t===`isNotEmpty`)return!At(e);switch(i.type){case r.Number:case r.Currency:case r.Progress:case r.Rating:return jt(e,t,n);case r.Date:case r.CreatedAt:case r.UpdatedAt:return Nt(e,t,n,a);case r.Checkbox:return zt(e,t,n);case r.SingleSelect:case r.MultiSelect:case r.Person:case r.Group:return Vt(e,t,n,i);default:return Ht(e,t,n)}}function At(e){return e==null?!0:Array.isArray(e)?e.length===0:typeof e==`string`&&e.trim()===``}function jt(e,t,n){let r=Mt(e),i=Mt(n);if(r==null||i==null)return!1;switch(t){case`is`:return r===i;case`isNot`:return r!==i;case`greaterThan`:return r>i;case`greaterThanOrEqual`:return r>=i;case`lessThan`:return r<i;case`lessThanOrEqual`:return r<=i;default:return!1}}function Mt(e){if(e==null||e===``)return null;let t=Number(e);return Number.isFinite(t)?t:null}function Nt(e,r,i,a){let o=Ft(e);if(o==null)return!1;let s=Pt(a.dateMode??n.EXACT,i,a.now);if(!s)return!1;switch(r){case t.IS:return o>=s.start&&o<=s.end;case t.IS_NOT:return o<s.start||o>s.end;case t.BEFORE:return o<s.start;case t.AFTER:return o>s.end;default:return!1}}function Pt(e,t,r=Date.now()){let i=It(r);switch(e){case n.EXACT:{let e=Ft(t);return e==null?null:H(e,0,1)}case n.TODAY:return H(i,0,1);case n.TOMORROW:return H(i,1,1);case n.YESTERDAY:return H(i,-1,1);case n.THIS_WEEK:return Lt(i,0);case n.LAST_WEEK:return Lt(i,-1);case n.THIS_MONTH:return Rt(i,0);case n.LAST_MONTH:return Rt(i,-1);case n.PAST_7_DAYS:return H(i,-6,7);case n.NEXT_7_DAYS:return H(i,0,7);case n.PAST_30_DAYS:return H(i,-29,30);case n.NEXT_30_DAYS:return H(i,0,30)}}function Ft(e){let t=B(e);return t==null?null:It(yt(t))}function It(e){let t=new Date(e);return t.setHours(0,0,0,0),t.getTime()}function Lt(e,t){return H(e,-((new Date(e).getDay()+6)%7)+t*7,7)}function H(e,t,n){let r=y(e).add(t,`day`);return{start:r.valueOf(),end:r.add(n,`day`).valueOf()-1}}function Rt(e,t){let n=new Date(e),r=new Date(n.getFullYear(),n.getMonth()+t,1),i=new Date(n.getFullYear(),n.getMonth()+t+1,1);return{start:r.getTime(),end:i.getTime()-1}}function zt(e,t,n){let r=Bt(e),i=Bt(n);switch(t){case`is`:return r===i;case`isNot`:return r!==i;default:return!1}}function Bt(e){return e===!0||e===`true`||e===1||e===`1`}function Vt(e,t,n,r){let i=Wt(e,r),a=Wt(n,r),o=a.length>0&&a.some(e=>i.includes(e));switch(t){case`is`:case`contains`:return o;case`isNot`:case`notContains`:return!o;default:return!1}}function Ht(e,t,n){let r=Ut(e),i=Ut(n);switch(t){case`is`:return r===i;case`isNot`:return r!==i;case`contains`:return i?r.includes(i):!1;case`notContains`:return!i||!r.includes(i);default:return!1}}function Ut(e){if(Array.isArray(e))return e.map(e=>Ut(e)).join(`
2
- `);if(e&&typeof e==`object`){let t=e;return String(t.name??t.label??t.text??t.value??t.id??``).trim().toLowerCase()}return String(e??``).trim().toLowerCase()}function Wt(e,t){let n=U(e),r=Gt(t.config??{});return n.flatMap(e=>r.get(e)??[e]).filter((e,t,n)=>e!==``&&n.indexOf(e)===t)}function U(e){if(e==null||e===``)return[];if(Array.isArray(e))return e.flatMap(e=>U(e));if(e&&typeof e==`object`){let t=e;return[`id`,`name`,`label`,`value`,`text`].flatMap(e=>U(t[e])).filter((e,t,n)=>n.indexOf(e)===t)}return[Ut(e)]}function Gt(e){let t=/* @__PURE__ */ new Map;return(Array.isArray(e.options)?e.options:[]).forEach(e=>{if(!e||typeof e!=`object`)return;let n=U(e),r=n.filter((e,t)=>e!==``&&n.indexOf(e)===t);r.forEach(e=>t.set(e,r))}),t}function W(e,t={},n=e=>e,r={}){let i=!Tt.has(e),a=n??(e=>e);return{type:e,i18nKey:`base.fieldType.${e}`,enabled:i,visibleInCreateMenu:i,createDefaultConfig:r.createDefaultConfig??(()=>({})),createDefaultValue:r.createDefaultValue??(e=>e.defaultValue??null),normalize:(e,t)=>a(e,t),validate:(e,t)=>{var n;return i?((n=r.validate)==null?void 0:n.call(r,e,t))??{valid:!0}:{valid:!1}},compare:(e,t)=>Ot(e,t),filter:(e,t,n,r)=>kt(e,t,n,r),toPlainText:r.toPlainText??(e=>e==null?``:String(e)),fromPlainText:r.fromPlainText??(t=>a(t,{id:``,name:``,type:e,config:{}})),getCapabilities:()=>({...wt,...t,editable:i&&(t.editable??wt.editable)})}}function Kt(){return[W(r.Text,{groupable:!0,usableAsTitle:!0},void 0,{createDefaultConfig:()=>({placeholder:`bases.fieldConfig.textPlaceholder`}),createDefaultValue:e=>e.defaultValue??``}),W(r.SingleSelect,{groupable:!0,usableAsKanbanGroup:!0,supportsOptions:!0},e=>e==null||e===``?null:String(e),{createDefaultConfig:()=>({options:[],optionSource:{type:`manual`}})}),W(r.MultiSelect,{filterable:!0,usableAsKanbanGroup:!0,supportsOptions:!0,supportsMultipleValues:!0},e=>Array.isArray(e)?e.map(String):e==null?[]:[String(e)],{createDefaultConfig:()=>({options:[],optionSource:{type:`manual`}}),createDefaultValue:e=>e.defaultValue??[]}),W(r.Person,{groupable:!0,usableAsKanbanGroup:!0,supportsMultipleValues:!0},Zt,{createDefaultConfig:()=>({allowMultiple:!1,provider:`person`}),validate:Qt}),W(r.Group,{groupable:!0,usableAsKanbanGroup:!0,supportsMultipleValues:!0},Yt,{createDefaultConfig:()=>({allowMultiple:!0,provider:`group`}),createDefaultValue:e=>e.defaultValue??[],validate:$t}),W(r.Date,{groupable:!0,usableAsCalendarDate:!0,usableAsGanttStart:!0,usableAsGanttEnd:!0},e=>B(e),{createDefaultConfig:()=>Jt(),validate:en}),W(r.Attachment,{usableAsCardCover:!0,supportsMultipleValues:!0},e=>e==null?[]:Array.isArray(e)?e:[e],{createDefaultValue:e=>e.defaultValue??[]}),W(r.Number,{},e=>e==null||e===``?null:Number(e),{createDefaultConfig:()=>qt(),validate:tn}),W(r.Checkbox,{groupable:!0,usableAsKanbanGroup:!0},e=>e===!0||e===`true`||e===1||e===`1`,{createDefaultConfig:()=>({icon:`check`,color:`#16a34a`}),createDefaultValue:e=>e.defaultValue??!1,validate:e=>typeof e==`boolean`?{valid:!0}:{valid:!1,reason:`[BaseField]: invalid checkbox value.`}}),W(r.Link,{supportsRelation:!0},rn,{createDefaultConfig:()=>({placeholder:`bases.fieldConfig.linkPlaceholder`}),toPlainText:e=>an(e),fromPlainText:e=>rn(e)}),W(r.Formula,{editable:!1},void 0,{createDefaultConfig:()=>({formula:``,dependencies:[],numfmt:{type:`general`,pattern:`General`}}),createDefaultValue:()=>null}),W(r.Numbering,{editable:!1,usableAsTitle:!0},void 0,{createDefaultConfig:()=>({mode:`autoIncrement`}),createDefaultValue:()=>null}),W(r.Phone,{usableAsTitle:!0},e=>e==null?null:String(e).trim(),{validate:e=>e==null||e===``||/^\+?[0-9 ()-]{6,20}$/.test(String(e))?{valid:!0}:{valid:!1,reason:`[BaseField]: invalid phone value.`}}),W(r.Email,{usableAsTitle:!0},e=>e==null?null:String(e).trim(),{validate:e=>e==null||e===``||sn(String(e))?{valid:!0}:{valid:!1,reason:`[BaseField]: invalid email value.`}}),W(r.Progress,{usableAsGanttProgress:!0},e=>e==null||e===``?null:Number(e),{createDefaultConfig:()=>({format:`percent`,decimalPlaces:0,color:`blue`,customRange:!1,start:0,end:100}),validate:(e,t)=>nn(e,t,`[BaseField]: invalid progress value.`)}),W(r.Currency,{},e=>e==null||e===``?null:Number(e),{createDefaultConfig:()=>({...qt(),currencySymbol:`$`}),validate:tn}),W(r.Rating,{groupable:!0,usableAsKanbanGroup:!0},e=>e==null||e===``?null:Number(e),{createDefaultConfig:()=>({icon:`star`,min:1,max:5}),createDefaultValue:()=>null,validate:(e,t)=>nn(e,t,`[BaseField]: invalid rating value.`)}),W(r.RecordLink,{supportsRelation:!0,supportsMultipleValues:!0},Xt,{createDefaultConfig:()=>({targetTableId:``,multiple:!1}),createDefaultValue:()=>``,validate:(e,t)=>ie(e,t.config.multiple===!0)}),W(r.RecordId,{editable:!1,sortable:!0,filterable:!0,usableAsTitle:!0}),W(r.CreatedBy,{editable:!1,groupable:!0},e=>e==null?null:String(e),{createDefaultConfig:()=>({provider:`user`}),createDefaultValue:()=>null}),W(r.UpdatedBy,{editable:!1,groupable:!0},e=>e==null?null:String(e),{createDefaultConfig:()=>({provider:`user`}),createDefaultValue:()=>null}),W(r.CreatedAt,{editable:!1,usableAsCalendarDate:!0,usableAsGanttStart:!0,usableAsGanttEnd:!0},e=>B(e),{createDefaultConfig:()=>Jt(),createDefaultValue:()=>null,validate:en}),W(r.UpdatedAt,{editable:!1,usableAsCalendarDate:!0,usableAsGanttStart:!0,usableAsGanttEnd:!0},e=>B(e),{createDefaultConfig:()=>Jt(),createDefaultValue:()=>null,validate:en})]}function qt(){return{pattern:`#,##0.00`,decimalPlaces:2,separatorStyle:`local`,useThousands:!0,abbreviation:`none`,allowNegative:!0}}function Jt(){return{locale:`en-US`,pattern:`yyyy/mm/dd`,includeTime:!1,hourCycle:`h24`,defaultMode:`none`}}function Yt(e){return e==null||e===``?[]:Array.isArray(e)?e.map(String):[String(e)]}function Xt(e){return typeof e==`string`?e:``}function Zt(e,t){return e==null||e===``?t.config.allowMultiple===!0?[]:null:t.config.allowMultiple===!0?Array.isArray(e)?e.map(String):[String(e)]:Array.isArray(e)?String(e[0]??``)||null:String(e)}function Qt(e,t){return t.config.allowMultiple===!0?$t(e):e==null||e===``||typeof e==`string`?{valid:!0}:{valid:!1,reason:`[BaseField]: invalid person value.`}}function $t(e){return e==null||Array.isArray(e)&&e.every(e=>typeof e==`string`)?{valid:!0}:{valid:!1,reason:`[BaseField]: invalid multi-value reference.`}}function en(e){return e==null||typeof e==`number`&&Number.isFinite(e)?{valid:!0}:{valid:!1,reason:`[BaseField]: invalid date value.`}}function tn(e,t){return e==null||e===``?{valid:!0}:typeof e!=`number`||!Number.isFinite(e)?{valid:!1,reason:`[BaseField]: invalid number value.`}:t.config.allowNegative===!1&&e<0?{valid:!1,reason:`[BaseField]: negative numbers are disabled.`}:{valid:!0}}function nn(e,t,n){let r=tn(e,t);if(!r.valid||e==null||e===``)return r;let i=Number(t.config.min??t.config.start??0),a=Number(t.config.max??t.config.end??100),o=Number(e);return o>=i&&o<=a?{valid:!0}:{valid:!1,reason:n}}function rn(e){if(e==null||e===``)return null;if(typeof e==`object`&&!Array.isArray(e)){let t=e,n=typeof t.text==`string`?t.text.trim():``,r=typeof t.url==`string`?t.url.trim():``,i=on(r||n);return i?{text:n||r||i,url:i}:null}let t=String(e).trim(),n=on(t);return n?{text:t,url:n}:null}function an(e){if(e==null)return``;if(typeof e==`object`&&!Array.isArray(e)){let t=e;return String(t.text||t.url||``)}return String(e)}function on(e){let t=e.trim();if(!t)return``;let n=/^[a-z][a-z\d+.-]*:/i.test(t)?t:t.startsWith(`//`)?`https:${t}`:`https://${t}`;try{let e=new URL(n);return e.protocol===`http:`||e.protocol===`https:`?e.href:``}catch{return``}}function sn(e){let t=e.indexOf(`@`);if(t<=0||t!==e.lastIndexOf(`@`))return!1;let n=e.slice(t+1);return n.includes(`.`)&&!e.includes(` `)&&!n.startsWith(`.`)&&!n.endsWith(`.`)}function G(e){"@babel/helpers - typeof";return G=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},G(e)}function cn(e,t){if(G(e)!=`object`||!e)return e;var n;if(typeof Symbol<`u`&&(n=e[Symbol.toPrimitive])!==void 0){var r=n.call(e,t||`default`);if(G(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function ln(e){var t=cn(e,`string`);return G(t)==`symbol`?t:t+``}function K(e,t,n){return(t=ln(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const un=v(`base.field-registry.service`);var dn=class extends f{constructor(...e){super(...e),K(this,`_plugins`,/* @__PURE__ */ new Map)}register(e){return this._plugins.set(e.type,e),b(()=>this._plugins.delete(e.type))}get(e){let t=this._plugins.get(e);if(!t)throw Error(`[BaseFieldRegistryService]: field type "${e}" is not registered.`);return t}getTypePlugin(e){return this._plugins.get(e)}getAll(){return Array.from(this._plugins.values())}};function fn(e,t){return function(n,r){t(n,r,e)}}function pn(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}function mn(e){let t=e&&typeof e==`object`?e:{},n=Number(t.start??0),r=Number(t.end??100);return t.customRange===!0?{start:Number.isFinite(n)?n:0,end:Number.isFinite(r)?r:100}:{start:0,end:100}}function hn(e,t){let n=t&&typeof t==`object`&&!Array.isArray(t)?t:{},r=e.toFixed(gn(n.decimalPlaces));return n.format===`number`?r:`${r}%`}function gn(e){if(e==null||e===``)return 0;let t=typeof e==`number`?e:Number(e);return Number.isFinite(t)?Math.max(0,Math.min(2,Math.round(t))):0}const _n=/* @__PURE__ */ new Set([r.Progress,r.Rating,r.Checkbox]);function vn(e){let t=e.fields[e.primaryFieldId];if((!t||t.system!==!0&&t.id.toLowerCase()!==`id`&&t.name.trim().toLowerCase()!==`id`)&&t)return t.id;for(let t of e.fieldOrder){let n=e.fields[t];if(n&&n.id!==e.primaryFieldId&&n.system!==!0&&n.type!==r.RecordId)return n.id}return e.primaryFieldId}function q(e,t=[],n=5){let i=new Set(t.filter(e=>!!e)),a=[],o=[];for(let t of e.fieldOrder){let n=e.fields[t];n&&n.system!==!0&&n.type!==r.RecordId&&!i.has(n.id)&&(_n.has(n.type)?a:o).push(n.id)}return[...a,...o].slice(0,n)}function yn(){return[{type:c.Grid,i18nKey:`base.viewType.grid`,createDefaultConfig:()=>({}),validateConfig:()=>({valid:!0}),buildProjection:()=>{throw Error(`Grid projection is implemented by BaseProjectionService.`)}},{type:c.Kanban,i18nKey:`base.viewType.kanban`,createDefaultConfig:e=>{let t=bn(e);return{groupFieldId:t,coverFieldId:null,cardLayout:`normal`,showFieldNames:!0,fieldSettings:{},columnSettings:{},card:{titleFieldId:e.primaryFieldId,fieldIds:q(e,[e.primaryFieldId,t])}}},validateConfig:()=>({valid:!0}),buildProjection:()=>{throw Error(`Kanban projection is implemented by BaseProjectionService.`)}},{type:c.Calendar,i18nKey:`base.viewType.calendar`,createDefaultConfig:e=>{let t=xn(e);return{startDateFieldId:t,endDateFieldId:Sn(e,t),titleFieldId:e.primaryFieldId,mode:`month`,timeslotSize:`medium`,timeZone:`local`,displayColor:{type:`custom`,color:`#3b82f6`},fieldSettings:{}}},validateConfig:()=>({valid:!0}),buildProjection:()=>{throw Error(`Calendar projection is implemented by BaseProjectionService.`)}},{type:c.Gantt,i18nKey:`base.viewType.gantt`,createDefaultConfig:e=>{let t=xn(e);return{startDateFieldId:t,endDateFieldId:Sn(e,t)??t,titleFieldId:e.primaryFieldId,scale:`month`,showTodayLine:!0,displayColor:{type:`custom`,color:`#3b82f6`},fieldSettings:{},workingDaysOnly:!1}},validateConfig:()=>({valid:!0}),buildProjection:()=>{throw Error(`Gantt projection is implemented by BaseProjectionService.`)}},{type:c.Gallery,i18nKey:`base.viewType.gallery`,createDefaultConfig:e=>{let t=vn(e);return{coverFieldId:null,cardLayout:`normal`,showFieldNames:!0,fieldSettings:{},card:{titleFieldId:t,coverFieldId:null,fieldIds:q(e,[t,e.primaryFieldId])},cardSize:`medium`}},validateConfig:()=>({valid:!0}),buildProjection:()=>{throw Error(`Gallery projection is implemented by BaseProjectionService.`)}}]}function bn(e){var t,n,i;let a=e.fieldOrder.map(t=>e.fields[t]).filter(e=>!!e);return((t=a.find(e=>e.type===r.SingleSelect||e.type===r.MultiSelect||e.type===r.Group))==null?void 0:t.id)??((n=a.find(e=>e.type===r.Text))==null?void 0:n.id)??((i=a.find(e=>e.type===r.Date||e.type===r.CreatedAt||e.type===r.UpdatedAt))==null?void 0:i.id)??e.primaryFieldId}function xn(e){var t;return((t=e.fieldOrder.map(t=>e.fields[t]).find(Cn))==null?void 0:t.id)??``}function Sn(e,t){var n;return(n=e.fieldOrder.map(t=>e.fields[t]).find(e=>Cn(e)&&e.id!==t))==null?void 0:n.id}function Cn(e){return!!e&&e.type===r.Date&&e.readonly!==!0&&e.system!==!0}const wn=v(`base.projection.service`),Tn=/* @__PURE__ */ new Set([r.Number,r.Currency,r.Progress,r.Rating,r.Date,r.CreatedAt,r.UpdatedAt,r.Checkbox]),J=864e5;let En=class extends f{constructor(e){super(),this._fieldRegistry=e,K(this,`_views`,/* @__PURE__ */ new Map),K(this,`_projectionCache`,/* @__PURE__ */ new WeakMap),K(this,`_projectedRowsCache`,/* @__PURE__ */ new Map),K(this,`_projectedViewRowsCache`,/* @__PURE__ */ new Map),K(this,`_projectedGroupsCache`,/* @__PURE__ */ new Map),K(this,`_hierarchyIndexCache`,/* @__PURE__ */ new Map),K(this,`_globalRevision`,0),K(this,`_tableRevisions`,/* @__PURE__ */ new Map),K(this,`_cellRevisions`,/* @__PURE__ */ new Map),K(this,`_cellInvalidations`,/* @__PURE__ */ new Map),K(this,`_viewRevisions`,/* @__PURE__ */ new Map)}registerView(e){return this._views.set(e.type,e),b(()=>this._views.delete(e.type))}getProjection(e,t,n){var r,i,a;return O(`BaseProjection.getProjection`,()=>{let r=this._getCachedProjection(e,t,n);if(r)return r;let i=e.tables[t],a=i==null?void 0:i.views[n];if(!i||!a)return this._setCachedProjection(e,t,n,{type:`invalid`,viewType:(a==null?void 0:a.type)??c.Grid,reason:`missingField`});let o;switch(a.type){case c.Grid:o=this._buildGrid(i,a);break;case c.Gantt:o=this._buildGantt(i,a);break;case c.Kanban:o=this._buildKanban(i,a);break;case c.Calendar:o=this._buildCalendar(i,a);break;case c.Gallery:o=this._buildGallery(i,a);break;default:o={type:`invalid`,viewType:a.type,reason:`missingField`}}return this._setCachedProjection(e,t,n,o)},{tableId:t,viewId:n,viewType:(r=e.tables[t])==null||(r=r.views[n])==null?void 0:r.type,records:((i=e.tables[t])==null||(i=i.recordOrder)==null?void 0:i.length)??Object.keys(((a=e.tables[t])==null?void 0:a.records)??{}).length})}repairViewConfig(e,t,n){var r,i,a;let o=e.tables[t],s=o==null?void 0:o.views[n];if(!o||!s)throw Error(`[BaseProjectionService]: missing view "${n}".`);let c=e=>!!o.fields[e],l={...s,filter:s.filter?{...s.filter,conditions:s.filter.conditions.filter(e=>c(e.fieldId))}:s.filter,sort:(r=s.sort)==null?void 0:r.filter(e=>c(e.fieldId)),group:(i=s.group)==null?void 0:i.filter(e=>c(e.fieldId)),fieldOrder:(a=s.fieldOrder)==null?void 0:a.filter(c),fieldSettings:Object.fromEntries(Object.entries(s.fieldSettings??{}).filter(([e])=>c(e)))};if(l.type===`kanban`){var u;let e=l.config??{},t=this._resolveKanbanGroupFieldId(o,l),n=this._resolveCardTitleFieldId(o,(u=e.card)==null?void 0:u.titleFieldId);l.config={...e,groupFieldId:t??e.groupFieldId,coverFieldId:this._resolveKanbanCoverFieldId(o,e),cardLayout:e.cardLayout===`compose`?`compose`:`normal`,showFieldNames:e.showFieldNames!==!1,fieldSettings:Object.fromEntries(Object.entries(e.fieldSettings??{}).filter(([e])=>c(e))),columnSettings:e.columnSettings??{},card:{...e.card??{},titleFieldId:n,fieldIds:this._resolveKanbanCardFieldIds(o,l,t??``,n)}}}return{repaired:JSON.stringify(l)!==JSON.stringify(s),view:l}}invalidateByOp(){this._globalRevision++}invalidateByCell(e,t,n){let r=this._getCellRevision(e)+1;this._cellRevisions.set(e,r);let i=this._cellInvalidations.get(e)??[];i.push({revision:r,recordId:t,fieldId:n}),this._cellInvalidations.set(e,i)}invalidateByField(e,t){this._bumpTableRevision(e)}invalidateByView(e,t){this._viewRevisions.set(this._viewRevisionKey(e,t),this._getViewRevision(e,t)+1)}_getCachedProjection(e,t,n){var r;let i=(r=this._projectionCache.get(e))==null?void 0:r.get(this._cacheKey(t,n));return i&&i.globalRevision===this._globalRevision&&i.tableRevision===this._getTableRevision(t)&&i.cellRevision===this._getCellRevision(t)&&i.viewRevision===this._getViewRevision(t,n)?i.projection:null}_setCachedProjection(e,t,n,r){let i=this._projectionCache.get(e);return i||(i=/* @__PURE__ */ new Map,this._projectionCache.set(e,i)),i.set(this._cacheKey(t,n),{projection:r,globalRevision:this._globalRevision,tableRevision:this._getTableRevision(t),cellRevision:this._getCellRevision(t),viewRevision:this._getViewRevision(t,n)}),r}_bumpTableRevision(e){this._tableRevisions.set(e,this._getTableRevision(e)+1)}_getTableRevision(e){return this._tableRevisions.get(e)??0}_getCellRevision(e){return this._cellRevisions.get(e)??0}_getViewRevision(e,t){return this._viewRevisions.get(this._viewRevisionKey(e,t))??0}_cacheKey(e,t){return`${e}\u0000${t}`}_viewRowsCacheKey(e,t){return`${e}\u0000${this._rowTransformCacheSegment(t)}`}_groupsCacheKey(e,t,n){return`${e}\u0000${this._rowTransformCacheSegment(t)}\u0000${this._groupConfigCacheSegment(n)}`}_rowTransformCacheSegment(e){return e?Y({filter:An(e.filter),sort:Mn(e.sort)}):`__all__`}_groupConfigCacheSegment(e){return Y(e.map(e=>({fieldId:e.fieldId,direction:e.direction??null})))}_viewRevisionKey(e,t){return`${e}\u0000${t}`}_buildGrid(e,t){let{rows:n,hierarchy:r}=this._projectHierarchyRows(e,t,T(e));return{type:c.Grid,fields:this._projectFields(e,t),rows:n,groups:this._projectHierarchyGroups(e,t,n,r),hierarchy:r,frozenFieldCount:typeof t.config.frozenFieldCount==`number`?t.config.frozenFieldCount:0}}_projectHierarchyRows(e,t,n){var r;let i=this._projectRows(e,t),a=(r=t.filter)!=null&&r.conditions.length?this._projectRows(e,{...t,filter:null}):i;return be(this._getHierarchyIndex(e,n,t.id,a.map(e=>e.recordId)),a,new Set(i.map(e=>e.recordId)))}_getHierarchyIndex(e,t,n,r){let i=`${e.id}\u0000${t}\u0000${n}`,a=this._getCellRevision(e.id),o=this._hierarchyIndexCache.get(i);if(o&&o.globalRevision===this._globalRevision&&o.tableRevision===this._getTableRevision(e.id)&&o.orderedRecordIds.length===r.length&&o.orderedRecordIds.every((e,t)=>e===r[t])){if(o.cellRevision===a&&o.table===e)return o.index;if(!this._cellInvalidationsTouchFields(e.id,o.cellRevision,a,/* @__PURE__ */ new Set([t])))return this._hierarchyIndexCache.set(i,{...o,table:e,cellRevision:a}),o.index}let s=D(e,t,r);return this._hierarchyIndexCache.set(i,{table:e,index:s,orderedRecordIds:r,globalRevision:this._globalRevision,tableRevision:this._getTableRevision(e.id),cellRevision:a}),s}_projectHierarchyGroups(e,t,n,r){var i;if(!((i=t.group)!=null&&i.length))return[];let a=new Map(n.map(e=>[e.recordId,e])),o=r.rootRecordIds.flatMap(e=>{let t=a.get(e);return t?[t]:[]}),s=this._projectGroups(e,t,o),c=new Map(r.orderedRecordIds.map((e,t)=>[e,t])),l=e=>{let t=r.nodes[e],n=c.get(e)??-1;return n<0||!t?[]:r.orderedRecordIds.slice(n,t.subtreeEndIndex+1)},u=e=>{var t,n;return{...e,recordIds:(t=e.children)!=null&&t.length?e.recordIds:e.recordIds.flatMap(l),children:(n=e.children)==null?void 0:n.map(u)}};return s.map(u)}_buildKanban(e,t){var n;let r=this._resolveKanbanGroupFieldId(e,t),i=r?e.fields[r]:void 0;if(!i)return{type:`invalid`,viewType:c.Kanban,reason:`invalidGroupField`,fieldId:t.config.groupFieldId};let a=this._projectRows(e,t),o=this._projectFields(e,t),s=t.config??{},l=this._resolveCardTitleFieldId(e,(n=s.card)==null?void 0:n.titleFieldId),u=this._resolveKanbanCardFieldIds(e,t,i.id,l),d=/* @__PURE__ */ new Map;if(C(e,i.id)){let n=this._getHierarchyIndex(e,i.id,t.id,a.map(e=>e.recordId)),r=/* @__PURE__ */ new Map;return a.forEach(t=>{let a=n.parentByRecordId.get(t.recordId)??null,o=a??``,c=a?e.records[a]:void 0,l=r.get(o)??{key:o,title:c?String(A(e,c.id,e.primaryFieldId)??a):this._kanbanLaneTitle(i,o,s),recordIds:[]};l.recordIds.push(t.recordId),r.set(o,l)}),{type:c.Kanban,fields:o,rows:a,groups:[],groupFieldId:i.id,titleFieldId:l,coverFieldId:this._resolveKanbanCoverFieldId(e,s),cardLayout:s.cardLayout===`compose`?`compose`:`normal`,showFieldNames:s.showFieldNames!==!1,visibleCardFieldIds:u,lanes:[``,...n.orderedRecordIds].flatMap(e=>{let t=r.get(e);return t!=null&&t.recordIds.length?[t]:[]})}}return this._getKanbanConfiguredLanes(i,s).forEach(e=>d.set(e.key,{...e,recordIds:[]})),a.forEach(e=>{this._kanbanGroupKeys(i,e.values[i.id]).forEach(t=>{let n=d.get(t)??{key:t,title:this._kanbanLaneTitle(i,t,s),color:this._kanbanLaneColor(i,t,s),recordIds:[]};n.recordIds.push(e.recordId),d.set(t,n)})}),{type:c.Kanban,fields:o,rows:a,groups:this._projectGroups(e,t,a),groupFieldId:i.id,titleFieldId:l,coverFieldId:this._resolveKanbanCoverFieldId(e,s),cardLayout:s.cardLayout===`compose`?`compose`:`normal`,showFieldNames:s.showFieldNames!==!1,visibleCardFieldIds:u,lanes:Array.from(d.values())}}_resolveKanbanGroupFieldId(e,t){var n;let r=(n=t.config)==null?void 0:n.groupFieldId;return r&&this._isKanbanGroupField(e,r)?r:this._findKanbanGroupField(e,e=>this._isAllowedKanbanGroupField(e))}_findKanbanGroupField(e,t){for(let n of e.fieldOrder){let r=e.fields[n];if(r&&t(r))return r.id}return null}_isKanbanGroupField(e,t){let n=e.fields[t];return this._isAllowedKanbanGroupField(n)||C(e,t)}_isAllowedKanbanGroupField(e){return!!e&&(e.type===r.SingleSelect||e.type===r.MultiSelect||e.type===r.Rating||e.type===r.Person||e.type===r.Group||e.type===r.Checkbox)}_isColorfulKanbanGroupField(e){return e.type===r.SingleSelect||e.type===r.MultiSelect}_resolveKanbanCoverFieldId(e,t){var n;let r=t.coverFieldId??((n=t.card)==null?void 0:n.coverFieldId)??null;if(!r)return null;let i=e.fields[r];return i&&this._capabilities(i).usableAsCardCover?i.id:null}_resolveKanbanCardFieldIds(e,t,n,i=this._resolveCardTitleFieldId(e,(()=>{var e;return(e=t.config)==null||(e=e.card)==null?void 0:e.titleFieldId})())){var a;let o=t.config??{},s=(a=o.card)!=null&&(a=a.fieldIds)!=null&&a.length?o.card.fieldIds:q(e,[i,e.primaryFieldId,n]),c=o.fieldSettings??{};return s.filter(a=>{var o,s;let l=e.fields[a];return!(!l||l.system===!0||l.type===r.RecordId||l.id===n||l.id===i||(o=t.fieldSettings)!=null&&(o=o[a])!=null&&o.hidden||(s=c[a])!=null&&s.hidden)}).sort((e,t)=>{var n,r;return(((n=c[e])==null?void 0:n.order)??s.indexOf(e))-(((r=c[t])==null?void 0:r.order)??s.indexOf(t))})}_getKanbanConfiguredLanes(e,t){var n;let r=(Array.isArray((n=e.config)==null?void 0:n.options)?e.config.options:[]).flatMap((n,r)=>{if(n==null)return[];let i=typeof n==`string`?{id:n,name:n,color:void 0}:n,a=String(i.id??i.name??`option-${r+1}`);return[{key:a,title:String(i.name??i.id??a),color:this._kanbanLaneColor(e,a,t)}]});return Object.entries(t.columnSettings??{}).forEach(([n,i])=>{r.some(e=>e.key===n)||r.push({key:n,title:this._isColorfulKanbanGroupField(e)?i.title??this._kanbanLaneTitle(e,n,t):this._kanbanLaneTitle(e,n,t),color:this._kanbanLaneColor(e,n,t)})}),r}_kanbanGroupKeys(e,t){let n=t=>{var n;let r=t==null?``:String(t);return!r||!this._isColorfulKanbanGroupField(e)?r:((n=$(e,r))==null?void 0:n.id)??r};if(Array.isArray(t)){let e=t.map(n).filter(e=>e!==``);return e.length?e:[``]}return[n(t)]}_kanbanLaneTitle(e,t,n){if(!t)return`Uncategorized`;let r=$(e,t);return(r==null?void 0:r.name)??t}_kanbanLaneColor(e,t,n){var r;if(this._isColorfulKanbanGroupField(e))return(r=$(e,t))==null?void 0:r.color}_buildCalendar(e,t){let n=this._normalizeCalendarConfig(e,t.config??{}),i=e.fields[n.startDateFieldId];if(!i||i.type!==r.Date||i.readonly===!0||i.system===!0||!this._capabilities(i).usableAsCalendarDate)return{type:`invalid`,viewType:c.Calendar,reason:`invalidDateField`,fieldId:n.startDateFieldId};let a=n.endDateFieldId?e.fields[n.endDateFieldId]:void 0,o=this._projectRows(e,t);return{type:c.Calendar,config:n,fields:this._projectFields(e,t),rows:o,groups:this._projectGroups(e,t,o),events:o.flatMap(t=>{let r=V(t.values[n.startDateFieldId]);if(!Number.isFinite(r))return[];let o=t.values[n.startDateFieldId],s=n.endDateFieldId==null?void 0:t.values[n.endDateFieldId],c=n.endDateFieldId==null?void 0:V(s),l=Number.isFinite(c)?c:void 0;return[{recordId:t.recordId,title:this._title(e,t,n.titleFieldId),start:r,end:l,color:this._calendarEventColor(e,t,n),startMs:r,endMs:l,allDay:this._isAllDayCalendarEvent(i,a,o,s),fieldValues:t.values}]})}}_normalizeCalendarConfig(e,t){let n=this._resolveCalendarDateFieldId(e,t.startDateFieldId),i=t.endDateFieldId&&this._isCalendarDateField(e,t.endDateFieldId)?t.endDateFieldId:this._findCalendarDateFieldId(e,n)??void 0,a=t.titleFieldId?e.fields[t.titleFieldId]:void 0,o=a&&a.system!==!0&&a.type!==r.RecordId?t.titleFieldId:e.primaryFieldId,s=t.mode===`day`||t.mode===`week`?t.mode:`month`,c=t.timeslotSize===`short`||t.timeslotSize===`long`?t.timeslotSize:`medium`,l=typeof t.timeZone==`string`&&t.timeZone.trim()?t.timeZone:`local`,u=this._normalizeCalendarDisplayColor(e,t);return{...t,startDateFieldId:n,endDateFieldId:i,titleFieldId:o,mode:s,timeslotSize:c,timeZone:l,displayColor:u,fieldSettings:Object.fromEntries(Object.entries(t.fieldSettings??{}).filter(([t])=>{let n=e.fields[t];return!!(n&&n.system!==!0&&n.type!==r.RecordId)}))}}_resolveCalendarDateFieldId(e,t){return t&&this._isCalendarDateField(e,t)?t:this._findCalendarDateFieldId(e)??t??``}_findCalendarDateFieldId(e,t){for(let n of e.fieldOrder)if(n!==t&&this._isCalendarDateField(e,n))return n;return null}_isCalendarDateField(e,t){let n=e.fields[t];return!!n&&n.type===r.Date&&n.readonly!==!0&&n.system!==!0&&this._capabilities(n).usableAsCalendarDate}_normalizeCalendarDisplayColor(e,t){let n=t.displayColor;if((n==null?void 0:n.type)===`selectField`){let t=e.fields[n.fieldId];if(t&&t.type===r.SingleSelect)return n}if((n==null?void 0:n.type)===`custom`&&typeof n.color==`string`&&n.color.trim())return{type:`custom`,color:n.color};if(t.colorFieldId){let n=e.fields[t.colorFieldId];if(n&&n.type===r.SingleSelect)return{type:`selectField`,fieldId:t.colorFieldId}}return{type:`custom`,color:`#3b82f6`}}_calendarEventColor(e,t,n){let r=n.displayColor;if((r==null?void 0:r.type)===`selectField`){var i;let n=e.fields[r.fieldId];if(!n)return;let a=t.values[r.fieldId],o=Array.isArray(a)?a[0]:a;return o==null||(i=$(n,String(o)))==null?void 0:i.color}if((r==null?void 0:r.type)===`custom`)return r.color}_isAllDayCalendarEvent(e,t,n,r){var i,a;let o=((i=e.config)==null?void 0:i.includeTime)===!0,s=(t==null||(a=t.config)==null?void 0:a.includeTime)===!0;return!o&&!s}_isAllDayGanttDateRange(e,t){var n,r;let i=((n=e.config)==null?void 0:n.includeTime)===!0,a=((r=t.config)==null?void 0:r.includeTime)===!0;return!i&&!a}_buildGantt(e,t){let n=this._normalizeGanttConfig(e,t.config),i=e.fields[n.startDateFieldId];if(!i||i.type!==r.Date||i.readonly===!0||i.system===!0||!this._capabilities(i).usableAsGanttStart)return{type:`invalid`,viewType:c.Gantt,reason:`invalidGanttStartField`,fieldId:n.startDateFieldId};let a=e.fields[n.endDateFieldId];if(!a||a.type!==r.Date||a.readonly===!0||a.system===!0||!this._capabilities(a).usableAsGanttEnd)return{type:`invalid`,viewType:c.Gantt,reason:`invalidGanttEndField`,fieldId:n.endDateFieldId};let o=this._isAllDayGanttDateRange(i,a),s=w(e),l=s?this._projectHierarchyRows(e,t,s):void 0,u=l==null?void 0:l.hierarchy,d=(l==null?void 0:l.rows)??this._projectRows(e,t),f=n.dependencyFieldId,p=f&&le(e.id,e.fields[f])?f:void 0,m=e.fields[n.progressFieldId??``],h=(m==null?void 0:m.type)===r.Progress&&!m.system?{id:m.id,...mn(m.config),editable:!m.readonly}:void 0,g=d.flatMap(t=>{let r=V(t.values[n.startDateFieldId]),i=V(t.values[n.endDateFieldId]);if(!Number.isFinite(r)||!Number.isFinite(i))return[];let a=Math.min(r,i),o=Math.max(r,i),s=t.values[n.progressFieldId??``],c=s==null||s===``?void 0:Number(s),l=c!=null&&Number.isFinite(c)&&h&&h.start!==h.end?Math.max(0,Math.min(1,(c-h.start)/(h.end-h.start))):void 0;return[{recordId:t.recordId,title:this._title(e,t,n.titleFieldId),start:a,end:o,color:this._ganttBarColor(e,t,n),progress:Number.isFinite(c)?c:void 0,completion:l,workingDayCount:n.workingDaysOnly?Un(a,o,n.workingDays):void 0,dependencyRecordIds:p?S(t.values[p]):void 0}]}),_=n.showPlanComparison===!0?this._buildGanttPlan(e,d,n):void 0,v=1/0,y=-1/0;for(let e of[g,(_==null?void 0:_.bars)??[]])for(let t of e)v=Math.min(v,t.start),y=Math.max(y,t.end);let ee=Date.now(),te=Z((Number.isFinite(v)?v:ee)-90*J),ne=Z((Number.isFinite(y)?y:ee)+91*J),b=Pn(n.scale,te,ne,n.workingDaysOnly?n.workingDays:void 0);return{type:c.Gantt,fields:this._projectFields(e,{...t,config:n}),rows:d,groups:u?this._projectHierarchyGroups(e,t,d,u):this._projectGroups(e,t,d),...u?{hierarchy:u}:{},config:{...n,dependencyFieldId:p},...h?{progressField:h}:{},dateRangeAllDay:o,timeline:{scale:n.scale,start:te,end:ne,unitWidth:b.unitWidth,majorHeaders:b.majorHeaders,columns:b.columns},bars:g,..._?{plan:_}:{}}}_buildGanttPlan(e,t,n){let{planStartDateFieldId:r,planEndDateFieldId:i}=n,a={bars:[],needsDateFields:!0,invalidRecordIds:[]};if(!r||!i||!this._isGanttDateField(e,r,`start`)||!this._isGanttDateField(e,i,`end`))return a;a.needsDateFields=!1;for(let o of t){let t=V(o.values[r]),s=V(o.values[i]);t!=null&&s!=null&&Number.isFinite(t)&&Number.isFinite(s)&&(t>s?a.invalidRecordIds.push(o.recordId):a.bars.push({recordId:o.recordId,title:this._title(e,o,n.titleFieldId),start:t,end:s}))}return a}_normalizeGanttConfig(e,t){let n=this._resolveGanttDateFieldId(e,t.startDateFieldId,`start`),i=this._resolveGanttDateFieldId(e,t.endDateFieldId,`end`)||n,a=t.titleFieldId?e.fields[t.titleFieldId]:void 0,o=a&&a.system!==!0&&a.type!==r.RecordId?t.titleFieldId:e.primaryFieldId,s=t.scale===`week`||t.scale===`quarter`||t.scale===`year`?t.scale:`month`,c=X(t.workingDays);return{...t,startDateFieldId:n,endDateFieldId:i,titleFieldId:o,scale:s,leftPaneWidth:typeof t.leftPaneWidth==`number`?t.leftPaneWidth:void 0,leftPaneCollapsed:t.leftPaneCollapsed===!0,showTodayLine:t.showTodayLine!==!1,displayColor:this._normalizeGanttDisplayColor(e,t),fieldSettings:Object.fromEntries(Object.entries(t.fieldSettings??{}).filter(([t])=>{let n=e.fields[t];return!!(n&&n.system!==!0&&n.type!==r.RecordId)})),workingDaysOnly:t.workingDaysOnly===!0,workingDays:c}}_resolveGanttDateFieldId(e,t,n){if(t&&this._isGanttDateField(e,t,n)||t)return t;for(let t of e.fieldOrder)if(this._isGanttDateField(e,t,n))return t;return t??``}_isGanttDateField(e,t,n){let i=e.fields[t];if(!i||i.type!==r.Date||i.readonly===!0||i.system===!0)return!1;let a=this._capabilities(i);return n===`start`?a.usableAsGanttStart:a.usableAsGanttEnd}_normalizeGanttDisplayColor(e,t){let n=t.displayColor;if((n==null?void 0:n.type)===`selectField`){let t=e.fields[n.fieldId];if(t&&t.type===r.SingleSelect)return n}return(n==null?void 0:n.type)===`conditional`&&Array.isArray(n.rules)?{type:`conditional`,rules:n.rules.filter(t=>!!e.fields[t.fieldId])}:(n==null?void 0:n.type)===`custom`&&typeof n.color==`string`&&n.color.trim()?{type:`custom`,color:n.color}:{type:`custom`,color:`#14b8a6`}}_ganttBarColor(e,t,n){let r=n.displayColor;if((r==null?void 0:r.type)===`conditional`){let n=r.rules.find(n=>this._matchesGanttColorRule(e,t,n));if(n)return n.color}if((r==null?void 0:r.type)===`selectField`){let n=e.fields[r.fieldId];if(n){var i;let e=t.values[r.fieldId],a=Array.isArray(e)?e[0]:e,o=a==null||(i=$(n,String(a)))==null?void 0:i.color;if(o)return o}}return(r==null?void 0:r.type)===`custom`?r.color:`#14b8a6`}_matchesGanttColorRule(e,t,n){let r=e.fields[n.fieldId];return r?kt(t.values[r.id],n.operator,n.operand,r,{dateMode:n.dateMode}):!1}_buildGallery(e,t){let n=this._projectRows(e,t),r=this._normalizeGalleryConfig(e,t.config??{}),i=this._projectFields(e,t);return{type:c.Gallery,fields:i,rows:n,groups:this._projectGroups(e,t,n),titleFieldId:r.card.titleFieldId,coverFieldId:r.coverFieldId,cardLayout:r.cardLayout??`normal`,showFieldNames:r.showFieldNames!==!1,visibleCardFieldIds:this._resolveGalleryCardFieldIds(e,t,r),cardSize:r.cardSize??`medium`,cards:n.map(t=>({recordId:t.recordId,title:this._title(e,t,r.card.titleFieldId),values:t.values}))}}_normalizeGalleryConfig(e,t){let n=t.card??{fieldIds:[]},i=this._resolveCardTitleFieldId(e,n.titleFieldId),a=this._resolveGalleryCoverFieldId(e,t),o=t.cardSize===`small`||t.cardSize===`large`?t.cardSize:`medium`;return{...t,coverFieldId:a,cardLayout:t.cardLayout===`compose`?`compose`:`normal`,showFieldNames:t.showFieldNames!==!1,fieldSettings:Object.fromEntries(Object.entries(t.fieldSettings??{}).filter(([t])=>{let n=e.fields[t];return!!(n&&n.system!==!0&&n.type!==r.RecordId)})),card:{...n,titleFieldId:i,coverFieldId:a,fieldIds:Array.isArray(n.fieldIds)?n.fieldIds:[]},cardSize:o}}_resolveCardTitleFieldId(e,t){let n=t?e.fields[t]:void 0;return n&&n.system!==!0&&n.type!==r.RecordId?n.id:vn(e)}_resolveGalleryCoverFieldId(e,t){var n;let r=t.coverFieldId??((n=t.card)==null?void 0:n.coverFieldId)??null;if(!r)return null;let i=e.fields[r];return i&&this._capabilities(i).usableAsCardCover?i.id:null}_resolveGalleryCardFieldIds(e,t,n){var i,a,o;let s=n.fieldSettings??{},c=((i=n.card)==null?void 0:i.titleFieldId)??vn(e),l=n.coverFieldId??((a=n.card)==null?void 0:a.coverFieldId)??null,u=(o=n.card)!=null&&(o=o.fieldIds)!=null&&o.length?n.card.fieldIds:q(e,[c,l,e.primaryFieldId]);return u.filter(n=>{var i,a;let o=e.fields[n];return!(!o||o.system===!0||o.type===r.RecordId||o.id===c||o.id===l||(i=t.fieldSettings)!=null&&(i=i[n])!=null&&i.hidden||(a=s[n])!=null&&a.hidden)}).sort((e,t)=>{var n,r;return(((n=s[e])==null?void 0:n.order)??u.indexOf(e))-(((r=s[t])==null?void 0:r.order)??u.indexOf(t))})}_projectFields(e,t){var n;return((n=t.fieldOrder)!=null&&n.length?t.fieldOrder:e.fieldOrder).flatMap(n=>{var i;let a=e.fields[n],o=((i=t.fieldSettings)==null?void 0:i[n])??{};return!a||a.system===!0||a.type===r.RecordId||o.hidden?[]:[{id:a.id,name:a.name,description:a.description,type:a.type,config:a.config,width:o.width,setting:o}]})}_projectRows(e,t){var n;return O(`BaseProjection.projectRows`,()=>{var n,r;let i=this._projectTableRows(e),a=this._viewRowsCacheKey(e.id,t),o=this._getCellRevision(e.id),s=this._projectedViewRowsCache.get(a);if(s&&s.globalRevision===this._globalRevision&&s.tableRevision===this._getTableRevision(e.id)){if(s.cellRevision===o&&s.baseRows===i)return s.rows;if(s.cellRevision!==o&&!this._cellInvalidationsTouchFields(e.id,s.cellRevision,o,this._filterSortFieldIds(t))){let e=s.rows===s.baseRows?i:this._patchCachedProjectedRows(s.rows,i);if(e)return this._projectedViewRowsCache.set(a,{...s,rows:e,baseRows:i,cellRevision:o}),e}}let c=O(`BaseProjection.filterAndSortRows`,()=>this._sortRows(e,t,this._filterRows(e,t,i)),{tableId:e.id,viewId:t==null?void 0:t.id,viewType:t==null?void 0:t.type,rows:i.length,filters:(t==null||(n=t.filter)==null?void 0:n.conditions.length)??0,sorts:(t==null||(r=t.sort)==null?void 0:r.length)??0});return this._projectedViewRowsCache.set(a,{table:e,rows:c,baseRows:i,globalRevision:this._globalRevision,tableRevision:this._getTableRevision(e.id),cellRevision:o}),c},{tableId:e.id,viewId:t==null?void 0:t.id,viewType:t==null?void 0:t.type,records:((n=e.recordOrder)==null?void 0:n.length)??Object.keys(e.records??{}).length})}_projectTableRows(e){var t;return O(`BaseProjection.projectTableRows`,()=>{var t;let n=this._getCellRevision(e.id),r=this._projectedRowsCache.get(e.id);if(r&&r.globalRevision===this._globalRevision&&r.tableRevision===this._getTableRevision(e.id)){if(r.cellRevision===n&&jn(r.table,e))return r.table=e,r.rows;let t=this._patchProjectedRowsForCellInvalidations(e,r,n);if(t)return t}kn(e)||k(e);let i=(t=e.recordOrder)!=null&&t.length?e.recordOrder:Nn(e.records),a=O(`BaseProjection.materializeTableRows`,()=>{let t=[];for(let n of i){let r=e.records[n];if(!r)continue;let i={};for(let t of e.fieldOrder)i[t]=A(e,r.id,t);t.push({recordId:r.id,values:i})}return t},{tableId:e.id,records:i.length,fields:e.fieldOrder.length});return this._projectedRowsCache.set(e.id,{table:e,rows:a,rowIndexById:On(a),globalRevision:this._globalRevision,tableRevision:this._getTableRevision(e.id),cellRevision:n}),a},{tableId:e.id,records:((t=e.recordOrder)==null?void 0:t.length)??Object.keys(e.records??{}).length,fields:e.fieldOrder.length})}_patchProjectedRowsForCellInvalidations(e,t,n){let r=(this._cellInvalidations.get(e.id)??[]).filter(e=>e.revision>t.cellRevision&&e.revision<=n);if(!r.length)return t.table===e?t.rows:null;let i=t.rows,a=/* @__PURE__ */ new Map;for(let e of r){let t=a.get(e.recordId);t||(t=/* @__PURE__ */ new Set,a.set(e.recordId,t)),t.add(e.fieldId)}for(let[n,r]of a){if(!e.records[n])return null;let a=t.rowIndexById.get(n);if(a==null)return null;i===t.rows&&(i=[...t.rows]);let o=i[a],s={...o.values};r.forEach(t=>{s[t]=A(e,n,t)}),i[a]={...o,values:s}}let o={table:e,rows:i,rowIndexById:t.rowIndexById,globalRevision:this._globalRevision,tableRevision:this._getTableRevision(e.id),cellRevision:n};return this._projectedRowsCache.set(e.id,o),this._cellInvalidations.set(e.id,(this._cellInvalidations.get(e.id)??[]).filter(e=>e.revision>Math.max(0,n-256))),i}_patchCachedProjectedRows(e,t){let n=new Map(t.map(e=>[e.recordId,e])),r=!1,i=e.map(e=>{let t=n.get(e.recordId);return t?t===e?e:(r=!0,t):e});return r?i:e}_cellInvalidationsTouchFields(e,t,n,r){return!r.size||t===n?!1:n-t>256||(this._cellInvalidations.get(e)??[]).some(e=>e.revision>t&&e.revision<=n&&r.has(e.fieldId))}_filterSortFieldIds(e){var t,n;let r=/* @__PURE__ */ new Set;return e==null||(t=e.filter)==null||t.conditions.forEach(e=>r.add(e.fieldId)),e==null||(n=e.sort)==null||n.forEach(e=>r.add(e.fieldId)),r}_groupProjectionFieldIds(e){var t;let n=this._filterSortFieldIds(e);return(t=e.group)==null||t.forEach(e=>n.add(e.fieldId)),n}_filterRows(e,t,n){let r=t==null?void 0:t.filter;if(!(r!=null&&r.conditions.length))return n;let a=r.conditions.filter(e=>!$n(e));return a.length?n.filter(t=>{if(r.conjunction===i.OR){for(let n of a){let r=e.fields[n.fieldId];if(!r||this._fieldRegistry.get(r.type).filter(t.values[r.id],n.operator,n.operand,r))return!0}return!1}for(let n of a){let r=e.fields[n.fieldId];if(r&&!this._fieldRegistry.get(r.type).filter(t.values[r.id],n.operator,n.operand,r))return!1}return!0}):n}_sortRows(e,t,n){let r=(t==null?void 0:t.sort)??[];if(!r.length)return n;let i=r.flatMap(t=>{let n=e.fields[t.fieldId];return n?[{...t,field:n}]:[]});return i.length?this._canUseFastSort(i)?this._fastSortRows(i,n):[...n].sort((e,t)=>{for(let n of i){let r=n.field,i=this._fieldRegistry.get(r.type).compare(e.values[r.id],t.values[r.id],r);if(i!==0)return n.direction===s.DESC?-i:i}return 0}):n}_canUseFastSort(e){return e.every(e=>Tn.has(e.field.type))}_fastSortRows(e,t){return t.map((t,n)=>({row:t,index:n,keys:e.map(e=>t.values[e.fieldId])})).sort((t,n)=>{for(let r=0;r<e.length;r++){let i=Qn(t.keys[r],n.keys[r]);if(i!==0)return e[r].direction===s.DESC?-i:i}return t.index-n.index}).map(e=>e.row)}_projectGroups(e,t,n){var r;return O(`BaseProjection.projectGroups`,()=>{var r;if(!((r=t.group)!=null&&r.length))return[];let i=t.group.filter(t=>e.fields[t.fieldId]);if(!i.length)return[];let a=this._groupsCacheKey(e.id,t,i),o=this._getCellRevision(e.id),s=this._projectedGroupsCache.get(a);if(s&&s.globalRevision===this._globalRevision&&s.tableRevision===this._getTableRevision(e.id)){if(s.cellRevision===o&&s.rows===n)return s.groups;if(s.cellRevision!==o&&!this._cellInvalidationsTouchFields(e.id,s.cellRevision,o,this._groupProjectionFieldIds(t)))return this._projectedGroupsCache.set(a,{...s,rows:n,cellRevision:o}),s.groups}let c=/* @__PURE__ */ new Map;for(let e of n){let t=c,n=``;for(let r=0;r<i.length;r++){let a=i[r],o=e.values[a.fieldId],s=Dn(o),c=`${a.fieldId}\u0000${s}`,l=`${n}/${a.fieldId}:${s}`,u=t.get(c);u||(u={key:s,value:o,path:l,label:s||`Empty`,fieldId:a.fieldId,level:r,recordIds:[],children:/* @__PURE__ */ new Map},t.set(c,u)),u.recordIds.push(e.recordId),t=u.children,n=l}}let l=this._materializeGroups(i,c,0);return this._projectedGroupsCache.set(a,{table:e,rows:n,groups:l,globalRevision:this._globalRevision,tableRevision:this._getTableRevision(e.id),cellRevision:o}),l},{tableId:e.id,viewId:t.id,viewType:t.type,rows:n.length,groupFields:((r=t.group)==null?void 0:r.length)??0})}_materializeGroups(e,t,n){var r;let i=Array.from(t.values()),a=(r=e[n])==null?void 0:r.direction;return a&&i.sort((e,t)=>{let n=e.key.localeCompare(t.key);return a===s.DESC?-n:n}),i.map(t=>({key:t.key,value:t.value,path:t.path,label:t.label,fieldId:t.fieldId,level:t.level,recordIds:t.recordIds,children:this._materializeGroups(e,t.children,n+1)}))}_title(e,t,n){let r=n??e.primaryFieldId,i=t.values[r];return i==null?``:String(i)}_capabilities(e){return this._fieldRegistry.get(e.type).getCapabilities(e)}};En=pn([fn(0,m(un))],En);function Dn(e){return e==null?``:String(e)}function On(e){return new Map(e.map((e,t)=>[e.recordId,t]))}function kn(e){return!!(Array.isArray(e.recordOrder)&&e.rowIndex&&e.rowId&&e.colIndex&&e.colId&&e.cellData)}function An(e){let t=(e==null?void 0:e.conditions.filter(e=>!$n(e)))??[];return!e||!t.length?null:{conjunction:e.conjunction,conditions:t.map(e=>({fieldId:e.fieldId,operator:e.operator,operand:e.operand}))}}function jn(e,t){return e.records===t.records&&e.recordOrder===t.recordOrder&&e.fields===t.fields&&e.fieldOrder===t.fieldOrder&&e.cellData===t.cellData&&e.rowIndex===t.rowIndex&&e.rowId===t.rowId&&e.colIndex===t.colIndex&&e.colId===t.colId}function Mn(e){return e!=null&&e.length?e.map(e=>({fieldId:e.fieldId,direction:e.direction})):null}function Y(e){if(typeof e!=`object`||!e)return JSON.stringify(e)??`undefined`;if(Array.isArray(e))return`[${e.map(Y).join(`,`)}]`;let t=e;return`{${Object.keys(t).sort().map(e=>`${JSON.stringify(e)}:${Y(t[e])}`).join(`,`)}}`}function Nn(e){let t=Object.values(e).sort((e,t)=>e.orderKey.localeCompare(t.orderKey)),n=[];for(let e of t)n.push(e.id);return n}function X(e){return{weekdays:Array.isArray(e==null?void 0:e.weekdays)&&e.weekdays.length?[...new Set(e.weekdays.filter(e=>Number.isInteger(e)&&e>=1&&e<=7))]:[1,2,3,4,5],exceptions:Array.isArray(e==null?void 0:e.exceptions)?e.exceptions.flatMap(e=>!e||!Number.isFinite(e.date)?[]:[{id:String(e.id||`exception-${e.date}`),date:Z(Number(e.date)),name:String(e.name||`Working day`),type:e.type===`working`?`working`:`off`}]):[]}}function Pn(e,t,n,r){let i=Rn(e,t),a=zn(e,n),o=Fn(e,i,a,r);return{scale:e,start:i,end:a,unitWidth:Ln(e),majorHeaders:In(e,i,a),columns:o}}function Fn(e,t,n,r){let i=[],a=t;for(;a<n;){let t=e===`quarter`?Q(a,7):e===`year`?Yn(a,1):Q(a,1);i.push({id:`${e}-${a}`,label:Bn(e,a,t),majorLabel:Vn(e,a),start:a,end:t,nonWorking:Wn(a,t,r)}),a=t}return i}function In(e,t,n){let r=[],i=e===`year`?Jn(t):qn(t);for(;i<n;){let t=e===`year`?Xn(i,1):Yn(i,1);r.push({id:`major-${i}`,label:e===`year`?String(new Date(i).getUTCFullYear()):Zn(i),start:i,end:t}),i=t}return r}function Ln(e){switch(e){case`week`:return 172;case`quarter`:return 172;case`year`:return 136;default:return 86}}function Rn(e,t){return e===`year`?Jn(t):e===`quarter`?Kn(t):Z(t)}function zn(e,t){return e===`year`?Xn(Jn(t),1):e===`quarter`?Q(Kn(t),7):Q(Z(t),1)}function Bn(e,t,n){let r=new Date(t);return e===`quarter`?`${r.getUTCDate()}-${(/* @__PURE__ */ new Date(n-J)).getUTCDate()}`:e===`year`?r.toLocaleString(`en-US`,{month:`short`,timeZone:`UTC`}):String(r.getUTCDate())}function Vn(e,t){return e===`year`?String(new Date(t).getUTCFullYear()):Zn(t)}function Hn(e,t,n){let r=Z(e),i=Z(t);if(r===i||!Number.isFinite(r)||!Number.isFinite(i))return 0;let a=Math.min(r,i),o=Math.max(r,i),s=(o-a)/J,c=X(n),l=e=>{let t=new Date(e).getUTCDay();return c.weekdays.some(e=>e%7===t)},u=Math.floor(s/7)*c.weekdays.length;for(let e=1;e<=s%7;e++)u+=Number(l(Q(a,e)));let d=/* @__PURE__ */ new Set;for(let e of c.exceptions)e.date>a&&e.date<=o&&!d.has(e.date)&&(d.add(e.date),u+=Number(e.type===`working`)-Number(l(e.date)));return i<r&&u!==0?-u:u}function Un(e,t,n){let r=X(n),i=0;for(let n=Z(e);n<=Z(t);n=Q(n,1))Gn(n,r)||i++;return i}function Wn(e,t,n){if(!n)return!1;let r=X(n);for(let n=Z(e);n<t;n=Q(n,1))if(!Gn(n,r))return!1;return!0}function Gn(e,t){let n=Z(e),r=t.exceptions.find(e=>Z(e.date)===n);if(r)return r.type===`off`;let i=new Date(n).getUTCDay(),a=i===0?7:i;return!t.weekdays.includes(a)}function Z(e){let t=new Date(e);return Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate())}function Kn(e){let t=Z(e),n=new Date(t).getUTCDay();return Q(t,-(n===0?6:n-1))}function qn(e){let t=new Date(e);return Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),1)}function Jn(e){let t=new Date(e);return Date.UTC(t.getUTCFullYear(),0,1)}function Q(e,t){return e+t*J}function Yn(e,t){let n=new Date(e);return Date.UTC(n.getUTCFullYear(),n.getUTCMonth()+t,1)}function Xn(e,t){let n=new Date(e);return Date.UTC(n.getUTCFullYear()+t,0,1)}function Zn(e){let t=new Date(e);return`${t.toLocaleString(`en-US`,{month:`short`,timeZone:`UTC`})} ${t.getUTCFullYear()}`}function Qn(e,t){if(e==null&&t==null)return 0;if(e==null)return-1;if(t==null)return 1;if(typeof e==`boolean`||typeof t==`boolean`)return Number(e===!0)-Number(t===!0);let n=Number(e),r=Number(t),i=Number.isFinite(n),a=Number.isFinite(r);return i&&a?n-r:i?1:a?-1:String(e).localeCompare(String(t))}function $n(e){if(e.operator!==`is`&&e.operator!==`isNot`)return!1;let t=e.operand;return t==null?!0:typeof t==`string`?t.trim()===``:Array.isArray(t)?t.length===0:!1}function $(e,t){var n;let r=Array.isArray((n=e.config)==null?void 0:n.options)?e.config.options:[];for(let e of r){if(e==null)continue;if(typeof e==`string`){if(e===t)return{id:e,name:e};continue}let n=e,r=String(n.id??n.name??``),i=String(n.name??n.id??r);if(r===t||i===t)return{id:r,name:i,color:n.color==null?void 0:String(n.color)}}return null}let er=/* @__PURE__ */ function(e){return e.CreateView=`create-view`,e.DeleteView=`delete-view`,e}({});const tr={id:`base.mutation.apply-base-json1`,type:u.MUTATION,handler(e,t){let{unitId:n,op:r,ganttPredecessorAddition:i}=t,a=e.get(p).getUnit(n,_.UNIVER_BASE);if(!a)return!1;if(!r)return!0;let o=a.getSnapshot(),s=new Ze,c=s.getAffectedRanges(r),l=s.applyOp(o,r);if(i){var u,d,f;let{tableId:e,fieldId:t,predecessorId:n,successorId:r}=i,a=(u=l.tables[e])==null?void 0:u.records;if(S(a==null||(d=a[r])==null?void 0:d.values[t]).includes(n)&&!S((f=o.tables[e])==null||(f=f.records[r])==null?void 0:f.values[t]).includes(n)&&ce(n,r,e=>{var n;return a==null||(n=a[e])==null?void 0:n.values[t]}))return!1}return a.setSnapshot(l),nr(l,c,e.get(wn)),!0}};function nr(e,t,n){let r=/* @__PURE__ */ new Set,i=/* @__PURE__ */ new Set,a=/* @__PURE__ */ new Set;for(let o of t){if(o.reason===`view`&&o.tableId&&o.viewId){let e=`${o.tableId}\u0000${o.viewId}`;a.has(e)||(a.add(e),n.invalidateByView(o.tableId,o.viewId));continue}if(o.reason===`field`&&o.tableId&&o.fieldId){let e=`${o.tableId}\u0000${o.fieldId}`;i.has(e)||(i.add(e),n.invalidateByField(o.tableId,o.fieldId));continue}if(o.reason!==`cell`){n.invalidateByOp();return}let t=rr(e,o);if(!t){n.invalidateByOp();return}let s=`${t.tableId}\u0000${t.recordId}\u0000${t.fieldId}`;r.has(s)||(r.add(s),n.invalidateByCell(t.tableId,t.recordId,t.fieldId))}}function rr(e,t){var n,r;if(!t.tableId)return null;if(t.recordId&&t.fieldId)return{tableId:t.tableId,recordId:t.recordId,fieldId:t.fieldId};if(t.row==null||t.column==null)return null;let i=e.tables[t.tableId],a=i==null||(n=i.rowId)==null?void 0:n[t.row],o=i==null||(r=i.colId)==null?void 0:r[t.column];return!a||!o?null:{tableId:t.tableId,recordId:a,fieldId:o}}var ir=`@univerjs-pro/bases`,ar=`1.6.1`;const or=`bases.config`,sr={},cr=`bases.remote.config`,lr={};export{xe as $,bt as A,Re as B,Dt as C,St as D,z as E,Ie as F,me as G,O as H,Le as I,D as J,pe as K,Fe as L,Xe as M,k as N,xt as O,Ve as P,w as Q,A as R,Et as S,V as T,ue as U,Be as V,de as W,E as X,he as Y,ye as Z,fn as _,ir as a,ge as at,K as b,er as c,se as ct,Hn as d,re as dt,C as et,yn as f,ie as ft,pn as g,gn as h,lr as i,_e as it,Ze as j,B as k,En as l,x as lt,mn as m,oe as mt,cr as n,T as nt,ar as o,ce as ot,hn as p,ae as pt,fe as q,sr as r,Se as rt,tr as s,le as st,or as t,be as tt,wn as u,S as ut,dn as v,kt as w,Kt as x,un as y,N as z};
2
+ `);if(e&&typeof e==`object`){let t=e;return String(t.name??t.label??t.text??t.value??t.id??``).trim().toLowerCase()}return String(e??``).trim().toLowerCase()}function Wt(e,t){let n=U(e),r=Gt(t.config??{});return n.flatMap(e=>r.get(e)??[e]).filter((e,t,n)=>e!==``&&n.indexOf(e)===t)}function U(e){if(e==null||e===``)return[];if(Array.isArray(e))return e.flatMap(e=>U(e));if(e&&typeof e==`object`){let t=e;return[`id`,`name`,`label`,`value`,`text`].flatMap(e=>U(t[e])).filter((e,t,n)=>n.indexOf(e)===t)}return[Ut(e)]}function Gt(e){let t=/* @__PURE__ */ new Map;return(Array.isArray(e.options)?e.options:[]).forEach(e=>{if(!e||typeof e!=`object`)return;let n=U(e),r=n.filter((e,t)=>e!==``&&n.indexOf(e)===t);r.forEach(e=>t.set(e,r))}),t}function W(e,t={},n=e=>e,r={}){let i=!Tt.has(e),a=n??(e=>e);return{type:e,i18nKey:`base.fieldType.${e}`,enabled:i,visibleInCreateMenu:i,createDefaultConfig:r.createDefaultConfig??(()=>({})),createDefaultValue:r.createDefaultValue??(e=>e.defaultValue??null),normalize:(e,t)=>a(e,t),validate:(e,t)=>{var n;return i?((n=r.validate)==null?void 0:n.call(r,e,t))??{valid:!0}:{valid:!1}},compare:(e,t)=>Ot(e,t),filter:(e,t,n,r)=>kt(e,t,n,r),toPlainText:r.toPlainText??(e=>e==null?``:String(e)),fromPlainText:r.fromPlainText??(t=>a(t,{id:``,name:``,type:e,config:{}})),getCapabilities:()=>({...wt,...t,editable:i&&(t.editable??wt.editable)})}}function Kt(){return[W(r.Text,{groupable:!0,usableAsTitle:!0},void 0,{createDefaultConfig:()=>({placeholder:`bases.fieldConfig.textPlaceholder`}),createDefaultValue:e=>e.defaultValue??``}),W(r.SingleSelect,{groupable:!0,usableAsKanbanGroup:!0,supportsOptions:!0},e=>e==null||e===``?null:String(e),{createDefaultConfig:()=>({options:[],optionSource:{type:`manual`}})}),W(r.MultiSelect,{filterable:!0,usableAsKanbanGroup:!0,supportsOptions:!0,supportsMultipleValues:!0},e=>Array.isArray(e)?e.map(String):e==null?[]:[String(e)],{createDefaultConfig:()=>({options:[],optionSource:{type:`manual`}}),createDefaultValue:e=>e.defaultValue??[]}),W(r.Person,{groupable:!0,usableAsKanbanGroup:!0,supportsMultipleValues:!0},Zt,{createDefaultConfig:()=>({allowMultiple:!1,provider:`person`}),validate:Qt}),W(r.Group,{groupable:!0,usableAsKanbanGroup:!0,supportsMultipleValues:!0},Yt,{createDefaultConfig:()=>({allowMultiple:!0,provider:`group`}),createDefaultValue:e=>e.defaultValue??[],validate:$t}),W(r.Date,{groupable:!0,usableAsCalendarDate:!0,usableAsGanttStart:!0,usableAsGanttEnd:!0},e=>B(e),{createDefaultConfig:()=>Jt(),validate:en}),W(r.Attachment,{usableAsCardCover:!0,supportsMultipleValues:!0},e=>e==null?[]:Array.isArray(e)?e:[e],{createDefaultValue:e=>e.defaultValue??[]}),W(r.Number,{},e=>e==null||e===``?null:Number(e),{createDefaultConfig:()=>qt(),validate:tn}),W(r.Checkbox,{groupable:!0,usableAsKanbanGroup:!0},e=>e===!0||e===`true`||e===1||e===`1`,{createDefaultConfig:()=>({icon:`check`,color:`#16a34a`}),createDefaultValue:e=>e.defaultValue??!1,validate:e=>typeof e==`boolean`?{valid:!0}:{valid:!1,reason:`[BaseField]: invalid checkbox value.`}}),W(r.Link,{supportsRelation:!0},rn,{createDefaultConfig:()=>({placeholder:`bases.fieldConfig.linkPlaceholder`}),toPlainText:e=>an(e),fromPlainText:e=>rn(e)}),W(r.Formula,{editable:!1},void 0,{createDefaultConfig:()=>({formula:``,dependencies:[],numfmt:{type:`general`,pattern:`General`}}),createDefaultValue:()=>null}),W(r.Numbering,{editable:!1,usableAsTitle:!0},void 0,{createDefaultConfig:()=>({mode:`autoIncrement`}),createDefaultValue:()=>null}),W(r.Phone,{usableAsTitle:!0},e=>e==null?null:String(e).trim(),{validate:e=>e==null||e===``||/^\+?[0-9 ()-]{6,20}$/.test(String(e))?{valid:!0}:{valid:!1,reason:`[BaseField]: invalid phone value.`}}),W(r.Email,{usableAsTitle:!0},e=>e==null?null:String(e).trim(),{validate:e=>e==null||e===``||sn(String(e))?{valid:!0}:{valid:!1,reason:`[BaseField]: invalid email value.`}}),W(r.Progress,{usableAsGanttProgress:!0},e=>e==null||e===``?null:Number(e),{createDefaultConfig:()=>({format:`percent`,decimalPlaces:0,color:`blue`,customRange:!1,start:0,end:100}),validate:(e,t)=>nn(e,t,`[BaseField]: invalid progress value.`)}),W(r.Currency,{},e=>e==null||e===``?null:Number(e),{createDefaultConfig:()=>({...qt(),currencySymbol:`$`}),validate:tn}),W(r.Rating,{groupable:!0,usableAsKanbanGroup:!0},e=>e==null||e===``?null:Number(e),{createDefaultConfig:()=>({icon:`star`,min:1,max:5}),createDefaultValue:()=>null,validate:(e,t)=>nn(e,t,`[BaseField]: invalid rating value.`)}),W(r.RecordLink,{supportsRelation:!0,supportsMultipleValues:!0},Xt,{createDefaultConfig:()=>({targetTableId:``,multiple:!1}),createDefaultValue:()=>``,validate:(e,t)=>ie(e,t.config.multiple===!0)}),W(r.RecordId,{editable:!1,sortable:!0,filterable:!0,usableAsTitle:!0}),W(r.CreatedBy,{editable:!1,groupable:!0},e=>e==null?null:String(e),{createDefaultConfig:()=>({provider:`user`}),createDefaultValue:()=>null}),W(r.UpdatedBy,{editable:!1,groupable:!0},e=>e==null?null:String(e),{createDefaultConfig:()=>({provider:`user`}),createDefaultValue:()=>null}),W(r.CreatedAt,{editable:!1,usableAsCalendarDate:!0,usableAsGanttStart:!0,usableAsGanttEnd:!0},e=>B(e),{createDefaultConfig:()=>Jt(),createDefaultValue:()=>null,validate:en}),W(r.UpdatedAt,{editable:!1,usableAsCalendarDate:!0,usableAsGanttStart:!0,usableAsGanttEnd:!0},e=>B(e),{createDefaultConfig:()=>Jt(),createDefaultValue:()=>null,validate:en})]}function qt(){return{pattern:`#,##0.00`,decimalPlaces:2,separatorStyle:`local`,useThousands:!0,abbreviation:`none`,allowNegative:!0}}function Jt(){return{locale:`en-US`,pattern:`yyyy/mm/dd`,includeTime:!1,hourCycle:`h24`,defaultMode:`none`}}function Yt(e){return e==null||e===``?[]:Array.isArray(e)?e.map(String):[String(e)]}function Xt(e){return typeof e==`string`?e:``}function Zt(e,t){return e==null||e===``?t.config.allowMultiple===!0?[]:null:t.config.allowMultiple===!0?Array.isArray(e)?e.map(String):[String(e)]:Array.isArray(e)?String(e[0]??``)||null:String(e)}function Qt(e,t){return t.config.allowMultiple===!0?$t(e):e==null||e===``||typeof e==`string`?{valid:!0}:{valid:!1,reason:`[BaseField]: invalid person value.`}}function $t(e){return e==null||Array.isArray(e)&&e.every(e=>typeof e==`string`)?{valid:!0}:{valid:!1,reason:`[BaseField]: invalid multi-value reference.`}}function en(e){return e==null||typeof e==`number`&&Number.isFinite(e)?{valid:!0}:{valid:!1,reason:`[BaseField]: invalid date value.`}}function tn(e,t){return e==null||e===``?{valid:!0}:typeof e!=`number`||!Number.isFinite(e)?{valid:!1,reason:`[BaseField]: invalid number value.`}:t.config.allowNegative===!1&&e<0?{valid:!1,reason:`[BaseField]: negative numbers are disabled.`}:{valid:!0}}function nn(e,t,n){let r=tn(e,t);if(!r.valid||e==null||e===``)return r;let i=Number(t.config.min??t.config.start??0),a=Number(t.config.max??t.config.end??100),o=Number(e);return o>=i&&o<=a?{valid:!0}:{valid:!1,reason:n}}function rn(e){if(e==null||e===``)return null;if(typeof e==`object`&&!Array.isArray(e)){let t=e,n=typeof t.text==`string`?t.text.trim():``,r=typeof t.url==`string`?t.url.trim():``,i=on(r||n);return i?{text:n||r||i,url:i}:null}let t=String(e).trim(),n=on(t);return n?{text:t,url:n}:null}function an(e){if(e==null)return``;if(typeof e==`object`&&!Array.isArray(e)){let t=e;return String(t.text||t.url||``)}return String(e)}function on(e){let t=e.trim();if(!t)return``;let n=/^[a-z][a-z\d+.-]*:/i.test(t)?t:t.startsWith(`//`)?`https:${t}`:`https://${t}`;try{let e=new URL(n);return e.protocol===`http:`||e.protocol===`https:`?e.href:``}catch{return``}}function sn(e){let t=e.indexOf(`@`);if(t<=0||t!==e.lastIndexOf(`@`))return!1;let n=e.slice(t+1);return n.includes(`.`)&&!e.includes(` `)&&!n.startsWith(`.`)&&!n.endsWith(`.`)}function G(e){"@babel/helpers - typeof";return G=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},G(e)}function cn(e,t){if(G(e)!=`object`||!e)return e;var n;if(typeof Symbol<`u`&&(n=e[Symbol.toPrimitive])!==void 0){var r=n.call(e,t||`default`);if(G(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function ln(e){var t=cn(e,`string`);return G(t)==`symbol`?t:t+``}function K(e,t,n){return(t=ln(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const un=v(`base.field-registry.service`);var dn=class extends f{constructor(...e){super(...e),K(this,`_plugins`,/* @__PURE__ */ new Map)}register(e){return this._plugins.set(e.type,e),b(()=>this._plugins.delete(e.type))}get(e){let t=this._plugins.get(e);if(!t)throw Error(`[BaseFieldRegistryService]: field type "${e}" is not registered.`);return t}getTypePlugin(e){return this._plugins.get(e)}getAll(){return Array.from(this._plugins.values())}};function fn(e,t){return function(n,r){t(n,r,e)}}function pn(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}function mn(e){let t=e&&typeof e==`object`?e:{},n=Number(t.start??0),r=Number(t.end??100);return t.customRange===!0?{start:Number.isFinite(n)?n:0,end:Number.isFinite(r)?r:100}:{start:0,end:100}}function hn(e,t){let n=t&&typeof t==`object`&&!Array.isArray(t)?t:{},r=e.toFixed(gn(n.decimalPlaces));return n.format===`number`?r:`${r}%`}function gn(e){if(e==null||e===``)return 0;let t=typeof e==`number`?e:Number(e);return Number.isFinite(t)?Math.max(0,Math.min(2,Math.round(t))):0}const _n=/* @__PURE__ */ new Set([r.Progress,r.Rating,r.Checkbox]);function vn(e){let t=e.fields[e.primaryFieldId];if((!t||t.system!==!0&&t.id.toLowerCase()!==`id`&&t.name.trim().toLowerCase()!==`id`)&&t)return t.id;for(let t of e.fieldOrder){let n=e.fields[t];if(n&&n.id!==e.primaryFieldId&&n.system!==!0&&n.type!==r.RecordId)return n.id}return e.primaryFieldId}function q(e,t=[],n=5){let i=new Set(t.filter(e=>!!e)),a=[],o=[];for(let t of e.fieldOrder){let n=e.fields[t];n&&n.system!==!0&&n.type!==r.RecordId&&!i.has(n.id)&&(_n.has(n.type)?a:o).push(n.id)}return[...a,...o].slice(0,n)}function yn(){return[{type:c.Grid,i18nKey:`base.viewType.grid`,createDefaultConfig:()=>({}),validateConfig:()=>({valid:!0}),buildProjection:()=>{throw Error(`Grid projection is implemented by BaseProjectionService.`)}},{type:c.Kanban,i18nKey:`base.viewType.kanban`,createDefaultConfig:e=>{let t=bn(e);return{groupFieldId:t,coverFieldId:null,cardLayout:`normal`,showFieldNames:!0,fieldSettings:{},columnSettings:{},card:{titleFieldId:e.primaryFieldId,fieldIds:q(e,[e.primaryFieldId,t])}}},validateConfig:()=>({valid:!0}),buildProjection:()=>{throw Error(`Kanban projection is implemented by BaseProjectionService.`)}},{type:c.Calendar,i18nKey:`base.viewType.calendar`,createDefaultConfig:e=>{let t=xn(e);return{startDateFieldId:t,endDateFieldId:Sn(e,t),titleFieldId:e.primaryFieldId,mode:`month`,timeslotSize:`medium`,timeZone:`local`,displayColor:{type:`custom`,color:`#3b82f6`},fieldSettings:{}}},validateConfig:()=>({valid:!0}),buildProjection:()=>{throw Error(`Calendar projection is implemented by BaseProjectionService.`)}},{type:c.Gantt,i18nKey:`base.viewType.gantt`,createDefaultConfig:e=>{let t=xn(e);return{startDateFieldId:t,endDateFieldId:Sn(e,t)??t,titleFieldId:e.primaryFieldId,scale:`month`,showTodayLine:!0,displayColor:{type:`custom`,color:`#3b82f6`},fieldSettings:{},workingDaysOnly:!1}},validateConfig:()=>({valid:!0}),buildProjection:()=>{throw Error(`Gantt projection is implemented by BaseProjectionService.`)}},{type:c.Gallery,i18nKey:`base.viewType.gallery`,createDefaultConfig:e=>{let t=vn(e);return{coverFieldId:null,cardLayout:`normal`,showFieldNames:!0,fieldSettings:{},card:{titleFieldId:t,coverFieldId:null,fieldIds:q(e,[t,e.primaryFieldId])},cardSize:`medium`}},validateConfig:()=>({valid:!0}),buildProjection:()=>{throw Error(`Gallery projection is implemented by BaseProjectionService.`)}}]}function bn(e){var t,n,i;let a=e.fieldOrder.map(t=>e.fields[t]).filter(e=>!!e);return((t=a.find(e=>e.type===r.SingleSelect||e.type===r.MultiSelect||e.type===r.Group))==null?void 0:t.id)??((n=a.find(e=>e.type===r.Text))==null?void 0:n.id)??((i=a.find(e=>e.type===r.Date||e.type===r.CreatedAt||e.type===r.UpdatedAt))==null?void 0:i.id)??e.primaryFieldId}function xn(e){var t;return((t=e.fieldOrder.map(t=>e.fields[t]).find(Cn))==null?void 0:t.id)??``}function Sn(e,t){var n;return(n=e.fieldOrder.map(t=>e.fields[t]).find(e=>Cn(e)&&e.id!==t))==null?void 0:n.id}function Cn(e){return!!e&&e.type===r.Date&&e.readonly!==!0&&e.system!==!0}const wn=v(`base.projection.service`),Tn=/* @__PURE__ */ new Set([r.Number,r.Currency,r.Progress,r.Rating,r.Date,r.CreatedAt,r.UpdatedAt,r.Checkbox]),J=864e5;let En=class extends f{constructor(e){super(),this._fieldRegistry=e,K(this,`_views`,/* @__PURE__ */ new Map),K(this,`_projectionCache`,/* @__PURE__ */ new WeakMap),K(this,`_projectedRowsCache`,/* @__PURE__ */ new Map),K(this,`_projectedViewRowsCache`,/* @__PURE__ */ new Map),K(this,`_projectedGroupsCache`,/* @__PURE__ */ new Map),K(this,`_hierarchyIndexCache`,/* @__PURE__ */ new Map),K(this,`_globalRevision`,0),K(this,`_tableRevisions`,/* @__PURE__ */ new Map),K(this,`_cellRevisions`,/* @__PURE__ */ new Map),K(this,`_cellInvalidations`,/* @__PURE__ */ new Map),K(this,`_viewRevisions`,/* @__PURE__ */ new Map)}registerView(e){return this._views.set(e.type,e),b(()=>this._views.delete(e.type))}getProjection(e,t,n){var r,i,a;return O(`BaseProjection.getProjection`,()=>{let r=this._getCachedProjection(e,t,n);if(r)return r;let i=e.tables[t],a=i==null?void 0:i.views[n];if(!i||!a)return this._setCachedProjection(e,t,n,{type:`invalid`,viewType:(a==null?void 0:a.type)??c.Grid,reason:`missingField`});let o;switch(a.type){case c.Grid:o=this._buildGrid(i,a);break;case c.Gantt:o=this._buildGantt(i,a);break;case c.Kanban:o=this._buildKanban(i,a);break;case c.Calendar:o=this._buildCalendar(i,a);break;case c.Gallery:o=this._buildGallery(i,a);break;default:o={type:`invalid`,viewType:a.type,reason:`missingField`}}return this._setCachedProjection(e,t,n,o)},{tableId:t,viewId:n,viewType:(r=e.tables[t])==null||(r=r.views[n])==null?void 0:r.type,records:((i=e.tables[t])==null||(i=i.recordOrder)==null?void 0:i.length)??Object.keys(((a=e.tables[t])==null?void 0:a.records)??{}).length})}repairViewConfig(e,t,n){var r,i,a;let o=e.tables[t],s=o==null?void 0:o.views[n];if(!o||!s)throw Error(`[BaseProjectionService]: missing view "${n}".`);let c=e=>!!o.fields[e],l={...s,filter:s.filter?{...s.filter,conditions:s.filter.conditions.filter(e=>c(e.fieldId))}:s.filter,sort:(r=s.sort)==null?void 0:r.filter(e=>c(e.fieldId)),group:(i=s.group)==null?void 0:i.filter(e=>c(e.fieldId)),fieldOrder:(a=s.fieldOrder)==null?void 0:a.filter(c),fieldSettings:Object.fromEntries(Object.entries(s.fieldSettings??{}).filter(([e])=>c(e)))};if(l.type===`kanban`){var u;let e=l.config??{},t=this._resolveKanbanGroupFieldId(o,l),n=this._resolveCardTitleFieldId(o,(u=e.card)==null?void 0:u.titleFieldId);l.config={...e,groupFieldId:t??e.groupFieldId,coverFieldId:this._resolveKanbanCoverFieldId(o,e),cardLayout:e.cardLayout===`compose`?`compose`:`normal`,showFieldNames:e.showFieldNames!==!1,fieldSettings:Object.fromEntries(Object.entries(e.fieldSettings??{}).filter(([e])=>c(e))),columnSettings:e.columnSettings??{},card:{...e.card??{},titleFieldId:n,fieldIds:this._resolveKanbanCardFieldIds(o,l,t??``,n)}}}return{repaired:JSON.stringify(l)!==JSON.stringify(s),view:l}}invalidateByOp(){this._globalRevision++}invalidateByCell(e,t,n){let r=this._getCellRevision(e)+1;this._cellRevisions.set(e,r);let i=this._cellInvalidations.get(e)??[];i.push({revision:r,recordId:t,fieldId:n}),this._cellInvalidations.set(e,i)}invalidateByField(e,t){this._bumpTableRevision(e)}invalidateByView(e,t){this._viewRevisions.set(this._viewRevisionKey(e,t),this._getViewRevision(e,t)+1)}_getCachedProjection(e,t,n){var r;let i=(r=this._projectionCache.get(e))==null?void 0:r.get(this._cacheKey(t,n));return i&&i.globalRevision===this._globalRevision&&i.tableRevision===this._getTableRevision(t)&&i.cellRevision===this._getCellRevision(t)&&i.viewRevision===this._getViewRevision(t,n)?i.projection:null}_setCachedProjection(e,t,n,r){let i=this._projectionCache.get(e);return i||(i=/* @__PURE__ */ new Map,this._projectionCache.set(e,i)),i.set(this._cacheKey(t,n),{projection:r,globalRevision:this._globalRevision,tableRevision:this._getTableRevision(t),cellRevision:this._getCellRevision(t),viewRevision:this._getViewRevision(t,n)}),r}_bumpTableRevision(e){this._tableRevisions.set(e,this._getTableRevision(e)+1)}_getTableRevision(e){return this._tableRevisions.get(e)??0}_getCellRevision(e){return this._cellRevisions.get(e)??0}_getViewRevision(e,t){return this._viewRevisions.get(this._viewRevisionKey(e,t))??0}_cacheKey(e,t){return`${e}\u0000${t}`}_viewRowsCacheKey(e,t){return`${e}\u0000${this._rowTransformCacheSegment(t)}`}_groupsCacheKey(e,t,n){return`${e}\u0000${this._rowTransformCacheSegment(t)}\u0000${this._groupConfigCacheSegment(n)}`}_rowTransformCacheSegment(e){return e?Y({filter:An(e.filter),sort:Mn(e.sort)}):`__all__`}_groupConfigCacheSegment(e){return Y(e.map(e=>({fieldId:e.fieldId,direction:e.direction??null})))}_viewRevisionKey(e,t){return`${e}\u0000${t}`}_buildGrid(e,t){let{rows:n,hierarchy:r}=this._projectHierarchyRows(e,t,T(e));return{type:c.Grid,fields:this._projectFields(e,t),rows:n,groups:this._projectHierarchyGroups(e,t,n,r),hierarchy:r,frozenFieldCount:typeof t.config.frozenFieldCount==`number`?t.config.frozenFieldCount:0}}_projectHierarchyRows(e,t,n){var r;let i=this._projectRows(e,t),a=(r=t.filter)!=null&&r.conditions.length?this._projectRows(e,{...t,filter:null}):i;return be(this._getHierarchyIndex(e,n,t.id,a.map(e=>e.recordId)),a,new Set(i.map(e=>e.recordId)))}_getHierarchyIndex(e,t,n,r){let i=`${e.id}\u0000${t}\u0000${n}`,a=this._getCellRevision(e.id),o=this._hierarchyIndexCache.get(i);if(o&&o.globalRevision===this._globalRevision&&o.tableRevision===this._getTableRevision(e.id)&&o.orderedRecordIds.length===r.length&&o.orderedRecordIds.every((e,t)=>e===r[t])){if(o.cellRevision===a&&o.table===e)return o.index;if(!this._cellInvalidationsTouchFields(e.id,o.cellRevision,a,/* @__PURE__ */ new Set([t])))return this._hierarchyIndexCache.set(i,{...o,table:e,cellRevision:a}),o.index}let s=D(e,t,r);return this._hierarchyIndexCache.set(i,{table:e,index:s,orderedRecordIds:r,globalRevision:this._globalRevision,tableRevision:this._getTableRevision(e.id),cellRevision:a}),s}_projectHierarchyGroups(e,t,n,r){var i;if(!((i=t.group)!=null&&i.length))return[];let a=new Map(n.map(e=>[e.recordId,e])),o=r.rootRecordIds.flatMap(e=>{let t=a.get(e);return t?[t]:[]}),s=this._projectGroups(e,t,o),c=new Map(r.orderedRecordIds.map((e,t)=>[e,t])),l=e=>{let t=r.nodes[e],n=c.get(e)??-1;return n<0||!t?[]:r.orderedRecordIds.slice(n,t.subtreeEndIndex+1)},u=e=>{var t,n;return{...e,recordIds:(t=e.children)!=null&&t.length?e.recordIds:e.recordIds.flatMap(l),children:(n=e.children)==null?void 0:n.map(u)}};return s.map(u)}_buildKanban(e,t){var n;let r=this._resolveKanbanGroupFieldId(e,t),i=r?e.fields[r]:void 0;if(!i)return{type:`invalid`,viewType:c.Kanban,reason:`invalidGroupField`,fieldId:t.config.groupFieldId};let a=this._projectRows(e,t),o=this._projectFields(e,t),s=t.config??{},l=this._resolveCardTitleFieldId(e,(n=s.card)==null?void 0:n.titleFieldId),u=this._resolveKanbanCardFieldIds(e,t,i.id,l),d=/* @__PURE__ */ new Map;if(C(e,i.id)){let n=this._getHierarchyIndex(e,i.id,t.id,a.map(e=>e.recordId)),r=/* @__PURE__ */ new Map;return a.forEach(t=>{let a=n.parentByRecordId.get(t.recordId)??null,o=a??``,c=a?e.records[a]:void 0,l=r.get(o)??{key:o,title:c?String(A(e,c.id,e.primaryFieldId)??a):this._kanbanLaneTitle(i,o,s),recordIds:[]};l.recordIds.push(t.recordId),r.set(o,l)}),{type:c.Kanban,fields:o,rows:a,groups:[],groupFieldId:i.id,titleFieldId:l,coverFieldId:this._resolveKanbanCoverFieldId(e,s),cardLayout:s.cardLayout===`compose`?`compose`:`normal`,showFieldNames:s.showFieldNames!==!1,visibleCardFieldIds:u,lanes:[``,...n.orderedRecordIds].flatMap(e=>{let t=r.get(e);return t!=null&&t.recordIds.length?[t]:[]})}}return this._getKanbanConfiguredLanes(i,s).forEach(e=>d.set(e.key,{...e,recordIds:[]})),a.forEach(e=>{this._kanbanGroupKeys(i,e.values[i.id]).forEach(t=>{let n=d.get(t)??{key:t,title:this._kanbanLaneTitle(i,t,s),color:this._kanbanLaneColor(i,t,s),recordIds:[]};n.recordIds.push(e.recordId),d.set(t,n)})}),{type:c.Kanban,fields:o,rows:a,groups:this._projectGroups(e,t,a),groupFieldId:i.id,titleFieldId:l,coverFieldId:this._resolveKanbanCoverFieldId(e,s),cardLayout:s.cardLayout===`compose`?`compose`:`normal`,showFieldNames:s.showFieldNames!==!1,visibleCardFieldIds:u,lanes:Array.from(d.values())}}_resolveKanbanGroupFieldId(e,t){var n;let r=(n=t.config)==null?void 0:n.groupFieldId;return r&&this._isKanbanGroupField(e,r)?r:this._findKanbanGroupField(e,e=>this._isAllowedKanbanGroupField(e))}_findKanbanGroupField(e,t){for(let n of e.fieldOrder){let r=e.fields[n];if(r&&t(r))return r.id}return null}_isKanbanGroupField(e,t){let n=e.fields[t];return this._isAllowedKanbanGroupField(n)||C(e,t)}_isAllowedKanbanGroupField(e){return!!e&&(e.type===r.SingleSelect||e.type===r.MultiSelect||e.type===r.Rating||e.type===r.Person||e.type===r.Group||e.type===r.Checkbox)}_isColorfulKanbanGroupField(e){return e.type===r.SingleSelect||e.type===r.MultiSelect}_resolveKanbanCoverFieldId(e,t){var n;let r=t.coverFieldId??((n=t.card)==null?void 0:n.coverFieldId)??null;if(!r)return null;let i=e.fields[r];return i&&this._capabilities(i).usableAsCardCover?i.id:null}_resolveKanbanCardFieldIds(e,t,n,i=this._resolveCardTitleFieldId(e,(()=>{var e;return(e=t.config)==null||(e=e.card)==null?void 0:e.titleFieldId})())){var a;let o=t.config??{},s=(a=o.card)!=null&&(a=a.fieldIds)!=null&&a.length?o.card.fieldIds:q(e,[i,e.primaryFieldId,n]),c=o.fieldSettings??{};return s.filter(a=>{var o,s;let l=e.fields[a];return!(!l||l.system===!0||l.type===r.RecordId||l.id===n||l.id===i||(o=t.fieldSettings)!=null&&(o=o[a])!=null&&o.hidden||(s=c[a])!=null&&s.hidden)}).sort((e,t)=>{var n,r;return(((n=c[e])==null?void 0:n.order)??s.indexOf(e))-(((r=c[t])==null?void 0:r.order)??s.indexOf(t))})}_getKanbanConfiguredLanes(e,t){var n;let r=(Array.isArray((n=e.config)==null?void 0:n.options)?e.config.options:[]).flatMap((n,r)=>{if(n==null)return[];let i=typeof n==`string`?{id:n,name:n,color:void 0}:n,a=String(i.id??i.name??`option-${r+1}`);return[{key:a,title:String(i.name??i.id??a),color:this._kanbanLaneColor(e,a,t)}]});return Object.entries(t.columnSettings??{}).forEach(([n,i])=>{r.some(e=>e.key===n)||r.push({key:n,title:this._isColorfulKanbanGroupField(e)?i.title??this._kanbanLaneTitle(e,n,t):this._kanbanLaneTitle(e,n,t),color:this._kanbanLaneColor(e,n,t)})}),r}_kanbanGroupKeys(e,t){let n=t=>{var n;let r=t==null?``:String(t);return!r||!this._isColorfulKanbanGroupField(e)?r:((n=$(e,r))==null?void 0:n.id)??r};if(Array.isArray(t)){let e=t.map(n).filter(e=>e!==``);return e.length?e:[``]}return[n(t)]}_kanbanLaneTitle(e,t,n){if(!t)return`Uncategorized`;let r=$(e,t);return(r==null?void 0:r.name)??t}_kanbanLaneColor(e,t,n){var r;if(this._isColorfulKanbanGroupField(e))return(r=$(e,t))==null?void 0:r.color}_buildCalendar(e,t){let n=this._normalizeCalendarConfig(e,t.config??{}),i=e.fields[n.startDateFieldId];if(!i||i.type!==r.Date||i.readonly===!0||i.system===!0||!this._capabilities(i).usableAsCalendarDate)return{type:`invalid`,viewType:c.Calendar,reason:`invalidDateField`,fieldId:n.startDateFieldId};let a=n.endDateFieldId?e.fields[n.endDateFieldId]:void 0,o=this._projectRows(e,t);return{type:c.Calendar,config:n,fields:this._projectFields(e,t),rows:o,groups:this._projectGroups(e,t,o),events:o.flatMap(t=>{let r=V(t.values[n.startDateFieldId]);if(!Number.isFinite(r))return[];let o=t.values[n.startDateFieldId],s=n.endDateFieldId==null?void 0:t.values[n.endDateFieldId],c=n.endDateFieldId==null?void 0:V(s),l=Number.isFinite(c)?c:void 0;return[{recordId:t.recordId,title:this._title(e,t,n.titleFieldId),start:r,end:l,color:this._calendarEventColor(e,t,n),startMs:r,endMs:l,allDay:this._isAllDayCalendarEvent(i,a,o,s),fieldValues:t.values}]})}}_normalizeCalendarConfig(e,t){let n=this._resolveCalendarDateFieldId(e,t.startDateFieldId),i=t.endDateFieldId&&this._isCalendarDateField(e,t.endDateFieldId)?t.endDateFieldId:this._findCalendarDateFieldId(e,n)??void 0,a=t.titleFieldId?e.fields[t.titleFieldId]:void 0,o=a&&a.system!==!0&&a.type!==r.RecordId?t.titleFieldId:e.primaryFieldId,s=t.mode===`day`||t.mode===`week`?t.mode:`month`,c=t.timeslotSize===`short`||t.timeslotSize===`long`?t.timeslotSize:`medium`,l=typeof t.timeZone==`string`&&t.timeZone.trim()?t.timeZone:`local`,u=this._normalizeCalendarDisplayColor(e,t);return{...t,startDateFieldId:n,endDateFieldId:i,titleFieldId:o,mode:s,timeslotSize:c,timeZone:l,displayColor:u,fieldSettings:Object.fromEntries(Object.entries(t.fieldSettings??{}).filter(([t])=>{let n=e.fields[t];return!!(n&&n.system!==!0&&n.type!==r.RecordId)}))}}_resolveCalendarDateFieldId(e,t){return t&&this._isCalendarDateField(e,t)?t:this._findCalendarDateFieldId(e)??t??``}_findCalendarDateFieldId(e,t){for(let n of e.fieldOrder)if(n!==t&&this._isCalendarDateField(e,n))return n;return null}_isCalendarDateField(e,t){let n=e.fields[t];return!!n&&n.type===r.Date&&n.readonly!==!0&&n.system!==!0&&this._capabilities(n).usableAsCalendarDate}_normalizeCalendarDisplayColor(e,t){let n=t.displayColor;if((n==null?void 0:n.type)===`selectField`){let t=e.fields[n.fieldId];if(t&&t.type===r.SingleSelect)return n}if((n==null?void 0:n.type)===`custom`&&typeof n.color==`string`&&n.color.trim())return{type:`custom`,color:n.color};if(t.colorFieldId){let n=e.fields[t.colorFieldId];if(n&&n.type===r.SingleSelect)return{type:`selectField`,fieldId:t.colorFieldId}}return{type:`custom`,color:`#3b82f6`}}_calendarEventColor(e,t,n){let r=n.displayColor;if((r==null?void 0:r.type)===`selectField`){var i;let n=e.fields[r.fieldId];if(!n)return;let a=t.values[r.fieldId],o=Array.isArray(a)?a[0]:a;return o==null||(i=$(n,String(o)))==null?void 0:i.color}if((r==null?void 0:r.type)===`custom`)return r.color}_isAllDayCalendarEvent(e,t,n,r){var i,a;let o=((i=e.config)==null?void 0:i.includeTime)===!0,s=(t==null||(a=t.config)==null?void 0:a.includeTime)===!0;return!o&&!s}_isAllDayGanttDateRange(e,t){var n,r;let i=((n=e.config)==null?void 0:n.includeTime)===!0,a=((r=t.config)==null?void 0:r.includeTime)===!0;return!i&&!a}_buildGantt(e,t){let n=this._normalizeGanttConfig(e,t.config),i=e.fields[n.startDateFieldId];if(!i||i.type!==r.Date||i.readonly===!0||i.system===!0||!this._capabilities(i).usableAsGanttStart)return{type:`invalid`,viewType:c.Gantt,reason:`invalidGanttStartField`,fieldId:n.startDateFieldId};let a=e.fields[n.endDateFieldId];if(!a||a.type!==r.Date||a.readonly===!0||a.system===!0||!this._capabilities(a).usableAsGanttEnd)return{type:`invalid`,viewType:c.Gantt,reason:`invalidGanttEndField`,fieldId:n.endDateFieldId};let o=this._isAllDayGanttDateRange(i,a),s=w(e),l=s?this._projectHierarchyRows(e,t,s):void 0,u=l==null?void 0:l.hierarchy,d=(l==null?void 0:l.rows)??this._projectRows(e,t),f=n.dependencyFieldId,p=f&&le(e.id,e.fields[f])?f:void 0,m=e.fields[n.progressFieldId??``],h=(m==null?void 0:m.type)===r.Progress&&!m.system?{id:m.id,...mn(m.config),editable:!m.readonly}:void 0,g=d.flatMap(t=>{let r=V(t.values[n.startDateFieldId]),i=V(t.values[n.endDateFieldId]);if(!Number.isFinite(r)||!Number.isFinite(i))return[];let a=Math.min(r,i),o=Math.max(r,i),s=t.values[n.progressFieldId??``],c=s==null||s===``?void 0:Number(s),l=c!=null&&Number.isFinite(c)&&h&&h.start!==h.end?Math.max(0,Math.min(1,(c-h.start)/(h.end-h.start))):void 0;return[{recordId:t.recordId,title:this._title(e,t,n.titleFieldId),start:a,end:o,color:this._ganttBarColor(e,t,n),progress:Number.isFinite(c)?c:void 0,completion:l,workingDayCount:n.workingDaysOnly?Un(a,o,n.workingDays):void 0,dependencyRecordIds:p?S(t.values[p]):void 0}]}),_=n.showPlanComparison===!0?this._buildGanttPlan(e,d,n):void 0,v=1/0,y=-1/0;for(let e of[g,(_==null?void 0:_.bars)??[]])for(let t of e)v=Math.min(v,t.start),y=Math.max(y,t.end);let ee=Date.now(),te=Z((Number.isFinite(v)?v:ee)-90*J),ne=Z((Number.isFinite(y)?y:ee)+91*J),b=Pn(n.scale,te,ne,n.workingDaysOnly?n.workingDays:void 0);return{type:c.Gantt,fields:this._projectFields(e,{...t,config:n}),rows:d,groups:u?this._projectHierarchyGroups(e,t,d,u):this._projectGroups(e,t,d),...u?{hierarchy:u}:{},config:{...n,dependencyFieldId:p},...h?{progressField:h}:{},dateRangeAllDay:o,timeline:{scale:n.scale,start:te,end:ne,unitWidth:b.unitWidth,majorHeaders:b.majorHeaders,columns:b.columns},bars:g,..._?{plan:_}:{}}}_buildGanttPlan(e,t,n){let{planStartDateFieldId:r,planEndDateFieldId:i}=n,a={bars:[],needsDateFields:!0,invalidRecordIds:[]};if(!r||!i||!this._isGanttDateField(e,r,`start`)||!this._isGanttDateField(e,i,`end`))return a;a.needsDateFields=!1;for(let o of t){let t=V(o.values[r]),s=V(o.values[i]);t!=null&&s!=null&&Number.isFinite(t)&&Number.isFinite(s)&&(t>s?a.invalidRecordIds.push(o.recordId):a.bars.push({recordId:o.recordId,title:this._title(e,o,n.titleFieldId),start:t,end:s}))}return a}_normalizeGanttConfig(e,t){let n=this._resolveGanttDateFieldId(e,t.startDateFieldId,`start`),i=this._resolveGanttDateFieldId(e,t.endDateFieldId,`end`)||n,a=t.titleFieldId?e.fields[t.titleFieldId]:void 0,o=a&&a.system!==!0&&a.type!==r.RecordId?t.titleFieldId:e.primaryFieldId,s=t.scale===`week`||t.scale===`quarter`||t.scale===`year`?t.scale:`month`,c=X(t.workingDays);return{...t,startDateFieldId:n,endDateFieldId:i,titleFieldId:o,scale:s,leftPaneWidth:typeof t.leftPaneWidth==`number`?t.leftPaneWidth:void 0,leftPaneCollapsed:t.leftPaneCollapsed===!0,showTodayLine:t.showTodayLine!==!1,displayColor:this._normalizeGanttDisplayColor(e,t),fieldSettings:Object.fromEntries(Object.entries(t.fieldSettings??{}).filter(([t])=>{let n=e.fields[t];return!!(n&&n.system!==!0&&n.type!==r.RecordId)})),workingDaysOnly:t.workingDaysOnly===!0,workingDays:c}}_resolveGanttDateFieldId(e,t,n){if(t&&this._isGanttDateField(e,t,n)||t)return t;for(let t of e.fieldOrder)if(this._isGanttDateField(e,t,n))return t;return t??``}_isGanttDateField(e,t,n){let i=e.fields[t];if(!i||i.type!==r.Date||i.readonly===!0||i.system===!0)return!1;let a=this._capabilities(i);return n===`start`?a.usableAsGanttStart:a.usableAsGanttEnd}_normalizeGanttDisplayColor(e,t){let n=t.displayColor;if((n==null?void 0:n.type)===`selectField`){let t=e.fields[n.fieldId];if(t&&t.type===r.SingleSelect)return n}return(n==null?void 0:n.type)===`conditional`&&Array.isArray(n.rules)?{type:`conditional`,rules:n.rules.filter(t=>!!e.fields[t.fieldId])}:(n==null?void 0:n.type)===`custom`&&typeof n.color==`string`&&n.color.trim()?{type:`custom`,color:n.color}:{type:`custom`,color:`#14b8a6`}}_ganttBarColor(e,t,n){let r=n.displayColor;if((r==null?void 0:r.type)===`conditional`){let n=r.rules.find(n=>this._matchesGanttColorRule(e,t,n));if(n)return n.color}if((r==null?void 0:r.type)===`selectField`){let n=e.fields[r.fieldId];if(n){var i;let e=t.values[r.fieldId],a=Array.isArray(e)?e[0]:e,o=a==null||(i=$(n,String(a)))==null?void 0:i.color;if(o)return o}}return(r==null?void 0:r.type)===`custom`?r.color:`#14b8a6`}_matchesGanttColorRule(e,t,n){let r=e.fields[n.fieldId];return r?kt(t.values[r.id],n.operator,n.operand,r,{dateMode:n.dateMode}):!1}_buildGallery(e,t){let n=this._projectRows(e,t),r=this._normalizeGalleryConfig(e,t.config??{}),i=this._projectFields(e,t);return{type:c.Gallery,fields:i,rows:n,groups:this._projectGroups(e,t,n),titleFieldId:r.card.titleFieldId,coverFieldId:r.coverFieldId,cardLayout:r.cardLayout??`normal`,showFieldNames:r.showFieldNames!==!1,visibleCardFieldIds:this._resolveGalleryCardFieldIds(e,t,r),cardSize:r.cardSize??`medium`,cards:n.map(t=>({recordId:t.recordId,title:this._title(e,t,r.card.titleFieldId),values:t.values}))}}_normalizeGalleryConfig(e,t){let n=t.card??{fieldIds:[]},i=this._resolveCardTitleFieldId(e,n.titleFieldId),a=this._resolveGalleryCoverFieldId(e,t),o=t.cardSize===`small`||t.cardSize===`large`?t.cardSize:`medium`;return{...t,coverFieldId:a,cardLayout:t.cardLayout===`compose`?`compose`:`normal`,showFieldNames:t.showFieldNames!==!1,fieldSettings:Object.fromEntries(Object.entries(t.fieldSettings??{}).filter(([t])=>{let n=e.fields[t];return!!(n&&n.system!==!0&&n.type!==r.RecordId)})),card:{...n,titleFieldId:i,coverFieldId:a,fieldIds:Array.isArray(n.fieldIds)?n.fieldIds:[]},cardSize:o}}_resolveCardTitleFieldId(e,t){let n=t?e.fields[t]:void 0;return n&&n.system!==!0&&n.type!==r.RecordId?n.id:vn(e)}_resolveGalleryCoverFieldId(e,t){var n;let r=t.coverFieldId??((n=t.card)==null?void 0:n.coverFieldId)??null;if(!r)return null;let i=e.fields[r];return i&&this._capabilities(i).usableAsCardCover?i.id:null}_resolveGalleryCardFieldIds(e,t,n){var i,a,o;let s=n.fieldSettings??{},c=((i=n.card)==null?void 0:i.titleFieldId)??vn(e),l=n.coverFieldId??((a=n.card)==null?void 0:a.coverFieldId)??null,u=(o=n.card)!=null&&(o=o.fieldIds)!=null&&o.length?n.card.fieldIds:q(e,[c,l,e.primaryFieldId]);return u.filter(n=>{var i,a;let o=e.fields[n];return!(!o||o.system===!0||o.type===r.RecordId||o.id===c||o.id===l||(i=t.fieldSettings)!=null&&(i=i[n])!=null&&i.hidden||(a=s[n])!=null&&a.hidden)}).sort((e,t)=>{var n,r;return(((n=s[e])==null?void 0:n.order)??u.indexOf(e))-(((r=s[t])==null?void 0:r.order)??u.indexOf(t))})}_projectFields(e,t){var n;return((n=t.fieldOrder)!=null&&n.length?t.fieldOrder:e.fieldOrder).flatMap(n=>{var i;let a=e.fields[n],o=((i=t.fieldSettings)==null?void 0:i[n])??{};return!a||a.system===!0||a.type===r.RecordId||o.hidden?[]:[{id:a.id,name:a.name,description:a.description,type:a.type,config:a.config,width:o.width,setting:o}]})}_projectRows(e,t){var n;return O(`BaseProjection.projectRows`,()=>{var n,r;let i=this._projectTableRows(e),a=this._viewRowsCacheKey(e.id,t),o=this._getCellRevision(e.id),s=this._projectedViewRowsCache.get(a);if(s&&s.globalRevision===this._globalRevision&&s.tableRevision===this._getTableRevision(e.id)){if(s.cellRevision===o&&s.baseRows===i)return s.rows;if(s.cellRevision!==o&&!this._cellInvalidationsTouchFields(e.id,s.cellRevision,o,this._filterSortFieldIds(t))){let e=s.rows===s.baseRows?i:this._patchCachedProjectedRows(s.rows,i);if(e)return this._projectedViewRowsCache.set(a,{...s,rows:e,baseRows:i,cellRevision:o}),e}}let c=O(`BaseProjection.filterAndSortRows`,()=>this._sortRows(e,t,this._filterRows(e,t,i)),{tableId:e.id,viewId:t==null?void 0:t.id,viewType:t==null?void 0:t.type,rows:i.length,filters:(t==null||(n=t.filter)==null?void 0:n.conditions.length)??0,sorts:(t==null||(r=t.sort)==null?void 0:r.length)??0});return this._projectedViewRowsCache.set(a,{table:e,rows:c,baseRows:i,globalRevision:this._globalRevision,tableRevision:this._getTableRevision(e.id),cellRevision:o}),c},{tableId:e.id,viewId:t==null?void 0:t.id,viewType:t==null?void 0:t.type,records:((n=e.recordOrder)==null?void 0:n.length)??Object.keys(e.records??{}).length})}_projectTableRows(e){var t;return O(`BaseProjection.projectTableRows`,()=>{var t;let n=this._getCellRevision(e.id),r=this._projectedRowsCache.get(e.id);if(r&&r.globalRevision===this._globalRevision&&r.tableRevision===this._getTableRevision(e.id)){if(r.cellRevision===n&&jn(r.table,e))return r.table=e,r.rows;let t=this._patchProjectedRowsForCellInvalidations(e,r,n);if(t)return t}kn(e)||k(e);let i=(t=e.recordOrder)!=null&&t.length?e.recordOrder:Nn(e.records),a=O(`BaseProjection.materializeTableRows`,()=>{let t=[];for(let n of i){let r=e.records[n];if(!r)continue;let i={};for(let t of e.fieldOrder)i[t]=A(e,r.id,t);t.push({recordId:r.id,values:i})}return t},{tableId:e.id,records:i.length,fields:e.fieldOrder.length});return this._projectedRowsCache.set(e.id,{table:e,rows:a,rowIndexById:On(a),globalRevision:this._globalRevision,tableRevision:this._getTableRevision(e.id),cellRevision:n}),a},{tableId:e.id,records:((t=e.recordOrder)==null?void 0:t.length)??Object.keys(e.records??{}).length,fields:e.fieldOrder.length})}_patchProjectedRowsForCellInvalidations(e,t,n){let r=(this._cellInvalidations.get(e.id)??[]).filter(e=>e.revision>t.cellRevision&&e.revision<=n);if(!r.length)return t.table===e?t.rows:null;let i=t.rows,a=/* @__PURE__ */ new Map;for(let e of r){let t=a.get(e.recordId);t||(t=/* @__PURE__ */ new Set,a.set(e.recordId,t)),t.add(e.fieldId)}for(let[n,r]of a){if(!e.records[n])return null;let a=t.rowIndexById.get(n);if(a==null)return null;i===t.rows&&(i=[...t.rows]);let o=i[a],s={...o.values};r.forEach(t=>{s[t]=A(e,n,t)}),i[a]={...o,values:s}}let o={table:e,rows:i,rowIndexById:t.rowIndexById,globalRevision:this._globalRevision,tableRevision:this._getTableRevision(e.id),cellRevision:n};return this._projectedRowsCache.set(e.id,o),this._cellInvalidations.set(e.id,(this._cellInvalidations.get(e.id)??[]).filter(e=>e.revision>Math.max(0,n-256))),i}_patchCachedProjectedRows(e,t){let n=new Map(t.map(e=>[e.recordId,e])),r=!1,i=e.map(e=>{let t=n.get(e.recordId);return t?t===e?e:(r=!0,t):e});return r?i:e}_cellInvalidationsTouchFields(e,t,n,r){return!r.size||t===n?!1:n-t>256||(this._cellInvalidations.get(e)??[]).some(e=>e.revision>t&&e.revision<=n&&r.has(e.fieldId))}_filterSortFieldIds(e){var t,n;let r=/* @__PURE__ */ new Set;return e==null||(t=e.filter)==null||t.conditions.forEach(e=>r.add(e.fieldId)),e==null||(n=e.sort)==null||n.forEach(e=>r.add(e.fieldId)),r}_groupProjectionFieldIds(e){var t;let n=this._filterSortFieldIds(e);return(t=e.group)==null||t.forEach(e=>n.add(e.fieldId)),n}_filterRows(e,t,n){let r=t==null?void 0:t.filter;if(!(r!=null&&r.conditions.length))return n;let a=r.conditions.filter(e=>!$n(e));return a.length?n.filter(t=>{if(r.conjunction===i.OR){for(let n of a){let r=e.fields[n.fieldId];if(!r||this._fieldRegistry.get(r.type).filter(t.values[r.id],n.operator,n.operand,r))return!0}return!1}for(let n of a){let r=e.fields[n.fieldId];if(r&&!this._fieldRegistry.get(r.type).filter(t.values[r.id],n.operator,n.operand,r))return!1}return!0}):n}_sortRows(e,t,n){let r=(t==null?void 0:t.sort)??[];if(!r.length)return n;let i=r.flatMap(t=>{let n=e.fields[t.fieldId];return n?[{...t,field:n}]:[]});return i.length?this._canUseFastSort(i)?this._fastSortRows(i,n):[...n].sort((e,t)=>{for(let n of i){let r=n.field,i=this._fieldRegistry.get(r.type).compare(e.values[r.id],t.values[r.id],r);if(i!==0)return n.direction===s.DESC?-i:i}return 0}):n}_canUseFastSort(e){return e.every(e=>Tn.has(e.field.type))}_fastSortRows(e,t){return t.map((t,n)=>({row:t,index:n,keys:e.map(e=>t.values[e.fieldId])})).sort((t,n)=>{for(let r=0;r<e.length;r++){let i=Qn(t.keys[r],n.keys[r]);if(i!==0)return e[r].direction===s.DESC?-i:i}return t.index-n.index}).map(e=>e.row)}_projectGroups(e,t,n){var r;return O(`BaseProjection.projectGroups`,()=>{var r;if(!((r=t.group)!=null&&r.length))return[];let i=t.group.filter(t=>e.fields[t.fieldId]);if(!i.length)return[];let a=this._groupsCacheKey(e.id,t,i),o=this._getCellRevision(e.id),s=this._projectedGroupsCache.get(a);if(s&&s.globalRevision===this._globalRevision&&s.tableRevision===this._getTableRevision(e.id)){if(s.cellRevision===o&&s.rows===n)return s.groups;if(s.cellRevision!==o&&!this._cellInvalidationsTouchFields(e.id,s.cellRevision,o,this._groupProjectionFieldIds(t)))return this._projectedGroupsCache.set(a,{...s,rows:n,cellRevision:o}),s.groups}let c=/* @__PURE__ */ new Map;for(let e of n){let t=c,n=``;for(let r=0;r<i.length;r++){let a=i[r],o=e.values[a.fieldId],s=Dn(o),c=`${a.fieldId}\u0000${s}`,l=`${n}/${a.fieldId}:${s}`,u=t.get(c);u||(u={key:s,value:o,path:l,label:s||`Empty`,fieldId:a.fieldId,level:r,recordIds:[],children:/* @__PURE__ */ new Map},t.set(c,u)),u.recordIds.push(e.recordId),t=u.children,n=l}}let l=this._materializeGroups(i,c,0);return this._projectedGroupsCache.set(a,{table:e,rows:n,groups:l,globalRevision:this._globalRevision,tableRevision:this._getTableRevision(e.id),cellRevision:o}),l},{tableId:e.id,viewId:t.id,viewType:t.type,rows:n.length,groupFields:((r=t.group)==null?void 0:r.length)??0})}_materializeGroups(e,t,n){var r;let i=Array.from(t.values()),a=(r=e[n])==null?void 0:r.direction;return a&&i.sort((e,t)=>{let n=e.key.localeCompare(t.key);return a===s.DESC?-n:n}),i.map(t=>({key:t.key,value:t.value,path:t.path,label:t.label,fieldId:t.fieldId,level:t.level,recordIds:t.recordIds,children:this._materializeGroups(e,t.children,n+1)}))}_title(e,t,n){let r=n??e.primaryFieldId,i=t.values[r];return i==null?``:String(i)}_capabilities(e){return this._fieldRegistry.get(e.type).getCapabilities(e)}};En=pn([fn(0,m(un))],En);function Dn(e){return e==null?``:String(e)}function On(e){return new Map(e.map((e,t)=>[e.recordId,t]))}function kn(e){return!!(Array.isArray(e.recordOrder)&&e.rowIndex&&e.rowId&&e.colIndex&&e.colId&&e.cellData)}function An(e){let t=(e==null?void 0:e.conditions.filter(e=>!$n(e)))??[];return!e||!t.length?null:{conjunction:e.conjunction,conditions:t.map(e=>({fieldId:e.fieldId,operator:e.operator,operand:e.operand}))}}function jn(e,t){return e.records===t.records&&e.recordOrder===t.recordOrder&&e.fields===t.fields&&e.fieldOrder===t.fieldOrder&&e.cellData===t.cellData&&e.rowIndex===t.rowIndex&&e.rowId===t.rowId&&e.colIndex===t.colIndex&&e.colId===t.colId}function Mn(e){return e!=null&&e.length?e.map(e=>({fieldId:e.fieldId,direction:e.direction})):null}function Y(e){if(typeof e!=`object`||!e)return JSON.stringify(e)??`undefined`;if(Array.isArray(e))return`[${e.map(Y).join(`,`)}]`;let t=e;return`{${Object.keys(t).sort().map(e=>`${JSON.stringify(e)}:${Y(t[e])}`).join(`,`)}}`}function Nn(e){let t=Object.values(e).sort((e,t)=>e.orderKey.localeCompare(t.orderKey)),n=[];for(let e of t)n.push(e.id);return n}function X(e){return{weekdays:Array.isArray(e==null?void 0:e.weekdays)&&e.weekdays.length?[...new Set(e.weekdays.filter(e=>Number.isInteger(e)&&e>=1&&e<=7))]:[1,2,3,4,5],exceptions:Array.isArray(e==null?void 0:e.exceptions)?e.exceptions.flatMap(e=>!e||!Number.isFinite(e.date)?[]:[{id:String(e.id||`exception-${e.date}`),date:Z(Number(e.date)),name:String(e.name||`Working day`),type:e.type===`working`?`working`:`off`}]):[]}}function Pn(e,t,n,r){let i=Rn(e,t),a=zn(e,n),o=Fn(e,i,a,r);return{scale:e,start:i,end:a,unitWidth:Ln(e),majorHeaders:In(e,i,a),columns:o}}function Fn(e,t,n,r){let i=[],a=t;for(;a<n;){let t=e===`quarter`?Q(a,7):e===`year`?Yn(a,1):Q(a,1);i.push({id:`${e}-${a}`,label:Bn(e,a,t),majorLabel:Vn(e,a),start:a,end:t,nonWorking:Wn(a,t,r)}),a=t}return i}function In(e,t,n){let r=[],i=e===`year`?Jn(t):qn(t);for(;i<n;){let t=e===`year`?Xn(i,1):Yn(i,1);r.push({id:`major-${i}`,label:e===`year`?String(new Date(i).getUTCFullYear()):Zn(i),start:i,end:t}),i=t}return r}function Ln(e){switch(e){case`week`:return 172;case`quarter`:return 172;case`year`:return 136;default:return 86}}function Rn(e,t){return e===`year`?Jn(t):e===`quarter`?Kn(t):Z(t)}function zn(e,t){return e===`year`?Xn(Jn(t),1):e===`quarter`?Q(Kn(t),7):Q(Z(t),1)}function Bn(e,t,n){let r=new Date(t);return e===`quarter`?`${r.getUTCDate()}-${(/* @__PURE__ */ new Date(n-J)).getUTCDate()}`:e===`year`?r.toLocaleString(`en-US`,{month:`short`,timeZone:`UTC`}):String(r.getUTCDate())}function Vn(e,t){return e===`year`?String(new Date(t).getUTCFullYear()):Zn(t)}function Hn(e,t,n){let r=Z(e),i=Z(t);if(r===i||!Number.isFinite(r)||!Number.isFinite(i))return 0;let a=Math.min(r,i),o=Math.max(r,i),s=(o-a)/J,c=X(n),l=e=>{let t=new Date(e).getUTCDay();return c.weekdays.some(e=>e%7===t)},u=Math.floor(s/7)*c.weekdays.length;for(let e=1;e<=s%7;e++)u+=Number(l(Q(a,e)));let d=/* @__PURE__ */ new Set;for(let e of c.exceptions)e.date>a&&e.date<=o&&!d.has(e.date)&&(d.add(e.date),u+=Number(e.type===`working`)-Number(l(e.date)));return i<r&&u!==0?-u:u}function Un(e,t,n){let r=X(n),i=0;for(let n=Z(e);n<=Z(t);n=Q(n,1))Gn(n,r)||i++;return i}function Wn(e,t,n){if(!n)return!1;let r=X(n);for(let n=Z(e);n<t;n=Q(n,1))if(!Gn(n,r))return!1;return!0}function Gn(e,t){let n=Z(e),r=t.exceptions.find(e=>Z(e.date)===n);if(r)return r.type===`off`;let i=new Date(n).getUTCDay(),a=i===0?7:i;return!t.weekdays.includes(a)}function Z(e){let t=new Date(e);return Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate())}function Kn(e){let t=Z(e),n=new Date(t).getUTCDay();return Q(t,-(n===0?6:n-1))}function qn(e){let t=new Date(e);return Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),1)}function Jn(e){let t=new Date(e);return Date.UTC(t.getUTCFullYear(),0,1)}function Q(e,t){return e+t*J}function Yn(e,t){let n=new Date(e);return Date.UTC(n.getUTCFullYear(),n.getUTCMonth()+t,1)}function Xn(e,t){let n=new Date(e);return Date.UTC(n.getUTCFullYear()+t,0,1)}function Zn(e){let t=new Date(e);return`${t.toLocaleString(`en-US`,{month:`short`,timeZone:`UTC`})} ${t.getUTCFullYear()}`}function Qn(e,t){if(e==null&&t==null)return 0;if(e==null)return-1;if(t==null)return 1;if(typeof e==`boolean`||typeof t==`boolean`)return Number(e===!0)-Number(t===!0);let n=Number(e),r=Number(t),i=Number.isFinite(n),a=Number.isFinite(r);return i&&a?n-r:i?1:a?-1:String(e).localeCompare(String(t))}function $n(e){if(e.operator!==`is`&&e.operator!==`isNot`)return!1;let t=e.operand;return t==null?!0:typeof t==`string`?t.trim()===``:Array.isArray(t)?t.length===0:!1}function $(e,t){var n;let r=Array.isArray((n=e.config)==null?void 0:n.options)?e.config.options:[];for(let e of r){if(e==null)continue;if(typeof e==`string`){if(e===t)return{id:e,name:e};continue}let n=e,r=String(n.id??n.name??``),i=String(n.name??n.id??r);if(r===t||i===t)return{id:r,name:i,color:n.color==null?void 0:String(n.color)}}return null}let er=/* @__PURE__ */ function(e){return e.CreateView=`create-view`,e.DeleteView=`delete-view`,e}({});const tr={id:`base.mutation.apply-base-json1`,type:u.MUTATION,handler(e,t){let{unitId:n,op:r,ganttPredecessorAddition:i}=t,a=e.get(p).getUnit(n,_.UNIVER_BASE);if(!a)return!1;if(!r)return!0;let o=a.getSnapshot(),s=new Ze,c=s.getAffectedRanges(r),l=s.applyOp(o,r);if(i){var u,d,f;let{tableId:e,fieldId:t,predecessorId:n,successorId:r}=i,a=(u=l.tables[e])==null?void 0:u.records;if(S(a==null||(d=a[r])==null?void 0:d.values[t]).includes(n)&&!S((f=o.tables[e])==null||(f=f.records[r])==null?void 0:f.values[t]).includes(n)&&ce(n,r,e=>{var n;return a==null||(n=a[e])==null?void 0:n.values[t]}))return!1}return a.setSnapshot(l),nr(l,c,e.get(wn)),!0}};function nr(e,t,n){let r=/* @__PURE__ */ new Set,i=/* @__PURE__ */ new Set,a=/* @__PURE__ */ new Set;for(let o of t){if(o.reason===`view`&&o.tableId&&o.viewId){let e=`${o.tableId}\u0000${o.viewId}`;a.has(e)||(a.add(e),n.invalidateByView(o.tableId,o.viewId));continue}if(o.reason===`field`&&o.tableId&&o.fieldId){let e=`${o.tableId}\u0000${o.fieldId}`;i.has(e)||(i.add(e),n.invalidateByField(o.tableId,o.fieldId));continue}if(o.reason!==`cell`){n.invalidateByOp();return}let t=rr(e,o);if(!t){n.invalidateByOp();return}let s=`${t.tableId}\u0000${t.recordId}\u0000${t.fieldId}`;r.has(s)||(r.add(s),n.invalidateByCell(t.tableId,t.recordId,t.fieldId))}}function rr(e,t){var n,r;if(!t.tableId)return null;if(t.recordId&&t.fieldId)return{tableId:t.tableId,recordId:t.recordId,fieldId:t.fieldId};if(t.row==null||t.column==null)return null;let i=e.tables[t.tableId],a=i==null||(n=i.rowId)==null?void 0:n[t.row],o=i==null||(r=i.colId)==null?void 0:r[t.column];return!a||!o?null:{tableId:t.tableId,recordId:a,fieldId:o}}var ir=`@univerjs-pro/bases`,ar=`1.7.0-alpha.0`;const or=`bases.config`,sr={},cr=`bases.remote.config`,lr={};export{xe as $,bt as A,Re as B,Dt as C,St as D,z as E,Ie as F,me as G,O as H,Le as I,D as J,pe as K,Fe as L,Xe as M,k as N,xt as O,Ve as P,w as Q,A as R,Et as S,V as T,ue as U,Be as V,de as W,E as X,he as Y,ye as Z,fn as _,ir as a,ge as at,K as b,er as c,se as ct,Hn as d,re as dt,C as et,yn as f,ie as ft,pn as g,gn as h,lr as i,_e as it,Ze as j,B as k,En as l,x as lt,mn as m,oe as mt,cr as n,T as nt,ar as o,ce as ot,hn as p,ae as pt,fe as q,sr as r,Se as rt,tr as s,le as st,or as t,be as tt,wn as u,S as ut,dn as v,kt as w,Kt as x,un as y,N as z};
package/lib/es/facade.js CHANGED
@@ -1 +1 @@
1
- import{ApplyBaseJson1Mutation as e,BASE_TABLE_NAME_REQUIREMENTS as t,BaseConditionalColorRuleUpdateType as n,BaseEventSource as r,BaseHierarchyErrorCode as i,BatchCreateBaseRecordsCommand as a,BatchDeleteBaseRecordsCommand as o,ChangeBaseFieldTypeCommand as s,CreateBaseChildRecordCommand as c,CreateBaseFieldCommand as l,CreateBaseRecordCommand as u,CreateBaseTableCommand as d,CreateBaseViewCommand as f,DeleteBaseFieldCommand as ee,DeleteBaseRecordCommand as te,DeleteBaseTableCommand as ne,DeleteBaseViewCommand as re,DuplicateBaseRecordCommand as p,IBaseProjectionService as ie,MoveBaseFieldCommand as ae,MoveBaseHierarchyRecordCommand as oe,MoveBaseViewCommand as se,RenameBaseTableCommand as ce,RenameBaseViewCommand as le,SetBaseNameCommand as ue,SetBasePermissionCommand as m,SetBasePermissionsCommand as de,SetBaseRangeValuesCommand as fe,SetBaseRecordValuesCommand as pe,SetBaseTableHierarchyFieldCommand as me,SetBaseViewFieldOrderCommand as he,SetBaseViewFieldVisibleCommand as ge,SetBaseViewFieldWidthCommand as _e,SetBaseViewFilterCommand as ve,SetBaseViewGroupCommand as ye,SetBaseViewSortCommand as be,UpdateBaseCellCommand as h,UpdateBaseFieldCommand as xe,UpdateBaseRecordOrderCommand as Se,UpdateBaseViewConditionalColorRulesCommand as g,UpdateBaseViewConfigCommand as Ce,ValidateBaseFormulaCommand as we,buildBaseHierarchyIndex as _,canEditBaseTargets as Te,copyBaseTableSnapshot as Ee,createUniqueBaseTableName as De,ensureBaseTableCellLayout as Oe,getActiveBaseHierarchyFieldIds as ke,getBaseCellValue as Ae,getBaseFieldPermissionObjectId as je,getBaseFormulaTableName as Me,getBaseHierarchyDeletePromotions as v,getBasePermissionValue as y,getBaseRecordPermissionObjectId as Ne,getBaseTablePermissionObjectId as b,getBaseViewPermissionObjectId as Pe,getRecordLinkFieldConfig as Fe,matchesBaseCondition as Ie,parseRecordLinkIds as x,resolveBaseHierarchyFieldId as S,resolveBaseRangeHierarchyPatches as Le,searchBaseTable as Re,serializeRecordLinkIds as ze,validateBaseHierarchyRecordCreations as C,validateBaseHierarchyRecordPatches as Be,validateBaseTableName as Ve,validateRecordLinkValue as He}from"@univerjs-pro/bases";import{BASE_RECORD_ID_FIELD_ID as w,BaseConditionalColorOperator as Ue,BaseConditionalColorTarget as We,BaseConditionalDateMode as Ge,BaseFieldType as T,BaseFilterConjunction as E,BaseFilterOperator as Ke,BaseHierarchyInvalidReason as qe,BaseRecordLinkRole as Je,BaseSortDirection as D,BaseViewType as O,CanceledError as k,ICommandService as A,IPermissionService as j,IResourceLoaderService as Ye,ImageSourceType as M,Inject as Xe,Injector as Ze,Tools as N,UniverInstanceType as P,createDefaultBaseTableSnapshot as Qe,generateRandomId as F}from"@univerjs/core";import*as $e from"@univerjs/core/facade";import{FBaseInitialable as et,FEnum as tt,FEventName as nt,FUniver as rt}from"@univerjs/core/facade";import{UnitAction as I}from"@univerjs/protocol";import{UpsertHostExternalReferencesCommand as it}from"@univerjs-pro/engine-formula";var at=class{constructor(e,t,n){this._unitId=e,this._commandService=t,this._permissionService=n}async setObjectPermissions(e){return this._commandService.executeCommand(de.id,{unitId:this._unitId,changes:e})}async setPoint(e,t){await this._commandService.executeCommand(m.id,{unitId:this._unitId,objectId:this._unitId,action:e,value:t})}getPoint(e){return y(this._permissionService,this._unitId,this._unitId,e)}async setEditable(e=!0){await this._commandService.executeCommand(m.id,{unitId:this._unitId,objectId:this._unitId,action:I.Edit,value:e})}async setReadOnly(){await this._commandService.executeCommand(m.id,{unitId:this._unitId,objectId:this._unitId,action:I.Edit,value:!1})}canEdit(){return y(this._permissionService,this._unitId,this._unitId,I.Edit)}},L=class{constructor(e,t,n,r,i){this._unitId=e,this._objectId=t,this._parentObjectIds=n,this._commandService=r,this._permissionService=i}async setEditable(e=!0){await this._commandService.executeCommand(m.id,{unitId:this._unitId,objectId:this._objectId,action:I.Edit,value:e})}async setReadOnly(){await this._commandService.executeCommand(m.id,{unitId:this._unitId,objectId:this._objectId,action:I.Edit,value:!1})}canEdit(){return Te(this._permissionService,this._unitId,[...this._parentObjectIds,this._objectId])}};function R(e,t){return function(n,r){t(n,r,e)}}function z(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}let B=class{constructor(e,t,n,r,i){this._base=e,this._table=t,this._fieldId=n,this._commandService=r,this._permissionService=i}getId(){return this._fieldId}getPermission(){let e=this._table.getId();return new L(this._base.getId(),je(e,this._fieldId),[b(e)],this._commandService,this._permissionService)}getField(){return this._getField()}getName(){return this._getField().name}getType(){return this._getField().type}getConfig(){return this._getField().config}getDefaultValue(){return this._getField().defaultValue}getDescription(){return this._getField().description}isReadonly(){return!!this._getField().readonly}setName(e){return this.update({name:e})}setConfig(e,t){return this.update({config:e},t)}setDefaultValue(e){return this.update({defaultValue:e})}update(e,t){let n=this._getField().type;return(e.type??n)===T.Formula&&(Object.prototype.hasOwnProperty.call(e,`config`)||e.type===T.Formula)&&!this._writeFormulaExternalReferences(t)?!1:this._commandService.syncExecuteCommand(xe.id,{unitId:this._base.getId(),tableId:this._table.getId(),fieldId:this._fieldId,patch:e})}changeType(e,t={},n){return e===T.Formula&&!this._writeFormulaExternalReferences(n)?!1:this._commandService.syncExecuteCommand(s.id,{unitId:this._base.getId(),tableId:this._table.getId(),fieldId:this._fieldId,input:{type:e,config:t}})}delete(){return this._commandService.syncExecuteCommand(ee.id,{unitId:this._base.getId(),tableId:this._table.getId(),fieldId:this._fieldId})}move(e){return this._commandService.syncExecuteCommand(ae.id,{unitId:this._base.getId(),tableId:this._table.getId(),fieldId:this._fieldId,target:e})}_getField(){let e=this._table.getTable().fields[this._fieldId];if(!e)throw Error(`[FField]: field "${this._fieldId}" does not exist.`);return e}_writeFormulaExternalReferences(e){if(!e||!Array.isArray(e.externalReferences))return console.warn(`[Base Field Facade]: Formula writes require { externalReferences }. Use [] only for a Host-local formula.`),!1;if(e.externalReferences.length===0)return!0;let t=this._commandService.syncExecuteCommand(it.id,{unitId:this._base.getId(),references:e.externalReferences});return t||console.warn(`[Base Field Facade]: Failed to bind External References.`),t}};B=z([R(3,A),R(4,j)],B);let ot=/* @__PURE__ */ function(e){return e.Id=`id`,e.Name=`name`,e.Auto=`auto`,e}({});function V(e){return!!(e&&e.system!==!0&&e.type!==T.RecordId)}function H(e,t,n=`id`){if(!t)return{};let r={};return Object.entries(t).forEach(([t,i])=>{let a=ct(e,t,n);r[a]=st(e.fields[a],i)}),r}function st(e,t){if((e==null?void 0:e.type)!==T.Attachment||t==null)return t;if(!Array.isArray(t))throw TypeError(`Invalid attachment value for field "${e.name}": expected an array.`);return t.map((t,n)=>lt(e,t,n))}function ct(e,t,n){if(n===`id`||n===`auto`&&e.fields[t])return t;let r=Object.values(e.fields).filter(e=>e.name===t);if(r.length===1)return r[0].id;throw r.length>1?Error(`Duplicate Base field name: ${t}`):Error(`Base field not found: ${t}`)}function lt(e,t,n){let r=`Invalid attachment at index ${n} for field "${e.name}"`;if(!ft(t))throw TypeError(`${r}: expected an object.`);if(`url`in t)throw TypeError(`${r}: "url" is not supported; use "source".`);if(`type`in t)throw TypeError(`${r}: "type" is not supported; use "mimeType".`);let i=U(t.id,r,`id`),a=U(t.name,r,`name`),o=U(t.source,r,`source`);return{id:i,name:a,source:o,sourceType:ut(t.sourceType,o,r),...dt(t,`mimeType`,r),...W(t,`size`,r),...W(t,`width`,r),...W(t,`height`,r),...dt(t,`thumbnail`,r)}}function ut(e,t,n){if(e==null)return t.startsWith(`data:`)?M.BASE64:M.URL;if(e===M.URL||e===M.UUID||e===M.BASE64)return e;throw TypeError(`${n}: "sourceType" must be URL, UUID, or BASE64.`)}function U(e,t,n){if(typeof e!=`string`||!e.trim())throw TypeError(`${t}: "${n}" must be a non-empty string.`);return e}function dt(e,t,n){let r=e[t];if(r==null)return{};if(typeof r!=`string`||!r.trim())throw TypeError(`${n}: "${t}" must be a non-empty string when provided.`);return{[t]:r}}function W(e,t,n){let r=e[t];if(r==null)return{};if(typeof r!=`number`||!Number.isFinite(r)||r<0)throw TypeError(`${n}: "${t}" must be a non-negative finite number when provided.`);return{[t]:r}}function ft(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var G;let K=G=class{constructor(e,t,n,r,i){this._base=e,this._table=t,this._range=n,this._inject=r,this._commandService=i,this._assertInBounds()}getBaseId(){return this._base.getId()}getTableId(){return this._table.getId()}getRange(){return{...this._range}}getRow(){return this._range.startRow}getColumn(){return this._range.startColumn}getNumRows(){return this._range.endRow-this._range.startRow+1}getNumColumns(){return this._range.endColumn-this._range.startColumn+1}getValues(){let e=this._getTable(),t=this._getFieldIds(e),n=[];for(let i=this._range.startRow;i<=this._range.endRow;i++){var r;let a=(r=e.rowId)==null?void 0:r[i],o=[];for(let n=this._range.startColumn;n<=this._range.endColumn;n++){let r=t[n];o.push(a&&r?Ae(e,a,r):null)}n.push(o)}return n}getValue(){var e;return((e=this.getValues()[0])==null?void 0:e[0])??null}setValue(e){return this.setValues([[e]])}setValues(e){let t=this.getNumRows(),n=this.getNumColumns();if(e.length>t||e.some(e=>e.length>n)){var i;throw Error(`[FBaseRange]: values size ${e.length}x${((i=e[0])==null?void 0:i.length)??0} exceeds range size ${t}x${n}.`)}let a=this._getTable(),o=this._getFieldIds(a),s=e.flatMap((e,t)=>e.map((e,n)=>{var r;let i=this._range.startRow+t,s=o[this._range.startColumn+n],c=(r=a.rowId)==null?void 0:r[i];if(!s||!c)throw Error(`[FBaseRange]: cannot resolve the public Base range address.`);return{recordId:c,fieldId:s,value:e}}));return this._commandService.syncExecuteCommand(fe.id,{unitId:this._base.getId(),tableId:this._table.getId(),patches:s,source:r.Facade})}clear(){return this.setValues(Array.from({length:this.getNumRows()},()=>Array.from({length:this.getNumColumns()},()=>null)))}offset(e,t,n=this.getNumRows(),r=this.getNumColumns()){return this._inject.createInstance(G,this._base,this._table,{startRow:this._range.startRow+e,startColumn:this._range.startColumn+t,endRow:this._range.startRow+e+n-1,endColumn:this._range.startColumn+t+r-1},this._inject)}_getTable(){let e=this._table.getTable();if(!e)throw Error(`[FBaseRange]: table does not exist.`);return Oe(e)}_assertInBounds(){var e;let t=this._getTable(),n=((e=t.recordOrder)==null?void 0:e.length)??0,r=this._getFieldIds(t).length;if(this._range.startRow<0||this._range.startColumn<0||this._range.endRow<this._range.startRow||this._range.endColumn<this._range.startColumn||this._range.endRow>=Math.max(n,1)||this._range.endColumn>=Math.max(r,1))throw Error(`[FBaseRange]: range is out of bounds. Max rows: ${n}, max columns: ${r}, range: ${JSON.stringify(this._range)}.`)}_getFieldIds(e){return e.fieldOrder.filter(t=>V(e.fields[t]))}};K=G=z([R(4,A)],K);function q(e){"@babel/helpers - typeof";return q=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},q(e)}function pt(e,t){if(q(e)!=`object`||!e)return e;var n;if(typeof Symbol<`u`&&(n=e[Symbol.toPrimitive])!==void 0){var r=n.call(e,t||`default`);if(q(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function mt(e){var t=pt(e,`string`);return q(t)==`symbol`?t:t+``}function ht(e,t,n){return(t=mt(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var J;let Y=J=class extends et{constructor(e,t,n,r,i,a){super(r),this._base=e,this._table=t,this._recordId=n,this._injector=r,this._commandService=i,this._permissionService=a,ht(this,`_baseUnitId`,void 0),ht(this,`_baseTableId`,void 0),this._baseUnitId=e.getId(),this._baseTableId=t.getId()}getBaseFacade(){return this._base}getTableFacade(){return this._table}getId(){return this._recordId}getPermission(){let e=this._table.getId();return new L(this._base.getId(),Ne(e,this._recordId),[b(e)],this._commandService,this._permissionService)}getRecord(){return{...this._getRecord(),values:this.getValues()}}getValue(e){return V(this._table.getTable().fields[e])?this._getRecord().values[e]??null:null}getValues(){let e=this._table.getTable();return Object.fromEntries(Object.entries(this._getRecord().values).filter(([t])=>V(e.fields[t])))}setValue(e,t){let n=this._table.getTable().fields[e];return this._commandService.syncExecuteCommand(h.id,{unitId:this._base.getId(),tableId:this._table.getId(),recordId:this._recordId,fieldId:e,value:st(n,t),source:r.Facade})}setAttachments(e,t){return this.setValue(e,t.map(e=>({...e})))}getAttachments(e){this._getAttachmentField(e);let t=this.getValue(e);return Array.isArray(t)?t.map((t,n)=>_t(t,e,n)):[]}deleteAttachments(e,t){this._getAttachmentField(e);let n=new Set(t.map(e=>e.id));if(!n.size)return!0;let r=this.getAttachments(e),i=r.filter(e=>!n.has(e.id));return i.length===r.length||this.setAttachments(e,i)}setValues(e,t=`id`){let n=this._table.getTable(),i=[{recordId:this._recordId,values:H(n,e,t)}];return this._commandService.syncExecuteCommand(pe.id,{unitId:this._base.getId(),tableId:this._table.getId(),patches:i,source:r.Facade})}delete(){return this._commandService.syncExecuteCommand(te.id,{unitId:this._base.getId(),tableId:this._table.getId(),recordId:this._recordId,source:r.Facade})}duplicate(e){let t={...this._getRecord(),...e,id:F(6)};t.values={...t.values,...e==null?void 0:e.values},Reflect.deleteProperty(t.values,w);let n=Date.now();if(t.orderKey||=`${n}`,t.createdAt||=n,t.updatedAt||=n,!this._commandService.syncExecuteCommand(p.id,{unitId:this._base.getId(),tableId:this._table.getId(),sourceRecordId:this._recordId,record:t,source:r.Facade}))throw Error(`[FRecord]: failed to duplicate record "${this._recordId}".`);return this._injector.createInstance(J,this._base,this._table,t.id,this._injector)}setOrderKey(e){return this._commandService.syncExecuteCommand(Se.id,{unitId:this._base.getId(),tableId:this._table.getId(),recordId:this._recordId,orderKey:e})}getLinkedRecordIds(e){let t=this._getRecordLinkField(e),n=this.getValue(t.id);return x(n)}setLinkedRecordIds(e,t){let n=this._getRecordLinkField(e),i=ze(t),a=He(this._base.getBase().getSnapshot(),n,i);if(!a.valid)throw Error(a.reason??`[FRecord]: invalid RecordLink value.`);return this._commandService.syncExecuteCommand(h.id,{unitId:this._base.getId(),tableId:this._table.getId(),recordId:this._recordId,fieldId:e,value:i,source:r.Facade})}addLinkedRecord(e,t){let n=this._getRecordLinkField(e),r=Fe(n);if(!r)throw Error(`[FRecord]: RecordLink field "${e}" has invalid config.`);let i=this.getLinkedRecordIds(e);return r.multiple&&i.includes(t)?!0:this.setLinkedRecordIds(e,r.multiple?[...i,t]:[t])}removeLinkedRecord(e,t){let n=this.getLinkedRecordIds(e);return!n.includes(t)||this.setLinkedRecordIds(e,n.filter(e=>e!==t))}getParent(e){let t=this._getHierarchyIndex(e).parentByRecordId.get(this._recordId)??null;return t?this._table.getRecordById(t):null}getChildren(e){return(this._getHierarchyIndex(e).childrenByParentId.get(this._recordId)??[]).flatMap(e=>{let t=this._table.getRecordById(e);return t?[t]:[]})}getAncestors(e){let t=this._getHierarchyIndex(e),n=[],r=t.parentByRecordId.get(this._recordId)??null;for(;r;){let e=this._table.getRecordById(r);e&&n.push(e),r=t.parentByRecordId.get(r)??null}return n}getDescendants(e){let t=this._getHierarchyIndex(e),n=t.orderedRecordIds.indexOf(this._recordId),r=t.subtreeHeightByRecordId.has(this._recordId)?this._collectDescendantIds(t.childrenByParentId,this._recordId):[];return n<0?[]:r.flatMap(e=>{let t=this._table.getRecordById(e);return t?[t]:[]})}setParent(e,t,n){return this._commandService.syncExecuteCommand(oe.id,{unitId:this._base.getId(),tableId:this._table.getId(),fieldId:e,recordId:this._recordId,parentRecordId:t,orderKey:n,source:r.Facade})}addChild(e,t,n=`id`,i){let a=this._table.getTable(),o=Date.now(),s={...i,id:F(6),values:H(a,t,n),orderKey:(i==null?void 0:i.orderKey)||`${o}`,createdAt:(i==null?void 0:i.createdAt)||o,updatedAt:(i==null?void 0:i.updatedAt)||o};if(!this._commandService.syncExecuteCommand(c.id,{unitId:this._base.getId(),tableId:this._table.getId(),fieldId:e,parentRecordId:this._recordId,record:s,source:r.Facade}))throw Error(`[FRecord]: failed to create child under "${this._recordId}".`);return this._injector.createInstance(J,this._base,this._table,s.id,this._injector)}_getHierarchyIndex(e){return _(this._table.getTable(),e)}_collectDescendantIds(e,t){let n=[],r=t=>{for(let i of e.get(t)??[])n.push(i),r(i)};return r(t),n}_getRecord(){let e=this._table.getTable().records[this._recordId];if(!e)throw Error(`[FRecord]: record "${this._recordId}" does not exist.`);return e}_getRecordLinkField(e){let t=this._table.getTable().fields[e];if(!t||t.type!==T.RecordLink)throw Error(`[FRecord]: field "${e}" is not a RecordLink field.`);return t}_getAttachmentField(e){let t=this._table.getTable().fields[e];if(!t||t.type!==T.Attachment)throw Error(`[FRecord]: field "${e}" is not an Attachment field.`);return t}};Y=J=z([R(4,A),R(5,j)],Y);function gt(e){return!!(e&&typeof e==`object`&&`id`in e&&typeof e.id==`string`&&`name`in e&&typeof e.name==`string`)}function _t(e,t,n){if(!gt(e))throw Error(`[FRecord]: attachment at index ${n} in field "${t}" is invalid.`);return{...e}}let X=class{constructor(e,t,n,r,i,a,o){this._base=e,this._table=t,this._viewId=n,this._injector=r,this._commandService=i,this._permissionService=a,this._projectionService=o}getId(){return this._viewId}getPermission(){let e=this._table.getId();return new L(this._base.getId(),Pe(e,this._viewId),[b(e)],this._commandService,this._permissionService)}getView(){return this._getView()}getName(){return this._getView().name}getType(){return this._getView().type}setName(e){return this._commandService.syncExecuteCommand(le.id,{unitId:this._base.getId(),tableId:this._table.getId(),viewId:this._viewId,name:e})}getConfig(){let e=this.getType(),t=this._getView().config;switch(e){case O.Grid:return t;case O.Kanban:return t;case O.Calendar:return t;case O.Gantt:return t;case O.Gallery:return t;default:return t}}updateConfig(e){return this._commandService.syncExecuteCommand(Ce.id,{unitId:this._base.getId(),tableId:this._table.getId(),viewId:this._viewId,patch:e})}getConditionalColorRules(){var e;return N.deepClone(((e=this._getView().config.conditionalColoring)==null?void 0:e.rules)??[])}setConditionalColorRules(e){return this._commandService.syncExecuteCommand(g.id,{unitId:this._base.getId(),tableId:this._table.getId(),viewId:this._viewId,type:n.Set,rules:e})}addConditionalColorRule(e){return this._commandService.syncExecuteCommand(g.id,{unitId:this._base.getId(),tableId:this._table.getId(),viewId:this._viewId,type:n.Add,rule:e})}deleteConditionalColorRule(e){return this._commandService.syncExecuteCommand(g.id,{unitId:this._base.getId(),tableId:this._table.getId(),viewId:this._viewId,type:n.Delete,ruleId:e})}clearConditionalColorRules(){return this._commandService.syncExecuteCommand(g.id,{unitId:this._base.getId(),tableId:this._table.getId(),viewId:this._viewId,type:n.Clear})}getFilter(){return this._getView().filter??null}setFilter(e){return this._commandService.syncExecuteCommand(ve.id,{unitId:this._base.getId(),tableId:this._table.getId(),viewId:this._viewId,filter:e})}getSort(){return this._getView().sort??[]}setSort(e){return this._commandService.syncExecuteCommand(be.id,{unitId:this._base.getId(),tableId:this._table.getId(),viewId:this._viewId,sort:e})}getGroup(){return this._getView().group??[]}setGroup(e){return this._commandService.syncExecuteCommand(ye.id,{unitId:this._base.getId(),tableId:this._table.getId(),viewId:this._viewId,group:e})}getFieldSettings(e){var t;return V(this._table.getTable().fields[e])?((t=this._getView().fieldSettings)==null?void 0:t[e])??{}:{}}getVisibleFields(){let e=this._table.getTable(),t=this._getView();return(t.fieldOrder??e.fieldOrder).filter(n=>{var r;let i=e.fields[n];return V(i)&&!((r=t.fieldSettings)!=null&&(r=r[n])!=null&&r.hidden)}).map(e=>this._injector.createInstance(B,this._base,this._table,e))}setFieldVisible(e,t){return V(this._table.getTable().fields[e])?this._commandService.syncExecuteCommand(ge.id,{unitId:this._base.getId(),tableId:this._table.getId(),viewId:this._viewId,fieldId:e,visible:t}):!1}setFieldWidth(e,t){return V(this._table.getTable().fields[e])?this._commandService.syncExecuteCommand(_e.id,{unitId:this._base.getId(),tableId:this._table.getId(),viewId:this._viewId,fieldId:e,width:t}):!1}moveField(e,t){let n=this._table.getTable(),r=t.beforeFieldId??t.afterFieldId;return!V(n.fields[e])||!r||!V(n.fields[r])?!1:this._commandService.syncExecuteCommand(he.id,{unitId:this._base.getId(),tableId:this._table.getId(),viewId:this._viewId,fieldId:e,target:t})}move(e){return this._commandService.syncExecuteCommand(se.id,{unitId:this._base.getId(),tableId:this._table.getId(),viewId:this._viewId,target:e})}delete(){return this._commandService.syncExecuteCommand(re.id,{unitId:this._base.getId(),tableId:this._table.getId(),viewId:this._viewId})}getProjection(){return this._projectionService.getProjection(this._base.getBase().getSnapshot(),this._table.getId(),this._viewId)}_getView(){let e=this._table.getTable().views[this._viewId];if(!e)throw Error(`[FView]: view "${this._viewId}" does not exist.`);return e}};X=z([R(4,A),R(5,j),R(6,ie)],X);let Z=class{constructor(e,t,n,r,i,a){this._base=e,this._tableId=t,this._injector=n,this._commandService=r,this._permissionService=i,this._projectionService=a}getBase(){return this._base.getBase()}getTable(){return this._getTable()}getId(){return this._tableId}getPermission(){return new L(this.getBase().getUnitId(),b(this._tableId),[],this._commandService,this._permissionService)}getHierarchyFieldId(){return S(this._getTable())}setHierarchyField(e){return this._commandService.syncExecuteCommand(me.id,{unitId:this._base.getId(),tableId:this._tableId,fieldId:e})}getName(){return this._getTable().name}getFormulaName(){let e=this._base.getBase().getSnapshot();return Me(this._getTable(),e)}setName(e){let n=Ve(this._base.getBase().getSnapshot(),e,this._tableId);if(!n.valid)throw Error(`[FBaseTable]: invalid table name "${e}". ${t} ${n.reason}`);return this._commandService.syncExecuteCommand(ce.id,{unitId:this._base.getId(),tableId:this._tableId,name:e})}search(e,t){let n=this._base.getBase().getSnapshot(),r=this._getTable();if(t){let i=this._projectionService.getProjection(n,this._tableId,t),a=r.views[t],o=e.fieldIds??Tt(r,a,i),s=`rows`in i&&Array.isArray(i.rows)?i.rows:[];return Re({...e,table:r,fieldIds:o,rows:s})}let i=(r.recordOrder?r.recordOrder.map(e=>r.records[e]):Object.values(r.records).sort((e,t)=>e.orderKey.localeCompare(t.orderKey))).filter(e=>e).map(e=>({recordId:e.id,values:e.values})),a=e.fieldIds??r.fieldOrder.filter(e=>V(r.fields[e]));return Re({...e,table:r,fieldIds:a,rows:i})}getPrimaryFieldId(){return this._getTable().primaryFieldId}getFields(){let e=this._getTable();return e.fieldOrder.map(t=>e.fields[t]).filter(V).map(e=>this._injector.createInstance(B,this._base,this,e.id))}getFieldById(e){let t=this._getTable().fields[e];return V(t)?this._injector.createInstance(B,this._base,this,t.id):null}getFieldByName(e){let t=this._getTable().fields,n=Object.values(t).find(t=>V(t)&&t.name===e);return n?this._injector.createInstance(B,this._base,this,n.id):null}getPrimaryField(){let e=this._getTable().primaryFieldId;return this._injector.createInstance(B,this._base,this,e)}addField(e,t,n){var r,i;if(!Object.values(T).some(e=>e===t))throw Error(`Unsupported Base field type "${String(t)}".`);if(t===T.Formula&&this._prepareFormulaFieldReferences(e,n),t===T.RecordLink&&(typeof(n==null||(r=n.field)==null||(r=r.config)==null?void 0:r.targetTableId)!=`string`||typeof n.field.config.multiple!=`boolean`))throw Error(`RecordLink fields require config { targetTableId, multiple }.`);let a={...n==null?void 0:n.field,id:F(6),name:e,type:t,config:(n==null||(i=n.field)==null?void 0:i.config)??{}};if(!this._commandService.syncExecuteCommand(l.id,{unitId:this._base.getId(),tableId:this._tableId,field:a,index:n==null?void 0:n.index}))throw Error(`Failed to add field "${e}"`);return this._injector.createInstance(B,this._base,this,a.id)}_prepareFormulaFieldReferences(e,t){var n;if(!t||!(`externalReferences`in t)||!Array.isArray(t.externalReferences))throw Error(`Formula fields require options.externalReferences. Use [] only for a Host-local formula.`);let r=this._commandService.syncExecuteCommand(we.id,{unitId:this._base.getId(),tableId:this._tableId,formula:String(((n=t.field)==null||(n=n.config)==null?void 0:n.formula)??``)});if(!r.valid)throw Error(r.reason??`Invalid Base formula.`);if(t.externalReferences.length>0&&!this._commandService.syncExecuteCommand(it.id,{unitId:this._base.getId(),references:t.externalReferences}))throw Error(`Failed to bind External References for formula field "${e}"`)}getRecords(){return this._resolveRecordIds().map(e=>this._injector.createInstance(Y,this._base,this,e,this._injector))}getRecordById(e){return this._getTable().records[e]?this._injector.createInstance(Y,this._base,this,e,this._injector):null}queryRecords(e={}){let t=this._getTable(),n=this._resolveRecordIds(e),r=Math.max(0,e.offset??0),i=e.limit==null?null:Math.max(0,e.limit),a=yt(n.map(e=>t.records[e]).filter(n=>xt(n,t,e.filter)),t,e.sort);return{records:vt(a,e).map(e=>this._injector.createInstance(Y,this._base,this,e.id,this._injector)),total:a.length,offset:r,limit:i,hasMore:i!=null&&r+i<a.length}}addRecord(e,t=`id`,n){let i=this._getTable(),a=Date.now(),o={...n,id:F(6),values:H(i,e,t),orderKey:(n==null?void 0:n.orderKey)||`${a}`,createdAt:(n==null?void 0:n.createdAt)||a,updatedAt:(n==null?void 0:n.updatedAt)||a};if(!this._commandService.syncExecuteCommand(u.id,{unitId:this._base.getId(),tableId:this._tableId,record:o,source:r.Facade}))throw Error(`Failed to add record with id "${o.id}"`);return this._injector.createInstance(Y,this._base,this,o.id,this._injector)}addRecords(e){if(!e.length)return[];let t=this._getTable(),n=Date.now(),i=e.map((e,r)=>{var i,a,o;return{...e.record,id:F(6),values:H(t,e.values,e.fieldKey??`id`),orderKey:((i=e.record)==null?void 0:i.orderKey)||`${n+r}`,createdAt:((a=e.record)==null?void 0:a.createdAt)||n,updatedAt:((o=e.record)==null?void 0:o.updatedAt)||n}});if(!this._commandService.syncExecuteCommand(a.id,{unitId:this._base.getId(),tableId:this._tableId,records:i,source:r.Facade}))throw Error(`Failed to add records`);return i.map(e=>this._injector.createInstance(Y,this._base,this,e.id,this._injector))}deleteRecords(e){return!e.length||this._commandService.syncExecuteCommand(o.id,{unitId:this._base.getId(),tableId:this._tableId,recordIds:e,source:r.Facade})}getRange(e,t,n=1,r=1){return this._injector.createInstance(K,this._base,this,{startRow:e,endRow:e+n-1,startColumn:t,endColumn:t+r-1},this._injector)}getDataRange(){var e;let t=Oe(this._getTable()),n=((e=t.recordOrder)==null?void 0:e.length)??0,r=t.fieldOrder.filter(e=>V(t.fields[e])).length;return this.getRange(0,0,Math.max(n,1),Math.max(r,1))}getViews(){let e=this._getTable();return e.viewOrder.filter(t=>e.views[t]).map(e=>this._injector.createInstance(X,this._base,this,e,this._injector))}getViewById(e){return this._getTable().views[e]?this._injector.createInstance(X,this._base,this,e,this._injector):null}getViewByName(e){let t=this._getTable(),n=Object.values(t.views).find(t=>t.name===e);return n?this._injector.createInstance(X,this._base,this,n.id,this._injector):null}createView(e,t,n){var r,i,a,o;let s=this._getTable(),c=(n==null||(r=n.view)==null?void 0:r.fieldOrder)??s.fieldOrder,l=[w,...c.filter(e=>V(s.fields[e]))],u={...n==null?void 0:n.view,id:F(6),name:e,type:t,tableId:this._tableId,config:(n==null||(i=n.view)==null?void 0:i.config)??{},fieldOrder:l,fieldSettings:{...n==null||(a=n.view)==null?void 0:a.fieldSettings,[w]:{...n==null||(o=n.view)==null||(o=o.fieldSettings)==null?void 0:o[w],hidden:!0}}};if(!this._commandService.syncExecuteCommand(f.id,{unitId:this._base.getId(),tableId:this._tableId,view:u,index:n==null?void 0:n.index}))throw Error(`Failed to create view "${e}"`);return this._injector.createInstance(X,this._base,this,u.id,this._injector)}getSchema(){let e=this._getTable(),t=e.fieldOrder.filter(t=>V(e.fields[t])),n=e.viewOrder.filter(t=>e.views[t]);return{id:e.id,name:e.name,formulaName:this.getFormulaName(),primaryFieldId:e.primaryFieldId,fieldIds:t,viewIds:n,recordCount:this._resolveRecordIds().length,fields:t.map(t=>{let n=e.fields[t];return{id:n.id,name:n.name,type:n.type,config:n.config,readonly:n.readonly,description:n.description}}),views:n.map(t=>{let n=e.views[t];return{id:n.id,name:n.name,type:n.type}})}}_getTable(){let e=this._base.getBase().getSnapshot().tables[this._tableId];if(!e)throw Error(`[FTable]: table "${this._tableId}" does not exist.`);return e}_resolveRecordIds(e={}){let t=this._base.getBase().getSnapshot(),n=this._getTable();if(e.viewId){let n=this._projectionService.getProjection(t,this._tableId,e.viewId);if(`rows`in n&&Array.isArray(n.rows))return n.rows.map(e=>e.recordId)}return(n.recordOrder?n.recordOrder.map(e=>n.records[e]):Object.values(n.records).sort((e,t)=>e.orderKey.localeCompare(t.orderKey))).filter(e=>e).map(e=>e.id)}};Z=z([R(3,A),R(4,j),R(5,ie)],Z);function vt(e,t){let n=Math.max(0,t.offset??0);return t.limit==null?e.slice(n):e.slice(n,n+Math.max(0,t.limit))}function yt(e,t,n=[]){return n.length?[...e].sort((e,r)=>{for(let a of n){var i;let n=a.direction===D.DESC?-1:1,o=bt(e.values[a.fieldId],r.values[a.fieldId],(i=t.fields[a.fieldId])==null?void 0:i.type);if(o!==0)return o*n}return String(e.orderKey??e.id).localeCompare(String(r.orderKey??r.id))}):e}function bt(e,t,n){return e==null&&t==null?0:e==null?-1:t==null?1:typeof e==`number`&&typeof t==`number`?e-t:n===T.Date?Number(e)-Number(t):String(e).localeCompare(String(t))}function xt(e,t,n){var r;if(!n||!((r=n.conditions)!=null&&r.length))return!0;let{conjunction:i=E.OR,conditions:a}=n;return i===E.AND&&a.length>1?a.every(n=>St(e,t,n)):a.some(n=>St(e,t,n))}function St(e,t,n){let r=e.values[n.fieldId],i=t.fields[n.fieldId];if(Ct(n)){let e=wt(n).test(String(r??``));return n.operator===`matches`?e:!e}return!i||Ie(r,n.operator,n.value,i)}function Ct(e){return e.operator===`matches`||e.operator===`notMatches`}function wt(e){let t=String(e.value??``);if(t.length>512)throw Error(`Base regex filter is too long. Maximum length is 512.`);try{return new RegExp(t,e.caseSensitive?void 0:`i`)}catch(e){throw Error(`Invalid Base regex filter: ${t}. ${e instanceof Error?e.message:String(e)}`)}}function Tt(e,t,n){if(n.type!==`invalid`&&n.type!==`custom`){var r;if(n.type===O.Kanban){var i;let t=[((i=n.fields)==null||(i=i[0])==null?void 0:i.id)??e.primaryFieldId,...n.visibleCardFieldIds??[]];return Array.from(new Set(t.filter(t=>!!e.fields[t])))}if((r=n.fields)!=null&&r.length)return n.fields.map(e=>e.id).filter(n=>{var r;return!(!e.fields[n]||t!=null&&(r=t.fieldSettings)!=null&&(r=r[n])!=null&&r.hidden)})}return e.fieldOrder.filter(n=>{var r;return!(!e.fields[n]||t!=null&&(r=t.fieldSettings)!=null&&(r=r[n])!=null&&r.hidden)})}let Q=class extends $e.FBase{constructor(e,t,n,r,i){super(),this._base=e,this._injector=t,this._resourceLoaderService=n,this._commandService=r,this._permissionService=i}getBase(){return this._base}getId(){return this._base.getUnitId()}getPermission(){return new at(this.getId(),this._commandService,this._permissionService)}save(){return this._resourceLoaderService.saveUnit(this.getId())??N.deepClone(this._base.getSnapshot())}getName(){return this._base.getSnapshot().name}setName(e){this._commandService.syncExecuteCommand(ue.id,{unitId:this.getId(),name:e})}getTables(){let e=this._base.getSnapshot();return e.tableOrder.map(t=>e.tables[t]).filter(e=>e).map(e=>this._injector.createInstance(Z,this,e.id,this._injector))}getTableById(e){let t=this._base.getSnapshot().tables[e];return t?this._injector.createInstance(Z,this,t.id,this._injector):null}getTableByName(e){let t=this._base.getSnapshot(),n=Object.values(t.tables).find(t=>t.name===e);return n?this._injector.createInstance(Z,this,n.id,this._injector):null}insertTable(e,n){let r=Qe({id:F(),name:e,...n==null?void 0:n.table,primaryFieldName:n==null?void 0:n.primaryFieldName}),i=N.commonExtend(r,(n==null?void 0:n.table)??{}),a=Ve(this._base.getSnapshot(),i.name);if(!a.valid)throw Error(`[FBase]: invalid table name "${i.name}". ${t} ${a.reason}`);if(!this._commandService.syncExecuteCommand(d.id,{unitId:this._base.getUnitId(),table:i,index:n==null?void 0:n.index}))throw Error(`Failed to create table "${e}".`);return this._injector.createInstance(Z,this,i.id,this._injector)}deleteTable(e){let t=typeof e==`string`?e:e.getId();if(!this._commandService.syncExecuteCommand(ne.id,{unitId:this._base.getUnitId(),tableId:t}))throw Error(`Failed to delete table "${t}".`);return!0}duplicateTable(e,t){let n=this._base.getSnapshot(),r=typeof e==`string`?e:e.getId(),i=n.tables[r];if(!i)throw Error(`[FBase]: table "${r}" does not exist.`);let a=n.tableOrder.indexOf(r)+1,o=F(),s=Ee(i,{id:o,name:De(n,`${i.name} Copy`),includeRecords:(t==null?void 0:t.includeRecords)??!1,regenerateViewIds:(t==null?void 0:t.regenerateViewIds)??!1});if(!this._commandService.syncExecuteCommand(d.id,{unitId:this._base.getUnitId(),table:s,index:a}))throw Error(`Failed to duplicate table "${r}".`);return this._injector.createInstance(Z,this,s.id,this._injector)}getSchema(){let e=this._base.getSnapshot();return{id:e.id,name:e.name,tables:this.getTables().map(e=>e.getSchema())}}};Q=z([R(1,Xe(Ze)),R(2,Ye),R(3,A),R(4,j)],Q);var Et=class extends rt{_initialize(){this._initBaseBeforeEvents(),this._initBaseAfterEvents()}createBase(e={},t){let n=this._univerInstanceService.createUnit(P.UNIVER_BASE,e,t);return this._injector.createInstance(Q,n)}getActiveBase(){let e=this._univerInstanceService.getCurrentUnitOfType(P.UNIVER_BASE);return e?this._injector.createInstance(Q,e):null}getBase(e){let t=this._univerInstanceService.getUnit(e,P.UNIVER_BASE);return t?this._injector.createInstance(Q,t):null}getBases(){return this._univerInstanceService.getAllUnitsForType(P.UNIVER_BASE).map(e=>this._injector.createInstance(Q,e))}_initBaseAfterEvents(){this.disposeWithMe(this.registerEventHandler(this.Event.BaseHierarchyChanged,()=>this._commandService.onCommandExecuted((t,n)=>{var i;if(!$(t,e))return;let a=t.params;if(!((i=a.hierarchyChanges)!=null&&i.length))return;let o=this.getBase(a.unitId),s=o==null?void 0:o.getTableById(a.hierarchyChanges[0].tableId);if(!o||!s)return;let c={base:o,table:s,changes:a.hierarchyChanges,source:n!=null&&n.fromCollab?r.Remote:a.source??r.UI};this.fireEvent(this.Event.BaseHierarchyChanged,c)}))),this.disposeWithMe(this.registerEventHandler(this.Event.BaseTableCreated,()=>this._commandService.onCommandExecuted(e=>{if(e.id!==d.id)return;let{unitId:t,table:n,index:r}=e.params,i=this.getBase(t);if(!i)return;let a={base:i,table:n,index:r};this.fireEvent(this.Event.BaseTableCreated,a)}))),this.disposeWithMe(this.registerEventHandler(this.Event.BaseTableFieldCreated,()=>this._commandService.onCommandExecuted(e=>{if(e.id!==l.id)return;let{unitId:t,tableId:n,field:r,index:i,viewIndexes:a}=e.params,o=this.getBase(t);if(!o)return;let s=o.getTableById(n);if(!s)return;let c={base:o,table:s,field:r,index:i,viewIndexes:a};this.fireEvent(this.Event.BaseTableFieldCreated,c)}))),this.disposeWithMe(this.registerEventHandler(this.Event.BaseTableRecordCreated,()=>this._commandService.onCommandExecuted(e=>{if(e.id!==u.id&&e.id!==a.id)return;let t=e.params,{unitId:n,tableId:r}=t,i=t.records??[t.record],o=this.getBase(n);if(!o)return;let s=o.getTableById(r);if(!s)return;let c={base:o,table:s,records:i};this.fireEvent(this.Event.BaseTableRecordCreated,c)}))),this.disposeWithMe(this.registerEventHandler(this.Event.BaseTableViewCreated,()=>this._commandService.onCommandExecuted(e=>{if(e.id!==f.id)return;let{unitId:t,tableId:n,view:r,index:i}=e.params,a=this.getBase(t);if(!a)return;let o=a.getTableById(n);if(!o)return;let s={base:a,table:o,view:r,index:i};this.fireEvent(this.Event.BaseTableViewCreated,s)}))),this.disposeWithMe(this.registerEventHandler(this.Event.BaseTableCellValueChanged,()=>this._commandService.onCommandExecuted(e=>{if(e.id!==h.id)return;let{unitId:t,tableId:n,recordId:r,fieldId:i,value:a}=e.params,o=this.getBase(t);if(!o)return;let s=o.getTableById(n);if(!s)return;let c=s.getFieldById(i);if(!c)return;let l=s.getRecordById(r);if(!l)return;let u={base:o,table:s,field:c,record:l,value:a};this.fireEvent(this.Event.BaseTableCellValueChanged,u)})))}_initBaseBeforeEvents(){this.disposeWithMe(this.registerEventHandler(this.Event.BeforeBaseHierarchyChange,()=>this._commandService.beforeCommandExecuted(e=>{if($(e,pe)){let{unitId:t,tableId:n,patches:i,source:a=r.UI}=e.params,o=this._getHierarchyEventContext(t,n);if(!o)return;this._fireBeforeHierarchyChange(o.base,o.table,Be(o.table.getTable(),i),a);return}if($(e,fe)){let{unitId:t,tableId:n,patches:i,source:a=r.UI}=e.params,o=this._getHierarchyEventContext(t,n);if(!o)return;let s=o.table.getTable();this._fireBeforeHierarchyChange(o.base,o.table,Be(s,Le(s,i)),a);return}if($(e,u)){let t=e.params,n=this._getHierarchyEventContext(t.unitId,t.tableId);if(!n)return;this._fireBeforeHierarchyChange(n.base,n.table,C(n.table.getTable(),[t.record]),t.source??r.UI);return}if($(e,a)){let t=e.params,n=this._getHierarchyEventContext(t.unitId,t.tableId);if(!n)return;this._fireBeforeHierarchyChange(n.base,n.table,C(n.table.getTable(),t.records),t.source??r.UI);return}if($(e,p)){let t=e.params,n=this._getHierarchyEventContext(t.unitId,t.tableId);if(!n)return;this._fireBeforeHierarchyChange(n.base,n.table,C(n.table.getTable(),[t.record]),t.source??r.UI);return}if($(e,oe)){let t=e.params,n=this._getHierarchyEventContext(t.unitId,t.tableId);if(!n)return;let i=n.table.getTable(),a=t.fieldId??S(i),o=_(i,a).parentByRecordId.get(t.recordId)??null;this._fireBeforeHierarchyChange(n.base,n.table,[{tableId:t.tableId,fieldId:a,recordId:t.recordId,oldParentRecordId:o,parentRecordId:t.parentRecordId}],t.source??r.UI);return}if($(e,c)){let t=e.params,n=this._getHierarchyEventContext(t.unitId,t.tableId);if(!n)return;let i=t.fieldId??S(n.table.getTable());this._fireBeforeHierarchyChange(n.base,n.table,[{tableId:t.tableId,fieldId:i,recordId:t.record.id,oldParentRecordId:null,parentRecordId:t.parentRecordId}],t.source??r.UI);return}if($(e,te)){let t=e.params,n=this._getHierarchyEventContext(t.unitId,t.tableId);if(!n)return;this._fireBeforeHierarchyChange(n.base,n.table,v(n.table.getTable(),[t.recordId]),t.source??r.UI);return}if($(e,o)){let t=e.params,n=this._getHierarchyEventContext(t.unitId,t.tableId);if(!n)return;this._fireBeforeHierarchyChange(n.base,n.table,v(n.table.getTable(),t.recordIds),t.source??r.UI);return}if(!$(e,h))return;let t=e.params,n=this._getHierarchyEventContext(t.unitId,t.tableId);if(!n)return;let i=n.table.getTable();if(!ke(i).includes(t.fieldId))return;let s=_(i,t.fieldId).parentByRecordId.get(t.recordId)??null,l=x(t.value)[0]??null;s!==l&&this._fireBeforeHierarchyChange(n.base,n.table,[{tableId:t.tableId,fieldId:t.fieldId,recordId:t.recordId,oldParentRecordId:s,parentRecordId:l}],t.source??r.UI)}))),this.disposeWithMe(this.registerEventHandler(this.Event.BeforeBaseTableCreate,()=>this._commandService.beforeCommandExecuted(e=>{if(e.id!==d.id)return;let{unitId:t,table:n,index:r}=e.params,i=this.getBase(t);if(!i)return;let a={base:i,table:n,index:r};if(this.fireEvent(this.Event.BeforeBaseTableCreate,a),a.cancel)throw new k}))),this.disposeWithMe(this.registerEventHandler(this.Event.BeforeBaseTableFieldCreate,()=>this._commandService.beforeCommandExecuted(e=>{if(e.id!==l.id)return;let{unitId:t,tableId:n,field:r,index:i,viewIndexes:a}=e.params,o=this.getBase(t);if(!o)return;let s=o.getTableById(n);if(!s)return;let c={base:o,table:s,field:r,index:i,viewIndexes:a};if(this.fireEvent(this.Event.BeforeBaseTableFieldCreate,c),c.cancel)throw new k}))),this.disposeWithMe(this.registerEventHandler(this.Event.BeforeBaseTableRecordCreate,()=>this._commandService.beforeCommandExecuted(e=>{if(e.id!==u.id&&e.id!==a.id)return;let t=e.params,{unitId:n,tableId:r}=t,i=t.records??[t.record],o=this.getBase(n);if(!o)return;let s=o.getTableById(r);if(!s)return;let c={base:o,table:s,records:i};if(this.fireEvent(this.Event.BeforeBaseTableRecordCreate,c),c.cancel)throw new k}))),this.disposeWithMe(this.registerEventHandler(this.Event.BeforeBaseTableViewCreate,()=>this._commandService.beforeCommandExecuted(e=>{if(e.id!==f.id)return;let{unitId:t,tableId:n,view:r,index:i}=e.params,a=this.getBase(t);if(!a)return;let o=a.getTableById(n);if(!o)return;let s={base:a,table:o,view:r,index:i};if(this.fireEvent(this.Event.BeforeBaseTableViewCreate,s),s.cancel)throw new k}))),this.disposeWithMe(this.registerEventHandler(this.Event.BeforeBaseTableCellValueChange,()=>this._commandService.beforeCommandExecuted(e=>{if(e.id!==h.id)return;let{unitId:t,tableId:n,recordId:r,fieldId:i,value:a}=e.params,o=this.getBase(t);if(!o)return;let s=o.getTableById(n);if(!s)return;let c=s.getFieldById(i);if(!c)return;let l=s.getRecordById(r);if(!l)return;let u={base:o,table:s,field:c,record:l,value:a};if(this.fireEvent(this.Event.BeforeBaseTableCellValueChange,u),u.cancel)throw new k})))}_getHierarchyEventContext(e,t){let n=this.getBase(e),r=n==null?void 0:n.getTableById(t);return n&&r?{base:n,table:r}:null}_fireBeforeHierarchyChange(e,t,n,r){if(!n.length)return;let i={base:e,table:t,changes:n,source:r};if(this.fireEvent(this.Event.BeforeBaseHierarchyChange,i),i.cancel)throw new k}};function $(e,t){return e.id===t.id&&e.params!==void 0}rt.extend(Et);var Dt=class extends tt{get BaseFieldType(){return T}get BaseFilterConjunction(){return E}get BaseFilterOperator(){return Ke}get BaseFieldKeyEnum(){return ot}get BaseViewType(){return O}get BaseConditionalColorTarget(){return We}get BaseConditionalColorOperator(){return Ue}get BaseConditionalDateMode(){return Ge}get BaseSortDirection(){return D}get BaseEventSource(){return r}get BaseHierarchyErrorCode(){return i}get BaseHierarchyInvalidReason(){return qe}get BaseRecordLinkRole(){return Je}};tt.extend(Dt);var Ot=class extends nt{get BaseTableCreated(){return`BaseTableCreated`}get BeforeBaseTableCreate(){return`BeforeBaseTableCreate`}get BaseTableFieldCreated(){return`BaseTableFieldCreated`}get BeforeBaseTableFieldCreate(){return`BeforeBaseTableFieldCreate`}get BaseTableRecordCreated(){return`BaseTableRecordCreated`}get BeforeBaseTableRecordCreate(){return`BeforeBaseTableRecordCreate`}get BaseTableViewCreated(){return`BaseTableViewCreated`}get BeforeBaseTableViewCreate(){return`BeforeBaseTableViewCreate`}get BaseTableCellValueChanged(){return`BaseTableCellValueChanged`}get BeforeBaseTableCellValueChange(){return`BeforeBaseTableCellValueChange`}get BaseHierarchyChanged(){return`BaseHierarchyChanged`}get BeforeBaseHierarchyChange(){return`BeforeBaseHierarchyChange`}};nt.extend(Ot);export{ot as BaseFieldKeyEnum,Q as FBase,L as FBaseObjectPermission,at as FBasePermission,Z as FBaseTable,B as FBaseTableField,K as FBaseTableRange,Y as FBaseTableRecord,X as FBaseTableView,Ot as FBasesEventNameMixin,ct as resolveBaseFieldKey,H as resolveBaseFieldValues};
1
+ import{ApplyBaseJson1Mutation as e,BASE_TABLE_NAME_REQUIREMENTS as t,BaseConditionalColorRuleUpdateType as n,BaseEventSource as r,BaseHierarchyErrorCode as i,BatchCreateBaseRecordsCommand as a,BatchDeleteBaseRecordsCommand as o,ChangeBaseFieldTypeCommand as s,CreateBaseChildRecordCommand as c,CreateBaseFieldCommand as l,CreateBaseRecordCommand as u,CreateBaseTableCommand as d,CreateBaseViewCommand as f,DeleteBaseFieldCommand as ee,DeleteBaseRecordCommand as te,DeleteBaseTableCommand as ne,DeleteBaseViewCommand as re,DuplicateBaseRecordCommand as p,IBaseProjectionService as ie,MoveBaseFieldCommand as ae,MoveBaseHierarchyRecordCommand as oe,MoveBaseViewCommand as se,RenameBaseTableCommand as ce,RenameBaseViewCommand as le,SetBaseNameCommand as ue,SetBasePermissionCommand as m,SetBasePermissionsCommand as de,SetBaseRangeValuesCommand as fe,SetBaseRecordValuesCommand as pe,SetBaseTableHierarchyFieldCommand as me,SetBaseViewFieldOrderCommand as he,SetBaseViewFieldVisibleCommand as ge,SetBaseViewFieldWidthCommand as _e,SetBaseViewFilterCommand as ve,SetBaseViewGroupCommand as ye,SetBaseViewSortCommand as be,UpdateBaseCellCommand as h,UpdateBaseFieldCommand as xe,UpdateBaseRecordOrderCommand as Se,UpdateBaseViewConditionalColorRulesCommand as g,UpdateBaseViewConfigCommand as Ce,ValidateBaseFormulaCommand as we,buildBaseHierarchyIndex as _,canEditBaseTargets as Te,copyBaseTableSnapshot as Ee,createUniqueBaseTableName as De,ensureBaseTableCellLayout as Oe,getActiveBaseHierarchyFieldIds as ke,getBaseCellValue as Ae,getBaseFieldPermissionObjectId as je,getBaseFormulaTableName as Me,getBaseHierarchyDeletePromotions as v,getBasePermissionValue as y,getBaseRecordPermissionObjectId as Ne,getBaseTablePermissionObjectId as b,getBaseViewPermissionObjectId as Pe,getRecordLinkFieldConfig as Fe,matchesBaseCondition as Ie,parseRecordLinkIds as x,resolveBaseHierarchyFieldId as S,resolveBaseRangeHierarchyPatches as Le,searchBaseTable as Re,serializeRecordLinkIds as ze,validateBaseHierarchyRecordCreations as C,validateBaseHierarchyRecordPatches as Be,validateBaseTableName as Ve,validateRecordLinkValue as He}from"@univerjs-pro/bases";import{BASE_RECORD_ID_FIELD_ID as w,BaseConditionalColorOperator as Ue,BaseConditionalColorTarget as We,BaseConditionalDateMode as Ge,BaseFieldType as T,BaseFilterConjunction as E,BaseFilterOperator as Ke,BaseHierarchyInvalidReason as qe,BaseRecordLinkRole as Je,BaseSortDirection as D,BaseViewType as O,CanceledError as k,ICommandService as A,IPermissionService as j,IResourceLoaderService as Ye,ImageSourceType as M,Inject as Xe,Injector as Ze,Tools as N,UniverInstanceType as P,createDefaultBaseTableSnapshot as Qe,generateRandomId as F}from"@univerjs/core";import*as $e from"@univerjs/core/facade";import{FBaseInitialable as et,FEnum as tt,FEventName as nt,FUniver as rt}from"@univerjs/core/facade";import{UnitAction as I}from"@univerjs/protocol";import{UpsertHostExternalReferencesCommand as it}from"@univerjs/engine-formula";var at=class{constructor(e,t,n){this._unitId=e,this._commandService=t,this._permissionService=n}async setObjectPermissions(e){return this._commandService.executeCommand(de.id,{unitId:this._unitId,changes:e})}async setPoint(e,t){await this._commandService.executeCommand(m.id,{unitId:this._unitId,objectId:this._unitId,action:e,value:t})}getPoint(e){return y(this._permissionService,this._unitId,this._unitId,e)}async setEditable(e=!0){await this._commandService.executeCommand(m.id,{unitId:this._unitId,objectId:this._unitId,action:I.Edit,value:e})}async setReadOnly(){await this._commandService.executeCommand(m.id,{unitId:this._unitId,objectId:this._unitId,action:I.Edit,value:!1})}canEdit(){return y(this._permissionService,this._unitId,this._unitId,I.Edit)}},L=class{constructor(e,t,n,r,i){this._unitId=e,this._objectId=t,this._parentObjectIds=n,this._commandService=r,this._permissionService=i}async setEditable(e=!0){await this._commandService.executeCommand(m.id,{unitId:this._unitId,objectId:this._objectId,action:I.Edit,value:e})}async setReadOnly(){await this._commandService.executeCommand(m.id,{unitId:this._unitId,objectId:this._objectId,action:I.Edit,value:!1})}canEdit(){return Te(this._permissionService,this._unitId,[...this._parentObjectIds,this._objectId])}};function R(e,t){return function(n,r){t(n,r,e)}}function z(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}let B=class{constructor(e,t,n,r,i){this._base=e,this._table=t,this._fieldId=n,this._commandService=r,this._permissionService=i}getId(){return this._fieldId}getPermission(){let e=this._table.getId();return new L(this._base.getId(),je(e,this._fieldId),[b(e)],this._commandService,this._permissionService)}getField(){return this._getField()}getName(){return this._getField().name}getType(){return this._getField().type}getConfig(){return this._getField().config}getDefaultValue(){return this._getField().defaultValue}getDescription(){return this._getField().description}isReadonly(){return!!this._getField().readonly}setName(e){return this.update({name:e})}setConfig(e,t){return this.update({config:e},t)}setDefaultValue(e){return this.update({defaultValue:e})}update(e,t){let n=this._getField().type;return(e.type??n)===T.Formula&&(Object.prototype.hasOwnProperty.call(e,`config`)||e.type===T.Formula)&&!this._writeFormulaExternalReferences(t)?!1:this._commandService.syncExecuteCommand(xe.id,{unitId:this._base.getId(),tableId:this._table.getId(),fieldId:this._fieldId,patch:e})}changeType(e,t={},n){return e===T.Formula&&!this._writeFormulaExternalReferences(n)?!1:this._commandService.syncExecuteCommand(s.id,{unitId:this._base.getId(),tableId:this._table.getId(),fieldId:this._fieldId,input:{type:e,config:t}})}delete(){return this._commandService.syncExecuteCommand(ee.id,{unitId:this._base.getId(),tableId:this._table.getId(),fieldId:this._fieldId})}move(e){return this._commandService.syncExecuteCommand(ae.id,{unitId:this._base.getId(),tableId:this._table.getId(),fieldId:this._fieldId,target:e})}_getField(){let e=this._table.getTable().fields[this._fieldId];if(!e)throw Error(`[FField]: field "${this._fieldId}" does not exist.`);return e}_writeFormulaExternalReferences(e){if(!e||!Array.isArray(e.externalReferences))return console.warn(`[Base Field Facade]: Formula writes require { externalReferences }. Use [] only for a Host-local formula.`),!1;if(e.externalReferences.length===0)return!0;let t=this._commandService.syncExecuteCommand(it.id,{unitId:this._base.getId(),references:e.externalReferences});return t||console.warn(`[Base Field Facade]: Failed to bind External References.`),t}};B=z([R(3,A),R(4,j)],B);let ot=/* @__PURE__ */ function(e){return e.Id=`id`,e.Name=`name`,e.Auto=`auto`,e}({});function V(e){return!!(e&&e.system!==!0&&e.type!==T.RecordId)}function H(e,t,n=`id`){if(!t)return{};let r={};return Object.entries(t).forEach(([t,i])=>{let a=ct(e,t,n);r[a]=st(e.fields[a],i)}),r}function st(e,t){if((e==null?void 0:e.type)!==T.Attachment||t==null)return t;if(!Array.isArray(t))throw TypeError(`Invalid attachment value for field "${e.name}": expected an array.`);return t.map((t,n)=>lt(e,t,n))}function ct(e,t,n){if(n===`id`||n===`auto`&&e.fields[t])return t;let r=Object.values(e.fields).filter(e=>e.name===t);if(r.length===1)return r[0].id;throw r.length>1?Error(`Duplicate Base field name: ${t}`):Error(`Base field not found: ${t}`)}function lt(e,t,n){let r=`Invalid attachment at index ${n} for field "${e.name}"`;if(!ft(t))throw TypeError(`${r}: expected an object.`);if(`url`in t)throw TypeError(`${r}: "url" is not supported; use "source".`);if(`type`in t)throw TypeError(`${r}: "type" is not supported; use "mimeType".`);let i=U(t.id,r,`id`),a=U(t.name,r,`name`),o=U(t.source,r,`source`);return{id:i,name:a,source:o,sourceType:ut(t.sourceType,o,r),...dt(t,`mimeType`,r),...W(t,`size`,r),...W(t,`width`,r),...W(t,`height`,r),...dt(t,`thumbnail`,r)}}function ut(e,t,n){if(e==null)return t.startsWith(`data:`)?M.BASE64:M.URL;if(e===M.URL||e===M.UUID||e===M.BASE64)return e;throw TypeError(`${n}: "sourceType" must be URL, UUID, or BASE64.`)}function U(e,t,n){if(typeof e!=`string`||!e.trim())throw TypeError(`${t}: "${n}" must be a non-empty string.`);return e}function dt(e,t,n){let r=e[t];if(r==null)return{};if(typeof r!=`string`||!r.trim())throw TypeError(`${n}: "${t}" must be a non-empty string when provided.`);return{[t]:r}}function W(e,t,n){let r=e[t];if(r==null)return{};if(typeof r!=`number`||!Number.isFinite(r)||r<0)throw TypeError(`${n}: "${t}" must be a non-negative finite number when provided.`);return{[t]:r}}function ft(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var G;let K=G=class{constructor(e,t,n,r,i){this._base=e,this._table=t,this._range=n,this._inject=r,this._commandService=i,this._assertInBounds()}getBaseId(){return this._base.getId()}getTableId(){return this._table.getId()}getRange(){return{...this._range}}getRow(){return this._range.startRow}getColumn(){return this._range.startColumn}getNumRows(){return this._range.endRow-this._range.startRow+1}getNumColumns(){return this._range.endColumn-this._range.startColumn+1}getValues(){let e=this._getTable(),t=this._getFieldIds(e),n=[];for(let i=this._range.startRow;i<=this._range.endRow;i++){var r;let a=(r=e.rowId)==null?void 0:r[i],o=[];for(let n=this._range.startColumn;n<=this._range.endColumn;n++){let r=t[n];o.push(a&&r?Ae(e,a,r):null)}n.push(o)}return n}getValue(){var e;return((e=this.getValues()[0])==null?void 0:e[0])??null}setValue(e){return this.setValues([[e]])}setValues(e){let t=this.getNumRows(),n=this.getNumColumns();if(e.length>t||e.some(e=>e.length>n)){var i;throw Error(`[FBaseRange]: values size ${e.length}x${((i=e[0])==null?void 0:i.length)??0} exceeds range size ${t}x${n}.`)}let a=this._getTable(),o=this._getFieldIds(a),s=e.flatMap((e,t)=>e.map((e,n)=>{var r;let i=this._range.startRow+t,s=o[this._range.startColumn+n],c=(r=a.rowId)==null?void 0:r[i];if(!s||!c)throw Error(`[FBaseRange]: cannot resolve the public Base range address.`);return{recordId:c,fieldId:s,value:e}}));return this._commandService.syncExecuteCommand(fe.id,{unitId:this._base.getId(),tableId:this._table.getId(),patches:s,source:r.Facade})}clear(){return this.setValues(Array.from({length:this.getNumRows()},()=>Array.from({length:this.getNumColumns()},()=>null)))}offset(e,t,n=this.getNumRows(),r=this.getNumColumns()){return this._inject.createInstance(G,this._base,this._table,{startRow:this._range.startRow+e,startColumn:this._range.startColumn+t,endRow:this._range.startRow+e+n-1,endColumn:this._range.startColumn+t+r-1},this._inject)}_getTable(){let e=this._table.getTable();if(!e)throw Error(`[FBaseRange]: table does not exist.`);return Oe(e)}_assertInBounds(){var e;let t=this._getTable(),n=((e=t.recordOrder)==null?void 0:e.length)??0,r=this._getFieldIds(t).length;if(this._range.startRow<0||this._range.startColumn<0||this._range.endRow<this._range.startRow||this._range.endColumn<this._range.startColumn||this._range.endRow>=Math.max(n,1)||this._range.endColumn>=Math.max(r,1))throw Error(`[FBaseRange]: range is out of bounds. Max rows: ${n}, max columns: ${r}, range: ${JSON.stringify(this._range)}.`)}_getFieldIds(e){return e.fieldOrder.filter(t=>V(e.fields[t]))}};K=G=z([R(4,A)],K);function q(e){"@babel/helpers - typeof";return q=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},q(e)}function pt(e,t){if(q(e)!=`object`||!e)return e;var n;if(typeof Symbol<`u`&&(n=e[Symbol.toPrimitive])!==void 0){var r=n.call(e,t||`default`);if(q(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function mt(e){var t=pt(e,`string`);return q(t)==`symbol`?t:t+``}function ht(e,t,n){return(t=mt(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var J;let Y=J=class extends et{constructor(e,t,n,r,i,a){super(r),this._base=e,this._table=t,this._recordId=n,this._injector=r,this._commandService=i,this._permissionService=a,ht(this,`_baseUnitId`,void 0),ht(this,`_baseTableId`,void 0),this._baseUnitId=e.getId(),this._baseTableId=t.getId()}getBaseFacade(){return this._base}getTableFacade(){return this._table}getId(){return this._recordId}getPermission(){let e=this._table.getId();return new L(this._base.getId(),Ne(e,this._recordId),[b(e)],this._commandService,this._permissionService)}getRecord(){return{...this._getRecord(),values:this.getValues()}}getValue(e){return V(this._table.getTable().fields[e])?this._getRecord().values[e]??null:null}getValues(){let e=this._table.getTable();return Object.fromEntries(Object.entries(this._getRecord().values).filter(([t])=>V(e.fields[t])))}setValue(e,t){let n=this._table.getTable().fields[e];return this._commandService.syncExecuteCommand(h.id,{unitId:this._base.getId(),tableId:this._table.getId(),recordId:this._recordId,fieldId:e,value:st(n,t),source:r.Facade})}setAttachments(e,t){return this.setValue(e,t.map(e=>({...e})))}getAttachments(e){this._getAttachmentField(e);let t=this.getValue(e);return Array.isArray(t)?t.map((t,n)=>_t(t,e,n)):[]}deleteAttachments(e,t){this._getAttachmentField(e);let n=new Set(t.map(e=>e.id));if(!n.size)return!0;let r=this.getAttachments(e),i=r.filter(e=>!n.has(e.id));return i.length===r.length||this.setAttachments(e,i)}setValues(e,t=`id`){let n=this._table.getTable(),i=[{recordId:this._recordId,values:H(n,e,t)}];return this._commandService.syncExecuteCommand(pe.id,{unitId:this._base.getId(),tableId:this._table.getId(),patches:i,source:r.Facade})}delete(){return this._commandService.syncExecuteCommand(te.id,{unitId:this._base.getId(),tableId:this._table.getId(),recordId:this._recordId,source:r.Facade})}duplicate(e){let t={...this._getRecord(),...e,id:F(6)};t.values={...t.values,...e==null?void 0:e.values},Reflect.deleteProperty(t.values,w);let n=Date.now();if(t.orderKey||=`${n}`,t.createdAt||=n,t.updatedAt||=n,!this._commandService.syncExecuteCommand(p.id,{unitId:this._base.getId(),tableId:this._table.getId(),sourceRecordId:this._recordId,record:t,source:r.Facade}))throw Error(`[FRecord]: failed to duplicate record "${this._recordId}".`);return this._injector.createInstance(J,this._base,this._table,t.id,this._injector)}setOrderKey(e){return this._commandService.syncExecuteCommand(Se.id,{unitId:this._base.getId(),tableId:this._table.getId(),recordId:this._recordId,orderKey:e})}getLinkedRecordIds(e){let t=this._getRecordLinkField(e),n=this.getValue(t.id);return x(n)}setLinkedRecordIds(e,t){let n=this._getRecordLinkField(e),i=ze(t),a=He(this._base.getBase().getSnapshot(),n,i);if(!a.valid)throw Error(a.reason??`[FRecord]: invalid RecordLink value.`);return this._commandService.syncExecuteCommand(h.id,{unitId:this._base.getId(),tableId:this._table.getId(),recordId:this._recordId,fieldId:e,value:i,source:r.Facade})}addLinkedRecord(e,t){let n=this._getRecordLinkField(e),r=Fe(n);if(!r)throw Error(`[FRecord]: RecordLink field "${e}" has invalid config.`);let i=this.getLinkedRecordIds(e);return r.multiple&&i.includes(t)?!0:this.setLinkedRecordIds(e,r.multiple?[...i,t]:[t])}removeLinkedRecord(e,t){let n=this.getLinkedRecordIds(e);return!n.includes(t)||this.setLinkedRecordIds(e,n.filter(e=>e!==t))}getParent(e){let t=this._getHierarchyIndex(e).parentByRecordId.get(this._recordId)??null;return t?this._table.getRecordById(t):null}getChildren(e){return(this._getHierarchyIndex(e).childrenByParentId.get(this._recordId)??[]).flatMap(e=>{let t=this._table.getRecordById(e);return t?[t]:[]})}getAncestors(e){let t=this._getHierarchyIndex(e),n=[],r=t.parentByRecordId.get(this._recordId)??null;for(;r;){let e=this._table.getRecordById(r);e&&n.push(e),r=t.parentByRecordId.get(r)??null}return n}getDescendants(e){let t=this._getHierarchyIndex(e),n=t.orderedRecordIds.indexOf(this._recordId),r=t.subtreeHeightByRecordId.has(this._recordId)?this._collectDescendantIds(t.childrenByParentId,this._recordId):[];return n<0?[]:r.flatMap(e=>{let t=this._table.getRecordById(e);return t?[t]:[]})}setParent(e,t,n){return this._commandService.syncExecuteCommand(oe.id,{unitId:this._base.getId(),tableId:this._table.getId(),fieldId:e,recordId:this._recordId,parentRecordId:t,orderKey:n,source:r.Facade})}addChild(e,t,n=`id`,i){let a=this._table.getTable(),o=Date.now(),s={...i,id:F(6),values:H(a,t,n),orderKey:(i==null?void 0:i.orderKey)||`${o}`,createdAt:(i==null?void 0:i.createdAt)||o,updatedAt:(i==null?void 0:i.updatedAt)||o};if(!this._commandService.syncExecuteCommand(c.id,{unitId:this._base.getId(),tableId:this._table.getId(),fieldId:e,parentRecordId:this._recordId,record:s,source:r.Facade}))throw Error(`[FRecord]: failed to create child under "${this._recordId}".`);return this._injector.createInstance(J,this._base,this._table,s.id,this._injector)}_getHierarchyIndex(e){return _(this._table.getTable(),e)}_collectDescendantIds(e,t){let n=[],r=t=>{for(let i of e.get(t)??[])n.push(i),r(i)};return r(t),n}_getRecord(){let e=this._table.getTable().records[this._recordId];if(!e)throw Error(`[FRecord]: record "${this._recordId}" does not exist.`);return e}_getRecordLinkField(e){let t=this._table.getTable().fields[e];if(!t||t.type!==T.RecordLink)throw Error(`[FRecord]: field "${e}" is not a RecordLink field.`);return t}_getAttachmentField(e){let t=this._table.getTable().fields[e];if(!t||t.type!==T.Attachment)throw Error(`[FRecord]: field "${e}" is not an Attachment field.`);return t}};Y=J=z([R(4,A),R(5,j)],Y);function gt(e){return!!(e&&typeof e==`object`&&`id`in e&&typeof e.id==`string`&&`name`in e&&typeof e.name==`string`)}function _t(e,t,n){if(!gt(e))throw Error(`[FRecord]: attachment at index ${n} in field "${t}" is invalid.`);return{...e}}let X=class{constructor(e,t,n,r,i,a,o){this._base=e,this._table=t,this._viewId=n,this._injector=r,this._commandService=i,this._permissionService=a,this._projectionService=o}getId(){return this._viewId}getPermission(){let e=this._table.getId();return new L(this._base.getId(),Pe(e,this._viewId),[b(e)],this._commandService,this._permissionService)}getView(){return this._getView()}getName(){return this._getView().name}getType(){return this._getView().type}setName(e){return this._commandService.syncExecuteCommand(le.id,{unitId:this._base.getId(),tableId:this._table.getId(),viewId:this._viewId,name:e})}getConfig(){let e=this.getType(),t=this._getView().config;switch(e){case O.Grid:return t;case O.Kanban:return t;case O.Calendar:return t;case O.Gantt:return t;case O.Gallery:return t;default:return t}}updateConfig(e){return this._commandService.syncExecuteCommand(Ce.id,{unitId:this._base.getId(),tableId:this._table.getId(),viewId:this._viewId,patch:e})}getConditionalColorRules(){var e;return N.deepClone(((e=this._getView().config.conditionalColoring)==null?void 0:e.rules)??[])}setConditionalColorRules(e){return this._commandService.syncExecuteCommand(g.id,{unitId:this._base.getId(),tableId:this._table.getId(),viewId:this._viewId,type:n.Set,rules:e})}addConditionalColorRule(e){return this._commandService.syncExecuteCommand(g.id,{unitId:this._base.getId(),tableId:this._table.getId(),viewId:this._viewId,type:n.Add,rule:e})}deleteConditionalColorRule(e){return this._commandService.syncExecuteCommand(g.id,{unitId:this._base.getId(),tableId:this._table.getId(),viewId:this._viewId,type:n.Delete,ruleId:e})}clearConditionalColorRules(){return this._commandService.syncExecuteCommand(g.id,{unitId:this._base.getId(),tableId:this._table.getId(),viewId:this._viewId,type:n.Clear})}getFilter(){return this._getView().filter??null}setFilter(e){return this._commandService.syncExecuteCommand(ve.id,{unitId:this._base.getId(),tableId:this._table.getId(),viewId:this._viewId,filter:e})}getSort(){return this._getView().sort??[]}setSort(e){return this._commandService.syncExecuteCommand(be.id,{unitId:this._base.getId(),tableId:this._table.getId(),viewId:this._viewId,sort:e})}getGroup(){return this._getView().group??[]}setGroup(e){return this._commandService.syncExecuteCommand(ye.id,{unitId:this._base.getId(),tableId:this._table.getId(),viewId:this._viewId,group:e})}getFieldSettings(e){var t;return V(this._table.getTable().fields[e])?((t=this._getView().fieldSettings)==null?void 0:t[e])??{}:{}}getVisibleFields(){let e=this._table.getTable(),t=this._getView();return(t.fieldOrder??e.fieldOrder).filter(n=>{var r;let i=e.fields[n];return V(i)&&!((r=t.fieldSettings)!=null&&(r=r[n])!=null&&r.hidden)}).map(e=>this._injector.createInstance(B,this._base,this._table,e))}setFieldVisible(e,t){return V(this._table.getTable().fields[e])?this._commandService.syncExecuteCommand(ge.id,{unitId:this._base.getId(),tableId:this._table.getId(),viewId:this._viewId,fieldId:e,visible:t}):!1}setFieldWidth(e,t){return V(this._table.getTable().fields[e])?this._commandService.syncExecuteCommand(_e.id,{unitId:this._base.getId(),tableId:this._table.getId(),viewId:this._viewId,fieldId:e,width:t}):!1}moveField(e,t){let n=this._table.getTable(),r=t.beforeFieldId??t.afterFieldId;return!V(n.fields[e])||!r||!V(n.fields[r])?!1:this._commandService.syncExecuteCommand(he.id,{unitId:this._base.getId(),tableId:this._table.getId(),viewId:this._viewId,fieldId:e,target:t})}move(e){return this._commandService.syncExecuteCommand(se.id,{unitId:this._base.getId(),tableId:this._table.getId(),viewId:this._viewId,target:e})}delete(){return this._commandService.syncExecuteCommand(re.id,{unitId:this._base.getId(),tableId:this._table.getId(),viewId:this._viewId})}getProjection(){return this._projectionService.getProjection(this._base.getBase().getSnapshot(),this._table.getId(),this._viewId)}_getView(){let e=this._table.getTable().views[this._viewId];if(!e)throw Error(`[FView]: view "${this._viewId}" does not exist.`);return e}};X=z([R(4,A),R(5,j),R(6,ie)],X);let Z=class{constructor(e,t,n,r,i,a){this._base=e,this._tableId=t,this._injector=n,this._commandService=r,this._permissionService=i,this._projectionService=a}getBase(){return this._base.getBase()}getTable(){return this._getTable()}getId(){return this._tableId}getPermission(){return new L(this.getBase().getUnitId(),b(this._tableId),[],this._commandService,this._permissionService)}getHierarchyFieldId(){return S(this._getTable())}setHierarchyField(e){return this._commandService.syncExecuteCommand(me.id,{unitId:this._base.getId(),tableId:this._tableId,fieldId:e})}getName(){return this._getTable().name}getFormulaName(){let e=this._base.getBase().getSnapshot();return Me(this._getTable(),e)}setName(e){let n=Ve(this._base.getBase().getSnapshot(),e,this._tableId);if(!n.valid)throw Error(`[FBaseTable]: invalid table name "${e}". ${t} ${n.reason}`);return this._commandService.syncExecuteCommand(ce.id,{unitId:this._base.getId(),tableId:this._tableId,name:e})}search(e,t){let n=this._base.getBase().getSnapshot(),r=this._getTable();if(t){let i=this._projectionService.getProjection(n,this._tableId,t),a=r.views[t],o=e.fieldIds??Tt(r,a,i),s=`rows`in i&&Array.isArray(i.rows)?i.rows:[];return Re({...e,table:r,fieldIds:o,rows:s})}let i=(r.recordOrder?r.recordOrder.map(e=>r.records[e]):Object.values(r.records).sort((e,t)=>e.orderKey.localeCompare(t.orderKey))).filter(e=>e).map(e=>({recordId:e.id,values:e.values})),a=e.fieldIds??r.fieldOrder.filter(e=>V(r.fields[e]));return Re({...e,table:r,fieldIds:a,rows:i})}getPrimaryFieldId(){return this._getTable().primaryFieldId}getFields(){let e=this._getTable();return e.fieldOrder.map(t=>e.fields[t]).filter(V).map(e=>this._injector.createInstance(B,this._base,this,e.id))}getFieldById(e){let t=this._getTable().fields[e];return V(t)?this._injector.createInstance(B,this._base,this,t.id):null}getFieldByName(e){let t=this._getTable().fields,n=Object.values(t).find(t=>V(t)&&t.name===e);return n?this._injector.createInstance(B,this._base,this,n.id):null}getPrimaryField(){let e=this._getTable().primaryFieldId;return this._injector.createInstance(B,this._base,this,e)}addField(e,t,n){var r,i;if(!Object.values(T).some(e=>e===t))throw Error(`Unsupported Base field type "${String(t)}".`);if(t===T.Formula&&this._prepareFormulaFieldReferences(e,n),t===T.RecordLink&&(typeof(n==null||(r=n.field)==null||(r=r.config)==null?void 0:r.targetTableId)!=`string`||typeof n.field.config.multiple!=`boolean`))throw Error(`RecordLink fields require config { targetTableId, multiple }.`);let a={...n==null?void 0:n.field,id:F(6),name:e,type:t,config:(n==null||(i=n.field)==null?void 0:i.config)??{}};if(!this._commandService.syncExecuteCommand(l.id,{unitId:this._base.getId(),tableId:this._tableId,field:a,index:n==null?void 0:n.index}))throw Error(`Failed to add field "${e}"`);return this._injector.createInstance(B,this._base,this,a.id)}_prepareFormulaFieldReferences(e,t){var n;if(!t||!(`externalReferences`in t)||!Array.isArray(t.externalReferences))throw Error(`Formula fields require options.externalReferences. Use [] only for a Host-local formula.`);let r=this._commandService.syncExecuteCommand(we.id,{unitId:this._base.getId(),tableId:this._tableId,formula:String(((n=t.field)==null||(n=n.config)==null?void 0:n.formula)??``)});if(!r.valid)throw Error(r.reason??`Invalid Base formula.`);if(t.externalReferences.length>0&&!this._commandService.syncExecuteCommand(it.id,{unitId:this._base.getId(),references:t.externalReferences}))throw Error(`Failed to bind External References for formula field "${e}"`)}getRecords(){return this._resolveRecordIds().map(e=>this._injector.createInstance(Y,this._base,this,e,this._injector))}getRecordById(e){return this._getTable().records[e]?this._injector.createInstance(Y,this._base,this,e,this._injector):null}queryRecords(e={}){let t=this._getTable(),n=this._resolveRecordIds(e),r=Math.max(0,e.offset??0),i=e.limit==null?null:Math.max(0,e.limit),a=yt(n.map(e=>t.records[e]).filter(n=>xt(n,t,e.filter)),t,e.sort);return{records:vt(a,e).map(e=>this._injector.createInstance(Y,this._base,this,e.id,this._injector)),total:a.length,offset:r,limit:i,hasMore:i!=null&&r+i<a.length}}addRecord(e,t=`id`,n){let i=this._getTable(),a=Date.now(),o={...n,id:F(6),values:H(i,e,t),orderKey:(n==null?void 0:n.orderKey)||`${a}`,createdAt:(n==null?void 0:n.createdAt)||a,updatedAt:(n==null?void 0:n.updatedAt)||a};if(!this._commandService.syncExecuteCommand(u.id,{unitId:this._base.getId(),tableId:this._tableId,record:o,source:r.Facade}))throw Error(`Failed to add record with id "${o.id}"`);return this._injector.createInstance(Y,this._base,this,o.id,this._injector)}addRecords(e){if(!e.length)return[];let t=this._getTable(),n=Date.now(),i=e.map((e,r)=>{var i,a,o;return{...e.record,id:F(6),values:H(t,e.values,e.fieldKey??`id`),orderKey:((i=e.record)==null?void 0:i.orderKey)||`${n+r}`,createdAt:((a=e.record)==null?void 0:a.createdAt)||n,updatedAt:((o=e.record)==null?void 0:o.updatedAt)||n}});if(!this._commandService.syncExecuteCommand(a.id,{unitId:this._base.getId(),tableId:this._tableId,records:i,source:r.Facade}))throw Error(`Failed to add records`);return i.map(e=>this._injector.createInstance(Y,this._base,this,e.id,this._injector))}deleteRecords(e){return!e.length||this._commandService.syncExecuteCommand(o.id,{unitId:this._base.getId(),tableId:this._tableId,recordIds:e,source:r.Facade})}getRange(e,t,n=1,r=1){return this._injector.createInstance(K,this._base,this,{startRow:e,endRow:e+n-1,startColumn:t,endColumn:t+r-1},this._injector)}getDataRange(){var e;let t=Oe(this._getTable()),n=((e=t.recordOrder)==null?void 0:e.length)??0,r=t.fieldOrder.filter(e=>V(t.fields[e])).length;return this.getRange(0,0,Math.max(n,1),Math.max(r,1))}getViews(){let e=this._getTable();return e.viewOrder.filter(t=>e.views[t]).map(e=>this._injector.createInstance(X,this._base,this,e,this._injector))}getViewById(e){return this._getTable().views[e]?this._injector.createInstance(X,this._base,this,e,this._injector):null}getViewByName(e){let t=this._getTable(),n=Object.values(t.views).find(t=>t.name===e);return n?this._injector.createInstance(X,this._base,this,n.id,this._injector):null}createView(e,t,n){var r,i,a,o;let s=this._getTable(),c=(n==null||(r=n.view)==null?void 0:r.fieldOrder)??s.fieldOrder,l=[w,...c.filter(e=>V(s.fields[e]))],u={...n==null?void 0:n.view,id:F(6),name:e,type:t,tableId:this._tableId,config:(n==null||(i=n.view)==null?void 0:i.config)??{},fieldOrder:l,fieldSettings:{...n==null||(a=n.view)==null?void 0:a.fieldSettings,[w]:{...n==null||(o=n.view)==null||(o=o.fieldSettings)==null?void 0:o[w],hidden:!0}}};if(!this._commandService.syncExecuteCommand(f.id,{unitId:this._base.getId(),tableId:this._tableId,view:u,index:n==null?void 0:n.index}))throw Error(`Failed to create view "${e}"`);return this._injector.createInstance(X,this._base,this,u.id,this._injector)}getSchema(){let e=this._getTable(),t=e.fieldOrder.filter(t=>V(e.fields[t])),n=e.viewOrder.filter(t=>e.views[t]);return{id:e.id,name:e.name,formulaName:this.getFormulaName(),primaryFieldId:e.primaryFieldId,fieldIds:t,viewIds:n,recordCount:this._resolveRecordIds().length,fields:t.map(t=>{let n=e.fields[t];return{id:n.id,name:n.name,type:n.type,config:n.config,readonly:n.readonly,description:n.description}}),views:n.map(t=>{let n=e.views[t];return{id:n.id,name:n.name,type:n.type}})}}_getTable(){let e=this._base.getBase().getSnapshot().tables[this._tableId];if(!e)throw Error(`[FTable]: table "${this._tableId}" does not exist.`);return e}_resolveRecordIds(e={}){let t=this._base.getBase().getSnapshot(),n=this._getTable();if(e.viewId){let n=this._projectionService.getProjection(t,this._tableId,e.viewId);if(`rows`in n&&Array.isArray(n.rows))return n.rows.map(e=>e.recordId)}return(n.recordOrder?n.recordOrder.map(e=>n.records[e]):Object.values(n.records).sort((e,t)=>e.orderKey.localeCompare(t.orderKey))).filter(e=>e).map(e=>e.id)}};Z=z([R(3,A),R(4,j),R(5,ie)],Z);function vt(e,t){let n=Math.max(0,t.offset??0);return t.limit==null?e.slice(n):e.slice(n,n+Math.max(0,t.limit))}function yt(e,t,n=[]){return n.length?[...e].sort((e,r)=>{for(let a of n){var i;let n=a.direction===D.DESC?-1:1,o=bt(e.values[a.fieldId],r.values[a.fieldId],(i=t.fields[a.fieldId])==null?void 0:i.type);if(o!==0)return o*n}return String(e.orderKey??e.id).localeCompare(String(r.orderKey??r.id))}):e}function bt(e,t,n){return e==null&&t==null?0:e==null?-1:t==null?1:typeof e==`number`&&typeof t==`number`?e-t:n===T.Date?Number(e)-Number(t):String(e).localeCompare(String(t))}function xt(e,t,n){var r;if(!n||!((r=n.conditions)!=null&&r.length))return!0;let{conjunction:i=E.OR,conditions:a}=n;return i===E.AND&&a.length>1?a.every(n=>St(e,t,n)):a.some(n=>St(e,t,n))}function St(e,t,n){let r=e.values[n.fieldId],i=t.fields[n.fieldId];if(Ct(n)){let e=wt(n).test(String(r??``));return n.operator===`matches`?e:!e}return!i||Ie(r,n.operator,n.value,i)}function Ct(e){return e.operator===`matches`||e.operator===`notMatches`}function wt(e){let t=String(e.value??``);if(t.length>512)throw Error(`Base regex filter is too long. Maximum length is 512.`);try{return new RegExp(t,e.caseSensitive?void 0:`i`)}catch(e){throw Error(`Invalid Base regex filter: ${t}. ${e instanceof Error?e.message:String(e)}`)}}function Tt(e,t,n){if(n.type!==`invalid`&&n.type!==`custom`){var r;if(n.type===O.Kanban){var i;let t=[((i=n.fields)==null||(i=i[0])==null?void 0:i.id)??e.primaryFieldId,...n.visibleCardFieldIds??[]];return Array.from(new Set(t.filter(t=>!!e.fields[t])))}if((r=n.fields)!=null&&r.length)return n.fields.map(e=>e.id).filter(n=>{var r;return!(!e.fields[n]||t!=null&&(r=t.fieldSettings)!=null&&(r=r[n])!=null&&r.hidden)})}return e.fieldOrder.filter(n=>{var r;return!(!e.fields[n]||t!=null&&(r=t.fieldSettings)!=null&&(r=r[n])!=null&&r.hidden)})}let Q=class extends $e.FBase{constructor(e,t,n,r,i){super(),this._base=e,this._injector=t,this._resourceLoaderService=n,this._commandService=r,this._permissionService=i}getBase(){return this._base}getId(){return this._base.getUnitId()}getPermission(){return new at(this.getId(),this._commandService,this._permissionService)}save(){return this._resourceLoaderService.saveUnit(this.getId())??N.deepClone(this._base.getSnapshot())}getName(){return this._base.getSnapshot().name}setName(e){this._commandService.syncExecuteCommand(ue.id,{unitId:this.getId(),name:e})}getTables(){let e=this._base.getSnapshot();return e.tableOrder.map(t=>e.tables[t]).filter(e=>e).map(e=>this._injector.createInstance(Z,this,e.id,this._injector))}getTableById(e){let t=this._base.getSnapshot().tables[e];return t?this._injector.createInstance(Z,this,t.id,this._injector):null}getTableByName(e){let t=this._base.getSnapshot(),n=Object.values(t.tables).find(t=>t.name===e);return n?this._injector.createInstance(Z,this,n.id,this._injector):null}insertTable(e,n){let r=Qe({id:F(),name:e,...n==null?void 0:n.table,primaryFieldName:n==null?void 0:n.primaryFieldName}),i=N.commonExtend(r,(n==null?void 0:n.table)??{}),a=Ve(this._base.getSnapshot(),i.name);if(!a.valid)throw Error(`[FBase]: invalid table name "${i.name}". ${t} ${a.reason}`);if(!this._commandService.syncExecuteCommand(d.id,{unitId:this._base.getUnitId(),table:i,index:n==null?void 0:n.index}))throw Error(`Failed to create table "${e}".`);return this._injector.createInstance(Z,this,i.id,this._injector)}deleteTable(e){let t=typeof e==`string`?e:e.getId();if(!this._commandService.syncExecuteCommand(ne.id,{unitId:this._base.getUnitId(),tableId:t}))throw Error(`Failed to delete table "${t}".`);return!0}duplicateTable(e,t){let n=this._base.getSnapshot(),r=typeof e==`string`?e:e.getId(),i=n.tables[r];if(!i)throw Error(`[FBase]: table "${r}" does not exist.`);let a=n.tableOrder.indexOf(r)+1,o=F(),s=Ee(i,{id:o,name:De(n,`${i.name} Copy`),includeRecords:(t==null?void 0:t.includeRecords)??!1,regenerateViewIds:(t==null?void 0:t.regenerateViewIds)??!1});if(!this._commandService.syncExecuteCommand(d.id,{unitId:this._base.getUnitId(),table:s,index:a}))throw Error(`Failed to duplicate table "${r}".`);return this._injector.createInstance(Z,this,s.id,this._injector)}getSchema(){let e=this._base.getSnapshot();return{id:e.id,name:e.name,tables:this.getTables().map(e=>e.getSchema())}}};Q=z([R(1,Xe(Ze)),R(2,Ye),R(3,A),R(4,j)],Q);var Et=class extends rt{_initialize(){this._initBaseBeforeEvents(),this._initBaseAfterEvents()}createBase(e={},t){let n=this._univerInstanceService.createUnit(P.UNIVER_BASE,e,t);return this._injector.createInstance(Q,n)}getActiveBase(){let e=this._univerInstanceService.getCurrentUnitOfType(P.UNIVER_BASE);return e?this._injector.createInstance(Q,e):null}getBase(e){let t=this._univerInstanceService.getUnit(e,P.UNIVER_BASE);return t?this._injector.createInstance(Q,t):null}getBases(){return this._univerInstanceService.getAllUnitsForType(P.UNIVER_BASE).map(e=>this._injector.createInstance(Q,e))}_initBaseAfterEvents(){this.disposeWithMe(this.registerEventHandler(this.Event.BaseHierarchyChanged,()=>this._commandService.onCommandExecuted((t,n)=>{var i;if(!$(t,e))return;let a=t.params;if(!((i=a.hierarchyChanges)!=null&&i.length))return;let o=this.getBase(a.unitId),s=o==null?void 0:o.getTableById(a.hierarchyChanges[0].tableId);if(!o||!s)return;let c={base:o,table:s,changes:a.hierarchyChanges,source:n!=null&&n.fromCollab?r.Remote:a.source??r.UI};this.fireEvent(this.Event.BaseHierarchyChanged,c)}))),this.disposeWithMe(this.registerEventHandler(this.Event.BaseTableCreated,()=>this._commandService.onCommandExecuted(e=>{if(e.id!==d.id)return;let{unitId:t,table:n,index:r}=e.params,i=this.getBase(t);if(!i)return;let a={base:i,table:n,index:r};this.fireEvent(this.Event.BaseTableCreated,a)}))),this.disposeWithMe(this.registerEventHandler(this.Event.BaseTableFieldCreated,()=>this._commandService.onCommandExecuted(e=>{if(e.id!==l.id)return;let{unitId:t,tableId:n,field:r,index:i,viewIndexes:a}=e.params,o=this.getBase(t);if(!o)return;let s=o.getTableById(n);if(!s)return;let c={base:o,table:s,field:r,index:i,viewIndexes:a};this.fireEvent(this.Event.BaseTableFieldCreated,c)}))),this.disposeWithMe(this.registerEventHandler(this.Event.BaseTableRecordCreated,()=>this._commandService.onCommandExecuted(e=>{if(e.id!==u.id&&e.id!==a.id)return;let t=e.params,{unitId:n,tableId:r}=t,i=t.records??[t.record],o=this.getBase(n);if(!o)return;let s=o.getTableById(r);if(!s)return;let c={base:o,table:s,records:i};this.fireEvent(this.Event.BaseTableRecordCreated,c)}))),this.disposeWithMe(this.registerEventHandler(this.Event.BaseTableViewCreated,()=>this._commandService.onCommandExecuted(e=>{if(e.id!==f.id)return;let{unitId:t,tableId:n,view:r,index:i}=e.params,a=this.getBase(t);if(!a)return;let o=a.getTableById(n);if(!o)return;let s={base:a,table:o,view:r,index:i};this.fireEvent(this.Event.BaseTableViewCreated,s)}))),this.disposeWithMe(this.registerEventHandler(this.Event.BaseTableCellValueChanged,()=>this._commandService.onCommandExecuted(e=>{if(e.id!==h.id)return;let{unitId:t,tableId:n,recordId:r,fieldId:i,value:a}=e.params,o=this.getBase(t);if(!o)return;let s=o.getTableById(n);if(!s)return;let c=s.getFieldById(i);if(!c)return;let l=s.getRecordById(r);if(!l)return;let u={base:o,table:s,field:c,record:l,value:a};this.fireEvent(this.Event.BaseTableCellValueChanged,u)})))}_initBaseBeforeEvents(){this.disposeWithMe(this.registerEventHandler(this.Event.BeforeBaseHierarchyChange,()=>this._commandService.beforeCommandExecuted(e=>{if($(e,pe)){let{unitId:t,tableId:n,patches:i,source:a=r.UI}=e.params,o=this._getHierarchyEventContext(t,n);if(!o)return;this._fireBeforeHierarchyChange(o.base,o.table,Be(o.table.getTable(),i),a);return}if($(e,fe)){let{unitId:t,tableId:n,patches:i,source:a=r.UI}=e.params,o=this._getHierarchyEventContext(t,n);if(!o)return;let s=o.table.getTable();this._fireBeforeHierarchyChange(o.base,o.table,Be(s,Le(s,i)),a);return}if($(e,u)){let t=e.params,n=this._getHierarchyEventContext(t.unitId,t.tableId);if(!n)return;this._fireBeforeHierarchyChange(n.base,n.table,C(n.table.getTable(),[t.record]),t.source??r.UI);return}if($(e,a)){let t=e.params,n=this._getHierarchyEventContext(t.unitId,t.tableId);if(!n)return;this._fireBeforeHierarchyChange(n.base,n.table,C(n.table.getTable(),t.records),t.source??r.UI);return}if($(e,p)){let t=e.params,n=this._getHierarchyEventContext(t.unitId,t.tableId);if(!n)return;this._fireBeforeHierarchyChange(n.base,n.table,C(n.table.getTable(),[t.record]),t.source??r.UI);return}if($(e,oe)){let t=e.params,n=this._getHierarchyEventContext(t.unitId,t.tableId);if(!n)return;let i=n.table.getTable(),a=t.fieldId??S(i),o=_(i,a).parentByRecordId.get(t.recordId)??null;this._fireBeforeHierarchyChange(n.base,n.table,[{tableId:t.tableId,fieldId:a,recordId:t.recordId,oldParentRecordId:o,parentRecordId:t.parentRecordId}],t.source??r.UI);return}if($(e,c)){let t=e.params,n=this._getHierarchyEventContext(t.unitId,t.tableId);if(!n)return;let i=t.fieldId??S(n.table.getTable());this._fireBeforeHierarchyChange(n.base,n.table,[{tableId:t.tableId,fieldId:i,recordId:t.record.id,oldParentRecordId:null,parentRecordId:t.parentRecordId}],t.source??r.UI);return}if($(e,te)){let t=e.params,n=this._getHierarchyEventContext(t.unitId,t.tableId);if(!n)return;this._fireBeforeHierarchyChange(n.base,n.table,v(n.table.getTable(),[t.recordId]),t.source??r.UI);return}if($(e,o)){let t=e.params,n=this._getHierarchyEventContext(t.unitId,t.tableId);if(!n)return;this._fireBeforeHierarchyChange(n.base,n.table,v(n.table.getTable(),t.recordIds),t.source??r.UI);return}if(!$(e,h))return;let t=e.params,n=this._getHierarchyEventContext(t.unitId,t.tableId);if(!n)return;let i=n.table.getTable();if(!ke(i).includes(t.fieldId))return;let s=_(i,t.fieldId).parentByRecordId.get(t.recordId)??null,l=x(t.value)[0]??null;s!==l&&this._fireBeforeHierarchyChange(n.base,n.table,[{tableId:t.tableId,fieldId:t.fieldId,recordId:t.recordId,oldParentRecordId:s,parentRecordId:l}],t.source??r.UI)}))),this.disposeWithMe(this.registerEventHandler(this.Event.BeforeBaseTableCreate,()=>this._commandService.beforeCommandExecuted(e=>{if(e.id!==d.id)return;let{unitId:t,table:n,index:r}=e.params,i=this.getBase(t);if(!i)return;let a={base:i,table:n,index:r};if(this.fireEvent(this.Event.BeforeBaseTableCreate,a),a.cancel)throw new k}))),this.disposeWithMe(this.registerEventHandler(this.Event.BeforeBaseTableFieldCreate,()=>this._commandService.beforeCommandExecuted(e=>{if(e.id!==l.id)return;let{unitId:t,tableId:n,field:r,index:i,viewIndexes:a}=e.params,o=this.getBase(t);if(!o)return;let s=o.getTableById(n);if(!s)return;let c={base:o,table:s,field:r,index:i,viewIndexes:a};if(this.fireEvent(this.Event.BeforeBaseTableFieldCreate,c),c.cancel)throw new k}))),this.disposeWithMe(this.registerEventHandler(this.Event.BeforeBaseTableRecordCreate,()=>this._commandService.beforeCommandExecuted(e=>{if(e.id!==u.id&&e.id!==a.id)return;let t=e.params,{unitId:n,tableId:r}=t,i=t.records??[t.record],o=this.getBase(n);if(!o)return;let s=o.getTableById(r);if(!s)return;let c={base:o,table:s,records:i};if(this.fireEvent(this.Event.BeforeBaseTableRecordCreate,c),c.cancel)throw new k}))),this.disposeWithMe(this.registerEventHandler(this.Event.BeforeBaseTableViewCreate,()=>this._commandService.beforeCommandExecuted(e=>{if(e.id!==f.id)return;let{unitId:t,tableId:n,view:r,index:i}=e.params,a=this.getBase(t);if(!a)return;let o=a.getTableById(n);if(!o)return;let s={base:a,table:o,view:r,index:i};if(this.fireEvent(this.Event.BeforeBaseTableViewCreate,s),s.cancel)throw new k}))),this.disposeWithMe(this.registerEventHandler(this.Event.BeforeBaseTableCellValueChange,()=>this._commandService.beforeCommandExecuted(e=>{if(e.id!==h.id)return;let{unitId:t,tableId:n,recordId:r,fieldId:i,value:a}=e.params,o=this.getBase(t);if(!o)return;let s=o.getTableById(n);if(!s)return;let c=s.getFieldById(i);if(!c)return;let l=s.getRecordById(r);if(!l)return;let u={base:o,table:s,field:c,record:l,value:a};if(this.fireEvent(this.Event.BeforeBaseTableCellValueChange,u),u.cancel)throw new k})))}_getHierarchyEventContext(e,t){let n=this.getBase(e),r=n==null?void 0:n.getTableById(t);return n&&r?{base:n,table:r}:null}_fireBeforeHierarchyChange(e,t,n,r){if(!n.length)return;let i={base:e,table:t,changes:n,source:r};if(this.fireEvent(this.Event.BeforeBaseHierarchyChange,i),i.cancel)throw new k}};function $(e,t){return e.id===t.id&&e.params!==void 0}rt.extend(Et);var Dt=class extends tt{get BaseFieldType(){return T}get BaseFilterConjunction(){return E}get BaseFilterOperator(){return Ke}get BaseFieldKeyEnum(){return ot}get BaseViewType(){return O}get BaseConditionalColorTarget(){return We}get BaseConditionalColorOperator(){return Ue}get BaseConditionalDateMode(){return Ge}get BaseSortDirection(){return D}get BaseEventSource(){return r}get BaseHierarchyErrorCode(){return i}get BaseHierarchyInvalidReason(){return qe}get BaseRecordLinkRole(){return Je}};tt.extend(Dt);var Ot=class extends nt{get BaseTableCreated(){return`BaseTableCreated`}get BeforeBaseTableCreate(){return`BeforeBaseTableCreate`}get BaseTableFieldCreated(){return`BaseTableFieldCreated`}get BeforeBaseTableFieldCreate(){return`BeforeBaseTableFieldCreate`}get BaseTableRecordCreated(){return`BaseTableRecordCreated`}get BeforeBaseTableRecordCreate(){return`BeforeBaseTableRecordCreate`}get BaseTableViewCreated(){return`BaseTableViewCreated`}get BeforeBaseTableViewCreate(){return`BeforeBaseTableViewCreate`}get BaseTableCellValueChanged(){return`BaseTableCellValueChanged`}get BeforeBaseTableCellValueChange(){return`BeforeBaseTableCellValueChange`}get BaseHierarchyChanged(){return`BaseHierarchyChanged`}get BeforeBaseHierarchyChange(){return`BeforeBaseHierarchyChange`}};nt.extend(Ot);export{ot as BaseFieldKeyEnum,Q as FBase,L as FBaseObjectPermission,at as FBasePermission,Z as FBaseTable,B as FBaseTableField,K as FBaseTableRange,Y as FBaseTableRecord,X as FBaseTableView,Ot as FBasesEventNameMixin,ct as resolveBaseFieldKey,H as resolveBaseFieldValues};