flagsmith-toolbar 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,3002 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ default: () => index_default,
24
+ destroy: () => destroy,
25
+ explainReason: () => explainReason,
26
+ hide: () => hide,
27
+ init: () => init,
28
+ parseReason: () => parseReason,
29
+ show: () => show,
30
+ toggle: () => toggle
31
+ });
32
+ module.exports = __toCommonJS(index_exports);
33
+
34
+ // src/checks.ts
35
+ function levenshtein(a4, b) {
36
+ if (a4 === b) return 0;
37
+ let previous = Array.from({ length: b.length + 1 }, (_3, i3) => i3);
38
+ for (let i3 = 1; i3 <= a4.length; i3++) {
39
+ const current2 = [i3];
40
+ for (let j2 = 1; j2 <= b.length; j2++) {
41
+ current2[j2] = Math.min(previous[j2] + 1, current2[j2 - 1] + 1, previous[j2 - 1] + (a4[i3 - 1] === b[j2 - 1] ? 0 : 1));
42
+ }
43
+ previous = current2;
44
+ }
45
+ return previous[b.length];
46
+ }
47
+ function closestKey(key, candidates) {
48
+ const limit = Math.max(2, Math.floor(key.length / 4));
49
+ let best = null;
50
+ let bestDistance = Infinity;
51
+ for (const candidate of candidates) {
52
+ const distance = levenshtein(key, candidate);
53
+ if (distance < bestDistance) {
54
+ best = candidate;
55
+ bestDistance = distance;
56
+ }
57
+ }
58
+ return bestDistance <= limit ? best : null;
59
+ }
60
+ var list = (keys) => keys.map((key) => `"${key}"`).join(", ");
61
+ function runSetupChecks(input) {
62
+ const issues = [];
63
+ const source = input.loadingState?.source;
64
+ const fromServer = source === "SERVER";
65
+ const flagKeys = Object.keys(input.serverFlags);
66
+ if (input.environmentKey?.startsWith("ser.")) {
67
+ issues.push({
68
+ id: "server-key",
69
+ level: "problem",
70
+ title: "A server-side key is in the browser",
71
+ detail: `Server-side keys start with "ser." and are meant for your backend. Anyone can read this one in the page. Use the environment's client-side key instead, and rotate this one.`
72
+ });
73
+ }
74
+ if (fromServer && flagKeys.length > 0) {
75
+ const unknown = [.../* @__PURE__ */ new Set([...Object.keys(input.seenOn ?? {}), ...Object.keys(input.reads)])].filter((key) => !(key in input.serverFlags)).sort();
76
+ for (const key of unknown) {
77
+ const guess = closestKey(key, flagKeys);
78
+ const pages = input.seenOn?.[key] ?? [];
79
+ const where = pages.length ? ` (on ${pages.slice(0, 3).join(", ")}${pages.length > 3 ? ", \u2026" : ""})` : "";
80
+ issues.push({
81
+ id: `unknown-flag:${key}`,
82
+ level: "problem",
83
+ title: `This app reads "${key}"${where}, which isn't in Flagsmith`,
84
+ detail: guess ? `There's no flag called "${key}", so it's always off. Did you mean "${guess}"?` : `There's no flag called "${key}" in this environment, so it's always off. Create it in Flagsmith, or remove it from the code.`
85
+ });
86
+ }
87
+ }
88
+ const error = input.loadingState?.error;
89
+ if (!input.loadingState?.isFetching && (error || source === "CACHE" || source === "DEFAULT_FLAGS")) {
90
+ const from = source === "CACHE" ? "your browser cache" : "the default flags in your code";
91
+ issues.push({
92
+ id: "not-from-server",
93
+ level: "warning",
94
+ title: "These flags didn't come from Flagsmith",
95
+ detail: `The page is using flags from ${from}${error ? ` because Flagsmith couldn't be reached (${error instanceof Error ? error.message : String(error)})` : ""}.`
96
+ });
97
+ }
98
+ if (fromServer && flagKeys.length > 0 && flagKeys.every((key) => !input.serverFlags[key].reason)) {
99
+ issues.push({
100
+ id: "no-reasons",
101
+ level: "warning",
102
+ title: "Flagsmith didn't say why flags have their values",
103
+ detail: "Reasons need Flagsmith 2.295 or newer and @flagsmith/flagsmith 12.6 or newer. Everything else in the toolbar still works.",
104
+ fix: "npm install @flagsmith/flagsmith@latest"
105
+ });
106
+ }
107
+ const dropped = [...new Set(input.events.filter((event) => event.status === "off").map((event) => event.name))];
108
+ const uncounted = input.experiments.filter((row) => row.state === "events-off").map((row) => row.key);
109
+ if (dropped.length > 0 || uncounted.length > 0) {
110
+ issues.push({
111
+ id: "events-off",
112
+ level: "warning",
113
+ title: dropped.length ? "Events are tracked, but never sent" : "This user is in an experiment that can't count them",
114
+ detail: `${dropped.length ? `The page tracked ${list(dropped)}, but` : `This user is in the experiment behind ${list(uncounted)}, but`} Flagsmith was started without enableEvents, so Experimentation never sees ${dropped.length ? "them" : "their exposures or conversions"}.`,
115
+ fix: "flagsmith.init({ environmentID, enableEvents: true })"
116
+ });
117
+ }
118
+ for (const key of flagKeys) {
119
+ const flag = input.serverFlags[key];
120
+ if (flag.experiment?.inExperiment && flag.reason?.toUpperCase().startsWith("SPLIT") && !flag.variant) {
121
+ issues.push({
122
+ id: `variant-without-key:${key}`,
123
+ level: "problem",
124
+ title: `"${key}"'s variant has no key, so its results can't be counted`,
125
+ detail: `This user sees "${String(flag.value)}" in "${flag.experiment.name}", but that variant has no key in Flagsmith, so their exposure arrives without a variant. Give every variant of "${key}" a key in Flagsmith.`
126
+ });
127
+ }
128
+ }
129
+ for (const row of input.experiments.filter((experiment) => experiment.state === "missing")) {
130
+ issues.push({
131
+ id: `exposure-missing:${row.key}`,
132
+ level: "warning",
133
+ title: `"${row.key}" is in an experiment, but no exposure was recorded`,
134
+ detail: `This user sees "${String(row.value)}" from "${row.name}", but the page never records that they saw it, so they won't be counted in the results. Read the flag with getExperimentFlag, or useExperiment in React.`,
135
+ fix: `flagsmith.getExperimentFlag('${row.key}')`
136
+ });
137
+ }
138
+ if (!input.identity) {
139
+ issues.push({
140
+ id: "anonymous",
141
+ level: "tip",
142
+ title: "No user is identified",
143
+ detail: "Segments, percentage splits and experiments only apply to identified users, so an anonymous visitor always gets the defaults. Use View as to test them."
144
+ });
145
+ }
146
+ const order = { problem: 0, warning: 1, tip: 2 };
147
+ return issues.sort((a4, b) => order[a4.level] - order[b.level]);
148
+ }
149
+
150
+ // src/personas.ts
151
+ function slugify(text) {
152
+ return text.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40) || "user";
153
+ }
154
+ function personaContext(base, persona) {
155
+ const traits = Object.fromEntries(
156
+ Object.entries(persona.traits ?? {}).map(([key, value]) => [key, { value, transient: true }])
157
+ );
158
+ const identity = persona.identifier ? { identifier: persona.identifier, traits } : { identifier: `toolbar-preview-${slugify(persona.name)}`, transient: true, traits };
159
+ return { ...base, identity };
160
+ }
161
+ function parseTraits(text) {
162
+ const traits = {};
163
+ for (const line of text.split(/\r?\n/)) {
164
+ const separator = line.indexOf("=");
165
+ if (separator <= 0) continue;
166
+ const key = line.slice(0, separator).trim();
167
+ const raw = line.slice(separator + 1).trim();
168
+ if (!key) continue;
169
+ if (raw === "true" || raw === "false") traits[key] = raw === "true";
170
+ else if (raw !== "" && Number.isFinite(Number(raw))) traits[key] = Number(raw);
171
+ else traits[key] = raw;
172
+ }
173
+ return traits;
174
+ }
175
+ function cloneContext(context) {
176
+ return JSON.parse(JSON.stringify(context ?? {}));
177
+ }
178
+
179
+ // src/compare.ts
180
+ function toFlagMap(items) {
181
+ const flags = {};
182
+ for (const item of items ?? []) {
183
+ const experiment = item.metadata?.experiment;
184
+ flags[item.feature.name.toLowerCase().replace(/ /g, "_")] = {
185
+ id: item.feature.id,
186
+ enabled: item.enabled,
187
+ value: item.feature_state_value,
188
+ ...item.variant ? { variant: item.variant } : {},
189
+ ...item.reason ? { reason: item.reason } : {},
190
+ ...experiment ? { experiment: { id: experiment.id, name: experiment.name, inExperiment: Boolean(experiment.in_experiment) } } : {}
191
+ };
192
+ }
193
+ return flags;
194
+ }
195
+ async function fetchFlagsFor(persona, options) {
196
+ const api = options.api.endsWith("/") ? options.api : `${options.api}/`;
197
+ const doFetch = options.fetch ?? ((url, init2) => fetch(url, init2));
198
+ const headers = { "X-Environment-Key": options.environmentKey, ...options.headers ?? {} };
199
+ let response;
200
+ if (!persona) {
201
+ response = await doFetch(`${api}flags/`, { headers, cache: "no-cache" });
202
+ } else {
203
+ const identity = personaContext({}, persona).identity ?? {};
204
+ const traits = Object.entries(identity.traits ?? {}).map(([trait_key, trait]) => ({
205
+ trait_key,
206
+ trait_value: trait?.value,
207
+ transient: true
208
+ }));
209
+ if (traits.length === 0 && persona.identifier) {
210
+ response = await doFetch(`${api}identities/?identifier=${encodeURIComponent(persona.identifier)}`, { headers, cache: "no-cache" });
211
+ } else {
212
+ response = await doFetch(`${api}identities/`, {
213
+ method: "POST",
214
+ headers: { ...headers, "Content-Type": "application/json; charset=utf-8" },
215
+ body: JSON.stringify({ identifier: identity.identifier, ...identity.transient ? { transient: true } : {}, traits }),
216
+ cache: "no-cache"
217
+ });
218
+ }
219
+ }
220
+ if (!response.ok) throw new Error(`Flagsmith answered ${response.status}`);
221
+ const data = await response.json();
222
+ return toFlagMap(Array.isArray(data) ? data : data.flags);
223
+ }
224
+ var valueOf = (flag) => flag?.value === void 0 || flag.value === "" ? null : flag.value;
225
+ function flagsMatch(a4, b) {
226
+ if (!a4 || !b) return a4 === b;
227
+ return a4.enabled === b.enabled && valueOf(a4) === valueOf(b);
228
+ }
229
+ function compareFlags(a4, b) {
230
+ const keys = [.../* @__PURE__ */ new Set([...Object.keys(a4), ...Object.keys(b)])].sort();
231
+ const comparison = { differ: [], same: [] };
232
+ for (const key of keys) {
233
+ const row = { key, a: a4[key], b: b[key] };
234
+ (flagsMatch(row.a, row.b) ? comparison.same : comparison.differ).push(row);
235
+ }
236
+ return comparison;
237
+ }
238
+
239
+ // src/experiments.ts
240
+ var EXPOSURE_GRACE_MS = 1500;
241
+ var exposureKey = (flagKey, identity) => `${flagKey}|${identity ?? ""}`;
242
+ function experimentRows(input) {
243
+ const grace = input.graceMs ?? EXPOSURE_GRACE_MS;
244
+ const rows = [];
245
+ for (const key of Object.keys(input.flags).sort()) {
246
+ const flag = input.flags[key];
247
+ if (!flag.experiment) continue;
248
+ const exposure = input.exposures[exposureKey(key, input.identity)];
249
+ const readAt = Math.max(input.reads[key] ?? 0, input.since ?? 0);
250
+ let state;
251
+ if (!flag.experiment.inExperiment) state = "not-enrolled";
252
+ else if (exposure) state = exposure.status === "sent" ? "recorded" : exposure.status === "held" ? "held" : exposure.status === "off" ? "events-off" : "missing";
253
+ else if (!input.eventsEnabled) state = "events-off";
254
+ else if (!(key in input.reads)) state = "not-read";
255
+ else if (input.previewing) state = "previewing";
256
+ else if (!flag.enabled) state = "disabled";
257
+ else if (input.now - readAt < grace) state = "waiting";
258
+ else state = "missing";
259
+ rows.push({
260
+ key,
261
+ id: flag.experiment.id,
262
+ name: flag.experiment.name,
263
+ inExperiment: flag.experiment.inExperiment,
264
+ enabled: flag.enabled,
265
+ value: flag.value,
266
+ state,
267
+ ...exposure ? { exposure } : {}
268
+ });
269
+ }
270
+ return rows;
271
+ }
272
+
273
+ // src/reasons.ts
274
+ var OVERRIDE_REASON = "TOOLBAR_OVERRIDE";
275
+ var IDENTITY_OVERRIDES_SEGMENT = "identity_overrides";
276
+ var EXPERIMENT_SEGMENT = /^experiment-\d+-rollout$/;
277
+ function parseReason(raw) {
278
+ if (!raw) return { code: "", params: {} };
279
+ const [code = "", ...parts] = raw.split(";").map((part) => part.trim());
280
+ const params = {};
281
+ for (const part of parts) {
282
+ const separator = part.indexOf("=");
283
+ if (separator > 0) params[part.slice(0, separator).trim()] = part.slice(separator + 1).trim();
284
+ }
285
+ return { code: code.toUpperCase(), params };
286
+ }
287
+ function formatWeight(weight) {
288
+ if (!weight) return "";
289
+ const value = Number(weight);
290
+ if (!Number.isFinite(value)) return `${weight}%`;
291
+ return `${Math.round(value * 10) / 10}%`;
292
+ }
293
+ function explainReason(raw) {
294
+ const { code, params } = parseReason(raw);
295
+ switch (code) {
296
+ case "STATIC":
297
+ return {
298
+ kind: "static",
299
+ label: "No targeting",
300
+ detail: "Nothing targets this flag for this user, so they get the environment's value. In a split test, this is the control value."
301
+ };
302
+ case "DEFAULT":
303
+ return {
304
+ kind: "default",
305
+ label: "No rule matched",
306
+ detail: "This flag has targeting rules, but none matched this user, so they get the environment's value."
307
+ };
308
+ case "TARGETING_MATCH": {
309
+ const segment = params.segment;
310
+ if (segment === IDENTITY_OVERRIDES_SEGMENT) {
311
+ return {
312
+ kind: "identity",
313
+ label: "Set for this user",
314
+ detail: "An identity override in Flagsmith sets this flag for this exact user."
315
+ };
316
+ }
317
+ if (segment && EXPERIMENT_SEGMENT.test(segment)) {
318
+ return {
319
+ kind: "experiment",
320
+ label: "Experiment: control group",
321
+ detail: "This user is in a running experiment, in its control group, so they see the original version."
322
+ };
323
+ }
324
+ return {
325
+ kind: "segment",
326
+ label: segment ? `Segment: ${segment}` : "Segment match",
327
+ detail: segment ? `This user is in the "${segment}" segment, and that segment overrides the flag.` : "A segment override matched this user."
328
+ };
329
+ }
330
+ case "SPLIT": {
331
+ const weight = formatWeight(params.weight);
332
+ return {
333
+ kind: "split",
334
+ label: weight ? `Split test: ${weight} bucket` : "Split test",
335
+ detail: weight ? `A percentage split put this user in a ${weight} bucket. The bucket comes from their identity, so it stays the same on every visit.` : "A percentage split put this user in this bucket."
336
+ };
337
+ }
338
+ case OVERRIDE_REASON:
339
+ return {
340
+ kind: "override",
341
+ label: "Changed by you",
342
+ detail: "You changed this in the toolbar. Only your browser sees it, and nothing changed in Flagsmith."
343
+ };
344
+ case "ERROR":
345
+ return {
346
+ kind: "error",
347
+ label: "Evaluation error",
348
+ detail: params.code ? `Flagsmith could not evaluate this flag (${params.code}).` : "Flagsmith could not evaluate this flag."
349
+ };
350
+ case "":
351
+ return {
352
+ kind: "missing",
353
+ label: "No reason sent",
354
+ detail: "Flagsmith did not send a reason. Reasons need Flagsmith 2.295 or newer and @flagsmith/flagsmith 12.6 or newer."
355
+ };
356
+ default:
357
+ return { kind: "other", label: raw ?? "", detail: `Flagsmith reported: ${raw}` };
358
+ }
359
+ }
360
+
361
+ // src/overrides.ts
362
+ function normalizeKey(key) {
363
+ return key.toLowerCase().replace(/ /g, "_");
364
+ }
365
+ function applyOverrides(flags, overrides) {
366
+ const keys = Object.keys(overrides);
367
+ if (keys.length === 0) return flags;
368
+ const result = { ...flags ?? {} };
369
+ for (const key of keys) {
370
+ const override = overrides[key];
371
+ const next = { ...result[key] ?? { enabled: false, value: null }, reason: OVERRIDE_REASON };
372
+ if (override.enabled !== void 0) next.enabled = override.enabled;
373
+ if (override.value !== void 0) {
374
+ next.value = override.value;
375
+ delete next.variant;
376
+ }
377
+ result[key] = next;
378
+ }
379
+ return result;
380
+ }
381
+ function withOverride(overrides, key, patch) {
382
+ return { ...overrides, [key]: { ...overrides[key], ...patch } };
383
+ }
384
+ function withoutOverride(overrides, key) {
385
+ const { [key]: _removed, ...rest } = overrides;
386
+ return rest;
387
+ }
388
+ function changedKeys(before, after) {
389
+ const keys = /* @__PURE__ */ new Set([...Object.keys(before ?? {}), ...Object.keys(after ?? {})]);
390
+ return [...keys].filter((key) => {
391
+ const a4 = before?.[key];
392
+ const b = after?.[key];
393
+ return a4?.enabled !== b?.enabled || a4?.value !== b?.value;
394
+ });
395
+ }
396
+ function parseValueInput(text, current2) {
397
+ const trimmed = text.trim();
398
+ if (trimmed === "") return null;
399
+ if (typeof current2 === "number") {
400
+ const number = Number(trimmed);
401
+ return Number.isFinite(number) ? number : text;
402
+ }
403
+ if (typeof current2 === "boolean") {
404
+ if (trimmed === "true") return true;
405
+ if (trimmed === "false") return false;
406
+ }
407
+ return text;
408
+ }
409
+ function formatValue(value) {
410
+ if (value === null || value === void 0 || value === "") return "No value";
411
+ return String(value);
412
+ }
413
+
414
+ // src/instrument.ts
415
+ function instrument(flagsmith, hooks) {
416
+ const sdk = flagsmith;
417
+ let serverFlags = sdk.flags ?? null;
418
+ let overrides = {};
419
+ let merged = null;
420
+ let mergedIsCurrent = false;
421
+ Object.defineProperty(sdk, "flags", {
422
+ configurable: true,
423
+ enumerable: true,
424
+ get: () => {
425
+ if (!mergedIsCurrent) {
426
+ merged = applyOverrides(serverFlags, overrides) ?? null;
427
+ mergedIsCurrent = true;
428
+ }
429
+ return merged;
430
+ },
431
+ set: (value) => {
432
+ serverFlags = value;
433
+ mergedIsCurrent = false;
434
+ hooks.onServerFlags(value ?? {});
435
+ }
436
+ });
437
+ const keys = /* @__PURE__ */ new Map();
438
+ const keyOf = (key) => {
439
+ const raw = String(key);
440
+ let normalized = keys.get(raw);
441
+ if (normalized === void 0) {
442
+ normalized = normalizeKey(raw);
443
+ if (keys.size < 5e3) keys.set(raw, normalized);
444
+ }
445
+ return normalized;
446
+ };
447
+ const originals = {};
448
+ const inherited = /* @__PURE__ */ new Set();
449
+ const wrap = (name, make) => {
450
+ const original = sdk[name];
451
+ if (typeof original !== "function") return;
452
+ if (!Object.prototype.hasOwnProperty.call(sdk, name)) inherited.add(name);
453
+ originals[name] = original;
454
+ sdk[name] = make(original);
455
+ };
456
+ const identity = () => sdk.getContext?.()?.identity?.identifier ?? sdk.identity ?? null;
457
+ const eventsOn = () => sdk.eventsEnabled === true;
458
+ wrap("hasFeature", (original) => (key, ...rest) => {
459
+ hooks.onRead(keyOf(key));
460
+ return original.call(sdk, key, ...rest);
461
+ });
462
+ wrap("getValue", (original) => (key, ...rest) => {
463
+ hooks.onRead(keyOf(key));
464
+ return original.call(sdk, key, ...rest);
465
+ });
466
+ wrap("getExperimentFlag", (original) => (key) => {
467
+ hooks.onRead(keyOf(key));
468
+ return original.call(sdk, key);
469
+ });
470
+ wrap("trackEvent", (original) => (event, opts) => {
471
+ const held = hooks.holdBack();
472
+ const status = held ? "held" : eventsOn() ? "sent" : "off";
473
+ hooks.onEvent({ kind: "event", name: String(event), value: opts?.value, identifier: opts?.identifier ?? identity(), status });
474
+ if (held) return void 0;
475
+ return original.call(sdk, event, opts);
476
+ });
477
+ wrap("trackExposureEvent", (original) => (featureName, opts) => {
478
+ const held = hooks.holdBack();
479
+ const who = opts?.identifier ?? identity();
480
+ const status = held ? "held" : !eventsOn() ? "off" : !who ? "no-identity" : "sent";
481
+ hooks.onEvent({
482
+ kind: "exposure",
483
+ name: String(featureName),
484
+ key: normalizeKey(String(featureName)),
485
+ value: opts?.value,
486
+ identifier: who,
487
+ status
488
+ });
489
+ if (held) return void 0;
490
+ return original.call(sdk, featureName, opts);
491
+ });
492
+ for (const name of ["identify", "logout", "setContext"]) {
493
+ wrap(name, (original) => (...args) => {
494
+ const fromApp = !hooks.isOwnContextChange?.();
495
+ const result = original.apply(sdk, args);
496
+ if (fromApp && hooks.onAppContextChange) {
497
+ const notify = () => hooks.onAppContextChange?.();
498
+ Promise.resolve(result).then(notify, notify);
499
+ }
500
+ return result;
501
+ });
502
+ }
503
+ return {
504
+ serverFlags: () => serverFlags ?? {},
505
+ setOverrides(next) {
506
+ overrides = next;
507
+ mergedIsCurrent = false;
508
+ },
509
+ notifyApp(changed) {
510
+ try {
511
+ sdk.onChange?.(serverFlags, { isFromServer: false, flagsChanged: changed, traitsChanged: null }, sdk.loadingState);
512
+ } catch (error) {
513
+ console.error("[flagsmith-toolbar] onChange threw", error);
514
+ }
515
+ sdk._trigger?.();
516
+ },
517
+ restore() {
518
+ Object.defineProperty(sdk, "flags", { configurable: true, enumerable: true, writable: true, value: serverFlags });
519
+ for (const [name, original] of Object.entries(originals)) {
520
+ if (inherited.has(name)) delete sdk[name];
521
+ else sdk[name] = original;
522
+ }
523
+ }
524
+ };
525
+ }
526
+
527
+ // src/pages.ts
528
+ function pageKey(location) {
529
+ return location.hash.startsWith("#/") ? `${location.pathname}${location.hash}` : location.pathname;
530
+ }
531
+ function watchNavigation(onNavigate) {
532
+ if (typeof window === "undefined" || !window.history) return () => {
533
+ };
534
+ const history = window.history;
535
+ let stopped = false;
536
+ const notify = () => {
537
+ if (!stopped) onNavigate();
538
+ };
539
+ const restores = [];
540
+ for (const name of ["pushState", "replaceState"]) {
541
+ const original = history[name];
542
+ if (typeof original !== "function") continue;
543
+ const own = Object.prototype.hasOwnProperty.call(history, name);
544
+ const wrapper = function(...args) {
545
+ const result = original.apply(this, args);
546
+ notify();
547
+ return result;
548
+ };
549
+ history[name] = wrapper;
550
+ restores.push(() => {
551
+ if (history[name] !== wrapper) return;
552
+ if (own) history[name] = original;
553
+ else delete history[name];
554
+ });
555
+ }
556
+ window.addEventListener("popstate", notify);
557
+ window.addEventListener("hashchange", notify);
558
+ return () => {
559
+ stopped = true;
560
+ for (const restore of restores) restore();
561
+ window.removeEventListener("popstate", notify);
562
+ window.removeEventListener("hashchange", notify);
563
+ };
564
+ }
565
+
566
+ // src/preview-link.ts
567
+ var PREVIEW_PARAM = "flagsmith-toolbar";
568
+ var PREVIEW_PATTERN = new RegExp(`(^|&)${PREVIEW_PARAM}=([A-Za-z0-9_-]+)`);
569
+ function toBase64Url(text) {
570
+ let binary = "";
571
+ for (const byte of new TextEncoder().encode(text)) binary += String.fromCharCode(byte);
572
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
573
+ }
574
+ function fromBase64Url(encoded) {
575
+ const base64 = encoded.replace(/-/g, "+").replace(/_/g, "/");
576
+ const padded = base64 + "=".repeat((4 - base64.length % 4) % 4);
577
+ const binary = atob(padded);
578
+ return new TextDecoder().decode(Uint8Array.from(binary, (char) => char.charCodeAt(0)));
579
+ }
580
+ var isFlagValue = (value) => value === null || ["string", "number", "boolean"].includes(typeof value);
581
+ var isTraitValue = (value) => ["string", "number", "boolean"].includes(typeof value);
582
+ function sanitizeOverrides(input) {
583
+ const overrides = {};
584
+ if (!input || typeof input !== "object") return overrides;
585
+ for (const [key, raw] of Object.entries(input)) {
586
+ if (!raw || typeof raw !== "object") continue;
587
+ const { enabled, value } = raw;
588
+ const override = {};
589
+ if (typeof enabled === "boolean") override.enabled = enabled;
590
+ if (value !== void 0 && isFlagValue(value)) override.value = value;
591
+ if (Object.keys(override).length) overrides[key] = override;
592
+ }
593
+ return overrides;
594
+ }
595
+ function sanitizePersona(input) {
596
+ if (!input || typeof input !== "object") return null;
597
+ const { name, description, identifier, traits } = input;
598
+ if (typeof name !== "string" || !name) return null;
599
+ const persona = { name };
600
+ if (typeof description === "string") persona.description = description;
601
+ if (typeof identifier === "string" && identifier) persona.identifier = identifier;
602
+ if (traits && typeof traits === "object") {
603
+ persona.traits = Object.fromEntries(
604
+ Object.entries(traits).filter(
605
+ (entry) => isTraitValue(entry[1])
606
+ )
607
+ );
608
+ }
609
+ return persona;
610
+ }
611
+ function encodePreview(state) {
612
+ return toBase64Url(JSON.stringify({ v: 1, o: state.overrides, p: state.persona ?? null }));
613
+ }
614
+ function decodePreview(payload) {
615
+ try {
616
+ const data = JSON.parse(fromBase64Url(payload));
617
+ if (!data || data.v !== 1) return null;
618
+ return { overrides: sanitizeOverrides(data.o), persona: sanitizePersona(data.p) };
619
+ } catch {
620
+ return null;
621
+ }
622
+ }
623
+ function buildPreviewUrl(href, state) {
624
+ const url = new URL(href);
625
+ const existing = url.hash.replace(/^#/, "").replace(PREVIEW_PATTERN, "").replace(/^&/, "");
626
+ const preview = `${PREVIEW_PARAM}=${encodePreview(state)}`;
627
+ url.hash = existing ? `${existing}&${preview}` : preview;
628
+ return url.toString();
629
+ }
630
+ function readPreviewFromUrl(href) {
631
+ const match = new URL(href).hash.replace(/^#/, "").match(PREVIEW_PATTERN);
632
+ return match ? decodePreview(match[2]) : null;
633
+ }
634
+ function stripPreviewFromUrl(href) {
635
+ const url = new URL(href);
636
+ url.hash = url.hash.replace(/^#/, "").replace(PREVIEW_PATTERN, "").replace(/^&/, "");
637
+ return url.toString().replace(/#$/, "");
638
+ }
639
+
640
+ // src/snapshot.ts
641
+ var cell = (text) => text.replace(/\|/g, "\\|").replace(/\r?\n/g, " ");
642
+ function describeUser(input) {
643
+ if (input.persona) {
644
+ const traits = Object.entries(input.persona.traits ?? {}).map(([key, value]) => `${key}=${value}`).join(", ");
645
+ return `${input.persona.name}${traits ? ` (${traits})` : ""} \u2014 previewed with the toolbar`;
646
+ }
647
+ return input.identity ? `identity \`${input.identity}\`` : "anonymous visitor";
648
+ }
649
+ function buildBugReport(input) {
650
+ const used = new Set(input.usedOnPage);
651
+ const changed = Object.keys(input.overrides);
652
+ const keys = Object.keys(input.flags).sort((a4, b) => Number(used.has(b)) - Number(used.has(a4)) || a4.localeCompare(b));
653
+ const rows = keys.map((key) => {
654
+ const flag = input.flags[key];
655
+ let why = explainReason(flag.reason).label;
656
+ if (input.overrides[key]) {
657
+ const real = input.serverFlags[key];
658
+ why += real ? ` (Flagsmith: ${real.enabled ? "on" : "off"}, ${formatValue(real.value)})` : "";
659
+ }
660
+ return `| \`${key}\` | ${flag.enabled ? "on" : "off"} | ${cell(formatValue(flag.value))} | ${cell(why)} | ${used.has(key) ? "yes" : ""} |`;
661
+ });
662
+ return [
663
+ "### Flagsmith flag state",
664
+ "",
665
+ `- **Page:** ${input.url}`,
666
+ `- **Flagsmith:** ${input.apiUrl ?? "unknown"}${input.environmentKey ? ` \xB7 environment \`${input.environmentKey}\`` : ""}`,
667
+ `- **User:** ${describeUser(input)}`,
668
+ `- **Changed in the toolbar:** ${changed.length ? changed.map((key) => `\`${key}\``).join(", ") : "nothing"}`,
669
+ `- **Captured:** ${input.takenAt.toISOString()}`,
670
+ "",
671
+ "| Flag | State | Value | Why | Used on this page |",
672
+ "| --- | --- | --- | --- | --- |",
673
+ ...rows,
674
+ "",
675
+ "_Captured with Flagsmith Toolbar_"
676
+ ].join("\n");
677
+ }
678
+
679
+ // src/store.ts
680
+ var TABS = ["flags", "viewas", "compare", "share", "experiments"];
681
+ var Store = class {
682
+ constructor(initial) {
683
+ this.listeners = /* @__PURE__ */ new Set();
684
+ this.state = initial;
685
+ }
686
+ get() {
687
+ return this.state;
688
+ }
689
+ set(patch) {
690
+ const next = typeof patch === "function" ? patch(this.state) : patch;
691
+ this.state = { ...this.state, ...next };
692
+ for (const listener of this.listeners) listener();
693
+ }
694
+ subscribe(listener) {
695
+ this.listeners.add(listener);
696
+ return () => this.listeners.delete(listener);
697
+ }
698
+ };
699
+ function sanitizeSaved(raw) {
700
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
701
+ const input = raw;
702
+ const saved = {};
703
+ if ("overrides" in input) saved.overrides = sanitizeOverrides(input.overrides);
704
+ if ("persona" in input) saved.persona = sanitizePersona(input.persona);
705
+ if (typeof input.welcomeDismissed === "boolean") saved.welcomeDismissed = input.welcomeDismissed;
706
+ if (typeof input.open === "boolean") saved.open = input.open;
707
+ const tab = input.tab === "events" ? "experiments" : input.tab;
708
+ if (typeof tab === "string" && TABS.includes(tab)) saved.tab = tab;
709
+ return saved;
710
+ }
711
+ function loadSaved(key) {
712
+ try {
713
+ const raw = window.localStorage.getItem(key);
714
+ return raw ? sanitizeSaved(JSON.parse(raw)) : {};
715
+ } catch {
716
+ return {};
717
+ }
718
+ }
719
+ function save(key, value) {
720
+ try {
721
+ window.localStorage.setItem(key, JSON.stringify(value));
722
+ } catch {
723
+ }
724
+ }
725
+
726
+ // ../../node_modules/.pnpm/preact@11.2.0/node_modules/preact/dist/preact.mjs
727
+ var n;
728
+ var t;
729
+ var r;
730
+ var u;
731
+ var i;
732
+ var f;
733
+ var o;
734
+ var e;
735
+ var l;
736
+ var c;
737
+ var a;
738
+ var s;
739
+ var h = /* @__PURE__ */ Symbol.for("pv");
740
+ var p = {};
741
+ var y = [];
742
+ var v = /^m(i|n|o|s|text|space)$/;
743
+ var w = Array.isArray;
744
+ var d = y.slice;
745
+ var _ = Object.assign;
746
+ function g(n2) {
747
+ n2 && n2.parentNode && n2.remove();
748
+ }
749
+ function m(r3, u3, i3, f4, o4) {
750
+ var e3 = { type: r3, props: u3, key: i3, ref: f4, __k: null, __: null, __b: 0, __e: null, __c: null, constructor: h, __v: o4 || ++t, __i: -1, __u: 0 };
751
+ return !o4 && n.vnode && n.vnode(e3), e3;
752
+ }
753
+ function $(n2) {
754
+ return n2.children;
755
+ }
756
+ function x(n2, t3) {
757
+ this.props = n2, this.context = t3, this.__g = 0;
758
+ }
759
+ function S(n2, t3) {
760
+ if (null == t3) return n2.__ && S(n2.__, n2.__i + 1);
761
+ for (var r3; t3 < n2.__k.length; t3++) if ((r3 = n2.__k[t3]) && r3.__e) return r3.__e;
762
+ return "function" != typeof n2.type || n2.props.__P ? null : S(n2);
763
+ }
764
+ function C(t3) {
765
+ var r3, u3 = t3.__v, i3 = u3.__e, f4 = [], o4 = [], e3 = t3.__P;
766
+ e3 && ((r3 = _({ constructor: h }, u3)).__v = u3.__v + 1, n.vnode && n.vnode(r3), z(e3, r3, u3, t3.__n, e3.namespaceURI, 32 & u3.__u ? [i3] : null, f4, i3 || S(u3), 32 & u3.__u, o4), r3.__v = u3.__v, r3.__.__k[r3.__i] = r3, E(f4, r3, o4), u3.__ = u3.__e = null, r3.__e != i3 && j(r3));
767
+ }
768
+ function j(n2) {
769
+ if ((n2 = n2.__) && n2.__c && !n2.props.__P) return n2.__e = null, n2.__k.some(function(t3) {
770
+ return t3 && (n2.__e = t3.__e);
771
+ }), j(n2);
772
+ }
773
+ function L(t3) {
774
+ (8 & t3.__g || (t3.__g |= 8, u.push(t3), f++)) && i == n.debounceRendering || ((i = n.debounceRendering) || queueMicrotask)(H);
775
+ }
776
+ function H() {
777
+ try {
778
+ for (var n2, t3 = 1; u.length; ) u.length > t3 && u.sort(o), n2 = u.shift(), t3 = u.length, 8 & n2.__g && C(n2);
779
+ } finally {
780
+ (f = u.length) && (i || queueMicrotask)(H);
781
+ }
782
+ }
783
+ function I(n2, t3, r3, u3, i3, f4, o4, e3, l3, c3, a4) {
784
+ var s3, h3, v3, w3, d3, _3, g3 = u3.__k || y, k2 = t3.length;
785
+ for (l3 = q(r3, t3, g3, l3, k2), s3 = 0; s3 < k2; s3++) null != (v3 = r3.__k[s3]) && (h3 = ~v3.__i && g3[v3.__i] || p, v3.__i = s3, _3 = z(n2, v3, h3, i3, f4, o4, e3, l3, c3, a4), w3 = v3.__e, (h3.ref != v3.ref || 8 & h3.__u) && (h3.ref && G(h3.ref, null, v3, h3), v3.ref && a4.push(v3.ref, v3.__c || w3, v3)), d3 = d3 || w3, 4 & v3.__u ? (l3 = A(v3, l3, n2, !h3.__v), h3.__e && (h3.__e = null)) : "function" == typeof v3.type && void 0 !== _3 ? l3 = _3 : w3 && (l3 = w3.nextSibling), v3.__u &= -21);
786
+ return r3.__e = d3, l3;
787
+ }
788
+ function q(n2, t3, r3, u3, i3) {
789
+ var f4, o4, e3, l3, c3, a4, s3, p3, y3, v3 = r3.length, d3 = v3, _3 = 0, g3 = 0, k2 = n2.__k = Array(i3);
790
+ for (f4 = 0; f4 < i3; f4++) null != (o4 = t3[f4]) && "boolean" != typeof o4 && "function" != typeof o4 ? ("object" != typeof o4 || o4.constructor === String ? o4 = k2[f4] = m(null, o4) : w(o4) ? o4 = k2[f4] = m($, { children: o4 }) : o4.constructor === h && o4.__b ? o4 = k2[f4] = m(o4.type, o4.props, o4.key, o4.ref, o4.__v) : k2[f4] = o4, l3 = f4 + _3, o4.__ = n2, o4.__b = n2.__b + 1, e3 = null, ~(c3 = o4.__i = P(o4, r3, l3, d3)) && (d3--, (e3 = r3[c3]) && (e3.__u |= 2)), e3 && e3.__v ? (o4.__u |= 16, c3 == l3 - 1 ? _3-- : c3 == l3 + 1 ? _3++ : c3 != l3 && (c3 > l3 ? _3-- : _3++, g3 = 1)) : (~c3 || (i3 > v3 ? _3-- : i3 < v3 && _3++), "function" != typeof o4.type && (o4.__u |= 4))) : k2[f4] = null;
791
+ if (g3) {
792
+ for (a4 = [], s3 = [], f4 = 0; f4 < i3; f4++) if ((o4 = k2[f4]) && 16 & o4.__u) {
793
+ for (_3 = 0, p3 = a4.length; _3 < p3; ) a4[y3 = _3 + p3 >> 1] < o4.__i ? _3 = y3 + 1 : p3 = y3;
794
+ a4[_3] = o4.__i, s3[f4] = _3 + 1;
795
+ }
796
+ for (_3 = a4.length; f4--; ) s3[f4] && (s3[f4] == _3 ? _3-- : k2[f4].__u |= 4);
797
+ }
798
+ if (d3) for (f4 = 0; f4 < v3; f4++) !(e3 = r3[f4]) || 2 & e3.__u || (e3.__e == u3 && (u3 = S(e3)), J(e3, e3));
799
+ return u3;
800
+ }
801
+ function A(n2, t3, r3, u3) {
802
+ var i3, f4, o4, e3;
803
+ if ("function" == typeof n2.type) {
804
+ if (n2.props.__P) return t3;
805
+ if (i3 = n2.__k) for (f4 = 0; f4 < i3.length; f4++) i3[f4] && (i3[f4].__ = n2, t3 = A(i3[f4], t3, r3, false));
806
+ return t3;
807
+ }
808
+ for (t3 && !t3.parentNode && (t3 = S(n2)) && !t3.parentNode && (t3 = null), o4 = n2.__e, e3 = t3; e3 && 8 == e3.nodeType; ) e3 = e3.nextSibling;
809
+ for (o4 != e3 && (!u3 && r3.moveBefore && o4.parentNode ? r3.moveBefore(o4, t3) : r3.insertBefore(o4, t3 || null)), t3 = o4; (t3 = t3 && t3.nextSibling) && 8 == t3.nodeType && !t3.data.startsWith("$s"); ) ;
810
+ return t3;
811
+ }
812
+ function P(n2, t3, r3, u3) {
813
+ var i3, f4 = n2.key, o4 = n2.type, e3 = t3[r3], l3 = e3 && !(2 & e3.__u);
814
+ if (null === e3 && null == f4 || l3 && f4 == e3.key && o4 == e3.type) return r3;
815
+ if (u3 > (l3 ? 1 : 0)) {
816
+ for (i3 = r3 - 1; i3 >= 0; i3--) if ((e3 = t3[i3]) && !(2 & e3.__u) && f4 == e3.key && o4 == e3.type) return i3;
817
+ for (i3 = r3 + 1; i3 < t3.length; i3++) if ((e3 = t3[i3]) && !(2 & e3.__u) && f4 == e3.key && o4 == e3.type) return i3;
818
+ }
819
+ return -1;
820
+ }
821
+ function T(n2, t3, r3) {
822
+ null == r3 && (r3 = ""), "-" == t3[0] ? n2.setProperty(t3, r3) : n2[t3] = r3;
823
+ }
824
+ function N(n2, t3, r3, u3, i3) {
825
+ var f4, o4;
826
+ if ("style" == t3) if ("string" == typeof r3) n2.style.cssText = r3;
827
+ else {
828
+ if ("string" == typeof u3 && (n2.style.cssText = u3 = ""), u3) for (t3 in u3) r3 && t3 in r3 || T(n2.style, t3);
829
+ if (r3) for (t3 in r3) u3 && r3[t3] == u3[t3] || T(n2.style, t3, r3[t3]);
830
+ }
831
+ else if ("o" == t3[0] && "n" == t3[1]) "function" != typeof r3 && (r3 = null), "function" != typeof u3 && (u3 = null), (n2.__e || (n2.__e = {}))[t3] = r3, r3 && u3 || (o4 = a[t3] || (a[t3] = V(t3)), (n2.__a || (n2.__a = {}))[t3] = c, f4 = t3 != (t3 = t3.replace(l, "$1")), (t3 = t3.slice(2))[0] < "a" && (t3 = t3.toLowerCase()), r3 ? n2.addEventListener(t3, o4, f4) : n2.removeEventListener(t3, o4, f4));
832
+ else {
833
+ if ("http://www.w3.org/2000/svg" == i3) t3 = t3.replace(/xlink(H|:h)/, "h").replace(/sName$/, "s");
834
+ else if ("width" != t3 && "height" != t3 && "href" != t3 && "list" != t3 && "form" != t3 && "tabIndex" != t3 && "download" != t3 && "rowSpan" != t3 && "colSpan" != t3 && "role" != t3 && "popover" != t3 && t3 in n2) try {
835
+ return void (n2[t3] = null == r3 ? "" : r3);
836
+ } catch (n3) {
837
+ }
838
+ if ("function" == typeof r3) return;
839
+ null == r3 || false === r3 && "-" != t3[4] ? n2.removeAttribute(t3) : n2.setAttribute(t3, "popover" == t3 && 1 == r3 ? "" : r3);
840
+ }
841
+ }
842
+ function V(t3) {
843
+ return function(r3) {
844
+ var u3 = this.__e;
845
+ if (u3) {
846
+ if (u3 = u3[t3], null == r3[e]) r3[e] = c++;
847
+ else if (r3[e] < this.__a[t3]) return;
848
+ return u3(n.event ? n.event(r3) : r3);
849
+ }
850
+ };
851
+ }
852
+ function z(t3, r3, u3, i3, f4, o4, e3, l3, c3, a4) {
853
+ var s3, p3, v3, d3, k2, b, m3, M, C3, j2, L2, H2, q2, A3, O, P2, T3, N2, V2 = r3.type;
854
+ if (r3.constructor !== h) return null;
855
+ 128 & u3.__u && (c3 = 32 & u3.__u, s3 = u3.__c.__z) && (r3.__u |= c3, p3 = o4 = [], 8 == s3.nodeType ? l3 = B(s3, o4) : o4.push(s3), l3 = o4[0] || l3), (s3 = n.__b) && s3(r3);
856
+ n: if ("function" == typeof V2) {
857
+ v3 = e3.length;
858
+ try {
859
+ if (M = r3.props, C3 = (s3 = V2.prototype) && s3.render, j2 = (s3 = V2.contextType) && i3[s3.__c], L2 = s3 ? j2 ? j2.props.value : s3.__ : i3, (d3 = u3.__c) ? (r3.__c = d3, 2 & d3.__g && (d3.__g |= 1)) : (C3 ? r3.__c = d3 = new V2(M, L2) : (r3.__c = d3 = new x(M, L2), d3.constructor = V2, d3.render = K), j2 && j2.sub(d3), d3.state || (d3.state = {}), d3.__n = i3, d3.__g |= 8, d3.__h = [], d3.__k = []), C3 && (d3.__s || (d3.__s = d3.state), V2.getDerivedStateFromProps && (d3.__s == d3.state && (d3.__s = _({}, d3.__s)), _(d3.__s, V2.getDerivedStateFromProps(M, d3.__s)))), k2 = d3.props, b = d3.state, d3.__v = r3, u3.__c) {
860
+ if (M !== k2 && C3 && !V2.getDerivedStateFromProps && d3.componentWillReceiveProps && d3.componentWillReceiveProps(M, L2), r3.__v == u3.__v && !(8 & d3.__g) || !(4 & d3.__g) && d3.shouldComponentUpdate && false === d3.shouldComponentUpdate(M, d3.__s, L2)) {
861
+ r3.__v != u3.__v && (d3.props = M, d3.state = d3.__s, d3.__g &= -9), r3.__e = u3.__e, r3.__k = u3.__k, r3.__k.some(function(n2) {
862
+ n2 && (n2.__ = r3);
863
+ }), y.push.apply(d3.__h, d3.__k), d3.__k = [], d3.__h.length && e3.push(d3), l3 = S(u3);
864
+ break n;
865
+ }
866
+ d3.componentWillUpdate && d3.componentWillUpdate(M, d3.__s, L2), C3 && d3.componentDidUpdate && d3.__h.push(function() {
867
+ d3.componentDidUpdate(k2, b, m3);
868
+ });
869
+ } else C3 && !V2.getDerivedStateFromProps && d3.componentWillMount && d3.componentWillMount(), C3 && d3.componentDidMount && d3.__h.push(d3.componentDidMount);
870
+ d3.context = L2, d3.props = M, d3.__P = t3, d3.__g &= -5, H2 = n.__r, q2 = C3 ? 25 : 0;
871
+ do {
872
+ d3.__g &= -9, H2 && H2(r3), s3 = d3.render(d3.props, d3.state = d3.__s, d3.context);
873
+ } while (8 & d3.__g && ++q2 < 25);
874
+ C3 && (y.push.apply(d3.__h, d3.__k), d3.__k = []), d3.state = d3.__s, d3.getChildContext && (i3 = _({}, i3, d3.getChildContext())), C3 && u3.__c && d3.getSnapshotBeforeUpdate && (m3 = d3.getSnapshotBeforeUpdate(k2, b)), A3 = s3 && s3.type === $ && null == s3.key ? s3.props.children : s3, M.__P && (s3 = l3, f4 = (t3 = M.__P).namespaceURI, c3 = o4 = null, u3.props && u3.props.__P != t3 && (u3.__k.some(function(n2) {
875
+ n2 && J(n2, n2);
876
+ }), u3.__k = null), l3 = u3.__k ? S(u3, 0) : null), l3 = I(t3, w(A3) ? A3 : [A3], r3, u3, i3, f4, o4, e3, l3, c3, a4), M.__P && (r3.__e = null, l3 = s3), r3.__u &= -161, p3 && p3.some(g), d3.__h.length && e3.push(d3), 1 & d3.__g && (d3.__g &= -4);
877
+ } catch (t4) {
878
+ if (e3.length = v3, r3.__v = null, c3 || o4) if (t4 && t4.then) {
879
+ if (r3.__u |= 128 | c3, o4) {
880
+ for (~(T3 = o4.indexOf(l3 || void 0)) || (T3 = o4.length); (N2 = o4[T3 - 1]) && 8 == N2.nodeType; ) T3--;
881
+ for (; T3 < o4.length; T3++) if (N2 = o4[T3]) if (o4[T3] = null, O) {
882
+ if (N2 == P2) break;
883
+ } else {
884
+ if (8 != N2.nodeType) break;
885
+ N2.data.startsWith("$s") && (P2 = B(O = N2));
886
+ }
887
+ }
888
+ if (!O) {
889
+ for (; l3 && 8 == l3.nodeType && l3.nextSibling; ) l3 = l3.nextSibling;
890
+ O = l3;
891
+ }
892
+ (s3 = B(O = r3.__c.__z || (r3.__c.__z = O))) ? (r3.__e = O, l3 = s3) : r3.__e = l3, l3 = l3 && l3.nextSibling;
893
+ } else o4 && o4.some(g);
894
+ else r3.__e = u3.__e;
895
+ r3.__k || (r3.__k = u3.__k || []), t4 && t4.then || D(r3), n.__e(t4, r3, u3);
896
+ }
897
+ } else l3 = r3.__e = F(u3.__e, r3, u3, i3, f4, o4, e3, c3, a4, t3);
898
+ return (s3 = n.diffed) && s3(r3), l3;
899
+ }
900
+ function B(n2, t3) {
901
+ if (n2 && 8 == n2.nodeType && n2.data.startsWith("$s")) for (var r3 = 1; n2 = n2.nextSibling; ) {
902
+ if (8 == n2.nodeType) {
903
+ if (n2.data.startsWith("$s")) r3++;
904
+ else if (n2.data.startsWith("/$s") && !--r3) return n2;
905
+ }
906
+ t3 && t3.push(n2);
907
+ }
908
+ }
909
+ function D(n2) {
910
+ n2 && (n2.__c && (n2.__c.__g |= 4), n2.__k && n2.__k.some(D));
911
+ }
912
+ function E(t3, r3, u3) {
913
+ for (var i3 = 0; i3 < u3.length; ) G(u3[i3++], u3[i3++], u3[i3++]);
914
+ n.__c && n.__c(r3, t3), t3.some(function(r4) {
915
+ try {
916
+ t3 = r4.__h, r4.__h = [], t3.some(function(n2) {
917
+ n2.call(r4);
918
+ });
919
+ } catch (t4) {
920
+ n.__e(t4, r4.__v);
921
+ }
922
+ });
923
+ }
924
+ function F(t3, r3, u3, i3, f4, o4, e3, l3, c3, a4) {
925
+ var s3, h3, y3, _3, k2, b, m3, M, $2 = u3.props || p, x2 = r3.props, C3 = r3.type;
926
+ if ("svg" == C3 ? f4 = "http://www.w3.org/2000/svg" : "math" == C3 ? f4 = "http://www.w3.org/1998/Math/MathML" : f4 || (f4 = "http://www.w3.org/1999/xhtml"), o4) {
927
+ for (s3 = 0; s3 < o4.length; s3++) if ((k2 = o4[s3]) && (C3 ? k2.localName == C3 : 3 == k2.nodeType)) {
928
+ t3 = k2, o4[s3] = null;
929
+ break;
930
+ }
931
+ }
932
+ if (!t3) {
933
+ if (M = a4.ownerDocument || document, !C3) return M.createTextNode(x2);
934
+ t3 = M.createElementNS(f4, C3, x2.is ? x2 : a4), l3 && (n.__m && n.__m(r3, o4), l3 = false), o4 = null;
935
+ }
936
+ if (C3) {
937
+ if (a4 = "template" == C3 && t3.content || t3, o4 = "textarea" == C3 && null != x2.defaultValue ? null : o4 && d.call(a4.childNodes), !l3 && o4) for ($2 = {}, s3 = 0; s3 < t3.attributes.length; s3++) $2[(k2 = t3.attributes[s3]).name] = k2.value;
938
+ for (s3 in $2) k2 = $2[s3], "dangerouslySetInnerHTML" == s3 ? y3 = k2 : "children" == s3 || s3 in x2 || "value" == s3 && "defaultValue" in x2 || "checked" == s3 && "defaultChecked" in x2 || N(t3, s3, null, k2, f4);
939
+ for (s3 in x2) k2 = x2[s3], "children" == s3 ? _3 = k2 : "dangerouslySetInnerHTML" == s3 ? h3 = k2 : "value" == s3 ? b = k2 : "checked" == s3 ? m3 = k2 : l3 && "function" != typeof k2 || $2[s3] === k2 || N(t3, s3, k2, $2[s3], f4);
940
+ h3 ? (l3 || y3 && (h3.__html == y3.__html || h3.__html == t3.innerHTML) || (t3.innerHTML = h3.__html), r3.__k = []) : (y3 && (t3.textContent = ""), ("foreignObject" == C3 || "http://www.w3.org/1998/Math/MathML" == f4 && v.test(C3)) && (f4 = "http://www.w3.org/1999/xhtml"), I(a4, w(_3) ? _3 : [_3], r3, u3, i3, f4, o4, e3, o4 ? o4[0] : u3.__k && S(u3, 0), l3, c3), o4 && o4.some(g)), l3 && "textarea" != C3 || (s3 = "value", "progress" == C3 && null == b ? t3.removeAttribute(s3) : null == b || b === t3[s3] && ("progress" != C3 || b) || N(t3, s3, b, $2[s3], f4), s3 = "checked", null != m3 && m3 != t3[s3] && N(t3, s3, m3, $2[s3], f4));
941
+ } else $2 === x2 || l3 && t3.data == x2 || (t3.data = x2);
942
+ return t3;
943
+ }
944
+ function G(t3, r3, u3, i3) {
945
+ try {
946
+ "function" == typeof t3 ? r3 ? r3.__x = t3(r3) || 1 : i3 && (i3 = i3.__c || i3.__e) && (r3 = i3.__x) && (i3.__x = null, "function" == typeof r3 ? r3() : t3(null)) : t3.current = r3;
947
+ } catch (t4) {
948
+ n.__e(t4, u3);
949
+ }
950
+ }
951
+ function J(t3, r3, u3) {
952
+ var i3, f4, o4, e3;
953
+ if (n.unmount && n.unmount(t3), !(i3 = t3.ref) || i3.current && i3.current != t3.__e || G(i3, null, r3, t3), i3 = t3.__c) {
954
+ if (i3.componentWillUnmount) try {
955
+ i3.componentWillUnmount();
956
+ } catch (t4) {
957
+ n.__e(t4, r3);
958
+ }
959
+ i3.__P = i3.__n = null;
960
+ }
961
+ if (i3 = t3.__k) for (e3 = 0; e3 < i3.length; e3++) i3[e3] && J(i3[e3], r3, "function" != typeof t3.type || u3 && !t3.props.__P);
962
+ !u3 && (i3 = t3.__c) && (i3 = i3.__z) && (f4 = B(i3, o4 = [])) && (i3 == t3.__e && o4.some(g), g(f4), g(i3)), u3 || g(t3.__e), t3.__e = t3.__c = t3.__ = null;
963
+ }
964
+ function K(n2, t3, r3) {
965
+ return this.constructor(n2, r3);
966
+ }
967
+ function Q(t3, r3) {
968
+ var u3, i3, f4, o4;
969
+ n.__ && n.__(t3, r3), 9 == r3.nodeType && (r3 = r3.documentElement), i3 = (u3 = t3 && 32 & t3.__u) ? null : r3.__k, r3.__k = m($, { children: [t3] }), f4 = [], o4 = [], z(r3, r3.__k, i3 || p, p, r3.namespaceURI, i3 ? null : r3.firstChild ? d.call(r3.childNodes) : null, f4, i3 ? i3.__e : r3.firstChild, u3, o4), E(f4, r3.__k, o4), r3.__k.props.children = null;
970
+ }
971
+ n = { __e: function(n2, t3, r3, u3) {
972
+ for (var i3, o4, e3; t3 = t3.__; ) if ((i3 = t3.__c) && !(1 & i3.__g)) {
973
+ i3.__g |= 4;
974
+ try {
975
+ if ((e3 = (o4 = i3.constructor) && o4.getDerivedStateFromError) && i3.setState(o4.getDerivedStateFromError(n2)), i3.componentDidCatch && (i3.componentDidCatch(n2, u3 || {}), e3 = 1), e3 && 8 & i3.__g) return void (i3.__g |= 2);
976
+ } catch (t4) {
977
+ n2 = t4;
978
+ }
979
+ }
980
+ throw f = 0, n2;
981
+ } }, t = 0, r = function(n2) {
982
+ return null != n2 && n2.constructor === h;
983
+ }, x.prototype.setState = function(n2, t3) {
984
+ var r3 = this.__s;
985
+ r3 && r3 != this.state || (r3 = this.__s = _({}, this.state)), "function" == typeof n2 && (n2 = n2(_({}, r3), this.props)), n2 && (_(r3, n2), this.__v && (t3 && this.__k.push(t3), L(this)));
986
+ }, x.prototype.forceUpdate = function(n2) {
987
+ this.__v && (this.__g |= 4, n2 && this.__h.push(n2), L(this));
988
+ }, x.prototype.render = $, u = [], f = 0, o = function(n2, t3) {
989
+ return n2.__v.__b - t3.__v.__b;
990
+ }, e = /* @__PURE__ */ Symbol(), l = /(PointerCapture)$|Capture$/i, c = 0, a = {}, s = 0;
991
+
992
+ // ../../node_modules/.pnpm/preact@11.2.0/node_modules/preact/hooks/dist/hooks.mjs
993
+ var t2;
994
+ var r2;
995
+ var u2;
996
+ var i2;
997
+ var o2 = Object.is;
998
+ var f2 = 0;
999
+ var c2 = [];
1000
+ var e2 = [];
1001
+ var a2 = n;
1002
+ var v2 = a2.__b;
1003
+ var l2 = a2.__r;
1004
+ var m2 = a2.diffed;
1005
+ var h2 = a2.__c;
1006
+ var s2 = a2.unmount;
1007
+ var p2 = a2.__;
1008
+ function y2(n2, t3) {
1009
+ a2.__h && a2.__h(r2, n2, f2 || t3), f2 = 0;
1010
+ var u3 = r2.__H || (r2.__H = { __: [], __h: [] });
1011
+ return n2 >= u3.__.length && u3.__.push({}), u3.__[n2];
1012
+ }
1013
+ function d2(n2) {
1014
+ return f2 = 1, _2(G2, n2);
1015
+ }
1016
+ function _2(n2, u3, i3) {
1017
+ var f4 = y2(t2++, 2);
1018
+ if (f4.t = n2, !f4.__c && (f4.__ = [i3 ? i3(u3) : G2(void 0, u3), function(n3) {
1019
+ var t3 = (f4.__N || f4.__)[0], r3 = f4.t(t3, n3);
1020
+ o2(t3, r3) || (f4.__N = [r3, f4.__[1]], f4.__c.setState({}));
1021
+ }], f4.__c = r2, !r2.__f)) {
1022
+ r2.__f = true;
1023
+ var c3 = r2.shouldComponentUpdate;
1024
+ r2.shouldComponentUpdate = function(n3, t3, r3) {
1025
+ var u4 = this.__H;
1026
+ if (!u4) return true;
1027
+ var i4 = false, f5 = this.props != n3;
1028
+ if (u4.__.some(function(n4) {
1029
+ n4.__N && (i4 = true, o2(n4.__[0], n4.__N[0]) || (f5 = true));
1030
+ }), c3) {
1031
+ var e3 = c3.call(this, n3, t3, r3);
1032
+ return i4 ? e3 || f5 : e3;
1033
+ }
1034
+ return !i4 || f5;
1035
+ };
1036
+ }
1037
+ return f4.__;
1038
+ }
1039
+ function A2(n2, u3) {
1040
+ var i3 = y2(t2++, 3);
1041
+ !a2.__s && E2(i3.__H, u3) && (i3.__P = true, i3.__ = n2, i3.u = u3, r2.__H.__h.push(i3));
1042
+ }
1043
+ function T2(n2) {
1044
+ return f2 = 5, w2(function() {
1045
+ return { current: n2 };
1046
+ }, []);
1047
+ }
1048
+ function w2(n2, r3) {
1049
+ var u3 = y2(t2++, 7);
1050
+ return E2(u3.__H, r3) && (u3.__ = n2(), u3.__H = r3), u3.__;
1051
+ }
1052
+ function g2() {
1053
+ var n2;
1054
+ do {
1055
+ for (; n2 = e2.shift(); ) try {
1056
+ C2(n2);
1057
+ } catch (t4) {
1058
+ a2.__e(t4, { __: (n2 = n2.__P) && n2.__v });
1059
+ }
1060
+ for (; n2 = c2.shift(); ) {
1061
+ var t3 = n2.__H;
1062
+ if (n2.__P && t3) try {
1063
+ t3.__h.some(C2), t3.__h.some(D2), t3.__h = [];
1064
+ } catch (r3) {
1065
+ t3.__h = [], a2.__e(r3, n2.__v);
1066
+ }
1067
+ }
1068
+ } while (e2.length);
1069
+ }
1070
+ a2.__b = function(n2) {
1071
+ r2 = null, v2 && v2(n2);
1072
+ }, a2.__ = function(n2, t3) {
1073
+ n2 && t3.__k && t3.__k.__m && (n2.__m = t3.__k.__m), p2 && p2(n2, t3);
1074
+ }, a2.__r = function(n2) {
1075
+ l2 && l2(n2), t2 = 0;
1076
+ var i3 = (r2 = n2.__c).__H;
1077
+ i3 && (u2 == r2 ? r2.__h = [] : (i3.__h.some(C2), i3.__h.some(D2), t2 = 0), i3.__h = [], i3.__.some(function(n3) {
1078
+ n3.__N && (n3.__ = n3.__N), n3.u = n3.__N = void 0;
1079
+ })), u2 = r2;
1080
+ }, a2.diffed = function(n2) {
1081
+ m2 && m2(n2);
1082
+ var t3 = n2.__c;
1083
+ t3 && t3.__H && (t3.__H.__h.length && B2(c2.push(t3)), t3.__H.__.some(function(n3) {
1084
+ n3.u && (n3.__H = n3.u);
1085
+ })), u2 = r2 = null;
1086
+ }, a2.__c = function(n2, t3) {
1087
+ t3.some(function(n3) {
1088
+ try {
1089
+ n3.__h.some(C2), n3.__h = n3.__h.filter(function(n4) {
1090
+ return !n4.__ || D2(n4);
1091
+ });
1092
+ } catch (t4) {
1093
+ n3.__h = [function() {
1094
+ throw t4;
1095
+ }];
1096
+ }
1097
+ }), h2 && h2(n2, t3);
1098
+ }, a2.unmount = function(n2) {
1099
+ s2 && s2(n2);
1100
+ var t3, r3, u3 = n2.__c;
1101
+ u3 && u3.__H && (u3.__H.__.some(function(u4) {
1102
+ try {
1103
+ if (u4.__P && u4.__c) {
1104
+ if (void 0 === r3) {
1105
+ for (r3 = n2.__; r3 && (!r3.__c || !r3.__c.__P); ) r3 = r3.__;
1106
+ r3 = r3 && r3.__c;
1107
+ }
1108
+ u4.__P = r3, B2(e2.push(u4));
1109
+ } else C2(u4);
1110
+ } catch (n3) {
1111
+ t3 = n3;
1112
+ }
1113
+ }), u3.__H = void 0, t3 && a2.__e(t3, u3.__v));
1114
+ };
1115
+ var k = "function" == typeof requestAnimationFrame;
1116
+ function z2(n2) {
1117
+ var t3, r3 = function() {
1118
+ clearTimeout(u3), k && cancelAnimationFrame(t3), setTimeout(n2);
1119
+ }, u3 = setTimeout(r3, 35);
1120
+ k && (t3 = requestAnimationFrame(r3));
1121
+ }
1122
+ function B2(n2) {
1123
+ 1 != n2 && i2 == a2.requestAnimationFrame || ((i2 = a2.requestAnimationFrame) || z2)(g2);
1124
+ }
1125
+ function C2(n2) {
1126
+ var t3 = r2, u3 = n2.__c;
1127
+ "function" == typeof u3 && (n2.__c = void 0, u3()), r2 = t3;
1128
+ }
1129
+ function D2(n2) {
1130
+ var t3 = r2;
1131
+ n2.__c = n2.__(), r2 = t3;
1132
+ }
1133
+ function E2(n2, t3) {
1134
+ return !n2 || n2.length != t3.length || t3.some(function(t4, r3) {
1135
+ return !o2(t4, n2[r3]);
1136
+ });
1137
+ }
1138
+ function G2(n2, t3) {
1139
+ return "function" == typeof t3 ? t3(n2) : t3;
1140
+ }
1141
+
1142
+ // ../../node_modules/.pnpm/preact@11.2.0/node_modules/preact/jsx-runtime/dist/jsxRuntime.mjs
1143
+ var f3 = /* @__PURE__ */ Symbol.for("pv");
1144
+ var o3 = 0;
1145
+ function a3(t3, e3, n2, u3, a4, i3) {
1146
+ e3 || (e3 = {});
1147
+ var c3, l3, p3 = e3;
1148
+ if ("ref" in p3 && "function" != typeof t3) for (l3 in p3 = {}, e3) "ref" == l3 ? c3 = e3[l3] : p3[l3] = e3[l3];
1149
+ var s3 = { type: t3, props: p3, key: n2, ref: c3, __k: null, __: null, __b: 0, __e: null, __c: null, constructor: f3, __v: --o3, __i: -1, __u: 0 };
1150
+ return (a4 || i3) && (s3.__source = a4, s3.__self = i3), n.vnode && n.vnode(s3), s3;
1151
+ }
1152
+
1153
+ // src/ui/icons.tsx
1154
+ function Icon({ children }) {
1155
+ return /* @__PURE__ */ a3("svg", { viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", "stroke-width": "2", "stroke-linecap": "round", "stroke-linejoin": "round", "aria-hidden": "true", children });
1156
+ }
1157
+ var FlagIcon = () => /* @__PURE__ */ a3(Icon, { children: [
1158
+ /* @__PURE__ */ a3("path", { d: "M4 22V4" }),
1159
+ /* @__PURE__ */ a3("path", { d: "M4 4h12l-1.5 4L16 12H4" })
1160
+ ] });
1161
+ var CloseIcon = () => /* @__PURE__ */ a3(Icon, { children: [
1162
+ /* @__PURE__ */ a3("path", { d: "M18 6 6 18" }),
1163
+ /* @__PURE__ */ a3("path", { d: "m6 6 12 12" })
1164
+ ] });
1165
+ var ExternalIcon = () => /* @__PURE__ */ a3(Icon, { children: [
1166
+ /* @__PURE__ */ a3("path", { d: "M15 3h6v6" }),
1167
+ /* @__PURE__ */ a3("path", { d: "M10 14 21 3" }),
1168
+ /* @__PURE__ */ a3("path", { d: "M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6" })
1169
+ ] });
1170
+ var ResetIcon = () => /* @__PURE__ */ a3(Icon, { children: [
1171
+ /* @__PURE__ */ a3("path", { d: "M3 12a9 9 0 1 0 3-6.7L3 8" }),
1172
+ /* @__PURE__ */ a3("path", { d: "M3 3v5h5" })
1173
+ ] });
1174
+ var UserIcon = () => /* @__PURE__ */ a3(Icon, { children: [
1175
+ /* @__PURE__ */ a3("circle", { cx: "12", cy: "8", r: "4" }),
1176
+ /* @__PURE__ */ a3("path", { d: "M4 21a8 8 0 0 1 16 0" })
1177
+ ] });
1178
+ var LinkIcon = () => /* @__PURE__ */ a3(Icon, { children: [
1179
+ /* @__PURE__ */ a3("path", { d: "M10 13a5 5 0 0 0 7.5.5l3-3a5 5 0 0 0-7-7l-1.7 1.7" }),
1180
+ /* @__PURE__ */ a3("path", { d: "M14 11a5 5 0 0 0-7.5-.5l-3 3a5 5 0 0 0 7 7l1.7-1.7" })
1181
+ ] });
1182
+ var ClipboardIcon = () => /* @__PURE__ */ a3(Icon, { children: [
1183
+ /* @__PURE__ */ a3("rect", { x: "8", y: "2", width: "8", height: "4", rx: "1" }),
1184
+ /* @__PURE__ */ a3("path", { d: "M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2" })
1185
+ ] });
1186
+ var RefreshIcon = () => /* @__PURE__ */ a3(Icon, { children: [
1187
+ /* @__PURE__ */ a3("path", { d: "M21 12a9 9 0 0 1-15.4 6.4L3 16" }),
1188
+ /* @__PURE__ */ a3("path", { d: "M3 21v-5h5" }),
1189
+ /* @__PURE__ */ a3("path", { d: "M3 12a9 9 0 0 1 15.4-6.4L21 8" }),
1190
+ /* @__PURE__ */ a3("path", { d: "M21 3v5h-5" })
1191
+ ] });
1192
+ var CheckIcon = () => /* @__PURE__ */ a3(Icon, { children: /* @__PURE__ */ a3("path", { d: "m5 12 5 5L20 7" }) });
1193
+ var AlertIcon = () => /* @__PURE__ */ a3(Icon, { children: [
1194
+ /* @__PURE__ */ a3("path", { d: "M10.3 3.9 1.8 18a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0Z" }),
1195
+ /* @__PURE__ */ a3("path", { d: "M12 9v4" }),
1196
+ /* @__PURE__ */ a3("path", { d: "M12 17h.01" })
1197
+ ] });
1198
+ var InfoIcon = () => /* @__PURE__ */ a3(Icon, { children: [
1199
+ /* @__PURE__ */ a3("circle", { cx: "12", cy: "12", r: "10" }),
1200
+ /* @__PURE__ */ a3("path", { d: "M12 16v-4" }),
1201
+ /* @__PURE__ */ a3("path", { d: "M12 8h.01" })
1202
+ ] });
1203
+ var FlaskIcon = () => /* @__PURE__ */ a3(Icon, { children: [
1204
+ /* @__PURE__ */ a3("path", { d: "M9 3h6" }),
1205
+ /* @__PURE__ */ a3("path", { d: "M10 3v6.5L4.5 19a1.5 1.5 0 0 0 1.3 2h12.4a1.5 1.5 0 0 0 1.3-2L14 9.5V3" }),
1206
+ /* @__PURE__ */ a3("path", { d: "M7.5 15h9" })
1207
+ ] });
1208
+ var CompareIcon = () => /* @__PURE__ */ a3(Icon, { children: [
1209
+ /* @__PURE__ */ a3("path", { d: "M8 3 4 7l4 4" }),
1210
+ /* @__PURE__ */ a3("path", { d: "M4 7h16" }),
1211
+ /* @__PURE__ */ a3("path", { d: "m16 21 4-4-4-4" }),
1212
+ /* @__PURE__ */ a3("path", { d: "M20 17H4" })
1213
+ ] });
1214
+
1215
+ // src/ui/CompareTab.tsx
1216
+ function shortLabel(controller, subject) {
1217
+ if (subject === "page") return "This page";
1218
+ if (subject === "anonymous") return "Anonymous";
1219
+ return controller.subjectLabel(subject).split("\xB7")[0].trim();
1220
+ }
1221
+ function CompareTab({ controller, state }) {
1222
+ const subjects = controller.compareSubjects();
1223
+ const { compareA: a4, compareB: b, compareStatus: status } = state;
1224
+ const opened = T2(false);
1225
+ A2(() => {
1226
+ const latest = controller.store.get();
1227
+ const usesPage = latest.compareA === "page" || latest.compareB === "page";
1228
+ const first = !opened.current;
1229
+ opened.current = true;
1230
+ if (usesPage || first && latest.compareStatus !== "done") void controller.compare(latest.compareA, latest.compareB);
1231
+ }, [state.serverFlags, state.overrides]);
1232
+ const comparison = state.compareResult ? compareFlags(state.compareResult.a, state.compareResult.b) : null;
1233
+ const total = comparison ? comparison.differ.length + comparison.same.length : 0;
1234
+ const labelA = shortLabel(controller, a4);
1235
+ const labelB = shortLabel(controller, b);
1236
+ return /* @__PURE__ */ a3("div", { class: "fst-stack", children: [
1237
+ /* @__PURE__ */ a3("div", { class: "fst-card fst-compare-pick", children: [
1238
+ /* @__PURE__ */ a3(Picker, { id: "fst-compare-a", label: "User A", value: a4, subjects, onChange: (next) => void controller.pickCompare("a", next) }),
1239
+ /* @__PURE__ */ a3("button", { class: "fst-icon-btn fst-swap", "aria-label": "Swap users A and B", title: "Swap", onClick: () => void controller.swapCompare(), children: /* @__PURE__ */ a3(CompareIcon, {}) }),
1240
+ /* @__PURE__ */ a3(Picker, { id: "fst-compare-b", label: "User B", value: b, subjects, onChange: (next) => void controller.pickCompare("b", next) })
1241
+ ] }),
1242
+ status === "loading" && /* @__PURE__ */ a3("p", { class: "fst-loading", children: [
1243
+ /* @__PURE__ */ a3("span", { class: "fst-spinner", "aria-hidden": "true" }),
1244
+ " Asking Flagsmith about both users\u2026"
1245
+ ] }),
1246
+ status === "error" && /* @__PURE__ */ a3("p", { class: "fst-error", children: state.compareError }),
1247
+ comparison && status !== "error" && /* @__PURE__ */ a3($, { children: [
1248
+ /* @__PURE__ */ a3("p", { class: "fst-compare-summary", role: "status", children: comparison.differ.length === 0 ? /* @__PURE__ */ a3($, { children: [
1249
+ /* @__PURE__ */ a3("strong", { children: labelA }),
1250
+ " and ",
1251
+ /* @__PURE__ */ a3("strong", { children: labelB }),
1252
+ " see the same ",
1253
+ total,
1254
+ " flags."
1255
+ ] }) : /* @__PURE__ */ a3($, { children: [
1256
+ /* @__PURE__ */ a3("strong", { children: [
1257
+ comparison.differ.length,
1258
+ " of ",
1259
+ total,
1260
+ " flags"
1261
+ ] }),
1262
+ " ",
1263
+ "differ between ",
1264
+ labelA,
1265
+ " and ",
1266
+ labelB,
1267
+ "."
1268
+ ] }) }),
1269
+ comparison.differ.length > 0 && /* @__PURE__ */ a3("ul", { class: "fst-list", children: comparison.differ.map((row) => /* @__PURE__ */ a3(CompareItem, { row, labelA, labelB }, row.key)) }),
1270
+ comparison.same.length > 0 && /* @__PURE__ */ a3("details", { class: "fst-same", children: [
1271
+ /* @__PURE__ */ a3("summary", { children: [
1272
+ "Same for both (",
1273
+ comparison.same.length,
1274
+ ")"
1275
+ ] }),
1276
+ /* @__PURE__ */ a3("div", { class: "fst-chips", children: comparison.same.map((row) => /* @__PURE__ */ a3("code", { class: "fst-chip", children: row.key })) })
1277
+ ] })
1278
+ ] }),
1279
+ /* @__PURE__ */ a3("p", { class: "fst-note", children: "Flagsmith evaluates each user live, with its real segments, splits and experiments. Users without an identity are transient, so nothing is saved and your page doesn't change." })
1280
+ ] });
1281
+ }
1282
+ function Picker({
1283
+ id,
1284
+ label,
1285
+ value,
1286
+ subjects,
1287
+ onChange
1288
+ }) {
1289
+ return /* @__PURE__ */ a3("div", { class: "fst-picker", children: [
1290
+ /* @__PURE__ */ a3("label", { class: "fst-label", for: id, children: label }),
1291
+ /* @__PURE__ */ a3("select", { id, class: "fst-input fst-select", value, onChange: (event) => onChange(event.currentTarget.value), children: subjects.map((subject) => /* @__PURE__ */ a3("option", { value: subject.id, children: subject.label })) })
1292
+ ] });
1293
+ }
1294
+ function CompareItem({ row, labelA, labelB }) {
1295
+ return /* @__PURE__ */ a3("li", { class: "fst-flag fst-compare-row", children: [
1296
+ /* @__PURE__ */ a3("div", { class: "fst-compare-key", children: /* @__PURE__ */ a3("code", { children: row.key }) }),
1297
+ /* @__PURE__ */ a3(Side, { label: labelA, flag: row.a }),
1298
+ /* @__PURE__ */ a3(Side, { label: labelB, flag: row.b })
1299
+ ] });
1300
+ }
1301
+ function Side({ label, flag }) {
1302
+ if (!flag) {
1303
+ return /* @__PURE__ */ a3("div", { class: "fst-side", children: [
1304
+ /* @__PURE__ */ a3("span", { class: "fst-side-label", children: label }),
1305
+ /* @__PURE__ */ a3("span", { class: "fst-muted", children: "Not sent for this user" })
1306
+ ] });
1307
+ }
1308
+ const why = explainReason(flag.reason);
1309
+ return /* @__PURE__ */ a3("div", { class: "fst-side", children: [
1310
+ /* @__PURE__ */ a3("span", { class: "fst-side-label", title: label, children: label }),
1311
+ /* @__PURE__ */ a3("span", { class: `fst-state${flag.enabled ? " is-on" : ""}`, children: flag.enabled ? "On" : "Off" }),
1312
+ /* @__PURE__ */ a3("span", { class: "fst-side-value", title: formatValue(flag.value), children: formatValue(flag.value) }),
1313
+ /* @__PURE__ */ a3("span", { class: `fst-reason fst-reason--${why.kind}`, title: why.detail, children: why.label })
1314
+ ] });
1315
+ }
1316
+
1317
+ // src/ui/ExperimentsTab.tsx
1318
+ var time = (at) => new Date(at).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", second: "2-digit" });
1319
+ function ExperimentsTab({ controller, state }) {
1320
+ const rows = controller.experiments();
1321
+ const identity = controller.currentIdentity();
1322
+ return /* @__PURE__ */ a3("div", { class: "fst-stack", children: [
1323
+ controller.isPreviewing() && /* @__PURE__ */ a3("div", { class: "fst-callout", children: [
1324
+ /* @__PURE__ */ a3(InfoIcon, {}),
1325
+ /* @__PURE__ */ a3("span", { children: "You're previewing, so the toolbar holds events back. Test visits never count in your real experiment results." })
1326
+ ] }),
1327
+ /* @__PURE__ */ a3("div", { class: "fst-section-title", children: "Experiments on this page" }),
1328
+ rows.length === 0 ? /* @__PURE__ */ a3("div", { class: "fst-card fst-muted", children: identity ? "None of the flags for this user are in a running experiment." : "Flagsmith only puts identified users into experiments, and nobody is identified yet. Use View as, or sign in to your app, to see them here." }) : /* @__PURE__ */ a3("ul", { class: "fst-list", children: rows.map((row) => /* @__PURE__ */ a3(ExperimentCard, { row, previewing: controller.isPreviewing() }, row.key)) }),
1329
+ /* @__PURE__ */ a3("div", { class: "fst-section-title", children: [
1330
+ "Events",
1331
+ state.events.length ? ` (${state.events.length})` : ""
1332
+ ] }),
1333
+ /* @__PURE__ */ a3(EventList, { events: state.events })
1334
+ ] });
1335
+ }
1336
+ var TONE = {
1337
+ recorded: "good",
1338
+ held: "neutral",
1339
+ previewing: "neutral",
1340
+ waiting: "neutral",
1341
+ missing: "bad",
1342
+ "events-off": "bad",
1343
+ "not-read": "neutral",
1344
+ "not-enrolled": "neutral",
1345
+ disabled: "neutral"
1346
+ };
1347
+ function statusText(row, previewing) {
1348
+ const at = row.exposure ? time(row.exposure.at) : "";
1349
+ switch (row.state) {
1350
+ case "recorded":
1351
+ return `Exposure recorded at ${at}, so this visit counts.`;
1352
+ case "held":
1353
+ return previewing ? `Exposure held back at ${at} because you're previewing, so this visit isn't counted.` : `Exposure held back at ${at}, while you were previewing. Reload the page to record a real one.`;
1354
+ case "previewing":
1355
+ return "You're previewing, so any exposure is held back and this visit isn't counted.";
1356
+ case "waiting":
1357
+ return "Waiting for the page to record the exposure\u2026";
1358
+ case "missing":
1359
+ return "No exposure recorded. The page shows this variant but never records that the user saw it, so they won't be counted. Read the flag with getExperimentFlag, or useExperiment in React.";
1360
+ case "events-off":
1361
+ return "Exposures can't be recorded, because Flagsmith was started without enableEvents.";
1362
+ case "not-read":
1363
+ return "This page doesn't use this flag.";
1364
+ case "not-enrolled":
1365
+ return "Flagsmith didn't put this user in the experiment, so they get the control value and aren't counted.";
1366
+ case "disabled":
1367
+ return "The flag is off for this user, so there's nothing to expose.";
1368
+ }
1369
+ }
1370
+ function ExperimentCard({ row, previewing }) {
1371
+ const tone = TONE[row.state];
1372
+ return /* @__PURE__ */ a3("li", { class: `fst-exp fst-exp--${tone}`, children: [
1373
+ /* @__PURE__ */ a3("div", { class: "fst-exp-head", children: [
1374
+ /* @__PURE__ */ a3(FlaskIcon, {}),
1375
+ /* @__PURE__ */ a3("strong", { children: row.name })
1376
+ ] }),
1377
+ /* @__PURE__ */ a3("div", { class: "fst-exp-meta", children: [
1378
+ /* @__PURE__ */ a3("code", { children: row.key }),
1379
+ row.inExperiment ? /* @__PURE__ */ a3("span", { children: [
1380
+ "in the experiment, sees ",
1381
+ /* @__PURE__ */ a3("strong", { children: formatValue(row.value) })
1382
+ ] }) : /* @__PURE__ */ a3("span", { children: [
1383
+ "not enrolled, sees ",
1384
+ formatValue(row.value)
1385
+ ] })
1386
+ ] }),
1387
+ /* @__PURE__ */ a3("p", { class: "fst-exp-status", children: [
1388
+ tone === "good" ? /* @__PURE__ */ a3(CheckIcon, {}) : tone === "bad" ? /* @__PURE__ */ a3(AlertIcon, {}) : /* @__PURE__ */ a3(InfoIcon, {}),
1389
+ /* @__PURE__ */ a3("span", { children: statusText(row, previewing) })
1390
+ ] }),
1391
+ row.state === "missing" && /* @__PURE__ */ a3("pre", { class: "fst-pre", children: `flagsmith.getExperimentFlag('${row.key}')` })
1392
+ ] });
1393
+ }
1394
+ var STATUS_NOTE = {
1395
+ sent: "",
1396
+ held: " \xB7 held back: preview",
1397
+ off: " \xB7 not sent: enableEvents is off",
1398
+ "no-identity": " \xB7 not sent: no user identified"
1399
+ };
1400
+ function EventList({ events }) {
1401
+ if (events.length === 0) {
1402
+ return /* @__PURE__ */ a3("div", { class: "fst-empty", children: [
1403
+ /* @__PURE__ */ a3("p", { children: /* @__PURE__ */ a3("strong", { children: "No events yet" }) }),
1404
+ /* @__PURE__ */ a3("p", { children: [
1405
+ "Events appear here as your app sends them: exposures from ",
1406
+ /* @__PURE__ */ a3("code", { children: "getExperimentFlag" }),
1407
+ " and",
1408
+ " ",
1409
+ /* @__PURE__ */ a3("code", { children: "trackExposureEvent" }),
1410
+ ", and conversions from ",
1411
+ /* @__PURE__ */ a3("code", { children: "trackEvent" }),
1412
+ "."
1413
+ ] })
1414
+ ] });
1415
+ }
1416
+ return /* @__PURE__ */ a3("ul", { class: "fst-events", children: events.map((event) => /* @__PURE__ */ a3("li", { class: `fst-event${event.status === "sent" ? "" : " is-unsent"}`, children: [
1417
+ /* @__PURE__ */ a3("span", { class: `fst-chip fst-chip--${event.kind}`, children: event.kind === "exposure" ? "Exposure" : "Event" }),
1418
+ /* @__PURE__ */ a3("code", { children: event.name }),
1419
+ event.value !== void 0 && event.value !== null && /* @__PURE__ */ a3("span", { class: "fst-muted", children: [
1420
+ "= ",
1421
+ String(event.value)
1422
+ ] }),
1423
+ /* @__PURE__ */ a3("span", { class: "fst-event-meta", children: [
1424
+ time(event.at),
1425
+ " \xB7 ",
1426
+ event.identifier ?? "no identity",
1427
+ STATUS_NOTE[event.status]
1428
+ ] })
1429
+ ] }, event.id)) });
1430
+ }
1431
+
1432
+ // src/flag-list.ts
1433
+ var FLAG_TYPE_LABELS = {
1434
+ onoff: "On/off",
1435
+ number: "Number",
1436
+ json: "JSON",
1437
+ text: "Text",
1438
+ variant: "Variant"
1439
+ };
1440
+ var NUMERIC = /^-?\d+(\.\d+)?$/;
1441
+ function flagType(flag) {
1442
+ if (typeof flag.variant === "string" && flag.variant !== "") return "variant";
1443
+ const { value } = flag;
1444
+ if (value === null || value === void 0 || value === "") return "onoff";
1445
+ if (typeof value === "number") return Number.isFinite(value) ? "number" : "text";
1446
+ if (typeof value !== "string") return "text";
1447
+ const trimmed = value.trim();
1448
+ if (NUMERIC.test(trimmed)) return "number";
1449
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
1450
+ try {
1451
+ const parsed = JSON.parse(trimmed);
1452
+ if (parsed !== null && typeof parsed === "object") return "json";
1453
+ } catch {
1454
+ }
1455
+ }
1456
+ return "text";
1457
+ }
1458
+ function matchesSearch(key, flag, search) {
1459
+ const query = search.trim().toLowerCase();
1460
+ return !query || key.toLowerCase().includes(query) || String(flag?.value ?? "").toLowerCase().includes(query);
1461
+ }
1462
+ function flagGroups(input) {
1463
+ const keys = Object.keys(input.flags).filter((key) => matchesSearch(key, input.flags[key], input.search)).sort();
1464
+ if (input.filter === "page") return nonEmpty([{ id: "all", title: null, keys: keys.filter((key) => key in input.reads) }]);
1465
+ if (input.filter === "changed") return nonEmpty([{ id: "all", title: null, keys: keys.filter((key) => key in input.overrides) }]);
1466
+ return nonEmpty([
1467
+ { id: "page", title: "On this page", keys: keys.filter((key) => key in input.reads) },
1468
+ { id: "other", title: "Other flags", keys: keys.filter((key) => !(key in input.reads)) }
1469
+ ]);
1470
+ }
1471
+ var nonEmpty = (groups) => groups.filter((group) => group.keys.length > 0);
1472
+
1473
+ // src/ui/hooks.ts
1474
+ function useStore(store) {
1475
+ const [state, setState] = d2(store.get());
1476
+ A2(() => {
1477
+ setState(store.get());
1478
+ return store.subscribe(() => setState(store.get()));
1479
+ }, [store]);
1480
+ return state;
1481
+ }
1482
+ async function copyText(text) {
1483
+ try {
1484
+ await navigator.clipboard.writeText(text);
1485
+ return true;
1486
+ } catch {
1487
+ }
1488
+ try {
1489
+ const textarea = document.createElement("textarea");
1490
+ textarea.value = text;
1491
+ textarea.style.cssText = "position:fixed;opacity:0;pointer-events:none;";
1492
+ document.body.appendChild(textarea);
1493
+ textarea.select();
1494
+ const copied = document.execCommand("copy");
1495
+ textarea.remove();
1496
+ return copied;
1497
+ } catch {
1498
+ return false;
1499
+ }
1500
+ }
1501
+
1502
+ // src/ui/FlagsTab.tsx
1503
+ function FlagsTab({ controller, state, flags }) {
1504
+ const keys = Object.keys(flags);
1505
+ const usedCount = keys.filter((key) => key in state.reads).length;
1506
+ const changedCount = Object.keys(state.overrides).length;
1507
+ const groups = flagGroups({ flags, reads: state.reads, overrides: state.overrides, filter: state.filter, search: state.search });
1508
+ const filters = [
1509
+ ["all", "All", keys.length],
1510
+ ["page", "On this page", usedCount],
1511
+ ["changed", "Changed", changedCount]
1512
+ ];
1513
+ return /* @__PURE__ */ a3("div", { class: "fst-stack", children: [
1514
+ !state.welcomeDismissed && /* @__PURE__ */ a3(Welcome, { controller }),
1515
+ /* @__PURE__ */ a3(ViewingAs, { controller, state }),
1516
+ /* @__PURE__ */ a3(
1517
+ "input",
1518
+ {
1519
+ class: "fst-input fst-search",
1520
+ type: "search",
1521
+ placeholder: "Search flags or values",
1522
+ "aria-label": "Search flags",
1523
+ value: state.search,
1524
+ onInput: (event) => controller.setSearch(event.currentTarget.value)
1525
+ }
1526
+ ),
1527
+ /* @__PURE__ */ a3("div", { class: "fst-segmented", role: "group", "aria-label": "Filter flags", children: filters.map(([id, label, count]) => /* @__PURE__ */ a3("button", { class: `fst-segment${state.filter === id ? " is-active" : ""}`, "aria-pressed": state.filter === id, onClick: () => controller.setFilter(id), children: [
1528
+ label,
1529
+ /* @__PURE__ */ a3("span", { class: "fst-segment-count", children: count })
1530
+ ] })) }),
1531
+ keys.length === 0 ? /* @__PURE__ */ a3("div", { class: "fst-empty", children: [
1532
+ /* @__PURE__ */ a3("p", { children: /* @__PURE__ */ a3("strong", { children: "Waiting for flags from Flagsmith\u2026" }) }),
1533
+ /* @__PURE__ */ a3("p", { children: "They appear here as soon as the SDK loads them." })
1534
+ ] }) : groups.length === 0 ? /* @__PURE__ */ a3("div", { class: "fst-empty", children: "No flags match." }) : groups.map((group) => /* @__PURE__ */ a3("div", { class: "fst-group", children: [
1535
+ group.title && /* @__PURE__ */ a3("p", { class: "fst-section-title fst-group-title", children: [
1536
+ group.title,
1537
+ /* @__PURE__ */ a3("span", { class: "fst-group-count", children: group.keys.length })
1538
+ ] }),
1539
+ /* @__PURE__ */ a3("ul", { class: "fst-list", "aria-label": group.title ?? "Flags", children: group.keys.map((key) => /* @__PURE__ */ a3(
1540
+ FlagRow,
1541
+ {
1542
+ controller,
1543
+ flagKey: key,
1544
+ flag: flags[key],
1545
+ server: state.serverFlags[key],
1546
+ changed: key in state.overrides,
1547
+ fresh: key in state.changedInFlagsmith,
1548
+ used: key in state.reads,
1549
+ pages: state.seenOn[key] ?? [],
1550
+ expanded: state.expanded === key
1551
+ },
1552
+ key
1553
+ )) })
1554
+ ] }, group.id)),
1555
+ changedCount > 0 && /* @__PURE__ */ a3("button", { class: "fst-link-btn", onClick: () => controller.resetAll(), children: [
1556
+ "Reset ",
1557
+ changedCount === 1 ? "your change" : `all ${changedCount} changes`
1558
+ ] })
1559
+ ] });
1560
+ }
1561
+ function Welcome({ controller }) {
1562
+ return /* @__PURE__ */ a3("div", { class: "fst-welcome", children: [
1563
+ /* @__PURE__ */ a3("strong", { class: "fst-welcome-title", children: "See what Flagsmith is doing on this page" }),
1564
+ /* @__PURE__ */ a3("ol", { children: [
1565
+ /* @__PURE__ */ a3("li", { children: [
1566
+ /* @__PURE__ */ a3("strong", { children: "Why:" }),
1567
+ " open any flag to see why it has its value."
1568
+ ] }),
1569
+ /* @__PURE__ */ a3("li", { children: [
1570
+ /* @__PURE__ */ a3("strong", { children: "Try the other side:" }),
1571
+ " flip a flag. Only you see the change."
1572
+ ] }),
1573
+ /* @__PURE__ */ a3("li", { children: [
1574
+ /* @__PURE__ */ a3("strong", { children: "View as and Compare:" }),
1575
+ " see the page as another user, or compare two users side by side."
1576
+ ] })
1577
+ ] }),
1578
+ /* @__PURE__ */ a3("p", { class: "fst-welcome-note", children: "The badge at the top checks your Flagsmith setup for common mistakes." }),
1579
+ /* @__PURE__ */ a3("button", { class: "fst-btn fst-btn--primary", onClick: () => controller.dismissWelcome(), children: "Got it" })
1580
+ ] });
1581
+ }
1582
+ function ViewingAs({ controller, state }) {
1583
+ const identity = controller.flagsmith.identity;
1584
+ const who = state.persona?.name ?? (identity ? `identity ${identity}` : "an anonymous visitor");
1585
+ return /* @__PURE__ */ a3("div", { class: "fst-viewing", children: [
1586
+ /* @__PURE__ */ a3(UserIcon, {}),
1587
+ /* @__PURE__ */ a3("span", { children: [
1588
+ "Flags for ",
1589
+ /* @__PURE__ */ a3("strong", { children: who })
1590
+ ] }),
1591
+ state.personaStatus === "loading" && /* @__PURE__ */ a3("span", { class: "fst-spinner", "aria-label": "Loading" }),
1592
+ /* @__PURE__ */ a3("button", { class: "fst-link-btn", onClick: () => controller.setTab("viewas"), children: "Change" })
1593
+ ] });
1594
+ }
1595
+ function FlagRow({ controller, flagKey, flag, server, changed, fresh, used, pages, expanded }) {
1596
+ const why = explainReason(flag.reason);
1597
+ const type = flagType(server ?? flag);
1598
+ return /* @__PURE__ */ a3("li", { class: `fst-flag${changed ? " is-changed" : ""}${fresh ? " is-fresh" : ""}`, children: [
1599
+ /* @__PURE__ */ a3("div", { class: "fst-flag-main", children: [
1600
+ /* @__PURE__ */ a3("button", { class: "fst-flag-summary", "aria-expanded": expanded, onClick: () => controller.toggleExpanded(flagKey), children: [
1601
+ /* @__PURE__ */ a3("span", { class: "fst-flag-name", children: [
1602
+ used && /* @__PURE__ */ a3("span", { class: "fst-used", title: "Used on this page" }),
1603
+ /* @__PURE__ */ a3("code", { children: flagKey }),
1604
+ fresh && /* @__PURE__ */ a3("span", { class: "fst-fresh", children: "Changed in Flagsmith" }),
1605
+ /* @__PURE__ */ a3("span", { class: "fst-type", children: FLAG_TYPE_LABELS[type] })
1606
+ ] }),
1607
+ /* @__PURE__ */ a3("span", { class: "fst-flag-meta", children: [
1608
+ /* @__PURE__ */ a3("span", { class: `fst-reason fst-reason--${why.kind}`, title: why.detail, children: why.label }),
1609
+ /* @__PURE__ */ a3("span", { class: "fst-flag-value", children: formatValue(flag.value) })
1610
+ ] })
1611
+ ] }),
1612
+ /* @__PURE__ */ a3(Switch, { checked: flag.enabled, label: `${flagKey}: turn ${flag.enabled ? "off" : "on"} just for you`, onChange: (enabled) => controller.setEnabled(flagKey, enabled) })
1613
+ ] }),
1614
+ expanded && /* @__PURE__ */ a3(FlagDetails, { controller, flagKey, flag, server, changed, pages })
1615
+ ] });
1616
+ }
1617
+ function FlagDetails({ controller, flagKey, flag, server, changed, pages }) {
1618
+ const [copied, setCopied] = d2(false);
1619
+ const why = explainReason(flag.reason);
1620
+ const serverWhy = explainReason(server?.reason);
1621
+ const link = controller.dashboardLink(flagKey);
1622
+ return /* @__PURE__ */ a3("div", { class: "fst-details", children: [
1623
+ /* @__PURE__ */ a3("p", { children: [
1624
+ /* @__PURE__ */ a3("strong", { children: "Why: " }),
1625
+ why.detail
1626
+ ] }),
1627
+ changed && server && /* @__PURE__ */ a3("p", { class: "fst-muted", children: [
1628
+ "Flagsmith says: ",
1629
+ /* @__PURE__ */ a3("strong", { children: server.enabled ? "on" : "off" }),
1630
+ ", ",
1631
+ formatValue(server.value),
1632
+ " (",
1633
+ serverWhy.label.toLowerCase(),
1634
+ ")"
1635
+ ] }),
1636
+ server?.reason && /* @__PURE__ */ a3("p", { class: "fst-raw", title: "The reason exactly as Flagsmith sent it", children: /* @__PURE__ */ a3("code", { children: server.reason }) }),
1637
+ /* @__PURE__ */ a3("p", { class: "fst-muted fst-pages", children: pages.length ? /* @__PURE__ */ a3($, { children: [
1638
+ "Read on:",
1639
+ " ",
1640
+ pages.map((page, index) => /* @__PURE__ */ a3("span", { children: [
1641
+ index > 0 && ", ",
1642
+ /* @__PURE__ */ a3("code", { children: page })
1643
+ ] }, page))
1644
+ ] }) : "Not read on any page yet" }),
1645
+ server?.experiment && /* @__PURE__ */ a3("p", { class: "fst-muted", children: [
1646
+ "Experiment ",
1647
+ /* @__PURE__ */ a3("strong", { children: server.experiment.name }),
1648
+ ":",
1649
+ " ",
1650
+ server.experiment.inExperiment ? "this user is in it." : "this user isn't enrolled.",
1651
+ " ",
1652
+ /* @__PURE__ */ a3("button", { class: "fst-link-btn", onClick: () => controller.setTab("experiments"), children: "See exposures" })
1653
+ ] }),
1654
+ /* @__PURE__ */ a3(ValueEditor, { controller, flagKey, flag }),
1655
+ /* @__PURE__ */ a3("div", { class: "fst-actions", children: [
1656
+ changed && /* @__PURE__ */ a3("button", { class: "fst-btn", onClick: () => controller.resetFlag(flagKey), children: [
1657
+ /* @__PURE__ */ a3(ResetIcon, {}),
1658
+ " Reset to Flagsmith"
1659
+ ] }),
1660
+ link && /* @__PURE__ */ a3("a", { class: "fst-btn", href: link, target: "_blank", rel: "noreferrer", children: [
1661
+ "Open in Flagsmith ",
1662
+ /* @__PURE__ */ a3(ExternalIcon, {})
1663
+ ] }),
1664
+ /* @__PURE__ */ a3(
1665
+ "button",
1666
+ {
1667
+ class: "fst-btn",
1668
+ onClick: async () => {
1669
+ setCopied(await copyText(flagKey));
1670
+ setTimeout(() => setCopied(false), 1500);
1671
+ },
1672
+ children: copied ? "Copied" : "Copy key"
1673
+ }
1674
+ )
1675
+ ] })
1676
+ ] });
1677
+ }
1678
+ function ValueEditor({ controller, flagKey, flag }) {
1679
+ const current2 = flag.value === null || flag.value === void 0 ? "" : String(flag.value);
1680
+ const [draft, setDraft] = d2(current2);
1681
+ const shown = T2(current2);
1682
+ A2(() => {
1683
+ if (shown.current === current2) return;
1684
+ shown.current = current2;
1685
+ setDraft(current2);
1686
+ }, [current2]);
1687
+ return /* @__PURE__ */ a3(
1688
+ "form",
1689
+ {
1690
+ class: "fst-value",
1691
+ onSubmit: (event) => {
1692
+ event.preventDefault();
1693
+ controller.setValue(flagKey, parseValueInput(draft, flag.value));
1694
+ },
1695
+ children: [
1696
+ /* @__PURE__ */ a3("label", { class: "fst-label", for: `fst-value-${flagKey}`, children: "Value, just for you" }),
1697
+ /* @__PURE__ */ a3("div", { class: "fst-value-row", children: [
1698
+ /* @__PURE__ */ a3("input", { id: `fst-value-${flagKey}`, class: "fst-input", value: draft, placeholder: "No value", onInput: (event) => setDraft(event.currentTarget.value) }),
1699
+ /* @__PURE__ */ a3("button", { class: "fst-btn fst-btn--primary", type: "submit", disabled: draft === current2, children: "Apply" })
1700
+ ] })
1701
+ ]
1702
+ }
1703
+ );
1704
+ }
1705
+ function Switch({ checked, label, onChange }) {
1706
+ return /* @__PURE__ */ a3("button", { role: "switch", "aria-checked": checked, "aria-label": label, title: label, class: `fst-switch${checked ? " is-on" : ""}`, onClick: () => onChange(!checked), children: /* @__PURE__ */ a3("span", { class: "fst-switch-thumb" }) });
1707
+ }
1708
+
1709
+ // src/ui/SetupCheck.tsx
1710
+ function SetupChip({ controller, issues, open }) {
1711
+ const toFix = issues.filter((issue) => issue.level !== "tip");
1712
+ const problem = toFix.some((issue) => issue.level === "problem");
1713
+ const tone = toFix.length === 0 ? "ok" : problem ? "problem" : "warning";
1714
+ return /* @__PURE__ */ a3(
1715
+ "button",
1716
+ {
1717
+ class: `fst-setup-chip fst-setup-chip--${tone}`,
1718
+ "aria-expanded": open,
1719
+ "aria-label": toFix.length ? `Setup check: ${toFix.length} to fix` : "Setup check: no problems found",
1720
+ title: "Check this page's Flagsmith setup",
1721
+ onClick: () => controller.toggleSetup(),
1722
+ children: [
1723
+ toFix.length ? /* @__PURE__ */ a3(AlertIcon, {}) : /* @__PURE__ */ a3(CheckIcon, {}),
1724
+ /* @__PURE__ */ a3("span", { children: toFix.length ? `${toFix.length} to fix` : "Setup OK" })
1725
+ ]
1726
+ }
1727
+ );
1728
+ }
1729
+ var ICON = { problem: AlertIcon, warning: AlertIcon, tip: InfoIcon };
1730
+ function SetupList({ controller, issues }) {
1731
+ return /* @__PURE__ */ a3("section", { class: "fst-setup", "aria-label": "Setup check", children: [
1732
+ /* @__PURE__ */ a3("div", { class: "fst-setup-head", children: [
1733
+ /* @__PURE__ */ a3("strong", { children: "Setup check" }),
1734
+ /* @__PURE__ */ a3("button", { class: "fst-icon-btn", "aria-label": "Close setup check", onClick: () => controller.toggleSetup(), children: /* @__PURE__ */ a3(CloseIcon, {}) })
1735
+ ] }),
1736
+ issues.filter((issue) => issue.level !== "tip").length === 0 && /* @__PURE__ */ a3("p", { class: "fst-setup-ok", children: [
1737
+ /* @__PURE__ */ a3(CheckIcon, {}),
1738
+ " No problems found with how this page uses Flagsmith."
1739
+ ] }),
1740
+ /* @__PURE__ */ a3("ul", { class: "fst-issues", children: issues.map((issue) => {
1741
+ const Icon2 = ICON[issue.level];
1742
+ return /* @__PURE__ */ a3("li", { class: `fst-issue fst-issue--${issue.level}`, children: [
1743
+ /* @__PURE__ */ a3(Icon2, {}),
1744
+ /* @__PURE__ */ a3("div", { children: [
1745
+ /* @__PURE__ */ a3("strong", { children: issue.title }),
1746
+ /* @__PURE__ */ a3("p", { children: issue.detail }),
1747
+ issue.fix && /* @__PURE__ */ a3("pre", { class: "fst-pre", children: issue.fix })
1748
+ ] })
1749
+ ] }, issue.id);
1750
+ }) })
1751
+ ] });
1752
+ }
1753
+
1754
+ // src/ui/ShareTab.tsx
1755
+ function ShareTab({ controller, state }) {
1756
+ const [link, setLink] = d2("");
1757
+ const [linkStatus, setLinkStatus] = d2("");
1758
+ const [report, setReport] = d2("");
1759
+ const [reportStatus, setReportStatus] = d2("");
1760
+ const changed = Object.keys(state.overrides).length;
1761
+ const summary = [state.persona ? `viewing as ${state.persona.name}` : "", changed ? `${changed} changed flag${changed === 1 ? "" : "s"}` : ""].filter(Boolean).join(" and ") || "no changes yet, so it opens the page as normal";
1762
+ return /* @__PURE__ */ a3("div", { class: "fst-stack", children: [
1763
+ /* @__PURE__ */ a3("section", { class: "fst-card", children: [
1764
+ /* @__PURE__ */ a3("div", { class: "fst-card-title", children: [
1765
+ /* @__PURE__ */ a3(LinkIcon, {}),
1766
+ " Share this preview"
1767
+ ] }),
1768
+ /* @__PURE__ */ a3("p", { children: [
1769
+ "Copy a link that opens this page with the same user and flag changes (",
1770
+ summary,
1771
+ "). Anyone who opens it with the toolbar enabled sees exactly what you see."
1772
+ ] }),
1773
+ /* @__PURE__ */ a3(
1774
+ "button",
1775
+ {
1776
+ class: "fst-btn fst-btn--primary",
1777
+ onClick: async () => {
1778
+ const url = controller.previewUrl();
1779
+ setLink(url);
1780
+ setLinkStatus(await copyText(url) ? "Link copied" : "Copy the link below");
1781
+ },
1782
+ children: "Copy preview link"
1783
+ }
1784
+ ),
1785
+ linkStatus && /* @__PURE__ */ a3("span", { class: "fst-status", children: linkStatus }),
1786
+ link && /* @__PURE__ */ a3("p", { children: /* @__PURE__ */ a3("input", { class: "fst-input fst-mono", readOnly: true, value: link, "aria-label": "Preview link", onFocus: (event) => event.currentTarget.select() }) })
1787
+ ] }),
1788
+ /* @__PURE__ */ a3("section", { class: "fst-card", children: [
1789
+ /* @__PURE__ */ a3("div", { class: "fst-card-title", children: [
1790
+ /* @__PURE__ */ a3(ClipboardIcon, {}),
1791
+ " Report a bug"
1792
+ ] }),
1793
+ /* @__PURE__ */ a3("p", { children: "Copy every flag on this page, its value and why it has it, as a Markdown table for a GitHub issue or Jira ticket." }),
1794
+ /* @__PURE__ */ a3(
1795
+ "button",
1796
+ {
1797
+ class: "fst-btn fst-btn--primary",
1798
+ onClick: async () => {
1799
+ const markdown = controller.bugReport();
1800
+ setReport(markdown);
1801
+ setReportStatus(await copyText(markdown) ? "Copied as Markdown" : "Copy the text below");
1802
+ },
1803
+ children: "Copy bug report"
1804
+ }
1805
+ ),
1806
+ reportStatus && /* @__PURE__ */ a3("span", { class: "fst-status", children: reportStatus }),
1807
+ report && /* @__PURE__ */ a3("pre", { class: "fst-pre", children: report })
1808
+ ] })
1809
+ ] });
1810
+ }
1811
+
1812
+ // src/ui/ViewAsTab.tsx
1813
+ function ViewAsTab({ controller, state }) {
1814
+ const personas = controller.options.personas ?? [];
1815
+ const identity = controller.flagsmith.identity;
1816
+ const loading = state.personaStatus === "loading";
1817
+ return /* @__PURE__ */ a3("div", { class: "fst-stack", children: [
1818
+ /* @__PURE__ */ a3("div", { class: "fst-card", children: [
1819
+ /* @__PURE__ */ a3("div", { class: "fst-muted", children: "Viewing the page as" }),
1820
+ /* @__PURE__ */ a3("div", { class: "fst-current-name", children: state.persona?.name ?? (identity ? `Identity ${identity}` : "Yourself (anonymous visitor)") }),
1821
+ loading && /* @__PURE__ */ a3("p", { class: "fst-muted", children: "Asking Flagsmith for this user's flags\u2026" }),
1822
+ state.personaError && /* @__PURE__ */ a3("p", { class: "fst-error", children: state.personaError }),
1823
+ state.persona && /* @__PURE__ */ a3("p", { children: /* @__PURE__ */ a3("button", { class: "fst-btn", disabled: loading, onClick: () => void controller.backToMe(), children: "Back to my view" }) })
1824
+ ] }),
1825
+ personas.length > 0 && /* @__PURE__ */ a3("div", { class: "fst-section-title", children: "Ready-made users" }),
1826
+ personas.length > 0 && /* @__PURE__ */ a3("ul", { class: "fst-personas", children: personas.map((persona) => /* @__PURE__ */ a3(PersonaCard, { controller, persona, active: state.persona?.name === persona.name, disabled: loading })) }),
1827
+ /* @__PURE__ */ a3("div", { class: "fst-section-title", children: "Any user" }),
1828
+ /* @__PURE__ */ a3(CustomUser, { controller, disabled: loading }),
1829
+ /* @__PURE__ */ a3("p", { class: "fst-note", children: "Flagsmith works out each user's flags live, with its real segments and splits. Users without an identity are transient, so Flagsmith saves nothing." })
1830
+ ] });
1831
+ }
1832
+ function PersonaCard({ controller, persona, active, disabled }) {
1833
+ const traits = Object.entries(persona.traits ?? {});
1834
+ return /* @__PURE__ */ a3("li", { class: `fst-persona${active ? " is-active" : ""}`, children: [
1835
+ /* @__PURE__ */ a3("div", { children: [
1836
+ /* @__PURE__ */ a3("div", { class: "fst-persona-name", children: persona.name }),
1837
+ persona.description && /* @__PURE__ */ a3("div", { class: "fst-muted", children: persona.description }),
1838
+ (persona.identifier || traits.length > 0) && /* @__PURE__ */ a3("div", { class: "fst-chips", children: [
1839
+ persona.identifier && /* @__PURE__ */ a3("span", { class: "fst-chip fst-chip--identity", children: [
1840
+ "identity: ",
1841
+ persona.identifier
1842
+ ] }),
1843
+ traits.map(([key, value]) => /* @__PURE__ */ a3("span", { class: "fst-chip", children: [
1844
+ key,
1845
+ ": ",
1846
+ String(value)
1847
+ ] }))
1848
+ ] })
1849
+ ] }),
1850
+ /* @__PURE__ */ a3("button", { class: `fst-btn${active ? "" : " fst-btn--primary"}`, disabled: active || disabled, onClick: () => void controller.viewAs(persona), children: active ? "Viewing" : "View as" })
1851
+ ] });
1852
+ }
1853
+ function CustomUser({ controller, disabled }) {
1854
+ const [identifier, setIdentifier] = d2("");
1855
+ const [traitsText, setTraitsText] = d2("country=IN\nplan=pro");
1856
+ return /* @__PURE__ */ a3(
1857
+ "form",
1858
+ {
1859
+ class: "fst-card fst-form",
1860
+ onSubmit: (event) => {
1861
+ event.preventDefault();
1862
+ const traits = parseTraits(traitsText);
1863
+ const id = identifier.trim();
1864
+ const summary = Object.entries(traits).map(([key, value]) => `${key}=${value}`).join(", ");
1865
+ void controller.viewAs({
1866
+ name: id || (summary ? `Custom user (${summary})` : "Custom user"),
1867
+ ...id ? { identifier: id } : {},
1868
+ traits
1869
+ });
1870
+ },
1871
+ children: [
1872
+ /* @__PURE__ */ a3("div", { children: [
1873
+ /* @__PURE__ */ a3("label", { class: "fst-label", for: "fst-identifier", children: "Identity (optional, uses that user's overrides)" }),
1874
+ /* @__PURE__ */ a3("input", { id: "fst-identifier", class: "fst-input", placeholder: "e.g. asha-beta-tester", value: identifier, onInput: (event) => setIdentifier(event.currentTarget.value) })
1875
+ ] }),
1876
+ /* @__PURE__ */ a3("div", { children: [
1877
+ /* @__PURE__ */ a3("label", { class: "fst-label", for: "fst-traits", children: "Traits, one per line as key=value" }),
1878
+ /* @__PURE__ */ a3("textarea", { id: "fst-traits", class: "fst-input fst-mono", rows: 3, value: traitsText, onInput: (event) => setTraitsText(event.currentTarget.value) })
1879
+ ] }),
1880
+ /* @__PURE__ */ a3("div", { children: /* @__PURE__ */ a3("button", { class: "fst-btn fst-btn--primary", type: "submit", disabled, children: "View as this user" }) })
1881
+ ]
1882
+ }
1883
+ );
1884
+ }
1885
+
1886
+ // src/ui/App.tsx
1887
+ var shortKey = (key) => key.length > 10 ? `${key.slice(0, 6)}\u2026` : key;
1888
+ var PUSH_MIN_WIDTH = 900;
1889
+ var PANEL_SPACE = "424px";
1890
+ function useHostLayout(controller, open) {
1891
+ const { layout, position } = controller.options;
1892
+ A2(() => {
1893
+ const html = document.documentElement;
1894
+ html.dataset.flagsmithToolbar = open ? "open" : "closed";
1895
+ if (layout !== "push" || !open) return;
1896
+ const property = position === "left" ? "padding-left" : "padding-right";
1897
+ const previous = html.style.getPropertyValue(property);
1898
+ const restore = () => previous ? html.style.setProperty(property, previous) : html.style.removeProperty(property);
1899
+ const apply = () => window.innerWidth >= PUSH_MIN_WIDTH ? html.style.setProperty(property, PANEL_SPACE) : restore();
1900
+ apply();
1901
+ window.addEventListener("resize", apply);
1902
+ return () => {
1903
+ window.removeEventListener("resize", apply);
1904
+ restore();
1905
+ };
1906
+ }, [open, layout, position]);
1907
+ A2(() => () => void delete document.documentElement.dataset.flagsmithToolbar, []);
1908
+ }
1909
+ function App({ controller }) {
1910
+ const state = useStore(controller.store);
1911
+ const wasOpen = T2(state.open);
1912
+ const focusOnOpen = state.open && !wasOpen.current;
1913
+ wasOpen.current = state.open;
1914
+ const changed = Object.keys(state.overrides).length;
1915
+ const previewing = Boolean(state.persona) || changed > 0;
1916
+ useHostLayout(controller, state.open);
1917
+ const pushed = controller.options.layout === "push" && state.open && window.innerWidth >= PUSH_MIN_WIDTH;
1918
+ return /* @__PURE__ */ a3("div", { class: `fst${controller.options.position === "left" ? " fst--left" : ""}${pushed ? " fst--pushed" : ""}`, children: [
1919
+ previewing && /* @__PURE__ */ a3(Banner, { controller, state, changed }),
1920
+ state.open ? /* @__PURE__ */ a3(Panel, { controller, state, focusOnOpen }) : /* @__PURE__ */ a3(Launcher, { controller, changed })
1921
+ ] });
1922
+ }
1923
+ function Launcher({ controller, changed }) {
1924
+ return /* @__PURE__ */ a3(
1925
+ "button",
1926
+ {
1927
+ class: "fst-launcher",
1928
+ onClick: () => controller.open(),
1929
+ title: `Flagsmith Toolbar (${formatHotkey(controller.options.hotkey)})`,
1930
+ "aria-label": "Flags: open Flagsmith Toolbar",
1931
+ children: [
1932
+ /* @__PURE__ */ a3(FlagIcon, {}),
1933
+ /* @__PURE__ */ a3("span", { children: "Flags" }),
1934
+ changed > 0 && /* @__PURE__ */ a3("span", { class: "fst-badge", "aria-label": `${changed} changed`, children: changed })
1935
+ ]
1936
+ }
1937
+ );
1938
+ }
1939
+ function Banner({ controller, state, changed }) {
1940
+ const parts = [];
1941
+ if (state.persona) parts.push(`Viewing as ${state.persona.name}`);
1942
+ if (changed) parts.push(`${changed} flag${changed === 1 ? "" : "s"} changed`);
1943
+ return /* @__PURE__ */ a3("div", { class: "fst-banner", role: "status", children: [
1944
+ /* @__PURE__ */ a3("span", { class: "fst-banner-tag", children: state.sharedPreview ? "Shared preview" : "Preview" }),
1945
+ /* @__PURE__ */ a3("span", { class: "fst-banner-text", children: parts.join(" \xB7 ") }),
1946
+ /* @__PURE__ */ a3("span", { class: "fst-banner-muted", children: "Only you see this" }),
1947
+ /* @__PURE__ */ a3("button", { class: "fst-banner-btn", onClick: () => void controller.exitPreview(), children: "Exit preview" })
1948
+ ] });
1949
+ }
1950
+ var REFRESH_TEXT = {
1951
+ idle: "",
1952
+ loading: "Getting the latest flags from Flagsmith\u2026",
1953
+ updated: "Updated: the highlighted flags changed in Flagsmith.",
1954
+ unchanged: "Up to date: nothing changed in Flagsmith.",
1955
+ error: "Couldn't reach Flagsmith. Try again in a moment."
1956
+ };
1957
+ function Panel({ controller, state, focusOnOpen }) {
1958
+ const panel = T2(null);
1959
+ A2(() => {
1960
+ if (focusOnOpen) panel.current?.focus({ preventScroll: true });
1961
+ }, []);
1962
+ const connection = controller.connection();
1963
+ const flags = controller.effectiveFlags();
1964
+ const flagCount = Object.keys(flags).length;
1965
+ const issues = controller.setupIssues();
1966
+ const needsAttention = controller.experiments().some((row) => row.state === "missing" || row.state === "events-off");
1967
+ const tabs = [
1968
+ ["flags", flagCount ? `Flags (${flagCount})` : "Flags", false],
1969
+ ["viewas", "View as", false],
1970
+ ["compare", "Compare", false],
1971
+ ["share", "Share", false],
1972
+ ["experiments", "Experiments", needsAttention]
1973
+ ];
1974
+ return /* @__PURE__ */ a3(
1975
+ "section",
1976
+ {
1977
+ ref: panel,
1978
+ class: "fst-panel",
1979
+ role: "dialog",
1980
+ "aria-label": "Flagsmith Toolbar",
1981
+ tabIndex: -1,
1982
+ onKeyDown: (event) => {
1983
+ if (event.key === "Escape") controller.close();
1984
+ },
1985
+ onPointerDown: (event) => {
1986
+ const target = event.target;
1987
+ if (!target.closest("input, textarea, select, [contenteditable]")) panel.current?.focus({ preventScroll: true });
1988
+ },
1989
+ children: [
1990
+ /* @__PURE__ */ a3("header", { class: "fst-header", children: [
1991
+ /* @__PURE__ */ a3("div", { class: "fst-title", children: [
1992
+ /* @__PURE__ */ a3(FlagIcon, {}),
1993
+ /* @__PURE__ */ a3("span", { children: "Flagsmith Toolbar" })
1994
+ ] }),
1995
+ /* @__PURE__ */ a3("div", { class: "fst-header-actions", children: [
1996
+ flagCount > 0 && /* @__PURE__ */ a3(SetupChip, { controller, issues, open: state.setupOpen }),
1997
+ controller.flagsmith.getFlags && /* @__PURE__ */ a3(
1998
+ "button",
1999
+ {
2000
+ class: `fst-icon-btn${state.refreshStatus === "loading" ? " is-spinning" : ""}`,
2001
+ "aria-label": "Get the latest flags from Flagsmith",
2002
+ title: "Get the latest flags from Flagsmith",
2003
+ disabled: state.refreshStatus === "loading",
2004
+ onClick: () => void controller.refresh(),
2005
+ children: /* @__PURE__ */ a3(RefreshIcon, {})
2006
+ }
2007
+ ),
2008
+ /* @__PURE__ */ a3("button", { class: "fst-icon-btn", "aria-label": "Close toolbar", title: `Close (${formatHotkey(controller.options.hotkey)})`, onClick: () => controller.close(), children: /* @__PURE__ */ a3(CloseIcon, {}) })
2009
+ ] })
2010
+ ] }),
2011
+ /* @__PURE__ */ a3("div", { class: "fst-connection", title: connection.apiUrl ?? "Not connected yet", children: [
2012
+ /* @__PURE__ */ a3("span", { class: `fst-dot${flagCount ? " fst-dot--ok" : ""}` }),
2013
+ /* @__PURE__ */ a3("span", { children: [
2014
+ connection.selfHosted ? "Self-hosted Flagsmith" : "Flagsmith",
2015
+ connection.host ? ` \xB7 ${connection.host}` : ""
2016
+ ] }),
2017
+ connection.environmentKey && /* @__PURE__ */ a3("code", { class: "fst-env", title: `Environment key ${connection.environmentKey}`, children: shortKey(connection.environmentKey) })
2018
+ ] }),
2019
+ state.refreshStatus !== "idle" && /* @__PURE__ */ a3("p", { class: `fst-refresh fst-refresh--${state.refreshStatus}`, role: "status", children: REFRESH_TEXT[state.refreshStatus] }),
2020
+ /* @__PURE__ */ a3("nav", { class: "fst-tabs", role: "tablist", "aria-label": "Toolbar sections", children: tabs.map(([id, label, attention]) => /* @__PURE__ */ a3("button", { role: "tab", "aria-selected": state.tab === id, class: `fst-tab${state.tab === id ? " is-active" : ""}`, onClick: () => controller.setTab(id), children: [
2021
+ label,
2022
+ attention && /* @__PURE__ */ a3("span", { class: "fst-tab-dot", "aria-label": "needs attention" })
2023
+ ] })) }),
2024
+ /* @__PURE__ */ a3("div", { class: "fst-body", children: [
2025
+ state.setupOpen && /* @__PURE__ */ a3(SetupList, { controller, issues }),
2026
+ state.tab === "flags" && /* @__PURE__ */ a3(FlagsTab, { controller, state, flags }),
2027
+ state.tab === "viewas" && /* @__PURE__ */ a3(ViewAsTab, { controller, state }),
2028
+ state.tab === "compare" && /* @__PURE__ */ a3(CompareTab, { controller, state }),
2029
+ state.tab === "share" && /* @__PURE__ */ a3(ShareTab, { controller, state }),
2030
+ state.tab === "experiments" && /* @__PURE__ */ a3(ExperimentsTab, { controller, state })
2031
+ ] }),
2032
+ /* @__PURE__ */ a3("footer", { class: "fst-footer", children: [
2033
+ /* @__PURE__ */ a3("span", { children: [
2034
+ formatHotkey(controller.options.hotkey).split("+").map((key, index) => /* @__PURE__ */ a3($, { children: [
2035
+ index > 0 && "+",
2036
+ /* @__PURE__ */ a3("kbd", { children: key })
2037
+ ] })),
2038
+ " ",
2039
+ "opens and closes"
2040
+ ] }),
2041
+ /* @__PURE__ */ a3("a", { href: "https://github.com/YashSoni998265/flagsmith-toolbar", target: "_blank", rel: "noreferrer", children: "flagsmith-toolbar" })
2042
+ ] })
2043
+ ]
2044
+ }
2045
+ );
2046
+ }
2047
+
2048
+ // src/ui/styles.ts
2049
+ var css = (
2050
+ /* css */
2051
+ `
2052
+ :host { all: initial; }
2053
+
2054
+ .fst {
2055
+ --fst-bg: #ffffff;
2056
+ --fst-surface: #f7f6fb;
2057
+ --fst-hover: #f0eef8;
2058
+ --fst-border: #e6e3f0;
2059
+ --fst-text: #1a1822;
2060
+ --fst-muted: #6b6780;
2061
+ --fst-accent: #6837fc;
2062
+ --fst-accent-ink: #ffffff;
2063
+ --fst-accent-soft: #efe9ff;
2064
+ --fst-green: #077348;
2065
+ --fst-green-soft: #e2f5ec;
2066
+ --fst-amber: #9a5b00;
2067
+ --fst-amber-soft: #fff2dc;
2068
+ --fst-blue: #1b64c9;
2069
+ --fst-blue-soft: #e6f0ff;
2070
+ --fst-pink: #b0287b;
2071
+ --fst-pink-soft: #fbe6f3;
2072
+ --fst-red: #b0262b;
2073
+ --fst-red-soft: #fde8e8;
2074
+ --fst-shadow: 0 24px 60px rgba(24, 16, 52, 0.18), 0 2px 10px rgba(24, 16, 52, 0.08);
2075
+ font-family: ui-sans-serif, system-ui, -apple-system, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
2076
+ font-size: 13px;
2077
+ line-height: 1.45;
2078
+ color: var(--fst-text);
2079
+ -webkit-font-smoothing: antialiased;
2080
+ }
2081
+
2082
+ @media (prefers-color-scheme: dark) {
2083
+ .fst {
2084
+ --fst-bg: #17161e;
2085
+ --fst-surface: #1f1e28;
2086
+ --fst-hover: #262532;
2087
+ --fst-border: #302e3d;
2088
+ --fst-text: #f2f1f7;
2089
+ --fst-muted: #a19eb5;
2090
+ --fst-accent: #9b7dff;
2091
+ --fst-accent-ink: #120f1c;
2092
+ --fst-accent-soft: #2a2342;
2093
+ --fst-green: #43d19c;
2094
+ --fst-green-soft: #12291f;
2095
+ --fst-amber: #f3b660;
2096
+ --fst-amber-soft: #2e2413;
2097
+ --fst-blue: #74adff;
2098
+ --fst-blue-soft: #15233a;
2099
+ --fst-pink: #f58bcb;
2100
+ --fst-pink-soft: #33182a;
2101
+ --fst-red: #ff8084;
2102
+ --fst-red-soft: #331a1c;
2103
+ --fst-shadow: 0 24px 60px rgba(0, 0, 0, 0.55);
2104
+ }
2105
+ }
2106
+
2107
+ *, *::before, *::after { box-sizing: border-box; }
2108
+ button, input, textarea { font: inherit; color: inherit; margin: 0; }
2109
+ button { cursor: pointer; }
2110
+ code, kbd, pre, .fst-mono { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 12px; }
2111
+ a { color: var(--fst-accent); }
2112
+ :focus-visible { outline: 2px solid var(--fst-accent); outline-offset: 2px; }
2113
+
2114
+ /* Launcher ---------------------------------------------------------------- */
2115
+ .fst-launcher {
2116
+ position: fixed; bottom: 20px; right: 20px;
2117
+ display: inline-flex; align-items: center; gap: 8px;
2118
+ padding: 10px 14px 10px 12px; border: 0; border-radius: 999px;
2119
+ background: var(--fst-accent); color: var(--fst-accent-ink);
2120
+ font-weight: 600; font-size: 13px; box-shadow: var(--fst-shadow);
2121
+ transition: transform 120ms ease;
2122
+ }
2123
+ .fst--left .fst-launcher { right: auto; left: 20px; }
2124
+ .fst-launcher:hover { transform: translateY(-1px); }
2125
+ .fst-launcher svg { width: 16px; height: 16px; }
2126
+ .fst-badge {
2127
+ min-width: 20px; height: 20px; padding: 0 6px; border-radius: 999px;
2128
+ display: inline-flex; align-items: center; justify-content: center;
2129
+ background: #ffffff; color: #6837fc; font-size: 11px; font-weight: 700;
2130
+ }
2131
+
2132
+ /* Preview banner ------------------------------------------------------------ */
2133
+ .fst-banner {
2134
+ position: fixed; bottom: 18px; left: 50%; transform: translateX(-50%);
2135
+ display: flex; align-items: center; gap: 10px; max-width: calc(100vw - 24px);
2136
+ padding: 6px 6px 6px 8px; border-radius: 999px;
2137
+ background: #1a1822; color: #ffffff; font-size: 12.5px;
2138
+ box-shadow: 0 10px 30px rgba(0, 0, 0, 0.25); white-space: nowrap;
2139
+ }
2140
+ /* In push mode the page is narrower, so centre the banner on the page, not the window. */
2141
+ .fst--pushed .fst-banner { left: calc((100vw - 424px) / 2); }
2142
+ .fst--pushed.fst--left .fst-banner { left: calc(424px + (100vw - 424px) / 2); }
2143
+ .fst-banner-tag {
2144
+ padding: 2px 8px; border-radius: 999px; background: #6837fc; color: #fff;
2145
+ font-weight: 700; font-size: 11px; letter-spacing: 0.02em; text-transform: uppercase;
2146
+ }
2147
+ .fst-banner-text { overflow: hidden; text-overflow: ellipsis; }
2148
+ .fst-banner-muted { color: #b9b4cc; }
2149
+ .fst-banner-btn {
2150
+ border: 0; border-radius: 999px; padding: 5px 10px;
2151
+ background: #ffffff; color: #1a1822; font-weight: 600; font-size: 12px;
2152
+ }
2153
+
2154
+ /* Panel --------------------------------------------------------------------- */
2155
+ .fst-panel {
2156
+ position: fixed; top: 12px; right: 12px; bottom: 12px;
2157
+ width: 400px; max-width: calc(100vw - 24px);
2158
+ display: flex; flex-direction: column;
2159
+ background: var(--fst-bg); border: 1px solid var(--fst-border); border-radius: 16px;
2160
+ box-shadow: var(--fst-shadow); overflow: hidden;
2161
+ }
2162
+ .fst--left .fst-panel { right: auto; left: 12px; }
2163
+ .fst-panel:focus { outline: none; }
2164
+ .fst-header { display: flex; align-items: center; justify-content: space-between; padding: 14px 14px 6px 16px; }
2165
+ .fst-title { display: flex; align-items: center; gap: 8px; font-weight: 700; font-size: 14px; }
2166
+ .fst-title svg { width: 18px; height: 18px; color: var(--fst-accent); }
2167
+ .fst-icon-btn {
2168
+ display: inline-flex; align-items: center; justify-content: center;
2169
+ width: 28px; height: 28px; border: 0; border-radius: 8px; background: transparent; color: var(--fst-muted);
2170
+ }
2171
+ .fst-icon-btn:hover { background: var(--fst-hover); color: var(--fst-text); }
2172
+ .fst-icon-btn:disabled { cursor: default; }
2173
+ .fst-icon-btn svg { width: 16px; height: 16px; }
2174
+ .fst-icon-btn.is-spinning svg { animation: fst-spin 800ms linear infinite; }
2175
+ .fst-header-actions { display: flex; align-items: center; gap: 2px; }
2176
+ .fst-setup-chip {
2177
+ display: inline-flex; align-items: center; gap: 4px; margin-right: 4px; padding: 3px 8px;
2178
+ border: 0; border-radius: 999px; font-size: 11.5px; font-weight: 700; white-space: nowrap;
2179
+ }
2180
+ .fst-setup-chip svg { width: 12px; height: 12px; }
2181
+ .fst-setup-chip--ok { background: var(--fst-green-soft); color: var(--fst-green); }
2182
+ .fst-setup-chip--warning { background: var(--fst-amber-soft); color: var(--fst-amber); }
2183
+ .fst-setup-chip--problem { background: var(--fst-red-soft); color: var(--fst-red); }
2184
+ .fst-refresh { margin: 0; padding: 6px 16px; font-size: 12px; font-weight: 600; }
2185
+ .fst-refresh--loading { color: var(--fst-muted); }
2186
+ .fst-refresh--updated { background: var(--fst-blue-soft); color: var(--fst-blue); }
2187
+ .fst-refresh--unchanged { background: var(--fst-green-soft); color: var(--fst-green); }
2188
+ .fst-refresh--error { background: var(--fst-red-soft); color: var(--fst-red); }
2189
+ .fst-connection {
2190
+ display: flex; align-items: center; gap: 8px; padding: 0 16px 10px;
2191
+ color: var(--fst-muted); font-size: 12px; min-width: 0;
2192
+ }
2193
+ .fst-connection > span:nth-child(2) { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
2194
+ .fst-dot { width: 8px; height: 8px; border-radius: 50%; background: var(--fst-muted); flex: none; }
2195
+ .fst-dot--ok { background: var(--fst-green); box-shadow: 0 0 0 3px var(--fst-green-soft); }
2196
+ .fst-env { margin-left: auto; padding: 1px 6px; border-radius: 6px; background: var(--fst-surface); color: var(--fst-muted); flex: none; }
2197
+ .fst-tabs {
2198
+ display: flex; gap: 0; padding: 0 8px; border-bottom: 1px solid var(--fst-border);
2199
+ overflow-x: auto; scrollbar-width: none;
2200
+ }
2201
+ .fst-tabs::-webkit-scrollbar { display: none; }
2202
+ .fst-tab {
2203
+ position: relative; flex: none; padding: 9px 7px 10px; border: 0; background: transparent;
2204
+ color: var(--fst-muted); font-weight: 600; font-size: 12.5px; white-space: nowrap;
2205
+ }
2206
+ .fst-tab-dot {
2207
+ display: inline-block; width: 6px; height: 6px; margin-left: 4px; border-radius: 50%;
2208
+ background: var(--fst-amber); vertical-align: middle;
2209
+ }
2210
+ .fst-tab:hover { color: var(--fst-text); }
2211
+ .fst-tab.is-active { color: var(--fst-accent); }
2212
+ .fst-tab.is-active::after {
2213
+ content: ''; position: absolute; left: 8px; right: 8px; bottom: -1px; height: 2px;
2214
+ border-radius: 2px; background: var(--fst-accent);
2215
+ }
2216
+ .fst-body { flex: 1; overflow-y: auto; padding: 12px; }
2217
+ .fst-footer {
2218
+ display: flex; justify-content: space-between; gap: 8px; padding: 8px 14px;
2219
+ border-top: 1px solid var(--fst-border); color: var(--fst-muted); font-size: 11.5px;
2220
+ }
2221
+ .fst-footer a { color: var(--fst-muted); }
2222
+ kbd {
2223
+ display: inline-block; padding: 0 5px; border: 1px solid var(--fst-border); border-bottom-width: 2px;
2224
+ border-radius: 5px; background: var(--fst-surface); font-size: 11px;
2225
+ }
2226
+
2227
+ /* Shared pieces ------------------------------------------------------------- */
2228
+ .fst-stack { display: flex; flex-direction: column; gap: 10px; }
2229
+ .fst-muted { color: var(--fst-muted); }
2230
+ .fst-note { margin: 0; color: var(--fst-muted); font-size: 12px; }
2231
+ .fst-error { margin: 0; color: var(--fst-red); }
2232
+ .fst-section-title { margin: 4px 2px 0; color: var(--fst-muted); font-size: 11.5px; font-weight: 700; letter-spacing: 0.04em; text-transform: uppercase; }
2233
+ .fst-card { padding: 12px; border: 1px solid var(--fst-border); border-radius: 12px; background: var(--fst-bg); }
2234
+ .fst-card p { margin: 6px 0 10px; color: var(--fst-muted); }
2235
+ .fst-card-title { display: flex; align-items: center; gap: 6px; font-weight: 700; }
2236
+ .fst-card-title svg { width: 15px; height: 15px; color: var(--fst-accent); }
2237
+ .fst-btn {
2238
+ display: inline-flex; align-items: center; gap: 6px; padding: 6px 10px;
2239
+ border: 1px solid var(--fst-border); border-radius: 8px; background: var(--fst-bg);
2240
+ font-weight: 600; font-size: 12.5px; text-decoration: none; color: var(--fst-text);
2241
+ }
2242
+ .fst-btn:hover { background: var(--fst-hover); }
2243
+ .fst-btn:disabled { opacity: 0.55; cursor: default; }
2244
+ .fst-btn svg { width: 13px; height: 13px; }
2245
+ .fst-btn--primary { border-color: var(--fst-accent); background: var(--fst-accent); color: var(--fst-accent-ink); }
2246
+ .fst-btn--primary:hover { background: var(--fst-accent); filter: brightness(1.08); }
2247
+ .fst-link-btn { padding: 0; border: 0; background: none; color: var(--fst-accent); font-weight: 600; font-size: 12.5px; }
2248
+ .fst-link-btn:hover { text-decoration: underline; }
2249
+ .fst-status { margin-left: 8px; color: var(--fst-green); font-weight: 600; font-size: 12px; }
2250
+ .fst-input {
2251
+ width: 100%; padding: 7px 10px; border: 1px solid var(--fst-border); border-radius: 8px;
2252
+ background: var(--fst-bg); font-size: 12.5px;
2253
+ }
2254
+ .fst-input:focus { outline: none; border-color: var(--fst-accent); box-shadow: 0 0 0 3px var(--fst-accent-soft); }
2255
+ textarea.fst-input { resize: vertical; min-height: 64px; }
2256
+ .fst-label { display: block; margin-bottom: 4px; color: var(--fst-muted); font-size: 12px; font-weight: 600; }
2257
+ .fst-pre {
2258
+ max-height: 220px; margin: 10px 0 0; padding: 10px; overflow: auto; border-radius: 8px;
2259
+ background: var(--fst-surface); white-space: pre-wrap; word-break: break-word; font-size: 11.5px;
2260
+ }
2261
+ .fst-empty { padding: 18px 8px; color: var(--fst-muted); text-align: center; }
2262
+ .fst-empty p { margin: 0 0 6px; }
2263
+ .fst-chips { display: flex; flex-wrap: wrap; gap: 4px; margin-top: 6px; }
2264
+ .fst-chip {
2265
+ display: inline-flex; align-items: center; gap: 4px; padding: 1px 7px; border-radius: 999px;
2266
+ background: var(--fst-surface); color: var(--fst-muted); font-size: 11.5px; font-weight: 600;
2267
+ }
2268
+ .fst-chip--identity { background: var(--fst-pink-soft); color: var(--fst-pink); }
2269
+ .fst-chip--exposure { background: var(--fst-blue-soft); color: var(--fst-blue); }
2270
+ .fst-chip--event { background: var(--fst-green-soft); color: var(--fst-green); }
2271
+ .fst-spinner {
2272
+ width: 12px; height: 12px; border-radius: 50%; flex: none;
2273
+ border: 2px solid var(--fst-accent-soft); border-top-color: var(--fst-accent);
2274
+ animation: fst-spin 700ms linear infinite;
2275
+ }
2276
+ @keyframes fst-spin { to { transform: rotate(360deg); } }
2277
+
2278
+ /* Welcome and "viewing as" ------------------------------------------------- */
2279
+ .fst-welcome { padding: 12px; border-radius: 12px; background: var(--fst-accent-soft); }
2280
+ .fst-welcome-title { display: block; margin-bottom: 6px; }
2281
+ .fst-welcome ol { margin: 0 0 8px; padding-left: 18px; }
2282
+ .fst-welcome li { margin: 3px 0; }
2283
+ .fst-welcome-note { margin: 0 0 10px; color: var(--fst-muted); font-size: 12px; }
2284
+ .fst-viewing {
2285
+ display: flex; align-items: center; gap: 8px; padding: 8px 10px;
2286
+ border-radius: 10px; background: var(--fst-surface); font-size: 12.5px;
2287
+ }
2288
+ .fst-viewing svg { width: 14px; height: 14px; color: var(--fst-muted); flex: none; }
2289
+ .fst-viewing > span { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
2290
+
2291
+ /* Flags list ---------------------------------------------------------------- */
2292
+ .fst-search { padding-left: 10px; }
2293
+ .fst-segmented { display: flex; gap: 4px; padding: 3px; border-radius: 10px; background: var(--fst-surface); }
2294
+ .fst-segment {
2295
+ flex: 1; padding: 5px 6px; border: 0; border-radius: 8px; background: transparent;
2296
+ color: var(--fst-muted); font-weight: 600; font-size: 12px; white-space: nowrap;
2297
+ }
2298
+ .fst-segment.is-active { background: var(--fst-bg); color: var(--fst-text); box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08); }
2299
+ .fst-segment-count { margin-left: 4px; color: var(--fst-muted); font-weight: 500; }
2300
+ .fst-list { margin: 0; padding: 0; list-style: none; display: flex; flex-direction: column; gap: 6px; }
2301
+ .fst-flag { border: 1px solid var(--fst-border); border-radius: 12px; background: var(--fst-bg); transition: border-color 120ms ease; }
2302
+ .fst-flag:hover { border-color: color-mix(in srgb, var(--fst-accent) 35%, var(--fst-border)); }
2303
+ .fst-flag.is-changed { border-color: var(--fst-amber); box-shadow: inset 3px 0 0 var(--fst-amber); }
2304
+ .fst-flag.is-fresh { border-color: var(--fst-blue); animation: fst-flash 1.2s ease-out 2; }
2305
+ @keyframes fst-flash { 0% { background: var(--fst-blue-soft); } 100% { background: var(--fst-bg); } }
2306
+ .fst-fresh {
2307
+ flex: none; padding: 0 6px; border-radius: 999px; background: var(--fst-blue-soft); color: var(--fst-blue);
2308
+ font-size: 10.5px; font-weight: 700; font-family: inherit;
2309
+ }
2310
+ .fst-flag-main { display: flex; align-items: center; gap: 8px; padding: 8px 10px 8px 12px; }
2311
+ .fst-flag-summary {
2312
+ flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 3px; padding: 0;
2313
+ border: 0; background: none; text-align: left;
2314
+ }
2315
+ .fst-flag-name { display: flex; align-items: center; gap: 6px; min-width: 0; font-weight: 600; }
2316
+ .fst-flag-name code { min-width: 0; font-size: 12.5px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
2317
+ .fst-used { width: 6px; height: 6px; border-radius: 50%; background: var(--fst-accent); flex: none; }
2318
+ .fst-type {
2319
+ flex: none; margin-left: auto; padding: 0 5px; border: 1px solid var(--fst-border); border-radius: 5px;
2320
+ color: var(--fst-muted); font-size: 10.5px; font-weight: 600; line-height: 16px;
2321
+ }
2322
+ .fst-group { display: flex; flex-direction: column; gap: 6px; }
2323
+ .fst-group-title { display: flex; align-items: center; gap: 6px; margin: 2px 2px 0; }
2324
+ .fst-group-count { color: var(--fst-muted); font-weight: 500; letter-spacing: 0; }
2325
+ .fst-pages code { padding: 0 4px; border-radius: 4px; background: var(--fst-surface); }
2326
+ .fst-flag-meta { display: flex; align-items: center; gap: 6px; min-width: 0; }
2327
+ .fst-flag-value { color: var(--fst-muted); font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 150px; }
2328
+ .fst-reason {
2329
+ flex: none; max-width: 190px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
2330
+ padding: 1px 7px; border-radius: 999px; font-size: 11px; font-weight: 600;
2331
+ background: var(--fst-surface); color: var(--fst-muted);
2332
+ }
2333
+ .fst-reason--segment { background: var(--fst-blue-soft); color: var(--fst-blue); }
2334
+ .fst-reason--identity { background: var(--fst-pink-soft); color: var(--fst-pink); }
2335
+ .fst-reason--split { background: var(--fst-green-soft); color: var(--fst-green); }
2336
+ .fst-reason--experiment { background: var(--fst-accent-soft); color: var(--fst-accent); }
2337
+ .fst-reason--override { background: var(--fst-amber-soft); color: var(--fst-amber); }
2338
+ .fst-reason--error { background: var(--fst-red-soft); color: var(--fst-red); }
2339
+ .fst-details { padding: 0 12px 12px; border-top: 1px dashed var(--fst-border); }
2340
+ .fst-details p { margin: 10px 0 0; }
2341
+ .fst-raw code { padding: 1px 6px; border-radius: 6px; background: var(--fst-surface); color: var(--fst-muted); }
2342
+ .fst-value { margin-top: 12px; }
2343
+ .fst-value-row { display: flex; gap: 6px; }
2344
+ .fst-actions { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 12px; }
2345
+
2346
+ /* Switch -------------------------------------------------------------------- */
2347
+ .fst-switch {
2348
+ position: relative; flex: none; width: 34px; height: 20px; padding: 0; border: 0; border-radius: 999px;
2349
+ background: var(--fst-border); transition: background 120ms ease;
2350
+ }
2351
+ .fst-switch.is-on { background: var(--fst-green); }
2352
+ .fst-switch-thumb {
2353
+ position: absolute; top: 2px; left: 2px; width: 16px; height: 16px; border-radius: 50%;
2354
+ background: #fff; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.25); transition: transform 120ms ease;
2355
+ }
2356
+ .fst-switch.is-on .fst-switch-thumb { transform: translateX(14px); }
2357
+
2358
+ /* View as -------------------------------------------------------------------- */
2359
+ .fst-current-name { margin-top: 4px; font-size: 15px; font-weight: 700; }
2360
+ .fst-personas { margin: 0; padding: 0; list-style: none; display: flex; flex-direction: column; gap: 6px; }
2361
+ .fst-persona {
2362
+ display: flex; align-items: center; justify-content: space-between; gap: 10px;
2363
+ padding: 10px 12px; border: 1px solid var(--fst-border); border-radius: 12px;
2364
+ }
2365
+ .fst-persona.is-active { border-color: var(--fst-accent); background: var(--fst-accent-soft); }
2366
+ .fst-persona > div { min-width: 0; }
2367
+ .fst-persona > .fst-btn { flex: none; white-space: nowrap; }
2368
+ .fst-persona-name { font-weight: 700; }
2369
+ .fst-form { display: flex; flex-direction: column; gap: 8px; }
2370
+
2371
+ /* Events -------------------------------------------------------------------- */
2372
+ .fst-events { margin: 0; padding: 0; list-style: none; display: flex; flex-direction: column; gap: 6px; }
2373
+ .fst-event {
2374
+ display: flex; flex-wrap: wrap; align-items: center; gap: 6px;
2375
+ padding: 8px 10px; border: 1px solid var(--fst-border); border-radius: 10px;
2376
+ }
2377
+ .fst-event-meta { width: 100%; color: var(--fst-muted); font-size: 11.5px; }
2378
+
2379
+ .fst-event.is-unsent { border-style: dashed; }
2380
+
2381
+ /* Setup check ------------------------------------------------------------------- */
2382
+ .fst-setup { margin-bottom: 10px; padding: 10px 12px; border: 1px solid var(--fst-border); border-radius: 12px; background: var(--fst-surface); }
2383
+ .fst-setup-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 4px; }
2384
+ .fst-setup-ok { display: flex; align-items: center; gap: 6px; margin: 4px 0 8px; color: var(--fst-green); font-weight: 600; }
2385
+ .fst-setup-ok svg { width: 14px; height: 14px; }
2386
+ .fst-issues { margin: 0; padding: 0; list-style: none; display: flex; flex-direction: column; gap: 8px; }
2387
+ .fst-issue { display: flex; gap: 8px; align-items: flex-start; }
2388
+ .fst-issue > svg { width: 15px; height: 15px; flex: none; margin-top: 2px; }
2389
+ .fst-issue p { margin: 2px 0 0; color: var(--fst-muted); }
2390
+ .fst-issue .fst-pre { margin-top: 6px; }
2391
+ .fst-issue--problem > svg { color: var(--fst-red); }
2392
+ .fst-issue--warning > svg { color: var(--fst-amber); }
2393
+ .fst-issue--tip > svg { color: var(--fst-muted); }
2394
+
2395
+ /* Compare ----------------------------------------------------------------------- */
2396
+ .fst-compare-pick { display: flex; align-items: flex-end; gap: 6px; }
2397
+ .fst-picker { flex: 1; min-width: 0; }
2398
+ .fst-select { appearance: auto; padding: 6px 8px; text-overflow: ellipsis; }
2399
+ .fst-swap { flex: none; margin-bottom: 2px; }
2400
+ .fst-loading { display: flex; align-items: center; gap: 8px; margin: 0; color: var(--fst-muted); }
2401
+ .fst-compare-summary { margin: 2px 2px 0; }
2402
+ .fst-compare-row { padding: 8px 12px 10px; }
2403
+ .fst-compare-key { margin-bottom: 6px; font-weight: 600; }
2404
+ .fst-compare-key code { font-size: 12.5px; }
2405
+ .fst-side { display: grid; grid-template-columns: 92px 30px minmax(0, 1fr); align-items: center; gap: 4px 6px; padding: 3px 0; }
2406
+ .fst-side .fst-reason { grid-column: 2 / 4; justify-self: start; max-width: 100%; }
2407
+ .fst-side-label { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--fst-muted); font-size: 12px; font-weight: 600; }
2408
+ .fst-side-value { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
2409
+ .fst-state { padding: 0 5px; border-radius: 6px; background: var(--fst-surface); color: var(--fst-muted); font-size: 11px; font-weight: 700; text-align: center; }
2410
+ .fst-state.is-on { background: var(--fst-green-soft); color: var(--fst-green); }
2411
+ .fst-same summary { cursor: pointer; color: var(--fst-muted); font-weight: 600; font-size: 12.5px; }
2412
+
2413
+ /* Experiments --------------------------------------------------------------------- */
2414
+ .fst-callout {
2415
+ display: flex; gap: 8px; align-items: flex-start; padding: 8px 10px; border-radius: 10px;
2416
+ background: var(--fst-blue-soft); color: var(--fst-blue); font-size: 12.5px;
2417
+ }
2418
+ .fst-callout svg { width: 15px; height: 15px; flex: none; margin-top: 1px; }
2419
+ .fst-exp { padding: 10px 12px; border: 1px solid var(--fst-border); border-radius: 12px; }
2420
+ .fst-exp--good { border-color: color-mix(in srgb, var(--fst-green) 45%, var(--fst-border)); }
2421
+ .fst-exp--bad { border-color: var(--fst-amber); box-shadow: inset 3px 0 0 var(--fst-amber); }
2422
+ .fst-exp-head { display: flex; align-items: center; gap: 6px; }
2423
+ .fst-exp-head svg { width: 15px; height: 15px; color: var(--fst-accent); }
2424
+ .fst-exp-meta { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; margin-top: 4px; color: var(--fst-muted); }
2425
+ .fst-exp-status { display: flex; gap: 6px; align-items: flex-start; margin: 8px 0 0; }
2426
+ .fst-exp-status svg { width: 14px; height: 14px; flex: none; margin-top: 2px; }
2427
+ .fst-exp--good .fst-exp-status svg { color: var(--fst-green); }
2428
+ .fst-exp--bad .fst-exp-status svg { color: var(--fst-amber); }
2429
+ .fst-exp--neutral .fst-exp-status svg { color: var(--fst-muted); }
2430
+
2431
+ /* Small screens ----------------------------------------------------------------- */
2432
+ @media (max-width: 560px) {
2433
+ .fst-panel, .fst--left .fst-panel { top: auto; left: 8px; right: 8px; bottom: 8px; width: auto; height: 80vh; }
2434
+ .fst-banner { top: 8px; bottom: auto; }
2435
+ .fst-banner-muted { display: none; }
2436
+ .fst-flag-value { max-width: 110px; }
2437
+ }
2438
+ `
2439
+ );
2440
+
2441
+ // src/ui/mount.tsx
2442
+ function mountUI(controller) {
2443
+ const host = document.createElement("div");
2444
+ host.setAttribute("data-flagsmith-toolbar", "");
2445
+ host.style.cssText = "position:fixed;top:0;left:0;width:0;height:0;z-index:2147483000;";
2446
+ const shadow = host.attachShadow({ mode: "open" });
2447
+ addStyles(shadow);
2448
+ const root = document.createElement("div");
2449
+ shadow.append(root);
2450
+ document.body.appendChild(host);
2451
+ Q(/* @__PURE__ */ a3(App, { controller }), root);
2452
+ return {
2453
+ unmount() {
2454
+ Q(null, root);
2455
+ host.remove();
2456
+ }
2457
+ };
2458
+ }
2459
+ function addStyles(shadow) {
2460
+ try {
2461
+ if ("adoptedStyleSheets" in shadow && "replaceSync" in CSSStyleSheet.prototype) {
2462
+ const sheet = new CSSStyleSheet();
2463
+ sheet.replaceSync(css);
2464
+ shadow.adoptedStyleSheets = [sheet];
2465
+ return;
2466
+ }
2467
+ } catch {
2468
+ }
2469
+ const style = document.createElement("style");
2470
+ style.textContent = css;
2471
+ shadow.append(style);
2472
+ }
2473
+
2474
+ // src/controller.ts
2475
+ var MAX_EVENTS = 50;
2476
+ var CHANGED_HIGHLIGHT_MS = 6e3;
2477
+ function parseHotkey(spec) {
2478
+ const parts = spec.toLowerCase().split("+").map((part) => part.trim()).filter(Boolean);
2479
+ const key = parts.pop() ?? "";
2480
+ return {
2481
+ key,
2482
+ shift: parts.includes("shift"),
2483
+ alt: parts.includes("alt") || parts.includes("option"),
2484
+ ctrl: parts.includes("ctrl") || parts.includes("control"),
2485
+ meta: parts.includes("meta") || parts.includes("cmd")
2486
+ };
2487
+ }
2488
+ function formatHotkey(spec) {
2489
+ return spec.split("+").map((part) => part.trim()).map((part) => part.length === 1 ? part.toUpperCase() : part.charAt(0).toUpperCase() + part.slice(1)).join("+");
2490
+ }
2491
+ var errorMessage = (error) => error instanceof Error ? error.message : String(error);
2492
+ var ToolbarController = class {
2493
+ constructor(flagsmith, options = {}) {
2494
+ this.flagsmith = flagsmith;
2495
+ /** The app's own evaluation context, kept while previewing as someone else. */
2496
+ this.appContext = null;
2497
+ this.pendingReads = {};
2498
+ /** The last state written to storage, so unchanged state isn't written again. */
2499
+ this.lastSaved = "";
2500
+ this.eventId = 0;
2501
+ this.cleanups = [];
2502
+ this.destroyed = false;
2503
+ /** The identity the current flags from Flagsmith were evaluated for. */
2504
+ this.lastFlagsFor = null;
2505
+ /** When flags for that identity first arrived. */
2506
+ this.flagsSince = 0;
2507
+ /** Counts the toolbar's own context changes, so they aren't mistaken for the app switching users. */
2508
+ this.ownContextChanges = 0;
2509
+ this.clockTimer = null;
2510
+ this.highlightTimer = null;
2511
+ this.statusTimer = null;
2512
+ this.compareRun = 0;
2513
+ this.options = { hotkey: "shift+f", position: "right", storageKey: "flagsmith-toolbar", layout: "overlay", ...options };
2514
+ const saved = loadSaved(this.options.storageKey);
2515
+ const shared = readPreviewFromUrl(window.location.href);
2516
+ if (shared) window.history.replaceState(window.history.state, "", stripPreviewFromUrl(window.location.href));
2517
+ this.store = new Store({
2518
+ open: shared ? true : options.open ?? saved.open ?? false,
2519
+ tab: saved.tab ?? "flags",
2520
+ filter: "all",
2521
+ search: "",
2522
+ expanded: null,
2523
+ serverFlags: {},
2524
+ page: pageKey(window.location),
2525
+ reads: {},
2526
+ seenOn: {},
2527
+ overrides: shared ? shared.overrides : saved.overrides ?? {},
2528
+ persona: shared ? shared.persona : saved.persona ?? null,
2529
+ personaStatus: "idle",
2530
+ personaError: null,
2531
+ events: [],
2532
+ exposures: {},
2533
+ welcomeDismissed: saved.welcomeDismissed ?? false,
2534
+ sharedPreview: Boolean(shared),
2535
+ setupOpen: false,
2536
+ changedInFlagsmith: {},
2537
+ refreshStatus: "idle",
2538
+ compareA: "page",
2539
+ compareB: options.personas?.length ? "persona:0" : "anonymous",
2540
+ compareStatus: "idle",
2541
+ compareError: null,
2542
+ compareResult: null,
2543
+ clock: Date.now()
2544
+ });
2545
+ this.instrumentation = instrument(flagsmith, {
2546
+ onServerFlags: (flags) => this.receiveServerFlags(flags),
2547
+ onRead: (key) => this.recordRead(key),
2548
+ onEvent: (event) => this.recordEvent(event),
2549
+ holdBack: () => this.isPreviewing(),
2550
+ onAppContextChange: () => this.onAppContextChange(),
2551
+ isOwnContextChange: () => this.ownContextChanges > 0
2552
+ });
2553
+ this.instrumentation.setOverrides(this.store.get().overrides);
2554
+ this.lastFlagsFor = this.currentIdentity();
2555
+ this.flagsSince = Date.now();
2556
+ this.store.set({ serverFlags: { ...this.instrumentation.serverFlags() } });
2557
+ this.cleanups.push(this.store.subscribe(() => this.saveIfChanged()));
2558
+ this.cleanups.push(watchNavigation(() => this.onNavigate()));
2559
+ }
2560
+ start() {
2561
+ const mount = () => {
2562
+ if (this.destroyed) return;
2563
+ const ui = mountUI(this);
2564
+ this.cleanups.push(ui.unmount);
2565
+ };
2566
+ if (document.body) mount();
2567
+ else document.addEventListener("DOMContentLoaded", mount, { once: true });
2568
+ this.cleanups.push(this.listenForHotkey());
2569
+ const persona = this.store.get().persona;
2570
+ if (persona) {
2571
+ void this.whenInitialised().then((ready) => {
2572
+ if (ready && !this.destroyed) void this.applyPersona(persona);
2573
+ });
2574
+ }
2575
+ }
2576
+ // Panel ------------------------------------------------------------------
2577
+ open() {
2578
+ this.store.set({ open: true });
2579
+ }
2580
+ close() {
2581
+ this.store.set({ open: false });
2582
+ }
2583
+ toggle() {
2584
+ this.store.set((state) => ({ open: !state.open }));
2585
+ }
2586
+ setTab(tab) {
2587
+ this.store.set({ tab });
2588
+ }
2589
+ setFilter(filter) {
2590
+ this.store.set({ filter });
2591
+ }
2592
+ setSearch(search) {
2593
+ this.store.set({ search });
2594
+ }
2595
+ toggleExpanded(key) {
2596
+ this.store.set((state) => ({ expanded: state.expanded === key ? null : key }));
2597
+ }
2598
+ dismissWelcome() {
2599
+ this.store.set({ welcomeDismissed: true });
2600
+ }
2601
+ toggleSetup() {
2602
+ this.store.set((state) => ({ setupOpen: !state.setupOpen }));
2603
+ }
2604
+ /** True while you are viewing as someone else or have changed a flag. Events are held back then. */
2605
+ isPreviewing() {
2606
+ const { persona, overrides } = this.store.get();
2607
+ return Boolean(persona) || Object.keys(overrides).length > 0;
2608
+ }
2609
+ /** The identity Flagsmith is evaluating flags for right now, or null for an anonymous visitor. */
2610
+ currentIdentity() {
2611
+ return this.flagsmith.getContext?.()?.identity?.identifier ?? this.flagsmith.identity ?? null;
2612
+ }
2613
+ /** Fetches the latest flags from Flagsmith, so a change made in the dashboard shows up without a reload. */
2614
+ async refresh() {
2615
+ if (!this.flagsmith.getFlags) return;
2616
+ const before = this.store.get().serverFlags;
2617
+ const who = this.lastFlagsFor;
2618
+ this.store.set({ refreshStatus: "loading" });
2619
+ try {
2620
+ await this.flagsmith.getFlags();
2621
+ if (this.destroyed) return;
2622
+ const after = this.store.get().serverFlags;
2623
+ const changed = who === this.lastFlagsFor && Object.keys(before).length > 0 ? Object.keys({ ...before, ...after }).filter((key) => !flagsMatch(before[key], after[key])) : [];
2624
+ if (changed.length) {
2625
+ const now = Date.now();
2626
+ this.store.set({ changedInFlagsmith: Object.fromEntries(changed.map((key) => [key, now])) });
2627
+ if (this.highlightTimer) clearTimeout(this.highlightTimer);
2628
+ this.highlightTimer = setTimeout(() => this.store.set({ changedInFlagsmith: {} }), CHANGED_HIGHLIGHT_MS);
2629
+ }
2630
+ this.flashStatus(changed.length ? "updated" : "unchanged");
2631
+ } catch (error) {
2632
+ this.recoverFromFailedFetch(error);
2633
+ this.flashStatus("error");
2634
+ }
2635
+ }
2636
+ /**
2637
+ * The SDK marks itself as fetching before a request and only clears that on success.
2638
+ * After a failed refresh, clear it the way a failed load would, so the app doesn't
2639
+ * think Flagsmith is still loading.
2640
+ */
2641
+ recoverFromFailedFetch(error) {
2642
+ const sdk = this.flagsmith;
2643
+ if (!sdk.loadingState?.isFetching) return;
2644
+ sdk.isLoading = false;
2645
+ sdk.loadingState = { ...sdk.loadingState, isFetching: false, isLoading: false, error };
2646
+ sdk._triggerLoadingState?.();
2647
+ }
2648
+ // Flags ------------------------------------------------------------------
2649
+ /** The flags the app sees right now: Flagsmith's flags with your changes on top. */
2650
+ effectiveFlags() {
2651
+ const { serverFlags, overrides } = this.store.get();
2652
+ return applyOverrides(serverFlags, overrides) ?? {};
2653
+ }
2654
+ usedOnPage() {
2655
+ return Object.keys(this.store.get().reads);
2656
+ }
2657
+ setEnabled(key, enabled) {
2658
+ this.changeFlag(key, { enabled });
2659
+ }
2660
+ setValue(key, value) {
2661
+ this.changeFlag(key, { value });
2662
+ }
2663
+ resetFlag(key) {
2664
+ this.updateOverrides(withoutOverride(this.store.get().overrides, key));
2665
+ }
2666
+ resetAll() {
2667
+ this.updateOverrides({});
2668
+ }
2669
+ /** Leaves preview mode: you see the page as yourself again and your changes are cleared. */
2670
+ async exitPreview() {
2671
+ if (this.store.get().persona) await this.backToMe();
2672
+ this.resetAll();
2673
+ this.store.set({ sharedPreview: false });
2674
+ }
2675
+ changeFlag(key, patch) {
2676
+ const { overrides, serverFlags } = this.store.get();
2677
+ const next = { ...overrides[key], ...patch };
2678
+ const real = serverFlags[key];
2679
+ const matchesFlagsmith = real !== void 0 && (next.enabled === void 0 || next.enabled === real.enabled) && (next.value === void 0 || next.value === real.value);
2680
+ this.updateOverrides(matchesFlagsmith ? withoutOverride(overrides, key) : withOverride(overrides, key, patch));
2681
+ }
2682
+ updateOverrides(next) {
2683
+ const before = this.effectiveFlags();
2684
+ this.instrumentation.setOverrides(next);
2685
+ this.store.set({ overrides: next });
2686
+ this.instrumentation.notifyApp(changedKeys(before, this.effectiveFlags()));
2687
+ }
2688
+ // View as ----------------------------------------------------------------
2689
+ async viewAs(persona) {
2690
+ await this.applyPersona(persona);
2691
+ }
2692
+ async backToMe() {
2693
+ const context = this.appContext;
2694
+ this.store.set({ personaStatus: "loading", personaError: null });
2695
+ try {
2696
+ if (context) await this.setOwnContext(context);
2697
+ this.appContext = null;
2698
+ this.store.set({ persona: null, personaStatus: "idle" });
2699
+ } catch (error) {
2700
+ this.store.set({ personaStatus: "error", personaError: `Flagsmith could not switch back to your view: ${errorMessage(error)}` });
2701
+ }
2702
+ }
2703
+ async applyPersona(persona) {
2704
+ if (!this.appContext) this.appContext = cloneContext(this.flagsmith.getContext());
2705
+ this.store.set({ persona, personaStatus: "loading", personaError: null });
2706
+ try {
2707
+ await this.setOwnContext(personaContext(this.appContext, persona));
2708
+ this.store.set({ personaStatus: "idle" });
2709
+ } catch (error) {
2710
+ this.store.set({ personaStatus: "error", personaError: `Flagsmith could not evaluate this user: ${errorMessage(error)}` });
2711
+ }
2712
+ }
2713
+ setOwnContext(context) {
2714
+ this.ownContextChanges++;
2715
+ try {
2716
+ return this.flagsmith.setContext(context);
2717
+ } finally {
2718
+ this.ownContextChanges--;
2719
+ }
2720
+ }
2721
+ /** The app switched users itself (say, after a login). If that ends a preview, the app's user wins. */
2722
+ onAppContextChange() {
2723
+ const { persona } = this.store.get();
2724
+ if (!persona) {
2725
+ this.appContext = null;
2726
+ return;
2727
+ }
2728
+ if (this.currentIdentity() === (personaContext({}, persona).identity?.identifier ?? null)) return;
2729
+ this.appContext = null;
2730
+ this.store.set({ persona: null, personaStatus: "idle", personaError: null });
2731
+ }
2732
+ // Share ------------------------------------------------------------------
2733
+ previewUrl() {
2734
+ const { overrides, persona } = this.store.get();
2735
+ return buildPreviewUrl(window.location.href, { overrides, persona });
2736
+ }
2737
+ bugReport() {
2738
+ const { serverFlags, overrides, persona } = this.store.get();
2739
+ const connection = this.connection();
2740
+ return buildBugReport({
2741
+ url: window.location.href,
2742
+ apiUrl: connection.apiUrl,
2743
+ environmentKey: connection.environmentKey,
2744
+ persona,
2745
+ identity: this.flagsmith.identity ?? null,
2746
+ flags: this.effectiveFlags(),
2747
+ serverFlags,
2748
+ overrides,
2749
+ usedOnPage: this.usedOnPage(),
2750
+ takenAt: /* @__PURE__ */ new Date()
2751
+ });
2752
+ }
2753
+ // Compare ----------------------------------------------------------------
2754
+ /** The users the Compare tab can pick from. */
2755
+ compareSubjects() {
2756
+ const personas = this.options.personas ?? [];
2757
+ return [
2758
+ { id: "page", label: this.subjectLabel("page") },
2759
+ { id: "anonymous", label: this.subjectLabel("anonymous") },
2760
+ ...personas.map((_3, index) => ({ id: `persona:${index}`, label: this.subjectLabel(`persona:${index}`) }))
2761
+ ];
2762
+ }
2763
+ subjectLabel(subject) {
2764
+ if (subject === "page") {
2765
+ const { persona } = this.store.get();
2766
+ const who = persona ? persona.name.split("\xB7")[0].trim() : this.flagsmith.identity;
2767
+ return who ? `This page \xB7 ${who}` : "This page";
2768
+ }
2769
+ if (subject === "anonymous") return "Anonymous visitor";
2770
+ return this.personaFor(subject)?.name ?? "Unknown user";
2771
+ }
2772
+ /** Compares two users' flags. Each one is evaluated live by Flagsmith; nothing is saved. */
2773
+ /** Picks one side of the comparison. Reads the latest state, so quick changes in a row never use a stale pick. */
2774
+ pickCompare(side, subject) {
2775
+ const { compareA, compareB } = this.store.get();
2776
+ return side === "a" ? this.compare(subject, compareB) : this.compare(compareA, subject);
2777
+ }
2778
+ swapCompare() {
2779
+ const { compareA, compareB } = this.store.get();
2780
+ return this.compare(compareB, compareA);
2781
+ }
2782
+ async compare(a4, b) {
2783
+ const run = ++this.compareRun;
2784
+ this.store.set({ compareA: a4, compareB: b, compareStatus: "loading", compareError: null });
2785
+ try {
2786
+ const [flagsA, flagsB] = await Promise.all([this.flagsFor(a4), this.flagsFor(b)]);
2787
+ if (run !== this.compareRun || this.destroyed) return;
2788
+ this.store.set({ compareStatus: "done", compareResult: { a: flagsA, b: flagsB, at: Date.now() } });
2789
+ } catch (error) {
2790
+ if (run !== this.compareRun || this.destroyed) return;
2791
+ this.store.set({ compareStatus: "error", compareError: `Flagsmith could not evaluate these users: ${errorMessage(error)}` });
2792
+ }
2793
+ }
2794
+ personaFor(subject) {
2795
+ const index = Number(subject.split(":")[1]);
2796
+ return subject.startsWith("persona:") ? this.options.personas?.[index] : void 0;
2797
+ }
2798
+ async flagsFor(subject) {
2799
+ if (subject === "page") return this.effectiveFlags();
2800
+ const { apiUrl, environmentKey } = this.connection();
2801
+ if (!apiUrl || !environmentKey) throw new Error("the SDK has not connected to Flagsmith yet");
2802
+ const persona = subject === "anonymous" ? null : this.personaFor(subject);
2803
+ if (persona === void 0) throw new Error("that user no longer exists");
2804
+ return fetchFlagsFor(persona, { api: apiUrl, environmentKey, headers: this.flagsmith.headers ?? null });
2805
+ }
2806
+ // Experiments and setup ------------------------------------------------------
2807
+ /** The experiments behind this page's flags, for the user Flagsmith is evaluating right now. */
2808
+ experiments() {
2809
+ const { serverFlags, reads, exposures, clock } = this.store.get();
2810
+ return experimentRows({
2811
+ flags: serverFlags,
2812
+ reads,
2813
+ exposures,
2814
+ // The user these flags belong to. Right after a switch the SDK already has the new
2815
+ // identity but still the old flags, and the two must not be mixed.
2816
+ identity: this.lastFlagsFor,
2817
+ eventsEnabled: this.flagsmith.eventsEnabled === true,
2818
+ previewing: this.isPreviewing(),
2819
+ now: Math.max(clock, Date.now()),
2820
+ since: this.flagsSince
2821
+ });
2822
+ }
2823
+ /** Common setup mistakes on this page, and on the pages visited before it. */
2824
+ setupIssues() {
2825
+ const { serverFlags, reads, seenOn, events } = this.store.get();
2826
+ return runSetupChecks({
2827
+ serverFlags,
2828
+ reads,
2829
+ seenOn,
2830
+ environmentKey: this.connection().environmentKey,
2831
+ loadingState: this.flagsmith.loadingState,
2832
+ identity: this.currentIdentity(),
2833
+ events,
2834
+ experiments: this.experiments()
2835
+ });
2836
+ }
2837
+ connection() {
2838
+ const apiUrl = this.flagsmith.api ?? null;
2839
+ let host = null;
2840
+ let selfHosted = false;
2841
+ if (apiUrl) {
2842
+ try {
2843
+ const url = new URL(apiUrl);
2844
+ host = url.host;
2845
+ selfHosted = !/(^|\.)flagsmith\.com$/i.test(url.hostname);
2846
+ } catch {
2847
+ }
2848
+ }
2849
+ const environmentKey = this.flagsmith.getContext?.()?.environment?.apiKey ?? null;
2850
+ return { apiUrl, host, selfHosted, environmentKey };
2851
+ }
2852
+ /** A link to the flag in the Flagsmith dashboard, when dashboardUrl and projectId are set. */
2853
+ dashboardLink(key) {
2854
+ const { dashboardUrl, projectId } = this.options;
2855
+ const id = this.store.get().serverFlags[key]?.id;
2856
+ const environmentKey = this.connection().environmentKey;
2857
+ if (!dashboardUrl || projectId === void 0 || projectId === "" || !id || !environmentKey) return null;
2858
+ return `${dashboardUrl.replace(/\/$/, "")}/project/${projectId}/environment/${environmentKey}/features?feature=${id}`;
2859
+ }
2860
+ // Lifecycle --------------------------------------------------------------
2861
+ destroy() {
2862
+ this.destroyed = true;
2863
+ for (const cleanup of this.cleanups.splice(0)) cleanup();
2864
+ for (const timer of [this.clockTimer, this.highlightTimer, this.statusTimer]) if (timer) clearTimeout(timer);
2865
+ this.instrumentation.restore();
2866
+ }
2867
+ receiveServerFlags(flags) {
2868
+ const who = this.currentIdentity();
2869
+ if (who !== this.lastFlagsFor) {
2870
+ this.lastFlagsFor = who;
2871
+ this.flagsSince = Date.now();
2872
+ }
2873
+ this.store.set({ serverFlags: { ...flags } });
2874
+ this.tickLater();
2875
+ }
2876
+ recordEvent(event) {
2877
+ const full = { ...event, id: ++this.eventId, at: Date.now() };
2878
+ this.store.set((state) => ({
2879
+ events: [full, ...state.events].slice(0, MAX_EVENTS),
2880
+ exposures: full.kind === "exposure" && full.key ? { ...state.exposures, [exposureKey(full.key, full.identifier)]: full } : state.exposures
2881
+ }));
2882
+ }
2883
+ flashStatus(status) {
2884
+ this.store.set({ refreshStatus: status });
2885
+ if (this.statusTimer) clearTimeout(this.statusTimer);
2886
+ this.statusTimer = setTimeout(() => this.store.set({ refreshStatus: "idle" }), 2500);
2887
+ }
2888
+ /** Re-renders once the exposure grace period has passed, so a missing exposure shows up. */
2889
+ tickLater() {
2890
+ if (this.clockTimer) clearTimeout(this.clockTimer);
2891
+ this.clockTimer = setTimeout(() => {
2892
+ if (!this.destroyed) this.store.set({ clock: Date.now() });
2893
+ }, EXPOSURE_GRACE_MS + 100);
2894
+ }
2895
+ recordRead(key) {
2896
+ if (key in this.store.get().reads || key in this.pendingReads) return;
2897
+ const first = Object.keys(this.pendingReads).length === 0;
2898
+ this.pendingReads[key] = Date.now();
2899
+ if (first) queueMicrotask(() => this.flushReads());
2900
+ }
2901
+ /** Moves batched reads into the store, on the page they were read on. */
2902
+ flushReads() {
2903
+ const pending = this.pendingReads;
2904
+ const keys = Object.keys(pending);
2905
+ if (this.destroyed || keys.length === 0) return;
2906
+ this.pendingReads = {};
2907
+ this.store.set((state) => {
2908
+ const seenOn = { ...state.seenOn };
2909
+ for (const key of keys) {
2910
+ const pages = seenOn[key] ?? [];
2911
+ if (!pages.includes(state.page)) seenOn[key] = [...pages, state.page];
2912
+ }
2913
+ return { reads: { ...state.reads, ...pending }, seenOn };
2914
+ });
2915
+ this.tickLater();
2916
+ }
2917
+ /** The app may have moved to another page. Reads start over there; where each flag was read is kept. */
2918
+ onNavigate() {
2919
+ if (this.destroyed) return;
2920
+ const page = pageKey(window.location);
2921
+ if (page === this.store.get().page) return;
2922
+ this.flushReads();
2923
+ this.store.set({ page, reads: {} });
2924
+ }
2925
+ /** Saves right away (no debounce), so a change made just before a reload is never lost. */
2926
+ saveIfChanged() {
2927
+ const { overrides, persona, welcomeDismissed, open, tab } = this.store.get();
2928
+ const snapshot = JSON.stringify({ overrides, persona, welcomeDismissed, open, tab });
2929
+ if (snapshot === this.lastSaved) return;
2930
+ this.lastSaved = snapshot;
2931
+ save(this.options.storageKey, { overrides, persona, welcomeDismissed, open, tab });
2932
+ }
2933
+ whenInitialised(timeoutMs = 2e4) {
2934
+ return new Promise((resolve) => {
2935
+ const started = Date.now();
2936
+ const check = () => {
2937
+ if (this.flagsmith.initialised) resolve(true);
2938
+ else if (this.destroyed || Date.now() - started > timeoutMs) resolve(false);
2939
+ else setTimeout(check, 100);
2940
+ };
2941
+ check();
2942
+ });
2943
+ }
2944
+ listenForHotkey() {
2945
+ const hotkey = parseHotkey(this.options.hotkey);
2946
+ const onKeyDown = (event) => {
2947
+ if (event.repeat) return;
2948
+ const target = event.composedPath()[0];
2949
+ const editing = target?.isContentEditable || ["INPUT", "TEXTAREA", "SELECT"].includes(target?.tagName ?? "");
2950
+ if (editing) return;
2951
+ const keyMatches = event.key.toLowerCase() === hotkey.key || event.code.toLowerCase() === `key${hotkey.key}`;
2952
+ if (keyMatches && event.shiftKey === hotkey.shift && event.altKey === hotkey.alt && event.ctrlKey === hotkey.ctrl && event.metaKey === hotkey.meta) {
2953
+ event.preventDefault();
2954
+ this.toggle();
2955
+ }
2956
+ };
2957
+ window.addEventListener("keydown", onKeyDown);
2958
+ return () => window.removeEventListener("keydown", onKeyDown);
2959
+ }
2960
+ };
2961
+
2962
+ // src/index.ts
2963
+ var current = null;
2964
+ function init(flagsmith, options = {}) {
2965
+ if (typeof window === "undefined" || typeof document === "undefined") return;
2966
+ if (options.enabled === false) return;
2967
+ current?.destroy();
2968
+ current = null;
2969
+ try {
2970
+ const controller = new ToolbarController(flagsmith, options);
2971
+ controller.start();
2972
+ current = controller;
2973
+ } catch (error) {
2974
+ console.error("[flagsmith-toolbar] could not start", error);
2975
+ }
2976
+ }
2977
+ function show() {
2978
+ current?.open();
2979
+ }
2980
+ function hide() {
2981
+ current?.close();
2982
+ }
2983
+ function toggle() {
2984
+ current?.toggle();
2985
+ }
2986
+ function destroy() {
2987
+ current?.destroy();
2988
+ current = null;
2989
+ }
2990
+ var FlagsmithToolbar = { init, show, hide, toggle, destroy };
2991
+ var index_default = FlagsmithToolbar;
2992
+ // Annotate the CommonJS export names for ESM import in node:
2993
+ 0 && (module.exports = {
2994
+ destroy,
2995
+ explainReason,
2996
+ hide,
2997
+ init,
2998
+ parseReason,
2999
+ show,
3000
+ toggle
3001
+ });
3002
+ //# sourceMappingURL=index.cjs.map