Skip to content
QISHU DOCUMENT ARCHIVE

Qishu Archives

A shared entry for product documents, interface references, engineering notes, and release-ready delivery records.

sdk / typescript

TypeScript SDK

NIB printer SDK integration guide for Web, mini-programs, Node, and bridge runtimes.

The TypeScript SDK is suitable for Web, mini-programs, UniApp, Taro, Node tools, and native bridge runtimes. When starting, keep one rule in mind: template code only generates print commands, and platform code only writes bytes into the printer.

Package Purpose
@boxliy/nib Standard aggregate package that exports core, Boxliy/Aryten/Lin8inch dialects, and image capabilities.
@nib/core ConnectedDevice, writeTo(), WriteOptions, receive sources, and query dispatch.
@nib/esc-boxliy, @nib/tspl-boxliy, @nib/cpcl-boxliy Boxliy ESC, TSPL, and CPCL command builders and response parsers.
@nib/esc, @nib/tspl, @nib/cpcl Aryten-compatible dialects.
@nib/esc-lin8inch, @nib/tspl-lin8inch Lin8inch dialects.
@nib/bluetooth-ble-core BLE characteristic selection, UUID matching, and credit flow control.
@nib/wechat-bluetooth-ble, @nib/uniapp-bluetooth-ble, @nib/taro-bluetooth-ble BLE adapters for WeChat, UniApp, and Taro.
@nib/webusb Browser WebUSB connection.

If you are not sure where to start, business projects usually start with @boxliy/nib. Depend on lower-level modules directly only when you need package splitting or capability trimming.

All platform adapters eventually provide core’s ConnectedDevice:

interface ConnectedDevice {
origin(): any
deviceName(): string
connectionState(): ConnectionState
disconnect(): Promise<void>
canRead(): boolean
write(data: Uint8Array): Promise<void>
read(options?: ReadOptions): Promise<Uint8Array>
notify(callback: (value: Uint8Array) => Promise<void>): void
flush(): void
}

WeChat, mini-program frameworks, WebUSB, and native App APIs can all be completely different. Once they are wrapped as this interface, the same print templates can be reused.

Start with a TSPL label example because it clearly expresses paper size, clearing the canvas, placing text, and print count:

import { TsplAryten } from '@boxliy/nib'
await TsplAryten.create()
.size(40, 30)
.cls()
.text({ x: 20, y: 20, content: 'NIB SDK' })
.print()
.writeTo(device)

writeTo(device) writes the bytes in the builder to the device, then clears the current builder. You can also get the bytes first and write manually:

import { WriteOptions, writeTo } from '@boxliy/nib'
const data = TsplAryten.create()
.size(40, 30)
.cls()
.text({ x: 20, y: 20, content: 'NIB SDK' })
.print()
.bytes()
await writeTo(device, data, new WriteOptions(true, 512))

writeTo() enables chunked writing by default, with a default chunk size of 512 bytes. Consider disabling chunking only when the device or platform API already handles it.

Do not mix examples from different languages or dialects. The current TypeScript EscBoxliy is suitable for ESC commands, queries, images, and related capabilities, but it does not use the Java/Swift-style text('...') example shape. For normal text content, use the TSPL/CPCL text(...) API, or generate raw bytes through the methods supported by the specific ESC dialect.

import { EscBoxliy } from '@boxliy/nib'
const script = EscBoxliy.create()
.reset()
.feed(2)
.bytes()
await writeTo(device, script)

@nib/bluetooth-ble-core provides two credit strategies:

API Purpose
BleLaneCreditFlowControlStrategy Default lane-credit strategy that writes chunks according to credits and MTU.
BleSignalCreditFlowControlStrategy signal-credit strategy for devices with different credit notification semantics.
BleCreditOptions Configures service UUID, write/read/credit characteristics, initial credit, MTU, and fallback.
selectBleCreditCharacteristicPair() Finds write, read, and credit characteristics from a service list by UUID.

Default UUIDs are:

Item Default
service FF00
write characteristic FF02
read characteristic FF01
credit characteristic FF03

The default lane-credit initial credit is 1, the initial MTU is 20, and payload overhead is 3. signal-credit defaults to initial credit 0 and payload overhead 0. If fallbackMode: 'bypass-write' is enabled, credit timeout can fall back to normal writes. The default behavior is to fail.

Common core receive and query types include ReceiveSource, PollingReceiveSource, CallbackReceiveSource, NotifyReceiveSource, receiveSourceOf(), QueryDispatcher, and PendingQuery.

Boxliy dialects provide response parsers:

Dialect Parser
ESC EscResponseParser
TSPL TsplResponseParser
CPCL CpclResponseParser

When querying status, first generate and write the query command with a dialect builder, then pass device responses to the corresponding parser. Keep parsing logic in the print session layer, not scattered across UI components.

Methods and Commands

The tables below list the public entry points integration teams usually need. Builder methods generate printer commands; actual availability still depends on the ESC, TSPL, CPCL, or Lin8inch command family supported by the target firmware.

Core, Connection, and Writing

