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

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 (89) hide show
  1. package/README.md +39 -64
  2. package/dist/account-sdk.d.ts +4 -0
  3. package/dist/account.d.ts +29 -0
  4. package/dist/cache.d.ts +65 -0
  5. package/dist/config.d.ts +86 -0
  6. package/dist/get-account-sdk.d.ts +3 -0
  7. package/dist/global-registry.d.ts +23 -0
  8. package/dist/globals.d.ts +15 -0
  9. package/dist/has-access-response.d.ts +2 -0
  10. package/dist/identity.d.ts +323 -0
  11. package/dist/index.d.ts +8 -0
  12. package/dist/index.js +859 -0
  13. package/dist/index.js.map +1 -0
  14. package/dist/monetization.d.ts +58 -0
  15. package/{src → dist}/object.d.ts +4 -9
  16. package/dist/popup.d.ts +9 -0
  17. package/dist/resolve-browser-window.d.ts +1 -0
  18. package/dist/rest-client.d.ts +102 -0
  19. package/dist/rest-clients.d.ts +10 -0
  20. package/dist/sdk-error.d.ts +27 -0
  21. package/dist/session-response.d.ts +30 -0
  22. package/{src/spidTalk.d.ts → dist/spid-talk.d.ts} +4 -6
  23. package/dist/types/account.d.ts +13 -0
  24. package/dist/types/common.d.ts +22 -0
  25. package/dist/types/identity.d.ts +41 -0
  26. package/dist/types/login.d.ts +120 -0
  27. package/dist/types/monetization-guards.d.ts +2 -0
  28. package/dist/types/monetization.d.ts +21 -0
  29. package/dist/types/session-guards.d.ts +36 -0
  30. package/dist/types/session.d.ts +124 -0
  31. package/dist/url.d.ts +8 -0
  32. package/dist/validate.d.ts +50 -0
  33. package/dist/version.d.ts +2 -0
  34. package/package.json +30 -22
  35. package/src/account-sdk.ts +74 -0
  36. package/src/account.ts +149 -0
  37. package/src/{cache.js → cache.ts} +53 -38
  38. package/src/{config.js → config.ts} +7 -32
  39. package/src/get-account-sdk.ts +94 -0
  40. package/src/global-registry.ts +39 -0
  41. package/src/globals.ts +12 -0
  42. package/src/has-access-response.ts +35 -0
  43. package/src/identity.ts +1102 -0
  44. package/src/index.ts +32 -0
  45. package/src/{monetization.js → monetization.ts} +65 -73
  46. package/src/{object.js → object.ts} +9 -16
  47. package/src/popup.ts +74 -0
  48. package/src/resolve-browser-window.ts +11 -0
  49. package/src/rest-client.ts +253 -0
  50. package/src/rest-clients.ts +30 -0
  51. package/src/sdk-error.ts +59 -0
  52. package/src/session-response.ts +85 -0
  53. package/src/{spidTalk.js → spid-talk.ts} +10 -12
  54. package/src/types/account.ts +27 -0
  55. package/src/types/common.ts +26 -0
  56. package/src/types/identity.ts +55 -0
  57. package/src/types/login.ts +145 -0
  58. package/src/types/monetization-guards.ts +35 -0
  59. package/src/types/monetization.ts +24 -0
  60. package/src/types/session-guards.ts +89 -0
  61. package/src/types/session.ts +147 -0
  62. package/src/{url.js → url.ts} +6 -10
  63. package/src/{validate.js → validate.ts} +27 -43
  64. package/src/{version.js → version.ts} +1 -2
  65. package/identity.d.ts +0 -1
  66. package/identity.js +0 -5
  67. package/index.d.ts +0 -4
  68. package/index.js +0 -9
  69. package/monetization.d.ts +0 -1
  70. package/monetization.js +0 -5
  71. package/payment.d.ts +0 -1
  72. package/payment.js +0 -5
  73. package/src/RESTClient.d.ts +0 -89
  74. package/src/RESTClient.js +0 -193
  75. package/src/SDKError.d.ts +0 -16
  76. package/src/SDKError.js +0 -55
  77. package/src/cache.d.ts +0 -64
  78. package/src/config.d.ts +0 -34
  79. package/src/global-registry.js +0 -20
  80. package/src/identity.d.ts +0 -679
  81. package/src/identity.js +0 -1154
  82. package/src/monetization.d.ts +0 -80
  83. package/src/payment.d.ts +0 -115
  84. package/src/payment.js +0 -211
  85. package/src/popup.d.ts +0 -10
  86. package/src/popup.js +0 -59
  87. package/src/url.d.ts +0 -10
  88. package/src/validate.d.ts +0 -64
  89. package/src/version.d.ts +0 -2
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Log callback used by the SDK for debug output.
3
+ * Receives a pre-formatted log line.
4
+ * @internal
5
+ */
6
+ export type LogFunction = (message: string) => void;
7
+ /**
8
+ * Supported Schibsted account environment keys.
9
+ */
10
+ export type AccountEnvironment = 'LOCAL' | 'DEV' | 'PRE' | 'PRO' | 'PRO_NO' | 'PRO_FI' | 'PRO_DK';
11
+ export type AccountBaseConfig = {
12
+ /** Mandatory client id. Example: "1234567890abcdef12345678" */
13
+ clientId: string;
14
+ /** Redirect uri. Example: "https://site.com" */
15
+ redirectUri: string;
16
+ /** Session Service domain. Example: "https://id.site.com" */
17
+ sessionDomain: string;
18
+ /** Schibsted account environment. Defaults to PRE. */
19
+ env?: AccountEnvironment;
20
+ /** Window object to use. Defaults to the global `window`. */
21
+ window?: Window;
22
+ };
@@ -0,0 +1,41 @@
1
+ import { AccountBaseConfig, LogFunction } from './common';
2
+ /**
3
+ * Callback invoked before the SDK performs a full-page session refresh redirect.
4
+ */
5
+ export type IdentityBeforeRedirectCallback = () => void | Promise<void>;
6
+ /**
7
+ * Options accepted by the {@link Identity} constructor.
8
+ */
9
+ export type IdentityOptions = AccountBaseConfig & {
10
+ /** Receives debug log information. If not set, no logging will be done. */
11
+ log?: LogFunction;
12
+ /** Callback triggered before a session refresh redirect happens. */
13
+ callbackBeforeRedirect?: IdentityBeforeRedirectCallback;
14
+ };
15
+ /**
16
+ * Identity events emitted by the SDK.
17
+ *
18
+ * - `login`: emitted when `hasSession()` resolves with a logged-in user payload.
19
+ * - `logout`: emitted when a previously logged-in user is no longer logged in, or when
20
+ * `logout()` is called.
21
+ * - `userChange`: emitted when the current session user id changes.
22
+ * - `sessionChange`: emitted when either the previous or current `hasSession()` payload contains
23
+ * a logged-in user.
24
+ * - `notLoggedin`: emitted when neither the previous nor current `hasSession()` payload contains
25
+ * a logged-in user.
26
+ * - `sessionInit`: emitted once for the first logged-in session payload.
27
+ * - `statusChange`: emitted when the session `userStatus` changes.
28
+ * - `error`: emitted when `hasSession()` fails.
29
+ * - `simplifiedLoginOpened`: emitted when the simplified login widget is displayed.
30
+ * - `simplifiedLoginCancelled`: emitted when the simplified login widget is closed.
31
+ */
32
+ export type IdentityEventName = 'login' | 'logout' | 'userChange' | 'sessionChange' | 'notLoggedin' | 'sessionInit' | 'statusChange' | 'error' | 'simplifiedLoginOpened' | 'simplifiedLoginCancelled';
33
+ /**
34
+ * Options for {@link Identity#enableVarnishCookie}.
35
+ */
36
+ export type VarnishCookieOptions = {
37
+ /** Override number of seconds before the Varnish cookie expires. */
38
+ expiresIn?: number;
39
+ /** Override cookie domain. E.g. "vg.no" instead of "www.vg.no". */
40
+ domain?: string;
41
+ };
@@ -0,0 +1,120 @@
1
+ /**
2
+ * Options accepted by {@link Identity#login} and related login URL helpers.
3
+ */
4
+ export type LoginOptions = {
5
+ /**
6
+ * An opaque value used by the client to maintain state between the request and callback.
7
+ * It's also recommended to prevent CSRF {@link https://tools.ietf.org/html/rfc6749#section-10.12}
8
+ */
9
+ state: string;
10
+ /**
11
+ * Authentication Context Class Reference Values. If omitted, the user will be asked to
12
+ * authenticate using username+password. For 2FA (Two-Factor Authentication) possible values
13
+ * are `sms`, `otp` (one time password), `password` (will force password confirmation, even if
14
+ * user is already logged in), `eid`. Those values might be mixed as space-separated string.
15
+ * To make sure that user has authenticated with 2FA you need to verify AMR (Authentication
16
+ * Methods References) claim in ID token. Might also be used to ensure additional acr
17
+ * (sms, otp, eid) for already logged in users. Supported value is also 'otp-email' means one
18
+ * time password using email.
19
+ */
20
+ acrValues?: 'password' | 'otp' | 'sms' | 'eid-dk' | 'eid-no' | 'eid-se' | 'eid-fi' | 'eid' | 'otp-email' | (string & {});
21
+ /**
22
+ * The OAuth scopes for the tokens. This is a list of scopes, separated by space. If the list
23
+ * of scopes contains `openid`, the generated tokens includes the id token which can be useful
24
+ * for getting information about the user. Omitting scope is allowed, while `invalid_scope` is
25
+ * returned when the client asks for a scope you aren't allowed to request.
26
+ * {@link https://tools.ietf.org/html/rfc6749#section-3.3}
27
+ * Defaults to `openid`.
28
+ */
29
+ scope?: 'openid' | (string & {});
30
+ /**
31
+ * Redirect uri that will receive the code. Must exactly match a redirectUri from your client
32
+ * in self-service
33
+ */
34
+ redirectUri?: string;
35
+ /** Should we try to open a popup window? Defaults to `false`. */
36
+ preferPopup?: boolean;
37
+ /** user email or UUID hint */
38
+ loginHint?: string;
39
+ /** Pulse tag */
40
+ tag?: string;
41
+ /** Teaser slug. Teaser with given slug will be displayed in place of default teaser */
42
+ teaser?: string;
43
+ /**
44
+ * Specifies the allowable elapsed time in seconds since the last time the End-User was actively
45
+ * authenticated. If last authentication time is more than maxAge seconds in the past,
46
+ * re-authentication will be required. See the OpenID Connect spec section 3.1.2.1 for more
47
+ * information. Prefer a number of seconds; strings remain accepted for legacy callers.
48
+ */
49
+ maxAge?: number | string;
50
+ /**
51
+ * Optional parameter to overwrite client locale setting.
52
+ * New flows supports nb_NO, fi_FI, sv_SE, en_US
53
+ */
54
+ locale?: 'nb_NO' | 'fi_FI' | 'sv_SE' | 'en_US';
55
+ /** display username and password on one screen. Defaults to `false`. */
56
+ oneStepLogin?: boolean;
57
+ /**
58
+ * String that specifies whether the Authorization Server prompts the End-User for
59
+ * reauthentication or confirm account screen. Supported values: `select_account` or `login`.
60
+ * Defaults to `select_account`.
61
+ */
62
+ prompt?: 'select_account' | 'login';
63
+ /** Identifier for cross-domain tracking in Pulse */
64
+ xDomainId?: string;
65
+ /** Environment for cross-domain tracking in Pulse */
66
+ xEnvironmentId?: string;
67
+ /** Campaign identifier for tracking in Pulse */
68
+ originCampaign?: string;
69
+ };
70
+ /**
71
+ * Identical to {@link LoginOptions} except that `state` may also be a (possibly async) function;
72
+ * all other fields reuse the `LoginOptions` documentation.
73
+ */
74
+ export type SimplifiedLoginWidgetLoginOptions = Omit<LoginOptions, 'state'> & {
75
+ /**
76
+ * An opaque value used by the client to maintain state between the request and callback.
77
+ * It's also recommended to prevent CSRF {@link https://tools.ietf.org/html/rfc6749#section-10.12}
78
+ */
79
+ state: string | (() => string | Promise<string>);
80
+ };
81
+ /**
82
+ * Minimal user information used by the simplified login widget flow.
83
+ */
84
+ export type SimplifiedLoginData = {
85
+ /** Deprecated: User UUID, to be be used as `loginHint` for {@link Identity#login} */
86
+ identifier: string;
87
+ /** Human-readable user identifier */
88
+ display_text: string;
89
+ /** Client name */
90
+ client_name: string;
91
+ /** Provider id used by the simplified login widget when supplied by the backend. */
92
+ provider_id?: string;
93
+ };
94
+ /**
95
+ * Configuration options for {@link Identity#showSimplifiedLoginWidget}.
96
+ */
97
+ export type SimplifiedLoginWidgetOptions = {
98
+ /** expected encoding of simplified login widget. Could be utf-8 (default), iso-8859-1 or iso-8859-15 */
99
+ encoding?: string;
100
+ /**
101
+ * expected locale of simplified login widget. Should be provided in a short format like 'nb',
102
+ * 'sv'. If not set, a value from the env variable is used.
103
+ */
104
+ locale?: 'nb' | 'sv' | 'fi' | 'da' | 'en';
105
+ };
106
+ export type SimplifiedLoginWidgetInitialParams = {
107
+ displayText: string;
108
+ env: string;
109
+ clientName: string;
110
+ clientId: string;
111
+ providerId?: string;
112
+ locale?: SimplifiedLoginWidgetOptions['locale'];
113
+ windowWidth: () => number;
114
+ windowOnResize: (handler: () => void) => void;
115
+ };
116
+ export type SimplifiedLoginWidgetHandler = () => void | Promise<void>;
117
+ export type OpenSimplifiedLoginWidget = (initialParams: SimplifiedLoginWidgetInitialParams, loginHandler: SimplifiedLoginWidgetHandler, loginNotYouHandler: SimplifiedLoginWidgetHandler, initHandler: SimplifiedLoginWidgetHandler, cancelLoginHandler: SimplifiedLoginWidgetHandler) => unknown;
118
+ export declare const hasOpenSimplifiedLoginWidget: (targetWindow: Window) => targetWindow is Window & {
119
+ openSimplifiedLoginWidget: OpenSimplifiedLoginWidget;
120
+ };
@@ -0,0 +1,2 @@
1
+ import { HasAccessResult } from './monetization.js';
2
+ export declare function parseHasAccessResult(value: unknown): HasAccessResult;
@@ -0,0 +1,21 @@
1
+ import { AccountBaseConfig } from './common';
2
+ import { SessionUserId } from './session';
3
+ /**
4
+ * Result returned by the Session Service `/hasAccess` endpoint, describing whether the user
5
+ * is entitled to a requested set of products/features.
6
+ * @internal
7
+ */
8
+ export interface HasAccessResult {
9
+ /** Whether the user is entitled to at least one of the requested products/features. */
10
+ entitled: boolean;
11
+ /** How long this result stays valid, in seconds, before the cache entry expires. */
12
+ ttl: number;
13
+ allowedFeatures: string[];
14
+ userId: SessionUserId;
15
+ uuid: string;
16
+ sig: string;
17
+ }
18
+ /**
19
+ * Options accepted by the {@link Monetization} constructor.
20
+ */
21
+ export type MonetizationOptions = Pick<AccountBaseConfig, 'clientId' | 'env' | 'window'> & Partial<Pick<AccountBaseConfig, 'redirectUri' | 'sessionDomain'>>;
@@ -0,0 +1,36 @@
1
+ import { ConnectedSessionResponse, ConnectedSessionWithUserIdResponse, SessionFailureResponse, SessionResponse, SessionSuccessResponse, UnrecognizedSessionResponse } from './session.js';
2
+ type SessionObjectResponse = SessionSuccessResponse | SessionFailureResponse | UnrecognizedSessionResponse;
3
+ type RedirectSessionPayload = {
4
+ redirectURL: string;
5
+ };
6
+ export type NormalizedSessionPayload = SessionObjectResponse | RedirectSessionPayload;
7
+ export declare function isSessionSuccessResponse(value: unknown): value is SessionSuccessResponse;
8
+ export declare function isConnectedSessionResponse(value: unknown): value is ConnectedSessionResponse;
9
+ export declare function isSessionFailureResponse(value: unknown): value is SessionFailureResponse;
10
+ export declare function isRedirectSessionPayload(value: unknown): value is RedirectSessionPayload;
11
+ export declare function isConnectedSessionWithUserIdResponse(value: SessionResponse): value is ConnectedSessionWithUserIdResponse;
12
+ /**
13
+ * Converts an unknown Session Service `hasSession` payload into one of the shapes the SDK knows how
14
+ * to handle.
15
+ *
16
+ * This function is intentionally tolerant because `hasSession()` historically resolved unknown
17
+ * object payloads instead of rejecting them. The SDK relies on that behavior for backwards
18
+ * compatibility with clients that check the raw response themselves.
19
+ *
20
+ * The normal cases are:
21
+ * - regular success payloads with a boolean `result`;
22
+ * - failure payloads wrapped as `{ error, response? }`;
23
+ * - Safari/session-refresh redirect payloads shaped as `{ redirectURL }`.
24
+ *
25
+ * Any other object is preserved as an unrecognized response so callers can still receive it.
26
+ * Non-object values are normalized to `{}`, matching the old "empty response" fallback used by
27
+ * `hasSession()` and cached-session reads.
28
+ *
29
+ * This is used both for network responses parsed by `RESTClient` and for values restored from the
30
+ * session cache, so the rest of the Identity flow can switch on typed guards instead of repeatedly
31
+ * re-validating unknown data.
32
+ *
33
+ * @internal
34
+ */
35
+ export declare function normalizeSessionResponse(value: unknown): NormalizedSessionPayload;
36
+ export {};
@@ -0,0 +1,124 @@
1
+ /**
2
+ * User identifier returned by Session Service responses.
3
+ *
4
+ * Session Service historically returned numeric ids, while some integrations and tests use
5
+ * string ids. SDK convenience methods normalize this where they promise a string.
6
+ */
7
+ export type SessionUserId = number | string;
8
+ /**
9
+ * Successful response returned from {@link Identity#hasSession}.
10
+ *
11
+ * `result` means the has-session call itself succeeded. `result: true` means the user is
12
+ * connected to the merchant; `result: false` means a session may exist, but the user is not
13
+ * connected to this client.
14
+ */
15
+ export type SessionSuccessResponse = {
16
+ /** Response status code. Example: 200. */
17
+ code: number;
18
+ /** Response type. Example: 'OK'. */
19
+ type: string;
20
+ /** Human-readable response description. Example: 'OK'. */
21
+ description: string;
22
+ /**
23
+ * Is the user connected to the merchant? This means the merchant id is in the list of
24
+ * merchants connected to this user.
25
+ */
26
+ result: boolean;
27
+ /** Connection status string. Deprecated; use `Identity.isConnected()`. Example: 'connected'. */
28
+ userStatus?: string;
29
+ /** Cookie base domain used as the `SP_ID` cookie domain fallback. Example: 'spid.no'. */
30
+ baseDomain?: string;
31
+ /** Legacy session id. Obsolete. Example: '58eca10fdbb9f6df72c3368f'. */
32
+ id?: string;
33
+ /** A numeric user id which is unique per realm (country). Example: 37162 */
34
+ userId?: SessionUserId;
35
+ /** Globally unique user id. Example: 'b3b23aa7-34f2-5d02-a10e-5a3455c6ab2c' */
36
+ uuid?: string;
37
+ /** Session token used for the `SP_ID` cookie. Example: 'eyJjbGllbnRfaWQ...'. */
38
+ sp_id?: string;
39
+ /** Session response TTL in seconds. Example: 300. */
40
+ expiresIn?: number;
41
+ /** Server time as a Unix timestamp in seconds. Example: 1506285759. */
42
+ serverTime?: number;
43
+ /**
44
+ * Example: 'NCdzXaz4ZRb7...' The sig parameter is a concatenation of an HMAC SHA-256
45
+ * signature string, a dot (.) and a base64url encoded JSON object (session).
46
+ * {@link http://techdocs.spid.no/sdks/js/response-signature-and-validation/}
47
+ */
48
+ sig?: string;
49
+ /** User display name. Example: 'batman'. */
50
+ displayName?: string;
51
+ /** User given name. Example: 'Bruce'. */
52
+ givenName?: string;
53
+ /** User family name. Example: 'Wayne'. */
54
+ familyName?: string;
55
+ /** User gender value. Example: 'male', 'female', 'undisclosed'. */
56
+ gender?: string;
57
+ /** User profile photo URL. Example: 'http://www.srv.com/some/picture.jpg' . */
58
+ photo?: string;
59
+ /** Whether tracking is enabled for this session. Example: true. */
60
+ tracking?: boolean;
61
+ /** Whether the client agreement is accepted. Example: true. */
62
+ clientAgreementAccepted?: boolean;
63
+ /** Whether the default agreement is accepted. Example: true. */
64
+ defaultAgreementAccepted?: boolean;
65
+ /** Pairwise user id for this client. Example: 'b2a23caa...'. */
66
+ pairId?: string;
67
+ /** User SDRN. Example: 'sdrn:spid.no:user:12345'. */
68
+ sdrn?: string;
69
+ };
70
+ /**
71
+ * Successful has-session response for a user connected to the merchant.
72
+ */
73
+ export type ConnectedSessionResponse = SessionSuccessResponse & {
74
+ result: true;
75
+ };
76
+ /**
77
+ * Connected session response that also carries a usable user id.
78
+ */
79
+ export type ConnectedSessionWithUserIdResponse = ConnectedSessionResponse & {
80
+ userId: SessionUserId;
81
+ };
82
+ /**
83
+ * Failure payload returned by Session Service.
84
+ *
85
+ * API and network failures usually reject with {@link SDKError}; this shape represents a failure
86
+ * payload when one is returned by Session Service and reaches the has-session flow.
87
+ */
88
+ export type SessionFailureResponse = {
89
+ /** Failure payload returned by Session Service. Usually an object, but tests also pass strings. */
90
+ error: string | number | boolean | object;
91
+ response?: {
92
+ /** Response status code. Example: 404. */
93
+ code: number;
94
+ /** Response type. Example: 'NOT_FOUND'. */
95
+ type: string;
96
+ /** Human-readable response description. Example: 'No session found'. */
97
+ description: string;
98
+ /** Cookie base domain used as the `SP_ID` cookie domain fallback. Example: 'spid.no'. */
99
+ baseDomain?: string;
100
+ /** Time span in milliseconds. Example: 30 * 60 * 1000 (for 30 minutes) */
101
+ expiresIn?: number;
102
+ result?: boolean;
103
+ /** Server time in seconds since the Unix Epoch. Example: 1506287788 */
104
+ serverTime?: number;
105
+ [key: string]: string | number | boolean | object | null | undefined;
106
+ };
107
+ };
108
+ /**
109
+ * Object response that does not match one of the SDK-known has-session shapes.
110
+ *
111
+ * This intentionally includes `{}`. Historically `hasSession()` could resolve an empty object or
112
+ * other object payloads that callers inspected themselves, so the SDK preserves those responses.
113
+ */
114
+ export type UnrecognizedSessionResponse = object;
115
+ export type RedirectSessionResponse = string;
116
+ export type SessionObjectResponse = SessionSuccessResponse | SessionFailureResponse | UnrecognizedSessionResponse;
117
+ export type RedirectSessionPayload = {
118
+ redirectURL: string;
119
+ };
120
+ export type NormalizedSessionPayload = SessionObjectResponse | RedirectSessionPayload;
121
+ /**
122
+ * Public response union returned from {@link Identity#hasSession}.
123
+ */
124
+ export type SessionResponse = SessionSuccessResponse | SessionFailureResponse | UnrecognizedSessionResponse | RedirectSessionResponse;
package/dist/url.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ /**
2
+ * A simple utility function that allows looking up URLs from a dictionary
3
+ * @param url - A url like http://example.com, or a key used for lookup
4
+ * @param urlMap - A map of URLs like `{ DEV: 'http://dev.example.com' }`
5
+ * @returns The resolved URL: the mapped value when `url` is a known key, otherwise `url` itself
6
+ * @throws {SDKError} - If the url is not a string or is an empty string
7
+ */
8
+ export declare function urlMapper(url: string, urlMap: Record<string, string>): string;
@@ -0,0 +1,50 @@
1
+ /**
2
+ * A utility function that throws an SDKError if an assertion fails. It's mostly useful for
3
+ * validating function inputs.
4
+ *
5
+ * Narrows `condition` for the rest of the enclosing scope (TypeScript assertion signature).
6
+ * @param condition - The condition that we're asserting
7
+ * @param message - The error message
8
+ * @throws {SDKError} - If the condition is falsy it throws the appropriate error
9
+ */
10
+ export declare function assert(condition: boolean, message?: string): asserts condition;
11
+ /**
12
+ * Checks if a value is a string or not
13
+ * @param value - The value to check
14
+ */
15
+ export declare function isStr(value: unknown): value is string;
16
+ /**
17
+ * Checks if a value is a non-empty string
18
+ * @param value - The value to check
19
+ */
20
+ export declare function isNonEmptyString(value: unknown): value is string;
21
+ /**
22
+ * checks if a given value is an object (but not null)
23
+ * @param value - The value to check
24
+ */
25
+ export declare function isObject(value: unknown): value is Record<string, unknown>;
26
+ /**
27
+ * Checks if a given value is an object with at least one own key
28
+ * @param value - The value to check
29
+ */
30
+ export declare function isNonEmptyObj(value: unknown): value is Record<string, unknown>;
31
+ /**
32
+ * Checks if a given string is a valid URL
33
+ * @param value - The string to be tested
34
+ * @param mandatoryFields - A list of mandatory fields that should exist in the parsed
35
+ * `URL` object
36
+ */
37
+ export declare function isUrl(value: string, ...mandatoryFields: (keyof URL)[]): boolean;
38
+ /**
39
+ * Checks if a given value is a function
40
+ * @param value - The value to check
41
+ */
42
+ export declare function isFunction(value: unknown): value is (...args: unknown[]) => unknown;
43
+ /**
44
+ * Checks if a string matches any of the strings in a set of possibilities
45
+ * @param value
46
+ * @param possibilities - An array of strings that'll be used to check the string
47
+ * inclusion. Note that for performance reasons, we don't validate this parameter.
48
+ * @param caseSensitive - Should the check be case sensitive
49
+ */
50
+ export declare function isStrIn(value: string, possibilities: string[], caseSensitive?: boolean): boolean;
@@ -0,0 +1,2 @@
1
+ declare const version = "6.0.0-alpha.3";
2
+ export default version;
package/package.json CHANGED
@@ -1,23 +1,30 @@
1
1
  {
2
2
  "name": "@schibsted/account-sdk-browser",
3
- "version": "6.0.0-alpha.1",
3
+ "version": "6.0.0-alpha.3",
4
4
  "description": "Schibsted account SDK for browsers",
5
- "main": "index.js",
5
+ "main": "dist/index.js",
6
6
  "type": "module",
7
7
  "exports": {
8
- ".": "./index.js",
9
- "./identity": "./identity.js",
10
- "./monetization": "./monetization.js",
11
- "./payment": "./payment.js"
8
+ ".": {
9
+ "default": "./dist/index.js",
10
+ "types": "./dist/index.d.ts"
11
+ }
12
12
  },
13
13
  "scripts": {
14
- "clean": "rimraf .cache coverage docs && npm run clean:legacy",
14
+ "clean": "rimraf .cache coverage docs dist && npm run clean:legacy",
15
15
  "clean:legacy": "rimraf es5",
16
- "docs": "rimraf docs && jsdoc -c ./jsdoc.conf.json --verbose",
17
- "lint": "eslint .",
18
- "lint:fix": "eslint . --fix",
16
+ "docs:build": "typedoc",
17
+ "docs:watch": "typedoc --watch",
18
+ "docs:open": "node scripts/open-docs.mjs",
19
+ "lint": "biome check",
20
+ "lint:fix": "biome check --fix",
21
+ "build": "vite build",
22
+ "typecheck": "tsc --noEmit",
23
+ "pretest": "npm run build",
19
24
  "test": "vitest run",
20
- "cover": "vitest run --coverage"
25
+ "precover": "npm run build",
26
+ "cover": "vitest run --coverage",
27
+ "prepublishOnly": "npm run build"
21
28
  },
22
29
  "author": "",
23
30
  "license": "MIT",
@@ -25,19 +32,20 @@
25
32
  "tiny-emitter": "^2.1.0"
26
33
  },
