@supadata/js 1.1.3 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -15,14 +15,18 @@ npm install @supadata/js
15
15
 
16
16
  ## Usage
17
17
 
18
+ ### Initialization
19
+
18
20
  ```typescript
19
21
  import {
20
22
  Crawl,
21
23
  CrawlJob,
24
+ JobResult,
22
25
  Map,
23
26
  Scrape,
24
27
  Supadata,
25
28
  Transcript,
29
+ TranscriptOrJobId,
26
30
  YoutubeChannel,
27
31
  YoutubePlaylist,
28
32
  YoutubeVideo,
@@ -32,7 +36,44 @@ import {
32
36
  const supadata = new Supadata({
33
37
  apiKey: 'YOUR_API_KEY',
34
38
  });
39
+ ```
40
+
41
+ ### Transcripts
42
+
43
+ ```typescript
44
+ // Get transcript from any supported platform (YouTube, TikTok, Instagram, Twitter) or file
45
+ const transcriptResult = await supadata.transcript({
46
+ url: 'https://www.youtube.com/watch?v=dQw4w9WgXcQ',
47
+ lang: 'en', // optional
48
+ text: true, // optional: return plain text instead of timestamped chunks
49
+ mode: 'auto', // optional: 'native', 'auto', or 'generate'
50
+ });
51
+
52
+ // Check if we got a transcript directly or a job ID for async processing
53
+ if ('jobId' in transcriptResult) {
54
+ // For large files, we get a job ID and need to poll for results
55
+ console.log(`Started transcript job: ${transcriptResult.jobId}`);
56
+
57
+ // Poll for job status
58
+ const jobResult = await supadata.transcript.getJobStatus(
59
+ transcriptResult.jobId
60
+ );
61
+ if (jobResult.status === 'completed') {
62
+ console.log('Transcript:', jobResult.result);
63
+ } else if (jobResult.status === 'failed') {
64
+ console.error('Transcript failed:', jobResult.error);
65
+ } else {
66
+ console.log('Job status:', jobResult.status); // 'queued' or 'active'
67
+ }
68
+ } else {
69
+ // For smaller files, we get the transcript directly
70
+ console.log('Transcript:', transcriptResult);
71
+ }
72
+ ```
73
+
74
+ ### YouTube
35
75
 
