@spectosh/react-native 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +83 -0
- package/package.json +45 -0
- package/src/core.js +325 -0
- package/src/index.js +29 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Evigasoft and Specto contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
# @spectosh/react-native
|
|
2
|
+
|
|
3
|
+
Specto for React Native apps. A session records the app's screens, network
|
|
4
|
+
requests, console output, JavaScript errors and your custom events, and the
|
|
5
|
+
dashboard treats it like a web session: it shows up in Sessions (Device:
|
|
6
|
+
mobile or tablet), its errors group into Issues, and its screens count in
|
|
7
|
+
funnels and paths as pages (`/Checkout`).
|
|
8
|
+
|
|
9
|
+
Apps have no DOM, so there is **no screen replay** — a session's page shows
|
|
10
|
+
its timeline, requests, logs and errors.
|
|
11
|
+
|
|
12
|
+
## Install
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
npm install @spectosh/react-native @react-native-async-storage/async-storage
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
AsyncStorage is optional; it keeps one visitor id across app launches.
|
|
19
|
+
Without it, every launch is a new visitor.
|
|
20
|
+
|
|
21
|
+
## Start
|
|
22
|
+
|
|
23
|
+
```js
|
|
24
|
+
import AsyncStorage from '@react-native-async-storage/async-storage'
|
|
25
|
+
import { init } from '@spectosh/react-native'
|
|
26
|
+
|
|
27
|
+
const specto = await init({
|
|
28
|
+
key: 'pk_…', // the project's public key
|
|
29
|
+
endpoint: 'https://specto.example.com', // your Specto instance
|
|
30
|
+
storage: AsyncStorage,
|
|
31
|
+
app: { name: 'Shop', version: '1.4.2' },
|
|
32
|
+
})
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
`init` reads the project's capture settings (Settings → Privacy): when
|
|
36
|
+
recording is off, or the session falls outside the sample rate, it records
|
|
37
|
+
nothing.
|
|
38
|
+
|
|
39
|
+
## Screens, users and events
|
|
40
|
+
|
|
41
|
+
```js
|
|
42
|
+
// React Navigation: every focused route becomes a screen
|
|
43
|
+
<NavigationContainer ref={navigationRef} onReady={() => specto.trackNavigation(navigationRef)}>
|
|
44
|
+
|
|
45
|
+
// or by hand
|
|
46
|
+
specto.screen('Checkout')
|
|
47
|
+
|
|
48
|
+
specto.identify(user.id, { plan: 'pro' })
|
|
49
|
+
specto.track('checkout_started', { items: 3 })
|
|
50
|
+
specto.captureError(error) // caught errors; uncaught ones are recorded for you
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
## What is recorded
|
|
54
|
+
|
|
55
|
+
| | |
|
|
56
|
+
|---|---|
|
|
57
|
+
| Screens | `trackNavigation` or `screen(name)` |
|
|
58
|
+
| Requests | method, URL, status and duration of every `fetch`/`XMLHttpRequest` (not bodies or headers); `privacy: 'strict'` drops query strings |
|
|
59
|
+
| Console | `console.log/info/warn/error/debug` text; strict privacy masks it; `captureConsole: false` turns it off |
|
|
60
|
+
| Errors | uncaught errors (through `ErrorUtils`, the app's own handler still runs) and `captureError` |
|
|
61
|
+
|
|
62
|
+
Email addresses and card-length numbers are replaced before anything
|
|
63
|
+
leaves the device. Events are sent in batches every 5 seconds and when the
|
|
64
|
+
app goes to the background; a batch that fails is retried with the same
|
|
65
|
+
number, so the server stores it once. After 30 minutes in the background
|
|
66
|
+
the next foreground starts a new session.
|
|
67
|
+
|
|
68
|
+
## Options
|
|
69
|
+
|
|
70
|
+
| Option | Default | |
|
|
71
|
+
|---|---|---|
|
|
72
|
+
| `key` | — | the project's public key |
|
|
73
|
+
| `endpoint` | — | your Specto URL |
|
|
74
|
+
| `storage` | memory | `getItem`/`setItem` (AsyncStorage) |
|
|
75
|
+
| `app` | — | `{ name, version }`, shown in the session's user agent |
|
|
76
|
+
| `privacy` | `'balanced'` | `'strict'`: no query strings, console masked |
|
|
77
|
+
| `captureConsole` | `true` | |
|
|
78
|
+
| `captureNetwork` | `true` | |
|
|
79
|
+
| `sampleRate` | `1` | the lower of this and the project's applies |
|
|
80
|
+
| `tablet` | `false` | count an Android tablet as a tablet |
|
|
81
|
+
|
|
82
|
+
`@spectosh/react-native/core` exports `createSpecto` without React Native
|
|
83
|
+
imports, for tests or other JavaScript runtimes.
|
package/package.json
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@spectosh/react-native",
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Specto for React Native apps — screens, requests, logs, errors and custom events in the same sessions, issues and funnels as your web app. No dependencies.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"publishConfig": {
|
|
7
|
+
"access": "public"
|
|
8
|
+
},
|
|
9
|
+
"repository": {
|
|
10
|
+
"type": "git",
|
|
11
|
+
"url": "git+https://github.com/evigasoft/specto.sh.git",
|
|
12
|
+
"directory": "packages/react-native"
|
|
13
|
+
},
|
|
14
|
+
"homepage": "https://specto.sh/docs/react-native",
|
|
15
|
+
"license": "MIT",
|
|
16
|
+
"main": "./src/index.js",
|
|
17
|
+
"react-native": "./src/index.js",
|
|
18
|
+
"exports": {
|
|
19
|
+
".": "./src/index.js",
|
|
20
|
+
"./core": "./src/core.js"
|
|
21
|
+
},
|
|
22
|
+
"files": [
|
|
23
|
+
"src",
|
|
24
|
+
"README.md"
|
|
25
|
+
],
|
|
26
|
+
"sideEffects": false,
|
|
27
|
+
"peerDependencies": {
|
|
28
|
+
"react-native": ">=0.72"
|
|
29
|
+
},
|
|
30
|
+
"peerDependenciesMeta": {
|
|
31
|
+
"react-native": {
|
|
32
|
+
"optional": true
|
|
33
|
+
}
|
|
34
|
+
},
|
|
35
|
+
"scripts": {
|
|
36
|
+
"test": "node --test \"test/**/*.test.mjs\""
|
|
37
|
+
},
|
|
38
|
+
"keywords": [
|
|
39
|
+
"specto",
|
|
40
|
+
"react-native",
|
|
41
|
+
"session-replay",
|
|
42
|
+
"analytics",
|
|
43
|
+
"error-tracking"
|
|
44
|
+
]
|
|
45
|
+
}
|
package/src/core.js
ADDED
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
// Specto for React Native apps (ROADMAP P3-8): sessions of screens, requests,
|
|
2
|
+
// logs, errors and custom events, sent to the same ingest as the browser SDK.
|
|
3
|
+
// An app has no DOM, so there is no screen replay — the dashboard shows the
|
|
4
|
+
// session's timeline, its requests, logs and errors, and counts it in
|
|
5
|
+
// funnels, paths and issues (a screen is a page: "/Checkout").
|
|
6
|
+
//
|
|
7
|
+
// Everything platform-specific (AppState, ErrorUtils, storage, fetch, XHR) is
|
|
8
|
+
// passed in, so this file runs anywhere; index.js wires React Native's.
|
|
9
|
+
//
|
|
10
|
+
// Wire format (packages/core/src/ingest-core.js): POST /api/ingest
|
|
11
|
+
// { key, sessionId, sk, b, meta: { visitorId, page, userAgent }, events: [{ kind, payload }] }
|
|
12
|
+
// sk is the session key: created with the session and sent with every batch,
|
|
13
|
+
// so ingest accepts appends only from the app that started the session.
|
|
14
|
+
// Batches are numbered (b) per session, and a failed batch is retried with
|
|
15
|
+
// the same number, so the server stores it once however often it arrives.
|
|
16
|
+
|
|
17
|
+
export const VERSION = '0.2.0'
|
|
18
|
+
|
|
19
|
+
const SESSION_IDLE_MS = 30 * 60_000 // back from the background after this: a new session
|
|
20
|
+
const FLUSH_MS = 5_000
|
|
21
|
+
const MAX_BATCH = 200
|
|
22
|
+
const MAX_QUEUE = 1_000 // events held while offline; the oldest go first
|
|
23
|
+
const MAX_RETRY_MS = 60_000
|
|
24
|
+
const LEVELS = ['log', 'info', 'warn', 'error', 'debug']
|
|
25
|
+
|
|
26
|
+
const memoryStorage = () => {
|
|
27
|
+
const m = new Map()
|
|
28
|
+
return { getItem: async (k) => m.get(k) ?? null, setItem: async (k, v) => { m.set(k, String(v)) } }
|
|
29
|
+
}
|
|
30
|
+
function randomHex(bytes) {
|
|
31
|
+
const a = new Uint8Array(bytes)
|
|
32
|
+
if (globalThis.crypto?.getRandomValues) globalThis.crypto.getRandomValues(a)
|
|
33
|
+
else for (let i = 0; i < bytes; i++) a[i] = Math.floor(Math.random() * 256)
|
|
34
|
+
return Array.from(a, (x) => x.toString(16).padStart(2, '0')).join('')
|
|
35
|
+
}
|
|
36
|
+
// what leaves the device never carries an email address or a card-length number
|
|
37
|
+
export const scrubText = (s) => String(s)
|
|
38
|
+
.replace(/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g, '[email]')
|
|
39
|
+
.replace(/\b(?:\d[ -]?){12,19}\b/g, '[number]')
|
|
40
|
+
const fmtArg = (a) => {
|
|
41
|
+
if (typeof a === 'string') return a
|
|
42
|
+
if (a instanceof Error) return `${a.name}: ${a.message}`
|
|
43
|
+
try { return JSON.stringify(a) } catch { return String(a) }
|
|
44
|
+
}
|
|
45
|
+
const stripQuery = (u) => String(u).replace(/[?#].*$/, '')
|
|
46
|
+
|
|
47
|
+
// The user agent the dashboard reads (device class, OS — util.js parseUA,
|
|
48
|
+
// deviceOfUA): "SpectoRN/0.2.0 (iPhone; iOS 18.0) Shop/1.4.2"
|
|
49
|
+
export function userAgentFor({ os, version, model, isPad, tablet } = {}, app = {}) {
|
|
50
|
+
const ver = String(version ?? '').slice(0, 20)
|
|
51
|
+
const appPart = app.name ? ` ${String(app.name).replace(/[^\w.-]/g, '')}/${String(app.version || '0').replace(/[^\w.-]/g, '')}` : ''
|
|
52
|
+
if (os === 'ios') return `SpectoRN/${VERSION} (${isPad || tablet ? 'iPad' : 'iPhone'}; iOS ${ver})${appPart}`
|
|
53
|
+
if (os === 'android') return `SpectoRN/${VERSION} (Linux; Android ${ver}; ${String(model || 'device').slice(0, 40)})${appPart}${tablet ? '' : ' Mobile'}`
|
|
54
|
+
return `SpectoRN/${VERSION} (${String(os || 'unknown').slice(0, 20)} ${ver})${appPart}`
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function createSpecto(opts = {}) {
|
|
58
|
+
const key = String(opts.key || '')
|
|
59
|
+
const endpoint = String(opts.endpoint || '').replace(/\/+$/, '')
|
|
60
|
+
if (!key || !/^https?:\/\//.test(endpoint)) throw new Error('Specto: pass your project key and your Specto URL as endpoint')
|
|
61
|
+
const fetchFn = opts.fetch || (globalThis.fetch ? globalThis.fetch.bind(globalThis) : null)
|
|
62
|
+
const storage = opts.storage || memoryStorage()
|
|
63
|
+
const appState = opts.appState || null
|
|
64
|
+
const errorUtils = opts.errorUtils !== undefined ? opts.errorUtils : globalThis.ErrorUtils || null
|
|
65
|
+
const con = opts.console || globalThis.console
|
|
66
|
+
const XHR = opts.XMLHttpRequest !== undefined ? opts.XMLHttpRequest : globalThis.XMLHttpRequest
|
|
67
|
+
const now = opts.now || (() => Date.now())
|
|
68
|
+
const userAgent = opts.userAgent || userAgentFor(opts.platform, opts.app)
|
|
69
|
+
const ingestUrl = `${endpoint}/api/ingest`
|
|
70
|
+
// the SDK's own calls (ingest, capture settings) are never recorded
|
|
71
|
+
const isOwn = (url) => { const u = String(url || ''); return u.startsWith(ingestUrl) || u.startsWith(`${endpoint}/api/sdk/`) }
|
|
72
|
+
|
|
73
|
+
// the stricter of the app's options and the project's settings applies
|
|
74
|
+
const cfg = { console: opts.captureConsole !== false, network: opts.captureNetwork !== false, strict: opts.privacy === 'strict', sampleRate: 1 }
|
|
75
|
+
let started = false
|
|
76
|
+
let stopped = false
|
|
77
|
+
let sessionId = null
|
|
78
|
+
let sessionKey = null
|
|
79
|
+
let sessionStart = 0
|
|
80
|
+
let nextBatch = 0
|
|
81
|
+
let visitorId = null
|
|
82
|
+
let screenPath = null
|
|
83
|
+
let meta = null
|
|
84
|
+
let entrySet = false // the session's page is its first screen
|
|
85
|
+
let queue = []
|
|
86
|
+
const pending = [] // batches waiting to be (re)sent: { sessionId, sk, b, meta, events, tries, at }
|
|
87
|
+
let sending = null // the drain in flight
|
|
88
|
+
let backgroundAt = null
|
|
89
|
+
let timer = null
|
|
90
|
+
const undo = []
|
|
91
|
+
|
|
92
|
+
const rel = () => Math.max(0, now() - sessionStart)
|
|
93
|
+
const push = (kind, payload) => {
|
|
94
|
+
if (!started || stopped) return
|
|
95
|
+
queue.push({ kind, payload })
|
|
96
|
+
if (queue.length > MAX_QUEUE) queue.splice(0, queue.length - MAX_QUEUE)
|
|
97
|
+
if (queue.length >= MAX_BATCH) flush()
|
|
98
|
+
}
|
|
99
|
+
const sealBatch = () => {
|
|
100
|
+
if (!queue.length) return
|
|
101
|
+
while (queue.length) {
|
|
102
|
+
pending.push({ sessionId, sk: sessionKey, b: nextBatch++, meta, events: queue.splice(0, MAX_BATCH), tries: 0, at: 0 })
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function newSession() {
|
|
107
|
+
sealBatch() // what the old session still holds goes out under its own id
|
|
108
|
+
sessionId = `rec_${randomHex(12)}`
|
|
109
|
+
sessionKey = `sk_${randomHex(16)}`
|
|
110
|
+
sessionStart = now()
|
|
111
|
+
nextBatch = 0
|
|
112
|
+
meta = { visitorId, page: screenPath || '/', userAgent }
|
|
113
|
+
entrySet = Boolean(screenPath)
|
|
114
|
+
if (screenPath) push('event', { t: 0, type: 'nav', path: screenPath })
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
async function send(batch) {
|
|
118
|
+
const res = await fetchFn(ingestUrl, {
|
|
119
|
+
method: 'POST',
|
|
120
|
+
headers: { 'Content-Type': 'text/plain' },
|
|
121
|
+
body: JSON.stringify({ key, sessionId: batch.sessionId, sk: batch.sk, b: batch.b, meta: batch.meta, events: batch.events }),
|
|
122
|
+
})
|
|
123
|
+
if (res.ok) return 'ok'
|
|
124
|
+
let code = ''
|
|
125
|
+
try { code = (await res.json())?.code || '' } catch { /* not json */ }
|
|
126
|
+
if ((res.status === 429 && code === 'session_limit') || (res.status === 403 && code === 'session_key')) return 'rotate'
|
|
127
|
+
if (res.status >= 500 || (res.status === 429 && code === 'rate_limited')) return 'retry'
|
|
128
|
+
// unknown key, suspended, recording off, quota spent: stop sending
|
|
129
|
+
if (res.status === 401 || res.status === 403 || (res.status === 429 && code === 'quota_exceeded')) return 'stop'
|
|
130
|
+
return 'drop' // malformed or too large: this batch can never succeed
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// a flush while one is in flight joins it: the running drain also sends
|
|
134
|
+
// what was sealed since
|
|
135
|
+
function flush() {
|
|
136
|
+
if (!started || !fetchFn) return Promise.resolve()
|
|
137
|
+
sealBatch()
|
|
138
|
+
if (!sending) sending = drain().finally(() => { sending = null })
|
|
139
|
+
return sending
|
|
140
|
+
}
|
|
141
|
+
async function drain() {
|
|
142
|
+
while (pending.length) {
|
|
143
|
+
const batch = pending[0]
|
|
144
|
+
if (batch.at > now()) return
|
|
145
|
+
let outcome
|
|
146
|
+
try { outcome = await send(batch) } catch { outcome = 'retry' }
|
|
147
|
+
if (outcome === 'retry') {
|
|
148
|
+
batch.tries++
|
|
149
|
+
batch.at = now() + Math.min(MAX_RETRY_MS, 1000 * 2 ** batch.tries)
|
|
150
|
+
return
|
|
151
|
+
}
|
|
152
|
+
pending.shift()
|
|
153
|
+
if (outcome === 'rotate' && batch.sessionId === sessionId) newSession()
|
|
154
|
+
if (outcome === 'stop') { stop({ flush: false }); return }
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// ---- capture -------------------------------------------------------------
|
|
159
|
+
function hookErrors() {
|
|
160
|
+
if (!errorUtils?.setGlobalHandler) return
|
|
161
|
+
const prev = errorUtils.getGlobalHandler?.()
|
|
162
|
+
errorUtils.setGlobalHandler((err, isFatal) => {
|
|
163
|
+
try {
|
|
164
|
+
captureError(err, { fatal: Boolean(isFatal) })
|
|
165
|
+
if (isFatal) flush()
|
|
166
|
+
} catch { /* never get in the app's way */ }
|
|
167
|
+
if (prev) prev(err, isFatal)
|
|
168
|
+
})
|
|
169
|
+
undo.push(() => { if (prev) errorUtils.setGlobalHandler(prev) })
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function hookConsole() {
|
|
173
|
+
if (!cfg.console || !con) return
|
|
174
|
+
for (const level of LEVELS) {
|
|
175
|
+
const orig = con[level]
|
|
176
|
+
if (typeof orig !== 'function') continue
|
|
177
|
+
con[level] = function (...args) {
|
|
178
|
+
try { push('console', { t: rel(), level: level === 'debug' ? 'log' : level, text: cfg.strict ? '[masked]' : scrubText(args.map(fmtArg).join(' ')).slice(0, 2000) }) } catch { /* ignore */ }
|
|
179
|
+
return orig.apply(this, args)
|
|
180
|
+
}
|
|
181
|
+
undo.push(() => { con[level] = orig })
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// React Native's fetch is built on XMLHttpRequest, so hooking XHR sees
|
|
186
|
+
// both; elsewhere (tests, other runtimes) fetch itself is hooked
|
|
187
|
+
function hookNetwork() {
|
|
188
|
+
if (!cfg.network) return
|
|
189
|
+
const urlOf = (u) => scrubText(cfg.strict ? stripQuery(u) : String(u)).slice(0, 500)
|
|
190
|
+
if (XHR?.prototype?.open) {
|
|
191
|
+
const { open, send: xsend } = XHR.prototype
|
|
192
|
+
XHR.prototype.open = function (method, url) {
|
|
193
|
+
this.__specto = isOwn(url) ? null : { method: String(method || 'GET').toUpperCase(), url: urlOf(url) }
|
|
194
|
+
return open.apply(this, arguments)
|
|
195
|
+
}
|
|
196
|
+
XHR.prototype.send = function () {
|
|
197
|
+
const m = this.__specto
|
|
198
|
+
if (m && this.addEventListener) {
|
|
199
|
+
const t0 = now()
|
|
200
|
+
const t = rel()
|
|
201
|
+
this.addEventListener('loadend', () => push('network', { t, method: m.method, url: m.url, status: this.status, dur: now() - t0, ...(this.status === 0 ? { error: true } : {}) }))
|
|
202
|
+
}
|
|
203
|
+
return xsend.apply(this, arguments)
|
|
204
|
+
}
|
|
205
|
+
undo.push(() => { XHR.prototype.open = open; XHR.prototype.send = xsend })
|
|
206
|
+
return
|
|
207
|
+
}
|
|
208
|
+
if (!fetchFn || !globalThis.fetch || opts.fetch) return
|
|
209
|
+
const orig = globalThis.fetch
|
|
210
|
+
globalThis.fetch = async function (input, init) {
|
|
211
|
+
const url = typeof input === 'string' ? input : input?.url
|
|
212
|
+
if (isOwn(url)) return orig.apply(this, arguments)
|
|
213
|
+
const method = String(init?.method || input?.method || 'GET').toUpperCase()
|
|
214
|
+
const t0 = now()
|
|
215
|
+
const t = rel()
|
|
216
|
+
try {
|
|
217
|
+
const res = await orig.apply(this, arguments)
|
|
218
|
+
push('network', { t, method, url: urlOf(url), status: res.status, dur: now() - t0 })
|
|
219
|
+
return res
|
|
220
|
+
} catch (e) {
|
|
221
|
+
push('network', { t, method, url: urlOf(url), status: 0, dur: now() - t0, error: true })
|
|
222
|
+
throw e
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
undo.push(() => { globalThis.fetch = orig })
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
function hookAppState() {
|
|
229
|
+
if (!appState?.addEventListener) return
|
|
230
|
+
const sub = appState.addEventListener('change', (state) => {
|
|
231
|
+
if (state === 'active') {
|
|
232
|
+
if (backgroundAt != null && now() - backgroundAt > SESSION_IDLE_MS) newSession()
|
|
233
|
+
backgroundAt = null
|
|
234
|
+
} else if (backgroundAt == null) {
|
|
235
|
+
backgroundAt = now()
|
|
236
|
+
flush() // the app may be killed in the background
|
|
237
|
+
}
|
|
238
|
+
})
|
|
239
|
+
undo.push(() => sub?.remove?.())
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// ---- public API ----------------------------------------------------------
|
|
243
|
+
async function start() {
|
|
244
|
+
if (started || stopped) return started
|
|
245
|
+
try {
|
|
246
|
+
visitorId = await storage.getItem('specto:visitor')
|
|
247
|
+
if (!visitorId || !/^[A-Za-z0-9_-]{1,64}$/.test(visitorId)) {
|
|
248
|
+
visitorId = `v_${randomHex(10)}`
|
|
249
|
+
await storage.setItem('specto:visitor', visitorId)
|
|
250
|
+
}
|
|
251
|
+
} catch { visitorId = `v_${randomHex(10)}` }
|
|
252
|
+
// the project's capture settings (Settings → Privacy) — the stricter wins
|
|
253
|
+
try {
|
|
254
|
+
const res = await fetchFn(`${endpoint}/api/sdk/config?key=${encodeURIComponent(key)}`)
|
|
255
|
+
if (res.ok) {
|
|
256
|
+
const c = await res.json()
|
|
257
|
+
if (c.enabled === false) return false
|
|
258
|
+
if (c.privacy === 'strict') cfg.strict = true
|
|
259
|
+
if (c.captureConsole === false) cfg.console = false
|
|
260
|
+
if (Number.isFinite(c.sampleRate)) cfg.sampleRate = c.sampleRate
|
|
261
|
+
} else if (res.status === 401 || res.status === 404) return false
|
|
262
|
+
} catch { /* offline: record with the app's own options, send later */ }
|
|
263
|
+
const rate = Math.min(cfg.sampleRate, opts.sampleRate ?? 1)
|
|
264
|
+
if (rate < 1 && Math.random() >= rate) return false
|
|
265
|
+
started = true
|
|
266
|
+
newSession()
|
|
267
|
+
hookErrors()
|
|
268
|
+
hookConsole()
|
|
269
|
+
hookNetwork()
|
|
270
|
+
hookAppState()
|
|
271
|
+
timer = setInterval(() => { flush() }, opts.flushIntervalMs || FLUSH_MS)
|
|
272
|
+
undo.push(() => clearInterval(timer))
|
|
273
|
+
return true
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
function stop({ flush: andFlush = true } = {}) {
|
|
277
|
+
if (andFlush) flush()
|
|
278
|
+
stopped = true
|
|
279
|
+
while (undo.length) { try { undo.pop()() } catch { /* ignore */ } }
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// a screen is a page to the dashboard: "/Checkout"
|
|
283
|
+
function screen(name) {
|
|
284
|
+
const path = `/${String(name || '').replace(/^\/+/, '')}`.slice(0, 300)
|
|
285
|
+
if (path === screenPath) return
|
|
286
|
+
screenPath = path
|
|
287
|
+
if (meta && !entrySet && nextBatch === 0 && !pending.length) { meta.page = path; entrySet = true }
|
|
288
|
+
push('event', { t: rel(), type: 'nav', path })
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
function identify(id, traits) {
|
|
292
|
+
if (id == null || id === '') return
|
|
293
|
+
push('identify', { id: String(id).slice(0, 256), traits: traits && typeof traits === 'object' ? traits : undefined })
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
function track(name, props) {
|
|
297
|
+
if (!name) return
|
|
298
|
+
push('event', { t: rel(), type: 'custom', name: String(name).slice(0, 120), props: props && typeof props === 'object' ? JSON.parse(JSON.stringify(props, (k, v) => (typeof v === 'string' ? scrubText(v).slice(0, 500) : v))) : undefined })
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
function captureError(err, { fatal = false } = {}) {
|
|
302
|
+
const e = err instanceof Error ? err : new Error(fmtArg(err))
|
|
303
|
+
const stack = e.stack ? scrubText(String(e.stack)).split('\n').slice(0, 8).map((l) => l.slice(0, 300)).join('\n') : undefined
|
|
304
|
+
push('event', { t: rel(), type: 'error', message: scrubText(`${fatal ? '[fatal] ' : ''}${e.name && e.name !== 'Error' ? `${e.name}: ` : ''}${e.message || 'error'}`).slice(0, 500), ...(stack ? { stack } : {}) })
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
// React Navigation: specto.trackNavigation(navigationRef) — every focused
|
|
308
|
+
// route becomes a screen
|
|
309
|
+
function trackNavigation(ref) {
|
|
310
|
+
let last = null
|
|
311
|
+
const onState = () => {
|
|
312
|
+
const r = ref?.getCurrentRoute?.()
|
|
313
|
+
if (r?.name && r.name !== last) { last = r.name; screen(r.name) }
|
|
314
|
+
}
|
|
315
|
+
const unsubscribe = ref?.addListener?.('state', onState)
|
|
316
|
+
onState()
|
|
317
|
+
return () => { if (typeof unsubscribe === 'function') unsubscribe() }
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
return {
|
|
321
|
+
start, stop, flush, screen, identify, track, captureError, trackNavigation,
|
|
322
|
+
get sessionId() { return sessionId },
|
|
323
|
+
get recording() { return started && !stopped },
|
|
324
|
+
}
|
|
325
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// @spectosh/react-native — Specto for React Native apps. Wires React Native's
|
|
2
|
+
// AppState and Platform into the platform-neutral core (core.js).
|
|
3
|
+
//
|
|
4
|
+
// import AsyncStorage from '@react-native-async-storage/async-storage'
|
|
5
|
+
// import { init } from '@spectosh/react-native'
|
|
6
|
+
// const specto = await init({ key: 'pk_…', endpoint: 'https://specto.example.com', storage: AsyncStorage, app: { name: 'Shop', version: '1.4.2' } })
|
|
7
|
+
// specto.trackNavigation(navigationRef) // React Navigation: screens
|
|
8
|
+
// specto.identify(user.id, { plan: 'pro' })
|
|
9
|
+
// specto.track('checkout_started', { items: 3 })
|
|
10
|
+
import { AppState, Platform } from 'react-native'
|
|
11
|
+
import { createSpecto } from './core.js'
|
|
12
|
+
|
|
13
|
+
export { createSpecto, userAgentFor, scrubText, VERSION } from './core.js'
|
|
14
|
+
|
|
15
|
+
export async function init(options = {}) {
|
|
16
|
+
const specto = createSpecto({
|
|
17
|
+
appState: AppState,
|
|
18
|
+
platform: {
|
|
19
|
+
os: Platform.OS,
|
|
20
|
+
version: String(Platform.Version ?? ''),
|
|
21
|
+
isPad: Boolean(Platform.isPad),
|
|
22
|
+
model: Platform.constants?.Model,
|
|
23
|
+
tablet: options.tablet,
|
|
24
|
+
},
|
|
25
|
+
...options,
|
|
26
|
+
})
|
|
27
|
+
await specto.start()
|
|
28
|
+
return specto
|
|
29
|
+
}
|