Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
//registry.npmjs.org/:_authToken=${NPM_TOKEN}
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,23 @@ duck.warn('Slow query', { ms: 1200 });

Before process exit, await `duck.flush()` so queued HTTP work finishes (for example at the end of an `async main()`).

### Reserved `_duck` on log payloads

The second argument to `log` / `debug` / `warn` / `error` / `fatal` may be a plain object with a reserved **`_duck`** field for technical metadata. **`_duck` is not sent inside `context`** on the wire.

- **`_duck.dTags`** — sets top-level `dTags` on the ingest event (same as in a raw JSON body).
- **`_duck.scope`** — one-shot `Partial<IngestSharedMetadata>` merged into **this** log only (after global `setScope`, before fixed fields). Use e.g. `platform: "ios"` to override the default `"node"`. Optional **`_duck.scope.context`** is used as the event `context` only when there are no other keys besides `_duck`.

Any other keys on the object become **`context`**, which matches typical ingest JSON (`dTags` at the root, domain fields under `context`).

```typescript
duck.warn("DUCKBUG_DTAGS_SMOKE_TEST", {
source: "initDuckBugDeviceContext",
platform: "ios",
_duck: { dTags: ["smoke-test", "dtags"] },
});
```

## Full usage example

End-to-end pattern for a Node/Bun service: DSN from env, scope (release, user, fingerprint), privacy pipeline, `beforeSend`, batched transport with retries, transport errors, console forwarding, global error handlers, structured logs, manual errors, and clean shutdown.
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@duckbug/js",
"version": "0.1.3",
"version": "1.0.0",
"type": "module",
"main": "./dist/cjs/index.cjs",
"module": "./dist/esm/index.js",
Expand Down
31 changes: 21 additions & 10 deletions src/SDK/DuckSDK.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import type {
DuckBugErrorEvent,
DuckBugLogEvent,
IngestJsonValue,
IngestSharedMetadata,
} from "../contract";
import type {
Expand All @@ -12,6 +11,7 @@ import { processError } from "../DuckBug/DuckBugHelper";
import { finalizeIngestEvent } from "../DuckBug/finalizeIngestEvent";
import type { StrippableIngestSection } from "../DuckBug/stripIngestSections";
import { SDK_IDENTITY } from "../sdkIdentity";
import { type DuckLogPayload, parseDuckLogPayload } from "./duckLogPayload";
import type { LogLevel } from "./LogLevel";
import { logLevel } from "./LogLevel";
import { LogProvider } from "./LogProvider";
Expand Down Expand Up @@ -72,23 +72,23 @@ export class DuckSDK {
).then(() => undefined);
}

