@flumens/models 0.2.1 → 0.3.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.
@@ -37,9 +37,8 @@ export interface Options extends GenericModelOptions {
37
37
  */
38
38
  config: BackendConfig;
39
39
  }
40
- export default class DrupalUserModel extends Model {
40
+ export default class DrupalUserModel<T extends Attrs = Attrs> extends Model<T> {
41
41
  config: BackendConfig;
42
- attrs: Attrs;
43
42
  loginSchema: AnySchema;
44
43
  loginSchemaBackend: AnySchema;
45
44
  resetSchema: AnySchema;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("axios"),r=require("jwt-decode"),s=require("yup"),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 i=this,a=r.config,o=e.__rest(r,["config"]);return(i=t.call(this,o)||this).attrs=n.default.extendAttrs(i.attrs,d),i.loginSchema=s.object().shape({email:s.string().email().required(),password:s.string().required()}),i.loginSchemaBackend=s.object().shape({id:s.number().required(),email:s.string().email().required()}),i.resetSchema=s.object().shape({email:s.string().email().required()}),i.registerSchema=s.object().shape({email:s.string().email().required(),password:s.string().required()}),i.registerSchemaBackend=s.object().shape({uid:s.array().of(s.object().shape({value:s.number().required()}))}),i.config=a,i}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 i,n,a,d;return e.__generator(this,(function(l){switch(l.label){case 0:return i=JSON.stringify(e.__assign({name:[{value:t}],pass:[{value:r}],mail:[{value:t}]},s)),n={method:"post",url:"".concat(this.config.url,"/user/register-with-password?_format=json"),headers:{"content-type":"application/json"},data:i,timeout:h},[4,o.default(n).catch(u)];case 1:return a=l.sent().data,[4,this.registerSchemaBackend.isValid(a)];case 2:if(!l.sent())throw new Error("Invalid backend response.");return[4,this._exchangePasswordToTokens(t,r)];case 3:return d=l.sent(),this.attrs.tokens=d,this.id=a.uid[0].value,this.attrs.email=t,c(this.attrs,a),[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}(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("yup"),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 i=this,n=r.config,a=e.__rest(r,["config"]);return(i=t.call(this,e.__assign(e.__assign({},a),{attrs:e.__assign(e.__assign({},d),a.attrs)}))||this).loginSchema=s.object().shape({email:s.string().email().required(),password:s.string().required()}),i.loginSchemaBackend=s.object().shape({id:s.number().required(),email:s.string().email().required()}),i.resetSchema=s.object().shape({email:s.string().email().required()}),i.registerSchema=s.object().shape({email:s.string().email().required(),password:s.string().required()}),i.registerSchemaBackend=s.object().shape({uid:s.array().of(s.object().shape({value:s.number().required()}))}),i.config=n,i}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 i,n,a,d;return e.__generator(this,(function(l){switch(l.label){case 0:return i=JSON.stringify(e.__assign({name:[{value:t}],pass:[{value:r}],mail:[{value:t}]},s)),n={method:"post",url:"".concat(this.config.url,"/user/register-with-password?_format=json"),headers:{"content-type":"application/json"},data:i,timeout:h},[4,o.default(n).catch(u)];case 1:return a=l.sent().data,[4,this.registerSchemaBackend.isValid(a)];case 2:if(!l.sent())throw new Error("Invalid backend response.");return[4,this._exchangePasswordToTokens(t,r)];case 3:return d=l.sent(),this.attrs.tokens=d,this.id=a.uid[0].value,this.attrs.email=t,c(this.attrs,a),[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}(n.default);exports.default=l;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t,e=require("tslib"),r=require("mobx"),i=require("@flumens/utils/dist/image"),a=require("../Model.js"),n=require("./helpers.js"),o=!!window.cordova||!!(null===(t=null===window||void 0===window?void 0:window.Capacitor)||void 0===t?void 0:t.isNative),s=function(t){function a(i){var a=this;void 0===i&&(i={});var n=i.metadata,o=void 0===n?{}:n,s=e.__rest(i,["metadata"]);return(a=t.call(this,s)||this).remote={synchronising:!1,url:null,headers:{},timeout:12e4},a.debouncedValue=300,a.parent=a.parent,a.metadata=r.observable(o),a}return e.__extends(a,t),a.fromJSON=function(t){var r,i,a;return new this(e.__assign(e.__assign({},t),{createdAt:t.createdAt||(null===(r=t.metadata)||void 0===r?void 0:r.createdOn),updatedAt:t.updatedAt||(null===(i=t.metadata)||void 0===i?void 0:i.updatedOn),syncedAt:t.syncedAt||(null===(a=t.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(t,r,a){return e.__awaiter(this,void 0,void 0,(function(){var n,s,d,u,h,c,l;return e.__generator(this,(function(e){switch(e.label){case 0:if(n=this,!t)throw new Error("File not found while creating image model.");return o?[4,i.createImage(t)]:[3,2];case 1:return h=e.sent(),s=h.width,d=h.height,u=t.split("/").pop(),[3,4];case 2:return[4,n.getDataURI(t,{width:2e3,height:2e3})];case 3:l=e.sent(),u=l[0],s=l[2],d=l[3],e.label=4;case 4:return c=new n({attrs:{data:u,type:"jpeg",width:s,height:d,path:r}}),a?[3,6]:[4,c.addThumbnail()];case 5:e.sent(),e.label=6;case 6:return[2,c]}}))}))},a.prototype.toJSON=function(){var i=t.prototype.toJSON.call(this);return JSON.parse(JSON.stringify(e.__assign(e.__assign({},i),{metadata:r.toJS(this.metadata)||{}})))},a.prototype.setupdatedAtTimestamp=function(e){var r;t.prototype.setUpdatedAtTimestamp.call(this,e),null===(r=this.parent)||void 0===r||r.setUpdatedAtTimestamp(e)},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 e.__awaiter(this,void 0,void 0,(function(){return e.__generator(this,(function(e){return[2,this.parent?this.parent.sync():t.prototype.sync.call(this)]}))}))},a.prototype.uploadFile=function(){var t;return e.__awaiter(this,void 0,void 0,(function(){var r,i,a,o,s,d;return e.__generator(this,(function(e){switch(e.label){case 0:if(this.id)throw new Error("A file of a media on the remote cannot be uploaded again.");return[4,this.getFormData()];case 1:return r=e.sent(),i=new FormData,(d=i).append.apply(d,r),"function"!=typeof this.remote.headers?[3,3]:[4,this.remote.headers()];case 2:return a=e.sent(),[3,4];case 3:a=this.remote.headers,e.label=4;case 4:return o={method:"POST",headers:a,body:i},[4,n.makeRequest("".concat(this.remote.url,"/media-queue"),o)];case 5:if(s=e.sent(),!(null===(t=s[this.cid])||void 0===t?void 0:t.name))throw new Error("New remote media name was not be found.");return this.attrs.queued=s[this.cid].name,this.syncedAt=(new Date).getTime(),[2]}}))}))},a.prototype.getFormData=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r,i,a,o,s,d;return e.__generator(this,(function(e){switch(e.label){case 0:return t=this.attrs.type,r=t,i=t,(null==t?void 0:t.match(/image.*/))?(d=t.split("/"),r=d[1]):i="image/".concat(i),a=this.getURL(),[4,n.getBlobFromURL(a,i)];case 1:return o=e.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=s;
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(){var e;return t.__awaiter(this,void 0,void 0,(function(){var r,i,a,n,o,s;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[4,this.getFormData()];case 1:return r=t.sent(),i=new FormData,(s=i).append.apply(s,r),"function"!=typeof this.remote.headers?[3,3]:[4,this.remote.headers()];case 2:return n=t.sent(),[3,4];case 3:n=this.remote.headers,t.label=4;case 4:return a=n,[4,d.default.post("".concat(this.remote.url,"/media-queue"),i,{headers:a,timeout:12e4})];case 5:if(o=t.sent(),!(null===(e=o.data[this.cid])||void 0===e?void 0:e.name))throw new Error("New remote media name was not be found.");return this.attrs.queued=o.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;
@@ -11,7 +11,7 @@ type ModelWithSubmodels = {
11
11
  samples?: Sample[];
12
12
  media?: Media[];
13
13
  };
14
- export declare const _getMediaFormData: (model: ModelWithSubmodels) => Promise<any[]>;
14
+ export declare const getMediaFormData: (model: ModelWithSubmodels) => Promise<any[]>;
15
15
  export interface Options<T = any, S = any> extends OptionsOriginal<T> {
16
16
  metadata?: S;
17
17
  occurrences?: any[];
@@ -61,7 +61,7 @@ export interface Survey extends BaseSurvey {
61
61
  smp?: Survey;
62
62
  occ?: BaseSurvey;
63
63
  }
64
- declare class Sample<T extends Attrs = Attrs, S extends Metadata = Metadata> extends Model {
64
+ declare class Sample<T extends Attrs = Attrs, S extends Metadata = Metadata> extends Model<T> {
65
65
  static fromJSON(jsonProp: any, OccurrenceClass?: any, Sample?: any, // eslint-disable-line
66
66
  MediaClass?: any): Sample<Attrs, Metadata>;
67
67
  /**
@@ -96,10 +96,6 @@ declare class Sample<T extends Attrs = Attrs, S extends Metadata = Metadata> ext
96
96
  * Model persistent observable metadata.
97
97
  */
98
98
  metadata: S;
99
- /**
100
- * Model's persistent observable attributes.
101
- */
102
- attrs: T;
103
99
  remote: Remote;
104
100
  validateRemote: any;
105
101
  error: {
@@ -131,11 +127,11 @@ declare class Sample<T extends Attrs = Attrs, S extends Metadata = Metadata> ext
131
127
  sync(): Promise<void>;
132
128
  requiresRemoteSync: () => boolean;
133
129
  saveRemote(): Promise<void>;
130
+ private postRemote;
134
131
  fetchRemote(): Promise<void>;
135
132
  updateRemote(): Promise<void>;
136
- private _createRemote;
137
- private _updateRemote;
138
- private _uploadMedia;
133
+ private putRemote;
134
+ private uploadMedia;
139
135
  getSubmission(warehouseMediaNames?: {}): any;
140
136
  isUploaded(): boolean;
141
137
  isDisabled(): boolean;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("mobx"),r=require("lodash"),s=require("@flumens/utils/dist/errors"),n=require("../Model.js"),a=require("./Media.js"),i=require("./Occurrence.js"),o=require("./helpers.js");function u(e,t){var r,s,n;t&&t.values?(e.id=t.values.id,e.samples&&t.samples&&(null===(r=e.samples)||void 0===r||r.forEach((function(e,r){return u(e,t.samples[r])}))),e.occurrences&&t.occurrences&&(null===(s=e.occurrences)||void 0===s||s.forEach((function(e,r){return u(e,t.occurrences[r])}))),e.media&&t.media&&(null===(n=e.media)||void 0===n||n.forEach((function(e,r){return u(e,t.media[r])})))):console.warn("Model didn't receive an id from the server")}var c=function(t){return e.__awaiter(void 0,void 0,void 0,(function(){var r,s,n;return e.__generator(this,(function(e){switch(e.label){case 0:return r=[],t.media?(s=function(e){return e.getFormData()},[4,Promise.all(t.media.map(s))]):[3,2];case 1:n=e.sent(),r.push.apply(r,n),e.label=2;case 2:return t.occurrences?[4,Promise.all(t.occurrences.map(c))]:[3,4];case 3:n=e.sent(),r.push.apply(r,n.flat()),e.label=4;case 4:return t.samples?[4,Promise.all(t.samples.map(c))]:[3,6];case 5:n=e.sent(),r.push.apply(r,n.flat()),e.label=6;case 6:return[2,r]}}))}))};function d(e,t){var r={values:{id:t||-1}};return e.occurrences&&(r.occurrences=e.occurrences.map((function(e){return d(e)}))),e.samples&&(r.samples=e.samples.map((function(e){return d(e)}))),e.media&&(r.media=e.media.map((function(e){return d(e)}))),r}function l(e){try{console.warn(JSON.stringify(e).substring(0,1e5))}catch(e){}}var h=function(n){function h(r){var s=this;void 0===r&&(r={});var a=r.metadata,i=void 0===a?{}:a,u=r.samples,c=void 0===u?[]:u,d=r.occurrences,l=void 0===d?[]:d,m=r.media,p=void 0===m?[]:m,f=r.attrs,v=void 0===f?{}:f,_=e.__rest(r,["metadata","samples","occurrences","media","attrs"]);(s=n.call(this,e.__assign(e.__assign({},_),{attrs:e.__assign({date:(new Date).toISOString(),location_type:"latlon"},v)}))||this).remote=t.observable({synchronising:!1,url:null,headers:{},timeout:12e4}),s.validateRemote=o.validateRemoteModel,s.error=t.observable({message:""}),s.debouncedValue=300,s.keys=function(){return e.__assign(e.__assign({},h.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))}),{})}(s.getSurvey().attrs||{}))},s.requiresRemoteSync=function(){return!s.syncedAt||s.updatedAt>s.syncedAt},s.metadata=t.observable(i),s.samples=t.observable(c),s.occurrences=t.observable(l),s.media=t.observable(p);var y=function(e){return e.parent=s};s.samples.forEach(y),s.occurrences.forEach(y),s.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),s.setupdatedAtTimestamp(Date.now())):e.removedCount&&s.setupdatedAtTimestamp(Date.now()),e};return t.intercept(s.samples,g),t.intercept(s.occurrences,g),t.intercept(s.media,g),s}return e.__extends(h,n),h.fromJSON=function(t,r,s,n){var o,u,c,d,l,h,m;void 0===r&&(r=i.default),void 0===s&&(s=this),void 0===n&&(n=a.default);var p=(null===(o=null==t?void 0:t.attrs)||void 0===o?void 0:o.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)}))}))},h.prototype.setupdatedAtTimestamp=function(e){var t;n.prototype.setUpdatedAtTimestamp.call(this,e),null===(t=this.parent)||void 0===t||t.setupdatedAtTimestamp(e)},h.prototype.toJSON=function(){var r,s,a,i,o=n.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===(r=this.samples)||void 0===r?void 0:r.map((function(e){return e.toJSON()})))||[],media:(null===(s=this.media)||void 0===s?void 0:s.map((function(e){return e.toJSON()})))||[]}})))},h.prototype.getSurvey=function(){return this.survey?this.parent?this.parent.getSurvey().smp||{}:this.survey:{}},h.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]}}))}))},h.prototype.destroy=function(t){return e.__awaiter(this,void 0,void 0,(function(){var r,s=this;return e.__generator(this,(function(e){switch(e.label){case 0:return r=function(){return Promise.all([Promise.all(s.media.map((function(e){return e.destroy(!0)}))),Promise.all(s.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(),this.collection&&this.collection.remove(this),[4,r()];case 4:return e.sent(),this.attrs.deleted=!0,[2]}}))}))},h.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)]}))}))},h.prototype.saveRemote=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r,s,n,a,i;return e.__generator(this,(function(e){switch(e.label){case 0:if(e.trys.push([0,6,,7]),!this.remote.url)throw new Error('A "remote" property is not configured.');t=void 0,e.label=1;case 1:return e.trys.push([1,4,,5]),this.remote.synchronising=!0,[4,this._uploadMedia()];case 2:return r=e.sent(),t=this.getSubmission(r),[4,this._createRemote(t)];case 3:return s=e.sent(),this.remote.synchronising=!1,u(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.payload=t,a;case 5:return[3,7];case 6:throw 400===(i=e.sent()).status&&i.payload&&l(i.payload),i;case 7:return[2]}}))}))},h.prototype.fetchRemote=function(){return e.__awaiter(this,void 0,void 0,(function(){return e.__generator(this,(function(e){throw new Error("Not implemented.")}))}))},h.prototype.updateRemote=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r,s,n,a,i;return e.__generator(this,(function(e){switch(e.label){case 0:if(e.trys.push([0,5,,6]),!this.remote.url)throw new Error('A "remote" property is not configured.');t=void 0,e.label=1;case 1:return e.trys.push([1,3,,4]),this.remote.synchronising=!0,r={},t=this.getSubmission(r),[4,this._updateRemote(this.id,t)];case 2:return s=e.sent(),this.remote.synchronising=!1,u(this,s),n=(new Date).getTime(),this.updatedAt=n,this.syncedAt=n,this.save(),[3,4];case 3:throw a=e.sent(),this.remote.synchronising=!1,a.payload=t,a;case 4:return[3,6];case 5:throw 400===(i=e.sent()).status&&i.payload&&l(i.payload),i;case 6:return[2]}}))}))},h.prototype._createRemote=function(t){return e.__awaiter(this,void 0,void 0,(function(){var r,n,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 n=e.sent(),[3,3];case 2:n=this.remote.headers,e.label=3;case 3:a={method:"POST",headers:n,body:JSON.stringify(t)},e.label=4;case 4:return e.trys.push([4,6,,7]),[4,o.makeRequest("".concat(r,"/samples"),a)];case 5:return[2,e.sent()];case 6:if(409===(i=e.sent()).status&&i.res&&i.res.duplicate_of)return[2,d(this,i.res.duplicate_of.id)];if("timeout"===i.message)throw new s.HandledError("Request aborted because of a network issue (timeout or similar).");throw i;case 7:return[2]}}))}))},h.prototype._updateRemote=function(t,r){return e.__awaiter(this,void 0,void 0,(function(){var n,a,i,u;return e.__generator(this,(function(e){switch(e.label){case 0:return n=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:i={method:"PUT",headers:a,body:JSON.stringify(r)},e.label=4;case 4:return e.trys.push([4,6,,7]),[4,o.makeRequest("".concat(n,"/samples/").concat(t),i)];case 5:return[2,e.sent()];case 6:if(409===(u=e.sent()).status&&u.res&&u.res.duplicate_of)return[2,d(this,u.res.duplicate_of.id)];if("timeout"===u.message)throw new s.HandledError("Request aborted because of a network issue (timeout or similar).");throw u;case 7:return[2]}}))}))},h.prototype._uploadMedia=function(){return e.__awaiter(this,void 0,void 0,(function(){var t,r,n,a,i,u,d=this;return e.__generator(this,(function(l){switch(l.label){case 0:return t={},[4,c(this)];case 1:if(r=l.sent(),!r.length)return[2,t];n=function(t){return e.__awaiter(d,void 0,void 0,(function(){var r,n,a;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 n=e.sent(),[3,3];case 2:n=this.remote.headers,e.label=3;case 3:a={method:"POST",headers:n,body:t};try{return[2,o.makeRequest("".concat(r,"/media-queue"),a)]}catch(e){if("timeout"===e.message)throw new s.HandledError("Request aborted because of a network issue (timeout or similar).");throw e}return[2]}}))}))},a=5,i=function(s){var i,o,u;return e.__generator(this,(function(c){switch(c.label){case 0:return i=r.slice(s,s+a),o=new FormData,i.forEach((function(e){return o.append.apply(o,e)})),[4,n(o)];case 1:return u=c.sent(),t=e.__assign(e.__assign({},t),u),[2]}}))},u=0,l.label=2;case 2:return u<r.length?[5,i(u)]:[3,5];case 3:l.sent(),l.label=4;case 4:return u+=a,[3,2];case 5:return[2,t]}}))}))},h.prototype.getSubmission=function(t){var s=this;void 0===t&&(t={});var n="function"==typeof this.keys?this.keys():this.keys,a=e.__assign(e.__assign({},h.keys),n),i={values:{external_key:this.cid},media:[],samples:[],occurrences:[]};this.id&&(i.values.id=this.id);var o=function(e,t){var r=a[e].values;if(!r)return t;if("function"==typeof r)return r(t,i,s);if(t instanceof Array)return t.map((function(t){return o(e,t)}));if(r instanceof Array){var n=r.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 r[t]};Object.keys(this.attrs).forEach((function(e){var t=s.attrs[e],n=function(e){return null==e};if(!n(t)){if(!a[e])return e=e.includes("smpAttr:")?e:r.snakeCase(e),void(i.values[e]=t);if(!n(t=o(e,t))){var u=a[e].id||e,c=Number.isNaN(Number(u))?u:"smpAttr:".concat(u);c=c.includes("smpAttr:")?c:r.snakeCase(c),i.values[c]=t}}})),this.samples.forEach((function(e){s.attrs.training&&(e.attrs.training=s.attrs.training);var r=e.getSubmission(t);r&&i.samples.push(r)})),this.occurrences.forEach((function(e){s.attrs.training&&(e.attrs.training=s.attrs.training);var r=e.getSubmission(t);r&&i.occurrences.push(r)})),this.media.forEach((function(e){var r=e.getSubmission(t);r&&i.media.push(r)}));var u=this.getSurvey();return u.modifySubmission?u.modifySubmission(i,this):i},h.prototype.isUploaded=function(){return this.parent?this.parent.isUploaded():!!this.syncedAt},h.prototype.isDisabled=function(){return this.isUploaded()},h.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:o.boolToWarehouseValue},deleted:{id:"deleted",values:o.boolToWarehouseValue}},h}(n.default);exports._getMediaFormData=c,exports.default=h;
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"]),y={date:(new Date).toISOString(),location_type:"latlon"};(n=r.call(this,e.__assign(e.__assign({},_),{attrs:e.__assign(e.__assign({},y),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 g=function(e){return e.parent=n};n.samples.forEach(g),n.occurrences.forEach(g),n.media.forEach(g);var w=function(e){var t;return(null===(t=e.added)||void 0===t?void 0:t.length)?(e.added.forEach(g),n.setupdatedAtTimestamp(Date.now())):e.removedCount&&n.setupdatedAtTimestamp(Date.now()),e};return t.intercept(n.samples,w),t.intercept(n.occurrences,w),t.intercept(n.media,w),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){return e.__awaiter(this,void 0,void 0,(function(){var r,s=this;return e.__generator(this,(function(e){switch(e.label){case 0:return r=function(){return Promise.all([Promise.all(s.media.map((function(e){return e.destroy(!0)}))),Promise.all(s.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(),this.collection&&this.collection.remove(this),[4,r()];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,9 +1,4 @@
1
- export declare class SyncError extends Error {
2
- status?: number;
3
- res?: any;
4
- payload?: any;
5
- }
6
- export declare function makeRequest(url: string, options: RequestInit, timeout?: number): Promise<any>;
1
+ export declare const getErrorMessageFromObject: (errors: any) => string;
7
2
  /**
8
3
  * Converts DataURI object to a Blob.
9
4
  *
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=function(t){function r(){return null!==t&&t.apply(this,arguments)||this}return e.__extends(r,t),r}(Error);function r(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 s(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.SyncError=t,exports.boolToWarehouseValue=function(e){return!0===e||"t"===e?"t":"f"},exports.dataURItoBlob=r,exports.getBlobFromURL=function(e,t){if(s(e)){var n=r(e,t);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.isDataURL=s,exports.makeRequest=function(r,s,n){return void 0===n&&(n=12e4),e.__awaiter(this,void 0,void 0,(function(){var o,i,a,u,c,l;return e.__generator(this,(function(e){switch(e.label){case 0:return o=new Promise((function(e,t){setTimeout((function(){return t(new Error("timeout"))}),n)})),[4,Promise.race([fetch(r,s),o])];case 1:i=e.sent(),a={},e.label=2;case 2:return e.trys.push([2,4,,5]),[4,i.text()];case 3:return a=e.sent(),a=JSON.parse(a),[3,5];case 4:if(u=e.sent(),201!==i.status||!a.includes("Document Moved"))throw u;return a=JSON.parse(a.slice(a.indexOf('{"values'))),[3,5];case 5:if(!i.ok)throw c=i.statusText,"object"==typeof a.message&&(d=a.message,c=Object.entries(d).reduce((function(e,t){return"".concat(e).concat(t[0]," ").concat(t[1],"\n")}),"")),(l=new t(c)).status=i.status,l.res=a,l;return[2,a]}var d}))}))},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]),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};
package/dist/Model.d.ts CHANGED
@@ -15,11 +15,7 @@ export interface Attrs {
15
15
  */
