@saasquatch/component-environment 1.0.0-1 → 1.0.0-2

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/CHANGELOG.md ADDED
@@ -0,0 +1,13 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [1.0.0] - 2022-06-16
9
+
10
+ Initial version.
11
+
12
+ [unreleased]: https://github.com/saasquatch/program-tools/compare/component-environment@1.0.0...HEAD
13
+ [1.0.0]: https://github.com/saasquatch/program-tools/releases/tag/%40saasquatch%2Fcomponent-environment%401.0.0
package/README.md ADDED
@@ -0,0 +1 @@
1
+ Provides the environment for running SaaSquatch web components.
package/dist/index.d.ts CHANGED
@@ -1,5 +1,226 @@
1
- export * from "./types";
2
- export * from "./environment";
3
- export * from "./contexts/UserIdentityContext";
4
- export * from "./contexts/LocaleContext";
5
- export * from "./contexts/ProgramContext";
1
+ import { ContextProvider } from 'dom-context';
2
+
3
+ declare global {
4
+ interface Window {
5
+ SquatchPortal?: PortalEnv;
6
+ widgetIdent?: WidgetIdent;
7
+ squatchUserIdentity?: ContextProvider<UserIdentity | undefined>;
8
+ squatchLocale?: ContextProvider<string | undefined>;
9
+ squatchProgramId?: ContextProvider<string | undefined>;
10
+ }
11
+ }
12
+ declare type UserContextName = "sq:user-identity";
13
+ declare type LocaleContextName = "sq:locale";
14
+ declare type ProgramContextName = "sq:program-id";
15
+ declare const USER_CONTEXT_NAME: UserContextName;
16
+ declare const LOCALE_CONTEXT_NAME: LocaleContextName;
17
+ declare const PROGRAM_CONTEXT_NAME: ProgramContextName;
18
+ /**
19
+ * The value stored in the UserContext
20
+ */
21
+ declare type UserIdentity = {
22
+ id: string;
23
+ accountId: string;
24
+ jwt?: string;
25
+ managedIdentity?: {
26
+ email: string;
27
+ emailVerified: boolean;
28
+ sessionData?: {
29
+ [key: string]: any;
30
+ };
31
+ };
32
+ };
33
+ declare type UserId = {
34
+ id: string;
35
+ accountId: string;
36
+ };
37
+ interface DecodedSquatchJWT {
38
+ exp?: number;
39
+ user: {
40
+ accountId: string;
41
+ id: string;
42
+ };
43
+ }
44
+ interface DecodedWidgetAPIJWT {
45
+ exp?: number;
46
+ sub: string;
47
+ }
48
+ declare type EngagementMedium = "EMBED" | "POPUP";
49
+ declare const DEFAULT_MEDIUM: EngagementMedium;
50
+ /**
51
+ * Provided by the SaaSquatch GraphQL backend when a widget is rendered.
52
+ *
53
+ * Source: https://github.com/saasquatch/saasquatch/blob/805e51284f818f8656b6458bcee6181f378819d3/packages/saasquatch-core/app/saasquatch/controllers/api/widget/WidgetApi.java
54
+ *
55
+ */
56
+ interface WidgetIdent {
57
+ tenantAlias: string;
58
+ appDomain: string;
59
+ token: string;
60
+ userId: string;
61
+ accountId: string;
62
+ locale?: string;
63
+ engagementMedium?: "POPUP" | "EMBED";
64
+ programId?: string;
65
+ env?: string;
66
+ }
67
+ /**
68
+ * Portal env doesn't include User Id
69
+ */
70
+ declare type PortalEnv = Pick<WidgetIdent, "tenantAlias" | "appDomain" | "programId">;
71
+ /**
72
+ * An interface for interacting with the SaaSquatch Admin Portal.
73
+ *
74
+ * Used for rendering widgets in a preview/demo mode.
75
+ */
76
+ interface SquatchAdmin {
77
+ /**
78
+ * Provides a way of providing user feedback when a widget is rendered in the SaaSquatch admin portal
79
+ *
80
+ * @param text
81
+ */
82
+ showMessage(text: string): void;
83
+ }
84
+ /**
85
+ * Type for the Javascript environment added by https://github.com/saasquatch/squatch-android
86
+ *
87
+ * Should exist as `window.SquatchAndroid`
88
+ */
89
+ interface SquatchAndroid {
90
+ /**
91
+ *
92
+ * @param shareLink
93
+ * @param messageLink fallback URL to redirect to if the app is not installed
94
+ */
95
+ shareOnFacebook(shareLink: string, messageLink: string): void;
96
+ /**
97
+ * Shows a native Android toast
98
+ *
99
+ * @param text
100
+ */
101
+ showToast(text: string): void;
102
+ }
103
+ /**
104
+ * An interface provided by Squatch.js V2 for widgets.
105
+ *
106
+ * See: https://github.com/saasquatch/squatch-js/blob/8f2b218c9d55567e0cc12d27d635a5fb545e6842/src/widgets/Widget.ts#L47
107
+ *
108
+ */
109
+ interface SquatchJS2 {
110
+ /**
111
+ * Opens the current popup widget (if loaded as a popup)
112
+ */
113
+ open?: () => void;
114
+ /**
115
+ * Closes the current popup widget (if loaded as a popup)
116
+ */
117
+ close?: () => void;
118
+ /**
119
+ * DEPRECATED used to update user details from inside the widget.
120
+ *
121
+ * Should no longer be used. Replace with natively using the GraphQL API and re-rendering locally. Will be removed in a future version of Squatch.js
122
+ *
123
+ * @deprecated
124
+ */
125
+ reload(userDetails: {
126
+ email: string;
127
+ firstName: string;
128
+ lastName: string;
129
+ }, jwt: string): void;
130
+ }
131
+ declare type Environment = EnvironmentSDK["type"];
132
+ declare type EnvironmentSDK = {
133
+ type: "SquatchJS2";
134
+ api: SquatchJS2;
135
+ widgetIdent: WidgetIdent;
136
+ } | {
137
+ type: "SquatchAndroid";
138
+ android: SquatchAndroid;
139
+ widgetIdent: WidgetIdent;
140
+ } | {
141
+ type: "SquatchPortal";
142
+ env: PortalEnv;
143
+ } | {
144
+ type: "SquatchAdmin";
145
+ adminSDK: SquatchAdmin;
146
+ } | {
147
+ type: "None";
148
+ };
149
+
150
+ /**
151
+ * Get the type of environment that this widget is being rendered in
152
+ *
153
+ * Should never return null.
154
+ */
155
+ declare function getEnvironment(): Environment;
156
+ /**
157
+ * Get the SDK for interacting with the host environment
158
+ */
159
+ declare function getEnvironmentSDK(): EnvironmentSDK;
160
+ declare function isDemo(): boolean;
161
+ declare function getTenantAlias(): string;
162
+ declare function getAppDomain(): string;
163
+ declare function getEngagementMedium(): EngagementMedium;
164
+
165
+ /**
166
+ * Lazily start the user context provider. If it already exists, the existing provider is
167
+ * returned. This function is safe to call multiple times.
168
+ *
169
+ * @returns The global user context provider
170
+ */
171
+ declare function lazilyStartUserContext(): ContextProvider<UserIdentity | undefined>;
172
+ /**
173
+ * Extract a user identity from a JWT
174
+ *
175
+ * @param jwt The JWT to extract a user identity from
176
+ * @returns The user identity or undefined if the JWT is not valid
177
+ */
178
+ declare function userIdentityFromJwt(jwt?: string): UserIdentity | undefined;
179
+ /**
180
+ * Overide the globally defined user context, and persists the user identity in local storage
181
+ *
182
+ * @param identity the new identity of the user, or undefined if logged out
183
+ */
184
+ declare function setUserIdentity(identity?: UserIdentity): void;
185
+ /**
186
+ * Get the current value of the user context
187
+ */
188
+ declare function getUserIdentity(): UserIdentity | undefined;
189
+
190
+ /**
191
+ * Lazily start the locale context provider. If it already exists, the existing provider is
192
+ * returned. This function is safe to call multiple times.
193
+ *
194
+ * @returns The global locale context provider
195
+ */
196
+ declare function lazilyStartLocaleContext(): ContextProvider<string | undefined>;
197
+ /**
198
+ * Overide the globally defined Locale context
199
+ *
200
+ * @param locale the new locale used by the user
201
+ */
202
+ declare function setLocale(locale?: string): void;
203
+ /**
204
+ * Get the current value of the locale context
205
+ */
206
+ declare function getLocale(): string | undefined;
207
+
208
+ /**
209
+ * Lazily start the program context provider. If it already exists, the existing provider is
210
+ * returned. This function is safe to call multiple times.
211
+ *
212
+ * @returns The global program context provider
213
+ */
214
+ declare function lazilyStartProgramContext(): ContextProvider<string | undefined>;
215
+ /**
216
+ * Overide the globally defined Program ID context
217
+ *
218
+ * @param programId the new programID used by the user, or undefined if logged out
219
+ */
220
+ declare function setProgramId(programId: string | undefined): void;
221
+ /**
222
+ * Get the current value of the program context
223
+ */
224
+ declare function getProgramId(): string | undefined;
225
+
226
+ export { DEFAULT_MEDIUM, DecodedSquatchJWT, DecodedWidgetAPIJWT, EngagementMedium, Environment, EnvironmentSDK, LOCALE_CONTEXT_NAME, LocaleContextName, PROGRAM_CONTEXT_NAME, PortalEnv, ProgramContextName, SquatchAdmin, SquatchAndroid, SquatchJS2, USER_CONTEXT_NAME, UserContextName, UserId, UserIdentity, WidgetIdent, getAppDomain, getEngagementMedium, getEnvironment, getEnvironmentSDK, getLocale, getProgramId, getTenantAlias, getUserIdentity, isDemo, lazilyStartLocaleContext, lazilyStartProgramContext, lazilyStartUserContext, setLocale, setProgramId, setUserIdentity, userIdentityFromJwt };
package/dist/index.js CHANGED
@@ -1,21 +1,432 @@
1
1
  "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
