mono-jsx 0.1.3 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,32 +2,34 @@
2
2
 
3
3
  ![`<html>` as a `Response`](./.github/og-image.png)
4
4
 
5
- mono-jsx is a JSX runtime that renders `<html>` element to a `Response` object in JavaScript runtimes like Node.js, Deno, Bun, Cloudflare Workers, etc.
5
+ mono-jsx is a JSX runtime that renders `<html>` element to `Response` object in JavaScript runtimes like Node.js, Deno, Bun, Cloudflare Workers, etc.
6
6
 
7
7
  - 🚀 No build step needed
8
8
  - 🦋 Lightweight (8KB gzipped), zero dependencies
9
9
  - 🔫 Minimal state runtime
10
- - 🚨 Complete Web API Typescript definitions
10
+ - 🚨 Complete Web API TypeScript definitions
11
11
  - ⏳ Streaming rendering
12
12
  - 🌎 Universal, works in Node.js, Deno, Bun, Cloudflare Workers, etc.
13
13
 
14
14
  ## Installation
15
15
 
16
- mono-jsx supports all modern JavaScript runtimes including Node.js, Deno, Bun, Cloudflare Workers, etc.
17
- You can install it via `npm i`, `deno add`, or `bun add`.
16
+ mono-jsx supports all modern JavaScript runtimes including Node.js, Deno, Bun, and Cloudflare Workers.
17
+ You can install it via `npm`, `deno`, or `bun`:
18
18
 
19
19
  ```bash
20
20
  # Node.js, Cloudflare Workers, or other node-compatible runtimes
21
21
  npm i mono-jsx
22
+
22
23
  # Deno
23
24
  deno add npm:mono-jsx
25
+
24
26
  # Bun
25
27
  bun add mono-jsx
26
28
  ```
27
29
 
28
30
  ## Setup JSX Runtime
29
31
 
30
- To use mono-jsx as JSX runtime, add the following configuration to your `tsconfig.json`(`deno.json` for Deno):
32
+ To use mono-jsx as your JSX runtime, add the following configuration to your `tsconfig.json` (or `deno.json` for Deno):
31
33
 
32
34
  ```jsonc
33
35
  {
@@ -38,30 +40,31 @@ To use mono-jsx as JSX runtime, add the following configuration to your `tsconfi
38
40
  }
39
41
  ```
40
42
 
41
- Alternatively, you can also use pragma directive in your JSX file.
43
+ Alternatively, you can use a pragma directive in your JSX file:
42
44
 
43
45
  ```js
44
46
  /** @jsxImportSource mono-jsx */
45
47
  ```
46
48
 
47
- You can also run `mono-jsx setup` to automatically add the configuration to your `tsconfig.json` or `deno.json`.
49
+ You can also run `mono-jsx setup` to automatically add the configuration to your project:
48
50
 
49
51
  ```bash
50
52
  # Node.js, Cloudflare Workers, or other node-compatible runtimes
51
53
  npx mono-jsx setup
54
+
52
55
  # Deno
53
- deno run npm:mono-jsx setup
56
+ deno run -A npm:mono-jsx setup
57
+
54
58
  # Bun
55
59
  bunx mono-jsx setup
56
60
  ```
57
61
 
58
62
  ## Usage
59
63
 
60
- mono-jsx allows you to return an `<html>` JSX element as a `Response` object in the `fetch` handler.
64
+ mono-jsx allows you to return an `<html>` JSX element as a `Response` object in the `fetch` handler:
61
65
 
62
66
  ```tsx
63
67
  // app.tsx
