@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/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.
@@ -137,10 +158,13 @@ JWT authorization applies to POST handlers; static files are public.
137
158
  launcher module. Absolute or relative file modules are also accepted for
138
159
  application-local code; relative modules in XML resolve from the containing
139
160
  package, and Builder modules resolve from its application root.
140
- * Groups concatenate path prefixes. Paths are case-sensitive. Exact paths win;
141
- otherwise the longest matching trailing `/*` prefix wins. `/orders/*` matches
142
- `/orders/save`, not `/orders`. Duplicate paths and unsupported wildcard forms
143
- are startup errors. The handler sees the actual path in `context request`.
161
+ * Groups concatenate path prefixes. Paths are case-sensitive. Literal endpoints
162
+ beat parameterized endpoints, which beat trailing `/*` wildcards. Among matching
163
+ patterns in the same category, the first differing literal segment beats a
164
+ parameter; otherwise longer wildcard prefixes win. `/orders/*` matches
165
+ `/orders/save`, not `/orders`. Duplicate paths, equivalent parameter patterns
166
+ and unsupported wildcard forms are startup errors. The handler and middleware
167
+ see the original actual path in `context request`.
144
168
  * Includes resolve the package's exported `./routes.xml`. Publish the XML file
145
169
  and add it to the package's `exports` and `files`. Nested includes resolve
146
170
  dependencies from the including package. Include prefixes concatenate; a
@@ -170,6 +194,51 @@ A feature package can expose its definitions as follows:
170
194
  Its XML still names the handler module explicitly, for example
171
195
  `<endpoint path="/list" module="@shop/catalog" handler="list"/>`.
172
196
 
197
+ ### Path parameters
198
+
199
+ An endpoint can capture complete path segments with `{name}`:
200
+
201
+ ```lango
202
+ builder.endpoint({
203
+ path: "/user/{userId}"
204
+ module: "@shop/users"
205
+ handler: "read"
206
+ auth: "login"
207
+ })
208
+ ```
209
+
210
+ ```xml
211
+ <endpoint path="/user/{userId}" module="@shop/users" handler="read"/>
212
+ ```
213
+
214
+ A POST to `/user/007` with body `{ "name": "Ada", "userId": "body-value" }`
215
+ passes `{ name: "Ada", userId: "007" }` to the handler. URL parameters overwrite
216
+ same-named body fields and are available before Register, middleware and handler
217
+ execution. The JSON body must still be an object. Validate retains its existing
218
+ input contract; parameters are not added to request headers or route metadata.
219
+
220
+ Values are strings, never inferred as numbers. Each parameter consumes exactly
221
+ one nonempty raw segment and is percent-decoded exactly once after choosing the
222
+ winning route. `%20` becomes a space, `+` remains a plus, `%2F` becomes a slash
223
+ inside that value, and `%252F` becomes `%2F`. Invalid percent encoding in a captured
224
+ value produces HTTP 400 InvalidPath before application code runs. request.path
225
+ and the middleware path argument retain the original encoded path.
226
+
227
+ Multiple parameters, group prefixes, XML groups and npm include prefixes are
228
+ supported. A trailing wildcard can follow parameters (`/user/{userId}/*`);
229
+ no wildcard value is added to input. Query strings and path parameters remain
230
+ separate concepts; this feature does not change the existing POST query policy.
231
+
232
+ Parameter names are case-sensitive ASCII identifiers beginning with a letter or
233
+ underscore. A name must occupy an entire segment, occur only once in a route,
234
+ and cannot be __proto__, constructor or prototype. Routes such as `/user/{id}`
235
+ and `/user/{name}` have the same structure and cannot both be registered.
236
+ Overlapping structures with different literal positions are resolved from left
237
+ to right, independently of registration order. For example, `/choose/static/{id}`
238
+ beats `/choose/{id}/fixed` when both match `/choose/static/fixed`.
239
+
240
+ Longpoll channel and fallback paths remain exact and do not accept parameters.
241
+
173
242
  ## Builder
174
243
 
175
244
  ```lango
@@ -257,6 +326,20 @@ registrations. An unresolved module, missing/non-function export, or route using
257
326
  unregistered middleware fails startup. No function or captured closure is
258
327
  transferred from the main thread, and no per-request import is needed.
259
328
 
329
+ Middleware registrations may also specify `validate: "checkRoutes"` (or the XML
330
+ attribute `validate="checkRoutes"`). This names another export in the same
331
+ module, called once in each worker before listening with an independent route
332
+ metadata snapshot. It may return a Promise. A missing/non-function validator or
333
+ a thrown/rejected error fails startup. Validators run without request contexts;
334
+ they check configuration rather than handling requests.
335
+
336
+ Inside request handlers and middleware, `context server` also provides
337
+ `routes()`. It returns a fresh array of `{ path, kind, auth, middleware }` records,
338
+ where kind is `endpoint` or `longpoll`. Module paths and handler names are not
339
+ exposed. Mutating a snapshot cannot change routing. Startup validators receive
340
+ the same metadata shape, allowing libraries to discover their configured URLs
341
+ without introducing library-specific behavior into the server.
342
+
260
343
  The middleware signature is `wrap(handler, path, input)`: `handler` is the resolved
261
344
  application function, `path` is the actual request path including mounted prefixes,
262
345
  and `input` is the decoded request object. For example, the registered module can
@@ -290,7 +373,7 @@ request/event deadlines and SQL transaction cleanup still apply.
290
373
 
291
374
  ```xml
292
375
  <deploy>
293
- <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"/>
294
377
  <workers workers="2" maxQueue="64" requestTimeoutMs="30000"
