extract-youtube 1.0.538 → 1.0.539

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 (54) hide show
  1. package/README.md +10 -4
  2. package/dist/cli-Do33ETWE.js +2024 -0
  3. package/dist/cli-Do33ETWE.js.map +1 -0
  4. package/dist/cli.js +1 -2359
  5. package/dist/download/handler.d.ts.map +1 -1
  6. package/dist/download/index.cjs.map +1 -1
  7. package/dist/download/index.mjs.map +1 -1
  8. package/dist/download/media.d.ts +1 -1
  9. package/dist/download/media.d.ts.map +1 -1
  10. package/dist/{download-B1w1a7Bx.js → download-CBVykDZQ.js} +4 -6
  11. package/dist/download-CBVykDZQ.js.map +1 -0
  12. package/dist/errors/index.d.ts.map +1 -1
  13. package/dist/fetchers/transcript-list-fetcher.d.ts.map +1 -1
  14. package/dist/formatters/index.d.ts.map +1 -1
  15. package/dist/http/fetch-http-client.d.ts +9 -2
  16. package/dist/http/fetch-http-client.d.ts.map +1 -1
  17. package/dist/index.cjs +1 -1
  18. package/dist/index.cjs.map +1 -1
  19. package/dist/index.mjs +1 -1
  20. package/dist/index.mjs.map +1 -1
  21. package/dist/library/client.d.ts.map +1 -1
  22. package/dist/library/index.cjs.map +1 -1
  23. package/dist/library/index.mjs.map +1 -1
  24. package/dist/library/types.d.ts +1 -1
  25. package/dist/library/types.d.ts.map +1 -1
  26. package/dist/library/youtube-data.d.ts.map +1 -1
  27. package/dist/models/fetched-transcript.d.ts.map +1 -1
  28. package/dist/models/transcript-list.d.ts.map +1 -1
  29. package/dist/models/transcript.d.ts.map +1 -1
  30. package/dist/parsers/transcript-parser.d.ts.map +1 -1
  31. package/dist/proxies/index.d.ts.map +1 -1
  32. package/dist/react/grid/format.d.ts.map +1 -1
  33. package/dist/react/index.cjs.map +1 -1
  34. package/dist/react/index.mjs.map +1 -1
  35. package/dist/react/player/playerStore.d.ts.map +1 -1
  36. package/dist/youtube-transcript-api.d.ts.map +1 -1
  37. package/package.json +2 -3
  38. package/src/errors/index.ts +3 -3
  39. package/src/http/fetch-http-client.ts +15 -7
  40. package/dist/archiver-web.es-6SHUi1vI.js +0 -2
  41. package/dist/archiver-web.es-6SHUi1vI.js.map +0 -1
  42. package/dist/archiver-web.es-BMOPAHYz.mjs +0 -2
  43. package/dist/archiver-web.es-BMOPAHYz.mjs.map +0 -1
  44. package/dist/archiver-web.es-D64GRoH3.js +0 -3141
  45. package/dist/archiver-web.es-D64GRoH3.js.map +0 -1
  46. package/dist/cli.js.map +0 -1
  47. package/dist/download-B1w1a7Bx.js.map +0 -1
  48. package/dist/index-CLlAnStL-CJZcZDNB.js +0 -6524
  49. package/dist/index-CLlAnStL-CJZcZDNB.js.map +0 -1
  50. package/dist/index-CLlAnStL-CTrJ2nY4.mjs +0 -2
  51. package/dist/index-CLlAnStL-CTrJ2nY4.mjs.map +0 -1
  52. package/dist/index-CLlAnStL-mkYPOznd.js +0 -2
  53. package/dist/index-CLlAnStL-mkYPOznd.js.map +0 -1
  54. package/dist/rolldown-runtime-ch10HqoO.js +0 -71
