@amedia/user 0.1.2 → 0.2.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.
Files changed (40) hide show
  1. package/dist/actions/authentication.d.ts +4 -0
  2. package/dist/actions/authorization.d.ts +3 -0
  3. package/dist/cache/engines/global.d.ts +6 -0
  4. package/dist/cache/engines/indexeddb.d.ts +6 -0
  5. package/dist/cache/index.d.ts +9 -0
  6. package/dist/cache/types.d.ts +10 -0
  7. package/dist/eventHandlers/activation.d.ts +13 -0
  8. package/dist/eventHandlers/authentication.d.ts +15 -0
  9. package/dist/eventHandlers/userAttributes.d.ts +12 -0
  10. package/dist/index.d.ts +2 -1
  11. package/dist/index.js +1 -1
  12. package/dist/lib/dataOrganizer.d.ts +2 -9
  13. package/dist/services/pluto.d.ts +5 -10
  14. package/dist/types.d.ts +12 -0
  15. package/dist/utils/customEventWrapper.d.ts +3 -0
  16. package/dist/utils/queue.d.ts +5 -0
  17. package/package.json +3 -2
  18. package/src/actions/authentication.ts +37 -0
  19. package/src/actions/authorization.ts +51 -0
  20. package/src/{lib/cache → cache/engines}/global.ts +5 -3
  21. package/src/{lib/cache/db.ts → cache/engines/indexeddb.ts} +5 -5
  22. package/src/cache/index.spec.ts +82 -0
  23. package/src/{services/cache.ts → cache/index.ts} +25 -13
  24. package/src/{lib/cache → cache}/types.ts +7 -1
  25. package/src/eventHandlers/activation.ts +29 -0
  26. package/src/eventHandlers/authentication.ts +29 -0
  27. package/src/{lib → eventHandlers}/userAttributes.ts +11 -12
  28. package/src/index.spec.ts +49 -30
  29. package/src/index.ts +14 -5
  30. package/src/lib/dataOrganizer.ts +33 -14
  31. package/src/services/pluto.spec.ts +3 -2
  32. package/src/services/pluto.ts +14 -10
  33. package/src/types.ts +13 -0
  34. package/src/utils/customEventWrapper.ts +42 -0
  35. package/src/utils/log.ts +7 -0
  36. package/src/lib/authentication.ts +0 -94
  37. package/src/lib/authorization.ts +0 -86
  38. package/src/lib/eventHandler.ts +0 -16
  39. package/src/lib/types.ts +0 -7
  40. /package/src/{lib → utils}/queue.ts +0 -0
@@ -0,0 +1,4 @@
1
+ import { Session } from '../services/pluto';
2
+ export declare const login: (requestedUrl: string) => void;
3
+ export declare const logout: () => void;
4
+ export declare const getSession: () => Promise<Session | null>;
@@ -0,0 +1,3 @@
1
+ import { AccessFeatures, CheckAccessForPaper } from '../services/jupiter';
2
+ export declare const checkForAccessToPublication: (publicationDomain: string, accessFeatures: AccessFeatures) => Promise<CheckAccessForPaper | null>;
3
+ export declare const activate: () => Promise<unknown>;
@@ -0,0 +1,6 @@
1
+ import { CacheEntry, Engine } from '../types';
2
+ export declare const get: (key: string) => Promise<CacheEntry>;
3
+ export declare const set: (key: string, data: unknown, expires: number) => Promise<void>;
4
+ export declare const remove: (key: string) => Promise<void>;
5
+ declare const _default: Engine;
6
+ export default _default;
@@ -0,0 +1,6 @@
1
+ import { CacheEntry, Engine } from '../types';
2
+ export declare const get: (key: string) => Promise<CacheEntry>;
3
+ export declare const set: (key: string, data: unknown, expires: number) => Promise<void>;
4
+ export declare const remove: (key: string) => Promise<void>;
5
+ declare const _default: Engine;
6
+ export default _default;
@@ -0,0 +1,9 @@
1
+ import { Record, Static } from 'runtypes';
2
+ import { Engine } from './types';
3
+ export declare const setCacheEngine: (engine: Engine) => void;
4
+ declare const _default: {
5
+ get: <T extends Record<any, any>>(key: string, validator: T) => Promise<void | Static<T>>;
6
+ set: (key: string, value: unknown, expires: number) => Promise<void>;
7
+ remove: (key: string) => Promise<void>;
8
+ };
9
+ export default _default;
@@ -0,0 +1,10 @@
1
+ export declare type CacheEntry = {
2
+ key: string;
3
+ data: unknown;
4
+ expires: number;
5
+ };
6
+ export declare type Engine = {
7
+ get: (key: string) => Promise<CacheEntry | null>;
8
+ set: (key: string, data: unknown, expires: number) => Promise<void>;
9
+ remove: (key: string) => Promise<void>;
10
+ };
@@ -0,0 +1,13 @@
1
+ export declare enum ActivationEvents {
2
+ REQUEST_ACTIVATION = "amedia-user.activation.request-activation",
3
+ ON_ACTIVATION_COMPLETE = "amedia-user.activation.on-activation-complete"
4
+ }
5
+ declare global {
6
+ interface WindowEventMap {
7
+ [ActivationEvents.REQUEST_ACTIVATION]: CustomEvent;
8
+ [ActivationEvents.ON_ACTIVATION_COMPLETE]: CustomEvent<{
9
+ status: 'success' | 'error';
10
+ }>;
11
+ }
12
+ }
13
+ export declare const listenForActivationRequests: () => void;
@@ -0,0 +1,15 @@
1
+ export declare enum AuthenticationEvents {
2
+ REQUEST_LOGIN = "amedia-user.authentication.request-login",
3
+ REQUEST_LOGOUT = "amedia-user.authentication.request-logout"
4
+ }
5
+ declare global {
6
+ interface WindowEventMap {
7
+ [AuthenticationEvents.REQUEST_LOGIN]: CustomEvent<{
8
+ requestedUrl?: string;
9
+ }>;
10
+ [AuthenticationEvents.REQUEST_LOGOUT]: CustomEvent<{
11
+ requestedUrl?: string;
12
+ }>;
13
+ }
14
+ }
15
+ export declare const listenForAuthenticationRequests: () => void;
@@ -0,0 +1,12 @@
1
+ import { UserAttributes } from '../types';
2
+ export declare enum AmediaUserEvents {
3
+ REQUEST_USER_ATTRIBUTES = "amedia-user.request-user-attributes",
4
+ ON_USER_ATTRIBUTES_UPDATED = "amedia-user.on-user-attributes-updated"
5
+ }
6
+ declare global {
7
+ interface WindowEventMap {
8
+ [AmediaUserEvents.REQUEST_USER_ATTRIBUTES]: CustomEvent<Array<keyof UserAttributes>>;
9
+ [AmediaUserEvents.ON_USER_ATTRIBUTES_UPDATED]: CustomEvent<UserAttributes>;
10
+ }
11
+ }
12
+ export declare const listenForUserAttributeRequests: () => void;
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { UserAttributes } from './lib/types';
1
+ import { UserAttributes } from './types';
2
2
  /**
3
3
  * Enables you to subscribe to the user attributes you care about and
4
4
  * get notified when something changes
@@ -18,3 +18,4 @@ export declare const subscribeToUserUpdates: <T extends (keyof UserAttributes)[]
18
18
  * @param requestedUrl
19
19
  */
20
20
  export declare const requestLogin: (requestedUrl?: string | undefined) => void;
