# @timbro/sdk

The SDK exposes the Source Fiscal Operations contract through one configured client. Rust owns the wire contract; the SDK uses generated operation bindings and validators at every HTTP boundary.

```ts
import { createTimbroClient, digestSha256Hex } from "@timbro/sdk";
import type { SourceSalesDocument } from "@timbro/sdk";

const credential = process.env.TIMBRO_CREDENTIAL;
if (credential === undefined || credential.trim() === "") {
  throw new Error("TIMBRO_CREDENTIAL is required");
}

const document: SourceSalesDocument = {
  kind: "consumer",
  buyer: { identity_kind: "anonymous" },
  sale: {
    currency: { kind: "dop" },
    declared_totals: {
      net: "100.00",
      non_billable: "0.00",
      tax: "18.00",
      total: "118.00",
    },
    lines: [
      {
        source_line_id: "line-1",
        description: "Example product",
        item_kind: "good",
        measurement_unit: "unit",
        quantity: "1",
        unit_price: "118.00",
        tax_treatment: "itbis_18",
      },
    ],
    payment_terms: { terms: "cash" },
  },
};

const sourceContentSha256 = await digestSha256Hex(
  new TextEncoder().encode(JSON.stringify(document)),
);

const timbro = createTimbroClient({
  baseUrl: "https://stamp.example.test",
  credential,
});

const operation = await timbro.fiscalOperations.create({
  source: {
    recordId: "checkout-order-1001",
    revision: 1,
    contentSha256: sourceContentSha256,
  },
  idempotencyKey: "checkout-order-1001-create",
  action: { kind: "issue", document },
  printedRepresentation: { profile: "receipt_80mm" },
});
```

`source.contentSha256` identifies the exact immutable Source record snapshot represented by `recordId` and `revision`; it is not a placeholder or a hash Timbro invents from the normalized Fiscal command. Define one deterministic serialization in the Source adapter, hash those exact bytes, and retain the same digest for every replay of that revision. If the Source snapshot changes, advance the revision and hash the new snapshot.

Both create boundaries return a retained operation when fiscal evaluation rejects it; inspect `operation.outcome` and its diagnostics just as you would after `get` or a webhook. Exceptions remain reserved for malformed or unsupported input, authentication and authorization failures, conflicts, transport failures, and other cases where no modeled create result can be returned.

`fiscalOperations.get({ fiscalOperationId })` recovers an operation and its actor-facing outcome. `findBySource({ recordId, revision })` arbitrates by the caller's source identity. The projection contains source identity, action, outcome and terminality, fiscal identity, exact decimal-string totals, correction relationships, signed-document readiness, printed-representation readiness, buyer-delivery readiness, bounded diagnostics, and the latest durable event identity. Internal attempts, drains, leases, storage keys, provider callbacks, and worker topology are not public.

An `outcome_unknown` submission remains `pending` while Timbro reconciles the same fiscal identity with DGII. Continue observing it without resubmitting the document. Only `intervention_required` means automatic reconciliation exhausted its bounded budget and an operator must take over.

For complete generated Fiscal intent, use the advanced boundary:

```ts
const operation = await timbro.advanced.fiscalIntentAdmissions.create({
  body: fiscalAdmissionPayload,
});
```

`printedRepresentations.download({ fiscalOperationId })` retrieves the operation-addressed immutable PDF and verifies every published identity header, profile/version, renderer identity, digest, signed-source digest, pagination-plan digest, length, page count, creation time, media type, and the actual bytes. The result exposes one content digest as `contentSha256`; storage keys and compatibility aliases are not exposed.

Buyer delivery is independent of representation readiness:

```ts
const delivery = await timbro.fiscalDeliveries.create({
  fiscalOperationId: operation.id,
  recipientEmail: "buyer@example.test",
  idempotencyKey: "checkout-order-1001-email",
});
```

### Webhooks and recovery

Verify the signature against the exact request body bytes before parsing. Do not parse, reserialize, or pretty-print the body before verification; the signed payload is the original UTF-8 text.

```ts
import {
  parseWebhookEvent,
} from "@timbro/sdk";
import { verifyWebhookSignature } from "@timbro/sdk/webhook-signature";

const signature = verifyWebhookSignature({
  payload: requestBodyText,
  signatureHeader: request.headers.get("timbro-signature") ?? "",
  secrets: [webhookSecret],
});
if (!signature.verified) {
  throw new Error(`Webhook signature rejected: ${signature.reason}`);
}

const event = parseWebhookEvent(requestBodyText);
if (event.event_type === "source_connection.verification_requested") {
  // Build and submit the signed activation proof before acknowledging this event.
  // See examples/webhook-receiver.ts for the complete server-runtime flow.
  throw new Error("activation verification must complete before acknowledgement");
}
const recovered = await timbro.fiscalOperations.get({
  fiscalOperationId: event.data.fiscal_operation_id,
});
```

The v4 envelope attributes every event to its recipient `source_connection_id`.
`webhook_event_id`, `sequence`, and `occurred_at` are retained as
strings/timestamps, and `sequence` stays a decimal string so JavaScript cannot
lose bigint precision. If an operation-event delivery is missed, recover the
current actor-facing outcome with `fiscalOperations.get` using its operation ID.

Credentials belong on a trusted application server or native-assisted client. The package does not establish DGII approval, printer compatibility or legibility, hosted Checkout cutover, production capacity, or certification.
