@letsmoe/otter-sdk 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +185 -2
  2. package/package.json +40 -4
  3. package/src/aes-gcm.ts +189 -0
  4. package/src/browser.ts +39 -0
  5. package/src/client.ts +23 -0
  6. package/src/context.ts +87 -0
  7. package/src/definition.ts +104 -0
  8. package/src/errors.ts +85 -0
  9. package/src/extract.ts +134 -0
  10. package/src/generated/index.ts +79 -0
  11. package/src/generated/runtime/batcher.ts +275 -0
  12. package/src/generated/runtime/createClient.ts +68 -0
  13. package/src/generated/runtime/error.ts +29 -0
  14. package/src/generated/runtime/fetcher.ts +97 -0
  15. package/src/generated/runtime/generateGraphqlOperation.ts +225 -0
  16. package/src/generated/runtime/index.ts +13 -0
  17. package/src/generated/runtime/linkTypeMap.ts +156 -0
  18. package/src/generated/runtime/typeSelection.ts +95 -0
  19. package/src/generated/runtime/types.ts +69 -0
  20. package/src/generated/schema.graphql +838 -0
  21. package/src/generated/schema.ts +1611 -0
  22. package/src/generated/types.ts +1744 -0
  23. package/src/hosters/dead-link.ts +55 -0
  24. package/src/hosters/dood.ts +69 -0
  25. package/src/hosters/filemoon.ts +152 -0
  26. package/src/hosters/generic.ts +63 -0
  27. package/src/hosters/index.ts +14 -0
  28. package/src/hosters/recaptcha.ts +61 -0
  29. package/src/hosters/registry.ts +74 -0
  30. package/src/hosters/streamtape.ts +63 -0
  31. package/src/hosters/vidara.ts +48 -0
  32. package/src/hosters/vinovo.ts +55 -0
  33. package/src/hosters/voe-decoding.ts +131 -0
  34. package/src/hosters/voe-domains.ts +39 -0
  35. package/src/hosters/voe.ts +95 -0
  36. package/src/http-client.ts +295 -0
  37. package/src/http.ts +97 -0
  38. package/src/index.ts +10 -0
  39. package/src/languages.ts +73 -0
  40. package/src/match.ts +120 -0
  41. package/src/model.ts +110 -0
  42. package/src/packer.ts +106 -0
  43. package/src/plugin.ts +4 -0
  44. package/src/run.ts +88 -0
  45. package/src/runtime.ts +274 -0
  46. package/src/testing.ts +123 -0
  47. package/src/timing.ts +11 -0
  48. package/src/types.ts +148 -0
  49. package/src/url.ts +60 -0
