src/adapters.js
// Official-API adapters for social-publisher's publish tool. Each adapter builds exactly one request to
// the platform's documented endpoint with the user's own OAuth token, and interprets the response.
// No adapter follows, likes, comments, messages or creates accounts.
import { ToolError } from "./errors.js";
import { xWeightedLength, linkedinLittleText, graphemes } from "./text.js";
const LINKEDIN_URN = /^urn:li:(person|organization):[A-Za-z0-9_-]{1,100}$/;
const FB_PAGE_ID = /^\d{1,30}$/;
async function readJson(res, maxChars = 1_000_000) {
const text = await res.text();
if (text.length > maxChars) throw new ToolError("platform_error", "Platform response was unexpectedly large");
try {
return JSON.parse(text);
} catch {
return null;
}
}
const short = (v) => (typeof v === "string" ? v.slice(0, 300) : "no error message");
function commonErrors(platform, res, json, credential) {
if (res.status === 401 || res.status === 403 || json?.error?.code === 190) {
// The platform's own reason (for example X "client-not-enrolled" when the developer plan has no
// write access) is passed on so a plan or permission problem is not mistaken for a bad token.
const reason = [json?.reason, json?.detail ?? json?.message ?? json?.error?.message ?? json?.title].filter((v) => typeof v === "string" && v.trim()).join(": ");
throw new ToolError(
"auth_error",
`${platform} refused the request (HTTP ${res.status})${reason ? `: ${short(reason).replace(/[\u0000-\u001f\u007f]/g, " ")}` : ""}. Check that ${credential} is a valid OAuth token for your own account with the posting scope, and that your app or plan allows posting.`,
);
}
if (res.status >= 500) {
throw new ToolError(
"outcome_unknown",
`${platform} returned HTTP ${res.status}. The post may or may not have been created: check the account before retrying (the idempotency key stays the same).`,
);
}
const msg = json?.detail ?? json?.message ?? json?.error?.message ?? json?.title;
throw new ToolError("platform_error", `${platform} API returned HTTP ${res.status}: ${short(msg)}`);
}
export const ADAPTERS = {
x: {
credential: "X_USER_ACCESS_TOKEN",
build({ item }) {
const len = xWeightedLength(item.text);
if (len > 280) throw new ToolError("too_long", `Text weighs ${len} on X; the limit is 280.`);
return { url: "https://api.x.com/2/tweets", headers: { "content-type": "application/json" }, body: JSON.stringify({ text: item.text }), payload: { text: item.text } };
},
async parse(res) {
const json = await readJson(res);
if ((res.status === 201 || res.status === 200) && typeof json?.data?.id === "string") {
return { status: "published", remote_id: json.data.id, url: `https://x.com/i/web/status/${encodeURIComponent(json.data.id)}` };
}
if (res.status === 403 && /duplicate/i.test(String(json?.detail ?? json?.title ?? ""))) return { status: "already_published", note: "X reported duplicate content: this text was already posted from this account." };
return commonErrors("X", res, json, "X_USER_ACCESS_TOKEN");
},
},
linkedin: {
credential: "LINKEDIN_ACCESS_TOKEN",
build({ item, input, account }) {
if (!LINKEDIN_URN.test(account)) throw new ToolError("invalid_input", "item.account must be the LinkedIn author URN (urn:li:person:... or urn:li:organization:...).");
const len = [...item.text].length;
if (len > 3000) throw new ToolError("too_long", `Text has ${len} characters; LinkedIn allows 3000.`);
const payload = {
author: account,
commentary: linkedinLittleText(item.text),
visibility: "PUBLIC",
distribution: { feedDistribution: "MAIN_FEED", targetEntities: [], thirdPartyDistributionChannels: [] },
lifecycleState: "PUBLISHED",
isReshareDisabledByAuthor: false,
};
return {
url: "https://api.linkedin.com/rest/posts",
headers: { "content-type": "application/json", "linkedin-version": input.linkedin_version ?? "202610", "x-restli-protocol-version": "2.0.0" },
body: JSON.stringify(payload),
payload,
};
},
async parse(res) {
const id = res.headers.get("x-restli-id") ?? res.headers.get("x-linkedin-id");
if (res.status === 201 && id) return { status: "published", remote_id: id, url: `https://www.linkedin.com/feed/update/${id}/` };
const json = await readJson(res);
if (res.status === 426) throw new ToolError("platform_error", "LinkedIn rejected the LinkedIn-Version header (HTTP 426). Pass a currently supported linkedin_version (YYYYMM).");
return commonErrors("LinkedIn", res, json, "LINKEDIN_ACCESS_TOKEN");
},
},
facebook: {
credential: "FACEBOOK_PAGE_ACCESS_TOKEN",
build({ item, input, account, token }) {
if (!FB_PAGE_ID.test(account)) throw new ToolError("invalid_input", "item.account must be the numeric Facebook Page id.");
const len = [...item.text].length;
if (len > 5000) throw new ToolError("too_long", `Text has ${len} characters; this agent's Facebook limit is 5000.`);
const payload = { message: item.text };
if (item.link) payload.link = item.link;
const version = input.graph_api_version ?? "v23.0";
// The token goes in the POST body (not the URL) so it never appears in URLs or this tool's output.
const body = new URLSearchParams({ ...payload, access_token: token }).toString();
return { url: `https://graph.facebook.com/${version}/${account}/feed`, headers: { "content-type": "application/x-www-form-urlencoded" }, body, payload, tokenInBody: true };
},
async parse(res) {
const json = await readJson(res);
if (res.ok && typeof json?.id === "string") return { status: "published", remote_id: json.id, url: `https://www.facebook.com/${encodeURIComponent(json.id)}` };
return commonErrors("Facebook", res, json, "FACEBOOK_PAGE_ACCESS_TOKEN");
},
},
youtube: {
credential: "YOUTUBE_ACCESS_TOKEN",
build({ item, input }) {
const yt = input.youtube;
if (!yt) throw new ToolError("invalid_input", "YouTube needs youtube: {video_size_bytes, video_mime_type, made_for_kids} for the upload session.");
const title = String(item.title ?? "").trim();
if (!title) throw new ToolError("invalid_input", "YouTube needs item.title.");
if (graphemes(title).length > 100) throw new ToolError("too_long", "YouTube titles are limited to 100 characters.");
if (Buffer.byteLength(item.text, "utf8") > 5000) throw new ToolError("too_long", "YouTube descriptions are limited to 5000 bytes.");
if (/[<>]/.test(title + item.text)) throw new ToolError("invalid_input", "YouTube rejects < and > in titles and descriptions.");
const tags = yt.tags ?? [];
const tagChars = tags.reduce((n, t) => n + [...t].length + (/\s/.test(t) ? 2 : 0), 0) + Math.max(0, tags.length - 1);
if (tagChars > 500) throw new ToolError("too_long", "YouTube tags may total at most 500 characters.");
const payload = {
snippet: { title, description: item.text, categoryId: yt.category_id ?? "22", ...(tags.length ? { tags } : {}) },
status: { privacyStatus: yt.privacy_status ?? "private", selfDeclaredMadeForKids: yt.made_for_kids },
};
return {
url: "https://www.googleapis.com/upload/youtube/v3/videos?uploadType=resumable&part=snippet,status",
headers: { "content-type": "application/json; charset=UTF-8", "x-upload-content-length": String(yt.video_size_bytes), "x-upload-content-type": yt.video_mime_type },
body: JSON.stringify(payload),
payload,
};
},
async parse(res) {
const loc = res.headers.get("location");
if (res.status === 200 && loc) {
let u;
try {
u = new URL(loc);
} catch {
throw new ToolError("platform_error", "YouTube returned an invalid upload session URL.");
}
if (u.protocol !== "https:" || u.hostname !== "www.googleapis.com") throw new ToolError("platform_error", "YouTube returned an upload session URL on an unexpected host; refusing to use it.");
return { status: "upload_session_created", upload_url: u.toString() };
}
const json = await readJson(res);
return commonErrors("YouTube", res, json, "YOUTUBE_ACCESS_TOKEN");
},
},
};
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
/** Seconds to wait after HTTP 429 (Retry-After seconds or date, or X's x-rate-limit-reset epoch), or null. */
function retryAfterSeconds(res, nowMs) {
const ra = res.headers.get("retry-after");
if (ra !== null) {
if (/^\d+$/.test(ra.trim())) return Number(ra.trim());
const d = Date.parse(ra);
if (!Number.isNaN(d)) return Math.max(0, Math.ceil((d - nowMs) / 1000));
}
const reset = res.headers.get("x-rate-limit-reset");
if (reset !== null && /^\d+$/.test(reset.trim())) return Math.max(0, Number(reset.trim()) - Math.floor(nowMs / 1000));
return null;
}
/**
* Sends the request. Retries only on HTTP 429 (the platform did not accept the request), at most twice,
* honouring Retry-After up to maxWaitSeconds. Never retries 5xx or network errors, where the post may exist.
*/
export async function send(ctx, req, token, maxWaitSeconds, key) {
const headers = { ...req.headers, accept: "application/json" };
if (!req.tokenInBody) headers.authorization = `Bearer ${token}`;
for (let attempt = 1; attempt <= 3; attempt++) {
let res;
try {
res = await ctx.fetch(req.url, { method: "POST", redirect: "error", headers, body: req.body });
} catch (e) {
if (e?.code === "network_denied") throw e;
throw new ToolError(
"outcome_unknown",
`Request failed (${e?.name === "TimeoutError" ? "timed out" : "network error"}). The post may or may not have been created: check the account before retrying with the same idempotency key ${key}.`,
);
}
if (res.status !== 429) return { res, attempts: attempt };
const wait = retryAfterSeconds(res, ctx.now().getTime());
await res.body?.cancel?.().catch(() => {});
if (attempt === 3 || wait === null || wait > maxWaitSeconds) {
throw new ToolError("rate_limited", `Rate limited (HTTP 429)${wait !== null ? `; retry after about ${wait} s` : ""}. Nothing was posted.`);
}
await sleep(wait * 1000);
}
throw new ToolError("rate_limited", "Rate limited (HTTP 429). Nothing was posted.");
}