@patchbay-nebius/agent 0.0.0-stage → 0.1.1

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/cli.js ADDED
@@ -0,0 +1,391 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ loadConfig,
4
+ missingLiveKeys,
5
+ startResearch,
6
+ startRun,
7
+ startVerify
8
+ } from "./chunk-JVXVCXNZ.js";
9
+
10
+ // src/cli.ts
11
+ import { cpSync, existsSync, mkdirSync, readdirSync as readdirSync2, readFileSync as readFileSync2, statSync as statSync2, watch, writeFileSync } from "fs";
12
+ import { basename, dirname, join as join2, relative as relative2, resolve } from "path";
13
+
14
+ // src/github-push.ts
15
+ import { readdirSync, readFileSync, statSync } from "fs";
16
+ import { join, relative } from "path";
17
+ var API = "https://api.github.com";
18
+ async function pushToGitHub(opts) {
19
+ const files = collectRunFiles(opts.runDir);
20
+ if (files.length === 0) throw new Error(`${opts.runDir} has no files to push (expected src/* and README.md).`);
21
+ const [owner, name] = opts.repo.split("/");
22
+ if (!owner || !name) throw new Error(`Expected --repo=owner/name, got "${opts.repo}"`);
23
+ const branch = opts.branch ?? `patchbay/${basenameNoSlash(opts.runDir)}`;
24
+ const title = opts.title ?? `patchbay: ${opts.targetPath}`;
25
+ const body = opts.body ?? `Generated by [patchbay](https://github.com/GodSmasher/patchbay) from \`${basenameNoSlash(opts.runDir)}\`.
26
+
27
+ Includes ${files.length} files under \`${opts.targetPath}/\`. Tests pass against the documented example in a hermetic sandbox.`;
28
+ if (opts.dryRun) {
29
+ return { prUrl: `(dry-run) would open PR on ${opts.repo}`, branch, base: opts.base ?? "(default)", files: files.map((f) => f.path) };
30
+ }
31
+ const api = createApi(opts.token);
32
+ const repo = await api(`/repos/${owner}/${name}`);
33
+ const base = opts.base ?? repo.default_branch;
34
+ const baseRef = await api(`/repos/${owner}/${name}/git/ref/heads/${base}`);
35
+ const baseSha = baseRef.object.sha;
36
+ try {
37
+ await api(`/repos/${owner}/${name}/git/refs`, {
38
+ method: "POST",
39
+ body: { ref: `refs/heads/${branch}`, sha: baseSha }
40
+ });
41
+ } catch (error) {
42
+ if (!/already exists/i.test(String(error))) throw error;
43
+ }
44
+ for (const file of files) {
45
+ const path = `${opts.targetPath}/${file.path}`.replace(/\\/g, "/");
46
+ const existing = await api(`/repos/${owner}/${name}/contents/${encodeURIComponent(path)}?ref=${branch}`).catch(() => null);
47
+ await api(`/repos/${owner}/${name}/contents/${encodeURIComponent(path)}`, {
48
+ method: "PUT",
49
+ body: {
50
+ message: `patchbay: ${path}`,
51
+ content: Buffer.from(file.content, "utf8").toString("base64"),
52
+ branch,
53
+ ...existing?.sha ? { sha: existing.sha } : {}
54
+ }
55
+ });
56
+ }
57
+ const pr = await api(`/repos/${owner}/${name}/pulls`, {
58
+ method: "POST",
59
+ body: { title, head: branch, base, body, draft: false }
60
+ });
61
+ return { prUrl: pr.html_url, branch, base, files: files.map((f) => f.path) };
62
+ }
63
+ function collectRunFiles(root) {
64
+ const out = [];
65
+ const walk = (dir) => {
66
+ for (const entry of readdirSync(dir)) {
67
+ if (entry === "run.json" || entry.startsWith(".")) continue;
68
+ const abs = join(dir, entry);
69
+ const st = statSync(abs);
70
+ if (st.isDirectory()) walk(abs);
71
+ else out.push({ path: relative(root, abs).replace(/\\/g, "/"), content: readFileSync(abs, "utf8") });
72
+ }
73
+ };
74
+ walk(root);
75
+ return out;
76
+ }
77
+ function basenameNoSlash(path) {
78
+ return path.replace(/[\\/]+$/, "").split(/[\\/]/).pop() ?? "run";
79
+ }
80
+ function createApi(token) {
81
+ return async (path, init = {}) => {
82
+ const res = await fetch(`${API}${path}`, {
83
+ method: init.method ?? "GET",
84
+ headers: {
85
+ Authorization: `Bearer ${token}`,
86
+ Accept: "application/vnd.github+json",
87
+ "X-GitHub-Api-Version": "2022-11-28",
88
+ "User-Agent": "patchbay-cli",
89
+ ...init.body ? { "Content-Type": "application/json" } : {}
90
+ },
91
+ body: init.body ? JSON.stringify(init.body) : void 0
92
+ });
93
+ const text = await res.text();
94
+ const data = text ? JSON.parse(text) : {};
95
+ if (!res.ok) throw new Error(`GitHub ${init.method ?? "GET"} ${path}: HTTP ${res.status} ${data.message ?? text.slice(0, 200)}`);
96
+ return data;
97
+ };
98
+ }
99
+
100
+ // src/cli.ts
101
+ var HELP = `patchbay \u2013 describe an integration, get a tested TypeScript connector.
102
+
103
+ Usage:
104
+ patchbay build [--record] "<one-sentence integration>"
105
+ patchbay research "<one-sentence integration>"
106
+ patchbay verify [--watch] <directory>
107
+ patchbay scan <directory> [--build-top=<n>] [--json]
108
+ patchbay add <run-dir> [--target=<dir>]
109
+ patchbay push <run-dir> --repo=owner/name [--path=connectors/<name>] [--branch=<branch>] [--dry-run]
110
+ patchbay help
111
+
112
+ Commands:
113
+ build Full pipeline: plan \u2192 research \u2192 generate \u2192 verify (with repair). Default if you pass a prompt.
114
+ research Plan + API research only. Prints the spec, no code.
115
+ verify Type-check and vitest an existing connector folder (needs src/connector.ts + tests).
116
+ scan Walk a repo and report integration opportunities patchbay could build.
117
+ add Drop a recorded run's connector files into another project.
118
+ push Open a pull request on a GitHub repo with the generated files.
119
+ help Show this message.
120
+
121
+ Flags:
122
+ --record build only. Writes runs/<timestamp>/ with generated files and the event log.
123
+ --watch verify only. Re-runs the sandbox verify whenever a .ts file in <directory> changes.
124
+ --build-top scan only. After reporting, build the top-N opportunities (full pipeline each).
125
+ --json scan only. Emit the raw opportunity list as JSON instead of the formatted report.
126
+ --target add only. Where to drop the files, defaults to ./connectors/<run-name>.
127
+ --repo push only. owner/name of the target GitHub repo.
128
+ --path push only. Where to drop the files inside the repo, defaults to connectors/<run-name>.
129
+ --branch push only. Branch name to create, defaults to patchbay/<run-name>.
130
+ --dry-run push only. Print the plan without hitting the GitHub API.
131
+
132
+ Environment:
133
+ NEBIUS_API_KEY, NEBIUS_AI_PROJECT, TAVILY_API_KEY \u2013 required for live runs.
134
+ PATCHBAY_MOCK=false \u2013 enable live mode (default is replay).
135
+ PATCHBAY_RUNNER=local|nebius \u2013 default nebius (isolated sandbox).
136
+ PATCHBAY_MAX_ATTEMPTS=<n> \u2013 repair attempts, default 3.
137
+ `;
138
+ async function main() {
139
+ const argv = process.argv.slice(2);
140
+ const first = argv[0];
141
+ if (!first || first === "help" || first === "--help" || first === "-h") {
142
+ console.log(HELP);
143
+ return;
144
+ }
145
+ const known = /* @__PURE__ */ new Set(["build", "research", "verify"]);
146
+ const cmd = known.has(first) ? first : "build";
147
+ const rest = known.has(first) ? argv.slice(1) : argv;
148
+ if (first === "add") return add(argv.slice(1));
149
+ if (first === "push") return push(argv.slice(1));
150
+ if (first === "scan") return scan(argv.slice(1));
151
+ switch (cmd) {
152
+ case "build":
153
+ return build(rest);
154
+ case "research":
155
+ return research(rest);
156
+ case "verify":
157
+ return verify(rest);
158
+ }
159
+ }
160
+ async function scan(args) {
161
+ const positional = args.filter((a) => !a.startsWith("--"));
162
+ const dir = positional[0] ? resolve(positional[0]) : process.cwd();
163
+ if (!existsSync(dir)) return usageError(`No such directory: ${dir}`);
164
+ const asJson = args.includes("--json");
165
+ const buildTopArg = args.find((a) => a.startsWith("--build-top="));
166
+ const buildTop = buildTopArg ? Math.max(0, Number(buildTopArg.slice("--build-top=".length))) : 0;
167
+ const { scanRepo, formatReport } = await import("./scanner-IPBNTPNM.js");
168
+ const opportunities = scanRepo(dir);
169
+ if (asJson) {
170
+ console.log(JSON.stringify(opportunities, null, 2));
171
+ } else {
172
+ console.log(formatReport(opportunities, dir));
173
+ }
174
+ if (buildTop > 0 && opportunities.length) {
175
+ const top = opportunities.slice(0, buildTop);
176
+ console.log(`
177
+ Building top ${top.length} opportunit${top.length === 1 ? "y" : "ies"}\u2026
178
+ `);
179
+ for (const [i, op] of top.entries()) {
180
+ console.log(`
181
+ \u2500\u2500\u2500\u2500 (${i + 1}/${top.length}) ${op.file}:${op.line} \u2500\u2500\u2500\u2500`);
182
+ await build(["--record", op.prompt]);
183
+ }
184
+ }
185
+ }
186
+ async function add(args) {
187
+ const positional = args.filter((a) => !a.startsWith("--"));
188
+ const flag = args.find((a) => a.startsWith("--target="));
189
+ const runDir = positional[0] ? resolve(positional[0]) : "";
190
+ if (!runDir) return usageError("add needs a run directory (e.g. runs/<timestamp>)");
191
+ if (!existsSync(runDir)) return usageError(`No such directory: ${runDir}`);
192
+ const srcDir = join2(runDir, "src");
193
+ if (!existsSync(join2(srcDir, "connector.ts"))) {
194
+ return usageError(`${runDir} does not look like a patchbay run (no src/connector.ts)`);
195
+ }
196
+ const target = flag ? resolve(flag.slice("--target=".length)) : resolve(process.cwd(), "connectors", basename(runDir));
197
+ if (existsSync(target)) {
198
+ console.error(`Refusing to overwrite ${target}. Pass --target=<fresh-dir> or move the existing folder out of the way.`);
199
+ process.exit(1);
200
+ }
201
+ mkdirSync(target, { recursive: true });
202
+ cpSync(srcDir, join2(target, "src"), { recursive: true });
203
+ const readme = join2(runDir, "README.md");
204
+ if (existsSync(readme)) cpSync(readme, join2(target, "README.md"));
205
+ const copied = readdirSync2(join2(target, "src"));
206
+ console.log(`\u2714 Copied ${copied.length + (existsSync(readme) ? 1 : 0)} files to ${target}`);
207
+ console.log(" src/" + copied.join("\n src/"));
208
+ if (existsSync(readme)) console.log(" README.md");
209
+ console.log(`
210
+ Tests should already pass unchanged \u2014 the connector is self-contained and uses an injected fetch.`);
211
+ console.log(`Add vitest and typescript as dev deps where you'll run them, or wire this into your existing suite.`);
212
+ }
213
+ async function build(args) {
214
+ const record = args.includes("--record");
215
+ const prompt = args.filter((a) => a !== "--record").join(" ").trim();
216
+ if (!prompt) return usageError("build needs a prompt");
217
+ const config = loadConfig();
218
+ const missing = missingLiveKeys(config);
219
+ if (config.mock || missing.length) {
220
+ console.log(`Replay mode (${config.mock ? 'PATCHBAY_MOCK is not "false"' : `missing ${missing.join(", ")}`})`);
221
+ }
222
+ const events = [];
223
+ for await (const event of startRun(prompt, config)) {
224
+ events.push(event);
225
+ printEvent(event);
226
+ }
227
+ if (record) {
228
+ const dir = join2(process.cwd(), "runs", (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-"));
229
+ const result = events.find((e) => e.type === "result");
230
+ for (const file of result?.type === "result" ? result.files : []) {
231
+ mkdirSync(dirname(join2(dir, file.path)), { recursive: true });
232
+ writeFileSync(join2(dir, file.path), file.content);
233
+ }
234
+ mkdirSync(dir, { recursive: true });
235
+ writeFileSync(join2(dir, "run.json"), JSON.stringify({ prompt, origin: "live", events }, null, 2));
236
+ console.log(`
237
+ Recorded to ${dir}`);
238
+ }
239
+ }
240
+ async function research(args) {
241
+ const prompt = args.join(" ").trim();
242
+ if (!prompt) return usageError("research needs a prompt");
243
+ const config = loadConfig();
244
+ const missing = missingLiveKeys(config);
245
+ if (config.mock || missing.length) {
246
+ console.log(`Replay mode (${config.mock ? 'PATCHBAY_MOCK is not "false"' : `missing ${missing.join(", ")}`}) \u2013 returning cached research`);
247
+ }
248
+ for await (const event of startResearch(prompt, config)) {
249
+ printEvent(event);
250
+ if (event.type === "spec") {
251
+ console.log("\nSpec:");
252
+ console.log(JSON.stringify(event.spec, null, 2));
253
+ }
254
+ }
255
+ }
256
+ async function verify(args) {
257
+ const watchMode = args.includes("--watch");
258
+ const positional = args.filter((a) => !a.startsWith("--"));
259
+ const dir = positional[0] ? resolve(positional[0]) : "";
260
+ if (!dir) return usageError("verify needs a directory");
261
+ if (!collectFiles(dir).some((f) => f.path === "src/connector.ts")) {
262
+ return usageError(`No src/connector.ts under ${dir}`);
263
+ }
264
+ const config = loadConfig();
265
+ const missing = missingLiveKeys(config);
266
+ if (config.mock || missing.length) {
267
+ console.error(`verify needs live keys. Set PATCHBAY_MOCK=false and provide ${missing.join(", ") || "the missing env vars"}.`);
268
+ process.exit(1);
269
+ }
270
+ const runOnce = async () => {
271
+ const files = collectFiles(dir);
272
+ console.log(`
273
+ Verifying ${files.length} files from ${dir}`);
274
+ for await (const event of startVerify(files, config)) printEvent(event);
275
+ };
276
+ await runOnce();
277
+ if (!watchMode) return;
278
+ console.log(`
279
+ Watching ${dir} for .ts changes. Ctrl+C to exit.`);
280
+ let running = false;
281
+ let rerun = false;
282
+ let pending = null;
283
+ const trigger = () => {
284
+ if (pending) clearTimeout(pending);
285
+ pending = setTimeout(async () => {
286
+ pending = null;
287
+ if (running) {
288
+ rerun = true;
289
+ return;
290
+ }
291
+ running = true;
292
+ try {
293
+ await runOnce();
294
+ } finally {
295
+ running = false;
296
+ if (rerun) {
297
+ rerun = false;
298
+ trigger();
299
+ }
300
+ }
301
+ }, 400);
302
+ };
303
+ watch(dir, { recursive: true }, (_, filename) => {
304
+ if (filename && (filename.endsWith(".ts") || filename.endsWith(".json"))) trigger();
305
+ });
306
+ await new Promise(() => {
307
+ });
308
+ }
309
+ async function push(args) {
310
+ const positional = args.filter((a) => !a.startsWith("--"));
311
+ const runDir = positional[0] ? resolve(positional[0]) : "";
312
+ if (!runDir) return usageError("push needs a run directory");
313
+ const repo = flagValue(args, "--repo");
314
+ if (!repo) return usageError("push needs --repo=owner/name");
315
+ const target = flagValue(args, "--path") ?? `connectors/${basename(runDir)}`;
316
+ const branch = flagValue(args, "--branch");
317
+ const dryRun = args.includes("--dry-run");
318
+ const token = process.env.GH_TOKEN || process.env.GITHUB_TOKEN;
319
+ if (!token && !dryRun) {
320
+ return usageError("push needs GH_TOKEN (or GITHUB_TOKEN) in the environment, with repo scope on the target.");
321
+ }
322
+ try {
323
+ const result = await pushToGitHub({
324
+ runDir,
325
+ repo,
326
+ token: token ?? "",
327
+ targetPath: target,
328
+ ...branch ? { branch } : {},
329
+ dryRun
330
+ });
331
+ console.log(dryRun ? "\u2714 Dry run:" : "\u2714 Opened pull request:");
332
+ console.log(` URL: ${result.prUrl}`);
333
+ console.log(` branch: ${result.branch} (base: ${result.base})`);
334
+ console.log(` files: ${result.files.length} under ${target}/`);
335
+ for (const path of result.files) console.log(` ${path}`);
336
+ } catch (error) {
337
+ console.error(error instanceof Error ? error.message : String(error));
338
+ process.exit(1);
339
+ }
340
+ }
341
+ function flagValue(args, flag) {
342
+ const match = args.find((a) => a.startsWith(`${flag}=`));
343
+ return match?.slice(flag.length + 1);
344
+ }
345
+ function collectFiles(root) {
346
+ const out = [];
347
+ const walk = (dir) => {
348
+ for (const entry of readdirSync2(dir)) {
349
+ if (entry === "node_modules" || entry.startsWith(".")) continue;
350
+ const abs = join2(dir, entry);
351
+ const st = statSync2(abs);
352
+ if (st.isDirectory()) walk(abs);
353
+ else if (entry.endsWith(".ts") || entry === "README.md") {
354
+ out.push({ path: relative2(root, abs).replace(/\\/g, "/"), content: readFileSync2(abs, "utf8") });
355
+ }
356
+ }
357
+ };
358
+ walk(root);
359
+ return out;
360
+ }
361
+ function usageError(message) {
362
+ console.error(`Error: ${message}
363
+ `);
364
+ console.error(HELP);
365
+ process.exit(1);
366
+ }
367
+ function printEvent(event) {
368
+ switch (event.type) {
369
+ case "step":
370
+ console.log(`${event.status === "start" ? "\u25B6" : event.status === "done" ? "\u2714" : "\u2716"} ${event.step}${event.detail ? ` \u2014 ${event.detail}` : ""}`);
371
+ break;
372
+ case "log":
373
+ console.log(` ${event.message}`);
374
+ break;
375
+ case "tests":
376
+ console.log(` attempt ${event.attempt}: ${event.report.passed}/${event.report.total} passed, typecheck ${event.report.typecheckOk ? "ok" : "failed"}`);
377
+ for (const f of event.report.failures) console.log(` \u2716 ${f.name}`);
378
+ break;
379
+ case "usage":
380
+ for (const u of event.usage) console.log(` ${u.model}: ${u.promptTokens} in / ${u.completionTokens} out, $${u.costUsd.toFixed(4)}`);
381
+ break;
382
+ case "error":
383
+ console.error(`Error: ${event.message}`);
384
+ break;
385
+ }
386
+ }
387
+ main().catch((error) => {
388
+ console.error(error);
389
+ process.exit(1);
390
+ });
391
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/cli.ts","../src/github-push.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, statSync, watch, writeFileSync } from 'node:fs'\nimport { basename, dirname, join, relative, resolve } from 'node:path'\nimport { loadConfig, missingLiveKeys } from './config'\nimport { pushToGitHub } from './github-push'\nimport { startResearch, startRun, startVerify } from './index'\nimport type { GeneratedFile, RunEvent } from './types'\n\nconst HELP = `patchbay – describe an integration, get a tested TypeScript connector.\n\nUsage:\n patchbay build [--record] \"<one-sentence integration>\"\n patchbay research \"<one-sentence integration>\"\n patchbay verify [--watch] <directory>\n patchbay scan <directory> [--build-top=<n>] [--json]\n patchbay add <run-dir> [--target=<dir>]\n patchbay push <run-dir> --repo=owner/name [--path=connectors/<name>] [--branch=<branch>] [--dry-run]\n patchbay help\n\nCommands:\n build Full pipeline: plan → research → generate → verify (with repair). Default if you pass a prompt.\n research Plan + API research only. Prints the spec, no code.\n verify Type-check and vitest an existing connector folder (needs src/connector.ts + tests).\n scan Walk a repo and report integration opportunities patchbay could build.\n add Drop a recorded run's connector files into another project.\n push Open a pull request on a GitHub repo with the generated files.\n help Show this message.\n\nFlags:\n --record build only. Writes runs/<timestamp>/ with generated files and the event log.\n --watch verify only. Re-runs the sandbox verify whenever a .ts file in <directory> changes.\n --build-top scan only. After reporting, build the top-N opportunities (full pipeline each).\n --json scan only. Emit the raw opportunity list as JSON instead of the formatted report.\n --target add only. Where to drop the files, defaults to ./connectors/<run-name>.\n --repo push only. owner/name of the target GitHub repo.\n --path push only. Where to drop the files inside the repo, defaults to connectors/<run-name>.\n --branch push only. Branch name to create, defaults to patchbay/<run-name>.\n --dry-run push only. Print the plan without hitting the GitHub API.\n\nEnvironment:\n NEBIUS_API_KEY, NEBIUS_AI_PROJECT, TAVILY_API_KEY – required for live runs.\n PATCHBAY_MOCK=false – enable live mode (default is replay).\n PATCHBAY_RUNNER=local|nebius – default nebius (isolated sandbox).\n PATCHBAY_MAX_ATTEMPTS=<n> – repair attempts, default 3.\n`\n\nasync function main() {\n const argv = process.argv.slice(2)\n const first = argv[0]\n\n if (!first || first === 'help' || first === '--help' || first === '-h') {\n console.log(HELP)\n return\n }\n\n // Backwards-compat: bare prompt = build\n const known = new Set(['build', 'research', 'verify'])\n const cmd = known.has(first) ? first : 'build'\n const rest = known.has(first) ? argv.slice(1) : argv\n\n if (first === 'add') return add(argv.slice(1))\n if (first === 'push') return push(argv.slice(1))\n if (first === 'scan') return scan(argv.slice(1))\n\n switch (cmd) {\n case 'build':\n return build(rest)\n case 'research':\n return research(rest)\n case 'verify':\n return verify(rest)\n }\n}\n\nasync function scan(args: string[]) {\n const positional = args.filter((a) => !a.startsWith('--'))\n const dir = positional[0] ? resolve(positional[0]) : process.cwd()\n if (!existsSync(dir)) return usageError(`No such directory: ${dir}`)\n const asJson = args.includes('--json')\n const buildTopArg = args.find((a) => a.startsWith('--build-top='))\n const buildTop = buildTopArg ? Math.max(0, Number(buildTopArg.slice('--build-top='.length))) : 0\n\n const { scanRepo, formatReport } = await import('./scanner')\n const opportunities = scanRepo(dir)\n if (asJson) {\n console.log(JSON.stringify(opportunities, null, 2))\n } else {\n console.log(formatReport(opportunities, dir))\n }\n\n if (buildTop > 0 && opportunities.length) {\n const top = opportunities.slice(0, buildTop)\n console.log(`\\nBuilding top ${top.length} opportunit${top.length === 1 ? 'y' : 'ies'}…\\n`)\n for (const [i, op] of top.entries()) {\n console.log(`\\n──── (${i + 1}/${top.length}) ${op.file}:${op.line} ────`)\n await build(['--record', op.prompt])\n }\n }\n}\n\n/**\n * Copy the files from a recorded run (`runs/<timestamp>/`) into a target\n * project. Default target is ./connectors/<run-basename>, so repeated adds\n * don't overwrite each other.\n */\nasync function add(args: string[]) {\n const positional = args.filter((a) => !a.startsWith('--'))\n const flag = args.find((a) => a.startsWith('--target='))\n const runDir = positional[0] ? resolve(positional[0]) : ''\n if (!runDir) return usageError('add needs a run directory (e.g. runs/<timestamp>)')\n if (!existsSync(runDir)) return usageError(`No such directory: ${runDir}`)\n const srcDir = join(runDir, 'src')\n if (!existsSync(join(srcDir, 'connector.ts'))) {\n return usageError(`${runDir} does not look like a patchbay run (no src/connector.ts)`)\n }\n const target = flag ? resolve(flag.slice('--target='.length)) : resolve(process.cwd(), 'connectors', basename(runDir))\n if (existsSync(target)) {\n console.error(`Refusing to overwrite ${target}. Pass --target=<fresh-dir> or move the existing folder out of the way.`)\n process.exit(1)\n }\n mkdirSync(target, { recursive: true })\n // src/ is self-contained (connector.ts + connector.test.ts + fixtures.ts).\n cpSync(srcDir, join(target, 'src'), { recursive: true })\n const readme = join(runDir, 'README.md')\n if (existsSync(readme)) cpSync(readme, join(target, 'README.md'))\n const copied = readdirSync(join(target, 'src'))\n console.log(`✔ Copied ${copied.length + (existsSync(readme) ? 1 : 0)} files to ${target}`)\n console.log(' src/' + copied.join('\\n src/'))\n if (existsSync(readme)) console.log(' README.md')\n console.log(`\\nTests should already pass unchanged — the connector is self-contained and uses an injected fetch.`)\n console.log(`Add vitest and typescript as dev deps where you'll run them, or wire this into your existing suite.`)\n}\n\nasync function build(args: string[]) {\n const record = args.includes('--record')\n const prompt = args.filter((a) => a !== '--record').join(' ').trim()\n if (!prompt) return usageError('build needs a prompt')\n\n const config = loadConfig()\n const missing = missingLiveKeys(config)\n if (config.mock || missing.length) {\n console.log(`Replay mode (${config.mock ? 'PATCHBAY_MOCK is not \"false\"' : `missing ${missing.join(', ')}`})`)\n }\n\n const events: RunEvent[] = []\n for await (const event of startRun(prompt, config)) {\n events.push(event)\n printEvent(event)\n }\n\n if (record) {\n const dir = join(process.cwd(), 'runs', new Date().toISOString().replace(/[:.]/g, '-'))\n const result = events.find((e) => e.type === 'result')\n for (const file of result?.type === 'result' ? result.files : []) {\n mkdirSync(dirname(join(dir, file.path)), { recursive: true })\n writeFileSync(join(dir, file.path), file.content)\n }\n mkdirSync(dir, { recursive: true })\n writeFileSync(join(dir, 'run.json'), JSON.stringify({ prompt, origin: 'live', events }, null, 2))\n console.log(`\\nRecorded to ${dir}`)\n }\n}\n\nasync function research(args: string[]) {\n const prompt = args.join(' ').trim()\n if (!prompt) return usageError('research needs a prompt')\n const config = loadConfig()\n const missing = missingLiveKeys(config)\n if (config.mock || missing.length) {\n console.log(`Replay mode (${config.mock ? 'PATCHBAY_MOCK is not \"false\"' : `missing ${missing.join(', ')}`}) – returning cached research`)\n }\n for await (const event of startResearch(prompt, config)) {\n printEvent(event)\n if (event.type === 'spec') {\n console.log('\\nSpec:')\n console.log(JSON.stringify(event.spec, null, 2))\n }\n }\n}\n\nasync function verify(args: string[]) {\n const watchMode = args.includes('--watch')\n const positional = args.filter((a) => !a.startsWith('--'))\n const dir = positional[0] ? resolve(positional[0]) : ''\n if (!dir) return usageError('verify needs a directory')\n if (!collectFiles(dir).some((f) => f.path === 'src/connector.ts')) {\n return usageError(`No src/connector.ts under ${dir}`)\n }\n const config = loadConfig()\n const missing = missingLiveKeys(config)\n if (config.mock || missing.length) {\n console.error(`verify needs live keys. Set PATCHBAY_MOCK=false and provide ${missing.join(', ') || 'the missing env vars'}.`)\n process.exit(1)\n }\n\n const runOnce = async () => {\n const files = collectFiles(dir)\n console.log(`\\nVerifying ${files.length} files from ${dir}`)\n for await (const event of startVerify(files, config)) printEvent(event)\n }\n\n await runOnce()\n if (!watchMode) return\n\n console.log(`\\nWatching ${dir} for .ts changes. Ctrl+C to exit.`)\n let running = false\n let rerun = false\n // Native fs.watch is good enough: debounced to avoid thrashing when an editor\n // saves multiple files in quick succession.\n let pending: NodeJS.Timeout | null = null\n const trigger = () => {\n if (pending) clearTimeout(pending)\n pending = setTimeout(async () => {\n pending = null\n if (running) { rerun = true; return }\n running = true\n try { await runOnce() } finally {\n running = false\n if (rerun) { rerun = false; trigger() }\n }\n }, 400)\n }\n watch(dir, { recursive: true }, (_, filename) => {\n if (filename && (filename.endsWith('.ts') || filename.endsWith('.json'))) trigger()\n })\n await new Promise(() => {}) // keep the process alive\n}\n\nasync function push(args: string[]) {\n const positional = args.filter((a) => !a.startsWith('--'))\n const runDir = positional[0] ? resolve(positional[0]) : ''\n if (!runDir) return usageError('push needs a run directory')\n const repo = flagValue(args, '--repo')\n if (!repo) return usageError('push needs --repo=owner/name')\n const target = flagValue(args, '--path') ?? `connectors/${basename(runDir)}`\n const branch = flagValue(args, '--branch')\n const dryRun = args.includes('--dry-run')\n const token = process.env.GH_TOKEN || process.env.GITHUB_TOKEN\n if (!token && !dryRun) {\n return usageError('push needs GH_TOKEN (or GITHUB_TOKEN) in the environment, with repo scope on the target.')\n }\n try {\n const result = await pushToGitHub({\n runDir, repo, token: token ?? '', targetPath: target,\n ...(branch ? { branch } : {}),\n dryRun,\n })\n console.log(dryRun ? '✔ Dry run:' : '✔ Opened pull request:')\n console.log(` URL: ${result.prUrl}`)\n console.log(` branch: ${result.branch} (base: ${result.base})`)\n console.log(` files: ${result.files.length} under ${target}/`)\n for (const path of result.files) console.log(` ${path}`)\n } catch (error) {\n console.error(error instanceof Error ? error.message : String(error))\n process.exit(1)\n }\n}\n\nfunction flagValue(args: string[], flag: string): string | undefined {\n const match = args.find((a) => a.startsWith(`${flag}=`))\n return match?.slice(flag.length + 1)\n}\n\nfunction collectFiles(root: string): GeneratedFile[] {\n const out: GeneratedFile[] = []\n const walk = (dir: string) => {\n for (const entry of readdirSync(dir)) {\n if (entry === 'node_modules' || entry.startsWith('.')) continue\n const abs = join(dir, entry)\n const st = statSync(abs)\n if (st.isDirectory()) walk(abs)\n else if (entry.endsWith('.ts') || entry === 'README.md') {\n out.push({ path: relative(root, abs).replace(/\\\\/g, '/'), content: readFileSync(abs, 'utf8') })\n }\n }\n }\n walk(root)\n return out\n}\n\nfunction usageError(message: string): void {\n console.error(`Error: ${message}\\n`)\n console.error(HELP)\n process.exit(1)\n}\n\nfunction printEvent(event: RunEvent) {\n switch (event.type) {\n case 'step':\n console.log(`${event.status === 'start' ? '▶' : event.status === 'done' ? '✔' : '✖'} ${event.step}${event.detail ? ` — ${event.detail}` : ''}`)\n break\n case 'log':\n console.log(` ${event.message}`)\n break\n case 'tests':\n console.log(` attempt ${event.attempt}: ${event.report.passed}/${event.report.total} passed, typecheck ${event.report.typecheckOk ? 'ok' : 'failed'}`)\n for (const f of event.report.failures) console.log(` ✖ ${f.name}`)\n break\n case 'usage':\n for (const u of event.usage) console.log(` ${u.model}: ${u.promptTokens} in / ${u.completionTokens} out, $${u.costUsd.toFixed(4)}`)\n break\n case 'error':\n console.error(`Error: ${event.message}`)\n break\n }\n}\n\nmain().catch((error) => {\n console.error(error)\n process.exit(1)\n})\n","import { readdirSync, readFileSync, statSync } from 'node:fs'\nimport { join, relative } from 'node:path'\n\nexport interface PushOptions {\n runDir: string\n repo: string // \"owner/name\"\n token: string\n /** Where inside the target repo the connector files land. */\n targetPath: string // e.g. \"connectors/typeform-pipedrive\"\n /** Branch to create. Defaults to patchbay/<basename(runDir)>. */\n branch?: string\n /** Base branch to branch from. GitHub defaults it to the repo's default. */\n base?: string\n /** PR title + body overrides. */\n title?: string\n body?: string\n /** Set true to log what would happen without hitting the API. */\n dryRun?: boolean\n}\n\nexport interface PushResult {\n prUrl: string\n branch: string\n base: string\n files: string[]\n}\n\nconst API = 'https://api.github.com'\n\n/**\n * Takes a recorded patchbay run (runs/<timestamp>/ with src/* + README.md) and lands it in a\n * target GitHub repo as a pull request: new branch, commits every file under `targetPath`,\n * opens a PR against the repo's default branch.\n *\n * Uses the GitHub REST API directly (fetch + token). The token needs `repo` scope on the\n * target. Dry-run prints the plan without calling the API.\n */\nexport async function pushToGitHub(opts: PushOptions): Promise<PushResult> {\n const files = collectRunFiles(opts.runDir)\n if (files.length === 0) throw new Error(`${opts.runDir} has no files to push (expected src/* and README.md).`)\n\n const [owner, name] = opts.repo.split('/')\n if (!owner || !name) throw new Error(`Expected --repo=owner/name, got \"${opts.repo}\"`)\n\n const branch = opts.branch ?? `patchbay/${basenameNoSlash(opts.runDir)}`\n const title = opts.title ?? `patchbay: ${opts.targetPath}`\n const body =\n opts.body ??\n `Generated by [patchbay](https://github.com/GodSmasher/patchbay) from \\`${basenameNoSlash(opts.runDir)}\\`.\\n\\n` +\n `Includes ${files.length} files under \\`${opts.targetPath}/\\`. Tests pass against the documented example in a hermetic sandbox.`\n\n if (opts.dryRun) {\n return { prUrl: `(dry-run) would open PR on ${opts.repo}`, branch, base: opts.base ?? '(default)', files: files.map((f) => f.path) }\n }\n\n const api = createApi(opts.token)\n const repo = (await api(`/repos/${owner}/${name}`)) as { default_branch: string }\n const base = opts.base ?? repo.default_branch\n const baseRef = (await api(`/repos/${owner}/${name}/git/ref/heads/${base}`)) as { object: { sha: string } }\n const baseSha = baseRef.object.sha\n\n // Create the branch (409 if it already exists, we tolerate that).\n try {\n await api(`/repos/${owner}/${name}/git/refs`, {\n method: 'POST',\n body: { ref: `refs/heads/${branch}`, sha: baseSha },\n })\n } catch (error) {\n if (!/already exists/i.test(String(error))) throw error\n }\n\n // One commit per file keeps the diff readable; could be batched into a tree later if it matters.\n for (const file of files) {\n const path = `${opts.targetPath}/${file.path}`.replace(/\\\\/g, '/')\n const existing = (await api(`/repos/${owner}/${name}/contents/${encodeURIComponent(path)}?ref=${branch}`).catch(() => null)) as { sha?: string } | null\n await api(`/repos/${owner}/${name}/contents/${encodeURIComponent(path)}`, {\n method: 'PUT',\n body: {\n message: `patchbay: ${path}`,\n content: Buffer.from(file.content, 'utf8').toString('base64'),\n branch,\n ...(existing?.sha ? { sha: existing.sha } : {}),\n },\n })\n }\n\n const pr = (await api(`/repos/${owner}/${name}/pulls`, {\n method: 'POST',\n body: { title, head: branch, base, body, draft: false },\n })) as { html_url: string }\n\n return { prUrl: pr.html_url, branch, base, files: files.map((f) => f.path) }\n}\n\ninterface RunFile {\n path: string\n content: string\n}\n\nfunction collectRunFiles(root: string): RunFile[] {\n const out: RunFile[] = []\n const walk = (dir: string) => {\n for (const entry of readdirSync(dir)) {\n if (entry === 'run.json' || entry.startsWith('.')) continue\n const abs = join(dir, entry)\n const st = statSync(abs)\n if (st.isDirectory()) walk(abs)\n else out.push({ path: relative(root, abs).replace(/\\\\/g, '/'), content: readFileSync(abs, 'utf8') })\n }\n }\n walk(root)\n return out\n}\n\nfunction basenameNoSlash(path: string): string {\n return path.replace(/[\\\\/]+$/, '').split(/[\\\\/]/).pop() ?? 'run'\n}\n\nfunction createApi(token: string) {\n return async <T = unknown>(path: string, init: { method?: string; body?: unknown } = {}): Promise<T> => {\n const res = await fetch(`${API}${path}`, {\n method: init.method ?? 'GET',\n headers: {\n Authorization: `Bearer ${token}`,\n Accept: 'application/vnd.github+json',\n 'X-GitHub-Api-Version': '2022-11-28',\n 'User-Agent': 'patchbay-cli',\n ...(init.body ? { 'Content-Type': 'application/json' } : {}),\n },\n body: init.body ? JSON.stringify(init.body) : undefined,\n })\n const text = await res.text()\n const data = text ? JSON.parse(text) : {}\n if (!res.ok) throw new Error(`GitHub ${init.method ?? 'GET'} ${path}: HTTP ${res.status} ${(data as { message?: string }).message ?? text.slice(0, 200)}`)\n return data as T\n }\n}\n"],"mappings":";;;;;;;;;;AACA,SAAS,QAAQ,YAAY,WAAW,eAAAA,cAAa,gBAAAC,eAAc,YAAAC,WAAU,OAAO,qBAAqB;AACzG,SAAS,UAAU,SAAS,QAAAC,OAAM,YAAAC,WAAU,eAAe;;;ACF3D,SAAS,aAAa,cAAc,gBAAgB;AACpD,SAAS,MAAM,gBAAgB;AA0B/B,IAAM,MAAM;AAUZ,eAAsB,aAAa,MAAwC;AACzE,QAAM,QAAQ,gBAAgB,KAAK,MAAM;AACzC,MAAI,MAAM,WAAW,EAAG,OAAM,IAAI,MAAM,GAAG,KAAK,MAAM,uDAAuD;AAE7G,QAAM,CAAC,OAAO,IAAI,IAAI,KAAK,KAAK,MAAM,GAAG;AACzC,MAAI,CAAC,SAAS,CAAC,KAAM,OAAM,IAAI,MAAM,oCAAoC,KAAK,IAAI,GAAG;AAErF,QAAM,SAAS,KAAK,UAAU,YAAY,gBAAgB,KAAK,MAAM,CAAC;AACtE,QAAM,QAAQ,KAAK,SAAS,aAAa,KAAK,UAAU;AACxD,QAAM,OACJ,KAAK,QACL,0EAA0E,gBAAgB,KAAK,MAAM,CAAC;AAAA;AAAA,WACxF,MAAM,MAAM,k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AClB,UAAQ,KAAK,CAAC;AAChB;AAEA,SAAS,WAAW,OAAiB;AACnC,UAAQ,MAAM,MAAM;AAAA,IAClB,KAAK;AACH,cAAQ,IAAI,GAAG,MAAM,WAAW,UAAU,WAAM,MAAM,WAAW,SAAS,WAAM,QAAG,IAAI,MAAM,IAAI,GAAG,MAAM,SAAS,WAAM,MAAM,MAAM,KAAK,EAAE,EAAE;AAC9I;AAAA,IACF,KAAK;AACH,cAAQ,IAAI,OAAO,MAAM,OAAO,EAAE;AAClC;AAAA,IACF,KAAK;AACH,cAAQ,IAAI,eAAe,MAAM,OAAO,KAAK,MAAM,OAAO,MAAM,IAAI,MAAM,OAAO,KAAK,sBAAsB,MAAM,OAAO,cAAc,OAAO,QAAQ,EAAE;AACxJ,iBAAW,KAAK,MAAM,OAAO,SAAU,SAAQ,IAAI,gBAAW,EAAE,IAAI,EAAE;AACtE;AAAA,IACF,KAAK;AACH,iBAAW,KAAK,MAAM,MAAO,SAAQ,IAAI,OAAO,EAAE,KAAK,KAAK,EAAE,YAAY,SAAS,EAAE,gBAAgB,UAAU,EAAE,QAAQ,QAAQ,CAAC,CAAC,EAAE;AACrI;AAAA,IACF,KAAK;AACH,cAAQ,MAAM,UAAU,MAAM,OAAO,EAAE;AACvC;AAAA,EACJ;AACF;AAEA,KAAK,EAAE,MAAM,CAAC,UAAU;AACtB,UAAQ,MAAM,KAAK;AACnB,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["readdirSync","readFileSync","statSync","join","relative","join","readdirSync","statSync","relative","readFileSync"]}
@@ -0,0 +1,41 @@
1
+ # Typeform → Pipedrive connector
2
+
3
+ Turns a Typeform `form_response` webhook into a Pipedrive organization, person and deal.
4
+
5
+ ## Configuration
6
+
7
+ | Env var | Used as | Notes |
8
+ | --- | --- | --- |
9
+ | `PIPEDRIVE_API_TOKEN` | `pipedriveApiToken` | Personal API token, sent as the `x-api-token` header |
10
+
11
+ `fieldRefs` maps your Typeform field refs to the lead fields. `name` and `email` are required; `company` and `phone` are optional.
12
+
13
+ ## Usage
14
+
15
+ ```ts
16
+ import { handle } from './src/connector'
17
+
18
+ export async function POST(request: Request) {
19
+ const payload = await request.json()
20
+ const result = await handle(payload, {
21
+ pipedriveApiToken: process.env.PIPEDRIVE_API_TOKEN!,
22
+ fieldRefs: { name: 'lead_name', email: 'lead_email', company: 'lead_company', phone: 'lead_phone' },
23
+ dealTitlePrefix: 'Website lead',
24
+ })
25
+ return Response.json(result)
26
+ }
27
+ ```
28
+
29
+ ## Behaviour
30
+
31
+ 1. Reads the answers by field ref, rejects the event when name or email is missing.
32
+ 2. Creates an organization when a company was answered (`POST /v1/organizations`).
33
+ 3. Creates the person with email and phone, linked to the organization (`POST /v1/persons`).
34
+ 4. Creates a deal for the person (`POST /v1/deals`).
35
+
36
+ Any non-2xx or `success: false` response throws with the status code and endpoint, so the webhook caller can retry.
37
+
38
+ ## Assumptions
39
+
40
+ - Typeform webhook signature verification happens before `handle` is called.
41
+ - Every submission is a new lead; the connector does not search for existing persons.
@@ -0,0 +1,111 @@
1
+ import { describe, it, expect, vi } from 'vitest'
2
+ import { handle, type ConnectorConfig, type TypeformWebhook } from './connector'
3
+ import { SOURCE_EXAMPLE, contractFetch } from './fixtures'
4
+
5
+ function fakeFetch(responses: Record<string, { status?: number; body: unknown }>) {
6
+ return vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
7
+ const url = String(input)
8
+ const path = Object.keys(responses).find((p) => url.endsWith(p))
9
+ const response = path ? responses[path] : undefined
10
+ if (!response) throw new Error(`unexpected request to ${url} ${init?.method}`)
11
+ return new Response(JSON.stringify(response.body), { status: response.status ?? 201 })
12
+ })
13
+ }
14
+
15
+ const ok = (id: number) => ({ body: { success: true, data: { id } } })
16
+
17
+ function payload(overrides: Partial<Record<'name' | 'email' | 'company' | 'phone', string | null>> = {}): TypeformWebhook {
18
+ const values = { name: 'Ada Lovelace', email: 'ada@example.com', company: 'Analytical Engines Ltd', phone: '+44 20 7946 0000', ...overrides }
19
+ const answers = [
20
+ values.name !== null && { type: 'text', field: { id: 'f1', ref: 'lead_name', type: 'short_text' }, text: values.name },
21
+ values.email !== null && { type: 'email', field: { id: 'f2', ref: 'lead_email', type: 'email' }, email: values.email },
22
+ values.company !== null && { type: 'text', field: { id: 'f3', ref: 'lead_company', type: 'short_text' }, text: values.company },
23
+ values.phone !== null && { type: 'phone_number', field: { id: 'f4', ref: 'lead_phone', type: 'phone_number' }, phone_number: values.phone },
24
+ ].filter(Boolean) as TypeformWebhook['form_response']['answers']
25
+ return {
26
+ event_id: 'evt_1',
27
+ event_type: 'form_response',
28
+ form_response: { form_id: 'frm_1', token: 'tok_1', submitted_at: '2026-10-01T09:00:00Z', answers },
29
+ }
30
+ }
31
+
32
+ function config(fetch: typeof globalThis.fetch): ConnectorConfig {
33
+ return {
34
+ pipedriveApiToken: 'test-token',
35
+ fieldRefs: { name: 'lead_name', email: 'lead_email', company: 'lead_company', phone: 'lead_phone' },
36
+ dealTitlePrefix: 'Website lead',
37
+ fetch,
38
+ }
39
+ }
40
+
41
+ describe('handle', () => {
42
+ it('creates organization, person and deal with the mapped fields', async () => {
43
+ const fetch = fakeFetch({ '/organizations': ok(11), '/persons': ok(22), '/deals': ok(33) })
44
+ const result = await handle(payload(), config(fetch))
45
+
46
+ expect(result).toEqual({ personId: 22, organizationId: 11, dealId: 33 })
47
+ const bodies = fetch.mock.calls.map(([url, init]) => [String(url), JSON.parse(String(init?.body))])
48
+ expect(bodies).toEqual([
49
+ ['https://api.pipedrive.com/v1/organizations', { name: 'Analytical Engines Ltd' }],
50
+ ['https://api.pipedrive.com/v1/persons', {
51
+ name: 'Ada Lovelace',
52
+ email: [{ value: 'ada@example.com', primary: true, label: 'work' }],
53
+ phone: [{ value: '+44 20 7946 0000', primary: true, label: 'work' }],
54
+ org_id: 11,
55
+ }],
56
+ ['https://api.pipedrive.com/v1/deals', { title: 'Website lead: Analytical Engines Ltd', person_id: 22, org_id: 11 }],
57
+ ])
58
+ })
59
+
60
+ it('authenticates every call with the x-api-token header', async () => {
61
+ const fetch = fakeFetch({ '/organizations': ok(1), '/persons': ok(2), '/deals': ok(3) })
62
+ await handle(payload(), config(fetch))
63
+ for (const [, init] of fetch.mock.calls) {
64
+ expect(new Headers(init?.headers).get('x-api-token')).toBe('test-token')
65
+ expect(init?.method).toBe('POST')
66
+ }
67
+ })
68
+
69
+ it('skips the organization when no company was answered', async () => {
70
+ const fetch = fakeFetch({ '/persons': ok(2), '/deals': ok(3) })
71
+ const result = await handle(payload({ company: null }), config(fetch))
72
+ expect(result.organizationId).toBeNull()
73
+ expect(fetch).toHaveBeenCalledTimes(2)
74
+ const deal = JSON.parse(String(fetch.mock.calls[1]?.[1]?.body))
75
+ expect(deal).toEqual({ title: 'Website lead: Ada Lovelace', person_id: 2 })
76
+ })
77
+
78
+ it('rejects a response without an email answer', async () => {
79
+ const fetch = fakeFetch({})
80
+ await expect(handle(payload({ email: null }), config(fetch))).rejects.toThrow(/lead_email/)
81
+ expect(fetch).not.toHaveBeenCalled()
82
+ })
83
+
84
+ it('surfaces Pipedrive errors with status and endpoint', async () => {
85
+ const fetch = fakeFetch({
86
+ '/organizations': ok(1),
87
+ '/persons': { status: 401, body: { success: false, error: 'unauthorized access' } },
88
+ })
89
+ await expect(handle(payload(), config(fetch))).rejects.toThrow('Pipedrive POST /persons failed with 401: unauthorized access')
90
+ })
91
+
92
+ it('ignores events that are not form responses', async () => {
93
+ const fetch = fakeFetch({})
94
+ const event = { ...payload(), event_type: 'form_deleted' } as unknown as TypeformWebhook
95
+ await expect(handle(event, config(fetch))).rejects.toThrow(/Unsupported Typeform event/)
96
+ })
97
+ })
98
+
99
+ describe('contract', () => {
100
+ it('handles the documented Typeform payload against the documented Pipedrive responses', async () => {
101
+ const { fetch, calls } = contractFetch()
102
+ const result = await handle(SOURCE_EXAMPLE as unknown as TypeformWebhook, {
103
+ pipedriveApiToken: 'contract-token',
104
+ fieldRefs: { name: 'lead_name', email: 'lead_email' },
105
+ fetch,
106
+ })
107
+ expect(result.personId).toBeGreaterThan(0)
108
+ expect(result.dealId).toBeGreaterThan(0)
109
+ expect(calls.map((c) => c.url)).toEqual(['https://api.pipedrive.com/v1/persons', 'https://api.pipedrive.com/v1/deals'])
110
+ })
111
+ })