@pao-at-office/reports-web 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE.md ADDED
@@ -0,0 +1,22 @@
1
+ # Reports.Web License / 使用許諾
2
+
3
+ Copyright (c) Pao@Office. All rights reserved.
4
+
5
+ This package is part of **Reports.Web**, a commercial product of Pao@Office.
6
+ Use of this package is governed by the Reports.Web End User License Agreement:
7
+
8
+ - 使用許諾(正式な条件): https://www.pao.ac/reports.web/manual/index.html#16
9
+ - 製品サイト: https://www.pao.ac/reports.web/
10
+ - ご購入・お見積もり: https://www.pao.ac/reports.web/buy.html
11
+
12
+ ## 要点 / Summary
13
+
14
+ - **体験版 / Trial** — 出力される帳票には赤い「SAMPLE」の印が付きます。購入前の評価に、無償でお使いいただけます。
15
+ Output carries a red "SAMPLE" mark. You may evaluate it free of charge before purchase.
16
+ - **製品版 / Product** — ご購入時に納品するライセンスファイルを Reports.Web エンジンに設定すると、「SAMPLE」の印が消えます。
17
+ Configure the license file delivered on purchase in the Reports.Web engine to remove the mark.
18
+ - **ライセンスの数え方 / Licensing** — 開発用パソコン 1 台につき 1 開発ライセンスです。運用専用のサーバーやエンドユーザーのパソコンには不要です(ランタイムライセンスフリー)。
19
+ One development license per development PC. Production servers and end-user PCs need no license (royalty-free runtime).
20
+
21
+ 上記の要点と使用許諾が異なる場合は、使用許諾が優先します。
22
+ If this summary and the license agreement differ, the license agreement prevails.
package/README.md ADDED
@@ -0,0 +1,92 @@
1
+ # @pao-at-office/reports-web
2
+
3
+ **Reports.Web for Node.js** — 帳票定義(`.prepdj`)に値を入れて印刷データ(PREPEJ)を作り、Reports.Web エンジン(C++ WebAssembly)で PDF にします。請求書・見積書・納品書・宛名ラベル・名刺など、日本の業務帳票向けです。
4
+
5
+ Build print data (PREPEJ) from a report definition (`.prepdj`) and render it to PDF with the Reports.Web engine (C++ WebAssembly). Designed for Japanese business forms: invoices, estimates, delivery slips, address labels, business cards.
6
+
7
+ - 製品サイト / Product: https://www.pao.ac/reports.web/
8
+ - デモのソース / Demo source: https://github.com/ReportsWeb/wasm-node
9
+ - オンラインデモ / Live demo: https://www.pao.ac/demo/reports.web/samples/node/
10
+
11
+ ## しくみ / How it works
12
+
13
+ ```
14
+ your Node.js app ──(PREPEJ JSON)──▶ Reports.Web engine (Docker: ghcr.io/reportsweb/engine) ──▶ PDF
15
+ ▲
16
+ report definition (.prepdj) designed in the browser designer
17
+ ```
18
+
19
+ 帳票のデザインは、ブラウザで動くデザイナーで作ります。アプリは値を入れて印刷データを作り、エンジンに送るだけです。描画はすべてエンジンが行います。
20
+
21
+ ## インストール / Install
22
+
23
+ ```sh
24
+ npm install @pao-at-office/reports-web
25
+ docker run -d -p 3107:3107 ghcr.io/reportsweb/engine:1.0.0
26
+ ```
27
+
28
+ Node.js 18 以降。エンジンは Docker イメージで動きます。
29
+ Requires Node.js 18+. The engine runs as a Docker image.
30
+
31
+ ## 使い方 / Quick start
32
+
33
+ ```js
34
+ import { readFile, writeFile } from "node:fs/promises";
35
+ import { PrintData, ReportsWebEngine } from "@pao-at-office/reports-web";
36
+
37
+ const definition = JSON.parse(await readFile("report.prepdj", "utf8"));
38
+
39
+ const printData = new PrintData()
40
+ .setDefinition(definition)
41
+ .pageStart()
42
+ .setValue("Message", "Node.jsから、あっという間に帳票出力")
43
+ .pageEnd();
44
+
45
+ const engine = new ReportsWebEngine({ url: "http://127.0.0.1:3107" });
46
+ await writeFile("report.pdf", await engine.renderPdf(printData));
47
+ ```
48
+
49
+ ## API
50
+
51
+ ### `PrintData`
52
+
53
+ | メソッド / Method | 内容 / Description |
54
+ |---|---|
55
+ | `setDefinition(definition)` | 帳票定義(`.prepdj` の内容)を設定 / Set the report definition |
56
+ | `pageStart(definition?)` / `pageEnd()` | ページの開始と終了。ページごとに別の定義も使えます / Begin and end a page (optionally with its own definition) |
57
+ | `setValue(name, value, index?, drawing?)` | 文字などの値を入れる / Set a value |
58
+ | `setRepeatedValue(name, value, x, y)` | 繰り返し(明細行など)の値 / Value for a repeated object |
59
+ | `setImage(name, source)` / `setBarcode(name, code)` | 画像・バーコード / Image and barcode |
60
+ | `changeAttributes(name, values)` | 色・位置などの属性を変える / Change attributes |
61
+ | `toObject()` / `toJson()` / `save(path)` | 印刷データ(PREPEJ)として取り出す・保存する / Get or save the PREPEJ |
62
+
63
+ ### `ReportsWebEngine`
64
+
65
+ | メソッド / Method | 内容 / Description |
66
+ |---|---|
67
+ | `new ReportsWebEngine({ url, timeoutMs, maxBytes })` | 既定の URL は `REPORTS_ENGINE_URL`、なければ `http://127.0.0.1:3107` |
68
+ | `renderPdf(printData)` | PDF の `Buffer` を返します / Returns the PDF as a `Buffer` |
69
+ | `health()` | エンジンの状態 / Engine status |
70
+
71
+ エラーは `ReportsWebEngineError`(`status` に HTTP ステータス)で返ります。
72
+ Errors are thrown as `ReportsWebEngineError` with the HTTP `status`.
73
+
74
+ ## 体験版と製品版 / Trial and product
75
+
76
+ このパッケージとエンジンのイメージは体験版です。出力には赤い「SAMPLE」の印が付きます。ご購入後に納品するライセンスファイルをエンジンに設定すると、印が消えます。
77
+
78
+ The package and the engine image are trial builds: output carries a red "SAMPLE" mark. Mount the license file delivered on purchase to remove it:
79
+
80
+ ```sh
81
+ docker run -d -p 3107:3107 -v /path/to/reports-web.license:/app/reports-web.license:ro ghcr.io/reportsweb/engine:1.0.0
82
+ ```
83
+
84
+ 開発用パソコン 1 台につき 1 ライセンス、運用環境はランタイムライセンスフリーです。詳しくは [LICENSE.md](LICENSE.md) と [使用許諾](https://www.pao.ac/reports.web/manual/index.html#16) をご覧ください。
85
+
86
+ ## 他の言語 / Other languages
87
+
88
+ Reports.Web は同じ帳票定義と印刷データを、PHP・Java・.NET・Go・Ruby・Rust・Node.js から使えます。Pure Java・Pure Python・WPF 版もあります。
89
+ https://github.com/ReportsWeb
90
+
91
+ ---
92
+ Pao@Office — https://www.pao.ac/ — info@pao.ac
@@ -0,0 +1,25 @@
1
+ export type JsonObject = Record<string, any>;
2
+ export type Scalar = string | number | boolean | null;
3
+ export declare class PrintData {
4
+ private definition;
5
+ private pages;
6
+ private page;
7
+ static assertDefinition(d: JsonObject): void;
8
+ setDefinition(d: JsonObject): this;
9
+ pageStart(d?: JsonObject | null): this;
10
+ private current;
11
+ private value;
12
+ setValue(n: string, v: Scalar, i?: number, drawing?: boolean): this;
13
+ setRepeatedValue(n: string, v: Scalar, x: number, y: number, drawing?: boolean): this;
14
+ setTypedValue(n: string, type: string, v: Scalar, i?: number, drawing?: boolean): this;
15
+ setImage(n: string, source: string, i?: number, drawing?: boolean): this;
16
+ setBarcode(n: string, code: string, i?: number, drawing?: boolean): this;
17
+ drawObject(n: string, i?: number, type?: string | null): this;
18
+ changeAttributes(n: string, values: Record<string, Scalar>, i?: number): this;
19
+ changeRepeatedAttributes(n: string, values: Record<string, Scalar>, i?: number, x?: number, y?: number, type?: string | null): this;
20
+ private resolveType;
21
+ pageEnd(): this;
22
+ toObject(): JsonObject;
23
+ toJson(pretty?: boolean): string;
24
+ save(path: string): Promise<void>;
25
+ }
@@ -0,0 +1,172 @@
1
+ import { writeFile, rename, unlink } from "node:fs/promises";
2
+ import { randomUUID } from "node:crypto";
3
+ const copy = (v) => structuredClone(v);
4
+ const name = (v) => {
5
+ if (typeof v !== "string" || !v.trim())
6
+ throw new Error("Name is required");
7
+ return v.trim();
8
+ };
9
+ const index = (v) => {
10
+ if (!Number.isSafeInteger(v) || v < 0)
11
+ throw new Error("Index must be a non-negative integer");
12
+ return v;
13
+ };
14
+ const scalar = (v) => {
15
+ if (v === null)
16
+ return null;
17
+ if (!["string", "number", "boolean"].includes(typeof v) ||
18
+ (typeof v === "number" && !Number.isFinite(v)))
19
+ throw new Error("A finite scalar is required");
20
+ return String(v);
21
+ };
22
+ export class PrintData {
23
+ definition = null;
24
+ pages = [];
25
+ page = null;
26
+ static assertDefinition(d) {
27
+ if (!d ||
28
+ typeof d !== "object" ||
29
+ !((d.Version !== undefined &&
30
+ Array.isArray(d.Objects) &&
31
+ ["mm", "px"].includes(String(d.CoordinateUnit ?? "mm").toLowerCase())) ||
32
+ (d.format === "pao-reports-web" &&
33
+ d.version === 1 &&
34
+ Array.isArray(d.pages) &&
35
+ d.pages.length)))
36
+ throw new Error("Invalid report definition");
37
+ }
38
+ setDefinition(d) {
39
+ PrintData.assertDefinition(d);
40
+ if (this.page)
41
+ throw new Error("Finish the current page first");
42
+ if (this.definition)
43
+ for (const p of this.pages)
44
+ if (!p.Definition)
45
+ p.Definition = copy(this.definition);
46
+ this.definition = copy(d);
47
+ return this;
48
+ }
49
+ pageStart(d = null) {
50
+ if (this.page)
51
+ throw new Error("Call pageEnd first");
52
+ if (d)
53
+ PrintData.assertDefinition(d);
54
+ if (!this.definition)
55
+ throw new Error("Set definition first");
56
+ this.page = {
57
+ Index: this.pages.length + 1,
58
+ Definition: copy(d),
59
+ Values: [],
60
+ DynamicAttributes: [],
61
+ };
62
+ return this;
63
+ }
64
+ current() {
65
+ if (!this.page)
66
+ throw new Error("Call pageStart first");
67
+ return this.page;
68
+ }
69
+ value(n, v, i, drawing, type, x, y) {
70
+ const item = {
71
+ Name: name(n),
72
+ Type: this.resolveType(n, type),
73
+ Index: index(i),
74
+ Drawing: drawing,
75
+ Value: scalar(v),
76
+ };
77
+ if (x !== undefined && y !== undefined) {
78
+ item.IndexX = index(x);
79
+ item.IndexY = index(y);
80
+ }
81
+ this.current().Values.push(item);
82
+ return this;
83
+ }
84
+ setValue(n, v, i = 0, drawing = true) {
85
+ return this.value(n, v, i, drawing, null);
86
+ }
87
+ setRepeatedValue(n, v, x, y, drawing = true) {
88
+ return this.value(n, v, 0, drawing, null, x, y);
89
+ }
90
+ setTypedValue(n, type, v, i = 0, drawing = true) {
91
+ return this.value(n, v, i, drawing, type);
92
+ }
93
+ setImage(n, source, i = 0, drawing = true) {
94
+ return this.setTypedValue(n, "DynamicImage", source, i, drawing);
95
+ }
96
+ setBarcode(n, code, i = 0, drawing = true) {
97
+ return this.setTypedValue(n, "DynamicBarcode", code, i, drawing);
98
+ }
99
+ drawObject(n, i = 0, type = null) {
100
+ return this.value(n, null, i, true, type);
101
+ }
102
+ changeAttributes(n, values, i = 0) {
103
+ return this.changeRepeatedAttributes(n, values, i);
104
+ }
105
+ changeRepeatedAttributes(n, values, i = 0, x, y, type = null) {
106
+ if ((x === undefined) !== (y === undefined))
107
+ throw new Error("Both repeat indexes required");
108
+ const item = {
109
+ Name: name(n),
110
+ Type: this.resolveType(n, type),
111
+ Index: index(i),
112
+ Values: {},
113
+ };
114
+ for (const [k, v] of Object.entries(values)) {
115
+ if (v === null)
116
+ throw new Error("Attributes cannot be null");
117
+ item.Values[k] = scalar(v);
118
+ }
119
+ if (x !== undefined && y !== undefined) {
120
+ item.IndexX = index(x);
121
+ item.IndexY = index(y);
122
+ }
123
+ this.current().DynamicAttributes.push(item);
124
+ return this;
125
+ }
126
+ // 型省略時は当該ページの定義を参照する。明示指定はそのまま保持する。
127
+ resolveType(n, explicit) {
128
+ if (explicit !== null)
129
+ return name(explicit);
130
+ const d = this.current().Definition ?? this.definition;
131
+ const objects = [...(d.Objects ?? []), ...(d.pages ?? []).flatMap((p) => p.objects ?? [])];
132
+ const kinds = ["Text", "Line", "Square", "Circle", "Image", "Barcode"];
133
+ const web = { text: "Text", line: "Line", rectangle: "Square", ellipse: "Circle", image: "Image", barcode: "Barcode" };
134
+ for (const o of objects) {
135
+ if ((o.Name ?? o.name) !== name(n))
136
+ continue;
137
+ if (/^[0-5]$/.test(String(o.Kind)))
138
+ return "Dynamic" + kinds[Number(o.Kind)];
139
+ if (web[o.kind])
140
+ return "Dynamic" + web[o.kind];
141
+ }
142
+ return "DynamicText";
143
+ }
144
+ pageEnd() {
145
+ this.pages.push(this.current());
146
+ this.page = null;
147
+ return this;
148
+ }
149
+ toObject() {
150
+ if (this.page || !this.definition || !this.pages.length)
151
+ throw new Error("Definition and completed pages required");
152
+ return copy({
153
+ Format: "Reports.net PrintData",
154
+ Version: "1.0",
155
+ Definition: this.definition,
156
+ Pages: this.pages,
157
+ });
158
+ }
159
+ toJson(pretty = true) {
160
+ return JSON.stringify(this.toObject(), null, pretty ? 2 : undefined) + "\n";
161
+ }
162
+ async save(path) {
163
+ const temp = path + "." + randomUUID() + ".tmp";
164
+ try {
165
+ await writeFile(temp, this.toJson(), { flag: "wx" });
166
+ await rename(temp, path);
167
+ }
168
+ finally {
169
+ await unlink(temp).catch(() => { });
170
+ }
171
+ }
172
+ }
@@ -0,0 +1,36 @@
1
+ import { PrintData, type JsonObject } from "./PrintData.js";
2
+ export interface ReportsWebEngineOptions {
3
+ /** Engine base URL. Default: REPORTS_ENGINE_URL or http://127.0.0.1:3107 */
4
+ url?: string;
5
+ /** Request timeout in milliseconds. Default: 90000 */
6
+ timeoutMs?: number;
7
+ /** Largest PDF accepted from the engine in bytes. Default: 32 MiB */
8
+ maxBytes?: number;
9
+ }
10
+ export interface RenderPdfOptions {
11
+ /** Spill large PDF images to temporary storage on the engine (X-Reports-Swap-Pdf-Image). */
12
+ swapPdfImage?: boolean;
13
+ }
14
+ /** Error returned by the Reports.Web engine (status is the HTTP status, or undefined for transport errors). */
15
+ export declare class ReportsWebEngineError extends Error {
16
+ readonly status?: number | undefined;
17
+ constructor(message: string, status?: number | undefined);
18
+ }
19
+ /**
20
+ * Client for the Reports.Web engine (ghcr.io/reportsweb/engine).
21
+ * Sends PREPEJ print data to POST /render/pdf and returns the PDF bytes.
22
+ */
23
+ export declare class ReportsWebEngine {
24
+ readonly url: string;
25
+ private readonly timeoutMs;
26
+ private readonly maxBytes;
27
+ constructor(options?: ReportsWebEngineOptions);
28
+ /** GET /health. Resolves to the engine status, e.g. { status: "ok", engine: "C++ WebAssembly" }. */
29
+ health(): Promise<{
30
+ status: string;
31
+ engine?: string;
32
+ }>;
33
+ /** Render PREPEJ print data (PrintData, its object form, or JSON text) to a PDF. */
34
+ renderPdf(data: PrintData | JsonObject | string, options?: RenderPdfOptions): Promise<Buffer>;
35
+ private request;
36
+ }
@@ -0,0 +1,74 @@
1
+ import { PrintData } from "./PrintData.js";
2
+ /** Error returned by the Reports.Web engine (status is the HTTP status, or undefined for transport errors). */
3
+ export class ReportsWebEngineError extends Error {
4
+ status;
5
+ constructor(message, status) {
6
+ super(message);
7
+ this.status = status;
8
+ this.name = "ReportsWebEngineError";
9
+ }
10
+ }
11
+ const DEFAULT_MAX = 32 * 1024 * 1024;
12
+ /**
13
+ * Client for the Reports.Web engine (ghcr.io/reportsweb/engine).
14
+ * Sends PREPEJ print data to POST /render/pdf and returns the PDF bytes.
15
+ */
16
+ export class ReportsWebEngine {
17
+ url;
18
+ timeoutMs;
19
+ maxBytes;
20
+ constructor(options = {}) {
21
+ const url = options.url ?? process.env.REPORTS_ENGINE_URL ?? "http://127.0.0.1:3107";
22
+ this.url = url.replace(/\/+$/, "");
23
+ this.timeoutMs = options.timeoutMs ?? 90000;
24
+ this.maxBytes = options.maxBytes ?? DEFAULT_MAX;
25
+ }
26
+ /** GET /health. Resolves to the engine status, e.g. { status: "ok", engine: "C++ WebAssembly" }. */
27
+ async health() {
28
+ const response = await this.request("/health", { method: "GET" });
29
+ if (!response.ok)
30
+ throw new ReportsWebEngineError(`Engine health check failed (HTTP ${response.status}).`, response.status);
31
+ return (await response.json());
32
+ }
33
+ /** Render PREPEJ print data (PrintData, its object form, or JSON text) to a PDF. */
34
+ async renderPdf(data, options = {}) {
35
+ const payload = typeof data === "string" ? data : JSON.stringify(data instanceof PrintData ? data.toObject() : data);
36
+ if (Buffer.byteLength(payload) > DEFAULT_MAX)
37
+ throw new ReportsWebEngineError("Print data exceeds 32 MiB.");
38
+ const headers = { "Content-Type": "application/json" };
39
+ if (options.swapPdfImage !== undefined)
40
+ headers["X-Reports-Swap-Pdf-Image"] = String(options.swapPdfImage);
41
+ const response = await this.request("/render/pdf", { method: "POST", headers, body: payload });
42
+ if (!response.ok || !response.body) {
43
+ let detail = "";
44
+ try {
45
+ const text = await response.text();
46
+ detail = JSON.parse(text).error ?? text;
47
+ }
48
+ catch {
49
+ /* keep the status only */
50
+ }
51
+ throw new ReportsWebEngineError(`Engine could not create the PDF (HTTP ${response.status})${detail ? ": " + detail : "."}`, response.status);
52
+ }
53
+ const chunks = [];
54
+ let size = 0;
55
+ for await (const part of response.body) {
56
+ size += part.length;
57
+ if (size > this.maxBytes)
58
+ throw new ReportsWebEngineError(`PDF exceeds ${this.maxBytes} bytes.`);
59
+ chunks.push(Buffer.from(part));
60
+ }
61
+ const pdf = Buffer.concat(chunks);
62
+ if (pdf.subarray(0, 5).toString("latin1") !== "%PDF-")
63
+ throw new ReportsWebEngineError("Engine response is not a PDF.");
64
+ return pdf;
65
+ }
66
+ async request(path, init) {
67
+ try {
68
+ return await fetch(this.url + path, { ...init, redirect: "error", signal: AbortSignal.timeout(this.timeoutMs) });
69
+ }
70
+ catch (error) {
71
+ throw new ReportsWebEngineError(`Cannot reach the Reports.Web engine at ${this.url}: ${error.message}`);
72
+ }
73
+ }
74
+ }
@@ -0,0 +1,2 @@
1
+ export { PrintData, type JsonObject, type Scalar } from "./PrintData.js";
2
+ export { ReportsWebEngine, ReportsWebEngineError, type ReportsWebEngineOptions, type RenderPdfOptions, } from "./ReportsWebEngine.js";
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { PrintData } from "./PrintData.js";
2
+ export { ReportsWebEngine, ReportsWebEngineError, } from "./ReportsWebEngine.js";
package/package.json ADDED
@@ -0,0 +1,57 @@
1
+ {
2
+ "name": "@pao-at-office/reports-web",
3
+ "version": "1.0.0",
4
+ "description": "Reports.Web for Node.js: build PREPEJ print data from report definitions (.prepdj) and render PDF with the Reports.Web engine (C++ WebAssembly). Japanese business forms such as invoices, estimates and labels.",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js"
12
+ }
13
+ },
14
+ "files": [
15
+ "dist/*.js",
16
+ "dist/*.d.ts",
17
+ "README.md",
18
+ "LICENSE.md"
19
+ ],
20
+ "engines": {
21
+ "node": ">=18"
22
+ },
23
+ "scripts": {
24
+ "build": "tsc",
25
+ "test": "npm run build && node --test test/engine.test.mjs"
26
+ },
27
+ "keywords": [
28
+ "reports",
29
+ "report",
30
+ "pdf",
31
+ "pdf-generation",
32
+ "report-designer",
33
+ "invoice",
34
+ "estimate",
35
+ "label",
36
+ "business-forms",
37
+ "webassembly",
38
+ "wasm",
39
+ "prepej",
40
+ "prepdj",
41
+ "japanese",
42
+ "帳票",
43
+ "Reports.Web",
44
+ "Reports.net"
45
+ ],
46
+ "homepage": "https://www.pao.ac/reports.web/",
47
+ "bugs": {
48
+ "url": "https://www.pao.ac/reports.web/",
49
+ "email": "info@pao.ac"
50
+ },
51
+ "author": "Pao@Office <info@pao.ac> (https://www.pao.ac/)",
52
+ "license": "SEE LICENSE IN LICENSE.md",
53
+ "devDependencies": {
54
+ "@types/node": "22.18.0",
55
+ "typescript": "5.9.2"
56
+ }
57
+ }