惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

B
Blog RSS Feed
博客园_首页
N
News | PayPal Newsroom
有赞技术团队
有赞技术团队
The Hacker News
The Hacker News
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
The Cloudflare Blog
S
SegmentFault 最新的问题
Jina AI
Jina AI
人人都是产品经理
人人都是产品经理
P
Privacy & Cybersecurity Law Blog
AI
AI
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Schneier on Security
Schneier on Security
博客园 - 三生石上(FineUI控件)
月光博客
月光博客
量子位
Forbes - Security
Forbes - Security
爱范儿
爱范儿
云风的 BLOG
云风的 BLOG
SecWiki News
SecWiki News
Last Week in AI
Last Week in AI
酷 壳 – CoolShell
酷 壳 – CoolShell
T
Tor Project blog
Recorded Future
Recorded Future
A
About on SuperTechFans
J
Java Code Geeks
The Register - Security
The Register - Security
PCI Perspectives
PCI Perspectives
H
Hacker News: Front Page
V2EX - 技术
V2EX - 技术
S
Secure Thoughts
V
Vulnerabilities – Threatpost
Hacker News: Ask HN
Hacker News: Ask HN
MongoDB | Blog
MongoDB | Blog
N
Netflix TechBlog - Medium
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Scott Helme
Scott Helme
T
The Exploit Database - CXSecurity.com
Y
Y Combinator Blog
AWS News Blog
AWS News Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
IT之家
IT之家
T
The Blog of Author Tim Ferriss
G
Google Developers Blog
C
CERT Recently Published Vulnerability Notes
L
LangChain Blog
F
Full Disclosure
Application and Cybersecurity Blog
Application and Cybersecurity Blog
The GitHub Blog
The GitHub Blog

Recent Commits to openclaw:main

