socialtap 0.0.1 → 1.453.20

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/dist/agents.js ADDED
@@ -0,0 +1,179 @@
1
+ // Code generated by engine/cmd/gensdk (make gen) from engine/internal/sdkgen/runtime; DO NOT EDIT.
2
+ // `socialtap init`: sets up coding agents (Claude Code, Codex, Cursor, Gemini CLI) with the site's Agent Skill and
3
+ // the remote MCP server, in each agent's own user-level config. The skill is the one the site publishes (its Agent
4
+ // Skills discovery index, digest checked), so there is one skill and it is never stale. Each agent's config format
5
+ // is its vendor's documented one: Claude Code through its own CLI (`claude mcp add-json`), Codex's config.toml
6
+ // ([mcp_servers.<name>]), Cursor's mcp.json and Gemini CLI's settings.json (mcpServers).
7
+ /// <reference types="node" />
8
+ import { execFile } from "node:child_process";
9
+ import { createHash } from "node:crypto";
10
+ import { existsSync } from "node:fs";
11
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
12
+ import { join } from "node:path";
13
+ const bearer = (s) => (s.key ? { headers: { Authorization: `Bearer ${s.key}` } } : {});
14
+ /** The shared user skills directory (agentskills.io): Codex, Cursor and Gemini CLI read it. */
15
+ const sharedSkills = (env) => join(env.home, ".agents", "skills");
16
+ export const AGENTS = [
17
+ {
18
+ id: "claude",
19
+ name: "Claude Code",
20
+ detect: (env) => existsSync(join(env.home, ".claude")),
21
+ skillsDir: (env) => join(env.home, ".claude", "skills"),
22
+ async addMcp(env, s) {
23
+ const config = JSON.stringify({ type: "http", url: s.url, ...bearer(s) });
24
+ // add-json refuses an existing name: remove it first (absent is fine).
25
+ await env.run("claude", ["mcp", "remove", "--scope", "user", s.name]).catch(() => undefined);
26
+ const r = await env.run("claude", ["mcp", "add-json", "--scope", "user", s.name, config]);
27
+ if (r.code !== 0)
28
+ throw new Error(`claude mcp add-json failed: ${(r.stderr || r.stdout).trim()}`);
29
+ return "claude mcp add-json --scope user (~/.claude.json)";
30
+ },
31
+ },
32
+ {
33
+ id: "codex",
34
+ name: "Codex",
35
+ detect: (env) => existsSync(codexHome(env)),
36
+ skillsDir: sharedSkills,
37
+ async addMcp(env, s) {
38
+ const path = join(codexHome(env), "config.toml");
39
+ const table = [
40
+ `[mcp_servers.${s.name}]`,
41
+ `url = ${JSON.stringify(s.url)}`,
42
+ ...(s.key ? [`http_headers = { "Authorization" = ${JSON.stringify(`Bearer ${s.key}`)} }`] : []),
43
+ ];
44
+ await writePrivate(path, setTomlTable(await readText(path), `mcp_servers.${s.name}`, table));
45
+ return path;
46
+ },
47
+ },
48
+ {
49
+ id: "cursor",
50
+ name: "Cursor",
51
+ detect: (env) => existsSync(join(env.home, ".cursor")),
52
+ skillsDir: sharedSkills,
53
+ async addMcp(env, s) {
54
+ const path = join(env.home, ".cursor", "mcp.json");
55
+ await setJsonServer(path, s.name, { url: s.url, ...bearer(s) });
56
+ return path;
57
+ },
58
+ },
59
+ {
60
+ id: "gemini",
61
+ name: "Gemini CLI",
62
+ detect: (env) => existsSync(join(env.home, ".gemini")),
63
+ skillsDir: sharedSkills,
64
+ async addMcp(env, s) {
65
+ const path = join(env.home, ".gemini", "settings.json");
66
+ await setJsonServer(path, s.name, { httpUrl: s.url, ...bearer(s) });
67
+ return path;
68
+ },
69
+ },
70
+ ];
71
+ function codexHome(env) {
72
+ return env.env.CODEX_HOME || join(env.home, ".codex");
73
+ }
74
+ /**
75
+ * The skills the site publishes: its Agent Skills discovery index (agentskills.io, schema 0.2.0), each SKILL.md
76
+ * fetched and checked against the index's sha256 digest.
77
+ */
78
+ export async function fetchSkills(env, origin, indexPath) {
79
+ const indexURL = new URL(indexPath, origin);
80
+ const index = (await getOK(env, indexURL).then((r) => r.json()));
81
+ const skills = [];
82
+ for (const entry of Array.isArray(index.skills) ? index.skills : []) {
83
+ const e = (entry ?? {});
84
+ if (e.type !== "skill-md" || typeof e.name !== "string" || typeof e.url !== "string")
85
+ continue;
86
+ if (!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(e.name))
87
+ throw new Error(`skill index ${indexURL}: invalid skill name ${JSON.stringify(e.name)}`);
88
+ const content = await getOK(env, new URL(e.url, indexURL)).then((r) => r.text());
89
+ const digest = `sha256:${createHash("sha256").update(content).digest("hex")}`;
90
+ if (typeof e.digest === "string" && e.digest !== digest)
91
+ throw new Error(`skill ${e.name}: digest mismatch (the index says ${e.digest}, got ${digest})`);
92
+ skills.push({ name: e.name, content });
93
+ }
94
+ if (skills.length === 0)
95
+ throw new Error(`skill index ${indexURL} lists no SKILL.md`);
96
+ return skills;
97
+ }
98
+ async function getOK(env, url) {
99
+ const r = await env.fetch(url);
100
+ if (!r.ok)
101
+ throw new Error(`GET ${url}: HTTP ${r.status}`);
102
+ return r;
103
+ }
104
+ /** Writes each skill to <dir>/<name>/SKILL.md; returns the files written. */
105
+ export async function writeSkills(dir, skills) {
106
+ const files = [];
107
+ for (const s of skills) {
108
+ const path = join(dir, s.name, "SKILL.md");
109
+ await mkdir(join(dir, s.name), { recursive: true });
110
+ await writeFile(path, s.content);
111
+ files.push(path);
112
+ }
113
+ return files;
114
+ }
115
+ async function readText(path) {
116
+ try {
117
+ return await readFile(path, "utf8");
118
+ }
119
+ catch (e) {
120
+ if (e.code === "ENOENT")
121
+ return "";
122
+ throw e;
123
+ }
124
+ }
125
+ /** Writes a config file that holds a secret: a new file is readable by the user only (an existing one keeps its mode). */
126
+ async function writePrivate(path, text) {
127
+ await mkdir(join(path, ".."), { recursive: true });
128
+ await writeFile(path, text, { mode: 0o600 });
129
+ }
130
+ /** Sets mcpServers[name] in a JSON config, keeping everything else; refuses a file that isn't plain JSON. */
131
+ async function setJsonServer(path, name, server) {
132
+ const text = await readText(path);
133
+ let config = {};
134
+ if (text.trim() !== "") {
135
+ try {
136
+ config = JSON.parse(text);
137
+ }
138
+ catch {
139
+ throw new Error(`${path} is not plain JSON (comments?): add mcpServers.${name} = ${JSON.stringify({ ...server, headers: "…" })} by hand`);
140
+ }
141
+ if (config === null || typeof config !== "object" || Array.isArray(config))
142
+ throw new Error(`${path}: not a JSON object`);
143
+ }
144
+ const servers = config.mcpServers && typeof config.mcpServers === "object" ? config.mcpServers : {};
145
+ config.mcpServers = { ...servers, [name]: server };
146
+ await writePrivate(path, `${JSON.stringify(config, null, 2)}\n`);
147
+ }
148
+ /**
149
+ * Replaces TOML table `name` (and its sub-tables `name.*`) with `lines`, or appends it. Line-based: a table runs from
150
+ * its header to the next table header, which is how config.toml is written.
151
+ */
152
+ export function setTomlTable(text, name, lines) {
153
+ const header = /^\s*\[\[?\s*([^\]]+?)\s*\]\]?\s*(#.*)?$/;
154
+ const kept = [];
155
+ let skipping = false;
156
+ for (const line of text.split("\n")) {
157
+ const m = header.exec(line);
158
+ if (m) {
159
+ const t = m[1].replace(/\s+/g, "");
160
+ skipping = t === name || t.startsWith(`${name}.`);
161
+ }
162
+ if (!skipping)
163
+ kept.push(line);
164
+ }
165
+ while (kept.length > 0 && kept.at(-1).trim() === "")
166
+ kept.pop();
167
+ return `${[...kept, ...(kept.length > 0 ? [""] : []), ...lines].join("\n")}\n`;
168
+ }
169
+ /** Runs a program (the Claude Code CLI) and collects its output. */
170
+ export function runProgram(cmd, args) {
171
+ return new Promise((resolve, reject) => {
172
+ execFile(cmd, args, { timeout: 30_000 }, (err, stdout, stderr) => {
173
+ if (err && err.code === "ENOENT")
174
+ return reject(err);
175
+ const code = err ? (typeof err.code === "number" ? err.code : 1) : 0;
176
+ resolve({ code, stdout: String(stdout), stderr: String(stderr) });
177
+ });
178
+ });
179
+ }
package/dist/ai.d.ts ADDED
@@ -0,0 +1,14 @@
1
+ import { type ToolSet } from "ai";
2
+ import type { ClientOptions, Core } from "./core.ts";
3
+ export interface SocialtapToolsOptions extends ClientOptions {
4
+ /** The client whose key and settings the tools use (default: a new one from the other options). */
5
+ client?: Core;
6
+ /** Only these tools (default: every tool). */
7
+ tools?: readonly string[];
8
+ }
9
+ /**
10
+ * Every tool as an AI SDK tool, keyed by name: `generateText({ model, tools: socialtapTools(), prompt })`. A tool's
11
+ * failure (an API error, a bad argument) is its output (`error` with `retryable` and `remediation`), so the model
12
+ * reads it; transport failures throw.
13
+ */
14
+ export declare function socialtapTools(options?: SocialtapToolsOptions): ToolSet;
package/dist/ai.js ADDED
@@ -0,0 +1,35 @@
1
+ // Code generated by engine/cmd/gensdk (make gen) from engine/internal/sdkgen/runtime; DO NOT EDIT.
2
+ // socialtap/ai: the agent tools (tools.ts) as Vercel AI SDK tools. `ai` is an optional peer dependency: only this
3
+ // entry point imports it.
4
+ import { jsonSchema, tool } from "ai";
5
+ import { SocialTap } from "./client.js";
6
+ import { TOOLS } from "./tooldefs.js";
7
+ import { callTool } from "./tools.js";
8
+ /**
9
+ * Every tool as an AI SDK tool, keyed by name: `generateText({ model, tools: socialtapTools(), prompt })`. A tool's
10
+ * failure (an API error, a bad argument) is its output (`error` with `retryable` and `remediation`), so the model
11
+ * reads it; transport failures throw.
12
+ */
13
+ export function socialtapTools(options = {}) {
14
+ const { client: given, tools: only, ...clientOptions } = options;
15
+ const client = given ?? new SocialTap(clientOptions);
16
+ const out = {};
17
+ for (const def of TOOLS) {
18
+ if (only && !only.includes(def.name))
19
+ continue;
20
+ out[def.name] = aiTool(client, def);
21
+ }
22
+ for (const name of only ?? []) {
23
+ if (!(name in out))
24
+ throw new Error(`socialtapTools: unknown tool ${JSON.stringify(name)} (known: ${TOOLS.map((t) => t.name).join(", ")})`);
25
+ }
26
+ return out;
27
+ }
28
+ function aiTool(client, def) {
29
+ return tool({
30
+ title: def.title,
31
+ description: def.description,
32
+ inputSchema: jsonSchema(def.inputSchema),
33
+ execute: async (args, { abortSignal }) => (await callTool(client, def.name, args, abortSignal ? { signal: abortSignal } : {})).output,
34
+ });
35
+ }
package/dist/bin.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/bin.js ADDED
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env node
2
+ // Code generated by engine/cmd/gensdk (make gen) from engine/internal/sdkgen/runtime; DO NOT EDIT.
3
+ // The package's bin: `npx socialtap …` (cli.ts).
4
+ /// <reference types="node" />
5
+ import { main } from "./cli.js";
6
+ process.exitCode = await main(process.argv.slice(2));
package/dist/cli.d.ts ADDED
@@ -0,0 +1,9 @@
1
+ import { type SetupEnv } from "./agents.ts";
2
+ /** Where the CLI reads and writes: replaced in tests. */
3
+ export interface IO extends SetupEnv {
4
+ out(text: string): void;
5
+ err(text: string): void;
6
+ }
7
+ export declare function processIO(): IO;
8
+ /** Runs the CLI; returns the exit code. */
9
+ export declare function main(argv: readonly string[], io?: IO): Promise<number>;
package/dist/cli.js ADDED
@@ -0,0 +1,325 @@
1
+ // Code generated by engine/cmd/gensdk (make gen) from engine/internal/sdkgen/runtime; DO NOT EDIT.
2
+ // The CLI (`npx socialtap`, ADR 0012 §4): one command per endpoint (commands.ts, from the catalog), the agent tools
3
+ // (`tool`), and `init`, which sets up coding agents (agents.ts). Results are JSON on stdout (a list walk with --all:
4
+ // one item per line); errors are JSON on stderr with exit code 1, usage errors exit 2.
5
+ /// <reference types="node" />
6
+ import { homedir } from "node:os";
7
+ import { parseArgs } from "node:util";
8
+ import { AGENTS, fetchSkills, runProgram, writeSkills } from "./agents.js";
9
+ import { SocialTap } from "./client.js";
10
+ import { AGENTS_DOCS_URL, COMMANDS, MCP_SERVER_NAME, PRODUCT_NAME, SIGNUP_URL, SKILLS_INDEX_PATH } from "./commands.js";
11
+ import { API_KEY_ENV, DEFAULT_BASE_URL, VERSION } from "./constants.js";
12
+ import { APIError, SocialTapError } from "./error.js";
13
+ import { MCP_PATH, TOOLS } from "./tooldefs.js";
14
+ import { callTool } from "./tools.js";
15
+ export function processIO() {
16
+ return {
17
+ out: (t) => process.stdout.write(t.endsWith("\n") ? t : `${t}\n`),
18
+ err: (t) => process.stderr.write(t.endsWith("\n") ? t : `${t}\n`),
19
+ home: homedir(),
20
+ env: process.env,
21
+ run: runProgram,
22
+ fetch: globalThis.fetch,
23
+ };
24
+ }
25
+ /** A usage error: printed with a hint, exit code 2. */
26
+ class UsageError extends Error {
27
+ }
28
+ const CLIENT_OPTIONS = {
29
+ "api-key": { type: "string" },
30
+ "base-url": { type: "string" },
31
+ help: { type: "boolean", short: "h" },
32
+ };
33
+ /** Runs the CLI; returns the exit code. */
34
+ export async function main(argv, io = processIO()) {
35
+ const [first, ...rest] = argv;
36
+ try {
37
+ switch (first) {
38
+ case undefined:
39
+ case "help":
40
+ case "--help":
41
+ case "-h":
42
+ io.out(usage());
43
+ return 0;
44
+ case "--version":
45
+ case "-v":
46
+ case "version":
47
+ io.out(VERSION);
48
+ return 0;
49
+ case "init":
50
+ return await init(rest, io);
51
+ case "skill":
52
+ return await skill(rest, io);
53
+ case "endpoints":
54
+ io.out(endpointList());
55
+ return 0;
56
+ case "tool":
57
+ case "tools":
58
+ return await tool(rest, io);
59
+ default:
60
+ return await endpoint(first, rest, io);
61
+ }
62
+ }
63
+ catch (e) {
64
+ return fail(e, io);
65
+ }
66
+ }
67
+ function fail(e, io) {
68
+ if (e instanceof UsageError) {
69
+ io.err(`${e.message}\nRun \`socialtap help\` for usage.`);
70
+ return 2;
71
+ }
72
+ if (e instanceof APIError) {
73
+ const error = {
74
+ code: e.code,
75
+ status: e.status,
76
+ message: e.message,
77
+ retryable: e.retryable,
78
+ remediation: e.remediation,
79
+ param: e.param,
80
+ details: e.details,
81
+ doc_url: e.docUrl,
82
+ request_id: e.requestId,
83
+ };
84
+ io.err(JSON.stringify({ error, credits_charged: e.creditsCharged }, null, 2));
85
+ return 1;
86
+ }
87
+ if (e instanceof SocialTapError && e.message.startsWith("missing API key")) {
88
+ io.err(`${e.message}${SIGNUP_URL ? `. Get one at ${SIGNUP_URL}` : ""}`);
89
+ return 1;
90
+ }
91
+ io.err(e instanceof Error ? e.message : String(e));
92
+ return 1;
93
+ }
94
+ function usage() {
95
+ const platforms = [...new Set(COMMANDS.map((c) => c.platform))];
96
+ return [
97
+ `${PRODUCT_NAME} CLI ${VERSION}: public social media data as JSON.`,
98
+ "",
99
+ "Usage:",
100
+ " socialtap <platform> <endpoint> --<param> <value> ... call an endpoint (JSON on stdout)",
101
+ " --all [--max-pages N] [--max-credits N] walk a list: one item per line",
102
+ " socialtap endpoints every endpoint, its params and price",
103
+ " socialtap tool [<name> [<json arguments>]] the agent tools (as the MCP server serves them)",
104
+ " socialtap init [--agent <id>]... set up coding agents: skill + MCP server",
105
+ " socialtap skill print the Agent Skill (SKILL.md)",
106
+ "",
107
+ `Options: --api-key <key> (default: $${API_KEY_ENV}), --base-url <url> (default: ${DEFAULT_BASE_URL}), --help.`,
108
+ `Platforms: ${platforms.join(", ")}. \`socialtap <platform>\` lists its endpoints, \`socialtap <platform> <endpoint> --help\` its params.`,
109
+ ].join("\n");
110
+ }
111
+ function endpointList() {
112
+ return COMMANDS.map((c) => {
113
+ const required = c.params.filter((p) => p.required).map((p) => `--${p.name} <${p.type}>`);
114
+ return `socialtap ${c.platform} ${c.name} ${required.join(" ")}\n ${c.summary} (${c.price}${c.kind === "list" ? " per page" : ""})`;
115
+ }).join("\n");
116
+ }
117
+ function commandHelp(c) {
118
+ const lines = [`socialtap ${c.platform} ${c.name}: ${c.summary}`, `Endpoint ${c.endpoint}. Price: ${c.price}${c.kind === "list" ? " per page" : ""}.`, "", "Params:"];
119
+ for (const p of c.params) {
120
+ lines.push(` --${p.name} <${p.enum ? p.enum.join("|") : p.type}>${p.required ? " (required)" : ""}`, ` ${p.description}`);
121
+ }
122
+ if (c.kind === "list") {
123
+ lines.push("", "List options:", " --all walk every page: one JSON item per line on stdout, a summary on stderr", " --max-pages <n> stop --all after n pages", " --max-credits <n> stop --all before spending more than n credits");
124
+ }
125
+ return lines.join("\n");
126
+ }
127
+ function client(values, io) {
128
+ const options = { apiKey: values["api-key"] ?? io.env[API_KEY_ENV], fetch: io.fetch };
129
+ if (values["base-url"])
130
+ options.baseURL = values["base-url"];
131
+ return new SocialTap(options);
132
+ }
133
+ // ---- endpoints ----
134
+ async function endpoint(platform, rest, io) {
135
+ const ofPlatform = COMMANDS.filter((c) => c.platform === platform);
136
+ if (ofPlatform.length === 0)
137
+ throw new UsageError(`unknown command or platform: ${platform}`);
138
+ const [name, ...args] = rest;
139
+ const cmd = ofPlatform.find((c) => c.name === name);
140
+ if (!cmd) {
141
+ if (name !== undefined && !name.startsWith("-"))
142
+ throw new UsageError(`unknown ${platform} endpoint: ${name} (known: ${ofPlatform.map((c) => c.name).join(", ")})`);
143
+ io.out(ofPlatform.map((c) => `socialtap ${c.platform} ${c.name}: ${c.summary} (${c.price})`).join("\n"));
144
+ return 0;
145
+ }
146
+ const options = { ...CLIENT_OPTIONS };
147
+ if (cmd.kind === "list")
148
+ Object.assign(options, { all: { type: "boolean" }, "max-pages": { type: "string" }, "max-credits": { type: "string" } });
149
+ for (const p of cmd.params) {
150
+ for (const flag of new Set([p.name, p.name.replaceAll("_", "-")]))
151
+ options[flag] = { type: p.type === "boolean" ? "boolean" : "string" };
152
+ }
153
+ const { values } = parse(args, options);
154
+ if (values.help) {
155
+ io.out(commandHelp(cmd));
156
+ return 0;
157
+ }
158
+ const params = readParams(cmd, values);
159
+ const c = client(values, io);
160
+ if (cmd.kind === "get") {
161
+ const r = await cmd.get(c, params);
162
+ io.out(JSON.stringify({ data: r.data, meta: r.meta }, null, 2));
163
+ return 0;
164
+ }
165
+ if (!values.all) {
166
+ const r = await cmd.list(c, params);
167
+ io.out(JSON.stringify({ data: r.data, page: r.page, meta: r.meta }, null, 2));
168
+ return 0;
169
+ }
170
+ const pages = cmd.iterate(c, params, {
171
+ ...optionalInt("max-pages", values["max-pages"], (n) => ({ maxPages: n })),
172
+ ...optionalInt("max-credits", values["max-credits"], (n) => ({ maxCredits: n })),
173
+ });
174
+ for await (const item of pages)
175
+ io.out(JSON.stringify(item));
176
+ io.err(JSON.stringify({ pages: pages.pagesFetched, credits_charged: pages.creditsCharged, stop_reason: pages.stopReason, end_reason: pages.endReason }));
177
+ return 0;
178
+ }
179
+ function parse(args, options) {
180
+ try {
181
+ return parseArgs({ args: [...args], options, strict: true, allowPositionals: false });
182
+ }
183
+ catch (e) {
184
+ throw new UsageError(e instanceof Error ? e.message : String(e));
185
+ }
186
+ }
187
+ /** The command's params from the flags (snake_case or kebab-case), typed; required ones present. */
188
+ function readParams(cmd, values) {
189
+ const params = {};
190
+ for (const p of cmd.params) {
191
+ const raw = values[p.name] ?? values[p.name.replaceAll("_", "-")];
192
+ if (raw === undefined) {
193
+ if (p.required)
194
+ throw new UsageError(`socialtap ${cmd.platform} ${cmd.name}: --${p.name} is required (${p.description})`);
195
+ continue;
196
+ }
197
+ params[p.name] = typed(p, raw);
198
+ }
199
+ return params;
200
+ }
201
+ function typed(p, raw) {
202
+ if (p.type === "boolean" || typeof raw !== "string")
203
+ return raw;
204
+ if (p.type === "string") {
205
+ if (p.enum && !p.enum.includes(raw))
206
+ throw new UsageError(`--${p.name} must be one of ${p.enum.join(", ")}`);
207
+ return raw;
208
+ }
209
+ const n = Number(raw);
210
+ if (raw.trim() === "" || !Number.isFinite(n) || (p.type === "integer" && !Number.isInteger(n)))
211
+ throw new UsageError(`--${p.name} must be ${p.type === "integer" ? "an integer" : "a number"}`);
212
+ return n;
213
+ }
214
+ function optionalInt(flag, raw, wrap) {
215
+ if (raw === undefined)
216
+ return {};
217
+ const n = Number(raw);
218
+ if (typeof raw !== "string" || !Number.isInteger(n) || n < 0)
219
+ throw new UsageError(`--${flag} must be a non-negative integer`);
220
+ return wrap(n);
221
+ }
222
+ // ---- tools ----
223
+ async function tool(rest, io) {
224
+ const { values, positionals } = (() => {
225
+ try {
226
+ return parseArgs({ args: [...rest], options: CLIENT_OPTIONS, strict: true, allowPositionals: true });
227
+ }
228
+ catch (e) {
229
+ throw new UsageError(e instanceof Error ? e.message : String(e));
230
+ }
231
+ })();
232
+ const [name, json] = positionals;
233
+ if (name === undefined || values.help) {
234
+ io.out(TOOLS.map((t) => `${t.name}: ${t.title}`).join("\n") || "this API has no MCP server");
235
+ return 0;
236
+ }
237
+ let args = {};
238
+ if (json !== undefined) {
239
+ try {
240
+ args = JSON.parse(json);
241
+ }
242
+ catch {
243
+ throw new UsageError(`tool arguments must be a JSON object, e.g. socialtap tool ${name} '{"url": "…"}'`);
244
+ }
245
+ if (args === null || typeof args !== "object" || Array.isArray(args))
246
+ throw new UsageError("tool arguments must be a JSON object");
247
+ }
248
+ const r = await callTool(client(values, io), name, args);
249
+ (r.isError ? io.err : io.out)(typeof r.output === "string" ? r.output : JSON.stringify(r.output, null, 2));
250
+ return r.isError ? 1 : 0;
251
+ }
252
+ // ---- skill and init ----
253
+ async function skill(rest, io) {
254
+ const { values } = parse(rest, { "base-url": { type: "string" } });
255
+ if (SKILLS_INDEX_PATH === null)
256
+ throw new Error(`${PRODUCT_NAME} publishes no Agent Skill`);
257
+ const skills = await fetchSkills(io, origin(values["base-url"]), SKILLS_INDEX_PATH);
258
+ io.out(skills.map((s) => s.content).join("\n"));
259
+ return 0;
260
+ }
261
+ function origin(baseURL) {
262
+ return (baseURL ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
263
+ }
264
+ async function init(rest, io) {
265
+ const ids = AGENTS.map((a) => a.id);
266
+ const { values } = parse(rest, { ...CLIENT_OPTIONS, agent: { type: "string", multiple: true } });
267
+ if (values.help) {
268
+ io.out([
269
+ "socialtap init [--agent <id>]... [--api-key <key>] [--base-url <url>]",
270
+ "",
271
+ `Installs the ${PRODUCT_NAME} Agent Skill and registers the MCP server in each coding agent's user config.`,
272
+ `Agents: ${AGENTS.map((a) => `${a.id} (${a.name})`).join(", ")}; default: every one installed.`,
273
+ `The agent signs you in with your browser the first time a tool needs it; with --api-key or $${API_KEY_ENV} it uses that key instead.`,
274
+ ].join("\n"));
275
+ return 0;
276
+ }
277
+ const wanted = values.agent ?? [];
278
+ for (const id of wanted)
279
+ if (!ids.includes(id))
280
+ throw new UsageError(`unknown agent ${id} (known: ${ids.join(", ")})`);
281
+ const agents = wanted.length > 0 ? AGENTS.filter((a) => wanted.includes(a.id)) : AGENTS.filter((a) => a.detect(io));
282
+ if (agents.length === 0) {
283
+ throw new UsageError(`found no coding agent (${AGENTS.map((a) => a.name).join(", ")}); choose with --agent <${ids.join("|")}>`);
284
+ }
285
+ const base = origin(values["base-url"]);
286
+ let failed = 0;
287
+ const note = (ok, line) => {
288
+ if (!ok)
289
+ failed++;
290
+ io.out(`${ok ? "✓" : "✗"} ${line}`);
291
+ };
292
+ if (SKILLS_INDEX_PATH !== null) {
293
+ try {
294
+ const skills = await fetchSkills(io, base, SKILLS_INDEX_PATH);
295
+ for (const dir of new Set(agents.map((a) => a.skillsDir(io)))) {
296
+ const users = agents.filter((a) => a.skillsDir(io) === dir).map((a) => a.name);
297
+ for (const file of await writeSkills(dir, skills))
298
+ note(true, `skill: ${file} (${users.join(", ")})`);
299
+ }
300
+ }
301
+ catch (e) {
302
+ note(false, `skill: ${e instanceof Error ? e.message : String(e)}`);
303
+ }
304
+ }
305
+ const key = values["api-key"] ?? io.env[API_KEY_ENV];
306
+ if (MCP_PATH === null) {
307
+ io.out(`(${PRODUCT_NAME} has no MCP server: skipped)`);
308
+ }
309
+ else {
310
+ const server = { name: MCP_SERVER_NAME, url: base + MCP_PATH, ...(key ? { key } : {}) };
311
+ if (!key)
312
+ io.out("No API key given: each agent signs you in with your browser the first time a tool needs it.");
313
+ for (const a of agents) {
314
+ try {
315
+ note(true, `MCP server ${server.name} in ${a.name}: ${await a.addMcp(io, server)}`);
316
+ }
317
+ catch (e) {
318
+ const why = e.code === "ENOENT" ? `its CLI is not on PATH` : e instanceof Error ? e.message : String(e);
319
+ note(false, `MCP server in ${a.name}: ${why}${AGENTS_DOCS_URL ? `. Setup by hand: ${AGENTS_DOCS_URL}` : ""}`);
320
+ }
321
+ }
322
+ }
323
+ io.out(failed === 0 ? "Done. Restart your agents to load the changes." : `${failed} step(s) failed (above).`);
324
+ return failed === 0 ? 0 : 1;
325
+ }
@@ -0,0 +1,99 @@
1
+ import { type ClientOptions, Core } from "./core.ts";
2
+ import { Bluesky, Facebook, Google, Instagram, Kick, Komi, Kwai, LnkBio, LinkedIn, Linkme, Linktree, Pillar, Reddit, Rumble, Snapchat, SoundCloud, Telegram, Threads, TikTok, TikTokShop, TruthSocial, Twitch, X, YouTube, AccountResource, UsageResource, CreditTransactionsResource, BillingResource, RequestsResource, ApiKeysResource, JobsResource, WebhookEndpointsResource, EventsResource, NotificationPreferencesResource } from "./resources.ts";
3
+ import { Webhooks } from "./webhooks.ts";
4
+ /**
5
+ * The SocialTap API client: `new SocialTap({ apiKey })` (default: the SOCIALTAP_API_KEY environment variable).
6
+ *
7
+ * Social media scraper API: send any public social media link and get clean JSON back. We handle the proxies,
8
+ * blocks and platform changes, and failed requests are free. Available now: ads on Facebook, Google, LinkedIn
9
+ * and TikTok; comments on Bluesky, Facebook, Instagram, Reddit, Rumble, Snapchat, Threads, TikTok and YouTube;
10
+ * communities on Facebook, Reddit and X; downloads on TikTok; effects on TikTok; embeds on Instagram;
11
+ * engagements on Facebook, Instagram, Reddit, Rumble, TikTok and YouTube; events on Facebook; hashtags on
12
+ * Instagram and TikTok; lives on TikTok and Twitch; places on Facebook and Instagram; playlists on Instagram and
13
+ * TikTok; posts on Bluesky, Facebook, Instagram, Kick, Kwai, LinkedIn, Reddit, Rumble, Snapchat, SoundCloud,
14
+ * Telegram, Threads, TikTok, Truth Social, Twitch, X and YouTube; products on Facebook and TikTok Shop; profiles
15
+ * on Bluesky, Facebook, Google, Instagram, Komi, Kwai, LinkedIn, Linkme, Linktree, Lnk.Bio, Pillar, Reddit,
16
+ * Rumble, Snapchat, SoundCloud, Telegram, Threads, TikTok, Truth Social, Twitch, X and YouTube; reviews on
17
+ * TikTok Shop; sounds on Instagram and TikTok; suggestions on Google and Instagram; topics on Instagram;
18
+ * transcripts on Facebook, Instagram, Kick, Reddit, Rumble, TikTok, Twitch and YouTube; usernames on Instagram;
19
+ * web results on Facebook, Instagram, LinkedIn, Telegram, TikTok and X.
20
+ */
21
+ export declare class SocialTap extends Core {
22
+ /** Bluesky endpoints. */
23
+ readonly bluesky: Bluesky;
24
+ /** Facebook endpoints. */
25
+ readonly facebook: Facebook;
26
+ /** Google endpoints. */
27
+ readonly google: Google;
28
+ /** Instagram endpoints. */
29
+ readonly instagram: Instagram;
30
+ /** Kick endpoints. */
31
+ readonly kick: Kick;
32
+ /** Komi endpoints. */
33
+ readonly komi: Komi;
34
+ /** Kwai endpoints. */
35
+ readonly kwai: Kwai;
36
+ /** Lnk.Bio endpoints. */
37
+ readonly linkbio: LnkBio;
38
+ /** LinkedIn endpoints. */
39
+ readonly linkedin: LinkedIn;
40
+ /** Linkme endpoints. */
41
+ readonly linkme: Linkme;
42
+ /** Linktree endpoints. */
43
+ readonly linktree: Linktree;
44
+ /** Pillar endpoints. */
45
+ readonly pillar: Pillar;
46
+ /** Reddit endpoints. */
47
+ readonly reddit: Reddit;
48
+ /** Rumble endpoints. */
49
+ readonly rumble: Rumble;
50
+ /** Snapchat endpoints. */
51
+ readonly snapchat: Snapchat;
52
+ /** SoundCloud endpoints. */
53
+ readonly soundcloud: SoundCloud;
54
+ /** Telegram endpoints. */
55
+ readonly telegram: Telegram;
56
+ /** Threads endpoints. */
57
+ readonly threads: Threads;
58
+ /** TikTok endpoints. */
59
+ readonly tiktok: TikTok;
60
+ /** TikTok Shop endpoints. */
61
+ readonly tiktokshop: TikTokShop;
62
+ /** Truth Social endpoints. */
63
+ readonly truthsocial: TruthSocial;
64
+ /** Twitch endpoints. */
65
+ readonly twitch: Twitch;
66
+ /** X endpoints. */
67
+ readonly x: X;
68
+ /** YouTube endpoints. */
69
+ readonly youtube: YouTube;
70
+ /** The account routes (account.get, account.update). */
71
+ readonly account: AccountResource;
72
+ /** The usage routes (usage.list). */
73
+ readonly usage: UsageResource;
74
+ /** The credit_transactions routes (credit_transactions.list). */
75
+ readonly creditTransactions: CreditTransactionsResource;
76
+ /** The billing routes (sub-resources only). */
77
+ readonly billing: BillingResource;
78
+ /** The requests routes (requests.list, requests.get, requests.get_response). */
79
+ readonly requests: RequestsResource;
80
+ /**
81
+ * The api_keys routes (api_keys.create, api_keys.list, api_keys.get, api_keys.update, api_keys.rotate_secret,
82
+ * api_keys.revoke).
83
+ */
84
+ readonly apiKeys: ApiKeysResource;
85
+ /** The jobs routes (jobs.create, jobs.list, jobs.get, jobs.cancel). */
86
+ readonly jobs: JobsResource;
87
+ /**
88
+ * The webhook_endpoints routes (webhook_endpoints.create, webhook_endpoints.list, webhook_endpoints.get,
89
+ * webhook_endpoints.update, webhook_endpoints.delete, webhook_endpoints.rotate_secret, webhook_endpoints.test).
90
+ */
91
+ readonly webhookEndpoints: WebhookEndpointsResource;
92
+ /** The events routes (events.list, events.get, events.redeliver). */
93
+ readonly events: EventsResource;
94
+ /** The notification_preferences routes (notification_preferences.get, notification_preferences.update). */
95
+ readonly notificationPreferences: NotificationPreferencesResource;
96
+ /** Webhook signature verification: client.webhooks.verify(rawBody, headers, secret). */
97
+ readonly webhooks: Webhooks;
98
+ constructor(options?: ClientOptions);
99
+ }