16
16
  deleted?: boolean;
17
17
  }
18
- export default class Model {
19
- /**
20
- * Extends observable attributes.
21
- */
22
- static extendAttrs: (obj1: any, obj2: any) => any;
18
+ export default class Model<T extends Attrs = Attrs> {
23
19
  /**
24
20
  * Remote server document ID.
25
21
  */
@@ -43,11 +39,18 @@ export default class Model {
43
39
  /**
44
40
  * Model's persistent observable attributes.
45
41
  */
46
- attrs: Attrs;
42
+ attrs: T;
47
43
  /**
48
44
  * The offline store used to save and fetch the model from.
49
45
  */
50
- protected store?: Store;
46
+ protected store?: Store<{
47
+ id?: string;
48
+ cid: string;
49
+ data: T;
50
+ createdAt: number;
51
+ updatedAt: number;
52
+ syncedAt?: number | null;
53
+ }>;
51
54
  /**
52
55
  * A deferred promise to flag if the model was initialised from the store.
53
56
  */
@@ -55,6 +58,7 @@ export default class Model {
55
58
  protected debouncedValue: number;
56
59
  constructor({ id, cid, createdAt, updatedAt, syncedAt, attrs, store, }: Options);
57
60
  setUpdatedAtTimestamp(newUpdatedAt: number): void;
61
+ private _observerPaused;
58
62
  /**
59
63
  * Initialize the model from store.
60
64
  */
@@ -77,7 +81,7 @@ export default class Model {
77
81
  createdAt: number;
78
82
  updatedAt: number;
79
83
  syncedAt: number | null | undefined;
80
- attrs: Attrs;
84
+ attrs: T;
81
85
  };
82
86
  resetDefaults(defaultsToSet?: any): Promise<void>;
83
87
  }
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.id=u,this.cid=h||u||o.default();var b,A,g=Date.now();this.createdAt=l||g,this.updatedAt=f||g,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.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),e.set(this.attrs,s.data),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.extendAttrs=function(s,r){return e.set(s,t.__assign(t.__assign({},r),s)),s},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/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;
@@ -10,7 +10,7 @@ interface Query {
10
10
  params?: unknown[];
11
11
  }
12
12
  export default class SQLiteDatabase {
13
- static migrateCordova(): Promise<void>;
13
+ static migrateCordova(isIOS?: boolean): Promise<void>;
14
14
  sqliteConnection: SQLiteConnection;
15
15
  private connection?;
16
16
  private get db();
@@ -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");function i(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var r=i(require("@flumens/utils/dist/deferred")),s=function(){function i(e){var t=e.name,i=e.debug,s=e.web;this.sqliteConnection=new n.SQLiteConnection(n.CapacitorSQLite),this.name="main",this.debug=!1,this.isWeb=!1,this.ready=new r.default,this.name=t||this.name,this.debug=i||this.debug,this.isWeb=s||this.isWeb}return i.migrateCordova=function(){var t;return e.__awaiter(this,void 0,void 0,(function(){var i,r,s;return e.__generator(this,(function(e){switch(e.label){case 0:i=new n.SQLiteConnection(n.CapacitorSQLite),e.label=1;case 1:return e.trys.push([1,5,,6]),[4,i.getMigratableDbList()];case 2:return r=e.sent(),(null===(t=r.values)||void 0===t?void 0:t.length)?(console.log(r.values),[4,i.addSQLiteSuffix(void 0,r.values)]):[2];case 3:return e.sent(),[4,i.deleteOldDatabases(void 0,r.values)];case 4:return e.sent(),[3,6];case 5:return s=e.sent(),console.error(s),[3,6];case 6:return[4,i.checkConnectionsConsistency()];case 7:return e.sent(),[4,i.closeAllConnections()];case 8:return e.sent(),[2]}}))}))},Object.defineProperty(i.prototype,"db",{get:function(){return this.connection},enumerable:!1,configurable:!0}),i.prototype.init=function(){return e.__awaiter(this,void 0,void 0,(function(){var n,i;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(),i=this,[4,this.sqliteConnection.createConnection(this.name,!1,"no-encryption",1,!1)];case 6:return i.connection=e.sent(),[4,this.connection.open()];case 7:return e.sent(),this.ready.resolve(!0),[2]}}))}))},i.prototype.query=function(t){var n,i=t.sql,r=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(i,r).then((function(e){return e.values||[]}))];case 2:return t=e.sent(),this.debug?(console.groupCollapsed("💾 SQL: ".concat(i.trimStart().replaceAll(/\n/g," ").replaceAll(/\s+/g," ").substring(0,30),"...")),console.debug(i,r,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]}}))}))},i.prototype.getUrl=function(){return e.__awaiter(this,void 0,void 0,(function(){return e.__generator(this,(function(e){switch(e.label){case 0:return this.isWeb?[2,""]:[4,this.db.getUrl()];case 1:return[2,e.sent().url]}}))}))},i}();exports.default=s;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("jeep-sqlite/loader"),n=require("@capacitor-community/sqlite");function i(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var r=i(require("@flumens/utils/dist/deferred")),s=function(){function i(e){var t=e.name,i=e.debug,s=e.web;this.sqliteConnection=new n.SQLiteConnection(n.CapacitorSQLite),this.name="main",this.debug=!1,this.isWeb=!1,this.ready=new r.default,this.name=t||this.name,this.debug=i||this.debug,this.isWeb=s||this.isWeb}return i.migrateCordova=function(t){var i;return e.__awaiter(this,void 0,void 0,(function(){var r,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 s=e.sent(),(null===(i=s.values)||void 0===i?void 0:i.length)?(console.log("SQLite: migrating",s.values),[4,r.addSQLiteSuffix(t?"Library/LocalDatabase":void 0,s.values)]):(console.log("SQLite: no Cordova db to migrate"),[2]);case 3:return e.sent(),[4,r.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,r.checkConnectionsConsistency()];case 7:return e.sent(),[4,r.closeAllConnections()];case 8:return e.sent(),[2]}}))}))},Object.defineProperty(i.prototype,"db",{get:function(){return this.connection},enumerable:!1,configurable:!0}),i.prototype.init=function(){return e.__awaiter(this,void 0,void 0,(function(){var n,i;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(),i=this,[4,this.sqliteConnection.createConnection(this.name,!1,"no-encryption",1,!1)];case 6:return i.connection=e.sent(),[4,this.connection.open()];case 7:return e.sent(),this.ready.resolve(!0),[2]}}))}))},i.prototype.query=function(t){var n,i=t.sql,r=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(i,r).then((function(e){return e.values||[]}))];case 2:return t=e.sent(),this.debug?(console.groupCollapsed("💾 SQL: ".concat(i.trimStart().replaceAll(/\n/g," ").replaceAll(/\s+/g," ").substring(0,30),"...")),console.debug(i,r,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]}}))}))},i.prototype.getUrl=function(){return e.__awaiter(this,void 0,void 0,(function(){return e.__generator(this,(function(e){switch(e.label){case 0:return this.isWeb?[2,""]:[4,this.db.getUrl()];case 1:return[2,e.sent().url]}}))}))},i}();exports.default=s;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flumens/models",
3
- "version": "0.2.1",
3
+ "version": "0.3.0",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/src/index.d.ts",
6
6
  "scripts": {