ObjectMethod / CommandPurposeParameters
ConnectedDeviceorigin(), deviceName(), connectionState(), disconnect(), canRead(), write(data), read(options), notify(callback), flush()Abstracts the real printer connection for templates, write pipelines, and query handling.`write/read/notify` are implemented by platform adapters; `flush` clears adapter queues or buffers.
writeTo / WriteOptionswriteTo(device, data, options), new WriteOptions(enableChunkWrite, chunkSize)Writes built bytes to a device with chunking, timeout, cancellation, and flow-control rules.`enableChunkWrite` toggles chunking; `chunkSize` defaults to 512; `data` can come from builder.bytes().
Pen / ReceiveSource / QueryDispatcherappend(), appendByte(), appendBytes(), appendText(), bytes(), reset(), start(), stop(), accept(), receive(), query(), cancel(), shutdown()Routes device responses into listeners or query dispatchers for status, battery, model, and similar queries.`append*` appends bytes or text; query matchers map responses to business results.
BLE adaptersBleCreditOptions, BleLaneCreditFlowControlStrategy, BleSignalCreditFlowControlStrategy, selectBleCreditCharacteristicPair(), isBleUuidMatch()Handles BLE characteristic selection, MTU chunking, credit notifications, and fallback writes.Configure UUIDs, initialCredit, initialMtu, payloadMtu, and fallbackMode; platform packages handle WeChat, Taro, UniApp, and WebUSB connections.

Command Builders

ObjectMethod / CommandPurposeParameters
EscBoxliy / EscArytenbytes(), reset(), lineDot(), backLineDot(), batteryVolume(), enable(), getShutdownTime(), learnLabelGap(), line(), location(), mac(), info(), model(), name(), paperType(), position(), printerVersion(), setShutdownTime(), sn(), state(), stopJob(), thickness(), version(), wakeup(), setBTType(), cut(), lineDotCut(), nn(), setCurrentTime(), image()Builds ESC/Boxliy commands for receipt, portable, and ESC-compatible printers.Most methods take no arguments or numbers; `setCurrentTime` takes date/time fields; `image` takes x/y/bitmap/byteWidth/height/compress.
TsplBoxliy / TsplArytenbytes(), reset(), size(), gap(), bline(), continuous(), label(), cls(), direction(), speed(), density(), reference(), offset(), shift(), ribbon(), tear(), peel(), cut(), print(), bar(), line(), box(), circle(), ellipse(), text(), textBox(), barcode(), qrcode(), dmatrix(), image(), downloadBmp(), putImage()Builds TSPL label commands for templates with paper size, coordinates, barcodes, and QR codes.TSPL methods mostly use options objects; coordinates and sizes are dots or millimeters according to the TSPL command; text/barcode/QR use content/value, font, rotation, and level.
CpclBoxliy / CpclArytenbytes(), reset(), page(), feed(), form(), print(), gapSense(), pageWidth(), text(), setMag(), bold(), underline(), watermark(), line(), box(), inverse(), barcode(), qrcode(), image(), status(), sn()Builds CPCL label commands for page setup, text, lines, barcodes, and images.CPCL methods mostly use options objects; `page` takes height/copies/pageWidth; primitives use coordinates, sizes, and line width; images use bitmap or prepared bitmap.
EscLin8inchbatteryLevel(), extendedModel(), bootVersion(), advancedDensity(), advancedDensityStatus(), mediaProfile(), mediaProfileStatus(), grayMode(), grayscaleImage(), wirelessProvisioning(), wirelessProvisioningStatus(), compressedRasterTransport(), mediaTag(), mediaTagUid(), consumedMediaLength(), remainingMediaLength(), restoreLabelStartPosition(), alternateMotionProfile()Adds Lin8inch telemetry, media, provisioning, and raster transport commands on top of ESC.`grayscaleImage` takes image options; `wirelessProvisioning` takes ssid/password/mode; most others are query or switch commands.
TsplLin8inchautomaticStatusFeedback(), printCompletion(), printerStatus(), firmwareVersion(), serialNumber(), macAddress(), deviceSpeed(), deviceSelfTest(), thermalStatus(), productId(), versionInfo(), selfTestPage(), redDensity(), blackColor(), ribbonEnd(), ribbonEndStatus(), modelSetting(), serialSetting(), versionSetting(), gbkCodepage(), utf8Codepage(), gapDetection()Adds Lin8inch status feedback, media, ribbon, and presentation commands on top of TSPL.`printCompletion` takes a token; `redDensity/deviceSpeed` take numbers; `printerStatus` takes a status flag.

Response Parsing

ObjectMethod / CommandPurposeParameters
EscResponse / TsplResponse / CpclResponsegetQuery(), getType(), getRaw(), getRawHex(), getStatusByte(), getStatusFlags(), hasStatusFlag(), isReady(), getBatteryLevel(), getText(), getMacAddress(), getEventValue(), getDescription()Parses printer responses into status, battery, text, MAC, event, or unknown response objects.ESC includes event values; TSPL/CPCL mainly expose status, battery, text, MAC, and descriptions.
  • Confirm whether the printer supports ESC, TSPL, or CPCL before choosing a builder.
  • Keep platform Bluetooth, USB, and bridge APIs in the adapter layer. The template layer only generates bytes.
  • Keep byte snapshot tests for every template so UI changes do not break commands.
  • BLE devices must be validated on real hardware for MTU, chunk size, credit notifications, and reconnect behavior.