@heedeo/sdk 0.0.0-stage → 0.1.0-pilot.5

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 Heedeo
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 CHANGED
@@ -1,3 +1,146 @@
1
- # Temporary Holding Version
1
+ # Heedeo package quickstart
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Pilot package for Node.js 20.18+, Next.js App Router, and Cloudflare Workers with `nodejs_compat`. It handles browser loading, same-domain forwarding, event requests, timeouts and one retry. Heedeo returns signals; your app still owns signup and authentication.
4
+
5
+ ## 1. Install
6
+
7
+ ```sh
8
+ npm install @heedeo/sdk
9
+ ```
10
+
11
+ The package is published on npm as `@heedeo/sdk`. It has no runtime dependencies.
12
+
13
+ Get your keys at https://app.heedeo.com/review/sign-up. Save the secret in your server's environment settings, including your deployed environment. Never put it in a `NEXT_PUBLIC_` variable.
14
+
15
+ ```sh
16
+ HEEDEO_SECRET_KEY=sk_your_secret_key
17
+ NEXT_PUBLIC_HEEDEO_KEY=pk_your_publishable_key
18
+ ```
19
+
20
+ ## 2. Configure the server once
21
+
22
+ ```ts
23
+ // lib/heedeo.ts — import only from server files
24
+ import { Heedeo } from '@heedeo/sdk';
25
+ import { trustedClientIp } from './trusted-client-ip';
26
+
27
+ export const heedeo = new Heedeo({
28
+ secretKey: process.env.HEEDEO_SECRET_KEY,
29
+ clientIp: trustedClientIp,
30
+ });
31
+ ```
32
+
33
+ `trustedClientIp(request)` is the one hosting-specific piece. It must return the real visitor's IP from a source your server trusts, or `null` when unavailable. Use the same function for the proxy and signup. The package deliberately does not guess whether an incoming forwarded header is trustworthy.
34
+
35
+ For local testing only:
36
+
37
+ ```ts
38
+ // lib/trusted-client-ip.ts
39
+ export function trustedClientIp(_request: Request): string | null {
40
+ if (process.env.NODE_ENV === 'development') return '127.0.0.1';
41
+ return null; // Configure your host's trusted IP source before deploying.
42
+ }
43
+ ```
44
+
45
+ For a Cloudflare-proxied app, `cf-connecting-ip` is an option only when your origin rejects requests that bypass that trusted proxy. Do not assume that a public Railway origin is protected just because the custom domain uses Cloudflare. Have your coding assistant inspect the actual deployment and configure this function. A missing IP returns a setup error; it does not silently group all production visitors under localhost.
46
+
47
+ ## 3. Add one route
48
+
49
+ ```ts
50
+ // app/hd/[...path]/route.ts
51
+ import { heedeo } from '../../../lib/heedeo';
52
+
53
+ export const runtime = 'nodejs';
54
+ export const GET = heedeo.proxy;
55
+ export const POST = heedeo.proxy;
56
+ ```
57
+
58
+ This assumes `lib` is at the project root, as in the runnable example. Keep `/hd/i.js` and `/hd/v1/identify` reachable before sign-in. Existing authentication middleware must allow those two paths. Only these endpoints are forwarded; this route cannot forward event submissions or arbitrary URLs. Cookies and request headers unrelated to Heedeo are not sent upstream.
59
+
60
+ ## 4. Identify just before signup
61
+
62
+ ```ts
63
+ // lib/heedeo-browser.ts — safe to import in a client component
64
+ import { createHeedeo } from '@heedeo/sdk/browser';
65
+
66
+ export const heedeo = createHeedeo({
67
+ publishableKey: process.env.NEXT_PUBLIC_HEEDEO_KEY,
68
+ });
69
+ ```
70
+
71
+ In your existing submit handler:
72
+
73
+ ```ts
74
+ const { data } = await heedeo.identify();
75
+ await signup({ email, heedeoToken: data?.token });
76
+ ```
77
+
78
+ Keep your existing `signup` function and its validation, loading state and error handling. The package loads the script once, waits for it, and returns a new receipt for each call. No script tag or global type declaration is needed. Identification happens at the action, not on every page load. If identification fails, `data` is `null` and `error` explains the problem; continue signup without signals. Do not mix the package with an existing Heedeo script tag.
79
+
80
+ ## 5. Record the event on your server
81
+
82
+ In the existing signup route, after validating the submitted fields:
83
+
84
+ ```ts
85
+ const { data, error } = await heedeo.event({
86
+ request,
87
+ token: input.heedeoToken,
88
+ action: 'signup',
89
+ email: input.email,
90
+ });
91
+
92
+ if (data) console.info('Heedeo event', data.event_id);
93
+ if (error) console.warn('Heedeo setup', error.code);
94
+ // Continue your existing signup. Observe only during the pilot.
95
+ ```
96
+
97
+ `request` is the original Web Request received by a Next.js route handler; it preserves the actual URL, method and headers. The call does not read or consume its body. Route handlers are the supported Next.js path for this first package release. Keep an existing server-action integration on the manual guide until an adapter has been tested; do not invent a request URL or replace authentication to use the package.
98
+
99
+ The SDK generates a request ID once and reuses the same body on its one retry. If your application retries the entire action, provide its stable ID as `requestId`. A new user action needs a new identification and ID. Do not send two events with the same receipt to attach a user ID later.
100
+
101
+ ## Check that it works
102
+
103
+ Run a test signup and check the server result: an `event_id` and a non-null `visitor` confirm a usable identification. `flag: false` is normal; an empty flags screen is not evidence of failure. Check that signup still completes with the script blocked or Heedeo unavailable. Never expose the full signals response or internal reasons to an end user.
104
+
105
+ Use HTTPS for deployed testing, including Safari's secure-cookie behavior. Review the privacy wording in https://app.heedeo.com/docs#7-what-heedeo-never-does before going live.
106
+
107
+ ## Options and errors
108
+
109
+ Server options: `secretKey`, required `clientIp(request)`, optional `path` (default `/hd`), `timeoutMs` (default 3000 total across event retries), `baseUrl` (default `https://app.heedeo.com`), and `fetch` for testing. Custom origins require HTTPS, except localhost. Browser options: `publishableKey`, matching `path`, and `timeoutMs` (default 3000 total for script loading and identification).
110
+
111
+ Configuration mistakes throw when you construct the client, so missing keys are caught at setup. Operational failures return `{ data: null, error: { code, message, status? } }`; checking `error` narrows `data` to the success value. `code` is a `HeedeoErrorCode`, so a `switch` over it is checked by TypeScript:
112
+
113
+ - Server: `missing_token`, `missing_client_ip`, `invalid_key`, `api_error`, `invalid_response`, `network_error`, `timeout_or_aborted`, `configuration_error`.
114
+ - Browser: `browser_required`, `timeout`, `invalid_response`, `identification_unavailable`.
115
+
116
+ Neither entry point logs credentials, request bodies or upstream error bodies.
117
+
118
+ Browser timeouts stop waiting, but cannot cancel an already-running collector call in this pilot version. Always pass the returned token explicitly; never fall back to an older cookie token after a timeout. Browser results are not security decisions. Secret keys and event signals stay on your server.
119
+
120
+ ## Pilot boundaries
121
+
122
+ This package is an ESM package (use `import`) for Node.js servers. The browser entry is separate and imports no server code. The server entry supports Node.js and Cloudflare Workers with `nodejs_compat`. Other edge runtimes have not been verified. No change to your hosting, database or sign-in provider is required. React hooks, server-action adapters, Express-specific wrappers and an automatic installer are not included in this release.
123
+
124
+ ## Cloudflare Workers
125
+
126
+ Enable `nodejs_compat` in Wrangler. Create the client inside the request handler so keys come from Worker secrets:
127
+
128
+ ```ts
129
+ import { Heedeo } from '@heedeo/sdk';
130
+
131
+ export default {
132
+ async fetch(request, env) {
133
+ const heedeo = new Heedeo({
134
+ secretKey: env.HEEDEO_SECRET_KEY,
135
+ clientIp: request => request.headers.get('cf-connecting-ip'),
136
+ });
137
+ if (new URL(request.url).pathname.startsWith('/hd/')) {
138
+ return heedeo.proxy(request);
139
+ }
140
+ // In your signup handler, use heedeo.event() as above.
141
+ return env.ASSETS.fetch(request);
142
+ },
143
+ };
144
+ ```
145
+
146
+ This IP resolver is for a Worker receiving requests through Cloudflare, not an unprotected origin. If you use static assets, set `assets.run_worker_first` for `/hd/*` and your signup route. Store `HEEDEO_SECRET_KEY` with `wrangler secret put`; only the publishable key belongs in the browser.
@@ -0,0 +1,10 @@
1
+ import { type Identification, type Result } from "./shared.js";
2
+ export type { HeedeoError, HeedeoErrorCode, Identification, Result } from "./shared.js";
3
+ /** Create once per app. Calling this function alone makes no identification request. */
4
+ export declare function createHeedeo(options: {
5
+ publishableKey: string | undefined;
6
+ path?: string;
7
+ timeoutMs?: number;
8
+ }): {
9
+ identify(): Promise<Result<Identification>>;
10
+ };
@@ -0,0 +1,77 @@
1
+ import { failure, isIdentification, pathPrefix, timeout, } from "./shared.js";
2
+ let loading;
3
+ function load(url, timeoutMs) {
4
+ if (loading) {
5
+ return loading.url === url
6
+ ? loading.promise
7
+ : Promise.reject(new Error("conflicting_configuration"));
8
+ }
9
+ const promise = new Promise((resolve, reject) => {
10
+ if (window.heedeo) {
11
+ reject(new Error("existing_collector"));
12
+ return;
13
+ }
14
+ const script = document.createElement("script");
15
+ script.src = url;
16
+ script.async = true;
17
+ const timer = setTimeout(() => finish(false), timeoutMs);
18
+ function finish(ok) {
19
+ clearTimeout(timer);
20
+ script.onload = null;
21
+ script.onerror = null;
22
+ if (ok && window.heedeo)
23
+ resolve();
24
+ else {
25
+ script.remove();
26
+ reject(new Error("script_unavailable"));
27
+ }
28
+ }
29
+ script.onload = () => finish(true);
30
+ script.onerror = () => finish(false);
31
+ document.head.append(script);
32
+ });
33
+ loading = { url, promise };
34
+ void promise.catch(() => {
35
+ if (loading?.promise === promise)
36
+ loading = undefined;
37
+ });
38
+ return promise;
39
+ }
40
+ /** Create once per app. Calling this function alone makes no identification request. */
41
+ export function createHeedeo(options) {
42
+ if (!options.publishableKey?.startsWith("pk_"))
43
+ throw new Error("Use a Heedeo publishable key in the browser.");
44
+ const publishableKey = options.publishableKey;
45
+ const path = pathPrefix(options.path ?? "/hd");
46
+ const budget = timeout(options.timeoutMs ?? 3000);
47
+ return {
48
+ async identify() {
49
+ if (typeof window === "undefined")
50
+ return failure("browser_required", "Call identify in a browser action handler.");
51
+ let timer;
52
+ const deadline = new Promise((resolve) => {
53
+ timer = setTimeout(() => resolve(failure("timeout", "Identification timed out. Continue without signals.")), budget);
54
+ });
55
+ const identify = async () => {
56
+ try {
57
+ const url = new URL(`${path}/i.js`, window.location.origin);
58
+ url.searchParams.set("key", publishableKey);
59
+ await load(url.href, budget);
60
+ const data = await window.heedeo?.identify();
61
+ return isIdentification(data)
62
+ ? { data, error: null }
63
+ : failure("invalid_response", "Identification returned an unexpected response.");
64
+ }
65
+ catch {
66
+ return failure("identification_unavailable", "Check the public key and proxy route. Continue signup without signals.");
67
+ }
68
+ };
69
+ try {
70
+ return await Promise.race([identify(), deadline]);
71
+ }
72
+ finally {
73
+ clearTimeout(timer);
74
+ }
75
+ },
76
+ };
77
+ }
@@ -0,0 +1,55 @@
1
+ type Counts = {
2
+ "24h": number;
3
+ "7d": number;
4
+ all: number;
5
+ };
6
+ export type EventData = {
7
+ event_id: string;
8
+ flag: boolean;
9
+ reasons: {
10
+ code: string;
11
+ text: string;
12
+ }[];
13
+ visitor: {
14
+ id: string;
15
+ confidence: number;
16
+ first_seen: string;
17
+ last_seen: string;
18
+ emails: Counts;
19
+ accounts: Counts;
20
+ } | null;
21
+ counts: {
22
+ "24h": number;
23
+ "7d": number;
24
+ };
25
+ listed: "allow" | "block" | null;
26
+ activity: {
27
+ last_hour: number;
28
+ hourly_norm: number;
29
+ burst: boolean;
30
+ };
31
+ email: {
32
+ disposable: boolean;
33
+ alias_of_existing: boolean;
34
+ pattern: boolean;
35
+ } | null;
36
+ network: {
37
+ datacenter: boolean;
38
+ vpn: boolean | null;
39
+ proxy: boolean | null;
40
+ tor: boolean;
41
+ private_relay: boolean;
42
+ anonymous: boolean | null;
43
+ network_type: string | null;
44
+ asn: string | null;
45
+ };
46
+ agent: {
47
+ operator: string | null;
48
+ verified: boolean;
49
+ declared: string | null;
50
+ operator_network: string | null;
51
+ automation: string | null;
52
+ } | null;
53
+ };
54
+ export declare function isEventData(value: unknown): value is EventData;
55
+ export {};
@@ -0,0 +1,59 @@
1
+ const object = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
2
+ const number = (value) => typeof value === "number" && Number.isFinite(value);
3
+ const string = (value) => typeof value === "string";
4
+ const boolean = (value) => typeof value === "boolean";
5
+ const nullable = (check) => (value) => value === null || check(value);
6
+ const counts = (value) => object(value) && number(value["24h"]) && number(value["7d"]);
7
+ export function isEventData(value) {
8
+ if (!object(value) ||
9
+ !string(value.event_id) ||
10
+ !boolean(value.flag) ||
11
+ !counts(value.counts) ||
12
+ (value.listed !== null && value.listed !== "allow" && value.listed !== "block") ||
13
+ !Array.isArray(value.reasons) ||
14
+ !value.reasons.every((reason) => object(reason) && string(reason.code) && string(reason.text)))
15
+ return false;
16
+ if (value.visitor !== null) {
17
+ const visitor = value.visitor;
18
+ if (!object(visitor) ||
19
+ !string(visitor.id) ||
20
+ !number(visitor.confidence) ||
21
+ !string(visitor.first_seen) ||
22
+ !string(visitor.last_seen) ||
23
+ !object(visitor.emails) ||
24
+ !counts(visitor.emails) ||
25
+ !number(visitor.emails.all) ||
26
+ !object(visitor.accounts) ||
27
+ !counts(visitor.accounts) ||
28
+ !number(visitor.accounts.all))
29
+ return false;
30
+ }
31
+ const activity = value.activity;
32
+ const network = value.network;
33
+ if (!object(activity) ||
34
+ !number(activity.last_hour) ||
35
+ !number(activity.hourly_norm) ||
36
+ !boolean(activity.burst) ||
37
+ !object(network) ||
38
+ !boolean(network.datacenter) ||
39
+ !boolean(network.tor) ||
40
+ !boolean(network.private_relay) ||
41
+ ![network.vpn, network.proxy, network.anonymous].every(nullable(boolean)) ||
42
+ ![network.network_type, network.asn].every(nullable(string)))
43
+ return false;
44
+ if (value.email !== null &&
45
+ (!object(value.email) ||
46
+ ![value.email.disposable, value.email.alias_of_existing, value.email.pattern].every(boolean)))
47
+ return false;
48
+ if (value.agent !== null &&
49
+ (!object(value.agent) ||
50
+ !boolean(value.agent.verified) ||
51
+ ![
52
+ value.agent.operator,
53
+ value.agent.declared,
54
+ value.agent.operator_network,
55
+ value.agent.automation,
56
+ ].every(nullable(string))))
57
+ return false;
58
+ return true;
59
+ }
@@ -0,0 +1,31 @@
1
+ import { type EventData } from "./response.js";
2
+ export type { EventData } from "./response.js";
3
+ import { type Result } from "./shared.js";
4
+ export type { HeedeoError, HeedeoErrorCode, Result } from "./shared.js";
5
+ export type HeedeoOptions = {
6
+ secretKey: string | undefined;
7
+ /** Resolve only an IP supplied by your trusted hosting layer. Used for BOTH requests. */
8
+ clientIp: (request: Request) => string | null;
9
+ baseUrl?: string;
10
+ path?: string;
11
+ /** Total event budget, including the retry. Default: 3000 ms. */
12
+ timeoutMs?: number;
13
+ fetch?: typeof fetch;
14
+ };
15
+ export type EventInput = {
16
+ request: Request;
17
+ token?: string | null;
18
+ action: string;
19
+ email?: string;
20
+ userId?: string;
21
+ /** Reuse across application-level retries of the same logical action. */
22
+ requestId?: string;
23
+ };
24
+ export declare class Heedeo {
25
+ #private;
26
+ constructor(options: HeedeoOptions);
27
+ /** Signals only. Errors are values; this method never decides whether signup is allowed. */
28
+ event: (input: EventInput) => Promise<Result<EventData>>;
29
+ /** Mount at /hd/[...path]. Only the public script and identification endpoint are forwarded. */
30
+ proxy: (request: Request) => Promise<Response>;
31
+ }
package/dist/server.js ADDED
@@ -0,0 +1,218 @@
1
+ // Node's built-in import also prevents accidentally bundling this entry into browser code.
2
+ import { isIP } from "node:net";
3
+ import { isEventData } from "./response.js";
4
+ import { failure, pathPrefix, timeout } from "./shared.js";
5
+ function origin(value) {
6
+ const url = new URL(value);
7
+ const local = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
8
+ if ((url.protocol !== "https:" && !(local && url.protocol === "http:")) ||
9
+ url.username ||
10
+ url.password ||
11
+ url.search ||
12
+ url.hash ||
13
+ url.pathname !== "/") {
14
+ throw new Error("Heedeo baseUrl must be an HTTPS origin (HTTP is allowed only on localhost).");
15
+ }
16
+ return url.origin;
17
+ }
18
+ // Send just the request context used for signals and signed-agent verification, never app secrets.
19
+ const EVENT_HEADERS = [
20
+ "user-agent",
21
+ "accept-language",
22
+ "signature",
23
+ "signature-input",
24
+ "signature-agent",
25
+ "content-digest",
26
+ "sec-ch-ua",
27
+ "sec-ch-ua-platform",
28
+ "sec-ch-ua-mobile",
29
+ ];
30
+ class PayloadTooLarge extends Error {
31
+ }
32
+ async function limitedBody(request, signal) {
33
+ const reader = request.body?.getReader();
34
+ if (!reader)
35
+ return new Uint8Array();
36
+ const chunks = [];
37
+ let size = 0;
38
+ const abort = () => {
39
+ void reader.cancel().catch(() => { });
40
+ };
41
+ signal.addEventListener("abort", abort, { once: true });
42
+ try {
43
+ while (true) {
44
+ signal.throwIfAborted();
45
+ const { done, value } = await reader.read();
46
+ signal.throwIfAborted();
47
+ if (done)
48
+ break;
49
+ size += value.byteLength;
50
+ if (size > 65536)
51
+ throw new PayloadTooLarge();
52
+ chunks.push(value);
53
+ }
54
+ const body = new Uint8Array(size);
55
+ let offset = 0;
56
+ for (const chunk of chunks) {
57
+ body.set(chunk, offset);
58
+ offset += chunk.byteLength;
59
+ }
60
+ return body;
61
+ }
62
+ finally {
63
+ signal.removeEventListener("abort", abort);
64
+ await reader.cancel().catch(() => { });
65
+ reader.releaseLock();
66
+ }
67
+ }
68
+ export class Heedeo {
69
+ #key;
70
+ #origin;
71
+ #path;
72
+ #timeout;
73
+ #fetch;
74
+ #clientIp;
75
+ constructor(options) {
76
+ if (!options.secretKey?.startsWith("sk_")) {
77
+ throw new Error("Set HEEDEO_SECRET_KEY on your server. Never use a publishable key here.");
78
+ }
79
+ this.#key = options.secretKey;
80
+ this.#origin = origin(options.baseUrl ?? "https://app.heedeo.com");
81
+ this.#path = pathPrefix(options.path ?? "/hd");
82
+ this.#timeout = timeout(options.timeoutMs ?? 3000);
83
+ // Workers requires the global receiver; do not call native fetch as a class method.
84
+ const send = options.fetch ?? globalThis.fetch.bind(globalThis);
85
+ this.#fetch = (input, init) => send(input, init);
86
+ this.#clientIp = options.clientIp;
87
+ }
88
+ #ip(request) {
89
+ const value = this.#clientIp(request);
90
+ const normalized = value?.replace(/^::ffff:/, "").trim();
91
+ return normalized && isIP(normalized) ? normalized : null;
92
+ }
93
+ /** Signals only. Errors are values; this method never decides whether signup is allowed. */
94
+ event = async (input) => {
95
+ if (!input.token)
96
+ return failure("missing_token", "Identification was unavailable. Continue without signals.");
97
+ try {
98
+ const ip = this.#ip(input.request);
99
+ if (!ip)
100
+ return failure("missing_client_ip", "Configure clientIp for your trusted hosting layer.");
101
+ const url = new URL(input.request.url);
102
+ const headers = {
103
+ host: url.host,
104
+ ":method": input.request.method,
105
+ ":path": url.pathname + url.search,
106
+ };
107
+ for (const name of EVENT_HEADERS) {
108
+ const value = input.request.headers.get(name);
109
+ if (value !== null)
110
+ headers[name] = value;
111
+ }
112
+ const body = JSON.stringify({
113
+ token: input.token,
114
+ action: input.action,
115
+ email: input.email,
116
+ user_id: input.userId,
117
+ client_ip: ip,
118
+ headers,
119
+ request_id: input.requestId ?? crypto.randomUUID(),
120
+ });
121
+ const signal = AbortSignal.any([AbortSignal.timeout(this.#timeout), input.request.signal]);
122
+ for (let attempt = 0; attempt < 2; attempt++) {
123
+ try {
124
+ const response = await this.#fetch(`${this.#origin}/v1/events`, {
125
+ method: "POST",
126
+ redirect: "manual",
127
+ signal,
128
+ headers: { authorization: `Bearer ${this.#key}`, "content-type": "application/json" },
129
+ body,
130
+ });
131
+ if (response.status >= 500 && attempt === 0 && !signal.aborted) {
132
+ await response.body?.cancel();
133
+ continue;
134
+ }
135
+ if (!response.ok) {
136
+ // Do not reflect response bodies: upstream errors can contain sensitive input.
137
+ const code = response.status === 401 || response.status === 403 ? "invalid_key" : "api_error";
138
+ return failure(code, "Heedeo could not record this event. Check the server configuration.", response.status);
139
+ }
140
+ const data = await response.json();
141
+ if (!isEventData(data)) {
142
+ return failure("invalid_response", "Heedeo returned an unexpected response.");
143
+ }
144
+ return { data, error: null };
145
+ }
146
+ catch {
147
+ if (signal.aborted)
148
+ return failure("timeout_or_aborted", "Heedeo did not finish within the request budget.");
149
+ if (attempt === 1)
150
+ return failure("network_error", "Heedeo is unavailable. Continue without signals.");
151
+ }
152
+ }
153
+ }
154
+ catch {
155
+ return failure("configuration_error", "Check the Heedeo request and clientIp configuration.");
156
+ }
157
+ return failure("network_error", "Heedeo is unavailable. Continue without signals.");
158
+ };
159
+ /** Mount at /hd/[...path]. Only the public script and identification endpoint are forwarded. */
160
+ proxy = async (request) => {
161
+ const url = new URL(request.url);
162
+ const script = url.pathname === `${this.#path}/i.js` && request.method === "GET";
163
+ const identify = url.pathname === `${this.#path}/v1/identify` && request.method === "POST";
164
+ if (!script && !identify)
165
+ return new Response("Not found", { status: 404 });
166
+ try {
167
+ const ip = this.#ip(request);
168
+ if (!ip)
169
+ return new Response("Heedeo clientIp is not configured", { status: 503 });
170
+ const target = new URL(script ? "/i.js" : "/v1/identify", this.#origin);
171
+ const key = url.searchParams.get("key");
172
+ if (!key?.startsWith("pk_"))
173
+ return new Response("A publishable key is required", { status: 400 });
174
+ target.searchParams.set("key", key);
175
+ const headers = new Headers({ "x-heedeo-client-ip": ip });
176
+ for (const name of ["user-agent", "accept-language", "content-type"]) {
177
+ const value = request.headers.get(name);
178
+ if (value)
179
+ headers.set(name, value);
180
+ }
181
+ const cookie = request.headers
182
+ .get("cookie")
183
+ ?.split(";")
184
+ .map((v) => v.trim())
185
+ .find((v) => v.startsWith("_idd="));
186
+ if (cookie)
187
+ headers.set("cookie", cookie);
188
+ const signal = AbortSignal.any([AbortSignal.timeout(this.#timeout), request.signal]);
189
+ const body = identify ? await limitedBody(request, signal) : undefined;
190
+ const response = await this.#fetch(target, {
191
+ method: request.method,
192
+ headers,
193
+ body,
194
+ signal,
195
+ redirect: "manual",
196
+ });
197
+ if (response.status >= 300 && response.status < 400) {
198
+ await response.body?.cancel();
199
+ throw new Error("Unexpected upstream redirect");
200
+ }
201
+ const outgoing = new Headers({ "cache-control": "no-store" });
202
+ const type = response.headers.get("content-type");
203
+ if (type)
204
+ outgoing.set("content-type", type);
205
+ for (const value of response.headers.getSetCookie())
206
+ outgoing.append("set-cookie", value);
207
+ return new Response(response.body, { status: response.status, headers: outgoing });
208
+ }
209
+ catch (error) {
210
+ if (error instanceof PayloadTooLarge)
211
+ return new Response("Payload too large", { status: 413 });
212
+ return new Response("Heedeo is unavailable", {
213
+ status: 502,
214
+ headers: { "cache-control": "no-store" },
215
+ });
216
+ }
217
+ };
218
+ }
@@ -0,0 +1,22 @@
1
+ export type HeedeoErrorCode = "missing_token" | "missing_client_ip" | "invalid_key" | "api_error" | "invalid_response" | "network_error" | "timeout_or_aborted" | "configuration_error" | "browser_required" | "timeout" | "identification_unavailable";
2
+ export type HeedeoError = {
3
+ code: HeedeoErrorCode;
4
+ message: string;
5
+ status?: number;
6
+ };
7
+ export type Result<T> = {
8
+ data: T;
9
+ error: null;
10
+ } | {
11
+ data: null;
12
+ error: HeedeoError;
13
+ };
14
+ export declare function failure(code: HeedeoErrorCode, message: string, status?: number): Result<never>;
15
+ export declare function timeout(value: number): number;
16
+ export declare function pathPrefix(value: string): string;
17
+ export type Identification = {
18
+ token: string;
19
+ visitor_id: string;
20
+ confidence: number;
21
+ };
22
+ export declare function isIdentification(value: unknown): value is Identification;
package/dist/shared.js ADDED
@@ -0,0 +1,24 @@
1
+ export function failure(code, message, status) {
2
+ return { data: null, error: { code, message, ...(status === undefined ? {} : { status }) } };
3
+ }
4
+ export function timeout(value) {
5
+ if (!Number.isInteger(value) || value < 1 || value > 30_000) {
6
+ throw new Error("Heedeo timeoutMs must be an integer between 1 and 30000.");
7
+ }
8
+ return value;
9
+ }
10
+ export function pathPrefix(value) {
11
+ if (!/^\/[a-zA-Z0-9_-]+(?:\/[a-zA-Z0-9_-]+)*$/.test(value)) {
12
+ throw new Error("Heedeo path must be a local prefix such as /hd.");
13
+ }
14
+ return value;
15
+ }
16
+ export function isIdentification(value) {
17
+ if (!value || typeof value !== "object")
18
+ return false;
19
+ const id = value;
20
+ return (typeof id.token === "string" &&
21
+ id.token.length > 0 &&
22
+ typeof id.visitor_id === "string" &&
23
+ typeof id.confidence === "number");
24
+ }
package/package.json CHANGED
@@ -1,6 +1,42 @@
1
1
  {
2
2
  "name": "@heedeo/sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0-pilot.5",
4
+ "description": "Browser identification and server-side signup signals for Heedeo",
5
+ "type": "module",
6
+ "engines": {
7
+ "node": ">=20.18"
8
+ },
9
+ "files": [
10
+ "dist",
11
+ "README.md",
12
+ "LICENSE"
13
+ ],
14
+ "exports": {
15
+ ".": {
16
+ "types": "./dist/server.d.ts",
17
+ "import": "./dist/server.js"
18
+ },
19
+ "./browser": {
20
+ "types": "./dist/browser.d.ts",
21
+ "import": "./dist/browser.js"
22
+ }
23
+ },
24
+ "scripts": {
25
+ "build": "tsc",
26
+ "test": "npm run build && node --test test/*.test.mjs",
27
+ "prepack": "npm run build",
28
+ "lint": "biome check ."
29
+ },
30
+ "devDependencies": {
31
+ "@biomejs/biome": "2.5.15",
32
+ "@types/node": "24.19.2",
33
+ "typescript": "7.0.2"
34
+ },
35
+ "publishConfig": {
36
+ "access": "public",
37
+ "registry": "https://registry.npmjs.org/",
38
+ "tag": "latest"
39
+ },
40
+ "homepage": "https://app.heedeo.com/docs/sdk",
41
+ "license": "MIT"
42
+ }