@server/next 0.19.0 → 0.20.1

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/index.d.ts ADDED
@@ -0,0 +1,50 @@
1
+ type Bucket = {};
2
+
3
+ type Method =
4
+ | "socket"
5
+ | "get"
6
+ | "head"
7
+ | "post"
8
+ | "put"
9
+ | "patch"
10
+ | "delete"
11
+ | "options";
12
+
13
+ type ServerOptions = {
14
+ port?: number;
15
+ views?: string | Bucket;
16
+ public?: string | Bucket;
17
+ uploads?: string | Bucket;
18
+ };
19
+
20
+ type Context = {
21
+ method: Method;
22
+ headers: { [key: string]: string | string[] };
23
+ cookies: { [key: string]: any };
24
+ body?: any;
25
+ url: URL & { params: {}; query: {} };
26
+ options: ServerOptions;
27
+ };
28
+
29
+ type Middleware = (ctx: Context) => any;
30
+
31
+ type Router = {};
32
+
33
+ declare interface Server {
34
+ (options?: ServerOptions): this;
35
+
36
+ socket(path: string, ...middleware: Middleware[]): this;
37
+ get(path: string, ...middleware: Middleware[]): this;
38
+ head(path: string, ...middleware: Middleware[]): this;
39
+ post(path: string, ...middleware: Middleware[]): this;
40
+ put(path: string, ...middleware: Middleware[]): this;
41
+ patch(path: string, ...middleware: Middleware[]): this;
42
+ del(path: string, ...middleware: Middleware[]): this;
43
+ options(path: string, ...middleware: Middleware[]): this;
44
+
45
+ use(...middleware: Middleware[]): this;
46
+ router(router: Router): this;
47
+ }
48
+
49
+ declare const server: Server;
50
+ export default server;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@server/next",
3
- "version": "0.19.0",
3
+ "version": "0.20.1",
4
4
  "description": "An experimental reimplementation of server.js focused on the DX",
5
5
  "homepage": "https://node-server.com/",
6
6
  "repository": "https://github.com/franciscop/server-next.git",
@@ -10,9 +10,7 @@
10
10
  "license": "UNLICENSED",
11
11
  "scripts": {
12
12
  "demo": "nodemon ./demo/app.js",
13
- "build": "bun build src/index.js --outdir ./ --entry-naming server.js",
14
13
  "start": "bun test --watch",
15
- "size": "echo \"$(gzip -c server.js | wc -c) bytes\" # Only for Unix",
16
14
  "test": "bun test"
17
15
  },
18
16
  "keywords": [
@@ -21,9 +19,11 @@
21
19
  "server.js"
22
20
  ],
23
21
  "type": "module",
22
+ "types": "index.d.ts",
24
23
  "main": "src/index.js",
25
24
  "files": [
26
- "src/"
25
+ "src/",
26
+ "index.d.ts"
27
27
  ],
