kwiklink-sdk-web 0.0.0-stage → 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,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,90 @@
1
- # Temporary Holding Version
1
+ # Kwiklink Web SDK
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
+ Resolves a Kwiklink short link's deep-link data on the page it sends visitors to, and tracks a Lead/Conversion funnel per link — all client-side, no backend integration required on your end.
4
+
5
+ ## Requirements
6
+
7
+ Any modern browser (`fetch`, `localStorage`). No framework dependency — works with a plain `<script>` tag or as an ES module/CommonJS import.
8
+
9
+ ## Installation
10
+
11
+ ```
12
+ npm install kwiklink-sdk-web
13
+ ```
14
+
15
+ or, without a build step:
16
+
17
+ ```html
18
+ <script src="https://unpkg.com/kwiklink-sdk-web/dist/index.global.js"></script>
19
+ ```
20
+
21
+ which exposes a global `Kwiklink` object with the same API as the module import below.
22
+
23
+ ## How the SDK talks to Kwiklink
24
+
25
+ Networking is entirely SDK-managed — you never configure an endpoint, only an API key. Every call goes to Kwiklink's own SDK-facing domain, not your short-link domain.
26
+
27
+ ## 1. Get a web API key
28
+
29
+ From your app's **API Keys** tab, click **New web key** — not the regular "Generate key" button. A web key is restricted server-side to only this SDK's resolve/tracking calls; it cannot create, read, or modify your links or account data, because it ships in plain, readable JavaScript to every visitor's browser rather than living inside a compiled app. You can optionally restrict it to specific domains when creating it — recommended for production.
30
+
31
+ ## 2. Initialize
32
+
33
+ ```js
34
+ import Kwiklink from "kwiklink-sdk-web";
35
+
36
+ Kwiklink.init({ apiKey: "dlweb_live_..." });
37
+ ```
38
+
39
+ Call this once, before anything else, as early as your page's own script runs.
40
+
41
+ ## 3. Resolve on page load
42
+
43
+ ```js
44
+ const result = await Kwiklink.resolveLink();
45
+ if (result.matched) {
46
+ console.log(result.linkId, result.linkData);
47
+ }
48
+ ```
49
+
50
+ Unlike a mobile app, a browser never lands on the short link's own page — it's already been redirected to wherever your link points before any SDK code runs. So this call is always a match attempt against the click that brought the visitor here: an exact match if the page's URL still carries Kwiklink's own continuity parameter (the normal case, right after following a link), or a best-effort IP+platform match otherwise (see **Data this SDK sends** below for what "best-effort" means here).
51
+
52
+ On a match, Kwiklink records a **Lead** for that link — once per device per link, so calling this on every page load for a returning visitor doesn't inflate the count — and this SDK remembers which link resolved, so a later `trackConversion()` call doesn't need to repeat it.
53
+
54
+ ## 4. Track a conversion
55
+
56
+ ```js
57
+ // after a signup form succeeds
58
+ await Kwiklink.trackConversion("signup");
59
+
60
+ // or with a value
61
+ await Kwiklink.trackConversion("purchase", { value: 49.99, metadata: { plan: "pro" } });
62
+ ```
63
+
64
+ `eventName` is whatever you want to call it — `"signup"` and `"purchase"` are just examples, not fixed options. Attributed to whichever link `resolveLink()` last matched on this device. If `resolveLink()` was never called, or never matched, there's nothing to attribute to and this resolves to `{ recorded: false }` with a console warning, rather than silently failing.
65
+
66
+ ## Reading the result
67
+
68
+ | Field | Type | Meaning |
69
+ |---|---|---|
70
+ | `matched` | `boolean` | Whether this device/click matched a real Kwiklink link |
71
+ | `linkId` | `string?` | The matched link's id |
72
+ | `linkData` | `object?` | Whatever custom data was attached to the link (campaign params, deep-link payload, etc.) |
73
+
74
+ ## Data this SDK sends
75
+
76
+ - **A device id**: a random UUID generated on first call and stored in `localStorage` — this identifies a **browser profile**, not a person. A different browser on the same device, or an incognito/private session, is a different id every time; clearing site data resets it. This is a known limitation shared by every attribution SDK that works this way (Branch, AppsFlyer, GA included) — not something unique to Kwiklink, and not solvable without resorting to fingerprinting, which this SDK deliberately does not do (fingerprinting is both increasingly blocked by browsers and a consent/privacy-law concern if used for tracking). If this device/browser was already counted this month under your plan's MAU limit, repeat visits don't count again.
77
+ - **The matched click's data** (link id, your own `linkData`) — only ever returned to your own page, never sent anywhere else by this SDK.
78
+ - **The fallback match** (when there's no continuity parameter on the page) uses your IP address and detected platform, hashed server-side, purely to look up a recent click — best-effort, not guaranteed, since there's no reliable deferred-attribution channel on the web the way an app store's install-referrer API provides for mobile.
79
+
80
+ ## Error handling
81
+
82
+ Every method throws on a genuine failure (network error, invalid API key, bad input) rather than swallowing it — wrap calls in `try`/`catch` if you want to handle failures explicitly. `trackConversion()` is the one exception: calling it with nothing to attribute to resolves normally (`{ recorded: false }`) rather than throwing, since that's a usage/sequencing issue, not a request failure.
83
+
84
+ ## Module layout
85
+
86
+ ```
87
+ kwiklink-sdk-web/
88
+ ├── src/ # TypeScript source
89
+ └── dist/ # built output (ESM, CJS, and a global IIFE build for <script> tags)
90
+ ```
package/dist/index.cjs ADDED
@@ -0,0 +1,175 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ default: () => index_default,
24
+ init: () => init,
25
+ resolveLink: () => resolveLink,
26
+ trackConversion: () => trackConversion
27
+ });
28
+ module.exports = __toCommonJS(index_exports);
29
+
30
+ // src/deviceId.ts
31
+ var STORAGE_KEY = "__kwiklink_device_id";
32
+ function generateId() {
33
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
34
+ return crypto.randomUUID();
35
+ }
36
+ const bytes = new Uint8Array(16);
37
+ if (typeof crypto !== "undefined" && typeof crypto.getRandomValues === "function") {
38
+ crypto.getRandomValues(bytes);
39
+ } else {
40
+ for (let i = 0; i < bytes.length; i++) bytes[i] = Math.floor(Math.random() * 256);
41
+ }
42
+ bytes[6] = bytes[6] & 15 | 64;
43
+ bytes[8] = bytes[8] & 63 | 128;
44
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
45
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
46
+ }
47
+ function getDeviceId() {
48
+ try {
49
+ const existing = localStorage.getItem(STORAGE_KEY);
50
+ if (existing) return existing;
51
+ const id = generateId();
52
+ localStorage.setItem(STORAGE_KEY, id);
53
+ return id;
54
+ } catch {
55
+ return null;
56
+ }
57
+ }
58
+ var LEAD_CONTEXT_KEY = "__kwiklink_lead_context";
59
+ function setLeadContext(linkId) {
60
+ try {
61
+ localStorage.setItem(LEAD_CONTEXT_KEY, linkId);
62
+ } catch {
63
+ }
64
+ }
65
+ function getLeadContext() {
66
+ try {
67
+ return localStorage.getItem(LEAD_CONTEXT_KEY);
68
+ } catch {
69
+ return null;
70
+ }
71
+ }
72
+
73
+ // src/net.ts
74
+ var API_HOST = "https://orbit-in1.kwiklink.io";
75
+ var KwiklinkRequestError = class extends Error {
76
+ constructor(message, status) {
77
+ super(message);
78
+ this.status = status;
79
+ this.name = "KwiklinkRequestError";
80
+ }
81
+ };
82
+ async function post(path, apiKey, body, extraHeaders = {}) {
83
+ let response;
84
+ try {
85
+ response = await fetch(`${API_HOST}${path}`, {
86
+ method: "POST",
87
+ headers: {
88
+ "Content-Type": "application/json",
89
+ "X-Api-Key": apiKey,
90
+ ...extraHeaders
91
+ },
92
+ body: JSON.stringify(body)
93
+ });
94
+ } catch (err) {
95
+ throw new KwiklinkRequestError(`network error calling ${path}: ${err.message}`);
96
+ }
97
+ let data = null;
98
+ try {
99
+ data = await response.json();
100
+ } catch {
101
+ }
102
+ if (!response.ok) {
103
+ const message = data?.error ?? `request to ${path} failed with status ${response.status}`;
104
+ throw new KwiklinkRequestError(message, response.status);
105
+ }
106
+ return data;
107
+ }
108
+
109
+ // src/index.ts
110
+ var CLICK_ID_PARAM = "__kw_cid";
111
+ var config = null;
112
+ function requireInit() {
113
+ if (!config) {
114
+ throw new Error("Kwiklink.init({ apiKey }) must be called before any other Kwiklink method.");
115
+ }
116
+ return config;
117
+ }
118
+ function consumeClickIdFromUrl() {
119
+ if (typeof window === "undefined") return void 0;
120
+ const url = new URL(window.location.href);
121
+ const clickId = url.searchParams.get(CLICK_ID_PARAM);
122
+ if (!clickId) return void 0;
123
+ url.searchParams.delete(CLICK_ID_PARAM);
124
+ window.history.replaceState(window.history.state, "", url.toString());
125
+ return clickId;
126
+ }
127
+ function init(cfg) {
128
+ if (!cfg?.apiKey) {
129
+ throw new Error("Kwiklink.init() requires { apiKey }.");
130
+ }
131
+ config = cfg;
132
+ }
133
+ function deviceHeaders() {
134
+ const deviceId = getDeviceId();
135
+ if (!deviceId) return {};
136
+ return { "X-Kwiklink-Device-Id": deviceId, "X-Kwiklink-Device-Id-Source": "web_storage" };
137
+ }
138
+ async function resolveLink() {
139
+ const { apiKey } = requireInit();
140
+ const clickId = consumeClickIdFromUrl();
141
+ const result = await post("/web/v1/links/resolve", apiKey, { clickId }, deviceHeaders());
142
+ if (result.matched && result.linkId) {
143
+ setLeadContext(result.linkId);
144
+ }
145
+ return result;
146
+ }
147
+ async function trackConversion(eventName, options = {}) {
148
+ const { apiKey } = requireInit();
149
+ const linkId = getLeadContext();
150
+ if (!linkId) {
151
+ console.warn(
152
+ "[Kwiklink] trackConversion() called with no prior resolveLink() match on this device \u2014 nothing recorded. Call resolveLink() on page load first."
153
+ );
154
+ return { recorded: false };
155
+ }
156
+ const headers = deviceHeaders();
157
+ if (!headers["X-Kwiklink-Device-Id"]) {
158
+ console.warn("[Kwiklink] trackConversion() couldn't read/create a device id (storage unavailable) \u2014 nothing recorded.");
159
+ return { recorded: false };
160
+ }
161
+ return post(
162
+ "/web/v1/events/conversion",
163
+ apiKey,
164
+ { linkId, eventName, value: options.value, metadata: options.metadata },
165
+ headers
166
+ );
167
+ }
168
+ var Kwiklink = { init, resolveLink, trackConversion };
169
+ var index_default = Kwiklink;
170
+ // Annotate the CommonJS export names for ESM import in node:
171
+ 0 && (module.exports = {
172
+ init,
173
+ resolveLink,
174
+ trackConversion
175
+ });
@@ -0,0 +1,60 @@
1
+ interface KwiklinkConfig {
2
+ /**
3
+ * A "web" key created from your app's API Keys tab — NOT a standard key.
4
+ * A standard key grants full link management access and is never safe to
5
+ * ship into a browser; a web key is restricted server-side to only the
6
+ * resolve/tracking calls this SDK makes. See the README's "API key" section.
7
+ */
8
+ apiKey: string;
9
+ }
10
+ interface LinkData {
11
+ [key: string]: unknown;
12
+ }
13
+ interface AttributionResult {
14
+ matched: boolean;
15
+ linkId?: string;
16
+ linkData?: LinkData;
17
+ }
18
+ interface TrackConversionOptions {
19
+ value?: number;
20
+ metadata?: Record<string, unknown>;
21
+ }
22
+ interface ConversionResult {
23
+ recorded: boolean;
24
+ }
25
+
26
+ /** Call once, before resolveLink()/trackConversion(). See README for where to get a web API key. */
27
+ declare function init(cfg: KwiklinkConfig): void;
28
+ /**
29
+ * Call on page load. Unlike the Android SDK, there's no "warm" open case —
30
+ * a browser never lands on the short link's own page, it's already been
31
+ * redirected server-side to this destination — so this is always a
32
+ * deferred-style match: an exact clickId lookup when the current URL still
33
+ * carries __kw_cid (the common case, right after following a Kwiklink
34
+ * link), falling back server-side to a best-effort IP+platform fingerprint
35
+ * otherwise (e.g. this page was reached some other way, or the link was
36
+ * followed a while ago and this is a later page load). The fingerprint
37
+ * fallback is best-effort only — see the README.
38
+ *
39
+ * On a match, the backend records a Lead (deduped — calling this
40
+ * repeatedly for the same returning visitor only counts once) and this SDK
41
+ * remembers linkId locally so a later trackConversion() call knows what to
42
+ * attribute to without you having to pass it again.
43
+ */
44
+ declare function resolveLink(): Promise<AttributionResult>;
45
+ /**
46
+ * Records a named conversion — trackConversion('signup'),
47
+ * trackConversion('purchase', { value: 49.99 }), anything you define.
48
+ * Attributed to whichever link resolveLink() last resolved on this device
49
+ * (last-touch); if resolveLink() was never called, or found no match,
50
+ * there's nothing to attribute to and this resolves to
51
+ * { recorded: false } without making a network call.
52
+ */
53
+ declare function trackConversion(eventName: string, options?: TrackConversionOptions): Promise<ConversionResult>;
54
+ declare const Kwiklink: {
55
+ init: typeof init;
56
+ resolveLink: typeof resolveLink;
57
+ trackConversion: typeof trackConversion;
58
+ };
59
+
60
+ export { type AttributionResult, type ConversionResult, type KwiklinkConfig, type LinkData, type TrackConversionOptions, Kwiklink as default, init, resolveLink, trackConversion };
@@ -0,0 +1,60 @@
1
+ interface KwiklinkConfig {
2
+ /**
3
+ * A "web" key created from your app's API Keys tab — NOT a standard key.
4
+ * A standard key grants full link management access and is never safe to
5
+ * ship into a browser; a web key is restricted server-side to only the
6
+ * resolve/tracking calls this SDK makes. See the README's "API key" section.
7
+ */
8
+ apiKey: string;
9
+ }
10
+ interface LinkData {
11
+ [key: string]: unknown;
12
+ }
13
+ interface AttributionResult {
14
+ matched: boolean;
15
+ linkId?: string;
16
+ linkData?: LinkData;
17
+ }
18
+ interface TrackConversionOptions {
19
+ value?: number;
20
+ metadata?: Record<string, unknown>;
21
+ }
22
+ interface ConversionResult {
23
+ recorded: boolean;
24
+ }
25
+
26
+ /** Call once, before resolveLink()/trackConversion(). See README for where to get a web API key. */
27
+ declare function init(cfg: KwiklinkConfig): void;
28
+ /**
29
+ * Call on page load. Unlike the Android SDK, there's no "warm" open case —
30
+ * a browser never lands on the short link's own page, it's already been
31
+ * redirected server-side to this destination — so this is always a
32
+ * deferred-style match: an exact clickId lookup when the current URL still
33
+ * carries __kw_cid (the common case, right after following a Kwiklink
34
+ * link), falling back server-side to a best-effort IP+platform fingerprint
35
+ * otherwise (e.g. this page was reached some other way, or the link was
36
+ * followed a while ago and this is a later page load). The fingerprint
37
+ * fallback is best-effort only — see the README.
38
+ *
39
+ * On a match, the backend records a Lead (deduped — calling this
40
+ * repeatedly for the same returning visitor only counts once) and this SDK
41
+ * remembers linkId locally so a later trackConversion() call knows what to
42
+ * attribute to without you having to pass it again.
43
+ */
44
+ declare function resolveLink(): Promise<AttributionResult>;
45
+ /**
46
+ * Records a named conversion — trackConversion('signup'),
47
+ * trackConversion('purchase', { value: 49.99 }), anything you define.
48
+ * Attributed to whichever link resolveLink() last resolved on this device
49
+ * (last-touch); if resolveLink() was never called, or found no match,
50
+ * there's nothing to attribute to and this resolves to
51
+ * { recorded: false } without making a network call.
52
+ */
53
+ declare function trackConversion(eventName: string, options?: TrackConversionOptions): Promise<ConversionResult>;
54
+ declare const Kwiklink: {
55
+ init: typeof init;
56
+ resolveLink: typeof resolveLink;
57
+ trackConversion: typeof trackConversion;
58
+ };
59
+
60
+ export { type AttributionResult, type ConversionResult, type KwiklinkConfig, type LinkData, type TrackConversionOptions, Kwiklink as default, init, resolveLink, trackConversion };
@@ -0,0 +1,171 @@
1
+ "use strict";
2
+ var Kwiklink = (() => {
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+
21
+ // src/index.ts
22
+ var index_exports = {};
23
+ __export(index_exports, {
24
+ default: () => index_default,
25
+ init: () => init,
26
+ resolveLink: () => resolveLink,
27
+ trackConversion: () => trackConversion
28
+ });
29
+
30
+ // src/deviceId.ts
31
+ var STORAGE_KEY = "__kwiklink_device_id";
32
+ function generateId() {
33
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
34
+ return crypto.randomUUID();
35
+ }
36
+ const bytes = new Uint8Array(16);
37
+ if (typeof crypto !== "undefined" && typeof crypto.getRandomValues === "function") {
38
+ crypto.getRandomValues(bytes);
39
+ } else {
40
+ for (let i = 0; i < bytes.length; i++) bytes[i] = Math.floor(Math.random() * 256);
41
+ }
42
+ bytes[6] = bytes[6] & 15 | 64;
43
+ bytes[8] = bytes[8] & 63 | 128;
44
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
45
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
46
+ }
47
+ function getDeviceId() {
48
+ try {
49
+ const existing = localStorage.getItem(STORAGE_KEY);
50
+ if (existing) return existing;
51
+ const id = generateId();
52
+ localStorage.setItem(STORAGE_KEY, id);
53
+ return id;
54
+ } catch {
55
+ return null;
56
+ }
57
+ }
58
+ var LEAD_CONTEXT_KEY = "__kwiklink_lead_context";
59
+ function setLeadContext(linkId) {
60
+ try {
61
+ localStorage.setItem(LEAD_CONTEXT_KEY, linkId);
62
+ } catch {
63
+ }
64
+ }
65
+ function getLeadContext() {
66
+ try {
67
+ return localStorage.getItem(LEAD_CONTEXT_KEY);
68
+ } catch {
69
+ return null;
70
+ }
71
+ }
72
+
73
+ // src/net.ts
74
+ var API_HOST = "https://orbit-in1.kwiklink.io";
75
+ var KwiklinkRequestError = class extends Error {
76
+ constructor(message, status) {
77
+ super(message);
78
+ this.status = status;
79
+ this.name = "KwiklinkRequestError";
80
+ }
81
+ };
82
+ async function post(path, apiKey, body, extraHeaders = {}) {
83
+ let response;
84
+ try {
85
+ response = await fetch(`${API_HOST}${path}`, {
86
+ method: "POST",
87
+ headers: {
88
+ "Content-Type": "application/json",
89
+ "X-Api-Key": apiKey,
90
+ ...extraHeaders
91
+ },
92
+ body: JSON.stringify(body)
93
+ });
94
+ } catch (err) {
95
+ throw new KwiklinkRequestError(`network error calling ${path}: ${err.message}`);
96
+ }
97
+ let data = null;
98
+ try {
99
+ data = await response.json();
100
+ } catch {
101
+ }
102
+ if (!response.ok) {
103
+ const message = data?.error ?? `request to ${path} failed with status ${response.status}`;
104
+ throw new KwiklinkRequestError(message, response.status);
105
+ }
106
+ return data;
107
+ }
108
+
109
+ // src/index.ts
110
+ var CLICK_ID_PARAM = "__kw_cid";
111
+ var config = null;
112
+ function requireInit() {
113
+ if (!config) {
114
+ throw new Error("Kwiklink.init({ apiKey }) must be called before any other Kwiklink method.");
115
+ }
116
+ return config;
117
+ }
118
+ function consumeClickIdFromUrl() {
119
+ if (typeof window === "undefined") return void 0;
120
+ const url = new URL(window.location.href);
121
+ const clickId = url.searchParams.get(CLICK_ID_PARAM);
122
+ if (!clickId) return void 0;
123
+ url.searchParams.delete(CLICK_ID_PARAM);
124
+ window.history.replaceState(window.history.state, "", url.toString());
125
+ return clickId;
126
+ }
127
+ function init(cfg) {
128
+ if (!cfg?.apiKey) {
129
+ throw new Error("Kwiklink.init() requires { apiKey }.");
130
+ }
131
+ config = cfg;
132
+ }
133
+ function deviceHeaders() {
134
+ const deviceId = getDeviceId();
135
+ if (!deviceId) return {};
136
+ return { "X-Kwiklink-Device-Id": deviceId, "X-Kwiklink-Device-Id-Source": "web_storage" };
137
+ }
138
+ async function resolveLink() {
139
+ const { apiKey } = requireInit();
140
+ const clickId = consumeClickIdFromUrl();
141
+ const result = await post("/web/v1/links/resolve", apiKey, { clickId }, deviceHeaders());
142
+ if (result.matched && result.linkId) {
143
+ setLeadContext(result.linkId);
144
+ }
145
+ return result;
146
+ }
147
+ async function trackConversion(eventName, options = {}) {
148
+ const { apiKey } = requireInit();
149
+ const linkId = getLeadContext();
150
+ if (!linkId) {
151
+ console.warn(
152
+ "[Kwiklink] trackConversion() called with no prior resolveLink() match on this device \u2014 nothing recorded. Call resolveLink() on page load first."
153
+ );
154
+ return { recorded: false };
155
+ }
156
+ const headers = deviceHeaders();
157
+ if (!headers["X-Kwiklink-Device-Id"]) {
158
+ console.warn("[Kwiklink] trackConversion() couldn't read/create a device id (storage unavailable) \u2014 nothing recorded.");
159
+ return { recorded: false };
160
+ }
161
+ return post(
162
+ "/web/v1/events/conversion",
163
+ apiKey,
164
+ { linkId, eventName, value: options.value, metadata: options.metadata },
165
+ headers
166
+ );
167
+ }
168
+ var Kwiklink = { init, resolveLink, trackConversion };
169
+ var index_default = Kwiklink;
170
+ return __toCommonJS(index_exports);
171
+ })();
package/dist/index.js ADDED
@@ -0,0 +1,146 @@
1
+ // src/deviceId.ts
2
+ var STORAGE_KEY = "__kwiklink_device_id";
3
+ function generateId() {
4
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
5
+ return crypto.randomUUID();
6
+ }
7
+ const bytes = new Uint8Array(16);
8
+ if (typeof crypto !== "undefined" && typeof crypto.getRandomValues === "function") {
9
+ crypto.getRandomValues(bytes);
10
+ } else {
11
+ for (let i = 0; i < bytes.length; i++) bytes[i] = Math.floor(Math.random() * 256);
12
+ }
13
+ bytes[6] = bytes[6] & 15 | 64;
14
+ bytes[8] = bytes[8] & 63 | 128;
15
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
16
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
17
+ }
18
+ function getDeviceId() {
19
+ try {
20
+ const existing = localStorage.getItem(STORAGE_KEY);
21
+ if (existing) return existing;
22
+ const id = generateId();
23
+ localStorage.setItem(STORAGE_KEY, id);
24
+ return id;
25
+ } catch {
26
+ return null;
27
+ }
28
+ }
29
+ var LEAD_CONTEXT_KEY = "__kwiklink_lead_context";
30
+ function setLeadContext(linkId) {
31
+ try {
32
+ localStorage.setItem(LEAD_CONTEXT_KEY, linkId);
33
+ } catch {
34
+ }
35
+ }
36
+ function getLeadContext() {
37
+ try {
38
+ return localStorage.getItem(LEAD_CONTEXT_KEY);
39
+ } catch {
40
+ return null;
41
+ }
42
+ }
43
+
44
+ // src/net.ts
45
+ var API_HOST = "https://orbit-in1.kwiklink.io";
46
+ var KwiklinkRequestError = class extends Error {
47
+ constructor(message, status) {
48
+ super(message);
49
+ this.status = status;
50
+ this.name = "KwiklinkRequestError";
51
+ }
52
+ };
53
+ async function post(path, apiKey, body, extraHeaders = {}) {
54
+ let response;
55
+ try {
56
+ response = await fetch(`${API_HOST}${path}`, {
57
+ method: "POST",
58
+ headers: {
59
+ "Content-Type": "application/json",
60
+ "X-Api-Key": apiKey,
61
+ ...extraHeaders
62
+ },
63
+ body: JSON.stringify(body)
64
+ });
65
+ } catch (err) {
66
+ throw new KwiklinkRequestError(`network error calling ${path}: ${err.message}`);
67
+ }
68
+ let data = null;
69
+ try {
70
+ data = await response.json();
71
+ } catch {
72
+ }
73
+ if (!response.ok) {
74
+ const message = data?.error ?? `request to ${path} failed with status ${response.status}`;
75
+ throw new KwiklinkRequestError(message, response.status);
76
+ }
77
+ return data;
78
+ }
79
+
80
+ // src/index.ts
81
+ var CLICK_ID_PARAM = "__kw_cid";
82
+ var config = null;
83
+ function requireInit() {
84
+ if (!config) {
85
+ throw new Error("Kwiklink.init({ apiKey }) must be called before any other Kwiklink method.");
86
+ }
87
+ return config;
88
+ }
89
+ function consumeClickIdFromUrl() {
90
+ if (typeof window === "undefined") return void 0;
91
+ const url = new URL(window.location.href);
92
+ const clickId = url.searchParams.get(CLICK_ID_PARAM);
93
+ if (!clickId) return void 0;
94
+ url.searchParams.delete(CLICK_ID_PARAM);
95
+ window.history.replaceState(window.history.state, "", url.toString());
96
+ return clickId;
97
+ }
98
+ function init(cfg) {
99
+ if (!cfg?.apiKey) {
100
+ throw new Error("Kwiklink.init() requires { apiKey }.");
101
+ }
102
+ config = cfg;
103
+ }
104
+ function deviceHeaders() {
105
+ const deviceId = getDeviceId();
106
+ if (!deviceId) return {};
107
+ return { "X-Kwiklink-Device-Id": deviceId, "X-Kwiklink-Device-Id-Source": "web_storage" };
108
+ }
109
+ async function resolveLink() {
110
+ const { apiKey } = requireInit();
111
+ const clickId = consumeClickIdFromUrl();
112
+ const result = await post("/web/v1/links/resolve", apiKey, { clickId }, deviceHeaders());
113
+ if (result.matched && result.linkId) {
114
+ setLeadContext(result.linkId);
115
+ }
116
+ return result;
117
+ }
118
+ async function trackConversion(eventName, options = {}) {
119
+ const { apiKey } = requireInit();
120
+ const linkId = getLeadContext();
121
+ if (!linkId) {
122
+ console.warn(
123
+ "[Kwiklink] trackConversion() called with no prior resolveLink() match on this device \u2014 nothing recorded. Call resolveLink() on page load first."
124
+ );
125
+ return { recorded: false };
126
+ }
127
+ const headers = deviceHeaders();
128
+ if (!headers["X-Kwiklink-Device-Id"]) {
129
+ console.warn("[Kwiklink] trackConversion() couldn't read/create a device id (storage unavailable) \u2014 nothing recorded.");
130
+ return { recorded: false };
131
+ }
132
+ return post(
133
+ "/web/v1/events/conversion",
134
+ apiKey,
135
+ { linkId, eventName, value: options.value, metadata: options.metadata },
136
+ headers
137
+ );
138
+ }
139
+ var Kwiklink = { init, resolveLink, trackConversion };
140
+ var index_default = Kwiklink;
141
+ export {
142
+ index_default as default,
143
+ init,
144
+ resolveLink,
145
+ trackConversion
146
+ };
package/package.json CHANGED
@@ -1,6 +1,36 @@
1
1
  {
2
2
  "name": "kwiklink-sdk-web",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Kwiklink deep-link resolution, Lead/Conversion tracking, and deferred-click attribution for the browser.",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "main": "./dist/index.cjs",
8
+ "module": "./dist/index.js",
9
+ "types": "./dist/index.d.ts",
10
+ "unpkg": "./dist/index.global.js",
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist/index.d.ts",
14
+ "import": "./dist/index.js",
15
+ "require": "./dist/index.cjs"
16
+ }
17
+ },
18
+ "files": [
19
+ "dist"
20
+ ],
21
+ "sideEffects": false,
22
+ "scripts": {
23
+ "build": "tsup src/index.ts --format esm,cjs,iife --global-name Kwiklink --dts --clean --env.KWIKLINK_API_HOST=https://orbit-in1.kwiklink.io",
24
+ "dev": "tsup src/index.ts --format esm,cjs,iife --global-name Kwiklink --dts --watch --env.KWIKLINK_API_HOST=https://orbit-in1.kwiklink.io",
25
+ "prepublishOnly": "npm run build"
26
+ },
27
+ "devDependencies": {
28
+ "tsup": "^8.3.5",
29
+ "typescript": "^5.7.2"
30
+ },
31
+ "repository": {
32
+ "type": "git",
33
+ "url": "git+https://github.com/kwiklink/kwiklink-sdk-web.git"
34
+ },
35
+ "homepage": "https://github.com/kwiklink/kwiklink-sdk-web#readme"
36
+ }