@flumens/models 0.5.3 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import Deferred from '@flumens/utils/dist/deferred';
1
+ import { Deferred } from '@flumens/utils';
2
2
  import ModelClass from './Model';
3
3
  import Store from './Stores/Store';
4
4
  interface ObservableArrayI<T> extends Array<T> {
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),r=require("@flumens/utils/dist/deferred"),i=require("@flumens/utils/dist/uuid"),n=require("./Model.js");function o(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var s=o(r),u=o(i),a=function(t){function r(r){var i=r.id,o=r.cid,a=r.models,l=void 0===a?[]:a,d=r.store,c=r.Model,f=void 0===c?n.default:c,p=t.apply(this,l)||this;return p.ready=new s.default,p.fetch=function(){return e.__awaiter(p,void 0,void 0,(function(){var t,r,i,n=this;return e.__generator(this,(function(e){switch(e.label){case 0:return this.store&&this.Model?[4,this.store.findAll()]:(this.ready.resolve(!1),[2]);case 1:return t=e.sent(),r=function(e){return new n.Model(e)},i=t.map(r),this.push.apply(this,i),this.ready.resolve(!0),[2]}}))}))},p.reset=function(){return e.__awaiter(p,void 0,void 0,(function(){return e.__generator(this,(function(e){switch(e.label){case 0:return this.length?[4,this.pop().destroy()]:[3,2];case 1:return e.sent(),[3,0];case 2:return[2]}}))}))},p.id=p.id||i,p.cid=p.cid||o||i||u.default(),p.Model=f,p.store=p.store||d,p}return e.__extends(r,t),r.prototype.spliceWithArray=function(){for(var e,t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return(e=this).spliceWithArray.apply(e,t)},r.prototype.clear=function(){return this.clear()},r.prototype.replace=function(){for(var e,t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return(e=this).replace.apply(e,t)},r.prototype.remove=function(){for(var e,t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return(e=this).remove.apply(e,t)},r.prototype.toJSON=function(){return this.toJSON()},r}((function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return t.observable(e)}));exports.default=a;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),r=require("@flumens/utils"),i=require("./Model.js"),n=function(t){function n(n){var o=n.id,s=n.cid,u=n.models,a=void 0===u?[]:u,l=n.store,c=n.Model,p=void 0===c?i.default:c,h=t.apply(this,a)||this;return h.ready=new r.Deferred,h.fetch=function(){return e.__awaiter(h,void 0,void 0,(function(){var t,r,i,n=this;return e.__generator(this,(function(e){switch(e.label){case 0:return this.store&&this.Model?[4,this.store.findAll()]:(this.ready.resolve(!1),[2]);case 1:return t=e.sent(),r=function(e){return new n.Model(e)},i=t.map(r),this.push.apply(this,i),this.ready.resolve(!0),[2]}}))}))},h.reset=function(){return e.__awaiter(h,void 0,void 0,(function(){return e.__generator(this,(function(e){switch(e.label){case 0:return this.length?[4,this.pop().destroy()]:[3,2];case 1:return e.sent(),[3,0];case 2:return[2]}}))}))},h.id=h.id||o,h.cid=h.cid||s||o||r.UUIDv7(),h.Model=p,h.store=h.store||l,h}return e.__extends(n,t),n.prototype.spliceWithArray=function(){for(var e,t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return(e=this).spliceWithArray.apply(e,t)},n.prototype.clear=function(){return this.clear()},n.prototype.replace=function(){for(var e,t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return(e=this).replace.apply(e,t)},n.prototype.remove=function(){for(var e,t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return(e=this).remove.apply(e,t)},n.prototype.toJSON=function(){return this.toJSON()},n}((function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return t.observable(e)}));exports.default=n;
@@ -1,5 +1,5 @@
1
1
  import { z } from 'zod';
2
- import Model, { Attrs as GenericModelAttrs, Options as GenericModelOptions } from '../Model';
2
+ import Model, { Data as GenericModelData, Options as GenericModelOptions } from '../Model';
3
3
  export type BackendConfig = {
4
4
  /**
5
5
  * Site URL without a trailing slash.
@@ -18,7 +18,7 @@ export type BackendConfig = {
18
18
  */
19
19
  scopes?: string[];
20
20
  };
21
- export interface Attrs extends GenericModelAttrs {
21
+ export interface Data extends GenericModelData {
22
22
  email?: string;
23
23
  verified?: boolean;
24
24
  indiciaUserId?: number;
@@ -37,7 +37,7 @@ export interface Options extends GenericModelOptions {
37
37
  */
38
38
  config: BackendConfig;
39
39
  }
40
- export default class DrupalUserModel<T extends Attrs = Attrs> extends Model<T> {
40
+ export default class DrupalUserModel<T extends Data = Data> extends Model<T> {
41
41
  config: BackendConfig;
42
42
  static loginSchema: z.ZodObject<{
43
43
  email: z.ZodString;
@@ -111,7 +111,7 @@ export default class DrupalUserModel<T extends Attrs = Attrs> extends Model<T> {
111
111
  isLoggedIn(): boolean;
112
112
  logOut(): Promise<void>;
113
113
  resetDefaults(defaultsToSet?: any): Promise<void>;
114
- getAccessToken(forceRefresh?: boolean): Promise<string | undefined>;
114
+ getAccessToken(forceRefresh?: boolean): Promise<string>;
115
115
  protected _sendVerificationEmail(email?: string): Promise<import("axios").AxiosResponse<any, any>>;
116
116
  private _exchangePasswordToTokens;
117
117
  private _refreshAccessToken;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("axios"),r=require("jwt-decode"),s=require("zod"),i=require("@flumens/utils/dist/errors"),n=require("../Model.js");function a(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var o=a(t);function c(e,t){Object.keys(t).forEach((function(r){if(r.match(/^field_/)){var s=r.replace("field_","").replace(/_([a-z])/g,(function(e){return e[1].toUpperCase()}));if(!t[r])return;if(Array.isArray(t[r])&&t[r].length)return void(e[s]=t[r][0].value);e[s]=t[r]}}))}var u=function(e){var t;if(e.response&&e.response.data&&e.response.data.message){if(e.response.data.message.includes("is already taken"))throw new i.HandledError("This email is already taken.");if("The user credentials were incorrect."===e.response.data.message)throw new i.HandledError("Incorrect password or email");if("Unrecognized username or email address."===e.response.data.message)throw new i.HandledError("Unrecognized email address.");if("This account is already activated"===e.response.data.message)throw new i.HandledError("This account is already activated.");if(e.response.data.message.includes("not been activated"))throw new i.HandledError("The user has not been activated or is blocked.");throw new Error(e.response.data.message)}if(null===(t=e.message)||void 0===t?void 0:t.includes("timeout"))throw new i.HandledError("Timeout");throw e},h=6e4;var d={email:"",tokens:void 0,verified:!1,iss:void 0,indiciaUserId:void 0},l=function(t){function i(r){var s=this,i=r.config,n=e.__rest(r,["config"]);return(s=t.call(this,e.__assign(e.__assign({},n),{attrs:e.__assign(e.__assign({},d),n.attrs)}))||this).config=i,s}return e.__extends(i,t),i.prototype.logIn=function(t,r){return e.__awaiter(this,void 0,void 0,(function(){var s;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this._exchangePasswordToTokens(t,r)];case 1:return s=e.sent(),this.attrs.tokens=s,[4,this.refreshProfile()];case 2:return e.sent(),[2,this.save()]}}))}))},i.prototype.register=function(t,r,s){return e.__awaiter(this,void 0,void 0,(function(){var n,a,d,l;return e.__generator(this,(function(f){switch(f.label){case 0:return n=JSON.stringify(e.__assign({name:[{value:t}],pass:[{value:r}],mail:[{value:t}]},s)),a={method:"post",url:"".concat(this.config.url,"/user/register-with-password?_format=json"),headers:{"content-type":"application/json"},data:n,timeout:h},[4,o.default(a).catch(u)];case 1:if(d=f.sent().data,!!i.registerSchemaBackend.safeParse(d).error)throw new Error("Invalid backend response.");return[4,this._exchangePasswordToTokens(t,r)];case 2:return l=f.sent(),this.attrs.tokens=l,this.id=d.uid[0].value,this.attrs.email=t,c(this.attrs,d),[2,this.save()]}}))}))},i.prototype.reset=function(t){return e.__awaiter(this,void 0,void 0,(function(){var r,s,i;return e.__generator(this,(function(e){switch(e.label){case 0:r=JSON.stringify({mail:t}),s={method:"post",url:"".concat(this.config.url,"/user/password?_format=json"),headers:{"content-type":"application/json"},data:r},e.label=1;case 1:return e.trys.push([1,3,,6]),[4,o.default(s).catch(u)];case 2:return e.sent(),[3,6];case 3:return"The user has not been activated or is blocked."!==(i=e.sent()).message?[3,5]:[4,this._sendVerificationEmail(t)];case 4:return e.sent(),[2];case 5:return u(i),[3,6];case 6:return[2]}}))}))},i.prototype.delete=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this.getAccessToken(!0)];case 1:return t=e.sent(),r={method:"delete",url:"".concat(this.config.url,"/user/").concat(this.id,"?_format=json"),headers:{Authorization:"Bearer ".concat(t)}},[4,o.default(r).catch(u)];case 2:return e.sent(),this.logOut(),[2]}}))}))},i.prototype.refreshProfile=function(){return e.__awaiter(this,void 0,void 0,(function(){var t=this;return e.__generator(this,(function(r){return this._refreshingProfilePromise||(this._refreshingProfilePromise=Promise.resolve().then((function(){return e.__awaiter(t,void 0,void 0,(function(){var t,r,s;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this.getAccessToken(!0)];case 1:return t=e.sent(),this.attrs.verified?(r={url:"".concat(this.config.url,"/user/").concat(this.id,"?_format=json"),headers:{Authorization:"Bearer ".concat(t)},timeout:h},[4,o.default(r).catch(u)]):[3,3];case 2:s=e.sent().data,this.attrs.email=s.mail[0].value,c(this.attrs,s),e.label=3;case 3:return[4,this.save()];case 4:return e.sent(),delete this._refreshingProfilePromise,[2]}}))}))})).catch((function(e){throw delete t._refreshingProfilePromise,e}))),[2,this._refreshingProfilePromise]}))}))},i.prototype.hasLogIn=function(){return console.warn("hasLogIn is deprecated, please use isLoggedIn instead."),this.isLoggedIn()},i.prototype.isLoggedIn=function(){return this.attrs.email,!!this.id},i.prototype.logOut=function(){return e.__awaiter(this,void 0,void 0,(function(){return e.__generator(this,(function(e){return[2,this.resetDefaults()]}))}))},i.prototype.resetDefaults=function(r){return t.prototype.resetDefaults.call(this,e.__assign(e.__assign({},d),r))},i.prototype.getAccessToken=function(t){var s;return e.__awaiter(this,void 0,void 0,(function(){var i,n,a,o,c;return e.__generator(this,(function(e){switch(e.label){case 0:if(!t&&!this.isLoggedIn())throw new Error("User is not logged in.");if(i=(this.attrs.tokens||{}).access_token,n=function(e){if(!e)return!0;var t=1e3*r.jwtDecode(e).exp;return Date.now()+12e4>t}(i),!(!i||n||t))return[3,6];e.label=1;case 1:return e.trys.push([1,3,,6]),[4,this._refreshAccessToken()];case 2:return e.sent(),[3,6];case 3:return a=e.sent(),console.error(a),o="The refresh token is invalid."===a.message,c="Token has no user email."===a.message,o||c?[4,this.logOut()]:[3,5];case 4:throw e.sent(),new Error("User re-login is required.");case 5:throw a;case 6:return[2,null===(s=this.attrs.tokens)||void 0===s?void 0:s.access_token]}}))}))},i.prototype._sendVerificationEmail=function(t){return e.__awaiter(this,void 0,void 0,(function(){var r,s;return e.__generator(this,(function(e){return r=JSON.stringify({mail:[{value:t||this.attrs.email}]}),s={method:"post",url:"".concat(this.config.url,"/user/register-with-password?_format=json&resendVerificationEmail=true"),headers:{"content-type":"application/json"},data:r,timeout:h},[2,o.default(s).catch(u)]}))}))},i.prototype._exchangePasswordToTokens=function(t,r){var s;return e.__awaiter(this,void 0,void 0,(function(){var i,n;return e.__generator(this,(function(e){switch(e.label){case 0:return(i=new FormData).append("grant_type","password"),i.append("username",t),i.append("password",r),i.append("client_id",this.config.clientId),this.config.clientPass&&i.append("client_secret",this.config.clientPass),(null===(s=this.config.scopes)||void 0===s?void 0:s.length)&&i.append("scope",this.config.scopes.join(" ")),n={method:"post",url:"".concat(this.config.url,"/oauth/token"),data:i},[4,o.default(n).catch(u)];case 1:return[2,e.sent().data]}}))}))},i.prototype._refreshAccessToken=function(){return e.__awaiter(this,void 0,void 0,(function(){var t=this;return e.__generator(this,(function(s){return this._refreshingTokenPromise||(this._refreshingTokenPromise=Promise.resolve().then((function(){return e.__awaiter(t,void 0,void 0,(function(){var t,s,i,n,a,d;return e.__generator(this,(function(l){switch(l.label){case 0:if(!(t=(this.attrs.tokens||{}).refresh_token))throw new Error("No user session refresh token was found");return(s=new FormData).append("grant_type","refresh_token"),s.append("refresh_token",t),s.append("client_id",this.config.clientId),this.config.clientPass&&s.append("client_secret",this.config.clientPass),i={method:"post",url:"".concat(this.config.url,"/oauth/token"),data:s,timeout:h},[4,o.default(i).catch(u)];case 1:if(n=l.sent().data,this.attrs.tokens=e.__assign(e.__assign({},this.attrs.tokens),n),a=r.jwtDecode(null===(d=this.attrs.tokens)||void 0===d?void 0:d.access_token),this.id=a.sub,this.attrs.email=a.email,!this.attrs.email)throw new Error("Token has no user email.");return this.attrs.verified=a.email_verified,this.attrs.iss=a.iss,this.attrs.indiciaUserId=a["http://indicia.org.uk/user:id"],a.scopes&&(this.attrs.roles=a.scopes),c(this.attrs,a),[4,this.save()];case 2:return l.sent(),delete this._refreshingTokenPromise,[2]}}))}))})).catch((function(e){throw delete t._refreshingTokenPromise,e}))),[2,this._refreshingTokenPromise]}))}))},i.loginSchema=s.object({email:s.z.string().email("Please fill in"),password:s.z.string().min(1,"Please fill in")}),i.loginSchemaBackend=s.object({id:s.z.number(),email:s.z.string().email()}),i.resetSchema=s.object({email:s.z.string().email("Please fill in")}),i.registerSchema=s.object({email:s.z.string().email("Please fill in"),password:s.z.string().min(1,"Please fill in")}),i.registerSchemaBackend=s.object({uid:s.z.array(s.object({value:s.z.number()}))}),i}(n.default);exports.default=l;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("axios"),r=require("jwt-decode"),s=require("zod"),i=require("@flumens/utils"),n=require("../Model.js");function a(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var o=a(t);function c(e,t){Object.keys(t).forEach((function(r){if(r.match(/^field_/)){var s=r.replace("field_","").replace(/_([a-z])/g,(function(e){return e[1].toUpperCase()}));if(!t[r])return;if(Array.isArray(t[r])&&t[r].length)return void(e[s]=t[r][0].value);e[s]=t[r]}}))}var u=function(e){var t;if(e.response&&e.response.data&&e.response.data.message){if(e.response.data.message.includes("is already taken"))throw new i.HandledError("This email is already taken.");if("The user credentials were incorrect."===e.response.data.message)throw new i.HandledError("Incorrect password or email");if("Unrecognized username or email address."===e.response.data.message)throw new i.HandledError("Unrecognized email address.");if("This account is already activated"===e.response.data.message)throw new i.HandledError("This account is already activated.");if(e.response.data.message.includes("not been activated"))throw new i.HandledError("The user has not been activated or is blocked.");throw new Error(e.response.data.message)}if(null===(t=e.message)||void 0===t?void 0:t.includes("timeout"))throw new i.HandledError("Timeout");throw e},d=6e4;var h={email:"",tokens:void 0,verified:!1,iss:void 0,indiciaUserId:void 0},l=function(t){function i(r){var s=this,i=r.config,n=e.__rest(r,["config"]);return(s=t.call(this,e.__assign(e.__assign({},n),{data:e.__assign(e.__assign({},h),n.data)}))||this).config=i,s}return e.__extends(i,t),i.prototype.logIn=function(t,r){return e.__awaiter(this,void 0,void 0,(function(){var s;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this._exchangePasswordToTokens(t,r)];case 1:return s=e.sent(),this.data.tokens=s,[4,this.refreshProfile()];case 2:return e.sent(),[2,this.save()]}}))}))},i.prototype.register=function(t,r,s){return e.__awaiter(this,void 0,void 0,(function(){var n,a,h,l;return e.__generator(this,(function(f){switch(f.label){case 0:return n=JSON.stringify(e.__assign({name:[{value:t}],pass:[{value:r}],mail:[{value:t}]},s)),a={method:"post",url:"".concat(this.config.url,"/user/register-with-password?_format=json"),headers:{"content-type":"application/json"},data:n,timeout:d},[4,o.default(a).catch(u)];case 1:if(h=f.sent().data,!!i.registerSchemaBackend.safeParse(h).error)throw new Error("Invalid backend response.");return[4,this._exchangePasswordToTokens(t,r)];case 2:return l=f.sent(),this.data.tokens=l,this.id=h.uid[0].value,this.data.email=t,c(this.data,h),[2,this.save()]}}))}))},i.prototype.reset=function(t){return e.__awaiter(this,void 0,void 0,(function(){var r,s,i;return e.__generator(this,(function(e){switch(e.label){case 0:r=JSON.stringify({mail:t}),s={method:"post",url:"".concat(this.config.url,"/user/password?_format=json"),headers:{"content-type":"application/json"},data:r},e.label=1;case 1:return e.trys.push([1,3,,6]),[4,o.default(s).catch(u)];case 2:return e.sent(),[3,6];case 3:return"The user has not been activated or is blocked."!==(i=e.sent()).message?[3,5]:[4,this._sendVerificationEmail(t)];case 4:return e.sent(),[2];case 5:return u(i),[3,6];case 6:return[2]}}))}))},i.prototype.delete=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this.getAccessToken(!0)];case 1:return t=e.sent(),r={method:"delete",url:"".concat(this.config.url,"/user/").concat(this.id,"?_format=json"),headers:{Authorization:"Bearer ".concat(t)}},[4,o.default(r).catch(u)];case 2:return e.sent(),this.logOut(),[2]}}))}))},i.prototype.refreshProfile=function(){return e.__awaiter(this,void 0,void 0,(function(){var t=this;return e.__generator(this,(function(r){return this._refreshingProfilePromise||(this._refreshingProfilePromise=Promise.resolve().then((function(){return e.__awaiter(t,void 0,void 0,(function(){var t,r,s;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this.getAccessToken(!0)];case 1:return t=e.sent(),this.data.verified?(r={url:"".concat(this.config.url,"/user/").concat(this.id,"?_format=json"),headers:{Authorization:"Bearer ".concat(t)},timeout:d},[4,o.default(r).catch(u)]):[3,3];case 2:s=e.sent().data,this.data.email=s.mail[0].value,c(this.data,s),e.label=3;case 3:return[4,this.save()];case 4:return e.sent(),delete this._refreshingProfilePromise,[2]}}))}))})).catch((function(e){throw delete t._refreshingProfilePromise,e}))),[2,this._refreshingProfilePromise]}))}))},i.prototype.hasLogIn=function(){return console.warn("hasLogIn is deprecated, please use isLoggedIn instead."),this.isLoggedIn()},i.prototype.isLoggedIn=function(){return this.data.email,!!this.id},i.prototype.logOut=function(){return e.__awaiter(this,void 0,void 0,(function(){return e.__generator(this,(function(e){return[2,this.resetDefaults()]}))}))},i.prototype.resetDefaults=function(r){return t.prototype.resetDefaults.call(this,e.__assign(e.__assign({},h),r))},i.prototype.getAccessToken=function(t){return e.__awaiter(this,void 0,void 0,(function(){var s,i,n,a,o;return e.__generator(this,(function(e){switch(e.label){case 0:if(!t&&!this.isLoggedIn())throw new Error("User is not logged in.");if(s=(this.data.tokens||{}).access_token,i=function(e){if(!e)return!0;var t=1e3*r.jwtDecode(e).exp;return Date.now()+12e4>t}(s),!(!s||i||t))return[3,6];e.label=1;case 1:return e.trys.push([1,3,,6]),[4,this._refreshAccessToken()];case 2:return e.sent(),[3,6];case 3:return n=e.sent(),console.error(n),a="The refresh token is invalid."===n.message,o="Token has no user email."===n.message,a||o?[4,this.logOut()]:[3,5];case 4:throw e.sent(),new Error("User re-login is required.");case 5:throw n;case 6:return[2,this.data.tokens.access_token]}}))}))},i.prototype._sendVerificationEmail=function(t){return e.__awaiter(this,void 0,void 0,(function(){var r,s;return e.__generator(this,(function(e){return r=JSON.stringify({mail:[{value:t||this.data.email}]}),s={method:"post",url:"".concat(this.config.url,"/user/register-with-password?_format=json&resendVerificationEmail=true"),headers:{"content-type":"application/json"},data:r,timeout:d},[2,o.default(s).catch(u)]}))}))},i.prototype._exchangePasswordToTokens=function(t,r){return e.__awaiter(this,void 0,void 0,(function(){var s,i,n;return e.__generator(this,(function(e){switch(e.label){case 0:return(s=new FormData).append("grant_type","password"),s.append("username",t),s.append("password",r),s.append("client_id",this.config.clientId),this.config.clientPass&&s.append("client_secret",this.config.clientPass),(null===(n=this.config.scopes)||void 0===n?void 0:n.length)&&s.append("scope",this.config.scopes.join(" ")),i={method:"post",url:"".concat(this.config.url,"/oauth/token"),data:s},[4,o.default(i).catch(u)];case 1:return[2,e.sent().data]}}))}))},i.prototype._refreshAccessToken=function(){return e.__awaiter(this,void 0,void 0,(function(){var t=this;return e.__generator(this,(function(s){return this._refreshingTokenPromise||(this._refreshingTokenPromise=Promise.resolve().then((function(){return e.__awaiter(t,void 0,void 0,(function(){var t,s,i,n,a,h;return e.__generator(this,(function(l){switch(l.label){case 0:if(!(t=(this.data.tokens||{}).refresh_token))throw new Error("No user session refresh token was found");return(s=new FormData).append("grant_type","refresh_token"),s.append("refresh_token",t),s.append("client_id",this.config.clientId),this.config.clientPass&&s.append("client_secret",this.config.clientPass),i={method:"post",url:"".concat(this.config.url,"/oauth/token"),data:s,timeout:d},[4,o.default(i).catch(u)];case 1:if(n=l.sent().data,this.data.tokens=e.__assign(e.__assign({},this.data.tokens),n),a=r.jwtDecode(null===(h=this.data.tokens)||void 0===h?void 0:h.access_token),this.id=a.sub,this.data.email=a.email,!this.data.email)throw new Error("Token has no user email.");return this.data.verified=a.email_verified,this.data.iss=a.iss,this.data.indiciaUserId=a["http://indicia.org.uk/user:id"],a.scopes&&(this.data.roles=a.scopes),c(this.data,a),[4,this.save()];case 2:return l.sent(),delete this._refreshingTokenPromise,[2]}}))}))})).catch((function(e){throw delete t._refreshingTokenPromise,e}))),[2,this._refreshingTokenPromise]}))}))},i.loginSchema=s.object({email:s.z.string().email("Please fill in"),password:s.z.string().min(1,"Please fill in")}),i.loginSchemaBackend=s.object({id:s.z.number(),email:s.z.string().email()}),i.resetSchema=s.object({email:s.z.string().email("Please fill in")}),i.registerSchema=s.object({email:s.z.string().email("Please fill in"),password:s.z.string().min(1,"Please fill in")}),i.registerSchemaBackend=s.object({uid:s.z.array(s.object({value:s.z.number()}))}),i}(n.default);exports.default=l;