28
28
  "engines": {
29
29
  "node": ">=20.0.0"
package/readme.md CHANGED
@@ -1,6 +1,8 @@
1
1
  # Server @ Next
2
2
 
3
- > **EXPERIMENTAL LIBRARY**
3
+ > **⚠️ WIP** This is an **experimental library** right now!
4
+
5
+ [**Documentation Here**](https://node-server.com/documentation/)
4
6
 
5
7
  A fully-fledged web server for Bun and Node.js, with all the basics covered for you:
6
8
 
@@ -9,26 +11,26 @@ import server from "@server/next";
9
11
 
10
12
  // Create a running instance of the server
11
13
  export default server(options)
12
- .router("/admin/", dashboard)
13
- .get("/users", getUsers)
14
- .post("/users", createUser)
15
- .put("/users/:id", editUser);
14
+ .get("/books", () => Book.list())
15
+ .post("/books", { body: BookSchema }, (ctx) => {
16
+ return Book.create(ctx.body).save();
17
+ });
16
18
  ```
17
19
 
18
- It includes all the things you would expect from a modern Server framework, like routing, static file serving, options\*, body+file parsing, gzip+brotli, streaming, server-timing, plugins\*, etc.
19
-
20
- > \* not yet available
20
+ It includes all the things you would expect from a modern Server framework, like routing, static file serving, body+file parsing, gzip+brotli, streaming, testing, error handling, websockets, etc. We also have integrations with these:
21
21
 
22
- For testing it's also easy, since we are exporting our server throught the WinterCG API we can do:
22
+ - KV Stores: in-memory, Redis, Consul, DynamoDB.
23
+ - Buckets: AWS S3, Cloudflare R2, Backblaze B2.
24
+ - Validation libraries: Zod, Joi, Yup.
23
25
 
24
26
  ```js
25
- // index.test.js
27
+ // Easy testing as well - index.test.js
26
28
  import app from "./";
27
29
 
28
30
  it("can retrieve the homepage", async () => {
29
- const res = await app.fetch(new Request("http://localhost:3000/hello/"));
30
- const data = await res.text();
31
- expect(data).toBe("Hello world");
31
+ const res = await app.fetch(new Request("http://localhost:3000/books/"));
32
+ const books = await res.json();
33
+ expect(books[0]).toEqual({ id: 0, name: 'The Catcher In The Rye', ... });
32
34
  });
33
35
  ```
34
36
 
@@ -43,18 +45,10 @@ Why? We live in the era of multi-cloud (Heroku, Workers, Lambda, etc) and multi-
43
45
  - Changed the reply logic greatly, including the removal of `render()`. This is the main reason express was removed. Many servers don't need render() at all.
44
46
  - **[security]** Removed mandatory CSRF token, since this is only useful for server-rendered pages and not for SPA. Now we provide an `auth` module instead.
45
47
 
46
- Major changes:
47
-
48
- - New fully fledged `ctx.url` that extends [`URL`](https://developer.mozilla.org/en-US/docs/Web/API/URL) object inside `ctx` (also note: `ctx.url` is no longer a string):
49
- - `ctx.params` is now `ctx.url.params`, e.g. `ctx.url.params.id`.
50
- - `ctx.query` is now `ctx.url.query`, e.g. `ctx.url.query.search`.
51
- - `ctx.path` is now `ctx.url.path` (or `ctx.url.pathname`).
52
- - All URL properties are available, like `ctx.url.port`, `ctx.url.searchParams`, etc.
53
-
54
48
  ## Progress
55
49
 
56
50
  - Router has all verbs, as well as URL pattern matches
57
- - Full URL parsing, including `query` and `params` in ctx.url.
51
+ - Full URL parsing, including `query` and `params` in `ctx.url`.
58
52
  - Body and Files parsing is working (need testing)
59
53
  - The middleware can return:
60
54
  - A number and it'll be set as the status code
@@ -63,42 +57,6 @@ Major changes:
63
57
  - An object with `status`, `body` and `headers` and it'll be set raw.
64
58
  - Response compression works
65
59
 
66
- ## Some plugins
67
-
68
- > This question is just some concepts/ideas
69
-
70
- Plugins? Or internals?
71
-
72
- ```js
73
- import Bucket from 'bucket/s3';
74
- import Redis from 'redis';
75
-
76
- const bucket = Bucket('my-bucket', { id, key });
77
- const cache = Redis('my-redis', ...);
78
-
79
- const app = server({ public: bucket, uploads: bucket, cache });
80
-
81
- app([
82
- post('/uploads', ctx => {
83
- // Without { public: bucket }, it'd be a local file in the filesystem
84
- console.log(ctx.files.profile);
85
- // file.name
86
- // file.id
87
- // file.path
88
- // file.type
89
- // file.size
90
-
91
- // With { public: bucket }, it's the reference to the bucket file
92
- console.log(ctx.files.profile);
93
- // file.name
94
- // file.id
95
- // file.path
96
- // file.type
97
- // file.size
98
- })
99
- ]);
100
- ```
101
-
102
60
  ## Examples
103
61
 
104
62
  ### Streams
@@ -156,58 +114,3 @@ export default server()
156
114
  return 201;
157
115
  });
158
116
  ```
159
-
160
- ```js
161
- import server, { jwtAuth } from "server";
162
- import BookRouter from "./BookRouter";
163
- import UserRouter from "./UserRouter";
164
-
165
- export default server({ port: 3000 })
166
- .use(jwtAuth)
167
- .route("/users", UserRouter)
168
- .route("/books", BookRouter);
169
- ```
170
-
171
- ```js
172
- // UserRouter.js -> A custom router
173
- import server, { router } from "server";
174
-
175
- export default router()
176
- .get("/", getUsers)
177
- .get("/:id", getUser)
178
- .post("/", createUser);
179
- ```
180
-
181
- MAYBE?
182
-
183
- ```js
184
- // BookRouter.js -> a REST API router
185
- import { RestRouter } from "server";
186
-
187
- export default class BookRouter extends RestRouter {
188
- async create(ctx) {
189
- // POST /
190
- }
191
- async list(ctx) {
192
- // GET /
193
- }
194
- async get(ctx) {
195
- // GET /:id
196
- }
197
- async search(ctx) {
198
- // GET /?...
199
- }
200
- async update(ctx) {
201
- // PUT /:id
202
- }
203
- async set(ctx) {
204
- // PATCH /:id
205
- }
206
- async delete(ctx) {
207
- // DELETE /:id
208
- }
209
- async error(ctx) {
210
- // ctx.error
211
- }
212
- }
213
- ```
package/src/bucket.js CHANGED
@@ -21,7 +21,6 @@ export default function (root) {
21
21
  path: root,
22
22
  read: (name, type = "utf8") => {
23
23
  const fullPath = absolute(name);
24
- console.log(name, fullPath);
25
24
  return fsp.readFile(fullPath, type);
26
25
  },
27
26
  write: (name, value, type = "utf8") => {
@@ -20,10 +20,23 @@ export default async (request, options = {}) => {
20
20
  Object.fromEntries(url.searchParams.entries())
21
21
  );
22
22
 
23
- if (request.body) {
24
- const type = ctx.headers["content-type"];
25
- ctx.body = await parseBody(request, type, options.uploads);
26
- }
23
+ await new Promise((resolve, reject) => {
24
+ const body = [];
25
+ request
26
+ .on("data", (chunk) => {
27
+ body.push(chunk);
28
+ })
29
+ .on("end", async () => {
30
+ const type = ctx.headers["content-type"];
31
+ ctx.body = await parseBody(
32
+ Buffer.concat(body).toString(),
33
+ type,
34
+ options.uploads
35
+ );
36
+ resolve();
37
+ })
38
+ .on("error", reject);
39
+ });
27
40
 
28
41
  return ctx;
29
42
  };
@@ -0,0 +1,6 @@
1
+ export default class StatusError extends Error {
2
+ constructor(msg, status = 500) {
3
+ super(msg);
4
+ this.status = status;
5
+ }
6
+ }
@@ -1,6 +1,7 @@
1
1
  import parseResponse from "../parseResponse.js";
2
2
  import pathPattern from "../pathPattern.js";
3
3
  import define from "./define.js";
4
+ import validate from "./validate.js";
4
5
 
5
6
  export default async function handleRequest(handlers, ctx) {
6
7
  for (let [matcher, ...cbs] of handlers[ctx.method]) {
@@ -11,10 +12,17 @@ export default async function handleRequest(handlers, ctx) {
11
12
  define(ctx.url, "params", () => match);
12
13
 
13
14
  for (let cb of cbs) {
14
- const out = await parseResponse(cb, ctx);
15
- if (out) return out;
15
+ try {
16
+ validate(ctx, cb);
17
+ if (typeof cb === "function") {
18
+ const out = await parseResponse(cb, ctx);
19
+ if (out) return out;
20
+ }
21
+ } catch (error) {
22
+ return new Response(error.message, { status: error.status || 500 });
23
+ }
16
24
  }
17
25
  }
18
26
 
19
- return Response("Not Found", { status: 404 });
27
+ return new Response("Not Found", { status: 404 });
20
28
  }
@@ -0,0 +1,35 @@
1
+ import StatusError from "./StatusError.js";
2
+
3
+ export default function (ctx, schema) {
4
+ if (!schema || typeof schema !== "object") return;
5
+
6
+ let base;
7
+ try {
8
+ if (typeof schema?.body === "function") {
9
+ base = "body";
10
+ schema.body(ctx.body || {});
11
+ }
12
+ if (typeof schema?.body?.parse === "function") {
13
+ base = "body";
14
+ schema.body.parse(ctx.body || {});
15
+ }
16
+ if (typeof schema?.query === "function") {
17
+ base = "query";
18
+ schema.query(ctx.url.query || {});
19
+ }
20
+ if (typeof schema?.query?.parse === "function") {
21
+ base = "query";
22
+ schema.query.parse(ctx.url.query || {});
23
+ }
24
+ } catch (error) {
25
+ if (error.constructor.name === "ZodError") {
26
+ console.log(error);
27
+ const message = error.issues
28
+ .map(({ path, message }) => `[${base}.${path.join(".")}]: ${message}`)
29
+ .sort()
30
+ .join("\n");
31
+ throw new StatusError(message, 422);
32
+ }
33
+ throw error;
34
+ }
35
+ }
package/src/index.js CHANGED
@@ -21,6 +21,8 @@ export default function server(options = {}) {
21
21
 
22
22
  this.handlers = {};
23
23
 
24
+ options.port = options.port || process.env.PORT || 3000;
25
+
24
26
  options.views = options.views ? Bucket(options.views) : null;
25
27
  options.public = options.public ? Bucket(options.public) : null;
26
28
  options.uploads = options.uploads ? Bucket(options.uploads) : null;
@@ -64,7 +66,7 @@ export default function server(options = {}) {
64
66
  this.fetch = async (request, env, fetchCtx) => {
65
67
  if (env?.upgrade(request)) return;
66
68
 
67
- const ctx = await createWinterContext(request, options);
69
+ const ctx = await createWinterContext(request, options, this.platform);
68
70
  ctx.platform = this.platform;
69
71
 
70
72
  return await handleRequest(this.handlers, ctx);
package/src/index.test.js CHANGED
@@ -1,21 +1,37 @@
1
1
  import server, { status } from "./index.js";
2
2
 
3
- describe("server", () => {
3
+ describe("return different types", () => {
4
4
  const app = server()
5
5
  .get("/", () => "Hello world")
6
6
  .get("/text", () => "Hello world")
7
7
  .get("/array", () => ["Hello world"])
8
8
  .get("/object", () => ({ hello: "world" }))
9
- .get("/status", () => 201)
10
- .post("/", (ctx) => status(201).send(ctx.body));
9
+ .get("/status", () => 201);
11
10
 
12
- it("can render hello world", async () => {
13
- const res = await app.fetch(new Request("http://localhost:3000/"));
14
-
15
- expect(res.status).toBe(200);
11
+ it("can get the plain text", async () => {
12
+ const res = await app.fetch(new Request("http://localhost:3000/text"));
16
13
  expect(await res.text()).toBe("Hello world");
17
14
  });
18
15
 
16
+ it("can get the array", async () => {
17
+ const res = await app.fetch(new Request("http://localhost:3000/array"));
18
+ expect(await res.json()).toEqual(["Hello world"]);
19
+ });
20
+
21
+ it("can get the object", async () => {
22
+ const res = await app.fetch(new Request("http://localhost:3000/object"));
23
+ expect(await res.json()).toEqual({ hello: "world" });
24
+ });
25
+
26
+ it("can get the status", async () => {
27
+ const res = await app.fetch(new Request("http://localhost:3000/status"));
28
+ expect(res.status).toBe(201);
29
+ });
30
+ });
31
+
32
+ describe("simple post works", () => {
33
+ const app = server().post("/", (ctx) => status(201).send(ctx.body));
34
+
19
35
  it("can post new data", async () => {
20
36
  const res = await app.fetch(
21
37
  new Request("http://localhost:3000/", {
@@ -41,5 +57,3 @@ describe("server", () => {
41
57
  expect(await res.json()).toEqual({ hello: "world" });
42
58
  });
43
59
  });
44
-
45
- describe("all the replies", () => {});
package/src/reply.js CHANGED
@@ -64,7 +64,6 @@ Reply.prototype.file = async function (path) {
64
64
 
65
65
  Reply.prototype.view = async function (path) {
66
66
  return async (ctx) => {
67
- console.log(ctx);
68
67
  if (!ctx.options.views) {
69
68
  throw new Error("Views not enabled");
70
69
  }