@patchbay-nebius/agent 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +66 -2
- package/dist/chunk-JVXVCXNZ.js +2356 -0
- package/dist/chunk-JVXVCXNZ.js.map +1 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +360 -0
- package/dist/cli.js.map +1 -0
- package/dist/fixtures/typeform-pipedrive/attempt-1/README.md +41 -0
- package/dist/fixtures/typeform-pipedrive/attempt-1/src/connector.test.ts +111 -0
- package/dist/fixtures/typeform-pipedrive/attempt-1/src/connector.ts +93 -0
- package/dist/fixtures/typeform-pipedrive/attempt-1/src/fixtures.ts +173 -0
- package/dist/fixtures/typeform-pipedrive/final/README.md +41 -0
- package/dist/fixtures/typeform-pipedrive/final/src/connector.test.ts +111 -0
- package/dist/fixtures/typeform-pipedrive/final/src/connector.ts +94 -0
- package/dist/fixtures/typeform-pipedrive/final/src/fixtures.ts +173 -0
- package/dist/fixtures/typeform-pipedrive/meta.json +192 -0
- package/dist/fixtures/typeform-pipedrive/run.json +444 -0
- package/dist/index.d.ts +302 -0
- package/dist/index.js +39 -0
- package/dist/index.js.map +1 -0
- package/package.json +61 -4
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
// Written by patchbay from the API documentation. Regenerated on every attempt, do not edit.
|
|
2
|
+
// Source: https://www.typeform.com/developers/webhooks/example-payload/
|
|
3
|
+
// Source: https://developers.pipedrive.com/docs/api/v1/Organizations
|
|
4
|
+
// Source: https://developers.pipedrive.com/docs/api/v1/Persons
|
|
5
|
+
// Source: https://developers.pipedrive.com/docs/api/v1/Deals
|
|
6
|
+
|
|
7
|
+
/** Example payload of the source event, as documented. */
|
|
8
|
+
export const SOURCE_EXAMPLE = {
|
|
9
|
+
"event_id": "01H...",
|
|
10
|
+
"event_type": "form_response",
|
|
11
|
+
"form_response": {
|
|
12
|
+
"form_id": "lT4Z3j",
|
|
13
|
+
"token": "a3a12ec67a1365927098a606107fac15",
|
|
14
|
+
"submitted_at": "2026-10-01T09:00:00Z",
|
|
15
|
+
"answers": [
|
|
16
|
+
{
|
|
17
|
+
"type": "text",
|
|
18
|
+
"field": {
|
|
19
|
+
"id": "f1",
|
|
20
|
+
"ref": "lead_name",
|
|
21
|
+
"type": "short_text"
|
|
22
|
+
},
|
|
23
|
+
"text": "Ada Lovelace"
|
|
24
|
+
},
|
|
25
|
+
{
|
|
26
|
+
"type": "email",
|
|
27
|
+
"field": {
|
|
28
|
+
"id": "f2",
|
|
29
|
+
"ref": "lead_email",
|
|
30
|
+
"type": "email"
|
|
31
|
+
},
|
|
32
|
+
"email": "ada@example.com"
|
|
33
|
+
}
|
|
34
|
+
]
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface DocumentedEndpoint {
|
|
39
|
+
method: string
|
|
40
|
+
/** As documented; may contain placeholders such as {id}, :id, <id> or a region host like usX. */
|
|
41
|
+
url: string
|
|
42
|
+
response: unknown
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Target endpoints the connector may call, in the documented order, with their documented responses. */
|
|
46
|
+
export const TARGET_ENDPOINTS: DocumentedEndpoint[] = [
|
|
47
|
+
{
|
|
48
|
+
"method": "POST",
|
|
49
|
+
"url": "https://api.pipedrive.com/v1/organizations",
|
|
50
|
+
"response": {
|
|
51
|
+
"success": true,
|
|
52
|
+
"data": {
|
|
53
|
+
"id": 11
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
},
|
|
57
|
+
{
|
|
58
|
+
"method": "POST",
|
|
59
|
+
"url": "https://api.pipedrive.com/v1/persons",
|
|
60
|
+
"response": {
|
|
61
|
+
"success": true,
|
|
62
|
+
"data": {
|
|
63
|
+
"id": 22
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
},
|
|
67
|
+
{
|
|
68
|
+
"method": "POST",
|
|
69
|
+
"url": "https://api.pipedrive.com/v1/deals",
|
|
70
|
+
"response": {
|
|
71
|
+
"success": true,
|
|
72
|
+
"data": {
|
|
73
|
+
"id": 33
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
]
|
|
78
|
+
|
|
79
|
+
export interface RecordedCall {
|
|
80
|
+
method: string
|
|
81
|
+
url: string
|
|
82
|
+
/** The request body exactly as sent (usually a JSON string). */
|
|
83
|
+
body: string | undefined
|
|
84
|
+
/** The body parsed as JSON, or undefined when it is not JSON. */
|
|
85
|
+
json: unknown
|
|
86
|
+
headers: Headers
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** The documented endpoint a request matches, placeholders and region subdomains included. */
|
|
90
|
+
export function findEndpoint(method: string, url: string): DocumentedEndpoint | undefined {
|
|
91
|
+
return TARGET_ENDPOINTS.find((endpoint) => endpoint.method === method.toUpperCase() && urlMatches(endpoint.url, url))
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* A fake fetch that answers every documented endpoint with its documented response and
|
|
96
|
+
* rejects anything else. Use it in the contract test:
|
|
97
|
+
*
|
|
98
|
+
* const { fetch, calls } = contractFetch()
|
|
99
|
+
* await handle(SOURCE_EXAMPLE as MyInput, { ...config, fetch })
|
|
100
|
+
* expect(calls.length).toBeGreaterThan(0)
|
|
101
|
+
*/
|
|
102
|
+
export function contractFetch(): { fetch: typeof fetch; calls: RecordedCall[] } {
|
|
103
|
+
return fakeFetch((request) => {
|
|
104
|
+
const endpoint = findEndpoint(request.method, request.url)
|
|
105
|
+
if (!endpoint) throw new Error(`contract: ${request.method} ${request.url} is not a documented endpoint`)
|
|
106
|
+
return jsonResponse(endpoint.response)
|
|
107
|
+
})
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* A correctly typed fake fetch for every other test. The handler receives the recorded
|
|
112
|
+
* request: { method, url, body (string as sent), json (parsed body), headers (Headers) }.
|
|
113
|
+
*
|
|
114
|
+
* const { fetch, calls } = fakeFetch((req) => req.url.endsWith('/deals') ? jsonResponse({ id: 1 }, 201) : jsonResponse({}, 404))
|
|
115
|
+
*/
|
|
116
|
+
export function fakeFetch(
|
|
117
|
+
handler: (request: RecordedCall) => Response | Promise<Response>,
|
|
118
|
+
): { fetch: typeof fetch; calls: RecordedCall[] } {
|
|
119
|
+
const calls: RecordedCall[] = []
|
|
120
|
+
const fake = async (input: string | URL | Request, init: RequestInit = {}): Promise<Response> => {
|
|
121
|
+
const url = input instanceof Request ? input.url : String(input)
|
|
122
|
+
const method = (init.method ?? (input instanceof Request ? input.method : 'GET')).toUpperCase()
|
|
123
|
+
const body = typeof init.body === 'string' ? init.body : init.body == null ? undefined : String(init.body)
|
|
124
|
+
const call: RecordedCall = { method, url, body, json: parseJson(body), headers: new Headers(init.headers) }
|
|
125
|
+
calls.push(call)
|
|
126
|
+
return handler(call)
|
|
127
|
+
}
|
|
128
|
+
return { fetch: fake as typeof fetch, calls }
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const STATUS_TEXT: Record<number, string> = {
|
|
132
|
+
200: 'OK', 201: 'Created', 202: 'Accepted', 204: 'No Content',
|
|
133
|
+
400: 'Bad Request', 401: 'Unauthorized', 403: 'Forbidden', 404: 'Not Found', 409: 'Conflict',
|
|
134
|
+
422: 'Unprocessable Entity', 429: 'Too Many Requests',
|
|
135
|
+
500: 'Internal Server Error', 502: 'Bad Gateway', 503: 'Service Unavailable',
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** A JSON Response with the standard status text, e.g. jsonResponse({ error: 'nope' }, 401) -> "401 Unauthorized". */
|
|
139
|
+
export function jsonResponse(body: unknown, status = 200): Response {
|
|
140
|
+
const init = { status, statusText: STATUS_TEXT[status] ?? '', headers: { 'Content-Type': 'application/json' } }
|
|
141
|
+
return new Response(status === 204 ? null : JSON.stringify(body), init)
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function parseJson(raw: string | undefined): unknown {
|
|
145
|
+
if (raw === undefined) return undefined
|
|
146
|
+
try {
|
|
147
|
+
return JSON.parse(raw)
|
|
148
|
+
} catch {
|
|
149
|
+
return undefined
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function urlMatches(template: string, actual: string): boolean {
|
|
154
|
+
const t = splitUrl(template)
|
|
155
|
+
const a = splitUrl(actual)
|
|
156
|
+
if (!t || !a) return false
|
|
157
|
+
const tHost = t.host.split('.')
|
|
158
|
+
const aHost = a.host.split('.')
|
|
159
|
+
if (tHost.slice(-2).join('.') !== aHost.slice(-2).join('.')) return false
|
|
160
|
+
const tPath = t.path.replace(/\/+$/, '').split('/')
|
|
161
|
+
const aPath = a.path.replace(/\/+$/, '').split('/')
|
|
162
|
+
if (tPath.length !== aPath.length) return false
|
|
163
|
+
return tPath.every((segment, i) => isPlaceholder(segment) || segment === aPath[i])
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function splitUrl(url: string): { host: string; path: string } | null {
|
|
167
|
+
const match = url.match(/^https?:\/\/([^/?#]+)([^?#]*)/i)
|
|
168
|
+
return match ? { host: (match[1] ?? '').toLowerCase(), path: match[2] || '/' } : null
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function isPlaceholder(segment: string): boolean {
|
|
172
|
+
return /^\{[^}]+\}$|^:[A-Za-z_]\w*$|^<[^>]+>$/.test(segment)
|
|
173
|
+
}
|
|
@@ -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
|
+
})
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
export interface ConnectorConfig {
|
|
2
|
+
/** Pipedrive personal API token (env: PIPEDRIVE_API_TOKEN). */
|
|
3
|
+
pipedriveApiToken: string
|
|
4
|
+
/** Defaults to https://api.pipedrive.com/v1 */
|
|
5
|
+
pipedriveBaseUrl?: string
|
|
6
|
+
/** Typeform field refs that hold the lead's data. */
|
|
7
|
+
fieldRefs: { name: string; email: string; company?: string; phone?: string }
|
|
8
|
+
/** Prefix for the deal title, e.g. "Website lead". */
|
|
9
|
+
dealTitlePrefix?: string
|
|
10
|
+
fetch?: typeof fetch
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface TypeformAnswer {
|
|
14
|
+
type: string
|
|
15
|
+
field: { id: string; ref: string; type: string }
|
|
16
|
+
text?: string
|
|
17
|
+
email?: string
|
|
18
|
+
phone_number?: string
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface TypeformWebhook {
|
|
22
|
+
event_id: string
|
|
23
|
+
event_type: 'form_response'
|
|
24
|
+
form_response: {
|
|
25
|
+
form_id: string
|
|
26
|
+
token: string
|
|
27
|
+
submitted_at: string
|
|
28
|
+
answers: TypeformAnswer[]
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface HandleResult {
|
|
33
|
+
personId: number
|
|
34
|
+
organizationId: number | null
|
|
35
|
+
dealId: number
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
interface PipedriveResponse {
|
|
39
|
+
success: boolean
|
|
40
|
+
data?: { id: number }
|
|
41
|
+
error?: string
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export async function handle(payload: TypeformWebhook, config: ConnectorConfig): Promise<HandleResult> {
|
|
45
|
+
if (payload?.event_type !== 'form_response') {
|
|
46
|
+
throw new Error(`Unsupported Typeform event: ${String(payload?.event_type)}`)
|
|
47
|
+
}
|
|
48
|
+
const answers = payload.form_response.answers ?? []
|
|
49
|
+
const name = answerValue(answers, config.fieldRefs.name)
|
|
50
|
+
const email = answerValue(answers, config.fieldRefs.email)
|
|
51
|
+
if (!name) throw new Error(`Missing required answer for field ref "${config.fieldRefs.name}" (name)`)
|
|
52
|
+
if (!email) throw new Error(`Missing required answer for field ref "${config.fieldRefs.email}" (email)`)
|
|
53
|
+
const company = config.fieldRefs.company ? answerValue(answers, config.fieldRefs.company) : undefined
|
|
54
|
+
const phone = config.fieldRefs.phone ? answerValue(answers, config.fieldRefs.phone) : undefined
|
|
55
|
+
|
|
56
|
+
const organizationId = company ? (await post(config, '/organizations', { name: company })).id : null
|
|
57
|
+
|
|
58
|
+
const person = await post(config, '/persons', {
|
|
59
|
+
name,
|
|
60
|
+
email: [{ value: email, primary: true, label: 'work' }],
|
|
61
|
+
...(phone ? { phone: [{ value: phone, primary: true, label: 'work' }] } : {}),
|
|
62
|
+
...(organizationId ? { org_id: organizationId } : {}),
|
|
63
|
+
})
|
|
64
|
+
|
|
65
|
+
const deal = await post(config, '/deals', {
|
|
66
|
+
title: `${config.dealTitlePrefix ?? 'Typeform lead'}: ${company ?? name}`,
|
|
67
|
+
person_id: person.id,
|
|
68
|
+
...(organizationId ? { org_id: organizationId } : {}),
|
|
69
|
+
})
|
|
70
|
+
|
|
71
|
+
return { personId: person.id, organizationId, dealId: deal.id }
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function answerValue(answers: TypeformAnswer[], ref: string): string | undefined {
|
|
75
|
+
const answer = answers.find((a) => a.field?.ref === ref)
|
|
76
|
+
if (!answer) return undefined
|
|
77
|
+
const value = answer.email ?? answer.phone_number ?? answer.text
|
|
78
|
+
return value?.trim() || undefined
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async function post(config: ConnectorConfig, path: string, body: Record<string, unknown>): Promise<{ id: number }> {
|
|
82
|
+
const doFetch = config.fetch ?? fetch
|
|
83
|
+
const url = `${config.pipedriveBaseUrl ?? 'https://api.pipedrive.com/v1'}${path}`
|
|
84
|
+
const res = await doFetch(url, {
|
|
85
|
+
method: 'POST',
|
|
86
|
+
headers: { 'Content-Type': 'application/json', 'x-api-token': config.pipedriveApiToken },
|
|
87
|
+
body: JSON.stringify(body),
|
|
88
|
+
})
|
|
89
|
+
const data = (await res.json().catch(() => ({}))) as PipedriveResponse
|
|
90
|
+
if (!res.ok || !data.success || !data.data) {
|
|
91
|
+
throw new Error(`Pipedrive POST ${path} failed with ${res.status}: ${data.error ?? 'no error message'}`)
|
|
92
|
+
}
|
|
93
|
+
return data.data
|
|
94
|
+
}
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
// Written by patchbay from the API documentation. Regenerated on every attempt, do not edit.
|
|
2
|
+
// Source: https://www.typeform.com/developers/webhooks/example-payload/
|
|
3
|
+
// Source: https://developers.pipedrive.com/docs/api/v1/Organizations
|
|
4
|
+
// Source: https://developers.pipedrive.com/docs/api/v1/Persons
|
|
5
|
+
// Source: https://developers.pipedrive.com/docs/api/v1/Deals
|
|
6
|
+
|
|
7
|
+
/** Example payload of the source event, as documented. */
|
|
8
|
+
export const SOURCE_EXAMPLE = {
|
|
9
|
+
"event_id": "01H...",
|
|
10
|
+
"event_type": "form_response",
|
|
11
|
+
"form_response": {
|
|
12
|
+
"form_id": "lT4Z3j",
|
|
13
|
+
"token": "a3a12ec67a1365927098a606107fac15",
|
|
14
|
+
"submitted_at": "2026-10-01T09:00:00Z",
|
|
15
|
+
"answers": [
|
|
16
|
+
{
|
|
17
|
+
"type": "text",
|
|
18
|
+
"field": {
|
|
19
|
+
"id": "f1",
|
|
20
|
+
"ref": "lead_name",
|
|
21
|
+
"type": "short_text"
|
|
22
|
+
},
|
|
23
|
+
"text": "Ada Lovelace"
|
|
24
|
+
},
|
|
25
|
+
{
|
|
26
|
+
"type": "email",
|
|
27
|
+
"field": {
|
|
28
|
+
"id": "f2",
|
|
29
|
+
"ref": "lead_email",
|
|
30
|
+
"type": "email"
|
|
31
|
+
},
|
|
32
|
+
"email": "ada@example.com"
|
|
33
|
+
}
|
|
34
|
+
]
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface DocumentedEndpoint {
|
|
39
|
+
method: string
|
|
40
|
+
/** As documented; may contain placeholders such as {id}, :id, <id> or a region host like usX. */
|
|
41
|
+
url: string
|
|
42
|
+
response: unknown
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Target endpoints the connector may call, in the documented order, with their documented responses. */
|
|
46
|
+
export const TARGET_ENDPOINTS: DocumentedEndpoint[] = [
|
|
47
|
+
{
|
|
48
|
+
"method": "POST",
|
|
49
|
+
"url": "https://api.pipedrive.com/v1/organizations",
|
|
50
|
+
"response": {
|
|
51
|
+
"success": true,
|
|
52
|
+
"data": {
|
|
53
|
+
"id": 11
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
},
|
|
57
|
+
{
|
|
58
|
+
"method": "POST",
|
|
59
|
+
"url": "https://api.pipedrive.com/v1/persons",
|
|
60
|
+
"response": {
|
|
61
|
+
"success": true,
|
|
62
|
+
"data": {
|
|
63
|
+
"id": 22
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
},
|
|
67
|
+
{
|
|
68
|
+
"method": "POST",
|
|
69
|
+
"url": "https://api.pipedrive.com/v1/deals",
|
|
70
|
+
"response": {
|
|
71
|
+
"success": true,
|
|
72
|
+
"data": {
|
|
73
|
+
"id": 33
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
]
|
|
78
|
+
|
|
79
|
+
export interface RecordedCall {
|
|
80
|
+
method: string
|
|
81
|
+
url: string
|
|
82
|
+
/** The request body exactly as sent (usually a JSON string). */
|
|
83
|
+
body: string | undefined
|
|
84
|
+
/** The body parsed as JSON, or undefined when it is not JSON. */
|
|
85
|
+
json: unknown
|
|
86
|
+
headers: Headers
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** The documented endpoint a request matches, placeholders and region subdomains included. */
|
|
90
|
+
export function findEndpoint(method: string, url: string): DocumentedEndpoint | undefined {
|
|
91
|
+
return TARGET_ENDPOINTS.find((endpoint) => endpoint.method === method.toUpperCase() && urlMatches(endpoint.url, url))
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* A fake fetch that answers every documented endpoint with its documented response and
|
|
96
|
+
* rejects anything else. Use it in the contract test:
|
|
97
|
+
*
|
|
98
|
+
* const { fetch, calls } = contractFetch()
|
|
99
|
+
* await handle(SOURCE_EXAMPLE as MyInput, { ...config, fetch })
|
|
100
|
+
* expect(calls.length).toBeGreaterThan(0)
|
|
101
|
+
*/
|
|
102
|
+
export function contractFetch(): { fetch: typeof fetch; calls: RecordedCall[] } {
|
|
103
|
+
return fakeFetch((request) => {
|
|
104
|
+
const endpoint = findEndpoint(request.method, request.url)
|
|
105
|
+
if (!endpoint) throw new Error(`contract: ${request.method} ${request.url} is not a documented endpoint`)
|
|
106
|
+
return jsonResponse(endpoint.response)
|
|
107
|
+
})
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* A correctly typed fake fetch for every other test. The handler receives the recorded
|
|
112
|
+
* request: { method, url, body (string as sent), json (parsed body), headers (Headers) }.
|
|
113
|
+
*
|
|
114
|
+
* const { fetch, calls } = fakeFetch((req) => req.url.endsWith('/deals') ? jsonResponse({ id: 1 }, 201) : jsonResponse({}, 404))
|
|
115
|
+
*/
|
|
116
|
+
export function fakeFetch(
|
|
117
|
+
handler: (request: RecordedCall) => Response | Promise<Response>,
|
|
118
|
+
): { fetch: typeof fetch; calls: RecordedCall[] } {
|
|
119
|
+
const calls: RecordedCall[] = []
|
|
120
|
+
const fake = async (input: string | URL | Request, init: RequestInit = {}): Promise<Response> => {
|
|
121
|
+
const url = input instanceof Request ? input.url : String(input)
|
|
122
|
+
const method = (init.method ?? (input instanceof Request ? input.method : 'GET')).toUpperCase()
|
|
123
|
+
const body = typeof init.body === 'string' ? init.body : init.body == null ? undefined : String(init.body)
|
|
124
|
+
const call: RecordedCall = { method, url, body, json: parseJson(body), headers: new Headers(init.headers) }
|
|
125
|
+
calls.push(call)
|
|
126
|
+
return handler(call)
|
|
127
|
+
}
|
|
128
|
+
return { fetch: fake as typeof fetch, calls }
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const STATUS_TEXT: Record<number, string> = {
|
|
132
|
+
200: 'OK', 201: 'Created', 202: 'Accepted', 204: 'No Content',
|
|
133
|
+
400: 'Bad Request', 401: 'Unauthorized', 403: 'Forbidden', 404: 'Not Found', 409: 'Conflict',
|
|
134
|
+
422: 'Unprocessable Entity', 429: 'Too Many Requests',
|
|
135
|
+
500: 'Internal Server Error', 502: 'Bad Gateway', 503: 'Service Unavailable',
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** A JSON Response with the standard status text, e.g. jsonResponse({ error: 'nope' }, 401) -> "401 Unauthorized". */
|
|
139
|
+
export function jsonResponse(body: unknown, status = 200): Response {
|
|
140
|
+
const init = { status, statusText: STATUS_TEXT[status] ?? '', headers: { 'Content-Type': 'application/json' } }
|
|
141
|
+
return new Response(status === 204 ? null : JSON.stringify(body), init)
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function parseJson(raw: string | undefined): unknown {
|
|
145
|
+
if (raw === undefined) return undefined
|
|
146
|
+
try {
|
|
147
|
+
return JSON.parse(raw)
|
|
148
|
+
} catch {
|
|
149
|
+
return undefined
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function urlMatches(template: string, actual: string): boolean {
|
|
154
|
+
const t = splitUrl(template)
|
|
155
|
+
const a = splitUrl(actual)
|
|
156
|
+
if (!t || !a) return false
|
|
157
|
+
const tHost = t.host.split('.')
|
|
158
|
+
const aHost = a.host.split('.')
|
|
159
|
+
if (tHost.slice(-2).join('.') !== aHost.slice(-2).join('.')) return false
|
|
160
|
+
const tPath = t.path.replace(/\/+$/, '').split('/')
|
|
161
|
+
const aPath = a.path.replace(/\/+$/, '').split('/')
|
|
162
|
+
if (tPath.length !== aPath.length) return false
|
|
163
|
+
return tPath.every((segment, i) => isPlaceholder(segment) || segment === aPath[i])
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function splitUrl(url: string): { host: string; path: string } | null {
|
|
167
|
+
const match = url.match(/^https?:\/\/([^/?#]+)([^?#]*)/i)
|
|
168
|
+
return match ? { host: (match[1] ?? '').toLowerCase(), path: match[2] || '/' } : null
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function isPlaceholder(segment: string): boolean {
|
|
172
|
+
return /^\{[^}]+\}$|^:[A-Za-z_]\w*$|^<[^>]+>$/.test(segment)
|
|
173
|
+
}
|