@starko-one/sdk 0.0.0-stage → 0.1.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/CHANGELOG.md +248 -0
  2. package/LICENSE +17 -0
  3. package/NOTICE +58 -0
  4. package/README.md +81 -2
  5. package/dist/api-BAFm4Lxj.d.ts +558 -0
  6. package/dist/api-DNrctwJu.d.cts +558 -0
  7. package/dist/browser/index.cjs +168 -0
  8. package/dist/browser/index.d.cts +131 -0
  9. package/dist/browser/index.d.ts +131 -0
  10. package/dist/browser/index.js +7 -0
  11. package/dist/build/rollup.cjs +22 -0
  12. package/dist/build/rollup.d.cts +34 -0
  13. package/dist/build/rollup.d.ts +34 -0
  14. package/dist/build/rollup.js +3 -0
  15. package/dist/build/vite.cjs +51 -0
  16. package/dist/build/vite.d.cts +23 -0
  17. package/dist/build/vite.d.ts +23 -0
  18. package/dist/build/vite.js +46 -0
  19. package/dist/build/webpack.cjs +18 -0
  20. package/dist/build/webpack.d.cts +39 -0
  21. package/dist/build/webpack.d.ts +39 -0
  22. package/dist/build/webpack.js +3 -0
  23. package/dist/chunk-2PM4FRM5.cjs +431 -0
  24. package/dist/chunk-335HNCOJ.js +249 -0
  25. package/dist/chunk-3AW5B2WW.js +115 -0
  26. package/dist/chunk-3R5TQAWD.js +216 -0
  27. package/dist/chunk-6H5MOPTQ.cjs +1230 -0
  28. package/dist/chunk-7TKNT3QJ.cjs +2487 -0
  29. package/dist/chunk-A4WLNFMU.cjs +220 -0
  30. package/dist/chunk-ALYFFOPR.cjs +134 -0
  31. package/dist/chunk-BVVFVRMO.js +1113 -0
  32. package/dist/chunk-CIHNKN62.cjs +15 -0
  33. package/dist/chunk-CMGCH6HD.js +1212 -0
  34. package/dist/chunk-D6QAPQ7L.cjs +56 -0
  35. package/dist/chunk-DUO5V6WZ.js +213 -0
  36. package/dist/chunk-EC2WZ6PG.js +90 -0
  37. package/dist/chunk-EFURLFJT.cjs +187 -0
  38. package/dist/chunk-EROUORMY.js +53 -0
  39. package/dist/chunk-LXBXFOAP.cjs +96 -0
  40. package/dist/chunk-MF6SA6DB.js +563 -0
  41. package/dist/chunk-N5R6ORIB.js +413 -0
  42. package/dist/chunk-N6R6BWHK.cjs +142 -0
  43. package/dist/chunk-QAGGN2T7.cjs +225 -0
  44. package/dist/chunk-QV4HRIDD.cjs +659 -0
  45. package/dist/chunk-TKNDYQB3.cjs +583 -0
  46. package/dist/chunk-UI5YC4TH.js +131 -0
  47. package/dist/chunk-VEHZYLK6.cjs +1151 -0
  48. package/dist/chunk-VNCWOGTI.js +12 -0
  49. package/dist/chunk-VWNIOGE6.js +180 -0
  50. package/dist/chunk-WDKRKGYF.js +608 -0
  51. package/dist/chunk-XOZIXBUK.js +2462 -0
  52. package/dist/chunk-ZS3K3SDR.cjs +258 -0
  53. package/dist/cli/index.cjs +2780 -0
  54. package/dist/common-DLFAqL2d.d.cts +36 -0
  55. package/dist/common-DbSXkaw6.d.ts +36 -0
  56. package/dist/dedupe-Bh5riD8Z.d.cts +13 -0
  57. package/dist/dedupe-DoYiSx-9.d.ts +13 -0
  58. package/dist/handler-BcnsnvhF.d.cts +82 -0
  59. package/dist/handler-qHzilC9T.d.ts +82 -0
  60. package/dist/index.cjs +309 -0
  61. package/dist/index.d.cts +187 -0
  62. package/dist/index.d.ts +187 -0
  63. package/dist/index.js +4 -0
  64. package/dist/next/client.cjs +113 -0
  65. package/dist/next/client.d.cts +26 -0
  66. package/dist/next/client.d.ts +26 -0
  67. package/dist/next/client.js +41 -0
  68. package/dist/next/config.cjs +277 -0
  69. package/dist/next/config.d.cts +193 -0
  70. package/dist/next/config.d.ts +193 -0
  71. package/dist/next/config.js +263 -0
  72. package/dist/next/index.cjs +148 -0
  73. package/dist/next/index.d.cts +32 -0
  74. package/dist/next/index.d.ts +32 -0
  75. package/dist/next/index.js +59 -0
  76. package/dist/node/index.cjs +257 -0
  77. package/dist/node/index.d.cts +145 -0
  78. package/dist/node/index.d.ts +145 -0
  79. package/dist/node/index.js +83 -0
  80. package/dist/options-BUhWuWJX.d.cts +79 -0
  81. package/dist/options-BUhWuWJX.d.ts +79 -0
  82. package/dist/react/index.cjs +107 -0
  83. package/dist/react/index.d.cts +84 -0
  84. package/dist/react/index.d.ts +84 -0
  85. package/dist/react/index.js +103 -0
  86. package/dist/scope-D1ouJm2h.d.cts +628 -0
  87. package/dist/scope-D1ouJm2h.d.ts +628 -0
  88. package/dist/server-edge-7624N3WF.cjs +51 -0
  89. package/dist/server-edge-BEEXWL7T.js +48 -0
  90. package/dist/server-node-ET4LIPEC.cjs +27 -0
  91. package/dist/server-node-TQUVMZUC.js +24 -0
  92. package/dist/session-C_WzbEN2.d.cts +4 -0
  93. package/dist/session-C_WzbEN2.d.ts +4 -0
  94. package/dist/session-propagation-Pr0Zb9Zn.d.cts +30 -0
  95. package/dist/session-propagation-RM5py1bp.d.ts +30 -0
  96. package/dist/starko.min.js +6 -0
  97. package/docs/browser.md +386 -0
  98. package/docs/configuration.md +310 -0
  99. package/docs/nextjs.md +488 -0
  100. package/docs/node.md +427 -0
  101. package/docs/other-backends.md +232 -0
  102. package/docs/privacy.md +112 -0
  103. package/docs/react.md +187 -0
  104. package/docs/source-maps.md +482 -0
  105. package/docs/troubleshooting.md +263 -0
  106. package/docs/widget.md +84 -0
  107. package/docs/wire-format.md +547 -0
  108. package/package.json +191 -4
