notu 0.4.0 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/notu.umd.js CHANGED
@@ -1,5 +1 @@
1
- (function(global2,factory){typeof exports=="object"&&typeof module<"u"?factory(exports):typeof define=="function"&&define.amd?define(["exports"],factory):(global2=typeof globalThis<"u"?globalThis:global2||self,factory(global2.notu={}))})(this,function(exports2){"use strict";var __defProp=Object.defineProperty;var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value;var __publicField=(obj,key,value)=>(__defNormalProp(obj,typeof key!="symbol"?key+"":key,value),value);class ModelWithState{constructor(){__publicField(this,"state","NEW")}new(){return this.state="NEW",this}clean(){return this.state="CLEAN",this}dirty(){return this.state="DIRTY",this}delete(){return this.state="DELETED",this}get isNew(){return this.state=="NEW"}get isClean(){return this.state=="CLEAN"}get isDirty(){return this.state=="DIRTY"}get isDeleted(){return this.state=="DELETED"}validate(throwError=!1){return!0}}class Attr extends ModelWithState{constructor(name){super();__publicField(this,"id",0);__publicField(this,"_name","");__publicField(this,"_type","TEXT");__publicField(this,"_spaceId",0);__publicField(this,"_space",null);name&&(this.name=name)}get name(){return this._name}set name(value){value!==this._name&&(this._name=value,this.isClean&&this.dirty())}get type(){return this._type}set type(value){if(!this.isNew)throw Error("Cannot change an attribute's type once it has been created.");this._type=value}get isText(){return this.type=="TEXT"}get isNumber(){return this.type=="NUMBER"}get isBoolean(){return this.type=="BOOLEAN"}get isDate(){return this.type=="DATE"}asText(){return this.type="TEXT",this}asNumber(){return this.type="NUMBER",this}asBoolean(){return this.type="BOOLEAN",this}asDate(){return this.type="DATE",this}get spaceId(){return this._spaceId}set spaceId(value){var _a;value!==this._spaceId&&(this._spaceId=value,value!==((_a=this.space)==null?void 0:_a.id)&&(this._space=null),this.isClean&&this.dirty())}get space(){return this._space}set space(value){this._space=value,this.spaceId=(value==null?void 0:value.id)??0}in(space){return typeof space=="number"?this.spaceId=space:this.space=space,this}duplicate(){const output=new Attr;return output.id=this.id,output.name=this.name,output.type=this.type,output.space=this.space,output}validate(throwError=!1){let output=null;if(this.spaceId<=0?output="Note spaceId must be greater than zero.":!this.isNew&&this.id<=0&&(output="Attr id must be greater than zero if in non-new state."),throwError&&output!=null)throw Error(output);return output==null}get defaultValue(){switch(this.type){case"TEXT":return"";case"NUMBER":return 0;case"BOOLEAN":return!1;case"DATE":return new Date}}toJSON(){return{state:this.state,id:this.id,name:this.name,type:this.type,spaceId:this.spaceId}}static fromJSON(json){const output=new Attr(json.name);return output.type=json.id,output.spaceId=json.spaceId,output.id=json.id,output.state=json.state,output}}class Environment{constructor(client){__publicField(this,"_client",null);__publicField(this,"_spaces",[]);if(!client)throw Error("Client must be set on Environment constructor");this._client=client}get client(){return this._client}get spaces(){return this._spaces}async loadSpaces(){return this._spaces=await this.client.getSpaces(),this.spaces}async saveSpace(space){return await this.client.saveSpace(space)}async getNotes(query,spaceId){return await this.client.getNotes(query,spaceId)}async getNoteCount(query,spaceId){return await this.client.getNoteCount(query,spaceId)}async saveNote(note){return(await this.client.saveNotes([note]))[0]}async saveNotes(notes){return await this.client.saveNotes(notes)}async customJob(name,data){return await this.client.customJob(name,data)}}function bind(fn,thisArg){return function(){return fn.apply(thisArg,arguments)}}const{toString}=Object.prototype,{getPrototypeOf}=Object,kindOf=(cache=>thing=>{const str=toString.call(thing);return cache[str]||(cache[str]=str.slice(8,-1).toLowerCase())})(Object.create(null)),kindOfTest=type=>(type=type.toLowerCase(),thing=>kindOf(thing)===type),typeOfTest=type=>thing=>typeof thing===type,{isArray}=Array,isUndefined=typeOfTest("undefined");function isBuffer(val){return val!==null&&!isUndefined(val)&&val.constructor!==null&&!isUndefined(val.constructor)&&isFunction(val.constructor.isBuffer)&&val.constructor.isBuffer(val)}const isArrayBuffer=kindOfTest("ArrayBuffer");function isArrayBufferView(val){let result;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?result=ArrayBuffer.isView(val):result=val&&val.buffer&&isArrayBuffer(val.buffer),result}const isString=typeOfTest("string"),isFunction=typeOfTest("function"),isNumber=typeOfTest("number"),isObject=thing=>thing!==null&&typeof thing=="object",isBoolean=thing=>thing===!0||thing===!1,isPlainObject=val=>{if(kindOf(val)!=="object")return!1;const prototype2=getPrototypeOf(val);return(prototype2===null||prototype2===Object.prototype||Object.getPrototypeOf(prototype2)===null)&&!(Symbol.toStringTag in val)&&!(Symbol.iterator in val)},isDate=kindOfTest("Date"),isFile=kindOfTest("File"),isBlob=kindOfTest("Blob"),isFileList=kindOfTest("FileList"),isStream=val=>isObject(val)&&isFunction(val.pipe),isFormData=thing=>{let kind;return thing&&(typeof FormData=="function"&&thing instanceof FormData||isFunction(thing.append)&&((kind=kindOf(thing))==="formdata"||kind==="object"&&isFunction(thing.toString)&&thing.toString()==="[object FormData]"))},isURLSearchParams=kindOfTest("URLSearchParams"),trim=str=>str.trim?str.trim():str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function forEach(obj,fn,{allOwnKeys=!1}={}){if(obj===null||typeof obj>"u")return;let i,l;if(typeof obj!="object"&&(obj=[obj]),isArray(obj))for(i=0,l=obj.length;i<l;i++)fn.call(null,obj[i],i,obj);else{const keys=allOwnKeys?Object.getOwnPropertyNames(obj):Object.keys(obj),len=keys.length;let key;for(i=0;i<len;i++)key=keys[i],fn.call(null,obj[key],key,obj)}}function findKey(obj,key){key=key.toLowerCase();const keys=Object.keys(obj);let i=keys.length,_key;for(;i-- >0;)if(_key=keys[i],key===_key.toLowerCase())return _key;return null}const _global=(()=>typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global)(),isContextDefined=context=>!isUndefined(context)&&context!==_global;function merge(){const{caseless}=isContextDefined(this)&&this||{},result={},assignValue=(val,key)=>{const targetKey=caseless&&findKey(result,key)||key;isPlainObject(result[targetKey])&&isPlainObject(val)?result[targetKey]=merge(result[targetKey],val):isPlainObject(val)?result[targetKey]=merge({},val):isArray(val)?result[targetKey]=val.slice():result[targetKey]=val};for(let i=0,l=arguments.length;i<l;i++)arguments[i]&&forEach(arguments[i],assignValue);return result}const extend=(a,b,thisArg,{allOwnKeys}={})=>(forEach(b,(val,key)=>{thisArg&&isFunction(val)?a[key]=bind(val,thisArg):a[key]=val},{allOwnKeys}),a),stripBOM=content=>(content.charCodeAt(0)===65279&&(content=content.slice(1)),content),inherits=(constructor,superConstructor,props,descriptors2)=>{constructor.prototype=Object.create(superConstructor.prototype,descriptors2),constructor.prototype.constructor=constructor,Object.defineProperty(constructor,"super",{value:superConstructor.prototype}),props&&Object.assign(constructor.prototype,props)},toFlatObject=(sourceObj,destObj,filter,propFilter)=>{let props,i,prop;const merged={};if(destObj=destObj||{},sourceObj==null)return destObj;do{for(props=Object.getOwnPropertyNames(sourceObj),i=props.length;i-- >0;)prop=props[i],(!propFilter||propFilter(prop,sourceObj,destObj))&&!merged[prop]&&(destObj[prop]=sourceObj[prop],merged[prop]=!0);sourceObj=filter!==!1&&getPrototypeOf(sourceObj)}while(sourceObj&&(!filter||filter(sourceObj,destObj))&&sourceObj!==Object.prototype);return destObj},endsWith=(str,searchString,position)=>{str=String(str),(position===void 0||position>str.length)&&(position=str.length),position-=searchString.length;const lastIndex=str.indexOf(searchString,position);return lastIndex!==-1&&lastIndex===position},toArray=thing=>{if(!thing)return null;if(isArray(thing))return thing;let i=thing.length;if(!isNumber(i))return null;const arr=new Array(i);for(;i-- >0;)arr[i]=thing[i];return arr},isTypedArray=(TypedArray=>thing=>TypedArray&&thing instanceof TypedArray)(typeof Uint8Array<"u"&&getPrototypeOf(Uint8Array)),forEachEntry=(obj,fn)=>{const iterator=(obj&&obj[Symbol.iterator]).call(obj);let result;for(;(result=iterator.next())&&!result.done;){const pair=result.value;fn.call(obj,pair[0],pair[1])}},matchAll=(regExp,str)=>{let matches;const arr=[];for(;(matches=regExp.exec(str))!==null;)arr.push(matches);return arr},isHTMLForm=kindOfTest("HTMLFormElement"),toCamelCase=str=>str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(m,p1,p2){return p1.toUpperCase()+p2}),hasOwnProperty=(({hasOwnProperty:hasOwnProperty2})=>(obj,prop)=>hasOwnProperty2.call(obj,prop))(Object.prototype),isRegExp=kindOfTest("RegExp"),reduceDescriptors=(obj,reducer)=>{const descriptors2=Object.getOwnPropertyDescriptors(obj),reducedDescriptors={};forEach(descriptors2,(descriptor,name)=>{let ret;(ret=reducer(descriptor,name,obj))!==!1&&(reducedDescriptors[name]=ret||descriptor)}),Object.defineProperties(obj,reducedDescriptors)},freezeMethods=obj=>{reduceDescriptors(obj,(descriptor,name)=>{if(isFunction(obj)&&["arguments","caller","callee"].indexOf(name)!==-1)return!1;const value=obj[name];if(isFunction(value)){if(descriptor.enumerable=!1,"writable"in descriptor){descriptor.writable=!1;return}descriptor.set||(descriptor.set=()=>{throw Error("Can not rewrite read-only method '"+name+"'")})}})},toObjectSet=(arrayOrString,delimiter)=>{const obj={},define2=arr=>{arr.forEach(value=>{obj[value]=!0})};return isArray(arrayOrString)?define2(arrayOrString):define2(String(arrayOrString).split(delimiter)),obj},noop=()=>{},toFiniteNumber=(value,defaultValue)=>(value=+value,Number.isFinite(value)?value:defaultValue),ALPHA="abcdefghijklmnopqrstuvwxyz",DIGIT="0123456789",ALPHABET={DIGIT,ALPHA,ALPHA_DIGIT:ALPHA+ALPHA.toUpperCase()+DIGIT},generateString=(size=16,alphabet=ALPHABET.ALPHA_DIGIT)=>{let str="";const{length}=alphabet;for(;size--;)str+=alphabet[Math.random()*length|0];return str};function isSpecCompliantForm(thing){return!!(thing&&isFunction(thing.append)&&thing[Symbol.toStringTag]==="FormData"&&thing[Symbol.iterator])}const toJSONObject=obj=>{const stack=new Array(10),visit=(source,i)=>{if(isObject(source)){if(stack.indexOf(source)>=0)return;if(!("toJSON"in source)){stack[i]=source;const target=isArray(source)?[]:{};return forEach(source,(value,key)=>{const reducedValue=visit(value,i+1);!isUndefined(reducedValue)&&(target[key]=reducedValue)}),stack[i]=void 0,target}}return source};return visit(obj,0)},isAsyncFn=kindOfTest("AsyncFunction"),utils={isArray,isArrayBuffer,isBuffer,isFormData,isArrayBufferView,isString,isNumber,isBoolean,isObject,isPlainObject,isUndefined,isDate,isFile,isBlob,isRegExp,isFunction,isStream,isURLSearchParams,isTypedArray,isFileList,forEach,merge,extend,trim,stripBOM,inherits,toFlatObject,kindOf,kindOfTest,endsWith,toArray,forEachEntry,matchAll,isHTMLForm,hasOwnProperty,hasOwnProp:hasOwnProperty,reduceDescriptors,freezeMethods,toObjectSet,toCamelCase,noop,toFiniteNumber,findKey,global:_global,isContextDefined,ALPHABET,generateString,isSpecCompliantForm,toJSONObject,isAsyncFn,isThenable:thing=>thing&&(isObject(thing)||isFunction(thing))&&isFunction(thing.then)&&isFunction(thing.catch)};function AxiosError(message,code,config,request,response){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=message,this.name="AxiosError",code&&(this.code=code),config&&(this.config=config),request&&(this.request=request),response&&(this.response=response)}utils.inherits(AxiosError,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:utils.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});const prototype$1=AxiosError.prototype,descriptors={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(code=>{descriptors[code]={value:code}}),Object.defineProperties(AxiosError,descriptors),Object.defineProperty(prototype$1,"isAxiosError",{value:!0}),AxiosError.from=(error,code,config,request,response,customProps)=>{const axiosError=Object.create(prototype$1);return utils.toFlatObject(error,axiosError,function(obj){return obj!==Error.prototype},prop=>prop!=="isAxiosError"),AxiosError.call(axiosError,error.message,code,config,request,response),axiosError.cause=error,axiosError.name=error.name,customProps&&Object.assign(axiosError,customProps),axiosError};const httpAdapter=null;function isVisitable(thing){return utils.isPlainObject(thing)||utils.isArray(thing)}function removeBrackets(key){return utils.endsWith(key,"[]")?key.slice(0,-2):key}function renderKey(path,key,dots){return path?path.concat(key).map(function(token,i){return token=removeBrackets(token),!dots&&i?"["+token+"]":token}).join(dots?".":""):key}function isFlatArray(arr){return utils.isArray(arr)&&!arr.some(isVisitable)}const predicates=utils.toFlatObject(utils,{},null,function(prop){return/^is[A-Z]/.test(prop)});function toFormData(obj,formData,options){if(!utils.isObject(obj))throw new TypeError("target must be an object");formData=formData||new FormData,options=utils.toFlatObject(options,{metaTokens:!0,dots:!1,indexes:!1},!1,function(option,source){return!utils.isUndefined(source[option])});const metaTokens=options.metaTokens,visitor=options.visitor||defaultVisitor,dots=options.dots,indexes=options.indexes,useBlob=(options.Blob||typeof Blob<"u"&&Blob)&&utils.isSpecCompliantForm(formData);if(!utils.isFunction(visitor))throw new TypeError("visitor must be a function");function convertValue(value){if(value===null)return"";if(utils.isDate(value))return value.toISOString();if(!useBlob&&utils.isBlob(value))throw new AxiosError("Blob is not supported. Use a Buffer instead.");return utils.isArrayBuffer(value)||utils.isTypedArray(value)?useBlob&&typeof Blob=="function"?new Blob([value]):Buffer.from(value):value}function defaultVisitor(value,key,path){let arr=value;if(value&&!path&&typeof value=="object"){if(utils.endsWith(key,"{}"))key=metaTokens?key:key.slice(0,-2),value=JSON.stringify(value);else if(utils.isArray(value)&&isFlatArray(value)||(utils.isFileList(value)||utils.endsWith(key,"[]"))&&(arr=utils.toArray(value)))return key=removeBrackets(key),arr.forEach(function(el,index){!(utils.isUndefined(el)||el===null)&&formData.append(indexes===!0?renderKey([key],index,dots):indexes===null?key:key+"[]",convertValue(el))}),!1}return isVisitable(value)?!0:(formData.append(renderKey(path,key,dots),convertValue(value)),!1)}const stack=[],exposedHelpers=Object.assign(predicates,{defaultVisitor,convertValue,isVisitable});function build(value,path){if(!utils.isUndefined(value)){if(stack.indexOf(value)!==-1)throw Error("Circular reference detected in "+path.join("."));stack.push(value),utils.forEach(value,function(el,key){(!(utils.isUndefined(el)||el===null)&&visitor.call(formData,el,utils.isString(key)?key.trim():key,path,exposedHelpers))===!0&&build(el,path?path.concat(key):[key])}),stack.pop()}}if(!utils.isObject(obj))throw new TypeError("data must be an object");return build(obj),formData}function encode$1(str){const charMap={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g,function(match){return charMap[match]})}function AxiosURLSearchParams(params,options){this._pairs=[],params&&toFormData(params,this,options)}const prototype=AxiosURLSearchParams.prototype;prototype.append=function(name,value){this._pairs.push([name,value])},prototype.toString=function(encoder){const _encode=encoder?function(value){return encoder.call(this,value,encode$1)}:encode$1;return this._pairs.map(function(pair){return _encode(pair[0])+"="+_encode(pair[1])},"").join("&")};function encode(val){return encodeURIComponent(val).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function buildURL(url,params,options){if(!params)return url;const _encode=options&&options.encode||encode,serializeFn=options&&options.serialize;let serializedParams;if(serializeFn?serializedParams=serializeFn(params,options):serializedParams=utils.isURLSearchParams(params)?params.toString():new AxiosURLSearchParams(params,options).toString(_encode),serializedParams){const hashmarkIndex=url.indexOf("#");hashmarkIndex!==-1&&(url=url.slice(0,hashmarkIndex)),url+=(url.indexOf("?")===-1?"?":"&")+serializedParams}return url}class InterceptorManager{constructor(){this.handlers=[]}use(fulfilled,rejected,options){return this.handlers.push({fulfilled,rejected,synchronous:options?options.synchronous:!1,runWhen:options?options.runWhen:null}),this.handlers.length-1}eject(id){this.handlers[id]&&(this.handlers[id]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(fn){utils.forEach(this.handlers,function(h){h!==null&&fn(h)})}}const InterceptorManager$1=InterceptorManager,transitionalDefaults={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},URLSearchParams$1=typeof URLSearchParams<"u"?URLSearchParams:AxiosURLSearchParams,FormData$1=typeof FormData<"u"?FormData:null,Blob$1=typeof Blob<"u"?Blob:null,isStandardBrowserEnv=(()=>{let product;return typeof navigator<"u"&&((product=navigator.product)==="ReactNative"||product==="NativeScript"||product==="NS")?!1:typeof window<"u"&&typeof document<"u"})(),isStandardBrowserWebWorkerEnv=(()=>typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function")(),platform={isBrowser:!0,classes:{URLSearchParams:URLSearchParams$1,FormData:FormData$1,Blob:Blob$1},isStandardBrowserEnv,isStandardBrowserWebWorkerEnv,protocols:["http","https","file","blob","url","data"]};function toURLEncodedForm(data,options){return toFormData(data,new platform.classes.URLSearchParams,Object.assign({visitor:function(value,key,path,helpers){return platform.isNode&&utils.isBuffer(value)?(this.append(key,value.toString("base64")),!1):helpers.defaultVisitor.apply(this,arguments)}},options))}function parsePropPath(name){return utils.matchAll(/\w+|\[(\w*)]/g,name).map(match=>match[0]==="[]"?"":match[1]||match[0])}function arrayToObject(arr){const obj={},keys=Object.keys(arr);let i;const len=keys.length;let key;for(i=0;i<len;i++)key=keys[i],obj[key]=arr[key];return obj}function formDataToJSON(formData){function buildPath(path,value,target,index){let name=path[index++];const isNumericKey=Number.isFinite(+name),isLast=index>=path.length;return name=!name&&utils.isArray(target)?target.length:name,isLast?(utils.hasOwnProp(target,name)?target[name]=[target[name],value]:target[name]=value,!isNumericKey):((!target[name]||!utils.isObject(target[name]))&&(target[name]=[]),buildPath(path,value,target[name],index)&&utils.isArray(target[name])&&(target[name]=arrayToObject(target[name])),!isNumericKey)}if(utils.isFormData(formData)&&utils.isFunction(formData.entries)){const obj={};return utils.forEachEntry(formData,(name,value)=>{buildPath(parsePropPath(name),value,obj,0)}),obj}return null}function stringifySafely(rawValue,parser,encoder){if(utils.isString(rawValue))try{return(parser||JSON.parse)(rawValue),utils.trim(rawValue)}catch(e){if(e.name!=="SyntaxError")throw e}return(encoder||JSON.stringify)(rawValue)}const defaults={transitional:transitionalDefaults,adapter:["xhr","http"],transformRequest:[function(data,headers){const contentType=headers.getContentType()||"",hasJSONContentType=contentType.indexOf("application/json")>-1,isObjectPayload=utils.isObject(data);if(isObjectPayload&&utils.isHTMLForm(data)&&(data=new FormData(data)),utils.isFormData(data))return hasJSONContentType&&hasJSONContentType?JSON.stringify(formDataToJSON(data)):data;if(utils.isArrayBuffer(data)||utils.isBuffer(data)||utils.isStream(data)||utils.isFile(data)||utils.isBlob(data))return data;if(utils.isArrayBufferView(data))return data.buffer;if(utils.isURLSearchParams(data))return headers.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),data.toString();let isFileList2;if(isObjectPayload){if(contentType.indexOf("application/x-www-form-urlencoded")>-1)return toURLEncodedForm(data,this.formSerializer).toString();if((isFileList2=utils.isFileList(data))||contentType.indexOf("multipart/form-data")>-1){const _FormData=this.env&&this.env.FormData;return toFormData(isFileList2?{"files[]":data}:data,_FormData&&new _FormData,this.formSerializer)}}return isObjectPayload||hasJSONContentType?(headers.setContentType("application/json",!1),stringifySafely(data)):data}],transformResponse:[function(data){const transitional=this.transitional||defaults.transitional,forcedJSONParsing=transitional&&transitional.forcedJSONParsing,JSONRequested=this.responseType==="json";if(data&&utils.isString(data)&&(forcedJSONParsing&&!this.responseType||JSONRequested)){const strictJSONParsing=!(transitional&&transitional.silentJSONParsing)&&JSONRequested;try{return JSON.parse(data)}catch(e){if(strictJSONParsing)throw e.name==="SyntaxError"?AxiosError.from(e,AxiosError.ERR_BAD_RESPONSE,this,null,this.response):e}}return data}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:platform.classes.FormData,Blob:platform.classes.Blob},validateStatus:function(status){return status>=200&&status<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};utils.forEach(["delete","get","head","post","put","patch"],method=>{defaults.headers[method]={}});const defaults$1=defaults,ignoreDuplicateOf=utils.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),parseHeaders=rawHeaders=>{const parsed={};let key,val,i;return rawHeaders&&rawHeaders.split(`
2
- `).forEach(function(line){i=line.indexOf(":"),key=line.substring(0,i).trim().toLowerCase(),val=line.substring(i+1).trim(),!(!key||parsed[key]&&ignoreDuplicateOf[key])&&(key==="set-cookie"?parsed[key]?parsed[key].push(val):parsed[key]=[val]:parsed[key]=parsed[key]?parsed[key]+", "+val:val)}),parsed},$internals=Symbol("internals");function normalizeHeader(header){return header&&String(header).trim().toLowerCase()}function normalizeValue(value){return value===!1||value==null?value:utils.isArray(value)?value.map(normalizeValue):String(value)}function parseTokens(str){const tokens=Object.create(null),tokensRE=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let match;for(;match=tokensRE.exec(str);)tokens[match[1]]=match[2];return tokens}const isValidHeaderName=str=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim());function matchHeaderValue(context,value,header,filter,isHeaderNameFilter){if(utils.isFunction(filter))return filter.call(this,value,header);if(isHeaderNameFilter&&(value=header),!!utils.isString(value)){if(utils.isString(filter))return value.indexOf(filter)!==-1;if(utils.isRegExp(filter))return filter.test(value)}}function formatHeader(header){return header.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(w,char,str)=>char.toUpperCase()+str)}function buildAccessors(obj,header){const accessorName=utils.toCamelCase(" "+header);["get","set","has"].forEach(methodName=>{Object.defineProperty(obj,methodName+accessorName,{value:function(arg1,arg2,arg3){return this[methodName].call(this,header,arg1,arg2,arg3)},configurable:!0})})}class AxiosHeaders{constructor(headers){headers&&this.set(headers)}set(header,valueOrRewrite,rewrite){const self2=this;function setHeader(_value,_header,_rewrite){const lHeader=normalizeHeader(_header);if(!lHeader)throw new Error("header name must be a non-empty string");const key=utils.findKey(self2,lHeader);(!key||self2[key]===void 0||_rewrite===!0||_rewrite===void 0&&self2[key]!==!1)&&(self2[key||_header]=normalizeValue(_value))}const setHeaders=(headers,_rewrite)=>utils.forEach(headers,(_value,_header)=>setHeader(_value,_header,_rewrite));return utils.isPlainObject(header)||header instanceof this.constructor?setHeaders(header,valueOrRewrite):utils.isString(header)&&(header=header.trim())&&!isValidHeaderName(header)?setHeaders(parseHeaders(header),valueOrRewrite):header!=null&&setHeader(valueOrRewrite,header,rewrite),this}get(header,parser){if(header=normalizeHeader(header),header){const key=utils.findKey(this,header);if(key){const value=this[key];if(!parser)return value;if(parser===!0)return parseTokens(value);if(utils.isFunction(parser))return parser.call(this,value,key);if(utils.isRegExp(parser))return parser.exec(value);throw new TypeError("parser must be boolean|regexp|function")}}}has(header,matcher){if(header=normalizeHeader(header),header){const key=utils.findKey(this,header);return!!(key&&this[key]!==void 0&&(!matcher||matchHeaderValue(this,this[key],key,matcher)))}return!1}delete(header,matcher){const self2=this;let deleted=!1;function deleteHeader(_header){if(_header=normalizeHeader(_header),_header){const key=utils.findKey(self2,_header);key&&(!matcher||matchHeaderValue(self2,self2[key],key,matcher))&&(delete self2[key],deleted=!0)}}return utils.isArray(header)?header.forEach(deleteHeader):deleteHeader(header),deleted}clear(matcher){const keys=Object.keys(this);let i=keys.length,deleted=!1;for(;i--;){const key=keys[i];(!matcher||matchHeaderValue(this,this[key],key,matcher,!0))&&(delete this[key],deleted=!0)}return deleted}normalize(format){const self2=this,headers={};return utils.forEach(this,(value,header)=>{const key=utils.findKey(headers,header);if(key){self2[key]=normalizeValue(value),delete self2[header];return}const normalized=format?formatHeader(header):String(header).trim();normalized!==header&&delete self2[header],self2[normalized]=normalizeValue(value),headers[normalized]=!0}),this}concat(...targets){return this.constructor.concat(this,...targets)}toJSON(asStrings){const obj=Object.create(null);return utils.forEach(this,(value,header)=>{value!=null&&value!==!1&&(obj[header]=asStrings&&utils.isArray(value)?value.join(", "):value)}),obj}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([header,value])=>header+": "+value).join(`
3
- `)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(thing){return thing instanceof this?thing:new this(thing)}static concat(first,...targets){const computed=new this(first);return targets.forEach(target=>computed.set(target)),computed}static accessor(header){const accessors=(this[$internals]=this[$internals]={accessors:{}}).accessors,prototype2=this.prototype;function defineAccessor(_header){const lHeader=normalizeHeader(_header);accessors[lHeader]||(buildAccessors(prototype2,_header),accessors[lHeader]=!0)}return utils.isArray(header)?header.forEach(defineAccessor):defineAccessor(header),this}}AxiosHeaders.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),utils.reduceDescriptors(AxiosHeaders.prototype,({value},key)=>{let mapped=key[0].toUpperCase()+key.slice(1);return{get:()=>value,set(headerValue){this[mapped]=headerValue}}}),utils.freezeMethods(AxiosHeaders);const AxiosHeaders$1=AxiosHeaders;function transformData(fns,response){const config=this||defaults$1,context=response||config,headers=AxiosHeaders$1.from(context.headers);let data=context.data;return utils.forEach(fns,function(fn){data=fn.call(config,data,headers.normalize(),response?response.status:void 0)}),headers.normalize(),data}function isCancel(value){return!!(value&&value.__CANCEL__)}function CanceledError(message,config,request){AxiosError.call(this,message??"canceled",AxiosError.ERR_CANCELED,config,request),this.name="CanceledError"}utils.inherits(CanceledError,AxiosError,{__CANCEL__:!0});function settle(resolve,reject,response){const validateStatus=response.config.validateStatus;!response.status||!validateStatus||validateStatus(response.status)?resolve(response):reject(new AxiosError("Request failed with status code "+response.status,[AxiosError.ERR_BAD_REQUEST,AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status/100)-4],response.config,response.request,response))}const cookies=platform.isStandardBrowserEnv?function(){return{write:function(name,value,expires,path,domain,secure){const cookie=[];cookie.push(name+"="+encodeURIComponent(value)),utils.isNumber(expires)&&cookie.push("expires="+new Date(expires).toGMTString()),utils.isString(path)&&cookie.push("path="+path),utils.isString(domain)&&cookie.push("domain="+domain),secure===!0&&cookie.push("secure"),document.cookie=cookie.join("; ")},read:function(name){const match=document.cookie.match(new RegExp("(^|;\\s*)("+name+")=([^;]*)"));return match?decodeURIComponent(match[3]):null},remove:function(name){this.write(name,"",Date.now()-864e5)}}}():function(){return{write:function(){},read:function(){return null},remove:function(){}}}();function isAbsoluteURL(url){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(url)}function combineURLs(baseURL,relativeURL){return relativeURL?baseURL.replace(/\/+$/,"")+"/"+relativeURL.replace(/^\/+/,""):baseURL}function buildFullPath(baseURL,requestedURL){return baseURL&&!isAbsoluteURL(requestedURL)?combineURLs(baseURL,requestedURL):requestedURL}const isURLSameOrigin=platform.isStandardBrowserEnv?function(){const msie=/(msie|trident)/i.test(navigator.userAgent),urlParsingNode=document.createElement("a");let originURL;function resolveURL(url){let href=url;return msie&&(urlParsingNode.setAttribute("href",href),href=urlParsingNode.href),urlParsingNode.setAttribute("href",href),{href:urlParsingNode.href,protocol:urlParsingNode.protocol?urlParsingNode.protocol.replace(/:$/,""):"",host:urlParsingNode.host,search:urlParsingNode.search?urlParsingNode.search.replace(/^\?/,""):"",hash:urlParsingNode.hash?urlParsingNode.hash.replace(/^#/,""):"",hostname:urlParsingNode.hostname,port:urlParsingNode.port,pathname:urlParsingNode.pathname.charAt(0)==="/"?urlParsingNode.pathname:"/"+urlParsingNode.pathname}}return originURL=resolveURL(window.location.href),function(requestURL){const parsed=utils.isString(requestURL)?resolveURL(requestURL):requestURL;return parsed.protocol===originURL.protocol&&parsed.host===originURL.host}}():function(){return function(){return!0}}();function parseProtocol(url){const match=/^([-+\w]{1,25})(:?\/\/|:)/.exec(url);return match&&match[1]||""}function speedometer(samplesCount,min){samplesCount=samplesCount||10;const bytes=new Array(samplesCount),timestamps=new Array(samplesCount);let head=0,tail=0,firstSampleTS;return min=min!==void 0?min:1e3,function(chunkLength){const now=Date.now(),startedAt=timestamps[tail];firstSampleTS||(firstSampleTS=now),bytes[head]=chunkLength,timestamps[head]=now;let i=tail,bytesCount=0;for(;i!==head;)bytesCount+=bytes[i++],i=i%samplesCount;if(head=(head+1)%samplesCount,head===tail&&(tail=(tail+1)%samplesCount),now-firstSampleTS<min)return;const passed=startedAt&&now-startedAt;return passed?Math.round(bytesCount*1e3/passed):void 0}}function progressEventReducer(listener,isDownloadStream){let bytesNotified=0;const _speedometer=speedometer(50,250);return e=>{const loaded=e.loaded,total=e.lengthComputable?e.total:void 0,progressBytes=loaded-bytesNotified,rate=_speedometer(progressBytes),inRange=loaded<=total;bytesNotified=loaded;const data={loaded,total,progress:total?loaded/total:void 0,bytes:progressBytes,rate:rate||void 0,estimated:rate&&total&&inRange?(total-loaded)/rate:void 0,event:e};data[isDownloadStream?"download":"upload"]=!0,listener(data)}}const knownAdapters={http:httpAdapter,xhr:typeof XMLHttpRequest<"u"&&function(config){return new Promise(function(resolve,reject){let requestData=config.data;const requestHeaders=AxiosHeaders$1.from(config.headers).normalize(),responseType=config.responseType;let onCanceled;function done(){config.cancelToken&&config.cancelToken.unsubscribe(onCanceled),config.signal&&config.signal.removeEventListener("abort",onCanceled)}let contentType;utils.isFormData(requestData)&&(platform.isStandardBrowserEnv||platform.isStandardBrowserWebWorkerEnv?requestHeaders.setContentType(!1):requestHeaders.getContentType(/^\s*multipart\/form-data/)?utils.isString(contentType=requestHeaders.getContentType())&&requestHeaders.setContentType(contentType.replace(/^\s*(multipart\/form-data);+/,"$1")):requestHeaders.setContentType("multipart/form-data"));let request=new XMLHttpRequest;if(config.auth){const username=config.auth.username||"",password=config.auth.password?unescape(encodeURIComponent(config.auth.password)):"";requestHeaders.set("Authorization","Basic "+btoa(username+":"+password))}const fullPath=buildFullPath(config.baseURL,config.url);request.open(config.method.toUpperCase(),buildURL(fullPath,config.params,config.paramsSerializer),!0),request.timeout=config.timeout;function onloadend(){if(!request)return;const responseHeaders=AxiosHeaders$1.from("getAllResponseHeaders"in request&&request.getAllResponseHeaders()),response={data:!responseType||responseType==="text"||responseType==="json"?request.responseText:request.response,status:request.status,statusText:request.statusText,headers:responseHeaders,config,request};settle(function(value){resolve(value),done()},function(err){reject(err),done()},response),request=null}if("onloadend"in request?request.onloadend=onloadend:request.onreadystatechange=function(){!request||request.readyState!==4||request.status===0&&!(request.responseURL&&request.responseURL.indexOf("file:")===0)||setTimeout(onloadend)},request.onabort=function(){request&&(reject(new AxiosError("Request aborted",AxiosError.ECONNABORTED,config,request)),request=null)},request.onerror=function(){reject(new AxiosError("Network Error",AxiosError.ERR_NETWORK,config,request)),request=null},request.ontimeout=function(){let timeoutErrorMessage=config.timeout?"timeout of "+config.timeout+"ms exceeded":"timeout exceeded";const transitional=config.transitional||transitionalDefaults;config.timeoutErrorMessage&&(timeoutErrorMessage=config.timeoutErrorMessage),reject(new AxiosError(timeoutErrorMessage,transitional.clarifyTimeoutError?AxiosError.ETIMEDOUT:AxiosError.ECONNABORTED,config,request)),request=null},platform.isStandardBrowserEnv){const xsrfValue=(config.withCredentials||isURLSameOrigin(fullPath))&&config.xsrfCookieName&&cookies.read(config.xsrfCookieName);xsrfValue&&requestHeaders.set(config.xsrfHeaderName,xsrfValue)}requestData===void 0&&requestHeaders.setContentType(null),"setRequestHeader"in request&&utils.forEach(requestHeaders.toJSON(),function(val,key){request.setRequestHeader(key,val)}),utils.isUndefined(config.withCredentials)||(request.withCredentials=!!config.withCredentials),responseType&&responseType!=="json"&&(request.responseType=config.responseType),typeof config.onDownloadProgress=="function"&&request.addEventListener("progress",progressEventReducer(config.onDownloadProgress,!0)),typeof config.onUploadProgress=="function"&&request.upload&&request.upload.addEventListener("progress",progressEventReducer(config.onUploadProgress)),(config.cancelToken||config.signal)&&(onCanceled=cancel=>{request&&(reject(!cancel||cancel.type?new CanceledError(null,config,request):cancel),request.abort(),request=null)},config.cancelToken&&config.cancelToken.subscribe(onCanceled),config.signal&&(config.signal.aborted?onCanceled():config.signal.addEventListener("abort",onCanceled)));const protocol=parseProtocol(fullPath);if(protocol&&platform.protocols.indexOf(protocol)===-1){reject(new AxiosError("Unsupported protocol "+protocol+":",AxiosError.ERR_BAD_REQUEST,config));return}request.send(requestData||null)})}};utils.forEach(knownAdapters,(fn,value)=>{if(fn){try{Object.defineProperty(fn,"name",{value})}catch{}Object.defineProperty(fn,"adapterName",{value})}});const renderReason=reason=>`- ${reason}`,isResolvedHandle=adapter=>utils.isFunction(adapter)||adapter===null||adapter===!1,adapters={getAdapter:adapters2=>{adapters2=utils.isArray(adapters2)?adapters2:[adapters2];const{length}=adapters2;let nameOrAdapter,adapter;const rejectedReasons={};for(let i=0;i<length;i++){nameOrAdapter=adapters2[i];let id;if(adapter=nameOrAdapter,!isResolvedHandle(nameOrAdapter)&&(adapter=knownAdapters[(id=String(nameOrAdapter)).toLowerCase()],adapter===void 0))throw new AxiosError(`Unknown adapter '${id}'`);if(adapter)break;rejectedReasons[id||"#"+i]=adapter}if(!adapter){const reasons=Object.entries(rejectedReasons).map(([id,state])=>`adapter ${id} `+(state===!1?"is not supported by the environment":"is not available in the build"));let s=length?reasons.length>1?`since :
4
- `+reasons.map(renderReason).join(`
5
- `):" "+renderReason(reasons[0]):"as no adapter specified";throw new AxiosError("There is no suitable adapter to dispatch the request "+s,"ERR_NOT_SUPPORT")}return adapter},adapters:knownAdapters};function throwIfCancellationRequested(config){if(config.cancelToken&&config.cancelToken.throwIfRequested(),config.signal&&config.signal.aborted)throw new CanceledError(null,config)}function dispatchRequest(config){return throwIfCancellationRequested(config),config.headers=AxiosHeaders$1.from(config.headers),config.data=transformData.call(config,config.transformRequest),["post","put","patch"].indexOf(config.method)!==-1&&config.headers.setContentType("application/x-www-form-urlencoded",!1),adapters.getAdapter(config.adapter||defaults$1.adapter)(config).then(function(response){return throwIfCancellationRequested(config),response.data=transformData.call(config,config.transformResponse,response),response.headers=AxiosHeaders$1.from(response.headers),response},function(reason){return isCancel(reason)||(throwIfCancellationRequested(config),reason&&reason.response&&(reason.response.data=transformData.call(config,config.transformResponse,reason.response),reason.response.headers=AxiosHeaders$1.from(reason.response.headers))),Promise.reject(reason)})}const headersToObject=thing=>thing instanceof AxiosHeaders$1?thing.toJSON():thing;function mergeConfig(config1,config2){config2=config2||{};const config={};function getMergedValue(target,source,caseless){return utils.isPlainObject(target)&&utils.isPlainObject(source)?utils.merge.call({caseless},target,source):utils.isPlainObject(source)?utils.merge({},source):utils.isArray(source)?source.slice():source}function mergeDeepProperties(a,b,caseless){if(utils.isUndefined(b)){if(!utils.isUndefined(a))return getMergedValue(void 0,a,caseless)}else return getMergedValue(a,b,caseless)}function valueFromConfig2(a,b){if(!utils.isUndefined(b))return getMergedValue(void 0,b)}function defaultToConfig2(a,b){if(utils.isUndefined(b)){if(!utils.isUndefined(a))return getMergedValue(void 0,a)}else return getMergedValue(void 0,b)}function mergeDirectKeys(a,b,prop){if(prop in config2)return getMergedValue(a,b);if(prop in config1)return getMergedValue(void 0,a)}const mergeMap={url:valueFromConfig2,method:valueFromConfig2,data:valueFromConfig2,baseURL:defaultToConfig2,transformRequest:defaultToConfig2,transformResponse:defaultToConfig2,paramsSerializer:defaultToConfig2,timeout:defaultToConfig2,timeoutMessage:defaultToConfig2,withCredentials:defaultToConfig2,adapter:defaultToConfig2,responseType:defaultToConfig2,xsrfCookieName:defaultToConfig2,xsrfHeaderName:defaultToConfig2,onUploadProgress:defaultToConfig2,onDownloadProgress:defaultToConfig2,decompress:defaultToConfig2,maxContentLength:defaultToConfig2,maxBodyLength:defaultToConfig2,beforeRedirect:defaultToConfig2,transport:defaultToConfig2,httpAgent:defaultToConfig2,httpsAgent:defaultToConfig2,cancelToken:defaultToConfig2,socketPath:defaultToConfig2,responseEncoding:defaultToConfig2,validateStatus:mergeDirectKeys,headers:(a,b)=>mergeDeepProperties(headersToObject(a),headersToObject(b),!0)};return utils.forEach(Object.keys(Object.assign({},config1,config2)),function(prop){const merge2=mergeMap[prop]||mergeDeepProperties,configValue=merge2(config1[prop],config2[prop],prop);utils.isUndefined(configValue)&&merge2!==mergeDirectKeys||(config[prop]=configValue)}),config}const VERSION="1.5.1",validators$1={};["object","boolean","number","function","string","symbol"].forEach((type,i)=>{validators$1[type]=function(thing){return typeof thing===type||"a"+(i<1?"n ":" ")+type}});const deprecatedWarnings={};validators$1.transitional=function(validator2,version,message){function formatMessage(opt,desc){return"[Axios v"+VERSION+"] Transitional option '"+opt+"'"+desc+(message?". "+message:"")}return(value,opt,opts)=>{if(validator2===!1)throw new AxiosError(formatMessage(opt," has been removed"+(version?" in "+version:"")),AxiosError.ERR_DEPRECATED);return version&&!deprecatedWarnings[opt]&&(deprecatedWarnings[opt]=!0,console.warn(formatMessage(opt," has been deprecated since v"+version+" and will be removed in the near future"))),validator2?validator2(value,opt,opts):!0}};function assertOptions(options,schema,allowUnknown){if(typeof options!="object")throw new AxiosError("options must be an object",AxiosError.ERR_BAD_OPTION_VALUE);const keys=Object.keys(options);let i=keys.length;for(;i-- >0;){const opt=keys[i],validator2=schema[opt];if(validator2){const value=options[opt],result=value===void 0||validator2(value,opt,options);if(result!==!0)throw new AxiosError("option "+opt+" must be "+result,AxiosError.ERR_BAD_OPTION_VALUE);continue}if(allowUnknown!==!0)throw new AxiosError("Unknown option "+opt,AxiosError.ERR_BAD_OPTION)}}const validator={assertOptions,validators:validators$1},validators=validator.validators;class Axios{constructor(instanceConfig){this.defaults=instanceConfig,this.interceptors={request:new InterceptorManager$1,response:new InterceptorManager$1}}request(configOrUrl,config){typeof configOrUrl=="string"?(config=config||{},config.url=configOrUrl):config=configOrUrl||{},config=mergeConfig(this.defaults,config);const{transitional,paramsSerializer,headers}=config;transitional!==void 0&&validator.assertOptions(transitional,{silentJSONParsing:validators.transitional(validators.boolean),forcedJSONParsing:validators.transitional(validators.boolean),clarifyTimeoutError:validators.transitional(validators.boolean)},!1),paramsSerializer!=null&&(utils.isFunction(paramsSerializer)?config.paramsSerializer={serialize:paramsSerializer}:validator.assertOptions(paramsSerializer,{encode:validators.function,serialize:validators.function},!0)),config.method=(config.method||this.defaults.method||"get").toLowerCase();let contextHeaders=headers&&utils.merge(headers.common,headers[config.method]);headers&&utils.forEach(["delete","get","head","post","put","patch","common"],method=>{delete headers[method]}),config.headers=AxiosHeaders$1.concat(contextHeaders,headers);const requestInterceptorChain=[];let synchronousRequestInterceptors=!0;this.interceptors.request.forEach(function(interceptor){typeof interceptor.runWhen=="function"&&interceptor.runWhen(config)===!1||(synchronousRequestInterceptors=synchronousRequestInterceptors&&interceptor.synchronous,requestInterceptorChain.unshift(interceptor.fulfilled,interceptor.rejected))});const responseInterceptorChain=[];this.interceptors.response.forEach(function(interceptor){responseInterceptorChain.push(interceptor.fulfilled,interceptor.rejected)});let promise,i=0,len;if(!synchronousRequestInterceptors){const chain=[dispatchRequest.bind(this),void 0];for(chain.unshift.apply(chain,requestInterceptorChain),chain.push.apply(chain,responseInterceptorChain),len=chain.length,promise=Promise.resolve(config);i<len;)promise=promise.then(chain[i++],chain[i++]);return promise}len=requestInterceptorChain.length;let newConfig=config;for(i=0;i<len;){const onFulfilled=requestInterceptorChain[i++],onRejected=requestInterceptorChain[i++];try{newConfig=onFulfilled(newConfig)}catch(error){onRejected.call(this,error);break}}try{promise=dispatchRequest.call(this,newConfig)}catch(error){return Promise.reject(error)}for(i=0,len=responseInterceptorChain.length;i<len;)promise=promise.then(responseInterceptorChain[i++],responseInterceptorChain[i++]);return promise}getUri(config){config=mergeConfig(this.defaults,config);const fullPath=buildFullPath(config.baseURL,config.url);return buildURL(fullPath,config.params,config.paramsSerializer)}}utils.forEach(["delete","get","head","options"],function(method){Axios.prototype[method]=function(url,config){return this.request(mergeConfig(config||{},{method,url,data:(config||{}).data}))}}),utils.forEach(["post","put","patch"],function(method){function generateHTTPMethod(isForm){return function(url,data,config){return this.request(mergeConfig(config||{},{method,headers:isForm?{"Content-Type":"multipart/form-data"}:{},url,data}))}}Axios.prototype[method]=generateHTTPMethod(),Axios.prototype[method+"Form"]=generateHTTPMethod(!0)});const Axios$1=Axios;class CancelToken{constructor(executor){if(typeof executor!="function")throw new TypeError("executor must be a function.");let resolvePromise;this.promise=new Promise(function(resolve){resolvePromise=resolve});const token=this;this.promise.then(cancel=>{if(!token._listeners)return;let i=token._listeners.length;for(;i-- >0;)token._listeners[i](cancel);token._listeners=null}),this.promise.then=onfulfilled=>{let _resolve;const promise=new Promise(resolve=>{token.subscribe(resolve),_resolve=resolve}).then(onfulfilled);return promise.cancel=function(){token.unsubscribe(_resolve)},promise},executor(function(message,config,request){token.reason||(token.reason=new CanceledError(message,config,request),resolvePromise(token.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(listener){if(this.reason){listener(this.reason);return}this._listeners?this._listeners.push(listener):this._listeners=[listener]}unsubscribe(listener){if(!this._listeners)return;const index=this._listeners.indexOf(listener);index!==-1&&this._listeners.splice(index,1)}static source(){let cancel;return{token:new CancelToken(function(c){cancel=c}),cancel}}}const CancelToken$1=CancelToken;function spread(callback){return function(arr){return callback.apply(null,arr)}}function isAxiosError(payload){return utils.isObject(payload)&&payload.isAxiosError===!0}const HttpStatusCode={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(HttpStatusCode).forEach(([key,value])=>{HttpStatusCode[value]=key});const HttpStatusCode$1=HttpStatusCode;function createInstance(defaultConfig){const context=new Axios$1(defaultConfig),instance=bind(Axios$1.prototype.request,context);return utils.extend(instance,Axios$1.prototype,context,{allOwnKeys:!0}),utils.extend(instance,context,null,{allOwnKeys:!0}),instance.create=function(instanceConfig){return createInstance(mergeConfig(defaultConfig,instanceConfig))},instance}const axios=createInstance(defaults$1);axios.Axios=Axios$1,axios.CanceledError=CanceledError,axios.CancelToken=CancelToken$1,axios.isCancel=isCancel,axios.VERSION=VERSION,axios.toFormData=toFormData,axios.AxiosError=AxiosError,axios.Cancel=axios.CanceledError,axios.all=function(promises){return Promise.all(promises)},axios.spread=spread,axios.isAxiosError=isAxiosError,axios.mergeConfig=mergeConfig,axios.AxiosHeaders=AxiosHeaders$1,axios.formToJSON=thing=>formDataToJSON(utils.isHTMLForm(thing)?new FormData(thing):thing),axios.getAdapter=adapters.getAdapter,axios.HttpStatusCode=HttpStatusCode$1,axios.default=axios;const axios$1=axios;class HttpClient{constructor(url,httpRequester=null){__publicField(this,"_url",null);__publicField(this,"_token",null);__publicField(this,"_httpRequester");if(!url)throw Error("Endpoint URL must be passed in to NotuClient constructor");this._url=url,this._httpRequester=httpRequester??axios$1}get url(){return this._url}get token(){return this._token}set token(value){this._token=value}async login(username,password){try{const result=await this._httpRequester({method:"post",url:(this.url+"/login").replace("//","/"),data:{username,password}});return this._token=result.data,{success:!0,error:null,token:result.data}}catch(ex){if(ex.response.status==401)return{success:!1,error:"Invalid username & password.",token:null};throw ex}}async getSpaces(){return(await this._httpRequester({method:"get",url:(this.url+"/spaces").replace("//","/"),headers:{Authorization:"Bearer "+this.token}})).data}async saveSpace(space){return(await this._httpRequester({method:"post",url:(this.url+"/spaces").replace("//","/"),data:space,headers:{Authorization:"Bearer "+this.token}})).data}async getNotes(query,spaceId){return(await this._httpRequester({method:"get",url:(this.url+"/notes").replace("//","/"),data:{query,spaceId},headers:{Authorization:"Bearer "+this.token}})).data}async getNoteCount(query,spaceId){return(await this._httpRequester({method:"get",url:(this.url+"/notes").replace("//","/"),data:{query,spaceId},headers:{Authorization:"Bearer "+this.token}})).data}async saveNotes(notes){return(await this._httpRequester({method:"post",url:(this.url+"/notes").replace("//","/"),data:{notes},headers:{Authorization:"Bearer "+this.token}})).data}async customJob(name,data){return(await this._httpRequester({method:"post",url:(this.url+"customjob").replace("//","/"),data:{name,data},headers:{Authorization:"Bearer "+this.token}})).data}}class NoteAttr extends ModelWithState{constructor(note,attr,value){super();__publicField(this,"_noteId",0);__publicField(this,"_note",null);__publicField(this,"_attrId",0);__publicField(this,"_attr",null);__publicField(this,"_value",null);__publicField(this,"_tagId",null);__publicField(this,"_tag",null);note!=null&&note!=null&&(typeof note=="number"?this.noteId=note:this.note=note),attr!=null&&attr!=null&&(typeof attr=="number"?this.attrId=attr:this.attr=attr),value!=null&&value!=null&&(this.value=value)}get noteId(){return this._noteId}set noteId(value){var _a;value!==this._noteId&&(this._noteId=value,value!==((_a=this.note)==null?void 0:_a.id)&&(this._note=null),this.isClean&&this.dirty())}get note(){return this._note}set note(value){this._note=value,this.noteId=(value==null?void 0:value.id)??0}get attrId(){return this._attrId}set attrId(value){var _a;value!==this._attrId&&(this._attrId=value,value!==((_a=this.attr)==null?void 0:_a.id)&&(this._attr=null),this.isClean&&this.dirty())}get attr(){return this._attr}set attr(newAttr){const oldAttr=this._attr;this._attr=newAttr,newAttr?(!oldAttr||newAttr.type!=oldAttr.type)&&(this.value=newAttr.defaultValue):this.value=null,this.attrId=(newAttr==null?void 0:newAttr.id)??0}get value(){return this._value}set value(newVal){newVal!=this._value&&(this._value=newVal,this.isClean&&this.dirty())}withValue(value){return this.value=value,this}get tagId(){return this._tagId}set tagId(value){var _a;value!==this._tagId&&(this._tagId=value,value!==((_a=this.tag)==null?void 0:_a.id)&&(this._tag=null),this.isClean&&this.dirty())}get tag(){return this._tag}set tag(value){this._tag=value,this.tagId=(value==null?void 0:value.id)??null}onTag(tag){return typeof tag=="number"?this.tagId=tag:this.tag=tag,this}duplicate(){const output=new NoteAttr;return output.noteId=this.noteId,output.note=this.note,output.attrId=this.attrId,output.attr=this.attr,output.tagId=this.tagId,output.tag=this.tag,output.value=this.value,output}validate(throwError=!1){let output=null;if(this.noteId<=0&&!this.isNew?output="NoteAttr noteId must be greater than zero":this.attrId<=0&&(output="NoteAttr attrId must be greater than zero"),throwError&&output!=null)throw Error(output);return output==null}toJSON(){return{state:this.state,noteId:this.noteId,attrId:this.attrId,tagId:this.tagId,value:this.value}}static fromJSON(json){const output=new NoteAttr(json.noteId,json.attrId,json.value);return output.tagId=json.tagId,output.state=json.state,output}}class NoteTag extends ModelWithState{constructor(note,tag){super();__publicField(this,"_noteId",0);__publicField(this,"_note",null);__publicField(this,"_tagId",0);__publicField(this,"_tag",null);note!=null&&note!=null&&(typeof note=="number"?this.noteId=note:this.note=note),tag!=null&&tag!=null&&(typeof tag=="number"?this.tagId=tag:this.tag=tag)}get noteId(){return this._noteId}set noteId(value){var _a;value!==this._noteId&&(this._noteId=value,value!==((_a=this.note)==null?void 0:_a.id)&&(this._note=null),this.isClean&&this.dirty())}get note(){return this._note}set note(value){this._note=value,this.noteId=(value==null?void 0:value.id)??0}get tagId(){return this._tagId}set tagId(value){var _a;value!==this._tagId&&(this._tagId=value,value!==((_a=this.tag)==null?void 0:_a.id)&&(this._tag=null),this.isClean&&this.dirty())}get tag(){return this._tag}set tag(value){this._tag=value,this.tagId=(value==null?void 0:value.id)??0}get attrs(){return this.note.attrs.filter(x=>x.tagId==this.tagId)}addAttr(attr){if(!this.note)throw new Error("Cannot call addAttr on NoteTag where note property has not been set");const na=this.note.addAttr(attr);return na.tag=this.tag,na}duplicate(){const output=new NoteTag;return output.noteId=this.noteId,output.tagId=this.tagId,output}validate(throwError=!1){let output=null;if(this.noteId<=0&&!this.isNew?output="NoteTag noteId must be greater than zero":this.tagId<=0?output="NoteTag tagId must be greater than zero":this.noteId==this.tagId&&(output="NoteTag cannot link a note to its own tag"),throwError&&output!=null)throw Error(output);return output==null}toJSON(){return{state:this.state,noteId:this.noteId,tagId:this.tagId}}static fromJSON(json){const output=new NoteTag(json.noteId,json.tagId);return output.state=json.state,output}}class Tag extends ModelWithState{constructor(name="",spaceId=0){super();__publicField(this,"_id",0);__publicField(this,"_spaceId",0);__publicField(this,"_space",null);__publicField(this,"_name","");__publicField(this,"_color",null);this._name=name,this._spaceId=spaceId}get id(){return this._id}set id(value){value!==this._id&&(this._id=value,this.isClean&&this.dirty())}get spaceId(){return this._spaceId}get space(){return this._space}set space(value){if(value===null){this._space=null;return}if(value.id!==this.spaceId)throw Error("Attempted to set space on Tag where spaceId doesnt match");this._space=value}get name(){return this._name}set name(value){value!==this._name&&(this._name=value,this.isClean&&this.dirty())}get color(){return this._color}set color(value){value!==this._color&&(this._color=value,this.isClean&&this.dirty())}duplicate(){const output=new Tag(this.name,this.spaceId);return output.id=this.id,output.state=this.state,output.color=this.color,output.space=this.space,output}validate(throwError=!1){let output=null;if(!this.isNew&&this.id<=0?output="Tag id must be greater than zero if in non-new state.":!this.name||!/^[a-zA-Z][a-zA-Z0-9 ]*[a-zA-Z0-9]?$/.test(this.name)?output="Tag name is invalid, must only contain letters, numbers, and spaces, starting with a letter":this.color&&!/^#?[A-z0-9]{6}$/.test(this.color)&&(output="Tag color is invalid, must be a 6 character hexadecimal."),throwError&&output!=null)throw Error(output);return output==null}getColorInt(){let hex=this.color;return hex?(hex.startsWith("#")&&(hex=hex.substring(1)),parseInt(hex,16)):null}toJSON(){return{state:this.state,id:this.id,name:this.name,spaceId:this.spaceId,color:this.color}}static fromJSON(json){const output=new Tag(json.name,json.spaceId);return output.id=json.id,output.color=json.color,output.state=json.state,output}}class Note extends ModelWithState{constructor(text){super();__publicField(this,"_id",0);__publicField(this,"_date",new Date);__publicField(this,"_text","");__publicField(this,"_archived",!1);__publicField(this,"_spaceId",0);__publicField(this,"_space",null);__publicField(this,"_ownTag",null);__publicField(this,"_tags",[]);__publicField(this,"_attrs",[]);text&&(this.text=text)}get id(){return this._id}set id(value){this._id=value,this.ownTag&&(this.ownTag.id=value)}get date(){return this._date}set date(value){value!==this._date&&(this._date=value,this.isClean&&this.dirty())}at(value){return this.date=value,this}get text(){return this._text}set text(value){value!==this._text&&(this._text=value,this.isClean&&this.dirty())}get archived(){return this._archived}set archived(value){value!==this._archived&&(this._archived=value,this.isClean&&this.dirty())}get spaceId(){return this._spaceId}set spaceId(value){var _a;value!==this._spaceId&&(this._spaceId=value,value!==((_a=this.space)==null?void 0:_a.id)&&(this._space=null),this.isClean&&this.dirty())}get space(){return this._space}set space(value){this._space=value,this.spaceId=(value==null?void 0:value.id)??0}in(space){return typeof space=="number"?this.spaceId=space:this.space=space,this}get ownTag(){return this._ownTag}setOwnTag(tag){if(typeof tag=="string")this.ownTag==null&&(this._ownTag=new Tag),this.ownTag.name=tag,this.ownTag.id=this.id;else{if(this.ownTag)throw new Error("Note has already had its tag set. If you would like to change the tag name, call setTag with just a string specifying the new tag name.");if(tag.id!=0&&tag.id!=this.id)throw new Error("Attempted to set tag to note with non-matching ID. Added tag id must either match the note id, which indicates that the tag has already been added to the note. Otherwise the tag id must be zero, indicating that the tag still needs to be added.");this._ownTag=tag}return this}removeOwnTag(){this.ownTag&&(this.ownTag.isNew?this._ownTag=null:this.ownTag.delete())}get tags(){return this._tags}addTag(tag){if(tag.isDeleted)throw Error("Cannot add a tag marked as deleted to a note");if(tag.isNew)throw Error("Cannot add a tag that hasn't yet been saved to a note");if(tag.id==this.id)throw Error("Note cannot add its own tag as a linked tag");let nt=this.tags.find(x=>x.tagId==tag.id);return nt?(nt.isDeleted&&nt.dirty(),nt):(nt=new NoteTag,nt.note=this,nt.tag=tag,this._tags.push(nt),nt)}removeTag(tag){const nt=this.tags.find(x=>x.tagId==tag.id);return nt?(nt.isNew?this._tags=this._tags.filter(x=>x!==nt):nt.delete(),this):this}get attrs(){return this._attrs}addAttr(attr){if(attr.isDeleted)throw Error("Cannot add an attribute marked as deleted to a note");if(attr.isNew)throw Error("Cannot add an attribute that hasn't yet been saved to a note");let na=this.attrs.find(x=>x.attrId==attr.id);return na?(na.isDeleted&&na.dirty(),na):(na=new NoteAttr,na.note=this,na.attr=attr,this._attrs.push(na),na)}removeAttr(attr){const na=this.attrs.find(x=>x.attrId==attr.id);return na?(na.isNew?this._attrs=this._attrs.filter(x=>x!==na):na.delete(),this):this}duplicate(){const output=new Note;return output.id=this.id,output.date=this.date,output.text=this.text,output.archived=this.archived,output.space=this.space,output.state=this.state,output}toJSON(){return{state:this.state,id:this.id,date:this.date,text:this.text,archived:this.archived,spaceId:this.spaceId,ownTag:this.ownTag,tags:this.tags,attrs:this.attrs}}static fromJSON(json){const output=new Note(json.text);return output.id=json.id,output.date=json.date,output.archived=json.archived,output.spaceId=json.spaceId,json.ownTag!=null&&output.setOwnTag(Tag.fromJSON(json.ownTag)),output._tags=json.tags.map(x=>NoteTag.fromJSON(x)),output._attrs=json.attrs.map(x=>NoteAttr.fromJSON(x)),output.state=json.state,output}validate(throwError=!1){let output=null;if(this.spaceId<=0?output="Note spaceId must be greater than zero.":!this.isNew&&this.id<=0&&(output="Note id must be greater than zero if in non-new state."),throwError&&output!=null)throw Error(output);if(this.ownTag&&!this.ownTag.validate(throwError))return!1;for(const nt of this.tags)if(!nt.validate(throwError))return!1;for(const na of this.attrs)if(!na.validate(throwError))return!1;return output==null}}class ParsedQuery{constructor(){__publicField(this,"where",null);__publicField(this,"order",null);__publicField(this,"tags",[]);__publicField(this,"attrs",[])}}class ParsedTag{constructor(){__publicField(this,"space",null);__publicField(this,"name",null);__publicField(this,"searchDepth",0);__publicField(this,"strictSearchDepth",!0);__publicField(this,"includeOwner",!1)}}class ParsedAttr{constructor(){__publicField(this,"space",null);__publicField(this,"name",null);__publicField(this,"exists",!1);__publicField(this,"tagNameFilters",null)}}function parseQuery(query){const output=splitQuery(query);return output.where=identifyTags(output.where,output),output.order=identifyTags(output.order,output),output.where=identifyAttrs(output.where,output),output.order=identifyAttrs(output.order,output),output}function splitQuery(query){query=" "+query+" ";const output=new ParsedQuery,orderByIndex=query.toUpperCase().indexOf(" ORDER BY ");return orderByIndex<0?output.where=query.trim():(output.where=query.substring(0,orderByIndex).trim(),output.order=query.substring(orderByIndex+10).trim()),output.where==""&&(output.where=null),output}function identifyTags(query,parsedQuery){const regexes=[/(#+\??~?|~)([\w\d]+\.)?([\w\d]+)/,/(#+\??~?|~)\[([\w\d\s]+\.)?([\w\d\s]+)\]/];for(const regex of regexes)for(;;){const match=regex.exec(query);if(!match)break;const hashPrefix=match[1],parsedTag=new ParsedTag;parsedTag.space=match[2]?match[2].substring(0,match[2].length-1):null,parsedTag.name=match[3],parsedTag.includeOwner=hashPrefix.includes("~"),parsedTag.searchDepth=(hashPrefix.match(/#/g)||[]).length,parsedTag.strictSearchDepth=!hashPrefix.includes("?");const fullMatch=match[0],matchStart=query.indexOf(fullMatch),matchEnd=matchStart+fullMatch.length;query=query.substring(0,matchStart)+`{tag${parsedQuery.tags.length}}`+query.substring(matchEnd),parsedQuery.tags.push(parsedTag)}return query}function identifyAttrs(query,parsedQuery){const regexes=[/@([\w\d]+\.(?!Exists\(|On\())?([\w\d]+)/,/@\[([\w\d\s]+\.)?([\w\d\s]+)\]/];for(const regex of regexes)for(;;){const match=regex.exec(query);if(!match)break;const parsedAttr=new ParsedAttr;parsedAttr.space=match[1]?match[1].substring(0,match[1].length-1):null,parsedAttr.name=match[2];const matchStart=query.indexOf(match[0]);let matchEnd=matchStart+match[0].length;if(query.substring(matchEnd,matchEnd+9)==".Exists()"&&(parsedAttr.exists=!0,matchEnd+=9),query.substring(matchEnd,matchEnd+4)==".On("){let tagFilterStart=matchEnd+4;if(matchEnd=query.indexOf(")",tagFilterStart),matchEnd<0)throw Error("Unclosed bracket detected");let tagNameFilters=query.substring(tagFilterStart,matchEnd).split("|");const dummyParsedQuery=new ParsedQuery;for(let tagNameFilter of tagNameFilters)tagNameFilter.startsWith("~")||(tagNameFilter="~"+tagNameFilter),identifyTags(tagNameFilter,dummyParsedQuery);parsedAttr.tagNameFilters=dummyParsedQuery.tags,matchEnd++}query=query.substring(0,matchStart)+`{attr${parsedQuery.attrs.length}}`+query.substring(matchEnd),parsedQuery.attrs.push(parsedAttr)}return query}class Space extends ModelWithState{constructor(name=""){super();__publicField(this,"id",0);__publicField(this,"_name","");this._name=name}get name(){return this._name}set name(value){value!==this._name&&(this._name=value,this.isClean&&this.dirty())}duplicate(){const output=new Space;return output.id=this.id,output.name=this.name,output.state=this.state,output}validate(throwError=!1){let output=null;if(!this.isNew&&this.id<=0&&(output="Space id must be greater than zero if in non-new state."),throwError&&output!=null)throw Error(output);return output==null}toJSON(){return{state:this.state,id:this.id,name:this.name}}static fromJSON(json){const output=new Space(json.name);return output.id=json.id,output.state=json.state,output}}exports2.Attr=Attr,exports2.Environment=Environment,exports2.HttpClient=HttpClient,exports2.Note=Note,exports2.NoteAttr=NoteAttr,exports2.NoteTag=NoteTag,exports2.ParsedAttr=ParsedAttr,exports2.ParsedQuery=ParsedQuery,exports2.ParsedTag=ParsedTag,exports2.Space=Space,exports2.Tag=Tag,exports2.parseQuery=parseQuery,Object.defineProperty(exports2,Symbol.toStringTag,{value:"Module"})});
1
+ (function(global,factory){typeof exports=="object"&&typeof module<"u"?factory(exports):typeof define=="function"&&define.amd?define(["exports"],factory):(global=typeof globalThis<"u"?globalThis:global||self,factory(global.notu={}))})(this,function(exports2){"use strict";var __defProp=Object.defineProperty;var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value;var __publicField=(obj,key,value)=>(__defNormalProp(obj,typeof key!="symbol"?key+"":key,value),value);class ModelWithState{constructor(){__publicField(this,"state","NEW")}new(){return this.state="NEW",this}clean(){return this.state="CLEAN",this}dirty(){return this.state="DIRTY",this}delete(){return this.state="DELETED",this}get isNew(){return this.state=="NEW"}get isClean(){return this.state=="CLEAN"}get isDirty(){return this.state=="DIRTY"}get isDeleted(){return this.state=="DELETED"}validate(throwError=!1){return!0}}class Attr extends ModelWithState{constructor(name){super();__publicField(this,"id",0);__publicField(this,"_name","");__publicField(this,"_type","TEXT");__publicField(this,"_spaceId",0);__publicField(this,"_space",null);name&&(this.name=name)}get name(){return this._name}set name(value){value!==this._name&&(this._name=value,this.isClean&&this.dirty())}get type(){return this._type}set type(value){if(!this.isNew)throw Error("Cannot change an attribute's type once it has been created.");this._type=value}get isText(){return this.type=="TEXT"}get isNumber(){return this.type=="NUMBER"}get isBoolean(){return this.type=="BOOLEAN"}get isDate(){return this.type=="DATE"}asText(){return this.type="TEXT",this}asNumber(){return this.type="NUMBER",this}asBoolean(){return this.type="BOOLEAN",this}asDate(){return this.type="DATE",this}get spaceId(){return this._spaceId}set spaceId(value){var _a;value!==this._spaceId&&(this._spaceId=value,value!==((_a=this.space)==null?void 0:_a.id)&&(this._space=null),this.isClean&&this.dirty())}get space(){return this._space}set space(value){this._space=value,this.spaceId=(value==null?void 0:value.id)??0}in(space){return typeof space=="number"?this.spaceId=space:this.space=space,this}duplicate(){const output=new Attr;return output.id=this.id,output.name=this.name,output.type=this.type,output.space=this.space,output}validate(throwError=!1){let output=null;if(this.spaceId<=0?output="Note spaceId must be greater than zero.":!this.isNew&&this.id<=0&&(output="Attr id must be greater than zero if in non-new state."),throwError&&output!=null)throw Error(output);return output==null}get defaultValue(){switch(this.type){case"TEXT":return"";case"NUMBER":return 0;case"BOOLEAN":return!1;case"DATE":return new Date}}toJSON(){return{state:this.state,id:this.id,name:this.name,type:this.type,spaceId:this.spaceId}}static fromJSON(json){const output=new Attr(json.name);return output.type=json.id,output.spaceId=json.spaceId,output.id=json.id,output.state=json.state,output}}class Environment{constructor(client){__publicField(this,"_client",null);__publicField(this,"_spaces",[]);if(!client)throw Error("Client must be set on Environment constructor");this._client=client}get client(){return this._client}get spaces(){return this._spaces}async loadSpaces(){return this._spaces=await this.client.getSpaces(),this.spaces}async saveSpace(space){return await this.client.saveSpace(space)}async getNotes(query,spaceId){return await this.client.getNotes(query,spaceId)}async getNoteCount(query,spaceId){return await this.client.getNoteCount(query,spaceId)}async saveNote(note){return(await this.client.saveNotes([note]))[0]}async saveNotes(notes){return await this.client.saveNotes(notes)}async customJob(name,data){return await this.client.customJob(name,data)}}class HttpClient{constructor(url,fetchMethod=null){__publicField(this,"_url",null);__publicField(this,"_token",null);__publicField(this,"_fetch");if(!url)throw Error("Endpoint URL must be passed in to NotuClient constructor");url.endsWith("/")&&(url=url.substring(0,url.length-1)),this._url=url,this._fetch=fetchMethod??fetch}get url(){return this._url}get token(){return this._token}set token(value){this._token=value}async login(username,password){const result=await this._fetch(this.url+"/login",{method:"POST",body:JSON.stringify({username,password})});return result.body!=null?(this._token=(await result.json()).token,{success:!0,error:null,token:this._token}):{success:!1,error:"Invalid username & password.",token:null}}async getSpaces(){return await(await this._fetch(this.url+"/spaces",{method:"GET",headers:{Authorization:"Bearer "+this.token}})).json()}async saveSpace(space){return await(await this._fetch(this.url+"/spaces",{method:"POST",body:JSON.stringify(space),headers:{Authorization:"Bearer "+this.token}})).json()}async getNotes(query,spaceId){return await(await this._fetch(this.url+"/notes",{method:"GET",body:JSON.stringify({query,spaceId}),headers:{Authorization:"Bearer "+this.token}})).json()}async getNoteCount(query,spaceId){return await(await this._fetch(this.url+"/notes",{method:"GET",body:JSON.stringify({query,spaceId}),headers:{Authorization:"Bearer "+this.token}})).json()}async saveNotes(notes){return await(await this._fetch(this.url+"/notes",{method:"POST",body:JSON.stringify(notes),headers:{Authorization:"Bearer "+this.token}})).json()}async customJob(name,data){return await(await this._fetch(this.url+"customjob",{method:"POST",body:JSON.stringify({name,data}),headers:{Authorization:"Bearer "+this.token}})).json()}}class NoteAttr extends ModelWithState{constructor(note,attr,value){super();__publicField(this,"_noteId",0);__publicField(this,"_note",null);__publicField(this,"_attrId",0);__publicField(this,"_attr",null);__publicField(this,"_value",null);__publicField(this,"_tagId",null);__publicField(this,"_tag",null);note!=null&&note!=null&&(typeof note=="number"?this.noteId=note:this.note=note),attr!=null&&attr!=null&&(typeof attr=="number"?this.attrId=attr:this.attr=attr),value!=null&&value!=null&&(this.value=value)}get noteId(){return this._noteId}set noteId(value){var _a;value!==this._noteId&&(this._noteId=value,value!==((_a=this.note)==null?void 0:_a.id)&&(this._note=null),this.isClean&&this.dirty())}get note(){return this._note}set note(value){this._note=value,this.noteId=(value==null?void 0:value.id)??0}get attrId(){return this._attrId}set attrId(value){var _a;value!==this._attrId&&(this._attrId=value,value!==((_a=this.attr)==null?void 0:_a.id)&&(this._attr=null),this.isClean&&this.dirty())}get attr(){return this._attr}set attr(newAttr){const oldAttr=this._attr;this._attr=newAttr,newAttr?(!oldAttr||newAttr.type!=oldAttr.type)&&(this.value=newAttr.defaultValue):this.value=null,this.attrId=(newAttr==null?void 0:newAttr.id)??0}get value(){return this._value}set value(newVal){newVal!=this._value&&(this._value=newVal,this.isClean&&this.dirty())}withValue(value){return this.value=value,this}get tagId(){return this._tagId}set tagId(value){var _a;value!==this._tagId&&(this._tagId=value,value!==((_a=this.tag)==null?void 0:_a.id)&&(this._tag=null),this.isClean&&this.dirty())}get tag(){return this._tag}set tag(value){this._tag=value,this.tagId=(value==null?void 0:value.id)??null}onTag(tag){return typeof tag=="number"?this.tagId=tag:this.tag=tag,this}duplicate(){const output=new NoteAttr;return output.noteId=this.noteId,output.note=this.note,output.attrId=this.attrId,output.attr=this.attr,output.tagId=this.tagId,output.tag=this.tag,output.value=this.value,output}validate(throwError=!1){let output=null;if(this.noteId<=0&&!this.isNew?output="NoteAttr noteId must be greater than zero":this.attrId<=0&&(output="NoteAttr attrId must be greater than zero"),throwError&&output!=null)throw Error(output);return output==null}toJSON(){return{state:this.state,noteId:this.noteId,attrId:this.attrId,tagId:this.tagId,value:this.value}}static fromJSON(json){const output=new NoteAttr(json.noteId,json.attrId,json.value);return output.tagId=json.tagId,output.state=json.state,output}}class NoteTag extends ModelWithState{constructor(note,tag){super();__publicField(this,"_noteId",0);__publicField(this,"_note",null);__publicField(this,"_tagId",0);__publicField(this,"_tag",null);note!=null&&note!=null&&(typeof note=="number"?this.noteId=note:this.note=note),tag!=null&&tag!=null&&(typeof tag=="number"?this.tagId=tag:this.tag=tag)}get noteId(){return this._noteId}set noteId(value){var _a;value!==this._noteId&&(this._noteId=value,value!==((_a=this.note)==null?void 0:_a.id)&&(this._note=null),this.isClean&&this.dirty())}get note(){return this._note}set note(value){this._note=value,this.noteId=(value==null?void 0:value.id)??0}get tagId(){return this._tagId}set tagId(value){var _a;value!==this._tagId&&(this._tagId=value,value!==((_a=this.tag)==null?void 0:_a.id)&&(this._tag=null),this.isClean&&this.dirty())}get tag(){return this._tag}set tag(value){this._tag=value,this.tagId=(value==null?void 0:value.id)??0}get attrs(){return this.note.attrs.filter(x=>x.tagId==this.tagId)}addAttr(attr){if(!this.note)throw new Error("Cannot call addAttr on NoteTag where note property has not been set");const na=this.note.addAttr(attr);return na.tag=this.tag,na}duplicate(){const output=new NoteTag;return output.noteId=this.noteId,output.tagId=this.tagId,output}validate(throwError=!1){let output=null;if(this.noteId<=0&&!this.isNew?output="NoteTag noteId must be greater than zero":this.tagId<=0?output="NoteTag tagId must be greater than zero":this.noteId==this.tagId&&(output="NoteTag cannot link a note to its own tag"),throwError&&output!=null)throw Error(output);return output==null}toJSON(){return{state:this.state,noteId:this.noteId,tagId:this.tagId}}static fromJSON(json){const output=new NoteTag(json.noteId,json.tagId);return output.state=json.state,output}}class Tag extends ModelWithState{constructor(name="",spaceId=0){super();__publicField(this,"_id",0);__publicField(this,"_spaceId",0);__publicField(this,"_space",null);__publicField(this,"_name","");__publicField(this,"_color",null);this._name=name,this._spaceId=spaceId}get id(){return this._id}set id(value){value!==this._id&&(this._id=value,this.isClean&&this.dirty())}get spaceId(){return this._spaceId}get space(){return this._space}set space(value){if(value===null){this._space=null;return}if(value.id!==this.spaceId)throw Error("Attempted to set space on Tag where spaceId doesnt match");this._space=value}get name(){return this._name}set name(value){value!==this._name&&(this._name=value,this.isClean&&this.dirty())}get color(){return this._color}set color(value){value!==this._color&&(this._color=value,this.isClean&&this.dirty())}duplicate(){const output=new Tag(this.name,this.spaceId);return output.id=this.id,output.state=this.state,output.color=this.color,output.space=this.space,output}validate(throwError=!1){let output=null;if(!this.isNew&&this.id<=0?output="Tag id must be greater than zero if in non-new state.":!this.name||!/^[a-zA-Z][a-zA-Z0-9 ]*[a-zA-Z0-9]?$/.test(this.name)?output="Tag name is invalid, must only contain letters, numbers, and spaces, starting with a letter":this.color&&!/^#?[A-z0-9]{6}$/.test(this.color)&&(output="Tag color is invalid, must be a 6 character hexadecimal."),throwError&&output!=null)throw Error(output);return output==null}getColorInt(){let hex=this.color;return hex?(hex.startsWith("#")&&(hex=hex.substring(1)),parseInt(hex,16)):null}toJSON(){return{state:this.state,id:this.id,name:this.name,spaceId:this.spaceId,color:this.color}}static fromJSON(json){const output=new Tag(json.name,json.spaceId);return output.id=json.id,output.color=json.color,output.state=json.state,output}}class Note extends ModelWithState{constructor(text){super();__publicField(this,"_id",0);__publicField(this,"_date",new Date);__publicField(this,"_text","");__publicField(this,"_archived",!1);__publicField(this,"_spaceId",0);__publicField(this,"_space",null);__publicField(this,"_ownTag",null);__publicField(this,"_tags",[]);__publicField(this,"_attrs",[]);text&&(this.text=text)}get id(){return this._id}set id(value){this._id=value,this.ownTag&&(this.ownTag.id=value)}get date(){return this._date}set date(value){value!==this._date&&(this._date=value,this.isClean&&this.dirty())}at(value){return this.date=value,this}get text(){return this._text}set text(value){value!==this._text&&(this._text=value,this.isClean&&this.dirty())}get archived(){return this._archived}set archived(value){value!==this._archived&&(this._archived=value,this.isClean&&this.dirty())}get spaceId(){return this._spaceId}set spaceId(value){var _a;value!==this._spaceId&&(this._spaceId=value,value!==((_a=this.space)==null?void 0:_a.id)&&(this._space=null),this.isClean&&this.dirty())}get space(){return this._space}set space(value){this._space=value,this.spaceId=(value==null?void 0:value.id)??0}in(space){return typeof space=="number"?this.spaceId=space:this.space=space,this}get ownTag(){return this._ownTag}setOwnTag(tag){if(typeof tag=="string")this.ownTag==null&&(this._ownTag=new Tag),this.ownTag.name=tag,this.ownTag.id=this.id;else{if(this.ownTag)throw new Error("Note has already had its tag set. If you would like to change the tag name, call setTag with just a string specifying the new tag name.");if(tag.id!=0&&tag.id!=this.id)throw new Error("Attempted to set tag to note with non-matching ID. Added tag id must either match the note id, which indicates that the tag has already been added to the note. Otherwise the tag id must be zero, indicating that the tag still needs to be added.");this._ownTag=tag}return this}removeOwnTag(){this.ownTag&&(this.ownTag.isNew?this._ownTag=null:this.ownTag.delete())}get tags(){return this._tags}addTag(tag){if(tag.isDeleted)throw Error("Cannot add a tag marked as deleted to a note");if(tag.isNew)throw Error("Cannot add a tag that hasn't yet been saved to a note");if(tag.id==this.id)throw Error("Note cannot add its own tag as a linked tag");let nt=this.tags.find(x=>x.tagId==tag.id);return nt?(nt.isDeleted&&nt.dirty(),nt):(nt=new NoteTag,nt.note=this,nt.tag=tag,this._tags.push(nt),nt)}removeTag(tag){const nt=this.tags.find(x=>x.tagId==tag.id);return nt?(nt.isNew?this._tags=this._tags.filter(x=>x!==nt):nt.delete(),this):this}get attrs(){return this._attrs}addAttr(attr){if(attr.isDeleted)throw Error("Cannot add an attribute marked as deleted to a note");if(attr.isNew)throw Error("Cannot add an attribute that hasn't yet been saved to a note");let na=this.attrs.find(x=>x.attrId==attr.id);return na?(na.isDeleted&&na.dirty(),na):(na=new NoteAttr,na.note=this,na.attr=attr,this._attrs.push(na),na)}removeAttr(attr){const na=this.attrs.find(x=>x.attrId==attr.id);return na?(na.isNew?this._attrs=this._attrs.filter(x=>x!==na):na.delete(),this):this}duplicate(){const output=new Note;return output.id=this.id,output.date=this.date,output.text=this.text,output.archived=this.archived,output.space=this.space,output.state=this.state,output}toJSON(){return{state:this.state,id:this.id,date:this.date,text:this.text,archived:this.archived,spaceId:this.spaceId,ownTag:this.ownTag,tags:this.tags,attrs:this.attrs}}static fromJSON(json){const output=new Note(json.text);return output.id=json.id,output.date=new Date(json.date),output.archived=json.archived,output.spaceId=json.spaceId,json.ownTag!=null&&output.setOwnTag(Tag.fromJSON(json.ownTag)),output._tags=json.tags.map(x=>NoteTag.fromJSON(x)),output._attrs=json.attrs.map(x=>NoteAttr.fromJSON(x)),output.state=json.state,output}validate(throwError=!1){let output=null;if(this.spaceId<=0?output="Note spaceId must be greater than zero.":!this.isNew&&this.id<=0&&(output="Note id must be greater than zero if in non-new state."),throwError&&output!=null)throw Error(output);if(this.ownTag&&!this.ownTag.validate(throwError))return!1;for(const nt of this.tags)if(!nt.validate(throwError))return!1;for(const na of this.attrs)if(!na.validate(throwError))return!1;return output==null}}class ParsedQuery{constructor(){__publicField(this,"where",null);__publicField(this,"order",null);__publicField(this,"tags",[]);__publicField(this,"attrs",[])}}class ParsedTag{constructor(){__publicField(this,"space",null);__publicField(this,"name",null);__publicField(this,"searchDepth",0);__publicField(this,"strictSearchDepth",!0);__publicField(this,"includeOwner",!1)}}class ParsedAttr{constructor(){__publicField(this,"space",null);__publicField(this,"name",null);__publicField(this,"exists",!1);__publicField(this,"tagNameFilters",null)}}function parseQuery(query){const output=splitQuery(query);return output.where=identifyTags(output.where,output),output.order=identifyTags(output.order,output),output.where=identifyAttrs(output.where,output),output.order=identifyAttrs(output.order,output),output}function splitQuery(query){query=" "+query+" ";const output=new ParsedQuery,orderByIndex=query.toUpperCase().indexOf(" ORDER BY ");return orderByIndex<0?output.where=query.trim():(output.where=query.substring(0,orderByIndex).trim(),output.order=query.substring(orderByIndex+10).trim()),output.where==""&&(output.where=null),output}function identifyTags(query,parsedQuery){const regexes=[/(#+\??~?|~)([\w\d]+\.)?([\w\d]+)/,/(#+\??~?|~)\[([\w\d\s]+\.)?([\w\d\s]+)\]/];for(const regex of regexes)for(;;){const match=regex.exec(query);if(!match)break;const hashPrefix=match[1],parsedTag=new ParsedTag;parsedTag.space=match[2]?match[2].substring(0,match[2].length-1):null,parsedTag.name=match[3],parsedTag.includeOwner=hashPrefix.includes("~"),parsedTag.searchDepth=(hashPrefix.match(/#/g)||[]).length,parsedTag.strictSearchDepth=!hashPrefix.includes("?");const fullMatch=match[0],matchStart=query.indexOf(fullMatch),matchEnd=matchStart+fullMatch.length;query=query.substring(0,matchStart)+`{tag${parsedQuery.tags.length}}`+query.substring(matchEnd),parsedQuery.tags.push(parsedTag)}return query}function identifyAttrs(query,parsedQuery){const regexes=[/@([\w\d]+\.(?!Exists\(|On\())?([\w\d]+)/,/@\[([\w\d\s]+\.)?([\w\d\s]+)\]/];for(const regex of regexes)for(;;){const match=regex.exec(query);if(!match)break;const parsedAttr=new ParsedAttr;parsedAttr.space=match[1]?match[1].substring(0,match[1].length-1):null,parsedAttr.name=match[2];const matchStart=query.indexOf(match[0]);let matchEnd=matchStart+match[0].length;if(query.substring(matchEnd,matchEnd+9)==".Exists()"&&(parsedAttr.exists=!0,matchEnd+=9),query.substring(matchEnd,matchEnd+4)==".On("){let tagFilterStart=matchEnd+4;if(matchEnd=query.indexOf(")",tagFilterStart),matchEnd<0)throw Error("Unclosed bracket detected");let tagNameFilters=query.substring(tagFilterStart,matchEnd).split("|");const dummyParsedQuery=new ParsedQuery;for(let tagNameFilter of tagNameFilters)tagNameFilter.startsWith("~")||(tagNameFilter="~"+tagNameFilter),identifyTags(tagNameFilter,dummyParsedQuery);parsedAttr.tagNameFilters=dummyParsedQuery.tags,matchEnd++}query=query.substring(0,matchStart)+`{attr${parsedQuery.attrs.length}}`+query.substring(matchEnd),parsedQuery.attrs.push(parsedAttr)}return query}class Space extends ModelWithState{constructor(name=""){super();__publicField(this,"id",0);__publicField(this,"_name","");this._name=name}get name(){return this._name}set name(value){value!==this._name&&(this._name=value,this.isClean&&this.dirty())}duplicate(){const output=new Space;return output.id=this.id,output.name=this.name,output.state=this.state,output}validate(throwError=!1){let output=null;if(!this.isNew&&this.id<=0&&(output="Space id must be greater than zero if in non-new state."),throwError&&output!=null)throw Error(output);return output==null}toJSON(){return{state:this.state,id:this.id,name:this.name}}static fromJSON(json){const output=new Space(json.name);return output.id=json.id,output.state=json.state,output}}exports2.Attr=Attr,exports2.Environment=Environment,exports2.HttpClient=HttpClient,exports2.Note=Note,exports2.NoteAttr=NoteAttr,exports2.NoteTag=NoteTag,exports2.ParsedAttr=ParsedAttr,exports2.ParsedQuery=ParsedQuery,exports2.ParsedTag=ParsedTag,exports2.Space=Space,exports2.Tag=Tag,exports2.parseQuery=parseQuery,Object.defineProperty(exports2,Symbol.toStringTag,{value:"Module"})});
@@ -1,4 +1,3 @@
1
- import { AxiosRequestConfig, AxiosResponse } from "axios";
2
1
  import Space from "../models/Space";
3
2
  import { Note } from "..";
4
3
  export interface NotuLoginResult {
@@ -21,8 +20,8 @@ export default class HttpClient {
21
20
  private _token;
22
21
  get token(): string;
23
22
  set token(value: string);
24
- private _httpRequester;
25
- constructor(url: string, httpRequester?: (config: AxiosRequestConfig<any>) => Promise<AxiosResponse<any, any>>);
23
+ private _fetch;
24
+ constructor(url: string, fetchMethod?: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>);
26
25
  login(username: string, password: string): Promise<NotuLoginResult>;
27
26
  getSpaces(): Promise<Array<Space>>;
28
27
  saveSpace(space: Space): Promise<Space>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "notu",
3
- "version": "0.4.0",
3
+ "version": "0.4.2",
4
4
  "main": "dist/notu.mjs",
5
5
  "unpkg": "dist/notu.mjs",
6
6
  "types": "dist/types/index.d.ts",
@@ -23,8 +23,5 @@
23
23
  "vite": "^4.4.5",
24
24
  "vite-plugin-dts": "^3.6.3",
25
25
  "vitest": "^0.34.4"
26
- },
27
- "dependencies": {
28
- "axios": "^1.5.1"
29
26
  }
30
27
  }