10
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
11
+ var __spreadValues = (a, b) => {
12
+ for (var prop in b || (b = {}))
13
+ if (__hasOwnProp.call(b, prop))
14
+ __defNormalProp(a, prop, b[prop]);
15
+ if (__getOwnPropSymbols)
16
+ for (var prop of __getOwnPropSymbols(b)) {
17
+ if (__propIsEnum.call(b, prop))
18
+ __defNormalProp(a, prop, b[prop]);
19
+ }
20
+ return a;
21
+ };
22
+ var __export = (target, all) => {
23
+ for (var name in all)
24
+ __defProp(target, name, { get: all[name], enumerable: true });
25
+ };
26
+ var __copyProps = (to, from, except, desc) => {
27
+ if (from && typeof from === "object" || typeof from === "function") {
28
+ for (let key of __getOwnPropNames(from))
29
+ if (!__hasOwnProp.call(to, key) && key !== except)
30
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
31
+ }
32
+ return to;
15
33
  };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./types"), exports);
18
- __exportStar(require("./environment"), exports);
19
- __exportStar(require("./contexts/UserIdentityContext"), exports);
20
- __exportStar(require("./contexts/LocaleContext"), exports);
21
- __exportStar(require("./contexts/ProgramContext"), exports);
34
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod));
35
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
36
+
37
+ // src/index.ts
38
+ var src_exports = {};
39
+ __export(src_exports, {
40
+ DEFAULT_MEDIUM: () => DEFAULT_MEDIUM,
41
+ LOCALE_CONTEXT_NAME: () => LOCALE_CONTEXT_NAME,
42
+ PROGRAM_CONTEXT_NAME: () => PROGRAM_CONTEXT_NAME,
43
+ USER_CONTEXT_NAME: () => USER_CONTEXT_NAME,
44
+ getAppDomain: () => getAppDomain,
45
+ getEngagementMedium: () => getEngagementMedium,
46
+ getEnvironment: () => getEnvironment,
47
+ getEnvironmentSDK: () => getEnvironmentSDK,
48
+ getLocale: () => getLocale,
49
+ getProgramId: () => getProgramId,
50
+ getTenantAlias: () => getTenantAlias,
51
+ getUserIdentity: () => getUserIdentity,
52
+ isDemo: () => isDemo,
53
+ lazilyStartLocaleContext: () => lazilyStartLocaleContext,
54
+ lazilyStartProgramContext: () => lazilyStartProgramContext,
55
+ lazilyStartUserContext: () => lazilyStartUserContext,
56
+ setLocale: () => setLocale,
57
+ setProgramId: () => setProgramId,
58
+ setUserIdentity: () => setUserIdentity,
59
+ userIdentityFromJwt: () => userIdentityFromJwt
60
+ });
61
+ module.exports = __toCommonJS(src_exports);
62
+
63
+ // src/types.ts
64
+ var USER_CONTEXT_NAME = "sq:user-identity";
65
+ var LOCALE_CONTEXT_NAME = "sq:locale";
66
+ var PROGRAM_CONTEXT_NAME = "sq:program-id";
67
+ var DEFAULT_MEDIUM = "EMBED";
68
+
69
+ // src/environment.ts
70
+ function getEnvironment() {
71
+ return getEnvironmentSDK().type;
72
+ }
73
+ function getEnvironmentSDK() {
74
+ var _a, _b;
75
+ if (window["SquatchAndroid"]) {
76
+ return {
77
+ type: "SquatchAndroid",
78
+ android: window["SquatchAndroid"],
79
+ widgetIdent: window["widgetIdent"]
80
+ };
81
+ }
82
+ if (window["SquatchPortal"]) {
83
+ return {
84
+ type: "SquatchPortal",
85
+ env: window["SquatchPortal"]
86
+ };
87
+ }
88
+ if (window["SquatchAdmin"]) {
89
+ return {
90
+ type: "SquatchAdmin",
91
+ adminSDK: window["SquatchAdmin"]
92
+ };
93
+ }
94
+ if (window["widgetIdent"] && ((_a = window["widgetIdent"]) == null ? void 0 : _a.env) !== "demo") {
95
+ return {
96
+ type: "SquatchJS2",
97
+ api: (_b = window.frameElement) == null ? void 0 : _b["squatchJsApi"],
98
+ widgetIdent: window["widgetIdent"]
99
+ };
100
+ }
101
+ return {
102
+ type: "None"
103
+ };
104
+ }
105
+ function isDemo() {
106
+ const sdk = getEnvironmentSDK();
107
+ return sdk.type === "None" || sdk.type === "SquatchAdmin";
108
+ }
109
+ var FAKE_TENANT = "demo";
110
+ function getTenantAlias() {
111
+ const sdk = getEnvironmentSDK();
112
+ switch (sdk.type) {
113
+ case "SquatchAndroid":
114
+ case "SquatchJS2":
115
+ return sdk.widgetIdent.tenantAlias;
116
+ case "SquatchAdmin":
117
+ case "None":
118
+ return FAKE_TENANT;
119
+ case "SquatchPortal":
120
+ return sdk.env.tenantAlias;
121
+ }
122
+ }
123
+ var DEFAULT_DOMAIN = "https://app.referralsaasquatch.com";
124
+ function getAppDomain() {
125
+ var _a;
126
+ const sdk = getEnvironmentSDK();
127
+ switch (sdk.type) {
128
+ case "SquatchAndroid":
129
+ case "SquatchJS2":
130
+ return sdk.widgetIdent.appDomain;
131
+ case "SquatchPortal":
132
+ return ((_a = sdk.env) == null ? void 0 : _a.appDomain) || DEFAULT_DOMAIN;
133
+ case "SquatchAdmin":
134
+ case "None":
135
+ return DEFAULT_DOMAIN;
136
+ }
137
+ }
138
+ function getEngagementMedium() {
139
+ const sdk = getEnvironmentSDK();
140
+ switch (sdk.type) {
141
+ case "SquatchJS2":
142
+ return sdk.widgetIdent.engagementMedium || DEFAULT_MEDIUM;
143
+ case "SquatchAndroid":
144
+ case "SquatchPortal":
145
+ case "SquatchAdmin":
146
+ case "None":
147
+ return DEFAULT_MEDIUM;
148
+ }
149
+ }
150
+
151
+ // src/contexts/UserIdentityContext.ts
152
+ var import_jwt_decode = __toESM(require("jwt-decode"));
153
+ var import_dom_context3 = require("dom-context");
154
+ var import_equality = require("@wry/equality");
155
+
156
+ // src/listeners.ts
157
+ var import_dom_context2 = require("dom-context");
158
+
159
+ // src/contexts/LocaleContext.ts
160
+ var import_dom_context = require("dom-context");
161
+
162
+ // src/debug.ts
163
+ var debugEnabled = localStorage.getItem("debug");
164
+ function debug(ns, ...args) {
165
+ if (debugEnabled) {
166
+ console.debug(`sq:environment:${ns}`, ...args);
167
+ }
168
+ }
169
+
170
+ // src/contexts/LocaleContext.ts
171
+ var debug2 = (...args) => debug(LOCALE_CONTEXT_NAME, ...args);
172
+ function lazilyStartLocaleContext() {
173
+ var _a;
174
+ let globalProvider = window.squatchLocale;
175
+ if (!globalProvider) {
176
+ debug2("Creating locale context provider");
177
+ globalProvider = new import_dom_context.ContextProvider({
178
+ element: document.documentElement,
179
+ initialState: ((_a = window.widgetIdent) == null ? void 0 : _a.locale) || navigator.language.replace("-", "_"),
180
+ contextName: LOCALE_CONTEXT_NAME
181
+ }).start();
182
+ window.squatchLocale = globalProvider;
183
+ }
184
+ return globalProvider;
185
+ }
186
+ function setLocale(locale) {
187
+ const globalProvider = lazilyStartLocaleContext();
188
+ if (globalProvider.context !== locale) {
189
+ debug2(`Setting locale context value [${locale}]`);
190
+ globalProvider.context = locale;
191
+ }
192
+ }
193
+ function getLocale() {
194
+ var _a;
195
+ return (_a = window.squatchLocale) == null ? void 0 : _a.context;
196
+ }
197
+
198
+ // src/fetchLocale.ts
199
+ var debug3 = (...args) => debug(LOCALE_CONTEXT_NAME, ...args);
200
+ var GET_LOCALE = `
201
+ query {
202
+ viewer {
203
+ ... on User {
204
+ locale
205
+ }
206
+ }
207
+ }
208
+ `;
209
+ async function fetchLocale() {
210
+ var _a;
211
+ debug3("Fetching locale from GraphQL for current user");
212
+ try {
213
+ const result = await fetch(`${getAppDomain()}/api/v1/${getTenantAlias()}/graphql`, {
214
+ method: "POST",
215
+ headers: {
216
+ "Content-Type": "application/json",
217
+ Authorization: `Bearer ${(_a = getUserIdentity()) == null ? void 0 : _a.jwt}`
218
+ },
219
+ body: JSON.stringify({
220
+ query: GET_LOCALE
221
+ })
222
+ });
223
+ if (!result.ok) {
224
+ throw new Error("Failed to fetch locale");
225
+ }
226
+ const json = await result.json();
227
+ if (json.errors) {
228
+ throw new Error(JSON.stringify(json.errors, null, 2));
229
+ }
230
+ return json.data.viewer.locale || void 0;
231
+ } catch (e) {
232
+ debug3(`Failed to fetch locale for current user`, e.message);
233
+ return void 0;
234
+ }
235
+ }
236
+
237
+ // src/listeners.ts
238
+ var debug4 = (...args) => debug(LOCALE_CONTEXT_NAME, ...args);
239
+ var userContextListenerDiv = (() => {
240
+ const id = "__environment_context_listener";
241
+ let div = document.getElementById(id);
242
+ if (!div) {
243
+ div = document.createElement("div");
244
+ div.id = id;
245
+ document.documentElement.appendChild(div);
246
+ }
247
+ return div;
248
+ })();
249
+ var userContextListenerForLocale = new import_dom_context2.ContextListener({
250
+ contextName: USER_CONTEXT_NAME,
251
+ element: userContextListenerDiv,
252
+ onChange: async (next) => {
253
+ var _a;
254
+ const localeProvider = lazilyStartLocaleContext();
255
+ const defaultLocale = ((_a = window.widgetIdent) == null ? void 0 : _a.locale) || navigator.language.replace("-", "_");
256
+ let newLocale;
257
+ if (next) {
258
+ debug4("User context changed, refetching locale");
259
+ const locale = await fetchLocale();
260
+ if (localeProvider.context !== locale) {
261
+ debug4(`New value fetched from GraphQL [${locale}]`);
262
+ newLocale = locale || defaultLocale;
263
+ }
264
+ } else {
265
+ newLocale = defaultLocale;
266
+ }
267
+ debug4(`Setting locale context to [${newLocale}]`);
268
+ localeProvider.context = newLocale;
269
+ },
270
+ onStatus: (status) => debug4("STATUS", status)
271
+ });
272
+ function startUserContextListenerForLocale() {
273
+ debug4("Starting user context listener for locale updates");
274
+ userContextListenerForLocale.start();
275
+ }
276
+
277
+ // src/contexts/UserIdentityContext.ts
278
+ var debug5 = (...args) => debug(USER_CONTEXT_NAME, ...args);
279
+ function lazilyStartUserContext() {
280
+ let globalProvider = window.squatchUserIdentity;
281
+ if (!globalProvider) {
282
+ debug5("Creating user context provider");
283
+ globalProvider = new import_dom_context3.ContextProvider({
284
+ element: document.documentElement,
285
+ initialState: _getInitialValue(),
286
+ contextName: USER_CONTEXT_NAME
287
+ }).start();
288
+ window.squatchUserIdentity = globalProvider;
289
+ startUserContextListenerForLocale();
290
+ }
291
+ return globalProvider;
292
+ }
293
+ function isDecodedSquatchJWT(decoded) {
294
+ return decoded.user && decoded.user.id && decoded.user.accountId;
295
+ }
296
+ function isDecodedWidgetAPIJWT(decoded) {
297
+ return decoded.sub && /.*:.*@.*:users/.test(decoded.sub);
298
+ }
299
+ function userIdentityFromJwt(jwt) {
300
+ if (!jwt)
301
+ return void 0;
302
+ try {
303
+ const decoded = (0, import_jwt_decode.default)(jwt);
304
+ const exp = decoded.exp;
305
+ let userId = void 0;
306
+ let accountId = void 0;
307
+ if (isDecodedWidgetAPIJWT(decoded)) {
308
+ const matches = decoded.sub.match(/(.*):(.*)@(.*):users/);
309
+ if (matches == null ? void 0 : matches[1])
310
+ accountId = atob(matches[1]);
311
+ if (matches == null ? void 0 : matches[2])
312
+ userId = atob(matches[2]);
313
+ } else if (isDecodedSquatchJWT(decoded)) {
314
+ accountId = decoded.user.accountId;
315
+ userId = decoded.user.id;
316
+ }
317
+ if (!userId || !accountId) {
318
+ return void 0;
319
+ }
320
+ if (exp && Date.now() >= exp * 1e3) {
321
+ return void 0;
322
+ }
323
+ return {
324
+ id: userId,
325
+ accountId,
326
+ jwt
327
+ };
328
+ } catch (e) {
329
+ return void 0;
330
+ }
331
+ }
332
+ function _getInitialValue() {
333
+ const sdk = getEnvironmentSDK();
334
+ switch (sdk.type) {
335
+ case "SquatchAndroid":
336
+ case "SquatchJS2":
337
+ return {
338
+ id: sdk.widgetIdent.userId,
339
+ accountId: sdk.widgetIdent.accountId,
340
+ jwt: sdk.widgetIdent.token
341
+ };
342
+ case "SquatchPortal":
343
+ const searchParams = new URLSearchParams(document.location.search);
344
+ if (searchParams.has("jwt")) {
345
+ return userIdentityFromJwt(searchParams.get("jwt"));
346
+ }
347
+ const stored = localStorage.getItem(USER_CONTEXT_NAME);
348
+ if (!stored)
349
+ return void 0;
350
+ try {
351
+ const potentialUserIdent = JSON.parse(stored);
352
+ const identity = userIdentityFromJwt(potentialUserIdent.jwt);
353
+ if (identity) {
354
+ return __spreadValues(__spreadValues({}, potentialUserIdent), identity);
355
+ }
356
+ return void 0;
357
+ } catch (e) {
358
+ return void 0;
359
+ }
360
+ case "SquatchAdmin":
361
+ case "None":
362
+ return void 0;
363
+ }
364
+ }
365
+ function setUserIdentity(identity) {
366
+ const globalProvider = lazilyStartUserContext();
367
+ if (!(0, import_equality.equal)(globalProvider.context, identity)) {
368
+ debug5(`Setting user context value [${JSON.stringify(identity)}]`);
369
+ globalProvider.context = identity;
370
+ }
371
+ if (identity && getEnvironmentSDK().type === "SquatchPortal") {
372
+ localStorage.setItem(USER_CONTEXT_NAME, JSON.stringify(identity));
373
+ } else if (!identity) {
374
+ localStorage.removeItem(USER_CONTEXT_NAME);
375
+ }
376
+ }
377
+ function getUserIdentity() {
378
+ var _a;
379
+ return (_a = window.squatchUserIdentity) == null ? void 0 : _a.context;
380
+ }
381
+
382
+ // src/contexts/ProgramContext.ts
383
+ var import_dom_context4 = require("dom-context");
384
+ var debug6 = (...args) => debug(PROGRAM_CONTEXT_NAME, ...args);
385
+ function lazilyStartProgramContext() {
386
+ var _a;
387
+ let globalProvider = window.squatchProgramId;
388
+ if (!globalProvider) {
389
+ debug6("Creating program context provider");
390
+ globalProvider = new import_dom_context4.ContextProvider({
391
+ element: document.documentElement,
392
+ initialState: ((_a = window.widgetIdent) == null ? void 0 : _a.programId) || void 0,
393
+ contextName: PROGRAM_CONTEXT_NAME
394
+ }).start();
395
+ window.squatchProgramId = globalProvider;
396
+ }
397
+ return globalProvider;
398
+ }
399
+ function setProgramId(programId) {
400
+ const globalProvider = lazilyStartProgramContext();
401
+ if (globalProvider.context !== programId) {
402
+ debug6(`Setting program context value [${programId}]`);
403
+ globalProvider.context = programId;
404
+ }
405
+ }
406
+ function getProgramId() {
407
+ var _a;
408
+ return (_a = window.squatchLocale) == null ? void 0 : _a.context;
409
+ }
410
+ // Annotate the CommonJS export names for ESM import in node:
411
+ 0 && (module.exports = {
412
+ DEFAULT_MEDIUM,
413
+ LOCALE_CONTEXT_NAME,
414
+ PROGRAM_CONTEXT_NAME,
415
+ USER_CONTEXT_NAME,
416
+ getAppDomain,
417
+ getEngagementMedium,
418
+ getEnvironment,
419
+ getEnvironmentSDK,
420
+ getLocale,
421
+ getProgramId,
422
+ getTenantAlias,
423
+ getUserIdentity,
424
+ isDemo,
425
+ lazilyStartLocaleContext,
426
+ lazilyStartProgramContext,
427
+ lazilyStartUserContext,
428
+ setLocale,
429
+ setProgramId,
430
+ setUserIdentity,
431
+ userIdentityFromJwt
432
+ });