@mundogamernetwork/shared-ui 1.17.18 → 1.18.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +23 -0
  2. package/assets/kit/kit-base.css +47 -0
  3. package/assets/whats-new/tokens.css +43 -0
  4. package/components/MediaKit/MgRateCardBundleEditor.vue +2 -7
  5. package/components/MediaKit/MgRateCardEditor.vue +1 -1
  6. package/components/keys/KeyBrowser.vue +4 -9
  7. package/components/keys/KeyCampaignDashboardCard.vue +1 -1
  8. package/components/playtest/PlaytestInviteLanding.vue +17 -6
  9. package/components/ui/MgBanners.vue +13 -0
  10. package/components/ui/MgLoginModal.vue +1 -1
  11. package/components/whats-new/MgWhatsNewDialog.vue +552 -0
  12. package/components/whats-new/MgWhatsNewMedia.vue +242 -0
  13. package/components/whats-new/MgWhatsNewModal.vue +285 -0
  14. package/components/whats-new/MgWhatsNewRichText.vue +90 -0
  15. package/composables/useForceLogout.ts +0 -1
  16. package/composables/useLogout.ts +0 -2
  17. package/composables/useMgCheckout.ts +0 -1
  18. package/error.vue +1 -1
  19. package/locales/de.json +6 -0
  20. package/locales/en.json +6 -0
  21. package/locales/es.json +6 -0
  22. package/locales/pt-BR.json +6 -0
  23. package/locales/ro.json +6 -0
  24. package/nuxt.config.ts +11 -2
  25. package/package.json +5 -11
  26. package/pages/[slug]/index.vue +1 -1
  27. package/pages/about.vue +1 -1
  28. package/pages/blog.vue +1 -1
  29. package/pages/careers.vue +1 -1
  30. package/pages/contact.vue +8 -14
  31. package/pages/faq.vue +1 -1
  32. package/pages/key-campaigns/index.vue +1 -1
  33. package/pages/key-campaigns/redeem-key.vue +5 -11
  34. package/pages/magazine/[slug]/index.vue +1 -1
  35. package/pages/magazine/[slug]/preview.vue +2 -2
  36. package/pages/magazine/index.vue +3 -2
  37. package/pages/partners.vue +1 -1
  38. package/pages/press.vue +1 -1
  39. package/pages/presskit/game/[slug].vue +29 -1
  40. package/pages/roadmap.vue +1 -1
  41. package/pages/status.vue +1 -1
  42. package/pages/team.vue +1 -1
  43. package/pages/whats-new-preview.vue +96 -0
  44. package/services/campaignService.ts +0 -1
  45. package/services/creatorNetworkProgramService.ts +47 -0
  46. package/services/documentService.ts +16 -4
  47. package/services/httpService.ts +2 -2
  48. package/services/institutionalService.ts +1 -1
  49. package/stores/whatsNew.ts +170 -0
  50. package/types/index.ts +0 -3
  51. package/utils/clearSession.ts +0 -1
  52. package/utils/keyRequestError.ts +54 -0
  53. package/utils/whatsNew.ts +300 -0
  54. package/utils/whatsNewMessages.ts +133 -0
  55. package/utils/whatsNewText.ts +10 -0
  56. package/types/echo.d.ts +0 -7