76
+ ```typescript
36
77
  // Get YouTube transcript
37
78
  const transcript: Transcript = await supadata.youtube.transcript({
38
79
  url: 'https://youtu.be/dQw4w9WgXcQ',
@@ -100,6 +141,36 @@ if (batchResults.status === 'completed') {
100
141
  console.log('Batch job status:', batchResults.status);
101
142
  }
102
143
 
144
+ // Search YouTube for videos, channels, and playlists
145
+ const searchResults = await supadata.youtube.search({
146
+ query: 'never gonna give you up',
147
+ type: 'video', // optional: 'all', 'video', 'channel', 'playlist', 'movie'
148
+ uploadDate: 'all', // optional: 'all', 'hour', 'today', 'week', 'month', 'year'
149
+ duration: 'all', // optional: 'all', 'short', 'medium', 'long'
150
+ sortBy: 'relevance', // optional: 'relevance', 'rating', 'date', 'views'
151
+ features: ['hd'], // optional: array of special video features
152
+ limit: 20, // optional: max results (1-5000)
153
+ nextPageToken: '...', // optional: for pagination
154
+ });
155
+
156
+ // Search for channels
157
+ const channelSearch = await supadata.youtube.search({
158
+ query: 'fireship',
159
+ type: 'channel',
160
+ limit: 5,
161
+ });
162
+
163
+ // Search for playlists
164
+ const playlistSearch = await supadata.youtube.search({
165
+ query: 'javascript tutorials',
166
+ type: 'playlist',
167
+ limit: 10,
168
+ });
169
+ ```
170
+
171
+ ### Web
172
+
173
+ ```typescript
103
174
  // Scrape web content
104
175
  const webContent: Scrape = await supadata.web.scrape('https://supadata.ai');
105
176
 
@@ -107,7 +178,7 @@ const webContent: Scrape = await supadata.web.scrape('https://supadata.ai');
107
178
  const siteMap: Map = await supadata.web.map('https://supadata.ai');
108
179
 
109
180
  // Crawl website
110
- const crawl: Crawl = await supadata.web.crawl({
181
+ const crawl: JobId = await supadata.web.crawl({
111
182
  url: 'https://supadata.ai',
112
183
  limit: 10,
113
184
  });
package/dist/index.cjs CHANGED
@@ -1,3 +1,3 @@
1
- 'use strict';var r=class extends Error{error;details;documentationUrl;constructor(e){super(e.message||"An unexpected error occurred"),this.error=e.error||"internal-error",this.details=e.details||"An unexpected error occurred",this.documentationUrl=e.documentationUrl||"",this.name="SupadataError";}};var b={name:"@supadata/js",version:"1.1.3",description:"TypeScript / JavaScript SDK for Supadata API",homepage:"https://supadata.ai",repository:"https://github.com/supadata-ai/js",main:"./dist/index.cjs",module:"./dist/index.mjs",types:"./dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.mjs",require:"./dist/index.cjs",default:"./dist/index.mjs"}},scripts:{dev:"tsup --watch",build:"tsup",test:"node --experimental-vm-modules node_modules/jest/bin/jest.js",prepare:"npm run build",format:'prettier --write "src/**/*.{js,ts}"',"format:check":'prettier --check "src/**/*.{js,ts}"'},files:["dist","README.md"],keywords:["supadata","api","sdk","typescript","youtube","transcript","web scraping"],author:"Supadata AI",license:"MIT",devDependencies:{"@types/jest":"^29.5.14","@types/node":"^22.10.10",jest:"^29.7.0","jest-fetch-mock":"^3.0.3",prettier:"^3.4.2","ts-jest":"^29.2.5",typescript:"^5.7.3",tsup:"^8.3.6"}};var f=`supadata-js/${b.version}`,o=class{config;constructor(e){this.config=e;}async fetch(e,t={},i="GET"){let a=`${this.config.baseUrl||"https://api.supadata.ai/v1"}${e.startsWith("/")?e:`/${e}`}`;if(i==="GET"&&Object.keys(t).length>0){let u=new URLSearchParams;Object.entries(t).forEach(([n,m])=>{m!=null&&u.append(n,String(m));}),a+=`?${u.toString()}`;}return this.fetchUrl(a,i,t)}async fetchUrl(e,t="GET",i){let s={method:t,headers:{"x-api-key":this.config.apiKey,"Content-Type":"application/json","User-Agent":f}};t==="POST"&&i&&(s.body=JSON.stringify(i));let a=await fetch(e,s),u=a.headers.get("content-type");if(!a.ok)if(u?.includes("application/json")){let n=await a.json();throw new r(n)}else throw new r({error:"internal-error",message:"Unexpected error response format",details:await a.text()});try{if(!u?.includes("application/json"))throw new r({error:"internal-error",message:"Invalid response format",details:"Expected JSON response but received different content type"});return await a.json()}catch(n){throw new r({error:"internal-error",message:"Failed to parse response",details:n instanceof Error?n.message:"Unknown error"})}}};var d=class extends o{transcript=Object.assign(async e=>this.fetch("/youtube/transcript",e),{batch:async e=>(this.validateBatchLimit(e),this.fetch("/youtube/transcript/batch",e,"POST"))});video=Object.assign(async e=>this.fetch("/youtube/video",e),{batch:async e=>(this.validateBatchLimit(e),this.fetch("/youtube/video/batch",e,"POST"))});channel=Object.assign(async e=>this.fetch("/youtube/channel",e),{videos:async e=>(this.validateLimit(e),this.fetch("/youtube/channel/videos",e))});playlist=Object.assign(async e=>this.fetch("/youtube/playlist",e),{videos:async e=>(this.validateLimit(e),this.fetch("/youtube/playlist/videos",e))});batch={getBatchResults:async e=>{if(!e)throw new r({error:"invalid-request",message:"Missing jobId",details:"The jobId parameter is required to get batch results."});return this.fetch(`/youtube/batch/${e}`)}};translate=async e=>this.fetch("/youtube/transcript/translate",e);validateLimit(e){if(e.limit!=null&&e.limit!=null&&(e.limit<1||e.limit>5e3))throw new r({error:"invalid-request",message:"Invalid limit.",details:"The limit must be between 1 and 5000."})}validateBatchLimit(e){if(e.limit!=null&&e.limit!=null&&(e.limit<1||e.limit>5e3))throw new r({error:"invalid-request",message:"Invalid limit for batch operation.",details:"The limit must be between 1 and 5000."})}};var p=class extends o{async scrape(e){return this.fetch("/web/scrape",{url:e})}async map(e){return this.fetch("/web/map",{url:e})}async crawl(e){return this.fetch("/web/crawl",e,"POST")}async getCrawlResults(e){let t,i=[],s;do t=await(s?this.fetchUrl(s):this.fetch(`/web/crawl/${e}`)),t.pages&&(i=[...i,...t.pages]),s=t.next;while(s);return t}};var h=class{youtube;web;constructor(e){this.youtube=new d(e),this.web=new p(e);}};
2
- exports.BaseClient=o;exports.Supadata=h;exports.SupadataError=r;exports.WebService=p;exports.YouTubeService=d;//# sourceMappingURL=index.cjs.map
1
+ 'use strict';var x=require('cross-fetch');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var x__default=/*#__PURE__*/_interopDefault(x);var r=class extends Error{error;details;documentationUrl;constructor(e){super(e.message||"An unexpected error occurred"),this.error=e.error||"internal-error",this.details=e.details||"An unexpected error occurred",this.documentationUrl=e.documentationUrl||"",this.name="SupadataError";}};var m={version:"1.3.0"};var S=`supadata-js/${m.version}`,n=class{config;constructor(e){this.config=e;}async fetch(e,t={},s="GET"){let a=`${this.config.baseUrl||"https://api.supadata.ai/v1"}${e.startsWith("/")?e:`/${e}`}`;if(s==="GET"&&Object.keys(t).length>0){let u=new URLSearchParams;Object.entries(t).forEach(([o,p])=>{p!=null&&(Array.isArray(p)?p.forEach(f=>u.append(o,String(f))):u.append(o,String(p)));}),a+=`?${u.toString()}`;}return this.fetchUrl(a,s,t)}async fetchUrl(e,t="GET",s){let i={method:t,headers:{"x-api-key":this.config.apiKey,"Content-Type":"application/json","User-Agent":S}};t==="POST"&&s&&(i.body=JSON.stringify(s));let a=await x__default.default(e,i),u=a.headers.get("content-type");if(!a.ok)if(u?.includes("application/json")){let o=await a.json();throw new r(o)}else throw new r({error:"internal-error",message:"Unexpected error response format",details:await a.text()});try{if(!u?.includes("application/json"))throw new r({error:"internal-error",message:"Invalid response format",details:"Expected JSON response but received different content type"});return await a.json()}catch(o){throw new r({error:"internal-error",message:"Failed to parse response",details:o instanceof Error?o.message:"Unknown error"})}}};var b=class extends n{transcript=Object.assign(async e=>this.fetch("/youtube/transcript",e),{batch:async e=>(this.validateLimit(e,1,5e3,"batch operation"),this.fetch("/youtube/transcript/batch",e,"POST"))});video=Object.assign(async e=>this.fetch("/youtube/video",e),{batch:async e=>(this.validateLimit(e,1,5e3,"batch operation"),this.fetch("/youtube/video/batch",e,"POST"))});channel=Object.assign(async e=>this.fetch("/youtube/channel",e),{videos:async e=>(this.validateLimit(e),this.fetch("/youtube/channel/videos",e))});playlist=Object.assign(async e=>this.fetch("/youtube/playlist",e),{videos:async e=>(this.validateLimit(e),this.fetch("/youtube/playlist/videos",e))});batch={getBatchResults:async e=>{if(!e)throw new r({error:"invalid-request",message:"Missing jobId",details:"The jobId parameter is required to get batch results."});return this.fetch(`/youtube/batch/${e}`)}};translate=async e=>this.fetch("/youtube/transcript/translate",e);search=async e=>{if(!e.query)throw new r({error:"invalid-request",message:"Missing query parameter",details:"The query parameter is required for search."});return this.validateLimit(e,1,5e3,"search"),this.fetch("/youtube/search",e)};validateLimit(e,t=1,s=5e3,i="operation"){if(e.limit!=null&&e.limit!=null&&(e.limit<t||e.limit>s))throw new r({error:"invalid-request",message:`Invalid limit for ${i}.`,details:`The limit must be between ${t} and ${s}.`})}};var h=class extends n{async scrape(e){return this.fetch("/web/scrape",{url:e})}async map(e){return this.fetch("/web/map",{url:e})}async crawl(e){return this.fetch("/web/crawl",e,"POST")}async getCrawlResults(e){let t,s=[],i;do t=await(i?this.fetchUrl(i):this.fetch(`/web/crawl/${e}`)),t.pages&&(s=[...s,...t.pages]),i=t.next;while(i);return t}};var d=class extends n{get=async e=>this.fetch("/transcript",e);getJobStatus=async e=>{if(!e)throw new r({error:"invalid-request",message:"Missing jobId",details:"The jobId parameter is required to get transcript job status."});return this.fetch(`/transcript/${e}`)}};var g=class{youtube;web;_transcriptService;constructor(e){this.youtube=new b(e),this.web=new h(e),this._transcriptService=new d(e);}transcript=Object.assign(async e=>this._transcriptService.get(e),{getJobStatus:e=>this._transcriptService.getJobStatus(e)})};
2
+ exports.BaseClient=n;exports.Supadata=g;exports.SupadataError=r;exports.TranscriptService=d;exports.WebService=h;exports.YouTubeService=b;//# sourceMappingURL=index.cjs.map
3
3
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/types.ts","../package.json","../src/client.ts","../src/services/youtube.ts","../src/services/web.ts","../src/index.ts"],"names":["SupadataError","error","package_default","USER_AGENT","BaseClient","config","endpoint","params","method","url","queryParams","key","value","body","options","response","contentType","errorData","YouTubeService","jobId","WebService","request","pages","nextUrl","Supadata"],"mappings":"aAoDO,IAAMA,EAAN,cAA4B,KAAM,CACvC,KAAA,CAQA,QACA,gBAEA,CAAA,WAAA,CAAYC,CAKT,CAAA,CACD,MAAMA,CAAM,CAAA,OAAA,EAAW,8BAA8B,CAAA,CACrD,KAAK,KAAQA,CAAAA,CAAAA,CAAM,KAAS,EAA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AAA,CAAQ,GAEpC,CAAA,CAAA,MAAM,IAAIP,CAAc,CAAA,CACtB,KAAO,CAAA,iBAAA,CACP,QAAS,oCACT,CAAA,OAAA,CAAS,uCACX,CAAC,CAEL,CACF,MC3PaoB,CAAN,CAAA,cAAyBhB,CAAW,CAOzC,MAAM,MAAOK,CAAAA,CAAAA,CAA8B,CACzC,OAAO,IAAA,CAAK,KAAc,CAAA,aAAA,CAAe,CAAE,GAAAA,CAAAA,CAAI,CAAC,CAClD,CAQA,MAAM,GAAA,CAAIA,EAA+B,CACvC,OAAO,KAAK,KAAe,CAAA,UAAA,CAAY,CAAE,GAAA,CAAAA,CAAI,CAAC,CAChD,CAUA,MAAM,MAAMY,CAAuC,CAAA,CACjD,OAAO,IAAA,CAAK,MAAa,YAAcA,CAAAA,CAAAA,CAAS,MAAM,CACxD,CASA,MAAM,eAAA,CAAgBF,CAAkC,CAAA,CACtD,IAAIJ,CACAO,CAAAA,CAAAA,CAAkB,EAAC,CACnBC,EAEJ,GACER,CAAAA,CAAW,MAAOQ,CAAAA,CACd,KAAK,QAAmBA,CAAAA,CAAO,EAC/B,IAAK,CAAA,KAAA,CAAgB,cAAcJ,CAAK,CAAA,CAAE,CAE1CJ,CAAAA,CAAAA,CAAAA,CAAS,QACXO,CAAQ,CAAA,CAAC,GAAGA,CAAAA,CAAO,GAAGP,CAAS,CAAA,KAAK,CAEtCQ,CAAAA,CAAAA,CAAAA,CAAUR,EAAS,IACZQ,CAAAA,MAAAA,CAAAA,EAET,OAAOR,CACT,CACF,ECpDaS,IAAAA,CAAAA,CAAN,KAAe,CACX,QACA,GAET,CAAA,WAAA,CAAYnB,CAAwB,CAAA,CAClC,KAAK,OAAU,CAAA,IAAIa,CAAeb,CAAAA,CAAM,EACxC,IAAK,CAAA,GAAA,CAAM,IAAIe,CAAWf,CAAAA,CAAM,EAClC,CACF","file":"index.cjs","sourcesContent":["export interface TranscriptChunk {\n text: string;\n offset: number;\n duration: number;\n lang: string;\n}\n\nexport interface Transcript {\n content: TranscriptChunk[] | string;\n lang: string;\n availableLangs: string[];\n}\n\nexport interface TranslatedTranscript {\n content: TranscriptChunk[] | string;\n lang: string;\n}\n\nexport interface Scrape {\n url: string;\n content: string;\n name: string;\n description: string;\n ogUrl: string;\n countCharacters: number;\n urls: string[];\n}\n\nexport interface SiteMap {\n urls: string[];\n}\n\nexport interface CrawlRequest {\n url: string;\n limit?: number;\n}\n\nexport interface Crawl {\n jobId: string;\n}\n\nexport interface CrawlJob {\n status: 'scraping' | 'completed' | 'failed' | 'cancelled';\n pages?: Scrape[];\n next?: string;\n}\n\nexport interface SupadataConfig {\n apiKey: string;\n baseUrl?: string;\n}\n\nexport class SupadataError extends Error {\n error:\n | 'invalid-request'\n | 'internal-error'\n | 'transcript-unavailable'\n | 'not-found'\n | 'unauthorized'\n | 'upgrade-required'\n | 'limit-exceeded';\n details: string;\n documentationUrl: string;\n\n constructor(error: {\n error: SupadataError['error'];\n message?: string;\n details?: string;\n documentationUrl?: string;\n }) {\n super(error.message || 'An unexpected error occurred');\n this.error = error.error || 'internal-error';\n this.details = error.details || 'An unexpected error occurred';\n this.documentationUrl = error.documentationUrl || '';\n this.name = 'SupadataError';\n }\n}\n\nexport interface YoutubeVideo {\n id: string;\n title: string;\n description: string;\n duration: number;\n channel: {\n id: string;\n name: string;\n };\n tags: string[];\n thumbnail: string;\n uploadDate: string;\n viewCount: number;\n likeCount: number;\n transcriptLanguages: string[];\n}\n\nexport interface YoutubeChannel {\n id: string;\n name: string;\n handle: string;\n description: string;\n subscriberCount: number;\n videoCount: number;\n thumbnail: string;\n banner: string;\n}\n\nexport interface YoutubePlaylist {\n id: string;\n title: string;\n videoCount: number;\n viewCount: number;\n lastUpdated: string;\n description: string;\n thumbnail: string;\n}\n\nexport interface YoutubeBatchSource {\n videoIds?: string[];\n playlistId?: string;\n channelId?: string;\n limit?: number;\n}\n\nexport interface YoutubeTranscriptBatchRequest extends YoutubeBatchSource {\n lang?: string;\n text?: boolean;\n}\n\nexport interface YoutubeVideoBatchRequest extends YoutubeBatchSource {}\n\nexport interface YoutubeBatchJob {\n jobId: string;\n}\n\nexport type YoutubeBatchJobStatus =\n | 'queued'\n | 'active'\n | 'completed'\n | 'failed';\n\nexport interface YoutubeBatchResultItem {\n videoId: string;\n transcript?: Transcript;\n video?: YoutubeVideo;\n errorCode?: string;\n}\n\nexport interface YoutubeBatchStats {\n total: number;\n succeeded: number;\n failed: number;\n}\n\nexport interface YoutubeBatchResults {\n status: YoutubeBatchJobStatus;\n results?: YoutubeBatchResultItem[];\n stats?: YoutubeBatchStats;\n completedAt?: string;\n}\n","{\n \"name\": \"@supadata/js\",\n \"version\": \"1.1.3\",\n \"description\": \"TypeScript / JavaScript SDK for Supadata API\",\n \"homepage\": \"https://supadata.ai\",\n \"repository\": \"https://github.com/supadata-ai/js\",\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.mjs\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.mjs\",\n \"require\": \"./dist/index.cjs\",\n \"default\": \"./dist/index.mjs\"\n }\n },\n \"scripts\": {\n \"dev\": \"tsup --watch\",\n \"build\": \"tsup\",\n \"test\": \"node --experimental-vm-modules node_modules/jest/bin/jest.js\",\n \"prepare\": \"npm run build\",\n \"format\": \"prettier --write \\\"src/**/*.{js,ts}\\\"\",\n \"format:check\": \"prettier --check \\\"src/**/*.{js,ts}\\\"\"\n },\n \"files\": [\n \"dist\",\n \"README.md\"\n ],\n \"keywords\": [\n \"supadata\",\n \"api\",\n \"sdk\",\n \"typescript\",\n \"youtube\",\n \"transcript\",\n \"web scraping\"\n ],\n \"author\": \"Supadata AI\",\n \"license\": \"MIT\",\n \"devDependencies\": {\n \"@types/jest\": \"^29.5.14\",\n \"@types/node\": \"^22.10.10\",\n \"jest\": \"^29.7.0\",\n \"jest-fetch-mock\": \"^3.0.3\",\n \"prettier\": \"^3.4.2\",\n \"ts-jest\": \"^29.2.5\",\n \"typescript\": \"^5.7.3\",\n \"tsup\": \"^8.3.6\"\n }\n}","import { SupadataConfig, SupadataError } from './types.js';\n// @ts-expect-error: Non-TS import for version from package.json\nimport pkg from '../package.json';\n\nconst USER_AGENT = `supadata-js/${pkg.version}`;\n\nexport class BaseClient {\n protected config: SupadataConfig;\n\n constructor(config: SupadataConfig) {\n this.config = config;\n }\n\n protected async fetch<T>(\n endpoint: string,\n params: Record<string, any> = {},\n method: 'GET' | 'POST' = 'GET'\n ): Promise<T> {\n const baseUrl = this.config.baseUrl || 'https://api.supadata.ai/v1';\n let url = `${baseUrl}${\n endpoint.startsWith('/') ? endpoint : `/${endpoint}`\n }`;\n\n if (method === 'GET' && Object.keys(params).length > 0) {\n const queryParams = new URLSearchParams();\n Object.entries(params).forEach(([key, value]) => {\n if (value !== undefined && value !== null) {\n queryParams.append(key, String(value));\n }\n });\n url += `?${queryParams.toString()}`;\n }\n\n return this.fetchUrl<T>(url, method, params);\n }\n\n protected async fetchUrl<T>(\n url: string,\n method: 'GET' | 'POST' = 'GET',\n body?: Record<string, any>\n ): Promise<T> {\n const options: RequestInit = {\n method,\n headers: {\n 'x-api-key': this.config.apiKey,\n 'Content-Type': 'application/json',\n 'User-Agent': USER_AGENT,\n },\n };\n\n if (method === 'POST' && body) {\n options.body = JSON.stringify(body);\n }\n\n const response = await fetch(url, options);\n\n const contentType = response.headers.get('content-type');\n\n if (!response.ok) {\n // Handle standard API errors\n if (contentType?.includes('application/json')) {\n const errorData = await response.json();\n throw new SupadataError(errorData);\n } else {\n // Fallback for unexpected non-JSON errors\n throw new SupadataError({\n error: 'internal-error',\n message: 'Unexpected error response format',\n details: await response.text(),\n });\n }\n }\n\n try {\n if (!contentType?.includes('application/json')) {\n throw new SupadataError({\n error: 'internal-error',\n message: 'Invalid response format',\n details: 'Expected JSON response but received different content type',\n });\n }\n\n return (await response.json()) as T;\n } catch (error) {\n throw new SupadataError({\n error: 'internal-error',\n message: 'Failed to parse response',\n details: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n }\n}\n","import { BaseClient } from '../client.js';\nimport {\n SupadataError,\n Transcript,\n TranslatedTranscript,\n YoutubeBatchJob,\n YoutubeBatchResults,\n YoutubeChannel,\n YoutubePlaylist,\n YoutubeTranscriptBatchRequest,\n YoutubeVideo,\n YoutubeVideoBatchRequest,\n} from '../types.js';\n\n/**\n * Ensures exactly one property from the specified keys is provided.\n * @example\n * // Valid: { url: \"...\" } or { videoId: \"...\" }\n * // Invalid: {} or { url: \"...\", videoId: \"...\" }\n */\ntype ExactlyOne<T, Keys extends keyof T> = {\n [K in Keys]: { [P in K]-?: T[P] } & { [P in Exclude<Keys, K>]?: never };\n}[Keys] &\n Omit<T, Keys>;\n\nexport type TranscriptParams = {\n lang?: string;\n text?: boolean;\n} & ExactlyOne<{ videoId: string; url: string }, 'videoId' | 'url'>;\n\nexport interface TranslateParams extends Omit<TranscriptParams, 'lang'> {\n lang: string;\n}\n\nexport interface ResourceParams {\n id: string;\n}\n\nexport interface ChannelVideosParams extends ResourceParams {\n limit?: number;\n type?: 'video' | 'short' | 'live' | 'all';\n}\n\nexport interface PlaylistVideosParams extends ResourceParams {\n limit?: number;\n}\n\nexport interface VideoIds {\n videoIds: string[];\n shortIds: string[];\n liveIds: string[];\n}\n\nexport class YouTubeService extends BaseClient {\n /**\n * Handles YouTube Transcript operations.\n */\n transcript = Object.assign(\n /**\n * Fetches a transcript for a YouTube video.\n * @param params - Parameters for fetching the transcript\n * @param params.videoId - The YouTube video ID (mutually exclusive with url)\n * @param params.url - The YouTube video URL (mutually exclusive with videoId)\n * @param params.lang - The language code for the transcript (optional)\n * @param params.text - Whether to return only the text content (optional)\n * @returns A promise that resolves to a Transcript object\n */\n async (params: TranscriptParams): Promise<Transcript> => {\n return this.fetch<Transcript>('/youtube/transcript', params);\n },\n {\n /**\n * Batch fetches transcripts for multiple YouTube videos.\n * @param params - Parameters for the transcript batch job\n * @param params.videoIds - Array of YouTube video IDs to fetch transcripts for\n * @param params.lang - The language code for the transcripts (optional)\n * @param params.limit - Maximum number of videos to process (optional, default: 10, max: 5000)\n * @param params.text - Whether to return only the text content (optional)\n * @returns A promise that resolves to a YoutubeBatchJob object with the job ID\n */\n batch: async (\n params: YoutubeTranscriptBatchRequest\n ): Promise<YoutubeBatchJob> => {\n this.validateBatchLimit(params);\n return this.fetch<YoutubeBatchJob>(\n '/youtube/transcript/batch',\n params,\n 'POST'\n );\n },\n }\n );\n\n /**\n * Handles YouTube video operations.\n */\n video = Object.assign(\n /**\n * Fetches a YouTube video based on the provided parameters.\n * @param params - The parameters required to fetch the YouTube video\n * @param params.id - The YouTube video ID\n * @returns A promise that resolves to a YoutubeVideo object\n */\n async (params: ResourceParams): Promise<YoutubeVideo> => {\n return this.fetch<YoutubeVideo>('/youtube/video', params);\n },\n {\n /**\n * Batch fetches metadata for multiple YouTube videos.\n * @param params - Parameters for the video metadata batch job\n * @param params.videoIds - Array of YouTube video IDs to fetch metadata for\n * @param params.limit - Maximum number of videos to process (optional, default: 10, max: 5000)\n * @returns A promise that resolves to a YoutubeBatchJob object with the job ID\n */\n batch: async (\n params: YoutubeVideoBatchRequest\n ): Promise<YoutubeBatchJob> => {\n this.validateBatchLimit(params);\n return this.fetch<YoutubeBatchJob>(\n '/youtube/video/batch',\n params,\n 'POST'\n );\n },\n }\n );\n\n /**\n * Handles YouTube channel operations.\n */\n channel = Object.assign(\n /**\n * Fetches YouTube channel information.\n * @param params - The parameters required to fetch the YouTube channel information\n * @param params.id - The YouTube channel ID\n * @returns A promise that resolves to a YoutubeChannel object containing the channel information\n */\n async (params: ResourceParams): Promise<YoutubeChannel> => {\n return this.fetch<YoutubeChannel>('/youtube/channel', params);\n },\n {\n /**\n * Fetches the videos of a YouTube channel.\n * @param params - The parameters required to fetch the YouTube channel videos\n * @param params.id - The YouTube channel ID\n * @param params.limit - The maximum number of videos to fetch (default: 30, max: 5000)\n * @param params.type - The type of videos to fetch ('video', 'short', 'live', or 'all', default: 'video')\n * @returns A promise that resolves to an object containing arrays of video IDs, short IDs, and live IDs\n * @throws {SupadataError} If the limit is invalid (less than 1 or greater than 5000)\n */\n videos: async (params: ChannelVideosParams): Promise<VideoIds> => {\n this.validateLimit(params);\n return this.fetch<VideoIds>('/youtube/channel/videos', params);\n },\n }\n );\n\n /**\n * Handles YouTube playlist operations.\n */\n playlist = Object.assign(\n /**\n * Fetches a YouTube playlist.\n * @param params - The parameters required to fetch the playlist\n * @param params.id - The YouTube playlist ID\n * @returns A promise that resolves to a YoutubePlaylist object\n */\n async (params: ResourceParams): Promise<YoutubePlaylist> => {\n return this.fetch<YoutubePlaylist>('/youtube/playlist', params);\n },\n {\n /**\n * Fetches the videos of a YouTube playlist.\n * @param params - The parameters required to fetch the playlist videos\n * @param params.id - The YouTube playlist ID\n * @param params.limit - The maximum number of videos to fetch (default: 30, max: 5000)\n * @returns A promise that resolves to an object containing arrays of video IDs, short IDs, and live IDs\n * @throws {SupadataError} If the limit is invalid (less than 1 or greater than 5000)\n */\n videos: async (params: PlaylistVideosParams): Promise<VideoIds> => {\n this.validateLimit(params);\n return this.fetch<VideoIds>('/youtube/playlist/videos', params);\n },\n }\n );\n\n /**\n * Handles YouTube batch operations.\n */\n batch = {\n /**\n * Retrieves the status and results of a batch job.\n * @param jobId - The ID of the batch job\n * @returns A promise that resolves to the YoutubeBatchResults containing job status and results\n * @throws {SupadataError} If jobId is not provided\n */\n getBatchResults: async (jobId: string): Promise<YoutubeBatchResults> => {\n if (!jobId) {\n throw new SupadataError({\n error: 'invalid-request',\n message: 'Missing jobId',\n details: 'The jobId parameter is required to get batch results.',\n });\n }\n return this.fetch<YoutubeBatchResults>(`/youtube/batch/${jobId}`);\n },\n };\n\n /**\n * Translates a YouTube video transcript to a specified language.\n * @param params - Parameters for translating the transcript\n * @param params.videoId - The YouTube video ID (mutually exclusive with url)\n * @param params.url - The YouTube video URL (mutually exclusive with videoId)\n * @param params.lang - The target language code for translation\n * @param params.text - Whether to return only the text content (optional)\n * @returns A promise that resolves to a TranslatedTranscript object\n */\n translate = async (\n params: TranslateParams\n ): Promise<TranslatedTranscript> => {\n return this.fetch<TranslatedTranscript>(\n '/youtube/transcript/translate',\n params\n );\n };\n\n private validateLimit(params: { limit?: number }) {\n if (\n params.limit != undefined &&\n params.limit != null &&\n (params.limit < 1 || params.limit > 5000)\n ) {\n throw new SupadataError({\n error: 'invalid-request',\n message: 'Invalid limit.',\n details: 'The limit must be between 1 and 5000.',\n });\n }\n }\n\n // Add a specific validator for batch limits as per documentation (Max: 5000, Default: 10)\n private validateBatchLimit(params: { limit?: number }) {\n if (\n params.limit != undefined &&\n params.limit != null &&\n (params.limit < 1 || params.limit > 5000)\n ) {\n throw new SupadataError({\n error: 'invalid-request',\n message: 'Invalid limit for batch operation.',\n details: 'The limit must be between 1 and 5000.',\n });\n }\n }\n}\n","import { BaseClient } from '../client.js';\nimport { Crawl, CrawlJob, CrawlRequest, Scrape, SiteMap } from '../types.js';\n\nexport class WebService extends BaseClient {\n /**\n * Extract content from any web page to Markdown format.\n *\n * @param url - URL of the webpage to scrape\n * @returns A promise that resolves to the scraped content\n */\n async scrape(url: string): Promise<Scrape> {\n return this.fetch<Scrape>('/web/scrape', { url });\n }\n\n /**\n * Extract all links found on a webpage.\n *\n * @param url - URL of the webpage to map\n * @returns A promise that resolves to a map of URLs found on the page\n */\n async map(url: string): Promise<SiteMap> {\n return this.fetch<SiteMap>('/web/map', { url });\n }\n\n /**\n * Create a crawl job to extract content from all pages on a website.\n *\n * @param request - Crawl request parameters\n * @param request.url - URL of the website to crawl\n * @param request.limit - Maximum number of pages to crawl (default: 100, max: 5000)\n * @returns A promise that resolves to the crawl job id\n */\n async crawl(request: CrawlRequest): Promise<Crawl> {\n return this.fetch<Crawl>('/web/crawl', request, 'POST');\n }\n\n /**\n * Get the status and results of a crawl job.\n * Automatically handles pagination to retrieve all pages from the crawl.\n *\n * @param jobId - The ID of the crawl job to retrieve\n * @returns A promise that resolves to the complete crawl job results\n */\n async getCrawlResults(jobId: string): Promise<CrawlJob> {\n let response: CrawlJob;\n let pages: Scrape[] = [];\n let nextUrl: string | undefined;\n\n do {\n response = await (nextUrl\n ? this.fetchUrl<CrawlJob>(nextUrl)\n : this.fetch<CrawlJob>(`/web/crawl/${jobId}`));\n\n if (response.pages) {\n pages = [...pages, ...response.pages];\n }\n nextUrl = response.next;\n } while (nextUrl);\n\n return response;\n }\n}\n","import { SupadataConfig } from './types.js';\nimport { YouTubeService } from './services/youtube.js';\nimport { WebService } from './services/web.js';\n\nexport * from './types.js';\nexport * from './client.js';\nexport * from './services/youtube.js';\nexport * from './services/web.js';\n\nexport class Supadata {\n readonly youtube: YouTubeService;\n readonly web: WebService;\n\n constructor(config: SupadataConfig) {\n this.youtube = new YouTubeService(config);\n this.web = new WebService(config);\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/types.ts","../package.json","../src/client.ts","../src/services/youtube.ts","../src/services/web.ts","../src/services/transcript.ts","../src/index.ts"],"names":["SupadataError","error","package_default","USER_AGENT","BaseClient","config","endpoint","params","method","url","queryParams","key","value","item","body","options","response","fetch","contentType","errorData","YouTubeService","jobId","min","max","operation","WebService","request","pages","nextUrl","TranscriptService","Supadata"],"mappings":"0JAgDaA,IAAAA,CAAAA,CAAN,cAA4B,KAAM,CACvC,MAQA,OACA,CAAA,gBAAA,CAEA,YAAYC,CAKT,CAAA,CACD,MAAMA,CAAM,CAAA,OAAA,EAAW,8BAA8B,CACrD,CAAA,IAAA,CAAK,MAAQA,CAAM,CAAA,KAAA,EAAS,iBAC5B,IAAK,CAAA,OAAA,CAAUA,EAAM,OAAW,EAAA,8BAAA,CAChC,KAAK,gBAAmBA,CAAAA,CAAAA,CAAM,kBAAoB,EAClD,CAAA,IAAA,CAAK,KAAO,gBACd,CACF,ECxEA,IAAAC,CAAAA,CAAA,CAEE,QAAW,OAsDb,ECnDMC,IAAAA,CAAAA,CAAa,eAAeD,CAAI,CAAA,OAAO,CAEhCE,CAAAA,CAAAA,CAA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O,CAAA,GAAGX,CAAS,CAAA,KAAK,CAEtCY,CAAAA,CAAAA,CAAAA,CAAUZ,EAAS,IACZY,CAAAA,MAAAA,CAAAA,EAET,OAAOZ,CACT,CACF,EC5Caa,IAAAA,CAAAA,CAAN,cAAgCzB,CAAW,CAMhD,IAAM,MAAOG,CAAAA,EACJ,KAAK,KAAyB,CAAA,aAAA,CAAeA,CAAM,CAS5D,CAAA,YAAA,CAAe,MAAOc,CAAkD,EAAA,CACtE,GAAI,CAACA,CAAAA,CACH,MAAM,IAAIrB,CAAAA,CAAc,CACtB,KAAO,CAAA,iBAAA,CACP,QAAS,eACT,CAAA,OAAA,CACE,+DACJ,CAAC,CAAA,CAEH,OAAO,IAAK,CAAA,KAAA,CAA6B,eAAeqB,CAAK,CAAA,CAAE,CACjE,CACF,ECtBO,IAAMS,EAAN,KAAe,CACX,QACA,GACD,CAAA,kBAAA,CAER,YAAYzB,CAAwB,CAAA,CAClC,KAAK,OAAU,CAAA,IAAIe,EAAef,CAAM,CAAA,CACxC,KAAK,GAAM,CAAA,IAAIoB,EAAWpB,CAAM,CAAA,CAChC,KAAK,kBAAqB,CAAA,IAAIwB,EAAkBxB,CAAM,EACxD,CAMA,UAAa,CAAA,MAAA,CAAO,OAClB,MAAOE,CAAAA,EACE,KAAK,kBAAmB,CAAA,GAAA,CAAIA,CAAM,CAE3C,CAAA,CACE,aAAec,CACN,EAAA,IAAA,CAAK,mBAAmB,YAAaA,CAAAA,CAAK,CAErD,CACF,CACF","file":"index.cjs","sourcesContent":["export interface TranscriptChunk {\n text: string;\n offset: number;\n duration: number;\n lang: string;\n}\n\nexport interface Transcript {\n content: TranscriptChunk[] | string;\n lang: string;\n availableLangs: string[];\n}\n\nexport interface TranslatedTranscript {\n content: TranscriptChunk[] | string;\n lang: string;\n}\n\nexport interface Scrape {\n url: string;\n content: string;\n name: string;\n description: string;\n ogUrl: string;\n countCharacters: number;\n urls: string[];\n}\n\nexport interface SiteMap {\n urls: string[];\n}\n\nexport interface CrawlRequest {\n url: string;\n limit?: number;\n}\n\nexport interface CrawlJob {\n status: 'scraping' | 'completed' | 'failed' | 'cancelled';\n pages?: Scrape[];\n next?: string;\n}\n\nexport interface SupadataConfig {\n apiKey: string;\n baseUrl?: string;\n}\n\nexport class SupadataError extends Error {\n error:\n | 'invalid-request'\n | 'internal-error'\n | 'transcript-unavailable'\n | 'not-found'\n | 'unauthorized'\n | 'upgrade-required'\n | 'limit-exceeded';\n details: string;\n documentationUrl: string;\n\n constructor(error: {\n error: SupadataError['error'];\n message?: string;\n details?: string;\n documentationUrl?: string;\n }) {\n super(error.message || 'An unexpected error occurred');\n this.error = error.error || 'internal-error';\n this.details = error.details || 'An unexpected error occurred';\n this.documentationUrl = error.documentationUrl || '';\n this.name = 'SupadataError';\n }\n}\n\nexport interface YoutubeVideo {\n id: string;\n title: string;\n description: string;\n duration: number;\n channel: {\n id: string;\n name: string;\n };\n tags: string[];\n thumbnail: string;\n uploadDate: string;\n viewCount: number;\n likeCount: number;\n transcriptLanguages: string[];\n}\n\nexport interface YoutubeChannel {\n id: string;\n name: string;\n handle: string;\n description: string;\n subscriberCount: number;\n videoCount: number;\n thumbnail: string;\n banner: string;\n}\n\nexport interface YoutubePlaylist {\n id: string;\n title: string;\n videoCount: number;\n viewCount: number;\n lastUpdated: string;\n description: string;\n thumbnail: string;\n}\n\nexport interface YoutubeBatchSource {\n videoIds?: string[];\n playlistId?: string;\n channelId?: string;\n limit?: number;\n}\n\nexport interface YoutubeTranscriptBatchRequest extends YoutubeBatchSource {\n lang?: string;\n text?: boolean;\n}\n\nexport interface YoutubeVideoBatchRequest extends YoutubeBatchSource {}\n\nexport interface JobId {\n jobId: string;\n}\n\nexport interface YoutubeBatchJob extends JobId {}\n\nexport type JobStatus = 'queued' | 'active' | 'completed' | 'failed';\n\nexport type YoutubeBatchJobStatus = JobStatus;\n\nexport interface YoutubeBatchResultItem {\n videoId: string;\n transcript?: Transcript;\n video?: YoutubeVideo;\n errorCode?: string;\n}\n\nexport interface YoutubeBatchStats {\n total: number;\n succeeded: number;\n failed: number;\n}\n\nexport interface YoutubeBatchResults {\n status: YoutubeBatchJobStatus;\n results?: YoutubeBatchResultItem[];\n stats?: YoutubeBatchStats;\n completedAt?: string;\n}\n\nexport type TranscriptOrJobId = Transcript | JobId;\n\nexport interface JobResult<T = any> {\n status: JobStatus;\n result?: T | null;\n error?: {\n error: SupadataError['error'];\n message: string;\n details: string;\n documentationUrl?: string;\n } | null;\n}\n\n// YouTube Search Types\nexport type YoutubeSearchUploadDate =\n | 'all'\n | 'hour'\n | 'today'\n | 'week'\n | 'month'\n | 'year';\nexport type YoutubeSearchType =\n | 'all'\n | 'video'\n | 'channel'\n | 'playlist'\n | 'movie';\nexport type YoutubeSearchDuration = 'all' | 'short' | 'medium' | 'long';\nexport type YoutubeSearchSortBy = 'relevance' | 'rating' | 'date' | 'views';\n\nexport interface YoutubeSearchParams {\n query: string;\n uploadDate?: YoutubeSearchUploadDate;\n type?: YoutubeSearchType;\n duration?: YoutubeSearchDuration;\n sortBy?: YoutubeSearchSortBy;\n features?: string[];\n limit?: number;\n nextPageToken?: string;\n}\n\nexport interface YoutubeSearchVideoResult {\n type: 'video';\n id: string;\n title: string;\n description: string;\n thumbnail: string;\n duration: number;\n viewCount: number;\n uploadDate: string;\n channel: {\n id: string;\n name: string;\n };\n}\n\nexport interface YoutubeSearchChannelResult {\n type: 'channel';\n id: string;\n name: string;\n handle: string;\n description: string;\n thumbnail: string;\n subscriberCount: number;\n videoCount: number;\n}\n\nexport interface YoutubeSearchPlaylistResult {\n type: 'playlist';\n id: string;\n title: string;\n description: string;\n thumbnail: string;\n videoCount: number;\n channel: {\n id: string;\n name: string;\n };\n}\n\nexport type YoutubeSearchResult =\n | YoutubeSearchVideoResult\n | YoutubeSearchChannelResult\n | YoutubeSearchPlaylistResult;\n\nexport interface YoutubeSearchResponse {\n query: string;\n results: YoutubeSearchResult[];\n totalResults: number;\n nextPageToken?: string;\n}\n","{\n \"name\": \"@supadata/js\",\n \"version\": \"1.3.0\",\n \"description\": \"TypeScript / JavaScript SDK for Supadata API\",\n \"homepage\": \"https://supadata.ai\",\n \"repository\": \"https://github.com/supadata-ai/js\",\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.mjs\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.mjs\",\n \"require\": \"./dist/index.cjs\",\n \"default\": \"./dist/index.mjs\"\n }\n },\n \"scripts\": {\n \"dev\": \"tsup --watch\",\n \"build\": \"tsup\",\n \"test\": \"node --experimental-vm-modules node_modules/jest/bin/jest.js\",\n \"prepare\": \"npm run build\",\n \"format\": \"prettier --write \\\"src/**/*.{js,ts}\\\"\",\n \"format:check\": \"prettier --check \\\"src/**/*.{js,ts}\\\"\"\n },\n \"files\": [\n \"dist\",\n \"README.md\"\n ],\n \"keywords\": [\n \"supadata\",\n \"api\",\n \"sdk\",\n \"typescript\",\n \"youtube\",\n \"transcript\",\n \"web scraping\"\n ],\n \"author\": \"Supadata AI\",\n \"license\": \"MIT\",\n \"engines\": {\n \"node\": \">=18\"\n },\n \"dependencies\": {\n \"cross-fetch\": \"^4.0.0\"\n },\n \"devDependencies\": {\n \"@types/jest\": \"^29.5.14\",\n \"@types/node\": \"^22.10.10\",\n \"jest\": \"^29.7.0\",\n \"jest-fetch-mock\": \"^3.0.3\",\n \"prettier\": \"^3.4.2\",\n \"ts-jest\": \"^29.2.5\",\n \"typescript\": \"^5.7.3\",\n \"tsup\": \"^8.3.6\"\n }\n}","import fetch from 'cross-fetch';\nimport { SupadataConfig, SupadataError } from './types.js';\n// @ts-expect-error: Non-TS import for version from package.json\nimport pkg from '../package.json';\n\nconst USER_AGENT = `supadata-js/${pkg.version}`;\n\nexport class BaseClient {\n protected config: SupadataConfig;\n\n constructor(config: SupadataConfig) {\n this.config = config;\n }\n\n protected async fetch<T>(\n endpoint: string,\n params: Record<string, any> = {},\n method: 'GET' | 'POST' = 'GET'\n ): Promise<T> {\n const baseUrl = this.config.baseUrl || 'https://api.supadata.ai/v1';\n let url = `${baseUrl}${\n endpoint.startsWith('/') ? endpoint : `/${endpoint}`\n }`;\n\n if (method === 'GET' && Object.keys(params).length > 0) {\n const queryParams = new URLSearchParams();\n Object.entries(params).forEach(([key, value]) => {\n if (value !== undefined && value !== null) {\n if (Array.isArray(value)) {\n value.forEach((item) => queryParams.append(key, String(item)));\n } else {\n queryParams.append(key, String(value));\n }\n }\n });\n url += `?${queryParams.toString()}`;\n }\n\n return this.fetchUrl<T>(url, method, params);\n }\n\n protected async fetchUrl<T>(\n url: string,\n method: 'GET' | 'POST' = 'GET',\n body?: Record<string, any>\n ): Promise<T> {\n const options: RequestInit = {\n method,\n headers: {\n 'x-api-key': this.config.apiKey,\n 'Content-Type': 'application/json',\n 'User-Agent': USER_AGENT,\n },\n };\n\n if (method === 'POST' && body) {\n options.body = JSON.stringify(body);\n }\n\n const response = await fetch(url, options);\n\n const contentType = response.headers.get('content-type');\n\n if (!response.ok) {\n // Handle standard API errors\n if (contentType?.includes('application/json')) {\n const errorData = await response.json();\n throw new SupadataError(errorData);\n } else {\n // Fallback for unexpected non-JSON errors\n throw new SupadataError({\n error: 'internal-error',\n message: 'Unexpected error response format',\n details: await response.text(),\n });\n }\n }\n\n try {\n if (!contentType?.includes('application/json')) {\n throw new SupadataError({\n error: 'internal-error',\n message: 'Invalid response format',\n details: 'Expected JSON response but received different content type',\n });\n }\n\n return (await response.json()) as T;\n } catch (error) {\n throw new SupadataError({\n error: 'internal-error',\n message: 'Failed to parse response',\n details: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n }\n}\n","import { BaseClient } from '../client.js';\nimport {\n SupadataError,\n Transcript,\n TranslatedTranscript,\n YoutubeBatchJob,\n YoutubeBatchResults,\n YoutubeChannel,\n YoutubePlaylist,\n YoutubeTranscriptBatchRequest,\n YoutubeVideo,\n YoutubeVideoBatchRequest,\n YoutubeSearchParams,\n YoutubeSearchResponse,\n} from '../types.js';\n\n/**\n * Ensures exactly one property from the specified keys is provided.\n * @example\n * // Valid: { url: \"...\" } or { videoId: \"...\" }\n * // Invalid: {} or { url: \"...\", videoId: \"...\" }\n */\ntype ExactlyOne<T, Keys extends keyof T> = {\n [K in Keys]: { [P in K]-?: T[P] } & { [P in Exclude<Keys, K>]?: never };\n}[Keys] &\n Omit<T, Keys>;\n\nexport type TranscriptParams = {\n lang?: string;\n text?: boolean;\n} & ExactlyOne<{ videoId: string; url: string }, 'videoId' | 'url'>;\n\nexport interface TranslateParams extends Omit<TranscriptParams, 'lang'> {\n lang: string;\n}\n\nexport interface ResourceParams {\n id: string;\n}\n\nexport interface ChannelVideosParams extends ResourceParams {\n limit?: number;\n type?: 'video' | 'short' | 'live' | 'all';\n}\n\nexport interface PlaylistVideosParams extends ResourceParams {\n limit?: number;\n}\n\nexport interface VideoIds {\n videoIds: string[];\n shortIds: string[];\n liveIds: string[];\n}\n\nexport class YouTubeService extends BaseClient {\n /**\n * Handles YouTube Transcript operations.\n */\n transcript = Object.assign(\n /**\n * Fetches a transcript for a YouTube video.\n * @param params - Parameters for fetching the transcript\n * @param params.videoId - The YouTube video ID (mutually exclusive with url)\n * @param params.url - The YouTube video URL (mutually exclusive with videoId)\n * @param params.lang - The language code for the transcript (optional)\n * @param params.text - Whether to return only the text content (optional)\n * @returns A promise that resolves to a Transcript object\n */\n async (params: TranscriptParams): Promise<Transcript> => {\n return this.fetch<Transcript>('/youtube/transcript', params);\n },\n {\n /**\n * Batch fetches transcripts for multiple YouTube videos.\n * @param params - Parameters for the transcript batch job\n * @param params.videoIds - Array of YouTube video IDs to fetch transcripts for\n * @param params.lang - The language code for the transcripts (optional)\n * @param params.limit - Maximum number of videos to process (optional, default: 10, max: 5000)\n * @param params.text - Whether to return only the text content (optional)\n * @returns A promise that resolves to a YoutubeBatchJob object with the job ID\n */\n batch: async (\n params: YoutubeTranscriptBatchRequest\n ): Promise<YoutubeBatchJob> => {\n this.validateLimit(params, 1, 5000, 'batch operation');\n return this.fetch<YoutubeBatchJob>(\n '/youtube/transcript/batch',\n params,\n 'POST'\n );\n },\n }\n );\n\n /**\n * Handles YouTube video operations.\n */\n video = Object.assign(\n /**\n * Fetches a YouTube video based on the provided parameters.\n * @param params - The parameters required to fetch the YouTube video\n * @param params.id - The YouTube video ID\n * @returns A promise that resolves to a YoutubeVideo object\n */\n async (params: ResourceParams): Promise<YoutubeVideo> => {\n return this.fetch<YoutubeVideo>('/youtube/video', params);\n },\n {\n /**\n * Batch fetches metadata for multiple YouTube videos.\n * @param params - Parameters for the video metadata batch job\n * @param params.videoIds - Array of YouTube video IDs to fetch metadata for\n * @param params.limit - Maximum number of videos to process (optional, default: 10, max: 5000)\n * @returns A promise that resolves to a YoutubeBatchJob object with the job ID\n */\n batch: async (\n params: YoutubeVideoBatchRequest\n ): Promise<YoutubeBatchJob> => {\n this.validateLimit(params, 1, 5000, 'batch operation');\n return this.fetch<YoutubeBatchJob>(\n '/youtube/video/batch',\n params,\n 'POST'\n );\n },\n }\n );\n\n /**\n * Handles YouTube channel operations.\n */\n channel = Object.assign(\n /**\n * Fetches YouTube channel information.\n * @param params - The parameters required to fetch the YouTube channel information\n * @param params.id - The YouTube channel ID\n * @returns A promise that resolves to a YoutubeChannel object containing the channel information\n */\n async (params: ResourceParams): Promise<YoutubeChannel> => {\n return this.fetch<YoutubeChannel>('/youtube/channel', params);\n },\n {\n /**\n * Fetches the videos of a YouTube channel.\n * @param params - The parameters required to fetch the YouTube channel videos\n * @param params.id - The YouTube channel ID\n * @param params.limit - The maximum number of videos to fetch (default: 30, max: 5000)\n * @param params.type - The type of videos to fetch ('video', 'short', 'live', or 'all', default: 'video')\n * @returns A promise that resolves to an object containing arrays of video IDs, short IDs, and live IDs\n * @throws {SupadataError} If the limit is invalid (less than 1 or greater than 5000)\n */\n videos: async (params: ChannelVideosParams): Promise<VideoIds> => {\n this.validateLimit(params);\n return this.fetch<VideoIds>('/youtube/channel/videos', params);\n },\n }\n );\n\n /**\n * Handles YouTube playlist operations.\n */\n playlist = Object.assign(\n /**\n * Fetches a YouTube playlist.\n * @param params - The parameters required to fetch the playlist\n * @param params.id - The YouTube playlist ID\n * @returns A promise that resolves to a YoutubePlaylist object\n */\n async (params: ResourceParams): Promise<YoutubePlaylist> => {\n return this.fetch<YoutubePlaylist>('/youtube/playlist', params);\n },\n {\n /**\n * Fetches the videos of a YouTube playlist.\n * @param params - The parameters required to fetch the playlist videos\n * @param params.id - The YouTube playlist ID\n * @param params.limit - The maximum number of videos to fetch (default: 30, max: 5000)\n * @returns A promise that resolves to an object containing arrays of video IDs, short IDs, and live IDs\n * @throws {SupadataError} If the limit is invalid (less than 1 or greater than 5000)\n */\n videos: async (params: PlaylistVideosParams): Promise<VideoIds> => {\n this.validateLimit(params);\n return this.fetch<VideoIds>('/youtube/playlist/videos', params);\n },\n }\n );\n\n /**\n * Handles YouTube batch operations.\n */\n batch = {\n /**\n * Retrieves the status and results of a batch job.\n * @param jobId - The ID of the batch job\n * @returns A promise that resolves to the YoutubeBatchResults containing job status and results\n * @throws {SupadataError} If jobId is not provided\n */\n getBatchResults: async (jobId: string): Promise<YoutubeBatchResults> => {\n if (!jobId) {\n throw new SupadataError({\n error: 'invalid-request',\n message: 'Missing jobId',\n details: 'The jobId parameter is required to get batch results.',\n });\n }\n return this.fetch<YoutubeBatchResults>(`/youtube/batch/${jobId}`);\n },\n };\n\n /**\n * Translates a YouTube video transcript to a specified language.\n * @param params - Parameters for translating the transcript\n * @param params.videoId - The YouTube video ID (mutually exclusive with url)\n * @param params.url - The YouTube video URL (mutually exclusive with videoId)\n * @param params.lang - The target language code for translation\n * @param params.text - Whether to return only the text content (optional)\n * @returns A promise that resolves to a TranslatedTranscript object\n */\n translate = async (\n params: TranslateParams\n ): Promise<TranslatedTranscript> => {\n return this.fetch<TranslatedTranscript>(\n '/youtube/transcript/translate',\n params\n );\n };\n\n /**\n * Search YouTube for videos, channels, and playlists with advanced filters.\n * @param params - Parameters for the search\n * @param params.query - The search query string\n * @param params.uploadDate - Filter by upload date (\"all\", \"hour\", \"today\", \"week\", \"month\", \"year\")\n * @param params.type - Filter by content type (\"all\", \"video\", \"channel\", \"playlist\", \"movie\")\n * @param params.duration - Filter video length (\"all\", \"short\", \"medium\", \"long\")\n * @param params.sortBy - Sort results by (\"relevance\", \"rating\", \"date\", \"views\")\n * @param params.features - Array of special video features\n * @param params.limit - Maximum results to return\n * @param params.nextPageToken - Token for pagination\n * @returns A promise that resolves to a YoutubeSearchResponse object\n */\n search = async (\n params: YoutubeSearchParams\n ): Promise<YoutubeSearchResponse> => {\n if (!params.query) {\n throw new SupadataError({\n error: 'invalid-request',\n message: 'Missing query parameter',\n details: 'The query parameter is required for search.',\n });\n }\n\n this.validateLimit(params, 1, 5000, 'search');\n\n return this.fetch<YoutubeSearchResponse>('/youtube/search', params);\n };\n\n private validateLimit(\n params: { limit?: number },\n min: number = 1,\n max: number = 5000,\n operation: string = 'operation'\n ) {\n if (\n params.limit != undefined &&\n params.limit != null &&\n (params.limit < min || params.limit > max)\n ) {\n throw new SupadataError({\n error: 'invalid-request',\n message: `Invalid limit for ${operation}.`,\n details: `The limit must be between ${min} and ${max}.`,\n });\n }\n }\n}\n","import { BaseClient } from '../client.js';\nimport { CrawlJob, CrawlRequest, JobId, Scrape, SiteMap } from '../types.js';\n\nexport class WebService extends BaseClient {\n /**\n * Extract content from any web page to Markdown format.\n *\n * @param url - URL of the webpage to scrape\n * @returns A promise that resolves to the scraped content\n */\n async scrape(url: string): Promise<Scrape> {\n return this.fetch<Scrape>('/web/scrape', { url });\n }\n\n /**\n * Extract all links found on a webpage.\n *\n * @param url - URL of the webpage to map\n * @returns A promise that resolves to a map of URLs found on the page\n */\n async map(url: string): Promise<SiteMap> {\n return this.fetch<SiteMap>('/web/map', { url });\n }\n\n /**\n * Create a crawl job to extract content from all pages on a website.\n *\n * @param request - Crawl request parameters\n * @param request.url - URL of the website to crawl\n * @param request.limit - Maximum number of pages to crawl (default: 100, max: 5000)\n * @returns A promise that resolves to the crawl job id\n */\n async crawl(request: CrawlRequest): Promise<JobId> {\n return this.fetch<JobId>('/web/crawl', request, 'POST');\n }\n\n /**\n * Get the status and results of a crawl job.\n * Automatically handles pagination to retrieve all pages from the crawl.\n *\n * @param jobId - The ID of the crawl job to retrieve\n * @returns A promise that resolves to the complete crawl job results\n */\n async getCrawlResults(jobId: string): Promise<CrawlJob> {\n let response: CrawlJob;\n let pages: Scrape[] = [];\n let nextUrl: string | undefined;\n\n do {\n response = await (nextUrl\n ? this.fetchUrl<CrawlJob>(nextUrl)\n : this.fetch<CrawlJob>(`/web/crawl/${jobId}`));\n\n if (response.pages) {\n pages = [...pages, ...response.pages];\n }\n nextUrl = response.next;\n } while (nextUrl);\n\n return response;\n }\n}\n","import { BaseClient } from '../client.js';\nimport {\n JobId,\n JobResult,\n SupadataError,\n Transcript,\n TranscriptOrJobId,\n} from '../types.js';\n\nexport interface GeneralTranscriptParams {\n url: string;\n lang?: string;\n text?: boolean;\n chunkSize?: number;\n mode?: 'native' | 'auto' | 'generate';\n}\n\nexport class TranscriptService extends BaseClient {\n /**\n * Get transcript from a supported video platform or file URL.\n * @param params - Parameters for fetching the transcript\n * @returns A promise that resolves to either a Transcript or JobId for async processing\n */\n get = async (params: GeneralTranscriptParams): Promise<TranscriptOrJobId> => {\n return this.fetch<TranscriptOrJobId>('/transcript', params);\n };\n\n /**\n * Get results for a transcript job by job ID.\n * @param jobId - The ID of the transcript job\n * @returns A promise that resolves to the job result containing status and transcript if completed\n * @throws {SupadataError} If jobId is not provided\n */\n getJobStatus = async (jobId: string): Promise<JobResult<Transcript>> => {\n if (!jobId) {\n throw new SupadataError({\n error: 'invalid-request',\n message: 'Missing jobId',\n details:\n 'The jobId parameter is required to get transcript job status.',\n });\n }\n return this.fetch<JobResult<Transcript>>(`/transcript/${jobId}`);\n };\n}\n","import {\n JobResult,\n SupadataConfig,\n Transcript,\n TranscriptOrJobId,\n} from './types.js';\nimport { YouTubeService } from './services/youtube.js';\nimport { WebService } from './services/web.js';\nimport {\n TranscriptService,\n GeneralTranscriptParams,\n} from './services/transcript.js';\n\nexport * from './types.js';\nexport * from './client.js';\nexport * from './services/youtube.js';\nexport * from './services/web.js';\nexport {\n TranscriptService,\n GeneralTranscriptParams,\n} from './services/transcript.js';\n\nexport class Supadata {\n readonly youtube: YouTubeService;\n readonly web: WebService;\n private _transcriptService: TranscriptService;\n\n constructor(config: SupadataConfig) {\n this.youtube = new YouTubeService(config);\n this.web = new WebService(config);\n this._transcriptService = new TranscriptService(config);\n }\n\n /**\n * Get transcript from a supported video platform (YouTube, TikTok, Instagram, Twitter) or file URL.\n * If the video is too large to return transcript immediately, request returns a job ID.\n */\n transcript = Object.assign(\n async (params: GeneralTranscriptParams): Promise<TranscriptOrJobId> => {\n return this._transcriptService.get(params);\n },\n {\n getJobStatus: (jobId: string): Promise<JobResult<Transcript>> => {\n return this._transcriptService.getJobStatus(jobId);\n },\n }\n );\n}\n"]}
package/dist/index.d.mts CHANGED
@@ -29,9 +29,6 @@ interface CrawlRequest {
29
29
  url: string;
30
30
  limit?: number;
31
31
  }
32
- interface Crawl {
33
- jobId: string;
34
- }
35
32
  interface CrawlJob {
36
33
  status: 'scraping' | 'completed' | 'failed' | 'cancelled';
37
34
  pages?: Scrape[];
@@ -99,10 +96,13 @@ interface YoutubeTranscriptBatchRequest extends YoutubeBatchSource {
99
96
  }
100
97
  interface YoutubeVideoBatchRequest extends YoutubeBatchSource {
101
98
  }
102
- interface YoutubeBatchJob {
99
+ interface JobId {
103
100
  jobId: string;
104
101
  }
105
- type YoutubeBatchJobStatus = 'queued' | 'active' | 'completed' | 'failed';
102
+ interface YoutubeBatchJob extends JobId {
103
+ }
104
+ type JobStatus = 'queued' | 'active' | 'completed' | 'failed';
105
+ type YoutubeBatchJobStatus = JobStatus;
106
106
  interface YoutubeBatchResultItem {
107
107
  videoId: string;
108
108
  transcript?: Transcript;
@@ -120,6 +120,74 @@ interface YoutubeBatchResults {
120
120
  stats?: YoutubeBatchStats;
121
121
  completedAt?: string;
122
122
  }
123
+ type TranscriptOrJobId = Transcript | JobId;
124
+ interface JobResult<T = any> {
125
+ status: JobStatus;
126
+ result?: T | null;
127
+ error?: {
128
+ error: SupadataError['error'];
129
+ message: string;
130
+ details: string;
131
+ documentationUrl?: string;
132
+ } | null;
133
+ }
134
+ type YoutubeSearchUploadDate = 'all' | 'hour' | 'today' | 'week' | 'month' | 'year';
135
+ type YoutubeSearchType = 'all' | 'video' | 'channel' | 'playlist' | 'movie';
136
+ type YoutubeSearchDuration = 'all' | 'short' | 'medium' | 'long';
137
+ type YoutubeSearchSortBy = 'relevance' | 'rating' | 'date' | 'views';
138
+ interface YoutubeSearchParams {
139
+ query: string;
140
+ uploadDate?: YoutubeSearchUploadDate;
141
+ type?: YoutubeSearchType;
142
+ duration?: YoutubeSearchDuration;
143
+ sortBy?: YoutubeSearchSortBy;
144
+ features?: string[];
145
+ limit?: number;
146
+ nextPageToken?: string;
147
+ }
148
+ interface YoutubeSearchVideoResult {
149
+ type: 'video';
150
+ id: string;
151
+ title: string;
152
+ description: string;
153
+ thumbnail: string;
154
+ duration: number;
155
+ viewCount: number;
156
+ uploadDate: string;
157
+ channel: {
158
+ id: string;
159
+ name: string;
160
+ };
161
+ }
162
+ interface YoutubeSearchChannelResult {
163
+ type: 'channel';
164
+ id: string;
165
+ name: string;
166
+ handle: string;
167
+ description: string;
168
+ thumbnail: string;
169
+ subscriberCount: number;
170
+ videoCount: number;
171
+ }
172
+ interface YoutubeSearchPlaylistResult {
173
+ type: 'playlist';
174
+ id: string;
175
+ title: string;
176
+ description: string;
177
+ thumbnail: string;
178
+ videoCount: number;
179
+ channel: {
180
+ id: string;
181
+ name: string;
182
+ };
183
+ }
184
+ type YoutubeSearchResult = YoutubeSearchVideoResult | YoutubeSearchChannelResult | YoutubeSearchPlaylistResult;
185
+ interface YoutubeSearchResponse {
186
+ query: string;
187
+ results: YoutubeSearchResult[];
188
+ totalResults: number;
189
+ nextPageToken?: string;
190
+ }
123
191
 
124
192
  declare class BaseClient {
125
193
  protected config: SupadataConfig;
@@ -246,8 +314,21 @@ declare class YouTubeService extends BaseClient {
246
314
  * @returns A promise that resolves to a TranslatedTranscript object
247
315
  */
248
316
  translate: (params: TranslateParams) => Promise<TranslatedTranscript>;
317
+ /**
318
+ * Search YouTube for videos, channels, and playlists with advanced filters.
319
+ * @param params - Parameters for the search
320
+ * @param params.query - The search query string
321
+ * @param params.uploadDate - Filter by upload date ("all", "hour", "today", "week", "month", "year")
322
+ * @param params.type - Filter by content type ("all", "video", "channel", "playlist", "movie")
323
+ * @param params.duration - Filter video length ("all", "short", "medium", "long")
324
+ * @param params.sortBy - Sort results by ("relevance", "rating", "date", "views")
325
+ * @param params.features - Array of special video features
326
+ * @param params.limit - Maximum results to return
327
+ * @param params.nextPageToken - Token for pagination
328
+ * @returns A promise that resolves to a YoutubeSearchResponse object
329
+ */
330
+ search: (params: YoutubeSearchParams) => Promise<YoutubeSearchResponse>;
249
331
  private validateLimit;
250
- private validateBatchLimit;
251
332
  }
252
333
 
253
334
  declare class WebService extends BaseClient {
@@ -273,7 +354,7 @@ declare class WebService extends BaseClient {
273
354
  * @param request.limit - Maximum number of pages to crawl (default: 100, max: 5000)
274
355
  * @returns A promise that resolves to the crawl job id
275
356
  */
276
- crawl(request: CrawlRequest): Promise<Crawl>;
357
+ crawl(request: CrawlRequest): Promise<JobId>;
277
358
  /**
278
359
  * Get the status and results of a crawl job.
279
360
  * Automatically handles pagination to retrieve all pages from the crawl.
@@ -284,10 +365,41 @@ declare class WebService extends BaseClient {
284
365
  getCrawlResults(jobId: string): Promise<CrawlJob>;
285
366
  }
286
367
 
368
+ interface GeneralTranscriptParams {
369
+ url: string;
370
+ lang?: string;
371
+ text?: boolean;
372
+ chunkSize?: number;
373
+ mode?: 'native' | 'auto' | 'generate';
374
+ }
375
+ declare class TranscriptService extends BaseClient {
376
+ /**
377
+ * Get transcript from a supported video platform or file URL.
378
+ * @param params - Parameters for fetching the transcript
379
+ * @returns A promise that resolves to either a Transcript or JobId for async processing
380
+ */
381
+ get: (params: GeneralTranscriptParams) => Promise<TranscriptOrJobId>;
382
+ /**
383
+ * Get results for a transcript job by job ID.
384
+ * @param jobId - The ID of the transcript job
385
+ * @returns A promise that resolves to the job result containing status and transcript if completed
386
+ * @throws {SupadataError} If jobId is not provided
387
+ */
388
+ getJobStatus: (jobId: string) => Promise<JobResult<Transcript>>;
389
+ }
390
+
287
391
  declare class Supadata {
288
392
  readonly youtube: YouTubeService;
289
393
  readonly web: WebService;
394
+ private _transcriptService;
290
395
  constructor(config: SupadataConfig);
396
+ /**
397
+ * Get transcript from a supported video platform (YouTube, TikTok, Instagram, Twitter) or file URL.
398
+ * If the video is too large to return transcript immediately, request returns a job ID.
399
+ */
400
+ transcript: ((params: GeneralTranscriptParams) => Promise<TranscriptOrJobId>) & {
401
+ getJobStatus: (jobId: string) => Promise<JobResult<Transcript>>;
402
+ };
291
403
  }
292
404
 
293
- export { BaseClient, type ChannelVideosParams, type Crawl, type CrawlJob, type CrawlRequest, type PlaylistVideosParams, type ResourceParams, type Scrape, type SiteMap, Supadata, type SupadataConfig, SupadataError, type Transcript, type TranscriptChunk, type TranscriptParams, type TranslateParams, type TranslatedTranscript, type VideoIds, WebService, YouTubeService, type YoutubeBatchJob, type YoutubeBatchJobStatus, type YoutubeBatchResultItem, type YoutubeBatchResults, type YoutubeBatchSource, type YoutubeBatchStats, type YoutubeChannel, type YoutubePlaylist, type YoutubeTranscriptBatchRequest, type YoutubeVideo, type YoutubeVideoBatchRequest };
405
+ export { BaseClient, type ChannelVideosParams, type CrawlJob, type CrawlRequest, type GeneralTranscriptParams, type JobId, type JobResult, type JobStatus, type PlaylistVideosParams, type ResourceParams, type Scrape, type SiteMap, Supadata, type SupadataConfig, SupadataError, type Transcript, type TranscriptChunk, type TranscriptOrJobId, type TranscriptParams, TranscriptService, type TranslateParams, type TranslatedTranscript, type VideoIds, WebService, YouTubeService, type YoutubeBatchJob, type YoutubeBatchJobStatus, type YoutubeBatchResultItem, type YoutubeBatchResults, type YoutubeBatchSource, type YoutubeBatchStats, type YoutubeChannel, type YoutubePlaylist, type YoutubeSearchChannelResult, type YoutubeSearchDuration, type YoutubeSearchParams, type YoutubeSearchPlaylistResult, type YoutubeSearchResponse, type YoutubeSearchResult, type YoutubeSearchSortBy, type YoutubeSearchType, type YoutubeSearchUploadDate, type YoutubeSearchVideoResult, type YoutubeTranscriptBatchRequest, type YoutubeVideo, type YoutubeVideoBatchRequest };
package/dist/index.d.ts CHANGED
@@ -29,9 +29,6 @@ interface CrawlRequest {
29
29
  url: string;
30
30
  limit?: number;
31
31
  }
32
- interface Crawl {
33
- jobId: string;
34
- }
35
32
  interface CrawlJob {
36
33
  status: 'scraping' | 'completed' | 'failed' | 'cancelled';
37
34
  pages?: Scrape[];
@@ -99,10 +96,13 @@ interface YoutubeTranscriptBatchRequest extends YoutubeBatchSource {
99
96
  }
100
97
  interface YoutubeVideoBatchRequest extends YoutubeBatchSource {
101
98
  }
102
- interface YoutubeBatchJob {
99
+ interface JobId {
103
100
  jobId: string;
104
101
  }
105
- type YoutubeBatchJobStatus = 'queued' | 'active' | 'completed' | 'failed';
102
+ interface YoutubeBatchJob extends JobId {
103
+ }
104
+ type JobStatus = 'queued' | 'active' | 'completed' | 'failed';
105
+ type YoutubeBatchJobStatus = JobStatus;
106
106
  interface YoutubeBatchResultItem {
107
107
  videoId: string;
108
108
  transcript?: Transcript;
@@ -120,6 +120,74 @@ interface YoutubeBatchResults {
120
120
  stats?: YoutubeBatchStats;
121
121
  completedAt?: string;
122
122
  }
123
+ type TranscriptOrJobId = Transcript | JobId;
124
+ interface JobResult<T = any> {
125
+ status: JobStatus;
126
+ result?: T | null;
127
+ error?: {
128
+ error: SupadataError['error'];
129
+ message: string;
130
+ details: string;
131
+ documentationUrl?: string;
132
+ } | null;
133
+ }
134
+ type YoutubeSearchUploadDate = 'all' | 'hour' | 'today' | 'week' | 'month' | 'year';
135
+ type YoutubeSearchType = 'all' | 'video' | 'channel' | 'playlist' | 'movie';
136
+ type YoutubeSearchDuration = 'all' | 'short' | 'medium' | 'long';
137
+ type YoutubeSearchSortBy = 'relevance' | 'rating' | 'date' | 'views';
138
+ interface YoutubeSearchParams {
139
+ query: string;
140
+ uploadDate?: YoutubeSearchUploadDate;
141
+ type?: YoutubeSearchType;
142
+ duration?: YoutubeSearchDuration;
143
+ sortBy?: YoutubeSearchSortBy;
144
+ features?: string[];
145
+ limit?: number;
146
+ nextPageToken?: string;
147
+ }
148
+ interface YoutubeSearchVideoResult {
149
+ type: 'video';
150
+ id: string;
151
+ title: string;
152
+ description: string;
153
+ thumbnail: string;
154
+ duration: number;
155
+ viewCount: number;
156
+ uploadDate: string;
157
+ channel: {
158
+ id: string;
159
+ name: string;
160
+ };
161
+ }
162
+ interface YoutubeSearchChannelResult {
163
+ type: 'channel';
164
+ id: string;
165
+ name: string;
166
+ handle: string;
167
+ description: string;
168
+ thumbnail: string;
169
+ subscriberCount: number;
170
+ videoCount: number;
171
+ }
172
+ interface YoutubeSearchPlaylistResult {
173
+ type: 'playlist';
174
+ id: string;
175
+ title: string;
176
+ description: string;
177
+ thumbnail: string;
178
+ videoCount: number;
179
+ channel: {
180
+ id: string;
181
+ name: string;
182
+ };
183
+ }
184
+ type YoutubeSearchResult = YoutubeSearchVideoResult | YoutubeSearchChannelResult | YoutubeSearchPlaylistResult;
185
+ interface YoutubeSearchResponse {
186
+ query: string;
187
+ results: YoutubeSearchResult[];
188
+ totalResults: number;
189
+ nextPageToken?: string;
190
+ }
123
191
 
124
192
  declare class BaseClient {
125
193
  protected config: SupadataConfig;
@@ -246,8 +314,21 @@ declare class YouTubeService extends BaseClient {
246
314
  * @returns A promise that resolves to a TranslatedTranscript object
247
315
  */
248
316
  translate: (params: TranslateParams) => Promise<TranslatedTranscript>;
317
+ /**
318
+ * Search YouTube for videos, channels, and playlists with advanced filters.
319
+ * @param params - Parameters for the search
320
+ * @param params.query - The search query string
321
+ * @param params.uploadDate - Filter by upload date ("all", "hour", "today", "week", "month", "year")
322
+ * @param params.type - Filter by content type ("all", "video", "channel", "playlist", "movie")
323
+ * @param params.duration - Filter video length ("all", "short", "medium", "long")
324
+ * @param params.sortBy - Sort results by ("relevance", "rating", "date", "views")
325
+ * @param params.features - Array of special video features
326
+ * @param params.limit - Maximum results to return
327
+ * @param params.nextPageToken - Token for pagination
328
+ * @returns A promise that resolves to a YoutubeSearchResponse object
329
+ */
330
+ search: (params: YoutubeSearchParams) => Promise<YoutubeSearchResponse>;
249
331
  private validateLimit;
250
- private validateBatchLimit;
251
332
  }
252
333
 
253
334
  declare class WebService extends BaseClient {
@@ -273,7 +354,7 @@ declare class WebService extends BaseClient {
273
354
  * @param request.limit - Maximum number of pages to crawl (default: 100, max: 5000)
274
355
  * @returns A promise that resolves to the crawl job id
275
356
  */
276
- crawl(request: CrawlRequest): Promise<Crawl>;
357
+ crawl(request: CrawlRequest): Promise<JobId>;
277
358
  /**
278
359
  * Get the status and results of a crawl job.
279
360
  * Automatically handles pagination to retrieve all pages from the crawl.
@@ -284,10 +365,41 @@ declare class WebService extends BaseClient {
284
365
  getCrawlResults(jobId: string): Promise<CrawlJob>;
285
366
  }
286
367
 
368
+ interface GeneralTranscriptParams {
369
+ url: string;
370
+ lang?: string;
371
+ text?: boolean;
372
+ chunkSize?: number;
373
+ mode?: 'native' | 'auto' | 'generate';
374
+ }
375
+ declare class TranscriptService extends BaseClient {
376
+ /**
377
+ * Get transcript from a supported video platform or file URL.
378
+ * @param params - Parameters for fetching the transcript
379
+ * @returns A promise that resolves to either a Transcript or JobId for async processing
380
+ */
381
+ get: (params: GeneralTranscriptParams) => Promise<TranscriptOrJobId>;
382
+ /**
383
+ * Get results for a transcript job by job ID.
384
+ * @param jobId - The ID of the transcript job
385
+ * @returns A promise that resolves to the job result containing status and transcript if completed
386
+ * @throws {SupadataError} If jobId is not provided
387
+ */
388
+ getJobStatus: (jobId: string) => Promise<JobResult<Transcript>>;
389
+ }
390
+
287
391
  declare class Supadata {
288
392
  readonly youtube: YouTubeService;
289
393
  readonly web: WebService;
394
+ private _transcriptService;
290
395
  constructor(config: SupadataConfig);
396
+ /**
397
+ * Get transcript from a supported video platform (YouTube, TikTok, Instagram, Twitter) or file URL.
398
+ * If the video is too large to return transcript immediately, request returns a job ID.
399
+ */
400
+ transcript: ((params: GeneralTranscriptParams) => Promise<TranscriptOrJobId>) & {
401
+ getJobStatus: (jobId: string) => Promise<JobResult<Transcript>>;
402
+ };
291
403
  }
292
404
 
293
- export { BaseClient, type ChannelVideosParams, type Crawl, type CrawlJob, type CrawlRequest, type PlaylistVideosParams, type ResourceParams, type Scrape, type SiteMap, Supadata, type SupadataConfig, SupadataError, type Transcript, type TranscriptChunk, type TranscriptParams, type TranslateParams, type TranslatedTranscript, type VideoIds, WebService, YouTubeService, type YoutubeBatchJob, type YoutubeBatchJobStatus, type YoutubeBatchResultItem, type YoutubeBatchResults, type YoutubeBatchSource, type YoutubeBatchStats, type YoutubeChannel, type YoutubePlaylist, type YoutubeTranscriptBatchRequest, type YoutubeVideo, type YoutubeVideoBatchRequest };
405
+ export { BaseClient, type ChannelVideosParams, type CrawlJob, type CrawlRequest, type GeneralTranscriptParams, type JobId, type JobResult, type JobStatus, type PlaylistVideosParams, type ResourceParams, type Scrape, type SiteMap, Supadata, type SupadataConfig, SupadataError, type Transcript, type TranscriptChunk, type TranscriptOrJobId, type TranscriptParams, TranscriptService, type TranslateParams, type TranslatedTranscript, type VideoIds, WebService, YouTubeService, type YoutubeBatchJob, type YoutubeBatchJobStatus, type YoutubeBatchResultItem, type YoutubeBatchResults, type YoutubeBatchSource, type YoutubeBatchStats, type YoutubeChannel, type YoutubePlaylist, type YoutubeSearchChannelResult, type YoutubeSearchDuration, type YoutubeSearchParams, type YoutubeSearchPlaylistResult, type YoutubeSearchResponse, type YoutubeSearchResult, type YoutubeSearchSortBy, type YoutubeSearchType, type YoutubeSearchUploadDate, type YoutubeSearchVideoResult, type YoutubeTranscriptBatchRequest, type YoutubeVideo, type YoutubeVideoBatchRequest };
package/dist/index.mjs CHANGED
@@ -1,3 +1,3 @@
1
- var r=class extends Error{error;details;documentationUrl;constructor(e){super(e.message||"An unexpected error occurred"),this.error=e.error||"internal-error",this.details=e.details||"An unexpected error occurred",this.documentationUrl=e.documentationUrl||"",this.name="SupadataError";}};var h={name:"@supadata/js",version:"1.1.3",description:"TypeScript / JavaScript SDK for Supadata API",homepage:"https://supadata.ai",repository:"https://github.com/supadata-ai/js",main:"./dist/index.cjs",module:"./dist/index.mjs",types:"./dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.mjs",require:"./dist/index.cjs",default:"./dist/index.mjs"}},scripts:{dev:"tsup --watch",build:"tsup",test:"node --experimental-vm-modules node_modules/jest/bin/jest.js",prepare:"npm run build",format:'prettier --write "src/**/*.{js,ts}"',"format:check":'prettier --check "src/**/*.{js,ts}"'},files:["dist","README.md"],keywords:["supadata","api","sdk","typescript","youtube","transcript","web scraping"],author:"Supadata AI",license:"MIT",devDependencies:{"@types/jest":"^29.5.14","@types/node":"^22.10.10",jest:"^29.7.0","jest-fetch-mock":"^3.0.3",prettier:"^3.4.2","ts-jest":"^29.2.5",typescript:"^5.7.3",tsup:"^8.3.6"}};var y=`supadata-js/${h.version}`,o=class{config;constructor(e){this.config=e;}async fetch(e,t={},i="GET"){let a=`${this.config.baseUrl||"https://api.supadata.ai/v1"}${e.startsWith("/")?e:`/${e}`}`;if(i==="GET"&&Object.keys(t).length>0){let u=new URLSearchParams;Object.entries(t).forEach(([n,b])=>{b!=null&&u.append(n,String(b));}),a+=`?${u.toString()}`;}return this.fetchUrl(a,i,t)}async fetchUrl(e,t="GET",i){let s={method:t,headers:{"x-api-key":this.config.apiKey,"Content-Type":"application/json","User-Agent":y}};t==="POST"&&i&&(s.body=JSON.stringify(i));let a=await fetch(e,s),u=a.headers.get("content-type");if(!a.ok)if(u?.includes("application/json")){let n=await a.json();throw new r(n)}else throw new r({error:"internal-error",message:"Unexpected error response format",details:await a.text()});try{if(!u?.includes("application/json"))throw new r({error:"internal-error",message:"Invalid response format",details:"Expected JSON response but received different content type"});return await a.json()}catch(n){throw new r({error:"internal-error",message:"Failed to parse response",details:n instanceof Error?n.message:"Unknown error"})}}};var p=class extends o{transcript=Object.assign(async e=>this.fetch("/youtube/transcript",e),{batch:async e=>(this.validateBatchLimit(e),this.fetch("/youtube/transcript/batch",e,"POST"))});video=Object.assign(async e=>this.fetch("/youtube/video",e),{batch:async e=>(this.validateBatchLimit(e),this.fetch("/youtube/video/batch",e,"POST"))});channel=Object.assign(async e=>this.fetch("/youtube/channel",e),{videos:async e=>(this.validateLimit(e),this.fetch("/youtube/channel/videos",e))});playlist=Object.assign(async e=>this.fetch("/youtube/playlist",e),{videos:async e=>(this.validateLimit(e),this.fetch("/youtube/playlist/videos",e))});batch={getBatchResults:async e=>{if(!e)throw new r({error:"invalid-request",message:"Missing jobId",details:"The jobId parameter is required to get batch results."});return this.fetch(`/youtube/batch/${e}`)}};translate=async e=>this.fetch("/youtube/transcript/translate",e);validateLimit(e){if(e.limit!=null&&e.limit!=null&&(e.limit<1||e.limit>5e3))throw new r({error:"invalid-request",message:"Invalid limit.",details:"The limit must be between 1 and 5000."})}validateBatchLimit(e){if(e.limit!=null&&e.limit!=null&&(e.limit<1||e.limit>5e3))throw new r({error:"invalid-request",message:"Invalid limit for batch operation.",details:"The limit must be between 1 and 5000."})}};var m=class extends o{async scrape(e){return this.fetch("/web/scrape",{url:e})}async map(e){return this.fetch("/web/map",{url:e})}async crawl(e){return this.fetch("/web/crawl",e,"POST")}async getCrawlResults(e){let t,i=[],s;do t=await(s?this.fetchUrl(s):this.fetch(`/web/crawl/${e}`)),t.pages&&(i=[...i,...t.pages]),s=t.next;while(s);return t}};var g=class{youtube;web;constructor(e){this.youtube=new p(e),this.web=new m(e);}};
2
- export{o as BaseClient,g as Supadata,r as SupadataError,m as WebService,p as YouTubeService};//# sourceMappingURL=index.mjs.map
1
+ import S from'cross-fetch';var r=class extends Error{error;details;documentationUrl;constructor(e){super(e.message||"An unexpected error occurred"),this.error=e.error||"internal-error",this.details=e.details||"An unexpected error occurred",this.documentationUrl=e.documentationUrl||"",this.name="SupadataError";}};var g={version:"1.3.0"};var T=`supadata-js/${g.version}`,n=class{config;constructor(e){this.config=e;}async fetch(e,t={},s="GET"){let a=`${this.config.baseUrl||"https://api.supadata.ai/v1"}${e.startsWith("/")?e:`/${e}`}`;if(s==="GET"&&Object.keys(t).length>0){let u=new URLSearchParams;Object.entries(t).forEach(([o,p])=>{p!=null&&(Array.isArray(p)?p.forEach(y=>u.append(o,String(y))):u.append(o,String(p)));}),a+=`?${u.toString()}`;}return this.fetchUrl(a,s,t)}async fetchUrl(e,t="GET",s){let i={method:t,headers:{"x-api-key":this.config.apiKey,"Content-Type":"application/json","User-Agent":T}};t==="POST"&&s&&(i.body=JSON.stringify(s));let a=await S(e,i),u=a.headers.get("content-type");if(!a.ok)if(u?.includes("application/json")){let o=await a.json();throw new r(o)}else throw new r({error:"internal-error",message:"Unexpected error response format",details:await a.text()});try{if(!u?.includes("application/json"))throw new r({error:"internal-error",message:"Invalid response format",details:"Expected JSON response but received different content type"});return await a.json()}catch(o){throw new r({error:"internal-error",message:"Failed to parse response",details:o instanceof Error?o.message:"Unknown error"})}}};var h=class extends n{transcript=Object.assign(async e=>this.fetch("/youtube/transcript",e),{batch:async e=>(this.validateLimit(e,1,5e3,"batch operation"),this.fetch("/youtube/transcript/batch",e,"POST"))});video=Object.assign(async e=>this.fetch("/youtube/video",e),{batch:async e=>(this.validateLimit(e,1,5e3,"batch operation"),this.fetch("/youtube/video/batch",e,"POST"))});channel=Object.assign(async e=>this.fetch("/youtube/channel",e),{videos:async e=>(this.validateLimit(e),this.fetch("/youtube/channel/videos",e))});playlist=Object.assign(async e=>this.fetch("/youtube/playlist",e),{videos:async e=>(this.validateLimit(e),this.fetch("/youtube/playlist/videos",e))});batch={getBatchResults:async e=>{if(!e)throw new r({error:"invalid-request",message:"Missing jobId",details:"The jobId parameter is required to get batch results."});return this.fetch(`/youtube/batch/${e}`)}};translate=async e=>this.fetch("/youtube/transcript/translate",e);search=async e=>{if(!e.query)throw new r({error:"invalid-request",message:"Missing query parameter",details:"The query parameter is required for search."});return this.validateLimit(e,1,5e3,"search"),this.fetch("/youtube/search",e)};validateLimit(e,t=1,s=5e3,i="operation"){if(e.limit!=null&&e.limit!=null&&(e.limit<t||e.limit>s))throw new r({error:"invalid-request",message:`Invalid limit for ${i}.`,details:`The limit must be between ${t} and ${s}.`})}};var m=class extends n{async scrape(e){return this.fetch("/web/scrape",{url:e})}async map(e){return this.fetch("/web/map",{url:e})}async crawl(e){return this.fetch("/web/crawl",e,"POST")}async getCrawlResults(e){let t,s=[],i;do t=await(i?this.fetchUrl(i):this.fetch(`/web/crawl/${e}`)),t.pages&&(s=[...s,...t.pages]),i=t.next;while(i);return t}};var b=class extends n{get=async e=>this.fetch("/transcript",e);getJobStatus=async e=>{if(!e)throw new r({error:"invalid-request",message:"Missing jobId",details:"The jobId parameter is required to get transcript job status."});return this.fetch(`/transcript/${e}`)}};var f=class{youtube;web;_transcriptService;constructor(e){this.youtube=new h(e),this.web=new m(e),this._transcriptService=new b(e);}transcript=Object.assign(async e=>this._transcriptService.get(e),{getJobStatus:e=>this._transcriptService.getJobStatus(e)})};
2
+ export{n as BaseClient,f as Supadata,r as SupadataError,b as TranscriptService,m as WebService,h as YouTubeService};//# sourceMappingURL=index.mjs.map
3
3
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/types.ts","../package.json","../src/client.ts","../src/services/youtube.ts","../src/services/web.ts","../src/index.ts"],"names":["SupadataError","error","package_default","USER_AGENT","BaseClient","config","endpoint","params","method","url","queryParams","key","value","body","options","response","contentType","errorData","YouTubeService","jobId","WebService","request","pages","nextUrl","Supadata"],"mappings":"AAoDO,IAAMA,EAAN,cAA4B,KAAM,CACvC,KAAA,CAQA,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,IAAK,CAAA,GAAA,CAAM,IAAIe,CAAWf,CAAAA,CAAM,EAClC,CACF","file":"index.mjs","sourcesContent":["export interface TranscriptChunk {\n text: string;\n offset: number;\n duration: number;\n lang: string;\n}\n\nexport interface Transcript {\n content: TranscriptChunk[] | string;\n lang: string;\n availableLangs: string[];\n}\n\nexport interface TranslatedTranscript {\n content: TranscriptChunk[] | string;\n lang: string;\n}\n\nexport interface Scrape {\n url: string;\n content: string;\n name: string;\n description: string;\n ogUrl: string;\n countCharacters: number;\n urls: string[];\n}\n\nexport interface SiteMap {\n urls: string[];\n}\n\nexport interface CrawlRequest {\n url: string;\n limit?: number;\n}\n\nexport interface Crawl {\n jobId: string;\n}\n\nexport interface CrawlJob {\n status: 'scraping' | 'completed' | 'failed' | 'cancelled';\n pages?: Scrape[];\n next?: string;\n}\n\nexport interface SupadataConfig {\n apiKey: string;\n baseUrl?: string;\n}\n\nexport class SupadataError extends Error {\n error:\n | 'invalid-request'\n | 'internal-error'\n | 'transcript-unavailable'\n | 'not-found'\n | 'unauthorized'\n | 'upgrade-required'\n | 'limit-exceeded';\n details: string;\n documentationUrl: string;\n\n constructor(error: {\n error: SupadataError['error'];\n message?: string;\n details?: string;\n documentationUrl?: string;\n }) {\n super(error.message || 'An unexpected error occurred');\n this.error = error.error || 'internal-error';\n this.details = error.details || 'An unexpected error occurred';\n this.documentationUrl = error.documentationUrl || '';\n this.name = 'SupadataError';\n }\n}\n\nexport interface YoutubeVideo {\n id: string;\n title: string;\n description: string;\n duration: number;\n channel: {\n id: string;\n name: string;\n };\n tags: string[];\n thumbnail: string;\n uploadDate: string;\n viewCount: number;\n likeCount: number;\n transcriptLanguages: string[];\n}\n\nexport interface YoutubeChannel {\n id: string;\n name: string;\n handle: string;\n description: string;\n subscriberCount: number;\n videoCount: number;\n thumbnail: string;\n banner: string;\n}\n\nexport interface YoutubePlaylist {\n id: string;\n title: string;\n videoCount: number;\n viewCount: number;\n lastUpdated: string;\n description: string;\n thumbnail: string;\n}\n\nexport interface YoutubeBatchSource {\n videoIds?: string[];\n playlistId?: string;\n channelId?: string;\n limit?: number;\n}\n\nexport interface YoutubeTranscriptBatchRequest extends YoutubeBatchSource {\n lang?: string;\n text?: boolean;\n}\n\nexport interface YoutubeVideoBatchRequest extends YoutubeBatchSource {}\n\nexport interface YoutubeBatchJob {\n jobId: string;\n}\n\nexport type YoutubeBatchJobStatus =\n | 'queued'\n | 'active'\n | 'completed'\n | 'failed';\n\nexport interface YoutubeBatchResultItem {\n videoId: string;\n transcript?: Transcript;\n video?: YoutubeVideo;\n errorCode?: string;\n}\n\nexport interface YoutubeBatchStats {\n total: number;\n succeeded: number;\n failed: number;\n}\n\nexport interface YoutubeBatchResults {\n status: YoutubeBatchJobStatus;\n results?: YoutubeBatchResultItem[];\n stats?: YoutubeBatchStats;\n completedAt?: string;\n}\n","{\n \"name\": \"@supadata/js\",\n \"version\": \"1.1.3\",\n \"description\": \"TypeScript / JavaScript SDK for Supadata API\",\n \"homepage\": \"https://supadata.ai\",\n \"repository\": \"https://github.com/supadata-ai/js\",\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.mjs\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.mjs\",\n \"require\": \"./dist/index.cjs\",\n \"default\": \"./dist/index.mjs\"\n }\n },\n \"scripts\": {\n \"dev\": \"tsup --watch\",\n \"build\": \"tsup\",\n \"test\": \"node --experimental-vm-modules node_modules/jest/bin/jest.js\",\n \"prepare\": \"npm run build\",\n \"format\": \"prettier --write \\\"src/**/*.{js,ts}\\\"\",\n \"format:check\": \"prettier --check \\\"src/**/*.{js,ts}\\\"\"\n },\n \"files\": [\n \"dist\",\n \"README.md\"\n ],\n \"keywords\": [\n \"supadata\",\n \"api\",\n \"sdk\",\n \"typescript\",\n \"youtube\",\n \"transcript\",\n \"web scraping\"\n ],\n \"author\": \"Supadata AI\",\n \"license\": \"MIT\",\n \"devDependencies\": {\n \"@types/jest\": \"^29.5.14\",\n \"@types/node\": \"^22.10.10\",\n \"jest\": \"^29.7.0\",\n \"jest-fetch-mock\": \"^3.0.3\",\n \"prettier\": \"^3.4.2\",\n \"ts-jest\": \"^29.2.5\",\n \"typescript\": \"^5.7.3\",\n \"tsup\": \"^8.3.6\"\n }\n}","import { SupadataConfig, SupadataError } from './types.js';\n// @ts-expect-error: Non-TS import for version from package.json\nimport pkg from '../package.json';\n\nconst USER_AGENT = `supadata-js/${pkg.version}`;\n\nexport class BaseClient {\n protected config: SupadataConfig;\n\n constructor(config: SupadataConfig) {\n this.config = config;\n }\n\n protected async fetch<T>(\n endpoint: string,\n params: Record<string, any> = {},\n method: 'GET' | 'POST' = 'GET'\n ): Promise<T> {\n const baseUrl = this.config.baseUrl || 'https://api.supadata.ai/v1';\n let url = `${baseUrl}${\n endpoint.startsWith('/') ? endpoint : `/${endpoint}`\n }`;\n\n if (method === 'GET' && Object.keys(params).length > 0) {\n const queryParams = new URLSearchParams();\n Object.entries(params).forEach(([key, value]) => {\n if (value !== undefined && value !== null) {\n queryParams.append(key, String(value));\n }\n });\n url += `?${queryParams.toString()}`;\n }\n\n return this.fetchUrl<T>(url, method, params);\n }\n\n protected async fetchUrl<T>(\n url: string,\n method: 'GET' | 'POST' = 'GET',\n body?: Record<string, any>\n ): Promise<T> {\n const options: RequestInit = {\n method,\n headers: {\n 'x-api-key': this.config.apiKey,\n 'Content-Type': 'application/json',\n 'User-Agent': USER_AGENT,\n },\n };\n\n if (method === 'POST' && body) {\n options.body = JSON.stringify(body);\n }\n\n const response = await fetch(url, options);\n\n const contentType = response.headers.get('content-type');\n\n if (!response.ok) {\n // Handle standard API errors\n if (contentType?.includes('application/json')) {\n const errorData = await response.json();\n throw new SupadataError(errorData);\n } else {\n // Fallback for unexpected non-JSON errors\n throw new SupadataError({\n error: 'internal-error',\n message: 'Unexpected error response format',\n details: await response.text(),\n });\n }\n }\n\n try {\n if (!contentType?.includes('application/json')) {\n throw new SupadataError({\n error: 'internal-error',\n message: 'Invalid response format',\n details: 'Expected JSON response but received different content type',\n });\n }\n\n return (await response.json()) as T;\n } catch (error) {\n throw new SupadataError({\n error: 'internal-error',\n message: 'Failed to parse response',\n details: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n }\n}\n","import { BaseClient } from '../client.js';\nimport {\n SupadataError,\n Transcript,\n TranslatedTranscript,\n YoutubeBatchJob,\n YoutubeBatchResults,\n YoutubeChannel,\n YoutubePlaylist,\n YoutubeTranscriptBatchRequest,\n YoutubeVideo,\n YoutubeVideoBatchRequest,\n} from '../types.js';\n\n/**\n * Ensures exactly one property from the specified keys is provided.\n * @example\n * // Valid: { url: \"...\" } or { videoId: \"...\" }\n * // Invalid: {} or { url: \"...\", videoId: \"...\" }\n */\ntype ExactlyOne<T, Keys extends keyof T> = {\n [K in Keys]: { [P in K]-?: T[P] } & { [P in Exclude<Keys, K>]?: never };\n}[Keys] &\n Omit<T, Keys>;\n\nexport type TranscriptParams = {\n lang?: string;\n text?: boolean;\n} & ExactlyOne<{ videoId: string; url: string }, 'videoId' | 'url'>;\n\nexport interface TranslateParams extends Omit<TranscriptParams, 'lang'> {\n lang: string;\n}\n\nexport interface ResourceParams {\n id: string;\n}\n\nexport interface ChannelVideosParams extends ResourceParams {\n limit?: number;\n type?: 'video' | 'short' | 'live' | 'all';\n}\n\nexport interface PlaylistVideosParams extends ResourceParams {\n limit?: number;\n}\n\nexport interface VideoIds {\n videoIds: string[];\n shortIds: string[];\n liveIds: string[];\n}\n\nexport class YouTubeService extends BaseClient {\n /**\n * Handles YouTube Transcript operations.\n */\n transcript = Object.assign(\n /**\n * Fetches a transcript for a YouTube video.\n * @param params - Parameters for fetching the transcript\n * @param params.videoId - The YouTube video ID (mutually exclusive with url)\n * @param params.url - The YouTube video URL (mutually exclusive with videoId)\n * @param params.lang - The language code for the transcript (optional)\n * @param params.text - Whether to return only the text content (optional)\n * @returns A promise that resolves to a Transcript object\n */\n async (params: TranscriptParams): Promise<Transcript> => {\n return this.fetch<Transcript>('/youtube/transcript', params);\n },\n {\n /**\n * Batch fetches transcripts for multiple YouTube videos.\n * @param params - Parameters for the transcript batch job\n * @param params.videoIds - Array of YouTube video IDs to fetch transcripts for\n * @param params.lang - The language code for the transcripts (optional)\n * @param params.limit - Maximum number of videos to process (optional, default: 10, max: 5000)\n * @param params.text - Whether to return only the text content (optional)\n * @returns A promise that resolves to a YoutubeBatchJob object with the job ID\n */\n batch: async (\n params: YoutubeTranscriptBatchRequest\n ): Promise<YoutubeBatchJob> => {\n this.validateBatchLimit(params);\n return this.fetch<YoutubeBatchJob>(\n '/youtube/transcript/batch',\n params,\n 'POST'\n );\n },\n }\n );\n\n /**\n * Handles YouTube video operations.\n */\n video = Object.assign(\n /**\n * Fetches a YouTube video based on the provided parameters.\n * @param params - The parameters required to fetch the YouTube video\n * @param params.id - The YouTube video ID\n * @returns A promise that resolves to a YoutubeVideo object\n */\n async (params: ResourceParams): Promise<YoutubeVideo> => {\n return this.fetch<YoutubeVideo>('/youtube/video', params);\n },\n {\n /**\n * Batch fetches metadata for multiple YouTube videos.\n * @param params - Parameters for the video metadata batch job\n * @param params.videoIds - Array of YouTube video IDs to fetch metadata for\n * @param params.limit - Maximum number of videos to process (optional, default: 10, max: 5000)\n * @returns A promise that resolves to a YoutubeBatchJob object with the job ID\n */\n batch: async (\n params: YoutubeVideoBatchRequest\n ): Promise<YoutubeBatchJob> => {\n this.validateBatchLimit(params);\n return this.fetch<YoutubeBatchJob>(\n '/youtube/video/batch',\n params,\n 'POST'\n );\n },\n }\n );\n\n /**\n * Handles YouTube channel operations.\n */\n channel = Object.assign(\n /**\n * Fetches YouTube channel information.\n * @param params - The parameters required to fetch the YouTube channel information\n * @param params.id - The YouTube channel ID\n * @returns A promise that resolves to a YoutubeChannel object containing the channel information\n */\n async (params: ResourceParams): Promise<YoutubeChannel> => {\n return this.fetch<YoutubeChannel>('/youtube/channel', params);\n },\n {\n /**\n * Fetches the videos of a YouTube channel.\n * @param params - The parameters required to fetch the YouTube channel videos\n * @param params.id - The YouTube channel ID\n * @param params.limit - The maximum number of videos to fetch (default: 30, max: 5000)\n * @param params.type - The type of videos to fetch ('video', 'short', 'live', or 'all', default: 'video')\n * @returns A promise that resolves to an object containing arrays of video IDs, short IDs, and live IDs\n * @throws {SupadataError} If the limit is invalid (less than 1 or greater than 5000)\n */\n videos: async (params: ChannelVideosParams): Promise<VideoIds> => {\n this.validateLimit(params);\n return this.fetch<VideoIds>('/youtube/channel/videos', params);\n },\n }\n );\n\n /**\n * Handles YouTube playlist operations.\n */\n playlist = Object.assign(\n /**\n * Fetches a YouTube playlist.\n * @param params - The parameters required to fetch the playlist\n * @param params.id - The YouTube playlist ID\n * @returns A promise that resolves to a YoutubePlaylist object\n */\n async (params: ResourceParams): Promise<YoutubePlaylist> => {\n return this.fetch<YoutubePlaylist>('/youtube/playlist', params);\n },\n {\n /**\n * Fetches the videos of a YouTube playlist.\n * @param params - The parameters required to fetch the playlist videos\n * @param params.id - The YouTube playlist ID\n * @param params.limit - The maximum number of videos to fetch (default: 30, max: 5000)\n * @returns A promise that resolves to an object containing arrays of video IDs, short IDs, and live IDs\n * @throws {SupadataError} If the limit is invalid (less than 1 or greater than 5000)\n */\n videos: async (params: PlaylistVideosParams): Promise<VideoIds> => {\n this.validateLimit(params);\n return this.fetch<VideoIds>('/youtube/playlist/videos', params);\n },\n }\n );\n\n /**\n * Handles YouTube batch operations.\n */\n batch = {\n /**\n * Retrieves the status and results of a batch job.\n * @param jobId - The ID of the batch job\n * @returns A promise that resolves to the YoutubeBatchResults containing job status and results\n * @throws {SupadataError} If jobId is not provided\n */\n getBatchResults: async (jobId: string): Promise<YoutubeBatchResults> => {\n if (!jobId) {\n throw new SupadataError({\n error: 'invalid-request',\n message: 'Missing jobId',\n details: 'The jobId parameter is required to get batch results.',\n });\n }\n return this.fetch<YoutubeBatchResults>(`/youtube/batch/${jobId}`);\n },\n };\n\n /**\n * Translates a YouTube video transcript to a specified language.\n * @param params - Parameters for translating the transcript\n * @param params.videoId - The YouTube video ID (mutually exclusive with url)\n * @param params.url - The YouTube video URL (mutually exclusive with videoId)\n * @param params.lang - The target language code for translation\n * @param params.text - Whether to return only the text content (optional)\n * @returns A promise that resolves to a TranslatedTranscript object\n */\n translate = async (\n params: TranslateParams\n ): Promise<TranslatedTranscript> => {\n return this.fetch<TranslatedTranscript>(\n '/youtube/transcript/translate',\n params\n );\n };\n\n private validateLimit(params: { limit?: number }) {\n if (\n params.limit != undefined &&\n params.limit != null &&\n (params.limit < 1 || params.limit > 5000)\n ) {\n throw new SupadataError({\n error: 'invalid-request',\n message: 'Invalid limit.',\n details: 'The limit must be between 1 and 5000.',\n });\n }\n }\n\n // Add a specific validator for batch limits as per documentation (Max: 5000, Default: 10)\n private validateBatchLimit(params: { limit?: number }) {\n if (\n params.limit != undefined &&\n params.limit != null &&\n (params.limit < 1 || params.limit > 5000)\n ) {\n throw new SupadataError({\n error: 'invalid-request',\n message: 'Invalid limit for batch operation.',\n details: 'The limit must be between 1 and 5000.',\n });\n }\n }\n}\n","import { BaseClient } from '../client.js';\nimport { Crawl, CrawlJob, CrawlRequest, Scrape, SiteMap } from '../types.js';\n\nexport class WebService extends BaseClient {\n /**\n * Extract content from any web page to Markdown format.\n *\n * @param url - URL of the webpage to scrape\n * @returns A promise that resolves to the scraped content\n */\n async scrape(url: string): Promise<Scrape> {\n return this.fetch<Scrape>('/web/scrape', { url });\n }\n\n /**\n * Extract all links found on a webpage.\n *\n * @param url - URL of the webpage to map\n * @returns A promise that resolves to a map of URLs found on the page\n */\n async map(url: string): Promise<SiteMap> {\n return this.fetch<SiteMap>('/web/map', { url });\n }\n\n /**\n * Create a crawl job to extract content from all pages on a website.\n *\n * @param request - Crawl request parameters\n * @param request.url - URL of the website to crawl\n * @param request.limit - Maximum number of pages to crawl (default: 100, max: 5000)\n * @returns A promise that resolves to the crawl job id\n */\n async crawl(request: CrawlRequest): Promise<Crawl> {\n return this.fetch<Crawl>('/web/crawl', request, 'POST');\n }\n\n /**\n * Get the status and results of a crawl job.\n * Automatically handles pagination to retrieve all pages from the crawl.\n *\n * @param jobId - The ID of the crawl job to retrieve\n * @returns A promise that resolves to the complete crawl job results\n */\n async getCrawlResults(jobId: string): Promise<CrawlJob> {\n let response: CrawlJob;\n let pages: Scrape[] = [];\n let nextUrl: string | undefined;\n\n do {\n response = await (nextUrl\n ? this.fetchUrl<CrawlJob>(nextUrl)\n : this.fetch<CrawlJob>(`/web/crawl/${jobId}`));\n\n if (response.pages) {\n pages = [...pages, ...response.pages];\n }\n nextUrl = response.next;\n } while (nextUrl);\n\n return response;\n }\n}\n","import { SupadataConfig } from './types.js';\nimport { YouTubeService } from './services/youtube.js';\nimport { WebService } from './services/web.js';\n\nexport * from './types.js';\nexport * from './client.js';\nexport * from './services/youtube.js';\nexport * from './services/web.js';\n\nexport class Supadata {\n readonly youtube: YouTubeService;\n readonly web: WebService;\n\n constructor(config: SupadataConfig) {\n this.youtube = new YouTubeService(config);\n this.web = new WebService(config);\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/types.ts","../package.json","../src/client.ts","../src/services/youtube.ts","../src/services/web.ts","../src/services/transcript.ts","../src/index.ts"],"names":["SupadataError","error","package_default","USER_AGENT","BaseClient","config","endpoint","params","method","url","queryParams","key","value","item","body","options","response","fetch","contentType","errorData","YouTubeService","jobId","min","max","operation","WebService","request","pages","nextUrl","TranscriptService","Supadata"],"mappings":"2BAgDaA,IAAAA,CAAAA,CAAN,cAA4B,KAAM,CACvC,MAQA,OACA,CAAA,gBAAA,CAEA,YAAYC,CAKT,CAAA,CACD,MAAMA,CAAM,CAAA,OAAA,EAAW,8BAA8B,CACrD,CAAA,IAAA,CAAK,MAAQA,CAAM,CAAA,KAAA,EAAS,iBAC5B,IAAK,CAAA,OAAA,CAAUA,EAAM,OAAW,EAAA,8BAAA,CAChC,KAAK,gBAAmBA,CAAAA,CAAAA,CAAM,kBAAoB,EAClD,CAAA,IAAA,CAAK,K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AO,CAC/B,CAAA,IAAA,CAAK,MAAgB,CAAcP,WAAAA,EAAAA,CAAK,EAAE,CAE1CL,CAAAA,CAAAA,CAAAA,CAAS,QACXW,CAAQ,CAAA,CAAC,GAAGA,CAAO,CAAA,GAAGX,CAAS,CAAA,KAAK,CAEtCY,CAAAA,CAAAA,CAAAA,CAAUZ,EAAS,IACZY,CAAAA,MAAAA,CAAAA,EAET,OAAOZ,CACT,CACF,EC5Caa,IAAAA,CAAAA,CAAN,cAAgCzB,CAAW,CAMhD,IAAM,MAAOG,CAAAA,EACJ,KAAK,KAAyB,CAAA,aAAA,CAAeA,CAAM,CAS5D,CAAA,YAAA,CAAe,MAAOc,CAAkD,EAAA,CACtE,GAAI,CAACA,CAAAA,CACH,MAAM,IAAIrB,CAAAA,CAAc,CACtB,KAAO,CAAA,iBAAA,CACP,QAAS,eACT,CAAA,OAAA,CACE,+DACJ,CAAC,CAAA,CAEH,OAAO,IAAK,CAAA,KAAA,CAA6B,eAAeqB,CAAK,CAAA,CAAE,CACjE,CACF,ECtBO,IAAMS,EAAN,KAAe,CACX,QACA,GACD,CAAA,kBAAA,CAER,YAAYzB,CAAwB,CAAA,CAClC,KAAK,OAAU,CAAA,IAAIe,EAAef,CAAM,CAAA,CACxC,KAAK,GAAM,CAAA,IAAIoB,EAAWpB,CAAM,CAAA,CAChC,KAAK,kBAAqB,CAAA,IAAIwB,EAAkBxB,CAAM,EACxD,CAMA,UAAa,CAAA,MAAA,CAAO,OAClB,MAAOE,CAAAA,EACE,KAAK,kBAAmB,CAAA,GAAA,CAAIA,CAAM,CAE3C,CAAA,CACE,aAAec,CACN,EAAA,IAAA,CAAK,mBAAmB,YAAaA,CAAAA,CAAK,CAErD,CACF,CACF","file":"index.mjs","sourcesContent":["export interface TranscriptChunk {\n text: string;\n offset: number;\n duration: number;\n lang: string;\n}\n\nexport interface Transcript {\n content: TranscriptChunk[] | string;\n lang: string;\n availableLangs: string[];\n}\n\nexport interface TranslatedTranscript {\n content: TranscriptChunk[] | string;\n lang: string;\n}\n\nexport interface Scrape {\n url: string;\n content: string;\n name: string;\n description: string;\n ogUrl: string;\n countCharacters: number;\n urls: string[];\n}\n\nexport interface SiteMap {\n urls: string[];\n}\n\nexport interface CrawlRequest {\n url: string;\n limit?: number;\n}\n\nexport interface CrawlJob {\n status: 'scraping' | 'completed' | 'failed' | 'cancelled';\n pages?: Scrape[];\n next?: string;\n}\n\nexport interface SupadataConfig {\n apiKey: string;\n baseUrl?: string;\n}\n\nexport class SupadataError extends Error {\n error:\n | 'invalid-request'\n | 'internal-error'\n | 'transcript-unavailable'\n | 'not-found'\n | 'unauthorized'\n | 'upgrade-required'\n | 'limit-exceeded';\n details: string;\n documentationUrl: string;\n\n constructor(error: {\n error: SupadataError['error'];\n message?: string;\n details?: string;\n documentationUrl?: string;\n }) {\n super(error.message || 'An unexpected error occurred');\n this.error = error.error || 'internal-error';\n this.details = error.details || 'An unexpected error occurred';\n this.documentationUrl = error.documentationUrl || '';\n this.name = 'SupadataError';\n }\n}\n\nexport interface YoutubeVideo {\n id: string;\n title: string;\n description: string;\n duration: number;\n channel: {\n id: string;\n name: string;\n };\n tags: string[];\n thumbnail: string;\n uploadDate: string;\n viewCount: number;\n likeCount: number;\n transcriptLanguages: string[];\n}\n\nexport interface YoutubeChannel {\n id: string;\n name: string;\n handle: string;\n description: string;\n subscriberCount: number;\n videoCount: number;\n thumbnail: string;\n banner: string;\n}\n\nexport interface YoutubePlaylist {\n id: string;\n title: string;\n videoCount: number;\n viewCount: number;\n lastUpdated: string;\n description: string;\n thumbnail: string;\n}\n\nexport interface YoutubeBatchSource {\n videoIds?: string[];\n playlistId?: string;\n channelId?: string;\n limit?: number;\n}\n\nexport interface YoutubeTranscriptBatchRequest extends YoutubeBatchSource {\n lang?: string;\n text?: boolean;\n}\n\nexport interface YoutubeVideoBatchRequest extends YoutubeBatchSource {}\n\nexport interface JobId {\n jobId: string;\n}\n\nexport interface YoutubeBatchJob extends JobId {}\n\nexport type JobStatus = 'queued' | 'active' | 'completed' | 'failed';\n\nexport type YoutubeBatchJobStatus = JobStatus;\n\nexport interface YoutubeBatchResultItem {\n videoId: string;\n transcript?: Transcript;\n video?: YoutubeVideo;\n errorCode?: string;\n}\n\nexport interface YoutubeBatchStats {\n total: number;\n succeeded: number;\n failed: number;\n}\n\nexport interface YoutubeBatchResults {\n status: YoutubeBatchJobStatus;\n results?: YoutubeBatchResultItem[];\n stats?: YoutubeBatchStats;\n completedAt?: string;\n}\n\nexport type TranscriptOrJobId = Transcript | JobId;\n\nexport interface JobResult<T = any> {\n status: JobStatus;\n result?: T | null;\n error?: {\n error: SupadataError['error'];\n message: string;\n details: string;\n documentationUrl?: string;\n } | null;\n}\n\n// YouTube Search Types\nexport type YoutubeSearchUploadDate =\n | 'all'\n | 'hour'\n | 'today'\n | 'week'\n | 'month'\n | 'year';\nexport type YoutubeSearchType =\n | 'all'\n | 'video'\n | 'channel'\n | 'playlist'\n | 'movie';\nexport type YoutubeSearchDuration = 'all' | 'short' | 'medium' | 'long';\nexport type YoutubeSearchSortBy = 'relevance' | 'rating' | 'date' | 'views';\n\nexport interface YoutubeSearchParams {\n query: string;\n uploadDate?: YoutubeSearchUploadDate;\n type?: YoutubeSearchType;\n duration?: YoutubeSearchDuration;\n sortBy?: YoutubeSearchSortBy;\n features?: string[];\n limit?: number;\n nextPageToken?: string;\n}\n\nexport interface YoutubeSearchVideoResult {\n type: 'video';\n id: string;\n title: string;\n description: string;\n thumbnail: string;\n duration: number;\n viewCount: number;\n uploadDate: string;\n channel: {\n id: string;\n name: string;\n };\n}\n\nexport interface YoutubeSearchChannelResult {\n type: 'channel';\n id: string;\n name: string;\n handle: string;\n description: string;\n thumbnail: string;\n subscriberCount: number;\n videoCount: number;\n}\n\nexport interface YoutubeSearchPlaylistResult {\n type: 'playlist';\n id: string;\n title: string;\n description: string;\n thumbnail: string;\n videoCount: number;\n channel: {\n id: string;\n name: string;\n };\n}\n\nexport type YoutubeSearchResult =\n | YoutubeSearchVideoResult\n | YoutubeSearchChannelResult\n | YoutubeSearchPlaylistResult;\n\nexport interface YoutubeSearchResponse {\n query: string;\n results: YoutubeSearchResult[];\n totalResults: number;\n nextPageToken?: string;\n}\n","{\n \"name\": \"@supadata/js\",\n \"version\": \"1.3.0\",\n \"description\": \"TypeScript / JavaScript SDK for Supadata API\",\n \"homepage\": \"https://supadata.ai\",\n \"repository\": \"https://github.com/supadata-ai/js\",\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.mjs\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.mjs\",\n \"require\": \"./dist/index.cjs\",\n \"default\": \"./dist/index.mjs\"\n }\n },\n \"scripts\": {\n \"dev\": \"tsup --watch\",\n \"build\": \"tsup\",\n \"test\": \"node --experimental-vm-modules node_modules/jest/bin/jest.js\",\n \"prepare\": \"npm run build\",\n \"format\": \"prettier --write \\\"src/**/*.{js,ts}\\\"\",\n \"format:check\": \"prettier --check \\\"src/**/*.{js,ts}\\\"\"\n },\n \"files\": [\n \"dist\",\n \"README.md\"\n ],\n \"keywords\": [\n \"supadata\",\n \"api\",\n \"sdk\",\n \"typescript\",\n \"youtube\",\n \"transcript\",\n \"web scraping\"\n ],\n \"author\": \"Supadata AI\",\n \"license\": \"MIT\",\n \"engines\": {\n \"node\": \">=18\"\n },\n \"dependencies\": {\n \"cross-fetch\": \"^4.0.0\"\n },\n \"devDependencies\": {\n \"@types/jest\": \"^29.5.14\",\n \"@types/node\": \"^22.10.10\",\n \"jest\": \"^29.7.0\",\n \"jest-fetch-mock\": \"^3.0.3\",\n \"prettier\": \"^3.4.2\",\n \"ts-jest\": \"^29.2.5\",\n \"typescript\": \"^5.7.3\",\n \"tsup\": \"^8.3.6\"\n }\n}","import fetch from 'cross-fetch';\nimport { SupadataConfig, SupadataError } from './types.js';\n// @ts-expect-error: Non-TS import for version from package.json\nimport pkg from '../package.json';\n\nconst USER_AGENT = `supadata-js/${pkg.version}`;\n\nexport class BaseClient {\n protected config: SupadataConfig;\n\n constructor(config: SupadataConfig) {\n this.config = config;\n }\n\n protected async fetch<T>(\n endpoint: string,\n params: Record<string, any> = {},\n method: 'GET' | 'POST' = 'GET'\n ): Promise<T> {\n const baseUrl = this.config.baseUrl || 'https://api.supadata.ai/v1';\n let url = `${baseUrl}${\n endpoint.startsWith('/') ? endpoint : `/${endpoint}`\n }`;\n\n if (method === 'GET' && Object.keys(params).length > 0) {\n const queryParams = new URLSearchParams();\n Object.entries(params).forEach(([key, value]) => {\n if (value !== undefined && value !== null) {\n if (Array.isArray(value)) {\n value.forEach((item) => queryParams.append(key, String(item)));\n } else {\n queryParams.append(key, String(value));\n }\n }\n });\n url += `?${queryParams.toString()}`;\n }\n\n return this.fetchUrl<T>(url, method, params);\n }\n\n protected async fetchUrl<T>(\n url: string,\n method: 'GET' | 'POST' = 'GET',\n body?: Record<string, any>\n ): Promise<T> {\n const options: RequestInit = {\n method,\n headers: {\n 'x-api-key': this.config.apiKey,\n 'Content-Type': 'application/json',\n 'User-Agent': USER_AGENT,\n },\n };\n\n if (method === 'POST' && body) {\n options.body = JSON.stringify(body);\n }\n\n const response = await fetch(url, options);\n\n const contentType = response.headers.get('content-type');\n\n if (!response.ok) {\n // Handle standard API errors\n if (contentType?.includes('application/json')) {\n const errorData = await response.json();\n throw new SupadataError(errorData);\n } else {\n // Fallback for unexpected non-JSON errors\n throw new SupadataError({\n error: 'internal-error',\n message: 'Unexpected error response format',\n details: await response.text(),\n });\n }\n }\n\n try {\n if (!contentType?.includes('application/json')) {\n throw new SupadataError({\n error: 'internal-error',\n message: 'Invalid response format',\n details: 'Expected JSON response but received different content type',\n });\n }\n\n return (await response.json()) as T;\n } catch (error) {\n throw new SupadataError({\n error: 'internal-error',\n message: 'Failed to parse response',\n details: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n }\n}\n","import { BaseClient } from '../client.js';\nimport {\n SupadataError,\n Transcript,\n TranslatedTranscript,\n YoutubeBatchJob,\n YoutubeBatchResults,\n YoutubeChannel,\n YoutubePlaylist,\n YoutubeTranscriptBatchRequest,\n YoutubeVideo,\n YoutubeVideoBatchRequest,\n YoutubeSearchParams,\n YoutubeSearchResponse,\n} from '../types.js';\n\n/**\n * Ensures exactly one property from the specified keys is provided.\n * @example\n * // Valid: { url: \"...\" } or { videoId: \"...\" }\n * // Invalid: {} or { url: \"...\", videoId: \"...\" }\n */\ntype ExactlyOne<T, Keys extends keyof T> = {\n [K in Keys]: { [P in K]-?: T[P] } & { [P in Exclude<Keys, K>]?: never };\n}[Keys] &\n Omit<T, Keys>;\n\nexport type TranscriptParams = {\n lang?: string;\n text?: boolean;\n} & ExactlyOne<{ videoId: string; url: string }, 'videoId' | 'url'>;\n\nexport interface TranslateParams extends Omit<TranscriptParams, 'lang'> {\n lang: string;\n}\n\nexport interface ResourceParams {\n id: string;\n}\n\nexport interface ChannelVideosParams extends ResourceParams {\n limit?: number;\n type?: 'video' | 'short' | 'live' | 'all';\n}\n\nexport interface PlaylistVideosParams extends ResourceParams {\n limit?: number;\n}\n\nexport interface VideoIds {\n videoIds: string[];\n shortIds: string[];\n liveIds: string[];\n}\n\nexport class YouTubeService extends BaseClient {\n /**\n * Handles YouTube Transcript operations.\n */\n transcript = Object.assign(\n /**\n * Fetches a transcript for a YouTube video.\n * @param params - Parameters for fetching the transcript\n * @param params.videoId - The YouTube video ID (mutually exclusive with url)\n * @param params.url - The YouTube video URL (mutually exclusive with videoId)\n * @param params.lang - The language code for the transcript (optional)\n * @param params.text - Whether to return only the text content (optional)\n * @returns A promise that resolves to a Transcript object\n */\n async (params: TranscriptParams): Promise<Transcript> => {\n return this.fetch<Transcript>('/youtube/transcript', params);\n },\n {\n /**\n * Batch fetches transcripts for multiple YouTube videos.\n * @param params - Parameters for the transcript batch job\n * @param params.videoIds - Array of YouTube video IDs to fetch transcripts for\n * @param params.lang - The language code for the transcripts (optional)\n * @param params.limit - Maximum number of videos to process (optional, default: 10, max: 5000)\n * @param params.text - Whether to return only the text content (optional)\n * @returns A promise that resolves to a YoutubeBatchJob object with the job ID\n */\n batch: async (\n params: YoutubeTranscriptBatchRequest\n ): Promise<YoutubeBatchJob> => {\n this.validateLimit(params, 1, 5000, 'batch operation');\n return this.fetch<YoutubeBatchJob>(\n '/youtube/transcript/batch',\n params,\n 'POST'\n );\n },\n }\n );\n\n /**\n * Handles YouTube video operations.\n */\n video = Object.assign(\n /**\n * Fetches a YouTube video based on the provided parameters.\n * @param params - The parameters required to fetch the YouTube video\n * @param params.id - The YouTube video ID\n * @returns A promise that resolves to a YoutubeVideo object\n */\n async (params: ResourceParams): Promise<YoutubeVideo> => {\n return this.fetch<YoutubeVideo>('/youtube/video', params);\n },\n {\n /**\n * Batch fetches metadata for multiple YouTube videos.\n * @param params - Parameters for the video metadata batch job\n * @param params.videoIds - Array of YouTube video IDs to fetch metadata for\n * @param params.limit - Maximum number of videos to process (optional, default: 10, max: 5000)\n * @returns A promise that resolves to a YoutubeBatchJob object with the job ID\n */\n batch: async (\n params: YoutubeVideoBatchRequest\n ): Promise<YoutubeBatchJob> => {\n this.validateLimit(params, 1, 5000, 'batch operation');\n return this.fetch<YoutubeBatchJob>(\n '/youtube/video/batch',\n params,\n 'POST'\n );\n },\n }\n );\n\n /**\n * Handles YouTube channel operations.\n */\n channel = Object.assign(\n /**\n * Fetches YouTube channel information.\n * @param params - The parameters required to fetch the YouTube channel information\n * @param params.id - The YouTube channel ID\n * @returns A promise that resolves to a YoutubeChannel object containing the channel information\n */\n async (params: ResourceParams): Promise<YoutubeChannel> => {\n return this.fetch<YoutubeChannel>('/youtube/channel', params);\n },\n {\n /**\n * Fetches the videos of a YouTube channel.\n * @param params - The parameters required to fetch the YouTube channel videos\n * @param params.id - The YouTube channel ID\n * @param params.limit - The maximum number of videos to fetch (default: 30, max: 5000)\n * @param params.type - The type of videos to fetch ('video', 'short', 'live', or 'all', default: 'video')\n * @returns A promise that resolves to an object containing arrays of video IDs, short IDs, and live IDs\n * @throws {SupadataError} If the limit is invalid (less than 1 or greater than 5000)\n */\n videos: async (params: ChannelVideosParams): Promise<VideoIds> => {\n this.validateLimit(params);\n return this.fetch<VideoIds>('/youtube/channel/videos', params);\n },\n }\n );\n\n /**\n * Handles YouTube playlist operations.\n */\n playlist = Object.assign(\n /**\n * Fetches a YouTube playlist.\n * @param params - The parameters required to fetch the playlist\n * @param params.id - The YouTube playlist ID\n * @returns A promise that resolves to a YoutubePlaylist object\n */\n async (params: ResourceParams): Promise<YoutubePlaylist> => {\n return this.fetch<YoutubePlaylist>('/youtube/playlist', params);\n },\n {\n /**\n * Fetches the videos of a YouTube playlist.\n * @param params - The parameters required to fetch the playlist videos\n * @param params.id - The YouTube playlist ID\n * @param params.limit - The maximum number of videos to fetch (default: 30, max: 5000)\n * @returns A promise that resolves to an object containing arrays of video IDs, short IDs, and live IDs\n * @throws {SupadataError} If the limit is invalid (less than 1 or greater than 5000)\n */\n videos: async (params: PlaylistVideosParams): Promise<VideoIds> => {\n this.validateLimit(params);\n return this.fetch<VideoIds>('/youtube/playlist/videos', params);\n },\n }\n );\n\n /**\n * Handles YouTube batch operations.\n */\n batch = {\n /**\n * Retrieves the status and results of a batch job.\n * @param jobId - The ID of the batch job\n * @returns A promise that resolves to the YoutubeBatchResults containing job status and results\n * @throws {SupadataError} If jobId is not provided\n */\n getBatchResults: async (jobId: string): Promise<YoutubeBatchResults> => {\n if (!jobId) {\n throw new SupadataError({\n error: 'invalid-request',\n message: 'Missing jobId',\n details: 'The jobId parameter is required to get batch results.',\n });\n }\n return this.fetch<YoutubeBatchResults>(`/youtube/batch/${jobId}`);\n },\n };\n\n /**\n * Translates a YouTube video transcript to a specified language.\n * @param params - Parameters for translating the transcript\n * @param params.videoId - The YouTube video ID (mutually exclusive with url)\n * @param params.url - The YouTube video URL (mutually exclusive with videoId)\n * @param params.lang - The target language code for translation\n * @param params.text - Whether to return only the text content (optional)\n * @returns A promise that resolves to a TranslatedTranscript object\n */\n translate = async (\n params: TranslateParams\n ): Promise<TranslatedTranscript> => {\n return this.fetch<TranslatedTranscript>(\n '/youtube/transcript/translate',\n params\n );\n };\n\n /**\n * Search YouTube for videos, channels, and playlists with advanced filters.\n * @param params - Parameters for the search\n * @param params.query - The search query string\n * @param params.uploadDate - Filter by upload date (\"all\", \"hour\", \"today\", \"week\", \"month\", \"year\")\n * @param params.type - Filter by content type (\"all\", \"video\", \"channel\", \"playlist\", \"movie\")\n * @param params.duration - Filter video length (\"all\", \"short\", \"medium\", \"long\")\n * @param params.sortBy - Sort results by (\"relevance\", \"rating\", \"date\", \"views\")\n * @param params.features - Array of special video features\n * @param params.limit - Maximum results to return\n * @param params.nextPageToken - Token for pagination\n * @returns A promise that resolves to a YoutubeSearchResponse object\n */\n search = async (\n params: YoutubeSearchParams\n ): Promise<YoutubeSearchResponse> => {\n if (!params.query) {\n throw new SupadataError({\n error: 'invalid-request',\n message: 'Missing query parameter',\n details: 'The query parameter is required for search.',\n });\n }\n\n this.validateLimit(params, 1, 5000, 'search');\n\n return this.fetch<YoutubeSearchResponse>('/youtube/search', params);\n };\n\n private validateLimit(\n params: { limit?: number },\n min: number = 1,\n max: number = 5000,\n operation: string = 'operation'\n ) {\n if (\n params.limit != undefined &&\n params.limit != null &&\n (params.limit < min || params.limit > max)\n ) {\n throw new SupadataError({\n error: 'invalid-request',\n message: `Invalid limit for ${operation}.`,\n details: `The limit must be between ${min} and ${max}.`,\n });\n }\n }\n}\n","import { BaseClient } from '../client.js';\nimport { CrawlJob, CrawlRequest, JobId, Scrape, SiteMap } from '../types.js';\n\nexport class WebService extends BaseClient {\n /**\n * Extract content from any web page to Markdown format.\n *\n * @param url - URL of the webpage to scrape\n * @returns A promise that resolves to the scraped content\n */\n async scrape(url: string): Promise<Scrape> {\n return this.fetch<Scrape>('/web/scrape', { url });\n }\n\n /**\n * Extract all links found on a webpage.\n *\n * @param url - URL of the webpage to map\n * @returns A promise that resolves to a map of URLs found on the page\n */\n async map(url: string): Promise<SiteMap> {\n return this.fetch<SiteMap>('/web/map', { url });\n }\n\n /**\n * Create a crawl job to extract content from all pages on a website.\n *\n * @param request - Crawl request parameters\n * @param request.url - URL of the website to crawl\n * @param request.limit - Maximum number of pages to crawl (default: 100, max: 5000)\n * @returns A promise that resolves to the crawl job id\n */\n async crawl(request: CrawlRequest): Promise<JobId> {\n return this.fetch<JobId>('/web/crawl', request, 'POST');\n }\n\n /**\n * Get the status and results of a crawl job.\n * Automatically handles pagination to retrieve all pages from the crawl.\n *\n * @param jobId - The ID of the crawl job to retrieve\n * @returns A promise that resolves to the complete crawl job results\n */\n async getCrawlResults(jobId: string): Promise<CrawlJob> {\n let response: CrawlJob;\n let pages: Scrape[] = [];\n let nextUrl: string | undefined;\n\n do {\n response = await (nextUrl\n ? this.fetchUrl<CrawlJob>(nextUrl)\n : this.fetch<CrawlJob>(`/web/crawl/${jobId}`));\n\n if (response.pages) {\n pages = [...pages, ...response.pages];\n }\n nextUrl = response.next;\n } while (nextUrl);\n\n return response;\n }\n}\n","import { BaseClient } from '../client.js';\nimport {\n JobId,\n JobResult,\n SupadataError,\n Transcript,\n TranscriptOrJobId,\n} from '../types.js';\n\nexport interface GeneralTranscriptParams {\n url: string;\n lang?: string;\n text?: boolean;\n chunkSize?: number;\n mode?: 'native' | 'auto' | 'generate';\n}\n\nexport class TranscriptService extends BaseClient {\n /**\n * Get transcript from a supported video platform or file URL.\n * @param params - Parameters for fetching the transcript\n * @returns A promise that resolves to either a Transcript or JobId for async processing\n */\n get = async (params: GeneralTranscriptParams): Promise<TranscriptOrJobId> => {\n return this.fetch<TranscriptOrJobId>('/transcript', params);\n };\n\n /**\n * Get results for a transcript job by job ID.\n * @param jobId - The ID of the transcript job\n * @returns A promise that resolves to the job result containing status and transcript if completed\n * @throws {SupadataError} If jobId is not provided\n */\n getJobStatus = async (jobId: string): Promise<JobResult<Transcript>> => {\n if (!jobId) {\n throw new SupadataError({\n error: 'invalid-request',\n message: 'Missing jobId',\n details:\n 'The jobId parameter is required to get transcript job status.',\n });\n }\n return this.fetch<JobResult<Transcript>>(`/transcript/${jobId}`);\n };\n}\n","import {\n JobResult,\n SupadataConfig,\n Transcript,\n TranscriptOrJobId,\n} from './types.js';\nimport { YouTubeService } from './services/youtube.js';\nimport { WebService } from './services/web.js';\nimport {\n TranscriptService,\n GeneralTranscriptParams,\n} from './services/transcript.js';\n\nexport * from './types.js';\nexport * from './client.js';\nexport * from './services/youtube.js';\nexport * from './services/web.js';\nexport {\n TranscriptService,\n GeneralTranscriptParams,\n} from './services/transcript.js';\n\nexport class Supadata {\n readonly youtube: YouTubeService;\n readonly web: WebService;\n private _transcriptService: TranscriptService;\n\n constructor(config: SupadataConfig) {\n this.youtube = new YouTubeService(config);\n this.web = new WebService(config);\n this._transcriptService = new TranscriptService(config);\n }\n\n /**\n * Get transcript from a supported video platform (YouTube, TikTok, Instagram, Twitter) or file URL.\n * If the video is too large to return transcript immediately, request returns a job ID.\n */\n transcript = Object.assign(\n async (params: GeneralTranscriptParams): Promise<TranscriptOrJobId> => {\n return this._transcriptService.get(params);\n },\n {\n getJobStatus: (jobId: string): Promise<JobResult<Transcript>> => {\n return this._transcriptService.getJobStatus(jobId);\n },\n }\n );\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@supadata/js",
3
- "version": "1.1.3",
3
+ "version": "1.3.0",
4
4
  "description": "TypeScript / JavaScript SDK for Supadata API",
5
5
  "homepage": "https://supadata.ai",
6
6
  "repository": "https://github.com/supadata-ai/js",
@@ -38,6 +38,12 @@
38
38
  ],
39
39
  "author": "Supadata AI",
40
40
  "license": "MIT",
41
+ "engines": {
42
+ "node": ">=18"
43
+ },
44
+ "dependencies": {
45
+ "cross-fetch": "^4.0.0"
46
+ },
41
47
  "devDependencies": {
42
48
  "@types/jest": "^29.5.14",
43
49
  "@types/node": "^22.10.10",