@lango-project/lango-client 0.2.1 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (240) hide show
  1. package/LICENSE +1 -0
  2. package/NOTICE +5 -1
  3. package/README.md +603 -906
  4. package/cli/.lango/localization.mjs +108 -0
  5. package/{dist/node → cli}/.lango/runtime.mjs +120 -20
  6. package/cli/.lango/vendor/i18next.LICENSE +21 -0
  7. package/cli/.lango/vendor/i18next.mjs +2434 -0
  8. package/cli/create.mjs +62 -0
  9. package/cli/create.mjs.map +1 -0
  10. package/dist/.lango/localization.mjs +108 -0
  11. package/dist/.lango/runtime.mjs +120 -20
  12. package/dist/.lango/vendor/i18next.LICENSE +21 -0
  13. package/dist/.lango/vendor/i18next.mjs +2434 -0
  14. package/dist/accordion.mjs +277 -0
  15. package/dist/accordion.mjs.map +1 -0
  16. package/dist/activities.mjs +185 -0
  17. package/dist/activities.mjs.map +1 -0
  18. package/dist/app.mjs +671 -0
  19. package/dist/app.mjs.map +1 -0
  20. package/dist/boot.mjs +24 -0
  21. package/dist/boot.mjs.map +1 -0
  22. package/dist/bootstrap-LICENSE +21 -0
  23. package/dist/bootstrap.min.css +6 -0
  24. package/dist/bootstrap.min.css.map +1 -0
  25. package/dist/button.mjs +77 -0
  26. package/dist/button.mjs.map +1 -0
  27. package/dist/chip.mjs +134 -0
  28. package/dist/chip.mjs.map +1 -0
  29. package/dist/client.css +102 -0
  30. package/dist/collections.mjs +77 -0
  31. package/dist/collections.mjs.map +1 -0
  32. package/dist/combo_box.mjs +408 -0
  33. package/dist/combo_box.mjs.map +1 -0
  34. package/dist/content.mjs +123 -0
  35. package/dist/content.mjs.map +1 -0
  36. package/dist/control.mjs +141 -0
  37. package/dist/control.mjs.map +1 -0
  38. package/dist/date_input.mjs +242 -0
  39. package/dist/date_input.mjs.map +1 -0
  40. package/dist/dimensions.mjs +102 -0
  41. package/dist/dimensions.mjs.map +1 -0
  42. package/dist/error_reporter.mjs +136 -0
  43. package/dist/error_reporter.mjs.map +1 -0
  44. package/dist/fields.mjs +454 -0
  45. package/dist/fields.mjs.map +1 -0
  46. package/dist/file_input.mjs +227 -0
  47. package/dist/file_input.mjs.map +1 -0
  48. package/dist/form.mjs +272 -0
  49. package/dist/form.mjs.map +1 -0
  50. package/dist/heartbeat.mjs +167 -254
  51. package/dist/heartbeat.mjs.map +1 -1
  52. package/dist/index.html +18 -0
  53. package/dist/indicators.mjs +127 -0
  54. package/dist/indicators.mjs.map +1 -0
  55. package/dist/input_changes.mjs +58 -0
  56. package/dist/input_changes.mjs.map +1 -0
  57. package/dist/input_group.mjs +38 -0
  58. package/dist/input_group.mjs.map +1 -0
  59. package/dist/layouts.mjs +195 -0
  60. package/dist/layouts.mjs.map +1 -0
  61. package/dist/library.mjs +130 -807
  62. package/dist/library.mjs.map +1 -1
  63. package/dist/longpoll.mjs +254 -0
  64. package/dist/longpoll.mjs.map +1 -0
  65. package/dist/main.mjs +147 -0
  66. package/dist/main.mjs.map +1 -0
  67. package/dist/markdown.mjs +61 -0
  68. package/dist/markdown.mjs.map +1 -0
  69. package/dist/menus.mjs +468 -0
  70. package/dist/menus.mjs.map +1 -0
  71. package/dist/navigation.mjs +260 -410
  72. package/dist/navigation.mjs.map +1 -1
  73. package/dist/numeric_input.mjs +181 -0
  74. package/dist/numeric_input.mjs.map +1 -0
  75. package/dist/otp_input.mjs +113 -0
  76. package/dist/otp_input.mjs.map +1 -0
  77. package/dist/presentations.mjs +852 -0
  78. package/dist/presentations.mjs.map +1 -0
  79. package/dist/renderer.mjs +295 -0
  80. package/dist/renderer.mjs.map +1 -0
  81. package/dist/rich_content.mjs +99 -0
  82. package/dist/rich_content.mjs.map +1 -0
  83. package/dist/table_scope.mjs +166 -0
  84. package/dist/table_scope.mjs.map +1 -0
  85. package/dist/tables.mjs +1052 -0
  86. package/dist/tables.mjs.map +1 -0
  87. package/dist/tabs.mjs +205 -0
  88. package/dist/tabs.mjs.map +1 -0
  89. package/dist/templates.mjs +46 -0
  90. package/dist/templates.mjs.map +1 -0
  91. package/dist/vendor/DOMPurify-LICENSE +202 -0
  92. package/dist/vendor/dompurify.mjs +2454 -0
  93. package/dist/vendor/flatpickr-LICENSE.md +21 -0
  94. package/dist/vendor/flatpickr.min.css +13 -0
  95. package/dist/vendor/flatpickr.mjs +2340 -0
  96. package/dist/vendor/flatpickr.mjs.map +7 -0
  97. package/dist/vendor/marked-LICENSE.md +44 -0
  98. package/dist/vendor/marked.esm.js.map +7 -0
  99. package/dist/vendor/marked.mjs +85 -0
  100. package/dist/vendor/purify.es.mjs.map +1 -0
  101. package/dist/widgets.mjs +197 -0
  102. package/dist/widgets.mjs.map +1 -0
  103. package/docs/implementation.md +93 -0
  104. package/package.json +25 -43
  105. package/src/accordion.lango +198 -0
  106. package/src/activities.lango +132 -0
  107. package/src/app.lango +540 -0
  108. package/src/boot.lango +12 -0
  109. package/src/button.lango +49 -0
  110. package/src/chip.lango +94 -0
  111. package/src/collections.lango +46 -0
  112. package/src/combo_box.lango +298 -0
  113. package/src/content.lango +75 -0
  114. package/src/control.lango +103 -0
  115. package/src/create.lango +42 -0
  116. package/src/date_input.lango +215 -0
  117. package/src/dimensions.lango +65 -0
  118. package/src/error_reporter.lango +95 -0
  119. package/src/fields.lango +327 -0
  120. package/src/file_input.lango +175 -0
  121. package/src/form.lango +195 -0
  122. package/src/heartbeat.lango +136 -199
  123. package/src/indicators.lango +94 -0
  124. package/src/input_changes.lango +33 -0
  125. package/src/input_group.lango +22 -0
  126. package/src/layouts.lango +137 -0
  127. package/src/library.lango +194 -599
  128. package/src/longpoll.lango +187 -0
  129. package/src/main.lango +118 -0
  130. package/src/markdown.lango +48 -0
  131. package/src/menus.lango +336 -0
  132. package/src/navigation.lango +209 -299
  133. package/src/numeric_input.lango +131 -0
  134. package/src/otp_input.lango +83 -0
  135. package/src/presentations.lango +617 -0
  136. package/src/renderer.lango +296 -0
  137. package/src/rich_content.lango +66 -0
  138. package/src/table_scope.lango +119 -0
  139. package/src/tables.lango +786 -0
  140. package/src/tabs.lango +144 -0
  141. package/src/templates.lango +29 -0
  142. package/src/widgets.lango +141 -0
  143. package/web/client.css +102 -0
  144. package/web/index.html +18 -0
  145. package/dist/application.mjs +0 -429
  146. package/dist/application.mjs.map +0 -1
  147. package/dist/coordinator.mjs +0 -91
  148. package/dist/coordinator.mjs.map +0 -1
  149. package/dist/demo.mjs +0 -110
  150. package/dist/demo.mjs.map +0 -1
  151. package/dist/demo_controls.mjs +0 -59
  152. package/dist/demo_controls.mjs.map +0 -1
  153. package/dist/errors.mjs +0 -201
  154. package/dist/errors.mjs.map +0 -1
  155. package/dist/form_state.mjs +0 -266
  156. package/dist/form_state.mjs.map +0 -1
  157. package/dist/inheritance.mjs +0 -240
  158. package/dist/inheritance.mjs.map +0 -1
  159. package/dist/input_values.mjs +0 -65
  160. package/dist/input_values.mjs.map +0 -1
  161. package/dist/node/.lango/xmldom/conventions.js +0 -429
  162. package/dist/node/.lango/xmldom/dom-parser.js +0 -591
  163. package/dist/node/.lango/xmldom/dom.js +0 -3759
  164. package/dist/node/.lango/xmldom/entities.js +0 -2171
  165. package/dist/node/.lango/xmldom/errors.js +0 -205
  166. package/dist/node/.lango/xmldom/grammar.js +0 -559
  167. package/dist/node/.lango/xmldom/index.js +0 -41
  168. package/dist/node/.lango/xmldom/package.json +0 -1
  169. package/dist/node/.lango/xmldom/sax.js +0 -983
  170. package/dist/node/.lango/xmldom.LICENSE.md +0 -8
  171. package/dist/node/browser_host.mjs +0 -351
  172. package/dist/node/browser_host.mjs.map +0 -1
  173. package/dist/node/create_app.mjs +0 -118
  174. package/dist/node/create_app.mjs.map +0 -1
  175. package/dist/presentation.mjs +0 -89
  176. package/dist/presentation.mjs.map +0 -1
  177. package/dist/protocol.mjs +0 -706
  178. package/dist/protocol.mjs.map +0 -1
  179. package/dist/session.mjs +0 -471
  180. package/dist/session.mjs.map +0 -1
  181. package/dist/tokens.mjs +0 -298
  182. package/dist/tokens.mjs.map +0 -1
  183. package/examples/contacts.lango +0 -293
  184. package/examples/contacts_flow.lango +0 -174
  185. package/examples/contacts_store.lango +0 -109
  186. package/examples/contacts_store_test.lango +0 -65
  187. package/examples/demo.css +0 -87
  188. package/examples/demo_test.lango +0 -356
  189. package/examples/index.html +0 -32
  190. package/examples/pages.lango +0 -174
  191. package/examples/server.lango +0 -189
  192. package/examples/worker.lango +0 -142
  193. package/src/application.lango +0 -327
  194. package/src/browser_host.lango +0 -276
  195. package/src/coordinator.lango +0 -57
  196. package/src/demo.lango +0 -110
  197. package/src/demo_controls.lango +0 -53
  198. package/src/errors.lango +0 -149
  199. package/src/errors_test.lango +0 -157
  200. package/src/form_state.lango +0 -168
  201. package/src/heartbeat_test.lango +0 -479
  202. package/src/inheritance.lango +0 -167
  203. package/src/input_values.lango +0 -37
  204. package/src/logout_test.lango +0 -564
  205. package/src/navigation_test.lango +0 -556
  206. package/src/presentation.lango +0 -55
  207. package/src/protocol.lango +0 -787
  208. package/src/renderer_test.lango +0 -2047
  209. package/src/session.lango +0 -343
  210. package/src/session_test.lango +0 -455
  211. package/src/tabs_test.lango +0 -216
  212. package/src/tokens.lango +0 -215
  213. package/template/.vscode/extensions.json +0 -3
  214. package/template/.vscode/settings.json +0 -9
  215. package/template/README.md +0 -44
  216. package/template/gitignore +0 -4
  217. package/template/package.json +0 -22
  218. package/template/public/app.css +0 -10
  219. package/template/public/index.html +0 -24
  220. package/template/src/client.lango +0 -78
  221. package/template/src/pages.lango +0 -55
  222. package/template/src/server.lango +0 -24
  223. package/template/src/worker.lango +0 -77
  224. package/template/test/app.lango +0 -9
  225. package/tools/browser_runner.lango +0 -32
  226. package/tools/browser_test.lango +0 -343
  227. package/tools/create_app.lango +0 -88
  228. package/tools/create_app_test.lango +0 -43
  229. package/tools/starter_test.lango +0 -227
  230. /package/{dist/node → cli}/.lango/bignumber.mjs +0 -0
  231. /package/{dist → cli}/.lango/xmldom/conventions.js +0 -0
  232. /package/{dist → cli}/.lango/xmldom/dom-parser.js +0 -0
  233. /package/{dist → cli}/.lango/xmldom/dom.js +0 -0
  234. /package/{dist → cli}/.lango/xmldom/entities.js +0 -0
  235. /package/{dist → cli}/.lango/xmldom/errors.js +0 -0
  236. /package/{dist → cli}/.lango/xmldom/grammar.js +0 -0
  237. /package/{dist → cli}/.lango/xmldom/index.js +0 -0
  238. /package/{dist → cli}/.lango/xmldom/package.json +0 -0
  239. /package/{dist → cli}/.lango/xmldom/sax.js +0 -0
  240. /package/{dist → cli}/.lango/xmldom.LICENSE.md +0 -0
