@formgong/core 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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Formgong
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,144 @@
1
+ # @formgong/core
2
+
3
+ [![npm](https://img.shields.io/npm/v/@formgong/core?color=4f46e5&label=npm)](https://www.npmjs.com/package/@formgong/core) [![size](https://img.shields.io/bundlephobia/minzip/@formgong/core?label=min%2Bgzip)](https://bundlephobia.com/package/@formgong/core) [![types](https://img.shields.io/npm/types/@formgong/core)](https://www.npmjs.com/package/@formgong/core) [![CI](https://github.com/formgong/js/actions/workflows/ci.yml/badge.svg)](https://github.com/formgong/js/actions/workflows/ci.yml) [![license](https://img.shields.io/npm/l/@formgong/core)](https://github.com/formgong/js/blob/main/LICENSE)
4
+
5
+ > A tiny, typed client for **[Formgong](https://formgong.com)**, the form backend for contact forms. Post a form from any JavaScript runtime and the submission arrives by email, Telegram or webhook. You don't need a server, a database or SMTP.
6
+
7
+ - **About 3 kB min+gzip, no dependencies.** ESM and CJS builds with TypeScript types.
8
+ - **Runs anywhere:** browsers, Node 18+, Deno, Bun, Cloudflare Workers, Vercel and Netlify Edge.
9
+ - **Typed errors** carry stable codes such as `unknown_access_key`, `rate_limited` and `turnstile_missing`.
10
+ - **Anti-spam built in:** honeypot handling, and the same behaviour signals and proof-of-work as Formgong's `fg.js`.
11
+ - **Account API** (`@formgong/core/api`) for scripts and AI agents: list forms, create a form, get a snippet, read submissions.
12
+
13
+ ```bash
14
+ npm install @formgong/core
15
+ ```
16
+
17
+ ## Quick start
18
+
19
+ ```ts
20
+ import { submit, FormgongError } from "@formgong/core";
21
+
22
+ try {
23
+ const { id, message } = await submit("fk_your_access_key", {
24
+ name: "Ada Lovelace",
25
+ email: "ada@example.com",
26
+ message: "Hello!",
27
+ });
28
+ console.log(message); // "Sent. Thank you!" (localized)
29
+ } catch (error) {
30
+ if (error instanceof FormgongError) console.error(error.code, error.message);
31
+ }
32
+ ```
33
+
34
+ Get a free access key (`fk_…`) at [formgong.com](https://formgong.com). It is **public by design**: it can only send submissions to your form, so it is safe in frontend code.
35
+
36
+ ## Browser forms
37
+
38
+ ```ts
39
+ import { createTracker, submit } from "@formgong/core";
40
+
41
+ const form = document.querySelector("form")!;
42
+ // Optional: the same anti-spam signals as fg.js (typing/paste counts + a small proof-of-work).
43
+ const tracker = createTracker(form, "fk_your_access_key");
44
+
45
+ form.addEventListener("submit", async (event) => {
46
+ event.preventDefault();
47
+ const result = await submit("fk_your_access_key", form, { tracker, lang: "de" });
48
+ form.reset();
49
+ tracker.next();
50
+ alert(result.message);
51
+ });
52
+ ```
53
+
54
+ Add a hidden honeypot field to the form, `<input name="botcheck" tabindex="-1" autocomplete="off" style="position:absolute;left:-10000px">`, and keep it empty.
55
+
56
+ ## API
57
+
58
+ ### `submit(accessKey, data, options?) => Promise<SubmitResult>`
59
+
60
+ `data` can be a plain object, `FormData`, `URLSearchParams` or an `HTMLFormElement`. Objects are sent as JSON, with arrays joined as `"a, b"`. Objects that contain a `Blob` or `File` are sent as multipart. FormData is copied, so your object is never modified.
61
+
62
+ | Option | Description |
63
+ | --- | --- |
64
+ | `lang` | Visitor language for messages and the autoreply: `en uk pl tr de es fr pt ar he hi ja`. Defaults to `<html lang>` in browsers. |
65
+ | `subject`, `replyTo`, `fromName` | Email subject, Reply-To address and sender name (`_subject`, `_replyto`, `_from_name`). |
66
+ | `turnstileToken` | Cloudflare Turnstile token, if the form has Turnstile enabled. |
67
+ | `tracker` | A `createTracker()` instance. It adds `_fg_b` and `_fg_pow`, exactly like fg.js. |
68
+ | `honeypot` | `"send"` (default) lets Formgong file a filled honeypot as spam. `"drop"` resolves locally without sending a request. |
69
+ | `origin` | Server-side only: the `Origin` header to send, for forms restricted to allowed domains. |
70
+ | `endpoint` | Submit URL. Default `https://formgong.com/submit`. |
71
+ | `timeoutMs`, `signal`, `fetch`, `headers` | Transport controls. The default timeout is 15 s. |
72
+
73
+ It resolves to `{ success: true, id, lang, message }` and throws `FormgongError` on failure.
74
+
75
+ ### `FormgongError`
76
+
77
+ | Property | Description |
78
+ | --- | --- |
79
+ | `code` | Stable code. Server codes: `missing_access_key`, `unknown_access_key`, `invalid_json`, `too_many_fields`, `too_large`, `origin_not_allowed`, `rate_limited`, `limit_exceeded`, `turnstile_missing`, `turnstile_failed`, `uploads_disabled`, `file_unsafe`, … Client codes: `network_error`, `timeout`, `aborted`, `invalid_response`. |
80
+ | `status` | HTTP status, or `0` for network errors. |
81
+ | `message` | Localized, human-readable text that is ready to show. |
82
+ | `retryable` | `true` for network problems, rate limits and 5xx responses. |
83
+
84
+ Other helpers:
85
+
86
+ - `trySubmit()`: the same as `submit` but never throws. It returns `{ ok, result | error }`.
87
+ - `createClient(accessKey, defaults)`: binds an access key and default options once.
88
+ - `honeypotTriggered(data)`: tells you whether a honeypot field is filled in.
89
+
90
+ ### Anti-spam: `createTracker(target, accessKey, options?)`
91
+
92
+ It counts keydowns, pastes and the distinct fields typed into, starting from when the form is seen. On the first interaction it fetches a signed challenge from `GET /pow?k=…` and solves it in the background with Web Crypto (SHA-256, about 13 bits, typically a fraction of a second). Call `tracker.signals()` to get `{ _fg_b, _fg_pow }`. It waits up to 2 s for the proof-of-work, like fg.js.
93
+
94
+ Formgong only scores these signals when `_fg_b` is present. Server-side and SDK posts without them are **never penalised**, so never create a tracker on a server and never fake the values.
95
+
96
+ Lower-level helpers: `solvePow(challenge)`, `fetchPowChallenge(accessKey)`, `leadingZeroBits()`.
97
+
98
+ ### Account API: `@formgong/core/api`
99
+
100
+ ```ts
101
+ import { FormgongApi } from "@formgong/core/api";
102
+
103
+ const api = new FormgongApi({ token: process.env.FORMGONG_TOKEN }); // fgp_… personal API token
104
+ const { form } = await api.createForm({ name: "Contact – acme.com" });
105
+ const { code } = await api.getFormSnippet({ form_id: form.id, framework: "react" });
106
+ const { submissions } = await api.listRecentSubmissions({ form_id: form.id, limit: 5 });
107
+ ```
108
+
109
+ This talks JSON-RPC to the [Formgong MCP endpoint](https://formgong.com/en/docs/mcp/) (`POST https://formgong.com/mcp`). Create tokens under Dashboard → Account → API tokens. Personal tokens are secrets: use them on the server, in scripts or in CI, never in a browser. Limits: 60 requests per minute per token and 10 new forms per hour.
110
+
111
+ ## Server-side notes
112
+
113
+ From a server (Node, Workers, Server Actions), per-IP rate limits apply to **your server's IP**: 20 submissions per minute per IP and 30 per minute per form. If the form only allows certain domains, pass `origin`. For Next.js, use [`@formgong/next`](https://www.npmjs.com/package/@formgong/next), which forwards Origin and Accept-Language for you.
114
+
115
+ ## Why Formgong
116
+
117
+ Formgong is a hosted form backend with a free plan, built for static and AI-built sites. Submissions go to **email and Telegram**, plus webhooks for Make, n8n and Zapier. Data is stored in the EU, and messages and autoreplies come in 12 languages. Spam filtering includes a honeypot, optional Cloudflare Turnstile and cookie-free behaviour signals, with no stored fingerprints.
118
+
119
+ How it compares with Formspree, Web3Forms, Basin, Getform, FormSubmit and Netlify Forms: **[formgong.com/en/compare](https://formgong.com/en/compare/)**. Moving from Formspree takes one line: change the form `action` or the access key ([guide](https://formgong.com/en/formspree-alternative/)).
120
+
121
+ ## Packages
122
+
123
+ | Package | What it is |
124
+ | --- | --- |
125
+ | [`@formgong/core`](https://www.npmjs.com/package/@formgong/core) | Tiny typed client: `submit()`, typed errors, anti-spam tracker, account API |
126
+ | [`@formgong/react`](https://www.npmjs.com/package/@formgong/react) | `<ContactForm>`, `<FormgongForm>`, `useFormgong()` for React, Lovable, Bolt and v0 |
127
+ | [`@formgong/next`](https://www.npmjs.com/package/@formgong/next) | Next.js Server Action and Route Handler helpers, plus App Router components |
128
+ | [`@formgong/vue`](https://www.npmjs.com/package/@formgong/vue) | Vue 3 and Nuxt components and the `useFormgong()` composable |
129
+ | [`@formgong/svelte`](https://www.npmjs.com/package/@formgong/svelte) | `use:formgong` action, store helper, Svelte components |
130
+ | [`@formgong/astro`](https://www.npmjs.com/package/@formgong/astro) | Astro components with progressive enhancement, plus a helper for Actions |
131
+ | [`formgong`](https://www.npmjs.com/package/formgong) | CLI: `npx formgong init` creates a form and adds it to your project |
132
+ | [`create-formgong`](https://www.npmjs.com/package/create-formgong) | `npm create formgong@latest`: starter projects |
133
+
134
+ ## Links
135
+
136
+ - Docs: https://formgong.com/en/docs/
137
+ - MCP server for Cursor, Claude and VS Code: https://formgong.com/en/docs/mcp/
138
+ - Source: https://github.com/formgong/js
139
+ - Issues: https://github.com/formgong/js/issues
140
+ - Support: support@formgong.com
141
+
142
+ ## License
143
+
144
+ MIT © Formgong
package/dist/api.cjs ADDED
@@ -0,0 +1,89 @@
1
+ 'use strict';
2
+
3
+ // src/api.ts
4
+ var DEFAULT_API_URL = "https://formgong.com/mcp";
5
+ var MCP_PROTOCOL_VERSION = "2025-06-18";
6
+ var FormgongApiError = class extends Error {
7
+ constructor(code, message, status = 0, data) {
8
+ super(message);
9
+ this.code = code;
10
+ this.status = status;
11
+ this.data = data;
12
+ this.name = "FormgongApiError";
13
+ }
14
+ };
15
+ var nextId = 1;
16
+ var FormgongApi = class {
17
+ constructor(options = {}) {
18
+ this.url = options.url ?? DEFAULT_API_URL;
19
+ this.token = options.token?.trim() || void 0;
20
+ this.doFetch = options.fetch ?? globalThis.fetch;
21
+ this.userAgent = options.userAgent;
22
+ }
23
+ /** Raw JSON-RPC call. */
24
+ async rpc(method, params) {
25
+ const headers = {
26
+ "Content-Type": "application/json",
27
+ Accept: "application/json, text/event-stream",
28
+ "MCP-Protocol-Version": MCP_PROTOCOL_VERSION
29
+ };
30
+ if (this.token) headers.Authorization = `Bearer ${this.token}`;
31
+ if (this.userAgent) headers["User-Agent"] = this.userAgent;
32
+ let response;
33
+ try {
34
+ response = await this.doFetch(this.url, { method: "POST", headers, body: JSON.stringify({ jsonrpc: "2.0", id: nextId++, method, ...params ? { params } : {} }) });
35
+ } catch (error) {
36
+ throw new FormgongApiError("network_error", `Could not reach ${this.url}: ${error instanceof Error ? error.message : String(error)}`);
37
+ }
38
+ const text = await response.text();
39
+ let json;
40
+ try {
41
+ json = JSON.parse(text);
42
+ } catch {
43
+ throw new FormgongApiError(response.ok ? "invalid_response" : "http_error", `Unexpected response from Formgong (HTTP ${response.status}).`, response.status);
44
+ }
45
+ if (json?.error) {
46
+ const reason = json.error.data?.reason;
47
+ const code = response.status === 429 ? "rate_limited" : reason === "invalid_token" ? "invalid_token" : reason === "token_required" ? "token_required" : "rpc_error";
48
+ throw new FormgongApiError(code, json.error.message, response.status, json.error.data);
49
+ }
50
+ if (!response.ok || !json || !("result" in json)) throw new FormgongApiError("http_error", `Formgong returned HTTP ${response.status}.`, response.status);
51
+ return json.result;
52
+ }
53
+ /** Call a tool and return its structured result. Throws `FormgongApiError("tool_error")` for tool errors. */
54
+ async call(name, args = {}) {
55
+ const result = await this.rpc("tools/call", { name, arguments: args });
56
+ const text = result.content?.map((part) => part.text ?? "").join("\n") ?? "";
57
+ if (result.isError) throw new FormgongApiError("tool_error", text || `Tool ${name} failed.`);
58
+ if (result.structuredContent !== void 0) return result.structuredContent;
59
+ try {
60
+ return JSON.parse(text);
61
+ } catch {
62
+ throw new FormgongApiError("invalid_response", `Tool ${name} returned no structured result.`);
63
+ }
64
+ }
65
+ async tools() {
66
+ return (await this.rpc("tools/list")).tools;
67
+ }
68
+ async ping() {
69
+ await this.rpc("ping");
70
+ return true;
71
+ }
72
+ listForms() {
73
+ return this.call("list_forms");
74
+ }
75
+ createForm(input) {
76
+ return this.call("create_form", input);
77
+ }
78
+ getFormSnippet(input) {
79
+ return this.call("get_form_snippet", input);
80
+ }
81
+ listRecentSubmissions(input) {
82
+ return this.call("list_recent_submissions", input);
83
+ }
84
+ };
85
+
86
+ exports.DEFAULT_API_URL = DEFAULT_API_URL;
87
+ exports.FormgongApi = FormgongApi;
88
+ exports.FormgongApiError = FormgongApiError;
89
+ exports.MCP_PROTOCOL_VERSION = MCP_PROTOCOL_VERSION;
package/dist/api.d.cts ADDED
@@ -0,0 +1,115 @@
1
+ /**
2
+ * @formgong/core/api: account API for scripts, CLIs and AI agents.
3
+ * Talks to the Formgong MCP endpoint (POST https://formgong.com/mcp, JSON-RPC 2.0) with a
4
+ * personal API token (fgp_…) from Dashboard → Account → API tokens. Server-side / CLI only:
5
+ * never ship a personal token to a browser.
6
+ */
7
+ declare const DEFAULT_API_URL = "https://formgong.com/mcp";
8
+ declare const MCP_PROTOCOL_VERSION = "2025-06-18";
9
+ type FormSummary = {
10
+ id: string;
11
+ name: string;
12
+ access_key: string;
13
+ created_at: string;
14
+ submissions_this_month: number;
15
+ dashboard_url: string;
16
+ };
17
+ type ListFormsResult = {
18
+ endpoint: string;
19
+ forms: FormSummary[];
20
+ };
21
+ type CreateFormInput = {
22
+ name: string;
23
+ notify_email?: boolean;
24
+ };
25
+ type CreateFormResult = {
26
+ form: {
27
+ id: string;
28
+ name: string;
29
+ access_key: string;
30
+ endpoint: string;
31
+ };
32
+ notifications: {
33
+ email: string | null;
34
+ email_verified: boolean;
35
+ telegram: string;
36
+ };
37
+ dashboard: {
38
+ install: string;
39
+ inbox: string;
40
+ email_settings: string;
41
+ telegram_settings: string;
42
+ };
43
+ next_step?: string;
44
+ };
45
+ type SnippetFramework = "html" | "react" | "next";
46
+ type GetSnippetInput = {
47
+ form_id: string;
48
+ framework?: SnippetFramework;
49
+ lang?: string;
50
+ };
51
+ type GetSnippetResult = {
52
+ form_id: string;
53
+ framework: SnippetFramework;
54
+ lang: string;
55
+ code: string;
56
+ notes: string[];
57
+ };
58
+ type ListSubmissionsInput = {
59
+ form_id: string;
60
+ limit?: number;
61
+ include_spam?: boolean;
62
+ };
63
+ type Submission = {
64
+ id: string;
65
+ created_at: string;
66
+ spam?: boolean;
67
+ fields: Record<string, string>;
68
+ };
69
+ type ListSubmissionsResult = {
70
+ form_id: string;
71
+ notice: string;
72
+ submissions: Submission[];
73
+ };
74
+ type ToolInfo = {
75
+ name: string;
76
+ title?: string;
77
+ description?: string;
78
+ inputSchema?: unknown;
79
+ annotations?: Record<string, unknown>;
80
+ };
81
+ type ApiErrorCode = "token_required" | "invalid_token" | "rate_limited" | "tool_error" | "rpc_error" | "http_error" | "network_error" | "invalid_response";
82
+ declare class FormgongApiError extends Error {
83
+ readonly code: ApiErrorCode;
84
+ readonly status: number;
85
+ readonly data?: unknown | undefined;
86
+ readonly name = "FormgongApiError";
87
+ constructor(code: ApiErrorCode, message: string, status?: number, data?: unknown | undefined);
88
+ }
89
+ type FormgongApiOptions = {
90
+ /** Personal API token (fgp_…). Optional for `tools()` / `ping()`. */
91
+ token?: string;
92
+ /** MCP endpoint. Default https://formgong.com/mcp. */
93
+ url?: string;
94
+ fetch?: typeof fetch;
95
+ userAgent?: string;
96
+ };
97
+ declare class FormgongApi {
98
+ readonly url: string;
99
+ private readonly token?;
100
+ private readonly doFetch;
101
+ private readonly userAgent?;
102
+ constructor(options?: FormgongApiOptions);
103
+ /** Raw JSON-RPC call. */
104
+ rpc<T = unknown>(method: string, params?: Record<string, unknown>): Promise<T>;
105
+ /** Call a tool and return its structured result. Throws `FormgongApiError("tool_error")` for tool errors. */
106
+ call<T = Record<string, unknown>>(name: string, args?: Record<string, unknown>): Promise<T>;
107
+ tools(): Promise<ToolInfo[]>;
108
+ ping(): Promise<boolean>;
109
+ listForms(): Promise<ListFormsResult>;
110
+ createForm(input: CreateFormInput): Promise<CreateFormResult>;
111
+ getFormSnippet(input: GetSnippetInput): Promise<GetSnippetResult>;
112
+ listRecentSubmissions(input: ListSubmissionsInput): Promise<ListSubmissionsResult>;
113
+ }
114
+
115
+ export { type ApiErrorCode, type CreateFormInput, type CreateFormResult, DEFAULT_API_URL, type FormSummary, FormgongApi, FormgongApiError, type FormgongApiOptions, type GetSnippetInput, type GetSnippetResult, type ListFormsResult, type ListSubmissionsInput, type ListSubmissionsResult, MCP_PROTOCOL_VERSION, type SnippetFramework, type Submission, type ToolInfo };
package/dist/api.d.ts ADDED
@@ -0,0 +1,115 @@
1
+ /**
2
+ * @formgong/core/api: account API for scripts, CLIs and AI agents.
3
+ * Talks to the Formgong MCP endpoint (POST https://formgong.com/mcp, JSON-RPC 2.0) with a
4
+ * personal API token (fgp_…) from Dashboard → Account → API tokens. Server-side / CLI only:
5
+ * never ship a personal token to a browser.
6
+ */
7
+ declare const DEFAULT_API_URL = "https://formgong.com/mcp";
8
+ declare const MCP_PROTOCOL_VERSION = "2025-06-18";
9
+ type FormSummary = {
10
+ id: string;
11
+ name: string;
12
+ access_key: string;
13
+ created_at: string;
14
+ submissions_this_month: number;
15
+ dashboard_url: string;
16
+ };
17
+ type ListFormsResult = {
18
+ endpoint: string;
19
+ forms: FormSummary[];
20
+ };
21
+ type CreateFormInput = {
22
+ name: string;
23
+ notify_email?: boolean;
24
+ };
25
+ type CreateFormResult = {
26
+ form: {
27
+ id: string;
28
+ name: string;
29
+ access_key: string;
30
+ endpoint: string;
31
+ };
32
+ notifications: {
33
+ email: string | null;
34
+ email_verified: boolean;
35
+ telegram: string;
36
+ };
37
+ dashboard: {
38
+ install: string;
39
+ inbox: string;
40
+ email_settings: string;
41
+ telegram_settings: string;
42
+ };
43
+ next_step?: string;
44
+ };
45
+ type SnippetFramework = "html" | "react" | "next";
46
+ type GetSnippetInput = {
47
+ form_id: string;
48
+ framework?: SnippetFramework;
49
+ lang?: string;
50
+ };
51
+ type GetSnippetResult = {
52
+ form_id: string;
53
+ framework: SnippetFramework;
54
+ lang: string;
55
+ code: string;
56
+ notes: string[];
57
+ };
58
+ type ListSubmissionsInput = {
59
+ form_id: string;
60
+ limit?: number;
61
+ include_spam?: boolean;
62
+ };
63
+ type Submission = {
64
+ id: string;
65
+ created_at: string;
66
+ spam?: boolean;
67
+ fields: Record<string, string>;
68
+ };
69
+ type ListSubmissionsResult = {
70
+ form_id: string;
71
+ notice: string;
72
+ submissions: Submission[];
73
+ };
74
+ type ToolInfo = {
75
+ name: string;
76
+ title?: string;
77
+ description?: string;
78
+ inputSchema?: unknown;
79
+ annotations?: Record<string, unknown>;
80
+ };
81
+ type ApiErrorCode = "token_required" | "invalid_token" | "rate_limited" | "tool_error" | "rpc_error" | "http_error" | "network_error" | "invalid_response";
82
+ declare class FormgongApiError extends Error {
83
+ readonly code: ApiErrorCode;
84
+ readonly status: number;
85
+ readonly data?: unknown | undefined;
86
+ readonly name = "FormgongApiError";
87
+ constructor(code: ApiErrorCode, message: string, status?: number, data?: unknown | undefined);
88
+ }
89
+ type FormgongApiOptions = {
90
+ /** Personal API token (fgp_…). Optional for `tools()` / `ping()`. */
91
+ token?: string;
92
+ /** MCP endpoint. Default https://formgong.com/mcp. */
93
+ url?: string;
94
+ fetch?: typeof fetch;
95
+ userAgent?: string;
96
+ };
97
+ declare class FormgongApi {
98
+ readonly url: string;
99
+ private readonly token?;
100
+ private readonly doFetch;
101
+ private readonly userAgent?;
102
+ constructor(options?: FormgongApiOptions);
103
+ /** Raw JSON-RPC call. */
104
+ rpc<T = unknown>(method: string, params?: Record<string, unknown>): Promise<T>;
105
+ /** Call a tool and return its structured result. Throws `FormgongApiError("tool_error")` for tool errors. */
106
+ call<T = Record<string, unknown>>(name: string, args?: Record<string, unknown>): Promise<T>;
107
+ tools(): Promise<ToolInfo[]>;
108
+ ping(): Promise<boolean>;
109
+ listForms(): Promise<ListFormsResult>;
110
+ createForm(input: CreateFormInput): Promise<CreateFormResult>;
111
+ getFormSnippet(input: GetSnippetInput): Promise<GetSnippetResult>;
112
+ listRecentSubmissions(input: ListSubmissionsInput): Promise<ListSubmissionsResult>;
113
+ }
114
+
115
+ export { type ApiErrorCode, type CreateFormInput, type CreateFormResult, DEFAULT_API_URL, type FormSummary, FormgongApi, FormgongApiError, type FormgongApiOptions, type GetSnippetInput, type GetSnippetResult, type ListFormsResult, type ListSubmissionsInput, type ListSubmissionsResult, MCP_PROTOCOL_VERSION, type SnippetFramework, type Submission, type ToolInfo };
package/dist/api.js ADDED
@@ -0,0 +1,84 @@
1
+ // src/api.ts
2
+ var DEFAULT_API_URL = "https://formgong.com/mcp";
3
+ var MCP_PROTOCOL_VERSION = "2025-06-18";
4
+ var FormgongApiError = class extends Error {
5
+ constructor(code, message, status = 0, data) {
6
+ super(message);
7
+ this.code = code;
8
+ this.status = status;
9
+ this.data = data;
10
+ this.name = "FormgongApiError";
11
+ }
12
+ };
13
+ var nextId = 1;
14
+ var FormgongApi = class {
15
+ constructor(options = {}) {
16
+ this.url = options.url ?? DEFAULT_API_URL;
17
+ this.token = options.token?.trim() || void 0;
18
+ this.doFetch = options.fetch ?? globalThis.fetch;
19
+ this.userAgent = options.userAgent;
20
+ }
21
+ /** Raw JSON-RPC call. */
22
+ async rpc(method, params) {
23
+ const headers = {
24
+ "Content-Type": "application/json",
25
+ Accept: "application/json, text/event-stream",
26
+ "MCP-Protocol-Version": MCP_PROTOCOL_VERSION
27
+ };
28
+ if (this.token) headers.Authorization = `Bearer ${this.token}`;
29
+ if (this.userAgent) headers["User-Agent"] = this.userAgent;
30
+ let response;
31
+ try {
32
+ response = await this.doFetch(this.url, { method: "POST", headers, body: JSON.stringify({ jsonrpc: "2.0", id: nextId++, method, ...params ? { params } : {} }) });
33
+ } catch (error) {
34
+ throw new FormgongApiError("network_error", `Could not reach ${this.url}: ${error instanceof Error ? error.message : String(error)}`);
35
+ }
36
+ const text = await response.text();
37
+ let json;
38
+ try {
39
+ json = JSON.parse(text);
40
+ } catch {
41
+ throw new FormgongApiError(response.ok ? "invalid_response" : "http_error", `Unexpected response from Formgong (HTTP ${response.status}).`, response.status);
42
+ }
43
+ if (json?.error) {
44
+ const reason = json.error.data?.reason;
45
+ const code = response.status === 429 ? "rate_limited" : reason === "invalid_token" ? "invalid_token" : reason === "token_required" ? "token_required" : "rpc_error";
46
+ throw new FormgongApiError(code, json.error.message, response.status, json.error.data);
47
+ }
48
+ if (!response.ok || !json || !("result" in json)) throw new FormgongApiError("http_error", `Formgong returned HTTP ${response.status}.`, response.status);
49
+ return json.result;
50
+ }
51
+ /** Call a tool and return its structured result. Throws `FormgongApiError("tool_error")` for tool errors. */
52
+ async call(name, args = {}) {
53
+ const result = await this.rpc("tools/call", { name, arguments: args });
54
+ const text = result.content?.map((part) => part.text ?? "").join("\n") ?? "";
55
+ if (result.isError) throw new FormgongApiError("tool_error", text || `Tool ${name} failed.`);
56
+ if (result.structuredContent !== void 0) return result.structuredContent;
57
+ try {
58
+ return JSON.parse(text);
59
+ } catch {
60
+ throw new FormgongApiError("invalid_response", `Tool ${name} returned no structured result.`);
61
+ }
62
+ }
63
+ async tools() {
64
+ return (await this.rpc("tools/list")).tools;
65
+ }
66
+ async ping() {
67
+ await this.rpc("ping");
68
+ return true;
69
+ }
70
+ listForms() {
71
+ return this.call("list_forms");
72
+ }
73
+ createForm(input) {
74
+ return this.call("create_form", input);
75
+ }
76
+ getFormSnippet(input) {
77
+ return this.call("get_form_snippet", input);
78
+ }
79
+ listRecentSubmissions(input) {
80
+ return this.call("list_recent_submissions", input);
81
+ }
82
+ };
83
+
84
+ export { DEFAULT_API_URL, FormgongApi, FormgongApiError, MCP_PROTOCOL_VERSION };