@inlang/paraglide-js 1.11.7 → 2.0.0-beta.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.
Files changed (247) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +20 -34
  3. package/bin/run.js +2 -2
  4. package/dist/adapter-utils/index.d.ts +6 -5
  5. package/dist/adapter-utils/index.d.ts.map +1 -0
  6. package/dist/adapter-utils/index.js +5 -422
  7. package/dist/adapter-utils/negotiation/language.d.ts +1 -0
  8. package/dist/adapter-utils/negotiation/language.d.ts.map +1 -0
  9. package/dist/adapter-utils/negotiation/language.js +137 -0
  10. package/dist/adapter-utils/negotiation/language.test.d.ts +1 -0
  11. package/dist/adapter-utils/negotiation/language.test.d.ts.map +1 -0
  12. package/dist/adapter-utils/negotiation/language.test.js +24 -0
  13. package/dist/adapter-utils/routing/detectLanguage.d.ts +1 -0
  14. package/dist/adapter-utils/routing/detectLanguage.d.ts.map +1 -0
  15. package/dist/adapter-utils/routing/detectLanguage.js +32 -0
  16. package/dist/adapter-utils/routing/detectLanguage.test.d.ts +1 -0
  17. package/dist/adapter-utils/routing/detectLanguage.test.d.ts.map +1 -0
  18. package/dist/adapter-utils/routing/detectLanguage.test.js +37 -0
  19. package/dist/adapter-utils/routing/resolveUserPathDefinition.test.d.ts +1 -0
  20. package/dist/adapter-utils/routing/resolveUserPathDefinition.test.d.ts.map +1 -0
  21. package/dist/adapter-utils/routing/resolveUserPathDefinition.test.js +35 -0
  22. package/dist/adapter-utils/routing/resolveUserPathDefinitions.d.ts +3 -3
  23. package/dist/adapter-utils/routing/resolveUserPathDefinitions.d.ts.map +1 -0
  24. package/dist/adapter-utils/routing/resolveUserPathDefinitions.js +22 -0
  25. package/dist/adapter-utils/routing/routeDefinitions.d.ts +1 -0
  26. package/dist/adapter-utils/routing/routeDefinitions.d.ts.map +1 -0
  27. package/dist/adapter-utils/routing/routeDefinitions.js +224 -0
  28. package/dist/adapter-utils/routing/routeDefinitions.test.d.ts +1 -0
  29. package/dist/adapter-utils/routing/routeDefinitions.test.d.ts.map +1 -0
  30. package/dist/adapter-utils/routing/routeDefinitions.test.js +234 -0
  31. package/dist/adapter-utils/routing/sortRoutes.d.ts +1 -0
  32. package/dist/adapter-utils/routing/sortRoutes.d.ts.map +1 -0
  33. package/dist/adapter-utils/routing/sortRoutes.js +135 -0
  34. package/dist/adapter-utils/routing/validatePathTranslations.d.ts +2 -2
  35. package/dist/adapter-utils/routing/validatePathTranslations.d.ts.map +1 -0
  36. package/dist/adapter-utils/routing/validatePathTranslations.js +98 -0
  37. package/dist/adapter-utils/routing/validatePathTranslations.test.d.ts +1 -0
  38. package/dist/adapter-utils/routing/validatePathTranslations.test.d.ts.map +1 -0
  39. package/dist/adapter-utils/routing/validatePathTranslations.test.js +121 -0
  40. package/dist/bundler-plugins/index.d.ts +3 -0
  41. package/dist/bundler-plugins/index.d.ts.map +1 -0
  42. package/dist/bundler-plugins/index.js +2 -0
  43. package/dist/bundler-plugins/rollup.d.ts +6 -0
  44. package/dist/bundler-plugins/rollup.d.ts.map +1 -0
  45. package/dist/bundler-plugins/rollup.js +3 -0
  46. package/dist/bundler-plugins/unplugin.d.ts +18 -0
  47. package/dist/bundler-plugins/unplugin.d.ts.map +1 -0
  48. package/dist/bundler-plugins/unplugin.js +68 -0
  49. package/dist/bundler-plugins/vite.d.ts +6 -0
  50. package/dist/bundler-plugins/vite.d.ts.map +1 -0
  51. package/dist/bundler-plugins/vite.js +3 -0
  52. package/dist/cli/commands/compile/command.d.ts +2 -2
  53. package/dist/cli/commands/compile/command.d.ts.map +1 -0
  54. package/dist/cli/commands/compile/command.js +38 -0
  55. package/dist/cli/commands/init/command.d.ts +7 -8
  56. package/dist/cli/commands/init/command.d.ts.map +1 -0
  57. package/dist/cli/commands/init/command.js +122 -0
  58. package/dist/cli/defaults.d.ts +4 -3
  59. package/dist/cli/defaults.d.ts.map +1 -0
  60. package/dist/cli/defaults.js +29 -0
  61. package/dist/cli/index.d.ts +11 -5
  62. package/dist/cli/index.d.ts.map +1 -0
  63. package/dist/cli/index.js +16 -696
  64. package/dist/cli/steps/check-for-uncomitted-changes.d.ts +3 -3
  65. package/dist/cli/steps/check-for-uncomitted-changes.d.ts.map +1 -0
  66. package/dist/cli/steps/check-for-uncomitted-changes.js +36 -0
  67. package/dist/cli/steps/initialize-inlang-project.d.ts +16 -12
  68. package/dist/cli/steps/initialize-inlang-project.d.ts.map +1 -0
  69. package/dist/cli/steps/initialize-inlang-project.js +190 -0
  70. package/dist/cli/steps/maybe-add-sherlock.d.ts +5 -6
  71. package/dist/cli/steps/maybe-add-sherlock.d.ts.map +1 -0
  72. package/dist/cli/steps/maybe-add-sherlock.js +36 -0
  73. package/dist/cli/steps/prompt-for-outdir.d.ts +3 -3
  74. package/dist/cli/steps/prompt-for-outdir.d.ts.map +1 -0
  75. package/dist/cli/steps/prompt-for-outdir.js +18 -0
  76. package/dist/cli/steps/run-compiler.d.ts +5 -5
  77. package/dist/cli/steps/run-compiler.d.ts.map +1 -0
  78. package/dist/cli/steps/run-compiler.js +13 -0
  79. package/dist/cli/steps/update-package-json.d.ts +4 -5
  80. package/dist/cli/steps/update-package-json.d.ts.map +1 -0
  81. package/dist/cli/steps/update-package-json.js +33 -0
  82. package/dist/cli/steps/update-ts-config.d.ts +5 -16
  83. package/dist/cli/steps/update-ts-config.d.ts.map +1 -0
  84. package/dist/cli/steps/update-ts-config.js +134 -0
  85. package/dist/cli/utils.d.ts +2 -2
  86. package/dist/cli/utils.d.ts.map +1 -0
  87. package/dist/cli/utils.js +19 -0
  88. package/dist/compiler/compile.d.ts +17 -22
  89. package/dist/compiler/compile.d.ts.map +1 -0
  90. package/dist/compiler/compile.js +42 -0
  91. package/dist/compiler/compile.test.d.ts +1 -0
  92. package/dist/compiler/compile.test.d.ts.map +1 -0
  93. package/dist/compiler/compile.test.js +81 -0
  94. package/dist/compiler/compileBundle.d.ts +20 -0
  95. package/dist/compiler/compileBundle.d.ts.map +1 -0
  96. package/dist/compiler/compileBundle.js +55 -0
  97. package/dist/compiler/compileExpression.d.ts +5 -0
  98. package/dist/compiler/compileExpression.d.ts.map +1 -0
  99. package/dist/compiler/compileExpression.js +41 -0
  100. package/dist/compiler/compileMessage.d.ts +7 -33
  101. package/dist/compiler/compileMessage.d.ts.map +1 -0
  102. package/dist/compiler/compileMessage.js +64 -0
  103. package/dist/compiler/compileMessage.test.d.ts +1 -0
  104. package/dist/compiler/compileMessage.test.d.ts.map +1 -0
  105. package/dist/compiler/compileMessage.test.js +74 -0
  106. package/dist/compiler/compilePattern.d.ts +6 -7
  107. package/dist/compiler/compilePattern.d.ts.map +1 -0
  108. package/dist/compiler/compilePattern.js +28 -0
  109. package/dist/compiler/compilePattern.test.d.ts +1 -0
  110. package/dist/compiler/compilePattern.test.d.ts.map +1 -0
  111. package/dist/compiler/compilePattern.test.js +67 -0
  112. package/dist/compiler/compileProject.d.ts +43 -0
  113. package/dist/compiler/compileProject.d.ts.map +1 -0
  114. package/dist/compiler/compileProject.js +110 -0
  115. package/dist/compiler/compileProject.test.d.ts +2 -0
  116. package/dist/compiler/compileProject.test.d.ts.map +1 -0
  117. package/dist/compiler/compileProject.test.js +639 -0
  118. package/dist/compiler/emit-dts.d.ts +7 -0
  119. package/dist/compiler/emit-dts.d.ts.map +1 -0
  120. package/dist/compiler/emit-dts.js +56 -0
  121. package/dist/compiler/emit-dts.test.d.ts +2 -0
  122. package/dist/compiler/emit-dts.test.d.ts.map +1 -0
  123. package/dist/compiler/emit-dts.test.js +43 -0
  124. package/dist/compiler/index.d.ts +7 -0
  125. package/dist/compiler/index.d.ts.map +1 -0
  126. package/dist/compiler/index.js +6 -0
  127. package/dist/compiler/jsDocComment.d.ts +9 -0
  128. package/dist/compiler/jsDocComment.d.ts.map +1 -0
  129. package/dist/compiler/jsDocComment.js +30 -0
  130. package/dist/compiler/output-structure/locale-modules.d.ts +4 -0
  131. package/dist/compiler/output-structure/locale-modules.d.ts.map +1 -0
  132. package/dist/compiler/output-structure/locale-modules.js +50 -0
  133. package/dist/compiler/output-structure/locale-modules.test.d.ts +2 -0
  134. package/dist/compiler/output-structure/locale-modules.test.d.ts.map +1 -0
  135. package/dist/compiler/output-structure/locale-modules.test.js +63 -0
  136. package/dist/compiler/output-structure/message-modules.d.ts +4 -0
  137. package/dist/compiler/output-structure/message-modules.d.ts.map +1 -0
  138. package/dist/compiler/output-structure/message-modules.js +57 -0
  139. package/dist/compiler/output-structure/message-modules.test.d.ts +2 -0
  140. package/dist/compiler/output-structure/message-modules.test.d.ts.map +1 -0
  141. package/dist/compiler/output-structure/message-modules.test.js +38 -0
  142. package/dist/compiler/registry.d.ts +14 -0
  143. package/dist/compiler/registry.d.ts.map +1 -0
  144. package/dist/compiler/registry.js +55 -0
  145. package/dist/compiler/runtime.d.ts +3 -3
  146. package/dist/compiler/runtime.d.ts.map +1 -0
  147. package/dist/compiler/runtime.js +158 -0
  148. package/dist/compiler/types.d.ts +11 -0
  149. package/dist/compiler/types.d.ts.map +1 -0
  150. package/dist/compiler/types.js +28 -0
  151. package/dist/index.d.ts +3 -4
  152. package/dist/index.d.ts.map +1 -0
  153. package/dist/index.js +2 -764
  154. package/dist/services/account/index.d.ts +15 -0
  155. package/dist/services/account/index.d.ts.map +1 -0
  156. package/dist/services/account/index.js +42 -0
  157. package/dist/services/codegen/escape.d.ts +1 -0
  158. package/dist/services/codegen/escape.d.ts.map +1 -0
  159. package/dist/services/codegen/escape.js +18 -0
  160. package/dist/services/codegen/identifier.d.ts +2 -3
  161. package/dist/services/codegen/identifier.d.ts.map +1 -0
  162. package/dist/services/codegen/identifier.js +11 -0
  163. package/dist/services/codegen/indentifier.test.d.ts +1 -0
  164. package/dist/services/codegen/indentifier.test.d.ts.map +1 -0
  165. package/dist/services/codegen/indentifier.test.js +8 -0
  166. package/dist/services/codegen/quotes.d.ts +3 -1
  167. package/dist/services/codegen/quotes.d.ts.map +1 -0
  168. package/dist/services/codegen/quotes.js +4 -0
  169. package/dist/services/env-variables/index.d.ts +6 -0
  170. package/dist/services/env-variables/index.d.ts.map +1 -0
  171. package/dist/services/env-variables/index.js +5 -0
  172. package/dist/services/environment/package.d.ts +3 -4
  173. package/dist/services/environment/package.d.ts.map +1 -0
  174. package/dist/services/environment/package.js +30 -0
  175. package/dist/services/environment/package.test.d.ts +1 -0
  176. package/dist/services/environment/package.test.d.ts.map +1 -0
  177. package/dist/services/environment/package.test.js +20 -0
  178. package/dist/services/error-handling.d.ts +4 -4
  179. package/dist/services/error-handling.d.ts.map +1 -0
  180. package/dist/services/error-handling.js +19 -0
  181. package/dist/services/error-handling.test.d.ts +1 -0
  182. package/dist/services/error-handling.test.d.ts.map +1 -0
  183. package/dist/services/error-handling.test.js +9 -0
  184. package/dist/services/file-handling/exists.d.ts +2 -3
  185. package/dist/services/file-handling/exists.d.ts.map +1 -0
  186. package/dist/services/file-handling/exists.js +23 -0
  187. package/dist/services/file-handling/exists.test.d.ts +1 -0
  188. package/dist/services/file-handling/exists.test.d.ts.map +1 -0
  189. package/dist/services/file-handling/exists.test.js +26 -0
  190. package/dist/services/file-handling/types.d.ts +5 -0
  191. package/dist/services/file-handling/types.d.ts.map +1 -0
  192. package/dist/services/file-handling/write-output.d.ts +3 -3
  193. package/dist/services/file-handling/write-output.d.ts.map +1 -0
  194. package/dist/services/file-handling/write-output.js +37 -0
  195. package/dist/services/file-handling/write-output.test.d.ts +1 -0
  196. package/dist/services/file-handling/write-output.test.d.ts.map +1 -0
  197. package/dist/services/file-handling/write-output.test.js +57 -0
  198. package/dist/services/logger/index.d.ts +1 -0
  199. package/dist/services/logger/index.d.ts.map +1 -0
  200. package/dist/services/logger/index.js +60 -0
  201. package/dist/services/lookup.d.ts +15 -0
  202. package/dist/services/lookup.d.ts.map +1 -0
  203. package/dist/services/lookup.js +23 -0
  204. package/dist/services/telemetry/capture.d.ts +16 -0
  205. package/dist/services/telemetry/capture.d.ts.map +1 -0
  206. package/dist/services/telemetry/capture.js +71 -0
  207. package/dist/services/telemetry/capture.test.d.ts +2 -0
  208. package/dist/services/telemetry/capture.test.d.ts.map +1 -0
  209. package/dist/services/telemetry/capture.test.js +40 -0
  210. package/dist/services/telemetry/events.d.ts +2 -1
  211. package/dist/services/telemetry/events.d.ts.map +1 -0
  212. package/dist/services/telemetry/stack-detection.d.ts +1 -0
  213. package/dist/services/telemetry/stack-detection.d.ts.map +1 -0
  214. package/dist/services/telemetry/stack-detection.js +82 -0
  215. package/dist/services/telemetry/stack-detection.test.d.ts +1 -0
  216. package/dist/services/telemetry/stack-detection.test.d.ts.map +1 -0
  217. package/dist/services/telemetry/stack-detection.test.js +39 -0
  218. package/dist/services/valid-js-identifier/index.d.ts +1 -0
  219. package/dist/services/valid-js-identifier/index.d.ts.map +1 -0
  220. package/dist/services/valid-js-identifier/index.js +24 -0
  221. package/dist/services/valid-js-identifier/index.test.d.ts +1 -0
  222. package/dist/services/valid-js-identifier/index.test.d.ts.map +1 -0
  223. package/dist/services/valid-js-identifier/index.test.js +30 -0
  224. package/dist/services/valid-js-identifier/reservedWords.d.ts +1 -0
  225. package/dist/services/valid-js-identifier/reservedWords.d.ts.map +1 -0
  226. package/dist/services/valid-js-identifier/reservedWords.js +50 -0
  227. package/dist/utilities/detect-json-formatting.d.ts +11 -0
  228. package/dist/utilities/detect-json-formatting.d.ts.map +1 -0
  229. package/dist/utilities/detect-json-formatting.js +79 -0
  230. package/package.json +46 -47
  231. package/default/index.d.ts +0 -1
  232. package/default/index.js +0 -1
  233. package/default/why.txt +0 -4
  234. package/dist/cli/steps/initialize-inlang-project.test.d.ts +0 -1
  235. package/dist/cli/steps/maybe-add-ninja.d.ts +0 -10
  236. package/dist/cli/steps.d.ts +0 -8
  237. package/dist/compiler/aliases.d.ts +0 -9
  238. package/dist/compiler/messageIndex.d.ts +0 -8
  239. package/dist/compiler/optionsType.d.ts +0 -3
  240. package/dist/compiler/optionsType.test.d.ts +0 -1
  241. package/dist/compiler/paramsType.d.ts +0 -11
  242. package/dist/compiler/paramsType.test.d.ts +0 -1
  243. package/dist/services/codegen/string-union.d.ts +0 -1
  244. package/dist/services/telemetry/implementation.d.ts +0 -24
  245. package/dist/services/telemetry/index.d.ts +0 -1
  246. /package/dist/{cli/commands/compile/command.test.d.ts → services/file-handling/types.js} +0 -0
  247. /package/dist/{cli/commands/init/command.test.d.ts → services/telemetry/events.js} +0 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Opral US Inc.
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.
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  # Getting started
4
4
 