test: merge chat side-result checks · openclaw/openclaw@ddd2c2a test: merge cron history checks · openclaw/openclaw@f7eb746 test: merge responsive navigation shell checks · openclaw/openclaw@c2e4b47 docs(changelog): add codex oauth fixes · openclaw/openclaw@628e6cd test: merge navigation routing cases · openclaw/openclaw@5d8cecb Tests: mock channel registry bundled fallback · openclaw/openclaw@2b08233 Secrets: avoid broad web search discovery for single plugin config · openclaw/openclaw@a464f59 test: merge config view browser checks · openclaw/openclaw@20cf511 fix(status): align oauth health with runtime · openclaw/openclaw@eed7116 feat: add macOS screen snapshots for monitor preview (#67954) thanks … · openclaw/openclaw@f377db1 fix: report shared auth scopes in hello-ok (#67810) thanks @BunsDev · openclaw/openclaw@0b6c39b Auto-reply: avoid eager bundled route fallback · openclaw/openclaw@3ea1bf4 Tests: narrow session binding contract setup · openclaw/openclaw@54e4e16 fix(macOS): enable undo/redo in webchat composer text input (#34962) · openclaw/openclaw@00951dc Tests: speed up channel setup promotion · openclaw/openclaw@82b529a Docs: refresh agent instructions · openclaw/openclaw@5775fe2 fix(auth): serialize OAuth refresh across agents to fix #26322 (#67876) · openclaw/openclaw@8e79080 test: allow ollama public surface boundary test · openclaw/openclaw@7d4f1a6 Docs: add test performance guardrails · openclaw/openclaw@89706d3 Tests: restore context-engine usage proof · openclaw/openclaw@e4c4f95 Tests: slim context engine runtime coverage · openclaw/openclaw@74c198f ci: retry failed custom checkouts · openclaw/openclaw@0ee5baf test: trim duplicate provider auth onboarding cases · openclaw/openclaw@1ffc02e matrix: fix sessions_spawn --thread subagent session spawning (#67643) · openclaw/openclaw@1ce2596 test: reduce auth choice fixture churn · openclaw/openclaw@857b9cd test: mock health status config boundaries · openclaw/openclaw@9d5ab4a test: mock onboard config io boundary · openclaw/openclaw@299694d test: mock legacy state plugin boundaries · openclaw/openclaw@2713089 test: mock channel install boundaries · openclaw/openclaw@b945248 test: mock doctor preview channel boundaries · openclaw/openclaw@b1a3ad4 test: trim doctor command hotspots · openclaw/openclaw@c66f16a test: isolate agent auth and spawn hotspots · openclaw/openclaw@9285935 test: stabilize MCP startup disposal race · openclaw/openclaw@dd9d2eb test: merge browser contract server suites · openclaw/openclaw@5817a76 test: narrow ollama provider discovery setup · openclaw/openclaw@a0d9598 build: declare qa-lab aimock runtime dependency · openclaw/openclaw@24431e5 test: speed up safe-bins exec harness · openclaw/openclaw@ee856ab test: preserve tool helpers in embedded runner mocks · openclaw/openclaw@acd86a0 refactor: move memory embeddings into provider plugins · openclaw/openclaw@77e6e4c test: reuse system-run temp fixtures · openclaw/openclaw@7e9ff0f test: trim hotspot wait overhead · openclaw/openclaw@12a59b0 Check: avoid duplicate boundary prep · openclaw/openclaw@baf11b8 test: reduce hotspot fixture overhead · openclaw/openclaw@3a59edd feat(ui): overhaul settings and slash command UX (#67819) thanks @Bun… · openclaw/openclaw@2cfb660 QA Matrix: exit cleanly on failure · openclaw/openclaw@42805d2 QA Matrix: isolate scenario coverage · openclaw/openclaw@7e659e1 Matrix: refresh crypto bootstrap state · openclaw/openclaw@94081d8 QA Lab: add provider registry · openclaw/openclaw@bb7e982 Matrix: add plugin changelog · openclaw/openclaw@4acab55 test: trim more hotspot overhead · openclaw/openclaw@f485311 test: trim remaining hotspot tests · openclaw/openclaw@6ba8626 test: narrow hotspot mocks · openclaw/openclaw@dbc8179 test: isolate gemini embedding request helpers · openclaw/openclaw@cd330f5 test: trim memory and mcp hotspots · openclaw/openclaw@fd48dfa test: slim provider registry mocks · openclaw/openclaw@2e08c77 test: harden Parallels update smoke · openclaw/openclaw@1a98090 feat: default Anthropic to Opus 4.7 · openclaw/openclaw@628b454 fix: harden node-host shell payload mutability checks · openclaw/openclaw@75c551e fix: land node-host approval binding for native binaries (#66731) (th… · openclaw/openclaw@29919bb CI: add daily schedule to CodeQL workflow (#67645) · openclaw/openclaw@69d25f5 fix(gateway): capture config hash after plugin auto-enable to prevent… · openclaw/openclaw@8c11210 fix: repair sanitized replay tool results before send (#67620) (thank… · openclaw/openclaw@c3c7a99 fix: restrict HTML timeout short-circuit to transient statuses · openclaw/openclaw@de129a6 fix: keep TUI watchdog bound to active run (#67401) (thanks @xantorres) · openclaw/openclaw@3525273 Gateway/skills: dedupe skills prefix-match + drop dead fallback on log · openclaw/openclaw@d7f489f Extensions/lmstudio: back off inference preload after consecutive fai… · openclaw/openclaw@b555214 TUI/streaming: add watchdog that resets the activity indicator after … · openclaw/openclaw@f44ab20 Agents/tool-loop: enable unknown-tool stream guard by default · openclaw/openclaw@36ed367 Gateway/skills: invalidate session skills snapshot on config write · openclaw/openclaw@b23d59a fix: classify HTML provider error pages correctly (#67642) (thanks @s… · openclaw/openclaw@e588e90 fix(skills): remove unused model-usage import (#67641) · openclaw/openclaw@55f05df docs(changelog): credit codex fix superseded PRs · openclaw/openclaw@e485f24 fix(openai-codex): normalize stale transport metadata in resolution a… · openclaw/openclaw@90801ba CI: pin Docker-related GitHub Actions (#67632) · openclaw/openclaw@f697b01 Android: modernize WebView and discovery API usage (#67627) · openclaw/openclaw@44a6e50 fix(deps): bump hono to 4.12.14 and @hono/node-server to 1.19.14 (GHS… · openclaw/openclaw@fbccc18 fix(deps): bump dompurify to 3.4.0 (#67614) · openclaw/openclaw@2c2dc00 CI: add explicit permissions to all workflow jobs (fixes code-scannin… · openclaw/openclaw@01b7516 fix: register bundled TTS providers and route overrides correctly (#6… · openclaw/openclaw@6ea3cdd fix: align host tilde paths with OS home (#62804) (thanks @stainlu) · openclaw/openclaw@ecfaf64 fix: flush creds queue before reconnect socket open (#67464) (thanks … · openclaw/openclaw@405c63f fix: strip standalone <function> tool call tags from visible text (#6… · openclaw/openclaw@78df859 fix(agents): preserve cli session metadata before transcript persist … · openclaw/openclaw@898fd04 docs(changelog): move cli transcript entry · openclaw/openclaw@c1817c6 fix(agents): normalize cli transcript api field · openclaw/openclaw@3a3fae0 docs(changelog): note cli transcript persistence · openclaw/openclaw@6c343f1 fix(agents): persist cli transcript turns · openclaw/openclaw@b8ef507 fix(msteams): harden security-sensitive flows (#65841) · openclaw/openclaw@c56b56e [Dashboard] Fix exec approval modal overflow for long command content… · openclaw/openclaw@053c5b0 Docs: remove QA changelog entry · openclaw/openclaw@7fd5771 QA: fix private runtime source loading (#67428) · openclaw/openclaw@d5933af docs(gateway): correct protocol.md schema path, hello-ok example, aut… · openclaw/openclaw@489404d CI: pin Node 22 runners to 22.18.0 · openclaw/openclaw@4ffa621 models.authStatus: normalize provider ids + tighten env-backed escape… · openclaw/openclaw@f2fdb9d Update CHANGELOG.md · openclaw/openclaw@7694a92 test(parallels): clean up npm update guard jobs · openclaw/openclaw@045ea7b Plugins: prefer scanDir override paths · openclaw/openclaw@b2974da fix(dreaming): default storage.mode to "separate" so phase blocks sto… · openclaw/openclaw@8c392f0 fix(memory-core): skip dreaming transcript ingestion via session stor… · openclaw/openclaw@a1b01f0 fix: dedupe replayed exec.finished node events (#67281) · openclaw/openclaw@5dcf526
refactor(qr): share PNG data URL helpers (#70784) · openclaw/openclaw@1daa552
vincentkoc · 2026-04-24 · via Recent Commits to openclaw:main
Original file line numberDiff line numberDiff line change

@@ -261,6 +261,13 @@ const pngQr = await api.runtime.media.renderQrPngBase64("https://openclaw.ai", {

261261

scale: 6, // 1-12

262262

marginModules: 4, // 0-16

263263

});

264+

const pngQrDataUrl = await api.runtime.media.renderQrPngDataUrl("https://openclaw.ai");

265+

const tmpRoot = resolvePreferredOpenClawTmpDir();

266+

const pngQrFile = await api.runtime.media.writeQrPngTempFile("https://openclaw.ai", {

267+

tmpRoot,

268+

dirPrefix: "my-plugin-qr-",

269+

fileName: "qr.png",

270+

});

264271

```

265272
266273

### `api.runtime.config`

Original file line numberDiff line numberDiff line change

@@ -17,4 +17,4 @@ export {

1717

resolvePreferredOpenClawTmpDir,

1818

runPluginCommandWithTimeout,

1919

} from "openclaw/plugin-sdk/sandbox";

20-

export { renderQrPngBase64 } from "./qr-image.js";

20+

export { renderQrPngBase64, renderQrPngDataUrl, writeQrPngTempFile } from "./qr-image.js";

Original file line numberDiff line numberDiff line change

@@ -17,9 +17,15 @@ const pluginApiMocks = vi.hoisted(() => ({

1717

expiresAtMs: Date.now() + 10 * 60_000,

1818

})),

1919

revokeDeviceBootstrapToken: vi.fn(async () => ({ removed: true })),

20-

renderQrPngBase64: vi.fn(async () => "ZmFrZXBuZw=="),

20+

renderQrPngDataUrl: vi.fn(async () => "data:image/png;base64,ZmFrZXBuZw=="),

2121

resolveGatewayPort: vi.fn(() => 18789),

2222

resolvePreferredOpenClawTmpDir: vi.fn(() => path.join(os.tmpdir(), "openclaw-device-pair-tests")),

23+

writeQrPngTempFile: vi.fn(async (_data: string, opts: { tmpRoot: string }) => {

24+

const dirPath = await fs.mkdtemp(path.join(opts.tmpRoot, "device-pair-qr-"));

25+

const filePath = path.join(dirPath, "pair-qr.png");

26+

await fs.writeFile(filePath, "fakepng");

27+

return { filePath, dirPath, mediaLocalRoots: [dirPath] };

28+

}),

2329

}));

2430
2531

vi.mock("./api.js", () => {

@@ -33,13 +39,14 @@ vi.mock("./api.js", () => {

3339

definePluginEntry: vi.fn((entry) => entry),

3440

issueDeviceBootstrapToken: pluginApiMocks.issueDeviceBootstrapToken,

3541

listDevicePairing: vi.fn(async () => ({ pending: [] })),

36-

renderQrPngBase64: pluginApiMocks.renderQrPngBase64,

42+

renderQrPngDataUrl: pluginApiMocks.renderQrPngDataUrl,

3743

revokeDeviceBootstrapToken: pluginApiMocks.revokeDeviceBootstrapToken,

3844

resolvePreferredOpenClawTmpDir: pluginApiMocks.resolvePreferredOpenClawTmpDir,

3945

resolveGatewayBindUrl: vi.fn(),

4046

resolveGatewayPort: pluginApiMocks.resolveGatewayPort,

4147

resolveTailnetHostWithRunner: vi.fn(),

4248

runPluginCommandWithTimeout: vi.fn(),

49+

writeQrPngTempFile: pluginApiMocks.writeQrPngTempFile,

4350

};

4451

});

4552

@@ -254,7 +261,7 @@ describe("device-pair /pair qr", () => {

254261

const payload = result as { text?: string; mediaUrl?: string; sensitiveMedia?: boolean };

255262

const text = requireText(result);

256263
257-

expect(pluginApiMocks.renderQrPngBase64).toHaveBeenCalledTimes(1);

264+

expect(pluginApiMocks.renderQrPngDataUrl).toHaveBeenCalledTimes(1);

258265

expect(pluginApiMocks.issueDeviceBootstrapToken).toHaveBeenCalledWith({

259266

profile: {

260267

roles: ["node"],

@@ -297,7 +304,7 @@ describe("device-pair /pair qr", () => {

297304

token: "second-token",

298305

expiresAtMs: Date.now() + 10 * 60_000,

299306

});

300-

pluginApiMocks.renderQrPngBase64.mockRejectedValueOnce(new Error("render failed"));

307+

pluginApiMocks.renderQrPngDataUrl.mockRejectedValueOnce(new Error("render failed"));

301308
302309

const command = registerPairCommand();

303310

const result = await command.handler(

Original file line numberDiff line numberDiff line change

@@ -1,4 +1,4 @@

1-

import { mkdtemp, rm, writeFile } from "node:fs/promises";

1+

import { rm } from "node:fs/promises";

22

import os from "node:os";

33

import path from "node:path";

44

import {

@@ -11,7 +11,8 @@ import {

1111

issueDeviceBootstrapToken,

1212

listDevicePairing,

1313

PAIRING_SETUP_BOOTSTRAP_PROFILE,

14-

renderQrPngBase64,

14+

renderQrPngDataUrl,

15+

writeQrPngTempFile,

1516

revokeDeviceBootstrapToken,

1617

resolveGatewayBindUrl,

1718

resolveGatewayPort,

@@ -35,20 +36,6 @@ import {

3536

resolvePairingCommandAuthState,

3637

} from "./pair-command-auth.js";

3738
38-

async function renderQrDataUrl(data: string): Promise<string> {

39-

const pngBase64 = await renderQrPngBase64(data);

40-

return `data:image/png;base64,${pngBase64}`;

41-

}

42-
43-

async function writeQrPngTempFile(data: string): Promise<string> {

44-

const pngBase64 = await renderQrPngBase64(data);

45-

const tmpRoot = resolvePreferredOpenClawTmpDir();

46-

const qrDir = await mkdtemp(path.join(tmpRoot, "device-pair-qr-"));

47-

const filePath = path.join(qrDir, "pair-qr.png");

48-

await writeFile(filePath, Buffer.from(pngBase64, "base64"));

49-

return filePath;

50-

}

51-
5239

function formatDurationMinutes(expiresAtMs: number): string {

5340

const msRemaining = Math.max(0, expiresAtMs - Date.now());

5441

const minutes = Math.max(1, Math.ceil(msRemaining / 60_000));

@@ -671,7 +658,13 @@ export default definePluginEntry({

671658

if (target && canSendQrPngToChannel(channel)) {

672659

let qrFilePath: string | undefined;

673660

try {

674-

qrFilePath = await writeQrPngTempFile(setupCode);

661+

qrFilePath = (

662+

await writeQrPngTempFile(setupCode, {

663+

tmpRoot: resolvePreferredOpenClawTmpDir(),

664+

dirPrefix: "device-pair-qr-",

665+

fileName: "pair-qr.png",

666+

})

667+

).filePath;

675668

const sent = await sendQrPngToSupportedChannel({

676669

api,

677670

ctx,

@@ -709,7 +702,7 @@ export default definePluginEntry({

709702

if (channel === "webchat") {

710703

let qrDataUrl: string;

711704

try {

712-

qrDataUrl = await renderQrDataUrl(setupCode);

705+

qrDataUrl = await renderQrPngDataUrl(setupCode);

713706

} catch (err) {

714707

api.logger.warn?.(

715708

`device-pair: webchat QR render failed, falling back (${(err as Error)?.message ?? err})`,

Original file line numberDiff line numberDiff line change

@@ -1 +1,5 @@

1-

export { renderQrPngBase64 } from "openclaw/plugin-sdk/media-runtime";

1+

export {

2+

renderQrPngBase64,

3+

renderQrPngDataUrl,

4+

writeQrPngTempFile,

5+

} from "openclaw/plugin-sdk/media-runtime";

Original file line numberDiff line numberDiff line change

@@ -40,6 +40,7 @@ vi.mock("./session.js", async () => {

4040
4141

vi.mock("./qr-image.js", () => ({

4242

renderQrPngBase64: vi.fn(async () => "base64"),

43+

renderQrPngDataUrl: vi.fn(async () => "data:image/png;base64,base64"),

4344

}));

4445
4546

const createWaSocketMock = vi.mocked(createWaSocket);

Original file line numberDiff line numberDiff line change

@@ -9,7 +9,7 @@ import {

99

waitForWhatsAppLoginResult,

1010

WHATSAPP_LOGGED_OUT_QR_MESSAGE,

1111

} from "./connection-controller.js";

12-

import { renderQrPngBase64 } from "./qr-image.js";

12+

import { renderQrPngDataUrl } from "./qr-image.js";

1313

import {

1414

createWaSocket,

1515

readWebAuthExistsForDecision,

@@ -278,8 +278,7 @@ export async function startWebLoginWithQr(

278278

};

279279

}

280280
281-

const base64 = await renderQrPngBase64(loginStartResult.qr);

282-

login.qrDataUrl = `data:image/png;base64,${base64}`;

281+

login.qrDataUrl = await renderQrPngDataUrl(loginStartResult.qr);

283282

return {

284283

qrDataUrl: login.qrDataUrl,

285284

message: "Scan this QR in WhatsApp → Linked Devices.",

Original file line numberDiff line numberDiff line change

@@ -1 +1 @@

1-

export { renderQrPngBase64 } from "openclaw/plugin-sdk/media-runtime";

1+

export { renderQrPngBase64, renderQrPngDataUrl } from "openclaw/plugin-sdk/media-runtime";

Original file line numberDiff line numberDiff line change

@@ -1,21 +1,41 @@

1-

import { beforeEach, describe, expect, it, vi } from "vitest";

1+

import fs from "node:fs/promises";

2+

import os from "node:os";

3+

import path from "node:path";

4+

import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";

25
3-

const renderPngBase64 = vi.hoisted(() => vi.fn(async () => "mocked-base64"));

6+

const { MOCK_PNG_BASE64, renderPngBase64 } = vi.hoisted(() => {

7+

const MOCK_PNG_BASE64 = "ZmFrZXBuZw==";

8+

return {

9+

MOCK_PNG_BASE64,

10+

renderPngBase64: vi.fn(async () => MOCK_PNG_BASE64),

11+

};

12+

});

413
514

vi.mock("@vincentkoc/qrcode-tui", () => ({

615

renderPngBase64,

716

}));

817
9-

import { renderQrPngBase64 } from "./qr-image.ts";

18+

import {

19+

formatQrPngDataUrl,

20+

renderQrPngBase64,

21+

renderQrPngDataUrl,

22+

writeQrPngTempFile,

23+

} from "./qr-image.ts";

1024
1125

describe("renderQrPngBase64", () => {

26+

const tmpRoot = path.join(os.tmpdir(), "openclaw-qr-image-tests");

27+
1228

beforeEach(() => {

1329

renderPngBase64.mockClear();

1430

});

1531
32+

afterEach(async () => {

33+

await fs.rm(tmpRoot, { recursive: true, force: true });

34+

});

35+
1636

it("delegates PNG rendering to qrcode-tui", async () => {

1737

await expect(renderQrPngBase64("openclaw", { scale: 8, marginModules: 2 })).resolves.toBe(

18-

"mocked-base64",

38+

MOCK_PNG_BASE64,

1939

);

2040

expect(renderPngBase64).toHaveBeenCalledWith("openclaw", {

2141

margin: 2,

@@ -50,4 +70,40 @@ describe("renderQrPngBase64", () => {

5070

await expect(renderQrPngBase64("openclaw", { scale, marginModules })).rejects.toThrow(message);

5171

expect(renderPngBase64).not.toHaveBeenCalled();

5272

});

73+
74+

it("formats QR PNG data URLs", async () => {

75+

expect(formatQrPngDataUrl(MOCK_PNG_BASE64)).toBe(`data:image/png;base64,${MOCK_PNG_BASE64}`);

76+

await expect(renderQrPngDataUrl("openclaw")).resolves.toBe(

77+

`data:image/png;base64,${MOCK_PNG_BASE64}`,

78+

);

79+

});

80+
81+

it("writes QR PNGs to a scoped temp file", async () => {

82+

await fs.mkdir(tmpRoot, { recursive: true });

83+
84+

const result = await writeQrPngTempFile("openclaw", {

85+

tmpRoot,

86+

dirPrefix: "pair-",

87+

fileName: "pair-qr.png",

88+

});

89+
90+

expect(path.basename(result.filePath)).toBe("pair-qr.png");

91+

expect(path.basename(result.dirPath)).toMatch(/^pair-/);

92+

expect(result.mediaLocalRoots).toEqual([result.dirPath]);

93+

await expect(fs.readFile(result.filePath, "utf8")).resolves.toBe("fakepng");

94+

});

95+
96+

it.each([

97+

["dirPrefix", { dirPrefix: "../pair-", fileName: "qr.png" }],

98+

["fileName", { dirPrefix: "pair-", fileName: "../qr.png" }],

99+

])("rejects pathful QR temp %s values", async (name, opts) => {

100+

await expect(

101+

writeQrPngTempFile("openclaw", {

102+

tmpRoot,

103+

dirPrefix: opts.dirPrefix,

104+

fileName: opts.fileName,

105+

}),

106+

).rejects.toThrow(`${name} must be a non-empty filename segment.`);

107+

expect(renderPngBase64).not.toHaveBeenCalled();

108+

});

53109

});

Original file line numberDiff line numberDiff line change

@@ -1,3 +1,5 @@

1+

import { mkdtemp, rm, writeFile } from "node:fs/promises";

2+

import path from "node:path";

13

import { loadQrCodeTuiRuntime } from "./qr-runtime.ts";

24
35

const DEFAULT_QR_PNG_SCALE = 6;

@@ -6,6 +8,24 @@ const MIN_QR_PNG_SCALE = 1;

68

const MAX_QR_PNG_SCALE = 12;

79

const MIN_QR_PNG_MARGIN_MODULES = 0;

810

const MAX_QR_PNG_MARGIN_MODULES = 16;

11+

const QR_PNG_DATA_URL_PREFIX = "data:image/png;base64,";

12+
13+

export type QrPngRenderOptions = {

14+

scale?: number;

15+

marginModules?: number;

16+

};

17+
18+

export type QrPngTempFileOptions = QrPngRenderOptions & {

19+

tmpRoot: string;

20+

dirPrefix: string;

21+

fileName?: string;

22+

};

23+
24+

export type QrPngTempFile = {

25+

filePath: string;

26+

dirPath: string;

27+

mediaLocalRoots: string[];

28+

};

929
1030

function resolveQrPngIntegerOption(params: {

1131

name: string;

@@ -27,9 +47,16 @@ function resolveQrPngIntegerOption(params: {

2747

return value;

2848

}

2949
50+

function resolveQrTempPathSegment(name: string, value: string): string {

51+

if (!value || value === "." || value === ".." || path.basename(value) !== value) {

52+

throw new RangeError(`${name} must be a non-empty filename segment.`);

53+

}

54+

return value;

55+

}

56+
3057

export async function renderQrPngBase64(

3158

input: string,

32-

opts: { scale?: number; marginModules?: number } = {},

59+

opts: QrPngRenderOptions = {},

3360

): Promise<string> {

3461

const scale = resolveQrPngIntegerOption({

3562

name: "scale",

@@ -51,3 +78,36 @@ export async function renderQrPngBase64(

5178

scale,

5279

});

5380

}

81+
82+

export function formatQrPngDataUrl(base64: string): string {

83+

return `${QR_PNG_DATA_URL_PREFIX}${base64}`;

84+

}

85+
86+

export async function renderQrPngDataUrl(

87+

input: string,

88+

opts: QrPngRenderOptions = {},

89+

): Promise<string> {

90+

return formatQrPngDataUrl(await renderQrPngBase64(input, opts));

91+

}

92+
93+

export async function writeQrPngTempFile(

94+

input: string,

95+

opts: QrPngTempFileOptions,

96+

): Promise<QrPngTempFile> {

97+

const dirPrefix = resolveQrTempPathSegment("dirPrefix", opts.dirPrefix);

98+

const fileName = resolveQrTempPathSegment("fileName", opts.fileName ?? "qr.png");

99+

const pngBase64 = await renderQrPngBase64(input, opts);

100+

const dirPath = await mkdtemp(path.join(opts.tmpRoot, dirPrefix));

101+

const filePath = path.join(dirPath, fileName);

102+

try {

103+

await writeFile(filePath, Buffer.from(pngBase64, "base64"));

104+

} catch (err) {

105+

await rm(dirPath, { recursive: true, force: true }).catch(() => {});

106+

throw err;

107+

}

108+

return {

109+

filePath,

110+

dirPath,

111+

mediaLocalRoots: [dirPath],

112+

};

113+

}