@schibsted/account-sdk-browser 6.0.0-alpha.1 → 6.0.0-alpha.10

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 (82) hide show
  1. package/README.md +46 -279
  2. package/dist/account-sdk.d.ts +22 -0
  3. package/dist/account.d.ts +179 -0
  4. package/dist/cache.d.ts +65 -0
  5. package/dist/config.d.ts +86 -0
  6. package/dist/globals.d.ts +11 -0
  7. package/dist/has-access-response.d.ts +2 -0
  8. package/dist/identity.d.ts +302 -0
  9. package/dist/index.d.ts +11 -0
  10. package/dist/index.js +828 -0
  11. package/dist/index.js.map +1 -0
  12. package/dist/monetization.d.ts +39 -0
  13. package/{src → dist}/object.d.ts +4 -9
  14. package/dist/popup.d.ts +9 -0
  15. package/dist/resolve-browser-window.d.ts +1 -0
  16. package/dist/rest-client.d.ts +102 -0
  17. package/dist/rest-clients.d.ts +10 -0
  18. package/dist/sdk-error.d.ts +29 -0
  19. package/dist/session-response.d.ts +54 -0
  20. package/{src/spidTalk.d.ts → dist/spid-talk.d.ts} +4 -6
  21. package/dist/types/account.d.ts +48 -0
  22. package/dist/types/common.d.ts +28 -0
  23. package/dist/types/identity.d.ts +23 -0
  24. package/dist/types/login.d.ts +125 -0
  25. package/dist/types/monetization.d.ts +26 -0
  26. package/dist/types/session.d.ts +146 -0
  27. package/dist/url.d.ts +8 -0
  28. package/dist/validate.d.ts +50 -0
  29. package/dist/version.d.ts +2 -0
  30. package/package.json +30 -25
  31. package/src/account-sdk.ts +92 -0
  32. package/src/account.ts +332 -0
  33. package/src/{cache.js → cache.ts} +53 -38
  34. package/src/{config.js → config.ts} +7 -32
  35. package/src/globals.ts +8 -0
  36. package/src/has-access-response.ts +35 -0
  37. package/src/identity.ts +1023 -0
  38. package/src/index.ts +40 -0
  39. package/src/monetization.ts +128 -0
  40. package/src/{object.js → object.ts} +9 -16
  41. package/src/popup.ts +74 -0
  42. package/src/resolve-browser-window.ts +11 -0
  43. package/src/rest-client.ts +253 -0
  44. package/src/rest-clients.ts +30 -0
  45. package/src/sdk-error.ts +61 -0
  46. package/src/session-response.ts +100 -0
  47. package/src/{spidTalk.js → spid-talk.ts} +10 -12
  48. package/src/types/account.ts +55 -0
  49. package/src/types/common.ts +32 -0
  50. package/src/types/identity.ts +26 -0
  51. package/src/types/login.ts +150 -0
  52. package/src/types/monetization.ts +29 -0
  53. package/src/types/session.ts +169 -0
  54. package/src/{url.js → url.ts} +6 -10
  55. package/src/{validate.js → validate.ts} +27 -43
  56. package/src/{version.js → version.ts} +1 -2
  57. package/identity.d.ts +0 -1
  58. package/identity.js +0 -5
  59. package/index.d.ts +0 -4
  60. package/index.js +0 -9
  61. package/monetization.d.ts +0 -1
  62. package/monetization.js +0 -5
  63. package/payment.d.ts +0 -1
  64. package/payment.js +0 -5
  65. package/src/RESTClient.d.ts +0 -89
  66. package/src/RESTClient.js +0 -193
  67. package/src/SDKError.d.ts +0 -16
  68. package/src/SDKError.js +0 -55
  69. package/src/cache.d.ts +0 -64
  70. package/src/config.d.ts +0 -34
  71. package/src/global-registry.js +0 -20
  72. package/src/identity.d.ts +0 -679
  73. package/src/identity.js +0 -1154
  74. package/src/monetization.d.ts +0 -80
  75. package/src/monetization.js +0 -172
  76. package/src/payment.d.ts +0 -115
  77. package/src/payment.js +0 -211
  78. package/src/popup.d.ts +0 -10
  79. package/src/popup.js +0 -59
  80. package/src/url.d.ts +0 -10
  81. package/src/validate.d.ts +0 -64
  82. package/src/version.d.ts +0 -2
