@flumens/models 0.29.1 → 0.31.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,19 +1,16 @@
1
+ import { IObservableArray } from 'mobx';
1
2
  import { Deferred } from '@flumens/utils';
2
3
  import ModelClass from './Model';
3
- import Store from './Stores/Store';
4
- interface IObservableArray<T = any> extends Array<T> {
5
- spliceWithArray(index: number, deleteCount?: number, newItems?: T[]): T[];
6
- clear(): T[];
7
- replace(newItems: T[]): T[];
8
- remove(value: T): boolean;
9
- toJSON(): T[];
10
- }
4
+ export type ModelConstructor<T extends ModelClass> = new (...args: never[]) => T;
5
+ type CollectionStore = {
6
+ findAll(query?: unknown): Promise<unknown[]>;
7
+ };
11
8
  export type Options<T extends ModelClass> = {
12
9
  data?: T[];
13
10
  id?: string;
14
11
  cid?: string;
15
- store?: Store;
16
- Model?: any;
12
+ store?: CollectionStore;
13
+ Model?: ModelConstructor<T>;
17
14
  };
18
15
  export default class Collection<T extends ModelClass> {
19
16
  /**
@@ -33,16 +30,16 @@ export default class Collection<T extends ModelClass> {
33
30
  /**
34
31
  * The offline store used to save and fetch the model from.
35
32
  */
36
- protected store?: Store;
33
+ protected store?: CollectionStore;
37
34
  /**
38
35
  * A promise to flag if all the models were initialised from the store.
39
36
  */
40
37
  readonly ready: Deferred<boolean>;
41
- Model: new (args: any) => T;
42
- constructor({ id, cid, data, store, Model }: Options<T>);
38
+ Model: ModelConstructor<T>;
39
+ constructor({ id, cid, data, store, Model, }: Options<T>);
43
40
  fetch(): Promise<void>;
44
41
  reset(): Promise<void>;
45
- filter(predicate: (value: T, index: number, array: T[]) => any): T[];
42
+ filter(predicate: (value: T, index: number, array: T[]) => unknown): T[];
46
43
  push(...items: T[]): number;
47
44
  pop(): T | undefined;
48
45
  find(predicate: (value: T, index: number, obj: T[]) => unknown): T | undefined;
@@ -1,5 +1,19 @@
1
1
  import { z } from 'zod';
2
+ import { HandledError } from '@flumens/utils';
2
3
  import Model, { Data as GenericModelData, Options as GenericModelOptions } from '../Model';
4
+ export declare enum DrupalUserErrorCode {
5
+ EmailTaken = "AUTH_EMAIL_TAKEN",
6
+ InvalidCredentials = "AUTH_INVALID_CREDENTIALS",
7
+ UnrecognizedEmail = "AUTH_UNRECOGNIZED_EMAIL",
8
+ AccountAlreadyActivated = "AUTH_ACCOUNT_ALREADY_ACTIVATED",
9
+ AccountInactive = "AUTH_ACCOUNT_INACTIVE",
10
+ Timeout = "AUTH_REQUEST_TIMEOUT"
11
+ }
12
+ export declare class DrupalUserError extends HandledError {
13
+ readonly code: DrupalUserErrorCode;
14
+ readonly cause: unknown;
15
+ constructor(code: DrupalUserErrorCode, message: string, cause?: unknown);
16
+ }
3
17
  export type BackendConfig = {
4
18
  /**
5
19
  * Site URL without a trailing slash.
@@ -33,7 +47,7 @@ export interface Data extends GenericModelData {
33
47
  /** A flag that is set when the full profile is downloaded. */
34
48
  profileFetched?: boolean;
35
49
  }
36
- export interface Options extends GenericModelOptions {
50
+ export interface Options<T extends Data = Data> extends GenericModelOptions<T> {
37
51
  /**
38
52
  * Drupal site config.
39
53
  */
@@ -44,65 +58,31 @@ export default class DrupalUserModel<T extends Data = Data> extends Model<T> {
44
58
  static loginSchema: z.ZodObject<{
45
59
  email: z.ZodString;
46
60
  password: z.ZodString;
47
- }, "strip", z.ZodTypeAny, {
48
- email: string;
49
- password: string;
50
- }, {
51
- email: string;
52
- password: string;
53
- }>;
61
+ }, z.core.$strip>;
54
62
  static loginSchemaBackend: z.ZodObject<{
55
63
  id: z.ZodNumber;
56
64
  email: z.ZodString;
57
- }, "strip", z.ZodTypeAny, {
58
- id: number;
59
- email: string;
60
- }, {
61
- id: number;
62
- email: string;
63
- }>;
65
+ }, z.core.$strip>;
64
66
  static resetSchema: z.ZodObject<{
65
67
  email: z.ZodString;
66
- }, "strip", z.ZodTypeAny, {
67
- email: string;
68
- }, {
69
- email: string;
70
- }>;
68
+ }, z.core.$strip>;
71
69
  static registerSchema: z.ZodObject<{
72
70
  email: z.ZodString;
73
71
  password: z.ZodString;
74
- }, "strip", z.ZodTypeAny, {
75
- email: string;
76
- password: string;
77
- }, {
78
- email: string;
79
- password: string;
80
- }>;
72
+ }, z.core.$strip>;
81
73
  static registerSchemaBackend: z.ZodObject<{
82
74
  uid: z.ZodArray<z.ZodObject<{
83
75
  value: z.ZodNumber;
84
- }, "strip", z.ZodTypeAny, {
85
- value: number;
86
- }, {
87
- value: number;
88
- }>, "many">;
89
- }, "strip", z.ZodTypeAny, {
90
- uid: {
91
- value: number;
92
- }[];
93
- }, {
94
- uid: {
95
- value: number;
96
- }[];
97
- }>;
76
+ }, z.core.$strip>>;
77
+ }, z.core.$strip>;
98
78
  private _refreshingProfilePromise?;
99
79
  private _refreshingTokenPromise?;
100
- constructor({ config, ...options }: Options);
80
+ constructor({ config, ...options }: Options<T>);
101
81
  logIn(email: string, password: string): Promise<void>;
102
- register(email: string, password: string, otherFields: any): Promise<void>;
82
+ register(email: string, password: string, otherFields: Record<string, unknown>): Promise<void>;
103
83
  resetPassword(email: string): Promise<void>;
104
84
  delete(): Promise<void>;
105
- updateRemote(values: Record<string, any>): Promise<void>;
85
+ updateRemote(values: Record<string, unknown>): Promise<void>;
106
86
  /**
107
87
  * Gets full user profile inc. fresh new tokens.
108
88
  */
