@sqid-dev/playground 0.1.0 → 0.1.2

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/README.md CHANGED
@@ -1,8 +1,8 @@
1
1
  # Sqid Playground
2
2
 
3
- A real-looking website with the Sqid panel docked on the side. Open it and watch yourself get
4
- identified. Try the scenarios, switch recipes on and off, read the record that goes out, then put
5
- Sqid on your own site from the same panel.
3
+ A real-looking website with the Sqid panel docked on the side. Open it and watch an anonymous
4
+ visitor (you) turn into a person. Then send that record to your app, or put Sqid on your own site,
5
+ from the same panel.
6
6
 
7
7
  The site is **Driftwood**, a made-up standing-desk company: a home page, a product with sizes and
8
8
  finishes, pricing, a demo form, a cart and a sign-in. Everything on it exists so you can see what
@@ -12,8 +12,8 @@ Sqid does with it. The panel shows what the SDK on the page actually did; nothin
12
12
  npx -y @sqid-dev/playground
13
13
  ```
14
14
 
15
- That signs you in to Sqid (browser), finds your account's Sandbox site, allows `http://localhost:3000`
16
- on it, and opens the site. The Sandbox hands every new visitor one of fifty made-up people and never
15
+ That signs you in to Sqid (browser), finds your account's Sandbox site, adds `http://localhost:3000`
16
+ to its allowed origins (the origins already on the site are kept), and opens the site. The Sandbox hands every new visitor one of fifty made-up people and never
17
17
  spends a credit, so the identification, the webhook record and the recipes all run for real.
18
18
 
19
19
  From Claude Code, the Sqid MCP server offers the same thing when you say "set up Sqid" and have no
@@ -21,17 +21,23 @@ website to paste the snippet into.
21
21
 
22
22
  ## What you can try
23
23
 
24
- | Tab | What it does |
24
+ The panel opens on one screen: the reveal.
25
+
26
+ | Where | What it does |
25
27
  | --- | --- |
26
- | **Start** | The five-step checklist (signed in, site, script, webhook, stream live) and the reveal: anonymous visitor, then the person, with the time it took. "Watch it again" replays it. (The Sandbox pins one person to a device; a private window gets another.) |
27
- | **Live** | Every SDK event and page action, newest first: connected, `visitor.identified`, clicks, variant switches, form stalls. |
28
- | **Scenarios** | Who you are right now, and a checklist of things to try on the site: switch sizes without buying, sign in and call `squid.identify()`, stall on the form, sit on the cart, return to pricing, labelled clicks, exit intent. |
29
- | **Recipes** | The docs recipes, live on this site: DOM personalisation, pricing personalisation, chat, form prefill, exit intent, analytics, the service-provider pattern against a built-in mock database. Toggle one and the page changes; the code shown is the code from the docs. |
30
- | **Delivery** | Your webhooks on the site (add any https endpoint, send a test), this visitor's full record from the visitor API, and a webhook sample. |
31
- | **Go live** | Create a real site from its URL and get the snippet, the MCP and CLI one-liners for your app, the API and OEM links for embedding, and the plan box with "Add a card". |
28
+ | **First screen** | An anonymous visitor, then the person, with the time it took. Name, company and title, and "See the full record" for everything Sqid returned. A one-line status ("Working", "Connecting", or what is wrong) with **Details** for the setup checks (signed in, site, script, webhook, first identification). |
29
+ | **Be someone new** | Calls `await squid.anonymouse()` and reloads. On a Sandbox that forgets the made-up person (it resolves `{ forgotten: true }`), so the next load is a new test person. Matching is by device, so a private window usually comes back as the same person. The console's **Forget identity** on a Test profile does the same. |
30
+ | **Send this to my app** | Add any https address as a webhook, send a test, and see an example of what gets sent. |
31
+ | **Put Sqid on my site** | Create a real site from its address and copy the one line of code. Below it: what it costs (prepaid credits, below) and, under "Other ways", the Claude Code / CLI one-liners and the API and OEM plan for putting Sqid inside your product. |
32
+ | **Explore** | Behind the button at the top. **Live events**: every SDK event and page action, newest first. **Things to try**: switch sizes without buying, sign in and call `squid.identify()`, stall on the form, sit on the cart, return to pricing, labelled clicks, exit intent. **Recipes**: the docs recipes live on this site (DOM and pricing personalisation, chat, form prefill, exit intent, analytics, the service-provider pattern against a built-in mock database); toggle one and the page changes. |
33
+
34
+ The Sandbox is free: every visitor is one of fifty made-up people and no credits are used. A real
35
+ site runs on the Developer plan's prepaid credits, $0.25 each, with 25 welcome credits when you add
36
+ a card; nothing is charged unless you buy credits or turn on auto-reload. Putting Sqid inside your
37
+ own product is the OEM plan: OEM Launch is $675/month with 500 identifications/month included.
32
38
 
33
- Moments (Signals) never fire on a Sandbox site. Add a card in the console and turn Signals on for a
34
- real site to see `visitor.moment` and the moment webhook.
39
+ Moments (Signals) never fire on a Sandbox site. Turn Signals on for a real site to see
40
+ `visitor.moment` and the moment webhook.
35
41
 
36
42
  ## Options
37
43
 
@@ -45,16 +51,16 @@ signs in ahead of time; otherwise the playground asks on first run.
45
51
  ## How it works
46
52
 
47
53
  - `src/index.js` parses the options and starts the server.
48
- - `src/sqid.js` is the bridge to the account: sign-in, the Sandbox, origins, webhooks, the visitor
49
- API (with a key bound to the site), creating a real site. It reuses the sqid CLI's modules, so there
54
+ - `src/sqid.js` is the bridge to the account: sign-in, the Sandbox, origins (read from the site
55
+ and only ever added to), webhooks, the visitor record, creating a real site. It reuses the sqid CLI's modules, so there
50
56
  is one copy of auth.
51
57
  - `src/server.js` serves the pages and a small local API under `/_sqid` (localhost only).
52
58
  - `src/layout.js` and `src/pages/` are Driftwood. The real Sqid snippet goes before `</head>`.
53
59
  - `public/panel.js` is the panel; `public/recipes.js` the recipes; `public/site.js` the site's own
54
60
  behaviour (variant picker, cart, sign-in calling `squid.identify`).
55
61
 
56
- Nothing is stored except what the CLI already keeps. Scenario progress and recipe toggles live in
57
- your browser's localStorage.
62
+ Nothing is stored except what the CLI already keeps. Scenario progress, recipe toggles and the
63
+ last panel screen live in your browser's localStorage.
58
64
 
59
65
  ## Development
