slackmark-node
v0.1.3
Published
Node.js image renderers for slackmark diagrams and display math
Maintainers
Readme
slackmark-node
Render Mermaid diagrams and display math to local PNGs, upload them, and emit native
Slack slack_file image blocks. Requires Node.js 22.12 or newer. Puppeteer downloads a
compatible browser during installation.
Install
pnpm add slackmark slackmark-nodeConvert
import { FetchSlackUploader } from "slackmark/slack";
import type { Block, UploadReceipt } from "slackmark";
import { createNodeConverter } from "slackmark-node";
declare const slackBotToken: string;
declare const agentMarkdown: string;
declare const channel: string;
declare function postPrepared(
prepared: PreparedPost,
timeoutMs: number,
): Promise<{ readonly ok: true } | { readonly ok: false; readonly status: number }>;
interface PreparedPost {
readonly channel: string;
readonly threadTs?: string;
readonly blocks: ReadonlyArray<Block>;
readonly text: string;
readonly receipts: ReadonlyArray<UploadReceipt>;
}
class PostError extends Error {
readonly prepared: PreparedPost;
readonly ambiguous: boolean;
constructor(prepared: PreparedPost, cause: unknown, ambiguous: boolean) {
super("Slack post failed", { cause });
this.prepared = prepared;
this.ambiguous = ambiguous;
}
}
const converter = createNodeConverter({
uploader: new FetchSlackUploader({ token: slackBotToken }),
});
// Reuse this converter for every request; it owns one shared Chromium.
export async function deliver(): Promise<void> {
const result = await converter.convert(agentMarkdown, { timeoutMs: 30_000 });
const prepared: PreparedPost = {
channel,
blocks: result.blocks,
text: result.text,
receipts: result.receipts,
};
try {
const outcome = await postPrepared(prepared, 10_000);
if (!outcome.ok) {
throw new PostError(
prepared,
new Error(`Slack rejected with HTTP ${String(outcome.status)}`),
false,
);
}
} catch (cause) {
if (cause instanceof PostError) throw cause;
throw new PostError(prepared, cause, true);
}
}
// Close once, during awaited process shutdown — never per request. A closed converter
// rejects every later call. For a one-shot script that converts and exits, close in a
// `finally` and preserve the primary error with `AggregateError`.
export async function shutdown(): Promise<void> {
await converter.close({ behavior: "drain", timeoutMs: 5_000 });
}PostError retains the exact envelope; reusing it prevents re-upload but does not make
chat.postMessage idempotent. Ambiguous timeout/lost-response failures require
reconciliation or acceptance of duplicate-message risk; definite Slack rejection can
retry by app policy. Never reconvert. prepared -> posted persistence is only for app
crash recovery and does not create Slack idempotency. Do not broadly log receipts or
source-bearing URLs.
timeoutMs is relative to call start. signal and timeoutMs are optional on
convert, convertToMessages, and warmup. Per-call uploaders override the optional
factory uploader.
Convert/warmup have no default timeout. Close defaults to drain/5 seconds; async disposal uses cancel/5 seconds. Browser launch and cleanup ceilings are 10 seconds and 2 seconds.
close() rejects new work immediately. Its default is bounded drain; use
close({ behavior: "cancel" }) to request cooperative cancellation. status() reports
state, active/queued work, and retained upload bytes. activeOperations includes
convert, convertToMessages, and warmup calls until underlying settlement. During
converter closing, local render/upload accepting may remain true for work from already
accepted operations. Async disposal uses a finite cancel timeout. The first valid close
promise wins; any accepted close failure, including caller abort, leaves permanent
close-failed state.
Preserve built-ins while extending
import type { UrlImageRenderer } from "slackmark";
import { createNodeConverter } from "slackmark-node";
declare const plantUmlService: {
render(source: string, options: { readonly signal?: AbortSignal | undefined }): Promise<string>;
};
const plantUml: UrlImageRenderer = {
id: "plantuml",
output: "url",
canRender: ({ lang }) => lang === "plantuml",
render: async ({ source, altText }, context) => {
const imageUrl = await plantUmlService.render(source, {
signal: context.signal,
});
return { kind: "url", imageUrl, altText };
},
};
const converter = createNodeConverter({
additionalRenderers: [plantUml],
upload: { concurrency: 2, maxQueueSize: 16 },
});Additional renderers run after local Mermaid and KaTeX. Native Slack Mermaid charts run
before every image renderer. Duplicate IDs are rejected. Use universal
slackmark.createConverter() only to replace the complete renderer list.
Receipts and errors
degradations describe content fallback or substitution. receipts preserve external
upload effects independently, including failed attempts hidden by later renderer
recovery. Receipts can contain sensitive Slack file IDs.
Recognise a caught error with isOperationError / isConfigurationError from slackmark
and isSlackUploadError from slackmark/slack. Each published entry is bundled
separately and carries its own copy of the error classes, so instanceof across entries
is a false negative.
Caller abort, deadline, and shutdown are distinct typed errors. Only
NodeShutdownTimeoutError includes a status snapshot; ordinary cleanup
NodeRenderError does not. A timeout rejects promptly but
cannot kill an arbitrary collaborator promise; queue slots and retained bytes remain
accounted until the underlying promise settles.
Prompt errors expose a frozen receipts snapshot and a non-rejecting
settledReceipts promise for final receipts from that operation. The latter may remain
pending if a collaborator never settles; callers choose any wait bound.
Mermaid and KaTeX run in isolated browser contexts with strict local assets, bounded
source/output limits, and browser egress denied. Advanced seams live at
slackmark-node/renderers and slackmark-node/puppeteer.
See the Rasterize content guide.
License
MIT © Siraj. See THIRD_PARTY_NOTICES.md.