5
- To use Paraglide standalone without a framework, run the following command:
5
+ To auto setup Paraglide JS, run the following command:
6
6
 
7
7
  ```bash
8
8
  npx @inlang/paraglide-js@latest init
@@ -10,68 +10,54 @@ npx @inlang/paraglide-js@latest init
10
10
 
11
11
  This will:
12
12
 
13
+ - Create an [inlang project](https://inlang.com/documentation/concept/project)
13
14
  - Install necessary dependencies
14
15
  - Generate a `messages/` folder where your translation files live
15
- - Add the Paraglide compiler to your `build` script in `package.json`
16
- - Create necessary configuration files
17
16
 
18
- Running the Paraglide compiler will generate a `src/paraglide` folder. This folder contains all the code that you will use in your app.
17
+ ## Adding and editing Messages
19
18
 
20
- ## Adding and Editing Messages
21
-
22
- Messages are stored in `messages/{lang}.json` as key-value pairs. You can add parameters with curly braces.
19
+ Messages are stored in `messages/{locale}.json` as key-value pairs. You can add parameters with curly braces.
23
20
 
24
21
  ```diff
25
22
  // messages/en.json
26
23
  {
27
- "$schema": "https://inlang.com/schema/inlang-message-format",
28
24
  + "greeting": "Hello {name}!"
29
25
  }
