post-upload 0.0.0-stage → 1.2.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/CHANGELOG.md +28 -0
- package/LICENSE +21 -0
- package/README.md +525 -2
- package/dist/cli.js +297 -0
- package/dist/index.d.mts +660 -0
- package/dist/index.d.ts +660 -0
- package/dist/index.js +1034 -0
- package/dist/index.mjs +984 -0
- package/package.json +96 -4
package/dist/cli.js
ADDED
|
@@ -0,0 +1,297 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";
|
|
3
|
+
|
|
4
|
+
// src/version.ts
|
|
5
|
+
var VERSION = "1.2.0";
|
|
6
|
+
|
|
7
|
+
// src/mcp-bridge.ts
|
|
8
|
+
var import_readline = require("readline");
|
|
9
|
+
var DEFAULT_MCP_URL = "https://api.post-upload.com/mcp";
|
|
10
|
+
var DEFAULT_MCP_TIMEOUT_MS = 3e5;
|
|
11
|
+
var TRANSPORT_ERROR_CODE = -32e3;
|
|
12
|
+
var PARSE_ERROR_CODE = -32700;
|
|
13
|
+
var INTERNAL_ERROR_CODE = -32603;
|
|
14
|
+
function parseSseData(text) {
|
|
15
|
+
const out = [];
|
|
16
|
+
for (const block of text.split(/\r?\n\r?\n/)) {
|
|
17
|
+
let event = "message";
|
|
18
|
+
const data = [];
|
|
19
|
+
for (const line of block.split(/\r?\n/)) {
|
|
20
|
+
if (line.startsWith(":")) continue;
|
|
21
|
+
const idx = line.indexOf(":");
|
|
22
|
+
const field = idx === -1 ? line : line.slice(0, idx);
|
|
23
|
+
let value = idx === -1 ? "" : line.slice(idx + 1);
|
|
24
|
+
if (value.startsWith(" ")) value = value.slice(1);
|
|
25
|
+
if (field === "event") event = value;
|
|
26
|
+
else if (field === "data") data.push(value);
|
|
27
|
+
}
|
|
28
|
+
if (event === "message" && data.length) {
|
|
29
|
+
const joined = data.join("\n");
|
|
30
|
+
if (joined.trim()) out.push(joined);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return out;
|
|
34
|
+
}
|
|
35
|
+
function isRequest(m) {
|
|
36
|
+
return !!m && typeof m === "object" && !Array.isArray(m) && typeof m.method === "string" && m.id !== void 0 && m.id !== null;
|
|
37
|
+
}
|
|
38
|
+
function isJsonRpcResponse(m) {
|
|
39
|
+
return !!m && typeof m === "object" && m.jsonrpc === "2.0" && ("error" in m || "result" in m);
|
|
40
|
+
}
|
|
41
|
+
function rpcError(id, code, message, data) {
|
|
42
|
+
const error = { code, message };
|
|
43
|
+
if (data !== void 0) error.data = data;
|
|
44
|
+
return { jsonrpc: "2.0", id, error };
|
|
45
|
+
}
|
|
46
|
+
function describeHttpError(status, statusText, body, text) {
|
|
47
|
+
let detail = "";
|
|
48
|
+
if (body && typeof body === "object") {
|
|
49
|
+
const b = body;
|
|
50
|
+
const parts = [b.error, b.error_description, b.message].filter((p) => typeof p === "string" && p);
|
|
51
|
+
detail = [...new Set(parts)].join(": ");
|
|
52
|
+
}
|
|
53
|
+
if (!detail && text.trim()) detail = text.trim().replace(/\s+/g, " ").slice(0, 200);
|
|
54
|
+
if (!detail) detail = statusText || "request failed";
|
|
55
|
+
let msg = `Post-Upload MCP server returned HTTP ${status}: ${detail}`;
|
|
56
|
+
if (status === 401 || status === 403) {
|
|
57
|
+
msg += " (check that POST_UPLOAD_API_KEY is a valid Post-Upload API key)";
|
|
58
|
+
}
|
|
59
|
+
return msg;
|
|
60
|
+
}
|
|
61
|
+
async function forwardLine(line, state, opts) {
|
|
62
|
+
const trimmed = line.trim();
|
|
63
|
+
if (!trimmed) return [];
|
|
64
|
+
let msg;
|
|
65
|
+
try {
|
|
66
|
+
msg = JSON.parse(trimmed);
|
|
67
|
+
} catch (err) {
|
|
68
|
+
opts.log(`[post-upload] ignoring invalid JSON on stdin: ${err.message}`);
|
|
69
|
+
return [rpcError(null, PARSE_ERROR_CODE, "Parse error: invalid JSON received on stdin")];
|
|
70
|
+
}
|
|
71
|
+
const isBatch = Array.isArray(msg);
|
|
72
|
+
const requests = (isBatch ? msg : [msg]).filter(isRequest);
|
|
73
|
+
const ids = requests.map((r) => r.id);
|
|
74
|
+
const isInitialize = requests.some((r) => r.method === "initialize");
|
|
75
|
+
const failAll = (code, message, data) => {
|
|
76
|
+
opts.log(`[post-upload] ${message}`);
|
|
77
|
+
if (!ids.length) return [];
|
|
78
|
+
const errors = ids.map((id) => rpcError(id, code, message, data));
|
|
79
|
+
return isBatch ? [errors] : errors;
|
|
80
|
+
};
|
|
81
|
+
const headers = {
|
|
82
|
+
Authorization: `ApiKey ${opts.apiKey}`,
|
|
83
|
+
"Content-Type": "application/json",
|
|
84
|
+
Accept: "application/json, text/event-stream",
|
|
85
|
+
"User-Agent": `post-upload-node/${VERSION}`
|
|
86
|
+
};
|
|
87
|
+
if (state.sessionId) headers["Mcp-Session-Id"] = state.sessionId;
|
|
88
|
+
if (state.protocolVersion && !isInitialize) headers["MCP-Protocol-Version"] = state.protocolVersion;
|
|
89
|
+
const controller = new AbortController();
|
|
90
|
+
const timer = setTimeout(() => controller.abort(), opts.timeoutMs);
|
|
91
|
+
let res;
|
|
92
|
+
let text;
|
|
93
|
+
try {
|
|
94
|
+
res = await opts.fetch(opts.url, { method: "POST", headers, body: trimmed, signal: controller.signal });
|
|
95
|
+
text = await res.text();
|
|
96
|
+
} catch (err) {
|
|
97
|
+
const e = err;
|
|
98
|
+
if (e?.name === "AbortError") {
|
|
99
|
+
return failAll(TRANSPORT_ERROR_CODE, `Request to Post-Upload MCP server timed out after ${Math.round(opts.timeoutMs / 1e3)}s`);
|
|
100
|
+
}
|
|
101
|
+
const cause = e?.cause;
|
|
102
|
+
const reason = cause?.code || cause?.message || e?.message || String(err);
|
|
103
|
+
return failAll(TRANSPORT_ERROR_CODE, `Could not reach Post-Upload MCP server at ${opts.url}: ${reason}`);
|
|
104
|
+
} finally {
|
|
105
|
+
clearTimeout(timer);
|
|
106
|
+
}
|
|
107
|
+
const sid = res.headers.get("mcp-session-id");
|
|
108
|
+
if (sid) state.sessionId = sid;
|
|
109
|
+
if (res.status === 202 || res.status === 204) return [];
|
|
110
|
+
const contentType = (res.headers.get("content-type") || "").toLowerCase();
|
|
111
|
+
const payloads = [];
|
|
112
|
+
let undecodable = false;
|
|
113
|
+
const chunks = contentType.includes("text/event-stream") ? parseSseData(text) : text.trim() ? [text] : [];
|
|
114
|
+
for (const chunk of chunks) {
|
|
115
|
+
try {
|
|
116
|
+
payloads.push(JSON.parse(chunk));
|
|
117
|
+
} catch {
|
|
118
|
+
undecodable = true;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
if (!res.ok) {
|
|
122
|
+
if (res.status === 404 && state.sessionId) {
|
|
123
|
+
opts.log("[post-upload] MCP session expired; the client must re-initialize");
|
|
124
|
+
state.sessionId = null;
|
|
125
|
+
}
|
|
126
|
+
const rpc = payloads.filter((p) => isJsonRpcResponse(p) || Array.isArray(p) && p.some(isJsonRpcResponse));
|
|
127
|
+
if (rpc.length) {
|
|
128
|
+
opts.log(`[post-upload] HTTP ${res.status} with JSON-RPC error body (passed through)`);
|
|
129
|
+
return rpc;
|
|
130
|
+
}
|
|
131
|
+
return failAll(
|
|
132
|
+
TRANSPORT_ERROR_CODE,
|
|
133
|
+
describeHttpError(res.status, res.statusText, payloads[0], text),
|
|
134
|
+
{ httpStatus: res.status, body: payloads[0] ?? (text.trim() ? text.slice(0, 500) : null) }
|
|
135
|
+
);
|
|
136
|
+
}
|
|
137
|
+
if (!payloads.length) {
|
|
138
|
+
if (undecodable) return failAll(INTERNAL_ERROR_CODE, "Post-Upload MCP server returned a response that is not valid JSON");
|
|
139
|
+
return ids.length ? failAll(INTERNAL_ERROR_CODE, `Post-Upload MCP server returned an empty response (HTTP ${res.status})`) : [];
|
|
140
|
+
}
|
|
141
|
+
if (isInitialize) {
|
|
142
|
+
for (const p of payloads.flat()) {
|
|
143
|
+
const v = p?.result?.protocolVersion;
|
|
144
|
+
if (typeof v === "string") state.protocolVersion = v;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
return payloads;
|
|
148
|
+
}
|
|
149
|
+
async function runMcpBridge(options) {
|
|
150
|
+
if (!options.apiKey) throw new Error("apiKey is required");
|
|
151
|
+
const input = options.input || process.stdin;
|
|
152
|
+
const output = options.output || process.stdout;
|
|
153
|
+
const log = options.log || ((m) => process.stderr.write(`${m}
|
|
154
|
+
`));
|
|
155
|
+
const fetchImpl = options.fetch || globalThis.fetch;
|
|
156
|
+
if (typeof fetchImpl !== "function") throw new Error("global fetch is unavailable; Node.js >= 18 is required");
|
|
157
|
+
const opts = {
|
|
158
|
+
apiKey: options.apiKey,
|
|
159
|
+
url: options.url || DEFAULT_MCP_URL,
|
|
160
|
+
timeoutMs: options.timeoutMs || DEFAULT_MCP_TIMEOUT_MS,
|
|
161
|
+
fetch: fetchImpl,
|
|
162
|
+
log
|
|
163
|
+
};
|
|
164
|
+
const state = { sessionId: null, protocolVersion: null, initGate: null };
|
|
165
|
+
const inflight = /* @__PURE__ */ new Set();
|
|
166
|
+
const write = (payload) => {
|
|
167
|
+
output.write(`${JSON.stringify(payload)}
|
|
168
|
+
`);
|
|
169
|
+
};
|
|
170
|
+
const handle = async (line) => {
|
|
171
|
+
const gate = state.initGate;
|
|
172
|
+
if (gate) await gate;
|
|
173
|
+
try {
|
|
174
|
+
for (const payload of await forwardLine(line, state, opts)) write(payload);
|
|
175
|
+
} catch (err) {
|
|
176
|
+
log(`[post-upload] unexpected bridge error: ${err?.stack || String(err)}`);
|
|
177
|
+
}
|
|
178
|
+
};
|
|
179
|
+
const rl = (0, import_readline.createInterface)({ input, crlfDelay: Infinity, terminal: false });
|
|
180
|
+
for await (const line of rl) {
|
|
181
|
+
if (!line.trim()) continue;
|
|
182
|
+
let initializing = false;
|
|
183
|
+
try {
|
|
184
|
+
const parsed = JSON.parse(line);
|
|
185
|
+
initializing = (Array.isArray(parsed) ? parsed : [parsed]).some((m) => m && m.method === "initialize");
|
|
186
|
+
} catch {
|
|
187
|
+
}
|
|
188
|
+
const p = handle(line);
|
|
189
|
+
inflight.add(p);
|
|
190
|
+
p.finally(() => inflight.delete(p));
|
|
191
|
+
if (initializing) state.initGate = p.then(() => void 0);
|
|
192
|
+
}
|
|
193
|
+
await Promise.allSettled([...inflight]);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// src/cli.ts
|
|
197
|
+
var HELP = `post-upload ${VERSION} \u2014 Post-Upload CLI
|
|
198
|
+
|
|
199
|
+
Usage:
|
|
200
|
+
post-upload mcp Run the stdio MCP bridge (for Claude Desktop, Cursor, ...)
|
|
201
|
+
post-upload --version Print the version
|
|
202
|
+
post-upload --help Show this help
|
|
203
|
+
|
|
204
|
+
Environment (mcp):
|
|
205
|
+
POST_UPLOAD_API_KEY Required. Your Post-Upload API key.
|
|
206
|
+
POST_UPLOAD_MCP_URL Optional. MCP endpoint (default: ${DEFAULT_MCP_URL}).
|
|
207
|
+
POST_UPLOAD_MCP_TIMEOUT_MS Optional. Per-request timeout (default: ${DEFAULT_MCP_TIMEOUT_MS}).
|
|
208
|
+
(The former INDREELFORGE_* names are still read as a fallback.)
|
|
209
|
+
|
|
210
|
+
Example MCP client config:
|
|
211
|
+
{
|
|
212
|
+
"mcpServers": {
|
|
213
|
+
"post-upload": {
|
|
214
|
+
"command": "npx",
|
|
215
|
+
"args": ["-y", "post-upload", "mcp"],
|
|
216
|
+
"env": { "POST_UPLOAD_API_KEY": "your-api-key" }
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
`;
|
|
221
|
+
function fail(message) {
|
|
222
|
+
process.stderr.write(`post-upload: ${message}
|
|
223
|
+
`);
|
|
224
|
+
process.exit(1);
|
|
225
|
+
}
|
|
226
|
+
function env(name) {
|
|
227
|
+
const current = `POST_UPLOAD_${name}`;
|
|
228
|
+
const legacy = `INDREELFORGE_${name}`;
|
|
229
|
+
if (process.env[current]) return { value: process.env[current], key: current };
|
|
230
|
+
if (process.env[legacy]) return { value: process.env[legacy], key: legacy };
|
|
231
|
+
return { value: void 0, key: current };
|
|
232
|
+
}
|
|
233
|
+
async function runMcp() {
|
|
234
|
+
const major = Number(process.versions.node.split(".")[0]);
|
|
235
|
+
if (!Number.isFinite(major) || major < 18) {
|
|
236
|
+
fail(`Node.js >= 18 is required (found ${process.versions.node}).`);
|
|
237
|
+
}
|
|
238
|
+
const apiKey = (env("API_KEY").value || "").trim();
|
|
239
|
+
if (!apiKey) {
|
|
240
|
+
fail(
|
|
241
|
+
'POST_UPLOAD_API_KEY is not set. Create an API key at https://post-upload.com/dashboard and pass it via the "env" block of your MCP client config.'
|
|
242
|
+
);
|
|
243
|
+
}
|
|
244
|
+
const urlEnv = env("MCP_URL");
|
|
245
|
+
const url = (urlEnv.value || "").trim() || DEFAULT_MCP_URL;
|
|
246
|
+
try {
|
|
247
|
+
const parsed = new URL(url);
|
|
248
|
+
if (parsed.protocol !== "https:" && parsed.protocol !== "http:") throw new Error("unsupported protocol");
|
|
249
|
+
} catch {
|
|
250
|
+
fail(`${urlEnv.key} is not a valid http(s) URL: ${url}`);
|
|
251
|
+
}
|
|
252
|
+
const timeoutEnv = env("MCP_TIMEOUT_MS");
|
|
253
|
+
const timeoutRaw = timeoutEnv.value;
|
|
254
|
+
const timeoutMs = timeoutRaw ? Number(timeoutRaw) : DEFAULT_MCP_TIMEOUT_MS;
|
|
255
|
+
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
|
|
256
|
+
fail(`${timeoutEnv.key} must be a positive number of milliseconds (got "${timeoutRaw}").`);
|
|
257
|
+
}
|
|
258
|
+
process.stdout.on("error", (err) => {
|
|
259
|
+
if (err.code === "EPIPE") process.exit(0);
|
|
260
|
+
process.stderr.write(`post-upload: stdout error: ${err.message}
|
|
261
|
+
`);
|
|
262
|
+
process.exit(1);
|
|
263
|
+
});
|
|
264
|
+
process.stderr.write(`[post-upload] MCP bridge v${VERSION} -> ${url}
|
|
265
|
+
`);
|
|
266
|
+
await runMcpBridge({ apiKey, url, timeoutMs });
|
|
267
|
+
}
|
|
268
|
+
async function main(argv) {
|
|
269
|
+
const args = argv.filter((a) => a !== "--");
|
|
270
|
+
if (args.includes("--version") || args.includes("-v")) {
|
|
271
|
+
process.stdout.write(`${VERSION}
|
|
272
|
+
`);
|
|
273
|
+
return;
|
|
274
|
+
}
|
|
275
|
+
if (args.includes("--help") || args.includes("-h")) {
|
|
276
|
+
process.stdout.write(HELP);
|
|
277
|
+
return;
|
|
278
|
+
}
|
|
279
|
+
const [command] = args;
|
|
280
|
+
if (!command) {
|
|
281
|
+
process.stderr.write(HELP);
|
|
282
|
+
process.exit(1);
|
|
283
|
+
}
|
|
284
|
+
if (command === "mcp") {
|
|
285
|
+
await runMcp();
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
process.stderr.write(`post-upload: unknown command "${command}"
|
|
289
|
+
|
|
290
|
+
${HELP}`);
|
|
291
|
+
process.exit(1);
|
|
292
|
+
}
|
|
293
|
+
main(process.argv.slice(2)).catch((err) => {
|
|
294
|
+
process.stderr.write(`post-upload: ${err?.stack || String(err)}
|
|
295
|
+
`);
|
|
296
|
+
process.exit(1);
|
|
297
|
+
});
|