@klauswuestefeld/jux-web 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/main.js ADDED
@@ -0,0 +1,1277 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var msal = require('@azure/msal-browser');
6
+
7
+ function _interopNamespace(e) {
8
+ if (e && e.__esModule) return e;
9
+ var n = Object.create(null);
10
+ if (e) {
11
+ Object.keys(e).forEach(function (k) {
12
+ if (k !== 'default') {
13
+ var d = Object.getOwnPropertyDescriptor(e, k);
14
+ Object.defineProperty(n, k, d.get ? d : {
15
+ enumerable: true,
16
+ get: function () { return e[k]; }
17
+ });
18
+ }
19
+ });
20
+ }
21
+ n["default"] = e;
22
+ return Object.freeze(n);
23
+ }
24
+
25
+ var msal__namespace = /*#__PURE__*/_interopNamespace(msal);
26
+
27
+ var getBrowserLanguage = function () {
28
+ var result = (navigator.languages && navigator.languages.length)
29
+ ? navigator.languages[0]
30
+ : navigator.userLanguage || navigator.language || navigator.browserLanguage || 'en';
31
+ return result.substring(0, 2);
32
+ };
33
+ var OVERRIDE_KEY = 'jux.language.override';
34
+ var translations = {};
35
+ var chosenLanguage = localStorage.getItem(OVERRIDE_KEY) || getBrowserLanguage();
36
+ var reloadWithLanguageOverride = function (lang) {
37
+ localStorage.setItem(OVERRIDE_KEY, lang);
38
+ location.reload();
39
+ };
40
+ // @ts-ignore
41
+ var getTranslation = function (k) { return translations[k] || k; };
42
+ var initLanguage = function (translations_, defaultLanguage) {
43
+ if (defaultLanguage === void 0) { defaultLanguage = 'en'; }
44
+ translations = translations_[chosenLanguage] || translations_[defaultLanguage];
45
+ document.title = getTranslation('title');
46
+ document.documentElement.lang = translations_[chosenLanguage] ? chosenLanguage : defaultLanguage;
47
+ };
48
+
49
+ var THRESHOLD_WIDTH = 640;
50
+
51
+ var icons = {
52
+ email: '<svg version="1.0" xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 64.000000 48.000000" preserveAspectRatio="xMidYMid meet"> <g transform="translate(0.000000,48.000000) scale(0.100000,-0.100000)" fill="#000000" stroke="none"> <path d="M44 468 c-38 -18 -44 -51 -44 -228 0 -180 6 -210 47 -229 33 -15 513 -15 546 0 41 19 47 49 47 229 0 180 -6 210 -47 229 -31 14 -519 14 -549 -1z m516 -33 c0 -7 -232 -205 -240 -205 -8 0 -240 198 -240 205 0 3 108 5 240 5 132 0 240 -2 240 -5z m-406 -118 l59 -53 -87 -97 -86 -97 0 170 0 171 28 -20 c15 -11 54 -44 86 -74z m446 -77 l0 -170 -85 95 c-47 53 -85 98 -85 99 0 5 162 146 167 146 1 0 3 -77 3 -170z m-319 -31 l39 -31 40 32 39 31 33 -37 c18 -21 57 -65 87 -99 l53 -60 -126 -3 c-69 -1 -183 -1 -252 0 l-126 3 84 97 c46 53 85 97 87 97 2 1 21 -13 42 -30z"/> </g> </svg>',
53
+ google: '<svg viewBox="0 0 24 24" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg"><g transform="matrix(1, 0, 0, 1, 27.009001, -39.238998)"><path fill="#4285F4" d="M -3.264 51.509 C -3.264 50.719 -3.334 49.969 -3.454 49.239 L -14.754 49.239 L -14.754 53.749 L -8.284 53.749 C -8.574 55.229 -9.424 56.479 -10.684 57.329 L -10.684 60.329 L -6.824 60.329 C -4.564 58.239 -3.264 55.159 -3.264 51.509 Z"/><path fill="#34A853" d="M -14.754 63.239 C -11.514 63.239 -8.804 62.159 -6.824 60.329 L -10.684 57.329 C -11.764 58.049 -13.134 58.489 -14.754 58.489 C -17.884 58.489 -20.534 56.379 -21.484 53.529 L -25.464 53.529 L -25.464 56.619 C -23.494 60.539 -19.444 63.239 -14.754 63.239 Z"/><path fill="#FBBC05" d="M -21.484 53.529 C -21.734 52.809 -21.864 52.039 -21.864 51.239 C -21.864 50.439 -21.724 49.669 -21.484 48.949 L -21.484 45.859 L -25.464 45.859 C -26.284 47.479 -26.754 49.299 -26.754 51.239 C -26.754 53.179 -26.284 54.999 -25.464 56.619 L -21.484 53.529 Z"/><path fill="#EA4335" d="M -14.754 43.989 C -12.984 43.989 -11.404 44.599 -10.154 45.789 L -6.734 42.369 C -8.804 40.429 -11.514 39.239 -14.754 39.239 C -19.444 39.239 -23.494 41.939 -25.464 45.859 L -21.484 48.949 C -20.534 46.099 -17.884 43.989 -14.754 43.989 Z"/></g></svg>',
54
+ linkedin: '<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" width="100%" height="100%" viewBox="1.786 1.783 76.226652 76.248" version="1.1" id="svg72" sodipodi:docname="linkedin.svg" inkscape:version="0.92.4 (5da689c313, 2019-01-14)"> <metadata id="metadata78"> <rdf:RDF> <cc:Work rdf:about=""> <dc:format>image/svg+xml</dc:format> <dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /> <dc:title></dc:title> </cc:Work> </rdf:RDF> </metadata> <defs id="defs76" /> <sodipodi:namedview pagecolor="#ffffff" bordercolor="#666666" borderopacity="1" objecttolerance="10" gridtolerance="10" guidetolerance="10" inkscape:pageopacity="0" inkscape:pageshadow="2" inkscape:window-width="1916" inkscape:window-height="1036" id="namedview74" showgrid="false" inkscape:zoom="0.79365665" inkscape:cx="428.70379" inkscape:cy="325.16058" inkscape:window-x="0" inkscape:window-y="20" inkscape:window-maximized="0" inkscape:current-layer="svg72" inkscape:pagecheckerboard="false" /> <path d="m 2.10821,7.2952417 c 0,-3.015 2.508,-5.462 5.6,-5.462 h 64.568 c 3.093,0 5.6,2.447 5.6,5.462 V 72.620242 c 0,3.016 -2.507,5.461 -5.6,5.461 h -64.568 c -3.092,0 -5.6,-2.445 -5.6,-5.46 V 7.2942417 Z" id="path64" inkscape:connector-curvature="0" style="fill:#0b78b7;fill-opacity:1" /> <path d="m 25.07621,65.660242 v -34.43 h -11.444 v 34.43 h 11.445 z m -5.72,-39.13 c 3.99,0 6.474,-2.644 6.474,-5.948 -0.075,-3.379 -2.484,-5.949 -6.398,-5.949 -3.917,0 -6.475,2.57 -6.475,5.949 0,3.304 2.483,5.948 6.324,5.948 h 0.074 z m 12.054,39.13 h 11.443 v -19.225 c 0,-1.028 0.075,-2.058 0.377,-2.792 0.827,-2.057 2.71,-4.186 5.872,-4.186 4.14,0 5.797,3.157 5.797,7.786 v 18.417 h 11.443 v -19.741 c 0,-10.575 -5.645,-15.496 -13.174,-15.496 -6.173,0 -8.884,3.45 -10.39,5.8 h 0.076 v -4.992 h -11.443 c 0.149,3.23 -0.001,34.43 -0.001,34.43 z" id="path70" inkscape:connector-curvature="0" style="fill:#ffffff" /> </svg>',
55
+ microsoft: '<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 21 21"><title>MS-SymbolLockup</title><rect x="1" y="1" width="9" height="9" fill="#f25022"/><rect x="1" y="11" width="9" height="9" fill="#00a4ef"/><rect x="11" y="1" width="9" height="9" fill="#7fba00"/><rect x="11" y="11" width="9" height="9" fill="#ffb900"/></svg>',
56
+ };
57
+ var applyComponentStyle = function (component) {
58
+ component.style.alignItems = 'center';
59
+ component.style.background = '#fff';
60
+ component.style.border = 'thin solid #888';
61
+ component.style.borderRadius = '5px';
62
+ component.style.boxShadow = '1px 1px 1px grey';
63
+ component.style.boxSizing = 'content - box';
64
+ component.style.color = '#444';
65
+ component.style.display = 'grid';
66
+ component.style.gridTemplateColumns = '12% 1fr 4fr';
67
+ component.style.height = '42px';
68
+ component.style.marginTop = '16px';
69
+ component.style.padding = '0 12px';
70
+ component.style.whiteSpace = 'nowrap';
71
+ component.style.width = '276px';
72
+ component.style.boxSizing = 'content-box';
73
+ };
74
+ var applyLabelStyle = function (label) {
75
+ label.style.display = 'inline-block';
76
+ label.style.fontSize = '14px';
77
+ label.style.fontWeight = '500';
78
+ label.style.gridColumnStart = '3';
79
+ label.style.marginRight = '34px';
80
+ label.style.paddingLeft = '20px';
81
+ };
82
+ var loginButton = function (type, fn) {
83
+ var loweredCasedType = type.toLowerCase();
84
+ var result = document.createElement('login-button');
85
+ applyComponentStyle(result);
86
+ result.tabIndex = 0;
87
+ result.setAttribute('data-cy', "".concat(loweredCasedType, "-button"));
88
+ var icon = document.createElement('login-icon');
89
+ icon.style.gridColumnStart = '2';
90
+ icon.style.width = '28px';
91
+ icon.style.height = '28px';
92
+ icon.style.padding = '6px';
93
+ icon.style.marginLeft = '4px';
94
+ icon.style.boxSizing = 'content-box';
95
+ icon.className = 'ico';
96
+ // @ts-ignore
97
+ icon.innerHTML = icons[loweredCasedType];
98
+ var label = document.createElement('login-label');
99
+ label.textContent = window.innerWidth <= THRESHOLD_WIDTH ? type : getTranslation("".concat(loweredCasedType, "-label"));
100
+ applyLabelStyle(label);
101
+ result.append(icon, label);
102
+ result.addEventListener('click', fn);
103
+ result.addEventListener('mouseenter', function () {
104
+ result.style.cursor = 'pointer';
105
+ result.style.boxShadow = '0 0 6px #808080';
106
+ });
107
+ result.addEventListener('mouseleave', function () {
108
+ result.style.cursor = 'auto';
109
+ result.style.boxShadow = '1px 1px 1px grey';
110
+ });
111
+ return result;
112
+ };
113
+
114
+ /******************************************************************************
115
+ Copyright (c) Microsoft Corporation.
116
+
117
+ Permission to use, copy, modify, and/or distribute this software for any
118
+ purpose with or without fee is hereby granted.
119
+
120
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
121
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
122
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
123
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
124
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
125
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
126
+ PERFORMANCE OF THIS SOFTWARE.
127
+ ***************************************************************************** */
128
+
129
+ function __awaiter(thisArg, _arguments, P, generator) {
130
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
131
+ return new (P || (P = Promise))(function (resolve, reject) {
132
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
133
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
134
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
135
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
136
+ });
137
+ }
138
+
139
+ function __generator(thisArg, body) {
140
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
141
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
142
+ function verb(n) { return function (v) { return step([n, v]); }; }
143
+ function step(op) {
144
+ if (f) throw new TypeError("Generator is already executing.");
145
+ while (_) try {
146
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
147
+ if (y = 0, t) op = [op[0] & 2, t.value];
148
+ switch (op[0]) {
149
+ case 0: case 1: t = op; break;
150
+ case 4: _.label++; return { value: op[1], done: false };
151
+ case 5: _.label++; y = op[1]; op = [0]; continue;
152
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
153
+ default:
154
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
155
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
156
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
157
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
158
+ if (t[2]) _.ops.pop();
159
+ _.trys.pop(); continue;
160
+ }
161
+ op = body.call(thisArg, _);
162
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
163
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
164
+ }
165
+ }
166
+
167
+ var extractTokenFromWindowLocation = function (tokenParam, additionalParam) {
168
+ if (additionalParam === void 0) { additionalParam = ''; }
169
+ if (!tokenParam)
170
+ return;
171
+ var token = '';
172
+ var tokenParameterName = "".concat(tokenParam, "=");
173
+ var search = window.location.search;
174
+ var tokenParameterIndex = search.indexOf(tokenParameterName);
175
+ if (tokenParameterIndex !== -1) {
176
+ var tokenParameterNameLength = tokenParameterName.length;
177
+ var leadingAmpersandIndex = search.indexOf('&', tokenParameterIndex);
178
+ var searchWithoutToken = search;
179
+ token = search.substring(tokenParameterIndex + tokenParameterNameLength);
180
+ if (leadingAmpersandIndex !== -1) {
181
+ token = search.substring(tokenParameterIndex + tokenParameterNameLength, leadingAmpersandIndex);
182
+ searchWithoutToken = searchWithoutToken.slice(0, leadingAmpersandIndex) + searchWithoutToken.slice(leadingAmpersandIndex + 1);
183
+ }
184
+ searchWithoutToken = searchWithoutToken.replace("".concat(tokenParam, "=") + token, '')
185
+ .replace(additionalParam, '')
186
+ .replace('\&cypress=true', '');
187
+ if (searchWithoutToken === '?') {
188
+ searchWithoutToken = '';
189
+ }
190
+ window.history.replaceState({}, document.title, window.location.pathname + searchWithoutToken);
191
+ }
192
+ return token;
193
+ };
194
+
195
+ var kebabCaseProvider = function () { var _a; return ((_a = localStorage.getItem('provider')) === null || _a === void 0 ? void 0 : _a.replace(/\./g, '-')) || ''; };
196
+ //@ts-ignore
197
+ var getDynamicBackendUrl = function () { return process.env.DYNAMIC_BACKEND_URL ? process.env.DYNAMIC_BACKEND_URL.replace('%provider', kebabCaseProvider()) : false; };
198
+ //@ts-ignore
199
+ var getBackendUrl = function () { return getDynamicBackendUrl() || process.env.BACKEND_URL; };
200
+ //@ts-ignore
201
+ var getSecondaryBackendUrl = function () { return process.env.STAGING_BACKEND_URL || getBackendUrl(); };
202
+ var getBackendUrlToTry = function () { return getBackendUrl(); };
203
+ var getApiUrl = function () { return getBackendUrl() + 'api/'; };
204
+ var getGoogleAuthUrl = function () { return getBackendUrl() + 'auth-google?google-id-token='; };
205
+ var getMicrosoftAuthUrl = function () { return getBackendUrl() + 'auth-microsoft?access-token='; };
206
+ var getMagicAuthUrl = function () { return getBackendUrl() + 'auth-magic?token='; };
207
+ var getMagicAuthReqUrl = function () { return getBackendUrl() + 'magic-link-request?email='; };
208
+ var timeout;
209
+ var maxRetries = 20;
210
+ var retries = 0;
211
+ var applySpinnerStyle = function (spinner) {
212
+ spinner.style.position = 'fixed';
213
+ spinner.style.top = '50%';
214
+ spinner.style.zIndex = '2147483647';
215
+ spinner.style.border = '8px solid #bababa';
216
+ spinner.style.borderTopColor = '#171f1c';
217
+ spinner.style.height = '80px';
218
+ spinner.style.width = '80px';
219
+ };
220
+ var renderOverlay = function () {
221
+ var overlay = document.createElement('reconnect-overlay');
222
+ var spinner = document.createElement('loading-spinner');
223
+ spinner.className = 'reconnect-spinner';
224
+ applySpinnerStyle(spinner);
225
+ document.body.append(overlay, spinner);
226
+ };
227
+ var removeOverlay = function () {
228
+ var _a, _b;
229
+ (_a = document.querySelector('reconnect-overlay')) === null || _a === void 0 ? void 0 : _a.remove();
230
+ (_b = document.querySelector('.reconnect-spinner')) === null || _b === void 0 ? void 0 : _b.remove();
231
+ };
232
+ var backendHelpMessage = function (req) {
233
+ return req.response && req.response.error || req.response || req;
234
+ };
235
+ var backendRequest = function (requestType, url, postContent, onJsonResponse, onHelpMessage) {
236
+ if (url.includes(getBackendUrl())) {
237
+ url = url.replace(getBackendUrl(), getBackendUrlToTry());
238
+ }
239
+ else if (url.includes(getSecondaryBackendUrl())) {
240
+ url = url.replace(getSecondaryBackendUrl(), getBackendUrlToTry());
241
+ }
242
+ clearInterval(timeout);
243
+ var req = new XMLHttpRequest();
244
+ req.open(requestType, url, true);
245
+ // @ts-ignore
246
+ var backendToken = window.store.backendToken;
247
+ if (backendToken) {
248
+ req.setRequestHeader('auth', backendToken);
249
+ }
250
+ req.setRequestHeader('Content-Type', 'application/json');
251
+ req.responseType = 'json';
252
+ req.onerror = req.ontimeout = function () {
253
+ if (req.status === 401) {
254
+ localStorage.removeItem('token');
255
+ alert(getTranslation('session-expired-msg'));
256
+ location.reload();
257
+ // googleAuthSignOut(); TODO
258
+ }
259
+ else if (req.status === 0) {
260
+ if (retries >= maxRetries) {
261
+ removeOverlay();
262
+ // displayPage(Page.DISCONNECTED); TODO
263
+ return;
264
+ }
265
+ retries++;
266
+ if (!document.querySelector('reconnect-overlay')) {
267
+ renderOverlay();
268
+ }
269
+ var backupBackendUrl_1 = getBackendUrlToTry() === getBackendUrl()
270
+ ? getSecondaryBackendUrl()
271
+ : getBackendUrl();
272
+ url = url.replace(getBackendUrlToTry(), backupBackendUrl_1);
273
+ getBackendUrlToTry = function () { return backupBackendUrl_1; };
274
+ timeout = setTimeout(function () {
275
+ backendRequest(requestType, url, postContent, onJsonResponse, onHelpMessage);
276
+ }, 2000);
277
+ }
278
+ else {
279
+ onHelpMessage(backendHelpMessage(req));
280
+ }
281
+ };
282
+ req.onload = function () {
283
+ retries = 0;
284
+ removeOverlay();
285
+ if (req.status === 200 || req.status === 202) {
286
+ onJsonResponse(req.response);
287
+ }
288
+ else {
289
+ if (req.onerror) {
290
+ // @ts-ignore
291
+ req.onerror();
292
+ }
293
+ }
294
+ };
295
+ req.timeout = 25000;
296
+ req.send(postContent);
297
+ };
298
+ var backendPost = function (endpoint, postContent, onJsonResponse, onHelpMessage) {
299
+ backendRequest('POST', getApiUrl() + endpoint, postContent, onJsonResponse, onHelpMessage);
300
+ };
301
+ var backendGet = function (endpoint, onJsonResponse, onHelpMessage) {
302
+ var api = getApiUrl() + endpoint;
303
+ if (endpoint.includes(getGoogleAuthUrl()) || endpoint.includes(getMicrosoftAuthUrl())) {
304
+ api = endpoint;
305
+ }
306
+ backendRequest('GET', api, undefined, onJsonResponse, onHelpMessage);
307
+ };
308
+ var backendGetPromise = function (endpoint) { return new Promise(function (resolve, reject) {
309
+ return backendGet(endpoint, resolve, reject);
310
+ }); };
311
+ var requestMagicLink = function (data, onJsonResponse) {
312
+ backendRequest('GET', getMagicAuthReqUrl() + encodeURIComponent(data.email) + '&destination=' + extractTokenFromWindowLocation('destination') + '&token=' + data.token, undefined, onJsonResponse, function () { });
313
+ };
314
+ var openMagicLink = function (magicToken, onJsonResponse, onHelpMessage) {
315
+ backendRequest('GET', getMagicAuthUrl() + magicToken, undefined, onJsonResponse, onHelpMessage);
316
+ };
317
+ var getMXData = function (domainName) { return __awaiter(void 0, void 0, void 0, function () {
318
+ var records, recordsJson, answer, data;
319
+ return __generator(this, function (_a) {
320
+ switch (_a.label) {
321
+ case 0: return [4 /*yield*/, fetch("https://dns.google.com/resolve?name=".concat(domainName, "&type=MX"), {
322
+ method: 'GET',
323
+ mode: 'cors'
324
+ })];
325
+ case 1:
326
+ records = _a.sent();
327
+ return [4 /*yield*/, records.json()];
328
+ case 2:
329
+ recordsJson = _a.sent();
330
+ answer = recordsJson.Answer;
331
+ if (!answer) {
332
+ return [2 /*return*/, null];
333
+ }
334
+ data = Array.from(answer).map(function (a) { return a.data; });
335
+ return [2 /*return*/, data];
336
+ }
337
+ });
338
+ }); };
339
+
340
+ var cleared = false;
341
+ var clearCookieValidation = function () {
342
+ var _a;
343
+ (_a = document.querySelector('#cookie-test-iframe')) === null || _a === void 0 ? void 0 : _a.remove();
344
+ cleared = true;
345
+ };
346
+ var checkCookiesEnable = function (ev, onEnabled, onDisabled) {
347
+ if (ev.data === 'MM:3PCunsupported') {
348
+ clearCookieValidation();
349
+ if (onDisabled) {
350
+ onDisabled();
351
+ }
352
+ }
353
+ else if (ev.data === 'MM:3PCsupported') {
354
+ clearCookieValidation();
355
+ onEnabled();
356
+ }
357
+ };
358
+ var cookieTest = function () {
359
+ var frame = document.createElement('iframe');
360
+ frame.id = 'cookie-test-iframe';
361
+ frame.src = 'https://mindmup.github.io/3rdpartycookiecheck/start.html';
362
+ frame.style.display = 'none';
363
+ document.body.appendChild(frame);
364
+ };
365
+ var validateThirdPartyCookies = function (onEnabled, onDisabled) {
366
+ cleared = false;
367
+ var listener = function (ev) { return checkCookiesEnable(ev, onEnabled, onDisabled); };
368
+ window.addEventListener('message', listener);
369
+ var timer = setInterval(function () {
370
+ if (cleared) {
371
+ window.removeEventListener('message', listener);
372
+ clearInterval(timer);
373
+ }
374
+ }, 50);
375
+ cookieTest();
376
+ };
377
+
378
+ var enableSignInLayout = function () {
379
+ document.documentElement.style.cursor = 'progress';
380
+ document.body.style.opacity = '0.5';
381
+ document.body.style.pointerEvents = 'none';
382
+ };
383
+ var disableSignInLayout = function () {
384
+ document.documentElement.style.cursor = 'default';
385
+ document.body.style.opacity = '1';
386
+ document.body.style.pointerEvents = 'auto';
387
+ };
388
+
389
+ // TODO: find a better way to import external scripts
390
+ var script$1 = document.createElement('script');
391
+ script$1.type = 'text/javascript';
392
+ script$1.src = 'https://apis.google.com/js/api.js';
393
+ document.head.appendChild(script$1);
394
+ var authStatus;
395
+ var authError;
396
+ var highLevelUser = function (gUser) {
397
+ var profile = gUser.getBasicProfile();
398
+ return {
399
+ name: profile.getName(),
400
+ email: profile.getEmail(),
401
+ picture: profile.getImageUrl(),
402
+ googletoken: gUser.getAuthResponse().id_token
403
+ };
404
+ };
405
+ var onUserChanged = function (googleUser, onUserLogin) { return __awaiter(void 0, void 0, void 0, function () {
406
+ var error_1;
407
+ return __generator(this, function (_a) {
408
+ switch (_a.label) {
409
+ case 0:
410
+ document.documentElement.classList.remove('progress');
411
+ document.body.classList.remove('disabled');
412
+ if (!googleUser) return [3 /*break*/, 5];
413
+ _a.label = 1;
414
+ case 1:
415
+ _a.trys.push([1, 3, , 4]);
416
+ return [4 /*yield*/, backendGetPromise(getGoogleAuthUrl() + googleUser.googletoken)
417
+ .then(function (res) {
418
+ var token = res.token;
419
+ // @ts-ignore
420
+ window.store.currentUser = res;
421
+ onTokenAcquired(token, onUserLogin);
422
+ })
423
+ .catch(function (error) { throw Error(error); })];
424
+ case 2:
425
+ _a.sent();
426
+ return [3 /*break*/, 4];
427
+ case 3:
428
+ error_1 = _a.sent();
429
+ console.error(error_1);
430
+ // logError(error); TODO
431
+ // checkMixpanel(() => mixpanel.track('Login Error', { 'Login Type': 'Google', 'Error': error })); TODO
432
+ return [2 /*return*/];
433
+ case 4: return [3 /*break*/, 6];
434
+ case 5:
435
+ setBackendToken('');
436
+ _a.label = 6;
437
+ case 6: return [2 /*return*/];
438
+ }
439
+ });
440
+ }); };
441
+ var onGoogleUserChanged = function (gUser, onUserLogin) {
442
+ onUserChanged(gUser.isSignedIn() ? highLevelUser(gUser) : null, onUserLogin);
443
+ };
444
+ var initGapiClient = function (callbackFn, onUserLogin) {
445
+ // @ts-ignore
446
+ var clientId = process.env.GOOGLE_CLIENT_ID;
447
+ gapi.auth2.init({ client_id: clientId, prompt: 'select_account' }).then(function () {
448
+ authStatus = 'LOADED';
449
+ var currentUser = getAuth().currentUser;
450
+ currentUser.listen(onGoogleUserChanged);
451
+ callbackFn ? callbackFn(clientId) : onGoogleUserChanged(currentUser.get(), onUserLogin);
452
+ }, onAuthError);
453
+ };
454
+ var onAuthError = function (error) {
455
+ authError = error;
456
+ console.error(error);
457
+ // logError(error, authError); // TODO
458
+ };
459
+ var initGapi = function (callbackFn, onUserLogin) {
460
+ if (callbackFn === void 0) { callbackFn = null; }
461
+ if (!window.location.protocol.startsWith('http')) {
462
+ onAuthError('To use Google Auth you must access this page using http(s), not ' + window.location.protocol);
463
+ return;
464
+ }
465
+ if (typeof gapi === 'undefined') {
466
+ onAuthError('Unable to load the Google API');
467
+ return;
468
+ }
469
+ authStatus = 'LOADING';
470
+ gapi.load('auth2', {
471
+ callback: function () { return initGapiClient(callbackFn, onUserLogin); },
472
+ onerror: onAuthError,
473
+ ontimeout: onAuthError,
474
+ timeout: 5000
475
+ });
476
+ };
477
+ var authAlert = function (error) {
478
+ alert('Google authentication is not working at this moment.\n\nPlease try again later or use a magic sign-in link.\n\nError: ' + JSON.stringify(error));
479
+ location.reload();
480
+ };
481
+ var onSignInError = function (error) {
482
+ disableSignInLayout();
483
+ console.error(error);
484
+ // logError(error); TODO
485
+ if (error && error.error === 'popup_closed_by_user') {
486
+ onUserChanged(null, function () { });
487
+ return;
488
+ }
489
+ authAlert(error);
490
+ };
491
+ var getAuth = function () {
492
+ if (typeof gapi === 'undefined') {
493
+ console.error('gapi is undefined');
494
+ // logError('gapi is undefined'); TODO
495
+ return null;
496
+ }
497
+ return gapi.auth2 && gapi.auth2.getAuthInstance();
498
+ };
499
+ var googleSignIn = function () { return getAuth().signIn().catch(onSignInError); };
500
+ var authSignIn = function (onUserLogin) {
501
+ if (authError) {
502
+ authAlert(authError);
503
+ return;
504
+ }
505
+ if (authStatus === 'LOADING') {
506
+ setTimeout(authSignIn, 400);
507
+ }
508
+ else {
509
+ try {
510
+ googleSignIn();
511
+ }
512
+ catch (err) {
513
+ try {
514
+ initGapi(function () { return googleSignIn(); }, onUserLogin);
515
+ }
516
+ catch (error) {
517
+ onSignInError(error);
518
+ }
519
+ }
520
+ }
521
+ };
522
+
523
+ // TODO: find a better way to import external scripts
524
+ var script = document.createElement('script');
525
+ script.type = 'text/javascript';
526
+ script.src = 'https://www.google.com/recaptcha/api.js';
527
+ document.head.appendChild(script);
528
+ var googleCaptcha = function () {
529
+ var result = document.createElement('google-captcha');
530
+ window.submitCaptcha = function (token) { return result.setAttribute('token', token); };
531
+ result.className = 'g-recaptcha';
532
+ // @ts-ignore
533
+ result.setAttribute('data-sitekey', process.env.GOOGLE_CAPTCHA_KEY);
534
+ result.setAttribute('data-callback', 'submitCaptcha');
535
+ grecaptcha.render(result);
536
+ return result;
537
+ };
538
+
539
+ var juxWhite = '#FFF';
540
+ var juxDarkGrey = '#282828';
541
+ var juxDimmedDarkGrey = '#28282822';
542
+ var juxDimmedBlack = '#00000088';
543
+ var juxLightGreen = '#20B03D';
544
+ var juxMediumGreen = '#0D631E';
545
+
546
+ var onKeyDown = function (ev, el, persitent, onClose) {
547
+ if (ev.key === 'Escape') {
548
+ if (persitent) {
549
+ return;
550
+ }
551
+ close(el, onClose);
552
+ }
553
+ else if (ev.key === 'Enter') {
554
+ if (ev.target.id === 'members-textarea') {
555
+ return;
556
+ }
557
+ el.dispatchEvent(new CustomEvent('ok'));
558
+ }
559
+ };
560
+ var close = function (el, onClose) {
561
+ el.remove();
562
+ if (onClose) {
563
+ onClose();
564
+ }
565
+ };
566
+ var attachEventHandlers = function (el, persitent, onClose) {
567
+ var cancelButton = el.querySelector('.cancel');
568
+ cancelButton === null || cancelButton === void 0 ? void 0 : cancelButton.addEventListener('click', function (_e) {
569
+ el.dispatchEvent(new CustomEvent('cancel'));
570
+ if (el.hasAttribute('dont-remove')) {
571
+ return;
572
+ }
573
+ close(el, onClose);
574
+ });
575
+ var closeButton = el.querySelector('.close');
576
+ if (closeButton) {
577
+ closeButton.addEventListener('click', function (_e) {
578
+ close(el, onClose);
579
+ });
580
+ }
581
+ var okButton = el.querySelector('.ok');
582
+ okButton === null || okButton === void 0 ? void 0 : okButton.addEventListener('click', function (_e) {
583
+ el.dispatchEvent(new CustomEvent('ok'));
584
+ });
585
+ el.removeEventListener('keydown', function (ev) { return onKeyDown(ev, el, persitent, function () { return onClose; }); });
586
+ el.addEventListener('keydown', function (ev) { return onKeyDown(ev, el, persitent, function () { return onClose; }); });
587
+ el === null || el === void 0 ? void 0 : el.addEventListener('click', function (e) {
588
+ if (e.target === el) {
589
+ if (persitent) {
590
+ return;
591
+ }
592
+ close(el, onClose);
593
+ }
594
+ });
595
+ };
596
+ // TODO: Mudar construtor para usar essa interface
597
+ // interface JuxModalOptions {
598
+ // title?: string,
599
+ // btns?: string[],
600
+ // content?: string,
601
+ // isPersistent?: boolean,
602
+ // isBusy?: boolean,
603
+ // body?: HTMLElement,
604
+ // okTxt?: string,
605
+ // cancelTxt?: string,
606
+ // onClose?: any,
607
+ // titleStyle?: string,
608
+ // }
609
+ var applyWrapperStyle = function (wrapper) {
610
+ wrapper.style.alignItems = 'center';
611
+ wrapper.style.backgroundColor = juxWhite;
612
+ wrapper.style.borderRadius = '.3125rem';
613
+ wrapper.style.boxShadow = "0 0 1.33rem ".concat(juxDimmedBlack);
614
+ wrapper.style.boxSizing = 'content-box';
615
+ wrapper.style.display = 'flex';
616
+ wrapper.style.flexDirection = 'column';
617
+ wrapper.style.justifyContent = 'flex-start';
618
+ wrapper.style.margin = '0';
619
+ wrapper.style.maxHeight = '88%';
620
+ wrapper.style.maxWidth = '40%';
621
+ wrapper.style.minWidth = '20%';
622
+ wrapper.style.padding = '1.33rem';
623
+ wrapper.style.position = 'relative';
624
+ };
625
+ var applyModalStyle = function (modal) {
626
+ modal.style.alignItems = 'center';
627
+ modal.style.backgroundColor = juxDimmedBlack;
628
+ modal.style.display = 'flex';
629
+ modal.style.height = '100vh';
630
+ modal.style.justifyContent = 'center';
631
+ modal.style.left = '0';
632
+ modal.style.overflow = 'hidden';
633
+ modal.style.position = 'fixed';
634
+ modal.style.top = '0';
635
+ modal.style.width = '100%';
636
+ modal.style.zIndex = '9999';
637
+ };
638
+ var applyHeaderStyle = function (header) {
639
+ header.style.alignItems = 'center';
640
+ header.style.color = juxMediumGreen;
641
+ header.style.flexDirection = 'row';
642
+ header.style.fontSize = '16px';
643
+ header.style.fontWeight = '700';
644
+ header.style.justifyContent = 'space-between';
645
+ header.style.margin = '0';
646
+ header.style.display = 'flex';
647
+ header.style.position = 'relative';
648
+ header.style.width = '100%';
649
+ };
650
+ var applyJuxModalContentStyle = function (el) {
651
+ el.style.display = 'flex';
652
+ el.style.position = 'relative';
653
+ el.style.width = '100%';
654
+ el.style.flexFlow = 'column';
655
+ el.style.marginTop = '1.33rem';
656
+ el.style.rowGap = '8px';
657
+ };
658
+ var juxModal = function (title, btns, content, persistent, _busy, body, okTxt, cancelTxt, onClose, titleStyle) {
659
+ if (btns === void 0) { btns = ['ok', 'cancel']; }
660
+ if (content === void 0) { content = ''; }
661
+ if (persistent === void 0) { persistent = false; }
662
+ if (okTxt === void 0) { okTxt = getTranslation('alert-ok-btn-txt'); }
663
+ if (cancelTxt === void 0) { cancelTxt = getTranslation('alert-cancel-btn-txt'); }
664
+ var result = document.createElement('jux-modal');
665
+ applyModalStyle(result);
666
+ var wrapper = document.createElement('modal-wrapper');
667
+ applyWrapperStyle(wrapper);
668
+ // START close
669
+ var closeBtn = document.createElement('button');
670
+ if (!persistent) {
671
+ closeBtn.className = 'close';
672
+ closeBtn.setAttribute('aria-label', getTranslation('close'));
673
+ }
674
+ // END close
675
+ // START header
676
+ var header = document.createElement('modal-header');
677
+ applyHeaderStyle(header);
678
+ if (title) {
679
+ if (titleStyle) {
680
+ header.classList.add(titleStyle);
681
+ }
682
+ var h3 = document.createElement('h3');
683
+ h3.textContent = title;
684
+ header.appendChild(h3);
685
+ }
686
+ // END header
687
+ // START content
688
+ var modalContent = document.createElement('jux-modal-content');
689
+ applyJuxModalContentStyle(modalContent);
690
+ if (content) {
691
+ modalContent.innerHTML = content;
692
+ }
693
+ else if (body) {
694
+ modalContent.appendChild(body);
695
+ }
696
+ // END content
697
+ // START footer
698
+ var footer = document.createElement('modal-footer');
699
+ if (btns.includes('cancel')) {
700
+ var cancelBtn = document.createElement('button');
701
+ cancelBtn.classList.add('secondary-button', 'modal-button', 'action', 'cancel-btn', 'cancel');
702
+ var cancelText = document.createElement('button-text');
703
+ cancelText.textContent = cancelTxt;
704
+ var cancelSpinner = document.createElement('loading-spinner');
705
+ cancelBtn.append(cancelText, cancelSpinner);
706
+ footer.appendChild(cancelBtn);
707
+ }
708
+ if (btns.includes('ok')) {
709
+ var okBtn = document.createElement('button');
710
+ okBtn.classList.add('primary-button', 'modal-button', 'action', 'ok');
711
+ var okText = document.createElement('button-text');
712
+ okText.textContent = okTxt;
713
+ var okSpinner = document.createElement('loading-spinner');
714
+ okBtn.append(okText, okSpinner);
715
+ footer.appendChild(okBtn);
716
+ }
717
+ // END footer
718
+ if (footer.hasChildNodes()) {
719
+ wrapper.append(closeBtn, header, modalContent, footer);
720
+ }
721
+ else {
722
+ wrapper.append(closeBtn, header, modalContent);
723
+ }
724
+ result.appendChild(wrapper);
725
+ if (!persistent) {
726
+ result.querySelector('.close').focus();
727
+ }
728
+ else {
729
+ if (btns.includes('ok')) {
730
+ result.querySelector('.ok').focus();
731
+ }
732
+ }
733
+ attachEventHandlers(result, persistent, onClose);
734
+ return result;
735
+ };
736
+
737
+ var contactField = function (tag, elType, elName, required, value) {
738
+ if (tag === void 0) { tag = 'input'; }
739
+ if (required === void 0) { required = true; }
740
+ var result = document.createElement('contact-field');
741
+ var elId = 'contact-' + elName;
742
+ var label = document.createElement('label');
743
+ label.textContent = getTranslation(elId + '-label');
744
+ label.htmlFor = elId;
745
+ var el = document.createElement(tag);
746
+ el.id = elId;
747
+ el.setAttribute('name', elName);
748
+ el.setAttribute('placeholder', getTranslation(elId + '-placeholder'));
749
+ if (tag === 'input') {
750
+ el.setAttribute('type', elType);
751
+ }
752
+ if (required) {
753
+ el.setAttribute('required', 'true');
754
+ }
755
+ if (value) {
756
+ el.setAttribute('value', value);
757
+ }
758
+ result.append(label, el);
759
+ return result;
760
+ };
761
+
762
+ var getNestedElValue = function (el, nestedTag) {
763
+ var nestedEl = el.querySelector(nestedTag);
764
+ return nestedEl.value;
765
+ };
766
+ var sendInquiry = function (name, email, msg, whatsapp, subject, token) {
767
+ var inquiryPayload = {
768
+ subject: "[".concat(subject.charAt(0).toUpperCase()).concat(subject.slice(1), "] ").concat(getNestedElValue(name, 'input')),
769
+ body: "<strong>Name</strong>: ".concat(getNestedElValue(name, 'input'), "<br><br>\n<strong>E-mail</strong>: ").concat(getNestedElValue(email, 'input'), "<br><br>\n<strong>Whatsapp</strong>: ").concat(getNestedElValue(whatsapp, 'input'), "<br><br>\n<strong>Message</strong>: ").concat(getNestedElValue(msg, 'textarea')),
770
+ token: token,
771
+ };
772
+ backendPost('contact-us', JSON.stringify(inquiryPayload), function (_res) {
773
+ var _a;
774
+ // success(getTranslation('form-success'), Length.long);
775
+ (_a = document.querySelector('#contact-us-modal')) === null || _a === void 0 ? void 0 : _a.remove();
776
+ }, function () { } // TODO: change it to be an error handling fn provided by the client
777
+ );
778
+ // checkMixpanel(() => mixpanel.track("Sent Contact Inquiry", {}));
779
+ };
780
+ var contactUsModal = function (subject) {
781
+ var _a, _b, _c, _d, _e;
782
+ var result = document.createElement('contact-us-modal');
783
+ // @ts-ignore
784
+ var currentName = window.store.currentUser ? window.store.currentUser.name : '';
785
+ // @ts-ignore
786
+ var currentEmail = window.store.currentUser ? window.store.currentUser.email : (_a = document.querySelector('#magic-link-email')) === null || _a === void 0 ? void 0 : _a.textContent;
787
+ var modalBody = document.createElement('modal-body');
788
+ var form = document.createElement('form');
789
+ form.id = 'contact-form';
790
+ var nameField = contactField('input', 'text', 'name', true, currentName);
791
+ var emailField = contactField('input', 'email', 'email', true, currentEmail);
792
+ var messageField = contactField('textarea', 'text', 'message', true);
793
+ var whatsappField = contactField('input', 'tel', 'whatsapp', false);
794
+ var btn = document.createElement('button');
795
+ btn.textContent = getTranslation('contact-submit');
796
+ btn.className = 'primary-button';
797
+ form.append(nameField, emailField, whatsappField, messageField, btn);
798
+ modalBody.appendChild(form);
799
+ var modal = juxModal(getTranslation('contact-page'), [], '', false, false, modalBody, '', '', function () { return result.remove(); });
800
+ modal.id = 'contact-us-modal';
801
+ document.body.appendChild(modal);
802
+ (_b = modal.querySelector('modal-wrapper')) === null || _b === void 0 ? void 0 : _b.setAttribute('style', 'max-width: 680px; width: 100%; overflow-y: auto;');
803
+ var captcha = googleCaptcha();
804
+ if (subject !== 'email-not-sent') {
805
+ // @ts-ignore
806
+ var admin = ((_d = (_c = window.store) === null || _c === void 0 ? void 0 : _c.selectedTeam) === null || _d === void 0 ? void 0 : _d.admin) || window.store.currentUser.email;
807
+ backendGet("credits-balance-for?admin=".concat(admin), function (res) {
808
+ var balance = res;
809
+ if (balance <= 0) {
810
+ form.insertBefore(captcha, btn);
811
+ }
812
+ }, function () { } // TODO: change it to be an error handling fn provided by the client
813
+ );
814
+ }
815
+ else {
816
+ form.insertBefore(captcha, btn);
817
+ }
818
+ (_e = nameField.querySelector('input')) === null || _e === void 0 ? void 0 : _e.select();
819
+ form.addEventListener('submit', function (event) {
820
+ event.preventDefault();
821
+ sendInquiry(nameField, emailField, messageField, whatsappField, subject, captcha.getAttribute('token'));
822
+ });
823
+ return result;
824
+ };
825
+
826
+ var applyPageStyles$1 = function (page, backgroundImg) {
827
+ page.style.backgroundImage = "url(".concat(backgroundImg, ")");
828
+ page.style.display = 'block';
829
+ page.style.width = '100%';
830
+ page.style.height = '100%';
831
+ page.style.backgroundPosition = '50%';
832
+ page.style.backgroundSize = 'cover';
833
+ page.style.display = 'block';
834
+ };
835
+ var applyContainerStyles$1 = function (container) {
836
+ container.style.backgroundColor = '#ffffffdd';
837
+ container.style.borderRadius = '16px';
838
+ container.style.inset = '50% 50% 50% 0';
839
+ container.style.position = 'relative';
840
+ container.style.transform = 'translateY(-50%)';
841
+ container.style.width = '620px';
842
+ container.style.alignItems = 'center';
843
+ container.style.display = 'flex';
844
+ container.style.flexDirection = 'column';
845
+ container.style.fontSize = '16px';
846
+ container.style.height = '100%';
847
+ container.style.justifyContent = 'center';
848
+ container.style.margin = '0 auto';
849
+ container.style.paddingTop = '0';
850
+ };
851
+ var applyBtnStyles = function (btn) {
852
+ btn.style.cursor = 'pointer';
853
+ btn.style.textDecoration = 'underline';
854
+ btn.style.border = 'none';
855
+ btn.style.backgroundColor = '';
856
+ btn.style.background = 'none';
857
+ btn.style.boxSizing = 'border-box';
858
+ btn.style.margin = '0';
859
+ btn.style.outline = 'none';
860
+ btn.style.padding = '0';
861
+ btn.style.whiteSpace = 'normal';
862
+ btn.style.font = 'inherit';
863
+ };
864
+ var magicLinkRequestedPage = function (backgroundImg, onReturn) {
865
+ var result = document.createElement('magic-link-requested-page');
866
+ var section = document.createElement('section');
867
+ applyContainerStyles$1(section);
868
+ var magicLinkSent = document.createElement('p');
869
+ magicLinkSent.id = 'magic-link-sent';
870
+ magicLinkSent.textContent = getTranslation(magicLinkSent.id);
871
+ magicLinkSent.style.marginBottom = '10px';
872
+ var magicLinkEmail = document.createElement('p');
873
+ magicLinkEmail.id = 'magic-link-email';
874
+ magicLinkEmail.style.fontWeight = '700';
875
+ magicLinkEmail.style.marginBottom = '10px';
876
+ var magicLinkHowTo = document.createElement('p');
877
+ magicLinkHowTo.id = 'magic-link-how-to';
878
+ magicLinkHowTo.innerHTML = getTranslation(magicLinkHowTo.id);
879
+ magicLinkHowTo.style.padding = '0 30px';
880
+ magicLinkHowTo.style.textAlign = 'center';
881
+ var btn = document.createElement('button');
882
+ btn.id = 'email-not-received-btn';
883
+ btn.addEventListener('click', function () { return document.body.appendChild(contactUsModal('email-not-sent')); });
884
+ btn.textContent = getTranslation('magic-link-let-us-know');
885
+ applyBtnStyles(btn);
886
+ var returnLink = document.createElement('a');
887
+ returnLink.textContent = getTranslation('return-link');
888
+ returnLink.onclick = function () {
889
+ result.remove();
890
+ onReturn();
891
+ };
892
+ returnLink.style.marginTop = '32px';
893
+ returnLink.style.cursor = 'pointer';
894
+ returnLink.style.fontWeight = '700';
895
+ returnLink.style.textDecoration = 'underline';
896
+ section.append(magicLinkSent, magicLinkEmail, magicLinkHowTo, btn, returnLink);
897
+ applyPageStyles$1(result, backgroundImg);
898
+ result.appendChild(section);
899
+ return result;
900
+ };
901
+
902
+ var setBackendToken = function (token) {
903
+ // @ts-ignore
904
+ window.store.backendToken = token;
905
+ if (token) {
906
+ localStorage.setItem('token', token);
907
+ }
908
+ };
909
+ var getBackendToken = function () {
910
+ var _a;
911
+ var token = (_a = localStorage.getItem('token')) !== null && _a !== void 0 ? _a : '';
912
+ // @ts-ignore
913
+ window.store.backendToken = token;
914
+ return token;
915
+ };
916
+ var onTokenAcquired = function (token, onUserLogin) {
917
+ setBackendToken(token);
918
+ // setSuperToken();
919
+ onUserLogin();
920
+ };
921
+ var clearSession = function () {
922
+ // onUserChanged(null);
923
+ localStorage.clear();
924
+ // @ts-ignore
925
+ window.store = {};
926
+ };
927
+ var onAuthenticationFailure = function (msg) {
928
+ localStorage.removeItem('token');
929
+ // displayPage(Page.LOGIN);
930
+ alert(getTranslation(msg));
931
+ };
932
+ var onAuthentication = function (onUserLogin, user, type) {
933
+ if ((user.token && getBackendToken()) && getBackendToken() !== user.token) {
934
+ clearSession();
935
+ }
936
+ // @ts-ignore
937
+ window.store.currentUser = user;
938
+ if (type === 'Token Authentication') {
939
+ user.token = localStorage.getItem('token');
940
+ }
941
+ onTokenAcquired(user.token, onUserLogin);
942
+ // mixpanelIdentify(user);
943
+ // checkMixpanel(() => mixpanel.track('Login', { 'Login Type': type }));
944
+ };
945
+ var displayPage = function (clientApp, page) {
946
+ Array.from(clientApp.children).forEach(function (el) { return el.remove(); });
947
+ clientApp.appendChild(page);
948
+ };
949
+ var initSession = function (clientApp, supportedLoginTypes, onUserLogin, backgroundImage) {
950
+ // if (startNewDemo()) {
951
+ // initDemo(setBackendToken, onAuthentication);
952
+ // return;
953
+ // }
954
+ var magicToken = extractTokenFromWindowLocation('magic-link');
955
+ if (magicToken) {
956
+ var host = extractTokenFromWindowLocation('host');
957
+ if (host) {
958
+ localStorage.setItem('provider', host);
959
+ }
960
+ openMagicLink(magicToken, function (res) { return onAuthentication(onUserLogin, res, 'Magic Link'); }, function () { return onAuthenticationFailure('unable-magic-login'); });
961
+ return;
962
+ }
963
+ if (getBackendToken()) {
964
+ backendGet('profile', function (res) { return onAuthentication(onUserLogin, res, 'Token Authentication'); }, function (_err) { return onAuthenticationFailure('login-failed'); });
965
+ return;
966
+ }
967
+ displayPage(clientApp, loginPage(clientApp, backgroundImage, onUserLogin, supportedLoginTypes));
968
+ // const linkedinToken = extractTokenFromWindowLocation('code', '\&state=9893849343');
969
+ // if (linkedinToken) {
970
+ // openLinkedinSession(
971
+ // linkedinToken,
972
+ // (res) => onAuthentication(res, 'Linkedin Authentication'),
973
+ // () => onAuthenticationFailure('unable-linkedin-login')
974
+ // );
975
+ // return;
976
+ // }
977
+ // validateThirdPartyCookies(initGapi, () => displayPage(Page.LOGIN));
978
+ // checkMixpanel(() => mixpanel.track('View Login Page'));
979
+ };
980
+ var onMicrosoftSignIn = function (onUserLogin) { return __awaiter(void 0, void 0, void 0, function () {
981
+ var msalConfig, msalInstance, loginRequest, loginResponse, accessToken, err_1;
982
+ return __generator(this, function (_a) {
983
+ switch (_a.label) {
984
+ case 0:
985
+ msalConfig = { auth: { clientId: process.env.MICROSOFT_CLIENT_ID } };
986
+ msalInstance = new msal__namespace.PublicClientApplication(msalConfig);
987
+ loginRequest = { scopes: ['user.read'] };
988
+ enableSignInLayout();
989
+ _a.label = 1;
990
+ case 1:
991
+ _a.trys.push([1, 4, , 5]);
992
+ return [4 /*yield*/, msalInstance.loginPopup(loginRequest)];
993
+ case 2:
994
+ loginResponse = _a.sent();
995
+ accessToken = loginResponse.accessToken;
996
+ return [4 /*yield*/, backendGetPromise(getMicrosoftAuthUrl() + accessToken)
997
+ .then(function (res) {
998
+ var token = res.token;
999
+ // @ts-ignore
1000
+ window.store.currentUser = res;
1001
+ onTokenAcquired(token, onUserLogin);
1002
+ })
1003
+ .catch(console.error)
1004
+ .finally(function () { return disableSignInLayout(); })];
1005
+ case 3:
1006
+ _a.sent();
1007
+ return [3 /*break*/, 5];
1008
+ case 4:
1009
+ err_1 = _a.sent();
1010
+ reportError(err_1);
1011
+ disableSignInLayout();
1012
+ return [3 /*break*/, 5];
1013
+ case 5: return [2 /*return*/];
1014
+ }
1015
+ });
1016
+ }); };
1017
+ var onCookieError = function () {
1018
+ disableSignInLayout();
1019
+ // warning('cookie-error'); TODO
1020
+ return;
1021
+ };
1022
+ var onGoogleSignIn = function (onUserLogin) {
1023
+ validateThirdPartyCookies(function () {
1024
+ enableSignInLayout();
1025
+ authSignIn(onUserLogin);
1026
+ }, onCookieError);
1027
+ };
1028
+ var handleMagicLinkRequest = function (token, onReturn, backgroundImage, currentPage, clientBody, email) {
1029
+ if (email === void 0) { email = ''; }
1030
+ if (!email) {
1031
+ var mailMagic = document.querySelector('#mail-magic');
1032
+ email = mailMagic.value;
1033
+ }
1034
+ var payload = { email: email, token: token };
1035
+ var provider = email.split('@')[1];
1036
+ localStorage.setItem('provider', provider);
1037
+ requestMagicLink(payload, function (_res) {
1038
+ currentPage.remove();
1039
+ clientBody.appendChild(magicLinkRequestedPage(backgroundImage, onReturn));
1040
+ var magicLinkEmail = document.querySelector('#magic-link-email');
1041
+ magicLinkEmail.textContent = email;
1042
+ });
1043
+ };
1044
+
1045
+ var socialLoginModal = function (userEmail, mailExchanger, token, onUserLogin, onReturn, backgroundImage, currentPage, clientBody, closeMagicLinkModal) {
1046
+ var result = document.createElement('social-login-modal');
1047
+ var email = document.createElement('p');
1048
+ email.textContent = "\"".concat(userEmail, "\"");
1049
+ var msg = document.createElement('social-login-msg');
1050
+ msg.textContent = getTranslation('social-login-recommendation') + mailExchanger + '.' + getTranslation('social-login-advantage');
1051
+ var body = document.createElement('social-login-body');
1052
+ var socialLoginBtn = mailExchanger === 'Microsoft' ?
1053
+ loginButton('Microsoft', function () { return onMicrosoftSignIn(onUserLogin); }) :
1054
+ loginButton('Google', function () { return onGoogleSignIn(onUserLogin); });
1055
+ var proceedMagicLinkRequest = document.createElement('a');
1056
+ proceedMagicLinkRequest.textContent = getTranslation('proceed-magic-link-request');
1057
+ proceedMagicLinkRequest.addEventListener('click', function () {
1058
+ handleMagicLinkRequest(token, onReturn, backgroundImage, currentPage, clientBody, userEmail);
1059
+ closeMagicLinkModal();
1060
+ result.remove();
1061
+ });
1062
+ body.append(email, msg, socialLoginBtn, proceedMagicLinkRequest);
1063
+ var modal = juxModal(getTranslation("using-".concat(mailExchanger.toLowerCase(), "-email")), [], '', false, false, body, '', '', function () { return result.remove(); });
1064
+ modal.setAttribute('data-cy', 'social-login-modal');
1065
+ result.appendChild(modal);
1066
+ var wrapper = modal.querySelector('modal-wrapper');
1067
+ wrapper.style.maxWidth = '360px';
1068
+ wrapper.style.width = '100%';
1069
+ return result;
1070
+ };
1071
+
1072
+ var isValidEmail = function (email) {
1073
+ var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
1074
+ return re.test(email);
1075
+ };
1076
+
1077
+ var recommendSocialLogin = function (userEmail, mailExchanger, token, onUserLogin, onReturn, backgroundImage, currentPage, clientBody, closeMagicLinkModal) {
1078
+ var _a;
1079
+ (_a = document.querySelector('magic-link-modal')) === null || _a === void 0 ? void 0 : _a.remove();
1080
+ document.body.appendChild(socialLoginModal(userEmail, mailExchanger, token, onUserLogin, onReturn, backgroundImage, currentPage, clientBody, closeMagicLinkModal));
1081
+ };
1082
+ var hasProvider = function (data, provider) {
1083
+ return data.some(function (entry) { return entry.includes(provider); });
1084
+ };
1085
+ var getMailExchanger = function (domainName) { return __awaiter(void 0, void 0, void 0, function () {
1086
+ var data;
1087
+ return __generator(this, function (_a) {
1088
+ switch (_a.label) {
1089
+ case 0: return [4 /*yield*/, getMXData(domainName)];
1090
+ case 1:
1091
+ data = _a.sent();
1092
+ if (!data) {
1093
+ return [2 /*return*/, null];
1094
+ }
1095
+ if (hasProvider(data, 'outlook.com')) {
1096
+ return [2 /*return*/, 'Microsoft'];
1097
+ }
1098
+ if (hasProvider(data, 'google.com')) {
1099
+ return [2 /*return*/, 'Google'];
1100
+ }
1101
+ return [2 /*return*/, null];
1102
+ }
1103
+ });
1104
+ }); };
1105
+ var onMagicLinkRequest = function (token, input, onUserLogin, onReturn, backgroundImage, currentPage, clientBody, closeMagicLinkModal, loginTypes) { return __awaiter(void 0, void 0, void 0, function () {
1106
+ var email, domain, mailExchanger, supportedMailExchanger;
1107
+ return __generator(this, function (_a) {
1108
+ switch (_a.label) {
1109
+ case 0:
1110
+ email = input.value;
1111
+ if (!email.includes('-test@') && !token) {
1112
+ console.error('invalid-captcha-response');
1113
+ // logError('invalid-captcha-response');
1114
+ return [2 /*return*/];
1115
+ }
1116
+ if (!isValidEmail(email)) return [3 /*break*/, 2];
1117
+ domain = email.split('@')[1] || '';
1118
+ return [4 /*yield*/, getMailExchanger(domain)];
1119
+ case 1:
1120
+ mailExchanger = _a.sent();
1121
+ supportedMailExchanger = mailExchanger !== null;
1122
+ if (supportedMailExchanger && loginTypes.includes(mailExchanger)) {
1123
+ recommendSocialLogin(email, mailExchanger, token, onUserLogin, onReturn, backgroundImage, currentPage, clientBody, closeMagicLinkModal);
1124
+ return [2 /*return*/];
1125
+ }
1126
+ _a.label = 2;
1127
+ case 2:
1128
+ handleMagicLinkRequest(token, onReturn, backgroundImage, currentPage, clientBody);
1129
+ closeMagicLinkModal();
1130
+ return [2 /*return*/];
1131
+ }
1132
+ });
1133
+ }); };
1134
+ var applyMagicEmailFieldStyle = function (el) {
1135
+ el.style.display = 'flex';
1136
+ el.style.flexFlow = 'column';
1137
+ el.style.marginTop = '8px';
1138
+ el.style.rowGap = '8px';
1139
+ el.style.width = '100%';
1140
+ };
1141
+ var applyInputStyle = function (input) {
1142
+ input.style.border = "1px solid ".concat(juxDarkGrey);
1143
+ input.style.maxWidth = '390px';
1144
+ input.style.padding = '10px';
1145
+ input.style.width = '100%';
1146
+ input.style.backgroundColor = juxWhite;
1147
+ input.style.borderRadius = '8px';
1148
+ input.style.boxShadow = "inset 0 2px 3px ".concat(juxDimmedDarkGrey);
1149
+ input.style.height = '40px';
1150
+ input.style.whiteSpace = 'pre-line';
1151
+ input.style.boxSizing = 'border-box';
1152
+ };
1153
+ var applyBtnStyle = function (btn) {
1154
+ btn.style.alignSelf = 'flex-end';
1155
+ btn.style.backgroundColor = juxLightGreen;
1156
+ btn.style.border = "2px solid ".concat(juxLightGreen);
1157
+ btn.style.borderRadius = '8px';
1158
+ btn.style.color = juxWhite;
1159
+ btn.style.cursor = 'pointer';
1160
+ btn.style.display = 'inline-block';
1161
+ btn.style.fontWeight = '700';
1162
+ btn.style.height = '40px';
1163
+ btn.style.lineHeight = '1';
1164
+ btn.style.marginLeft = '10px';
1165
+ btn.style.padding = '10px 16px';
1166
+ btn.style.position = 'relative';
1167
+ };
1168
+ var magicEmailField = function (onUserLogin, onReturn, backgroundImage, currentPage, clientBody, closeMagicLinkModal, loginTypes) {
1169
+ var result = document.createElement('magic-email-field');
1170
+ applyMagicEmailFieldStyle(result);
1171
+ var captcha = googleCaptcha();
1172
+ var input = document.createElement('input');
1173
+ input.id = 'mail-magic';
1174
+ input.type = 'text';
1175
+ input.className = 'textfield';
1176
+ input.placeholder = 'e-mail';
1177
+ applyInputStyle(input);
1178
+ input.addEventListener('keydown', function (ev) {
1179
+ if (ev.key === 'Enter') {
1180
+ onMagicLinkRequest(captcha.getAttribute('token'), input, onUserLogin, onReturn, backgroundImage, currentPage, clientBody, closeMagicLinkModal, loginTypes);
1181
+ }
1182
+ });
1183
+ var btn = document.createElement('button');
1184
+ applyBtnStyle(btn);
1185
+ btn.id = 'send-magic';
1186
+ btn.className = 'primary-button';
1187
+ btn.addEventListener('click', function (_ev) { return onMagicLinkRequest(captcha.getAttribute('token'), input, onUserLogin, onReturn, backgroundImage, currentPage, clientBody, closeMagicLinkModal, loginTypes); });
1188
+ btn.textContent = getTranslation('send-magic');
1189
+ result.append(input, captcha, btn);
1190
+ return result;
1191
+ };
1192
+
1193
+ var magicLinkModal = function (onUserLogin, onReturn, backgroundImage, currentPage, clientBody, loginTypes) {
1194
+ var result = document.createElement('magic-link-modal');
1195
+ var subtitle = document.createElement('magic-link-request-subtitle');
1196
+ subtitle.style.fontSize = '14px';
1197
+ subtitle.textContent = getTranslation('magic-link-request-subtitle');
1198
+ var body = document.createElement('magic-link-request-body');
1199
+ body.append(subtitle, magicEmailField(onUserLogin, onReturn, backgroundImage, currentPage, clientBody, function () { return result.remove(); }, loginTypes));
1200
+ var modal = juxModal(getTranslation('magic-link-request-title'), [], '', false, false, body, '', '', function () { return result.remove(); });
1201
+ modal.setAttribute('data-cy', 'magic-link-modal');
1202
+ result.appendChild(modal);
1203
+ var wrapper = modal.querySelector('modal-wrapper');
1204
+ wrapper.style.maxWidth = '360px';
1205
+ wrapper.style.width = '100%';
1206
+ return result;
1207
+ };
1208
+
1209
+ var applyContainerStyles = function (container) {
1210
+ container.style.backgroundColor = '#ffffffdd';
1211
+ container.style.borderRadius = '16px';
1212
+ container.style.inset = '50% 50% 50% 0';
1213
+ container.style.position = 'relative';
1214
+ container.style.transform = 'translateY(-50%)';
1215
+ container.style.width = '620px';
1216
+ container.style.alignItems = 'center';
1217
+ container.style.display = 'flex';
1218
+ container.style.flexDirection = 'column';
1219
+ container.style.fontSize = '16px';
1220
+ container.style.height = '100%';
1221
+ container.style.justifyContent = 'center';
1222
+ container.style.margin = '0 auto';
1223
+ container.style.paddingTop = '0';
1224
+ };
1225
+ var applyPageStyles = function (page) {
1226
+ page.style.backgroundPosition = '50%';
1227
+ page.style.backgroundSize = 'cover';
1228
+ page.style.display = 'block';
1229
+ page.style.height = '100%';
1230
+ };
1231
+ var onEmailLoginRequest = function (clientApp, loginPage, onUserLogin, backgroundImage, loginTypes) {
1232
+ var onReturn = function () { return clientApp.appendChild(loginPage); };
1233
+ loginPage.appendChild(magicLinkModal(onUserLogin, onReturn, backgroundImage, loginPage, clientApp, loginTypes));
1234
+ };
1235
+ var appendLoginTypes = function (loginPage, section, clientApp, onUserLogin, loginTypes, backgroundImg) {
1236
+ if (loginTypes.includes('Google')) {
1237
+ section.appendChild(loginButton('Google', function () { return onGoogleSignIn(onUserLogin); }));
1238
+ }
1239
+ if (loginTypes.includes('Microsoft')) {
1240
+ section.appendChild(loginButton('Microsoft', function () { return onMicrosoftSignIn(onUserLogin); }));
1241
+ }
1242
+ if (loginTypes.includes('Linkedin')) {
1243
+ section.appendChild(loginButton('LinkedIn', function () { return console.log('login with Linkedin'); }));
1244
+ }
1245
+ if (loginTypes.includes('Email')) {
1246
+ section.appendChild(loginButton('Email', function () { return onEmailLoginRequest(clientApp, loginPage, onUserLogin, backgroundImg, loginTypes); }));
1247
+ }
1248
+ };
1249
+ var loginPage = function (clientApp, backgroundImg, onUserLogin, loginTypes) {
1250
+ var result = document.createElement('login-page');
1251
+ applyPageStyles(result);
1252
+ var section = document.createElement('section');
1253
+ applyContainerStyles(section);
1254
+ var salutation = document.createElement('sign-in-salutation');
1255
+ salutation.textContent = getTranslation('sign-in-salutation');
1256
+ var explanation = document.createElement('sign-in-explanation');
1257
+ explanation.textContent = getTranslation('sign-in-explanation');
1258
+ var msg = document.createElement('sign-in-msg');
1259
+ msg.textContent = getTranslation('sign-in-msg-general');
1260
+ result.style.backgroundImage = "url(".concat(backgroundImg, ")");
1261
+ section.append(salutation, explanation, msg);
1262
+ appendLoginTypes(result, section, clientApp, onUserLogin, loginTypes, backgroundImg);
1263
+ result.appendChild(section);
1264
+ return result;
1265
+ };
1266
+
1267
+ exports.chosenLanguage = chosenLanguage;
1268
+ exports.getTranslation = getTranslation;
1269
+ exports.handleMagicLinkRequest = handleMagicLinkRequest;
1270
+ exports.initLanguage = initLanguage;
1271
+ exports.initSession = initSession;
1272
+ exports.loginButton = loginButton;
1273
+ exports.loginPage = loginPage;
1274
+ exports.magicLinkModal = magicLinkModal;
1275
+ exports.onMicrosoftSignIn = onMicrosoftSignIn;
1276
+ exports.reloadWithLanguageOverride = reloadWithLanguageOverride;
1277
+ exports.requestMagicLink = requestMagicLink;