21
+ export declare const activate: () => Promise<unknown>;
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.user=t():e.user=t()}(self,(function(){return(()=>{"use strict";var e={36:function(e,t,r){var n=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,o,a=r.call(e),i=[];try{for(;(void 0===t||t-- >0)&&!(n=a.next()).done;)i.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(r=a.return)&&r.call(a)}finally{if(o)throw o.error}}return i},o=this&&this.__spreadArray||function(e,t){for(var r=0,n=t.length,o=e.length;r<n;r++,o++)e[o]=t[r];return e};Object.defineProperty(t,"__esModule",{value:!0}),t.AsyncContract=void 0;var a=r(888),i=r(611);t.AsyncContract=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r=e.length-1,u=e.slice(0,r),c=e[r];return{enforce:function(e){return function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];if(t.length<u.length){var l="Expected "+u.length+" arguments but only received "+t.length,f=i.FAILURE.ARGUMENT_INCORRECT(l);throw new a.ValidationError(f)}for(var s=0;s<u.length;s++)u[s].check(t[s]);var d=e.apply(void 0,o([],n(t)));if(!(d instanceof Promise))throw l="Expected function to return a promise, but instead got "+d,f=i.FAILURE.RETURN_INCORRECT(l),new a.ValidationError(f);return d.then(c.check)}}}}},361:function(e,t,r){var n=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,o,a=r.call(e),i=[];try{for(;(void 0===t||t-- >0)&&!(n=a.next()).done;)i.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(r=a.return)&&r.call(a)}finally{if(o)throw o.error}}return i},o=this&&this.__spreadArray||function(e,t){for(var r=0,n=t.length,o=e.length;r<n;r++,o++)e[o]=t[r];return e};Object.defineProperty(t,"__esModule",{value:!0}),t.Contract=void 0;var a=r(888),i=r(611);t.Contract=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r=e.length-1,u=e.slice(0,r),c=e[r];return{enforce:function(e){return function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];if(t.length<u.length){var l="Expected "+u.length+" arguments but only received "+t.length,f=i.FAILURE.ARGUMENT_INCORRECT(l);throw new a.ValidationError(f)}for(var s=0;s<u.length;s++)u[s].check(t[s]);return c.check(e.apply(void 0,o([],n(t))))}}}}},316:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.checked=t.check=void 0;var n=r(888),o=r(611),a=new WeakMap;function i(e,t,r){var n=a.get(e),o=n&&n.get(t);if(o)return o;for(var i=[],u=0;u<r;u++)i.push(u);return i}t.check=function(e,t,r){var n=a.get(e)||new Map;a.set(e,n);var o=n.get(t)||[];n.set(t,o),o.push(r)},t.checked=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];if(0===e.length)throw new Error("No runtype provided to `@checked`. Please remove the decorator.");return function(t,r,a){var u=a.value,c=(t.name||t.constructor.name+".prototype")+("string"==typeof r?'["'+r+'"]':"["+String(r)+"]"),l=i(t,r,e.length);if(l.length!==e.length)throw new Error("Number of `@checked` runtypes and @check parameters not matched.");if(l.length>u.length)throw new Error("Number of `@checked` runtypes exceeds actual parameter length.");a.value=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return e.forEach((function(e,r){var a=l[r],i=e.validate(t[a]);if(!i.success){var u=c+", argument #"+a+": "+i.message,f=o.FAILURE.ARGUMENT_INCORRECT(u);throw new n.ValidationError(f)}})),u.apply(this,t)}}}},888:function(e,t){var r,n=this&&this.__extends||(r=function(e,t){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])})(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}r(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)});Object.defineProperty(t,"__esModule",{value:!0}),t.ValidationError=void 0;var o=function(e){function t(r){var n=e.call(this,r.message)||this;return n.name="ValidationError",n.code=r.code,void 0!==r.details&&(n.details=r.details),Object.setPrototypeOf(n,t.prototype),n}return n(t,e),t}(Error);t.ValidationError=o},529:function(e,t,r){var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r),Object.defineProperty(e,n,{enumerable:!0,get:function(){return t[r]}})}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),o=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),t.InstanceOf=t.Null=t.Undefined=t.Literal=void 0,o(r(550),t),o(r(691),t),o(r(361),t),o(r(36),t),o(r(74),t),o(r(888),t),o(r(101),t),o(r(913),t),o(r(203),t);var a=r(275);Object.defineProperty(t,"Literal",{enumerable:!0,get:function(){return a.Literal}}),Object.defineProperty(t,"Undefined",{enumerable:!0,get:function(){return a.Undefined}}),Object.defineProperty(t,"Null",{enumerable:!0,get:function(){return a.Null}}),o(r(19),t),o(r(257),t),o(r(481),t),o(r(304),t),o(r(333),t),o(r(380),t),o(r(226),t),o(r(695),t),o(r(132),t),o(r(724),t),o(r(239),t),o(r(209),t),o(r(559),t);var i=r(867);Object.defineProperty(t,"InstanceOf",{enumerable:!0,get:function(){return i.InstanceOf}}),o(r(802),t),o(r(845),t),o(r(111),t),o(r(316),t)},74:function(e,t){var r=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},n=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,o,a=r.call(e),i=[];try{for(;(void 0===t||t-- >0)&&!(n=a.next()).done;)i.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(r=a.return)&&r.call(a)}finally{if(o)throw o.error}}return i};Object.defineProperty(t,"__esModule",{value:!0}),t.match=void 0,t.match=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return function(t){var o,a;try{for(var i=r(e),u=i.next();!u.done;u=i.next()){var c=n(u.value,2),l=c[0],f=c[1];if(l.guard(t))return f(t)}}catch(e){o={error:e}}finally{try{u&&!u.done&&(a=i.return)&&a.call(i)}finally{if(o)throw o.error}}throw new Error("No alternatives were matched")}}},550:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},691:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Failcode=void 0,t.Failcode={TYPE_INCORRECT:"TYPE_INCORRECT",VALUE_INCORRECT:"VALUE_INCORRECT",KEY_INCORRECT:"KEY_INCORRECT",CONTENT_INCORRECT:"CONTENT_INCORRECT",ARGUMENT_INCORRECT:"ARGUMENT_INCORRECT",RETURN_INCORRECT:"RETURN_INCORRECT",CONSTRAINT_FAILED:"CONSTRAINT_FAILED",PROPERTY_MISSING:"PROPERTY_MISSING",PROPERTY_PRESENT:"PROPERTY_PRESENT",NOTHING_EXPECTED:"NOTHING_EXPECTED"}},732:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.innerValidate=t.create=void 0;var n=r(529),o=r(233),a=r(888),i=r(611);t.create=function(e,t){return t.check=r,t.assert=r,t._innerValidate=function(r,n){return n.has(r,t)?i.SUCCESS(r):e(r,n)},t.validate=function(e){return t._innerValidate(e,(r=new WeakMap,n=function(e,t){if(null!==e&&"object"==typeof e){var n=r.get(e);r.set(e,n?n.set(t,!0):(new WeakMap).set(t,!0))}},{has:function(e,t){var o=r.get(e),a=o&&o.get(t)||!1;return n(e,t),a}}));var r,n},t.guard=function(e){return t.validate(e).success},t.Or=function(e){return n.Union(t,e)},t.And=function(e){return n.Intersect(t,e)},t.optional=function(){return n.Optional(t)},t.nullable=function(){return n.Union(t,n.Null)},t.withConstraint=function(e,r){return n.Constraint(t,e,r)},t.withGuard=function(e,r){return n.Constraint(t,e,r)},t.withBrand=function(e){return n.Brand(e,t)},t.reflect=t,t.toString=function(){return"Runtype<"+o.default(t)+">"},t;function r(e){var r=t.validate(e);if(r.success)return r.value;throw new a.ValidationError(r)}},t.innerValidate=function(e,t,r){return e._innerValidate(t,r)}},233:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0});var r=function(e,t){return function(o){var a=function(t){return e?"("+t+")":t};if(t.has(o))return a("CIRCULAR "+o.tag);t.add(o);try{switch(o.tag){case"unknown":case"never":case"void":case"boolean":case"number":case"bigint":case"string":case"symbol":case"function":return o.tag;case"literal":var i=o.value;return"string"==typeof i?'"'+i+'"':String(i);case"array":return""+n(o)+r(!0,t)(o.element)+"[]";case"dictionary":return"{ [_: "+o.key+"]: "+r(!1,t)(o.value)+" }";case"record":var u=Object.keys(o.fields);return u.length?"{ "+u.map((function(e){return""+n(o)+e+(i=e,u=(a=o).isPartial,c=a.fields,(u||void 0!==i&&"optional"===c[i].tag?"?":"")+": ")+("optional"===o.fields[e].tag?r(!1,t)(o.fields[e].underlying):r(!1,t)(o.fields[e]))+";";var a,i,u,c})).join(" ")+" }":"{}";case"tuple":return"["+o.components.map(r(!1,t)).join(", ")+"]";case"union":return a(""+o.alternatives.map(r(!0,t)).join(" | "));case"intersect":return a(""+o.intersectees.map(r(!0,t)).join(" & "));case"optional":return r(e,t)(o.underlying)+" | undefined";case"constraint":return o.name||r(e,t)(o.underlying);case"instanceof":return o.ctor.name;case"brand":return r(e,t)(o.entity)}}finally{t.delete(o)}throw Error("impossible")}};function n(e){return e.isReadonly?"readonly ":""}t.default=r(!1,new Set)},380:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Array=void 0;var n=r(732),o=r(611);function a(e,t){var r,i={tag:"array",isReadonly:t,element:e};return(r=n.create((function(t,r){if(!Array.isArray(t))return o.FAILURE.TYPE_INCORRECT(i,t);var a=o.enumerableKeysOf(t),u=a.map((function(o){return n.innerValidate(e,t[o],r)})),c=a.reduce((function(e,t){var r=u[t];return r.success||(e[t]=r.details||r.message),e}),[]);return 0!==o.enumerableKeysOf(c).length?o.FAILURE.CONTENT_INCORRECT(i,c):o.SUCCESS(t)}),i)).asReadonly=function(){return a(r.element,!0)},r}t.Array=function(e){return a(e,!1)}},481:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BigInt=void 0;var n=r(732),o=r(611),a={tag:"bigint"};t.BigInt=n.create((function(e){return"bigint"==typeof e?o.SUCCESS(e):o.FAILURE.TYPE_INCORRECT(a,e)}),a)},19:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Boolean=void 0;var n=r(732),o=r(611),a={tag:"boolean"};t.Boolean=n.create((function(e){return"boolean"==typeof e?o.SUCCESS(e):o.FAILURE.TYPE_INCORRECT(a,e)}),a)},111:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Brand=void 0;var n=r(732);t.Brand=function(e,t){var r={tag:"brand",brand:e,entity:t};return n.create((function(e){return t.validate(e)}),r)}},845:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Guard=t.Constraint=void 0;var n=r(732),o=r(611),a=r(101);t.Constraint=function(e,t,r){var a=r&&r.name,i=r&&r.args,u={tag:"constraint",underlying:e,constraint:t,name:a,args:i};return n.create((function(r){var n=e.validate(r);if(!n.success)return n;var a=t(n.value);return"string"==typeof a?o.FAILURE.CONSTRAINT_FAILED(u,a):a?o.SUCCESS(n.value):o.FAILURE.CONSTRAINT_FAILED(u)}),u)},t.Guard=function(e,t){return a.Unknown.withGuard(e,t)}},132:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Dictionary=void 0;var n=r(732),o=r(304),a=r(845),i=r(233),u=r(611),c=a.Constraint(o.String,(function(e){return!isNaN(+e)}),{name:"number"});t.Dictionary=function(e,t){var a=void 0===t||"string"===t?o.String:"number"===t?c:t,l=i.default(a),f={tag:"dictionary",key:l,value:e};return n.create((function(t,o){if(null==t||"object"!=typeof t)return u.FAILURE.TYPE_INCORRECT(f,t);if(Object.getPrototypeOf(t)!==Object.prototype&&(!Array.isArray(t)||"string"===l))return u.FAILURE.TYPE_INCORRECT(f,t);var i=/^(?:NaN|-?\d+(?:\.\d+)?)$/u,c=u.enumerableKeysOf(t),s=c.reduce((function(c,l){var s="string"==typeof l&&i.test(l),d=s?r.g.Number(l):l;return(s?a.guard(d)||a.guard(l):a.guard(d))?c[l]=n.innerValidate(e,t[l],o):c[l]=u.FAILURE.KEY_INCORRECT(f,a.reflect,d),c}),{}),d=c.reduce((function(e,t){var r=s[t];return r.success||(e[t]=r.details||r.message),e}),{});return 0!==u.enumerableKeysOf(d).length?u.FAILURE.CONTENT_INCORRECT(f,d):u.SUCCESS(t)}),f)}},559:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Function=void 0;var n=r(732),o=r(611),a={tag:"function"};t.Function=n.create((function(e){return"function"==typeof e?o.SUCCESS(e):o.FAILURE.TYPE_INCORRECT(a,e)}),a)},867:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.InstanceOf=void 0;var n=r(732),o=r(611);t.InstanceOf=function(e){var t={tag:"instanceof",ctor:e};return n.create((function(r){return r instanceof e?o.SUCCESS(r):o.FAILURE.TYPE_INCORRECT(t,r)}),t)}},239:function(e,t,r){var n=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(t,"__esModule",{value:!0}),t.Intersect=void 0;var o=r(732),a=r(611);t.Intersect=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r={tag:"intersect",intersectees:e};return o.create((function(t,r){var i,u;try{for(var c=n(e),l=c.next();!l.done;l=c.next()){var f=l.value,s=o.innerValidate(f,t,r);if(!s.success)return s}}catch(e){i={error:e}}finally{try{l&&!l.done&&(u=c.return)&&u.call(c)}finally{if(i)throw i.error}}return a.SUCCESS(t)}),r)}},802:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Lazy=void 0;var n=r(732);t.Lazy=function(e){var t,r={get tag(){return o().tag}};function o(){if(!t)for(var n in t=e())"tag"!==n&&(r[n]=t[n]);return t}return n.create((function(e){return o().validate(e)}),r)}},275:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Null=t.Undefined=t.Literal=void 0;var n=r(732),o=r(611);function a(e){return Array.isArray(e)?String(e.map(String)):"bigint"==typeof e?String(e)+"n":String(e)}function i(e){var t={tag:"literal",value:e};return n.create((function(t){return t===e?o.SUCCESS(t):o.FAILURE.VALUE_INCORRECT("literal","`"+a(e)+"`","`"+a(t)+"`")}),t)}t.Literal=i,t.Undefined=i(void 0),t.Null=i(null)},913:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Never=void 0;var n=r(732),o=r(611);t.Never=n.create(o.FAILURE.NOTHING_EXPECTED,{tag:"never"})},257:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Number=void 0;var n=r(732),o=r(611),a={tag:"number"};t.Number=n.create((function(e){return"number"==typeof e?o.SUCCESS(e):o.FAILURE.TYPE_INCORRECT(a,e)}),a)},209:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Optional=void 0;var n=r(732),o=r(611);t.Optional=function(e){var t={tag:"optional",underlying:e};return n.create((function(t){return void 0===t?o.SUCCESS(t):e.validate(t)}),t)}},695:function(e,t,r){var n=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,o,a=r.call(e),i=[];try{for(;(void 0===t||t-- >0)&&!(n=a.next()).done;)i.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(r=a.return)&&r.call(a)}finally{if(o)throw o.error}}return i},o=this&&this.__spreadArray||function(e,t){for(var r=0,n=t.length,o=e.length;r<n;r++,o++)e[o]=t[r];return e};Object.defineProperty(t,"__esModule",{value:!0}),t.Partial=t.Record=t.InternalRecord=void 0;var a=r(732),i=r(611);function u(e,t,r){var c,l={tag:"record",isPartial:t,isReadonly:r,fields:e};return(c=a.create((function(r,u){if(null==r)return i.FAILURE.TYPE_INCORRECT(l,r);var c=i.enumerableKeysOf(e);if(0!==c.length&&"object"!=typeof r)return i.FAILURE.TYPE_INCORRECT(l,r);var f=o([],n(new Set(o(o([],n(c)),n(i.enumerableKeysOf(r)))))),s=f.reduce((function(n,o){var c=i.hasKey(o,e),l=i.hasKey(o,r);if(c){var f=e[o],s=t||"optional"===f.reflect.tag;if(l){var d=r[o];n[o]=s&&void 0===d?i.SUCCESS(d):a.innerValidate(f,d,u)}else n[o]=s?i.SUCCESS(void 0):i.FAILURE.PROPERTY_MISSING(f.reflect)}else{if(!l)throw new Error("impossible");d=r[o],n[o]=i.SUCCESS(d)}return n}),{}),d=f.reduce((function(e,t){var r=s[t];return r.success||(e[t]=r.details||r.message),e}),{});return 0!==i.enumerableKeysOf(d).length?i.FAILURE.CONTENT_INCORRECT(l,d):i.SUCCESS(r)}),l)).asPartial=function(){return u(c.fields,!0,c.isReadonly)},c.asReadonly=function(){return u(c.fields,c.isPartial,!0)},c.pick=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r={};return e.forEach((function(e){r[e]=c.fields[e]})),u(r,c.isPartial,c.isReadonly)},c.omit=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r={};return i.enumerableKeysOf(c.fields).forEach((function(t){e.includes(t)||(r[t]=c.fields[t])})),u(r,c.isPartial,c.isReadonly)},c}t.InternalRecord=u,t.Record=function(e){return u(e,!1,!1)},t.Partial=function(e){return u(e,!0,!1)}},304:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.String=void 0;var n=r(732),o=r(611),a={tag:"string"};t.String=n.create((function(e){return"string"==typeof e?o.SUCCESS(e):o.FAILURE.TYPE_INCORRECT(a,e)}),a)},333:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Symbol=void 0;var n=r(732),o=r(611),a={tag:"symbol"};t.Symbol=n.create((function(e){return"symbol"==typeof e?o.SUCCESS(e):o.FAILURE.TYPE_INCORRECT(a,e)}),Object.assign((function(e){var t={tag:"symbol",key:e};return n.create((function(n){if("symbol"!=typeof n)return o.FAILURE.TYPE_INCORRECT(t,n);var a=r.g.Symbol.keyFor(n);return a!==e?o.FAILURE.VALUE_INCORRECT("symbol key",i(e),i(a)):o.SUCCESS(n)}),t)}),a));var i=function(e){return void 0===e?"undefined":'"'+e+'"'}},226:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Tuple=void 0;var n=r(732),o=r(611);t.Tuple=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r={tag:"tuple",components:e};return n.create((function(t,a){if(!Array.isArray(t))return o.FAILURE.TYPE_INCORRECT(r,t);if(t.length!==e.length)return o.FAILURE.CONSTRAINT_FAILED(r,"Expected length "+e.length+", but was "+t.length);var i=o.enumerableKeysOf(t),u=i.map((function(r){return n.innerValidate(e[r],t[r],a)})),c=i.reduce((function(e,t){var r=u[t];return r.success||(e[t]=r.details||r.message),e}),[]);return 0!==o.enumerableKeysOf(c).length?o.FAILURE.CONTENT_INCORRECT(r,c):o.SUCCESS(t)}),r)}},724:function(e,t,r){var n=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(t,"__esModule",{value:!0}),t.Union=void 0;var o=r(732),a=r(611);t.Union=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return function(r){for(var n=0;n<e.length;n++)if(e[n].guard(r))return t[n](r)}},i={tag:"union",alternatives:e,match:r};return o.create((function(t,r){var u,c,l,f,s,d,v,E;if("object"!=typeof t||null===t){try{for(var y=n(e),R=y.next();!R.done;R=y.next()){var _=R.value;if(o.innerValidate(_,t,r).success)return a.SUCCESS(t)}}catch(e){u={error:e}}finally{try{R&&!R.done&&(c=y.return)&&c.call(y)}finally{if(u)throw u.error}}return a.FAILURE.TYPE_INCORRECT(i,t)}var h={};try{for(var p=n(e),g=p.next();!g.done;g=p.next())if("record"===(_=g.value).reflect.tag){var T=function(e){var t=_.reflect.fields[e];"literal"===t.tag&&(h[e]?h[e].every((function(e){return e!==t.value}))&&h[e].push(t.value):h[e]=[t.value])};for(var C in _.reflect.fields)T(C)}}catch(e){l={error:e}}finally{try{g&&!g.done&&(f=p.return)&&f.call(p)}finally{if(l)throw l.error}}for(var C in h)if(h[C].length===e.length)try{for(var O=(s=void 0,n(e)),S=O.next();!S.done;S=O.next())if("record"===(_=S.value).reflect.tag){var b=_.reflect.fields[C];if("literal"===b.tag&&a.hasKey(C,t)&&t[C]===b.value)return o.innerValidate(_,t,r)}}catch(e){s={error:e}}finally{try{S&&!S.done&&(d=O.return)&&d.call(O)}finally{if(s)throw s.error}}try{for(var I=n(e),m=I.next();!m.done;m=I.next()){var U=m.value;if(o.innerValidate(U,t,r).success)return a.SUCCESS(t)}}catch(e){v={error:e}}finally{try{m&&!m.done&&(E=I.return)&&E.call(I)}finally{if(v)throw v.error}}return a.FAILURE.TYPE_INCORRECT(i,t)}),i)}},101:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Unknown=void 0;var n=r(732),o=r(611);t.Unknown=n.create((function(e){return o.SUCCESS(e)}),{tag:"unknown"})},203:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Void=void 0;var n=r(101);t.Void=n.Unknown},611:function(e,t,r){var n=this&&this.__assign||function(){return(n=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var o in t=arguments[r])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e}).apply(this,arguments)};Object.defineProperty(t,"__esModule",{value:!0}),t.FAILURE=t.SUCCESS=t.enumerableKeysOf=t.typeOf=t.hasKey=void 0;var o=r(691),a=r(233);t.hasKey=function(e,t){return"object"==typeof t&&null!==t&&e in t},t.typeOf=function(e){return"object"==typeof e?null===e?"null":Array.isArray(e)?"array":"Object"===e.constructor.name?"object":e.constructor.name:typeof e},t.enumerableKeysOf=function(e){return"object"==typeof e&&null!==e?Reflect.ownKeys(e).filter((function(t){var r,n;return null===(n=null===(r=e.propertyIsEnumerable)||void 0===r?void 0:r.call(e,t))||void 0===n||n})):[]},t.SUCCESS=function(e){return{success:!0,value:e}},t.FAILURE=Object.assign((function(e,t,r){return n({success:!1,code:e,message:t},r?{details:r}:{})}),{TYPE_INCORRECT:function(e,r){var n="Expected "+a.default(e)+", but was "+t.typeOf(r);return t.FAILURE(o.Failcode.TYPE_INCORRECT,n)},VALUE_INCORRECT:function(e,r,n){return t.FAILURE(o.Failcode.VALUE_INCORRECT,"Expected "+e+" "+String(r)+", but was "+String(n))},KEY_INCORRECT:function(e,r,n){return t.FAILURE(o.Failcode.KEY_INCORRECT,"Expected "+a.default(e)+" key to be "+a.default(r)+", but was "+t.typeOf(n))},CONTENT_INCORRECT:function(e,r){var n="Expected "+a.default(e)+", but was incompatible";return t.FAILURE(o.Failcode.CONTENT_INCORRECT,n,r)},ARGUMENT_INCORRECT:function(e){return t.FAILURE(o.Failcode.ARGUMENT_INCORRECT,e)},RETURN_INCORRECT:function(e){return t.FAILURE(o.Failcode.RETURN_INCORRECT,e)},CONSTRAINT_FAILED:function(e,r){var n=r?": "+r:"";return t.FAILURE(o.Failcode.CONSTRAINT_FAILED,"Failed constraint check for "+a.default(e)+n)},PROPERTY_MISSING:function(e){var r="Expected "+a.default(e)+", but was missing";return t.FAILURE(o.Failcode.PROPERTY_MISSING,r)},PROPERTY_PRESENT:function(e){var r="Expected nothing, but was "+t.typeOf(e);return t.FAILURE(o.Failcode.PROPERTY_PRESENT,r)},NOTHING_EXPECTED:function(e){var r="Expected nothing, but was "+t.typeOf(e);return t.FAILURE(o.Failcode.NOTHING_EXPECTED,r)}})}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var a=t[n]={exports:{}};return e[n].call(a.exports,a,a.exports,r),a.exports}r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var n={};return(()=>{r.r(n),r.d(n,{requestLogin:()=>_,subscribeToUserUpdates:()=>R});const e=(window||r.g)["amedia-user-cache"]={},t={get:t=>{const r=e[t];return Promise.resolve(r)},set:(t,r,n)=>(e[t]={key:t,data:r,expires:n},Promise.resolve()),remove:t=>(delete e[t],Promise.resolve())};const o=()=>t,a=(e,t)=>{return r=void 0,n=void 0,i=function*(){const r=yield o().get(e);if(!r)return Promise.resolve();try{return t.check(r)}catch(t){return console.error("Failed validating data",{data:r,error:t}),o().remove(e),Promise.resolve()}},new((a=void 0)||(a=Promise))((function(e,t){function o(e){try{c(i.next(e))}catch(e){t(e)}}function u(e){try{c(i.throw(e))}catch(e){t(e)}}function c(t){var r;t.done?e(t.value):(r=t.value,r instanceof a?r:new a((function(e){e(r)}))).then(o,u)}c((i=i.apply(r,n||[])).next())}));var r,n,a,i};var i=r(529);const u=(0,i.Record)({created_at:i.String,updated_at:i.String,user_uuid:i.String,user_name:i.String,tracking_key:i.String,user_agent:(0,i.Optional)(i.String),user_key:(0,i.Optional)(i.String)});let c=window||r.g;const l=(e,t)=>{c.addEventListener(e,t)},f=e=>{c.dispatchEvent(e)};var s;!function(e){e.REQUEST_LOGIN="amedia_user.authentication.request_login",e.REQUEST_LOGOUT="amedia_user.authentication.request_logout",e.REQUEST_AUTH_STATE="amedia_user.authentication.request_auth_state",e.ON_AUTH_STATE_UPDATED="amedia_user.authentication.on_auth_state_updated"}(s||(s={}));let d=!1;const v="is_logged_in",E=()=>{return e=void 0,t=void 0,n=function*(){if(d)return null;d=!0;const e=yield a(v,u);if(e)return d=!1,e;const t=yield(r=void 0,n=void 0,i=void 0,c=function*(){return fetch("/api/pluto/v1/sessions/current").then((e=>{if(!e.ok)throw new Error(`Request not ok (${e.status}: ${e.statusText}).`);return e.json()})).then((e=>{try{return u.check(e)}catch(e){throw console.error("Invalid schema",e),e}}))},new(i||(i=Promise))((function(e,t){function o(e){try{u(c.next(e))}catch(e){t(e)}}function a(e){try{u(c.throw(e))}catch(e){t(e)}}function u(t){var r;t.done?e(t.value):(r=t.value,r instanceof i?r:new i((function(e){e(r)}))).then(o,a)}u((c=c.apply(r,n||[])).next())})));var r,n,i,c,l,f,s;return l=v,f=t,s=Date.now()+1e4,o().set(l,f,s),d=!1,t},new((r=void 0)||(r=Promise))((function(o,a){function i(e){try{c(n.next(e))}catch(e){a(e)}}function u(e){try{c(n.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(i,u)}c((n=n.apply(e,t||[])).next())}));var e,t,r,n};var y;l(s.REQUEST_LOGIN,(e=>{if(!window)throw new Error("Cannot perform login in node-context yet!");(e=>{const t=new URL("https://aid.no/logg_inn/");t.searchParams.set("requestedUrl",e||window.location.href),window.location.href=t.href})(e.detail.requestedUrl||window.location.href)})),l(s.REQUEST_LOGOUT,(()=>{if(!window)throw new Error("Cannot perform login in node-context yet!")})),l(s.REQUEST_AUTH_STATE,(e=>{e.stopImmediatePropagation(),E().then((e=>{null!==e&&f(new CustomEvent(s.ON_AUTH_STATE_UPDATED,{detail:e}))}))})),function(e){e.REQUEST_USER_ATTRIBUTES="amedia-user.request-user-attributes",e.ON_USER_ATTRIBUTES_UPDATED="amedia-user.on-user-attributes-updated"}(y||(y={})),l(y.REQUEST_USER_ATTRIBUTES,(e=>{e.stopImmediatePropagation(),f(new CustomEvent(y.ON_USER_ATTRIBUTES_UPDATED,{detail:(e.detail,{isLoggedIn:!0,name:"Donald Duck"})}))}));const R=(e,t)=>{l(y.ON_USER_ATTRIBUTES_UPDATED,(r=>{const n=r.detail,o={isLoggedIn:n.isLoggedIn};e.forEach((e=>{void 0!==n[e]&&(o[e]=n[e])})),t(o)})),f(new CustomEvent(y.REQUEST_USER_ATTRIBUTES,{detail:e}))},_=e=>f(new CustomEvent(s.REQUEST_LOGIN,{detail:{requestedUrl:e}}))})(),n})()}));
1
+ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.user=t():e.user=t()}(self,(function(){return(()=>{"use strict";var e={36:function(e,t,r){var n=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,o,a=r.call(e),i=[];try{for(;(void 0===t||t-- >0)&&!(n=a.next()).done;)i.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(r=a.return)&&r.call(a)}finally{if(o)throw o.error}}return i},o=this&&this.__spreadArray||function(e,t){for(var r=0,n=t.length,o=e.length;r<n;r++,o++)e[o]=t[r];return e};Object.defineProperty(t,"__esModule",{value:!0}),t.AsyncContract=void 0;var a=r(888),i=r(611);t.AsyncContract=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r=e.length-1,u=e.slice(0,r),c=e[r];return{enforce:function(e){return function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];if(t.length<u.length){var l="Expected "+u.length+" arguments but only received "+t.length,f=i.FAILURE.ARGUMENT_INCORRECT(l);throw new a.ValidationError(f)}for(var s=0;s<u.length;s++)u[s].check(t[s]);var d=e.apply(void 0,o([],n(t)));if(!(d instanceof Promise))throw l="Expected function to return a promise, but instead got "+d,f=i.FAILURE.RETURN_INCORRECT(l),new a.ValidationError(f);return d.then(c.check)}}}}},361:function(e,t,r){var n=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,o,a=r.call(e),i=[];try{for(;(void 0===t||t-- >0)&&!(n=a.next()).done;)i.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(r=a.return)&&r.call(a)}finally{if(o)throw o.error}}return i},o=this&&this.__spreadArray||function(e,t){for(var r=0,n=t.length,o=e.length;r<n;r++,o++)e[o]=t[r];return e};Object.defineProperty(t,"__esModule",{value:!0}),t.Contract=void 0;var a=r(888),i=r(611);t.Contract=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r=e.length-1,u=e.slice(0,r),c=e[r];return{enforce:function(e){return function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];if(t.length<u.length){var l="Expected "+u.length+" arguments but only received "+t.length,f=i.FAILURE.ARGUMENT_INCORRECT(l);throw new a.ValidationError(f)}for(var s=0;s<u.length;s++)u[s].check(t[s]);return c.check(e.apply(void 0,o([],n(t))))}}}}},316:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.checked=t.check=void 0;var n=r(888),o=r(611),a=new WeakMap;function i(e,t,r){var n=a.get(e),o=n&&n.get(t);if(o)return o;for(var i=[],u=0;u<r;u++)i.push(u);return i}t.check=function(e,t,r){var n=a.get(e)||new Map;a.set(e,n);var o=n.get(t)||[];n.set(t,o),o.push(r)},t.checked=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];if(0===e.length)throw new Error("No runtype provided to `@checked`. Please remove the decorator.");return function(t,r,a){var u=a.value,c=(t.name||t.constructor.name+".prototype")+("string"==typeof r?'["'+r+'"]':"["+String(r)+"]"),l=i(t,r,e.length);if(l.length!==e.length)throw new Error("Number of `@checked` runtypes and @check parameters not matched.");if(l.length>u.length)throw new Error("Number of `@checked` runtypes exceeds actual parameter length.");a.value=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return e.forEach((function(e,r){var a=l[r],i=e.validate(t[a]);if(!i.success){var u=c+", argument #"+a+": "+i.message,f=o.FAILURE.ARGUMENT_INCORRECT(u);throw new n.ValidationError(f)}})),u.apply(this,t)}}}},888:function(e,t){var r,n=this&&this.__extends||(r=function(e,t){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])})(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}r(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)});Object.defineProperty(t,"__esModule",{value:!0}),t.ValidationError=void 0;var o=function(e){function t(r){var n=e.call(this,r.message)||this;return n.name="ValidationError",n.code=r.code,void 0!==r.details&&(n.details=r.details),Object.setPrototypeOf(n,t.prototype),n}return n(t,e),t}(Error);t.ValidationError=o},529:function(e,t,r){var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r),Object.defineProperty(e,n,{enumerable:!0,get:function(){return t[r]}})}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),o=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),t.InstanceOf=t.Null=t.Undefined=t.Literal=void 0,o(r(550),t),o(r(691),t),o(r(361),t),o(r(36),t),o(r(74),t),o(r(888),t),o(r(101),t),o(r(913),t),o(r(203),t);var a=r(275);Object.defineProperty(t,"Literal",{enumerable:!0,get:function(){return a.Literal}}),Object.defineProperty(t,"Undefined",{enumerable:!0,get:function(){return a.Undefined}}),Object.defineProperty(t,"Null",{enumerable:!0,get:function(){return a.Null}}),o(r(19),t),o(r(257),t),o(r(481),t),o(r(304),t),o(r(333),t),o(r(380),t),o(r(226),t),o(r(695),t),o(r(132),t),o(r(724),t),o(r(239),t),o(r(209),t),o(r(559),t);var i=r(867);Object.defineProperty(t,"InstanceOf",{enumerable:!0,get:function(){return i.InstanceOf}}),o(r(802),t),o(r(845),t),o(r(111),t),o(r(316),t)},74:function(e,t){var r=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},n=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,o,a=r.call(e),i=[];try{for(;(void 0===t||t-- >0)&&!(n=a.next()).done;)i.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(r=a.return)&&r.call(a)}finally{if(o)throw o.error}}return i};Object.defineProperty(t,"__esModule",{value:!0}),t.match=void 0,t.match=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return function(t){var o,a;try{for(var i=r(e),u=i.next();!u.done;u=i.next()){var c=n(u.value,2),l=c[0],f=c[1];if(l.guard(t))return f(t)}}catch(e){o={error:e}}finally{try{u&&!u.done&&(a=i.return)&&a.call(i)}finally{if(o)throw o.error}}throw new Error("No alternatives were matched")}}},550:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},691:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Failcode=void 0,t.Failcode={TYPE_INCORRECT:"TYPE_INCORRECT",VALUE_INCORRECT:"VALUE_INCORRECT",KEY_INCORRECT:"KEY_INCORRECT",CONTENT_INCORRECT:"CONTENT_INCORRECT",ARGUMENT_INCORRECT:"ARGUMENT_INCORRECT",RETURN_INCORRECT:"RETURN_INCORRECT",CONSTRAINT_FAILED:"CONSTRAINT_FAILED",PROPERTY_MISSING:"PROPERTY_MISSING",PROPERTY_PRESENT:"PROPERTY_PRESENT",NOTHING_EXPECTED:"NOTHING_EXPECTED"}},732:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.innerValidate=t.create=void 0;var n=r(529),o=r(233),a=r(888),i=r(611);t.create=function(e,t){return t.check=r,t.assert=r,t._innerValidate=function(r,n){return n.has(r,t)?i.SUCCESS(r):e(r,n)},t.validate=function(e){return t._innerValidate(e,(r=new WeakMap,n=function(e,t){if(null!==e&&"object"==typeof e){var n=r.get(e);r.set(e,n?n.set(t,!0):(new WeakMap).set(t,!0))}},{has:function(e,t){var o=r.get(e),a=o&&o.get(t)||!1;return n(e,t),a}}));var r,n},t.guard=function(e){return t.validate(e).success},t.Or=function(e){return n.Union(t,e)},t.And=function(e){return n.Intersect(t,e)},t.optional=function(){return n.Optional(t)},t.nullable=function(){return n.Union(t,n.Null)},t.withConstraint=function(e,r){return n.Constraint(t,e,r)},t.withGuard=function(e,r){return n.Constraint(t,e,r)},t.withBrand=function(e){return n.Brand(e,t)},t.reflect=t,t.toString=function(){return"Runtype<"+o.default(t)+">"},t;function r(e){var r=t.validate(e);if(r.success)return r.value;throw new a.ValidationError(r)}},t.innerValidate=function(e,t,r){return e._innerValidate(t,r)}},233:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0});var r=function(e,t){return function(o){var a=function(t){return e?"("+t+")":t};if(t.has(o))return a("CIRCULAR "+o.tag);t.add(o);try{switch(o.tag){case"unknown":case"never":case"void":case"boolean":case"number":case"bigint":case"string":case"symbol":case"function":return o.tag;case"literal":var i=o.value;return"string"==typeof i?'"'+i+'"':String(i);case"array":return""+n(o)+r(!0,t)(o.element)+"[]";case"dictionary":return"{ [_: "+o.key+"]: "+r(!1,t)(o.value)+" }";case"record":var u=Object.keys(o.fields);return u.length?"{ "+u.map((function(e){return""+n(o)+e+(i=e,u=(a=o).isPartial,c=a.fields,(u||void 0!==i&&"optional"===c[i].tag?"?":"")+": ")+("optional"===o.fields[e].tag?r(!1,t)(o.fields[e].underlying):r(!1,t)(o.fields[e]))+";";var a,i,u,c})).join(" ")+" }":"{}";case"tuple":return"["+o.components.map(r(!1,t)).join(", ")+"]";case"union":return a(""+o.alternatives.map(r(!0,t)).join(" | "));case"intersect":return a(""+o.intersectees.map(r(!0,t)).join(" & "));case"optional":return r(e,t)(o.underlying)+" | undefined";case"constraint":return o.name||r(e,t)(o.underlying);case"instanceof":return o.ctor.name;case"brand":return r(e,t)(o.entity)}}finally{t.delete(o)}throw Error("impossible")}};function n(e){return e.isReadonly?"readonly ":""}t.default=r(!1,new Set)},380:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Array=void 0;var n=r(732),o=r(611);function a(e,t){var r,i={tag:"array",isReadonly:t,element:e};return(r=n.create((function(t,r){if(!Array.isArray(t))return o.FAILURE.TYPE_INCORRECT(i,t);var a=o.enumerableKeysOf(t),u=a.map((function(o){return n.innerValidate(e,t[o],r)})),c=a.reduce((function(e,t){var r=u[t];return r.success||(e[t]=r.details||r.message),e}),[]);return 0!==o.enumerableKeysOf(c).length?o.FAILURE.CONTENT_INCORRECT(i,c):o.SUCCESS(t)}),i)).asReadonly=function(){return a(r.element,!0)},r}t.Array=function(e){return a(e,!1)}},481:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BigInt=void 0;var n=r(732),o=r(611),a={tag:"bigint"};t.BigInt=n.create((function(e){return"bigint"==typeof e?o.SUCCESS(e):o.FAILURE.TYPE_INCORRECT(a,e)}),a)},19:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Boolean=void 0;var n=r(732),o=r(611),a={tag:"boolean"};t.Boolean=n.create((function(e){return"boolean"==typeof e?o.SUCCESS(e):o.FAILURE.TYPE_INCORRECT(a,e)}),a)},111:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Brand=void 0;var n=r(732);t.Brand=function(e,t){var r={tag:"brand",brand:e,entity:t};return n.create((function(e){return t.validate(e)}),r)}},845:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Guard=t.Constraint=void 0;var n=r(732),o=r(611),a=r(101);t.Constraint=function(e,t,r){var a=r&&r.name,i=r&&r.args,u={tag:"constraint",underlying:e,constraint:t,name:a,args:i};return n.create((function(r){var n=e.validate(r);if(!n.success)return n;var a=t(n.value);return"string"==typeof a?o.FAILURE.CONSTRAINT_FAILED(u,a):a?o.SUCCESS(n.value):o.FAILURE.CONSTRAINT_FAILED(u)}),u)},t.Guard=function(e,t){return a.Unknown.withGuard(e,t)}},132:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Dictionary=void 0;var n=r(732),o=r(304),a=r(845),i=r(233),u=r(611),c=a.Constraint(o.String,(function(e){return!isNaN(+e)}),{name:"number"});t.Dictionary=function(e,t){var a=void 0===t||"string"===t?o.String:"number"===t?c:t,l=i.default(a),f={tag:"dictionary",key:l,value:e};return n.create((function(t,o){if(null==t||"object"!=typeof t)return u.FAILURE.TYPE_INCORRECT(f,t);if(Object.getPrototypeOf(t)!==Object.prototype&&(!Array.isArray(t)||"string"===l))return u.FAILURE.TYPE_INCORRECT(f,t);var i=/^(?:NaN|-?\d+(?:\.\d+)?)$/u,c=u.enumerableKeysOf(t),s=c.reduce((function(c,l){var s="string"==typeof l&&i.test(l),d=s?r.g.Number(l):l;return(s?a.guard(d)||a.guard(l):a.guard(d))?c[l]=n.innerValidate(e,t[l],o):c[l]=u.FAILURE.KEY_INCORRECT(f,a.reflect,d),c}),{}),d=c.reduce((function(e,t){var r=s[t];return r.success||(e[t]=r.details||r.message),e}),{});return 0!==u.enumerableKeysOf(d).length?u.FAILURE.CONTENT_INCORRECT(f,d):u.SUCCESS(t)}),f)}},559:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Function=void 0;var n=r(732),o=r(611),a={tag:"function"};t.Function=n.create((function(e){return"function"==typeof e?o.SUCCESS(e):o.FAILURE.TYPE_INCORRECT(a,e)}),a)},867:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.InstanceOf=void 0;var n=r(732),o=r(611);t.InstanceOf=function(e){var t={tag:"instanceof",ctor:e};return n.create((function(r){return r instanceof e?o.SUCCESS(r):o.FAILURE.TYPE_INCORRECT(t,r)}),t)}},239:function(e,t,r){var n=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(t,"__esModule",{value:!0}),t.Intersect=void 0;var o=r(732),a=r(611);t.Intersect=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r={tag:"intersect",intersectees:e};return o.create((function(t,r){var i,u;try{for(var c=n(e),l=c.next();!l.done;l=c.next()){var f=l.value,s=o.innerValidate(f,t,r);if(!s.success)return s}}catch(e){i={error:e}}finally{try{l&&!l.done&&(u=c.return)&&u.call(c)}finally{if(i)throw i.error}}return a.SUCCESS(t)}),r)}},802:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Lazy=void 0;var n=r(732);t.Lazy=function(e){var t,r={get tag(){return o().tag}};function o(){if(!t)for(var n in t=e())"tag"!==n&&(r[n]=t[n]);return t}return n.create((function(e){return o().validate(e)}),r)}},275:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Null=t.Undefined=t.Literal=void 0;var n=r(732),o=r(611);function a(e){return Array.isArray(e)?String(e.map(String)):"bigint"==typeof e?String(e)+"n":String(e)}function i(e){var t={tag:"literal",value:e};return n.create((function(t){return t===e?o.SUCCESS(t):o.FAILURE.VALUE_INCORRECT("literal","`"+a(e)+"`","`"+a(t)+"`")}),t)}t.Literal=i,t.Undefined=i(void 0),t.Null=i(null)},913:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Never=void 0;var n=r(732),o=r(611);t.Never=n.create(o.FAILURE.NOTHING_EXPECTED,{tag:"never"})},257:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Number=void 0;var n=r(732),o=r(611),a={tag:"number"};t.Number=n.create((function(e){return"number"==typeof e?o.SUCCESS(e):o.FAILURE.TYPE_INCORRECT(a,e)}),a)},209:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Optional=void 0;var n=r(732),o=r(611);t.Optional=function(e){var t={tag:"optional",underlying:e};return n.create((function(t){return void 0===t?o.SUCCESS(t):e.validate(t)}),t)}},695:function(e,t,r){var n=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,o,a=r.call(e),i=[];try{for(;(void 0===t||t-- >0)&&!(n=a.next()).done;)i.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(r=a.return)&&r.call(a)}finally{if(o)throw o.error}}return i},o=this&&this.__spreadArray||function(e,t){for(var r=0,n=t.length,o=e.length;r<n;r++,o++)e[o]=t[r];return e};Object.defineProperty(t,"__esModule",{value:!0}),t.Partial=t.Record=t.InternalRecord=void 0;var a=r(732),i=r(611);function u(e,t,r){var c,l={tag:"record",isPartial:t,isReadonly:r,fields:e};return(c=a.create((function(r,u){if(null==r)return i.FAILURE.TYPE_INCORRECT(l,r);var c=i.enumerableKeysOf(e);if(0!==c.length&&"object"!=typeof r)return i.FAILURE.TYPE_INCORRECT(l,r);var f=o([],n(new Set(o(o([],n(c)),n(i.enumerableKeysOf(r)))))),s=f.reduce((function(n,o){var c=i.hasKey(o,e),l=i.hasKey(o,r);if(c){var f=e[o],s=t||"optional"===f.reflect.tag;if(l){var d=r[o];n[o]=s&&void 0===d?i.SUCCESS(d):a.innerValidate(f,d,u)}else n[o]=s?i.SUCCESS(void 0):i.FAILURE.PROPERTY_MISSING(f.reflect)}else{if(!l)throw new Error("impossible");d=r[o],n[o]=i.SUCCESS(d)}return n}),{}),d=f.reduce((function(e,t){var r=s[t];return r.success||(e[t]=r.details||r.message),e}),{});return 0!==i.enumerableKeysOf(d).length?i.FAILURE.CONTENT_INCORRECT(l,d):i.SUCCESS(r)}),l)).asPartial=function(){return u(c.fields,!0,c.isReadonly)},c.asReadonly=function(){return u(c.fields,c.isPartial,!0)},c.pick=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r={};return e.forEach((function(e){r[e]=c.fields[e]})),u(r,c.isPartial,c.isReadonly)},c.omit=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r={};return i.enumerableKeysOf(c.fields).forEach((function(t){e.includes(t)||(r[t]=c.fields[t])})),u(r,c.isPartial,c.isReadonly)},c}t.InternalRecord=u,t.Record=function(e){return u(e,!1,!1)},t.Partial=function(e){return u(e,!0,!1)}},304:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.String=void 0;var n=r(732),o=r(611),a={tag:"string"};t.String=n.create((function(e){return"string"==typeof e?o.SUCCESS(e):o.FAILURE.TYPE_INCORRECT(a,e)}),a)},333:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Symbol=void 0;var n=r(732),o=r(611),a={tag:"symbol"};t.Symbol=n.create((function(e){return"symbol"==typeof e?o.SUCCESS(e):o.FAILURE.TYPE_INCORRECT(a,e)}),Object.assign((function(e){var t={tag:"symbol",key:e};return n.create((function(n){if("symbol"!=typeof n)return o.FAILURE.TYPE_INCORRECT(t,n);var a=r.g.Symbol.keyFor(n);return a!==e?o.FAILURE.VALUE_INCORRECT("symbol key",i(e),i(a)):o.SUCCESS(n)}),t)}),a));var i=function(e){return void 0===e?"undefined":'"'+e+'"'}},226:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Tuple=void 0;var n=r(732),o=r(611);t.Tuple=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r={tag:"tuple",components:e};return n.create((function(t,a){if(!Array.isArray(t))return o.FAILURE.TYPE_INCORRECT(r,t);if(t.length!==e.length)return o.FAILURE.CONSTRAINT_FAILED(r,"Expected length "+e.length+", but was "+t.length);var i=o.enumerableKeysOf(t),u=i.map((function(r){return n.innerValidate(e[r],t[r],a)})),c=i.reduce((function(e,t){var r=u[t];return r.success||(e[t]=r.details||r.message),e}),[]);return 0!==o.enumerableKeysOf(c).length?o.FAILURE.CONTENT_INCORRECT(r,c):o.SUCCESS(t)}),r)}},724:function(e,t,r){var n=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(t,"__esModule",{value:!0}),t.Union=void 0;var o=r(732),a=r(611);t.Union=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return function(r){for(var n=0;n<e.length;n++)if(e[n].guard(r))return t[n](r)}},i={tag:"union",alternatives:e,match:r};return o.create((function(t,r){var u,c,l,f,s,d,v,E;if("object"!=typeof t||null===t){try{for(var y=n(e),R=y.next();!R.done;R=y.next()){var h=R.value;if(o.innerValidate(h,t,r).success)return a.SUCCESS(t)}}catch(e){u={error:e}}finally{try{R&&!R.done&&(c=y.return)&&c.call(y)}finally{if(u)throw u.error}}return a.FAILURE.TYPE_INCORRECT(i,t)}var p={};try{for(var _=n(e),g=_.next();!g.done;g=_.next())if("record"===(h=g.value).reflect.tag){var C=function(e){var t=h.reflect.fields[e];"literal"===t.tag&&(p[e]?p[e].every((function(e){return e!==t.value}))&&p[e].push(t.value):p[e]=[t.value])};for(var T in h.reflect.fields)C(T)}}catch(e){l={error:e}}finally{try{g&&!g.done&&(f=_.return)&&f.call(_)}finally{if(l)throw l.error}}for(var T in p)if(p[T].length===e.length)try{for(var O=(s=void 0,n(e)),S=O.next();!S.done;S=O.next())if("record"===(h=S.value).reflect.tag){var b=h.reflect.fields[T];if("literal"===b.tag&&a.hasKey(T,t)&&t[T]===b.value)return o.innerValidate(h,t,r)}}catch(e){s={error:e}}finally{try{S&&!S.done&&(d=O.return)&&d.call(O)}finally{if(s)throw s.error}}try{for(var I=n(e),m=I.next();!m.done;m=I.next()){var N=m.value;if(o.innerValidate(N,t,r).success)return a.SUCCESS(t)}}catch(e){v={error:e}}finally{try{m&&!m.done&&(E=I.return)&&E.call(I)}finally{if(v)throw v.error}}return a.FAILURE.TYPE_INCORRECT(i,t)}),i)}},101:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Unknown=void 0;var n=r(732),o=r(611);t.Unknown=n.create((function(e){return o.SUCCESS(e)}),{tag:"unknown"})},203:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Void=void 0;var n=r(101);t.Void=n.Unknown},611:function(e,t,r){var n=this&&this.__assign||function(){return(n=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var o in t=arguments[r])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e}).apply(this,arguments)};Object.defineProperty(t,"__esModule",{value:!0}),t.FAILURE=t.SUCCESS=t.enumerableKeysOf=t.typeOf=t.hasKey=void 0;var o=r(691),a=r(233);t.hasKey=function(e,t){return"object"==typeof t&&null!==t&&e in t},t.typeOf=function(e){return"object"==typeof e?null===e?"null":Array.isArray(e)?"array":"Object"===e.constructor.name?"object":e.constructor.name:typeof e},t.enumerableKeysOf=function(e){return"object"==typeof e&&null!==e?Reflect.ownKeys(e).filter((function(t){var r,n;return null===(n=null===(r=e.propertyIsEnumerable)||void 0===r?void 0:r.call(e,t))||void 0===n||n})):[]},t.SUCCESS=function(e){return{success:!0,value:e}},t.FAILURE=Object.assign((function(e,t,r){return n({success:!1,code:e,message:t},r?{details:r}:{})}),{TYPE_INCORRECT:function(e,r){var n="Expected "+a.default(e)+", but was "+t.typeOf(r);return t.FAILURE(o.Failcode.TYPE_INCORRECT,n)},VALUE_INCORRECT:function(e,r,n){return t.FAILURE(o.Failcode.VALUE_INCORRECT,"Expected "+e+" "+String(r)+", but was "+String(n))},KEY_INCORRECT:function(e,r,n){return t.FAILURE(o.Failcode.KEY_INCORRECT,"Expected "+a.default(e)+" key to be "+a.default(r)+", but was "+t.typeOf(n))},CONTENT_INCORRECT:function(e,r){var n="Expected "+a.default(e)+", but was incompatible";return t.FAILURE(o.Failcode.CONTENT_INCORRECT,n,r)},ARGUMENT_INCORRECT:function(e){return t.FAILURE(o.Failcode.ARGUMENT_INCORRECT,e)},RETURN_INCORRECT:function(e){return t.FAILURE(o.Failcode.RETURN_INCORRECT,e)},CONSTRAINT_FAILED:function(e,r){var n=r?": "+r:"";return t.FAILURE(o.Failcode.CONSTRAINT_FAILED,"Failed constraint check for "+a.default(e)+n)},PROPERTY_MISSING:function(e){var r="Expected "+a.default(e)+", but was missing";return t.FAILURE(o.Failcode.PROPERTY_MISSING,r)},PROPERTY_PRESENT:function(e){var r="Expected nothing, but was "+t.typeOf(e);return t.FAILURE(o.Failcode.PROPERTY_PRESENT,r)},NOTHING_EXPECTED:function(e){var r="Expected nothing, but was "+t.typeOf(e);return t.FAILURE(o.Failcode.NOTHING_EXPECTED,r)}})}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var a=t[n]={exports:{}};return e[n].call(a.exports,a,a.exports,r),a.exports}r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var n={};return(()=>{r.r(n),r.d(n,{activate:()=>O,requestLogin:()=>T,subscribeToUserUpdates:()=>C});let e=window||r.g;const t=(t,r,n=!0)=>{e.addEventListener(t,(e=>{n&&e.stopImmediatePropagation(),r.apply(window,[e])}))},o=t=>{e.dispatchEvent(t)};var a=r(529);const i=(0,a.Record)({user_name:a.String,tracking_key:a.String}),u=(0,a.Record)({name:a.String,trackingKey:a.String}),c=window["amedia-user-cache"]={},l={get:e=>{const t=c[e];return Promise.resolve(t)},set:(e,t,r)=>(c[e]={key:e,data:t,expires:r},Promise.resolve()),remove:e=>(delete c[e],Promise.resolve())};const f=()=>l,s=e=>f().remove(e),d=(e,t)=>{return r=void 0,n=void 0,a=function*(){const r=yield f().get(e);if(!r)return Promise.resolve();if(Date.now()>r.expires)return s(e),Promise.resolve();try{return t.check(r.data)}catch(t){return console.error("Failed validating data",{cacheEntry:r,error:t}),s(e),Promise.resolve()}},new((o=void 0)||(o=Promise))((function(e,t){function i(e){try{c(a.next(e))}catch(e){t(e)}}function u(e){try{c(a.throw(e))}catch(e){t(e)}}function c(t){var r;t.done?e(t.value):(r=t.value,r instanceof o?r:new o((function(e){e(r)}))).then(i,u)}c((a=a.apply(r,n||[])).next())}));var r,n,o,a};let v=!1;const E="is_logged_in",y=()=>{return e=void 0,t=void 0,n=function*(){if(v)return null;v=!0;const e=yield d(E,u);if(e)return v=!1,e;const t=yield(r=void 0,n=void 0,o=void 0,a=function*(){return fetch("/api/pluto/v1/sessions/current").then((e=>{if(!e.ok)throw new Error(`Request not ok (${e.status}: ${e.statusText}).`);return e.json()})).then((e=>{try{return{name:(t=i.check(e)).user_name,trackingKey:t.tracking_key}}catch(e){throw console.error("Invalid schema",e),e}var t}))},new(o||(o=Promise))((function(e,t){function i(e){try{c(a.next(e))}catch(e){t(e)}}function u(e){try{c(a.throw(e))}catch(e){t(e)}}function c(t){var r;t.done?e(t.value):(r=t.value,r instanceof o?r:new o((function(e){e(r)}))).then(i,u)}c((a=a.apply(r,n||[])).next())})));var r,n,o,a,c,l,s;return c=E,l=t,s=Date.now()+1e4,f().set(c,l,s),v=!1,t},new((r=void 0)||(r=Promise))((function(o,a){function i(e){try{c(n.next(e))}catch(e){a(e)}}function u(e){try{c(n.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(i,u)}c((n=n.apply(e,t||[])).next())}));var e,t,r,n};var R;!function(e){e.REQUEST_LOGIN="amedia-user.authentication.request-login",e.REQUEST_LOGOUT="amedia-user.authentication.request-logout"}(R||(R={})),t(R.REQUEST_LOGIN,(e=>{(e=>{const t=new URL("https://aid.no/logg_inn/");t.searchParams.set("requestedUrl",e||window.location.href),window.location.href=t.href})(e.detail.requestedUrl||window.location.href)})),t(R.REQUEST_LOGOUT,(()=>{}));const h={name:y,trackingKey:y};var p;!function(e){e.REQUEST_USER_ATTRIBUTES="amedia-user.request-user-attributes",e.ON_USER_ATTRIBUTES_UPDATED="amedia-user.on-user-attributes-updated"}(p||(p={})),t(p.REQUEST_USER_ATTRIBUTES,(e=>{((e,t)=>{const r=[];for(e.forEach((e=>{const t=h[e];t?r.includes(t)||r.push(t):console.warn("Unknown attribute was requested")}));r.length>0;){const e=r.pop();e&&e().then((e=>{t(e)}))}})(e.detail,(e=>{o(new CustomEvent(p.ON_USER_ATTRIBUTES_UPDATED,{detail:e}))}))}));const _=(0,a.Record)({id:a.Number,domain:a.String});var g;(0,a.Record)({status:(0,a.Literal)("success"),access:(0,a.Union)((0,a.Literal)("granted"),(0,a.Literal)("denied")),publication:_,access_features:(0,a.Array)(a.String)}),(0,a.Record)({status:(0,a.Literal)("success"),cookie:a.String,access_features:(0,a.Array)(a.String)}),(0,a.Record)({status:(0,a.Literal)("success"),vstoken_cookie:a.String,uuid:a.String,access_features:(0,a.Array)(a.String)}),function(e){e.REQUEST_ACTIVATION="amedia-user.activation.request-activation",e.ON_ACTIVATION_COMPLETE="amedia-user.activation.on-activation-complete"}(g||(g={})),t(g.REQUEST_ACTIVATION,(()=>{new Promise(((e,t)=>{setTimeout((()=>{e({status:"success"})}),1e3)})).then((e=>{o(new CustomEvent(g.ON_ACTIVATION_COMPLETE,{detail:e}))}))}));const C=(e,r)=>{t(p.ON_USER_ATTRIBUTES_UPDATED,(t=>{const n=t.detail,o={isLoggedIn:n.isLoggedIn};e.forEach((e=>{void 0!==n[e]&&(o[e]=n[e])})),r(o)})),o(new CustomEvent(p.REQUEST_USER_ATTRIBUTES,{detail:e}))},T=e=>o(new CustomEvent(R.REQUEST_LOGIN,{detail:{requestedUrl:e}})),O=()=>new Promise(((e,r)=>{t(g.ON_ACTIVATION_COMPLETE,(t=>{e(t)})),o(new CustomEvent(g.REQUEST_ACTIVATION))}))})(),n})()}));
@@ -1,9 +1,2 @@
1
- import { UserAttributes } from './types';
2
- /**
3
- * Jeg tror ikke vi burde gjøre det slik som dette.
4
- * Denne funksjonen var hentet ut fra userAttribute kun for å
5
- * kunne mocke implementasjonen så jeg kunne teste event-callback mekanismen.
6
- *
7
- * En implementasjon som dette vil gjøre det vanskelig svare etterhvert som vi får data.
8
- */
9
- export declare const fetchDataBasedOnAttributes: (attributes: (keyof UserAttributes)[]) => UserAttributes;
1
+ import { UserAttributes } from '../types';
2
+ export declare const fetchDataBasedOnAttributes: (attributes: Array<keyof UserAttributes>, onDataUpdated: (attributes: UserAttributes) => void) => void;
@@ -1,13 +1,8 @@
1
- import { Optional, Record, Static, String } from 'runtypes';
2
- export declare const SessionSchema: Record<{
3
- created_at: String;
4
- updated_at: String;
5
- user_uuid: String;
6
- user_name: String;
7
- tracking_key: String;
8
- user_agent: Optional<String>;
9
- user_key: Optional<String>;
1
+ import { Record, Static, String } from 'runtypes';
2
+ export declare const Session: Record<{
3
+ name: String;
4
+ trackingKey: String;
10
5
  }, false>;
11
- export declare type Session = Static<typeof SessionSchema>;
6
+ export declare type Session = Static<typeof Session>;
12
7
  export declare const getCurrentSession: () => Promise<Session>;
13
8
  export declare const removeSession: (domain: string) => Promise<void>;
@@ -0,0 +1,12 @@
1
+ export declare type UserAttributes = {
2
+ isLoggedIn: boolean;
3
+ name?: string;
4
+ email?: string;
5
+ phone?: string;
6
+ trackingKey?: string;
7
+ extraData: [];
8
+ access: string[];
9
+ };
10
+ export declare type AnonymousAttributes = {
11
+ age: number;
12
+ };
@@ -0,0 +1,3 @@
1
+ export declare const setRootElement: (element: any) => void;
2
+ export declare const listen: <T extends keyof WindowEventMap>(type: T, listener: (this: Window, ev: WindowEventMap[T]) => void, exclusivity?: boolean) => void;
3
+ export declare const dispatch: <T extends Event>(event: T) => void;
@@ -0,0 +1,5 @@
1
+ declare const _default: {
2
+ add: (key: string, data: unknown) => void;
3
+ getAll: (key: string) => unknown[];
4
+ };
5
+ export default _default;
package/package.json CHANGED
@@ -1,9 +1,10 @@
1
1
  {
2
2
  "name": "@amedia/user",
3
- "version": "0.1.2",
3
+ "version": "0.2.0",
4
4
  "description": "Client lib for working with aID user",
5
- "main": "dist/index.js",
5
+ "repository": "https://github.com/amedia/amedia-user-js",
6
6
  "author": "Amedia Utvikling (ID og data)",
7
+ "main": "dist/index.js",
7
8
  "scripts": {
8
9
  "test": "jest",
9
10
  "build": "webpack --mode=production"
@@ -0,0 +1,37 @@
1
+ import { getCurrentSession, Session } from '../services/pluto';
2
+ import cache from '../cache';
3
+
4
+ const EXPIRES_10_SECONDS = 10000;
5
+
6
+ export const login = (requestedUrl: string) => {
7
+ // TODO Need to get environment smarts from incentive embed
8
+ const url = new URL('https://aid.no/logg_inn/');
9
+ url.searchParams.set('requestedUrl', requestedUrl || window.location.href);
10
+ window.location.href = url.href;
11
+ };
12
+
13
+ export const logout = () => {
14
+ // TODO Perform logout
15
+ };
16
+
17
+ let isFetchingSession = false;
18
+ const IS_LOGGED_IN_CACHE_KEY = 'is_logged_in';
19
+ export const getSession = async (): Promise<Session | null> => {
20
+ if (isFetchingSession) {
21
+ return null;
22
+ }
23
+ isFetchingSession = true;
24
+
25
+ // Try the cache first
26
+ const cacheResponse = await cache.get(IS_LOGGED_IN_CACHE_KEY, Session);
27
+ if (cacheResponse) {
28
+ isFetchingSession = false;
29
+ return cacheResponse;
30
+ }
31
+
32
+ // Actually perform a request against backend for the session
33
+ const session = await getCurrentSession();
34
+ cache.set(IS_LOGGED_IN_CACHE_KEY, session, Date.now() + EXPIRES_10_SECONDS);
35
+ isFetchingSession = false;
36
+ return session;
37
+ };
@@ -0,0 +1,51 @@
1
+ import {
2
+ AccessFeatures,
3
+ CheckAccessForPaper,
4
+ CheckAccessForPaperSchema,
5
+ checkForAccess,
6
+ } from '../services/jupiter';
7
+ import cache from '../cache';
8
+
9
+ const EXPIRES_OFFSET = 10000; // 10 seconds
10
+ const CHECK_FOR_ACCESS_CACHE_KEY = 'check_for_access_to_publication';
11
+
12
+ let isCheckingForAccess: boolean = false;
13
+ export const checkForAccessToPublication = async (
14
+ publicationDomain: string,
15
+ accessFeatures: AccessFeatures
16
+ ): Promise<CheckAccessForPaper | null> => {
17
+ if (isCheckingForAccess) {
18
+ return null;
19
+ }
20
+ isCheckingForAccess = true;
21
+
22
+ // Try the cache first
23
+ const cacheResponse = await cache.get(
24
+ CHECK_FOR_ACCESS_CACHE_KEY,
25
+ CheckAccessForPaperSchema
26
+ );
27
+ if (cacheResponse) {
28
+ isCheckingForAccess = false;
29
+ return cacheResponse;
30
+ }
31
+
32
+ // Actually perform a request against backend for the accessState
33
+ const accessState = await checkForAccess(publicationDomain, accessFeatures);
34
+ cache.set(
35
+ CHECK_FOR_ACCESS_CACHE_KEY,
36
+ accessState,
37
+ Date.now() + EXPIRES_OFFSET
38
+ );
39
+
40
+ isCheckingForAccess = false;
41
+
42
+ return accessState;
43
+ };
44
+
45
+ // TODO This is just mock implementation
46
+ export const activate = () =>
47
+ new Promise((resolve, reject) => {
48
+ setTimeout(() => {
49
+ resolve({ status: 'success' });
50
+ }, 1000);
51
+ });
@@ -1,7 +1,9 @@
1
+ import { CacheEntry, Engine } from '../types';
2
+
1
3
  // eslint-disable-next-line no-multi-assign
2
- const cache = ((window || global)['amedia-user-cache'] = {});
4
+ const cache = (window['amedia-user-cache'] = {});
3
5
 
4
- export const get = (key: string): Promise<unknown> => {
6
+ export const get = (key: string): Promise<CacheEntry> => {
5
7
  const data = cache[key];
6
8
  return Promise.resolve(data);
7
9
  };
@@ -20,4 +22,4 @@ export const remove = (key: string): Promise<void> => {
20
22
  return Promise.resolve();
21
23
  };
22
24
 
23
- export default { get, set, remove };
25
+ export default { get, set, remove } as Engine;
@@ -1,13 +1,13 @@
1
1
  import Dexie from 'dexie';
2
- import { Engine } from './types';
2
+ import { CacheEntry, Engine } from '../types';
3
3
 
4
- const db = new Dexie('amedia-user-cache');
5
- db.version(1).stores({
4
+ const indexeddb = new Dexie('amedia-user-cache');
5
+ indexeddb.version(1).stores({
6
6
  cache: 'key,data,expires',
7
7
  });
8
- const cache = db.table('cache');
8
+ const cache = indexeddb.table('cache');
9
9
 
10
- export const get = (key: string): Promise<unknown> => cache.get(key);
10
+ export const get = (key: string): Promise<CacheEntry> => cache.get(key);
11
11
  export const set = (
12
12
  key: string,
13
13
  data: unknown,
@@ -0,0 +1,82 @@
1
+ /**
2
+ * @jest-environment jsdom
3
+ */
4
+
5
+ import { Record, String } from 'runtypes';
6
+ import cache, { setCacheEngine } from '.';
7
+ import log from '../utils/log';
8
+ import resetAllMocks = jest.resetAllMocks;
9
+ import stringMatching = jasmine.stringMatching;
10
+
11
+ const TestDataSchema = Record({
12
+ test: String,
13
+ });
14
+
15
+ let mockEngine;
16
+ beforeEach(() => {
17
+ resetAllMocks();
18
+ // @ts-ignore
19
+ mockEngine = { get: jest.fn(), set: jest.fn(), remove: jest.fn() };
20
+ // @ts-ignore
21
+ setCacheEngine(mockEngine);
22
+ log.error = jest.fn();
23
+ });
24
+
25
+ describe('Cache', () => {
26
+ describe('get', () => {
27
+ it('should get from engine', () => {
28
+ mockEngine.get.mockReturnValueOnce(Promise.resolve(null));
29
+ expect(cache.get('foo', TestDataSchema)).resolves.toBeUndefined();
30
+ expect(mockEngine.get).toHaveBeenCalledWith('foo');
31
+ });
32
+
33
+ it('should validate valid data from engine', () => {
34
+ mockEngine.get.mockReturnValueOnce(
35
+ Promise.resolve({
36
+ key: 'foo',
37
+ data: {
38
+ test: 'cache',
39
+ },
40
+ expires: Date.now() + 1000,
41
+ })
42
+ );
43
+ expect(cache.get('foo', TestDataSchema)).resolves.toEqual({
44
+ test: 'cache',
45
+ });
46
+ });
47
+
48
+ it('should return undefined and delete record on invalid data', async () => {
49
+ mockEngine.get.mockReturnValueOnce(
50
+ Promise.resolve({
51
+ key: 'foo',
52
+ data: {
53
+ invalid: 'data',
54
+ },
55
+ expires: Date.now() + 1000,
56
+ })
57
+ );
58
+ await expect(cache.get('foo', TestDataSchema)).resolves.toBeUndefined();
59
+ expect(mockEngine.get).toHaveBeenCalledWith('foo');
60
+ expect(mockEngine.remove).toHaveBeenCalledWith('foo');
61
+ expect(log.error).toHaveBeenCalledWith('Failed validating data', {
62
+ data: { invalid: 'data' },
63
+ error: { test: 'Expected string, but was missing' },
64
+ });
65
+ });
66
+
67
+ it('deletes expired data', async () => {
68
+ mockEngine.get.mockReturnValueOnce(
69
+ Promise.resolve({
70
+ key: 'foo',
71
+ data: {
72
+ test: 'cache',
73
+ },
74
+ expires: Date.now() - 1000,
75
+ })
76
+ );
77
+ await expect(cache.get('foo', TestDataSchema)).resolves.toBeUndefined();
78
+ expect(mockEngine.get).toHaveBeenCalledWith('foo');
79
+ expect(mockEngine.remove).toHaveBeenCalledWith('foo');
80
+ });
81
+ });
82
+ });
@@ -1,6 +1,7 @@
1
- import { Record, Static } from 'runtypes';
2
- import globalCache from '../lib/cache/global';
3
- import { Engine } from '../lib/cache/types';
1
+ import { Record, Static, ValidationError } from 'runtypes';
2
+ import globalCache from './engines/global';
3
+ import { Engine } from './types';
4
+ import log from '../utils/log';
4
5
 
5
6
  let cacheEngine: Engine;
6
7
 
@@ -10,27 +11,38 @@ export const setCacheEngine = (engine: Engine) => {
10
11
 
11
12
  const getCacheEngine = (): Engine => cacheEngine || globalCache;
12
13
 
14
+ const set = (key: string, value: unknown, expires: number) =>
15
+ getCacheEngine().set(key, value, expires);
16
+
17
+ const remove = (key: string): Promise<void> => getCacheEngine().remove(key);
18
+
13
19
  const get = async <T extends Record<any, any>>(
14
20
  key: string,
15
21
  validator: T
16
22
  ): Promise<Static<T> | void> => {
17
- const data = await getCacheEngine().get(key);
18
- if (!data) {
23
+ const cacheEntry = await getCacheEngine().get(key);
24
+ if (!cacheEntry) {
25
+ return Promise.resolve();
26
+ }
27
+ if (Date.now() > cacheEntry.expires) {
28
+ remove(key);
19
29
  return Promise.resolve();
20
30
  }
21
31
  try {
22
- const typedData = validator.check(data);
32
+ const typedData = validator.check(cacheEntry.data);
23
33
  return typedData as T;
24
34
  } catch (error) {
25
- console.error('Failed validating data', { data, error });
26
- getCacheEngine().remove(key);
35
+ if (error instanceof ValidationError) {
36
+ log.error('Failed validating data', {
37
+ data: cacheEntry.data,
38
+ error: error.details,
39
+ });
40
+ } else {
41
+ log.error('Unknown error', error);
42
+ }
43
+ remove(key);
27
44
  return Promise.resolve();
28
45
  }
29
46
  };
30
47
 
31
- const set = (key: string, value: unknown, expires: number) =>
32
- getCacheEngine().set(key, value, expires);
33
-
34
- const remove = (key: string): Promise<void> => getCacheEngine().remove(key);
35
-
36
48
  export default { get, set, remove };
@@ -1,5 +1,11 @@
1
+ export type CacheEntry = {
2
+ key: string;
3
+ data: unknown;
4
+ expires: number;
5
+ };
6
+
1
7
  export type Engine = {
2
- get: (key: string) => Promise<unknown>;
8
+ get: (key: string) => Promise<CacheEntry | null>;
3
9
  set: (key: string, data: unknown, expires: number) => Promise<void>;
4
10
  remove: (key: string) => Promise<void>;
5
11
  };
@@ -0,0 +1,29 @@
1
+ import { dispatch, listenWithExclusivity } from '../utils/customEventWrapper';
2
+ import { activate } from '../actions/authorization';
3
+
4
+ export enum ActivationEvents {
5
+ REQUEST_ACTIVATION = 'amedia-user.activation.request-activation',
6
+ ON_ACTIVATION_COMPLETE = 'amedia-user.activation.on-activation-complete',
7
+ }
8
+
9
+ declare global {
10
+ interface WindowEventMap {
11
+ [ActivationEvents.REQUEST_ACTIVATION]: CustomEvent;
12
+ [ActivationEvents.ON_ACTIVATION_COMPLETE]: CustomEvent<{
13
+ status: 'success' | 'error';
14
+ }>;
15
+ }
16
+ }
17
+
18
+ export const listenForActivationRequests = () => {
19
+ listenWithExclusivity(ActivationEvents.REQUEST_ACTIVATION, () => {
20
+ activate().then((result) => {
21
+ dispatch(
22
+ new CustomEvent(ActivationEvents.ON_ACTIVATION_COMPLETE, {
23
+ detail: result,
24
+ })
25
+ );
26
+ });
27
+ });
28
+ };
29
+ listenForActivationRequests();
@@ -0,0 +1,29 @@
1
+ import { listenWithExclusivity } from '../utils/customEventWrapper';
2
+ import { login, logout } from '../actions/authentication';
3
+
4
+ export enum AuthenticationEvents {
5
+ REQUEST_LOGIN = 'amedia-user.authentication.request-login',
6
+ REQUEST_LOGOUT = 'amedia-user.authentication.request-logout',
7
+ }
8
+
9
+ declare global {
10
+ interface WindowEventMap {
11
+ [AuthenticationEvents.REQUEST_LOGIN]: CustomEvent<{
12
+ requestedUrl?: string;
13
+ }>;
14
+ [AuthenticationEvents.REQUEST_LOGOUT]: CustomEvent<{
15
+ requestedUrl?: string;
16
+ }>;
17
+ }
18
+ }
19
+
20
+ export const listenForAuthenticationRequests = () => {
21
+ listenWithExclusivity(AuthenticationEvents.REQUEST_LOGIN, (evt) => {
22
+ login(evt.detail.requestedUrl || window.location.href);
23
+ });
24
+
25
+ listenWithExclusivity(AuthenticationEvents.REQUEST_LOGOUT, () => {
26
+ logout();
27
+ });
28
+ };
29
+ listenForAuthenticationRequests();
@@ -1,6 +1,6 @@
1
- import { fetchDataBasedOnAttributes } from './dataOrganizer';
2
- import { dispatch, listen } from './eventHandler';
3
- import { UserAttributes } from './types';
1
+ import { fetchDataBasedOnAttributes } from '../lib/dataOrganizer';
2
+ import { dispatch, listenWithExclusivity } from '../utils/customEventWrapper';
3
+ import { UserAttributes } from '../types';
4
4
 
5
5
  export enum AmediaUserEvents {
6
6
  REQUEST_USER_ATTRIBUTES = 'amedia-user.request-user-attributes',
@@ -17,15 +17,14 @@ declare global {
17
17
  }
18
18
 
19
19
  export const listenForUserAttributeRequests = () => {
20
- listen(AmediaUserEvents.REQUEST_USER_ATTRIBUTES, (evt) => {
21
- // Prevent other instances of this package from further processing
22
- evt.stopImmediatePropagation();
23
-
24
- dispatch(
25
- new CustomEvent(AmediaUserEvents.ON_USER_ATTRIBUTES_UPDATED, {
26
- detail: fetchDataBasedOnAttributes(evt.detail),
27
- })
28
- );
20
+ listenWithExclusivity(AmediaUserEvents.REQUEST_USER_ATTRIBUTES, (evt) => {
21
+ fetchDataBasedOnAttributes(evt.detail, (attributes) => {
22
+ dispatch(
23
+ new CustomEvent(AmediaUserEvents.ON_USER_ATTRIBUTES_UPDATED, {
24
+ detail: attributes,
25
+ })
26
+ );
27
+ });
29
28
  });
30
29
  };
31
30
 
package/src/index.spec.ts CHANGED
@@ -4,8 +4,8 @@
4
4
 
5
5
  import { subscribeToUserUpdates } from './index';
6
6
  import * as dataOrganizer from './lib/dataOrganizer';
7
- import { setRootElement } from './lib/eventHandler';
8
- import { listenForUserAttributeRequests } from './lib/userAttributes';
7
+ import { setRootElement } from './utils/customEventWrapper';
8
+ import { listenForUserAttributeRequests } from './eventHandlers/userAttributes';
9
9
 
10
10
  beforeEach(() => {
11
11
  jest.resetAllMocks();
@@ -21,10 +21,14 @@ beforeEach(() => {
21
21
 
22
22
  describe('Public endpoint', () => {
23
23
  it('should alert about user data', () => {
24
- jest.spyOn(dataOrganizer, 'fetchDataBasedOnAttributes').mockReturnValue({
25
- name: 'Donald Duck',
26
- isLoggedIn: true,
27
- });
24
+ jest
25
+ .spyOn(dataOrganizer, 'fetchDataBasedOnAttributes')
26
+ .mockImplementation((_, callback: Function) => {
27
+ callback({
28
+ name: 'Donald Duck',
29
+ isLoggedIn: true,
30
+ });
31
+ });
28
32
 
29
33
  const onUserUpdate = jest.fn();
30
34
  subscribeToUserUpdates(['name'], onUserUpdate);
@@ -38,13 +42,17 @@ describe('Public endpoint', () => {
38
42
  it('should alert when others also ask about data', () => {
39
43
  jest
40
44
  .spyOn(dataOrganizer, 'fetchDataBasedOnAttributes')
41
- .mockReturnValueOnce({
42
- name: undefined,
43
- isLoggedIn: false,
45
+ .mockImplementationOnce((_, callback: Function) => {
46
+ callback({
47
+ name: undefined,
48
+ isLoggedIn: false,
49
+ });
44
50
  })
45
- .mockReturnValueOnce({
46
- name: 'Donald Duck',
47
- isLoggedIn: true,
51
+ .mockImplementationOnce((_, callback: Function) => {
52
+ callback({
53
+ name: 'Donald Duck',
54
+ isLoggedIn: true,
55
+ });
48
56
  });
49
57
 
50
58
  const firstOnUserUpdate = jest.fn();
@@ -73,10 +81,12 @@ describe('Public endpoint', () => {
73
81
  it('should not return more data that requested (except for login status)', () => {
74
82
  jest
75
83
  .spyOn(dataOrganizer, 'fetchDataBasedOnAttributes')
76
- .mockReturnValueOnce({
77
- name: 'Donald Duck',
78
- email: 'donald.duck@andeby.no',
79
- isLoggedIn: true,
84
+ .mockImplementationOnce((_, callback: Function) => {
85
+ callback({
86
+ name: 'Donald Duck',
87
+ email: 'donald.duck@andeby.no',
88
+ isLoggedIn: true,
89
+ });
80
90
  });
81
91
 
82
92
  const onUserUpdate = jest.fn();
@@ -91,10 +101,13 @@ describe('Public endpoint', () => {
91
101
  it('should support returning multiple requested attributes', () => {
92
102
  jest
93
103
  .spyOn(dataOrganizer, 'fetchDataBasedOnAttributes')
94
- .mockReturnValueOnce({
95
- name: 'Donald Duck',
96
- email: 'donald.duck@andeby.no',
97
- isLoggedIn: true,
104
+
105
+ .mockImplementationOnce((_, callback: Function) => {
106
+ callback({
107
+ name: 'Donald Duck',
108
+ email: 'donald.duck@andeby.no',
109
+ isLoggedIn: true,
110
+ });
98
111
  });
99
112
 
100
113
  const onUserUpdate = jest.fn();
@@ -110,10 +123,12 @@ describe('Public endpoint', () => {
110
123
  it('should support no attributes, returning only logged in state', () => {
111
124
  jest
112
125
  .spyOn(dataOrganizer, 'fetchDataBasedOnAttributes')
113
- .mockReturnValueOnce({
114
- name: 'Donald Duck',
115
- email: 'donald.duck@andeby.no',
116
- isLoggedIn: true,
126
+ .mockImplementationOnce((_, callback: Function) => {
127
+ callback({
128
+ name: 'Donald Duck',
129
+ email: 'donald.duck@andeby.no',
130
+ isLoggedIn: true,
131
+ });
117
132
  });
118
133
 
119
134
  const onUserUpdate = jest.fn();
@@ -124,12 +139,16 @@ describe('Public endpoint', () => {
124
139
  });
125
140
  });
126
141
 
127
- it('should support requesting difference amount of attributes', () => {
128
- jest.spyOn(dataOrganizer, 'fetchDataBasedOnAttributes').mockReturnValue({
129
- name: 'Donald Duck',
130
- email: 'donald.duck@andeby.no',
131
- isLoggedIn: true,
132
- });
142
+ it('should support requesting different attributes', () => {
143
+ jest
144
+ .spyOn(dataOrganizer, 'fetchDataBasedOnAttributes')
145
+ .mockImplementation((_, callback: Function) => {
146
+ callback({
147
+ name: 'Donald Duck',
148
+ email: 'donald.duck@andeby.no',
149
+ isLoggedIn: true,
150
+ });
151
+ });
133
152
 
134
153
  const firstOnUserUpdate = jest.fn();
135
154
  subscribeToUserUpdates([], firstOnUserUpdate);
package/src/index.ts CHANGED
@@ -1,7 +1,8 @@
1
- import { AuthenticationEvents } from './lib/authentication';
2
- import { AmediaUserEvents } from './lib/userAttributes';
3
- import { dispatch, listen } from './lib/eventHandler';
4
- import { UserAttributes } from './lib/types';
1
+ import { AuthenticationEvents } from './eventHandlers/authentication';
2
+ import { AmediaUserEvents } from './eventHandlers/userAttributes';
3
+ import { ActivationEvents } from './eventHandlers/activation';
4
+ import { dispatch, listenForAllEvents } from './utils/customEventWrapper';
5
+ import { UserAttributes } from './types';
5
6
 
6
7
  /**
7
8
  * Enables you to subscribe to the user attributes you care about and
@@ -22,7 +23,7 @@ export const subscribeToUserUpdates = <T extends Array<keyof UserAttributes>>(
22
23
  attributes: Pick<UserAttributes, T[number] | 'isLoggedIn'>
23
24
  ) => void
24
25
  ) => {
25
- listen(AmediaUserEvents.ON_USER_ATTRIBUTES_UPDATED, (evt) => {
26
+ listenForAllEvents(AmediaUserEvents.ON_USER_ATTRIBUTES_UPDATED, (evt) => {
26
27
  const userAttributes = evt.detail;
27
28
  // @ts-ignore
28
29
  const responseAttributes: Pick<UserAttributes, T[number] | 'isLoggedIn'> = {
@@ -56,3 +57,11 @@ export const requestLogin = (requestedUrl?: string) =>
56
57
  detail: { requestedUrl },
57
58
  })
58
59
  );
60
+
61
+ export const activate = (): Promise<unknown> =>
62
+ new Promise((resolve, reject) => {
63
+ listenForAllEvents(ActivationEvents.ON_ACTIVATION_COMPLETE, (result) => {
64
+ resolve(result);
65
+ });
66
+ dispatch(new CustomEvent(ActivationEvents.REQUEST_ACTIVATION));
67
+ });
@@ -1,18 +1,37 @@
1
- import { UserAttributes } from './types';
1
+ import { UserAttributes } from '../types';
2
+ import { getSession } from '../actions/authentication';
2
3
 
3
- /**
4
- * Jeg tror ikke vi burde gjøre det slik som dette.
5
- * Denne funksjonen var hentet ut fra userAttribute kun for å
6
- * kunne mocke implementasjonen så jeg kunne teste event-callback mekanismen.
7
- *
8
- * En implementasjon som dette vil gjøre det vanskelig svare etterhvert som vi får data.
9
- */
4
+ // TODO We may want actions to tell us what they can deliver and not have this "organizer" (wohoo-bad-name) tell the actions..
5
+ const dataServiceMap: {
6
+ // TODO Must get proper type here. Perhaps all actions should return UserAttribute-compatible response?
7
+ [key in keyof UserAttributes]?: () => Promise<any>;
8
+ } = {
9
+ name: getSession,
10
+ trackingKey: getSession,
11
+ };
10
12
 
11
13
  export const fetchDataBasedOnAttributes = (
12
- attributes: (keyof UserAttributes)[]
13
- ): UserAttributes =>
14
- // TODO: Implement fetching based on attributes
15
- ({
16
- isLoggedIn: true,
17
- name: 'Donald Duck',
14
+ attributes: Array<keyof UserAttributes>,
15
+ onDataUpdated: (attributes: UserAttributes) => void
16
+ ) => {
17
+ const requiredServices: Array<() => Promise<UserAttributes>> = [];
18
+ attributes.forEach((attribute) => {
19
+ const service = dataServiceMap[attribute];
20
+ if (!service) {
21
+ console.warn('Unknown attribute was requested');
22
+ return;
23
+ }
24
+ if (!requiredServices.includes(service)) {
25
+ requiredServices.push(service);
26
+ }
18
27
  });
28
+
29
+ while (requiredServices.length > 0) {
30
+ const service = requiredServices.pop();
31
+ if (service) {
32
+ service().then((a) => {
33
+ onDataUpdated(a);
34
+ });
35
+ }
36
+ }
37
+ };
@@ -20,8 +20,9 @@ describe('Pluto service', () => {
20
20
  };
21
21
  fetch.mockResponseOnce(JSON.stringify(data));
22
22
 
23
- getCurrentSession().then((res) => {
24
- expect(res).toEqual(data);
23
+ expect(getCurrentSession()).resolves.toEqual({
24
+ name: 'Earl Hickey',
25
+ trackingKey: 'some tracking key',
25
26
  });
26
27
  expect(fetch).toHaveBeenCalledTimes(1);
27
28
  });
@@ -1,17 +1,21 @@
1
- import { Optional, Record, Static, String } from 'runtypes';
1
+ import { Record, Static, String } from 'runtypes';
2
2
 
3
- export const SessionSchema = Record({
4
- created_at: String,
5
- updated_at: String,
6
- user_uuid: String,
3
+ const SessionSchema = Record({
7
4
  user_name: String,
8
5
  tracking_key: String,
9
- user_agent: Optional(String),
6
+ });
7
+
8
+ export const Session = Record({
9
+ name: String,
10
+ trackingKey: String,
11
+ });
12
+ // eslint-disable-next-line @typescript-eslint/no-redeclare
13
+ export type Session = Static<typeof Session>;
10
14
 
11
- // @deprecated Use tracking_key
12
- user_key: Optional(String),
15
+ const mapSession = (session: Static<typeof SessionSchema>): Session => ({
16
+ name: session.user_name,
17
+ trackingKey: session.tracking_key,
13
18
  });
14
- export type Session = Static<typeof SessionSchema>;
15
19
 
16
20
  export const getCurrentSession = async (): Promise<Session> =>
17
21
  fetch(`/api/pluto/v1/sessions/current`)
@@ -26,7 +30,7 @@ export const getCurrentSession = async (): Promise<Session> =>
26
30
  })
27
31
  .then((json) => {
28
32
  try {
29
- return SessionSchema.check(json);
33
+ return mapSession(SessionSchema.check(json));
30
34
  } catch (error) {
31
35
  console.error('Invalid schema', error);
32
36
  throw error;
package/src/types.ts ADDED
@@ -0,0 +1,13 @@
1
+ export type UserAttributes = {
2
+ isLoggedIn: boolean;
3
+ name?: string;
4
+ email?: string;
5
+ phone?: string;
6
+ trackingKey?: string;
7
+ extraData: [];
8
+ access: string[];
9
+ };
10
+
11
+ export type AnonymousAttributes = {
12
+ age: number;
13
+ };
@@ -0,0 +1,42 @@
1
+ let rootElement = window || global;
2
+
3
+ export const setRootElement = (element) => {
4
+ rootElement = element;
5
+ };
6
+
7
+ /**
8
+ * This listener MUST be used by all listeners in ../eventHandlers
9
+ * We want to ensure that only _one_ instance of this package actually
10
+ * orchestrates data and performs requests against backends.
11
+ * @param type
12
+ * @param listener
13
+ */
14
+ export const listenWithExclusivity = <T extends keyof WindowEventMap>(
15
+ type: T,
16
+ listener: (this: Window, ev: WindowEventMap[T]) => void
17
+ ) => {
18
+ rootElement.addEventListener(type, (evt) => {
19
+ // Since this lib might me loaded multiple times, we need to prevent all other processing of this event.
20
+ evt.stopImmediatePropagation();
21
+ listener.apply(window, [evt]);
22
+ });
23
+ };
24
+
25
+ /**
26
+ * Use this for response listeners. (../index.ts) where we want
27
+ * all updates with data - no matter who sent the actual request
28
+ * @param type
29
+ * @param listener
30
+ */
31
+ export const listenForAllEvents = <T extends keyof WindowEventMap>(
32
+ type: T,
33
+ listener: (this: Window, ev: WindowEventMap[T]) => void
34
+ ) => {
35
+ rootElement.addEventListener(type, (evt) => {
36
+ listener.apply(window, [evt]);
37
+ });
38
+ };
39
+
40
+ export const dispatch = <T extends Event>(event: T) => {
41
+ rootElement.dispatchEvent(event);
42
+ };
@@ -0,0 +1,7 @@
1
+ // TODO: Actually support logging in some form..
2
+ export default {
3
+ debug: console.debug,
4
+ info: console.log,
5
+ warning: console.warn,
6
+ error: console.error,
7
+ };
@@ -1,94 +0,0 @@
1
- import cache from '../services/cache';
2
- import { getCurrentSession, Session, SessionSchema } from '../services/pluto';
3
- import { dispatch, listen } from './eventHandler';
4
-
5
- const EXPIRES_OFFSET = 10000; // 10 seconds
6
-
7
- export enum AuthenticationEvents {
8
- REQUEST_LOGIN = 'amedia_user.authentication.request_login',
9
- REQUEST_LOGOUT = 'amedia_user.authentication.request_logout',
10
- REQUEST_AUTH_STATE = 'amedia_user.authentication.request_auth_state',
11
- ON_AUTH_STATE_UPDATED = 'amedia_user.authentication.on_auth_state_updated',
12
- }
13
-
14
- declare global {
15
- interface WindowEventMap {
16
- [AuthenticationEvents.REQUEST_LOGIN]: CustomEvent<{
17
- requestedUrl?: string;
18
- }>;
19
- [AuthenticationEvents.REQUEST_LOGOUT]: CustomEvent<{
20
- requestedUrl?: string;
21
- }>;
22
- [AuthenticationEvents.REQUEST_AUTH_STATE]: CustomEvent<Session>;
23
- [AuthenticationEvents.ON_AUTH_STATE_UPDATED]: CustomEvent<Session>;
24
- }
25
- }
26
-
27
- const login = (requestedUrl: string) => {
28
- // TODO Need to get environment smarts from incentive embed
29
- const url = new URL('https://aid.no/logg_inn/');
30
- url.searchParams.set('requestedUrl', requestedUrl || window.location.href);
31
- window.location.href = url.href;
32
- };
33
-
34
- const logout = () => {
35
- // TODO Perform logout
36
- };
37
-
38
- let isFetchingSession = false;
39
- const IS_LOGGED_IN_CACHE_KEY = 'is_logged_in';
40
- const getSession = async (): Promise<Session | null> => {
41
- if (isFetchingSession) {
42
- return null;
43
- }
44
- isFetchingSession = true;
45
-
46
- // Try the cache first
47
- const cacheResponse = await cache.get(IS_LOGGED_IN_CACHE_KEY, SessionSchema);
48
- if (cacheResponse) {
49
- isFetchingSession = false;
50
- return cacheResponse;
51
- }
52
-
53
- // Actually perform a request against backend for the session
54
- const session = await getCurrentSession();
55
- cache.set(IS_LOGGED_IN_CACHE_KEY, session, Date.now() + EXPIRES_OFFSET);
56
- isFetchingSession = false;
57
- return session;
58
- };
59
-
60
- export const listenForAuthenticationRequests = () => {
61
- listen(AuthenticationEvents.REQUEST_LOGIN, (evt) => {
62
- if (!window) {
63
- throw new Error('Cannot perform login in node-context yet!');
64
- }
65
- login(evt.detail.requestedUrl || window.location.href);
66
- });
67
-
68
- listen(AuthenticationEvents.REQUEST_LOGOUT, () => {
69
- if (!window) {
70
- throw new Error('Cannot perform login in node-context yet!');
71
- }
72
- logout();
73
- });
74
-
75
- listen(AuthenticationEvents.REQUEST_AUTH_STATE, (evt) => {
76
- // Since this lib might me loaded multiple times, we need to prevent all other processing of this event.
77
- evt.stopImmediatePropagation();
78
-
79
- getSession().then((session) => {
80
- // Supports not getting a response. We're probably working on it already and will emit
81
- // events on window / global when complete.
82
- if (session === null) {
83
- return;
84
- }
85
- dispatch(
86
- new CustomEvent(AuthenticationEvents.ON_AUTH_STATE_UPDATED, {
87
- detail: session,
88
- })
89
- );
90
- });
91
- });
92
- };
93
-
94
- listenForAuthenticationRequests();
@@ -1,86 +0,0 @@
1
- import {
2
- AccessFeatures,
3
- CheckAccessForPaper,
4
- CheckAccessForPaperSchema,
5
- checkForAccess,
6
- } from '../services/jupiter';
7
- import cache from '../services/cache';
8
- import { dispatch, listen } from './eventHandler';
9
-
10
- const EXPIRES_OFFSET = 10000; // 10 seconds
11
- const CHECK_FOR_ACCESS_CACHE_KEY = 'check_for_access_to_publication';
12
- let isCheckingForAccess: boolean = false;
13
-
14
- export enum AuthorizationEvents {
15
- REQUEST_PUBLICATION_ACCESS_STATE_CHECK = 'amedia_user.authorization.request_publication_access_state_check',
16
- ON_PUBLICATION_ACCESS_STATE_UPDATED = 'amedia_user.authorization.on_publication_access_state_updated',
17
- }
18
-
19
- declare global {
20
- interface WindowEventMap {
21
- [AuthorizationEvents.REQUEST_PUBLICATION_ACCESS_STATE_CHECK]: CustomEvent<{
22
- publicationDomain: string;
23
- accessFeatures: AccessFeatures;
24
- }>;
25
- [AuthorizationEvents.ON_PUBLICATION_ACCESS_STATE_UPDATED]: CustomEvent<CheckAccessForPaper>;
26
- }
27
- }
28
-
29
- const checkForAccessToPublication = async (
30
- publicationDomain: string,
31
- accessFeatures: AccessFeatures
32
- ): Promise<CheckAccessForPaper | null> => {
33
- if (isCheckingForAccess) {
34
- return null;
35
- }
36
- isCheckingForAccess = true;
37
-
38
- // Try the cache first
39
- const cacheResponse = await cache.get(
40
- CHECK_FOR_ACCESS_CACHE_KEY,
41
- CheckAccessForPaperSchema
42
- );
43
- if (cacheResponse) {
44
- isCheckingForAccess = false;
45
- return cacheResponse;
46
- }
47
-
48
- // Actually perform a request against backend for the accessState
49
- const accessState = await checkForAccess(publicationDomain, accessFeatures);
50
- cache.set(
51
- CHECK_FOR_ACCESS_CACHE_KEY,
52
- accessState,
53
- Date.now() + EXPIRES_OFFSET
54
- );
55
-
56
- isCheckingForAccess = false;
57
-
58
- return accessState;
59
- };
60
-
61
- export const listenForAuthorizationRequests = () => {
62
- listen(AuthorizationEvents.REQUEST_PUBLICATION_ACCESS_STATE_CHECK, (evt) => {
63
- // Since this lib might me loaded multiple times, we need to prevent all other processing of this event.
64
- evt.stopImmediatePropagation();
65
- checkForAccessToPublication(
66
- evt.detail.publicationDomain,
67
- evt.detail.accessFeatures
68
- ).then((accessState) => {
69
- // Supports not getting a response. We're probably working on it already and will emit
70
- // events on window / global when complete.
71
- if (!accessState) {
72
- return;
73
- }
74
- dispatch(
75
- new CustomEvent(
76
- AuthorizationEvents.ON_PUBLICATION_ACCESS_STATE_UPDATED,
77
- {
78
- detail: accessState,
79
- }
80
- )
81
- );
82
- });
83
- });
84
- };
85
-
86
- listenForAuthorizationRequests();
@@ -1,16 +0,0 @@
1
- let rootElement = window || global;
2
-
3
- export const setRootElement = (element) => {
4
- rootElement = element;
5
- };
6
-
7
- export const listen = <T extends keyof WindowEventMap>(
8
- type: T,
9
- listener: (this: Window, ev: WindowEventMap[T]) => void
10
- ) => {
11
- rootElement.addEventListener(type, listener);
12
- };
13
-
14
- export const dispatch = <T extends Event>(event: T) => {
15
- rootElement.dispatchEvent(event);
16
- };
package/src/lib/types.ts DELETED
@@ -1,7 +0,0 @@
1
- export type UserAttributes = {
2
- isLoggedIn?: boolean;
3
- name?: string;
4
- email?: string;
5
- phone?: string;
6
- trackingKey?: string;
7
- };
File without changes