ziex 0.0.1-dev.7 → 0.1.0-dev.1014

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
@@ -1,10 +1,17 @@
1
- # ZX
1
+ <p align="center">
2
+ <img src="https://raw.githubusercontent.com/ziex-dev/branding/main/banner.svg" alt="Ziex banner" width="100%" />
3
+ </p>
2
4
 
3
- A Zig library for building web applications with JSX-like syntax. Write declarative UI components using familiar JSX patterns, transpiled to efficient Zig code.
5
+ A full-stack web framework for Zig. Write declarative UI components using familiar JSX patterns, transpiled to efficient Zig code.
4
6
 
5
- ZX combines the power and performance of Zig with the expressiveness of JSX, enabling you to build fast, type-safe web applications. ZX is significantly faster than frameworks like Next.js at SSR.
7
+ Ziex combines the power and performance of Zig with the expressiveness of JSX, enabling you to build fast, type-safe web applications.
8
+
9
+ **[Documentation →](https://ziex.dev/learn)**
10
+
11
+
12
+
13
+ > **Note:** Most of the API and syntax are finalized and stable, and server-side rendering (SSR) features are production-ready, Ziex continues to evolve with ongoing improvements to client-side rendering and state management. You can start using the documented features today, as they are stable and unlikely to change. Areas still under development are not yet documented and will be added as they mature.
6
14
 
7
- **[Full Documentation →](https://ziex.dev)**
8
15
 
9
16
  ## Installation
10
17
 
@@ -25,47 +32,45 @@ winget install -e --id zig.zig # Windows
25
32
  ```
26
33
  [_See for other platforms →_](https://ziglang.org/learn/getting-started/)
27
34
 
28
- ## Quick Example
29
35
 
30
- ```tsx site/pages/examples/overview.zx
31
- pub fn QuickExample(allocator: zx.Allocator) zx.Component {
36
+ ## At a Glance
37
+
38
+ ```tsx site/pages/examples/playground.zx
39
+ pub fn Playground(allocator: zx.Allocator) zx.Component {
32
40
  const is_loading = true;
33
- const chars = "Hello, ZX Dev!";
41
+ var i: usize = 0;
34
42
 
35
43
  return (
36
44
  <main @allocator={allocator}>
37
- <section>
38
- {if (is_loading) (<h1>Loading...</h1>) else (<h1>Loaded</h1>)}
39
- </section>
40
-
41
- <section>
42
- {for (chars) |char| (<span>{[char:c]}</span>)}
43
- </section>
44
-
45
- <section>
46
- {for (users) |user| (
47
- <Profile name={user.name} age={user.age} role={user.role} />
48
- )}
49
- </section>
45
+ <h1>Hello, Ziex!</h1>
46
+
47
+ {for (users) |user| (
48
+ <Profile name={user.name} age={user.age} role={user.role} />
49
+ )}
50
+
51
+ {if (is_loading) (<p>Loading...</p>) else (<p>Loaded</p>)}
52
+
53
+ {while (i < 5) : (i += 1) (<i>{i}</i>)}
50
54
  </main>
51
55
  );
52
56
  }
53
57
 
54
- fn Profile(allocator: zx.Allocator, user: User) zx.Component {
58
+ fn Profile(ctx: *zx.ComponentCtx(User)) zx.Component {
55
59
  return (
56
- <div @allocator={allocator}>
57
- <h1>{user.name}</h1>
58
- <p>{[user.age:d]}</p>
59
- {switch (user.role) {
60
- .admin => (<p>Admin</p>),
61
- .member => (<p>Member</p>),
62
- }}
60
+ <div @allocator={ctx.allocator}>
61
+ <h3>{ctx.props.name}</h3>
62
+ <div>{ctx.props.age}</div>
63
+ <strong>
64
+ {switch (ctx.props.role) {
65
+ .admin => "Admin",
66
+ .member => "Member",
67
+ }}
68
+ </strong>
63
69
  </div>
64
70
  );
65
71
  }
66
72
 
67
- const UserRole = enum { admin, member };
68
- const User = struct { name: []const u8, age: u32, role: UserRole };
73
+ const User = struct { name: []const u8, age: u32, role: enum { admin, member } };
69
74
 
70
75
  const users = [_]User{
71
76
  .{ .name = "John", .age = 20, .role = .admin },
@@ -74,79 +79,116 @@ const users = [_]User{
74
79
 
75
80
  const zx = @import("zx");
76
81
  ```
77
- ## Feature Checklist
78
-
79
- - [x] Server Side Rendering (SSR)
80
- - [x] Static Site Generation (SSG)
81
- - [ ] Client Side Rendering (CSR) via WebAssembly (_WIP_)
82
- - [x] Client Side Rendering (CSR) via React
83
- - [x] Type Safety
84
- - [x] Routing
85
- - [x] File-system Routing
86
- - [x] Search Parameters
87
- - [x] Path Segments
88
- - [x] Components
89
- - [x] Control Flow
90
- - [x] `if`
91
- - [ ] `if` nested
92
- - [x] `if/else`
93
- - [x] `if/else` nested
94
- - [x] `for`
95
- - [x] `for` nested
96
- - [x] `switch`
97
- - [x] `switch` nested
98
- - [x] `while`
99
- - [x] `while` nested
100
- - [x] Assets
101
- - [x] Copying
102
- - [x] Serving
103
- - [ ] Assets Optimization
104
- - [ ] Image
105
- - [ ] CSS
106
- - [ ] JS
107
- - [ ] HTML
108
- - [ ] Middleware
109
- - [ ] API Endpoints
110
- - [ ] Server Actions
111
- - [x] CLI
112
- - [x] `init` Project Template
113
- - [x] `transpile` Transpile .zx files to Zig source code
114
- - [x] `serve` Serve the project
115
- - [x] `dev` HMR or Rebuild on Change
116
- - [x] `fmt` Format the ZX source code (_Alpha_)
117
- - [x] `export` Generate static site assets
118
- - [x] `bundle` Bundle the ZX executable with public/assets and exe
119
- - [x] `version` Show the version of the ZX CLI
120
- - [x] `update` Update the version of ZX dependency
121
- - [x] `upgrade` Upgrade the version of ZX CLI
122
-
123
- #### Editor Support
124
-
125
- * [VSCode](https://marketplace.visualstudio.com/items?itemName=nurulhudaapon.zx)/[Cursor](https://marketplace.visualstudio.com/items?itemName=nurulhudaapon.zx) Extension
126
- - [x] Syntax Highlighting
127
- - [x] LSP Support
128
- - [x] Auto Format
129
-
130
- * Neovim
131
- - [ ] Syntax Highlighting
132
- - [ ] LSP Support
133
- - [ ] Auto Format
134
-
135
- ## Similar Projects
136
-
137
- * [Yew](https://github.com/yewstack/yew) - Rust / Wasm framework for creating reliable and efficient web applications
138
- * [ZTS](https://github.com/zigster64/zts) Zig Templates made Simple, a templating system for Zig
139
- * [zmpl](https://github.com/jetzig-framework/zmpl) — Mode-based templating language that compiles to Zig functions at build time, used in Jetzig
140
- * [mustache-zig](https://github.com/batiati/mustache-zig) — Mustache template engine implementation in Zig
141
- * [etch](https://github.com/haze/etch) — Compile-time tuned templating engine focusing on speed and simplicity
142
- * [Zap](https://github.com/zigzap/zap) — High-performance backend framework in Zig
143
- * [http.zig](https://github.com/karlseguin/http.zig) — Low-level HTTP/1.1 server written entirely in Zig (_ZX_'s backend)
144
- * [tokamak](https://github.com/cztomsik/tokamak) — Server-side framework for Zig
145
- * [zig-router](https://github.com/Cloudef/zig-router) — Straightforward HTTP-like request routing library for Zig
146
- * [zig-webui](https://github.com/webui-dev/zig-webui/) — Zig library that allows using any web browser as a GUI
147
- * [Zine](https://github.com/kristoff-it/zine) Fast, scalable, flexible static site generator (SSG) written in Zig
148
- * [Zinc](https://github.com/zon-dev/zinc/) Web framework written in pure Zig with focus on high performance, usability, security, and extensibility
149
- * [zUI](https://github.com/thienpow/zui) UI kit for Jetzig framework with reusable components and styles
82
+
83
+ Try this in [Playground →](https://ziex.dev/playground#data=eF59U01vnDAQ_StTTtAiyGZVqSKAEuVSVa2USy8NUUTAu2sJbGQgoUv83ztjlo-y2_rCfLx5zMyze-uhSH_vlWxF7h07K7Cq9gV2AuawnRaFzNJGqgCOnXc3eg5597KspGCigT4RgCeTom6A18-FTHMu9hBBo1p2M2RfUwU8gLbmR4aZKwwPCcWaVgmwB49OWKZcwO3086ifTB3PMAM9bOKvDLMu_OKs-xD6GBiZx9PvpAK7rZmqHXin7_vydxPXg5I7XjAQacminnAemRrS_eijpUHJYvTJ1OCvunL0WQt8B_a8GgfssIq_D47neaFfxQ6womZTguUmeM70dqAebQ4hfHYgIOtTBBui5HHPdehzUzYWhD6t89Shg2s3lKTzMK6dNV0AH5eK3jed_RPHcy4LfUGxnL_-JRhyev8RbRsbRKVkVQ87RuG2axiSLnG0-9Cn4ApXN0qK_SpKp6_feJMdwJ5JSDBnHGR9vDQv8eZFMSTWHZmJ5f4DWbLyhakB-sPYF7Far3r1z5pdjjTJM7wl0gDfCpa0GW7fXMwAHp-GbPvFpZuJb2p77ZpLGQATbYlAM4cLpyY16JuZ1LwDZH18fiL-0yq8HowQmEisb_JAowOtHAPXV2gSP9qnFWn3Ulkq2LJssygbW8G6ZTPHDpO3HC-YauzEOnaJRTuw9B927V4U)
84
+
85
+ <details>
86
+ <summary>Explanation of this</summary>
87
+
88
+ ```tsx site/pages/examples/playground.zx
89
+ // A Zig function that returns a `zx.Component`.
90
+ pub fn Playground(allocator: zx.Allocator) zx.Component {
91
+ const is_loading = true;
92
+ var i: usize = 0;
93
+
94
+ // HTML Block is always surrounded by parentheses and can contain HTML elements and control flow statements.
95
+ return (
96
+ // @allocator or any other attribute starting with `@` is called builtin attribute
97
+ // `@allocator` is used to specify the allocator for the component and its children for mem allocation.
98
+ <main @allocator={allocator}>
99
+ <h1>Hello, Ziex!</h1>
100
+
101
+ // `for` loop to iterate over `users` array and render a `Profile` component for each user.
102
+ // Since this is an expression the HTMLs are inside parenteses not curly braces.
103
+ {for (users) |user| (
104
+ // `Profile` component is called with props: name, age, and role.
105
+ // Optional props can be omitted, and the component will receive default values for them.
106
+ <Profile name={user.name} age={user.age} role={user.role} />
107
+ )}
108
+
109
+ // `if` statement works just like other control flow statements.
110
+ {if (is_loading) (<p>Loading...</p>) else (<p>Loaded</p>)}
111
+
112
+ // `while` loop with an optional increment statement.
113
+ {while (i < 5) : (i += 1) (<i>{i}</i>)}
114
+ </main>
115
+ );
116
+ }
117
+
118
+ // A Ziex Component is a Zig function that returns a `zx.Component`.
119
+ // It can have signatures like:
120
+ // - `pub fn ComponentName(allocator: zx.Allocator) zx.Component`
121
+ // - `pub fn ComponentName(ctx: *zx.ComponentCtx<PropsType>) zx.Component`
122
+ // - `pub fn ComponentName(allocator: zx.Allocator, props: PropsType) zx.Component`
123
+ fn Profile(ctx: *zx.ComponentCtx(User)) zx.Component {
124
+ return (
125
+ <div @allocator={ctx.allocator}>
126
+ // Exrepssion starts with `{` and ends with `}`. You can use it to access props, call functions, any valid Zig expression
127
+ <h3>{ctx.props.name}</h3>
128
+ <div>{ctx.props.age}</div>
129
+ <strong>
130
+ {switch (ctx.props.role) {
131
+ .admin => "Admin",
132
+ .member => "Member",
133
+ }}
134
+ </strong>
135
+ </div>
136
+ );
137
+ }
138
+
139
+ const User = struct { name: []const u8, age: u32, role: enum { admin, member } };
140
+
141
+ const users = [_]User{
142
+ .{ .name = "John", .age = 20, .role = .admin },
143
+ .{ .name = "Jane", .age = 21, .role = .member },
144
+ };
145
+
146
+ const zx = @import("zx");
147
+ ```
148
+
149
+ </details>
150
+
151
+ ## Features
152
+ - **JSX-like Syntax**: Write declarative UI components using familiar JSX patterns, transpiled to efficient Zig code.
153
+ - **Full-Stack Capabilities**: Build both frontend and backend of your web application using
154
+ - **It's Fast**: Significantly faster at SSR than many other frameworks.
155
+ - **Compile-time Safety**: Zig's type system catches bugs at compile time. No runtime surprises, no GC.
156
+ - **Familiar Syntax**: Familiar JSX-like syntax, or plain HTML-style markup, with full access to Zig's control flow.
157
+ - **Server-side Rendering**: Render per request on the server for dynamic data, auth, and personalized pages for best performance and SEO.
158
+ - **Static Site Generation**: Pre-render pages at build/export time into static HTML for fast CDN delivery.
159
+ - **File System Routing**: Folder structure defines routes. No configs, no magic strings, just files in folders.
160
+ - **Client-side Rendering**: Optional client-side rendering for interactive experiences when you need it.
161
+ - **Control Flow in Zig's Syntax**: if/else, for/while, and switch all work as expected. It's just Zig.
162
+ - **Developer Tooling**: CLI, hot reload, and editor extensions for the best DX.
163
+
164
+ ## Roadmap
165
+
166
+ We track our feature roadmap and bugs using GitHub Issues.
167
+ You can view our current progress and planned features here:
168
+
169
+ **[Check out the Ziex Issue Tracker →](https://github.com/ziex-dev/ziex/issues)**
170
+
171
+ ## Editor Support
172
+
173
+ * [VSCode](https://marketplace.visualstudio.com/items?itemName=ziex.ziex)/[VSCode Forks](https://open-vsx.org/extension/ziex/ziex) Extension
174
+ * [Neovim](/ide/neovim/)
175
+ * [Helix](/ide/helix/)
176
+ * [Zed](/ide/zed/)
177
+
178
+ ## Community
179
+
180
+ - [Discord](https://ziex.dev/r/discord)
181
+ - [Topic on Ziggit](https://ziex.dev/r/ziggit)
182
+ - [Project on Zig Discord Community](https://ziex.dev/r/zig-discord) (Join Zig Discord first: https://discord.gg/zig)
183
+
184
+
185
+ ## Links
186
+
187
+ * [Codeberg Mirror](https://codeberg.org/ziex/ziex) - ZX repository mirror on Codeberg
188
+ * [ziex.dev](https://github.com/ziex-dev/ziex/tree/main/site) - Official documentation site of ZX made using ZX.
189
+ * [example-blog](https://github.com/ziex-dev/example-blog) - Demo blog web application built with ZX
190
+ * [zx-numbers-game](https://github.com/Andrew-Velox/zx-numbers-game) - ZX numbers game
191
+ * [Comparision with other frameworks](https://ziex.dev/vs)
150
192
 
151
193
  ## Contributing
152
194
 
package/app.d.ts ADDED
@@ -0,0 +1,124 @@
1
+ import type { DurableObjectNamespace } from "./runtime";
2
+ import type { KVNamespace } from "./kv";
3
+ import type { D1Database } from "./db";
4
+ import type { WASI } from "./wasi";
5
+ /**
6
+ * Anything that can be resolved to a `WebAssembly.Module`:
7
+ * - `WebAssembly.Module` — already compiled (Cloudflare Workers, wrangler)
8
+ * - `ArrayBuffer` / `ArrayBufferView` — raw WASM bytes
9
+ * - `Response` — a fetch() response whose body is the WASM binary
10
+ * - `string` — an HTTP(S) URL or an absolute file path (Bun)
11
+ * - `URL` — a URL object
12
+ */
13
+ export type WasmInput = WebAssembly.Module | ArrayBuffer | ArrayBufferView | Response | string | URL;
14
+ /**
15
+ * Resolve any supported WASM input to a compiled `WebAssembly.Module`.
16
+ * The result is NOT cached here — cache it at the call site if needed.
17
+ */
18
+ export declare function resolveModule(input: WasmInput): Promise<WebAssembly.Module>;
19
+ /** Keys of `Env` whose value extends {@link KVNamespace}. */
20
+ type KVKey<Env> = {
21
+ [K in keyof Env]: Env[K] extends KVNamespace ? K : never;
22
+ }[keyof Env];
23
+ /** Keys of `Env` whose value extends {@link DurableObjectNamespace}. */
24
+ type DOKey<Env> = {
25
+ [K in keyof Env]: Env[K] extends DurableObjectNamespace ? K : never;
26
+ }[keyof Env];
27
+ type DBKey<Env> = {
28
+ [K in keyof Env]: Env[K] extends D1Database ? K : never;
29
+ }[keyof Env];
30
+ type ZiexOptions<Env> = {
31
+ /** WASM module — accepts any {@link WasmInput}. Resolved and cached on first request. */
32
+ module: WasmInput;
33
+ /** Optional pre-configured WASI instance. */
34
+ wasi?: WASI;
35
+ /** Extra WASM import namespaces. */
36
+ imports?: (mem: () => WebAssembly.Memory) => Record<string, Record<string, unknown>>;
37
+ /**
38
+ * KV namespace bindings. Two forms are supported:
39
+ *
40
+ * - **Env key**: a single key from `Env` whose value is a `KVNamespace` — used as the `"default"` binding.
41
+ * - **Name map**: `{ [bindingName]: envKey }` — map namespace names to env keys.
42
+ *
43
+ * @example Single env key (becomes the "default" binding)
44
+ * ```ts
45
+ * kv: "MY_KV"
46
+ * ```
47
+ * @example Name map
48
+ * ```ts
49
+ * kv: { default: "MY_KV", users: "USERS_KV" }
50
+ * ```
51
+ */
52
+ kv?: KVKey<Env> | Record<string, KVKey<Env>>;
53
+ /**
54
+ * D1 database bindings. Same shape as `kv`:
55
+ *
56
+ * - `"DB"` maps `env.DB` to the `"default"` database binding.
57
+ * - `{ default: "DB", analytics: "ANALYTICS_DB" }` maps multiple bindings.
58
+ */
59
+ db?: DBKey<Env> | Record<string, DBKey<Env>>;
60
+ /**
61
+ * Env key whose value is a `DurableObjectNamespace` for WebSocket pub/sub.
62
+ * Requires `createWebSocketDO` export on the worker.
63
+ *
64
+ * @example
65
+ * ```ts
66
+ * websocket: "ChatRoom"
67
+ * ```
68
+ */
69
+ websocket?: DOKey<Env>;
70
+ };
71
+ /**
72
+ * Main Ziex application class. Mirrors the Hono API style — construct once,
73
+ * export as default, and the runtime calls `fetch` for you.
74
+ *
75
+ * Works on Cloudflare Workers, Bun, and Vercel Edge out of the box.
76
+ *
77
+ * @example Cloudflare Workers / wrangler
78
+ * ```ts
79
+ * import { Ziex } from "ziex";
80
+ * import module from "./app.wasm";
81
+ *
82
+ * const app = new Ziex<Env>({
83
+ * module,
84
+ * kv: (env) => ({ default: env.KV }),
85
+ * });
86
+ * export default app;
87
+ * ```
88
+ *
89
+ * @example Bun
90
+ * ```ts
91
+ * import { Ziex } from "ziex";
92
+ * import wasmPath from "./app.wasm" with { type: "wasm" };
93
+ *
94
+ * const app = new Ziex({ module: wasmPath });
95
+ * export default app;
96
+ * ```
97
+ *
98
+ * @example Vercel Edge
99
+ * ```ts
100
+ * import { Ziex } from "ziex";
101
+ * import { handle } from "ziex/vercel";
102
+ *
103
+ * const app = new Ziex({ module: "https://example.com/app.wasm" });
104
+ * export default handle(app);
105
+ * ```
106
+ */
107
+ export declare class Ziex<Env = Record<string, unknown>> {
108
+ private readonly options;
109
+ private resolved;
110
+ constructor(options: ZiexOptions<Env>);
111
+ private getModule;
112
+ private resolveKV;
113
+ private resolveDB;
114
+ /**
115
+ * Fetch handler called by the runtime on every request.
116
+ *
117
+ * Arrow function so `this` is always the class instance, even when the
118
+ * runtime extracts `fetch` from the exported object (e.g. Bun).
119
+ */
120
+ fetch: (request: Request, env: Env, ctx?: {
121
+ waitUntil(p: Promise<unknown>): void;
122
+ }) => Promise<Response>;
123
+ }
124
+ export {};
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Ziex adapter for AWS Lambda (API Gateway v1, v2, and ALB).
3
+ *
4
+ * Based on Hono's AWS Lambda adapter implementation.
5
+ *
6
+ * @example API Gateway v2 (HTTP API)
7
+ * ```ts
8
+ * import { Ziex } from "ziex/cloudflare";
9
+ * import { handle } from "ziex/aws-lambda";
10
+ * import module from "./app.wasm";
11
+ *
12
+ * const app = new Ziex({ module });
13
+ * export const handler = handle(app);
14
+ * ```
15
+ */
16
+ type ApiGwV1Event = {
17
+ version?: "1.0";
18
+ httpMethod: string;
19
+ path: string;
20
+ headers: Record<string, string> | null;
21
+ multiValueHeaders: Record<string, string[]> | null;
22
+ queryStringParameters: Record<string, string> | null;
23
+ multiValueQueryStringParameters: Record<string, string[]> | null;
24
+ body: string | null;
25
+ isBase64Encoded: boolean;
26
+ requestContext: {
27
+ elb?: unknown;
28
+ };
29
+ };
30
+ type ApiGwV2Event = {
31
+ version: "2.0";
32
+ requestContext: {
33
+ http: {
34
+ method: string;
35
+ };
36
+ };
37
+ rawPath: string;
38
+ rawQueryString: string;
39
+ headers: Record<string, string>;
40
+ body?: string;
41
+ isBase64Encoded: boolean;
42
+ };
43
+ type AlbEvent = {
44
+ httpMethod: string;
45
+ path: string;
46
+ headers: Record<string, string> | null;
47
+ multiValueHeaders: Record<string, string[]> | null;
48
+ queryStringParameters: Record<string, string> | null;
49
+ multiValueQueryStringParameters: Record<string, string[]> | null;
50
+ body: string | null;
51
+ isBase64Encoded: boolean;
52
+ requestContext: {
53
+ elb: unknown;
54
+ };
55
+ };
56
+ export type LambdaEvent = ApiGwV1Event | ApiGwV2Event | AlbEvent;
57
+ export type LambdaContext = {
58
+ functionName: string;
59
+ functionVersion: string;
60
+ invokedFunctionArn: string;
61
+ memoryLimitInMB: string;
62
+ awsRequestId: string;
63
+ logGroupName: string;
64
+ logStreamName: string;
65
+ callbackWaitsForEmptyEventLoop: boolean;
66
+ getRemainingTimeInMillis(): number;
67
+ };
68
+ export type LambdaResult = {
69
+ statusCode: number;
70
+ headers: Record<string, string>;
71
+ multiValueHeaders: Record<string, string[]>;
72
+ body: string;
73
+ isBase64Encoded: boolean;
74
+ cookies?: string[];
75
+ };
76
+ type FetchApp = {
77
+ fetch(req: Request, env?: unknown, ctx?: unknown): Promise<Response>;
78
+ };
79
+ export type HandleOptions = {
80
+ /**
81
+ * Content types to encode as base64 in the Lambda response.
82
+ * By default, non-text content types are base64 encoded automatically.
83
+ */
84
+ binaryMediaTypes?: string[];
85
+ };
86
+ /**
87
+ * Wrap a Ziex app as an AWS Lambda handler.
88
+ *
89
+ * @example
90
+ * ```ts
91
+ * import { handle } from "ziex/aws-lambda";
92
+ * export const handler = handle(app);
93
+ * ```
94
+ */
95
+ export declare function handle(app: FetchApp, options?: HandleOptions): (event: LambdaEvent, _context?: LambdaContext) => Promise<LambdaResult>;
96
+ export {};
@@ -0,0 +1,130 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __returnValue = (v) => v;
3
+ function __exportSetter(name, newValue) {
4
+ this[name] = __returnValue.bind(null, newValue);
5
+ }
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, {
9
+ get: all[name],
10
+ enumerable: true,
11
+ configurable: true,
12
+ set: __exportSetter.bind(all, name)
13
+ });
14
+ };
15
+
16
+ // src/aws-lambda/index.ts
17
+ function isV2(event) {
18
+ return "requestContext" in event && event.requestContext !== null && "http" in event.requestContext;
19
+ }
20
+ function getMethod(event) {
21
+ if (isV2(event))
22
+ return event.requestContext.http.method;
23
+ return event.httpMethod;
24
+ }
25
+ function getPath(event) {
26
+ if (isV2(event)) {
27
+ return event.rawPath + (event.rawQueryString ? `?${event.rawQueryString}` : "");
28
+ }
29
+ const e = event;
30
+ const mvqs = e.multiValueQueryStringParameters;
31
+ const qs = e.queryStringParameters;
32
+ let queryString = "";
33
+ if (mvqs) {
34
+ queryString = Object.entries(mvqs).flatMap(([k, vs]) => (vs ?? []).map((v) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)).join("&");
35
+ } else if (qs) {
36
+ queryString = new URLSearchParams(qs).toString();
37
+ }
38
+ return e.path + (queryString ? `?${queryString}` : "");
39
+ }
40
+ function getHeaders(event) {
41
+ const headers = new Headers;
42
+ if (event.headers) {
43
+ for (const [k, v] of Object.entries(event.headers)) {
44
+ if (v != null)
45
+ headers.set(k, v);
46
+ }
47
+ }
48
+ if ("multiValueHeaders" in event && event.multiValueHeaders) {
49
+ for (const [k, vs] of Object.entries(event.multiValueHeaders)) {
50
+ if (!vs?.length)
51
+ continue;
52
+ headers.delete(k);
53
+ for (const v of vs)
54
+ headers.append(k, v);
55
+ }
56
+ }
57
+ return headers;
58
+ }
59
+ function getBody(event) {
60
+ if (!event.body)
61
+ return null;
62
+ if (event.isBase64Encoded)
63
+ return Buffer.from(event.body, "base64");
64
+ return event.body;
65
+ }
66
+ function toRequest(event, headers) {
67
+ const method = getMethod(event);
68
+ const host = headers.get("host") ?? "localhost";
69
+ const proto = headers.get("x-forwarded-proto") ?? "https";
70
+ const path = getPath(event);
71
+ const url = `${proto}://${host}${path}`;
72
+ const body = ["GET", "HEAD"].includes(method) ? null : getBody(event);
73
+ return new Request(url, { method, headers, body });
74
+ }
75
+ var TEXT_CONTENT_TYPES = [
76
+ "text/",
77
+ "application/json",
78
+ "application/xml",
79
+ "application/javascript",
80
+ "application/xhtml"
81
+ ];
82
+ function isBinaryContent(contentType, binaryMediaTypes) {
83
+ if (binaryMediaTypes.length > 0) {
84
+ return binaryMediaTypes.some((t) => contentType.includes(t));
85
+ }
86
+ return !TEXT_CONTENT_TYPES.some((t) => contentType.startsWith(t));
87
+ }
88
+ async function toLambdaResult(res, binaryMediaTypes) {
89
+ const responseHeaders = {};
90
+ const multiValueHeaders = {};
91
+ res.headers.forEach((value, key) => {
92
+ if (key in responseHeaders) {
93
+ multiValueHeaders[key] = [...multiValueHeaders[key] ?? [responseHeaders[key]], value];
94
+ delete responseHeaders[key];
95
+ } else if (key in multiValueHeaders) {
96
+ multiValueHeaders[key].push(value);
97
+ } else {
98
+ responseHeaders[key] = value;
99
+ }
100
+ });
101
+ const contentType = res.headers.get("content-type") ?? "";
102
+ const binary = isBinaryContent(contentType, binaryMediaTypes);
103
+ let body;
104
+ let isBase64Encoded = false;
105
+ if (binary) {
106
+ body = Buffer.from(await res.arrayBuffer()).toString("base64");
107
+ isBase64Encoded = true;
108
+ } else {
109
+ body = await res.text();
110
+ }
111
+ return {
112
+ statusCode: res.status,
113
+ headers: responseHeaders,
114
+ multiValueHeaders,
115
+ body,
116
+ isBase64Encoded
117
+ };
118
+ }
119
+ function handle(app, options = {}) {
120
+ const binaryMediaTypes = options.binaryMediaTypes ?? [];
121
+ return async (event, _context) => {
122
+ const headers = getHeaders(event);
123
+ const req = toRequest(event, headers);
124
+ const res = await app.fetch(req);
125
+ return toLambdaResult(res, binaryMediaTypes);
126
+ };
127
+ }
128
+ export {
129
+ handle
130
+ };
package/bin/ziex ADDED
@@ -0,0 +1,25 @@
1
+ #!/usr/bin/env node
2
+ import { spawn } from 'node:child_process';
3
+ import { createRequire } from 'node:module';
4
+
5
+ const require = createRequire(import.meta.url);
6
+ const pkgName = `@ziex/cli-${process.platform}-${process.arch}`;
7
+
8
+ try {
9
+ const binaryPath = require.resolve(`${pkgName}/bin/zx`);
10
+
11
+ const child = spawn(binaryPath, process.argv.slice(2), {
12
+ stdio: 'inherit',
13
+ shell: process.platform === 'win32'
14
+ });
15
+
16
+ child.on('exit', (code) => process.exit(code ?? 0));
17
+ child.on('error', (err) => {
18
+ console.error('Failed to start child process:', err);
19
+ process.exit(1);
20
+ });
21
+ } catch (e) {
22
+ console.error(`Error: Could not find binary for ${process.platform}-${process.arch}`);
23
+ console.error(`Ensure the optional dependency "${pkgName}" is installed.`);
24
+ process.exit(1);
25
+ }