package/dist/index.js ADDED
@@ -0,0 +1,828 @@
1
+ //#region src/sdk-error.ts
2
+ var e = [
3
+ "boolean",
4
+ "number",
5
+ "string"
6
+ ], t = class extends Error {
7
+ code;
8
+ constructor(e, t) {
9
+ if (super(e), this.name = "SDKError", t) try {
10
+ Object.assign(this, t);
11
+ } catch {}
12
+ }
13
+ toString() {
14
+ let t = `${this.name}: ${this.message}`, n = Object.keys(this).filter((t) => t !== "name" && e.includes(typeof this[t])).map((e) => ` ${e}: ${this[e]}`).join("\n");
15
+ return n ? `${t}\n${n}` : t;
16
+ }
17
+ };
18
+ //#endregion
19
+ //#region src/cache.ts
20
+ function n(e) {
21
+ if (!e) return !1;
22
+ try {
23
+ let t = e(), n = "x-x-x-x".replace(/x/g, () => String(Math.random())), r = "TEST-VALUE";
24
+ t.setItem(n, r);
25
+ let i = t.getItem(n);
26
+ return t.removeItem(n), i === r;
27
+ } catch {
28
+ return !1;
29
+ }
30
+ }
31
+ var r = class {
32
+ store;
33
+ get;
34
+ set;
35
+ delete;
36
+ constructor(e) {
37
+ this.store = e, this.get = (e) => this.store.getItem(e), this.set = (e, t) => this.store.setItem(e, t), this.delete = (e) => this.store.removeItem(e);
38
+ }
39
+ }, i = class {
40
+ store;
41
+ get;
42
+ set;
43
+ delete;
44
+ constructor() {
45
+ this.store = {}, this.get = (e) => this.store[e], this.set = (e, t) => {
46
+ this.store[e] = t;
47
+ }, this.delete = (e) => {
48
+ delete this.store[e];
49
+ };
50
+ }
51
+ }, a = 2 ** 31 - 1, o = class {
52
+ cache;
53
+ type;
54
+ constructor(e) {
55
+ e && n(e) ? (this.cache = new r(e()), this.type = "WebStorage") : (this.cache = new i(), this.type = "ObjectLiteralStorage");
56
+ }
57
+ get(e) {
58
+ function n(e) {
59
+ if (e == null) return null;
60
+ try {
61
+ return JSON.parse(e);
62
+ } catch {
63
+ return null;
64
+ }
65
+ }
66
+ try {
67
+ let t = n(this.cache.get(e));
68
+ return t && Number.isInteger(t.expiresOn) && t.expiresOn > Date.now() ? t.value : (this.delete(e), null);
69
+ } catch (e) {
70
+ throw new t(String(e));
71
+ }
72
+ }
73
+ set(e, n, r = 0) {
74
+ if (!(r <= 0)) {
75
+ r = Math.min(a, r);
76
+ try {
77
+ let t = Math.floor(Date.now() + r);
78
+ this.cache.set(e, JSON.stringify({
79
+ expiresOn: t,
80
+ value: n
81
+ })), setTimeout(() => this.delete(e), r);
82
+ } catch (e) {
83
+ throw new t(String(e));
84
+ }
85
+ }
86
+ }
87
+ delete(e) {
88
+ try {
89
+ this.cache.delete(e);
90
+ } catch (e) {
91
+ throw new t(String(e));
92
+ }
93
+ }
94
+ }, s = {
95
+ ENDPOINTS: {
96
+ SPiD: {
97
+ LOCAL: "http://id.localhost",
98
+ DEV: "https://identity-dev.schibsted.com",
99
+ PRE: "https://identity-pre.schibsted.com",
100
+ PRO: "https://login.schibsted.com",
101
+ PRO_NO: "https://payment.schibsted.no",
102
+ PRO_FI: "https://login.schibsted.fi",
103
+ PRO_DK: "https://login.schibsted.dk"
104
+ },
105
+ BFF: {
106
+ LOCAL: "http://id.localhost/authn/",
107
+ DEV: "https://identity-dev.schibsted.com/authn/",
108
+ PRE: "https://identity-pre.schibsted.com/authn/",
109
+ PRO: "https://login.schibsted.com/authn/",
110
+ PRO_NO: "https://payment.schibsted.no/authn/",
111
+ PRO_FI: "https://login.schibsted.fi/authn/",
112
+ PRO_DK: "https://login.schibsted.dk/authn/"
113
+ },
114
+ SESSION_SERVICE: {
115
+ LOCAL: "http://session-service.id.localhost",
116
+ DEV: "https://session-service.identity-dev.schibsted.com",
117
+ PRE: "https://session-service.identity-pre.schibsted.com",
118
+ PRO: "https://session-service.login.schibsted.com",
119
+ PRO_NO: "https://session-service.payment.schibsted.no",
120
+ PRO_FI: "https://session-service.login.schibsted.fi",
121
+ PRO_DK: "https://session-service.login.schibsted.dk"
122
+ }
123
+ },
124
+ NAMESPACE: {
125
+ LOCAL: "id.localhost",
126
+ DEV: "schibsted.com",
127
+ PRE: "schibsted.com",
128
+ PRO: "schibsted.com",
129
+ PRO_NO: "spid.no",
130
+ PRO_FI: "schibsted.fi",
131
+ PRO_DK: "schibsted.dk"
132
+ }
133
+ }, c = s.ENDPOINTS, l = s.NAMESPACE;
134
+ //#endregion
135
+ //#region src/validate.ts
136
+ function u(e, n = "Assertion failed") {
137
+ if (!e) throw new t(n);
138
+ }
139
+ function d(e) {
140
+ return typeof e == "string";
141
+ }
142
+ function f(e) {
143
+ return typeof e == "string" && e.length > 0;
144
+ }
145
+ function p(e) {
146
+ return typeof e == "object" && !!e;
147
+ }
148
+ function m(e) {
149
+ return p(e) && Object.keys(e).length > 0;
150
+ }
151
+ function h(e, ...t) {
152
+ try {
153
+ let n = new URL(e);
154
+ return t.every((e) => n[e]);
155
+ } catch {
156
+ return !1;
157
+ }
158
+ }
159
+ function g(e) {
160
+ return typeof e == "function";
161
+ }
162
+ function _(e, t, n = !1) {
163
+ return d(e) && Array.isArray(t) ? n ? t.indexOf(e) !== -1 : t.some((t) => d(t) && e.toUpperCase() === t.toUpperCase()) : !1;
164
+ }
165
+ //#endregion
166
+ //#region src/object.ts
167
+ function v(...e) {
168
+ let n = {};
169
+ if (!(e && e.length)) throw new t("No objects to clone");
170
+ return e.forEach((e) => {
171
+ u(p(e)), m(e) && Object.entries(e).forEach(([e, t]) => {
172
+ t !== void 0 && (n[e] = p(t) ? y(t) : t);
173
+ });
174
+ }), n;
175
+ }
176
+ function y(e) {
177
+ return u(typeof e == "object", `obj should be an object (even null) but it is ${e}`), JSON.parse(JSON.stringify(e)) || e;
178
+ }
179
+ //#endregion
180
+ //#region src/popup.ts
181
+ function b(e) {
182
+ return u(p(e), `Object must be an object but it is '${e}'`), Object.keys(e).map((t) => `${t}=${e[t]}`).join(",");
183
+ }
184
+ var ee = {
185
+ scrollbars: "yes",
186
+ location: "yes",
187
+ status: "no",
188
+ menubar: "no",
189
+ toolbar: "no",
190
+ resizable: "yes"
191
+ };
192
+ function te(e, t, n = "", r = {}) {
193
+ u(p(e), `window was supposed to be an object but it is ${e}`), u(p(e.screen), "window should be a valid Window object but it lacks a 'screen' property"), u(g(e.open), "window should be a valid Window object but it lacks an 'open' function"), u(h(t), "Invalid URL for popup");
194
+ let { height: i, width: a } = e.screen, o = v(ee, r), { width: s, height: c } = o;
195
+ typeof s == "number" && Number.isFinite(s) && Number.isFinite(a) && (o.left = (a - s) / 2), typeof c == "number" && Number.isFinite(c) && Number.isFinite(i) && (o.top = (i - c) / 2);
196
+ let l = b(o);
197
+ return e.open(t, n, l);
198
+ }
199
+ //#endregion
200
+ //#region src/url.ts
201
+ function x(e, t) {
202
+ return u(f(e), `"url" param must be a non empty string: ${typeof e}`), m(t) && h(t[e]) ? t[e] : (u(h(e, "hostname"), `Bad URL given: '${e}'`), e);
203
+ }
204
+ //#endregion
205
+ //#region src/rest-client.ts
206
+ var ne = (e) => e.map((e) => p(e) ? JSON.stringify(e, null, 2) : e).join(" "), S = (e, ...t) => {
207
+ e && e(ne(t));
208
+ };
209
+ function C(e) {
210
+ let t = {
211
+ "!": "%21",
212
+ "'": "%27",
213
+ "(": "%28",
214
+ ")": "%29",
215
+ "~": "%7E",
216
+ "%20": "+",
217
+ "%00": "\0"
218
+ };
219
+ return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g, (e) => t[e]);
220
+ }
221
+ var re = () => window.fetch && window.fetch.bind(window), w = () => {
222
+ throw new t("fetch is not available in this environment");
223
+ }, T = class e {
224
+ url;
225
+ defaultParams;
226
+ log;
227
+ fetch;
228
+ constructor({ serverUrl: e = "PRE", envDic: t, fetch: n = re() ?? w, log: r, defaultParams: i = {} }) {
229
+ u(p(i), "defaultParams should be a non-null object");
230
+ let a = x(e, t ?? {}), o = a.endsWith("/") ? a : `${a}/`;
231
+ this.url = new URL(o), this.defaultParams = i, r && (u(g(r), `log must be a function but it is ${r}`), this.log = r), this.fetch = n;
232
+ }
233
+ async go(e) {
234
+ let { method: n, headers: r, pathname: i, data: a = {}, useDefaultParams: o = !0, fetchOptions: s = {
235
+ method: e.method,
236
+ credentials: "include"
237
+ }, parseResponse: c } = e;
238
+ u(f(n), `Method must be a non empty string but it is "${n}"`), u(f(i), `Pathname must be string but it is "${i}"`), u(p(a), "data must be a non-null object"), s.headers = p(r) ? r : {};
239
+ let l = this.makeUrl(i, a, o);
240
+ S(this.log, "Request:", n.toUpperCase(), l), S(this.log, "Request Headers:", s.headers), S(this.log, "Request Body:", s.body);
241
+ try {
242
+ let e = await this.fetch(l, s);
243
+ if (S(this.log, "Response Code:", e.status, e.statusText), !e.ok) throw new t(e.statusText, { code: e.status });
244
+ let n = await e.json();
245
+ return S(this.log, "Response Parsed:", n), c ? c(n) : n;
246
+ } catch (e) {
247
+ let r = d(e) ? e : "Unknown RESTClient error";
248
+ p(e) && d(e.message) && (r = e.message);
249
+ let i = p(e) ? e : void 0;
250
+ throw new t(`Failed to '${n}' '${l}': '${r}'`, i);
251
+ }
252
+ }
253
+ makeUrl(t = "", n = {}, r = !0) {
254
+ let i = t.startsWith("/") ? t.slice(1) : t, a = new URL(i, this.url);
255
+ return a.search = e.search(n, r, this.defaultParams), a.href;
256
+ }
257
+ get(e, t, n) {
258
+ return n ? this.go({
259
+ method: "GET",
260
+ pathname: e,
261
+ data: t,
262
+ parseResponse: n
263
+ }) : this.go({
264
+ method: "GET",
265
+ pathname: e,
266
+ data: t
267
+ });
268
+ }
269
+ static search(e, t, n) {
270
+ let r = t ? v(n, e) : v(e);
271
+ return Object.keys(r).filter((e) => r[e] !== "").map((e) => `${C(e)}=${C(String(r[e]))}`).join("&");
272
+ }
273
+ }, E = (e) => Object.hasOwn(l, e), D = (e, t) => (u(f(t), "clientId parameter is required"), u(E(e), `env parameter is invalid: ${e}`), `sdrn:${l[e]}:client:${t}`), O = ({ serverUrl: e, log: t, defaultParams: n }) => new T({
274
+ serverUrl: e,
275
+ log: t,
276
+ defaultParams: n
277
+ });
278
+ //#endregion
279
+ //#region src/session-response.ts
280
+ function k(e) {
281
+ return p(e) && typeof e.result == "boolean";
282
+ }
283
+ function A(e) {
284
+ return k(e) && e.result === !0;
285
+ }
286
+ function j(e) {
287
+ return p(e) && !!e.error;
288
+ }
289
+ function M(e) {
290
+ return p(e) && Object.keys(e).length === 1 && d(e.redirectURL);
291
+ }
292
+ function N(e) {
293
+ return A(e) && typeof e.userId == "number";
294
+ }
295
+ function P(e) {
296
+ return M(e) || j(e) || k(e) || p(e) ? e : {};
297
+ }
298
+ //#endregion
299
+ //#region src/spid-talk.ts
300
+ function F(e) {
301
+ (!e.SPiD || typeof e.SPiD != "object") && (e.SPiD = {}), (!e.SPiD.Talk || typeof e.SPiD.Talk != "object") && (e.SPiD.Talk = {}), g(e.SPiD.Talk.response) || (e.SPiD.Talk.response = (t, n) => e[t](n));
302
+ }
303
+ //#endregion
304
+ //#region src/types/login.ts
305
+ var I = (e) => typeof e.openSimplifiedLoginWidget == "function", L = "6.0.0-alpha.10", R = "hasSession-cache", z = "sessionCallBlocked-cache", B = 1e3 * 60 * 5, V = "tab-id-cache", H = Math.floor(Math.random() * 1e5), U = 1e3 * 60 * 60 * 24 * 30, W = () => window, G = class {
306
+ eventTarget = new EventTarget();
307
+ window;
308
+ clientId;
309
+ redirectUri;
310
+ env;
311
+ log;
312
+ callbackBeforeRedirect;
313
+ sessionStorageCache;
314
+ localStorageCache;
315
+ enableSessionCaching;
316
+ spid;
317
+ oauthService;
318
+ bffService;
319
+ sessionService;
320
+ globalSessionService;
321
+ usedSessionServiceGetSessionEndpoint;
322
+ session;
323
+ hasSessionInProgress;
324
+ popup;
325
+ setVarnishCookie;
326
+ varnishExpiresIn;
327
+ varnishCookieDomain;
328
+ constructor({ clientId: e, redirectUri: t, sessionDomain: n, env: r = "PRE", log: i, window: a = W(), callbackBeforeRedirect: s = () => {} }) {
329
+ u(f(e), "clientId parameter is required"), u(p(a), "The reference to window is missing"), u(!t || h(t), "redirectUri parameter is invalid"), u(f(n) && h(n), "sessionDomain parameter is not a valid URL"), u(d(r), `env parameter is invalid: ${r}`), F(a), this.window = a, this.clientId = e, this.redirectUri = t, this.env = r, this.log = i, this.callbackBeforeRedirect = s, this.sessionStorageCache = new o(() => this.window && this.window.sessionStorage), this.localStorageCache = new o(() => this.window && this.window.localStorage), this.enableSessionCaching = !0, this.session = {};
330
+ let l = {
331
+ client_id: this.clientId,
332
+ redirect_uri: this.redirectUri
333
+ }, m = D(this.env, this.clientId);
334
+ this.spid = O({
335
+ serverUrl: x(r, c.SPiD),
336
+ log: this.log,
337
+ defaultParams: l
338
+ }), this.oauthService = O({
339
+ serverUrl: x(r, c.SPiD),
340
+ log: this.log,
341
+ defaultParams: l
342
+ }), this.bffService = O({
343
+ serverUrl: x(r, c.BFF),
344
+ log: this.log,
345
+ defaultParams: l
346
+ }), this.sessionService = O({
347
+ serverUrl: n,
348
+ log: this.log,
349
+ defaultParams: {
350
+ client_sdrn: m,
351
+ redirect_uri: this.redirectUri,
352
+ sdk_version: L
353
+ }
354
+ }), this.globalSessionService = O({
355
+ serverUrl: x(r, c.SESSION_SERVICE),
356
+ log: this.log,
357
+ defaultParams: {
358
+ client_sdrn: m,
359
+ sdk_version: L
360
+ }
361
+ }), this.usedSessionServiceGetSessionEndpoint = this.sessionService.url.pathname && this.sessionService.url.pathname.length <= 1 ? "v2/session" : "session", this._unblockSessionCall();
362
+ }
363
+ addEventListener(e, t) {
364
+ this.eventTarget.addEventListener(e, t);
365
+ }
366
+ removeEventListener(e, t) {
367
+ this.eventTarget.removeEventListener(e, t);
368
+ }
369
+ _getTabId() {
370
+ if (this.enableSessionCaching) {
371
+ let e = this.sessionStorageCache.get(V);
372
+ return typeof e == "number" ? e : (this.sessionStorageCache.set(V, H, U), H);
373
+ }
374
+ }
375
+ _isSessionCallBlocked() {
376
+ return !!this.localStorageCache.get(z);
377
+ }
378
+ _blockSessionCall() {
379
+ this.localStorageCache.set(z, !0, B);
380
+ }
381
+ _unblockSessionCall() {
382
+ this.localStorageCache.delete(z);
383
+ }
384
+ _closePopup() {
385
+ this.popup &&= (this.popup.closed || this.popup.close(), null);
386
+ }
387
+ enableVarnishCookie(e) {
388
+ if (typeof e != "object") throw new t("VarnishCookieOptions must be an object");
389
+ let { expiresIn: n = 0, domain: r } = e;
390
+ u(Number.isInteger(n), "'expiresIn' must be an integer"), u(n >= 0, "'expiresIn' cannot be negative"), this.setVarnishCookie = !0, this.varnishExpiresIn = n, this.varnishCookieDomain = r;
391
+ }
392
+ _maybeSetVarnishCookie(e) {
393
+ if (!this.setVarnishCookie || !k(e)) return;
394
+ let t = /* @__PURE__ */ new Date();
395
+ if (this.varnishExpiresIn || typeof e.expiresIn == "number" && e.expiresIn > 0) {
396
+ let n = this.varnishExpiresIn || e.expiresIn || 0;
397
+ t.setTime(t.getTime() + n * 1e3);
398
+ } else t.setTime(0);
399
+ let n = this.varnishCookieDomain || (typeof e.baseDomain == "string" ? e.baseDomain : this.window.location.hostname) || "", r = [
400
+ `SP_ID=${e.sp_id}`,
401
+ `expires=${t.toUTCString()}`,
402
+ "path=/",
403
+ `domain=.${n}`
404
+ ].join("; ");
405
+ document.cookie = r;
406
+ }
407
+ _maybeClearVarnishCookie() {
408
+ this.setVarnishCookie && this._clearVarnishCookie();
409
+ }
410
+ _clearVarnishCookie() {
411
+ let e = this.session && k(this.session) && typeof this.session.baseDomain == "string" ? this.session.baseDomain : this.window.location.hostname, t = this.varnishCookieDomain || e || "";
412
+ document.cookie = `SP_ID=nothing; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; domain=.${t}`;
413
+ }
414
+ hasSession() {
415
+ if (this._isSessionCallBlocked()) {
416
+ let e = P(this.session);
417
+ return Promise.resolve(M(e) ? {} : e);
418
+ }
419
+ if (this.hasSessionInProgress) return this.hasSessionInProgress;
420
+ let e = !1, n = (n) => {
421
+ if (j(n)) throw new t("HasSession failed", p(n.error) ? n.error : { description: String(n.error) });
422
+ return this._maybeSetVarnishCookie(n), e = (k(this.session) && this.session.id) !== (k(n) && n.id), this.session = n, n;
423
+ }, r = () => {
424
+ let e = this.sessionStorageCache.get(R);
425
+ return e ? P(e) : null;
426
+ }, i = async () => {
427
+ if (this.enableSessionCaching) {
428
+ let e = r();
429
+ if (e) return M(e) ? {} : n(e);
430
+ }
431
+ let e = null;
432
+ try {
433
+ e = await this.sessionService.get(this.usedSessionServiceGetSessionEndpoint, { tabId: this._getTabId() }, P);
434
+ } catch (e) {
435
+ let t = p(e) ? e : void 0;
436
+ if (t?.code === 400 && this.enableSessionCaching) {
437
+ let n = 1e3 * (typeof t.expiresIn == "number" ? t.expiresIn : 300);
438
+ this.sessionStorageCache.set(R, { error: e }, n);
439
+ } else t && typeof t.code == "number" && t.code >= 500 && t.code < 600 && this.enableSessionCaching && this.sessionStorageCache.set(R, { error: e }, 30 * 1e3);
440
+ throw e;
441
+ }
442
+ if (e) {
443
+ if (M(e)) return this._blockSessionCall(), await this.callbackBeforeRedirect(), this.sessionService.makeUrl(e.redirectURL, { tabId: this._getTabId() });
444
+ if (this.enableSessionCaching) {
445
+ let t = 1e3 * (k(e) && e.expiresIn || 300);
446
+ this.sessionStorageCache.set(R, e, t);
447
+ }
448
+ }
449
+ return n(e ?? {});
450
+ };
451
+ return this.hasSessionInProgress = i().then((t) => (e && typeof t != "string" && this.eventTarget.dispatchEvent(new CustomEvent("sessionUpdated", { detail: t })), this.hasSessionInProgress = !1, typeof t == "string" && (this.window.location.href = t), t), (e) => {
452
+ throw this.hasSessionInProgress = !1, new t("HasSession failed", e);
453
+ }), this.hasSessionInProgress;
454
+ }
455
+ async isLoggedIn() {
456
+ try {
457
+ return k(await this.hasSession());
458
+ } catch {
459
+ return !1;
460
+ }
461
+ }
462
+ setSessionCachingEnabled(e) {
463
+ this.enableSessionCaching = e;
464
+ }
465
+ clearCachedUserSession() {
466
+ this.sessionStorageCache.delete(R);
467
+ }
468
+ async isConnected() {
469
+ try {
470
+ return A(await this.hasSession());
471
+ } catch {
472
+ return !1;
473
+ }
474
+ }
475
+ async getUser() {
476
+ let e = await this.hasSession();
477
+ if (!A(e)) throw new t("The user is not connected to this merchant");
478
+ return y(e);
479
+ }
480
+ async getUserId() {
481
+ let e = await this.hasSession();
482
+ if (N(e)) return e.userId;
483
+ throw new t("The user is not connected to this merchant");
484
+ }
485
+ async getExternalId(e, n = "") {
486
+ let r = await this.hasSession(), i = k(r) ? r.pairId : void 0;
487
+ if (!i) throw new t("pairId missing in user session!");
488
+ if (!e || e.length === 0) throw new t("externalParty cannot be empty");
489
+ let a = (e) => Array.from(new Uint8Array(e)).map((e) => e.toString(16).padStart(2, "0")).join(""), o = (e) => crypto.subtle.digest("SHA-256", e);
490
+ return (async (e) => o(new TextEncoder().encode(e)).then((e) => a(e)))(((e, t, n) => n ? `${e}:${t}:${n}` : `${e}:${t}`)(i, e, n));
491
+ }
492
+ async getUserSDRN() {
493
+ let e = await this.hasSession();
494
+ if (k(e) && e.sdrn) return e.sdrn;
495
+ throw new t("Failed to get SDRN from user session");
496
+ }
497
+ async getUserUuid() {
498
+ let e = await this.hasSession();
499
+ if (k(e) && e.uuid && e.result) return e.uuid;
500
+ throw new t("The user is not connected to this merchant");
501
+ }
502
+ async getUserContextData() {
503
+ try {
504
+ return await this.globalSessionService.get("user-context", void 0, (e) => p(e) && d(e.identifier) ? {
505
+ identifier: e.identifier,
506
+ display_text: d(e.display_text) ? e.display_text : "",
507
+ client_name: d(e.client_name) ? e.client_name : "",
508
+ provider_id: d(e.provider_id) ? e.provider_id : void 0
509
+ } : null);
510
+ } catch {
511
+ return null;
512
+ }
513
+ }
514
+ login({ state: e, acrValues: t, scope: n = "openid", redirectUri: r = this.redirectUri, preferPopup: i = !1, loginHint: a = "", tag: o = "", teaser: s = "", maxAge: c = "", locale: l, oneStepLogin: u = !1, prompt: d = "select_account", xDomainId: f = "", xEnvironmentId: p = "", originCampaign: m = "" }) {
515
+ this._closePopup(), this.sessionStorageCache.delete(R);
516
+ let h = this.loginUrl({
517
+ state: e,
518
+ acrValues: t,
519
+ scope: n,
520
+ redirectUri: r,
521
+ loginHint: a,
522
+ tag: o,
523
+ teaser: s,
524
+ maxAge: c,
525
+ locale: l,
526
+ oneStepLogin: u,
527
+ prompt: d,
528
+ xDomainId: f,
529
+ xEnvironmentId: p,
530
+ originCampaign: m
531
+ });
532
+ return i && (this.popup = te(this.window, h, "Schibsted account", {
533
+ width: 360,
534
+ height: 570
535
+ }), this.popup) ? (this.eventTarget.dispatchEvent(new CustomEvent("loginRequested", { detail: {
536
+ url: h,
537
+ method: "popup"
538
+ } })), this.popup) : (this.eventTarget.dispatchEvent(new CustomEvent("loginRequested", { detail: {
539
+ url: h,
540
+ method: "default"
541
+ } })), this.window.location.href = h, null);
542
+ }
543
+ async getSpId() {
544
+ try {
545
+ let e = await this.hasSession();
546
+ if (k(e)) return e.sp_id || null;
547
+ let t = p(e) && "sp_id" in e ? e.sp_id : void 0;
548
+ return d(t) ? t : null;
549
+ } catch {
550
+ return null;
551
+ }
552
+ }
553
+ logout(e = this.redirectUri) {
554
+ this.sessionStorageCache.delete(R), this._maybeClearVarnishCookie();
555
+ let t = this.logoutUrl(e);
556
+ this.eventTarget.dispatchEvent(new CustomEvent("logoutRequested", { detail: { url: t } })), this.window.location.href = t;
557
+ }
558
+ loginUrl({ state: e, acrValues: t = "", scope: n = "openid", redirectUri: r = this.redirectUri, loginHint: i = "", tag: a = "", teaser: o = "", maxAge: s = "", locale: c, oneStepLogin: l = !1, prompt: d = "select_account", xDomainId: p = "", xEnvironmentId: m = "", originCampaign: g = "" }) {
559
+ return u(!t || _(t, ["", "otp-email"], !0) || t.split(" ").every((e) => _(e, [
560
+ "password",
561
+ "otp",
562
+ "sms",
563
+ "eid-dk",
564
+ "eid-no",
565
+ "eid-se",
566
+ "eid-fi",
567
+ "eid"
568
+ ], !0)), `The acrValues parameter is not acceptable: ${t}`), u(h(r), `loginUrl(): redirectUri must be a valid url but is ${r}`), u(f(e), `the state parameter should be a non empty string but it is ${e}`), this.oauthService.makeUrl("oauth/authorize", {
569
+ response_type: "code",
570
+ redirect_uri: r,
571
+ scope: n,
572
+ state: e,
573
+ acr_values: t,
574
+ login_hint: i,
575
+ tag: a,
576
+ teaser: o,
577
+ max_age: s,
578
+ locale: c,
579
+ one_step_login: l || "",
580
+ prompt: t ? "" : d,
581
+ x_domain_id: p,
582
+ x_env_id: m,
583
+ utm_campaign: g
584
+ });
585
+ }
586
+ logoutUrl(e = this.redirectUri) {
587
+ u(h(e), "logoutUrl(): redirectUri is invalid");
588
+ let t = { redirect_uri: e };
589
+ return this.sessionService.makeUrl("logout", t);
590
+ }
591
+ accountUrl(e = this.redirectUri) {
592
+ return this.spid.makeUrl("profile-pages", {
593
+ response_type: "code",
594
+ redirect_uri: e
595
+ });
596
+ }
597
+ async showSimplifiedLoginWidget(e, n) {
598
+ let r = await this.getUserContextData(), i = { client_id: this.clientId };
599
+ n && n.encoding && (i.encoding = n.encoding);
600
+ let a = this.bffService.makeUrl("simplified-login-widget", i, !1), o = async (e) => {
601
+ let t = typeof e.state == "function" ? await e.state() : e.state;
602
+ return {
603
+ ...e,
604
+ state: t
605
+ };
606
+ };
607
+ return new Promise((i, s) => {
608
+ if (!r?.display_text || !r.identifier) {
609
+ s(new t("Missing user data"));
610
+ return;
611
+ }
612
+ let c = {
613
+ displayText: r.display_text,
614
+ env: this.env,
615
+ clientName: r.client_name || "",
616
+ clientId: this.clientId,
617
+ providerId: r.provider_id,
618
+ windowWidth: () => window.innerWidth,
619
+ windowOnResize: (e) => {
620
+ window.onresize = e;
621
+ }
622
+ };
623
+ n && n.locale && (c.locale = n.locale);
624
+ let l = async () => {
625
+ this.login(Object.assign(await o(e), { loginHint: r.identifier }));
626
+ }, u = async () => {
627
+ this.login(Object.assign(await o(e), {
628
+ loginHint: r.identifier,
629
+ prompt: "login"
630
+ }));
631
+ }, d = () => {
632
+ this.eventTarget.dispatchEvent(new Event("simplifiedLoginOpened"));
633
+ }, f = () => {
634
+ this.eventTarget.dispatchEvent(new Event("simplifiedLoginCancelled"));
635
+ };
636
+ if (I(window)) return window.openSimplifiedLoginWidget(c, l, u, d, f), i(!0);
637
+ let p = document.createElement("script");
638
+ p.type = "text/javascript", p.src = a, p.onload = () => {
639
+ if (!I(window)) {
640
+ s(new t("Error when loading simplified login widget content"));
641
+ return;
642
+ }
643
+ window.openSimplifiedLoginWidget(c, l, u, d, f), i(!0);
644
+ }, p.onerror = () => {
645
+ s(new t("Error when loading simplified login widget content"));
646
+ }, document.getElementsByTagName("body")[0].appendChild(p);
647
+ });
648
+ }
649
+ };
650
+ //#endregion
651
+ //#region src/has-access-response.ts
652
+ function K(e) {
653
+ if (!p(e)) throw new t("Invalid hasAccess response");
654
+ let { entitled: n, ttl: r, allowedFeatures: i, userId: a, uuid: o, sig: s } = e;
655
+ if (typeof n != "boolean" || typeof r != "number" || !Array.isArray(i) || typeof a != "number" || !d(o) || !d(s)) throw new t("Invalid hasAccess response");
656
+ return {
657
+ entitled: n,
658
+ ttl: r,
659
+ allowedFeatures: i.filter(d),
660
+ userId: a,
661
+ uuid: o,
662
+ sig: s
663
+ };
664
+ }
665
+ //#endregion
666
+ //#region src/monetization.ts
667
+ var q = () => window, J = class {
668
+ cache;
669
+ sessionService;
670
+ pendingHasAccessRequests;
671
+ constructor({ clientId: e, redirectUri: t, env: n = "PRE", sessionDomain: r, window: i = q() }) {
672
+ F(i), u(f(e), "clientId parameter is required"), u(d(n), `env parameter is invalid: ${n}`);
673
+ let a = D(n, e);
674
+ this.cache = new o(() => i && i.sessionStorage), this.pendingHasAccessRequests = {}, r && (u(h(r), "sessionDomain parameter is not a valid URL"), this.sessionService = O({
675
+ serverUrl: r,
676
+ defaultParams: {
677
+ client_sdrn: a,
678
+ redirect_uri: t,
679
+ sdk_version: L
680
+ }
681
+ }));
682
+ }
683
+ async hasAccess(e, n) {
684
+ if (!this.sessionService) throw new t("hasAccess can only be called if 'sessionDomain' is configured");
685
+ if (!n) throw new t("'userId' must be specified");
686
+ if (!Array.isArray(e)) throw new t("'productIds' must be an array");
687
+ let r = [...e].sort(), i = this.accessCacheKey(r, n), a = this.cache.get(i);
688
+ if (!a) {
689
+ this.pendingHasAccessRequests[i] || (this.pendingHasAccessRequests[i] = this.sessionService.get(`/hasAccess/${r.join(",")}`, void 0, K));
690
+ let e = this.pendingHasAccessRequests[i];
691
+ try {
692
+ a = await e;
693
+ let t = a.ttl;
694
+ this.cache.set(i, a, t * 1e3);
695
+ } finally {
696
+ this.pendingHasAccessRequests[i] === e && delete this.pendingHasAccessRequests[i];
697
+ }
698
+ }
699
+ return a.entitled ? a : null;
700
+ }
701
+ clearCachedAccessResult(e, t) {
702
+ this.cache.delete(this.accessCacheKey(e, t));
703
+ }
704
+ accessCacheKey(e, t) {
705
+ return `prd_${[...e].sort()}_${t}`;
706
+ }
707
+ }, Y = (e) => e || (typeof window > "u" ? void 0 : window), X = class {
708
+ #e;
709
+ #t;
710
+ #n;
711
+ constructor(e) {
712
+ let n = Y(e.window);
713
+ if (!n) throw new t("Schibsted Account SDK is not available in this browser context");
714
+ if (n.schAccount) throw new t("Schibsted Account SDK has already been initialized");
715
+ let { log: r, callbackBeforeRedirect: i, defaultProductIds: a, varnish: o } = e, s = {
716
+ clientId: e.clientId,
717
+ redirectUri: e.redirectUri,
718
+ sessionDomain: e.sessionDomain,
719
+ env: e.env,
720
+ window: n
721
+ };
722
+ if (this.#e = new G({
723
+ ...s,
724
+ log: r,
725
+ callbackBeforeRedirect: i
726
+ }), a !== void 0 && !Array.isArray(a)) throw new t("Account defaultProductIds config must be an array");
727
+ if (this.#n = a, o) {
728
+ if (typeof o != "object" || Array.isArray(o)) throw new t("Account varnish config must be an object");
729
+ this.#e.enableVarnishCookie(o);
730
+ }
731
+ this.#t = new J(s), n.schAccount = this, n.dispatchEvent(new CustomEvent("schAccount:ready", { detail: { instance: this } }));
732
+ }
733
+ hasSession() {
734
+ return this.#e.hasSession();
735
+ }
736
+ isLoggedIn() {
737
+ return this.#e.isLoggedIn();
738
+ }
739
+ isConnected() {
740
+ return this.#e.isConnected();
741
+ }
742
+ getUser() {
743
+ return this.#e.getUser();
744
+ }
745
+ getUserId() {
746
+ return this.#e.getUserId();
747
+ }
748
+ getExternalId(e, t = "") {
749
+ return this.#e.getExternalId(e, t);
750
+ }
751
+ getUserUuid() {
752
+ return this.#e.getUserUuid();
753
+ }
754
+ getUserSDRN() {
755
+ return this.#e.getUserSDRN();
756
+ }
757
+ getUserContextData() {
758
+ return this.#e.getUserContextData();
759
+ }
760
+ getSpId() {
761
+ return this.#e.getSpId();
762
+ }
763
+ login(e) {
764
+ return this.#e.login(e);
765
+ }
766
+ logout(e) {
767
+ this.#e.logout(e);
768
+ }
769
+ loginUrl(e) {
770
+ return this.#e.loginUrl(e);
771
+ }
772
+ logoutUrl(e) {
773
+ return this.#e.logoutUrl(e);
774
+ }
775
+ accountUrl(e) {
776
+ return this.#e.accountUrl(e);
777
+ }
778
+ showSimplifiedLoginWidget(e, t) {
779
+ return this.#e.showSimplifiedLoginWidget(e, t);
780
+ }
781
+ setSessionCachingEnabled(e) {
782
+ this.#e.setSessionCachingEnabled(e);
783
+ }
784
+ clearCachedUserSession() {
785
+ this.#e.clearCachedUserSession();
786
+ }
787
+ async hasAccess(e = this.#n) {
788
+ if (!e) throw new t("hasAccess requires productIds or defaultProductIds in the Account config");
789
+ if (e.length === 0) return null;
790
+ let n = await this.#e.getUserId();
791
+ return this.#t.hasAccess(e, n);
792
+ }
793
+ clearCachedAccessResult(e, t) {
794
+ this.#t.clearCachedAccessResult(e, t);
795
+ }
796
+ on(e, t) {
797
+ return this.#e.addEventListener(e, t), this;
798
+ }
799
+ off(e, t) {
800
+ return this.#e.removeEventListener(e, t), this;
801
+ }
802
+ }, Z = "schAccount:ready", Q = 4e3, $, ie = () => /* @__PURE__ */ Error("Schibsted Account SDK is not available in this browser context"), ae = () => /* @__PURE__ */ Error(`Schibsted Account SDK was not initialized within ${Q} ms`);
803
+ function oe(e) {
804
+ return new X(e);
805
+ }
806
+ function se() {
807
+ let e = Y();
808
+ if (!e) {
809
+ let e = ie();
810
+ return console.error(e.message), Promise.reject(e);
811
+ }
812
+ return e.schAccount ? Promise.resolve(e.schAccount) : $ || ($ = new Promise((t, n) => {
813
+ let r, i = () => {
814
+ e.removeEventListener(Z, a), r !== void 0 && e.clearTimeout(r), $ = void 0;
815
+ }, a = () => {
816
+ let n = e.schAccount;
817
+ n && (i(), t(n));
818
+ };
819
+ e.addEventListener(Z, a), r = e.setTimeout(() => {
820
+ let e = ae();
821
+ console.error(e.message), i(), n(e);
822
+ }, Q), a();
823
+ }), $);
824
+ }
825
+ //#endregion
826
+ export { X as Account, t as SDKError, oe as createAccountSdk, se as getAccountSdk, A as isConnectedSessionResponse, N as isConnectedSessionWithUserIdResponse, j as isSessionFailureResponse, k as isSessionSuccessResponse };
827
+
828
+ //# sourceMappingURL=index.js.map