60
66
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sqid-dev/playground",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "A real-looking website (Driftwood, a desk company) with a Sqid panel docked on the side: watch a visitor get identified, try the scenarios and recipes, see the record that goes out, then go live on your own site.",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/public/panel.css CHANGED
@@ -4,15 +4,12 @@
4
4
  .pg-panel a{color:#22d3ee}
5
5
  .pg-top{display:flex;align-items:center;gap:10px;padding:10px 14px;border-bottom:1px solid #26262b;font-size:12px}
6
6
  .pg-top .dot{width:8px;height:8px;border-radius:4px;background:#22d3ee;flex-shrink:0}
7
- .pg-top .name{font-weight:600;letter-spacing:.04em}
8
- .pg-top .site{color:#a1a1aa;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
7
+ .pg-top .name{font-weight:600;font-size:13px}
8
+ .pg-top .site{color:#a1a1aa;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}
9
9
  .pg-top .conn{margin-left:auto;display:inline-flex;align-items:center;gap:6px;color:#a1a1aa;white-space:nowrap}
10
10
  .pg-top .conn i{width:8px;height:8px;border-radius:4px;background:#52525b;display:inline-block}
11
11
  .pg-top .conn.on{color:#4ade80}.pg-top .conn.on i{background:#4ade80}
12
- .pg-tabs{display:flex;gap:0;padding:6px 8px 0;border-bottom:1px solid #26262b}
13
- .pg-tabs button{padding:9px 8px;border:0;border-bottom:2px solid transparent;background:transparent;color:#a1a1aa;font:inherit;font-size:12.5px;cursor:pointer}
14
- .pg-tabs button[aria-selected="true"]{color:#fafafa;font-weight:600;border-bottom-color:#22d3ee}
15
- .pg-body{flex-grow:1;overflow-y:auto;padding:16px 14px;display:flex;flex-direction:column;gap:14px}
12
+ .pg-body{flex-grow:1;overflow-y:auto;overflow-x:hidden;padding:16px 14px;display:flex;flex-direction:column;gap:14px;min-width:0}
16
13
  .pg-h{margin:0;font-size:16px;font-weight:600;letter-spacing:-.01em}
17
14
  .pg-p{margin:0;color:#a1a1aa;line-height:1.5}
18
15
  .pg-label{font-size:11px;font-weight:600;letter-spacing:.08em;color:#71717a}
@@ -21,24 +18,18 @@
21
18
  .pg-card.warn{background:#1a1708;border-color:#713f12}
22
19
  .pg-card.warn .pg-label{color:#facc15}
23
20
  .pg-row{display:flex;align-items:center;gap:8px}
24
- .pg-row .grow{flex-grow:1}
21
+ .pg-row .grow,.pg-item .grow{flex-grow:1;min-width:0}
22
+ .pg-row.pg-wrap{flex-wrap:wrap}
25
23
  .pg-btn{height:30px;padding:0 11px;border-radius:6px;border:1px solid #3f3f46;background:transparent;color:#fafafa;font:inherit;font-size:12px;cursor:pointer;white-space:nowrap}
26
24
  .pg-btn.primary{background:#fafafa;color:#0b0b0d;border-color:#fafafa;font-weight:600}
27
25
  .pg-btn.accent{background:#22d3ee;color:#0b0b0d;border-color:#22d3ee;font-weight:600}
28
26
  .pg-btn.yellow{background:#facc15;color:#0b0b0d;border-color:#facc15;font-weight:600}
29
27
  .pg-btn:disabled{opacity:.5;cursor:default}
30
- .pg-input{height:34px;border-radius:6px;border:1px solid #3f3f46;background:#0b0b0d;color:#fafafa;padding:0 10px;font:inherit;font-size:12.5px;width:100%}
28
+ .pg-input{min-width:0;height:34px;border-radius:6px;border:1px solid #3f3f46;background:#0b0b0d;color:#fafafa;padding:0 10px;font:inherit;font-size:12.5px;width:100%}
31
29
  .pg-mono{font-family:'JetBrains Mono',monospace;font-size:11.5px;line-height:1.55}
32
- pre.pg-mono{margin:0;padding:12px;border-radius:8px;background:#141416;border:1px solid #26262b;color:#d4d4d8;overflow-x:auto;white-space:pre}
30
+ pre.pg-mono{max-width:100%;margin:0;padding:12px;border-radius:8px;background:#141416;border:1px solid #26262b;color:#d4d4d8;overflow-x:auto;white-space:pre}
33
31
  .pg-muted{color:#71717a}.pg-ok{color:#4ade80}.pg-acc{color:#22d3ee}.pg-vio{color:#a78bfa}.pg-yel{color:#facc15}
34
32
 
35
- .pg-steps{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:8px}
36
- .pg-step{display:flex;gap:10px;align-items:flex-start;padding:10px 12px;border-radius:10px;background:#141416;border:1px solid #26262b}
37
- .pg-step.now{border-color:#22d3ee}.pg-step.todo{opacity:.6}
38
- .pg-step svg{flex-shrink:0;margin-top:1px}
39
- .pg-step .t{font-weight:500}.pg-step .s{font-size:12px;color:#a1a1aa;line-height:1.45}
40
- .pg-step .body{display:flex;flex-direction:column;gap:4px;flex-grow:1}
41
-
42
33
  .pg-reveal{display:flex;align-items:center;gap:10px}
43
34
  .pg-reveal .who{flex:1 1 0;min-width:0;display:flex;flex-direction:column;gap:3px;padding:10px;border-radius:8px;border:1px dashed #3f3f46}
44
35
  .pg-reveal .who.known{border:1px solid #22d3ee;background:#0e2a30}
@@ -61,16 +52,66 @@ pre.pg-mono{margin:0;padding:12px;border-radius:8px;background:#141416;border:1p
61
52
  .pg-item .r a{color:#22d3ee}
62
53
  .pg-item svg{flex-shrink:0}
63
54
 
64
- .pg-personas{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px}
65
- .pg-persona{display:flex;flex-direction:column;gap:2px;align-items:flex-start;padding:10px 12px;border-radius:8px;border:1px solid #26262b;background:#141416;color:#fafafa;font:inherit;text-align:left;cursor:pointer}
66
- .pg-persona.on{border-color:#22d3ee;background:#0e2a30}
67
- .pg-persona b{font-size:13px}.pg-persona span{font-size:11px;color:#a1a1aa}
68
-
69
55
  .pg-toggle{width:32px;height:18px;border-radius:9px;background:#3f3f46;position:relative;flex-shrink:0;border:0;cursor:pointer;padding:0}
70
56
  .pg-toggle i{position:absolute;left:2px;top:2px;width:14px;height:14px;border-radius:7px;background:#a1a1aa}
71
57
  .pg-toggle.on{background:#22d3ee}.pg-toggle.on i{left:auto;right:2px;background:#0b0b0d}
72
58
 
73
- .pg-tog{display:flex;align-items:center;gap:12px}
74
- .pg-tog .r{margin-left:auto;font-size:11px;color:#71717a}
75
- .pg-foot{margin-top:auto;display:flex;flex-direction:column;gap:6px}
76
- @media (max-width:900px){.pg-panel{position:static;height:auto;max-height:70vh}}
59
+ .pg-btn.ghost{border-color:transparent;color:#a1a1aa;padding:0 8px}
60
+ .pg-btn.ghost:hover,.pg-btn.ghost.on{color:#fafafa;border-color:#3f3f46}
61
+ .pg-btn.big{height:38px;font-size:13px}
62
+ .pg-btn.accent,.pg-btn.primary{display:inline-flex;align-items:center;justify-content:center;text-decoration:none}
63
+ .pg-panel a.pg-btn.accent{color:#0b0b0d}
64
+ .pg-link{border:0;background:none;padding:0;color:#22d3ee;font:inherit;font-size:12.5px;cursor:pointer;text-align:left;align-self:flex-start}
65
+ .pg-back{border:0;background:none;padding:0;color:#a1a1aa;font:inherit;font-size:12.5px;cursor:pointer;align-self:flex-start}
66
+ .pg-back:hover{color:#fafafa}
67
+ .small{font-size:12px}
68
+ .pg-strong{color:#fafafa}
69
+ .pg-scroll{max-height:320px;overflow:auto}
70
+
71
+ /* one-line setup status */
72
+ .pg-status{display:flex;align-items:center;gap:8px;font-size:12.5px;color:#a1a1aa}
73
+ .pg-status i{width:8px;height:8px;border-radius:4px;background:#52525b;flex-shrink:0}
74
+ .pg-status.ok i{background:#4ade80}.pg-status.warn i{background:#facc15}.pg-status.warn .txt{color:#facc15}
75
+ .pg-status .txt{flex:1 1 auto;min-width:0}
76
+ .pg-status .pg-link,.pg-row .pg-link{align-self:auto;flex-shrink:0}
77
+ .pg-checks{list-style:none;margin:-4px 0 0;padding:10px 12px;border-radius:10px;background:#141416;border:1px solid #26262b;display:flex;flex-direction:column;gap:8px}
78
+ .pg-checks li{display:flex;gap:8px;align-items:flex-start}
79
+ .pg-checks svg{flex-shrink:0;margin-top:2px}
80
+ .pg-checks div{display:flex;flex-direction:column;gap:1px;min-width:0}
81
+ .pg-checks .t{font-weight:500;font-size:12.5px}.pg-checks .s{font-size:12px;color:#a1a1aa;overflow-wrap:anywhere}
82
+
83
+ /* the reveal */
84
+ .pg-hero{gap:12px;padding:14px}
85
+ .pg-hero .pg-h{font-size:17px;line-height:1.3}
86
+ .pg-facts{margin:0;display:flex;flex-direction:column;gap:6px}
87
+ .pg-facts div{display:grid;grid-template-columns:72px 1fr;gap:8px}
88
+ .pg-facts dt{color:#71717a;font-size:12px;line-height:20px}
89
+ .pg-facts dd{margin:0;font-weight:500;overflow-wrap:anywhere}
90
+
91
+ /* the two next steps */
92
+ .pg-next{display:flex;flex-direction:column;gap:8px}
93
+ .pg-cta{display:flex;align-items:center;gap:10px;width:100%;padding:12px 14px;border-radius:10px;border:1px solid #fafafa;background:#fafafa;color:#0b0b0d;font:inherit;text-align:left;cursor:pointer}
94
+ .pg-cta > span{display:flex;flex-direction:column;gap:2px;flex:1 1 auto;min-width:0}
95
+ .pg-cta b{font-size:14px}.pg-cta span span{font-size:12px;color:#3f3f46}
96
+ .pg-cta svg{flex-shrink:0}
97
+ .pg-cta:hover{background:#e4e4e7}
98
+
99
+ /* Explore's segmented control */
100
+ .pg-seg{display:flex;gap:2px;padding:3px;border-radius:8px;background:#141416;border:1px solid #26262b}
101
+ .pg-seg button{flex:1 1 0;min-width:0;height:28px;border:0;border-radius:6px;background:transparent;color:#a1a1aa;font:inherit;font-size:12px;cursor:pointer;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
102
+ .pg-seg button[aria-selected="true"]{background:#26262b;color:#fafafa;font-weight:600}
103
+
104
+ .pg-form{display:flex;flex-direction:column;gap:8px}
105
+ .pg-form label{display:flex;flex-direction:column;gap:4px}
106
+ .pg-url{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0;flex:1 1 auto}
107
+ .pg-dot{width:8px;height:8px;border-radius:4px;background:#52525b;flex-shrink:0}.pg-dot.on{background:#4ade80}
108
+
109
+ @media (max-width:900px){
110
+ .pg-panel{position:static;height:auto;max-height:none;flex:1 1 100%;border-left:0;border-top:1px solid #26262b}
111
+ }
112
+ @media (max-width:420px){
113
+ .pg-top{gap:6px;padding:10px 12px}
114
+ .pg-top .conn .lbl{display:none}
115
+ .pg-body{padding:14px 12px}
116
+ .pg-reveal{gap:6px}
117
+ }
package/public/panel.js CHANGED
@@ -1,6 +1,9 @@
1
- // The Sqid panel. Six tabs: Start, Live, Scenarios, Recipes, Delivery, Go live. It listens to
2
- // the real SDK on this page (window.squid), to the page (sqid:page events from site.js) and to
3
- // the local API (/_sqid/*). Nothing here is mocked: what it shows is what Sqid did.
1
+ // The Sqid panel. The first screen is the reveal (an anonymous visitor becomes a person) with two
2
+ // next steps: "Send this to my app" (webhooks) and "Put Sqid on my site" (a real site and its
3
+ // snippet). Live events, things to try and the recipes sit behind Explore.
4
+ //
5
+ // It listens to the real SDK on this page (window.squid), to the page (sqid:page events from
6
+ // site.js) and to the local API (/_sqid/*). Nothing here is mocked: what it shows is what Sqid did.
4
7
  (function(){
5
8
  'use strict';
6
9
  const cfg = window.SQID_PLAYGROUND || { site : {}, page : '' };
@@ -12,24 +15,41 @@
12
15
  const since = () => ((performance.now() - t0) / 1000).toFixed(2) + 's';
13
16
  const store = {
14
17
  get(k, d){ try{ let v = JSON.parse(localStorage.getItem('sqid.playground.' + k)); return v == null ? d : v; }catch(error){ return d; } },
15
- set(k, v){ localStorage.setItem('sqid.playground.' + k, JSON.stringify(v)); },
18
+ set(k, v){ try{ localStorage.setItem('sqid.playground.' + k, JSON.stringify(v)); }catch(error){ /* private mode */ } },
16
19
  sget(k, d){ try{ let v = JSON.parse(sessionStorage.getItem('sqid.playground.' + k)); return v == null ? d : v; }catch(error){ return d; } },
17
- sset(k, v){ sessionStorage.setItem('sqid.playground.' + k, JSON.stringify(v)); }
20
+ sset(k, v){ try{ sessionStorage.setItem('sqid.playground.' + k, JSON.stringify(v)); }catch(error){ /* private mode */ } }
21
+ };
22
+ const VIEWS = ['home', 'send', 'golive', 'explore'];
23
+ const EXPLORE = { live : 'Live events', scenarios : 'Things to try', recipes : 'Recipes' };
24
+ const CONSOLE = () => S.state?.console || 'https://app.sqid.dev';
25
+
26
+ // ---- svg bits -----------------------------------------------------------------------------------
27
+ const ICON = {
28
+ done : '<svg width="16" height="16" viewBox="0 0 20 20" role="img" aria-label="done"><circle cx="10" cy="10" r="9" fill="#22d3ee"></circle><path d="M6 10.5l2.5 2.5L14 7.5" stroke="#0b0b0d" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"></path></svg>',
29
+ now : '<svg width="16" height="16" viewBox="0 0 20 20" role="img" aria-label="current"><circle cx="10" cy="10" r="8" stroke="#22d3ee" stroke-width="2" fill="none"></circle><circle cx="10" cy="10" r="3" fill="#22d3ee"></circle></svg>',
30
+ todo : '<svg width="16" height="16" viewBox="0 0 20 20" role="img" aria-label="pending"><circle cx="10" cy="10" r="8" stroke="#52525b" stroke-width="2" fill="none"></circle></svg>',
31
+ arrow: '<svg width="20" height="20" viewBox="0 0 22 22" role="img" aria-label="became"><path d="M3 11h14M12 6l5 5-5 5" stroke="#22d3ee" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"></path></svg>',
32
+ next : '<svg width="16" height="16" viewBox="0 0 20 20" aria-hidden="true"><path d="M7 4l6 6-6 6" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"></path></svg>'
18
33
  };
19
34
 
20
35
  // ---- state --------------------------------------------------------------------------------
21
36
  const S = {
22
- tab : store.get('tab', 'start'),
37
+ view : VIEWS.includes(store.get('view', 'home')) ? store.get('view', 'home') : 'home',
38
+ explore : EXPLORE[store.get('explore', 'live')] ? store.get('explore', 'live') : 'live',
23
39
  state : null, // /_sqid/state
24
40
  connected : false,
41
+ sdkFailed : false,
25
42
  visitor : null, // engine.visitor()
26
43
  traits : null, // visitor.identified detail
27
44
  identified: null,
28
45
  timeToId : null,
29
46
  log : store.sget('log', []),
30
47
  done : store.get('done', {}), // scenario id -> true
31
- record : null, // last visitor record from the API
48
+ record : null, // the visitor's full record from the console
32
49
  recordErr : null,
50
+ showRecord: false,
51
+ details : false, // setup checklist open
52
+ note : null, // a message under "Be someone new"
33
53
  webhooks : [],
34
54
  goLive : store.get('golive', null),
35
55
  hidden : store.get('hidden', false)
@@ -41,7 +61,7 @@
41
61
  S.log.unshift({ at : since(), page : cfg.path, kind, detail, cls : cls || 'pg-muted', t : Date.now() });
42
62
  S.log = S.log.slice(0, 80);
43
63
  store.sset('log', S.log);
44
- if(S.tab === 'live' || S.tab === 'start' || S.tab === 'scenarios'){ render(); }
64
+ if(S.view === 'explore' || S.view === 'home'){ render(); }
45
65
  }
46
66
 
47
67
  // ---- scenarios ----------------------------------------------------------------------------
@@ -77,7 +97,7 @@
77
97
  // ---- the SDK --------------------------------------------------------------------------------
78
98
  function whenSquid(cb, tries = 200){
79
99
  if(window.squid && window.squid.engine){ return cb(window.squid); }
80
- if(tries <= 0){ log('sdk', 'the SDK did not load: is this origin allowed on the site?', 'pg-yel'); return render(); }
100
+ if(tries <= 0){ S.sdkFailed = true; log('sdk', 'the SDK did not load: is this origin allowed on the site?', 'pg-yel'); return render(); }
81
101
  setTimeout(() => whenSquid(cb, tries - 1), 100);
82
102
  }
83
103
  whenSquid(squid => {
@@ -114,37 +134,65 @@
114
134
 
115
135
  // ---- actions ----------------------------------------------------------------------------------
116
136
  const A = {
117
- tab(name){ S.tab = name; store.set('tab', name); render(); },
137
+ go(view){ S.view = VIEWS.includes(view) ? view : 'home'; store.set('view', S.view); render(); root.querySelector('.pg-body')?.scrollTo(0, 0); },
138
+ explore(key){ S.explore = key; store.set('explore', key); S.view = 'explore'; store.set('view', 'explore'); render(); },
118
139
  hide(){ S.hidden = true; store.set('hidden', true); document.body.classList.add('pg-panel-hidden'); mountShow(); },
119
140
  again(){
120
- // Replay the reveal: the page loads as a stranger and Sqid resolves the person again. The
121
- // Sandbox pins one person to this device (a new visitor id gets the same person back), so a
122
- // different person needs a private window or another device until the SDK has a reset call.
141
+ // Replay the reveal: the page loads as a stranger and Sqid resolves the same person again.
123
142
  S.log = []; store.sset('log', []); recordFor = null;
124
- sessionStorage.removeItem('rc.exit');
143
+ try{ sessionStorage.removeItem('rc.exit'); }catch(error){ /* ignore */ }
125
144
  location.reload();
126
145
  },
146
+ async someoneNew(btn){
147
+ // Matching is by device, so a private window usually comes back as the same person. On a
148
+ // Sandbox, squid.anonymouse() forgets the made-up identity and the next load gets a new one.
149
+ let squid = window.squid;
150
+ if(!squid || typeof squid.anonymouse !== 'function'){
151
+ S.note = 'This version of the Sqid script cannot reset the visitor. In the console, open this person under Identities and use Forget identity, then reload.';
152
+ return render();
153
+ }
154
+ btn.disabled = true; btn.textContent = 'Resetting…';
155
+ try{
156
+ let r = await squid.anonymouse();
157
+ if(r && r.forgotten === false){
158
+ S.note = 'This is a real site, not the Sandbox: the visitor was marked inactive, but the same person will come back. A new test person is a Sandbox feature.';
159
+ btn.disabled = false; btn.textContent = 'Be someone new'; return render();
160
+ }
161
+ log('reset', 'squid.anonymouse(): identity forgotten, reloading', 'pg-acc');
162
+ S.log = []; store.sset('log', []); recordFor = null;
163
+ location.reload();
164
+ }catch(error){
165
+ S.note = `Could not reset (${error.message}). In the console, open this person under Identities and use Forget identity, then reload.`;
166
+ btn.disabled = false; btn.textContent = 'Be someone new'; render();
167
+ }
168
+ },
127
169
  toggleRecipe(key){ window.SqidRecipes.toggle(key); window.SqidRecipes.apply(S.traits); render(); },
128
170
  showCode(key){ S.code = S.code === key ? null : key; render(); },
129
- copy(text, btn){ navigator.clipboard?.writeText(text).then(() => { btn.textContent = 'Copied'; setTimeout(() => btn.textContent = 'Copy', 1200); }); },
171
+ copy(text, btn){ navigator.clipboard?.writeText(text).then(() => { let was = btn.textContent; btn.textContent = 'Copied'; setTimeout(() => btn.textContent = was, 1200); }); },
130
172
  async addWebhook(form){
131
173
  let url = form.url.value.trim(); let btn = form.querySelector('button[type=submit]'); btn.disabled = true;
174
+ S.hookErr = null;
132
175
  try{ let r = await post('/_sqid/webhooks', { url, event : 'identification' }); S.webhooks = r.webhooks || []; log('webhook', `added ${url}`, 'pg-ok'); form.url.value = ''; }
133
- catch(error){ log('webhook', `could not add: ${error.message}`, 'pg-yel'); }
176
+ catch(error){ S.hookErr = error.message; log('webhook', `could not add: ${error.message}`, 'pg-yel'); }
134
177
  btn.disabled = false; render();
135
178
  },
136
179
  async testWebhook(id, btn){
137
180
  btn.disabled = true; btn.textContent = 'Sending…';
138
- try{ let r = await post(`/_sqid/webhooks/${id}/test`); log('webhook', `test delivery: ${r?.status || r?.response?.status || 'sent'}`, 'pg-ok'); S.lastTest = r; }
139
- catch(error){ log('webhook', `test failed: ${error.message}`, 'pg-yel'); }
140
- btn.disabled = false; btn.textContent = 'Send test'; render();
181
+ try{ let r = await post(`/_sqid/webhooks/${id}/test`); let status = r?.status || r?.response?.status || 'sent'; S.lastTest = { id, ok : true, text : `Test sent. Your app answered: ${status}.` }; log('webhook', `test delivery: ${status}`, 'pg-ok'); }
182
+ catch(error){ S.lastTest = { id, ok : false, text : `The test did not go through: ${error.message}` }; log('webhook', `test failed: ${error.message}`, 'pg-yel'); }
183
+ btn.disabled = false; btn.textContent = 'Send a test'; render();
184
+ },
185
+ async sample(){
186
+ if(S.showSample){ S.showSample = false; return render(); }
187
+ S.showSample = true; render();
188
+ if(!S.sample){ try{ S.sample = await get('/_sqid/sample'); }catch(error){ S.sample = { error : error.message }; } render(); }
141
189
  },
142
- async sample(){ try{ S.sample = await get('/_sqid/sample'); }catch(error){ S.sample = { error : error.message }; } S.showSample = true; render(); },
143
190
  async createSite(form){
144
191
  let btn = form.querySelector('button[type=submit]'); btn.disabled = true; btn.textContent = 'Creating…';
192
+ S.goLiveErr = null;
145
193
  try{ let r = await post('/_sqid/sites', { name : form.name.value.trim(), url : form.url.value.trim() }); S.goLive = { site : r.site, snippet : r.snippet, origins : r.origins, at : Date.now() }; store.set('golive', S.goLive); log('go live', `site "${r.site.name}" created`, 'pg-ok'); pollSite(); }
146
194
  catch(error){ S.goLiveErr = error.message; }
147
- btn.disabled = false; btn.textContent = 'Create site and get my snippet'; render();
195
+ btn.disabled = false; btn.textContent = 'Create my site'; render();
148
196
  },
149
197
  forgetGoLive(){ S.goLive = null; store.set('golive', null); render(); }
150
198
  };
@@ -157,181 +205,202 @@
157
205
  }
158
206
  if(S.goLive && !S.goLive.status?.connected){ pollSite(); }
159
207
 
160
- // ---- svg bits -----------------------------------------------------------------------------------
161
- const ICON = {
162
- done : '<svg width="18" height="18" viewBox="0 0 20 20" role="img" aria-label="done"><circle cx="10" cy="10" r="9" fill="#22d3ee"></circle><path d="M6 10.5l2.5 2.5L14 7.5" stroke="#0b0b0d" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"></path></svg>',
163
- now : '<svg width="18" height="18" viewBox="0 0 20 20" role="img" aria-label="current"><circle cx="10" cy="10" r="8" stroke="#22d3ee" stroke-width="2" fill="none"></circle><circle cx="10" cy="10" r="3" fill="#22d3ee"></circle></svg>',
164
- todo : '<svg width="18" height="18" viewBox="0 0 20 20" role="img" aria-label="pending"><circle cx="10" cy="10" r="8" stroke="#52525b" stroke-width="2" fill="none"></circle></svg>',
165
- arrow: '<svg width="20" height="20" viewBox="0 0 22 22" role="img" aria-label="became"><path d="M3 11h14M12 6l5 5-5 5" stroke="#22d3ee" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"></path></svg>'
166
- };
167
-
168
208
  // ---- render -------------------------------------------------------------------------------------
169
209
  function render(){
170
210
  if(S.hidden){ return; }
171
- let st = S.state;
211
+ // Keep what someone is typing: renders happen on every SDK or page event.
212
+ let typed = [...root.querySelectorAll('input[name]')].map(i => [i.closest('form')?.dataset.form + ':' + i.name, i.value, document.activeElement === i]);
213
+ let body = ({ home : viewHome, send : viewSend, golive : viewGoLive, explore : viewExplore }[S.view] || viewHome)(S.state);
172
214
  root.innerHTML = `
173
215
  <div class="pg-top">
174
- <span class="dot" aria-hidden="true"></span><span class="name">SQID ${cfg.site.sandbox ? 'SANDBOX' : 'SITE'}</span>
175
- <span class="site" title="${esc(cfg.site.id)}">${esc(cfg.site.name || '')}</span>
176
- <span class="conn ${S.connected ? 'on' : ''}"><i></i>${S.connected ? 'Connected' : 'Connecting'}</span>
177
- <button class="pg-btn" data-act="hide" title="Hide the panel">Hide</button>
216
+ <span class="dot" aria-hidden="true"></span><span class="name">Sqid</span>
217
+ <span class="site" title="${esc(cfg.site.id)}">${cfg.site.sandbox ? 'Sandbox' : esc(cfg.site.name || '')}</span>
218
+ <span class="conn ${S.connected ? 'on' : ''}" title="${S.connected ? 'Connected' : 'Connecting'}"><i></i><span class="lbl">${S.connected ? 'Connected' : 'Connecting'}</span></span>
219
+ <button class="pg-btn ghost ${S.view === 'explore' ? 'on' : ''}" data-act="explore" aria-pressed="${S.view === 'explore'}">Explore</button>
220
+ <button class="pg-btn ghost" data-act="hide" title="Hide the panel">Hide</button>
178
221
  </div>
179
- <div class="pg-tabs" role="tablist">${['start', 'live', 'scenarios', 'recipes', 'delivery', 'golive'].map(k => `<button role="tab" aria-selected="${S.tab === k}" data-tab="${k}">${{ start : 'Start', live : 'Live', scenarios : 'Scenarios', recipes : 'Recipes', delivery : 'Delivery', golive : 'Go live' }[k]}</button>`).join('')}</div>
180
- <div class="pg-body">${({ start : tabStart, live : tabLive, scenarios : tabScenarios, recipes : tabRecipes, delivery : tabDelivery, golive : tabGoLive }[S.tab] || tabStart)(st)}</div>`;
222
+ <div class="pg-body">${S.view !== 'home' ? `<button class="pg-back" data-go="home">&larr; Back</button>` : ''}${body}</div>`;
223
+ for(let [key, value, focused] of typed){
224
+ let [form, name] = key.split(':');
225
+ let el = root.querySelector(`form[data-form="${form}"] input[name="${name}"]`);
226
+ if(el){ el.value = value; if(focused){ el.focus(); } }
227
+ }
181
228
  wire();
182
229
  }
183
230
 
231
+ // One line for the five setup checks; the list is behind "Details".
232
+ function status(st){
233
+ let hooks = S.webhooks || [];
234
+ let steps = [
235
+ { t : 'Signed in to Sqid', s : st?.email ? `${st.email}${st.plan?.has ? ` (${st.plan.name || 'Developer'} plan)` : ''}` : st?.error || 'checking…', ok : !!st?.email },
236
+ { t : `${cfg.site.sandbox ? 'Sandbox site' : 'Site'} ready`, s : st?.site ? `${st.site.name}, ${location.origin} allowed` : '…', ok : !!st?.site },
237
+ { t : 'Sqid script on this page', s : S.sdkFailed ? 'It did not load. Add this address to the site\'s allowed origins in the console.' : S.connected ? 'Loaded and connected.' : 'Loading…', ok : S.connected },
238
+ { t : 'Somewhere to send records', s : hooks.length ? `${hooks.length} web address${hooks.length > 1 ? 'es' : ''} (webhooks)` : 'None yet. Optional: "Send this to my app".', ok : hooks.length > 0, optional : true },
239
+ { t : 'A visitor identified', s : S.identified ? 'Yes, on this page.' : 'Happens on the first identification.', ok : !!S.identified }
240
+ ];
241
+ let line, cls;
242
+ if(st?.error){ line = 'Not signed in to Sqid. Restart the playground to sign in.'; cls = 'warn'; }
243
+ else if(S.sdkFailed){ line = 'The Sqid script did not load on this page.'; cls = 'warn'; }
244
+ else if(!S.connected){ line = 'Connecting to Sqid…'; cls = ''; }
245
+ else if(S.identified){ line = `Working. ${cfg.site.sandbox ? 'Test site, no credits used.' : ''}`; cls = 'ok'; }
246
+ else { line = 'Connected. Waiting for the answer…'; cls = ''; }
247
+ return `
248
+ <div class="pg-status ${cls}">
249
+ <i aria-hidden="true"></i><span class="txt">${esc(line)}</span>
250
+ <button class="pg-link" data-act="details" aria-expanded="${S.details}">${S.details ? 'Hide details' : 'Details'}</button>
251
+ </div>
252
+ ${S.details ? `<ul class="pg-checks">${steps.map(x => `<li>${x.ok ? ICON.done : ICON.todo}<div><span class="t">${esc(x.t)}${x.optional ? ' <span class="pg-muted">(optional)</span>' : ''}</span><span class="s">${esc(x.s)}</span></div></li>`).join('')}</ul>` : ''}`;
253
+ }
254
+
184
255
  function reveal(){
185
256
  let v = S.visitor, tr = S.traits;
186
- let anon = `<div class="who anon"><span class="k">Anonymous</span><span class="n">Visitor ${esc(String(v?.meta?.user_id || '').slice(0, 6) || '…')}…</span><span class="m">${esc(deviceLine())}</span></div>`;
257
+ let anon = `<div class="who anon"><span class="k">Anonymous visitor</span><span class="n">No name yet</span><span class="m">${esc(deviceLine())}</span></div>`;
187
258
  let known = S.identified
188
- ? `<div class="who known"><span class="k">Identified${S.timeToId != null ? ` in ${(S.timeToId / 1000).toFixed(2)} s` : ''}</span><span class="n">${esc(cap(tr?.name) || tr?.email || '')}</span><span class="m">${esc([cap(tr?.company_role), cap(tr?.company)].filter(Boolean).join(' · '))}</span></div>`
259
+ ? `<div class="who known"><span class="k">Identified</span><span class="n">${esc(cap(tr?.name) || tr?.email || '')}</span><span class="m">${esc(cap(tr?.company) || '')}</span></div>`
189
260
  : S.identified === false
190
- ? `<div class="who anon"><span class="k">Still anonymous</span><span class="n">Sqid could not identify this visitor</span><span class="m">that happens on real sites too</span></div>`
191
- : `<div class="who anon"><span class="k">Resolving…</span><span class="n">Sqid is looking</span><span class="m">${S.connected ? 'connected, waiting for the answer' : 'connecting'}</span></div>`;
261
+ ? `<div class="who anon"><span class="k">Still anonymous</span><span class="n">Not identified</span><span class="m">that happens on real sites too</span></div>`
262
+ : `<div class="who anon"><span class="k">Looking…</span><span class="n">Sqid is working</span><span class="m">${S.connected ? 'connected' : 'connecting'}</span></div>`;
192
263
  return `<div class="pg-reveal">${anon}${ICON.arrow}${known}</div>`;
193
264
  }
194
- function deviceLine(){ let ua = navigator.userAgent; let dev = /Mobi/.test(ua) ? 'mobile' : 'desktop'; let ref = document.referrer ? new URL(document.referrer).hostname : 'direct'; return `${dev} · ${ref} · ${cfg.path}`; }
265
+ function deviceLine(){ let ua = navigator.userAgent; let dev = /Mobi/.test(ua) ? 'phone' : 'computer'; let ref = 'came in directly'; try{ if(document.referrer){ ref = `from ${new URL(document.referrer).hostname}`; } }catch(error){ /* ignore */ } return `${dev}, ${ref}`; }
195
266
 
196
- function tabStart(st){
197
- let hooks = S.webhooks || [];
198
- let steps = [
199
- { t : 'Signed in to Sqid', s : st?.email ? `${st.email}${st.plan?.has ? ` · ${st.plan.name || 'Developer'} plan` : ''}` : (st?.error ? st.error : 'checking…'), ok : !!st?.email },
200
- { t : `${cfg.site.sandbox ? 'Sandbox' : 'Site'} provisioned`, s : st ? `${st.site.name} · ${location.origin} allowed` : '…', ok : !!st?.site },
201
- { t : 'Script added to layout', s : S.connected ? 'This page loads it. Connected.' : 'This page loads it; waiting for the connection.', ok : S.connected },
202
- { t : 'Webhook wired', s : hooks.length ? `${hooks.length} endpoint${hooks.length > 1 ? 's' : ''} on the site` : 'Where should identified visitors go? Add your endpoint in Delivery, or just watch the record there.', ok : hooks.length > 0, cta : hooks.length ? null : 'delivery' },
203
- { t : 'Stream is live', s : S.identified ? 'A visitor was identified on this page.' : 'Confirmed on the first identification.', ok : !!S.identified }
204
- ];
205
- let firstTodo = steps.findIndex(x => !x.ok);
267
+ function viewHome(st){
268
+ let tr = S.traits;
269
+ let secs = S.timeToId != null ? (S.timeToId / 1000).toFixed(2) : null;
270
+ let headline = S.identified
271
+ ? `Sqid knew who this was${secs ? ` in ${secs} seconds` : ''}.`
272
+ : S.identified === false ? 'Sqid could not tell who this visitor is.' : 'A stranger just opened this page.';
273
+ let rows = S.identified ? [['Name', cap(tr?.name) || tr?.email], ['Company', cap(tr?.company)], ['Title', cap(tr?.company_role)]].filter(r => r[1]) : [];
274
+ let json = S.record ? JSON.stringify(S.record, null, 2) : null;
206
275
  return `
207
- <h2 class="pg-h">Set up Sqid</h2>
208
- <p class="pg-p">Five steps. The site on the left is your test site. Nothing here costs credits.</p>
209
- <ol class="pg-steps">${steps.map((x, i) => `<li class="pg-step ${x.ok ? '' : i === firstTodo ? 'now' : 'todo'}">${x.ok ? ICON.done : i === firstTodo ? ICON.now : ICON.todo}<div class="body"><span class="t">${esc(x.t)}</span><span class="s">${esc(x.s)}</span>${!x.ok && x.cta ? `<div class="pg-row"><button class="pg-btn primary" data-tab="${x.cta}">Open Delivery</button></div>` : ''}</div></li>`).join('')}</ol>
210
- <div class="pg-card">
211
- <div class="pg-row"><span class="pg-label">THIS VISITOR</span><button class="pg-btn grow-0" style="margin-left:auto" data-act="again">Watch it again</button></div>
276
+ ${status(st)}
277
+ <div class="pg-card hi pg-hero">
278
+ <h2 class="pg-h">${esc(headline)}</h2>
212
279
  ${reveal()}
213
- <span class="pg-p" style="font-size:12px">${S.identified ? 'The page loaded as a stranger. Sqid resolved the person and the headline changed. The full record is in Delivery.' : 'The page loaded as a stranger. When Sqid resolves the person, this flips and the headline on the left changes.'}</span>
280
+ ${rows.length ? `<dl class="pg-facts">${rows.map(([k, v]) => `<div><dt>${k}</dt><dd>${esc(v)}</dd></div>`).join('')}</dl>` : `<p class="pg-p small">${S.identified === false ? 'No identity came back for this visitor.' : 'When Sqid works out who it is, their name, company and title appear here, and the site on the left changes its headline.'}</p>`}
281
+ ${S.identified ? `
282
+ <button class="pg-link" data-act="record" aria-expanded="${S.showRecord}">${S.showRecord ? 'Hide the full record' : 'See the full record'}</button>
283
+ ${S.showRecord ? (json
284
+ ? `<pre class="pg-mono pg-scroll" id="pg-record">${esc(json)}</pre><div class="pg-row"><button class="pg-btn" data-copytext="record">Copy</button><span class="pg-muted small">This is what "Send this to my app" delivers.</span></div>`
285
+ : `<p class="pg-p small">${S.recordErr ? `Could not read the record: ${esc(S.recordErr)}` : 'Loading…'}</p>`) : ''}` : ''}
286
+ <div class="pg-row pg-wrap">
287
+ <button class="pg-btn" data-act="someone-new">Be someone new</button>
288
+ <button class="pg-link" data-act="again">Replay</button>
289
+ </div>
290
+ ${S.note ? `<p class="pg-p small pg-yel">${esc(S.note)}</p>` : ''}
291
+ ${cfg.site.sandbox ? '<p class="pg-p small">This is your Sandbox: every visitor is one of fifty made-up test people, and nothing costs credits.</p>' : ''}
214
292
  </div>
215
- <div class="pg-foot">
216
- <span class="pg-label">SAME THING FROM A TERMINAL OR CLAUDE</span>
217
- <pre class="pg-mono">npx -y @sqid-dev/playground
218
- <span class="pg-muted">/sqid:setup in Claude Code</span></pre>
293
+ <div class="pg-next">
294
+ <button class="pg-cta" data-go="send"><span><b>Send this to my app</b><span>Get each identified visitor's record at a web address you choose.</span></span>${ICON.next}</button>
295
+ <button class="pg-cta" data-go="golive"><span><b>Put Sqid on my site</b><span>Create your site and copy one line of code into it.</span></span>${ICON.next}</button>
219
296
  </div>`;
220
297
  }
221
298
 
222
- function tabLive(){
299
+ function viewSend(st){
300
+ let hooks = S.webhooks || [];
223
301
  return `
224
- <div class="pg-row"><h2 class="pg-h">Live</h2><button class="pg-btn" style="margin-left:auto" data-act="clearlog">Clear</button></div>
225
- <p class="pg-p">Everything the SDK and the page did, newest first. Survives navigation within this tab session.</p>
226
- <div class="pg-log">${S.log.length ? S.log.map(e => `<div class="ev"><span class="at">${esc(e.at)}</span><span><span class="k ${esc(e.cls)}">${esc(e.kind)}</span> <span class="d">${esc(e.detail)}</span>${e.page && e.page !== cfg.path ? ` <span class="pg-muted">${esc(e.page)}</span>` : ''}</span></div>`).join('') : '<span class="pg-muted">Nothing yet.</span>'}</div>`;
302
+ <h2 class="pg-h">Send this to my app</h2>
303
+ <p class="pg-p">Each time Sqid identifies a visitor, it sends their record to a web address in your app (a webhook). Any https address works, including a free request catcher if you just want to look.</p>
304
+ ${hooks.length ? `<ul class="pg-list">${hooks.map(h => `<li class="pg-item"><i class="pg-dot ${h.enabled ? 'on' : ''}" aria-hidden="true"></i><span class="pg-url" title="${esc(h.url)}">${esc(h.url)}</span><span class="r"><button class="pg-btn" data-test="${esc(h.id)}">Send a test</button></span></li>${S.lastTest?.id === h.id ? `<li class="pg-p small ${S.lastTest.ok ? 'pg-ok' : 'pg-yel'}">${esc(S.lastTest.text)}</li>` : ''}`).join('')}</ul>` : ''}
305
+ <form class="pg-form" data-form="webhook">
306
+ <label class="pg-muted small" for="pg-hook-url">${hooks.length ? 'Add another address' : 'Your app\'s address'}</label>
307
+ <div class="pg-row"><input class="pg-input" id="pg-hook-url" name="url" type="url" placeholder="https://your-app.com/api/sqid" required><button class="pg-btn primary" type="submit">Add</button></div>
308
+ ${S.hookErr ? `<span class="pg-yel small">${esc(S.hookErr)}</span>` : ''}
309
+ </form>
310
+ <div>
311
+ <button class="pg-link" data-act="sample" aria-expanded="${!!S.showSample}">${S.showSample ? 'Hide the example' : 'See an example of what gets sent'}</button>
312
+ ${S.showSample ? `<pre class="pg-mono pg-scroll" style="margin-top:8px">${S.sample ? esc(JSON.stringify(S.sample, null, 2)) : 'Loading…'}</pre>` : ''}
313
+ </div>
314
+ <p class="pg-p small">Sandbox records are marked <span class="pg-mono">"sandbox": true</span>. Moments (Signals) are only sent from a real site, never from the Sandbox. <a href="https://docs.sqid.dev/sdk/events" target="_blank" rel="noopener">All the fields</a></p>`;
227
315
  }
228
316
 
229
- function tabScenarios(){
230
- let tr = S.traits;
317
+ function viewGoLive(st){
318
+ let g = S.goLive;
231
319
  return `
232
- <div>
233
- <span class="pg-label">WHO YOU ARE</span>
234
- <div class="pg-card hi" style="margin-top:8px">
235
- <div class="pg-row"><div class="grow"><div><b>${esc(cap(tr?.name) || (S.identified === false ? 'Unknown visitor' : 'Resolving…'))}</b></div><div class="pg-muted" style="font-size:12px">${esc(tr ? [cap(tr.company_role), cap(tr.company), tr.email].filter(Boolean).join(' · ') : 'the Sandbox gives every new visitor one made-up person')}</div></div><button class="pg-btn" data-act="again">Watch it again</button></div>
236
- </div>
237
- <p class="pg-p" style="font-size:12px;margin-top:8px">Sandbox test people, like Stripe test cards. Real sites resolve real people; the Sandbox hands out one of fifty and never spends a credit. This device keeps its person; a private window or another device gets a different one.</p>
238
- </div>
239
- <div>
240
- <span class="pg-label">THINGS TO TRY</span>
241
- <ul class="pg-list" style="margin-top:8px">${SCENARIOS.map(s => { let on = s.where === cfg.path; return `<li class="pg-item ${on && !S.done[s.id] ? 'now' : ''}">${S.done[s.id] ? ICON.done : on ? ICON.now : ICON.todo}<span>${esc(s.t)}</span><span class="r">${S.done[s.id] ? 'done' : s.where ? (on ? '<span class="pg-acc">this page</span>' : `<a href="${s.where}">${esc(s.label)}</a>`) : esc(s.label)}</span></li>`; }).join('')}</ul>
242
- </div>
320
+ <h2 class="pg-h">Put Sqid on my site</h2>
321
+ ${g ? `
322
+ <p class="pg-p">Your site <b class="pg-strong">${esc(g.site.name)}</b> is ready for ${esc(g.origins.join(', '))}. Paste this just before <span class="pg-mono">&lt;/head&gt;</span> on every page, publish, then open your site once.</p>
323
+ <pre class="pg-mono" id="pg-snippet">${esc(g.snippet)}</pre>
324
+ <div class="pg-row pg-wrap"><button class="pg-btn primary" data-copytext="snippet">Copy the code</button><span class="small" style="color:${g.status?.connected ? '#4ade80' : '#a1a1aa'}">${g.status?.connected ? 'Connected. Your site is live.' : g.status?.deployed ? 'Seen a page view, connecting…' : 'Waiting for the first visit…'}</span></div>
325
+ <div class="pg-row pg-wrap"><a href="${esc(CONSOLE())}" target="_blank" rel="noopener" class="small">Open the console</a><button class="pg-link" data-act="forget">Start over</button></div>`
326
+ : `
327
+ <p class="pg-p">Give your website's address. Sqid adds the site to your account and gives you one line of code to paste into it.</p>
328
+ <form class="pg-form" data-form="site">
329
+ <label class="pg-muted small">Website address<input class="pg-input" name="url" type="url" placeholder="https://www.yourcompany.com" required></label>
330
+ <label class="pg-muted small">Name (optional)<input class="pg-input" name="name" type="text" placeholder="Marketing site" maxlength="50"></label>
331
+ <button class="pg-btn primary big" type="submit">Create my site</button>
332
+ ${S.goLiveErr ? `<span class="pg-yel small">${esc(S.goLiveErr)}</span>` : ''}
333
+ </form>`}
243
334
  <div class="pg-card">
244
- <span class="pg-label">WHAT THE SDK SAW HERE</span>
245
- <div class="pg-log">${S.log.filter(e => e.page === cfg.path).slice(0, 6).map(e => `<div class="ev"><span class="at">${esc(e.at)}</span><span><span class="k ${esc(e.cls)}">${esc(e.kind)}</span> <span class="d">${esc(e.detail)}</span></span></div>`).join('') || '<span class="pg-muted">Nothing on this page yet.</span>'}</div>
246
- <span class="pg-p" style="font-size:12px">On a real site with Signals on, these shapes become moments (choosing_options, form_stall, cart_stall, deliberation). The Sandbox shows the raw behaviour only.</span>
247
- </div>`;
335
+ <b>Paying for it</b>
336
+ <p class="pg-p small">The Sandbox is free. A real site uses prepaid credits on the Developer plan: $0.25 each. Add a card and you get 25 welcome credits. Nothing is charged unless you buy credits or turn on auto-reload. With no credits left, your site stops identifying new visitors until you add more.</p>
337
+ <div class="pg-row pg-wrap"><a class="pg-btn accent" href="${esc(CONSOLE())}/billing" target="_blank" rel="noopener">Add a card</a><a href="https://sqid.dev/pricing" target="_blank" rel="noopener" class="small">Pricing</a></div>
338
+ </div>
339
+ <button class="pg-link" data-act="more" aria-expanded="${!!S.showMore}">${S.showMore ? 'Hide other ways' : 'Other ways: from my code editor, or inside my product'}</button>
340
+ ${S.showMore ? `
341
+ <div class="pg-card">
342
+ <b>From my code editor</b>
343
+ <p class="pg-p small">Claude Code adds the code to your layout and writes the webhook handler for your framework.</p>
344
+ <pre class="pg-mono">claude mcp add --transport http sqid https://mcp.sqid.dev/mcp
345
+ /sqid:setup</pre>
346
+ <pre class="pg-mono">npx -y @sqid-dev/sqid init</pre>
347
+ </div>
348
+ <div class="pg-card">
349
+ <b>Inside my product</b>
350
+ <p class="pg-p small">Identify visitors in your own app or on your customers' sites, with the visitor API and server-side enrichment. Reselling it is the OEM plan: OEM Launch is $675/month with 500 identifications/month included.</p>
351
+ <div class="pg-row pg-wrap"><a href="https://docs.sqid.dev/api-reference/overview" target="_blank" rel="noopener" class="small">API reference</a><a href="https://sqid.dev/#oem" target="_blank" rel="noopener" class="small">OEM plan</a></div>
352
+ </div>` : ''}`;
248
353
  }
249
354
 
250
- function tabRecipes(){
251
- let R = window.SqidRecipes, on = R.enabled();
252
- let open = S.code && R.all[S.code] ? S.code : null;
355
+ function viewExplore(){
356
+ let body = ({ live : exLive, scenarios : exScenarios, recipes : exRecipes }[S.explore] || exLive)();
253
357
  return `
254
- <p class="pg-p">Turn a recipe on and this site changes. Each one is the code from the docs, running against the live profile.</p>
255
- <ul class="pg-list">${Object.entries(R.all).map(([k, r]) => `<li class="pg-item ${open === k ? 'now' : ''}" style="cursor:pointer" data-code="${k}"><button class="pg-toggle ${on.includes(k) && !r.locked ? 'on' : ''}" data-recipe="${k}" ${r.locked ? 'disabled' : ''} aria-label="toggle ${esc(r.title)}"><i></i></button><span>${esc(r.title)}</span><span class="r ${r.locked ? 'pg-yel' : ''}">${esc(r.where)}</span></li>`).join('')}</ul>
256
- ${open ? `<div>
257
- <div class="pg-row"><span class="pg-label">${esc(R.all[open].title.toUpperCase())}</span><a href="${R.all[open].docs}" target="_blank" rel="noopener" style="margin-left:auto;font-size:12px">Docs</a><button class="pg-btn" data-copy="${open}">Copy</button></div>
258
- <pre class="pg-mono" style="margin-top:8px">${esc(R.all[open].code)}</pre>
259
- <span class="pg-p" style="font-size:12px;display:block;margin-top:6px">${R.all[open].locked ? 'Sandbox sites never receive moments. Add a card and put Sqid on a real site to see this one fire.' : S.traits ? `Running with ${esc(cap(S.traits.name) || S.traits.email)}'s profile. Click "Be someone else" in Scenarios to see it change.` : 'Waiting for an identified visitor.'}</span>
260
- </div>` : '<span class="pg-muted">Click a recipe to see its code.</span>'}`;
358
+ <div class="pg-seg" role="tablist">${Object.entries(EXPLORE).map(([k, t]) => `<button role="tab" aria-selected="${S.explore === k}" data-explore="${k}">${t}</button>`).join('')}</div>
359
+ ${body}`;
261
360
  }
262
361
 
263
- function tabDelivery(st){
264
- let rec = S.record;
265
- let json = rec ? JSON.stringify(rec, null, 2) : null;
266
- let hooks = S.webhooks || [];
362
+ function exLive(){
267
363
  return `
268
- <div>
269
- <span class="pg-label">WHERE IT GOES</span>
270
- <ul class="pg-list" style="margin-top:8px">
271
- ${hooks.map(h => `<li class="pg-item"><i style="width:8px;height:8px;border-radius:4px;background:${h.enabled ? '#4ade80' : '#52525b'};flex-shrink:0"></i><span style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap" title="${esc(h.url)}">${esc(h.url)}</span><span class="r"><button class="pg-btn" data-test="${esc(h.id)}">Send test</button></span></li>`).join('')}
272
- <li class="pg-item"><form class="pg-row grow" data-form="webhook" style="width:100%"><input class="pg-input" name="url" type="url" placeholder="https://your-app.com/api/sqid" required><button class="pg-btn primary" type="submit">Add</button></form></li>
273
- </ul>
274
- <span class="pg-p" style="font-size:12px;display:block;margin-top:6px">Any https endpoint works, a request catcher included. Identified visitors on this site are delivered there as the record below.</span>
275
- </div>
276
- <div>
277
- <div class="pg-row"><span class="pg-label">THIS VISITOR'S RECORD</span><span class="pg-mono pg-acc" style="font-size:11px">${rec ? 'profile ' + esc(String(S.visitor?.meta?.user_id || '').slice(0, 8)) + '…' : ''}</span>${json ? `<button class="pg-btn" style="margin-left:auto" data-copytext="record">Copy JSON</button>` : ''}</div>
278
- ${json ? `<pre class="pg-mono" style="margin-top:8px;max-height:360px;overflow:auto" id="pg-record">${esc(json)}</pre>` : `<span class="pg-p" style="font-size:12px;display:block;margin-top:8px">${S.recordErr ? `Could not read the record: ${esc(S.recordErr)}` : S.identified ? 'Loading from the visitor API…' : 'Appears once this visitor is identified. It is the same record a webhook delivers.'}</span>`}
279
- <div class="pg-row" style="margin-top:8px"><button class="pg-btn" data-act="sample">Show a webhook sample</button><a href="https://docs.sqid.dev/sdk/events" target="_blank" rel="noopener" style="margin-left:auto;font-size:12px">All the fields</a></div>
280
- ${S.showSample ? `<pre class="pg-mono" style="margin-top:8px;max-height:280px;overflow:auto">${esc(JSON.stringify(S.sample, null, 2))}</pre>` : ''}
281
- </div>
282
- <div class="pg-card warn">
283
- <span class="pg-label">MOMENTS ARE OFF IN THE SANDBOX</span>
284
- <span class="pg-p" style="font-size:12px;color:#d4d4d8">Add a card to start the free credit and Signals turns on for your real site. The form stall or cart stall you cause here would then arrive as a moment with an instruction for your agent.</span>
285
- <div class="pg-row"><a class="pg-btn yellow" href="${esc(st?.console || 'https://app.sqid.dev')}/billing" target="_blank" rel="noopener" style="display:inline-flex;align-items:center;color:#0b0b0d">Start free credit</a><a href="https://docs.sqid.dev/guides/signals" target="_blank" rel="noopener" style="font-size:12px">About moments</a></div>
286
- </div>`;
364
+ <div class="pg-row"><p class="pg-p grow">Everything the Sqid script and the page did, newest first.</p><button class="pg-btn" data-act="clearlog">Clear</button></div>
365
+ <div class="pg-log">${S.log.length ? S.log.map(e => `<div class="ev"><span class="at">${esc(e.at)}</span><span><span class="k ${esc(e.cls)}">${esc(e.kind)}</span> <span class="d">${esc(e.detail)}</span>${e.page && e.page !== cfg.path ? ` <span class="pg-muted">${esc(e.page)}</span>` : ''}</span></div>`).join('') : '<span class="pg-muted">Nothing yet.</span>'}</div>`;
287
366
  }
288
367
 
289
- function tabGoLive(st){
290
- let g = S.goLive;
368
+ function exScenarios(){
291
369
  return `
292
- <h2 class="pg-h">Put Sqid on your own thing</h2>
293
- <p class="pg-p">Same account, same snippet shape. Three ways in; each ends with the stream live and real identifications arriving.</p>
294
- <div class="pg-card hi">
295
- <div class="pg-row"><b>My website</b><span class="r pg-acc" style="margin-left:auto;font-size:11px">most people</span></div>
296
- ${g ? `
297
- <div class="pg-p" style="font-size:12px">Site <b style="color:#fafafa">${esc(g.site.name)}</b> created for ${esc(g.origins.join(', '))}. Paste this before &lt;/head&gt; on every page, deploy, open the site once.</div>
298
- <pre class="pg-mono" id="pg-snippet">${esc(g.snippet)}</pre>
299
- <div class="pg-row"><button class="pg-btn primary" data-copytext="snippet">Copy snippet</button><span class="pg-mono" style="font-size:11px;color:${g.status?.connected ? '#4ade80' : '#a1a1aa'}">${g.status?.connected ? 'Connected: the stream is live' : g.status?.deployed ? 'Page view seen, waiting for the connection…' : 'Waiting for the first page view…'}</span><button class="pg-btn" style="margin-left:auto" data-act="forget">Done</button></div>
300
- <a href="${esc(st?.console || 'https://app.sqid.dev')}" target="_blank" rel="noopener" style="font-size:12px">Open the console</a>`
301
- : `
302
- <form data-form="site" style="display:flex;flex-direction:column;gap:8px">
303
- <label class="pg-muted" style="font-size:12px">Public URL<input class="pg-input" name="url" type="url" placeholder="https://www.yourcompany.com" required style="margin-top:4px"></label>
304
- <label class="pg-muted" style="font-size:12px">Name (optional)<input class="pg-input" name="name" type="text" placeholder="Marketing site" maxlength="50" style="margin-top:4px"></label>
305
- <button class="pg-btn primary" type="submit">Create site and get my snippet</button>
306
- ${S.goLiveErr ? `<span class="pg-yel" style="font-size:12px">${esc(S.goLiveErr)}</span>` : ''}
307
- </form>
308
- <span class="pg-p" style="font-size:12px">Makes the site on your account, shows the one script tag, then waits here for the first real page view.</span>`}
309
- </div>
370
+ <p class="pg-p">Things to do on the site on the left. Each one shows up under Live events as Sqid sees it.</p>
371
+ <ul class="pg-list">${SCENARIOS.map(s => { let on = s.where === cfg.path; return `<li class="pg-item ${on && !S.done[s.id] ? 'now' : ''}">${S.done[s.id] ? ICON.done : on ? ICON.now : ICON.todo}<span class="grow">${esc(s.t)}</span><span class="r">${S.done[s.id] ? 'done' : s.where ? (on ? '<span class="pg-acc">this page</span>' : `<a href="${s.where}">${esc(s.label)}</a>`) : esc(s.label)}</span></li>`; }).join('')}</ul>
310
372
  <div class="pg-card">
311
- <b>My app, from my editor</b>
312
- <span class="pg-p" style="font-size:12px">Claude Code pastes the snippet into your layout and writes the webhook handler in your framework.</span>
313
- <pre class="pg-mono">claude mcp add --transport http sqid https://mcp.sqid.dev/mcp
314
- /sqid:setup</pre>
315
- <pre class="pg-mono">npx -y @sqid-dev/sqid init</pre>
316
- </div>
317
- <div class="pg-card">
318
- <b>Embedded in my product</b>
319
- <span class="pg-p" style="font-size:12px">Identify visitors inside your own app or on your customers' sites. Server-side enrichment, the visitor API, and OEM terms for resale.</span>
320
- <div class="pg-row"><a href="https://docs.sqid.dev/api-reference/overview" target="_blank" rel="noopener" style="font-size:12px">API reference</a><a href="https://sqid.dev/#oem" target="_blank" rel="noopener" style="font-size:12px">OEM program</a></div>
321
- </div>
322
- <div class="pg-card" style="background:#0e2a30;border-color:#155e75">
323
- <div class="pg-row"><b>${esc(st?.plan?.name || 'Developer')} plan${st?.plan?.has ? '' : ' (starts with your first site)'}</b><span class="r" style="margin-left:auto;color:#a5f3fc">${st?.plan?.has ? 'you are on it' : 'free'}</span></div>
324
- <span class="pg-p" style="font-size:12px;color:#d4d4d8">Real identifications start as soon as your site connects. Add a card to unlock the free credit, moments, and higher caps. No charge until you use it.</span>
325
- <div class="pg-row"><a class="pg-btn accent" href="${esc(st?.console || 'https://app.sqid.dev')}/billing" target="_blank" rel="noopener" style="display:inline-flex;align-items:center;color:#0b0b0d">Add a card</a><a href="https://sqid.dev/pricing" target="_blank" rel="noopener" style="font-size:12px">Compare plans</a></div>
373
+ <span class="pg-label">ON THIS PAGE</span>
374
+ <div class="pg-log">${S.log.filter(e => e.page === cfg.path).slice(0, 6).map(e => `<div class="ev"><span class="at">${esc(e.at)}</span><span><span class="k ${esc(e.cls)}">${esc(e.kind)}</span> <span class="d">${esc(e.detail)}</span></span></div>`).join('') || '<span class="pg-muted">Nothing on this page yet.</span>'}</div>
375
+ <p class="pg-p small">On a real site with Signals on, these become moments (choosing_options, form_stall, cart_stall, deliberation). The Sandbox never sends moments; it shows the raw behaviour only.</p>
326
376
  </div>`;
327
377
  }
328
378
 
379
+ function exRecipes(){
380
+ let R = window.SqidRecipes, on = R.enabled();
381
+ let open = S.code && R.all[S.code] ? S.code : null;
382
+ return `
383
+ <p class="pg-p">Turn a recipe on and the site changes. Each one is the code from the docs, running on this visitor.</p>
384
+ <ul class="pg-list">${Object.entries(R.all).map(([k, r]) => `<li class="pg-item ${open === k ? 'now' : ''}" style="cursor:pointer" data-code="${k}"><button class="pg-toggle ${on.includes(k) && !r.locked ? 'on' : ''}" data-recipe="${k}" ${r.locked ? 'disabled' : ''} aria-label="toggle ${esc(r.title)}"><i></i></button><span class="grow">${esc(r.title)}</span><span class="r ${r.locked ? 'pg-yel' : ''}">${esc(r.where)}</span></li>`).join('')}</ul>
385
+ ${open ? `<div>
386
+ <div class="pg-row"><span class="pg-label grow">${esc(R.all[open].title.toUpperCase())}</span><a href="${R.all[open].docs}" target="_blank" rel="noopener" class="small">Docs</a><button class="pg-btn" data-copy="${open}">Copy</button></div>
387
+ <pre class="pg-mono" style="margin-top:8px">${esc(R.all[open].code)}</pre>
388
+ <p class="pg-p small" style="margin-top:6px">${R.all[open].locked ? 'The Sandbox never sends moments. Put Sqid on a real site and turn Signals on to see this one fire.' : S.traits ? `Running with ${esc(cap(S.traits.name) || S.traits.email)}'s profile. "Be someone new" on the first screen changes it.` : 'Waiting for an identified visitor.'}</p>
389
+ </div>` : '<span class="pg-muted small">Click a recipe to see its code.</span>'}`;
390
+ }
391
+
329
392
  // ---- wiring ---------------------------------------------------------------------------------------
330
393
  function wire(){
331
- root.querySelectorAll('[data-tab]').forEach(b => b.addEventListener('click', () => A.tab(b.dataset.tab)));
394
+ root.querySelectorAll('[data-go]').forEach(b => b.addEventListener('click', () => A.go(b.dataset.go)));
395
+ root.querySelectorAll('[data-explore]').forEach(b => b.addEventListener('click', () => A.explore(b.dataset.explore)));
332
396
  root.querySelectorAll('[data-act]').forEach(b => b.addEventListener('click', () => {
333
397
  let a = b.dataset.act;
334
398
  if(a === 'hide'){ A.hide(); } if(a === 'again'){ A.again(); } if(a === 'sample'){ A.sample(); } if(a === 'forget'){ A.forgetGoLive(); }
399
+ if(a === 'someone-new'){ A.someoneNew(b); }
400
+ if(a === 'explore'){ A.go(S.view === 'explore' ? 'home' : 'explore'); }
401
+ if(a === 'details'){ S.details = !S.details; render(); }
402
+ if(a === 'record'){ S.showRecord = !S.showRecord; render(); }
403
+ if(a === 'more'){ S.showMore = !S.showMore; render(); }
335
404
  if(a === 'clearlog'){ S.log = []; store.sset('log', []); render(); }
336
405
  }));
337
406
  root.querySelectorAll('[data-recipe]').forEach(b => b.addEventListener('click', e => { e.stopPropagation(); A.toggleRecipe(b.dataset.recipe); }));
package/public/recipes.js CHANGED
@@ -7,7 +7,6 @@
7
7
  const cap = (s) => String(s || '').replace(/\b[a-z]/g, c => c.toUpperCase());
8
8
  const first = (v) => cap(v?.firstName || (v?.name || '').split(' ')[0] || '') || null;
9
9
  const company = (v) => v?.company ? cap(v.company) : null;
10
- const sizeOf = (v) => v?.company_size || v?.job_company_size || null;
11
10
 
12
11
  const RECIPES = {
13
12
  dom : {
@@ -34,31 +33,37 @@ engine.on('visitor.unknown', () => {
34
33
  },
35
34
  pricing : {
36
35
  title : 'Pricing personalisation', where : '/pricing', docs : 'https://docs.sqid.dev/recipes/pricing-personalization',
37
- code : `const engine = new squid.engine();
36
+ code : `// Sqid tells you who the visitor is. Which plan fits them is your data:
37
+ // route the profile through your backend and let it answer.
38
+ const engine = new squid.engine({ sp: 'https://api.example.com' });
38
39
 
39
40
  engine.on('visitor.identified', (e) => {
40
- const v = e.detail;
41
- const size = v.company_size || '';
42
- const team = /^(1[01]-|51-|201-)/.test(size); // 10 to 500 people
43
- document.querySelector('#pricing-title').textContent = \`Team pricing for \${v.company}\`;
44
- document.querySelector('#plan-team').classList.toggle('featured', team);
41
+ const v = e.detail; // Sqid's traits + your fields
42
+ document.querySelector('#pricing-title').textContent = \`Pricing for \${v.company}\`;
43
+ document.querySelector(\`#plan-\${v.accountType.toLowerCase()}\`).classList.add('featured');
45
44
  });`,
46
45
  apply(v, on){
47
46
  if(page() !== 'pricing'){ return; }
47
+ this._on = on;
48
48
  let t = document.getElementById('pricing-title'), s = document.getElementById('pricing-sub'), pill = document.getElementById('pricing-pill');
49
- let team = document.getElementById('plan-team'), badge = document.getElementById('plan-team-badge'), ent = document.getElementById('plan-enterprise');
50
- let size = sizeOf(v) || '';
51
- let big = /^(1001|5001|10001)/.test(size), mid = /^(11-|51-|201-|501-)/.test(size);
52
- if(v && on){
53
- t.textContent = `Team pricing for ${company(v)}`;
54
- s.textContent = big ? `Companies your size usually roll out by floor. Enterprise is where ${company(v)} fits.` : mid ? `Teams of ${size} get volume pricing and a dedicated account manager.` : `Start with one desk; the Team tier is there when ${company(v)} grows.`;
49
+ let plans = { starter : document.getElementById('plan-starter'), team : document.getElementById('plan-team'), enterprise : document.getElementById('plan-enterprise') };
50
+ let badge = document.getElementById('plan-team-badge');
51
+ const reset = () => { t.textContent = t.dataset.default; s.textContent = s.dataset.default; pill.classList.add('hidden'); badge.classList.add('hidden'); Object.values(plans).forEach(p => p.classList.remove('featured')); };
52
+ const show = (d) => {
53
+ if(!this._on){ return; }
54
+ let plan = String(d.accountType || '').toLowerCase();
55
+ t.textContent = `Pricing for ${company(d)}`;
56
+ s.textContent = `Your account is on ${d.accountType}. (That came from the mock "your database", not from Sqid: Sqid supplied who you are.)`;
55
57
  pill.classList.remove('hidden');
56
- team.classList.toggle('featured', mid); badge.classList.toggle('hidden', !mid);
57
- ent.classList.toggle('featured', big);
58
- } else {
59
- t.textContent = t.dataset.default; s.textContent = s.dataset.default; pill.classList.add('hidden');
60
- team.classList.remove('featured'); badge.classList.add('hidden'); ent.classList.remove('featured');
61
- }
58
+ Object.entries(plans).forEach(([k, el]) => el.classList.toggle('featured', k === plan));
59
+ badge.classList.toggle('hidden', plan !== 'team');
60
+ };
61
+ if(!(v && on)){ reset(); return; }
62
+ if(this._last){ show(this._last); }
63
+ if(this._engine || !window.squid?.engine){ return; }
64
+ // The same service-provider pattern the docs recipe uses, against the playground's mock backend.
65
+ this._engine = new window.squid.engine({ sp : location.origin + '/_sqid/sp' });
66
+ this._engine.on('visitor.identified', e => { this._last = e.detail; show(e.detail); });
62
67
  }
63
68
  },
64
69
  chat : {
@@ -128,15 +133,16 @@ document.addEventListener('mouseleave', (e) => {
128
133
 
129
134
  engine.on('visitor.identified', (e) => {
130
135
  const v = e.detail;
131
- // GA4 / Segment / Mixpanel / Amplitude / PostHog: one identify call each
132
- window.gtag?.('set', 'user_properties', { company: v.company, role: v.company_role });
133
- window.analytics?.identify(v.id, { email: v.email, company: v.company });
134
- window.posthog?.identify(v.id, { email: v.email });
136
+ const uid = v.id || engine.visitor().meta.user_id; // your id if you set one, else Sqid's
137
+ // Segment / Mixpanel / Amplitude / PostHog: one identify call each
138
+ window.analytics?.identify(uid, { email: v.email, company: v.company, title: v.company_role });
139
+ window.posthog?.identify(uid, { email: v.email, company: v.company });
135
140
  });`,
136
141
  apply(v, on){
137
142
  if(!(v && on)){ return; }
138
- console.log('[analytics] identify', { id : v.id, email : v.email, company : v.company, role : v.company_role });
139
- document.dispatchEvent(new CustomEvent('sqid:recipe', { detail : { recipe : 'analytics', text : `identify(${v.id}) sent to the analytics stubs (see the console)` } }));
143
+ let uid = v.id || document.cookie.match(/squid_vid=([^;]+)/)?.[1] || null;
144
+ console.log('[analytics] identify', uid, { email : v.email, company : v.company, title : v.company_role });
145
+ document.dispatchEvent(new CustomEvent('sqid:recipe', { detail : { recipe : 'analytics', text : `identify(${uid}) sent to the analytics stubs (see the browser console)` } }));
140
146
  }
141
147
  },
142
148
  sp : {
package/src/index.js CHANGED
@@ -53,7 +53,12 @@ export async function main(argv){
53
53
  let ready = await bridge.prepare(origin); // signs in if needed, finds the Sandbox, allows the origin
54
54
  process.stdout.write(` Signed in as ${ready.email}\n`);
55
55
  process.stdout.write(` Site: ${ready.site.name} (${ready.site.id})${ready.site.sandbox ? ', Sandbox' : ''}\n`);
56
- process.stdout.write(` Origin ${origin} ${ready.originAdded ? 'allowed on the site' : 'already allowed'}\n`);
56
+ if(ready.originError){
57
+ process.stdout.write(` Could not check the site's allowed origins (${ready.originError}). Nothing was changed.\n`);
58
+ process.stdout.write(` If the panel says the SDK did not load, add ${origin} to the site in the console (SDKs, allowed origins).\n`);
59
+ }else{
60
+ process.stdout.write(` Origin ${origin} ${ready.originAdded ? 'added to the site (its other origins are kept)' : 'already allowed'}\n`);
61
+ }
57
62
 
58
63
  let app = createApp(bridge);
59
64
  let server = createServer(app);
package/src/sqid.js CHANGED
@@ -12,53 +12,88 @@ import { loginLoopback, userinfo } from '@sqid-dev/sqid/src/oauth.js';
12
12
 
13
13
  const base = (site, ev) => `${ev.v2 ? '/api/v2' : '/api'}/projects/${site.id}`;
14
14
 
15
- // Sites with their allowed origins (the CLI's siteRow leaves origins out).
16
- async function listSites(flags){
17
- let rows = await api('GET', '/api/sqid/projects', { flags });
18
- return (rows || []).map(p => ({ ...siteRow(p), origins : (p.site_origins || []).map(String) }));
15
+ // A site's allowed origins live in its jwt (payload.site and payload.app, comma-separated): that is
16
+ // how the console's own edit page reads them. Neither GET /api/sqid/projects nor GET /api/projects/:id
17
+ // returns a site_origins field, so reading one gives an empty list, and writing that back wipes
18
+ // the origins set in the console.
19
+ export function originsOf(project){
20
+ let token = String(project?.jwt || '').split('.')[1];
21
+ if(!token){ return null; }
22
+ try{
23
+ let payload = JSON.parse(Buffer.from(token.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'));
24
+ const list = (v) => String(v || '').split(',').map(s => s.trim()).filter(Boolean);
25
+ return { site : list(payload.site), app : list(payload.app) };
26
+ }catch(error){ return null; }
27
+ }
28
+
29
+ // Add `origin` to both lists when missing; never removes or reorders anything.
30
+ // Returns null when nothing needs to change.
31
+ export function withOrigin(current, origin){
32
+ let site = [...(current?.site || [])], app = [...(current?.app || [])];
33
+ if(site.includes(origin) && app.includes(origin)){ return null; }
34
+ if(!site.includes(origin)){ site.push(origin); }
35
+ if(!app.includes(origin)){ app.push(origin); }
36
+ return { site, app };
37
+ }
38
+
39
+ // Sites, with the origins their jwt allows (the CLI's siteRow leaves origins out).
40
+ async function listSites(flags, call = api){
41
+ let rows = await call('GET', '/api/sqid/projects', { flags });
42
+ return (rows || []).map(p => ({ ...siteRow(p), origins : originsOf(p)?.site || [] }));
19
43
  }
20
44
 
21
45
  export class Bridge {
22
- constructor(flags = {}){
46
+ // `deps` swaps the API and credential reads in tests; normally the CLI's own.
47
+ constructor(flags = {}, deps = {}){
23
48
  this.flags = flags;
49
+ this.api = deps.api || api;
50
+ this.readCredentials = deps.readCredentials || readCredentials;
24
51
  this.site = null;
25
52
  this.me = null;
26
53
  }
27
54
 
28
55
  // Sign in if needed, pick the site, allow this origin on it.
29
56
  async prepare(origin){
30
- let creds = await readCredentials();
57
+ let creds = await this.readCredentials();
31
58
  if(!creds?.access_token){
32
59
  process.stdout.write(' Not signed in to Sqid. Opening your browser to sign in...\n');
33
60
  let tokens = await loginLoopback({ onUrl : (url, { opened }) => process.stdout.write(opened ? ` If it did not open: ${url}\n` : ` Open this link to sign in: ${url}\n`) });
34
61
  let info = await userinfo(tokens.access_token).catch(() => null);
35
62
  await writeCredentials({ ...tokens, email : info?.email, user_id : info?.sub || info?.user_id, issued_on : os.hostname(), issued_at : new Date().toISOString() });
36
- creds = await readCredentials();
63
+ creds = await this.readCredentials();
37
64
  }
38
- this.me = await api('GET', '/api/sqid/me', { flags : this.flags });
65
+ this.me = await this.api('GET', '/api/sqid/me', { flags : this.flags });
39
66
 
40
- let sites = await listSites(this.flags);
67
+ let sites = await listSites(this.flags, this.api);
41
68
  let site = this.flags.site ? sites.find(s => s.id === this.flags.site || s.name === this.flags.site) : sites.find(s => s.sandbox);
42
69
  if(this.flags.site && !site){ throw Object.assign(new Error(`No site "${this.flags.site}" on this account.`), { exit : 2 }); }
43
70
  if(!site){
44
71
  // The account has no Sandbox (deleted, or an older account): make it again.
45
- let made = await api('POST', '/api/sqid/sandbox', { flags : this.flags, body : {} });
46
- sites = await listSites(this.flags);
72
+ let made = await this.api('POST', '/api/sqid/sandbox', { flags : this.flags, body : {} });
73
+ sites = await listSites(this.flags, this.api);
47
74
  site = sites.find(s => s.id === String(made?.sdk_id)) || sites.find(s => s.sandbox);
48
75
  if(!site){ throw new Error('Sqid did not return a Sandbox site.'); }
49
76
  }
50
77
  this.site = site;
51
78
 
52
79
  // Allow this origin on the site (the snippet loads nothing from an origin the site does not list).
53
- let originAdded = false;
54
- let current = (site.origins || []).map(String);
55
- if(!current.includes(origin)){
56
- let next = toOrigins([...current, origin].join(','));
57
- await api('PATCH', `/api/projects/${site.id}`, { flags : this.flags, body : { name : site.name, site_origins : next, product_origins : next } });
58
- this.site = { ...site, origins : next };
59
- originAdded = true;
80
+ // Read the current lists from the site itself and only add; if they cannot be read, write nothing.
81
+ let originAdded = false, originError = null;
82
+ let current = null;
83
+ try{ current = originsOf(await this.api('GET', `/api/projects/${site.id}`, { flags : this.flags })); }
84
+ catch(error){ originError = error.message; }
85
+ if(!current){
86
+ originError = originError || 'could not read the site\'s allowed origins';
87
+ }else{
88
+ let next = withOrigin(current, origin);
89
+ if(next){
90
+ await this.api('PATCH', `/api/projects/${site.id}`, { flags : this.flags, body : { name : site.name, site_origins : next.site, product_origins : next.app } });
91
+ current = next;
92
+ originAdded = true;
93
+ }
94
+ this.site = { ...site, origins : current.site };
60
95
  }
61
- return { email : this.me?.email || this.me?.user?.email || creds?.email || 'you', site : this.site, originAdded };
96
+ return { email : this.me?.email || this.me?.user?.email || creds?.email || 'you', site : this.site, originAdded, originError };
62
97
  }
63
98
 
64
99
  snippet(id = this.site.id){ return snippetFor(id); }
@@ -66,7 +101,7 @@ export class Bridge {
66
101
  // What the panel's Start tab needs, in one call.
67
102
  async state(){
68
103
  let [me, hooks] = await Promise.all([
69
- api('GET', '/api/sqid/me', { flags : this.flags }).catch(() => this.me),
104
+ this.api('GET', '/api/sqid/me', { flags : this.flags }).catch(() => this.me),
70
105
  this.webhooks().catch(() => [])
71
106
  ]);
72
107
  this.me = me || this.me;
@@ -82,14 +117,14 @@ export class Bridge {
82
117
  }
83
118
 
84
119
  async webhooks(){
85
- let r = await api('GET', `/api/sqid/sdks/${this.site.id}/webhooks`, { flags : this.flags });
120
+ let r = await this.api('GET', `/api/sqid/sdks/${this.site.id}/webhooks`, { flags : this.flags });
86
121
  let list = Array.isArray(r) ? r : r?.webhooks || [];
87
122
  return list.map(w => ({ id : String(w._id || w.id), url : w.url, event : w.namespace || w.event, enabled : w.enabled !== false, health : w.health || null, name : w.name || null }));
88
123
  }
89
124
 
90
125
  async addWebhook(url, eventKey = 'identification'){
91
126
  let ev = EVENTS[eventKey] || EVENTS.identification;
92
- return api('POST', `${base(this.site, ev)}/webhook`, { flags : this.flags, body : { url, namespace : ev.namespace, name : 'Playground' } });
127
+ return this.api('POST', `${base(this.site, ev)}/webhook`, { flags : this.flags, body : { url, namespace : ev.namespace, name : 'Playground' } });
93
128
  }
94
129
 
95
130
  async testWebhook(id){
@@ -97,13 +132,13 @@ export class Bridge {
97
132
  let w = hooks.find(h => h.id === id);
98
133
  if(!w){ throw Object.assign(new Error('No such webhook'), { status : 404 }); }
99
134
  let ev = Object.values(EVENTS).find(e => e.namespace === w.event) || EVENTS.identification;
100
- return api('POST', `${base(this.site, ev)}/webhook/test`, { flags : this.flags, body : { webhook_id : id } });
135
+ return this.api('POST', `${base(this.site, ev)}/webhook/test`, { flags : this.flags, body : { webhook_id : id } });
101
136
  }
102
137
 
103
138
  // A sample of the record a webhook delivers (nothing is sent).
104
139
  async sample(eventKey = 'identification'){
105
140
  let ev = EVENTS[eventKey] || EVENTS.identification;
106
- let r = await api('POST', `${base(this.site, ev)}/webhook/preview`, { flags : this.flags, body : { namespace : ev.namespace } });
141
+ let r = await this.api('POST', `${base(this.site, ev)}/webhook/preview`, { flags : this.flags, body : { namespace : ev.namespace } });
107
142
  return r?.payload || r;
108
143
  }
109
144
 
@@ -111,7 +146,7 @@ export class Bridge {
111
146
  // public visitor API does not index Sandbox people, so this goes through the console route).
112
147
  async visitor(id){
113
148
  if(!/^[a-f0-9]{24}$/i.test(String(id))){ throw Object.assign(new Error('not a visitor id'), { status : 400 }); }
114
- let r = await api('GET', `/api/projects/${this.site.id}/profiles/${id}`, { flags : this.flags });
149
+ let r = await this.api('GET', `/api/projects/${this.site.id}/profiles/${id}`, { flags : this.flags });
115
150
  if(!r){ throw Object.assign(new Error('not found'), { status : 404 }); }
116
151
  let { seen_by, pinned_by, __v, ...rest } = r;
117
152
  return rest;
@@ -119,24 +154,24 @@ export class Bridge {
119
154
 
120
155
  async visitorEvents(id){
121
156
  if(!/^[a-f0-9]{24}$/i.test(String(id))){ return { error : 'not a visitor id' }; }
122
- return api('GET', `/api/projects/${this.site.id}/profiles/${id}/key-events`, { flags : this.flags }).catch(e => ({ error : e.message }));
157
+ return this.api('GET', `/api/projects/${this.site.id}/profiles/${id}/key_events`, { flags : this.flags }).catch(e => ({ error : e.message }));
123
158
  }
124
159
 
125
160
  // Go live: a real site on the account, with its snippet.
126
161
  async createSite({ name, url }){
127
162
  let origins = toOrigins(url);
128
163
  if(!origins.length){ throw Object.assign(new Error('Give the site\'s public URL, e.g. https://www.example.com'), { status : 400 }); }
129
- let me = await api('GET', '/api/sqid/me', { flags : this.flags });
164
+ let me = await this.api('GET', '/api/sqid/me', { flags : this.flags });
130
165
  if(!me?.account?.hasSubscription){
131
- try{ await api('POST', '/api/sqid/billing/start', { flags : this.flags, body : {} }); }catch(error){ /* the project route starts it too */ }
166
+ try{ await this.api('POST', '/api/sqid/billing/start', { flags : this.flags, body : {} }); }catch(error){ /* the project route starts it too */ }
132
167
  }
133
- let sites = await listSites(this.flags);
168
+ let sites = await listSites(this.flags, this.api);
134
169
  let same = sites.find(s => !s.sandbox && s.name?.toLowerCase() === String(name || '').toLowerCase());
135
170
  let site = same;
136
171
  if(!site){
137
- let created = await api('POST', '/api/projects', { flags : this.flags, body : { name : name || new URL(origins[0]).hostname, site_origins : origins, product_origins : origins, avatar_index : 1 } });
172
+ let created = await this.api('POST', '/api/projects', { flags : this.flags, body : { name : name || new URL(origins[0]).hostname, site_origins : origins, product_origins : origins, avatar_index : 1 } });
138
173
  let id = String(created?._id || created?.id || created?.sdk_id || '');
139
- sites = await listSites(this.flags);
174
+ sites = await listSites(this.flags, this.api);
140
175
  site = sites.find(s => s.id === id) || sites.find(s => !s.sandbox && s.origins?.includes(origins[0]));
141
176
  }
142
177
  if(!site){ throw new Error('Sqid did not return the new site.'); }
@@ -144,7 +179,7 @@ export class Bridge {
144
179
  }
145
180
 
146
181
  async siteStatus(id){
147
- let sites = await listSites(this.flags);
182
+ let sites = await listSites(this.flags, this.api);
148
183
  let s = sites.find(x => x.id === id);
149
184
  return s ? { id : s.id, name : s.name, deployed : !!s.deployed, connected : !!s.connected } : null;
150
185
  }