udf-cli 0.3.0 → 0.4.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/README.md +130 -7
- package/dist/bin/udf-cli.d.ts +0 -1
- package/dist/bin/udf-cli.js +1 -121
- package/dist/chunk-6564CQ7U.js +1 -0
- package/dist/module-resolve-XD725NCC.js +1 -0
- package/dist/pin-prompt-FSXBDU36.js +1 -0
- package/dist/sign-BNEXYCMC.js +1 -0
- package/dist/src/index.d.ts +117 -6
- package/dist/src/index.js +1 -6
- package/package.json +19 -3
- package/dist/bin/udf-cli.js.map +0 -1
- package/dist/src/converters/html-to-udf.d.ts +0 -1
- package/dist/src/converters/html-to-udf.js +0 -7
- package/dist/src/converters/html-to-udf.js.map +0 -1
- package/dist/src/converters/markdown-to-udf.d.ts +0 -1
- package/dist/src/converters/markdown-to-udf.js +0 -7
- package/dist/src/converters/markdown-to-udf.js.map +0 -1
- package/dist/src/converters/udf-to-html.d.ts +0 -1
- package/dist/src/converters/udf-to-html.js +0 -7
- package/dist/src/converters/udf-to-html.js.map +0 -1
- package/dist/src/converters/udf-to-markdown.d.ts +0 -1
- package/dist/src/converters/udf-to-markdown.js +0 -7
- package/dist/src/converters/udf-to-markdown.js.map +0 -1
- package/dist/src/html/markdown-parser.d.ts +0 -2
- package/dist/src/html/markdown-parser.js +0 -172
- package/dist/src/html/markdown-parser.js.map +0 -1
- package/dist/src/html/markdown-serializer.d.ts +0 -2
- package/dist/src/html/markdown-serializer.js +0 -156
- package/dist/src/html/markdown-serializer.js.map +0 -1
- package/dist/src/html/parser.d.ts +0 -2
- package/dist/src/html/parser.js +0 -576
- package/dist/src/html/parser.js.map +0 -1
- package/dist/src/html/serializer.d.ts +0 -6
- package/dist/src/html/serializer.js +0 -285
- package/dist/src/html/serializer.js.map +0 -1
- package/dist/src/index.js.map +0 -1
- package/dist/src/model/document.d.ts +0 -107
- package/dist/src/model/document.js +0 -88
- package/dist/src/model/document.js.map +0 -1
- package/dist/src/udf/cdata-builder.d.ts +0 -14
- package/dist/src/udf/cdata-builder.js +0 -71
- package/dist/src/udf/cdata-builder.js.map +0 -1
- package/dist/src/udf/parser.d.ts +0 -2
- package/dist/src/udf/parser.js +0 -325
- package/dist/src/udf/parser.js.map +0 -1
- package/dist/src/udf/serializer.d.ts +0 -5
- package/dist/src/udf/serializer.js +0 -267
- package/dist/src/udf/serializer.js.map +0 -1
- package/dist/src/utils/color.d.ts +0 -9
- package/dist/src/utils/color.js +0 -87
- package/dist/src/utils/color.js.map +0 -1
- package/dist/src/utils/style.d.ts +0 -23
- package/dist/src/utils/style.js +0 -80
- package/dist/src/utils/style.js.map +0 -1
package/README.md
CHANGED
|
@@ -131,6 +131,42 @@ Example output:
|
|
|
131
131
|
- Çatı izolasyonunda bozulma
|
|
132
132
|
```
|
|
133
133
|
|
|
134
|
+
## Signing (.udf) with an e-signature card
|
|
135
|
+
|
|
136
|
+
`udf-cli sign` adds a detached **CAdES-BES** signature (`sign.sgn`) to one or more
|
|
137
|
+
`.udf` files using a PKCS#11 smart card. The PIN is requested once and reused for all
|
|
138
|
+
files in a single card session.
|
|
139
|
+
|
|
140
|
+
```bash
|
|
141
|
+
# Driver auto-detected, PIN entered in a native GUI window (nothing on the command line):
|
|
142
|
+
udf-cli sign evrak1.udf evrak2.udf
|
|
143
|
+
# explicit driver + non-interactive PIN sources:
|
|
144
|
+
udf-cli sign *.udf --module /usr/local/lib/libakisp11.dylib --pin 1234
|
|
145
|
+
UDF_PIN=1234 UDF_PKCS11_MODULE=/usr/local/lib/libakisp11.dylib udf-cli sign *.udf
|
|
146
|
+
# with intermediate CA certs (if the card holds only the leaf):
|
|
147
|
+
udf-cli sign evrak.udf --extra-certs türktrust-h7.cer türktrust-root.cer
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
- **Driver auto-detection:** if you omit `--module`, the CLI looks for your installed vendor
|
|
151
|
+
driver in known locations (AKİS `libakisp11`, SafeNet `eTPKCS11`, Gemalto `gtop11dotnet`) and
|
|
152
|
+
loads the first that works on your CPU arch. Override with `--module` or `UDF_PKCS11_MODULE`.
|
|
153
|
+
The driver is shipped by your card vendor and is **not bundled or downloaded** — install your
|
|
154
|
+
card software (e.g. AKİS). On Apple Silicon, use a universal/arm64 driver (or run Node under
|
|
155
|
+
Rosetta with an x86_64-only one).
|
|
156
|
+
- **PIN entry, agent-friendly:** if you omit `--pin`/`UDF_PIN`, a **native OS dialog**
|
|
157
|
+
(macOS `osascript`, Linux `zenity`/`kdialog`, Windows WinForms) pops up for the human to
|
|
158
|
+
type the PIN — outside the terminal, so a tool/agent driving the CLI never handles it. In a
|
|
159
|
+
headless session (no desktop), it errors clearly and asks for `--pin`/`UDF_PIN` instead.
|
|
160
|
+
- `--extra-certs` embeds intermediate CA certificates (PEM or DER) when the card stores
|
|
161
|
+
only the signer certificate and UYAP needs the full chain.
|
|
162
|
+
- The PIN is requested once. On a wrong PIN the command aborts immediately and does **not**
|
|
163
|
+
retry — cards lock after ~3 failed attempts.
|
|
164
|
+
- Signing pulls in the optional `koffi` dependency, which downloads a prebuilt native
|
|
165
|
+
binary on first install (needs network). Format conversion commands do not need it.
|
|
166
|
+
- The signature is plain BES (no timestamp/policy), matching the UYAP editor's output.
|
|
167
|
+
- **macOS (Apple Silicon):** some vendors ship x86_64-only drivers. If `--module` fails to
|
|
168
|
+
load on arm64, run Node under Rosetta: `arch -x86_64 node $(which udf-cli) sign ...`.
|
|
169
|
+
|
|
134
170
|
## Library Usage
|
|
135
171
|
|
|
136
172
|
```typescript
|
|
@@ -161,13 +197,16 @@ Paste this into your agent's system prompt:
|
|
|
161
197
|
|
|
162
198
|
> Generate UDF input as HTML with inline CSS. Use `pt` for all lengths.
|
|
163
199
|
>
|
|
200
|
+
> - **Default:** when no `font-family` / `font-size` is set, text is **Times New Roman 12pt**, black on white. Omit these attributes unless the user requests a different style.
|
|
164
201
|
> - **Inline styles:** `<strong>`, `<em>`, `<u>`, `<span style="font-family:Arial; font-size:12pt; color:#FF0000; background-color:#FFFF00">`
|
|
165
|
-
> - **Paragraphs:** `<p style="text-align:justify; line-height:1.5; margin-top:12pt; margin-bottom:6pt; margin-left:36pt; text-indent:24pt">`
|
|
202
|
+
> - **Paragraphs:** `<p style="text-align:justify; line-height:1.5; margin-top:12pt; margin-bottom:6pt; margin-left:36pt; text-indent:24pt">` (also `text-align:right`, hanging indent via negative `text-indent`)
|
|
203
|
+
> - **Headings:** `<h1>`–`<h6>` produce bold paragraphs at 24/20/16/14/12/10pt
|
|
166
204
|
> - **Tab stops:** `<p style="tab-stops:36pt 72pt 108pt">Item<tab/>Value<tab/>Notes</p>`
|
|
167
205
|
> - **Page break:** `<page-break/>` — **only use when the user explicitly asks for one**. The UDF editor renders an inline "sayfa sonudur" marker between pages that readers often mistake for document content. Default to letting the page flow naturally.
|
|
168
|
-
> - **Tables:** standard `<table><tr><td>...</td></tr></table>`; cell styles via inline CSS
|
|
206
|
+
> - **Tables:** standard `<table><tr><td>...</td></tr></table>`; supports `colspan`/`rowspan`; cell styles via inline CSS (`background-color`, `vertical-align`, `border`, `border-style:none` to hide borders)
|
|
169
207
|
> - **Lists:** `<ul>`, `<ol>`, `<li>` (nesting via nested lists)
|
|
170
|
-
> - **Images:** `<img src="data:image/png;base64,..." width="200" height="100">`
|
|
208
|
+
> - **Images:** `<img src="data:image/png;base64,..." width="200" height="100">` (width/height in `pt`)
|
|
209
|
+
> - **Colors:** hex (`#RGB`, `#RRGGBB`), `rgb(r,g,b)`, or named CSS colors all work
|
|
171
210
|
>
|
|
172
211
|
> Always use `pt`. Do not escape `<tab/>` or `<page-break/>`. Do not use `<br>` to separate paragraphs — start a new `<p>`.
|
|
173
212
|
|
|
@@ -234,6 +273,86 @@ Paste this into your agent's system prompt:
|
|
|
234
273
|
<p style="margin-top:24pt; tab-stops:280pt"><strong>Yargıtay</strong><tab/><strong>Mahkeme Mührü</strong></p>
|
|
235
274
|
```
|
|
236
275
|
|
|
276
|
+
#### Headings (auto-bold, fixed sizes)
|
|
277
|
+
|
|
278
|
+
```html
|
|
279
|
+
<h1>Karar Özeti</h1>
|
|
280
|
+
<h2>Tarafların İddiaları</h2>
|
|
281
|
+
<p>Normal gövde metni.</p>
|
|
282
|
+
```
|
|
283
|
+
|
|
284
|
+
#### Numbered list with a nested bullet list
|
|
285
|
+
|
|
286
|
+
```html
|
|
287
|
+
<ol>
|
|
288
|
+
<li>Birinci madde</li>
|
|
289
|
+
<li>İkinci madde
|
|
290
|
+
<ul>
|
|
291
|
+
<li>Alt madde a</li>
|
|
292
|
+
<li>Alt madde b</li>
|
|
293
|
+
</ul>
|
|
294
|
+
</li>
|
|
295
|
+
<li>Üçüncü madde</li>
|
|
296
|
+
</ol>
|
|
297
|
+
```
|
|
298
|
+
|
|
299
|
+
#### Right-aligned paragraph (e.g. date / venue line)
|
|
300
|
+
|
|
301
|
+
```html
|
|
302
|
+
<p style="text-align:right">İstanbul, 7 Mayıs 2026</p>
|
|
303
|
+
```
|
|
304
|
+
|
|
305
|
+
#### Hanging indent (negative `text-indent`)
|
|
306
|
+
|
|
307
|
+
```html
|
|
308
|
+
<p style="margin-left:36pt; text-indent:-36pt">DAVACI<tab/>: Mehmet Yılmaz, T.C. Kimlik No 11111111111, İstanbul</p>
|
|
309
|
+
```
|
|
310
|
+
|
|
311
|
+
#### Embedded image (base64 data URI, sized in points)
|
|
312
|
+
|
|
313
|
+
```html
|
|
314
|
+
<p><img src="data:image/png;base64,iVBORw0KGgo..." width="200" height="100"></p>
|
|
315
|
+
```
|
|
316
|
+
|
|
317
|
+
#### Table with merged cells (`colspan` / `rowspan`)
|
|
318
|
+
|
|
319
|
+
```html
|
|
320
|
+
<table>
|
|
321
|
+
<tr>
|
|
322
|
+
<td rowspan="2" style="vertical-align:middle"><strong>Kalem</strong></td>
|
|
323
|
+
<td colspan="2" style="text-align:center"><strong>Tutar</strong></td>
|
|
324
|
+
</tr>
|
|
325
|
+
<tr>
|
|
326
|
+
<td>Net</td>
|
|
327
|
+
<td>KDV Dahil</td>
|
|
328
|
+
</tr>
|
|
329
|
+
<tr>
|
|
330
|
+
<td>Vekalet ücreti</td>
|
|
331
|
+
<td>1.000 TL</td>
|
|
332
|
+
<td>1.200 TL</td>
|
|
333
|
+
</tr>
|
|
334
|
+
</table>
|
|
335
|
+
```
|
|
336
|
+
|
|
337
|
+
#### Borderless table (layout grid, no visible lines)
|
|
338
|
+
|
|
339
|
+
```html
|
|
340
|
+
<table>
|
|
341
|
+
<tr>
|
|
342
|
+
<td style="border-style:none">Sol sütun</td>
|
|
343
|
+
<td style="border-style:none">Sağ sütun</td>
|
|
344
|
+
</tr>
|
|
345
|
+
</table>
|
|
346
|
+
```
|
|
347
|
+
|
|
348
|
+
#### Page break via CSS on `<div>` (alternative to `<page-break/>`)
|
|
349
|
+
|
|
350
|
+
```html
|
|
351
|
+
<p>Birinci bölüm.</p>
|
|
352
|
+
<div style="page-break-before:always"></div>
|
|
353
|
+
<p>İkinci bölüm.</p>
|
|
354
|
+
```
|
|
355
|
+
|
|
237
356
|
### Unit rules
|
|
238
357
|
|
|
239
358
|
- Always use `pt`. Conversion happens automatically for `px`, `em`, `rem`, `cm`, `mm`, `in`, but agents should not rely on this — sticking to `pt` makes output predictable.
|
|
@@ -278,18 +397,22 @@ These are non-standard tags handled by `udf-cli`:
|
|
|
278
397
|
|
|
279
398
|
These inline styles are recognized on `<p>`, `<span>`, `<td>`:
|
|
280
399
|
|
|
281
|
-
- `font-family` — mapped to UDF font family
|
|
282
|
-
- `font-size` — supports `px` (converted to pt) and `pt
|
|
400
|
+
- `font-family` — mapped to UDF font family. Default: **Times New Roman**.
|
|
401
|
+
- `font-size` — supports `px` (converted to pt) and `pt`. Default: **12pt**.
|
|
283
402
|
- `font-weight: bold` — bold text
|
|
284
403
|
- `font-style: italic` — italic text
|
|
285
404
|
- `text-decoration: underline` — underlined text
|
|
286
|
-
- `color` — text color (
|
|
287
|
-
- `background-color` — text/cell background
|
|
405
|
+
- `color` — text color. Accepts hex (`#RGB`, `#RRGGBB`), `rgb(r,g,b)`, and named CSS colors (`red`, `navy`, …).
|
|
406
|
+
- `background-color` — text/cell background (same color formats as `color`)
|
|
288
407
|
- `text-align` — left, center, right, justify
|
|
289
408
|
- `vertical-align` — top, middle, bottom (table cells)
|
|
290
409
|
- `line-height` — paragraph line spacing
|
|
410
|
+
- `margin-top` / `margin-bottom` / `margin-left` / `margin-right` — paragraph spacing & indentation
|
|
411
|
+
- `padding-top` / `padding-bottom` / `padding-left` / `padding-right` (on `<p>`) — added to the corresponding `margin-*` value
|
|
291
412
|
- `text-indent` — first-line indent (positive or negative for hanging indent)
|
|
292
413
|
- `tab-stops` — space- or comma-separated list of tab positions (custom property)
|
|
414
|
+
- `border` (on `<td>`) — shorthand `<width> <style> <color>`, e.g. `border:1pt solid #000`
|
|
415
|
+
- `border-style` (on `<td>`) — `solid` or `none` (`none` hides cell borders)
|
|
293
416
|
- `page-break-before` / `page-break-after` (on `<div>`) — value `always` or `page` inserts a page break
|
|
294
417
|
|
|
295
418
|
## Writing HTML for UDF Conversion
|
package/dist/bin/udf-cli.d.ts
CHANGED
package/dist/bin/udf-cli.js
CHANGED
|
@@ -1,122 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { Command } from 'commander';
|
|
3
|
-
import { existsSync, readFileSync, writeFileSync } from 'fs';
|
|
4
|
-
import { htmlToUdf } from '../src/converters/html-to-udf.js';
|
|
5
|
-
import { udfToHtml } from '../src/converters/udf-to-html.js';
|
|
6
|
-
import { udfToMarkdown } from '../src/converters/udf-to-markdown.js';
|
|
7
|
-
import { markdownToUdf } from '../src/converters/markdown-to-udf.js';
|
|
8
|
-
const program = new Command();
|
|
9
|
-
program
|
|
10
|
-
.name('udf-cli')
|
|
11
|
-
.description('Convert between HTML and UYAP UDF file format')
|
|
12
|
-
.version('0.1.0');
|
|
13
|
-
program
|
|
14
|
-
.command('html2udf')
|
|
15
|
-
.description('Convert HTML to UDF format')
|
|
16
|
-
.argument('<input>', 'HTML input file, - for stdin, or raw HTML string')
|
|
17
|
-
.argument('[output]', 'UDF output file (omit for stdout)')
|
|
18
|
-
.action(async (input, output) => {
|
|
19
|
-
try {
|
|
20
|
-
let html;
|
|
21
|
-
if (input === '-') {
|
|
22
|
-
html = readFileSync(0, 'utf-8');
|
|
23
|
-
}
|
|
24
|
-
else if (input.includes('<') || !existsSync(input)) {
|
|
25
|
-
// Treat as raw HTML string if it contains '<' or doesn't exist as a file
|
|
26
|
-
html = input;
|
|
27
|
-
}
|
|
28
|
-
else {
|
|
29
|
-
html = readFileSync(input, 'utf-8');
|
|
30
|
-
}
|
|
31
|
-
const udf = await htmlToUdf(html);
|
|
32
|
-
if (output) {
|
|
33
|
-
writeFileSync(output, udf);
|
|
34
|
-
}
|
|
35
|
-
else {
|
|
36
|
-
process.stdout.write(udf);
|
|
37
|
-
}
|
|
38
|
-
}
|
|
39
|
-
catch (err) {
|
|
40
|
-
console.error(`Error: ${err instanceof Error ? err.message : err}`);
|
|
41
|
-
process.exit(1);
|
|
42
|
-
}
|
|
43
|
-
});
|
|
44
|
-
program
|
|
45
|
-
.command('udf2html')
|
|
46
|
-
.description('Convert UDF to HTML format')
|
|
47
|
-
.argument('<input>', 'UDF input file (use - for stdin)')
|
|
48
|
-
.argument('[output]', 'HTML output file (omit for stdout)')
|
|
49
|
-
.action(async (input, output) => {
|
|
50
|
-
try {
|
|
51
|
-
const udf = input === '-'
|
|
52
|
-
? readFileSync(0)
|
|
53
|
-
: readFileSync(input);
|
|
54
|
-
const html = await udfToHtml(Buffer.from(udf));
|
|
55
|
-
if (output) {
|
|
56
|
-
writeFileSync(output, html, 'utf-8');
|
|
57
|
-
}
|
|
58
|
-
else {
|
|
59
|
-
process.stdout.write(html);
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
catch (err) {
|
|
63
|
-
console.error(`Error: ${err instanceof Error ? err.message : err}`);
|
|
64
|
-
process.exit(1);
|
|
65
|
-
}
|
|
66
|
-
});
|
|
67
|
-
program
|
|
68
|
-
.command('udf2md')
|
|
69
|
-
.description('Convert UDF to Markdown format')
|
|
70
|
-
.argument('<input>', 'UDF input file (use - for stdin)')
|
|
71
|
-
.argument('[output]', 'Markdown output file (omit for stdout)')
|
|
72
|
-
.action(async (input, output) => {
|
|
73
|
-
try {
|
|
74
|
-
const udf = input === '-'
|
|
75
|
-
? readFileSync(0)
|
|
76
|
-
: readFileSync(input);
|
|
77
|
-
const md = await udfToMarkdown(Buffer.from(udf));
|
|
78
|
-
if (output) {
|
|
79
|
-
writeFileSync(output, md, 'utf-8');
|
|
80
|
-
}
|
|
81
|
-
else {
|
|
82
|
-
process.stdout.write(md);
|
|
83
|
-
}
|
|
84
|
-
}
|
|
85
|
-
catch (err) {
|
|
86
|
-
console.error(`Error: ${err instanceof Error ? err.message : err}`);
|
|
87
|
-
process.exit(1);
|
|
88
|
-
}
|
|
89
|
-
});
|
|
90
|
-
program
|
|
91
|
-
.command('md2udf')
|
|
92
|
-
.description('Convert Markdown to UDF format')
|
|
93
|
-
.argument('<input>', 'Markdown input file, - for stdin, or raw Markdown string')
|
|
94
|
-
.argument('[output]', 'UDF output file (omit for stdout)')
|
|
95
|
-
.action(async (input, output) => {
|
|
96
|
-
try {
|
|
97
|
-
let md;
|
|
98
|
-
if (input === '-') {
|
|
99
|
-
md = readFileSync(0, 'utf-8');
|
|
100
|
-
}
|
|
101
|
-
else if (existsSync(input) && !input.includes('\n')) {
|
|
102
|
-
md = readFileSync(input, 'utf-8');
|
|
103
|
-
}
|
|
104
|
-
else {
|
|
105
|
-
// Treat as raw Markdown string
|
|
106
|
-
md = input;
|
|
107
|
-
}
|
|
108
|
-
const udf = await markdownToUdf(md);
|
|
109
|
-
if (output) {
|
|
110
|
-
writeFileSync(output, udf);
|
|
111
|
-
}
|
|
112
|
-
else {
|
|
113
|
-
process.stdout.write(udf);
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
catch (err) {
|
|
117
|
-
console.error(`Error: ${err instanceof Error ? err.message : err}`);
|
|
118
|
-
process.exit(1);
|
|
119
|
-
}
|
|
120
|
-
});
|
|
121
|
-
program.parse();
|
|
122
|
-
//# sourceMappingURL=udf-cli.js.map
|
|
2
|
+
import{htmlToUdf,markdownToUdf,udfToHtml,udfToMarkdown}from'../chunk-6564CQ7U.js';import{Command}from'commander';import{existsSync,readFileSync,writeFileSync}from'fs';import{fileURLToPath}from'url';import{dirname as a0a,resolve}from'path';import a0b from'open';var DEFAULT_API_BASE='https://api.workos.com',DEFAULT_CLI_CLIENT_ID='client_01KRPJRBTG0YG5BCPMBXRA63QA';function loadAuthConfig(a=process['env']){return{'apiBase':a['WORKOS_API_BASE']??DEFAULT_API_BASE,'clientId':a['YARGI_CLI_CLIENT_ID']??DEFAULT_CLI_CLIENT_ID};}var DEFAULT_SERVER_URL='https://yargi.betaspacestudio.com';function loadServerConfig(a=process['env']){const b=a['YARGI_SERVER_URL']??DEFAULT_SERVER_URL;return{'serverUrl':b['replace'](/\/+$/,'')};}import{chmod,mkdir,readFile,writeFile,unlink,stat}from'fs/promises';import{homedir}from'os';import{dirname,join}from'path';import{z}from'zod';var StoredTokensSchema=z['object']({'accessToken':z['string'](),'refreshToken':z['string'](),'expiresAt':z['number'](),'email':z['string'](),'userId':z['string']()});function defaultTokenPath(a=process['env']){const b=a['XDG_CONFIG_HOME']??join(homedir(),'.config');return join(b,'yargi','token.json');}function decodeJwtExp(a){try{const b=a['split']('.')[0x1];if(!b)throw new Error('no\x20payload');const c=Buffer['from'](b,'base64url')['toString']('utf8'),d=JSON['parse'](c)['exp'];if(typeof d!=='number')throw new Error('no\x20exp');return d*0x3e8;}catch{return Date['now']()+0x5*0xea60;}}var FileTokenStore=class{constructor(a=defaultTokenPath()){this['path']=a;}['path'];async['load'](){let a;try{a=await readFile(this['path'],'utf8');}catch{return null;}try{const d=await stat(this['path']);(d['mode']&0x3f)!==0x0&&process['stderr']['write']('warning:\x20'+this['path']+'\x20has\x20loose\x20permissions;\x20expected\x200600\x0a');}catch{}let b;try{b=JSON['parse'](a);}catch{return null;}const c=StoredTokensSchema['safeParse'](b);return c['success']?c['data']:null;}async['save'](a){await mkdir(dirname(this['path']),{'recursive':!![],'mode':0x1c0}),await writeFile(this['path'],JSON['stringify'](a),{'mode':0x180}),await chmod(this['path'],0x180);}async['clear'](){try{await unlink(this['path']);}catch{}}};import{z as a0c}from'zod';var DeviceAuthorizationResponseSchema=a0c['object']({'device_code':a0c['string'](),'user_code':a0c['string'](),'verification_uri':a0c['string'](),'verification_uri_complete':a0c['string'](),'expires_in':a0c['number'](),'interval':a0c['number']()})['passthrough'](),WorkosUserSchema=a0c['object']({'id':a0c['string'](),'email':a0c['string']()})['passthrough'](),TokenResponseSchema=a0c['object']({'access_token':a0c['string'](),'refresh_token':a0c['string'](),'user':WorkosUserSchema})['passthrough'](),DeviceCodeExpiredError=class extends Error{constructor(){super('Device\x20code\x20expired.\x20Run\x20login\x20again.'),this['name']='DeviceCodeExpiredError';}},AuthorizationDeniedError=class extends Error{constructor(){super('Authorization\x20was\x20denied.'),this['name']='AuthorizationDeniedError';}},RefreshFailedError=class extends Error{constructor(){super('Token\x20refresh\x20failed.'),this['name']='RefreshFailedError';}},DEVICE_GRANT='urn:ietf:params:oauth:grant-type:device_code';async function postForm(a,b){const c=await fetch(a,{'method':'POST','headers':{'content-type':'application/x-www-form-urlencoded'},'body':new URLSearchParams(b)['toString']()}),d=await c['text']();let e=void 0x0;try{e=d?JSON['parse'](d):void 0x0;}catch{e=void 0x0;}return{'status':c['status'],'json':e};}async function startDeviceAuthorization(a){const {status:b,json:c}=await postForm(a['apiBase']+'/user_management/authorize/device',{'client_id':a['clientId']});if(b!==0xc8)throw new Error('device\x20authorization\x20failed\x20('+b+')');return DeviceAuthorizationResponseSchema['parse'](c);}var defaultSleep=a=>new Promise(b=>setTimeout(b,a));async function pollForToken(a,b,c={}){const d=c['sleep']??defaultSleep,e=Date['now']()+b['expiresIn']*0x3e8;let f=b['interval'];for(;;){if(Date['now']()>e)throw new DeviceCodeExpiredError();await d(f*0x3e8);const {status:g,json:h}=await postForm(a['apiBase']+'/user_management/authenticate',{'client_id':a['clientId'],'grant_type':DEVICE_GRANT,'device_code':b['deviceCode']});if(g===0xc8)return TokenResponseSchema['parse'](h);const i=h?.['error'];if(i==='authorization_pending')continue;if(i==='slow_down'){f+=0x5;continue;}if(i==='expired_token')throw new DeviceCodeExpiredError();if(i==='access_denied')throw new AuthorizationDeniedError();throw new Error('device\x20token\x20exchange\x20failed:\x20'+(i??g));}}async function refreshToken(a,b){const {status:c,json:d}=await postForm(a['apiBase']+'/user_management/authenticate',{'client_id':a['clientId'],'grant_type':'refresh_token','refresh_token':b});if(c!==0xc8)throw new RefreshFailedError();const e=TokenResponseSchema['safeParse'](d);if(!e['success'])throw new RefreshFailedError();return e['data'];}var NotLoggedInError=class extends Error{constructor(){super('Önce\x20giriş\x20yapmalısınız:\x20`udf-cli\x20login`'),this['name']='NotLoggedInError';}},AccountBannedError=class extends Error{constructor(a){super('Hesabınız\x20devre\x20dışı\x20bırakıldı'+(a?':\x20'+a:'.')),this['reason']=a,this['name']='AccountBannedError';}['reason'];},ServerUnreachableError=class extends Error{constructor(a){super('Sunucuya\x20ulaşılamadı:\x20'+a+'.\x20İnternet\x20bağlantınızı\x20kontrol\x20edip\x20tekrar\x20deneyin.'),this['name']='ServerUnreachableError';}},EXPIRY_SKEW_MS=0xea60;async function getValidAccessToken(a,b,c={}){const d=c['refresh']??refreshToken,e=await a['load']();if(!e)throw new NotLoggedInError();if(Date['now']()<e['expiresAt']-EXPIRY_SKEW_MS)return e['accessToken'];let f;try{f=await d(b,e['refreshToken']);}catch{await a['clear']();throw new NotLoggedInError();}const g={'accessToken':f['access_token'],'refreshToken':f['refresh_token'],'expiresAt':decodeJwtExp(f['access_token']),'email':f['user']['email'],'userId':f['user']['id']};try{await a['save'](g);}catch{return g['accessToken'];}return g['accessToken'];}async function reportActivation(a){const b=a['serverUrl']+'/api/cli/activations';let c;try{c=await fetch(b,{'method':'POST','headers':{'authorization':'Bearer\x20'+a['accessToken'],'content-type':'application/json'},'body':JSON['stringify']({'command':'udf','metadata':a['metadata']})});}catch(d){throw new ServerUnreachableError(d instanceof Error?d['message']:String(d));}if(c['status']===0x191)throw new NotLoggedInError();if(c['status']===0x193){const e=await c['json']()['catch'](()=>({}));if(e['error']==='banned')throw new AccountBannedError(e['reason']??null);throw new ServerUnreachableError('forbidden\x20('+(e['error']??'unknown')+')');}if(c['status']>=0x1f4)throw new ServerUnreachableError('HTTP\x20'+c['status']);if(!c['ok']){const f=await c['text']()['catch'](()=>'');throw new ServerUnreachableError('HTTP\x20'+c['status']+'\x20'+f['slice'](0x0,0xc8));}return await c['json']();}var cfg=loadAuthConfig(),serverCfg=loadServerConfig(),store=new FileTokenStore();async function gate(a){const b=await getValidAccessToken(store,cfg);await reportActivation({'serverUrl':serverCfg['serverUrl'],'accessToken':b,'metadata':{'action':a}});}async function runLogin(a){const b=await startDeviceAuthorization(cfg);a('Giriş\x20için\x20şu\x20adresi\x20açın:\x20'+b['verification_uri_complete']),a('ve\x20kodu\x20onaylayın:\x20'+b['user_code']);try{await a0b(b['verification_uri_complete']);}catch{a('Tarayıcı\x20otomatik\x20açılamadı;\x20yukarıdaki\x20adresi\x20elle\x20açın.');}const c=await pollForToken(cfg,{'deviceCode':b['device_code'],'interval':b['interval'],'expiresIn':b['expires_in']});await store['save']({'accessToken':c['access_token'],'refreshToken':c['refresh_token'],'expiresAt':decodeJwtExp(c['access_token']),'email':c['user']['email'],'userId':c['user']['id']}),a('Giriş\x20yapıldı:\x20'+c['user']['email']);}async function runWhoami(a){await getValidAccessToken(store,cfg);const b=await store['load']();if(!b)throw new NotLoggedInError();a(b['email']+'\x20('+b['userId']+')');}async function runLogout(a){await store['clear'](),a('Çıkış\x20yapıldı.');}var pkgJson=JSON['parse'](readFileSync(resolve(a0a(fileURLToPath(import.meta.url)),'..','..','package.json'),'utf-8')),program=new Command();program['name']('udf-cli')['description']('Convert\x20between\x20HTML\x20and\x20UYAP\x20UDF\x20file\x20format')['version'](pkgJson['version']),program['command']('html2udf')['description']('Convert\x20HTML\x20to\x20UDF\x20format')['argument']('<input>','HTML\x20input\x20file,\x20-\x20for\x20stdin,\x20or\x20raw\x20HTML\x20string')['argument']('[output]','UDF\x20output\x20file\x20(omit\x20for\x20stdout)')['action'](async(a,b)=>{try{await gate('html2udf');let c;if(a==='-')c=readFileSync(0x0,'utf-8');else a['includes']('<')||!existsSync(a)?c=a:c=readFileSync(a,'utf-8');const d=await htmlToUdf(c);b?writeFileSync(b,d):process['stdout']['write'](d);}catch(e){console['error']('Error:\x20'+(e instanceof Error?e['message']:e)),process['exit'](0x1);}}),program['command']('udf2html')['description']('Convert\x20UDF\x20to\x20HTML\x20format')['argument']('<input>','UDF\x20input\x20file\x20(use\x20-\x20for\x20stdin)')['argument']('[output]','HTML\x20output\x20file\x20(omit\x20for\x20stdout)')['action'](async(a,b)=>{try{await gate('udf2html');const c=a==='-'?readFileSync(0x0):readFileSync(a),d=await udfToHtml(Buffer['from'](c));b?writeFileSync(b,d,'utf-8'):process['stdout']['write'](d);}catch(e){console['error']('Error:\x20'+(e instanceof Error?e['message']:e)),process['exit'](0x1);}}),program['command']('udf2md')['description']('Convert\x20UDF\x20to\x20Markdown\x20format')['argument']('<input>','UDF\x20input\x20file\x20(use\x20-\x20for\x20stdin)')['argument']('[output]','Markdown\x20output\x20file\x20(omit\x20for\x20stdout)')['action'](async(a,b)=>{try{await gate('udf2md');const c=a==='-'?readFileSync(0x0):readFileSync(a),d=await udfToMarkdown(Buffer['from'](c));b?writeFileSync(b,d,'utf-8'):process['stdout']['write'](d);}catch(e){console['error']('Error:\x20'+(e instanceof Error?e['message']:e)),process['exit'](0x1);}}),program['command']('md2udf')['description']('Convert\x20Markdown\x20to\x20UDF\x20format')['argument']('<input>','Markdown\x20input\x20file,\x20-\x20for\x20stdin,\x20or\x20raw\x20Markdown\x20string')['argument']('[output]','UDF\x20output\x20file\x20(omit\x20for\x20stdout)')['action'](async(a,b)=>{try{await gate('md2udf');let c;if(a==='-')c=readFileSync(0x0,'utf-8');else existsSync(a)&&!a['includes']('\x0a')?c=readFileSync(a,'utf-8'):c=a;const d=await markdownToUdf(c);b?writeFileSync(b,d):process['stdout']['write'](d);}catch(e){console['error']('Error:\x20'+(e instanceof Error?e['message']:e)),process['exit'](0x1);}}),program['command']('sign')['description']('Sign\x20one\x20or\x20more\x20.udf\x20files\x20with\x20a\x20PKCS#11\x20e-signature\x20card\x20(CAdES-BES)')['argument']('<files...>','.udf\x20files\x20to\x20sign\x20in\x20place')['option']('-m,\x20--module\x20<path>','PKCS#11\x20driver\x20path\x20(auto-detected\x20if\x20omitted;\x20or\x20set\x20UDF_PKCS11_MODULE)')['option']('-p,\x20--pin\x20<pin>','card\x20PIN\x20(omit\x20to\x20enter\x20it\x20in\x20a\x20native\x20GUI\x20dialog;\x20or\x20set\x20UDF_PIN)')['option']('--extra-certs\x20<paths...>','intermediate\x20CA\x20certificate\x20files\x20(DER\x20or\x20PEM)\x20to\x20embed')['action'](async(a,b)=>{try{await gate('sign');const {resolveModules:c}=await import('../module-resolve-XD725NCC.js'),d=c(b['module']);d['length']===0x0&&(console['error']('Error:\x20no\x20PKCS#11\x20driver\x20found.\x20Install\x20your\x20card\x20software\x20(e.g.\x20AKİS),\x20pass\x20--module,\x20or\x20set\x20UDF_PKCS11_MODULE.'),process['exit'](0x1));let e=b['pin']??process['env']['UDF_PIN'];if(!e){const {promptPinGui:i}=await import('../pin-prompt-FSXBDU36.js');e=i();}const f=(b['extraCerts']??[])['flatMap'](j=>{const k=readFileSync(j),l=k['toString']('latin1'),m=l['match'](/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g);if(m)return m['map'](n=>new Uint8Array(Buffer['from'](n['replace'](/-----[^-]+-----/g,'')['replace'](/\s+/g,''),'base64')));return[new Uint8Array(k)];}),{signUdfFiles:g}=await import('../sign-BNEXYCMC.js'),h=await g({'module':d,'pin':e,'files':a,'extraCertsDer':f});for(const j of h){console['error'](j['ok']?'signed:\x20'+j['file']:'FAILED:\x20'+j['file']+'\x20—\x20'+j['error']);}if(h['some'](k=>!k['ok']))process['exit'](0x1);}catch(k){console['error']('Error:\x20'+(k instanceof Error?k['message']:k)),process['exit'](0x1);}});var log=a=>process['stdout']['write'](a+'\x0a');program['command']('login')['description']('WorkOS\x20cihaz\x20akışıyla\x20giriş\x20yap\x20(dava-cli\x20ile\x20aynı\x20oturum)')['action'](async()=>{try{await runLogin(log);}catch(a){console['error']('Error:\x20'+(a instanceof Error?a['message']:a)),process['exit'](0x1);}}),program['command']('whoami')['description']('Giriş\x20yapılan\x20hesabı\x20göster')['action'](async()=>{try{await runWhoami(log);}catch(a){console['error']('Error:\x20'+(a instanceof Error?a['message']:a)),process['exit'](0x1);}}),program['command']('logout')['description']('Çıkış\x20yap\x20ve\x20kayıtlı\x20oturumu\x20temizle')['action'](async()=>{try{await runLogout(log);}catch(a){console['error']('Error:\x20'+(a instanceof Error?a['message']:a)),process['exit'](0x1);}}),program['parseAsync']();
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var Alignment=(a=>{return a[a['Left']=0x0]='Left',a[a['Center']=0x1]='Center',a[a['Right']=0x2]='Right',a[a['Justify']=0x3]='Justify',a;})(Alignment||{}),DEFAULT_TEXT_STYLE={'fontFamily':'Times\x20New\x20Roman','fontSize':0xc,'bold':![],'italic':![],'underline':![],'color':-0x1000000,'backgroundColor':-0x1},DEFAULT_PAGE_FORMAT={'mediaSizeName':0x1,'leftMargin':42.52,'rightMargin':28.35,'topMargin':14.17,'bottomMargin':14.17,'paperOrientation':0x1,'headerFOffset':0x14,'footerFOffset':0x14},DEFAULT_BORDER={'name':'borderCell','style':'borderStyle-solid'};function createParagraph(a){return{'type':'paragraph','alignment':0x0,'leftIndent':0x0,'rightIndent':0x0,'firstLineIndent':0x0,'lineSpacing':0x0,'spaceBefore':0x0,'spaceAfter':0x0,'runs':[],...a};}function createTextRun(a,b){return{'type':'text','text':a,'style':{...DEFAULT_TEXT_STYLE,...b}};}function createTable(a,b,c){return{'type':'table','name':'Sabit','columns':b['length'],'columnWidths':b,'border':{...DEFAULT_BORDER},'rows':a,...c};}function createTableCell(a,b){return{'colspan':0x1,'rowspan':0x1,'verticalAlign':'top','fillColor':0xffffff,'border':{...DEFAULT_BORDER},'borderWidth':0.5,'borderColor':0x0,'borderSpec':0xf,'content':a,...b};}function createTableRow(a,b){return{'name':'row1','rowType':'dataRow','height':0x0,'border':{...DEFAULT_BORDER},'cells':a,...b};}import{Parser}from'htmlparser2';var NAMED_COLORS={'black':[0x0,0x0,0x0],'white':[0xff,0xff,0xff],'red':[0xff,0x0,0x0],'green':[0x0,0x80,0x0],'blue':[0x0,0x0,0xff],'yellow':[0xff,0xff,0x0],'cyan':[0x0,0xff,0xff],'magenta':[0xff,0x0,0xff],'orange':[0xff,0xa5,0x0],'purple':[0x80,0x0,0x80],'gray':[0x80,0x80,0x80],'grey':[0x80,0x80,0x80],'navy':[0x0,0x0,0x80],'teal':[0x0,0x80,0x80],'maroon':[0x80,0x0,0x0],'olive':[0x80,0x80,0x0],'silver':[0xc0,0xc0,0xc0],'lime':[0x0,0xff,0x0],'aqua':[0x0,0xff,0xff],'fuchsia':[0xff,0x0,0xff],'transparent':[0x0,0x0,0x0]};function rgbToArgbInt(a,c,d){const e=(0xff<<0x18|a<<0x10|c<<0x8|d)>>>0x0;return e|0x0;}function parseHexColor(a){a=a['replace']('#','');a['length']===0x3&&(a=a[0x0]+a[0x0]+a[0x1]+a[0x1]+a[0x2]+a[0x2]);if(a['length']!==0x6)return null;const c=parseInt(a['slice'](0x0,0x2),0x10),d=parseInt(a['slice'](0x2,0x4),0x10),e=parseInt(a['slice'](0x4,0x6),0x10);if(isNaN(c)||isNaN(d)||isNaN(e))return null;return[c,d,e];}function parseRgbColor(a){const b=a['match'](/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);if(!b)return null;return[parseInt(b[0x1]),parseInt(b[0x2]),parseInt(b[0x3])];}function cssToArgb(a){a=a['trim']()['toLowerCase']();if(a['startsWith']('#')){const c=parseHexColor(a);if(c)return rgbToArgbInt(...c);}if(a['startsWith']('rgb')){const d=parseRgbColor(a);if(d)return rgbToArgbInt(...d);}const b=NAMED_COLORS[a];if(b)return rgbToArgbInt(...b);return-0x1000000;}function argbToCss(a){const c=a>>>0x0,d=c>>0x10&0xff,e=c>>0x8&0xff,f=c&0xff;return'#'+d['toString'](0x10)['padStart'](0x2,'0')+e['toString'](0x10)['padStart'](0x2,'0')+f['toString'](0x10)['padStart'](0x2,'0');}function parseInlineStyle(a){const b={};if(!a)return b;const c=a['split'](';');for(const d of c){const e=d['indexOf'](':');if(e===-0x1)continue;const f=d['slice'](0x0,e)['trim'](),g=d['slice'](e+0x1)['trim']();if(!f||!g)continue;const h=f['replace'](/-([a-z])/g,(i,j)=>j['toUpperCase']());b[h]=g;}return b;}function parseFontSize(a){const b=a['match'](/^([\d.]+)\s*(px|pt|em|rem)?$/);if(!b)return 0xc;const c=parseFloat(b[0x1]),d=b[0x2]||'pt';switch(d){case'px':return c*0.75;case'pt':return c;case'em':case'rem':return c*0xc;default:return c;}}function parseLengthPt(a,b='pt'){if(!a)return 0x0;const c=a['trim']()['match'](/^(-?[\d.]+)\s*(px|pt|em|rem|cm|mm|in)?$/);if(!c)return 0x0;const d=parseFloat(c[0x1]);if(isNaN(d))return 0x0;const e=c[0x2]??b;switch(e){case'px':return d*0.75;case'pt':return d;case'em':case'rem':return d*0xc;case'cm':return d*28.3465;case'mm':return d*2.83465;case'in':return d*0x48;default:return d;}}function buildInlineStyle(a){const b=[];for(const [c,d]of Object['entries'](a)){if(d===void 0x0||d==='')continue;const e=c['replace'](/([A-Z])/g,'-$1')['toLowerCase']();b['push'](e+':'+d);}return b['join'](';');}var HEADING_SIZES={'h1':0x18,'h2':0x14,'h3':0x10,'h4':0xe,'h5':0xc,'h6':0xa};function parseAlignment(a){switch(a['toLowerCase']()){case'center':return 0x1;case'right':return 0x2;case'justify':return 0x3;default:return 0x0;}}function parseVerticalAlign(a){switch(a['toLowerCase']()){case'middle':return'middle';case'bottom':return'bottom';default:return'top';}}function parseTabStops(a){return a['split'](/[\s,]+/)['filter'](b=>b&&/^-?[\d.]+\s*(px|pt|em|rem|cm|mm|in)?$/['test'](b['trim']()))['map'](b=>parseLengthPt(b))['filter'](b=>!isNaN(b)&&b>=0x0);}function parseBorderCss(a){const b=a['trim']()['split'](/\s+/);let c=0.5,d='borderStyle-solid',e=0x0;for(const f of b){if(/^\d+(\.\d+)?(px|pt)?$/['test'](f))c=parseFloat(f);else{if(['solid','dashed','dotted','double','none']['includes'](f))d=f==='none'?'borderStyle-none':'borderStyle-'+f;else(f['startsWith']('#')||f['startsWith']('rgb'))&&(e=cssToArgb(f));}}return{'width':c,'style':d,'color':e};}function parseHtml(a){const b=[],c=[{'kind':'root','blocks':[]}];let d=![];function e(){if(b['length']===0x0)return{'bold':![],'italic':![],'underline':![]};return b[b['length']-0x1];}function f(s){const t=e();b['push']({'bold':s['bold']??t['bold'],'italic':s['italic']??t['italic'],'underline':s['underline']??t['underline'],'fontFamily':s['fontFamily']??t['fontFamily'],'fontSize':s['fontSize']??t['fontSize'],'color':s['color']??t['color'],'backgroundColor':s['backgroundColor']??t['backgroundColor']});}function g(){if(b['length']>0x0)b['pop']();}function h(){return c[c['length']-0x1];}function i(s){c['push'](s);}function j(){return c['pop']();}function k(){const s=e();return{'fontFamily':s['fontFamily']??DEFAULT_TEXT_STYLE['fontFamily'],'fontSize':s['fontSize']??DEFAULT_TEXT_STYLE['fontSize'],'bold':s['bold']||d,'italic':s['italic'],'underline':s['underline'],'color':s['color']??DEFAULT_TEXT_STYLE['color'],'backgroundColor':s['backgroundColor']??DEFAULT_TEXT_STYLE['backgroundColor']};}function l(){for(let s=c['length']-0x1;s>=0x0;s--){if(c[s]['kind']==='paragraph')return c[s];}return null;}function m(){const s=l();if(s)return s;const t=createParagraph(),u={'kind':'paragraph','paragraph':t};return i(u),u;}function n(s){for(let t=c['length']-0x1;t>=0x0;t--){const u=c[t];switch(u['kind']){case'root':u['blocks']['push'](s);return;case'tableCell':u['blocks']['push'](s);return;case'list':u['blocks']['push'](s);return;case'div':u['blocks']['push'](s);return;default:continue;}}}function o(){let s=-0x1;for(const t of c){if(t['kind']==='list')s++;}return Math['max'](s,0x0);}function p(){for(let s=c['length']-0x1;s>=0x0;s--){if(c[s]['kind']==='list')return c[s];}return null;}const q=new Parser({'onopentag'(s,t){const u=s['toLowerCase']();if(u==='strong'||u==='b'){f({'bold':!![]});return;}if(u==='em'||u==='i'){f({'italic':!![]});return;}if(u==='u'){f({'underline':!![]});return;}if(u==='span'){const v={};if(t['style']){const w=parseInlineStyle(t['style']);if(w['fontFamily'])v['fontFamily']=w['fontFamily'];if(w['fontSize'])v['fontSize']=parseFontSize(w['fontSize']);if(w['color'])v['color']=cssToArgb(w['color']);if(w['backgroundColor'])v['backgroundColor']=cssToArgb(w['backgroundColor']);}f(v);return;}if(u in HEADING_SIZES){const x=HEADING_SIZES[u];f({'bold':!![],'fontSize':x});const y=createParagraph();i({'kind':'paragraph','paragraph':y});return;}if(u==='p'){const z=createParagraph();if(t['style']){const A=parseInlineStyle(t['style']);if(A['textAlign'])z['alignment']=parseAlignment(A['textAlign']);if(A['lineHeight']){const B=parseFloat(A['lineHeight']);if(!isNaN(B))z['lineSpacing']=B-0x1;}if(A['marginLeft'])z['leftIndent']=parseLengthPt(A['marginLeft']);if(A['marginRight'])z['rightIndent']=parseLengthPt(A['marginRight']);if(A['paddingLeft'])z['leftIndent']+=parseLengthPt(A['paddingLeft']);if(A['paddingRight'])z['rightIndent']+=parseLengthPt(A['paddingRight']);if(A['marginTop'])z['spaceBefore']=parseLengthPt(A['marginTop']);if(A['marginBottom'])z['spaceAfter']=parseLengthPt(A['marginBottom']);if(A['paddingTop'])z['spaceBefore']+=parseLengthPt(A['paddingTop']);if(A['paddingBottom'])z['spaceAfter']+=parseLengthPt(A['paddingBottom']);A['textIndent']&&(z['firstLineIndent']=parseLengthPt(A['textIndent']));if(A['tabStops']){const C=parseTabStops(A['tabStops']);if(C['length']>0x0)z['tabStops']=C;}if(A['color'])f({'color':cssToArgb(A['color'])});else f({});}else f({});i({'kind':'paragraph','paragraph':z});return;}if(u==='br'){const D=l();if(D){const E=j();if(E['kind']==='paragraph'){n(E['paragraph']);const F=createParagraph();i({'kind':'paragraph','paragraph':F});}else c['push'](E),D['paragraph']['runs']['push'](createTextRun(''));}else n(createParagraph());return;}if(u==='tab'){const G=m(),H=k();G['paragraph']['runs']['push']({'type':'tab','style':H});return;}if(u==='page-break'){const I=c['some'](J=>J['kind']==='tableCell');if(I)return;while(h()['kind']==='paragraph'){const J=j();n(J['paragraph']);}n({'type':'pageBreak'});return;}if(u==='img'){const K=t['src']||'',L=K['match'](/^data:image\/[^;]+;base64,(.+)$/);if(L){const M={'type':'image','data':L[0x1],'width':parseFloat(t['width'])||0x64,'height':parseFloat(t['height'])||0x64},N=m();N['paragraph']['runs']['push'](M);}return;}if(u==='table'){i({'kind':'table','rows':[]});return;}if(u==='tr'){i({'kind':'tableRow','cells':[]});return;}if(u==='td'||u==='th'){if(u==='th')d=!![];const O={};if(t['colspan']){const P=parseInt(t['colspan'],0xa);if(!isNaN(P)&&P>0x0)O['colspan']=P;}if(t['rowspan']){const Q=parseInt(t['rowspan'],0xa);if(!isNaN(Q)&&Q>0x0)O['rowspan']=Q;}if(t['style']){const R=parseInlineStyle(t['style']);if(R['backgroundColor'])O['fillColor']=cssToArgb(R['backgroundColor']);if(R['verticalAlign'])O['verticalAlign']=parseVerticalAlign(R['verticalAlign']);if(R['border']){const S=parseBorderCss(R['border']);O['borderWidth']=S['width'],O['borderColor']=S['color'],O['border']={'name':'borderCell','style':S['style']};}R['borderStyle']&&(O['border']={'name':'borderCell','style':R['borderStyle']==='none'?'borderStyle-none':'borderStyle-'+R['borderStyle']});}i({'kind':'tableCell','cell':O,'blocks':[]});return;}if(u==='ul'){const T=o()+(p()?0x1:0x0);i({'kind':'list','listType':'bulleted','level':T,'blocks':[]});return;}if(u==='ol'){const U=o()+(p()?0x1:0x0);i({'kind':'list','listType':'numbered','level':U,'blocks':[]});return;}if(u==='li'){const V=p();if(V){const W={'type':V['listType'],'level':V['level']};V['listType']==='bulleted'?W['bulletType']='BULLET_TYPE_ELLIPSE':W['numberType']='NUMBER_TYPE_NUMBER_DOT';const X=createParagraph({'list':W});i({'kind':'paragraph','paragraph':X}),f({});}return;}if(u==='div'){let Y=![];if(t['style']){const Z=parseInlineStyle(t['style']),a0=c['some'](a3=>a3['kind']==='tableCell'),a1=Z['pageBreakBefore']?.['toLowerCase']();if(!a0&&(a1==='always'||a1==='page')){while(h()['kind']==='paragraph'){const a3=j();n(a3['paragraph']);}n({'type':'pageBreak'});}const a2=Z['pageBreakAfter']?.['toLowerCase']();!a0&&(a2==='always'||a2==='page')&&(Y=!![]);}i({'kind':'div','blocks':[],'pendingAfter':Y});return;}},'ontext'(s){if(!s)return;const t=l();if(!t&&!s['trim']())return;const u=t??m(),v=k();u['paragraph']['runs']['push']({'type':'text','text':s,'style':v});},'onclosetag'(s){const t=s['toLowerCase']();if(t==='strong'||t==='b'||t==='em'||t==='i'||t==='u'||t==='span'){g();return;}if(t in HEADING_SIZES){g();const u=j();u['kind']==='paragraph'&&n(u['paragraph']);return;}if(t==='p'){g();const v=j();v['kind']==='paragraph'&&n(v['paragraph']);return;}if(t==='td'||t==='th'){if(t==='th')d=![];while(h()['kind']==='paragraph'){const x=j();n(x['paragraph']);}const w=j();if(w['kind']==='tableCell'){const y=createTableCell(w['blocks'],w['cell']),z=h();z['kind']==='tableRow'&&z['cells']['push'](y);}return;}if(t==='tr'){const A=j();if(A['kind']==='tableRow'){const B=createTableRow(A['cells']),C=h();C['kind']==='table'&&C['rows']['push'](B);}return;}if(t==='table'){const D=j();if(D['kind']==='table'&&D['rows']['length']>0x0){const E=Math['max'](...D['rows']['map'](H=>H['cells']['length'])),F=Array['from']({'length':E},()=>0x1),G=createTable(D['rows'],F);n(G);}return;}if(t==='li'){if(h()['kind']==='paragraph'){const H=j();n(H['paragraph']);}g();return;}if(t==='ul'||t==='ol'){const I=j();if(I['kind']==='list')for(const J of I['blocks']){n(J);}return;}if(t==='div'){while(h()['kind']==='paragraph'){const L=j();n(L['paragraph']);}const K=j();if(K['kind']==='div'){for(const M of K['blocks']){n(M);}K['pendingAfter']&&n({'type':'pageBreak'});}return;}}},{'decodeEntities':!![]});q['write'](a),q['end']();while(c['length']>0x1){const s=j();s['kind']==='paragraph'&&n(s['paragraph']);}const r=c[0x0];return{'pages':{...DEFAULT_PAGE_FORMAT},'body':r['blocks']};}import a1a from'jszip';function runeCount(a){return Array['from'](a)['length'];}function buildCdata(a){const b=[],c=[];let d=0x0,e=0x0;function f(i){const j=e++;if(i['runs']['length']===0x0)b['push'](''),d+=0x1;else for(const k of i['runs']){if(k['type']==='text'){const l=runeCount(k['text']);c['push']({'element':k,'startOffset':d,'length':l,'blockId':j}),b['push'](k['text']),d+=l;}else{if(k['type']==='image')c['push']({'element':k,'startOffset':d,'length':0x1,'blockId':j}),b['push'](''),d+=0x1;else k['type']==='tab'&&(c['push']({'element':k,'startOffset':d,'length':0x1,'blockId':j}),b['push']('\x09'),d+=0x1);}}b['push']('\x0a'),d+=0x1;}function g(i){for(const j of i['rows']){for(const k of j['cells']){h(k['content']);}}}function h(i){for(const j of i){if(j['type']==='paragraph')f(j);else{if(j['type']==='table')g(j);else j['type']==='pageBreak'&&(b['push']('\x0a'),d+=0x2,e++);}}}return h(a),{'cdata':b['join'](''),'entries':c};}function escapeAttr(a){return a['replace'](/&/g,'&')['replace'](/</g,'<')['replace'](/>/g,'>')['replace'](/"/g,'"');}function cellAlignAttr(a){if(a==='middle')return'vcenter';return a;}function serializePageFormat(a){return'<properties><pageFormat\x20mediaSizeName=\x22'+a['mediaSizeName']+'\x22\x20leftMargin=\x22'+a['leftMargin']['toFixed'](0x2)+'\x22\x20rightMargin=\x22'+a['rightMargin']['toFixed'](0x2)+'\x22\x20topMargin=\x22'+a['topMargin']['toFixed'](0x2)+'\x22\x20bottomMargin=\x22'+a['bottomMargin']['toFixed'](0x2)+'\x22\x20paperOrientation=\x22'+a['paperOrientation']+'\x22\x20headerFOffset=\x22'+a['headerFOffset']['toFixed'](0x1)+'\x22\x20footerFOffset=\x22'+a['footerFOffset']['toFixed'](0x1)+'\x22\x20/></properties>';}function fontAttributes(a){let b='\x20family=\x22'+escapeAttr(a['fontFamily'])+'\x22';b+='\x20size=\x22'+a['fontSize']+'\x22';if(a['bold'])b+='\x20bold=\x22true\x22';if(a['italic'])b+='\x20italic=\x22true\x22';if(a['underline'])b+='\x20underline=\x22true\x22';return a['color']!==-0x1000000&&(b+='\x20foreground=\x22'+a['color']+'\x22'),a['backgroundColor']!==-0x1&&(b+='\x20background=\x22'+a['backgroundColor']+'\x22'),b;}function entriesForBlock(a,b){return a['filter'](c=>c['blockId']===b);}function serializeParagraph(a,b,c=0x0){let d='<paragraph';d+='\x20Alignment=\x22'+a['alignment']+'\x22',d+='\x20LeftIndent=\x22'+a['leftIndent']['toFixed'](0x1)+'\x22',d+='\x20RightIndent=\x22'+a['rightIndent']['toFixed'](0x1)+'\x22';a['firstLineIndent']!==0x0&&(d+='\x20FirstLineIndent=\x22'+a['firstLineIndent']['toFixed'](0x2)+'\x22');a['lineSpacing']!==0x0&&(d+='\x20LineSpacing=\x22'+a['lineSpacing']['toFixed'](0x2)+'\x22');a['spaceBefore']!==0x0&&(d+='\x20SpaceAbove=\x22'+a['spaceBefore']['toFixed'](0x2)+'\x22');a['spaceAfter']!==0x0&&(d+='\x20SpaceBelow=\x22'+a['spaceAfter']['toFixed'](0x2)+'\x22');if(a['tabStops']&&a['tabStops']['length']>0x0){const e=a['tabStops']['map'](f=>f['toFixed'](0x2)+':0:0')['join'](',');d+='\x20TabSet=\x22'+e+'\x22';}if(a['list']){if(a['list']['type']==='numbered')d+='\x20Numbered=\x22true\x22',a['list']['numberType']&&(d+='\x20NumberType=\x22'+escapeAttr(a['list']['numberType'])+'\x22'),a['list']['listId']!==void 0x0&&(d+='\x20ListId=\x22'+a['list']['listId']+'\x22'),d+='\x20ListLevel=\x22'+a['list']['level']+'\x22';else a['list']['type']==='bulleted'&&(d+='\x20Bulleted=\x22true\x22',a['list']['bulletType']&&(d+='\x20BulletType=\x22'+escapeAttr(a['list']['bulletType'])+'\x22'),d+='\x20ListLevel=\x22'+a['list']['level']+'\x22');}d+='>';if(b['length']===0x0)d+='<content\x20startOffset=\x22'+c+'\x22\x20length=\x222\x22\x20family=\x22Times\x20New\x20Roman\x22\x20size=\x2210\x22\x20/>';else{const f=b['length']-0x1;for(let g=0x0;g<b['length'];g++){const h=b[g],j=g===f&&h['element']['type']==='text';if(h['element']['type']==='text'){const k=h['element'],l=h['length']+(j?0x1:0x0);d+='<content',d+='\x20startOffset=\x22'+h['startOffset']+'\x22',d+='\x20length=\x22'+l+'\x22',d+=fontAttributes(k['style']),d+='\x20/>';}else{if(h['element']['type']==='image'){const m=h['element'];d+='<image',d+='\x20imageData=\x22'+m['data']+'\x22',d+='\x20startOffset=\x22'+h['startOffset']+'\x22',d+='\x20length=\x221\x22',d+='\x20width=\x22'+m['width']['toFixed'](0x1)+'\x22',d+='\x20height=\x22'+m['height']['toFixed'](0x1)+'\x22',d+='\x20/>';}else{if(h['element']['type']==='tab'){const n=h['element'];d+='<tab',d+='\x20startOffset=\x22'+h['startOffset']+'\x22',d+='\x20length=\x221\x22',d+=fontAttributes(n['style']),d+='\x20/>';}}}}}return d+='</paragraph>\x0a',d;}function serializeTable(a,b,c,d){let e='<table';e+='\x20tableName=\x22'+escapeAttr(a['name'])+'\x22',e+='\x20columnCount=\x22'+a['columns']+'\x22';const f=a['columnWidths']['map'](g=>Math['round'](g)['toString']());e+='\x20columnSpans=\x22'+f['join'](',')+'\x22',e+='\x20border=\x22'+escapeAttr(a['border']['name'])+'\x22',e+='>';for(const g of a['rows']){e+=serializeRow(g,b,c,d);}return e+='</table>\x0a',e;}function serializeRow(a,b,c,d){let e='<row';e+='\x20rowName=\x22'+escapeAttr(a['name'])+'\x22',e+='\x20rowType=\x22'+escapeAttr(a['rowType'])+'\x22',e+='>';for(const f of a['cells']){e+=serializeCell(f,b,c,d);}return e+='</row>',e;}function serializeCell(a,b,c,d){let e='<cell';if(a['colspan']>0x1)e+='\x20colspan=\x22'+a['colspan']+'\x22';if(a['verticalAlign']!=='top')e+='\x20align=\x22'+cellAlignAttr(a['verticalAlign'])+'\x22';if(a['fillColor']!==0xffffff&&a['fillColor']!==-0x1)e+='\x20fillColor=\x22'+a['fillColor']+'\x22';return a['borderSpec']!==0x0&&(e+='\x20border=\x22'+escapeAttr(a['border']['name'])+'\x22',e+='\x20borderWidth=\x22'+a['borderWidth']['toFixed'](0x1)+'\x22',e+='\x20borderSpec=\x22'+a['borderSpec']+'\x22',e+='\x20borderColor=\x22'+a['borderColor']+'\x22',e+='\x20borderStyle=\x22'+escapeAttr(a['border']['style'])+'\x22'),e+='>',e+=serializeBlocks(a['content'],b,c,d),e+='</cell>',e;}function serializeBlocks(a,b,c,d){let e='';for(const f of a){if(f['type']==='paragraph'){const g=c['value']++,h=entriesForBlock(b,g);e+=serializeParagraph(f,h,d['value']);if(h['length']===0x0)d['value']+=0x2;else{const i=h[h['length']-0x1];d['value']=i['startOffset']+i['length']+0x1;}}else{if(f['type']==='table')e+=serializeTable(f,b,c,d);else{if(f['type']==='pageBreak'){c['value']++;const j=serializeParagraph(createParagraph(),[],d['value']);e+='<page-break>'+j['replace'](/\n$/,'')+'</page-break>\x0a',d['value']+=0x2;}}}}return e;}async function serializeUdf(a){const {cdata:b,entries:c}=buildCdata(a['body']);let d='<?xml\x20version=\x221.0\x22\x20encoding=\x22UTF-8\x22\x20?>\x0a';d+='<template\x20format_id=\x221.8\x22>\x0a',d+='<content><![CDATA['+b+']]></content>',d+=serializePageFormat(a['pages']),d+='\x0a',d+='<elements\x20resolver=\x22hvl-default\x22>\x0a';const e={'value':0x0},f={'value':0x0};d+=serializeBlocks(a['body'],c,e,f),d+='</elements>\x0a',d+='<styles>',d+='<style\x20name=\x22default\x22\x20description=\x22Geçerli\x22\x20family=\x22Dialog\x22\x20size=\x2212\x22\x20bold=\x22false\x22\x20italic=\x22false\x22\x20foreground=\x22-13421773\x22\x20FONT_ATTRIBUTE_KEY=\x22javax.swing.plaf.FontUIResource[family=Dialog,name=Dialog,style=plain,size=12]\x22\x20/>',d+='<style\x20name=\x22hvl-default\x22\x20family=\x22Times\x20New\x20Roman\x22\x20size=\x2212\x22\x20description=\x22Gövde\x22\x20/>',d+='</styles>\x0a',d+='</template>';const g=new a1a();g['file']('content.xml',d,{'compression':'DEFLATE'});const h=await g['generateAsync']({'type':'nodebuffer'});return h;}async function htmlToUdf(a){const b=parseHtml(a);return serializeUdf(b);}import a1b from'jszip';import{parseDocument}from'htmlparser2';import{Element,Text,CDATA}from'domhandler';function childElements(a){return a['children']['filter'](b=>b instanceof Element);}function findElement(a,b){return childElements(a)['find'](d=>d['name']===b);}function findAllElements(a,b){return childElements(a)['filter'](d=>d['name']===b);}function textContent(a){const b=[];for(const c of a['children']){if(c instanceof Text)b['push'](c['data']);else{if(c instanceof CDATA)for(const d of c['children']){d instanceof Text&&b['push'](d['data']);}}}return b['join']('');}function attrFloat(a,b,c=0x0){const d=a['attribs'][b];if(d===void 0x0||d==='')return c;const e=parseFloat(d);return isNaN(e)?c:e;}function attrInt(a,b,c=0x0){const d=a['attribs'][b];if(d===void 0x0||d==='')return c;const e=parseInt(d,0xa);return isNaN(e)?c:e;}function attrStr(a,b,c=''){return a['attribs'][b]??c;}function attrBool(a,b){const c=a['attribs'][b];return c==='true';}function parseAlignment2(a){switch(a){case'1':return 0x1;case'2':return 0x2;case'3':return 0x3;default:return 0x0;}}function parseVerticalAlign2(a){switch(a){case'vcenter':return'middle';case'bottom':return'bottom';default:return'top';}}function parseBorderStyle(a){const b=attrStr(a,'border',DEFAULT_BORDER['name']),c=attrStr(a,'borderStyle',DEFAULT_BORDER['style']);return{'name':b,'style':c};}function parsePageFormat(a){const b=findElement(a,'pageFormat');if(!b)return{...DEFAULT_PAGE_FORMAT};return{'mediaSizeName':attrInt(b,'mediaSizeName',DEFAULT_PAGE_FORMAT['mediaSizeName']),'leftMargin':attrFloat(b,'leftMargin',DEFAULT_PAGE_FORMAT['leftMargin']),'rightMargin':attrFloat(b,'rightMargin',DEFAULT_PAGE_FORMAT['rightMargin']),'topMargin':attrFloat(b,'topMargin',DEFAULT_PAGE_FORMAT['topMargin']),'bottomMargin':attrFloat(b,'bottomMargin',DEFAULT_PAGE_FORMAT['bottomMargin']),'paperOrientation':attrInt(b,'paperOrientation',DEFAULT_PAGE_FORMAT['paperOrientation']),'headerFOffset':attrFloat(b,'headerFOffset',DEFAULT_PAGE_FORMAT['headerFOffset']),'footerFOffset':attrFloat(b,'footerFOffset',DEFAULT_PAGE_FORMAT['footerFOffset'])};}function parseTextRun(a,b){const c=attrInt(a,'startOffset'),d=attrInt(a,'length');let e=b['slice'](c,c+d)['join']('');e=e['replace'](/\u200B/g,''),e=e['replace'](/\n$/,'');const f={'fontFamily':attrStr(a,'family',DEFAULT_TEXT_STYLE['fontFamily']),'fontSize':attrFloat(a,'size',DEFAULT_TEXT_STYLE['fontSize']),'bold':attrBool(a,'bold'),'italic':attrBool(a,'italic'),'underline':attrBool(a,'underline'),'color':attrInt(a,'foreground',DEFAULT_TEXT_STYLE['color']),'backgroundColor':attrInt(a,'background',DEFAULT_TEXT_STYLE['backgroundColor'])};return{'type':'text','text':e,'style':f};}function parseImageRun(a){return{'type':'image','data':attrStr(a,'imageData'),'width':attrFloat(a,'width'),'height':attrFloat(a,'height')};}function parseParagraph(a,b){const c=[];for(const i of childElements(a)){switch(i['name']){case'content':case'field':c['push'](parseTextRun(i,b));break;case'image':c['push'](parseImageRun(i));break;case'tab':{const j={'fontFamily':attrStr(i,'family',DEFAULT_TEXT_STYLE['fontFamily']),'fontSize':attrFloat(i,'size',DEFAULT_TEXT_STYLE['fontSize']),'bold':attrBool(i,'bold'),'italic':attrBool(i,'italic'),'underline':attrBool(i,'underline'),'color':attrInt(i,'foreground',DEFAULT_TEXT_STYLE['color']),'backgroundColor':attrInt(i,'background',DEFAULT_TEXT_STYLE['backgroundColor'])};c['push']({'type':'tab','style':j});break;}}}const d=c['filter'](k=>{if(k['type']==='text'&&k['text']==='')return![];return!![];}),e={'type':'paragraph','alignment':parseAlignment2(a['attribs']['Alignment']),'leftIndent':attrFloat(a,'LeftIndent'),'rightIndent':attrFloat(a,'RightIndent'),'firstLineIndent':attrFloat(a,'FirstLineIndent'),'lineSpacing':attrFloat(a,'LineSpacing'),'spaceBefore':attrFloat(a,'SpaceAbove'),'spaceAfter':attrFloat(a,'SpaceBelow'),'runs':d},f=attrBool(a,'Numbered'),g=attrBool(a,'Bulleted');if(f||g){const k={'type':f?'numbered':'bulleted','level':attrInt(a,'ListLevel')},l=a['attribs']['NumberType'];if(l)k['numberType']=l;const m=a['attribs']['BulletType'];if(m)k['bulletType']=m;const n=a['attribs']['ListId'];n!==void 0x0&&n!==''&&(k['listId']=parseInt(n,0xa)),e['list']=k;}const h=a['attribs']['TabSet'];if(h){const o=h['split'](/[,;]/)['map'](p=>parseFloat(p['split'](':')[0x0]))['filter'](p=>!isNaN(p));if(o['length']>0x0)e['tabStops']=o;}return e;}function parseTableCell(a,b){const c=[];for(const d of childElements(a)){if(d['name']==='paragraph')c['push'](parseParagraph(d,b));else d['name']==='table'&&c['push'](parseTable(d,b));}return{'colspan':attrInt(a,'colspan',0x1),'rowspan':attrInt(a,'rowspan',0x1),'verticalAlign':parseVerticalAlign2(a['attribs']['align']),'fillColor':attrInt(a,'fillColor',0xffffff),'border':parseBorderStyle(a),'borderWidth':attrFloat(a,'borderWidth',0.5),'borderColor':attrInt(a,'borderColor',0x0),'borderSpec':attrInt(a,'borderSpec',0xf),'content':c};}function parseTableRow(a,b){const c=[];for(const d of findAllElements(a,'cell')){c['push'](parseTableCell(d,b));}return{'name':attrStr(a,'rowName','row1'),'rowType':attrStr(a,'rowType','dataRow'),'height':attrFloat(a,'height'),'border':parseBorderStyle(a),'cells':c};}function parseTable(a,b){const c=[];for(const f of findAllElements(a,'row')){c['push'](parseTableRow(f,b));}const d=attrStr(a,'columnSpans'),e=d?d['split'](',')['map'](g=>parseFloat(g['trim']())):[];return{'type':'table','name':attrStr(a,'tableName','Sabit'),'columns':attrInt(a,'columnCount',e['length']),'columnWidths':e,'border':parseBorderStyle(a),'rows':c};}function parseElements(a,b){const c=[];for(const d of childElements(a)){if(d['name']==='paragraph')c['push'](parseParagraph(d,b));else{if(d['name']==='table')c['push'](parseTable(d,b));else d['name']==='page-break'&&c['push']({'type':'pageBreak'});}}return c;}async function parseUdf(a){const b=await a1b['loadAsync'](a),c=b['file']('content.xml');if(!c)throw new Error('UDF\x20file\x20does\x20not\x20contain\x20content.xml');const d=await c['async']('string'),e=parseDocument(d,{'xmlMode':!![]}),f=e['children']['find'](n=>n instanceof Element&&n['name']==='template');if(!f)throw new Error('Missing\x20<template>\x20root\x20element');const g=findElement(f,'content');if(!g)throw new Error('Missing\x20<content>\x20element');const h=textContent(g),i=Array['from'](h),j=findElement(f,'properties'),k=j?parsePageFormat(j):{...DEFAULT_PAGE_FORMAT},l=findElement(f,'elements'),m=l?parseElements(l,i):[];return{'pages':k,'body':m};}function escapeHtml(a){return a['replace'](/&/g,'&')['replace'](/</g,'<')['replace'](/>/g,'>');}function detectImageFormat(a){if(a['startsWith']('/9j/'))return'jpeg';if(a['startsWith']('iVBOR'))return'png';if(a['startsWith']('R0lGOD'))return'gif';if(a['startsWith']('UklGR'))return'webp';return'png';}function alignmentToCss(a){switch(a){case 0x1:return'center';case 0x2:return'right';case 0x3:return'justify';default:return void 0x0;}}function wrapStyled(a,b){const c={},d=b;d['fontFamily']!==DEFAULT_TEXT_STYLE['fontFamily']&&(c['fontFamily']=d['fontFamily']);d['fontSize']!==DEFAULT_TEXT_STYLE['fontSize']&&(c['fontSize']=d['fontSize']+'pt');d['color']!==DEFAULT_TEXT_STYLE['color']&&(c['color']=argbToCss(d['color']));d['backgroundColor']!==DEFAULT_TEXT_STYLE['backgroundColor']&&(c['backgroundColor']=argbToCss(d['backgroundColor']));const e=Object['keys'](c)['length']>0x0,f=e?buildInlineStyle(c):'';let g=a;return d['underline']&&(g='<u>'+g+'</u>'),d['italic']&&(g='<em>'+g+'</em>'),d['bold']&&(g='<strong>'+g+'</strong>'),e&&(g='<span\x20style=\x22'+f+'\x22>'+g+'</span>'),g;}function serializeTextRun(a){const b=escapeHtml(a['text']);if(!b&&!a['style']['bold']&&!a['style']['italic']&&!a['style']['underline'])return'';return wrapStyled(b,a['style']);}function serializeTabRun(a){const b=a['style'],c=b['fontFamily']===DEFAULT_TEXT_STYLE['fontFamily']&&b['fontSize']===DEFAULT_TEXT_STYLE['fontSize']&&b['color']===DEFAULT_TEXT_STYLE['color']&&b['backgroundColor']===DEFAULT_TEXT_STYLE['backgroundColor']&&!b['bold']&&!b['italic']&&!b['underline'];if(c)return'<tab/>';return wrapStyled('<tab/>',b);}function serializeImageRun(a){const b=detectImageFormat(a['data']);return'<img\x20src=\x22data:image/'+b+';base64,'+a['data']+'\x22\x20width=\x22'+a['width']+'\x22\x20height=\x22'+a['height']+'\x22\x20/>';}function serializeInline(a){if(a['type']==='text')return serializeTextRun(a);if(a['type']==='image')return serializeImageRun(a);if(a['type']==='tab')return serializeTabRun(a);return'';}function buildParagraphStyle(a){const b={},c=alignmentToCss(a['alignment']);if(c)b['textAlign']=c;return a['lineSpacing']!==0x0&&(b['lineHeight']=String(0x1+a['lineSpacing'])),a['spaceBefore']!==0x0&&(b['marginTop']=a['spaceBefore']+'pt'),a['spaceAfter']!==0x0&&(b['marginBottom']=a['spaceAfter']+'pt'),a['leftIndent']!==0x0&&(b['marginLeft']=a['leftIndent']+'pt'),a['rightIndent']!==0x0&&(b['marginRight']=a['rightIndent']+'pt'),a['firstLineIndent']!==0x0&&(b['textIndent']=a['firstLineIndent']+'pt'),a['tabStops']&&a['tabStops']['length']>0x0&&(b['tabStops']=a['tabStops']['map'](d=>d+'pt')['join']('\x20')),buildInlineStyle(b);}function serializeTableCell(a){const b=[];a['colspan']>0x1&&b['push']('colspan=\x22'+a['colspan']+'\x22');a['rowspan']>0x1&&b['push']('rowspan=\x22'+a['rowspan']+'\x22');const c={};if(a['border']['style']!=='borderStyle-none'){const h=argbToCss(a['borderColor']),i=a['borderWidth']||0.5;if(a['borderSpec']===0xf)c['border']=i+'px\x20solid\x20'+h;else{if(a['borderSpec']&0x1)c['borderTop']=i+'px\x20solid\x20'+h;if(a['borderSpec']&0x2)c['borderRight']=i+'px\x20solid\x20'+h;if(a['borderSpec']&0x4)c['borderBottom']=i+'px\x20solid\x20'+h;if(a['borderSpec']&0x8)c['borderLeft']=i+'px\x20solid\x20'+h;}}c['padding']='4px';const d=argbToCss(a['fillColor']);d!=='#ffffff'&&d!=='#000000'&&(c['backgroundColor']=d);a['fillColor']!==0xffffff&&a['fillColor']!==-0x1&&(c['backgroundColor']=d);a['verticalAlign']!=='top'&&(c['verticalAlign']=a['verticalAlign']);const e=buildInlineStyle(c);if(e)b['push']('style=\x22'+e+'\x22');const f=b['length']>0x0?'\x20'+b['join']('\x20'):'',g=a['content']['map'](serializeBlock)['join']('');return'<td'+f+'>'+g+'</td>';}function serializeTable2(a){const b=a['rows']['map'](c=>{const d=c['cells']['map'](serializeTableCell)['join']('');return'<tr>'+d+'</tr>';})['join']('');return'<table\x20style=\x22border-collapse:collapse\x22>'+b+'</table>';}function serializeListGroup(a){const b=a['type']==='numbered'?'ol':'ul',c=a['paragraphs']['map'](d=>{const e=d['runs']['map'](serializeInline)['join']('');return'<li>'+e+'</li>';})['join']('');return'<'+b+'>'+c+'</'+b+'>';}function serializeParagraph2(a){const b=a['runs']['map'](serializeInline)['join'](''),c=buildParagraphStyle(a),d=c?'\x20style=\x22'+c+'\x22':'',e=b||'<br\x20/>';return'<p'+d+'>'+e+'</p>';}function serializeBlock(a){if(a['type']==='paragraph'){if(a['list']){const b=a['list']['type']==='numbered'?'ol':'ul',c=a['runs']['map'](serializeInline)['join']('');return'<'+b+'><li>'+c+'</li></'+b+'>';}return serializeParagraph2(a);}if(a['type']==='table')return serializeTable2(a);if(a['type']==='pageBreak')return'<page-break/>';return'';}function serializeBlocks2(a){const b=[];let c=0x0;while(c<a['length']){const d=a[c];if(d['type']==='paragraph'&&d['list']){const e=d['list']['type'],f={'type':e,'level':d['list']['level'],'paragraphs':[]};while(c<a['length']&&a[c]['type']==='paragraph'&&a[c]['list']?.['type']===e){f['paragraphs']['push'](a[c]),c++;}b['push'](serializeListGroup(f));}else b['push'](serializeBlock(d)),c++;}return b['join']('');}function serializeHtml(a){return serializeBlocks2(a['body']);}async function udfToHtml(a){const b=await parseUdf(a);return serializeHtml(b);}function escapeMarkdown(a){return a['replace'](/\\/g,'\x5c\x5c')['replace'](/\|/g,'\x5c|')['replace'](/\[/g,'\x5c[')['replace'](/\]/g,'\x5c]');}function serializeRun(a){if(a['type']==='tab')return'\x09';if(a['type']==='image'){const d=a;return'';}const b=a;let c=escapeMarkdown(b['text']);if(c['trim']()===''||c==='')return c===''?'':c;if(b['style']['bold']&&b['style']['italic'])c='***'+c+'***';else{if(b['style']['bold'])c='**'+c+'**';else b['style']['italic']&&(c='*'+c+'*');}return c;}function serializeParagraphContent(a){return a['runs']['map'](serializeRun)['join']('');}function serializeParagraph3(a){const b=serializeParagraphContent(a);if(!b['trim']())return'';return b;}function serializeTableRow(a){return'|\x20'+a['join']('\x20|\x20')+'\x20|';}function serializeTable3(a){const b=[];for(let c=0x0;c<a['rows']['length'];c++){const d=a['rows'][c],e=d['cells']['map'](f=>{const g=[];for(const h of f['content']){if(h['type']==='paragraph'){const j=serializeParagraph3(h);if(j)g['push'](j);}else h['type']==='table'&&g['push'](flattenTable(h));}return g['join']('\x20')||'\x20';});b['push'](serializeTableRow(e));if(c===0x0){const f=d['cells']['map'](g=>{const h=g['content']['find'](k=>k['type']==='paragraph'),j=h?.['alignment']??0x0;switch(j){case 0x1:return':---:';case 0x2:return'---:';default:return'---';}});b['push']('|\x20'+f['join']('\x20|\x20')+'\x20|');}}return b['join']('\x0a');}function flattenTable(a){const b=[];for(const c of a['rows']){const d=c['cells']['map'](e=>{return e['content']['filter'](f=>f['type']==='paragraph')['map'](f=>serializeParagraph3(f))['filter'](Boolean)['join']('\x20');});b['push'](d['join']('\x20/\x20'));}return b['join'](';\x20');}function serializeMarkdown(a){const b=[],c=a['body'];let d=0x0;while(d<c['length']){const f=c[d];if(f['type']==='pageBreak'){b['push'](''),b['push']('---'),b['push'](''),d++;continue;}if(f['type']==='table'){b['push'](''),b['push'](serializeTable3(f)),b['push'](''),d++;continue;}const g=f;if(g['list']){const k=[];let l=d,m=0x1;while(l<c['length']&&c[l]['type']==='paragraph'&&c[l]['list']){const n=c[l],o=serializeParagraphContent(n),p='\x20\x20'['repeat'](n['list']['level']);n['list']['type']==='numbered'?(k['push'](''+p+m+'.\x20'+o),m++):k['push'](p+'-\x20'+o),l++;}b['push'](''),b['push'](...k),b['push'](''),d=l;continue;}const h=serializeParagraph3(g);if(!h['trim']()){b['push'](''),d++;continue;}b['push'](h),d++;}const e=b['join']('\x0a')['replace'](/\n{3,}/g,'\x0a\x0a')['trim']();return e+'\x0a';}async function udfToMarkdown(a){const b=await parseUdf(a);return serializeMarkdown(b);}function parseMarkdown(a){const b=a['split']('\x0a'),c={'body':[],'pos':0x0,'lines':b};while(c['pos']<c['lines']['length']){const d=c['lines'][c['pos']];if(d['trim']()===''){c['pos']++;continue;}if(d['trimStart']()['startsWith']('|')){parseTable2(c);continue;}if(/^\s*[-*+]\s/['test'](d)){parseList(c,'bulleted');continue;}if(/^\s*\d+\.\s/['test'](d)){parseList(c,'numbered');continue;}const e=d['match'](/^(#{1,6})\s+(.+)$/);if(e){const g=e[0x1]['length'],h={0x1:0x18,0x2:0x14,0x3:0x10,0x4:0xe,0x5:0xc,0x6:0xa},i=parseInline(e[0x2],{...DEFAULT_TEXT_STYLE,'bold':!![],'fontSize':h[g]||0xc});c['body']['push'](createParagraph({'runs':i,'alignment':0x0})),c['pos']++;continue;}const f=parseInline(d,{...DEFAULT_TEXT_STYLE});c['body']['push'](createParagraph({'runs':f})),c['pos']++;}return{'pages':{...DEFAULT_PAGE_FORMAT},'body':c['body']};}function parseInline(a,b){const c=[];let d=a;while(d['length']>0x0){const e=d['match'](/^\*\*\*(.+?)\*\*\*/);if(e){c['push'](createTextRun(e[0x1],{...b,'bold':!![],'italic':!![]})),d=d['slice'](e[0x0]['length']);continue;}const f=d['match'](/^\*\*(.+?)\*\*/);if(f){c['push'](createTextRun(f[0x1],{...b,'bold':!![]})),d=d['slice'](f[0x0]['length']);continue;}const g=d['match'](/^\*(.+?)\*/);if(g){c['push'](createTextRun(g[0x1],{...b,'italic':!![]})),d=d['slice'](g[0x0]['length']);continue;}const h=d['match'](/^!\[([^\]]*)\]\(data:image\/[^;]+;base64,([^)]+)\)/);if(h){c['push']({'type':'image','data':h[0x2],'width':0xc8,'height':0x96}),d=d['slice'](h[0x0]['length']);continue;}const i=d['match'](/^[^*!\[\\]+/);if(i){c['push'](createTextRun(i[0x0],b)),d=d['slice'](i[0x0]['length']);continue;}if(d['startsWith']('\x5c')&&d['length']>0x1){c['push'](createTextRun(d[0x1],b)),d=d['slice'](0x2);continue;}c['push'](createTextRun(d[0x0],b)),d=d['slice'](0x1);}return mergeRuns(c);}function mergeRuns(a){if(a['length']<=0x1)return a;const b=[a[0x0]];for(let c=0x1;c<a['length'];c++){const d=b[b['length']-0x1],e=a[c];d['type']==='text'&&e['type']==='text'&&stylesEqual(d['style'],e['style'])?b[b['length']-0x1]=createTextRun(d['text']+e['text'],d['style']):b['push'](e);}return b;}function stylesEqual(c,d){return c['fontFamily']===d['fontFamily']&&c['fontSize']===d['fontSize']&&c['bold']===d['bold']&&c['italic']===d['italic']&&c['underline']===d['underline']&&c['color']===d['color']&&c['backgroundColor']===d['backgroundColor'];}function parseList(a,b){const c=b==='numbered'?/^(\s*)\d+\.\s(.+)$/:/^(\s*)[-*+]\s(.+)$/;let d=0x1;while(a['pos']<a['lines']['length']){const e=a['lines'][a['pos']],f=e['match'](c);if(!f)break;const g=f[0x1]['length'],h=Math['floor'](g/0x2),i=f[0x2],j=parseInline(i,{...DEFAULT_TEXT_STYLE}),k={'type':b,'level':h,'listId':d,...b==='numbered'?{'numberType':'NUMBER_TYPE_NUMBER_DOT'}:{'bulletType':'BULLET_TYPE_ELLIPSE'}};a['body']['push'](createParagraph({'runs':j,'list':k})),a['pos']++;}}function parseTable2(a){const b=[];while(a['pos']<a['lines']['length']){const f=a['lines'][a['pos']]['trim']();if(!f['startsWith']('|'))break;const g=f['split']('|')['slice'](0x1,-0x1)['map'](h=>h['trim']());if(g['every'](h=>/^:?-{2,}:?$/['test'](h))){a['pos']++;continue;}b['push'](g),a['pos']++;}if(b['length']===0x0)return;const c=Math['max'](...b['map'](h=>h['length'])),d=Array(c)['fill'](Math['round'](0x12c/c)),e=b['map']((h,j)=>{const k=[];for(let l=0x0;l<c;l++){const m=h[l]||'',n=parseInline(m,{...DEFAULT_TEXT_STYLE}),o=createParagraph({'runs':n});k['push'](createTableCell([o]));}return createTableRow(k,{'name':'row'+(j+0x1)});});a['body']['push'](createTable(e,d));}async function markdownToUdf(a){const b=parseMarkdown(a);return serializeUdf(b);}export{Alignment,DEFAULT_TEXT_STYLE,DEFAULT_PAGE_FORMAT,DEFAULT_BORDER,createParagraph,createTextRun,createTable,createTableCell,createTableRow,htmlToUdf,udfToHtml,udfToMarkdown,markdownToUdf};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{existsSync}from'fs';import{homedir}from'os';import{join}from'path';function candidatePaths(){const a=homedir();switch(process['platform']){case'darwin':return[join(a,'.local/lib/libakisp11.dylib'),'/usr/local/lib/libakisp11.dylib','/usr/local/lib/eTPKCS11.dylib','/usr/local/lib/libgtop11dotnet.dylib','/Library/OpenSC/lib/opensc-pkcs11.so'];case'linux':return[join(a,'.local/lib/libakisp11.so'),'/usr/local/lib/libakisp11.so','/usr/lib/libakisp11.so','/usr/lib/eTPKCS11.so','/usr/lib/x86_64-linux-gnu/opensc-pkcs11.so'];case'win32':return['C:\x5cWindows\x5cSystem32\x5cakisp11.dll','C:\x5cWindows\x5cSystem32\x5ceTPKCS11.dll','C:\x5cWindows\x5cSystem32\x5cgtop11dotnet.dll'];default:return[];}}function resolveModules(a){if(a)return[a];const b=process['env']['UDF_PKCS11_MODULE'];if(b)return[b];return candidatePaths()['filter'](c=>existsSync(c));}export{candidatePaths,resolveModules};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{execFileSync}from'child_process';function promptPinGui(a='udf-cli',b='UYAP\x20e-imza\x20PIN'){switch(process['platform']){case'darwin':return macPrompt(a,b);case'linux':return linuxPrompt(a,b);case'win32':return windowsPrompt(a,b);default:throw new Error('GUI\x20PIN\x20prompt\x20unsupported\x20on\x20'+process['platform']+';\x20pass\x20--pin\x20or\x20set\x20UDF_PIN');}}var noGui=()=>new Error('Could\x20not\x20open\x20a\x20GUI\x20PIN\x20dialog\x20(no\x20desktop\x20session,\x20or\x20cancelled).\x20Pass\x20--pin\x20or\x20set\x20UDF_PIN.');function macPrompt(a,b){const c=d=>'\x22'+d['replace'](/\\/g,'\x5c\x5c')['replace'](/"/g,'\x5c\x22')+'\x22';try{const d=execFileSync('osascript',['-e','display\x20dialog\x20'+c(b)+'\x20default\x20answer\x20\x22\x22\x20with\x20hidden\x20answer\x20buttons\x20{\x22İptal\x22,\x20\x22Tamam\x22}\x20default\x20button\x20\x22Tamam\x22\x20cancel\x20button\x20\x22İptal\x22\x20with\x20title\x20'+c(a),'-e','text\x20returned\x20of\x20result'],{'encoding':'utf8','stdio':['ignore','pipe','pipe']});return d['replace'](/\r?\n$/,'');}catch{throw noGui();}}function linuxPrompt(a,b){const c=[['zenity',['--password','--title='+a]],['kdialog',['--password',b,'--title',a]]];for(const [d,e]of c){try{const f=execFileSync(d,e,{'encoding':'utf8','stdio':['ignore','pipe','pipe']});return f['replace'](/\r?\n$/,'');}catch(g){if(g['code']==='ENOENT')continue;throw noGui();}}throw new Error('No\x20GUI\x20PIN\x20dialog\x20available\x20(install\x20zenity\x20or\x20kdialog),\x20or\x20pass\x20--pin\x20/\x20set\x20UDF_PIN.');}function windowsPrompt(a,b){const c=e=>'\x27'+e['replace'](/'/g,'\x27\x27')+'\x27',d=['Add-Type\x20-AssemblyName\x20System.Windows.Forms,System.Drawing','$f=New-Object\x20Windows.Forms.Form;\x20$f.Text='+c(a)+';\x20$f.Width=340;\x20$f.Height=160;\x20$f.TopMost=$true;\x20$f.StartPosition=\x27CenterScreen\x27','$l=New-Object\x20Windows.Forms.Label;\x20$l.Text='+c(b)+';\x20$l.AutoSize=$true;\x20$l.Top=12;\x20$l.Left=12;\x20$f.Controls.Add($l)','$t=New-Object\x20Windows.Forms.TextBox;\x20$t.UseSystemPasswordChar=$true;\x20$t.Top=40;\x20$t.Left=12;\x20$t.Width=300;\x20$f.Controls.Add($t)','$b=New-Object\x20Windows.Forms.Button;\x20$b.Text=\x27Tamam\x27;\x20$b.Top=75;\x20$b.Left=232;\x20$b.DialogResult=\x27OK\x27;\x20$f.AcceptButton=$b;\x20$f.Controls.Add($b)','if($f.ShowDialog()\x20-eq\x20\x27OK\x27){[Console]::Out.Write($t.Text)}else{exit\x201}']['join'](';\x20');try{return execFileSync('powershell',['-NoProfile','-STA','-Command',d],{'encoding':'utf8','stdio':['ignore','pipe','pipe']});}catch{throw noGui();}}export{promptPinGui};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{readFile,writeFile}from'fs/promises';import a4a from'jszip';async function readContentXml(a){const b=await a4a['loadAsync'](a),c=b['file']('content.xml');if(!c)throw new Error('content.xml\x20not\x20found\x20in\x20.udf');return new Uint8Array(await c['async']('uint8array'));}async function writeSignature(a,b){const c=await a4a['loadAsync'](a),d=c['file']('content.xml');if(!d)throw new Error('content.xml\x20not\x20found\x20in\x20.udf');return c['file']('sign.sgn',b),c['generateAsync']({'type':'uint8array','compression':'DEFLATE'});}import{AsnConvert,OctetString}from'@peculiar/asn1-schema';import{ContentInfo,SignedData,SignerInfo,SignerInfos,SignerIdentifier,IssuerAndSerialNumber,EncapsulatedContentInfo,Attribute,DigestAlgorithmIdentifiers,CertificateSet,CertificateChoices}from'@peculiar/asn1-cms';import{AlgorithmIdentifier,Certificate,GeneralName,GeneralNames}from'@peculiar/asn1-x509';import{SigningCertificateV2,ESSCertIDv2,IssuerSerial}from'@peculiar/asn1-ess';import*as a4b from'asn1js';import{createHash}from'crypto';function sha256(a){return new Uint8Array(createHash('sha256')['update'](a)['digest']());}var OID_PKCS7_DATA='1.2.840.113549.1.7.1',OID_SIGNED_DATA='1.2.840.113549.1.7.2',OID_CONTENT_TYPE='1.2.840.113549.1.9.3',OID_MESSAGE_DIGEST='1.2.840.113549.1.9.4',OID_SIGNING_TIME='1.2.840.113549.1.9.5',OID_SIGNING_CERTIFICATE_V2='1.2.840.113549.1.9.16.2.47',OID_SHA256='2.16.840.1.101.3.4.2.1',OID_SHA256_WITH_RSA='1.2.840.113549.1.1.11',DER_NULL=new Uint8Array([0x5,0x0])['buffer'];function attr(a,b){return new Attribute({'attrType':a,'attrValues':[b]});}function toAb(a){return a['buffer']['slice'](a['byteOffset'],a['byteOffset']+a['byteLength']);}function algoSha256(){return new AlgorithmIdentifier({'algorithm':OID_SHA256});}function algoRsaSha256(){return new AlgorithmIdentifier({'algorithm':OID_SHA256_WITH_RSA,'parameters':DER_NULL});}function derLen(a){if(a<0x80)return new Uint8Array([a]);const b=[];let c=a;while(c>0x0){b['unshift'](c&0xff),c>>=0x8;}return new Uint8Array([0x80|b['length'],...b]);}function derSetOf(a){const b=a['reduce']((g,h)=>g+h['length'],0x0),c=derLen(b),d=new Uint8Array(0x1+c['length']+b);d[0x0]=0x31,d['set'](c,0x1);let f=0x1+c['length'];for(const g of a){d['set'](g,f),f+=g['length'];}return d;}function buildSigningCertificateV2(a,b){const c=new ESSCertIDv2({'certHash':new OctetString(toAb(sha256(b))),'issuerSerial':new IssuerSerial({'issuer':new GeneralNames([new GeneralName({'directoryName':a['tbsCertificate']['issuer']})]),'serialNumber':a['tbsCertificate']['serialNumber']})});return AsnConvert['serialize'](new SigningCertificateV2({'certs':[c]}));}function buildSignSgn(a){const {contentXml:b,certChainDer:c,sign:d,signingTime:e}=a,f=c[0x0],g=AsnConvert['parse'](toAb(f),Certificate),h=new a4b['ObjectIdentifier']({'value':OID_PKCS7_DATA})['toBER'](),i=new a4b['OctetString']({'valueHex':toAb(sha256(b))})['toBER'](),j=new a4b['UTCTime']({'valueDate':e})['toBER'](),k=buildSigningCertificateV2(g,f);let l=[attr(OID_CONTENT_TYPE,h),attr(OID_MESSAGE_DIGEST,i),attr(OID_SIGNING_TIME,j),attr(OID_SIGNING_CERTIFICATE_V2,k)];const m=l['map'](t=>({'a':t,'der':new Uint8Array(AsnConvert['serialize'](t))}))['sort']((t,u)=>cmpBytes(t['der'],u['der']));l=m['map'](t=>t['a']);const n=derSetOf(m['map'](t=>t['der'])),o=d(n),p=new SignerInfo({'version':0x1,'sid':new SignerIdentifier({'issuerAndSerialNumber':new IssuerAndSerialNumber({'issuer':g['tbsCertificate']['issuer'],'serialNumber':g['tbsCertificate']['serialNumber']})}),'digestAlgorithm':algoSha256(),'signedAttrs':l,'signatureAlgorithm':algoRsaSha256(),'signature':new OctetString(toAb(o))}),q=new CertificateSet(c['map'](t=>new CertificateChoices({'certificate':AsnConvert['parse'](toAb(t),Certificate)}))),r=new SignedData({'version':0x1,'digestAlgorithms':new DigestAlgorithmIdentifiers([algoSha256()]),'encapContentInfo':new EncapsulatedContentInfo({'eContentType':OID_PKCS7_DATA}),'certificates':q,'signerInfos':new SignerInfos([p])}),s=new ContentInfo({'contentType':OID_SIGNED_DATA,'content':AsnConvert['serialize'](r)});return new Uint8Array(AsnConvert['serialize'](s));}function cmpBytes(c,d){const e=Math['min'](c['length'],d['length']);for(let f=0x0;f<e;f++){if(c[f]!==d[f])return c[f]-d[f];}return c['length']-d['length'];}import a4c from'koffi';import{AsnConvert as a4d}from'@peculiar/asn1-schema';import{Certificate as a4e,KeyUsage,id_ce_keyUsage}from'@peculiar/asn1-x509';function toAb2(a){return a['buffer']['slice'](a['byteOffset'],a['byteOffset']+a['byteLength']);}function selectSigningCert(a){for(let b=0x0;b<a['length'];b++){const c=a4d['parse'](toAb2(a[b]),a4e),d=(c['tbsCertificate']['extensions']??[])['find'](f=>f['extnID']===id_ce_keyUsage);if(!d)continue;const e=a4d['parse'](d['extnValue']['buffer'],KeyUsage);if(e['toJSON']()['includes']('nonRepudiation'))return b;}return 0x0;}var CKF_SERIAL_SESSION=0x4,CKU_USER=0x1,CKO_CERTIFICATE=0x2,CKO_PRIVATE_KEY=0x3,CKA_CLASS=0x0,CKA_VALUE=0x11,CKA_ID=0x102,CKM_SHA256_RSA_PKCS=0x40,CKM_RSA_PKCS=0x1,CKR_PIN_INCORRECT=0xa0,CKR_PIN_LOCKED=0xa4,CKR_MECHANISM_INVALID=0x70,SHA256_DIGESTINFO_PREFIX=new Uint8Array([0x30,0x31,0x30,0xd,0x6,0x9,0x60,0x86,0x48,0x1,0x65,0x3,0x4,0x2,0x1,0x5,0x0,0x4,0x20]);function openSession(a,b){const c=Array['isArray'](a)?a:[a];if(c['length']===0x0)throw new Error('No\x20PKCS#11\x20driver\x20found.\x20Install\x20your\x20card\x20software\x20(e.g.\x20AKİS),\x20pass\x20--module,\x20or\x20set\x20UDF_PKCS11_MODULE.');let d;const f=[];for(const y of c){try{d=a4c['load'](y);break;}catch(z){f['push'](y+':\x20'+z['message']);}}if(!d)throw new Error('Could\x20not\x20load\x20any\x20PKCS#11\x20driver:\x0a\x20\x20'+f['join']('\x0a\x20\x20')+'\x0aPass\x20--module\x20or\x20set\x20UDF_PKCS11_MODULE.');const g='unsigned\x20long',h=d['func']('unsigned\x20long\x20C_Initialize(void\x20*)'),i=d['func']('unsigned\x20long\x20C_GetSlotList(bool,\x20_Out_\x20'+g+'\x20*,\x20_Inout_\x20'+g+'\x20*)'),j=d['func']('unsigned\x20long\x20C_OpenSession('+g+',\x20'+g+',\x20void\x20*,\x20void\x20*,\x20_Out_\x20'+g+'\x20*)'),k=d['func']('unsigned\x20long\x20C_Login('+g+',\x20'+g+',\x20const\x20char\x20*,\x20'+g+')'),l=d['func']('unsigned\x20long\x20C_FindObjectsInit('+g+',\x20void\x20*,\x20'+g+')'),m=d['func']('unsigned\x20long\x20C_FindObjects('+g+',\x20_Out_\x20'+g+'\x20*,\x20'+g+',\x20_Out_\x20'+g+'\x20*)'),n=d['func']('unsigned\x20long\x20C_FindObjectsFinal('+g+')'),o=d['func']('unsigned\x20long\x20C_GetAttributeValue('+g+',\x20'+g+',\x20void\x20*,\x20'+g+')'),q=d['func']('unsigned\x20long\x20C_SignInit('+g+',\x20void\x20*,\x20'+g+')'),r=d['func']('unsigned\x20long\x20C_Sign('+g+',\x20const\x20uint8_t\x20*,\x20'+g+',\x20_Out_\x20uint8_t\x20*,\x20_Inout_\x20'+g+'\x20*)'),s=d['func']('unsigned\x20long\x20C_Logout('+g+')'),t=d['func']('unsigned\x20long\x20C_CloseSession('+g+')'),u=d['func']('unsigned\x20long\x20C_Finalize(void\x20*)'),v=(A,B)=>{if(A!==0x0)throw new Error('PKCS#11\x20'+B+'\x20failed:\x200x'+A['toString'](0x10));};v(h(null),'C_Initialize');let w;const x=()=>{try{if(w!==void 0x0)s(w);}catch{}try{if(w!==void 0x0)t(w);}catch{}try{u(null);}catch{}};try{const A=[0x0];v(i(!![],null,A),'C_GetSlotList(count)');if(A[0x0]<0x1)throw new Error('no\x20PKCS#11\x20token\x20present');const B=new Array(A[0x0])['fill'](0x0);v(i(!![],B,A),'C_GetSlotList');const C=B[0x0],D=[0x0];v(j(C,CKF_SERIAL_SESSION,null,null,D),'C_OpenSession'),w=D[0x0];const E=k(w,CKU_USER,b,Buffer['byteLength'](b,'utf8'));if(E===CKR_PIN_INCORRECT)throw new Error('PIN\x20incorrect\x20—\x20aborting.\x20Do\x20NOT\x20retry;\x20the\x20card\x20locks\x20after\x20~3\x20attempts.');if(E===CKR_PIN_LOCKED)throw new Error('PIN\x20is\x20locked\x20—\x20unlock\x20the\x20card\x20with\x20its\x20PUK\x20before\x20signing.');v(E,'C_Login');const F=a4c['struct']('CK_ATTRIBUTE',{'type':'unsigned\x20long','pValue':'void\x20*','ulValueLen':'unsigned\x20long'}),G=T=>{const U=T['map'](W=>({'type':W['type'],'pValue':W['value'],'ulValueLen':W['value']?W['value']['length']:0x0}));v(l(w,a4c['as'](U,a4c['array'](F,U['length'])),U['length']),'C_FindObjectsInit');const V=[];for(;;){const W=[0x0],X=[0x0];v(m(w,X,0x1,W),'C_FindObjects');if(W[0x0]===0x0)break;V['push'](X[0x0]);}return v(n(w),'C_FindObjectsFinal'),V;},H=(T,U)=>{const V=[{'type':U,'pValue':null,'ulValueLen':0x0}];v(o(w,T,a4c['as'](V,a4c['array'](F,0x1)),0x1),'C_GetAttributeValue(len)');const W=Number(V[0x0]['ulValueLen']),X=Buffer['alloc'](W),Y=[{'type':U,'pValue':X,'ulValueLen':W}];return v(o(w,T,a4c['as'](Y,a4c['array'](F,0x1)),0x1),'C_GetAttributeValue'),X;},I=a4c['sizeof']('unsigned\x20long'),J=T=>{const U=Buffer['alloc'](I);if(I===0x8)U['writeBigUInt64LE'](BigInt(T));else U['writeUInt32LE'](T);return U;},K=G([{'type':CKA_CLASS,'value':J(CKO_CERTIFICATE)}]);if(K['length']===0x0)throw new Error('no\x20certificate\x20found\x20on\x20token');const L=K['map'](T=>({'der':new Uint8Array(H(T,CKA_VALUE)),'id':H(T,CKA_ID)})),M=L[selectSigningCert(L['map'](T=>T['der']))],N=G([{'type':CKA_CLASS,'value':J(CKO_PRIVATE_KEY)}]);if(N['length']===0x0)throw new Error('no\x20private\x20key\x20found\x20on\x20token');let O;for(const T of N){if(H(T,CKA_ID)['equals'](M['id'])){O=T;break;}}if(O===void 0x0)throw new Error('no\x20private\x20key\x20matches\x20the\x20selected\x20signing\x20certificate\x20(CKA_ID)');const P=[M['der']],Q=a4c['struct']('CK_MECHANISM',{'mechanism':'unsigned\x20long','pParameter':'void\x20*','ulParameterLen':'unsigned\x20long'}),R=(U,V)=>{const W=[{'mechanism':U,'pParameter':null,'ulParameterLen':0x0}],X=q(w,a4c['as'](W,a4c['array'](Q,0x1)),O);if(X===CKR_MECHANISM_INVALID)throw Object['assign'](new Error('mechanism\x20invalid'),{'ckr':CKR_MECHANISM_INVALID});v(X,'C_SignInit');const Y=Buffer['from'](V),Z=[0x0];v(r(w,Y,Y['length'],null,Z),'C_Sign(len)');const a0=Buffer['alloc'](Number(Z[0x0]));return v(r(w,Y,Y['length'],a0,Z),'C_Sign'),new Uint8Array(a0['subarray'](0x0,Number(Z[0x0])));},S=U=>{try{return R(CKM_SHA256_RSA_PKCS,U);}catch(V){if(V['ckr']!==CKR_MECHANISM_INVALID)throw V;const W=new Uint8Array(SHA256_DIGESTINFO_PREFIX['length']+0x20);return W['set'](SHA256_DIGESTINFO_PREFIX,0x0),W['set'](sha256(U),SHA256_DIGESTINFO_PREFIX['length']),R(CKM_RSA_PKCS,W);}};return{'certChainDer':P,'sign':S,'close':x};}catch(U){x();throw U;}}async function signUdfFiles(a){const b=openSession(a['module'],a['pin']),c=[...b['certChainDer'],...a['extraCertsDer']??[]],d=[];try{for(const e of a['files']){try{const f=new Uint8Array(await readFile(e)),g=await readContentXml(f),h=buildSignSgn({'contentXml':g,'certChainDer':c,'sign':b['sign'],'signingTime':new Date()}),i=await writeSignature(f,h);await writeFile(e,i),d['push']({'file':e,'ok':!![]});}catch(j){d['push']({'file':e,'ok':![],'error':j instanceof Error?j['message']:String(j)});}}}finally{b['close']();}return d;}export{signUdfFiles};
|