@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.js ADDED
@@ -0,0 +1,284 @@
1
+ // src/errors.ts
2
+ var FormgongError = class extends Error {
3
+ constructor(code, message, status = 0, body, options) {
4
+ super(message);
5
+ this.name = "FormgongError";
6
+ this.code = code;
7
+ this.status = status;
8
+ this.body = body;
9
+ if (options && "cause" in options) this.cause = options.cause;
10
+ }
11
+ /** True for errors worth retrying later (network trouble, rate limits). */
12
+ get retryable() {
13
+ return this.code === "network_error" || this.code === "timeout" || this.code === "rate_limited" || this.status >= 500;
14
+ }
15
+ };
16
+ function isFormgongError(error) {
17
+ return error instanceof FormgongError || typeof error === "object" && error !== null && error.name === "FormgongError" && typeof error.code === "string";
18
+ }
19
+
20
+ // src/pow.ts
21
+ var BATCH = 128;
22
+ var POW_MAX_NONCE = 1e6;
23
+ function subtle() {
24
+ const c = globalThis.crypto;
25
+ return c && c.subtle ? c.subtle : void 0;
26
+ }
27
+ function powSupported() {
28
+ return subtle() !== void 0;
29
+ }
30
+ function leadingZeroBits(bytes) {
31
+ let bits = 0;
32
+ for (const byte of bytes) {
33
+ if (byte === 0) {
34
+ bits += 8;
35
+ continue;
36
+ }
37
+ return bits + Math.clz32(byte) - 24;
38
+ }
39
+ return bits;
40
+ }
41
+ function challengeBits(challenge) {
42
+ const bits = Number(challenge.split(".")[3]);
43
+ if (!Number.isInteger(bits) || bits < 1 || bits > 32) throw new Error("Invalid Formgong proof-of-work challenge");
44
+ return bits;
45
+ }
46
+ async function solvePow(challenge, options = {}) {
47
+ const api = subtle();
48
+ if (!api) return "na";
49
+ const bits = challengeBits(challenge);
50
+ const max = options.maxNonce ?? POW_MAX_NONCE;
51
+ const encoder = new TextEncoder();
52
+ for (let n = 0; n < max; n += BATCH) {
53
+ if (options.signal?.aborted) throw options.signal.reason ?? new Error("aborted");
54
+ const batch = [];
55
+ for (let j = 0; j < BATCH; j++) batch.push(api.digest("SHA-256", encoder.encode(`${challenge}:${n + j}`)));
56
+ const hashes = await Promise.all(batch);
57
+ for (let j = 0; j < BATCH; j++) {
58
+ if (leadingZeroBits(new Uint8Array(hashes[j])) >= bits) return `${challenge}~${n + j}`;
59
+ }
60
+ }
61
+ return "na";
62
+ }
63
+ async function fetchPowChallenge(accessKey, options = {}) {
64
+ const doFetch = options.fetch ?? globalThis.fetch;
65
+ const url = `${(options.baseUrl ?? "https://formgong.com").replace(/\/+$/, "")}/pow?k=${encodeURIComponent(accessKey)}`;
66
+ const response = await doFetch(url, { signal: options.signal });
67
+ if (!response.ok) throw new Error(`Formgong /pow returned HTTP ${response.status}`);
68
+ return (await response.text()).trim();
69
+ }
70
+
71
+ // src/tracker.ts
72
+ var TRIGGERS = ["focusin", "pointerdown", "touchstart", "keydown"];
73
+ function createTracker(target, accessKey, options = {}) {
74
+ const started = Date.now();
75
+ let keys = 0;
76
+ let pastes = 0;
77
+ let typed = 0;
78
+ const seen = /* @__PURE__ */ new Set();
79
+ let pow = "";
80
+ let pending = null;
81
+ const key = () => (typeof accessKey === "function" ? accessKey() : accessKey).trim();
82
+ const warmUp = () => {
83
+ if (pending) return;
84
+ if (!powSupported()) {
85
+ pending = Promise.resolve("na");
86
+ pending.then((v) => {
87
+ pow = v;
88
+ });
89
+ return;
90
+ }
91
+ const current = pending = fetchPowChallenge(key(), { baseUrl: options.baseUrl, fetch: options.fetch }).then((challenge) => solvePow(challenge)).catch(() => "");
92
+ current.then((value) => {
93
+ if (pending === current) pow = value;
94
+ });
95
+ };
96
+ const listeners = [
97
+ ["keydown", () => {
98
+ keys++;
99
+ }],
100
+ ["paste", () => {
101
+ pastes++;
102
+ }],
103
+ ["input", (event) => {
104
+ const name = `$${event.target?.name ?? ""}`;
105
+ if (!seen.has(name)) {
106
+ seen.add(name);
107
+ typed++;
108
+ }
109
+ }],
110
+ ...TRIGGERS.map((type) => [type, warmUp])
111
+ ];
112
+ for (const [type, fn] of listeners) target.addEventListener(type, fn, { passive: true });
113
+ if (options.eager) warmUp();
114
+ return {
115
+ async signals(waitMs = 2e3) {
116
+ let value = pow;
117
+ if (!value && pending) {
118
+ value = await Promise.race([pending, new Promise((resolve) => setTimeout(() => resolve(""), waitMs))]) || "";
119
+ }
120
+ return { _fg_b: `1.${Date.now() - started}.${keys}.${pastes}.${typed}`, _fg_pow: value || "p" };
121
+ },
122
+ warmUp,
123
+ next() {
124
+ pow = "";
125
+ pending = null;
126
+ },
127
+ destroy() {
128
+ for (const [type, fn] of listeners) target.removeEventListener(type, fn);
129
+ }
130
+ };
131
+ }
132
+
133
+ // src/index.ts
134
+ var VERSION = "0.1.0";
135
+ var DEFAULT_BASE_URL = "https://formgong.com";
136
+ var DEFAULT_ENDPOINT = `${DEFAULT_BASE_URL}/submit`;
137
+ var HONEYPOT_FIELDS = ["botcheck", "_honeypot"];
138
+ var LANGS = ["en", "uk", "pl", "tr", "de", "es", "fr", "pt", "ar", "he", "hi", "ja"];
139
+ function baseUrlFromEndpoint(endpoint) {
140
+ if (!endpoint) return DEFAULT_BASE_URL;
141
+ try {
142
+ return new URL(endpoint).origin;
143
+ } catch {
144
+ return DEFAULT_BASE_URL;
145
+ }
146
+ }
147
+ function isFormElement(data) {
148
+ return typeof data === "object" && data !== null && "elements" in data && String(data.tagName).toUpperCase() === "FORM";
149
+ }
150
+ function browserLang() {
151
+ const doc = globalThis.document;
152
+ const lang = doc?.documentElement?.lang?.trim();
153
+ return lang || void 0;
154
+ }
155
+ function flatten(value) {
156
+ if (value === void 0 || value === null) return void 0;
157
+ if (typeof Blob !== "undefined" && value instanceof Blob) return value;
158
+ if (Array.isArray(value)) return value.map(String).join(", ");
159
+ return String(value);
160
+ }
161
+ function toBody(data) {
162
+ if (typeof FormData !== "undefined" && data instanceof FormData) return { fields: /* @__PURE__ */ new Map(), form: data };
163
+ if (isFormElement(data)) return { fields: /* @__PURE__ */ new Map(), form: new FormData(data) };
164
+ const fields = /* @__PURE__ */ new Map();
165
+ if (typeof URLSearchParams !== "undefined" && data instanceof URLSearchParams) {
166
+ for (const [k, v] of data) fields.set(k, fields.has(k) ? `${fields.get(k)}, ${v}` : v);
167
+ return { fields };
168
+ }
169
+ let form;
170
+ for (const [k, raw] of Object.entries(data)) {
171
+ const v = flatten(raw);
172
+ if (v === void 0) continue;
173
+ if (typeof v !== "string") {
174
+ form ?? (form = new FormData());
175
+ form.append(k, v);
176
+ } else fields.set(k, v);
177
+ }
178
+ if (form) {
179
+ for (const [k, v] of fields) form.append(k, v);
180
+ return { fields: /* @__PURE__ */ new Map(), form };
181
+ }
182
+ return { fields };
183
+ }
184
+ function readField(body, name) {
185
+ const value = body.form ? body.form.get(name) : body.fields.get(name);
186
+ return typeof value === "string" ? value : "";
187
+ }
188
+ function setField(body, name, value) {
189
+ if (body.form) body.form.set(name, value);
190
+ else body.fields.set(name, value);
191
+ }
192
+ function honeypotTriggered(data) {
193
+ const body = toBody(data);
194
+ return HONEYPOT_FIELDS.some((name) => readField(body, name).trim() !== "");
195
+ }
196
+ async function submit(accessKey, data, options = {}) {
197
+ const key = typeof accessKey === "string" ? accessKey.trim() : "";
198
+ if (!key) throw new FormgongError("missing_access_key", "Formgong access key is missing. Copy it (fk_\u2026) from https://formgong.com/dashboard.");
199
+ const body = toBody(data);
200
+ if (body.form && data instanceof FormData) {
201
+ const copy = new FormData();
202
+ for (const [k, v] of body.form) copy.append(k, v);
203
+ body.form = copy;
204
+ }
205
+ if (options.honeypot === "drop" && HONEYPOT_FIELDS.some((name) => readField(body, name).trim() !== "")) {
206
+ return { success: true, id: "", message: "", dropped: true };
207
+ }
208
+ setField(body, "access_key", key);
209
+ const lang = options.lang ?? (readField(body, "_lang") || browserLang());
210
+ if (lang) setField(body, "_lang", lang);
211
+ if (options.subject) setField(body, "_subject", options.subject);
212
+ if (options.replyTo) setField(body, "_replyto", options.replyTo);
213
+ if (options.fromName) setField(body, "_from_name", options.fromName);
214
+ if (options.turnstileToken) setField(body, "cf-turnstile-response", options.turnstileToken);
215
+ if (options.tracker) {
216
+ const signals = await options.tracker.signals();
217
+ setField(body, "_fg_b", signals._fg_b);
218
+ setField(body, "_fg_pow", signals._fg_pow);
219
+ }
220
+ const headers = { Accept: "application/json", ...options.headers };
221
+ if (options.origin) headers.Origin = options.origin;
222
+ let payload;
223
+ if (body.form) payload = body.form;
224
+ else {
225
+ headers["Content-Type"] = "application/json";
226
+ payload = JSON.stringify(Object.fromEntries(body.fields));
227
+ }
228
+ const doFetch = options.fetch ?? globalThis.fetch;
229
+ if (typeof doFetch !== "function") throw new FormgongError("network_error", "fetch is not available in this runtime. Pass options.fetch.");
230
+ const timeoutMs = options.timeoutMs ?? 15e3;
231
+ const controller = typeof AbortController !== "undefined" ? new AbortController() : void 0;
232
+ const onAbort = () => controller?.abort(options.signal?.reason);
233
+ if (options.signal) {
234
+ if (options.signal.aborted) throw new FormgongError("aborted", "The submission was aborted.");
235
+ options.signal.addEventListener("abort", onAbort, { once: true });
236
+ }
237
+ let timedOut = false;
238
+ const timer = timeoutMs > 0 && controller ? setTimeout(() => {
239
+ timedOut = true;
240
+ controller.abort();
241
+ }, timeoutMs) : void 0;
242
+ let response;
243
+ try {
244
+ response = await doFetch(options.endpoint ?? DEFAULT_ENDPOINT, { method: "POST", headers, body: payload, signal: controller?.signal });
245
+ } catch (error) {
246
+ if (timedOut) throw new FormgongError("timeout", `Formgong did not answer within ${timeoutMs} ms.`, 0, void 0, { cause: error });
247
+ if (options.signal?.aborted) throw new FormgongError("aborted", "The submission was aborted.", 0, void 0, { cause: error });
248
+ throw new FormgongError("network_error", "Network error. Check your connection and try again.", 0, void 0, { cause: error });
249
+ } finally {
250
+ if (timer) clearTimeout(timer);
251
+ options.signal?.removeEventListener("abort", onAbort);
252
+ }
253
+ let json;
254
+ try {
255
+ json = await response.json();
256
+ } catch {
257
+ json = void 0;
258
+ }
259
+ if (!json || typeof json !== "object") {
260
+ throw new FormgongError("invalid_response", `Unexpected response from Formgong (HTTP ${response.status}).`, response.status);
261
+ }
262
+ if (json.success === true && response.ok) {
263
+ return { ...json, success: true, id: String(json.id ?? ""), message: String(json.message ?? "") };
264
+ }
265
+ const code = typeof json.code === "string" && json.code || (typeof json.error === "string" && /^[a-z_]+$/.test(json.error) ? json.error : "unknown_error");
266
+ const message = typeof json.message === "string" && json.message || `Something went wrong (HTTP ${response.status}). Please try again.`;
267
+ throw new FormgongError(code, message, response.status, json);
268
+ }
269
+ function createClient(accessKey, defaults = {}) {
270
+ return {
271
+ accessKey,
272
+ submit: (data, options) => submit(accessKey, data, { ...defaults, ...options, headers: { ...defaults.headers, ...options?.headers } })
273
+ };
274
+ }
275
+ async function trySubmit(accessKey, data, options) {
276
+ try {
277
+ return { ok: true, result: await submit(accessKey, data, options) };
278
+ } catch (error) {
279
+ if (error instanceof FormgongError) return { ok: false, error };
280
+ return { ok: false, error: new FormgongError("unknown_error", error instanceof Error ? error.message : String(error), 0, void 0, { cause: error }) };
281
+ }
282
+ }
283
+
284
+ export { DEFAULT_BASE_URL, DEFAULT_ENDPOINT, FormgongError, HONEYPOT_FIELDS, LANGS, POW_MAX_NONCE, VERSION, baseUrlFromEndpoint, challengeBits, createClient, createTracker, fetchPowChallenge, honeypotTriggered, isFormgongError, leadingZeroBits, powSupported, solvePow, submit, trySubmit };
package/package.json ADDED
@@ -0,0 +1,95 @@
1
+ {
2
+ "name": "@formgong/core",
3
+ "version": "0.1.0",
4
+ "description": "Tiny, typed, zero-dependency client for Formgong, the form backend for contact forms: submissions go to email, Telegram and webhooks. Browser, Node, Deno, Bun and edge. A Formspree / Web3Forms alternative.",
5
+ "type": "module",
6
+ "main": "./dist/index.cjs",
7
+ "module": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "import": {
12
+ "types": "./dist/index.d.ts",
13
+ "default": "./dist/index.js"
14
+ },
15
+ "require": {
16
+ "types": "./dist/index.d.cts",
17
+ "default": "./dist/index.cjs"
18
+ }
19
+ },
20
+ "./api": {
21
+ "import": {
22
+ "types": "./dist/api.d.ts",
23
+ "default": "./dist/api.js"
24
+ },
25
+ "require": {
26
+ "types": "./dist/api.d.cts",
27
+ "default": "./dist/api.cjs"
28
+ }
29
+ },
30
+ "./package.json": "./package.json"
31
+ },
32
+ "files": [
33
+ "dist",
34
+ "README.md",
35
+ "LICENSE"
36
+ ],
37
+ "sideEffects": false,
38
+ "keywords": [
39
+ "formgong",
40
+ "form-backend",
41
+ "form backend",
42
+ "contact-form",
43
+ "contact form",
44
+ "forms",
45
+ "form-submission",
46
+ "formspree-alternative",
47
+ "formspree alternative",
48
+ "web3forms-alternative",
49
+ "web3forms alternative",
50
+ "getform-alternative",
51
+ "telegram",
52
+ "email",
53
+ "webhooks",
54
+ "gdpr",
55
+ "spam-protection",
56
+ "honeypot",
57
+ "serverless",
58
+ "edge",
59
+ "cloudflare-workers",
60
+ "nextjs",
61
+ "react",
62
+ "vue",
63
+ "svelte",
64
+ "astro",
65
+ "lovable",
66
+ "bolt",
67
+ "v0",
68
+ "static-site",
69
+ "no-backend",
70
+ "typescript"
71
+ ],
72
+ "author": "Formgong <support@formgong.com>",
73
+ "license": "MIT",
74
+ "homepage": "https://formgong.com/en/docs/",
75
+ "repository": {
76
+ "type": "git",
77
+ "url": "git+https://github.com/formgong/js.git",
78
+ "directory": "packages/core"
79
+ },
80
+ "bugs": {
81
+ "url": "https://github.com/formgong/js/issues",
82
+ "email": "support@formgong.com"
83
+ },
84
+ "engines": {
85
+ "node": ">=18.17"
86
+ },
87
+ "publishConfig": {
88
+ "access": "public"
89
+ },
90
+ "scripts": {
91
+ "build": "tsup",
92
+ "typecheck": "tsc --noEmit",
93
+ "test": "vitest run"
94
+ }
95
+ }