@univerjs/core 0.2.10 → 0.2.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/cjs/index.js CHANGED
@@ -5,5 +5,5 @@
5
5
  Maybe your dependencies added redi as its dependency and bundled redi to its dist files. Or you import different versions of redi.
6
6
  For more info please visit our website: https://redi.wendell.fun/en-US/docs/debug#import-scripts-of-redi-more-than-once`):globalObject$1[__REDI_GLOBAL_LOCK__]=!0;var __REDI_CONTEXT_LOCK__="REDI_CONTEXT_LOCK",isNode=typeof process<"u"&&process.versions!=null&&process.versions.node!=null,globalObject=typeof globalThis<"u"&&globalThis||typeof window<"u"&&window||typeof global<"u"&&global;globalObject[__REDI_CONTEXT_LOCK__]?isNode||console.error(`[redi]: "RediContext" is already created. You may import "RediContext" from different paths. Use "import { RediContext } from '@wendellhu/redi/react-bindings'; instead."`):globalObject[__REDI_CONTEXT_LOCK__]=!0;var RediContext=React__namespace.createContext({injector:null});RediContext.displayName="RediContext";var RediProvider=RediContext.Provider,RediConsumer=RediContext.Consumer,__extends$1=function(){var extendStatics=__name(function(d,b){return extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d2,b2){d2.__proto__=b2}||function(d2,b2){for(var p in b2)Object.prototype.hasOwnProperty.call(b2,p)&&(d2[p]=b2[p])},extendStatics(d,b)},"extendStatics");return function(d,b){if(typeof b!="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}__name(__,"__"),d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}(),HooksNotInRediContextError=function(_super){__extends$1(HooksNotInRediContextError2,_super);function HooksNotInRediContextError2(){return _super.call(this,"Using dependency injection outside of a RediContext.")||this}return __name(HooksNotInRediContextError2,"HooksNotInRediContextError"),HooksNotInRediContextError2}(RediError);function useInjector(){var injectionContext=React__namespace.useContext(RediContext);if(!injectionContext.injector)throw new HooksNotInRediContextError;return injectionContext.injector}__name(useInjector,"useInjector");function useDependency(id,quantityOrLookUp,lookUp){var injector=useInjector();return React__namespace.useMemo(function(){return injector.get(id,quantityOrLookUp,lookUp)},[id,quantityOrLookUp,lookUp])}__name(useDependency,"useDependency");var __assign=__name(function(){return __assign=Object.assign||function(t){for(var s,i=1,n=arguments.length;i<n;i++){s=arguments[i];for(var p in s)Object.prototype.hasOwnProperty.call(s,p)&&(t[p]=s[p])}return t},__assign.apply(this,arguments)},"__assign");function RediInjector(props){var children=props.children,dependencies=props.dependencies,childInjectorRef=React__namespace.useRef(null);return React__namespace.useEffect(function(){return function(){var _a13;return(_a13=childInjectorRef.current)===null||_a13===void 0?void 0:_a13.dispose()}},[]),React__namespace.createElement(RediConsumer,null,function(context){var childInjector;return childInjectorRef.current?childInjector=childInjectorRef.current:(childInjector=context.injector?context.injector.createChild(dependencies):new Injector(dependencies),childInjectorRef.current=childInjector),React__namespace.createElement(RediProvider,{value:{injector:childInjector}},children)})}__name(RediInjector,"RediInjector");function connectInjector(Comp,injector){return __name(function(props){return React__namespace.createElement(RediProvider,{value:{injector}},React__namespace.createElement(Comp,__assign({},props)))},"ComponentWithInjector")}__name(connectInjector,"connectInjector");function connectDependencies(Comp,dependencies){return __name(function(props){return React__namespace.createElement(RediInjector,{dependencies},React__namespace.createElement(Comp,__assign({},props)))},"ComponentWithInjector")}__name(connectDependencies,"connectDependencies");var __extends=function(){var extendStatics=__name(function(d,b){return extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d2,b2){d2.__proto__=b2}||function(d2,b2){for(var p in b2)Object.prototype.hasOwnProperty.call(b2,p)&&(d2[p]=b2[p])},extendStatics(d,b)},"extendStatics");return function(d,b){if(typeof b!="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}__name(__,"__"),d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}(),ClassComponentNotInRediContextError=function(_super){__extends(ClassComponentNotInRediContextError2,_super);function ClassComponentNotInRediContextError2(component){return _super.call(this,'You should make "RediContext" as '.concat(component.constructor.name,"'s default context type. ")+"If you want to use multiple context, please check this on React doc site. https://reactjs.org/docs/context.html#classcontexttype")||this}return __name(ClassComponentNotInRediContextError2,"ClassComponentNotInRediContextError"),ClassComponentNotInRediContextError2}(RediError);function WithDependency(id,quantity,lookUp){return function(){return{get:__name(function(){var thisComponent=this,context=thisComponent.context;if(!context||!context.injector)throw new ClassComponentNotInRediContextError(thisComponent);var injector=context.injector,thing=injector.get(id,quantity||exports.Quantity.REQUIRED,lookUp);return thing},"get")}}}__name(WithDependency,"WithDependency");var __spreadArray=__name(function(to,from,pack){if(pack||arguments.length===2)for(var i=0,l=from.length,ar;i<l;i++)(ar||!(i in from))&&(ar||(ar=Array.prototype.slice.call(from,0,i)),ar[i]=from[i]);return to.concat(ar||Array.prototype.slice.call(from))},"__spreadArray");function useDependencyValue(depValue$,defaultValue){var firstValue=depValue$ instanceof rxjs.BehaviorSubject&&typeof defaultValue>"u"?depValue$.getValue():defaultValue,_a13=React.useState(firstValue),value=_a13[0],setValue=_a13[1];return React.useEffect(function(){var subscription=depValue$.subscribe(function(val){return setValue(val)});return function(){return subscription.unsubscribe()}},[depValue$]),value}__name(useDependencyValue,"useDependencyValue");function unwrap(o){return typeof o=="function"?o():o}__name(unwrap,"unwrap");function useObservable(observable,defaultValue,shouldHaveSyncValue,deps){if(typeof observable=="function"&&!deps)throw new RediError("Expected deps to be provided when observable is a function!");var observableRef=React.useRef(null),initializedRef=React.useRef(!1),destObservable=React.useMemo(function(){return observable},__spreadArray([],typeof deps<"u"?deps:[observable],!0)),_a13=React.useState(0);_a13[0];var setRenderCounter=_a13[1],valueRef=React.useRef(function(){var innerDefaultValue;if(destObservable){var sub=unwrap(destObservable).subscribe(function(value){initializedRef.current=!0,innerDefaultValue=value});sub.unsubscribe()}return innerDefaultValue!=null?innerDefaultValue:defaultValue}());if(React.useEffect(function(){var subscription=null;return destObservable&&(observableRef.current=unwrap(destObservable),subscription=observableRef.current.subscribe(function(value){valueRef.current=value,setRenderCounter(function(prev){return prev+1})})),function(){return subscription==null?void 0:subscription.unsubscribe()}},[destObservable]),shouldHaveSyncValue&&!initializedRef.current)throw new Error("Expect `shouldHaveSyncValue` but not getting a sync value!");return valueRef.current}__name(useObservable,"useObservable");function useUpdateBinder(update$){var _a13=React.useState(0),dumpSet=_a13[1];React.useEffect(function(){var subscription=update$.subscribe(function(){return dumpSet(function(prev){return prev+1})});return function(){return subscription.unsubscribe()}},[])}__name(useUpdateBinder,"useUpdateBinder");var DepValueMapProvider=new WeakMap;function useDependencyContext(depValue$,defaultValue){var depRef=React.useRef(void 0),value=useDependencyValue(depValue$,defaultValue),Context=React.useMemo(function(){return React.createContext(value)},[depValue$]),Provider=React.useCallback(function(props){return React.createElement(Context.Provider,{value},props.children)},[depValue$,value]);return depRef.current!==depValue$&&(depRef.current&&DepValueMapProvider.delete(depRef.current),depRef.current=depValue$,DepValueMapProvider.set(depValue$,Context)),{Provider,value}}__name(useDependencyContext,"useDependencyContext");function useDependencyContextValue(depValue$){var context=DepValueMapProvider.get(depValue$);if(!context)throw new RediError("try to read context value but no ancestor component subscribed it.");return React.useContext(context)}__name(useDependencyContextValue,"useDependencyContextValue");async function sequenceAsync(tasks){for(const[index2,task]of tasks.entries())try{if(!await task())return{index:index2,result:!1}}catch(e){return{index:index2,result:!1,error:e}}return{result:!0,index:-1}}__name(sequenceAsync,"sequenceAsync");function sequence(tasks){for(const[index2,task]of tasks.entries())try{if(!task())return{index:index2,result:!1}}catch(e){return{index:index2,result:!1,error:e}}return{result:!0,index:-1}}__name(sequence,"sequence");const IContextService=createIdentifier("univer.context-service"),_ContextService=class _ContextService extends Disposable{constructor(){super(...arguments);__publicField(this,"_contextChanged$",new rxjs.Subject);__publicField(this,"contextChanged$",this._contextChanged$.asObservable());__publicField(this,"_contextMap",new Map)}dispose(){super.dispose(),this._contextChanged$.complete()}getContextValue(key){var _a13;return(_a13=this._contextMap.get(key))!=null?_a13:!1}setContextValue(key,value){this._contextMap.set(key,value),this._contextChanged$.next({[key]:value})}subscribeContextValue$(key){return new rxjs.Observable(observer=>{const contextChangeSubscription=this._contextChanged$.pipe(rxjs.filter(event=>typeof event[key]<"u")).subscribe(event=>observer.next(event[key]));return this._contextMap.has(key)&&observer.next(this._contextMap.get(key)),()=>contextChangeSubscription.unsubscribe()})}};__name(_ContextService,"ContextService");let ContextService=_ContextService;var LogLevel=(LogLevel2=>(LogLevel2[LogLevel2.SILENT=0]="SILENT",LogLevel2[LogLevel2.ERROR=1]="ERROR",LogLevel2[LogLevel2.WARN=2]="WARN",LogLevel2[LogLevel2.INFO=3]="INFO",LogLevel2[LogLevel2.VERBOSE=4]="VERBOSE",LogLevel2))(LogLevel||{});const ILogService=createIdentifier("univer.log"),_DesktopLogService=class _DesktopLogService extends Disposable{constructor(){super(...arguments);__publicField(this,"_logLevel",3)}debug(...args){this._logLevel>=4&&this._log(console.debug,...args)}log(...args){this._logLevel>=3&&this._log(console.log,...args)}warn(...args){this._logLevel>=2&&this._log(console.warn,...args)}error(...args){this._logLevel>=1&&this._log(console.error,...args)}setLogLevel(logLevel){this._logLevel=logLevel}_log(method,...args){const firstArg=args[0];/^\[(.*?)\]/g.test(firstArg)?method(`\x1B[97;104m${firstArg}\x1B[0m`,...args.slice(1)):method(...args)}};__name(_DesktopLogService,"DesktopLogService");let DesktopLogService=_DesktopLogService;const _CustomCommandExecutionError=class _CustomCommandExecutionError extends Error{constructor(message){super(message),this.name="CustomCommandExecutionError"}};__name(_CustomCommandExecutionError,"CustomCommandExecutionError");let CustomCommandExecutionError=_CustomCommandExecutionError;var __defProp$8=Object.defineProperty,__getOwnPropDesc$8=Object.getOwnPropertyDescriptor,__decorateClass$8=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$8(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$8(target,key,result),result},"__decorateClass$8"),__decorateParam$7=__name((index2,decorator)=>(target,key)=>decorator(target,key,index2),"__decorateParam$7"),CommandType=(CommandType2=>(CommandType2[CommandType2.COMMAND=0]="COMMAND",CommandType2[CommandType2.OPERATION=1]="OPERATION",CommandType2[CommandType2.MUTATION=2]="MUTATION",CommandType2))(CommandType||{});const ICommandService=createIdentifier("anywhere.command-service"),_CommandRegistry=class _CommandRegistry{constructor(){__publicField(this,"_commands",new Map);__publicField(this,"_commandTypes",new Map)}registerCommand(command){if(this._commands.has(command.id))throw new Error(`[CommandRegistry]: command "${command.id}" has been registered before.`);return this._commands.set(command.id,command),this._commandTypes.set(command.id,command.type),toDisposable(()=>{this._commands.delete(command.id),this._commandTypes.delete(command.id)})}hasCommand(id){return this._commands.has(id)}getCommand(id){return this._commands.has(id)?[this._commands.get(id)]:null}getCommandType(id){return this._commandTypes.get(id)}};__name(_CommandRegistry,"CommandRegistry");let CommandRegistry=_CommandRegistry;const NilCommand={id:"nil",type:0,handler:__name(()=>!0,"handler")};var _a2;exports.CommandService=(_a2=class extends Disposable{constructor(_injector,_logService){super();__publicField(this,"_commandRegistry");__publicField(this,"_beforeCommandExecutionListeners",[]);__publicField(this,"_commandExecutedListeners",[]);__publicField(this,"_multiCommandDisposables",new Map);__publicField(this,"_commandExecutingLevel",0);__publicField(this,"_commandExecutionStack",[]);this._injector=_injector,this._logService=_logService,this._commandRegistry=new CommandRegistry,this._registerCommand(NilCommand)}dispose(){super.dispose(),this._commandExecutedListeners.length=0,this._beforeCommandExecutionListeners.length=0}hasCommand(commandId){return this._commandRegistry.hasCommand(commandId)}registerCommand(command){return this._registerCommand(command)}registerMultipleCommand(command){return this._registerMultiCommand(command)}beforeCommandExecuted(listener){if(this._beforeCommandExecutionListeners.indexOf(listener)===-1)return this._beforeCommandExecutionListeners.push(listener),toDisposable(()=>{const index2=this._beforeCommandExecutionListeners.indexOf(listener);this._beforeCommandExecutionListeners.splice(index2,1)});throw new Error("[CommandService]: could not add a listener twice.")}onCommandExecuted(listener){if(this._commandExecutedListeners.indexOf(listener)===-1)return this._commandExecutedListeners.push(listener),toDisposable(()=>{const index2=this._commandExecutedListeners.indexOf(listener);this._commandExecutedListeners.splice(index2,1)});throw new Error("[CommandService]: could not add a listener twice.")}async executeCommand(id,params,options){try{const item=this._commandRegistry.getCommand(id);if(item){const[command]=item,commandInfo={id:command.id,type:command.type,params},stackItemDisposable=this._pushCommandExecutionStack(commandInfo);this._beforeCommandExecutionListeners.forEach(listener=>listener(commandInfo,options));const result=await this._execute(command,params,options);return this._commandExecutedListeners.forEach(listener=>listener(commandInfo,options)),stackItemDisposable.dispose(),result}throw new Error(`[CommandService]: command "${id}" is not registered.`)}catch(error){if(error instanceof CustomCommandExecutionError)return!1;throw this._logService.error(error),error}}syncExecuteCommand(id,params,options){var _a13;try{const item=this._commandRegistry.getCommand(id);if(item){const[command]=item,commandInfo={id:command.id,type:command.type,params};if(command.type===2){const triggerCommand=findLast(this._commandExecutionStack,item2=>item2.type===0);triggerCommand&&(commandInfo.params=(_a13=commandInfo.params)!=null?_a13:{},commandInfo.params.trigger=triggerCommand.id)}const stackItemDisposable=this._pushCommandExecutionStack(commandInfo);this._beforeCommandExecutionListeners.forEach(listener=>listener(commandInfo,options));const result=this._syncExecute(command,params,options);return this._commandExecutedListeners.forEach(listener=>listener(commandInfo,options)),stackItemDisposable.dispose(),result}throw new Error(`[CommandService]: command "${id}" is not registered.`)}catch(error){throw this._logService.error(error),error}}_pushCommandExecutionStack(stackItem){return this._commandExecutionStack.push(stackItem),toDisposable(()=>remove(this._commandExecutionStack,stackItem))}_registerCommand(command){return this._commandRegistry.registerCommand(command)}_registerMultiCommand(command){const registry=this._commandRegistry.getCommand(command.id);let multiCommand;if(registry){if(registry[0].multi!==!0)throw new Error("Command has registered as a single command.");multiCommand=registry[0]}else{const disposableCollection=new DisposableCollection;multiCommand=new MultiCommand(command.id),disposableCollection.add(this._commandRegistry.registerCommand(multiCommand)),disposableCollection.add(toDisposable(()=>{this._multiCommandDisposables.delete(command.id)})),this._multiCommandDisposables.set(command.id,disposableCollection)}const implementationDisposable=multiCommand.registerImplementation(command);return toDisposable(()=>{var _a13;implementationDisposable.dispose(),multiCommand.hasImplementations()||(_a13=this._multiCommandDisposables.get(command.id))==null||_a13.dispose()})}async _execute(command,params,options){this._logService.debug("[CommandService]",`${"|-".repeat(Math.max(this._commandExecutingLevel,0))}executing command "${command.id}"`),this._commandExecutingLevel++;let result;try{result=await this._injector.invoke(command.handler,params,options),this._commandExecutingLevel--}catch(e){throw result=!1,this._commandExecutingLevel=0,e}return result}_syncExecute(command,params,options){this._logService.debug("[CommandService]",`${"|-".repeat(Math.max(0,this._commandExecutingLevel))}executing command "${command.id}".`),this._commandExecutingLevel++;let result;try{if(result=this._injector.invoke(command.handler,params,options),result instanceof Promise)throw new TypeError("[CommandService]: Command handler should not return a promise.");this._commandExecutingLevel--}catch(e){throw result=!1,this._commandExecutingLevel=0,e}return result}},__name(_a2,"CommandService"),_a2);exports.CommandService=__decorateClass$8([__decorateParam$7(0,Inject(Injector)),__decorateParam$7(1,ILogService)],exports.CommandService);const _MultiCommand=class _MultiCommand{constructor(id){__publicField(this,"name");__publicField(this,"multi",!0);__publicField(this,"type",0);__publicField(this,"priority",0);__publicField(this,"_implementations",[]);__publicField(this,"handler",__name(async(accessor,params)=>{if(!this._implementations.length)return!1;const logService=accessor.get(ILogService),contextService=accessor.get(IContextService),injector=accessor.get(Injector);for(const item of this._implementations){const preconditions=item.command.preconditions;if((!preconditions||preconditions&&preconditions(contextService))&&(logService.debug("[MultiCommand]",`executing implementation "${item.command.name}".`),await injector.invoke(item.command.handler,params)))return!0}return!1},"handler"));this.id=id,this.name=id}registerImplementation(implementation){const registry={command:implementation};return this._implementations.push(registry),this._implementations.sort((a,b)=>b.command.priority-a.command.priority),toDisposable(()=>{const index2=this._implementations.indexOf(registry);this._implementations.splice(index2,1)})}hasImplementations(){return this._implementations.length>0}};__name(_MultiCommand,"MultiCommand");let MultiCommand=_MultiCommand;function sequenceExecute(tasks,commandService,options){const taskFns=tasks.map(task=>()=>commandService.syncExecuteCommand(task.id,task.params,options));return sequence(taskFns)}__name(sequenceExecute,"sequenceExecute");function sequenceExecuteAsync(tasks,commandService,options){const promises=tasks.map(task=>()=>commandService.executeCommand(task.id,task.params,options));return sequenceAsync(promises)}__name(sequenceExecuteAsync,"sequenceExecuteAsync");function fromCallback(callback){return new rxjs.Observable(subscriber=>{const disposable=callback((...args)=>subscriber.next(args));return()=>disposable==null?void 0:disposable.dispose()})}__name(fromCallback,"fromCallback");function takeAfter(callback){return __name(function(source){return new rxjs.Observable(subscriber=>(source.subscribe({next:__name(v=>{subscriber.next(v),callback(v)&&subscriber.complete()},"next"),complete:__name(()=>subscriber.complete(),"complete"),error:__name(error=>subscriber.error(error),"error")}),()=>subscriber.unsubscribe()))},"complateAfter")}__name(takeAfter,"takeAfter");const afterInitApply=__name(commandService=>new Promise(res=>{rxjs.merge(fromCallback(commandService.onCommandExecuted.bind(commandService)).pipe(operators.filter(([info])=>info.type===CommandType.MUTATION)),rxjs.timer(300)).pipe(operators.debounceTime(16),operators.first()).subscribe(()=>{res()})}),"afterInitApply");var I=(E=>(E[E.UNIVER_UNKNOWN=0]="UNIVER_UNKNOWN",E[E.UNIVER_DOC=1]="UNIVER_DOC",E[E.UNIVER_SHEET=2]="UNIVER_SHEET",E[E.UNIVER_SLIDE=3]="UNIVER_SLIDE",E[E.UNIVER_PROJECT=4]="UNIVER_PROJECT",E[E.UNRECOGNIZED=-1]="UNRECOGNIZED",E))(I||{}),G=(E=>(E[E.Reader=0]="Reader",E[E.Editor=1]="Editor",E[E.Owner=2]="Owner",E[E.UNRECOGNIZED=-1]="UNRECOGNIZED",E))(G||{}),H=(E=>(E[E.SomeCollaborator=0]="SomeCollaborator",E[E.AllCollaborator=1]="AllCollaborator",E[E.OneSelf=2]="OneSelf",E[E.UNRECOGNIZED=-1]="UNRECOGNIZED",E))(H||{});const _UnitModel=class _UnitModel extends Disposable{};__name(_UnitModel,"UnitModel");let UnitModel=_UnitModel;const _Registry=class _Registry{constructor(){__publicField(this,"_data",[])}static create(){return new _Registry}add(dataInstance){this._data.indexOf(dataInstance)>-1||this._data.push(dataInstance)}delete(dataInstance){const index2=this._data.indexOf(dataInstance);this._data.splice(index2,1)}getData(){return this._data}};__name(_Registry,"Registry");let Registry=_Registry;const _RegistryAsMap=class _RegistryAsMap{constructor(){__publicField(this,"_data",new Map)}static create(){return new _RegistryAsMap}add(id,dataInstance){this._data.has(id)||this._data.set(id,dataInstance)}delete(id){this._data.delete(id)}getData(){return this._data}};__name(_RegistryAsMap,"RegistryAsMap");let RegistryAsMap=_RegistryAsMap;var DataStreamTreeNodeType=(DataStreamTreeNodeType2=>(DataStreamTreeNodeType2.PARAGRAPH="PARAGRAPH",DataStreamTreeNodeType2.SECTION_BREAK="SECTION_BREAK",DataStreamTreeNodeType2.TABLE="TABLE",DataStreamTreeNodeType2.TABLE_ROW="TABLE_ROW",DataStreamTreeNodeType2.TABLE_CELL="TABLE_CELL",DataStreamTreeNodeType2.CUSTOM_BLOCK="CUSTOM_BLOCK",DataStreamTreeNodeType2))(DataStreamTreeNodeType||{}),DataStreamTreeTokenType=(DataStreamTreeTokenType2=>(DataStreamTreeTokenType2.PARAGRAPH="\r",DataStreamTreeTokenType2.SECTION_BREAK=`
7
7
  `,DataStreamTreeTokenType2.TABLE_START="",DataStreamTreeTokenType2.TABLE_ROW_START="\x1B",DataStreamTreeTokenType2.TABLE_CELL_START="",DataStreamTreeTokenType2.TABLE_CELL_END="",DataStreamTreeTokenType2.TABLE_ROW_END="",DataStreamTreeTokenType2.TABLE_END="",DataStreamTreeTokenType2.CUSTOM_RANGE_START="",DataStreamTreeTokenType2.CUSTOM_RANGE_END="",DataStreamTreeTokenType2.COLUMN_BREAK="\v",DataStreamTreeTokenType2.PAGE_BREAK="\f",DataStreamTreeTokenType2.DOCS_END="\0",DataStreamTreeTokenType2.TAB=" ",DataStreamTreeTokenType2.CUSTOM_BLOCK="\b",DataStreamTreeTokenType2.LETTER="",DataStreamTreeTokenType2.SPACE=" ",DataStreamTreeTokenType2))(DataStreamTreeTokenType||{});function makeCustomRangeStream(stream){return`${stream}`}__name(makeCustomRangeStream,"makeCustomRangeStream");var DocStyleType=(DocStyleType2=>(DocStyleType2[DocStyleType2.character=0]="character",DocStyleType2[DocStyleType2.paragraph=1]="paragraph",DocStyleType2[DocStyleType2.table=2]="table",DocStyleType2[DocStyleType2.numbering=3]="numbering",DocStyleType2))(DocStyleType||{}),FollowNumberWithType=(FollowNumberWithType2=>(FollowNumberWithType2[FollowNumberWithType2.TAB=0]="TAB",FollowNumberWithType2[FollowNumberWithType2.SPACE=1]="SPACE",FollowNumberWithType2[FollowNumberWithType2.NOTHING=2]="NOTHING",FollowNumberWithType2))(FollowNumberWithType||{}),GlyphType=(GlyphType2=>(GlyphType2[GlyphType2.BULLET=0]="BULLET",GlyphType2[GlyphType2.NONE=1]="NONE",GlyphType2[GlyphType2.DECIMAL=2]="DECIMAL",GlyphType2[GlyphType2.DECIMAL_ZERO=3]="DECIMAL_ZERO",GlyphType2[GlyphType2.UPPER_LETTER=4]="UPPER_LETTER",GlyphType2[GlyphType2.LOWER_LETTER=5]="LOWER_LETTER",GlyphType2[GlyphType2.UPPER_ROMAN=6]="UPPER_ROMAN",GlyphType2[GlyphType2.LOWER_ROMAN=7]="LOWER_ROMAN",GlyphType2[GlyphType2.ORDINAL=8]="ORDINAL",GlyphType2[GlyphType2.CARDINAL_TEXT=9]="CARDINAL_TEXT",GlyphType2[GlyphType2.ORDINAL_TEXT=10]="ORDINAL_TEXT",GlyphType2[GlyphType2.HEX=11]="HEX",GlyphType2[GlyphType2.CHICAGO=12]="CHICAGO",GlyphType2[GlyphType2.IDEOGRAPH_DIGITAL=13]="IDEOGRAPH_DIGITAL",GlyphType2[GlyphType2.JAPANESE_COUNTING=14]="JAPANESE_COUNTING",GlyphType2[GlyphType2.AIUEO=15]="AIUEO",GlyphType2[GlyphType2.IROHA=16]="IROHA",GlyphType2[GlyphType2.DECIMAL_FULL_WIDTH=17]="DECIMAL_FULL_WIDTH",GlyphType2[GlyphType2.DECIMAL_HALF_WIDTH=18]="DECIMAL_HALF_WIDTH",GlyphType2[GlyphType2.JAPANESE_LEGAL=19]="JAPANESE_LEGAL",GlyphType2[GlyphType2.JAPANESE_DIGITAL_TEN_THOUSAND=20]="JAPANESE_DIGITAL_TEN_THOUSAND",GlyphType2[GlyphType2.DECIMAL_ENCLOSED_CIRCLE=21]="DECIMAL_ENCLOSED_CIRCLE",GlyphType2[GlyphType2.DECIMAL_FULL_WIDTH2=22]="DECIMAL_FULL_WIDTH2",GlyphType2[GlyphType2.AIUEO_FULL_WIDTH=23]="AIUEO_FULL_WIDTH",GlyphType2[GlyphType2.IROHA_FULL_WIDTH=24]="IROHA_FULL_WIDTH",GlyphType2[GlyphType2.GANADA=25]="GANADA",GlyphType2[GlyphType2.CHOSUNG=26]="CHOSUNG",GlyphType2[GlyphType2.DECIMAL_ENCLOSED_FULLSTOP=27]="DECIMAL_ENCLOSED_FULLSTOP",GlyphType2[GlyphType2.DECIMAL_ENCLOSED_PAREN=28]="DECIMAL_ENCLOSED_PAREN",GlyphType2[GlyphType2.DECIMAL_ENCLOSED_CIRCLE_CHINESE=29]="DECIMAL_ENCLOSED_CIRCLE_CHINESE",GlyphType2[GlyphType2.IDEOGRAPH_ENCLOSED_CIRCLE=30]="IDEOGRAPH_ENCLOSED_CIRCLE",GlyphType2[GlyphType2.IDEOGRAPH_TRADITIONAL=31]="IDEOGRAPH_TRADITIONAL",GlyphType2[GlyphType2.IDEOGRAPH_ZODIAC=32]="IDEOGRAPH_ZODIAC",GlyphType2[GlyphType2.IDEOGRAPH_ZODIAC_TRADITIONAL=33]="IDEOGRAPH_ZODIAC_TRADITIONAL",GlyphType2[GlyphType2.TAIWANESE_COUNTING=34]="TAIWANESE_COUNTING",GlyphType2[GlyphType2.IDEOGRAPH_LEGAL_TRADITIONAL=35]="IDEOGRAPH_LEGAL_TRADITIONAL",GlyphType2[GlyphType2.TAIWANESE_COUNTING_THOUSAND=36]="TAIWANESE_COUNTING_THOUSAND",GlyphType2[GlyphType2.TAIWANESE_DIGITAL=37]="TAIWANESE_DIGITAL",GlyphType2[GlyphType2.CHINESE_COUNTING=38]="CHINESE_COUNTING",GlyphType2[GlyphType2.CHINESE_LEGAL_SIMPLIFIED=39]="CHINESE_LEGAL_SIMPLIFIED",GlyphType2[GlyphType2.CHINESE_COUNTING_THOUSAND=40]="CHINESE_COUNTING_THOUSAND",GlyphType2[GlyphType2.KOREAN_DIGITAL=41]="KOREAN_DIGITAL",GlyphType2[GlyphType2.KOREAN_COUNTING=42]="KOREAN_COUNTING",GlyphType2[GlyphType2.KOREAN_LEGAL=43]="KOREAN_LEGAL",GlyphType2[GlyphType2.KOREAN_DIGITAL2=44]="KOREAN_DIGITAL2",GlyphType2[GlyphType2.VIETNAMESE_COUNTING=45]="VIETNAMESE_COUNTING",GlyphType2[GlyphType2.RUSSIAN_LOWER=46]="RUSSIAN_LOWER",GlyphType2[GlyphType2.RUSSIAN_UPPER=47]="RUSSIAN_UPPER",GlyphType2[GlyphType2.NUMBER_IN_DASH=48]="NUMBER_IN_DASH",GlyphType2[GlyphType2.HEBREW1=49]="HEBREW1",GlyphType2[GlyphType2.HEBREW2=50]="HEBREW2",GlyphType2[GlyphType2.ARABIC_ALPHA=51]="ARABIC_ALPHA",GlyphType2[GlyphType2.ARABIC_ABJAD=52]="ARABIC_ABJAD",GlyphType2[GlyphType2.HINDI_VOWELS=53]="HINDI_VOWELS",GlyphType2[GlyphType2.HINDI_CONSONANTS=54]="HINDI_CONSONANTS",GlyphType2[GlyphType2.HINDI_NUMBERS=55]="HINDI_NUMBERS",GlyphType2[GlyphType2.HINDI_COUNTING=56]="HINDI_COUNTING",GlyphType2[GlyphType2.THAI_LETTERS=57]="THAI_LETTERS",GlyphType2[GlyphType2.THAI_NUMBERS=58]="THAI_NUMBERS",GlyphType2[GlyphType2.THAI_COUNTING=59]="THAI_COUNTING",GlyphType2[GlyphType2.CUSTOM=60]="CUSTOM",GlyphType2))(GlyphType||{}),BulletAlignment=(BulletAlignment2=>(BulletAlignment2[BulletAlignment2.BULLET_ALIGNMENT_UNSPECIFIED=0]="BULLET_ALIGNMENT_UNSPECIFIED",BulletAlignment2[BulletAlignment2.START=1]="START",BulletAlignment2[BulletAlignment2.CENTER=2]="CENTER",BulletAlignment2[BulletAlignment2.END=3]="END",BulletAlignment2[BulletAlignment2.BOTH=4]="BOTH",BulletAlignment2))(BulletAlignment||{}),CustomRangeType=(CustomRangeType2=>(CustomRangeType2[CustomRangeType2.HYPERLINK=0]="HYPERLINK",CustomRangeType2[CustomRangeType2.FIELD=1]="FIELD",CustomRangeType2[CustomRangeType2.SDT=2]="SDT",CustomRangeType2[CustomRangeType2.BOOKMARK=3]="BOOKMARK",CustomRangeType2[CustomRangeType2.COMMENT=4]="COMMENT",CustomRangeType2[CustomRangeType2.CUSTOM=5]="CUSTOM",CustomRangeType2[CustomRangeType2.MENTION=6]="MENTION",CustomRangeType2[CustomRangeType2.UNI_FORMULA=7]="UNI_FORMULA",CustomRangeType2))(CustomRangeType||{}),CustomDecorationType=(CustomDecorationType2=>(CustomDecorationType2[CustomDecorationType2.COMMENT=0]="COMMENT",CustomDecorationType2))(CustomDecorationType||{}),BlockType=(BlockType2=>(BlockType2[BlockType2.DRAWING=0]="DRAWING",BlockType2[BlockType2.CUSTOM=1]="CUSTOM",BlockType2))(BlockType||{}),DocumentFlavor=(DocumentFlavor2=>(DocumentFlavor2[DocumentFlavor2.TRADITIONAL=0]="TRADITIONAL",DocumentFlavor2[DocumentFlavor2.MODERN=1]="MODERN",DocumentFlavor2))(DocumentFlavor||{}),GridType=(GridType2=>(GridType2[GridType2.DEFAULT=0]="DEFAULT",GridType2[GridType2.LINES=1]="LINES",GridType2[GridType2.LINES_AND_CHARS=2]="LINES_AND_CHARS",GridType2[GridType2.SNAP_TO_CHARS=3]="SNAP_TO_CHARS",GridType2))(GridType||{}),SectionType=(SectionType2=>(SectionType2[SectionType2.SECTION_TYPE_UNSPECIFIED=0]="SECTION_TYPE_UNSPECIFIED",SectionType2[SectionType2.CONTINUOUS=1]="CONTINUOUS",SectionType2[SectionType2.NEXT_PAGE=2]="NEXT_PAGE",SectionType2[SectionType2.EVEN_PAGE=3]="EVEN_PAGE",SectionType2[SectionType2.ODD_PAGE=4]="ODD_PAGE",SectionType2))(SectionType||{}),ColumnSeparatorType=(ColumnSeparatorType2=>(ColumnSeparatorType2[ColumnSeparatorType2.COLUMN_SEPARATOR_STYLE_UNSPECIFIED=0]="COLUMN_SEPARATOR_STYLE_UNSPECIFIED",ColumnSeparatorType2[ColumnSeparatorType2.NONE=1]="NONE",ColumnSeparatorType2[ColumnSeparatorType2.BETWEEN_EACH_COLUMN=2]="BETWEEN_EACH_COLUMN",ColumnSeparatorType2))(ColumnSeparatorType||{}),TextDirectionType=(TextDirectionType2=>(TextDirectionType2[TextDirectionType2.NORMAL=0]="NORMAL",TextDirectionType2[TextDirectionType2.TBRL=1]="TBRL",TextDirectionType2[TextDirectionType2.LRTBV=2]="LRTBV",TextDirectionType2))(TextDirectionType||{}),ParagraphElementType=(ParagraphElementType2=>(ParagraphElementType2[ParagraphElementType2.TEXT_RUN=0]="TEXT_RUN",ParagraphElementType2[ParagraphElementType2.AUTO_TEXT=1]="AUTO_TEXT",ParagraphElementType2[ParagraphElementType2.PAGE_BREAK=2]="PAGE_BREAK",ParagraphElementType2[ParagraphElementType2.COLUMN_BREAK=3]="COLUMN_BREAK",ParagraphElementType2[ParagraphElementType2.FOOT_NOTE_REFERENCE=4]="FOOT_NOTE_REFERENCE",ParagraphElementType2[ParagraphElementType2.HORIZONTAL_RULE=5]="HORIZONTAL_RULE",ParagraphElementType2[ParagraphElementType2.EQUATION=6]="EQUATION",ParagraphElementType2[ParagraphElementType2.DRAWING=7]="DRAWING",ParagraphElementType2[ParagraphElementType2.PERSON=8]="PERSON",ParagraphElementType2[ParagraphElementType2.RICH_LINK=9]="RICH_LINK",ParagraphElementType2))(ParagraphElementType||{}),WrapTextType=(WrapTextType2=>(WrapTextType2[WrapTextType2.BOTH_SIDES=0]="BOTH_SIDES",WrapTextType2[WrapTextType2.LEFT=1]="LEFT",WrapTextType2[WrapTextType2.RIGHT=2]="RIGHT",WrapTextType2[WrapTextType2.LARGEST=3]="LARGEST",WrapTextType2))(WrapTextType||{}),PositionedObjectLayoutType=(PositionedObjectLayoutType2=>(PositionedObjectLayoutType2[PositionedObjectLayoutType2.INLINE=0]="INLINE",PositionedObjectLayoutType2[PositionedObjectLayoutType2.WRAP_NONE=1]="WRAP_NONE",PositionedObjectLayoutType2[PositionedObjectLayoutType2.WRAP_POLYGON=2]="WRAP_POLYGON",PositionedObjectLayoutType2[PositionedObjectLayoutType2.WRAP_SQUARE=3]="WRAP_SQUARE",PositionedObjectLayoutType2[PositionedObjectLayoutType2.WRAP_THROUGH=4]="WRAP_THROUGH",PositionedObjectLayoutType2[PositionedObjectLayoutType2.WRAP_TIGHT=5]="WRAP_TIGHT",PositionedObjectLayoutType2[PositionedObjectLayoutType2.WRAP_TOP_AND_BOTTOM=6]="WRAP_TOP_AND_BOTTOM",PositionedObjectLayoutType2))(PositionedObjectLayoutType||{}),NamedStyleType=(NamedStyleType2=>(NamedStyleType2[NamedStyleType2.NAMED_STYLE_TYPE_UNSPECIFIED=0]="NAMED_STYLE_TYPE_UNSPECIFIED",NamedStyleType2[NamedStyleType2.NORMAL_TEXT=1]="NORMAL_TEXT",NamedStyleType2[NamedStyleType2.TITLE=2]="TITLE",NamedStyleType2[NamedStyleType2.SUBTITLE=3]="SUBTITLE",NamedStyleType2[NamedStyleType2.HEADING_1=4]="HEADING_1",NamedStyleType2[NamedStyleType2.HEADING_2=5]="HEADING_2",NamedStyleType2[NamedStyleType2.HEADING_3=6]="HEADING_3",NamedStyleType2[NamedStyleType2.HEADING_4=7]="HEADING_4",NamedStyleType2[NamedStyleType2.HEADING_5=8]="HEADING_5",NamedStyleType2[NamedStyleType2.HEADING_6=9]="HEADING_6",NamedStyleType2))(NamedStyleType||{}),SpacingRule=(SpacingRule2=>(SpacingRule2[SpacingRule2.AUTO=0]="AUTO",SpacingRule2[SpacingRule2.AT_LEAST=1]="AT_LEAST",SpacingRule2[SpacingRule2.EXACT=2]="EXACT",SpacingRule2))(SpacingRule||{}),DashStyleType=(DashStyleType2=>(DashStyleType2[DashStyleType2.DASH_STYLE_UNSPECIFIED=0]="DASH_STYLE_UNSPECIFIED",DashStyleType2[DashStyleType2.SOLID=1]="SOLID",DashStyleType2[DashStyleType2.DOT=2]="DOT",DashStyleType2[DashStyleType2.DASH=3]="DASH",DashStyleType2))(DashStyleType||{}),TabStopAlignment=(TabStopAlignment2=>(TabStopAlignment2[TabStopAlignment2.TAB_STOP_ALIGNMENT_UNSPECIFIED=0]="TAB_STOP_ALIGNMENT_UNSPECIFIED",TabStopAlignment2[TabStopAlignment2.START=1]="START",TabStopAlignment2[TabStopAlignment2.CENTER=2]="CENTER",TabStopAlignment2[TabStopAlignment2.END=3]="END",TabStopAlignment2))(TabStopAlignment||{}),TableSizeType=(TableSizeType2=>(TableSizeType2[TableSizeType2.UNSPECIFIED=0]="UNSPECIFIED",TableSizeType2[TableSizeType2.SPECIFIED=1]="SPECIFIED",TableSizeType2))(TableSizeType||{}),TableAlignmentType=(TableAlignmentType2=>(TableAlignmentType2[TableAlignmentType2.START=0]="START",TableAlignmentType2[TableAlignmentType2.CENTER=1]="CENTER",TableAlignmentType2[TableAlignmentType2.END=2]="END",TableAlignmentType2))(TableAlignmentType||{}),TableLayoutType=(TableLayoutType2=>(TableLayoutType2[TableLayoutType2.AUTO_FIT=0]="AUTO_FIT",TableLayoutType2[TableLayoutType2.FIXED=1]="FIXED",TableLayoutType2))(TableLayoutType||{}),TableTextWrapType=(TableTextWrapType2=>(TableTextWrapType2[TableTextWrapType2.NONE=0]="NONE",TableTextWrapType2[TableTextWrapType2.WRAP=1]="WRAP",TableTextWrapType2))(TableTextWrapType||{}),TableCellHeightRule=(TableCellHeightRule2=>(TableCellHeightRule2[TableCellHeightRule2.AUTO=0]="AUTO",TableCellHeightRule2[TableCellHeightRule2.AT_LEAST=1]="AT_LEAST",TableCellHeightRule2[TableCellHeightRule2.EXACT=2]="EXACT",TableCellHeightRule2))(TableCellHeightRule||{}),VerticalAlignmentType=(VerticalAlignmentType2=>(VerticalAlignmentType2[VerticalAlignmentType2.CONTENT_ALIGNMENT_UNSPECIFIED=0]="CONTENT_ALIGNMENT_UNSPECIFIED",VerticalAlignmentType2[VerticalAlignmentType2.BOTH=1]="BOTH",VerticalAlignmentType2[VerticalAlignmentType2.TOP=2]="TOP",VerticalAlignmentType2[VerticalAlignmentType2.CENTER=3]="CENTER",VerticalAlignmentType2[VerticalAlignmentType2.BOTTOM=4]="BOTTOM",VerticalAlignmentType2))(VerticalAlignmentType||{}),FontStyleType=(FontStyleType2=>(FontStyleType2.NORMAL="normal",FontStyleType2.BOLD="bold",FontStyleType2.ITALIC="italic",FontStyleType2))(FontStyleType||{}),ObjectRelativeFromH=(ObjectRelativeFromH2=>(ObjectRelativeFromH2[ObjectRelativeFromH2.PAGE=0]="PAGE",ObjectRelativeFromH2[ObjectRelativeFromH2.COLUMN=1]="COLUMN",ObjectRelativeFromH2[ObjectRelativeFromH2.CHARACTER=2]="CHARACTER",ObjectRelativeFromH2[ObjectRelativeFromH2.MARGIN=3]="MARGIN",ObjectRelativeFromH2[ObjectRelativeFromH2.INSIDE_MARGIN=4]="INSIDE_MARGIN",ObjectRelativeFromH2[ObjectRelativeFromH2.OUTSIDE_MARGIN=5]="OUTSIDE_MARGIN",ObjectRelativeFromH2[ObjectRelativeFromH2.LEFT_MARGIN=6]="LEFT_MARGIN",ObjectRelativeFromH2[ObjectRelativeFromH2.RIGHT_MARGIN=7]="RIGHT_MARGIN",ObjectRelativeFromH2))(ObjectRelativeFromH||{}),ObjectRelativeFromV=(ObjectRelativeFromV2=>(ObjectRelativeFromV2[ObjectRelativeFromV2.PAGE=0]="PAGE",ObjectRelativeFromV2[ObjectRelativeFromV2.PARAGRAPH=1]="PARAGRAPH",ObjectRelativeFromV2[ObjectRelativeFromV2.LINE=2]="LINE",ObjectRelativeFromV2[ObjectRelativeFromV2.MARGIN=3]="MARGIN",ObjectRelativeFromV2[ObjectRelativeFromV2.TOP_MARGIN=4]="TOP_MARGIN",ObjectRelativeFromV2[ObjectRelativeFromV2.BOTTOM_MARGIN=5]="BOTTOM_MARGIN",ObjectRelativeFromV2[ObjectRelativeFromV2.INSIDE_MARGIN=6]="INSIDE_MARGIN",ObjectRelativeFromV2[ObjectRelativeFromV2.OUTSIDE_MARGIN=7]="OUTSIDE_MARGIN",ObjectRelativeFromV2))(ObjectRelativeFromV||{}),NumberUnitType=(NumberUnitType2=>(NumberUnitType2[NumberUnitType2.POINT=0]="POINT",NumberUnitType2[NumberUnitType2.LINE=1]="LINE",NumberUnitType2[NumberUnitType2.CHARACTER=2]="CHARACTER",NumberUnitType2[NumberUnitType2.PIXEL=3]="PIXEL",NumberUnitType2[NumberUnitType2.PERCENT=4]="PERCENT",NumberUnitType2))(NumberUnitType||{}),AlignTypeH=(AlignTypeH2=>(AlignTypeH2[AlignTypeH2.CENTER=0]="CENTER",AlignTypeH2[AlignTypeH2.INSIDE=1]="INSIDE",AlignTypeH2[AlignTypeH2.LEFT=2]="LEFT",AlignTypeH2[AlignTypeH2.OUTSIDE=3]="OUTSIDE",AlignTypeH2[AlignTypeH2.RIGHT=4]="RIGHT",AlignTypeH2[AlignTypeH2.BOTH=5]="BOTH",AlignTypeH2[AlignTypeH2.DISTRIBUTE=6]="DISTRIBUTE",AlignTypeH2))(AlignTypeH||{}),AlignTypeV=(AlignTypeV2=>(AlignTypeV2[AlignTypeV2.BOTTOM=0]="BOTTOM",AlignTypeV2[AlignTypeV2.CENTER=1]="CENTER",AlignTypeV2[AlignTypeV2.INSIDE=2]="INSIDE",AlignTypeV2[AlignTypeV2.OUTSIDE=3]="OUTSIDE",AlignTypeV2[AlignTypeV2.TOP=4]="TOP",AlignTypeV2))(AlignTypeV||{}),characterSpacingControlType=(characterSpacingControlType2=>(characterSpacingControlType2[characterSpacingControlType2.compressPunctuation=0]="compressPunctuation",characterSpacingControlType2[characterSpacingControlType2.compressPunctuationAndJapaneseKana=1]="compressPunctuationAndJapaneseKana",characterSpacingControlType2[characterSpacingControlType2.doNotCompress=2]="doNotCompress",characterSpacingControlType2))(characterSpacingControlType||{}),PageOrientType=(PageOrientType2=>(PageOrientType2[PageOrientType2.PORTRAIT=0]="PORTRAIT",PageOrientType2[PageOrientType2.LANDSCAPE=1]="LANDSCAPE",PageOrientType2))(PageOrientType||{}),ArrangeTypeEnum=(ArrangeTypeEnum2=>(ArrangeTypeEnum2[ArrangeTypeEnum2.forward=0]="forward",ArrangeTypeEnum2[ArrangeTypeEnum2.backward=1]="backward",ArrangeTypeEnum2[ArrangeTypeEnum2.front=2]="front",ArrangeTypeEnum2[ArrangeTypeEnum2.back=3]="back",ArrangeTypeEnum2))(ArrangeTypeEnum||{}),DrawingTypeEnum=(DrawingTypeEnum2=>(DrawingTypeEnum2[DrawingTypeEnum2.UNRECOGNIZED=-1]="UNRECOGNIZED",DrawingTypeEnum2[DrawingTypeEnum2.DRAWING_IMAGE=0]="DRAWING_IMAGE",DrawingTypeEnum2[DrawingTypeEnum2.DRAWING_SHAPE=1]="DRAWING_SHAPE",DrawingTypeEnum2[DrawingTypeEnum2.DRAWING_CHART=2]="DRAWING_CHART",DrawingTypeEnum2[DrawingTypeEnum2.DRAWING_TABLE=3]="DRAWING_TABLE",DrawingTypeEnum2[DrawingTypeEnum2.DRAWING_SMART_ART=4]="DRAWING_SMART_ART",DrawingTypeEnum2[DrawingTypeEnum2.DRAWING_VIDEO=5]="DRAWING_VIDEO",DrawingTypeEnum2[DrawingTypeEnum2.DRAWING_GROUP=6]="DRAWING_GROUP",DrawingTypeEnum2[DrawingTypeEnum2.DRAWING_UNIT=7]="DRAWING_UNIT",DrawingTypeEnum2[DrawingTypeEnum2.DRAWING_DOM=8]="DRAWING_DOM",DrawingTypeEnum2))(DrawingTypeEnum||{}),QuickListType=(QuickListType2=>(QuickListType2.ORDER_LIST_QUICK_1="1.",QuickListType2.ORDER_LIST_QUICK_2="a)",QuickListType2.ORDER_LIST_QUICK_3="a.",QuickListType2.ORDER_LIST_QUICK_4="i.",QuickListType2.ORDER_LIST_QUICK_5="A.",QuickListType2.ORDER_LIST_QUICK_6="I.",QuickListType2.ORDER_LIST_QUICK_7="01.",QuickListType2))(QuickListType||{}),PresetListType=(PresetListType2=>(PresetListType2.BULLET_LIST="BULLET_LIST",PresetListType2.BULLET_LIST_1="BULLET_LIST_1",PresetListType2.BULLET_LIST_2="BULLET_LIST_2",PresetListType2.BULLET_LIST_3="BULLET_LIST_3",PresetListType2.BULLET_LIST_4="BULLET_LIST_4",PresetListType2.BULLET_LIST_5="BULLET_LIST_5",PresetListType2.ORDER_LIST="ORDER_LIST",PresetListType2.ORDER_LIST_1="ORDER_LIST_1",PresetListType2.ORDER_LIST_2="ORDER_LIST_2",PresetListType2.ORDER_LIST_3="ORDER_LIST_3",PresetListType2.ORDER_LIST_4="ORDER_LIST_4",PresetListType2.ORDER_LIST_5="ORDER_LIST_5",PresetListType2.ORDER_LIST_QUICK_2="ORDER_LIST_QUICK_2",PresetListType2.ORDER_LIST_QUICK_3="ORDER_LIST_QUICK_3",PresetListType2.ORDER_LIST_QUICK_4="ORDER_LIST_QUICK_4",PresetListType2.ORDER_LIST_QUICK_5="ORDER_LIST_QUICK_5",PresetListType2.ORDER_LIST_QUICK_6="ORDER_LIST_QUICK_6",PresetListType2.CHECK_LIST="CHECK_LIST",PresetListType2.CHECK_LIST_CHECKED="CHECK_LIST_CHECKED",PresetListType2))(PresetListType||{});const orderListSymbolMap={"a)":{glyphFormat:"%1)",glyphType:GlyphType.DECIMAL},"1.":{glyphFormat:"%1.",glyphType:GlyphType.DECIMAL},"a.":{glyphFormat:"%1.",glyphType:GlyphType.LOWER_LETTER},"A.":{glyphFormat:"%1.",glyphType:GlyphType.UPPER_LETTER},"i.":{glyphFormat:"%1.",glyphType:GlyphType.LOWER_ROMAN},"I.":{glyphFormat:"%1.",glyphType:GlyphType.UPPER_LETTER}},bulletListFactory=__name(symbols=>[...symbols,...symbols,...symbols].map((templateSymbol,i)=>({glyphFormat:` %${i+1}`,glyphSymbol:templateSymbol,bulletAlignment:BulletAlignment.START,textStyle:{fs:12},startNumber:0,paragraphProperties:{hanging:{v:21},indentStart:{v:21*(i+1)}}})),"bulletListFactory"),orderListFactory=__name(options=>options.map((format,i)=>({...format,bulletAlignment:BulletAlignment.START,textStyle:{fs:12},startNumber:0,paragraphProperties:{hanging:{v:21},indentStart:{v:21*(i+1)}}})),"orderListFactory"),checkListFactory=__name((symbol,textStyle)=>Array(9).fill(0).map((_,i)=>({glyphFormat:` %${i+1}`,glyphSymbol:symbol,bulletAlignment:BulletAlignment.START,textStyle:{fs:16},startNumber:0,paragraphProperties:{hanging:{v:21},indentStart:{v:21*(i+1)},textStyle}})),"checkListFactory"),PRESET_LIST_TYPE={BULLET_LIST:{listType:"BULLET_LIST",nestingLevel:bulletListFactory(["●","○","■"])},BULLET_LIST_1:{listType:"BULLET_LIST",nestingLevel:bulletListFactory(["❖","➢","■"])},BULLET_LIST_2:{listType:"BULLET_LIST",nestingLevel:bulletListFactory(["✔","●","◆"])},BULLET_LIST_3:{listType:"BULLET_LIST",nestingLevel:bulletListFactory(["■","◆","○"])},BULLET_LIST_4:{listType:"BULLET_LIST",nestingLevel:bulletListFactory(["✧","○","■"])},BULLET_LIST_5:{listType:"BULLET_LIST",nestingLevel:bulletListFactory(["➢","○","◆"])},ORDER_LIST:{listType:"ORDER_LIST",nestingLevel:orderListFactory([{glyphFormat:"%1.",glyphType:GlyphType.DECIMAL},{glyphFormat:"%2.",glyphType:GlyphType.LOWER_LETTER},{glyphFormat:"%3.",glyphType:GlyphType.LOWER_ROMAN},{glyphFormat:"%4.",glyphType:GlyphType.DECIMAL},{glyphFormat:"%5.",glyphType:GlyphType.LOWER_LETTER},{glyphFormat:"%6.",glyphType:GlyphType.LOWER_ROMAN},{glyphFormat:"%7.",glyphType:GlyphType.DECIMAL},{glyphFormat:"%8.",glyphType:GlyphType.LOWER_LETTER},{glyphFormat:"%9.",glyphType:GlyphType.LOWER_ROMAN}])},ORDER_LIST_1:{listType:"ORDER_LIST",nestingLevel:orderListFactory([{glyphFormat:"%1)",glyphType:GlyphType.DECIMAL},{glyphFormat:"%2)",glyphType:GlyphType.LOWER_LETTER},{glyphFormat:"%3)",glyphType:GlyphType.LOWER_ROMAN},{glyphFormat:"%4)",glyphType:GlyphType.DECIMAL},{glyphFormat:"%5)",glyphType:GlyphType.LOWER_LETTER},{glyphFormat:"%6)",glyphType:GlyphType.LOWER_ROMAN},{glyphFormat:"%7)",glyphType:GlyphType.DECIMAL},{glyphFormat:"%8)",glyphType:GlyphType.LOWER_LETTER},{glyphFormat:"%9)",glyphType:GlyphType.LOWER_ROMAN}])},ORDER_LIST_2:{listType:"ORDER_LIST",nestingLevel:orderListFactory(["%1.","%1.%2.","%1.%2.%3.","%1.%2.%3.%4.","%1.%2.%3.%4.%5.","%1.%2.%3.%4.%5.%6.","%1.%2.%3.%4.%5.%6.%7."].map(format=>({glyphFormat:format,glyphType:GlyphType.DECIMAL})))},ORDER_LIST_3:{listType:"ORDER_LIST",nestingLevel:orderListFactory([{glyphFormat:"%1.",glyphType:GlyphType.UPPER_LETTER},{glyphFormat:"%2.",glyphType:GlyphType.LOWER_LETTER},{glyphFormat:"%3.",glyphType:GlyphType.LOWER_ROMAN},{glyphFormat:"%4.",glyphType:GlyphType.UPPER_LETTER},{glyphFormat:"%5.",glyphType:GlyphType.LOWER_LETTER},{glyphFormat:"%6.",glyphType:GlyphType.LOWER_ROMAN},{glyphFormat:"%7.",glyphType:GlyphType.UPPER_LETTER},{glyphFormat:"%8.",glyphType:GlyphType.LOWER_LETTER},{glyphFormat:"%9.",glyphType:GlyphType.LOWER_ROMAN}])},ORDER_LIST_4:{listType:"ORDER_LIST",nestingLevel:orderListFactory([{glyphFormat:"%1.",glyphType:GlyphType.UPPER_LETTER},{glyphFormat:"%2.",glyphType:GlyphType.DECIMAL},{glyphFormat:"%3.",glyphType:GlyphType.LOWER_ROMAN},{glyphFormat:"%4.",glyphType:GlyphType.UPPER_LETTER},{glyphFormat:"%5.",glyphType:GlyphType.DECIMAL},{glyphFormat:"%6.",glyphType:GlyphType.LOWER_ROMAN},{glyphFormat:"%7.",glyphType:GlyphType.UPPER_LETTER},{glyphFormat:"%8.",glyphType:GlyphType.DECIMAL},{glyphFormat:"%9.",glyphType:GlyphType.LOWER_ROMAN}])},ORDER_LIST_5:{listType:"ORDER_LIST",nestingLevel:orderListFactory([{glyphFormat:"%1.",glyphType:GlyphType.DECIMAL_ZERO},{glyphFormat:"%2.",glyphType:GlyphType.LOWER_LETTER},{glyphFormat:"%3.",glyphType:GlyphType.LOWER_ROMAN},{glyphFormat:"%4.",glyphType:GlyphType.DECIMAL_ZERO},{glyphFormat:"%5.",glyphType:GlyphType.LOWER_LETTER},{glyphFormat:"%6.",glyphType:GlyphType.LOWER_ROMAN},{glyphFormat:"%7.",glyphType:GlyphType.DECIMAL_ZERO},{glyphFormat:"%8.",glyphType:GlyphType.LOWER_LETTER},{glyphFormat:"%9.",glyphType:GlyphType.LOWER_ROMAN}])},CHECK_LIST:{listType:"CHECK_LIST",nestingLevel:checkListFactory("☐")},CHECK_LIST_CHECKED:{listType:"CHECK_LIST_CHECKED",nestingLevel:checkListFactory("☑",{st:{s:BooleanNumber.TRUE}})}},generateOrderList=__name(opt=>{const{glyphFormat,glyphType}=opt,data=Tools.deepClone(PRESET_LIST_TYPE.ORDER_LIST);return data.nestingLevel[0].glyphFormat=glyphFormat,data.nestingLevel[0].glyphType=glyphType,data},"generateOrderList"),QUICK_LIST_TYPE={ORDER_LIST_QUICK_2:generateOrderList(orderListSymbolMap["a)"]),ORDER_LIST_QUICK_3:generateOrderList(orderListSymbolMap["a."]),ORDER_LIST_QUICK_4:generateOrderList(orderListSymbolMap["i."]),ORDER_LIST_QUICK_6:generateOrderList(orderListSymbolMap["I."])};Object.assign(PRESET_LIST_TYPE,QUICK_LIST_TYPE);const QuickListTypeMap={"1.":"ORDER_LIST","a)":"ORDER_LIST_QUICK_2","a.":"ORDER_LIST_QUICK_3","i.":"ORDER_LIST_QUICK_4","A.":"ORDER_LIST_3","I.":"ORDER_LIST_QUICK_6","01.":"ORDER_LIST_5"};function normalizeTextRuns(textRuns){const results=[];for(const textRun of textRuns){const{ed,ts}=textRun;if(textRun.sId===void 0&&delete textRun.sId,Tools.isEmptyObject(ts)&&textRun.sId==null)continue;if(results.length===0){results.push(textRun);continue}const peak=results.pop();isSameStyleTextRun(textRun,peak)&&Tools.hasIntersectionBetweenTwoRanges(peak.st,peak.ed,textRun.st,textRun.ed)?results.push({...textRun,st:peak.st,ed}):results.push(peak,textRun)}return results}__name(normalizeTextRuns,"normalizeTextRuns");function insertTextRuns(body,insertBody,textLength,currentIndex){var _a13;const{textRuns}=body;if(textRuns==null)return;const newTextRuns=[],len=textRuns.length;let hasInserted=!1;const insertTextRuns2=(_a13=insertBody.textRuns)!=null?_a13:[];if(insertTextRuns2.length)for(const insertTextRun of insertTextRuns2)insertTextRun.st+=currentIndex,insertTextRun.ed+=currentIndex;for(let i=0;i<len;i++){const textRun=textRuns[i],nextRun=textRuns[i+1],{st,ed}=textRun;if(ed<currentIndex)newTextRuns.push(textRun);else if(currentIndex>=st&&currentIndex<=ed){if(nextRun&&nextRun.st===nextRun.ed&&currentIndex===nextRun.st){newTextRuns.push(textRun);continue}if(hasInserted)textRun.st+=textLength,textRun.ed+=textLength,newTextRuns.push(textRun);else{hasInserted=!0,textRun.ed+=textLength;const pendingTextRuns=[];if(insertTextRuns2.length){const startSplitTextRun={...textRun,st,ed:insertTextRuns2[0].st};startSplitTextRun.ed>startSplitTextRun.st&&pendingTextRuns.push(startSplitTextRun),pendingTextRuns.push(...insertTextRuns2);const lastInsertTextRuns=insertTextRuns2[insertTextRuns2.length-1],endSplitTextRun={...textRun,st:lastInsertTextRuns.ed,ed:ed+textLength};endSplitTextRun.ed>endSplitTextRun.st&&pendingTextRuns.push(endSplitTextRun)}else pendingTextRuns.push(textRun);newTextRuns.push(...pendingTextRuns)}}else textRun.st+=textLength,textRun.ed+=textLength,hasInserted||(hasInserted=!0,newTextRuns.push(...insertTextRuns2)),newTextRuns.push(textRun)}hasInserted||(hasInserted=!0,newTextRuns.push(...insertTextRuns2)),body.textRuns=normalizeTextRuns(newTextRuns)}__name(insertTextRuns,"insertTextRuns");function insertParagraphs(body,insertBody,textLength,currentIndex){const{paragraphs}=body;if(paragraphs==null)return;const{paragraphs:insertParagraphs2,dataStream:insertDataStream}=insertBody,paragraphIndexList=[];let firstInsertParagraphNextIndex=-1;for(let i=0,len=paragraphs.length;i<len;i++){const paragraph=paragraphs[i],{startIndex}=paragraph;startIndex>=currentIndex&&(paragraph.startIndex+=textLength),firstInsertParagraphNextIndex===-1&&startIndex>=currentIndex&&(firstInsertParagraphNextIndex=i),paragraphIndexList.push(paragraph.startIndex)}let deleteReptIndex=-1;if(insertParagraphs2){for(let i=0,len=insertParagraphs2.length;i<len;i++){const insertParagraph=insertParagraphs2[i];insertParagraph.startIndex+=currentIndex;const insertIndex=insertParagraph.startIndex;deleteReptIndex=paragraphIndexList.indexOf(insertIndex)}if(insertDataStream===DataStreamTreeTokenType.PARAGRAPH&&insertParagraphs2.length===1){const nextParagraph=paragraphs[firstInsertParagraphNextIndex],insertParagraph=insertParagraphs2[0],nextParagraphStyle=nextParagraph.paragraphStyle,nextBullet=nextParagraph.bullet;nextParagraph.paragraphStyle=insertParagraph.paragraphStyle,nextParagraph.bullet=insertParagraph.bullet,insertParagraph.paragraphStyle=nextParagraphStyle,insertParagraph.bullet=nextBullet}deleteReptIndex!==-1&&paragraphs.splice(deleteReptIndex,1),paragraphs.push(...insertParagraphs2),paragraphs.sort(sortRulesFactory("startIndex"))}}__name(insertParagraphs,"insertParagraphs");function insertSectionBreaks(body,insertBody,textLength,currentIndex){const{sectionBreaks}=body;if(sectionBreaks==null)return;for(let i=0,len=sectionBreaks.length;i<len;i++){const sectionBreak=sectionBreaks[i],{startIndex}=sectionBreak;startIndex>=currentIndex&&(sectionBreak.startIndex+=textLength)}const insertSectionBreaks2=insertBody.sectionBreaks;if(insertSectionBreaks2){for(let i=0,len=insertSectionBreaks2.length;i<len;i++){const sectionBreak=insertSectionBreaks2[i];sectionBreak.startIndex+=currentIndex}sectionBreaks.push(...insertSectionBreaks2),sectionBreaks.sort(sortRulesFactory("startIndex"))}}__name(insertSectionBreaks,"insertSectionBreaks");function insertCustomBlocks(body,insertBody,textLength,currentIndex){const{customBlocks}=body;if(customBlocks==null)return;for(let i=0,len=customBlocks.length;i<len;i++){const customBlock=customBlocks[i],{startIndex}=customBlock;startIndex>=currentIndex&&(customBlock.startIndex+=textLength)}const insertCustomBlocks2=insertBody.customBlocks;if(insertCustomBlocks2){for(let i=0,len=insertCustomBlocks2.length;i<len;i++){const customBlock=insertCustomBlocks2[i];customBlock.startIndex+=currentIndex}customBlocks.push(...insertCustomBlocks2),customBlocks.sort(sortRulesFactory("startIndex"))}}__name(insertCustomBlocks,"insertCustomBlocks");function insertTables(body,insertBody,textLength,currentIndex){const{tables}=body;if(tables==null)return;for(let i=0,len=tables.length;i<len;i++){const table=tables[i],{startIndex,endIndex}=table;startIndex>currentIndex?(table.startIndex+=textLength,table.endIndex+=textLength):endIndex>currentIndex&&(table.endIndex+=textLength)}const insertTables2=insertBody.tables;if(insertTables2){for(let i=0,len=insertTables2.length;i<len;i++){const table=insertTables2[i];table.startIndex+=currentIndex,table.endIndex+=currentIndex}tables.push(...insertTables2),tables.sort(sortRulesFactory("startIndex"))}}__name(insertTables,"insertTables");function insertCustomRanges(body,insertBody,textLength,currentIndex){body.customRanges||(body.customRanges=[]);const{customRanges}=body,customRangeMap={};for(let i=0,len=customRanges.length;i<len;i++){const customRange=customRanges[i];customRangeMap[customRange.rangeId]=customRange;const{startIndex,endIndex}=customRange;startIndex>=currentIndex?(customRange.startIndex+=textLength,customRange.endIndex+=textLength):endIndex>currentIndex-1&&(customRange.endIndex+=textLength)}if(customRanges.find(range=>range.startIndex>currentIndex&&range.endIndex<currentIndex))return;const insertCustomRanges2=[];if(insertBody.customRanges){for(let i=0,len=insertBody.customRanges.length;i<len;i++){const customRange=insertBody.customRanges[i],oldCustomRange=customRangeMap[customRange.rangeId];if(customRange.startIndex+=currentIndex,customRange.endIndex+=currentIndex,oldCustomRange){if(oldCustomRange.startIndex<=customRange.startIndex&&oldCustomRange.endIndex>=customRange.endIndex)continue;if(body.dataStream[oldCustomRange.startIndex]===DataStreamTreeTokenType.CUSTOM_RANGE_START&&body.dataStream[oldCustomRange.endIndex]===DataStreamTreeTokenType.CUSTOM_RANGE_END){insertCustomRanges2.push(customRange);continue}if(body.dataStream[oldCustomRange.startIndex]===DataStreamTreeTokenType.CUSTOM_RANGE_START){oldCustomRange.endIndex=customRange.endIndex;continue}if(body.dataStream[oldCustomRange.endIndex]===DataStreamTreeTokenType.CUSTOM_RANGE_END){oldCustomRange.startIndex=customRange.startIndex;continue}}insertCustomRanges2.push(customRange)}customRanges.push(...insertCustomRanges2),customRanges.sort(sortRulesFactory("startIndex"))}}__name(insertCustomRanges,"insertCustomRanges");function mergeRanges(lineSegments){lineSegments.sort((a,b)=>a.startIndex-b.startIndex);const mergedSegments=[];let currentSegment=lineSegments[0];for(let i=1;i<lineSegments.length;i++)currentSegment.endIndex+1>=lineSegments[i].startIndex?currentSegment.endIndex=Math.max(currentSegment.endIndex,lineSegments[i].endIndex):(mergedSegments.push(currentSegment),currentSegment=lineSegments[i]);return mergedSegments.push(currentSegment),mergedSegments}__name(mergeRanges,"mergeRanges");function mergeDecorations(customDecorations){const customDecorationMap={};for(let i=0,len=customDecorations.length;i<len;i++){const customDecoration=customDecorations[i],currentDecorations=customDecorationMap[customDecoration.id];customDecorationMap[customDecoration.id]=[...currentDecorations!=null?currentDecorations:[],customDecoration]}return Object.keys(customDecorationMap).forEach(id=>{const decorations=customDecorationMap[id],newRanges=mergeRanges(decorations);customDecorationMap[id]=newRanges}),Object.values(customDecorationMap).flat()}__name(mergeDecorations,"mergeDecorations");function insertCustomDecorations(body,insertBody,textLength,currentIndex){body.customDecorations||(body.customDecorations=[]);const{customDecorations}=body;if(textLength>0)for(let i=0,len=customDecorations.length;i<len;i++){const customDecoration=customDecorations[i],{startIndex,endIndex}=customDecoration;startIndex>=currentIndex?(customDecoration.startIndex+=textLength,customDecoration.endIndex+=textLength):endIndex>currentIndex-1&&(customDecoration.endIndex+=textLength)}if(insertBody.customDecorations){const insertCustomDecorations2=[];for(let i=0,len=insertBody.customDecorations.length;i<len;i++){const customDecoration=insertBody.customDecorations[i];insertCustomDecorations2.push(customDecoration),customDecoration.startIndex+=currentIndex,customDecoration.endIndex+=currentIndex}customDecorations.push(...insertCustomDecorations2),body.customDecorations=mergeDecorations(customDecorations),body.customDecorations.sort(sortRulesFactory("startIndex"))}}__name(insertCustomDecorations,"insertCustomDecorations");function deleteTextRuns(body,textLength,currentIndex){var _a13;const{textRuns}=body,startIndex=currentIndex,endIndex=currentIndex+textLength,removeTextRuns=[];if(startIndex===endIndex&&(textRuns!=null&&textRuns.find(t=>t.st===currentIndex&&t.ed===currentIndex))){const textRun=textRuns.find(t=>t.st===currentIndex&&t.ed===currentIndex);return removeTextRuns.push({...textRun,st:textRun.st-currentIndex,ed:textRun.ed-currentIndex}),body.textRuns=(_a13=body.textRuns)==null?void 0:_a13.filter(t=>t!==textRun),removeTextRuns}if(textRuns){const newTextRuns=[];for(let i=0,len=textRuns.length;i<len;i++){const textRun=textRuns[i],{st,ed}=textRun;if(startIndex<=st&&endIndex>=ed)if(removeTextRuns.push({...textRun,st:st-startIndex,ed:ed-startIndex}),startIndex===st)textRun.ed=st;else continue;else st<=startIndex&&ed>=endIndex?(removeTextRuns.push({...textRun,st:startIndex-startIndex,ed:endIndex-startIndex}),textRun.ed-=textLength):startIndex>=st&&startIndex<ed?(removeTextRuns.push({...textRun,st:startIndex-startIndex,ed:ed-startIndex}),textRun.ed=startIndex):endIndex>st&&endIndex<=ed?(removeTextRuns.push({...textRun,st:st-startIndex,ed:endIndex-startIndex}),textRun.st=endIndex-textLength,textRun.ed-=textLength):st>=endIndex&&(textRun.st-=textLength,textRun.ed-=textLength);newTextRuns.push(textRun)}body.textRuns=newTextRuns}return removeTextRuns.length===0&&removeTextRuns.push({st:0,ed:textLength,ts:{}}),removeTextRuns}__name(deleteTextRuns,"deleteTextRuns");function deleteParagraphs(body,textLength,currentIndex){const{paragraphs}=body,startIndex=currentIndex,endIndex=currentIndex+textLength,removeParagraphs=[];if(paragraphs){const newParagraphs=[];for(let i=0,len=paragraphs.length;i<len;i++){const paragraph=paragraphs[i],{startIndex:index2}=paragraph;if(index2>=startIndex&&index2<endIndex){removeParagraphs.push({...paragraph,startIndex:index2-currentIndex});continue}else index2>=endIndex&&(paragraph.startIndex-=textLength);newParagraphs.push(paragraph)}body.paragraphs=newParagraphs}return removeParagraphs}__name(deleteParagraphs,"deleteParagraphs");function deleteSectionBreaks(body,textLength,currentIndex){const{sectionBreaks}=body,startIndex=currentIndex,endIndex=currentIndex+textLength-1,removeSectionBreaks=[];if(sectionBreaks){const newSectionBreaks=[];for(let i=0,len=sectionBreaks.length;i<len;i++){const sectionBreak=sectionBreaks[i],{startIndex:index2}=sectionBreak;if(index2>=startIndex&&index2<=endIndex){removeSectionBreaks.push({...sectionBreak,startIndex:index2-currentIndex});continue}else index2>endIndex&&(sectionBreak.startIndex-=textLength);newSectionBreaks.push(sectionBreak)}body.sectionBreaks=newSectionBreaks}return removeSectionBreaks}__name(deleteSectionBreaks,"deleteSectionBreaks");function deleteCustomBlocks(body,textLength,currentIndex){const{customBlocks}=body,startIndex=currentIndex,endIndex=currentIndex+textLength-1,removeCustomBlocks=[];if(customBlocks){const newCustomBlocks=[];for(let i=0,len=customBlocks.length;i<len;i++){const customBlock=customBlocks[i],{startIndex:index2}=customBlock;if(index2>=startIndex&&index2<=endIndex){removeCustomBlocks.push({...customBlock,startIndex:index2-currentIndex});continue}else index2>endIndex&&(customBlock.startIndex-=textLength);newCustomBlocks.push(customBlock)}body.customBlocks=newCustomBlocks}return removeCustomBlocks}__name(deleteCustomBlocks,"deleteCustomBlocks");function deleteTables(body,textLength,currentIndex){const{tables}=body,startIndex=currentIndex,endIndex=currentIndex+textLength-1,removeTables=[];if(tables){const newTables=[];for(let i=0,len=tables.length;i<len;i++){const table=tables[i],{startIndex:st,endIndex:ed}=table;if(startIndex<=st&&endIndex>=ed){removeTables.push({...table,startIndex:st-currentIndex,endIndex:ed-currentIndex});continue}else if(st<=startIndex&&ed>=endIndex){const segments=horizontalLineSegmentsSubtraction(st,ed,startIndex,endIndex);if(table.startIndex=segments[0],table.endIndex=segments[1],table.startIndex===table.endIndex)continue}else endIndex<st&&(table.startIndex-=textLength,table.endIndex-=textLength);newTables.push(table)}body.tables=newTables}return removeTables}__name(deleteTables,"deleteTables");function deleteCustomRanges(body,textLength,currentIndex){const{customRanges}=body,startIndex=currentIndex,endIndex=currentIndex+textLength-1,removeCustomRanges=[];if(customRanges){const newCustomRanges=[];for(let i=0,len=customRanges.length;i<len;i++){const customRange=customRanges[i],{startIndex:st,endIndex:ed}=customRange;if(startIndex<=st&&endIndex>=st){removeCustomRanges.push({...customRange,startIndex:st-currentIndex,endIndex:ed-currentIndex});continue}else if(st<=startIndex&&ed>=endIndex){const segments=horizontalLineSegmentsSubtraction(st,ed,startIndex,endIndex);customRange.startIndex=segments[0],customRange.endIndex=segments[1]}else endIndex<st&&(customRange.startIndex-=textLength,customRange.endIndex-=textLength);newCustomRanges.push(customRange)}body.customRanges=newCustomRanges}return removeCustomRanges}__name(deleteCustomRanges,"deleteCustomRanges");function deleteCustomDecorations(body,textLength,currentIndex,needOffset=!0){const{customDecorations}=body,startIndex=currentIndex,endIndex=currentIndex+textLength-1,removeCustomDecorations=[];if(customDecorations){const newCustomDecorations=[];for(let i=0,len=customDecorations.length;i<len;i++){const customDecoration=customDecorations[i],{startIndex:st,endIndex:ed}=customDecoration;if(st>=startIndex&&ed<=endIndex){removeCustomDecorations.push(customDecoration);continue}else if(Math.max(startIndex,st)<=Math.min(endIndex,ed)){const segments=horizontalLineSegmentsSubtraction(st,ed,startIndex,endIndex);customDecoration.startIndex=segments[0],customDecoration.endIndex=segments[1]}else endIndex<st&&needOffset&&(customDecoration.startIndex-=textLength,customDecoration.endIndex-=textLength);newCustomDecorations.push(customDecoration)}body.customDecorations=newCustomDecorations}return removeCustomDecorations}__name(deleteCustomDecorations,"deleteCustomDecorations");function updateAttribute(body,updateBody,textLength,currentIndex,coverType){const removeTextRuns=updateTextRuns(body,updateBody,textLength,currentIndex,coverType),removeParagraphs=updateParagraphs(body,updateBody,textLength,currentIndex,coverType),removeSectionBreaks=updateSectionBreaks(body,updateBody,textLength,currentIndex,coverType),removeCustomBlocks=updateCustomBlocks(body,updateBody,textLength,currentIndex,coverType),removeTables=updateTables(body,updateBody,textLength,currentIndex,coverType),removeCustomRanges=updateCustomRanges(body,updateBody,textLength,currentIndex,coverType),removeCustomDecorations=updateCustomDecorations(body,updateBody,textLength,currentIndex,coverType);return{dataStream:"",textRuns:removeTextRuns,paragraphs:removeParagraphs,sectionBreaks:removeSectionBreaks,customBlocks:removeCustomBlocks,tables:removeTables,customRanges:removeCustomRanges,customDecorations:removeCustomDecorations}}__name(updateAttribute,"updateAttribute");function updateTextRuns(body,updateBody,textLength,currentIndex,coverType){const{textRuns}=body,{textRuns:updateTextRuns2}=updateBody;if(textRuns==null||updateTextRuns2==null)return;const removeTextRuns=deleteTextRuns(body,textLength,currentIndex);if(coverType!==UpdateDocsAttributeType.REPLACE){const newUpdateTextRun=coverTextRuns(updateTextRuns2,removeTextRuns,coverType);updateBody.textRuns=newUpdateTextRun}return insertTextRuns(body,updateBody,textLength,currentIndex),removeTextRuns}__name(updateTextRuns,"updateTextRuns");function coverTextRuns(updateDataTextRuns,removeTextRuns,coverType){if(removeTextRuns.length===0)return updateDataTextRuns;updateDataTextRuns=Tools.deepClone(updateDataTextRuns),removeTextRuns=Tools.deepClone(removeTextRuns);const newUpdateTextRuns=[],updateLength=updateDataTextRuns.length,removeLength=removeTextRuns.length;let updateIndex=0,removeIndex=0,pending=null;function pushPendingAndReturnStatus(){return pending?(newUpdateTextRuns.push(pending),pending=null,!0):!1}for(__name(pushPendingAndReturnStatus,"pushPendingAndReturnStatus");updateIndex<updateLength&&removeIndex<removeLength;){const{st:updateSt,ed:updateEd,ts:updateStyle}=updateDataTextRuns[updateIndex],{st:removeSt,ed:removeEd,ts:removeStyle,sId}=removeTextRuns[removeIndex];let newTs;if(coverType===UpdateDocsAttributeType.COVER?newTs={...removeStyle,...updateStyle}:newTs={...updateStyle,...removeStyle},updateEd<removeSt)pushPendingAndReturnStatus()||newUpdateTextRuns.push(updateDataTextRuns[updateIndex]),updateIndex++;else if(removeEd<updateSt)pushPendingAndReturnStatus()||newUpdateTextRuns.push(removeTextRuns[removeIndex]),removeIndex++;else{const newTextRun={st:Math.min(updateSt,removeSt),ed:Math.max(updateSt,removeSt),ts:updateSt<removeSt?{...updateStyle}:{...removeStyle},sId:updateSt<removeSt?void 0:sId};newTextRun.ed>newTextRun.st&&newUpdateTextRuns.push(newTextRun),newUpdateTextRuns.push({st:Math.max(updateSt,removeSt),ed:Math.min(updateEd,removeEd),ts:newTs,sId}),updateEd<removeEd?(updateIndex++,removeTextRuns[removeIndex].st=updateEd,removeTextRuns[removeIndex].st===removeTextRuns[removeIndex].ed&&removeIndex++):(removeIndex++,updateDataTextRuns[updateIndex].st=removeEd,updateDataTextRuns[updateIndex].st===updateDataTextRuns[updateIndex].ed&&updateIndex++);const pendingTextRun={st:Math.min(updateEd,removeEd),ed:Math.max(updateEd,removeEd),ts:updateEd<removeEd?{...removeStyle}:{...updateStyle},sId:updateEd<removeEd?sId:void 0};pending=pendingTextRun.ed>pendingTextRun.st?pendingTextRun:null}}pushPendingAndReturnStatus();const tempTopTextRun=newUpdateTextRuns[newUpdateTextRuns.length-1],updateLastTextRun=updateDataTextRuns[updateLength-1],removeLastTextRun=removeTextRuns[removeLength-1];return tempTopTextRun&&tempTopTextRun.ed!==Math.max(updateLastTextRun.ed,removeLastTextRun.ed)&&(updateLastTextRun.ed>removeLastTextRun.ed?newUpdateTextRuns.push(updateLastTextRun):newUpdateTextRuns.push(removeLastTextRun)),normalizeTextRuns(newUpdateTextRuns)}__name(coverTextRuns,"coverTextRuns");function updateParagraphs(body,updateBody,textLength,currentIndex,coverType){const{paragraphs}=body,{paragraphs:updateDataParagraphs}=updateBody;if(paragraphs==null||updateDataParagraphs==null)return;const removeParagraphs=deleteParagraphs(body,textLength,currentIndex);if(coverType!==UpdateDocsAttributeType.REPLACE){const newUpdateParagraphs=[];for(const updateParagraph of updateDataParagraphs){const{startIndex:updateStartIndex,paragraphStyle:updateParagraphStyle,bullet:updateBullet}=updateParagraph;let splitUpdateParagraphs=[];for(const removeParagraph of removeParagraphs){const{startIndex:removeStartIndex,paragraphStyle:removeParagraphStyle,bullet:removeBullet}=removeParagraph;let newParagraphStyle,newBullet;if(coverType===UpdateDocsAttributeType.COVER?(newParagraphStyle={...removeParagraphStyle,...updateParagraphStyle},newBullet={listId:"",listType:PresetListType.BULLET_LIST,nestingLevel:0,textStyle:{},...removeBullet,...updateBullet}):(newParagraphStyle={...updateParagraphStyle,...removeParagraphStyle},newBullet={listId:"",listType:PresetListType.BULLET_LIST,nestingLevel:0,textStyle:{},...updateBullet,...removeBullet}),updateStartIndex===removeStartIndex){splitUpdateParagraphs.push({startIndex:updateStartIndex,paragraphStyle:newParagraphStyle,bullet:newBullet});break}}newUpdateParagraphs.push(...splitUpdateParagraphs),splitUpdateParagraphs=[]}updateBody.paragraphs=newUpdateParagraphs}return insertParagraphs(body,updateBody,textLength,currentIndex),removeParagraphs}__name(updateParagraphs,"updateParagraphs");function updateSectionBreaks(body,updateBody,textLength,currentIndex,coverType){const{sectionBreaks}=body,{sectionBreaks:updateDataSectionBreaks}=updateBody;if(sectionBreaks==null||updateDataSectionBreaks==null)return;const removeSectionBreaks=deleteSectionBreaks(body,textLength,currentIndex);if(coverType!==UpdateDocsAttributeType.REPLACE){const newUpdateSectionBreaks=[];for(const updateSectionBreak of updateDataSectionBreaks){const{startIndex:updateStartIndex}=updateSectionBreak;let splitUpdateSectionBreaks=[];for(const removeSectionBreak of removeSectionBreaks){const{startIndex:removeStartIndex}=removeSectionBreak;if(updateStartIndex===removeStartIndex){coverType===UpdateDocsAttributeType.COVER?splitUpdateSectionBreaks.push({...removeSectionBreak,...updateSectionBreak}):splitUpdateSectionBreaks.push({...updateSectionBreak,...removeSectionBreak});break}}newUpdateSectionBreaks.push(...splitUpdateSectionBreaks),splitUpdateSectionBreaks=[]}updateBody.sectionBreaks=newUpdateSectionBreaks}return insertParagraphs(body,updateBody,textLength,currentIndex),removeSectionBreaks}__name(updateSectionBreaks,"updateSectionBreaks");function updateCustomBlocks(body,updateBody,textLength,currentIndex,coverType){const{customBlocks}=body,{customBlocks:updateDataCustomBlocks}=updateBody;if(customBlocks==null||updateDataCustomBlocks==null)return;const removeCustomBlocks=deleteCustomBlocks(body,textLength,currentIndex);if(coverType!==UpdateDocsAttributeType.REPLACE){const newUpdateCustomBlocks=[];for(const updateCustomBlock of updateDataCustomBlocks){const{startIndex:updateStartIndex}=updateCustomBlock;let splitUpdateCustomBlocks=[];for(const removeCustomBlock of removeCustomBlocks){const{startIndex:removeStartIndex}=removeCustomBlock;if(updateStartIndex===removeStartIndex){coverType===UpdateDocsAttributeType.COVER?splitUpdateCustomBlocks.push({...removeCustomBlock,...updateCustomBlock}):splitUpdateCustomBlocks.push({...updateCustomBlock,...removeCustomBlock});break}}newUpdateCustomBlocks.push(...splitUpdateCustomBlocks),splitUpdateCustomBlocks=[]}updateBody.customBlocks=newUpdateCustomBlocks}return insertCustomBlocks(body,updateBody,textLength,currentIndex),removeCustomBlocks}__name(updateCustomBlocks,"updateCustomBlocks");function updateTables(body,updateBody,textLength,currentIndex,coverType){const{tables}=body,{tables:updateDataTables}=updateBody;if(tables==null||updateDataTables==null)return;const removeTables=deleteTables(body,textLength,currentIndex);if(coverType!==UpdateDocsAttributeType.REPLACE){const newUpdateTables=[];for(const updateTable of updateDataTables){const{startIndex:updateStartIndex,endIndex:updateEndIndex}=updateTable;let splitUpdateTables=[];for(const removeTable of removeTables){const{startIndex:removeStartIndex,endIndex:removeEndIndex}=removeTable;if(removeStartIndex>=updateStartIndex&&removeEndIndex<=updateEndIndex){coverType===UpdateDocsAttributeType.COVER?splitUpdateTables.push({...removeTable,...updateTable}):splitUpdateTables.push({...updateTable,...removeTable});break}}newUpdateTables.push(...splitUpdateTables),splitUpdateTables=[]}updateBody.tables=newUpdateTables}return insertTables(body,updateBody,textLength,currentIndex),removeTables}__name(updateTables,"updateTables");function updateCustomRanges(body,updateBody,textLength,currentIndex,coverType){body.customRanges||(body.customRanges=[]);const{customRanges}=body,{customRanges:updateDataCustomRanges}=updateBody;if(customRanges==null||updateDataCustomRanges==null)return;let removeCustomRanges=[];return coverType===UpdateDocsAttributeType.REPLACE&&(removeCustomRanges=deleteCustomRanges(body,textLength,currentIndex)),insertCustomRanges(body,updateBody,0,currentIndex),removeCustomRanges}__name(updateCustomRanges,"updateCustomRanges");function updateCustomDecorations(body,updateBody,textLength,currentIndex,coverType){body.customDecorations||(body.customDecorations=[]);let removeCustomDecorations=[];return coverType===UpdateDocsAttributeType.REPLACE&&(removeCustomDecorations=deleteCustomDecorations(body,textLength,currentIndex,!1)),insertCustomDecorations(body,updateBody,0,currentIndex),removeCustomDecorations}__name(updateCustomDecorations,"updateCustomDecorations");var SliceBodyType=(SliceBodyType2=>(SliceBodyType2[SliceBodyType2.copy=0]="copy",SliceBodyType2[SliceBodyType2.cut=1]="cut",SliceBodyType2))(SliceBodyType||{});function getBodySlice(body,startOffset,endOffset,returnEmptyTextRun=!1,type2=1){const{dataStream,textRuns=[],paragraphs=[],customBlocks=[],tables=[]}=body,docBody={dataStream:dataStream.slice(startOffset,endOffset)},newTextRuns=[];for(const textRun of textRuns){const clonedTextRun=Tools.deepClone(textRun),{st,ed}=clonedTextRun;Tools.hasIntersectionBetweenTwoRanges(st,ed,startOffset,endOffset)&&(startOffset>=st&&startOffset<=ed?newTextRuns.push({...clonedTextRun,st:startOffset,ed:Math.min(endOffset,ed)}):endOffset>=st&&endOffset<=ed?newTextRuns.push({...clonedTextRun,st:Math.max(startOffset,st),ed:endOffset}):newTextRuns.push(clonedTextRun))}newTextRuns.length?docBody.textRuns=newTextRuns.map(tr=>{const{st,ed}=tr;return{...tr,st:st-startOffset,ed:ed-startOffset}}):returnEmptyTextRun&&(docBody.textRuns=[{st:0,ed:endOffset-startOffset,ts:{}}]);const newTables=[];for(const table of tables){const clonedTable=Tools.deepClone(table),{startIndex,endIndex}=clonedTable;startIndex>=startOffset&&endIndex<=endOffset&&newTables.push({...clonedTable,startIndex:startIndex-startOffset,endIndex:endIndex-startOffset})}newTables.length&&(docBody.tables=newTables);const newParagraphs=[];for(const paragraph of paragraphs){const{startIndex}=paragraph;startIndex>=startOffset&&startIndex<=endOffset&&newParagraphs.push(Tools.deepClone(paragraph))}newParagraphs.length&&(docBody.paragraphs=newParagraphs.map(p=>({...p,startIndex:p.startIndex-startOffset}))),type2===1&&(docBody.customDecorations=getCustomDecorationSlice(body,startOffset,endOffset));const{customRanges}=getCustomRangeSlice(body,startOffset,endOffset);docBody.customRanges=customRanges;const newCustomBlocks=[];for(const block of customBlocks){const{startIndex}=block;startIndex>=startOffset&&startIndex<=endOffset&&newCustomBlocks.push(Tools.deepClone(block))}return newCustomBlocks.length&&(docBody.customBlocks=newCustomBlocks.map(b=>({...b,startIndex:b.startIndex-startOffset}))),docBody}__name(getBodySlice,"getBodySlice");function normalizeBody(body){const{dataStream,textRuns,paragraphs,customRanges,customDecorations,tables}=body;let leftOffset=0,rightOffset=0;customRanges==null||customRanges.forEach(range=>{range.startIndex<0&&(leftOffset=Math.max(leftOffset,-range.startIndex)),range.endIndex>dataStream.length-1&&(rightOffset=Math.max(rightOffset,range.endIndex-dataStream.length+1))});const newData=`${DataStreamTreeTokenType.CUSTOM_RANGE_START.repeat(leftOffset)}${dataStream}${DataStreamTreeTokenType.CUSTOM_RANGE_END.repeat(rightOffset)}`;return textRuns&&(textRuns[0]&&(textRuns[0].st=textRuns[0].st-leftOffset),textRuns[textRuns.length-1]&&(textRuns[textRuns.length-1].ed=textRuns[textRuns.length-1].ed+rightOffset)),textRuns==null||textRuns.forEach(textRun=>{textRun.st+=leftOffset,textRun.ed+=leftOffset}),paragraphs==null||paragraphs.forEach(p=>{p.startIndex+=leftOffset}),customRanges==null||customRanges.forEach(range=>{range.startIndex+=leftOffset,range.endIndex+=leftOffset}),customDecorations==null||customDecorations.forEach(d=>{d.startIndex+=leftOffset,d.endIndex+=rightOffset}),tables==null||tables.forEach(table=>{table.startIndex+=leftOffset,table.endIndex+=rightOffset}),{...body,dataStream:newData,textRuns,paragraphs,customRanges,customDecorations,tables}}__name(normalizeBody,"normalizeBody");function getCustomRangeSlice(body,startOffset,endOffset){const{customRanges=[]}=body;let leftOffset=0,rightOffset=0;const relativeCustomRanges=customRanges.filter(customRange=>Math.max(customRange.startIndex,startOffset)<=Math.min(customRange.endIndex,endOffset-1)).map(range=>({...range,startIndex:range.startIndex,endIndex:range.endIndex}));if(relativeCustomRanges.length){relativeCustomRanges.forEach(customRange=>{customRange.startIndex<startOffset&&(leftOffset+=1),customRange.endIndex>endOffset-1&&(rightOffset+=1)});for(let i=0;i<leftOffset;i++){const range=relativeCustomRanges[i];range.startIndex=startOffset-leftOffset+i}if(rightOffset){const sorted=[...relativeCustomRanges].sort((pre,aft)=>aft.endIndex-pre.endIndex);for(let i=0;i<rightOffset;i++){const range=sorted[i];range.endIndex=endOffset+rightOffset-i-1}}}return{customRanges:relativeCustomRanges.map(range=>({...range,startIndex:range.startIndex-startOffset,endIndex:range.endIndex-startOffset})),leftOffset,rightOffset}}__name(getCustomRangeSlice,"getCustomRangeSlice");function getCustomDecorationSlice(body,startOffset,endOffset){const{customDecorations=[]}=body,customDecorationSlice=[];return customDecorations.forEach(range=>{if(Math.max(range.startIndex,startOffset)<=Math.min(range.endIndex,endOffset-1)){const copy=Tools.deepClone(range);customDecorationSlice.push({...copy,startIndex:Math.max(copy.startIndex-startOffset,0),endIndex:Math.min(copy.endIndex,endOffset)-startOffset})}}),customDecorationSlice}__name(getCustomDecorationSlice,"getCustomDecorationSlice");function composeBody(thisBody,otherBody,coverType=UpdateDocsAttributeType.COVER){if(otherBody.dataStream!=="")throw new Error("Cannot compose other body with non-empty dataStream");const retBody={dataStream:thisBody.dataStream},{textRuns:thisTextRuns=[],paragraphs:thisParagraphs=[]}=thisBody,{textRuns:otherTextRuns=[],paragraphs:otherParagraphs=[]}=otherBody,textRuns=coverTextRuns(otherTextRuns,thisTextRuns,coverType);textRuns.length&&(retBody.textRuns=textRuns);const paragraphs=[];let thisIndex=0,otherIndex=0;for(;thisIndex<thisParagraphs.length&&otherIndex<otherParagraphs.length;){const thisParagraph=thisParagraphs[thisIndex],otherParagraph=otherParagraphs[otherIndex],{startIndex:thisStart}=thisParagraph,{startIndex:otherStart}=otherParagraph;thisStart===otherStart?(paragraphs.push(Tools.deepMerge(thisParagraph,otherParagraph)),thisIndex++,otherIndex++):thisStart<otherStart?(paragraphs.push(Tools.deepClone(thisParagraph)),thisIndex++):(paragraphs.push(Tools.deepClone(otherParagraph)),otherIndex++)}return thisIndex<thisParagraphs.length&&paragraphs.push(...thisParagraphs.slice(thisIndex)),otherIndex<otherParagraphs.length&&paragraphs.push(...otherParagraphs.slice(otherIndex)),paragraphs.length&&(retBody.paragraphs=paragraphs),retBody}__name(composeBody,"composeBody");function isUselessRetainAction(action){const{body}=action;if(body==null)return!0;const{textRuns=[],paragraphs=[]}=body;return textRuns.length===0&&paragraphs.length===0}__name(isUselessRetainAction,"isUselessRetainAction");function getEmptySnapshot$1(unitID=Tools.generateRandomId(6),locale=LocaleType.EN_US,title=""){return{id:unitID,locale,title,body:{dataStream:`\r
8
- `,textRuns:[],paragraphs:[{startIndex:0,paragraphStyle:{spaceAbove:{v:5},lineSpacing:1,spaceBelow:{v:0}}}],sectionBreaks:[{startIndex:1}]},documentStyle:{pageSize:{width:793.3333333333334,height:1122.6666666666667},marginTop:50,marginBottom:50,marginRight:40,marginLeft:40,renderConfig:{vertexAngle:0,centerAngle:0}},settings:{}}}__name(getEmptySnapshot$1,"getEmptySnapshot$1");var dist$1={},json1_release={},deepEqual$1={};Object.defineProperty(deepEqual$1,"__esModule",{value:!0});function eqObj(a,b){if(Array.isArray(b))return!1;for(let k in a)if(!deepEqual(a[k],b[k]))return!1;for(let k in b)if(a[k]===void 0)return!1;return!0}__name(eqObj,"eqObj");function eqArr(a,b){if(!Array.isArray(b)||a.length!==b.length)return!1;for(let i=0;i<a.length;i++)if(!deepEqual(a[i],b[i]))return!1;return!0}__name(eqArr,"eqArr");function deepEqual(a,b){return a===b?!0:a===null||b===null||typeof a!="object"||typeof b!="object"?!1:Array.isArray(a)?eqArr(a,b):eqObj(a,b)}__name(deepEqual,"deepEqual");deepEqual$1.default=deepEqual;var deepClone$1={};Object.defineProperty(deepClone$1,"__esModule",{value:!0});function deepClone(old){if(old===null)return null;if(Array.isArray(old))return old.map(deepClone);if(typeof old=="object"){const o={};for(let k in old)o[k]=deepClone(old[k]);return o}else return old}__name(deepClone,"deepClone");deepClone$1.default=deepClone;var cursor={};(function(exports2){Object.defineProperty(exports2,"__esModule",{value:!0}),exports2.eachChildOf=exports2.advancer=exports2.readCursor=exports2.writeCursor=exports2.WriteCursor=exports2.ReadCursor=exports2.isValidPathItem=void 0;function assert(pred,msg){if(!pred)throw new Error(msg)}__name(assert,"assert");const isObject2=__name(o=>o!=null&&typeof o=="object"&&!Array.isArray(o),"isObject"),isGreaterKey=__name((a,b)=>typeof a==typeof b?a>b:typeof a=="string"&&typeof b=="number","isGreaterKey");function copyAll(c,w){for(let _k in c){const k=_k;w.write(k,c[k])}}__name(copyAll,"copyAll"),exports2.isValidPathItem=k=>typeof k=="number"||typeof k=="string"&&k!=="__proto__";const _Cursor=class _Cursor{constructor(op=null){this.parents=[],this.indexes=[],this.lcIdx=-1,this.idx=-1,this.container=op}ascend(){assert(this.parents.length===this.indexes.length/2),this.idx===0?this.parents.length?(this.lcIdx=this.indexes.pop(),this.container=this.parents.pop(),this.idx=this.indexes.pop()):(this.lcIdx=0,this.idx=-1):(assert(this.idx>0),this.idx--,isObject2(this.container[this.idx])&&this.idx--)}getPath(){const path=[];let c=this.container,p=this.parents.length-1,i=this.idx;for(;i>=0;)path.unshift(c[i]),i===0?(i=this.indexes[p*2],c=this.parents[p--]):i-=isObject2(c[i-1])?2:1;return path}};__name(_Cursor,"Cursor");let Cursor=_Cursor;const _ReadCursor=class _ReadCursor extends Cursor{get(){return this.container?this.container.slice(this.idx+1):null}getKey(){return assert(this.container!=null,"Invalid call to getKey before cursor descended"),this.container[this.idx]}getComponent(){let c;return this.container&&this.container.length>this.idx+1&&isObject2(c=this.container[this.idx+1])?c:null}descendFirst(){let i=this.idx+1;if(!this.container||i>=this.container.length||isObject2(this.container[i])&&i+1>=this.container.length)return!1;isObject2(this.container[i])&&i++;const firstChild=this.container[i];return Array.isArray(firstChild)?(this.indexes.push(this.idx),this.parents.push(this.container),this.indexes.push(i),this.idx=0,this.container=firstChild):this.idx=i,!0}nextSibling(){if(assert(this.parents.length===this.indexes.length/2),this.idx>0||this.parents.length===0)return!1;const i=this.indexes[this.indexes.length-1]+1,c=this.parents[this.parents.length-1];return i>=c.length?!1:(assert(!isNaN(i)),this.indexes[this.indexes.length-1]=i,this.container=c[i],!0)}_init(_container,_idx,_parents,_indexes){this.container=_container,this.idx=_idx,this.parents=_parents.slice(),this.indexes=_indexes.slice()}clone(){const c=new _ReadCursor;return c._init(this.container,this.idx,this.parents,this.indexes),c}*[Symbol.iterator](){if(this.descendFirst()){do yield this.getKey();while(this.nextSibling());this.ascend()}}traverse(w,fn){const c=this.getComponent();c&&fn(c,w);for(const key of this)w&&w.descend(key),this.traverse(w,fn),w&&w.ascend()}eachPick(w,fn){this.traverse(w,(c,w2)=>{c.p!=null&&fn(c.p,w2)})}eachDrop(w,fn){this.traverse(w,(c,w2)=>{c.d!=null&&fn(c.d,w2)})}};__name(_ReadCursor,"ReadCursor");let ReadCursor=_ReadCursor;exports2.ReadCursor=ReadCursor;const _WriteCursor=class _WriteCursor extends Cursor{constructor(op=null){super(op),this.pendingDescent=[],this._op=op}flushDescent(){assert(this.parents.length===this.indexes.length/2),this.container===null&&(this._op=this.container=[]);for(let j=0;j<this.pendingDescent.length;j++){const k=this.pendingDescent[j];let i=this.idx+1;if(i<this.container.length&&isObject2(this.container[i])&&i++,assert(i===this.container.length||!isObject2(this.container[i])),i===this.container.length)this.container.push(k),this.idx=i;else if(this.container[i]===k)this.idx=i;else{if(!Array.isArray(this.container[i])){const oldChild=this.container.splice(i,this.container.length-i);this.container.push(oldChild),this.lcIdx>-1&&(this.lcIdx=i)}for(this.indexes.push(this.idx),this.parents.push(this.container),this.lcIdx!==-1&&(assert(isGreaterKey(k,this.container[this.lcIdx][0])),i=this.lcIdx+1,this.lcIdx=-1);i<this.container.length&&isGreaterKey(k,this.container[i][0]);)i++;if(this.indexes.push(i),this.idx=0,i<this.container.length&&this.container[i][0]===k)this.container=this.container[i];else{const child=[k];this.container.splice(i,0,child),this.container=child}}}this.pendingDescent.length=0}reset(){this.lcIdx=-1}getComponent(){this.flushDescent();const i=this.idx+1;if(i<this.container.length&&isObject2(this.container[i]))return this.container[i];{const component={};return this.container.splice(i,0,component),component}}write(key,value){const component=this.getComponent();assert(component[key]==null||component[key]===value,"Internal consistency error: Overwritten component. File a bug"),component[key]=value}get(){return this._op}descend(key){if(!exports2.isValidPathItem(key))throw Error("Invalid JSON key");this.pendingDescent.push(key)}descendPath(path){return this.pendingDescent.push(...path),this}ascend(){this.pendingDescent.length?this.pendingDescent.pop():super.ascend()}mergeTree(data,mergeFn=copyAll){if(data===null)return;if(assert(Array.isArray(data)),data===this._op)throw Error("Cannot merge into my own tree");const _lcIdx=this.lcIdx,oldDepth=this.parents.length;let depth=0;for(let i=0;i<data.length;i++){const c=data[i];typeof c=="string"||typeof c=="number"?(depth++,this.descend(c)):Array.isArray(c)?this.mergeTree(c,mergeFn):typeof c=="object"&&mergeFn(c,this)}for(;depth--;)this.ascend();this.lcIdx=this.parents.length===oldDepth?_lcIdx:-1}at(path,fn){this.descendPath(path),fn(this);for(let i=0;i<path.length;i++)this.ascend();return this}writeAtPath(path,key,value){return this.at(path,()=>this.write(key,value)),this.reset(),this}writeMove(path1,path2,slot=0){return this.writeAtPath(path1,"p",slot).writeAtPath(path2,"d",slot)}getPath(){const path=super.getPath();return path.push(...this.pendingDescent),path}};__name(_WriteCursor,"WriteCursor");let WriteCursor=_WriteCursor;exports2.WriteCursor=WriteCursor,exports2.writeCursor=()=>new WriteCursor,exports2.readCursor=op=>new ReadCursor(op);function advancer(r,listMap,listAdv){let didDescend,valid;valid=didDescend=r?r.descendFirst():!1;function adv(ktarget){let k2_;for(;valid;){const k2=k2_=r.getKey();if(ktarget!=null){let skip=!1;if(listMap&&typeof k2=="number"&&(k2_=listMap(k2,r.getComponent()),k2_<0&&(k2_=~k2_,skip=!0)),isGreaterKey(k2_,ktarget))return null;if(k2_===ktarget&&!skip)return r}listAdv&&typeof k2_=="number"&&listAdv(k2_,r.getComponent()),valid=r.nextSibling()}return null}return __name(adv,"adv"),adv.end=()=>{didDescend&&r.ascend()},adv}__name(advancer,"advancer"),exports2.advancer=advancer;function eachChildOf(r1,r2,fn){let hasChild1,descended1,hasChild2,descended2;for(hasChild1=descended1=r1&&r1.descendFirst(),hasChild2=descended2=r2&&r2.descendFirst();hasChild1||hasChild2;){let k1=hasChild1?r1.getKey():null,k2=hasChild2?r2.getKey():null;k1!==null&&k2!==null&&(isGreaterKey(k2,k1)?k2=null:k1!==k2&&(k1=null)),fn(k1==null?k2:k1,k1!=null?r1:null,k2!=null?r2:null),k1!=null&&hasChild1&&(hasChild1=r1.nextSibling()),k2!=null&&hasChild2&&(hasChild2=r2.nextSibling())}descended1&&r1.ascend(),descended2&&r2.ascend()}__name(eachChildOf,"eachChildOf"),exports2.eachChildOf=eachChildOf})(cursor);var types={};(function(exports2){Object.defineProperty(exports2,"__esModule",{value:!0}),exports2.ConflictType=void 0,function(ConflictType){ConflictType[ConflictType.RM_UNEXPECTED_CONTENT=1]="RM_UNEXPECTED_CONTENT",ConflictType[ConflictType.DROP_COLLISION=2]="DROP_COLLISION",ConflictType[ConflictType.BLACKHOLE=3]="BLACKHOLE"}(exports2.ConflictType||(exports2.ConflictType={}))})(types);var dist={},unicount={},hasRequiredUnicount;function requireUnicount(){return hasRequiredUnicount||(hasRequiredUnicount=1,Object.defineProperty(unicount,"__esModule",{value:!0}),unicount.uniToStrPos=unicount.strPosToUni=void 0,unicount.strPosToUni=(s,strOffset=s.length)=>{let pairs=0,i=0;for(;i<strOffset;i++){const code=s.charCodeAt(i);code>=55296&&code<=57343&&(pairs++,i++)}if(i!==strOffset)throw Error("Invalid offset - splits unicode bytes");return i-pairs},unicount.uniToStrPos=(s,uniOffset)=>{let pos=0;for(;uniOffset>0;uniOffset--){const code=s.charCodeAt(pos);pos+=code>=55296&&code<=57343?2:1}return pos}),unicount}__name(requireUnicount,"requireUnicount");var type={},hasRequiredType;function requireType(){return hasRequiredType||(hasRequiredType=1,function(exports2){Object.defineProperty(exports2,"__esModule",{value:!0}),exports2.uniSlice=exports2.dlen=exports2.eachOp=void 0;const unicount_1=requireUnicount(),checkOp=__name(op=>{if(!Array.isArray(op))throw Error("Op must be an array of components");let last=null;for(let i=0;i<op.length;i++){const c=op[i];switch(typeof c){case"object":if(typeof c.d!="number"&&typeof c.d!="string")throw Error("Delete must be number or string");if(exports2.dlen(c.d)<=0)throw Error("Deletes must not be empty");break;case"string":if(!(c.length>0))throw Error("Inserts cannot be empty");break;case"number":if(!(c>0))throw Error("Skip components must be >0");if(typeof last=="number")throw Error("Adjacent skip components should be combined");break}last=c}if(typeof last=="number")throw Error("Op has a trailing skip")},"checkOp");function eachOp(op,fn){let prePos=0,postPos=0;for(let i=0;i<op.length;i++){const c=op[i];switch(fn(c,prePos,postPos),typeof c){case"object":prePos+=exports2.dlen(c.d);break;case"string":postPos+=unicount_1.strPosToUni(c);break;case"number":prePos+=c,postPos+=c;break}}}__name(eachOp,"eachOp"),exports2.eachOp=eachOp;function mapOp(op,fn){const newOp=[],append=makeAppend(newOp);return eachOp(op,(c,prePos,postPos)=>{append(fn(c,prePos,postPos))}),trim(newOp)}__name(mapOp,"mapOp");const id=__name(x=>x,"id"),normalize=__name(op=>mapOp(op,id),"normalize");exports2.dlen=d=>typeof d=="number"?d:unicount_1.strPosToUni(d);const makeAppend=__name(op=>component=>{if(!(!component||component.d===0||component.d===""))if(op.length===0)op.push(component);else if(typeof component==typeof op[op.length-1])if(typeof component=="object"){const last=op[op.length-1];last.d=typeof last.d=="string"&&typeof component.d=="string"?last.d+component.d:exports2.dlen(last.d)+exports2.dlen(component.d)}else op[op.length-1]+=component;else op.push(component)},"makeAppend"),componentLength=__name(c=>typeof c=="number"?c:typeof c=="string"?unicount_1.strPosToUni(c):typeof c.d=="number"?c.d:unicount_1.strPosToUni(c.d),"componentLength");exports2.uniSlice=(s,startUni,endUni)=>{const start=unicount_1.uniToStrPos(s,startUni),end=endUni==null?1/0:unicount_1.uniToStrPos(s,endUni);return s.slice(start,end)};const dslice=__name((d,start,end)=>typeof d=="number"?end==null?d-start:Math.min(d,end)-start:exports2.uniSlice(d,start,end),"dslice"),makeTake=__name(op=>{let idx=0,offset=0;return{take:__name((n,indivisableField)=>{if(idx===op.length)return n===-1?null:n;const c=op[idx];let part;if(typeof c=="number")return n===-1||c-offset<=n?(part=c-offset,++idx,offset=0,part):(offset+=n,n);if(typeof c=="string"){if(n===-1||indivisableField==="i"||unicount_1.strPosToUni(c.slice(offset))<=n)return part=c.slice(offset),++idx,offset=0,part;{const offset2=offset+unicount_1.uniToStrPos(c.slice(offset),n);return part=c.slice(offset,offset2),offset=offset2,part}}else{if(n===-1||indivisableField==="d"||exports2.dlen(c.d)-offset<=n)return part={d:dslice(c.d,offset)},++idx,offset=0,part;{let result=dslice(c.d,offset,offset+n);return offset+=n,{d:result}}}},"take"),peek:__name(()=>op[idx],"peek")}},"makeTake"),trim=__name(op=>(op.length>0&&typeof op[op.length-1]=="number"&&op.pop(),op),"trim");function transform(op1,op2,side){if(side!=="left"&&side!=="right")throw Error("side ("+side+") must be 'left' or 'right'");checkOp(op1),checkOp(op2);const newOp=[],append=makeAppend(newOp),{take,peek}=makeTake(op1);for(let i=0;i<op2.length;i++){const c2=op2[i];let length,c1;switch(typeof c2){case"number":for(length=c2;length>0;)c1=take(length,"i"),append(c1),typeof c1!="string"&&(length-=componentLength(c1));break;case"string":side==="left"&&typeof peek()=="string"&&append(take(-1)),append(unicount_1.strPosToUni(c2));break;case"object":for(length=exports2.dlen(c2.d);length>0;)switch(c1=take(length,"i"),typeof c1){case"number":length-=c1;break;case"string":append(c1);break;case"object":length-=exports2.dlen(c1.d)}break}}let c;for(;c=take(-1);)append(c);return trim(newOp)}__name(transform,"transform");function compose(op1,op2){checkOp(op1),checkOp(op2);const result=[],append=makeAppend(result),{take}=makeTake(op1);for(let i=0;i<op2.length;i++){const component=op2[i];let length,chunk;switch(typeof component){case"number":for(length=component;length>0;)chunk=take(length,"d"),append(chunk),typeof chunk!="object"&&(length-=componentLength(chunk));break;case"string":append(component);break;case"object":length=exports2.dlen(component.d);let offset=0;for(;offset<length;)switch(chunk=take(length-offset,"d"),typeof chunk){case"number":append({d:dslice(component.d,offset,offset+chunk)}),offset+=chunk;break;case"string":offset+=unicount_1.strPosToUni(chunk);break;case"object":append(chunk)}break}}let c;for(;c=take(-1);)append(c);return trim(result)}__name(compose,"compose");const transformPosition=__name((cursor2,op)=>{let pos=0;for(let i=0;i<op.length&&cursor2>pos;i++){const c=op[i];switch(typeof c){case"number":{pos+=c;break}case"string":const offset=unicount_1.strPosToUni(c);pos+=offset,cursor2+=offset;break;case"object":cursor2-=Math.min(exports2.dlen(c.d),cursor2-pos);break}}return cursor2},"transformPosition"),transformSelection=__name((selection,op)=>typeof selection=="number"?transformPosition(selection,op):selection.map(s=>transformPosition(s,op)),"transformSelection");function makeInvertible(op,doc,ropeImpl){return mapOp(op,(c,prePos)=>typeof c=="object"&&typeof c.d=="number"?{d:ropeImpl.slice(doc,prePos,prePos+c.d)}:c)}__name(makeInvertible,"makeInvertible");function invert(op){return mapOp(op,c=>{switch(typeof c){case"object":if(typeof c.d=="number")throw Error("Cannot invert text op: Deleted characters missing from operation. makeInvertible must be called first.");return c.d;case"string":return{d:c};case"number":return c}})}__name(invert,"invert");function stripInvertible(op){return mapOp(op,c=>typeof c=="object"&&typeof c.d=="string"?{d:unicount_1.strPosToUni(c.d)}:c)}__name(stripInvertible,"stripInvertible");function isInvertible(op){let invertible=!0;return eachOp(op,c=>{typeof c=="object"&&typeof c.d=="number"&&(invertible=!1)}),invertible}__name(isInvertible,"isInvertible");function makeType(ropeImpl){return{name:"text-unicode",uri:"http://sharejs.org/types/text-unicode",trim,normalize,checkOp,create(initial=""){if(typeof initial!="string")throw Error("Initial data must be a string");return ropeImpl.create(initial)},apply(str,op){checkOp(op);const builder=ropeImpl.builder(str);for(let i=0;i<op.length;i++){const component=op[i];switch(typeof component){case"number":builder.skip(component);break;case"string":builder.append(component);break;case"object":builder.del(exports2.dlen(component.d));break}}return builder.build()},transform,compose,transformPosition,transformSelection,isInvertible,makeInvertible(op,doc){return makeInvertible(op,doc,ropeImpl)},stripInvertible,invert,invertWithDoc(op,doc){return invert(makeInvertible(op,doc,ropeImpl))},isNoop:__name(op=>op.length===0,"isNoop")}}__name(makeType,"makeType"),exports2.default=makeType}(type)),type}__name(requireType,"requireType");var api={},hasRequiredApi;function requireApi(){if(hasRequiredApi)return api;hasRequiredApi=1,Object.defineProperty(api,"__esModule",{value:!0});const type_1=requireType(),unicount_1=requireUnicount();function api$1(getSnapshot,submitOp){return{get:getSnapshot,getLength(){return getSnapshot().length},insert(pos,text,callback){const uniPos=unicount_1.strPosToUni(getSnapshot(),pos);return submitOp([uniPos,text],callback)},remove(pos,lengthOrContent,callback){const uniPos=unicount_1.strPosToUni(getSnapshot(),pos);return submitOp([uniPos,{d:lengthOrContent}],callback)},_onOp(op){type_1.eachOp(op,(component,prePos,postPos)=>{switch(typeof component){case"string":this.onInsert&&this.onInsert(postPos,component);break;case"object":const dl=type_1.dlen(component.d);this.onRemove&&this.onRemove(postPos,dl)}})},onInsert:null,onRemove:null}}return __name(api$1,"api$1"),api.default=api$1,api$1.provides={text:!0},api}__name(requireApi,"requireApi");var hasRequiredDist;function requireDist(){return hasRequiredDist||(hasRequiredDist=1,function(exports2){var __createBinding=commonjsGlobal&&commonjsGlobal.__createBinding||(Object.create?function(o,m,k,k2){k2===void 0&&(k2=k),Object.defineProperty(o,k2,{enumerable:!0,get:__name(function(){return m[k]},"get")})}:function(o,m,k,k2){k2===void 0&&(k2=k),o[k2]=m[k]}),__setModuleDefault=commonjsGlobal&&commonjsGlobal.__setModuleDefault||(Object.create?function(o,v){Object.defineProperty(o,"default",{enumerable:!0,value:v})}:function(o,v){o.default=v}),__importStar=commonjsGlobal&&commonjsGlobal.__importStar||function(mod){if(mod&&mod.__esModule)return mod;var result={};if(mod!=null)for(var k in mod)Object.hasOwnProperty.call(mod,k)&&__createBinding(result,mod,k);return __setModuleDefault(result,mod),result},__importDefault=commonjsGlobal&&commonjsGlobal.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports2,"__esModule",{value:!0}),exports2.type=exports2.remove=exports2.insert=void 0;const unicount_1=requireUnicount(),type_1=__importStar(requireType()),api_1=__importDefault(requireApi()),ropeImplUnicodeString={create(s){return s},toString(s){return s},builder(oldDoc){if(typeof oldDoc!="string")throw Error("Invalid document snapshot: "+oldDoc);const newDoc=[];return{skip(n){let offset=unicount_1.uniToStrPos(oldDoc,n);if(offset>oldDoc.length)throw Error("The op is too long for this document");newDoc.push(oldDoc.slice(0,offset)),oldDoc=oldDoc.slice(offset)},append(s){newDoc.push(s)},del(n){oldDoc=oldDoc.slice(unicount_1.uniToStrPos(oldDoc,n))},build(){return newDoc.join("")+oldDoc}}},slice:type_1.uniSlice},textString=type_1.default(ropeImplUnicodeString),type2=Object.assign(Object.assign({},textString),{api:api_1.default});exports2.type=type2,exports2.insert=(pos,text)=>text.length===0?[]:pos===0?[text]:[pos,text],exports2.remove=(pos,textOrLen)=>type_1.dlen(textOrLen)===0?[]:pos===0?[{d:textOrLen}]:[pos,{d:textOrLen}];var type_2=requireType();Object.defineProperty(exports2,"makeType",{enumerable:!0,get:__name(function(){return type_2.default},"get")})}(dist)),dist}__name(requireDist,"requireDist");(function(exports2){var __importDefault=commonjsGlobal&&commonjsGlobal.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports2,"__esModule",{value:!0}),exports2.editOp=exports2.replaceOp=exports2.insertOp=exports2.moveOp=exports2.removeOp=exports2.type=void 0;const deepEqual_js_1=__importDefault(deepEqual$1),deepClone_js_1=__importDefault(deepClone$1),cursor_js_1=cursor,types_js_1=types;function assert(pred,msg){if(!pred)throw new Error(msg)}__name(assert,"assert"),exports2.type={name:"json1",uri:"http://sharejs.org/types/JSONv1",readCursor:cursor_js_1.readCursor,writeCursor:cursor_js_1.writeCursor,create:__name(data=>data,"create"),isNoop:__name(op=>op==null,"isNoop"),setDebug(val){},registerSubtype,checkValidOp,normalize,apply,transformPosition,compose,tryTransform,transform,makeInvertible,invert,invertWithDoc,RM_UNEXPECTED_CONTENT:types_js_1.ConflictType.RM_UNEXPECTED_CONTENT,DROP_COLLISION:types_js_1.ConflictType.DROP_COLLISION,BLACKHOLE:types_js_1.ConflictType.BLACKHOLE,transformNoConflict:__name((op1,op2,side)=>transformWithConflictsPred(()=>!0,op1,op2,side),"transformNoConflict"),typeAllowingConflictsPred:__name(allowConflict=>Object.assign(Object.assign({},exports2.type),{transform:__name((op1,op2,side)=>transformWithConflictsPred(allowConflict,op1,op2,side),"transform")}),"typeAllowingConflictsPred")};const getComponent=__name(r=>r?r.getComponent():null,"getComponent");function isObject2(o){return o&&typeof o=="object"&&!Array.isArray(o)}__name(isObject2,"isObject");const shallowClone=__name(obj=>Array.isArray(obj)?obj.slice():obj!==null&&typeof obj=="object"?Object.assign({},obj):obj,"shallowClone"),hasPick=__name(c=>c&&(c.p!=null||c.r!==void 0),"hasPick"),hasDrop=__name(c=>c&&(c.d!=null||c.i!==void 0),"hasDrop");function removeChild(container,key){return assert(container!=null),typeof key=="number"?(assert(Array.isArray(container),"Invalid key - child is not an array"),(container=container.slice()).splice(key,1)):(assert(isObject2(container),"Invalid key - child is not an object"),delete(container=Object.assign({},container))[key]),container}__name(removeChild,"removeChild");function insertChildMut(container,key,value){return typeof key=="number"?(assert(container!=null,"Container is missing for key"),assert(Array.isArray(container),"Cannot use numerical key for object container"),assert(container.length>=key,"Cannot insert into out of bounds index"),container.splice(key,0,value)):(assert(isObject2(container),"Cannot insert into missing item"),assert(container[key]===void 0,"Trying to overwrite value at key. Your op needs to remove it first"),container[key]=value),value}__name(insertChildMut,"insertChildMut"),exports2.removeOp=(path,value=!0)=>cursor_js_1.writeCursor().writeAtPath(path,"r",value).get(),exports2.moveOp=(from,to)=>cursor_js_1.writeCursor().writeMove(from,to).get(),exports2.insertOp=(path,value)=>cursor_js_1.writeCursor().writeAtPath(path,"i",value).get(),exports2.replaceOp=(path,oldVal,newVal)=>cursor_js_1.writeCursor().at(path,w=>{w.write("r",oldVal),w.write("i",newVal)}).get(),exports2.editOp=(path,type2,subOp,preserveNoop=!1)=>cursor_js_1.writeCursor().at(path,w=>writeEdit(w,type2,subOp,preserveNoop)).get();const isValidKey=__name((container,key)=>container!=null&&(typeof key=="number"?Array.isArray(container):typeof container=="object"),"isValidKey"),maybeGetChild=__name((container,key)=>isValidKey(container,key)?container[key]:void 0,"maybeGetChild"),subtypes={};function registerSubtype(subtype){let _subtype=subtype.type?subtype.type:subtype;_subtype.name&&(subtypes[_subtype.name]=_subtype),_subtype.uri&&(subtypes[_subtype.uri]=_subtype)}__name(registerSubtype,"registerSubtype");const typeOrThrow=__name(name=>{const type2=subtypes[name];if(type2)return type2;throw Error("Missing type: "+name)},"typeOrThrow");registerSubtype(requireDist());const add=__name((a,b)=>a+b,"add");registerSubtype({name:"number",apply:add,compose:add,invert:__name(n=>-n,"invert"),transform:__name(a=>a,"transform")});const getEditType=__name(c=>c==null?null:c.et?typeOrThrow(c.et):c.es?subtypes["text-unicode"]:c.ena!=null?subtypes.number:null,"getEditType"),getEdit=__name(c=>c.es?c.es:c.ena!=null?c.ena:c.e,"getEdit"),writeEdit=__name((w,typeOrName,edit,preserveNoop=!1)=>{const[type2,name]=typeof typeOrName=="string"?[typeOrThrow(typeOrName),typeOrName]:[typeOrName,typeOrName.name];!preserveNoop&&type2.isNoop&&type2.isNoop(edit)||(name==="number"?w.write("ena",edit):name==="text-unicode"?w.write("es",edit):(w.write("et",name),w.write("e",edit)))},"writeEdit");function checkNonNegInteger(n){assert(typeof n=="number"),assert(n>=0),assert(n===(0|n))}__name(checkNonNegInteger,"checkNonNegInteger");function checkScalar(s){typeof s=="number"?checkNonNegInteger(s):assert(typeof s=="string")}__name(checkScalar,"checkScalar");function checkValidOp(op){if(op===null)return;const pickedSlots=new Set,droppedSlots=new Set,checkComponent=__name(e=>{let empty=!0,hasEdit=!1;for(let k in e){const v=e[k];if(empty=!1,assert(k==="p"||k==="r"||k==="d"||k==="i"||k==="e"||k==="es"||k==="ena"||k==="et","Invalid component item '"+k+"'"),k==="p")checkNonNegInteger(v),assert(!pickedSlots.has(v)),pickedSlots.add(v),assert(e.r===void 0);else if(k==="d")checkNonNegInteger(v),assert(!droppedSlots.has(v)),droppedSlots.add(v),assert(e.i===void 0);else if(k==="e"||k==="es"||k==="ena"){assert(!hasEdit),hasEdit=!0;const t=getEditType(e);assert(t,"Missing type in edit"),t.checkValidOp&&t.checkValidOp(getEdit(e))}}assert(!empty)},"checkComponent"),checkDescent=__name((descent,isRoot,removed)=>{if(!Array.isArray(descent))throw Error("Op must be null or a list");if(descent.length===0)throw Error("Empty descent");isRoot||checkScalar(descent[0]);let last=1,numDescents=0,lastKey=0;for(let i=0;i<descent.length;i++){const d=descent[i];if(assert(d!=null),Array.isArray(d)){const key=checkDescent(d,!1);if(numDescents){const t1=typeof lastKey,t2=typeof key;t1===t2?assert(lastKey<key,"descent keys are not in order"):assert(t1==="number"&&t2==="string")}lastKey=key,numDescents++,last=3}else typeof d=="object"?(assert(last===1,`Prev not scalar - instead ${last}`),checkComponent(d),last=2):(assert(last!==3),checkScalar(d),assert(cursor_js_1.isValidPathItem(d),"Invalid path key"),last=1)}return assert(numDescents!==1,"Operation makes multiple descents. Remove some []"),assert(last===2||last===3),descent[0]},"checkDescent");checkDescent(op,!0),assert(pickedSlots.size===droppedSlots.size,"Mismatched picks and drops in op");for(let i=0;i<pickedSlots.size;i++)assert(pickedSlots.has(i)),assert(droppedSlots.has(i))}__name(checkValidOp,"checkValidOp");function normalize(op){let nextSlot=0,slotMap=[];const w=cursor_js_1.writeCursor();return w.mergeTree(op,(c,w2)=>{const t=getEditType(c);if(t){const op2=getEdit(c);writeEdit(w2,t,t.normalize?t.normalize(op2):op2)}for(const k of["r","p","i","d"])if(c[k]!==void 0){const r=k==="p"||k==="d"?(inSlot=c[k],slotMap[inSlot]==null&&(slotMap[inSlot]=nextSlot++),slotMap[inSlot]):c[k];w2.write(k,r)}var inSlot}),w.get()}__name(normalize,"normalize");function apply(snapshot,op){if(checkValidOp(op),op===null)return snapshot;const held=[];return __name(function drop(root,descent){let subDoc=root,i=0,rootContainer={root},m=0,container=rootContainer,key="root";function mut(){for(;m<i;m++){let d=descent[m];typeof d!="object"&&(assert(isValidKey(container,key)),container=container[key]=shallowClone(container[key]),key=d)}}for(__name(mut,"mut");i<descent.length;i++){const d=descent[i];if(Array.isArray(d)){const child=drop(subDoc,d);child!==subDoc&&child!==void 0&&(mut(),subDoc=container[key]=child)}else if(typeof d=="object"){d.d!=null?(mut(),subDoc=insertChildMut(container,key,held[d.d])):d.i!==void 0&&(mut(),subDoc=insertChildMut(container,key,d.i));const t=getEditType(d);if(t)mut(),subDoc=container[key]=t.apply(subDoc,getEdit(d));else if(d.e!==void 0)throw Error("Subtype "+d.et+" undefined")}else subDoc=maybeGetChild(subDoc,d)}return rootContainer.root},"drop")(snapshot=__name(function pick(subDoc,descent){const stack=[];let i=0;for(;i<descent.length;i++){const d=descent[i];if(Array.isArray(d))break;typeof d!="object"&&(stack.push(subDoc),subDoc=maybeGetChild(subDoc,d))}for(let j=descent.length-1;j>=i;j--)subDoc=pick(subDoc,descent[j]);for(--i;i>=0;i--){const d=descent[i];if(typeof d!="object"){const container=stack.pop();subDoc=subDoc===maybeGetChild(container,d)?container:subDoc===void 0?removeChild(container,d):(k=d,v=subDoc,(obj=shallowClone(obj=container))[k]=v,obj)}else hasPick(d)&&(assert(subDoc!==void 0,"Cannot pick up or remove undefined"),d.p!=null&&(held[d.p]=subDoc),subDoc=void 0)}var obj,k,v;return subDoc},"pick")(snapshot,op),op)}__name(apply,"apply");function transformPosition(path,op){path=path.slice(),checkValidOp(op);const r=cursor_js_1.readCursor(op);let pickedAtSlot,pickIndex,removed=!1;const advStack=[];for(let i=0;;i++){const k=path[i],c=r.getComponent();if(c&&(c.r!==void 0?removed=!0:c.p!=null&&(removed=!1,pickedAtSlot=c.p,pickIndex=i)),i>=path.length)break;let pickOffset=0;const pickAdv=cursor_js_1.advancer(r,void 0,(k2,c2)=>{hasPick(c2)&&pickOffset++});advStack.unshift(pickAdv);const hasNext=pickAdv(k);if(typeof k=="number"&&(path[i]-=pickOffset),!hasNext)break}if(advStack.forEach(pickAdv=>pickAdv.end()),removed)return null;const handleDrop=__name(()=>{let i=0;if(pickedAtSlot!=null){const rPath=r.getPath();i=rPath.length,path=rPath.concat(path.slice(pickIndex))}for(;i<path.length;i++){const k=path[i],c=getComponent(r),et=getEditType(c);if(et){const e=getEdit(c);et.transformPosition&&(path[i]=et.transformPosition(path[i],e));break}let dropOffset=0;const hasNext=cursor_js_1.advancer(r,(k2,c2)=>hasDrop(c2)?~(k2-dropOffset):k2-dropOffset,(k2,c2)=>{hasDrop(c2)&&dropOffset++})(k);if(typeof k=="number"&&(path[i]+=dropOffset),!hasNext)break}},"handleDrop");return pickedAtSlot!=null?r.eachDrop(null,slot=>{slot===pickedAtSlot&&handleDrop()}):handleDrop(),path}__name(transformPosition,"transformPosition");function compose(op1,op2){if(checkValidOp(op1),checkValidOp(op2),op1==null)return op2;if(op2==null)return op1;let nextSlot=0;const r1=cursor_js_1.readCursor(op1),r2=cursor_js_1.readCursor(op2),w=cursor_js_1.writeCursor(),heldPickWrites=[],heldDropWrites=[],held1Pick=[],held2Drop=[],p1SlotMap=[],p2SlotMap=[],visitedOp2EditCs=new Set;r1.traverse(null,c=>{c.p!=null&&(held1Pick[c.p]=r1.clone())}),r2.traverse(null,c=>{c.d!=null&&(held2Drop[c.d]=r2.clone())});const w2=cursor_js_1.writeCursor();return __name(function xfBoundary(r1Pick,r1Drop,r2Pick,r2Drop,litIn,rmParent,wd,wp){assert(r1Drop||r2Pick);const c1d=getComponent(r1Drop),c2p=getComponent(r2Pick),rmHere=!!c2p&&c2p.r!==void 0,insHere=!!c1d&&c1d.i!==void 0,drop1Slot=c1d?c1d.d:null,pick2Slot=c2p?c2p.p:null,rmChildren=(rmParent||rmHere)&&pick2Slot==null;if(pick2Slot!=null)r2Drop=held2Drop[pick2Slot],wd=heldDropWrites[pick2Slot]=new cursor_js_1.WriteCursor;else if(c2p&&c2p.r!==void 0)r2Drop=null;else{const c2d2=getComponent(r2Drop);c2d2&&c2d2.d!=null&&(r2Drop=null)}const c2d=getComponent(r2Drop);if(drop1Slot!=null)if(r1Pick=held1Pick[drop1Slot],wp=heldPickWrites[drop1Slot]=new cursor_js_1.WriteCursor,rmChildren)rmParent&&!rmHere&&wp.write("r",!0);else{const slot=p1SlotMap[drop1Slot]=nextSlot++;wd.write("d",slot)}else if(c1d&&c1d.i!==void 0)r1Pick=null;else{const c1p=getComponent(r1Pick);c1p&&c1p.p!=null&&(r1Pick=null)}let litOut;insHere?(assert(litIn===void 0),litOut=c1d.i):litOut=litIn;const insComponent=(pick2Slot==null?!insHere||rmParent||rmHere:litOut===void 0)?null:wd.getComponent();if(pick2Slot!=null){if(!(litIn!==void 0||insHere)){const slot=drop1Slot!=null?p1SlotMap[drop1Slot]:nextSlot++;p2SlotMap[pick2Slot]=slot,wp.write("p",slot)}}else rmHere&&(insHere||litIn!==void 0||(c2p.r,wp.write("r",c2p.r)));const type1=rmChildren?null:getEditType(c1d),type2=getEditType(c2d);if((type1||type2)&&(type1&&type1.name,type2&&type2.name),type1&&type2){assert(type1===type2);const e1=getEdit(c1d),e2=getEdit(c2d),r=type1.compose(e1,e2);writeEdit(wd,type1,r),visitedOp2EditCs.add(c2d)}else type1?writeEdit(wd,type1,getEdit(c1d)):type2&&(writeEdit(wd,type2,getEdit(c2d)),visitedOp2EditCs.add(c2d));const hasContainerLiteral=typeof litOut=="object"&&litOut!=null;let isCloned=!1,p1PickOff=0,p1DropOff=0,p2PickOff=0,p2DropOff=0,litOff=0;const p2DropAdv=cursor_js_1.advancer(r2Drop,(k,c)=>hasDrop(c)?p2DropOff-k-1:k-p2DropOff,(k,c)=>{hasDrop(c)&&p2DropOff++}),p1PickAdv=cursor_js_1.advancer(r1Pick,(k,c)=>hasPick(c)?p1PickOff-k-1:k-p1PickOff,(k,c)=>{hasPick(c)&&p1PickOff++});if(cursor_js_1.eachChildOf(r1Drop,r2Pick,(inKey,_p1Drop,_p2Pick)=>{let _p1Pick,_p2Drop,p1PickKey=inKey,p2DropKey=inKey,litKey=inKey;if(typeof inKey=="number"){let p2Mid=inKey+p2PickOff;_p2Drop=p2DropAdv(p2Mid),p2DropKey=p2Mid+p2DropOff;let p1Mid=inKey+p1DropOff;_p1Pick=p1PickAdv(p1Mid),hasDrop(getComponent(_p2Drop))&&(_p1Pick=null),p1PickKey=p1Mid+p1PickOff,litKey=inKey+litOff,assert(p1PickKey>=0,"p1PickKey is negative"),assert(p2DropKey>=0,"p2DropKey is negative");const hd1=hasDrop(getComponent(_p1Drop)),hp2=hasPick(getComponent(_p2Pick));(hd1||hp2&&!rmChildren)&&litOff--,hd1&&p1DropOff--,hp2&&p2PickOff--}else _p1Pick=p1PickAdv(inKey),_p2Drop=p2DropAdv(inKey);wp.descend(p1PickKey),wd.descend(p2DropKey);const _lit=hasContainerLiteral&&!hasDrop(getComponent(_p1Drop))?litOut[litKey]:void 0,_litResult=xfBoundary(_p1Pick,_p1Drop,_p2Pick,_p2Drop,_lit,rmChildren,wd,wp);var container,key,child;hasContainerLiteral&&!rmChildren?_lit!==_litResult&&(isCloned||(litOut=Array.isArray(litOut)?litOut.slice():Object.assign({},litOut),isCloned=!0),container=litOut,child=_litResult,typeof(key=litKey)=="number"?(assert(Array.isArray(container)),assert(key<container.length)):(assert(!Array.isArray(container)),assert(container[key]!==void 0)),child===void 0?typeof key=="number"?container.splice(key,1):delete container[key]:container[key]=child):assert(_litResult===void 0),wd.ascend(),wp.ascend()}),p1PickAdv.end(),p2DropAdv.end(),insComponent!=null)insComponent.i=litOut;else if(!rmParent&&!rmHere&&pick2Slot==null)return litOut},"xfBoundary")(r1,r1.clone(),r2,r2.clone(),void 0,!1,w,w2),w.reset(),w.mergeTree(w2.get()),w.reset(),w.get(),heldPickWrites.map(w3=>w3.get()),heldDropWrites.map(w3=>w3.get()),r1.traverse(w,(c,w3)=>{const slot1=c.p;if(slot1!=null){const slot=p1SlotMap[slot1];slot!=null&&w3.write("p",slot);const _w=heldPickWrites[slot1];_w&&_w.get(),_w&&w3.mergeTree(_w.get())}else c.r!==void 0&&w3.write("r",c.r)}),w.reset(),w.get(),r2.traverse(w,(c,w3)=>{const slot2=c.d;if(slot2!=null){const slot=p2SlotMap[slot2];slot!=null&&w3.write("d",slot);const _w=heldDropWrites[slot2];_w&&w3.mergeTree(_w.get())}else c.i!==void 0&&w3.write("i",c.i);const t=getEditType(c);t&&!visitedOp2EditCs.has(c)&&writeEdit(w3,t,getEdit(c))}),w.get()}__name(compose,"compose");function invert(op){if(op==null)return null;const r=new cursor_js_1.ReadCursor(op),w=new cursor_js_1.WriteCursor;let editsToTransform;const heldPick=[],heldWrites=[];return __name(function invertSimple(r2,w2,subDoc){const c=r2.getComponent();let insertHere,subdocModified=!1;if(c){c.p!=null&&(w2.write("d",c.p),heldPick[c.p]=r2.clone()),c.r!==void 0&&w2.write("i",c.r),c.d!=null&&(w2.write("p",c.d),subDoc=void 0),c.i!==void 0&&(subDoc=insertHere=c.i);const t=getEditType(c);t&&(subDoc===void 0?(editsToTransform||(editsToTransform=new Set),editsToTransform.add(c)):(getEdit(c),subDoc=t.apply(subDoc,getEdit(c)),subdocModified=!0))}let dropOff=0;for(const key of r2){w2.descend(key);const raw=typeof key=="number"?key-dropOff:key,childIn=maybeGetChild(subDoc,raw);hasDrop(r2.getComponent())&&dropOff++;const childOut=invertSimple(r2,w2,childIn);if(subDoc!==void 0&&childOut!==void 0){if(subdocModified||(subdocModified=!0,subDoc=shallowClone(subDoc)),!isValidKey(subDoc,raw))throw Error("Cannot modify child - invalid operation");subDoc[raw]=childOut}w2.ascend()}if(insertHere===void 0)return subdocModified?subDoc:void 0;w2.write("r",subDoc)},"invertSimple")(r,w,void 0),editsToTransform&&(w.reset(),__name(function transformEdits(rPick,rDrop,w2){const cd=rDrop.getComponent();if(cd){const dropSlot=cd.d;if(dropSlot!=null&&(rPick=heldPick[dropSlot],w2=heldWrites[dropSlot]=cursor_js_1.writeCursor()),editsToTransform.has(cd)){const t=getEditType(cd);if(!t.invert)throw Error(`Cannot invert subtype ${t.name}`);writeEdit(w2,t,t.invert(getEdit(cd)))}}let pickOff=0,dropOff=0;const ap=cursor_js_1.advancer(rPick,(k,c)=>hasPick(c)?pickOff-k-1:k-pickOff,(k,c)=>{hasPick(c)&&pickOff++});for(const key of rDrop)if(typeof key=="number"){const mid=key-dropOff,_rPick=ap(mid),raw=mid+pickOff;w2.descend(raw),transformEdits(_rPick,rDrop,w2),hasDrop(rDrop.getComponent())&&dropOff++,w2.ascend()}else w2.descend(key),transformEdits(ap(key),rDrop,w2),w2.ascend();ap.end()},"transformEdits")(r.clone(),r,w),heldWrites.length&&(w.reset(),r.traverse(w,(c,w2)=>{const slot=c.p;if(slot!=null){const _w=heldWrites[slot];_w&&_w.get(),_w&&w2.mergeTree(_w.get())}}))),w.get()}__name(invert,"invert");const anyComponent=__name((op,fn)=>op.some(c=>typeof c=="object"&&(Array.isArray(c)?anyComponent(c,fn):fn(c))),"anyComponent");function makeInvertible(op,doc){if(op==null||!anyComponent(op,c=>{var _a13;return c.r!==void 0||((_a13=getEditType(c))===null||_a13===void 0?void 0:_a13.makeInvertible)!=null}))return op;const r=new cursor_js_1.ReadCursor(op),w=new cursor_js_1.WriteCursor;let hasEdits=!1;const heldPick=[],heldDoc=[],traversePick=__name((r2,w2,subDoc)=>{const c=r2.getComponent();let modified=!1;if(c){c.d!=null&&w2.write("d",c.d),c.i!==void 0&&w2.write("i",c.i);const pickSlot=c.p;if(pickSlot!=null&&(heldPick[pickSlot]=r2.clone(),assert(subDoc!==void 0,"Operation picks up at an invalid key"),heldDoc[pickSlot]=subDoc,w2.write("p",c.p)),c.r!==void 0&&subDoc===void 0)throw Error("Invalid doc / op in makeInvertible: removed item missing from doc");const t=getEditType(c);t&&(t.makeInvertible?hasEdits=!0:writeEdit(w2,t,getEdit(c),!0))}let listOff=0;for(const key of r2){w2.descend(key);const keyRaw=typeof key=="number"?key-listOff:key,childIn=maybeGetChild(subDoc,keyRaw),childOut=traversePick(r2,w2,childIn);childIn!==childOut&&(modified||(modified=!0,subDoc=shallowClone(subDoc)),childOut===void 0?(subDoc=removeChild(subDoc,keyRaw),typeof key=="number"&&listOff++):subDoc[keyRaw]=childOut),w2.ascend()}return c&&(c.r!==void 0?(w2.write("r",deepClone_js_1.default(subDoc)),subDoc=void 0):c.p!=null&&(subDoc=void 0)),subDoc},"traversePick");return traversePick(r,w,doc),w.get(),hasEdits&&(w.reset(),__name(function traverseDrop(rPick,rDrop,w2,subDoc,isLiteral){const c=rDrop.getComponent();if(c){c.i!==void 0?(subDoc=c.i,isLiteral=!0):c.d!=null&&(subDoc=heldDoc[c.d],rPick=heldPick[c.d],isLiteral=!1,c.d);let t=getEditType(c);if(t&&t.makeInvertible){const edit=getEdit(c);writeEdit(w2,t,t.makeInvertible(edit,subDoc),!0)}}let pickOff=0,dropOff=0;const ap=cursor_js_1.advancer(rPick,(k,c2)=>hasPick(c2)?pickOff-k-1:k-pickOff,(k,c2)=>{hasPick(c2)&&pickOff++});for(const key of rDrop)if(typeof key=="number"){const mid=key-dropOff,_rPick=ap(mid),raw=mid+pickOff,child=maybeGetChild(subDoc,isLiteral?mid:raw);w2.descend(key),traverseDrop(_rPick,rDrop,w2,child,isLiteral),hasDrop(rDrop.getComponent())&&dropOff++,w2.ascend()}else{const child=maybeGetChild(subDoc,key);w2.descend(key),traverseDrop(ap(key),rDrop,w2,child,isLiteral),w2.ascend()}ap.end()},"traverseDrop")(r.clone(),r,w,doc,!1)),w.get()}__name(makeInvertible,"makeInvertible");function invertWithDoc(op,doc){return invert(makeInvertible(op,doc))}__name(invertWithDoc,"invertWithDoc");const shallowCloneOp=__name(op=>{if(op==null)return null;const result=op.slice();for(let i=0;i<op.length;i++){const c=result[i];Array.isArray(c)&&(result[i]=shallowCloneOp(c))}return result},"shallowCloneOp");function tryTransform(op1,op2,direction){assert(direction==="left"||direction==="right","Direction must be left or right");const side=direction==="left"?0:1;if(op2==null)return{ok:!0,result:op1};checkValidOp(op1),checkValidOp(op2);let conflict=null;const heldOp1PickByOp1=[],heldOp1DropByOp1=[],heldOp2PickByOp2=[],heldOp2DropByOp2=[],heldOp1PickByOp2=[],heldOp2PickByOp1=[],heldOp2DropByOp1=[],heldOp2RmForOp1=[],heldOp1RmForOp2=[],cancelledOp2=[],discardedOp2Drop=[],heldPickWrites=[],heldDropWrites=[],op1PickAtOp2Pick=[],op1PicksOp2DropSlots=[];let nextSlot=0;const r1=cursor_js_1.readCursor(op1),r2=cursor_js_1.readCursor(op2),w=cursor_js_1.writeCursor();if(__name(function scanOp2Pick(r2Pick,r1Pick=null,removed1){const c1=getComponent(r1Pick);c1&&(c1.r!==void 0?removed1=r1Pick.clone():c1.p!=null&&(removed1=null,heldOp2PickByOp1[c1.p]=r2Pick.clone()));const c2=r2Pick.getComponent();let slot2;c2&&(slot2=c2.p)!=null&&(heldOp1PickByOp2[slot2]=r1Pick?r1Pick.clone():null,heldOp2PickByOp2[slot2]=r2Pick.clone(),removed1&&(cancelledOp2[slot2]=!0,heldOp1RmForOp2[slot2]=removed1),c1&&c1.p!=null&&(op1PickAtOp2Pick[slot2]=c1.p));const ap1=cursor_js_1.advancer(r1Pick);for(const key of r2Pick)scanOp2Pick(r2Pick,ap1(key),removed1);ap1.end()},"scanOp2Pick")(r2,r1,null),__name(function scanOp2Drop(r1Pick,r2Pick,r2Drop,pickSlot1,removed1){const c2d=r2Drop.getComponent();let slot2,droppedHere=!1;c2d&&((slot2=c2d.d)!=null?(heldOp2DropByOp2[slot2]=r2Drop.clone(),pickSlot1!=null&&(op1PicksOp2DropSlots[pickSlot1]==null&&(op1PicksOp2DropSlots[pickSlot1]=[]),op1PicksOp2DropSlots[pickSlot1].push(slot2)),r1Pick=heldOp1PickByOp2[slot2]||null,r2Pick=heldOp2PickByOp2[slot2]||null,cancelledOp2[slot2]?(removed1&&(discardedOp2Drop[slot2]=!0),removed1=heldOp1RmForOp2[slot2]||null):!removed1||side!==1&&op1PickAtOp2Pick[slot2]!=null||conflict==null&&(conflict={type:types_js_1.ConflictType.RM_UNEXPECTED_CONTENT,op1:exports2.removeOp(removed1.getPath()),op2:exports2.moveOp(r2Pick.getPath(),r2Drop.getPath())}),droppedHere=!0):c2d.i!==void 0&&(r1Pick=r2Pick=null,droppedHere=!0,removed1&&conflict==null&&(conflict={type:types_js_1.ConflictType.RM_UNEXPECTED_CONTENT,op1:exports2.removeOp(removed1.getPath()),op2:exports2.insertOp(r2Drop.getPath(),c2d.i)})));const c1p=getComponent(r1Pick);c1p&&(c1p.r!==void 0?removed1=r1Pick.clone():c1p.p!=null&&(c1p.p,pickSlot1=c1p.p,removed1=null));const t2=getEditType(c2d);t2&&removed1&&conflict==null&&(conflict={type:types_js_1.ConflictType.RM_UNEXPECTED_CONTENT,op1:exports2.removeOp(removed1.getPath()),op2:exports2.editOp(r2Drop.getPath(),t2,getEdit(c2d),!0)});let p2PickOff=0,p2DropOff=0;const ap2=cursor_js_1.advancer(r2Pick,(k,c)=>hasPick(c)?p2PickOff-k-1:k-p2PickOff,(k,c)=>{hasPick(c)&&p2PickOff++}),ap1=cursor_js_1.advancer(r1Pick);for(const key of r2Drop)if(typeof key=="number"){const p2Mid=key-p2DropOff,_p2Pick=ap2(p2Mid);p2DropOff+=+scanOp2Drop(ap1(p2Mid+p2PickOff),_p2Pick,r2Drop,pickSlot1,removed1)}else{const _p2Pick=ap2(key);scanOp2Drop(ap1(key),_p2Pick,r2Drop,pickSlot1,removed1)}return ap2.end(),ap1.end(),droppedHere},"scanOp2Drop")(r1,r2,r2.clone(),null,null),heldOp2DropByOp2.map(x=>x&&x.get()),conflict)return{ok:!1,conflict};discardedOp2Drop.map(x=>!!x);const pickComponents=[];let cancelledRemoves=null;__name(function writeOp1Pick(r1Pick,r2Pick,r2Drop,w2,removed2){let iAmMoved=!1;const c2p=getComponent(r2Pick);if(hasPick(c2p)){const slot2=c2p.p;slot2!=null?(r2Drop=heldOp2DropByOp2[slot2],w2=heldPickWrites[slot2]=cursor_js_1.writeCursor(),iAmMoved=!0,removed2=null):(r2Drop=null,removed2=r2Pick.clone())}else hasDrop(getComponent(r2Drop))&&(r2Drop=null);const c1=r1Pick.getComponent();if(c1){const slot1=c1.p;slot1!=null?(removed2&&(heldOp2RmForOp1[slot1]=removed2),pickComponents[slot1]=removed2||side===1&&iAmMoved?null:w2.getComponent(),heldOp1PickByOp1[slot1]=r1Pick.clone(),r2Drop&&(heldOp2DropByOp1[slot1]=r2Drop.clone())):c1.r!==void 0&&(removed2||w2.write("r",!0),(removed2||iAmMoved)&&(cancelledRemoves==null&&(cancelledRemoves=new Set),cancelledRemoves.add(c1)))}let p2PickOff=0,p2DropOff=0;const ap2Pick=cursor_js_1.advancer(r2Pick,void 0,(k,c)=>{hasPick(c)&&p2PickOff++}),ap2Drop=cursor_js_1.advancer(r2Drop,(k,c)=>hasDrop(c)?~(k-p2DropOff):k-p2DropOff,(k,c)=>{hasDrop(c)&&p2DropOff++});if(r1Pick)for(const key of r1Pick)if(typeof key=="string"){const p2Pick_=ap2Pick(key),p2Drop_=ap2Drop(key);w2.descend(key),writeOp1Pick(r1Pick,p2Pick_,p2Drop_,w2,removed2),w2.ascend()}else{const p2Pick_=ap2Pick(key),p2Mid=key-p2PickOff,p2Drop_=hasPick(getComponent(p2Pick_))?null:ap2Drop(p2Mid),finalKey=p2Mid+p2DropOff;assert(finalKey>=0),w2.descend(finalKey),writeOp1Pick(r1Pick,p2Pick_,p2Drop_,w2,removed2),w2.ascend()}ap2Pick.end(),ap2Drop.end()},"writeOp1Pick")(r1,r2,r2.clone(),w,null),w.reset();let outputSlotMap=[];if(__name(function writeOp1Drop(p1Pick,p1Drop,p2Pick,p2Drop,w2,removed2){assert(p1Drop);const c1d=p1Drop.getComponent();let c2d=getComponent(p2Drop),droppedHere=!1;const insOrMv=__name((r12,r22,c)=>r12?exports2.moveOp(r12.getPath(),r22.getPath()):exports2.insertOp(r22.getPath(),c.i),"insOrMv");if(hasDrop(c1d)){const slot1=c1d.d;slot1!=null&&(heldOp1DropByOp1[slot1]=p1Drop.clone());const pc=slot1!=null?pickComponents[slot1]:null;let identical=!1;if(c1d.i!==void 0||slot1!=null&&pc){let slot2;c2d&&(c2d.i!==void 0||(slot2=c2d.d)!=null&&!cancelledOp2[slot2])&&(identical=slot2!=null?slot1!=null&&slot1===op1PickAtOp2Pick[slot2]:deepEqual_js_1.default(c2d.i,c1d.i),identical||slot2!=null&&side!==1&&op1PickAtOp2Pick[slot2]!=null||conflict==null&&(conflict={type:types_js_1.ConflictType.DROP_COLLISION,op1:insOrMv(slot1!=null?heldOp1PickByOp1[slot1]:null,p1Drop,c1d),op2:insOrMv(slot2!=null?heldOp2PickByOp2[slot2]:null,p2Drop,c2d)})),identical||(removed2?conflict==null&&(conflict={type:types_js_1.ConflictType.RM_UNEXPECTED_CONTENT,op1:insOrMv(slot1!=null?heldOp1PickByOp1[slot1]:null,p1Drop,c1d),op2:exports2.removeOp(removed2.getPath())}):(slot1!=null?(outputSlotMap[nextSlot]=slot1,w2.write("d",pc.p=nextSlot++)):w2.write("i",deepClone_js_1.default(c1d.i)),droppedHere=!0))}else if(slot1!=null&&!pc){const h=heldOp2RmForOp1[slot1];h&&(removed2=h.clone())}slot1!=null?(p1Pick=heldOp1PickByOp1[slot1],p2Pick=heldOp2PickByOp1[slot1],p2Drop=heldOp2DropByOp1[slot1]):c1d.i!==void 0&&(p1Pick=p2Pick=null,identical||(p2Drop=null))}else hasPick(getComponent(p1Pick))&&(p1Pick=p2Pick=p2Drop=null);const c1p=getComponent(p1Pick),c2p=getComponent(p2Pick);if(hasPick(c2p)){const slot2=c2p.p;c2p.r!==void 0&&(!c1p||c1p.r===void 0)||cancelledOp2[slot2]?(p2Drop=null,removed2=p2Pick.clone()):slot2!=null&&(p2Drop=heldOp2DropByOp2[slot2],side!==1&&op1PickAtOp2Pick[slot2]!=null||((w2=heldDropWrites[slot2])||(w2=heldDropWrites[slot2]=cursor_js_1.writeCursor()),w2.reset(),removed2=null))}else!hasDrop(c1d)&&hasDrop(c2d)&&(p2Drop=null);c2d=p2Drop!=null?p2Drop.getComponent():null;const t1=getEditType(c1d);if(t1){const e1=getEdit(c1d);if(removed2)conflict==null&&(conflict={type:types_js_1.ConflictType.RM_UNEXPECTED_CONTENT,op1:exports2.editOp(p1Drop.getPath(),t1,e1,!0),op2:exports2.removeOp(removed2.getPath())});else{const t2=getEditType(c2d);let e;if(t2){if(t1!==t2)throw Error("Transforming incompatible types");const e2=getEdit(c2d);e=t1.transform(e1,e2,direction)}else e=deepClone_js_1.default(e1);writeEdit(w2,t1,e)}}let p1PickOff=0,p1DropOff=0,p2PickOff=0,p2DropOff=0,outPickOff=0,outDropOff=0,p1pValid=p1Pick!=null&&p1Pick.descendFirst(),p1pDidDescend=p1pValid;const ap2p=cursor_js_1.advancer(p2Pick,void 0,(k,c)=>{hasPick(c)&&p2PickOff++});let p2dValid=p2Drop!=null&&p2Drop.descendFirst(),p2dDidDescend=p2dValid;for(const key of p1Drop)if(typeof key=="number"){let _p1Pick;const hd1=hasDrop(p1Drop.getComponent()),k1Mid=key-p1DropOff;{let p1k;for(;p1pValid&&typeof(p1k=p1Pick.getKey())=="number";){p1k+=p1PickOff;const c=p1Pick.getComponent(),hp=hasPick(c);if(p1k>k1Mid||p1k===k1Mid&&(!hp||side===0&&hd1))break;if(hp){p1PickOff--;const slot1=c.p;op1PickAtOp2Pick.includes(slot1),c.d,getComponent(heldDropWrites[c.d]),hasPick(getComponent(heldDropWrites[c.d])),(c.r===void 0||cancelledRemoves&&cancelledRemoves.has(c))&&(slot1==null||!pickComponents[slot1]||side!==1&&op1PickAtOp2Pick.includes(slot1))||outPickOff--}p1pValid=p1Pick.nextSibling()}_p1Pick=p1pValid&&p1k===k1Mid?p1Pick:null}const raw=k1Mid-p1PickOff;let _p2Pick=ap2p(raw);const k2Mid=raw-p2PickOff;let _p2Drop=null;{let p2dk,op2Mid;for(;p2dValid&&typeof(p2dk=p2Drop.getKey())=="number";){op2Mid=p2dk-p2DropOff;const c=p2Drop.getComponent(),hd2=hasDrop(c);if(op2Mid>k2Mid)break;if(op2Mid===k2Mid){if(!hd2){_p2Drop=p2Drop;break}{if(side===0&&hd1){_p2Drop=p2Drop;break}const hp2=_p2Pick&&hasPick(_p2Pick.getComponent());if(side===0&&hp2)break}}if(hd2){const slot2=c.d;op1PickAtOp2Pick[slot2],c.i===void 0&&(cancelledOp2[slot2]||op1PickAtOp2Pick[slot2]!=null&&side!==1)?(cancelledOp2[slot2]||op1PickAtOp2Pick[slot2]!=null&&side===0)&&(p2DropOff++,outDropOff--):p2DropOff++}p2dValid=p2Drop.nextSibling()}}const descend=k2Mid+p2DropOff+outPickOff+outDropOff;assert(descend>=0,"trying to descend to a negative index"),w2.descend(descend),hd1&&(_p1Pick=_p2Pick=_p2Drop=null,p1DropOff++),writeOp1Drop(_p1Pick,p1Drop,_p2Pick,_p2Drop,w2,removed2)&&outDropOff++,w2.ascend()}else{let p1k;for(;p1pValid&&(p1k=p1Pick.getKey(),typeof p1k!="string"||!(p1k>key||p1k===key));)p1pValid=p1Pick.nextSibling();const _p1Pick=p1pValid&&p1k===key?p1Pick:null,_p2Pick=ap2p(key);let p2dk;for(;p2dValid&&(p2dk=p2Drop.getKey(),typeof p2dk!="string"||!(p2dk>key||p2dk===key));)p2dValid=p2Drop.nextSibling();const _p2Drop=p2dValid&&p2dk===key?p2Drop:null;w2.descend(key),writeOp1Drop(_p1Pick,p1Drop,_p2Pick,_p2Drop,w2,removed2),w2.ascend()}return ap2p.end(),p1pDidDescend&&p1Pick.ascend(),p2dDidDescend&&p2Drop.ascend(),droppedHere},"writeOp1Drop")(r1,r1.clone(),r2,r2.clone(),w,null),conflict)return{ok:!1,conflict};w.reset();const eachDrop=__name((r,w2,fn)=>r.traverse(w2,(c,w3)=>{c.d!=null&&fn(c.d,r,w3)}),"eachDrop");(cancelledOp2.length||heldPickWrites.length)&&(eachDrop(r2,w,(slot2,r,w2)=>{cancelledOp2[slot2]&&!discardedOp2Drop[slot2]&&w2.write("r",!0),heldPickWrites[slot2]&&w2.mergeTree(heldPickWrites[slot2].get())}),w.reset());const heldOutDropRead=[],heldOutDropWrites=[];if((heldDropWrites.length||cancelledOp2.length)&&!conflict){const rOut=cursor_js_1.readCursor(shallowCloneOp(w.get()));if(eachDrop(rOut,null,(slotOut,r)=>{heldOutDropRead[slotOut]=r.clone()}),heldDropWrites.forEach(hdw=>{hdw&&eachDrop(cursor_js_1.readCursor(hdw.get()),null,(slotOut,r)=>{heldOutDropRead[slotOut]=r.clone()})}),__name(function writeHeldOp2Drop(p2Drop,outPick,outDrop,w2,parentC,removedOut){const coutp=getComponent(outPick);if(coutp&&hasPick(coutp))if(coutp.p!=null){const slot=coutp.p;heldOutDropRead[slot].getPath(),outDrop=heldOutDropRead[slot],w2=heldOutDropWrites[slot]=cursor_js_1.writeCursor()}else coutp.r!==void 0&&(outDrop=null);else hasDrop(getComponent(outDrop))&&(outDrop=null);const c2=p2Drop.getComponent();if(c2){let slot2;if((slot2=c2.d)!=null){const _w=heldDropWrites[slot2];_w&&(_w.get(),w2.mergeTree(_w.get()),outDrop=cursor_js_1.readCursor(_w.get()))}}let outPickOff=0,outDropOff=0;const oPickAdv=cursor_js_1.advancer(outPick,void 0,(k,c)=>{hasPick(c)&&outPickOff--}),oDropAdv=cursor_js_1.advancer(outDrop,(k,c)=>hasDrop(c)?-(k-outDropOff)-1:k-outDropOff,(k,c)=>{hasDrop(c)&&outDropOff++});for(const o2dk of p2Drop)if(typeof o2dk=="number"){const _outPick=oPickAdv(o2dk),rmid=o2dk+outPickOff,_outDrop=oDropAdv(rmid),rfinal=rmid+outDropOff;w2.descend(rfinal),writeHeldOp2Drop(p2Drop,_outPick,_outDrop,w2),w2.ascend()}else w2.descend(o2dk),writeHeldOp2Drop(p2Drop,oPickAdv(o2dk),oDropAdv(o2dk),w2),w2.ascend();oPickAdv.end(),oDropAdv.end()},"writeHeldOp2Drop")(r2,rOut,rOut.clone(),w),w.reset(),conflict)return{ok:!1,conflict};if(w.get(),heldOutDropWrites.length){const heldOutDropContent=heldOutDropWrites.map(w2=>w2?w2.get():null),rOut2=cursor_js_1.readCursor(shallowCloneOp(w.get()));if(eachDrop(rOut2,w,(slotOut,r,w2)=>{const data=heldOutDropContent[slotOut];data&&(w2.mergeTree(data),heldOutDropContent[slotOut]=null)}),heldOutDropContent.find(x=>x)){const w1=cursor_js_1.writeCursor(),w2=cursor_js_1.writeCursor();let nextSlot1=0,nextSlot2=0;heldOutDropContent.forEach(data=>{data!=null&&eachDrop(cursor_js_1.readCursor(data),null,c=>{const slot1=outputSlotMap[c];w1.writeMove(heldOp1PickByOp1[slot1].getPath(),heldOp1DropByOp1[slot1].getPath(),nextSlot1++);const slot2s=op1PicksOp2DropSlots[slot1];slot2s&&slot2s.forEach(slot2=>{cancelledOp2[slot2]||side!==1&&op1PickAtOp2Pick[slot2]!=null||w2.writeMove(heldOp2PickByOp2[slot2].getPath(),heldOp2DropByOp2[slot2].getPath(),nextSlot2++)})})}),conflict={type:types_js_1.ConflictType.BLACKHOLE,op1:w1.get(),op2:w2.get()}}}}return conflict?{ok:!1,conflict}:{ok:!0,result:w.get()}}__name(tryTransform,"tryTransform");const throwConflictErr=__name(conflict=>{const err=new Error("Transform detected write conflict");throw err.conflict=conflict,err.type=err.name="writeConflict",err},"throwConflictErr");function transform(op1,op2,side){const res=tryTransform(op1,op2,side);if(res.ok)return res.result;throwConflictErr(res.conflict)}__name(transform,"transform");const opThatRemovesDE=__name(op=>{const w=cursor_js_1.writeCursor();return cursor_js_1.readCursor(op).traverse(w,(c,w2)=>{(hasDrop(c)||getEditType(c))&&w2.write("r",!0)}),w.get()},"opThatRemovesDE"),resolveConflict=__name((conflict,side)=>{const{type:type2,op1,op2}=conflict;switch(type2){case types_js_1.ConflictType.DROP_COLLISION:return side==="left"?[null,opThatRemovesDE(op2)]:[opThatRemovesDE(op1),null];case types_js_1.ConflictType.RM_UNEXPECTED_CONTENT:let op1HasRemove=!1;return cursor_js_1.readCursor(op1).traverse(null,c=>{c.r!==void 0&&(op1HasRemove=!0)}),op1HasRemove?[null,opThatRemovesDE(op2)]:[opThatRemovesDE(op1),null];case types_js_1.ConflictType.BLACKHOLE:return[opThatRemovesDE(op1),opThatRemovesDE(op2)];default:throw Error("Unrecognised conflict: "+type2)}},"resolveConflict");function transformWithConflictsPred(allowConflict,op1,op2,side){let r2Aggregate=null;for(;;){const res=tryTransform(op1,op2,side);if(res.ok)return compose(r2Aggregate,res.result);{const{conflict}=res;allowConflict(conflict)||throwConflictErr(conflict);const[r1,r2]=resolveConflict(conflict,side);op1=compose(normalize(op1),r1),op2=compose(normalize(op2),r2),r2Aggregate=compose(r2Aggregate,r2)}}}__name(transformWithConflictsPred,"transformWithConflictsPred")})(json1_release);(function(exports2){var __createBinding=commonjsGlobal&&commonjsGlobal.__createBinding||(Object.create?function(o,m,k,k2){k2===void 0&&(k2=k),Object.defineProperty(o,k2,{enumerable:!0,get:__name(function(){return m[k]},"get")})}:function(o,m,k,k2){k2===void 0&&(k2=k),o[k2]=m[k]}),__exportStar=commonjsGlobal&&commonjsGlobal.__exportStar||function(m,exports3){for(var p in m)p!=="default"&&!exports3.hasOwnProperty(p)&&__createBinding(exports3,m,p)};Object.defineProperty(exports2,"__esModule",{value:!0}),__exportStar(json1_release,exports2);var cursor_js_1=cursor;Object.defineProperty(exports2,"ReadCursor",{enumerable:!0,get:__name(function(){return cursor_js_1.ReadCursor},"get")}),Object.defineProperty(exports2,"WriteCursor",{enumerable:!0,get:__name(function(){return cursor_js_1.WriteCursor},"get")});var types_1=types;Object.defineProperty(exports2,"ConflictType",{enumerable:!0,get:__name(function(){return types_1.ConflictType},"get")})})(dist$1);const index=getDefaultExportFromCjs(dist$1),index$1=_mergeNamespaces({__proto__:null,default:index},[dist$1]);var TextXActionType=(TextXActionType2=>(TextXActionType2.RETAIN="r",TextXActionType2.INSERT="i",TextXActionType2.DELETE="d",TextXActionType2))(TextXActionType||{});const _ActionIterator=class _ActionIterator{constructor(_actions){__publicField(this,"_index",0);__publicField(this,"_offset",0);this._actions=_actions}hasNext(){return this.peekLength()<Number.POSITIVE_INFINITY}next(length){length||(length=Number.POSITIVE_INFINITY);const nextAction=this._actions[this._index];if(nextAction){const offset=this._offset,actionLength=nextAction.len;return length>=actionLength-offset?(length=actionLength-offset,this._index+=1,this._offset=0):this._offset+=length,nextAction.t===TextXActionType.DELETE||nextAction.t===TextXActionType.RETAIN&&nextAction.body==null?Tools.deepClone({...nextAction,len:length}):Tools.deepClone({...nextAction,len:length,body:getBodySlice(nextAction.body,offset,offset+length)})}else return{t:TextXActionType.RETAIN,len:Number.POSITIVE_INFINITY}}peek(){return this._actions[this._index]}peekLength(){return this._actions[this._index]?this._actions[this._index].len-this._offset:Number.POSITIVE_INFINITY}peekType(){const action=this._actions[this._index];return action?action.t:TextXActionType.RETAIN}rest(){if(this.hasNext()){if(this._offset===0)return this._actions.slice(this._index);{const offset=this._offset,index2=this._index,next=this.next(),restActions=this._actions.slice(this._index);return this._offset=offset,this._index=index2,[next].concat(restActions)}}else return[]}};__name(_ActionIterator,"ActionIterator");let ActionIterator=_ActionIterator;const _MemoryCursor=class _MemoryCursor{constructor(){__publicField(this,"cursor",0)}reset(){return this.cursor=0,this}moveCursor(pos){this.cursor+=pos}moveCursorTo(pos){this.cursor=pos}};__name(_MemoryCursor,"MemoryCursor");let MemoryCursor=_MemoryCursor;function updateAttributeByDelete(body,textLength,currentIndex){const{dataStream}=body,startIndex=currentIndex,endIndex=currentIndex+textLength,removeTextRuns=deleteTextRuns(body,textLength,currentIndex),removeParagraphs=deleteParagraphs(body,textLength,currentIndex),removeSectionBreaks=deleteSectionBreaks(body,textLength,currentIndex),removeCustomBlocks=deleteCustomBlocks(body,textLength,currentIndex),removeTables=deleteTables(body,textLength,currentIndex),removeCustomRanges=deleteCustomRanges(body,textLength,currentIndex),removeCustomDecorations=deleteCustomDecorations(body,textLength,currentIndex);let removeDataStream="";return dataStream&&(body.dataStream=deleteContent(dataStream,startIndex,endIndex),removeDataStream=dataStream.slice(startIndex,endIndex)),{dataStream:removeDataStream,textRuns:removeTextRuns,paragraphs:removeParagraphs,sectionBreaks:removeSectionBreaks,customBlocks:removeCustomBlocks,tables:removeTables,customRanges:removeCustomRanges,customDecorations:removeCustomDecorations}}__name(updateAttributeByDelete,"updateAttributeByDelete");function updateAttributeByInsert(body,insertBody,textLength,currentIndex){body.dataStream=insertTextToContent(body.dataStream,currentIndex,insertBody.dataStream),insertTextRuns(body,insertBody,textLength,currentIndex),insertParagraphs(body,insertBody,textLength,currentIndex),insertSectionBreaks(body,insertBody,textLength,currentIndex),insertCustomBlocks(body,insertBody,textLength,currentIndex),insertTables(body,insertBody,textLength,currentIndex),insertCustomRanges(body,insertBody,textLength,currentIndex),insertCustomDecorations(body,insertBody,textLength,currentIndex)}__name(updateAttributeByInsert,"updateAttributeByInsert");function updateApply(doc,updateBody,textLength,currentIndex,coverType=UpdateDocsAttributeType.COVER){return updateAttribute(doc,updateBody,textLength,currentIndex,coverType)}__name(updateApply,"updateApply");function deleteApply(doc,textLength,currentIndex){return textLength<=0?{dataStream:""}:updateAttributeByDelete(doc,textLength,currentIndex)}__name(deleteApply,"deleteApply");function insertApply(doc,insertBody,textLength,currentIndex){textLength!==0&&updateAttributeByInsert(doc,insertBody,textLength,currentIndex)}__name(insertApply,"insertApply");function textXApply(doc,actions){const memoryCursor=new MemoryCursor;return memoryCursor.reset(),actions.forEach(action=>{const clonedAction=Tools.deepClone(action);switch(clonedAction.t){case TextXActionType.RETAIN:{const{coverType,body,len}=clonedAction;body!=null&&updateApply(doc,body,len,memoryCursor.cursor,coverType),memoryCursor.moveCursor(len);break}case TextXActionType.INSERT:{const{body,len}=clonedAction;insertApply(doc,body,len,memoryCursor.cursor),memoryCursor.moveCursor(len);break}case TextXActionType.DELETE:{const{len}=clonedAction;deleteApply(doc,len,memoryCursor.cursor);break}default:throw new Error(`Unknown action type for action: ${clonedAction}.`)}}),doc}__name(textXApply,"textXApply");function transformTextRuns(originTextRuns,targetTextRuns,transformType){if(originTextRuns.length===0)return targetTextRuns;targetTextRuns=core.Tools.deepClone(targetTextRuns),originTextRuns=core.Tools.deepClone(originTextRuns);const newUpdateTextRuns=[],updateLength=targetTextRuns.length,removeLength=originTextRuns.length;let updateIndex=0,removeIndex=0,pending=null;function pushPendingAndReturnStatus(){return pending?(newUpdateTextRuns.push(pending),pending=null,!0):!1}for(__name(pushPendingAndReturnStatus,"pushPendingAndReturnStatus");updateIndex<updateLength&&removeIndex<removeLength;){const{st:updateSt,ed:updateEd,ts:targetStyle}=targetTextRuns[updateIndex],{st:removeSt,ed:removeEd,ts:originStyle,sId}=originTextRuns[removeIndex];let newTs={};if(transformType===0)newTs={...targetStyle};else if(newTs={...targetStyle},originStyle){const keys=Object.keys(originStyle);for(const key of keys)newTs[key]&&delete newTs[key]}if(updateEd<removeSt)pushPendingAndReturnStatus()||newUpdateTextRuns.push(targetTextRuns[updateIndex]),updateIndex++;else if(removeEd<updateSt)pushPendingAndReturnStatus()||newUpdateTextRuns.push(originTextRuns[removeIndex]),removeIndex++;else{const newTextRun={st:Math.min(updateSt,removeSt),ed:Math.max(updateSt,removeSt),ts:updateSt<removeSt?{...targetStyle}:{...originStyle},sId:updateSt<removeSt?void 0:sId};newTextRun.ed>newTextRun.st&&newUpdateTextRuns.push(),newUpdateTextRuns.push({st:Math.max(updateSt,removeSt),ed:Math.min(updateEd,removeEd),ts:newTs,sId}),updateEd<removeEd?(updateIndex++,originTextRuns[removeIndex].st=updateEd,originTextRuns[removeIndex].st===originTextRuns[removeIndex].ed&&removeIndex++):(removeIndex++,targetTextRuns[updateIndex].st=removeEd,targetTextRuns[updateIndex].st===targetTextRuns[updateIndex].ed&&updateIndex++);const pendingTextRun={st:Math.min(updateEd,removeEd),ed:Math.max(updateEd,removeEd),ts:updateEd<removeEd?{...originStyle}:{...targetStyle},sId:updateEd<removeEd?sId:void 0};pending=pendingTextRun.ed>pendingTextRun.st?pendingTextRun:null}}pushPendingAndReturnStatus();const tempTopTextRun=newUpdateTextRuns[newUpdateTextRuns.length-1],updateLastTextRun=targetTextRuns[updateLength-1],removeLastTextRun=originTextRuns[removeLength-1];return tempTopTextRun.ed!==Math.max(updateLastTextRun.ed,removeLastTextRun.ed)&&(updateLastTextRun.ed>removeLastTextRun.ed?newUpdateTextRuns.push(updateLastTextRun):newUpdateTextRuns.push(removeLastTextRun)),core.normalizeTextRuns(newUpdateTextRuns)}__name(transformTextRuns,"transformTextRuns");function transformParagraph(originParagraph,targetParagraph,transformType){const paragraph={startIndex:targetParagraph.startIndex};if(targetParagraph.paragraphStyle){if(originParagraph.paragraphStyle==null)paragraph.paragraphStyle={...targetParagraph.paragraphStyle};else if(paragraph.paragraphStyle={...targetParagraph.paragraphStyle},transformType===1){const keys=Object.keys(originParagraph.paragraphStyle);for(const key of keys)paragraph.paragraphStyle[key]&&delete paragraph.paragraphStyle[key]}}return targetParagraph.bullet&&(originParagraph.bullet==null||transformType===0)&&(paragraph.bullet={...targetParagraph.bullet}),paragraph}__name(transformParagraph,"transformParagraph");function transformBody(thisAction,otherAction,priority=!1){const{body:thisBody}=thisAction,{body:otherBody}=otherAction;if(thisBody==null||thisBody.dataStream!==""||otherBody==null||otherBody.dataStream!=="")throw new Error("Data stream is not supported in transform.");const retBody={dataStream:""},{textRuns:thisTextRuns=[],paragraphs:thisParagraphs=[]}=thisBody,{textRuns:otherTextRuns=[],paragraphs:otherParagraphs=[]}=otherBody;let textRuns=[];priority?textRuns=transformTextRuns(thisTextRuns,otherTextRuns,1):textRuns=transformTextRuns(thisTextRuns,otherTextRuns,0),textRuns.length&&(retBody.textRuns=textRuns);const paragraphs=[];let thisIndex=0,otherIndex=0;for(;thisIndex<thisParagraphs.length&&otherIndex<otherParagraphs.length;){const thisParagraph=thisParagraphs[thisIndex],otherParagraph=otherParagraphs[otherIndex],{startIndex:thisStart}=thisParagraph,{startIndex:otherStart}=otherParagraph;if(thisStart===otherStart){let paragraph={startIndex:thisStart};priority?paragraph=transformParagraph(thisParagraph,otherParagraph,1):paragraph=transformParagraph(thisParagraph,otherParagraph,0),paragraphs.push(paragraph),thisIndex++,otherIndex++}else thisStart<otherStart?thisIndex++:(paragraphs.push(core.Tools.deepClone(otherParagraph)),otherIndex++)}return otherIndex<otherParagraphs.length&&paragraphs.push(...otherParagraphs.slice(otherIndex)),paragraphs.length&&(retBody.paragraphs=paragraphs),retBody}__name(transformBody,"transformBody");function onlyHasDataStream(body){return Object.keys(body).length===1}__name(onlyHasDataStream,"onlyHasDataStream");const _TextX=class _TextX{constructor(){__publicField(this,"_actions",[])}static apply(doc,actions){return textXApply(doc,actions)}static compose(thisActions,otherActions){const thisIter=new ActionIterator(thisActions),otherIter=new ActionIterator(otherActions),textX=new _TextX;for(;thisIter.hasNext()||otherIter.hasNext();)if(otherIter.peekType()===TextXActionType.INSERT)textX.push(otherIter.next());else if(thisIter.peekType()===TextXActionType.DELETE)textX.push(thisIter.next());else{const length=Math.min(thisIter.peekLength(),otherIter.peekLength()),thisAction=thisIter.next(length),otherAction=otherIter.next(length);thisAction.t===TextXActionType.INSERT&&otherAction.t===TextXActionType.RETAIN?otherAction.body==null?textX.push(thisAction):textX.push({...thisAction,body:composeBody(thisAction.body,otherAction.body,otherAction.coverType)}):thisAction.t===TextXActionType.RETAIN&&otherAction.t===TextXActionType.RETAIN?thisAction.body==null&&otherAction.body==null?textX.push(thisAction.len!==Number.POSITIVE_INFINITY?thisAction:otherAction):thisAction.body&&otherAction.body?textX.push({...thisAction,body:composeBody(thisAction.body,otherAction.body,otherAction.coverType)}):textX.push(thisAction.body?thisAction:otherAction):thisAction.t===TextXActionType.RETAIN&&otherAction.t===TextXActionType.DELETE?textX.push(otherAction):thisAction.t===TextXActionType.INSERT&&(otherAction.t,TextXActionType.DELETE)}return textX.trimEndUselessRetainAction(),textX.serialize()}static transform(thisActions,otherActions,priority="right"){return this._transform(otherActions,thisActions,priority==="left"?"right":"left")}static _transform(thisActions,otherActions,priority="right"){var _a13;const thisIter=new ActionIterator(thisActions),otherIter=new ActionIterator(otherActions),textX=new _TextX;for(;thisIter.hasNext()||otherIter.hasNext();)if(thisIter.peekType()===TextXActionType.INSERT&&(priority==="left"||otherIter.peekType()!==TextXActionType.INSERT)){const thisAction=thisIter.next();textX.retain(thisAction.len,(_a13=thisAction.segmentId)!=null?_a13:"")}else if(otherIter.peekType()===TextXActionType.INSERT)textX.push(otherIter.next());else{const length=Math.min(thisIter.peekLength(),otherIter.peekLength()),thisAction=thisIter.next(length),otherAction=otherIter.next(length);if(thisAction.t===TextXActionType.DELETE)continue;if(otherAction.t===TextXActionType.DELETE){textX.push(otherAction);continue}thisAction.body==null||otherAction.body==null?textX.push(otherAction):textX.push({...otherAction,body:transformBody(thisAction,otherAction,priority==="left")})}return textX.trimEndUselessRetainAction(),textX.serialize()}static transformPosition(thisActions,index2,priority=!1){const thisIter=new ActionIterator(thisActions);let offset=0;for(;thisIter.hasNext()&&offset<=index2;){const length=thisIter.peekLength(),nextType=thisIter.peekType();if(thisIter.next(),nextType===TextXActionType.DELETE){index2-=Math.min(length,index2-offset);continue}else nextType===TextXActionType.INSERT&&(offset<index2||!priority)&&(index2+=length);offset+=length}return index2}static isNoop(actions){return actions.length===0}static invert(actions){const invertedActions=[];for(const action of actions)if(action.t===TextXActionType.INSERT)invertedActions.push({t:TextXActionType.DELETE,len:action.len,line:0,body:action.body,segmentId:action.segmentId});else if(action.t===TextXActionType.DELETE){if(action.body==null)throw new Error("Can not invert DELETE action without body property, makeInvertible must be called first.");invertedActions.push({t:TextXActionType.INSERT,body:action.body,len:action.len,line:0,segmentId:action.segmentId})}else if(action.body!=null){if(action.oldBody==null)throw new Error("Can not invert RETAIN action without oldBody property, makeInvertible must be called first.");invertedActions.push({t:TextXActionType.RETAIN,body:action.oldBody,oldBody:action.body,len:action.len,coverType:UpdateDocsAttributeType.REPLACE,segmentId:action.segmentId})}else invertedActions.push(action);return invertedActions}static makeInvertible(actions,doc){const invertibleActions=[];let index2=0;for(const action of actions){if(action.t===TextXActionType.DELETE&&action.body==null){const body=getBodySlice(doc,index2,index2+action.len,!1);action.len=body.dataStream.length,action.body=body}if(action.t===TextXActionType.RETAIN&&action.body!=null){const body=getBodySlice(doc,index2,index2+action.len,!0);action.oldBody={...body,dataStream:""},action.len=body.dataStream.length}invertibleActions.push(action),action.t!==TextXActionType.INSERT&&(index2+=action.len)}return invertibleActions}insert(len,body,segmentId=""){const insertAction={t:TextXActionType.INSERT,body,len,line:0,segmentId};return this.push(insertAction),this}retain(len,segmentId="",body,coverType){const retainAction={t:TextXActionType.RETAIN,len,segmentId};return body!=null&&(retainAction.body=body),coverType!=null&&(retainAction.coverType=coverType),this.push(retainAction),this}delete(len,segmentId=""){const deleteAction={t:TextXActionType.DELETE,len,line:0,segmentId};return this.push(deleteAction),this}empty(){return this._actions=[],this}serialize(){return this._actions}push(...args){if(args.length>1){for(const ac of args)this.push(ac);return this}let index2=this._actions.length,lastAction=this._actions[index2-1];const newAction=Tools.deepClone(args[0]);if(newAction.t===TextXActionType.RETAIN&&newAction.len===0&&newAction.body==null)return this;if(typeof lastAction=="object"){if(lastAction.t===TextXActionType.DELETE&&newAction.t===TextXActionType.DELETE)return lastAction.len+=newAction.len,this;if(lastAction.t===TextXActionType.DELETE&&newAction.t===TextXActionType.INSERT&&(index2-=1,lastAction=this._actions[index2-1],lastAction==null))return this._actions.unshift(newAction),this;if(lastAction.t===TextXActionType.RETAIN&&newAction.t===TextXActionType.RETAIN&&lastAction.body==null&&newAction.body==null)return lastAction.len+=newAction.len,this;if(lastAction.t===TextXActionType.INSERT&&onlyHasDataStream(lastAction.body)&&newAction.t===TextXActionType.INSERT&&onlyHasDataStream(newAction.body))return lastAction.len+=newAction.len,lastAction.body.dataStream+=newAction.body.dataStream,this}return index2===this._actions.length?this._actions.push(newAction):this._actions.splice(index2,0,newAction),this}trimEndUselessRetainAction(){let lastAction=this._actions[this._actions.length-1];for(;lastAction&&lastAction.t===TextXActionType.RETAIN&&isUselessRetainAction(lastAction);)this._actions.pop(),lastAction=this._actions[this._actions.length-1];return this}};__name(_TextX,"TextX"),__publicField(_TextX,"id","text-x"),__publicField(_TextX,"uri","https://github.com/dream-num/univer#text-x");let TextX=_TextX;Object.defineProperty(TextX,"name",{value:"text-x"});const _JSONX=class _JSONX{static registerSubtype(subType){var _a13;subType==null||this._subTypes.has(subType.name)&&((_a13=this._subTypes.get(subType.name))==null?void 0:_a13.id)!==TextX.id||(this._subTypes.set(subType.name,subType),dist$1.type.registerSubtype(subType))}static apply(doc,actions){if(!dist$1.type.isNoop(actions))return dist$1.type.apply(doc,actions)}static compose(thisActions,otherActions){return dist$1.type.compose(thisActions,otherActions)}static transform(thisActions,otherActions,priority){return dist$1.type.transform(thisActions,otherActions,priority)}static transformPosition(thisActions,index2,priority="right"){return thisActions&&thisActions.length===2&&thisActions[0]==="body"&&thisActions[1].et===TextX.name?TextX.transformPosition(thisActions[1].e,index2,priority==="left"):index2}static invertWithDoc(actions,doc){return dist$1.type.invertWithDoc(actions,doc)}static isNoop(actions){return dist$1.type.isNoop(actions)}static getInstance(){return this._instance==null&&(this._instance=new _JSONX),this._instance}removeOp(path,value){return dist$1.removeOp(path,value)}moveOp(from,to){return dist$1.moveOp(from,to)}insertOp(path,value){return dist$1.insertOp(path,value)}replaceOp(path,oldVal,newVal){return dist$1.replaceOp(path,oldVal,newVal)}editOp(subOp,path=["body"]){return dist$1.editOp(path,TextX.name,subOp)}};__name(_JSONX,"JSONX"),__publicField(_JSONX,"uri","https://github.com/dream-num/univer#json-x"),__publicField(_JSONX,"_subTypes",new Map),__publicField(_JSONX,"_instance",null);let JSONX=_JSONX;JSONX.registerSubtype(TextX);const DEFAULT_DOC={id:"default_doc",documentStyle:{}},_DocumentDataModelSimple=class _DocumentDataModelSimple extends UnitModel{constructor(snapshot){var _a13;super();__publicField(this,"type",I.UNIVER_DOC);__publicField(this,"_name$",new rxjs.BehaviorSubject(""));__publicField(this,"name$",this._name$.asObservable());__publicField(this,"snapshot");this.snapshot={...DEFAULT_DOC,...snapshot},this._name$.next((_a13=this.snapshot.title)!=null?_a13:"No Title")}getUnitId(){throw new Error("Method not implemented.")}setName(name){this.snapshot.title=name,this._name$.next(name)}get drawings(){return this.snapshot.drawings}get documentStyle(){return this.snapshot.documentStyle}get lists(){return this.snapshot.lists}get zoomRatio(){var _a13;return((_a13=this.snapshot.settings)==null?void 0:_a13.zoomRatio)||1}resetDrawing(drawings,drawingsOrder){this.snapshot.drawings=drawings,this.snapshot.drawingsOrder=drawingsOrder}getBody(){return this.snapshot.body}getSnapshot(){return this.snapshot}getBulletPresetList(){var _a13;const customLists=(_a13=this.snapshot.lists)!=null?_a13:{};return{...PRESET_LIST_TYPE,...customLists}}updateDocumentId(unitId){this.snapshot.id=unitId}updateDocumentRenderConfig(config){const{documentStyle}=this.snapshot;documentStyle.renderConfig==null?documentStyle.renderConfig=config:documentStyle.renderConfig={...documentStyle.renderConfig,...config}}updateDocumentStyle(config){this.snapshot.documentStyle==null?this.snapshot.documentStyle=config:this.snapshot.documentStyle={...this.snapshot.documentStyle,...config}}updateDocumentDataMargin(data){const{t,l,b,r}=data,{documentStyle}=this.snapshot;t!=null&&(documentStyle.marginTop=t),l!=null&&(documentStyle.marginLeft=l),b!=null&&(documentStyle.marginBottom=b),r!=null&&(documentStyle.marginRight=r)}updateDocumentDataPageSize(width,height){const{documentStyle}=this.snapshot;if(!documentStyle.pageSize){width=width!=null?width:Number.POSITIVE_INFINITY,height=height!=null?height:Number.POSITIVE_INFINITY,documentStyle.pageSize={width,height};return}width!==void 0&&(documentStyle.pageSize.width=width),height!==void 0&&(documentStyle.pageSize.height=height)}updateDrawing(id,config){const{drawings}=this,{width,height,left,top}=config,drawing=drawings==null?void 0:drawings[id];if(!drawing)return;const objectTransform=drawing.docTransform;objectTransform.size.width=width,objectTransform.size.height=height,objectTransform.positionH.posOffset=left,objectTransform.positionV.posOffset=top}setZoomRatio(zoomRatio=1){this.snapshot.settings==null?this.snapshot.settings={zoomRatio}:this.snapshot.settings.zoomRatio=1}};__name(_DocumentDataModelSimple,"DocumentDataModelSimple");let DocumentDataModelSimple=_DocumentDataModelSimple;const _DocumentDataModel=class _DocumentDataModel extends DocumentDataModelSimple{constructor(snapshot){var _a13,_b2;super(Tools.isEmptyObject(snapshot)?getEmptySnapshot$1():snapshot);__publicField(this,"_unitId");__publicField(this,"headerModelMap",new Map);__publicField(this,"footerModelMap",new Map);const UNIT_ID_LENGTH=6;this._unitId=(_a13=this.snapshot.id)!=null?_a13:Tools.generateRandomId(UNIT_ID_LENGTH),this._initializeHeaderFooterModel(),this._name$.next((_b2=this.snapshot.title)!=null?_b2:"")}dispose(){super.dispose(),this.headerModelMap.forEach(header=>{header.dispose()}),this.footerModelMap.forEach(footer=>{footer.dispose()}),this._name$.complete()}getDrawings(){return this.snapshot.drawings}getDrawingsOrder(){return this.snapshot.drawingsOrder}getCustomRanges(){var _a13;return(_a13=this.snapshot.body)==null?void 0:_a13.customRanges}getCustomDecorations(){var _a13;return(_a13=this.snapshot.body)==null?void 0:_a13.customDecorations}getRev(){var _a13;return(_a13=this.snapshot.rev)!=null?_a13:1}incrementRev(){this.snapshot.rev=this.getRev()+1}getSettings(){return this.snapshot.settings}reset(snapshot){if(snapshot.id&&snapshot.id!==this._unitId)throw new Error("Cannot reset a document model with a different unit id!");this.snapshot={...DEFAULT_DOC,...snapshot},this._initializeHeaderFooterModel()}getSelfOrHeaderFooterModel(segmentId){if(segmentId!=null){if(this.headerModelMap.has(segmentId))return this.headerModelMap.get(segmentId);if(this.footerModelMap.has(segmentId))return this.footerModelMap.get(segmentId)}return this}getUnitId(){return this._unitId}apply(actions){if(!JSONX.isNoop(actions))return this.snapshot=JSONX.apply(this.snapshot,actions),actions!=null&&actions.some(a=>Array.isArray(a)&&((a==null?void 0:a[0])==="headers"||(a==null?void 0:a[0])==="footers"))&&(this.headerModelMap.clear(),this.footerModelMap.clear(),this._initializeHeaderFooterModel()),this.snapshot}sliceBody(startOffset,endOffset,type2=SliceBodyType.copy){const body=this.getBody();if(body!=null)return getBodySlice(body,startOffset,endOffset,!1,type2)}_initializeHeaderFooterModel(){const{headers,footers}=this.getSnapshot();if(headers)for(const headerId in headers){const header=headers[headerId];this.headerModelMap.set(headerId,new _DocumentDataModel(header)),this.headerModelMap.get(headerId).updateDocumentId(this.getUnitId())}if(footers)for(const footerId in footers){const footer=footers[footerId];this.footerModelMap.set(footerId,new _DocumentDataModel(footer)),this.footerModelMap.get(footerId).updateDocumentId(this.getUnitId())}}updateDocumentId(unitId){super.updateDocumentId(unitId),this._unitId=unitId}};__name(_DocumentDataModel,"DocumentDataModel");let DocumentDataModel=_DocumentDataModel;const IConfigService=createIdentifier("univer.config-service"),_ConfigService=class _ConfigService{constructor(){__publicField(this,"_config",new Map)}getConfig(id){return this._config.get(id)}setConfig(id,value){this._config.set(id,value)}deleteConfig(id){this._config.delete(id)}};__name(_ConfigService,"ConfigService");let ConfigService=_ConfigService;const _ErrorService=class _ErrorService extends Disposable{constructor(){super(...arguments);__publicField(this,"_error$",new rxjs.Subject);__publicField(this,"error$",this._error$.asObservable())}dispose(){this._error$.complete()}emit(key){this._error$.next({errorKey:key})}};__name(_ErrorService,"ErrorService");let ErrorService=_ErrorService;const _Styles=class _Styles{constructor(styles={}){__publicField(this,"_styles");__publicField(this,"_cacheMap",new LRUMap(1e5));this._styles=styles,this._generateCacheMap()}each(callback){return Object.entries(this._styles).forEach(callback),this}search(data,styleObject){if(this._cacheMap.has(styleObject))return this._cacheMap.get(styleObject);const existingId=this._getExistingStyleId(data);return existingId||"-1"}get(id){return typeof id!="string"?id:(id=String(id),this._styles[id])}add(data,styleObject){const id=Tools.generateRandomId(6);return this._styles[id]=data,this._cacheMap.set(styleObject,id),id}setValue(data){if(data==null)return;const styleObject=JSON.stringify(data),result=this.search(data,styleObject);return result!=="-1"?result:this.add(data,styleObject)}toJSON(){return this._styles}getStyleByCell(cell){let style;cell&&Tools.isObject(cell.s)?style=cell.s:style=(cell==null?void 0:cell.s)&&this.get(cell.s);const interceptStyle=cell==null?void 0:cell.interceptorStyle;return interceptStyle?{...style,...interceptStyle}:style}_generateCacheMap(){const{_styles,_cacheMap}=this;for(const id in _styles){const styleObject=JSON.stringify(_styles[id]);_cacheMap.set(styleObject,id)}}_getExistingStyleId(data){const{_styles}=this;for(const id in _styles)if(Tools.diffValue(_styles[id],data))return id;return null}};__name(_Styles,"Styles");let Styles=_Styles;const _ColumnManager=class _ColumnManager{constructor(_config,data){__publicField(this,"_columnData",{});this._config=_config,this._columnData=data}getColumnData(){return this._columnData}getColVisible(colPos){const{_columnData}=this,col=_columnData[colPos];return col?col.hd!==BooleanNumber.TRUE:!0}getHiddenCols(start=0,end=this.getSize()-1){const hiddenCols=[];let inHiddenRange=!1,startColumn=-1;for(let i=start;i<=end;i++){const visible=this.getColVisible(i);inHiddenRange&&visible?(inHiddenRange=!1,hiddenCols.push({rangeType:RANGE_TYPE.COLUMN,startColumn,endColumn:i-1,startRow:0,endRow:0})):!inHiddenRange&&!visible&&(inHiddenRange=!0,startColumn=i)}return inHiddenRange&&hiddenCols.push({startRow:0,endRow:0,startColumn,endColumn:end,rangeType:RANGE_TYPE.COLUMN}),hiddenCols}getVisibleCols(start=0,end=this.getSize()-1){const visibleCols=[];let inVisibleRange=!1,startColumn=-1;for(let i=start;i<=end;i++){const visible=this.getColVisible(i);inVisibleRange&&!visible?(inVisibleRange=!1,visibleCols.push({rangeType:RANGE_TYPE.COLUMN,startColumn,endColumn:i-1,startRow:0,endRow:0})):!inVisibleRange&&visible&&(inVisibleRange=!0,startColumn=i)}return inVisibleRange&&visibleCols.push({startRow:0,endRow:0,startColumn,endColumn:end,rangeType:RANGE_TYPE.COLUMN}),visibleCols}getColumnDatas(columnPos,numColumns){const columnData={};let index2=0;for(let i=columnPos;i<columnPos+numColumns;i++){const data=this.getColumnOrCreate(i);columnData[index2]=data,index2++}return columnData}getSize(){return getArrayLength(this._columnData)}getColumnWidth(columnPos){const{_columnData}=this,config=this._config;let width=0;return width=(_columnData[columnPos]||{hd:BooleanNumber.FALSE,w:config.defaultColumnWidth}).w||config.defaultColumnWidth,width}getColumn(columnPos){const column=this._columnData[columnPos];if(column)return column}getColumnOrCreate(columnPos){const{_columnData}=this,config=this._config,column=_columnData[columnPos];if(column)return column;const create={w:config.defaultColumnWidth,hd:BooleanNumber.FALSE};return this._columnData[columnPos]=create,create}};__name(_ColumnManager,"ColumnManager");let ColumnManager=_ColumnManager;const _RowManager=class _RowManager{constructor(_config,_viewModel,data){__publicField(this,"_rowData");this._config=_config,this._viewModel=_viewModel,this._rowData=data}getRowData(){return this._rowData}getRowDatas(rowPos,numRows){const rowData={};let index2=0;for(let i=rowPos;i<rowPos+numRows;i++){const data=this.getRowOrCreate(i);rowData[index2]=data,index2++}return rowData}getRowHeight(rowPos,count=1){const{_rowData}=this,config=this._config;let height=0;for(let i=0;i<count;i++){const row=_rowData[i+rowPos]||{hd:BooleanNumber.FALSE,h:config.defaultRowHeight},{ia,ah,h=config.defaultRowHeight}=row;height+=(ia==null||ia===BooleanNumber.TRUE)&&typeof ah=="number"?ah:h}return height}getRow(rowPos){return this._rowData[rowPos]}getRowOrCreate(rowPos){const{_rowData}=this,row=_rowData[rowPos];if(row)return row;const config=this._config,create={hd:BooleanNumber.FALSE,h:config.defaultRowHeight};return _rowData[rowPos]=create,create}getHiddenRows(start=0,end=this.getSize()-1){const hiddenRows=[];let inHiddenRange=!1,startRow=-1;for(let i=start;i<=end;i++){const visible=this.getRowRawVisible(i);inHiddenRange&&visible?(inHiddenRange=!1,hiddenRows.push({startRow,endRow:i-1,startColumn:0,endColumn:0,rangeType:RANGE_TYPE.ROW})):!inHiddenRange&&!visible&&(inHiddenRange=!0,startRow=i)}return inHiddenRange&&hiddenRows.push({startRow,endRow:end,startColumn:0,endColumn:0,rangeType:RANGE_TYPE.ROW}),hiddenRows}getVisibleRows(start=0,end=this.getSize()-1){const visibleRows=[];let inVisibleRange=!1,startRow=-1;for(let i=start;i<=end;i++){const visible=this.getRowRawVisible(i);inVisibleRange&&!visible?(inVisibleRange=!1,visibleRows.push({startRow,endRow:i-1,startColumn:0,endColumn:0,rangeType:RANGE_TYPE.ROW})):!inVisibleRange&&visible&&(inVisibleRange=!0,startRow=i)}return inVisibleRange&&visibleRows.push({startRow,endRow:end,startColumn:0,endColumn:0,rangeType:RANGE_TYPE.ROW}),visibleRows}getRowRawVisible(row){const rowData=this.getRow(row);return rowData?rowData.hd!==BooleanNumber.TRUE:!0}getSize(){return getArrayLength(this._rowData)}};__name(_RowManager,"RowManager");let RowManager=_RowManager;const DEFAULT_WORKSHEET_ROW_COUNT_KEY="DEFAULT_WORKSHEET_ROW_COUNT",DEFAULT_WORKSHEET_ROW_COUNT=1e3,DEFAULT_WORKSHEET_COLUMN_COUNT_KEY="DEFAULT_WORKSHEET_COLUMN_COUNT",DEFAULT_WORKSHEET_COLUMN_COUNT=20,DEFAULT_WORKSHEET_ROW_HEIGHT_KEY="DEFAULT_WORKSHEET_ROW_HEIGHT",DEFAULT_WORKSHEET_ROW_HEIGHT=24,DEFAULT_WORKSHEET_COLUMN_WIDTH_KEY="DEFAULT_WORKSHEET_COLUMN_WIDTH",DEFAULT_WORKSHEET_COLUMN_WIDTH=88,DEFAULT_WORKSHEET_ROW_TITLE_WIDTH_KEY="DEFAULT_WORKSHEET_ROW_TITLE_WIDTH",DEFAULT_WORKSHEET_ROW_TITLE_WIDTH=46,DEFAULT_WORKSHEET_COLUMN_TITLE_HEIGHT_KEY="DEFAULT_WORKSHEET_COLUMN_TITLE_HEIGHT",DEFAULT_WORKSHEET_COLUMN_TITLE_HEIGHT=20;function mergeWorksheetSnapshotWithDefault(snapshot){const defaultSnapshot={name:"Sheet1",id:"sheet-01",tabColor:"",hidden:BooleanNumber.FALSE,rowCount:DEFAULT_WORKSHEET_ROW_COUNT,columnCount:DEFAULT_WORKSHEET_COLUMN_COUNT,zoomRatio:1,freeze:{xSplit:0,ySplit:0,startRow:-1,startColumn:-1},scrollTop:0,scrollLeft:0,defaultColumnWidth:DEFAULT_WORKSHEET_COLUMN_WIDTH,defaultRowHeight:DEFAULT_WORKSHEET_ROW_HEIGHT,mergeData:[],cellData:{},rowData:{},columnData:{},showGridlines:BooleanNumber.TRUE,rowHeader:{width:DEFAULT_WORKSHEET_ROW_TITLE_WIDTH,hidden:BooleanNumber.FALSE},columnHeader:{height:DEFAULT_WORKSHEET_COLUMN_TITLE_HEIGHT,hidden:BooleanNumber.FALSE},rightToLeft:BooleanNumber.FALSE};return Object.keys(defaultSnapshot).forEach(_key=>{const key=_key;typeof snapshot[key]>"u"&&(snapshot[key]=defaultSnapshot[key])}),snapshot}__name(mergeWorksheetSnapshotWithDefault,"mergeWorksheetSnapshotWithDefault");const _SheetViewModel=class _SheetViewModel extends Disposable{constructor(getRawCell){super();__publicField(this,"_cellContentInterceptor",null);__publicField(this,"_rowFilteredInterceptor",null);this.getRawCell=getRawCell}dispose(){super.dispose(),this._cellContentInterceptor=null,this._rowFilteredInterceptor=null}getCell(row,col){return this._cellContentInterceptor?this._cellContentInterceptor.getCell(row,col):this.getRawCell(row,col)}getRowFiltered(row){var _a13,_b2;return(_b2=(_a13=this._rowFilteredInterceptor)==null?void 0:_a13.getRowFiltered(row))!=null?_b2:!1}registerCellContentInterceptor(interceptor){if(this._cellContentInterceptor)throw new Error("[SheetViewModel]: Interceptor already registered.");return this._cellContentInterceptor=interceptor,toDisposable(()=>this._cellContentInterceptor=null)}registerRowFilteredInterceptor(interceptor){if(this._rowFilteredInterceptor)throw new Error("[SheetViewModel]: Interceptor already registered.");return this._rowFilteredInterceptor=interceptor,toDisposable(()=>this._rowFilteredInterceptor=null)}};__name(_SheetViewModel,"SheetViewModel");let SheetViewModel=_SheetViewModel;const _Worksheet=class _Worksheet{constructor(unitId,snapshot,_styles){__publicField(this,"_sheetId");__publicField(this,"_snapshot");__publicField(this,"_cellData");__publicField(this,"_rowManager");__publicField(this,"_columnManager");__publicField(this,"_viewModel");var _a13;this.unitId=unitId,this._styles=_styles,this._snapshot=mergeWorksheetSnapshotWithDefault(snapshot);const{columnData,rowData,cellData}=this._snapshot;this._sheetId=(_a13=this._snapshot.id)!=null?_a13:Tools.generateRandomId(6),this._cellData=new ObjectMatrix(cellData),this._viewModel=new SheetViewModel((row,col)=>this.getCellRaw(row,col)),this._rowManager=new RowManager(this._snapshot,this._viewModel,rowData),this._columnManager=new ColumnManager(this._snapshot,columnData)}__interceptViewModel(callback){callback(this._viewModel)}getSnapshot(){return this._snapshot}getCellMatrix(){return this._cellData}getCellMatrixPrintRange(){const matrix=this.getCellMatrix(),mergedCells=this.getMergeData();let startRow=-1,endRow=-1,startColumn=-1,endColumn=-1,rowInitd=!1,columnInitd=!1;return matrix.forEach((rowIndex,row)=>{Object.keys(row).forEach(colIndexStr=>{const colIndex=+colIndexStr,cellValue=matrix.getValue(rowIndex,colIndex),style=cellValue!=null&&cellValue.s?this._styles.get(cellValue.s):null,isLegalBorder=(style==null?void 0:style.bd)&&(style.bd.b||style.bd.l||style.bd.r||style.bd.t||style.bd.bc_tr||style.bd.bl_tr||style.bd.ml_tr||style.bd.tl_bc||style.bd.tl_br||style.bd.tl_mr);(cellValue&&(cellValue.v||cellValue.p)||style!=null&&style.bg||isLegalBorder)&&(rowInitd?startRow=Math.min(startRow,rowIndex):(startRow=rowIndex,rowInitd=!0),endRow=Math.max(endRow,rowIndex),columnInitd?startColumn=Math.min(startColumn,colIndex):(columnInitd=!0,startColumn=colIndex),endColumn=Math.max(endColumn,colIndex))})}),mergedCells.forEach(mergedCell=>{rowInitd?startRow=Math.min(startRow,mergedCell.startRow):(startRow=mergedCell.startRow,rowInitd=!0),endRow=Math.max(endRow,mergedCell.endRow),columnInitd?startColumn=Math.min(startColumn,mergedCell.startColumn):(startColumn=mergedCell.startColumn,rowInitd=!0),endColumn=Math.max(endColumn,mergedCell.endColumn)}),!rowInitd||!columnInitd?null:{startColumn,startRow,endColumn,endRow}}getRowManager(){return this._rowManager}getUnitId(){return this.unitId}getSheetId(){return this._sheetId}getColumnManager(){return this._columnManager}getName(){return this._snapshot.name}clone(){const{_snapshot:_config}=this,copy=Tools.deepClone(_config);return new _Worksheet(this.unitId,copy,this._styles)}getMergeData(){return this._snapshot.mergeData}getMergedCell(row,col){const rectangleList=this._snapshot.mergeData;for(let i=0;i<rectangleList.length;i++){const range=rectangleList[i];if(Rectangle.intersects({startRow:row,startColumn:col,endRow:row,endColumn:col},range))return range}return null}getCell(row,col){return row<0||col<0?null:this._viewModel.getCell(row,col)}getCellRaw(row,col){return this.getCellMatrix().getValue(row,col)}getRowFiltered(row){return this._viewModel.getRowFiltered(row)}getMatrixWithMergedCells(row,col,endRow,endCol,isRaw=!1){const matrix=this.getCellMatrix(),mergedCellsInRange=this._snapshot.mergeData.filter(rect=>Rectangle.intersects({startRow:row,startColumn:col,endRow,endColumn:endCol},rect)),returnCellMatrix=new ObjectMatrix;return createRowColIter(row,endRow,col,endCol).forEach((row2,col2)=>{const v=isRaw?this.getCellRaw(row2,col2):this.getCell(row2,col2);v&&returnCellMatrix.setValue(row2,col2,v)}),mergedCellsInRange.forEach(mergedCell=>{const{startColumn,startRow,endColumn,endRow:endRow2}=mergedCell;createRowColIter(startRow,endRow2,startColumn,endColumn).forEach((row2,col2)=>{row2===startRow&&col2===startColumn&&returnCellMatrix.setValue(row2,col2,{...matrix.getValue(row2,col2),rowSpan:endRow2-startRow+1,colSpan:endColumn-startColumn+1}),(row2!==startRow||col2!==startColumn)&&returnCellMatrix.realDeleteValue(row2,col2)})}),returnCellMatrix}getRange(startRowOrRange,startColumn,endRow,endColumn){return typeof startRowOrRange=="object"?new Range(this,startRowOrRange,{getStyles:__name(()=>this._styles,"getStyles")}):new Range(this,{startRow:startRowOrRange,startColumn,endColumn:endColumn||startColumn,endRow:endRow||startRowOrRange},{getStyles:__name(()=>this._styles,"getStyles")})}getScrollLeftTopFromSnapshot(){return{scrollLeft:this._snapshot.scrollLeft,scrollTop:this._snapshot.scrollTop}}getZoomRatio(){return this._snapshot.zoomRatio||1}getConfig(){return this._snapshot}getFreeze(){return this._snapshot.freeze}getMaxColumns(){const{_snapshot:_config}=this,{columnCount}=_config;return columnCount}getMaxRows(){const{_snapshot:_config}=this,{rowCount}=_config;return rowCount}getRowCount(){return this._snapshot.rowCount}setRowCount(count){this._snapshot.rowCount=count}getColumnCount(){return this._snapshot.columnCount}setColumnCount(count){this._snapshot.columnCount=count}isSheetHidden(){return this._snapshot.hidden}hasHiddenGridlines(){const{_snapshot:_config}=this,{showGridlines}=_config;return showGridlines===0}getTabColor(){const{_snapshot:_config}=this,{tabColor}=_config;return tabColor}getColumnWidth(columnPosition){return this.getColumnManager().getColumnWidth(columnPosition)}getRowHeight(row){return this._viewModel.getRowFiltered(row)?0:this.getRowManager().getRowHeight(row)}getRowVisible(row){return this._viewModel.getRowFiltered(row)?!1:this.getRowRawVisible(row)}getRowRawVisible(row){return this.getRowManager().getRowRawVisible(row)}getHiddenRows(start,end){const lastColumn=this.getMaxColumns()-1,ranges=this._rowManager.getHiddenRows(start,end);return ranges.forEach(range=>range.endColumn=lastColumn),ranges}getColVisible(col){return this._columnManager.getColVisible(col)}getHiddenCols(start,end){const lastRow=this.getMaxRows()-1,ranges=this._columnManager.getHiddenCols(start,end);return ranges.forEach(range=>range.endRow=lastRow),ranges}getVisibleRows(){const rowCount=this.getRowCount();return this._rowManager.getVisibleRows(0,rowCount-1)}getVisibleCols(){const columnCount=this.getColumnCount();return this._columnManager.getVisibleCols(0,columnCount-1)}isRightToLeft(){const{_snapshot:_config}=this,{rightToLeft}=_config;return rightToLeft}getLastRowWithContent(){return this._cellData.getLength()-1}getLastColumnWithContent(){return this._cellData.getRange().endColumn}cellHasValue(value){return value&&(value.v!==void 0||value.f!==void 0||value.p!==void 0)}iterateByRow(range,skipEmpty=!0){const{startRow,startColumn,endRow,endColumn}=range,worksheet=this;return{[Symbol.iterator]:()=>{let rowIndex=startRow,columnIndex=startColumn;return{next(){for(;;){if(columnIndex>endColumn&&(rowIndex+=1,columnIndex=startColumn),rowIndex>endRow)return{done:!0,value:void 0};const cellValue=worksheet.getCell(rowIndex,columnIndex),isEmptyCell2=!cellValue,mergedCell=worksheet.getMergedCell(rowIndex,columnIndex);if(mergedCell){if(rowIndex!==mergedCell.startRow||columnIndex!==mergedCell.startColumn){columnIndex=mergedCell.endColumn+1;continue}if(isEmptyCell2&&skipEmpty){columnIndex=mergedCell.endColumn+1;continue}const value={row:rowIndex,col:columnIndex,value:cellValue};return value.colSpan=mergedCell.endColumn-mergedCell.startColumn+1,value.rowSpan=mergedCell.endRow-mergedCell.startRow+1,columnIndex=mergedCell.endColumn+1,{done:!1,value}}if(isEmptyCell2&&skipEmpty)columnIndex+=1;else{const value={row:rowIndex,col:columnIndex,value:cellValue};return columnIndex+=1,{done:!1,value}}}}}}}}iterateByColumn(range,skipEmpty=!0,skipNonTopLeft=!0){const{startRow,startColumn,endRow,endColumn}=range,worksheet=this;return{[Symbol.iterator]:()=>{let rowIndex=startRow,columnIndex=startColumn;return{next(){for(;;){if(rowIndex>endRow&&(columnIndex+=1,rowIndex=startRow),columnIndex>endColumn)return{done:!0,value:void 0};const mergedCell=worksheet.getMergedCell(rowIndex,columnIndex);if(mergedCell){const isNotTop=rowIndex!==mergedCell.startRow,isNotTopLeft=isNotTop||columnIndex!==mergedCell.startColumn;if(skipNonTopLeft&&isNotTopLeft||!skipNonTopLeft&&isNotTop){rowIndex=mergedCell.endRow+1;continue}const cellValue2=worksheet.getCell(mergedCell.startRow,mergedCell.startColumn);if(!cellValue2&&skipEmpty){rowIndex=mergedCell.endRow+1;continue}const value={row:rowIndex,col:mergedCell.startColumn,value:cellValue2};return value.colSpan=mergedCell.endColumn-mergedCell.startColumn+1,value.rowSpan=mergedCell.endRow-mergedCell.startRow+1,rowIndex=mergedCell.endRow+1,{done:!1,value}}const cellValue=worksheet.getCell(rowIndex,columnIndex);if(!cellValue&&skipEmpty)rowIndex+=1;else{const value={row:rowIndex,col:columnIndex,value:cellValue};return rowIndex+=1,{done:!1,value}}}}}}}}};__name(_Worksheet,"Worksheet");let Worksheet=_Worksheet;function extractPureTextFromCell(cell){var _a13,_b2;if(!cell)return"";const richTextValue=(_b2=(_a13=cell.p)==null?void 0:_a13.body)==null?void 0:_b2.dataStream;if(richTextValue)return richTextValue;const rawValue=cell.v;return typeof rawValue=="string"?cell.t===CellValueType.BOOLEAN?rawValue.toUpperCase():rawValue.replace(/[\r\n]/g,""):typeof rawValue=="number"?cell.t===CellValueType.BOOLEAN?rawValue?"TRUE":"FALSE":rawValue.toString():typeof rawValue=="boolean"?rawValue?"TRUE":"FALSE":""}__name(extractPureTextFromCell,"extractPureTextFromCell");const version="0.2.10";function getEmptySnapshot(unitID="",locale=LocaleType.ZH_CN,name=""){return{id:unitID,sheetOrder:[],name,appVersion:version,locale,styles:{},sheets:{},resources:[]}}__name(getEmptySnapshot,"getEmptySnapshot");var __defProp$7=Object.defineProperty,__getOwnPropDesc$7=Object.getOwnPropertyDescriptor,__decorateClass$7=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$7(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$7(target,key,result),result},"__decorateClass$7"),__decorateParam$6=__name((index2,decorator)=>(target,key)=>decorator(target,key,index2),"__decorateParam$6");function getWorksheetUID(workbook,worksheet){return`${workbook.getUnitId()}|${worksheet.getSheetId()}`}__name(getWorksheetUID,"getWorksheetUID");var _a3;exports.Workbook=(_a3=class extends UnitModel{constructor(workbookData={},_logService){super();__publicField(this,"type",I.UNIVER_SHEET);__publicField(this,"_sheetCreated$",new rxjs.Subject);__publicField(this,"sheetCreated$",this._sheetCreated$.asObservable());__publicField(this,"_sheetDisposed$",new rxjs.Subject);__publicField(this,"sheetDisposed$",this._sheetDisposed$.asObservable());__publicField(this,"_activeSheet$",new rxjs.BehaviorSubject(null));__publicField(this,"activeSheet$",this._activeSheet$.asObservable());__publicField(this,"_worksheets");__publicField(this,"_styles");__publicField(this,"_snapshot");__publicField(this,"_unitId");__publicField(this,"_count");__publicField(this,"_name$");__publicField(this,"name$");this._logService=_logService;const DEFAULT_WORKBOOK=getEmptySnapshot();Tools.isEmptyObject(workbookData)?this._snapshot=DEFAULT_WORKBOOK:this._snapshot=Tools.commonExtend(DEFAULT_WORKBOOK,workbookData);const{styles}=this._snapshot;(this._snapshot.id==null||this._snapshot.id.length===0)&&(this._snapshot.id=Tools.generateRandomId(6)),this._unitId=this._snapshot.id,this._styles=new Styles(styles),this._count=1,this._worksheets=new Map,this._name$=new rxjs.BehaviorSubject(workbookData.name||""),this.name$=this._name$.asObservable(),this._parseWorksheetSnapshots()}get _activeSheet(){return this._activeSheet$.getValue()}get name(){return this._name$.getValue()}static isIRangeType(range){return typeof range=="string"||"startRow"in range||"row"in range}dispose(){super.dispose(),this._sheetCreated$.complete(),this._sheetDisposed$.complete(),this._activeSheet$.complete(),this._name$.complete()}save(){return Tools.deepClone(this._snapshot)}getSnapshot(){return this._snapshot}getName(){return this._snapshot.name}setName(name){this._name$.next(name),this._snapshot.name=name}getUnitId(){return this._unitId}getRev(){var _a13;return(_a13=this._snapshot.rev)!=null?_a13:1}incrementRev(){this._snapshot.rev=this.getRev()+1}addWorksheet(id,index2,worksheetSnapshot){const{sheets,sheetOrder}=this._snapshot;if(sheets[id])return!1;sheets[id]=worksheetSnapshot,sheetOrder.splice(index2,0,id);const worksheet=new Worksheet(this._unitId,worksheetSnapshot,this._styles);return this._worksheets.set(id,worksheet),this._sheetCreated$.next(worksheet),!0}getSheetOrders(){return this._snapshot.sheetOrder}getWorksheets(){return this._worksheets}getActiveSpreadsheet(){return this}getStyles(){return this._styles}getConfig(){return this._snapshot}getIndexBySheetId(sheetId){const{sheetOrder}=this._snapshot;return sheetOrder.findIndex(id=>id===sheetId)}getActiveSheet(allowNull){if(!this._activeSheet&&typeof allowNull>"u")throw new Error(`[Workbook]: no active Worksheet on Workbook ${this._unitId}!`);return this._activeSheet}ensureActiveSheet(){const currentActive=this._activeSheet;if(currentActive)return currentActive;const sheetOrder=this._snapshot.sheetOrder;for(let i=0,len=sheetOrder.length;i<len;i++){const worksheet2=this._worksheets.get(sheetOrder[i]);if(worksheet2&&worksheet2.isSheetHidden()!==BooleanNumber.TRUE)return this.setActiveSheet(worksheet2),worksheet2}const worksheet=this._worksheets.get(sheetOrder[0]);return this.setActiveSheet(worksheet),worksheet}setActiveSheet(worksheet){this._activeSheet$.next(worksheet)}removeSheet(sheetId){const sheetToRemove=this._worksheets.get(sheetId);return sheetToRemove?(this._worksheets.delete(sheetId),this._snapshot.sheetOrder.splice(this._snapshot.sheetOrder.indexOf(sheetId),1),delete this._snapshot.sheets[sheetId],this._sheetDisposed$.next(sheetToRemove),!0):!1}getActiveSheetIndex(){const{sheetOrder}=this._snapshot;return sheetOrder.findIndex(sheetId=>this._worksheets.get(sheetId)===this._activeSheet)}getSheetSize(){return this._snapshot.sheetOrder.length}getSheets(){const{sheetOrder}=this._snapshot;return sheetOrder.map(sheetId=>this._worksheets.get(sheetId))}getSheetsName(){const{sheetOrder}=this._snapshot,names=[];return sheetOrder.forEach(sheetId=>{const worksheet=this._worksheets.get(sheetId);worksheet&&names.push(worksheet.getName())}),names}getSheetIndex(sheet){const{sheetOrder}=this._snapshot;return sheetOrder.findIndex(sheetId=>sheet.getSheetId()===sheetId)}getSheetBySheetName(name){const{sheetOrder}=this._snapshot,sheetId=sheetOrder.find(sheetId2=>this._worksheets.get(sheetId2).getName()===name);return this._worksheets.get(sheetId)}getSheetBySheetId(sheetId){return this._worksheets.get(sheetId)}getSheetByIndex(index2){const{sheetOrder}=this._snapshot;return this._worksheets.get(sheetOrder[index2])}getHiddenWorksheets(){return this.getSheets().filter(s=>s.getConfig().hidden===BooleanNumber.TRUE).map(s=>s.getConfig().id)}getUnhiddenWorksheets(){return this.getSheets().filter(s=>s.getConfig().hidden!==BooleanNumber.TRUE).map(s=>s.getConfig().id)}load(config){this._snapshot=config}checkSheetName(name){return this.getSheetsName().includes(name)}uniqueSheetName(name="Sheet1"){let output=name;for(;this.checkSheetName(output);)output=name+this._count,this._count++;return output}generateNewSheetName(name){let output=name+this._count;for(;this.checkSheetName(output);)output=name+this._count,this._count++;return output}_parseWorksheetSnapshots(){const{_snapshot,_worksheets}=this,{sheets,sheetOrder}=_snapshot;if(Tools.isEmptyObject(sheets)){const firstSheetId=Tools.generateRandomId();sheets[firstSheetId]={id:firstSheetId}}for(const sheetId in sheets){const worksheetSnapshot=sheets[sheetId],{name}=worksheetSnapshot;worksheetSnapshot.name=this.uniqueSheetName(name),worksheetSnapshot.name!==name&&this._logService.debug("[Workbook]",`The worksheet name ${name} is duplicated, we changed it to ${worksheetSnapshot.name}. Please fix the problem in your snapshot.`);const worksheet=new Worksheet(this._unitId,worksheetSnapshot,this._styles);_worksheets.set(sheetId,worksheet),sheetOrder.includes(sheetId)||sheetOrder.push(sheetId)}this.ensureActiveSheet()}},__name(_a3,"Workbook"),_a3);exports.Workbook=__decorateClass$7([__decorateParam$6(1,ILogService)],exports.Workbook);var PageType=(PageType2=>(PageType2[PageType2.SLIDE=0]="SLIDE",PageType2[PageType2.MASTER=1]="MASTER",PageType2[PageType2.LAYOUT=2]="LAYOUT",PageType2[PageType2.HANDOUT_MASTER=3]="HANDOUT_MASTER",PageType2[PageType2.NOTES_MASTER=4]="NOTES_MASTER",PageType2))(PageType||{}),PageElementType=(PageElementType2=>(PageElementType2[PageElementType2.SHAPE=0]="SHAPE",PageElementType2[PageElementType2.IMAGE=1]="IMAGE",PageElementType2[PageElementType2.TEXT=2]="TEXT",PageElementType2[PageElementType2.SPREADSHEET=3]="SPREADSHEET",PageElementType2[PageElementType2.DOCUMENT=4]="DOCUMENT",PageElementType2[PageElementType2.SLIDE=5]="SLIDE",PageElementType2))(PageElementType||{}),RelativeSlideLink=(RelativeSlideLink2=>(RelativeSlideLink2[RelativeSlideLink2.RELATIVE_SLIDE_LINK_UNSPECIFIED=0]="RELATIVE_SLIDE_LINK_UNSPECIFIED",RelativeSlideLink2[RelativeSlideLink2.NEXT_SLIDE=1]="NEXT_SLIDE",RelativeSlideLink2[RelativeSlideLink2.PREVIOUS_SLIDE=2]="PREVIOUS_SLIDE",RelativeSlideLink2[RelativeSlideLink2.FIRST_SLIDE=3]="FIRST_SLIDE",RelativeSlideLink2[RelativeSlideLink2.LAST_SLIDE=4]="LAST_SLIDE",RelativeSlideLink2))(RelativeSlideLink||{});const _SlideDataModel=class _SlideDataModel extends UnitModel{constructor(snapshot){var _a13;super();__publicField(this,"type",I.UNIVER_SLIDE);__publicField(this,"_activePage$",new rxjs.BehaviorSubject(null));__publicField(this,"activePage$",this._activePage$.asObservable());__publicField(this,"_name$");__publicField(this,"name$");__publicField(this,"_snapshot");__publicField(this,"_unitId");this._snapshot={...DEFAULT_SLIDE,...snapshot},this._unitId=(_a13=this._snapshot.id)!=null?_a13:Tools.generateRandomId(6),this._name$=new rxjs.BehaviorSubject(this._snapshot.title),this.name$=this._name$.asObservable()}get _activePage(){var _a13,_b2;const activePage=this._activePage$.getValue();if(!activePage){const activePageId=(_a13=this.getPageOrder())==null?void 0:_a13[0];return activePageId?(_b2=this.getPages())==null?void 0:_b2[activePageId]:null}return activePage}setName(name){var _a13;this._snapshot.title=name,this._name$.next(name),this._unitId=(_a13=this._snapshot.id)!=null?_a13:generateRandomId(6)}getSnapshot(){return this._snapshot}getUnitId(){return this._unitId}getPages(){var _a13;return(_a13=this._snapshot.body)==null?void 0:_a13.pages}getPageOrder(){var _a13;return(_a13=this._snapshot.body)==null?void 0:_a13.pageOrder}getPage(pageId){const pages=this.getPages();return pages==null?void 0:pages[pageId]}getElementsByPage(pageId){var _a13;return(_a13=this.getPage(pageId))==null?void 0:_a13.pageElements}getElement(pageId,elementId){var _a13;return(_a13=this.getElementsByPage(pageId))==null?void 0:_a13[elementId]}getPageSize(){return this._snapshot.pageSize}getBlankPage(){const id=generateRandomId(6);return{id,pageType:PageType.SLIDE,zIndex:10,title:id,description:"",pageBackgroundFill:{rgb:"rgb(255,255,255)"},pageElements:{}}}setActivePage(page){this._activePage$.next(page)}getActivePage(){return this._activePage}updatePage(pageId,page){this._snapshot.body&&(this._snapshot.body.pages[pageId]=page)}appendPage(page){var _a13;if(!this._snapshot.body)return;this._snapshot.body.pages[page.id]=page;const activePage=this._activePage,index2=this._snapshot.body.pageOrder.indexOf((_a13=activePage==null?void 0:activePage.id)!=null?_a13:"");this._snapshot.body.pageOrder.splice(index2+1,0,page.id)}};__name(_SlideDataModel,"SlideDataModel");let SlideDataModel=_SlideDataModel;const FOCUSING_UNIT="FOCUSING_UNIT",FOCUSING_SHEET="FOCUSING_SHEET",FOCUSING_DOC="FOCUSING_DOC",FOCUSING_SLIDE="FOCUSING_SLIDE",FOCUSING_EDITOR_BUT_HIDDEN="FOCUSING_EDITOR_BUT_HIDDEN",EDITOR_ACTIVATED="EDITOR_ACTIVATED",FOCUSING_EDITOR_INPUT_FORMULA="FOCUSING_EDITOR_INPUT_FORMULA",FOCUSING_FX_BAR_EDITOR="FOCUSING_FX_BAR_EDITOR",FOCUSING_UNIVER_EDITOR="FOCUSING_UNIVER_EDITOR",FOCUSING_EDITOR_STANDALONE="FOCUSING_EDITOR_INPUT_FORMULA",FOCUSING_UNIVER_EDITOR_STANDALONE_SINGLE_MODE="FOCUSING_UNIVER_EDITOR_STANDALONE_SINGLE_MODE",FOCUSING_COMMON_DRAWINGS="FOCUSING_COMMON_DRAWINGS",FORMULA_EDITOR_ACTIVATED="FORMULA_EDITOR_ACTIVATED";var __defProp$6=Object.defineProperty,__getOwnPropDesc$6=Object.getOwnPropertyDescriptor,__decorateClass$6=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$6(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$6(target,key,result),result},"__decorateClass$6"),__decorateParam$5=__name((index2,decorator)=>(target,key)=>decorator(target,key,index2),"__decorateParam$5");const IUniverInstanceService=createIdentifier("univer.current");var _a4;exports.UniverInstanceService=(_a4=class extends Disposable{constructor(_injector,_contextService){super();__publicField(this,"_unitsByType",new Map);__publicField(this,"_createHandler");__publicField(this,"_ctorByType",new Map);__publicField(this,"_currentUnits",new Map);__publicField(this,"_currentUnits$",new rxjs.BehaviorSubject(this._currentUnits));__publicField(this,"currentUnits$",this._currentUnits$.asObservable());__publicField(this,"_unitAdded$",new rxjs.Subject);__publicField(this,"unitAdded$",this._unitAdded$.asObservable());__publicField(this,"_unitDisposed$",new rxjs.Subject);__publicField(this,"unitDisposed$",this._unitDisposed$.asObservable());__publicField(this,"_focused$",new rxjs.BehaviorSubject(null));__publicField(this,"focused$",this._focused$.asObservable());this._injector=_injector,this._contextService=_contextService}dispose(){super.dispose(),this._focused$.complete()}__setCreateHandler(handler){this._createHandler=handler}createUnit(type2,data,options){return this._createHandler(type2,data,this._ctorByType.get(type2),options)}registerCtorForType(type2,ctor){return this._ctorByType.set(type2,ctor),{dispose:__name(()=>{this._ctorByType.delete(type2)},"dispose")}}getCurrentTypeOfUnit$(type2){return this.currentUnits$.pipe(rxjs.map(units=>{var _a13;return(_a13=units.get(type2))!=null?_a13:null}),rxjs.distinctUntilChanged())}getCurrentUnitForType(type2){return this._currentUnits.get(type2)}setCurrentUnitForType(unitId){const result=this._getUnitById(unitId);if(!result)throw new Error(`[UniverInstanceService]: no document with unitId ${unitId}!`);this._currentUnits.set(result[1],result[0]),this._currentUnits$.next(this._currentUnits)}getTypeOfUnitAdded$(type2){return this._unitAdded$.pipe(rxjs.filter(unit=>unit.type===type2))}__addUnit(unit,options){var _a13;const type2=unit.type;this._unitsByType.has(type2)||this._unitsByType.set(type2,[]);const units=this._unitsByType.get(type2),newUnitId=unit.getUnitId();if(units.findIndex(u=>u.getUnitId()===newUnitId)!==-1)throw new Error(`[UniverInstanceService]: cannot create a unit with the same unit id: ${newUnitId}.`);units.push(unit),this._unitAdded$.next(unit),((_a13=options==null?void 0:options.makeCurrent)==null||_a13)&&this.setCurrentUnitForType(unit.getUnitId())}getTypeOfUnitDisposed$(type2){return this.unitDisposed$.pipe(rxjs.filter(unit=>unit.type===type2))}getUnit(id,type2){var _a13;const unit=(_a13=this._getUnitById(id))==null?void 0:_a13[0];return type2&&(unit==null?void 0:unit.type)!==type2?null:unit}getCurrentUniverDocInstance(){return this.getCurrentUnitForType(I.UNIVER_DOC)}getUniverDocInstance(unitId){return this.getUnit(unitId,I.UNIVER_DOC)}getUniverSheetInstance(unitId){return this.getUnit(unitId,I.UNIVER_SHEET)}getAllUnitsForType(type2){var _a13;return(_a13=this._unitsByType.get(type2))!=null?_a13:[]}changeDoc(unitId,doc){const allDocs=this.getAllUnitsForType(I.UNIVER_DOC),oldDoc=allDocs.find(doc2=>doc2.getUnitId()===unitId);if(oldDoc!=null){const index2=allDocs.indexOf(oldDoc);allDocs.splice(index2,1)}this.__addUnit(doc)}get focused(){var _a13;const id=this._focused$.getValue();return id?(_a13=this._getUnitById(id))==null?void 0:_a13[0]:null}focusUnit(id){this._focused$.next(id),this.focused instanceof exports.Workbook?(this._contextService.setContextValue(FOCUSING_UNIT,!0),this._contextService.setContextValue(FOCUSING_DOC,!1),this._contextService.setContextValue(FOCUSING_SHEET,!0),this._contextService.setContextValue(FOCUSING_SLIDE,!1),this.setCurrentUnitForType(id)):this.focused instanceof DocumentDataModel?(this._contextService.setContextValue(FOCUSING_UNIT,!0),this._contextService.setContextValue(FOCUSING_DOC,!0),this._contextService.setContextValue(FOCUSING_SHEET,!1),this._contextService.setContextValue(FOCUSING_SLIDE,!1),this.setCurrentUnitForType(id)):this.focused instanceof SlideDataModel?(this._contextService.setContextValue(FOCUSING_UNIT,!0),this._contextService.setContextValue(FOCUSING_DOC,!1),this._contextService.setContextValue(FOCUSING_SHEET,!1),this._contextService.setContextValue(FOCUSING_SLIDE,!0),this.setCurrentUnitForType(id)):(this._contextService.setContextValue(FOCUSING_UNIT,!1),this._contextService.setContextValue(FOCUSING_DOC,!1),this._contextService.setContextValue(FOCUSING_SHEET,!1),this._contextService.setContextValue(FOCUSING_SLIDE,!1))}getFocusedUnit(){return this.focused}getUnitType(unitId){const result=this._getUnitById(unitId);return result?result[1]:I.UNRECOGNIZED}disposeUnit(unitId){const result=this._getUnitById(unitId);if(!result)return!1;const[unit,type2]=result,units=this._unitsByType.get(type2),index2=units.indexOf(unit);return units.splice(index2,1),this._tryRemoveCurrentUnitForType(unitId,type2),this._tryBlurUnitOnRemoval(unitId),this._unitDisposed$.next(unit),!0}_tryRemoveCurrentUnitForType(unitId,type2){const current=this.getCurrentUnitForType(type2);(current==null?void 0:current.getUnitId())===unitId&&(this._currentUnits.set(type2,null),this._currentUnits$.next(this._currentUnits))}_tryBlurUnitOnRemoval(unitId){var _a13;((_a13=this.focused)==null?void 0:_a13.getUnitId())===unitId&&this._focused$.next(null)}_getUnitById(unitId){for(const[type2,units]of this._unitsByType){const unit=units.find(unit2=>unit2.getUnitId()===unitId);if(unit)return[unit,type2]}}},__name(_a4,"UniverInstanceService"),_a4);exports.UniverInstanceService=__decorateClass$6([__decorateParam$5(0,Inject(Injector)),__decorateParam$5(1,IContextService)],exports.UniverInstanceService);var LifecycleStages=(LifecycleStages2=>(LifecycleStages2[LifecycleStages2.Starting=0]="Starting",LifecycleStages2[LifecycleStages2.Ready=1]="Ready",LifecycleStages2[LifecycleStages2.Rendered=2]="Rendered",LifecycleStages2[LifecycleStages2.Steady=3]="Steady",LifecycleStages2))(LifecycleStages||{});const LifecycleNameMap={0:"Starting",1:"Ready",2:"Rendered",3:"Steady"},LifecycleToModules=new Map;function OnLifecycle(lifecycleStage,identifier){return __name(function(_){runOnLifecycle(lifecycleStage,identifier)},"decorator2")}__name(OnLifecycle,"OnLifecycle");function runOnLifecycle(lifecycleStage,identifier){LifecycleToModules.has(lifecycleStage)||LifecycleToModules.set(lifecycleStage,[]),LifecycleToModules.get(lifecycleStage).push(identifier)}__name(runOnLifecycle,"runOnLifecycle");var __defProp$5=Object.defineProperty,__getOwnPropDesc$5=Object.getOwnPropertyDescriptor,__decorateClass$5=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$5(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$5(target,key,result),result},"__decorateClass$5"),__decorateParam$4=__name((index2,decorator)=>(target,key)=>decorator(target,key,index2),"__decorateParam$4"),_a5;exports.LifecycleService=(_a5=class extends Disposable{constructor(_logService){super();__publicField(this,"_lifecycle$",new rxjs.BehaviorSubject(LifecycleStages.Starting));__publicField(this,"lifecycle$",this._lifecycle$.asObservable());__publicField(this,"_lock",!1);this._logService=_logService,this._reportProgress(LifecycleStages.Starting)}get stage(){return this._lifecycle$.getValue()}set stage(stage){if(this._lock)throw new Error("[LifecycleService]: cannot set new stage when related logic is all handled!");if(stage<this.stage)throw new Error("[LifecycleService]: lifecycle stage cannot go backward!");stage!==this.stage&&(this._lock=!0,this._reportProgress(stage),this._lifecycle$.next(stage),this._lock=!1)}dispose(){this._lifecycle$.complete(),super.dispose()}subscribeWithPrevious(){return rxjs.merge(getLifecycleStagesAndBefore(this.stage),this._lifecycle$.pipe(rxjs.skip(1))).pipe(takeAfter(s=>s===LifecycleStages.Steady))}_reportProgress(stage){this._logService.debug("[LifecycleService]",`lifecycle progressed to "${LifecycleNameMap[stage]}".`)}},__name(_a5,"LifecycleService"),_a5);exports.LifecycleService=__decorateClass$5([__decorateParam$4(0,ILogService)],exports.LifecycleService);var _a6;exports.LifecycleInitializerService=(_a6=class extends Disposable{constructor(_injector){super();__publicField(this,"_seenTokens",new Set);this._injector=_injector}initModulesOnStage(stage){var _a13;(_a13=LifecycleToModules.get(stage))==null||_a13.forEach(m=>{this._injector.has(m)&&!this._seenTokens.has(m)&&(this._injector.get(m),this._seenTokens.add(m))})}},__name(_a6,"LifecycleInitializerService"),_a6);exports.LifecycleInitializerService=__decorateClass$5([__decorateParam$4(0,Inject(Injector))],exports.LifecycleInitializerService);function getLifecycleStagesAndBefore(lifecycleStage){switch(lifecycleStage){case LifecycleStages.Starting:return rxjs.of(LifecycleStages.Starting);case LifecycleStages.Ready:return rxjs.of(LifecycleStages.Starting,LifecycleStages.Ready);case LifecycleStages.Rendered:return rxjs.of(LifecycleStages.Starting,LifecycleStages.Ready,LifecycleStages.Rendered);default:return rxjs.of(LifecycleStages.Starting,LifecycleStages.Ready,LifecycleStages.Rendered,LifecycleStages.Steady)}}__name(getLifecycleStagesAndBefore,"getLifecycleStagesAndBefore");const _LocaleService=class _LocaleService extends Disposable{constructor(){super();__publicField(this,"_currentLocale$",new rxjs.BehaviorSubject(LocaleType.ZH_CN));__publicField(this,"currentLocale$",this._currentLocale$.asObservable());__publicField(this,"_locales",null);__publicField(this,"localeChanged$",new rxjs.Subject);__publicField(this,"t",__name((key,...args)=>{if(!this._locales)throw new Error("[LocaleService]: Locale not initialized");const keys=key.split("."),resolvedValue=this.resolveKeyPath(this._locales[this._currentLocale],keys);if(typeof resolvedValue=="string"){let result=resolvedValue;return args.forEach((arg,index2)=>{result=result.replace(`{${index2}}`,arg)}),result}else return key},"t"));this.disposeWithMe(toDisposable(()=>this.localeChanged$.complete()))}get _currentLocale(){return this._currentLocale$.value}load(locales){var _a13;this._locales=Tools.deepMerge((_a13=this._locales)!=null?_a13:{},locales)}setLocale(locale){this._currentLocale$.next(locale),this.localeChanged$.next()}getLocales(){var _a13;return(_a13=this._locales)==null?void 0:_a13[this._currentLocale]}getCurrentLocale(){return this._currentLocale}resolveKeyPath(obj,keys){const currentKey=keys.shift();if(currentKey&&obj&&currentKey in obj){const nextObj=obj[currentKey];return keys.length>0&&(typeof nextObj=="object"||Array.isArray(nextObj))?this.resolveKeyPath(nextObj,keys):nextObj}return null}};__name(_LocaleService,"LocaleService");let LocaleService=_LocaleService;var PermissionStatus=(PermissionStatus2=>(PermissionStatus2.INIT="init",PermissionStatus2.FETCHING="fetching",PermissionStatus2.DONE="done",PermissionStatus2))(PermissionStatus||{});const IPermissionService=createIdentifier("univer.permission-service");runOnLifecycle(LifecycleStages.Starting,IPermissionService);const _PermissionService=class _PermissionService extends Disposable{constructor(){super(...arguments);__publicField(this,"_permissionPointMap",new Map);__publicField(this,"_permissionPointUpdate$",new rxjs.Subject);__publicField(this,"permissionPointUpdate$",this._permissionPointUpdate$.asObservable())}deletePermissionPoint(permissionId){const permissionPoint=this._permissionPointMap.get(permissionId);permissionPoint&&(permissionPoint.complete(),this._permissionPointMap.delete(permissionId))}addPermissionPoint(_item){const isSubject=_item instanceof rxjs.BehaviorSubject,item=isSubject?_item.getValue():_item;if(!item.id)return!1;if(this._permissionPointMap.get(item.id))throw new Error(`${item.id} PermissionPoint already exists`);return this._permissionPointMap.set(item.id,isSubject?_item:new rxjs.BehaviorSubject(item)),this._permissionPointUpdate$.next(item),!0}updatePermissionPoint(permissionId,value){const permissionPoint=this._permissionPointMap.get(permissionId);if(!permissionPoint)return;const subject=permissionPoint.getValue();subject.value=value,subject.status=PermissionStatus.DONE,permissionPoint.next(subject),this._permissionPointUpdate$.next(subject)}clearPermissionMap(){this._permissionPointMap.clear()}getPermissionPoint(permissionId){const permissionPoint=this._permissionPointMap.get(permissionId);if(permissionPoint)return permissionPoint.getValue()}getPermissionPoint$(permissionId){const permissionPoint=this._permissionPointMap.get(permissionId);if(permissionPoint)return permissionPoint}composePermission$(permissionIdList){const subjectList=permissionIdList.map(id=>{var _a13;const subject=(_a13=this._permissionPointMap)==null?void 0:_a13.get(id);if(!subject)throw new Error(`[PermissionService]: ${id} permissionPoint does not exist!`);return subject.asObservable()});return rxjs.combineLatest(subjectList).pipe(operators.map(list=>list))}composePermission(permissionIdList){return permissionIdList.map(id=>{var _a13;const subject=(_a13=this._permissionPointMap)==null?void 0:_a13.get(id);if(!subject)throw new Error(`[PermissionService]: ${id} permissionPoint does not exist!`);return subject.getValue()})}getAllPermissionPoint(){const cacheMap=new Map;return this._permissionPointMap.forEach((v,key)=>{cacheMap.set(key,v)}),cacheMap}};__name(_PermissionService,"PermissionService");let PermissionService=_PermissionService;const _ResourceManagerService=class _ResourceManagerService extends Disposable{constructor(){super(...arguments);__publicField(this,"_resourceMap",new Map);__publicField(this,"_register$",new rxjs.Subject);__publicField(this,"register$",this._register$.asObservable())}getAllResourceHooks(){return[...this._resourceMap.values()]}getResources(unitId,type2){return type2?this.getResourcesByType(unitId,type2):this.getAllResourceHooks().map(resourceHook=>{const data=resourceHook.toJson(unitId);return{name:resourceHook.pluginName,data}})}getResourcesByType(unitId,type2){return this.getAllResourceHooks().filter(hook=>hook.businesses.includes(type2)).map(resourceHook=>{const data=resourceHook.toJson(unitId);return{name:resourceHook.pluginName,data}})}registerPluginResource(hook){const resourceName=hook.pluginName;if(this._resourceMap.has(resourceName))throw new Error(`the pluginName is registered {${resourceName}}`);return this._resourceMap.set(resourceName,hook),this._register$.next(hook),toDisposable(()=>this._resourceMap.delete(resourceName))}disposePluginResource(pluginName){this._resourceMap.delete(pluginName)}loadResources(unitId,resources){this.getAllResourceHooks().forEach(hook=>{var _a13;const data=(_a13=resources==null?void 0:resources.find(resource=>resource.name===hook.pluginName))==null?void 0:_a13.data;if(data)try{const model=hook.parseJson(data);hook.onLoad(unitId,model)}catch{console.error("LoadResources Error!")}})}unloadResources(unitId){this.getAllResourceHooks().forEach(hook=>{hook.onUnLoad(unitId)})}dispose(){this._register$.complete(),this._resourceMap.clear()}};__name(_ResourceManagerService,"ResourceManagerService");let ResourceManagerService=_ResourceManagerService;const IResourceManagerService=createIdentifier("core.resource-manager.service"),PREFIX="__INTERNAL_EDITOR__",DOCS_NORMAL_EDITOR_UNIT_ID_KEY=`${PREFIX}DOCS_NORMAL`,DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY=`${PREFIX}DOCS_FORMULA_BAR`,DOCS_ZEN_EDITOR_UNIT_ID_KEY=`${PREFIX}ZEN_EDITOR`,DEFAULT_EMPTY_DOCUMENT_VALUE=`\r
8
+ `,textRuns:[],paragraphs:[{startIndex:0,paragraphStyle:{spaceAbove:{v:5},lineSpacing:1,spaceBelow:{v:0}}}],sectionBreaks:[{startIndex:1}]},documentStyle:{pageSize:{width:793.3333333333334,height:1122.6666666666667},marginTop:50,marginBottom:50,marginRight:40,marginLeft:40,renderConfig:{vertexAngle:0,centerAngle:0}},settings:{}}}__name(getEmptySnapshot$1,"getEmptySnapshot$1");var dist$1={},json1_release={},deepEqual$1={};Object.defineProperty(deepEqual$1,"__esModule",{value:!0});function eqObj(a,b){if(Array.isArray(b))return!1;for(let k in a)if(!deepEqual(a[k],b[k]))return!1;for(let k in b)if(a[k]===void 0)return!1;return!0}__name(eqObj,"eqObj");function eqArr(a,b){if(!Array.isArray(b)||a.length!==b.length)return!1;for(let i=0;i<a.length;i++)if(!deepEqual(a[i],b[i]))return!1;return!0}__name(eqArr,"eqArr");function deepEqual(a,b){return a===b?!0:a===null||b===null||typeof a!="object"||typeof b!="object"?!1:Array.isArray(a)?eqArr(a,b):eqObj(a,b)}__name(deepEqual,"deepEqual");deepEqual$1.default=deepEqual;var deepClone$1={};Object.defineProperty(deepClone$1,"__esModule",{value:!0});function deepClone(old){if(old===null)return null;if(Array.isArray(old))return old.map(deepClone);if(typeof old=="object"){const o={};for(let k in old)o[k]=deepClone(old[k]);return o}else return old}__name(deepClone,"deepClone");deepClone$1.default=deepClone;var cursor={};(function(exports2){Object.defineProperty(exports2,"__esModule",{value:!0}),exports2.eachChildOf=exports2.advancer=exports2.readCursor=exports2.writeCursor=exports2.WriteCursor=exports2.ReadCursor=exports2.isValidPathItem=void 0;function assert(pred,msg){if(!pred)throw new Error(msg)}__name(assert,"assert");const isObject2=__name(o=>o!=null&&typeof o=="object"&&!Array.isArray(o),"isObject"),isGreaterKey=__name((a,b)=>typeof a==typeof b?a>b:typeof a=="string"&&typeof b=="number","isGreaterKey");function copyAll(c,w){for(let _k in c){const k=_k;w.write(k,c[k])}}__name(copyAll,"copyAll"),exports2.isValidPathItem=k=>typeof k=="number"||typeof k=="string"&&k!=="__proto__";const _Cursor=class _Cursor{constructor(op=null){this.parents=[],this.indexes=[],this.lcIdx=-1,this.idx=-1,this.container=op}ascend(){assert(this.parents.length===this.indexes.length/2),this.idx===0?this.parents.length?(this.lcIdx=this.indexes.pop(),this.container=this.parents.pop(),this.idx=this.indexes.pop()):(this.lcIdx=0,this.idx=-1):(assert(this.idx>0),this.idx--,isObject2(this.container[this.idx])&&this.idx--)}getPath(){const path=[];let c=this.container,p=this.parents.length-1,i=this.idx;for(;i>=0;)path.unshift(c[i]),i===0?(i=this.indexes[p*2],c=this.parents[p--]):i-=isObject2(c[i-1])?2:1;return path}};__name(_Cursor,"Cursor");let Cursor=_Cursor;const _ReadCursor=class _ReadCursor extends Cursor{get(){return this.container?this.container.slice(this.idx+1):null}getKey(){return assert(this.container!=null,"Invalid call to getKey before cursor descended"),this.container[this.idx]}getComponent(){let c;return this.container&&this.container.length>this.idx+1&&isObject2(c=this.container[this.idx+1])?c:null}descendFirst(){let i=this.idx+1;if(!this.container||i>=this.container.length||isObject2(this.container[i])&&i+1>=this.container.length)return!1;isObject2(this.container[i])&&i++;const firstChild=this.container[i];return Array.isArray(firstChild)?(this.indexes.push(this.idx),this.parents.push(this.container),this.indexes.push(i),this.idx=0,this.container=firstChild):this.idx=i,!0}nextSibling(){if(assert(this.parents.length===this.indexes.length/2),this.idx>0||this.parents.length===0)return!1;const i=this.indexes[this.indexes.length-1]+1,c=this.parents[this.parents.length-1];return i>=c.length?!1:(assert(!isNaN(i)),this.indexes[this.indexes.length-1]=i,this.container=c[i],!0)}_init(_container,_idx,_parents,_indexes){this.container=_container,this.idx=_idx,this.parents=_parents.slice(),this.indexes=_indexes.slice()}clone(){const c=new _ReadCursor;return c._init(this.container,this.idx,this.parents,this.indexes),c}*[Symbol.iterator](){if(this.descendFirst()){do yield this.getKey();while(this.nextSibling());this.ascend()}}traverse(w,fn){const c=this.getComponent();c&&fn(c,w);for(const key of this)w&&w.descend(key),this.traverse(w,fn),w&&w.ascend()}eachPick(w,fn){this.traverse(w,(c,w2)=>{c.p!=null&&fn(c.p,w2)})}eachDrop(w,fn){this.traverse(w,(c,w2)=>{c.d!=null&&fn(c.d,w2)})}};__name(_ReadCursor,"ReadCursor");let ReadCursor=_ReadCursor;exports2.ReadCursor=ReadCursor;const _WriteCursor=class _WriteCursor extends Cursor{constructor(op=null){super(op),this.pendingDescent=[],this._op=op}flushDescent(){assert(this.parents.length===this.indexes.length/2),this.container===null&&(this._op=this.container=[]);for(let j=0;j<this.pendingDescent.length;j++){const k=this.pendingDescent[j];let i=this.idx+1;if(i<this.container.length&&isObject2(this.container[i])&&i++,assert(i===this.container.length||!isObject2(this.container[i])),i===this.container.length)this.container.push(k),this.idx=i;else if(this.container[i]===k)this.idx=i;else{if(!Array.isArray(this.container[i])){const oldChild=this.container.splice(i,this.container.length-i);this.container.push(oldChild),this.lcIdx>-1&&(this.lcIdx=i)}for(this.indexes.push(this.idx),this.parents.push(this.container),this.lcIdx!==-1&&(assert(isGreaterKey(k,this.container[this.lcIdx][0])),i=this.lcIdx+1,this.lcIdx=-1);i<this.container.length&&isGreaterKey(k,this.container[i][0]);)i++;if(this.indexes.push(i),this.idx=0,i<this.container.length&&this.container[i][0]===k)this.container=this.container[i];else{const child=[k];this.container.splice(i,0,child),this.container=child}}}this.pendingDescent.length=0}reset(){this.lcIdx=-1}getComponent(){this.flushDescent();const i=this.idx+1;if(i<this.container.length&&isObject2(this.container[i]))return this.container[i];{const component={};return this.container.splice(i,0,component),component}}write(key,value){const component=this.getComponent();assert(component[key]==null||component[key]===value,"Internal consistency error: Overwritten component. File a bug"),component[key]=value}get(){return this._op}descend(key){if(!exports2.isValidPathItem(key))throw Error("Invalid JSON key");this.pendingDescent.push(key)}descendPath(path){return this.pendingDescent.push(...path),this}ascend(){this.pendingDescent.length?this.pendingDescent.pop():super.ascend()}mergeTree(data,mergeFn=copyAll){if(data===null)return;if(assert(Array.isArray(data)),data===this._op)throw Error("Cannot merge into my own tree");const _lcIdx=this.lcIdx,oldDepth=this.parents.length;let depth=0;for(let i=0;i<data.length;i++){const c=data[i];typeof c=="string"||typeof c=="number"?(depth++,this.descend(c)):Array.isArray(c)?this.mergeTree(c,mergeFn):typeof c=="object"&&mergeFn(c,this)}for(;depth--;)this.ascend();this.lcIdx=this.parents.length===oldDepth?_lcIdx:-1}at(path,fn){this.descendPath(path),fn(this);for(let i=0;i<path.length;i++)this.ascend();return this}writeAtPath(path,key,value){return this.at(path,()=>this.write(key,value)),this.reset(),this}writeMove(path1,path2,slot=0){return this.writeAtPath(path1,"p",slot).writeAtPath(path2,"d",slot)}getPath(){const path=super.getPath();return path.push(...this.pendingDescent),path}};__name(_WriteCursor,"WriteCursor");let WriteCursor=_WriteCursor;exports2.WriteCursor=WriteCursor,exports2.writeCursor=()=>new WriteCursor,exports2.readCursor=op=>new ReadCursor(op);function advancer(r,listMap,listAdv){let didDescend,valid;valid=didDescend=r?r.descendFirst():!1;function adv(ktarget){let k2_;for(;valid;){const k2=k2_=r.getKey();if(ktarget!=null){let skip=!1;if(listMap&&typeof k2=="number"&&(k2_=listMap(k2,r.getComponent()),k2_<0&&(k2_=~k2_,skip=!0)),isGreaterKey(k2_,ktarget))return null;if(k2_===ktarget&&!skip)return r}listAdv&&typeof k2_=="number"&&listAdv(k2_,r.getComponent()),valid=r.nextSibling()}return null}return __name(adv,"adv"),adv.end=()=>{didDescend&&r.ascend()},adv}__name(advancer,"advancer"),exports2.advancer=advancer;function eachChildOf(r1,r2,fn){let hasChild1,descended1,hasChild2,descended2;for(hasChild1=descended1=r1&&r1.descendFirst(),hasChild2=descended2=r2&&r2.descendFirst();hasChild1||hasChild2;){let k1=hasChild1?r1.getKey():null,k2=hasChild2?r2.getKey():null;k1!==null&&k2!==null&&(isGreaterKey(k2,k1)?k2=null:k1!==k2&&(k1=null)),fn(k1==null?k2:k1,k1!=null?r1:null,k2!=null?r2:null),k1!=null&&hasChild1&&(hasChild1=r1.nextSibling()),k2!=null&&hasChild2&&(hasChild2=r2.nextSibling())}descended1&&r1.ascend(),descended2&&r2.ascend()}__name(eachChildOf,"eachChildOf"),exports2.eachChildOf=eachChildOf})(cursor);var types={};(function(exports2){Object.defineProperty(exports2,"__esModule",{value:!0}),exports2.ConflictType=void 0,function(ConflictType){ConflictType[ConflictType.RM_UNEXPECTED_CONTENT=1]="RM_UNEXPECTED_CONTENT",ConflictType[ConflictType.DROP_COLLISION=2]="DROP_COLLISION",ConflictType[ConflictType.BLACKHOLE=3]="BLACKHOLE"}(exports2.ConflictType||(exports2.ConflictType={}))})(types);var dist={},unicount={},hasRequiredUnicount;function requireUnicount(){return hasRequiredUnicount||(hasRequiredUnicount=1,Object.defineProperty(unicount,"__esModule",{value:!0}),unicount.uniToStrPos=unicount.strPosToUni=void 0,unicount.strPosToUni=(s,strOffset=s.length)=>{let pairs=0,i=0;for(;i<strOffset;i++){const code=s.charCodeAt(i);code>=55296&&code<=57343&&(pairs++,i++)}if(i!==strOffset)throw Error("Invalid offset - splits unicode bytes");return i-pairs},unicount.uniToStrPos=(s,uniOffset)=>{let pos=0;for(;uniOffset>0;uniOffset--){const code=s.charCodeAt(pos);pos+=code>=55296&&code<=57343?2:1}return pos}),unicount}__name(requireUnicount,"requireUnicount");var type={},hasRequiredType;function requireType(){return hasRequiredType||(hasRequiredType=1,function(exports2){Object.defineProperty(exports2,"__esModule",{value:!0}),exports2.uniSlice=exports2.dlen=exports2.eachOp=void 0;const unicount_1=requireUnicount(),checkOp=__name(op=>{if(!Array.isArray(op))throw Error("Op must be an array of components");let last=null;for(let i=0;i<op.length;i++){const c=op[i];switch(typeof c){case"object":if(typeof c.d!="number"&&typeof c.d!="string")throw Error("Delete must be number or string");if(exports2.dlen(c.d)<=0)throw Error("Deletes must not be empty");break;case"string":if(!(c.length>0))throw Error("Inserts cannot be empty");break;case"number":if(!(c>0))throw Error("Skip components must be >0");if(typeof last=="number")throw Error("Adjacent skip components should be combined");break}last=c}if(typeof last=="number")throw Error("Op has a trailing skip")},"checkOp");function eachOp(op,fn){let prePos=0,postPos=0;for(let i=0;i<op.length;i++){const c=op[i];switch(fn(c,prePos,postPos),typeof c){case"object":prePos+=exports2.dlen(c.d);break;case"string":postPos+=unicount_1.strPosToUni(c);break;case"number":prePos+=c,postPos+=c;break}}}__name(eachOp,"eachOp"),exports2.eachOp=eachOp;function mapOp(op,fn){const newOp=[],append=makeAppend(newOp);return eachOp(op,(c,prePos,postPos)=>{append(fn(c,prePos,postPos))}),trim(newOp)}__name(mapOp,"mapOp");const id=__name(x=>x,"id"),normalize=__name(op=>mapOp(op,id),"normalize");exports2.dlen=d=>typeof d=="number"?d:unicount_1.strPosToUni(d);const makeAppend=__name(op=>component=>{if(!(!component||component.d===0||component.d===""))if(op.length===0)op.push(component);else if(typeof component==typeof op[op.length-1])if(typeof component=="object"){const last=op[op.length-1];last.d=typeof last.d=="string"&&typeof component.d=="string"?last.d+component.d:exports2.dlen(last.d)+exports2.dlen(component.d)}else op[op.length-1]+=component;else op.push(component)},"makeAppend"),componentLength=__name(c=>typeof c=="number"?c:typeof c=="string"?unicount_1.strPosToUni(c):typeof c.d=="number"?c.d:unicount_1.strPosToUni(c.d),"componentLength");exports2.uniSlice=(s,startUni,endUni)=>{const start=unicount_1.uniToStrPos(s,startUni),end=endUni==null?1/0:unicount_1.uniToStrPos(s,endUni);return s.slice(start,end)};const dslice=__name((d,start,end)=>typeof d=="number"?end==null?d-start:Math.min(d,end)-start:exports2.uniSlice(d,start,end),"dslice"),makeTake=__name(op=>{let idx=0,offset=0;return{take:__name((n,indivisableField)=>{if(idx===op.length)return n===-1?null:n;const c=op[idx];let part;if(typeof c=="number")return n===-1||c-offset<=n?(part=c-offset,++idx,offset=0,part):(offset+=n,n);if(typeof c=="string"){if(n===-1||indivisableField==="i"||unicount_1.strPosToUni(c.slice(offset))<=n)return part=c.slice(offset),++idx,offset=0,part;{const offset2=offset+unicount_1.uniToStrPos(c.slice(offset),n);return part=c.slice(offset,offset2),offset=offset2,part}}else{if(n===-1||indivisableField==="d"||exports2.dlen(c.d)-offset<=n)return part={d:dslice(c.d,offset)},++idx,offset=0,part;{let result=dslice(c.d,offset,offset+n);return offset+=n,{d:result}}}},"take"),peek:__name(()=>op[idx],"peek")}},"makeTake"),trim=__name(op=>(op.length>0&&typeof op[op.length-1]=="number"&&op.pop(),op),"trim");function transform(op1,op2,side){if(side!=="left"&&side!=="right")throw Error("side ("+side+") must be 'left' or 'right'");checkOp(op1),checkOp(op2);const newOp=[],append=makeAppend(newOp),{take,peek}=makeTake(op1);for(let i=0;i<op2.length;i++){const c2=op2[i];let length,c1;switch(typeof c2){case"number":for(length=c2;length>0;)c1=take(length,"i"),append(c1),typeof c1!="string"&&(length-=componentLength(c1));break;case"string":side==="left"&&typeof peek()=="string"&&append(take(-1)),append(unicount_1.strPosToUni(c2));break;case"object":for(length=exports2.dlen(c2.d);length>0;)switch(c1=take(length,"i"),typeof c1){case"number":length-=c1;break;case"string":append(c1);break;case"object":length-=exports2.dlen(c1.d)}break}}let c;for(;c=take(-1);)append(c);return trim(newOp)}__name(transform,"transform");function compose(op1,op2){checkOp(op1),checkOp(op2);const result=[],append=makeAppend(result),{take}=makeTake(op1);for(let i=0;i<op2.length;i++){const component=op2[i];let length,chunk;switch(typeof component){case"number":for(length=component;length>0;)chunk=take(length,"d"),append(chunk),typeof chunk!="object"&&(length-=componentLength(chunk));break;case"string":append(component);break;case"object":length=exports2.dlen(component.d);let offset=0;for(;offset<length;)switch(chunk=take(length-offset,"d"),typeof chunk){case"number":append({d:dslice(component.d,offset,offset+chunk)}),offset+=chunk;break;case"string":offset+=unicount_1.strPosToUni(chunk);break;case"object":append(chunk)}break}}let c;for(;c=take(-1);)append(c);return trim(result)}__name(compose,"compose");const transformPosition=__name((cursor2,op)=>{let pos=0;for(let i=0;i<op.length&&cursor2>pos;i++){const c=op[i];switch(typeof c){case"number":{pos+=c;break}case"string":const offset=unicount_1.strPosToUni(c);pos+=offset,cursor2+=offset;break;case"object":cursor2-=Math.min(exports2.dlen(c.d),cursor2-pos);break}}return cursor2},"transformPosition"),transformSelection=__name((selection,op)=>typeof selection=="number"?transformPosition(selection,op):selection.map(s=>transformPosition(s,op)),"transformSelection");function makeInvertible(op,doc,ropeImpl){return mapOp(op,(c,prePos)=>typeof c=="object"&&typeof c.d=="number"?{d:ropeImpl.slice(doc,prePos,prePos+c.d)}:c)}__name(makeInvertible,"makeInvertible");function invert(op){return mapOp(op,c=>{switch(typeof c){case"object":if(typeof c.d=="number")throw Error("Cannot invert text op: Deleted characters missing from operation. makeInvertible must be called first.");return c.d;case"string":return{d:c};case"number":return c}})}__name(invert,"invert");function stripInvertible(op){return mapOp(op,c=>typeof c=="object"&&typeof c.d=="string"?{d:unicount_1.strPosToUni(c.d)}:c)}__name(stripInvertible,"stripInvertible");function isInvertible(op){let invertible=!0;return eachOp(op,c=>{typeof c=="object"&&typeof c.d=="number"&&(invertible=!1)}),invertible}__name(isInvertible,"isInvertible");function makeType(ropeImpl){return{name:"text-unicode",uri:"http://sharejs.org/types/text-unicode",trim,normalize,checkOp,create(initial=""){if(typeof initial!="string")throw Error("Initial data must be a string");return ropeImpl.create(initial)},apply(str,op){checkOp(op);const builder=ropeImpl.builder(str);for(let i=0;i<op.length;i++){const component=op[i];switch(typeof component){case"number":builder.skip(component);break;case"string":builder.append(component);break;case"object":builder.del(exports2.dlen(component.d));break}}return builder.build()},transform,compose,transformPosition,transformSelection,isInvertible,makeInvertible(op,doc){return makeInvertible(op,doc,ropeImpl)},stripInvertible,invert,invertWithDoc(op,doc){return invert(makeInvertible(op,doc,ropeImpl))},isNoop:__name(op=>op.length===0,"isNoop")}}__name(makeType,"makeType"),exports2.default=makeType}(type)),type}__name(requireType,"requireType");var api={},hasRequiredApi;function requireApi(){if(hasRequiredApi)return api;hasRequiredApi=1,Object.defineProperty(api,"__esModule",{value:!0});const type_1=requireType(),unicount_1=requireUnicount();function api$1(getSnapshot,submitOp){return{get:getSnapshot,getLength(){return getSnapshot().length},insert(pos,text,callback){const uniPos=unicount_1.strPosToUni(getSnapshot(),pos);return submitOp([uniPos,text],callback)},remove(pos,lengthOrContent,callback){const uniPos=unicount_1.strPosToUni(getSnapshot(),pos);return submitOp([uniPos,{d:lengthOrContent}],callback)},_onOp(op){type_1.eachOp(op,(component,prePos,postPos)=>{switch(typeof component){case"string":this.onInsert&&this.onInsert(postPos,component);break;case"object":const dl=type_1.dlen(component.d);this.onRemove&&this.onRemove(postPos,dl)}})},onInsert:null,onRemove:null}}return __name(api$1,"api$1"),api.default=api$1,api$1.provides={text:!0},api}__name(requireApi,"requireApi");var hasRequiredDist;function requireDist(){return hasRequiredDist||(hasRequiredDist=1,function(exports2){var __createBinding=commonjsGlobal&&commonjsGlobal.__createBinding||(Object.create?function(o,m,k,k2){k2===void 0&&(k2=k),Object.defineProperty(o,k2,{enumerable:!0,get:__name(function(){return m[k]},"get")})}:function(o,m,k,k2){k2===void 0&&(k2=k),o[k2]=m[k]}),__setModuleDefault=commonjsGlobal&&commonjsGlobal.__setModuleDefault||(Object.create?function(o,v){Object.defineProperty(o,"default",{enumerable:!0,value:v})}:function(o,v){o.default=v}),__importStar=commonjsGlobal&&commonjsGlobal.__importStar||function(mod){if(mod&&mod.__esModule)return mod;var result={};if(mod!=null)for(var k in mod)Object.hasOwnProperty.call(mod,k)&&__createBinding(result,mod,k);return __setModuleDefault(result,mod),result},__importDefault=commonjsGlobal&&commonjsGlobal.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports2,"__esModule",{value:!0}),exports2.type=exports2.remove=exports2.insert=void 0;const unicount_1=requireUnicount(),type_1=__importStar(requireType()),api_1=__importDefault(requireApi()),ropeImplUnicodeString={create(s){return s},toString(s){return s},builder(oldDoc){if(typeof oldDoc!="string")throw Error("Invalid document snapshot: "+oldDoc);const newDoc=[];return{skip(n){let offset=unicount_1.uniToStrPos(oldDoc,n);if(offset>oldDoc.length)throw Error("The op is too long for this document");newDoc.push(oldDoc.slice(0,offset)),oldDoc=oldDoc.slice(offset)},append(s){newDoc.push(s)},del(n){oldDoc=oldDoc.slice(unicount_1.uniToStrPos(oldDoc,n))},build(){return newDoc.join("")+oldDoc}}},slice:type_1.uniSlice},textString=type_1.default(ropeImplUnicodeString),type2=Object.assign(Object.assign({},textString),{api:api_1.default});exports2.type=type2,exports2.insert=(pos,text)=>text.length===0?[]:pos===0?[text]:[pos,text],exports2.remove=(pos,textOrLen)=>type_1.dlen(textOrLen)===0?[]:pos===0?[{d:textOrLen}]:[pos,{d:textOrLen}];var type_2=requireType();Object.defineProperty(exports2,"makeType",{enumerable:!0,get:__name(function(){return type_2.default},"get")})}(dist)),dist}__name(requireDist,"requireDist");(function(exports2){var __importDefault=commonjsGlobal&&commonjsGlobal.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports2,"__esModule",{value:!0}),exports2.editOp=exports2.replaceOp=exports2.insertOp=exports2.moveOp=exports2.removeOp=exports2.type=void 0;const deepEqual_js_1=__importDefault(deepEqual$1),deepClone_js_1=__importDefault(deepClone$1),cursor_js_1=cursor,types_js_1=types;function assert(pred,msg){if(!pred)throw new Error(msg)}__name(assert,"assert"),exports2.type={name:"json1",uri:"http://sharejs.org/types/JSONv1",readCursor:cursor_js_1.readCursor,writeCursor:cursor_js_1.writeCursor,create:__name(data=>data,"create"),isNoop:__name(op=>op==null,"isNoop"),setDebug(val){},registerSubtype,checkValidOp,normalize,apply,transformPosition,compose,tryTransform,transform,makeInvertible,invert,invertWithDoc,RM_UNEXPECTED_CONTENT:types_js_1.ConflictType.RM_UNEXPECTED_CONTENT,DROP_COLLISION:types_js_1.ConflictType.DROP_COLLISION,BLACKHOLE:types_js_1.ConflictType.BLACKHOLE,transformNoConflict:__name((op1,op2,side)=>transformWithConflictsPred(()=>!0,op1,op2,side),"transformNoConflict"),typeAllowingConflictsPred:__name(allowConflict=>Object.assign(Object.assign({},exports2.type),{transform:__name((op1,op2,side)=>transformWithConflictsPred(allowConflict,op1,op2,side),"transform")}),"typeAllowingConflictsPred")};const getComponent=__name(r=>r?r.getComponent():null,"getComponent");function isObject2(o){return o&&typeof o=="object"&&!Array.isArray(o)}__name(isObject2,"isObject");const shallowClone=__name(obj=>Array.isArray(obj)?obj.slice():obj!==null&&typeof obj=="object"?Object.assign({},obj):obj,"shallowClone"),hasPick=__name(c=>c&&(c.p!=null||c.r!==void 0),"hasPick"),hasDrop=__name(c=>c&&(c.d!=null||c.i!==void 0),"hasDrop");function removeChild(container,key){return assert(container!=null),typeof key=="number"?(assert(Array.isArray(container),"Invalid key - child is not an array"),(container=container.slice()).splice(key,1)):(assert(isObject2(container),"Invalid key - child is not an object"),delete(container=Object.assign({},container))[key]),container}__name(removeChild,"removeChild");function insertChildMut(container,key,value){return typeof key=="number"?(assert(container!=null,"Container is missing for key"),assert(Array.isArray(container),"Cannot use numerical key for object container"),assert(container.length>=key,"Cannot insert into out of bounds index"),container.splice(key,0,value)):(assert(isObject2(container),"Cannot insert into missing item"),assert(container[key]===void 0,"Trying to overwrite value at key. Your op needs to remove it first"),container[key]=value),value}__name(insertChildMut,"insertChildMut"),exports2.removeOp=(path,value=!0)=>cursor_js_1.writeCursor().writeAtPath(path,"r",value).get(),exports2.moveOp=(from,to)=>cursor_js_1.writeCursor().writeMove(from,to).get(),exports2.insertOp=(path,value)=>cursor_js_1.writeCursor().writeAtPath(path,"i",value).get(),exports2.replaceOp=(path,oldVal,newVal)=>cursor_js_1.writeCursor().at(path,w=>{w.write("r",oldVal),w.write("i",newVal)}).get(),exports2.editOp=(path,type2,subOp,preserveNoop=!1)=>cursor_js_1.writeCursor().at(path,w=>writeEdit(w,type2,subOp,preserveNoop)).get();const isValidKey=__name((container,key)=>container!=null&&(typeof key=="number"?Array.isArray(container):typeof container=="object"),"isValidKey"),maybeGetChild=__name((container,key)=>isValidKey(container,key)?container[key]:void 0,"maybeGetChild"),subtypes={};function registerSubtype(subtype){let _subtype=subtype.type?subtype.type:subtype;_subtype.name&&(subtypes[_subtype.name]=_subtype),_subtype.uri&&(subtypes[_subtype.uri]=_subtype)}__name(registerSubtype,"registerSubtype");const typeOrThrow=__name(name=>{const type2=subtypes[name];if(type2)return type2;throw Error("Missing type: "+name)},"typeOrThrow");registerSubtype(requireDist());const add=__name((a,b)=>a+b,"add");registerSubtype({name:"number",apply:add,compose:add,invert:__name(n=>-n,"invert"),transform:__name(a=>a,"transform")});const getEditType=__name(c=>c==null?null:c.et?typeOrThrow(c.et):c.es?subtypes["text-unicode"]:c.ena!=null?subtypes.number:null,"getEditType"),getEdit=__name(c=>c.es?c.es:c.ena!=null?c.ena:c.e,"getEdit"),writeEdit=__name((w,typeOrName,edit,preserveNoop=!1)=>{const[type2,name]=typeof typeOrName=="string"?[typeOrThrow(typeOrName),typeOrName]:[typeOrName,typeOrName.name];!preserveNoop&&type2.isNoop&&type2.isNoop(edit)||(name==="number"?w.write("ena",edit):name==="text-unicode"?w.write("es",edit):(w.write("et",name),w.write("e",edit)))},"writeEdit");function checkNonNegInteger(n){assert(typeof n=="number"),assert(n>=0),assert(n===(0|n))}__name(checkNonNegInteger,"checkNonNegInteger");function checkScalar(s){typeof s=="number"?checkNonNegInteger(s):assert(typeof s=="string")}__name(checkScalar,"checkScalar");function checkValidOp(op){if(op===null)return;const pickedSlots=new Set,droppedSlots=new Set,checkComponent=__name(e=>{let empty=!0,hasEdit=!1;for(let k in e){const v=e[k];if(empty=!1,assert(k==="p"||k==="r"||k==="d"||k==="i"||k==="e"||k==="es"||k==="ena"||k==="et","Invalid component item '"+k+"'"),k==="p")checkNonNegInteger(v),assert(!pickedSlots.has(v)),pickedSlots.add(v),assert(e.r===void 0);else if(k==="d")checkNonNegInteger(v),assert(!droppedSlots.has(v)),droppedSlots.add(v),assert(e.i===void 0);else if(k==="e"||k==="es"||k==="ena"){assert(!hasEdit),hasEdit=!0;const t=getEditType(e);assert(t,"Missing type in edit"),t.checkValidOp&&t.checkValidOp(getEdit(e))}}assert(!empty)},"checkComponent"),checkDescent=__name((descent,isRoot,removed)=>{if(!Array.isArray(descent))throw Error("Op must be null or a list");if(descent.length===0)throw Error("Empty descent");isRoot||checkScalar(descent[0]);let last=1,numDescents=0,lastKey=0;for(let i=0;i<descent.length;i++){const d=descent[i];if(assert(d!=null),Array.isArray(d)){const key=checkDescent(d,!1);if(numDescents){const t1=typeof lastKey,t2=typeof key;t1===t2?assert(lastKey<key,"descent keys are not in order"):assert(t1==="number"&&t2==="string")}lastKey=key,numDescents++,last=3}else typeof d=="object"?(assert(last===1,`Prev not scalar - instead ${last}`),checkComponent(d),last=2):(assert(last!==3),checkScalar(d),assert(cursor_js_1.isValidPathItem(d),"Invalid path key"),last=1)}return assert(numDescents!==1,"Operation makes multiple descents. Remove some []"),assert(last===2||last===3),descent[0]},"checkDescent");checkDescent(op,!0),assert(pickedSlots.size===droppedSlots.size,"Mismatched picks and drops in op");for(let i=0;i<pickedSlots.size;i++)assert(pickedSlots.has(i)),assert(droppedSlots.has(i))}__name(checkValidOp,"checkValidOp");function normalize(op){let nextSlot=0,slotMap=[];const w=cursor_js_1.writeCursor();return w.mergeTree(op,(c,w2)=>{const t=getEditType(c);if(t){const op2=getEdit(c);writeEdit(w2,t,t.normalize?t.normalize(op2):op2)}for(const k of["r","p","i","d"])if(c[k]!==void 0){const r=k==="p"||k==="d"?(inSlot=c[k],slotMap[inSlot]==null&&(slotMap[inSlot]=nextSlot++),slotMap[inSlot]):c[k];w2.write(k,r)}var inSlot}),w.get()}__name(normalize,"normalize");function apply(snapshot,op){if(checkValidOp(op),op===null)return snapshot;const held=[];return __name(function drop(root,descent){let subDoc=root,i=0,rootContainer={root},m=0,container=rootContainer,key="root";function mut(){for(;m<i;m++){let d=descent[m];typeof d!="object"&&(assert(isValidKey(container,key)),container=container[key]=shallowClone(container[key]),key=d)}}for(__name(mut,"mut");i<descent.length;i++){const d=descent[i];if(Array.isArray(d)){const child=drop(subDoc,d);child!==subDoc&&child!==void 0&&(mut(),subDoc=container[key]=child)}else if(typeof d=="object"){d.d!=null?(mut(),subDoc=insertChildMut(container,key,held[d.d])):d.i!==void 0&&(mut(),subDoc=insertChildMut(container,key,d.i));const t=getEditType(d);if(t)mut(),subDoc=container[key]=t.apply(subDoc,getEdit(d));else if(d.e!==void 0)throw Error("Subtype "+d.et+" undefined")}else subDoc=maybeGetChild(subDoc,d)}return rootContainer.root},"drop")(snapshot=__name(function pick(subDoc,descent){const stack=[];let i=0;for(;i<descent.length;i++){const d=descent[i];if(Array.isArray(d))break;typeof d!="object"&&(stack.push(subDoc),subDoc=maybeGetChild(subDoc,d))}for(let j=descent.length-1;j>=i;j--)subDoc=pick(subDoc,descent[j]);for(--i;i>=0;i--){const d=descent[i];if(typeof d!="object"){const container=stack.pop();subDoc=subDoc===maybeGetChild(container,d)?container:subDoc===void 0?removeChild(container,d):(k=d,v=subDoc,(obj=shallowClone(obj=container))[k]=v,obj)}else hasPick(d)&&(assert(subDoc!==void 0,"Cannot pick up or remove undefined"),d.p!=null&&(held[d.p]=subDoc),subDoc=void 0)}var obj,k,v;return subDoc},"pick")(snapshot,op),op)}__name(apply,"apply");function transformPosition(path,op){path=path.slice(),checkValidOp(op);const r=cursor_js_1.readCursor(op);let pickedAtSlot,pickIndex,removed=!1;const advStack=[];for(let i=0;;i++){const k=path[i],c=r.getComponent();if(c&&(c.r!==void 0?removed=!0:c.p!=null&&(removed=!1,pickedAtSlot=c.p,pickIndex=i)),i>=path.length)break;let pickOffset=0;const pickAdv=cursor_js_1.advancer(r,void 0,(k2,c2)=>{hasPick(c2)&&pickOffset++});advStack.unshift(pickAdv);const hasNext=pickAdv(k);if(typeof k=="number"&&(path[i]-=pickOffset),!hasNext)break}if(advStack.forEach(pickAdv=>pickAdv.end()),removed)return null;const handleDrop=__name(()=>{let i=0;if(pickedAtSlot!=null){const rPath=r.getPath();i=rPath.length,path=rPath.concat(path.slice(pickIndex))}for(;i<path.length;i++){const k=path[i],c=getComponent(r),et=getEditType(c);if(et){const e=getEdit(c);et.transformPosition&&(path[i]=et.transformPosition(path[i],e));break}let dropOffset=0;const hasNext=cursor_js_1.advancer(r,(k2,c2)=>hasDrop(c2)?~(k2-dropOffset):k2-dropOffset,(k2,c2)=>{hasDrop(c2)&&dropOffset++})(k);if(typeof k=="number"&&(path[i]+=dropOffset),!hasNext)break}},"handleDrop");return pickedAtSlot!=null?r.eachDrop(null,slot=>{slot===pickedAtSlot&&handleDrop()}):handleDrop(),path}__name(transformPosition,"transformPosition");function compose(op1,op2){if(checkValidOp(op1),checkValidOp(op2),op1==null)return op2;if(op2==null)return op1;let nextSlot=0;const r1=cursor_js_1.readCursor(op1),r2=cursor_js_1.readCursor(op2),w=cursor_js_1.writeCursor(),heldPickWrites=[],heldDropWrites=[],held1Pick=[],held2Drop=[],p1SlotMap=[],p2SlotMap=[],visitedOp2EditCs=new Set;r1.traverse(null,c=>{c.p!=null&&(held1Pick[c.p]=r1.clone())}),r2.traverse(null,c=>{c.d!=null&&(held2Drop[c.d]=r2.clone())});const w2=cursor_js_1.writeCursor();return __name(function xfBoundary(r1Pick,r1Drop,r2Pick,r2Drop,litIn,rmParent,wd,wp){assert(r1Drop||r2Pick);const c1d=getComponent(r1Drop),c2p=getComponent(r2Pick),rmHere=!!c2p&&c2p.r!==void 0,insHere=!!c1d&&c1d.i!==void 0,drop1Slot=c1d?c1d.d:null,pick2Slot=c2p?c2p.p:null,rmChildren=(rmParent||rmHere)&&pick2Slot==null;if(pick2Slot!=null)r2Drop=held2Drop[pick2Slot],wd=heldDropWrites[pick2Slot]=new cursor_js_1.WriteCursor;else if(c2p&&c2p.r!==void 0)r2Drop=null;else{const c2d2=getComponent(r2Drop);c2d2&&c2d2.d!=null&&(r2Drop=null)}const c2d=getComponent(r2Drop);if(drop1Slot!=null)if(r1Pick=held1Pick[drop1Slot],wp=heldPickWrites[drop1Slot]=new cursor_js_1.WriteCursor,rmChildren)rmParent&&!rmHere&&wp.write("r",!0);else{const slot=p1SlotMap[drop1Slot]=nextSlot++;wd.write("d",slot)}else if(c1d&&c1d.i!==void 0)r1Pick=null;else{const c1p=getComponent(r1Pick);c1p&&c1p.p!=null&&(r1Pick=null)}let litOut;insHere?(assert(litIn===void 0),litOut=c1d.i):litOut=litIn;const insComponent=(pick2Slot==null?!insHere||rmParent||rmHere:litOut===void 0)?null:wd.getComponent();if(pick2Slot!=null){if(!(litIn!==void 0||insHere)){const slot=drop1Slot!=null?p1SlotMap[drop1Slot]:nextSlot++;p2SlotMap[pick2Slot]=slot,wp.write("p",slot)}}else rmHere&&(insHere||litIn!==void 0||(c2p.r,wp.write("r",c2p.r)));const type1=rmChildren?null:getEditType(c1d),type2=getEditType(c2d);if((type1||type2)&&(type1&&type1.name,type2&&type2.name),type1&&type2){assert(type1===type2);const e1=getEdit(c1d),e2=getEdit(c2d),r=type1.compose(e1,e2);writeEdit(wd,type1,r),visitedOp2EditCs.add(c2d)}else type1?writeEdit(wd,type1,getEdit(c1d)):type2&&(writeEdit(wd,type2,getEdit(c2d)),visitedOp2EditCs.add(c2d));const hasContainerLiteral=typeof litOut=="object"&&litOut!=null;let isCloned=!1,p1PickOff=0,p1DropOff=0,p2PickOff=0,p2DropOff=0,litOff=0;const p2DropAdv=cursor_js_1.advancer(r2Drop,(k,c)=>hasDrop(c)?p2DropOff-k-1:k-p2DropOff,(k,c)=>{hasDrop(c)&&p2DropOff++}),p1PickAdv=cursor_js_1.advancer(r1Pick,(k,c)=>hasPick(c)?p1PickOff-k-1:k-p1PickOff,(k,c)=>{hasPick(c)&&p1PickOff++});if(cursor_js_1.eachChildOf(r1Drop,r2Pick,(inKey,_p1Drop,_p2Pick)=>{let _p1Pick,_p2Drop,p1PickKey=inKey,p2DropKey=inKey,litKey=inKey;if(typeof inKey=="number"){let p2Mid=inKey+p2PickOff;_p2Drop=p2DropAdv(p2Mid),p2DropKey=p2Mid+p2DropOff;let p1Mid=inKey+p1DropOff;_p1Pick=p1PickAdv(p1Mid),hasDrop(getComponent(_p2Drop))&&(_p1Pick=null),p1PickKey=p1Mid+p1PickOff,litKey=inKey+litOff,assert(p1PickKey>=0,"p1PickKey is negative"),assert(p2DropKey>=0,"p2DropKey is negative");const hd1=hasDrop(getComponent(_p1Drop)),hp2=hasPick(getComponent(_p2Pick));(hd1||hp2&&!rmChildren)&&litOff--,hd1&&p1DropOff--,hp2&&p2PickOff--}else _p1Pick=p1PickAdv(inKey),_p2Drop=p2DropAdv(inKey);wp.descend(p1PickKey),wd.descend(p2DropKey);const _lit=hasContainerLiteral&&!hasDrop(getComponent(_p1Drop))?litOut[litKey]:void 0,_litResult=xfBoundary(_p1Pick,_p1Drop,_p2Pick,_p2Drop,_lit,rmChildren,wd,wp);var container,key,child;hasContainerLiteral&&!rmChildren?_lit!==_litResult&&(isCloned||(litOut=Array.isArray(litOut)?litOut.slice():Object.assign({},litOut),isCloned=!0),container=litOut,child=_litResult,typeof(key=litKey)=="number"?(assert(Array.isArray(container)),assert(key<container.length)):(assert(!Array.isArray(container)),assert(container[key]!==void 0)),child===void 0?typeof key=="number"?container.splice(key,1):delete container[key]:container[key]=child):assert(_litResult===void 0),wd.ascend(),wp.ascend()}),p1PickAdv.end(),p2DropAdv.end(),insComponent!=null)insComponent.i=litOut;else if(!rmParent&&!rmHere&&pick2Slot==null)return litOut},"xfBoundary")(r1,r1.clone(),r2,r2.clone(),void 0,!1,w,w2),w.reset(),w.mergeTree(w2.get()),w.reset(),w.get(),heldPickWrites.map(w3=>w3.get()),heldDropWrites.map(w3=>w3.get()),r1.traverse(w,(c,w3)=>{const slot1=c.p;if(slot1!=null){const slot=p1SlotMap[slot1];slot!=null&&w3.write("p",slot);const _w=heldPickWrites[slot1];_w&&_w.get(),_w&&w3.mergeTree(_w.get())}else c.r!==void 0&&w3.write("r",c.r)}),w.reset(),w.get(),r2.traverse(w,(c,w3)=>{const slot2=c.d;if(slot2!=null){const slot=p2SlotMap[slot2];slot!=null&&w3.write("d",slot);const _w=heldDropWrites[slot2];_w&&w3.mergeTree(_w.get())}else c.i!==void 0&&w3.write("i",c.i);const t=getEditType(c);t&&!visitedOp2EditCs.has(c)&&writeEdit(w3,t,getEdit(c))}),w.get()}__name(compose,"compose");function invert(op){if(op==null)return null;const r=new cursor_js_1.ReadCursor(op),w=new cursor_js_1.WriteCursor;let editsToTransform;const heldPick=[],heldWrites=[];return __name(function invertSimple(r2,w2,subDoc){const c=r2.getComponent();let insertHere,subdocModified=!1;if(c){c.p!=null&&(w2.write("d",c.p),heldPick[c.p]=r2.clone()),c.r!==void 0&&w2.write("i",c.r),c.d!=null&&(w2.write("p",c.d),subDoc=void 0),c.i!==void 0&&(subDoc=insertHere=c.i);const t=getEditType(c);t&&(subDoc===void 0?(editsToTransform||(editsToTransform=new Set),editsToTransform.add(c)):(getEdit(c),subDoc=t.apply(subDoc,getEdit(c)),subdocModified=!0))}let dropOff=0;for(const key of r2){w2.descend(key);const raw=typeof key=="number"?key-dropOff:key,childIn=maybeGetChild(subDoc,raw);hasDrop(r2.getComponent())&&dropOff++;const childOut=invertSimple(r2,w2,childIn);if(subDoc!==void 0&&childOut!==void 0){if(subdocModified||(subdocModified=!0,subDoc=shallowClone(subDoc)),!isValidKey(subDoc,raw))throw Error("Cannot modify child - invalid operation");subDoc[raw]=childOut}w2.ascend()}if(insertHere===void 0)return subdocModified?subDoc:void 0;w2.write("r",subDoc)},"invertSimple")(r,w,void 0),editsToTransform&&(w.reset(),__name(function transformEdits(rPick,rDrop,w2){const cd=rDrop.getComponent();if(cd){const dropSlot=cd.d;if(dropSlot!=null&&(rPick=heldPick[dropSlot],w2=heldWrites[dropSlot]=cursor_js_1.writeCursor()),editsToTransform.has(cd)){const t=getEditType(cd);if(!t.invert)throw Error(`Cannot invert subtype ${t.name}`);writeEdit(w2,t,t.invert(getEdit(cd)))}}let pickOff=0,dropOff=0;const ap=cursor_js_1.advancer(rPick,(k,c)=>hasPick(c)?pickOff-k-1:k-pickOff,(k,c)=>{hasPick(c)&&pickOff++});for(const key of rDrop)if(typeof key=="number"){const mid=key-dropOff,_rPick=ap(mid),raw=mid+pickOff;w2.descend(raw),transformEdits(_rPick,rDrop,w2),hasDrop(rDrop.getComponent())&&dropOff++,w2.ascend()}else w2.descend(key),transformEdits(ap(key),rDrop,w2),w2.ascend();ap.end()},"transformEdits")(r.clone(),r,w),heldWrites.length&&(w.reset(),r.traverse(w,(c,w2)=>{const slot=c.p;if(slot!=null){const _w=heldWrites[slot];_w&&_w.get(),_w&&w2.mergeTree(_w.get())}}))),w.get()}__name(invert,"invert");const anyComponent=__name((op,fn)=>op.some(c=>typeof c=="object"&&(Array.isArray(c)?anyComponent(c,fn):fn(c))),"anyComponent");function makeInvertible(op,doc){if(op==null||!anyComponent(op,c=>{var _a13;return c.r!==void 0||((_a13=getEditType(c))===null||_a13===void 0?void 0:_a13.makeInvertible)!=null}))return op;const r=new cursor_js_1.ReadCursor(op),w=new cursor_js_1.WriteCursor;let hasEdits=!1;const heldPick=[],heldDoc=[],traversePick=__name((r2,w2,subDoc)=>{const c=r2.getComponent();let modified=!1;if(c){c.d!=null&&w2.write("d",c.d),c.i!==void 0&&w2.write("i",c.i);const pickSlot=c.p;if(pickSlot!=null&&(heldPick[pickSlot]=r2.clone(),assert(subDoc!==void 0,"Operation picks up at an invalid key"),heldDoc[pickSlot]=subDoc,w2.write("p",c.p)),c.r!==void 0&&subDoc===void 0)throw Error("Invalid doc / op in makeInvertible: removed item missing from doc");const t=getEditType(c);t&&(t.makeInvertible?hasEdits=!0:writeEdit(w2,t,getEdit(c),!0))}let listOff=0;for(const key of r2){w2.descend(key);const keyRaw=typeof key=="number"?key-listOff:key,childIn=maybeGetChild(subDoc,keyRaw),childOut=traversePick(r2,w2,childIn);childIn!==childOut&&(modified||(modified=!0,subDoc=shallowClone(subDoc)),childOut===void 0?(subDoc=removeChild(subDoc,keyRaw),typeof key=="number"&&listOff++):subDoc[keyRaw]=childOut),w2.ascend()}return c&&(c.r!==void 0?(w2.write("r",deepClone_js_1.default(subDoc)),subDoc=void 0):c.p!=null&&(subDoc=void 0)),subDoc},"traversePick");return traversePick(r,w,doc),w.get(),hasEdits&&(w.reset(),__name(function traverseDrop(rPick,rDrop,w2,subDoc,isLiteral){const c=rDrop.getComponent();if(c){c.i!==void 0?(subDoc=c.i,isLiteral=!0):c.d!=null&&(subDoc=heldDoc[c.d],rPick=heldPick[c.d],isLiteral=!1,c.d);let t=getEditType(c);if(t&&t.makeInvertible){const edit=getEdit(c);writeEdit(w2,t,t.makeInvertible(edit,subDoc),!0)}}let pickOff=0,dropOff=0;const ap=cursor_js_1.advancer(rPick,(k,c2)=>hasPick(c2)?pickOff-k-1:k-pickOff,(k,c2)=>{hasPick(c2)&&pickOff++});for(const key of rDrop)if(typeof key=="number"){const mid=key-dropOff,_rPick=ap(mid),raw=mid+pickOff,child=maybeGetChild(subDoc,isLiteral?mid:raw);w2.descend(key),traverseDrop(_rPick,rDrop,w2,child,isLiteral),hasDrop(rDrop.getComponent())&&dropOff++,w2.ascend()}else{const child=maybeGetChild(subDoc,key);w2.descend(key),traverseDrop(ap(key),rDrop,w2,child,isLiteral),w2.ascend()}ap.end()},"traverseDrop")(r.clone(),r,w,doc,!1)),w.get()}__name(makeInvertible,"makeInvertible");function invertWithDoc(op,doc){return invert(makeInvertible(op,doc))}__name(invertWithDoc,"invertWithDoc");const shallowCloneOp=__name(op=>{if(op==null)return null;const result=op.slice();for(let i=0;i<op.length;i++){const c=result[i];Array.isArray(c)&&(result[i]=shallowCloneOp(c))}return result},"shallowCloneOp");function tryTransform(op1,op2,direction){assert(direction==="left"||direction==="right","Direction must be left or right");const side=direction==="left"?0:1;if(op2==null)return{ok:!0,result:op1};checkValidOp(op1),checkValidOp(op2);let conflict=null;const heldOp1PickByOp1=[],heldOp1DropByOp1=[],heldOp2PickByOp2=[],heldOp2DropByOp2=[],heldOp1PickByOp2=[],heldOp2PickByOp1=[],heldOp2DropByOp1=[],heldOp2RmForOp1=[],heldOp1RmForOp2=[],cancelledOp2=[],discardedOp2Drop=[],heldPickWrites=[],heldDropWrites=[],op1PickAtOp2Pick=[],op1PicksOp2DropSlots=[];let nextSlot=0;const r1=cursor_js_1.readCursor(op1),r2=cursor_js_1.readCursor(op2),w=cursor_js_1.writeCursor();if(__name(function scanOp2Pick(r2Pick,r1Pick=null,removed1){const c1=getComponent(r1Pick);c1&&(c1.r!==void 0?removed1=r1Pick.clone():c1.p!=null&&(removed1=null,heldOp2PickByOp1[c1.p]=r2Pick.clone()));const c2=r2Pick.getComponent();let slot2;c2&&(slot2=c2.p)!=null&&(heldOp1PickByOp2[slot2]=r1Pick?r1Pick.clone():null,heldOp2PickByOp2[slot2]=r2Pick.clone(),removed1&&(cancelledOp2[slot2]=!0,heldOp1RmForOp2[slot2]=removed1),c1&&c1.p!=null&&(op1PickAtOp2Pick[slot2]=c1.p));const ap1=cursor_js_1.advancer(r1Pick);for(const key of r2Pick)scanOp2Pick(r2Pick,ap1(key),removed1);ap1.end()},"scanOp2Pick")(r2,r1,null),__name(function scanOp2Drop(r1Pick,r2Pick,r2Drop,pickSlot1,removed1){const c2d=r2Drop.getComponent();let slot2,droppedHere=!1;c2d&&((slot2=c2d.d)!=null?(heldOp2DropByOp2[slot2]=r2Drop.clone(),pickSlot1!=null&&(op1PicksOp2DropSlots[pickSlot1]==null&&(op1PicksOp2DropSlots[pickSlot1]=[]),op1PicksOp2DropSlots[pickSlot1].push(slot2)),r1Pick=heldOp1PickByOp2[slot2]||null,r2Pick=heldOp2PickByOp2[slot2]||null,cancelledOp2[slot2]?(removed1&&(discardedOp2Drop[slot2]=!0),removed1=heldOp1RmForOp2[slot2]||null):!removed1||side!==1&&op1PickAtOp2Pick[slot2]!=null||conflict==null&&(conflict={type:types_js_1.ConflictType.RM_UNEXPECTED_CONTENT,op1:exports2.removeOp(removed1.getPath()),op2:exports2.moveOp(r2Pick.getPath(),r2Drop.getPath())}),droppedHere=!0):c2d.i!==void 0&&(r1Pick=r2Pick=null,droppedHere=!0,removed1&&conflict==null&&(conflict={type:types_js_1.ConflictType.RM_UNEXPECTED_CONTENT,op1:exports2.removeOp(removed1.getPath()),op2:exports2.insertOp(r2Drop.getPath(),c2d.i)})));const c1p=getComponent(r1Pick);c1p&&(c1p.r!==void 0?removed1=r1Pick.clone():c1p.p!=null&&(c1p.p,pickSlot1=c1p.p,removed1=null));const t2=getEditType(c2d);t2&&removed1&&conflict==null&&(conflict={type:types_js_1.ConflictType.RM_UNEXPECTED_CONTENT,op1:exports2.removeOp(removed1.getPath()),op2:exports2.editOp(r2Drop.getPath(),t2,getEdit(c2d),!0)});let p2PickOff=0,p2DropOff=0;const ap2=cursor_js_1.advancer(r2Pick,(k,c)=>hasPick(c)?p2PickOff-k-1:k-p2PickOff,(k,c)=>{hasPick(c)&&p2PickOff++}),ap1=cursor_js_1.advancer(r1Pick);for(const key of r2Drop)if(typeof key=="number"){const p2Mid=key-p2DropOff,_p2Pick=ap2(p2Mid);p2DropOff+=+scanOp2Drop(ap1(p2Mid+p2PickOff),_p2Pick,r2Drop,pickSlot1,removed1)}else{const _p2Pick=ap2(key);scanOp2Drop(ap1(key),_p2Pick,r2Drop,pickSlot1,removed1)}return ap2.end(),ap1.end(),droppedHere},"scanOp2Drop")(r1,r2,r2.clone(),null,null),heldOp2DropByOp2.map(x=>x&&x.get()),conflict)return{ok:!1,conflict};discardedOp2Drop.map(x=>!!x);const pickComponents=[];let cancelledRemoves=null;__name(function writeOp1Pick(r1Pick,r2Pick,r2Drop,w2,removed2){let iAmMoved=!1;const c2p=getComponent(r2Pick);if(hasPick(c2p)){const slot2=c2p.p;slot2!=null?(r2Drop=heldOp2DropByOp2[slot2],w2=heldPickWrites[slot2]=cursor_js_1.writeCursor(),iAmMoved=!0,removed2=null):(r2Drop=null,removed2=r2Pick.clone())}else hasDrop(getComponent(r2Drop))&&(r2Drop=null);const c1=r1Pick.getComponent();if(c1){const slot1=c1.p;slot1!=null?(removed2&&(heldOp2RmForOp1[slot1]=removed2),pickComponents[slot1]=removed2||side===1&&iAmMoved?null:w2.getComponent(),heldOp1PickByOp1[slot1]=r1Pick.clone(),r2Drop&&(heldOp2DropByOp1[slot1]=r2Drop.clone())):c1.r!==void 0&&(removed2||w2.write("r",!0),(removed2||iAmMoved)&&(cancelledRemoves==null&&(cancelledRemoves=new Set),cancelledRemoves.add(c1)))}let p2PickOff=0,p2DropOff=0;const ap2Pick=cursor_js_1.advancer(r2Pick,void 0,(k,c)=>{hasPick(c)&&p2PickOff++}),ap2Drop=cursor_js_1.advancer(r2Drop,(k,c)=>hasDrop(c)?~(k-p2DropOff):k-p2DropOff,(k,c)=>{hasDrop(c)&&p2DropOff++});if(r1Pick)for(const key of r1Pick)if(typeof key=="string"){const p2Pick_=ap2Pick(key),p2Drop_=ap2Drop(key);w2.descend(key),writeOp1Pick(r1Pick,p2Pick_,p2Drop_,w2,removed2),w2.ascend()}else{const p2Pick_=ap2Pick(key),p2Mid=key-p2PickOff,p2Drop_=hasPick(getComponent(p2Pick_))?null:ap2Drop(p2Mid),finalKey=p2Mid+p2DropOff;assert(finalKey>=0),w2.descend(finalKey),writeOp1Pick(r1Pick,p2Pick_,p2Drop_,w2,removed2),w2.ascend()}ap2Pick.end(),ap2Drop.end()},"writeOp1Pick")(r1,r2,r2.clone(),w,null),w.reset();let outputSlotMap=[];if(__name(function writeOp1Drop(p1Pick,p1Drop,p2Pick,p2Drop,w2,removed2){assert(p1Drop);const c1d=p1Drop.getComponent();let c2d=getComponent(p2Drop),droppedHere=!1;const insOrMv=__name((r12,r22,c)=>r12?exports2.moveOp(r12.getPath(),r22.getPath()):exports2.insertOp(r22.getPath(),c.i),"insOrMv");if(hasDrop(c1d)){const slot1=c1d.d;slot1!=null&&(heldOp1DropByOp1[slot1]=p1Drop.clone());const pc=slot1!=null?pickComponents[slot1]:null;let identical=!1;if(c1d.i!==void 0||slot1!=null&&pc){let slot2;c2d&&(c2d.i!==void 0||(slot2=c2d.d)!=null&&!cancelledOp2[slot2])&&(identical=slot2!=null?slot1!=null&&slot1===op1PickAtOp2Pick[slot2]:deepEqual_js_1.default(c2d.i,c1d.i),identical||slot2!=null&&side!==1&&op1PickAtOp2Pick[slot2]!=null||conflict==null&&(conflict={type:types_js_1.ConflictType.DROP_COLLISION,op1:insOrMv(slot1!=null?heldOp1PickByOp1[slot1]:null,p1Drop,c1d),op2:insOrMv(slot2!=null?heldOp2PickByOp2[slot2]:null,p2Drop,c2d)})),identical||(removed2?conflict==null&&(conflict={type:types_js_1.ConflictType.RM_UNEXPECTED_CONTENT,op1:insOrMv(slot1!=null?heldOp1PickByOp1[slot1]:null,p1Drop,c1d),op2:exports2.removeOp(removed2.getPath())}):(slot1!=null?(outputSlotMap[nextSlot]=slot1,w2.write("d",pc.p=nextSlot++)):w2.write("i",deepClone_js_1.default(c1d.i)),droppedHere=!0))}else if(slot1!=null&&!pc){const h=heldOp2RmForOp1[slot1];h&&(removed2=h.clone())}slot1!=null?(p1Pick=heldOp1PickByOp1[slot1],p2Pick=heldOp2PickByOp1[slot1],p2Drop=heldOp2DropByOp1[slot1]):c1d.i!==void 0&&(p1Pick=p2Pick=null,identical||(p2Drop=null))}else hasPick(getComponent(p1Pick))&&(p1Pick=p2Pick=p2Drop=null);const c1p=getComponent(p1Pick),c2p=getComponent(p2Pick);if(hasPick(c2p)){const slot2=c2p.p;c2p.r!==void 0&&(!c1p||c1p.r===void 0)||cancelledOp2[slot2]?(p2Drop=null,removed2=p2Pick.clone()):slot2!=null&&(p2Drop=heldOp2DropByOp2[slot2],side!==1&&op1PickAtOp2Pick[slot2]!=null||((w2=heldDropWrites[slot2])||(w2=heldDropWrites[slot2]=cursor_js_1.writeCursor()),w2.reset(),removed2=null))}else!hasDrop(c1d)&&hasDrop(c2d)&&(p2Drop=null);c2d=p2Drop!=null?p2Drop.getComponent():null;const t1=getEditType(c1d);if(t1){const e1=getEdit(c1d);if(removed2)conflict==null&&(conflict={type:types_js_1.ConflictType.RM_UNEXPECTED_CONTENT,op1:exports2.editOp(p1Drop.getPath(),t1,e1,!0),op2:exports2.removeOp(removed2.getPath())});else{const t2=getEditType(c2d);let e;if(t2){if(t1!==t2)throw Error("Transforming incompatible types");const e2=getEdit(c2d);e=t1.transform(e1,e2,direction)}else e=deepClone_js_1.default(e1);writeEdit(w2,t1,e)}}let p1PickOff=0,p1DropOff=0,p2PickOff=0,p2DropOff=0,outPickOff=0,outDropOff=0,p1pValid=p1Pick!=null&&p1Pick.descendFirst(),p1pDidDescend=p1pValid;const ap2p=cursor_js_1.advancer(p2Pick,void 0,(k,c)=>{hasPick(c)&&p2PickOff++});let p2dValid=p2Drop!=null&&p2Drop.descendFirst(),p2dDidDescend=p2dValid;for(const key of p1Drop)if(typeof key=="number"){let _p1Pick;const hd1=hasDrop(p1Drop.getComponent()),k1Mid=key-p1DropOff;{let p1k;for(;p1pValid&&typeof(p1k=p1Pick.getKey())=="number";){p1k+=p1PickOff;const c=p1Pick.getComponent(),hp=hasPick(c);if(p1k>k1Mid||p1k===k1Mid&&(!hp||side===0&&hd1))break;if(hp){p1PickOff--;const slot1=c.p;op1PickAtOp2Pick.includes(slot1),c.d,getComponent(heldDropWrites[c.d]),hasPick(getComponent(heldDropWrites[c.d])),(c.r===void 0||cancelledRemoves&&cancelledRemoves.has(c))&&(slot1==null||!pickComponents[slot1]||side!==1&&op1PickAtOp2Pick.includes(slot1))||outPickOff--}p1pValid=p1Pick.nextSibling()}_p1Pick=p1pValid&&p1k===k1Mid?p1Pick:null}const raw=k1Mid-p1PickOff;let _p2Pick=ap2p(raw);const k2Mid=raw-p2PickOff;let _p2Drop=null;{let p2dk,op2Mid;for(;p2dValid&&typeof(p2dk=p2Drop.getKey())=="number";){op2Mid=p2dk-p2DropOff;const c=p2Drop.getComponent(),hd2=hasDrop(c);if(op2Mid>k2Mid)break;if(op2Mid===k2Mid){if(!hd2){_p2Drop=p2Drop;break}{if(side===0&&hd1){_p2Drop=p2Drop;break}const hp2=_p2Pick&&hasPick(_p2Pick.getComponent());if(side===0&&hp2)break}}if(hd2){const slot2=c.d;op1PickAtOp2Pick[slot2],c.i===void 0&&(cancelledOp2[slot2]||op1PickAtOp2Pick[slot2]!=null&&side!==1)?(cancelledOp2[slot2]||op1PickAtOp2Pick[slot2]!=null&&side===0)&&(p2DropOff++,outDropOff--):p2DropOff++}p2dValid=p2Drop.nextSibling()}}const descend=k2Mid+p2DropOff+outPickOff+outDropOff;assert(descend>=0,"trying to descend to a negative index"),w2.descend(descend),hd1&&(_p1Pick=_p2Pick=_p2Drop=null,p1DropOff++),writeOp1Drop(_p1Pick,p1Drop,_p2Pick,_p2Drop,w2,removed2)&&outDropOff++,w2.ascend()}else{let p1k;for(;p1pValid&&(p1k=p1Pick.getKey(),typeof p1k!="string"||!(p1k>key||p1k===key));)p1pValid=p1Pick.nextSibling();const _p1Pick=p1pValid&&p1k===key?p1Pick:null,_p2Pick=ap2p(key);let p2dk;for(;p2dValid&&(p2dk=p2Drop.getKey(),typeof p2dk!="string"||!(p2dk>key||p2dk===key));)p2dValid=p2Drop.nextSibling();const _p2Drop=p2dValid&&p2dk===key?p2Drop:null;w2.descend(key),writeOp1Drop(_p1Pick,p1Drop,_p2Pick,_p2Drop,w2,removed2),w2.ascend()}return ap2p.end(),p1pDidDescend&&p1Pick.ascend(),p2dDidDescend&&p2Drop.ascend(),droppedHere},"writeOp1Drop")(r1,r1.clone(),r2,r2.clone(),w,null),conflict)return{ok:!1,conflict};w.reset();const eachDrop=__name((r,w2,fn)=>r.traverse(w2,(c,w3)=>{c.d!=null&&fn(c.d,r,w3)}),"eachDrop");(cancelledOp2.length||heldPickWrites.length)&&(eachDrop(r2,w,(slot2,r,w2)=>{cancelledOp2[slot2]&&!discardedOp2Drop[slot2]&&w2.write("r",!0),heldPickWrites[slot2]&&w2.mergeTree(heldPickWrites[slot2].get())}),w.reset());const heldOutDropRead=[],heldOutDropWrites=[];if((heldDropWrites.length||cancelledOp2.length)&&!conflict){const rOut=cursor_js_1.readCursor(shallowCloneOp(w.get()));if(eachDrop(rOut,null,(slotOut,r)=>{heldOutDropRead[slotOut]=r.clone()}),heldDropWrites.forEach(hdw=>{hdw&&eachDrop(cursor_js_1.readCursor(hdw.get()),null,(slotOut,r)=>{heldOutDropRead[slotOut]=r.clone()})}),__name(function writeHeldOp2Drop(p2Drop,outPick,outDrop,w2,parentC,removedOut){const coutp=getComponent(outPick);if(coutp&&hasPick(coutp))if(coutp.p!=null){const slot=coutp.p;heldOutDropRead[slot].getPath(),outDrop=heldOutDropRead[slot],w2=heldOutDropWrites[slot]=cursor_js_1.writeCursor()}else coutp.r!==void 0&&(outDrop=null);else hasDrop(getComponent(outDrop))&&(outDrop=null);const c2=p2Drop.getComponent();if(c2){let slot2;if((slot2=c2.d)!=null){const _w=heldDropWrites[slot2];_w&&(_w.get(),w2.mergeTree(_w.get()),outDrop=cursor_js_1.readCursor(_w.get()))}}let outPickOff=0,outDropOff=0;const oPickAdv=cursor_js_1.advancer(outPick,void 0,(k,c)=>{hasPick(c)&&outPickOff--}),oDropAdv=cursor_js_1.advancer(outDrop,(k,c)=>hasDrop(c)?-(k-outDropOff)-1:k-outDropOff,(k,c)=>{hasDrop(c)&&outDropOff++});for(const o2dk of p2Drop)if(typeof o2dk=="number"){const _outPick=oPickAdv(o2dk),rmid=o2dk+outPickOff,_outDrop=oDropAdv(rmid),rfinal=rmid+outDropOff;w2.descend(rfinal),writeHeldOp2Drop(p2Drop,_outPick,_outDrop,w2),w2.ascend()}else w2.descend(o2dk),writeHeldOp2Drop(p2Drop,oPickAdv(o2dk),oDropAdv(o2dk),w2),w2.ascend();oPickAdv.end(),oDropAdv.end()},"writeHeldOp2Drop")(r2,rOut,rOut.clone(),w),w.reset(),conflict)return{ok:!1,conflict};if(w.get(),heldOutDropWrites.length){const heldOutDropContent=heldOutDropWrites.map(w2=>w2?w2.get():null),rOut2=cursor_js_1.readCursor(shallowCloneOp(w.get()));if(eachDrop(rOut2,w,(slotOut,r,w2)=>{const data=heldOutDropContent[slotOut];data&&(w2.mergeTree(data),heldOutDropContent[slotOut]=null)}),heldOutDropContent.find(x=>x)){const w1=cursor_js_1.writeCursor(),w2=cursor_js_1.writeCursor();let nextSlot1=0,nextSlot2=0;heldOutDropContent.forEach(data=>{data!=null&&eachDrop(cursor_js_1.readCursor(data),null,c=>{const slot1=outputSlotMap[c];w1.writeMove(heldOp1PickByOp1[slot1].getPath(),heldOp1DropByOp1[slot1].getPath(),nextSlot1++);const slot2s=op1PicksOp2DropSlots[slot1];slot2s&&slot2s.forEach(slot2=>{cancelledOp2[slot2]||side!==1&&op1PickAtOp2Pick[slot2]!=null||w2.writeMove(heldOp2PickByOp2[slot2].getPath(),heldOp2DropByOp2[slot2].getPath(),nextSlot2++)})})}),conflict={type:types_js_1.ConflictType.BLACKHOLE,op1:w1.get(),op2:w2.get()}}}}return conflict?{ok:!1,conflict}:{ok:!0,result:w.get()}}__name(tryTransform,"tryTransform");const throwConflictErr=__name(conflict=>{const err=new Error("Transform detected write conflict");throw err.conflict=conflict,err.type=err.name="writeConflict",err},"throwConflictErr");function transform(op1,op2,side){const res=tryTransform(op1,op2,side);if(res.ok)return res.result;throwConflictErr(res.conflict)}__name(transform,"transform");const opThatRemovesDE=__name(op=>{const w=cursor_js_1.writeCursor();return cursor_js_1.readCursor(op).traverse(w,(c,w2)=>{(hasDrop(c)||getEditType(c))&&w2.write("r",!0)}),w.get()},"opThatRemovesDE"),resolveConflict=__name((conflict,side)=>{const{type:type2,op1,op2}=conflict;switch(type2){case types_js_1.ConflictType.DROP_COLLISION:return side==="left"?[null,opThatRemovesDE(op2)]:[opThatRemovesDE(op1),null];case types_js_1.ConflictType.RM_UNEXPECTED_CONTENT:let op1HasRemove=!1;return cursor_js_1.readCursor(op1).traverse(null,c=>{c.r!==void 0&&(op1HasRemove=!0)}),op1HasRemove?[null,opThatRemovesDE(op2)]:[opThatRemovesDE(op1),null];case types_js_1.ConflictType.BLACKHOLE:return[opThatRemovesDE(op1),opThatRemovesDE(op2)];default:throw Error("Unrecognised conflict: "+type2)}},"resolveConflict");function transformWithConflictsPred(allowConflict,op1,op2,side){let r2Aggregate=null;for(;;){const res=tryTransform(op1,op2,side);if(res.ok)return compose(r2Aggregate,res.result);{const{conflict}=res;allowConflict(conflict)||throwConflictErr(conflict);const[r1,r2]=resolveConflict(conflict,side);op1=compose(normalize(op1),r1),op2=compose(normalize(op2),r2),r2Aggregate=compose(r2Aggregate,r2)}}}__name(transformWithConflictsPred,"transformWithConflictsPred")})(json1_release);(function(exports2){var __createBinding=commonjsGlobal&&commonjsGlobal.__createBinding||(Object.create?function(o,m,k,k2){k2===void 0&&(k2=k),Object.defineProperty(o,k2,{enumerable:!0,get:__name(function(){return m[k]},"get")})}:function(o,m,k,k2){k2===void 0&&(k2=k),o[k2]=m[k]}),__exportStar=commonjsGlobal&&commonjsGlobal.__exportStar||function(m,exports3){for(var p in m)p!=="default"&&!exports3.hasOwnProperty(p)&&__createBinding(exports3,m,p)};Object.defineProperty(exports2,"__esModule",{value:!0}),__exportStar(json1_release,exports2);var cursor_js_1=cursor;Object.defineProperty(exports2,"ReadCursor",{enumerable:!0,get:__name(function(){return cursor_js_1.ReadCursor},"get")}),Object.defineProperty(exports2,"WriteCursor",{enumerable:!0,get:__name(function(){return cursor_js_1.WriteCursor},"get")});var types_1=types;Object.defineProperty(exports2,"ConflictType",{enumerable:!0,get:__name(function(){return types_1.ConflictType},"get")})})(dist$1);const index=getDefaultExportFromCjs(dist$1),index$1=_mergeNamespaces({__proto__:null,default:index},[dist$1]);var TextXActionType=(TextXActionType2=>(TextXActionType2.RETAIN="r",TextXActionType2.INSERT="i",TextXActionType2.DELETE="d",TextXActionType2))(TextXActionType||{});const _ActionIterator=class _ActionIterator{constructor(_actions){__publicField(this,"_index",0);__publicField(this,"_offset",0);this._actions=_actions}hasNext(){return this.peekLength()<Number.POSITIVE_INFINITY}next(length){length||(length=Number.POSITIVE_INFINITY);const nextAction=this._actions[this._index];if(nextAction){const offset=this._offset,actionLength=nextAction.len;return length>=actionLength-offset?(length=actionLength-offset,this._index+=1,this._offset=0):this._offset+=length,nextAction.t===TextXActionType.DELETE||nextAction.t===TextXActionType.RETAIN&&nextAction.body==null?Tools.deepClone({...nextAction,len:length}):Tools.deepClone({...nextAction,len:length,body:getBodySlice(nextAction.body,offset,offset+length)})}else return{t:TextXActionType.RETAIN,len:Number.POSITIVE_INFINITY}}peek(){return this._actions[this._index]}peekLength(){return this._actions[this._index]?this._actions[this._index].len-this._offset:Number.POSITIVE_INFINITY}peekType(){const action=this._actions[this._index];return action?action.t:TextXActionType.RETAIN}rest(){if(this.hasNext()){if(this._offset===0)return this._actions.slice(this._index);{const offset=this._offset,index2=this._index,next=this.next(),restActions=this._actions.slice(this._index);return this._offset=offset,this._index=index2,[next].concat(restActions)}}else return[]}};__name(_ActionIterator,"ActionIterator");let ActionIterator=_ActionIterator;const _MemoryCursor=class _MemoryCursor{constructor(){__publicField(this,"cursor",0)}reset(){return this.cursor=0,this}moveCursor(pos){this.cursor+=pos}moveCursorTo(pos){this.cursor=pos}};__name(_MemoryCursor,"MemoryCursor");let MemoryCursor=_MemoryCursor;function updateAttributeByDelete(body,textLength,currentIndex){const{dataStream}=body,startIndex=currentIndex,endIndex=currentIndex+textLength,removeTextRuns=deleteTextRuns(body,textLength,currentIndex),removeParagraphs=deleteParagraphs(body,textLength,currentIndex),removeSectionBreaks=deleteSectionBreaks(body,textLength,currentIndex),removeCustomBlocks=deleteCustomBlocks(body,textLength,currentIndex),removeTables=deleteTables(body,textLength,currentIndex),removeCustomRanges=deleteCustomRanges(body,textLength,currentIndex),removeCustomDecorations=deleteCustomDecorations(body,textLength,currentIndex);let removeDataStream="";return dataStream&&(body.dataStream=deleteContent(dataStream,startIndex,endIndex),removeDataStream=dataStream.slice(startIndex,endIndex)),{dataStream:removeDataStream,textRuns:removeTextRuns,paragraphs:removeParagraphs,sectionBreaks:removeSectionBreaks,customBlocks:removeCustomBlocks,tables:removeTables,customRanges:removeCustomRanges,customDecorations:removeCustomDecorations}}__name(updateAttributeByDelete,"updateAttributeByDelete");function updateAttributeByInsert(body,insertBody,textLength,currentIndex){body.dataStream=insertTextToContent(body.dataStream,currentIndex,insertBody.dataStream),insertTextRuns(body,insertBody,textLength,currentIndex),insertParagraphs(body,insertBody,textLength,currentIndex),insertSectionBreaks(body,insertBody,textLength,currentIndex),insertCustomBlocks(body,insertBody,textLength,currentIndex),insertTables(body,insertBody,textLength,currentIndex),insertCustomRanges(body,insertBody,textLength,currentIndex),insertCustomDecorations(body,insertBody,textLength,currentIndex)}__name(updateAttributeByInsert,"updateAttributeByInsert");function updateApply(doc,updateBody,textLength,currentIndex,coverType=UpdateDocsAttributeType.COVER){return updateAttribute(doc,updateBody,textLength,currentIndex,coverType)}__name(updateApply,"updateApply");function deleteApply(doc,textLength,currentIndex){return textLength<=0?{dataStream:""}:updateAttributeByDelete(doc,textLength,currentIndex)}__name(deleteApply,"deleteApply");function insertApply(doc,insertBody,textLength,currentIndex){textLength!==0&&updateAttributeByInsert(doc,insertBody,textLength,currentIndex)}__name(insertApply,"insertApply");function textXApply(doc,actions){const memoryCursor=new MemoryCursor;return memoryCursor.reset(),actions.forEach(action=>{const clonedAction=Tools.deepClone(action);switch(clonedAction.t){case TextXActionType.RETAIN:{const{coverType,body,len}=clonedAction;body!=null&&updateApply(doc,body,len,memoryCursor.cursor,coverType),memoryCursor.moveCursor(len);break}case TextXActionType.INSERT:{const{body,len}=clonedAction;insertApply(doc,body,len,memoryCursor.cursor),memoryCursor.moveCursor(len);break}case TextXActionType.DELETE:{const{len}=clonedAction;deleteApply(doc,len,memoryCursor.cursor);break}default:throw new Error(`Unknown action type for action: ${clonedAction}.`)}}),doc}__name(textXApply,"textXApply");function transformTextRuns(originTextRuns,targetTextRuns,transformType){if(originTextRuns.length===0)return targetTextRuns;targetTextRuns=core.Tools.deepClone(targetTextRuns),originTextRuns=core.Tools.deepClone(originTextRuns);const newUpdateTextRuns=[],updateLength=targetTextRuns.length,removeLength=originTextRuns.length;let updateIndex=0,removeIndex=0,pending=null;function pushPendingAndReturnStatus(){return pending?(newUpdateTextRuns.push(pending),pending=null,!0):!1}for(__name(pushPendingAndReturnStatus,"pushPendingAndReturnStatus");updateIndex<updateLength&&removeIndex<removeLength;){const{st:updateSt,ed:updateEd,ts:targetStyle}=targetTextRuns[updateIndex],{st:removeSt,ed:removeEd,ts:originStyle,sId}=originTextRuns[removeIndex];let newTs={};if(transformType===0)newTs={...targetStyle};else if(newTs={...targetStyle},originStyle){const keys=Object.keys(originStyle);for(const key of keys)newTs[key]&&delete newTs[key]}if(updateEd<removeSt)pushPendingAndReturnStatus()||newUpdateTextRuns.push(targetTextRuns[updateIndex]),updateIndex++;else if(removeEd<updateSt)pushPendingAndReturnStatus()||newUpdateTextRuns.push(originTextRuns[removeIndex]),removeIndex++;else{const newTextRun={st:Math.min(updateSt,removeSt),ed:Math.max(updateSt,removeSt),ts:updateSt<removeSt?{...targetStyle}:{...originStyle},sId:updateSt<removeSt?void 0:sId};newTextRun.ed>newTextRun.st&&newUpdateTextRuns.push(),newUpdateTextRuns.push({st:Math.max(updateSt,removeSt),ed:Math.min(updateEd,removeEd),ts:newTs,sId}),updateEd<removeEd?(updateIndex++,originTextRuns[removeIndex].st=updateEd,originTextRuns[removeIndex].st===originTextRuns[removeIndex].ed&&removeIndex++):(removeIndex++,targetTextRuns[updateIndex].st=removeEd,targetTextRuns[updateIndex].st===targetTextRuns[updateIndex].ed&&updateIndex++);const pendingTextRun={st:Math.min(updateEd,removeEd),ed:Math.max(updateEd,removeEd),ts:updateEd<removeEd?{...originStyle}:{...targetStyle},sId:updateEd<removeEd?sId:void 0};pending=pendingTextRun.ed>pendingTextRun.st?pendingTextRun:null}}pushPendingAndReturnStatus();const tempTopTextRun=newUpdateTextRuns[newUpdateTextRuns.length-1],updateLastTextRun=targetTextRuns[updateLength-1],removeLastTextRun=originTextRuns[removeLength-1];return tempTopTextRun.ed!==Math.max(updateLastTextRun.ed,removeLastTextRun.ed)&&(updateLastTextRun.ed>removeLastTextRun.ed?newUpdateTextRuns.push(updateLastTextRun):newUpdateTextRuns.push(removeLastTextRun)),core.normalizeTextRuns(newUpdateTextRuns)}__name(transformTextRuns,"transformTextRuns");function transformParagraph(originParagraph,targetParagraph,transformType){const paragraph={startIndex:targetParagraph.startIndex};if(targetParagraph.paragraphStyle){if(originParagraph.paragraphStyle==null)paragraph.paragraphStyle={...targetParagraph.paragraphStyle};else if(paragraph.paragraphStyle={...targetParagraph.paragraphStyle},transformType===1){const keys=Object.keys(originParagraph.paragraphStyle);for(const key of keys)paragraph.paragraphStyle[key]&&delete paragraph.paragraphStyle[key]}}return targetParagraph.bullet&&(originParagraph.bullet==null||transformType===0)&&(paragraph.bullet={...targetParagraph.bullet}),paragraph}__name(transformParagraph,"transformParagraph");function transformBody(thisAction,otherAction,priority=!1){const{body:thisBody}=thisAction,{body:otherBody}=otherAction;if(thisBody==null||thisBody.dataStream!==""||otherBody==null||otherBody.dataStream!=="")throw new Error("Data stream is not supported in transform.");const retBody={dataStream:""},{textRuns:thisTextRuns=[],paragraphs:thisParagraphs=[]}=thisBody,{textRuns:otherTextRuns=[],paragraphs:otherParagraphs=[]}=otherBody;let textRuns=[];priority?textRuns=transformTextRuns(thisTextRuns,otherTextRuns,1):textRuns=transformTextRuns(thisTextRuns,otherTextRuns,0),textRuns.length&&(retBody.textRuns=textRuns);const paragraphs=[];let thisIndex=0,otherIndex=0;for(;thisIndex<thisParagraphs.length&&otherIndex<otherParagraphs.length;){const thisParagraph=thisParagraphs[thisIndex],otherParagraph=otherParagraphs[otherIndex],{startIndex:thisStart}=thisParagraph,{startIndex:otherStart}=otherParagraph;if(thisStart===otherStart){let paragraph={startIndex:thisStart};priority?paragraph=transformParagraph(thisParagraph,otherParagraph,1):paragraph=transformParagraph(thisParagraph,otherParagraph,0),paragraphs.push(paragraph),thisIndex++,otherIndex++}else thisStart<otherStart?thisIndex++:(paragraphs.push(core.Tools.deepClone(otherParagraph)),otherIndex++)}return otherIndex<otherParagraphs.length&&paragraphs.push(...otherParagraphs.slice(otherIndex)),paragraphs.length&&(retBody.paragraphs=paragraphs),retBody}__name(transformBody,"transformBody");function onlyHasDataStream(body){return Object.keys(body).length===1}__name(onlyHasDataStream,"onlyHasDataStream");const _TextX=class _TextX{constructor(){__publicField(this,"_actions",[])}static apply(doc,actions){return textXApply(doc,actions)}static compose(thisActions,otherActions){const thisIter=new ActionIterator(thisActions),otherIter=new ActionIterator(otherActions),textX=new _TextX;for(;thisIter.hasNext()||otherIter.hasNext();)if(otherIter.peekType()===TextXActionType.INSERT)textX.push(otherIter.next());else if(thisIter.peekType()===TextXActionType.DELETE)textX.push(thisIter.next());else{const length=Math.min(thisIter.peekLength(),otherIter.peekLength()),thisAction=thisIter.next(length),otherAction=otherIter.next(length);thisAction.t===TextXActionType.INSERT&&otherAction.t===TextXActionType.RETAIN?otherAction.body==null?textX.push(thisAction):textX.push({...thisAction,body:composeBody(thisAction.body,otherAction.body,otherAction.coverType)}):thisAction.t===TextXActionType.RETAIN&&otherAction.t===TextXActionType.RETAIN?thisAction.body==null&&otherAction.body==null?textX.push(thisAction.len!==Number.POSITIVE_INFINITY?thisAction:otherAction):thisAction.body&&otherAction.body?textX.push({...thisAction,body:composeBody(thisAction.body,otherAction.body,otherAction.coverType)}):textX.push(thisAction.body?thisAction:otherAction):thisAction.t===TextXActionType.RETAIN&&otherAction.t===TextXActionType.DELETE?textX.push(otherAction):thisAction.t===TextXActionType.INSERT&&(otherAction.t,TextXActionType.DELETE)}return textX.trimEndUselessRetainAction(),textX.serialize()}static transform(thisActions,otherActions,priority="right"){return this._transform(otherActions,thisActions,priority==="left"?"right":"left")}static _transform(thisActions,otherActions,priority="right"){var _a13;const thisIter=new ActionIterator(thisActions),otherIter=new ActionIterator(otherActions),textX=new _TextX;for(;thisIter.hasNext()||otherIter.hasNext();)if(thisIter.peekType()===TextXActionType.INSERT&&(priority==="left"||otherIter.peekType()!==TextXActionType.INSERT)){const thisAction=thisIter.next();textX.retain(thisAction.len,(_a13=thisAction.segmentId)!=null?_a13:"")}else if(otherIter.peekType()===TextXActionType.INSERT)textX.push(otherIter.next());else{const length=Math.min(thisIter.peekLength(),otherIter.peekLength()),thisAction=thisIter.next(length),otherAction=otherIter.next(length);if(thisAction.t===TextXActionType.DELETE)continue;if(otherAction.t===TextXActionType.DELETE){textX.push(otherAction);continue}thisAction.body==null||otherAction.body==null?textX.push(otherAction):textX.push({...otherAction,body:transformBody(thisAction,otherAction,priority==="left")})}return textX.trimEndUselessRetainAction(),textX.serialize()}static transformPosition(thisActions,index2,priority=!1){const thisIter=new ActionIterator(thisActions);let offset=0;for(;thisIter.hasNext()&&offset<=index2;){const length=thisIter.peekLength(),nextType=thisIter.peekType();if(thisIter.next(),nextType===TextXActionType.DELETE){index2-=Math.min(length,index2-offset);continue}else nextType===TextXActionType.INSERT&&(offset<index2||!priority)&&(index2+=length);offset+=length}return index2}static isNoop(actions){return actions.length===0}static invert(actions){const invertedActions=[];for(const action of actions)if(action.t===TextXActionType.INSERT)invertedActions.push({t:TextXActionType.DELETE,len:action.len,line:0,body:action.body,segmentId:action.segmentId});else if(action.t===TextXActionType.DELETE){if(action.body==null)throw new Error("Can not invert DELETE action without body property, makeInvertible must be called first.");invertedActions.push({t:TextXActionType.INSERT,body:action.body,len:action.len,line:0,segmentId:action.segmentId})}else if(action.body!=null){if(action.oldBody==null)throw new Error("Can not invert RETAIN action without oldBody property, makeInvertible must be called first.");invertedActions.push({t:TextXActionType.RETAIN,body:action.oldBody,oldBody:action.body,len:action.len,coverType:UpdateDocsAttributeType.REPLACE,segmentId:action.segmentId})}else invertedActions.push(action);return invertedActions}static makeInvertible(actions,doc){const invertibleActions=[];let index2=0;for(const action of actions){if(action.t===TextXActionType.DELETE&&action.body==null){const body=getBodySlice(doc,index2,index2+action.len,!1);action.len=body.dataStream.length,action.body=body}if(action.t===TextXActionType.RETAIN&&action.body!=null){const body=getBodySlice(doc,index2,index2+action.len,!0);action.oldBody={...body,dataStream:""},action.len=body.dataStream.length}invertibleActions.push(action),action.t!==TextXActionType.INSERT&&(index2+=action.len)}return invertibleActions}insert(len,body,segmentId=""){const insertAction={t:TextXActionType.INSERT,body,len,line:0,segmentId};return this.push(insertAction),this}retain(len,segmentId="",body,coverType){const retainAction={t:TextXActionType.RETAIN,len,segmentId};return body!=null&&(retainAction.body=body),coverType!=null&&(retainAction.coverType=coverType),this.push(retainAction),this}delete(len,segmentId=""){const deleteAction={t:TextXActionType.DELETE,len,line:0,segmentId};return this.push(deleteAction),this}empty(){return this._actions=[],this}serialize(){return this._actions}push(...args){if(args.length>1){for(const ac of args)this.push(ac);return this}let index2=this._actions.length,lastAction=this._actions[index2-1];const newAction=Tools.deepClone(args[0]);if(newAction.t===TextXActionType.RETAIN&&newAction.len===0&&newAction.body==null)return this;if(typeof lastAction=="object"){if(lastAction.t===TextXActionType.DELETE&&newAction.t===TextXActionType.DELETE)return lastAction.len+=newAction.len,this;if(lastAction.t===TextXActionType.DELETE&&newAction.t===TextXActionType.INSERT&&(index2-=1,lastAction=this._actions[index2-1],lastAction==null))return this._actions.unshift(newAction),this;if(lastAction.t===TextXActionType.RETAIN&&newAction.t===TextXActionType.RETAIN&&lastAction.body==null&&newAction.body==null)return lastAction.len+=newAction.len,this;if(lastAction.t===TextXActionType.INSERT&&onlyHasDataStream(lastAction.body)&&newAction.t===TextXActionType.INSERT&&onlyHasDataStream(newAction.body))return lastAction.len+=newAction.len,lastAction.body.dataStream+=newAction.body.dataStream,this}return index2===this._actions.length?this._actions.push(newAction):this._actions.splice(index2,0,newAction),this}trimEndUselessRetainAction(){let lastAction=this._actions[this._actions.length-1];for(;lastAction&&lastAction.t===TextXActionType.RETAIN&&isUselessRetainAction(lastAction);)this._actions.pop(),lastAction=this._actions[this._actions.length-1];return this}};__name(_TextX,"TextX"),__publicField(_TextX,"id","text-x"),__publicField(_TextX,"uri","https://github.com/dream-num/univer#text-x");let TextX=_TextX;Object.defineProperty(TextX,"name",{value:"text-x"});const _JSONX=class _JSONX{static registerSubtype(subType){var _a13;subType==null||this._subTypes.has(subType.name)&&((_a13=this._subTypes.get(subType.name))==null?void 0:_a13.id)!==TextX.id||(this._subTypes.set(subType.name,subType),dist$1.type.registerSubtype(subType))}static apply(doc,actions){if(!dist$1.type.isNoop(actions))return dist$1.type.apply(doc,actions)}static compose(thisActions,otherActions){return dist$1.type.compose(thisActions,otherActions)}static transform(thisActions,otherActions,priority){return dist$1.type.transform(thisActions,otherActions,priority)}static transformPosition(thisActions,index2,priority="right"){return thisActions&&thisActions.length===2&&thisActions[0]==="body"&&thisActions[1].et===TextX.name?TextX.transformPosition(thisActions[1].e,index2,priority==="left"):index2}static invertWithDoc(actions,doc){return dist$1.type.invertWithDoc(actions,doc)}static isNoop(actions){return dist$1.type.isNoop(actions)}static getInstance(){return this._instance==null&&(this._instance=new _JSONX),this._instance}removeOp(path,value){return dist$1.removeOp(path,value)}moveOp(from,to){return dist$1.moveOp(from,to)}insertOp(path,value){return dist$1.insertOp(path,value)}replaceOp(path,oldVal,newVal){return dist$1.replaceOp(path,oldVal,newVal)}editOp(subOp,path=["body"]){return dist$1.editOp(path,TextX.name,subOp)}};__name(_JSONX,"JSONX"),__publicField(_JSONX,"uri","https://github.com/dream-num/univer#json-x"),__publicField(_JSONX,"_subTypes",new Map),__publicField(_JSONX,"_instance",null);let JSONX=_JSONX;JSONX.registerSubtype(TextX);const DEFAULT_DOC={id:"default_doc",documentStyle:{}},_DocumentDataModelSimple=class _DocumentDataModelSimple extends UnitModel{constructor(snapshot){var _a13;super();__publicField(this,"type",I.UNIVER_DOC);__publicField(this,"_name$",new rxjs.BehaviorSubject(""));__publicField(this,"name$",this._name$.asObservable());__publicField(this,"snapshot");this.snapshot={...DEFAULT_DOC,...snapshot},this._name$.next((_a13=this.snapshot.title)!=null?_a13:"No Title")}getUnitId(){throw new Error("Method not implemented.")}setName(name){this.snapshot.title=name,this._name$.next(name)}get drawings(){return this.snapshot.drawings}get documentStyle(){return this.snapshot.documentStyle}get lists(){return this.snapshot.lists}get zoomRatio(){var _a13;return((_a13=this.snapshot.settings)==null?void 0:_a13.zoomRatio)||1}resetDrawing(drawings,drawingsOrder){this.snapshot.drawings=drawings,this.snapshot.drawingsOrder=drawingsOrder}getBody(){return this.snapshot.body}getSnapshot(){return this.snapshot}getBulletPresetList(){var _a13;const customLists=(_a13=this.snapshot.lists)!=null?_a13:{};return{...PRESET_LIST_TYPE,...customLists}}updateDocumentId(unitId){this.snapshot.id=unitId}updateDocumentRenderConfig(config){const{documentStyle}=this.snapshot;documentStyle.renderConfig==null?documentStyle.renderConfig=config:documentStyle.renderConfig={...documentStyle.renderConfig,...config}}updateDocumentStyle(config){this.snapshot.documentStyle==null?this.snapshot.documentStyle=config:this.snapshot.documentStyle={...this.snapshot.documentStyle,...config}}updateDocumentDataMargin(data){const{t,l,b,r}=data,{documentStyle}=this.snapshot;t!=null&&(documentStyle.marginTop=t),l!=null&&(documentStyle.marginLeft=l),b!=null&&(documentStyle.marginBottom=b),r!=null&&(documentStyle.marginRight=r)}updateDocumentDataPageSize(width,height){const{documentStyle}=this.snapshot;if(!documentStyle.pageSize){width=width!=null?width:Number.POSITIVE_INFINITY,height=height!=null?height:Number.POSITIVE_INFINITY,documentStyle.pageSize={width,height};return}width!==void 0&&(documentStyle.pageSize.width=width),height!==void 0&&(documentStyle.pageSize.height=height)}updateDrawing(id,config){const{drawings}=this,{width,height,left,top}=config,drawing=drawings==null?void 0:drawings[id];if(!drawing)return;const objectTransform=drawing.docTransform;objectTransform.size.width=width,objectTransform.size.height=height,objectTransform.positionH.posOffset=left,objectTransform.positionV.posOffset=top}setZoomRatio(zoomRatio=1){this.snapshot.settings==null?this.snapshot.settings={zoomRatio}:this.snapshot.settings.zoomRatio=1}};__name(_DocumentDataModelSimple,"DocumentDataModelSimple");let DocumentDataModelSimple=_DocumentDataModelSimple;const _DocumentDataModel=class _DocumentDataModel extends DocumentDataModelSimple{constructor(snapshot){var _a13,_b2;super(Tools.isEmptyObject(snapshot)?getEmptySnapshot$1():snapshot);__publicField(this,"_unitId");__publicField(this,"headerModelMap",new Map);__publicField(this,"footerModelMap",new Map);const UNIT_ID_LENGTH=6;this._unitId=(_a13=this.snapshot.id)!=null?_a13:Tools.generateRandomId(UNIT_ID_LENGTH),this._initializeHeaderFooterModel(),this._name$.next((_b2=this.snapshot.title)!=null?_b2:"")}dispose(){super.dispose(),this.headerModelMap.forEach(header=>{header.dispose()}),this.footerModelMap.forEach(footer=>{footer.dispose()}),this._name$.complete()}getDrawings(){return this.snapshot.drawings}getDrawingsOrder(){return this.snapshot.drawingsOrder}getCustomRanges(){var _a13;return(_a13=this.snapshot.body)==null?void 0:_a13.customRanges}getCustomDecorations(){var _a13;return(_a13=this.snapshot.body)==null?void 0:_a13.customDecorations}getRev(){var _a13;return(_a13=this.snapshot.rev)!=null?_a13:1}incrementRev(){this.snapshot.rev=this.getRev()+1}getSettings(){return this.snapshot.settings}reset(snapshot){if(snapshot.id&&snapshot.id!==this._unitId)throw new Error("Cannot reset a document model with a different unit id!");this.snapshot={...DEFAULT_DOC,...snapshot},this._initializeHeaderFooterModel()}getSelfOrHeaderFooterModel(segmentId){if(segmentId!=null){if(this.headerModelMap.has(segmentId))return this.headerModelMap.get(segmentId);if(this.footerModelMap.has(segmentId))return this.footerModelMap.get(segmentId)}return this}getUnitId(){return this._unitId}apply(actions){if(!JSONX.isNoop(actions))return this.snapshot=JSONX.apply(this.snapshot,actions),actions!=null&&actions.some(a=>Array.isArray(a)&&((a==null?void 0:a[0])==="headers"||(a==null?void 0:a[0])==="footers"))&&(this.headerModelMap.clear(),this.footerModelMap.clear(),this._initializeHeaderFooterModel()),this.snapshot}sliceBody(startOffset,endOffset,type2=SliceBodyType.copy){const body=this.getBody();if(body!=null)return getBodySlice(body,startOffset,endOffset,!1,type2)}_initializeHeaderFooterModel(){const{headers,footers}=this.getSnapshot();if(headers)for(const headerId in headers){const header=headers[headerId];this.headerModelMap.set(headerId,new _DocumentDataModel(header)),this.headerModelMap.get(headerId).updateDocumentId(this.getUnitId())}if(footers)for(const footerId in footers){const footer=footers[footerId];this.footerModelMap.set(footerId,new _DocumentDataModel(footer)),this.footerModelMap.get(footerId).updateDocumentId(this.getUnitId())}}updateDocumentId(unitId){super.updateDocumentId(unitId),this._unitId=unitId}};__name(_DocumentDataModel,"DocumentDataModel");let DocumentDataModel=_DocumentDataModel;const IConfigService=createIdentifier("univer.config-service"),_ConfigService=class _ConfigService{constructor(){__publicField(this,"_config",new Map)}getConfig(id){return this._config.get(id)}setConfig(id,value){this._config.set(id,value)}deleteConfig(id){this._config.delete(id)}};__name(_ConfigService,"ConfigService");let ConfigService=_ConfigService;const _ErrorService=class _ErrorService extends Disposable{constructor(){super(...arguments);__publicField(this,"_error$",new rxjs.Subject);__publicField(this,"error$",this._error$.asObservable())}dispose(){this._error$.complete()}emit(key){this._error$.next({errorKey:key})}};__name(_ErrorService,"ErrorService");let ErrorService=_ErrorService;const _Styles=class _Styles{constructor(styles={}){__publicField(this,"_styles");__publicField(this,"_cacheMap",new LRUMap(1e5));this._styles=styles,this._generateCacheMap()}each(callback){return Object.entries(this._styles).forEach(callback),this}search(data,styleObject){if(this._cacheMap.has(styleObject))return this._cacheMap.get(styleObject);const existingId=this._getExistingStyleId(data);return existingId||"-1"}get(id){return typeof id!="string"?id:(id=String(id),this._styles[id])}add(data,styleObject){const id=Tools.generateRandomId(6);return this._styles[id]=data,this._cacheMap.set(styleObject,id),id}setValue(data){if(data==null)return;const styleObject=JSON.stringify(data),result=this.search(data,styleObject);return result!=="-1"?result:this.add(data,styleObject)}toJSON(){return this._styles}getStyleByCell(cell){let style;cell&&Tools.isObject(cell.s)?style=cell.s:style=(cell==null?void 0:cell.s)&&this.get(cell.s);const interceptStyle=cell==null?void 0:cell.interceptorStyle;return interceptStyle?{...style,...interceptStyle}:style}_generateCacheMap(){const{_styles,_cacheMap}=this;for(const id in _styles){const styleObject=JSON.stringify(_styles[id]);_cacheMap.set(styleObject,id)}}_getExistingStyleId(data){const{_styles}=this;for(const id in _styles)if(Tools.diffValue(_styles[id],data))return id;return null}};__name(_Styles,"Styles");let Styles=_Styles;const _ColumnManager=class _ColumnManager{constructor(_config,data){__publicField(this,"_columnData",{});this._config=_config,this._columnData=data}getColumnData(){return this._columnData}getColVisible(colPos){const{_columnData}=this,col=_columnData[colPos];return col?col.hd!==BooleanNumber.TRUE:!0}getHiddenCols(start=0,end=this.getSize()-1){const hiddenCols=[];let inHiddenRange=!1,startColumn=-1;for(let i=start;i<=end;i++){const visible=this.getColVisible(i);inHiddenRange&&visible?(inHiddenRange=!1,hiddenCols.push({rangeType:RANGE_TYPE.COLUMN,startColumn,endColumn:i-1,startRow:0,endRow:0})):!inHiddenRange&&!visible&&(inHiddenRange=!0,startColumn=i)}return inHiddenRange&&hiddenCols.push({startRow:0,endRow:0,startColumn,endColumn:end,rangeType:RANGE_TYPE.COLUMN}),hiddenCols}getVisibleCols(start=0,end=this.getSize()-1){const visibleCols=[];let inVisibleRange=!1,startColumn=-1;for(let i=start;i<=end;i++){const visible=this.getColVisible(i);inVisibleRange&&!visible?(inVisibleRange=!1,visibleCols.push({rangeType:RANGE_TYPE.COLUMN,startColumn,endColumn:i-1,startRow:0,endRow:0})):!inVisibleRange&&visible&&(inVisibleRange=!0,startColumn=i)}return inVisibleRange&&visibleCols.push({startRow:0,endRow:0,startColumn,endColumn:end,rangeType:RANGE_TYPE.COLUMN}),visibleCols}getColumnDatas(columnPos,numColumns){const columnData={};let index2=0;for(let i=columnPos;i<columnPos+numColumns;i++){const data=this.getColumnOrCreate(i);columnData[index2]=data,index2++}return columnData}getSize(){return getArrayLength(this._columnData)}getColumnWidth(columnPos){const{_columnData}=this,config=this._config;let width=0;return width=(_columnData[columnPos]||{hd:BooleanNumber.FALSE,w:config.defaultColumnWidth}).w||config.defaultColumnWidth,width}getColumn(columnPos){const column=this._columnData[columnPos];if(column)return column}getColumnOrCreate(columnPos){const{_columnData}=this,config=this._config,column=_columnData[columnPos];if(column)return column;const create={w:config.defaultColumnWidth,hd:BooleanNumber.FALSE};return this._columnData[columnPos]=create,create}};__name(_ColumnManager,"ColumnManager");let ColumnManager=_ColumnManager;const _RowManager=class _RowManager{constructor(_config,_viewModel,data){__publicField(this,"_rowData");this._config=_config,this._viewModel=_viewModel,this._rowData=data}getRowData(){return this._rowData}getRowDatas(rowPos,numRows){const rowData={};let index2=0;for(let i=rowPos;i<rowPos+numRows;i++){const data=this.getRowOrCreate(i);rowData[index2]=data,index2++}return rowData}getRowHeight(rowPos,count=1){const{_rowData}=this,config=this._config;let height=0;for(let i=0;i<count;i++){const row=_rowData[i+rowPos]||{hd:BooleanNumber.FALSE,h:config.defaultRowHeight},{ia,ah,h=config.defaultRowHeight}=row;height+=(ia==null||ia===BooleanNumber.TRUE)&&typeof ah=="number"?ah:h}return height}getRow(rowPos){return this._rowData[rowPos]}getRowOrCreate(rowPos){const{_rowData}=this,row=_rowData[rowPos];if(row)return row;const config=this._config,create={hd:BooleanNumber.FALSE,h:config.defaultRowHeight};return _rowData[rowPos]=create,create}getHiddenRows(start=0,end=this.getSize()-1){const hiddenRows=[];let inHiddenRange=!1,startRow=-1;for(let i=start;i<=end;i++){const visible=this.getRowRawVisible(i);inHiddenRange&&visible?(inHiddenRange=!1,hiddenRows.push({startRow,endRow:i-1,startColumn:0,endColumn:0,rangeType:RANGE_TYPE.ROW})):!inHiddenRange&&!visible&&(inHiddenRange=!0,startRow=i)}return inHiddenRange&&hiddenRows.push({startRow,endRow:end,startColumn:0,endColumn:0,rangeType:RANGE_TYPE.ROW}),hiddenRows}getVisibleRows(start=0,end=this.getSize()-1){const visibleRows=[];let inVisibleRange=!1,startRow=-1;for(let i=start;i<=end;i++){const visible=this.getRowRawVisible(i);inVisibleRange&&!visible?(inVisibleRange=!1,visibleRows.push({startRow,endRow:i-1,startColumn:0,endColumn:0,rangeType:RANGE_TYPE.ROW})):!inVisibleRange&&visible&&(inVisibleRange=!0,startRow=i)}return inVisibleRange&&visibleRows.push({startRow,endRow:end,startColumn:0,endColumn:0,rangeType:RANGE_TYPE.ROW}),visibleRows}getRowRawVisible(row){const rowData=this.getRow(row);return rowData?rowData.hd!==BooleanNumber.TRUE:!0}getSize(){return getArrayLength(this._rowData)}};__name(_RowManager,"RowManager");let RowManager=_RowManager;const DEFAULT_WORKSHEET_ROW_COUNT_KEY="DEFAULT_WORKSHEET_ROW_COUNT",DEFAULT_WORKSHEET_ROW_COUNT=1e3,DEFAULT_WORKSHEET_COLUMN_COUNT_KEY="DEFAULT_WORKSHEET_COLUMN_COUNT",DEFAULT_WORKSHEET_COLUMN_COUNT=20,DEFAULT_WORKSHEET_ROW_HEIGHT_KEY="DEFAULT_WORKSHEET_ROW_HEIGHT",DEFAULT_WORKSHEET_ROW_HEIGHT=24,DEFAULT_WORKSHEET_COLUMN_WIDTH_KEY="DEFAULT_WORKSHEET_COLUMN_WIDTH",DEFAULT_WORKSHEET_COLUMN_WIDTH=88,DEFAULT_WORKSHEET_ROW_TITLE_WIDTH_KEY="DEFAULT_WORKSHEET_ROW_TITLE_WIDTH",DEFAULT_WORKSHEET_ROW_TITLE_WIDTH=46,DEFAULT_WORKSHEET_COLUMN_TITLE_HEIGHT_KEY="DEFAULT_WORKSHEET_COLUMN_TITLE_HEIGHT",DEFAULT_WORKSHEET_COLUMN_TITLE_HEIGHT=20;function mergeWorksheetSnapshotWithDefault(snapshot){const defaultSnapshot={name:"Sheet1",id:"sheet-01",tabColor:"",hidden:BooleanNumber.FALSE,rowCount:DEFAULT_WORKSHEET_ROW_COUNT,columnCount:DEFAULT_WORKSHEET_COLUMN_COUNT,zoomRatio:1,freeze:{xSplit:0,ySplit:0,startRow:-1,startColumn:-1},scrollTop:0,scrollLeft:0,defaultColumnWidth:DEFAULT_WORKSHEET_COLUMN_WIDTH,defaultRowHeight:DEFAULT_WORKSHEET_ROW_HEIGHT,mergeData:[],cellData:{},rowData:{},columnData:{},showGridlines:BooleanNumber.TRUE,rowHeader:{width:DEFAULT_WORKSHEET_ROW_TITLE_WIDTH,hidden:BooleanNumber.FALSE},columnHeader:{height:DEFAULT_WORKSHEET_COLUMN_TITLE_HEIGHT,hidden:BooleanNumber.FALSE},rightToLeft:BooleanNumber.FALSE};return Object.keys(defaultSnapshot).forEach(_key=>{const key=_key;typeof snapshot[key]>"u"&&(snapshot[key]=defaultSnapshot[key])}),snapshot}__name(mergeWorksheetSnapshotWithDefault,"mergeWorksheetSnapshotWithDefault");const _SheetViewModel=class _SheetViewModel extends Disposable{constructor(getRawCell){super();__publicField(this,"_cellContentInterceptor",null);__publicField(this,"_rowFilteredInterceptor",null);this.getRawCell=getRawCell}dispose(){super.dispose(),this._cellContentInterceptor=null,this._rowFilteredInterceptor=null}getCell(row,col){return this._cellContentInterceptor?this._cellContentInterceptor.getCell(row,col):this.getRawCell(row,col)}getRowFiltered(row){var _a13,_b2;return(_b2=(_a13=this._rowFilteredInterceptor)==null?void 0:_a13.getRowFiltered(row))!=null?_b2:!1}registerCellContentInterceptor(interceptor){if(this._cellContentInterceptor)throw new Error("[SheetViewModel]: Interceptor already registered.");return this._cellContentInterceptor=interceptor,toDisposable(()=>this._cellContentInterceptor=null)}registerRowFilteredInterceptor(interceptor){if(this._rowFilteredInterceptor)throw new Error("[SheetViewModel]: Interceptor already registered.");return this._rowFilteredInterceptor=interceptor,toDisposable(()=>this._rowFilteredInterceptor=null)}};__name(_SheetViewModel,"SheetViewModel");let SheetViewModel=_SheetViewModel;const _Worksheet=class _Worksheet{constructor(unitId,snapshot,_styles){__publicField(this,"_sheetId");__publicField(this,"_snapshot");__publicField(this,"_cellData");__publicField(this,"_rowManager");__publicField(this,"_columnManager");__publicField(this,"_viewModel");var _a13;this.unitId=unitId,this._styles=_styles,this._snapshot=mergeWorksheetSnapshotWithDefault(snapshot);const{columnData,rowData,cellData}=this._snapshot;this._sheetId=(_a13=this._snapshot.id)!=null?_a13:Tools.generateRandomId(6),this._cellData=new ObjectMatrix(cellData),this._viewModel=new SheetViewModel((row,col)=>this.getCellRaw(row,col)),this._rowManager=new RowManager(this._snapshot,this._viewModel,rowData),this._columnManager=new ColumnManager(this._snapshot,columnData)}__interceptViewModel(callback){callback(this._viewModel)}getSnapshot(){return this._snapshot}getCellMatrix(){return this._cellData}getCellMatrixPrintRange(){const matrix=this.getCellMatrix(),mergedCells=this.getMergeData();let startRow=-1,endRow=-1,startColumn=-1,endColumn=-1,rowInitd=!1,columnInitd=!1;return matrix.forEach((rowIndex,row)=>{Object.keys(row).forEach(colIndexStr=>{const colIndex=+colIndexStr,cellValue=matrix.getValue(rowIndex,colIndex),style=cellValue!=null&&cellValue.s?this._styles.get(cellValue.s):null,isLegalBorder=(style==null?void 0:style.bd)&&(style.bd.b||style.bd.l||style.bd.r||style.bd.t||style.bd.bc_tr||style.bd.bl_tr||style.bd.ml_tr||style.bd.tl_bc||style.bd.tl_br||style.bd.tl_mr);(cellValue&&(cellValue.v||cellValue.p)||style!=null&&style.bg||isLegalBorder)&&(rowInitd?startRow=Math.min(startRow,rowIndex):(startRow=rowIndex,rowInitd=!0),endRow=Math.max(endRow,rowIndex),columnInitd?startColumn=Math.min(startColumn,colIndex):(columnInitd=!0,startColumn=colIndex),endColumn=Math.max(endColumn,colIndex))})}),mergedCells.forEach(mergedCell=>{rowInitd?startRow=Math.min(startRow,mergedCell.startRow):(startRow=mergedCell.startRow,rowInitd=!0),endRow=Math.max(endRow,mergedCell.endRow),columnInitd?startColumn=Math.min(startColumn,mergedCell.startColumn):(startColumn=mergedCell.startColumn,rowInitd=!0),endColumn=Math.max(endColumn,mergedCell.endColumn)}),!rowInitd||!columnInitd?null:{startColumn,startRow,endColumn,endRow}}getRowManager(){return this._rowManager}getUnitId(){return this.unitId}getSheetId(){return this._sheetId}getColumnManager(){return this._columnManager}getName(){return this._snapshot.name}clone(){const{_snapshot:_config}=this,copy=Tools.deepClone(_config);return new _Worksheet(this.unitId,copy,this._styles)}getMergeData(){return this._snapshot.mergeData}getMergedCell(row,col){const rectangleList=this._snapshot.mergeData;for(let i=0;i<rectangleList.length;i++){const range=rectangleList[i];if(Rectangle.intersects({startRow:row,startColumn:col,endRow:row,endColumn:col},range))return range}return null}getCell(row,col){return row<0||col<0?null:this._viewModel.getCell(row,col)}getCellRaw(row,col){return this.getCellMatrix().getValue(row,col)}getRowFiltered(row){return this._viewModel.getRowFiltered(row)}getMatrixWithMergedCells(row,col,endRow,endCol,isRaw=!1){const matrix=this.getCellMatrix(),mergedCellsInRange=this._snapshot.mergeData.filter(rect=>Rectangle.intersects({startRow:row,startColumn:col,endRow,endColumn:endCol},rect)),returnCellMatrix=new ObjectMatrix;return createRowColIter(row,endRow,col,endCol).forEach((row2,col2)=>{const v=isRaw?this.getCellRaw(row2,col2):this.getCell(row2,col2);v&&returnCellMatrix.setValue(row2,col2,v)}),mergedCellsInRange.forEach(mergedCell=>{const{startColumn,startRow,endColumn,endRow:endRow2}=mergedCell;createRowColIter(startRow,endRow2,startColumn,endColumn).forEach((row2,col2)=>{row2===startRow&&col2===startColumn&&returnCellMatrix.setValue(row2,col2,{...matrix.getValue(row2,col2),rowSpan:endRow2-startRow+1,colSpan:endColumn-startColumn+1}),(row2!==startRow||col2!==startColumn)&&returnCellMatrix.realDeleteValue(row2,col2)})}),returnCellMatrix}getRange(startRowOrRange,startColumn,endRow,endColumn){return typeof startRowOrRange=="object"?new Range(this,startRowOrRange,{getStyles:__name(()=>this._styles,"getStyles")}):new Range(this,{startRow:startRowOrRange,startColumn,endColumn:endColumn||startColumn,endRow:endRow||startRowOrRange},{getStyles:__name(()=>this._styles,"getStyles")})}getScrollLeftTopFromSnapshot(){return{scrollLeft:this._snapshot.scrollLeft,scrollTop:this._snapshot.scrollTop}}getZoomRatio(){return this._snapshot.zoomRatio||1}getConfig(){return this._snapshot}getFreeze(){return this._snapshot.freeze}getMaxColumns(){const{_snapshot:_config}=this,{columnCount}=_config;return columnCount}getMaxRows(){const{_snapshot:_config}=this,{rowCount}=_config;return rowCount}getRowCount(){return this._snapshot.rowCount}setRowCount(count){this._snapshot.rowCount=count}getColumnCount(){return this._snapshot.columnCount}setColumnCount(count){this._snapshot.columnCount=count}isSheetHidden(){return this._snapshot.hidden}hasHiddenGridlines(){const{_snapshot:_config}=this,{showGridlines}=_config;return showGridlines===0}getTabColor(){const{_snapshot:_config}=this,{tabColor}=_config;return tabColor}getColumnWidth(columnPosition){return this.getColumnManager().getColumnWidth(columnPosition)}getRowHeight(row){return this._viewModel.getRowFiltered(row)?0:this.getRowManager().getRowHeight(row)}getRowVisible(row){return this._viewModel.getRowFiltered(row)?!1:this.getRowRawVisible(row)}getRowRawVisible(row){return this.getRowManager().getRowRawVisible(row)}getHiddenRows(start,end){const lastColumn=this.getMaxColumns()-1,ranges=this._rowManager.getHiddenRows(start,end);return ranges.forEach(range=>range.endColumn=lastColumn),ranges}getColVisible(col){return this._columnManager.getColVisible(col)}getHiddenCols(start,end){const lastRow=this.getMaxRows()-1,ranges=this._columnManager.getHiddenCols(start,end);return ranges.forEach(range=>range.endRow=lastRow),ranges}getVisibleRows(){const rowCount=this.getRowCount();return this._rowManager.getVisibleRows(0,rowCount-1)}getVisibleCols(){const columnCount=this.getColumnCount();return this._columnManager.getVisibleCols(0,columnCount-1)}isRightToLeft(){const{_snapshot:_config}=this,{rightToLeft}=_config;return rightToLeft}getLastRowWithContent(){return this._cellData.getLength()-1}getLastColumnWithContent(){return this._cellData.getRange().endColumn}cellHasValue(value){return value&&(value.v!==void 0||value.f!==void 0||value.p!==void 0)}iterateByRow(range,skipEmpty=!0){const{startRow,startColumn,endRow,endColumn}=range,worksheet=this;return{[Symbol.iterator]:()=>{let rowIndex=startRow,columnIndex=startColumn;return{next(){for(;;){if(columnIndex>endColumn&&(rowIndex+=1,columnIndex=startColumn),rowIndex>endRow)return{done:!0,value:void 0};const cellValue=worksheet.getCell(rowIndex,columnIndex),isEmptyCell2=!cellValue,mergedCell=worksheet.getMergedCell(rowIndex,columnIndex);if(mergedCell){if(rowIndex!==mergedCell.startRow||columnIndex!==mergedCell.startColumn){columnIndex=mergedCell.endColumn+1;continue}if(isEmptyCell2&&skipEmpty){columnIndex=mergedCell.endColumn+1;continue}const value={row:rowIndex,col:columnIndex,value:cellValue};return value.colSpan=mergedCell.endColumn-mergedCell.startColumn+1,value.rowSpan=mergedCell.endRow-mergedCell.startRow+1,columnIndex=mergedCell.endColumn+1,{done:!1,value}}if(isEmptyCell2&&skipEmpty)columnIndex+=1;else{const value={row:rowIndex,col:columnIndex,value:cellValue};return columnIndex+=1,{done:!1,value}}}}}}}}iterateByColumn(range,skipEmpty=!0,skipNonTopLeft=!0){const{startRow,startColumn,endRow,endColumn}=range,worksheet=this;return{[Symbol.iterator]:()=>{let rowIndex=startRow,columnIndex=startColumn;return{next(){for(;;){if(rowIndex>endRow&&(columnIndex+=1,rowIndex=startRow),columnIndex>endColumn)return{done:!0,value:void 0};const mergedCell=worksheet.getMergedCell(rowIndex,columnIndex);if(mergedCell){const isNotTop=rowIndex!==mergedCell.startRow,isNotTopLeft=isNotTop||columnIndex!==mergedCell.startColumn;if(skipNonTopLeft&&isNotTopLeft||!skipNonTopLeft&&isNotTop){rowIndex=mergedCell.endRow+1;continue}const cellValue2=worksheet.getCell(mergedCell.startRow,mergedCell.startColumn);if(!cellValue2&&skipEmpty){rowIndex=mergedCell.endRow+1;continue}const value={row:rowIndex,col:mergedCell.startColumn,value:cellValue2};return value.colSpan=mergedCell.endColumn-mergedCell.startColumn+1,value.rowSpan=mergedCell.endRow-mergedCell.startRow+1,rowIndex=mergedCell.endRow+1,{done:!1,value}}const cellValue=worksheet.getCell(rowIndex,columnIndex);if(!cellValue&&skipEmpty)rowIndex+=1;else{const value={row:rowIndex,col:columnIndex,value:cellValue};return rowIndex+=1,{done:!1,value}}}}}}}}};__name(_Worksheet,"Worksheet");let Worksheet=_Worksheet;function extractPureTextFromCell(cell){var _a13,_b2;if(!cell)return"";const richTextValue=(_b2=(_a13=cell.p)==null?void 0:_a13.body)==null?void 0:_b2.dataStream;if(richTextValue)return richTextValue;const rawValue=cell.v;return typeof rawValue=="string"?cell.t===CellValueType.BOOLEAN?rawValue.toUpperCase():rawValue.replace(/[\r\n]/g,""):typeof rawValue=="number"?cell.t===CellValueType.BOOLEAN?rawValue?"TRUE":"FALSE":rawValue.toString():typeof rawValue=="boolean"?rawValue?"TRUE":"FALSE":""}__name(extractPureTextFromCell,"extractPureTextFromCell");const version="0.2.11";function getEmptySnapshot(unitID="",locale=LocaleType.ZH_CN,name=""){return{id:unitID,sheetOrder:[],name,appVersion:version,locale,styles:{},sheets:{},resources:[]}}__name(getEmptySnapshot,"getEmptySnapshot");var __defProp$7=Object.defineProperty,__getOwnPropDesc$7=Object.getOwnPropertyDescriptor,__decorateClass$7=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$7(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$7(target,key,result),result},"__decorateClass$7"),__decorateParam$6=__name((index2,decorator)=>(target,key)=>decorator(target,key,index2),"__decorateParam$6");function getWorksheetUID(workbook,worksheet){return`${workbook.getUnitId()}|${worksheet.getSheetId()}`}__name(getWorksheetUID,"getWorksheetUID");var _a3;exports.Workbook=(_a3=class extends UnitModel{constructor(workbookData={},_logService){super();__publicField(this,"type",I.UNIVER_SHEET);__publicField(this,"_sheetCreated$",new rxjs.Subject);__publicField(this,"sheetCreated$",this._sheetCreated$.asObservable());__publicField(this,"_sheetDisposed$",new rxjs.Subject);__publicField(this,"sheetDisposed$",this._sheetDisposed$.asObservable());__publicField(this,"_activeSheet$",new rxjs.BehaviorSubject(null));__publicField(this,"activeSheet$",this._activeSheet$.asObservable());__publicField(this,"_worksheets");__publicField(this,"_styles");__publicField(this,"_snapshot");__publicField(this,"_unitId");__publicField(this,"_count");__publicField(this,"_name$");__publicField(this,"name$");this._logService=_logService;const DEFAULT_WORKBOOK=getEmptySnapshot();Tools.isEmptyObject(workbookData)?this._snapshot=DEFAULT_WORKBOOK:this._snapshot=Tools.commonExtend(DEFAULT_WORKBOOK,workbookData);const{styles}=this._snapshot;(this._snapshot.id==null||this._snapshot.id.length===0)&&(this._snapshot.id=Tools.generateRandomId(6)),this._unitId=this._snapshot.id,this._styles=new Styles(styles),this._count=1,this._worksheets=new Map,this._name$=new rxjs.BehaviorSubject(workbookData.name||""),this.name$=this._name$.asObservable(),this._parseWorksheetSnapshots()}get _activeSheet(){return this._activeSheet$.getValue()}get name(){return this._name$.getValue()}static isIRangeType(range){return typeof range=="string"||"startRow"in range||"row"in range}dispose(){super.dispose(),this._sheetCreated$.complete(),this._sheetDisposed$.complete(),this._activeSheet$.complete(),this._name$.complete()}save(){return Tools.deepClone(this._snapshot)}getSnapshot(){return this._snapshot}getName(){return this._snapshot.name}setName(name){this._name$.next(name),this._snapshot.name=name}getUnitId(){return this._unitId}getRev(){var _a13;return(_a13=this._snapshot.rev)!=null?_a13:1}incrementRev(){this._snapshot.rev=this.getRev()+1}addWorksheet(id,index2,worksheetSnapshot){const{sheets,sheetOrder}=this._snapshot;if(sheets[id])return!1;sheets[id]=worksheetSnapshot,sheetOrder.splice(index2,0,id);const worksheet=new Worksheet(this._unitId,worksheetSnapshot,this._styles);return this._worksheets.set(id,worksheet),this._sheetCreated$.next(worksheet),!0}getSheetOrders(){return this._snapshot.sheetOrder}getWorksheets(){return this._worksheets}getActiveSpreadsheet(){return this}getStyles(){return this._styles}getConfig(){return this._snapshot}getIndexBySheetId(sheetId){const{sheetOrder}=this._snapshot;return sheetOrder.findIndex(id=>id===sheetId)}getActiveSheet(allowNull){if(!this._activeSheet&&typeof allowNull>"u")throw new Error(`[Workbook]: no active Worksheet on Workbook ${this._unitId}!`);return this._activeSheet}ensureActiveSheet(){const currentActive=this._activeSheet;if(currentActive)return currentActive;const sheetOrder=this._snapshot.sheetOrder;for(let i=0,len=sheetOrder.length;i<len;i++){const worksheet2=this._worksheets.get(sheetOrder[i]);if(worksheet2&&worksheet2.isSheetHidden()!==BooleanNumber.TRUE)return this.setActiveSheet(worksheet2),worksheet2}const worksheet=this._worksheets.get(sheetOrder[0]);return this.setActiveSheet(worksheet),worksheet}setActiveSheet(worksheet){this._activeSheet$.next(worksheet)}removeSheet(sheetId){const sheetToRemove=this._worksheets.get(sheetId);return sheetToRemove?(this._worksheets.delete(sheetId),this._snapshot.sheetOrder.splice(this._snapshot.sheetOrder.indexOf(sheetId),1),delete this._snapshot.sheets[sheetId],this._sheetDisposed$.next(sheetToRemove),!0):!1}getActiveSheetIndex(){const{sheetOrder}=this._snapshot;return sheetOrder.findIndex(sheetId=>this._worksheets.get(sheetId)===this._activeSheet)}getSheetSize(){return this._snapshot.sheetOrder.length}getSheets(){const{sheetOrder}=this._snapshot;return sheetOrder.map(sheetId=>this._worksheets.get(sheetId))}getSheetsName(){const{sheetOrder}=this._snapshot,names=[];return sheetOrder.forEach(sheetId=>{const worksheet=this._worksheets.get(sheetId);worksheet&&names.push(worksheet.getName())}),names}getSheetIndex(sheet){const{sheetOrder}=this._snapshot;return sheetOrder.findIndex(sheetId=>sheet.getSheetId()===sheetId)}getSheetBySheetName(name){const{sheetOrder}=this._snapshot,sheetId=sheetOrder.find(sheetId2=>this._worksheets.get(sheetId2).getName()===name);return this._worksheets.get(sheetId)}getSheetBySheetId(sheetId){return this._worksheets.get(sheetId)}getSheetByIndex(index2){const{sheetOrder}=this._snapshot;return this._worksheets.get(sheetOrder[index2])}getHiddenWorksheets(){return this.getSheets().filter(s=>s.getConfig().hidden===BooleanNumber.TRUE).map(s=>s.getConfig().id)}getUnhiddenWorksheets(){return this.getSheets().filter(s=>s.getConfig().hidden!==BooleanNumber.TRUE).map(s=>s.getConfig().id)}load(config){this._snapshot=config}checkSheetName(name){return this.getSheetsName().includes(name)}uniqueSheetName(name="Sheet1"){let output=name;for(;this.checkSheetName(output);)output=name+this._count,this._count++;return output}generateNewSheetName(name){let output=name+this._count;for(;this.checkSheetName(output);)output=name+this._count,this._count++;return output}_parseWorksheetSnapshots(){const{_snapshot,_worksheets}=this,{sheets,sheetOrder}=_snapshot;if(Tools.isEmptyObject(sheets)){const firstSheetId=Tools.generateRandomId();sheets[firstSheetId]={id:firstSheetId}}for(const sheetId in sheets){const worksheetSnapshot=sheets[sheetId],{name}=worksheetSnapshot;worksheetSnapshot.name=this.uniqueSheetName(name),worksheetSnapshot.name!==name&&this._logService.debug("[Workbook]",`The worksheet name ${name} is duplicated, we changed it to ${worksheetSnapshot.name}. Please fix the problem in your snapshot.`);const worksheet=new Worksheet(this._unitId,worksheetSnapshot,this._styles);_worksheets.set(sheetId,worksheet),sheetOrder.includes(sheetId)||sheetOrder.push(sheetId)}this.ensureActiveSheet()}},__name(_a3,"Workbook"),_a3);exports.Workbook=__decorateClass$7([__decorateParam$6(1,ILogService)],exports.Workbook);var PageType=(PageType2=>(PageType2[PageType2.SLIDE=0]="SLIDE",PageType2[PageType2.MASTER=1]="MASTER",PageType2[PageType2.LAYOUT=2]="LAYOUT",PageType2[PageType2.HANDOUT_MASTER=3]="HANDOUT_MASTER",PageType2[PageType2.NOTES_MASTER=4]="NOTES_MASTER",PageType2))(PageType||{}),PageElementType=(PageElementType2=>(PageElementType2[PageElementType2.SHAPE=0]="SHAPE",PageElementType2[PageElementType2.IMAGE=1]="IMAGE",PageElementType2[PageElementType2.TEXT=2]="TEXT",PageElementType2[PageElementType2.SPREADSHEET=3]="SPREADSHEET",PageElementType2[PageElementType2.DOCUMENT=4]="DOCUMENT",PageElementType2[PageElementType2.SLIDE=5]="SLIDE",PageElementType2))(PageElementType||{}),RelativeSlideLink=(RelativeSlideLink2=>(RelativeSlideLink2[RelativeSlideLink2.RELATIVE_SLIDE_LINK_UNSPECIFIED=0]="RELATIVE_SLIDE_LINK_UNSPECIFIED",RelativeSlideLink2[RelativeSlideLink2.NEXT_SLIDE=1]="NEXT_SLIDE",RelativeSlideLink2[RelativeSlideLink2.PREVIOUS_SLIDE=2]="PREVIOUS_SLIDE",RelativeSlideLink2[RelativeSlideLink2.FIRST_SLIDE=3]="FIRST_SLIDE",RelativeSlideLink2[RelativeSlideLink2.LAST_SLIDE=4]="LAST_SLIDE",RelativeSlideLink2))(RelativeSlideLink||{});const _SlideDataModel=class _SlideDataModel extends UnitModel{constructor(snapshot){var _a13;super();__publicField(this,"type",I.UNIVER_SLIDE);__publicField(this,"_activePage$",new rxjs.BehaviorSubject(null));__publicField(this,"activePage$",this._activePage$.asObservable());__publicField(this,"_name$");__publicField(this,"name$");__publicField(this,"_snapshot");__publicField(this,"_unitId");this._snapshot={...DEFAULT_SLIDE,...snapshot},this._unitId=(_a13=this._snapshot.id)!=null?_a13:Tools.generateRandomId(6),this._name$=new rxjs.BehaviorSubject(this._snapshot.title),this.name$=this._name$.asObservable()}get _activePage(){var _a13,_b2;const activePage=this._activePage$.getValue();if(!activePage){const activePageId=(_a13=this.getPageOrder())==null?void 0:_a13[0];return activePageId?(_b2=this.getPages())==null?void 0:_b2[activePageId]:null}return activePage}setName(name){var _a13;this._snapshot.title=name,this._name$.next(name),this._unitId=(_a13=this._snapshot.id)!=null?_a13:generateRandomId(6)}getSnapshot(){return this._snapshot}getUnitId(){return this._unitId}getPages(){var _a13;return(_a13=this._snapshot.body)==null?void 0:_a13.pages}getPageOrder(){var _a13;return(_a13=this._snapshot.body)==null?void 0:_a13.pageOrder}getPage(pageId){const pages=this.getPages();return pages==null?void 0:pages[pageId]}getElementsByPage(pageId){var _a13;return(_a13=this.getPage(pageId))==null?void 0:_a13.pageElements}getElement(pageId,elementId){var _a13;return(_a13=this.getElementsByPage(pageId))==null?void 0:_a13[elementId]}getPageSize(){return this._snapshot.pageSize}getBlankPage(){const id=generateRandomId(6);return{id,pageType:PageType.SLIDE,zIndex:10,title:id,description:"",pageBackgroundFill:{rgb:"rgb(255,255,255)"},pageElements:{}}}setActivePage(page){this._activePage$.next(page)}getActivePage(){return this._activePage}updatePage(pageId,page){this._snapshot.body&&(this._snapshot.body.pages[pageId]=page)}appendPage(page){var _a13;if(!this._snapshot.body)return;this._snapshot.body.pages[page.id]=page;const activePage=this._activePage,index2=this._snapshot.body.pageOrder.indexOf((_a13=activePage==null?void 0:activePage.id)!=null?_a13:"");this._snapshot.body.pageOrder.splice(index2+1,0,page.id)}};__name(_SlideDataModel,"SlideDataModel");let SlideDataModel=_SlideDataModel;const FOCUSING_UNIT="FOCUSING_UNIT",FOCUSING_SHEET="FOCUSING_SHEET",FOCUSING_DOC="FOCUSING_DOC",FOCUSING_SLIDE="FOCUSING_SLIDE",FOCUSING_EDITOR_BUT_HIDDEN="FOCUSING_EDITOR_BUT_HIDDEN",EDITOR_ACTIVATED="EDITOR_ACTIVATED",FOCUSING_EDITOR_INPUT_FORMULA="FOCUSING_EDITOR_INPUT_FORMULA",FOCUSING_FX_BAR_EDITOR="FOCUSING_FX_BAR_EDITOR",FOCUSING_UNIVER_EDITOR="FOCUSING_UNIVER_EDITOR",FOCUSING_EDITOR_STANDALONE="FOCUSING_EDITOR_INPUT_FORMULA",FOCUSING_UNIVER_EDITOR_STANDALONE_SINGLE_MODE="FOCUSING_UNIVER_EDITOR_STANDALONE_SINGLE_MODE",FOCUSING_COMMON_DRAWINGS="FOCUSING_COMMON_DRAWINGS",FORMULA_EDITOR_ACTIVATED="FORMULA_EDITOR_ACTIVATED";var __defProp$6=Object.defineProperty,__getOwnPropDesc$6=Object.getOwnPropertyDescriptor,__decorateClass$6=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$6(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$6(target,key,result),result},"__decorateClass$6"),__decorateParam$5=__name((index2,decorator)=>(target,key)=>decorator(target,key,index2),"__decorateParam$5");const IUniverInstanceService=createIdentifier("univer.current");var _a4;exports.UniverInstanceService=(_a4=class extends Disposable{constructor(_injector,_contextService){super();__publicField(this,"_unitsByType",new Map);__publicField(this,"_createHandler");__publicField(this,"_ctorByType",new Map);__publicField(this,"_currentUnits",new Map);__publicField(this,"_currentUnits$",new rxjs.BehaviorSubject(this._currentUnits));__publicField(this,"currentUnits$",this._currentUnits$.asObservable());__publicField(this,"_unitAdded$",new rxjs.Subject);__publicField(this,"unitAdded$",this._unitAdded$.asObservable());__publicField(this,"_unitDisposed$",new rxjs.Subject);__publicField(this,"unitDisposed$",this._unitDisposed$.asObservable());__publicField(this,"_focused$",new rxjs.BehaviorSubject(null));__publicField(this,"focused$",this._focused$.asObservable());this._injector=_injector,this._contextService=_contextService}dispose(){super.dispose(),this._focused$.complete()}__setCreateHandler(handler){this._createHandler=handler}createUnit(type2,data,options){return this._createHandler(type2,data,this._ctorByType.get(type2),options)}registerCtorForType(type2,ctor){return this._ctorByType.set(type2,ctor),{dispose:__name(()=>{this._ctorByType.delete(type2)},"dispose")}}getCurrentTypeOfUnit$(type2){return this.currentUnits$.pipe(rxjs.map(units=>{var _a13;return(_a13=units.get(type2))!=null?_a13:null}),rxjs.distinctUntilChanged())}getCurrentUnitForType(type2){return this._currentUnits.get(type2)}setCurrentUnitForType(unitId){const result=this._getUnitById(unitId);if(!result)throw new Error(`[UniverInstanceService]: no document with unitId ${unitId}!`);this._currentUnits.set(result[1],result[0]),this._currentUnits$.next(this._currentUnits)}getTypeOfUnitAdded$(type2){return this._unitAdded$.pipe(rxjs.filter(unit=>unit.type===type2))}__addUnit(unit,options){var _a13;const type2=unit.type;this._unitsByType.has(type2)||this._unitsByType.set(type2,[]);const units=this._unitsByType.get(type2),newUnitId=unit.getUnitId();if(units.findIndex(u=>u.getUnitId()===newUnitId)!==-1)throw new Error(`[UniverInstanceService]: cannot create a unit with the same unit id: ${newUnitId}.`);units.push(unit),this._unitAdded$.next(unit),((_a13=options==null?void 0:options.makeCurrent)==null||_a13)&&this.setCurrentUnitForType(unit.getUnitId())}getTypeOfUnitDisposed$(type2){return this.unitDisposed$.pipe(rxjs.filter(unit=>unit.type===type2))}getUnit(id,type2){var _a13;const unit=(_a13=this._getUnitById(id))==null?void 0:_a13[0];return type2&&(unit==null?void 0:unit.type)!==type2?null:unit}getCurrentUniverDocInstance(){return this.getCurrentUnitForType(I.UNIVER_DOC)}getUniverDocInstance(unitId){return this.getUnit(unitId,I.UNIVER_DOC)}getUniverSheetInstance(unitId){return this.getUnit(unitId,I.UNIVER_SHEET)}getAllUnitsForType(type2){var _a13;return(_a13=this._unitsByType.get(type2))!=null?_a13:[]}changeDoc(unitId,doc){const allDocs=this.getAllUnitsForType(I.UNIVER_DOC),oldDoc=allDocs.find(doc2=>doc2.getUnitId()===unitId);if(oldDoc!=null){const index2=allDocs.indexOf(oldDoc);allDocs.splice(index2,1)}this.__addUnit(doc)}get focused(){var _a13;const id=this._focused$.getValue();return id?(_a13=this._getUnitById(id))==null?void 0:_a13[0]:null}focusUnit(id){this._focused$.next(id),this.focused instanceof exports.Workbook?(this._contextService.setContextValue(FOCUSING_UNIT,!0),this._contextService.setContextValue(FOCUSING_DOC,!1),this._contextService.setContextValue(FOCUSING_SHEET,!0),this._contextService.setContextValue(FOCUSING_SLIDE,!1),this.setCurrentUnitForType(id)):this.focused instanceof DocumentDataModel?(this._contextService.setContextValue(FOCUSING_UNIT,!0),this._contextService.setContextValue(FOCUSING_DOC,!0),this._contextService.setContextValue(FOCUSING_SHEET,!1),this._contextService.setContextValue(FOCUSING_SLIDE,!1),this.setCurrentUnitForType(id)):this.focused instanceof SlideDataModel?(this._contextService.setContextValue(FOCUSING_UNIT,!0),this._contextService.setContextValue(FOCUSING_DOC,!1),this._contextService.setContextValue(FOCUSING_SHEET,!1),this._contextService.setContextValue(FOCUSING_SLIDE,!0),this.setCurrentUnitForType(id)):(this._contextService.setContextValue(FOCUSING_UNIT,!1),this._contextService.setContextValue(FOCUSING_DOC,!1),this._contextService.setContextValue(FOCUSING_SHEET,!1),this._contextService.setContextValue(FOCUSING_SLIDE,!1))}getFocusedUnit(){return this.focused}getUnitType(unitId){const result=this._getUnitById(unitId);return result?result[1]:I.UNRECOGNIZED}disposeUnit(unitId){const result=this._getUnitById(unitId);if(!result)return!1;const[unit,type2]=result,units=this._unitsByType.get(type2),index2=units.indexOf(unit);return units.splice(index2,1),this._tryRemoveCurrentUnitForType(unitId,type2),this._tryBlurUnitOnRemoval(unitId),this._unitDisposed$.next(unit),!0}_tryRemoveCurrentUnitForType(unitId,type2){const current=this.getCurrentUnitForType(type2);(current==null?void 0:current.getUnitId())===unitId&&(this._currentUnits.set(type2,null),this._currentUnits$.next(this._currentUnits))}_tryBlurUnitOnRemoval(unitId){var _a13;((_a13=this.focused)==null?void 0:_a13.getUnitId())===unitId&&this._focused$.next(null)}_getUnitById(unitId){for(const[type2,units]of this._unitsByType){const unit=units.find(unit2=>unit2.getUnitId()===unitId);if(unit)return[unit,type2]}}},__name(_a4,"UniverInstanceService"),_a4);exports.UniverInstanceService=__decorateClass$6([__decorateParam$5(0,Inject(Injector)),__decorateParam$5(1,IContextService)],exports.UniverInstanceService);var LifecycleStages=(LifecycleStages2=>(LifecycleStages2[LifecycleStages2.Starting=0]="Starting",LifecycleStages2[LifecycleStages2.Ready=1]="Ready",LifecycleStages2[LifecycleStages2.Rendered=2]="Rendered",LifecycleStages2[LifecycleStages2.Steady=3]="Steady",LifecycleStages2))(LifecycleStages||{});const LifecycleNameMap={0:"Starting",1:"Ready",2:"Rendered",3:"Steady"},LifecycleToModules=new Map;function OnLifecycle(lifecycleStage,identifier){return __name(function(_){runOnLifecycle(lifecycleStage,identifier)},"decorator2")}__name(OnLifecycle,"OnLifecycle");function runOnLifecycle(lifecycleStage,identifier){LifecycleToModules.has(lifecycleStage)||LifecycleToModules.set(lifecycleStage,[]),LifecycleToModules.get(lifecycleStage).push(identifier)}__name(runOnLifecycle,"runOnLifecycle");var __defProp$5=Object.defineProperty,__getOwnPropDesc$5=Object.getOwnPropertyDescriptor,__decorateClass$5=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$5(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$5(target,key,result),result},"__decorateClass$5"),__decorateParam$4=__name((index2,decorator)=>(target,key)=>decorator(target,key,index2),"__decorateParam$4"),_a5;exports.LifecycleService=(_a5=class extends Disposable{constructor(_logService){super();__publicField(this,"_lifecycle$",new rxjs.BehaviorSubject(LifecycleStages.Starting));__publicField(this,"lifecycle$",this._lifecycle$.asObservable());__publicField(this,"_lock",!1);this._logService=_logService,this._reportProgress(LifecycleStages.Starting)}get stage(){return this._lifecycle$.getValue()}set stage(stage){if(this._lock)throw new Error("[LifecycleService]: cannot set new stage when related logic is all handled!");if(stage<this.stage)throw new Error("[LifecycleService]: lifecycle stage cannot go backward!");stage!==this.stage&&(this._lock=!0,this._reportProgress(stage),this._lifecycle$.next(stage),this._lock=!1)}dispose(){this._lifecycle$.complete(),super.dispose()}subscribeWithPrevious(){return rxjs.merge(getLifecycleStagesAndBefore(this.stage),this._lifecycle$.pipe(rxjs.skip(1))).pipe(takeAfter(s=>s===LifecycleStages.Steady))}_reportProgress(stage){this._logService.debug("[LifecycleService]",`lifecycle progressed to "${LifecycleNameMap[stage]}".`)}},__name(_a5,"LifecycleService"),_a5);exports.LifecycleService=__decorateClass$5([__decorateParam$4(0,ILogService)],exports.LifecycleService);var _a6;exports.LifecycleInitializerService=(_a6=class extends Disposable{constructor(_injector){super();__publicField(this,"_seenTokens",new Set);this._injector=_injector}initModulesOnStage(stage){var _a13;(_a13=LifecycleToModules.get(stage))==null||_a13.forEach(m=>{this._injector.has(m)&&!this._seenTokens.has(m)&&(this._injector.get(m),this._seenTokens.add(m))})}},__name(_a6,"LifecycleInitializerService"),_a6);exports.LifecycleInitializerService=__decorateClass$5([__decorateParam$4(0,Inject(Injector))],exports.LifecycleInitializerService);function getLifecycleStagesAndBefore(lifecycleStage){switch(lifecycleStage){case LifecycleStages.Starting:return rxjs.of(LifecycleStages.Starting);case LifecycleStages.Ready:return rxjs.of(LifecycleStages.Starting,LifecycleStages.Ready);case LifecycleStages.Rendered:return rxjs.of(LifecycleStages.Starting,LifecycleStages.Ready,LifecycleStages.Rendered);default:return rxjs.of(LifecycleStages.Starting,LifecycleStages.Ready,LifecycleStages.Rendered,LifecycleStages.Steady)}}__name(getLifecycleStagesAndBefore,"getLifecycleStagesAndBefore");const _LocaleService=class _LocaleService extends Disposable{constructor(){super();__publicField(this,"_currentLocale$",new rxjs.BehaviorSubject(LocaleType.ZH_CN));__publicField(this,"currentLocale$",this._currentLocale$.asObservable());__publicField(this,"_locales",null);__publicField(this,"localeChanged$",new rxjs.Subject);__publicField(this,"t",__name((key,...args)=>{if(!this._locales)throw new Error("[LocaleService]: Locale not initialized");const keys=key.split("."),resolvedValue=this.resolveKeyPath(this._locales[this._currentLocale],keys);if(typeof resolvedValue=="string"){let result=resolvedValue;return args.forEach((arg,index2)=>{result=result.replace(`{${index2}}`,arg)}),result}else return key},"t"));this.disposeWithMe(toDisposable(()=>this.localeChanged$.complete()))}get _currentLocale(){return this._currentLocale$.value}load(locales){var _a13;this._locales=Tools.deepMerge((_a13=this._locales)!=null?_a13:{},locales)}setLocale(locale){this._currentLocale$.next(locale),this.localeChanged$.next()}getLocales(){var _a13;return(_a13=this._locales)==null?void 0:_a13[this._currentLocale]}getCurrentLocale(){return this._currentLocale}resolveKeyPath(obj,keys){const currentKey=keys.shift();if(currentKey&&obj&&currentKey in obj){const nextObj=obj[currentKey];return keys.length>0&&(typeof nextObj=="object"||Array.isArray(nextObj))?this.resolveKeyPath(nextObj,keys):nextObj}return null}};__name(_LocaleService,"LocaleService");let LocaleService=_LocaleService;var PermissionStatus=(PermissionStatus2=>(PermissionStatus2.INIT="init",PermissionStatus2.FETCHING="fetching",PermissionStatus2.DONE="done",PermissionStatus2))(PermissionStatus||{});const IPermissionService=createIdentifier("univer.permission-service");runOnLifecycle(LifecycleStages.Starting,IPermissionService);const _PermissionService=class _PermissionService extends Disposable{constructor(){super(...arguments);__publicField(this,"_permissionPointMap",new Map);__publicField(this,"_permissionPointUpdate$",new rxjs.Subject);__publicField(this,"permissionPointUpdate$",this._permissionPointUpdate$.asObservable())}deletePermissionPoint(permissionId){const permissionPoint=this._permissionPointMap.get(permissionId);permissionPoint&&(permissionPoint.complete(),this._permissionPointMap.delete(permissionId))}addPermissionPoint(_item){const isSubject=_item instanceof rxjs.BehaviorSubject,item=isSubject?_item.getValue():_item;if(!item.id)return!1;if(this._permissionPointMap.get(item.id))throw new Error(`${item.id} PermissionPoint already exists`);return this._permissionPointMap.set(item.id,isSubject?_item:new rxjs.BehaviorSubject(item)),this._permissionPointUpdate$.next(item),!0}updatePermissionPoint(permissionId,value){const permissionPoint=this._permissionPointMap.get(permissionId);if(!permissionPoint)return;const subject=permissionPoint.getValue();subject.value=value,subject.status=PermissionStatus.DONE,permissionPoint.next(subject),this._permissionPointUpdate$.next(subject)}clearPermissionMap(){this._permissionPointMap.clear()}getPermissionPoint(permissionId){const permissionPoint=this._permissionPointMap.get(permissionId);if(permissionPoint)return permissionPoint.getValue()}getPermissionPoint$(permissionId){const permissionPoint=this._permissionPointMap.get(permissionId);if(permissionPoint)return permissionPoint}composePermission$(permissionIdList){const subjectList=permissionIdList.map(id=>{var _a13;const subject=(_a13=this._permissionPointMap)==null?void 0:_a13.get(id);if(!subject)throw new Error(`[PermissionService]: ${id} permissionPoint does not exist!`);return subject.asObservable()});return rxjs.combineLatest(subjectList).pipe(operators.map(list=>list))}composePermission(permissionIdList){return permissionIdList.map(id=>{var _a13;const subject=(_a13=this._permissionPointMap)==null?void 0:_a13.get(id);if(!subject)throw new Error(`[PermissionService]: ${id} permissionPoint does not exist!`);return subject.getValue()})}getAllPermissionPoint(){const cacheMap=new Map;return this._permissionPointMap.forEach((v,key)=>{cacheMap.set(key,v)}),cacheMap}};__name(_PermissionService,"PermissionService");let PermissionService=_PermissionService;const _ResourceManagerService=class _ResourceManagerService extends Disposable{constructor(){super(...arguments);__publicField(this,"_resourceMap",new Map);__publicField(this,"_register$",new rxjs.Subject);__publicField(this,"register$",this._register$.asObservable())}getAllResourceHooks(){return[...this._resourceMap.values()]}getResources(unitId,type2){return type2?this.getResourcesByType(unitId,type2):this.getAllResourceHooks().map(resourceHook=>{const data=resourceHook.toJson(unitId);return{name:resourceHook.pluginName,data}})}getResourcesByType(unitId,type2){return this.getAllResourceHooks().filter(hook=>hook.businesses.includes(type2)).map(resourceHook=>{const data=resourceHook.toJson(unitId);return{name:resourceHook.pluginName,data}})}registerPluginResource(hook){const resourceName=hook.pluginName;if(this._resourceMap.has(resourceName))throw new Error(`the pluginName is registered {${resourceName}}`);return this._resourceMap.set(resourceName,hook),this._register$.next(hook),toDisposable(()=>this._resourceMap.delete(resourceName))}disposePluginResource(pluginName){this._resourceMap.delete(pluginName)}loadResources(unitId,resources){this.getAllResourceHooks().forEach(hook=>{var _a13;const data=(_a13=resources==null?void 0:resources.find(resource=>resource.name===hook.pluginName))==null?void 0:_a13.data;if(data)try{const model=hook.parseJson(data);hook.onLoad(unitId,model)}catch{console.error("LoadResources Error!")}})}unloadResources(unitId){this.getAllResourceHooks().forEach(hook=>{hook.onUnLoad(unitId)})}dispose(){this._register$.complete(),this._resourceMap.clear()}};__name(_ResourceManagerService,"ResourceManagerService");let ResourceManagerService=_ResourceManagerService;const IResourceManagerService=createIdentifier("core.resource-manager.service"),PREFIX="__INTERNAL_EDITOR__",DOCS_NORMAL_EDITOR_UNIT_ID_KEY=`${PREFIX}DOCS_NORMAL`,DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY=`${PREFIX}DOCS_FORMULA_BAR`,DOCS_ZEN_EDITOR_UNIT_ID_KEY=`${PREFIX}ZEN_EDITOR`,DEFAULT_EMPTY_DOCUMENT_VALUE=`\r
9
9
  `;function createInternalEditorID(id){return`${PREFIX}${id}`}__name(createInternalEditorID,"createInternalEditorID");function isInternalEditorID(id){return id.startsWith(PREFIX)}__name(isInternalEditorID,"isInternalEditorID");var __defProp$4=Object.defineProperty,__getOwnPropDesc$4=Object.getOwnPropertyDescriptor,__decorateClass$4=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$4(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$4(target,key,result),result},"__decorateClass$4"),__decorateParam$3=__name((index2,decorator)=>(target,key)=>decorator(target,key,index2),"__decorateParam$3"),_a7;let ResourceLoaderService=(_a7=class extends Disposable{constructor(_resourceManagerService,_univerInstanceService){super(),this._resourceManagerService=_resourceManagerService,this._univerInstanceService=_univerInstanceService,this._init()}_init(){const handleHookAdd=__name(hook=>{hook.businesses.forEach(business=>{switch(business){case I.UNRECOGNIZED:case I.UNIVER_UNKNOWN:case I.UNIVER_SLIDE:case I.UNIVER_DOC:{this._univerInstanceService.getAllUnitsForType(I.UNIVER_DOC).forEach(doc=>{const plugin=(doc.getSnapshot().resources||[]).find(r=>r.name===hook.pluginName);if(plugin)try{const data=hook.parseJson(plugin.data);hook.onLoad(doc.getUnitId(),data)}catch{console.error(`Load Document{${doc.getUnitId()}} Resources{${hook.pluginName}} Data Error.`)}});break}case I.UNIVER_SHEET:this._univerInstanceService.getAllUnitsForType(I.UNIVER_SHEET).forEach(workbook=>{const plugin=(workbook.getSnapshot().resources||[]).find(r=>r.name===hook.pluginName);if(plugin)try{const data=hook.parseJson(plugin.data);hook.onLoad(workbook.getUnitId(),data)}catch{console.error(`Load Workbook{${workbook.getUnitId()}} Resources{${hook.pluginName}} Data Error.`)}})}})},"handleHookAdd");this._resourceManagerService.getAllResourceHooks().forEach(hook=>handleHookAdd(hook)),this.disposeWithMe(this._resourceManagerService.register$.subscribe(hook=>handleHookAdd(hook))),this.disposeWithMe(this._univerInstanceService.getTypeOfUnitAdded$(I.UNIVER_SHEET).subscribe(workbook=>{this._resourceManagerService.loadResources(workbook.getUnitId(),workbook.getSnapshot().resources)})),this.disposeWithMe(this._univerInstanceService.getTypeOfUnitAdded$(I.UNIVER_DOC).subscribe(doc=>{const unitId=doc.getUnitId();isInternalEditorID(unitId)||this._resourceManagerService.loadResources(doc.getUnitId(),doc.getSnapshot().resources)})),this.disposeWithMe(this._univerInstanceService.getTypeOfUnitDisposed$(I.UNIVER_SHEET).subscribe(workbook=>{this._resourceManagerService.unloadResources(workbook.getUnitId())})),this.disposeWithMe(this._univerInstanceService.getTypeOfUnitDisposed$(I.UNIVER_DOC).subscribe(doc=>{this._resourceManagerService.unloadResources(doc.getUnitId())}))}saveUnit(unitId){const unit=this._univerInstanceService.getUnit(unitId);if(!unit)return null;const resources=this._resourceManagerService.getResources(unitId,unit.type),snapshot=Tools.deepClone(unit.getSnapshot());return snapshot.resources=resources,snapshot}},__name(_a7,"ResourceLoaderService"),_a7);ResourceLoaderService=__decorateClass$4([__decorateParam$3(0,Inject(IResourceManagerService)),__decorateParam$3(1,Inject(IUniverInstanceService))],ResourceLoaderService);const IResourceLoaderService=createIdentifier("resource-loader-service");runOnLifecycle(LifecycleStages.Ready,IResourceLoaderService);const _ThemeService=class _ThemeService extends Disposable{constructor(){super();__publicField(this,"_currentTheme");__publicField(this,"_currentTheme$",new rxjs.BehaviorSubject({}));__publicField(this,"currentTheme$",this._currentTheme$.asObservable());this.disposeWithMe(toDisposable(()=>this._currentTheme$.complete()))}getCurrentTheme(){if(!this._currentTheme)throw new Error("[ThemeService]: current theme is not set!");return this._currentTheme}setTheme(theme){this._currentTheme=theme,this._currentTheme$.next(theme)}};__name(_ThemeService,"ThemeService");let ThemeService=_ThemeService;var __defProp$3=Object.defineProperty,__getOwnPropDesc$3=Object.getOwnPropertyDescriptor,__decorateClass$3=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$3(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$3(target,key,result),result},"__decorateClass$3"),__decorateParam$2=__name((index2,decorator)=>(target,key)=>decorator(target,key,index2),"__decorateParam$2");const IUndoRedoService=createIdentifier("univer.undo-redo.service"),STACK_CAPACITY=20,_MultiImplementationCommand=class _MultiImplementationCommand{dispose(){}async dispatchToHandlers(){return!1}};__name(_MultiImplementationCommand,"MultiImplementationCommand");let MultiImplementationCommand=_MultiImplementationCommand;const RedoCommandId="univer.command.redo",UndoCommandId="univer.command.undo",UndoCommand=new class extends MultiImplementationCommand{constructor(){super(...arguments);__publicField(this,"type",CommandType.COMMAND);__publicField(this,"id",UndoCommandId)}async handler(accessor){const undoRedoService=accessor.get(IUndoRedoService),element=undoRedoService.pitchTopUndoElement();if(!element)return!1;const commandService=accessor.get(ICommandService);return sequenceExecute(element.undoMutations,commandService)?(undoRedoService.popUndoToRedo(),!0):!1}},RedoCommand=new class extends MultiImplementationCommand{constructor(){super(...arguments);__publicField(this,"type",CommandType.COMMAND);__publicField(this,"id",RedoCommandId)}async handler(accessor){const undoRedoService=accessor.get(IUndoRedoService),element=undoRedoService.pitchTopRedoElement();if(!element)return!1;const commandService=accessor.get(ICommandService);return sequenceExecute(element.redoMutations,commandService)?(undoRedoService.popRedoToUndo(),!0):!1}};var _a8;exports.LocalUndoRedoService=(_a8=class extends Disposable{constructor(_univerInstanceService,_commandService,_contextService){super();__publicField(this,"undoRedoStatus$");__publicField(this,"_undoRedoStatus$",new rxjs.BehaviorSubject({undos:0,redos:0}));__publicField(this,"_undoStacks",new Map);__publicField(this,"_redoStacks",new Map);__publicField(this,"_batchingStatus",new Map);this._univerInstanceService=_univerInstanceService,this._commandService=_commandService,this._contextService=_contextService,this.undoRedoStatus$=this._undoRedoStatus$.asObservable(),this.disposeWithMe(this._commandService.registerCommand(UndoCommand)),this.disposeWithMe(this._commandService.registerCommand(RedoCommand)),this.disposeWithMe(toDisposable(()=>this._undoRedoStatus$.complete())),this.disposeWithMe(toDisposable(this._univerInstanceService.focused$.subscribe(()=>this._updateStatus())))}pushUndoRedo(item){const{unitID}=item,redoStack=this._getRedoStack(unitID,!0),undoStack=this._getUndoStack(unitID,!0);if(redoStack.length=0,this._batchingStatus.has(item.unitID)){const batchingStatus=this._batchingStatus.get(item.unitID),lastItem=this._pitchUndoElement(item.unitID);batchingStatus===0||!lastItem?(appendNewItem(item),this._batchingStatus.set(item.unitID,1)):this._tryBatchingElements(lastItem,item)}else appendNewItem(item);function appendNewItem(item2){undoStack.push(item2),undoStack.length>STACK_CAPACITY&&undoStack.splice(0,1)}__name(appendNewItem,"appendNewItem"),this._updateStatus()}clearUndoRedo(unitID){const redoStack=this._getRedoStack(unitID);redoStack&&(redoStack.length=0);const undoStack=this._getUndoStack(unitID);undoStack&&(undoStack.length=0),this._updateStatus()}pitchTopUndoElement(){const unitID=this._getFocusedUnitId();return this._pitchUndoElement(unitID)}pitchTopRedoElement(){const unitID=this._getFocusedUnitId();return this._pitchRedoElement(unitID)}_pitchUndoElement(unitId){const stack=this._getUndoStack(unitId);return stack!=null&&stack.length?stack[stack.length-1]:null}_pitchRedoElement(unitId){const stack=this._getRedoStack(unitId);return stack!=null&&stack.length?stack[stack.length-1]:null}popUndoToRedo(){const element=this._getUndoStackForFocused().pop();element&&(this._getRedoStackForFocused().push(element),this._updateStatus())}popRedoToUndo(){const element=this._getRedoStackForFocused().pop();element&&(this._getUndoStackForFocused().push(element),this._updateStatus())}__tempBatchingUndoRedo(unitId){if(this._batchingStatus.has(unitId))throw new Error("[LocalUndoRedoService]: cannot batching undo redo twice at the same time!");return this._batchingStatus.set(unitId,0),toDisposable(()=>this._batchingStatus.delete(unitId))}_updateStatus(){var _a13,_b2;const unitID=this._getFocusedUnitId(),undos=unitID&&((_a13=this._undoStacks.get(unitID))==null?void 0:_a13.length)||0,redos=unitID&&((_b2=this._redoStacks.get(unitID))==null?void 0:_b2.length)||0;this._undoRedoStatus$.next({undos,redos})}_getUndoStack(unitId,createAsNeeded=!1){let stack=this._undoStacks.get(unitId);return!stack&&createAsNeeded&&(stack=[],this._undoStacks.set(unitId,stack)),stack||null}_getRedoStack(unitId,createAsNeeded=!1){let stack=this._redoStacks.get(unitId);return!stack&&createAsNeeded&&(stack=[],this._redoStacks.set(unitId,stack)),stack||null}_getUndoStackForFocused(){const unitID=this._getFocusedUnitId();if(!unitID)throw new Error("No focused univer instance!");return this._getUndoStack(unitID,!0)}_getRedoStackForFocused(){const unitID=this._getFocusedUnitId();if(!unitID)throw new Error("No focused univer instance!");return this._getRedoStack(unitID,!0)}_tryBatchingElements(item,newItem){item.redoMutations.push(...newItem.redoMutations),item.undoMutations.push(...newItem.undoMutations)}_getFocusedUnitId(){var _a13,_b2,_c,_d;let unitID="";const isFocusSheet=this._contextService.getContextValue(FOCUSING_SHEET),isFocusFormulaEditor=this._contextService.getContextValue(FOCUSING_FX_BAR_EDITOR),isFocusEditor=this._contextService.getContextValue(EDITOR_ACTIVATED);return isFocusSheet?isFocusFormulaEditor?unitID=DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY:isFocusEditor?unitID=DOCS_NORMAL_EDITOR_UNIT_ID_KEY:unitID=(_b2=(_a13=this._univerInstanceService.getFocusedUnit())==null?void 0:_a13.getUnitId())!=null?_b2:"":unitID=(_d=(_c=this._univerInstanceService.getFocusedUnit())==null?void 0:_c.getUnitId())!=null?_d:"",unitID}},__name(_a8,"LocalUndoRedoService"),_a8);exports.LocalUndoRedoService=__decorateClass$3([__decorateParam$2(0,IUniverInstanceService),__decorateParam$2(1,ICommandService),__decorateParam$2(2,IContextService)],exports.LocalUndoRedoService);const DependentOnSymbol=Symbol("DependentOn"),_Plugin=class _Plugin extends Disposable{onStarting(_injector){}onReady(){}onRendered(){}onSteady(){}getUniverInstanceType(){return this.constructor.type}getPluginName(){return this.constructor.pluginName}};__name(_Plugin,"Plugin"),__publicField(_Plugin,"pluginName"),__publicField(_Plugin,"type",I.UNIVER_UNKNOWN);let Plugin=_Plugin;const _PluginStore=class _PluginStore{constructor(){__publicField(this,"_plugins",[])}addPlugin(plugin){this._plugins.push(plugin)}removePlugins(){const plugins=this._plugins.slice();return this._plugins.length=0,plugins}forEachPlugin(callback){this._plugins.forEach(callback)}};__name(_PluginStore,"PluginStore");let PluginStore=_PluginStore;const _PluginRegistry=class _PluginRegistry{constructor(){__publicField(this,"_pluginsRegistered",[])}registerPlugin(pluginCtor,options){this._pluginsRegistered.push({plugin:pluginCtor,options})}getRegisterPlugins(){return this._pluginsRegistered.slice()}removePlugins(){this._pluginsRegistered=[]}};__name(_PluginRegistry,"PluginRegistry");let PluginRegistry=_PluginRegistry;var __defProp$2=Object.defineProperty,__getOwnPropDesc$2=Object.getOwnPropertyDescriptor,__decorateClass$2=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$2(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$2(target,key,result),result},"__decorateClass$2"),__decorateParam$1=__name((index2,decorator)=>(target,key)=>decorator(target,key,index2),"__decorateParam$1");const INIT_LAZY_PLUGINS_TIMEOUT=4;function DependentOn(...plugins){return function(target){target[DependentOnSymbol]=plugins}}__name(DependentOn,"DependentOn");var _a9;exports.PluginService=(_a9=class{constructor(_injector){__publicField(this,"_pluginHolderForUniver");__publicField(this,"_pluginHoldersForTypes",new Map);__publicField(this,"_seenPlugins",new Set);__publicField(this,"_flushTimer");this._injector=_injector,this._pluginHolderForUniver=this._injector.createInstance(PluginHolder,this._checkPluginSeen.bind(this),this._immediateInitPlugin.bind(this)),this._pluginHolderForUniver.start()}dispose(){this._clearFlushTimer();for(const holder of this._pluginHoldersForTypes.values())holder.dispose();this._pluginHolderForUniver.dispose()}registerPlugin(ctor,config){this._assertPluginValid(ctor),this._scheduleInitPlugin();const{type:type2}=ctor;type2===I.UNIVER_UNKNOWN?(this._pluginHolderForUniver.register(ctor,config),this._pluginHolderForUniver.flush()):this._ensurePluginHolderForType(type2).register(ctor,config)}startPluginForType(type2){this._ensurePluginHolderForType(type2).start()}_ensurePluginHolderForType(type2){if(!this._pluginHoldersForTypes.has(type2)){const pluginHolder=this._injector.createInstance(PluginHolder,this._checkPluginSeen.bind(this),this._immediateInitPlugin.bind(this));return this._pluginHoldersForTypes.set(type2,pluginHolder),pluginHolder}return this._pluginHoldersForTypes.get(type2)}_immediateInitPlugin(ctor){this._seenPlugins.add(ctor.pluginName),this._ensurePluginHolderForType(ctor.type).immediateInitPlugin(ctor)}_checkPluginSeen(ctor){return this._seenPlugins.has(ctor.pluginName)}_assertPluginValid(ctor){const{type:type2,pluginName}=ctor;if(type2===I.UNRECOGNIZED)throw new Error(`[PluginService]: invalid plugin type for ${ctor}. Please assign a "type" to your plugin.`);if(pluginName==="")throw new Error(`[PluginService]: no plugin name for ${ctor}. Please assign a "pluginName" to your plugin.`);if(this._seenPlugins.has(pluginName))throw new Error(`[PluginService]: duplicated plugin name for "${pluginName}". Maybe a plugin that dependents on "${pluginName} has already registered it. In that case please register "${pluginName}" before the that plugin.`);this._seenPlugins.add(ctor.pluginName)}_scheduleInitPlugin(){this._flushTimer===void 0&&(this._flushTimer=setTimeout(()=>{this._pluginHolderForUniver.started||this._pluginHolderForUniver.start(),this._flushPlugins(),this._clearFlushTimer()},INIT_LAZY_PLUGINS_TIMEOUT))}_clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}_flushPlugins(){this._pluginHolderForUniver.flush();for(const[_,holder]of this._pluginHoldersForTypes)holder.started&&holder.flush()}},__name(_a9,"PluginService"),_a9);exports.PluginService=__decorateClass$2([__decorateParam$1(0,Inject(Injector))],exports.PluginService);var _a10;let PluginHolder=(_a10=class extends Disposable{constructor(_checkPluginRegistered,_registerPlugin,_logService,_injector,_lifecycleService,_lifecycleInitializerService){super();__publicField(this,"_started",!1);__publicField(this,"_warnedAboutOnStartingDeprecation",!1);__publicField(this,"_pluginRegistry",new PluginRegistry);__publicField(this,"_pluginStore",new PluginStore);__publicField(this,"_awaitingPlugins",[]);this._checkPluginRegistered=_checkPluginRegistered,this._registerPlugin=_registerPlugin,this._logService=_logService,this._injector=_injector,this._lifecycleService=_lifecycleService,this._lifecycleInitializerService=_lifecycleInitializerService,this.disposeWithMe(this._lifecycleService.lifecycle$.pipe(rxjs.skip(1)).subscribe(stage=>{this._awaitingPlugins.forEach(plugins=>this._runStage(plugins,stage))}))}get started(){return this._started}dispose(){super.dispose(),this._pluginStore.forEachPlugin(plugin=>plugin.dispose()),this._pluginStore.removePlugins(),this._pluginRegistry.removePlugins(),this._awaitingPlugins.length=0}register(pluginCtor,config){this._pluginRegistry.registerPlugin(pluginCtor,config)}immediateInitPlugin(plugin){const p=this._initPlugin(plugin,void 0);this._pluginsRunLifecycle([p])}start(){this._started||(this._started=!0,this.flush())}flush(){if(!this._started)return;const plugins=this._pluginRegistry.getRegisterPlugins().map(({plugin,options})=>this._initPlugin(plugin,options));plugins.length&&(this._pluginsRunLifecycle(plugins),this._pluginRegistry.removePlugins())}_initPlugin(plugin,options){const dependents=plugin[DependentOnSymbol];if(dependents){const exhaustUnregisteredDependents=__name(()=>{const NotRegistered=dependents.find(d=>!this._checkPluginRegistered(d));return NotRegistered?(this._logService.debug("[PluginService]",`plugin "${plugin.pluginName}" depends on "${NotRegistered.pluginName}" which is not registered. Univer will automatically register it with default configuration.`),this._registerPlugin(NotRegistered,void 0),!0):!1},"exhaustUnregisteredDependents");for(;exhaustUnregisteredDependents(););}const pluginInstance=this._injector.createInstance(plugin,options);return this._pluginStore.addPlugin(pluginInstance),pluginInstance}_pluginsRunLifecycle(plugins){getLifecycleStagesAndBefore(this._lifecycleService.stage).subscribe(stage=>this._runStage(plugins,stage)),this._awaitingPlugins.push(plugins)}_runStage(plugins,stage){plugins.forEach(p=>{switch(stage){case LifecycleStages.Starting:p.onStarting.length>0&&p.onStarting!==Plugin.prototype.onStarting&&!this._warnedAboutOnStartingDeprecation&&(this._logService.warn("[PluginService]",p.onStarting.length,`Plugin "${p.getPluginName()}" is using deprecated "onStarting" method with arguments. Please use "this._injector" instead.`),this._warnedAboutOnStartingDeprecation=!0),p.onStarting(this._injector);break;case LifecycleStages.Ready:p.onReady();break;case LifecycleStages.Rendered:p.onRendered();break;case LifecycleStages.Steady:p.onSteady();break}}),this._lifecycleInitializerService.initModulesOnStage(stage)}},__name(_a10,"PluginHolder"),_a10);PluginHolder=__decorateClass$2([__decorateParam$1(2,ILogService),__decorateParam$1(3,Inject(Injector)),__decorateParam$1(4,Inject(exports.LifecycleService)),__decorateParam$1(5,Inject(exports.LifecycleInitializerService))],PluginHolder);function mergeOverrideWithDependencies(dependencies,override){if(!override)return dependencies;const result=[];for(const dependency of dependencies){const overrideItem=override.find(([identifier])=>identifier===dependency[0]);if(overrideItem){if(overrideItem[1]===null)continue;result.push([dependency[0],overrideItem[1]])}else result.push(dependency)}return result}__name(mergeOverrideWithDependencies,"mergeOverrideWithDependencies");const nameMap={[G.Editor]:"Editor",[G.Owner]:"Owner",[G.Reader]:"Reader",[G.UNRECOGNIZED]:"UNRECOGNIZED"},createDefaultUser=__name(type2=>type2?{userID:`${nameMap[type2]}_${Tools.generateRandomId(8)}`,name:nameMap[type2],avatar:""}:{userID:"",name:"",avatar:"",anonymous:!0,canBindAnonymous:!1},"createDefaultUser"),isDevRole=__name((userId,type2)=>userId.startsWith(nameMap[type2]),"isDevRole");var __defProp$1=Object.defineProperty,__getOwnPropDesc$1=Object.getOwnPropertyDescriptor,__decorateClass$1=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$1(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$1(target,key,result),result},"__decorateClass$1"),_a11;exports.UserManagerService=(_a11=class{constructor(){__publicField(this,"_model",new Map);__publicField(this,"_userChange$",new rxjs.Subject);__publicField(this,"userChange$",this._userChange$.asObservable());__publicField(this,"_currentUser$",new rxjs.BehaviorSubject(createDefaultUser()));__publicField(this,"currentUser$",this._currentUser$.asObservable())}getCurrentUser(){return this._currentUser$.getValue()}setCurrentUser(user){this.addUser(user),this._currentUser$.next(user)}addUser(user){this._model.set(user.userID,user),this._userChange$.next({type:"add",user})}getUser(userId,callBack){const user=this._model.get(userId);if(user)return user;callBack&&callBack()}delete(userId){const user=this.getUser(userId);this._model.delete(userId),user&&this._userChange$.next({type:"delete",user})}clear(){this._model.clear(),this._userChange$.next({type:"clear"})}list(){return Array.from(this._model.values())}},__name(_a11,"UserManagerService"),_a11);exports.UserManagerService=__decorateClass$1([OnLifecycle(LifecycleStages.Starting,exports.UserManagerService)],exports.UserManagerService);var __defProp2=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__decorateClass=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp2(target,key,result),result},"__decorateClass"),__decorateParam=__name((index2,decorator)=>(target,key)=>decorator(target,key,index2),"__decorateParam"),_a12;exports.AuthzIoLocalService=(_a12=class{constructor(_resourceManagerService,_userManagerService){__publicField(this,"_permissionMap",new Map([]));this._resourceManagerService=_resourceManagerService,this._userManagerService=_userManagerService,this._initSnapshot(),this._initDefaultUser()}_initDefaultUser(){const currentUser=this._userManagerService.getCurrentUser();currentUser&&currentUser.userID||this._userManagerService.setCurrentUser(createDefaultUser(G.Owner))}_getRole(type2){const user=this._userManagerService.getCurrentUser();return user?isDevRole(user.userID,type2):!1}_initSnapshot(){this._resourceManagerService.registerPluginResource({toJson:__name(_unitId=>{const obj=[...this._permissionMap.keys()].reduce((r,k)=>{const v=this._permissionMap.get(k);return r[k]=v,r},{});return JSON.stringify(obj)},"toJson"),parseJson:__name(json=>JSON.parse(json),"parseJson"),pluginName:"SHEET_AuthzIoMockService_PLUGIN",businesses:[I.UNIVER_SHEET,I.UNIVER_DOC,I.UNIVER_SLIDE],onLoad:__name((_unitId,resource)=>{for(const key in resource)this._permissionMap.set(key,resource[key])},"onLoad"),onUnLoad:__name(()=>{this._permissionMap.clear()},"onUnLoad")})}async create(config){return generateRandomId(8)}async allowed(_config){return Promise.resolve([])}async batchAllowed(_config){return Promise.resolve([])}async list(config){const result=[];return config.objectIDs.forEach(objectID=>{const rule=this._permissionMap.get(objectID);if(rule){const item={objectID,unitID:config.unitID,objectType:rule.objectType,name:rule.name,shareOn:!1,shareRole:G.Owner,shareScope:-1,scope:{read:H.AllCollaborator,edit:H.AllCollaborator},creator:createDefaultUser(G.Owner),strategies:[{action:6,role:1},{action:16,role:1},{action:17,role:1},{action:18,role:1},{action:19,role:1},{action:33,role:1},{action:34,role:1},{action:35,role:1},{action:36,role:1},{action:37,role:1},{action:38,role:1},{action:39,role:1},{action:40,role:1}],actions:config.actions.map(a=>({action:a,allowed:this._getRole(G.Owner)||this._getRole(G.Editor)}))};result.push(item)}}),result}async listCollaborators(){return[]}async listRoles(){return{roles:[],actions:[]}}async deleteCollaborator(){}async update(config){}async updateCollaborator(){}async createCollaborator(){}async putCollaborators(config){}},__name(_a12,"AuthzIoLocalService"),_a12);exports.AuthzIoLocalService=__decorateClass([__decorateParam(0,IResourceManagerService),__decorateParam(1,Inject(exports.UserManagerService))],exports.AuthzIoLocalService);const IAuthzIoService=createIdentifier("IAuthzIoIoService"),_Univer=class _Univer{constructor(config={},parentInjector){__publicField(this,"_startedTypes",new Set);__publicField(this,"_injector");const injector=this._injector=createUniverInjector(parentInjector,config==null?void 0:config.override),{theme,locale,locales,logLevel}=config;theme&&this._injector.get(ThemeService).setTheme(theme),locales&&this._injector.get(LocaleService).load(locales),locale&&this._injector.get(LocaleService).setLocale(locale),logLevel&&this._injector.get(ILogService).setLogLevel(logLevel),this._init(injector)}get _univerInstanceService(){return this._injector.get(IUniverInstanceService)}get _pluginService(){return this._injector.get(exports.PluginService)}__getInjector(){return this._injector}dispose(){this._injector.dispose()}setLocale(locale){this._injector.get(LocaleService).setLocale(locale)}createUnit(type2,data){return this._univerInstanceService.createUnit(type2,data)}createUniverSheet(data){return this._univerInstanceService.createUnit(I.UNIVER_SHEET,data)}createUniverDoc(data){return this._univerInstanceService.createUnit(I.UNIVER_DOC,data)}createUniverSlide(data){return this._univerInstanceService.createUnit(I.UNIVER_SLIDE,data)}_init(injector){this._univerInstanceService.registerCtorForType(I.UNIVER_SHEET,exports.Workbook),this._univerInstanceService.registerCtorForType(I.UNIVER_DOC,DocumentDataModel),this._univerInstanceService.registerCtorForType(I.UNIVER_SLIDE,SlideDataModel);const univerInstanceService=injector.get(IUniverInstanceService);univerInstanceService.__setCreateHandler((type2,data,ctor,options)=>{if(!this._startedTypes.has(type2)){this._pluginService.startPluginForType(type2),this._startedTypes.add(type2);const model2=injector.createInstance(ctor,data);return univerInstanceService.__addUnit(model2,options),this._tryProgressToReady(),model2}const model=injector.createInstance(ctor,data);return univerInstanceService.__addUnit(model,options),model})}_tryProgressToReady(){this._injector.get(exports.LifecycleService).stage<LifecycleStages.Ready&&(this._injector.get(exports.LifecycleService).stage=LifecycleStages.Ready)}registerPlugin(plugin,config){this._pluginService.registerPlugin(plugin,config)}};__name(_Univer,"Univer");let Univer=_Univer;function createUniverInjector(parentInjector,override){const dependencies=mergeOverrideWithDependencies([[ErrorService],[LocaleService],[ThemeService],[exports.LifecycleService],[exports.LifecycleInitializerService],[exports.PluginService],[exports.UserManagerService],[IUniverInstanceService,{useClass:exports.UniverInstanceService}],[IPermissionService,{useClass:PermissionService}],[ILogService,{useClass:DesktopLogService,lazy:!0}],[ICommandService,{useClass:exports.CommandService}],[IUndoRedoService,{useClass:exports.LocalUndoRedoService,lazy:!0}],[IConfigService,{useClass:ConfigService}],[IContextService,{useClass:ContextService}],[IResourceManagerService,{useClass:ResourceManagerService,lazy:!0}],[IResourceLoaderService,{useClass:ResourceLoaderService,lazy:!0}],[IAuthzIoService,{useClass:exports.AuthzIoLocalService,lazy:!0}]],override);return parentInjector?parentInjector.createChild(dependencies):new Injector(dependencies)}__name(createUniverInjector,"createUniverInjector");function shallowEqual(objA,objB){if(Object.is(objA,objB))return!0;if(typeof objA!="object"||!objA||typeof objB!="object"||!objB)return!1;const keysA=Object.keys(objA),keysB=Object.keys(objB);if(keysA.length!==keysB.length)return!1;const bHasOwnProperty=Object.prototype.hasOwnProperty.bind(objB);for(let idx=0;idx<keysA.length;idx++){const key=keysA[idx];if(!bHasOwnProperty(key))return!1;const valueA=objA[key],valueB=objB[key];if(valueA!==valueB)return!1}return!0}__name(shallowEqual,"shallowEqual");function isNumeric(str){return/^-?\d+(\.\d+)?$/.test(str)}__name(isNumeric,"isNumeric");function isSafeNumeric(str){return isNumeric(str)?Number(str)<=Number.MAX_SAFE_INTEGER:!1}__name(isSafeNumeric,"isSafeNumeric");function isBooleanString(str){return["true","false"].includes(str.toLowerCase())}__name(isBooleanString,"isBooleanString");function mergeSets(s1,s2){return s2.forEach(s=>s1.add(s)),s1}__name(mergeSets,"mergeSets");function throttle(fn,wait=16){let lastTime=0,timer=null;return __name(function(...args){const now=Date.now();now-lastTime<wait?(timer&&clearTimeout(timer),timer=setTimeout(()=>{lastTime=now,fn.apply(this,args)},wait)):(lastTime=now,fn.apply(this,args))},"throttled")}__name(throttle,"throttle");function requestImmediateMacroTask(callback){const channel=new MessageChannel;let cancelled=!1;const hanlder=__name(()=>{cancelled||callback()},"hanlder");return channel.port1.onmessage=hanlder,channel.port2.postMessage(null),()=>{cancelled=!0,channel.port1.close(),channel.port2.close()}}__name(requestImmediateMacroTask,"requestImmediateMacroTask");var DataValidationRenderMode=(DataValidationRenderMode2=>(DataValidationRenderMode2[DataValidationRenderMode2.TEXT=0]="TEXT",DataValidationRenderMode2[DataValidationRenderMode2.ARROW=1]="ARROW",DataValidationRenderMode2[DataValidationRenderMode2.CUSTOM=2]="CUSTOM",DataValidationRenderMode2))(DataValidationRenderMode||{});function replaceInDocumentBody(body,query,target){if(query==="")return body;const mockDocumentData={id:"mock-id",body,documentStyle:{}},documentDataModel=new DocumentDataModel(mockDocumentData),queryLen=query.length;let index2;for(;(index2=documentDataModel.getBody().dataStream.indexOf(query))>=0;){const textX=new TextX,jsonX=JSONX.getInstance();if(index2>0&&textX.retain(index2),target.length>0){const sliceBody=documentDataModel.sliceBody(index2,index2+queryLen),replaceBody={dataStream:target};Array.isArray(sliceBody==null?void 0:sliceBody.textRuns)&&sliceBody.textRuns.length&&(replaceBody.textRuns=[{...sliceBody.textRuns[0],st:0,ed:target.length}]),textX.insert(target.length,replaceBody)}textX.delete(queryLen),documentDataModel.apply(jsonX.editOp(textX.serialize()))}const newBody=documentDataModel.getBody();return documentDataModel.dispose(),newBody}__name(replaceInDocumentBody,"replaceInDocumentBody");const _EventState=class _EventState{constructor(){__publicField(this,"skipNextObservers",!1);__publicField(this,"lastReturnValue");__publicField(this,"isStopPropagation",!1)}stopPropagation(){this.isStopPropagation=!0}};__name(_EventState,"EventState");let EventState=_EventState;const _EventSubject=class _EventSubject extends rxjs.Subject{constructor(){super(...arguments);__publicField(this,"_sortedObservers",[])}subscribe(){throw new Error("[EventSubject]: please use `subscribeEvent` instead of `subscribe` method for `EventSubject`.")}next(){throw new Error("[EventSubject]: please use `emitEvent` instead of `next` method for `EventSubject`.")}unsubscribe(){super.unsubscribe(),this._sortedObservers.length=0}complete(){super.complete(),this._sortedObservers.length=0}subscribeEvent(observer){let ob;typeof observer=="function"?ob={next:__name(([evt,state])=>observer(evt,state),"next")}:ob=observer;const subscription=super.subscribe(ob);return this._sortedObservers.push(ob),this._sortedObservers.sort((a,b)=>{var _a13,_b2;return((_a13=a.priority)!=null?_a13:0)-((_b2=b.priority)!=null?_b2:0)}),subscription.add(()=>this._sortedObservers=this._sortedObservers.filter(o=>o!==ob)),subscription}clearObservers(){this._sortedObservers.forEach(observer=>{var _a13;return(_a13=observer.complete)==null?void 0:_a13.call(observer)}),this._sortedObservers.length=0}emitEvent(event){var _a13;if(!this.closed){const state=new EventState;state.lastReturnValue=event;for(const observer of this._sortedObservers){const value=(_a13=observer.next)==null?void 0:_a13.call(observer,[event,state]);if(state.lastReturnValue=value,state.skipNextObservers)return{handled:!0,lastReturnValue:state.lastReturnValue,stopPropagation:state.isStopPropagation}}return{handled:this._sortedObservers.length>0,lastReturnValue:state.lastReturnValue,stopPropagation:state.isStopPropagation}}throw new Error("[EventSubject]: cannot emit event on a closed subject.")}};__name(_EventSubject,"EventSubject");let EventSubject=_EventSubject;function fromEventSubject(subject$){return new rxjs.Observable(subscriber=>{const ob=subject$.subscribeEvent(evt=>{subscriber.next(evt)});return()=>ob.unsubscribe()})}__name(fromEventSubject,"fromEventSubject");const ILocalStorageService=createIdentifier("ILocalStorageService");function createInterceptorKey(key){return`sheet_interceptor_${key}`}__name(createInterceptorKey,"createInterceptorKey");const composeInterceptors=__name(interceptors=>function(initialValue,context){let index2=-1;function passThrough(i,v){if(i<=index2)throw new Error("[SheetInterceptorService]: next() called multiple times!");return index2=i,i===interceptors.length?v:interceptors[i].handler(v,context,passThrough.bind(null,i+1))}return __name(passThrough,"passThrough"),passThrough(0,initialValue)},"composeInterceptors"),_InterceptorManager=class _InterceptorManager{constructor(interceptorPoints){__publicField(this,"_interceptorsByName",new Map);__publicField(this,"_interceptorPoints");this._interceptorPoints=interceptorPoints}fetchThroughInterceptors(name){const key=name,interceptors=this._interceptorsByName.get(key);return composeInterceptors(interceptors||[])}intercept(name,interceptor){const key=name;this._interceptorsByName.has(key)||this._interceptorsByName.set(key,[]);const interceptors=this._interceptorsByName.get(key);return interceptors.push(interceptor),this._interceptorsByName.set(key,interceptors.sort((a,b)=>{var _a13,_b2;return((_a13=b.priority)!=null?_a13:0)-((_b2=a.priority)!=null?_b2:0)})),()=>remove(this._interceptorsByName.get(key),interceptor)}getInterceptPoints(){return this._interceptorPoints}};__name(_InterceptorManager,"InterceptorManager");let InterceptorManager=_InterceptorManager;const isRangesEqual=__name((oldRanges,ranges)=>ranges.length===oldRanges.length&&!oldRanges.some(oldRange=>ranges.some(range=>!Rectangle.equals(range,oldRange))),"isRangesEqual"),isUnitRangesEqual=__name((oldRanges,ranges)=>ranges.length===oldRanges.length&&oldRanges.every((oldRange,i)=>{const current=ranges[i];return current.unitId===oldRange.unitId&&current.sheetId===oldRange.sheetId&&Rectangle.equals(oldRange.range,current.range)}),"isUnitRangesEqual");var DataValidationErrorStyle=(DataValidationErrorStyle2=>(DataValidationErrorStyle2[DataValidationErrorStyle2.INFO=0]="INFO",DataValidationErrorStyle2[DataValidationErrorStyle2.STOP=1]="STOP",DataValidationErrorStyle2[DataValidationErrorStyle2.WARNING=2]="WARNING",DataValidationErrorStyle2))(DataValidationErrorStyle||{}),DataValidationImeMode=(DataValidationImeMode2=>(DataValidationImeMode2[DataValidationImeMode2.DISABLED=0]="DISABLED",DataValidationImeMode2[DataValidationImeMode2.FULL_ALPHA=1]="FULL_ALPHA",DataValidationImeMode2[DataValidationImeMode2.FULL_HANGUL=2]="FULL_HANGUL",DataValidationImeMode2[DataValidationImeMode2.FULL_KATAKANA=3]="FULL_KATAKANA",DataValidationImeMode2[DataValidationImeMode2.HALF_ALPHA=4]="HALF_ALPHA",DataValidationImeMode2[DataValidationImeMode2.HALF_HANGUL=5]="HALF_HANGUL",DataValidationImeMode2[DataValidationImeMode2.HALF_KATAKANA=6]="HALF_KATAKANA",DataValidationImeMode2[DataValidationImeMode2.HIRAGANA=7]="HIRAGANA",DataValidationImeMode2[DataValidationImeMode2.NO_CONTROL=8]="NO_CONTROL",DataValidationImeMode2[DataValidationImeMode2.OFF=9]="OFF",DataValidationImeMode2[DataValidationImeMode2.ON=10]="ON",DataValidationImeMode2))(DataValidationImeMode||{}),DataValidationOperator=(DataValidationOperator2=>(DataValidationOperator2.BETWEEN="between",DataValidationOperator2.EQUAL="equal",DataValidationOperator2.GREATER_THAN="greaterThan",DataValidationOperator2.GREATER_THAN_OR_EQUAL="greaterThanOrEqual",DataValidationOperator2.LESS_THAN="lessThan",DataValidationOperator2.LESS_THAN_OR_EQUAL="lessThanOrEqual",DataValidationOperator2.NOT_BETWEEN="notBetween",DataValidationOperator2.NOT_EQUAL="notEqual",DataValidationOperator2))(DataValidationOperator||{}),DataValidationType=(DataValidationType2=>(DataValidationType2.CUSTOM="custom",DataValidationType2.LIST="list",DataValidationType2.LIST_MULTIPLE="listMultiple",DataValidationType2.NONE="none",DataValidationType2.TEXT_LENGTH="textLength",DataValidationType2.DATE="date",DataValidationType2.TIME="time",DataValidationType2.WHOLE="whole",DataValidationType2.DECIMAL="decimal",DataValidationType2.CHECKBOX="checkbox",DataValidationType2))(DataValidationType||{}),DataValidationStatus=(DataValidationStatus2=>(DataValidationStatus2.VALID="valid",DataValidationStatus2.INVALID="invalid",DataValidationStatus2.VALIDATING="validating",DataValidationStatus2))(DataValidationStatus||{});const skipParseTagNames=["script","style","meta","comment","link"];function nameCharacterCheck(name){return!(name.length===0||name.length>31||name.startsWith("'")||name.endsWith("'")||/[:\\\/\?\*\[\]]/.test(name))}__name(nameCharacterCheck,"nameCharacterCheck");function mixinClass(targetClassPrototype,mixin){for(const key in mixin)mixin.hasOwnProperty(key)&&(targetClassPrototype[key]=mixin[key])}__name(mixinClass,"mixinClass");installShims();exports.ABCToNumber=ABCToNumber;exports.AbsoluteRefType=AbsoluteRefType;exports.ActionIterator=ActionIterator;exports.AlignTypeH=AlignTypeH;exports.AlignTypeV=AlignTypeV;exports.ArrangeTypeEnum=ArrangeTypeEnum;exports.ArrowsAndMarkersShapes=ArrowsAndMarkersShapes;exports.AutoFillSeries=AutoFillSeries;exports.BaselineOffset=BaselineOffset;exports.BasicShapes=BasicShapes;exports.BlockType=BlockType;exports.BooleanNumber=BooleanNumber;exports.BorderStyleTypes=BorderStyleTypes;exports.BorderType=BorderType;exports.BulletAlignment=BulletAlignment;exports.COLORS=COLORS;exports.CellValueType=CellValueType;exports.Color=Color;exports.ColorBuilder=ColorBuilder;exports.ColorKit=ColorKit;exports.ColorType=ColorType;exports.ColumnSeparatorType=ColumnSeparatorType;exports.CommandType=CommandType;exports.CommonHideTypes=CommonHideTypes;exports.ConfigService=ConfigService;exports.ContextService=ContextService;exports.CopyPasteType=CopyPasteType;exports.CustomCommandExecutionError=CustomCommandExecutionError;exports.CustomDecorationType=CustomDecorationType;exports.CustomRangeType=CustomRangeType;exports.DEFAULT_CELL=DEFAULT_CELL;exports.DEFAULT_DOC=DEFAULT_DOC;exports.DEFAULT_DOCUMENT_SUB_COMPONENT_ID=DEFAULT_DOCUMENT_SUB_COMPONENT_ID;exports.DEFAULT_EMPTY_DOCUMENT_VALUE=DEFAULT_EMPTY_DOCUMENT_VALUE;exports.DEFAULT_RANGE=DEFAULT_RANGE;exports.DEFAULT_RANGE_ARRAY=DEFAULT_RANGE_ARRAY;exports.DEFAULT_SELECTION=DEFAULT_SELECTION;exports.DEFAULT_SLIDE=DEFAULT_SLIDE;exports.DEFAULT_STYLES=DEFAULT_STYLES;exports.DEFAULT_WORKSHEET_COLUMN_COUNT=DEFAULT_WORKSHEET_COLUMN_COUNT;exports.DEFAULT_WORKSHEET_COLUMN_COUNT_KEY=DEFAULT_WORKSHEET_COLUMN_COUNT_KEY;exports.DEFAULT_WORKSHEET_COLUMN_TITLE_HEIGHT=DEFAULT_WORKSHEET_COLUMN_TITLE_HEIGHT;exports.DEFAULT_WORKSHEET_COLUMN_TITLE_HEIGHT_KEY=DEFAULT_WORKSHEET_COLUMN_TITLE_HEIGHT_KEY;exports.DEFAULT_WORKSHEET_COLUMN_WIDTH=DEFAULT_WORKSHEET_COLUMN_WIDTH;exports.DEFAULT_WORKSHEET_COLUMN_WIDTH_KEY=DEFAULT_WORKSHEET_COLUMN_WIDTH_KEY;exports.DEFAULT_WORKSHEET_ROW_COUNT=DEFAULT_WORKSHEET_ROW_COUNT;exports.DEFAULT_WORKSHEET_ROW_COUNT_KEY=DEFAULT_WORKSHEET_ROW_COUNT_KEY;exports.DEFAULT_WORKSHEET_ROW_HEIGHT=DEFAULT_WORKSHEET_ROW_HEIGHT;exports.DEFAULT_WORKSHEET_ROW_HEIGHT_KEY=DEFAULT_WORKSHEET_ROW_HEIGHT_KEY;exports.DEFAULT_WORKSHEET_ROW_TITLE_WIDTH=DEFAULT_WORKSHEET_ROW_TITLE_WIDTH;exports.DEFAULT_WORKSHEET_ROW_TITLE_WIDTH_KEY=DEFAULT_WORKSHEET_ROW_TITLE_WIDTH_KEY;exports.DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY=DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY;exports.DOCS_NORMAL_EDITOR_UNIT_ID_KEY=DOCS_NORMAL_EDITOR_UNIT_ID_KEY;exports.DOCS_ZEN_EDITOR_UNIT_ID_KEY=DOCS_ZEN_EDITOR_UNIT_ID_KEY;exports.DashStyleType=DashStyleType;exports.DataStreamTreeNodeType=DataStreamTreeNodeType;exports.DataStreamTreeTokenType=DataStreamTreeTokenType;exports.DataValidationErrorStyle=DataValidationErrorStyle;exports.DataValidationImeMode=DataValidationImeMode;exports.DataValidationOperator=DataValidationOperator;exports.DataValidationRenderMode=DataValidationRenderMode;exports.DataValidationStatus=DataValidationStatus;exports.DataValidationType=DataValidationType;exports.DependentOn=DependentOn;exports.DesktopLogService=DesktopLogService;exports.DeveloperMetadataVisibility=DeveloperMetadataVisibility;exports.Dimension=Dimension;exports.Direction=Direction;exports.Disposable=Disposable;exports.DisposableCollection=DisposableCollection;exports.DocStyleType=DocStyleType;exports.DocumentDataModel=DocumentDataModel;exports.DocumentFlavor=DocumentFlavor;exports.DrawingTypeEnum=DrawingTypeEnum;exports.EDITOR_ACTIVATED=EDITOR_ACTIVATED;exports.EXTENSION_NAMES=EXTENSION_NAMES;exports.Entry=Entry;exports.EntryIterator=EntryIterator;exports.ErrorService=ErrorService;exports.EventState=EventState;exports.EventSubject=EventSubject;exports.FOCUSING_COMMON_DRAWINGS=FOCUSING_COMMON_DRAWINGS;exports.FOCUSING_DOC=FOCUSING_DOC;exports.FOCUSING_EDITOR_BUT_HIDDEN=FOCUSING_EDITOR_BUT_HIDDEN;exports.FOCUSING_EDITOR_INPUT_FORMULA=FOCUSING_EDITOR_INPUT_FORMULA;exports.FOCUSING_EDITOR_STANDALONE=FOCUSING_EDITOR_STANDALONE;exports.FOCUSING_FX_BAR_EDITOR=FOCUSING_FX_BAR_EDITOR;exports.FOCUSING_SHEET=FOCUSING_SHEET;exports.FOCUSING_SLIDE=FOCUSING_SLIDE;exports.FOCUSING_UNIT=FOCUSING_UNIT;exports.FOCUSING_UNIVER_EDITOR=FOCUSING_UNIVER_EDITOR;exports.FOCUSING_UNIVER_EDITOR_STANDALONE_SINGLE_MODE=FOCUSING_UNIVER_EDITOR_STANDALONE_SINGLE_MODE;exports.FORMULA_EDITOR_ACTIVATED=FORMULA_EDITOR_ACTIVATED;exports.FollowNumberWithType=FollowNumberWithType;exports.FontItalic=FontItalic;exports.FontStyleType=FontStyleType;exports.FontWeight=FontWeight;exports.FormatType=FormatType;exports.GlyphType=GlyphType;exports.GridType=GridType;exports.HLSColor=HLSColor;exports.HorizontalAlign=HorizontalAlign;exports.IAuthzIoService=IAuthzIoService;exports.ICommandService=ICommandService;exports.IConfigService=IConfigService;exports.IContextService=IContextService;exports.ILocalStorageService=ILocalStorageService;exports.ILogService=ILogService;exports.IPermissionService=IPermissionService;exports.IResourceLoaderService=IResourceLoaderService;exports.IResourceManagerService=IResourceManagerService;exports.IUndoRedoService=IUndoRedoService;exports.IUniverInstanceService=IUniverInstanceService;exports.Inject=Inject;exports.Injector=Injector;exports.InterceptorManager=InterceptorManager;exports.InterpolationPointType=InterpolationPointType;exports.JSON1=index$1;exports.JSONX=JSONX;exports.KeyIterator=KeyIterator;exports.LRUHelper=LRUHelper;exports.LRUMap=LRUMap;exports.LifecycleStages=LifecycleStages;exports.LocaleService=LocaleService;exports.LocaleType=LocaleType;exports.LogLevel=LogLevel;exports.MOVE_BUFFER_VALUE=MOVE_BUFFER_VALUE;exports.Many=Many;exports.MemoryCursor=MemoryCursor;exports.NamedStyleType=NamedStyleType;exports.NilCommand=NilCommand;exports.NumberUnitType=NumberUnitType;exports.ObjectMatrix=ObjectMatrix;exports.ObjectRelativeFromH=ObjectRelativeFromH;exports.ObjectRelativeFromV=ObjectRelativeFromV;exports.OnLifecycle=OnLifecycle;exports.Optional=Optional;exports.OtherShapes=OtherShapes;exports.PRESET_LIST_TYPE=PRESET_LIST_TYPE;exports.PageElementType=PageElementType;exports.PageOrientType=PageOrientType;exports.PageType=PageType;exports.ParagraphElementType=ParagraphElementType;exports.PermissionService=PermissionService;exports.PermissionStatus=PermissionStatus;exports.Plugin=Plugin;exports.PositionedObjectLayoutType=PositionedObjectLayoutType;exports.PresetListType=PresetListType;exports.ProtectionType=ProtectionType;exports.QuickListType=QuickListType;exports.QuickListTypeMap=QuickListTypeMap;exports.RANGE_TYPE=RANGE_TYPE;exports.RCDisposable=RCDisposable;exports.RGBA_PAREN=RGBA_PAREN;exports.RGB_PAREN=RGB_PAREN;exports.ROTATE_BUFFER_VALUE=ROTATE_BUFFER_VALUE;exports.Range=Range;exports.Rectangle=Rectangle;exports.RediConsumer=RediConsumer;exports.RediContext=RediContext;exports.RediError=RediError;exports.RediProvider=RediProvider;exports.RedoCommand=RedoCommand;exports.RedoCommandId=RedoCommandId;exports.RefAlias=RefAlias;exports.Registry=Registry;exports.RegistryAsMap=RegistryAsMap;exports.RelativeDate=RelativeDate;exports.RelativeSlideLink=RelativeSlideLink;exports.ResourceManagerService=ResourceManagerService;exports.RgbColor=RgbColor;exports.RxDisposable=RxDisposable;exports.SectionType=SectionType;exports.Self=Self;exports.SheetTypes=SheetTypes;exports.SheetViewModel=SheetViewModel;exports.SkipSelf=SkipSelf;exports.SliceBodyType=SliceBodyType;exports.SlideDataModel=SlideDataModel;exports.SpacingRule=SpacingRule;exports.SpecialShapes=SpecialShapes;exports.Styles=Styles;exports.THEME_COLORS=THEME_COLORS;exports.TabStopAlignment=TabStopAlignment;exports.TableAlignmentType=TableAlignmentType;exports.TableCellHeightRule=TableCellHeightRule;exports.TableLayoutType=TableLayoutType;exports.TableSizeType=TableSizeType;exports.TableTextWrapType=TableTextWrapType;exports.TextDecoration=TextDecoration;exports.TextDirection=TextDirection;exports.TextDirectionType=TextDirectionType;exports.TextX=TextX;exports.TextXActionType=TextXActionType;exports.ThemeColor=ThemeColor;exports.ThemeColorType=ThemeColorType;exports.ThemeColors=ThemeColors;exports.ThemeService=ThemeService;exports.Tools=Tools;exports.UNIVER_INTERNAL=UNIVER_INTERNAL;exports.UndoCommand=UndoCommand;exports.UndoCommandId=UndoCommandId;exports.UnitModel=UnitModel;exports.Univer=Univer;exports.UniverInstanceType=I;exports.UpdateDocsAttributeType=UpdateDocsAttributeType;exports.ValueIterator=ValueIterator;exports.VerticalAlign=VerticalAlign;exports.VerticalAlignmentType=VerticalAlignmentType;exports.WithDependency=WithDependency;exports.WithNew=WithNew;exports.Worksheet=Worksheet;exports.WrapStrategy=WrapStrategy;exports.WrapTextType=WrapTextType;exports.afterInitApply=afterInitApply;exports.binarySearchArray=binarySearchArray;exports.cellToRange=cellToRange;exports.characterSpacingControlType=characterSpacingControlType;exports.checkForSubstrings=checkForSubstrings;exports.checkIfMove=checkIfMove;exports.checkParagraphHasBullet=checkParagraphHasBullet;exports.checkParagraphHasIndent=checkParagraphHasIndent;exports.checkParagraphHasIndentByStyle=checkParagraphHasIndentByStyle;exports.codeToBlob=codeToBlob;exports.composeBody=composeBody;exports.composeInterceptors=composeInterceptors;exports.concatMatrixArray=concatMatrixArray;exports.connectDependencies=connectDependencies;exports.connectInjector=connectInjector;exports.convertBodyToHtml=convertBodyToHtml;exports.covertTextRunToHtml=covertTextRunToHtml;exports.createDefaultUser=createDefaultUser;exports.createIdentifier=createIdentifier;exports.createInterceptorKey=createInterceptorKey;exports.createInternalEditorID=createInternalEditorID;exports.createRowColIter=createRowColIter;exports.debounce=debounce;exports.dedupe=dedupe;exports.deepCompare=deepCompare;exports.deleteContent=deleteContent;exports.extractPureTextFromCell=extractPureTextFromCell;exports.forwardRef=forwardRef;exports.fromCallback=fromCallback;exports.fromEventSubject=fromEventSubject;exports.fromObservable=fromObservable;exports.generateRandomId=generateRandomId;exports.getArrayLength=getArrayLength;exports.getBodySlice=getBodySlice;exports.getBodySliceHtml=getBodySliceHtml;exports.getBorderStyleType=getBorderStyleType;exports.getCellInfoInMergeData=getCellInfoInMergeData;exports.getCellValueType=getCellValueType;exports.getColorStyle=getColorStyle;exports.getCustomDecorationSlice=getCustomDecorationSlice;exports.getCustomRangeSlice=getCustomRangeSlice;exports.getDocsUpdateBody=getDocsUpdateBody;exports.getReverseDirection=getReverseDirection;exports.getWorksheetUID=getWorksheetUID;exports.groupBy=groupBy;exports.handleStyleToString=handleStyleToString;exports.hashAlgorithm=hashAlgorithm;exports.horizontalLineSegmentsSubtraction=horizontalLineSegmentsSubtraction;exports.insertMatrixArray=insertMatrixArray;exports.insertTextToContent=insertTextToContent;exports.isAsyncDependencyItem=isAsyncDependencyItem;exports.isAsyncHook=isAsyncHook;exports.isBlackColor=isBlackColor;exports.isBooleanString=isBooleanString;exports.isCellCoverable=isCellCoverable;exports.isCellV=isCellV;exports.isClassDependencyItem=isClassDependencyItem;exports.isCtor=isCtor;exports.isDisposable=isDisposable;exports.isEmptyCell=isEmptyCell;exports.isFactoryDependencyItem=isFactoryDependencyItem;exports.isFormulaId=isFormulaId;exports.isFormulaString=isFormulaString;exports.isICellData=isICellData;exports.isInternalEditorID=isInternalEditorID;exports.isNullCell=isNullCell;exports.isNumeric=isNumeric;exports.isRangesEqual=isRangesEqual;exports.isRealNum=isRealNum;exports.isSafeNumeric=isSafeNumeric;exports.isSameStyleTextRun=isSameStyleTextRun;exports.isUnitRangesEqual=isUnitRangesEqual;exports.isValidRange=isValidRange;exports.isValueDependencyItem=isValueDependencyItem;exports.isWhiteColor=isWhiteColor;exports.makeArray=makeArray;exports.makeCellRangeToRangeData=makeCellRangeToRangeData;exports.makeCellToSelection=makeCellToSelection;exports.makeCustomRangeStream=makeCustomRangeStream;exports.mergeOverrideWithDependencies=mergeOverrideWithDependencies;exports.mergeSets=mergeSets;exports.mergeWorksheetSnapshotWithDefault=mergeWorksheetSnapshotWithDefault;exports.mixinClass=mixinClass;exports.moveMatrixArray=moveMatrixArray;exports.moveRangeByOffset=moveRangeByOffset;exports.nameCharacterCheck=nameCharacterCheck;exports.normalizeBody=normalizeBody;exports.normalizeTextRuns=normalizeTextRuns;exports.numberToABC=numberToABC;exports.numberToListABC=numberToListABC;exports.numfmt=numfmt;exports.orderSearchArray=orderSearchArray;exports.queryObjectMatrix=queryObjectMatrix;exports.remove=remove;exports.repeatStringNumTimes=repeatStringNumTimes;exports.replaceInDocumentBody=replaceInDocumentBody;exports.requestImmediateMacroTask=requestImmediateMacroTask;exports.rotate=rotate;exports.runOnLifecycle=runOnLifecycle;exports.searchArray=searchArray;exports.selectionToArray=selectionToArray;exports.sequence=sequence;exports.sequenceAsync=sequenceAsync;exports.sequenceExecute=sequenceExecute;exports.sequenceExecuteAsync=sequenceExecuteAsync;exports.setDependencies=setDependencies;exports.shallowEqual=shallowEqual;exports.skipParseTagNames=skipParseTagNames;exports.sliceMatrixArray=sliceMatrixArray;exports.sortRules=sortRules;exports.sortRulesByDesc=sortRulesByDesc;exports.sortRulesFactory=sortRulesFactory;exports.spliceArray=spliceArray;exports.takeAfter=takeAfter;exports.throttle=throttle;exports.toDisposable=toDisposable;exports.updateAttributeByDelete=updateAttributeByDelete;exports.updateAttributeByInsert=updateAttributeByInsert;exports.useDependency=useDependency;exports.useDependencyContext=useDependencyContext;exports.useDependencyContextValue=useDependencyContextValue;exports.useDependencyValue=useDependencyValue;exports.useInjector=useInjector;exports.useObservable=useObservable;exports.useUpdateBinder=useUpdateBinder;