@@ -135,4 +135,9 @@ export default interface Source {
135
135
  warehouse: string;
136
136
  id: string;
137
137
  }
138
+ export declare function fetchElasticOccurrences({ parentId, url, accessToken, }: {
139
+ parentId: string | string[];
140
+ url: string;
141
+ accessToken: string;
142
+ }): Promise<Source[]>;
138
143
  export {};
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib");function r(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var t=r(require("axios"));exports.fetchElasticOccurrences=function(r){return e.__awaiter(this,arguments,void 0,(function(r){var n,i,s,o,a,u,c,d,l,v,p=r.parentId,_=r.url,f=r.accessToken;return e.__generator(this,(function(r){switch(r.label){case 0:return n={terms:{"event.parent_event_id":Array.isArray(p)?p:[p]}},i={terms:{"event.event_id":Array.isArray(p)?p:[p]}},s=JSON.stringify({size:1e3,query:{bool:{must:[{bool:{should:[n,i]}}]}}}),o={Authorization:"Bearer ".concat(f)},a={method:"post",url:"".concat(_,"/index.php/services/rest/es-occurrences/_search"),headers:e.__assign({"Content-Type":"application/json"},o),data:s},[4,t.default.request(a)];case 1:return u=r.sent(),c=function(e){return e._source},[2,(null===(v=null===(l=null===(d=u.data)||void 0===d?void 0:d.hits)||void 0===l?void 0:l.hits)||void 0===v?void 0:v.map(c))||[]]}}))}))};
@@ -96,4 +96,15 @@ export default interface Source {
96
96
  '@timestamp': Date;
97
97
  id: string;
98
98
  }
99
+ export declare function fetchElasticSubSamples({ parentId, url, accessToken, }: {
100
+ parentId: string | string[];
101
+ url: string;
102
+ accessToken: string;
103
+ }): Promise<Source[]>;
104
+ export declare function fetchElasticSample({ id, cid, url, accessToken, }: {
105
+ id?: string;
106
+ cid?: string;
107
+ url: string;
108
+ accessToken: string;
109
+ }): Promise<Source>;
99
110
  export {};
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib");function t(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var r=t(require("axios"));exports.fetchElasticSample=function(t){return e.__awaiter(this,arguments,void 0,(function(t){var i,s,n,o,a,u,c,l,d,h,p=t.id,v=t.cid,f=t.url,_=t.accessToken;return e.__generator(this,(function(t){switch(t.label){case 0:return i=JSON.stringify({size:1e3,query:{bool:{must:[{match:{id:p}}]}}}),p||(i=JSON.stringify({size:1e3,query:{bool:{must:[{match:{"event.source_system_key":v}}]}}})),s={Authorization:"Bearer ".concat(_)},n={method:"post",url:"".concat(f,"/index.php/services/rest/es-samples/_search"),headers:e.__assign({"Content-Type":"application/json"},s),data:i},[4,r.default.request(n)];case 1:if(o=t.sent(),a=function(e){return e._source},u=(null===(h=null===(d=null===(l=o.data)||void 0===l?void 0:l.hits)||void 0===d?void 0:d.hits)||void 0===h?void 0:h.map(a))||[],!(c=u[0]))throw new Error("Remote sample with id ".concat(p||v," was not found"));return[2,c]}}))}))},exports.fetchElasticSubSamples=function(t){return e.__awaiter(this,arguments,void 0,(function(t){var i,s,n,o,a,u,c,l,d=t.parentId,h=t.url,p=t.accessToken;return e.__generator(this,(function(t){switch(t.label){case 0:return i=JSON.stringify({size:1e3,query:{bool:{must:[{terms:{"event.parent_event_id":Array.isArray(d)?d:[d]}}]}}}),s={Authorization:"Bearer ".concat(p)},n={method:"post",url:"".concat(h,"/index.php/services/rest/es-samples/_search"),headers:e.__assign({"Content-Type":"application/json"},s),data:i},[4,r.default.request(n)];case 1:return o=t.sent(),a=function(e){return e._source},[2,(null===(l=null===(c=null===(u=o.data)||void 0===u?void 0:u.hits)||void 0===c?void 0:c.hits)||void 0===l?void 0:l.map(a))||[]]}}))}))};
@@ -1,4 +1,4 @@
1
- import Model, { Attrs as AttrsOriginal, Options as OptionsOriginal } from '../Model';
1
+ import Model, { Data as DataOriginal, Options as OptionsOriginal } from '../Model';
2
2
  import Occurrence from './Occurrence';
3
3
  import Sample from './Sample';
