@pen.dev/cli 0.3.3 → 0.3.4

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 (82) hide show
  1. package/README.md +13 -6
  2. package/dist/anthropic-messages-COZrsSdY.mjs +40 -0
  3. package/dist/azure-openai-responses-Dmf1EaVz.mjs +2 -0
  4. package/dist/browserAll-BZYrVO32.mjs +2 -0
  5. package/dist/{dist-BEo0Z8Vf.mjs → dist-D9ROAuw3.mjs} +348 -319
  6. package/dist/{dist-BY6vOcMF.mjs → dist-DGrygXHh.mjs} +2 -2
  7. package/dist/{error-body-D2Mrqb4g.mjs → error-body-BBlqjbe7.mjs} +1 -1
  8. package/dist/google-generative-ai-BMEzR_34.mjs +2 -0
  9. package/dist/google-shared-DXgnvvDU.mjs +318 -0
  10. package/dist/google-vertex-In7qdx36.mjs +2 -0
  11. package/dist/index.mjs +2 -2
  12. package/dist/mistral-conversations-DdYjdrRy.mjs +5 -0
  13. package/dist/models-BBd5zwn6.mjs +2 -0
  14. package/dist/{multipart-parser-DX5ZDxQv.mjs → multipart-parser-BdmM0fdd.mjs} +1 -1
  15. package/dist/node_modules/@highagency/pencil-wasm/package.json +1 -1
  16. package/dist/node_modules/@highagency/pencil-wasm/pencil.d.ts +3 -0
  17. package/dist/node_modules/@highagency/pencil-wasm/pencil.js +1 -1
  18. package/dist/node_modules/@highagency/pencil-wasm/pencil.wasm +0 -0
  19. package/dist/openai-CbFQ5q5I.mjs +18 -0
  20. package/dist/openai-codex-responses-CD-2hfWB.mjs +8 -0
  21. package/dist/openai-completions-DamtYjy7.mjs +6 -0
  22. package/dist/openai-responses-DgeWdtm-.mjs +2 -0
  23. package/dist/openai-responses-shared-DKseiGAg.mjs +11 -0
  24. package/dist/{openrouter-images-BbBWg9zF.mjs → openrouter-images-gArAwqnL.mjs} +1 -1
  25. package/dist/out/mcp-server-darwin-arm64 +0 -0
  26. package/dist/out/mcp-server-darwin-x64 +0 -0
  27. package/dist/out/mcp-server-linux-arm64 +0 -0
  28. package/dist/out/mcp-server-linux-x64 +0 -0
  29. package/dist/out/mcp-server-windows-arm64.exe +0 -0
  30. package/dist/out/mcp-server-windows-x64.exe +0 -0
  31. package/dist/out/skills/pen-dev/SKILL.md +204 -0
  32. package/dist/out/skills/pen-dev/execute.md +364 -0
  33. package/dist/out/skills/pen-dev/guide/code.md +198 -0
  34. package/dist/out/skills/pen-dev/guide/components.md +45 -0
  35. package/dist/out/skills/pen-dev/guide/design-system.md +556 -0
  36. package/dist/out/skills/pen-dev/guide/landing-page.md +31 -0
  37. package/dist/out/skills/pen-dev/guide/mobile-app.md +31 -0
  38. package/dist/out/skills/pen-dev/guide/slides.md +222 -0
  39. package/dist/out/skills/pen-dev/guide/table.md +37 -0
  40. package/dist/out/skills/pen-dev/guide/tailwind.md +328 -0
  41. package/dist/out/skills/pen-dev/guide/web-app.md +245 -0
  42. package/dist/out/skills/pen-dev/pen-schema.md +202 -0
  43. package/dist/out/skills/pen-dev/scripts-and-shaders.md +94 -0
  44. package/dist/pi-user-agent-m9a4CjJo.mjs +2 -0
  45. package/dist/{src-B_lvnEtX.mjs → src-KoDMTA_Q.mjs} +1 -1
  46. package/dist/transform-messages-BHnJzowk.mjs +2 -0
  47. package/dist/webworkerAll-CB00nbs9.mjs +2 -0
  48. package/package.json +3 -3
  49. package/dist/anthropic-messages-Bf-fvkNu.mjs +0 -40
  50. package/dist/azure-openai-responses-CzgVqECr.mjs +0 -2
  51. package/dist/browserAll-8jKh1NRi.mjs +0 -2
  52. package/dist/completionchunk-BQtPqA8U.mjs +0 -28
  53. package/dist/google-generative-ai-DSOqI0LF.mjs +0 -2
  54. package/dist/google-shared-CetPT_Vt.mjs +0 -318
  55. package/dist/google-vertex-CPtOc5oU.mjs +0 -2
  56. package/dist/mistral-conversations-CUsdbDQ8.mjs +0 -10
  57. package/dist/models-CwK5xZH9.mjs +0 -2
  58. package/dist/openai-Brr_V-tF.mjs +0 -17
  59. package/dist/openai-codex-responses-Cb5pfH5S.mjs +0 -8
  60. package/dist/openai-completions-BvTlcCeP.mjs +0 -6
  61. package/dist/openai-responses-IuaLTEHh.mjs +0 -2
  62. package/dist/openai-responses-shared-D4d0NbBE.mjs +0 -11
  63. package/dist/otel-CaADOqYZ.mjs +0 -4
  64. package/dist/transform-messages-CSBQpmXO.mjs +0 -2
  65. package/dist/webworkerAll-BD-7VH16.mjs +0 -2
  66. /package/dist/{dist-BnoSGZKP.mjs → dist-D8tvRm1b.mjs} +0 -0
  67. /package/dist/{emscripten-module.browser-F76W5DM6-CNibWX-6.mjs → emscripten-module.browser-F76W5DM6-DWhj_jYh.mjs} +0 -0
  68. /package/dist/{emscripten-module.browser-XIKQQPVU-BNfdGnMe.mjs → emscripten-module.browser-XIKQQPVU-Dmh4no3c.mjs} +0 -0
  69. /package/dist/{ffi-C5tLdQO9.mjs → ffi-BroAqW9B.mjs} +0 -0
  70. /package/dist/{ffi-BuJ13coi.mjs → ffi-DwdyvnFx.mjs} +0 -0
  71. /package/dist/{from-py2TfO8m.mjs → from-Choxbpmr.mjs} +0 -0
  72. /package/dist/{github-copilot-headers-DZOfokGy.mjs → github-copilot-headers-DCj7hJoC.mjs} +0 -0
  73. /package/dist/{hash-Kp92CI9R.mjs → hash-DNYCELl4.mjs} +0 -0
  74. /package/dist/{html-GGJ1fTRB.mjs → html-DEPARSNH.mjs} +0 -0
  75. /package/dist/{init-B9LSomNH.mjs → init-DwIpBeuP.mjs} +0 -0
  76. /package/dist/{module-ES6BEMUI-DwQ9nTMF.mjs → module-ES6BEMUI-DUGQwtIb.mjs} +0 -0
  77. /package/dist/{module-asyncify-2EFITU5U-B54Mkt6K.mjs → module-asyncify-2EFITU5U-U7fqmMTF.mjs} +0 -0
  78. /package/dist/{openai-prompt-cache-t4kk9puG.mjs → openai-prompt-cache-tVHrB8oW.mjs} +0 -0
  79. /package/dist/{photon_rs-BySSRmP5.mjs → photon_rs-o0nbTM4F.mjs} +0 -0
  80. /package/dist/{provider-retry-BM3ArvaW.mjs → provider-retry-wOYAq0sa.mjs} +0 -0
  81. /package/dist/{sanitize-unicode-CHjuq5rK.mjs → sanitize-unicode-Byz9nlLd.mjs} +0 -0
  82. /package/dist/{standalone-DYT2Zg6I.mjs → standalone-DwaYVpTH.mjs} +0 -0
