-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathkit.js
More file actions
2236 lines (2190 loc) · 88.9 KB
/
Copy pathkit.js
File metadata and controls
2236 lines (2190 loc) · 88.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// The utility kit: many small, deterministic, pay-per-call tools.
// Each entry: { route, name, slug, category, price, description, tags,
// discovery, mimeType?, handler(input) -> result | { __binary, contentType } }
// Handlers receive merged { ...query, ...body } and throw { statusCode: 400 }
// (via bad()) for invalid input.
import { createHash, createHmac, randomBytes, randomUUID, randomInt } from "node:crypto";
import { resolveMx, reverse } from "node:dns/promises";
import { isIP } from "node:net";
import tls from "node:tls";
import { lookup } from "node:dns/promises";
import { Worker } from "node:worker_threads";
import { fileURLToPath } from "node:url";
import { JSDOM } from "jsdom";
import TurndownService from "turndown";
// Named imports, not a default import: js-yaml v5 dropped the default export
// ("does not provide an export named 'default'", which broke the v5 bump on
// CI). Named imports resolve on both v4 (synthesized from the CJS build) and
// v5, so this stays correct across the upgrade.
import { load as yamlLoad, dump as yamlDump, JSON_SCHEMA as YAML_JSON_SCHEMA } from "js-yaml";
import { marked } from "marked";
import QRCode from "qrcode";
import { assertPublicUrl, safeFetch, ssrfDispatcher, isSsrfBlock } from "./fetch-guard.js";
const REGEX_WORKER = fileURLToPath(new URL("./regex-worker.js", import.meta.url));
const REGEX_TIMEOUT_MS = 750;
// Run a user regex in a worker thread with a hard timeout. ReDoS patterns are
// contained to a single terminated worker instead of freezing the event loop.
function runRegexSafely({ pattern, flags, text, maxMatches }) {
return new Promise((resolve, reject) => {
const worker = new Worker(REGEX_WORKER, { workerData: { pattern, flags, text, maxMatches } });
let done = false;
const finish = (fn, arg) => {
if (done) return;
done = true;
clearTimeout(timer);
worker.terminate();
fn(arg);
};
const timer = setTimeout(
() => finish(reject, bad("Regex timed out (>750ms) - pattern likely has catastrophic backtracking")),
REGEX_TIMEOUT_MS
);
worker.on("message", (msg) =>
msg.error ? finish(reject, bad(msg.error)) : finish(resolve, msg)
);
worker.on("error", (e) => finish(reject, bad(`Regex execution error: ${e.message}`)));
worker.on("exit", (code) => {
if (!done && code !== 0) finish(reject, bad("Regex worker stopped unexpectedly"));
});
});
}
function bad(message) {
const err = new Error(message);
err.statusCode = 400;
return err;
}
function need(input, field, type = "string") {
const v = input[field];
if (v === undefined || v === null || (type === "string" && typeof v !== "string"))
throw bad(`Missing or invalid "${field}"`);
return v;
}
function capText(text, max = 100_000, label = "text") {
if (typeof text !== "string") throw bad(`"${label}" must be a string`);
if (text.length > max) throw bad(`"${label}" exceeds ${max} characters`);
return text;
}
function parseMaybeJson(value, label) {
if (typeof value !== "string") return value;
try {
return JSON.parse(value);
} catch (e) {
throw bad(`"${label}" is not valid JSON: ${e.message}`);
}
}
// ---------------------------------------------------------------------------
// Encoding & crypto
// ---------------------------------------------------------------------------
const HASH_ALGOS = ["sha256", "sha512", "sha1", "md5"];
const B32_CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
function ulid(time = Date.now()) {
let out = "";
let t = time;
for (let i = 0; i < 10; i++) {
out = B32_CROCKFORD[t % 32] + out;
t = Math.floor(t / 32);
}
const rand = randomBytes(16);
for (let i = 0; i < 16; i++) out += B32_CROCKFORD[rand[i] % 32];
return out;
}
function uuidV7() {
const bytes = randomBytes(16);
const ms = BigInt(Date.now());
bytes[0] = Number((ms >> 40n) & 0xffn);
bytes[1] = Number((ms >> 32n) & 0xffn);
bytes[2] = Number((ms >> 24n) & 0xffn);
bytes[3] = Number((ms >> 16n) & 0xffn);
bytes[4] = Number((ms >> 8n) & 0xffn);
bytes[5] = Number(ms & 0xffn);
bytes[6] = (bytes[6] & 0x0f) | 0x70;
bytes[8] = (bytes[8] & 0x3f) | 0x80;
const hex = bytes.toString("hex");
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
}
function base32Decode(str) {
const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
const clean = str.toUpperCase().replace(/=+$/, "").replace(/\s/g, "");
let bits = 0;
let value = 0;
const out = [];
for (const ch of clean) {
const idx = alphabet.indexOf(ch);
if (idx === -1) throw bad("Invalid base32 secret");
value = (value << 5) | idx;
bits += 5;
if (bits >= 8) {
out.push((value >>> (bits - 8)) & 0xff);
bits -= 8;
}
}
return Buffer.from(out);
}
const encodingTools = [
{
route: "POST /api/hash",
name: "Hash",
slug: "hash",
category: "encoding",
price: "$0.001",
description: "Cryptographic hash of a text string. Algorithms: sha256 (default), sha512, sha1, md5. Returns hex and base64 digests.",
tags: ["hash", "sha256", "checksum", "crypto"],
discovery: {
bodyType: "json",
input: { text: "hello world", algo: "sha256" },
inputSchema: {
properties: {
text: { type: "string", description: "Text to hash (max 100KB)" },
algo: { type: "string", description: "sha256 | sha512 | sha1 | md5" },
},
required: ["text"],
},
output: { example: { algo: "sha256", hex: "b94d27…", base64: "uU0n…" } },
},
handler: (input) => {
const text = capText(need(input, "text"));
const algo = (input.algo || "sha256").toLowerCase();
if (!HASH_ALGOS.includes(algo)) throw bad(`algo must be one of: ${HASH_ALGOS.join(", ")}`);
const h = createHash(algo).update(text);
const buf = h.digest();
return { algo, hex: buf.toString("hex"), base64: buf.toString("base64") };
},
},
{
route: "POST /api/hmac",
name: "HMAC",
slug: "hmac",
category: "encoding",
price: "$0.001",
description: "HMAC signature of a message with a shared key. Algorithms: sha256 (default), sha512, sha1. Returns hex and base64.",
tags: ["hmac", "signature", "webhook", "crypto"],
discovery: {
bodyType: "json",
input: { text: "payload", key: "secret", algo: "sha256" },
inputSchema: {
properties: {
text: { type: "string", description: "Message to sign (max 100KB)" },
key: { type: "string", description: "Shared secret key" },
algo: { type: "string", description: "sha256 | sha512 | sha1" },
},
required: ["text", "key"],
},
output: { example: { algo: "sha256", hex: "f7bc…", base64: "97w…" } },
},
handler: (input) => {
const text = capText(need(input, "text"));
const key = need(input, "key");
const algo = (input.algo || "sha256").toLowerCase();
if (!["sha256", "sha512", "sha1"].includes(algo)) throw bad("algo must be sha256, sha512, or sha1");
const buf = createHmac(algo, key).update(text).digest();
return { algo, hex: buf.toString("hex"), base64: buf.toString("base64") };
},
},
{
route: "POST /api/base64",
name: "Base64",
slug: "base64",
category: "encoding",
price: "$0.001",
description: "Base64 encode or decode text. mode: encode (default) or decode. Handles URL-safe base64 on decode.",
tags: ["base64", "encode", "decode"],
discovery: {
bodyType: "json",
input: { text: "hello", mode: "encode" },
inputSchema: {
properties: {
text: { type: "string", description: "Input text (max 100KB)" },
mode: { type: "string", description: "encode | decode" },
},
required: ["text"],
},
output: { example: { mode: "encode", result: "aGVsbG8=" } },
},
handler: (input) => {
const text = capText(need(input, "text"));
const mode = input.mode === "decode" ? "decode" : "encode";
if (mode === "encode") return { mode, result: Buffer.from(text, "utf8").toString("base64") };
const normalized = text.replace(/-/g, "+").replace(/_/g, "/");
const decoded = Buffer.from(normalized, "base64");
return { mode, result: decoded.toString("utf8") };
},
},
{
route: "POST /api/hex",
name: "Hex",
slug: "hex",
category: "encoding",
price: "$0.001",
description: "Hex encode or decode text. mode: encode (default) or decode.",
tags: ["hex", "encode", "decode"],
discovery: {
bodyType: "json",
input: { text: "hi", mode: "encode" },
inputSchema: {
properties: {
text: { type: "string", description: "Input text (max 100KB)" },
mode: { type: "string", description: "encode | decode" },
},
required: ["text"],
},
output: { example: { mode: "encode", result: "6869" } },
},
handler: (input) => {
const text = capText(need(input, "text"));
const mode = input.mode === "decode" ? "decode" : "encode";
if (mode === "encode") return { mode, result: Buffer.from(text, "utf8").toString("hex") };
if (!/^[0-9a-fA-F]*$/.test(text) || text.length % 2) throw bad("Not a valid hex string");
return { mode, result: Buffer.from(text, "hex").toString("utf8") };
},
},
{
route: "POST /api/url-code",
name: "URL encode/decode",
slug: "url-code",
category: "encoding",
price: "$0.001",
description: "Percent-encode or decode a string for URLs. mode: encode (default) or decode. component: true (default) uses encodeURIComponent semantics.",
tags: ["url", "percent-encoding", "encode", "decode"],
discovery: {
bodyType: "json",
input: { text: "a b&c", mode: "encode" },
inputSchema: {
properties: {
text: { type: "string", description: "Input text (max 100KB)" },
mode: { type: "string", description: "encode | decode" },
component: { type: "boolean", description: "Use component encoding (default true)" },
},
required: ["text"],
},
output: { example: { mode: "encode", result: "a%20b%26c" } },
},
handler: (input) => {
const text = capText(need(input, "text"));
const mode = input.mode === "decode" ? "decode" : "encode";
const component = input.component !== false && input.component !== "false";
try {
const result =
mode === "encode"
? component
? encodeURIComponent(text)
: encodeURI(text)
: component
? decodeURIComponent(text)
: decodeURI(text);
return { mode, result };
} catch {
throw bad("Malformed percent-encoding");
}
},
},
{
route: "POST /api/jwt-decode",
name: "JWT decode",
slug: "jwt-decode",
category: "encoding",
price: "$0.001",
description: "Decode a JWT without verification: header, payload, expiry status, and time remaining. (Decoding only - signatures are NOT verified.)",
tags: ["jwt", "token", "auth", "decode"],
discovery: {
bodyType: "json",
input: { token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhZ2VudDQwMiIsIm5hbWUiOiJkZW1vIGFnZW50IiwiaWF0IjoxNzAwMDAwMDAwLCJleHAiOjk5OTk5OTk5OTl9.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c" },
inputSchema: {
properties: { token: { type: "string", description: "The JWT string" } },
required: ["token"],
},
output: { example: { header: { alg: "HS256" }, payload: { sub: "agent402", exp: 9999999999 }, expired: false } },
},
handler: (input) => {
const token = capText(need(input, "token"), 16_384, "token");
const parts = token.split(".");
if (parts.length < 2) throw bad("Not a JWT (expected at least 2 dot-separated segments)");
const decode = (seg) => {
try {
return JSON.parse(Buffer.from(seg.replace(/-/g, "+").replace(/_/g, "/"), "base64").toString("utf8"));
} catch {
throw bad("JWT segment is not valid base64url JSON");
}
};
const header = decode(parts[0]);
const payload = decode(parts[1]);
const now = Math.floor(Date.now() / 1000);
const expired = typeof payload.exp === "number" ? payload.exp < now : null;
return {
header,
payload,
signaturePresent: parts.length === 3 && parts[2].length > 0,
verified: false,
expired,
expiresInSeconds: typeof payload.exp === "number" ? payload.exp - now : null,
};
},
},
{
route: "GET /api/uuid",
name: "UUID generator",
slug: "uuid",
category: "identifiers",
price: "$0.001",
description: "Generate UUIDs. ?version=4 (default, random) or 7 (time-ordered), ?count=1..100.",
tags: ["uuid", "id", "generator"],
discovery: {
input: { version: "7", count: "3" },
inputSchema: {
properties: {
version: { type: "string", description: "4 (random) or 7 (time-ordered)" },
count: { type: "string", description: "How many (1-100, default 1)" },
},
},
output: { example: { version: 7, uuids: ["0190a1b2-…"] } },
},
handler: (input) => {
const version = String(input.version || "4");
if (!["4", "7"].includes(version)) throw bad("version must be 4 or 7");
const count = Math.min(Math.max(parseInt(input.count, 10) || 1, 1), 100);
const gen = version === "7" ? uuidV7 : randomUUID;
return { version: Number(version), uuids: Array.from({ length: count }, () => gen()) };
},
},
{
route: "GET /api/ulid",
name: "ULID generator",
slug: "ulid",
category: "identifiers",
price: "$0.001",
description: "Generate ULIDs (sortable, timestamp-prefixed identifiers). ?count=1..100.",
tags: ["ulid", "id", "generator", "sortable"],
discovery: {
input: { count: "3" },
inputSchema: { properties: { count: { type: "string", description: "How many (1-100, default 1)" } } },
output: { example: { ulids: ["01J9ZK7M3N…"] } },
},
handler: (input) => {
const count = Math.min(Math.max(parseInt(input.count, 10) || 1, 1), 100);
return { ulids: Array.from({ length: count }, () => ulid()) };
},
},
{
route: "GET /api/password",
name: "Password generator",
slug: "password",
category: "identifiers",
price: "$0.001",
description: "Generate cryptographically random passwords. ?length=8..128 (default 24), ?symbols=true|false (default true), ?count=1..20.",
tags: ["password", "random", "generator", "security"],
discovery: {
input: { length: "32", symbols: "true", count: "1" },
inputSchema: {
properties: {
length: { type: "string", description: "8-128, default 24" },
symbols: { type: "string", description: "Include symbols (default true)" },
count: { type: "string", description: "How many (1-20, default 1)" },
},
},
output: { example: { passwords: ["k9#mP2…"], entropyBits: 190 } },
},
handler: (input) => {
const length = Math.min(Math.max(parseInt(input.length, 10) || 24, 8), 128);
const symbols = input.symbols !== "false" && input.symbols !== false;
const count = Math.min(Math.max(parseInt(input.count, 10) || 1, 1), 20);
const alphabet =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" + (symbols ? "!@#$%^&*()-_=+[]{}<>?" : "");
const make = () => Array.from({ length }, () => alphabet[randomInt(alphabet.length)]).join("");
return {
passwords: Array.from({ length: count }, make),
entropyBits: Math.floor(length * Math.log2(alphabet.length)),
};
},
},
{
route: "GET /api/random",
name: "Random",
slug: "random",
category: "identifiers",
price: "$0.001",
description: "Cryptographically secure randomness. ?bytes=1..1024 returns hex; or ?min=&max= returns a uniform integer; ?count=1..100.",
tags: ["random", "entropy", "dice"],
discovery: {
input: { min: "1", max: "100", count: "3" },
inputSchema: {
properties: {
bytes: { type: "string", description: "Return N random bytes as hex (1-1024)" },
min: { type: "string", description: "Integer lower bound (inclusive)" },
max: { type: "string", description: "Integer upper bound (inclusive)" },
count: { type: "string", description: "How many values (1-100, default 1)" },
},
},
output: { example: { integers: [42, 7, 93] } },
},
handler: (input) => {
const count = Math.min(Math.max(parseInt(input.count, 10) || 1, 1), 100);
if (input.bytes !== undefined) {
const n = Math.min(Math.max(parseInt(input.bytes, 10) || 16, 1), 1024);
return { hex: Array.from({ length: count }, () => randomBytes(n).toString("hex")) };
}
const min = parseInt(input.min, 10);
const max = parseInt(input.max, 10);
if (Number.isNaN(min) || Number.isNaN(max) || max <= min) throw bad("Provide ?bytes= or integer ?min= and ?max= with max > min");
return { integers: Array.from({ length: count }, () => randomInt(min, max + 1)) };
},
},
{
route: "POST /api/totp",
name: "TOTP code",
slug: "totp",
category: "encoding",
price: "$0.002",
description: "Compute the current TOTP code (RFC 6238, 30s period, SHA-1, 6 digits) from a base32 secret. Useful for agents that must complete 2FA flows they are authorized for.",
tags: ["totp", "2fa", "otp", "authentication"],
discovery: {
bodyType: "json",
input: { secret: "JBSWY3DPEHPK3PXP" },
inputSchema: {
properties: {
secret: { type: "string", description: "Base32 TOTP secret" },
digits: { type: "number", description: "6 (default) or 8" },
},
required: ["secret"],
},
output: { example: { code: "492039", secondsRemaining: 17 } },
},
handler: (input) => {
const secret = need(input, "secret");
const digits = input.digits === 8 || input.digits === "8" ? 8 : 6;
const key = base32Decode(secret);
const counter = Math.floor(Date.now() / 1000 / 30);
const msg = Buffer.alloc(8);
msg.writeBigUInt64BE(BigInt(counter));
const digest = createHmac("sha1", key).update(msg).digest();
const offset = digest[digest.length - 1] & 0x0f;
const code = (digest.readUInt32BE(offset) & 0x7fffffff) % 10 ** digits;
return {
code: String(code).padStart(digits, "0"),
secondsRemaining: 30 - (Math.floor(Date.now() / 1000) % 30),
};
},
},
];
// ---------------------------------------------------------------------------
// Data conversion
// ---------------------------------------------------------------------------
function flatten(obj, prefix = "", out = {}) {
for (const [k, v] of Object.entries(obj)) {
const key = prefix ? `${prefix}.${k}` : k;
if (v && typeof v === "object" && !Array.isArray(v)) flatten(v, key, out);
else out[key] = Array.isArray(v) ? JSON.stringify(v) : v;
}
return out;
}
function csvEscape(v) {
const s = v === null || v === undefined ? "" : String(v);
return /[",\n\r]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
}
function parseCsv(text, delimiter = ",") {
const rows = [];
let row = [];
let field = "";
let inQuotes = false;
for (let i = 0; i < text.length; i++) {
const c = text[i];
if (inQuotes) {
if (c === '"') {
if (text[i + 1] === '"') {
field += '"';
i++;
} else inQuotes = false;
} else field += c;
} else if (c === '"') inQuotes = true;
else if (c === delimiter) {
row.push(field);
field = "";
} else if (c === "\n" || c === "\r") {
if (c === "\r" && text[i + 1] === "\n") i++;
row.push(field);
field = "";
rows.push(row);
row = [];
} else field += c;
}
if (field !== "" || row.length) {
row.push(field);
rows.push(row);
}
return rows;
}
function xmlNodeToJson(node) {
const children = [...node.children];
const attrs = {};
for (const a of node.attributes ?? []) attrs[a.name] = a.value;
const base = Object.keys(attrs).length ? { _attrs: attrs } : {};
if (!children.length) {
const text = node.textContent.trim();
return Object.keys(base).length ? { ...base, _text: text } : text;
}
const out = { ...base };
for (const child of children) {
const val = xmlNodeToJson(child);
if (out[child.tagName] === undefined) out[child.tagName] = val;
else {
if (!Array.isArray(out[child.tagName])) out[child.tagName] = [out[child.tagName]];
out[child.tagName].push(val);
}
}
return out;
}
function deepDiff(a, b, path = "", out = []) {
if (out.length >= 1000) return out;
if (a === b) return out;
const ta = a === null ? "null" : Array.isArray(a) ? "array" : typeof a;
const tb = b === null ? "null" : Array.isArray(b) ? "array" : typeof b;
if (ta !== tb || (ta !== "object" && ta !== "array")) {
out.push({ path: path || "(root)", type: "changed", a, b });
return out;
}
const keys = new Set([...Object.keys(a), ...Object.keys(b)]);
for (const k of keys) {
const p = path ? `${path}.${k}` : k;
if (!(k in a)) out.push({ path: p, type: "added", b: b[k] });
else if (!(k in b)) out.push({ path: p, type: "removed", a: a[k] });
else deepDiff(a[k], b[k], p, out);
}
return out;
}
const dataTools = [
{
route: "POST /api/json-format",
name: "JSON validate & format",
slug: "json-format",
category: "conversion",
price: "$0.001",
description: "Validate, pretty-print, or minify JSON. Returns parse errors with position when invalid.",
tags: ["json", "format", "validate", "minify"],
discovery: {
bodyType: "json",
input: { json: '{"a":1}', indent: 2 },
inputSchema: {
properties: {
json: { type: "string", description: "JSON text to validate/format (max 100KB)" },
indent: { type: "number", description: "Spaces of indentation; 0 = minify (default 2)" },
},
required: ["json"],
},
output: { example: { valid: true, formatted: '{\n "a": 1\n}' } },
},
handler: (input) => {
const text = capText(need(input, "json"), 100_000, "json");
let parsed;
try {
parsed = JSON.parse(text);
} catch (e) {
return { valid: false, error: e.message };
}
const indent = input.indent === undefined ? 2 : Math.min(Math.max(parseInt(input.indent, 10) || 0, 0), 8);
return { valid: true, formatted: JSON.stringify(parsed, null, indent || undefined) };
},
},
{
route: "POST /api/json-to-csv",
name: "JSON to CSV",
slug: "json-to-csv",
category: "conversion",
price: "$0.002",
description: "Convert a JSON array of objects to CSV. Nested objects are flattened to dot-path columns.",
tags: ["json", "csv", "convert", "spreadsheet"],
discovery: {
bodyType: "json",
input: { json: [{ name: "Ada", role: { title: "Engineer" } }] },
inputSchema: {
properties: {
json: { description: "Array of objects (or a JSON string of one)" },
delimiter: { type: "string", description: "Default ," },
},
required: ["json"],
},
output: { example: { csv: "name,role.title\nAda,Engineer\n", rows: 1, columns: 2 } },
},
handler: (input) => {
const data = parseMaybeJson(need(input, "json", "any"), "json");
if (!Array.isArray(data) || !data.length) throw bad('"json" must be a non-empty array of objects');
if (data.length > 10_000) throw bad("Max 10000 rows");
const delimiter = typeof input.delimiter === "string" && input.delimiter.length === 1 ? input.delimiter : ",";
const flat = data.map((row) => flatten(row && typeof row === "object" ? row : { value: row }));
const columns = [...new Set(flat.flatMap((r) => Object.keys(r)))];
const lines = [columns.map(csvEscape).join(delimiter)];
for (const r of flat) lines.push(columns.map((c) => csvEscape(r[c])).join(delimiter));
return { csv: lines.join("\n") + "\n", rows: data.length, columns: columns.length };
},
},
{
route: "POST /api/csv-to-json",
name: "CSV to JSON",
slug: "csv-to-json",
category: "conversion",
price: "$0.002",
description: "Parse CSV (quoted fields supported) into a JSON array of objects, using the first row as headers (header=false for arrays).",
tags: ["csv", "json", "convert", "parse"],
discovery: {
bodyType: "json",
input: { csv: "name,age\nAda,36\n" },
inputSchema: {
properties: {
csv: { type: "string", description: "CSV text (max 100KB)" },
delimiter: { type: "string", description: "Default ," },
header: { type: "boolean", description: "First row is headers (default true)" },
},
required: ["csv"],
},
output: { example: { rows: [{ name: "Ada", age: "36" }], count: 1 } },
},
handler: (input) => {
const text = capText(need(input, "csv"), 100_000, "csv");
const delimiter = typeof input.delimiter === "string" && input.delimiter.length === 1 ? input.delimiter : ",";
const grid = parseCsv(text, delimiter).filter((r) => !(r.length === 1 && r[0] === ""));
if (!grid.length) throw bad("Empty CSV");
const header = input.header !== false && input.header !== "false";
if (!header) return { rows: grid, count: grid.length };
const cols = grid[0];
const rows = grid.slice(1).map((r) => Object.fromEntries(cols.map((c, i) => [c, r[i] ?? ""])));
return { rows, count: rows.length };
},
},
{
route: "POST /api/yaml-to-json",
name: "YAML to JSON",
slug: "yaml-to-json",
category: "conversion",
price: "$0.002",
description: "Parse YAML into JSON (safe schema - no code execution).",
tags: ["yaml", "json", "convert", "config"],
discovery: {
bodyType: "json",
input: { yaml: "name: Ada\ntags:\n - eng" },
inputSchema: {
properties: { yaml: { type: "string", description: "YAML text (max 100KB)" } },
required: ["yaml"],
},
output: { example: { json: { name: "Ada", tags: ["eng"] } } },
},
handler: (input) => {
const text = capText(need(input, "yaml"), 100_000, "yaml");
try {
return { json: yamlLoad(text, { schema: YAML_JSON_SCHEMA }) ?? null };
} catch (e) {
throw bad(`YAML parse error: ${e.message.split("\n")[0]}`);
}
},
},
{
route: "POST /api/json-to-yaml",
name: "JSON to YAML",
slug: "json-to-yaml",
category: "conversion",
price: "$0.002",
description: "Convert JSON to YAML.",
tags: ["json", "yaml", "convert", "config"],
discovery: {
bodyType: "json",
input: { json: { name: "Ada", tags: ["eng"] } },
inputSchema: {
properties: { json: { description: "Any JSON value (or a JSON string of one)" } },
required: ["json"],
},
output: { example: { yaml: "name: Ada\ntags:\n - eng\n" } },
},
handler: (input) => {
const data = parseMaybeJson(need(input, "json", "any"), "json");
return { yaml: yamlDump(data, { lineWidth: 120 }) };
},
},
{
route: "POST /api/xml-to-json",
name: "XML to JSON",
slug: "xml-to-json",
category: "conversion",
price: "$0.002",
description: "Parse XML into a JSON object tree (attributes under _attrs, text under _text; repeated elements become arrays).",
tags: ["xml", "json", "convert", "parse"],
discovery: {
bodyType: "json",
input: { xml: "<user id='1'><name>Ada</name></user>" },
inputSchema: {
properties: { xml: { type: "string", description: "XML text (max 100KB)" } },
required: ["xml"],
},
output: { example: { json: { user: { _attrs: { id: "1" }, name: "Ada" } } } },
},
handler: (input) => {
const text = capText(need(input, "xml"), 100_000, "xml");
// Guard against deeply-nested XML: JSDOM's parse is superlinear in depth and
// can block the event loop for tens of seconds. Reject pathological nesting
// cheaply (single O(n) scan) before handing it to the parser.
let depth = 0, maxDepth = 0;
for (const m of text.matchAll(/<(\/)?[A-Za-z!?][^>]*?(\/)?>/g)) {
if (m[1]) depth = Math.max(0, depth - 1);
else if (!m[2] && !m[0].startsWith("<!") && !m[0].startsWith("<?")) { depth++; if (depth > maxDepth) maxDepth = depth; }
}
if (maxDepth > 256) throw bad("XML nesting too deep (max 256 levels)");
const dom = new JSDOM("");
const doc = new dom.window.DOMParser().parseFromString(text, "text/xml");
if (doc.querySelector("parsererror")) throw bad("XML parse error");
const root = doc.documentElement;
return { json: { [root.tagName]: xmlNodeToJson(root) } };
},
},
{
route: "POST /api/markdown-to-html",
name: "Markdown to HTML",
slug: "markdown-to-html",
category: "conversion",
price: "$0.002",
description: "Render CommonMark + GFM markdown to HTML.",
tags: ["markdown", "html", "convert", "render"],
discovery: {
bodyType: "json",
input: { markdown: "# Hi\n\n**bold**" },
inputSchema: {
properties: { markdown: { type: "string", description: "Markdown text (max 100KB)" } },
required: ["markdown"],
},
output: { example: { html: "<h1>Hi</h1>\n<p><strong>bold</strong></p>\n" } },
},
handler: (input) => {
const text = capText(need(input, "markdown"), 100_000, "markdown");
return { html: marked.parse(text, { async: false }) };
},
},
{
route: "POST /api/html-to-markdown",
name: "HTML to Markdown",
slug: "html-to-markdown",
category: "conversion",
price: "$0.002",
description: "Convert an HTML fragment or document you already have into clean markdown. (To fetch + convert a live URL, use /api/extract.)",
tags: ["html", "markdown", "convert"],
discovery: {
bodyType: "json",
input: { html: "<h1>Hi</h1><p><b>bold</b></p>" },
inputSchema: {
properties: { html: { type: "string", description: "HTML text (max 100KB)" } },
required: ["html"],
},
output: { example: { markdown: "# Hi\n\n**bold**" } },
},
handler: (input) => {
// Accept html under several common aliases; agents frequently call this
// with `body`, `content`, or `text` instead of `html`.
const raw = input.html ?? input.body ?? input.content ?? input.text;
if (typeof raw !== "string" || !raw) {
throw bad('Missing "html". Send {"html":"<h1>Hi</h1>..."} - alternate fields body/content/text are also accepted.');
}
const text = capText(raw, 100_000, "html");
const td = new TurndownService({ headingStyle: "atx", codeBlockStyle: "fenced" });
return { markdown: td.turndown(text) };
},
},
{
route: "POST /api/json-diff",
name: "JSON diff",
slug: "json-diff",
category: "conversion",
price: "$0.002",
description: "Deep-compare two JSON values. Returns a list of changed/added/removed paths (capped at 1000 differences).",
tags: ["json", "diff", "compare"],
discovery: {
bodyType: "json",
input: { a: { x: 1, y: 2 }, b: { x: 1, y: 3, z: 4 } },
inputSchema: {
properties: { a: { description: "First JSON value" }, b: { description: "Second JSON value" } },
required: ["a", "b"],
},
output: { example: { equal: false, differences: [{ path: "y", type: "changed", a: 2, b: 3 }, { path: "z", type: "added", b: 4 }] } },
},
handler: (input) => {
if (!("a" in input) || !("b" in input)) throw bad('Provide "a" and "b"');
const a = parseMaybeJson(input.a, "a");
const b = parseMaybeJson(input.b, "b");
const differences = deepDiff(a, b);
return { equal: differences.length === 0, differences };
},
},
{
route: "POST /api/json-query",
name: "JSON query",
slug: "json-query",
category: "conversion",
price: "$0.001",
description: 'Extract a value from JSON by dot/bracket path, e.g. "items[2].name".',
tags: ["json", "query", "jsonpath", "extract"],
discovery: {
bodyType: "json",
input: { json: { items: [{ name: "a" }, { name: "b" }] }, path: "items[1].name" },
inputSchema: {
properties: {
json: { description: "JSON value (or a JSON string of one)" },
path: { type: "string", description: 'Path like "a.b[0].c"' },
},
required: ["json", "path"],
},
output: { example: { found: true, value: "b" } },
},
handler: (input) => {
const data = parseMaybeJson(need(input, "json", "any"), "json");
const path = need(input, "path");
const segs = path.match(/[^.[\]]+/g) ?? [];
let cur = data;
for (const seg of segs) {
if (cur === null || typeof cur !== "object") return { found: false, value: null };
cur = cur[/^\d+$/.test(seg) ? Number(seg) : seg];
if (cur === undefined) return { found: false, value: null };
}
return { found: true, value: cur };
},
},
];
// ---------------------------------------------------------------------------
// Text
// ---------------------------------------------------------------------------
const STOPWORDS = new Set(
"a about above after again all also am an and any are as at be because been before being below between both but by can did do does doing down during each few for from further had has have having he her here hers herself him himself his how i if in into is it its itself just me more most my myself no nor not now of off on once only or other our ours ourselves out over own same she should so some such than that the their theirs them themselves then there these they this those through to too under until up very was we were what when where which while who whom why will with you your yours yourself yourselves".split(
" "
)
);
function splitWords(text) {
return text
.replace(/([a-z0-9])([A-Z])/g, "$1 $2")
.split(/[^A-Za-z0-9]+/)
.filter(Boolean);
}
function lineDiff(aText, bText) {
const a = aText.split("\n").slice(0, 2000);
const b = bText.split("\n").slice(0, 2000);
const m = a.length;
const n = b.length;
const lcs = Array.from({ length: m + 1 }, () => new Uint16Array(n + 1));
for (let i = m - 1; i >= 0; i--)
for (let j = n - 1; j >= 0; j--)
lcs[i][j] = a[i] === b[j] ? lcs[i + 1][j + 1] + 1 : Math.max(lcs[i + 1][j], lcs[i][j + 1]);
const ops = [];
let i = 0;
let j = 0;
while (i < m && j < n) {
if (a[i] === b[j]) {
ops.push({ op: " ", line: a[i] });
i++;
j++;
} else if (lcs[i + 1][j] >= lcs[i][j + 1]) ops.push({ op: "-", line: a[i++] });
else ops.push({ op: "+", line: b[j++] });
}
while (i < m) ops.push({ op: "-", line: a[i++] });
while (j < n) ops.push({ op: "+", line: b[j++] });
return ops;
}
const LOREM_WORDS =
"lorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua enim ad minim veniam quis nostrud exercitation ullamco laboris nisi aliquip ex ea commodo consequat duis aute irure in reprehenderit voluptate velit esse cillum eu fugiat nulla pariatur excepteur sint occaecat cupidatat non proident sunt culpa qui officia deserunt mollit anim id est laborum".split(
" "
);
const textTools = [
{
route: "POST /api/slugify",
name: "Slugify",
slug: "slugify",
category: "text",
price: "$0.001",
description: "Turn any text into a URL-safe slug (lowercase, hyphenated, diacritics stripped).",
tags: ["slug", "url", "text"],
discovery: {
bodyType: "json",
input: { text: "Héllo, Wörld! 2024" },
inputSchema: {
properties: {
text: { type: "string", description: "Text to slugify" },
separator: { type: "string", description: "Default -" },
},
required: ["text"],
},
output: { example: { slug: "hello-world-2024" } },
},
handler: (input) => {
const text = capText(need(input, "text"), 10_000);
const sep = typeof input.separator === "string" && input.separator.length === 1 ? input.separator : "-";
const slug = text
.normalize("NFKD")
.replace(/[̀-ͯ]/g, "")
.toLowerCase()
.replace(/[^a-z0-9]+/g, sep)
.replace(new RegExp(`^\\${sep}+|\\${sep}+$`, "g"), "");
return { slug };
},
},
{
route: "POST /api/case",
name: "Case convert",
slug: "case",
category: "text",
price: "$0.001",
description: "Convert text between camelCase, PascalCase, snake_case, kebab-case, CONSTANT_CASE, Title Case, lower, UPPER.",
tags: ["case", "camel", "snake", "kebab", "text"],
discovery: {
bodyType: "json",
input: { text: "hello world example", to: "camel" },
inputSchema: {
properties: {
text: { type: "string", description: "Input text" },
to: { type: "string", description: "camel | pascal | snake | kebab | constant | title | lower | upper" },
},
required: ["text", "to"],
},
output: { example: { result: "helloWorldExample" } },
},
handler: (input) => {
const text = capText(need(input, "text"), 50_000);
const to = need(input, "to").toLowerCase();
const words = splitWords(text).map((w) => w.toLowerCase());
const capitalize = (w) => w.charAt(0).toUpperCase() + w.slice(1);
const map = {
camel: () => words.map((w, i) => (i ? capitalize(w) : w)).join(""),
pascal: () => words.map(capitalize).join(""),
snake: () => words.join("_"),
kebab: () => words.join("-"),
constant: () => words.join("_").toUpperCase(),
title: () => words.map(capitalize).join(" "),
lower: () => text.toLowerCase(),
upper: () => text.toUpperCase(),
};
if (!map[to]) throw bad(`"to" must be one of: ${Object.keys(map).join(", ")}`);
return { result: map[to]() };
},
},
{
route: "POST /api/text-stats",
name: "Text statistics",
slug: "text-stats",
category: "text",
price: "$0.001",
description: "Characters, words, sentences, paragraphs, average word length, reading time, and an LLM token estimate for any text.",
tags: ["text", "statistics", "tokens", "reading-time"],
discovery: {
bodyType: "json",
input: { text: "Some long document…" },
inputSchema: {
properties: { text: { type: "string", description: "Text to analyze (max 500KB)" } },
required: ["text"],
},
output: { example: { characters: 1200, words: 210, sentences: 14, paragraphs: 4, readingTimeMinutes: 1.1, estimatedTokens: 300 } },
},
handler: (input) => {
const text = capText(need(input, "text"), 500_000);