@x12i/reportic-api 0.0.0-stage → 0.2.2

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/dist/server.js ADDED
@@ -0,0 +1,1037 @@
1
+ #!/usr/bin/env node
2
+
3
+ // packages/reportic-api/openapi.json
4
+ var openapi_default = {
5
+ openapi: "3.1.0",
6
+ info: {
7
+ title: "Reportic API",
8
+ version: "0.2.2",
9
+ description: "Shared Reportic engine for template discovery, validation, previews, report generation, and private local jobs. Bearer authentication is required when a token is configured; remote binds require a token."
10
+ },
11
+ servers: [
12
+ {
13
+ url: "http://127.0.0.1:4173"
14
+ }
15
+ ],
16
+ security: [
17
+ {
18
+ bearerAuth: []
19
+ }
20
+ ],
21
+ paths: {
22
+ "/v1/components": {
23
+ get: {
24
+ summary: "List component schemas and target capabilities",
25
+ responses: {
26
+ "200": {
27
+ description: "Success",
28
+ content: {
29
+ "application/json": {
30
+ schema: {
31
+ type: "object"
32
+ }
33
+ }
34
+ }
35
+ },
36
+ "401": {
37
+ description: "Bearer authentication is required."
38
+ },
39
+ "422": {
40
+ description: "Invalid inputs or rendering failure.",
41
+ content: {
42
+ "application/json": {
43
+ schema: {
44
+ $ref: "#/components/schemas/Failure"
45
+ }
46
+ }
47
+ }
48
+ }
49
+ }
50
+ }
51
+ },
52
+ "/v1/components/{type}": {
53
+ get: {
54
+ summary: "Get one component definition",
55
+ parameters: [
56
+ {
57
+ name: "type",
58
+ in: "path",
59
+ required: true,
60
+ schema: {
61
+ type: "string"
62
+ }
63
+ }
64
+ ],
65
+ responses: {
66
+ "200": {
67
+ description: "Success",
68
+ content: {
69
+ "application/json": {
70
+ schema: {
71
+ type: "object"
72
+ }
73
+ }
74
+ }
75
+ },
76
+ "401": {
77
+ description: "Bearer authentication is required."
78
+ },
79
+ "422": {
80
+ description: "Invalid inputs or rendering failure.",
81
+ content: {
82
+ "application/json": {
83
+ schema: {
84
+ $ref: "#/components/schemas/Failure"
85
+ }
86
+ }
87
+ }
88
+ }
89
+ }
90
+ }
91
+ },
92
+ "/v1/templates/inspect": {
93
+ post: {
94
+ summary: "Inspect a template",
95
+ requestBody: {
96
+ required: true,
97
+ content: {
98
+ "application/json": {
99
+ schema: {
100
+ $ref: "#/components/schemas/ReportRequest"
101
+ }
102
+ }
103
+ }
104
+ },
105
+ responses: {
106
+ "200": {
107
+ description: "Success",
108
+ content: {
109
+ "application/json": {
110
+ schema: {
111
+ type: "object"
112
+ }
113
+ }
114
+ }
115
+ },
116
+ "401": {
117
+ description: "Bearer authentication is required."
118
+ },
119
+ "422": {
120
+ description: "Invalid inputs or rendering failure.",
121
+ content: {
122
+ "application/json": {
123
+ schema: {
124
+ $ref: "#/components/schemas/Failure"
125
+ }
126
+ }
127
+ }
128
+ }
129
+ }
130
+ }
131
+ },
132
+ "/v1/templates/validate": {
133
+ post: {
134
+ summary: "Validate template authoring syntax",
135
+ requestBody: {
136
+ required: true,
137
+ content: {
138
+ "application/json": {
139
+ schema: {
140
+ $ref: "#/components/schemas/ReportRequest"
141
+ }
142
+ }
143
+ }
144
+ },
145
+ responses: {
146
+ "200": {
147
+ description: "Success",
148
+ content: {
149
+ "application/json": {
150
+ schema: {
151
+ $ref: "#/components/schemas/Validation"
152
+ }
153
+ }
154
+ }
155
+ },
156
+ "401": {
157
+ description: "Bearer authentication is required."
158
+ },
159
+ "422": {
160
+ description: "Invalid inputs or rendering failure.",
161
+ content: {
162
+ "application/json": {
163
+ schema: {
164
+ $ref: "#/components/schemas/Failure"
165
+ }
166
+ }
167
+ }
168
+ }
169
+ }
170
+ }
171
+ },
172
+ "/v1/reports/validate": {
173
+ post: {
174
+ summary: "Validate a report without creating an artifact",
175
+ requestBody: {
176
+ required: true,
177
+ content: {
178
+ "application/json": {
179
+ schema: {
180
+ $ref: "#/components/schemas/ReportRequest"
181
+ }
182
+ }
183
+ }
184
+ },
185
+ responses: {
186
+ "200": {
187
+ description: "Success",
188
+ content: {
189
+ "application/json": {
190
+ schema: {
191
+ $ref: "#/components/schemas/Validation"
192
+ }
193
+ }
194
+ }
195
+ },
196
+ "401": {
197
+ description: "Bearer authentication is required."
198
+ },
199
+ "422": {
200
+ description: "Invalid inputs or rendering failure.",
201
+ content: {
202
+ "application/json": {
203
+ schema: {
204
+ $ref: "#/components/schemas/Failure"
205
+ }
206
+ }
207
+ }
208
+ }
209
+ }
210
+ }
211
+ },
212
+ "/v1/reports/preview": {
213
+ post: {
214
+ summary: "Create a self-contained HTML preview",
215
+ requestBody: {
216
+ required: true,
217
+ content: {
218
+ "application/json": {
219
+ schema: {
220
+ $ref: "#/components/schemas/ReportRequest"
221
+ }
222
+ }
223
+ }
224
+ },
225
+ responses: {
226
+ "200": {
227
+ description: "Success",
228
+ content: {
229
+ "application/json": {
230
+ schema: {
231
+ type: "object"
232
+ }
233
+ }
234
+ }
235
+ },
236
+ "401": {
237
+ description: "Bearer authentication is required."
238
+ },
239
+ "422": {
240
+ description: "Invalid inputs or rendering failure.",
241
+ content: {
242
+ "application/json": {
243
+ schema: {
244
+ $ref: "#/components/schemas/Failure"
245
+ }
246
+ }
247
+ }
248
+ }
249
+ }
250
+ }
251
+ },
252
+ "/v1/reports/generate": {
253
+ post: {
254
+ summary: "Generate a report; PDF is the default",
255
+ requestBody: {
256
+ required: true,
257
+ content: {
258
+ "application/json": {
259
+ schema: {
260
+ $ref: "#/components/schemas/ReportRequest"
261
+ }
262
+ }
263
+ }
264
+ },
265
+ responses: {
266
+ "200": {
267
+ description: "Verified report bytes or ZIP bundle.",
268
+ content: {
269
+ "application/octet-stream": {
270
+ schema: {
271
+ type: "string",
272
+ format: "binary"
273
+ }
274
+ },
275
+ "application/pdf": {
276
+ schema: {
277
+ type: "string",
278
+ format: "binary"
279
+ }
280
+ }
281
+ }
282
+ },
283
+ "406": {
284
+ description: "Accept mismatch or companion assets require the bundle endpoint."
285
+ },
286
+ "422": {
287
+ description: "Report failed.",
288
+ content: {
289
+ "application/json": {
290
+ schema: {
291
+ $ref: "#/components/schemas/Failure"
292
+ }
293
+ }
294
+ }
295
+ }
296
+ }
297
+ }
298
+ },
299
+ "/v1/report-jobs": {
300
+ post: {
301
+ summary: "Submit a private background report job",
302
+ requestBody: {
303
+ required: true,
304
+ content: {
305
+ "application/json": {
306
+ schema: {
307
+ $ref: "#/components/schemas/ReportRequest"
308
+ }
309
+ }
310
+ }
311
+ },
312
+ responses: {
313
+ "202": {
314
+ description: "Success",
315
+ content: {
316
+ "application/json": {
317
+ schema: {
318
+ $ref: "#/components/schemas/Job"
319
+ }
320
+ }
321
+ }
322
+ },
323
+ "401": {
324
+ description: "Bearer authentication is required."
325
+ },
326
+ "409": {
327
+ description: "Idempotency key reused with different inputs."
328
+ },
329
+ "422": {
330
+ description: "Invalid inputs or rendering failure.",
331
+ content: {
332
+ "application/json": {
333
+ schema: {
334
+ $ref: "#/components/schemas/Failure"
335
+ }
336
+ }
337
+ }
338
+ }
339
+ },
340
+ parameters: [
341
+ {
342
+ in: "header",
343
+ name: "Idempotency-Key",
344
+ schema: {
345
+ type: "string"
346
+ }
347
+ }
348
+ ]
349
+ }
350
+ },
351
+ "/v1/report-jobs/{id}": {
352
+ get: {
353
+ summary: "Read job state and artifact metadata",
354
+ parameters: [
355
+ {
356
+ name: "id",
357
+ in: "path",
358
+ required: true,
359
+ schema: {
360
+ type: "string",
361
+ format: "uuid"
362
+ }
363
+ }
364
+ ],
365
+ responses: {
366
+ "200": {
367
+ description: "Success",
368
+ content: {
369
+ "application/json": {
370
+ schema: {
371
+ $ref: "#/components/schemas/Job"
372
+ }
373
+ }
374
+ }
375
+ },
376
+ "401": {
377
+ description: "Bearer authentication is required."
378
+ },
379
+ "422": {
380
+ description: "Invalid inputs or rendering failure.",
381
+ content: {
382
+ "application/json": {
383
+ schema: {
384
+ $ref: "#/components/schemas/Failure"
385
+ }
386
+ }
387
+ }
388
+ }
389
+ }
390
+ },
391
+ delete: {
392
+ summary: "Cancel a pending or running job",
393
+ parameters: [
394
+ {
395
+ name: "id",
396
+ in: "path",
397
+ required: true,
398
+ schema: {
399
+ type: "string",
400
+ format: "uuid"
401
+ }
402
+ }
403
+ ],
404
+ responses: {
405
+ "200": {
406
+ description: "Success",
407
+ content: {
408
+ "application/json": {
409
+ schema: {
410
+ $ref: "#/components/schemas/Job"
411
+ }
412
+ }
413
+ }
414
+ },
415
+ "401": {
416
+ description: "Bearer authentication is required."
417
+ },
418
+ "422": {
419
+ description: "Invalid inputs or rendering failure.",
420
+ content: {
421
+ "application/json": {
422
+ schema: {
423
+ $ref: "#/components/schemas/Failure"
424
+ }
425
+ }
426
+ }
427
+ }
428
+ }
429
+ }
430
+ },
431
+ "/v1/report-jobs/{id}/artifact": {
432
+ get: {
433
+ summary: "Download a verified primary artifact",
434
+ parameters: [
435
+ {
436
+ name: "id",
437
+ in: "path",
438
+ required: true,
439
+ schema: {
440
+ type: "string",
441
+ format: "uuid"
442
+ }
443
+ }
444
+ ],
445
+ responses: {
446
+ "200": {
447
+ description: "Verified report bytes or ZIP bundle.",
448
+ content: {
449
+ "application/octet-stream": {
450
+ schema: {
451
+ type: "string",
452
+ format: "binary"
453
+ }
454
+ },
455
+ "application/pdf": {
456
+ schema: {
457
+ type: "string",
458
+ format: "binary"
459
+ }
460
+ }
461
+ }
462
+ },
463
+ "406": {
464
+ description: "Accept mismatch or companion assets require the bundle endpoint."
465
+ },
466
+ "422": {
467
+ description: "Report failed.",
468
+ content: {
469
+ "application/json": {
470
+ schema: {
471
+ $ref: "#/components/schemas/Failure"
472
+ }
473
+ }
474
+ }
475
+ }
476
+ }
477
+ }
478
+ },
479
+ "/v1/report-jobs/{id}/bundle": {
480
+ get: {
481
+ summary: "Download a ZIP including companion assets",
482
+ parameters: [
483
+ {
484
+ name: "id",
485
+ in: "path",
486
+ required: true,
487
+ schema: {
488
+ type: "string",
489
+ format: "uuid"
490
+ }
491
+ }
492
+ ],
493
+ responses: {
494
+ "200": {
495
+ description: "Verified report bytes or ZIP bundle.",
496
+ content: {
497
+ "application/octet-stream": {
498
+ schema: {
499
+ type: "string",
500
+ format: "binary"
501
+ }
502
+ },
503
+ "application/pdf": {
504
+ schema: {
505
+ type: "string",
506
+ format: "binary"
507
+ }
508
+ }
509
+ }
510
+ },
511
+ "406": {
512
+ description: "Accept mismatch or companion assets require the bundle endpoint."
513
+ },
514
+ "422": {
515
+ description: "Report failed.",
516
+ content: {
517
+ "application/json": {
518
+ schema: {
519
+ $ref: "#/components/schemas/Failure"
520
+ }
521
+ }
522
+ }
523
+ }
524
+ }
525
+ }
526
+ }
527
+ },
528
+ components: {
529
+ securitySchemes: {
530
+ bearerAuth: {
531
+ type: "http",
532
+ scheme: "bearer"
533
+ }
534
+ },
535
+ schemas: {
536
+ Diagnostic: {
537
+ type: "object",
538
+ required: [
539
+ "code",
540
+ "severity",
541
+ "phase",
542
+ "message"
543
+ ],
544
+ properties: {
545
+ code: {
546
+ type: "string"
547
+ },
548
+ severity: {
549
+ enum: [
550
+ "error",
551
+ "warning",
552
+ "info"
553
+ ]
554
+ },
555
+ phase: {
556
+ enum: [
557
+ "parse",
558
+ "input",
559
+ "prepare",
560
+ "render"
561
+ ]
562
+ },
563
+ message: {
564
+ type: "string"
565
+ },
566
+ elementId: {
567
+ type: "string"
568
+ },
569
+ bindingPath: {
570
+ type: "string"
571
+ },
572
+ line: {
573
+ type: "integer"
574
+ },
575
+ column: {
576
+ type: "integer"
577
+ },
578
+ format: {
579
+ type: "string"
580
+ }
581
+ }
582
+ },
583
+ Validation: {
584
+ type: "object",
585
+ required: [
586
+ "valid",
587
+ "diagnostics"
588
+ ],
589
+ properties: {
590
+ valid: {
591
+ type: "boolean"
592
+ },
593
+ diagnostics: {
594
+ type: "array",
595
+ items: {
596
+ $ref: "#/components/schemas/Diagnostic"
597
+ }
598
+ }
599
+ }
600
+ },
601
+ Failure: {
602
+ type: "object",
603
+ properties: {
604
+ error: {
605
+ type: "string"
606
+ },
607
+ diagnostics: {
608
+ type: "array",
609
+ items: {
610
+ $ref: "#/components/schemas/Diagnostic"
611
+ }
612
+ }
613
+ }
614
+ },
615
+ Job: {
616
+ type: "object",
617
+ properties: {
618
+ id: {
619
+ type: "string",
620
+ format: "uuid"
621
+ },
622
+ state: {
623
+ enum: [
624
+ "queued",
625
+ "running",
626
+ "succeeded",
627
+ "failed",
628
+ "cancelled",
629
+ "expired"
630
+ ]
631
+ },
632
+ createdAt: {
633
+ type: "string",
634
+ format: "date-time"
635
+ },
636
+ expiresAt: {
637
+ type: "string",
638
+ format: "date-time"
639
+ },
640
+ diagnostics: {
641
+ type: "array",
642
+ items: {
643
+ $ref: "#/components/schemas/Diagnostic"
644
+ }
645
+ },
646
+ artifact: {
647
+ type: "object",
648
+ properties: {
649
+ filename: {
650
+ type: "string"
651
+ },
652
+ mediaType: {
653
+ type: "string"
654
+ },
655
+ bytes: {
656
+ type: "integer"
657
+ },
658
+ url: {
659
+ type: "string"
660
+ },
661
+ bundleUrl: {
662
+ type: "string"
663
+ }
664
+ }
665
+ }
666
+ }
667
+ },
668
+ ReportRequest: {
669
+ type: "object",
670
+ required: [
671
+ "template"
672
+ ],
673
+ additionalProperties: false,
674
+ properties: {
675
+ template: {
676
+ type: "string",
677
+ maxLength: 1e6
678
+ },
679
+ dataSets: {
680
+ type: "array",
681
+ default: [],
682
+ items: {
683
+ type: "object",
684
+ required: [
685
+ "name",
686
+ "data"
687
+ ],
688
+ properties: {
689
+ name: {
690
+ type: "string",
691
+ pattern: "^[A-Za-z_][A-Za-z0-9_]*$"
692
+ },
693
+ data: {
694
+ type: "object"
695
+ }
696
+ }
697
+ }
698
+ },
699
+ variables: {
700
+ type: "object",
701
+ default: {}
702
+ },
703
+ format: {
704
+ enum: [
705
+ "pdf",
706
+ "pptx",
707
+ "docx",
708
+ "html",
709
+ "markdown"
710
+ ],
711
+ default: "pdf"
712
+ },
713
+ theme: {
714
+ type: "object"
715
+ },
716
+ css: {
717
+ type: "string"
718
+ },
719
+ assets: {
720
+ type: "object",
721
+ additionalProperties: {
722
+ type: "object",
723
+ required: [
724
+ "base64",
725
+ "mediaType"
726
+ ],
727
+ properties: {
728
+ base64: {
729
+ type: "string",
730
+ contentEncoding: "base64"
731
+ },
732
+ mediaType: {
733
+ enum: [
734
+ "image/png",
735
+ "image/jpeg",
736
+ "image/webp",
737
+ "image/svg+xml"
738
+ ]
739
+ }
740
+ }
741
+ }
742
+ },
743
+ html: {
744
+ type: "object",
745
+ properties: {
746
+ assetMode: {
747
+ enum: [
748
+ "embedded",
749
+ "bundled"
750
+ ]
751
+ }
752
+ }
753
+ },
754
+ pdf: {
755
+ type: "object",
756
+ properties: {
757
+ size: {
758
+ enum: [
759
+ "A4",
760
+ "Letter"
761
+ ]
762
+ },
763
+ landscape: {
764
+ type: "boolean"
765
+ },
766
+ pageNumbers: {
767
+ type: "boolean"
768
+ },
769
+ preferCSSPageSize: {
770
+ type: "boolean"
771
+ }
772
+ }
773
+ },
774
+ pptx: {
775
+ type: "object",
776
+ properties: {
777
+ editability: {
778
+ enum: [
779
+ "normal",
780
+ "strict"
781
+ ]
782
+ },
783
+ layout: {
784
+ enum: [
785
+ "wide",
786
+ "standard"
787
+ ]
788
+ }
789
+ }
790
+ },
791
+ docx: {
792
+ type: "object"
793
+ },
794
+ diagramMode: {
795
+ enum: [
796
+ "portable",
797
+ "mermaid"
798
+ ]
799
+ },
800
+ strictStyles: {
801
+ type: "boolean"
802
+ }
803
+ }
804
+ }
805
+ }
806
+ }
807
+ };
808
+
809
+ // packages/reportic-api/src/index.ts
810
+ import express2 from "express";
811
+ import { timingSafeEqual, randomUUID, createHash } from "crypto";
812
+ import { inspectTemplate, validateReport, validateTemplate, generateReport, listComponents, getComponent, ReporticError } from "@x12i/reportic";
813
+
814
+ // packages/reportic-api/src/dataset-routes.ts
815
+ import express from "express";
816
+ import { parseAuthoringYaml } from "@x12i/reportic-core/authoring";
817
+ import { importOpenApiOperations } from "@x12i/reportic-adapter-api";
818
+ import { checkJson, datasetError, DatasetError, DatasetExecutionError } from "@x12i/reportic-datasets";
819
+ import { CatalogError } from "@x12i/reportic-catalog";
820
+
821
+ // packages/reportic-api/src/index.ts
822
+ function createReporticRouter(config = {}) {
823
+ const router = express2.Router();
824
+ router.get("/openapi.json", (_req, res) => res.json(openapi_default));
825
+ const jobs = /* @__PURE__ */ new Map();
826
+ const idempotency = /* @__PURE__ */ new Map();
827
+ let active = 0;
828
+ router.use(express2.json({ limit: "12mb" }));
829
+ router.use((req, res, next) => {
830
+ if (config.token) {
831
+ const value = (req.headers.authorization ?? "").replace(/^Bearer /, "");
832
+ const a = Buffer.from(value), b = Buffer.from(config.token);
833
+ if (a.length !== b.length || !timingSafeEqual(a, b)) {
834
+ res.status(401).json({ error: "UNAUTHORIZED", message: "A valid bearer token is required." });
835
+ return;
836
+ }
837
+ }
838
+ req.owner = config.token ? "authenticated" : "local";
839
+ res.setHeader("Cache-Control", "no-store");
840
+ next();
841
+ });
842
+ function input(req) {
843
+ const b = req.body;
844
+ if (!b || typeof b.template !== "string" || b.dataSets !== void 0 && !Array.isArray(b.dataSets) || b.variables !== void 0 && (!b.variables || typeof b.variables !== "object" || Array.isArray(b.variables))) throw new ReporticError([{ code: "INVALID_REQUEST", severity: "error", phase: "input", message: "Provide template text, a dataSets array, and a variables object." }]);
845
+ const allowed = ["template", "dataSets", "variables", "format", "theme", "css", "assets", "html", "pdf", "pptx", "docx", "diagramMode", "strictStyles"];
846
+ for (const key of Object.keys(b)) if (!allowed.includes(key)) throw new ReporticError([{ code: "INVALID_REQUEST_OPTION", severity: "error", phase: "input", message: `Request option "${key}" is not accepted.` }]);
847
+ const assets = {};
848
+ if (b.assets) {
849
+ for (const [key, a] of Object.entries(b.assets)) {
850
+ if (typeof a.base64 !== "string" || typeof a.mediaType !== "string") throw new Error("Invalid asset payload.");
851
+ assets[key] = { bytes: Buffer.from(a.base64, "base64"), mediaType: a.mediaType };
852
+ }
853
+ }
854
+ const options = { ...config.trustedOptions, registry: config.registry ?? config.trustedOptions?.registry, format: b.format, theme: b.theme, css: b.css, assets: { ...config.trustedOptions?.assets, ...assets }, html: b.html ? { assetMode: b.html.assetMode } : void 0, pdf: b.pdf ? { ...config.trustedOptions?.pdf, size: b.pdf.size, landscape: b.pdf.landscape, pageNumbers: b.pdf.pageNumbers, preferCSSPageSize: b.pdf.preferCSSPageSize } : config.trustedOptions?.pdf, pptx: b.pptx ? { editability: b.pptx.editability, layout: b.pptx.layout } : void 0, docx: b.docx ? { landscape: b.docx.landscape, margin: b.docx.margin, header: b.docx.header, footer: b.docx.footer } : void 0, diagramMode: b.diagramMode, strictStyles: b.strictStyles };
855
+ return { template: b.template, dataSets: b.dataSets ?? [], variables: b.variables ?? {}, options };
856
+ }
857
+ const send = (res, r) => {
858
+ res.setHeader("Content-Type", r.mediaType);
859
+ res.setHeader("Content-Disposition", `attachment; filename="${r.filename}"`);
860
+ res.setHeader("X-Reportic-Diagnostics", encodeURIComponent(JSON.stringify(r.diagnostics)));
861
+ if (r.assets.length) {
862
+ res.status(406).json({ error: "BUNDLE_REQUIRED", message: "This export contains companion assets. Use a report job with /bundle, or select self-contained HTML." });
863
+ return;
864
+ }
865
+ res.send(Buffer.from(r.bytes));
866
+ };
867
+ const publicJob = (j) => ({ id: j.id, state: j.state, createdAt: j.createdAt, expiresAt: j.expiresAt, diagnostics: j.diagnostics, ...j.result ? { artifact: { filename: j.result.filename, mediaType: j.result.mediaType, bytes: j.result.bytes.length, url: `/v1/report-jobs/${j.id}/artifact`, bundleUrl: `/v1/report-jobs/${j.id}/bundle` } } : {} });
868
+ function prune() {
869
+ const now = Date.now();
870
+ for (const [id, j] of jobs) {
871
+ if (new Date(j.expiresAt).getTime() < now) {
872
+ j.controller.abort();
873
+ j.result = void 0;
874
+ j.state = "expired";
875
+ if (now - new Date(j.expiresAt).getTime() > 6e4 || jobs.size >= (config.maxJobs ?? 100)) jobs.delete(id);
876
+ }
877
+ }
878
+ for (const [k, v] of idempotency) if (!jobs.has(v.id)) idempotency.delete(k);
879
+ }
880
+ function find(req, res) {
881
+ prune();
882
+ const job = jobs.get(String(req.params.id));
883
+ if (!job || job.owner !== req.owner) {
884
+ res.status(404).json({ error: "JOB_NOT_FOUND" });
885
+ return;
886
+ }
887
+ return job;
888
+ }
889
+ router.get("/components", (req, res) => res.json(listComponents({ format: req.query.format, editability: req.query.editability }, config.registry)));
890
+ router.get("/components/:type", (req, res) => {
891
+ const component = getComponent(String(req.params.type), config.registry);
892
+ component ? res.json(component) : res.status(404).json({ error: "COMPONENT_NOT_FOUND" });
893
+ });
894
+ router.post("/templates/inspect", (req, res) => res.json(inspectTemplate(req.body?.template)));
895
+ router.post("/templates/validate", async (req, res) => res.json(await validateTemplate(req.body?.template, { registry: config.registry })));
896
+ router.post("/reports/validate", async (req, res) => {
897
+ const i = input(req);
898
+ res.json(await validateReport(i.template, i.dataSets, i.variables, i.options));
899
+ });
900
+ router.post("/reports/preview", async (req, res) => {
901
+ const i = input(req);
902
+ const result = await generateReport(i.template, i.dataSets, i.variables, { ...i.options, format: "html", html: { assetMode: "embedded" } });
903
+ res.json({ html: Buffer.from(result.bytes).toString(), diagnostics: result.diagnostics, metadata: result.metadata });
904
+ });
905
+ router.post("/reports/generate", async (req, res) => {
906
+ if (active >= (config.concurrency ?? 2)) {
907
+ res.setHeader("Retry-After", "2");
908
+ res.status(429).json({ error: "CAPACITY_EXCEEDED" });
909
+ return;
910
+ }
911
+ const i = input(req);
912
+ const accept = req.headers.accept;
913
+ if (accept && !accept.includes("*/*") && !accept.includes("application/octet-stream")) {
914
+ const expected = { pdf: "application/pdf", pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation", docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", html: "text/html", markdown: "text/markdown" };
915
+ if (!accept.includes(expected[i.options.format ?? "pdf"])) {
916
+ res.status(406).json({ error: "ACCEPT_MISMATCH" });
917
+ return;
918
+ }
919
+ }
920
+ active++;
921
+ try {
922
+ const result = await generateReport(i.template, i.dataSets, i.variables, i.options);
923
+ send(res, result);
924
+ } finally {
925
+ active--;
926
+ }
927
+ });
928
+ router.post("/report-jobs", async (req, res) => {
929
+ prune();
930
+ const i = input(req);
931
+ const key = req.headers["idempotency-key"];
932
+ const hash = createHash("sha256").update(JSON.stringify(req.body)).digest("hex");
933
+ const scopedKey = typeof key === "string" ? `${req.owner}:${key}` : void 0;
934
+ if (scopedKey && idempotency.has(scopedKey)) {
935
+ const existing = idempotency.get(scopedKey);
936
+ if (existing.hash !== hash) {
937
+ res.status(409).json({ error: "IDEMPOTENCY_CONFLICT" });
938
+ return;
939
+ }
940
+ res.json(publicJob(jobs.get(existing.id)));
941
+ return;
942
+ }
943
+ if (jobs.size >= (config.maxJobs ?? 100)) {
944
+ res.status(429).json({ error: "JOB_LIMIT" });
945
+ return;
946
+ }
947
+ const job = { id: randomUUID(), owner: req.owner, state: "queued", createdAt: (/* @__PURE__ */ new Date()).toISOString(), expiresAt: new Date(Date.now() + (config.ttlMs ?? 36e5)).toISOString(), diagnostics: [], controller: new AbortController() };
948
+ jobs.set(job.id, job);
949
+ if (scopedKey) idempotency.set(scopedKey, { hash, id: job.id });
950
+ res.status(202).json(publicJob(job));
951
+ const execute = async () => {
952
+ if (job.state !== "queued") return;
953
+ if (active >= (config.concurrency ?? 2)) {
954
+ const timer = setTimeout(() => void execute(), 150);
955
+ timer.unref();
956
+ return;
957
+ }
958
+ active++;
959
+ job.state = "running";
960
+ try {
961
+ const result = await generateReport(i.template, i.dataSets, i.variables, { ...i.options, signal: job.controller.signal });
962
+ if (job.state === "running") {
963
+ job.result = result;
964
+ job.diagnostics = result.diagnostics;
965
+ job.state = "succeeded";
966
+ }
967
+ } catch (e) {
968
+ if (!job.controller.signal.aborted) {
969
+ job.state = "failed";
970
+ job.diagnostics = e instanceof ReporticError ? e.diagnostics : [{ code: "RENDER_FAILED", severity: "error", phase: "render", message: "Report job failed." }];
971
+ }
972
+ } finally {
973
+ active--;
974
+ }
975
+ };
976
+ void execute();
977
+ });
978
+ router.get("/report-jobs/:id", (req, res) => {
979
+ const job = find(req, res);
980
+ if (job) res.json(publicJob(job));
981
+ });
982
+ router.get("/report-jobs/:id/artifact", (req, res) => {
983
+ const j = find(req, res);
984
+ if (!j) return;
985
+ if (!j.result) {
986
+ res.status(j.state === "expired" ? 410 : 409).json({ error: "ARTIFACT_UNAVAILABLE", state: j.state });
987
+ return;
988
+ }
989
+ send(res, j.result);
990
+ });
991
+ router.get("/report-jobs/:id/bundle", async (req, res) => {
992
+ const j = find(req, res);
993
+ if (!j) return;
994
+ if (!j.result) {
995
+ res.status(409).json({ error: "ARTIFACT_UNAVAILABLE" });
996
+ return;
997
+ }
998
+ const { default: JSZip } = await import("jszip");
999
+ const zip = new JSZip();
1000
+ zip.file(j.result.filename, j.result.bytes);
1001
+ for (const asset of j.result.assets) zip.file(asset.path, asset.bytes);
1002
+ res.type("application/zip").attachment(j.result.filename + ".zip").send(await zip.generateAsync({ type: "nodebuffer" }));
1003
+ });
1004
+ router.delete("/report-jobs/:id", (req, res) => {
1005
+ const j = find(req, res);
1006
+ if (j) {
1007
+ if (j.state === "queued" || j.state === "running") {
1008
+ j.controller.abort();
1009
+ j.state = "cancelled";
1010
+ }
1011
+ res.json(publicJob(j));
1012
+ }
1013
+ });
1014
+ router.use((error, req, res, next) => {
1015
+ if (res.headersSent) {
1016
+ next(error);
1017
+ return;
1018
+ }
1019
+ const diagnostics = error instanceof ReporticError ? error.diagnostics : [{ code: error.type === "entity.too.large" ? "REQUEST_TOO_LARGE" : "INVALID_REQUEST", severity: "error", phase: "input", message: "Request could not be processed." }];
1020
+ res.status(422).json({ error: "REPORT_FAILED", diagnostics });
1021
+ });
1022
+ return router;
1023
+ }
1024
+ function createReporticApp(options = {}) {
1025
+ const app = express2();
1026
+ app.disable("x-powered-by");
1027
+ app.use("/v1", createReporticRouter(options));
1028
+ app.get("/health", (_req, res) => res.json({ status: "ok", version: "0.2.2" }));
1029
+ return app;
1030
+ }
1031
+
1032
+ // packages/reportic-api/src/server.ts
1033
+ var host = process.env.HOST ?? "127.0.0.1";
1034
+ if (!["127.0.0.1", "localhost", "::1"].includes(host) && !process.env.REPORTIC_API_TOKEN) throw new Error("Set REPORTIC_API_TOKEN before binding a remote interface.");
1035
+ var port = Number(process.env.PORT ?? 4174);
1036
+ createReporticApp({ token: process.env.REPORTIC_API_TOKEN }).listen(port, host, () => console.log(`Reportic API: http://${host}:${port}`));
1037
+ //# sourceMappingURL=server.js.map