// © 2026 Evntx FZCO, Dubai, UAE. All rights reserved. // Reference connector (#DEVKIT-REFERENCE-CONNECTORS-1): an API key, numbered pages, a list picker filled from the API, // and a polling trigger that never starts a flow twice for the same contact. Built only against the public // connector framework package. The API is a generic contacts service (https://api.example.org/v2). import { createAction, createConnector, createTrigger, ConnectorAuth, Property, TriggerStrategy } from '@aancer/connector-framework'; export const API = 'https://api.example.org/v2'; export type Contact = { id: string; email: string; name: string; listId: string; createdAt: string }; type Page = { items: T[]; page: number; total_pages: number }; /** One API call with the key in a header; up to 3 retries on 429/5xx (Retry-After in seconds, else 1 s doubling). */ export async function call(apiKey: string, path: string, init: { method?: 'GET' | 'POST'; body?: unknown } = {}): Promise { for (let attempt = 0; ; attempt++) { const res = await fetch(`${API}${path}`, { method: init.method ?? 'GET', headers: { 'x-api-key': apiKey, accept: 'application/json', ...(init.body === undefined ? {} : { 'content-type': 'application/json' }) }, body: init.body === undefined ? undefined : JSON.stringify(init.body), signal: AbortSignal.timeout(30_000), }); if ((res.status === 429 || res.status >= 500) && attempt < 3) { const s = Number(res.headers.get('retry-after') ?? NaN); await new Promise((r) => setTimeout(r, Math.min(Number.isFinite(s) ? s * 1000 : 1000 * 2 ** attempt, 30_000))); continue; } if (res.status === 401 || res.status === 403) throw new Error('Example Contacts: the API key was refused. Check it in the connection.'); if (!res.ok) throw new Error(`Example Contacts ${init.method ?? 'GET'} ${path}: HTTP ${res.status} ${(await res.text()).slice(0, 300)}`); return (await res.json()) as T; } } /** Every item of a numbered-page listing, page 1..total_pages, at most `max`. */ export async function allPages(apiKey: string, path: string, max: number): Promise { const out: T[] = []; for (let page = 1; out.length < max; page++) { const sep = path.includes('?') ? '&' : '?'; const r: Page = await call>(apiKey, `${path}${sep}page=${page}&per_page=100`); out.push(...r.items); if (page >= r.total_pages || r.items.length === 0) break; } return out.slice(0, max); } export const auth = ConnectorAuth.SecretText({ displayName: 'API key', description: 'Settings → API keys in your Example Contacts account. Read access is enough for the trigger.', required: true, validate: async ({ auth }) => { try { await call(auth, '/me'); return { valid: true }; } catch (e) { return { valid: false, error: (e as Error).message }; } }, }); /** The list picker: filled from the API with the connection the step uses. */ const listProp = Property.Dropdown({ displayName: 'List', required: true, auth, refreshers: [], options: async ({ auth: conn }) => { if (!conn) return { disabled: true, placeholder: 'Choose a connection first', options: [] }; const lists = await allPages<{ id: string; name: string }>(conn.secret_text, '/lists', 1000); return { options: lists.map((l) => ({ label: l.name, value: l.id })) }; }, }); export const listContacts = createAction({ auth, name: 'list_contacts', displayName: 'List contacts', description: 'Returns the contacts of a list, page by page up to the limit.', props: { listId: listProp, maxItems: Property.Number({ displayName: 'At most', required: false, defaultValue: 500 }) }, async run({ auth, propsValue }) { const max = Math.min(Math.max(Math.trunc(propsValue.maxItems ?? 500), 1), 10_000); return { contacts: await allPages(auth.secret_text, `/lists/${encodeURIComponent(propsValue.listId)}/contacts`, max) }; }, }); // Polling: the installation calls run() on its schedule. The store keeps a high-water mark (createdAt) plus the ids // seen AT that instant, so two contacts with the same timestamp across two polls are neither lost nor doubled. const MARK = 'contacts_mark'; type Mark = { at: string; ids: string[] }; export function fresh(items: Contact[], mark: Mark): { items: Contact[]; mark: Mark } { const seen = new Set(mark.ids); const out = items.filter((c) => c.createdAt > mark.at || (c.createdAt === mark.at && !seen.has(c.id))) .sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id)); if (!out.length) return { items: [], mark }; const at = out[out.length - 1].createdAt; const ids = [...(at === mark.at ? mark.ids : []), ...out.filter((c) => c.createdAt === at).map((c) => c.id)]; return { items: out, mark: { at, ids } }; } export const newContact = createTrigger({ auth, name: 'new_contact', displayName: 'New contact', description: 'Starts once for every contact added to the list.', type: TriggerStrategy.POLLING, props: { listId: listProp }, sampleData: { id: 'c_1', email: 'person@example.org', name: 'A Person', listId: 'l_1', createdAt: '2026-01-01T00:00:00.000Z' }, async onEnable({ auth, propsValue, store }) { // Start from now: contacts that exist when the flow is switched on do not start it. const latest = await call>(auth.secret_text, `/lists/${encodeURIComponent(propsValue.listId)}/contacts?sort=-createdAt&page=1&per_page=1`); const top = latest.items[0]; await store.put(MARK, { at: top?.createdAt ?? new Date(0).toISOString(), ids: top ? [top.id] : [] }); }, async onDisable({ store }) { await store.delete(MARK); }, async run({ auth, propsValue, store }) { const mark = (await store.get(MARK)) ?? { at: new Date(0).toISOString(), ids: [] }; const since = encodeURIComponent(mark.at); const items = await allPages(auth.secret_text, `/lists/${encodeURIComponent(propsValue.listId)}/contacts?created_since=${since}`, 5000); const r = fresh(items, mark); if (r.items.length) await store.put(MARK, r.mark); return r.items; }, async test({ auth, propsValue }) { return allPages(auth.secret_text, `/lists/${encodeURIComponent(propsValue.listId)}/contacts`, 3); }, }); export const exampleContacts = createConnector({ displayName: 'Reference: API key contacts', description: 'Lists contacts page by page and starts a flow for each new contact.', logoUrl: 'https://api.example.org/logo.svg', minimumSupportedRelease: '0.0.0', authors: ['aancer'], auth, actions: [listContacts], triggers: [newContact], });