waybetter-for-x/apps/desktop/src-tauri/observer.js
2026-09-30 23:01:13 +00:00

928 lines
36 KiB
JavaScript

"use strict";
(() => {
// src/observer/relationships.ts
var object = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
function parseRelationshipObservations(body) {
const output = /* @__PURE__ */ new Map();
const pending = [{ value: body, depth: 0 }];
const visited = /* @__PURE__ */ new Set();
let examined = 0;
while (pending.length && examined++ < 2048 && output.size < 64) {
const { value, depth } = pending.pop();
if (!value || typeof value !== "object" || depth > 20 || visited.has(value)) continue;
visited.add(value);
if (object(value)) {
const legacy = object(value.legacy) ? value.legacy : void 0;
const perspective = object(value.relationship_perspectives) ? value.relationship_perspectives : void 0;
if (value.__typename === "User" && typeof value.rest_id === "string" && /^\d{1,25}$/.test(value.rest_id)) {
const following = typeof perspective?.following === "boolean" ? perspective.following : typeof legacy?.following === "boolean" ? legacy.following : null;
const followedBy = typeof perspective?.followed_by === "boolean" ? perspective.followed_by : typeof legacy?.followed_by === "boolean" ? legacy.followed_by : null;
if (following !== null || followedBy !== null) {
output.set(value.rest_id, { userId: value.rest_id, following, followedBy });
}
}
}
let childCount = 0;
for (const key in value) {
if (!Object.prototype.hasOwnProperty.call(value, key)) continue;
if (++childCount > 128 || pending.length >= 2048) break;
const child = value[key];
if (child && typeof child === "object") pending.push({ value: child, depth: depth + 1 });
}
}
return [...output.values()];
}
// src/observer/network.ts
var OBSERVATION_EVENT = "x-workspace:relationship-observation";
var MAX_RESPONSE_BYTES = 64 * 1024;
var MAX_OBSERVATION_READERS = 4;
var MAX_OBSERVATION_READ_MS = 1500;
var installations = /* @__PURE__ */ new WeakMap();
function isSupportedPage(target) {
try {
return target.top === target && target.location.origin === "https://x.com";
} catch {
return false;
}
}
var CHAT_PATH = /^\/(?:messages|i\/chat)(?:\/|$)/i;
function eligibleUrl(input, base) {
try {
const raw = typeof input === "string" ? input : input instanceof URL ? input.href : input && typeof input === "object" && "url" in input ? String(input.url) : "";
if (!raw.includes("/i/api/")) return false;
const url = new URL(raw, base);
return url.origin === "https://x.com" && url.pathname.startsWith("/i/api/");
} catch {
return false;
}
}
function jsonType(contentType) {
return Boolean(contentType && /^application\/(?:[\w.-]+\+)?json(?:\s*;|$)/i.test(contentType));
}
function declaredTooLarge(length) {
return length !== null && (!/^\d+$/.test(length) || Number(length) > MAX_RESPONSE_BYTES);
}
async function readSmallJson(response, signal) {
if (signal.aborted) return;
if (!jsonType(response.headers.get("content-type")) || declaredTooLarge(response.headers.get("content-length"))) return;
if (!response.body) return;
const clone = response.clone();
const reader = clone.body.getReader();
const cancel = () => {
void reader.cancel().catch(() => {
});
};
signal.addEventListener("abort", cancel, { once: true });
const decoder = new TextDecoder();
let text = "";
let bytes = 0;
try {
while (true) {
const chunk = await reader.read();
if (signal.aborted) return;
if (chunk.done) break;
bytes += chunk.value.byteLength;
if (bytes > MAX_RESPONSE_BYTES) return;
text += decoder.decode(chunk.value, { stream: true });
}
text += decoder.decode();
return JSON.parse(text);
} catch {
return;
} finally {
signal.removeEventListener("abort", cancel);
cancel();
reader.releaseLock();
}
}
function installResponseObserver(target = window, options = {}) {
const existing = installations.get(target);
if (existing) return existing;
if (!isSupportedPage(target)) return { installed: false, reason: "Only the top-level https://x.com page is supported.", advanceEpoch: () => 0, dispose() {
} };
const page = target;
let epoch = 0;
let active = true;
const activeReaders = /* @__PURE__ */ new Set();
let pageUrl = page.location.href;
const stamp = () => {
if (page.location.href !== pageUrl) {
pageUrl = page.location.href;
epoch++;
for (const reader of activeReaders) reader.abort();
}
return { requestEpoch: epoch, requestStartedAt: (/* @__PURE__ */ new Date()).toISOString() };
};
const emit = (body, started) => {
if (!active || started.requestEpoch !== epoch) return;
for (const relation of parseRelationshipObservations(body)) {
const event = {
...relation,
...started,
accountId: null,
observedAt: (/* @__PURE__ */ new Date()).toISOString(),
source: "x-page-response:unverified-schema"
};
try {
options.onObservation?.(event);
} catch {
}
try {
target.dispatchEvent(new page.CustomEvent(OBSERVATION_EVENT, { detail: event }));
} catch {
}
}
};
const originalFetch = page.fetch;
const onChat = () => CHAT_PATH.test(page.location.pathname ?? "");
const fetchWrapper = function(...args) {
if (!eligibleUrl(args[0], page.location.href) || onChat()) return Reflect.apply(originalFetch, this, args);
const started = stamp();
const result = Reflect.apply(originalFetch, this, args);
void result.then((response) => {
if (active && started.requestEpoch === epoch && activeReaders.size < MAX_OBSERVATION_READERS && response.ok && (!response.url || eligibleUrl(response.url, page.location.href))) {
const controller = new AbortController();
activeReaders.add(controller);
const timeout = setTimeout(() => controller.abort(), MAX_OBSERVATION_READ_MS);
void readSmallJson(response, controller.signal).then((body) => emit(body, started)).catch(() => {
}).finally(() => {
clearTimeout(timeout);
activeReaders.delete(controller);
});
}
}, () => {
}).catch(() => {
});
return result;
};
let fetchPatched = false;
try {
page.fetch = fetchWrapper;
fetchPatched = page.fetch === fetchWrapper;
} catch {
}
const prototype = page.XMLHttpRequest?.prototype;
const originalOpen = prototype?.open;
const originalSend = prototype?.send;
const states = /* @__PURE__ */ new WeakMap();
const pendingListeners = /* @__PURE__ */ new Set();
const openWrapper = function(...args) {
const result = Reflect.apply(originalOpen, this, args);
states.get(this)?.cleanup?.();
states.set(this, { url: String(args[1]) });
return result;
};
const sendWrapper = function(...args) {
const state = states.get(this);
if (!state || !eligibleUrl(state.url, page.location.href) || onChat()) return Reflect.apply(originalSend, this, args);
const started = stamp();
const cleanup = () => {
this.removeEventListener("load", onLoad);
this.removeEventListener("loadend", cleanup);
pendingListeners.delete(cleanup);
if (state.cleanup === cleanup) state.cleanup = void 0;
};
const onLoad = () => {
try {
if (!active || this.status < 200 || this.status >= 300) return;
if (this.responseURL && !eligibleUrl(this.responseURL, page.location.href)) return;
if (!jsonType(this.getResponseHeader("content-type"))) return;
const length = this.getResponseHeader("content-length");
if (declaredTooLarge(length)) return;
if (this.responseType === "" || this.responseType === "text") {
const text = this.responseText;
if (text.length > MAX_RESPONSE_BYTES || new TextEncoder().encode(text).byteLength > MAX_RESPONSE_BYTES) return;
emit(JSON.parse(text), started);
} else if (this.responseType === "json" && length !== null) {
emit(this.response, started);
}
} catch {
}
};
state.cleanup = cleanup;
pendingListeners.add(cleanup);
this.addEventListener("load", onLoad);
this.addEventListener("loadend", cleanup, { once: true });
try {
return Reflect.apply(originalSend, this, args);
} catch (error) {
cleanup();
throw error;
}
};
let xhrPatched = false;
if (prototype) {
try {
prototype.open = openWrapper;
prototype.send = sendWrapper;
xhrPatched = prototype.open === openWrapper && prototype.send === sendWrapper;
} catch {
}
}
const handle = {
installed: fetchPatched || xhrPatched,
...!fetchPatched && !xhrPatched ? { reason: "Page request hooks are unavailable." } : {},
advanceEpoch() {
for (const reader of activeReaders) reader.abort();
return ++epoch;
},
dispose() {
if (!active) return;
active = false;
for (const reader of activeReaders) reader.abort();
if (page.fetch === fetchWrapper) page.fetch = originalFetch;
if (prototype?.open === openWrapper) prototype.open = originalOpen;
if (prototype?.send === sendWrapper) prototype.send = originalSend;
for (const cleanup of pendingListeners) cleanup();
installations.delete(target);
}
};
installations.set(target, handle);
return handle;
}
// src/core/text.ts
var translate = (key) => key;
function setCoreText(fn) {
translate = fn;
}
function coreText(key, params) {
return translate(key, params);
}
// src/observer/capture-queue.ts
var same = (left, right) => Boolean(left && right && left.text === right.text && left.contextUrl === right.contextUrl && left.kind === right.kind);
function createCaptureQueue(options) {
let sequence = 0;
let pending;
let acknowledged;
let failed;
let running;
let status = "idle";
const setStatus = (next) => {
status = next;
try {
options.onStatus?.(next);
} catch {
}
};
const drain = () => {
if (running) return running;
if (!failed && !pending) return Promise.resolve();
running = Promise.resolve().then(async () => {
while (failed || pending) {
const capture = failed ?? { ...pending, composerId: options.composerId, sequence: ++sequence };
if (!failed) pending = void 0;
failed = void 0;
setStatus("saving");
try {
const ack = await options.save(capture);
if (!ack || ack.sequence !== capture.sequence || !Number.isSafeInteger(ack.revision) || ack.revision < 1) throw new Error("Invalid native acknowledgement");
acknowledged = capture;
if (same(pending, acknowledged)) pending = void 0;
} catch {
failed = capture;
setStatus("error");
return;
}
}
setStatus("saved");
}).finally(() => {
running = void 0;
if (pending && !failed) void drain();
});
return running;
};
return {
enqueue(snapshot) {
if (!failed && !pending && same(snapshot, acknowledged)) return;
pending = { ...snapshot };
setStatus("pending");
void drain();
},
retry() {
void drain();
},
flush: drain,
getStatus: () => status
};
}
// src/observer/composer.ts
var COMPOSER_SELECTOR = '[data-testid^="tweetTextarea_"][role="textbox"][contenteditable="true"]';
var MAX_CAPTURE_BYTES = 65536;
var BUTTON_SELECTOR = '[data-testid="tweetButton"],[data-testid="tweetButtonInline"]';
var installations2 = /* @__PURE__ */ new WeakMap();
function isExcludedComposerPath(pathname) {
return /^\/(?:messages|i\/(?:chat|grok))(?:\/|$)/i.test(pathname);
}
function identifyComposer(editor, location) {
if (location.origin !== "https://x.com" || isExcludedComposerPath(location.pathname)) return null;
if (!editor.matches(COMPOSER_SELECTOR) || editor.getAttribute("data-testid") !== "tweetTextarea_0") return null;
if (!editor.closest('[role="dialog"],[data-testid="primaryColumn"]')) return null;
let area = editor.parentElement;
for (let depth = 0; area && depth < 40; depth++, area = area.parentElement) {
if (area.querySelector(BUTTON_SELECTOR)) break;
if (area.matches('main,body,[data-testid="primaryColumn"]')) return null;
}
if (!area || !area.querySelector(BUTTON_SELECTOR) || area.querySelectorAll(COMPOSER_SELECTOR).length !== 1) return null;
const quote = area.querySelector('[data-testid="quoteTweet"]');
const reply = area.querySelector('[data-testid="replyingTo"]');
const kind = quote ? "quote" : reply || /^\/[^/]+\/status\/\d+(?:\/|$)/.test(location.pathname) ? "reply" : "post";
let contextUrl = `${location.origin}${location.pathname}`;
const anchor = quote?.querySelector('a[href*="/status/"]');
if (anchor) {
try {
const url = new URL(anchor.getAttribute("href"), location.href);
if (url.origin === "https://x.com" && /^\/[^/]+\/status\/\d+(?:\/|$)/.test(url.pathname)) contextUrl = `${url.origin}${url.pathname}`;
} catch {
}
}
return { kind, contextUrl };
}
function installComposerCapture(target = window, options = {}) {
const existing = installations2.get(target);
if (existing) return existing;
if (!isSupportedPage(target)) return { installed: false, reason: "Only the top-level https://x.com page is supported.", scan() {
}, dispose() {
} };
const page = target;
const invoke = options.invoke ?? page.__TAURI__?.core?.invoke;
const doc = page.document;
const states = /* @__PURE__ */ new Map();
const retired = /* @__PURE__ */ new Set();
const seenEditors = /* @__PURE__ */ new WeakSet();
const allStates = () => [...states.values(), ...retired];
let active = true;
let scanTimer;
const panel = doc.createElement("div");
panel.id = "x-workspace-capture-status";
panel.setAttribute("role", "status");
panel.setAttribute("aria-live", "polite");
panel.style.cssText = "position:fixed;bottom:16px;left:50%;transform:translateX(-50%);z-index:2147483646;padding:7px 12px;border-radius:999px;background:rgba(21,27,35,.94);color:#edf2f7;border:1px solid #3b4a5a;font:12px/1.4 system-ui,sans-serif;max-width:min(420px,90vw);box-shadow:0 4px 16px rgba(0,0,0,.35);pointer-events:auto;";
panel.hidden = true;
const title = doc.createElement("div");
title.textContent = coreText("x.capture.title");
title.style.cssText = "font-weight:600;display:none;";
const status = doc.createElement("div");
const note = doc.createElement("div");
note.textContent = coreText("x.capture.note");
note.style.cssText = "display:none;";
const retry = doc.createElement("button");
retry.textContent = coreText("x.capture.retry");
retry.type = "button";
retry.style.cssText = "margin-top:5px;padding:3px 7px;background:#344254;color:white;border:1px solid #8793a2;border-radius:4px;cursor:pointer;";
retry.hidden = true;
panel.append(title, status, note, retry);
let latestLabel = "";
let hideTimer;
const render2 = () => {
if (!active) return;
const all = allStates();
const connected = [...states.values()].filter((state) => state.editor.isConnected && identifyComposer(state.editor, page.location));
const failed = all.some((state) => state.queue.getStatus() === "error");
const debouncing = all.some((state) => state.timer);
const saving = all.some((state) => ["pending", "saving"].includes(state.queue.getStatus()));
const oversized = connected.some((state) => state.oversized);
const savedNow = all.some((state) => state.queue.getStatus() === "saved");
const key = !invoke ? "x.capture.unavailable" : failed ? "x.capture.failed" : oversized ? "x.capture.oversized" : debouncing ? "x.capture.waiting" : saving ? "x.capture.saving" : isExcludedComposerPath(page.location.pathname) ? "x.capture.unsupported" : !connected.length ? "x.capture.idle" : savedNow ? "x.capture.saved" : "x.capture.found";
const label = coreText(key);
if (label !== latestLabel) {
status.textContent = label;
latestLabel = label;
const attention = failed || oversized || debouncing || saving || !invoke;
const justSaved = key === "x.capture.saved";
clearTimeout(hideTimer);
if (attention || justSaved) {
if (panel.hidden) panel.hidden = false;
if (justSaved) hideTimer = setTimeout(() => {
if (latestLabel === label) panel.hidden = true;
}, 2500);
} else if (!panel.hidden) panel.hidden = true;
}
if (retry.hidden === failed) retry.hidden = !failed;
};
const flush = (state) => {
if (state.timer) {
clearTimeout(state.timer);
state.timer = void 0;
}
if (!state.staged) return;
const snapshot = state.staged;
state.staged = void 0;
state.queue.enqueue(snapshot);
};
const scheduleRead = (state) => {
if (!invoke) return;
const context = identifyComposer(state.editor, page.location);
if (!context || context.kind !== state.kind || context.contextUrl !== state.contextUrl) {
render2();
return;
}
const text = !state.editor.textContent ? "" : typeof state.editor.innerText === "string" ? state.editor.innerText : state.editor.textContent;
state.oversized = new TextEncoder().encode(text).byteLength > MAX_CAPTURE_BYTES;
if (state.oversized) {
render2();
return;
}
if (!text && !state.touched) return;
state.touched = true;
state.staged = { text, kind: state.kind, contextUrl: state.contextUrl };
if (state.timer) clearTimeout(state.timer);
state.timer = setTimeout(() => flush(state), 250);
render2();
};
const retire = (state) => {
if (states.get(state.editor) === state) states.delete(state.editor);
retired.add(state);
flush(state);
if (["idle", "saved"].includes(state.queue.getStatus())) retired.delete(state);
};
const scan = () => {
if (!active) return;
if (!panel.isConnected && doc.body) doc.body.append(panel);
for (const [editor, state] of states) {
const context = editor.isConnected ? identifyComposer(editor, page.location) : null;
if (!context || context.kind !== state.kind || context.contextUrl !== state.contextUrl) retire(state);
}
if (invoke && !isExcludedComposerPath(page.location.pathname)) {
const editors = doc.querySelectorAll(COMPOSER_SELECTOR);
for (const editor of editors) {
if (states.has(editor) || states.size + retired.size >= 32) continue;
const context = identifyComposer(editor, page.location);
if (!context) continue;
const reused = seenEditors.has(editor);
seenEditors.add(editor);
const state = {
editor,
touched: false,
oversized: false,
...context,
queue: createCaptureQueue({
composerId: page.crypto.randomUUID(),
save: (capture) => invoke("capture_draft", { capture }),
onStatus: (next) => {
if (next === "saved") retired.delete(state);
render2();
}
})
};
states.set(editor, state);
if (!reused && editor.textContent) scheduleRead(state);
}
}
render2();
};
const onInput = (event) => {
if (!active || isExcludedComposerPath(page.location.pathname)) return;
const eventTarget = event.target;
if (!(eventTarget instanceof page.Element)) return;
const editor = eventTarget.closest(COMPOSER_SELECTOR);
if (!editor) return;
scan();
const state = states.get(editor);
if (state && identifyComposer(editor, page.location)) scheduleRead(state);
};
const onRetry = () => {
for (const state of allStates()) if (state.queue.getStatus() === "error") state.queue.retry();
};
const onPageHide = () => {
for (const state of allStates()) flush(state);
};
const mutation = new page.MutationObserver((records) => {
if (!active || records.every((record) => panel.contains(record.target))) return;
if (scanTimer) clearTimeout(scanTimer);
scanTimer = setTimeout(() => {
scanTimer = void 0;
scan();
}, 100);
});
mutation.observe(doc, { childList: true, subtree: true });
doc.addEventListener("input", onInput, true);
target.addEventListener("popstate", scan);
target.addEventListener("pagehide", onPageHide);
retry.addEventListener("click", onRetry);
const handle = {
installed: Boolean(invoke),
...!invoke ? { reason: "Native capture bridge unavailable." } : {},
scan,
dispose() {
if (!active) return;
onPageHide();
active = false;
if (scanTimer) clearTimeout(scanTimer);
mutation.disconnect();
doc.removeEventListener("input", onInput, true);
target.removeEventListener("popstate", scan);
target.removeEventListener("pagehide", onPageHide);
retry.removeEventListener("click", onRetry);
panel.remove();
states.clear();
retired.clear();
installations2.delete(target);
}
};
installations2.set(target, handle);
scan();
return handle;
}
// src/observer/paint.ts
function watchFirstPaint(options) {
const { doc, clock, painted, report } = options;
const limitMs = options.limitMs ?? 1e4;
let done = false;
let queued = false;
let expiry = null;
const stop = () => {
if (done) return;
done = true;
unobserve();
doc.removeEventListener("visibilitychange", onVisibility);
if (expiry !== null) clock.clearTimeout(expiry);
};
const check = () => {
if (done || queued || doc.visibilityState !== "visible") return;
queued = true;
clock.requestAnimationFrame(() => {
queued = false;
if (done || !painted()) return;
stop();
clock.requestAnimationFrame(() => clock.requestAnimationFrame(report));
});
};
const startExpiry = () => {
if (expiry === null && doc.visibilityState === "visible") expiry = clock.setTimeout(stop, limitMs);
};
function onVisibility() {
if (doc.visibilityState !== "visible") return;
queued = false;
startExpiry();
check();
}
const unobserve = options.changed(check);
doc.addEventListener("visibilitychange", onVisibility);
startExpiry();
check();
return stop;
}
// ../../waybetter/packages/runtime/src/i18n.ts
var MessageSyntaxError = class extends Error {
source;
index;
constructor(message, source, index) {
super(`${message} at ${index} in ${JSON.stringify(source.length > 80 ? `${source.slice(0, 80)}\u2026` : source)}`);
this.name = "MessageSyntaxError";
this.source = source;
this.index = index;
}
};
var NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
function parseMessage(source) {
let i = 0;
const parseParts = (inPlural, depth) => {
const parts2 = [];
let text = "";
const flush = () => {
if (text) parts2.push(text);
text = "";
};
while (i < source.length) {
const ch = source[i];
if (ch === "'") {
const next = source[i + 1];
if (next === "'") {
text += "'";
i += 2;
continue;
}
if (next === "{" || next === "}" || next === "#") {
i += 1;
while (i < source.length) {
if (source[i] === "'") {
if (source[i + 1] === "'") {
text += "'";
i += 2;
continue;
}
i += 1;
break;
}
text += source[i];
i += 1;
}
continue;
}
text += ch;
i += 1;
continue;
}
if (ch === "}") {
if (depth > 0) break;
throw new MessageSyntaxError("unexpected }", source, i);
}
if (ch === "#" && inPlural) {
flush();
parts2.push({ kind: "pound" });
i += 1;
continue;
}
if (ch === "{") {
flush();
parts2.push(parseArgument(depth));
continue;
}
text += ch;
i += 1;
}
flush();
return parts2;
};
const skipSpace = () => {
while (i < source.length && /\s/.test(source[i])) i += 1;
};
const readWord = () => {
const start = i;
while (i < source.length && /[^\s,{}]/.test(source[i])) i += 1;
return source.slice(start, i);
};
const expect = (ch) => {
if (source[i] !== ch) throw new MessageSyntaxError(`expected ${ch}`, source, i);
i += 1;
};
const parseOptions = (inPlural, depth) => {
const options = {};
for (; ; ) {
skipSpace();
if (source[i] === "}") break;
const selector = readWord();
if (!selector) throw new MessageSyntaxError("expected a selector", source, i);
skipSpace();
expect("{");
options[selector] = parseParts(inPlural, depth + 1);
expect("}");
}
if (!("other" in options)) throw new MessageSyntaxError('a plural or select needs an "other" option', source, i);
return options;
};
const parseArgument = (depth) => {
expect("{");
skipSpace();
const name = readWord();
if (!NAME.test(name)) throw new MessageSyntaxError(`invalid placeholder name ${JSON.stringify(name)}`, source, i);
skipSpace();
if (source[i] === "}") {
i += 1;
return { kind: "arg", name };
}
expect(",");
skipSpace();
const type = readWord();
skipSpace();
if (type === "plural" || type === "selectordinal") {
expect(",");
skipSpace();
let offset = 0;
const offsetMatch = /^offset:(\d+)/.exec(source.slice(i));
if (offsetMatch) {
offset = Number(offsetMatch[1]);
i += offsetMatch[0].length;
}
const options = parseOptions(true, depth);
expect("}");
return { kind: "plural", name, ordinal: type === "selectordinal", offset, options };
}
if (type === "select") {
expect(",");
const options = parseOptions(false, depth);
expect("}");
return { kind: "select", name, options };
}
if (type === "number" || type === "date" || type === "time") {
let style;
if (source[i] === ",") {
i += 1;
skipSpace();
style = readWord();
skipSpace();
}
expect("}");
return { kind: "arg", name, format: type, style };
}
throw new MessageSyntaxError(`unknown argument type ${JSON.stringify(type)}`, source, i);
};
const parts = parseParts(false, 0);
if (i < source.length) throw new MessageSyntaxError("unexpected }", source, i);
return parts;
}
var formatterCache = /* @__PURE__ */ new Map();
function cached(key, make) {
let value = formatterCache.get(key);
if (!value) {
value = make();
if (formatterCache.size > 256) formatterCache.clear();
formatterCache.set(key, value);
}
return value;
}
function safeLocale(locale) {
const base = locale.split("-x-")[0];
try {
return Intl.getCanonicalLocales(base)[0] ?? "en";
} catch {
return "en";
}
}
function numberFormat(locale, options) {
const tag = safeLocale(locale);
return cached(`n|${tag}|${JSON.stringify(options ?? {})}`, () => new Intl.NumberFormat(tag, options));
}
function dateFormat(locale, options) {
const tag = safeLocale(locale);
return cached(`d|${tag}|${JSON.stringify(options ?? {})}`, () => new Intl.DateTimeFormat(tag, options));
}
function pluralRules(locale, ordinal = false) {
const tag = safeLocale(locale);
return cached(`p|${tag}|${ordinal}`, () => new Intl.PluralRules(tag, { type: ordinal ? "ordinal" : "cardinal" }));
}
var NUMBER_STYLES = {
integer: { maximumFractionDigits: 0 },
percent: { style: "percent" },
compact: { notation: "compact" }
};
var DATE_STYLES = {
short: { dateStyle: "short" },
medium: { dateStyle: "medium" },
long: { dateStyle: "long" },
full: { dateStyle: "full" }
};
var TIME_STYLES = {
short: { timeStyle: "short" },
medium: { timeStyle: "medium" },
long: { timeStyle: "long" },
full: { timeStyle: "full" }
};
function toDate(value) {
const date = value instanceof Date ? value : typeof value === "number" || typeof value === "string" ? new Date(value) : null;
return date && Number.isFinite(date.getTime()) ? date : null;
}
function render(parts, params, locale, pound, onMissingParam) {
let out = "";
for (const part of parts) {
if (typeof part === "string") {
out += part;
continue;
}
if (part.kind === "pound") {
out += pound === null ? "#" : numberFormat(locale).format(pound);
continue;
}
const has = Object.prototype.hasOwnProperty.call(params, part.name);
const value = has ? params[part.name] : void 0;
if (!has || value === void 0 || value === null) {
onMissingParam?.(part.name);
out += `{${part.name}}`;
continue;
}
if (part.kind === "arg") {
if (part.format === "number" && typeof value === "number") {
out += numberFormat(locale, NUMBER_STYLES[part.style ?? ""] ?? void 0).format(value);
} else if ((part.format === "date" || part.format === "time") && toDate(value)) {
const styles = part.format === "date" ? DATE_STYLES : TIME_STYLES;
out += dateFormat(locale, styles[part.style ?? "medium"] ?? styles.medium).format(toDate(value));
} else if (typeof value === "number") {
out += numberFormat(locale).format(value);
} else {
out += String(value);
}
continue;
}
if (part.kind === "select") {
const key = String(value);
out += render(part.options[key] ?? part.options.other, params, locale, pound, onMissingParam);
continue;
}
const n = typeof value === "number" ? value : Number(value);
if (!Number.isFinite(n)) {
out += String(value);
continue;
}
const exact = part.options[`=${n}`];
const shifted = n - part.offset;
const option = exact ?? part.options[pluralRules(locale, part.ordinal).select(shifted)] ?? part.options.other;
out += render(option, params, locale, shifted, onMissingParam);
}
return out;
}
var compiled = /* @__PURE__ */ new Map();
function formatMessage(source, params = {}, locale = "en", hooks = {}) {
if (!source.includes("{") && !source.includes("'")) return source;
let parts = compiled.get(source);
if (!parts) {
try {
parts = parseMessage(source);
} catch (error) {
parts = error instanceof Error ? error : new Error(String(error));
}
if (compiled.size > 4096) compiled.clear();
compiled.set(source, parts);
}
if (parts instanceof Error) {
hooks.onError?.(parts);
return source;
}
return render(parts, params, locale, null, hooks.onMissingParam);
}
// locales/en.json
var en_default = { messages: { "x.capture.title": "wayBetter for X \xB7 draft capture", "x.capture.note": "Unassigned account \xB7 text only \xB7 no DM capture", "x.capture.retry": "Retry local save", "x.capture.unavailable": "Capture unavailable \xB7 native bridge not found", "x.capture.failed": "Local save failed \xB7 changes are not confirmed saved", "x.capture.oversized": "Text exceeds 64 KiB \xB7 latest changes not saved", "x.capture.waiting": "Unsaved changes \xB7 waiting to save locally", "x.capture.saving": "Saving locally\u2026", "x.capture.unsupported": "Unsupported surface \xB7 capture is off here", "x.capture.idle": "No supported composer found \xB7 capture idle", "x.capture.saved": "Saved locally \xB7 draft kept in wayBetter for X", "x.capture.found": "Composer found \xB7 local save starts when you type" } };
// src/observer/entry.ts
var english = en_default.messages;
setCoreText((key, params) => {
const runtime = window.BetterTwttr;
const translated = runtime?.i18n?.t?.(key, params);
if (translated && translated !== key) return translated;
return english[key] === void 0 ? key : formatMessage(english[key], params ?? {});
});
var INSTALLATION = Symbol.for("x-workspace.observer.installation.v1");
if (typeof window !== "undefined" && isSupportedPage(window) && !window[INSTALLATION]) {
const observer = installResponseObserver(window);
const stopPaintWatch = watchFirstPaint({
doc: document,
clock: {
requestAnimationFrame: (callback) => window.requestAnimationFrame(callback),
setTimeout: (callback, ms) => window.setTimeout(callback, ms),
clearTimeout: (handle) => window.clearTimeout(handle)
},
changed: (listener) => {
const mutations = new MutationObserver(listener);
mutations.observe(document, { childList: true, subtree: true });
return () => mutations.disconnect();
},
painted: () => {
const root = document.getElementById("react-root") ?? document.querySelector(".jetfuel-style-root");
if (!root) return false;
return [...root.querySelectorAll('h1, h2, button, [role="button"], a, [role="link"]')].some((element) => {
const label = element.textContent?.trim() ?? "";
if (label.length < 8) return false;
const rect = element.getBoundingClientRect();
return rect.width > 1 && rect.height > 1 && getComputedStyle(element).visibility === "visible";
});
},
report: () => {
void window.__TAURI_INTERNALS__?.invoke("tab_report", { report: { painted: true } }).catch(() => {
});
}
});
let capture;
const startCapture = () => {
capture = installComposerCapture(window);
};
if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", startCapture, { once: true });
else startCapture();
const onNavigation = () => {
observer.advanceEpoch();
capture?.scan();
};
const historyHooks = [];
for (const name of ["pushState", "replaceState"]) {
const original = window.history[name];
const wrapper = function(...args) {
const previous = window.location.href;
const result = Reflect.apply(original, this, args);
if (window.location.href !== previous) {
try {
onNavigation();
} catch {
}
}
return result;
};
try {
window.history[name] = wrapper;
historyHooks.push({ name, original, wrapper });
} catch {
}
}
const dispose = () => {
stopPaintWatch();
document.removeEventListener("DOMContentLoaded", startCapture);
window.removeEventListener("popstate", onNavigation);
window.removeEventListener("pagehide", onPageHide);
for (const { name, original, wrapper } of historyHooks) if (window.history[name] === wrapper) window.history[name] = original;
capture?.dispose();
observer.dispose();
delete window[INSTALLATION];
};
const onPageHide = (event) => {
if (event.persisted) return;
dispose();
};
Object.defineProperty(window, INSTALLATION, { value: { dispose }, configurable: true });
window.addEventListener("popstate", onNavigation);
window.addEventListener("pagehide", onPageHide);
}
})();