64
-
65
68
  export default {
66
69
  fetch: (req) => (
67
70
  <html>
@@ -71,24 +74,23 @@ export default {
71
74
  };
72
75
  ```
73
76
 
74
- For Deno/Bun users, you can run the `app.tsx` directly.
77
+ For Deno/Bun users, you can run the `app.tsx` directly:
75
78
 
76
79
  ```bash
77
80
  deno serve app.tsx
78
81
  bun run app.tsx
79
82
  ```
80
83
 
81
- If you are building a web app with [Cloudflare Workers](https://developers.cloudflare.com/workers/wrangler/commands/#dev), use `wrangler dev` command to start the app in local development mode.
84
+ If you're building a web app with [Cloudflare Workers](https://developers.cloudflare.com/workers/wrangler/commands/#dev), use `wrangler dev` to start local development:
82
85
 
83
86
  ```bash
84
87
  npx wrangler dev app.tsx
85
88
  ```
86
89
 
87
- **Node.js does not support JSX syntax and declarative fetch server**, we recommend using mono-jsx with [srvx](https://srvx.h3.dev/).
90
+ **Node.js doesn't support JSX syntax or declarative fetch servers**, so we recommend using mono-jsx with [srvx](https://srvx.h3.dev/):
88
91
 
89
92
  ```tsx
90
93
  // app.tsx
91
-
92
94
  import { serve } from "srvx";
93
95
 
94
96
  serve({
@@ -101,7 +103,7 @@ serve({
101
103
  });
102
104
  ```
103
105
 
104
- and you will need [tsx](https://www.npmjs.com/package/tsx) to start the app without a build step.
106
+ You'll need [tsx](https://www.npmjs.com/package/tsx) to start the app without a build step:
105
107
 
106
108
  ```bash
107
109
  npx tsx app.tsx
@@ -109,27 +111,33 @@ npx tsx app.tsx
109
111
 
110
112
  ## Using JSX
111
113
 
112
- mono-jsx uses [**JSX**](https://react.dev/learn/describing-the-ui) to describe the user interface, similar to React but with some differences.
114
+ mono-jsx uses [**JSX**](https://react.dev/learn/describing-the-ui) to describe the user interface, similar to React but with key differences.
113
115
 
114
116
  ### Using Standard HTML Property Names
115
117
 
116
- mono-jsx adopts standard HTML property names, avoiding React's custom property naming conventions.
118
+ mono-jsx adopts standard HTML property names, avoiding React's custom naming conventions:
117
119
 
118
- - `className` becomes `class`
119
- - `htmlFor` becomes `for`
120
- - `onChange` becomes `onInput`
120
+ - `className` `class`
121
+ - `htmlFor` `for`
122
+ - `onChange` `onInput`
121
123
 
122
- ### Composition `class`
124
+ ### Composition with `class`
123
125
 
124
- mono-jsx allows you to compose the `class` property using an array of strings, objects, or expressions.
126
+ mono-jsx allows you to compose the `class` property using arrays of strings, objects, or expressions:
125
127
 
126
128
  ```jsx
127
- <div class={["container box", isActive && "active", { hover: isHover }]} />;
129
+ <div
130
+ class={[
131
+ "container box",
132
+ isActive && "active",
133
+ { hover: isHover },
134
+ ]}
135
+ />;
128
136
  ```
129
137
 
130
- ### Using Pseudo Classes and Media Queries in the `style` Property
138
+ ### Using Pseudo Classes and Media Queries in `style`
131
139
 
132
- mono-jsx allows you to use [pseudo classes](https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-classes), [pseudo elements](https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-elements), [media queries](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_media_queries/Using_media_queries), and [css nesting](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_nesting/Using_CSS_nesting) in the `style` property.
140
+ mono-jsx supports [pseudo classes](https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-classes), [pseudo elements](https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-elements), [media queries](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_media_queries/Using_media_queries), and [CSS nesting](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_nesting/Using_CSS_nesting) in the `style` property:
133
141
 
134
142
  ```jsx
135
143
  <a
@@ -148,14 +156,16 @@ mono-jsx allows you to use [pseudo classes](https://developer.mozilla.org/en-US/
148
156
 
149
157
  ### `<slot>` Element
150
158
 
151
- mono-jsx uses [`<slot>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/slot) element to render the slotted content (Equivalent to React's `children` property). Plus, you also can add the `name` attribute to define a named slot.
159
+ mono-jsx uses [`<slot>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/slot) elements to render slotted content (equivalent to React's `children` property). You can also add the `name` attribute to define named slots:
152
160
 
153
161
  ```jsx
154
162
  function Container() {
155
163
  return (
156
164
  <div class="container">
157
- <slot /> {/* <h1>Hello world!</h1> */}
158
- <slot name="desc" /> {/* <p>This is a description.</p> */}
165
+ {/* Default slot */}
166
+ <slot />
167
+ {/* Named slot */}
168
+ <slot name="desc" />
159
169
  </div>
160
170
  );
161
171
  }
@@ -163,7 +173,9 @@ function Container() {
163
173
  function App() {
164
174
  return (
165
175
  <Container>
176
+ {/* This goes to the named slot */}
166
177
  <p slot="desc">This is a description.</p>
178
+ {/* This goes to the default slot */}
167
179
  <h1>Hello world!</h1>
168
180
  </Container>
169
181
  );
@@ -172,7 +184,7 @@ function App() {
172
184
 
173
185
  ### `html` Tag Function
174
186
 
175
- mono-jsx doesn't support the `dangerouslySetInnerHTML` property, instead, it provides a `html` tag function to render raw HTML in JSX.
187
+ mono-jsx provides an `html` tag function to render raw HTML in JSX instead of React's `dangerouslySetInnerHTML`:
176
188
 
177
189
  ```jsx
178
190
  function App() {
@@ -180,8 +192,7 @@ function App() {
180
192
  }
181
193
  ```
182
194
 
183
- The `html` tag function is a global function injected by mono-jsx, you can use it in any JSX expression without importing it.
184
- You also can use the `css` and `js`, that are just aliases of the `html` tag function, to render CSS and JavaScript code.
195
+ The `html` tag function is globally available without importing. You can also use `css` and `js` tag functions for CSS and JavaScript:
185
196
 
186
197
  ```jsx
187
198
  function App() {
@@ -195,31 +206,38 @@ function App() {
195
206
  ```
196
207
 
197
208
  > [!WARNING]
198
- > the `html` tag function is **unsafe** that can cause [**XSS**](https://en.wikipedia.org/wiki/Cross-site_scripting) vulnerabilities.
209
+ > The `html` tag function is **unsafe** and can cause [**XSS**](https://en.wikipedia.org/wiki/Cross-site_scripting) vulnerabilities.
199
210
 
200
211
  ### Event Handlers
201
212
 
202
- mono-jsx allows you to write event handlers directly in the JSX code, like React.
213
+ mono-jsx lets you write event handlers directly in JSX, similar to React:
203
214
 
204
215
  ```jsx
205
216
  function Button() {
206
- return <button onClick={(evt) => alert("BOOM!")}>Click Me</button>;
217
+ return (
218
+ <button onClick={(evt) => alert("BOOM!")}>
219
+ Click Me
220
+ </button>
221
+ );
207
222
  }
208
223
  ```
209
224
 
210
225
  > [!NOTE]
211
- > the event handler would never be called in server-side. It will be serialized to a string and sent to the client-side. **This means you should NOT use any server-side variables or functions in the event handler.**
226
+ > Event handlers are never called on the server-side. They're serialized to strings and sent to the client. **This means you should NOT use server-side variables or functions in event handlers.**
212
227
 
213
228
  ```tsx
229
+ import { doSomething } from "some-library";
230
+
214
231
  function Button(this: FC, props: { role: string }) {
215
232
  let message = "BOOM!";
216
- console.log(message); // only print message in server-side
233
+ console.log(message); // only executes on server-side
217
234
  return (
218
235
  <button
219
236
  role={props.role}
220
237
  onClick={(evt) => {
221
238
  alert(message); // ❌ `message` is a server-side variable
222
239
  console.log(props.role); // ❌ `props` is a server-side variable
240
+ doSomething(); // ❌ `doSomething` is imported on the server-side
223
241
  Deno.exit(0); // ❌ `Deno` is unavailable in the browser
224
242
  document.title = "BOOM!"; // ✅ `document` is a browser API
225
243
  console.log(evt.target); // ✅ `evt` is the event object
@@ -232,7 +250,7 @@ function Button(this: FC, props: { role: string }) {
232
250
  }
233
251
  ```
234
252
 
235
- Plus, mono-jsx supports the `mount` event that will be triggered when the element is mounted in the client-side.
253
+ Additionally, mono-jsx supports the `mount` event for when elements are mounted in the client-side DOM:
236
254
 
237
255
  ```jsx
238
256
  function App() {
@@ -244,14 +262,14 @@ function App() {
244
262
  }
245
263
  ```
246
264
 
247
- mono-jsx also accepts a function as the `action` property for `form` elements, which will be called when the form is submitted.
265
+ mono-jsx also accepts functions for the `action` property on `form` elements, which will be called on form submission:
248
266
 
249
267
  ```tsx
250
268
  function App() {
251
269
  return (
252
270
  <form
253
- action={(data: FormData, evt) => {
254
- evt.defaultPrevented // true
271
+ action={(data: FormData, event: SubmitEvent) => {
272
+ event.preventDefault(); // true
255
273
  console.log(data.get("name"));
256
274
  }}
257
275
  >
@@ -262,23 +280,28 @@ function App() {
262
280
  }
263
281
  ```
264
282
 
265
- ## Using State
283
+ ## Reactive
284
+
285
+ mono-jsx provides a minimal state runtime for updating the view based on client-side state changes:
286
+
287
+ ### Using State
266
288
 
267
- mono-jsx provides a minimal state runtime that allows you to update view based on state changes in client-side.
289
+ You can use `this` to define state in your components. The view will automatically update when the state changes:
268
290
 
269
291
  ```tsx
270
292
  function Counter(
271
293
  this: FC<{ count: number }>,
272
294
  props: { initialCount?: number },
273
295
  ) {
296
+ // Initialize state
274
297
  this.count = props.initialCount ?? 0;
298
+
275
299
  return (
276
300
  <div>
277
- {/* use the state */}
301
+ {/* render state */}
278
302
  <span>{this.count}</span>
279
- {/* use computed state */}
280
- <span>doubled: {this.computed(() => 2 * this.count)}</span>
281
- {/* update the state in event handlers */}
303
+
304
+ {/* Update state to trigger re-render */}
282
305
  <button onClick={() => this.count--}>-</button>
283
306
  <button onClick={() => this.count++}>+</button>
284
307
  </div>
@@ -286,11 +309,36 @@ function Counter(
286
309
  }
287
310
  ```
288
311
 
289
- > [!WARNING]
290
- > The state cannot be used in an arrow function component, you should use a `function` declaration instead.
312
+ ### Using Computed Properties
291
313
 
292
- ```jsx
293
- // ❌ `this.count++` won't update the view, please use a function declaration instead
314
+ You can use `this.computed` to create computed properties based on state. The computed property will automatically update when the state changes:
315
+
316
+ ```tsx
317
+ function App(this: FC<{ input: string }>) {
318
+ this.input = 'Hello, world';
319
+ return (
320
+ <div>
321
+ <h1>{this.computed(() = this.input + "!")}</h1>
322
+
323
+ <form
324
+ action={(data: FormData ) => {
325
+ this.input = data.get("input") as string;
326
+ }}
327
+ >
328
+ <input type="text" name="input" value={this.input} />
329
+ <button type="submit">Submit</button>
330
+ </form>
331
+ </div>
332
+ );
333
+ }
334
+ ```
335
+
336
+ ### Limitation of States
337
+
338
+ 1\. States cannot be used in arrow function components.
339
+
340
+ ```tsx
341
+ // ❌ Won't work - state updates won't refresh the view
294
342
  const App = () => {
295
343
  this.count = 0;
296
344
  return (
@@ -300,40 +348,87 @@ const App = () => {
300
348
  </div>
301
349
  );
302
350
  };
351
+
352
+ // ✅ Works correctly
353
+ function App(this: FC) {
354
+ this.count = 0;
355
+ return (
356
+ <div>
357
+ <span>{this.count}</span>
358
+ <button onClick={() => this.count++}>+</button>
359
+ </div>
360
+ );
361
+ }
362
+ ```
363
+
364
+ 2\. States cannot be computed outside of the `this.computed` method.
365
+
366
+ ```tsx
367
+ // ❌ Won't work - state updates won't refresh the view
368
+ function App(this: FC<{ message: string }>) {
369
+ this.message = "Hello, world";
370
+ return (
371
+ <div>
372
+ <h1 title={this.message + "!"}>{this.message + "!"}</h1>
373
+ <button onClick={() => this.message = "Clicked"}>
374
+ Click Me
375
+ </button>
376
+ </div>
377
+ );
378
+ }
379
+
380
+ // ✅ Works correctly
381
+ function App(this: FC) {
382
+ this.message = "Hello, world";
383
+ return (
384
+ <div>
385
+ <h1 title={this.computed(() => this.message + "!")}>{this.computed(() => this.message + "!")}</h1>
386
+ <button onClick={() => this.message = "Clicked"}>
387
+ Click Me
388
+ </button>
389
+ </div>
390
+ );
391
+ }
303
392
  ```
304
393
 
305
394
  ## Built-in Elements
306
395
 
307
- mono-jsx provides some built-in elements to help you build your app.
396
+ mono-jsx provides built-in elements to help you build reactive UIs.
308
397
 
309
398
  ### `<toggle>` element
310
399
 
311
- `<toggle>` element allows you to toggle the visibility of the slotted content.
400
+ The `<toggle>` element conditionally renders content based on a boolean value:
312
401
 
313
402
  ```tsx
314
403
  function App(this: FC<{ show: boolean }>) {
315
404
  this.show = false;
405
+
406
+ function toggle() {
407
+ this.show = !this.show;
408
+ }
409
+
316
410
  return (
317
411
  <div>
318
412
  <toggle value={this.show}>
319
413
  <h1>Welcome to mono-jsx!</h1>
320
414
  </toggle>
321
- <button onClick={toggle}>{this.computed(() => this.show ? "Hide" : "Show")}</button>
415
+
416
+ <button onClick={toggle}>
417
+ {this.computed(() => this.show ? "Hide" : "Show")}
418
+ </button>
322
419
  </div>
323
420
  );
324
- function toggle() {
325
- this.show = !this.show;
326
- }
327
421
  }
328
422
  ```
329
423
 
330
424
  ### `<switch>` element
331
425
 
332
- `<switch>` element allows you to switch the slotted content based on the `value` property. You need to define the `slot` attribute in the slotted content to match the `value`, otherwise, the default slots will be rendered.
426
+ The `<switch>` element renders different content based on a value. Elements with matching `slot` attributes are displayed when their value matches, otherwise default content is shown:
333
427
 
334
428
  ```tsx
335
429
  function App(this: FC<{ lang: "en" | "zh" | "emoji" }>) {
336
430
  this.lang = "en";
431
+
337
432
  return (
338
433
  <div>
339
434
  <switch value={this.lang}>
@@ -341,6 +436,7 @@ function App(this: FC<{ lang: "en" | "zh" | "emoji" }>) {
341
436
  <h1 slot="zh">你好,世界!</h1>
342
437
  <h1>✋🌎❗️</h1>
343
438
  </switch>
439
+
344
440
  <button onClick={() => this.lang = "en"}>English</button>
345
441
  <button onClick={() => this.lang = "zh"}>中文</button>
346
442
  <button onClick={() => this.lang = "emoji"}>Emoji</button>
@@ -351,10 +447,10 @@ function App(this: FC<{ lang: "en" | "zh" | "emoji" }>) {
351
447
 
352
448
  ## Streaming Rendering
353
449
 
354
- mono-jsx renders your `<html>` as a readable stream, that allows async function components are rendered asynchronously. You can set a `placeholder` attribute to show a loading state while the async component is loading.
450
+ mono-jsx renders your `<html>` as a readable stream, allowing async components to render asynchronously. You can use `placeholder` to display a loading state while waiting for async components to render:
355
451
 
356
452
  ```jsx
357
- async function Sleep(ms) {
453
+ async function Sleep({ ms }) {
358
454
  await new Promise((resolve) => setTimeout(resolve, ms));
359
455
  return <slot />;
360
456
  }
@@ -363,6 +459,7 @@ export default {
363
459
  fetch: (req) => (
364
460
  <html>
365
461
  <h1>Welcome to mono-jsx!</h1>
462
+
366
463
  <Sleep ms={1000} placeholder={<p>Sleeping...</p>}>
367
464
  <p>After 1 second</p>
368
465
  </Sleep>
@@ -371,10 +468,10 @@ export default {
371
468
  };
372
469
  ```
373
470
 
374
- You can also set `rendering` attribute to "eager" to render the async component eagerly, which means the async component will be rendered as a sync function component and the `placeholder` will be ignored.
471
+ You can set the `rendering` attribute to `"eager"` to force synchronous rendering (the `placeholder` will be ignored):
375
472
 
376
473
  ```jsx
377
- async function Sleep(ms) {
474
+ async function Sleep({ ms }) {
378
475
  await new Promise((resolve) => setTimeout(resolve, ms));
379
476
  return <slot />;
380
477
  }
@@ -383,6 +480,7 @@ export default {
383
480
  fetch: (req) => (
384
481
  <html>
385
482
  <h1>Welcome to mono-jsx!</h1>
483
+
386
484
  <Sleep ms={1000} rendering="eager">
387
485
  <p>After 1 second</p>
388
486
  </Sleep>
@@ -391,9 +489,36 @@ export default {
391
489
  };
392
490
  ```
393
491
 
492
+ ## Using Context
493
+
494
+ You can use the `context` property in `this` to access context values in your components. The context is defined on the root `<html>` element:
495
+
496
+ ```tsx
497
+ function Dash(this: FC<{}, { auth: { uuid: string; name: string } }>) {
498
+ const { auth } = this.context;
499
+ return (
500
+ <div>
501
+ <h1>Welcome back, {auth.name}!</h1>;
502
+ <p>Your UUID is {auth.uuid}</p>
503
+ </div>
504
+ );
505
+ }
506
+
507
+ export default {
508
+ fetch: (req) => {
509
+ const auth = doAuth(req);
510
+ return (
511
+ <html context={{ auth }} request={req}>
512
+ <Dash />
513
+ </html>
514
+ );
515
+ },
516
+ };
517
+ ```
518
+
394
519
  ## Accessing Request Info
395
520
 
396
- You can access the request info in a function component by using the `request` property in the `this` context. And you must pass the `request` object to the root `<html>` element to make it work.
521
+ You can access request information in components via the `request` property in `this` which is set on the root `<html>` element:
397
522
 
398
523
  ```tsx
399
524
  function RequestInfo(this: FC) {
@@ -419,7 +544,7 @@ export default {
419
544
 
420
545
  ## Customizing Response
421
546
 
422
- You can add `status` or `headers` attribute to the `<html>` element to customize the response.
547
+ Add `status` or `headers` attributes to the root `<html>` element to customize the response:
423
548
 
424
549
  ```jsx
425
550
  export default {
package/bin/mono-jsx CHANGED
@@ -1,34 +1,53 @@
1
1
  #!/usr/bin/env node
2
2
 
3
+ import { existsSync } from "node:fs";
3
4
  import { readFile, writeFile } from "node:fs/promises";
4
5
  import process from "node:process";
5
6
 
6
7
  switch (process.argv[2]) {
7
8
  case "setup":
8
- setup().then(() => {
9
- console.log("✅ JSX runtime setup complete.");
10
- });
9
+ setup()
11
10
  break;
12
11
  default:
13
12
  process.exit(0);
14
13
  }
15
14
 
16
15
  async function setup() {
17
- let tsConfigPath = globalThis.Deno ? "deno.json" : "tsconfig.json";
16
+ if (globalThis.Deno && existsSync("deno.jsonc")) {
17
+ console.log("Please add the following options to your deno.jsonc file:");
18
+ console.log(
19
+ [
20
+ `{`,
21
+ ` "compilerOptions": {`,
22
+ ` %c"jsx": "react-jsx",`,
23
+ ` "jsxImportSource": "mono-jsx",%c`,
24
+ ` }`,
25
+ `}`,
26
+ ].join("\n"),
27
+ "color:green",
28
+ "",
29
+ );
30
+ return;
31
+ }
32
+ let tsConfigFilename = globalThis.Deno ? "deno.json" : "tsconfig.json";
18
33
  let tsConfig = Object.create(null);
19
34
  try {
20
- const json = await readFile(tsConfigPath, "utf8");
21
- tsConfig = JSON.parse(json);
35
+ const data = await readFile(tsConfigFilename, "utf8");
36
+ tsConfig = JSON.parse(data);
22
37
  } catch {
23
38
  // ignore
24
39
  }
25
- tsConfig.compilerOptions = {
26
- ...tsConfig.compilerOptions,
27
- jsx: "react-jsx",
28
- jsxImportSource: "mono-jsx",
29
- };
40
+ const compilerOptions = tsConfig.compilerOptions ?? (tsConfig.compilerOptions = {});
41
+ if (compilerOptions.jsx === "react-jsx" && compilerOptions.jsxImportSource === "mono-jsx") {
42
+ console.log("%cmono-jsx already setup.","color:grey");
43
+ return;
44
+ }
30
45
  if (!globalThis.Deno) {
31
- tsConfig.compilerOptions.alllowJs = true
46
+ compilerOptions.module ??= "es2022";
47
+ compilerOptions.moduleResolution ??= "bundler";
32
48
  }
33
- await writeFile(tsConfigPath, JSON.stringify(tsConfig, null, 2));
49
+ compilerOptions.jsx = "react-jsx";
50
+ compilerOptions.jsxImportSource = "mono-jsx";
51
+ await writeFile(tsConfigFilename, JSON.stringify(tsConfig, null, 2));
52
+ console.log("✅ mono-jsx setup complete.")
34
53
  }
package/jsx-runtime.mjs CHANGED
@@ -6,7 +6,7 @@ var $state = Symbol.for("mono.state");
6
6
  var $computed = Symbol.for("mono.computed");
7
7
 
8
8
  // state.ts
9
- function createState(request) {
9
+ function createState(context, request) {
10
10
  let collectDeps;
11
11
  const computed = (fn) => {
12
12
  const deps = /* @__PURE__ */ Object.create(null);
@@ -18,24 +18,28 @@ function createState(request) {
18
18
  };
19
19
  return new Proxy(/* @__PURE__ */ Object.create(null), {
20
20
  get(target, key, receiver) {
21
- const value = Reflect.get(target, key, receiver);
22
- if (key === "request") {
23
- if (!request) {
24
- throw new Error("request is not defined");
21
+ switch (key) {
22
+ case "context":
23
+ return context ?? {};
24
+ case "request":
25
+ if (!request) {
26
+ throw new Error("request is not defined");
27
+ }
28
+ return request;
29
+ case "computed":
30
+ return computed;
31
+ default: {
32
+ const value = Reflect.get(target, key, receiver);
33
+ if (typeof key === "symbol") {
34
+ return value;
35
+ }
36
+ if (collectDeps) {
37
+ collectDeps(key, value);
38
+ return value;
39
+ }
40
+ return [$state, { key, value }, $vnode];
25
41
  }
26
- return request;
27
- }
28
- if (key === "computed") {
29
- return computed;
30
42
  }
31
- if (typeof key === "symbol") {
32
- return value;
33
- }
34
- if (collectDeps) {
35
- collectDeps(key, value);
36
- return value;
37
- }
38
- return [$state, { key, value }, $vnode];
39
43
  },
40
44
  set(target, key, value, receiver) {
41
45
  const vt = typeof value;
@@ -375,7 +379,7 @@ async function renderNode(ctx, node, stripSlotProp) {
375
379
  eager = true;
376
380
  }
377
381
  try {
378
- const v = tag.call(createState(ctx.request), fcProps);
382
+ const v = tag.call(createState(ctx.context, ctx.request), fcProps);
379
383
  ctx.index.fc++;
380
384
  if (v instanceof Promise) {
381
385
  if (eager) {
@@ -575,10 +579,6 @@ async function renderNode(ctx, node, stripSlotProp) {
575
579
  );
576
580
  }
577
581
  }
578
- } else if (Array.isArray(node) || node && Symbol.iterator in node) {
579
- for (const child of node) {
580
- await renderNode(ctx, child);
581
- }
582
582
  }
583
583
  break;
584
584
  }
@@ -593,24 +593,25 @@ async function renderChildren(ctx, children, stripSlotProp) {
593
593
  }
594
594
  }
595
595
  function render(node, renderOptions = {}) {
596
- const { request, status, headers: headersRaw, rendering } = renderOptions;
597
- const headers = /* @__PURE__ */ Object.create(null);
598
- if (headersRaw) {
599
- const { etag, lastModified } = headersRaw;
596
+ const { context, request, status, headers: headersInit, rendering } = renderOptions;
597
+ const headers = new Headers();
598
+ if (headersInit) {
599
+ for (const [key, value] of Object.entries(headersInit)) {
600
+ if (value) {
601
+ headers.set(toHyphenCase(key), value);
602
+ }
603
+ }
604
+ const etag = headers.get("etag");
600
605
  if (etag && request?.headers.get("if-none-match") === etag) {
601
606
  return new Response(null, { status: 304 });
602
607
  }
608
+ const lastModified = headers.get("last-modified");
603
609
  if (lastModified && request?.headers.get("if-modified-since") === lastModified) {
604
610
  return new Response(null, { status: 304 });
605
611
  }
606
- for (const [key, value] of Object.entries(headersRaw)) {
607
- if (value) {
608
- headers[toHyphenCase(key)] = value;
609
- }
610
- }
611
612
  }
612
- headers["transfer-encoding"] = "chunked";
613
- headers["content-type"] = "text/html; charset=utf-8";
613
+ headers.set("transfer-encoding", "chunked");
614
+ headers.set("content-type", "text/html; charset=utf-8");
614
615
  return new Response(
615
616
  new ReadableStream({
616
617
  async start(controller) {
@@ -620,6 +621,7 @@ function render(node, renderOptions = {}) {
620
621
  const rtComponents = { cx: false, styleToCSS: false };
621
622
  const ctx = {
622
623
  write,
624
+ context,
623
625
  request,
624
626
  stateStore,
625
627
  suspenses,
@@ -673,7 +675,7 @@ var jsx = (tag, props = /* @__PURE__ */ Object.create(null), key) => {
673
675
  }
674
676
  if (tag === "html") {
675
677
  const renderOptions = /* @__PURE__ */ Object.create(null);
676
- for (const key2 of ["request", "status", "headers", "rendering"]) {
678
+ for (const key2 of ["context", "request", "status", "headers", "rendering"]) {
677
679
  if (Object.hasOwn(props, key2)) {
678
680
  renderOptions[key2] = props[key2];
679
681
  delete props[key2];
@@ -690,8 +692,8 @@ var html = (raw, ...values) => [
690
692
  $vnode
691
693
  ];
692
694
  Object.assign(globalThis, {
693
- css: html,
694
695
  html,
696
+ css: html,
695
697
  js: html
696
698
  });
697
699
  export {
package/package.json CHANGED
@@ -1,25 +1,28 @@
1
1
  {
2
2
  "name": "mono-jsx",
3
- "version": "0.1.3",
3
+ "version": "0.2.0",
4
4
  "description": "`<html>` as a `Response`.",
5
5
  "type": "module",
6
6
  "module": "./index.mjs",
7
+ "types": "./types/index.d.ts",
7
8
  "bin": {
8
9
  "mono-jsx": "./bin/mono-jsx"
9
10
  },
10
11
  "exports": {
11
12
  ".": {
13
+ "types": "./types/index.d.ts",
14
+ "node": "./index.mjs",
12
15
  "import": "./index.mjs"
13
16
  },
14
17
  "./jsx-runtime": {
15
18
  "types": "./types/jsx-runtime.d.ts",
16
- "import": "./jsx-runtime.mjs",
17
- "node": "./jsx-runtime.mjs"
19
+ "node": "./jsx-runtime.mjs",
20
+ "import": "./jsx-runtime.mjs"
18
21
  },
19
22
  "./jsx-dev-runtime": {
20
23
  "types": "./types/jsx-runtime.d.ts",
21
- "import": "./jsx-runtime.mjs",
22
- "node": "./jsx-runtime.mjs"
24
+ "node": "./jsx-runtime.mjs",
25
+ "import": "./jsx-runtime.mjs"
23
26
  }
24
27
  },
25
28
  "scripts": {
@@ -0,0 +1 @@
1
+ export {};
package/types/jsx.d.ts CHANGED
@@ -4,7 +4,6 @@ import type * as Mono from "./mono.d.ts";
4
4
  import type { HTML } from "./html.d.ts";
5
5
 
6
6
  export type ChildType = VNode | string | number | bigint | boolean | null;
7
- export type Children = ChildType | (ChildType | ChildType[])[];
8
7
 
9
8
  export type VNode = readonly [
10
9
  tag: string | symbol | FC<any>,
package/types/mono.d.ts CHANGED
@@ -66,7 +66,10 @@ export interface CSSProperties extends BaseCSSProperties, AtRuleCSSProperties, P
66
66
  [key: `&${" " | "." | "["}${string}`]: CSSProperties;
67
67
  }
68
68
 
69
+ export type ChildType = JSX.Element | string | number | bigint | boolean | null;
70
+
69
71
  export interface BaseAttributes {
72
+ children?: ChildType | (ChildType)[];
70
73
  key?: string | number;
71
74
  slot?: string;
72
75
  }
@@ -98,8 +101,9 @@ export interface Elements {
98
101
  }
99
102
 
100
103
  declare global {
101
- type FC<T = Record<string, unknown>> = {
104
+ type FC<T = Record<string, unknown>, Context = Record<string, unknown>> = {
105
+ context: Context;
102
106
  request: Request;
103
- computed: <T = unknown>(fn: () => T) => T;
107
+ computed: <V = unknown>(fn: () => V) => V;
104
108
  } & Omit<T, "request" | "computed">;
105
109
  }
package/types/render.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  export interface RenderOptions {
2
+ context?: Record<string, unknown>;
2
3
  request?: Request;
3
4
  status?: number;
4
5
  headers?: {