llmz 0.6.0 → 0.6.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.
Files changed (110) hide show
  1. package/DOCS.md +1 -3
  2. package/dist/_baseForOwn-CFhWe_W6.js +48 -0
  3. package/dist/_baseForOwn-buOZDFbK.cjs +103 -0
  4. package/dist/_baseIteratee-CF4qP2a8.cjs +2377 -0
  5. package/dist/_baseIteratee-P_firB7b.js +2138 -0
  6. package/dist/_getPrototype-CG7Dxrrz.js +6 -0
  7. package/dist/_getPrototype-DQDlNVVM.cjs +10 -0
  8. package/dist/_overArg-C5Hy7oCi.cjs +196 -0
  9. package/dist/_overArg-CRYbj1NH.js +155 -0
  10. package/dist/citations.d.ts +11 -11
  11. package/dist/component-BwixNVH8.cjs +73 -0
  12. package/dist/component-DGG7d_Mz.js +44 -0
  13. package/dist/context.d.ts +8 -8
  14. package/dist/custom-client-BPmEoWKu.cjs +2618 -0
  15. package/dist/custom-client-NUoxrFQh.js +2547 -0
  16. package/dist/dual-modes-D_p-jedw.js +2750 -0
  17. package/dist/dual-modes-wAOAlaBS.cjs +2840 -0
  18. package/dist/errors-C962uJdS.cjs +220 -0
  19. package/dist/errors-Cg1G0Awu.js +161 -0
  20. package/dist/execute-BEaq3jkV.cjs +1003 -0
  21. package/dist/execute-DYvFRs54.js +1001 -0
  22. package/dist/exit-BGi0Kk0y.cjs +428 -0
  23. package/dist/exit-CDdxDBRT.js +417 -0
  24. package/dist/index.cjs +1786 -1489
  25. package/dist/index.d.ts +10 -9
  26. package/dist/index.js +1721 -1479
  27. package/dist/index.workerd.js +17534 -16875
  28. package/dist/isEmpty-BhJRCqIF.js +52 -0
  29. package/dist/isEmpty-LY533Wmh.cjs +57 -0
  30. package/dist/isPlainObject-CSxXVKCk.cjs +56 -0
  31. package/dist/isPlainObject-D39AzPO2.js +51 -0
  32. package/dist/jsx-BWvT6ukg.cjs +75 -0
  33. package/dist/jsx-CIgdGGVs.js +52 -0
  34. package/dist/jsx.d.ts +2 -2
  35. package/dist/prompts/chat-mode/system.md.d.ts +1 -1
  36. package/dist/prompts/chat-mode/user.md.d.ts +1 -1
  37. package/dist/prompts/worker-mode/system.md.d.ts +1 -1
  38. package/dist/prompts/worker-mode/user.md.d.ts +1 -1
  39. package/dist/quickjs-variant-BYhMBpwU.js +45 -0
  40. package/dist/quickjs-variant-CsIwTVFC.cjs +56 -0
  41. package/dist/quickjs-variant.workerd.d.ts +1 -1
  42. package/dist/result.d.ts +12 -12
  43. package/dist/rolldown-runtime-EAsCxrDo.js +14 -0
  44. package/dist/runtime/interpret-result.d.ts +1 -1
  45. package/dist/snapshots.d.ts +5 -5
  46. package/dist/stack-traces-BIE_5Xwf.js +21 -0
  47. package/dist/stack-traces-ntw_qhoy.cjs +26 -0
  48. package/dist/tool-CAo-BQHs.js +643 -0
  49. package/dist/tool-DdPZb0JW.cjs +654 -0
  50. package/dist/tool.d.ts +3 -3
  51. package/dist/truncator-B6aaJaN1.cjs +276 -0
  52. package/dist/truncator-DZqEqnpD.js +253 -0
  53. package/dist/typings-BwAz_TM9.cjs +784 -0
  54. package/dist/typings-CrBa7Tyy.js +743 -0
  55. package/dist/uniq-BYQ7GWwb.js +183 -0
  56. package/dist/uniq-G872RWmE.cjs +200 -0
  57. package/dist/utils-UBeAFeEI.js +950 -0
  58. package/dist/utils-ZpJm00ed.cjs +1075 -0
  59. package/dist/vm/errors.d.ts +2 -2
  60. package/dist/vm-BjkJqSQH.cjs +3438 -0
  61. package/dist/vm-C5vf1LH3.js +3436 -0
  62. package/package.json +7 -7
  63. package/dist/chunk-34GJUS6U.js +0 -3266
  64. package/dist/chunk-3UZKLXAD.cjs +0 -3249
  65. package/dist/chunk-4POZJQXN.js +0 -1530
  66. package/dist/chunk-5WBNTV42.cjs +0 -1530
  67. package/dist/chunk-5ZF6NTYI.cjs +0 -33
  68. package/dist/chunk-72ZWBNZV.js +0 -173
  69. package/dist/chunk-DDSJTR6Q.cjs +0 -257
  70. package/dist/chunk-GDJTKI7J.js +0 -792
  71. package/dist/chunk-GLXADNTR.js +0 -199
  72. package/dist/chunk-GOWPACSK.cjs +0 -199
  73. package/dist/chunk-HB2G32AK.js +0 -257
  74. package/dist/chunk-HC2QZTVT.cjs +0 -3266
  75. package/dist/chunk-HEAQAEFZ.cjs +0 -173
  76. package/dist/chunk-HMMM32RG.cjs +0 -792
  77. package/dist/chunk-I56MPOVG.cjs +0 -62
  78. package/dist/chunk-KIN7Y247.cjs +0 -32
  79. package/dist/chunk-KTDBAJBB.cjs +0 -1685
  80. package/dist/chunk-KWQTYXAT.js +0 -62
  81. package/dist/chunk-LOX7GOR6.js +0 -1685
  82. package/dist/chunk-PK72FAKD.cjs +0 -175
  83. package/dist/chunk-PZE6PIPG.cjs +0 -621
  84. package/dist/chunk-RGUG3UMF.cjs +0 -26
  85. package/dist/chunk-TDALRNGL.js +0 -621
  86. package/dist/chunk-UGHFNCPD.js +0 -26
  87. package/dist/chunk-WSVDMGMR.js +0 -175
  88. package/dist/chunk-XTEHT2TK.js +0 -33
  89. package/dist/chunk-YEAWWJSJ.js +0 -32
  90. package/dist/chunk-YRS7KRKP.js +0 -3249
  91. package/dist/component-2NYFY6CW.cjs +0 -14
  92. package/dist/component-ASNZHQUR.js +0 -14
  93. package/dist/dual-modes-S5TJ5JVJ.js +0 -10
  94. package/dist/dual-modes-TCMWBZIH.cjs +0 -10
  95. package/dist/execute-FF7D46TY.js +0 -1109
  96. package/dist/execute-IK6O4SU2.cjs +0 -1109
  97. package/dist/exit-MX56VN2C.cjs +0 -8
  98. package/dist/exit-UQ3EUX5D.js +0 -8
  99. package/dist/jsx-DDZ63UUF.js +0 -13
  100. package/dist/jsx-ULPWX5TW.cjs +0 -13
  101. package/dist/tool-KD7FL45V.js +0 -11
  102. package/dist/tool-VE2YHIY2.cjs +0 -11
  103. package/dist/truncator-73RCL52Y.js +0 -12
  104. package/dist/truncator-FZNLYSDL.cjs +0 -12
  105. package/dist/typings-E2RROCLT.js +0 -10
  106. package/dist/typings-LQOBZXSO.cjs +0 -10
  107. package/dist/utils-IATCUNKF.js +0 -43
  108. package/dist/utils-ITB4NEL7.cjs +0 -43
  109. package/dist/vm-6D3IIIU7.cjs +0 -12
  110. package/dist/vm-QO5FSGPN.js +0 -12