30
26
  ```
31
27
 
32
- Make sure to re-run the paraglide compiler after editing your messages.
28
+ Run the compiler via the CLI to generate the message functions.
33
29
 
34
30
  ```bash
35
31
  npx @inlang/paraglide-js compile --project ./project.inlang --outdir ./src/paraglide
36
32
  ```
37
33
 
38
- If you are using a Bundler use one of the [Bundler Plugins](usage#usage-with-a-bundler) to recompile automatically.
34
+ _If you are using a Bundler use one of the [Bundler Plugins](usage#usage-with-a-bundler) to recompile automatically._
39
35
 
40
- ## Using Messages in Code
36
+ ## Using messages in code
41
37
 
42
38
  After running the compiler import the messages with `import * as m from "./paraglide/messages"`. By convention, a wildcard import is used.
43
39
 
44
40
  ```js
45
- import * as m from "./paraglide/messages.js"
41
+ import * as m from "./paraglide/messages.js";
46
42
 
47
- m.hello() // Hello world!
48
- m.loginHeader({ name: "Samuel" }) // Hello Samuel, please login to continue.
43
+ m.greeting({ name: "Samuel" }); // Hello Samuel!
49
44
  ```
50
45
 
51
- # Playground
46
+ ## Changing the locale
52
47
 
53
- Find examples of how to use Paraglide on CodeSandbox or in [our GitHub repository](https://github.com/opral/monorepo/tree/main/inlang/source-code/paraglide).
48
+ To change the locale, use the `setLocale` function.
54
49
 
55
- <doc-links>
56
- <doc-link title="NextJS + Paraglide JS" icon="lucide:codesandbox" href="https://stackblitz.com/~/LorisSigrist/paraglide-next-app-router-example" description="Play around with NextJS and Paraglide JS"></doc-link>
57
- <doc-link title="Svelte + Paraglide JS" icon="lucide:codesandbox" href="https://stackblitz.com/~/github.com/LorisSigrist/paraglide-sveltekit-example" description="Play around with Svelte and Paraglide JS"></doc-link>
58
- <doc-link title="Astro + Paraglide JS" icon="lucide:codesandbox" href="https://stackblitz.com/~/github.com/LorisSigrist/paraglide-astro-example" description="Play around with Astro and Paraglide JS"></doc-link>
59
- </doc-links>
50
+ ```js
51
+ import { setLocale } from "./paraglide/runtime.js";
52
+ import * as m from "./paraglide/messages.js";
60
53
 