@@ -0,0 +1,245 @@
1
+ # WEBAPP SYSTEM PROMPT
2
+
3
+ You are designing a responsive web application interface.
4
+
5
+ This document defines universal product design principles that apply to ANY use case:
6
+ CRM, analytics, editor, marketplace, fintech, admin panel, AI tool, or unknown future systems.
7
+
8
+ Visual identity, typography, color, and stylistic expression are defined in `brand.md`.
9
+
10
+ This file defines structural, cognitive, and product-quality laws.
11
+
12
+ Do not generate marketing pages.
13
+ Generate functional product UI only.
14
+
15
+ ---
16
+
17
+ ## 1. Purpose First
18
+
19
+ Every screen must have a clearly defined primary purpose.
20
+
21
+ - A screen should answer one dominant user question.
22
+ - A screen should support one primary action.
23
+ - If multiple goals compete, separate them into distinct surfaces.
24
+
25
+ No multi-purpose cluttered screens.
26
+
27
+ ---
28
+
29
+ ## 2. Dominant Region Rule
30
+
31
+ Every screen must contain one dominant visual region.
32
+
33
+ - Visual weight must reflect importance.
34
+ - Secondary regions must be subordinate.
35
+ - Avoid equal-weight layouts.
36
+ - Avoid competing focal points.
37
+
38
+ Hierarchy is mandatory.
39
+
40
+ ---
41
+
42
+ ## 3. Understandability
43
+
44
+ The interface must explain itself.
45
+
46
+ - Labels must be clear.
47
+ - Actions must be recognizable.
48
+ - Icons must not replace essential text.
49
+ - System state must be visible.
50
+
51
+ If a user must guess what something does, redesign it.
52
+
53
+ ---
54
+
55
+ ## 4. Progressive Disclosure
56
+
57
+ Reveal complexity gradually.
58
+
59
+ - Show essential information first.
60
+ - Advanced controls must be contextual.
61
+ - Do not overwhelm with full capability at once.
62
+ - Detail views should open on demand.
63
+
64
+ Complexity is allowed.
65
+ Confusion is not.
66
+
67
+ ---
68
+
69
+ ## 5. Recognition Over Recall
70
+
71
+ Reduce cognitive load.
72
+
73
+ - Surface relevant actions when needed.
74
+ - Do not require users to remember previous states.
75
+ - Keep navigation predictable.
76
+ - Use consistent placement of controls.
77
+
78
+ The system must reduce thinking effort.
79
+
80
+ ---
81
+
82
+ ## 6. System Status Visibility
83
+
84
+ The system must always communicate state.
85
+
86
+ Every data-driven surface must support:
87
+
88
+ - Loading state
89
+ - Empty state
90
+ - Error state
91
+ - Success confirmation
92
+ - Permission or restriction state (when applicable)
93
+
94
+ No silent failure.
95
+ No blank ambiguity.
96
+
97
+ ---
98
+
99
+ ## 7. Action Hierarchy
100
+
101
+ Actions must scale logically.
102
+
103
+ - One primary action per screen or section.
104
+ - Secondary actions visually reduced.
105
+ - Destructive actions clearly distinct.
106
+ - Rare actions placed in overflow.
107
+
108
+ Do not give equal emphasis to all actions.
109
+
110
+ Honest emphasis only.
111
+
112
+ ---
113
+
114
+ ## 8. Structural Consistency
115
+
116
+ Patterns must repeat across the system.
117
+
118
+ - Similar problems → similar solutions.
119
+ - Navigation logic must remain stable.
120
+ - Layout rhythm must feel system-driven.
121
+ - Spacing must follow a consistent scale.
122
+
123
+ Predictability builds trust.
124
+
125
+ ---
126
+
127
+ ## 9. Density Intentionality
128
+
129
+ Density must be deliberate.
130
+
131
+ Allowed modes:
132
+
133
+ - Compact → high data environments
134
+ - Medium → balanced default
135
+ - Airy → low-complexity workflows
136
+
137
+ Do not mix density modes arbitrarily within one screen.
138
+
139
+ ---
140
+
141
+ ## 10. Spatial Logic
142
+
143
+ Layout must be architectural.
144
+
145
+ - One dominant axis per screen.
146
+ - Prefer two structural zones before three.
147
+ - Avoid unnecessary nested scroll containers.
148
+ - Use whitespace for separation.
149
+ - Avoid decorative dividers unless functionally needed.
150
+
151
+ Structure over ornament.
152
+
153
+ ---
154
+
155
+ ## 11. Feedback & Response
156
+
157
+ Every user action must produce clear feedback.
158
+
159
+ - Immediate acknowledgment.
160
+ - Clear validation messaging.
161
+ - Reversible actions where possible.
162
+ - Confirm destructive operations.
163
+
164
+ Silence after interaction is unacceptable.
165
+
166
+ ---
167
+
168
+ ## 12. Responsiveness Philosophy
169
+
170
+ Hierarchy must survive all breakpoints.
171
+
172
+ Mobile:
173
+ - Single dominant column.
174
+ - Secondary panels become sheets or stacked sections.
175
+ - No horizontal scrolling unless essential.
176
+
177
+ Tablet:
178
+ - Transitional structural logic.
179
+
180
+ Desktop:
181
+ - Multi-zone allowed.
182
+ - Higher density permitted.
183
+
184
+ Scaling must preserve clarity.
185
+
186
+ ---
187
+
188
+ ## 13. Entity Integrity
189
+
190
+ Whenever representing an entity (user, record, document, asset):
191
+
192
+ - Display its name prominently.
193
+ - Surface its status clearly.
194
+ - Show key metadata.
195
+ - Make actions obvious.
196
+
197
+ Entities must feel concrete and usable.
198
+
199
+ ---
200
+
201
+ ## 14. Constraint Over Decoration
202
+
203
+ If an element does not support:
204
+
205
+ - Navigation
206
+ - Understanding
207
+ - Decision-making
208
+ - Action-taking
209
+
210
+ It should not exist.
211
+
212
+ As little design as possible.
213
+
214
+ ---
215
+
216
+ ## 15. Scalability
217
+
218
+ Design decisions must scale.
219
+
220
+ - More data must not break structure.
221
+ - More features must not collapse hierarchy.
222
+ - Growth should extend patterns, not create chaos.
223
+
224
+ Design for longevity.
225
+
226
+ ---
227
+
228
+ ## 16. Adaptation Logic
229
+
230
+ Infer product type from the user prompt.
231
+
232
+ Then determine:
233
+
234
+ - Dominant region
235
+ - Primary action
236
+ - Appropriate density
237
+ - Level of progressive disclosure
238
+
239
+ Do not assume dashboards, tables, sidebars, or canvases unless required by purpose.
240
+
241
+ Structure must emerge from utility.
242
+
243
+ ---
244
+
245
+ End of system prompt.
@@ -0,0 +1,202 @@
1
+ # .pen File Schema
2
+
3
+ ```typescript
4
+ /** Theme axis -> axis value. E.g. { 'device': 'phone' } */
5
+ export interface Theme { [key: string]: string; }
6
+ /** Dollar-prefixed variable name; binds the property to that variable. */
7
+ export type Variable = string;
8
+ export type NumberOrVariable = number | Variable;
9
+ /** Hex color: #RGB, #RRGGBB, or #RRGGBBAA. */
10
+ export type Color = string;
11
+ export type ColorOrVariable = Color | Variable;
12
+ export type BooleanOrVariable = boolean | Variable;
13
+ export type StringOrVariable = string | Variable;
14
+ export interface Layout {
15
+ /** Flex layout direction. 'none'=absolutely positioned children. */
16
+ layout?: "none" | "vertical" | "horizontal";
17
+ /** Main-axis gap between children. Default 0. */
18
+ gap?: NumberOrVariable;
19
+ layoutIncludeStroke?: boolean;
20
+ /** Inside padding. */
21
+ padding?: /** all sides */ NumberOrVariable | /** [vertical, horizontal] */ [NumberOrVariable, NumberOrVariable] | /** [top, right, bottom, left] */ [NumberOrVariable, NumberOrVariable, NumberOrVariable, NumberOrVariable];
22
+ /** Main-axis alignment. Default 'start'. */
23
+ justifyContent?: "start" | "center" | "end" | "space_between" | "space_around";
24
+ /** Cross-axis alignment. Default 'start'. */
25
+ alignItems?: "start" | "center" | "end";
26
+ }
27
+ /** Dynamic layout size:
28
+ - fit_content: combined size of children, requires layout on the node (fallback when no children).
29
+ - fill_container: parent size, requires layout on the parent (fallback when not in a layout or when using absolute position).
30
+ Optional fallback in parens, e.g. 'fit_content(100)'. */
31
+ export type SizingBehavior = string;
32
+ /** Position relative to parent. X right, Y down. IGNORED when parent uses flex layout. */
33
+ export interface Position { x?: number; y?: number; }
34
+ export interface Size { width?: NumberOrVariable | SizingBehavior; height?: NumberOrVariable | SizingBehavior; }
35
+ export type BlendMode = 'normal' | 'darken' | 'multiply' | 'linearBurn' | 'colorBurn' | 'light' | 'screen' | 'linearDodge' | 'colorDodge' | 'overlay' | 'softLight' | 'hardLight' | 'difference' | 'exclusion' | 'hue' | 'saturation' | 'color' | 'luminosity';
36
+ export type Fill = ColorOrVariable | {
37
+ type: "color";
38
+ enabled?: BooleanOrVariable;
39
+ blendMode?: BlendMode;
40
+ /** Fill opacity can only be set via the hex alpha channel. */
41
+ color: ColorOrVariable;
42
+ } | {
43
+ type: "gradient";
44
+ enabled?: BooleanOrVariable;
45
+ blendMode?: BlendMode;
46
+ gradientType?: "linear" | "radial" | "angular";
47
+ opacity?: NumberOrVariable;
48
+ /** Normalized to bbox. Default 0.5,0.5. */
49
+ center?: Position;
50
+ /** Normalized to bbox. Default 1,1. Linear: height = gradient length, width ignored. Radial/Angular: ellipse diameters. */
51
+ size?: { width?: NumberOrVariable; height?: NumberOrVariable };
52
+ /** Degrees CCW (0° up, 90° left, 180° down). */
53
+ rotation?: NumberOrVariable;
54
+ colors?: { color: ColorOrVariable; position: NumberOrVariable }[];
55
+ } | /** Image fill. URL is relative to the .pen file, e.g. `./image.jpg`. */ { type: "image"; enabled?: BooleanOrVariable; blendMode?: BlendMode; opacity?: NumberOrVariable; url?: string; mode?: "stretch" | "fill" | "fit" } | /** Shader fill. URL points to a WebGL 1.0 (#version 100) fragment shader file, relative to the .pen file, e.g. `./effect.glsl`. Uniforms are described via `@directive` annotations inside block comments in the shader source. A `vec2` uniform annotated with `@resolution` is auto-bound to the fill size in pixels. Other uniforms' user-set values are stored in `uniforms`. */ {
56
+ type: "shader";
57
+ enabled?: BooleanOrVariable;
58
+ blendMode?: BlendMode;
59
+ opacity?: NumberOrVariable;
60
+ url: string;
61
+ /** Override values for shader uniforms, keyed by uniform name. Uniforms annotated with `@resolution` or `@time` must not appear here. Allowed value shapes: number (float/int), boolean (bool), hex color string like `#RRGGBB[AA]` (color), array of 2-4 numbers (vec2/3/4), or a variable reference `$name` (numeric uniforms accept number variables; color uniforms accept color variables). */
62
+ uniforms?: { [key: string]: number | boolean | string | number[] };
63
+ } | /** Bezier-interpolated color grid, row-major. Keep edge points at default positions. */ {
64
+ type: "mesh_gradient";
65
+ enabled?: BooleanOrVariable;
66
+ blendMode?: BlendMode;
67
+ opacity?: NumberOrVariable;
68
+ columns?: number;
69
+ rows?: number;
70
+ /** Color per vertex. */
71
+ colors?: ColorOrVariable[];
72
+ /** columns * rows points in [0,1]. */
73
+ points?: (/** Auto-generated handles. */ [number, number] | /** Optional bezier handles (relative offsets); omitted = auto. */ { position: [number, number]; leftHandle?: [number, number]; rightHandle?: [number, number]; topHandle?: [number, number]; bottomHandle?: [number, number] })[];
74
+ };
75
+ export type Fills = Fill | Fill[];
76
+ export interface CanHaveStroke {
77
+ stroke?: Fills;
78
+ /** Stroke thickness, uniform or per side. */
79
+ strokeWidth?: NumberOrVariable | { top?: NumberOrVariable; right?: NumberOrVariable; bottom?: NumberOrVariable; left?: NumberOrVariable };
80
+ strokeLinecap?: "butt" | "round" | "square";
81
+ strokeLinejoin?: "miter" | "bevel" | "round";
82
+ strokeAlignment?: "inner" | "center" | "outer";
83
+ }
84
+ export type Effect = /** Blurs the entire node. */ { enabled?: BooleanOrVariable; type: "blur"; radius?: NumberOrVariable } | /** Blurs the backdrop behind the node. */ { enabled?: BooleanOrVariable; type: "background_blur"; radius?: NumberOrVariable } | /** Inner or outer drop shadow. */ { type: "shadow"; enabled?: BooleanOrVariable; shadowType?: "inner" | "outer"; offset?: { x: NumberOrVariable; y: NumberOrVariable }; spread?: NumberOrVariable; blur?: NumberOrVariable; color?: ColorOrVariable; blendMode?: BlendMode };
85
+ export type Effects = Effect | Effect[];
86
+ export interface CanHaveEffects { effect?: Effects; }
87
+ export interface CanHaveGraphics extends CanHaveEffects, CanHaveStroke { fill?: Fills; }
88
+ export interface Entity extends Position {
89
+ /** Unique string; MUST NOT contain '/'. Auto-generated if omitted. */
90
+ id: string;
91
+ name?: string;
92
+ context?: string;
93
+ /** When true, can be duplicated via `ref` objects. Default false. */
94
+ reusable?: boolean;
95
+ theme?: Theme;
96
+ enabled?: BooleanOrVariable;
97
+ opacity?: NumberOrVariable;
98
+ flipX?: BooleanOrVariable;
99
+ flipY?: BooleanOrVariable;
100
+ /** Absolute position detaches the object from parent's layout and can be absolute positioned. Default auto */
101
+ layoutPosition?: "auto" | "absolute";
102
+ metadata?: { type: string; [key: string]: any };
103
+ /** Degrees CCW around top-left corner. */
104
+ rotation?: NumberOrVariable;
105
+ }
106
+ export interface Rectangleish extends Entity, Size, CanHaveGraphics { cornerRadius?: NumberOrVariable | [NumberOrVariable, NumberOrVariable, NumberOrVariable, NumberOrVariable]; }
107
+ /** Position is the top-left corner. */
108
+ export interface Rectangle extends Rectangleish { type: "rectangle"; }
109
+ /** Defined by its bounding rectangle. */
110
+ export interface Ellipse extends Entity, Size, CanHaveGraphics {
111
+ type: "ellipse";
112
+ /** Ring inner/outer radius ratio. 0=solid, 1=hollow. Default 0. */
113
+ innerRadius?: NumberOrVariable;
114
+ /** Arc start angle, degrees CCW from right. Default 0. */
115
+ startAngle?: NumberOrVariable;
116
+ /** Arc length from startAngle. Positive=CCW, negative=CW. Range -360..360. Default 360. */
117
+ sweepAngle?: NumberOrVariable;
118
+ }
119
+ /** Defined by its bounding rectangle. */
120
+ export interface Polygon extends Entity, Size, CanHaveGraphics { type: "polygon"; polygonCount?: NumberOrVariable; cornerRadius?: NumberOrVariable; }
121
+ export interface Path extends Entity, Size, CanHaveGraphics {
122
+ /** Default 'nonzero'. */
123
+ fillRule?: "nonzero" | "evenodd";
124
+ /** SVG path. */
125
+ geometry?: string;
126
+ /** SVG coord-space [x,y,w,h] mapping onto the node box. Default: tight bbox of geometry. */
127
+ viewBox?: [number, number, number, number];
128
+ type: "path";
129
+ }
130
+ export interface TextStyle {
131
+ fontFamily?: StringOrVariable;
132
+ fontSize?: NumberOrVariable;
133
+ fontWeight?: StringOrVariable;
134
+ letterSpacing?: NumberOrVariable;
135
+ fontStyle?: StringOrVariable;
136
+ underline?: BooleanOrVariable;
137
+ /** Multiplier of fontSize. Defaults to font's built-in. */
138
+ lineHeight?: NumberOrVariable;
139
+ textAlign?: "left" | "center" | "right" | "justify";
140
+ textAlignVertical?: "top" | "middle" | "bottom";
141
+ strikethrough?: BooleanOrVariable;
142
+ href?: string;
143
+ }
144
+ export type TextContent = StringOrVariable;
145
+ export interface Text extends Entity, Size, CanHaveGraphics, TextStyle {
146
+ type: "text";
147
+ content?: TextContent;
148
+ /** Required before width/height take effect.
149
+ 'auto': grows to fit; no wrapping.
150
+ 'fixed-width': width fixed, wraps; height grows.
151
+ 'fixed-width-height': both fixed; may overflow. */
152
+ textGrowth?: "auto" | "fixed-width" | "fixed-width-height";
153
+ }
154
+ export interface CanHaveChildren { children?: Child[]; }
155
+ /** Container to create hierarchy and layout. default layout=horizontal, width=fit_content, height=fit_content, clip=false. */
156
+ export interface Frame extends Rectangleish, CanHaveChildren, Layout {
157
+ type: "frame";
158
+ /** Clip overflow. Default false. */
159
+ clip?: BooleanOrVariable;
160
+ placeholder?: boolean;
161
+ /** Marks frame as a slot for component instances. Array entries are IDs of recommended reusable child components (e.g. menu items inside a menu bar). */
162
+ slot?: false | string[];
163
+ }
164
+ export interface Group extends Entity, CanHaveChildren, CanHaveEffects { type: "group"; }
165
+ export interface Note extends Entity, Size, TextStyle { type: "note"; content?: TextContent; }
166
+ export interface Prompt extends Entity, Size, TextStyle { type: "prompt"; content?: TextContent; model?: StringOrVariable; }
167
+ export interface Context extends Entity, Size, TextStyle { type: "context"; content?: TextContent; }
168
+ /** Icon from a library. The icon is scaled to fit the width and height. */
169
+ export interface Icon extends Entity, Size, CanHaveEffects {
170
+ type: "icon";
171
+ /** Valid: 'lucide', 'feather', 'Material Symbols Outlined', 'Material Symbols Rounded', 'Material Symbols Sharp', 'phosphor'. */
172
+ library?: StringOrVariable;
173
+ icon?: StringOrVariable;
174
+ /** Variable weight, 100-700; only for libraries that support it. */
175
+ weight?: NumberOrVariable;
176
+ fill?: Fills;
177
+ }
178
+ /** Generates nested children from JavaScript. */
179
+ export interface Script extends Entity, Size {
180
+ type: "script";
181
+ /** Clip overflow. Default false. */
182
+ clip?: BooleanOrVariable;
183
+ /** JS file URI, relative to the .pen file. */
184
+ scriptUri?: string;
185
+ /** Input values by name. */
186
+ inputs?: { [key: string]: string | number | boolean | Variable };
187
+ }
188
+ /** Reuses another object. */
189
+ export interface Ref extends Entity {
190
+ type: "ref";
191
+ /** ID of the referenced object. */
192
+ ref: string;
193
+ /** Customize descendant properties. */
194
+ descendants?: { [key: string /** ID path of the descendant. */]: {} /** Based on the presence of `type`:
195
+ - `type` is not present = property overrides: the descendant node is updated with the listed properties.
196
+ - `type` is present = replacement: the descendant node is fully replaced with a new node tree. */ };
197
+ [key: string]: any;
198
+ }
199
+ export type Child = Frame | Group | Rectangle | Ellipse | Path | Polygon | Text | Note | Prompt | Context | Icon | Script | Ref;
200
+ export type IdPath = string;
201
+ export interface Document { version: "2.17"; themes?: { [key: string /** RegEx: [^:]+ */]: string[] }; imports?: { [key: string]: string /** Value: relative URI of imported .pen file. Key: short alias. */ }; variables?: { [key: string /** RegEx: [^:]+ */]: { type: "boolean"; value: BooleanOrVariable | { value: BooleanOrVariable; theme?: Theme }[] } | { type: "color"; value: ColorOrVariable | { value: ColorOrVariable; theme?: Theme }[] } | { type: "number"; value: NumberOrVariable | { value: NumberOrVariable; theme?: Theme }[] } | { type: "string"; value: StringOrVariable | { value: StringOrVariable; theme?: Theme }[] } }; children: (Frame | Group | Rectangle | Ellipse | Polygon | Path | Text | Note | Context | Prompt | Icon | Script | Ref)[]; }
202
+ ```
@@ -0,0 +1,94 @@
1
+ # Using scripts and shaders on the pen.dev canvas
2
+
3
+ ## Scripting
4
+
5
+ Use `script` node types to generate content with JavaScript. Scripts are `.js` files on disk, referenced via relative uri path in `scriptUri`.
6
+
7
+ - Every script must start with `/** @schema 2.11 */` (current version). Missing this tag is an error.
8
+ - Scripts receive a `pencil` object: `pencil.width`, `pencil.height`, `pencil.input.<name>`.
9
+ - Scripts must return an array of node objects following the `.pen` schema.
10
+ - Declare inputs as `@input name: type [= default]`. Available types: `number`, `string`, `boolean`, `color`, `ref`, `enum`.
11
+ - Math.random() is deterministic in scripts and can be safely used for procedural generation.
12
+
13
+ ```js
14
+ /**
15
+ * @schema 2.11
16
+ * @input rows: number = 3
17
+ * @input gap: number = 4
18
+ * @input color: color = #3B82F6
19
+ * @input label: string = "Hello"
20
+ * @input filled: boolean = true
21
+ * @input layout: enum("grid", "stack", "scatter") = "grid"
22
+ * @input target: ref
23
+ */
24
+ const rows = Math.max(1, Math.floor(pencil.input.rows));
25
+ const cellH = (pencil.height - pencil.input.gap * (rows - 1)) / rows;
26
+
27
+ const nodes = [];
28
+ for (let r = 0; r < rows; r++) {
29
+ nodes.push({
30
+ type: "rectangle",
31
+ name: "Bar " + (r + 1),
32
+ x: 0,
33
+ y: r * (cellH + pencil.input.gap),
34
+ width: pencil.width,
35
+ height: cellH * Math.random(),
36
+ fill: pencil.input.color,
37
+ });
38
+ }
39
+
40
+ return nodes;
41
+ ```
42
+
43
+ ## Shaders
44
+
45
+ The `shader` fill type can be used to create complex graphics effects using WebGL shaders.
46
+
47
+ - Shaders are WebGL 1.0 fragment shaders (#version 100), with one addition: textureSize(sampler, lod) is available for aspect-correct texturing.
48
+ - Supported uniform types:
49
+ - float, int: as numbers
50
+ - vec2/3/4, ivec2/3/4: as arrays of numbers or "#RRGGBB" strings for colors
51
+ - sampler2D: as image URL strings
52
+ - Uniforms can be annotated with special comments:
53
+ - @color: marks vec3 or vec4 uniforms to use color picker controls.
54
+ - @default: sets the default value for the uniform.
55
+ - @resolution: set to the resolution of the output. e.g. can be used to normalize gl_FragCoord.
56
+ - @mouse: set to the mouse position in the same space as gl_FragCoord. For interactive effects.
57
+ - @time: set to the elapsed time in seconds. For animations.
58
+ - @sdf: a sampler2D set to an SDF texture of the node's shape. The r channel holds the signed distance in @resolution units (positive = inside). The gb channels hold the gradient of the distance field (direction of increasing distance), in texel space. Use gb instead of numerically differentiating the r channel!
59
+ - @backdrop: a sampler2D set to the content rendered behind the node. offset/distort the sampling coordinate for refraction-like effects. Ideal for glass/frosted/refraction/magnifier effects. Prefer @backdrop over faking the background.
60
+ - @min/@max: set the range of a uniform for better UI controls. Only applies to number uniforms.
61
+ - @range <min>, <max>: shorthand for @min and @max on the same line. Shows a slider in the UI.
62
+ - @label <text>: sets the uniform's display name in the UI. Always set the label.
63
+
64
+ ```glsl
65
+ /** @resolution */
66
+ uniform vec2 u_resolution;
67
+
68
+ /**
69
+ * @label Size
70
+ * @default 32
71
+ */
72
+ uniform float u_size;
73
+
74
+ /**
75
+ * @label Primary Color
76
+ * @color
77
+ * @default #ffffff
78
+ */
79
+ uniform vec3 u_color1;
80
+
81
+ /**
82
+ * @label Secondary Color
83
+ * @color
84
+ * @default #000000
85
+ */
86
+ uniform vec3 u_color2;
87
+
88
+ void main() {
89
+ vec2 cell = floor(gl_FragCoord.xy / u_size);
90
+ float check = mod(cell.x + cell.y, 2.0);
91
+ vec3 color = mix(u_color1, u_color2, check);
92
+ gl_FragColor = vec4(color, 1.0);
93
+ }
94
+ ```
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ function e(){return typeof process>`u`||!(process.versions?.node||process.versions?.bun)?null:process.getBuiltinModule?.(`node:os`)??null}const t=e();function n(){return t?`pi (${t.platform()} ${t.release()}; ${t.arch()})`:`pi (browser)`}export{n as t};
@@ -1,4 +1,4 @@
1
1
  #!/usr/bin/env node
2
- import{lt as e}from"./index.mjs";import{a as t,i as n,n as r,o as i,r as a,s as o,t as s}from"./from-py2TfO8m.mjs";import{format as c}from"node:url";import{Buffer as l}from"node:buffer";import u,{PassThrough as d,pipeline as f}from"node:stream";import{deprecate as p,promisify as m,types as h}from"node:util";import g from"node:zlib";import{isIP as _}from"node:net";import v from"node:http";import ee from"node:https";function te(e){if(!/^data:/i.test(e))throw TypeError('`uri` does not appear to be a Data URI (must begin with "data:")');e=e.replace(/\r?\n/g,``);let t=e.indexOf(`,`);if(t===-1||t<=4)throw TypeError(`malformed data: URI`);let n=e.substring(5,t).split(`;`),r=``,i=!1,a=n[0]||`text/plain`,o=a;for(let e=1;e<n.length;e++)n[e]===`base64`?i=!0:n[e]&&(o+=`;${n[e]}`,n[e].indexOf(`charset=`)===0&&(r=n[e].substring(8)));!n[0]&&!r.length&&(o+=`;charset=US-ASCII`,r=`US-ASCII`);let s=i?`base64`:`ascii`,c=unescape(e.substring(t+1)),l=Buffer.from(c,s);return l.type=a,l.typeFull=o,l.charset=r,l}var ne=e((()=>{})),y,b=e((()=>{y=class extends Error{constructor(e,t){super(e),Error.captureStackTrace(this,this.constructor),this.type=t}get name(){return this.constructor.name}get[Symbol.toStringTag](){return this.constructor.name}}})),x,re=e((()=>{b(),x=class extends y{constructor(e,t,n){super(e,t),n&&(this.code=this.errno=n.code,this.erroredSysCall=n.syscall)}}})),S,C,w,T,E,ie,D=e((()=>{S=Symbol.toStringTag,C=e=>typeof e==`object`&&typeof e.append==`function`&&typeof e.delete==`function`&&typeof e.get==`function`&&typeof e.getAll==`function`&&typeof e.has==`function`&&typeof e.set==`function`&&typeof e.sort==`function`&&e[S]===`URLSearchParams`,w=e=>e&&typeof e==`object`&&typeof e.arrayBuffer==`function`&&typeof e.type==`string`&&typeof e.stream==`function`&&typeof e.constructor==`function`&&/^(Blob|File)$/.test(e[S]),T=e=>typeof e==`object`&&(e[S]===`AbortSignal`||e[S]===`EventTarget`),E=(e,t)=>{let n=new URL(t).hostname,r=new URL(e).hostname;return n===r||n.endsWith(`.${r}`)},ie=(e,t)=>new URL(t).protocol===new URL(e).protocol}));async function O(e){if(e[A].disturbed)throw TypeError(`body used already for: ${e.url}`);if(e[A].disturbed=!0,e[A].error)throw e[A].error;let{body:t}=e;if(t===null||!(t instanceof u))return l.alloc(0);let n=[],r=0;try{for await(let i of t){if(e.size>0&&r+i.length>e.size){let n=new x(`content size at ${e.url} over limit: ${e.size}`,`max-size`);throw t.destroy(n),n}r+=i.length,n.push(i)}}catch(t){throw t instanceof y?t:new x(`Invalid response body while trying to fetch ${e.url}: ${t.message}`,`system`,t)}if(t.readableEnded===!0||t._readableState.ended===!0)try{return n.every(e=>typeof e==`string`)?l.from(n.join(``)):l.concat(n,r)}catch(t){throw new x(`Could not create Buffer from response body for ${e.url}: ${t.message}`,`system`,t)}else throw new x(`Premature close of server response while trying to fetch ${e.url}`)}var k,A,j,M,N,P,F,ae,I=e((()=>{o(),n(),re(),b(),D(),k=m(u.pipeline),A=Symbol(`Body internals`),j=class{constructor(e,{size:t=0}={}){let n=null;e===null?e=null:C(e)?e=l.from(e.toString()):w(e)||l.isBuffer(e)||(h.isAnyArrayBuffer(e)?e=l.from(e):ArrayBuffer.isView(e)?e=l.from(e.buffer,e.byteOffset,e.byteLength):e instanceof u||(e instanceof r?(e=a(e),n=e.type.split(`=`)[1]):e=l.from(String(e))));let i=e;l.isBuffer(e)?i=u.Readable.from(e):w(e)&&(i=u.Readable.from(e.stream())),this[A]={body:e,stream:i,boundary:n,disturbed:!1,error:null},this.size=t,e instanceof u&&e.on(`error`,e=>{let t=e instanceof y?e:new x(`Invalid response body while trying to fetch ${this.url}: ${e.message}`,`system`,e);this[A].error=t})}get body(){return this[A].stream}get bodyUsed(){return this[A].disturbed}async arrayBuffer(){let{buffer:e,byteOffset:t,byteLength:n}=await O(this);return e.slice(t,t+n)}async formData(){let e=this.headers.get(`content-type`);if(e.startsWith(`application/x-www-form-urlencoded`)){let e=new r,t=new URLSearchParams(await this.text());for(let[n,r]of t)e.append(n,r);return e}let{toFormData:t}=await import(`./multipart-parser-DX5ZDxQv.mjs`);return t(this.body,e)}async blob(){let e=this.headers&&this.headers.get(`content-type`)||this[A].body&&this[A].body.type||``;return new i([await this.arrayBuffer()],{type:e})}async json(){let e=await this.text();return JSON.parse(e)}async text(){let e=await O(this);return new TextDecoder().decode(e)}buffer(){return O(this)}},j.prototype.buffer=p(j.prototype.buffer,`Please use 'response.arrayBuffer()' instead of 'response.buffer()'`,`node-fetch#buffer`),Object.defineProperties(j.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0},data:{get:p(()=>{},`data doesn't exist, use json(), text(), arrayBuffer(), or body instead`,`https://github.com/node-fetch/node-fetch/issues/1000 (response)`)}}),M=(e,t)=>{let n,r,{body:i}=e[A];if(e.bodyUsed)throw Error(`cannot clone body after it is used`);return i instanceof u&&typeof i.getBoundary!=`function`&&(n=new d({highWaterMark:t}),r=new d({highWaterMark:t}),i.pipe(n),i.pipe(r),e[A].stream=n,i=r),i},N=p(e=>e.getBoundary(),`form-data doesn't follow the spec and requires special treatment. Use alternative package`,`https://github.com/node-fetch/node-fetch/issues/1167`),P=(e,t)=>e===null?null:typeof e==`string`?`text/plain;charset=UTF-8`:C(e)?`application/x-www-form-urlencoded;charset=UTF-8`:w(e)?e.type||null:l.isBuffer(e)||h.isAnyArrayBuffer(e)||ArrayBuffer.isView(e)?null:e instanceof r?`multipart/form-data; boundary=${t[A].boundary}`:e&&typeof e.getBoundary==`function`?`multipart/form-data;boundary=${N(e)}`:e instanceof u?null:`text/plain;charset=UTF-8`,F=e=>{let{body:t}=e[A];return t===null?0:w(t)?t.size:l.isBuffer(t)?t.length:t&&typeof t.getLengthSync==`function`&&t.hasKnownLength&&t.hasKnownLength()?t.getLengthSync():null},ae=async(e,{body:t})=>{t===null?e.end():await k(t,e)}}));function oe(e=[]){return new z(e.reduce((e,t,n,r)=>(n%2==0&&e.push(r.slice(n,n+2)),e),[]).filter(([e,t])=>{try{return L(e),R(e,String(t)),!0}catch{return!1}}))}var L,R,z,B=e((()=>{L=typeof v.validateHeaderName==`function`?v.validateHeaderName:e=>{if(!/^[\^`\-\w!#$%&'*+.|~]+$/.test(e)){let t=TypeError(`Header name must be a valid HTTP token [${e}]`);throw Object.defineProperty(t,`code`,{value:`ERR_INVALID_HTTP_TOKEN`}),t}},R=typeof v.validateHeaderValue==`function`?v.validateHeaderValue:(e,t)=>{if(/[^\t\u0020-\u007E\u0080-\u00FF]/.test(t)){let t=TypeError(`Invalid character in header content ["${e}"]`);throw Object.defineProperty(t,`code`,{value:`ERR_INVALID_CHAR`}),t}},z=class e extends URLSearchParams{constructor(t){let n=[];if(t instanceof e){let e=t.raw();for(let[t,r]of Object.entries(e))n.push(...r.map(e=>[t,e]))}else if(t!=null)if(typeof t==`object`&&!h.isBoxedPrimitive(t)){let e=t[Symbol.iterator];if(e==null)n.push(...Object.entries(t));else{if(typeof e!=`function`)throw TypeError(`Header pairs must be iterable`);n=[...t].map(e=>{if(typeof e!=`object`||h.isBoxedPrimitive(e))throw TypeError(`Each header pair must be an iterable object`);return[...e]}).map(e=>{if(e.length!==2)throw TypeError(`Each header pair must be a name/value tuple`);return[...e]})}}else throw TypeError(`Failed to construct 'Headers': The provided value is not of type '(sequence<sequence<ByteString>> or record<ByteString, ByteString>)`);return n=n.length>0?n.map(([e,t])=>(L(e),R(e,String(t)),[String(e).toLowerCase(),String(t)])):void 0,super(n),new Proxy(this,{get(e,t,n){switch(t){case`append`:case`set`:return(n,r)=>(L(n),R(n,String(r)),URLSearchParams.prototype[t].call(e,String(n).toLowerCase(),String(r)));case`delete`:case`has`:case`getAll`:return n=>(L(n),URLSearchParams.prototype[t].call(e,String(n).toLowerCase()));case`keys`:return()=>(e.sort(),new Set(URLSearchParams.prototype.keys.call(e)).keys());default:return Reflect.get(e,t,n)}}})}get[Symbol.toStringTag](){return this.constructor.name}toString(){return Object.prototype.toString.call(this)}get(e){let t=this.getAll(e);if(t.length===0)return null;let n=t.join(`, `);return/^content-encoding$/i.test(e)&&(n=n.toLowerCase()),n}forEach(e,t=void 0){for(let n of this.keys())Reflect.apply(e,t,[this.get(n),n,this])}*values(){for(let e of this.keys())yield this.get(e)}*entries(){for(let e of this.keys())yield[e,this.get(e)]}[Symbol.iterator](){return this.entries()}raw(){return[...this.keys()].reduce((e,t)=>(e[t]=this.getAll(t),e),{})}[Symbol.for(`nodejs.util.inspect.custom`)](){return[...this.keys()].reduce((e,t)=>{let n=this.getAll(t);return t===`host`?e[t]=n[0]:e[t]=n.length>1?n:n[0],e},{})}},Object.defineProperties(z.prototype,[`get`,`entries`,`forEach`,`values`].reduce((e,t)=>(e[t]={enumerable:!0},e),{}))})),V,H,U=e((()=>{V=new Set([301,302,303,307,308]),H=e=>V.has(e)})),W,G,se=e((()=>{B(),I(),U(),W=Symbol(`Response internals`),G=class e extends j{constructor(e=null,t={}){super(e,t);let n=t.status==null?200:t.status,r=new z(t.headers);if(e!==null&&!r.has(`Content-Type`)){let t=P(e,this);t&&r.append(`Content-Type`,t)}this[W]={type:`default`,url:t.url,status:n,statusText:t.statusText||``,headers:r,counter:t.counter,highWaterMark:t.highWaterMark}}get type(){return this[W].type}get url(){return this[W].url||``}get status(){return this[W].status}get ok(){return this[W].status>=200&&this[W].status<300}get redirected(){return this[W].counter>0}get statusText(){return this[W].statusText}get headers(){return this[W].headers}get highWaterMark(){return this[W].highWaterMark}clone(){return new e(M(this,this.highWaterMark),{type:this.type,url:this.url,status:this.status,statusText:this.statusText,headers:this.headers,ok:this.ok,redirected:this.redirected,size:this.size,highWaterMark:this.highWaterMark})}static redirect(t,n=302){if(!H(n))throw RangeError(`Failed to execute "redirect" on "response": Invalid status code`);return new e(null,{headers:{location:new URL(t).toString()},status:n})}static error(){let t=new e(null,{status:0,statusText:``});return t[W].type=`error`,t}static json(t=void 0,n={}){let r=JSON.stringify(t);if(r===void 0)throw TypeError(`data is not JSON serializable`);let i=new z(n&&n.headers);return i.has(`content-type`)||i.set(`content-type`,`application/json`),new e(r,{...n,headers:i})}get[Symbol.toStringTag](){return`Response`}},Object.defineProperties(G.prototype,{type:{enumerable:!0},url:{enumerable:!0},status:{enumerable:!0},ok:{enumerable:!0},redirected:{enumerable:!0},statusText:{enumerable:!0},headers:{enumerable:!0},clone:{enumerable:!0}})})),K,ce=e((()=>{K=e=>{if(e.search)return e.search;let t=e.href.length-1,n=e.hash||(e.href[t]===`#`?`#`:``);return e.href[t-n.length]===`?`?`?`:``}}));function q(e,t=!1){return e==null||(e=new URL(e),/^(about|blob|data):$/.test(e.protocol))?`no-referrer`:(e.username=``,e.password=``,e.hash=``,t&&(e.pathname=``,e.search=``),e)}function le(e){if(!Y.has(e))throw TypeError(`Invalid referrerPolicy: ${e}`);return e}function ue(e){if(/^(http|ws)s:$/.test(e.protocol))return!0;let t=e.host.replace(/(^\[)|(]$)/g,``),n=_(t);return n===4&&/^127\./.test(t)||n===6&&/^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(t)?!0:e.host===`localhost`||e.host.endsWith(`.localhost`)?!1:e.protocol===`file:`}function J(e){return/^about:(blank|srcdoc)$/.test(e)||e.protocol===`data:`||/^(blob|filesystem):$/.test(e.protocol)?!0:ue(e)}function de(e,{referrerURLCallback:t,referrerOriginCallback:n}={}){if(e.referrer===`no-referrer`||e.referrerPolicy===``)return null;let r=e.referrerPolicy;if(e.referrer===`about:client`)return`no-referrer`;let i=e.referrer,a=q(i),o=q(i,!0);a.toString().length>4096&&(a=o),t&&(a=t(a)),n&&(o=n(o));let s=new URL(e.url);switch(r){case`no-referrer`:return`no-referrer`;case`origin`:return o;case`unsafe-url`:return a;case`strict-origin`:return J(a)&&!J(s)?`no-referrer`:o.toString();case`strict-origin-when-cross-origin`:return a.origin===s.origin?a:J(a)&&!J(s)?`no-referrer`:o;case`same-origin`:return a.origin===s.origin?a:`no-referrer`;case`origin-when-cross-origin`:return a.origin===s.origin?a:o;case`no-referrer-when-downgrade`:return J(a)&&!J(s)?`no-referrer`:a;default:throw TypeError(`Invalid referrerPolicy: ${r}`)}}function fe(e){let t=(e.get(`referrer-policy`)||``).split(/[,\s]+/),n=``;for(let e of t)e&&Y.has(e)&&(n=e);return n}var Y,X,pe=e((()=>{Y=new Set([``,`no-referrer`,`no-referrer-when-downgrade`,`same-origin`,`origin`,`strict-origin`,`origin-when-cross-origin`,`strict-origin-when-cross-origin`,`unsafe-url`]),X=`strict-origin-when-cross-origin`})),Z,Q,me,$,he,ge=e((()=>{B(),I(),D(),ce(),pe(),Z=Symbol(`Request internals`),Q=e=>typeof e==`object`&&typeof e[Z]==`object`,me=p(()=>{},`.data is not a valid RequestInit property, use .body instead`,`https://github.com/node-fetch/node-fetch/issues/1000 (request)`),$=class e extends j{constructor(e,t={}){let n;if(Q(e)?n=new URL(e.url):(n=new URL(e),e={}),n.username!==``||n.password!==``)throw TypeError(`${n} is an url with embedded credentials.`);let r=t.method||e.method||`GET`;if(/^(delete|get|head|options|post|put)$/i.test(r)&&(r=r.toUpperCase()),!Q(t)&&`data`in t&&me(),(t.body!=null||Q(e)&&e.body!==null)&&(r===`GET`||r===`HEAD`))throw TypeError(`Request with GET/HEAD method cannot have body`);let i=t.body?t.body:Q(e)&&e.body!==null?M(e):null;super(i,{size:t.size||e.size||0});let a=new z(t.headers||e.headers||{});if(i!==null&&!a.has(`Content-Type`)){let e=P(i,this);e&&a.set(`Content-Type`,e)}let o=Q(e)?e.signal:null;if(`signal`in t&&(o=t.signal),o!=null&&!T(o))throw TypeError(`Expected signal to be an instanceof AbortSignal or EventTarget`);let s=t.referrer==null?e.referrer:t.referrer;if(s===``)s=`no-referrer`;else if(s){let e=new URL(s);s=/^about:(\/\/)?client$/.test(e)?`client`:e}else s=void 0;this[Z]={method:r,redirect:t.redirect||e.redirect||`follow`,headers:a,parsedURL:n,signal:o,referrer:s},this.follow=t.follow===void 0?e.follow===void 0?20:e.follow:t.follow,this.compress=t.compress===void 0?e.compress===void 0?!0:e.compress:t.compress,this.counter=t.counter||e.counter||0,this.agent=t.agent||e.agent,this.highWaterMark=t.highWaterMark||e.highWaterMark||16384,this.insecureHTTPParser=t.insecureHTTPParser||e.insecureHTTPParser||!1,this.referrerPolicy=t.referrerPolicy||e.referrerPolicy||``}get method(){return this[Z].method}get url(){return c(this[Z].parsedURL)}get headers(){return this[Z].headers}get redirect(){return this[Z].redirect}get signal(){return this[Z].signal}get referrer(){if(this[Z].referrer===`no-referrer`)return``;if(this[Z].referrer===`client`)return`about:client`;if(this[Z].referrer)return this[Z].referrer.toString()}get referrerPolicy(){return this[Z].referrerPolicy}set referrerPolicy(e){this[Z].referrerPolicy=le(e)}clone(){return new e(this)}get[Symbol.toStringTag](){return`Request`}},Object.defineProperties($.prototype,{method:{enumerable:!0},url:{enumerable:!0},headers:{enumerable:!0},redirect:{enumerable:!0},clone:{enumerable:!0},signal:{enumerable:!0},referrer:{enumerable:!0},referrerPolicy:{enumerable:!0}}),he=e=>{let{parsedURL:t}=e[Z],n=new z(e[Z].headers);n.has(`Accept`)||n.set(`Accept`,`*/*`);let r=null;if(e.body===null&&/^(post|put)$/i.test(e.method)&&(r=`0`),e.body!==null){let t=F(e);typeof t==`number`&&!Number.isNaN(t)&&(r=String(t))}r&&n.set(`Content-Length`,r),e.referrerPolicy===``&&(e.referrerPolicy=X),e.referrer&&e.referrer!==`no-referrer`?e[Z].referrer=de(e):e[Z].referrer=`no-referrer`,e[Z].referrer instanceof URL&&n.set(`Referer`,e.referrer),n.has(`User-Agent`)||n.set(`User-Agent`,`node-fetch`),e.compress&&!n.has(`Accept-Encoding`)&&n.set(`Accept-Encoding`,`gzip, deflate, br`);let{agent:i}=e;typeof i==`function`&&(i=i(t));let a=K(t);return{parsedURL:t,options:{path:t.pathname+a,method:e.method,headers:n[Symbol.for(`nodejs.util.inspect.custom`)](),insecureHTTPParser:e.insecureHTTPParser,agent:i}}}})),_e,ve=e((()=>{b(),_e=class extends y{constructor(e,t=`aborted`){super(e,t)}}}));async function ye(e,t){return new Promise((n,r)=>{let i=new $(e,t),{parsedURL:a,options:o}=he(i);if(!xe.has(a.protocol))throw TypeError(`node-fetch cannot load ${e}. URL scheme "${a.protocol.replace(/:$/,``)}" is not supported.`);if(a.protocol===`data:`){let e=te(i.url);n(new G(e,{headers:{"Content-Type":e.typeFull}}));return}let s=(a.protocol===`https:`?ee:v).request,{signal:c}=i,l=null,p=()=>{let e=new _e(`The operation was aborted.`);r(e),i.body&&i.body instanceof u.Readable&&i.body.destroy(e),!(!l||!l.body)&&l.body.emit(`error`,e)};if(c&&c.aborted){p();return}let m=()=>{p(),_()},h=s(a.toString(),o);c&&c.addEventListener(`abort`,m);let _=()=>{h.abort(),c&&c.removeEventListener(`abort`,m)};h.on(`error`,e=>{r(new x(`request to ${i.url} failed, reason: ${e.message}`,`system`,e)),_()}),be(h,e=>{l&&l.body&&l.body.destroy(e)}),process.version<`v14`&&h.on(`socket`,e=>{let t;e.prependListener(`end`,()=>{t=e._eventsCount}),e.prependListener(`close`,n=>{if(l&&t<e._eventsCount&&!n){let e=Error(`Premature close`);e.code=`ERR_STREAM_PREMATURE_CLOSE`,l.body.emit(`error`,e)}})}),h.on(`response`,e=>{h.setTimeout(0);let a=oe(e.rawHeaders);if(H(e.statusCode)){let o=a.get(`Location`),s=null;try{s=o===null?null:new URL(o,i.url)}catch{if(i.redirect!==`manual`){r(new x(`uri requested responds with an invalid redirect URL: ${o}`,`invalid-redirect`)),_();return}}switch(i.redirect){case`error`:r(new x(`uri requested responds with a redirect, redirect mode is set to error: ${i.url}`,`no-redirect`)),_();return;case`manual`:break;case`follow`:{if(s===null)break;if(i.counter>=i.follow){r(new x(`maximum redirect reached at: ${i.url}`,`max-redirect`)),_();return}let o={headers:new z(i.headers),follow:i.follow,counter:i.counter+1,agent:i.agent,compress:i.compress,method:i.method,body:M(i),signal:i.signal,size:i.size,referrer:i.referrer,referrerPolicy:i.referrerPolicy};if(!E(i.url,s)||!ie(i.url,s))for(let e of[`authorization`,`www-authenticate`,`cookie`,`cookie2`])o.headers.delete(e);if(e.statusCode!==303&&i.body&&t.body instanceof u.Readable){r(new x(`Cannot follow redirect with body being a readable stream`,`unsupported-redirect`)),_();return}(e.statusCode===303||(e.statusCode===301||e.statusCode===302)&&i.method===`POST`)&&(o.method=`GET`,o.body=void 0,o.headers.delete(`content-length`));let c=fe(a);c&&(o.referrerPolicy=c),n(ye(new $(s,o))),_();return}default:return r(TypeError(`Redirect option '${i.redirect}' is not a valid value of RequestRedirect`))}}c&&e.once(`end`,()=>{c.removeEventListener(`abort`,m)});let o=f(e,new d,e=>{e&&r(e)});process.version<`v12.10`&&e.on(`aborted`,m);let s={url:i.url,status:e.statusCode,statusText:e.statusMessage,headers:a,size:i.size,counter:i.counter,highWaterMark:i.highWaterMark},p=a.get(`Content-Encoding`);if(!i.compress||i.method===`HEAD`||p===null||e.statusCode===204||e.statusCode===304){l=new G(o,s),n(l);return}let v={flush:g.Z_SYNC_FLUSH,finishFlush:g.Z_SYNC_FLUSH};if(p===`gzip`||p===`x-gzip`){o=f(o,g.createGunzip(v),e=>{e&&r(e)}),l=new G(o,s),n(l);return}if(p===`deflate`||p===`x-deflate`){let t=f(e,new d,e=>{e&&r(e)});t.once(`data`,e=>{o=(e[0]&15)==8?f(o,g.createInflate(),e=>{e&&r(e)}):f(o,g.createInflateRaw(),e=>{e&&r(e)}),l=new G(o,s),n(l)}),t.once(`end`,()=>{l||(l=new G(o,s),n(l))});return}if(p===`br`){o=f(o,g.createBrotliDecompress(),e=>{e&&r(e)}),l=new G(o,s),n(l);return}l=new G(o,s),n(l)}),ae(h,i).catch(r)})}function be(e,t){let n=l.from(`0\r
2
+ import{lt as e}from"./index.mjs";import{a as t,i as n,n as r,o as i,r as a,s as o,t as s}from"./from-Choxbpmr.mjs";import{format as c}from"node:url";import{Buffer as l}from"node:buffer";import u,{PassThrough as d,pipeline as f}from"node:stream";import{deprecate as p,promisify as m,types as h}from"node:util";import g from"node:zlib";import{isIP as _}from"node:net";import v from"node:http";import ee from"node:https";function te(e){if(!/^data:/i.test(e))throw TypeError('`uri` does not appear to be a Data URI (must begin with "data:")');e=e.replace(/\r?\n/g,``);let t=e.indexOf(`,`);if(t===-1||t<=4)throw TypeError(`malformed data: URI`);let n=e.substring(5,t).split(`;`),r=``,i=!1,a=n[0]||`text/plain`,o=a;for(let e=1;e<n.length;e++)n[e]===`base64`?i=!0:n[e]&&(o+=`;${n[e]}`,n[e].indexOf(`charset=`)===0&&(r=n[e].substring(8)));!n[0]&&!r.length&&(o+=`;charset=US-ASCII`,r=`US-ASCII`);let s=i?`base64`:`ascii`,c=unescape(e.substring(t+1)),l=Buffer.from(c,s);return l.type=a,l.typeFull=o,l.charset=r,l}var ne=e((()=>{})),y,b=e((()=>{y=class extends Error{constructor(e,t){super(e),Error.captureStackTrace(this,this.constructor),this.type=t}get name(){return this.constructor.name}get[Symbol.toStringTag](){return this.constructor.name}}})),x,re=e((()=>{b(),x=class extends y{constructor(e,t,n){super(e,t),n&&(this.code=this.errno=n.code,this.erroredSysCall=n.syscall)}}})),S,C,w,T,E,ie,D=e((()=>{S=Symbol.toStringTag,C=e=>typeof e==`object`&&typeof e.append==`function`&&typeof e.delete==`function`&&typeof e.get==`function`&&typeof e.getAll==`function`&&typeof e.has==`function`&&typeof e.set==`function`&&typeof e.sort==`function`&&e[S]===`URLSearchParams`,w=e=>e&&typeof e==`object`&&typeof e.arrayBuffer==`function`&&typeof e.type==`string`&&typeof e.stream==`function`&&typeof e.constructor==`function`&&/^(Blob|File)$/.test(e[S]),T=e=>typeof e==`object`&&(e[S]===`AbortSignal`||e[S]===`EventTarget`),E=(e,t)=>{let n=new URL(t).hostname,r=new URL(e).hostname;return n===r||n.endsWith(`.${r}`)},ie=(e,t)=>new URL(t).protocol===new URL(e).protocol}));async function O(e){if(e[A].disturbed)throw TypeError(`body used already for: ${e.url}`);if(e[A].disturbed=!0,e[A].error)throw e[A].error;let{body:t}=e;if(t===null||!(t instanceof u))return l.alloc(0);let n=[],r=0;try{for await(let i of t){if(e.size>0&&r+i.length>e.size){let n=new x(`content size at ${e.url} over limit: ${e.size}`,`max-size`);throw t.destroy(n),n}r+=i.length,n.push(i)}}catch(t){throw t instanceof y?t:new x(`Invalid response body while trying to fetch ${e.url}: ${t.message}`,`system`,t)}if(t.readableEnded===!0||t._readableState.ended===!0)try{return n.every(e=>typeof e==`string`)?l.from(n.join(``)):l.concat(n,r)}catch(t){throw new x(`Could not create Buffer from response body for ${e.url}: ${t.message}`,`system`,t)}else throw new x(`Premature close of server response while trying to fetch ${e.url}`)}var k,A,j,M,N,P,F,ae,I=e((()=>{o(),n(),re(),b(),D(),k=m(u.pipeline),A=Symbol(`Body internals`),j=class{constructor(e,{size:t=0}={}){let n=null;e===null?e=null:C(e)?e=l.from(e.toString()):w(e)||l.isBuffer(e)||(h.isAnyArrayBuffer(e)?e=l.from(e):ArrayBuffer.isView(e)?e=l.from(e.buffer,e.byteOffset,e.byteLength):e instanceof u||(e instanceof r?(e=a(e),n=e.type.split(`=`)[1]):e=l.from(String(e))));let i=e;l.isBuffer(e)?i=u.Readable.from(e):w(e)&&(i=u.Readable.from(e.stream())),this[A]={body:e,stream:i,boundary:n,disturbed:!1,error:null},this.size=t,e instanceof u&&e.on(`error`,e=>{let t=e instanceof y?e:new x(`Invalid response body while trying to fetch ${this.url}: ${e.message}`,`system`,e);this[A].error=t})}get body(){return this[A].stream}get bodyUsed(){return this[A].disturbed}async arrayBuffer(){let{buffer:e,byteOffset:t,byteLength:n}=await O(this);return e.slice(t,t+n)}async formData(){let e=this.headers.get(`content-type`);if(e.startsWith(`application/x-www-form-urlencoded`)){let e=new r,t=new URLSearchParams(await this.text());for(let[n,r]of t)e.append(n,r);return e}let{toFormData:t}=await import(`./multipart-parser-BdmM0fdd.mjs`);return t(this.body,e)}async blob(){let e=this.headers&&this.headers.get(`content-type`)||this[A].body&&this[A].body.type||``;return new i([await this.arrayBuffer()],{type:e})}async json(){let e=await this.text();return JSON.parse(e)}async text(){let e=await O(this);return new TextDecoder().decode(e)}buffer(){return O(this)}},j.prototype.buffer=p(j.prototype.buffer,`Please use 'response.arrayBuffer()' instead of 'response.buffer()'`,`node-fetch#buffer`),Object.defineProperties(j.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0},data:{get:p(()=>{},`data doesn't exist, use json(), text(), arrayBuffer(), or body instead`,`https://github.com/node-fetch/node-fetch/issues/1000 (response)`)}}),M=(e,t)=>{let n,r,{body:i}=e[A];if(e.bodyUsed)throw Error(`cannot clone body after it is used`);return i instanceof u&&typeof i.getBoundary!=`function`&&(n=new d({highWaterMark:t}),r=new d({highWaterMark:t}),i.pipe(n),i.pipe(r),e[A].stream=n,i=r),i},N=p(e=>e.getBoundary(),`form-data doesn't follow the spec and requires special treatment. Use alternative package`,`https://github.com/node-fetch/node-fetch/issues/1167`),P=(e,t)=>e===null?null:typeof e==`string`?`text/plain;charset=UTF-8`:C(e)?`application/x-www-form-urlencoded;charset=UTF-8`:w(e)?e.type||null:l.isBuffer(e)||h.isAnyArrayBuffer(e)||ArrayBuffer.isView(e)?null:e instanceof r?`multipart/form-data; boundary=${t[A].boundary}`:e&&typeof e.getBoundary==`function`?`multipart/form-data;boundary=${N(e)}`:e instanceof u?null:`text/plain;charset=UTF-8`,F=e=>{let{body:t}=e[A];return t===null?0:w(t)?t.size:l.isBuffer(t)?t.length:t&&typeof t.getLengthSync==`function`&&t.hasKnownLength&&t.hasKnownLength()?t.getLengthSync():null},ae=async(e,{body:t})=>{t===null?e.end():await k(t,e)}}));function oe(e=[]){return new z(e.reduce((e,t,n,r)=>(n%2==0&&e.push(r.slice(n,n+2)),e),[]).filter(([e,t])=>{try{return L(e),R(e,String(t)),!0}catch{return!1}}))}var L,R,z,B=e((()=>{L=typeof v.validateHeaderName==`function`?v.validateHeaderName:e=>{if(!/^[\^`\-\w!#$%&'*+.|~]+$/.test(e)){let t=TypeError(`Header name must be a valid HTTP token [${e}]`);throw Object.defineProperty(t,`code`,{value:`ERR_INVALID_HTTP_TOKEN`}),t}},R=typeof v.validateHeaderValue==`function`?v.validateHeaderValue:(e,t)=>{if(/[^\t\u0020-\u007E\u0080-\u00FF]/.test(t)){let t=TypeError(`Invalid character in header content ["${e}"]`);throw Object.defineProperty(t,`code`,{value:`ERR_INVALID_CHAR`}),t}},z=class e extends URLSearchParams{constructor(t){let n=[];if(t instanceof e){let e=t.raw();for(let[t,r]of Object.entries(e))n.push(...r.map(e=>[t,e]))}else if(t!=null)if(typeof t==`object`&&!h.isBoxedPrimitive(t)){let e=t[Symbol.iterator];if(e==null)n.push(...Object.entries(t));else{if(typeof e!=`function`)throw TypeError(`Header pairs must be iterable`);n=[...t].map(e=>{if(typeof e!=`object`||h.isBoxedPrimitive(e))throw TypeError(`Each header pair must be an iterable object`);return[...e]}).map(e=>{if(e.length!==2)throw TypeError(`Each header pair must be a name/value tuple`);return[...e]})}}else throw TypeError(`Failed to construct 'Headers': The provided value is not of type '(sequence<sequence<ByteString>> or record<ByteString, ByteString>)`);return n=n.length>0?n.map(([e,t])=>(L(e),R(e,String(t)),[String(e).toLowerCase(),String(t)])):void 0,super(n),new Proxy(this,{get(e,t,n){switch(t){case`append`:case`set`:return(n,r)=>(L(n),R(n,String(r)),URLSearchParams.prototype[t].call(e,String(n).toLowerCase(),String(r)));case`delete`:case`has`:case`getAll`:return n=>(L(n),URLSearchParams.prototype[t].call(e,String(n).toLowerCase()));case`keys`:return()=>(e.sort(),new Set(URLSearchParams.prototype.keys.call(e)).keys());default:return Reflect.get(e,t,n)}}})}get[Symbol.toStringTag](){return this.constructor.name}toString(){return Object.prototype.toString.call(this)}get(e){let t=this.getAll(e);if(t.length===0)return null;let n=t.join(`, `);return/^content-encoding$/i.test(e)&&(n=n.toLowerCase()),n}forEach(e,t=void 0){for(let n of this.keys())Reflect.apply(e,t,[this.get(n),n,this])}*values(){for(let e of this.keys())yield this.get(e)}*entries(){for(let e of this.keys())yield[e,this.get(e)]}[Symbol.iterator](){return this.entries()}raw(){return[...this.keys()].reduce((e,t)=>(e[t]=this.getAll(t),e),{})}[Symbol.for(`nodejs.util.inspect.custom`)](){return[...this.keys()].reduce((e,t)=>{let n=this.getAll(t);return t===`host`?e[t]=n[0]:e[t]=n.length>1?n:n[0],e},{})}},Object.defineProperties(z.prototype,[`get`,`entries`,`forEach`,`values`].reduce((e,t)=>(e[t]={enumerable:!0},e),{}))})),V,H,U=e((()=>{V=new Set([301,302,303,307,308]),H=e=>V.has(e)})),W,G,se=e((()=>{B(),I(),U(),W=Symbol(`Response internals`),G=class e extends j{constructor(e=null,t={}){super(e,t);let n=t.status==null?200:t.status,r=new z(t.headers);if(e!==null&&!r.has(`Content-Type`)){let t=P(e,this);t&&r.append(`Content-Type`,t)}this[W]={type:`default`,url:t.url,status:n,statusText:t.statusText||``,headers:r,counter:t.counter,highWaterMark:t.highWaterMark}}get type(){return this[W].type}get url(){return this[W].url||``}get status(){return this[W].status}get ok(){return this[W].status>=200&&this[W].status<300}get redirected(){return this[W].counter>0}get statusText(){return this[W].statusText}get headers(){return this[W].headers}get highWaterMark(){return this[W].highWaterMark}clone(){return new e(M(this,this.highWaterMark),{type:this.type,url:this.url,status:this.status,statusText:this.statusText,headers:this.headers,ok:this.ok,redirected:this.redirected,size:this.size,highWaterMark:this.highWaterMark})}static redirect(t,n=302){if(!H(n))throw RangeError(`Failed to execute "redirect" on "response": Invalid status code`);return new e(null,{headers:{location:new URL(t).toString()},status:n})}static error(){let t=new e(null,{status:0,statusText:``});return t[W].type=`error`,t}static json(t=void 0,n={}){let r=JSON.stringify(t);if(r===void 0)throw TypeError(`data is not JSON serializable`);let i=new z(n&&n.headers);return i.has(`content-type`)||i.set(`content-type`,`application/json`),new e(r,{...n,headers:i})}get[Symbol.toStringTag](){return`Response`}},Object.defineProperties(G.prototype,{type:{enumerable:!0},url:{enumerable:!0},status:{enumerable:!0},ok:{enumerable:!0},redirected:{enumerable:!0},statusText:{enumerable:!0},headers:{enumerable:!0},clone:{enumerable:!0}})})),K,ce=e((()=>{K=e=>{if(e.search)return e.search;let t=e.href.length-1,n=e.hash||(e.href[t]===`#`?`#`:``);return e.href[t-n.length]===`?`?`?`:``}}));function q(e,t=!1){return e==null||(e=new URL(e),/^(about|blob|data):$/.test(e.protocol))?`no-referrer`:(e.username=``,e.password=``,e.hash=``,t&&(e.pathname=``,e.search=``),e)}function le(e){if(!Y.has(e))throw TypeError(`Invalid referrerPolicy: ${e}`);return e}function ue(e){if(/^(http|ws)s:$/.test(e.protocol))return!0;let t=e.host.replace(/(^\[)|(]$)/g,``),n=_(t);return n===4&&/^127\./.test(t)||n===6&&/^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(t)?!0:e.host===`localhost`||e.host.endsWith(`.localhost`)?!1:e.protocol===`file:`}function J(e){return/^about:(blank|srcdoc)$/.test(e)||e.protocol===`data:`||/^(blob|filesystem):$/.test(e.protocol)?!0:ue(e)}function de(e,{referrerURLCallback:t,referrerOriginCallback:n}={}){if(e.referrer===`no-referrer`||e.referrerPolicy===``)return null;let r=e.referrerPolicy;if(e.referrer===`about:client`)return`no-referrer`;let i=e.referrer,a=q(i),o=q(i,!0);a.toString().length>4096&&(a=o),t&&(a=t(a)),n&&(o=n(o));let s=new URL(e.url);switch(r){case`no-referrer`:return`no-referrer`;case`origin`:return o;case`unsafe-url`:return a;case`strict-origin`:return J(a)&&!J(s)?`no-referrer`:o.toString();case`strict-origin-when-cross-origin`:return a.origin===s.origin?a:J(a)&&!J(s)?`no-referrer`:o;case`same-origin`:return a.origin===s.origin?a:`no-referrer`;case`origin-when-cross-origin`:return a.origin===s.origin?a:o;case`no-referrer-when-downgrade`:return J(a)&&!J(s)?`no-referrer`:a;default:throw TypeError(`Invalid referrerPolicy: ${r}`)}}function fe(e){let t=(e.get(`referrer-policy`)||``).split(/[,\s]+/),n=``;for(let e of t)e&&Y.has(e)&&(n=e);return n}var Y,X,pe=e((()=>{Y=new Set([``,`no-referrer`,`no-referrer-when-downgrade`,`same-origin`,`origin`,`strict-origin`,`origin-when-cross-origin`,`strict-origin-when-cross-origin`,`unsafe-url`]),X=`strict-origin-when-cross-origin`})),Z,Q,me,$,he,ge=e((()=>{B(),I(),D(),ce(),pe(),Z=Symbol(`Request internals`),Q=e=>typeof e==`object`&&typeof e[Z]==`object`,me=p(()=>{},`.data is not a valid RequestInit property, use .body instead`,`https://github.com/node-fetch/node-fetch/issues/1000 (request)`),$=class e extends j{constructor(e,t={}){let n;if(Q(e)?n=new URL(e.url):(n=new URL(e),e={}),n.username!==``||n.password!==``)throw TypeError(`${n} is an url with embedded credentials.`);let r=t.method||e.method||`GET`;if(/^(delete|get|head|options|post|put)$/i.test(r)&&(r=r.toUpperCase()),!Q(t)&&`data`in t&&me(),(t.body!=null||Q(e)&&e.body!==null)&&(r===`GET`||r===`HEAD`))throw TypeError(`Request with GET/HEAD method cannot have body`);let i=t.body?t.body:Q(e)&&e.body!==null?M(e):null;super(i,{size:t.size||e.size||0});let a=new z(t.headers||e.headers||{});if(i!==null&&!a.has(`Content-Type`)){let e=P(i,this);e&&a.set(`Content-Type`,e)}let o=Q(e)?e.signal:null;if(`signal`in t&&(o=t.signal),o!=null&&!T(o))throw TypeError(`Expected signal to be an instanceof AbortSignal or EventTarget`);let s=t.referrer==null?e.referrer:t.referrer;if(s===``)s=`no-referrer`;else if(s){let e=new URL(s);s=/^about:(\/\/)?client$/.test(e)?`client`:e}else s=void 0;this[Z]={method:r,redirect:t.redirect||e.redirect||`follow`,headers:a,parsedURL:n,signal:o,referrer:s},this.follow=t.follow===void 0?e.follow===void 0?20:e.follow:t.follow,this.compress=t.compress===void 0?e.compress===void 0?!0:e.compress:t.compress,this.counter=t.counter||e.counter||0,this.agent=t.agent||e.agent,this.highWaterMark=t.highWaterMark||e.highWaterMark||16384,this.insecureHTTPParser=t.insecureHTTPParser||e.insecureHTTPParser||!1,this.referrerPolicy=t.referrerPolicy||e.referrerPolicy||``}get method(){return this[Z].method}get url(){return c(this[Z].parsedURL)}get headers(){return this[Z].headers}get redirect(){return this[Z].redirect}get signal(){return this[Z].signal}get referrer(){if(this[Z].referrer===`no-referrer`)return``;if(this[Z].referrer===`client`)return`about:client`;if(this[Z].referrer)return this[Z].referrer.toString()}get referrerPolicy(){return this[Z].referrerPolicy}set referrerPolicy(e){this[Z].referrerPolicy=le(e)}clone(){return new e(this)}get[Symbol.toStringTag](){return`Request`}},Object.defineProperties($.prototype,{method:{enumerable:!0},url:{enumerable:!0},headers:{enumerable:!0},redirect:{enumerable:!0},clone:{enumerable:!0},signal:{enumerable:!0},referrer:{enumerable:!0},referrerPolicy:{enumerable:!0}}),he=e=>{let{parsedURL:t}=e[Z],n=new z(e[Z].headers);n.has(`Accept`)||n.set(`Accept`,`*/*`);let r=null;if(e.body===null&&/^(post|put)$/i.test(e.method)&&(r=`0`),e.body!==null){let t=F(e);typeof t==`number`&&!Number.isNaN(t)&&(r=String(t))}r&&n.set(`Content-Length`,r),e.referrerPolicy===``&&(e.referrerPolicy=X),e.referrer&&e.referrer!==`no-referrer`?e[Z].referrer=de(e):e[Z].referrer=`no-referrer`,e[Z].referrer instanceof URL&&n.set(`Referer`,e.referrer),n.has(`User-Agent`)||n.set(`User-Agent`,`node-fetch`),e.compress&&!n.has(`Accept-Encoding`)&&n.set(`Accept-Encoding`,`gzip, deflate, br`);let{agent:i}=e;typeof i==`function`&&(i=i(t));let a=K(t);return{parsedURL:t,options:{path:t.pathname+a,method:e.method,headers:n[Symbol.for(`nodejs.util.inspect.custom`)](),insecureHTTPParser:e.insecureHTTPParser,agent:i}}}})),_e,ve=e((()=>{b(),_e=class extends y{constructor(e,t=`aborted`){super(e,t)}}}));async function ye(e,t){return new Promise((n,r)=>{let i=new $(e,t),{parsedURL:a,options:o}=he(i);if(!xe.has(a.protocol))throw TypeError(`node-fetch cannot load ${e}. URL scheme "${a.protocol.replace(/:$/,``)}" is not supported.`);if(a.protocol===`data:`){let e=te(i.url);n(new G(e,{headers:{"Content-Type":e.typeFull}}));return}let s=(a.protocol===`https:`?ee:v).request,{signal:c}=i,l=null,p=()=>{let e=new _e(`The operation was aborted.`);r(e),i.body&&i.body instanceof u.Readable&&i.body.destroy(e),!(!l||!l.body)&&l.body.emit(`error`,e)};if(c&&c.aborted){p();return}let m=()=>{p(),_()},h=s(a.toString(),o);c&&c.addEventListener(`abort`,m);let _=()=>{h.abort(),c&&c.removeEventListener(`abort`,m)};h.on(`error`,e=>{r(new x(`request to ${i.url} failed, reason: ${e.message}`,`system`,e)),_()}),be(h,e=>{l&&l.body&&l.body.destroy(e)}),process.version<`v14`&&h.on(`socket`,e=>{let t;e.prependListener(`end`,()=>{t=e._eventsCount}),e.prependListener(`close`,n=>{if(l&&t<e._eventsCount&&!n){let e=Error(`Premature close`);e.code=`ERR_STREAM_PREMATURE_CLOSE`,l.body.emit(`error`,e)}})}),h.on(`response`,e=>{h.setTimeout(0);let a=oe(e.rawHeaders);if(H(e.statusCode)){let o=a.get(`Location`),s=null;try{s=o===null?null:new URL(o,i.url)}catch{if(i.redirect!==`manual`){r(new x(`uri requested responds with an invalid redirect URL: ${o}`,`invalid-redirect`)),_();return}}switch(i.redirect){case`error`:r(new x(`uri requested responds with a redirect, redirect mode is set to error: ${i.url}`,`no-redirect`)),_();return;case`manual`:break;case`follow`:{if(s===null)break;if(i.counter>=i.follow){r(new x(`maximum redirect reached at: ${i.url}`,`max-redirect`)),_();return}let o={headers:new z(i.headers),follow:i.follow,counter:i.counter+1,agent:i.agent,compress:i.compress,method:i.method,body:M(i),signal:i.signal,size:i.size,referrer:i.referrer,referrerPolicy:i.referrerPolicy};if(!E(i.url,s)||!ie(i.url,s))for(let e of[`authorization`,`www-authenticate`,`cookie`,`cookie2`])o.headers.delete(e);if(e.statusCode!==303&&i.body&&t.body instanceof u.Readable){r(new x(`Cannot follow redirect with body being a readable stream`,`unsupported-redirect`)),_();return}(e.statusCode===303||(e.statusCode===301||e.statusCode===302)&&i.method===`POST`)&&(o.method=`GET`,o.body=void 0,o.headers.delete(`content-length`));let c=fe(a);c&&(o.referrerPolicy=c),n(ye(new $(s,o))),_();return}default:return r(TypeError(`Redirect option '${i.redirect}' is not a valid value of RequestRedirect`))}}c&&e.once(`end`,()=>{c.removeEventListener(`abort`,m)});let o=f(e,new d,e=>{e&&r(e)});process.version<`v12.10`&&e.on(`aborted`,m);let s={url:i.url,status:e.statusCode,statusText:e.statusMessage,headers:a,size:i.size,counter:i.counter,highWaterMark:i.highWaterMark},p=a.get(`Content-Encoding`);if(!i.compress||i.method===`HEAD`||p===null||e.statusCode===204||e.statusCode===304){l=new G(o,s),n(l);return}let v={flush:g.Z_SYNC_FLUSH,finishFlush:g.Z_SYNC_FLUSH};if(p===`gzip`||p===`x-gzip`){o=f(o,g.createGunzip(v),e=>{e&&r(e)}),l=new G(o,s),n(l);return}if(p===`deflate`||p===`x-deflate`){let t=f(e,new d,e=>{e&&r(e)});t.once(`data`,e=>{o=(e[0]&15)==8?f(o,g.createInflate(),e=>{e&&r(e)}):f(o,g.createInflateRaw(),e=>{e&&r(e)}),l=new G(o,s),n(l)}),t.once(`end`,()=>{l||(l=new G(o,s),n(l))});return}if(p===`br`){o=f(o,g.createBrotliDecompress(),e=>{e&&r(e)}),l=new G(o,s),n(l);return}l=new G(o,s),n(l)}),ae(h,i).catch(r)})}function be(e,t){let n=l.from(`0\r
3
3
  \r
4
4
  `),r=!1,i=!1,a;e.on(`response`,e=>{let{headers:t}=e;r=t[`transfer-encoding`]===`chunked`&&!t[`content-length`]}),e.on(`socket`,o=>{let s=()=>{if(r&&!i){let e=Error(`Premature close`);e.code=`ERR_STREAM_PREMATURE_CLOSE`,t(e)}},c=e=>{i=l.compare(e.slice(-5),n)===0,!i&&a&&(i=l.compare(a.slice(-3),n.slice(0,3))===0&&l.compare(e.slice(-2),n.slice(3))===0),a=e};o.prependListener(`close`,s),o.on(`data`,c),e.on(`close`,()=>{o.removeListener(`close`,s),o.removeListener(`data`,c)})})}var xe;e((()=>{ne(),I(),se(),B(),ge(),re(),ve(),U(),n(),D(),pe(),s(),xe=new Set([`data:`,`http:`,`https:`])}))();export{ye as default};
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ var e=class extends Error{};const t=[`$ref`,`$defs`,`definitions`,`allOf`,`oneOf`,`patternProperties`,`dependentSchemas`,`dependencies`,`unevaluatedProperties`,`propertyNames`,`contains`,`prefixItems`,`not`,`if`,`then`,`else`];function n(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function r(e){if(!n(e))return!1;let t=typeof e.type==`string`?[e.type]:Array.isArray(e.type)?e.type:[];return t.includes(`object`)||t.includes(`array`)||e.properties!==void 0||e.items!==void 0}function i(e){return n(e)?e.type===`null`||Array.isArray(e.type)&&e.type.includes(`null`)||e.const===null||Array.isArray(e.enum)&&e.enum.includes(null)?!0:Array.isArray(e.anyOf)&&e.anyOf.some(e=>i(e)):!1}function a(o){if(!n(o))throw new e(`boolean schemas are unsupported`);for(let n of t)if(o[n]!==void 0)throw new e(`${n} schemas are unsupported`);if(o.anyOf!==void 0){if(!Array.isArray(o.anyOf)||o.anyOf.length===0)throw new e(`anyOf must contain at least one schema`);for(let t of o.anyOf){if(r(t))throw new e(`object and array unions are unsupported`);a(t)}}if(o.items!==void 0){if(Array.isArray(o.items))throw new e(`tuple schemas are unsupported`);a(o.items)}let s=o.type===`object`;if(o.properties!==void 0&&!s)throw new e(`properties require type object`);if(!s)return;if(o.additionalProperties!==void 0&&o.additionalProperties!==!1)throw new e(`schema-valued or true additionalProperties is unsupported`);if(o.properties!==void 0&&!n(o.properties))throw new e(`object properties must be a schema map`);if(o.required!==void 0&&(!Array.isArray(o.required)||o.required.some(e=>typeof e!=`string`)))throw new e(`object required must be a string array`);let c=o.properties??{},l=Object.keys(c),u=new Set(Array.isArray(o.required)?o.required:[]);if([...u].some(e=>!l.includes(e)))throw new e(`required contains an unknown property`);for(let[e,t]of Object.entries(c))a(t),!u.has(e)&&!i(t)&&(c[e]={anyOf:[t,{type:`null`}]});o.required=l,o.additionalProperties=!1}function o(t){let r=structuredClone(t);if(!n(r)||(a(r),r.type!==`object`))throw new e(`root schema must have type object`);return r}function s(e,t){return t===!0?o(e.parameters):e.parameters}function c(e,t,n){let r=t[n];if(typeof r!=`string`)throw Error(`Grammar tool call "${e}" requires argument "${n}" to be a string.`);return r}function l(e,t,n,r){if(e.closed){if(r&&n===e.input)return;throw Error(`grammar tool input for property "${t}" changed after it was closed`)}if(!n.startsWith(e.input))throw Error(`grammar tool input for property "${t}" changed non-monotonically`);let i=n.slice(e.input.length);if(!r&&i.length===0)return;let a=``;return e.started||=(a+=`{${JSON.stringify(t)}:"`,!0),a+=JSON.stringify(i).slice(1,-1),e.input=n,r&&(a+=`"}`,e.closed=!0),a}function u(e){let t=e.parameters;if(t.type!==`object`)throw Error(`grammar constrained sampling requires an object parameter schema`);if(!Array.isArray(t.required)||t.required.length!==1||typeof t.required[0]!=`string`)throw Error(`grammar constrained sampling requires exactly one required string property`);let n=t.required[0];if(!t.properties?.[n])throw Error(`grammar constrained sampling requires a properties entry for ${n}`);if(t.properties[n]?.type!==`string`)throw Error(`grammar constrained sampling property ${n} must have type string`);return n}function d(t,n){let r=t.constrainedSampling;if(!(!r||r.type!==`json_schema`)){if(n)try{return o(t.parameters),!0}catch(n){if(!(n instanceof e))throw n;if(r.strict!==`require`)return;throw Error(`Tool "${t.name}" requires JSON-schema constrained sampling, but ${n.message}.`)}if(r.strict===`require`)throw Error(`Tool "${t.name}" requires JSON-schema constrained sampling, but strict tools are unsupported.`)}}function f(e,t){let n=e.constrainedSampling;if(!n||n.type!==`grammar`||!t)return;let r=n.variants.openai_lark,i=n.variants.openai_regex,a=typeof r==`string`&&r.trim().length>0,o=typeof i==`string`&&i.trim().length>0;if(!a&&!o)throw Error(`Tool "${e.name}" cannot use grammar constrained sampling: no supported grammar variant was provided.`);try{return{format:a?`lark`:`regex`,definition:a?r:i,inputProperty:u(e)}}catch(t){let n=t instanceof Error?t.message:String(t);throw Error(`Tool "${e.name}" cannot use grammar constrained sampling: ${n}.`)}}function p(e,t){let n=new Map;for(let r of e??[]){let e=f(r,t);e&&n.set(r.name,e.inputProperty)}return n}function m(e){return e.totalTokens||e.input+e.output+e.cacheRead+e.cacheWrite}function h(e){try{return JSON.stringify(e)??`undefined`}catch{return`[unserializable]`}}function g(e){if(typeof e==`string`)return e.length;let t=0;for(let n of e)t+=n.type===`text`?n.text.length:4800;return t}function _(e){return Math.ceil(e.length/4)}function v(e){return Math.ceil(g(e)/4)}function y(e){let t=0;if(e.role===`user`||e.role===`toolResult`)return v(e.content);for(let n of e.content)n.type===`text`?t+=n.text.length:n.type===`thinking`?t+=n.thinking.length:t+=n.name.length+h(n.arguments).length;return Math.ceil(t/4)}function b(e){let t=-1/0,n;for(let r=0;r<e.length;r++){let i=e[r];if(i.role===`assistant`){let e=i;e.timestamp>=t&&e.stopReason!==`aborted`&&e.stopReason!==`error`&&m(e.usage)>0&&(n={usage:e.usage,index:r})}t=Math.max(t,i.timestamp)}return n}function x(e){let t=b(e);if(t){let n=m(t.usage),r=0;for(let n=t.index+1;n<e.length;n++)r+=y(e[n]);return{tokens:n+r,usageTokens:n,trailingTokens:r,lastUsageIndex:t.index}}let n=0;for(let t of e)n+=y(t);return{tokens:n,usageTokens:0,trailingTokens:n,lastUsageIndex:null}}function S(e){return!e||e.length===0?0:_(h(e))}function C(e){return Array.isArray(e)}function w(e){if(C(e))return x(e);let t=x(e.messages);if(t.lastUsageIndex!==null){let n=new Set(e.messages.slice(t.lastUsageIndex+1).filter(e=>e.role===`toolResult`).flatMap(e=>e.addedToolNames??[])),r=S(e.tools?.filter(e=>n.has(e.name)));return{tokens:t.tokens+r,usageTokens:t.usageTokens,trailingTokens:t.trailingTokens+r,lastUsageIndex:t.lastUsageIndex}}let n=(e.systemPrompt?_(e.systemPrompt):0)+S(e.tools);return{tokens:t.tokens+n,usageTokens:t.usageTokens,trailingTokens:t.trailingTokens+n,lastUsageIndex:t.lastUsageIndex}}function T(e,t,n){if(e.contextWindow<=0)return Math.max(1,n);let r=e.contextWindow-w(t).tokens-4096;return Math.min(n,Math.max(1,r))}function E(e,t,n,r){let i=e.samplingParams||n?.samplingParams?{...e.samplingParams,...n?.samplingParams}:void 0;return{temperature:n?.temperature,samplingParams:i,maxTokens:T(e,t,n?.maxTokens??e.maxTokens),signal:n?.signal,telemetryContext:n?.telemetryContext,apiKey:r||n?.apiKey,fetch:n?.fetch,transport:n?.transport,cacheRetention:n?.cacheRetention,sessionId:n?.sessionId,headers:n?.headers,onPayload:n?.onPayload,onResponse:n?.onResponse,timeoutMs:n?.timeoutMs,websocketConnectTimeoutMs:n?.websocketConnectTimeoutMs,maxRetries:n?.maxRetries,maxRetryDelayMs:n?.maxRetryDelayMs,metadata:n?.metadata,env:n?.env}}const D=1024;function O(e){return e===`xhigh`||e===`max`?`high`:e}function k(e,t,n,r){let i={minimal:1024,low:2048,medium:8192,high:16384,...r}[O(n)],a=e===void 0?t:Math.min(e+i,t);return a<=i&&(i=Math.max(0,a-D)),{maxTokens:a,thinkingBudget:i}}function A(e,t){let n=[],r=!1;for(let i of e){if(i.type===`image`){r||n.push({type:`text`,text:t}),r=!0;continue}n.push(i),r=i.text===t}return n}function j(e,t){return t.input.includes(`image`)?e:e.map(e=>e.role===`user`&&Array.isArray(e.content)?{...e,content:A(e.content,`(image omitted: model does not support images)`)}:e.role===`toolResult`?{...e,content:A(e.content,`(tool image omitted: model does not support images)`)}:e)}function M(e,t,n){let r=new Map,i=j(e.map(e=>e.content==null?{...e,content:[]}:e),t).map(e=>{if(e.role===`user`)return e;if(e.role===`toolResult`){let t=r.get(e.toolCallId);return t&&t!==e.toolCallId?{...e,toolCallId:t}:e}if(e.role===`assistant`){let i=e,a=i.provider===t.provider&&i.api===t.api&&i.model===t.id,o=i.content.flatMap(e=>{if(e.type===`thinking`)return e.redacted?a?e:[]:a&&e.thinkingSignature?e:!e.thinking||e.thinking.trim()===``?[]:a?e:{type:`text`,text:e.thinking};if(e.type===`text`)return a?e:{type:`text`,text:e.text};if(e.type===`toolCall`){let o=e,s=o;if(!a&&o.thoughtSignature&&(s={...o},delete s.thoughtSignature),!a&&n){let e=n(o.id,t,i);e!==o.id&&(r.set(o.id,e),s={...s,id:e})}return s}return e});return{...i,content:o}}return e}),a=[],o=[],s=new Set,c=()=>{if(o.length>0){for(let e of o)s.has(e.id)||a.push({role:`toolResult`,toolCallId:e.id,toolName:e.name,content:[{type:`text`,text:`No result provided`}],isError:!0,timestamp:Date.now()});o=[],s=new Set}};for(let e=0;e<i.length;e++){let t=i[e];if(t.role===`assistant`){c();let e=t;if(e.stopReason===`error`||e.stopReason===`aborted`)continue;let n=e.content.filter(e=>e.type===`toolCall`);n.length>0&&(o=n,s=new Set),a.push(t)}else t.role===`toolResult`?(s.add(t.toolCallId),a.push(t)):(t.role===`user`&&c(),a.push(t))}return c(),a}export{T as a,p as c,f as d,d as f,E as i,c as l,D as n,O as o,k as r,l as s,M as t,s as u};