4
4
  export interface Metadata {
@@ -8,7 +8,7 @@ export type URL = string;
8
8
  export interface Options<T = any, S = any> extends OptionsOriginal<T> {
9
9
  metadata?: S;
10
10
  }
11
- export interface Attrs extends AttrsOriginal {
11
+ export interface Data extends DataOriginal {
12
12
  type?: string;
13
13
  data?: any;
14
14
  thumbnail?: DataURI;
@@ -24,8 +24,7 @@ export interface Remote {
24
24
  headers?: any;
25
25
  timeout?: number;
26
26
  }
27
- declare class Media<T extends Attrs = Attrs, S extends Metadata = Metadata> extends Model {
28
- static fromJSON(json: any): Media<Attrs, Metadata>;
27
+ declare class Media<T extends Data = Data, S extends Metadata = Metadata> extends Model<T> {
29
28
  /**
30
29
  * Transforms and resizes an image file into a string.
31
30
  * Can accept file image path and a file input file.
@@ -53,7 +52,6 @@ declare class Media<T extends Attrs = Attrs, S extends Metadata = Metadata> exte
53
52
  * @returns
54
53
  */
55
54
  static getImageModel(imageURL: URL, dataDirPath: string, skipThumbnail?: boolean): Promise<Media>;
56
- attrs: T;
57
55
  metadata: S;
58
56
  remote: Remote;
59
57
  debouncedValue: number;
@@ -82,7 +80,7 @@ declare class Media<T extends Attrs = Attrs, S extends Metadata = Metadata> exte
82
80
  width?: number;
83
81
  height?: number;
84
82
  }): Promise<void>;
85
- isUploaded(): boolean;
86
- isDisabled(): boolean;
83
+ get isUploaded(): boolean;
84
+ get isDisabled(): boolean;
87
85
  }
88
86
  export default Media;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("tslib"),e=require("mobx"),r=require("axios"),i=require("@flumens/utils/dist/image"),a=require("../Model.js"),n=require("./helpers.js");function o(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}var s,d=o(r),u=!!window.cordova||!!(null===(s=null===window||void 0===window?void 0:window.Capacitor)||void 0===s?void 0:s.isNative),h=function(r){function a(i){var a=this;void 0===i&&(i={});var n=i.metadata,o=void 0===n?{}:n,s=t.__rest(i,["metadata"]);return(a=r.call(this,s)||this).remote={synchronising:!1,url:null,headers:{},timeout:12e4},a.debouncedValue=300,a.parent=a.parent,a.metadata=e.observable(o),a}return t.__extends(a,r),a.fromJSON=function(e){var r,i,a;return new this(t.__assign(t.__assign({},e),{createdAt:e.createdAt||(null===(r=e.metadata)||void 0===r?void 0:r.createdOn),updatedAt:e.updatedAt||(null===(i=e.metadata)||void 0===i?void 0:i.updatedOn),syncedAt:e.syncedAt||(null===(a=e.metadata)||void 0===a?void 0:a.syncedOn)}))},a.getDataURI=function(t,e){void 0===e&&(e={});var r=new Promise((function(r,i){if("string"==typeof t){var n=t.replace(/.*\.([a-z]+)$/i,"$1");return"jpg"===n&&(n="jpeg"),void a.resize(t,n,e.width,e.height).then((function(t){var e=t[0],i=t[1];r([i,n,e.width,e.height])}))}if(window.FileReader){var o=new FileReader;o.onload=function(i){var n,o;if(e.width||e.height)a.resize(null===(n=i.target)||void 0===n?void 0:n.result,t.type,e.width,e.height).then((function(e){var i=e[0],a=e[1];r([a,t.type,i.width,i.height])}));else{var s=new window.Image;s.onload=function(){var e,a=t.type.replace(/.*\/([a-z]+)$/i,"$1");r([null===(e=i.target)||void 0===e?void 0:e.result,a,s.width,s.height])},s.src=null===(o=i.target)||void 0===o?void 0:o.result}},o.readAsDataURL(t)}else i(new Error("No File Reader"))}));return r},a.resize=function(t,e,r,i){var a=new Promise((function(a){var n=new window.Image;n.onload=function(){var t,o=n.width,s=n.height,d=null;o/=d=o>s?o/(!r||r>o?o:r):s/(!i||i>s?s:i),s/=d;var u=document.createElement("canvas");u.width=o,u.height=s,null===(t=u.getContext("2d"))||void 0===t||t.drawImage(n,0,0,o,s),a([n,u.toDataURL(e)])},n.src=t}));return a},a.getImageModel=function(e,r,a){return t.__awaiter(this,void 0,void 0,(function(){var n,o,s,d,h,c,l;return t.__generator(this,(function(t){switch(t.label){case 0:if(n=this,!e)throw new Error("File not found while creating image model.");return u?[4,i.createImage(e)]:[3,2];case 1:return h=t.sent(),o=h.width,s=h.height,d=e.split("/").pop(),[3,4];case 2:return[4,n.getDataURI(e,{width:2e3,height:2e3})];case 3:l=t.sent(),d=l[0],o=l[2],s=l[3],t.label=4;case 4:return c=new n({attrs:{data:d,type:"jpeg",width:o,height:s,path:r}}),a?[3,6]:[4,c.addThumbnail()];case 5:t.sent(),t.label=6;case 6:return[2,c]}}))}))},a.prototype.toJSON=function(){var i=r.prototype.toJSON.call(this);return JSON.parse(JSON.stringify(t.__assign(t.__assign({},i),{metadata:e.toJS(this.metadata)||{}})))},a.prototype.setupdatedAtTimestamp=function(t){var e;r.prototype.setUpdatedAtTimestamp.call(this,t),null===(e=this.parent)||void 0===e||e.setUpdatedAtTimestamp(t)},a.prototype.getSubmission=function(t){void 0===t&&(t={});var e=t[this.cid];if(!this.id&&!e)throw new Error("Image ID or queued ID is missing.");var r={values:{caption:this.attrs.caption}};return this.id?r.values.id=this.id:r.values.queued=e.name,r},a.prototype.sync=function(){return t.__awaiter(this,void 0,void 0,(function(){return t.__generator(this,(function(t){return[2,this.parent?this.parent.sync():r.prototype.sync.call(this)]}))}))},a.prototype.uploadFile=function(e){var r;return void 0===e&&(e=!1),t.__awaiter(this,void 0,void 0,(function(){var i,a,n,o,s,u,h,c;return t.__generator(this,(function(t){switch(t.label){case 0:if(this.id)throw new Error("A file of a media on the remote cannot be uploaded again.");return i=Date.now()-432e5,a=this.syncedAt>i&&this.attrs.queued,!e&&a?[2]:[4,this.getFormData()];case 1:return n=t.sent(),o=new FormData,(c=o).append.apply(c,n),"function"!=typeof this.remote.headers?[3,3]:[4,this.remote.headers()];case 2:return u=t.sent(),[3,4];case 3:u=this.remote.headers,t.label=4;case 4:return s=u,[4,d.default.post("".concat(this.remote.url,"/media-queue"),o,{headers:s,timeout:12e4})];case 5:if(h=t.sent(),!(null===(r=h.data[this.cid])||void 0===r?void 0:r.name))throw new Error("New remote media name was not be found.");return this.attrs.queued=h.data[this.cid].name,this.syncedAt=(new Date).getTime(),[2]}}))}))},a.prototype.getFormData=function(){return t.__awaiter(this,void 0,void 0,(function(){var e,r,i,a,o,s,d;return t.__generator(this,(function(t){switch(t.label){case 0:return e=this.attrs.type,r=e,i=e,(null==e?void 0:e.match(/image.*/))?(d=e.split("/"),r=d[1]):i="image/".concat(i),a=this.getURL(),[4,n.getBlobFromURL(a,i)];case 1:return o=t.sent(),[2,[s=this.cid,o,"".concat(s,".").concat(r)]]}}))}))},a.prototype.getRemoteURL=function(){if(!this.remote.url)throw new Error("No remote url was set.");if(!this.attrs.queued&&!this.attrs.path)throw new Error("No media queued or path attribute.");var t=this.remote.url.replace("/index.php/services/rest","");return this.attrs.queued?"".concat(t,"/upload-queue/").concat(this.attrs.queued):"".concat(t,"/upload/").concat(this.attrs.path)},a.prototype.getURL=function(){return this.attrs.data},a.prototype.resize=function(t,e){var r=this,i=this,n=new Promise((function(n,o){a.resize(r.getURL(),r.attrs.type,t,e).then((function(t){var e=t[0],r=t[1];i.attrs.data=r,n([e,r])})).catch(o)}));return n},a.prototype.addThumbnail=function(t){var e=this,r=this;return new Promise((function(t,i){/^data:/i.test(e.getURL())?a.resize(e.getURL(),e.attrs.type,100,100).then((function(e){var i=e[1];r.attrs.thumbnail=i,t()})).catch(i):a.getDataURI(e.getURL(),{width:100,height:100}).then((function(e){r.attrs.thumbnail=e[0],t()})).catch(i)}))},a.prototype.isUploaded=function(){if(!this.parent)throw new Error("No media parent to return disabled status.");return this.parent.isUploaded()},a.prototype.isDisabled=function(){return this.isUploaded()},a}(a.default);exports.default=h;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("tslib"),e=require("mobx"),a=require("axios"),r=require("@flumens/utils"),i=require("../Model.js"),n=require("./helpers.js");function o(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}var s=o(a),d=r.isPlatform("hybrid"),u=function(a){function i(r){void 0===r&&(r={});var i=this,n=r.metadata,o=void 0===n?{}:n,s=t.__rest(r,["metadata"]);return s.createdAt=s.createdAt||(null==o?void 0:o.createdOn),s.updatedAt=s.updatedAt||(null==o?void 0:o.updatedOn),s.syncedAt=s.syncedAt||(null==o?void 0:o.syncedOn),(i=a.call(this,s)||this).remote={synchronising:!1,url:null,headers:{},timeout:12e4},i.debouncedValue=300,i.parent=i.parent,i.metadata=e.observable(o),i}return t.__extends(i,a),i.getDataURI=function(t,e){return void 0===e&&(e={}),new Promise((function(a,r){if("string"==typeof t){var n=t.replace(/.*\.([a-z]+)$/i,"$1");return"jpg"===n&&(n="jpeg"),void i.resize(t,n,e.width,e.height).then((function(t){var e=t[0],r=t[1];a([r,n,e.width,e.height])}))}if(window.FileReader){var o=new FileReader;o.onload=function(r){var n,o;if(e.width||e.height)i.resize(null===(n=r.target)||void 0===n?void 0:n.result,t.type,e.width,e.height).then((function(e){var r=e[0],i=e[1];a([i,t.type,r.width,r.height])}));else{var s=new window.Image;s.onload=function(){var e,i=t.type.replace(/.*\/([a-z]+)$/i,"$1");a([null===(e=r.target)||void 0===e?void 0:e.result,i,s.width,s.height])},s.src=null===(o=r.target)||void 0===o?void 0:o.result}},o.readAsDataURL(t)}else r(new Error("No File Reader"))}))},i.resize=function(t,e,a,r){return new Promise((function(i){var n=new window.Image;n.onload=function(){var t,o=n.width,s=n.height,d=null;o/=d=o>s?o/(!a||a>o?o:a):s/(!r||r>s?s:r),s/=d;var u=document.createElement("canvas");u.width=o,u.height=s,null===(t=u.getContext("2d"))||void 0===t||t.drawImage(n,0,0,o,s),i([n,u.toDataURL(e)])},n.src=t}))},i.getImageModel=function(e,a,i){return t.__awaiter(this,void 0,void 0,(function(){var n,o,s,u,h,c,l;return t.__generator(this,(function(t){switch(t.label){case 0:if(n=this,!e)throw new Error("File not found while creating image model.");return d?[4,r.createImage(e)]:[3,2];case 1:return h=t.sent(),o=h.width,s=h.height,u=e.split("/").pop(),[3,4];case 2:return[4,n.getDataURI(e,{width:2e3,height:2e3})];case 3:l=t.sent(),u=l[0],o=l[2],s=l[3],t.label=4;case 4:return c=new n({data:{data:u,type:"jpeg",width:o,height:s,path:a}}),i?[3,6]:[4,c.addThumbnail()];case 5:t.sent(),t.label=6;case 6:return[2,c]}}))}))},i.prototype.toJSON=function(){var r=a.prototype.toJSON.call(this);return JSON.parse(JSON.stringify(t.__assign(t.__assign({},r),{metadata:e.toJS(this.metadata)||{}})))},i.prototype.setupdatedAtTimestamp=function(t){var e;a.prototype.setUpdatedAtTimestamp.call(this,t),null===(e=this.parent)||void 0===e||e.setUpdatedAtTimestamp(t)},i.prototype.getSubmission=function(t){void 0===t&&(t={});var e=t[this.cid];if(!this.id&&!e)throw new Error("Image ID or queued ID is missing.");var a={values:{caption:this.data.caption}};return this.id?a.values.id=this.id:a.values.queued=e.name,a},i.prototype.sync=function(){return t.__awaiter(this,void 0,void 0,(function(){return t.__generator(this,(function(t){return[2,this.parent?this.parent.sync():a.prototype.sync.call(this)]}))}))},i.prototype.uploadFile=function(){return t.__awaiter(this,arguments,void 0,(function(e){var a,r,i,n,o,d,u,h,c;return void 0===e&&(e=!1),t.__generator(this,(function(t){switch(t.label){case 0:if(this.id)throw new Error("A file of a media on the remote cannot be uploaded again.");return a=Date.now()-432e5,r=this.syncedAt>a&&this.data.queued,!e&&r?[2]:[4,this.getFormData()];case 1:return i=t.sent(),n=new FormData,(h=n).append.apply(h,i),"function"!=typeof this.remote.headers?[3,3]:[4,this.remote.headers()];case 2:return d=t.sent(),[3,4];case 3:d=this.remote.headers,t.label=4;case 4:return o=d,[4,s.default.post("".concat(this.remote.url,"/media-queue"),n,{headers:o,timeout:12e4})];case 5:if(u=t.sent(),!(null===(c=u.data[this.cid])||void 0===c?void 0:c.name))throw new Error("New remote media name was not be found.");return this.data.queued=u.data[this.cid].name,this.syncedAt=(new Date).getTime(),[2]}}))}))},i.prototype.getFormData=function(){return t.__awaiter(this,void 0,void 0,(function(){var e,a,r,i,o,s,d;return t.__generator(this,(function(t){switch(t.label){case 0:return e=this.data.type,a=e,r=e,(null==e?void 0:e.match(/image.*/))?(d=e.split("/"),a=d[1]):r="image/".concat(r),i=this.getURL(),[4,n.getBlobFromURL(i,r)];case 1:return o=t.sent(),[2,[s=this.cid,o,"".concat(s,".").concat(a)]]}}))}))},i.prototype.getRemoteURL=function(){if(!this.remote.url)throw new Error("No remote url was set.");if(!this.data.queued&&!this.data.path)throw new Error("No media queued or path attribute.");var t=this.remote.url.replace("/index.php/services/rest","");return this.data.queued?"".concat(t,"/upload-queue/").concat(this.data.queued):"".concat(t,"/upload/").concat(this.data.path)},i.prototype.getURL=function(){return this.data.data},i.prototype.resize=function(t,e){var a=this,r=this;return new Promise((function(n,o){i.resize(a.getURL(),a.data.type,t,e).then((function(t){var e=t[0],a=t[1];r.data.data=a,n([e,a])})).catch(o)}))},i.prototype.addThumbnail=function(t){var e=this,a=this;return new Promise((function(t,r){/^data:/i.test(e.getURL())?i.resize(e.getURL(),e.data.type,100,100).then((function(e){var r=e[1];a.data.thumbnail=r,t()})).catch(r):i.getDataURI(e.getURL(),{width:100,height:100}).then((function(e){a.data.thumbnail=e[0],t()})).catch(r)}))},Object.defineProperty(i.prototype,"isUploaded",{get:function(){if(!this.parent)throw new Error("No media parent to return disabled status.");return this.parent.isUploaded},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"isDisabled",{get:function(){return this.isUploaded},enumerable:!1,configurable:!0}),i}(i.default);exports.default=u;
@@ -1,5 +1,6 @@
1
1
  import { IObservableArray } from 'mobx';
2
- import Model, { Attrs as AttrsOriginal, Options as OptionsOriginal } from '../Model';
2
+ import Model, { Data as DataOriginal, Options as OptionsOriginal } from '../Model';
3
+ import ElasticOccurrence from './ElasticOccurrence';
3
4
  import Media from './Media';
4
5
  import Sample from './Sample';
5
6
  import { RemoteConfig, Keys } from './helpers';
@@ -9,8 +10,9 @@ export interface Metadata {
9
10
  export interface Options<T = any, S = any> extends OptionsOriginal<T> {
10
11
  metadata?: S;
11
12
  media?: any[];
13
+ Media?: typeof Media<any, any>;
12
14
  }
13
- export interface Attrs extends AttrsOriginal {
15
+ export interface Data extends DataOriginal {
14
16
  training?: boolean;
15
17
  /**
16
18
  * R - released record (default).
@@ -50,8 +52,27 @@ export interface Attrs extends AttrsOriginal {
50
52
  comment?: string;
51
53
  taxon?: any;
52
54
  }
53
- export default class Occurrence<T extends Attrs = Attrs, S extends Metadata = Metadata> extends Model {
54
- static fromJSON(json: any, MediaClass?: any): Occurrence<Attrs, Metadata>;
55
+ export default class Occurrence<T extends Data = Data, S extends Metadata = Metadata> extends Model {
56
+ /**
57
+ * Transform ES document into local structure.
58
+ */
59
+ static parseRemoteJSON({ id, metadata, event, occurrence, taxon }: ElasticOccurrence, remoteUrl: string, survey: any): {
60
+ id: string;
61
+ cid: string;
62
+ createdAt: number;
63
+ updatedAt: number;
64
+ syncedAt: number;
65
+ data: any;
66
+ media: {
67
+ id: string;
68
+ createdAt: number;
69
+ updatedAt: number;
70
+ syncedAt: number;
71
+ data: {
72
+ data: string;
73
+ };
74
+ }[] | undefined;
75
+ };
55
76
  /**
56
77
  * Warehouse attributes and their values.
57
78
  */
@@ -61,27 +82,28 @@ export default class Occurrence<T extends Attrs = Attrs, S extends Metadata = Me
61
82
  };
62
83
  training: {
63
84
  id: string;
64
- values: (val?: boolean | "t" | "f" | null | undefined) => "t" | "f";
85
+ values: (val?: boolean | "t" | "f" | null) => "t" | "f";
65
86
  };
66
87
  deleted: {
67
88
  id: string;
68
- values: (val?: boolean | "t" | "f" | null | undefined) => "t" | "f";
89
+ values: (val?: boolean | "t" | "f" | null) => "t" | "f";
69
90
  };
70
91
  confidential: {
71
92
  id: string;
72
- values: (val?: boolean | "t" | "f" | null | undefined) => "t" | "f";
93
+ values: (val?: boolean | "t" | "f" | null) => "t" | "f";
73
94
  };
74
95
  zeroAbundance: {
75
96
  id: string;
76
- values: (val?: boolean | "t" | "f" | null | undefined) => "t" | "f";
97
+ values: (val?: boolean | "t" | "f" | null) => "t" | "f";
77
98
  };
78
99
  };
100
+ Media: typeof Media<any, any>;
79
101
  metadata: S;
80
- attrs: T;
102
+ data: T;
81
103
  parent?: Sample;
82
104
  media: IObservableArray<Media>;
83
105
  debouncedValue: number;
84
- constructor({ metadata, media, ...options }?: Options);
106
+ constructor({ metadata, media, Media: MediaClass, ...options }?: Options);
85
107
  setUpdatedAtTimestamp(newUpdatedAt: number): void;
86
108
  /**
87
109
  * Save the model to the offline store.
@@ -100,13 +122,13 @@ export default class Occurrence<T extends Attrs = Attrs, S extends Metadata = Me
100
122
  getSurvey(): {
101
123
  attrs?: {
102
124
  [key: string]: {
103
- remote?: RemoteConfig | undefined;
125
+ remote?: RemoteConfig;
104
126
  };
105
- } | undefined;
106
- modifySubmission?: ((submission: any, model: any) => any) | undefined;
127
+ };
128
+ modifySubmission?: (submission: any, model: any) => any;
107
129
  };
108
- isUploaded(): boolean;
109
- isDisabled(): boolean;
130
+ get isUploaded(): boolean;
131
+ get isDisabled(): boolean;
110
132
  /**
111
133
  * Returns an object with attributes and their values
112
134
  * mapped for warehouse submission.
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("tslib"),e=require("mobx"),r=require("lodash"),i=require("../Model.js"),a=require("./Media.js"),n=require("./helpers.js"),o=function(i){function o(r){var a=this;void 0===r&&(r={});var n=r.metadata,s=void 0===n?{}:n,u=r.media,d=void 0===u?[]:u,c=t.__rest(r,["metadata","media"]);(a=i.call(this,c)||this).debouncedValue=300,a.keys=function(){var e;return t.__assign(t.__assign({},o.keys),(e=a.getSurvey().attrs||{},Object.keys(e).reduce((function(r,i){var a;return t.__assign(t.__assign({},r),((a={})[i]=e[i].remote||e[i],a))}),{})))},a.metadata=e.observable(s),a.media=e.observable(d);var l=function(t){return t.parent=a};a.media.forEach(l);return e.intercept(a.media,(function(t){var e;return(null===(e=t.added)||void 0===e?void 0:e.length)?(t.added.forEach(l),a.setUpdatedAtTimestamp(Date.now())):t.removedCount&&a.setUpdatedAtTimestamp(Date.now()),t})),a}return t.__extends(o,i),o.fromJSON=function(e,r){var i,n,o,s;return void 0===r&&(r=a.default),new this(t.__assign(t.__assign({},e),{createdAt:e.createdAt||(null===(i=e.metadata)||void 0===i?void 0:i.createdOn),updatedAt:e.updatedAt||(null===(n=e.metadata)||void 0===n?void 0:n.updatedOn),syncedAt:e.syncedAt||(null===(o=e.metadata)||void 0===o?void 0:o.syncedOn),media:null===(s=e.media)||void 0===s?void 0:s.map((function(t){return r.fromJSON(t)}))}))},o.prototype.setUpdatedAtTimestamp=function(t){var e;i.prototype.setUpdatedAtTimestamp.call(this,t),null===(e=this.parent)||void 0===e||e.setUpdatedAtTimestamp(t)},o.prototype.save=function(){return t.__awaiter(this,void 0,void 0,(function(){return t.__generator(this,(function(t){if(!this.parent)throw new Error("Trying to save locally without a parent");return this.parent.save(),[2]}))}))},o.prototype.destroy=function(e){return t.__awaiter(this,void 0,void 0,(function(){return t.__generator(this,(function(t){switch(t.label){case 0:if(!this.parent)throw new Error("Trying to destroy locally without a parent");return this.parent.occurrences.remove(this),[4,Promise.all(this.media.map((function(t){return t.destroy(!0)})))];case 1:return t.sent(),e?[2]:[4,this.parent.save()];case 2:return t.sent(),[2]}}))}))},o.prototype.sync=function(){return t.__awaiter(this,void 0,void 0,(function(){return t.__generator(this,(function(t){return[2,this.parent?this.parent.sync():i.prototype.sync.call(this)]}))}))},o.prototype.toJSON=function(){var r,a=i.prototype.toJSON.call(this);return JSON.parse(JSON.stringify(t.__assign(t.__assign({},a),{media:(null===(r=this.media)||void 0===r?void 0:r.map((function(t){return t.toJSON()})))||[],metadata:e.toJS(this.metadata)||{}})))},o.prototype.getSurvey=function(){return this.parent&&this.parent.getSurvey().occ||{}},o.prototype.isUploaded=function(){if(!this.parent)throw new Error("No occurrence parent to return disabled status.");return this.parent.isUploaded()},o.prototype.isDisabled=function(){return this.isUploaded()},o.prototype.getSubmission=function(e){var i=this;void 0===e&&(e={});var a="function"==typeof this.keys?this.keys():this.keys,n=t.__assign(t.__assign({},o.keys),a),s={values:{external_key:this.cid},media:[]};this.id&&(s.values.id=this.id);Object.keys(this.attrs).forEach((function(t){var e=i.attrs[t],a=function(t){return null==t};if(!a(e)){if(!n[t])return t=t.includes("occAttr:")?t:r.snakeCase(t),void(s.values[t]=e);var o=n[t].id||t;if(e=function(t,e){var r=n[t].values;if(!r)return e;if("function"==typeof r)return r(e,s,i);if(r instanceof Array){var a=r.find((function(t){return t.value===e}));if(!a||!a.id)throw new Error('A "'.concat(t,'" attribute "').concat(e,'" value could not be mapped to a remote database field.'));return a.id}return e instanceof Array?e.map((function(t){return r[t]})):r[e]}(t,e),!a(e)){var u=Number.isNaN(Number(o))?o:"occAttr:".concat(o);u=u.includes("occAttr:")?u:r.snakeCase(u),s.values[u]=e}}})),this.media.forEach((function(t){var r=t.getSubmission(e);r&&s.media.push(r)}));var u=this.getSurvey();return u.modifySubmission?u.modifySubmission(s,this):s},o.keys={taxon:{id:"taxa_taxon_list_id"},training:{id:"training",values:n.boolToWarehouseValue},deleted:{id:"deleted",values:n.boolToWarehouseValue},confidential:{id:"confidential",values:n.boolToWarehouseValue},zeroAbundance:{id:"zero_abundance",values:n.boolToWarehouseValue}},o}(i.default);exports.default=o;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),a=require("lodash"),n=require("../Model.js"),i=require("./Media.js"),r=require("./helpers.js"),o=function(n){function o(a){void 0===a&&(a={});var r=this,s=a.metadata,d=void 0===s?{}:s,u=a.media,c=void 0===u?[]:u,l=a.Media,p=void 0===l?i.default:l,v=e.__rest(a,["metadata","media","Media"]);v.createdAt=v.createdAt||(null==d?void 0:d.createdOn),v.updatedAt=v.updatedAt||(null==d?void 0:d.updatedOn),v.syncedAt=v.syncedAt||(null==d?void 0:d.syncedOn),(r=n.call(this,v)||this).debouncedValue=300,r.keys=function(){var t;return e.__assign(e.__assign({},o.keys),(t=r.getSurvey().attrs||{},Object.keys(t).reduce((function(a,n){var i;return e.__assign(e.__assign({},a),((i={})[n]=t[n].remote||t[n],i))}),{})))},r.Media=p,r.metadata=t.observable(d);var m,f,_=c.map((m=r.Media,void 0===f&&(f={}),function(t){return t instanceof m?t:new m(e.__assign(e.__assign({},t),f))}));r.media=t.observable(_);var h=function(e){return e.parent=r};r.media.forEach(h);return t.intercept(r.media,(function(e){var t;return(null===(t=e.added)||void 0===t?void 0:t.length)?(e.added.forEach(h),r.setUpdatedAtTimestamp(Date.now())):e.removedCount&&r.setUpdatedAtTimestamp(Date.now()),e})),r}return e.__extends(o,n),o.parseRemoteJSON=function(t,a,n){var i,o,s,d,u,c,l,p=t.id,v=t.metadata,m=t.event,f=t.occurrence,_=t.taxon,h=new Date(v.created_on).getTime(),y=new Date(v.updated_on).getTime(),b=Date.now(),g=m.parent_event_id?null===(o=null===(i=n.smp)||void 0===i?void 0:i.occ)||void 0===o?void 0:o.attrs:null===(s=n.occ)||void 0===s?void 0:s.attrs;g||(g=(null===(u=null===(d=n.smp)||void 0===d?void 0:d.occ)||void 0===u?void 0:u.attrs)||(null===(c=n.occ)||void 0===c?void 0:c.attrs)||{});var A=r.parseRemoteAttrs(g,f.attributes||[]),w=null===(l=f.media)||void 0===l?void 0:l.map((function(e){var t=e.path;return{id:t,createdAt:h,updatedAt:y,syncedAt:b,data:{data:"".concat(a,"/upload/").concat(t)}}})),N=_.species||_.taxon_name,x=N!==_.taxon_name?_.taxon_name:"";return{id:p,cid:p,createdAt:h,updatedAt:y,syncedAt:b,data:e.__assign(e.__assign({},A),{taxon:{warehouse_id:parseInt(_.taxa_taxon_list_id,10),scientific_name:N,scientificName:N,common_name:x,commonName:x,found_in_name:x?"common_name":"scientific_name",foundInName:x?"commonName":"scientificName"},comment:f.occurrence_remarks}),media:w}},o.prototype.setUpdatedAtTimestamp=function(e){var t;n.prototype.setUpdatedAtTimestamp.call(this,e),null===(t=this.parent)||void 0===t||t.setUpdatedAtTimestamp(e)},o.prototype.save=function(){return e.__awaiter(this,void 0,void 0,(function(){return e.__generator(this,(function(e){if(!this.parent)throw new Error("Trying to save locally without a parent");return this.parent.save(),[2]}))}))},o.prototype.destroy=function(t){return e.__awaiter(this,void 0,void 0,(function(){return e.__generator(this,(function(e){switch(e.label){case 0:if(!this.parent)throw new Error("Trying to destroy locally without a parent");return this.parent.occurrences.remove(this),[4,Promise.all(this.media.map((function(e){return e.destroy(!0)})))];case 1:return e.sent(),t?[2]:[4,this.parent.save()];case 2:return e.sent(),[2]}}))}))},o.prototype.sync=function(){return e.__awaiter(this,void 0,void 0,(function(){return e.__generator(this,(function(e){return[2,this.parent?this.parent.sync():n.prototype.sync.call(this)]}))}))},o.prototype.toJSON=function(){var a,i=n.prototype.toJSON.call(this);return JSON.parse(JSON.stringify(e.__assign(e.__assign({},i),{media:(null===(a=this.media)||void 0===a?void 0:a.map((function(e){return e.toJSON()})))||[],metadata:t.toJS(this.metadata)||{}})))},o.prototype.getSurvey=function(){return this.parent&&this.parent.getSurvey().occ||{}},Object.defineProperty(o.prototype,"isUploaded",{get:function(){if(!this.parent)throw new Error("No occurrence parent to return disabled status.");return this.parent.isUploaded},enumerable:!1,configurable:!0}),Object.defineProperty(o.prototype,"isDisabled",{get:function(){return this.isUploaded},enumerable:!1,configurable:!0}),o.prototype.getSubmission=function(t){var n=this;void 0===t&&(t={});var i="function"==typeof this.keys?this.keys():this.keys,r=e.__assign(e.__assign({},o.keys),i),s={values:{external_key:this.cid},media:[]};this.id&&(s.values.id=this.id);Object.keys(this.data).forEach((function(e){var t=n.data[e],i=function(e){return null==e};if(!i(t)){if(!r[e])return e=e.includes("occAttr:")?e:a.snakeCase(e),void(s.values[e]=t);var o=r[e].id||e;if(t=function(e,t){var a=r[e].values;if(!a)return t;if("function"==typeof a)return a(t,s,n);if(a instanceof Array){var i=a.find((function(e){return e.value===t}));if(!i||!i.id)throw new Error('A "'.concat(e,'" attribute "').concat(t,'" value could not be mapped to a remote database field.'));return i.id}return t instanceof Array?t.map((function(e){return a[e]})):a[t]}(e,t),!i(t)){var d=Number.isNaN(Number(o))?o:"occAttr:".concat(o);d=d.includes("occAttr:")?d:a.snakeCase(d),s.values[d]=t}}})),this.media.forEach((function(e){var a=e.getSubmission(t);a&&s.media.push(a)}));var d=this.getSurvey();return d.modifySubmission?d.modifySubmission(s,this):s},o.keys={taxon:{id:"taxa_taxon_list_id"},training:{id:"training",values:r.boolToWarehouseValue},deleted:{id:"deleted",values:r.boolToWarehouseValue},confidential:{id:"confidential",values:r.boolToWarehouseValue},zeroAbundance:{id:"zero_abundance",values:r.boolToWarehouseValue}},o}(n.default);exports.default=o;
@@ -1,5 +1,6 @@
1
1
  import { IObservableArray } from 'mobx';
2
- import Model, { Attrs as AttrsOriginal, Options as OptionsOriginal } from '../Model';
2
+ import Model, { Data as DataOriginal, Options as OptionsOriginal } from '../Model';
3
+ import ElasticSample from './ElasticSample';
3
4
  import Media from './Media';
4
5
  import Occurrence from './Occurrence';
5
6
  import { RemoteConfig, Keys } from './helpers';
@@ -17,8 +18,16 @@ export interface Options<T = any, S = any> extends OptionsOriginal<T> {
17
18
  occurrences?: any[];
18
19
  samples?: any[];
19
20
  media?: any[];
21
+ Sample?: typeof Sample<any, any>;
22
+ Occurrence?: typeof Occurrence<any, any>;
23
+ Media?: typeof Media<any, any>;
24
+ skipStore?: boolean;
20
25
  }
21
- export interface Attrs extends AttrsOriginal {
26
+ export interface Data extends DataOriginal {
27
+ /**
28
+ * Flag whether the Sample was deleted. Global and persistent models might not need this.
29
+ */
30
+ deleted?: boolean;
22
31
  surveyId?: string | number | null;
23
32
  /**
24
33
  * Remote website survey edit page path.
@@ -39,7 +48,7 @@ export interface Attrs extends AttrsOriginal {
39
48
  export interface Remote {
40
49
  synchronising?: boolean;
41
50
  url?: string | null;
42
- headers?: any;
51
+ getAccessToken: () => Promise<string>;
43
52
  timeout?: number;
44
53
  /**
45
54
  * @deprecated
@@ -62,9 +71,32 @@ export interface Survey extends BaseSurvey {
62
71
  smp?: Survey;
63
72
  occ?: BaseSurvey;
64
73
  }
65
- declare class Sample<T extends Attrs = Attrs, S extends Metadata = Metadata> extends Model<T> {
66
- static fromJSON(jsonProp: any, OccurrenceClass?: any, Sample?: any, // eslint-disable-line
67
- MediaClass?: any): Sample<Attrs, Metadata>;
74
+ declare class Sample<T extends Data = Data, S extends Metadata = Metadata> extends Model<T> {
75
+ /**
76
+ * Transform ES document into local structure.
77
+ */
78
+ static parseRemoteJSON({ id, event, location, metadata }: ElasticSample, remoteUrl: string, survey?: any): {
79
+ id: string;
80
+ cid: string;
81
+ createdAt: number;
82
+ updatedAt: number;
83
+ syncedAt: number;
84
+ metadata: {
85
+ saved: boolean;
86
+ };
87
+ data: any;
88
+ media: {
89
+ id: string;
90
+ metadata: {
91
+ updatedOn: Date;
92
+ createdOn: Date;
93
+ syncedOn: Date;
94
+ };
95
+ data: {
96
+ data: string;
97
+ };
98
+ }[] | undefined;
99
+ };
68
100
  /**
69
101
  * Warehouse attributes and their values.
70
102
  */
@@ -86,13 +118,16 @@ declare class Sample<T extends Attrs = Attrs, S extends Metadata = Metadata> ext
86
118
  };
87
119
  training: {
88
120
  id: string;
89
- values: (val?: boolean | "t" | "f" | null | undefined) => "t" | "f";
121
+ values: (val?: boolean | "t" | "f" | null) => "t" | "f";
90
122
  };
91
123
  deleted: {
92
124
  id: string;
93
- values: (val?: boolean | "t" | "f" | null | undefined) => "t" | "f";
125
+ values: (val?: boolean | "t" | "f" | null) => "t" | "f";
94
126
  };
95
127
  };
128
+ Sample: typeof Sample<any, any>;
129
+ Occurrence: typeof Occurrence<any, any>;
130
+ Media: typeof Media<any, any>;
96
131
  /**
97
132
  * Model persistent observable metadata.
98
133
  */
@@ -107,10 +142,18 @@ declare class Sample<T extends Attrs = Attrs, S extends Metadata = Metadata> ext
107
142
  occurrences: IObservableArray<Occurrence>;
108
143
  media: IObservableArray<Media>;
109
144
  parent?: Sample<T, S>;
110
- survey?: Survey;
145
+ private survey?;
111
146
  debouncedValue: number;
112
- constructor({ metadata, samples, occurrences, media, attrs, ...options }?: Options);
113
- setupdatedAtTimestamp(newUpdatedAt: number): void;
147
+ constructor({ metadata, samples, occurrences, media, Sample: SampleClass, Occurrence: OccurrenceClass, Media: MediaClass, skipStore, ...options }?: Options);
148
+ get isStored(): import("..").IStore<{
149
+ id?: string;
150
+ cid: string;
151
+ data: T;
152
+ createdAt: number;
153
+ updatedAt: number;
154
+ syncedAt?: number | null;
155
+ }> | undefined;
156
+ setUpdatedAtTimestamp(newUpdatedAt: number): void;
114
157
  /**
115
158
  * Returns a clean (no observables) JSON representation of the model.
116
159
  */
@@ -134,7 +177,7 @@ declare class Sample<T extends Attrs = Attrs, S extends Metadata = Metadata> ext
134
177
  private putRemote;
135
178
  private uploadMedia;
136
179
  getSubmission(warehouseMediaNames?: {}): any;
137
- isUploaded(): boolean;
138
- isDisabled(): boolean;
180
+ get isUploaded(): boolean;
181
+ get isDisabled(): boolean;
139
182
  }
140
183
  export default Sample;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),r=require("axios"),s=require("lodash"),n=require("@flumens/utils/dist/errors"),a=require("../Model.js"),i=require("./Media.js"),o=require("./Occurrence.js"),u=require("./helpers.js");function c(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var d=c(r);function l(e,t){var r,s,n,a;if(null==t?void 0:t.values)e.id=t.values.id,e.samples&&t.samples&&(null===(s=e.samples)||void 0===s||s.forEach((function(e,r){return l(e,t.samples[r])}))),e.occurrences&&t.occurrences&&(null===(n=e.occurrences)||void 0===n||n.forEach((function(e,r){return l(e,t.occurrences[r])}))),e.media&&t.media&&(null===(a=e.media)||void 0===a||a.forEach((function(e,r){return l(e,t.media[r])})));else{if("test"===(null===(r=null===process||void 0===process?void 0:process.env)||void 0===r?void 0:r.NODE_ENV))return;console.warn("Model didn't receive an id from the server")}}var h=function(t){return e.__awaiter(void 0,void 0,void 0,(function(){var r,s,n;return e.__generator(this,(function(a){switch(a.label){case 0:return r=[],t.media?(s=function(t){return e.__awaiter(void 0,void 0,void 0,(function(){var r;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,t.getFormData()];case 1:return r=e.sent(),[2,[t,r]]}}))}))},[4,Promise.all(t.media.map(s))]):[3,2];case 1:n=a.sent(),r.push.apply(r,n),a.label=2;case 2:return t.occurrences?[4,Promise.all(t.occurrences.map(h))]:[3,4];case 3:n=a.sent(),r.push.apply(r,n.flat()),a.label=4;case 4:return t.samples?[4,Promise.all(t.samples.map(h))]:[3,6];case 5:n=a.sent(),r.push.apply(r,n.flat()),a.label=6;case 6:return[2,r]}}))}))};function m(e,t){var r={values:{id:t||-1}};return e.occurrences&&(r.occurrences=e.occurrences.map((function(e){return m(e)}))),e.samples&&(r.samples=e.samples.map((function(e){return m(e)}))),e.media&&(r.media=e.media.map((function(e){return m(e)}))),r}function p(e){try{console.warn(JSON.stringify(e).substring(0,1e5))}catch(e){}}var f=function(r){function a(s){var n=this;void 0===s&&(s={});var i=s.metadata,o=void 0===i?{}:i,c=s.samples,d=void 0===c?[]:c,l=s.occurrences,h=void 0===l?[]:l,m=s.media,p=void 0===m?[]:m,f=s.attrs,v=void 0===f?{}:f,_=e.__rest(s,["metadata","samples","occurrences","media","attrs"]);(n=r.call(this,e.__assign(e.__assign({},_),{attrs:e.__assign({},v)}))||this).remote=t.observable({synchronising:!1,url:null,headers:{},timeout:12e4}),n.validateRemote=u.validateRemoteModel,n.error=t.observable({message:""}),n.debouncedValue=300,n.keys=function(){return e.__assign(e.__assign({},a.keys),function(t){return Object.keys(t).reduce((function(r,s){var n;return e.__assign(e.__assign({},r),((n={})[s]=t[s].remote||t[s],n))}),{})}(n.getSurvey().attrs||{}))},n.requiresRemoteSync=function(){return!n.syncedAt||n.updatedAt>n.syncedAt},n.metadata=t.observable(o),n.samples=t.observable(d),n.occurrences=t.observable(h),n.media=t.observable(p);var y=function(e){return e.parent=n};n.samples.forEach(y),n.occurrences.forEach(y),n.media.forEach(y);var g=function(e){var t;return(null===(t=e.added)||void 0===t?void 0:t.length)?(e.added.forEach(y),n.setupdatedAtTimestamp(Date.now())):e.removedCount&&n.setupdatedAtTimestamp(Date.now()),e};return t.intercept(n.samples,g),t.intercept(n.occurrences,g),t.intercept(n.media,g),n}return e.__extends(a,r),a.fromJSON=function(t,r,s,n){var a,u,c,d,l,h,m;void 0===r&&(r=o.default),void 0===s&&(s=this),void 0===n&&(n=i.default);var p=(null===(a=null==t?void 0:t.attrs)||void 0===a?void 0:a.attrs)?null==t?void 0:t.attrs:t;return new this(e.__assign(e.__assign({},t),{attrs:p.attrs,metadata:p.metadata,createdAt:t.createdAt||(null===(u=t.metadata)||void 0===u?void 0:u.createdOn),updatedAt:t.updatedAt||(null===(c=t.metadata)||void 0===c?void 0:c.updatedOn),syncedAt:t.syncedAt||(null===(d=t.metadata)||void 0===d?void 0:d.syncedOn),samples:null===(l=p.samples)||void 0===l?void 0:l.map((function(e){return s.fromJSON(e,r,s,n)})),occurrences:null===(h=p.occurrences)||void 0===h?void 0:h.map((function(e){return r.fromJSON(e,n)})),media:null===(m=p.media)||void 0===m?void 0:m.map((function(e){return n.fromJSON(e)}))}))},a.prototype.setupdatedAtTimestamp=function(e){var t;r.prototype.setUpdatedAtTimestamp.call(this,e),null===(t=this.parent)||void 0===t||t.setupdatedAtTimestamp(e)},a.prototype.toJSON=function(){var s,n,a,i,o=r.prototype.toJSON.call(this);return this.parent?JSON.parse(JSON.stringify(e.__assign(e.__assign({},o),{metadata:t.toJS(this.metadata)||{},occurrences:this.occurrences.map((function(e){return e.toJSON()}))||[],samples:(null===(a=this.samples)||void 0===a?void 0:a.map((function(e){return e.toJSON()})))||[],media:(null===(i=this.media)||void 0===i?void 0:i.map((function(e){return e.toJSON()})))||[]}))):JSON.parse(JSON.stringify(e.__assign(e.__assign({},o),{attrs:{attrs:o.attrs,metadata:t.toJS(this.metadata)||{},occurrences:this.occurrences.map((function(e){return e.toJSON()}))||[],samples:(null===(s=this.samples)||void 0===s?void 0:s.map((function(e){return e.toJSON()})))||[],media:(null===(n=this.media)||void 0===n?void 0:n.map((function(e){return e.toJSON()})))||[]}})))},a.prototype.getSurvey=function(){return this.survey?this.parent?this.parent.getSurvey().smp||{}:this.survey:{}},a.prototype.save=function(){return e.__awaiter(this,void 0,void 0,(function(){var t;return e.__generator(this,(function(r){switch(r.label){case 0:if(this.attrs.deleted)return[2];if(this.parent)return this.parent.save(),[2];if(!this.store)throw new Error("Trying to sync locally without a store");return t=this.toJSON(),[4,this.store.save(e.__assign(e.__assign({},t),{data:t.attrs}))];case 1:return r.sent(),[2]}}))}))},a.prototype.destroy=function(t){var r;return e.__awaiter(this,void 0,void 0,(function(){var s,n=this;return e.__generator(this,(function(e){switch(e.label){case 0:return s=function(){return Promise.all([Promise.all(n.media.map((function(e){return e.destroy(!0)}))),Promise.all(n.occurrences.map((function(e){return e.destroy(!0)})))])},this.parent?(this.parent.samples.remove(this),[4,s()]):[3,2];case 1:return e.sent(),t?[2]:(this.parent.save(),[2]);case 2:if(!this.store)throw new Error("Trying to sync locally without a store");return[4,this.store.delete(this.cid)];case 3:return e.sent(),null===(r=this.collection)||void 0===r||r.remove(this),[4,s()];case 4:return e.sent(),this.attrs.deleted=!0,[2]}}))}))},a.prototype.sync=function(){return e.__awaiter(this,void 0,void 0,(function(){return e.__generator(this,(function(e){return[2,this.parent?this.parent.sync():r.prototype.sync.call(this)]}))}))},a.prototype.saveRemote=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r,s,n,a;return e.__generator(this,(function(e){switch(e.label){case 0:if(!this.remote.url)throw new Error('A "remote" property is not configured.');e.label=1;case 1:return e.trys.push([1,4,,5]),this.remote.synchronising=!0,[4,this.uploadMedia()];case 2:return t=e.sent(),r=this.getSubmission(t),[4,this.postRemote(r)];case 3:return s=e.sent(),this.remote.synchronising=!1,l(this,s),n=(new Date).getTime(),this.updatedAt=n,this.syncedAt=n,this.save(),[3,5];case 4:throw a=e.sent(),this.remote.synchronising=!1,a;case 5:return[2]}}))}))},a.prototype.postRemote=function(t){var r,s,a;return e.__awaiter(this,void 0,void 0,(function(){var i,o,c,l,h;return e.__generator(this,(function(e){switch(e.label){case 0:return i=this.remote.url,"function"!=typeof this.remote.headers?[3,2]:[4,this.remote.headers()];case 1:return c=e.sent(),[3,3];case 2:c=this.remote.headers,e.label=3;case 3:o=c,e.label=4;case 4:return e.trys.push([4,6,,7]),[4,d.default.post("".concat(i,"/samples"),t,{headers:o,timeout:12e4})];case 5:return[2,e.sent().data];case 6:if(l=e.sent(),409===(h=l).status&&(null===(r=h.response)||void 0===r?void 0:r.data.duplicate_of))return[2,m(this,h.response.data.duplicate_of.id)];if(n.isAxiosNetworkError(h))throw new n.HandledError("Request aborted because of a network issue (timeout or similar).");if(400===h.status)throw p(t),new Error(u.getErrorMessageFromObject(null===(a=null===(s=h.response)||void 0===s?void 0:s.data)||void 0===a?void 0:a.message));throw new Error(h.message);case 7:return[2]}}))}))},a.prototype.fetchRemote=function(){return e.__awaiter(this,void 0,void 0,(function(){return e.__generator(this,(function(e){throw new Error("Not implemented.")}))}))},a.prototype.updateRemote=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r,s,n;return e.__generator(this,(function(e){switch(e.label){case 0:if(!this.remote.url)throw new Error('A "remote" property is not configured.');e.label=1;case 1:return e.trys.push([1,3,,4]),this.remote.synchronising=!0,t={},r=this.getSubmission(t),[4,this.putRemote(this.id,r)];case 2:return l(this,e.sent()),s=(new Date).getTime(),this.updatedAt=s,this.syncedAt=s,this.save(),this.remote.synchronising=!1,[3,4];case 3:throw n=e.sent(),this.remote.synchronising=!1,n;case 4:return[2]}}))}))},a.prototype.putRemote=function(t,r){var s,a;return e.__awaiter(this,void 0,void 0,(function(){var i,o,c,l,h;return e.__generator(this,(function(e){switch(e.label){case 0:return i=this.remote.url,"function"!=typeof this.remote.headers?[3,2]:[4,this.remote.headers()];case 1:return c=e.sent(),[3,3];case 2:c=this.remote.headers,e.label=3;case 3:o=c,e.label=4;case 4:return e.trys.push([4,6,,7]),[4,d.default.put("".concat(i,"/samples/").concat(t),r,{headers:o,timeout:12e4})];case 5:return[2,e.sent().data];case 6:if(l=e.sent(),h=l,n.isAxiosNetworkError(h))throw new n.HandledError("Request aborted because of a network issue (timeout or similar).");if(400===h.status)throw p(r),new Error(u.getErrorMessageFromObject(null===(a=null===(s=h.response)||void 0===s?void 0:s.data)||void 0===a?void 0:a.message));throw new Error(h.message);case 7:return[2]}}))}))},a.prototype.uploadMedia=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r,s,a,i,o,u,c,l=this;return e.__generator(this,(function(m){switch(m.label){case 0:return t={},[4,h(this)];case 1:if(r=m.sent(),!r.length)return[2,t];s=function(t){return e.__awaiter(l,void 0,void 0,(function(){var r,s,a,i;return e.__generator(this,(function(e){switch(e.label){case 0:return r=this.remote.url,"function"!=typeof this.remote.headers?[3,2]:[4,this.remote.headers()];case 1:return a=e.sent(),[3,3];case 2:a=this.remote.headers,e.label=3;case 3:s=a,e.label=4;case 4:return e.trys.push([4,6,,7]),[4,d.default.post("".concat(r,"/media-queue"),t,{headers:s,timeout:12e4})];case 5:return[2,e.sent().data];case 6:if("timeout"===(i=e.sent()).message)throw new n.HandledError("Request aborted because of a network issue (timeout or similar).");throw i;case 7:return[2]}}))}))},a=[],i=Date.now()-432e5,r.forEach((function(e){var r=e[0];r.syncedAt>i&&r.attrs.queued?t[r.cid]={name:r.attrs.queued}:a.push(e)})),o=5,u=function(r){var n,i,u,c;return e.__generator(this,(function(d){switch(d.label){case 0:return n=a.slice(r,r+o),i=new FormData,n.forEach((function(e){var t=e[1];return i.append.apply(i,t)})),[4,s(i)];case 1:return u=d.sent(),c=(new Date).getTime(),n.forEach((function(e){var t=e[0];t.syncedAt=c,t.attrs.queued=u[t.cid].name})),t=e.__assign(e.__assign({},t),u),[2]}}))},c=0,m.label=2;case 2:return c<a.length?[5,u(c)]:[3,5];case 3:m.sent(),m.label=4;case 4:return c+=o,[3,2];case 5:return[2,t]}}))}))},a.prototype.getSubmission=function(t){var r=this;void 0===t&&(t={});var n="function"==typeof this.keys?this.keys():this.keys,i=e.__assign(e.__assign({},a.keys),n),o={values:{external_key:this.cid},media:[],samples:[],occurrences:[]};this.id&&(o.values.id=this.id);var u=function(e,t){var s=i[e].values;if(!s)return t;if("function"==typeof s)return s(t,o,r);if(t instanceof Array)return t.map((function(t){return u(e,t)}));if(s instanceof Array){var n=s.find((function(e){return e.value===t}));if(!n||!n.id)throw new Error('A "'.concat(e,'" attribute "').concat(t,'" value could not be mapped to a remote database field.'));return n.id}return s[t]};Object.keys(this.attrs).forEach((function(e){var t=r.attrs[e],n=function(e){return null==e};if(!n(t)){if(!i[e])return e=e.includes("smpAttr:")?e:s.snakeCase(e),void(o.values[e]=t);if(!n(t=u(e,t))){var a=i[e].id||e,c=Number.isNaN(Number(a))?a:"smpAttr:".concat(a);c=c.includes("smpAttr:")?c:s.snakeCase(c),o.values[c]=t}}})),this.samples.forEach((function(e){r.attrs.training&&(e.attrs.training=r.attrs.training);var s=e.getSubmission(t);s&&o.samples.push(s)})),this.occurrences.forEach((function(e){r.attrs.training&&(e.attrs.training=r.attrs.training);var s=e.getSubmission(t);s&&o.occurrences.push(s)})),this.media.forEach((function(e){var r=e.getSubmission(t);r&&o.media.push(r)}));var c=this.getSurvey();return c.modifySubmission?c.modifySubmission(o,this):o},a.prototype.isUploaded=function(){return this.parent?this.parent.isUploaded():!!this.syncedAt},a.prototype.isDisabled=function(){return this.isUploaded()},a.keys={location:{id:"entered_sref"},location_type:{id:"entered_sref_system",values:{british:"OSGB",irish:"OSIE",channel:"utm30ed50",latlon:4326}},group:{id:"group_id"},training:{id:"training",values:u.boolToWarehouseValue},deleted:{id:"deleted",values:u.boolToWarehouseValue}},a}(a.default);exports.default=f,exports.getMediaFormData=h;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),r=require("axios"),s=require("lodash"),a=require("wellknown"),n=require("@flumens/utils"),i=require("../Model.js"),o=require("./ElasticOccurrence.js"),u=require("./ElasticSample.js"),c=require("./Media.js"),d=require("./Occurrence.js"),l=require("./helpers.js");function p(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var m=p(r),h=p(a),f=function(t,r){return void 0===r&&(r={}),function(s){return s instanceof t?s:new t(e.__assign(e.__assign({},s),r))}};function v(e,t){var r,s,a,n;if(null==t?void 0:t.values)e.id=t.values.id,e.samples&&t.samples&&(null===(s=e.samples)||void 0===s||s.forEach((function(e,r){return v(e,t.samples[r])}))),e.occurrences&&t.occurrences&&(null===(a=e.occurrences)||void 0===a||a.forEach((function(e,r){return v(e,t.occurrences[r])}))),e.media&&t.media&&(null===(n=e.media)||void 0===n||n.forEach((function(e,r){return v(e,t.media[r])})));else{if("test"===(null===(r=null===process||void 0===process?void 0:process.env)||void 0===r?void 0:r.NODE_ENV))return;console.warn("Model didn't receive an id from the server")}}var _=function(t){return e.__awaiter(void 0,void 0,void 0,(function(){var r,s,a;return e.__generator(this,(function(n){switch(n.label){case 0:return r=[],t.media?(s=function(t){return e.__awaiter(void 0,void 0,void 0,(function(){var r;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,t.getFormData()];case 1:return r=e.sent(),[2,[t,r]]}}))}))},[4,Promise.all(t.media.map(s))]):[3,2];case 1:a=n.sent(),r.push.apply(r,a),n.label=2;case 2:return t.occurrences?[4,Promise.all(t.occurrences.map(_))]:[3,4];case 3:a=n.sent(),r.push.apply(r,a.flat()),n.label=4;case 4:return t.samples?[4,Promise.all(t.samples.map(_))]:[3,6];case 5:a=n.sent(),r.push.apply(r,a.flat()),n.label=6;case 6:return[2,r]}}))}))};function g(e,t){var r={values:{id:t||-1}};return e.occurrences&&(r.occurrences=e.occurrences.map((function(e){return g(e)}))),e.samples&&(r.samples=e.samples.map((function(e){return g(e)}))),e.media&&(r.media=e.media.map((function(e){return g(e)}))),r}function y(e){try{console.warn(JSON.stringify(e).substring(0,1e5))}catch(e){}}var b=function(r){function a(s){void 0===s&&(s={});var n=this,i=s.metadata,o=void 0===i?{}:i,u=s.samples,p=void 0===u?[]:u,m=s.occurrences,h=void 0===m?[]:m,v=s.media,_=void 0===v?[]:v,g=s.Sample,y=void 0===g?a:g,b=s.Occurrence,w=void 0===b?d.default:b,S=s.Media,A=void 0===S?c.default:S,O=s.skipStore,E=e.__rest(s,["metadata","samples","occurrences","media","Sample","Occurrence","Media","skipStore"]);E.createdAt=E.createdAt||(null==o?void 0:o.createdOn),E.updatedAt=E.updatedAt||(null==o?void 0:o.updatedOn),E.syncedAt=E.syncedAt||(null==o?void 0:o.syncedOn);var k=O?void 0:E.store;(n=r.call(this,e.__assign(e.__assign({},E),{store:k}))||this).remote=t.observable({synchronising:!1,url:null,getAccessToken:function(){return Promise.resolve("auth token is missing")},timeout:12e4}),n.validateRemote=l.validateRemoteModel,n.error=t.observable({message:""}),n.debouncedValue=300,n.keys=function(){var t;return e.__assign(e.__assign({},a.keys),(t=n.getSurvey().attrs||{},Object.keys(t).reduce((function(r,s){var a;return e.__assign(e.__assign({},r),((a={})[s]=t[s].remote||t[s],a))}),{})))},n.requiresRemoteSync=function(){return!n.syncedAt||n.updatedAt>n.syncedAt},n.Sample=y,n.Occurrence=w,n.Media=A,n.metadata=t.observable(o);var T=p.map(f(n.Sample));n.samples=t.observable(T);var N=h.map(f(n.Occurrence,{Media:n.Media}));n.occurrences=t.observable(N);var q=_.map(f(n.Media));n.media=t.observable(q);var R=function(e){return e.parent=n};n.samples.forEach(R),n.occurrences.forEach(R),n.media.forEach(R);var j=function(e){var t;return(null===(t=e.added)||void 0===t?void 0:t.length)?(e.added.forEach(R),n.setUpdatedAtTimestamp(Date.now())):e.removedCount&&n.setUpdatedAtTimestamp(Date.now()),e};return t.intercept(n.samples,j),t.intercept(n.occurrences,j),t.intercept(n.media,j),n}return e.__extends(a,r),a.parseRemoteJSON=function(t,r,s){var a,n=t.id,i=t.event,o=t.location,u=t.metadata,c=new Date(i.date_start),d=new Date(u.updated_on).getTime(),p=Date.now(),m=o.point.split(",").map(parseFloat),f=m[0],v=m[1],_="OSGB"===o.output_sref_system?o.output_sref:"",g=o.geom?h.default.parse(o.geom):null,y=i.parent_event_id,b=l.parseRemoteAttrs(y?null==s?void 0:s.smp.attrs:null==s?void 0:s.attrs,i.attributes||[]),w=null===(a=i.media)||void 0===a?void 0:a.map((function(e){var t=e.path;return{id:t,metadata:{updatedOn:c,createdOn:c,syncedOn:c},data:{data:"".concat(r,"/upload/").concat(t)}}}));return{id:n,cid:i.source_system_key||n,createdAt:c.getTime(),updatedAt:d,syncedAt:p,metadata:{saved:!0},data:e.__assign(e.__assign({},b),{surveyId:u.survey.id,date:c.toISOString(),location:{code:o.code,name:o.name||o.verbatim_locality,latitude:f,longitude:v,shape:g,gridref:_},enteredSrefSystem:4326,group:u.group,comment:i.event_remarks,training:"true"===u.trial}),media:w}},Object.defineProperty(a.prototype,"isStored",{get:function(){return this.store},enumerable:!1,configurable:!0}),a.prototype.setUpdatedAtTimestamp=function(e){var t;r.prototype.setUpdatedAtTimestamp.call(this,e),null===(t=this.parent)||void 0===t||t.setUpdatedAtTimestamp(e)},a.prototype.toJSON=function(){var s,a,n,i=r.prototype.toJSON.call(this);return n=e.__assign(e.__assign({},i),{metadata:t.toJS(this.metadata)||{},occurrences:this.occurrences.map((function(e){return e.toJSON()}))||[],samples:(null===(s=this.samples)||void 0===s?void 0:s.map((function(e){return e.toJSON()})))||[],media:(null===(a=this.media)||void 0===a?void 0:a.map((function(e){return e.toJSON()})))||[]}),JSON.parse(JSON.stringify(n))},a.prototype.getSurvey=function(){return this.survey?this.parent?this.parent.getSurvey().smp||{}:this.survey:{}},a.prototype.save=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r,s,a,n,i,o,u;return e.__generator(this,(function(c){switch(c.label){case 0:if(this.data.deleted)return[2];if(this.parent)return this.parent.save(),[2];if(!this.store)throw new Error("Trying to sync locally without a store");return t=this.toJSON(),r=t.data,s=t.metadata,a=t.occurrences,n=t.samples,i=t.media,o=e.__rest(t,["data","metadata","occurrences","samples","media"]),u=e.__assign(e.__assign({},o),{data:{data:r,metadata:s,occurrences:a,samples:n,media:i}}),[4,this.store.save(u)];case 1:return c.sent(),[2]}}))}))},a.prototype.destroy=function(t){return e.__awaiter(this,void 0,void 0,(function(){var r,s,a=this;return e.__generator(this,(function(e){switch(e.label){case 0:return r=function(){return Promise.all([Promise.all(a.media.map((function(e){return e.destroy(!0)}))),Promise.all(a.occurrences.map((function(e){return e.destroy(!0)})))])},this.parent?(this.parent.samples.remove(this),[4,r()]):[3,2];case 1:return e.sent(),t?[2]:(this.parent.save(),[2]);case 2:if(!this.store)throw new Error("Trying to sync locally without a store");return[4,this.store.delete(this.cid)];case 3:return e.sent(),null===(s=this.collection)||void 0===s||s.remove(this),[4,r()];case 4:return e.sent(),this.data.deleted=!0,[2]}}))}))},a.prototype.sync=function(){return e.__awaiter(this,void 0,void 0,(function(){return e.__generator(this,(function(e){return[2,this.parent?this.parent.sync():r.prototype.sync.call(this)]}))}))},a.prototype.saveRemote=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r,s,a,n;return e.__generator(this,(function(e){switch(e.label){case 0:if(!this.remote.url||this.remote.url.includes("index.php"))throw new Error('A "remote" property is not configured.');e.label=1;case 1:return e.trys.push([1,4,,5]),this.remote.synchronising=!0,[4,this.uploadMedia()];case 2:return t=e.sent(),r=this.getSubmission(t),[4,this.postRemote(r)];case 3:return s=e.sent(),this.remote.synchronising=!1,v(this,s),a=(new Date).getTime(),this.updatedAt=a,this.syncedAt=a,this.save(),[3,5];case 4:throw n=e.sent(),this.remote.synchronising=!1,n;case 5:return[2]}}))}))},a.prototype.postRemote=function(t){return e.__awaiter(this,void 0,void 0,(function(){var r,s,a,i,o,u,c,d;return e.__generator(this,(function(e){switch(e.label){case 0:return e.trys.push([0,3,,4]),o={},s="Bearer ".concat,[4,this.remote.getAccessToken()];case 1:return o.Authorization=s.apply("Bearer ",[e.sent()]),r=o,[4,m.default.post("".concat(this.remote.url,"/index.php/services/rest/samples"),t,{headers:r,timeout:12e4})];case 2:return[2,e.sent().data];case 3:if(a=e.sent(),409===(i=a).status&&(null===(u=i.response)||void 0===u?void 0:u.data.duplicate_of))return[2,g(this,i.response.data.duplicate_of.id)];if(n.isAxiosNetworkError(i))throw new n.HandledError("Request aborted because of a network issue (timeout or similar).");if(400===i.status)throw y(t),new Error(l.getErrorMessageFromObject(null===(d=null===(c=i.response)||void 0===c?void 0:c.data)||void 0===d?void 0:d.message));throw new Error(i.message);case 4:return[2]}}))}))},a.prototype.fetchRemote=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r,s,a,n,i,c,d,l,p,m,h,f,v,_,g,y,b,w,S,A=this;return e.__generator(this,(function(O){switch(O.label){case 0:if(!this.remote.url||this.remote.url.includes("index.php"))throw new Error('A "remote" property is not configured.');if(!this.cid)throw new Error("Sample cid or id is missing for fetching remote model.");return t=this.remote.url,[4,this.remote.getAccessToken()];case 1:return r=O.sent(),[4,u.fetchElasticSample({id:this.id,cid:this.cid,url:t,accessToken:r})];case 2:return s=O.sent(),this.data.surveyId||(this.data.surveyId=s.metadata.survey.id),a=this.getSurvey(),n=this.Sample.parseRemoteJSON(s,this.remote.url,a),this.id=n.id,this.cid=n.cid||this.cid,Object.assign(this.data,n.data),Object.assign(this.metadata,n.metadata),i=u.fetchElasticSubSamples({parentId:this.id,url:t,accessToken:r}),c=o.fetchElasticOccurrences({parentId:this.id,url:t,accessToken:r}),[4,Promise.all([i,c])];case 3:return d=O.sent(),l=d[0],p=d[1],m=(new Date).getTime(),h=function(e){var t=A.Sample.parseRemoteJSON(e,A.remote.url,A.getSurvey()),r=new A.Sample(t);return r.syncedAt=m,r},f=l.map(h),v=function(t,r){var s;return e.__assign(e.__assign({},t),((s={})[r.id]=r,s))},_=f.reduce(v,((w={})[this.id]=this,w)),this.samples.clear(),(S=this.samples).push.apply(S,f),g=function(e){var t=A.Occurrence.parseRemoteJSON(e,A.remote.url,A.getSurvey()),r=new A.Occurrence(t);return r.syncedAt=m,[r,e.event.event_id]},y=p.map(g),b=function(e){var t=e[0],r=e[1];r!==parseInt(A.id,10)?_[r]?_[r].occurrences.push(t):console.error("Can't attach occ to missing ".concat(r," sample")):A.occurrences.push(t)},y.forEach(b),this.syncedAt=m,[2]}}))}))},a.prototype.updateRemote=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r,s,a;return e.__generator(this,(function(e){switch(e.label){case 0:if(!this.remote.url||this.remote.url.includes("index.php"))throw new Error('A "remote" property is not configured.');e.label=1;case 1:return e.trys.push([1,3,,4]),this.remote.synchronising=!0,t={},r=this.getSubmission(t),[4,this.putRemote(this.id,r)];case 2:return v(this,e.sent()),s=(new Date).getTime(),this.updatedAt=s,this.syncedAt=s,this.save(),this.remote.synchronising=!1,[3,4];case 3:throw a=e.sent(),this.remote.synchronising=!1,a;case 4:return[2]}}))}))},a.prototype.putRemote=function(t,r){return e.__awaiter(this,void 0,void 0,(function(){var s,a,i,o,u,c,d;return e.__generator(this,(function(e){switch(e.label){case 0:return u={},a="Bearer ".concat,[4,this.remote.getAccessToken()];case 1:u.Authorization=a.apply("Bearer ",[e.sent()]),s=u,e.label=2;case 2:return e.trys.push([2,4,,5]),[4,m.default.put("".concat(this.remote.url,"/samples/").concat(t),r,{headers:s,timeout:12e4})];case 3:return[2,e.sent().data];case 4:if(i=e.sent(),o=i,n.isAxiosNetworkError(o))throw new n.HandledError("Request aborted because of a network issue (timeout or similar).");if(400===o.status)throw y(r),new Error(l.getErrorMessageFromObject(null===(d=null===(c=o.response)||void 0===c?void 0:c.data)||void 0===d?void 0:d.message));throw new Error(o.message);case 5:return[2]}}))}))},a.prototype.uploadMedia=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r,s,a,i,o,u,c,d=this;return e.__generator(this,(function(l){switch(l.label){case 0:return t={},[4,_(this)];case 1:if(r=l.sent(),!r.length)return[2,t];s=function(t){return e.__awaiter(d,void 0,void 0,(function(){var r,s,a,i;return e.__generator(this,(function(e){switch(e.label){case 0:return i={},s="Bearer ".concat,[4,this.remote.getAccessToken()];case 1:i.Authorization=s.apply("Bearer ",[e.sent()]),r=i,e.label=2;case 2:return e.trys.push([2,4,,5]),[4,m.default.post("".concat(this.remote.url,"/media-queue"),t,{headers:r,timeout:12e4})];case 3:return[2,e.sent().data];case 4:if("timeout"===(a=e.sent()).message)throw new n.HandledError("Request aborted because of a network issue (timeout or similar).");throw a;case 5:return[2]}}))}))},a=[],i=Date.now()-432e5,r.forEach((function(e){var r=e[0];r.syncedAt>i&&r.data.queued?t[r.cid]={name:r.data.queued}:a.push(e)})),o=5,u=function(r){var n,i,u,c;return e.__generator(this,(function(d){switch(d.label){case 0:return n=a.slice(r,r+o),i=new FormData,n.forEach((function(e){var t=e[1];return i.append.apply(i,t)})),[4,s(i)];case 1:return u=d.sent(),c=(new Date).getTime(),n.forEach((function(e){var t=e[0];t.syncedAt=c,t.data.queued=u[t.cid].name})),t=e.__assign(e.__assign({},t),u),[2]}}))},c=0,l.label=2;case 2:return c<a.length?[5,u(c)]:[3,5];case 3:l.sent(),l.label=4;case 4:return c+=o,[3,2];case 5:return[2,t]}}))}))},a.prototype.getSubmission=function(t){var r=this;void 0===t&&(t={});var n="function"==typeof this.keys?this.keys():this.keys,i=e.__assign(e.__assign({},a.keys),n),o={values:{external_key:this.cid},media:[],samples:[],occurrences:[]};this.id&&(o.values.id=this.id);var u=function(e,t){var s=i[e].values;if(!s)return t;if("function"==typeof s)return s(t,o,r);if(t instanceof Array)return t.map((function(t){return u(e,t)}));if(s instanceof Array){var a=s.find((function(e){return e.value===t}));if(!a||!a.id)throw new Error('A "'.concat(e,'" attribute "').concat(t,'" value could not be mapped to a remote database field.'));return a.id}return s[t]};Object.keys(this.data).forEach((function(e){var t=r.data[e],a=function(e){return null==e};if(!a(t)){if(!i[e])return e=e.includes("smpAttr:")?e:s.snakeCase(e),void(o.values[e]=t);if(!a(t=u(e,t))){var n=i[e].id||e,c=Number.isNaN(Number(n))?n:"smpAttr:".concat(n);c=c.includes("smpAttr:")?c:s.snakeCase(c),o.values[c]=t}}})),this.samples.forEach((function(e){r.data.training&&(e.data.training=r.data.training);var s=e.getSubmission(t);s&&o.samples.push(s)})),this.occurrences.forEach((function(e){r.data.training&&(e.data.training=r.data.training);var s=e.getSubmission(t);s&&o.occurrences.push(s)})),this.media.forEach((function(e){var r=e.getSubmission(t);r&&o.media.push(r)}));var c=this.getSurvey();return c.modifySubmission?c.modifySubmission(o,this):o},Object.defineProperty(a.prototype,"isUploaded",{get:function(){return this.parent?this.parent.isUploaded:!!this.syncedAt},enumerable:!1,configurable:!0}),Object.defineProperty(a.prototype,"isDisabled",{get:function(){return this.isUploaded},enumerable:!1,configurable:!0}),a.keys={location:{id:"entered_sref"},location_type:{id:"entered_sref_system",values:{british:"OSGB",irish:"OSIE",channel:"utm30ed50",latlon:4326}},group:{id:"group_id"},training:{id:"training",values:l.boolToWarehouseValue},deleted:{id:"deleted",values:l.boolToWarehouseValue}},a}(i.default);exports.default=b,exports.getMediaFormData=_;
