@malakaofc/yts-search 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/index.js +128 -0
  2. package/package.json +9 -4
  3. package/README.md +0 -3
package/index.js ADDED
@@ -0,0 +1,128 @@
1
+ // ytsearch.js — YouTube search (CommonJS). npm i axios
2
+ // Order: 1) youtube.com/results page scrape 2) youtubei innertube API 3) davidcyril fallback API
3
+ const axios = require("axios");
4
+
5
+ const UA =
6
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36";
7
+
8
+ const text = (o) =>
9
+ (o && (o.simpleText || (o.runs && o.runs.map((r) => r.text).join("")))) || "";
10
+
11
+ // ytInitialData JSON එක HTML එකෙන් ගන්නවා ({ } balance කරලා)
12
+ function extractInitialData(html) {
13
+ const marks = ["var ytInitialData = ", "var ytInitialData=", 'window["ytInitialData"] = ', "ytInitialData = "];
14
+ for (const m of marks) {
15
+ const i = html.indexOf(m);
16
+ if (i === -1) continue;
17
+ const start = html.indexOf("{", i + m.length - 1);
18
+ if (start === -1) continue;
19
+ let depth = 0, inStr = false, esc = false;
20
+ for (let j = start; j < html.length; j++) {
21
+ const c = html[j];
22
+ if (inStr) {
23
+ if (esc) esc = false;
24
+ else if (c === "\\") esc = true;
25
+ else if (c === '"') inStr = false;
26
+ } else if (c === '"') inStr = true;
27
+ else if (c === "{") depth++;
28
+ else if (c === "}" && --depth === 0) return JSON.parse(html.slice(start, j + 1));
29
+ }
30
+ }
31
+ throw new Error("ytInitialData not found (consent page / page changed)");
32
+ }
33
+
34
+ function collectVideos(node, out, seen = new Set()) {
35
+ if (!node || typeof node !== "object") return;
36
+ if (node.videoRenderer && node.videoRenderer.videoId) {
37
+ const v = node.videoRenderer;
38
+ if (seen.has(v.videoId)) return;
39
+ seen.add(v.videoId);
40
+ const thumbs = (v.thumbnail && v.thumbnail.thumbnails) || [];
41
+ const owner = v.ownerText && v.ownerText.runs && v.ownerText.runs[0];
42
+ const chPath =
43
+ owner && owner.navigationEndpoint && owner.navigationEndpoint.browseEndpoint &&
44
+ owner.navigationEndpoint.browseEndpoint.canonicalBaseUrl;
45
+ const snip = v.detailedMetadataSnippets && v.detailedMetadataSnippets[0];
46
+ out.push({
47
+ title: text(v.title),
48
+ id: v.videoId,
49
+ url: `https://www.youtube.com/watch?v=${v.videoId}`,
50
+ thumbnail: thumbs.length
51
+ ? thumbs[thumbs.length - 1].url.split("?")[0]
52
+ : `https://i.ytimg.com/vi/${v.videoId}/hqdefault.jpg`,
53
+ views: text(v.viewCountText),
54
+ duration: text(v.lengthText), // live stream වලට නැහැ
55
+ published: text(v.publishedTimeText),
56
+ author: owner ? owner.text : "",
57
+ channel: chPath ? "https://www.youtube.com" + chPath : "",
58
+ description: (snip && text(snip.snippetText)) || "",
59
+ });
60
+ return;
61
+ }
62
+ for (const k of Object.keys(node)) collectVideos(node[k], out, seen);
63
+ }
64
+
65
+ async function viaYouTube(query) {
66
+ const { data: html } = await axios.get("https://www.youtube.com/results", {
67
+ params: { search_query: query, hl: "en", gl: "US" },
68
+ headers: { "User-Agent": UA, "Accept-Language": "en-US,en;q=0.9", Cookie: "CONSENT=YES+1; SOCS=CAI" },
69
+ timeout: 12000,
70
+ });
71
+ const out = [];
72
+ collectVideos(extractInitialData(String(html)), out);
73
+ if (!out.length) throw new Error("empty results");
74
+ return out.slice(0, 20);
75
+ }
76
+
77
+ async function viaInnertube(query) {
78
+ const { data } = await axios.post(
79
+ "https://www.youtube.com/youtubei/v1/search?prettyPrint=false",
80
+ {
81
+ context: { client: { clientName: "WEB", clientVersion: "2.20250101.00.00", hl: "en", gl: "US" } },
82
+ query,
83
+ params: "EgIQAQ%3D%3D", // filter: videos only
84
+ },
85
+ { headers: { "User-Agent": UA, "Content-Type": "application/json", Cookie: "CONSENT=YES+1; SOCS=CAI" }, timeout: 12000 }
86
+ );
87
+ const out = [];
88
+ collectVideos(data, out);
89
+ if (!out.length) throw new Error("empty results");
90
+ return out.slice(0, 20);
91
+ }
92
+
93
+ async function viaDavid(query) {
94
+ const { data } = await axios.get("https://apis.davidcyriltech.my.id/youtube/search", {
95
+ params: { query },
96
+ timeout: 10000,
97
+ });
98
+ if (!data || !data.status || !Array.isArray(data.results) || !data.results.length)
99
+ throw new Error("bad fallback response");
100
+ return data.results.map((v) => ({
101
+ title: v.title, id: v.videoId, url: v.url, thumbnail: v.thumbnail,
102
+ views: v.views, duration: v.duration, published: v.published,
103
+ }));
104
+ }
105
+
106
+ const searchYouTube = async (query) => {
107
+ query = String(query || "").trim();
108
+ if (!query) throw new Error("search text එකක් දෙන්න");
109
+ const errs = [];
110
+ for (const fn of [viaYouTube, viaInnertube, viaDavid]) {
111
+ try {
112
+ return await fn(query);
113
+ } catch (e) {
114
+ errs.push(`${fn.name}: ${e.message}`);
115
+ }
116
+ }
117
+ throw new Error(`Failed to search YouTube — ${errs.join(" | ")}`);
118
+ };
119
+
120
+ module.exports = { searchYouTube };
121
+
122
+ // node ytsearch.js "lelena sinhala song"
123
+ if (require.main === module) {
124
+ searchYouTube(process.argv.slice(2).join(" ") || "lelena")
125
+ .then((r) => console.log(JSON.stringify(r.slice(0, 5), null, 2)))
126
+ .catch((e) => console.error(e.message));
127
+ }
128
+
package/package.json CHANGED
@@ -1,6 +1,11 @@
1
1
  {
2
2
  "name": "@malakaofc/yts-search",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.1",
4
+ "description": "",
5
+ "main": "index.js",
6
+ "scripts": {
7
+ "test": "echo \"Error: no test specified\" && exit 1"
8
+ },
9
+ "keywords": [],
10
+ "type": "commonjs"
11
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.