package/src/runtime.ts ADDED
@@ -0,0 +1,274 @@
1
+ // Bridges a v2 plugin definition and the v1 wire protocol the backend speaks.
2
+
3
+ import { createContext, type ContextOptions } from "./context.ts";
4
+ import type { PluginContext, PluginDefinition } from "./definition.ts";
5
+ import { domainOf } from "./http.ts";
6
+ import type {
7
+ EpisodeRef,
8
+ List,
9
+ MediaRef,
10
+ MovieRef,
11
+ SeriesRef,
12
+ Source,
13
+ SourceInput,
14
+ SourceRetrieveParams,
15
+ Stream,
16
+ StreamInput,
17
+ StreamListParams,
18
+ Subtitle,
19
+ SubtitleInput,
20
+ SubtitleListParams,
21
+ } from "./model.ts";
22
+ import { normalize } from "./match.ts";
23
+ import { resolveWithTiming } from "./timing.ts";
24
+ import type {
25
+ Capability,
26
+ Download,
27
+ LoginArgs,
28
+ LoginResult,
29
+ PluginMeta,
30
+ ResolveResult,
31
+ StreamsArgs,
32
+ StreamsResult,
33
+ SubtitleFile,
34
+ SubtitlesArgs,
35
+ SubtitlesResult,
36
+ } from "./types.ts";
37
+
38
+ export interface PluginHandlers {
39
+ meta: PluginMeta;
40
+ /** Locates a TMDB-known movie or episode on the site and lists its links. */
41
+ streams?: (args: StreamsArgs) => Promise<StreamsResult>;
42
+ /** Turns a hoster link into a playable media URL. */
43
+ resolve?: (url: string) => Promise<ResolveResult>;
44
+ /** Lists caption files for a TMDB-known movie or episode. */
45
+ subtitles?: (args: SubtitlesArgs) => Promise<SubtitlesResult>;
46
+ /** Logs in to the site and returns a session. */
47
+ login?: (credentials: LoginArgs) => Promise<LoginResult>;
48
+ }
49
+
50
+ export function isPluginDefinition(plugin: PluginHandlers | PluginDefinition): plugin is PluginDefinition {
51
+ return !("meta" in plugin);
52
+ }
53
+
54
+ // ---- meta ------------------------------------------------------------------
55
+
56
+ function capabilitiesOf(definition: PluginDefinition): Capability[] {
57
+ const capabilities: Capability[] = [];
58
+ if (definition.streams) capabilities.push("streams");
59
+ if (definition.sources) capabilities.push("resolve");
60
+ if (definition.subtitles) capabilities.push("subtitles");
61
+ if (definition.account) capabilities.push("login");
62
+ return capabilities;
63
+ }
64
+
65
+ function accountRequirementOf(definition: PluginDefinition): PluginMeta["account"] {
66
+ if (!definition.account) return undefined;
67
+ return { signup_url: definition.account.signup_url };
68
+ }
69
+
70
+ function domainsOf(definition: PluginDefinition): string[] | undefined {
71
+ if (!definition.sources) return undefined;
72
+ const domains = [...definition.sources.domains];
73
+ if (definition.sources.fallback) domains.push("*");
74
+ return domains;
75
+ }
76
+
77
+ export function metaOf(definition: PluginDefinition): PluginMeta {
78
+ return {
79
+ name: definition.id,
80
+ display_name: definition.name,
81
+ description: definition.description,
82
+ icon: definition.icon,
83
+ version: definition.version,
84
+ capabilities: capabilitiesOf(definition),
85
+ domains: domainsOf(definition),
86
+ settings: definition.settings,
87
+ requires_solver: definition.requires_solver,
88
+ base_url: definition.base_url,
89
+ languages: definition.languages,
90
+ media: definition.media,
91
+ account: accountRequirementOf(definition),
92
+ };
93
+ }
94
+
95
+ // ---- params ----------------------------------------------------------------
96
+
97
+ /** "603" if the TMDB id is known, else the IMDb id, else the normalized title. */
98
+ function identityPart(args: StreamsArgs): string {
99
+ if (args.tmdb_id) return String(args.tmdb_id);
100
+ if (args.imdb_id) return args.imdb_id;
101
+ return normalize(args.title).replace(/ /g, "-");
102
+ }
103
+
104
+ function movieRefOf(args: StreamsArgs): MovieRef {
105
+ return {
106
+ object: "movie",
107
+ id: `movie:${identityPart(args)}`,
108
+ title: args.title,
109
+ original_title: args.original_title,
110
+ year: args.year,
111
+ tmdb_id: args.tmdb_id,
112
+ imdb_id: args.imdb_id,
113
+ };
114
+ }
115
+
116
+ function seriesRefOf(args: StreamsArgs): SeriesRef {
117
+ return {
118
+ object: "series",
119
+ id: `series:${identityPart(args)}`,
120
+ title: args.title,
121
+ original_title: args.original_title,
122
+ year: args.year,
123
+ tmdb_id: args.tmdb_id,
124
+ imdb_id: args.imdb_id,
125
+ };
126
+ }
127
+
128
+ function episodeRefOf(args: StreamsArgs): EpisodeRef {
129
+ const seasonNumber = args.season_number || 0;
130
+ const episodeNumber = args.episode_number || 0;
131
+ return {
132
+ object: "episode",
133
+ id: `episode:${identityPart(args)}:${seasonNumber}:${episodeNumber}`,
134
+ series: seriesRefOf(args),
135
+ season_number: seasonNumber,
136
+ episode_number: episodeNumber,
137
+ };
138
+ }
139
+
140
+ /** The backend's StreamsArgs describe an episode by its series; this turns them into the v2 media ref. */
141
+ export function toStreamListParams(args: StreamsArgs): StreamListParams {
142
+ let media: MediaRef = movieRefOf(args);
143
+ if (args.media_type === "episode") media = episodeRefOf(args);
144
+ return { media };
145
+ }
146
+
147
+ export function toSubtitleListParams(args: SubtitlesArgs): SubtitleListParams {
148
+ return { media: toStreamListParams(args).media, languages: args.languages || [] };
149
+ }
150
+
151
+ // ---- results ---------------------------------------------------------------
152
+
153
+ function labelOf(input: StreamInput, ctx: PluginContext): string {
154
+ if (input.label) return input.label;
155
+ const hosterName = ctx.hosters.nameOf(input.url);
156
+ if (hosterName) return hosterName;
157
+ return domainOf(input.url) || "Stream";
158
+ }
159
+
160
+ export function completeStream(input: StreamInput, ctx: PluginContext): Stream {
161
+ return { ...input, object: "stream", label: labelOf(input, ctx), language: languageOf(input, ctx) };
162
+ }
163
+
164
+ /** A site with a single declared language serves its links in it, unless the link says otherwise. */
165
+ function languageOf(input: StreamInput, ctx: PluginContext): string | undefined {
166
+ if (input.language) return input.language;
167
+ if (ctx.plugin.languages.length !== 1) return undefined;
168
+ return ctx.plugin.languages[0];
169
+ }
170
+
171
+ export function toDownload(stream: Stream): Download {
172
+ return {
173
+ label: stream.label,
174
+ url: stream.url,
175
+ quality: stream.quality,
176
+ language: stream.language,
177
+ format: stream.format,
178
+ size_bytes: stream.size_bytes,
179
+ };
180
+ }
181
+
182
+ export function completeSubtitle(input: SubtitleInput): Subtitle {
183
+ return { ...input, object: "subtitle", format: input.format || "srt" };
184
+ }
185
+
186
+ export function toSubtitleFile(subtitle: Subtitle): SubtitleFile {
187
+ return {
188
+ url: subtitle.url,
189
+ language: subtitle.language,
190
+ format: subtitle.format,
191
+ label: subtitle.label,
192
+ release: subtitle.release,
193
+ hearing_impaired: subtitle.hearing_impaired,
194
+ headers: subtitle.headers,
195
+ };
196
+ }
197
+
198
+ export function completeSource(input: SourceInput): Source {
199
+ return { ...input, object: "source" };
200
+ }
201
+
202
+ export function toResolveResult(source: Source): ResolveResult {
203
+ return {
204
+ url: source.url,
205
+ mime_type: source.mime_type,
206
+ headers: source.headers,
207
+ quality: source.quality,
208
+ };
209
+ }
210
+
211
+ // ---- running ---------------------------------------------------------------
212
+
213
+ /** A definition's capabilities, run with a real context. */
214
+ export class PluginRuntime {
215
+ readonly ctx: PluginContext;
216
+
217
+ constructor(
218
+ private readonly definition: PluginDefinition,
219
+ options: ContextOptions = {},
220
+ ) {
221
+ this.ctx = createContext(definition, options);
222
+ }
223
+
224
+ async listStreams(params: StreamListParams): Promise<List<Stream>> {
225
+ const capability = this.definition.streams;
226
+ if (!capability) throw new Error("streams not implemented");
227
+ const result = await capability.list(params, this.ctx);
228
+ return this.ctx.list(result.data.map((input) => completeStream(input, this.ctx)));
229
+ }
230
+
231
+ async listSubtitles(params: SubtitleListParams): Promise<List<Subtitle>> {
232
+ const capability = this.definition.subtitles;
233
+ if (!capability) throw new Error("subtitles not implemented");
234
+ const result = await capability.list(params, this.ctx);
235
+ return this.ctx.list(result.data.map(completeSubtitle));
236
+ }
237
+
238
+ async retrieveSource(params: SourceRetrieveParams): Promise<Source> {
239
+ const capability = this.definition.sources;
240
+ if (!capability) throw new Error("resolve not implemented");
241
+ return completeSource(await capability.retrieve(params, this.ctx));
242
+ }
243
+
244
+ async login(credentials: LoginArgs): Promise<LoginResult> {
245
+ const capability = this.definition.account;
246
+ if (!capability) throw new Error("login not implemented");
247
+ return capability.login(credentials, this.ctx);
248
+ }
249
+ }
250
+
251
+ /** The v1 handlers of a v2 definition, so one dispatcher serves both kinds of plugin. */
252
+ export function handlersOf(definition: PluginDefinition, options: ContextOptions = {}): PluginHandlers {
253
+ const runtime = new PluginRuntime(definition, options);
254
+ const handlers: PluginHandlers = { meta: metaOf(definition) };
255
+ if (definition.streams) {
256
+ handlers.streams = async (args) => {
257
+ const list = await runtime.listStreams(toStreamListParams(args));
258
+ return { downloads: list.data.map(toDownload) };
259
+ };
260
+ }
261
+ if (definition.subtitles) {
262
+ handlers.subtitles = async (args) => {
263
+ const list = await runtime.listSubtitles(toSubtitleListParams(args));
264
+ return { subtitles: list.data.map(toSubtitleFile) };
265
+ };
266
+ }
267
+ if (definition.sources) {
268
+ handlers.resolve = (url) => resolveWithTiming(async () => toResolveResult(await runtime.retrieveSource({ url })));
269
+ }
270
+ if (definition.account) {
271
+ handlers.login = (credentials) => runtime.login(credentials);
272
+ }
273
+ return handlers;
274
+ }
package/src/testing.ts ADDED
@@ -0,0 +1,123 @@
1
+ // Helpers for testing plugins without a network: `testPlugin` runs a
2
+ // definition's handlers with a real context, `fixtures` serves saved pages.
3
+
4
+ import { existsSync, readFileSync } from "node:fs";
5
+ import { join } from "node:path";
6
+ import type { Browser } from "./browser.ts";
7
+ import type { PluginContext, PluginDefinition } from "./definition.ts";
8
+ import type {
9
+ EpisodeRef,
10
+ List,
11
+ MovieRef,
12
+ Source,
13
+ SourceRetrieveParams,
14
+ Stream,
15
+ StreamListParams,
16
+ Subtitle,
17
+ SubtitleListParams,
18
+ TitleFields,
19
+ } from "./model.ts";
20
+ import { PluginRuntime } from "./runtime.ts";
21
+
22
+ export interface TestPluginOptions {
23
+ /** Replaces the network, typically `fixtures(dir)`. */
24
+ fetch?: typeof fetch;
25
+ /** The plugin's env: settings values and OTTER_BASE_URL. Empty by default. */
26
+ env?: Record<string, string | undefined>;
27
+ /** Replaces the Otter app's WebView behind ctx.browser. */
28
+ browser?: Browser;
29
+ }
30
+
31
+ export interface TestPlugin {
32
+ ctx: PluginContext;
33
+ streams: { list(params: StreamListParams): Promise<List<Stream>> };
34
+ sources: { retrieve(params: SourceRetrieveParams): Promise<Source> };
35
+ subtitles: { list(params: SubtitleListParams): Promise<List<Subtitle>> };
36
+ }
37
+
38
+ /** Calls the plugin's handlers the way the backend would, and returns the completed objects. */
39
+ export function testPlugin(definition: PluginDefinition, options: TestPluginOptions = {}): TestPlugin {
40
+ const runtime = new PluginRuntime(definition, { fetch: options.fetch, env: options.env || {}, browser: options.browser });
41
+ return {
42
+ ctx: runtime.ctx,
43
+ streams: { list: (params) => runtime.listStreams(params) },
44
+ sources: { retrieve: (params) => runtime.retrieveSource(params) },
45
+ subtitles: { list: (params) => runtime.listSubtitles(params) },
46
+ };
47
+ }
48
+
49
+ function identityPart(fields: TitleFields): string {
50
+ if (fields.tmdb_id) return String(fields.tmdb_id);
51
+ return fields.title.toLowerCase().replace(/[^a-z0-9]+/g, "-");
52
+ }
53
+
54
+ /** A movie to look for: `movie({ title: "Matrix", year: 1999, tmdb_id: 603 })`. */
55
+ export function movie(fields: TitleFields): MovieRef {
56
+ return { object: "movie", id: `movie:${identityPart(fields)}`, ...fields };
57
+ }
58
+
59
+ export interface SeriesFields extends Omit<TitleFields, "title"> {
60
+ /** The series' title. */
61
+ series: string;
62
+ }
63
+
64
+ /** An episode to look for: `episode({ series: "Dark", tmdb_id: 70523 }, 1, 2)`. */
65
+ export function episode(fields: SeriesFields, seasonNumber: number, episodeNumber: number): EpisodeRef {
66
+ const { series, ...rest } = fields;
67
+ const seriesFields: TitleFields = { title: series, ...rest };
68
+ return {
69
+ object: "episode",
70
+ id: `episode:${identityPart(seriesFields)}:${seasonNumber}:${episodeNumber}`,
71
+ series: { object: "series", id: `series:${identityPart(seriesFields)}`, ...seriesFields },
72
+ season_number: seasonNumber,
73
+ episode_number: episodeNumber,
74
+ };
75
+ }
76
+
77
+ const FIXTURE_EXTENSIONS = ["", ".html", ".json", ".js", ".txt"];
78
+
79
+ /** Maps `https://s.to/serie/dark?x=1` to `s.to_serie_dark_x_1`: host, path and query with every other character as "_". */
80
+ export function fixtureName(url: string, includeQuery: boolean): string {
81
+ const parsed = new URL(url);
82
+ let name = parsed.host + parsed.pathname;
83
+ if (includeQuery) name += parsed.search;
84
+ return name.replace(/[^A-Za-z0-9.-]+/g, "_").replace(/_+$/, "");
85
+ }
86
+
87
+ function findFixtureFile(directory: string, url: string, method: string): string | undefined {
88
+ const prefix = method === "GET" ? "" : `${method.toLowerCase()}.`;
89
+ const names = [fixtureName(url, true), fixtureName(url, false)];
90
+ for (const name of names) {
91
+ for (const extension of FIXTURE_EXTENSIONS) {
92
+ const path = join(directory, prefix + name + extension);
93
+ if (existsSync(path)) return path;
94
+ }
95
+ }
96
+ return undefined;
97
+ }
98
+
99
+ function contentTypeOf(path: string): string {
100
+ if (path.endsWith(".json")) return "application/json";
101
+ return "text/html";
102
+ }
103
+
104
+ /**
105
+ * A fetch replacement serving saved files. A request maps to the file named
106
+ * after its URL (see `fixtureName`), looked up first with the query string, then
107
+ * without, with or without an .html/.json/.js/.txt extension. Non-GET requests
108
+ * look for the same name prefixed with the lowercase method ("post."). Anything
109
+ * else answers 404.
110
+ */
111
+ export function fixtures(directory: string): typeof fetch {
112
+ return (async (input: RequestInfo | URL, init?: RequestInit) => {
113
+ const url = String(input);
114
+ const method = (init?.method || "GET").toUpperCase();
115
+ const path = findFixtureFile(directory, url, method);
116
+ if (!path) {
117
+ console.error(`fixtures: nothing for ${method} ${url}; expected ${fixtureName(url, true)} in ${directory}`);
118
+ return new Response("fixture not found", { status: 404 });
119
+ }
120
+ const headers = { "content-type": contentTypeOf(path) };
121
+ return new Response(readFileSync(path), { status: 200, headers });
122
+ }) as typeof fetch;
123
+ }
package/src/timing.ts ADDED
@@ -0,0 +1,11 @@
1
+ import type { ResolveResult } from "./types.ts";
2
+
3
+ /**
4
+ * Resolves a link and adds how long that took. Whether the media really plays
5
+ * and how fast is measured by the backend, which probes the actual segments.
6
+ */
7
+ export async function resolveWithTiming(resolve: () => Promise<ResolveResult>): Promise<ResolveResult> {
8
+ const startedAt = Date.now();
9
+ const result = await resolve();
10
+ return { ...result, load_time_ms: Date.now() - startedAt };
11
+ }
package/src/types.ts ADDED
@@ -0,0 +1,148 @@
1
+ // Mirrors apps/backend/internal/plugins/types.go — keep in sync.
2
+ // All JSON field names use snake_case.
3
+ //
4
+ // Otter plugins do three things: find stream links for a title TMDB already
5
+ // identified ("streams"), turn a hoster link into a playable media URL
6
+ // ("resolve"), and find subtitle files for a title ("subtitles"). Plugins
7
+ // whose site needs an account also log in ("login").
8
+
9
+ export type Capability = "meta" | "streams" | "resolve" | "subtitles" | "login";
10
+
11
+ /** The site needs the user's account. */
12
+ export interface AccountRequirement {
13
+ /** Where users without an account can make one. */
14
+ signup_url?: string;
15
+ }
16
+
17
+ /** Passed to the login capability: the user's credentials for the site. */
18
+ export interface LoginArgs {
19
+ username: string;
20
+ password: string;
21
+ }
22
+
23
+ /** An opaque session (e.g. the site's cookies) the plugin gets back with every later call. */
24
+ export interface LoginResult {
25
+ session: string;
26
+ /** RFC 3339; omitted when unknown. */
27
+ expires_at?: string;
28
+ }
29
+
30
+ /** Env vars through which a plugin with an account receives it on every call. */
31
+ export const ACCOUNT_USERNAME_ENV_KEY = "OTTER_ACCOUNT_USERNAME";
32
+ export const ACCOUNT_SESSION_ENV_KEY = "OTTER_ACCOUNT_SESSION";
33
+
34
+ export type MediaType = "movie" | "series" | "episode";
35
+
36
+ export interface PluginSettingField {
37
+ key: string;
38
+ label: string;
39
+ description?: string;
40
+ type: "string" | "password" | "boolean" | "number";
41
+ required?: boolean;
42
+ default?: string;
43
+ }
44
+
45
+ export interface PluginMeta {
46
+ name: string;
47
+ display_name?: string;
48
+ description?: string;
49
+ /** Emoji or URL */
50
+ icon?: string;
51
+ version: string;
52
+ capabilities: Capability[];
53
+ /** Domains this plugin handles for the resolve capability. Use "*" for wildcard. */
54
+ domains?: string[];
55
+ settings?: PluginSettingField[];
56
+ /** Site sits behind a Cloudflare challenge and only works through FlareSolverr. */
57
+ requires_solver?: boolean;
58
+ /** The site's address; the backend offers it as an editable "Domain" setting. */
59
+ base_url?: string;
60
+ languages?: string[];
61
+ media?: Array<"movie" | "episode">;
62
+ /** Set when the site only works with the user's login. */
63
+ account?: AccountRequirement;
64
+ }
65
+
66
+ /** One playable source: usually a hoster page that still needs resolving. */
67
+ export interface Download {
68
+ label: string;
69
+ url: string;
70
+ /** "4K" | "1080p" | "720p" | ... */
71
+ quality?: string;
72
+ language?: string;
73
+ /** "mkv" | "mp4" | ... */
74
+ format?: string;
75
+ size_bytes?: number;
76
+ speed_bps?: number;
77
+ }
78
+
79
+ /** Passed to the streams capability: a title already known from TMDB. */
80
+ export interface StreamsArgs {
81
+ media_type: "movie" | "episode";
82
+ title: string;
83
+ original_title?: string;
84
+ year?: number;
85
+ tmdb_id?: number;
86
+ imdb_id?: string;
87
+ season_number?: number; // episode only
88
+ episode_number?: number; // episode only
89
+ }
90
+
91
+ export interface StreamsResult {
92
+ downloads: Download[];
93
+ }
94
+
95
+ /** Passed to the subtitles capability: the title as in StreamsArgs, plus the languages wanted. */
96
+ export interface SubtitlesArgs extends StreamsArgs {
97
+ /** Preferred ISO 639-1 codes, most preferred first. */
98
+ languages?: string[];
99
+ }
100
+
101
+ /** One downloadable caption file. */
102
+ export interface SubtitleFile {
103
+ url: string;
104
+ /** ISO 639-1, e.g. "de". */
105
+ language: string;
106
+ format: "srt" | "vtt";
107
+ label?: string;
108
+ /** Release name the file was made for. */
109
+ release?: string;
110
+ hearing_impaired?: boolean;
111
+ /** Request headers the download needs. */
112
+ headers?: Record<string, string>;
113
+ }
114
+
115
+ export interface SubtitlesResult {
116
+ subtitles: SubtitleFile[];
117
+ }
118
+
119
+ export interface ResolveArgs {
120
+ url: string;
121
+ }
122
+
123
+ export interface ResolveResult {
124
+ url: string;
125
+ mime_type: "application/x-mpegURL" | "application/dash+xml" | "video/mp4" | "video/webm";
126
+ headers?: Record<string, string>;
127
+ quality?: string;
128
+ load_time_ms?: number;
129
+ speed_bps?: number;
130
+ }
131
+
132
+ // ---------------------------------------------------------------------------
133
+ // Helpers for a plugin's own site search, used to locate a title before
134
+ // listing its links. Not part of the backend protocol.
135
+
136
+ export interface DiscoveredItem {
137
+ title: string;
138
+ media_type: MediaType;
139
+ source_url: string;
140
+ external_id: string;
141
+ year?: number;
142
+ poster_path?: string;
143
+ tmdb_id?: number;
144
+ }
145
+
146
+ export interface SearchResult {
147
+ items: DiscoveredItem[];
148
+ }
package/src/url.ts ADDED
@@ -0,0 +1,60 @@
1
+ // URL helpers that behave the same under Bun and in the backend's embedded
2
+ // runtime, whose URL class drops the port from `origin` and resolves relative
3
+ // paths without a leading slash against the root.
4
+
5
+ const ABSOLUTE_URL = /^[a-z][a-z0-9+.-]*:/i;
6
+ const URL_PARTS = /^([a-z][a-z0-9+.-]*:)\/\/([^/?#]+)([^?#]*)(\?[^#]*)?/i;
7
+
8
+ interface UrlParts {
9
+ protocol: string;
10
+ origin: string;
11
+ pathname: string;
12
+ search: string;
13
+ }
14
+
15
+ function partsOf(url: string): UrlParts {
16
+ const parsed = URL_PARTS.exec(url);
17
+ if (!parsed) throw new Error(`not an absolute URL: ${url}`);
18
+ return {
19
+ protocol: parsed[1],
20
+ origin: `${parsed[1]}//${parsed[2]}`,
21
+ pathname: parsed[3] || "/",
22
+ search: parsed[4] || "",
23
+ };
24
+ }
25
+
26
+ /** "https://host:8080" of an absolute URL, port included. */
27
+ export function originOf(url: string): string {
28
+ return partsOf(url).origin;
29
+ }
30
+
31
+ /** Drops "." and ".." segments, keeping a query or fragment as is. */
32
+ function removeDotSegments(path: string): string {
33
+ const suffixStart = path.search(/[?#]/);
34
+ let pathname = path;
35
+ let suffix = "";
36
+ if (suffixStart !== -1) {
37
+ pathname = path.slice(0, suffixStart);
38
+ suffix = path.slice(suffixStart);
39
+ }
40
+ const kept: string[] = [];
41
+ for (const segment of pathname.split("/")) {
42
+ if (segment === "..") kept.pop();
43
+ else if (segment !== ".") kept.push(segment);
44
+ }
45
+ const joined = kept.join("/");
46
+ if (joined.startsWith("/")) return joined + suffix;
47
+ return "/" + joined + suffix;
48
+ }
49
+
50
+ /** Resolves a link found on `baseUrl`'s page: absolute, scheme-relative, root-relative or relative. */
51
+ export function resolveAgainst(baseUrl: string, reference: string): string {
52
+ if (ABSOLUTE_URL.test(reference)) return reference;
53
+ const base = partsOf(baseUrl);
54
+ if (reference.startsWith("//")) return base.protocol + reference;
55
+ if (reference.startsWith("/")) return base.origin + removeDotSegments(reference);
56
+ if (reference.startsWith("?")) return base.origin + base.pathname + reference;
57
+ if (reference.startsWith("#")) return base.origin + base.pathname + base.search + reference;
58
+ const directory = base.pathname.slice(0, base.pathname.lastIndexOf("/") + 1);
59
+ return base.origin + removeDotSegments(directory + reference);
60
+ }