@lango-project/lango-server 0.1.1 → 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.
Files changed (61) hide show
  1. package/README.md +149 -18
  2. package/dist/.lango/localization.mjs +108 -0
  3. package/dist/.lango/runtime.mjs +25 -6
  4. package/dist/.lango/vendor/i18next.LICENSE +21 -0
  5. package/dist/.lango/vendor/i18next.mjs +2434 -0
  6. package/dist/cli/.lango/localization.mjs +108 -0
  7. package/dist/cli/.lango/runtime.mjs +25 -6
  8. package/dist/cli/.lango/vendor/i18next.LICENSE +21 -0
  9. package/dist/cli/.lango/vendor/i18next.mjs +2434 -0
  10. package/dist/cli/endpoint.mjs +2 -6
  11. package/dist/cli/endpoint.mjs.map +1 -1
  12. package/dist/cli/longpoll_options.mjs +1 -1
  13. package/dist/cli/longpoll_options.mjs.map +1 -1
  14. package/dist/cli/options.mjs +2 -2
  15. package/dist/cli/options.mjs.map +1 -1
  16. package/dist/cli/route_pattern.mjs +129 -0
  17. package/dist/cli/route_pattern.mjs.map +1 -0
  18. package/dist/cli/routes.mjs +25 -13
  19. package/dist/cli/routes.mjs.map +1 -1
  20. package/dist/cli/static_files.mjs +121 -25
  21. package/dist/cli/static_files.mjs.map +1 -1
  22. package/dist/endpoint.mjs +2 -6
  23. package/dist/endpoint.mjs.map +1 -1
  24. package/dist/http_failure.mjs +45 -0
  25. package/dist/http_failure.mjs.map +1 -0
  26. package/dist/longpoll_options.mjs +1 -1
  27. package/dist/longpoll_options.mjs.map +1 -1
  28. package/dist/options.mjs +2 -2
  29. package/dist/options.mjs.map +1 -1
  30. package/dist/response.mjs +8 -0
  31. package/dist/response.mjs.map +1 -1
  32. package/dist/route_info.mjs +22 -0
  33. package/dist/route_info.mjs.map +1 -0
  34. package/dist/route_pattern.mjs +129 -0
  35. package/dist/route_pattern.mjs.map +1 -0
  36. package/dist/routes.mjs +25 -13
  37. package/dist/routes.mjs.map +1 -1
  38. package/dist/runtime.mjs +132 -22
  39. package/dist/runtime.mjs.map +1 -1
  40. package/dist/server_context.mjs +25 -2
  41. package/dist/server_context.mjs.map +1 -1
  42. package/dist/static_files.mjs +121 -25
  43. package/dist/static_files.mjs.map +1 -1
  44. package/dist/token.mjs +38 -13
  45. package/dist/token.mjs.map +1 -1
  46. package/dist/tokens.mjs +16 -1
  47. package/dist/tokens.mjs.map +1 -1
  48. package/package.json +3 -3
  49. package/src/endpoint.lango +3 -4
  50. package/src/http_failure.lango +26 -0
  51. package/src/longpoll_options.lango +1 -1
  52. package/src/options.lango +2 -2
  53. package/src/response.lango +6 -0
  54. package/src/route_info.lango +15 -0
  55. package/src/route_pattern.lango +86 -0
  56. package/src/routes.lango +20 -8
  57. package/src/runtime.lango +119 -19
  58. package/src/server_context.lango +19 -3
  59. package/src/static_files.lango +99 -23
  60. package/src/token.lango +24 -3
  61. package/src/tokens.lango +11 -1
package/dist/token.mjs CHANGED
@@ -15,20 +15,35 @@ import {
15
15
  } from "./.lango/runtime.mjs";
16
16
 