@@ -0,0 +1,743 @@
1
+ import { n as __exportAll } from "./rolldown-runtime-EAsCxrDo.js";
2
+ import { a as getMultilineComment, f as toPropertyKey, n as escapeString } from "./utils-UBeAFeEI.js";
3
+ import { r as CodeFormattingError } from "./errors-Cg1G0Awu.js";
4
+ import { z } from "@bpinternal/zui";
5
+ //#region src/typings-formatter.ts
6
+ /**
7
+ * A minimal, dependency-free formatter for the TypeScript typings generated by
8
+ * llmz (typings.ts, objects.ts, hoist.ts). It supports only the small grammar
9
+ * those generators emit — type expressions, `declare const` / `declare function`
10
+ * declarations, `type` aliases and `export namespace` blocks — and produces
11
+ * prettier-like output: 80 columns, 2-space indent, no semicolons in broken
12
+ * objects, hugged single-object function params, unions wrapped with leading `|`.
13
+ *
14
+ * If the input cannot be tokenized or has unbalanced brackets, it is returned
15
+ * unchanged.
16
+ */
17
+ const WIDTH = 80;
18
+ const INDENT = " ";
19
+ const isGroup = (n) => n.kind === "group";
20
+ const isPunct = (n, text) => !isGroup(n) && n.kind === "punct" && n.text === text;
21
+ const WORD_CHAR = /[A-Za-z0-9_$.]/;
22
+ function tokenize(src) {
23
+ const toks = [];
24
+ let i = 0;
25
+ let nl = 0;
26
+ const len = src.length;
27
+ while (i < len) {
28
+ const c = src[i];
29
+ if (c === "\n") {
30
+ nl++;
31
+ i++;
32
+ continue;
33
+ }
34
+ if (c === " " || c === " " || c === "\r") {
35
+ i++;
36
+ continue;
37
+ }
38
+ if (c === "/" && src[i + 1] === "*") {
39
+ const end = src.indexOf("*/", i + 2);
40
+ if (end === -1) throw new Error("unterminated block comment");
41
+ toks.push({
42
+ kind: "block-comment",
43
+ text: src.slice(i, end + 2),
44
+ nl
45
+ });
46
+ nl = 0;
47
+ i = end + 2;
48
+ continue;
49
+ }
50
+ if (c === "/" && src[i + 1] === "/") {
51
+ let end = src.indexOf("\n", i);
52
+ if (end === -1) end = len;
53
+ toks.push({
54
+ kind: "line-comment",
55
+ text: src.slice(i, end).trimEnd(),
56
+ nl
57
+ });
58
+ nl = 0;
59
+ i = end;
60
+ continue;
61
+ }
62
+ if (c === "'" || c === "\"" || c === "`") {
63
+ let j = i + 1;
64
+ while (j < len && src[j] !== c) j += src[j] === "\\" ? 2 : 1;
65
+ if (j >= len) throw new Error("unterminated string");
66
+ toks.push({
67
+ kind: "string",
68
+ text: src.slice(i, j + 1),
69
+ nl
70
+ });
71
+ nl = 0;
72
+ i = j + 1;
73
+ continue;
74
+ }
75
+ if (c === "=" && src[i + 1] === ">") {
76
+ toks.push({
77
+ kind: "punct",
78
+ text: "=>",
79
+ nl
80
+ });
81
+ nl = 0;
82
+ i += 2;
83
+ continue;
84
+ }
85
+ if (WORD_CHAR.test(c) || c === "-" && /\d/.test(src[i + 1] ?? "")) {
86
+ let j = i + 1;
87
+ while (j < len && WORD_CHAR.test(src[j])) j++;
88
+ toks.push({
89
+ kind: "word",
90
+ text: src.slice(i, j),
91
+ nl
92
+ });
93
+ nl = 0;
94
+ i = j;
95
+ continue;
96
+ }
97
+ toks.push({
98
+ kind: "punct",
99
+ text: c,
100
+ nl
101
+ });
102
+ nl = 0;
103
+ i++;
104
+ }
105
+ return toks;
106
+ }
107
+ const CLOSER = {
108
+ "{": "}",
109
+ "(": ")",
110
+ "[": "]",
111
+ "<": ">"
112
+ };
113
+ function parse(toks) {
114
+ const root = [];
115
+ const stack = [];
116
+ const siblings = () => stack.length ? stack[stack.length - 1].children : root;
117
+ for (const t of toks) {
118
+ if (t.kind === "punct" && (t.text === "{" || t.text === "(" || t.text === "[")) {
119
+ const g = {
120
+ kind: "group",
121
+ open: t.text,
122
+ close: CLOSER[t.text],
123
+ children: [],
124
+ nl: t.nl
125
+ };
126
+ siblings().push(g);
127
+ stack.push(g);
128
+ continue;
129
+ }
130
+ if (t.kind === "punct" && t.text === "<") {
131
+ const prev = siblings()[siblings().length - 1];
132
+ if (prev && !isGroup(prev) && prev.kind === "word") {
133
+ const g = {
134
+ kind: "group",
135
+ open: "<",
136
+ close: ">",
137
+ children: [],
138
+ nl: t.nl
139
+ };
140
+ siblings().push(g);
141
+ stack.push(g);
142
+ continue;
143
+ }
144
+ siblings().push(t);
145
+ continue;
146
+ }
147
+ if (t.kind === "punct" && (t.text === "}" || t.text === ")" || t.text === "]" || t.text === ">")) {
148
+ const g = stack[stack.length - 1];
149
+ if (t.text === ">" && (!g || g.open !== "<")) {
150
+ siblings().push(t);
151
+ continue;
152
+ }
153
+ if (!g || g.close !== t.text) throw new Error("unbalanced brackets");
154
+ stack.pop();
155
+ continue;
156
+ }
157
+ siblings().push(t);
158
+ }
159
+ if (stack.length) throw new Error("unbalanced brackets");
160
+ return root;
161
+ }
162
+ /**
163
+ * Cleans up generator artifacts: trailing `,`/`;` inside groups, and redundant
164
+ * parens in value position like `[key: (string)]: ({ ... } | undefined)`.
165
+ */
166
+ function normalize(nodes) {
167
+ for (let i = 0; i < nodes.length; i++) {
168
+ const n = nodes[i];
169
+ if (!isGroup(n)) {
170
+ const key = n.kind === "string" && /^["']([A-Za-z_$][A-Za-z0-9_$]*)["']$/.exec(n.text);
171
+ const next = nodes[i + 1];
172
+ if (key && next && isPunct(next, ":")) nodes[i] = {
173
+ kind: "word",
174
+ text: key[1],
175
+ nl: n.nl
176
+ };
177
+ continue;
178
+ }
179
+ normalize(n.children);
180
+ while (n.children.length && (isPunct(n.children[n.children.length - 1], ",") || isPunct(n.children[n.children.length - 1], ";"))) n.children.pop();
181
+ const prev = nodes[i - 1];
182
+ const next = nodes[i + 1];
183
+ const wrapsWholeValue = next === void 0 || isPunct(next, ";") || isPunct(next, ",");
184
+ const isFunctionType = n.children.some((c) => isPunct(c, "=>"));
185
+ if (n.open === "(" && n.children.length > 0 && prev && isPunct(prev, ":") && wrapsWholeValue && !isFunctionType) {
186
+ n.children[0].nl = n.nl;
187
+ nodes.splice(i, 1, ...n.children);
188
+ i--;
189
+ }
190
+ }
191
+ }
192
+ function isMemberEnd(n) {
193
+ if (isGroup(n)) return true;
194
+ return n.kind === "word" || n.kind === "string" || n.kind === "block-comment" || n.kind === "line-comment" || n.text === "?";
195
+ }
196
+ function isMemberStart(n) {
197
+ if (isGroup(n)) return false;
198
+ return n.kind === "word" || n.kind === "string" || n.kind === "block-comment" || n.kind === "line-comment";
199
+ }
200
+ /**
201
+ * Splits a flat node sequence into members: on top-level `;`, on top-level `,`
202
+ * (when enabled), after line comments, and at "safe" newlines — a newline
203
+ * between a token that can end a member and one that can start the next one.
204
+ * Newlines elsewhere (e.g. the generator's stray newlines around descriptions)
205
+ * are ignored.
206
+ */
207
+ function splitMembers(nodes, splitOnComma) {
208
+ const members = [];
209
+ let cur = [];
210
+ let hasSeparators = false;
211
+ let usedComma = false;
212
+ const push = () => {
213
+ if (cur.length) members.push(cur);
214
+ cur = [];
215
+ };
216
+ for (const n of nodes) {
217
+ if (isPunct(n, ";") || splitOnComma && isPunct(n, ",")) {
218
+ hasSeparators = true;
219
+ usedComma ||= n.text === ",";
220
+ push();
221
+ continue;
222
+ }
223
+ const isTrailingLineComment = !isGroup(n) && n.kind === "line-comment" && n.nl === 0;
224
+ if (isTrailingLineComment && !cur.length && members.length) {
225
+ members[members.length - 1].push(n);
226
+ continue;
227
+ }
228
+ if (cur.length) {
229
+ const prev = cur[cur.length - 1];
230
+ if (!isGroup(prev) && prev.kind === "line-comment" || n.nl > 0 && !isTrailingLineComment && isMemberEnd(prev) && isMemberStart(n)) push();
231
+ }
232
+ cur.push(n);
233
+ }
234
+ push();
235
+ for (let i = members.length - 2; i >= 0; i--) if (members[i].every((n) => !isGroup(n) && n.kind === "block-comment")) {
236
+ members[i + 1].unshift(...members[i]);
237
+ members.splice(i, 1);
238
+ }
239
+ return {
240
+ members,
241
+ hasSeparators,
242
+ usedComma
243
+ };
244
+ }
245
+ function hasMultilineComment(nodes) {
246
+ return nodes.some((n) => !isGroup(n) && n.kind === "block-comment" && n.text.includes("\n"));
247
+ }
248
+ function hasLineComment(nodes) {
249
+ return nodes.some((n) => !isGroup(n) && n.kind === "line-comment");
250
+ }
251
+ /** Whether a group can never be rendered on a single line. */
252
+ function mustBreak(g) {
253
+ if (hasLineComment(g.children) || hasMultilineComment(g.children)) return true;
254
+ const { members, hasSeparators } = splitMembers(g.children, true);
255
+ if (members.length > 1 && !hasSeparators) return true;
256
+ if ((g.open === "{" || g.open === "(") && members.some((m) => !isGroup(m[0]) && m[0].kind === "block-comment")) return true;
257
+ return g.children.some((c) => isGroup(c) && mustBreak(c));
258
+ }
259
+ function needSpace(a, b) {
260
+ if (!a) return false;
261
+ if (a.kind === "open" && b.kind === "close") return false;
262
+ if (b.kind === "punct" && (b.text === "," || b.text === ";" || b.text === ":" || b.text === "?")) return false;
263
+ if (b.kind === "close") return b.text === "}";
264
+ if (a.kind === "open") return a.text === "{";
265
+ if (b.kind === "open") {
266
+ if (b.text === "(" || b.text === "[") return !(a.kind === "word" || a.kind === "string" || a.kind === "close");
267
+ if (b.text === "<") return false;
268
+ return true;
269
+ }
270
+ return true;
271
+ }
272
+ function flatAtoms(nodes) {
273
+ const out = [];
274
+ for (const n of nodes) if (isGroup(n)) {
275
+ out.push({
276
+ kind: "open",
277
+ text: n.open
278
+ });
279
+ out.push(...flatAtoms(n.children));
280
+ out.push({
281
+ kind: "close",
282
+ text: n.close
283
+ });
284
+ } else out.push({
285
+ kind: n.kind,
286
+ text: n.text
287
+ });
288
+ return out;
289
+ }
290
+ function joinAtoms(atoms) {
291
+ let s = "";
292
+ let prev = null;
293
+ for (const a of atoms) {
294
+ if (needSpace(prev, a)) s += " ";
295
+ s += a.text;
296
+ prev = a;
297
+ }
298
+ return s;
299
+ }
300
+ const canFlatten = (nodes) => !hasLineComment(nodes) && !hasMultilineComment(nodes) && !nodes.some((n) => isGroup(n) && mustBreak(n));
301
+ var Printer = class {
302
+ _lines = [];
303
+ _cur = "";
304
+ _prev = null;
305
+ atom(a) {
306
+ if (this._prev && this._cur !== "" && needSpace(this._prev, a)) this._cur += " ";
307
+ this._cur += a.text;
308
+ this._prev = a;
309
+ }
310
+ flat(nodes) {
311
+ for (const a of flatAtoms(nodes)) this.atom(a);
312
+ }
313
+ newline(level) {
314
+ this._lines.push(this._cur);
315
+ this._cur = INDENT.repeat(level);
316
+ this._prev = null;
317
+ }
318
+ blankLine(level) {
319
+ this._lines.push(this._cur);
320
+ this._lines.push("");
321
+ this._cur = INDENT.repeat(level);
322
+ this._prev = null;
323
+ }
324
+ get column() {
325
+ return this._cur.length;
326
+ }
327
+ get lineIsEmpty() {
328
+ return this._cur.trim() === "";
329
+ }
330
+ comment(text, level) {
331
+ const lines = text.split("\n").map((l) => l.trim());
332
+ for (let i = 0; i < lines.length; i++) {
333
+ if (i > 0) {
334
+ this.newline(level);
335
+ this._cur += lines[i].startsWith("*") ? " " : "";
336
+ this._cur += lines[i];
337
+ } else this.atom({
338
+ kind: "block-comment",
339
+ text: lines[i]
340
+ });
341
+ this._prev = {
342
+ kind: "block-comment",
343
+ text: lines[i]
344
+ };
345
+ }
346
+ }
347
+ toString() {
348
+ this._lines.push(this._cur);
349
+ const out = this._lines.map((l) => l.trim() === "" ? "" : l).join("\n").replace(/\n{3,}/g, "\n\n");
350
+ this._lines.pop();
351
+ return out.trim();
352
+ }
353
+ };
354
+ function flatWidth(nodes) {
355
+ if (!canFlatten(nodes)) return null;
356
+ return joinAtoms(flatAtoms(nodes)).length;
357
+ }
358
+ function fitsFlat(p, nodes) {
359
+ const width = flatWidth(nodes);
360
+ return width !== null && p.column + width + 1 <= WIDTH;
361
+ }
362
+ /**
363
+ * Emits nodes left to right, breaking groups in place when they don't fit.
364
+ * `tailWidth` is the flat width of whatever the caller will emit right after
365
+ * these nodes on the same line (e.g. `): unknown` after hugged params).
366
+ */
367
+ function walk(p, nodes, level, tailWidth = 0) {
368
+ for (let i = 0; i < nodes.length; i++) {
369
+ const n = nodes[i];
370
+ if (isGroup(n)) {
371
+ const own = mustBreak(n) ? null : flatWidth([n]);
372
+ let restNodes = nodes.slice(i + 1);
373
+ const lineCommentIdx = restNodes.findIndex((x) => !isGroup(x) && x.kind === "line-comment");
374
+ if (lineCommentIdx !== -1) restNodes = restNodes.slice(0, lineCommentIdx);
375
+ const rest = flatWidth(restNodes);
376
+ const after = rest === null ? 0 : rest + tailWidth;
377
+ if (own !== null && p.column + 1 + own + after <= WIDTH) p.flat([n]);
378
+ else breakGroup(p, n, level, after);
379
+ continue;
380
+ }
381
+ if (n.kind === "block-comment" && n.text.includes("\n")) {
382
+ if (!p.lineIsEmpty) p.newline(level);
383
+ p.comment(n.text, level);
384
+ p.newline(level);
385
+ continue;
386
+ }
387
+ if (n.kind === "line-comment") {
388
+ p.atom({
389
+ kind: "line-comment",
390
+ text: n.text
391
+ });
392
+ continue;
393
+ }
394
+ p.atom({
395
+ kind: n.kind,
396
+ text: n.text
397
+ });
398
+ }
399
+ }
400
+ function breakGroup(p, g, level, tailWidth = 0) {
401
+ if (g.open === "<") {
402
+ p.atom({
403
+ kind: "open",
404
+ text: "<"
405
+ });
406
+ walk(p, g.children, level, tailWidth + 1);
407
+ p.atom({
408
+ kind: "close",
409
+ text: ">"
410
+ });
411
+ return;
412
+ }
413
+ const { members, usedComma } = splitMembers(g.children, true);
414
+ const hasLeadingComment = members.some((m) => !isGroup(m[0]) && m[0].kind === "block-comment");
415
+ const single = members.length === 1 ? members[0] : null;
416
+ const endsInObject = !!single && isGroup(single[single.length - 1]) && single[single.length - 1].open === "{";
417
+ const hasUnion = !!single && single.some((n) => isPunct(n, "|"));
418
+ if (g.open === "(" && endsInObject && !hasUnion && !hasLeadingComment) {
419
+ p.atom({
420
+ kind: "open",
421
+ text: "("
422
+ });
423
+ walk(p, g.children, level, tailWidth + 1);
424
+ p.atom({
425
+ kind: "close",
426
+ text: ")"
427
+ });
428
+ return;
429
+ }
430
+ const separator = g.open === "(" || g.open === "[" ? "," : usedComma ? "," : null;
431
+ const trailingSeparator = g.open === "(" || g.open === "[";
432
+ p.atom({
433
+ kind: "open",
434
+ text: g.open
435
+ });
436
+ for (let i = 0; i < members.length; i++) {
437
+ p.newline(level + 1);
438
+ renderMember(p, members[i], level + 1);
439
+ if (separator && (trailingSeparator || i < members.length - 1)) p.atom({
440
+ kind: "punct",
441
+ text: separator
442
+ });
443
+ }
444
+ p.newline(level);
445
+ p.atom({
446
+ kind: "close",
447
+ text: g.close
448
+ });
449
+ }
450
+ /** Renders one member (or statement body): leading comments, then flat / union-break / walk. */
451
+ function renderMember(p, nodes, level) {
452
+ let rest = nodes;
453
+ while (rest.length && !isGroup(rest[0]) && rest[0].kind === "block-comment") {
454
+ const c = rest[0];
455
+ p.comment(c.text, level);
456
+ rest = rest.slice(1);
457
+ if (rest.length) p.newline(level);
458
+ }
459
+ if (!rest.length) return;
460
+ if (fitsFlat(p, rest)) {
461
+ p.flat(rest);
462
+ return;
463
+ }
464
+ const pipeIdx = rest.findIndex((n) => isPunct(n, "|"));
465
+ const parenIdx = rest.findIndex((n) => isGroup(n) && n.open === "(");
466
+ if (pipeIdx !== -1 && (parenIdx === -1 || pipeIdx < parenIdx)) {
467
+ let colonIdx = -1;
468
+ for (let i = 0; i < pipeIdx; i++) if (isPunct(rest[i], ":") || isPunct(rest[i], "=")) colonIdx = i;
469
+ const prefix = rest.slice(0, colonIdx + 1);
470
+ const tail = rest.slice(colonIdx + 1);
471
+ if (!prefix.length || fitsFlat(p, prefix)) {
472
+ p.flat(prefix);
473
+ const options = [];
474
+ let cur = [];
475
+ for (const n of tail) if (isPunct(n, "|")) {
476
+ options.push(cur);
477
+ cur = [];
478
+ } else cur.push(n);
479
+ options.push(cur);
480
+ const optionLevel = prefix.length ? level + 1 : level;
481
+ let first = true;
482
+ for (const option of options) {
483
+ if (!option.length) continue;
484
+ if (!first || prefix.length) p.newline(optionLevel);
485
+ first = false;
486
+ p.atom({
487
+ kind: "punct",
488
+ text: "|"
489
+ });
490
+ walk(p, option, optionLevel + 1);
491
+ }
492
+ return;
493
+ }
494
+ }
495
+ const eqIdx = rest.findIndex((n) => isPunct(n, "="));
496
+ if (eqIdx !== -1) {
497
+ const prefix = rest.slice(0, eqIdx + 1);
498
+ if (fitsFlat(p, prefix)) {
499
+ p.flat(prefix);
500
+ walk(p, rest.slice(eqIdx + 1), level);
501
+ return;
502
+ }
503
+ }
504
+ walk(p, rest, level);
505
+ }
506
+ function renderStatements(p, nodes, level) {
507
+ const { members: statements } = splitMembers(nodes, false);
508
+ for (let i = 0; i < statements.length; i++) {
509
+ const stmt = statements[i];
510
+ if (i > 0) {
511
+ if ((stmt[0].nl ?? 0) >= 2) p.blankLine(level);
512
+ else p.newline(level);
513
+ }
514
+ renderStatement(p, stmt, level);
515
+ }
516
+ }
517
+ function renderStatement(p, stmt, level) {
518
+ while (stmt.length && !isGroup(stmt[0]) && stmt[0].kind === "block-comment") {
519
+ p.comment(stmt[0].text, level);
520
+ stmt = stmt.slice(1);
521
+ if (stmt.length) p.newline(level);
522
+ }
523
+ if (!stmt.length) return;
524
+ const nsIdx = stmt.findIndex((n) => !isGroup(n) && n.kind === "word" && (n.text === "namespace" || n.text === "module"));
525
+ const bodyIdx = stmt.findIndex((n) => isGroup(n) && n.open === "{");
526
+ if (nsIdx !== -1 && bodyIdx > nsIdx) {
527
+ const body = stmt[bodyIdx];
528
+ p.flat(stmt.slice(0, bodyIdx));
529
+ p.atom({
530
+ kind: "open",
531
+ text: "{"
532
+ });
533
+ if (body.children.length) {
534
+ p.newline(level + 1);
535
+ renderStatements(p, body.children, level + 1);
536
+ p.newline(level);
537
+ }
538
+ p.atom({
539
+ kind: "close",
540
+ text: "}"
541
+ });
542
+ walk(p, stmt.slice(bodyIdx + 1), level);
543
+ return;
544
+ }
545
+ renderMember(p, stmt, level);
546
+ }
547
+ /** Formats typings, throwing on input it cannot parse (unbalanced brackets, etc.) */
548
+ function formatTypingsUnsafe(typings) {
549
+ const tokens = tokenize(typings);
550
+ if (!tokens.length) return "";
551
+ const nodes = parse(tokens);
552
+ normalize(nodes);
553
+ const printer = new Printer();
554
+ renderStatements(printer, nodes, 0);
555
+ return printer.toString();
556
+ }
557
+ //#endregion
558
+ //#region src/formatting.ts
559
+ async function formatTypings(typings, options) {
560
+ try {
561
+ return formatTypingsUnsafe(typings);
562
+ } catch (err) {
563
+ if ((options === null || options === void 0 ? void 0 : options.throwOnError) ?? true) throw new CodeFormattingError(err instanceof Error ? err.message : (err === null || err === void 0 ? void 0 : err.toString()) ?? "Unknown Error", typings);
564
+ return typings;
565
+ }
566
+ }
567
+ //#endregion
568
+ //#region src/typings.ts
569
+ var typings_exports = /* @__PURE__ */ __exportAll({ getTypings: () => getTypings });
570
+ const Primitives = [
571
+ "string",
572
+ "number",
573
+ "boolean",
574
+ "unknown",
575
+ "void",
576
+ "any",
577
+ "null",
578
+ "undefined",
579
+ "never",
580
+ "bigint",
581
+ "symbol",
582
+ "object"
583
+ ];
584
+ const LARGE_DECLARATION_LINES = 5;
585
+ const isPrimitive = (type) => Primitives.includes(type);
586
+ const isArrayOfPrimitives = (type) => Primitives.map((p) => `${p}[]`).includes(type);
587
+ const stripSpaces = (typings) => typings.replace(/ +/g, " ").trim();
588
+ var KeyValue = class {
589
+ key;
590
+ value;
591
+ constructor(key, value) {
592
+ this.key = key;
593
+ this.value = value;
594
+ }
595
+ };
596
+ var FnParameters = class {
597
+ schema;
598
+ constructor(schema) {
599
+ this.schema = schema;
600
+ }
601
+ };
602
+ var FnReturn = class {
603
+ schema;
604
+ constructor(schema) {
605
+ this.schema = schema;
606
+ }
607
+ };
608
+ var Declaration = class {
609
+ schema;
610
+ identifier;
611
+ constructor(schema, identifier) {
612
+ this.schema = schema;
613
+ this.identifier = identifier;
614
+ }
615
+ };
616
+ async function getTypings(schema, options) {
617
+ options ??= {};
618
+ options.declaration ??= false;
619
+ let wrappedSchema = schema;
620
+ if ((options === null || options === void 0 ? void 0 : options.declaration) && z.is.zuiType(schema)) {
621
+ const title = "title" in schema.ui ? schema.ui.title : null;
622
+ if (!title) throw new Error("Only schemas with \"title\" Zui property can be declared.");
623
+ wrappedSchema = new Declaration(schema, title);
624
+ }
625
+ let dts = await sUnwrapZodRecursive(wrappedSchema, { ...options });
626
+ dts = await formatTypings(dts, { throwOnError: false });
627
+ return dts;
628
+ }
629
+ async function sUnwrapZodRecursive(schema, options) {
630
+ return sUnwrapZod(schema, options);
631
+ }
632
+ async function sUnwrapZod(schema, options) {
633
+ const newOptions = {
634
+ ...options,
635
+ declaration: false,
636
+ parent: schema
637
+ };
638
+ if (schema instanceof Declaration) {
639
+ const description = getMultilineComment(schema.schema.description);
640
+ const typings = await sUnwrapZodRecursive(schema.schema.describe(""), {
641
+ ...newOptions,
642
+ declaration: true
643
+ });
644
+ const closingTag = typings.split("\n").length >= LARGE_DECLARATION_LINES ? `// end of ${schema.identifier}` : "";
645
+ if (z.is.zuiFunction(schema.schema)) return stripSpaces(`${description}
646
+ declare function ${schema.identifier}${typings};${closingTag}`);
647
+ return stripSpaces(`${description}
648
+ declare const ${schema.identifier}: ${typings};${closingTag}`);
649
+ }
650
+ if (schema instanceof KeyValue) {
651
+ if (z.is.zuiOptional(schema.value) || z.is.zuiDefault(schema.value)) {
652
+ let innerType = schema.value._def.innerType;
653
+ if (z.is.zuiType(innerType) && !innerType.description && schema.value.description) innerType = innerType === null || innerType === void 0 ? void 0 : innerType.describe(schema.value.description);
654
+ const optionalToken = schema.key.endsWith("?") ? "" : "?";
655
+ return sUnwrapZodRecursive(new KeyValue(schema.key + optionalToken, innerType), newOptions);
656
+ }
657
+ const description = getMultilineComment(schema.value._def.description || schema.value.description);
658
+ const delimiter = (description === null || description === void 0 ? void 0 : description.trim().length) > 0 ? "\n" : "";
659
+ const withoutDesc = schema.value.describe("");
660
+ return `${delimiter}${description}${delimiter}${schema.key}: ${await sUnwrapZodRecursive(withoutDesc, newOptions)}${delimiter}`;
661
+ }
662
+ if (schema instanceof FnParameters) {
663
+ if (z.is.zuiTuple(schema.schema)) {
664
+ let args = "";
665
+ for (let i = 0; i < schema.schema.items.length; i++) {
666
+ var _schema$schema$items$;
667
+ const argName = ((_schema$schema$items$ = schema.schema.items[i]) === null || _schema$schema$items$ === void 0 || (_schema$schema$items$ = _schema$schema$items$.ui) === null || _schema$schema$items$ === void 0 ? void 0 : _schema$schema$items$.title) ?? `arg${i}`;
668
+ const item = schema.schema.items[i];
669
+ args += `${await sUnwrapZodRecursive(new KeyValue(toPropertyKey(argName), item), newOptions)}, `;
670
+ }
671
+ return args;
672
+ }
673
+ const isLiteral = z.is.zuiLiteral(schema.schema.naked());
674
+ const typings = (await sUnwrapZodRecursive(schema.schema, newOptions)).trim();
675
+ if (typings.startsWith("{") && typings.endsWith("}") || typings.startsWith("[") && typings.endsWith("]") || typings.startsWith("(") && typings.endsWith(")") || typings.startsWith("Array<") && typings.endsWith(">") || typings.startsWith("Record<") && typings.endsWith(">") || isArrayOfPrimitives(typings) || isLiteral) return `args: ${typings}`;
676
+ else return typings;
677
+ }
678
+ if (schema instanceof FnReturn) {
679
+ if (z.is.zuiOptional(schema.schema)) return `${await sUnwrapZodRecursive(schema.schema.unwrap(), newOptions)} | undefined`;
680
+ return sUnwrapZodRecursive(schema.schema, newOptions);
681
+ }
682
+ if (schema === null) return "unknown";
683
+ if (z.is.zuiDefault(schema)) return sUnwrapZodRecursive(schema._def.innerType, options);
684
+ if (z.is.zuiVoid(schema)) return "void";
685
+ if (z.is.zuiUnknown(schema)) return "unknown";
686
+ if (z.is.zuiAny(schema)) return "any";
687
+ if (z.is.zuiPromise(schema)) return `Promise<${await sUnwrapZodRecursive(schema.unwrap(), newOptions)}>`;
688
+ if (z.is.zuiFunction(schema)) {
689
+ const description = getMultilineComment(schema._def.description);
690
+ const input = await sUnwrapZodRecursive(new FnParameters(schema._def.args), newOptions);
691
+ const output = await sUnwrapZodRecursive(new FnReturn(schema._def.returns), newOptions);
692
+ if (options === null || options === void 0 ? void 0 : options.declaration) return `${description}
693
+ (${input}): ${output}`;
694
+ return `${description}
695
+ (${input}) => ${output}`;
696
+ }
697
+ if (z.is.zuiArray(schema)) {
698
+ const item = await sUnwrapZodRecursive(schema._def.type, newOptions);
699
+ if (isPrimitive(item)) return `${item}[]`;
700
+ return `Array<${item}>`;
701
+ }
702
+ if (z.is.zuiEnum(schema)) return schema._def.values.map(escapeString).join(" | ");
703
+ if (z.is.zuiTuple(schema)) {
704
+ if (schema.items.length === 0) return "[]";
705
+ return `[${(await Promise.all(schema.items.map((i) => sUnwrapZodRecursive(i, newOptions)))).join(", ")}]`;
706
+ }
707
+ if (z.is.zuiNullable(schema)) return `${await sUnwrapZodRecursive(schema.unwrap(), options)} | null`;
708
+ if (z.is.zuiOptional(schema)) {
709
+ if ((options === null || options === void 0 ? void 0 : options.declaration) || z.is.zuiType(options === null || options === void 0 ? void 0 : options.parent) && options.parent.typeName === "ZodRecord") return `${await sUnwrapZodRecursive(schema._def.innerType, newOptions)} | undefined`;
710
+ const optionalToken = options.parent instanceof KeyValue ? "| undefined" : "";
711
+ return `${await sUnwrapZodRecursive(schema._def.innerType, newOptions)}${optionalToken}`;
712
+ }
713
+ if (z.is.zuiObject(schema)) return `{ ${(await Promise.all(Object.entries(schema.shape).map(async ([key, value]) => {
714
+ if (z.is.zuiType(value)) return sUnwrapZodRecursive(new KeyValue(toPropertyKey(key), value), newOptions);
715
+ return `${key}: unknown`;
716
+ }))).join("; ")} }`;
717
+ if (z.is.zuiString(schema)) return `${getMultilineComment(schema._def.description)} string`.trim();
718
+ if (z.is.zuiUnion(schema)) return `${getMultilineComment(schema._def.description)}
719
+ ${(await Promise.all(schema.options.map(async (option) => {
720
+ return sUnwrapZodRecursive(option, newOptions);
721
+ }))).join(" | ")}`;
722
+ if (z.is.zuiLiteral(schema)) return `${getMultilineComment(schema._def.description)}
723
+ ${typeof schema.value === "string" ? escapeString(schema.value) : String(schema.value)}`.trim();
724
+ if (z.is.zuiNumber(schema)) return `${getMultilineComment(schema._def.description)} number`.trim();
725
+ if (z.is.zuiBoolean(schema)) return `${getMultilineComment(schema._def.description)} boolean`.trim();
726
+ if (z.is.zuiCatch(schema)) return sUnwrapZodRecursive(schema.removeCatch(), newOptions);
727
+ if (z.is.zuiLazy(schema)) return sUnwrapZodRecursive(schema._def.getter(), newOptions);
728
+ if (z.is.zuiRecord(schema)) return `${getMultilineComment(schema._def.description)} { [key: (${await sUnwrapZodRecursive(schema._def.keyType, newOptions)})]: (${await sUnwrapZodRecursive(schema._def.valueType, newOptions)}) }`;
729
+ try {
730
+ let typings = schema === null || schema === void 0 ? void 0 : schema.toTypescriptType({ treatDefaultAsOptional: true });
731
+ typings ??= "unknown";
732
+ return stripSpaces(typings);
733
+ } catch (error) {
734
+ console.error("Error in sUnwrapZod", {
735
+ error,
736
+ schema,
737
+ parent: options === null || options === void 0 ? void 0 : options.parent
738
+ });
739
+ return "unknown";
740
+ }
741
+ }
742
+ //#endregion
743
+ export { isPunct as a, isGroup as i, typings_exports as n, parse as o, formatTypings as r, tokenize as s, getTypings as t };