27
34
  "devDependencies": {
28
- "@vitest/coverage-v8": "^2.1.9",
29
- "docdash": "git+https://github.com/torarvid/docdash.git#v0.5.0",
30
- "eslint": "^6.8.0",
31
- "eslint-plugin-import": "^2.20.2",
32
- "jsdoc": "^3.6.11",
33
- "jsdom": "^25.0.1",
34
- "node-fetch": "^2.6.0",
35
- "vitest": "^2.1.9",
36
- "whatwg-url": "^8.0.0"
35
+ "@biomejs/biome": "2.4.15",
36
+ "@vitest/coverage-v8": "^4.1.7",
37
+ "jsdom": "^29.1.1",
38
+ "open": "^11.0.0",
39
+ "rimraf": "^6.1.3",
40
+ "typedoc": "^0.28.19",
41
+ "typedoc-plugin-mdn-links": "^5.1.1",
42
+ "typescript": "^6.0.3",
43
+ "unplugin-dts": "^1.0.1",
44
+ "vite": "^8.0.14",
45
+ "vitest": "^4.1.7"
37
46
  },
38
47
  "repository": {
39
48
  "type": "git",
40
49
  "url": "git://schibsted.ghe.com/user-identity/account-sdk-browser.git"
41
- },
42
- "typings": "index.d.ts"
50
+ }
43
51
  }
