diff --git a/typescript/package.json b/typescript/package.json index bfbf791..9e4c4c4 100644 --- a/typescript/package.json +++ b/typescript/package.json @@ -1,6 +1,6 @@ { "name": "@flexmodel/sdk", - "version": "0.0.9", + "version": "0.0.10", "description": "Flexmodel TypeScript SDK — Fluent query builder for data CRUD with API Key auth", "type": "module", "main": "./dist/index.cjs", diff --git a/typescript/src/client.ts b/typescript/src/client.ts index 0b8c71a..c94b01b 100644 --- a/typescript/src/client.ts +++ b/typescript/src/client.ts @@ -161,11 +161,16 @@ export class FlexmodelClient< return this as unknown as FlexmodelClient } - /** 设置当前请求的认证令牌(优先级高于构造函数中的 apiKey)。 */ + /** 设置当前请求的认证令牌(优先级高于构造函数中的 apiKey)。 */ setAuthToken(token?: string): void { this.http.setAuthToken(token) } + /** 设置当前链路追踪 ID,设置后 outgoing 请求自动注入 W3C traceparent 头。 */ + setTraceId(traceId?: string): void { + this.http.setTraceId(traceId) + } + /** 更新 API 基础地址(运行时可变)。 */ setBaseURL(baseURL: string): void { this.http.setBaseURL(baseURL) @@ -302,10 +307,15 @@ export class FlexmodelAdminClient< return this as unknown as FlexmodelAdminClient } - /** 设置认证令牌。 */ - setAuthToken(token?: string): void { - this.http.setAuthToken(token) - } + /** 设置认证令牌。 */ + setAuthToken(token?: string): void { + this.http.setAuthToken(token) + } + + /** 设置当前链路追踪 ID,设置后 outgoing 请求自动注入 W3C traceparent 头。 */ + setTraceId(traceId?: string): void { + this.http.setTraceId(traceId) + } /** 更新 API 基础地址。 */ setBaseURL(baseURL: string): void { diff --git a/typescript/src/http.ts b/typescript/src/http.ts index 67862c5..3265902 100644 --- a/typescript/src/http.ts +++ b/typescript/src/http.ts @@ -29,6 +29,19 @@ export class HttpTransport { this.activeToken = token } + /** 当前 traceId,用于 W3C traceparent 头传播(函数调用 → SDK → Java 后端链路关联) */ + private activeTraceId?: string + + /** + * 设置当前链路追踪 ID。 + * 设置后所有 outgoing 请求会自动注入 W3C traceparent 头, + * 使 Java 后端能关联到同一 traceId。 + * 传入 undefined 清除。 + */ + setTraceId(traceId?: string): void { + this.activeTraceId = traceId + } + /** * 更新 API 基础地址(运行时可变)。 * 自动去除尾部斜杠。 @@ -71,6 +84,14 @@ export class HttpTransport { } else if (this.apiKey) { headers['Authorization'] = `Bearer ${this.apiKey}` } + if (this.activeTraceId) { + // W3C traceparent: 00-{traceId}-{spanId}-{flags} + // spanId 用 16 hex 随机值(SDK 侧无 OTel SDK,生成伪 spanId 满足格式要求) + const spanId = Array.from({length: 8}, () => + Math.floor(Math.random() * 256).toString(16).padStart(2, '0') + ).join('') + headers['traceparent'] = `00-${this.activeTraceId}-${spanId}-01` + } return headers }