package/dist/cli.js CHANGED
@@ -1,2361 +1,3 @@
1
1
  #!/usr/bin/env node
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const require_rolldown_runtime = require("./rolldown-runtime-ch10HqoO.js");
4
- let html_entities = require("html-entities");
5
- let fast_xml_parser = require("fast-xml-parser");
6
- let https_proxy_agent = require("https-proxy-agent");
7
- //#region src/errors/index.ts
8
- var _CouldNotRetrieveTranscript;
9
- var _RequestBlocked;
10
- var YOUTUBE_WATCH_URL$1 = "https://www.youtube.com/watch?v={video_id}";
11
- /**
12
- * Base exception class for all YouTube Transcript API errors.
13
- */
14
- var YouTubeTranscriptApiException = class YouTubeTranscriptApiException extends Error {
15
- constructor(message) {
16
- super(message);
17
- this.name = "YouTubeTranscriptApiException";
18
- Object.setPrototypeOf(this, YouTubeTranscriptApiException.prototype);
19
- }
20
- };
21
- /**
22
- * Base exception class for transcript retrieval errors.
23
- */
24
- var CouldNotRetrieveTranscript = class CouldNotRetrieveTranscript extends YouTubeTranscriptApiException {
25
- constructor(videoId) {
26
- super("");
27
- this.causeMessage = "";
28
- this.videoId = videoId;
29
- Object.setPrototypeOf(this, CouldNotRetrieveTranscript.prototype);
30
- this.message = this.buildErrorMessage();
31
- }
32
- buildErrorMessage() {
33
- const videoUrl = YOUTUBE_WATCH_URL$1.replace("{video_id}", this.videoId);
34
- let errorMessage = CouldNotRetrieveTranscript.ERROR_MESSAGE.replace("{video_url}", videoUrl);
35
- const cause = this.getCause();
36
- if (cause) {
37
- errorMessage += CouldNotRetrieveTranscript.CAUSE_MESSAGE_INTRO.replace("{cause}", cause);
38
- errorMessage += CouldNotRetrieveTranscript.GITHUB_REFERRAL;
39
- }
40
- return errorMessage;
41
- }
42
- getCause() {
43
- return this.causeMessage;
44
- }
45
- };
46
- _CouldNotRetrieveTranscript = CouldNotRetrieveTranscript;
47
- _CouldNotRetrieveTranscript.ERROR_MESSAGE = "\nCould not retrieve a transcript for the video {video_url}!";
48
- _CouldNotRetrieveTranscript.CAUSE_MESSAGE_INTRO = " This is most likely caused by:\n\n{cause}";
49
- _CouldNotRetrieveTranscript.GITHUB_REFERRAL = "\n\nIf you are sure that the described cause is not responsible for this error and that a transcript should be retrievable, please create an issue at https://github.com/jdepoix/youtube-transcript-api/issues. Please add which version of youtube_transcript_api you are using and provide the information needed to replicate the error. Also make sure that there are no open issues which already describe your problem!";
50
- var YouTubeDataUnparsable = class YouTubeDataUnparsable extends CouldNotRetrieveTranscript {
51
- constructor(videoId) {
52
- super(videoId);
53
- this.causeMessage = "The data required to fetch the transcript is not parsable. This should not happen, please open an issue (make sure to include the video ID)!";
54
- this.name = "YouTubeDataUnparsable";
55
- Object.setPrototypeOf(this, YouTubeDataUnparsable.prototype);
56
- this.message = this.buildErrorMessage();
57
- }
58
- };
59
- var YouTubeRequestFailed = class YouTubeRequestFailed extends CouldNotRetrieveTranscript {
60
- constructor(videoId, httpError) {
61
- super(videoId);
62
- this.httpErrorReason = httpError.message;
63
- this.name = "YouTubeRequestFailed";
64
- this.message = this.buildErrorMessage();
65
- Object.setPrototypeOf(this, YouTubeRequestFailed.prototype);
66
- }
67
- getCause() {
68
- return `Request to YouTube failed: ${this.httpErrorReason}`;
69
- }
70
- };
71
- var VideoUnplayable = class VideoUnplayable extends CouldNotRetrieveTranscript {
72
- constructor(videoId, unplayableReason, additionalDetails) {
73
- super(videoId);
74
- this.unplayableReason = unplayableReason;
75
- this.additionalDetails = additionalDetails;
76
- this.name = "VideoUnplayable";
77
- this.message = this.buildErrorMessage();
78
- Object.setPrototypeOf(this, VideoUnplayable.prototype);
79
- }
80
- getCause() {
81
- let reason = this.unplayableReason ?? "No reason specified!";
82
- if (this.additionalDetails.length > 0) {
83
- const formattedDetails = this.additionalDetails.map((detail) => ` - ${detail}`).join("\n");
84
- reason = `${reason}\n\nAdditional Details:\n${formattedDetails}`;
85
- }
86
- return `The video is unplayable for the following reason: ${reason}`;
87
- }
88
- };
89
- var VideoUnavailable = class VideoUnavailable extends CouldNotRetrieveTranscript {
90
- constructor(videoId) {
91
- super(videoId);
92
- this.causeMessage = "The video is no longer available";
93
- this.name = "VideoUnavailable";
94
- Object.setPrototypeOf(this, VideoUnavailable.prototype);
95
- this.message = this.buildErrorMessage();
96
- }
97
- };
98
- var InvalidVideoId = class InvalidVideoId extends CouldNotRetrieveTranscript {
99
- constructor(videoId) {
100
- super(videoId);
101
- this.causeMessage = "You provided an invalid video id. Make sure you are using the video id and NOT the url!\n\nDo NOT run: `new YouTubeTranscriptApi().fetch(\"https://www.youtube.com/watch?v=1234\")`\nInstead run: `new YouTubeTranscriptApi().fetch(\"1234\")`";
102
- this.name = "InvalidVideoId";
103
- Object.setPrototypeOf(this, InvalidVideoId.prototype);
104
- this.message = this.buildErrorMessage();
105
- }
106
- };
107
- var AgeRestricted = class AgeRestricted extends CouldNotRetrieveTranscript {
108
- constructor(videoId) {
109
- super(videoId);
110
- this.causeMessage = "This video is age-restricted. Therefore, you are unable to retrieve transcripts for it without authenticating yourself.\n\nUnfortunately, Cookie Authentication is temporarily unsupported in youtube-transcript-api, as recent changes in YouTube's API broke the previous implementation. I will do my best to re-implement it as soon as possible.";
111
- this.name = "AgeRestricted";
112
- Object.setPrototypeOf(this, AgeRestricted.prototype);
113
- this.message = this.buildErrorMessage();
114
- }
115
- };
116
- var FailedToCreateConsentCookie = class FailedToCreateConsentCookie extends CouldNotRetrieveTranscript {
117
- constructor(videoId) {
118
- super(videoId);
119
- this.causeMessage = "Failed to automatically give consent to saving cookies";
120
- this.name = "FailedToCreateConsentCookie";
121
- Object.setPrototypeOf(this, FailedToCreateConsentCookie.prototype);
122
- this.message = this.buildErrorMessage();
123
- }
124
- };
125
- var TranscriptsDisabled = class TranscriptsDisabled extends CouldNotRetrieveTranscript {
126
- constructor(videoId) {
127
- super(videoId);
128
- this.causeMessage = "Subtitles are disabled for this video";
129
- this.name = "TranscriptsDisabled";
130
- Object.setPrototypeOf(this, TranscriptsDisabled.prototype);
131
- this.message = this.buildErrorMessage();
132
- }
133
- };
134
- var NotTranslatable = class NotTranslatable extends CouldNotRetrieveTranscript {
135
- constructor(videoId) {
136
- super(videoId);
137
- this.causeMessage = "The requested language is not translatable";
138
- this.name = "NotTranslatable";
139
- Object.setPrototypeOf(this, NotTranslatable.prototype);
140
- this.message = this.buildErrorMessage();
141
- }
142
- };
143
- var TranslationLanguageNotAvailable = class TranslationLanguageNotAvailable extends CouldNotRetrieveTranscript {
144
- constructor(videoId) {
145
- super(videoId);
146
- this.causeMessage = "The requested translation language is not available";
147
- this.name = "TranslationLanguageNotAvailable";
148
- Object.setPrototypeOf(this, TranslationLanguageNotAvailable.prototype);
149
- this.message = this.buildErrorMessage();
150
- }
151
- };
152
- var NoTranscriptFound = class NoTranscriptFound extends CouldNotRetrieveTranscript {
153
- constructor(videoId, requestedLanguageCodes, availableTranscriptData) {
154
- super(videoId);
155
- this.requestedLanguageCodes = requestedLanguageCodes;
156
- this.availableTranscriptData = availableTranscriptData;
157
- this.name = "NoTranscriptFound";
158
- this.message = this.buildErrorMessage();
159
- Object.setPrototypeOf(this, NoTranscriptFound.prototype);
160
- }
161
- getCause() {
162
- return `No transcripts were found for any of the requested language codes: ${this.requestedLanguageCodes.join(", ")}\n\n` + this.availableTranscriptData.toString();
163
- }
164
- };
165
- var PoTokenRequired = class PoTokenRequired extends CouldNotRetrieveTranscript {
166
- constructor(videoId) {
167
- super(videoId);
168
- this.causeMessage = "The requested video cannot be retrieved without a PO Token. If this happens, please open a GitHub issue!";
169
- this.name = "PoTokenRequired";
170
- Object.setPrototypeOf(this, PoTokenRequired.prototype);
171
- this.message = this.buildErrorMessage();
172
- }
173
- };
174
- var RequestBlocked = class RequestBlocked extends CouldNotRetrieveTranscript {
175
- constructor(videoId) {
176
- super(videoId);
177
- this.proxyConfig = null;
178
- this.name = "RequestBlocked";
179
- Object.setPrototypeOf(this, RequestBlocked.prototype);
180
- this.message = this.buildErrorMessage();
181
- }
182
- withProxyConfig(proxyConfig) {
183
- this.proxyConfig = proxyConfig;
184
- this.message = this.buildErrorMessage();
185
- return this;
186
- }
187
- getCause() {
188
- if (this.proxyConfig && this.proxyConfig.constructor.name === "WebshareProxyConfig") return RequestBlocked.WITH_WEBSHARE_PROXY_CAUSE_MESSAGE;
189
- if (this.proxyConfig && this.proxyConfig.constructor.name === "GenericProxyConfig") return RequestBlocked.WITH_GENERIC_PROXY_CAUSE_MESSAGE;
190
- return RequestBlocked.DEFAULT_CAUSE_MESSAGE;
191
- }
192
- };
193
- _RequestBlocked = RequestBlocked;
194
- _RequestBlocked.BASE_CAUSE_MESSAGE = "YouTube is blocking requests from your IP. This usually is due to one of the following reasons:\n- You have done too many requests and your IP has been blocked by YouTube\n- You are doing requests from an IP belonging to a cloud provider (like AWS, Google Cloud Platform, Azure, etc.). Unfortunately, most IPs from cloud providers are blocked by YouTube.\n\n";
195
- _RequestBlocked.DEFAULT_CAUSE_MESSAGE = _RequestBlocked.BASE_CAUSE_MESSAGE + "There are two things you can do to work around this:\n1. Use proxies to hide your IP address, as explained in the \"Working around IP bans\" section of the README (https://github.com/jdepoix/youtube-transcript-api?tab=readme-ov-file#working-around-ip-bans-requestblocked-or-ipblocked-exception).\n2. (NOT RECOMMENDED) If you authenticate your requests using cookies, you will be able to continue doing requests for a while. However, YouTube will eventually permanently ban the account that you have used to authenticate with! So only do this if you don't mind your account being banned!";
196
- _RequestBlocked.WITH_GENERIC_PROXY_CAUSE_MESSAGE = "YouTube is blocking your requests, despite you using proxies. Keep in mind that a proxy is just a way to hide your real IP behind the IP of that proxy, but there is no guarantee that the IP of that proxy won't be blocked as well.\n\nThe only truly reliable way to prevent IP blocks is rotating through a large pool of residential IPs, by using a provider like Webshare (https://www.webshare.io/?referral_code=w0xno53eb50g), which provides you with a pool of >30M residential IPs (make sure to purchase \"Residential\" proxies, NOT \"Proxy Server\" or \"Static Residential\"!).\n\nYou will find more information on how to easily integrate Webshare here: https://github.com/jdepoix/youtube-transcript-api?tab=readme-ov-file#using-webshare";
197
- _RequestBlocked.WITH_WEBSHARE_PROXY_CAUSE_MESSAGE = "YouTube is blocking your requests, despite you using Webshare proxies. Please make sure that you have purchased \"Residential\" proxies and NOT \"Proxy Server\" or \"Static Residential\", as those won't work as reliably! The free tier also uses \"Proxy Server\" and will NOT work!\n\nThe only reliable option is using \"Residential\" proxies (not \"Static Residential\"), as this allows you to rotate through a pool of over 30M IPs, which means you will always find an IP that hasn't been blocked by YouTube yet!\n\nYou can support the development of this open source project by making your Webshare purchases through this affiliate link: https://www.webshare.io/?referral_code=w0xno53eb50g \n\nThank you for your support! <3";
198
- var IpBlocked = class IpBlocked extends RequestBlocked {
199
- constructor(videoId) {
200
- super(videoId);
201
- this.causeMessage = "YouTube is blocking requests from your IP. This usually is due to one of the following reasons:\n- You have done too many requests and your IP has been blocked by YouTube\n- You are doing requests from an IP belonging to a cloud provider (like AWS, Google Cloud Platform, Azure, etc.). Unfortunately, most IPs from cloud providers are blocked by YouTube.\n\nWays to work around this are explained in the \"Working around IP bans\" section of the README (https://github.com/jdepoix/youtube-transcript-api?tab=readme-ov-file#working-around-ip-bans-requestblocked-or-ipblocked-exception).\n";
202
- this.name = "IpBlocked";
203
- Object.setPrototypeOf(this, IpBlocked.prototype);
204
- this.message = this.buildErrorMessage();
205
- }
206
- getCause() {
207
- return this.causeMessage;
208
- }
209
- };
210
- //#endregion
211
- //#region src/models/fetched-transcript.ts
212
- /**
213
- * Represents a fetched transcript with all its snippets and metadata.
214
- * This class is iterable, allowing you to iterate over transcript snippets.
215
- *
216
- * @example
217
- * ```typescript
218
- * const transcript = await api.fetch('video_id');
219
- * for (const snippet of transcript) {
220
- * console.log(snippet.text);
221
- * }
222
- * ```
223
- */
224
- var FetchedTranscript = class {
225
- /**
226
- * Creates a new FetchedTranscript instance.
227
- *
228
- * @param {FetchedTranscriptSnippet[]} snippets - Array of transcript snippets
229
- * @param {string} videoId - The video ID
230
- * @param {string} language - The language name
231
- * @param {string} languageCode - The language code
232
- * @param {boolean} isGenerated - Whether the transcript is auto-generated
233
- */
234
- constructor(snippets, videoId, language, languageCode, isGenerated) {
235
- this.snippets = snippets;
236
- this.videoId = videoId;
237
- this.language = language;
238
- this.languageCode = languageCode;
239
- this.isGenerated = isGenerated;
240
- }
241
- /**
242
- * Makes the transcript iterable, allowing for...of loops.
243
- *
244
- * @returns {Iterator<FetchedTranscriptSnippet>} Iterator over the snippets
245
- */
246
- [Symbol.iterator]() {
247
- return this.snippets[Symbol.iterator]();
248
- }
249
- /**
250
- * Gets a snippet by index.
251
- *
252
- * @param {number} index - The index of the snippet
253
- * @returns {FetchedTranscriptSnippet} The snippet at the given index
254
- */
255
- getSnippetAtIndex(index) {
256
- return this.snippets[index];
257
- }
258
- /**
259
- * Alias for getSnippetAtIndex() for backward compatibility.
260
- *
261
- * @deprecated Use getSnippetAtIndex() instead
262
- * @param {number} index - The index of the snippet
263
- * @returns {FetchedTranscriptSnippet} The snippet at the given index
264
- */
265
- get(index) {
266
- return this.getSnippetAtIndex(index);
267
- }
268
- /**
269
- * Gets the total number of snippets in the transcript.
270
- *
271
- * @returns {number} The number of snippets
272
- */
273
- get length() {
274
- return this.snippets.length;
275
- }
276
- /**
277
- * Converts the transcript to raw data format (array of objects).
278
- * This is useful for serialization or when you need plain data objects.
279
- *
280
- * @returns {Array<{text: string, start: number, duration: number}>} Raw transcript data
281
- */
282
- toRawData() {
283
- return this.snippets.map((snippet) => ({
284
- text: snippet.text,
285
- start: snippet.start,
286
- duration: snippet.duration
287
- }));
288
- }
289
- };
290
- //#endregion
291
- //#region src/parsers/transcript-parser.ts
292
- /**
293
- * @fileoverview Parser for converting YouTube transcript XML data into structured snippets
294
- */
295
- var _TranscriptParser;
296
- /**
297
- * Parses transcript XML data from YouTube into FetchedTranscriptSnippet objects.
298
- *
299
- * @example
300
- * ```typescript
301
- * const parser = new TranscriptParser(false);
302
- * const snippets = parser.parseTranscriptXml(xmlData);
303
- * ```
304
- */
305
- var TranscriptParser = class TranscriptParser {
306
- /**
307
- * Creates a new TranscriptParser instance.
308
- *
309
- * @param {boolean} [preserveFormatting=false] - Whether to preserve HTML formatting tags
310
- */
311
- constructor(preserveFormatting = false) {
312
- this.htmlRemovalRegex = this.buildHtmlRemovalRegex(preserveFormatting);
313
- }
314
- /**
315
- * Builds a regex pattern for removing HTML tags based on formatting preferences.
316
- *
317
- * @private
318
- * @param {boolean} preserveFormatting - Whether to preserve formatting tags
319
- * @returns {RegExp} The HTML removal regex
320
- */
321
- buildHtmlRemovalRegex(preserveFormatting) {
322
- if (preserveFormatting) {
323
- const pattern = `<\\/?(?!\\/?(?:${TranscriptParser.FORMATTING_TAGS.join("|")})\\b).*?\\b>`;
324
- return new RegExp(pattern, "gi");
325
- } else return /<[^>]*>/gi;
326
- }
327
- /**
328
- * Parses raw XML transcript data into an array of transcript snippets.
329
- *
330
- * @param {string} xmlData - The raw XML data from YouTube's transcript API
331
- * @returns {FetchedTranscriptSnippet[]} Array of parsed transcript snippets
332
- *
333
- * @example
334
- * ```typescript
335
- * const parser = new TranscriptParser();
336
- * const snippets = parser.parseTranscriptXml(xmlData);
337
- * for (const snippet of snippets) {
338
- * console.log(`${snippet.start}s: ${snippet.text}`);
339
- * }
340
- * ```
341
- */
342
- parseTranscriptXml(xmlData) {
343
- const textElements = new fast_xml_parser.XMLParser({
344
- ignoreAttributes: false,
345
- attributeNamePrefix: "@_"
346
- }).parse(xmlData).transcript?.text || [];
347
- return (Array.isArray(textElements) ? textElements : [textElements]).filter((element) => element["#text"]).map((element) => this.parseTranscriptSnippet(element));
348
- }
349
- /**
350
- * Parses a single XML element into a FetchedTranscriptSnippet.
351
- *
352
- * @private
353
- * @param {any} element - The XML element to parse
354
- * @returns {FetchedTranscriptSnippet} The parsed snippet
355
- */
356
- parseTranscriptSnippet(element) {
357
- return {
358
- text: this.cleanTranscriptText(element["#text"]),
359
- start: this.parseFloatAttribute(element["@_start"]),
360
- duration: this.parseFloatAttribute(element["@_dur"])
361
- };
362
- }
363
- /**
364
- * Parses a string attribute as a float, defaulting to 0 if invalid.
365
- *
366
- * @private
367
- * @param {string | undefined} value - The attribute value to parse
368
- * @returns {number} The parsed float value
369
- */
370
- parseFloatAttribute(value) {
371
- return parseFloat(value || "0");
372
- }
373
- /**
374
- * Cleans transcript text by decoding HTML entities and removing HTML tags.
375
- *
376
- * @private
377
- * @param {string} text - The raw transcript text
378
- * @returns {string} The cleaned text
379
- */
380
- cleanTranscriptText(text) {
381
- if (typeof text !== "string") text = String(text || "");
382
- return (0, html_entities.decode)(text).replace(this.htmlRemovalRegex, "");
383
- }
384
- };
385
- _TranscriptParser = TranscriptParser;
386
- _TranscriptParser.FORMATTING_TAGS = [
387
- "strong",
388
- "em",
389
- "b",
390
- "i",
391
- "mark",
392
- "small",
393
- "del",
394
- "ins",
395
- "sub",
396
- "sup"
397
- ];
398
- //#endregion
399
- //#region src/utils/http-error-handler.ts
400
- /**
401
- * @fileoverview HTTP error handling utilities for YouTube API requests
402
- */
403
- /**
404
- * Checks an HTTP response and throws appropriate errors if the request failed.
405
- *
406
- * @param {Response} response - The HTTP response to check
407
- * @param {string} videoId - The video ID associated with the request
408
- * @throws {IpBlocked} If status is 429 (Too Many Requests)
409
- * @throws {YouTubeRequestFailed} If status indicates an error
410
- *
411
- * @example
412
- * ```typescript
413
- * const response = await httpClient.get(url);
414
- * handleHttpErrors(response, videoId);
415
- * // If we reach here, the request was successful
416
- * ```
417
- */
418
- function handleHttpErrors(response, videoId) {
419
- if (response.status === 429) throw new IpBlocked(videoId);
420
- if (!response.ok) {
421
- const errorMessage = `HTTP ${response.status}: ${response.statusText}`;
422
- throw new YouTubeRequestFailed(videoId, new Error(errorMessage));
423
- }
424
- }
425
- //#endregion
426
- //#region src/models/transcript.ts
427
- /**
428
- * Represents a transcript that can be fetched or translated.
429
- * You typically obtain Transcript objects from a TranscriptList.
430
- *
431
- * @example
432
- * ```typescript
433
- * const transcriptList = await api.list('video_id');
434
- * const transcript = transcriptList.findTranscript(['en']);
435
- * const fetched = await transcript.fetch();
436
- * ```
437
- */
438
- var Transcript = class Transcript {
439
- /**
440
- * Creates a new Transcript instance.
441
- * You probably don't want to initialize this directly.
442
- * Usually you'll access Transcript objects using a TranscriptList.
443
- *
444
- * @param {HttpClient} httpClient - HTTP client for making requests
445
- * @param {string} videoId - The video ID
446
- * @param {string} transcriptUrl - The transcript URL
447
- * @param {string} language - The language name
448
- * @param {string} languageCode - The language code
449
- * @param {boolean} isGenerated - Whether the transcript is auto-generated
450
- * @param {TranslationLanguage[]} translationLanguages - Available translation languages
451
- */
452
- constructor(httpClient, videoId, transcriptUrl, language, languageCode, isGenerated, translationLanguages) {
453
- this.httpClient = httpClient;
454
- this.videoId = videoId;
455
- this.transcriptUrl = transcriptUrl;
456
- this.language = language;
457
- this.languageCode = languageCode;
458
- this.isGenerated = isGenerated;
459
- this.translationLanguages = translationLanguages;
460
- this.translationLanguagesMap = this.buildTranslationLanguagesMap(translationLanguages);
461
- }
462
- /**
463
- * Builds a map of language codes to language names for quick lookup.
464
- *
465
- * @private
466
- * @param {TranslationLanguage[]} languages - Array of translation languages
467
- * @returns {Record<string, string>} Map of language code to language name
468
- */
469
- buildTranslationLanguagesMap(languages) {
470
- const map = {};
471
- for (const lang of languages) map[lang.language_code] = lang.language;
472
- return map;
473
- }
474
- /**
475
- * Loads the actual transcript data from YouTube.
476
- *
477
- * @param {boolean} [preserveFormatting=false] - Whether to keep select HTML text formatting
478
- * @returns {Promise<FetchedTranscript>} The fetched transcript with all snippets
479
- * @throws {PoTokenRequired} If a PO Token is required for this video
480
- * @throws {YouTubeRequestFailed} If the HTTP request fails
481
- *
482
- * @example
483
- * ```typescript
484
- * const transcript = transcriptList.findTranscript(['en']);
485
- * const fetched = await transcript.fetch();
486
- *
487
- * // With formatting preserved
488
- * const fetchedWithFormatting = await transcript.fetch(true);
489
- * ```
490
- */
491
- async fetch(preserveFormatting = false) {
492
- if (this.transcriptUrl.includes("&exp=xpe")) throw new PoTokenRequired(this.videoId);
493
- const response = await this.httpClient.get(this.transcriptUrl);
494
- handleHttpErrors(response, this.videoId);
495
- const xmlData = await response.text();
496
- return new FetchedTranscript(new TranscriptParser(preserveFormatting).parseTranscriptXml(xmlData), this.videoId, this.language, this.languageCode, this.isGenerated);
497
- }
498
- /**
499
- * Checks whether this transcript can be translated to other languages.
500
- *
501
- * @returns {boolean} True if the transcript supports translation
502
- */
503
- get isTranslatable() {
504
- return this.translationLanguages.length > 0;
505
- }
506
- /**
507
- * Creates a translated version of this transcript.
508
- *
509
- * @param {string} targetLanguageCode - The target language code (e.g., 'de', 'fr')
510
- * @returns {Transcript} A new Transcript object for the translated transcript
511
- * @throws {NotTranslatable} If the transcript cannot be translated
512
- * @throws {TranslationLanguageNotAvailable} If the requested language is not available
513
- *
514
- * @example
515
- * ```typescript
516
- * const englishTranscript = transcriptList.findTranscript(['en']);
517
- * if (englishTranscript.isTranslatable) {
518
- * const germanTranscript = englishTranscript.translate('de');
519
- * const fetched = await germanTranscript.fetch();
520
- * }
521
- * ```
522
- */
523
- translate(targetLanguageCode) {
524
- if (!this.isTranslatable) throw new NotTranslatable(this.videoId);
525
- if (!(targetLanguageCode in this.translationLanguagesMap)) throw new TranslationLanguageNotAvailable(this.videoId);
526
- const translatedUrl = `${this.transcriptUrl}&tlang=${targetLanguageCode}`;
527
- const translatedLanguage = this.translationLanguagesMap[targetLanguageCode];
528
- return new Transcript(this.httpClient, this.videoId, translatedUrl, translatedLanguage, targetLanguageCode, true, []);
529
- }
530
- /**
531
- * Returns a string representation of the transcript.
532
- *
533
- * @returns {string} A formatted string representation
534
- */
535
- toString() {
536
- const translatableFlag = this.isTranslatable ? "[TRANSLATABLE]" : "";
537
- return `${this.languageCode} ("${this.language}")${translatableFlag}`;
538
- }
539
- };
540
- //#endregion
541
- //#region src/models/transcript-list.ts
542
- /**
543
- * Represents a list of available transcripts for a video.
544
- * This object is iterable and provides methods to search for specific transcripts.
545
- *
546
- * @example
547
- * ```typescript
548
- * const transcriptList = await api.list('video_id');
549
- *
550
- * // Iterate over all transcripts
551
- * for (const transcript of transcriptList) {
552
- * console.log(transcript.language, transcript.languageCode);
553
- * }
554
- *
555
- * // Find a specific transcript
556
- * const transcript = transcriptList.findTranscript(['de', 'en']);
557
- * ```
558
- */
559
- var TranscriptList = class TranscriptList {
560
- /**
561
- * Creates a new TranscriptList instance.
562
- * The constructor is only for internal use. Use the static buildFromCaptionsJson method instead.
563
- *
564
- * @param {string} videoId - The video ID
565
- * @param {Record<string, Transcript>} manuallyCreatedTranscripts - Map of manually created transcripts
566
- * @param {Record<string, Transcript>} autoGeneratedTranscripts - Map of auto-generated transcripts
567
- * @param {TranslationLanguage[]} availableTranslationLanguages - Available translation languages
568
- */
569
- constructor(videoId, manuallyCreatedTranscripts, autoGeneratedTranscripts, availableTranslationLanguages) {
570
- this.videoId = videoId;
571
- this.manuallyCreatedTranscripts = manuallyCreatedTranscripts;
572
- this.autoGeneratedTranscripts = autoGeneratedTranscripts;
573
- this.availableTranslationLanguages = availableTranslationLanguages;
574
- }
575
- /**
576
- * Factory method to build a TranscriptList from YouTube's captions JSON data.
577
- *
578
- * @param {HttpClient} httpClient - HTTP client for making requests
579
- * @param {string} videoId - The video ID
580
- * @param {CaptionsJson} captionsJson - The JSON parsed from YouTube's response
581
- * @returns {TranscriptList} The created TranscriptList
582
- */
583
- static buildFromCaptionsJson(httpClient, videoId, captionsJson) {
584
- const translationLanguages = TranscriptList.extractTranslationLanguages(captionsJson);
585
- const { manualTranscripts, generatedTranscripts } = TranscriptList.categorizeTranscripts(httpClient, videoId, captionsJson, translationLanguages);
586
- return new TranscriptList(videoId, manualTranscripts, generatedTranscripts, translationLanguages);
587
- }
588
- /**
589
- * Extracts translation languages from the captions JSON.
590
- *
591
- * @private
592
- * @param {CaptionsJson} captionsJson - The captions JSON data
593
- * @returns {TranslationLanguage[]} Array of translation languages
594
- */
595
- static extractTranslationLanguages(captionsJson) {
596
- return (captionsJson.translationLanguages || []).map((lang) => ({
597
- language: lang.languageName.runs[0].text,
598
- language_code: lang.languageCode
599
- }));
600
- }
601
- /**
602
- * Categorizes transcripts into manually created and auto-generated.
603
- *
604
- * @private
605
- * @param {HttpClient} httpClient - HTTP client for making requests
606
- * @param {string} videoId - The video ID
607
- * @param {CaptionsJson} captionsJson - The captions JSON data
608
- * @param {TranslationLanguage[]} translationLanguages - Available translation languages
609
- * @returns {{manualTranscripts: Record<string, Transcript>, generatedTranscripts: Record<string, Transcript>}}
610
- */
611
- static categorizeTranscripts(httpClient, videoId, captionsJson, translationLanguages) {
612
- const manualTranscripts = {};
613
- const generatedTranscripts = {};
614
- for (const captionTrack of captionsJson.captionTracks) {
615
- const isAutoGenerated = captionTrack.kind === "asr";
616
- const targetMap = isAutoGenerated ? generatedTranscripts : manualTranscripts;
617
- const transcript = new Transcript(httpClient, videoId, captionTrack.baseUrl.replace("&fmt=srv3", ""), captionTrack.name.runs[0].text, captionTrack.languageCode, isAutoGenerated, captionTrack.isTranslatable ? translationLanguages : []);
618
- targetMap[captionTrack.languageCode] = transcript;
619
- }
620
- return {
621
- manualTranscripts,
622
- generatedTranscripts
623
- };
624
- }
625
- /**
626
- * Makes the transcript list iterable, allowing for...of loops.
627
- * Manual transcripts are yielded first, followed by auto-generated transcripts.
628
- *
629
- * @returns {Iterator<Transcript>} Iterator over all transcripts
630
- */
631
- [Symbol.iterator]() {
632
- const manualTranscripts = Object.values(this.manuallyCreatedTranscripts);
633
- const generatedTranscripts = Object.values(this.autoGeneratedTranscripts);
634
- return [...manualTranscripts, ...generatedTranscripts][Symbol.iterator]();
635
- }
636
- /**
637
- * Finds a transcript for given language codes. Manually created transcripts are
638
- * returned first and only if none are found, auto-generated transcripts are used.
639
- *
640
- * @param {string[]} languageCodes - A list of language codes in descending priority
641
- * @returns {Transcript} The found transcript
642
- * @throws {NoTranscriptFound} If no transcript is found for any of the language codes
643
- *
644
- * @example
645
- * ```typescript
646
- * // Try German first, then English
647
- * const transcript = transcriptList.findTranscript(['de', 'en']);
648
- * ```
649
- */
650
- findTranscript(languageCodes) {
651
- return this.findTranscriptInMaps(languageCodes, [this.manuallyCreatedTranscripts, this.autoGeneratedTranscripts]);
652
- }
653
- /**
654
- * Finds an automatically generated transcript for given language codes.
655
- *
656
- * @param {string[]} languageCodes - A list of language codes in descending priority
657
- * @returns {Transcript} The found auto-generated transcript
658
- * @throws {NoTranscriptFound} If no auto-generated transcript is found
659
- *
660
- * @example
661
- * ```typescript
662
- * const transcript = transcriptList.findGeneratedTranscript(['en']);
663
- * ```
664
- */
665
- findGeneratedTranscript(languageCodes) {
666
- return this.findTranscriptInMaps(languageCodes, [this.autoGeneratedTranscripts]);
667
- }
668
- /**
669
- * Finds a manually created transcript for given language codes.
670
- *
671
- * @param {string[]} languageCodes - A list of language codes in descending priority
672
- * @returns {Transcript} The found manually created transcript
673
- * @throws {NoTranscriptFound} If no manually created transcript is found
674
- *
675
- * @example
676
- * ```typescript
677
- * const transcript = transcriptList.findManuallyCreatedTranscript(['en']);
678
- * ```
679
- */
680
- findManuallyCreatedTranscript(languageCodes) {
681
- return this.findTranscriptInMaps(languageCodes, [this.manuallyCreatedTranscripts]);
682
- }
683
- /**
684
- * Internal method to find a transcript by searching through provided maps.
685
- *
686
- * @private
687
- * @param {string[]} languageCodes - Language codes to search for
688
- * @param {Record<string, Transcript>[]} transcriptMaps - Maps to search through
689
- * @returns {Transcript} The found transcript
690
- * @throws {NoTranscriptFound} If no transcript is found
691
- */
692
- findTranscriptInMaps(languageCodes, transcriptMaps) {
693
- for (const languageCode of languageCodes) for (const transcriptMap of transcriptMaps) if (languageCode in transcriptMap) return transcriptMap[languageCode];
694
- throw new NoTranscriptFound(this.videoId, languageCodes, this);
695
- }
696
- /**
697
- * Returns a formatted string representation of all available transcripts.
698
- *
699
- * @returns {string} A formatted string showing all available transcripts
700
- */
701
- toString() {
702
- const formatTranscriptMap = (transcripts) => {
703
- const descriptions = Object.values(transcripts).map((t) => ` - ${t.toString()}`);
704
- return descriptions.length > 0 ? descriptions.join("\n") : "None";
705
- };
706
- const formatTranslationLanguages = () => {
707
- const descriptions = this.availableTranslationLanguages.map((lang) => ` - ${lang.language_code} ("${lang.language}")`);
708
- return descriptions.length > 0 ? descriptions.join("\n") : "None";
709
- };
710
- return `For this video (${this.videoId}) transcripts are available in the following languages:\n\n(MANUALLY CREATED)\n${formatTranscriptMap(this.manuallyCreatedTranscripts)}\n\n(GENERATED)\n${formatTranscriptMap(this.autoGeneratedTranscripts)}\n\n(TRANSLATION LANGUAGES)\n${formatTranslationLanguages()}`;
711
- }
712
- };
713
- //#endregion
714
- //#region src/types/index.ts
715
- /**
716
- * Playability status enum values
717
- */
718
- var PlayabilityStatus = /* @__PURE__ */ function(PlayabilityStatus) {
719
- PlayabilityStatus["OK"] = "OK";
720
- PlayabilityStatus["ERROR"] = "ERROR";
721
- PlayabilityStatus["LOGIN_REQUIRED"] = "LOGIN_REQUIRED";
722
- return PlayabilityStatus;
723
- }({});
724
- /**
725
- * Playability failed reason enum values
726
- */
727
- var PlayabilityFailedReason = /* @__PURE__ */ function(PlayabilityFailedReason) {
728
- PlayabilityFailedReason["BOT_DETECTED"] = "Sign in to confirm you're not a bot";
729
- PlayabilityFailedReason["AGE_RESTRICTED"] = "This video may be inappropriate for some users.";
730
- PlayabilityFailedReason["VIDEO_UNAVAILABLE"] = "This video is unavailable";
731
- return PlayabilityFailedReason;
732
- }({});
733
- //#endregion
734
- //#region src/fetchers/youtube-data-extractor.ts
735
- /**
736
- * @fileoverview Utilities for extracting data from YouTube HTML and InnerTube API responses
737
- */
738
- /**
739
- * Extracts the InnerTube API key from YouTube's HTML page.
740
- *
741
- * @param {string} htmlContent - The HTML content from YouTube's watch page
742
- * @param {string} videoId - The video ID being processed
743
- * @returns {string} The extracted API key
744
- * @throws {IpBlocked} If the page contains a reCAPTCHA (IP is blocked)
745
- * @throws {YouTubeDataUnparsable} If the API key cannot be found
746
- *
747
- * @example
748
- * ```typescript
749
- * const html = await fetchVideoHtml(videoId);
750
- * const apiKey = extractInnertubeApiKey(html, videoId);
751
- * ```
752
- */
753
- function extractInnertubeApiKey(htmlContent, videoId) {
754
- const match = htmlContent.match(/"INNERTUBE_API_KEY":\s*"([a-zA-Z0-9_-]+)"/);
755
- if (match && match.length === 2) return match[1];
756
- if (htmlContent.includes("class=\"g-recaptcha\"")) throw new IpBlocked(videoId);
757
- throw new YouTubeDataUnparsable(videoId);
758
- }
759
- /**
760
- * Extracts captions JSON from YouTube's InnerTube API response.
761
- *
762
- * @param {InnerTubeData} innertubeData - The InnerTube API response data
763
- * @param {string} videoId - The video ID being processed
764
- * @returns {CaptionsJson} The extracted captions data
765
- * @throws {TranscriptsDisabled} If captions are disabled for the video
766
- *
767
- * @example
768
- * ```typescript
769
- * const innertubeData = await fetchInnertubeData(videoId, apiKey);
770
- * const captionsJson = extractCaptionsJson(innertubeData, videoId);
771
- * ```
772
- */
773
- function extractCaptionsJson(innertubeData, videoId) {
774
- validatePlayabilityStatus(innertubeData.playabilityStatus, videoId);
775
- const captionsJson = innertubeData.captions?.playerCaptionsTracklistRenderer;
776
- if (!captionsJson || !captionsJson.captionTracks) throw new TranscriptsDisabled(videoId);
777
- return captionsJson;
778
- }
779
- /**
780
- * Validates the playability status of a video and throws appropriate errors.
781
- *
782
- * @param {any} playabilityStatusData - The playability status data from InnerTube
783
- * @param {string} videoId - The video ID being validated
784
- * @throws {RequestBlocked} If YouTube detected a bot
785
- * @throws {AgeRestricted} If the video is age-restricted
786
- * @throws {VideoUnavailable} If the video is unavailable
787
- * @throws {InvalidVideoId} If the video ID is invalid (URL was provided instead)
788
- * @throws {VideoUnplayable} If the video is unplayable for any other reason
789
- *
790
- * @example
791
- * ```typescript
792
- * validatePlayabilityStatus(innertubeData.playabilityStatus, videoId);
793
- * ```
794
- */
795
- function validatePlayabilityStatus(playabilityStatusData, videoId) {
796
- if (!playabilityStatusData) return;
797
- const playabilityStatus = playabilityStatusData.status;
798
- if (playabilityStatus === PlayabilityStatus.OK || !playabilityStatus) return;
799
- const reason = playabilityStatusData.reason;
800
- if (playabilityStatus === PlayabilityStatus.LOGIN_REQUIRED) {
801
- if (reason === PlayabilityFailedReason.BOT_DETECTED) throw new RequestBlocked(videoId);
802
- if (reason === PlayabilityFailedReason.AGE_RESTRICTED) throw new AgeRestricted(videoId);
803
- }
804
- if (playabilityStatus === PlayabilityStatus.ERROR && reason === PlayabilityFailedReason.VIDEO_UNAVAILABLE) {
805
- if (videoId.startsWith("http://") || videoId.startsWith("https://")) throw new InvalidVideoId(videoId);
806
- throw new VideoUnavailable(videoId);
807
- }
808
- throw new VideoUnplayable(videoId, reason, extractPlayabilitySubreasons(playabilityStatusData));
809
- }
810
- /**
811
- * Extracts sub-reasons from the playability status error screen.
812
- *
813
- * @private
814
- * @param {any} playabilityStatusData - The playability status data
815
- * @returns {string[]} Array of sub-reason messages
816
- */
817
- function extractPlayabilitySubreasons(playabilityStatusData) {
818
- const runs = playabilityStatusData.errorScreen?.playerErrorMessageRenderer?.subreason?.runs;
819
- if (!runs || !Array.isArray(runs)) return [];
820
- return runs.map((run) => run.text || "").filter((text) => text.length > 0);
821
- }
822
- //#endregion
823
- //#region src/fetchers/transcript-list-fetcher.ts
824
- /**
825
- * @fileoverview Fetcher for retrieving transcript lists from YouTube
826
- */
827
- /** YouTube watch page URL template */
828
- var YOUTUBE_WATCH_URL = "https://www.youtube.com/watch?v={video_id}";
829
- /** YouTube InnerTube API URL template */
830
- var INNERTUBE_API_URL = "https://www.youtube.com/youtubei/v1/player?key={api_key}";
831
- /** InnerTube API context configuration for requests */
832
- var INNERTUBE_CONTEXT = { client: {
833
- clientName: "ANDROID",
834
- clientVersion: "20.10.38"
835
- } };
836
- /**
837
- * Fetches transcript lists from YouTube for given video IDs.
838
- * Handles consent cookies, retries on blocks, and extracts caption data.
839
- *
840
- * @example
841
- * ```typescript
842
- * const fetcher = new TranscriptListFetcher(httpClient, proxyConfig);
843
- * const transcriptList = await fetcher.fetchTranscriptList('dQw4w9WgXcQ');
844
- * ```
845
- */
846
- var TranscriptListFetcher = class {
847
- /**
848
- * Creates a new TranscriptListFetcher instance.
849
- *
850
- * @param {HttpClient} httpClient - The HTTP client to use for requests
851
- * @param {ProxyConfig | null} proxyConfig - Optional proxy configuration
852
- */
853
- constructor(httpClient, proxyConfig) {
854
- this.httpClient = httpClient;
855
- this.proxyConfig = proxyConfig;
856
- }
857
- /**
858
- * Fetches the list of available transcripts for a video.
859
- *
860
- * @param {string} videoId - The YouTube video ID
861
- * @returns {Promise<TranscriptList>} The transcript list
862
- * @throws {RequestBlocked} If requests are blocked and retries exhausted
863
- * @throws {IpBlocked} If IP is blocked by YouTube
864
- * @throws {YouTubeDataUnparsable} If YouTube data cannot be parsed
865
- * @throws {TranscriptsDisabled} If transcripts are disabled for the video
866
- *
867
- * @example
868
- * ```typescript
869
- * const transcriptList = await fetcher.fetchTranscriptList('dQw4w9WgXcQ');
870
- * const transcript = transcriptList.findTranscript(['en']);
871
- * ```
872
- */
873
- async fetchTranscriptList(videoId) {
874
- const captionsJson = await this.fetchCaptionsJsonWithRetry(videoId);
875
- return TranscriptList.buildFromCaptionsJson(this.httpClient, videoId, captionsJson);
876
- }
877
- /**
878
- * Fetches captions JSON with retry logic for blocked requests.
879
- *
880
- * @private
881
- * @param {string} videoId - The video ID
882
- * @param {number} [attemptNumber=0] - Current attempt number (for retry logic)
883
- * @returns {Promise<CaptionsJson>} The captions JSON data
884
- */
885
- async fetchCaptionsJsonWithRetry(videoId, attemptNumber = 0) {
886
- try {
887
- const apiKey = extractInnertubeApiKey(await this.fetchVideoPageHtml(videoId), videoId);
888
- return extractCaptionsJson(await this.fetchInnertubePlayerData(videoId, apiKey), videoId);
889
- } catch (error) {
890
- if (error instanceof RequestBlocked) return this.handleBlockedRequest(error, videoId, attemptNumber);
891
- throw error;
892
- }
893
- }
894
- /**
895
- * Handles blocked requests with retry logic based on proxy configuration.
896
- *
897
- * @private
898
- * @param {RequestBlocked} error - The blocked request error
899
- * @param {string} videoId - The video ID
900
- * @param {number} attemptNumber - Current attempt number
901
- * @returns {Promise<CaptionsJson>} The captions JSON data from retry
902
- * @throws {RequestBlocked} If retries are exhausted
903
- */
904
- async handleBlockedRequest(error, videoId, attemptNumber) {
905
- const maxRetries = this.proxyConfig?.retriesWhenBlocked || 0;
906
- if (attemptNumber + 1 < maxRetries) return this.fetchCaptionsJsonWithRetry(videoId, attemptNumber + 1);
907
- throw error.withProxyConfig(this.proxyConfig);
908
- }
909
- /**
910
- * Fetches the HTML content of a video's watch page, handling consent cookies.
911
- *
912
- * @private
913
- * @param {string} videoId - The video ID
914
- * @returns {Promise<string>} The HTML content
915
- * @throws {FailedToCreateConsentCookie} If consent cookie creation fails
916
- */
917
- async fetchVideoPageHtml(videoId) {
918
- let htmlContent = await this.fetchAndDecodeHtml(videoId);
919
- if (this.isConsentPageDetected(htmlContent)) {
920
- this.createConsentCookie(htmlContent, videoId);
921
- htmlContent = await this.fetchAndDecodeHtml(videoId);
922
- if (this.isConsentPageDetected(htmlContent)) throw new FailedToCreateConsentCookie(videoId);
923
- }
924
- return htmlContent;
925
- }
926
- /**
927
- * Checks if the HTML content is a consent page.
928
- *
929
- * @private
930
- * @param {string} htmlContent - The HTML content to check
931
- * @returns {boolean} True if consent page detected
932
- */
933
- isConsentPageDetected(htmlContent) {
934
- return htmlContent.includes("action=\"https://consent.youtube.com/s\"");
935
- }
936
- /**
937
- * Fetches HTML from YouTube watch page and decodes HTML entities.
938
- *
939
- * @private
940
- * @param {string} videoId - The video ID
941
- * @returns {Promise<string>} The decoded HTML content
942
- */
943
- async fetchAndDecodeHtml(videoId) {
944
- const url = this.buildWatchUrl(videoId);
945
- const response = await this.httpClient.get(url);
946
- handleHttpErrors(response, videoId);
947
- const rawHtml = await response.text();
948
- return (0, html_entities.decode)(rawHtml);
949
- }
950
- /**
951
- * Builds the YouTube watch URL for a video ID.
952
- *
953
- * @private
954
- * @param {string} videoId - The video ID
955
- * @returns {string} The watch URL
956
- */
957
- buildWatchUrl(videoId) {
958
- return YOUTUBE_WATCH_URL.replace("{video_id}", videoId);
959
- }
960
- /**
961
- * Creates a consent cookie from the HTML content.
962
- * Note: This is a placeholder - cookie handling should be implemented in the HTTP client.
963
- *
964
- * @private
965
- * @param {string} htmlContent - The HTML content containing consent form
966
- * @param {string} videoId - The video ID
967
- * @throws {FailedToCreateConsentCookie} If consent value cannot be extracted
968
- */
969
- createConsentCookie(htmlContent, videoId) {
970
- if (!htmlContent.match(/name="v" value="(.*?)"/)) throw new FailedToCreateConsentCookie(videoId);
971
- }
972
- /**
973
- * Fetches player data from YouTube's InnerTube API.
974
- *
975
- * @private
976
- * @param {string} videoId - The video ID
977
- * @param {string} apiKey - The InnerTube API key
978
- * @returns {Promise<InnerTubeData>} The InnerTube player data
979
- */
980
- async fetchInnertubePlayerData(videoId, apiKey) {
981
- const url = this.buildInnertubeApiUrl(apiKey);
982
- const requestBody = this.buildInnertubeRequestBody(videoId);
983
- const response = await this.httpClient.post(url, {
984
- headers: { "Content-Type": "application/json" },
985
- body: JSON.stringify(requestBody)
986
- });
987
- handleHttpErrors(response, videoId);
988
- return await response.json();
989
- }
990
- /**
991
- * Builds the InnerTube API URL with the provided API key.
992
- *
993
- * @private
994
- * @param {string} apiKey - The API key
995
- * @returns {string} The complete API URL
996
- */
997
- buildInnertubeApiUrl(apiKey) {
998
- return INNERTUBE_API_URL.replace("{api_key}", apiKey);
999
- }
1000
- /**
1001
- * Builds the request body for InnerTube API calls.
1002
- *
1003
- * @private
1004
- * @param {string} videoId - The video ID
1005
- * @returns {object} The request body
1006
- */
1007
- buildInnertubeRequestBody(videoId) {
1008
- return {
1009
- context: INNERTUBE_CONTEXT,
1010
- videoId
1011
- };
1012
- }
1013
- };
1014
- //#endregion
1015
- //#region ../../node_modules/.bun/grab-url@1.6.22/node_modules/grab-url/dist/log.es.js
1016
- var t = {
1017
- reset: [0, "000000"],
1018
- black: [30, "1f2937"],
1019
- red: [31, "dc2626"],
1020
- green: [32, "2d6a4f"],
1021
- yellow: [33, "92400e"],
1022
- blue: [34, "1a56db"],
1023
- magenta: [35, "6d28d9"],
1024
- cyan: [36, "0e7490"],
1025
- white: [37, "374151"],
1026
- gray: [90, "6b7280"],
1027
- brightRed: [91, "ef4444"],
1028
- brightGreen: [92, "059669"],
1029
- brightYellow: [93, "d97706"],
1030
- brightBlue: [94, "3b82f6"],
1031
- brightMagenta: [95, "8b5cf6"],
1032
- brightCyan: [96, "06b6d4"],
1033
- brightWhite: [97, "f9fafb"],
1034
- bgBlack: [40, "111827"],
1035
- bgRed: [41, "fca5a5"],
1036
- bgGreen: [42, "a7f3d0"],
1037
- bgYellow: [43, "fde68a"],
1038
- bgBlue: [44, "bfdbfe"],
1039
- bgMagenta: [45, "ddd6fe"],
1040
- bgCyan: [46, "a5f3fc"],
1041
- bgWhite: [47, "f9fafb"],
1042
- bgGray: [100, "d1d5db"],
1043
- bgBrightRed: [101, "fee2e2"],
1044
- bgBrightGreen: [102, "d1fae5"],
1045
- bgBrightYellow: [103, "fef3c7"],
1046
- bgBrightBlue: [104, "dbeafe"],
1047
- bgBrightMagenta: [105, "ede9fe"],
1048
- bgBrightCyan: [106, "cffafe"],
1049
- bgBrightWhite: [107, "ffffff"]
1050
- };
1051
- function r$1(e = "ansi") {
1052
- const r = {};
1053
- for (const [n, [o, i]] of Object.entries(t)) r[n] = "html" === e ? "reset" === n ? "</span>" : `<span style="color:#${i}">` : "\x1B[" + o + "m";
1054
- return r;
1055
- }
1056
- function n$1(e, t = "ansi") {
1057
- const n = r$1(t);
1058
- return "string" == typeof e ? n.yellow : "number" == typeof e ? n.cyan : "boolean" == typeof e ? n.magenta : "function" == typeof e ? n.red : null === e ? n.gray : Array.isArray(e) ? n.blue : "object" == typeof e ? n.green : n.white;
1059
- }
1060
- function o$1(e) {
1061
- return "string" == typeof e ? "\"\"" : "number" == typeof e ? "number" : "boolean" == typeof e ? "bool" : "function" == typeof e ? "function" : null === e ? "null" : Array.isArray(e) ? e.length ? "[" + o$1(e[0]) + "]" : "[]" : "object" == typeof e ? "{...}" : typeof e;
1062
- }
1063
- function i$2(e, t = 0, l = "ansi") {
1064
- const g = r$1(l), a = "html" === l, s = " ".repeat(t);
1065
- if ("object" != typeof e || null === e) return n$1(e, l) + o$1(e) + g.reset;
1066
- if (Array.isArray(e)) {
1067
- if (a) {
1068
- let r = [];
1069
- e.length && (r = e.every((t) => typeof t == typeof e[0]) ? [i$2(e[0], t + 1, l)] : e.map((e) => i$2(e, t + 1, l)));
1070
- return `<details open><summary style="cursor:pointer;display:inline">${`${g.blue}[${g.reset}&thinsp;${e.length} × ${o$1(e[0] ?? void 0)}&thinsp;${g.blue}]${g.reset}`}</summary>${r.map((e) => `<div style="margin-left:1.5em">${e}</div>`).join("")}</details>`;
1071
- }
1072
- let r = g.blue + "[" + g.reset;
1073
- return e.length && (r += "\n"), e.every((t) => typeof t == typeof e[0]) ? r += s + " " + i$2(e[0], t + 1, l) + ",\n" : e.forEach((n, o) => {
1074
- r += s + " " + i$2(n, t + 1, l), o < e.length - 1 && (r += ","), r += "\n";
1075
- }), r += s + g.blue + "]" + g.reset, r;
1076
- }
1077
- const b = Object.keys(e);
1078
- if (a) {
1079
- const r = b.slice(0, 4).join(", ") + (b.length > 4 ? "…" : "");
1080
- return `<details open><summary style="cursor:pointer">${`${g.green}{${g.reset}&nbsp;${r}&nbsp;${g.green}}${g.reset}`}</summary>${b.map((r) => {
1081
- const a = e[r], s = n$1(a, l);
1082
- return "object" == typeof a && null !== a ? `<div style="margin-left:1.5em">${s}${r}${g.reset}: ${i$2(a, t + 1, l)}</div>` : `<div style="margin-left:1.5em">${s}${r}: ${o$1(a)}${g.reset}</div>`;
1083
- }).join("")}</details>`;
1084
- }
1085
- let f = g.green + "{" + g.reset;
1086
- return b.length && (f += "\n"), b.forEach((r, a) => {
1087
- const y = e[r], c = n$1(y, l);
1088
- f += s + " ", f += "object" == typeof y && null !== y ? c + r + g.reset + ": " + i$2(y, t + 1, l) : c + r + ": " + o$1(y) + g.reset, a < b.length - 1 && (f += ","), f += "\n";
1089
- }), f += s + g.green + "}" + g.reset, f;
1090
- }
1091
- function l$2(e = "", t = {}) {
1092
- let { color: n, style: o = "color:rgb(54, 165, 220); font-size: 10pt;", hideInProduction: l, startSpinner: g = !1, stopSpinner: a = !1 } = t;
1093
- const s = r$1();
1094
- void 0 === l && (l = "undefined" != typeof window && window?.location.hostname.includes("localhost")), "object" == typeof e && (e = i$2(e) + "\n\n" + JSON.stringify(e, null, 2)), Array.isArray(n) && 1 == n.length && (n = n[0]), n && "undefined" != typeof process && ("string" == typeof e && e.includes("%c") && Array.isArray(n) ? e = e.replace(/%c/g, (e, t) => s[n[t]] || "") : n && "string" == typeof n && (e = (s[n] || "") + e + s.reset));
1095
- var b = 0;
1096
- return g ? globalThis.interval = setInterval(() => {
1097
- process.stdout.write((Array.isArray(n) ? s[n[0]] : s[n] || "") + "\r" + "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏".split("")[b = ++b % 10] + " " + e + s.reset);
1098
- }, 50) : a ? (clearInterval(globalThis.interval), process.stdout.write("\r" + (e || " ") + " ".repeat("string" == typeof e ? e.length + 20 : 40) + "\n")) : "string" == typeof o ? (1 == o.split(" ").length || n ? o = `color: ${n || o}; font-size: 11pt;` : o.match(/^#[0-9a-fA-F]{6}$/) && (o = `color: ${o}; font-size: 11pt;`), l ? console.debug((o ? "%c" : "") + (e || ""), o) : console.log((o ? "%c" : "") + (e || ""), o)) : "object" == typeof o && console.log(e, ...o), !0;
1099
- }
1100
- //#endregion
1101
- //#region ../../node_modules/.bun/grab-url@1.6.22/node_modules/grab-url/dist/core-BX1uvK6L.js
1102
- var n = async (e, t) => {
1103
- let n;
1104
- return async function(...o) {
1105
- clearTimeout(n), n = setTimeout(async () => {
1106
- clearTimeout(n), await e(...o);
1107
- }, t);
1108
- };
1109
- };
1110
- var o = (e) => new Promise((t) => setTimeout(t, 1e3 * e || 0));
1111
- var r = (e, t) => {
1112
- let n = (e) => t?.startsWith(e) || !1, o = e, r = t;
1113
- return t?.startsWith("http:") || t?.startsWith("https:") ? o = "" : n("/") || o.endsWith("/") ? n("/") && o.endsWith("/") && (r = t.slice(1)) : r = "/" + t, {
1114
- baseURL: o,
1115
- path: r
1116
- };
1117
- };
1118
- function s(e) {
1119
- if ("undefined" == typeof document) return;
1120
- let t, n = document.getElementById("alert-overlay");
1121
- if (!n) {
1122
- n = document.body.appendChild(document.createElement("div")), n.id = "alert-overlay", n.setAttribute("style", "position:fixed;inset:0;z-index:9999;background:rgba(0,0,0,0.5);display:flex;align-items:center;justify-content:center"), n.innerHTML = "<div id=\"alert-box\" style=\"background:#fff;padding:1.5em 2em;border-radius:8px;box-shadow:0 2px 16px #0003;min-width:320px;max-width:90vw;max-height:80vh;position:relative;display:flex;flex-direction:column;\">\n <button id=\"close-alert\" style=\"position:absolute;top:12px;right:20px;font-size:1.5em;background:none;border:none;cursor:pointer;color:black;\">&times;</button>\n <div id=\"alert-list\" style=\"overflow:auto;flex:1;font-family:monospace;font-size:13px;\"></div>\n </div>", n.addEventListener("click", (e) => e.target == n && n.remove());
1123
- const e = document.getElementById("close-alert");
1124
- e && (e.onclick = () => n.remove());
1125
- }
1126
- t = document.getElementById("alert-list"), t.innerHTML += `<div style="border-bottom:1px solid #e5e7eb;margin:0.5em 0;padding-bottom:0.5em">${e}</div>`;
1127
- }
1128
- function i$1(e) {
1129
- return e.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1130
- }
1131
- function a() {
1132
- "undefined" != typeof document && document.addEventListener("keydown", (t) => {
1133
- const n = window.grab;
1134
- if (n && n.log && "i" === t.key && t.ctrlKey && t.altKey) {
1135
- let t = "";
1136
- for (const o of n.log) {
1137
- const n = new Date(o.lastFetchTime).toLocaleString(), r = i$2(o.request, 0, "html"), s = i$2(o.response, 0, "html"), a = i$1(JSON.stringify(o.response, null, 2));
1138
- t += `\n <details open style="margin-bottom:0.75em">\n <summary style="cursor:pointer;font-weight:bold;padding:4px 0;list-style:none;display:flex;justify-content:space-between">\n <span style="color:#1a56db">${i$1(o.path)}</span>\n <span style="color:#6b7280;font-weight:normal;margin-left:1em">${n}</span>\n </summary>\n <div style="padding-left:1em;margin-top:0.5em">\n <details style="margin-bottom:0.4em">\n <summary style="cursor:pointer;color:#6b7280;font-size:0.9em">Request</summary>\n <div style="padding:0.4em 0 0 1em">${r}</div>\n </details>\n <details open style="margin-bottom:0.4em">\n <summary style="cursor:pointer;color:#6b7280;font-size:0.9em">Response (structure)</summary>\n <div style="padding:0.4em 0 0 1em">${s}</div>\n </details>\n <details style="margin-bottom:0.4em">\n <summary style="cursor:pointer;color:#6b7280;font-size:0.9em">Response (data)</summary>\n <pre style="margin:0.4em 0 0 1em;padding:0.5em;background:#f9fafb;border:1px solid #e5e7eb;border-radius:4px;overflow:auto;max-height:300px;font-size:12px">${a}</pre>\n </details>\n </div>\n </details>`;
1139
- }
1140
- s(t || "<em>No requests logged yet.</em>");
1141
- }
1142
- });
1143
- }
1144
- function l$1(o) {
1145
- return async function i(a, l) {
1146
- const c = function(e) {
1147
- return {
1148
- ..."undefined" != typeof window ? window?.grab?.defaults : globalThis?.grab?.defaults || {},
1149
- ...e
1150
- };
1151
- }(l);
1152
- let { headers: d, response: u, method: f = c.post ? "POST" : c.put ? "PUT" : c.patch ? "PATCH" : "GET", cache: p, timeout: m = 30, baseURL: y = "undefined" != typeof process && process.env.SERVER_API_URL || "/api/", cancelOngoingIfNew: g, cancelNewIfOngoing: b, rateLimit: w, debug: h, infiniteScroll: v, logger: T = l$2, onRequest: x, onResponse: L, onError: E, onStream: A, unzip: S, dom: O, body: R, post: P, put: k, patch: $, ...j } = c;
1153
- const q = r(y, a);
1154
- y = q.baseURL, a = q.path;
1155
- const F = function(e) {
1156
- const t = "function" == typeof e ? e : null;
1157
- return {
1158
- response: !e || t ? {} : e,
1159
- resFunction: t
1160
- };
1161
- }(u);
1162
- let N = F.response, D = F.resFunction;
1163
- const I = ("undefined" != typeof window ? window.grab : globalThis.grab)?.log || [];
1164
- D ? N = D({
1165
- ...N,
1166
- isLoading: !0
1167
- }) : "object" == typeof N && (N.isLoading = !0);
1168
- try {
1169
- const r = await async function(e, t, o, r) {
1170
- const { debounce: s = 0, repeat: i = 0, repeatEvery: a = null, setDefaults: l = !1 } = o;
1171
- if (s > 0) return await (await n(async () => {
1172
- await r(e, {
1173
- ...t,
1174
- debounce: 0
1175
- });
1176
- }, 1e3 * s))(), o.response || {};
1177
- if (i > 1) {
1178
- for (let n = 0; n < i; n++) await r(e, {
1179
- ...t,
1180
- repeat: 0
1181
- });
1182
- return o.response || {};
1183
- }
1184
- if (a) return setInterval(async () => {
1185
- await r(e, {
1186
- ...t,
1187
- repeat: 0,
1188
- repeatEvery: null
1189
- });
1190
- }, 1e3 * a), o.response || {};
1191
- if (l) {
1192
- const e = "undefined" != typeof window ? window.grab : globalThis.grab;
1193
- return e && (e.defaults = {
1194
- ...t,
1195
- setDefaults: void 0
1196
- }), o.response || {};
1197
- }
1198
- return null;
1199
- }(a, l || {}, c, i);
1200
- if (r) return r;
1201
- (function(e, t, n, o) {
1202
- if ("undefined" == typeof window) return;
1203
- const { regrabOnStale: r, regrabOnFocus: s, regrabOnNetwork: i, cache: a, cacheForTime: l = 60 } = n, c = async () => await o(e, {
1204
- ...t,
1205
- cache: !1
1206
- });
1207
- r && a && setTimeout(c, 1e3 * l), i && window.addEventListener("online", c), s && (window.addEventListener("focus", c), document.addEventListener("visibilitychange", async () => {
1208
- "visible" === document.visibilityState && await c();
1209
- }));
1210
- })(a, l || {}, c, i);
1211
- let { params: s, priorRequest: u, response: E, paramsAsText: P } = function(e, t, n, o, r, s) {
1212
- const { cache: i, cacheForTime: a, infiniteScroll: l } = n, [c, d] = l || [], u = JSON.stringify(c ? {
1213
- ...t,
1214
- [c]: void 0
1215
- } : t);
1216
- let f = s.find((t) => t.request === u && t.path === e);
1217
- if (c) {
1218
- let e = (f?.currentPage || 0) + 1 || t?.[c] || 1;
1219
- f ? f.currentPage = e : (o[d] = [], e = 1), t = {
1220
- ...t,
1221
- [c]: e
1222
- };
1223
- } else {
1224
- for (let e of Object.keys(o)) o[e] = void 0;
1225
- if (i && f?.response && (!a || f.lastFetchTime > Date.now() - 1e3 * a)) {
1226
- for (let e of Object.keys(f.response)) o[e] = f.response[e];
1227
- r && (o = r(o));
1228
- }
1229
- }
1230
- return {
1231
- params: t,
1232
- priorRequest: f,
1233
- response: o,
1234
- paramsAsText: u
1235
- };
1236
- }(a, j, c, N, D, I);
1237
- if (j = s, N = E, function(e, n, o, r, s) {
1238
- if ("undefined" == typeof window || !o?.length) return;
1239
- const [i, , a] = o;
1240
- if (void 0 === a) return;
1241
- let l = "string" == typeof a ? document.querySelector(a) : a;
1242
- l ? (window.scrollListener && "function" == typeof l.removeEventListener && l.removeEventListener("scroll", window.scrollListener), window.scrollListener = (t) => {
1243
- const o = t.target;
1244
- localStorage.setItem("scroll", JSON.stringify([
1245
- o.scrollTop,
1246
- o.scrollLeft,
1247
- a
1248
- ])), o.scrollHeight - o.scrollTop <= o.clientHeight + 200 && s(e, {
1249
- ...n,
1250
- cache: !1,
1251
- [i]: (r?.currentPage || 0) + 1
1252
- });
1253
- }, l.addEventListener("scroll", window.scrollListener)) : l$2("paginateDOM not found", { color: "red" });
1254
- }(a, l, v, u, i), w > 0 && u?.lastFetchTime > Date.now() - 1e3 * w) throw new Error(`Fetch rate limit exceeded for ${a}. Wait ${w}s between requests.`);
1255
- if (u?.controller) {
1256
- if (g) u.controller.abort();
1257
- else if (b) return { isLoading: !0 };
1258
- }
1259
- const k = new AbortController();
1260
- let $ = k.signal;
1261
- g || "function" != typeof AbortSignal.timeout || ($ = AbortSignal.timeout(1e3 * m)), I.unshift({
1262
- path: a,
1263
- request: P,
1264
- lastFetchTime: Date.now(),
1265
- controller: k
1266
- });
1267
- let { fetchParams: q, paramsGETRequest: F } = function(e, t, n, o, r, s) {
1268
- const i = [
1269
- "POST",
1270
- "PUT",
1271
- "PATCH"
1272
- ].includes(e), a = {
1273
- method: e,
1274
- headers: {
1275
- "Content-Type": "application/json",
1276
- Accept: "application/json",
1277
- ...t
1278
- },
1279
- body: n || (i ? JSON.stringify(o) : null),
1280
- redirect: "follow",
1281
- cache: r ? "force-cache" : "no-store",
1282
- signal: s
1283
- };
1284
- let l = "";
1285
- return i || (l = (Object.keys(o).length ? "?" : "") + new URLSearchParams(o).toString()), {
1286
- fetchParams: a,
1287
- paramsGETRequest: l
1288
- };
1289
- }(f, d, R, j, !!p, $);
1290
- if ("function" == typeof x) {
1291
- const e = x(a, N, j, q);
1292
- Array.isArray(e) && ([a, N, j, q] = e);
1293
- }
1294
- const z = /* @__PURE__ */ new Date(), U = await o(y, a, F, q, j, A, S, O);
1295
- if (D ? N = D({
1296
- ...N,
1297
- isLoading: void 0
1298
- }) : "object" == typeof N && delete N.isLoading, "function" == typeof L) {
1299
- const e = L(a, N, j, q);
1300
- Array.isArray(e) && ([a, N, j, q] = e);
1301
- }
1302
- const H = ((Number(/* @__PURE__ */ new Date()) - Number(z)) / 1e3).toFixed(1);
1303
- h && T(`Path:${y + a + F}\n${JSON.stringify(l, null, 2)}\nTime: ${H}s\nResponse: ${i$2(U)}`);
1304
- const [, W] = v || [];
1305
- return N = function(e, t, n, o) {
1306
- if ("object" == typeof e && null !== e) {
1307
- for (let n of Object.keys(e)) t[n] = o === n && Array.isArray(t[n]) ? [...t[n], ...e[n]] : e[n];
1308
- t.data = e;
1309
- } else n ? t = n({
1310
- data: e,
1311
- ...e
1312
- }) : "object" == typeof t && (t.data = e);
1313
- return t;
1314
- }(U, N, D, W), I[0] && (I[0].response = N), D && (N = D(N)), N;
1315
- } catch (U) {
1316
- if ("function" == typeof E && E(U.message, y + a, j), c.retryAttempts && c.retryAttempts > 0) return await i(a, {
1317
- ...l,
1318
- retryAttempts: --c.retryAttempts
1319
- });
1320
- !U.message.includes("signal") && h && (T(`Error: ${U.message}\nPath:${y + a}\n`, { color: "red" }), "undefined" != typeof document && s(U.message)), N = N || {}, N.error = U.message;
1321
- const e = "function" == typeof u ? u : null;
1322
- return e ? (N.data = e({
1323
- isLoading: void 0,
1324
- error: U.message
1325
- }), N = N.data) : delete N.isLoading, N;
1326
- }
1327
- };
1328
- }
1329
- //#endregion
1330
- //#region ../../node_modules/.bun/grab-url@1.6.22/node_modules/grab-url/dist/grab-api.es.js
1331
- async function i(t) {
1332
- const { extract: r } = await Promise.resolve().then(() => require("./archiver-web.es-D64GRoH3.js")), o = await r({ archiveBuffer: t }), e = {};
1333
- for (const n of o) e[n.path] = n.content;
1334
- return e;
1335
- }
1336
- async function c(t, r) {
1337
- const { parseHTML: o } = await Promise.resolve().then(() => require("./index-CLlAnStL-CJZcZDNB.js")), { document: e } = o(t);
1338
- if (!r || !0 === r) return e;
1339
- const n = e.querySelector(r);
1340
- return n ? n.innerHTML ?? n.textContent : null;
1341
- }
1342
- var l = l$1(async function(r, o$2, e, n, a, s, l, d) {
1343
- const u = ("undefined" != typeof window ? window.grab : globalThis.grab)?.mock?.[o$2], f = JSON.stringify(a);
1344
- if (u && (!u.method || u.method === n.method) && (!u.params || f === JSON.stringify(u.params))) return await o(u.delay || 0), "function" == typeof u.response ? u.response(a) : u.response;
1345
- const w = await fetch(r + o$2 + e, n).catch((t) => {
1346
- throw new Error(t.message);
1347
- });
1348
- if (!w.ok) throw new Error(`HTTP error: ${w.status} ${w.statusText}`);
1349
- if (s) return await s(w.body), null;
1350
- const h = w.headers.get("content-type") ?? "", g = !1 !== l && (h.includes("application/zip") || h.includes("application/x-zip")), m = !1 !== d && ("string" == typeof d || h.includes("text/html"));
1351
- if (g) return { data: await i(await w.arrayBuffer().catch((t) => {
1352
- throw new Error("Error reading zip: " + t);
1353
- })) };
1354
- if (m) return { data: await c(await w.text().catch((t) => {
1355
- throw new Error("Error reading html: " + t);
1356
- }), "string" != typeof d || d) };
1357
- return await (h.includes("application/json") ? w.json() : h.includes("application/pdf") || h.includes("application/octet-stream") ? w.blob() : h ? w.text() : w.json()).catch((t) => {
1358
- throw new Error("Error parsing response: " + t);
1359
- });
1360
- });
1361
- var d = l;
1362
- d.instance = (t = {}) => (r, o = {}) => l(r, {
1363
- ...t,
1364
- ...o
1365
- }), d.log = [], d.mock = {}, d.defaults = {}, "undefined" != typeof window ? (window.log = l$2, window.grab = d, a(), document.addEventListener("DOMContentLoaded", () => {
1366
- try {
1367
- const t = localStorage.getItem("scroll");
1368
- if (!t) return;
1369
- const [r, o, e] = JSON.parse(t);
1370
- if (!r || !e) return;
1371
- const n = document.querySelector(e);
1372
- n && (n.scrollTop = r, n.scrollLeft = o);
1373
- } catch (t) {
1374
- console.warn("Failed to restore scroll position", t);
1375
- }
1376
- })) : "undefined" != typeof globalThis && (globalThis.log = l$2, globalThis.grab = d);
1377
- //#endregion
1378
- //#region src/http/fetch-http-client.ts
1379
- /**
1380
- * @fileoverview HTTP client implementation using grab-url
1381
- */
1382
- /**
1383
- * Simple HTTP client implementation using grab-url with proxy support.
1384
- * This client handles HTTP/HTTPS requests with configurable headers and proxy settings.
1385
- *
1386
- * @internal
1387
- */
1388
- var FetchHttpClient = class {
1389
- /**
1390
- * Creates a new FetchHttpClient instance.
1391
- * Sets default Accept-Language header to English.
1392
- */
1393
- constructor() {
1394
- this.requestHeaders = {};
1395
- this.proxyConfiguration = {};
1396
- this.requestHeaders["Accept-Language"] = "en-US";
1397
- }
1398
- /**
1399
- * Sets a custom header for all requests.
1400
- *
1401
- * @param {string} headerName - The header name
1402
- * @param {string} headerValue - The header value
1403
- */
1404
- setHeader(headerName, headerValue) {
1405
- this.requestHeaders[headerName] = headerValue;
1406
- }
1407
- /**
1408
- * Configures proxy settings for all requests.
1409
- *
1410
- * @param {RequestsProxyConfigDict} proxies - Proxy configuration dictionary
1411
- */
1412
- setProxies(proxies) {
1413
- this.proxyConfiguration = proxies;
1414
- }
1415
- /**
1416
- * Performs an HTTP GET request.
1417
- *
1418
- * @param {string} url - The URL to request
1419
- * @param {RequestInit} [options] - Additional request options
1420
- * @returns {Promise<Response>} The HTTP response
1421
- */
1422
- async get(url, options) {
1423
- const proxyAgent = this.getProxyAgentForUrl(url);
1424
- return d(url, {
1425
- ...options,
1426
- method: "GET",
1427
- headers: {
1428
- ...this.requestHeaders,
1429
- ...options?.headers
1430
- },
1431
- agent: proxyAgent
1432
- });
1433
- }
1434
- /**
1435
- * Performs an HTTP POST request.
1436
- *
1437
- * @param {string} url - The URL to request
1438
- * @param {RequestInit} [options] - Additional request options
1439
- * @returns {Promise<Response>} The HTTP response
1440
- */
1441
- async post(url, options) {
1442
- const proxyAgent = this.getProxyAgentForUrl(url);
1443
- return d(url, {
1444
- ...options,
1445
- method: "POST",
1446
- headers: {
1447
- ...this.requestHeaders,
1448
- ...options?.headers
1449
- },
1450
- agent: proxyAgent
1451
- });
1452
- }
1453
- /**
1454
- * Gets the appropriate proxy agent for a given URL.
1455
- *
1456
- * @private
1457
- * @param {string} url - The URL being requested
1458
- * @returns {any} The proxy agent or undefined if no proxy is configured
1459
- */
1460
- getProxyAgentForUrl(url) {
1461
- if (Object.keys(this.proxyConfiguration).length === 0) return;
1462
- const proxyUrl = url.startsWith("https://") ? this.proxyConfiguration.https : this.proxyConfiguration.http;
1463
- if (!proxyUrl) return;
1464
- return new https_proxy_agent.HttpsProxyAgent(proxyUrl);
1465
- }
1466
- };
1467
- //#endregion
1468
- //#region src/youtube-transcript-api.ts
1469
- /**
1470
- * Main API class for retrieving YouTube transcripts.
1471
- * This is the primary entry point for the library.
1472
- *
1473
- * @example
1474
- * ```typescript
1475
- * // Basic usage
1476
- * const api = new YouTubeTranscriptApi();
1477
- * const transcript = await api.fetchTranscript('video_id');
1478
- *
1479
- * // With language preference
1480
- * const transcript = await api.fetchTranscript('video_id', { languages: ['de', 'en'] });
1481
- *
1482
- * // With proxy
1483
- * import { GenericProxyConfig } from 'youtube-transcript-api';
1484
- * const api = new YouTubeTranscriptApi({
1485
- * proxyConfig: new GenericProxyConfig({
1486
- * httpUrl: 'http://user:pass@proxy.example.com:8080'
1487
- * })
1488
- * });
1489
- * ```
1490
- */
1491
- var YouTubeTranscriptApi = class {
1492
- /**
1493
- * Creates a new YouTubeTranscriptApi instance.
1494
- *
1495
- * Note on thread-safety: As this class initializes an HTTP client,
1496
- * it is not thread-safe. Make sure to initialize an instance per
1497
- * thread if used in a multi-threading scenario!
1498
- *
1499
- * @param {Object} [options] - Configuration options
1500
- * @param {ProxyConfig} [options.proxyConfig] - An optional ProxyConfig object defining proxies
1501
- * used for all network requests. This can be used to work around your IP being blocked
1502
- * by YouTube, as described in the "Working around IP bans" section of the README.
1503
- * @param {HttpClient} [options.httpClient] - You can optionally pass in a custom HTTP client
1504
- * if you want to share state between different instances of YouTubeTranscriptApi or
1505
- * customize request behavior.
1506
- *
1507
- * @example
1508
- * ```typescript
1509
- * // Basic usage
1510
- * const api = new YouTubeTranscriptApi();
1511
- *
1512
- * // With Webshare proxy
1513
- * import { WebshareProxyConfig } from 'youtube-transcript-api';
1514
- * const api = new YouTubeTranscriptApi({
1515
- * proxyConfig: new WebshareProxyConfig({
1516
- * proxyUsername: 'your-username',
1517
- * proxyPassword: 'your-password',
1518
- * filterIpLocations: ['us', 'de']
1519
- * })
1520
- * });
1521
- *
1522
- * // With generic proxy
1523
- * import { GenericProxyConfig } from 'youtube-transcript-api';
1524
- * const api = new YouTubeTranscriptApi({
1525
- * proxyConfig: new GenericProxyConfig({
1526
- * httpUrl: 'http://user:pass@proxy.example.com:8080',
1527
- * httpsUrl: 'https://user:pass@proxy.example.com:8080'
1528
- * })
1529
- * });
1530
- * ```
1531
- */
1532
- constructor(options) {
1533
- const httpClient = this.initializeHttpClient(options);
1534
- this.configureHttpClientWithProxy(httpClient, options?.proxyConfig);
1535
- this.transcriptListFetcher = new TranscriptListFetcher(httpClient, options?.proxyConfig || null);
1536
- }
1537
- /**
1538
- * Initializes the HTTP client from options or creates a default one.
1539
- *
1540
- * @private
1541
- * @param {Object} [options] - Configuration options
1542
- * @returns {HttpClient} The initialized HTTP client
1543
- */
1544
- initializeHttpClient(options) {
1545
- return options?.httpClient || new FetchHttpClient();
1546
- }
1547
- /**
1548
- * Configures the HTTP client with proxy settings if provided.
1549
- *
1550
- * @private
1551
- * @param {HttpClient} httpClient - The HTTP client to configure
1552
- * @param {ProxyConfig} [proxyConfig] - Optional proxy configuration
1553
- */
1554
- configureHttpClientWithProxy(httpClient, proxyConfig) {
1555
- if (!proxyConfig || !(httpClient instanceof FetchHttpClient)) return;
1556
- const proxyDictionary = proxyConfig.toRequestsDict();
1557
- httpClient.setProxies(proxyDictionary);
1558
- if (proxyConfig.preventKeepingConnectionsAlive) httpClient.setHeader("Connection", "close");
1559
- }
1560
- /**
1561
- * Retrieves the transcript for a single video.
1562
- * This is a shortcut for calling:
1563
- * `api.listTranscripts(videoId).then(list => list.findTranscript(languages)).then(t => t.fetch())`
1564
- *
1565
- * @param {string} videoId - The ID of the video you want to retrieve the transcript for.
1566
- * Make sure that this is the actual ID, NOT the full URL to the video!
1567
- * @param {Object} [options] - Fetch options
1568
- * @param {string[]} [options.languages=['en']] - A list of language codes in descending priority.
1569
- * For example, if this is set to ['de', 'en'] it will first try to fetch the german
1570
- * transcript (de) and then fetch the english transcript (en) if it fails to do so.
1571
- * @param {boolean} [options.preserveFormatting=false] - Whether to keep select HTML text formatting
1572
- * @returns {Promise<FetchedTranscript>} The fetched transcript
1573
- *
1574
- * @example
1575
- * ```typescript
1576
- * const api = new YouTubeTranscriptApi();
1577
- *
1578
- * // Fetch English transcript
1579
- * const transcript = await api.fetchTranscript('dQw4w9WgXcQ');
1580
- *
1581
- * // Fetch with language preference
1582
- * const transcript = await api.fetchTranscript('dQw4w9WgXcQ', {
1583
- * languages: ['de', 'en']
1584
- * });
1585
- *
1586
- * // Preserve HTML formatting
1587
- * const transcript = await api.fetchTranscript('dQw4w9WgXcQ', {
1588
- * preserveFormatting: true
1589
- * });
1590
- *
1591
- * // Iterate over snippets
1592
- * for (const snippet of transcript) {
1593
- * console.log(`${snippet.start}s: ${snippet.text}`);
1594
- * }
1595
- * ```
1596
- */
1597
- async fetchTranscript(videoId, options) {
1598
- const preferredLanguages = options?.languages || ["en"];
1599
- const preserveFormatting = options?.preserveFormatting || false;
1600
- return (await this.listTranscripts(videoId)).findTranscript(preferredLanguages).fetch(preserveFormatting);
1601
- }
1602
- /**
1603
- * Retrieves the list of transcripts which are available for a given video.
1604
- * It returns a TranscriptList object which is iterable and provides methods to
1605
- * filter the list of transcripts for specific languages.
1606
- *
1607
- * While iterating over the TranscriptList, the individual transcripts are
1608
- * represented by Transcript objects, which provide metadata and can either
1609
- * be fetched by calling transcript.fetch() or translated by calling
1610
- * transcript.translate('en').
1611
- *
1612
- * @param {string} videoId - The ID of the video you want to retrieve the transcript for.
1613
- * Make sure that this is the actual ID, NOT the full URL to the video!
1614
- * @returns {Promise<TranscriptList>} A list of available transcripts
1615
- *
1616
- * @example
1617
- * ```typescript
1618
- * const api = new YouTubeTranscriptApi();
1619
- *
1620
- * // Retrieve available transcripts
1621
- * const transcriptList = await api.listTranscripts('video_id');
1622
- *
1623
- * // Iterate over all available transcripts
1624
- * for (const transcript of transcriptList) {
1625
- * console.log(
1626
- * transcript.videoId,
1627
- * transcript.language,
1628
- * transcript.languageCode,
1629
- * transcript.isGenerated,
1630
- * transcript.isTranslatable,
1631
- * transcript.translationLanguages
1632
- * );
1633
- *
1634
- * // Fetch the actual transcript data
1635
- * const fetched = await transcript.fetch();
1636
- * console.log(fetched);
1637
- *
1638
- * // Translate the transcript
1639
- * if (transcript.isTranslatable) {
1640
- * const translated = transcript.translate('de');
1641
- * const fetchedTranslated = await translated.fetch();
1642
- * console.log(fetchedTranslated);
1643
- * }
1644
- * }
1645
- *
1646
- * // Filter for specific language
1647
- * const transcript = transcriptList.findTranscript(['de', 'en']);
1648
- *
1649
- * // Filter for manually created transcripts
1650
- * const manual = transcriptList.findManuallyCreatedTranscript(['de', 'en']);
1651
- *
1652
- * // Filter for automatically generated transcripts
1653
- * const generated = transcriptList.findGeneratedTranscript(['de', 'en']);
1654
- * ```
1655
- */
1656
- async listTranscripts(videoId) {
1657
- return this.transcriptListFetcher.fetchTranscriptList(videoId);
1658
- }
1659
- /**
1660
- * Alias for fetchTranscript() for backward compatibility.
1661
- *
1662
- * @deprecated Use fetchTranscript() instead
1663
- * @param {string} videoId - The video ID
1664
- * @param {Object} [options] - Fetch options
1665
- * @returns {Promise<FetchedTranscript>} The fetched transcript
1666
- */
1667
- async fetch(videoId, options) {
1668
- return this.fetchTranscript(videoId, options);
1669
- }
1670
- /**
1671
- * Alias for listTranscripts() for backward compatibility.
1672
- *
1673
- * @deprecated Use listTranscripts() instead
1674
- * @param {string} videoId - The video ID
1675
- * @returns {Promise<TranscriptList>} A list of available transcripts
1676
- */
1677
- async list(videoId) {
1678
- return this.listTranscripts(videoId);
1679
- }
1680
- };
1681
- //#endregion
1682
- //#region src/utils/transcript-utils.ts
1683
- /**
1684
- * Encodes speech speed from a fetched transcript into a compact run-length string.
1685
- * Optionally prepends a YouTube embed iframe with data-timestamps for player sync.
1686
- * @param transcript - A FetchedTranscript returned by fetchTranscript()
1687
- * @param addPlayer - If true, prepends an iframe embed with data-timestamps attribute
1688
- * @returns html content, word count, run-length encoded speed string, and raw timestamps
1689
- */
1690
- function encodeTranscriptSpeeds(transcript, addPlayer = false) {
1691
- let charCount = 0;
1692
- const timestamps = [];
1693
- const textParts = [];
1694
- for (const snippet of transcript.snippets) {
1695
- textParts.push(snippet.text);
1696
- charCount += snippet.text.length;
1697
- if (snippet.start > 0) timestamps.push([charCount, snippet.start]);
1698
- }
1699
- const content = textParts.join(" ").replace(/\s+/g, " ");
1700
- const word_count = content.split(/\s+/).filter(Boolean).length;
1701
- const speedValues = timestamps.map(([char, time]) => Math.floor(char / time) - 10);
1702
- if (speedValues.length === 0) return {
1703
- html: content,
1704
- word_count,
1705
- speeds: ""
1706
- };
1707
- const compressed = [];
1708
- const compressedCount = [];
1709
- let currentNum = speedValues[0];
1710
- let count = 1;
1711
- for (let i = 1; i < speedValues.length; i++) if (speedValues[i] === currentNum) count++;
1712
- else {
1713
- compressed.push(currentNum);
1714
- compressedCount.push(count);
1715
- currentNum = speedValues[i];
1716
- count = 1;
1717
- }
1718
- compressed.push(currentNum);
1719
- compressedCount.push(count);
1720
- const speeds = compressed.map((val, i) => `${val}x${compressedCount[i]}`).join(",");
1721
- return {
1722
- html: addPlayer ? `<iframe width="100%" height="315px" data-timestamps="${speeds}" src="https://www.youtube.com/embed/${transcript.videoId}" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>${content}` : content,
1723
- word_count,
1724
- speeds
1725
- };
1726
- }
1727
- //#endregion
1728
- //#region src/proxies/index.ts
1729
- var _WebshareProxyConfig;
1730
- /**
1731
- * Exception for invalid proxy configurations
1732
- */
1733
- var InvalidProxyConfig = class InvalidProxyConfig extends Error {
1734
- constructor(message) {
1735
- super(message);
1736
- this.name = "InvalidProxyConfig";
1737
- Object.setPrototypeOf(this, InvalidProxyConfig.prototype);
1738
- }
1739
- };
1740
- /**
1741
- * Base class for all proxy configurations.
1742
- * Any proxy config can be used as long as it can be converted to a RequestsProxyConfigDict.
1743
- */
1744
- var ProxyConfig = class {
1745
- /**
1746
- * If you are using rotating proxies, it can be useful to prevent the HTTP
1747
- * client from keeping TCP connections alive, as your IP won't be rotated on
1748
- * every request if your connection stays open.
1749
- * @returns {boolean} Whether to prevent keeping connections alive
1750
- */
1751
- get preventKeepingConnectionsAlive() {
1752
- return false;
1753
- }
1754
- /**
1755
- * Defines how many times we should retry if a request is blocked. When using
1756
- * rotating residential proxies with a large IP pool it can make sense to retry a
1757
- * couple of times when a blocked IP is encountered, since a retry will trigger
1758
- * an IP rotation and the next IP might not be blocked.
1759
- * @returns {number} Number of retries when blocked
1760
- */
1761
- get retriesWhenBlocked() {
1762
- return 0;
1763
- }
1764
- };
1765
- /**
1766
- * Generic proxy configuration that can be used to set up any HTTP/HTTPS/SOCKS proxy.
1767
- *
1768
- * If only an HTTP or an HTTPS proxy is provided, it will be used for both types of
1769
- * connections. However, you will have to provide at least one of the two.
1770
- *
1771
- * @example
1772
- * ```typescript
1773
- * const proxyConfig = new GenericProxyConfig({
1774
- * httpUrl: 'http://user:pass@proxy.example.com:8080',
1775
- * httpsUrl: 'https://user:pass@proxy.example.com:8080'
1776
- * });
1777
- * ```
1778
- */
1779
- var GenericProxyConfig = class extends ProxyConfig {
1780
- /**
1781
- * Creates a generic proxy configuration.
1782
- * If only an HTTP or an HTTPS proxy is provided, it will be used for both types of
1783
- * connections. However, you will have to provide at least one of the two.
1784
- *
1785
- * @param {Object} options - Proxy configuration options
1786
- * @param {string} [options.httpUrl] - The proxy URL used for HTTP requests. Defaults to httpsUrl if not provided.
1787
- * @param {string} [options.httpsUrl] - The proxy URL used for HTTPS requests. Defaults to httpUrl if not provided.
1788
- * @throws {InvalidProxyConfig} If neither httpUrl nor httpsUrl is provided
1789
- */
1790
- constructor(options) {
1791
- super();
1792
- const { httpUrl, httpsUrl } = options;
1793
- if (!httpUrl && !httpsUrl) throw new InvalidProxyConfig("GenericProxyConfig requires you to define at least one of the two: http or https");
1794
- this._httpUrl = httpUrl || null;
1795
- this._httpsUrl = httpsUrl || null;
1796
- }
1797
- get httpUrl() {
1798
- return this._httpUrl;
1799
- }
1800
- get httpsUrl() {
1801
- return this._httpsUrl;
1802
- }
1803
- toRequestsDict() {
1804
- return {
1805
- http: this.httpUrl || this.httpsUrl,
1806
- https: this.httpsUrl || this.httpUrl
1807
- };
1808
- }
1809
- };
1810
- /**
1811
- * Webshare proxy configuration for rotating residential proxies.
1812
- *
1813
- * Webshare is a provider offering rotating residential proxies, which is the
1814
- * most reliable way to work around being blocked by YouTube.
1815
- *
1816
- * If you don't have a Webshare account yet, you will have to create one
1817
- * at https://www.webshare.io/?referral_code=w0xno53eb50g and purchase a "Residential"
1818
- * proxy package that suits your workload (make sure NOT to purchase "Proxy Server"
1819
- * or "Static Residential"!).
1820
- *
1821
- * Once you have created an account you only need the "Proxy Username" and
1822
- * "Proxy Password" that you can find in your Webshare settings to set up this config.
1823
- *
1824
- * @example
1825
- * ```typescript
1826
- * const proxyConfig = new WebshareProxyConfig({
1827
- * proxyUsername: 'your-username',
1828
- * proxyPassword: 'your-password',
1829
- * filterIpLocations: ['us', 'de']
1830
- * });
1831
- * ```
1832
- */
1833
- var WebshareProxyConfig = class WebshareProxyConfig extends GenericProxyConfig {
1834
- /**
1835
- * Creates a Webshare proxy configuration.
1836
- *
1837
- * Once you have created a Webshare account and purchased a "Residential" package
1838
- * (make sure NOT to purchase "Proxy Server" or "Static Residential"!), this config
1839
- * class allows you to easily use it by defaulting to the most reliable proxy settings
1840
- * (rotating residential proxies).
1841
- *
1842
- * @param {Object} options - Webshare configuration options
1843
- * @param {string} options.proxyUsername - "Proxy Username" found at https://dashboard.webshare.io/proxy/settings
1844
- * @param {string} options.proxyPassword - "Proxy Password" found at https://dashboard.webshare.io/proxy/settings
1845
- * @param {string[]} [options.filterIpLocations] - If you want to limit the pool of IPs to specific countries,
1846
- * provide a list of location codes (e.g., ['us', 'de']). This can reduce latency and work around location-based restrictions.
1847
- * @param {number} [options.retriesWhenBlocked=10] - How many times to retry if a request is blocked
1848
- * @param {string} [options.domainName] - Custom domain name (defaults to p.webshare.io)
1849
- * @param {number} [options.proxyPort] - Custom proxy port (defaults to 80)
1850
- */
1851
- constructor(options) {
1852
- super({ httpUrl: "placeholder" });
1853
- this.proxyUsername = options.proxyUsername;
1854
- this.proxyPassword = options.proxyPassword;
1855
- this.domainName = options.domainName || WebshareProxyConfig.DEFAULT_DOMAIN_NAME;
1856
- this.proxyPort = options.proxyPort || WebshareProxyConfig.DEFAULT_PORT;
1857
- this.filterIpLocations = options.filterIpLocations || [];
1858
- this._retriesWhenBlocked = options.retriesWhenBlocked ?? 10;
1859
- }
1860
- /**
1861
- * Gets the full proxy URL with location filtering and rotation settings.
1862
- * @returns {string} The complete proxy URL
1863
- */
1864
- get url() {
1865
- const locationCodes = this.filterIpLocations.map((code) => `-${code.toUpperCase()}`).join("");
1866
- let username = this.proxyUsername;
1867
- const suffix = "-rotate";
1868
- if (username.endsWith(suffix)) username = username.slice(0, -7);
1869
- return `http://${username}${locationCodes}${suffix}:${this.proxyPassword}@${this.domainName}:${this.proxyPort}/`;
1870
- }
1871
- get httpUrl() {
1872
- return this.url;
1873
- }
1874
- get httpsUrl() {
1875
- return this.url;
1876
- }
1877
- toRequestsDict() {
1878
- return {
1879
- http: this.url,
1880
- https: this.url
1881
- };
1882
- }
1883
- get preventKeepingConnectionsAlive() {
1884
- return true;
1885
- }
1886
- get retriesWhenBlocked() {
1887
- return this._retriesWhenBlocked;
1888
- }
1889
- };
1890
- _WebshareProxyConfig = WebshareProxyConfig;
1891
- _WebshareProxyConfig.DEFAULT_DOMAIN_NAME = "p.webshare.io";
1892
- _WebshareProxyConfig.DEFAULT_PORT = 80;
1893
- //#endregion
1894
- //#region src/formatters/index.ts
1895
- /**
1896
- * Base abstract class for all transcript formatters.
1897
- */
1898
- var Formatter = class {};
1899
- /**
1900
- * Formatter that converts transcripts to pretty-printed JSON format.
1901
- */
1902
- var PrettyPrintFormatter = class extends Formatter {
1903
- formatTranscript(transcript) {
1904
- return JSON.stringify(transcript.toRawData(), null, 2);
1905
- }
1906
- formatTranscripts(transcripts) {
1907
- return JSON.stringify(transcripts.map((t) => t.toRawData()), null, 2);
1908
- }
1909
- };
1910
- /**
1911
- * Formatter that converts transcripts to JSON format.
1912
- */
1913
- var JSONFormatter = class extends Formatter {
1914
- formatTranscript(transcript, options) {
1915
- return JSON.stringify(transcript.toRawData(), null, options?.indent);
1916
- }
1917
- formatTranscripts(transcripts, options) {
1918
- return JSON.stringify(transcripts.map((t) => t.toRawData()), null, options?.indent);
1919
- }
1920
- };
1921
- /**
1922
- * Formatter that converts transcripts to plain text format with no timestamps.
1923
- */
1924
- var TextFormatter = class extends Formatter {
1925
- formatTranscript(transcript) {
1926
- return transcript.snippets.map((snippet) => snippet.text).join("\n");
1927
- }
1928
- formatTranscripts(transcripts) {
1929
- return transcripts.map((t) => this.formatTranscript(t)).join("\n\n\n");
1930
- }
1931
- };
1932
- /**
1933
- * Base class for subtitle formatters (SRT, WebVTT).
1934
- */
1935
- var SubtitleFormatterBase = class extends TextFormatter {
1936
- secondsToTimestamp(timeInSeconds) {
1937
- const hours = Math.floor(timeInSeconds / 3600);
1938
- const remainder = timeInSeconds % 3600;
1939
- const minutes = Math.floor(remainder / 60);
1940
- const seconds = Math.floor(remainder % 60);
1941
- const milliseconds = Math.round((timeInSeconds - Math.floor(timeInSeconds)) * 1e3);
1942
- return this.formatTimestamp(hours, minutes, seconds, milliseconds);
1943
- }
1944
- formatTranscript(transcript) {
1945
- const formattedLines = [];
1946
- for (let i = 0; i < transcript.snippets.length; i++) {
1947
- const snippet = transcript.snippets[i];
1948
- const snippetEndTime = snippet.start + snippet.duration;
1949
- const actualEndTime = i < transcript.snippets.length - 1 && transcript.snippets[i + 1].start < snippetEndTime ? transcript.snippets[i + 1].start : snippetEndTime;
1950
- const timeRangeText = `${this.secondsToTimestamp(snippet.start)} --> ${this.secondsToTimestamp(actualEndTime)}`;
1951
- formattedLines.push(this.formatSubtitleEntry(i, timeRangeText, snippet));
1952
- }
1953
- return this.formatTranscriptHeader(formattedLines);
1954
- }
1955
- };
1956
- /**
1957
- * Formatter that converts transcripts to SRT (SubRip) format.
1958
- */
1959
- var SRTFormatter = class extends SubtitleFormatterBase {
1960
- formatTimestamp(h, m, s, ms) {
1961
- const pad = (n, w) => n.toString().padStart(w, "0");
1962
- return `${pad(h, 2)}:${pad(m, 2)}:${pad(s, 2)},${pad(ms, 3)}`;
1963
- }
1964
- formatTranscriptHeader(lines) {
1965
- return lines.join("\n\n") + "\n";
1966
- }
1967
- formatSubtitleEntry(index, timeRange, snippet) {
1968
- return `${index + 1}\n${timeRange}\n${snippet.text}`;
1969
- }
1970
- };
1971
- /**
1972
- * Formatter that converts transcripts to WebVTT format.
1973
- */
1974
- var WebVTTFormatter = class extends SubtitleFormatterBase {
1975
- formatTimestamp(h, m, s, ms) {
1976
- const pad = (n, w) => n.toString().padStart(w, "0");
1977
- return `${pad(h, 2)}:${pad(m, 2)}:${pad(s, 2)}.${pad(ms, 3)}`;
1978
- }
1979
- formatTranscriptHeader(lines) {
1980
- return "WEBVTT\n\n" + lines.join("\n\n") + "\n";
1981
- }
1982
- formatSubtitleEntry(index, timeRange, snippet) {
1983
- return `${timeRange}\n${snippet.text}`;
1984
- }
1985
- };
1986
- //#endregion
1987
- //#region package.json
1988
- var package_exports = /* @__PURE__ */ require_rolldown_runtime.__exportAll({
1989
- author: () => "",
1990
- bin: () => bin,
1991
- default: () => package_default,
1992
- dependencies: () => dependencies,
1993
- description: () => description,
1994
- devDependencies: () => devDependencies,
1995
- engines: () => engines,
1996
- exports: () => exports$1,
1997
- files: () => files,
1998
- keywords: () => keywords,
1999
- license: () => license,
2000
- main: () => main$1,
2001
- module: () => module$1,
2002
- name: () => name,
2003
- peerDependencies: () => peerDependencies,
2004
- peerDependenciesMeta: () => peerDependenciesMeta,
2005
- repository: () => repository,
2006
- scripts: () => scripts,
2007
- types: () => types,
2008
- version: () => version
2009
- }), name, version, description, main$1, module$1, types, exports$1, bin, files, scripts, keywords, license, repository, dependencies, peerDependencies, peerDependenciesMeta, devDependencies, engines, package_default;
2010
- var init_package = require_rolldown_runtime.__esmMin((() => {
2011
- name = "extract-youtube";
2012
- version = "1.0.414";
2013
- description = "Fast, no-browser serverless-optimized YouTube transcript extractor, with optional cloud-ytdl audio/video download (MP3 via ffmpeg) and a media HTTP API, with a video library admin API (D1 or in-memory) and React UI: a floating YouTube player, a synced-transcript modal, video grid/list components and library admin screens";
2014
- main$1 = "dist/index.cjs";
2015
- module$1 = "dist/index.mjs";
2016
- types = "dist/index.d.ts";
2017
- exports$1 = {
2018
- ".": {
2019
- "types": "./dist/index.d.ts",
2020
- "import": "./dist/index.mjs",
2021
- "require": "./dist/index.cjs"
2022
- },
2023
- "./react": {
2024
- "types": "./dist/react/index.d.ts",
2025
- "import": "./dist/react/index.mjs",
2026
- "require": "./dist/react/index.cjs"
2027
- },
2028
- "./library": {
2029
- "types": "./dist/library/index.d.ts",
2030
- "import": "./dist/library/index.mjs",
2031
- "require": "./dist/library/index.cjs"
2032
- },
2033
- "./download": {
2034
- "types": "./dist/download/index.d.ts",
2035
- "import": "./dist/download/index.mjs",
2036
- "require": "./dist/download/index.cjs"
2037
- }
2038
- };
2039
- bin = { "extract-youtube": "dist/cli.js" };
2040
- files = ["dist", "src"];
2041
- scripts = {
2042
- "clean": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\"",
2043
- "build": "npm run clean && npm run build:lib && npm run build:cli && npm run build:react && npm run build:library && npm run build:download && npm run build:types",
2044
- "build:types": "tsc --emitDeclarationOnly --declaration --declarationMap",
2045
- "build:lib": "vite build",
2046
- "build:cli": "BUILD_CLI=true vite build",
2047
- "build:react": "BUILD_REACT=true vite build",
2048
- "build:library": "BUILD_LIBRARY=true vite build",
2049
- "build:download": "BUILD_DOWNLOAD=true vite build",
2050
- "build:bundle": "npm run build:lib && npm run build:cli && npm run build:react && npm run build:library && npm run build:download",
2051
- "build:legacy": "tsc",
2052
- "ship": "npm run build && npx standard-version --release-as patch; npm publish",
2053
- "test": "jest",
2054
- "test:coverage": "jest --coverage",
2055
- "test:speeds": "bun src/cli.ts dQw4w9WgXcQ -f speeds",
2056
- "lint": "eslint src --ext .ts"
2057
- };
2058
- keywords = [
2059
- "youtube",
2060
- "transcript",
2061
- "subtitles",
2062
- "captions",
2063
- "api",
2064
- "serverless",
2065
- "lambda",
2066
- "vercel",
2067
- "cloudflare",
2068
- "edge",
2069
- "typescript",
2070
- "youtube-transcript",
2071
- "youtube-transcript-api",
2072
- "srt",
2073
- "webvtt",
2074
- "video",
2075
- "parsing",
2076
- "extraction",
2077
- "optimized",
2078
- "react",
2079
- "floating-player",
2080
- "picture-in-picture",
2081
- "video-player",
2082
- "youtube-player",
2083
- "playlist",
2084
- "video-library",
2085
- "video-grid",
2086
- "admin",
2087
- "cloudflare-d1",
2088
- "youtube-downloader",
2089
- "mp3",
2090
- "audio-extraction",
2091
- "storybook"
2092
- ];
2093
- license = "rights.institute/PROSPER";
2094
- repository = {
2095
- "type": "git",
2096
- "url": "git+https://github.com/OpenSourceAGI/qwksearch-research-agent.git",
2097
- "directory": "packages/extract-youtube"
2098
- };
2099
- dependencies = {
2100
- "fast-xml-parser": "^5.11.1",
2101
- "html-entities": "^2.6.0",
2102
- "https-proxy-agent": "^9.1.0",
2103
- "grab-url": "^1.6.22",
2104
- "youtube-transcript-api": "^3.0.6"
2105
- };
2106
- peerDependencies = {
2107
- "cloud-ytdl": ">=1.0.5-next",
2108
- "react": ">=18",
2109
- "react-dom": ">=18",
2110
- "lucide-react": "^0.300.0 || ^1.0.0"
2111
- };
2112
- peerDependenciesMeta = {
2113
- "cloud-ytdl": { "optional": true },
2114
- "react": { "optional": true },
2115
- "react-dom": { "optional": true },
2116
- "lucide-react": { "optional": true }
2117
- };
2118
- devDependencies = {
2119
- "@types/jest": "^30.0.0",
2120
- "@types/node": "^26.5.0",
2121
- "@types/react": "^19.2.18",
2122
- "@types/react-dom": "^19.2.7",
2123
- "cloud-ytdl": "^1.0.5-next",
2124
- "jest": "^30.5.1",
2125
- "lucide-react": "^1.43.0",
2126
- "react": "^19.2.8",
2127
- "react-dom": "^19.2.8",
2128
- "terser": "^5.51.2",
2129
- "ts-jest": "^29.4.12",
2130
- "typescript": "npm:@typescript/typescript6@^6.0.2",
2131
- "vite": "^8.2.2"
2132
- };
2133
- engines = { "node": ">=14.0.0" };
2134
- package_default = {
2135
- name,
2136
- version,
2137
- description,
2138
- main: main$1,
2139
- module: module$1,
2140
- types,
2141
- exports: exports$1,
2142
- "//bin": "Spelled out as an object with a relative path. npm normalizes the string form itself and prints a notice for it on every publish.",
2143
- bin,
2144
- "//files": "Publish only what consumers resolve. Without this the tarball also carries test/, jest.config.js, tsconfig*.json and vite.config.ts. Matches extract-webpage and extract-pdf.",
2145
- files,
2146
- scripts,
2147
- keywords,
2148
- author: "",
2149
- license,
2150
- repository,
2151
- dependencies,
2152
- "//peerDependencies": "cloud-ytdl backs only the Node-only extract-youtube/download entry (audio/video download, MP3 via ffmpeg); optional so a transcript-only install stays dependency-light and Worker-safe.",
2153
- peerDependencies,
2154
- peerDependenciesMeta,
2155
- devDependencies,
2156
- engines
2157
- };
2158
- }));
2159
- //#endregion
2160
- //#region src/cli.ts
2161
- /**
2162
- * @fileoverview CLI for extracting YouTube transcripts
2163
- */
2164
- function parseArgs() {
2165
- const args = process.argv.slice(2);
2166
- const options = { videoId: "" };
2167
- for (let i = 0; i < args.length; i++) {
2168
- const arg = args[i];
2169
- switch (arg) {
2170
- case "-h":
2171
- case "--help":
2172
- options.help = true;
2173
- break;
2174
- case "-v":
2175
- case "--version":
2176
- options.version = true;
2177
- break;
2178
- case "-l":
2179
- case "--languages":
2180
- options.languages = args[++i]?.split(",").map((l) => l.trim());
2181
- break;
2182
- case "-f":
2183
- case "--format":
2184
- options.format = args[++i];
2185
- break;
2186
- case "-p":
2187
- case "--preserve-formatting":
2188
- options.preserveFormatting = true;
2189
- break;
2190
- case "--proxy":
2191
- options.proxy = args[++i];
2192
- break;
2193
- case "--webshare-user":
2194
- options.webshareUser = args[++i];
2195
- break;
2196
- case "--webshare-pass":
2197
- options.websharePass = args[++i];
2198
- break;
2199
- default: if (!arg.startsWith("-") && !options.videoId) options.videoId = arg;
2200
- }
2201
- }
2202
- return options;
2203
- }
2204
- function showHelp() {
2205
- console.log(`
2206
- extract-youtube - Extract YouTube video transcripts
2207
-
2208
- USAGE:
2209
- extract-youtube <video-id> [options]
2210
-
2211
- OPTIONS:
2212
- -h, --help Show this help message
2213
- -v, --version Show version number
2214
- -l, --languages <codes> Comma-separated language codes (e.g., en,de,fr)
2215
- -f, --format <type> Output format: json, text, srt, webvtt, pretty, speeds (default: json)
2216
- -p, --preserve-formatting Preserve text formatting (line breaks, etc.)
2217
- --proxy <url> HTTP/HTTPS proxy URL
2218
- --webshare-user <username> Webshare proxy username
2219
- --webshare-pass <password> Webshare proxy password
2220
-
2221
- EXAMPLES:
2222
- # Extract transcript in JSON format
2223
- extract-youtube jNQXAC9IVRw
2224
-
2225
- # Extract transcript in SRT format
2226
- extract-youtube jNQXAC9IVRw -f srt
2227
-
2228
- # Extract transcript with specific languages
2229
- extract-youtube jNQXAC9IVRw -l en,de
2230
-
2231
- # Extract transcript with proxy
2232
- extract-youtube jNQXAC9IVRw --proxy http://proxy.example.com:8080
2233
-
2234
- # Extract transcript with Webshare proxy
2235
- extract-youtube jNQXAC9IVRw --webshare-user myuser --webshare-pass mypass
2236
-
2237
- # Extract transcript as plain text with preserved formatting
2238
- extract-youtube jNQXAC9IVRw -f text -p
2239
-
2240
- # Extract speech speed encoding with joined text and timestamps
2241
- extract-youtube jNQXAC9IVRw -f speeds
2242
-
2243
- MEDIA (needs the optional peer: npm install cloud-ytdl; MP3 also needs ffmpeg):
2244
- extract-youtube audio <video-id> [--format mp3|m4a|webm] [--bitrate 64] [--mono] [-o file]
2245
- extract-youtube serve-media [--port 8787] # HTTP API; set MEDIA_API_KEY to require a key
2246
- Cookies for restricted videos: YOUTUBE_COOKIES env var. Proxy: --proxy <url>.
2247
- `);
2248
- }
2249
- function showVersion() {
2250
- const pkg = (init_package(), require_rolldown_runtime.__toCommonJS(package_exports).default);
2251
- console.log(`extract-youtube v${pkg.version}`);
2252
- }
2253
- /** `audio` and `serve-media`: the cloud-ytdl backed `extract-youtube/download` entry. */
2254
- async function runMediaCommand(command, args) {
2255
- const { createMediaExtractor, serveMediaApi } = await Promise.resolve().then(() => require("./download-B1w1a7Bx.js"));
2256
- const flag = (name) => {
2257
- const i = args.indexOf(name);
2258
- return i >= 0 ? args[i + 1] : void 0;
2259
- };
2260
- const shared = {
2261
- cookies: process.env.YOUTUBE_COOKIES,
2262
- proxy: flag("--proxy")
2263
- };
2264
- if (command === "serve-media") {
2265
- const port = Number(flag("--port") ?? process.env.PORT ?? 8787);
2266
- await serveMediaApi({
2267
- ...shared,
2268
- port,
2269
- apiKey: process.env.MEDIA_API_KEY
2270
- });
2271
- console.error(`extract-youtube media API listening on :${port}${process.env.MEDIA_API_KEY ? "" : " (no MEDIA_API_KEY: open to anyone)"}`);
2272
- return;
2273
- }
2274
- const videoId = args.find((a, i) => !a.startsWith("-") && !args[i - 1]?.startsWith("-"));
2275
- if (!videoId) throw new Error("Usage: extract-youtube audio <video-id> [--format mp3|m4a|webm] [-o file]");
2276
- const download = await createMediaExtractor(shared).downloadAudio(videoId, {
2277
- container: flag("--format") ?? "mp3",
2278
- bitrateKbps: flag("--bitrate") ? Number(flag("--bitrate")) : void 0,
2279
- mono: args.includes("--mono")
2280
- });
2281
- const file = flag("-o") ?? flag("--output") ?? download.filename;
2282
- const fs = await import("node:fs");
2283
- const { pipeline } = await import("node:stream/promises");
2284
- await pipeline(download.stream, fs.createWriteStream(file));
2285
- console.error(`Saved ${download.info.title} to ${file}`);
2286
- }
2287
- async function main() {
2288
- const [command, ...rest] = process.argv.slice(2);
2289
- if (command === "audio" || command === "serve-media") {
2290
- await runMediaCommand(command, rest);
2291
- return;
2292
- }
2293
- const options = parseArgs();
2294
- if (options.help) {
2295
- showHelp();
2296
- process.exit(0);
2297
- }
2298
- if (options.version) {
2299
- showVersion();
2300
- process.exit(0);
2301
- }
2302
- if (!options.videoId) {
2303
- console.error("Error: Video ID is required\n");
2304
- showHelp();
2305
- process.exit(1);
2306
- }
2307
- try {
2308
- let proxyConfig;
2309
- if (options.webshareUser && options.websharePass) proxyConfig = new WebshareProxyConfig({
2310
- proxyUsername: options.webshareUser,
2311
- proxyPassword: options.websharePass
2312
- });
2313
- else if (options.proxy) proxyConfig = new GenericProxyConfig({ httpUrl: options.proxy });
2314
- const transcript = await new YouTubeTranscriptApi({ proxyConfig }).fetchTranscript(options.videoId, {
2315
- languages: options.languages,
2316
- preserveFormatting: options.preserveFormatting
2317
- });
2318
- const format = options.format || "json";
2319
- let output;
2320
- switch (format) {
2321
- case "json":
2322
- output = new JSONFormatter().formatTranscript(transcript);
2323
- break;
2324
- case "text":
2325
- output = new TextFormatter().formatTranscript(transcript);
2326
- break;
2327
- case "srt":
2328
- output = new SRTFormatter().formatTranscript(transcript);
2329
- break;
2330
- case "webvtt":
2331
- output = new WebVTTFormatter().formatTranscript(transcript);
2332
- break;
2333
- case "pretty":
2334
- output = new PrettyPrintFormatter().formatTranscript(transcript);
2335
- break;
2336
- case "speeds": {
2337
- const { html, word_count, speeds } = encodeTranscriptSpeeds(transcript);
2338
- output = JSON.stringify({
2339
- html,
2340
- word_count,
2341
- speeds
2342
- });
2343
- break;
2344
- }
2345
- default: throw new Error(`Unknown format: ${format}`);
2346
- }
2347
- console.log(output);
2348
- process.exit(0);
2349
- } catch (error) {
2350
- if (error instanceof Error) console.error(`Error: ${error.message}`);
2351
- else console.error(`Error: ${String(error)}`);
2352
- process.exit(1);
2353
- }
2354
- }
2355
- main().catch((error) => {
2356
- console.error(`Error: ${error instanceof Error ? error.message : String(error)}`);
2357
- process.exit(1);
2358
- });
2359
- //#endregion
2360
-
2361
- //# sourceMappingURL=cli.js.map
3
+ require("./cli-Do33ETWE.js");