@@ -0,0 +1,74 @@
1
+ /* Copyright 2026 Schibsted Products & Technology AS. Licensed under the terms of the MIT license.
2
+ * See LICENSE.md in the project root.
3
+ */
4
+
5
+ import { Account } from './account.js';
6
+ import { resolveBrowserWindow } from './resolve-browser-window.js';
7
+ import type { AccountConfig } from './types/account.js';
8
+
9
+ const ACCOUNT_READY_EVENT = 'schAccount:ready';
10
+ const GET_ACCOUNT_SDK_TIMEOUT_MS = 4000;
11
+
12
+ let pendingAccountPromise: Promise<Account> | undefined;
13
+
14
+ const createUnavailableError = (): Error =>
15
+ new Error('Schibsted Account SDK is not available in this browser context');
16
+
17
+ const createTimeoutError = (): Error =>
18
+ new Error(`Schibsted Account SDK was not initialized within ${GET_ACCOUNT_SDK_TIMEOUT_MS} ms`);
19
+
20
+ export function createAccountSdk(config: AccountConfig): Account {
21
+ return new Account(config);
22
+ }
23
+
24
+ export function getAccountSdk(): Promise<Account> {
25
+ const browserWindow = resolveBrowserWindow();
26
+
27
+ if (!browserWindow) {
28
+ const error = createUnavailableError();
29
+ console.error(error.message);
30
+ return Promise.reject(error);
31
+ }
32
+
33
+ if (browserWindow.schAccount) {
34
+ return Promise.resolve(browserWindow.schAccount);
35
+ }
36
+
37
+ if (pendingAccountPromise) {
38
+ return pendingAccountPromise;
39
+ }
40
+
41
+ pendingAccountPromise = new Promise<Account>((resolve, reject) => {
42
+ let timeoutId: number | undefined;
43
+
44
+ const cleanup = () => {
45
+ browserWindow.removeEventListener(ACCOUNT_READY_EVENT, resolveRegisteredAccount);
46
+ if (timeoutId !== undefined) {
47
+ browserWindow.clearTimeout(timeoutId);
48
+ }
49
+ pendingAccountPromise = undefined;
50
+ };
51
+
52
+ const resolveRegisteredAccount = () => {
53
+ const account = browserWindow.schAccount;
54
+ if (!account) {
55
+ return;
56
+ }
57
+
58
+ cleanup();
59
+ resolve(account);
60
+ };
61
+
62
+ browserWindow.addEventListener(ACCOUNT_READY_EVENT, resolveRegisteredAccount);
63
+ timeoutId = browserWindow.setTimeout(() => {
64
+ const error = createTimeoutError();
65
+ console.error(error.message);
66
+ cleanup();
67
+ reject(error);
68
+ }, GET_ACCOUNT_SDK_TIMEOUT_MS);
69
+
70
+ resolveRegisteredAccount();
71
+ });
72
+
73
+ return pendingAccountPromise;
74
+ }