package/cli/create.mjs ADDED
@@ -0,0 +1,62 @@
1
+ #!/usr/bin/env node
2
+ import * as fs from "node:fs";
3
+ import * as path from "node:path";
4
+ import {
5
+ hostGlobal as __hostGlobal,
6
+ println as __println,
7
+ requireBoolean as __requireBoolean,
8
+ normalize as __normalize,
9
+ boundary as __boundary,
10
+ requireArity as __requireArity,
11
+ } from "./.lango/runtime.mjs";
12
+
13
+ export function copyClient(source, destination, update = false) {
14
+ __requireArity(arguments.length, [0, 1], "copyClient");
15
+ source = __boundary(source);
16
+ destination = __boundary(destination);
17
+ update = __boundary(update);
18
+ source = __normalize(path.resolve(source));
19
+ destination = __normalize(path.resolve(destination));
20
+ let relative = __normalize(path.relative(source, destination));
21
+ if (__requireBoolean(__requireBoolean(relative === "") || __requireBoolean(__requireBoolean(__requireBoolean(relative !== "..") && __requireBoolean(!__requireBoolean(__normalize(relative.startsWith(`..${__normalize(path.sep)}`))))) && __requireBoolean(!__requireBoolean(__normalize(path.isAbsolute(relative))))))) {
22
+ throw "Destination must be outside the client distribution";
23
+ }
24
+ if (__requireBoolean(__requireBoolean(!__requireBoolean(__normalize(fs.existsSync(__normalize(path.join(source, "index.html")))))) || __requireBoolean(!__requireBoolean(__normalize(fs.existsSync(__normalize(path.join(source, "boot.mjs")))))))) {
25
+ throw "Client distribution is missing; build the package first";
26
+ }
27
+ if (__requireBoolean(__normalize(fs.existsSync(destination)))) {
28
+ if (__requireBoolean(!__requireBoolean(__normalize(__normalize(fs.statSync(destination)).isDirectory())))) {
29
+ throw "Client destination must be a directory";
30
+ }
31
+ if (__requireBoolean(__requireBoolean(!__requireBoolean(update)) && __requireBoolean(__normalize(__normalize(fs.readdirSync(destination)).length) > 0))) {
32
+ throw "Client destination is not empty; --update refreshes generated assets";
33
+ }
34
+ }
35
+ __normalize(fs.mkdirSync(destination, { recursive: true }));
36
+ __normalize(fs.cpSync(source, destination, { recursive: true, force: update, errorOnExist: !__requireBoolean(update) }));
37
+ return destination;
38
+ return null;
39
+ }
40
+
41
+ export function main(args) {
42
+ __requireArity(arguments.length, [0], "main");
43
+ args = __boundary(args);
44
+ if (__requireBoolean(__requireBoolean(__normalize(args.length) === 0) || __requireBoolean(__normalize(args[0]) === "--help"))) {
45
+ __println("Usage: lango-client <directory> [--update]");
46
+ __println("Write the same-origin Web/Bootstrap browser application to a static directory.");
47
+ return null;
48
+ }
49
+ if (__requireBoolean(__requireBoolean(__normalize(args.length) > 2) || __requireBoolean(__requireBoolean(__normalize(args.length) === 2) && __requireBoolean(__normalize(args[1]) !== "--update")))) {
50
+ throw "Usage: lango-client <directory> [--update]";
51
+ }
52
+ let executable = __normalize(fs.realpathSync(__normalize(__hostGlobal(["process"]).argv[1])));
53
+ let source = __normalize(path.resolve(__normalize(path.dirname(executable)), "../dist"));
54
+ let directory = copyClient(source, __normalize(args[0]), __normalize(args.length) === 2);
55
+ __println(`Browser assets written to ${directory}`);
56
+ return null;
57
+ return null;
58
+ }
59
+ const { configure } = await import("./.lango/runtime.mjs");
60
+ configure({ output: (value) => console.log(value) });
61
+ await main(process.argv.slice(2));
62
+ //# sourceMappingURL=create.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"create.mjs","sources":["create.lango"],"sourcesContent":["import js \"node:fs\" as fs\nimport js \"node:path\" as path\nimport js global process\n\nexport main(args)\nexport copyClient(source, destination, update = false)\n\ncopyClient(source, destination, update = false)\n source = path/resolve(source)\n destination = path/resolve(destination)\n relative = path/relative(source, destination)\n if relative == \"\" or (relative != \"..\" and !relative.startsWith(\"..${path.sep}\") and !path/isAbsolute(relative))\n throw \"Destination must be outside the client distribution\"\n if !fs/existsSync(path/join(source, \"index.html\")) or !fs/existsSync(path/join(source, \"boot.mjs\"))\n throw \"Client distribution is missing; build the package first\"\n if fs/existsSync(destination)\n if !fs/statSync(destination).isDirectory()\n throw \"Client destination must be a directory\"\n if !update and fs/readdirSync(destination).length > 0\n throw \"Client destination is not empty; --update refreshes generated assets\"\n fs/mkdirSync(destination, {\n recursive: true\n })\n fs/cpSync(source, destination, {\n recursive: true\n force: update\n errorOnExist: !update\n })\n return destination\n\nmain(args)\n if args.length == 0 or args[0] == \"--help\"\n println(\"Usage: lango-client <directory> [--update]\")\n println(\"Write the same-origin Web/Bootstrap browser application to a static directory.\")\n return null\n if args.length > 2 or (args.length == 2 and args[1] != \"--update\")\n throw \"Usage: lango-client <directory> [--update]\"\n executable = fs/realpathSync(process.argv[1])\n source = path/resolve(path/dirname(executable), \"../dist\")\n directory = copyClient(source, args[0], args.length == 2)\n println(\"Browser assets written to ${directory}\")\n return null\n"],"names":[],"mappings":";;;;;;;;;;;;AAOA;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuBA;;;;;;;;;;;;;;;;;;;;;;"}
@@ -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
  const DOMParser = globalThis.DOMParser;
