@lango-project/lango-server 0.1.2 → 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
@@ -58,7 +58,7 @@ greet(input)
58
58
  log.info("Greeting requested")
59
59
  return {
60
60
  message: "Hello, ${input.name}"
61
- clientId: token.clientId
61
+ clientId: token.clientId?
62
62
  }
63
63
  ```
64
64
 
@@ -107,8 +107,29 @@ exist when the server starts. Only one static root is supported.
107
107
  GET and HEAD stream files in the main thread without reserving a worker or
108
108
  creating a token. HTML is served unchanged. File responses support conditional
109
109
  requests and byte ranges through `serve-static`. Query strings are allowed for
110
- static assets. Missing files and directories without an index return 404;
111
- directory listings and SPA fallbacks are not enabled. Dotfiles are denied.
110
+ static assets. By default, missing files and directories without an index return
111
+ 404; directory listings are disabled and dotfiles are denied.
112
+
113
+ For a Lango browser application, explicitly enable its compiler runtime and
114
+ HTML page fallback:
115
+
116
+ ```xml
117
+ <static directory=".lango/public" fallback="index.html" runtime="true"/>
118
+ ```
119
+
120
+ The equivalent Builder settings are `fallback: "index.html"` and `runtime: true`
121
+ inside `static`. Both are off by default. The fallback file must exist at startup.
122
+ Only missing extensionless GET/HEAD paths that explicitly accept HTML receive
123
+ this unchanged shell. Asset paths such as `/missing.js`, JSON requests and HTML
124
+ with `q=0` keep their error responses. An existing file still uses ordinary
125
+ range/conditional handling. Dotted page paths do not use this fallback.
126
+
127
+ `runtime` permits the public `.lango` compiler-runtime subtree at the static
128
+ root, which generated browser modules import. Other dotfiles, nested hidden
129
+ segments, traversal, invalid escapes, backslashes and NUL paths are rejected.
130
+ Put only public runtime assets there; signing keys remain outside the static
131
+ root. The application generator uses `.lango/public` for assets and the separate
132
+ `.lango/keys.json` for its local signing key.
112
133
 
113
134
  POST requests retain the normal JSON worker pipeline, including at `/`. Static
114
135
  serving alone does not reserve that POST path or install UI lifecycle handlers.
@@ -352,7 +373,7 @@ request/event deadlines and SQL transaction cleanup still apply.
352
373
 
353
374
  ```xml
354
375
  <deploy>
355
- <http host="127.0.0.1" port="3000" bodyLimit="1048576" bodyTimeoutMs="30000"/>
376
+ <http host="127.0.0.1" port="3000" bodyLimit="2097152" bodyTimeoutMs="30000"/>
356
377
  <workers workers="2" maxQueue="64" requestTimeoutMs="30000"
357
378
  startupTimeoutMs="30000" shutdownTimeoutMs="30000"/>
358
379
  <events requestEvent="false" eventTimeoutMs="5000"/>
@@ -363,8 +384,10 @@ request/event deadlines and SQL transaction cleanup still apply.
363
384
  These are also the default values, apart from the required signing key and the
364
385
  example issuer/audience (defaults: `lango-server` / `lango-client`). Builder uses
365
386
  these attribute names directly in `configure`. Unknown options are errors.
366
- `bodyLimit` is bytes; timeouts are milliseconds. Workers range from 1 to 128;
367
- `maxQueue: 0` disables waiting. JWT lifetime is 1 to 86400 seconds.
387
+ `bodyLimit` is bytes and defaults to 2 MiB (2097152 bytes), allowing a 1 MiB
388
+ binary file encoded as base64 within a JSON form. Larger combined form payloads
389
+ require an explicit higher limit. Timeouts are milliseconds. Workers range from
390
+ 1 to 128; `maxQueue: 0` disables waiting. JWT lifetime is 1 to 86400 seconds.
368
391
 
369
392
  For rotation, use `keysFile` instead of `keyEnv`, and select `activeKeyId`:
370
393
 
@@ -399,12 +422,15 @@ Unauthorized requests do not receive a newly created token.
399
422
 
400
423
  `context token` supports:
401
424
 
402
- * `clientId`, `auth`, `expiresAt`: identity, comma-separated permissions, expiry.
425
+ * `clientId?`, `auth?`, `expiresAt?`: getter-only identity, comma-separated
426
+ permissions and expiry. Direct assignment is rejected, including JavaScript
427
+ attempts to shadow these properties. Use the controlled methods below to update
428
+ claims or permissions.
403
429
  * `AddAuth("login")`, `clearAuth()`, `hasAuth("admin")`: exact trimmed membership.