@@ -1,14 +1,22 @@
1
1
  import Collection, { Options as CollectionOptions } from '../Collection';
2
2
  import Store from '../Stores/Store';
3
- import IndiciaSample from './Sample';
4
- export type Options<T extends IndiciaSample> = {
3
+ import Occurrence from './Occurrence';
4
+ import Sample, { Remote } from './Sample';
5
+ export type Options<T extends Sample> = {
5
6
  models?: T[];
6
7
  store?: Store;
7
- Model?: typeof IndiciaSample<any, any>;
8
+ Model?: typeof Sample<any, any>;
9
+ Occurrence?: typeof Occurrence<any, any>;
10
+ url?: Remote['url'];
11
+ getAccessToken?: Remote['getAccessToken'];
8
12
  } & CollectionOptions<T>;
9
- export default class SampleCollection<T extends IndiciaSample> extends Collection<T> {
13
+ export default class SampleCollection<T extends Sample> extends Collection<T> {
14
+ remote: Remote;
15
+ Occurrence?: typeof Occurrence<any, any>;
16
+ cidMap: Map<string, Sample>;
10
17
  constructor(options: Options<T>);
11
18
  fetch: () => Promise<void>;
19
+ fetchRemote: (from: number, surveyIDs: any[]) => Promise<T[]>;
12
20
  removeAllSynced: () => Promise<any[]>;
13
21
  /**
14
22
  * Reverse order so that newest are at the top of list.
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),r=function(r){function n(n){var o=r.call(this,n)||this;o.fetch=function(){return e.__awaiter(o,void 0,void 0,(function(){var t,r,n,o=this;return e.__generator(this,(function(i){switch(i.label){case 0:return this.store&&this.Model?[4,this.store.findAll()]:(this.ready.resolve(!1),[2]);case 1:return t=i.sent(),r=function(t){return o.Model.fromJSON(e.__assign(e.__assign({},t),{attrs:t.data}))},n=t.map(r),this.push.apply(this,n),this.ready.resolve(!0),[2]}}))}))},o.removeAllSynced=function(){var e=[];return o.forEach((function(t){t.syncedAt&&e.push(t.destroy())})),Promise.all(e)},o.comparator=function(e){return-new Date(e.createdAt).getTime()},o.reset=function(){return e.__awaiter(o,void 0,void 0,(function(){var t;return e.__generator(this,(function(e){switch(e.label){case 0:return t=this.map((function(e){return e.destroy()})),[4,Promise.all(t)];case 1:return e.sent(),[2]}}))}))};return t.observe(o,(function(e){e.addedCount&&e.added.forEach((function(e){return e.collection=o})),e.removedCount&&e.removed.forEach((function(e){return delete e.collection}))})),o}return e.__extends(n,r),n}(require("../Collection.js").default);exports.default=r;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),r=require("axios"),n=require("../Collection.js"),a=require("./ElasticOccurrence.js"),s=require("./ElasticSample.js");function i(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var c=i(r),o=function(r){function n(n){var i=r.call(this,n)||this;i.remote=t.observable({synchronising:!1,url:null,getAccessToken:function(){return Promise.resolve("auth token is missing")},timeout:12e4}),i.fetch=function(){return e.__awaiter(i,void 0,void 0,(function(){var t,r,n,a=this;return e.__generator(this,(function(s){switch(s.label){case 0:return this.store&&this.Model?[4,this.store.findAll()]:(this.ready.resolve(!1),[2]);case 1:return t=s.sent(),r=function(t){var r=t.data,n=r.data,s=r.metadata,i=r.occurrences,c=r.samples,o=r.media;return new a.Model(e.__assign(e.__assign({},t),{data:n,metadata:s,occurrences:i,samples:c,media:o}))},n=t.map(r),this.push.apply(this,n),this.ready.resolve(!0),[2]}}))}))},i.fetchRemote=function(t,r){return e.__awaiter(i,void 0,void 0,(function(){var n,i,o,u,d,l,f,m,h,p,v,_,y,g,b,w,A,O,S,M,k,E,T=this;return e.__generator(this,(function(j){switch(j.label){case 0:return console.log("Fetching remote samples, page",t),n={bool:{must_not:{exists:{field:"event.parent_event_id"}}}},i={match:{"metadata.trial":"false"}},o=function(e){return{match:{"metadata.survey.id":e}}},u={bool:{should:r.map(o)}},d=[u,n,i],l=JSON.stringify({from:t,size:100,query:{bool:{must:d}},sort:[{"metadata.created_on":"desc"}]}),f=this.remote.url,[4,this.remote.getAccessToken()];case 1:return m=j.sent(),h={method:"post",url:"".concat(f,"/index.php/services/rest/es-samples/_search"),headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(m)},data:l},[4,c.default.request(h)];case 2:return p=j.sent(),v=function(e){return e._source},_=p.data.hits.hits.map(v),y=_.map((function(e){return e.id})),g=s.fetchElasticSubSamples({parentId:y,url:f,accessToken:m}),b=a.fetchElasticOccurrences({parentId:y,url:f,accessToken:m}),[4,Promise.all([g,b])];case 3:return w=j.sent(),A=w[0],O=w[1],S=function(e){return!!e},M=_.map(function(t,r,n,a,s){return function(i){var c,o,u=(new Date).getTime();try{var d=new n({skipStore:!0});d.data.surveyId=i.metadata.survey.id;var l=d.getSurvey(),f=n.parseRemoteJSON(i,t,l);d.id=f.id,d.cid=f.cid||d.cid,Object.assign(d.data,f.data),Object.assign(d.metadata,f.metadata);var m=function(e){return e.event.parent_event_id===d.id||e.event.event_id===d.id},h=a.filter(m).map((function(e){var r=n.parseRemoteJSON(e,t,l),a=new n(r);return a.syncedAt=u,a})),p=h.reduce((function(t,r){var n;return e.__assign(e.__assign({},t),((n={})[r.id]=r,n))}),((c={})[d.id]=d,c));return s.filter(m).map((function(e){var n=r.parseRemoteJSON(e,t,l),a=new r(n);return a.syncedAt=u,[a,e.event.event_id]})).forEach((function(e){var t=e[0],r=e[1];r!==parseInt(d.id,10)?p[r]?p[r].occurrences.push(t):console.error("Can't attach occ to missing ".concat(r," sample")):d.occurrences.push(t)})),(o=d.samples).push.apply(o,h),d.syncedAt=u,d}catch(e){return console.warn(JSON.stringify(i)),console.error(e),null}}}(f,this.Occurrence,this.Model,A,O)).filter(S),k=function(e){return!T.cidMap.has(e.cid)},E=M.filter(k),this.push.apply(this,E),[2,E]}}))}))},i.removeAllSynced=function(){var e=[];return i.forEach((function(t){t.syncedAt&&e.push(t.destroy())})),Promise.all(e)},i.comparator=function(e){return-new Date(e.createdAt).getTime()},i.reset=function(){return e.__awaiter(i,void 0,void 0,(function(){var t;return e.__generator(this,(function(e){switch(e.label){case 0:return t=this.map((function(e){return e.destroy()})),[4,Promise.all(t)];case 1:return e.sent(),[2]}}))}))},i.Occurrence=n.Occurrence,i.remote.url=n.url,i.remote.getAccessToken=n.getAccessToken,i.cidMap=new Map;t.intercept(i,(function(e){if(e.added&&e.added.length){e.added.forEach((function(e){i.cidMap.set(e.cid,e)}))}if(e.removedCount>0){var t=Array.from(i.cidMap.keys())[e.index];i.cidMap.delete(t)}return e}));return t.observe(i,(function(e){e.addedCount&&e.added.forEach((function(e){return e.collection=i})),e.removedCount&&e.removed.forEach((function(e){return delete e.collection}))})),i}return e.__extends(n,r),n}(n.default);exports.default=o;
@@ -18,7 +18,7 @@ export interface RemoteConfig {
18
18
  [key: string]: string | number | null;
19
19
  } | ((value: any, submission: any, model: any) => any);
20
20
  }
21
- export declare const boolToWarehouseValue: (val?: boolean | 't' | 'f' | null) => "t" | "f";
21
+ export declare const boolToWarehouseValue: (val?: boolean | "t" | "f" | null) => "t" | "f";
22
22
  export type Keys = (() => {
23
23
  [key: string]: RemoteConfig;
24
24
  }) | {
@@ -29,3 +29,12 @@ export declare function validateRemoteModel(): {
29
29
  model: any;
30
30
  models: any;
31
31
  } | null;
32
+ interface RemoteAttr {
33
+ value: any;
34
+ id: string;
35
+ }
36
+ type AttrConfig = any;
37
+ export declare const parseRemoteAttrs: (config: {
38
+ [key: string]: AttrConfig;
39
+ }, remoteAttrs: RemoteAttr[]) => any;
40
+ export {};
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib");function t(e,t){for(var r=atob(e.split(",")[1]),s=[],n=0;n<r.length;n++)s.push(r.charCodeAt(n));return new Blob([new Uint8Array(s)],{type:t})}function r(e){if(!e)return!1;return!!e.toString().match(/^\s*data:([a-z]+\/[a-z]+(;[a-z\-]+\=[a-z\-]+)?)?(;base64)?,[a-z0-9\!\$\&\'\,\(\)\*\+\,\;\=\-\.\_\~\:\@\/\?\%\s]*\s*$/i)}exports.boolToWarehouseValue=function(e){return!0===e||"t"===e?"t":"f"},exports.dataURItoBlob=t,exports.getBlobFromURL=function(e,s){if(r(e)){var n=t(e,s);return Promise.resolve(n)}return new Promise((function(t){var r=new XMLHttpRequest;r.open("GET",e,!0),r.responseType="blob",r.onload=function(){var e=r.response;t(e)},r.send()}))},exports.getErrorMessageFromObject=function(e){return Object.entries(e).reduce((function(e,t){return"".concat(e).concat(t[0]," ").concat(t[1],"\n")}),"")},exports.isDataURL=r,exports.validateRemoteModel=function(){var t=this.getSurvey(),r=t.verify&&t.verify(this.attrs,this),s={};if(r){var n=r&&"issues"in r;!("ValidationError"===(null==r?void 0:r.name)||"ValidationError"===(null==r?void 0:r.type))&&!n?s.errors=[r.message]:n?s.errors=r.issues.map((function(e){return e.message})):s=e.__assign({},r)}var o=function(e,t){var r=t.validateRemote();return r&&(e[t.cid]=r,e[t.cid].model=t),e},i=(this.samples||[]).reduce(o,{}),a=(this.occurrences||[]).reduce(o,{}),u=(this.media||[]).reduce(o,{});return Object.keys(s).length||Object.keys(i).length||Object.keys(a).length||Object.keys(u).length?{attributes:s,model:this,models:e.__assign(e.__assign(e.__assign({},i),a),u)}:null};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib");function t(e,t){for(var r=atob(e.split(",")[1]),n=[],s=0;s<r.length;s++)n.push(r.charCodeAt(s));return new Blob([new Uint8Array(n)],{type:t})}function r(e){if(!e)return!1;return!!e.toString().match(/^\s*data:([a-z]+\/[a-z]+(;[a-z\-]+\=[a-z\-]+)?)?(;base64)?,[a-z0-9\!\$\&\'\,\(\)\*\+\,\;\=\-\.\_\~\:\@\/\?\%\s]*\s*$/i)}exports.boolToWarehouseValue=function(e){return!0===e||"t"===e?"t":"f"},exports.dataURItoBlob=t,exports.getBlobFromURL=function(e,n){if(r(e)){var s=t(e,n);return Promise.resolve(s)}return new Promise((function(t){var r=new XMLHttpRequest;r.open("GET",e,!0),r.responseType="blob",r.onload=function(){var e=r.response;t(e)},r.send()}))},exports.getErrorMessageFromObject=function(e){return Object.entries(e).reduce((function(e,t){return"".concat(e).concat(t[0]," ").concat(t[1],"\n")}),"")},exports.isDataURL=r,exports.parseRemoteAttrs=function(e,t){e=e||{};var r=Object.entries(e);return t.reduce((function(e,t){var n=r.find((function(e){var r;return(null===(r=e[1].remote)||void 0===r?void 0:r.id)===parseInt(t.id,10)}));if(!n)return e;var s=n[0],o=isNaN(t.value)?t.value:parseFloat(t.value);return e[s]=o,e}),{})},exports.validateRemoteModel=function(){var t=this.getSurvey(),r=t.verify&&t.verify(this.data,this),n={};if(r){var s=r&&"issues"in r;!("ValidationError"===(null==r?void 0:r.name)||"ValidationError"===(null==r?void 0:r.type))&&!s?n.errors=[r.message]:s?n.errors=r.issues.map((function(e){return e.message})):n=e.__assign({},r)}var o=function(e,t){var r=t.validateRemote();return r&&(e[t.cid]=r,e[t.cid].model=t),e},a=(this.samples||[]).reduce(o,{}),i=(this.occurrences||[]).reduce(o,{}),u=(this.media||[]).reduce(o,{});return Object.keys(n).length||Object.keys(a).length||Object.keys(i).length||Object.keys(u).length?{attributes:n,model:this,models:e.__assign(e.__assign(e.__assign({},a),i),u)}:null};
package/dist/Model.d.ts CHANGED
@@ -1,21 +1,22 @@
1
- import Deferred from '@flumens/utils/dist/deferred';
1
+ import { Deferred } from '@flumens/utils';
2
2
  import Store from './Stores/Store';
3
+ export declare const copyObject: (obj: any) => any;
3
4
  export interface Options<T = any> {
4
5
  id?: string;
5
6
  cid?: string;
6
7
  createdAt?: number;
7
8
  updatedAt?: number;
8
9
  syncedAt?: number;
9
- attrs?: T;
10
+ data?: T;
10
11
  store?: Store;
11
- }
12
- export interface Attrs {
13
12
  /**
14
- * Flag whether the model was deleted. Global and persistent models might not need this.
13
+ * @deprecated
15
14
  */
16
- deleted?: boolean;
15
+ attrs?: any;
16
+ }
17
+ export interface Data {
17
18
  }
18
- export default class Model<T extends Attrs = Attrs> {
19
+ export default class Model<T extends Data = Data> {
19
20
  /**
20
21
  * Remote server document ID.
21
22
  */
@@ -39,7 +40,7 @@ export default class Model<T extends Attrs = Attrs> {
39
40
  /**
40
41
  * Model's persistent observable attributes.
41
42
  */
42
- attrs: T;
43
+ data: T;
43
44
  /**
44
45
  * The offline store used to save and fetch the model from.
45
46
  */
@@ -56,7 +57,7 @@ export default class Model<T extends Attrs = Attrs> {
56
57
  */
57
58
  readonly ready: Deferred<boolean>;
58
59
  protected debouncedValue: number;
59
- constructor({ id, cid, createdAt, updatedAt, syncedAt, attrs, store, }: Options);
60
+ constructor({ id, cid, createdAt, updatedAt, syncedAt, data, attrs, store, }: Options);
60
61
  setUpdatedAtTimestamp(newUpdatedAt: number): void;
61
62
  private _observerPaused;
62
63
  /**
@@ -81,7 +82,7 @@ export default class Model<T extends Attrs = Attrs> {
81
82
  createdAt: number;
82
83
  updatedAt: number;
83
84
  syncedAt: number | null | undefined;
84
- attrs: T;
85
+ data: T;
85
86
  };
86
87
  resetDefaults(defaultsToSet?: any): Promise<void>;
87
88
  }
package/dist/Model.js CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("tslib"),e=require("mobx"),s=require("mobx-utils"),r=require("@flumens/utils/dist/deferred"),i=require("@flumens/utils/dist/uuid");function a(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}var n=a(r),o=a(i),d={deleted:!1},u=function(){function r(r){var i=this,a=r.id,u=void 0===a?"":a,c=r.cid,h=void 0===c?"":c,l=r.createdAt,f=r.updatedAt,v=r.syncedAt,p=r.attrs,_=void 0===p?{}:p,y=r.store;this.ready=new n.default,this.debouncedValue=3e3,this._observerPaused=!1,this.id=u,this.cid=h||u||o.default();var b,A,w=Date.now();this.createdAt=l||w,this.updatedAt=f||w,this.syncedAt=v,this.attrs=(b=t.__assign(t.__assign({},d),_),JSON.parse(JSON.stringify(b))),e.makeObservable(this,{createdAt:e.observable,updatedAt:e.observable,syncedAt:e.observable,attrs:e.observable}),this.store=y;s.deepObserve(this.attrs,(function(){i._observerPaused||(i.updatedAt=Date.now(),function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];clearTimeout(A),A=setTimeout((function(){return i.sync.apply(i,t)}),i.debouncedValue)}())}))}return r.prototype.setUpdatedAtTimestamp=function(t){this.updatedAt=t},r.prototype.fetch=function(){return t.__awaiter(this,void 0,void 0,(function(){var s;return t.__generator(this,(function(t){switch(t.label){case 0:return this.store?[4,this.store.find(this.cid)]:(this.ready.resolve(!1),[2]);case 1:return(s=t.sent())?[3,3]:[4,this.save()];case 2:return t.sent(),this.ready.resolve(!0),[2];case 3:return s.id&&(this.id=s.id),s.cid&&(this.cid=s.cid),this._observerPaused=!0,e.set(this.attrs,s.data),this._observerPaused=!1,this.createdAt=s.createdAt,this.updatedAt=s.updatedAt,this.syncedAt=s.syncedAt,this.ready.resolve(!0),[2]}}))}))},r.prototype.save=function(){return t.__awaiter(this,void 0,void 0,(function(){var e;return t.__generator(this,(function(s){switch(s.label){case 0:if(!this.store)throw new Error("Trying to save locally without a store");return e=this.toJSON(),[4,this.store.save(t.__assign(t.__assign({},e),{data:e.attrs}))];case 1:return s.sent(),[2]}}))}))},r.prototype.destroy=function(){return t.__awaiter(this,void 0,void 0,(function(){return t.__generator(this,(function(t){switch(t.label){case 0:if(!this.store)throw new Error("Trying to delete locally without a store");return[4,this.store.delete(this.cid)];case 1:return t.sent(),[2]}}))}))},r.prototype.sync=function(){return t.__awaiter(this,void 0,void 0,(function(){return t.__generator(this,(function(t){switch(t.label){case 0:return this.store?[4,this.save()]:[3,2];case 1:t.sent(),t.label=2;case 2:return[2]}}))}))},r.prototype.toJSON=function(){return{id:this.id,cid:this.cid,createdAt:this.createdAt,updatedAt:this.updatedAt,syncedAt:this.syncedAt,attrs:e.toJS(this.attrs)}},r.prototype.resetDefaults=function(s){var r=this;this.id="";var i=JSON.parse(JSON.stringify(t.__assign(t.__assign({},d),s)));e.set(this.attrs,i);var a=Object.keys(i);return Object.keys(this.attrs).forEach((function(t){a.includes(t)||(r.attrs[t]=null,delete r.attrs[t])})),this.save()},r}();exports.default=u;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("tslib"),e=require("mobx"),s=require("mobx-utils"),r=require("@flumens/utils"),i=function(t){return JSON.parse(JSON.stringify(t))},a={},n=function(){function n(n){var o=n.id,d=void 0===o?"":o,u=n.cid,c=void 0===u?"":u,h=n.createdAt,l=n.updatedAt,v=n.syncedAt,f=n.data,p=void 0===f?{}:f,y=n.attrs,_=void 0===y?{}:y,b=n.store,A=this;this.ready=new r.Deferred,this.debouncedValue=3e3,this._observerPaused=!1,this.id=d,this.cid=c||d||r.UUIDv7();var w,g=Date.now();this.createdAt=h||g,this.updatedAt=l||g,this.syncedAt=v,this.data=i(t.__assign(t.__assign(t.__assign({},a),p),_)),e.makeObservable(this,{createdAt:e.observable,updatedAt:e.observable,syncedAt:e.observable,data:e.observable}),this.store=b;s.deepObserve(this.data,(function(){A._observerPaused||(A.updatedAt=Date.now(),function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];clearTimeout(w),w=setTimeout((function(){return A.sync.apply(A,t)}),A.debouncedValue)}())}))}return n.prototype.setUpdatedAtTimestamp=function(t){this.updatedAt=t},n.prototype.fetch=function(){return t.__awaiter(this,void 0,void 0,(function(){var s;return t.__generator(this,(function(t){switch(t.label){case 0:return this.store?[4,this.store.find(this.cid)]:(this.ready.resolve(!1),[2]);case 1:return(s=t.sent())?[3,3]:[4,this.save()];case 2:return t.sent(),this.ready.resolve(!0),[2];case 3:return s.id&&(this.id=s.id),s.cid&&(this.cid=s.cid),this._observerPaused=!0,e.set(this.data,s.data),this._observerPaused=!1,this.createdAt=s.createdAt,this.updatedAt=s.updatedAt,this.syncedAt=s.syncedAt,this.ready.resolve(!0),[2]}}))}))},n.prototype.save=function(){return t.__awaiter(this,void 0,void 0,(function(){var e;return t.__generator(this,(function(t){switch(t.label){case 0:if(!this.store)throw new Error("Trying to save locally without a store");return e=this.toJSON(),[4,this.store.save(e)];case 1:return t.sent(),[2]}}))}))},n.prototype.destroy=function(){return t.__awaiter(this,void 0,void 0,(function(){return t.__generator(this,(function(t){switch(t.label){case 0:if(!this.store)throw new Error("Trying to delete locally without a store");return[4,this.store.delete(this.cid)];case 1:return t.sent(),[2]}}))}))},n.prototype.sync=function(){return t.__awaiter(this,void 0,void 0,(function(){return t.__generator(this,(function(t){switch(t.label){case 0:return this.store?[4,this.save()]:[3,2];case 1:t.sent(),t.label=2;case 2:return[2]}}))}))},n.prototype.toJSON=function(){return{id:this.id,cid:this.cid,createdAt:this.createdAt,updatedAt:this.updatedAt,syncedAt:this.syncedAt,data:e.toJS(this.data)}},n.prototype.resetDefaults=function(s){var r=this;this.id="";var i=JSON.parse(JSON.stringify(t.__assign(t.__assign({},a),s)));e.set(this.data,i);var n=Object.keys(i);return Object.keys(this.data).forEach((function(t){n.includes(t)||(r.data[t]=null,delete r.data[t])})),this.save()},n}();exports.copyObject=i,exports.default=n;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),r=require("localforage"),t=require("localforage-cordovasqlitedriver"),i=require("@ionic/react"),n=require("./utils.js");function o(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var a=o(r),s=o(t),u=["indexeddb","websql","localstorage"];if(i.isPlatform("hybrid")){if(!window.sqlitePlugin)throw new Error("cordova-sql-storage plugin is missing. Please install it.");u=e.__spreadArray([s.default],u,!0)}var c={driverOrder:u},d=function(){function r(t){var i=this,n=e.__assign(e.__assign({},c),t);this.debugging=n.debugging,this.localForage=null,this.ready=new Promise((function(e,t){var o=new Promise((function(e){n.driverOrder&&"object"==typeof n.driverOrder[0]?a.default.defineDriver(n.driverOrder[0]).then(e):e(void 0)}));if(!n.storeName)throw new Error("storeName prop is missing");i.storeName=n.storeName,o.then((function(){var o={name:n.name||"indicia",storeName:n.storeName};n.version&&(o.version=n.version);var s=r._getDriverOrder(n.driverOrder),u=n.LocalForage||a.default;i.localForage=u.createInstance(o),i.localForage.setDriver(s).then(e).catch(t)}))}))}return r._getDriverOrder=function(e){return e.map((function(e){switch(e){case"indexeddb":return a.default.INDEXEDDB;case"websql":return a.default.WEBSQL;case"localstorage":return a.default.LOCALSTORAGE;default:return"object"==typeof e&&e._driver?e._driver:console.error("No such db driver!")}}))},r.prototype.save=function(r){return e.__awaiter(this,void 0,void 0,(function(){var t;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this.ready];case 1:if(e.sent(),!r.cid)throw new Error("Invalid key passed to store");return this.debugging?[4,this.find(r.cid)]:[3,3];case 2:t=e.sent(),n.printDiff(t,r,r.cid,this.storeName),e.label=3;case 3:return[2,this.localForage.setItem(r.cid,r)]}}))}))},r.prototype.find=function(r){return e.__awaiter(this,void 0,void 0,(function(){return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this.ready];case 1:if(e.sent(),!r)throw new Error("Invalid key passed to store");return[2,this.localForage.getItem(r)]}}))}))},r.prototype.findAll=function(){return e.__awaiter(this,void 0,void 0,(function(){var r;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this.ready];case 1:return e.sent(),r=[],[4,this.localForage.iterate((function(e){r.push(e)}))];case 2:return e.sent(),[2,r]}}))}))},r.prototype.delete=function(r){return e.__awaiter(this,void 0,void 0,(function(){return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this.ready];case 1:if(e.sent(),!r)throw new Error("Invalid key passed to store");return[2,this.localForage.removeItem(r)]}}))}))},r.prototype.deleteAll=function(){return e.__awaiter(this,void 0,void 0,(function(){var r,t=this;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this.ready];case 1:return e.sent(),[4,this.findAll()];case 2:return r=e.sent(),[4,Promise.all(r.map((function(e){return t.delete(e)})))];case 3:return e.sent(),[2]}}))}))},r.prototype.export=function(){return e.__awaiter(this,void 0,void 0,(function(){var r;return e.__generator(this,(function(t){switch(t.label){case 0:return[4,this.ready];case 1:return t.sent(),r=function(r,t){var i;return e.__assign(e.__assign({},r),((i={})[t.cid]=t,i))},[4,this.findAll()];case 2:return[2,t.sent().reduce(r,{})]}}))}))},r.prototype.import=function(r){return e.__awaiter(this,void 0,void 0,(function(){var t,i=this;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this.ready];case 1:return e.sent(),[4,this.deleteAll()];case 2:if(e.sent(),"object"!=typeof r)throw new Error("Invalid obj passed to store");return t=Object.entries(r).map((function(e){var r=e[1];return i.save(r)})),[4,Promise.all(t)];case 3:return e.sent(),[2]}}))}))},r}();exports.default=d;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),r=require("localforage"),t=require("localforage-cordovasqlitedriver"),i=require("@flumens/utils"),n=require("./utils.js");function o(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var s=o(r),a=o(t),u=["indexeddb","websql","localstorage"];if(i.isPlatform("hybrid")){if(!window.sqlitePlugin)throw new Error("cordova-sql-storage plugin is missing. Please install it.");u=e.__spreadArray([a.default],u,!0)}var c={driverOrder:u},d=function(){function r(t){var i=this,n=e.__assign(e.__assign({},c),t);this.debugging=n.debugging,this.localForage=null,this.ready=new Promise((function(e,t){var o=new Promise((function(e){n.driverOrder&&"object"==typeof n.driverOrder[0]?s.default.defineDriver(n.driverOrder[0]).then(e):e(void 0)}));if(!n.storeName)throw new Error("storeName prop is missing");i.storeName=n.storeName,o.then((function(){var o={name:n.name||"indicia",storeName:n.storeName};n.version&&(o.version=n.version);var a=r._getDriverOrder(n.driverOrder),u=n.LocalForage||s.default;i.localForage=u.createInstance(o),i.localForage.setDriver(a).then(e).catch(t)}))}))}return r._getDriverOrder=function(e){return e.map((function(e){switch(e){case"indexeddb":return s.default.INDEXEDDB;case"websql":return s.default.WEBSQL;case"localstorage":return s.default.LOCALSTORAGE;default:return"object"==typeof e&&e._driver?e._driver:console.error("No such db driver!")}}))},r.prototype.save=function(r){return e.__awaiter(this,void 0,void 0,(function(){var t;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this.ready];case 1:if(e.sent(),!r.cid)throw new Error("Invalid key passed to store");return this.debugging?[4,this.find(r.cid)]:[3,3];case 2:t=e.sent(),n.printDiff(t,r,r.cid,this.storeName),e.label=3;case 3:return[2,this.localForage.setItem(r.cid,r)]}}))}))},r.prototype.find=function(r){return e.__awaiter(this,void 0,void 0,(function(){return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this.ready];case 1:if(e.sent(),!r)throw new Error("Invalid key passed to store");return[2,this.localForage.getItem(r)]}}))}))},r.prototype.findAll=function(){return e.__awaiter(this,void 0,void 0,(function(){var r;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this.ready];case 1:return e.sent(),r=[],[4,this.localForage.iterate((function(e){r.push(e)}))];case 2:return e.sent(),[2,r]}}))}))},r.prototype.delete=function(r){return e.__awaiter(this,void 0,void 0,(function(){return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this.ready];case 1:if(e.sent(),!r)throw new Error("Invalid key passed to store");return[2,this.localForage.removeItem(r)]}}))}))},r.prototype.deleteAll=function(){return e.__awaiter(this,void 0,void 0,(function(){var r,t=this;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this.ready];case 1:return e.sent(),[4,this.findAll()];case 2:return r=e.sent(),[4,Promise.all(r.map((function(e){return t.delete(e)})))];case 3:return e.sent(),[2]}}))}))},r.prototype.export=function(){return e.__awaiter(this,void 0,void 0,(function(){var r;return e.__generator(this,(function(t){switch(t.label){case 0:return[4,this.ready];case 1:return t.sent(),r=function(r,t){var i;return e.__assign(e.__assign({},r),((i={})[t.cid]=t,i))},[4,this.findAll()];case 2:return[2,t.sent().reduce(r,{})]}}))}))},r.prototype.import=function(r){return e.__awaiter(this,void 0,void 0,(function(){var t,i=this;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this.ready];case 1:return e.sent(),[4,this.deleteAll()];case 2:if(e.sent(),"object"!=typeof r)throw new Error("Invalid obj passed to store");return t=Object.entries(r).map((function(e){var r=e[1];return i.save(r)})),[4,Promise.all(t)];case 3:return e.sent(),[2]}}))}))},r}();exports.default=d;
@@ -1,5 +1,5 @@
1
1
  import { SQLiteConnection } from '@capacitor-community/sqlite';
2
- import Deferred from '@flumens/utils/dist/deferred';
2
+ import { Deferred } from '@flumens/utils';
3
3
  type SQLiteDatabaseOptions = {
4
4
  name?: string;
5
5
  debug?: boolean;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("jeep-sqlite/loader"),n=require("@capacitor-community/sqlite"),r=require("@capacitor/core"),i=require("@capacitor/filesystem");function s(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var o=s(require("@flumens/utils/dist/deferred")),a=function(){function s(e){var t=e.name,r=e.debug,i=e.web;this.sqliteConnection=new n.SQLiteConnection(n.CapacitorSQLite),this.name="main",this.debug=!1,this.isWeb=!1,this.ready=new o.default,this.name=t||this.name,this.debug=r||this.debug,this.isWeb=i||this.isWeb}return s.migrateCordova=function(t){var r;return e.__awaiter(this,void 0,void 0,(function(){var i,s,o;return e.__generator(this,(function(e){switch(e.label){case 0:console.log("SQLite: Cordova db migration"),i=new n.SQLiteConnection(n.CapacitorSQLite),e.label=1;case 1:return e.trys.push([1,5,,6]),[4,i.getMigratableDbList(t?"Library/LocalDatabase":void 0)];case 2:return s=e.sent(),(null===(r=s.values)||void 0===r?void 0:r.length)?(console.log("SQLite: migrating",s.values),[4,i.addSQLiteSuffix(t?"Library/LocalDatabase":void 0,s.values)]):(console.log("SQLite: no Cordova db to migrate"),[2]);case 3:return e.sent(),[4,i.deleteOldDatabases(t?"Library/LocalDatabase":void 0,s.values)];case 4:return e.sent(),console.log("SQLite: migrating done",s.values),[3,6];case 5:return o=e.sent(),console.error(o),[3,6];case 6:return[4,i.checkConnectionsConsistency()];case 7:return e.sent(),[4,i.closeAllConnections()];case 8:return e.sent(),[2]}}))}))},Object.defineProperty(s.prototype,"db",{get:function(){return this.connection},enumerable:!1,configurable:!0}),s.prototype.init=function(){return e.__awaiter(this,void 0,void 0,(function(){var n,r;return e.__generator(this,(function(e){switch(e.label){case 0:return this.isWeb?(t.defineCustomElements(window),(n=document.createElement("jeep-sqlite")).setAttribute("autoSave","true"),document.body.appendChild(n),[4,customElements.whenDefined("jeep-sqlite")]):[3,3];case 1:return e.sent(),[4,this.sqliteConnection.initWebStore()];case 2:e.sent(),e.label=3;case 3:return[4,this.sqliteConnection.checkConnectionsConsistency()];case 4:return e.sent(),[4,this.sqliteConnection.closeAllConnections()];case 5:return e.sent(),r=this,[4,this.sqliteConnection.createConnection(this.name,!1,"no-encryption",1,!1)];case 6:return r.connection=e.sent(),[4,this.connection.open()];case 7:return e.sent(),this.ready.resolve(!0),[2]}}))}))},s.prototype.query=function(t){var n,r=t.sql,i=t.params;return e.__awaiter(this,void 0,void 0,(function(){var t;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this.ready];case 1:return e.sent(),[4,this.db.query(r,i).then((function(e){return e.values||[]}))];case 2:return t=e.sent(),this.debug?(console.groupCollapsed("💾 SQL: ".concat(r.trimStart().replaceAll(/\n/g," ").replaceAll(/\s+/g," ").substring(0,30),"...")),console.debug(r,i,t),console.groupEnd(),[4,null===(n=this.sqliteConnection)||void 0===n?void 0:n.saveToStore(this.name)]):[3,4];case 3:e.sent(),e.label=4;case 4:return[2,t]}}))}))},s.prototype.export=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,n;return e.__generator(this,(function(e){switch(e.label){case 0:return this.isWeb?(t=this.name,[2,new Promise((function(e){indexedDB.open("jeepSqliteStore").onsuccess=function(n){n.target.result.transaction(["databases"],"readwrite").objectStore("databases").get("".concat(t,"SQLite.db")).onsuccess=function(t){var n=new Blob([t.target.result],{type:"application/vnd.sqlite3"});e(n)}}}))]):[4,this.db.getUrl()];case 1:return n=e.sent().url,[4,fetch(r.Capacitor.convertFileSrc(n))];case 2:return[2,e.sent().blob()]}}))}))},s.prototype.import=function(t){return e.__awaiter(this,void 0,void 0,(function(){var n,r,s,o,a;return e.__generator(this,(function(e){switch(e.label){case 0:return this.isWeb?(r=Uint8Array.bind,[4,t.arrayBuffer()]):[3,2];case 1:return n=new(r.apply(Uint8Array,[void 0,e.sent()])),s=this.name,new Promise((function(e){indexedDB.open("jeepSqliteStore").onsuccess=function(t){t.target.result.transaction(["databases"],"readwrite").objectStore("databases").put(n,"".concat(s,"SQLite.db"),0).onsuccess=function(){return e()}}})),[2];case 2:return[4,this.db.getUrl()];case 3:return o=e.sent().url,[4,new Promise((function(e){var n=new FileReader;n.onload=e,n.readAsDataURL(t)})).then((function(e){return e.target.result}))];case 4:return a=e.sent(),[4,i.Filesystem.writeFile({path:o,data:a})];case 5:return e.sent(),[2]}}))}))},s}();exports.default=a;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("jeep-sqlite/loader"),n=require("@capacitor-community/sqlite"),r=require("@capacitor/core"),i=require("@capacitor/filesystem"),s=require("@flumens/utils"),o=function(){function o(e){var t=e.name,r=e.debug,i=e.web;this.sqliteConnection=new n.SQLiteConnection(n.CapacitorSQLite),this.name="main",this.debug=!1,this.isWeb=!1,this.ready=new s.Deferred,this.name=t||this.name,this.debug=r||this.debug,this.isWeb=i||this.isWeb}return o.migrateCordova=function(t){return e.__awaiter(this,void 0,void 0,(function(){var r,i,s,o;return e.__generator(this,(function(e){switch(e.label){case 0:console.log("SQLite: Cordova db migration"),r=new n.SQLiteConnection(n.CapacitorSQLite),e.label=1;case 1:return e.trys.push([1,5,,6]),[4,r.getMigratableDbList(t?"Library/LocalDatabase":void 0)];case 2:return i=e.sent(),(null===(o=i.values)||void 0===o?void 0:o.length)?(console.log("SQLite: migrating",i.values),[4,r.addSQLiteSuffix(t?"Library/LocalDatabase":void 0,i.values)]):(console.log("SQLite: no Cordova db to migrate"),[2]);case 3:return e.sent(),[4,r.deleteOldDatabases(t?"Library/LocalDatabase":void 0,i.values)];case 4:return e.sent(),console.log("SQLite: migrating done",i.values),[3,6];case 5:return s=e.sent(),console.error(s),[3,6];case 6:return[4,r.checkConnectionsConsistency()];case 7:return e.sent(),[4,r.closeAllConnections()];case 8:return e.sent(),[2]}}))}))},Object.defineProperty(o.prototype,"db",{get:function(){return this.connection},enumerable:!1,configurable:!0}),o.prototype.init=function(){return e.__awaiter(this,void 0,void 0,(function(){var n,r;return e.__generator(this,(function(e){switch(e.label){case 0:return this.isWeb?(t.defineCustomElements(window),(n=document.createElement("jeep-sqlite")).setAttribute("autoSave","true"),document.body.appendChild(n),[4,customElements.whenDefined("jeep-sqlite")]):[3,3];case 1:return e.sent(),[4,this.sqliteConnection.initWebStore()];case 2:e.sent(),e.label=3;case 3:return[4,this.sqliteConnection.checkConnectionsConsistency()];case 4:return e.sent(),[4,this.sqliteConnection.closeAllConnections()];case 5:return e.sent(),r=this,[4,this.sqliteConnection.createConnection(this.name,!1,"no-encryption",1,!1)];case 6:return r.connection=e.sent(),[4,this.connection.open()];case 7:return e.sent(),this.ready.resolve(!0),[2]}}))}))},o.prototype.query=function(t){return e.__awaiter(this,arguments,void 0,(function(t){var n,r,i=t.sql,s=t.params;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,this.ready];case 1:return e.sent(),[4,this.db.query(i,s).then((function(e){return e.values||[]}))];case 2:return n=e.sent(),this.debug?(console.groupCollapsed("💾 SQL: ".concat(i.trimStart().replaceAll(/\n/g," ").replaceAll(/\s+/g," ").substring(0,30),"...")),console.debug(i,s,n),console.groupEnd(),[4,null===(r=this.sqliteConnection)||void 0===r?void 0:r.saveToStore(this.name)]):[3,4];case 3:e.sent(),e.label=4;case 4:return[2,n]}}))}))},o.prototype.export=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,n;return e.__generator(this,(function(e){switch(e.label){case 0:return this.isWeb?(t=this.name,[2,new Promise((function(e){indexedDB.open("jeepSqliteStore").onsuccess=function(n){n.target.result.transaction(["databases"],"readwrite").objectStore("databases").get("".concat(t,"SQLite.db")).onsuccess=function(t){var n=new Blob([t.target.result],{type:"application/vnd.sqlite3"});e(n)}}}))]):[4,this.db.getUrl()];case 1:return n=e.sent().url,[4,fetch(r.Capacitor.convertFileSrc(n))];case 2:return[2,e.sent().blob()]}}))}))},o.prototype.import=function(t){return e.__awaiter(this,void 0,void 0,(function(){var n,r,s,o,a;return e.__generator(this,(function(e){switch(e.label){case 0:return this.isWeb?(r=Uint8Array.bind,[4,t.arrayBuffer()]):[3,2];case 1:return n=new(r.apply(Uint8Array,[void 0,e.sent()])),s=this.name,new Promise((function(e){indexedDB.open("jeepSqliteStore").onsuccess=function(t){t.target.result.transaction(["databases"],"readwrite").objectStore("databases").put(n,"".concat(s,"SQLite.db"),0).onsuccess=function(){return e()}}})),[2];case 2:return[4,this.db.getUrl()];case 3:return o=e.sent().url,[4,new Promise((function(e){var n=new FileReader;n.onload=e,n.readAsDataURL(t)})).then((function(e){return e.target.result}))];case 4:return a=e.sent(),[4,i.Filesystem.writeFile({path:o,data:a})];case 5:return e.sent(),[2]}}))}))},o}();exports.default=o;
@@ -1,9 +1,9 @@
1
1
  import { BuildColumns, ColumnBuilderBase, ColumnBuilderBaseConfig, ColumnDataType, InferModelFromColumns, SQL } from 'drizzle-orm';
2
2
  import { SQLiteSelect, SQLiteDelete, SQLiteTable } from 'drizzle-orm/sqlite-core';
3
- import Deferred from '@flumens/utils/dist/deferred';
3
+ import { Deferred } from '@flumens/utils';
4
4
  import SQLiteDatabase from './SQLiteDatabase';
5
5
  import Store from './Store';
6
- export declare function conflictUpdateAllExcept<T extends SQLiteTable, E extends (keyof T['$inferInsert'])[]>(table: T, except: E): Omit<Record<string | number, SQL<unknown>>, E[number]>;
6
+ export declare function conflictUpdateAllExcept<T extends SQLiteTable, E extends (keyof T['$inferInsert'])[]>(table: T, except: E): Omit<Record<keyof typeof table.$inferInsert, SQL>, E[number]>;
7
7
  export declare const jsonb: <TData>(name: string) => import("drizzle-orm/sqlite-core").SQLiteCustomColumnBuilder<{
8
8
  name: string;
9
9
  dataType: "custom";
@@ -11,7 +11,6 @@ export declare const jsonb: <TData>(name: string) => import("drizzle-orm/sqlite-
11
11
  data: TData;
12
12
  driverParam: string;
13
13
  enumValues: undefined;
14
- generated: undefined;
15
14
  }>;
16
15
  type SQLiteStoreOptions = {
17
16
  db: SQLiteDatabase;
@@ -20,8 +19,8 @@ type SQLiteStoreOptions = {
20
19
  columns?: any;
21
20
  };
22
21
  export declare const defaultCols: () => {
23
- id: import("drizzle-orm/sqlite-core").SQLiteTextBuilderInitial<"", [string, ...string[]]>;
24
- cid: import("drizzle-orm").HasDefault<import("drizzle-orm").NotNull<import("drizzle-orm").IsPrimaryKey<import("drizzle-orm").NotNull<import("drizzle-orm/sqlite-core").SQLiteTextBuilderInitial<"", [string, ...string[]]>>>>>;
22
+ id: import("drizzle-orm/sqlite-core").SQLiteTextBuilderInitial<"", [string, ...string[]], undefined>;
23
+ cid: import("drizzle-orm").HasDefault<import("drizzle-orm").NotNull<import("drizzle-orm").IsPrimaryKey<import("drizzle-orm").NotNull<import("drizzle-orm/sqlite-core").SQLiteTextBuilderInitial<"", [string, ...string[]], undefined>>>>>;
25
24
  data: import("drizzle-orm").NotNull<import("drizzle-orm/sqlite-core").SQLiteCustomColumnBuilder<{
26
25
  name: string;
27
26
  dataType: "custom";
@@ -29,7 +28,6 @@ export declare const defaultCols: () => {
29
28
  data: any;
30
29
  driverParam: string;
31
30
  enumValues: undefined;
32
- generated: undefined;
33
31
  }>>;
34
32
  createdAt: import("drizzle-orm").NotNull<import("drizzle-orm/sqlite-core").SQLiteIntegerBuilderInitial<"created_at">>;
35
33
  updatedAt: import("drizzle-orm").NotNull<import("drizzle-orm/sqlite-core").SQLiteIntegerBuilderInitial<"updated_at">>;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("tslib"),e=require("drizzle-orm"),r=require("drizzle-orm/casing"),n=require("drizzle-orm/sqlite-core"),i=require("@flumens/utils/dist/deferred"),a=require("./utils.js");function s(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}var o=s(i);function u(r,n){var i=e.getTableColumns(r);return Object.entries(i).filter((function(t){var e=t[0];return!n.includes(e)})).reduce((function(r,n){var i,a=n[0],s=n[1];return t.__assign(t.__assign({},r),((i={})[a]=e.sql.raw("excluded.".concat(s.name)),i))}),{})}var c=function(t){return n.customType({dataType:function(){return"jsonb"},toDriver:function(t){return JSON.stringify(t)}})(t)},d=new n.SQLiteSyncDialect,l=function(){return{id:n.text(),cid:n.text().primaryKey().notNull().default("id"),data:c("data").notNull(),createdAt:n.integer("created_at").notNull(),updatedAt:n.integer("updated_at").notNull(),syncedAt:n.integer("synced_at")}},f=function(){function i(t){var e=t.db,r=t.name,i=t.debug,a=t.columns,s=void 0===a?l():a;this.ready=new o.default,this.db=e,this.name=r,this.debug=i||!1,this.table=n.sqliteTable(this.name,s),this.init()}return i.prototype.init=function(){return t.__awaiter(this,void 0,void 0,(function(){var e,r;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.db.ready];case 1:return t.sent(),e=function(t){return"".concat(t.name," ").concat(t.getSQLType()).concat(t.primary?" primary key":"").concat(t.notNull?" not null":"").concat(t.default?" default ".concat(t.default):"")},r=n.getTableConfig(this.table).columns.map(e).join(",\n"),[4,this.db.query({sql:"CREATE TABLE IF NOT EXISTS ".concat(this.name," (").concat(r,");")})];case 2:return t.sent(),this.ready.resolve(!0),[2]}}))}))},i.prototype.save=function(e){return t.__awaiter(this,void 0,void 0,(function(){var r,i,s;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.ready];case 1:return t.sent(),(Array.isArray(e)?e.length:e)?this.debug&&e.cid?[4,this.find({cid:e.cid})]:[3,3]:[2];case 2:r=t.sent(),a.printDiff(r,e,e.cid,this.name),t.label=3;case 3:return i=new n.SQLiteInsertBuilder(this.table,{},d).values(e),(s=this._getPrimaryCol())&&(i=i.onConflictDoUpdate({target:s,set:u(this.table,[])})),[4,this.db.query(i.toSQL())];case 4:return t.sent(),[2]}}))}))},i.prototype.find=function(r){return t.__awaiter(this,void 0,void 0,(function(){var n,i=this;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.ready];case 1:return t.sent(),n=function(t){if("function"==typeof r)return r(t).limit(1);if("string"==typeof r){var n=i._getPrimaryCol();if(!n)throw new Error("Primary col is missing");return t.where(e.eq(n,r)).limit(1)}var a=Object.entries(r).map((function(t){var r=t[0],n=t[1];return e.eq(i.table[r],n)}));return t.where(e.and.apply(void 0,a)).limit(1)},[4,this.findAll(n)];case 2:return[2,t.sent()[0]]}}))}))},i.prototype.findAll=function(i){return t.__awaiter(this,void 0,void 0,(function(){var a,s,o,u=this;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.ready];case 1:return t.sent(),a=(new n.QueryBuilder).select().from(this.table),i&&(a=i(a)),[4,this.db.query(a.toSQL())];case 2:return s=t.sent(),o=function(t){return Object.entries(t).reduce((function(t,n){var i,a=n[0],s=n[1],o="jsonb"===(null===(i=e.getTableColumns(u.table)[a])||void 0===i?void 0:i.sqlName);return t[r.toCamelCase(a)]=o?JSON.parse(s):s,t}),{})},[2,s.map(o)]}}))}))},i.prototype.delete=function(r){return t.__awaiter(this,void 0,void 0,(function(){var n,i=this;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.ready];case 1:return t.sent(),n=function(t){if("function"==typeof r)return r(t);if("string"==typeof r){var n=i._getPrimaryCol();if(!n)throw new Error("Primary col is missing");return t.where(e.eq(n,r))}var a=Object.entries(r).map((function(t){var r=t[0],n=t[1];return e.eq(i.table[r],n)}));return t.where(e.and.apply(void 0,a))},[4,this.deleteAll(n)];case 2:return t.sent(),[2]}}))}))},i.prototype.deleteAll=function(e){return t.__awaiter(this,void 0,void 0,(function(){var r;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.ready];case 1:return t.sent(),r=new n.SQLiteDeleteBase(this.table,{},d),e&&(r=e(r)),[4,this.db.query(r.toSQL())];case 2:return t.sent(),[2]}}))}))},i.prototype.export=function(){return t.__awaiter(this,void 0,void 0,(function(){var e;return t.__generator(this,(function(r){switch(r.label){case 0:return[4,this.ready];case 1:return r.sent(),e=function(e,r){var n;return t.__assign(t.__assign({},e),((n={})[r.cid]=r,n))},[4,this.findAll()];case 2:return[2,r.sent().reduce(e,{})]}}))}))},i.prototype.import=function(e){return t.__awaiter(this,void 0,void 0,(function(){var r,n,i=this;return t.__generator(this,(function(a){switch(a.label){case 0:return[4,this.ready];case 1:return a.sent(),[4,this.deleteAll()];case 2:if(a.sent(),"object"!=typeof e)throw new Error("Invalid obj passed to store");return r=function(e){var r,n,i,a,s,o;if(!e.createdAt&&(null===(r=e.metadata)||void 0===r?void 0:r.createdOn)&&(e.createdAt=null===(n=e.metadata)||void 0===n?void 0:n.createdOn),!e.updatedAt&&(null===(i=e.metadata)||void 0===i?void 0:i.updatedOn)&&(e.updatedAt=null===(a=e.metadata)||void 0===a?void 0:a.updatedOn),!e.syncedAt&&(null===(s=e.metadata)||void 0===s?void 0:s.syncedOn)&&(e.syncedAt=null===(o=e.metadata)||void 0===o?void 0:o.syncedOn),e.samples){var u=e.id,c=e.cid,d=e.createdAt,l=e.updatedAt,f=e.syncedAt,h=t.__rest(e,["id","cid","createdAt","updatedAt","syncedAt"]);e={id:u,cid:c,createdAt:d,updatedAt:l,syncedAt:f,data:t.__assign({},h)}}return e},n=Object.entries(e).map((function(t){var e=t[1];return i.save(r(e))})),Promise.all(n),[2]}}))}))},i.prototype._getPrimaryCol=function(){return Object.values(e.getTableColumns(this.table)).find((function(t){return!!t.primary}))},i}();exports.conflictUpdateAllExcept=u,exports.default=f,exports.defaultCols=l,exports.jsonb=c;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("tslib"),e=require("drizzle-orm"),r=require("drizzle-orm/casing"),n=require("drizzle-orm/sqlite-core"),i=require("@flumens/utils"),a=require("./utils.js");function s(r,n){var i=e.getTableColumns(r);return Object.entries(i).filter((function(t){var e=t[0];return!n.includes(e)})).reduce((function(r,n){var i,a=n[0],s=n[1];return t.__assign(t.__assign({},r),((i={})[a]=e.sql.raw("excluded.".concat(s.name)),i))}),{})}var o=function(t){return n.customType({dataType:function(){return"jsonb"},toDriver:function(t){return JSON.stringify(t)}})(t)},u=new n.SQLiteSyncDialect,c=function(){return{id:n.text(),cid:n.text().primaryKey().notNull().default("id"),data:o("data").notNull(),createdAt:n.integer("created_at").notNull(),updatedAt:n.integer("updated_at").notNull(),syncedAt:n.integer("synced_at")}},d=function(){function o(t){var e=t.db,r=t.name,a=t.debug,s=t.columns,o=void 0===s?c():s;this.ready=new i.Deferred,this.db=e,this.name=r,this.debug=a||!1,this.table=n.sqliteTable(this.name,o),this.init()}return o.prototype.init=function(){return t.__awaiter(this,void 0,void 0,(function(){var e,r;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.db.ready];case 1:return t.sent(),e=function(t){return"".concat(t.name," ").concat(t.getSQLType()).concat(t.primary?" primary key":"").concat(t.notNull?" not null":"").concat(t.default?" default ".concat(t.default):"")},r=n.getTableConfig(this.table).columns.map(e).join(",\n"),[4,this.db.query({sql:"CREATE TABLE IF NOT EXISTS ".concat(this.name," (").concat(r,");")})];case 2:return t.sent(),this.ready.resolve(!0),[2]}}))}))},o.prototype.save=function(e){return t.__awaiter(this,void 0,void 0,(function(){var r,i,o;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.ready];case 1:return t.sent(),(Array.isArray(e)?e.length:e)?this.debug&&e.cid?[4,this.find({cid:e.cid})]:[3,3]:[2];case 2:r=t.sent(),a.printDiff(r,e,e.cid,this.name),t.label=3;case 3:return i=new n.SQLiteInsertBuilder(this.table,{},u).values(e),(o=this._getPrimaryCol())&&(i=i.onConflictDoUpdate({target:o,set:s(this.table,[])})),[4,this.db.query(i.toSQL())];case 4:return t.sent(),[2]}}))}))},o.prototype.find=function(r){return t.__awaiter(this,void 0,void 0,(function(){var n,i=this;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.ready];case 1:return t.sent(),n=function(t){if("function"==typeof r)return r(t).limit(1);if("string"==typeof r){var n=i._getPrimaryCol();if(!n)throw new Error("Primary col is missing");return t.where(e.eq(n,r)).limit(1)}var a=Object.entries(r).map((function(t){var r=t[0],n=t[1];return e.eq(i.table[r],n)}));return t.where(e.and.apply(void 0,a)).limit(1)},[4,this.findAll(n)];case 2:return[2,t.sent()[0]]}}))}))},o.prototype.findAll=function(i){return t.__awaiter(this,void 0,void 0,(function(){var a,s,o,u=this;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.ready];case 1:return t.sent(),a=(new n.QueryBuilder).select().from(this.table),i&&(a=i(a)),[4,this.db.query(a.toSQL())];case 2:return s=t.sent(),o=function(t){return Object.entries(t).reduce((function(t,n){var i,a=n[0],s=n[1],o="jsonb"===(null===(i=e.getTableColumns(u.table)[a])||void 0===i?void 0:i.sqlName);return t[r.toCamelCase(a)]=o?JSON.parse(s):s,t}),{})},[2,s.map(o)]}}))}))},o.prototype.delete=function(r){return t.__awaiter(this,void 0,void 0,(function(){var n,i=this;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.ready];case 1:return t.sent(),n=function(t){if("function"==typeof r)return r(t);if("string"==typeof r){var n=i._getPrimaryCol();if(!n)throw new Error("Primary col is missing");return t.where(e.eq(n,r))}var a=Object.entries(r).map((function(t){var r=t[0],n=t[1];return e.eq(i.table[r],n)}));return t.where(e.and.apply(void 0,a))},[4,this.deleteAll(n)];case 2:return t.sent(),[2]}}))}))},o.prototype.deleteAll=function(e){return t.__awaiter(this,void 0,void 0,(function(){var r;return t.__generator(this,(function(t){switch(t.label){case 0:return[4,this.ready];case 1:return t.sent(),r=new n.SQLiteDeleteBase(this.table,{},u),e&&(r=e(r)),[4,this.db.query(r.toSQL())];case 2:return t.sent(),[2]}}))}))},o.prototype.export=function(){return t.__awaiter(this,void 0,void 0,(function(){var e;return t.__generator(this,(function(r){switch(r.label){case 0:return[4,this.ready];case 1:return r.sent(),e=function(e,r){var n;return t.__assign(t.__assign({},e),((n={})[r.cid]=r,n))},[4,this.findAll()];case 2:return[2,r.sent().reduce(e,{})]}}))}))},o.prototype.import=function(e){return t.__awaiter(this,void 0,void 0,(function(){var r,n,i=this;return t.__generator(this,(function(a){switch(a.label){case 0:return[4,this.ready];case 1:return a.sent(),[4,this.deleteAll()];case 2:if(a.sent(),"object"!=typeof e)throw new Error("Invalid obj passed to store");return r=function(e){var r,n,i,a,s,o;if(!e.createdAt&&(null===(r=e.metadata)||void 0===r?void 0:r.createdOn)&&(e.createdAt=null===(n=e.metadata)||void 0===n?void 0:n.createdOn),!e.updatedAt&&(null===(i=e.metadata)||void 0===i?void 0:i.updatedOn)&&(e.updatedAt=null===(a=e.metadata)||void 0===a?void 0:a.updatedOn),!e.syncedAt&&(null===(s=e.metadata)||void 0===s?void 0:s.syncedOn)&&(e.syncedAt=null===(o=e.metadata)||void 0===o?void 0:o.syncedOn),e.samples){var u=e.id,c=e.cid,d=e.createdAt,l=e.updatedAt,f=e.syncedAt,h=t.__rest(e,["id","cid","createdAt","updatedAt","syncedAt"]);e={id:u,cid:c,createdAt:d,updatedAt:l,syncedAt:f,data:t.__assign({},h)}}return e},n=Object.entries(e).map((function(t){var e=t[1];return i.save(r(e))})),Promise.all(n),[2]}}))}))},o.prototype._getPrimaryCol=function(){return Object.values(e.getTableColumns(this.table)).find((function(t){return!!t.primary}))},o}();exports.conflictUpdateAllExcept=s,exports.default=d,exports.defaultCols=c,exports.jsonb=o;
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "@flumens/models",
3
- "version": "0.5.3",
3
+ "version": "0.7.0",
4
4
  "main": "dist/index.js",
5
- "types": "dist/src/index.d.ts",
5
+ "types": "dist/index.d.ts",
6
6
  "scripts": {
7
7
  "build": "rollup -c",
8
8
  "build:watch": "rollup -c -w",
9
- "prepare": "npm run build",
10
9
  "test:eslint": "eslint src --quiet --ext .jsx --ext .ts --ext .tsx --ext .js && echo '\\033[37;42;1m PASS \\033[00m'",
10
+ "prepare": "npm run build",
11
11
  "postpublish": "TAG_NAME=models-v\"$npm_package_version\" && git tag $TAG_NAME && git push origin \"$TAG_NAME\"",
12
12
  "test": "jest --passWithNoTests",
13
13
  "test:watch": "jest --watchAll"
@@ -15,20 +15,17 @@
15
15
  "author": "Flumens",
16
16
  "license": "GNU GPL v3",
17
17
  "devDependencies": {
18
- "@rollup/plugin-json": "6.0.0",
19
- "@rollup/plugin-node-resolve": "13.3.0",
20
- "@rollup/plugin-typescript": "8.3.2",
21
- "@trivago/prettier-plugin-sort-imports": "4.3.0",
22
- "@types/react": "18.2.38",
23
- "@types/react-dom": "18.2.17",
24
- "prettier": "3.2.5",
25
- "react": "^18.2.0",
26
- "react-dom": "^18.2.0",
18
+ "@rollup/plugin-json": "6.1.0",
19
+ "@rollup/plugin-node-resolve": "16.0.0",
20
+ "@rollup/plugin-typescript": "12.1.2",
21
+ "@trivago/prettier-plugin-sort-imports": "5.2.2",
22
+ "@types/wellknown": "^0.5.8",
23
+ "prettier": "3.5.0",
27
24
  "rollup-plugin-clear": "2.0.7",
28
25
  "rollup-plugin-copy": "3.5.0",
29
26
  "rollup-plugin-terser": "7.0.2",
30
- "tslib": "2.6.2",
31
- "typescript": "4.9.4"
27
+ "tslib": "2.8.1",
28
+ "typescript": "5.7.3"
32
29
  },
33
30
  "peerDependencies": {
34
31
  "@flumens/utils": "*"
@@ -38,13 +35,14 @@
38
35
  "@capacitor/filesystem": "^6 || ^7",
39
36
  "@capacitor-community/sqlite": "^6 || ^7",
40
37
  "deep-diff": "^1",
41
- "drizzle-orm": "^0.34.1",
42
- "jeep-sqlite": "^2.8.0",
38
+ "drizzle-orm": "^0.39.3",
39
+ "jeep-sqlite": "^2",
43
40
  "jwt-decode": "^4",
44
41
  "localforage": "^1",
45
42
  "localforage-cordovasqlitedriver": "^1",
46
43
  "mobx-utils": "^6",
47
- "zod": "^3"
44
+ "zod": "^3",
45
+ "wellknown": "^0.5.0"
48
46
  },
49
47
  "jest": {
50
48
  "testEnvironment": "jsdom",