@@ -134,13 +134,13 @@ export function mgApiUrl(endpoint: string, usePrefix = true) {
134
134
  case "login":
135
135
  case "logout":
136
136
  case "register":
137
- return ([apiBaseURL, usePrefix ? locale : "", endpoint] as string[])
137
+ return [apiBaseURL, usePrefix ? locale : "", endpoint]
138
138
  .filter((v) => v)
139
139
  .map((part) => part.replace(/^\//, ""))
140
140
  .map((part) => part.replace(/\/api\/v1$/, ""))
141
141
  .join("/");
142
142
  default:
143
- return ([apiBaseURL, usePrefix ? locale : "", endpoint] as string[])
143
+ return [apiBaseURL, usePrefix ? locale : "", endpoint]
144
144
  .filter((v) => v)
145
145
  .map((part) => part.replace(/^\//, ""))
146
146
  .join("/");
@@ -31,7 +31,7 @@ export const complexSerialize = function (obj: SerializeObject): string {
31
31
  if (typeof value === "object" && value !== null) {
32
32
  appendObject(`${baseKey}[${key}]`, value);
33
33
  } else {
34
- searchParams.append(`${baseKey}[${key}]`, String(value));
34
+ searchParams.append(`${baseKey}[${key}]`, value.toString());
35
35
  }
36
36
  });
37
37
  };
@@ -0,0 +1,170 @@
1
+ import { defineStore } from "pinia";
2
+ import {
3
+ WN_MAX_BATCH,
4
+ chunkEvents,
5
+ newDeviceId,
6
+ toApiLang,
7
+ type WnEventName,
8
+ type WnPost,
9
+ type WnReceiptEvent,
10
+ } from "../utils/whatsNew";
11
+
12
+ const DEVICE_KEY = "mg_wn_device_id";
13
+ const LAST_SHOWN_KEY = "mg_wn_last_shown_at";
14
+
15
+ function readStorage(key: string): string | null {
16
+ try {
17
+ return localStorage.getItem(key);
18
+ } catch {
19
+ return null;
20
+ }
21
+ }
22
+
23
+ function writeStorage(key: string, value: string) {
24
+ try {
25
+ localStorage.setItem(key, value);
26
+ } catch {
27
+ // private mode / quota — the server is the source of truth anyway
28
+ }
29
+ }
30
+
31
+ /** Anonymous random id, generated once per browser; never derived from the user. */
32
+ export function getDeviceId(): string {
33
+ const existing = readStorage(DEVICE_KEY);
34
+ if (existing) return existing;
35
+ const id = newDeviceId();
36
+ writeStorage(DEVICE_KEY, id);
37
+ return id;
38
+ }
39
+
40
+ function getConfig() {
41
+ const runtimeConfig = useRuntimeConfig();
42
+ const shared: any = runtimeConfig.public.mgSharedUi || {};
43
+ return {
44
+ networkBaseUrl: (shared.networkBaseUrl || import.meta.env.VITE_BASE_URL_NETWORK || "") as string,
45
+ platformId: Number(shared.systemId || import.meta.env.VITE_SYSTEM_ID),
46
+ };
47
+ }
48
+
49
+ // Kept outside state: never serialized, never shared between tabs.
50
+ let pendingEvents: WnReceiptEvent[] = [];
51
+ let flushTimer: ReturnType<typeof setTimeout> | null = null;
52
+
53
+ export const useWhatsNewStore = defineStore("whats-new-store", {
54
+ // The definition is cached in memory only (it carries the user's first name).
55
+ state: () => ({
56
+ post: null as WnPost | null,
57
+ remaining: 0,
58
+ fetchedFor: null as string | null,
59
+ loading: false,
60
+ shownThisSession: false,
61
+ open: false,
62
+ }),
63
+
64
+ actions: {
65
+ lastShownAt(): number | null {
66
+ const raw = readStorage(LAST_SHOWN_KEY);
67
+ const n = raw ? Number(raw) : NaN;
68
+ return Number.isFinite(n) ? n : null;
69
+ },
70
+
71
+ /** One `pending` call per session / login identity. */
72
+ async fetchPending(identity: string, locale: string) {
73
+ if (this.fetchedFor === identity || this.loading) return;
74
+ const { networkBaseUrl, platformId } = getConfig();
75
+ if (!networkBaseUrl || !platformId) return;
76
+
77
+ this.loading = true;
78
+ this.fetchedFor = identity;
79
+ try {
80
+ const params = new URLSearchParams({
81
+ platform_id: String(platformId),
82
+ surface: "web",
83
+ lang: toApiLang(locale),
84
+ device_id: getDeviceId(),
85
+ });
86
+ const res: any = await $fetch(`${networkBaseUrl}/whats-new/pending?${params.toString()}`, {
87
+ credentials: "include",
88
+ timeout: 8000,
89
+ retry: 0,
90
+ });
91
+ // Logged out / switched user while the request was in flight.
92
+ if (this.fetchedFor !== identity) return;
93
+ this.post = res?.data ?? null;
94
+ this.remaining = Number(res?.remaining ?? 0);
95
+ } catch {
96
+ // Non-critical: a failed call just means no comunicado this session.
97
+ this.post = null;
98
+ this.fetchedFor = null;
99
+ } finally {
100
+ this.loading = false;
101
+ }
102
+ },
103
+
104
+ /** Opens the modal: marks the session, stamps the 24h gap and records `view`. */
105
+ show() {
106
+ if (!this.post) return;
107
+ this.open = true;
108
+ this.shownThisSession = true;
109
+ writeStorage(LAST_SHOWN_KEY, String(Date.now()));
110
+ this.track("view");
111
+ },
112
+
113
+ hide() {
114
+ this.open = false;
115
+ this.flush();
116
+ },
117
+
118
+ reset() {
119
+ this.post = null;
120
+ this.remaining = 0;
121
+ this.fetchedFor = null;
122
+ this.open = false;
123
+ },
124
+
125
+ track(event: WnEventName, target?: string) {
126
+ if (!this.post) return;
127
+ const { platformId } = getConfig();
128
+ if (!platformId) return;
129
+ const entry: WnReceiptEvent = {
130
+ post_id: this.post.id,
131
+ post_version: this.post.version,
132
+ event,
133
+ platform_id: platformId,
134
+ surface: "web",
135
+ device_id: getDeviceId(),
136
+ occurred_at: new Date().toISOString(),
137
+ };
138
+ if (target) entry.target = target;
139
+ pendingEvents.push(entry);
140
+ if (pendingEvents.length >= WN_MAX_BATCH) this.flush();
141
+ else if (!flushTimer) flushTimer = setTimeout(() => this.flush(), 1500);
142
+ },
143
+
144
+ /** Sends queued events in batches of ≤20. keepalive lets it survive a page unload. */
145
+ flush() {
146
+ if (flushTimer) {
147
+ clearTimeout(flushTimer);
148
+ flushTimer = null;
149
+ }
150
+ if (!pendingEvents.length) return;
151
+ const { networkBaseUrl } = getConfig();
152
+ const events = pendingEvents;
153
+ pendingEvents = [];
154
+ if (!networkBaseUrl) return;
155
+ for (const batch of chunkEvents(events)) {
156
+ fetch(`${networkBaseUrl}/whats-new/receipts`, {
157
+ method: "POST",
158
+ credentials: "include",
159
+ keepalive: true,
160
+ headers: { "Content-Type": "application/json", Accept: "application/json" },
161
+ body: JSON.stringify({ events: batch }),
162
+ }).catch(() => {});
163
+ }
164
+ },
165
+ },
166
+ });
167
+
168
+ if (import.meta.hot) {
169
+ import.meta.hot.accept(acceptHMRUpdate(useWhatsNewStore, import.meta.hot));
170
+ }
package/types/index.ts CHANGED
@@ -114,8 +114,6 @@ export interface MgSharedUiConfig {
114
114
  systemId: string;
115
115
  apiBaseURL: string;
116
116
  accountsBaseUrl: string;
117
- communityApiUrl?: string;
118
- communitySiteUrl?: string;
119
117
  features: {
120
118
  chat: boolean;
121
119
  notifications: boolean;
@@ -123,7 +121,6 @@ export interface MgSharedUiConfig {
123
121
  darkMode: boolean;
124
122
  search: boolean;
125
123
  statusOnline: boolean;
126
- gamification?: boolean;
127
124
  };
128
125
  languages: string[];
129
126
  protectedRoutes: string[];
@@ -9,7 +9,6 @@
9
9
  * The fix: clear the auth credentials CLIENT-SIDE so the next request is a clean
10
10
  * guest request and the user can log in again.
11
11
  */
12
- import { useAuthStore } from "../stores/auth";
13
12
 
14
13
  // Auth-related cookies set across the MGN ecosystem.
15
14
  const AUTH_COOKIES = [
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Which message a failed key request deserves.
3
+ *
4
+ * Every 403 used to read "not available for your current plan", whatever the
5
+ * real reason was: a closed campaign, the wrong country, a creator who is not on
6
+ * the campaign's list, a streamer level that is too low. People were told to
7
+ * upgrade a plan that had nothing to do with it. The API already says why
8
+ * (error_code / reason / requires_tier / requires_streamer_type); this turns
9
+ * that into one i18n key so every page that sends a request answers the same
10
+ * way.
11
+ *
12
+ * Returns the i18n key and its params, or null for errors that have no specific
13
+ * message (the caller keeps its own fallback).
14
+ */
15
+ export interface KeyRequestErrorMessage {
16
+ key: string
17
+ params?: Record<string, string>
18
+ }
19
+
20
+ export function keyRequestErrorMessage(err: any): KeyRequestErrorMessage | null {
21
+ const status = err?.response?.status
22
+ const data = err?.response?.data ?? {}
23
+ const errorCode: string | undefined = data.error_code
24
+ const reason: string | undefined = data.reason
25
+
26
+ if (status === 409) return { key: "keys.campaigns.error_duplicate" }
27
+
28
+ if (status === 422 && errorCode === "pending_limit_reached") {
29
+ return { key: "keys.campaigns.error_pending_limit" }
30
+ }
31
+
32
+ if (status !== 403) return null
33
+
34
+ if (errorCode === "user_key_blocked") return { key: "keys.campaigns.error_user_blocked" }
35
+ if (errorCode === "campaign_not_open_yet") return { key: "keys.campaigns.error_not_open_yet" }
36
+ if (errorCode === "campaign_closed") return { key: "keys.campaigns.error_closed" }
37
+
38
+ if (errorCode === "access_denied") {
39
+ if (reason === "COUNTRY_NOT_ELIGIBLE") return { key: "keys.campaigns.error_country" }
40
+ if (reason === "NOT_AN_APPROVED_CREATOR") return { key: "keys.campaigns.error_not_approved_creator" }
41
+ // Not signed in (any more): a session problem, not a plan problem.
42
+ if (reason === "UNAUTHENTICATED") return { key: "keys.campaigns.error_session_expired" }
43
+ }
44
+
45
+ // Plan lock: name the plan that is actually required.
46
+ if (data.requires_tier) {
47
+ return { key: "keys.campaigns.error_tier_locked", params: { tier: String(data.requires_tier) } }
48
+ }
49
+
50
+ if (data.requires_streamer_type) return { key: "keys.campaigns.error_streamer_level" }
51
+
52
+ // A 403 we do not recognise keeps the generic message.
53
+ return { key: "keys.campaigns.error_not_eligible" }
54
+ }
@@ -0,0 +1,300 @@
1
+ /**
2
+ * "Novidades da Rede" (What's New) — pure helpers shared by the store, the
3
+ * modal and the vitest suite. Nothing here touches Nuxt auto-imports or the
4
+ * DOM at import time, so it runs unchanged under plain Node.
5
+ */
6
+
7
+ export type WnSectionType = "feature" | "improvement" | "fix" | "note";
8
+ export type WnMediaType = "image" | "gif" | "video_upload" | "video_embed";
9
+ export type WnEventName = "view" | "dismiss" | "cta_click" | "video_play" | "link_click";
10
+
11
+ export interface WnMedia {
12
+ type: WnMediaType;
13
+ url: string | null;
14
+ poster_url: string | null;
15
+ width: number | null;
16
+ height: number | null;
17
+ duration_s: number | null;
18
+ embed: { provider: "youtube" | "vimeo"; id: string; watch_url?: string | null } | null;
19
+ description: string | null;
20
+ }
21
+
22
+ export interface WnItem {
23
+ body: string;
24
+ link_url: string | null;
25
+ }
26
+
27
+ export interface WnSection {
28
+ type: WnSectionType;
29
+ title: string;
30
+ items: WnItem[];
31
+ }
32
+
33
+ export interface WnPost {
34
+ id: number;
35
+ version: number;
36
+ kind: "release" | "update" | "launch" | "maintenance";
37
+ title: string;
38
+ summary: string | null;
39
+ published_at: string | null;
40
+ display_mode: "once" | "until_dismissed";
41
+ media: WnMedia | null;
42
+ sections: WnSection[];
43
+ cta: { label: string; type: "url" | "app_route"; target: string } | null;
44
+ links: { kind: "social" | "link"; label: string; url: string }[];
45
+ history_url: string | null;
46
+ }
47
+
48
+ // ─── Inline markup: **bold** and [text](url) ────────────────────────────────
49
+
50
+ /** The single link regex shared with every other client (see the contract). */
51
+ export const WN_LINK_SOURCE = String.raw`\[([^\[\]]+)\]\(([^()\s"<>]+)\)`;
52
+ const WN_BOLD_RE = /\*\*(.+?)\*\*/g;
53
+
54
+ export type WnLinkKind = "external" | "internal";
55
+
56
+ /**
57
+ * Only `https://…` (external) and `/path` (internal, never `//host`) may become
58
+ * links. Everything else — http:, javascript:, data:, protocol-relative — is
59
+ * rejected and the caller renders plain text.
60
+ */
61
+ export function classifyHref(href: string | null | undefined): WnLinkKind | null {
62
+ if (!href || typeof href !== "string") return null;
63
+ const value = href.trim();
64
+ if (/\s/.test(value)) return null;
65
+ if (/^https:\/\/[^/\s]+/i.test(value)) return "external";
66
+ if (value.startsWith("/") && !value.startsWith("//") && !value.startsWith("/\\")) return "internal";
67
+ return null;
68
+ }
69
+
70
+ export type WnNode =
71
+ | { type: "text"; text: string }
72
+ | { type: "bold"; text: string }
73
+ | { type: "link"; href: string; kind: WnLinkKind; children: WnNode[] };
74
+
75
+ function parseBold(text: string): WnNode[] {
76
+ const nodes: WnNode[] = [];
77
+ let last = 0;
78
+ for (const match of text.matchAll(WN_BOLD_RE)) {
79
+ const start = match.index ?? 0;
80
+ if (start > last) nodes.push({ type: "text", text: text.slice(last, start) });
81
+ nodes.push({ type: "bold", text: match[1] });
82
+ last = start + match[0].length;
83
+ }
84
+ if (last < text.length) nodes.push({ type: "text", text: text.slice(last) });
85
+ return nodes;
86
+ }
87
+
88
+ /**
89
+ * Turns server text into a flat, safe node list. No HTML is ever produced: the
90
+ * renderer builds text nodes, <strong> and <a> from this structure.
91
+ * `allowLinks:false` flattens links to their label (used when the whole item is
92
+ * already a link, to avoid nested anchors).
93
+ */
94
+ export function parseRich(text: string | null | undefined, allowLinks = true): WnNode[] {
95
+ if (!text) return [];
96
+ const nodes: WnNode[] = [];
97
+ const re = new RegExp(WN_LINK_SOURCE, "g");
98
+ let last = 0;
99
+ for (const match of text.matchAll(re)) {
100
+ const start = match.index ?? 0;
101
+ if (start > last) nodes.push(...parseBold(text.slice(last, start)));
102
+ const kind = allowLinks ? classifyHref(match[2]) : null;
103
+ if (kind) nodes.push({ type: "link", href: match[2], kind, children: parseBold(match[1]) });
104
+ else nodes.push(...parseBold(match[1]));
105
+ last = start + match[0].length;
106
+ }
107
+ if (last < text.length) nodes.push(...parseBold(text.slice(last)));
108
+ return nodes;
109
+ }
110
+
111
+ /** Plain-text version (used for aria labels). */
112
+ export function richToPlain(nodes: WnNode[]): string {
113
+ return nodes
114
+ .map((n) => (n.type === "link" ? richToPlain(n.children) : n.text))
115
+ .join("");
116
+ }
117
+
118
+ // ─── Locale ────────────────────────────────────────────────────────────────
119
+
120
+ export const WN_UI_LOCALES = ["en", "pt-BR", "de", "es", "ro", "ar"] as const;
121
+ export type WnUiLocale = (typeof WN_UI_LOCALES)[number];
122
+
123
+ /** Locale code sent to the API (`lang`). ar-AE → ar; unknown stays as-is. */
124
+ export function toApiLang(code: string | null | undefined): string {
125
+ const raw = String(code || "en").replace("_", "-");
126
+ const lower = raw.toLowerCase();
127
+ if (lower.startsWith("ar")) return "ar";
128
+ if (lower === "pt" || lower.startsWith("pt-")) return "pt-BR";
129
+ const base = lower.split("-")[0];
130
+ if (base === "en" || base === "de" || base === "es" || base === "ro") return base;
131
+ return "en";
132
+ }
133
+
134
+ /** Dictionary used for the fixed modal copy (en, pt-BR, de, es, ro, ar); anything else falls back to en. */
135
+ export function toUiLocale(code: string | null | undefined): WnUiLocale {
136
+ const api = toApiLang(code);
137
+ return (WN_UI_LOCALES as readonly string[]).includes(api) ? (api as WnUiLocale) : "en";
138
+ }
139
+
140
+ export function isRtl(code: string | null | undefined): boolean {
141
+ return toApiLang(code) === "ar";
142
+ }
143
+
144
+ // ─── Where the modal may appear ────────────────────────────────────────────
145
+
146
+ const LOCALE_PREFIX_RE = /^\/(en|pt-BR|pt|de|es|ro|ar-AE|ar)(?=\/|$)/i;
147
+
148
+ export function normalizePath(path: string): string {
149
+ let p = (path || "/").split("?")[0].split("#")[0];
150
+ p = p.replace(LOCALE_PREFIX_RE, "");
151
+ if (!p.startsWith("/")) p = "/" + p;
152
+ if (p.length > 1) p = p.replace(/\/+$/, "");
153
+ return p || "/";
154
+ }
155
+
156
+ /** Whole-segment words that mean "a flow the user must not be interrupted in". */
157
+ const BLOCKED_EXACT = new Set(["new", "novo", "nova", "edit", "editar", "submit", "pay", "oauth", "callback"]);
158
+ /** Words that block when they appear as a token of a segment (create-jam, jam-wizard). */
159
+ const BLOCKED_TOKENS = new Set([
160
+ "login", "logout", "signin", "signup", "register", "registro", "cadastro", "entrar",
161
+ "checkout", "payment", "payments", "pagamento", "pagamentos",
162
+ "create", "criar", "publish", "publicar", "upload", "wizard", "editor", "onboarding",
163
+ ]);
164
+
165
+ export function isBlockedPath(path: string, extra: (string | RegExp)[] = []): boolean {
166
+ const normalized = normalizePath(path);
167
+ const segments = normalized.split("/").filter(Boolean);
168
+ for (const segment of segments) {
169
+ const lower = segment.toLowerCase();
170
+ if (BLOCKED_EXACT.has(lower)) return true;
171
+ if (lower.split(/[-_]/).some((token) => BLOCKED_TOKENS.has(token))) return true;
172
+ }
173
+ return extra.some((rule) => matchesRoute(normalized, rule));
174
+ }
175
+
176
+ /** String rules are path prefixes ("/" matches only the root); RegExp rules test the normalized path. */
177
+ export function matchesRoute(normalizedPath: string, rule: string | RegExp): boolean {
178
+ if (rule instanceof RegExp) return rule.test(normalizedPath);
179
+ const r = normalizePath(rule);
180
+ if (r === "/") return normalizedPath === "/";
181
+ return normalizedPath === r || normalizedPath.startsWith(r + "/");
182
+ }
183
+
184
+ export const WN_IDLE_MS = 2500;
185
+ export const WN_MIN_GAP_MS = 24 * 60 * 60 * 1000;
186
+
187
+ export interface WnGateInput {
188
+ loggedIn: boolean;
189
+ path: string;
190
+ allowedRoutes?: (string | RegExp)[];
191
+ blockedRoutes?: (string | RegExp)[];
192
+ shownThisSession: boolean;
193
+ lastShownAt: number | null;
194
+ now: number;
195
+ suppressed: boolean;
196
+ otherModalOpen: boolean;
197
+ pageVisible: boolean;
198
+ }
199
+
200
+ export type WnGateResult = "ok" | "logged_out" | "session" | "gap" | "route" | "suppressed" | "other_modal" | "hidden";
201
+
202
+ /** Decides whether a comunicado may open right now. Pure so it can be tested. */
203
+ export function gate(input: WnGateInput): WnGateResult {
204
+ if (!input.loggedIn) return "logged_out";
205
+ if (input.shownThisSession) return "session";
206
+ if (input.lastShownAt !== null && input.now - input.lastShownAt < WN_MIN_GAP_MS) return "gap";
207
+ const normalized = normalizePath(input.path);
208
+ if (isBlockedPath(input.path, input.blockedRoutes)) return "route";
209
+ if (input.allowedRoutes?.length && !input.allowedRoutes.some((rule) => matchesRoute(normalized, rule))) return "route";
210
+ if (input.suppressed) return "suppressed";
211
+ if (input.otherModalOpen) return "other_modal";
212
+ if (!input.pageVisible) return "hidden";
213
+ return "ok";
214
+ }
215
+
216
+ // ─── Video embeds ──────────────────────────────────────────────────────────
217
+
218
+ /** Cookie-less player URL, or null when the provider/id is not what we expect. */
219
+ export function embedSrc(provider: string, id: string): string | null {
220
+ if (provider === "youtube" && /^[\w-]{6,20}$/.test(id)) {
221
+ return `https://www.youtube-nocookie.com/embed/${id}?autoplay=1&rel=0&playsinline=1`;
222
+ }
223
+ if (provider === "vimeo" && /^\d{3,12}$/.test(id)) {
224
+ return `https://player.vimeo.com/video/${id}?dnt=1&autoplay=1`;
225
+ }
226
+ return null;
227
+ }
228
+
229
+ // ─── Receipts ──────────────────────────────────────────────────────────────
230
+
231
+ export interface WnReceiptEvent {
232
+ post_id: number;
233
+ post_version: number;
234
+ event: WnEventName;
235
+ platform_id: number;
236
+ surface: "web";
237
+ device_id: string;
238
+ occurred_at: string;
239
+ target?: string;
240
+ }
241
+
242
+ export const WN_MAX_BATCH = 20;
243
+
244
+ /** Splits a queue into API-sized batches (the endpoint takes 1–20 events). */
245
+ export function chunkEvents<T>(events: T[], size = WN_MAX_BATCH): T[][] {
246
+ const out: T[][] = [];
247
+ for (let i = 0; i < events.length; i += size) out.push(events.slice(i, i + size));
248
+ return out;
249
+ }
250
+
251
+ export function newDeviceId(): string {
252
+ const c: any = typeof globalThis !== "undefined" ? (globalThis as any).crypto : undefined;
253
+ if (c?.randomUUID) return c.randomUUID();
254
+ // RFC4122 v4 from getRandomValues, last resort Math.random (device id is not a secret).
255
+ const bytes = new Uint8Array(16);
256
+ if (c?.getRandomValues) c.getRandomValues(bytes);
257
+ else for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256);
258
+ bytes[6] = (bytes[6] & 0x0f) | 0x40;
259
+ bytes[8] = (bytes[8] & 0x3f) | 0x80;
260
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0"));
261
+ return `${hex.slice(0, 4).join("")}-${hex.slice(4, 6).join("")}-${hex.slice(6, 8).join("")}-${hex.slice(8, 10).join("")}-${hex.slice(10).join("")}`;
262
+ }
263
+
264
+ /** Media/poster URLs must be https (or same-origin paths); anything else is dropped. */
265
+ export function safeMediaUrl(url: string | null | undefined): string | null {
266
+ return classifyHref(url) ? (url as string) : null;
267
+ }
268
+
269
+ /** Shallow shape check for payloads that arrive from outside (admin preview). */
270
+ export function isWnPost(value: any): value is WnPost {
271
+ return (
272
+ !!value &&
273
+ typeof value === "object" &&
274
+ typeof value.title === "string" &&
275
+ Array.isArray(value.sections ?? []) &&
276
+ (value.cta == null || typeof value.cta === "object")
277
+ );
278
+ }
279
+
280
+ export function normalizeWnPost(value: any): WnPost | null {
281
+ if (!isWnPost(value)) return null;
282
+ return {
283
+ id: Number(value.id) || 0,
284
+ version: Number(value.version) || 1,
285
+ kind: value.kind || "update",
286
+ title: value.title,
287
+ summary: value.summary ?? null,
288
+ published_at: value.published_at ?? null,
289
+ display_mode: value.display_mode || "once",
290
+ media: value.media ?? null,
291
+ sections: (value.sections ?? []).map((s: any) => ({
292
+ type: s.type || "note",
293
+ title: s.title || "",
294
+ items: (s.items ?? []).map((i: any) => ({ body: String(i.body ?? ""), link_url: i.link_url ?? null })),
295
+ })),
296
+ cta: value.cta ?? null,
297
+ links: value.links ?? [],
298
+ history_url: value.history_url ?? null,
299
+ };
300
+ }