404
430
  * `get(name)`, `set(name, value)`: JSON custom claims; server-owned JWT fields are
405
431
  protected. `get` returns a copy for structured values.
406
432
  * `renew()`: requests renewal after successful serialization and SQL cleanup on
407
- a reply with a status below 400. It does not immediately change `expiresAt`.
433
+ a reply with a status below 400. It does not immediately change `expiresAt?`.
408
434
 
409
435
  Default endpoint auth is `login`. `auth="anonymous"` permits anonymous callers;
410
436
  other values require that exact permission. `admin` does not imply `login`.
@@ -412,7 +438,7 @@ The application authenticates credentials and grants permissions. These methods
412
438
  do not authenticate anyone automatically.
413
439
 
414
440
  Token updates are committed only after the handler and JSON serialization
415
- succeed. Validation updates preserve the original token expiry. `clearAuth()`
441
+ succeed. Successful validation also requests expiry renewal. `clearAuth()`
416
442
  updates the returned token; it does not invalidate previously issued copies.
417
443
  Use application-owned storage and Validate to enforce logout/revocation across
418
444
  old tokens. There is no built-in session database or UI replay protocol.
@@ -442,9 +468,10 @@ Promise results are supported, and events run under the request's contexts.
442
468
  token. Only `true` continues; `false` produces 401. Exceptions, invalid return
443
469
  types, mutation, or timeouts fail the request without running the handler;
444
470
  operational failures are not reported as invalid credentials. Successful
445
- validation updates the server-owned timestamp in the next successful reply.
446
- Recent-token use does not advance it. If no event is configured, standard JWT
447
- verification is sufficient. Revocation checks have a one-second freshness
471
+ validation updates the server-owned timestamp and renews expiry in the next
472
+ successful reply. Recent-token use does not advance the timestamp or implicitly
473
+ renew expiry. If no event is configured, standard JWT verification supplies
474
+ the successful validation result at the same freshness boundary. Revocation checks have a one-second freshness
448
475
  allowance and depend on the application's storage consistency.
449
476
  * **request(metadata)** is enabled only by `requestEvent: true`. It runs after
450
477
  the handler completes and JSON serialization succeeds, before the reply is
@@ -788,3 +815,28 @@ LANGO_TEST_REDIS=redis://127.0.0.1:6379 npm run test:longpoll
788
815
  The suite briefly pauses Redis commands to test infrastructure timeouts. Do not
789
816
  point it at a shared or production Redis instance. CI runs this suite separately
790
817
  from `npm test`, alongside the PostgreSQL integration suite.