17
17
  export class Token {
18
- clientId;
19
- auth;
20
- expiresAt;
21
18
  #claims;
22
19
  #readonly;
20
+ #renew;
21
+ #clientId;
22
+ #auth;
23
+ #expiresAt;
23
24
  constructor(claims, readonly = false) {
24
25
  __requireArity(arguments.length, [0], "constructor");
25
26
  claims = __boundary(claims);
26
27
  readonly = __boundary(readonly);
27
28
  this.#claims = __fromJson(__toJson(claims));
28
29
  this.#readonly = readonly;
29
- this.clientId = __normalize(claims.clientId);
30
- this.auth = __normalize(claims.auth);
31
- this.expiresAt = __normalize(claims.exp);
30
+ this.#renew = false;
31
+ this.#clientId = __normalize(claims.clientId);
32
+ this.#auth = __normalize(claims.auth);
33
+ this.#expiresAt = __normalize(claims.exp);
34
+ __normalize(__hostGlobal(["Object"]).freeze(this));
35
+ }
36
+ get clientId() {
37
+ return __normalize(this.#clientId);
38
+ return null;
39
+ }
40
+ get auth() {
41
+ return __normalize(this.#auth);
42
+ return null;
43
+ }
44
+ get expiresAt() {
45
+ return __normalize(this.#expiresAt);
46
+ return null;
32
47
  }
33
48
  AddAuth(permission) {
34
49
  __requireArity(arguments.length, [0], "AddAuth");
@@ -39,10 +54,10 @@ export class Token {
39
54
  }
40
55
  permission = __normalize(permission.trim());
41
56
  if (__requireBoolean(!__requireBoolean(this.hasAuth(permission)))) {
42
- if (__requireBoolean(__normalize(this.auth) === "")) {
43
- this.auth = permission;
57
+ if (__requireBoolean(__normalize(this.#auth) === "")) {
58
+ this.#auth = permission;
44
59
  } else {
45
- this.auth = `${__normalize(this.auth)}, ${permission}`;
60
+ this.#auth = `${__normalize(this.#auth)}, ${permission}`;
46
61
  }
47
62
  }
48
63
  return this;
@@ -50,14 +65,14 @@ export class Token {
50
65
  }
51
66
  clearAuth() {
52
67
  this.#writable();
53
- this.auth = "";
68
+ this.#auth = "";
54
69
  return this;
55
70
  return null;
56
71
  }
57
72
  hasAuth(permission) {
58
73
  __requireArity(arguments.length, [0], "hasAuth");
59
74
  permission = __boundary(permission);
60
- for (const name of __normalize(this.auth.split(","))) {
75
+ for (const name of __normalize(this.#auth.split(","))) {
61
76
  if (__requireBoolean(__normalize(name.trim()) === permission)) {
62
77
  return true;
63
78
  }
@@ -88,13 +103,23 @@ export class Token {
88
103
  }
89
104
  snapshot() {
90
105
  let claims = __fromJson(__toJson(__normalize(this.#claims)));
91
- if (__requireBoolean(__requireBoolean(__requireBoolean(__normalize(this.clientId) !== __normalize(claims.clientId)) || __requireBoolean(__normalize(this.expiresAt) !== __normalize(claims.exp))) || __requireBoolean(!__requireBoolean(__isString(__normalize(this.auth)))))) {
106
+ if (__requireBoolean(__requireBoolean(__requireBoolean(__normalize(this.#clientId) !== __normalize(claims.clientId)) || __requireBoolean(__normalize(this.#expiresAt) !== __normalize(claims.exp))) || __requireBoolean(!__requireBoolean(__isString(__normalize(this.#auth)))))) {
92
107
  throw "Token identity and expiry cannot be changed";
93
108
  }
94
- claims.auth = __normalize(this.auth);
109
+ claims.auth = __normalize(this.#auth);
95
110
  return claims;
96
111
  return null;
97
112
  }
113
+ renew() {
114
+ this.#writable();
115
+ this.#renew = true;
116
+ return this;
117
+ return null;
118
+ }
119
+ renewalRequested() {
120
+ return __normalize(this.#renew);
121
+ return null;
122
+ }
98
123
  #writable() {
99
124
  if (__requireBoolean(__normalize(this.#readonly))) {
100
125
  throw "Token is read-only during this event";
@@ -1 +1 @@
1
- {"version":3,"file":"token.mjs","sources":["token.lango"],"sourcesContent":["import \"./options\"\n contains(items, value)\nimport js global Object\n\nexport class Token(claims, readonly = false)\n properties\n clientId\n auth\n expiresAt\n methods\n AddAuth(permission)\n clearAuth()\n hasAuth(permission)\n get(name)\n set(name, value)\n snapshot()\n\nToken(claims, readonly = false)\n @claims = from_json(to_json(claims))\n @readonly = readonly\n @clientId = claims.clientId\n @auth = claims.auth\n @expiresAt = claims.exp\n\nToken:AddAuth(permission)\n writable()\n if !is_string(permission) or permission.trim() == \"\" or permission.includes(\",\")\n throw \"Permission must be a nonempty name without commas\"\n permission = permission.trim()\n if !hasAuth(permission)\n if @auth == \"\"\n @auth = permission\n else\n @auth = \"${@auth}, ${permission}\"\n return @this\n\nToken:clearAuth()\n writable()\n @auth = \"\"\n return @this\n\nToken:hasAuth(permission)\n for @auth.split(\",\") as name\n if name.trim() == permission\n return true\n return false\n\nToken:get(name)\n if !Object/hasOwn(@claims, name)\n return null\n return from_json(to_json(@claims[name]))\n\nToken:set(name, value)\n writable()\n if contains([\"clientId\", \"auth\", \"iat\", \"exp\", \"iss\", \"aud\", \"validatedAt\", \"nbf\", \"__proto__\", \"constructor\", \"prototype\"], name)\n throw \"Reserved token field: ${name}\"\n @claims[name] = from_json(to_json(value))\n return @this\n\nToken:snapshot()\n claims = from_json(to_json(@claims))\n if @clientId != claims.clientId or @expiresAt != claims.exp or !is_string(@auth)\n throw \"Token identity and expiry cannot be changed\"\n claims.auth = @auth\n return claims\n\nToken:writable()\n if @readonly\n throw \"Token is read-only during this event\"\n return null\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAIA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"token.mjs","sources":["token.lango"],"sourcesContent":["import \"./options\"\n contains(items, value)\nimport js global Object\n\nexport class Token(claims, readonly = false)\n properties\n clientId?\n auth?\n expiresAt?\n methods\n AddAuth(permission)\n clearAuth()\n hasAuth(permission)\n get(name)\n set(name, value)\n snapshot()\n renew()\n renewalRequested()\n\nToken(claims, readonly = false)\n @claims = from_json(to_json(claims))\n @readonly = readonly\n @renew = false\n @clientId = claims.clientId\n @auth = claims.auth\n @expiresAt = claims.exp\n Object/freeze(@this)\n\nToken:clientId?\n return @clientId\n\nToken:auth?\n return @auth\n\nToken:expiresAt?\n return @expiresAt\n\nToken:AddAuth(permission)\n writable()\n if !is_string(permission) or permission.trim() == \"\" or permission.includes(\",\")\n throw \"Permission must be a nonempty name without commas\"\n permission = permission.trim()\n if !hasAuth(permission)\n if @auth == \"\"\n @auth = permission\n else\n @auth = \"${@auth}, ${permission}\"\n return @this\n\nToken:clearAuth()\n writable()\n @auth = \"\"\n return @this\n\nToken:hasAuth(permission)\n for @auth.split(\",\") as name\n if name.trim() == permission\n return true\n return false\n\nToken:get(name)\n if !Object/hasOwn(@claims, name)\n return null\n return from_json(to_json(@claims[name]))\n\nToken:set(name, value)\n writable()\n if contains([\"clientId\", \"auth\", \"iat\", \"exp\", \"iss\", \"aud\", \"validatedAt\", \"nbf\", \"__proto__\", \"constructor\", \"prototype\"], name)\n throw \"Reserved token field: ${name}\"\n @claims[name] = from_json(to_json(value))\n return @this\n\nToken:snapshot()\n claims = from_json(to_json(@claims))\n if @clientId != claims.clientId or @expiresAt != claims.exp or !is_string(@auth)\n throw \"Token identity and expiry cannot be changed\"\n claims.auth = @auth\n return claims\n\nToken:renew()\n writable()\n @renew = true\n return @this\n\nToken:renewalRequested()\n return @renew\n\nToken:writable()\n if @readonly\n throw \"Token is read-only during this event\"\n return null\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAIA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
package/dist/tokens.mjs CHANGED
@@ -2,6 +2,8 @@ import * as jwt from "jsonwebtoken";
2
2
  import * as crypto from "node:crypto";
3
3
  import {
4
4
  hostGlobal as __hostGlobal,
5
+ fromJson as __fromJson,
6
+ toJson as __toJson,
5
7
  isNumber as __isNumber,
6
8
  isString as __isString,
7
9
  isBool as __isBool,
@@ -55,12 +57,25 @@ export class Tokens {
55
57
  if (__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(!__requireBoolean(__normalize(__hostGlobal(["Number"]).isSafeInteger(__normalize(claims.iat))))) || __requireBoolean(!__requireBoolean(__normalize(__hostGlobal(["Number"]).isSafeInteger(__normalize(claims.exp)))))) || __requireBoolean(__normalize(claims.exp) <= __normalize(claims.iat))) || __requireBoolean(__finite(__normalize(claims.exp) - __normalize(claims.iat)) > __normalize(settings.ttlSeconds))) || __requireBoolean(__finite(__normalize(claims.iat) * 1000) > __normalize(__hostGlobal(["Date"]).now())))) {
56
58
  throw "InvalidToken";
57
59
  }
58
- if (__requireBoolean(__requireBoolean(__requireBoolean(!__requireBoolean(__normalize(__hostGlobal(["Number"]).isSafeInteger(__normalize(claims.validatedAt))))) || __requireBoolean(__normalize(claims.validatedAt) < __finite(__normalize(claims.iat) * 1000))) || __requireBoolean(__normalize(claims.validatedAt) > __normalize(__hostGlobal(["Date"]).now())))) {
60
+ if (__requireBoolean(__requireBoolean(__requireBoolean(!__requireBoolean(__normalize(__hostGlobal(["Number"]).isSafeInteger(__normalize(claims.validatedAt))))) || __requireBoolean(__normalize(claims.validatedAt) < 0)) || __requireBoolean(__normalize(claims.validatedAt) > __normalize(__hostGlobal(["Date"]).now())))) {
59
61
  throw "InvalidToken";
60
62
  }
61
63
  return claims;
62
64
  return null;
63
65
  }
66
+ renew(claims) {
67
+ __requireArity(arguments.length, [0], "renew");
68
+ claims = __boundary(claims);
69
+ if (__requireBoolean(__finite(__normalize(claims.exp) * 1000) <= __normalize(__hostGlobal(["Date"]).now()))) {
70
+ throw "TokenExpired";
71
+ }
72
+ let updated = __fromJson(__toJson(claims));
73
+ let now = __normalize(__hostGlobal(["Math"]).floor(__finite(__normalize(__hostGlobal(["Date"]).now()) / 1000)));
74
+ updated.iat = now;
75
+ updated.exp = __numericAdd(now, __normalize(this.#settings.ttlSeconds));
76
+ return updated;
77
+ return null;
78
+ }
64
79
  sign(claims) {
65
80
  __requireArity(arguments.length, [0], "sign");
66
81
  claims = __boundary(claims);
@@ -1 +1 @@
1
- {"version":3,"file":"tokens.mjs","sources":["tokens.lango"],"sourcesContent":["import js \"jsonwebtoken\" as jwt\nimport js \"node:crypto\" as crypto\nimport js global Object\nimport js global Date\nimport js global Math\nimport js global Number\n\nexport class Tokens(settings)\n methods\n read(header)\n sign(claims)\n create()\n\nTokens(settings)\n @settings = settings\n\nTokens:create()\n settings = @settings\n now = Math/floor(Date/now() / 1000)\n return {\n clientId: crypto/randomUUID()\n auth: \"\"\n iat: now\n exp: now + settings.ttlSeconds\n iss: settings.issuer\n aud: settings.audience\n validatedAt: Date/now()\n }\n\nTokens:read(header)\n settings = @settings\n if !is_string(header) or header.length > 16384 or header.slice(0, 7).toLowerCase() != \"bearer \" or header.length == 7\n throw \"InvalidToken\"\n encoded = header.slice(7)\n decoded = jwt/default/decode(encoded, {\n complete: true\n })\n if !is_object(decoded) or !is_object(decoded.header)\n throw \"InvalidToken\"\n head = decoded.header\n if head.alg != \"HS256\" or head.typ != \"JWT\" or !is_string(head.kid) or head.crit != null or head.b64 != null\n throw \"InvalidToken\"\n keys = settings.keys\n if !Object/hasOwn(keys, head.kid)\n throw \"InvalidToken\"\n claims = jwt/default/verify(encoded, keys[head.kid], {\n algorithms: [\"HS256\"]\n issuer: settings.issuer\n audience: settings.audience\n })\n if !is_object(claims) or !is_string(claims.clientId) or claims.clientId == \"\" or !is_string(claims.auth)\n throw \"InvalidToken\"\n if !Number/isSafeInteger(claims.iat) or !Number/isSafeInteger(claims.exp) or claims.exp <= claims.iat or claims.exp - claims.iat > settings.ttlSeconds or claims.iat * 1000 > Date/now()\n throw \"InvalidToken\"\n if !Number/isSafeInteger(claims.validatedAt) or claims.validatedAt < claims.iat * 1000 or claims.validatedAt > Date/now()\n throw \"InvalidToken\"\n return claims\n\nTokens:sign(claims)\n settings = @settings\n if claims.exp * 1000 <= Date/now()\n throw \"TokenExpired\"\n keys = settings.keys\n return jwt/default/sign(claims, keys[settings.activeKeyId], {\n algorithm: \"HS256\"\n header: {\n typ: \"JWT\"\n kid: settings.activeKeyId\n }\n })\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAOA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"tokens.mjs","sources":["tokens.lango"],"sourcesContent":["import js \"jsonwebtoken\" as jwt\nimport js \"node:crypto\" as crypto\nimport js global Object\nimport js global Date\nimport js global Math\nimport js global Number\n\nexport class Tokens(settings)\n methods\n read(header)\n sign(claims)\n create()\n renew(claims)\n\nTokens(settings)\n @settings = settings\n\nTokens:create()\n settings = @settings\n now = Math/floor(Date/now() / 1000)\n return {\n clientId: crypto/randomUUID()\n auth: \"\"\n iat: now\n exp: now + settings.ttlSeconds\n iss: settings.issuer\n aud: settings.audience\n validatedAt: Date/now()\n }\n\nTokens:read(header)\n settings = @settings\n if !is_string(header) or header.length > 16384 or header.slice(0, 7).toLowerCase() != \"bearer \" or header.length == 7\n throw \"InvalidToken\"\n encoded = header.slice(7)\n decoded = jwt/default/decode(encoded, {\n complete: true\n })\n if !is_object(decoded) or !is_object(decoded.header)\n throw \"InvalidToken\"\n head = decoded.header\n if head.alg != \"HS256\" or head.typ != \"JWT\" or !is_string(head.kid) or head.crit != null or head.b64 != null\n throw \"InvalidToken\"\n keys = settings.keys\n if !Object/hasOwn(keys, head.kid)\n throw \"InvalidToken\"\n claims = jwt/default/verify(encoded, keys[head.kid], {\n algorithms: [\"HS256\"]\n issuer: settings.issuer\n audience: settings.audience\n })\n if !is_object(claims) or !is_string(claims.clientId) or claims.clientId == \"\" or !is_string(claims.auth)\n throw \"InvalidToken\"\n if !Number/isSafeInteger(claims.iat) or !Number/isSafeInteger(claims.exp) or claims.exp <= claims.iat or claims.exp - claims.iat > settings.ttlSeconds or claims.iat * 1000 > Date/now()\n throw \"InvalidToken\"\n if !Number/isSafeInteger(claims.validatedAt) or claims.validatedAt < 0 or claims.validatedAt > Date/now()\n throw \"InvalidToken\"\n return claims\n\nTokens:renew(claims)\n if claims.exp * 1000 <= Date/now()\n throw \"TokenExpired\"\n updated = from_json(to_json(claims))\n now = Math/floor(Date/now() / 1000)\n updated.iat = now\n updated.exp = now + @settings.ttlSeconds\n return updated\n\nTokens:sign(claims)\n settings = @settings\n if claims.exp * 1000 <= Date/now()\n throw \"TokenExpired\"\n keys = settings.keys\n return jwt/default/sign(claims, keys[settings.activeKeyId], {\n algorithm: \"HS256\"\n header: {\n typ: \"JWT\"\n kid: settings.activeKeyId\n }\n })\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AAOA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lango-project/lango-server",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "A small JSON HTTP server for Lango applications.",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
@@ -26,7 +26,7 @@
26
26
  ],
27
27
  "scripts": {
28
28
  "build": "lango run tools/clean.lango && lango build src/library.lango --out dist/library.mjs && lango build src/server.lango --out dist/cli/server.mjs --executable && lango build src/worker.lango --out dist/worker.mjs && lango build examples/application/handlers.lango --out examples/application/dist/handlers.mjs && lango build src/postgres_worker.lango --out dist/postgres_worker.mjs && lango build examples/database/handlers.lango --out examples/database/dist/handlers.mjs",
29
- "test": "npm run build && lango build src/test/handlers.lango --out .test-output/handlers.mjs && lango build src/test/sql_handlers.lango --out .test-output/sql_handlers.mjs && lango build src/test/middleware_handlers.lango --out .test-output/middleware_handlers.mjs && lango test src/test/database.lango --build-dir .test-output/database && lango test src/test/unit.lango --build-dir .test-output/unit && lango test src/test/http.lango --build-dir .test-output/http && lango test src/test/middleware.lango --build-dir .test-output/middleware && lango test src/test/static.lango --build-dir .test-output/static && lango test src/test/standalone.lango --build-dir .test-output/standalone",
29
+ "test": "npm run build && lango build src/test/handlers.lango --out .test-output/handlers.mjs && lango build src/test/sql_handlers.lango --out .test-output/sql_handlers.mjs && lango build src/test/middleware_handlers.lango --out .test-output/middleware_handlers.mjs && lango test src/test/database.lango --build-dir .test-output/database && lango test src/test/unit.lango --build-dir .test-output/unit && lango test src/test/route_parameters.lango --build-dir .test-output/route-parameters && lango test src/test/http.lango --build-dir .test-output/http && lango test src/test/middleware.lango --build-dir .test-output/middleware && lango test src/test/static.lango --build-dir .test-output/static && lango test src/test/standalone.lango --build-dir .test-output/standalone",
30
30
  "start": "node dist/cli/server.mjs examples/application",
31
31
  "prepack": "npm run build",
32
32
  "test:postgres": "lango build src/test/sql_handlers.lango --out .test-output/sql_handlers.mjs && lango test src/test/database.lango --build-dir .test-output/database-postgres",
@@ -41,6 +41,6 @@
41
41
  "serve-static": "^2.2.1"
42
42
  },
43
43
  "devDependencies": {
44
- "@lango-project/lango-js": "^0.1.13"
44
+ "@lango-project/lango-js": "^0.1.16"
45
45
  }
46
46
  }
@@ -1,3 +1,5 @@
1
+ import "./route_pattern"
2
+ routePattern(path)
1
3
  import "./middleware"
2
4
  middlewareName(name)
3
5
 
@@ -10,10 +12,7 @@ export class Endpoint(spec)
10
12
  middleware
11
13
 
12
14
  Endpoint(spec)
13
- if !is_string(spec.path) or !spec.path.startsWith("/") or spec.path.includes("?") or spec.path.includes("#") or spec.path.includes("\\") or spec.path.includes("//")
14
- throw "Endpoint requires an absolute URL path"
15
- if spec.path.includes("*") and (!spec.path.endsWith("/*") or spec.path.indexOf("*") != spec.path.lastIndexOf("*"))
16
- throw "Only trailing /* wildcards are supported"
15
+ routePattern(spec.path)
17
16
  for ["module", "handler"] as key
18
17
  if !is_string(spec[key]) or spec[key] == ""
19
18
  throw "Endpoint requires ${key}"
@@ -0,0 +1,26 @@
1
+ import js global RegExp
2
+
3
+ export class HttpFailure(status, code, headers)
4
+ methods
5
+ result()
6
+
7
+ HttpFailure(status, code, headers)
8
+ if !is_number(status) or status % 1 != 0 or status < 400 or status > 599
9
+ throw "Rejected response requires an error status"
10
+ pattern = new RegExp("^[A-Za-z][A-Za-z0-9_]{0,63}$")
11
+ if !is_string(code) or !pattern.test(code)
12
+ throw "Rejected response requires an error code"
13
+ @status = status
14
+ @code = code
15
+ @headers = from_json(to_json(headers))
16
+ if status == 401
17
+ @headers["www-authenticate"] = "Bearer"
18
+
19
+ HttpFailure:result()
20
+ return {
21
+ status: @status
22
+ headers: from_json(to_json(@headers))
23
+ body: to_json({
24
+ error: @code
25
+ })
26
+ }
@@ -42,7 +42,7 @@ longpollOptions(spec)
42
42
  return result
43
43
 
44
44
  validPath(value)
45
- if !is_string(value) or !value.startsWith("/") or value.includes("*") or value.includes("?") or value.includes("#") or value.includes("\\") or value.includes("//")
45
+ if !is_string(value) or !value.startsWith("/") or value.includes("*") or value.includes("{") or value.includes("}") or value.includes("?") or value.includes("#") or value.includes("\\") or value.includes("//")
46
46
  throw "Longpoll requires an exact absolute URL path"
47
47
  return null
48
48
 
package/src/options.lango CHANGED
@@ -28,7 +28,7 @@ options(root, supplied = null)
28
28
  port: 3000
29
29
  workers: 2
30
30
  maxQueue: 64
31
- bodyLimit: 1048576
31
+ bodyLimit: 2097152
32
32
  bodyTimeoutMs: 30000
33
33
  requestTimeoutMs: 30000
34
34
  eventTimeoutMs: 5000
@@ -99,7 +99,7 @@ deployment(directory)
99
99
  seen.add(name)
100
100
  switch name
101
101
  case "static"
102
- attributes(tag, ["path", "directory", "index"])
102
+ attributes(tag, ["path", "directory", "index", "fallback", "runtime"])
103
103
  settings.static = tag.attributes()
104
104
  continue
105
105
  case "http"
@@ -2,11 +2,14 @@ import js "node:http" as http
2
2
 
3
3
  import "./options"
4
4
  contains(items, value)
5
+ import "./http_failure"
6
+ class HttpFailure
5
7
  export class Response()
6
8
  methods
7
9
  status(code)
8
10
  header(name, value)
9
11
  result(body)
12
+ reject(status, code)
10
13
 
11
14
  Response()
12
15
  @status = 200
@@ -40,3 +43,6 @@ Response:result(body)
40
43
  headers: from_json(to_json(@headers))
41
44
  body: body
42
45
  }
46
+
47
+ Response:reject(status, code)
48
+ throw new HttpFailure(status, code, @headers)
@@ -0,0 +1,15 @@
1
+ export routeInfo(definitions)
2
+
3
+ routeInfo(definitions)
4
+ result = []
5
+ for definitions as route
6
+ kind = route.kind
7
+ if kind == null
8
+ kind = "endpoint"
9
+ result.add({
10
+ path: route.path
11
+ kind: kind
12
+ auth: route.auth
13
+ middleware: route.middleware
14
+ })
15
+ return result
@@ -0,0 +1,86 @@
1
+ import js global RegExp
2
+
3
+ export routePattern(path)
4
+ export matchPath(pattern, path)
5
+ export moreSpecific(candidate, current)
6
+
7
+ routePattern(path)
8
+ if !is_string(path) or !path.startsWith("/") or path.includes("?") or path.includes("#") or path.includes("\\") or path.includes("//")
9
+ throw "Endpoint requires an absolute URL path"
10
+ if path.includes("*") and (!path.endsWith("/*") or path.indexOf("*") != path.lastIndexOf("*"))
11
+ throw "Only trailing /* wildcards are supported"
12
+ segments = path.split("/")
13
+ segments = segments.slice(1)
14
+ wildcard = path.endsWith("/*")
15
+ if wildcard
16
+ segments.pop()
17
+ names = []
18
+ shape = []
19
+ identifier = new RegExp("^[A-Za-z_][A-Za-z0-9_]*$")
20
+ reserved = ["__proto__", "constructor", "prototype"]
21
+ for segments as segment
22
+ if segment.includes("{") or segment.includes("}")
23
+ if !segment.startsWith("{") or !segment.endsWith("}")
24
+ throw "Path parameters must occupy an entire segment"
25
+ name = segment.slice(1, -1)
26
+ if !identifier.test(name) or reserved.includes(name)
27
+ throw "Invalid path parameter name: ${name}"
28
+ if names.includes(name)
29
+ throw "Duplicate path parameter: ${name}"
30
+ names.add(name)
31
+ shape.add("{}")
32
+ else
33
+ shape.add(segment)
34
+ if wildcard
35
+ shape.add("*")
36
+ key = shape.join("/")
37
+ key = "/${key}"
38
+ return {
39
+ segments: segments
40
+ wildcard: wildcard
41
+ key: key
42
+ }
43
+
44
+ matchPath(pattern, path)
45
+ parts = path.split("/")
46
+ if parts[0] != ""
47
+ return null
48
+ parts = parts.slice(1)
49
+ count = pattern.segments.length
50
+ if pattern.wildcard
51
+ if parts.length <= count
52
+ return null
53
+ else
54
+ if parts.length != count
55
+ return null
56
+ parameters = {}
57
+ for pattern.segments as index: segment
58
+ value = parts[index]
59
+ if segment.startsWith("{")
60
+ if value == ""
61
+ return null
62
+ name = segment.slice(1, -1)
63
+ parameters[name] = value
64
+ else
65
+ if segment != value
66
+ return null
67
+ return parameters
68
+
69
+ moreSpecific(candidate, current)
70
+ if current == null
71
+ return true
72
+ if candidate.wildcard != current.wildcard
73
+ return !candidate.wildcard
74
+ first = candidate.segments
75
+ second = current.segments
76
+ count = first.length
77
+ if second.length < count
78
+ count = second.length
79
+ for range(count) as index
80
+ segment = first[index]
81
+ alternative = second[index]
82
+ literal = !segment.startsWith("{")
83
+ other = !alternative.startsWith("{")
84
+ if literal != other
85
+ return literal
86
+ return first.length > second.length
package/src/routes.lango CHANGED
@@ -1,3 +1,5 @@
1
+ import "./route_pattern"
2
+ routePattern(path)
1
3
  import "./options"
2
4
  contains(items, value)
3
5
  import js "node:fs" as fs
@@ -34,9 +36,7 @@ Routes(root)
34
36
 
35
37
  Routes:endpoint(spec)
36
38
  item = new Endpoint(spec)
37
- for @items as other
38
- if other.path == item.path
39
- throw "Duplicate endpoint: ${item.path}"
39
+ checkPath(item.path)
40
40
  @items.add({
41
41
  path: item.path
42
42
  module: resolveModule(item.module, @root)
@@ -46,6 +46,16 @@ Routes:endpoint(spec)
46
46
  })
47
47
  return @this
48
48
 
49
+ Routes:checkPath(path)
50
+ pattern = routePattern(path)
51
+ for @items as other
52
+ if other.path == path
53
+ throw "Duplicate endpoint: ${path}"
54
+ existing = routePattern(other.path)
55
+ if existing.key == pattern.key
56
+ throw "Conflicting endpoint pattern: ${path}"
57
+ return null
58
+
49
59
  Routes:addMiddleware(name, spec)
50
60
  middlewareName(name)
51
61
  if Object/hasOwn(@middlewares, name)
@@ -53,13 +63,16 @@ Routes:addMiddleware(name, spec)
53
63
  if !is_object(spec) or is_array(spec)
54
64
  throw "Middleware requires a module and exported handler"
55
65
  for spec as key: value
56
- if key != "module" and key != "handler"
66
+ if key != "module" and key != "handler" and key != "validate"
57
67
  throw "Unknown middleware option: ${key}"
58
68
  if !is_string(spec.handler) or spec.handler == ""
59
69
  throw "Middleware handler is required"
70
+ if spec.validate != null and (!is_string(spec.validate) or spec.validate == "")
71
+ throw "Middleware validate must name an exported function"
60
72
  @middlewares[name] = {
61
73
  module: resolveModule(spec.module, @root)
62
74
  handler: spec.handler
75
+ validate: spec.validate
63
76
  }
64
77
  return @this
65
78
 
@@ -68,9 +81,7 @@ Routes:middlewares()
68
81
 
69
82
  Routes:longpoll(spec)
70
83
  item = longpollOptions(spec)
71
- for @items as other
72
- if other.path == item.path
73
- throw "Duplicate endpoint: ${item.path}"
84
+ checkPath(item.path)
74
85
  @items.add(item)
75
86
  return @this
76
87
 
@@ -188,13 +199,14 @@ Routes:collect(parent, prefix, inheritedModule, inheritedAuth, directory, stack,
188
199
  leaf(tag)
189
200
  includeAt(spec, directory, prefix, stack, auth)
190
201
  case "middleware"
191
- attributes(tag, ["name", "module", "handler"])
202
+ attributes(tag, ["name", "module", "handler", "validate"])
192
203
  leaf(tag)
193
204
  if !allowEvents
194
205
  throw "Middleware declarations are only allowed in the application's root routes.xml"
195
206
  addMiddleware(spec.name, {
196
207
  module: resolveModule(spec.module, directory)
197
208
  handler: spec.handler
209
+ validate: spec.validate
198
210
  })
199
211
  case "event"
200
212
  attributes(tag, ["name", "module", "handler"])