package/docs/node.md ADDED
@@ -0,0 +1,427 @@
1
+ # Node.js
2
+
3
+ `@starko-one/sdk/node` reports errors from servers, workers, scripts and
4
+ serverless functions on Node.js 18 and later. It uses Node's built-ins only.
5
+ For Next.js use [nextjs.md](./nextjs.md), which starts this SDK for you.
6
+
7
+ ## Shortest setup
8
+
9
+ ```sh
10
+ npm install @starko-one/sdk
11
+ ```
12
+
13
+ ```ts
14
+ import * as Starko from "@starko-one/sdk/node";
15
+
16
+ Starko.init({
17
+ workspaceKey: "<STARKO_WORKSPACE_KEY>",
18
+ apiKey: process.env.STARKO_API_KEY,
19
+ release: "api@2.3.0",
20
+ environment: "production",
21
+ });
22
+ ```
23
+
24
+ Call `init` once, at start-up, before the rest of your app runs, so errors
25
+ thrown while it starts are captured. From then on the SDK captures uncaught
26
+ exceptions and unhandled promise rejections, and isolates every incoming HTTP
27
+ request (below). `init` never throws.
28
+
29
+ Set `environment` from your host's own variable where it has one (on
30
+ Vercel, `VERCEL_ENV`), not from `NODE_ENV` alone: hosts that build preview
31
+ deployments like production ones set `NODE_ENV=production` there too, and
32
+ preview errors would be filed as production.
33
+
34
+ `release` defaults to the `STARKO_RELEASE` environment variable, then to the
35
+ release a build plugin wrote into your server bundle. The bundle's release
36
+ is read for each event, so `init` may run before the bundle loads
37
+ (`node --require ./instrument.js dist/server.js`). If you upload source
38
+ maps (only needed when your server code is bundled or compiled), use the
39
+ release they were uploaded for.
40
+
41
+ ## The secret key (`apiKey`)
42
+
43
+ `apiKey` is optional. It is a secret key (`sk_starko_…`) with the
44
+ `errors:write` scope, created in Starko under Settings. With it:
45
+
46
+ - the `user.id` your server sets is linked to the customer without a user
47
+ hash (a browser cannot be trusted with that; a server holding the key can);
48
+ - the per-IP limits of the ingest API do not apply to your server.
49
+
50
+ It is sent as `Authorization: Bearer …` on the requests that send events,
51
+ only to the configured `host`, and never logged. Redirects are never
52
+ followed, so it cannot be forwarded to another host. Keep it in an
53
+ environment variable on the server. **Never ship it to a browser**: anyone
54
+ holding it can send events that Starko trusts. Without it, the server's
55
+ events are accepted like a browser's, and a user needs a hash to be linked
56
+ (see [browser.md](./browser.md#identify-the-user)).
57
+
58
+ ## Every request in its own scope
59
+
60
+ From `init` on, each request an HTTP, HTTPS or HTTP/2 server receives
61
+ runs in its own scope, with no middleware: the user, tags, breadcrumbs and
62
+ console lines of one request never appear on another request's errors, and
63
+ every event carries the request's method, URL and route and the browser's
64
+ session id (from the `x-starko-session-id` header, see
65
+ [nextjs.md](./nextjs.md#how-a-server-error-links-to-the-browser-session)).
66
+ The SDK finds each server through Node's diagnostics channels, at its
67
+ first connection or request, and wraps the server's `emit`, so servers
68
+ created before or after `init` are covered. If the SDK's own code fails,
69
+ your handler runs unscoped; what your handler throws is never changed.
70
+
71
+ A request scope starts from the **base**: the `user` passed to `init`, and
72
+ the tags, extra and contexts set before the process began serving (below).
73
+ It never starts with a user set with `setUser` and never with earlier
74
+ breadcrumbs.
75
+
76
+ Covered: any framework that serves through a `node:http`, `node:https` or
77
+ `node:http2` server (Express is tested). Each `request`, `checkContinue`,
78
+ `checkExpectation`, `upgrade` (WebSockets) and `connect` event gets its own
79
+ scope, and on HTTP/2 servers both the compatibility API
80
+ (`http2.createServer(handler)`, `createSecureServer`) and the raw `stream`
81
+ event do. Tested on Node 20, 22, 24 and 26.
82
+
83
+ Not covered, so use `wrapHandler` or `runWithRequestScope` (below):
84
+
85
+ - servers that do not go through `node:http` (uWebSockets.js, for one);
86
+ - the Edge runtime (see [nextjs.md](./nextjs.md#edge-runtime)).
87
+
88
+ So in a request handler:
89
+
90
+ ```ts
91
+ import { createServer } from "node:http";
92
+ import * as Starko from "@starko-one/sdk/node";
93
+
94
+ Starko.init({ workspaceKey: "<STARKO_WORKSPACE_KEY>", apiKey: process.env.STARKO_API_KEY });
95
+
96
+ createServer((req, res) => {
97
+ const userId = req.headers["x-user-id"];
98
+ if (typeof userId === "string") Starko.setUser({ id: userId }); // this request only
99
+ Starko.setTag("tenant", "acme"); // this request only
100
+ res.end("ok");
101
+ }).listen(3000);
102
+ ```
103
+
104
+ ### Code outside a request
105
+
106
+ A process **begins serving** at the first connection or request one of its
107
+ servers receives after `init`, at Next.js's `register()`, at the first
108
+ request scope (`runWithRequestScope`, `wrapHandler`, Express), or when you
109
+ call `markServing()`, whichever comes first.
110
+
111
+ - **Before that** (start-up, a CLI, a script), what you set outside a
112
+ request (`setUser`, `setTag`, breadcrumbs) applies to every later event.
113
+ - **When it begins**, the base is fixed: `init({ user })` and the tags,
114
+ extra and contexts set so far. `setUser` users and breadcrumbs are not
115
+ part of it.
116
+ - **After that**, code outside any request (a job, a queue consumer, a
117
+ timer, a database pool's callback, top-level code) gets a scope of its
118
+ own on its first write. What it sets is seen by the rest of that
119
+ synchronous code and by everything it starts afterwards (its `await`s,
120
+ timers, promises), never by a request or another job. `setUser` with a
121
+ different user starts a fresh scope from the base, so the next job of a
122
+ loop carries none of the previous job's tags or breadcrumbs. A later
123
+ callback of the same timer or socket (the next tick of an interval, the
124
+ next reply on a pooled connection) does not see what an earlier one set.
125
+ An error captured outside a request where nothing was set carries the
126
+ base.
127
+
128
+ A worker or queue consumer with no HTTP server begins serving only at its
129
+ first request scope: call `markServing()` after `init` to get this per-job
130
+ behaviour from the start. For exact boundaries, run each job in `runWithRequestScope`:
131
+
132
+ ```ts
133
+ import * as Starko from "@starko-one/sdk/node";
134
+
135
+ Starko.init({ workspaceKey: "<STARKO_WORKSPACE_KEY>", apiKey: process.env.STARKO_API_KEY });
136
+ Starko.markServing();
137
+
138
+ export function handleJob(job: { id: string; userId: string; run: () => Promise<void> }) {
139
+ return Starko.runWithRequestScope(async () => {
140
+ Starko.setUser({ id: job.userId }); // this job only
141
+ Starko.setTag("job", job.id);
142
+ try {
143
+ await job.run();
144
+ } catch (error) {
145
+ Starko.captureException(error);
146
+ }
147
+ });
148
+ }
149
+ ```
150
+
151
+ Limits of the automatic per-job scopes:
152
+
153
+ - Two jobs started in the same synchronous run, before their first
154
+ `await`, share one scope unless they set different users. Wrap each in
155
+ `runWithRequestScope`.
156
+ - A user and breadcrumbs set before serving began stay with the global
157
+ scope: a job started at start-up that captures an error after serving
158
+ began does not carry them. Set the user again in the job, or pass a
159
+ process-wide user to `init({ user })`.
160
+ - Writing to `getGlobalScope()` after serving began reaches no event.
161
+
162
+ ## Express
163
+
164
+ ```ts
165
+ import express from "express";
166
+ import * as Starko from "@starko-one/sdk/node";
167
+
168
+ Starko.init({ workspaceKey: "<STARKO_WORKSPACE_KEY>", apiKey: process.env.STARKO_API_KEY });
169
+
170
+ const app = express();
171
+ app.use(Starko.expressRequestHandler()); // first
172
+
173
+ app.get("/orders/:id", (req, res) => {
174
+ throw new Error(`Order ${req.params.id} not found in the warehouse`);
175
+ });
176
+
177
+ app.use(Starko.expressErrorHandler()); // after the routes, before your own error handlers
178
+ app.use((err: Error, req: express.Request, res: express.Response, next: express.NextFunction) => {
179
+ res.status(500).send("Something went wrong");
180
+ });
181
+
182
+ app.listen(3000);
183
+ ```
184
+
185
+ - `expressErrorHandler()` captures errors passed to `next(err)` (and, on
186
+ Express 5, thrown or rejected by handlers), then calls `next(err)`, so
187
+ your error handling runs exactly as before. By default it captures only
188
+ errors that become a 5xx: a `status`, `statusCode`, `status_code` or
189
+ `output.statusCode` of 500 or more, or none. Change that with
190
+ `expressErrorHandler({ shouldHandleError: (error) => true })`. A captured
191
+ error with a status below 500 is recorded as handled.
192
+ - `expressRequestHandler()` is optional (every request already has its own
193
+ scope). It records the route as Express matched it (`/orders/:id`,
194
+ including the mount path of nested routers) and opens the request scope
195
+ itself where the automatic isolation is not active.
196
+ - Express 4 and 5.
197
+
198
+ ## Other frameworks and serverless: `wrapHandler`
199
+
200
+ ```ts
201
+ import * as Starko from "@starko-one/sdk/node";
202
+
203
+ Starko.init({ workspaceKey: "<STARKO_WORKSPACE_KEY>", apiKey: process.env.STARKO_API_KEY });
204
+
205
+ export const handler = Starko.wrapHandler(
206
+ async (event: { rawPath: string; requestContext: { http: { method: string } } }) => {
207
+ if (!event.rawPath.startsWith("/api/")) throw new Error(`No route for ${event.rawPath}`);
208
+ return { statusCode: 200, body: "ok" };
209
+ },
210
+ { getRequestData: (event) => ({ method: event.requestContext.http.method, url: event.rawPath }) },
211
+ );
212
+ ```
213
+
214
+ Each call of the wrapped function:
215
+
216
+ - runs in its own request scope. When the first argument is a request
217
+ (Node's `IncomingMessage`, Express's `req`, a Fetch `Request`), its method,
218
+ URL and session header are read; otherwise pass `getRequestData`;
219
+ - captures what the function throws or rejects with (as unhandled), then
220
+ rethrows it unchanged;
221
+ - flushes queued events before the returned promise settles, for at most
222
+ `flushTimeout` (default 2000 ms), because a serverless platform may freeze
223
+ the process as soon as the handler returns. When the platform offers a
224
+ `waitUntil` for the request (Vercel, Cloudflare via OpenNext), the flush is
225
+ handed to it instead and the call settles at once. Nothing is flushed when
226
+ nothing is queued. A synchronous function stays synchronous: its flush is
227
+ started, not awaited.
228
+
229
+ For code that is not a handler, `runWithRequestScope(fn, requestData?)`
230
+ runs `fn` in a new request scope, a fork of the base (not of the scope it
231
+ is called from), and begins serving. The callback comes **first**, the
232
+ request second. The request is `{ method?, url?, route?, sessionId? }`, or
233
+ a function returning it; `requestDataFrom(req)` builds it from a Node,
234
+ Express or Fetch request object. `runWithRequestScope` returns what `fn`
235
+ returns, and what `fn` throws propagates (it is not captured):
236
+
237
+ ```ts
238
+ import type { IncomingMessage } from "node:http";
239
+ import * as Starko from "@starko-one/sdk/node";
240
+
241
+ export function handle(req: IncomingMessage, work: () => Promise<void>) {
242
+ return Starko.runWithRequestScope(async () => {
243
+ try {
244
+ await work();
245
+ } catch (error) {
246
+ Starko.captureException(error);
247
+ }
248
+ }, Starko.requestDataFrom(req));
249
+ }
250
+ ```
251
+
252
+ `withScope(fn)` forks the current scope for one callback.
253
+
254
+ ## Dropping the errors of some requests
255
+
256
+ `denyUrls` and `allowUrls` match the file path of the most recent stack
257
+ frame, not the URL of the request. To drop server events by request path
258
+ (for example an app that hosts or proxies its own error ingest, whose
259
+ failures would otherwise report themselves), check `event.request.url` in
260
+ `beforeSend`. On a server it holds the URL of the request the error
261
+ happened in, as the request gave it: usually a path with its query
262
+ (`/api/ingest/errors?…`), absolute for a Fetch `Request`. An event captured
263
+ outside any request has no `request`.
264
+
265
+ ```ts
266
+ import * as Starko from "@starko-one/sdk/node";
267
+
268
+ Starko.init({
269
+ workspaceKey: "<STARKO_WORKSPACE_KEY>",
270
+ beforeSend(event) {
271
+ const url = event.request?.url;
272
+ if (url && new URL(url, "http://localhost").pathname.startsWith("/api/ingest/")) return null;
273
+ return event;
274
+ },
275
+ });
276
+ ```
277
+
278
+ The same works in Next's `register`.
279
+
280
+ ## Flush before the process ends
281
+
282
+ The SDK never keeps a process alive: its timers and sockets do not hold the
283
+ event loop. What happens to queued events:
284
+
285
+ | How the process ends | Queued events |
286
+ | --- | --- |
287
+ | The event loop empties (a script finishes) | Sent first: the SDK holds the process for at most `shutdownTimeout` (default 2000 ms). A process with nothing queued exits at once. |
288
+ | `SIGTERM` / `SIGINT`, and your app has **no** handler for that signal | Sent first (at most `shutdownTimeout`), then the signal is raised again, so the process ends the way the signal ends it (exit status 128 + signal number). |
289
+ | `SIGTERM` / `SIGINT`, and your app **has** a handler | The SDK does nothing; your handler decides. Flush in it (below). |
290
+ | `process.exit()` | **Lost.** `process.exit` ends the process synchronously and no network request can run after it. Flush first. |
291
+ | A crash (see below) | Sent for at most `fatalFlushTimeout` (default 1000 ms). |
292
+
293
+ None of these flushes waits for the workspace's remote config: the events
294
+ go out at once.
295
+
296
+ So before any `process.exit`:
297
+
298
+ ```ts
299
+ import * as Starko from "@starko-one/sdk/node";
300
+
301
+ Starko.init({ workspaceKey: "<STARKO_WORKSPACE_KEY>" });
302
+
303
+ process.on("SIGTERM", async () => {
304
+ await Starko.flush(2000); // resolves true when everything went out within 2 s
305
+ process.exit(143);
306
+ });
307
+ ```
308
+
309
+ `close(timeout)` flushes and then removes every hook; nothing is sent after it.
310
+
311
+ ### Shutdown and signals
312
+
313
+ The `SIGTERM` / `SIGINT` flush is the `FlushOnExit` integration. Turn the
314
+ signal part off with `flushOnExitIntegration({ signals: false })` (see
315
+ [configuration.md](./configuration.md#adding-and-removing-integrations)).
316
+ The `beforeExit` flush stays.
317
+
318
+ ## When the process crashes
319
+
320
+ An uncaught exception, or a promise rejection Node turns into one:
321
+
322
+ - **Your app has its own `uncaughtException` listener:** the SDK only
323
+ captures the error (level `error`). Your listener decides what happens, as
324
+ before.
325
+ - **It has none** (another error SDK's listener does not count): Node would
326
+ print the error and exit with code 1. The SDK captures it (level `fatal`),
327
+ prints it to stderr the way Node does, sends it for at most
328
+ `fatalFlushTimeout` (default 1000 ms), then calls `process.exit(1)`
329
+ (`process.abort()` under `--abort-on-uncaught-exception`). While it sends,
330
+ new HTTP connections are refused, as a dead process would refuse them, and
331
+ a second uncaught error is captured and printed without extending the
332
+ wait. Your timers and I/O keep running during the wait, and
333
+ `process.on("exit")` listeners run after it. For a thrown value that is
334
+ not an `Error`, the printed text has no source excerpt.
335
+ - **In a worker thread** (`worker_threads`) with no listener of its own:
336
+ the SDK captures the error (level `fatal`), sends it for at most
337
+ `fatalFlushTimeout`, then hands it back to Node, so the worker ends and
338
+ the parent's `Worker` emits `'error'` with the same value and the same
339
+ exit code as without the SDK. `uncaughtExceptionMonitor` listeners in the
340
+ worker run twice. With a listener of its own, the worker's error is only
341
+ captured (level `error`).
342
+
343
+ What the SDK never changes: whether the process exits, its exit code, and
344
+ what Node does with an unhandled rejection under your
345
+ `--unhandled-rejections` mode:
346
+
347
+ | Mode | Captured | What Node does (unchanged) |
348
+ | --- | --- | --- |
349
+ | `throw` (default) | Yes | Raises it as an uncaught exception (above), unless your app listens for `unhandledRejection`. |
350
+ | `strict` | Yes, as an uncaught exception | Raises it as an uncaught exception. |
351
+ | `warn-with-error-code` | Yes | Prints a warning and sets exit code 1. |
352
+ | `warn`, `none` | Yes | Prints a warning, or nothing. |
353
+
354
+ ## Limits on a server
355
+
356
+ A server runs for weeks, so there is no lifetime cap. Instead:
357
+
358
+ - per error: 10 at once, then 1 every 10 seconds. An error here is its
359
+ type and the first 120 characters of its message, with numbers, UUIDs
360
+ and long hex ids masked
361
+ (`Order 1234 not found` and `Order 98 not found` count as one); without
362
+ a message, its type and the file and line it was thrown from;
363
+ - 300 events a minute across all errors (`maxEventsPerMinute`), so a crash
364
+ loop throwing ever new errors still sends at most 300 a minute;
365
+ - 500 events waiting in memory (`maxQueueSize`); the oldest are dropped first.
366
+
367
+ Drops by the first two limits are printed even without `debug`, at most
368
+ once a minute per limit, with the number dropped since the previous line
369
+ (for the per-error limit, also the latest dropped error's key); a full
370
+ queue is printed once. The workspace's
371
+ remote config (on/off, sample rate, rules) is read just before the first
372
+ event is sent, so an idle process makes no request at all.
373
+
374
+ ## Proxies
375
+
376
+ The SDK sends with `node:http` / `node:https`. On Node 24.5 and later, run
377
+ with `NODE_USE_ENV_PROXY=1` and it honours `HTTPS_PROXY` and `NO_PROXY`. On
378
+ any version, you can pass the `fetch` to send with instead, for example
379
+ undici's with a proxy agent:
380
+
381
+ ```ts
382
+ import { fetch as undiciFetch, ProxyAgent } from "undici";
383
+ import * as Starko from "@starko-one/sdk/node";
384
+
385
+ const dispatcher = new ProxyAgent("http://proxy.internal:3128");
386
+
387
+ Starko.init({
388
+ workspaceKey: "<STARKO_WORKSPACE_KEY>",
389
+ fetch: ((input: string, init: RequestInit) => undiciFetch(input, { ...init, dispatcher })) as unknown as typeof fetch,
390
+ });
391
+ ```
392
+
393
+ With your own `fetch`, a request in flight keeps the process alive until it
394
+ ends (at most 10 seconds), because the SDK cannot release its socket.
395
+
396
+ ## Source lines
397
+
398
+ Each in-app frame of an event gets up to 7 lines of source before and after
399
+ it, read from disk after sampling and the rate limits (so only for events
400
+ that are sent). A file is read only when all of these hold:
401
+
402
+ - the frame names an absolute path or a `file://` URL;
403
+ - the file ends in `.js`, `.mjs`, `.cjs`, `.jsx`, `.ts`, `.tsx`, `.mts` or
404
+ `.cts` (before and after resolving symbolic links) and its name does not
405
+ start with a dot;
406
+ - its real path is inside the application root or a directory you add
407
+ with `contextLinesIntegration({ roots })`. The application root is the
408
+ working directory at `init` (`process.cwd()`). When that is a filesystem
409
+ root (`/`, the default working directory of a systemd service), it is
410
+ the main module's directory instead (`require.main`, else the script in
411
+ `process.argv[1]`); when that is a filesystem root too, or unknown, no
412
+ file is read. A filesystem root given in `roots` is ignored;
413
+ - it is not under `node_modules` (unless `includeNodeModules: true`), not
414
+ larger than 1 MiB, not minified (no line over 1000 characters, no `.min.`
415
+ in the name).
416
+
417
+ Never read: `.env` files and any other dotfile, files outside those
418
+ directories (a stack can name any path), files reached through a link that
419
+ points outside them, and anything that is not a source file. At most 10
420
+ files per event, each line cut to 300 characters. Turn source lines off by
421
+ removing the `ContextLines` integration.
422
+
423
+ ## See also
424
+
425
+ - [configuration.md](./configuration.md#nodejs): every option and its default.
426
+ - [privacy.md](./privacy.md): what a server event contains.
427
+ - [troubleshooting.md](./troubleshooting.md).
@@ -0,0 +1,232 @@
1
+ # Servers without a Starko SDK
2
+
3
+ There is a Starko SDK for browsers and Node.js only. A server written in
4
+ another language can report errors in two ways:
5
+
6
+ - **(a) the HTTP API** that the SDKs use: any language, full control,
7
+ customers linked when you send a secret key;
8
+ - **(b) PostHog's server SDKs pointed at Starko**: less code, but only for
9
+ the languages listed below, and errors are never linked to a customer.
10
+
11
+ ## (a) The HTTP API
12
+
13
+ One `POST` with a JSON body. A complete example, a Python `KeyError` sent as
14
+ a `custom` frame:
15
+
16
+ ```sh
17
+ curl -sS https://v2.starko.one/api/v1/ingest/errors \
18
+ -H "Content-Type: application/json" \
19
+ -H "Authorization: Bearer <STARKO_API_KEY>" \
20
+ --data-binary @- <<'JSON'
21
+ {
22
+ "v": 1,
23
+ "workspace": "<STARKO_WORKSPACE_KEY>",
24
+ "sdk": { "name": "acme.billing-worker", "version": "1.0.0" },
25
+ "sent_at": 1795000000500,
26
+ "events": [
27
+ {
28
+ "event_id": "0b0e7a52-5c1f-4c58-9a57-6f1d2f0c9a11",
29
+ "timestamp": 1795000000000,
30
+ "platform": "python",
31
+ "level": "error",
32
+ "exception_list": [
33
+ {
34
+ "type": "KeyError",
35
+ "value": "'invoice_id'",
36
+ "mechanism": { "type": "generic", "handled": false },
37
+ "stacktrace": {
38
+ "type": "raw",
39
+ "frames": [
40
+ { "platform": "custom", "lang": "python", "filename": "billing/jobs.py", "function": "charge", "module": "billing.jobs", "lineno": 42, "in_app": true, "resolved": true },
41
+ { "platform": "custom", "lang": "python", "filename": "billing/worker.py", "function": "run", "module": "billing.worker", "lineno": 17, "in_app": true, "resolved": true }
42
+ ]
43
+ }
44
+ }
45
+ ],
46
+ "release": "billing@3.1.0",
47
+ "environment": "production",
48
+ "server_name": "worker-1",
49
+ "user": { "id": "user_123" }
50
+ }
51
+ ]
52
+ }
53
+ JSON
54
+ ```
55
+
56
+ Required fields:
57
+
58
+ | Where | Fields |
59
+ | --- | --- |
60
+ | Body | `v` (always `1`), `workspace` (the workspace key), `sdk` (`name`, `version` of your sender), `sent_at` (your clock, epoch milliseconds, set again on every retry), `events` (1 to 20). |
61
+ | Each event | `event_id` (a new UUID per event; Starko counts an id once, so a retry never double-counts), `timestamp` (epoch milliseconds), `platform` (`dotnet`, `php`, `python`, `ruby`, `go`, `java`, `other`, …), `level` (`fatal`, `error`, `warning`, `info`, `debug`; only `error` and `fatal` can file a ticket), `exception_list` (at least one). |
62
+ | Each exception | `type`, `value` (the message). |
63
+ | Each `custom` frame | `platform: "custom"` and `lang` (lowercase language name). |
64
+
65
+ Frames are ordered **most recent call first**: `frames[0]` is where the
66
+ error was thrown. `custom` frames are stored as you send them; send
67
+ `"resolved": true` when they already show your source (languages that run
68
+ their source, or carry debug info). Everything else (`release`, `user`,
69
+ `tags`, `extra`, `breadcrumbs`, `request`, …) is optional and described in
70
+ [wire-format.md](./wire-format.md), with the limits on each field.
71
+
72
+ `Authorization: Bearer <STARKO_API_KEY>` is optional: a secret key with the
73
+ `errors:write` scope. With it, the `user.id` you send is linked to the
74
+ customer in Starko and the per-IP limits do not apply. Without it, a user is
75
+ kept as text unless you send a user hash (see
76
+ [browser.md](./browser.md#identify-the-user)).
77
+
78
+ ### Responses
79
+
80
+ Every response is JSON, `{ "ok": …, "message": …, "data": … }`; when a
81
+ request is refused, `data.reason` says why.
82
+
83
+ | Status | `data.reason` | What to do |
84
+ | --- | --- | --- |
85
+ | 200 | | Done. `data.accepted` and `data.rejected` count the events; rejected ones failed validation. |
86
+ | 3xx | | Do not follow the redirect (the POST would become a GET and your key would go to another host). Drop the batch and fix the URL. |
87
+ | 400 | `invalid`, `unsupported_version` | Drop the batch: the body is malformed. |
88
+ | 401 | `invalid` | Your secret key is not valid. A configuration error: do not retry; fix or remove the key. |
89
+ | 401 | `unknown_workspace` | Unknown workspace key. Stop sending until it is fixed. |
90
+ | 403 | `disabled` | Error tracking is off for the workspace. Stop sending. |
91
+ | 413 | `too_large` | Body too large (512 KiB as sent, 2 MiB decompressed). Halve the batch and retry once. |
92
+ | 429 | `rate_limit` | Wait `Retry-After` seconds, then retry. |
93
+ | 429 | `quota` | The workspace's allowance is used up. Drop the batch; send nothing until `Retry-After` has passed. |
94
+ | 503 | `busy` | Wait `Retry-After` seconds, then retry. |
95
+
96
+ Retry network failures and 5xx with back-off, at most three attempts per
97
+ batch, and never sooner than `Retry-After` when the answer has one.
98
+ A 401 or 403 **without** one of the reasons above comes from something in
99
+ between (a proxy, a firewall) and is temporary. The full rules are in
100
+ [wire-format.md](./wire-format.md#responses).
101
+
102
+ ### PHP
103
+
104
+ ```php
105
+ <?php
106
+ function starko_report(Throwable $e, bool $handled = true): void
107
+ {
108
+ $trace = $e->getTrace();
109
+ // Frame 0 is where the exception was thrown; each trace entry adds its caller.
110
+ $frames = [['platform' => 'custom', 'lang' => 'php', 'filename' => $e->getFile(), 'lineno' => $e->getLine(),
111
+ 'function' => $trace[0]['function'] ?? '{main}', 'resolved' => true]];
112
+ foreach ($trace as $i => $call) {
113
+ if (!isset($call['file'], $call['line'])) continue;
114
+ $frames[] = ['platform' => 'custom', 'lang' => 'php', 'filename' => $call['file'], 'lineno' => $call['line'],
115
+ 'function' => $trace[$i + 1]['function'] ?? '{main}', 'resolved' => true];
116
+ }
117
+
118
+ $id = random_bytes(16);
119
+ $id[6] = chr((ord($id[6]) & 0x0f) | 0x40);
120
+ $id[8] = chr((ord($id[8]) & 0x3f) | 0x80);
121
+ $now = (int) round(microtime(true) * 1000);
122
+
123
+ $body = json_encode([
124
+ 'v' => 1,
125
+ 'workspace' => '<STARKO_WORKSPACE_KEY>',
126
+ 'sdk' => ['name' => 'acme.php', 'version' => '1.0.0'],
127
+ 'sent_at' => $now,
128
+ 'events' => [[
129
+ 'event_id' => vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($id), 4)),
130
+ 'timestamp' => $now,
131
+ 'platform' => 'php',
132
+ 'level' => 'error',
133
+ 'exception_list' => [[
134
+ 'type' => get_class($e),
135
+ 'value' => $e->getMessage(),
136
+ 'mechanism' => ['type' => 'generic', 'handled' => $handled],
137
+ 'stacktrace' => ['type' => 'raw', 'frames' => array_slice($frames, 0, 50)],
138
+ ]],
139
+ ]],
140
+ ], JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE);
141
+
142
+ $context = stream_context_create(['http' => [
143
+ 'method' => 'POST',
144
+ 'header' => "Content-Type: application/json\r\n",
145
+ 'content' => $body,
146
+ 'timeout' => 5,
147
+ 'follow_location' => 0,
148
+ 'ignore_errors' => true,
149
+ ]]);
150
+ @file_get_contents('https://v2.starko.one/api/v1/ingest/errors', false, $context);
151
+ }
152
+
153
+ set_exception_handler(function (Throwable $e): void {
154
+ starko_report($e, false);
155
+ error_log((string) $e);
156
+ http_response_code(500);
157
+ });
158
+ ```
159
+
160
+ Call `starko_report($e)` from your own `catch` blocks too. This sends one
161
+ exception; chain `$e->getPrevious()` as further items of `exception_list`
162
+ if you need causes. A web request waits for the call (at most the 5-second
163
+ timeout); for high volumes, queue the reports and send them in batches of up
164
+ to 20 from a worker.
165
+
166
+ ## (b) PostHog server SDKs pointed at Starko
167
+
168
+ Starko accepts PostHog's capture format at `{your Starko host}/api/ingest/ph`.
169
+ Point a PostHog **server** SDK at it, with the Starko workspace key as the
170
+ project token:
171
+
172
+ - Only `$exception` events are kept. Every other event (page views,
173
+ identify, custom events, …) is discarded when the request arrives: never
174
+ queued, stored or logged.
175
+ - These errors are **never linked to a customer**. The `distinct_id` is kept
176
+ on the error as text.
177
+ - Use a PostHog client that sends **only exceptions** to Starko. If you also
178
+ use PostHog for analytics, keep that in a separate client pointed at
179
+ PostHog.
180
+ - In browsers, use `@starko-one/sdk` instead.
181
+
182
+ ### Python (`posthog` 8 and later)
183
+
184
+ ```python
185
+ from posthog import Posthog
186
+
187
+ posthog = Posthog(project_api_key="<STARKO_WORKSPACE_KEY>", host="https://v2.starko.one/api/ingest/ph", enable_exception_autocapture=True)
188
+ ```
189
+
190
+ Do not set `personal_api_key`: it starts feature-flag polling. For Django,
191
+ Flask and ASGI apps, use the integrations as PostHog's documentation shows,
192
+ with this client.
193
+
194
+ ### .NET (PostHog 2.x)
195
+
196
+ ```csharp
197
+ var posthog = new PostHogClient(new PostHogOptions { ProjectToken = "<STARKO_WORKSPACE_KEY>", HostUrl = new Uri("https://v2.starko.one/api/ingest/ph/"), CaptureUnhandledExceptions = true });
198
+ ```
199
+
200
+ In ASP.NET Core, also capture the exceptions of requests:
201
+
202
+ ```csharp
203
+ app.UsePostHogRequestContext(o => o.CaptureExceptions = true);
204
+ ```
205
+
206
+ **The trailing slash on `HostUrl` is required.** Without it the SDK posts to
207
+ the wrong path and the events are lost. If you configure the client in
208
+ `appsettings.json`, the same applies there:
209
+ `"HostUrl": "https://v2.starko.one/api/ingest/ph/"`. Do not set
210
+ `PersonalApiKey`.
211
+
212
+ ### Node (`posthog-node` 6)
213
+
214
+ ```js
215
+ import { PostHog } from 'posthog-node'
216
+
217
+ const posthog = new PostHog('<STARKO_WORKSPACE_KEY>', { host: 'https://v2.starko.one/api/ingest/ph', enableExceptionAutocapture: true })
218
+ ```
219
+
220
+ Prefer `@starko-one/sdk/node` ([node.md](./node.md)): it links users to
221
+ customers, isolates requests and adds source lines.
222
+
223
+ ### PHP and Ruby: not supported through this route yet
224
+
225
+ Their SDKs post to a path that ends in a slash, which the Starko host
226
+ currently answers with a redirect they do not follow; Ruby's SDK also drops
227
+ the path from the host. Use the [HTTP API](#a-the-http-api) for now (the PHP
228
+ example above).
229
+
230
+ ### Go
231
+
232
+ Not verified. Use the HTTP API.