@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/dist/index.cjs ADDED
@@ -0,0 +1,304 @@
1
+ 'use strict';
2
+
3
+ // src/errors.ts
4
+ var FormgongError = class extends Error {
5
+ constructor(code, message, status = 0, body, options) {
6
+ super(message);
7
+ this.name = "FormgongError";
8
+ this.code = code;
9
+ this.status = status;
10
+ this.body = body;
11
+ if (options && "cause" in options) this.cause = options.cause;
12
+ }
13
+ /** True for errors worth retrying later (network trouble, rate limits). */
14
+ get retryable() {
15
+ return this.code === "network_error" || this.code === "timeout" || this.code === "rate_limited" || this.status >= 500;
16
+ }
17
+ };
18
+ function isFormgongError(error) {
19
+ return error instanceof FormgongError || typeof error === "object" && error !== null && error.name === "FormgongError" && typeof error.code === "string";
20
+ }
21
+
22
+ // src/pow.ts
23
+ var BATCH = 128;
24
+ var POW_MAX_NONCE = 1e6;
25
+ function subtle() {
26
+ const c = globalThis.crypto;
27
+ return c && c.subtle ? c.subtle : void 0;
28
+ }
29
+ function powSupported() {
30
+ return subtle() !== void 0;
31
+ }
32
+ function leadingZeroBits(bytes) {
33
+ let bits = 0;
34
+ for (const byte of bytes) {
35
+ if (byte === 0) {
36
+ bits += 8;
37
+ continue;
38
+ }
39
+ return bits + Math.clz32(byte) - 24;
40
+ }
41
+ return bits;
42
+ }
43
+ function challengeBits(challenge) {
44
+ const bits = Number(challenge.split(".")[3]);
45
+ if (!Number.isInteger(bits) || bits < 1 || bits > 32) throw new Error("Invalid Formgong proof-of-work challenge");
46
+ return bits;
47
+ }
48
+ async function solvePow(challenge, options = {}) {
49
+ const api = subtle();
50
+ if (!api) return "na";
51
+ const bits = challengeBits(challenge);
52
+ const max = options.maxNonce ?? POW_MAX_NONCE;
53
+ const encoder = new TextEncoder();
54
+ for (let n = 0; n < max; n += BATCH) {
55
+ if (options.signal?.aborted) throw options.signal.reason ?? new Error("aborted");
56
+ const batch = [];
57
+ for (let j = 0; j < BATCH; j++) batch.push(api.digest("SHA-256", encoder.encode(`${challenge}:${n + j}`)));
58
+ const hashes = await Promise.all(batch);
59
+ for (let j = 0; j < BATCH; j++) {
60
+ if (leadingZeroBits(new Uint8Array(hashes[j])) >= bits) return `${challenge}~${n + j}`;
61
+ }
62
+ }
63
+ return "na";
64
+ }
65
+ async function fetchPowChallenge(accessKey, options = {}) {
66
+ const doFetch = options.fetch ?? globalThis.fetch;
67
+ const url = `${(options.baseUrl ?? "https://formgong.com").replace(/\/+$/, "")}/pow?k=${encodeURIComponent(accessKey)}`;
68
+ const response = await doFetch(url, { signal: options.signal });
69
+ if (!response.ok) throw new Error(`Formgong /pow returned HTTP ${response.status}`);
70
+ return (await response.text()).trim();
71
+ }
72
+
73
+ // src/tracker.ts
74
+ var TRIGGERS = ["focusin", "pointerdown", "touchstart", "keydown"];
75
+ function createTracker(target, accessKey, options = {}) {
76
+ const started = Date.now();
77
+ let keys = 0;
78
+ let pastes = 0;
79
+ let typed = 0;
80
+ const seen = /* @__PURE__ */ new Set();
81
+ let pow = "";
82
+ let pending = null;
83
+ const key = () => (typeof accessKey === "function" ? accessKey() : accessKey).trim();
84
+ const warmUp = () => {
85
+ if (pending) return;
86
+ if (!powSupported()) {
87
+ pending = Promise.resolve("na");
88
+ pending.then((v) => {
89
+ pow = v;
90
+ });
91
+ return;
92
+ }
93
+ const current = pending = fetchPowChallenge(key(), { baseUrl: options.baseUrl, fetch: options.fetch }).then((challenge) => solvePow(challenge)).catch(() => "");
94
+ current.then((value) => {
95
+ if (pending === current) pow = value;
96
+ });
97
+ };
98
+ const listeners = [
99
+ ["keydown", () => {
100
+ keys++;
101
+ }],
102
+ ["paste", () => {
103
+ pastes++;
104
+ }],
105
+ ["input", (event) => {
106
+ const name = `$${event.target?.name ?? ""}`;
107
+ if (!seen.has(name)) {
108
+ seen.add(name);
109
+ typed++;
110
+ }
111
+ }],
112
+ ...TRIGGERS.map((type) => [type, warmUp])
113
+ ];
114
+ for (const [type, fn] of listeners) target.addEventListener(type, fn, { passive: true });
115
+ if (options.eager) warmUp();
116
+ return {
117
+ async signals(waitMs = 2e3) {
118
+ let value = pow;
119
+ if (!value && pending) {
120
+ value = await Promise.race([pending, new Promise((resolve) => setTimeout(() => resolve(""), waitMs))]) || "";
121
+ }
122
+ return { _fg_b: `1.${Date.now() - started}.${keys}.${pastes}.${typed}`, _fg_pow: value || "p" };
123
+ },
124
+ warmUp,
125
+ next() {
126
+ pow = "";
127
+ pending = null;
128
+ },
129
+ destroy() {
130
+ for (const [type, fn] of listeners) target.removeEventListener(type, fn);
131
+ }
132
+ };
133
+ }
134
+
135
+ // src/index.ts
136
+ var VERSION = "0.1.0";
137
+ var DEFAULT_BASE_URL = "https://formgong.com";
138
+ var DEFAULT_ENDPOINT = `${DEFAULT_BASE_URL}/submit`;
139
+ var HONEYPOT_FIELDS = ["botcheck", "_honeypot"];
140
+ var LANGS = ["en", "uk", "pl", "tr", "de", "es", "fr", "pt", "ar", "he", "hi", "ja"];
141
+ function baseUrlFromEndpoint(endpoint) {
142
+ if (!endpoint) return DEFAULT_BASE_URL;
143
+ try {
144
+ return new URL(endpoint).origin;
145
+ } catch {
146
+ return DEFAULT_BASE_URL;
147
+ }
148
+ }
149
+ function isFormElement(data) {
150
+ return typeof data === "object" && data !== null && "elements" in data && String(data.tagName).toUpperCase() === "FORM";
151
+ }
152
+ function browserLang() {
153
+ const doc = globalThis.document;
154
+ const lang = doc?.documentElement?.lang?.trim();
155
+ return lang || void 0;
156
+ }
157
+ function flatten(value) {
158
+ if (value === void 0 || value === null) return void 0;
159
+ if (typeof Blob !== "undefined" && value instanceof Blob) return value;
160
+ if (Array.isArray(value)) return value.map(String).join(", ");
161
+ return String(value);
162
+ }
163
+ function toBody(data) {
164
+ if (typeof FormData !== "undefined" && data instanceof FormData) return { fields: /* @__PURE__ */ new Map(), form: data };
165
+ if (isFormElement(data)) return { fields: /* @__PURE__ */ new Map(), form: new FormData(data) };
166
+ const fields = /* @__PURE__ */ new Map();
167
+ if (typeof URLSearchParams !== "undefined" && data instanceof URLSearchParams) {
168
+ for (const [k, v] of data) fields.set(k, fields.has(k) ? `${fields.get(k)}, ${v}` : v);
169
+ return { fields };
170
+ }
171
+ let form;
172
+ for (const [k, raw] of Object.entries(data)) {
173
+ const v = flatten(raw);
174
+ if (v === void 0) continue;
175
+ if (typeof v !== "string") {
176
+ form ?? (form = new FormData());
177
+ form.append(k, v);
178
+ } else fields.set(k, v);
179
+ }
180
+ if (form) {
181
+ for (const [k, v] of fields) form.append(k, v);
182
+ return { fields: /* @__PURE__ */ new Map(), form };
183
+ }
184
+ return { fields };
185
+ }
186
+ function readField(body, name) {
187
+ const value = body.form ? body.form.get(name) : body.fields.get(name);
188
+ return typeof value === "string" ? value : "";
189
+ }
190
+ function setField(body, name, value) {
191
+ if (body.form) body.form.set(name, value);
192
+ else body.fields.set(name, value);
193
+ }
194
+ function honeypotTriggered(data) {
195
+ const body = toBody(data);
196
+ return HONEYPOT_FIELDS.some((name) => readField(body, name).trim() !== "");
197
+ }
198
+ async function submit(accessKey, data, options = {}) {
199
+ const key = typeof accessKey === "string" ? accessKey.trim() : "";
200
+ if (!key) throw new FormgongError("missing_access_key", "Formgong access key is missing. Copy it (fk_\u2026) from https://formgong.com/dashboard.");
201
+ const body = toBody(data);
202
+ if (body.form && data instanceof FormData) {
203
+ const copy = new FormData();
204
+ for (const [k, v] of body.form) copy.append(k, v);
205
+ body.form = copy;
206
+ }
207
+ if (options.honeypot === "drop" && HONEYPOT_FIELDS.some((name) => readField(body, name).trim() !== "")) {
208
+ return { success: true, id: "", message: "", dropped: true };
209
+ }
210
+ setField(body, "access_key", key);
211
+ const lang = options.lang ?? (readField(body, "_lang") || browserLang());
212
+ if (lang) setField(body, "_lang", lang);
213
+ if (options.subject) setField(body, "_subject", options.subject);
214
+ if (options.replyTo) setField(body, "_replyto", options.replyTo);
215
+ if (options.fromName) setField(body, "_from_name", options.fromName);
216
+ if (options.turnstileToken) setField(body, "cf-turnstile-response", options.turnstileToken);
217
+ if (options.tracker) {
218
+ const signals = await options.tracker.signals();
219
+ setField(body, "_fg_b", signals._fg_b);
220
+ setField(body, "_fg_pow", signals._fg_pow);
221
+ }
222
+ const headers = { Accept: "application/json", ...options.headers };
223
+ if (options.origin) headers.Origin = options.origin;
224
+ let payload;
225
+ if (body.form) payload = body.form;
226
+ else {
227
+ headers["Content-Type"] = "application/json";
228
+ payload = JSON.stringify(Object.fromEntries(body.fields));
229
+ }
230
+ const doFetch = options.fetch ?? globalThis.fetch;
231
+ if (typeof doFetch !== "function") throw new FormgongError("network_error", "fetch is not available in this runtime. Pass options.fetch.");
232
+ const timeoutMs = options.timeoutMs ?? 15e3;
233
+ const controller = typeof AbortController !== "undefined" ? new AbortController() : void 0;
234
+ const onAbort = () => controller?.abort(options.signal?.reason);
235
+ if (options.signal) {
236
+ if (options.signal.aborted) throw new FormgongError("aborted", "The submission was aborted.");
237
+ options.signal.addEventListener("abort", onAbort, { once: true });
238
+ }
239
+ let timedOut = false;
240
+ const timer = timeoutMs > 0 && controller ? setTimeout(() => {
241
+ timedOut = true;
242
+ controller.abort();
243
+ }, timeoutMs) : void 0;
244
+ let response;
245
+ try {
246
+ response = await doFetch(options.endpoint ?? DEFAULT_ENDPOINT, { method: "POST", headers, body: payload, signal: controller?.signal });
247
+ } catch (error) {
248
+ if (timedOut) throw new FormgongError("timeout", `Formgong did not answer within ${timeoutMs} ms.`, 0, void 0, { cause: error });
249
+ if (options.signal?.aborted) throw new FormgongError("aborted", "The submission was aborted.", 0, void 0, { cause: error });
250
+ throw new FormgongError("network_error", "Network error. Check your connection and try again.", 0, void 0, { cause: error });
251
+ } finally {
252
+ if (timer) clearTimeout(timer);
253
+ options.signal?.removeEventListener("abort", onAbort);
254
+ }
255
+ let json;
256
+ try {
257
+ json = await response.json();
258
+ } catch {
259
+ json = void 0;
260
+ }
261
+ if (!json || typeof json !== "object") {
262
+ throw new FormgongError("invalid_response", `Unexpected response from Formgong (HTTP ${response.status}).`, response.status);
263
+ }
264
+ if (json.success === true && response.ok) {
265
+ return { ...json, success: true, id: String(json.id ?? ""), message: String(json.message ?? "") };
266
+ }
267
+ const code = typeof json.code === "string" && json.code || (typeof json.error === "string" && /^[a-z_]+$/.test(json.error) ? json.error : "unknown_error");
268
+ const message = typeof json.message === "string" && json.message || `Something went wrong (HTTP ${response.status}). Please try again.`;
269
+ throw new FormgongError(code, message, response.status, json);
270
+ }
271
+ function createClient(accessKey, defaults = {}) {
272
+ return {
273
+ accessKey,
274
+ submit: (data, options) => submit(accessKey, data, { ...defaults, ...options, headers: { ...defaults.headers, ...options?.headers } })
275
+ };
276
+ }
277
+ async function trySubmit(accessKey, data, options) {
278
+ try {
279
+ return { ok: true, result: await submit(accessKey, data, options) };
280
+ } catch (error) {
281
+ if (error instanceof FormgongError) return { ok: false, error };
282
+ return { ok: false, error: new FormgongError("unknown_error", error instanceof Error ? error.message : String(error), 0, void 0, { cause: error }) };
283
+ }
284
+ }
285
+
286
+ exports.DEFAULT_BASE_URL = DEFAULT_BASE_URL;
287
+ exports.DEFAULT_ENDPOINT = DEFAULT_ENDPOINT;
288
+ exports.FormgongError = FormgongError;
289
+ exports.HONEYPOT_FIELDS = HONEYPOT_FIELDS;
290
+ exports.LANGS = LANGS;
291
+ exports.POW_MAX_NONCE = POW_MAX_NONCE;
292
+ exports.VERSION = VERSION;
293
+ exports.baseUrlFromEndpoint = baseUrlFromEndpoint;
294
+ exports.challengeBits = challengeBits;
295
+ exports.createClient = createClient;
296
+ exports.createTracker = createTracker;
297
+ exports.fetchPowChallenge = fetchPowChallenge;
298
+ exports.honeypotTriggered = honeypotTriggered;
299
+ exports.isFormgongError = isFormgongError;
300
+ exports.leadingZeroBits = leadingZeroBits;
301
+ exports.powSupported = powSupported;
302
+ exports.solvePow = solvePow;
303
+ exports.submit = submit;
304
+ exports.trySubmit = trySubmit;
@@ -0,0 +1,165 @@
1
+ /** Stable error codes returned by https://formgong.com/submit, plus client-side codes. */
2
+ type FormgongErrorCode = "missing_access_key" | "unknown_access_key" | "invalid_json" | "unsupported_type" | "files_not_supported" | "too_many_fields" | "too_large" | "origin_not_allowed" | "rate_limited" | "limit_exceeded" | "email_unconfirmed_cap" | "turnstile_missing" | "turnstile_failed" | "turnstile_not_configured" | "uploads_disabled" | "uploads_unverified" | "uploads_unavailable" | "file_unsafe" | "network_error" | "timeout" | "aborted" | "invalid_response" | "invalid_access_key" | "unknown_error" | (string & {});
3
+ /** Error thrown by `submit()` when Formgong rejects a submission or the request fails. */
4
+ declare class FormgongError extends Error {
5
+ readonly name = "FormgongError";
6
+ /** Stable machine-readable code, e.g. `unknown_access_key` or `rate_limited`. */
7
+ readonly code: FormgongErrorCode;
8
+ /** HTTP status (0 for network errors). */
9
+ readonly status: number;
10
+ /** Raw JSON body from Formgong, when there was one. */
11
+ readonly body?: unknown;
12
+ constructor(code: FormgongErrorCode, message: string, status?: number, body?: unknown, options?: {
13
+ cause?: unknown;
14
+ });
15
+ /** True for errors worth retrying later (network trouble, rate limits). */
16
+ get retryable(): boolean;
17
+ }
18
+ declare function isFormgongError(error: unknown): error is FormgongError;
19
+
20
+ type Listener = (event: Event) => void;
21
+ type Target = {
22
+ addEventListener(type: string, fn: Listener, opts?: unknown): void;
23
+ removeEventListener(type: string, fn: Listener, opts?: unknown): void;
24
+ };
25
+ type TrackerOptions = {
26
+ /** Origin of the Formgong API. Default https://formgong.com. */
27
+ baseUrl?: string;
28
+ fetch?: typeof fetch;
29
+ /** Start the proof-of-work right away instead of on first interaction. */
30
+ eager?: boolean;
31
+ };
32
+ type SpamSignals = {
33
+ _fg_b: string;
34
+ _fg_pow: string;
35
+ };
36
+ interface FormgongTracker {
37
+ /** Current signals. Waits up to `waitMs` (default 2000, like fg.js) for the proof-of-work. */
38
+ signals(waitMs?: number): Promise<SpamSignals>;
39
+ /** Start solving now (also happens on focus, pointer, touch or key events). */
40
+ warmUp(): void;
41
+ /** Forget the used proof-of-work after a submission (counters keep running). */
42
+ next(): void;
43
+ /** Remove all listeners. */
44
+ destroy(): void;
45
+ }
46
+ declare function createTracker(target: Target, accessKey: string | (() => string), options?: TrackerOptions): FormgongTracker;
47
+
48
+ /**
49
+ * Proof-of-work used by Formgong's anti-spam (same algorithm as https://formgong.com/fg.js).
50
+ * GET /pow?k=<access_key> returns `1.<ts36>.<rand>.<bits>.<sig>`; the client finds a decimal
51
+ * nonce n so that SHA-256(`${challenge}:${n}`) starts with at least `bits` zero bits.
52
+ * Submitted as `_fg_pow = "<challenge>~<nonce>"`.
53
+ */
54
+ declare const POW_MAX_NONCE = 1000000;
55
+ /** True when Web Crypto is available (browsers on https, Node 18+, Deno, Bun, Workers). */
56
+ declare function powSupported(): boolean;
57
+ declare function leadingZeroBits(bytes: Uint8Array): number;
58
+ /** Difficulty encoded in a challenge (4th dot-separated part). */
59
+ declare function challengeBits(challenge: string): number;
60
+ /**
61
+ * Solve a challenge. Returns `"<challenge>~<nonce>"`, or `"na"` when Web Crypto is missing
62
+ * or no nonce was found below `maxNonce` (the server treats "na" as neutral).
63
+ */
64
+ declare function solvePow(challenge: string, options?: {
65
+ maxNonce?: number;
66
+ signal?: AbortSignal;
67
+ }): Promise<string>;
68
+ /** Fetch a fresh challenge for an access key. */
69
+ declare function fetchPowChallenge(accessKey: string, options?: {
70
+ baseUrl?: string;
71
+ fetch?: typeof fetch;
72
+ signal?: AbortSignal;
73
+ }): Promise<string>;
74
+
75
+ /**
76
+ * @formgong/core: tiny, dependency-free client for https://formgong.com/submit.
77
+ * Works in browsers, Node 18+, Deno, Bun, Cloudflare Workers and other edge runtimes.
78
+ */
79
+
80
+ declare const VERSION = "0.1.0";
81
+ declare const DEFAULT_BASE_URL = "https://formgong.com";
82
+ declare const DEFAULT_ENDPOINT = "https://formgong.com/submit";
83
+ /** Honeypot field names Formgong understands. Keep them empty and hidden from people. */
84
+ declare const HONEYPOT_FIELDS: readonly ["botcheck", "_honeypot"];
85
+ /** Languages for Formgong's messages and autoreplies. */
86
+ declare const LANGS: readonly ["en", "uk", "pl", "tr", "de", "es", "fr", "pt", "ar", "he", "hi", "ja"];
87
+ type FormgongLang = (typeof LANGS)[number];
88
+ type FieldValue = string | number | boolean | null | undefined | Blob | ReadonlyArray<string | number | boolean>;
89
+ /** What you can submit: a plain object, FormData, URLSearchParams or an HTML <form> element. */
90
+ type SubmitData = Record<string, FieldValue> | FormData | URLSearchParams | HTMLFormElementLike;
91
+ type HTMLFormElementLike = {
92
+ tagName: string;
93
+ elements: unknown;
94
+ querySelector?: unknown;
95
+ };
96
+ type SubmitOptions = {
97
+ /** Full submit URL. Default https://formgong.com/submit. */
98
+ endpoint?: string;
99
+ /** Visitor language (en, uk, pl, tr, de, es, fr, pt, ar, he, hi, ja). In browsers defaults to <html lang>. */
100
+ lang?: FormgongLang | (string & {});
101
+ /** Email subject for this submission (`_subject`). */
102
+ subject?: string;
103
+ /** Reply-To address for the notification email (`_replyto`). Defaults to the `email` field server-side. */
104
+ replyTo?: string;
105
+ /** Sender name shown in the notification email (`_from_name`). */
106
+ fromName?: string;
107
+ /** Cloudflare Turnstile token, if the form has Turnstile enabled. */
108
+ turnstileToken?: string;
109
+ /** Browser anti-spam tracker from `createTracker()`. Adds `_fg_b` + `_fg_pow`, exactly like fg.js. */
110
+ tracker?: FormgongTracker;
111
+ /**
112
+ * What to do when a honeypot field (`botcheck`, `_honeypot`) is filled in:
113
+ * "send" (default) lets Formgong file it as spam; "drop" resolves locally without a request.
114
+ */
115
+ honeypot?: "send" | "drop";
116
+ /** Server-side only: Origin to send, for forms restricted to allowed domains. */
117
+ origin?: string;
118
+ headers?: Record<string, string>;
119
+ /** Custom fetch (tests, proxies). Defaults to globalThis.fetch. */
120
+ fetch?: typeof fetch;
121
+ signal?: AbortSignal;
122
+ /** Abort after this many ms. Default 15000. Set 0 to disable. */
123
+ timeoutMs?: number;
124
+ };
125
+ type SubmitResult = {
126
+ success: true;
127
+ /** Submission id ("" when dropped locally by the honeypot). */
128
+ id: string;
129
+ /** Language Formgong used for the visitor. */
130
+ lang?: string;
131
+ /** Localized success message, ready to show. */
132
+ message: string;
133
+ /** True when the honeypot was filled and `honeypot: "drop"` skipped the request. */
134
+ dropped?: boolean;
135
+ [extra: string]: unknown;
136
+ };
137
+ /** Origin of a submit URL, used for /pow: "https://formgong.com/submit" -> "https://formgong.com". */
138
+ declare function baseUrlFromEndpoint(endpoint?: string): string;
139
+ /** True when a honeypot field is filled in, i.e. the sender is most likely a bot. */
140
+ declare function honeypotTriggered(data: SubmitData): boolean;
141
+ /**
142
+ * Send a submission to Formgong. Resolves with the success payload or throws `FormgongError`
143
+ * with a stable `code` (e.g. `unknown_access_key`, `rate_limited`, `turnstile_missing`).
144
+ *
145
+ * ```ts
146
+ * await submit("fk_...", { name: "Ada", email: "ada@example.com", message: "Hi" });
147
+ * ```
148
+ */
149
+ declare function submit(accessKey: string, data: SubmitData, options?: SubmitOptions): Promise<SubmitResult>;
150
+ type FormgongClient = {
151
+ readonly accessKey: string;
152
+ submit(data: SubmitData, options?: SubmitOptions): Promise<SubmitResult>;
153
+ };
154
+ /** Bind an access key and default options once, then call `client.submit(data)`. */
155
+ declare function createClient(accessKey: string, defaults?: SubmitOptions): FormgongClient;
156
+ /** Non-throwing variant: `{ ok: true, result }` or `{ ok: false, error }`. Handy in UI state machines. */
157
+ declare function trySubmit(accessKey: string, data: SubmitData, options?: SubmitOptions): Promise<{
158
+ ok: true;
159
+ result: SubmitResult;
160
+ } | {
161
+ ok: false;
162
+ error: FormgongError;
163
+ }>;
164
+
165
+ export { DEFAULT_BASE_URL, DEFAULT_ENDPOINT, type FieldValue, type FormgongClient, FormgongError, type FormgongErrorCode, type FormgongLang, type FormgongTracker, HONEYPOT_FIELDS, type HTMLFormElementLike, LANGS, POW_MAX_NONCE, type SpamSignals, type SubmitData, type SubmitOptions, type SubmitResult, type TrackerOptions, VERSION, baseUrlFromEndpoint, challengeBits, createClient, createTracker, fetchPowChallenge, honeypotTriggered, isFormgongError, leadingZeroBits, powSupported, solvePow, submit, trySubmit };
@@ -0,0 +1,165 @@
1
+ /** Stable error codes returned by https://formgong.com/submit, plus client-side codes. */
2
+ type FormgongErrorCode = "missing_access_key" | "unknown_access_key" | "invalid_json" | "unsupported_type" | "files_not_supported" | "too_many_fields" | "too_large" | "origin_not_allowed" | "rate_limited" | "limit_exceeded" | "email_unconfirmed_cap" | "turnstile_missing" | "turnstile_failed" | "turnstile_not_configured" | "uploads_disabled" | "uploads_unverified" | "uploads_unavailable" | "file_unsafe" | "network_error" | "timeout" | "aborted" | "invalid_response" | "invalid_access_key" | "unknown_error" | (string & {});
3
+ /** Error thrown by `submit()` when Formgong rejects a submission or the request fails. */
4
+ declare class FormgongError extends Error {
5
+ readonly name = "FormgongError";
6
+ /** Stable machine-readable code, e.g. `unknown_access_key` or `rate_limited`. */
7
+ readonly code: FormgongErrorCode;
8
+ /** HTTP status (0 for network errors). */
9
+ readonly status: number;
10
+ /** Raw JSON body from Formgong, when there was one. */
11
+ readonly body?: unknown;
12
+ constructor(code: FormgongErrorCode, message: string, status?: number, body?: unknown, options?: {
13
+ cause?: unknown;
14
+ });
15
+ /** True for errors worth retrying later (network trouble, rate limits). */
16
+ get retryable(): boolean;
17
+ }
18
+ declare function isFormgongError(error: unknown): error is FormgongError;
19
+
20
+ type Listener = (event: Event) => void;
21
+ type Target = {
22
+ addEventListener(type: string, fn: Listener, opts?: unknown): void;
23
+ removeEventListener(type: string, fn: Listener, opts?: unknown): void;
24
+ };
25
+ type TrackerOptions = {
26
+ /** Origin of the Formgong API. Default https://formgong.com. */
27
+ baseUrl?: string;
28
+ fetch?: typeof fetch;
29
+ /** Start the proof-of-work right away instead of on first interaction. */
30
+ eager?: boolean;
31
+ };
32
+ type SpamSignals = {
33
+ _fg_b: string;
34
+ _fg_pow: string;
35
+ };
36
+ interface FormgongTracker {
37
+ /** Current signals. Waits up to `waitMs` (default 2000, like fg.js) for the proof-of-work. */
38
+ signals(waitMs?: number): Promise<SpamSignals>;
39
+ /** Start solving now (also happens on focus, pointer, touch or key events). */
40
+ warmUp(): void;
41
+ /** Forget the used proof-of-work after a submission (counters keep running). */
42
+ next(): void;
43
+ /** Remove all listeners. */
44
+ destroy(): void;
45
+ }
46
+ declare function createTracker(target: Target, accessKey: string | (() => string), options?: TrackerOptions): FormgongTracker;
47
+
48
+ /**
49
+ * Proof-of-work used by Formgong's anti-spam (same algorithm as https://formgong.com/fg.js).
50
+ * GET /pow?k=<access_key> returns `1.<ts36>.<rand>.<bits>.<sig>`; the client finds a decimal
51
+ * nonce n so that SHA-256(`${challenge}:${n}`) starts with at least `bits` zero bits.
52
+ * Submitted as `_fg_pow = "<challenge>~<nonce>"`.
53
+ */
54
+ declare const POW_MAX_NONCE = 1000000;
55
+ /** True when Web Crypto is available (browsers on https, Node 18+, Deno, Bun, Workers). */
56
+ declare function powSupported(): boolean;
57
+ declare function leadingZeroBits(bytes: Uint8Array): number;
58
+ /** Difficulty encoded in a challenge (4th dot-separated part). */
59
+ declare function challengeBits(challenge: string): number;
60
+ /**
61
+ * Solve a challenge. Returns `"<challenge>~<nonce>"`, or `"na"` when Web Crypto is missing
62
+ * or no nonce was found below `maxNonce` (the server treats "na" as neutral).
63
+ */
64
+ declare function solvePow(challenge: string, options?: {
65
+ maxNonce?: number;
66
+ signal?: AbortSignal;
67
+ }): Promise<string>;
68
+ /** Fetch a fresh challenge for an access key. */
69
+ declare function fetchPowChallenge(accessKey: string, options?: {
70
+ baseUrl?: string;
71
+ fetch?: typeof fetch;
72
+ signal?: AbortSignal;
73
+ }): Promise<string>;
74
+
75
+ /**
76
+ * @formgong/core: tiny, dependency-free client for https://formgong.com/submit.
77
+ * Works in browsers, Node 18+, Deno, Bun, Cloudflare Workers and other edge runtimes.
78
+ */
79
+
80
+ declare const VERSION = "0.1.0";
81
+ declare const DEFAULT_BASE_URL = "https://formgong.com";
82
+ declare const DEFAULT_ENDPOINT = "https://formgong.com/submit";
83
+ /** Honeypot field names Formgong understands. Keep them empty and hidden from people. */
84
+ declare const HONEYPOT_FIELDS: readonly ["botcheck", "_honeypot"];
85
+ /** Languages for Formgong's messages and autoreplies. */
86
+ declare const LANGS: readonly ["en", "uk", "pl", "tr", "de", "es", "fr", "pt", "ar", "he", "hi", "ja"];
87
+ type FormgongLang = (typeof LANGS)[number];
88
+ type FieldValue = string | number | boolean | null | undefined | Blob | ReadonlyArray<string | number | boolean>;
89
+ /** What you can submit: a plain object, FormData, URLSearchParams or an HTML <form> element. */
90
+ type SubmitData = Record<string, FieldValue> | FormData | URLSearchParams | HTMLFormElementLike;
91
+ type HTMLFormElementLike = {
92
+ tagName: string;
93
+ elements: unknown;
94
+ querySelector?: unknown;
95
+ };
96
+ type SubmitOptions = {
97
+ /** Full submit URL. Default https://formgong.com/submit. */
98
+ endpoint?: string;
99
+ /** Visitor language (en, uk, pl, tr, de, es, fr, pt, ar, he, hi, ja). In browsers defaults to <html lang>. */
100
+ lang?: FormgongLang | (string & {});
101
+ /** Email subject for this submission (`_subject`). */
102
+ subject?: string;
103
+ /** Reply-To address for the notification email (`_replyto`). Defaults to the `email` field server-side. */
104
+ replyTo?: string;
105
+ /** Sender name shown in the notification email (`_from_name`). */
106
+ fromName?: string;
107
+ /** Cloudflare Turnstile token, if the form has Turnstile enabled. */
108
+ turnstileToken?: string;
109
+ /** Browser anti-spam tracker from `createTracker()`. Adds `_fg_b` + `_fg_pow`, exactly like fg.js. */
110
+ tracker?: FormgongTracker;
111
+ /**
112
+ * What to do when a honeypot field (`botcheck`, `_honeypot`) is filled in:
113
+ * "send" (default) lets Formgong file it as spam; "drop" resolves locally without a request.
114
+ */
115
+ honeypot?: "send" | "drop";
116
+ /** Server-side only: Origin to send, for forms restricted to allowed domains. */
117
+ origin?: string;
118
+ headers?: Record<string, string>;
119
+ /** Custom fetch (tests, proxies). Defaults to globalThis.fetch. */
120
+ fetch?: typeof fetch;
121
+ signal?: AbortSignal;
122
+ /** Abort after this many ms. Default 15000. Set 0 to disable. */
123
+ timeoutMs?: number;
124
+ };
125
+ type SubmitResult = {
126
+ success: true;
127
+ /** Submission id ("" when dropped locally by the honeypot). */
128
+ id: string;
129
+ /** Language Formgong used for the visitor. */
130
+ lang?: string;
131
+ /** Localized success message, ready to show. */
132
+ message: string;
133
+ /** True when the honeypot was filled and `honeypot: "drop"` skipped the request. */
134
+ dropped?: boolean;
135
+ [extra: string]: unknown;
136
+ };
137
+ /** Origin of a submit URL, used for /pow: "https://formgong.com/submit" -> "https://formgong.com". */
138
+ declare function baseUrlFromEndpoint(endpoint?: string): string;
139
+ /** True when a honeypot field is filled in, i.e. the sender is most likely a bot. */
140
+ declare function honeypotTriggered(data: SubmitData): boolean;
141
+ /**
142
+ * Send a submission to Formgong. Resolves with the success payload or throws `FormgongError`
143
+ * with a stable `code` (e.g. `unknown_access_key`, `rate_limited`, `turnstile_missing`).
144
+ *
145
+ * ```ts
146
+ * await submit("fk_...", { name: "Ada", email: "ada@example.com", message: "Hi" });
147
+ * ```
148
+ */
149
+ declare function submit(accessKey: string, data: SubmitData, options?: SubmitOptions): Promise<SubmitResult>;
150
+ type FormgongClient = {
151
+ readonly accessKey: string;
152
+ submit(data: SubmitData, options?: SubmitOptions): Promise<SubmitResult>;
153
+ };
154
+ /** Bind an access key and default options once, then call `client.submit(data)`. */
155
+ declare function createClient(accessKey: string, defaults?: SubmitOptions): FormgongClient;
156
+ /** Non-throwing variant: `{ ok: true, result }` or `{ ok: false, error }`. Handy in UI state machines. */
157
+ declare function trySubmit(accessKey: string, data: SubmitData, options?: SubmitOptions): Promise<{
158
+ ok: true;
159
+ result: SubmitResult;
160
+ } | {
161
+ ok: false;
162
+ error: FormgongError;
163
+ }>;
164
+
165
+ export { DEFAULT_BASE_URL, DEFAULT_ENDPOINT, type FieldValue, type FormgongClient, FormgongError, type FormgongErrorCode, type FormgongLang, type FormgongTracker, HONEYPOT_FIELDS, type HTMLFormElementLike, LANGS, POW_MAX_NONCE, type SpamSignals, type SubmitData, type SubmitOptions, type SubmitResult, type TrackerOptions, VERSION, baseUrlFromEndpoint, challengeBits, createClient, createTracker, fetchPowChallenge, honeypotTriggered, isFormgongError, leadingZeroBits, powSupported, solvePow, submit, trySubmit };