818
+
819
+ ## Framework token refresh batches
820
+
821
+ `context server.refreshTokens(tokens)` supports middleware that refreshes several
822
+ form tokens in one HTTP request. It accepts 1–64 distinct nonempty token strings
823
+ (up to 16,384 characters each). Structural validation completes before any item
824
+ runs. The current authenticated token supplies the batch client identity.
825
+
826
+ Each item must pass normal JWT verification and belong to that same `clientId`.
827
+ The server dispatches the **current route** again with an empty input map and
828
+ that item's Bearer token, using separate token, response and database scopes.
829
+ This is used by Lango UI Ping; its ordinary empty-body path invokes the hook and
830
+ requests renewal. Do not use this helper from a handler that recursively batches
831
+ empty requests.
832
+
833
+ The result is an array of `{ previous, token, status }`. Invalid, expired or
834
+ foreign-client tokens produce an individual 401 and no replacement token.
835
+ Handler/SQL failures retain their normal status and do not publish that item's
836
+ claim changes. Items execute sequentially under the physical request's overall
837
+ deadline and normal event deadlines. An interrupted physical request publishes
838
+ no completed batch response; already completed item transactions are not undone.
839
+ There is no automatic retry.
840
+
841
+ Request auditing runs once for the physical batch response, not once per internal
842
+ item; an internal result cannot replace the prepared outer HTTP reply.
@@ -0,0 +1,108 @@
1
+ import i18next from "./vendor/i18next.mjs";
2
+
3
+ function record(value, label) {
4
+ if (value === null || typeof value !== "object" || Array.isArray(value))
5
+ throw new TypeError(`${label} must be a map`);
6
+ return value;
7
+ }
8
+
9
+ function language(value) {
10
+ if (typeof value !== "string" || value === "") throw new TypeError("locale must be a language tag");
11
+ return Intl.getCanonicalLocales(value)[0];
12
+ }
13
+
14
+ function numeric(value) {
15
+ // Decimal instances from independently generated runtimes share this backend marker.
16
+ if (value?._isBigNumber === true && typeof value.toFixed === "function") {
17
+ if (!value.isFinite()) throw new TypeError("formatNumber requires a finite value");
18
+ return value.toFixed();
19
+ }
20
+ if (typeof value === "bigint") return value;
21
+ if (typeof value !== "number" || !Number.isFinite(value))
22
+ throw new TypeError("formatNumber requires a finite number or Decimal");
23
+ return value;
24
+ }
25
+
26
+ function dateValue(value) {
27
+ if (typeof value === "string") {
28
+ const parts = /^(\d{4})-(\d{2})-(\d{2})(?:T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:\d{2}))?$/.exec(value);
29
+ if (!parts) throw new TypeError("formatDate requires an ISO date or an instant with a time-zone offset");
30
+ const calendar = new Date(0);
31
+ calendar.setUTCFullYear(Number(parts[1]), Number(parts[2]) - 1, Number(parts[3]));
32
+ if (calendar.getUTCMonth() !== Number(parts[2]) - 1 || calendar.getUTCDate() !== Number(parts[3]))
33
+ throw new TypeError("formatDate requires a valid date");
34
+ }
35
+ if (!(value instanceof Date) && typeof value !== "string" && typeof value !== "number")
36
+ throw new TypeError("formatDate requires a Date, ISO string or epoch milliseconds");
37
+ const date = new Date(value);
38
+ if (!Number.isFinite(date.getTime())) throw new TypeError("formatDate requires a valid date");
39
+ return date;
40
+ }
41
+
42
+ /** Create an immutable, synchronous translator; catalogs are application-owned data. */
43
+ export function createI18n(options = {}) {
44
+ record(options, "i18n options");
45
+ const locale = language(options.locale ?? "en");
46
+ const fallbackLocale = language(options.fallbackLocale ?? "en");
47
+ const timeZone = new Intl.DateTimeFormat("en", { timeZone: options.timeZone ?? "UTC" }).resolvedOptions().timeZone;
48
+ const currency = options.currency == null ? null : options.currency;
49
+ if (currency !== null) new Intl.NumberFormat("en", { style: "currency", currency });
50
+ const resources = Object.create(null);
51
+ const catalogs = { ...record(options.catalogs ?? {}, "catalogs") };
52
+ if (options.catalog != null) catalogs[locale] = { ...catalogs[locale], ...record(options.catalog, "catalog") };
53
+ for (const [tag, catalog] of Object.entries(catalogs)) {
54
+ const messages = record(catalog, "translation catalog");
55
+ if (Object.values(messages).some(value => typeof value !== "string"))
56
+ throw new TypeError("translation catalog entries must be strings");
57
+ resources[language(tag)] = { translation: { ...messages } };
58
+ }
59
+ const engine = i18next.createInstance();
60
+ // All resources are in memory: no async backend, network lookup, or global language mutation.
61
+ engine.init({
62
+ lng: locale, fallbackLng: fallbackLocale, resources, initAsync: false,
63
+ keySeparator: false, nsSeparator: false, returnNull: false,
64
+ interpolation: { escapeValue: false },
65
+ });
66
+ const fixed = engine.getFixedT(locale);
67
+ const formatNumber = (value, options = null) => {
68
+ const settings = { ...record(options ?? {}, "number format options") };
69
+ if (settings.style === "currency" && settings.currency == null && currency !== null)
70
+ settings.currency = currency;
71
+ return new Intl.NumberFormat(locale, settings).format(numeric(value));
72
+ };
73
+ const formatDate = (value, options = null) => {
74
+ const settings = { timeZone, ...record(options ?? {}, "date format options") };
75
+ return new Intl.DateTimeFormat(locale, settings).format(dateValue(value));
76
+ };
77
+ const translate = (template, values = [], options = null) => {
78
+ if (typeof template !== "string" || !Array.isArray(values))
79
+ throw new TypeError("translation requires a template and a values array");
80
+ const settings = record(options ?? {}, "translation options");
81
+ if (settings.count != null && (typeof settings.count !== "number" || !Number.isFinite(settings.count)))
82
+ throw new TypeError("translation count must be a finite number");
83
+ if (settings.context != null && typeof settings.context !== "string")
84
+ throw new TypeError("translation context must be a string");
85
+ const params = record(settings.formatParams ?? {}, "formatParams");
86
+ const message = fixed(template, {
87
+ defaultValue: template, skipInterpolation: true,
88
+ ...(settings.count == null ? {} : { count: settings.count }),
89
+ ...(settings.context == null ? {} : { context: settings.context }),
90
+ });
91
+ // Render once: values are data and can never introduce further placeholders or code.
92
+ return message.replace(/{{|}}|{(\d+)(?:,\s*(number|currency|percent|date|datetime))?}/g, (token, index, format) => {
93
+ if (token === "{{") return "{";
94
+ if (token === "}}") return "}";
95
+ if (Number(index) >= values.length) throw new RangeError(`missing translation parameter {${index}}`);
96
+ const value = values[index];
97
+ const options = record(params[index] ?? {}, "parameter format options");
98
+ switch (format) {
99
+ case "number": return formatNumber(value, options);
100
+ case "currency": return formatNumber(value, { ...options, style: "currency" });
101
+ case "percent": return formatNumber(value, { ...options, style: "percent" });
102
+ case "date": case "datetime": return formatDate(value, options);
103
+ default: return String(value);
104
+ }
105
+ });
106
+ };
107
+ return Object.freeze({ locale, fallbackLocale, timeZone, currency, translate, formatNumber, formatDate });
108
+ }
@@ -1,4 +1,6 @@
1
1
  import BigNumber from "./bignumber.mjs";
