@tracelumo/node 0.0.0-stage → 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/README.md CHANGED
@@ -1,3 +1,78 @@
1
- # Temporary Holding Version
1
+ # TraceLumo for Node.js
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ `@tracelumo/node` connects a Node.js app to TraceLumo. It traces Node HTTP and HTTPS, Express and built-in `fetch`, sends `console` output as logs linked to the active trace, and announces the service when it starts. Requires Node.js 22.15 or later.
4
+
5
+ ## Quick setup
6
+
7
+ Create a token on your project's **Agent tokens** page, then run this in your app's folder:
8
+
9
+ ```sh
10
+ npx @tracelumo/node init --endpoint http://127.0.0.1:911 --token tl_agent_your_project_token
11
+ ```
12
+
13
+ `init` installs the SDK, saves the endpoint and token to `.env.local` (and makes sure Git ignores it), and hooks the SDK into the app's normal start-up:
14
+
15
+ - **Next.js:** creates `instrumentation.ts`, which Next.js runs whenever the server starts.
16
+ - **Other Node.js apps:** adds the preload to the `dev` and `start` scripts.
17
+
18
+ Start your app as usual. It shows as **Connected** in TraceLumo as soon as it boots. Running `init` again is safe.
19
+
20
+ ## Manual setup
21
+
22
+ ```sh
23
+ npm install @tracelumo/node
24
+ ```
25
+
26
+ Set the endpoint and token in the app's environment or `.env.local`:
27
+
28
+ ```dotenv
29
+ TRACELUMO_OTLP_ENDPOINT=http://127.0.0.1:911
30
+ TRACELUMO_AGENT_TOKEN=tl_agent_your_project_token
31
+ ```
32
+
33
+ Then load the SDK before the app starts. In Next.js, add `instrumentation.ts`:
34
+
35
+ ```ts
36
+ export async function register() {
37
+ if (process.env.NEXT_RUNTIME === "nodejs") await import("@tracelumo/node/register");
38
+ }
39
+ ```
40
+
41
+ For other apps, preload it:
42
+
43
+ ```sh
44
+ node --require @tracelumo/node/register server.js
45
+ NODE_OPTIONS="--require @tracelumo/node/register" npm run dev
46
+ ```
47
+
48
+ ## Settings
49
+
50
+ | Variable | Default | Purpose |
51
+ | --- | --- | --- |
52
+ | `TRACELUMO_OTLP_ENDPOINT` | — | API address. Remote endpoints must use HTTPS. |
53
+ | `TRACELUMO_AGENT_TOKEN` | — | Project agent token. |
54
+ | `TRACELUMO_SERVICE_NAME` | `name` in package.json | Service name shown in TraceLumo. |
55
+ | `TRACELUMO_LOGS` | `true` | Set to `false` to stop sending console output as logs. |
56
+ | `TRACELUMO_ENABLED` | `true` | Set to `false` to turn the SDK off. |
57
+
58
+ Logs are batched (up to 100 per request, sent every second) and capped at 8 KiB per line. The SDK never traces or logs its own requests. Use a single OpenTelemetry setup per app: if you already register a tracer, replace it with this package.
59
+
60
+ ## Lifecycle hooks
61
+
62
+ Long-running apps export completed spans automatically. Short jobs and custom shutdown handlers can call `await flush()` to export buffered spans or `await shutdown()` to stop tracing and close the exporter. These functions are available from the package's CommonJS and ESM entry points. The package leaves process signal handling to the application.
63
+
64
+ ```js
65
+ import { shutdown } from "@tracelumo/node";
66
+
67
+ await shutdown();
68
+ ```
69
+
70
+ ## Local package
71
+
72
+ From the TRACELUMO repository, run
73
+
74
+ ```sh
75
+ (cd packages/node && npm pack --pack-destination /tmp)
76
+ ```
77
+
78
+ Then run `npm install /tmp/tracelumo-node-0.2.0.tgz` in the application directory.
package/package.json CHANGED
@@ -1,6 +1,51 @@
1
1
  {
2
2
  "name": "@tracelumo/node",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Connect Node.js apps to TraceLumo: automatic traces and logs",
5
+ "type": "commonjs",
6
+ "main": "./src/index.cjs",
7
+ "bin": {
8
+ "tracelumo-node": "src/init.cjs"
9
+ },
10
+ "exports": {
11
+ ".": {
12
+ "import": {
13
+ "types": "./src/index.d.mts",
14
+ "default": "./src/index.mjs"
15
+ },
16
+ "require": {
17
+ "types": "./src/index.d.cts",
18
+ "default": "./src/index.cjs"
19
+ }
20
+ },
21
+ "./register": {
22
+ "types": "./src/register.d.cts",
23
+ "default": "./src/register.cjs"
24
+ }
25
+ },
26
+ "files": [
27
+ "src/"
28
+ ],
29
+ "engines": {
30
+ "node": ">=22.15.0"
31
+ },
32
+ "scripts": {
33
+ "test": "node --test test/*.test.cjs"
34
+ },
35
+ "dependencies": {
36
+ "@opentelemetry/api": "^1.10.0",
37
+ "@opentelemetry/context-async-hooks": "^3.1.1",
38
+ "@opentelemetry/core": "^3.1.1",
39
+ "@opentelemetry/instrumentation": "^0.301.2",
40
+ "@opentelemetry/instrumentation-express": "^0.73.0",
41
+ "@opentelemetry/instrumentation-http": "^0.301.2",
42
+ "@opentelemetry/instrumentation-undici": "^0.35.1",
43
+ "@opentelemetry/otlp-exporter-base": "0.301.2",
44
+ "@opentelemetry/otlp-transformer": "0.301.2",
45
+ "@opentelemetry/resources": "^3.1.1",
46
+ "@opentelemetry/sdk-trace": "^3.1.1"
47
+ },
48
+ "devDependencies": {
49
+ "express": "^5.3.0"
50
+ }
51
+ }
package/src/config.cjs ADDED
@@ -0,0 +1,65 @@
1
+ 'use strict';
2
+
3
+ const { readFileSync } = require('node:fs');
4
+ const { resolve } = require('node:path');
5
+ const { parseEnv } = require('node:util');
6
+
7
+ function readIfPresent(path) {
8
+ try {
9
+ return readFileSync(path, 'utf8');
10
+ } catch (error) {
11
+ if (error.code === 'ENOENT') return '';
12
+ throw error;
13
+ }
14
+ }
15
+
16
+ function appName(cwd) {
17
+ const manifest = readIfPresent(resolve(cwd, 'package.json'));
18
+ if (!manifest) return 'node-app';
19
+ const name = JSON.parse(manifest)?.name;
20
+ return typeof name === 'string' && name.trim() ? name : 'node-app';
21
+ }
22
+
23
+ function traceURL(endpoint) {
24
+ let url;
25
+ try {
26
+ url = new URL(endpoint);
27
+ } catch {
28
+ throw new Error('Set TRACELUMO_OTLP_ENDPOINT to an absolute HTTP or HTTPS URL.');
29
+ }
30
+ const loopback = ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
31
+ if ((url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback)) ||
32
+ url.username || url.password || url.search || url.hash) {
33
+ throw new Error('Use an HTTPS endpoint without credentials, query parameters, or a fragment. HTTP is available on loopback.');
34
+ }
35
+ const path = url.pathname.replace(/\/+$/, '');
36
+ url.pathname = path.endsWith('/v1/traces') ? path : `${path}/v1/traces`;
37
+ return url.href;
38
+ }
39
+
40
+ function configuration(options = {}, cwd = process.cwd(), environment = process.env) {
41
+ if (options.enabled === false || (options.enabled === undefined && environment.TRACELUMO_ENABLED === 'false')) return null;
42
+
43
+ const dotEnv = {
44
+ ...parseEnv(readIfPresent(resolve(cwd, '.env'))),
45
+ ...parseEnv(readIfPresent(resolve(cwd, '.env.local'))),
46
+ };
47
+ const setting = (key) => environment[key] ?? dotEnv[key];
48
+ if (options.enabled === undefined && setting('TRACELUMO_ENABLED') === 'false') return null;
49
+
50
+ const endpoint = options.endpoint ?? setting('TRACELUMO_OTLP_ENDPOINT');
51
+ const token = (options.token ?? setting('TRACELUMO_AGENT_TOKEN') ?? '').trim();
52
+ const service = (options.serviceName ?? setting('TRACELUMO_SERVICE_NAME') ?? appName(cwd)).trim();
53
+ if (!endpoint || !token) throw new Error('Set TRACELUMO_OTLP_ENDPOINT and TRACELUMO_AGENT_TOKEN.');
54
+ if (!/^tl_agent_[A-Za-z0-9_-]{23,119}$/.test(token)) {
55
+ throw new Error('TRACELUMO_AGENT_TOKEN must be an active project agent token.');
56
+ }
57
+ if (!service || Buffer.byteLength(service) > 128 || /[\0\r\n]/.test(service)) {
58
+ throw new Error('TRACELUMO_SERVICE_NAME must contain 1 to 128 bytes on a single line.');
59
+ }
60
+ const url = traceURL(endpoint);
61
+ const logs = options.logs ?? setting('TRACELUMO_LOGS') !== 'false';
62
+ return { url, logsUrl: url.replace(/\/v1\/traces$/, '/v1/ingest/logs'), token, service, logs };
63
+ }
64
+
65
+ module.exports = { configuration, traceURL };
@@ -0,0 +1,23 @@
1
+ 'use strict';
2
+
3
+ const { OTLPExporterBase } = require('@opentelemetry/otlp-exporter-base');
4
+ const { createOtlpHttpExportDelegate, httpAgentFactoryFromOptions } = require('@opentelemetry/otlp-exporter-base/node-http');
5
+ const { ProtobufTraceSerializer, TraceExporterMetricsHelper } = require('@opentelemetry/otlp-transformer');
6
+
7
+ function createExporter({ url, token }) {
8
+ // Use an explicit transport configuration so unrelated OTEL_* headers and credentials stay isolated.
9
+ const transport = createOtlpHttpExportDelegate({
10
+ url,
11
+ timeoutMillis: 5000,
12
+ concurrencyLimit: 2,
13
+ compression: 'gzip',
14
+ agentFactory: httpAgentFactoryFromOptions({ keepAlive: true }),
15
+ headers: async () => ({
16
+ 'Content-Type': 'application/x-protobuf',
17
+ Authorization: `Bearer ${token}`,
18
+ }),
19
+ }, ProtobufTraceSerializer, 'otlp_http_span_exporter', TraceExporterMetricsHelper);
20
+ return new OTLPExporterBase(transport);
21
+ }
22
+
23
+ module.exports = { createExporter };
package/src/index.cjs ADDED
@@ -0,0 +1,96 @@
1
+ 'use strict';
2
+
3
+ const { configuration } = require('./config.cjs');
4
+ const { syncBuiltinESMExports } = require('node:module');
5
+
6
+ const instance = Symbol.for('@tracelumo/node.sdk');
7
+
8
+ function start(options) {
9
+ if (globalThis[instance]) return;
10
+ const config = configuration(options);
11
+ if (!config) return;
12
+
13
+ const { context, isSpanContextValid, propagation, trace } = require('@opentelemetry/api');
14
+ const { AsyncLocalStorageContextManager } = require('@opentelemetry/context-async-hooks');
15
+ const { suppressTracing, W3CTraceContextPropagator } = require('@opentelemetry/core');
16
+ const { registerInstrumentations } = require('@opentelemetry/instrumentation');
17
+ const { ExpressInstrumentation } = require('@opentelemetry/instrumentation-express');
18
+ const { HttpInstrumentation } = require('@opentelemetry/instrumentation-http');
19
+ const { UndiciInstrumentation } = require('@opentelemetry/instrumentation-undici');
20
+ const { resourceFromAttributes } = require('@opentelemetry/resources');
21
+ const { TracerProvider, BatchSpanProcessor } = require('@opentelemetry/sdk-trace');
22
+
23
+ const { createExporter } = require('./exporter.cjs');
24
+
25
+ const provider = new TracerProvider({
26
+ resource: resourceFromAttributes({ 'service.name': config.service }),
27
+ spanLimits: {
28
+ attributeCountLimit: 32,
29
+ attributeValueLengthLimit: 128,
30
+ eventCountLimit: 0,
31
+ linkCountLimit: 0,
32
+ },
33
+ spanProcessors: [new BatchSpanProcessor({
34
+ exporter: createExporter(config),
35
+ maxQueueSize: 1024,
36
+ maxExportBatchSize: 64,
37
+ scheduledDelayMillis: 1000,
38
+ exportTimeoutMillis: 6000,
39
+ })],
40
+ });
41
+
42
+ if (!trace.setGlobalTracerProvider(provider)) {
43
+ void provider.shutdown().catch(() => {});
44
+ throw new Error('An OpenTelemetry tracer is already registered. Use a single tracing preload.');
45
+ }
46
+ const manager = new AsyncLocalStorageContextManager().enable();
47
+ if (!context.setGlobalContextManager(manager)) manager.disable();
48
+ propagation.setGlobalPropagator(new W3CTraceContextPropagator());
49
+
50
+ const stopInstrumentation = registerInstrumentations({
51
+ tracerProvider: provider,
52
+ instrumentations: [
53
+ new HttpInstrumentation(),
54
+ new ExpressInstrumentation(),
55
+ new UndiciInstrumentation(),
56
+ ],
57
+ });
58
+ // Apply the HTTP hooks before an ESM application reads named built-in exports.
59
+ require('node:http');
60
+ require('node:https');
61
+ syncBuiltinESMExports();
62
+
63
+ let logs = null;
64
+ let restoreConsole = () => {};
65
+ if (config.logs) {
66
+ const { captureConsole, createLogShipper } = require('./logs.cjs');
67
+ logs = createLogShipper(config, { suppress: (fn) => context.with(suppressTracing(context.active()), fn) });
68
+ restoreConsole = captureConsole(logs, () => {
69
+ const span = trace.getSpanContext(context.active());
70
+ return span && isSpanContextValid(span) ? span.traceId : undefined;
71
+ });
72
+ // Announce the service as soon as it starts, so the project shows as connected before any request.
73
+ logs.add('info', `TraceLumo connected: ${config.service} started (Node.js ${process.version}, pid ${process.pid})`);
74
+ setImmediate(logs.flush);
75
+ }
76
+ globalThis[instance] = { provider, stopInstrumentation, logs, restoreConsole };
77
+ }
78
+
79
+ async function flush() {
80
+ const sdk = globalThis[instance];
81
+ if (sdk) await Promise.all([sdk.stopping ?? sdk.provider.forceFlush(), sdk.logs?.flush()]);
82
+ }
83
+
84
+ async function shutdown() {
85
+ const sdk = globalThis[instance];
86
+ if (!sdk) return;
87
+ if (!sdk.stopping) {
88
+ sdk.stopInstrumentation();
89
+ sdk.restoreConsole();
90
+ syncBuiltinESMExports();
91
+ sdk.stopping = Promise.all([sdk.provider.shutdown(), sdk.logs?.close()]).then(() => {});
92
+ }
93
+ await sdk.stopping;
94
+ }
95
+
96
+ module.exports = { start, flush, shutdown };
@@ -0,0 +1,12 @@
1
+ export interface TracingOptions {
2
+ endpoint?: string;
3
+ token?: string;
4
+ serviceName?: string;
5
+ enabled?: boolean;
6
+ /** Send console output as logs. Defaults to true; TRACELUMO_LOGS=false turns it off. */
7
+ logs?: boolean;
8
+ }
9
+
10
+ export function start(options?: TracingOptions): void;
11
+ export function flush(): Promise<void>;
12
+ export function shutdown(): Promise<void>;
@@ -0,0 +1 @@
1
+ export { start, flush, shutdown, type TracingOptions } from './index.cjs';
package/src/index.mjs ADDED
@@ -0,0 +1 @@
1
+ export { start, flush, shutdown } from './index.cjs';
package/src/init.cjs ADDED
@@ -0,0 +1,273 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ // `npx @tracelumo/node init` connects an app to TraceLumo in one step: it installs the SDK, wires
5
+ // it into the app's normal start-up, and saves the endpoint and token. Running it again is safe.
6
+
7
+ const { execFileSync } = require('node:child_process');
8
+ const { chmodSync, existsSync, readFileSync, writeFileSync } = require('node:fs');
9
+ const { join } = require('node:path');
10
+ const { parseArgs, parseEnv } = require('node:util');
11
+ const { traceURL } = require('./config.cjs');
12
+
13
+ const PACKAGE = '@tracelumo/node';
14
+ const PRELOAD = `${PACKAGE}/register`;
15
+ const TOKEN = /^tl_agent_[A-Za-z0-9_-]{23,119}$/;
16
+ const { version } = require('../package.json');
17
+
18
+ const usage = `Connect this app to TraceLumo.
19
+
20
+ Usage: npx @tracelumo/node init --endpoint <url> --token <tl_agent_…> [options]
21
+
22
+ Options:
23
+ --endpoint <url> TraceLumo API address, e.g. http://127.0.0.1:911
24
+ --token <token> Project agent token from the Agent tokens page
25
+ --service <name> Service name shown in TraceLumo (default: package.json name)
26
+ --package <spec> Install the SDK from this spec instead of npm (e.g. a local .tgz)
27
+ --skip-install Don't install the SDK
28
+ --dir <path> App directory (default: current directory)
29
+ -h, --help Show this help`;
30
+
31
+ function readText(path) {
32
+ try {
33
+ return readFileSync(path, 'utf8');
34
+ } catch (error) {
35
+ if (error.code === 'ENOENT') return null;
36
+ throw error;
37
+ }
38
+ }
39
+
40
+ function readJSON(path) {
41
+ const text = readText(path);
42
+ if (text === null) return null;
43
+ const indent = /^(\s+)"/m.exec(text)?.[1] ?? ' ';
44
+ return { data: JSON.parse(text), indent };
45
+ }
46
+
47
+ function writeJSON(path, { data, indent }) {
48
+ writeFileSync(path, `${JSON.stringify(data, null, indent)}\n`);
49
+ }
50
+
51
+ function packageManager(dir) {
52
+ if (existsSync(join(dir, 'pnpm-lock.yaml'))) return ['pnpm', ['add']];
53
+ if (existsSync(join(dir, 'yarn.lock'))) return ['yarn', ['add']];
54
+ if (existsSync(join(dir, 'bun.lockb')) || existsSync(join(dir, 'bun.lock'))) return ['bun', ['add']];
55
+ return ['npm', ['install']];
56
+ }
57
+
58
+ function installedVersion(dir) {
59
+ const manifest = readJSON(join(dir, 'node_modules', PACKAGE, 'package.json'));
60
+ return manifest?.data.version ?? null;
61
+ }
62
+
63
+ function newer(a, b) {
64
+ const pa = a.split('.').map(Number);
65
+ const pb = b.split('.').map(Number);
66
+ for (let i = 0; i < 3; i += 1) if ((pa[i] || 0) !== (pb[i] || 0)) return (pa[i] || 0) > (pb[i] || 0);
67
+ return false;
68
+ }
69
+
70
+ /** Sets KEY=value lines in a dotenv file, replacing existing assignments and keeping everything else. */
71
+ function upsertEnv(path, entries) {
72
+ const original = readText(path);
73
+ const lines = original === null ? [] : original.replace(/\n$/, '').split('\n');
74
+ const missing = new Map(Object.entries(entries));
75
+ const updated = lines.map((line) => {
76
+ const key = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(line)?.[1];
77
+ if (key && missing.has(key)) {
78
+ const value = missing.get(key);
79
+ missing.delete(key);
80
+ return `${key}=${value}`;
81
+ }
82
+ return line;
83
+ });
84
+ if (missing.size) {
85
+ if (updated.length && updated.at(-1) !== '') updated.push('');
86
+ updated.push('# TraceLumo');
87
+ for (const [key, value] of missing) updated.push(`${key}=${value}`);
88
+ }
89
+ const next = `${updated.join('\n')}\n`;
90
+ if (next === original) return false;
91
+ writeFileSync(path, next, { mode: 0o600 });
92
+ chmodSync(path, 0o600); // The file holds a token, so keep it private even if it already existed.
93
+ return true;
94
+ }
95
+
96
+ function gitIgnores(dir, file) {
97
+ try {
98
+ execFileSync('git', ['rev-parse', '--is-inside-work-tree'], { cwd: dir, stdio: 'ignore' });
99
+ } catch {
100
+ return null;
101
+ }
102
+ try {
103
+ execFileSync('git', ['check-ignore', '-q', file], { cwd: dir, stdio: 'ignore' });
104
+ return true;
105
+ } catch {
106
+ return false;
107
+ }
108
+ }
109
+
110
+ const INSTRUMENTATION = `// Sends this app's traces and logs to TraceLumo. Added by \`npx @tracelumo/node init\`.
111
+ export async function register() {
112
+ if (process.env.NEXT_RUNTIME === "nodejs") {
113
+ await import("${PRELOAD}");
114
+ }
115
+ }
116
+ `;
117
+
118
+ function setupNext(dir, report) {
119
+ const base = existsSync(join(dir, 'src', 'app')) || existsSync(join(dir, 'src', 'pages')) ? join(dir, 'src') : dir;
120
+ const label = base === dir ? '' : 'src/';
121
+ const existing = ['ts', 'js', 'mjs'].map((ext) => join(base, `instrumentation.${ext}`)).find(existsSync);
122
+ if (existing) {
123
+ const name = `${label}${existing.split(/[\\/]/).at(-1)}`;
124
+ if (readText(existing).includes(PACKAGE)) {
125
+ report.ok(`${name} already loads TraceLumo`);
126
+ } else {
127
+ report.todo(`${name} already exists. Add this inside its register() function:\n` +
128
+ ` if (process.env.NEXT_RUNTIME === "nodejs") await import("${PRELOAD}");`);
129
+ }
130
+ return;
131
+ }
132
+ const ext = existsSync(join(dir, 'tsconfig.json')) ? 'ts' : 'js';
133
+ writeFileSync(join(base, `instrumentation.${ext}`), INSTRUMENTATION);
134
+ report.ok(`Created ${label}instrumentation.${ext} (Next.js runs it whenever the server starts)`);
135
+ }
136
+
137
+ function setupNode(dir, report) {
138
+ const path = join(dir, 'package.json');
139
+ const manifest = readJSON(path);
140
+ const scripts = manifest.data.scripts ?? {};
141
+ const changed = [];
142
+ for (const name of ['dev', 'start']) {
143
+ const script = scripts[name];
144
+ if (typeof script !== 'string' || script.includes(PRELOAD)) continue;
145
+ scripts[name] = /^node\s/.test(script)
146
+ ? script.replace(/^node\s+/, `node --require ${PRELOAD} `)
147
+ : `NODE_OPTIONS='--require ${PRELOAD}' ${script}`;
148
+ changed.push(name);
149
+ }
150
+ if (changed.length) {
151
+ manifest.data.scripts = scripts;
152
+ writeJSON(path, manifest);
153
+ report.ok(`Added TraceLumo to the ${changed.map((name) => `"${name}"`).join(' and ')} script${changed.length > 1 ? 's' : ''}`);
154
+ } else if (Object.values(scripts).some((script) => typeof script === 'string' && script.includes(PRELOAD))) {
155
+ report.ok('Start scripts already load TraceLumo');
156
+ } else {
157
+ report.todo(`No "dev" or "start" script found. Start your app with: node --require ${PRELOAD} <entry file>`);
158
+ }
159
+ }
160
+
161
+ async function verify(endpoint, token) {
162
+ try {
163
+ const response = await fetch(traceURL(endpoint), {
164
+ method: 'POST',
165
+ headers: { 'Content-Type': 'application/x-protobuf', Authorization: `Bearer ${token}` },
166
+ body: new Uint8Array(0),
167
+ signal: AbortSignal.timeout(5000),
168
+ });
169
+ return response.ok ? 'ok' : response.status === 401 ? 'rejected' : `HTTP ${response.status}`;
170
+ } catch {
171
+ return 'unreachable';
172
+ }
173
+ }
174
+
175
+ async function main(argv = process.argv.slice(2)) {
176
+ const { values, positionals } = parseArgs({
177
+ args: argv,
178
+ allowPositionals: true,
179
+ options: {
180
+ endpoint: { type: 'string' },
181
+ token: { type: 'string' },
182
+ service: { type: 'string' },
183
+ package: { type: 'string' },
184
+ 'skip-install': { type: 'boolean' },
185
+ dir: { type: 'string' },
186
+ help: { type: 'boolean', short: 'h' },
187
+ },
188
+ });
189
+ if (values.help || (positionals.length && positionals[0] !== 'init')) {
190
+ console.log(usage);
191
+ return values.help ? 0 : 1;
192
+ }
193
+
194
+ const dir = values.dir ?? process.cwd();
195
+ const report = {
196
+ lines: [],
197
+ todos: [],
198
+ ok(text) { this.lines.push(` ✓ ${text}`); },
199
+ todo(text) { this.todos.push(` ! ${text}`); },
200
+ };
201
+ const fail = (message) => { console.error(`TraceLumo setup stopped: ${message}`); return 1; };
202
+
203
+ if (!readJSON(join(dir, 'package.json'))) return fail(`no package.json in ${dir}. Run this in your app's folder.`);
204
+
205
+ const envPath = join(dir, '.env.local');
206
+ const current = parseEnv(readText(envPath) ?? '');
207
+ const endpoint = (values.endpoint ?? current.TRACELUMO_OTLP_ENDPOINT ?? '').trim().replace(/\/+$/, '');
208
+ const token = (values.token ?? current.TRACELUMO_AGENT_TOKEN ?? '').trim();
209
+ if (!endpoint) return fail('pass --endpoint with your TraceLumo API address.');
210
+ try {
211
+ traceURL(endpoint);
212
+ } catch (error) {
213
+ return fail(error.message);
214
+ }
215
+ if (!TOKEN.test(token)) return fail('pass --token with an agent token from the Agent tokens page (it starts with tl_agent_).');
216
+
217
+ console.log('Connecting this app to TraceLumo…\n');
218
+
219
+ // 1. Install the SDK unless a current version is already there.
220
+ const have = installedVersion(dir);
221
+ if (values['skip-install']) {
222
+ report.ok('Skipped installing the SDK');
223
+ } else if (have && !values.package && !newer(version, have)) {
224
+ report.ok(`${PACKAGE} ${have} is already installed`);
225
+ } else {
226
+ const [command, args] = packageManager(dir);
227
+ const spec = values.package ?? `${PACKAGE}@^${version}`;
228
+ console.log(` Installing ${spec} with ${command}…`);
229
+ try {
230
+ execFileSync(command, [...args, spec], { cwd: dir, stdio: ['ignore', 'ignore', 'inherit'] });
231
+ } catch {
232
+ return fail(`${command} could not install ${spec}.`);
233
+ }
234
+ report.ok(`Installed ${PACKAGE} ${installedVersion(dir) ?? ''}`.trim());
235
+ }
236
+
237
+ // 2. Save the endpoint and token where the SDK reads them.
238
+ const settings = { TRACELUMO_OTLP_ENDPOINT: endpoint, TRACELUMO_AGENT_TOKEN: token };
239
+ if (values.service) settings.TRACELUMO_SERVICE_NAME = values.service;
240
+ report.ok(upsertEnv(envPath, settings) ? 'Saved the endpoint and token to .env.local' : '.env.local already has these settings');
241
+ const ignored = gitIgnores(dir, '.env.local');
242
+ if (ignored === false) {
243
+ const gitignore = join(dir, '.gitignore');
244
+ writeFileSync(gitignore, `${(readText(gitignore) ?? '').replace(/\n?$/, '\n')}.env.local\n`);
245
+ report.ok('Added .env.local to .gitignore so the token is never committed');
246
+ }
247
+
248
+ // 3. Load the SDK whenever the app starts.
249
+ const manifest = readJSON(join(dir, 'package.json')).data;
250
+ const deps = { ...manifest.dependencies, ...manifest.devDependencies };
251
+ if (deps.next) setupNext(dir, report);
252
+ else setupNode(dir, report);
253
+
254
+ // 4. Check the token against the API.
255
+ const check = await verify(endpoint, token);
256
+ if (check === 'ok') report.ok(`Token accepted by ${endpoint}`);
257
+ else if (check === 'rejected') report.todo('The API rejected this token. Create a new one on the Agent tokens page and run init again.');
258
+ else if (check === 'unreachable') report.todo(`Couldn't reach ${endpoint}. Make sure TraceLumo is running; the app will connect once it is.`);
259
+ else report.todo(`The API answered ${check} when checking the token.`);
260
+
261
+ console.log([...report.lines, ...report.todos].join('\n'));
262
+ console.log(`\nDone. Start your app as usual${deps.next ? ' (npm run dev)' : ''}. It shows as Connected in TraceLumo as soon as it starts.`);
263
+ return 0;
264
+ }
265
+
266
+ if (require.main === module) {
267
+ main().then((code) => { process.exitCode = code; }, (error) => {
268
+ console.error(`TraceLumo setup failed: ${error.message}`);
269
+ process.exitCode = 1;
270
+ });
271
+ }
272
+
273
+ module.exports = { main, upsertEnv };
package/src/logs.cjs ADDED
@@ -0,0 +1,130 @@
1
+ 'use strict';
2
+
3
+ const { randomUUID } = require('node:crypto');
4
+ const http = require('node:http');
5
+ const https = require('node:https');
6
+ const { format } = require('node:util');
7
+ const { gzipSync } = require('node:zlib');
8
+
9
+ // Limits match the TraceLumo log ingest API.
10
+ const MAX_BATCH = 100;
11
+ const MAX_BODY = 8192;
12
+ const MAX_QUEUE = 2000;
13
+ const INTERVAL = 1000;
14
+ const ANSI = /\u001b\[[0-?]*[ -/]*[@-~]/g;
15
+ const METHODS = { debug: 'debug', trace: 'debug', log: 'info', info: 'info', warn: 'warn', error: 'error' };
16
+
17
+ function clip(text) {
18
+ if (Buffer.byteLength(text) <= MAX_BODY) return text;
19
+ return `${Buffer.from(text).subarray(0, MAX_BODY - 3).toString('utf8').replace(/�+$/, '')}…`;
20
+ }
21
+
22
+ /**
23
+ * Batches log events and sends them to the ingest API. Requests run with tracing suppressed so
24
+ * the SDK never traces or logs its own traffic. Transient failures are retried on the next tick;
25
+ * a rejected token is reported once and its events are dropped.
26
+ */
27
+ function createLogShipper({ logsUrl, token, service }, { suppress }) {
28
+ const target = new URL(logsUrl);
29
+ const transport = target.protocol === 'https:' ? https : http;
30
+ let queue = [];
31
+ let inflight = null;
32
+ let warned = false;
33
+
34
+ function post(batch) {
35
+ const data = gzipSync(JSON.stringify(batch));
36
+ return new Promise((resolve) => {
37
+ suppress(() => {
38
+ const request = transport.request(target, {
39
+ method: 'POST',
40
+ timeout: 5000,
41
+ headers: {
42
+ 'Content-Type': 'application/json',
43
+ 'Content-Encoding': 'gzip',
44
+ 'Content-Length': data.length,
45
+ Authorization: `Bearer ${token}`,
46
+ },
47
+ }, (response) => {
48
+ response.on('error', () => resolve(0));
49
+ response.on('end', () => resolve(response.statusCode ?? 0));
50
+ response.resume();
51
+ });
52
+ request.on('timeout', () => request.destroy());
53
+ request.on('error', () => resolve(0));
54
+ request.end(data);
55
+ });
56
+ });
57
+ }
58
+
59
+ async function drain() {
60
+ while (queue.length) {
61
+ const batch = queue.splice(0, MAX_BATCH);
62
+ const status = await post(batch);
63
+ if (status >= 200 && status < 300) continue;
64
+ if (status === 0 || status === 429 || status >= 500) {
65
+ queue = batch.concat(queue).slice(-MAX_QUEUE);
66
+ return;
67
+ }
68
+ if (!warned) {
69
+ warned = true;
70
+ process.emitWarning(`TraceLumo rejected a log batch (HTTP ${status}). Check TRACELUMO_AGENT_TOKEN.`, { code: 'TRACELUMO_LOGS' });
71
+ }
72
+ }
73
+ }
74
+
75
+ function flush() {
76
+ inflight ??= drain().finally(() => { inflight = null; });
77
+ return inflight;
78
+ }
79
+
80
+ function add(severity, body, traceId) {
81
+ if (queue.length >= MAX_QUEUE) queue.shift();
82
+ const event = { event_id: randomUUID(), timestamp: new Date().toISOString(), service, severity, body: clip(body) };
83
+ if (traceId) event.trace_id = traceId;
84
+ queue.push(event);
85
+ if (queue.length >= MAX_BATCH) setImmediate(flush);
86
+ }
87
+
88
+ const timer = setInterval(flush, INTERVAL);
89
+ timer.unref();
90
+ process.once('beforeExit', () => { void flush(); });
91
+
92
+ return {
93
+ add,
94
+ flush,
95
+ async close() {
96
+ clearInterval(timer);
97
+ await flush();
98
+ },
99
+ };
100
+ }
101
+
102
+ /** Mirrors console output to the shipper, tagged with the active trace. Returns a restore function. */
103
+ function captureConsole(shipper, traceId) {
104
+ const originals = {};
105
+ let busy = false;
106
+ for (const [method, severity] of Object.entries(METHODS)) {
107
+ const original = console[method];
108
+ if (typeof original !== 'function') continue;
109
+ originals[method] = original;
110
+ console[method] = function tracelumoConsole(...args) {
111
+ original.apply(this, args);
112
+ if (busy) return;
113
+ busy = true;
114
+ try {
115
+ let body = format(...args).replace(ANSI, '').trim();
116
+ if (method === 'trace') body = `Trace: ${body}`;
117
+ if (body) shipper.add(severity, body, traceId());
118
+ } catch {
119
+ // Logging must never break the application.
120
+ } finally {
121
+ busy = false;
122
+ }
123
+ };
124
+ }
125
+ return () => {
126
+ for (const [method, original] of Object.entries(originals)) console[method] = original;
127
+ };
128
+ }
129
+
130
+ module.exports = { createLogShipper, captureConsole, clip };
@@ -0,0 +1,7 @@
1
+ 'use strict';
2
+
3
+ try {
4
+ require('./index.cjs').start();
5
+ } catch (error) {
6
+ process.emitWarning(error.message, { code: 'TRACELUMO_SETUP' });
7
+ }
@@ -0,0 +1 @@
1
+ export {};