61
- # Roadmap
54
+ m.greeting({ name: "Samuel" }); // Hello Samuel!
62
55
 
63
- Of course, we're not done yet! We plan on adding the following features to Paraglide JS soon:
56
+ setLocale("de");
64
57
 
65
- - [ ] Pluralization ([Join the Discussion](https://github.com/opral/monorepo/discussions/2025))
66
- - [ ] Formatting of numbers and dates ([Join the Discussion](https://github.com/opral/monorepo/discussions/992))
67
- - [ ] Markup Placeholders ([Join the Discussion](https://github.com/opral/monorepo/discussions/913))
68
- - [ ] Component Interpolation
69
- - [ ] Per-Language Splitting without Lazy-Loading
70
- - [ ] Even Smaller Output
58
+ m.greeting({ name: "Samuel" }); // Guten Tag Samuel!
59
+ ```
71
60
 
72
- # Talks
61
+ ## Define your strategy
73
62
 
74
- - [Svelte Summit Spring 2023](https://www.youtube.com/watch?v=Y6IbPfMU1xM)
75
- - [Svelte Summit Fall 2023](https://www.youtube.com/watch?v=-YES3CCAG90)
76
- - Web Zurich December 2023
77
- - [Svelte London January 2024](https://www.youtube.com/watch?v=eswNQiq4T2w&t=646s)
63
+ In the last step, you need to define what strategy you want to use to resolve the locale. Visit the [strategy documentation](https://inlang.com/m/gerre34r/library-inlang-paraglideJs/strategy) to learn more.
package/bin/run.js CHANGED
@@ -1,4 +1,4 @@
1
1
  #!/usr/bin/env node
2
- import { cli } from "../dist/cli/index.js"
2
+ import { cli } from "../dist/cli/index.js";
3
3
 
4
- cli.parse()
4
+ cli.parse();
@@ -1,5 +1,6 @@
1
- export { negotiateLanguagePreferences } from './negotiation/language.js';
2
- export { detectLanguageFromPath } from './routing/detectLanguage.js';
3
- export { bestMatch, resolveRoute, parseRouteDefinition, type PathDefinitionTranslations, type ParamMatcher, type RouteParam, } from './routing/routeDefinitions.js';
4
- export { validatePathTranslations, prettyPrintPathDefinitionIssues, } from './routing/validatePathTranslations.js';
5
- export { resolveUserPathDefinitions, type UserPathDefinitionTranslations, } from './routing/resolveUserPathDefinitions.js';
1
+ export { negotiateLanguagePreferences } from "./negotiation/language.js";
2
+ export { detectLanguageFromPath } from "./routing/detectLanguage.js";
3
+ export { bestMatch, resolveRoute, parseRouteDefinition, type PathDefinitionTranslations, type ParamMatcher, type RouteParam, } from "./routing/routeDefinitions.js";
4
+ export { validatePathTranslations, prettyPrintPathDefinitionIssues, } from "./routing/validatePathTranslations.js";
5
+ export { resolveUserPathDefinitions, type UserPathDefinitionTranslations, } from "./routing/resolveUserPathDefinitions.js";
6
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/adapter-utils/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,4BAA4B,EAAE,MAAM,2BAA2B,CAAC;AACzE,OAAO,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AACrE,OAAO,EACN,SAAS,EACT,YAAY,EACZ,oBAAoB,EACpB,KAAK,0BAA0B,EAC/B,KAAK,YAAY,EACjB,KAAK,UAAU,GACf,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACN,wBAAwB,EACxB,+BAA+B,GAC/B,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EACN,0BAA0B,EAC1B,KAAK,8BAA8B,GACnC,MAAM,yCAAyC,CAAC"}
@@ -1,422 +1,5 @@
1
- function negotiateLanguagePreferences(accept, availableLanguageTags) {
2
- accept ||= "*";
3
- const acceptLanguageSpecs = parseAcceptLanguageHeader(accept);
4
- const priorities = availableLanguageTags.map(
5
- (languageTag, index) => getHighestLanguagePriority(languageTag, acceptLanguageSpecs, index)
6
- );
7
- return priorities.filter((prio) => prio.quality > 0).sort(bySpecificity).sort(byQuality).map((priority) => priority.languageTag);
8
- }
9
- function parseAcceptLanguageHeader(acceptLanguage) {
10
- return acceptLanguage.split(",").map((dfn) => dfn.trim()).map((dfn, index) => parseLanguage(dfn, index)).filter((maybeSpec) => Boolean(maybeSpec));
11
- }
12
- function parseLanguage(languageTag, index) {
13
- const LANGUAGE_REGEXP = /^\s*([^\s\-;]+)(?:-([^\s;]+))?\s*(?:;(.*))?$/;
14
- const match = LANGUAGE_REGEXP.exec(languageTag);
15
- if (!match)
16
- return void 0;
17
- const [, prefix, suffix, qualityMatch] = match;
18
- if (!prefix)
19
- throw new Error(`Invalid language tag: ${languageTag}`);
20
- const full = suffix ? `${prefix}-${suffix}` : prefix;
21
- const quality = parseQuality(qualityMatch ?? "") ?? 1;
22
- return {
23
- prefix,
24
- suffix,
25
- quality,
26
- index,
27
- full
28
- };
29
- }
30
- function parseQuality(qualityMatch) {
31
- return qualityMatch.split(";").map((param) => param.split("=")).filter((p) => p[0] == "q" && !!p[1]).map(([, value]) => parseFloat(value))[0];
32
- }
33
- function getHighestLanguagePriority(languageTag, acceptableLanguages, index) {
34
- const priorities = acceptableLanguages.map((spec) => calculatePriority(languageTag, spec, index)).filter((prio) => Boolean(prio));
35
- const highestPriority = priorities.sort(bySpecificity)[0] || {
36
- languageTag,
37
- index: 0,
38
- order: -1,
39
- quality: 0,
40
- specificity: 0
41
- };
42
- return highestPriority;
43
- }
44
- function calculatePriority(languageTag, spec, index) {
45
- const parsed = parseLanguage(languageTag, 0);
46
- if (!parsed)
47
- return void 0;
48
- let specificity = 0;
49
- if (spec.full.toLowerCase() === parsed.full.toLowerCase()) {
50
- specificity = 4;
51
- } else if (spec.prefix.toLowerCase() === parsed.full.toLowerCase()) {
52
- specificity = 2;
53
- } else if (spec.full.toLowerCase() === parsed.prefix.toLowerCase()) {
54
- specificity = 1;
55
- }
56
- if (specificity === 0 && spec.full !== "*")
57
- return void 0;
58
- return {
59
- languageTag,
60
- index,
61
- order: spec.index,
62
- quality: spec.quality,
63
- specificity
64
- };
65
- }
66
- const byQuality = (a, b) => b.quality - a.quality;
67
- const bySpecificity = (a, b) => b.specificity - a.specificity || a.order - b.order || a.index - b.index;
68
- function detectLanguageFromPath({
69
- path,
70
- availableLanguageTags,
71
- base
72
- }) {
73
- base ??= "";
74
- if (base === "/")
75
- base = "";
76
- if (!path.startsWith(base))
77
- return void 0;
78
- const pathWithoutBase = path.replace(base, "");
79
- const maybeLang = pathWithoutBase.split("/")[1];
80
- if (!maybeLang)
81
- return void 0;
82
- return availableLanguageTags.map(lower).includes(lower(maybeLang)) ? maybeLang : void 0;
83
- }
84
- const lower = (s) => s.toLowerCase();
85
- const STATIC = 0;
86
- const OPTIONAL = 1;
87
- const REST = 2;
88
- const REQUIRED = 4;
89
- const PART_TYPE = 0;
90
- const PART_CONTENT = 1;
91
- const PART_MATCHED = 2;
92
- function sort_routes(routes) {
93
- const get_parts = cached(split);
94
- return routes.sort((route_a, route_b) => {
95
- var _a, _b, _c, _d, _e, _f;
96
- const segments_a = split_route_id(route_a).map(get_parts);
97
- const segments_b = split_route_id(route_b).map(get_parts);
98
- for (let i = 0; i < Math.max(segments_a.length, segments_b.length); i += 1) {
99
- const segment_a = segments_a[i];
100
- const segment_b = segments_b[i];
101
- if (!segment_a)
102
- return -1;
103
- if (!segment_b)
104
- return 1;
105
- for (let j = 0; j < Math.max(segment_a.length, segment_b.length); j += 1) {
106
- const a = segment_a[j];
107
- const b = segment_b[j];
108
- const dynamic = (a == null ? void 0 : a[PART_TYPE]) || (b == null ? void 0 : b[PART_TYPE]);
109
- if (dynamic) {
110
- if (!a)
111
- return -1;
112
- if (!b)
113
- return 1;
114
- const next_a = ((_a = segment_a[j + 1]) == null ? void 0 : _a[PART_CONTENT]) || ((_c = (_b = segments_a[i + 1]) == null ? void 0 : _b[0]) == null ? void 0 : _c[PART_CONTENT]);
115
- const next_b = ((_d = segment_b[j + 1]) == null ? void 0 : _d[PART_CONTENT]) || ((_f = (_e = segments_b[i + 1]) == null ? void 0 : _e[0]) == null ? void 0 : _f[PART_CONTENT]);
116
- const both_have_next = next_a && next_b;
117
- const only_a_has_next = next_a && !next_b;
118
- const only_b_has_next = !next_a && next_b;
119
- if ((a[PART_TYPE] && b[PART_TYPE]) === REST) {
120
- if (both_have_next)
121
- continue;
122
- if (only_a_has_next)
123
- return -1;
124
- if (only_b_has_next)
125
- return 1;
126
- }
127
- if (a[PART_TYPE] === REST)
128
- return only_a_has_next ? -1 : 1;
129
- if (b[PART_TYPE] === REST)
130
- return only_b_has_next ? 1 : -1;
131
- if (a[PART_MATCHED] !== b[PART_MATCHED])
132
- return (-1) ** +a[PART_MATCHED];
133
- if (a[PART_TYPE] !== b[PART_TYPE]) {
134
- return (-1) ** +(a[PART_TYPE] > b[PART_TYPE]);
135
- }
136
- } else if ((a == null ? void 0 : a[PART_CONTENT]) !== (b == null ? void 0 : b[PART_CONTENT])) {
137
- return sort_static(a[PART_CONTENT], b[PART_CONTENT]);
138
- }
139
- }
140
- }
141
- return route_a < route_b ? 1 : -1;
142
- });
143
- }
144
- function cached(fn) {
145
- const cache = /* @__PURE__ */ new Map();
146
- return (arg) => {
147
- if (!cache.has(arg))
148
- cache.set(arg, fn(arg));
149
- return cache.get(arg);
150
- };
151
- }
152
- function split(id) {
153
- const parts = [];
154
- let i = 0;
155
- while (i <= id.length) {
156
- const start = id.indexOf("[", i);
157
- const entirelyStatic = start === -1;
158
- parts.push([STATIC, id.slice(i, entirelyStatic ? void 0 : start), false]);
159
- if (entirelyStatic)
160
- break;
161
- const type = id[start + 1] === "[" ? OPTIONAL : id[start + 1] === "." ? REST : REQUIRED;
162
- const endBrackets = type === OPTIONAL ? "]]" : "]";
163
- const endBracketIdx = id.indexOf(endBrackets, start);
164
- if (endBracketIdx === -1)
165
- throw new Error(`Invalid route definition ${id}`);
166
- const content = id.slice(start, i = endBracketIdx + endBrackets.length);
167
- parts.push([type, content, content.includes("=")]);
168
- }
169
- return parts;
170
- }
171
- const split_route_id = (id) => id.replace(/\[\[[^\]]+\]\](?!$)/g, "").split("/").filter(Boolean);
172
- function sort_static(a, b) {
173
- if (a === b)
174
- return 0;
175
- let idx = 0;
176
- while (a[idx] === b[idx])
177
- idx++;
178
- return !a[idx] ? 1 : !b[idx] ? -1 : a[idx] < b[idx] ? -1 : 1;
179
- }
180
- const param_pattern = /^(\[)?(\.\.\.)?(\w+)(?:=(\w+))?(\])?$/;
181
- function parseRouteDefinition(id) {
182
- const params = [];
183
- const pattern = id === "/" ? /^\/$/ : new RegExp(
184
- `^${get_route_segments(id).map((segment) => {
185
- const rest_match = /^\[\.\.\.(\w+)(?:=(\w+))?\]$/.exec(segment);
186
- if (rest_match) {
187
- params.push({
188
- name: rest_match[1],
189
- matcher: rest_match[2],
190
- optional: false,
191
- rest: true,
192
- chained: true
193
- });
194
- return "(?:/(.*))?";
195
- }
196
- const optional_match = /^\[\[(\w+)(?:=(\w+))?\]\]$/.exec(segment);
197
- if (optional_match) {
198
- params.push({
199
- name: optional_match[1],
200
- matcher: optional_match[2],
201
- optional: true,
202
- rest: false,
203
- chained: true
204
- });
205
- return "(?:/([^/]+))?";
206
- }
207
- if (!segment) {
208
- return;
209
- }
210
- const parts = segment.split(/\[(.+?)\](?!\])/);
211
- const result = parts.map((content, i) => {
212
- if (i % 2) {
213
- if (content.startsWith("x+")) {
214
- return escape(String.fromCharCode(parseInt(content.slice(2), 16)));
215
- }
216
- if (content.startsWith("u+")) {
217
- return escape(
218
- String.fromCharCode(
219
- ...content.slice(2).split("-").map((code) => parseInt(code, 16))
220
- )
221
- );
222
- }
223
- const match = (
224
- /** @type {RegExpExecArray} */
225
- param_pattern.exec(content)
226
- );
227
- if (!match) {
228
- throw new Error(`Invalid param: ${content}`);
229
- }
230
- const [, is_optional, is_rest, name, matcher] = match;
231
- params.push({
232
- name,
233
- matcher,
234
- optional: !!is_optional,
235
- rest: !!is_rest,
236
- chained: is_rest ? i === 1 && parts[0] === "" : false
237
- });
238
- return is_rest ? "(.*?)" : is_optional ? "([^/]*)?" : "([^/]+?)";
239
- }
240
- return escape(content);
241
- }).join("");
242
- return "/" + result;
243
- }).join("")}/?$`
244
- );
245
- return { pattern, params };
246
- }
247
- function exec(match, params, matchers) {
248
- const result = {};
249
- const values = match.slice(1);
250
- const values_needing_match = values.filter((v) => v !== void 0);
251
- let buffered = 0;
252
- for (const [i, param] of params.entries()) {
253
- let value = values[i - buffered];
254
- if (param.chained && param.rest && buffered) {
255
- value = values.slice(i - buffered, i + 1).filter((s) => s).join("/");
256
- buffered = 0;
257
- }
258
- if (value === void 0) {
259
- if (param.rest)
260
- result[param.name] = "";
261
- continue;
262
- }
263
- if (param.matcher && !matchers[param.matcher])
264
- return void 0;
265
- const matcher = matchers[param.matcher] ?? (() => true);
266
- if (matcher(value)) {
267
- result[param.name] = value;
268
- const next_param = params[i + 1];
269
- const next_value = values[i + 1];
270
- if (next_param && !next_param.rest && next_param.optional && next_value && param.chained) {
271
- buffered = 0;
272
- }
273
- if (!next_param && !next_value && Object.keys(result).length === values_needing_match.length) {
274
- buffered = 0;
275
- }
276
- continue;
277
- }
278
- if (param.optional && param.chained) {
279
- buffered++;
280
- continue;
281
- }
282
- return;
283
- }
284
- if (buffered)
285
- return;
286
- return result;
287
- }
288
- function escape(str) {
289
- return str.normalize().replace(/[[\]]/g, "\\$&").replace(/%/g, "%25").replace(/\//g, "%2[Ff]").replace(/\?/g, "%3[Ff]").replace(/#/g, "%23").replace(/[.*+?^${}()|\\]/g, "\\$&");
290
- }
291
- const basic_param_pattern = /\[(\[)?(\.\.\.)?(\w+?)(?:=(\w+))?\]\]?/g;
292
- function resolveRoute(id, params) {
293
- return "/" + get_route_segments(id).map(
294
- (segment) => segment.replace(basic_param_pattern, (_, optional, rest, name) => {
295
- const param_value = params[name];
296
- if (!param_value) {
297
- if (optional || rest && param_value !== void 0)
298
- return "";
299
- else
300
- throw new Error(`Missing parameter '${name}' in route ${id}`);
301
- }
302
- if (param_value[0] == "/" || param_value.endsWith("/"))
303
- throw new Error(`Parameter '${name}' in route ${id} cannot start or end with a slash`);
304
- return param_value;
305
- })
306
- ).filter(Boolean).join("/");
307
- }
308
- function bestMatch(canonicalPath, pathDefinitions, matchers) {
309
- const sorted = sort_routes(pathDefinitions);
310
- for (const pathDefinition of sorted) {
311
- const route = parseRouteDefinition(pathDefinition);
312
- const match = route.pattern.exec(removeTrailingSlash(canonicalPath));
313
- if (!match)
314
- continue;
315
- const params = exec(match, route.params, matchers);
316
- if (params)
317
- return { params, id: pathDefinition };
318
- }
319
- return void 0;
320
- }
321
- const removeTrailingSlash = (path) => path.endsWith("/") ? path.slice(0, -1) : path;
322
- const get_route_segments = (route) => route.slice(1).split("/");
323
- function validatePathTranslations(pathTranslations, availableLanguageTags, matchers) {
324
- const issues = [];
325
- const expectedLanguages = new Set(availableLanguageTags);
326
- const availableMatchers = new Set(Object.keys(matchers));
327
- for (const path in pathTranslations) {
328
- if (!isValidPath(path)) {
329
- issues.push({
330
- path,
331
- message: "Path must start with a slash."
332
- });
333
- continue;
334
- }
335
- const { params: expectedParams } = parseRouteDefinition(path);
336
- const expectedMatchers = expectedParams.map((param) => param.matcher).filter(Boolean);
337
- for (const matcher of expectedMatchers) {
338
- if (!availableMatchers.has(matcher)) {
339
- issues.push({
340
- path,
341
- message: `Matcher ${matcher} is used but not available. Did you forget to pass it to createI18n?`
342
- });
343
- }
344
- }
345
- const translations = pathTranslations[path];
346
- if (!translations)
347
- continue;
348
- for (const [lang, translatedPath] of Object.entries(translations)) {
349
- if (!isValidPath(translatedPath)) {
350
- issues.push({
351
- path,
352
- message: `The translation for language ${lang} must start with a slash.`
353
- });
354
- }
355
- const { params: actualParams } = parseRouteDefinition(translatedPath);
356
- let paramsDontMatch = false;
357
- for (const param of expectedParams) {
358
- if (!actualParams.some((actualParam) => paramsAreEqual(param, actualParam))) {
359
- paramsDontMatch = true;
360
- }
361
- }
362
- if (expectedParams.length !== actualParams.length) {
363
- paramsDontMatch = true;
364
- }
365
- if (paramsDontMatch) {
366
- issues.push({
367
- path,
368
- message: `The translation for language ${lang} must have the same parameters as the canonical path.`
369
- });
370
- }
371
- }
372
- const translatedLanguages = new Set(Object.keys(translations));
373
- if (!isSubset(expectedLanguages, translatedLanguages)) {
374
- const missingLanguages = new Set(expectedLanguages);
375
- for (const lang of translatedLanguages) {
376
- missingLanguages.delete(lang);
377
- }
378
- issues.push({
379
- path,
380
- message: `The following languages are missing translations: ${[...missingLanguages].join(
381
- ", "
382
- )}`
383
- });
384
- }
385
- }
386
- return issues;
387
- }
388
- function paramsAreEqual(param1, param2) {
389
- return param1.chained == param2.chained && param1.matcher == param2.matcher && param1.name == param2.name && param1.optional == param2.optional && param1.rest == param2.rest;
390
- }
391
- function isValidPath(maybePath) {
392
- return maybePath.startsWith("/");
393
- }
394
- function isSubset(a, b) {
395
- for (const value of a) {
396
- if (!b.has(value))
397
- return false;
398
- }
399
- return true;
400
- }
401
- function prettyPrintPathDefinitionIssues(issues) {
402
- return issues.map((issue) => `${issue.path}: ${issue.message}`).join("\n");
403
- }
404
- const resolveUserPathDefinitions = (userTranslations, availableLanguageTags) => Object.fromEntries(
405
- Object.entries(userTranslations).map(([path, translation]) => [
406
- path,
407
- typeof translation === "object" ? translation : fromMessage(translation, availableLanguageTags)
408
- ])
409
- );
410
- const fromMessage = (message, availableLanguageTags) => Object.fromEntries(
411
- availableLanguageTags.map((languageTag) => [languageTag, message({}, { languageTag })])
412
- );
413
- export {
414
- bestMatch,
415
- detectLanguageFromPath,
416
- negotiateLanguagePreferences,
417
- parseRouteDefinition,
418
- prettyPrintPathDefinitionIssues,
419
- resolveRoute,
420
- resolveUserPathDefinitions,
421
- validatePathTranslations
422
- };
1
+ export { negotiateLanguagePreferences } from "./negotiation/language.js";
2
+ export { detectLanguageFromPath } from "./routing/detectLanguage.js";
3
+ export { bestMatch, resolveRoute, parseRouteDefinition, } from "./routing/routeDefinitions.js";
4
+ export { validatePathTranslations, prettyPrintPathDefinitionIssues, } from "./routing/validatePathTranslations.js";
5
+ export { resolveUserPathDefinitions, } from "./routing/resolveUserPathDefinitions.js";
@@ -7,3 +7,4 @@
7
7
  * @returns The acceptable available language tags in descending order of preference
8
8
  */
9
9
  export declare function negotiateLanguagePreferences<T extends string = string>(accept: string | undefined | null, availableLanguageTags: readonly T[]): T[];
10
+ //# sourceMappingURL=language.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"language.d.ts","sourceRoot":"","sources":["../../../src/adapter-utils/negotiation/language.ts"],"names":[],"mappings":"AA+EA;;;;;;;GAOG;AACH,wBAAgB,4BAA4B,CAAC,CAAC,SAAS,MAAM,GAAG,MAAM,EACrE,MAAM,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI,EACjC,qBAAqB,EAAE,SAAS,CAAC,EAAE,GACjC,CAAC,EAAE,CAkBL"}