3
5
 
4
6
  const Decimal = BigNumber.clone({
@@ -29,11 +31,76 @@ export function toJsNumber(value) {
29
31
  return new Decimal(value).toNumber();
30
32
  }
31
33
 
32
- let catalog = {};
34
+ let defaultI18n = null;
33
35
  let output = null;
34
36
  let database = null;
35
- let failedTransaction = false;
37
+ const failureStore = Symbol.for("lango.databaseFailures");
38
+ const failedTransactions = globalThis[failureStore] ?? new WeakSet();
39
+ globalThis[failureStore] = failedTransactions;
40
+
41
+ function sqlBindings(sql) {
42
+ const bindings = [];
43
+ for (let i = 0; i < sql.length;) {
44
+ if (sql.startsWith("--", i)) {
45
+ const end = sql.indexOf("\n", i + 2);
46
+ i = end < 0 ? sql.length : end + 1;
47
+ } else if (sql.startsWith("/*", i)) {
48
+ let depth = 1;
49
+ i += 2;
50
+ while (i < sql.length && depth) {
51
+ if (sql.startsWith("/*", i)) { depth++; i += 2; }
52
+ else if (sql.startsWith("*/", i)) { depth--; i += 2; }
53
+ else i++;
54
+ }
55
+ } else if ("'\"`[".includes(sql[i])) {
56
+ const start = sql[i];
57
+ const end = start === "[" ? "]" : start;
58
+ const escape = start === "'" && /[eE]/.test(sql[i - 1] ?? "") &&
59
+ !/[\w$]/.test(sql[i - 2] ?? "");
60
+ i++;
61
+ while (i < sql.length) {
62
+ if (escape && sql[i] === "\\") i += 2;
63
+ else if (sql[i] === end) {
64
+ i++;
65
+ if (sql[i] !== end) break;
66
+ i++;
67
+ } else i++;
68
+ }
69
+ } else if (sql[i] === "$" && !/[\w$]/.test(sql[i - 1] ?? "")) {
70
+ const tag = /^\$(?:[A-Za-z_]\w*)?\$/.exec(sql.slice(i))?.[0];
71
+ if (tag) {
72
+ const end = sql.indexOf(tag, i + tag.length);
73
+ i = end < 0 ? sql.length : end + tag.length;
74
+ } else i++;
75
+ } else if (sql[i] === ":" && sql[i - 1] !== ":" && /[A-Za-z_]/.test(sql[i + 1] ?? "")) {
76
+ const start = i++;
77
+ while (/\w/.test(sql[i] ?? "")) i++;
78
+ bindings.push({ name: sql.slice(start + 1, i), start, end: i });
79
+ } else i++;
80
+ }
81
+ return bindings;
82
+ }
83
+ function postgresQuery(sql, parameters) {
84
+ const positions = new Map();
85
+ const values = [];
86
+ let text = "";
87
+ let at = 0;
88
+ for (const binding of sqlBindings(sql)) {
89
+ if (!Object.hasOwn(parameters, binding.name))
90
+ throw new Error(`SqlParameterNotBound: ${binding.name}`);
91
+ if (!positions.has(binding.name)) {
92
+ values.push(parameters[binding.name]);
93
+ positions.set(binding.name, values.length);
94
+ }
95
+ text += sql.slice(at, binding.start) + "$" + positions.get(binding.name);
96
+ at = binding.end;
97
+ }
98
+ return { text: text + sql.slice(at), values };
99
+ }
36
100
  export const DB = Object.freeze({ Active: "active", RollbackOnly: "rollback_only", Failed: "failed" });
101
+ const loggingStore = Symbol.for("lango.logging");
102
+ const logging = globalThis[loggingStore] ?? { verbose: false };
103
+ globalThis[loggingStore] = logging;
37
104
  const contextStore = Symbol.for("lango.contexts");
38
105
  const contexts = globalThis[contextStore] ?? new Map();
39
106
  globalThis[contextStore] = contexts;
@@ -48,6 +115,8 @@ export class RuntimeConfigurationError extends Error {
48
115
  export function configure(options = {}) {
49
116
  if (options === null || typeof options !== "object" || Array.isArray(options))
50
117
  throw new RuntimeConfigurationError("runtime configuration must be an object");
118
+ if (options.verbose !== undefined && typeof options.verbose !== "boolean")
119
+ throw new RuntimeConfigurationError("runtime verbose must be boolean");
51
120
  const nextCatalog = options.catalog ?? {};
52
121
  const nextOutput = options.output ?? null;
53
122
  const nextDatabase = options.database_adapter ?? null;
@@ -57,38 +126,57 @@ export function configure(options = {}) {
57
126
  throw new RuntimeConfigurationError("runtime output must be a function or null");
58
127
  if (nextDatabase !== null && (typeof nextDatabase !== "object" && typeof nextDatabase !== "function"))
59
128
  throw new RuntimeConfigurationError("runtime database_adapter must be an object or null");
60
- catalog = nextCatalog;
129
+ let nextI18n;
130
+ try {
131
+ nextI18n = options.i18n ?? createI18n({
132
+ catalog: nextCatalog, catalogs: options.catalogs,
133
+ locale: options.locale, fallbackLocale: options.fallbackLocale,
134
+ timeZone: options.timeZone, currency: options.currency,
135
+ });
136
+ if (typeof nextI18n.translate !== "function" || typeof nextI18n.formatNumber !== "function" || typeof nextI18n.formatDate !== "function")
137
+ throw new TypeError("i18n requires translate, formatNumber and formatDate methods");
138
+ } catch (error) {
139
+ throw new RuntimeConfigurationError(error.message);
140
+ }
141
+ if (options.verbose !== undefined) logging.verbose = options.verbose;
142
+ defaultI18n = nextI18n;
61
143
  output = nextOutput;
144
+ if (database !== null) failedTransactions.delete(database);
62
145
  database = nextDatabase;
63
- failedTransaction = false;
146
+ if (database !== null) failedTransactions.delete(database);
64
147
  contexts.clear();
65
148
  return null;
66
149
  }
67
150
 
68
151
  function requireDatabase() {
69
- if (database === null) throw new Error("DatabaseNotConfigured");
70
- return database;
152
+ const stack = contexts.get("db");
153
+ const adapter = stack?.length ? stack.at(-1) : database;
154
+ if (adapter === null || adapter === undefined) throw new Error("DatabaseNotConfigured");
155
+ return adapter;
71
156
  }
72
157
 
73
158
  export function startTrans() {
74
- if (failedTransaction) throw new Error("TransactionFailed");
75
- requireDatabase().begin();
159
+ const adapter = requireDatabase();
160
+ if (failedTransactions.has(adapter)) throw new Error("TransactionFailed");
161
+ adapter.begin();
76
162
  return null;
77
163
  }
78
164
  export function commitTrans() {
79
- if (failedTransaction) throw new Error("TransactionFailed");
80
- requireDatabase().commit();
165
+ const adapter = requireDatabase();
166
+ if (failedTransactions.has(adapter)) throw new Error("TransactionFailed");
167
+ adapter.commit();
81
168
  return null;
82
169
  }
83
170
  export function rollbackTrans() {
84
171
  const adapter = requireDatabase();
85
172
  adapter.rollback();
86
- if (adapter.transactionState() === null) failedTransaction = false;
173
+ if (adapter.transactionState() === null) failedTransactions.delete(adapter);
87
174
  return null;
88
175
  }
89
176
  export function transState() {
90
- const state = requireDatabase().transactionState();
91
- return failedTransaction && state !== null ? DB.Failed : state;
177
+ const adapter = requireDatabase();
178
+ const state = adapter.transactionState();
179
+ return failedTransactions.has(adapter) && state !== null ? DB.Failed : state;
92
180
  }
93
181
 
94
182
  export class SqlError extends Error {
@@ -116,10 +204,16 @@ export function query(sql, parameterNames) {
116
204
  ]),
117
205
  );
118
206
  try {
119
- result = adapter.execute(sql, boundParameters);
207
+ if (failedTransactions.has(adapter)) throw new Error("TransactionFailed");
208
+ if (adapter.parameterStyle === "postgresql") {
209
+ const prepared = postgresQuery(sql, boundParameters);
210
+ result = adapter.execute(prepared.text, prepared.values);
211
+ } else result = adapter.execute(sql, boundParameters);
212
+ if (result && typeof result.then === "function")
213
+ throw new Error("SynchronousDatabaseAdapterRequired");
120
214
  } catch (error) {
121
215
  if (error?.transactionUnusable === true && adapter.transactionState() !== null)
122
- failedTransaction = true;
216
+ failedTransactions.add(adapter);
123
217
  throw new SqlError(error, sql);
124
218
  }
125
219
  rows = result.rows;
@@ -153,10 +247,14 @@ export function query(sql, parameterNames) {
153
247
  return proxy;
154
248
  }
155
249
 
156
- export function translate(template, values) {
157
- const translated = catalog[template] ?? template;
158
-
159
- return translated.replace(/\{(\d+)\}/g, (_, index) => String(values[index]));
250
+ export function translate(template, values, options = null) {
251
+ return contextGet("i18n").translate(template, values, options);
252
+ }
253
+ export function formatNumber(value, options = null) {
254
+ return contextGet("i18n").formatNumber(value, options);
255
+ }
256
+ export function formatDate(value, options = null) {
257
+ return contextGet("i18n").formatDate(value, options);
160
258
  }
161
259
 
162
260
  export function xmlEscape(value) {
@@ -247,7 +345,8 @@ export function println(value) {
247
345
  }
248
346
 
249
347
  const defaultLog = Object.freeze({
250
- debug(value) { console.debug(String(value)); return null; },
348
+ get verbose() { return logging.verbose || false; },
349
+ debug(value) { if (!defaultLog.verbose) return null; console.debug(String(value)); return null; },
251
350
  info(value) { console.info(String(value)); return null; },
252
351
  warn(value) { console.warn(String(value)); return null; },
253
352
  err(value) { console.error(String(value)); return null; },
@@ -584,6 +683,7 @@ export function withArity(callback, requiredPositions, name) {
584
683
  export function contextGet(name) {
585
684
  const stack = contexts.get(name);
586
685
  if ((!stack || stack.length === 0) && name === "log") return defaultLog;
686
+ if ((!stack || stack.length === 0) && name === "i18n") return defaultI18n ??= createI18n();
587
687
  if (!stack || stack.length === 0) {
588
688
  throw new Error(`Lango context is unavailable: ${name}`);
589
689
  }
@@ -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.