295
378
  startupTimeoutMs="30000" shutdownTimeoutMs="30000"/>
296
379
  <events requestEvent="false" eventTimeoutMs="5000"/>
@@ -301,8 +384,10 @@ request/event deadlines and SQL transaction cleanup still apply.
301
384
  These are also the default values, apart from the required signing key and the
302
385
  example issuer/audience (defaults: `lango-server` / `lango-client`). Builder uses
303
386
  these attribute names directly in `configure`. Unknown options are errors.
304
- `bodyLimit` is bytes; timeouts are milliseconds. Workers range from 1 to 128;
305
- `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.
306
391
 
307
392
  For rotation, use `keysFile` instead of `keyEnv`, and select `activeKeyId`:
308
393
 
@@ -320,8 +405,14 @@ timestamps are checked. Keys are never generated or stored by the server.
320
405
 
321
406
  Handlers and events can declare `context request`, `response`, `token`, and `log`.
322
407
  Request metadata is read-only: `id`, `method`, `path`, `headers`, `remoteAddress`.
323
- Response supports `status(code)` and `header(name, value)`; the handler return
324
- value supplies its JSON body. Transport/token headers remain server-owned.
408
+ Response supports `status(code)`, `header(name, value)` and `reject(status, code)`;
409
+ the handler return value supplies its JSON body. Transport/token headers remain
410
+ server-owned. `reject` throws a controlled HTTP failure (400–599) with a short
411
+ error code, for example `response.reject(400, "InvalidInput")`. Codes start with
412
+ an ASCII letter and contain at most 64 letters, digits or underscores. Configured
413
+ response headers are preserved. Rejections roll back open SQL transactions and
414
+ send `{ error: code }` without a token; committed side effects are not undone.
415
+ Unexpected exceptions still produce a generic 500.
325
416
 
326
417
  Tokens arrive in `Authorization: Bearer <jwt>` and successful replies contain
327
418
  `X-Lango-Token`. Missing tokens create an anonymous identity with a UUID
@@ -331,10 +422,15 @@ Unauthorized requests do not receive a newly created token.
331
422
 
332
423
  `context token` supports:
333
424
 
334
- * `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.
335
429
  * `AddAuth("login")`, `clearAuth()`, `hasAuth("admin")`: exact trimmed membership.
336
430
  * `get(name)`, `set(name, value)`: JSON custom claims; server-owned JWT fields are
337
431
  protected. `get` returns a copy for structured values.
432
+ * `renew()`: requests renewal after successful serialization and SQL cleanup on
433
+ a reply with a status below 400. It does not immediately change `expiresAt?`.
338
434
 
339
435
  Default endpoint auth is `login`. `auth="anonymous"` permits anonymous callers;
340
436
  other values require that exact permission. `admin` does not imply `login`.
@@ -342,11 +438,20 @@ The application authenticates credentials and grants permissions. These methods
342
438
  do not authenticate anyone automatically.
343
439
 
344
440
  Token updates are committed only after the handler and JSON serialization
345
- succeed. Validation updates preserve the original token expiry. `clearAuth()`
441
+ succeed. Successful validation also requests expiry renewal. `clearAuth()`
346
442
  updates the returned token; it does not invalidate previously issued copies.
347
443
  Use application-owned storage and Validate to enforce logout/revocation across
348
444
  old tokens. There is no built-in session database or UI replay protocol.
349
445
 
446
+ Renewal sets the new JWT's `iat` to the current second and `exp` to that value
447
+ plus `ttlSeconds`. Identity, permissions and custom claims are retained. The
448
+ timestamp of the last actual Validate result is preserved, so it may precede
449
+ the renewed token's issuance time. Renewal does not fake a fresh validation.
450
+ Read-only event tokens cannot request renewal. Expiration is checked again
451
+ before renewal and signing; an expired token cannot be revived. Failed or
452
+ rejected requests publish no renewal. Previously issued tokens remain valid
453
+ until their own expiry unless the application's Validate policy revokes them.
454
+
350
455
  ## Events
351
456
 
352
457
  Event modules and function names are strings, resolved during worker startup.
@@ -363,9 +468,10 @@ Promise results are supported, and events run under the request's contexts.
363
468
  token. Only `true` continues; `false` produces 401. Exceptions, invalid return
364
469
  types, mutation, or timeouts fail the request without running the handler;
365
470
  operational failures are not reported as invalid credentials. Successful
366
- validation updates the server-owned timestamp in the next successful reply.
367
- Recent-token use does not advance it. If no event is configured, standard JWT
368
- 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
369
475
  allowance and depend on the application's storage consistency.
370
476
  * **request(metadata)** is enabled only by `requestEvent: true`. It runs after
371
477
  the handler completes and JSON serialization succeeds, before the reply is
@@ -572,7 +678,7 @@ No sticky sessions are required.
572
678
  The Builder equivalent is `builder.longpoll(options)` or
573
679
  `group.longpoll(options)`. No module or handler is needed. Group and include
574
680
  prefixes apply to both `path` and `fallback`; auth is inherited and defaults to
575
- `login`. Paths must be exact absolute URL paths, without wildcards or query
681
+ `login`. Paths must be exact absolute URL paths, without parameters, wildcards or query
576
682
  strings. Duplicate paths conflict with endpoints as well as other longpoll routes.
577
683
  The fallback is returned to the client; the server never calls it automatically.
578
684
 
@@ -709,3 +815,28 @@ LANGO_TEST_REDIS=redis://127.0.0.1:6379 npm run test:longpoll
709
815
  The suite briefly pauses Redis commands to test infrastructure timeouts. Do not
710
816
  point it at a shared or production Redis instance. CI runs this suite separately
711
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.