log(tag: string, payload?: object) {
log(tag: string, payload?: DuckLogPayload) {
this.emitLog(logLevel.DEBUG, tag, payload);
}

error(tag: string, payload?: object) {
error(tag: string, payload?: DuckLogPayload) {
this.emitLog(logLevel.ERROR, tag, payload);
}

debug(tag: string, payload?: object) {
debug(tag: string, payload?: DuckLogPayload) {
this.emitLog(logLevel.DEBUG, tag, payload);
}

warn(tag: string, payload?: object) {
warn(tag: string, payload?: DuckLogPayload) {
this.emitLog(logLevel.WARN, tag, payload);
}

fatal(tag: string, payload?: object) {
fatal(tag: string, payload?: DuckLogPayload) {
this.emitLog(logLevel.FATAL, tag, payload);
}

Expand Down Expand Up @@ -155,15 +155,26 @@ export class DuckSDK {
return out as DuckBugErrorEvent;
}

private emitLog(level: LogLevel, message: string, payload?: object) {
private emitLog(level: LogLevel, message: string, payload?: DuckLogPayload) {
const { scopePatch, context, dTags } = parseDuckLogPayload(payload);
const platform =
scopePatch.platform !== undefined &&
typeof scopePatch.platform === "string"
? scopePatch.platform
: "node";
const scopeForSpread = { ...scopePatch } as Record<string, unknown>;
delete scopeForSpread.platform;

const event: DuckBugLogEvent = this.mergeScope({
...scopeForSpread,
time: Date.now(),
level,
message,
platform: "node",
platform,
sdk: { ...SDK_IDENTITY },
...(payload !== undefined ? { context: payload as IngestJsonValue } : {}),
});
...(dTags !== undefined ? { dTags } : {}),
...(context !== undefined ? { context } : {}),
} as DuckBugLogEvent);
const finalized = finalizeIngestEvent(event, {
extraSensitiveKeys: this.extraSensitiveKeys,
stripSections: this.stripSections,
Expand Down
101 changes: 101 additions & 0 deletions src/SDK/duckLogPayload.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
import type { IngestJsonValue, IngestSharedMetadata } from "../contract";

/**
* Reserved key on the second argument to `Duck` / `DuckSDK` log methods.
* Not sent inside `context` on the wire.
*/
export type DuckReservedMeta = {
dTags?: string[];
/** One-shot metadata merged into this log only (after global `setScope`, before fixed fields). */
scope?: Partial<IngestSharedMetadata>;
};

export type DuckLogPayload = Record<string, unknown> & {
_duck?: DuckReservedMeta;
};

/** Log event fields applied by emitLog; strip if passed via `_duck.scope`. */
const EMIT_OWNED = ["time", "level", "message", "sdk"] as const;

/**
* Splits the optional second argument into scope-like fields, `dTags`, and `context`.
* - Plain object: strips `_duck`, remaining keys become `context` if non-empty.
* - Non-plain-object payload: entire value becomes `context` (legacy).
*/
export function parseDuckLogPayload(payload: object | undefined): {
scopePatch: Partial<IngestSharedMetadata>;
context: IngestJsonValue | undefined;
dTags: string[] | undefined;
} {
if (payload === undefined) {
return { scopePatch: {}, context: undefined, dTags: undefined };
}
// `typeof null === "object"` — treat null like other non-object contexts.
if (
payload === null ||
Array.isArray(payload) ||
typeof payload !== "object"
) {
return {
scopePatch: {},
context: payload as IngestJsonValue,
dTags: undefined,
};
}

const rec = { ...(payload as Record<string, unknown>) };
const rawDuck = rec._duck;
delete rec._duck;

let reserved: DuckReservedMeta | undefined;
if (
rawDuck !== null &&
typeof rawDuck === "object" &&
!Array.isArray(rawDuck)
) {
reserved = rawDuck as DuckReservedMeta;
}

const hasRest = Object.keys(rec).length > 0;
const restContext = hasRest ? (rec as IngestJsonValue) : undefined;

let scopeContext: IngestJsonValue | undefined;
let scopePatch: Partial<IngestSharedMetadata> = {};
const inner = reserved?.scope;
if (
inner !== undefined &&
typeof inner === "object" &&
!Array.isArray(inner)
) {
const s = inner as IngestSharedMetadata & { context?: IngestJsonValue };
scopeContext = s.context;
const { context: _c, ...restScope } = s;
scopePatch = { ...restScope };
}

for (const k of EMIT_OWNED) {
delete (scopePatch as Record<string, unknown>)[k];
}

let context: IngestJsonValue | undefined;
if (hasRest) {
context = restContext;
} else if (scopeContext !== undefined) {
context = scopeContext;
}

let dTags: string[] | undefined;
if (reserved?.dTags !== undefined) {
dTags = reserved.dTags;
} else if (scopePatch.dTags !== undefined) {
dTags = scopePatch.dTags;
}

const { dTags: _scopeDtags, ...scopePatchNoDtags } = scopePatch;

return {
scopePatch: scopePatchNoDtags,
context,
dTags,
};
}
4 changes: 4 additions & 0 deletions src/SDK/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
export type { Provider, SendEventMeta } from "../SDK/Provider";
export type { DuckSDKOptions } from "./DuckSDK";
export { Duck, DuckSDK } from "./DuckSDK";
export type {
DuckLogPayload,
DuckReservedMeta,
} from "./duckLogPayload";
export type { LogLevel } from "./LogLevel";
export { logLevel } from "./LogLevel";
export { LogProvider } from "./LogProvider";
Expand Down
123 changes: 122 additions & 1 deletion tests/SDK/DuckSDK.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { beforeEach, describe, expect, it, mock } from "bun:test";
import { beforeEach, describe, expect, it, mock, spyOn } from "bun:test";
import type { LogProviderConfig, Provider } from "../../src/SDK";
import { Duck, DuckSDK } from "../../src/SDK/DuckSDK";
import { logLevel } from "../../src/SDK/LogLevel";
Expand Down Expand Up @@ -250,6 +250,127 @@ describe("DuckSDK", () => {
});
});

describe("_duck log payload", () => {
beforeEach(() => {
sdk = new DuckSDK(providers);
});

it("maps dTags to top level and domain fields to context (ingest curl shape)", () => {
const spy = spyOn(Date, "now").mockReturnValue(1_704_067_200_000);

sdk.warn("DUCKBUG_DTAGS_SMOKE_TEST", {
source: "initDuckBugDeviceContext",
platform: "ios",
_duck: { dTags: ["smoke-test", "dtags"] },
});

expect(mockProvider1.sendLog).toHaveBeenCalledWith(
expect.objectContaining({
time: 1_704_067_200_000,
level: logLevel.WARN,
message: "DUCKBUG_DTAGS_SMOKE_TEST",
dTags: ["smoke-test", "dtags"],
context: {
source: "initDuckBugDeviceContext",
platform: "ios",
},
}),
SDK_SKIP_PIPELINE,
);
const body = (mockProvider1.sendLog as ReturnType<typeof mock>).mock
.calls[0][0] as { context?: Record<string, unknown> };
expect(body.context?._duck).toBeUndefined();
spy.mockRestore();
});

it("uses _duck.scope.context when payload has no other keys", () => {
sdk.warn("ONLY_SCOPE_CTX", {
_duck: {
scope: {
context: { a: 1 },
release: "1.0.0",
},
},
});
expect(mockProvider1.sendLog).toHaveBeenCalledWith(
expect.objectContaining({
message: "ONLY_SCOPE_CTX",
context: { a: 1 },
release: "1.0.0",
}),
SDK_SKIP_PIPELINE,
);
});

it("prefers root payload over _duck.scope.context for context", () => {
sdk.warn("ROOT_WINS", {
b: 2,
_duck: {
scope: {
context: { a: 1 },
},
},
});
expect(mockProvider1.sendLog).toHaveBeenCalledWith(
expect.objectContaining({
context: { b: 2 },
}),
SDK_SKIP_PIPELINE,
);
});

it("applies _duck.scope.platform over default node", () => {
sdk.warn("PLATFORM", {
_duck: { scope: { platform: "ios" } },
});
expect(mockProvider1.sendLog).toHaveBeenCalledWith(
expect.objectContaining({
platform: "ios",
}),
SDK_SKIP_PIPELINE,
);
});

it("uses dTags from _duck.scope when _duck.dTags omitted", () => {
sdk.warn("TAG", {
_duck: { scope: { dTags: ["from-scope"] } },
});
expect(mockProvider1.sendLog).toHaveBeenCalledWith(
expect.objectContaining({
dTags: ["from-scope"],
}),
SDK_SKIP_PIPELINE,
);
});

it("_duck.dTags overrides scope.dTags", () => {
sdk.warn("TAG", {
_duck: {
dTags: ["reserved"],
scope: { dTags: ["ignored"] },
},
});
expect(mockProvider1.sendLog).toHaveBeenCalledWith(
expect.objectContaining({
dTags: ["reserved"],
}),
SDK_SKIP_PIPELINE,
);
});

it("treats null payload as context null (typeof null is object)", () => {
// @ts-expect-error intentional loose call
sdk.log("NULL_CTX", null);
expect(mockProvider1.sendLog).toHaveBeenCalledWith(
expect.objectContaining({
message: "NULL_CTX",
context: null,
}),
SDK_SKIP_PIPELINE,
);
});
});

describe("quack", () => {
beforeEach(() => {
sdk = new DuckSDK(providers);
Expand Down
Loading