2
+ import { createI18n } from "./localization.mjs";
3
+ export { createI18n };
2
4
  import { createRequire } from "node:module";
3
5
  const require = createRequire(import.meta.url);
4
6
  const { DOMParser } = require("./xmldom/index.js");
@@ -31,7 +33,7 @@ export function toJsNumber(value) {
31
33
  return new Decimal(value).toNumber();
32
34
  }
33
35
 
34
- let catalog = {};
36
+ let defaultI18n = null;
35
37
  let output = null;
36
38
  let database = null;
37
39
  const failureStore = Symbol.for("lango.databaseFailures");
@@ -121,7 +123,19 @@ export function configure(options = {}) {
121
123
  throw new RuntimeConfigurationError("runtime output must be a function or null");
122
124
  if (nextDatabase !== null && (typeof nextDatabase !== "object" && typeof nextDatabase !== "function"))
123
125
  throw new RuntimeConfigurationError("runtime database_adapter must be an object or null");
124
- catalog = nextCatalog;
126
+ let nextI18n;
127
+ try {
128
+ nextI18n = options.i18n ?? createI18n({
129
+ catalog: nextCatalog, catalogs: options.catalogs,
130
+ locale: options.locale, fallbackLocale: options.fallbackLocale,
131
+ timeZone: options.timeZone, currency: options.currency,
132
+ });
133
+ if (typeof nextI18n.translate !== "function" || typeof nextI18n.formatNumber !== "function" || typeof nextI18n.formatDate !== "function")
134
+ throw new TypeError("i18n requires translate, formatNumber and formatDate methods");
135
+ } catch (error) {
136
+ throw new RuntimeConfigurationError(error.message);
137
+ }
138
+ defaultI18n = nextI18n;
125
139
  output = nextOutput;
126
140
  if (database !== null) failedTransactions.delete(database);
127
141
  database = nextDatabase;
@@ -229,10 +243,14 @@ export function query(sql, parameterNames) {
229
243
  return proxy;
230
244
  }
231
245
 
232
- export function translate(template, values) {
233
- const translated = catalog[template] ?? template;
234
-
235
- return translated.replace(/\{(\d+)\}/g, (_, index) => String(values[index]));
246
+ export function translate(template, values, options = null) {
247
+ return contextGet("i18n").translate(template, values, options);
248
+ }
249
+ export function formatNumber(value, options = null) {
250
+ return contextGet("i18n").formatNumber(value, options);
251
+ }
252
+ export function formatDate(value, options = null) {
253
+ return contextGet("i18n").formatDate(value, options);
236
254
  }
237
255
 
238
256
  export function xmlEscape(value) {
@@ -660,6 +678,7 @@ export function withArity(callback, requiredPositions, name) {
660
678
  export function contextGet(name) {
661
679
  const stack = contexts.get(name);
662
680
  if ((!stack || stack.length === 0) && name === "log") return defaultLog;
681
+ if ((!stack || stack.length === 0) && name === "i18n") return defaultI18n ??= createI18n();
663
682
  if (!stack || stack.length === 0) {
664
683
  throw new Error(`Lango context is unavailable: ${name}`);
665
684
  }
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2011-present i18next
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.