@sortment/web-sdk 0.1.0 → 0.1.1

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/llms-full.txt ADDED
@@ -0,0 +1,374 @@
1
+ # Sortment Web SDK: guide for AI coding agents
2
+
3
+ > You are adding Sortment to a website so its marketing team can build
4
+ > audiences and journeys from what visitors do. Follow this guide in order.
5
+ > It is written for agents (Claude Code, Cursor, Copilot, Codex…) working in
6
+ > the customer's codebase, and is complete: you should not need other docs.
7
+
8
+ Package: `@sortment/web-sdk` (npm). Script-tag build:
9
+ https://cdn.jsdelivr.net/npm/@sortment/web-sdk@0/dist/sortment.umd.js
10
+ Types: https://cdn.jsdelivr.net/npm/@sortment/web-sdk@0/dist/types/index.d.ts
11
+
12
+ ## 1. What you need from the user
13
+
14
+ Ask the user for these before writing code. Never invent them.
15
+
16
+ 1. **Publishable key**: starts with `srt_pk_`. A Sortment admin creates it for
17
+ the project. It is safe in browser code and in public env vars.
18
+ - If they give a key starting with `srt_` but not `srt_pk_`, it is a
19
+ **secret key**. Do not put it in the site. The SDK refuses it. Ask for a
20
+ publishable key instead.
21
+ 2. **API host**: their Sortment URL. Default `https://app.sortment.com`. Only
22
+ change it if the user says so.
23
+ 3. **Consent**: does the site show a cookie/consent banner (GDPR, CCPA)? If
24
+ yes, set it up as in step 5.
25
+ 4. **Allowed origins**: the key may be limited to exact origins such as
26
+ `https://www.example.com`. Local development (`http://localhost:3000`) only
27
+ works if that origin is on the key too, or the key has no origin limit.
28
+ Tell the user this if you test locally.
29
+
30
+ ## 2. Choose how to install
31
+
32
+ Look at the codebase, then pick one:
33
+
34
+ | The site is… | Use |
35
+ | --------------------------------------------------------- | ---------- |
36
+ | Has a `package.json` and a bundler (Vite, Next.js, Nuxt, webpack, Angular CLI…) | npm (3a) |
37
+ | Static HTML, server-rendered templates (Rails, Django, Laravel, PHP), WordPress, Shopify, Webflow, Google Tag Manager | Script tag (3b) |
38
+
39
+ Install it once per site, in the place every page loads. Never install both.
40
+
41
+ ## 3a. npm
42
+
43
+ ```bash
44
+ npm install @sortment/web-sdk
45
+ ```
46
+
47
+ Use the project's package manager (`pnpm add`, `yarn add`, `bun add`) if it
48
+ has one.
49
+
50
+ ```ts
51
+ import { sortment } from '@sortment/web-sdk';
52
+
53
+ sortment.init(PUBLISHABLE_KEY, { apiHost: 'https://app.sortment.com' });
54
+ ```
55
+
56
+ Rules:
57
+
58
+ - Call `init` **once**, as early as possible, outside any component render.
59
+ - `init` does nothing during server-side rendering, so importing it in shared
60
+ code is safe. It still has to run in the browser.
61
+ - Read the key from the project's public env vars, for example
62
+ `VITE_SORTMENT_KEY`, `NEXT_PUBLIC_SORTMENT_KEY` or `NUXT_PUBLIC_SORTMENT_KEY`.
63
+ Add it to `.env.example` if the project has one.
64
+ - `sortment` is a single shared instance. Import it wherever you track.
65
+
66
+ Where to put `init`:
67
+
68
+ - **Vite / Create React App / plain SPA**: the entry file (`src/main.tsx`,
69
+ `src/main.ts`, `src/index.tsx`), before rendering the app.
70
+ - **Next.js App Router**: a client component rendered in `app/layout.tsx`:
71
+
72
+ ```tsx
73
+ // app/sortment.tsx
74
+ 'use client';
75
+
76
+ import { sortment } from '@sortment/web-sdk';
77
+ import { useEffect } from 'react';
78
+
79
+ export function Sortment() {
80
+ useEffect(() => {
81
+ sortment.init(process.env.NEXT_PUBLIC_SORTMENT_KEY!, {
82
+ apiHost: 'https://app.sortment.com',
83
+ });
84
+ }, []);
85
+ return null;
86
+ }
87
+ ```
88
+
89
+ Then render `<Sortment />` inside `<body>` in `app/layout.tsx`.
90
+ - **Next.js Pages Router**: the same `useEffect` in `pages/_app.tsx`.
91
+ - **Nuxt**: a client-only plugin, `plugins/sortment.client.ts`.
92
+ - **Vue (Vite)**: `src/main.ts`, before `app.mount()`.
93
+ - **SvelteKit**: `onMount` in the root `+layout.svelte`.
94
+ - **Angular**: `src/main.ts`, before `bootstrapApplication`.
95
+
96
+ Calls made before `init` (for example from a component that renders first) are
97
+ kept and run after `init`, so ordering is forgiving.
98
+
99
+ ## 3b. Script tag
100
+
101
+ Paste this before `</head>` in the layout or template that every page uses.
102
+ Replace only the key (and the host if the user gave one):
103
+
104
+ ```html
105
+ <script>
106
+ (function (w, d, key, host) {
107
+ var s = (w.sortment = w.sortment || []);
108
+ if (!Array.isArray(s)) return;
109
+ [
110
+ 'init',
111
+ 'identify',
112
+ 'track',
113
+ 'page',
114
+ 'alias',
115
+ 'reset',
116
+ 'setConsent',
117
+ 'flush',
118
+ ].forEach(function (m) {
119
+ s[m] = function () {
120
+ s.push([m].concat([].slice.call(arguments)));
121
+ };
122
+ });
123
+ var t = d.createElement('script');
124
+ t.async = true;
125
+ t.src =
126
+ 'https://cdn.jsdelivr.net/npm/@sortment/web-sdk@0/dist/sortment.umd.js';
127
+ d.head.appendChild(t);
128
+ s.init(key, { apiHost: host });
129
+ })(window, document, 'srt_pk_YOUR_KEY', 'https://app.sortment.com');
130
+ </script>
131
+ ```
132
+
133
+ Then call `window.sortment.track(...)` and the other methods from any script.
134
+ Calls made before the file finishes loading are replayed.
135
+
136
+ - **WordPress**: the theme's `header.php` before `</head>`, or a "header
137
+ scripts" plugin. Not inside the post editor.
138
+ - **Shopify**: `layout/theme.liquid` before `</head>`.
139
+ - **Webflow**: Site settings → Custom code → Head code.
140
+ - **Google Tag Manager**: a Custom HTML tag with the snippet, triggered on
141
+ All Pages.
142
+
143
+ ## 4. What is captured without code
144
+
145
+ After `init`, these are sent automatically. Do not add tracking calls for
146
+ them:
147
+
148
+ | Event | When |
149
+ | ----------------- | ----------------------------------------------------------------- |
150
+ | `page_viewed` | Page load, and route changes in single-page apps (History API) |
151
+ | `element_clicked` | Clicks on links, buttons and elements with `data-sortment-event` |
152
+ | `form_submitted` | Form submits: form id, name, action, method, field count. Never values. |
153
+ | `session_started` | First event after 30 minutes without activity |
154
+
155
+ UTM parameters, `gclid`, `fbclid`, `msclkid` and the referrer are added to
156
+ every event of the visit. Each piece can be switched off:
157
+
158
+ ```ts
159
+ sortment.init(key, {
160
+ autoCapture: {
161
+ pageViews: true,
162
+ clicks: true,
163
+ formSubmits: true,
164
+ sessions: true,
165
+ attribution: true,
166
+ },
167
+ });
168
+ ```
169
+
170
+ `autoCapture: false` turns all of them off.
171
+
172
+ **Hash routers** (`/#/route`): route changes are not captured. Call
173
+ `sortment.page()` from the router's after-navigation hook.
174
+
175
+ ## 5. Consent
176
+
177
+ If the site has a consent banner, nothing may be stored or sent before the
178
+ visitor agrees:
179
+
180
+ ```ts
181
+ sortment.init(key, {
182
+ apiHost: 'https://app.sortment.com',
183
+ defaultConsent: 'pending',
184
+ });
185
+
186
+ // In the consent tool's callback, when the visitor chooses:
187
+ sortment.setConsent(true); // or false
188
+ ```
189
+
190
+ - While consent is pending, events are held in memory and sent if consent is
191
+ granted. `setConsent(false)` deletes everything the SDK stored.
192
+ - The choice is remembered across visits and applies to all open tabs.
193
+ - Find the consent tool's own "consent changed" callback or event (OneTrust,
194
+ Cookiebot, Osano, a custom banner…) and call `setConsent` from it, both on
195
+ the first choice and when the visitor changes their mind. Map the
196
+ "analytics" or "marketing" category, as the user decides.
197
+
198
+ Without a consent banner, leave `defaultConsent` out (the default is
199
+ `'granted'`).
200
+
201
+ ## 6. Identify users
202
+
203
+ When a visitor signs in or signs up, and on every page load while they are
204
+ signed in:
205
+
206
+ ```ts
207
+ sortment.identify(user.id, {
208
+ email: user.email,
209
+ name: user.name,
210
+ plan: user.plan,
211
+ createdAt: user.createdAt, // ISO 8601 string
212
+ });
213
+ ```
214
+
215
+ - The first argument is the site's **stable internal user id** (database id).
216
+ Not the email, not a session id. It must never change for that person.
217
+ - Traits describe the person. Email and phone are fine here: marketers need
218
+ them to reach the person. Never pass passwords, tokens or payment data.
219
+ - Calling it again with the same id merges traits, so calling it on each load
220
+ is fine.
221
+ - Every event carries the visitor's anonymous id; after `identify` it carries
222
+ the user id too, so activity before and after sign-in can be connected. Do
223
+ not add your own id cookies.
224
+
225
+ On **sign-out**:
226
+
227
+ ```ts
228
+ sortment.reset();
229
+ ```
230
+
231
+ This forgets the user and starts a new anonymous id, so the next person on the
232
+ device is not mixed up with them.
233
+
234
+ ## 7. Track business events
235
+
236
+ Auto-capture covers browsing. Add `track` calls for the moments marketers will
237
+ build audiences and journeys on: sign-up, trial start, checkout, purchase,
238
+ plan change, key feature use.
239
+
240
+ ```ts
241
+ sortment.track('Completed checkout', {
242
+ orderId: 'ord_8231',
243
+ total: 129.5,
244
+ currency: 'USD',
245
+ itemCount: 3,
246
+ });
247
+ ```
248
+
249
+ Put the call where the action **succeeds** (after the API responds OK), not on
250
+ the button click, so failed attempts are not counted.
251
+
252
+ Naming:
253
+
254
+ - Past tense, verb first, sentence case: `Signed up`, `Started trial`,
255
+ `Added to cart`, `Completed checkout`, `Upgraded plan`.
256
+ - One name per action across the whole site. Search the codebase for existing
257
+ `track(` calls and follow their names and style if there are any.
258
+ - Never put ids, numbers or user data in the name. Use properties:
259
+ `Viewed product` with `{ productId: 'A1' }`, not `Viewed product A1`.
260
+ - At most 200 characters.
261
+ - Do not reuse the automatic names: `page_viewed`, `element_clicked`,
262
+ `form_submitted`, `session_started`, `identify`, `alias`, `screen_viewed`.
263
+
264
+ Properties:
265
+
266
+ - A flat JSON object: strings, numbers, booleans, null, and arrays or objects
267
+ of those. Numbers as numbers, dates as ISO 8601 strings, money with a
268
+ `currency` code.
269
+ - camelCase keys, used the same way in every event.
270
+ - Under 32 KB per event. Do not send whole API responses.
271
+ - No personal data in event properties: put it on the user with `identify`.
272
+
273
+ **No-code option** for clicks the user only wants named, without JavaScript:
274
+
275
+ ```html
276
+ <button data-sortment-event="Started trial" data-sortment-prop-plan="pro">
277
+ Try Pro
278
+ </button>
279
+ ```
280
+
281
+ This sends `Started trial` with `{ plan: 'pro' }` instead of
282
+ `element_clicked`. `data-sortment-prop-*` attributes become camelCase
283
+ properties.
284
+
285
+ ## 8. Privacy controls
286
+
287
+ On by default; do not turn them off unless the user asks.
288
+
289
+ - Form field values are never read.
290
+ - Values under keys that look sensitive (password, token, secret, card number,
291
+ CVV, PIN, OTP, SSN, IBAN, auth, cookie…) are replaced with `[redacted]`, in
292
+ properties, traits and URL query and fragment parameters. Add more keys
293
+ with `sensitiveFields: ['dateOfBirth']`.
294
+ - `data-sortment-mask` on an element: clicks are kept, its text is dropped.
295
+ Use it on elements that show personal data (an account menu with the
296
+ user's email).
297
+ - `data-sortment-ignore` on an element: nothing inside it is captured.
298
+
299
+ ## 9. Verify the install
300
+
301
+ 1. Temporarily add `debug: true` to the `init` options and load the site.
302
+ The console logs each event.
303
+ 2. In the browser's network tab, look for `POST …/api/v1/srt/sdk/batch`
304
+ about 5 seconds after an event. A `200` response with
305
+ `"status": "queued"` per event means Sortment has it.
306
+ 3. Remove `debug: true` before committing.
307
+ 4. Ask the user to check that the events appear in Sortment.
308
+
309
+ | Problem | Cause and fix |
310
+ | ----------------------------- | -------------------------------------------------------------------- |
311
+ | `401` "Invalid or disabled API key" | Wrong or revoked key. Ask the user for the current publishable key. |
312
+ | `401` "Origin … is not allowed for this key" | The site's origin is not on the key. Ask the user to add it. |
313
+ | "This is not a publishable key" in the console | A secret key was used. Replace it with an `srt_pk_` key. |
314
+ | Nothing sent at all | `init` never ran in the browser, or consent is still pending. |
315
+ | No `page_viewed` on route change | Hash router: call `sortment.page()` on navigation (step 4). |
316
+
317
+ ## 10. API reference
318
+
319
+ | Method | Use |
320
+ | ---------------------------------------- | -------------------------------------------------------------- |
321
+ | `init(writeKey, options?)` | Start the SDK. Once per page load. |
322
+ | `track(event, properties?)` | A named action. |
323
+ | `identify(userId, traits?)` | Who the visitor is. On sign-in and each load while signed in. |
324
+ | `page(name?, properties?)` | A page view. Only needed for hash routers or custom names. |
325
+ | `alias(userId, previousId?)` | Link an old id to a new one, such as when a user id changes. Rarely needed. |
326
+ | `reset()` | On sign-out. |
327
+ | `setConsent(granted)` | From the consent banner. |
328
+ | `flush()` | Send queued events now. Returns a promise. |
329
+ | `getAnonymousId()` | The visitor's anonymous id, or null before `init` (or during SSR). |
330
+ | `getUserId()` | The identified user id, or null. |
331
+ | `destroy()` | Stop the SDK and remove its listeners. For tests and teardown. |
332
+
333
+ Options for `init` (all optional):
334
+
335
+ | Option | Default | Meaning |
336
+ | ----------------------- | -------------------------- | ----------------------------------------------- |
337
+ | `apiHost` | `https://app.sortment.com` | Sortment URL |
338
+ | `autoCapture` | all on | Object of booleans (step 4), or `false` |
339
+ | `defaultConsent` | `'granted'` | `'pending'` to wait for `setConsent` (step 5) |
340
+ | `maskSensitiveFields` | `true` | Redact sensitive keys (step 8) |
341
+ | `sensitiveFields` | `[]` | Extra keys to redact |
342
+ | `debug` | `false` | Log to the console |
343
+ | `flushInterval` | `5000` | Milliseconds between sends |
344
+ | `flushAt` | `20` | Send when this many are queued (max 100) |
345
+ | `maxQueueSize` | `1000` | Oldest queued events are dropped beyond this |
346
+ | `maxRetries` | `10` | Failed sends before an event is dropped |
347
+ | `sessionTimeoutMinutes` | `30` | Inactivity before a new session |
348
+
349
+ Leave delivery options at their defaults unless the user asks. Events are
350
+ queued in `localStorage`, retried with backoff, survive reloads and offline
351
+ periods, and are sent with `navigator.sendBeacon` when the page closes.
352
+
353
+ ## 11. Do not
354
+
355
+ - Do not put a secret key (`srt_` without `pk_`) in browser code.
356
+ - Do not install both the npm package and the script tag.
357
+ - Do not call `init` inside a component render or on every route change.
358
+ - Do not track form field values, passwords or payment data.
359
+ - Do not use email or other personal data as the `identify` user id or in
360
+ event names or properties.
361
+ - Do not add `track` calls for page views, clicks or form submits that
362
+ auto-capture already sends, unless the user wants a specific name.
363
+ - Do not commit `debug: true`.
364
+
365
+ ## 12. Before you finish
366
+
367
+ Tell the user:
368
+
369
+ - where you installed the SDK and how the key is configured,
370
+ - which events you added, with their names and properties, so marketers know
371
+ what to build on,
372
+ - whether consent handling is in place,
373
+ - anything they need to do: add the site's origins to the key, set the env
374
+ var in production, check events in Sortment.
package/llms.txt ADDED
@@ -0,0 +1,24 @@
1
+ # Sortment Web SDK
2
+
3
+ > `@sortment/web-sdk` sends website events to Sortment: custom events
4
+ > (`track`), who the visitor is (`identify`), and page views, clicks, form
5
+ > submits, sessions and UTM attribution captured automatically. Install it
6
+ > with npm or a script tag and a publishable key (`srt_pk_…`). About 6 KB
7
+ > gzipped, privacy-safe by default.
8
+
9
+ AI agents installing or instrumenting the SDK: read the full guide first. It
10
+ covers what to ask the user for, where to install per framework (React,
11
+ Next.js, Vue, Nuxt, SvelteKit, Angular, WordPress, Shopify, Webflow, Google
12
+ Tag Manager), consent, identifying users, naming events, verifying the
13
+ install, and what not to do.
14
+
15
+ ## Docs
16
+
17
+ - [Agent guide](https://cdn.jsdelivr.net/npm/@sortment/web-sdk@0/llms-full.txt): complete, step-by-step install and instrumentation guide for AI coding agents
18
+ - [README](https://cdn.jsdelivr.net/npm/@sortment/web-sdk@0/README.md): human-oriented overview of install, API, auto-capture, privacy and options
19
+ - [Type definitions](https://cdn.jsdelivr.net/npm/@sortment/web-sdk@0/dist/types/index.d.ts): exact signatures of every method and option
20
+
21
+ ## Optional
22
+
23
+ - [npm package](https://www.npmjs.com/package/@sortment/web-sdk)
24
+ - [Script-tag bundle](https://cdn.jsdelivr.net/npm/@sortment/web-sdk@0/dist/sortment.umd.js)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sortment/web-sdk",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Sortment web SDK: track, identify and auto-capture events from websites.",
5
5
  "license": "MIT",
6
6
  "sideEffects": [
@@ -23,7 +23,9 @@
23
23
  },
24
24
  "files": [
25
25
  "dist/**/*",
26
- "README.md"
26
+ "README.md",
27
+ "llms.txt",
28
+ "llms-full.txt"
27
29
  ],
28
30
  "publishConfig": {
29
31
  "access": "public"