@lango-project/lango-server 0.1.2 → 0.2.2
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 +115 -12
- package/dist/.lango/localization.mjs +108 -0
- package/dist/.lango/runtime.mjs +33 -7
- package/dist/.lango/vendor/i18next.LICENSE +21 -0
- package/dist/.lango/vendor/i18next.mjs +2434 -0
- package/dist/cli/.lango/localization.mjs +108 -0
- package/dist/cli/.lango/runtime.mjs +33 -7
- package/dist/cli/.lango/vendor/i18next.LICENSE +21 -0
- package/dist/cli/.lango/vendor/i18next.mjs +2434 -0
- package/dist/cli/error_details.mjs +45 -0
- package/dist/cli/error_details.mjs.map +1 -0
- package/dist/cli/options.mjs +2 -2
- package/dist/cli/options.mjs.map +1 -1
- package/dist/cli/server.mjs +64 -21
- package/dist/cli/server.mjs.map +1 -1
- package/dist/cli/static_files.mjs +123 -25
- package/dist/cli/static_files.mjs.map +1 -1
- package/dist/cli/trace.mjs +53 -0
- package/dist/cli/trace.mjs.map +1 -0
- package/dist/error_details.mjs +45 -0
- package/dist/error_details.mjs.map +1 -0
- package/dist/options.mjs +2 -2
- package/dist/options.mjs.map +1 -1
- package/dist/request_identity.mjs +22 -0
- package/dist/request_identity.mjs.map +1 -0
- package/dist/runtime.mjs +99 -10
- package/dist/runtime.mjs.map +1 -1
- package/dist/server.mjs +64 -21
- package/dist/server.mjs.map +1 -1
- package/dist/server_context.mjs +14 -1
- package/dist/server_context.mjs.map +1 -1
- package/dist/static_files.mjs +123 -25
- package/dist/static_files.mjs.map +1 -1
- package/dist/token.mjs +26 -13
- package/dist/token.mjs.map +1 -1
- package/dist/trace.mjs +53 -0
- package/dist/trace.mjs.map +1 -0
- package/dist/worker.mjs +1 -0
- package/dist/worker.mjs.map +1 -1
- package/package.json +2 -2
- package/src/error_details.lango +21 -0
- package/src/options.lango +2 -2
- package/src/request_identity.lango +9 -0
- package/src/runtime.lango +88 -5
- package/src/server.lango +42 -5
- package/src/server_context.lango +10 -2
- package/src/static_files.lango +102 -23
- package/src/token.lango +13 -3
- package/src/trace.lango +23 -0
- package/src/worker.lango +1 -0
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.
|
|
111
|
-
directory listings
|
|
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.
|
|
@@ -348,11 +369,19 @@ in the worker. Request events observe that final serialized result. Middleware,
|
|
|
348
369
|
handler and serialization errors follow the existing error/token behavior;
|
|
349
370
|
request/event deadlines and SQL transaction cleanup still apply.
|
|
350
371
|
|
|
372
|
+
Unexpected failures are logged through `context log` with the request ID, the
|
|
373
|
+
request token's `clientId`, and optional `sessionId` and `userId` claims when
|
|
374
|
+
non-null. The original error message and stack trace are included when available. Workers enable Node source
|
|
375
|
+
maps so compiled application errors point to their `.lango` source when matching
|
|
376
|
+
`.mjs.map` files are deployed. Keep these files alongside the compiled modules.
|
|
377
|
+
HTTP clients receive the generic `InternalServerError` response; internal error
|
|
378
|
+
messages and stack traces remain in the server logs.
|
|
379
|
+
|
|
351
380
|
## Configuration
|
|
352
381
|
|
|
353
382
|
```xml
|
|
354
383
|
<deploy>
|
|
355
|
-
<http host="127.0.0.1" port="3000" bodyLimit="
|
|
384
|
+
<http host="127.0.0.1" port="3000" bodyLimit="2097152" bodyTimeoutMs="30000"/>
|
|
356
385
|
<workers workers="2" maxQueue="64" requestTimeoutMs="30000"
|
|
357
386
|
startupTimeoutMs="30000" shutdownTimeoutMs="30000"/>
|
|
358
387
|
<events requestEvent="false" eventTimeoutMs="5000"/>
|
|
@@ -363,8 +392,10 @@ request/event deadlines and SQL transaction cleanup still apply.
|
|
|
363
392
|
These are also the default values, apart from the required signing key and the
|
|
364
393
|
example issuer/audience (defaults: `lango-server` / `lango-client`). Builder uses
|
|
365
394
|
these attribute names directly in `configure`. Unknown options are errors.
|
|
366
|
-
`bodyLimit` is bytes
|
|
367
|
-
|
|
395
|
+
`bodyLimit` is bytes and defaults to 2 MiB (2097152 bytes), allowing a 1 MiB
|
|
396
|
+
binary file encoded as base64 within a JSON form. Larger combined form payloads
|
|
397
|
+
require an explicit higher limit. Timeouts are milliseconds. Workers range from
|
|
398
|
+
1 to 128; `maxQueue: 0` disables waiting. JWT lifetime is 1 to 86400 seconds.
|
|
368
399
|
|
|
369
400
|
For rotation, use `keysFile` instead of `keyEnv`, and select `activeKeyId`:
|
|
370
401
|
|
|
@@ -399,12 +430,15 @@ Unauthorized requests do not receive a newly created token.
|
|
|
399
430
|
|
|
400
431
|
`context token` supports:
|
|
401
432
|
|
|
402
|
-
* `clientId
|
|
433
|
+
* `clientId?`, `auth?`, `expiresAt?`: getter-only identity, comma-separated
|
|
434
|
+
permissions and expiry. Direct assignment is rejected, including JavaScript
|
|
435
|
+
attempts to shadow these properties. Use the controlled methods below to update
|
|
436
|
+
claims or permissions.
|
|
403
437
|
* `AddAuth("login")`, `clearAuth()`, `hasAuth("admin")`: exact trimmed membership.
|
|
404
438
|
* `get(name)`, `set(name, value)`: JSON custom claims; server-owned JWT fields are
|
|
405
439
|
protected. `get` returns a copy for structured values.
|
|
406
440
|
* `renew()`: requests renewal after successful serialization and SQL cleanup on
|
|
407
|
-
a reply with a status below 400. It does not immediately change `expiresAt
|
|
441
|
+
a reply with a status below 400. It does not immediately change `expiresAt?`.
|
|
408
442
|
|
|
409
443
|
Default endpoint auth is `login`. `auth="anonymous"` permits anonymous callers;
|
|
410
444
|
other values require that exact permission. `admin` does not imply `login`.
|
|
@@ -412,7 +446,7 @@ The application authenticates credentials and grants permissions. These methods
|
|
|
412
446
|
do not authenticate anyone automatically.
|
|
413
447
|
|
|
414
448
|
Token updates are committed only after the handler and JSON serialization
|
|
415
|
-
succeed.
|
|
449
|
+
succeed. Successful validation also requests expiry renewal. `clearAuth()`
|
|
416
450
|
updates the returned token; it does not invalidate previously issued copies.
|
|
417
451
|
Use application-owned storage and Validate to enforce logout/revocation across
|
|
418
452
|
old tokens. There is no built-in session database or UI replay protocol.
|
|
@@ -442,9 +476,10 @@ Promise results are supported, and events run under the request's contexts.
|
|
|
442
476
|
token. Only `true` continues; `false` produces 401. Exceptions, invalid return
|
|
443
477
|
types, mutation, or timeouts fail the request without running the handler;
|
|
444
478
|
operational failures are not reported as invalid credentials. Successful
|
|
445
|
-
validation updates the server-owned timestamp in the next
|
|
446
|
-
Recent-token use does not advance
|
|
447
|
-
|
|
479
|
+
validation updates the server-owned timestamp and renews expiry in the next
|
|
480
|
+
successful reply. Recent-token use does not advance the timestamp or implicitly
|
|
481
|
+
renew expiry. If no event is configured, standard JWT verification supplies
|
|
482
|
+
the successful validation result at the same freshness boundary. Revocation checks have a one-second freshness
|
|
448
483
|
allowance and depend on the application's storage consistency.
|
|
449
484
|
* **request(metadata)** is enabled only by `requestEvent: true`. It runs after
|
|
450
485
|
the handler completes and JSON serialization succeeds, before the reply is
|
|
@@ -788,3 +823,71 @@ LANGO_TEST_REDIS=redis://127.0.0.1:6379 npm run test:longpoll
|
|
|
788
823
|
The suite briefly pauses Redis commands to test infrastructure timeouts. Do not
|
|
789
824
|
point it at a shared or production Redis instance. CI runs this suite separately
|
|
790
825
|
from `npm test`, alongside the PostgreSQL integration suite.
|
|
826
|
+
|
|
827
|
+
## Framework token refresh batches
|
|
828
|
+
|
|
829
|
+
`context server.refreshTokens(tokens)` supports middleware that refreshes several
|
|
830
|
+
form tokens in one HTTP request. It accepts 1–64 distinct nonempty token strings
|
|
831
|
+
(up to 16,384 characters each). Structural validation completes before any item
|
|
832
|
+
runs. The current authenticated token supplies the batch client identity.
|
|
833
|
+
|
|
834
|
+
Each item must pass normal JWT verification and belong to that same `clientId`.
|
|
835
|
+
The server dispatches the **current route** again with an empty input map and
|
|
836
|
+
that item's Bearer token, using separate token, response and database scopes.
|
|
837
|
+
This is used by Lango UI Ping; its ordinary empty-body path invokes the hook and
|
|
838
|
+
requests renewal. Do not use this helper from a handler that recursively batches
|
|
839
|
+
empty requests.
|
|
840
|
+
|
|
841
|
+
The result is an array of `{ previous, token, status }`. Invalid, expired or
|
|
842
|
+
foreign-client tokens produce an individual 401 and no replacement token.
|
|
843
|
+
Handler/SQL failures retain their normal status and do not publish that item's
|
|
844
|
+
claim changes. Items execute sequentially under the physical request's overall
|
|
845
|
+
deadline and normal event deadlines. An interrupted physical request publishes
|
|
846
|
+
no completed batch response; already completed item transactions are not undone.
|
|
847
|
+
There is no automatic retry.
|
|
848
|
+
|
|
849
|
+
Request auditing runs once for the physical batch response, not once per internal
|
|
850
|
+
item; an internal result cannot replace the prepared outer HTTP reply.
|
|
851
|
+
|
|
852
|
+
|
|
853
|
+
## Verbose diagnostics
|
|
854
|
+
|
|
855
|
+
Run `lango-server <application-directory> --verbose` (or `npm start -- --verbose`
|
|
856
|
+
in a generated UI application). The flag can appear before or after the directory.
|
|
857
|
+
It enables `LANGO_VERBOSE=1` for the server process and its workers. Normal startup
|
|
858
|
+
keeps debug logs disabled. `LANGO_VERBOSE=1` also enables diagnostics for a server
|
|
859
|
+
started through its library API.
|
|
860
|
+
|
|
861
|
+
Verbose logs show configuration loading, worker module/export resolution, HTTP
|
|
862
|
+
request paths, queue/dispatch stages, matched routes, handler invocation and
|
|
863
|
+
response status. Verified request identity is included once available. Request
|
|
864
|
+
bodies, authorization headers, signing keys and raw JWTs are not logged.
|
|
865
|
+
|
|
866
|
+
```lango
|
|
867
|
+
context log
|
|
868
|
+
if log.verbose?
|
|
869
|
+
log.debug("Preparing optional diagnostic details")
|
|
870
|
+
```
|
|
871
|
+
|
|
872
|
+
`log.verbose?` is readonly. `debug()` is filtered automatically, while `info()`,
|
|
873
|
+
`warn()` and `err()` remain enabled. Rebuild application modules with Lango JS
|
|
874
|
+
0.1.17 or newer to give their default log objects the same verbose behavior.
|
|
875
|
+
|
|
876
|
+
|
|
877
|
+
For browser startup, GET / serves the static HTML shell; it does not invoke an
|
|
878
|
+
application handler. Browser modules subsequently POST / to bootstrap and POST
|
|
879
|
+
/index (or the selected page path) to request the view. Verbose static logs show
|
|
880
|
+
the serving directory and HTTP completion status. Invalid JWTs are rejected
|
|
881
|
+
before handler invocation, with a verbose diagnostic identifying that stage.
|
|
882
|
+
A client with an expired/replaced stored token can therefore load HTML but fail
|
|
883
|
+
its bootstrap POST with 401 before any application log statement runs.
|
|
884
|
+
|
|
885
|
+
|
|
886
|
+
HTTP failures are visible without verbose mode: completed 4xx responses use
|
|
887
|
+
`log.warn()` and completed 5xx responses use `log.err()`, with the method, URL
|
|
888
|
+
path, status and dispatched request ID where available. Successful responses
|
|
889
|
+
remain debug-only. JWT rejection reasons are warnings even before a handler is
|
|
890
|
+
invoked; raw JWTs and unverified claims are not logged as client identity.
|
|
891
|
+
Expired or invalid tokens can occur during ordinary session lifetimes, but a
|
|
892
|
+
failed startup is still a logged rejection. Detailed internal failures retain
|
|
893
|
+
their existing exception and identity logs.
|
|
@@ -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
|
+
}
|
package/dist/.lango/runtime.mjs
CHANGED
|
@@ -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
|
|
36
|
+
let defaultI18n = null;
|
|
35
37
|
let output = null;
|
|
36
38
|
let database = null;
|
|
37
39
|
const failureStore = Symbol.for("lango.databaseFailures");
|
|
@@ -98,6 +100,9 @@ function postgresQuery(sql, parameters) {
|
|
|
98
100
|
return { text: text + sql.slice(at), values };
|
|
99
101
|
}
|
|
100
102
|
export const DB = Object.freeze({ Active: "active", RollbackOnly: "rollback_only", Failed: "failed" });
|
|
103
|
+
const loggingStore = Symbol.for("lango.logging");
|
|
104
|
+
const logging = globalThis[loggingStore] ?? { verbose: false };
|
|
105
|
+
globalThis[loggingStore] = logging;
|
|
101
106
|
const contextStore = Symbol.for("lango.contexts");
|
|
102
107
|
const contexts = globalThis[contextStore] ?? new Map();
|
|
103
108
|
globalThis[contextStore] = contexts;
|
|
@@ -112,6 +117,8 @@ export class RuntimeConfigurationError extends Error {
|
|
|
112
117
|
export function configure(options = {}) {
|
|
113
118
|
if (options === null || typeof options !== "object" || Array.isArray(options))
|
|
114
119
|
throw new RuntimeConfigurationError("runtime configuration must be an object");
|
|
120
|
+
if (options.verbose !== undefined && typeof options.verbose !== "boolean")
|
|
121
|
+
throw new RuntimeConfigurationError("runtime verbose must be boolean");
|
|
115
122
|
const nextCatalog = options.catalog ?? {};
|
|
116
123
|
const nextOutput = options.output ?? null;
|
|
117
124
|
const nextDatabase = options.database_adapter ?? null;
|
|
@@ -121,7 +128,20 @@ export function configure(options = {}) {
|
|
|
121
128
|
throw new RuntimeConfigurationError("runtime output must be a function or null");
|
|
122
129
|
if (nextDatabase !== null && (typeof nextDatabase !== "object" && typeof nextDatabase !== "function"))
|
|
123
130
|
throw new RuntimeConfigurationError("runtime database_adapter must be an object or null");
|
|
124
|
-
|
|
131
|
+
let nextI18n;
|
|
132
|
+
try {
|
|
133
|
+
nextI18n = options.i18n ?? createI18n({
|
|
134
|
+
catalog: nextCatalog, catalogs: options.catalogs,
|
|
135
|
+
locale: options.locale, fallbackLocale: options.fallbackLocale,
|
|
136
|
+
timeZone: options.timeZone, currency: options.currency,
|
|
137
|
+
});
|
|
138
|
+
if (typeof nextI18n.translate !== "function" || typeof nextI18n.formatNumber !== "function" || typeof nextI18n.formatDate !== "function")
|
|
139
|
+
throw new TypeError("i18n requires translate, formatNumber and formatDate methods");
|
|
140
|
+
} catch (error) {
|
|
141
|
+
throw new RuntimeConfigurationError(error.message);
|
|
142
|
+
}
|
|
143
|
+
if (options.verbose !== undefined) logging.verbose = options.verbose;
|
|
144
|
+
defaultI18n = nextI18n;
|
|
125
145
|
output = nextOutput;
|
|
126
146
|
if (database !== null) failedTransactions.delete(database);
|
|
127
147
|
database = nextDatabase;
|
|
@@ -229,10 +249,14 @@ export function query(sql, parameterNames) {
|
|
|
229
249
|
return proxy;
|
|
230
250
|
}
|
|
231
251
|
|
|
232
|
-
export function translate(template, values) {
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
252
|
+
export function translate(template, values, options = null) {
|
|
253
|
+
return contextGet("i18n").translate(template, values, options);
|
|
254
|
+
}
|
|
255
|
+
export function formatNumber(value, options = null) {
|
|
256
|
+
return contextGet("i18n").formatNumber(value, options);
|
|
257
|
+
}
|
|
258
|
+
export function formatDate(value, options = null) {
|
|
259
|
+
return contextGet("i18n").formatDate(value, options);
|
|
236
260
|
}
|
|
237
261
|
|
|
238
262
|
export function xmlEscape(value) {
|
|
@@ -323,7 +347,8 @@ export function println(value) {
|
|
|
323
347
|
}
|
|
324
348
|
|
|
325
349
|
const defaultLog = Object.freeze({
|
|
326
|
-
|
|
350
|
+
get verbose() { return logging.verbose || process.env.LANGO_VERBOSE === "1"; },
|
|
351
|
+
debug(value) { if (!defaultLog.verbose) return null; return writeLog(process.stdout, "DEBUG", value); },
|
|
327
352
|
info(value) { return writeLog(process.stdout, "INFO", value); },
|
|
328
353
|
warn(value) { return writeLog(process.stderr, "WARN", value); },
|
|
329
354
|
err(value) { return writeLog(process.stderr, "ERROR", value); },
|
|
@@ -660,6 +685,7 @@ export function withArity(callback, requiredPositions, name) {
|
|
|
660
685
|
export function contextGet(name) {
|
|
661
686
|
const stack = contexts.get(name);
|
|
662
687
|
if ((!stack || stack.length === 0) && name === "log") return defaultLog;
|
|
688
|
+
if ((!stack || stack.length === 0) && name === "i18n") return defaultI18n ??= createI18n();
|
|
663
689
|
if (!stack || stack.length === 0) {
|
|
664
690
|
throw new Error(`Lango context is unavailable: ${name}`);
|
|
665
691
|
}
|
|
@@ -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.
|