diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 27494608..cf76e3d6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -21,7 +21,9 @@ jobs: - name: GQL checks run: | vpx gql-tada generate output + vpx gql-tada generate output -c packages/plugin-7tv/tsconfig.json vpx gql-tada check + vpx gql-tada check -c packages/plugin-7tv/tsconfig.json - name: Type check run: vpr check @@ -37,10 +39,26 @@ jobs: node-version: 24 cache: true - name: Generate GQL types - run: vpx gql-tada generate output + run: | + vpx gql-tada generate output + vpx gql-tada generate output -c packages/plugin-7tv/tsconfig.json - name: Check run: vp check + test: + name: Test + runs-on: blacksmith-2vcpu-ubuntu-2404 + steps: + - name: Checkout + uses: actions/checkout@v7 + - name: Setup Vite+ + uses: voidzero-dev/setup-vp@v1.22.0 + with: + node-version: lts + cache: true + - name: Test + run: vp test + build: name: Build runs-on: blacksmith-2vcpu-ubuntu-2404 diff --git a/package.json b/package.json index c0a998ba..cef7ab9d 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,7 @@ "dev": "vp dev", "build": "vp build", "preview": "vp preview", - "sync": "svelte-kit sync && gql-tada generate-output && gql-tada turbo", + "sync": "svelte-kit sync && gql-tada generate-output && gql-tada turbo && gql-tada generate-output -c packages/plugin-7tv/tsconfig.json && gql-tada turbo -c packages/plugin-7tv/tsconfig.json", "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json", "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch", "tauri": "tauri", @@ -39,7 +39,12 @@ "@tauri-store/svelte": "^3.2.1", "@ui-sdk/core": "0.1.0-beta.24", "@ui-sdk/svelte": "0.1.0-beta.24", - "colord": "^2.14.1", + "@usehyperion/plugin": "workspace:^", + "@usehyperion/plugin-7tv": "workspace:^", + "@usehyperion/plugin-bttv": "workspace:^", + "@usehyperion/plugin-ffz": "workspace:^", + "@usehyperion/types": "workspace:^", + "colord": "^2.14.0", "dayjs": "^1.11.23", "gql.tada": "^1.11.6", "graphql-web-lite": "16.6.0-4", diff --git a/packages/plugin-7tv/.gitignore b/packages/plugin-7tv/.gitignore new file mode 100644 index 00000000..cc06060c --- /dev/null +++ b/packages/plugin-7tv/.gitignore @@ -0,0 +1 @@ +gql-*.d.ts diff --git a/packages/plugin-7tv/package.json b/packages/plugin-7tv/package.json new file mode 100644 index 00000000..f2dfacc2 --- /dev/null +++ b/packages/plugin-7tv/package.json @@ -0,0 +1,27 @@ +{ + "name": "@usehyperion/plugin-7tv", + "version": "0.1.0", + "private": true, + "type": "module", + "exports": { + ".": "./src/index.ts", + "./package.json": "./package.json" + }, + "dependencies": { + "gql.tada": "^1.11.4", + "graphql-web-lite": "16.6.0-4" + }, + "devDependencies": { + "@usehyperion/plugin": "workspace:^", + "svelte": "^5.57.3", + "vite": "catalog:" + }, + "peerDependencies": { + "svelte": "^5.57.3" + }, + "hyperion": { + "id": "7tv", + "name": "7TV", + "description": "Emotes, badges, and paints from [7TV](https://7tv.app/)." + } +} diff --git a/packages/plugin-7tv/src/components/EmoteEmbed.svelte b/packages/plugin-7tv/src/components/EmoteEmbed.svelte new file mode 100644 index 00000000..6527371c --- /dev/null +++ b/packages/plugin-7tv/src/components/EmoteEmbed.svelte @@ -0,0 +1,58 @@ + + +{#await data.fetch(data.id) then emote} + {#if emote} + + {#snippet media()} +
+ {emote.displayName} +
+ + {#if !emote.listed && blurred} + + {/if} + {/snippet} + +
+ + {emote.displayName} + + + {#if !emote.listed} + + unlisted + + {/if} +
+ +
+ by {emote.owner ?? "Unknown"} +
+
+ {/if} +{/await} diff --git a/src/lib/components/message/events/EmoteSetChange.svelte b/packages/plugin-7tv/src/components/EmoteSetChange.svelte similarity index 50% rename from src/lib/components/message/events/EmoteSetChange.svelte rename to packages/plugin-7tv/src/components/EmoteSetChange.svelte index 0ab46ca0..9d2a37d7 100644 --- a/src/lib/components/message/events/EmoteSetChange.svelte +++ b/packages/plugin-7tv/src/components/EmoteSetChange.svelte @@ -1,17 +1,16 @@ - + {#if name} changed the active emote set to diff --git a/packages/plugin-7tv/src/components/EmoteSetUpdate.svelte b/packages/plugin-7tv/src/components/EmoteSetUpdate.svelte new file mode 100644 index 00000000..4352cc69 --- /dev/null +++ b/packages/plugin-7tv/src/components/EmoteSetUpdate.svelte @@ -0,0 +1,25 @@ + + + + +{#if action === "renamed"} + renamed {oldName} to + {emote.displayName} +{:else} + {action} an emote: + {emote.displayName} +{/if} + + diff --git a/packages/plugin-7tv/src/components/HiddenIcon.svelte b/packages/plugin-7tv/src/components/HiddenIcon.svelte new file mode 100644 index 00000000..1b9cd8cd --- /dev/null +++ b/packages/plugin-7tv/src/components/HiddenIcon.svelte @@ -0,0 +1,16 @@ + + + + + + + + + diff --git a/packages/plugin-7tv/src/components/Icon.svelte b/packages/plugin-7tv/src/components/Icon.svelte new file mode 100644 index 00000000..3ca122cf --- /dev/null +++ b/packages/plugin-7tv/src/components/Icon.svelte @@ -0,0 +1,19 @@ + + + + + + diff --git a/packages/plugin-7tv/src/cosmetics.ts b/packages/plugin-7tv/src/cosmetics.ts new file mode 100644 index 00000000..7ba2b6ab --- /dev/null +++ b/packages/plugin-7tv/src/cosmetics.ts @@ -0,0 +1,101 @@ +import type { EmoteData } from "@usehyperion/plugin"; +import { SvelteMap } from "svelte/reactivity"; + +import type { PaintObject } from "./types"; + +export interface Paint { + name: string; + css: string; +} + +/** + * Paints and personal emotes, learned from live events. + */ +export class Cosmetics { + /** + * Paints keyed by their id. + */ + public readonly paints = new Map(); + + /** + * The emotes of personal emote sets keyed by set id. + */ + public readonly personalSets = new SvelteMap(); + + /** + * The paint each user has equipped keyed by Twitch user id. + */ + public readonly userPaints = new SvelteMap(); + + /** + * The personal emote set each user has keyed by Twitch user id. + */ + public readonly userPersonalSets = new SvelteMap(); + + /** + * The emote with the given name in the user's personal emote set. + */ + public personalEmote(userId: string, name: string) { + const setId = this.userPersonalSets.get(userId); + + return setId + ? this.personalSets.get(setId)?.find((emote) => emote.displayName === name) + : undefined; + } +} + +function toRgb(decimal: number) { + const r = (decimal >>> 24) & 255; + const g = (decimal >>> 16) & 255; + const b = (decimal >>> 8) & 255; + const a = (decimal & 255) / 255; + + return `rgb(${r} ${g} ${b} / ${a.toFixed(2)})`; +} + +/** + * The CSS that paints text with the given paint. + */ +export function paintCss(paint: PaintObject) { + const args: string[] = []; + + switch (paint.function) { + case "LINEAR_GRADIENT": { + args.push(`${paint.angle}deg`); + break; + } + + case "RADIAL_GRADIENT": { + args.push(paint.shape); + break; + } + + case "URL": { + args.push(paint.image_url); + break; + } + } + + if (paint.function !== "URL") { + for (const stop of paint.stops) { + args.push(`${toRgb(stop.color)} ${stop.at * 100}%`); + } + } + + const cssFunction = + (paint.repeat ? "repeating-" : "") + paint.function.toLowerCase().replace(/_/g, "-"); + + const shadows = paint.shadows.map( + (shadow) => + `drop-shadow(${shadow.x_offset}px ${shadow.y_offset}px ${shadow.radius}px ${toRgb(shadow.color)})`, + ); + + return [ + `background-color: currentcolor`, + `background-image: ${cssFunction}(${args.join(", ")})`, + `background-size: 100% 100%`, + `background-clip: text`, + `filter: ${shadows.join(" ")}`, + `-webkit-text-fill-color: transparent`, + ].join(";"); +} diff --git a/packages/plugin-7tv/src/emotes.ts b/packages/plugin-7tv/src/emotes.ts new file mode 100644 index 00000000..0f38265f --- /dev/null +++ b/packages/plugin-7tv/src/emotes.ts @@ -0,0 +1,102 @@ +import type { EmoteData } from "@usehyperion/plugin"; + +import type { Emote } from "./gql"; +import type { EmoteChange } from "./types"; + +import { fileUrl } from "./types"; + +const ZERO_WIDTH_FLAG = 256; + +interface Image { + url: string; + format: string; + width: number; + height: number; + scale: number; +} + +function toEmote( + emote: { id: string; name: string; alias?: string | null; zeroWidth: boolean }, + images: Image[], +): EmoteData { + const format = ["webp", "gif", "png"].find((f) => images.some((img) => img.format === f)); + + const candidates = images + .filter((img) => img.format === format) + .toSorted((a, b) => b.width - a.width); + + const largest = candidates.at(0); + const scale = largest?.scale || 1; + const alias = emote.alias && emote.alias !== emote.name ? emote.alias : undefined; + + return { + id: emote.id, + name: emote.name, + alias, + displayName: alias ?? emote.name, + width: largest?.width ?? 28, + height: largest?.height ?? 28, + displayWidth: (largest?.width ?? 28) / scale, + displayHeight: (largest?.height ?? 28) / scale, + srcset: candidates.map((img) => `${img.url} ${img.scale}x`), + zeroWidth: emote.zeroWidth, + }; +} + +/** + * A copy of the emote typed as the given name, so messages that already show + * the emote keep its old name. + */ +export function rename(emote: T, name: string): T { + return { + ...emote, + alias: name === emote.name ? undefined : name, + displayName: name, + }; +} + +/** + * Converts an emote from the GraphQL API. + */ +export function fromGql(emote: Emote, alias?: string | null): EmoteData { + return toEmote( + { + id: emote.id, + name: emote.defaultName, + alias, + zeroWidth: emote.flags.defaultZeroWidth, + }, + emote.images + .filter((img) => !img.url.includes("static")) + .map((img) => ({ + url: img.url, + format: img.mime.split("/").at(-1) ?? "", + width: img.width, + height: img.height, + scale: img.scale, + })), + ); +} + +/** + * Converts an emote from a live event. + */ +export function fromEvent(emote: EmoteChange): EmoteData { + const { host } = emote.data; + + return toEmote( + { + id: emote.id, + name: emote.data.name, + alias: emote.name, + zeroWidth: (emote.data.flags & ZERO_WIDTH_FLAG) === ZERO_WIDTH_FLAG, + }, + host.files.map((file) => ({ + url: fileUrl(host, file), + format: file.format.toLowerCase(), + width: file.width, + height: file.height, + scale: Number(file.name[0]) || 1, + })), + ); +} diff --git a/src/lib/graphql/7tv.ts b/packages/plugin-7tv/src/gql.ts similarity index 64% rename from src/lib/graphql/7tv.ts rename to packages/plugin-7tv/src/gql.ts index e51d4058..350bddde 100644 --- a/src/lib/graphql/7tv.ts +++ b/packages/plugin-7tv/src/gql.ts @@ -1,23 +1,67 @@ +import type { PluginHttp } from "@usehyperion/plugin"; import { initGraphQLTada } from "gql.tada"; import type { FragmentOf, ResultOf, TadaDocumentNode } from "gql.tada"; +import { print } from "graphql-web-lite"; -import { request, type GqlRequestOptions, type NonNullableDeep } from "."; +const ENDPOINT = "https://7tv.io/v4/gql"; const gql = initGraphQLTada<{ disableMasking: true; - introspection: import("./7tv-env").introspection; + introspection: import("./gql-env").introspection; scalars: { Id: string; DateTime: string; }; }>(); -export function execute7tvQuery( - query: TadaDocumentNode, - variables?: U, - { signal }: Pick = {}, -) { - return request("https://7tv.io/v4/gql", query, variables, { signal }); +type GqlResponse = + | { + data: T; + errors?: never; + } + | { + data?: never; + errors: { message: string }[]; + }; + +type NonNullableDeep = P extends `${infer K}.${infer R}` + ? K extends keyof T + ? NonNullableDeep, R> + : never + : P extends keyof T + ? NonNullable + : never; + +export type Query = ( + document: TadaDocumentNode, + variables?: V, + signal?: AbortSignal, +) => Promise; + +export function createQuery(http: PluginHttp): Query { + return async function query( + document: TadaDocumentNode, + variables?: V, + signal?: AbortSignal, + ) { + // @ts-expect-error - outdated types + const source: string = print(document); + + const response = await http.json>(ENDPOINT, { + method: "POST", + body: { query: source, variables }, + signal, + }); + + if (response.errors) { + throw new AggregateError( + response.errors.map((error) => new Error(error.message)), + "7TV GraphQL request failed", + ); + } + + return response.data; + }; } const emoteDetailsFragment = gql(` diff --git a/packages/plugin-7tv/src/index.ts b/packages/plugin-7tv/src/index.ts new file mode 100644 index 00000000..1b2e0e5b --- /dev/null +++ b/packages/plugin-7tv/src/index.ts @@ -0,0 +1,645 @@ +import { + Plugin, + type BadgeProviderHandle, + type Channel, + type EmoteData, + type EmoteLoadContext, + type EmoteProviderHandle, + type EmoteSetData, + type User, +} from "@usehyperion/plugin"; +import type { ComponentProps } from "svelte"; + +import type { ActiveEmoteSet } from "./gql"; +import type { EmbeddedEmote, EmoteEmbedData, EventMap, SevenTvUser } from "./types"; + +import EmoteEmbed from "./components/EmoteEmbed.svelte"; +import EmoteSetChange from "./components/EmoteSetChange.svelte"; +import EmoteSetUpdate from "./components/EmoteSetUpdate.svelte"; +import Icon from "./components/Icon.svelte"; +import { Cosmetics, paintCss } from "./cosmetics"; +import { fromEvent, fromGql, rename } from "./emotes"; +import { + activeEmoteSetQuery, + createQuery, + emoteQuery, + globalEmoteSetQuery, + globalEmoteSetVersionQuery, + userEmoteSetsQuery, +} from "./gql"; +import logo from "./logo.svg"; +import { EventSocket, type Condition } from "./socket"; +import { fileUrl, twitchConnection } from "./types"; + +const NAME = "7TV"; + +interface SetVersion { + setId: string; + updatedAt: string; +} + +interface VersionedEmotes { + emotes: EmoteData[]; + version: SetVersion | null; +} + +/** + * A channel's 7TV account and its active emote set. + */ +interface Account { + userId: string | null; + setId: string | null; +} + +type UpdateProps = Omit, "actor" | "ui">; + +type Handlers = { [K in keyof EventMap]: (data: EventMap[K]) => unknown }; + +export default class SevenTv extends Plugin.withSettings({ + emotes: { + type: "switch", + label: "Enable emotes", + description: "Show and autocomplete emotes from 7TV, including personal emotes.", + default: true, + }, + badges: { + type: "switch", + label: "Enable badges", + description: "Show badges from 7TV.", + default: true, + }, + paints: { + type: "switch", + label: "Paint usernames", + description: "Style usernames with 7TV paints if the user has one.", + default: true, + }, +}) { + readonly #query = createQuery(this.http); + readonly #cosmetics = new Cosmetics(); + + /** + * The 7TV account of each channel keyed by Twitch channel id, once it's + * been looked up. + */ + readonly #accounts = new Map(); + + /** + * The ids of the channels whose events are followed. + */ + readonly #joined = new Set(); + + /** + * The 7TV user id of each signed in Twitch user, for presences. + */ + readonly #selves = new Map>(); + + readonly #socket = new EventSocket({ + log: this.log, + onDispatch: (type, body) => { + this.#dispatch(type, body).catch((error) => { + this.log.error(`Failed to handle ${type}`, error); + }); + }, + }); + + readonly #handlers: Handlers = { + "cosmetic.create": (data) => this.#onCosmetic(data), + "entitlement.create": (data) => this.#onEntitlement(data), + "emote_set.create": (data) => this.#cosmetics.personalSets.set(data.id, []), + "emote_set.update": (data) => this.#onEmoteSetUpdate(data), + "user.update": (data) => this.#onUserUpdate(data), + }; + + #emoteProvider!: EmoteProviderHandle; + #badgeProvider!: BadgeProviderHandle; + + public override onunload() { + this.#socket.close(); + } + + public onload() { + this.#emoteProvider = this.emotes.provide({ + name: NAME, + icon: Icon, + logo, + enabled: () => this.settings.emotes, + // Cached by set version rather than age, see #loadVersioned. + fresh: false, + global: (load) => this.#globalEmotes(load), + channel: (channel, load) => this.#channelEmotes(channel, load), + personal: (userId, name) => this.#cosmetics.personalEmote(userId, name), + userSets: (user, { signal }) => this.#fetchUserSets(user, signal), + }); + + this.#badgeProvider = this.badges.provide({ + name: NAME, + enabled: () => this.settings.badges, + }); + + this.users.decorate((userId) => + this.settings.paints ? this.#cosmetics.userPaints.get(userId)?.css : undefined, + ); + + this.embeds.provide({ + match: (url) => this.#matchEmbed(url), + component: EmoteEmbed, + }); + + // Registered after the providers since it runs right away for the + // channels that are already joined. + this.channels.on("join", (channel) => this.#join(channel)); + this.channels.on("leave", (channel) => this.#leave(channel)); + this.channels.on("messageSent", (channel) => void this.#sendPresence(channel.id)); + + this.#socket.connect(); + } + + #join(channel: Channel) { + this.#joined.add(channel.id); + this.#follow(channel.id); + + void this.#sendPresence(channel.id); + + // Loading the channel's emotes resolves its account already. + if (this.settings.emotes && !this.#emoteProvider.channel(channel.id)?.loaded) { + return; + } + + void this.#syncAccount(channel.id); + } + + #leave(channel: Channel) { + this.#joined.delete(channel.id); + this.#socket.removeChannel(channel.id); + } + + #follow(channelId: string) { + if (!this.#joined.has(channelId)) { + this.#socket.removeChannel(channelId); + return; + } + + const channel: Condition = { + ctx: "channel", + platform: "TWITCH", + id: channelId, + }; + + const events: [string, Condition][] = [ + ["cosmetic.create", channel], + ["entitlement.create", channel], + ]; + + const account = this.#accounts.get(channelId); + + if (account?.setId) { + events.push(["emote_set.*", { object_id: account.setId }]); + } + + if (account?.userId) { + events.push(["user.update", { object_id: account.userId }]); + } + + this.#socket.setChannel(channelId, events); + } + + #setAccount(channelId: string, userId: string | null, setId: string | null) { + const current = this.#accounts.get(channelId); + if (current && current.userId === userId && current.setId === setId) return; + + this.#accounts.set(channelId, { userId, setId }); + this.#follow(channelId); + } + + #findChannel(matches: (account: Account) => boolean) { + for (const [channelId, account] of this.#accounts) { + if (matches(account)) return channelId; + } + + return undefined; + } + + /** + * Resolves the channel's 7TV account and active emote set so their events + * can be followed. + */ + async #activeSet(channelId: string, details: D, signal?: AbortSignal) { + const { users } = await this.#query( + activeEmoteSetQuery, + { id: channelId, details }, + signal, + ); + + const user = users.userByConnection; + const set = user?.style.activeEmoteSet ?? null; + + this.#setAccount(channelId, user?.id ?? null, set?.id ?? null); + + // oxlint-disable-next-line typescript/no-unsafe-type-assertion + return set as ActiveEmoteSet | null; + } + + /** + * Looks up the channel's active emote set and reloads its emotes if it + * changed while the channel wasn't followed. + */ + async #syncAccount(channelId: string) { + try { + const previous = this.#accounts.get(channelId)?.setId ?? null; + const set = await this.#activeSet(channelId, false); + const scope = this.#emoteProvider.channel(channelId); + + if (scope?.loaded && (set?.id ?? null) !== previous) { + await scope.reload(); + } + } catch (error) { + // The channel still works without knowing its 7TV account. + this.log.warn(`Failed to sync the emote set of ${channelId}`, error); + } + } + + #globalEmotes(load: EmoteLoadContext) { + return this.#loadVersioned( + "emotes:global", + load, + (signal) => this.#fetchGlobal(signal), + (signal) => this.#fetchGlobalVersion(signal), + () => true, + ); + } + + #channelEmotes(channel: Channel, load: EmoteLoadContext) { + return this.#loadVersioned( + `emotes:${channel.id}`, + load, + async (signal) => { + const set = await this.#activeSet(channel.id, true, signal); + + return { + emotes: set?.emotes.items.map((item) => fromGql(item.emote, item.alias)) ?? [], + version: set && { setId: set.id, updatedAt: set.updatedAt }, + }; + }, + async (signal) => { + const set = await this.#activeSet(channel.id, false, signal); + return set && { setId: set.id, updatedAt: set.updatedAt }; + }, + // Unknown until the channel's account has been resolved, which + // happens while revalidating. + (setId) => { + const account = this.#accounts.get(channel.id); + return account?.userId == null || setId === account.setId; + }, + ); + } + + /** + * Returns cached emotes immediately and checks whether their set has + * changed since in the background, applying the new emotes if it has. + */ + async #loadVersioned( + key: string, + load: EmoteLoadContext, + fetchSet: (signal: AbortSignal) => Promise, + fetchVersion: (signal: AbortSignal) => Promise, + isCurrent: (setId: string | null) => boolean, + ) { + const entry = load.force ? null : await this.cache.get(key); + + if (entry && isCurrent(entry.version?.setId ?? null)) { + this.#revalidate(key, load, entry.version, fetchSet, fetchVersion).catch((error) => { + if (!load.signal.aborted) { + this.log.warn(`Failed to revalidate ${key}`, error); + } + }); + + return entry.emotes; + } + + const fetched = await fetchSet(load.signal); + void this.cache.set(key, fetched); + + return fetched.emotes; + } + + async #revalidate( + key: string, + load: EmoteLoadContext, + cached: SetVersion | null, + fetchSet: (signal: AbortSignal) => Promise, + fetchVersion: (signal: AbortSignal) => Promise, + ) { + const version = await fetchVersion(load.signal); + + if (version?.setId === cached?.setId && version?.updatedAt === cached?.updatedAt) { + return; + } + + const fetched = await fetchSet(load.signal); + void this.cache.set(key, fetched); + + load.update(fetched.emotes); + } + + async #fetchGlobal(signal: AbortSignal): Promise { + const { emoteSets } = await this.#query(globalEmoteSetQuery, undefined, signal); + const set = emoteSets.global!; + + return { + emotes: set.emotes.items.map((item) => fromGql(item.emote, item.alias)), + version: { setId: set.id, updatedAt: set.updatedAt }, + }; + } + + async #fetchGlobalVersion(signal: AbortSignal) { + const { emoteSets } = await this.#query(globalEmoteSetVersionQuery, undefined, signal); + const set = emoteSets.global; + + return set ? { setId: set.id, updatedAt: set.updatedAt } : null; + } + + async #fetchUserSets(user: User, signal: AbortSignal) { + const { users } = await this.#query(userEmoteSetsQuery, { id: user.id }, signal); + const account = users.userByConnection; + + this.#selves.set(user.id, Promise.resolve(account?.id ?? null)); + + const sets: EmoteSetData[] = []; + + if (account?.personalEmoteSet) { + sets.push({ + id: account.personalEmoteSet.id, + name: `${user.displayName}: 7TV Personal Emotes`, + emotes: account.personalEmoteSet.emotes.items.map((item) => + fromGql(item.emote, item.alias), + ), + }); + } + + for (const set of account?.specialEmoteSets ?? []) { + sets.push({ + id: set.id, + name: set.name, + emotes: set.emotes.items.map((item) => fromGql(item.emote, item.alias)), + }); + } + + return sets; + } + + #matchEmbed(url: URL): EmoteEmbedData | null { + const official = url.hostname === "7tv.app" || url.hostname.endsWith(".7tv.app"); + const [, section, id] = url.pathname.split("/"); + + return official && section === "emotes" && id + ? { id, fetch: (emoteId) => this.#fetchEmbeddedEmote(emoteId) } + : null; + } + + async #fetchEmbeddedEmote(id: string): Promise { + try { + const { emotes } = await this.#query(emoteQuery, { id }); + const emote = emotes.emote; + if (!emote) return null; + + return { + ...fromGql(emote), + listed: emote.flags.publicListed, + owner: emote.owner?.mainConnection?.platformDisplayName ?? null, + }; + } catch (error) { + this.log.warn("Failed to fetch emote embed", error); + return null; + } + } + + #selfId() { + const user = this.users.current; + if (!user) return Promise.resolve(null); + + let id = this.#selves.get(user.id); + + if (!id) { + id = this.#query(activeEmoteSetQuery, { id: user.id, details: false }).then( + ({ users }) => users.userByConnection?.id ?? null, + ); + + this.#selves.set(user.id, id); + + // Try again next time. + id.catch(() => this.#selves.delete(user.id)); + } + + return id; + } + + /** + * Tells 7TV the user is active in the channel so others see their + * cosmetics. + */ + async #sendPresence(channelId: string) { + try { + const id = await this.#selfId(); + if (!id) return; + + await this.http.json(`https://7tv.io/v3/users/${id}/presences`, { + method: "POST", + body: { + kind: 1, + passive: false, + session_id: null, + data: { platform: "TWITCH", id: channelId }, + }, + }); + + this.log.debug(`Presence sent in ${channelId}`); + } catch (error) { + this.log.warn("Failed to send presence", error); + } + } + + /** + * Resolves who made a change, as a viewer of the channel. + */ + async #actorIn(channelId: string, actor: SevenTvUser) { + const twitch = twitchConnection(actor); + const channel = this.channels.get(channelId); + + const user = twitch && channel ? await this.channels.fetchUser(channel, twitch.id) : null; + + return user && channel ? { channel, user } : null; + } + + async #dispatch(type: string, body: unknown) { + if (!Object.hasOwn(this.#handlers, type)) return; + + // oxlint-disable-next-line typescript/no-unsafe-type-assertion + const handle = this.#handlers[type as keyof EventMap] as (data: unknown) => unknown; + + await handle(body); + } + + #onCosmetic(cosmetic: EventMap["cosmetic.create"]) { + if (cosmetic.kind === "BADGE") { + const { host } = cosmetic.data; + const file = host.files.find((f) => f.name.startsWith("4x")); + if (!file) return; + + this.#badgeProvider.set({ + version: cosmetic.id, + title: cosmetic.data.name, + description: cosmetic.data.tooltip, + imageUrl: fileUrl(host, file), + }); + + return; + } + + this.#cosmetics.paints.set(cosmetic.id, { + name: cosmetic.data.name, + css: paintCss(cosmetic.data), + }); + } + + #onEntitlement(entitlement: EventMap["entitlement.create"]) { + const twitch = twitchConnection(entitlement.user); + if (!twitch) return; + + switch (entitlement.kind) { + case "BADGE": { + this.#badgeProvider.give(twitch.id, entitlement.ref_id); + break; + } + + case "PAINT": { + this.#cosmetics.userPaints.set( + twitch.id, + this.#cosmetics.paints.get(entitlement.ref_id), + ); + break; + } + + case "EMOTE_SET": { + this.#cosmetics.userPersonalSets.set(twitch.id, entitlement.ref_id); + break; + } + } + } + + async #onEmoteSetUpdate(data: EventMap["emote_set.update"]) { + const channelId = this.#findChannel((account) => account.setId === data.id); + + if (!channelId) { + this.#updatePersonalSet(data); + return; + } + + const scope = this.#emoteProvider.channel(channelId); + if (!scope?.loaded) return; + + let last: UpdateProps | null = null; + + for (const change of data.pushed ?? []) { + const emote = fromEvent(change.value); + scope.set(emote); + + const added = scope.get(emote.displayName); + + if (added) { + last = { action: "added", emote: added }; + } + } + + for (const change of data.pulled ?? []) { + const emote = scope.get(change.old_value.name); + if (!emote) continue; + + scope.delete(change.old_value.name); + last = { action: "removed", emote }; + } + + for (const change of data.updated ?? []) { + const emote = scope.get(change.old_value.name); + if (!emote) continue; + + const renamed = rename(emote, change.value.name); + + scope.delete(change.old_value.name); + scope.set(renamed); + + last = { + action: "renamed", + oldName: emote.displayName, + emote: renamed, + }; + } + + if (!last) return; + + const props = last; + const found = await this.#actorIn(channelId, data.actor); + + if (!found) return; + + this.channels.event( + found.channel, + EmoteSetUpdate, + { ...props, actor: found.user, ui: this.ui }, + { type: "emote-set-update" }, + ); + } + + #updatePersonalSet(data: EventMap["emote_set.update"]) { + const current = this.#cosmetics.personalSets.get(data.id); + if (!current) return; + + const pulled = new Set(data.pulled?.map((change) => change.old_value.id)); + + const kept = current + .filter((emote) => !pulled.has(emote.id)) + .map((emote) => { + const update = data.updated?.find((change) => change.value.id === emote.id); + return update ? rename(emote, update.value.name) : emote; + }); + + const pushed = data.pushed?.map((change) => fromEvent(change.value)) ?? []; + + this.#cosmetics.personalSets.set(data.id, [...kept, ...pushed]); + } + + async #onUserUpdate(data: EventMap["user.update"]) { + const channelId = this.#findChannel((account) => account.userId === data.id); + if (!channelId) return; + + const account = this.#accounts.get(channelId)!; + + const root = data.updated?.find((change) => change.key === "connections"); + if (!root) return; + + const child = root.value.find( + (change) => change.key === "emote_set" && change.value?.id !== account.setId, + ); + if (!child) return; + + const scope = this.#emoteProvider.channel(channelId); + scope?.clear(); + + // Follow the new set before fetching its emotes so its updates aren't + // missed if the fetch fails. + this.#setAccount(channelId, account.userId, child.value?.id ?? null); + + const found = await this.#actorIn(channelId, data.actor); + + if (found) { + this.channels.event( + found.channel, + EmoteSetChange, + { name: child.value?.name, actor: found.user, ui: this.ui }, + { type: "emote-set-change" }, + ); + } + + await scope?.reload(); + } +} diff --git a/src/assets/logos/7tv.svg b/packages/plugin-7tv/src/logo.svg similarity index 100% rename from src/assets/logos/7tv.svg rename to packages/plugin-7tv/src/logo.svg diff --git a/packages/plugin-7tv/src/socket.ts b/packages/plugin-7tv/src/socket.ts new file mode 100644 index 00000000..b886387c --- /dev/null +++ b/packages/plugin-7tv/src/socket.ts @@ -0,0 +1,345 @@ +import type { PluginLogger } from "@usehyperion/plugin"; + +const URL = "wss://events.7tv.io/v3"; + +/** + * Assumed until the server's hello says otherwise. + */ +const DEFAULT_HEARTBEAT_INTERVAL = 25_000; + +/** + * How late a heartbeat may be before the connection counts as dead. + */ +const HEARTBEAT_GRACE = 10_000; + +const INITIAL_BACKOFF = 1000; +const MAX_BACKOFF = 120_000; + +const Op = { + Dispatch: 0, + Hello: 1, + Heartbeat: 2, + Reconnect: 4, + Ack: 5, + Error: 6, + EndOfStream: 7, + Resume: 34, + Subscribe: 35, + Unsubscribe: 36, +} as const; + +interface Envelope { + op: number; + d?: any; +} + +export type Condition = Record; + +interface Subscription { + type: string; + condition: Condition; +} + +export interface EventSocketOptions { + log: PluginLogger; + onDispatch(type: string, body: unknown): void; +} + +/** + * A connection to the 7TV EventAPI that reconnects with backoff, resumes the + * previous session to replay missed events, and keeps the server's + * subscriptions in sync with what each channel needs. + */ +export class EventSocket { + /** + * What should be subscribed to, keyed by owner and event type. + */ + readonly #wanted = new Map(); + + /** + * What the server was told. + */ + readonly #synced = new Map(); + + #socket: WebSocket | null = null; + + /** + * The last session that became ready. Resuming it after a drop keeps its + * subscriptions and replays the events missed in between. + */ + #sessionId: string | null = null; + + #closed = false; + #ready = false; + + /** + * This connection's session, while waiting to hear whether resuming + * `#sessionId` worked. + */ + #resuming: string | null = null; + + #heartbeatTimeout = DEFAULT_HEARTBEAT_INTERVAL + HEARTBEAT_GRACE; + #backoff = INITIAL_BACKOFF; + + #watchdog: ReturnType | undefined; + #retry: ReturnType | undefined; + + public constructor(private readonly options: EventSocketOptions) {} + + public connect() { + if (this.#closed || this.#socket) return; + + const socket = new WebSocket(URL); + this.#socket = socket; + + socket.addEventListener("open", () => { + this.#resuming = null; + this.#expect(); + }); + + socket.addEventListener("message", (event) => { + if (typeof event.data === "string") this.#received(event.data); + }); + + socket.addEventListener("close", () => { + if (this.#socket === socket) this.#dropped(); + }); + } + + public close() { + this.#closed = true; + clearTimeout(this.#retry); + this.#disconnect(); + } + + /** + * Replaces the subscriptions kept for a channel. + */ + public setChannel(channelId: string, events: [type: string, condition: Condition][]) { + this.#removeOwned(channelId); + + for (const [type, condition] of events) { + this.#wanted.set(`${channelId}\n${type}`, { type, condition }); + } + + this.#sync(); + } + + public removeChannel(channelId: string) { + this.#removeOwned(channelId); + this.#sync(); + } + + #removeOwned(channelId: string) { + for (const key of this.#wanted.keys()) { + if (key.startsWith(`${channelId}\n`)) this.#wanted.delete(key); + } + } + + #received(text: string) { + let envelope: Envelope; + + try { + envelope = JSON.parse(text); + } catch (error) { + this.options.log.warn("Failed to parse 7TV message", error); + return; + } + + // Heartbeats are what the server promises, but anything it sends shows + // the connection is alive. + this.#expect(); + + const { op, d } = envelope; + + switch (op) { + case Op.Dispatch: { + const body = d?.body; + const payload = + body && typeof body === "object" && "object" in body ? body.object : body; + + try { + this.options.onDispatch(d?.type, payload); + } catch (error) { + this.options.log.error(`Failed to handle ${d?.type}`, error); + } + + break; + } + + case Op.Hello: { + this.#hello(d); + break; + } + + case Op.Heartbeat: { + break; + } + + case Op.Reconnect: { + this.options.log.warn("Server requested a reconnect"); + this.#reconnect(); + break; + } + + case Op.Ack: { + // Nothing is subscribed while resuming, so this acknowledges it. + const sessionId = this.#resuming; + + if (sessionId) { + this.#resuming = null; + this.#resumed(sessionId, d?.data?.success === true); + } + + break; + } + + case Op.Error: { + this.options.log.error(`Server returned an error: ${JSON.stringify(d)}`); + + // In place of the resume's ack, it means resuming failed. + const sessionId = this.#resuming; + + if (sessionId) { + this.#resuming = null; + this.#resumed(sessionId, false); + } + + break; + } + + case Op.EndOfStream: { + this.options.log.warn(`End of stream: ${JSON.stringify(d)}`); + this.#reconnect(); + break; + } + } + } + + #hello(hello: { session_id?: string; heartbeat_interval?: number } | undefined) { + if (!hello?.session_id) { + this.options.log.error("Malformed hello"); + this.#reconnect(); + + return; + } + + if (hello.heartbeat_interval) { + this.#heartbeatTimeout = hello.heartbeat_interval + HEARTBEAT_GRACE; + this.#expect(); + } + + const previous = this.#sessionId; + + if (!previous) { + this.options.log.info(`Session ${hello.session_id} established`); + + this.#sessionId = hello.session_id; + this.#becomeReady(false); + + return; + } + + this.options.log.info(`Resuming session ${previous}`); + + this.#resuming = hello.session_id; + this.#send(Op.Resume, { session_id: previous }); + } + + #resumed(sessionId: string, restored: boolean) { + if (restored) { + this.options.log.info(`Session ${sessionId} resumed`); + } else { + this.options.log.warn(`Resuming failed, resubscribing in session ${sessionId}`); + } + + this.#sessionId = sessionId; + this.#becomeReady(restored); + } + + #becomeReady(restored: boolean) { + if (!restored) this.#synced.clear(); + + this.#ready = true; + this.#backoff = INITIAL_BACKOFF; + this.#sync(); + } + + /** + * Sends the subscription changes made since the last sync. Changes made + * while not ready are sent once the session is. + */ + #sync() { + if (!this.#ready) return; + + for (const [key, subscription] of this.#synced) { + if (!same(this.#wanted.get(key), subscription)) { + this.#send(Op.Unsubscribe, subscription); + this.#synced.delete(key); + } + } + + for (const [key, subscription] of this.#wanted) { + if (!same(this.#synced.get(key), subscription)) { + this.#send(Op.Subscribe, subscription); + this.#synced.set(key, subscription); + } + } + } + + #send(op: number, d: unknown) { + if (this.#socket?.readyState === WebSocket.OPEN) { + this.#socket.send(JSON.stringify({ op, d })); + } + } + + /** + * Restarts the countdown after which the connection counts as dead. + */ + #expect() { + clearTimeout(this.#watchdog); + + this.#watchdog = setTimeout(() => { + this.options.log.warn("Server stopped responding"); + this.#reconnect(); + }, this.#heartbeatTimeout); + } + + #reconnect() { + this.#disconnect(); + this.#dropped(); + } + + /** + * Closes the socket without waiting for the server, which may never answer + * on a dead connection. + */ + #disconnect() { + const socket = this.#socket; + this.#socket = null; + + clearTimeout(this.#watchdog); + this.#ready = false; + + if (socket && socket.readyState < WebSocket.CLOSING) { + socket.close(); + } + } + + #dropped() { + this.#disconnect(); + if (this.#closed) return; + + const delay = this.#backoff; + this.#backoff = Math.min(this.#backoff * 2, MAX_BACKOFF); + + this.options.log.info(`Reconnecting in ${delay / 1000}s`); + + clearTimeout(this.#retry); + this.#retry = setTimeout(() => this.connect(), delay); + } +} + +function same(a: Subscription | undefined, b: Subscription) { + return a?.type === b.type && JSON.stringify(a.condition) === JSON.stringify(b.condition); +} diff --git a/src/lib/seventv.ts b/packages/plugin-7tv/src/types.ts similarity index 59% rename from src/lib/seventv.ts rename to packages/plugin-7tv/src/types.ts index e271bfd4..61165bdd 100644 --- a/src/lib/seventv.ts +++ b/packages/plugin-7tv/src/types.ts @@ -1,6 +1,19 @@ -import { SvelteMap } from "svelte/reactivity"; +import type { EmoteData } from "@usehyperion/plugin"; -import type { Emote as ChatEmote } from "./emotes"; +/** + * An emote linked in chat, with what its embed shows. + */ +export interface EmbeddedEmote extends EmoteData { + listed: boolean; + owner: string | null; +} + +export interface EmoteEmbedData { + id: string; + fetch: (id: string) => Promise; +} + +// The payloads of the 7TV EventAPI events the plugin subscribes to. interface EventObject { id: string; @@ -21,7 +34,7 @@ export interface Host { files: HostFile[]; } -interface Emote { +interface EmoteObject { name: string; listed: boolean; flags: number; @@ -30,12 +43,7 @@ interface Emote { } export interface EmoteChange extends EventObject { - data: Emote; -} - -export interface Paint { - name: string; - css: string; + data: EmoteObject; } interface Connection { @@ -61,7 +69,7 @@ export interface SevenTvUser { style: UserStyle; } -interface BadgeData extends EventObject { +interface BadgeObject extends EventObject { host: Host; tooltip: string; } @@ -69,7 +77,7 @@ interface BadgeData extends EventObject { interface BadgeCosmetic { id: string; kind: "BADGE"; - data: BadgeData; + data: BadgeObject; } interface PaintShadow { @@ -84,7 +92,7 @@ interface PaintStop { at: number; } -interface PaintData extends EventObject { +export interface PaintObject extends EventObject { angle: number; color: number | null; function: "LINEAR_GRADIENT" | "RADIAL_GRADIENT" | "URL"; @@ -98,11 +106,9 @@ interface PaintData extends EventObject { interface PaintCosmetic { id: string; kind: "PAINT"; - data: PaintData; + data: PaintObject; } -type CosmeticCreate = BadgeCosmetic | PaintCosmetic; - interface EmoteSetCreate extends EventObject { capacity: number; flags: number; @@ -134,13 +140,8 @@ interface ChangeMap { updated?: ChangeField<"updated", T, N>[]; } -export interface DispatchPayload { - type: string; - body: { object: unknown } | ChangeMap; -} - -export interface SevenTvEventMap { - "cosmetic.create": CosmeticCreate; +export interface EventMap { + "cosmetic.create": BadgeCosmetic | PaintCosmetic; "emote_set.create": EmoteSetCreate; "emote_set.update": ChangeMap; "entitlement.create": EntitlementCreate; @@ -151,46 +152,6 @@ export function twitchConnection(user: SevenTvUser) { return user.connections.find((c) => c.platform === "TWITCH"); } -export function sevenTvFileUrl(host: Host, file: HostFile) { +export function fileUrl(host: Host, file: HostFile) { return `https:${host.url}/${file.name}`; } - -export class SevenTvCosmetics { - /** - * Paints keyed by their id. - */ - public readonly paints = new Map(); - - /** - * The emotes of personal emote sets keyed by set id. - */ - public readonly personalSets = new SvelteMap(); - - /** - * The paint each user has equipped keyed by user id. - */ - public readonly userPaints = new SvelteMap(); - - /** - * The personal emote set each user has keyed by user id. - */ - public readonly userPersonalSets = new SvelteMap(); - - /** - * The emote with the given name in the user's personal emote set. - */ - public personalEmote(userId: string, name: string) { - const setId = this.userPersonalSets.get(userId); - - return setId - ? this.personalSets.get(setId)?.find((emote) => emote.displayName === name) - : undefined; - } - - public clear() { - this.paints.clear(); - this.userPaints.clear(); - this.personalSets.clear(); - this.userPersonalSets.clear(); - } -} diff --git a/packages/plugin-7tv/tsconfig.json b/packages/plugin-7tv/tsconfig.json new file mode 100644 index 00000000..1abc3ce3 --- /dev/null +++ b/packages/plugin-7tv/tsconfig.json @@ -0,0 +1,16 @@ +{ + "extends": "@usehyperion/plugin/tsconfig.json", + "compilerOptions": { + "plugins": [ + { + "name": "gql.tada/ts-plugin", + "shouldCheckForColocatedFragments": false, + "trackFieldUsage": false, + "schema": "https://7tv.io/v4/gql", + "tadaOutputLocation": "./src/gql-env.d.ts", + "tadaTurboLocation": "./src/gql-cache.d.ts" + } + ] + }, + "include": ["src"] +} diff --git a/packages/plugin-bttv/package.json b/packages/plugin-bttv/package.json new file mode 100644 index 00000000..b3a54331 --- /dev/null +++ b/packages/plugin-bttv/package.json @@ -0,0 +1,23 @@ +{ + "name": "@usehyperion/plugin-bttv", + "version": "0.1.0", + "private": true, + "type": "module", + "exports": { + ".": "./src/index.ts", + "./package.json": "./package.json" + }, + "devDependencies": { + "@usehyperion/plugin": "workspace:^", + "svelte": "^5.57.3", + "vite": "catalog:" + }, + "peerDependencies": { + "svelte": "^5.57.3" + }, + "hyperion": { + "id": "bttv", + "name": "BetterTTV", + "description": "Emotes and badges from [BetterTTV](https://betterttv.com/)." + } +} diff --git a/packages/plugin-bttv/src/Icon.svelte b/packages/plugin-bttv/src/Icon.svelte new file mode 100644 index 00000000..672672f2 --- /dev/null +++ b/packages/plugin-bttv/src/Icon.svelte @@ -0,0 +1,23 @@ + + + + + + + + diff --git a/packages/plugin-bttv/src/index.ts b/packages/plugin-bttv/src/index.ts new file mode 100644 index 00000000..c4e37968 --- /dev/null +++ b/packages/plugin-bttv/src/index.ts @@ -0,0 +1,123 @@ +import { + Plugin, + type BadgeData, + type BadgeSet, + type Channel, + type EmoteData, + type LoadContext, +} from "@usehyperion/plugin"; + +import Icon from "./Icon.svelte"; +import logo from "./logo.svg"; + +const NAME = "BetterTTV"; +const API = "https://api.betterttv.net/3"; + +interface BttvEmote { + id: string; + code: string; + width?: number; + height?: number; +} + +interface BttvUser { + channelEmotes: BttvEmote[]; + sharedEmotes: BttvEmote[]; +} + +interface BttvBadgeOwner { + providerId: string; + badge: { + type: number; + description: string; + svg: string; + }; +} + +function toEmote(emote: BttvEmote): EmoteData { + const width = emote.width ?? 28; + const height = emote.height ?? 28; + + return { + id: emote.id, + name: emote.code, + displayName: emote.code, + width, + height, + displayWidth: width, + displayHeight: height, + srcset: [1, 2, 3].map((n) => `https://cdn.betterttv.net/emote/${emote.id}/${n}x ${n}x`), + }; +} + +export default class Bttv extends Plugin.withSettings({ + emotes: { + type: "switch", + label: "Enable emotes", + description: "Show and autocomplete emotes from BetterTTV.", + default: true, + }, + badges: { + type: "switch", + label: "Enable badges", + description: "Show badges from BetterTTV.", + default: true, + }, +}) { + public onload() { + this.emotes.provide({ + name: NAME, + icon: Icon, + logo, + enabled: () => this.settings.emotes, + global: (load) => this.#globalEmotes(load), + channel: (channel, load) => this.#channelEmotes(channel, load), + }); + + this.badges.provide({ + name: NAME, + enabled: () => this.settings.badges, + load: (load) => this.#badges(load), + }); + } + + async #globalEmotes({ signal }: LoadContext) { + const emotes = await this.http.json(`${API}/cached/emotes/global`, { + signal, + }); + + return emotes.map(toEmote); + } + + async #channelEmotes(channel: Channel, { signal }: LoadContext) { + const user = await this.http.json( + `${API}/cached/users/twitch/${channel.id}`, + { notFound: null, signal }, + ); + + return user ? [...user.channelEmotes, ...user.sharedEmotes].map(toEmote) : []; + } + + async #badges({ signal }: LoadContext): Promise { + const owners = await this.http.json(`${API}/cached/badges`, { signal }); + + const badges = new Map(); + const users: Record = {}; + + for (const { providerId, badge } of owners) { + const version = badge.type.toString(); + + if (!badges.has(version)) { + badges.set(version, { + version, + title: badge.description, + imageUrl: badge.svg, + }); + } + + (users[version] ??= []).push(providerId); + } + + return { badges: [...badges.values()], users }; + } +} diff --git a/src/assets/logos/bttv.svg b/packages/plugin-bttv/src/logo.svg similarity index 100% rename from src/assets/logos/bttv.svg rename to packages/plugin-bttv/src/logo.svg diff --git a/packages/plugin-bttv/tsconfig.json b/packages/plugin-bttv/tsconfig.json new file mode 100644 index 00000000..678520af --- /dev/null +++ b/packages/plugin-bttv/tsconfig.json @@ -0,0 +1,4 @@ +{ + "extends": "@usehyperion/plugin/tsconfig.json", + "include": ["src"] +} diff --git a/packages/plugin-ffz/package.json b/packages/plugin-ffz/package.json new file mode 100644 index 00000000..a3522880 --- /dev/null +++ b/packages/plugin-ffz/package.json @@ -0,0 +1,23 @@ +{ + "name": "@usehyperion/plugin-ffz", + "version": "0.1.0", + "private": true, + "type": "module", + "exports": { + ".": "./src/index.ts", + "./package.json": "./package.json" + }, + "devDependencies": { + "@usehyperion/plugin": "workspace:^", + "svelte": "^5.57.3", + "vite": "catalog:" + }, + "peerDependencies": { + "svelte": "^5.57.3" + }, + "hyperion": { + "id": "ffz", + "name": "FrankerFaceZ", + "description": "Emotes and badges from [FrankerFaceZ](https://www.frankerfacez.com/)." + } +} diff --git a/packages/plugin-ffz/src/Icon.svelte b/packages/plugin-ffz/src/Icon.svelte new file mode 100644 index 00000000..a34deeac --- /dev/null +++ b/packages/plugin-ffz/src/Icon.svelte @@ -0,0 +1,19 @@ + + + + + + diff --git a/packages/plugin-ffz/src/index.ts b/packages/plugin-ffz/src/index.ts new file mode 100644 index 00000000..e2809cb2 --- /dev/null +++ b/packages/plugin-ffz/src/index.ts @@ -0,0 +1,133 @@ +import { + Plugin, + type BadgeData, + type BadgeSet, + type Channel, + type EmoteData, + type LoadContext, +} from "@usehyperion/plugin"; + +import Icon from "./Icon.svelte"; +import logo from "./logo.svg"; + +const NAME = "FrankerFaceZ"; +const API = "https://api.frankerfacez.com/v1"; + +const GLOBAL_SET = 3; + +// Twitch already has a bot badge so we don't need the FFZ one +const BOT_BADGE = 2; + +interface FfzEmote { + id: number; + name: string; + height: number; + width: number; + urls: Record; +} + +interface FfzEmoteSet { + emoticons: FfzEmote[]; +} + +interface GlobalSets { + sets: Record; +} + +interface Room { + room: { set: number }; + sets: Record; +} + +interface FfzBadge { + id: number; + title: string; + color: string; + urls: Record; +} + +interface Badges { + badges: FfzBadge[]; + users: Record; +} + +function toEmote(emote: FfzEmote): EmoteData { + return { + id: emote.id.toString(), + name: emote.name, + displayName: emote.name, + width: emote.width, + height: emote.height, + displayWidth: emote.width, + displayHeight: emote.height, + srcset: Object.entries(emote.urls).map(([n, url]) => `${url} ${n}x`), + }; +} + +export default class Ffz extends Plugin.withSettings({ + emotes: { + type: "switch", + label: "Enable emotes", + description: "Show and autocomplete emotes from FrankerFaceZ.", + default: true, + }, + badges: { + type: "switch", + label: "Enable badges", + description: "Show badges from FrankerFaceZ.", + default: true, + }, +}) { + public onload() { + this.emotes.provide({ + name: NAME, + icon: Icon, + logo, + enabled: () => this.settings.emotes, + global: (load) => this.#globalEmotes(load), + channel: (channel, load) => this.#channelEmotes(channel, load), + }); + + this.badges.provide({ + name: NAME, + enabled: () => this.settings.badges, + load: (load) => this.#badges(load), + }); + } + + async #globalEmotes({ signal }: LoadContext) { + const data = await this.http.json(`${API}/set/global`, { signal }); + return data.sets[GLOBAL_SET].emoticons.map(toEmote); + } + + async #channelEmotes(channel: Channel, { signal }: LoadContext) { + const data = await this.http.json(`${API}/room/id/${channel.id}`, { + notFound: null, + signal, + }); + + return data?.sets[data.room.set].emoticons.map(toEmote) ?? []; + } + + async #badges({ signal }: LoadContext): Promise { + const data = await this.http.json(`${API}/badges/ids`, { signal }); + + const badges: BadgeData[] = data.badges + .filter((badge) => badge.id !== BOT_BADGE) + .map((badge) => ({ + version: badge.id.toString(), + title: badge.title, + color: badge.color, + imageUrl: badge.urls["4"], + })); + + const users = Object.fromEntries( + Object.entries(data.users).map(([version, ids]) => [ + version, + ids.map((id) => id.toString()), + ]), + ); + + return { badges, users }; + } +} diff --git a/src/assets/logos/ffz.svg b/packages/plugin-ffz/src/logo.svg similarity index 100% rename from src/assets/logos/ffz.svg rename to packages/plugin-ffz/src/logo.svg diff --git a/packages/plugin-ffz/tsconfig.json b/packages/plugin-ffz/tsconfig.json new file mode 100644 index 00000000..678520af --- /dev/null +++ b/packages/plugin-ffz/tsconfig.json @@ -0,0 +1,4 @@ +{ + "extends": "@usehyperion/plugin/tsconfig.json", + "include": ["src"] +} diff --git a/packages/plugin/README.md b/packages/plugin/README.md new file mode 100644 index 00000000..befc3271 --- /dev/null +++ b/packages/plugin/README.md @@ -0,0 +1,13 @@ +# `@usehyperion/plugin` + +```ts +import { hyperion } from "@usehyperion/plugin/vite"; +// vite.config.ts +import { defineConfig } from "vite"; + +export default defineConfig({ + plugins: [hyperion()], +}); +``` + +The output is an ES module and a `manifest.json` that the app installs. diff --git a/packages/plugin/package.json b/packages/plugin/package.json new file mode 100644 index 00000000..6116c518 --- /dev/null +++ b/packages/plugin/package.json @@ -0,0 +1,35 @@ +{ + "name": "@usehyperion/plugin", + "version": "0.1.0", + "private": true, + "description": "Types and build tooling for Hyperion plugins", + "type": "module", + "exports": { + ".": "./src/index.ts", + "./vite": "./src/vite.ts", + "./tsconfig.json": "./tsconfig.base.json", + "./package.json": "./package.json" + }, + "dependencies": { + "@usehyperion/types": "workspace:^" + }, + "devDependencies": { + "@sveltejs/vite-plugin-svelte": "^7.0.0", + "@types/node": "^26.6.6", + "svelte": "^5.57.3", + "vite": "catalog:" + }, + "peerDependencies": { + "@sveltejs/vite-plugin-svelte": "^7.0.0", + "svelte": "^5.57.3", + "vite": "*" + }, + "peerDependenciesMeta": { + "@sveltejs/vite-plugin-svelte": { + "optional": true + }, + "vite": { + "optional": true + } + } +} diff --git a/packages/plugin/src/index.ts b/packages/plugin/src/index.ts new file mode 100644 index 00000000..ac27a98e --- /dev/null +++ b/packages/plugin/src/index.ts @@ -0,0 +1,751 @@ +import type { Channel, Emote, User } from "@usehyperion/types"; +import type { Component, ComponentProps, Snippet } from "svelte"; + +export type { Channel, Emote, User } from "@usehyperion/types"; + +export interface PluginManifest { + /** + * Uses only lowercase letters, digits, and dashes. The app stores the + * plugin's settings under this id, so changing it will reset the user's + * settings. + */ + readonly id: string; + + /** + * The name shown in the plugin settings. + */ + readonly name: string; + + /** + * The description shown in the plugin settings. Supports the same markdown + * as {@linkcode PluginSetting} descriptions. + */ + readonly description: string; + readonly version: string; +} + +/** + * The `manifest.json` that the Vite plugin writes next to a built plugin. + */ +export interface BuiltManifest extends PluginManifest { + /** + * The semver range of `@usehyperion/plugin` that the plugin was written + * against, taken from the plugin's dependencies. + */ + readonly api: string; + + /** + * The exact Svelte version that compiled the plugin's components. Compiled + * components only work with a matching Svelte runtime. + */ + readonly svelte: string; + + /** + * The path of the plugin's module, relative to the manifest. + */ + readonly entry: string; +} + +export type EmoteData = Omit; + +/** + * Emotes that the current user can use in every channel, for example from a + * subscription to the provider. Shown as one group in the emote picker. + */ +export interface EmoteSetData { + /** + * Unique among the sets of every provider. + */ + readonly id: string; + readonly name: string; + readonly emotes: EmoteData[]; +} + +export interface ChannelEventOptions { + /** + * Set as the event's `data-type` attribute. The plugin id is set as + * `data-plugin`, so types only need to be unique within the plugin. + */ + readonly type?: string; +} + +export interface LoadContext { + /** + * The app aborts this signal when it no longer needs the result. This + * happens when the user disables the provider or when a reload replaces the + * load. Pass it to {@linkcode PluginHttp.json} to also stop the request. + */ + readonly signal: AbortSignal; +} + +export interface EmoteLoadContext extends LoadContext { + /** + * Whether the user asked for a reload, so cached emotes shouldn't be used. + * Only relevant when the provider caches emotes itself, see + * {@linkcode EmoteProviderOptions.fresh}. + */ + readonly force: boolean; + + /** + * Replaces the emotes that the load resolved with, for example after a + * provider that caches emotes itself finds that they changed. Returns + * whether the emotes were applied. If the {@linkcode signal} was aborted, + * then this is `false`. + */ + update(emotes: EmoteData[]): boolean; +} + +/** + * Registers a source of emotes with {@linkcode Plugin.emotes}. + */ +export interface EmoteProviderOptions { + /** + * Shown in the emote picker and in emote tooltips. The app uses the name to + * identify the provider, so registration throws if another provider already + * uses the same name. + */ + readonly name: string; + + /** + * The icon for the provider's tab in the emote picker. + */ + readonly icon: Component; + + /** + * The image URL that the emote picker shows as the avatar of the + * provider's global emotes. + */ + readonly logo: string; + + /** + * Returns whether the app loads and shows the provider's emotes. The app + * reads it in a reactive context, so the emotes load or disappear when a + * value read inside it changes. The provider is always enabled by default. + * If it throws, the app logs the error and treats the provider as disabled. + */ + readonly enabled?: () => boolean; + + /** + * Loads the emotes that users can use in every channel. + */ + readonly global?: (ctx: EmoteLoadContext) => Promise; + + /** + * Loads the emotes of a channel. Resolve to an empty array when the channel + * has no emotes from this provider. If the provider's API responds with 404 + * for such a channel, pass {@linkcode RequestOptions.notFound} to + * {@linkcode PluginHttp.json}. + */ + readonly channel?: (channel: Channel, ctx: EmoteLoadContext) => Promise; + + /** + * Finds an emote that only the given user can use, in any channel, by its + * name. Personal emotes are prioritized over global and channel emotes. + */ + readonly personal?: (userId: string, name: string) => EmoteData | undefined; + + /** + * Loads the sets of emotes that the current user can use in every + * channel, for the emote picker and autocompletion. + */ + readonly userSets?: (user: User, ctx: LoadContext) => Promise; + + /** + * How many seconds the app uses cached emotes before it fetches them again. + * Pass `false` to cache emotes yourself with {@linkcode Plugin.cache}, for + * example to check whether they changed rather than refetching them after + * a fixed time. + * + * @default 300 // 5 minutes + */ + readonly fresh?: number | false; +} + +/** + * The scope of which a provider's emotes are available, either globally or in + * a channel. + */ +export interface EmoteScope { + /** + * Whether the provider's emotes have loaded here. + */ + readonly loaded: boolean; + + /** + * Finds one of the provider's emotes by its name. + */ + get(name: string): Emote | undefined; + + /** + * Adds an emote or replaces the one with the same + * {@linkcode Emote.displayName}, for example after a live update. + */ + set(emote: EmoteData): void; + + /** + * Removes one of the provider's emotes by its name. + */ + delete(name: string): void; + + /** + * Loads the provider's emotes again if it's enabled. With `force`, the + * load skips the cache. + */ + reload(force?: boolean): Promise; + + /** + * Removes the provider's emotes until they're loaded again. + */ + clear(): void; +} + +export interface EmoteProviderHandle { + readonly global: EmoteScope; + readonly dispose: Dispose; + + /** + * The provider's emotes in a channel, or `undefined` if the app doesn't + * know the channel. + */ + channel(id: string): EmoteScope | undefined; +} + +export interface BadgeData { + /** + * Identifies the badge among this provider's badges. The keys of + * {@linkcode BadgeSet.users} refer to this value. + */ + readonly version: string; + readonly title: string; + + /** + * The alt text of the badge image; defaults to the title. + */ + readonly description?: string; + + /** + * A CSS background color for the badge. + */ + readonly color?: string; + readonly imageUrl: string; +} + +export interface BadgeSet { + readonly badges: BadgeData[]; + + /** + * The Twitch user ids that have each badge, keyed by + * {@linkcode BadgeData.version}. The app ignores versions that are not in + * {@linkcode badges}. + */ + readonly users: Record; +} + +/** + * Registers a source of badges with {@linkcode Plugin.badges}. + */ +export interface BadgeProviderOptions { + /** + * A readable name for the provider. + */ + readonly name: string; + + /** + * Returns whether the app loads and shows the provider's badges. The app + * reads it in a reactive context, so the badges load or disappear when a + * value read inside it changes. The provider is always enabled by default. + * If it throws, the app logs the error and treats the provider as disabled. + */ + readonly enabled?: () => boolean; + + /** + * Loads all of the provider's badges and their users. Omit it if the badges + * arrive some other way, and add them with {@linkcode BadgeProviderHandle}. + */ + readonly load?: (ctx: LoadContext) => Promise; +} + +export interface BadgeProviderHandle { + /** + * Adds a badge or replaces the one with the same version. + */ + set(badge: BadgeData): void; + + /** + * Gives a user a badge that {@linkcode BadgeProviderOptions.load} returned + * or that was added with {@linkcode set}. Does nothing if the provider has + * no badge with that version. + */ + give(userId: string, version: string): void; + readonly dispose: Dispose; +} + +export interface EmbedCardProps { + /** + * Where clicking the card leads. + */ + readonly href: string; + + /** + * The accessible name of the card's link. + */ + readonly label: string; + + /** + * Set as the card's `data-type` attribute. + */ + readonly type: string; + + /** + * The square area at the start of the card, usually an image. + */ + readonly media: Snippet; + + /** + * The text next to the media. + */ + readonly children: Snippet; +} + +/** + * Components from the app that plugins can render. + */ +export interface PluginUi { + /** + * A user's name in their color and decorations. + */ + readonly Username: Component<{ user: User }>; + + /** + * An emote at its chat size with a tooltip. + */ + readonly Emote: Component<{ emote: Emote }>; + + /** + * The card that link embeds use. + */ + readonly EmbedCard: Component; +} + +export interface EmbedProps { + readonly url: URL; + + /** + * What {@linkcode EmbedProviderOptions.match} returned for the URL. + */ + readonly data: T; + readonly ui: PluginUi; +} + +/** + * Registers a kind of link embed with {@linkcode Plugin.embeds}. + */ +export interface EmbedProviderOptions { + /** + * Returns the data the component needs to embed the URL, or `null` if the + * provider doesn't embed anything. This is called for every link in chat. + * If it throws, the app logs the error and treats it as `null`. + */ + match(url: URL): T | null; + + /** + * Renders the embed. This is where you can load more data if necessary. + */ + readonly component: Component>; +} + +interface SettingBase { + readonly label: string; + + /** + * Shown under the label. Supports inline code, links, bold, and italics. + */ + readonly description?: string; + + /** + * Additional search terms that aren't included in the label or description. + */ + readonly keywords?: string[]; +} + +interface ChoiceItem { + readonly label: string; + + /** + * The value that the setting stores when the user selects this item. + */ + readonly value: string; + readonly description?: string; +} + +export type PluginSetting = SettingBase & + ( + | { + readonly type: "switch"; + readonly default: boolean; + } + | { + readonly type: "input"; + readonly default: string; + readonly placeholder?: string; + } + | { + /** + * - `radio` shows every item at once. + * - `select` shows the items in a dropdown, suited for longer lists. + */ + readonly type: "radio" | "select"; + + /** + * The {@linkcode ChoiceItem.value} of the item selected by default. + */ + readonly default: string; + readonly items: ChoiceItem[]; + } + | { + readonly type: "slider"; + readonly default: number; + readonly min?: number; + readonly max?: number; + readonly step?: number; + + /** + * Shows a tick mark at each step along the track. + */ + readonly showSteps?: boolean; + + /** + * Formats the value that the slider displays, for example to add a + * unit. + */ + readonly formatValue?: (value: number) => string; + } + ); + +/** + * A plugin's settings, keyed by a name that is unique in the plugin. Each value + * is stored as `plugins..`, so renaming a key will reset the + * value. The key `enabled` is reserved for the plugin itself. + */ +export type PluginSettings = Record; + +// Distributes over the union so the values of the base `PluginSettings` widen +// to every value type rather than narrowing to `string`. +type SettingValue = T extends { readonly default: infer D } + ? D extends boolean + ? boolean + : D extends number + ? number + : string + : never; + +/** + * The current value of each of the plugin's settings, or its default if the + * user has not changed it. When you read a value in a reactive context, the + * context runs again after the user changes that setting. + */ +export type SettingValues = { + readonly [K in keyof S]: SettingValue; +}; + +export interface RequestOptions { + /** + * @default "GET" + */ + readonly method?: "GET" | "POST"; + readonly headers?: HeadersInit; + + /** + * Sent as a JSON request body. + */ + readonly body?: Record; + + /** + * Cancels the request. When this signal aborts, the promise rejects with + * the signal's reason. + */ + readonly signal?: AbortSignal; + + /** + * The value to resolve with when the server responds with 404. Without it, + * a 404 rejects like any other error status. + */ + readonly notFound?: T; +} + +export interface PluginHttp { + /** + * Fetches a URL and parses the response as JSON. The request uses the + * app's timeout, and an error status or timeout rejects with the app's API + * error, so failures look the same as the app's own requests. + */ + json(url: string, options?: RequestOptions): Promise; +} + +/** + * Stores data across launches in the app's cache. Keys are scoped to the + * plugin, and the user can clear the cache at any time. + */ +export interface PluginCache { + get(key: string): Promise; + + /** + * @param ttl Seconds until the entry is removed; defaults to 30 days. + */ + set(key: string, value: unknown, ttl?: number): Promise; +} + +/** + * Maps each event name to the arguments its listeners receive. + */ +export type EventMap = { [K in keyof E]: unknown[] }; + +export type Listener = (...args: A) => void; + +/** + * Notifies listeners of named events. Listeners are removed when the plugin + * is disabled, so removing them yourself is only needed before that. + */ +export interface EventEmitter> { + /** + * Adds a listener for the event. If it throws, the app logs the error and + * continues with the next listener. + */ + on(event: K, listener: Listener): Dispose; + + /** + * Removes a listener added with {@linkcode on}. This does the same as + * calling the function returned by `on`. + */ + off(event: K, listener: Listener): void; +} + +export interface ChannelEvents { + /** + * The current user joined a channel's chat, including after a reconnect. + * A listener added while channels are already joined runs for each of + * them right away. + */ + join: [channel: Channel]; + + /** + * The current user left a channel's chat. + */ + leave: [channel: Channel]; + + /** + * The current user sent a message in a channel. + */ + messageSent: [channel: Channel]; +} + +export interface PluginChannels extends EventEmitter { + /** + * A channel that the app has in memory, or `undefined`. + */ + get(id: string): Channel | undefined; + + /** + * Adds an event to the channel's chat, rendered by the given component + * with the event chrome around it. Does nothing if the app no longer has + * the channel. + */ + event>( + channel: Channel, + component: C, + props: ComponentProps, + options?: ChannelEventOptions, + ): void; + + /** + * Resolves a user as a viewer of the channel, fetching them if the app + * hasn't seen them yet. Resolves to `null` if the user doesn't exist or + * the app no longer has the channel. + */ + fetchUser(channel: Channel, userId: string): Promise; +} + +export interface PluginUsers { + /** + * The signed-in user, or `null` while nobody is signed in. Reactive. + */ + readonly current: User | null; + + /** + * Adds CSS that styles a user's name, for example a gradient. The app + * reads it in a reactive context and uses the first decoration that + * returns a value, after the user's color. If it throws, the app logs the + * error and moves on to the next decoration. + */ + decorate(style: (userId: string) => string | undefined): Dispose; +} + +/** + * Writes to the app's log. Each message from a plugin is prefixed with + * `[plugin:]`. + */ +export interface PluginLogger { + debug(message: string): void; + info(message: string): void; + warn(message: string, cause?: unknown): void; + error(message: string, cause?: unknown): void; +} + +/** + * Registers providers of one kind. Each call registers one provider and + * returns a way to remove it. + */ +interface Provider { + provide(options: T): R; +} + +interface EmbedProvider { + provide(options: EmbedProviderOptions): Dispose; +} + +/** + * Removes what a call registered. + * + * This only has an effect during the plugin's lifetime since the app removes + * everything that the plugin registered when it's disabled. + */ +export type Dispose = () => void; + +export interface PluginContext { + readonly id: string; + readonly settings: SettingValues; + readonly log: PluginLogger; + readonly http: PluginHttp; + readonly cache: PluginCache; + readonly channels: PluginChannels; + readonly users: PluginUsers; + readonly ui: PluginUi; + readonly emotes: Provider; + readonly badges: Provider; + readonly embeds: EmbedProvider; + register(cleanup: Dispose): void; +} + +/** + * The base class of every plugin. + * + * The app's services are available as fields from the constructor on, so + * field initializers can use them. Everything the plugin registers through + * them is removed when the plugin is disabled. + * + * If you need to provide settings for your plugin, extend + * {@linkcode Plugin.withSettings} instead. + */ +export abstract class Plugin< + S extends PluginSettings = PluginSettings, +> implements PluginContext { + /** + * The settings shown for the plugin on the settings page, set by + * {@linkcode Plugin.withSettings}. + */ + public static readonly settings?: PluginSettings; + + /** + * Returns a base class for a plugin with the given settings, providing + * strong typing for {@linkcode Plugin.settings | this.settings}. + */ + public static withSettings(settings: T): PluginBase { + abstract class WithSettings extends Plugin { + public static override readonly settings = settings; + } + + return WithSettings; + } + + /** + * The plugin's {@linkcode PluginManifest.id}. + */ + public readonly id: string; + public readonly settings: SettingValues; + public readonly log: PluginLogger; + public readonly http: PluginHttp; + public readonly cache: PluginCache; + public readonly channels: PluginChannels; + public readonly users: PluginUsers; + public readonly ui: PluginUi; + + /** + * Registers emote providers. A plugin can register more than one, but each + * one needs a unique name. + */ + public readonly emotes: PluginContext["emotes"]; + + /** + * Registers the plugin's badge provider. A plugin can register only one + * badge provider at a time; attempting to register more than one will throw + * an error. + */ + public readonly badges: PluginContext["badges"]; + + /** + * Registers link embeds. The first provider that matches a link wins. + */ + public readonly embeds: PluginContext["embeds"]; + + readonly #register: (cleanup: Dispose) => void; + + public constructor(ctx: PluginContext) { + this.id = ctx.id; + this.settings = ctx.settings; + this.log = ctx.log; + this.http = ctx.http; + this.cache = ctx.cache; + this.channels = ctx.channels; + this.users = ctx.users; + this.ui = ctx.ui; + this.emotes = ctx.emotes; + this.badges = ctx.badges; + this.embeds = ctx.embeds; + this.#register = (cleanup) => ctx.register(cleanup); + } + + /** + * Runs when the plugin is enabled, inside an + * [`$effect.root`](https://svelte.dev/docs/svelte/$effect#$effect.root) + * that also tracks the constructor. Nested effects are stopped when the + * plugin is disabled. If the root effect throws, the app logs the error, + * removes everything the plugin registered, and calls + * {@linkcode onunload}. + */ + public abstract onload(): void; + + /** + * Runs when the plugin is disabled, after its effects stop and after the + * cleanup functions given to {@linkcode register} run. It also runs when + * {@linkcode onload} throws, so it must handle a plugin that only loaded + * partway. + */ + public onunload(): void {} + + /** + * Adds a function that runs when the plugin is disabled. Cleanup functions + * run in the reverse order of registration. If one throws, the app logs + * the error and continues with the next. + */ + public register(cleanup: Dispose) { + this.#register(cleanup); + } +} + +/** + * The class that {@linkcode Plugin.withSettings} returns. + */ +export type PluginBase = (abstract new ( + ctx: PluginContext, +) => Plugin) & { + readonly settings: S; +}; + +// oxlint-disable-next-line typescript/no-explicit-any +export type PluginConstructor = (new (ctx: PluginContext) => Plugin) & { + readonly settings?: PluginSettings; +}; + +export interface PluginModule { + readonly default: PluginConstructor; +} diff --git a/packages/plugin/src/vite.ts b/packages/plugin/src/vite.ts new file mode 100644 index 00000000..31feda31 --- /dev/null +++ b/packages/plugin/src/vite.ts @@ -0,0 +1,141 @@ +import { readFileSync } from "node:fs"; +import { createRequire } from "node:module"; +import { resolve } from "node:path"; + +import { svelte } from "@sveltejs/vite-plugin-svelte"; +import type { Plugin, PluginOption } from "vite"; + +import type { BuiltManifest } from "./index"; + +export interface HyperionOptions { + /** + * The path of the module that default exports the plugin class, + * relative to the Vite root. + * + * @default "src/index.ts" + */ + entry?: string; +} + +interface PackageJson { + version?: string; + hyperion?: Record; + dependencies?: Record; + devDependencies?: Record; + peerDependencies?: Record; +} + +const API_PACKAGE = "@usehyperion/plugin"; +const ENTRY_FILE = "index.js"; +const ID_REGEX = /^[a-z0-9]+(?:-[a-z0-9]+)*$/; + +// Modules that the build leaves as imports because the app supplies them at +// runtime. +const SHARED = /^svelte(?:\/|$)/; + +export function hyperion(options: HyperionOptions = {}): PluginOption[] { + let root = process.cwd(); + let manifest: BuiltManifest; + + const plugin: Plugin = { + name: "hyperion:plugin", + config(config) { + root = resolve(config.root ?? process.cwd()); + + return { + build: { + target: "esnext", + minify: true, + lib: { + entry: resolve(root, options.entry ?? "src/index.ts"), + formats: ["es"], + fileName: () => ENTRY_FILE, + }, + rolldownOptions: { + external: (id) => SHARED.test(id), + }, + }, + }; + }, + buildStart() { + manifest = readManifest(root, (message) => this.error(message)); + }, + generateBundle() { + this.emitFile({ + type: "asset", + fileName: "manifest.json", + source: `${JSON.stringify(manifest, null, "\t")}\n`, + }); + }, + }; + + return [ + // Each component injects its own styles, so the build emits no CSS file + // and the plugin stays one module. + svelte({ + emitCss: false, + compilerOptions: { css: "injected" }, + }), + plugin, + ]; +} + +function readManifest(root: string, fail: (message: string) => never): BuiltManifest { + const pkgPath = resolve(root, "package.json"); + // oxlint-disable-next-line typescript/no-unsafe-type-assertion + const pkg = JSON.parse(readFileSync(pkgPath, "utf8")) as PackageJson; + const meta = pkg.hyperion ?? fail(`${pkgPath} has no "hyperion" field`); + + function field(key: string) { + const value = meta[key]; + + return typeof value === "string" && value.trim() + ? value.trim() + : fail(`"hyperion.${key}" in ${pkgPath} must be a non-empty string`); + } + + const id = field("id"); + + if (!ID_REGEX.test(id)) { + fail(`"hyperion.id" can only contain lowercase letters, digits, and dashes, got "${id}"`); + } + + const range = + pkg.peerDependencies?.[API_PACKAGE] ?? + pkg.dependencies?.[API_PACKAGE] ?? + pkg.devDependencies?.[API_PACKAGE] ?? + fail(`${pkgPath} must depend on ${API_PACKAGE}`); + + const require = createRequire(pkgPath); + const installed = (name: string) => + // oxlint-disable-next-line typescript/no-unsafe-type-assertion + (require(`${name}/package.json`) as { version: string }).version; + + return { + id, + name: field("name"), + description: field("description"), + version: pkg.version ?? fail(`${pkgPath} has no "version"`), + api: resolveRange(range, () => installed(API_PACKAGE)), + svelte: installed("svelte"), + entry: ENTRY_FILE, + }; +} + +function resolveRange(range: string, version: () => string) { + if (!range.startsWith("workspace:")) { + return range; + } + + const spec = range.slice("workspace:".length); + + switch (spec) { + case "*": + return version(); + case "^": + case "~": + return spec + version(); + default: + return spec; + } +} diff --git a/packages/plugin/tsconfig.base.json b/packages/plugin/tsconfig.base.json new file mode 100644 index 00000000..99b9b7a6 --- /dev/null +++ b/packages/plugin/tsconfig.base.json @@ -0,0 +1,17 @@ +{ + "$schema": "https://json.schemastore.org/tsconfig", + "compilerOptions": { + "target": "esnext", + "module": "esnext", + "moduleResolution": "bundler", + "lib": ["esnext", "DOM", "DOM.Iterable"], + "types": ["vite/client"], + "strict": true, + "noEmit": true, + "isolatedModules": true, + "verbatimModuleSyntax": true, + "resolveJsonModule": true, + "skipLibCheck": true, + "noImplicitOverride": true + } +} diff --git a/packages/plugin/tsconfig.json b/packages/plugin/tsconfig.json new file mode 100644 index 00000000..c3a8b021 --- /dev/null +++ b/packages/plugin/tsconfig.json @@ -0,0 +1,7 @@ +{ + "extends": "./tsconfig.base.json", + "compilerOptions": { + "types": ["node"] + }, + "include": ["src"] +} diff --git a/packages/types/package.json b/packages/types/package.json new file mode 100644 index 00000000..fe54d60c --- /dev/null +++ b/packages/types/package.json @@ -0,0 +1,9 @@ +{ + "name": "@usehyperion/types", + "version": "0.1.0", + "private": true, + "type": "module", + "exports": { + ".": "./src/index.ts" + } +} diff --git a/packages/types/src/index.ts b/packages/types/src/index.ts new file mode 100644 index 00000000..9be92fd0 --- /dev/null +++ b/packages/types/src/index.ts @@ -0,0 +1,96 @@ +export interface User { + /** + * The Twitch user id. + */ + readonly id: string; + + /** + * The lowercase Twitch login name. + */ + readonly username: string; + + /** + * The name shown in chat. The capitalization may differ from the username, + * and it may include a localized name if the user enabled those. + */ + readonly displayName: string; + + /** + * The CSS color of the user's name, after the app's readability + * adjustments. + */ + readonly color: string; +} + +export interface Channel { + /** + * The Twitch user id of the channel owner. + */ + readonly id: string; + + /** + * The channel owner. + */ + readonly user: User; +} + +export interface Emote { + /** + * The name of the provider that supplied the emote, e.g. `Twitch`. + */ + readonly provider: string; + + /** + * The emote's id from its provider. + */ + readonly id: string; + + /** + * The name the provider gives the emote. + */ + readonly name: string; + + /** + * A different name the emote has in one channel, if the channel renamed it. + */ + alias?: string; + + /** + * The name that users see and type. Set it to the alias if there is one, + * and to the name if there is not. + */ + displayName: string; + + /** + * The width of the source image in pixels. + */ + readonly width: number; + + /** + * The height of the source image in pixels. + */ + readonly height: number; + + /** + * The width in pixels that the emote takes up in a chat message. It can be + * different from the image width. + */ + readonly displayWidth: number; + + /** + * The height in pixels that the emote takes up in a chat message. + */ + readonly displayHeight: number; + + /** + * The image candidates for the `srcset` attribute. Each entry has the + * format ` x`, for example `https://cdn.example/1x 1x`. + */ + readonly srcset: string[]; + + /** + * When true, the emote has no width of its own and the app draws it on top + * of the emote before it. + */ + readonly zeroWidth?: boolean; +} diff --git a/packages/types/tsconfig.json b/packages/types/tsconfig.json new file mode 100644 index 00000000..fa8fb83c --- /dev/null +++ b/packages/types/tsconfig.json @@ -0,0 +1,15 @@ +{ + "$schema": "https://json.schemastore.org/tsconfig", + "compilerOptions": { + "target": "esnext", + "module": "esnext", + "moduleResolution": "bundler", + "lib": ["esnext"], + "strict": true, + "noEmit": true, + "isolatedModules": true, + "verbatimModuleSyntax": true, + "skipLibCheck": true + }, + "include": ["src"] +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ecc0780e..596c16aa 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -232,8 +232,23 @@ importers: '@ui-sdk/svelte': specifier: 0.1.0-beta.24 version: 0.1.0-beta.24(@ui-sdk/core@0.1.0-beta.24)(svelte@5.60.2(@typescript-eslint/types@8.74.0)) + '@usehyperion/plugin': + specifier: workspace:^ + version: link:packages/plugin + '@usehyperion/plugin-7tv': + specifier: workspace:^ + version: link:packages/plugin-7tv + '@usehyperion/plugin-bttv': + specifier: workspace:^ + version: link:packages/plugin-bttv + '@usehyperion/plugin-ffz': + specifier: workspace:^ + version: link:packages/plugin-ffz + '@usehyperion/types': + specifier: workspace:^ + version: link:packages/types colord: - specifier: ^2.14.1 + specifier: ^2.14.0 version: 2.14.1 dayjs: specifier: ^1.11.23 @@ -264,7 +279,7 @@ importers: version: 7.6.4 valibot: specifier: ^1.5.0 - version: 1.5.0(typescript@6.0.3) + version: 1.6.0(typescript@6.0.3) virtua: specifier: ^0.56.0 version: 0.56.0(svelte@5.60.2(@typescript-eslint/types@8.74.0)) @@ -280,10 +295,10 @@ importers: version: 3.12.4 '@sveltejs/adapter-static': specifier: ^4.0.1 - version: 4.0.1(@sveltejs/kit@3.5.0(@sveltejs/vite-plugin-svelte@7.3.2(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3))(svelte@5.60.2(@typescript-eslint/types@8.74.0)))(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3))(svelte@5.60.2(@typescript-eslint/types@8.74.0))(typescript@6.0.3)) + version: 4.0.1(@sveltejs/kit@3.5.0(@sveltejs/vite-plugin-svelte@7.3.3(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3))(svelte@5.60.2(@typescript-eslint/types@8.74.0)))(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3))(svelte@5.60.2(@typescript-eslint/types@8.74.0))(typescript@6.0.3)) '@sveltejs/kit': specifier: ^3.5.0 - version: 3.5.0(@sveltejs/vite-plugin-svelte@7.3.2(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3))(svelte@5.60.2(@typescript-eslint/types@8.74.0)))(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3))(svelte@5.60.2(@typescript-eslint/types@8.74.0))(typescript@6.0.3) + version: 3.5.0(@sveltejs/vite-plugin-svelte@7.3.3(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3))(svelte@5.60.2(@typescript-eslint/types@8.74.0)))(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3))(svelte@5.60.2(@typescript-eslint/types@8.74.0))(typescript@6.0.3) '@tauri-apps/cli': specifier: ^2.13.0 version: 2.13.0 @@ -321,6 +336,70 @@ importers: specifier: 'catalog:' version: 1.9.0(@types/node@26.6.11)(@vitest/ui@5.1.2)(jiti@2.7.0)(svelte@5.60.2(@typescript-eslint/types@8.74.0))(typescript@6.0.3) + packages/plugin: + dependencies: + '@usehyperion/types': + specifier: workspace:^ + version: link:../types + vite: + specifier: npm:@voidzero-dev/vite-plus-core@8.4.0 + version: '@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3)' + devDependencies: + '@sveltejs/vite-plugin-svelte': + specifier: ^7.0.0 + version: 7.3.3(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3))(svelte@5.60.2(@typescript-eslint/types@8.74.0)) + '@types/node': + specifier: ^26.6.6 + version: 26.6.11 + svelte: + specifier: ^5.57.3 + version: 5.60.2(@typescript-eslint/types@8.74.0) + + packages/plugin-7tv: + dependencies: + gql.tada: + specifier: ^1.11.4 + version: 1.11.6(@gql.tada/svelte-support@1.0.3(svelte@5.60.2(@typescript-eslint/types@8.74.0))(typescript@6.0.3))(graphql@17.1.0)(typescript@6.0.3) + graphql-web-lite: + specifier: 16.6.0-4 + version: 16.6.0-4(graphql@17.1.0) + devDependencies: + '@usehyperion/plugin': + specifier: workspace:^ + version: link:../plugin + svelte: + specifier: ^5.57.3 + version: 5.60.2(@typescript-eslint/types@8.74.0) + vite: + specifier: 'catalog:' + version: '@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3)' + + packages/plugin-bttv: + devDependencies: + '@usehyperion/plugin': + specifier: workspace:^ + version: link:../plugin + svelte: + specifier: ^5.57.3 + version: 5.60.2(@typescript-eslint/types@8.74.0) + vite: + specifier: 'catalog:' + version: '@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3)' + + packages/plugin-ffz: + devDependencies: + '@usehyperion/plugin': + specifier: workspace:^ + version: link:../plugin + svelte: + specifier: ^5.57.3 + version: 5.60.2(@typescript-eslint/types@8.74.0) + vite: + specifier: 'catalog:' + version: '@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3)' + + packages/types: {} + packages: '@0no-co/graphql.web@1.3.4': @@ -343,16 +422,16 @@ packages: '@antfu/install-pkg@2.1.0': resolution: {integrity: sha512-sdg9NxU3zR4Mnawfbc/x6GB5Wf17WYud5qOuEuxXjaKpYpMkISSJEjItGebXJ2bQ4DIcly4NYH23mtkGJjvKUw==} - '@babel/code-frame@7.29.7': - resolution: {integrity: sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==} + '@babel/code-frame@7.29.17': + resolution: {integrity: sha512-IdlVpcDeoDATtN2cfmnVk0A4XJKhu7SlpGuSaiOFdko09YC1MD07WokWUSEdw5R2o4o8VObX2LzViQW6VXnzkA==} engines: {node: '>=6.9.0'} - '@babel/helper-validator-identifier@7.29.7': - resolution: {integrity: sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==} + '@babel/helper-validator-identifier@7.29.17': + resolution: {integrity: sha512-AG+olLB+teKhkQ2WYJeaZqJwNLjtWTz1waQIP/tEYITzVzpdHLP7IXx2c/bH2JTsNCgvWlkqdCv91xcb8lul8Q==} engines: {node: '>=6.9.0'} - '@babel/runtime@7.29.16': - resolution: {integrity: sha512-LKBjGopxrQE0aFucNL69OyyyF143MOWUULEOftU3oCgyD35Sy84UUpVnt/sNvTb7ZmCyALSt7om+fojlW35zYQ==} + '@babel/runtime@7.29.17': + resolution: {integrity: sha512-CvlZdpED5dsu21yK0DfpXksJWt1zeW09lY49hp7P9cA5Qedx/QkwEs1PfluSJjijH9i94oT9LmtgGWlPY8ISzw==} engines: {node: '>=6.9.0'} '@blazediff/core@1.10.0': @@ -804,8 +883,8 @@ packages: resolution: {integrity: sha512-VT3qmUb8pRV2QrZjd8iAmtg8lf4W0TIjZbvXtz5MKei/q96teWZgGJyyidJzOjzZzvdq616eSRVeMYIQChUTAQ==} engines: {node: '>= 18.0.0'} - '@sveltejs/vite-plugin-svelte@7.3.2': - resolution: {integrity: sha512-86J4nBLeTqYYIx/paBIRqYJMFYlpTS2sepUdQ6tUyU1jxqRV72ejOrIV2wsqlOsKlkM+h0G1SgwoHI30N+n9CA==} + '@sveltejs/vite-plugin-svelte@7.3.3': + resolution: {integrity: sha512-DRlbdAR4JPByiz+9MIUCS101Mx5xLHRAdj85qc0QJurwjsaS+0wt+pyDPqi7iN957mo+LqVqgKeN/F9iv7vqeQ==} engines: {node: ^20.19 || ^22.12 || >=24} peerDependencies: svelte: ^5.46.4 @@ -1027,8 +1106,8 @@ packages: resolution: {integrity: sha512-yzr2S9HyAIdhz2/6qHgbs665Q7PKVcDF05vsOlHPxG1mo36gKVesdYVeDLnXgfjJ03CrKRk08knc6+E/9m8v2Q==} engines: {node: '>=18'} - '@testing-library/user-event@14.6.13': - resolution: {integrity: sha512-2LVZGptuB5un1Cu/u31o9adkCwbsUTMp4B4p04xupI7uobvTIpgKidSdShqZiReo/mQmvR9xjgdgTgge4oAbYA==} + '@testing-library/user-event@14.6.14': + resolution: {integrity: sha512-N2IuJHrFLa4uEpVzOqMjwoFJ26PLjbEZnX+8ogaDKRcKyKGb5WviZW4IZ1zOQZJzIZGpB0ESkG4QTjJ4ViiYtA==} engines: {node: '>=12', npm: '>=6'} peerDependencies: '@testing-library/dom': '>=7.21.4' @@ -1385,8 +1464,8 @@ packages: resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==} engines: {node: 18 || 20 || >=22} - brace-expansion@5.1.0: - resolution: {integrity: sha512-aa11Dv491GKnYqxaul3aRJ0szew7yMJMfZPnqD44NjGrZXoj62l41OEDDpdpC4eE2P88vBFfLuSyRhpG91NUvg==} + brace-expansion@5.1.2: + resolution: {integrity: sha512-ELhY3JEerIBbhgW+rh0/8glkZAaMqn1x3BAvp3yTULSEGozMK/5PT6WTdBgsdvJqwwmv7MAQNOydfYbvK1Vgfw==} engines: {node: 20 || >=22} cacheable@2.5.0: @@ -1420,8 +1499,8 @@ packages: resolution: {integrity: sha512-SL0cVuEdETEp7pN0FuZb01toc3vnODEfVUCooxG1SJN0yIirh7JMb9X9bvfCFf0vzzbT68RdbKDHYTiWy7a7iw==} engines: {node: '>=22'} - cross-spawn@7.0.6: - resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==} + cross-spawn@7.1.2: + resolution: {integrity: sha512-8BPK2r+sKWC8sDinRwLwrFMq2lXTBBwzYYEB9LiCznfMurOi4FOvQflq3XOLGG+HPdMSVpe+k/s96+AtDEOgPg==} engines: {node: '>= 8'} dayjs@1.11.23: @@ -1442,10 +1521,6 @@ packages: deep-is@0.1.4: resolution: {integrity: sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==} - deepmerge@4.3.1: - resolution: {integrity: sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==} - engines: {node: '>=0.10.0'} - dequal@2.0.3: resolution: {integrity: sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==} engines: {node: '>=6'} @@ -1464,8 +1539,8 @@ packages: dom-accessibility-api@0.5.16: resolution: {integrity: sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==} - enhanced-resolve@5.27.0: - resolution: {integrity: sha512-Do6BB2xzlcc/odFg+XEYyneAx4T/WfywO71yw9ePS2tVfRsf7JVR4mUeELadIeHzixkzbG5DpluiEFPi2WGfYQ==} + enhanced-resolve@5.27.2: + resolution: {integrity: sha512-Cpp3nuaI7ZdgEsvVP6zzk08uxrfGTSUnDwijv6PZfe8qHjcUYv5X9bJF71WTt5HwOeaeVandf9zACK4jcWroNw==} engines: {node: '>=10.13.0'} es-module-lexer@2.3.2: @@ -1581,8 +1656,8 @@ packages: flat-cache@6.1.23: resolution: {integrity: sha512-f++BY9pTk+983xK1FLzlLpmM0i0z+jHmx3QESGkURMXujQZz1k5wzwX6hjnQ8goaD0B+sYnDK1yZ6MTyZfUaqA==} - flatted@3.4.4: - resolution: {integrity: sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q==} + flatted@3.6.0: + resolution: {integrity: sha512-1Szo+c/GCm/cKBovrfT0Wpqw7fiqZg/xzlZtLtvWlYyvT4zUGZTS8Qo3sXPQ0nWqMg3N4nEFL2Ukzrjnsopwbg==} fsevents@2.3.3: resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} @@ -1766,8 +1841,8 @@ packages: magic-string@1.4.5: resolution: {integrity: sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==} - minimatch@11.0.9: - resolution: {integrity: sha512-KCFkfyjqerNlSstjlhIGNXIKZGA/6O4V4RlhZ+Dsr621SPPw0mzlypE9D9ZOoPiVefHID+j7/XuMMlqfD/F60Q==} + minimatch@11.0.10: + resolution: {integrity: sha512-L3/cjhQ5E6lft0VCp/2mO3Ic74RnutKy3rz7iGwp/6w1hKcO262g2rbfacFyw6eBig5OdI0nu5PpuA0/WQs9Tw==} engines: {node: 20 || >=22} mlly@1.8.2: @@ -1865,8 +1940,8 @@ packages: resolution: {integrity: sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==} engines: {node: '>=10'} - package-manager-detector@1.9.0: - resolution: {integrity: sha512-zAMfbta9nPA8AKkA4WdmNAT8R8s6Dk0/xwPsqNnRidMFcLo1YkLuPDTgs2f64XdzS8vbLNnoJ+uUIkgbz7oRHA==} + package-manager-detector@1.10.0: + resolution: {integrity: sha512-FlC7wr4YYRfVyk1E3u3qwi7Vh6qVvPowYkHQSDEoSKCN0o0F7w0TzNfJSBb/1rwEQbU3c96Exx/2vMYiCIx+wQ==} paneforge@1.0.2: resolution: {integrity: sha512-KzmIXQH1wCfwZ4RsMohD/IUtEjVhteR+c+ulb/CHYJHX8SuDXoJmChtsc/Xs5Wl8NHS4L5Q7cxL8MG40gSU1bA==} @@ -1973,8 +2048,8 @@ packages: resolution: {integrity: sha512-2wcC/oGxHis/BoHkkPwldgiPSYcpZK3JU28WoMVv55yHJgcZ8rlXvuG9iZggz+sU1d4bRgIGASwyWqjxu3FM0g==} engines: {node: '>=18'} - source-map-js@1.2.4: - resolution: {integrity: sha512-J7ZjMvHd9O1fcT/5V09QWaaSl2BbWx3F6O08spde82Namf9UB0GxRVIPiNbVsdKkoizHiSpTodo3vp2bAy91MA==} + source-map-js@1.3.0: + resolution: {integrity: sha512-pdUVfIWcK0kCgK831ibqkZDcL7I9zljjOu0TQFnA+fiQ6y1CYqYB7RkTOHHO45FGMg5P/Mvk/+4ToQ7gAYAL5Q==} engines: {node: '>=6.0.0'} std-env@4.3.0: @@ -2003,11 +2078,11 @@ packages: peerDependencies: svelte: ^5.30.2 - svelte2tsx@0.7.63: - resolution: {integrity: sha512-gRgz/V6wOx0NDZhm6OMD2VIh+/HrgZc3k6ibX93rkNPEkWNn/P3Uhb1fYCqOrimEUpQd8r65dhiHZIJXSQBeow==} + svelte2tsx@0.7.64: + resolution: {integrity: sha512-/aPUIr0+kyVtiPr+HGl88YMR4DQdpjskiw5/90FWgek3W0lL1DPkdeMAFdhZ4bVui5M1UEhdfyqY+/iWmyqNvg==} peerDependencies: - svelte: ^3.55 || ^4.0.0-next.0 || ^4.0 || ^5.0.0-next.0 - typescript: ^4.9.4 || ^5.0.0 || ^6.0.0 + svelte: ^3.55 || ^4.0.0 || ^5.0.0 + typescript: ^4.9.4 || ^5.0.0 || ^6.0.0 || ^7.1.0-0 svelte@5.60.2: resolution: {integrity: sha512-AlsscDbX17QNh1MV4ZO/7a8XpjDrWTDX8Wv3QjHzFATvC7NL+z/PRvu0poBAkVZe8dvpvieGBqcJio7aopkh0A==} @@ -2150,8 +2225,8 @@ packages: resolution: {integrity: sha512-Sc5u1VVln93y1Xnz4R+CunOZc7R9LUcTmhj7Rc7Eg3HVcf7rVn2FOoa812fe0W8p3jD7xeoGSYbfqCGGH2B6xw==} hasBin: true - valibot@1.5.0: - resolution: {integrity: sha512-nil6AkP2TChWL43Z5uJ6GTxX01CUA+g8LWUM+N/rB9NBbkUMaUsi9PUNzlUPgoKASgmx9f7eGOYpJ04/fSa6FQ==} + valibot@1.6.0: + resolution: {integrity: sha512-r8Cpu38zehdfONp8KbtWDDAFR3S3sklmSm0hAn61yC5WUKJvMr4LTds+c3kQqkjw4bKliHlo29doqZk0mbiTXQ==} peerDependencies: typescript: '>=5' peerDependenciesMeta: @@ -2319,23 +2394,23 @@ snapshots: '@antfu/install-pkg@1.1.0': dependencies: - package-manager-detector: 1.9.0 + package-manager-detector: 1.10.0 tinyexec: 1.4.0 '@antfu/install-pkg@2.1.0': dependencies: - package-manager-detector: 1.9.0 + package-manager-detector: 1.10.0 tinyexec: 1.4.0 - '@babel/code-frame@7.29.7': + '@babel/code-frame@7.29.17': dependencies: - '@babel/helper-validator-identifier': 7.29.7 + '@babel/helper-validator-identifier': 7.29.17 js-tokens: 4.0.0 picocolors: 1.1.1 - '@babel/helper-validator-identifier@7.29.7': {} + '@babel/helper-validator-identifier@7.29.17': {} - '@babel/runtime@7.29.16': {} + '@babel/runtime@7.29.17': {} '@blazediff/core@1.10.0': {} @@ -2405,7 +2480,7 @@ snapshots: dependencies: '@eslint/object-schema': 3.0.5 debug: 4.4.3 - minimatch: 11.0.9 + minimatch: 11.0.10 transitivePeerDependencies: - supports-color @@ -2443,7 +2518,7 @@ snapshots: '@gql.tada/svelte-support@1.0.3(svelte@5.60.2(@typescript-eslint/types@8.74.0))(typescript@6.0.3)': dependencies: '@jridgewell/sourcemap-codec': 1.6.0 - svelte2tsx: 0.7.63(svelte@5.60.2(@typescript-eslint/types@8.74.0))(typescript@6.0.3) + svelte2tsx: 0.7.64(svelte@5.60.2(@typescript-eslint/types@8.74.0))(typescript@6.0.3) typescript: 6.0.3 vscode-languageserver-textdocument: 1.0.16 transitivePeerDependencies: @@ -2648,16 +2723,16 @@ snapshots: dependencies: acorn: 8.19.0 - '@sveltejs/adapter-static@4.0.1(@sveltejs/kit@3.5.0(@sveltejs/vite-plugin-svelte@7.3.2(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3))(svelte@5.60.2(@typescript-eslint/types@8.74.0)))(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3))(svelte@5.60.2(@typescript-eslint/types@8.74.0))(typescript@6.0.3))': + '@sveltejs/adapter-static@4.0.1(@sveltejs/kit@3.5.0(@sveltejs/vite-plugin-svelte@7.3.3(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3))(svelte@5.60.2(@typescript-eslint/types@8.74.0)))(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3))(svelte@5.60.2(@typescript-eslint/types@8.74.0))(typescript@6.0.3))': dependencies: - '@sveltejs/kit': 3.5.0(@sveltejs/vite-plugin-svelte@7.3.2(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3))(svelte@5.60.2(@typescript-eslint/types@8.74.0)))(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3))(svelte@5.60.2(@typescript-eslint/types@8.74.0))(typescript@6.0.3) + '@sveltejs/kit': 3.5.0(@sveltejs/vite-plugin-svelte@7.3.3(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3))(svelte@5.60.2(@typescript-eslint/types@8.74.0)))(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3))(svelte@5.60.2(@typescript-eslint/types@8.74.0))(typescript@6.0.3) - '@sveltejs/kit@3.5.0(@sveltejs/vite-plugin-svelte@7.3.2(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3))(svelte@5.60.2(@typescript-eslint/types@8.74.0)))(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3))(svelte@5.60.2(@typescript-eslint/types@8.74.0))(typescript@6.0.3)': + '@sveltejs/kit@3.5.0(@sveltejs/vite-plugin-svelte@7.3.3(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3))(svelte@5.60.2(@typescript-eslint/types@8.74.0)))(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3))(svelte@5.60.2(@typescript-eslint/types@8.74.0))(typescript@6.0.3)': dependencies: '@jridgewell/trace-mapping': 0.3.31 '@rolldown/pluginutils': 1.1.1 '@standard-schema/spec': 1.1.0 - '@sveltejs/vite-plugin-svelte': 7.3.2(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3))(svelte@5.60.2(@typescript-eslint/types@8.74.0)) + '@sveltejs/vite-plugin-svelte': 7.3.3(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3))(svelte@5.60.2(@typescript-eslint/types@8.74.0)) cookie: 2.0.2 devalue: 6.0.4 esm-env: 1.2.2 @@ -2671,9 +2746,8 @@ snapshots: '@sveltejs/load-config@0.2.3': {} - '@sveltejs/vite-plugin-svelte@7.3.2(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3))(svelte@5.60.2(@typescript-eslint/types@8.74.0))': + '@sveltejs/vite-plugin-svelte@7.3.3(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3))(svelte@5.60.2(@typescript-eslint/types@8.74.0))': dependencies: - deepmerge: 4.3.1 obug: 3.0.0 svelte: 5.60.2(@typescript-eslint/types@8.74.0) vite: '@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3)' @@ -2684,11 +2758,11 @@ snapshots: '@tailwindcss/node@4.3.5': dependencies: '@jridgewell/remapping': 2.3.5 - enhanced-resolve: 5.27.0 + enhanced-resolve: 5.27.2 jiti: 2.7.0 lightningcss: 1.33.0 magic-string: 1.4.5 - source-map-js: 1.2.4 + source-map-js: 1.3.0 tailwindcss: 4.3.5 '@tailwindcss/oxide-android-arm64@4.3.5': @@ -2848,8 +2922,8 @@ snapshots: '@testing-library/dom@10.4.2': dependencies: - '@babel/code-frame': 7.29.7 - '@babel/runtime': 7.29.16 + '@babel/code-frame': 7.29.17 + '@babel/runtime': 7.29.17 '@types/aria-query': 5.0.4 aria-query: 5.3.0 dom-accessibility-api: 0.5.16 @@ -2857,7 +2931,7 @@ snapshots: picocolors: 1.1.1 pretty-format: 27.5.1 - '@testing-library/user-event@14.6.13(@testing-library/dom@10.4.2)': + '@testing-library/user-event@14.6.14(@testing-library/dom@10.4.2)': dependencies: '@testing-library/dom': 10.4.2 @@ -2931,7 +3005,7 @@ snapshots: '@typescript-eslint/types': 8.74.0 '@typescript-eslint/visitor-keys': 8.74.0 debug: 4.4.3 - minimatch: 11.0.9 + minimatch: 11.0.10 semver: 7.8.6 tinyglobby: 0.2.17 ts-api-utils: 2.5.0(typescript@6.0.3) @@ -2966,7 +3040,7 @@ snapshots: '@vitest/browser-preview@5.1.2(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3))(vitest@5.1.2)': dependencies: '@testing-library/dom': 10.4.2 - '@testing-library/user-event': 14.6.13(@testing-library/dom@10.4.2) + '@testing-library/user-event': 14.6.14(@testing-library/dom@10.4.2) '@vitest/browser': 5.1.2(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3))(vitest@5.1.2) vitest: 5.1.2(@types/node@26.6.11)(@vitest/browser-preview@5.1.2)(@vitest/ui@5.1.2)(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3)) transitivePeerDependencies: @@ -3019,7 +3093,7 @@ snapshots: dependencies: '@vitest/utils': 5.1.2 fflate: 0.8.3 - flatted: 3.4.4 + flatted: 3.6.0 pathe: 2.0.3 sirv: 3.0.2 tinyrainbow: 3.2.0 @@ -3127,7 +3201,7 @@ snapshots: balanced-match@4.0.4: {} - brace-expansion@5.1.0: + brace-expansion@5.1.2: dependencies: balanced-match: 4.0.4 @@ -3157,7 +3231,7 @@ snapshots: cookie@2.0.2: {} - cross-spawn@7.0.6: + cross-spawn@7.1.2: dependencies: path-key: 3.1.1 shebang-command: 2.0.0 @@ -3173,8 +3247,6 @@ snapshots: deep-is@0.1.4: {} - deepmerge@4.3.1: {} - dequal@2.0.3: {} destr@2.0.5: {} @@ -3185,7 +3257,7 @@ snapshots: dom-accessibility-api@0.5.16: {} - enhanced-resolve@5.27.0: + enhanced-resolve@5.27.2: dependencies: graceful-fs: 4.2.12 tapable: 2.3.4 @@ -3232,7 +3304,7 @@ snapshots: '@humanwhocodes/retry': 0.4.3 '@types/estree': 1.0.11 ajv: 6.15.0 - cross-spawn: 7.0.6 + cross-spawn: 7.1.2 debug: 4.4.3 escape-string-regexp: 4.0.0 eslint-scope: 9.1.2 @@ -3248,7 +3320,7 @@ snapshots: imurmurhash: 0.1.4 is-glob: 4.0.3 json-stable-stringify-without-jsonify: 1.0.1 - minimatch: 11.0.9 + minimatch: 11.0.10 natural-compare: 1.4.0 optionator: 0.9.4 optionalDependencies: @@ -3314,10 +3386,10 @@ snapshots: flat-cache@6.1.23: dependencies: cacheable: 2.5.0 - flatted: 3.4.4 + flatted: 3.6.0 hookified: 1.15.1 - flatted@3.4.4: {} + flatted@3.6.0: {} fsevents@2.3.3: optional: true @@ -3466,10 +3538,10 @@ snapshots: dependencies: '@jridgewell/sourcemap-codec': 1.6.0 - minimatch@11.0.9: + minimatch@11.0.10: dependencies: '@isaacs/nonrecursive-glob-match': 1.1.0 - brace-expansion: 5.1.0 + brace-expansion: 5.1.2 mlly@1.8.2: dependencies: @@ -3581,7 +3653,7 @@ snapshots: dependencies: p-limit: 3.1.0 - package-manager-detector@1.9.0: {} + package-manager-detector@1.10.0: {} paneforge@1.0.2(svelte@5.60.2(@typescript-eslint/types@8.74.0)): dependencies: @@ -3617,7 +3689,7 @@ snapshots: dependencies: nanoid: 3.3.20 picocolors: 1.1.1 - source-map-js: 1.2.4 + source-map-js: 1.3.0 prelude-ls@1.2.1: {} @@ -3676,7 +3748,7 @@ snapshots: mrmime: 2.0.1 totalist: 3.0.1 - source-map-js@1.2.4: {} + source-map-js@1.3.0: {} std-env@4.3.0: {} @@ -3711,7 +3783,7 @@ snapshots: style-to-object: 1.0.14 svelte: 5.60.2(@typescript-eslint/types@8.74.0) - svelte2tsx@0.7.63(svelte@5.60.2(@typescript-eslint/types@8.74.0))(typescript@6.0.3): + svelte2tsx@0.7.64(svelte@5.60.2(@typescript-eslint/types@8.74.0))(typescript@6.0.3): dependencies: dedent-js: 1.0.1 scule: 1.3.0 @@ -3830,7 +3902,7 @@ snapshots: uuid@14.0.3: {} - valibot@1.5.0(typescript@6.0.3): + valibot@1.6.0(typescript@6.0.3): optionalDependencies: typescript: 6.0.3 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index cf2f3936..078489e3 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -1,3 +1,5 @@ +packages: + - packages/* allowBuilds: esbuild: false catalog: diff --git a/src-tauri/src/api.rs b/src-tauri/src/api.rs index ca42fae4..26789f00 100644 --- a/src-tauri/src/api.rs +++ b/src-tauri/src/api.rs @@ -19,8 +19,6 @@ pub fn ensure_login(login: &str) -> Result<(), Error> { pub async fn join( state: State<'_, Mutex>, id: String, - stv_id: Option, - set_id: Option, login: String, is_mod: bool, ) -> Result<(), Error> { @@ -30,12 +28,6 @@ pub async fn join( let state = state.lock().await; let irc = irc::client(&state)?; - if let Some(seventv) = &state.seventv { - seventv - .client() - .join(&login, &id, stv_id.as_deref(), set_id.as_deref()); - } - if let Some(pubsub) = &state.pubsub { pubsub.client().listen(&login, &id, is_mod); } @@ -53,10 +45,6 @@ pub async fn leave(state: State<'_, Mutex>, login: String) -> Result<( let state = state.lock().await; let irc = irc::client(&state)?; - if let Some(seventv) = &state.seventv { - seventv.client().leave(&login); - } - if let Some(pubsub) = &state.pubsub { pubsub.client().unlisten(&login); } diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 58b446c1..b4502f59 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -5,7 +5,6 @@ use cache::Cache; use connection::Connection; use irc::IrcClient; use pubsub::PubSubClient; -use seventv::SeventTvClient; use tauri::Manager; use tauri::async_runtime::{self, Mutex}; use tauri::ipc::Invoke; @@ -23,7 +22,6 @@ mod log; mod notify; mod popout; mod pubsub; -mod seventv; mod theme; mod ws; @@ -41,7 +39,6 @@ pub struct AppState { unverified: PendingToken, integrity: IntegrityState, irc: Option>, - seventv: Option>, pubsub: Option>, } @@ -53,7 +50,6 @@ impl AppState { unverified: PendingToken::default(), integrity: IntegrityState::default(), irc: None, - seventv: None, pubsub: None, } } @@ -61,7 +57,6 @@ impl AppState { fn close_connections(&mut self) { connection::close(&mut self.irc); connection::close(&mut self.pubsub); - connection::close(&mut self.seventv); } } @@ -182,8 +177,6 @@ fn get_handler() -> impl Fn(Invoke) -> bool { log::log, log::update_log_level, pubsub::connect_pubsub, - seventv::connect_seventv, - seventv::sync_seventv, notify::notify, ] } diff --git a/src-tauri/src/seventv/client.rs b/src-tauri/src/seventv/client.rs deleted file mode 100644 index 642e7a7d..00000000 --- a/src-tauri/src/seventv/client.rs +++ /dev/null @@ -1,228 +0,0 @@ -use std::sync::Arc; -use std::time::Duration; - -use futures::FutureExt; -use serde::Deserialize; -use serde_json::json; -use tokio::sync::mpsc; - -use crate::connection::Started; -use crate::ws::{self, Changes, Flow, Link, Protocol, SubscriptionStore, WsError}; - -/// Assumed until the server's hello says otherwise. -const DEFAULT_HEARTBEAT_INTERVAL: Duration = Duration::from_secs(25); - -/// How late a heartbeat may be before the connection counts as dead. -const HEARTBEAT_GRACE: Duration = Duration::from_secs(10); - -mod op { - pub const DISPATCH: u8 = 0; - pub const HELLO: u8 = 1; - pub const HEARTBEAT: u8 = 2; - pub const RECONNECT: u8 = 4; - pub const ACK: u8 = 5; - pub const ERROR: u8 = 6; - pub const END_OF_STREAM: u8 = 7; - pub const RESUME: u8 = 34; - pub const SUBSCRIBE: u8 = 35; - pub const UNSUBSCRIBE: u8 = 36; -} - -#[derive(Deserialize)] -struct Envelope { - op: u8, - #[serde(default)] - d: serde_json::Value, -} - -#[derive(Deserialize)] -struct Hello { - session_id: String, - heartbeat_interval: Option, -} - -pub struct SeventTvClient { - subscriptions: SubscriptionStore, -} - -impl SeventTvClient { - pub fn start() -> Started { - let client = Arc::new(Self { - subscriptions: SubscriptionStore::default(), - }); - - let (events_tx, events) = mpsc::unbounded_channel(); - - let driver = SeventTvDriver { - client: Arc::clone(&client), - events: events_tx, - session_id: None, - resuming: None, - heartbeat_timeout: DEFAULT_HEARTBEAT_INTERVAL + HEARTBEAT_GRACE, - }; - - Started { - client, - events, - run: Some(ws::run(driver).boxed()), - } - } - - /// Replaces the events subscribed to for `channel`. - pub fn set_channel(&self, channel: &str, events: Vec<(String, serde_json::Value)>) { - self.subscriptions.set_channel(channel, events); - } - - pub fn leave(&self, channel: &str) { - self.subscriptions.remove_channel(channel); - } -} - -struct SeventTvDriver { - client: Arc, - events: mpsc::UnboundedSender, - /// The last session that became ready. Resuming it after a drop keeps its - /// subscriptions and replays the events missed in between. - session_id: Option, - /// This connection's session, while waiting to hear whether resuming - /// `session_id` worked. - resuming: Option, - heartbeat_timeout: Duration, -} - -impl SeventTvDriver { - async fn hello(&mut self, hello: Hello, link: &mut Link) -> Result { - if let Some(interval) = hello.heartbeat_interval { - self.heartbeat_timeout = Duration::from_millis(interval) + HEARTBEAT_GRACE; - link.expect_within(self.heartbeat_timeout); - } - - let Some(previous) = &self.session_id else { - tracing::info!(id = %hello.session_id, "Session established"); - self.session_id = Some(hello.session_id); - - return Ok(Flow::Ready { restored: false }); - }; - - tracing::info!(%previous, "Resuming session"); - - link.send(&json!({ - "op": op::RESUME, - "d": { "session_id": previous } - })) - .await?; - - self.resuming = Some(hello.session_id); - - Ok(Flow::Continue) - } - - fn resumed(&mut self, session_id: String, restored: bool) -> Flow { - if restored { - tracing::info!(id = %session_id, "Session resumed"); - } else { - tracing::warn!(id = %session_id, "Resume unsuccessful, resubscribing"); - } - - self.session_id = Some(session_id); - - Flow::Ready { restored } - } -} - -impl Protocol for SeventTvDriver { - type Subscription = serde_json::Value; - - const NAME: &'static str = "7TV"; - const URI: &'static str = "wss://events.7tv.io/v3"; - - fn subscriptions(&self) -> &SubscriptionStore { - &self.client.subscriptions - } - - fn opened(&mut self, link: &mut Link) -> Flow { - self.resuming = None; - link.expect_within(self.heartbeat_timeout); - - Flow::Continue - } - - async fn received(&mut self, text: &str, link: &mut Link) -> Result { - let Envelope { op, d } = match serde_json::from_str(text) { - Ok(envelope) => envelope, - Err(err) => { - tracing::warn!(%err, "Failed to deserialize 7TV message"); - return Ok(Flow::Continue); - } - }; - - // Heartbeats are what the server promises, but anything it sends shows - // the connection is alive - link.expect_within(self.heartbeat_timeout); - - match op { - op::DISPATCH => { - if self.events.send(d).is_err() { - tracing::warn!("7TV event receiver dropped"); - } - } - op::HELLO => match serde_json::from_value(d) { - Ok(hello) => return self.hello(hello, link).await, - Err(err) => { - tracing::error!(%err, "Malformed hello"); - return Ok(Flow::Reconnect); - } - }, - op::HEARTBEAT => tracing::trace!("Heartbeat received"), - op::RECONNECT => { - tracing::warn!("7TV server requested reconnect"); - return Ok(Flow::Reconnect); - } - op::ACK => match self.resuming.take() { - // Nothing is subscribed while resuming, so this acknowledges it - Some(session_id) => { - let restored = d["data"]["success"].as_bool().unwrap_or(false); - return Ok(self.resumed(session_id, restored)); - } - None => tracing::debug!(payload = %d, "Opcode acknowledged"), - }, - op::ERROR => { - tracing::error!(payload = %d, "7TV returned an error"); - - // In place of the resume's ack, it means resuming failed - if let Some(session_id) = self.resuming.take() { - return Ok(self.resumed(session_id, false)); - } - } - op::END_OF_STREAM => { - tracing::warn!(payload = %d, "End of stream reached"); - return Ok(Flow::Reconnect); - } - _ => tracing::debug!(op, "Unhandled 7TV opcode"), - } - - Ok(Flow::Continue) - } - - async fn sync( - &mut self, - changes: &Changes, - link: &mut Link, - ) -> Result<(), WsError> { - let removed = changes.removed.iter().map(|entry| (op::UNSUBSCRIBE, entry)); - let added = changes.added.iter().map(|entry| (op::SUBSCRIBE, entry)); - - for (op, (key, condition)) in removed.chain(added) { - link.send(&json!({ - "op": op, - "d": { - "type": key.event, - "condition": condition - } - })) - .await?; - } - - Ok(()) - } -} diff --git a/src-tauri/src/seventv/mod.rs b/src-tauri/src/seventv/mod.rs deleted file mode 100644 index f3232f90..00000000 --- a/src-tauri/src/seventv/mod.rs +++ /dev/null @@ -1,86 +0,0 @@ -mod client; - -pub use client::SeventTvClient; -use serde_json::json; -use tauri::ipc::Channel; -use tauri::{AppHandle, State}; -use tokio::sync::Mutex; - -use crate::AppState; -use crate::api::ensure_login; -use crate::connection::{self, Client, Connection}; -use crate::error::Error; - -impl SeventTvClient { - pub fn join( - &self, - login: &str, - channel_id: &str, - user_id: Option<&str>, - emote_set_id: Option<&str>, - ) { - let channel = json!({ - "ctx": "channel", - "platform": "TWITCH", - "id": channel_id - }); - - let mut events = vec![ - ("cosmetic.create".to_owned(), channel.clone()), - ("entitlement.create".to_owned(), channel), - ]; - - if let Some(emote_set_id) = emote_set_id { - events.push(( - "emote_set.*".to_owned(), - json!({ "object_id": emote_set_id }), - )); - } - - if let Some(user_id) = user_id { - events.push(("user.update".to_owned(), json!({ "object_id": user_id }))); - } - - self.set_channel(login, events); - } -} - -impl Client for SeventTvClient { - type Message = serde_json::Value; - - const NAME: &'static str = "7TV"; - - fn slot(state: &mut AppState) -> &mut Option> { - &mut state.seventv - } -} - -#[tauri::command] -pub async fn connect_seventv( - app_handle: AppHandle, - channel: Channel, -) -> Result<(), Error> { - connection::connect(app_handle, channel, |_| Ok(SeventTvClient::start())).await -} - -/// Recomputes the 7TV subscriptions for a joined channel after its 7TV user or -/// active emote set changed. -#[tracing::instrument(skip(state))] -#[tauri::command] -pub async fn sync_seventv( - state: State<'_, Mutex>, - login: String, - id: String, - stv_id: Option, - set_id: Option, -) -> Result<(), Error> { - ensure_login(&login)?; - - if let Some(seventv) = &state.lock().await.seventv { - seventv - .client() - .join(&login, &id, stv_id.as_deref(), set_id.as_deref()); - } - - Ok(()) -} diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 3a758cef..eff4c803 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -25,7 +25,7 @@ } ], "security": { - "csp": "default-src 'self' https: ipc: http://ipc.localhost; style-src 'self' 'unsafe-inline' theme: http://theme.localhost; font-src 'self' data: theme: http://theme.localhost https:; img-src 'self' data: https: theme: http://theme.localhost", + "csp": "default-src 'self' https: ipc: http://ipc.localhost; connect-src 'self' https: wss: ipc: http://ipc.localhost; style-src 'self' 'unsafe-inline' theme: http://theme.localhost; font-src 'self' data: theme: http://theme.localhost https:; img-src 'self' data: https: theme: http://theme.localhost", "dangerousDisableAssetCspModification": ["style-src"] } }, diff --git a/src/hooks.client.ts b/src/hooks.client.ts index 00fc06f1..63157d00 100644 --- a/src/hooks.client.ts +++ b/src/hooks.client.ts @@ -4,6 +4,8 @@ import localizedFormat from "dayjs/plugin/localizedFormat"; import relativeTime from "dayjs/plugin/relativeTime"; import { log } from "#lib/log.js"; +import { startPlugins } from "#lib/plugins/host.svelte.js"; +import { settings } from "#lib/settings.js"; import { loadThemes } from "#lib/themes.js"; dayjs.extend(duration); @@ -11,6 +13,12 @@ dayjs.extend(localizedFormat); dayjs.extend(relativeTime); export async function init() { + // Settings need to be started before plugins so their settings are loaded + // before they're read. + await settings.start().catch(log.swallow("Failed to load settings")); + + startPlugins(); + // Themes are optional, so errors shouldn't block the app from starting await loadThemes().catch(log.swallow("Failed to load themes")); } diff --git a/src/lib/app.svelte.ts b/src/lib/app.svelte.ts index 54a1e800..2cf5a8b4 100644 --- a/src/lib/app.svelte.ts +++ b/src/lib/app.svelte.ts @@ -7,7 +7,6 @@ import { page } from "$app/state"; import type { Channel } from "./models/channel.svelte"; import type { Followed } from "./models/current-user.svelte"; import type { NotificationOptions, NotificationResponse } from "./notifications"; -import type { DispatchPayload } from "./seventv"; import type { IrcMessage } from "./twitch/irc"; import type { PubSubMessage } from "./twitch/pubsub"; @@ -18,7 +17,6 @@ import { ChannelManager } from "./managers/channel-manager"; import { EmoteManager } from "./managers/emote-manager"; import { CurrentUser } from "./models/current-user.svelte"; import { settings } from "./settings"; -import { SevenTvCosmetics } from "./seventv"; import { SplitController } from "./splits/controller.svelte"; import { firstLeaf } from "./splits/tree"; import { storage } from "./stores"; @@ -57,7 +55,6 @@ class App { * Provider-specific global emotes. */ public readonly emotes = new EmoteManager(); - public readonly cosmetics = new SevenTvCosmetics(); /** * Provider-specific global badges. @@ -333,18 +330,9 @@ class App { }); }); - const seventv = new IpcChannel(async (message) => { - await dispatch( - "seventv", - message.type, - "object" in message.body ? message.body.object : message.body, - ); - }); - await Promise.all([ invoke("connect_irc", { channel: irc }), invoke("connect_pubsub", { channel: pubsub }), - invoke("connect_seventv", { channel: seventv }), ]); this.#connected = true; @@ -367,7 +355,6 @@ class App { this.channels.clear(); this.emotes.clear(); - this.cosmetics.clear(); this.badges.clear(); } diff --git a/src/lib/commands/built-in/reload-badges.ts b/src/lib/commands/built-in/reload-badges.ts index f447e804..987d0616 100644 --- a/src/lib/commands/built-in/reload-badges.ts +++ b/src/lib/commands/built-in/reload-badges.ts @@ -1,13 +1,8 @@ import { app } from "#lib/app.svelte.js"; import { CommandError } from "#lib/errors/command-error.js"; -import { BADGE_PROVIDERS, type BadgeProvider } from "#lib/managers/badge-manager.js"; import { command } from "../define"; -function isProvider(name: string): name is BadgeProvider { - return (BADGE_PROVIDERS as readonly string[]).includes(name); -} - export default command({ name: "reload-badges", description: @@ -20,21 +15,19 @@ export default command({ }, ], async exec(args, channel) { + const providers = app.badges.providers; const names = args.providers?.toLowerCase().split(",").filter(Boolean) ?? []; - const unknown = names.filter((name) => name !== "all" && !isProvider(name)); + const unknown = names.filter((name) => name !== "all" && !providers.includes(name)); if (unknown.length) { - const valid = [...BADGE_PROVIDERS, "all"].join(", "); + const valid = [...providers, "all"].join(", "); throw new CommandError(`Unknown badge provider: ${unknown.join(", ")}. Use ${valid}.`); } await Promise.all([ channel.badges.fetch(true), - app.badges.fetch( - names.includes("all") ? BADGE_PROVIDERS : names.filter(isProvider), - true, - ), + app.badges.fetch(names.includes("all") ? providers : names, true), ]); channel.chat.notice("Reloaded badges."); diff --git a/src/lib/components/emote-picker/EmotePicker.svelte b/src/lib/components/emote-picker/EmotePicker.svelte index c1140c49..5640f344 100644 --- a/src/lib/components/emote-picker/EmotePicker.svelte +++ b/src/lib/components/emote-picker/EmotePicker.svelte @@ -1,10 +1,13 @@ -{#if target.type === "emote"} - {#await fetchEmote(target.id) then emote} - {#if emote} - {#snippet emoteMedia()} -
- {emote.displayName} -
- - {#if !emote.listed && blurred} - - {/if} - {/snippet} - - {#snippet emoteBody()} -
- - {emote.displayName} - - - {#if !emote.listed} - - unlisted - - {/if} -
- - {#snippet emoteMeta()} - - by {emote.owner?.mainConnection?.platformDisplayName ?? "Unknown"} - - {/snippet} - - {@render meta(emoteMeta)} - {/snippet} - - {@render card(url.href, emote.displayName, emoteMedia, emoteBody)} - {/if} - {/await} +{#if target.type === "plugin"} + {:else if target.type === "spotify"}
+ {@render clipBody()} + {/if} {/await} {/if} -{#snippet card(href: string, label: string, media: Snippet, body: Snippet)} -
- - -
- {@render media()} -
- -
- {@render body()} -
-
-{/snippet} - {#snippet meta(children: Snippet)}
{@render children()} diff --git a/src/lib/components/message/EmbedCard.svelte b/src/lib/components/message/EmbedCard.svelte new file mode 100644 index 00000000..39ee3950 --- /dev/null +++ b/src/lib/components/message/EmbedCard.svelte @@ -0,0 +1,23 @@ + + +
+ + +
+ {@render media()} +
+ +
+ {@render children()} +
+
diff --git a/src/lib/components/message/Event.svelte b/src/lib/components/message/Event.svelte index 75a3946b..bbaae094 100644 --- a/src/lib/components/message/Event.svelte +++ b/src/lib/components/message/Event.svelte @@ -7,8 +7,6 @@ import BlockStatus from "./events/BlockStatus.svelte"; import Clear from "./events/Clear.svelte"; import Delete from "./events/Delete.svelte"; - import EmoteSetChange from "./events/EmoteSetChange.svelte"; - import EmoteSetUpdate from "./events/EmoteSetUpdate.svelte"; import Join from "./events/Join.svelte"; import Mode from "./events/Mode.svelte"; import Notice from "./events/Notice.svelte"; @@ -31,8 +29,6 @@ [BlockStatus, "block-status"], [Clear, "clear"], [Delete, "delete"], - [EmoteSetChange, "emote-set-change"], - [EmoteSetUpdate, "emote-set-update"], [Join, "join"], [Mode, "mode"], [Notice, "notice"], @@ -68,7 +64,8 @@
diff --git a/src/lib/components/message/events/EmoteSetUpdate.svelte b/src/lib/components/message/events/EmoteSetUpdate.svelte deleted file mode 100644 index fdfcd3d2..00000000 --- a/src/lib/components/message/events/EmoteSetUpdate.svelte +++ /dev/null @@ -1,28 +0,0 @@ - - - - -{#if action === "renamed"} - renamed {oldName} to - {emote.displayName} -{:else} - {action} an emote: - {emote.displayName} -{/if} - - diff --git a/src/lib/components/settings/FieldControl.svelte b/src/lib/components/settings/FieldControl.svelte index 78a68105..aaad54c1 100644 --- a/src/lib/components/settings/FieldControl.svelte +++ b/src/lib/components/settings/FieldControl.svelte @@ -9,7 +9,9 @@ import Slider from "#lib/components/ui/Slider.svelte"; import Switch from "#lib/components/ui/Switch.svelte"; import { settings } from "#lib/settings.js"; + import { parseMarkdown } from "#lib/util/index.js"; + import PluginCard from "./custom/plugins/PluginCard.svelte"; import FieldControl from "./FieldControl.svelte"; interface Props { @@ -17,25 +19,8 @@ } const { field }: Props = $props(); - - // Descriptions use a small subset of Markdown: inline code, links, bold, - // and italics. - function parseDescription(description: string) { - return description - .replace(/`([^`]+)`/g, "$1") - .replace( - /\[([^\]]+)\]\(([^)]+)\)/g, - '$1', - ) - .replace(/(\*\*)(.*?)\1/g, "$2") - .replace(/(\*)(.*?)\1/g, "$2"); - } -{#snippet markdown(text: string)} - {@html parseDescription(text)} -{/snippet} - {#if field.type === "group"}
{#each field.fields as subField (subField)} @@ -45,13 +30,15 @@ {:else} {#snippet description()} {#if field.description} - {@render markdown(field.description)} + {@html parseMarkdown(field.description)} {/if} {/snippet} {@const described = field.description ? description : undefined} - {#if field.type === "custom"} + {#if field.type === "plugin"} + + {:else if field.type === "custom"}
@@ -75,7 +62,9 @@ > {#each field.items as option (option.value)} {#snippet optionDescription()} - {#if option.description}{@render markdown(option.description)}{/if} + {#if option.description} + {@html parseMarkdown(option.description)} + {/if} {/snippet} {#each results as category (category.label)} - + {/each} diff --git a/src/lib/components/settings/custom/plugins/PluginCard.svelte b/src/lib/components/settings/custom/plugins/PluginCard.svelte new file mode 100644 index 00000000..c6c48061 --- /dev/null +++ b/src/lib/components/settings/custom/plugins/PluginCard.svelte @@ -0,0 +1,80 @@ + + +
+
+
+
+ +
+
+

+ {manifest.name} +

+ + + v{manifest.version} + +
+ +

+ {@html parseMarkdown(manifest.description)} +

+
+ + +
+ + {#if count > 0} +
+ + {#snippet render({ props })} + + {/snippet} + +
+ + + {/if} +
diff --git a/src/lib/components/settings/custom/plugins/PluginDialog.svelte b/src/lib/components/settings/custom/plugins/PluginDialog.svelte new file mode 100644 index 00000000..886f0bc2 --- /dev/null +++ b/src/lib/components/settings/custom/plugins/PluginDialog.svelte @@ -0,0 +1,57 @@ + + + + {#snippet header()} +
+ {manifest.name} + + v{manifest.version} +
+ + + {@html parseMarkdown(manifest.description)} + + {/snippet} + + {#if !enabled} +

+ Turn on {manifest.name} to change its settings. +

+ {/if} + +
+ {#each field.fields as subField (subField)} + + {/each} +
+ + {#snippet footer()} + + {#snippet render({ props })} + + {/snippet} + + {/snippet} +
diff --git a/src/lib/components/settings/schema/categories/chat.ts b/src/lib/components/settings/schema/categories/chat.ts index c622e4f7..62b2d6aa 100644 --- a/src/lib/components/settings/schema/categories/chat.ts +++ b/src/lib/components/settings/schema/categories/chat.ts @@ -38,30 +38,6 @@ export default { }, ], }, - { - type: "group", - label: "Badges", - fields: [ - { - id: "chat.badges.ffz", - type: "switch", - label: "Enable FrankerFaceZ badges", - description: "Show badges from [FrankerFaceZ](https://www.frankerfacez.com/).", - }, - { - id: "chat.badges.bttv", - type: "switch", - label: "Enable BetterTTV badges", - description: "Show badges from [BetterTTV](https://betterttv.com/).", - }, - { - id: "chat.badges.seventv", - type: "switch", - label: "Enable 7TV badges", - description: "Show badges from [7TV](https://7tv.app/).", - }, - ], - }, { type: "group", label: "Usernames", @@ -78,7 +54,7 @@ export default { type: "switch", label: "Readable name colors", description: - "Lightens or darkens the color of usernames based on the current theme. This does not apply to 7TV paints.", + "Lightens or darkens the color of usernames based on the current theme. This does not apply to paints from plugins such as 7TV.", }, { id: "chat.usernames.randomColor", @@ -87,18 +63,12 @@ export default { description: "Assign a random Twitch color to usernames that do not have a color set.", }, - { - id: "chat.usernames.paint", - type: "switch", - label: "Paint usernames", - description: "Style usernames with 7TV paints if the user has one.", - }, { id: "chat.usernames.mentionStyle", type: "radio", label: "Mention style", description: - "Choose how mentions in messages are displayed. Painted mentions will fallback to the user's color if they have no 7TV paint.", + "Choose how mentions in messages are displayed. Painted mentions use paints from plugins such as 7TV, and fall back to the user's color if they have none.", items: [ { label: "None", value: "none" }, { label: "Colored", value: "colored" }, @@ -111,26 +81,6 @@ export default { type: "group", label: "Emotes", fields: [ - { - id: "chat.emotes.ffz", - type: "switch", - label: "Enable FrankerFaceZ emotes", - description: - "Show and autocomplete emotes from [FrankerFaceZ](https://www.frankerfacez.com/).", - }, - { - id: "chat.emotes.bttv", - type: "switch", - label: "Enable BetterTTV emotes", - description: - "Show and autocomplete emotes from [BetterTTV](https://betterttv.com/).", - }, - { - id: "chat.emotes.seventv", - type: "switch", - label: "Enable 7TV emotes", - description: "Show and autocomplete emotes from [7TV](https://7tv.app/).", - }, { id: "chat.emotes.padding", type: "slider", diff --git a/src/lib/components/settings/schema/categories/plugins.ts b/src/lib/components/settings/schema/categories/plugins.ts new file mode 100644 index 00000000..1038629f --- /dev/null +++ b/src/lib/components/settings/schema/categories/plugins.ts @@ -0,0 +1,73 @@ +import type { PluginSetting } from "@usehyperion/plugin"; + +import type { InstalledPlugin } from "#lib/plugins/internal.js"; + +import { IconPlugins } from "#lib/icons.js"; +import { isPluginEnabled } from "#lib/plugins/host.svelte.js"; +import { plugins } from "#lib/plugins/internal.js"; +import { enabledKey, settingKey } from "#lib/plugins/settings.js"; + +import type { SettingsCategory, SettingsField } from "../types"; + +function toField(plugin: InstalledPlugin, key: string, setting: PluginSetting): SettingsField { + const base = { + id: settingKey(plugin.manifest.id, key), + label: setting.label, + description: setting.description, + keywords: setting.keywords, + disabled: () => !isPluginEnabled(plugin), + }; + + switch (setting.type) { + case "switch": + return { + ...base, + type: "switch", + }; + case "input": + return { + ...base, + type: "input", + placeholder: setting.placeholder, + }; + case "radio": + case "select": + return { + ...base, + type: setting.type, + items: setting.items, + }; + } + + return { + ...base, + type: "slider", + min: setting.min, + max: setting.max, + step: setting.step, + showSteps: setting.showSteps, + formatValue: setting.formatValue, + }; +} + +export default { + order: 50, + label: "Plugins", + icon: IconPlugins, + fields: [ + { + type: "group", + fields: plugins.map((plugin) => ({ + id: enabledKey(plugin.manifest.id), + type: "plugin", + label: plugin.manifest.name, + description: plugin.manifest.description, + keywords: ["plugin", plugin.manifest.id], + plugin, + fields: Object.entries(plugin.settings).map(([key, setting]) => + toField(plugin, key, setting), + ), + })), + }, + ], +} satisfies SettingsCategory; diff --git a/src/lib/components/settings/schema/search.ts b/src/lib/components/settings/schema/search.ts index d1bba80f..1056b13f 100644 --- a/src/lib/components/settings/schema/search.ts +++ b/src/lib/components/settings/schema/search.ts @@ -21,6 +21,10 @@ function fieldText(field: SettingsField): string { parts.push(item.label, item.description ?? ""); } } + + if (field.type === "plugin") { + parts.push(...field.fields.map(fieldText)); + } } return parts.join(" ").toLowerCase(); diff --git a/src/lib/components/settings/schema/types.ts b/src/lib/components/settings/schema/types.ts index 21b4a385..7ffa8a26 100644 --- a/src/lib/components/settings/schema/types.ts +++ b/src/lib/components/settings/schema/types.ts @@ -1,5 +1,7 @@ import type { Component } from "svelte"; +import type { InstalledPlugin } from "#lib/plugins/internal.js"; +import type { PluginSettingKey } from "#lib/plugins/settings.js"; import type { Settings } from "#lib/settings.js"; type SettingKey = keyof Settings; @@ -37,6 +39,12 @@ interface CustomField extends BaseField { component: Component; } +export interface PluginField extends BaseField { + type: "plugin"; + plugin: InstalledPlugin; + fields: SettingsField[]; +} + interface InputField extends BaseField> { type: "input"; placeholder?: string; @@ -76,6 +84,7 @@ interface SwitchField extends BaseField> { export type SettingsField = | GroupField | CustomField + | PluginField | InputField | ChoiceField | SliderField diff --git a/src/lib/components/user/Username.svelte b/src/lib/components/user/Username.svelte index 8df7d229..e1ad22cd 100644 --- a/src/lib/components/user/Username.svelte +++ b/src/lib/components/user/Username.svelte @@ -1,5 +1,5 @@