@@ -113,7 +93,7 @@ export default class DrupalUserModel<T extends Data = Data> extends Model<T> {
113
93
  hasLogIn(): boolean;
114
94
  isLoggedIn(): boolean;
115
95
  logOut(): Promise<void>;
116
- reset(defaultsToSet?: any): Promise<void>;
96
+ reset(defaultsToSet?: Partial<T>): Promise<void>;
117
97
  getAccessToken(forceRefresh?: boolean): Promise<string>;
118
98
  protected _sendVerificationEmail(email?: string): Promise<import("axios").AxiosResponse<any, any>>;
119
99
  private _exchangePasswordToTokens;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),i=require("axios"),t=require("jwt-decode"),s=require("zod"),r=require("@flumens/utils"),o=require("../Model.js");function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var a=n(i);function d(e){const i={};return Object.keys(e).forEach((t=>{if(t.match(/^field_/)){const s=t.replace("field_","").replace(/_([a-z])/g,(e=>e[1].toUpperCase()));if(!e[t])return;if(Array.isArray(e[t])&&e[t].length)return void(i[s]=e[t][0].value);i[s]=e[t]}})),i}const c=e=>{var i,t,s,o,n;const a=(null===(t=null===(i=e.response)||void 0===i?void 0:i.data)||void 0===t?void 0:t.error_description)||(null===(o=null===(s=e.response)||void 0===s?void 0:s.data)||void 0===o?void 0:o.message);if(a){if(a.includes("is already taken"))throw new r.HandledError("This email is already taken.");if("The user credentials were incorrect."===a)throw new r.HandledError("Incorrect password or email");if("Unrecognized username or email address."===a)throw new r.HandledError("Unrecognized email address.");if("This account is already activated"===a)throw new r.HandledError("This account is already activated.");if(a.includes("not been activated"))throw new r.HandledError("The user has not been activated or is blocked.");throw new Error(a)}if(null===(n=e.message)||void 0===n?void 0:n.includes("timeout"))throw new r.HandledError("Timeout");throw e},l=6e4;const h={email:"",tokens:void 0,verified:!1,iss:void 0,indiciaUserId:void 0,profileFetched:!1};class u extends o.default{constructor(i){var{config:t}=i,s=e.__rest(i,["config"]);super(Object.assign(Object.assign({},s),{data:Object.assign(Object.assign({},h),s.data)})),this.config=t}logIn(i,t){return e.__awaiter(this,void 0,void 0,(function*(){const e=yield this._exchangePasswordToTokens(i,t);return this.data.tokens=e,yield this.refreshProfile(),this.save()}))}register(i,t,s){return e.__awaiter(this,void 0,void 0,(function*(){const e=JSON.stringify(Object.assign({name:[{value:i}],pass:[{value:t}],mail:[{value:i}]},s)),r={method:"post",url:`${this.config.url}/user/register-with-password?_format=json`,headers:{"content-type":"application/json"},data:e,timeout:l},{data:o}=yield a.default(r).catch(c);if(!!u.registerSchemaBackend.safeParse(o).error)throw new Error("Invalid backend response.");const n=yield this._exchangePasswordToTokens(i,t);this.id=o.uid[0].value;const h=d(o);return Object.assign(this.data,Object.assign({email:i,tokens:n,profileFetched:!0},h)),this.save()}))}resetPassword(i){return e.__awaiter(this,void 0,void 0,(function*(){const e=JSON.stringify({mail:i}),t={method:"post",url:`${this.config.url}/user/password?_format=json`,headers:{"content-type":"application/json"},data:e};try{yield a.default(t).catch(c)}catch(e){if("The user has not been activated or is blocked."===e.message)return void(yield this._sendVerificationEmail(i));c(e)}}))}delete(){return e.__awaiter(this,void 0,void 0,(function*(){const e=yield this.getAccessToken(!0),i={method:"delete",url:`${this.config.url}/user/${this.id}?_format=json`,headers:{Authorization:`Bearer ${e}`}};yield a.default(i).catch(c),this.logOut()}))}updateRemote(i){return e.__awaiter(this,void 0,void 0,(function*(){const e=yield this.getAccessToken(),t={method:"patch",url:`${this.config.url}/user/${this.id}?_format=json`,data:i,headers:{Authorization:`Bearer ${e}`},timeout:l};yield a.default(t),yield this._refreshAccessToken(),this.save()}))}refreshProfile(){return e.__awaiter(this,void 0,void 0,(function*(){return this._refreshingProfilePromise||(this._refreshingProfilePromise=Promise.resolve().then((()=>e.__awaiter(this,void 0,void 0,(function*(){const e=yield this.getAccessToken(!0);if(this.data.verified){const i={url:`${this.config.url}/user/${this.id}?_format=json`,headers:{Authorization:`Bearer ${e}`},timeout:l},{data:t}=yield a.default(i).catch(c),s=d(t);Object.assign(this.data,Object.assign({email:t.mail[0].value,profileFetched:!0},s))}yield this.save(),delete this._refreshingProfilePromise})))).catch((e=>{throw delete this._refreshingProfilePromise,e}))),this._refreshingProfilePromise}))}hasLogIn(){return console.warn("hasLogIn is deprecated, please use isLoggedIn instead."),this.isLoggedIn()}isLoggedIn(){return this.data.email,!!this.id}logOut(){return e.__awaiter(this,void 0,void 0,(function*(){return this.reset()}))}reset(e){return super.reset(Object.assign(Object.assign({},h),e))}getAccessToken(i){return e.__awaiter(this,void 0,void 0,(function*(){if(!i&&!this.isLoggedIn())throw new Error("User is not logged in.");const{access_token:e}=this.data.tokens||{},s=function(e){if(!e)return!0;const{exp:i}=t.jwtDecode(e),s=1e3*i;return Date.now()+12e4>s}(e);if(!e||s||i)try{yield this._refreshAccessToken()}catch(e){console.error(e);const i="The refresh token is invalid."===e.message,t="Token has no user email."===e.message;if(i||t)throw yield this.logOut(),new Error("User re-login is required.");throw e}return this.data.tokens.access_token}))}_sendVerificationEmail(i){return e.__awaiter(this,void 0,void 0,(function*(){const e=JSON.stringify({mail:[{value:i||this.data.email}]}),t={method:"post",url:`${this.config.url}/user/register-with-password?_format=json&resendVerificationEmail=true`,headers:{"content-type":"application/json"},data:e,timeout:l};return a.default(t).catch(c)}))}_exchangePasswordToTokens(i,t){return e.__awaiter(this,void 0,void 0,(function*(){var e;const s=new FormData;s.append("grant_type","password"),s.append("username",i),s.append("password",t),s.append("client_id",this.config.clientId),this.config.clientPass&&s.append("client_secret",this.config.clientPass),(null===(e=this.config.scopes)||void 0===e?void 0:e.length)&&s.append("scope",this.config.scopes.join(" "));const r={method:"post",url:`${this.config.url}/oauth/token`,data:s},{data:o}=yield a.default(r).catch(c);return o}))}_refreshAccessToken(){return e.__awaiter(this,void 0,void 0,(function*(){return this._refreshingTokenPromise||(this._refreshingTokenPromise=Promise.resolve().then((()=>e.__awaiter(this,void 0,void 0,(function*(){const{refresh_token:e}=this.data.tokens||{};if(!e)throw new Error("No user session refresh token was found");const i=new FormData;i.append("grant_type","refresh_token"),i.append("refresh_token",e),i.append("client_id",this.config.clientId),this.config.clientPass&&i.append("client_secret",this.config.clientPass);const s={method:"post",url:`${this.config.url}/oauth/token`,data:i,timeout:l},{data:r}=yield a.default(s).catch(c),o=Object.assign(Object.assign({},this.data.tokens),r),n=t.jwtDecode(o.access_token),{email:h}=n;if(!h)throw new Error("Token has no user email.");const{iss:u,email_verified:f}=n,g=n["http://indicia.org.uk/user:id"],m=n.scopes,v=d(n);this.id=n.sub,Object.assign(this.data,Object.assign({email:h,roles:m,verified:f,iss:u,indiciaUserId:g,tokens:o},v)),yield this.save(),delete this._refreshingTokenPromise})))).catch((e=>{throw delete this._refreshingTokenPromise,e}))),this._refreshingTokenPromise}))}}u.loginSchema=s.object({email:s.z.string().email("Please fill in"),password:s.z.string().min(1,"Please fill in")}),u.loginSchemaBackend=s.object({id:s.z.number(),email:s.z.string().email()}),u.resetSchema=s.object({email:s.z.string().email("Please fill in")}),u.registerSchema=s.object({email:s.z.string().email("Please fill in"),password:s.z.string().min(1,"Please fill in")}),u.registerSchemaBackend=s.object({uid:s.z.array(s.object({value:s.z.number()}))}),exports.default=u;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),i=require("axios"),t=require("jwt-decode"),r=require("zod"),s=require("@flumens/utils"),o=require("../Model.js");function a(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var n,d=a(i);function c(e){const i={};return Object.keys(e).forEach((t=>{if(t.match(/^field_/)){const r=t.replace("field_","").replace(/_([a-z])/g,(e=>e[1].toUpperCase()));if(!e[t])return;if(Array.isArray(e[t])&&e[t].length)return void(i[r]=e[t][0].value);i[r]=e[t]}})),i}exports.DrupalUserErrorCode=void 0,(n=exports.DrupalUserErrorCode||(exports.DrupalUserErrorCode={})).EmailTaken="AUTH_EMAIL_TAKEN",n.InvalidCredentials="AUTH_INVALID_CREDENTIALS",n.UnrecognizedEmail="AUTH_UNRECOGNIZED_EMAIL",n.AccountAlreadyActivated="AUTH_ACCOUNT_ALREADY_ACTIVATED",n.AccountInactive="AUTH_ACCOUNT_INACTIVE",n.Timeout="AUTH_REQUEST_TIMEOUT";class l extends s.HandledError{constructor(e,i,t){super(i),this.name="DrupalUserError",this.code=e,this.cause=t}}const h=e=>{var i,t,r,s,o;const a=(null===(t=null===(i=e.response)||void 0===i?void 0:i.data)||void 0===t?void 0:t.error_description)||(null===(s=null===(r=e.response)||void 0===r?void 0:r.data)||void 0===s?void 0:s.message);if(a){if(a.includes("is already taken"))throw new l(exports.DrupalUserErrorCode.EmailTaken,"This email is already taken.",e);if("The user credentials were incorrect."===a)throw new l(exports.DrupalUserErrorCode.InvalidCredentials,"Incorrect password or email",e);if("Unrecognized username or email address."===a)throw new l(exports.DrupalUserErrorCode.UnrecognizedEmail,"Unrecognized email address.",e);if("This account is already activated"===a)throw new l(exports.DrupalUserErrorCode.AccountAlreadyActivated,"This account is already activated.",e);if(a.includes("not been activated"))throw new l(exports.DrupalUserErrorCode.AccountInactive,"The user has not been activated or is blocked.",e);throw new Error(a)}if(null===(o=e.message)||void 0===o?void 0:o.includes("timeout"))throw new l(exports.DrupalUserErrorCode.Timeout,"Timeout",e);throw e},u=6e4;const f={email:"",tokens:void 0,verified:!1,iss:void 0,indiciaUserId:void 0,profileFetched:!1};class g extends o.default{constructor(i){var{config:t}=i,r=e.__rest(i,["config"]);super(Object.assign(Object.assign({},r),{data:Object.assign(Object.assign({},f),r.data)})),this.config=t}logIn(i,t){return e.__awaiter(this,void 0,void 0,(function*(){const e=yield this._exchangePasswordToTokens(i,t);return this.data.tokens=e,yield this.refreshProfile(),this.save()}))}register(i,t,r){return e.__awaiter(this,void 0,void 0,(function*(){const e=JSON.stringify(Object.assign({name:[{value:i}],pass:[{value:t}],mail:[{value:i}]},r)),s={method:"post",url:`${this.config.url}/user/register-with-password?_format=json`,headers:{"content-type":"application/json"},data:e,timeout:u},{data:o}=yield d.default(s).catch(h);if(!!g.registerSchemaBackend.safeParse(o).error)throw new Error("Invalid backend response.");const a=yield this._exchangePasswordToTokens(i,t);this.id=o.uid[0].value;const n=c(o);return Object.assign(this.data,Object.assign({email:i,tokens:a,profileFetched:!0},n)),this.save()}))}resetPassword(i){return e.__awaiter(this,void 0,void 0,(function*(){const e=JSON.stringify({mail:i}),t={method:"post",url:`${this.config.url}/user/password?_format=json`,headers:{"content-type":"application/json"},data:e};try{yield d.default(t).catch(h)}catch(e){if("The user has not been activated or is blocked."===e.message)return void(yield this._sendVerificationEmail(i));h(e)}}))}delete(){return e.__awaiter(this,void 0,void 0,(function*(){const e=yield this.getAccessToken(!0),i={method:"delete",url:`${this.config.url}/user/${this.id}?_format=json`,headers:{Authorization:`Bearer ${e}`}};yield d.default(i).catch(h),this.logOut()}))}updateRemote(i){return e.__awaiter(this,void 0,void 0,(function*(){const e=yield this.getAccessToken(),t={method:"patch",url:`${this.config.url}/user/${this.id}?_format=json`,data:i,headers:{Authorization:`Bearer ${e}`},timeout:u};yield d.default(t),yield this._refreshAccessToken(),this.save()}))}refreshProfile(){return e.__awaiter(this,void 0,void 0,(function*(){return this._refreshingProfilePromise||(this._refreshingProfilePromise=Promise.resolve().then((()=>e.__awaiter(this,void 0,void 0,(function*(){const e=yield this.getAccessToken(!0);if(this.data.verified){const i={url:`${this.config.url}/user/${this.id}?_format=json`,headers:{Authorization:`Bearer ${e}`},timeout:u},{data:t}=yield d.default(i).catch(h),r=c(t);Object.assign(this.data,Object.assign({email:t.mail[0].value,profileFetched:!0},r))}yield this.save(),delete this._refreshingProfilePromise})))).catch((e=>{throw delete this._refreshingProfilePromise,e}))),this._refreshingProfilePromise}))}hasLogIn(){return console.warn("hasLogIn is deprecated, please use isLoggedIn instead."),this.isLoggedIn()}isLoggedIn(){return this.data.email,!!this.id}logOut(){return e.__awaiter(this,void 0,void 0,(function*(){return this.reset()}))}reset(e){return super.reset(Object.assign(Object.assign({},f),e))}getAccessToken(i){return e.__awaiter(this,void 0,void 0,(function*(){if(!i&&!this.isLoggedIn())throw new Error("User is not logged in.");const{access_token:e}=this.data.tokens||{},r=function(e){if(!e)return!0;const{exp:i}=t.jwtDecode(e),r=1e3*i;return Date.now()+12e4>r}(e);if(!e||r||i)try{yield this._refreshAccessToken()}catch(e){console.error(e);const i="The refresh token is invalid."===e.message,t="Token has no user email."===e.message;if(i||t)throw yield this.logOut(),new Error("User re-login is required.");throw e}return this.data.tokens.access_token}))}_sendVerificationEmail(i){return e.__awaiter(this,void 0,void 0,(function*(){const e=JSON.stringify({mail:[{value:i||this.data.email}]}),t={method:"post",url:`${this.config.url}/user/register-with-password?_format=json&resendVerificationEmail=true`,headers:{"content-type":"application/json"},data:e,timeout:u};return d.default(t).catch(h)}))}_exchangePasswordToTokens(i,t){return e.__awaiter(this,void 0,void 0,(function*(){var e;const r=new FormData;r.append("grant_type","password"),r.append("username",i),r.append("password",t),r.append("client_id",this.config.clientId),this.config.clientPass&&r.append("client_secret",this.config.clientPass),(null===(e=this.config.scopes)||void 0===e?void 0:e.length)&&r.append("scope",this.config.scopes.join(" "));const s={method:"post",url:`${this.config.url}/oauth/token`,data:r},{data:o}=yield d.default(s).catch(h);return o}))}_refreshAccessToken(){return e.__awaiter(this,void 0,void 0,(function*(){return this._refreshingTokenPromise||(this._refreshingTokenPromise=Promise.resolve().then((()=>e.__awaiter(this,void 0,void 0,(function*(){const{refresh_token:e}=this.data.tokens||{};if(!e)throw new Error("No user session refresh token was found");const i=new FormData;i.append("grant_type","refresh_token"),i.append("refresh_token",e),i.append("client_id",this.config.clientId),this.config.clientPass&&i.append("client_secret",this.config.clientPass);const r={method:"post",url:`${this.config.url}/oauth/token`,data:i,timeout:u},{data:s}=yield d.default(r).catch(h),o=Object.assign(Object.assign({},this.data.tokens),s),a=t.jwtDecode(o.access_token),{email:n}=a;if(!n)throw new Error("Token has no user email.");const{iss:l,email_verified:f}=a,g=a["http://indicia.org.uk/user:id"],p=a.scopes,m=c(a);this.id=a.sub,Object.assign(this.data,Object.assign({email:n,roles:p,verified:f,iss:l,indiciaUserId:g,tokens:o},m)),yield this.save(),delete this._refreshingTokenPromise})))).catch((e=>{throw delete this._refreshingTokenPromise,e}))),this._refreshingTokenPromise}))}}g.loginSchema=r.object({email:r.z.string().email("Please fill in"),password:r.z.string().min(1,"Please fill in")}),g.loginSchemaBackend=r.object({id:r.z.number(),email:r.z.string().email()}),g.resetSchema=r.object({email:r.z.string().email("Please fill in")}),g.registerSchema=r.object({email:r.z.string().email("Please fill in"),password:r.z.string().min(1,"Please fill in")}),g.registerSchemaBackend=r.object({uid:r.z.array(r.object({value:r.z.number()}))}),exports.DrupalUserError=l,exports.default=g;
@@ -0,0 +1 @@
1
+ "use strict";var e=require("tslib"),t=require("node:assert/strict"),n=require("node:test"),o=require("mailslurp-client");function a(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var i=a(t);const r=12e4,s="https://example.com",d="http://indicia.org.uk/user:id";function l(e){console.info(`[user lifecycle] ${e}`)}function u(e){const t=process.env[e];return i.default.ok(t,`${e} must be set`),t}const c=new URL(u("DRUPAL_SITE_URL")),f=u("APP_BACKEND_CLIENT_ID"),h=process.env.APP_BACKEND_CLIENT_PASS,p=new o.MailSlurp({apiKey:u("MAILSLURP_API_KEY")});function m(e){return new URL(e,c)}function v(e){return`'${e.replaceAll("'","'\\''")}'`}function y(e,t={}){const n=["curl",`--request ${t.method||"GET"}`,v(e.toString())];if(new Headers(t.headers).forEach(((e,t)=>{n.push(`--header ${v(`${t}: ${e}`)}`)})),t.body instanceof FormData)for(const[e,o]of t.body.entries())n.push(`--form ${v(`${e}=${String(o)}`)}`);if(t.body instanceof URLSearchParams)for(const[e,o]of t.body.entries())n.push(`--data-urlencode ${v(`${e}=${o}`)}`);return"string"==typeof t.body&&n.push(`--data ${v(t.body)}`),n.map(((e,t)=>t?` ${e}`:e)).join(" \\\n")}function _(e){console.error(`[user lifecycle] Failed request:\n${e}`)}function g(e,t){const n=e.headers.get("access-control-allow-origin"),o="*"===n||n===s;o||_(t),i.default.ok(o,`${e.url} returned ${e.status} with Access-Control-Allow-Origin: ${n||"missing"}`)}function w(t){return e.__awaiter(this,arguments,void 0,(function*(e,t={}){const n=m(e),o=new Headers(t.headers);o.set("Origin",s);const a=Object.assign(Object.assign({},t),{headers:o}),i=y(n,a);let r;try{r=yield fetch(n,a)}catch(e){throw _(i),e}return g(r,i),{response:r,curl:i}}))}function k(t,n){return e.__awaiter(this,arguments,void 0,(function*(e,t,n=[]){var o,a;const r=new Headers({Origin:s,"Access-Control-Request-Method":t});n.length&&r.set("Access-Control-Request-Headers",n.join(", "));const d=m(e),u={method:"OPTIONS",headers:r},c=y(d,u);let f;try{f=yield fetch(d,u)}catch(e){throw _(c),e}g(f,c);const h=(null===(o=f.headers.get("access-control-allow-methods"))||void 0===o?void 0:o.toUpperCase())||"",p=(null===(a=f.headers.get("access-control-allow-headers"))||void 0===a?void 0:a.toLowerCase())||"";f.ok&&(h.includes("*")||h.includes(t))&&!n.some((e=>!p.includes(e)))||_(c),i.default.ok(f.ok,`CORS preflight returned ${f.status}`),i.default.ok(h.includes("*")||h.includes(t),`CORS preflight did not allow ${t}`);for(const e of n)i.default.ok(p.includes(e),`CORS preflight did not allow ${e}`);l(`Validated CORS preflight for ${t} ${d.pathname}`)}))}function $(t){return e.__awaiter(this,arguments,void 0,(function*(t,n={}){const{response:o,curl:a}=yield w(t,n);return yield function(t,n){return e.__awaiter(this,void 0,void 0,(function*(){if(!t.ok)throw _(n),new Error(`${t.url} returned ${t.status}: ${yield t.text()}`);l(`Received ${t.status} from ${new URL(t.url).pathname}`)}))}(o,a),o}))}function S(e,t){const n=new FormData;return n.append("grant_type","password"),n.append("username",e),n.append("password",t),n.append("client_id",f),h&&n.append("client_secret",h),n}function j(e){const t=new FormData;return t.append("grant_type","refresh_token"),t.append("refresh_token",e),t.append("client_id",f),h&&t.append("client_secret",h),t}function E(e){const t=e.split(".")[1];return i.default.ok(t,"Access token is not a JWT"),JSON.parse(Buffer.from(t,"base64url").toString())}function T(e,t,n){const o=E(e);i.default.equal(o.email,t),i.default.equal(o.email_verified,n),i.default.ok(o[d],`JWT did not include ${d}`),l(`Validated JWT email, verification, and ${d}`)}function b(t){return e.__awaiter(this,void 0,void 0,(function*(){var e;const n=(t.isHTML?(yield p.emailController.getEmailLinks({emailId:t.id})).links:(null===(e=t.body)||void 0===e?void 0:e.match(/https?:\/\/[^\s"'<>]+/g))||[]).map((e=>e.replaceAll("&amp;","&"))),o=n.find((e=>{const t=new URL(e,c);return/\/user\/(?:registrationpassword|reset)\//.test(t.pathname)}));return o||l(`Email links found: ${n.join(", ")||"none"}`),i.default.ok(o,"Drupal account link was not found in the email"),o}))}n.test("supports browser CORS requests",(()=>e.__awaiter(void 0,void 0,void 0,(function*(){yield k("/oauth/token","POST"),yield k("/user/register-with-password?_format=json","POST",["content-type"]),yield k("/user/register-with-password?_format=json&resendVerificationEmail=true","POST",["content-type"]),yield k("/user/password?_format=json","POST",["content-type"]),yield k("/user/1?_format=json","GET",["authorization"]),yield k("/user/1?_format=json","PATCH",["authorization","content-type"]),yield k("/user/1?_format=json","DELETE",["authorization"]),yield k("/user/login_status?_format=json","GET",["authorization"])})))),n.test("completes the Drupal user account lifecycle",{timeout:3e5},(t=>e.__awaiter(void 0,void 0,void 0,(function*(){var n,o,a,s,d,u,f,h,v,g,k,C,O,R;l(`Starting test against ${c.origin}`),l("Creating temporary MailSlurp inbox");const P=yield p.createInbox(),q=P.emailAddress,D=`E2e-${crypto.randomUUID()}-aA1!`,A="User",L="Updated",U="E2E User";let I,N,F,z=!1;i.default.ok(q,"MailSlurp did not create an email address"),t.after((()=>e.__awaiter(void 0,void 0,void 0,(function*(){l("Cleaning up test resources");const e=[p.deleteInbox(P.id)];F&&I&&!z&&(l(`Deleting Drupal account ${F} during cleanup`),e.push(fetch(m(`/user/${F}?_format=json`),{method:"DELETE",headers:{Authorization:`Bearer ${I}`}}).then((e=>{e.ok||l(`Drupal account ${F} requires manual cleanup after delete returned ${e.status}`)})))),!F||I||z||l(`Drupal account ${F} requires manual cleanup because no access token was obtained`),yield Promise.allSettled(e),l("Cleanup complete")})))),l("Creating Drupal account");const J=yield $("/user/register-with-password?_format=json",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:[{value:q}],pass:[{value:D}],mail:[{value:q}],field_first_name:[{value:"E2E"}],field_last_name:[{value:A}]})}),V=yield J.json();F=null===(o=null===(n=V.uid)||void 0===n?void 0:n[0])||void 0===o?void 0:o.value,i.default.ok(F,"Registration response did not include a user ID"),l(`Created Drupal account ${F}`),l("Following the model registration login before verification");const B=yield $("/oauth/token",{method:"POST",body:S(q,D)}),x=yield B.json();I=x.access_token,N=x.refresh_token,i.default.ok(I,"Registration login did not return an access token"),i.default.ok(N,"Registration login did not return a refresh token"),T(I,q,!1),l("Confirmed the account can log in but remains unverified"),l("Waiting for account verification email");const H=yield p.waitForLatestEmail(P.id,r,!0);l("Received account verification email"),yield b(H),l("Validated initial account verification email"),l("Requesting a password reset for the unverified account"),yield $("/user/password?_format=json",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mail:q})}),l("Requesting a verification email for the unverified account"),yield $("/user/register-with-password?_format=json&resendVerificationEmail=true",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mail:[{value:q}]})}),l("Waiting for resent account verification email");const M=yield p.waitForLatestEmail(P.id,r,!0);i.default.notEqual(M.id,H.id,"Verification email was not resent");const W=yield b(M);l("Received resent account verification email"),l("Opening resent account verification link");const K={redirect:"manual"},G=y(new URL(W),K);let Y;try{Y=yield fetch(W,K)}catch(e){throw _(G),e}let Q=Y.ok||Y.status>=300&&Y.status<400;if(Q||_(G),504===Y.status){l("Checking whether the timed-out verification completed");const e=yield $("/oauth/token",{method:"POST",body:S(q,D)});Q=!0===E((yield e.json()).access_token).email_verified}i.default.ok(Q,`Verification returned ${Y.status}`),l(`Verified account with response ${Y.status}`),l("Requesting access and refresh tokens");const X=yield $("/oauth/token",{method:"POST",body:S(q,D)}),Z=yield X.json();I=Z.access_token,N=Z.refresh_token,i.default.ok(I,"Password grant did not return an access token"),i.default.ok(N,"Password grant did not return a refresh token"),T(I,q,!0),l("Received access and refresh tokens"),l("Fetching and validating account data");const ee=yield $(`/user/${F}?_format=json`,{headers:{Authorization:`Bearer ${I}`}}),te=yield ee.json();i.default.equal(null===(s=null===(a=te.name)||void 0===a?void 0:a[0])||void 0===s?void 0:s.value,q),i.default.equal(null===(u=null===(d=te.mail)||void 0===d?void 0:d[0])||void 0===u?void 0:u.value,q),i.default.equal(null===(h=null===(f=te.field_first_name)||void 0===f?void 0:f[0])||void 0===h?void 0:h.value,"E2E"),i.default.equal(null===(g=null===(v=te.field_last_name)||void 0===v?void 0:v[0])||void 0===g?void 0:g.value,A),l("Validated account name, email, first name, and last name"),l("Updating account first and last names"),yield $(`/user/${F}?_format=json`,{method:"PATCH",headers:{Authorization:`Bearer ${I}`,"Content-Type":"application/json"},body:JSON.stringify({field_first_name:[{value:L}],field_last_name:[{value:U}]})}),l("Refreshing access token after account update");const ne=yield $("/oauth/token",{method:"POST",body:j(N)}),oe=yield ne.json();I=oe.access_token,N=oe.refresh_token||N,i.default.ok(I,"Refresh grant did not return an access token"),i.default.ok(N,"Refresh grant did not retain a refresh token"),T(I,q,!0),l("Refreshed access token after account update"),l("Fetching and validating updated account data");const ae=yield $(`/user/${F}?_format=json`,{headers:{Authorization:`Bearer ${I}`}}),ie=yield ae.json();i.default.equal(null===(C=null===(k=ie.field_first_name)||void 0===k?void 0:k[0])||void 0===C?void 0:C.value,L),i.default.equal(null===(R=null===(O=ie.field_last_name)||void 0===O?void 0:O[0])||void 0===R?void 0:R.value,U),l("Updated and validated account data"),l("Requesting password reset email"),yield $("/user/password?_format=json",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mail:q})}),l("Waiting for password reset email");const re=yield p.waitForLatestEmail(P.id,r,!0);i.default.ok(re.to.includes(q),"Password reset email was not sent to the test account"),l("Received password reset email"),l("Deleting Drupal account"),yield $(`/user/${F}?_format=json`,{method:"DELETE",headers:{Authorization:`Bearer ${I}`}}),z=!0,l("Checking the refresh token after account deletion");const se=j(N),{response:de,curl:le}=yield w("/oauth/token",{method:"POST",body:se});if(de.ok){const e=E((yield de.json()).access_token);i.default.equal(e.email,void 0,"Deleted account unexpectedly received a usable token"),l("Confirmed the deleted account token has no user email")}else{const e=yield de.text();_(le),i.default.match(e,/invalid|revoked|user|email/i),l(`Confirmed refresh was rejected with ${de.status}`)}l("Deleted Drupal account; lifecycle complete")}))));
@@ -1,5 +1,5 @@
1
1
  interface Attribute {
2
- value: any;
2
+ value: unknown;
3
3
  id: string;
4
4
  }
5
5
  export interface Media {
@@ -77,14 +77,14 @@ interface Metadata {
77
77
  interface AutoChecks {
78
78
  result: string;
79
79
  enabled: string;
80
- output: any[];
80
+ output: unknown[];
81
81
  }
82
82
  interface Verifier {
83
83
  id: string;
84
84
  name: string;
85
85
  }
86
86
  export type VerifiedStates = 'C' | 'V' | 'R';
87
- interface Identification {
87
+ export interface Identification {
88
88
  verification_status: VerifiedStates;
89
89
  auto_checks: AutoChecks;
90
90
  query?: 'Q';
@@ -1,5 +1,5 @@
1
1
  interface Attribute {
2
- value: any;
2
+ value: unknown;
3
3
  id: string;
4
4
  }
5
5
  export interface Media {
@@ -6,49 +6,31 @@ export declare const dtoSchema: z.ZodObject<{
6
6
  createdOn: z.ZodString;
7
7
  description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
8
8
  groupType: z.ZodOptional<z.ZodNullable<z.ZodString>>;
9
- joiningMethod: z.ZodOptional<z.ZodNullable<z.ZodEnum<["P", "R", "A", "I"]>>>;
9
+ joiningMethod: z.ZodOptional<z.ZodNullable<z.ZodEnum<{
10
+ R: "R";
11
+ P: "P";
12
+ I: "I";
13
+ A: "A";
14
+ }>>>;
10
15
  websiteId: z.ZodOptional<z.ZodNullable<z.ZodString>>;
11
16
  groupTypeId: z.ZodOptional<z.ZodNullable<z.ZodString>>;
12
17
  createdById: z.ZodOptional<z.ZodNullable<z.ZodString>>;
13
18
  fromDate: z.ZodOptional<z.ZodNullable<z.ZodString>>;
14
19
  toDate: z.ZodOptional<z.ZodNullable<z.ZodString>>;
15
- indexedLocationIds: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodNumber, "many">>>;
16
- userIsAdministrator: z.ZodOptional<z.ZodNullable<z.ZodEnum<["t", "f"]>>>;
17
- userIsMember: z.ZodOptional<z.ZodNullable<z.ZodEnum<["t", "f"]>>>;
18
- userIsPending: z.ZodOptional<z.ZodNullable<z.ZodEnum<["t", "f"]>>>;
19
- }, "strip", z.ZodTypeAny, {
20
- id: string;
21
- title: string;
22
- createdOn: string;
23
- description?: string | null | undefined;
24
- groupType?: string | null | undefined;
25
- joiningMethod?: "R" | "P" | "I" | "A" | null | undefined;
26
- websiteId?: string | null | undefined;
27
- groupTypeId?: string | null | undefined;
28
- createdById?: string | null | undefined;
29
- fromDate?: string | null | undefined;
30
- toDate?: string | null | undefined;
31
- indexedLocationIds?: number[] | null | undefined;
32
- userIsAdministrator?: "t" | "f" | null | undefined;
33
- userIsMember?: "t" | "f" | null | undefined;
34
- userIsPending?: "t" | "f" | null | undefined;
35
- }, {
36
- id: string;
37
- title: string;
38
- createdOn: string;
39
- description?: string | null | undefined;
40
- groupType?: string | null | undefined;
41
- joiningMethod?: "R" | "P" | "I" | "A" | null | undefined;
42
- websiteId?: string | null | undefined;
43
- groupTypeId?: string | null | undefined;
44
- createdById?: string | null | undefined;
45
- fromDate?: string | null | undefined;
46
- toDate?: string | null | undefined;
47
- indexedLocationIds?: number[] | null | undefined;
48
- userIsAdministrator?: "t" | "f" | null | undefined;
49
- userIsMember?: "t" | "f" | null | undefined;
50
- userIsPending?: "t" | "f" | null | undefined;
51
- }>;
20
+ indexedLocationIds: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodNumber>>>;
21
+ userIsAdministrator: z.ZodOptional<z.ZodNullable<z.ZodEnum<{
22
+ t: "t";
23
+ f: "f";
24
+ }>>>;
25
+ userIsMember: z.ZodOptional<z.ZodNullable<z.ZodEnum<{
26
+ t: "t";
27
+ f: "f";
28
+ }>>>;
29
+ userIsPending: z.ZodOptional<z.ZodNullable<z.ZodEnum<{
30
+ t: "t";
31
+ f: "f";
32
+ }>>>;
33
+ }, z.core.$strip>;
52
34
  declare const locationDTOSchema: z.ZodObject<{
53
35
  id: z.ZodOptional<z.ZodNullable<z.ZodString>>;
54
36
  createdOn: z.ZodOptional<z.ZodNullable<z.ZodString>>;
@@ -69,50 +51,10 @@ declare const locationDTOSchema: z.ZodObject<{
69
51
  locationUpdatedById: z.ZodOptional<z.ZodNullable<z.ZodString>>;
70
52
  locationComment: z.ZodOptional<z.ZodNullable<z.ZodString>>;
71
53
  locationExternalKey: z.ZodOptional<z.ZodNullable<z.ZodString>>;
72
- }, "strip", z.ZodTypeAny, {
73
- locationId: string;
74
- locationName: string;
75
- locationBoundaryGeom: string;
76
- locationLat: string;
77
- locationLon: string;
78
- locationCreatedOn: string;
79
- locationUpdatedOn: string;
80
- locationCentroidSref: string;
81
- locationCentroidSrefSystem: string;
82
- id?: string | null | undefined;
83
- createdOn?: string | null | undefined;
84
- createdById?: string | null | undefined;
85
- groupId?: string | null | undefined;
86
- groupTitle?: string | null | undefined;
87
- locationCode?: string | null | undefined;
88
- locationCreatedById?: string | null | undefined;
89
- locationUpdatedById?: string | null | undefined;
90
- locationComment?: string | null | undefined;
91
- locationExternalKey?: string | null | undefined;
92
- }, {
93
- locationId: string;
94
- locationName: string;
95
- locationBoundaryGeom: string;
96
- locationLat: string;
97
- locationLon: string;
98
- locationCreatedOn: string;
99
- locationUpdatedOn: string;
100
- locationCentroidSref: string;
101
- locationCentroidSrefSystem: string;
102
- id?: string | null | undefined;
103
- createdOn?: string | null | undefined;
104
- createdById?: string | null | undefined;
105
- groupId?: string | null | undefined;
106
- groupTitle?: string | null | undefined;
107
- locationCode?: string | null | undefined;
108
- locationCreatedById?: string | null | undefined;
109
- locationUpdatedById?: string | null | undefined;
110
- locationComment?: string | null | undefined;
111
- locationExternalKey?: string | null | undefined;
112
- }>;
54
+ }, z.core.$strip>;
113
55
  type LocationDTO = z.infer<typeof locationDTOSchema>;
114
56
  export type LocationData = LocationDTO;
115
- export interface Options<T = any> extends OptionsOriginal<T> {
57
+ export interface Options<T extends Data = Data> extends OptionsOriginal<T> {
116
58
  skipStore?: boolean;
117
59
  url?: string;
118
60
  getAccessToken?: () => Promise<string>;
@@ -128,7 +70,7 @@ declare class Group<T extends Data = Data> extends Model<T> {
128
70
  getAccessToken?: () => Promise<string>;
129
71
  getIndiciaUserId?: () => Promise<string | number>;
130
72
  };
131
- constructor({ skipStore, store, url, getAccessToken, getIndiciaUserId, ...options }: Options);
73
+ constructor({ skipStore, store, url, getAccessToken, getIndiciaUserId, ...options }: Options<T>);
132
74
  join(): Promise<void>;
133
75
  leave(): Promise<void>;
134
76
  addRemoteLocation(locationId: string | number): Promise<this>;
@@ -1,23 +1,14 @@
1
1
  import { IObservableArray } from 'mobx';
2
2
  import { z } from 'zod';
3
3
  import Model, { Options as OptionsOriginal, Data as ModelData } from '../Model';
4
- import Media from './Media';
4
+ import Media, { MediaConstructor, WarehouseMediaNames } from './Media';
5
5
  export declare const dtoSchema: z.ZodObject<{
6
6
  lat: z.ZodString;
7
7
  lon: z.ZodString;
8
- /**
9
- * Location name.
10
- */
11
8
  name: z.ZodString;
12
- /**
13
- * Location type e.g. transect = 777, transect section = 778 etc.
14
- */
15
9
  locationTypeId: z.ZodString;
16
10
  centroidSref: z.ZodString;
17
11
  centroidSrefSystem: z.ZodString;
18
- /**
19
- * Entity ID.
20
- */
21
12
  id: z.ZodOptional<z.ZodString>;
22
13
  createdOn: z.ZodOptional<z.ZodString>;
23
14
  updatedOn: z.ZodOptional<z.ZodString>;
@@ -30,45 +21,7 @@ export declare const dtoSchema: z.ZodObject<{
30
21
  centroidGeom: z.ZodOptional<z.ZodNullable<z.ZodString>>;
31
22
  public: z.ZodOptional<z.ZodNullable<z.ZodString>>;
32
23
  comment: z.ZodOptional<z.ZodNullable<z.ZodString>>;
33
- }, "strip", z.ZodTypeAny, {
34
- name: string;
35
- lat: string;
36
- lon: string;
37
- locationTypeId: string;
38
- centroidSref: string;
39
- centroidSrefSystem: string;
40
- id?: string | undefined;
41
- code?: string | null | undefined;
42
- parentId?: string | null | undefined;
43
- createdOn?: string | undefined;
44
- createdById?: string | null | undefined;
45
- updatedOn?: string | undefined;
46
- boundaryGeom?: string | null | undefined;
47
- updatedById?: string | null | undefined;
48
- externalKey?: string | null | undefined;
49
- centroidGeom?: string | null | undefined;
50
- public?: string | null | undefined;
51
- comment?: string | null | undefined;
52
- }, {
53
- name: string;
54
- lat: string;
55
- lon: string;
56
- locationTypeId: string;
57
- centroidSref: string;
58
- centroidSrefSystem: string;
59
- id?: string | undefined;
60
- code?: string | null | undefined;
61
- parentId?: string | null | undefined;
62
- createdOn?: string | undefined;
63
- createdById?: string | null | undefined;
64
- updatedOn?: string | undefined;
65
- boundaryGeom?: string | null | undefined;
66
- updatedById?: string | null | undefined;
67
- externalKey?: string | null | undefined;
68
- centroidGeom?: string | null | undefined;
69
- public?: string | null | undefined;
70
- comment?: string | null | undefined;
71
- }>;
24
+ }, z.core.$strip>;
72
25
  export type Metadata = {
73
26
  saved?: boolean;
74
27
  groupId?: string;
@@ -83,10 +36,10 @@ export declare enum LocationType {
83
36
  }
84
37
  export type DTO = z.infer<typeof dtoSchema>;
85
38
  export type Data = Omit<DTO, 'createdOn' | 'updatedOn'> & ModelData;
86
- export interface Options<T = Data, S = Metadata> extends OptionsOriginal<T> {
39
+ export interface Options<T extends Data = Data, S extends Metadata = Metadata> extends OptionsOriginal<T> {
87
40
  metadata?: S;
88
- media?: any[];
89
- Media?: typeof Media<any, any>;
41
+ media?: (Media | Record<string, unknown>)[];
42
+ Media?: MediaConstructor;
90
43
  skipStore?: boolean;
91
44
  url?: string;
92
45
  getAccessToken?: () => Promise<string>;
@@ -98,7 +51,7 @@ declare class Location<T extends Data = Data, S extends Metadata = Metadata> ext
98
51
  url?: string;
99
52
  getAccessToken?: () => Promise<string>;
100
53
  };
101
- Media: typeof Media<any, any>;
54
+ Media: MediaConstructor;
102
55
  media: IObservableArray<Media>;
103
56
  /**
104
57
  * Model persistent observable metadata.
@@ -106,8 +59,11 @@ declare class Location<T extends Data = Data, S extends Metadata = Metadata> ext
106
59
  metadata: S;
107
60
  constructor({ skipStore, store, media, metadata, url, getAccessToken, Media: MediaClass, ...options }?: Options<T, S>);
108
61
  saveRemote(): Promise<this>;
109
- toDTO(warehouseMediaNames?: {}): any;
110
- protected uploadMedia(): Promise<any>;
62
+ toDTO(warehouseMediaNames?: WarehouseMediaNames): {
63
+ values: Record<string, unknown>;
64
+ media: unknown[];
65
+ };
66
+ protected uploadMedia(): Promise<WarehouseMediaNames>;
111
67
  get isUploaded(): boolean;
112
68
  get isSynchronising(): boolean;
113
69
  get isDraft(): boolean;
@@ -1,6 +1,6 @@
1
1
  import Collection, { Options as BaseOptions } from '../Collection';
2
2
  import Location, { LocationType } from './Location';
3
- type RemoteFetchParams = any;
3
+ type RemoteFetchParams = Record<string, unknown>;
4
4
  export interface Options<T extends Location> extends BaseOptions<T> {
5
5
  url?: string | null;
6
6
  getAccessToken: () => Promise<string>;
@@ -1,18 +1,23 @@
1
1
  import Model, { Data as DataOriginal, Options as OptionsOriginal } from '../Model';
2
+ import type Location from './Location';
2
3
  import Occurrence from './Occurrence';
3
4
  import Sample from './Sample';
4
5
  export interface Metadata {
6
+ createdOn?: number;
7
+ updatedOn?: number;
8
+ syncedOn?: number;
9
+ [key: string]: unknown;
5
10
  }
6
11
  export type DataURI = string;
7
12
  export type URL = string;
8
- export interface Options<T = any, S = any> extends OptionsOriginal<T> {
13
+ export interface Options<T extends Data = Data, S extends Metadata = Metadata> extends OptionsOriginal<T> {
9
14
  metadata?: S;
10
15
  url?: string;
11
16
  getAccessToken?: () => Promise<string>;
12
17
  }
13
18
  export interface Data extends DataOriginal {
14
19
  type?: string;
15
- data?: any;
20
+ data?: string;
16
21
  thumbnail?: DataURI;
17
22
  queued?: string | null;
18
23
  path?: string | null;
@@ -26,6 +31,14 @@ export interface Remote {
26
31
  getAccessToken?: () => Promise<string>;
27
32
  timeout?: number;
28
33
  }
34
+ type ResizeResult = [image: HTMLImageElement, dataURI: DataURI];
35
+ export type FormDataEntry = [name: string, blob: Blob, fileName: string];
36
+ export type WarehouseMediaNames = Record<string, {
37
+ name: string;
38
+ }>;
39
+ type Submission = {
40
+ values: Record<string, unknown>;
41
+ };
29
42
  declare class Media<T extends Data = Data, S extends Metadata = Metadata> extends Model<T> {
30
43
  /**
31
44
  * Transforms and resizes an image file into a string.
@@ -36,7 +49,10 @@ declare class Media<T extends Data = Data, S extends Metadata = Metadata> extend
36
49
  * @param onSaveSuccess
37
50
  * @returns {number}
38
51
  */
39
- static getDataURI(file: any, options?: any): Promise<[
52
+ static getDataURI(file: string | Blob, options?: {
53
+ width?: number;
54
+ height?: number;
55
+ }): Promise<[
40
56
  dataURI: DataURI,
41
57
  fileType: string,
42
58
  width: number,
@@ -45,7 +61,7 @@ declare class Media<T extends Data = Data, S extends Metadata = Metadata> extend
45
61
  /**
46
62
  * http://stackoverflow.com/questions/2516117/how-to-scale-an-image-in-data-uri-format-in-javascript-real-scaling-not-usin
47
63
  */
48
- static resize(data: URL | DataURI, fileType: string, MAX_WIDTH?: number, MAX_HEIGHT?: number): Promise<unknown>;
64
+ static resize(data: URL | DataURI, fileType: string, MAX_WIDTH?: number, MAX_HEIGHT?: number): Promise<ResizeResult>;
49
65
  /**
50
66
  * Create new image model with a photo
51
67
  * @param ImageModel Class representing the model.
@@ -61,19 +77,19 @@ declare class Media<T extends Data = Data, S extends Metadata = Metadata> extend
61
77
  };
62
78
  metadata: S;
63
79
  debouncedValue: number;
64
- constructor({ metadata, ...options }?: Options);
65
- parent?: Sample | Occurrence;
80
+ constructor({ metadata, ...options }?: Options<NoInfer<T>, NoInfer<S>>);
81
+ parent?: Sample | Occurrence | Location;
66
82
  toJSON(): any;
67
83
  setUpdatedAtTimestamp(newUpdatedAt: number): void;
68
- toDTO(warehouseMediaNames?: any): any;
84
+ toDTO(warehouseMediaNames?: WarehouseMediaNames): Submission;
69
85
  sync(): Promise<void>;
70
86
  uploadFile(force?: boolean): Promise<void>;
71
- getFormData(): Promise<unknown[]>;
87
+ getFormData(): Promise<FormDataEntry>;
72
88
  getRemoteURL(): string;
73
89
  /**
74
90
  * Returns image's absolute URL or dataURI.
75
91
  */
76
- getURL(): any;
92
+ getURL(): string;
77
93
  /**
78
94
  * Resizes itself.
79
95
  */
@@ -90,4 +106,5 @@ declare class Media<T extends Data = Data, S extends Metadata = Metadata> extend
90
106
  get isDisabled(): boolean;
91
107
  get isSynchronising(): boolean;
92
108
  }
109
+ export type MediaConstructor = new (...args: never[]) => Media;
93
110
  export default Media;