Marketing skills for Claude Code and AI agents. CRO, copywriting, SEO, analytics, and growth engineering.
JavaScript agent-skillsai-agentsai-seoclaudeclaude-codeclaude-code-pluginclaude-skillscodexcontent-marketingconversion-rate-optimizationcopywritingcursoremail-marketinggenerative-engine-optimizationgrowth-marketingmarketingmarketing-automationsaas-marketingseoskill-md
feat(segment): support anonymous event identities
Rudy Celeklid7b576e80d8e
diff --git a/tests/clis/segment-anonymous-identity.test.cjs b/tests/clis/segment-anonymous-identity.test.cjsnew file mode 100644index 0000000..f3bfe89--- /dev/null+++ b/tests/clis/segment-anonymous-identity.test.cjs@@ -0,0 +1,43 @@+const { test } = require('node:test')+const assert = require('node:assert/strict')+const { spawnSync } = require('node:child_process')+const path = require('node:path')+const cli = path.resolve(__dirname, '../../tools/clis/segment.js')+function run(args, oracle='') {+ const fixture=`global.fetch=async(url,options)=>{const assert=require('node:assert/strict');${oracle}+ return new Response(JSON.stringify({url,method:options.method,authorization:options.headers.Authorization,body:options.body?JSON.parse(options.body):undefined}),{status:200});+ };process.argv=['node',${JSON.stringify(cli)},...${JSON.stringify(args)}];require(${JSON.stringify(cli)});`+ return spawnSync(process.execPath,['-e',fixture],{encoding:'utf8',timeout:10000,env:{...process.env,SEGMENT_WRITE_KEY:'fixture-write',SEGMENT_ACCESS_TOKEN:'fixture-profile'}})+}+function output(result){assert.equal(result.status,0,result.stderr);return JSON.parse(result.stdout)}+for(const [command,path,extra,payload] of [+ [['track','event'],'track',['--event','Pricing Viewed','--properties','{"plan":"pro"}'],{event:'Pricing Viewed',properties:{plan:'pro'}}],+ [['page','view'],'page',['--name','Pricing','--properties','{"path":"/pricing"}'],{name:'Pricing',properties:{path:'/pricing'}}],+ [['identify','user'],'identify',['--traits','{"plan":"trial"}'],{traits:{plan:'trial'}}],+])test(`${path} supports an anonymous identity without inventing a user ID`,()=>{+ const result=output(run([...command,'--anonymous-id','anon-owned',...extra]))+ assert.equal(result.url,`https://api.segment.io/v1/${path}`);assert.equal(result.method,'POST')+ assert.equal(result.authorization,`Basic ${Buffer.from('fixture-write:').toString('base64')}`);assert.deepEqual(result.body,{anonymousId:'anon-owned',...payload})+})+test('identify preserves both known and anonymous IDs for the same caller identity',()=>{+ const result=output(run(['identify','user','--user-id','user-owned','--anonymous-id','anon-owned','--traits','{"plan":"paid"}']))+ assert.deepEqual(result.body,{userId:'user-owned',anonymousId:'anon-owned',traits:{plan:'paid'}})+})+test('known track keeps the original request body',()=>{+ const result=output(run(['track','event','--user-id','user-owned','--event','Signed Up']))+ assert.deepEqual(result.body,{userId:'user-owned',event:'Signed Up'})+})+test('anonymous page preview masks credentials without a request',()=>{+ const result=output(run(['page','view','--anonymous-id','anon-owned','--dry-run'],"throw new Error('unexpected request')"))+ assert.deepEqual(result.body,{anonymousId:'anon-owned'});assert.equal(result.headers.Authorization,'***')+})+test('a missing identity fails locally before collecting an event',()=>{+ for(const args of [['track','event','--event','Viewed'],['identify','user'],['page','view']]){+ const result=run(args,"throw new Error('unexpected request')")+ assert.equal(result.status,1);assert.match(JSON.parse(result.stderr).error,/--user-id or --anonymous-id/)+ }+})+test('profile lookups still require a known user and use the encoded profile path',()=>{+ const result=output(run(['profiles','traits','--space-id','space','--user-id','user-owned']))+ assert.equal(result.url,'https://profiles.segment.com/v1/spaces/space/collections/users/profiles/user_id:user-owned/traits');assert.equal(result.method,'GET')+})diff --git a/tools/clis/segment.js b/tools/clis/segment.jsindex ea2efed..05cedc2 100755--- a/tools/clis/segment.js+++ b/tools/clis/segment.js@@ -81,6 +81,14 @@ function parseArgs(args) {const args = parseArgs(rawArgs)const [cmd, sub, ...rest] = args._+function eventIdentity() {+ const identity = {}+ if (typeof args['user-id'] === 'string' && args['user-id']) identity.userId = args['user-id']+ if (typeof args['anonymous-id'] === 'string' && args['anonymous-id']) identity.anonymousId = args['anonymous-id']+ if (!Object.keys(identity).length) throw new Error('--user-id or --anonymous-id required')+ return identity+}+async function main() {let result@@ -88,10 +96,9 @@ async function main() {case 'track':switch (sub) {case 'event': {- if (!args['user-id']) { result = { error: '--user-id required' }; break }if (!args.event) { result = { error: '--event required' }; break }const body = {- userId: args['user-id'],+ ...eventIdentity(),event: args.event,}if (args.properties) {@@ -108,8 +115,7 @@ async function main() {case 'identify':switch (sub) {case 'user': {- if (!args['user-id']) { result = { error: '--user-id required' }; break }- const body = { userId: args['user-id'] }+ const body = eventIdentity()if (args.traits) {try { body.traits = JSON.parse(args.traits) } catch { result = { error: 'Invalid JSON in --traits' }; break }}@@ -124,8 +130,7 @@ async function main() {case 'page':switch (sub) {case 'view': {- if (!args['user-id']) { result = { error: '--user-id required' }; break }- const body = { userId: args['user-id'] }+ const body = eventIdentity()if (args.name) body.name = args.nameif (args.properties) {try { body.properties = JSON.parse(args.properties) } catch { result = { error: 'Invalid JSON in --properties' }; break }@@ -175,9 +180,9 @@ async function main() {result = {error: 'Unknown command',usage: {- track: 'track event --user-id <id> --event <name> [--properties <json>]',- identify: 'identify user --user-id <id> [--traits <json>]',- page: 'page view --user-id <id> [--name <name>] [--properties <json>]',+ track: 'track event [--user-id <id>] [--anonymous-id <id>] --event <name> [--properties <json>]',+ identify: 'identify user [--user-id <id>] [--anonymous-id <id>] [--traits <json>]',+ page: 'page view [--user-id <id>] [--anonymous-id <id>] [--name <name>] [--properties <json>]',batch: 'batch send --events <json_array>',profiles: 'profiles [traits|events] --space-id <id> --user-id <id>',}diff --git a/tools/integrations/segment.md b/tools/integrations/segment.mdindex 3d5a9be..0271bcc 100644--- a/tools/integrations/segment.md+++ b/tools/integrations/segment.md@@ -163,3 +163,34 @@ analytics.page('Pricing');Pass the raw user ID to `profiles traits` or `profiles events`. The CLI URL-encodesthe value so characters such as `/`, `+`, `?`, and `#` remain part of the user ID.Do not pre-encode it. See [Profile API identifiers](https://www.twilio.com/docs/segment/unify/profile-api).++## CLI anonymous and known identities++The `track event`, `page view`, and `identify user` commands accept either+`--user-id`, `--anonymous-id`, or both. Use an existing anonymous identifier+for pre-signup activity rather than inventing a known customer ID:++```bash+node tools/clis/segment.js track event --anonymous-id anon-owned \+ --event 'Pricing Viewed' --properties '{"plan":"pro"}' --dry-run++# When this same visitor becomes a known user+node tools/clis/segment.js identify user --user-id user-owned \+ --anonymous-id anon-owned --traits '{"plan":"paid"}' --dry-run+```++The CLI passes the IDs through unchanged; it does not generate an anonymous+ID, store identity state, or infer that two people are the same. Reuse the+actual identifier associated with that visitor and supply both only when the+association is known. Destination identity handling varies: acceptance by+Segment does not prove every destination merged the history. An anonymous ID+is an identifier, not a guarantee of anonymity or permission to collect data.+Send events only when the collection is already authorized.++At least one ID is required before sending these single-event requests.+Existing `--user-id` calls and raw batch payloads are unchanged. Profile+lookups continue to require a known `--user-id`; `--anonymous-id` does not+change their resource path. Previews mask the write key and make no request.++Official [common identity fields](https://www.twilio.com/docs/segment/connections/spec/common)+and [Identify semantics](https://www.twilio.com/docs/segment/connections/spec/identify).