Compare commits

..
Author SHA1 Message Date
github-actions[bot]andSasha Sorokin 016c6938b8 Version Packages 2023-05-07 05:38:43 +02:00
Sasha Sorokin 25b5acfdd4 Don't require additionalImports to be a non-empty array 2023-05-07 05:36:36 +02:00
github-actions[bot]andSasha Sorokin 67168d2d2e Version Packages 2023-05-03 13:24:11 +02:00
Sasha Sorokin 71b900075f Fix object import sources not resolving by default 2023-05-03 13:06:40 +02:00
Sasha Sorokin 26354bacc9 Improve writing of warning about the descriptions in descriptors 2023-04-29 15:08:04 +02:00
Sasha Sorokin 566bf1561a Fix docs links after moving to Netlify 2023-04-29 14:56:09 +02:00
github-actions[bot] d451794575 Version Packages 2023-04-29 12:24:48 +00:00
Sasha Sorokin 70c440e3df Fix arrays of imports having incorrect types 2023-04-29 13:28:02 +02:00
Sasha Sorokin 439c3c6b0a Fix release workflow 2023-04-27 19:09:42 +02:00
github-actions[bot]andSasha Sorokin 0b944a49ef Version Packages 2023-04-27 18:46:58 +02:00
Sasha SorokinandGitHub d12429ccca Add option to opt out of the import resolution (#11)
* Add option to opt out of the import resolution

* Add docs on resolve option

* Promote to minor update

* Mention of UnspecifiedImportSource in `additionalImports` opt of Locale

* Prettier formatting

* Fix UnspecifiedImportSource updates in docs
2023-04-27 18:40:17 +02:00
github-actions[bot]andSasha Sorokin 68dd4ab524 Version Packages 2023-04-26 01:10:57 +02:00
Sasha Sorokin 56a2b8ce74 Fix docs introduction page 2023-04-26 00:46:33 +02:00
Sasha Sorokin 8554729423 Restore legacy resolution fields to package.json 2023-04-26 00:37:49 +02:00
github-actions[bot]andSasha Sorokin 8a030dfbe6 Version Packages 2023-04-25 22:22:19 +02:00
Sasha Sorokin bfca7c27ab Export types with shims instead of module types directly 2023-04-25 22:04:50 +02:00
Sasha Sorokin b65df861cc Fix edit on gh link in docs 2023-04-25 19:21:53 +02:00
github-actions[bot]andSasha Sorokin 8cffade11e Version Packages 2023-04-25 09:45:22 +02:00
Sasha Sorokin 8b2deee771 Add .vercel dir to list of nuxt build outputs 2023-04-25 09:05:27 +02:00
Sasha Sorokin d5d00b1ea6 Fix double buildStart call error during the build
(potentially)
2023-04-25 08:38:40 +02:00
Sasha Sorokin bb33034468 Fix release workflow permissions 2023-04-25 06:22:41 +02:00
Sasha Sorokin 5bb8d765c2 Initial release changeset 2023-04-25 06:15:09 +02:00
Sasha Sorokin 4f7dcad0da Remove unused defu dependency 2023-04-25 06:15:09 +02:00
Sasha Sorokin 64d0fa2c06 Add funding page
As terrible as it feels to beg I probably have to
2023-04-25 05:53:31 +02:00
Sasha Sorokin 7e5509a291 Add warnings about production in README and introduction doc 2023-04-25 05:52:14 +02:00
Sasha Sorokin 5930913f5f Fix headings on hooks docs page 2023-04-25 05:51:09 +02:00
Sasha Sorokin 23be78b633 Remove incorrect ‘privatePackages’ field from changesets config 2023-04-25 05:50:36 +02:00
Sasha Sorokin d7e7a8c4e1 Initial work on READMEs 2023-04-25 04:44:38 +02:00
Sasha Sorokin 94a2a57cd7 Add release workflow
I have no clue if it's going to work but let's pray that it does
2023-04-24 23:00:42 +02:00
Sasha Sorokin 54a659dc1b Add @changesets/cli package 2023-04-24 19:26:06 +02:00
Sasha Sorokin c5934349a6 Add prepack task to nuxt-intl-monorepo 2023-04-24 19:23:40 +02:00
Sasha Sorokin 5f9690a6bc Initial versioning 2023-04-24 19:23:05 +02:00
Sasha Sorokin e8076aa8e3 Fix docs message format
Haha what a funny bug
2023-04-24 06:22:55 +02:00
Sasha Sorokin 3a35f7bccf Properly register VIntl unplugin 2023-04-24 04:55:34 +02:00
Sasha Sorokin ff84113afc Change the default message loading order in parserless mode 2023-04-24 04:52:04 +02:00
Sasha Sorokin 5970d7ac3e Actually remove the parser in parserless mode 2023-04-24 04:03:39 +02:00
Sasha Sorokin 3cfea86a30 Extend @nuxt/kit to have webpack dep for types 2023-04-24 04:03:10 +02:00
Sasha Sorokin 29bd0edbaf Enable cache for ESLint 2023-04-23 22:10:31 +02:00
Sasha Sorokin 8caeec200f Fix ESLint warnings 2023-04-23 22:05:59 +02:00
Sasha Sorokin 389642100d Add vintl-nuxt stubs to runtime tsconfig 2023-04-23 21:44:39 +02:00
Sasha Sorokin 6caa4eec1a Fix ESLint ignorePatterns
Relative patterns should start with / rather than ./, bruh
2023-04-23 21:44:39 +02:00
Sasha Sorokin fe066dd97d Eject nuxt/eslint-config to update it for TS 5 2023-04-23 21:44:39 +02:00
Sasha Sorokin e43466938b Fix .vue extra ESLint extension 2023-04-23 21:26:38 +02:00
Sasha Sorokin d7df2f466c Add root lint scripts for all projects 2023-04-23 19:05:44 +02:00
Sasha Sorokin a3ed91a43d Make lint task dependent on dev:prepare 2023-04-23 19:05:14 +02:00
Sasha Sorokin eb29a87f1f Get rid of .eslintignore files 2023-04-23 18:50:53 +02:00
Sasha Sorokin e887574b65 Make ESLint VSC extension work 2023-04-23 18:37:59 +02:00
Sasha Sorokin 35e136e9b0 Apply ESLint fixes 2023-04-23 17:51:36 +02:00
Sasha Sorokin f7bef4719b Disable newline Vue lint rule as it is incompatible with Prettier 2023-04-23 17:23:46 +02:00
Sasha Sorokin bff2068152 Share ESLint config and use it per project 2023-04-23 17:19:25 +02:00
Sasha Sorokin c7725d933c Move Nuxt config to dev deps 2023-04-23 15:54:16 +02:00
Sasha Sorokin 4399c04a1e Remove unused static tsconfig from docs 2023-04-23 15:29:07 +02:00
Sasha Sorokin 0a80037b6d Configs cleanup 2023-04-23 12:26:22 +00:00
Sasha Sorokin a171d3aeb6 Fix repo link on landing page 2023-04-23 00:13:24 +00:00
Sasha Sorokin 6d87db8135 Add packageManager to root repo 2023-04-22 23:32:23 +00:00
Sasha Sorokin 18cc4b0d9f Use caret ranges of workspace packages in playground and docs 2023-04-22 23:31:21 +00:00
Sasha Sorokin 6eb737e015 Remove excessive playground dependencies 2023-04-22 23:29:40 +00:00
Sasha Sorokin 3c12c0df6a Update playground Nuxt version 2023-04-22 23:27:56 +00:00
Sasha Sorokin 05c0313c19 Clean up tasks 2023-04-22 23:24:49 +00:00
Sasha Sorokin a281fcc98d Restore theme tokens from bak file 2023-04-22 23:12:58 +00:00
Sasha Sorokin 28ae7975e1 Add require export to the module 2023-04-22 23:12:42 +00:00
Sasha Sorokin 0ed58ada2e Initial commit 2023-04-22 22:51:22 +02:00
335 changed files with 14543 additions and 42869 deletions
-3
View File
@@ -1,3 +0,0 @@
# Windows has stack overflows when calling from Tauri, so we increase compiler size
[target.'cfg(windows)']
rustflags = ["-C", "link-args=/STACK:16777220"]
+8
View File
@@ -0,0 +1,8 @@
# Changesets
Hello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that works
with multi-package repos, or single-package repos to help you version and publish your code. You can
find the full documentation for it [in our repository](https://github.com/changesets/changesets)
We have a quick list of common questions to get you started engaging with this project in
[our documentation](https://github.com/changesets/changesets/blob/main/docs/common-questions.md)
+11
View File
@@ -0,0 +1,11 @@
{
"$schema": "https://unpkg.com/@changesets/config@2.3.0/schema.json",
"changelog": "@changesets/cli/changelog",
"commit": false,
"fixed": [],
"linked": [],
"access": "public",
"baseBranch": "main",
"updateInternalDependencies": "patch",
"ignore": []
}
-37
View File
@@ -1,37 +0,0 @@
name: Bug report
description: Create a report to help us improve Modrinth
labels: [bug]
body:
- type: textarea
attributes:
label: Describe the bug
description: A clear and concise description of what the bug is.
validations:
required: false
- type: textarea
attributes:
label: Steps to reproduce
description: Steps to reproduce the behavior.
placeholder: |
1. Go to '...'
2. Click on '...'
3. Scroll down to '...'
4. See error
validations:
required: false
- type: textarea
attributes:
label: Expected behavior
description: A clear and concise description of what you expected to happen.
validations:
required: false
- type: textarea
attributes:
label: System information
description: Add any information about what OS you are on (like Windows or Mac), and what version of the app you are using.
- type: textarea
attributes:
label: Additional context
description: Add any other context about the problem here. This might include logs, screenshots, etc. The more the merrier!
validations:
required: false
-16
View File
@@ -1,16 +0,0 @@
blank_issues_enabled: true
contact_links:
- name: Discord
about: Ask questions on our Discord Server.
url: https://discord.modrinth.com
- name: Roadmap
about: View our Roadmap. Please do not open issues for items on our roadmap.
url: https://roadmap.modrinth.com
- name: Discussions (Feature requests)
about: |
Please use Issues for reporting bugs and suggesting enhancements to existing features.
Suggestions for new features should be made as a Discussion.
url: https://github.com/orgs/modrinth/discussions/categories/feature-requests
- name: Documentation
about: Useful documentation about Modrinth, its API, and how you can contribute.
url: https://docs.modrinth.com
-28
View File
@@ -1,28 +0,0 @@
name: Enhancement
description: Suggest an enhancement for an existing Modrinth feature
labels: [enhancement]
body:
- type: textarea
attributes:
label: Is your suggested enhancement related to a problem? Please describe.
description: A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
validations:
required: false
- type: textarea
attributes:
label: Describe the solution you'd like
description: A clear and concise description of what you want to happen.
validations:
required: false
- type: textarea
attributes:
label: Describe alternatives you've considered
description: A clear and concise description of any alternative solutions or features you've considered.
validations:
required: false
- type: textarea
attributes:
label: Additional context
description: Add any other context or screenshots about the suggested enhancement here.
validations:
required: false
-42
View File
@@ -1,42 +0,0 @@
name: GUI Build + Lint
on:
push:
branches: [master]
pull_request:
jobs:
build:
runs-on: ubuntu-latest
defaults:
run:
working-directory: ./theseus_gui
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Use Node.js
uses: actions/setup-node@v3
with:
node-version: 18.x
- name: Install pnpm via corepack
shell: bash
run: |
corepack enable
corepack prepare --activate
- name: Get pnpm store directory
id: pnpm-cache
shell: bash
run: |
echo "STORE_PATH=$(pnpm store path)" >> $GITHUB_OUTPUT
- name: Setup pnpm cache
uses: actions/cache@v3
with:
path: ${{ steps.pnpm-cache.outputs.STORE_PATH }}
key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}
restore-keys: |
${{ runner.os }}-pnpm-store-
- name: Install dependencies
run: pnpm install
- name: Run Lint
run: pnpm lint
- name: Build
run: pnpm build
+63
View File
@@ -0,0 +1,63 @@
name: Test and release
on:
push:
branches: [main, next, alpha, beta, rc]
jobs:
release:
runs-on: ubuntu-latest
permissions:
id-token: write
contents: write
packages: write
pull-requests: write
issues: read
if: >-
!contains(github.event.head_commit.message, '[skip ci]')
&& !contains(github.event.head_commit.message, '[ci skip]')
&& !contains(github.event.head_commit.message, '[auto]')
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Set up Node.js
uses: actions/setup-node@v3
with:
node-version: 18.x
- name: Install pnpm via corepack
shell: bash
run: |
corepack enable
corepack prepare --activate
- name: Get pnpm store directory
id: pnpm-cache
shell: bash
run: |
echo "STORE_PATH=$(pnpm store path)" >> $GITHUB_OUTPUT
- uses: actions/cache@v3
name: Setup pnpm cache
with:
path: ${{ steps.pnpm-cache.outputs.STORE_PATH }}
key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}
restore-keys: |
${{ runner.os }}-pnpm-store-
- name: Install dependencies
run: pnpm install
- name: Create release PR or publish to npm
if: github.repository_owner == 'vintl-dev'
id: changesets
uses: changesets/action@v1
with:
publish: pnpm _ci:publish
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
-109
View File
@@ -1,109 +0,0 @@
name: 'Tauri GUI Build'
on:
push:
branches: [ master ]
pull_request:
jobs:
test-tauri:
strategy:
fail-fast: false
matrix:
platform: [macos-latest, windows-latest, ubuntu-20.04, ubuntu-22.04]
runs-on: ${{ matrix.platform }}
defaults:
run:
working-directory: ./theseus_gui
steps:
- uses: actions/checkout@v3
- name: Rust setup (mac)
if: startsWith(matrix.platform, 'macos')
uses: dtolnay/rust-toolchain@stable
with:
components: rustfmt, clippy
targets: aarch64-apple-darwin
- name: Rust setup
if: "!startsWith(matrix.platform, 'macos')"
uses: dtolnay/rust-toolchain@stable
with:
components: rustfmt, clippy
- name: Rust cache
uses: swatinem/rust-cache@v2
with:
workspaces: './src-tauri -> target'
- name: Use Node.js
uses: actions/setup-node@v3
with:
node-version: 18.x
- name: Install pnpm via corepack
shell: bash
run: |
corepack enable
corepack prepare --activate
- name: Get pnpm store directory
id: pnpm-cache
shell: bash
run: |
echo "STORE_PATH=$(pnpm store path)" >> $GITHUB_OUTPUT
- name: Setup pnpm cache
uses: actions/cache@v3
with:
path: ${{ steps.pnpm-cache.outputs.STORE_PATH }}
key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}
restore-keys: |
${{ runner.os }}-pnpm-store-
- name: install dependencies (ubuntu only)
if: startsWith(matrix.platform, 'ubuntu')
run: |
sudo apt-get update
sudo apt-get install -y libgtk-3-dev libwebkit2gtk-4.0-dev libappindicator3-dev librsvg2-dev patchelf libselinux1
- name: Install frontend dependencies
run: pnpm install
- name: build app (macos)
uses: tauri-apps/tauri-action@v0
id: build_os_mac
if: startsWith(matrix.platform, 'macos')
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
ENABLE_CODE_SIGNING: ${{ secrets.APPLE_CERTIFICATE }}
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
APPLE_SIGNING_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY }}
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
TAURI_PRIVATE_KEY: ${{ secrets.TAURI_PRIVATE_KEY }}
TAURI_KEY_PASSWORD: ${{ secrets.TAURI_KEY_PASSWORD }}
with:
args: --target universal-apple-darwin
- name: build app
uses: tauri-apps/tauri-action@v0
id: build_os
if: "!startsWith(matrix.platform, 'macos')"
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAURI_PRIVATE_KEY: ${{ secrets.TAURI_PRIVATE_KEY }}
TAURI_KEY_PASSWORD: ${{ secrets.TAURI_KEY_PASSWORD }}
- name: upload ${{ matrix.platform }}
uses: actions/upload-artifact@v3
if: startsWith(matrix.platform, 'macos')
with:
name: ${{ matrix.platform }}
path: "${{ join(fromJSON(steps.build_os_mac.outputs.artifactPaths), '\n') }}"
- name: upload ${{ matrix.platform }}
uses: actions/upload-artifact@v3
if: "!startsWith(matrix.platform, 'macos')"
with:
name: ${{ matrix.platform }}
path: "${{ join(fromJSON(steps.build_os.outputs.artifactPaths), '\n') }}"
+55 -115
View File
@@ -1,115 +1,55 @@
/target
node_modules/
.svelte-kit/
theseus_gui/build/
theseus_gui/generated/
WixTools
.direnv/
.DS_Store
.pnpm-debug.log
minecraft
config
[#]*[#]
# TEMPORARY: ignore my test instance and metadata
theseus_cli/foo
### Intellij+all ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
# AWS User-specific
.idea/**/aws.xml
# Generated files
.idea/**/contentModel.xml
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/artifacts
# .idea/compiler.xml
# .idea/jarRepositories.xml
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# *.iml
# *.ipr
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# SonarLint plugin
.idea/sonarlint/
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser
### Intellij+all Patch ###
# Ignore everything but code style settings and run configurations
# that are supposed to be shared within teams.
.idea/*
.vscode/*
!.idea/codeStyles
!.idea/runConfigurations
# These are backup files generated by rustfmt
**/*.rs.bk
# MSVC Windows builds of rustc generate these, which store debugging information
*.pdb
theseus.iml
# Created by https://www.toptal.com/developers/gitignore/api/node
# Edit at https://www.toptal.com/developers/gitignore?templates=node
### Node ###
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Dependency directories
node_modules/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
dist
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
# End of https://www.toptal.com/developers/gitignore/api/node
# Turborepo cache
.turbo
.vscode/*
# Don't ignore VS Code settings that configure ESLint extension
!.vscode/settings.json
+1
View File
@@ -0,0 +1 @@
shamefully-hoist=true
+1
View File
@@ -0,0 +1 @@
apps/docs/content/0.index.md
+6
View File
@@ -0,0 +1,6 @@
{
"trailingComma": "all",
"singleQuote": true,
"semi": false,
"plugins": ["prettier-plugin-jsdoc"]
}
+3
View File
@@ -0,0 +1,3 @@
{
"eslint.workingDirectories": [{ "mode": "auto" }]
}
-13
View File
@@ -1,13 +0,0 @@
# Copying
The source code of the theseus repository is licensed under the GNU General Public License, Version 3 only, which is provided in the file [LICENSE](./LICENSE). However, some files listed below are licensed under a different license.
## Modrinth logo
Any files depicting the Modrinth branding, including the wrench-in-labyrinth logo, the landing image, and variations thereof, are licensed as follows:
> All rights reserved. © 2020-2023 Rinth, Inc.
This includes, but may not be limited to, the following files:
- theseus_gui/src-tauri/icons/*
Generated
-6712
View File
File diff suppressed because it is too large Load Diff
-27
View File
@@ -1,27 +0,0 @@
[workspace]
members = [
"theseus",
"theseus_playground",
"theseus_gui/src-tauri",
"theseus_macros"
]
[profile.dev]
opt-level = 0
debug = true
debug-assertions = true
overflow-checks = true
lto = false
panic = 'unwind'
incremental = true
codegen-units = 256
rpath = false
# Optimize for speed and reduce size on release builds
[profile.release]
panic = "abort" # Strip expensive panic clean-up logic
codegen-units = 1 # Compile crates one after another so the compiler can optimize better
lto = true # Enables link to optimizations
opt-level = "s" # Optimize for binary size
strip = true # Remove debug symbols
+21 -674
View File
@@ -1,674 +1,21 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
MIT License
Copyright (c) Alexander 'Brawaru' Sorokin <https://github.com/brawaru>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+71 -9
View File
@@ -1,9 +1,71 @@
# theseus
A game launcher which can be used as a CLI, GUI, and a library for creating and playing modrinth projects
Theseus aims to provide three components:
- A library (theseus)
- A CLI (theseus-cli)
- A GUI (theseus-gui)
Feel free to contribute!
# VIntl for Nuxt monorepo
This monorepo hosts the VIntl for Nuxt module as well as other projects that help building it.
## Project structure
**Legend**: 🔒 Private · 🌐 Website
### Apps
- [Playground](https://github.com/vintl-dev/nuxt/tree/main/apps/playground) 🔒
- [Docs](https://github.com/vintl-dev/nuxt/tree/main/apps/docs) 🔒 [🌐](https://vintl-nuxt.netlify.app/)
### Packages
- [VIntl for Nuxt module](https://github.com/vintl-dev/nuxt/tree/main/packages/vintl-nuxt)
- [ESLint config](https://github.com/vintl-dev/nuxt/tree/main/packages/eslint-config) 🔒
- [Playground translations](https://github.com/vintl-dev/nuxt/tree/main/packages/translations) 🔒
## Working with this monorepo
If you want to contribute a change or just want to try some changes in the project, follow the instruction below to get started.
> **Note** Corepack is recommended! It allows you to quickly switch package managers and their versions. As this monorepo uses pnpm, it is specified in root `package.json`, so you can use `corepack prepare --activate` to quickly switch to the version recommended for this repository. See [corepack docs](https://nodejs.org/api/corepack.html) for details.
1. **Clone the repository**
```bash
git clone https://github.com/vintl-dev/nuxt.git vintl-nuxt
cd vintl-nuxt
```
2. **Install dependencies**
```bash
pnpm install
```
3. **Prepare apps** (optional)
This will build the module and prepare all the apps, such as sandbox and docs.
```
pnpm all:prepare
```
4. **Build module**
```bash
pnpm mod:build
```
5. **Start playground**
Running playground in dev mode you can play and test that the module works in a regular Nuxt project.
```bash
pnpm pg:dev
```
6. **Create a changeset**
If you want to make a contribution to the module, make a changeset. This will ask you about the level of change (patch, minor or major) and the description of the change made.
You don't need changesets for private packages (like playground).
```bash
pnpm changeset
```
> **Warning** Do not run commands like `pnpm add` when your working directory is not set to the monorepo root. `pnpm` seems to ignore top-level `.npmrc` and will reinstall dependency tree in a manner currently incompatible with Nuxt. Use `pnpm --filter <pkg/relative-path> add` from the root. A lot of convenient scripts utilising Turborepo are also available in monorepo's `package.json`. You rarely need to `cd` into subdirectories.
+17
View File
@@ -0,0 +1,17 @@
{
"root": true,
"extends": ["@vintl-dev/eslint-config-peony"],
"overrides": [
{
"files": ["./**/*.{ts,tsx,vue}"],
"parserOptions": {
"project": "./tsconfig.json"
},
"rules": {
"vue/max-attributes-per-line": "off",
"vue/multi-word-component-names": "off"
}
}
],
"ignorePatterns": ["/.nuxt", "/.output"]
}
+12
View File
@@ -0,0 +1,12 @@
node_modules
*.iml
.idea
*.log*
.nuxt
.vscode
.DS_Store
coverage
dist
sw.*
.env
.output
+1
View File
@@ -0,0 +1 @@
shamefully-hoist=true
+3
View File
@@ -0,0 +1,3 @@
# VIntl for Nuxt documentation website
A documentation website for the VIntl for Nuxt package created using [Docus](https://docus.dev).
+33
View File
@@ -0,0 +1,33 @@
export default defineAppConfig({
docus: {
title: 'VIntl for Nuxt',
description: 'Internationalization for your Nuxt apps',
url: 'https://vintl-nuxt.netlify.app',
// image: '/social-card-preview.png',
socials: {
github: 'vintl-dev/nuxt',
},
github: {
dir: 'apps/docs/content',
repo: 'nuxt',
owner: 'vintl-dev',
branch: 'main',
edit: true,
},
layout: 'default',
header: {
title: 'VIntl for Nuxt',
logo: false,
showLinkIcon: false,
},
footer: {
credits: {
icon: 'IconDocus',
text: 'Powered by Docus',
href: 'https://docus.dev',
},
textLinks: [],
iconLinks: [],
},
},
})
@@ -0,0 +1,8 @@
<script setup lang="ts">
const vintl = useVIntl()
const locale = computed(() => vintl.locale)
</script>
<template>
<div>{{ locale }}</div>
</template>
+12
View File
@@ -0,0 +1,12 @@
<script setup lang="ts">
const { formats: fmt } = useVIntl()
const props = defineProps<{
items: string[]
type?: 'conjunction' | 'disjunction' | 'unit'
}>()
const list = computed(() => fmt.list(props.items, { type: props.type }))
</script>
<template>{{ list }}</template>
@@ -0,0 +1,29 @@
<script setup lang="ts">
const vintl = useVIntl()
const switching = ref(false)
const activeLocale = computed({
get() {
return vintl.locale
},
set(value) {
if (switching.value) return
switching.value = true
vintl.changeLocale(value).finally(() => {
switching.value = false
})
},
})
</script>
<template>
<div>
<label>
Locale:
<select v-model="activeLocale" :disabled="switching.value">
<option v-for="locale in vintl.availableLocales" :key="locale.tag">
{{ locale.tag }}
</option>
</select>
</label>
</div>
</template>
@@ -0,0 +1,12 @@
<script setup lang="ts">
const { formatMessage } = useVIntl()
const greeting = defineMessage({
id: 'greeting',
defaultMessage: 'Hello, {name}!',
})
</script>
<template>
<div>{{ formatMessage(greeting, { name: 'Alex' }) }}</div>
</template>
@@ -0,0 +1,28 @@
<script setup lang="ts">
const messages = defineMessages({
greeting: {
id: 'personal-greeting',
defaultMessage: 'Hello, <bold>{name}</bold>! {waving_hand}',
},
})
const user = {
displayName: 'John',
}
</script>
<template>
<div>
<IntlFormatted
:message-id="messages.greeting"
:values="{ name: user.displayName }"
>
<template #bold="{ children }">
<strong><component :is="() => children" /></strong>
</template>
<template #~waving_hand>
<Icon name="noto:waving-hand" />
</template>
</IntlFormatted>
</div>
</template>
+77
View File
@@ -0,0 +1,77 @@
---
title-template: UwU
navigation: false
layout: landing
---
<!-- prettier-ignore-file -->
::block-hero
---
cta:
- Get Started
- /introduction
secondary:
- Open on GitHub →
- https://github.com/vintl-dev/nuxt
---
#title
VIntl for Nuxt
#description
Nuxt app internationalization made easy
#extra
::list
- Power of the browser Intl API
- ICU MessageFormat syntax for messages
- Formatted components
::
#support
::terminal
---
content:
- npm install @vintl/nuxt
---
::
::
::card-grid
#title
What's included
#root
:ellipsis{left=0px width=40rem top=10rem blur=140px}
#default
::card{icon=noto:globe-with-meridians}
#title
Automatic language detection
#description
Detect the languages your user use and apply them automatically.
::
::card{icon=noto:pencil}
#title
Plurals, dates, and more
#description
ICU MessageFormat syntax provides a powerful way to format your messages.
::
::card{icon=noto:rocket}
#title
Parserless mode
#description
Parse your messages once during the build to reduce bundle size and improve performance.
::
::card{icon=noto:floppy-disk}
#title
Storage options
#description
Store your users preferences with cookies, localStorage, or with the custom storage adapter.
::
::
+118
View File
@@ -0,0 +1,118 @@
# Getting started
Start localizing your app with VIntl in minutes.
::alert{type="warning"}
VIntl for Nuxt is still very new and may not be fully production-ready for large scale apps. That being said, the fundamental functionality is already in place, so it's probably good enough for small apps and general testing. Please submit your feedback and bug reports [on GitHub](https://github.com/vintl-dev/nuxt/issues).
::
## Installing VIntl for Nuxt
To install VIntl for Nuxt, you'll need to install the [`@vintl/nuxt`](https://npm.im/@vintl/nuxt) package:
::code-group
```sh [npm]
npm install @vintl/nuxt
```
```sh [pnpm]
pnpm add @vintl/nuxt
```
```sh [yarn]
yarn add @vintl/nuxt
```
::
## Configuring Nuxt
In the [`nuxt.config.ts`](https://nuxt.com/docs/api/configuration/nuxt-config), under the `modules` key, add `'@vintl/nuxt'`:
```ts [nuxt.config.ts] {2}
export default defineNuxtConfig({
modules: ['@vintl/nuxt'],
})
```
Now, refresh Nuxt types to see intellisense for the new `vintl` property of `nuxt.config.ts`:
```sh
nuxi prepare
```
## Configuring the module
Now that you have updated the types, you can use the `vintl` property in your `nuxt.config.ts` to configure the various aspects of VIntl.
Without this configuration our app won't start, so let's declare our locales and set the default locale:
```ts [nuxt.config.ts]
export default defineNuxtConfig({
modules: ['@vintl/nuxt'],
vintl: {
defaultLocale: 'en-US',
locales: [
{
tag: 'en-US',
file: './locales/en-US.json',
meta: { displayName: 'English' },
},
{
tag: 'uk',
file: './locales/uk.json',
meta: { displayName: 'Ukrainian' },
},
],
},
})
```
We will also create the locale files:
::code-group
```json [locales/en-US.json]
{
"greeting": {
"defaultMessage": "Hello, {username}!"
}
}
```
```json [locales/uk.json]
{
"greeting": {
"defaultMessage": "Привіт, {username}!"
}
}
```
::
## Using the module
After configuring the module and creating our first locale files, we are ready to start using VIntl in our app.
Let's create a page `vintl-test`, where we will use our `greeting` message.
```vue [pages/vintl-test.vue]
<script setup lang="ts">
const { formatMessage } = useVIntl()
</script>
<template>
<div>
{{ formatMessage('greeting', { username: 'world' }) }}
</div>
</template>
```
Go to the page in your browser, and you should see the message Hello, world!.
::alert{type="success"}
:tada: **Congratulations!** VIntl is now set up. Continue to explore the VIntl documentation to learn more about VIntl features, configuration options, and more.
::
@@ -0,0 +1,146 @@
# Configuration
VIntl for Nuxt provides variety of options to configure the plugin and integration.
::alert
All options are validated using Zod, and only when launching Nuxt in dev or build modes.
::
## `ModuleOptions`
Represents the VIntl module options.
**Properties**
| Property | Default | Description |
| :---------------------- | :------------------: | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `defaultLocale` | | A string that represents the BCP 47 code of the locale to use by default. |
| `resolveDir` | `'.'` | An optional string that represents a directory where all the imports associated with the locales are being resolved. If it's relative, then it will be resolved against the Nuxt `srcDir` directory. If this property is not set, modules will be resolved from the Nuxt `srcDir`. |
| `locales` | | An array of [`LocaleDescriptor`] objects that represent all the configured locales. |
| `storage` | | An optional string that represents either a built-in storage name (`localStorage` / `cookie`), or a node import specifier that exports a custom storage adapter as the default export. |
| `broadcastLocaleChange` | `true` | An optional boolean value that determines whether to use [`BroadcastChannel`] (if available) to synchronize the locale changes between the tabs on the same origin. |
| `hostLanguageParam` | `'hl'` | An optional name of the query parameter used to override the user language (including automatically detected one). It is used to generate SEO meta tags. Using `null` will disable them. |
| `parserless` | `{ enabled: false }` | An optional [`ParserlessOptions`] object or [`ParserlessMode`] which configures the parserless mode. |
[`BroadcastChannel`]: https://developer.mozilla.org/en-US/docs/Web/API/BroadcastChannel
[`ParserlessOptions`]: #parserlessoptions
[`ParserlessMode`]: #parserlessmode
## `LocaleDescriptor`
[`LocaleDescriptor`]: #localedescriptor
Represents a configured locale.
| Property | Description |
| :------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `file` | An optional [`MessagesImportSource`] that represents a source of import for the messages file. If the `files` option is specified together with this option, this messages file will be imported before any other file defined in `files`. |
| `files` | An optional array of [`MessagesImportSource`] that represent import sources for the message files. The messages in previously imported sources will be overridden by the messages in later imported sources in the order of their appearance in the array. |
| `tag` | A string that represents the BCP 47 language tag of the locale. |
| `additionalImports` | An optional array of [`UnspecifiedImportSource`] that represent additional side-effect only imports, such as polyfill data. |
| `resources` | An optional object representing the resources map, where each key is a resource name and values are [`ImportSource`]. Unlike additional imports, these imports will be accessible through VIntl instance. This is useful for language-associated documents that would otherwise create a frustrating experience for translators if left as regular strings in the messages file. |
| `meta` | An optional object that represents custom meta for the locale. It can be used to store data like language display name or translations percentage. It has to be JSON serializable. |
## `ImportSource`
[`ImportSource`]: #ImportSource
Represents an import source for a file. It can be one of the following:
- A string with the a path / Node.js module ID to import the default export from.
- An array (tuple) of an import path or and export name from the module imported from that path.
| Index | (Name) | Description |
| :---- | :----------- | :---------------------------------------------------------------------------- |
| `1` | `source` | A string that represents the import path of the file. |
| `2` | `exportName` | A string that represents the name of the export to be imported from the file. |
- An object containing `from` property with import path and `name` property with module path.
| Property | Default | Description |
| :-------- | :-----: | :------------------------------------------------------------------------------------ |
| `from` | | A string that represents the import path of the file. |
| `name` | | A string that represents the name of the export to be imported from the file. |
| `resolve` | `true` | A boolean value indicating whether the import path must be resolved or used as is is. |
Here's how some of the example values will be expanded:
```js
// './locales/en-US/document.md'
import localeData$rabc12ef3 from '<resolveDir>/locales/en-US/document.md'
// `'@org/pkg/data/en-US/document.md'`
import localeData$rabc12ef3 from '@org/pkg/data/en-US/document.md'
// `['./locales/en-US/index.js', 'document']`
import { document as localeData$rabc12ef3 } from '../../locales/en-US/index.js'
// `{ from: '@org/pkg/data/messages.res', name: 'enUS' }`
import { enUS as localeData$rabc12ef3 } from '../../node_modules/@org/pkg/dist/data/en-US/messages.res'
// `{ from: '@org/pkg/data/messages.res', name: 'enUS', resolve: false }`
import { enUS as localeData$rabc12ef3 } from '@org/pkg/data/en-US/messages.res'
```
There's an issue with Vite where dependencies imported by direct path will not be cached and instead imported as separate modules. This can break data imports that rely on importing the module rather than expanding some global property. This is where `resolve` property comes in handy: it does not perform resolution and imports the path as is.
::alert{type=warning}
Alias imports are currently not supported, but will be in the future.
::
## `UnspecifiedImportSource`
[`UnspecifiedImportSource`]: #unspecifiedimportsource
Represents an import source without any specifiers, also known as side-effect only imports.
It can be one of the following:
- A string with the a path / Node.js module ID to import.
- An object containing `from` property with import path, and optionally `resolve` property.
| Property | Default | Description |
| :-------- | :-----: | :------------------------------------------------------------------------------------ |
| `from` | | A string that represents the import path of the file. |
| `resolve` | `true` | A boolean value indicating whether the import path must be resolved or used as is is. |
Examples:
```js
// '@org/pkg/polyfill/add-global-data/en'
import '../../node_modules/@org/pkg/dist/polyfill/add-global-data/en.mjs'
// { from: '@org/pkg/polyfill/add-global-data/en', resolve: false }
import '@org/pkg/polyfill/add-global-data/en'
```
## `MessagesImportSource`
[`MessagesImportSource`]: #messagesimportsource
Represents an import source for the messages file. It is similar to the [`ImportSource`], but can have additional options specifying the format or formatter of the file, as well as parser function. It does not have `resolve` option, as resolution is required to properly process message files.
| Property | Default | Description |
| :------- | :---------: | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `format` | `'default'` | An optional string that represents a FormatJS [format name][fjs_formats] or a function that accepts an unknown value in and returns a record where keys are messages IDs and values are the message contents. |
| `parser` | | An optional function which accepts file contents and module ID and parses it (useful, for example, for TOML files). |
[fjs_formats]: https://formatjs.io/docs/tooling/cli/#builtin-formatters
## `ParserlessOptions`
Represents options for the parserless mode.
| Property | Description |
| :-------- | :----------------------------------------------------------------------- |
| `enabled` | A `ParserlessMode` value representing the status of the parserless mode. |
## `ParserlessMode`
A string or boolean value representing the status of the parserless mode.
| Value | Boolean value | Meaning |
| :---------- | :-----------: | :---------------------------------------------------------------------------------- |
| `always` | `true` | Parserless mode is always enabled, regardless of the mode in which Nuxt is running. |
| `only-prod` | | Parserless mode is only enabled when building Nuxt app for production. |
| `never` | `false` | Parserless mode is never enabled, the parser is always present in the runtime. |
@@ -0,0 +1,2 @@
title: Introduction
icon: carbon:idea
+91
View File
@@ -0,0 +1,91 @@
# useVIntl
`useVIntl` is a composable that is automatically imported when using VIntl for Nuxt. When used, it injects the active VIntl instance, which can be used to provide internationalisation capabilities, such as `formatMessage` function, or access to the current state of the controller (e.g. `locale`).
## Examples
Here are a few examples showcasing `useVIntl` usage.
### Basic usage
::code-group
```vue [Code]
<script setup lang="ts">
const { formatMessage } = useVIntl()
const greeting = defineMessage({
id: 'greeting',
defaultMessage: 'Hello, {name}!',
})
</script>
<template>
<div>{{ formatMessage(greeting, { name: 'Alex' }) }}</div>
</template>
```
::code-block{label="Preview" preview}
:div[:LocaleChanger]{style="float: right"}
:StaticGreeting
::
::
In the example above, we use `formatMessage` to format a translated message with a variable. We define our message using the `defineMessage` [function](./2.definemessages.md).
### Accessing the current locale
::code-group
```vue [Code]
<script setup lang="ts">
const vintl = useVIntl()
const locale = computed(() => vintl.locale)
</script>
<template>
<div>{{ locale }}</div>
</template>
```
::code-block{label="Preview" preview}
:div[:LocaleChanger]{style="float: right"}
:CurrentLocale
::
::
In this example, we use `useVIntl` to access the current locale and display it in the component.
### Writing a list component
::code-group
```vue [Code]
<script setup lang="ts">
const { formats: fmt } = useVIntl()
const props = defineProps<{
items: string[]
type?: 'conjunction' | 'disjunction' | 'unit'
}>()
const list = computed(() =>
fmt.list(props.items, {
type: props.type,
}),
)
</script>
<template>{{ list }}</template>
```
::code-block{label="Preview" preview}
:div[:LocaleChanger]{style="float: right"}
:IntlList{:items='["Kevin", "Jane", "Natalie"]'}
::
::
Here we used destructuring to get the `formats` property of the controller, which contains the aliases for formatters. We also define `items` and `type` props. `items` will contain list items, and `type` will declare how the list will be rendered. We then use `computed`, where we format the list, this will help us avoid useless re-renders. In the end we get a `<List>` component that we can use to render lists of various items.
@@ -0,0 +1,106 @@
# defineMessages
The `defineMessages` function allows you to define messages in your code that can be easily extracted and translated into other languages, helping you create a more inclusive and accessible experience for your users.
## ICU MessageFormat syntax
Messages use the ICU MessageFormat syntax. ICU MessageFormat is a syntax for defining localised text messages that can handle variable substitution, plurals, and other complex use cases. If you're not familiar with ICU MessageFormat syntax, you can find more information on the [FormatJS documentation page][icu_syntax].
[icu_syntax]: https://formatjs.io/docs/core-concepts/icu-syntax
## Usage
### Defining a single message
You can define a single message with defineMessage function. It accepts a descriptor object that describes the message, and returns it back. This function is used to make the message descriptor statically analysable and extractable.
```ts
const myMessage = defineMessage({
id: 'unique-message-id',
defaultMessage: 'Message content',
})
```
### Defining multiple messages
To define multiple messages, you can use `defineMessages`, which accepts an object with custom properties, where each property is set to an object containing a message descriptor. Just like defineMessage, it returns the input back as is.
```ts
const messages = defineMessages({
example: {
id: 'example',
defaultMessage: 'This is an example',
},
})
```
Property names of the object do not matter, as they don't affect the extraction in any way.
## Message Descriptors
Message descriptors are objects that describe a message and its properties. The following properties can be defined for a message:
- `id`: A unique identifier for the message.
- `defaultMessage`: The default message to display if no translation is available.
- `description` (optional): A description of the message for translators.
::alert{type="warning"}
Note that VIntl for Nuxt does not currently transpile code during the build process. This means that any `description` properties of message descriptors will remain unchanged, needlessly increasing the bundle size. If you must use `description` properties, we recommend using the [Babel plugin by FormatJS][babel_plugin] to remove them.
[babel_plugin]: https://formatjs.io/docs/tooling/babel-plugin
::
## Common pitfalls
### No dynamic descriptors
Message descriptors should be statically analysable, otherwise the extractor will not be able to extract them. This means that you should not use dynamic values in the message descriptor objects.
:div[:icon{name="uil:exclamation-triangle" color="orange" size="1.5rem" style="display: flex"} **Incorrect code**]{style="display: flex;column-gap: .5rem; align-items: center"}
```ts
function createID(key) {
return `prefix.${key}`
}
const PREFIX = `our-prefix`
const unexportedMessages = defineMessages({
greeting: {
id: createID('greeting'),
defaultMessage: 'Hello!',
},
farewell: {
id: `${PREFIX}.farewell`,
defaultMessage: 'Goodbye!',
},
})
```
In this example, neither of the defined messages are statically analysable:
- `greeting` calls the `createID` function to create an ID
- `farewell` uses the `PREFIX` variable in a template string
You should instead use static values for the ID and defaultMessage properties.
:div[:icon{name="gg:check-o" color="var(--color-green-600)" size="1.5rem" style="display: flex"} **Correct code**]{style="display: flex; column-gap: .5rem; align-items: center"}
```ts
const messages = defineMessages({
greeting: {
id: 'prefix.greeting',
defaultMessage: 'Hello!',
},
farewell: {
id: 'our-prefix.farewell',
defaultMessage: 'Goodbye!',
},
})
```
### New lines in template strings
Template strings in JavaScript can be broken into multiple lines. Unfortunately, the extractor currently does not handle this case, removing new lines from the string. If you need new lines, you should use the `\n` character or custom tags that will wrap the contents into `<p>`, `<div>` elements.
@@ -0,0 +1,94 @@
# IntlFormatted component
`IntlFormatted` is a component that allows you to format messages and render them as a component tree.
## Props
### `message`
**Type**: `string | MessageFormatElement[]`
This prop is used to specify the message to be formatted as a string or as an AST. If this prop is provided, the `message-id` prop will be ignored.
### `message-id`
**Type**: `string | MessageDescriptor`
This prop is used to specify the message to be formatted. It should be either a string that identifies the message or an object that contains an `id` property, which is a string that identifies the message, and a `defaultMessage` property, which is the message to be formatted. If this prop is provided, the `message` prop will be ignored.
### `values`
**Type**: `Record<string, any>`
This prop is used to provide values that will be used in the message. The values should be provided as an object where the keys correspond to the placeholders in the message.
## Slots
The `IntlFormatted` component has named slots that can be used to format the message.
### `~[placeholder]`
**Scoped props**: `values`
This slot is used to insert a value for a placeholder in the message. The name of the slot should start with a tilde (`~`) followed by the name of the placeholder in the message.
`values` scoped prop provides the access to the properties passed as `:values` prop to `IntlFormatted` component.
### `[tag]`
**Scoped props**: `children`, `values`
This slot is used to format a portion of the message as a component. The name of the slot should be the name of the HTML tag that should be used to wrap the contents.
The slot receives `children` prop. It contains `VNode`s, representing the children components.
As the children are `VNode`s, you cannot use `{{ interpolation }}` and have to use Vue 3 [`component` meta component][vuejs_component] that accepts a render function as `:is` property, which will simply return the children.
[vuejs_component]: https://vuejs.org/api/built-in-special-elements.html#component
## Example
Here's an example of how to use the `IntlFormatted` component:
::code-group
```vue [Code]
<script setup>
const messages = defineMessages({
greeting: {
id: 'personal-greeting',
defaultMessage: 'Hello, <bold>{name}</bold>! {waving_hand}',
},
})
const user = useAuthorizedUser()
</script>
<template>
<IntlFormatted
:message-id="messages.greeting"
:values="{ name: user.displayName }"
>
<template #bold="{ children }">
<strong><component :is="() => children" /></strong>
</template>
<template #~waving_hand><Icon name="noto:waving-hand" /></template>
</IntlFormatted>
</template>
```
::code-block{label="Preview" preview}
:div[:LocaleChanger]{style="float: right"}
:UserGreeting
::
::
In this example we format the `greeting` message, which contains `name` and `waving_hand` arguments (placeholders), as well as utilises `bold` tag.
To do so we set `message-id` prop to our greeting message descriptor, as well as set `values` to an object containing value for `name` argument.
We then define two named slots:
- `bold`, which will receive `children` (in this case text `VNode`, containing user's display name), and which we wrap into `<strong>` element.
- `waving_hand`, which contains content of the argument with the same name, which is just an icon with waving hand.
+87
View File
@@ -0,0 +1,87 @@
# Hooks
VIntl for Nuxt binds VIntl events to Nuxt's hook system.
## Build hooks
### `vintl:extendOptions(options)`
**Kind**: `async`
**Parameters**:
- `options` (`InputModuleOptions`) — mutable input options.
Called before VIntl for Nuxt options are validated. Useful to dynamically modify the configuration (e.g. automatically search files).
## Runtime hooks
### `i18n:automatic(ctx)`
**Kind**: `sync`
**Parameters**:
- `ctx` (`EventContext<AutomaticStateChangeEvent>`) — an object containing the controller and the event.
Called whenever automatic mode is switched on or off.
<a href="https://vintl.vercel.app/guide/controller/events.html#automatic-state-change-event" target="blank">More about this event <Icon name="majesticons:external-link-line" /></a>
### `i18n:beforeLocaleChange(ctx)`
**Kind**: `sync`
**Parameters**:
- `ctx` (`EventContext<LocaleChangeEvent>`) — an object containing the controller and the event.
Called before the locale change and load.
<a href="https://vintl.vercel.app/guide/controller/events.html#locale-change-event" target="blank">More about this event <Icon name="majesticons:external-link-line" /></a>
### `i18n:extendLocale(ctx)`
**Kind**: `async`
**Parameters**:
- `ctx` (`EventContext<LocaleLoadEvent>`) — an object containing the controller and the event.
Called during locale load and allows to load additional messages and resources for locale.
<a href="https://vintl.vercel.app/guide/controller/events.html#locale-load-event" target="blank">More about this event <Icon name="majesticons:external-link-line" /></a>
### `i18n:afterLocaleChange(ctx)`
**Kind**: `sync`
**Parameters**:
- `ctx` (`EventContext<AfterLocaleChangeEvent>`) — an object containing the controller and the event.
Called after the locale has been applied.
<a href="https://vintl.vercel.app/guide/controller/events.html#after-locale-change-event" target="blank">More about this event <Icon name="majesticons:external-link-line" /></a>
### `i18n:error(ctx)`
**Kind**: `sync`
**Parameters**:
- `ctx` (`EventContext<ErrorEvent>`) — an object containing the controller and the event.
Called when an error occurs in the controller or one of the listeners.
<a href="https://vintl.vercel.app/guide/controller/events.html#error-event" target="blank">More about this event <Icon name="majesticons:external-link-line" /></a>
### `i18n:ready(controller)`
**Kind**: `async`
**Parameters**:
- `controller` (`IntlController<MessageValueType>`) — the controller object that has just been set up.
Called when plugin setup is complete.
+2
View File
@@ -0,0 +1,2 @@
title: Usage
icon: iconoir:app-window
+13
View File
@@ -0,0 +1,13 @@
---
icon: solar:book-2-linear
---
# VIntl documentation
More information about VIntl can be found on the official documentation website. There you can find:
- Information about controller, its properties and methods
- How to format compact numbers and relative time
- And more...
:button-link[Open VIntl documentation]{icon="solar:book-2-linear" href="https://vintl.vercel.app/guide/intro.html" blank}
+23
View File
@@ -0,0 +1,23 @@
---
icon: ph:hand-heart-bold
---
# Support project
Hello, and thank you for checking out my project. As the creator, I am currently in a difficult financial situation, and your support would mean the world to me.
This project has been a labour of love, and I have spent countless hours working on it in hope that it provides value to its users and contributes to the open-source community.
If you have found this project helpful or inspiring, please consider supporting its continued development. Every donation helps, no matter how small.
You can find a list of donation methods, including Boosty, Yoomoney, and cryptocurrencies, on my [SUPPORT.md](https://github.com/Brawaru/Brawaru/blob/main/SUPPORT.md) page.
Thank you for your support, it means everything to me.
:div[**~ Brawaru**]{style="float: right"}
<!-- Uncomment when contributing page is ready.
---
P.S. If you're not in a position to donate but still want to help, I would appreciate contributions to the project in any form. Whether it's writing tests, creating documentation, or suggesting new features, every little bit helps. You can find more information about how to contribute on the [project's GitHub page](https://github.com/vintl-dev/nuxt). -->
+11
View File
@@ -0,0 +1,11 @@
<script setup lang="ts">
const { config } = useDocus()
const titleTemplate = computed(() => config.value.title)
watch(titleTemplate, (v) => useHead({ titleTemplate: v }), { immediate: true })
</script>
<template>
<NuxtLayout name="page">
<slot />
</NuxtLayout>
</template>
+8
View File
@@ -0,0 +1,8 @@
{
"greeting": {
"defaultMessage": "Hello, {name}!"
},
"personal-greeting": {
"defaultMessage": "Hello, <bold>{name}</bold>! {waving_hand}"
}
}
+8
View File
@@ -0,0 +1,8 @@
{
"greeting": {
"defaultMessage": "Привіт, {name}!"
},
"personal-greeting": {
"defaultMessage": "Привіт, <bold>{name}</bold>! {waving_hand}"
}
}
+17
View File
@@ -0,0 +1,17 @@
export default defineNuxtConfig({
extends: '@nuxt-themes/docus',
modules: ['@vintl/nuxt'],
vintl: {
defaultLocale: 'en-US',
locales: [
{
tag: 'en-US',
file: './locales/en-US.json',
},
{
tag: 'uk',
file: './locales/uk.json',
},
],
},
})
+25
View File
@@ -0,0 +1,25 @@
{
"name": "@vintl-dev/docs",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "nuxi dev",
"dev:prepare": "nuxi prepare",
"build": "nuxi build",
"generate": "nuxi generate",
"preview": "nuxi preview",
"lint": "eslint --cache .",
"intl:extract": "formatjs extract \"{,components,composables,layouts,middleware,modules,pages,plugins,utils}/**/*.{vue,ts,tsx,js,jsx,mts,cts,mjs,cjs}\" --ignore '**/*.d.ts' --ignore 'node_modules' --out-file locales/en-US.json",
"start": "node .output/server/index.mjs"
},
"devDependencies": {
"@formatjs/cli": "^6.0.4",
"@nuxt-themes/docus": "^1.10.1",
"@nuxt/eslint-config": "^0.1.1",
"@vintl-dev/eslint-config-peony": "workspace:^",
"@vintl/nuxt": "workspace:^",
"eslint": "^8.39.0",
"nuxt": "^3.4.2",
"theme-colors": "^0.0.5"
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

+8
View File
@@ -0,0 +1,8 @@
{
"extends": [
"@nuxtjs"
],
"lockFileMaintenance": {
"enabled": true
}
}
+12
View File
@@ -0,0 +1,12 @@
import { defineTheme } from 'pinceau'
import { getColors } from 'theme-colors'
const colorScheme = getColors('#6a5acd') as {
[K in keyof NonNullable<Parameters<typeof getColors>[1]>]: string
}
export default defineTheme({
color: {
primary: colorScheme,
},
})
+3
View File
@@ -0,0 +1,3 @@
{
"extends": "./.nuxt/tsconfig.json"
}
+13
View File
@@ -0,0 +1,13 @@
{
"root": true,
"extends": ["@vintl-dev/eslint-config-peony"],
"overrides": [
{
"files": ["./**/*.{ts,tsx,vue}"],
"parserOptions": {
"project": "./tsconfig.json"
}
}
],
"ignorePatterns": ["/.nuxt", "/.output"]
}
+9
View File
@@ -0,0 +1,9 @@
node_modules
*.log*
.nuxt
.nitro
.cache
.output
.env
dist
.DS_Store
+1
View File
@@ -0,0 +1 @@
shamefully-hoist=true
+3
View File
@@ -0,0 +1,3 @@
# VIntl for Nuxt playground
This playground is used to test the functionality of the VIntl for Nuxt package.
+23
View File
@@ -0,0 +1,23 @@
{
"example": {
"message": "Example"
},
"greeting": {
"message": "Hello, {name}!"
},
"index.other-page": {
"message": "To the other page"
},
"language": {
"message": "Language"
},
"options": {
"message": "Options"
},
"other-page.back": {
"message": "Go back"
},
"other-page.title": {
"message": "Hello from the other page!"
}
}
+14
View File
@@ -0,0 +1,14 @@
{
"example": {
"message": "Приклад"
},
"greeting": {
"message": "Привіт, {name}!"
},
"language": {
"message": "Мова"
},
"options": {
"message": "Налаштування"
}
}
+34
View File
@@ -0,0 +1,34 @@
// https://nuxt.com/docs/api/configuration/nuxt-config
export default defineNuxtConfig({
modules: ['@vintl/nuxt'],
vintl: {
defaultLocale: 'en-US',
locales: [
{
tag: 'en-US',
files: [
{
from: '@vintl-dev/pg-messages/en-US',
format: 'crowdin',
},
{
from: './locales/en-US.json',
format: 'crowdin',
},
],
},
{
tag: 'uk',
files: [
{
from: './locales/uk.json',
format: 'crowdin',
},
],
},
],
storage: 'cookie',
broadcastLocaleChange: true,
parserless: 'always',
},
})
+24
View File
@@ -0,0 +1,24 @@
{
"name": "@vintl-dev/pg",
"version": "0.1.0",
"description": "Development playground for Nuxt VIntl module",
"private": true,
"scripts": {
"dev": "nuxi dev",
"dev:prepare": "nuxi prepare",
"build": "nuxi build",
"generate": "nuxi generate",
"preview": "nuxi preview",
"lint": "eslint --cache .",
"intl:extract": "formatjs extract \"{,components,composables,layouts,middleware,modules,pages,plugins,utils}/**/*.{vue,ts,tsx,js,jsx,mts,cts,mjs,cjs}\" --ignore '**/*.d.ts' --ignore 'node_modules' --out-file locales/en-US.json --format simple",
"start": "node .output/server/index.mjs"
},
"devDependencies": {
"@vintl-dev/eslint-config-peony": "workspace:^",
"@vintl-dev/pg-messages": "workspace:^",
"@vintl/nuxt": "workspace:^",
"eslint": "^8.39.0",
"nuxi": "^3.4.2",
"nuxt": "^3.4.2"
}
}
+78
View File
@@ -0,0 +1,78 @@
<script lang="ts" setup>
import { computed } from 'vue'
import { useVIntl } from '@vintl/vintl'
const messages = defineMessages({
options: {
id: 'options',
defaultMessage: 'Options',
},
language: {
id: 'language',
defaultMessage: 'Language',
},
example: {
id: 'example',
defaultMessage: 'Example',
},
greeting: {
id: 'greeting',
defaultMessage: 'Hello, {name}!',
},
otherPage: {
id: 'index.other-page',
defaultMessage: 'To the other page',
},
} as const)
const vintl = useVIntl()
const { formatMessage } = vintl
const currentLocale = computed({
get() {
return vintl.locale
},
set() {
// ignore
},
})
async function onLocaleChange(e: Event) {
await vintl.changeLocale(
(e as Event & { target: HTMLSelectElement }).target.value,
)
}
</script>
<template>
<div>
<div>
<h3>{{ formatMessage(messages.options) }}</h3>
<label for="language-select">
{{ formatMessage(messages.language) }}
</label>
<select
id="language-select"
v-model="currentLocale"
@change="onLocaleChange"
>
<option
v-for="locale in [...$nuxt.$i18n.$locales.value.keys()]"
:key="locale.tag"
:value="locale.tag"
>
{{ locale.tag }}
</option>
</select>
</div>
<div>
<h3><IntlFormatted :message-id="messages.example" /></h3>
<div>{{ formatMessage(messages.greeting, { name: 'world' }) }}</div>
</div>
<div>
<NuxtLink to="/other">{{ formatMessage(messages.otherPage) }} </NuxtLink>
</div>
</div>
</template>
+28
View File
@@ -0,0 +1,28 @@
<script setup lang="ts">
const messages = defineMessages({
title: {
id: 'other-page.title',
defaultMessage: 'Hello from the other page!',
},
description: {
id: 'other-page.description',
defaultMessage: "You must've clicked me a thousand times",
},
goBack: {
id: 'other-page.back',
defaultMessage: 'Go back',
},
})
const { formatMessage } = useVIntl()
</script>
<template>
<div>
<h1>{{ formatMessage(messages.title) }}</h1>
<p>{{ formatMessage(messages.description) }}</p>
<p>
<NuxtLink to="/"> {{ formatMessage(messages.goBack) }}</NuxtLink>
</p>
</div>
</template>
Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

+4
View File
@@ -0,0 +1,4 @@
{
// https://nuxt.com/docs/guide/concepts/typescript
"extends": "./.nuxt/tsconfig.json"
}
+43
View File
@@ -0,0 +1,43 @@
{
"name": "nuxt-intl-monorepo",
"version": "0.0.0",
"private": true,
"workspaces": [
"apps/*",
"packages/*"
],
"devDependencies": {
"@changesets/cli": "^2.26.1",
"turbo": "^1.8.7"
},
"scripts": {
"pg:prepare": "turbo run --no-daemon @vintl-dev/pg#dev:prepare",
"pg:dev": "turbo run --no-daemon @vintl-dev/pg#dev",
"pg:build": "turbo run --no-daemon @vintl-dev/pg#build",
"pg:start": "turbo run --no-daemon @vintl-dev/pg#start",
"pg:lint": "turbo run --no-daemon @vintl-dev/pg#lint",
"docs:prepare": "turbo run --no-daemon @vintl-dev/docs#dev:prepare",
"docs:dev": "turbo run --no-daemon @vintl-dev/docs#dev",
"docs:build": "turbo run --no-daemon @vintl-dev/docs#build",
"docs:start": "turbo run --no-daemon @vintl-dev/docs#start",
"docs:lint": "turbo run --no-daemon @vintl-dev/docs#lint",
"mod:build": "turbo run --no-daemon @vintl/nuxt#build",
"mod:lint": "turbo run --no-daemon @vintl/nuxt#lint",
"all:prepare": "turbo run --no-daemon prepare",
"all:lint": "turbo run --no-daemon lint",
"_ci:publish": "changeset publish"
},
"pnpm": {
"patchedDependencies": {
"astring@1.8.4": "patches/astring@1.8.4.patch"
},
"packageExtensions": {
"@nuxt/kit": {
"dependencies": {
"webpack": "^5.80.0"
}
}
}
},
"packageManager": "pnpm@8.3.1"
}
+37
View File
@@ -0,0 +1,37 @@
{
"extends": ["./nuxt-eslint-config.cjs"],
"rules": {
"space-before-function-paren": "off",
"comma-dangle": "off",
"arrow-parens": ["error", "always"],
"curly": ["error", "multi-line"],
"no-mixed-spaces-and-tabs": ["error", "smart-tabs"],
"no-use-before-define": "off",
"@typescript-eslint/no-use-before-define": [
"error",
{ "functions": false, "classes": false, "variables": false }
],
"no-redeclare": "off",
"@typescript-eslint/no-redeclare": [
"error",
{ "builtinGlobals": false, "ignoreDeclarationMerge": true }
],
"no-void": ["error", { "allowAsStatement": true }],
"require-await": "off",
"@typescript-eslint/require-await": "error",
"@typescript-eslint/consistent-type-imports": [
"error",
{ "fixStyle": "inline-type-imports" }
],
"@typescript-eslint/no-extra-semi": "off",
"indent": "off",
"no-useless-constructor": "off",
"@typescript-eslint/no-useless-constructor": "warn",
"brace-style": "off",
"vue/singleline-html-element-content-newline": "off"
},
"parserOptions": {
"extraFileExtensions": [".vue"]
},
"ignorePatterns": ["node_modules", ".turbo"]
}
@@ -0,0 +1,84 @@
// MIT License
// Copyright (c) 2019-2022 Nuxt Project
// https://github.com/nuxt/eslint-config/blob/main/LICENSE
require('@rushstack/eslint-patch/modern-module-resolution')
/** @type {import('eslint').ESLint.ConfigData} */
module.exports = {
parserOptions: {
ecmaVersion: 'latest',
parser: {
js: 'espree',
jsx: 'espree',
ts: '@typescript-eslint/parser',
tsx: '@typescript-eslint/parser',
},
extraFileExtensions: ['.vue'],
ecmaFeatures: {
jsx: true,
},
},
env: { node: true },
plugins: ['@typescript-eslint'],
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/eslint-recommended',
'plugin:vue/vue3-recommended',
],
overrides: [
{
files: ['*.ts', '*.tsx', '*.mts', '*.cts', '*.vue'],
rules: {
// The core 'no-unused-vars' rules (in the eslint:recommended ruleset)
// does not work with type definitions.
'no-unused-vars': 'off',
'@typescript-eslint/no-unused-vars': 'warn',
},
},
{
// Include typescript eslint rules in *.vue files
// https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/src/configs/eslint-recommended.ts
files: ['*.vue'],
rules: {
'constructor-super': 'off', // ts(2335) & ts(2377)
'getter-return': 'off', // ts(2378)
'no-const-assign': 'off', // ts(2588)
'no-dupe-args': 'off', // ts(2300)
'no-dupe-class-members': 'off', // ts(2393) & ts(2300)
'no-dupe-keys': 'off', // ts(1117)
'no-func-assign': 'off', // ts(2539)
'no-import-assign': 'off', // ts(2539) & ts(2540)
'no-new-symbol': 'off', // ts(7009)
'no-obj-calls': 'off', // ts(2349)
'no-redeclare': 'off', // ts(2451)
'no-setter-return': 'off', // ts(2408)
'no-this-before-super': 'off', // ts(2376)
'no-undef': 'off', // ts(2304)
'no-unreachable': 'off', // ts(7027)
'no-unsafe-negation': 'off', // ts(2365) & ts(2360) & ts(2358)
'no-var': 'error', // ts transpiles let/const to var, so no need for vars any more
'prefer-const': 'error', // ts provides better types with const
'prefer-rest-params': 'error', // ts provides better types with rest args over arguments
'prefer-spread': 'error', // ts transpiles spread to apply, so no need for manual apply
'valid-typeof': 'off', // ts(2367)
},
},
{
// These pages are not used directly by users so they can have one-word names.
files: [
'**/pages/**/*.{js,ts,vue}',
'**/layouts/**/*.{js,ts,vue}',
'**/app.{js,ts,vue}',
'**/error.{js,ts,vue}',
],
rules: { 'vue/multi-word-component-names': 'off' },
},
{
// Pages and layouts are required to have a single root element if transitions are enabled.
files: ['**/pages/**/*.{js,ts,vue}', '**/layouts/**/*.{js,ts,vue}'],
rules: { 'vue/no-multiple-template-root': 'error' },
},
],
}
+39
View File
@@ -0,0 +1,39 @@
{
"name": "@vintl-dev/eslint-config-peony",
"private": true,
"version": "0.1.0",
"description": "Shared ESLint configuration for VIntl for Nuxt monorepo",
"homepage": "https://github.com/vintl-dev/nuxt/tree/main/packages/eslint-config",
"bugs": "https://github.com/vintl-dev/nuxt/issues",
"author": {
"name": "Alexander 'Brawaru' Sorokin",
"url": "https://github.com/brawaru"
},
"funding": "https://github.com/brawaru/brawaru/blob/main/SUPPORT.md",
"repository": {
"type": "git",
"url": "https://github.com/vintl-dev/nuxt.git"
},
"license": "MIT",
"type": "module",
"exports": {
".": {
"default": "./config.json"
},
"./package.json": "./package.json"
},
"files": [
"config.json"
],
"dependencies": {
"@rushstack/eslint-patch": "^1.2.0",
"@typescript-eslint/eslint-plugin": "^5.59.0",
"@typescript-eslint/parser": "^5.59.0",
"eslint-plugin-vue": "^9.11.0",
"typescript": "^5.0.4"
},
"devDependencies": {
"@types/eslint": "^8.37.0",
"eslint": "^8.38.0"
}
}
+9
View File
@@ -0,0 +1,9 @@
{
"name": "@vintl-dev/pg-messages",
"description": "Translations for strings used in playground",
"version": "0.1.0",
"private": true,
"exports": {
"./*": "./src/*.json"
}
}
+5
View File
@@ -0,0 +1,5 @@
{
"module.greetings": {
"message": "This is a message coming from the module!"
}
}
@@ -1,13 +1,12 @@
root = true
[*]
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
charset = utf-8
[{*.js,*.ts,*.mts,package.json,*.cjson,*.yml,*.yaml}]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
max_line_length = 100
[*.md]
trim_trailing_whitespace = false
+30
View File
@@ -0,0 +1,30 @@
{
"root": true,
"extends": ["@vintl-dev/eslint-config-peony"],
"overrides": [
{
"files": ["./src/**/*.ts", "./types/*.d.ts"],
"excludedFiles": ["./src/runtime/**/*.ts", "./dist"],
"parserOptions": {
"project": "./tsconfig.json"
}
},
{
"files": ["./build.config.ts"],
"parserOptions": {
"project": "./tsconfig.build.json"
}
},
{
"files": [
"./stubs/*.{d.ts,js}",
"./src/runtime/**/*.{ts,mts}",
"./types/*.d.ts"
],
"parserOptions": {
"project": "./tsconfig.runtime.json"
}
}
],
"ignorePatterns": ["/dist"]
}
+73
View File
@@ -0,0 +1,73 @@
# @vintl/nuxt
## 1.1.3
### Patch Changes
- 25b5acf: Don't require additionalImports to be a non-empty array
## 1.1.2
### Patch Changes
- 71b9000: Fix object import sources not resolving by default
## 1.1.1
### Patch Changes
- 70c440e: Fix arrays of imports having incorrect types
## 1.1.0
### Minor Changes
- d12429c: Add option to opt out of the import resolution
All imports except message imports (because they have to be resolved for formatter and parser to work) are now including `resolve` boolean property when using object forms to declare imports (resources or additional side-effect only imports).
By setting it to `false` imports are added as is, and not checked during the options file generation, which can help avoid hitting a problem like in Vite where import by path imports a different module than import by package name and (export) path within it.
```ts
// { from: '@vintl/compact-number/locale-data/en', resolve: true }
import '../../node_modules/@vintl/compact-number/dist/locale-data/en.js'
// { from: '@vintl/compact-number/locale-data/en', resolve: false }
import '@vintl/compact-number/locale-data/en'
```
This is a temporary solution to [#10](https://github.com/vintl-dev/nuxt/issues/10) until there's a better one.
## 1.0.2
### Patch Changes
- 8554729: Restore legacy resolution fields to package.json
Nuxt still uses the legacy resolution mechanism that ignores the `exports` field. So `module` and `types` also need to be present in `package.json`.
## 1.0.1
### Patch Changes
- bfca7c2: Export types with shims instead of module types directly
## 1.0.0
### Major Changes
- 5bb8d76: # Initial release
I believe VIntl for Nuxt is finally ready for its initial release.
As with any package that just releases, I cannot promise that it's going to be bug-free or fully production-ready, but it's probably good enough for small apps and general testing.
There's a lot of work and plans going ahead, but fundamental functionality is already in place. Please remember to submit your feedback and bug reports [on GitHub](https://github.com/vintl-dev/nuxt/issues).
You can also support me working on this project through the link below:
<a href="https://github.com/Brawaru/Brawaru/blob/main/SUPPORT.md"><img alt="Support me by donating" height="56" src="https://cdn.jsdelivr.net/npm/@intergrav/devins-badges@3/assets/cozy/donate/generic-singular_vector.svg"></a>
Thank you!
— Brawaru
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) Alexander 'Brawaru' Sorokin <https://github.com/brawaru>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+45
View File
@@ -0,0 +1,45 @@
# VIntl for Nuxt
Nuxt app internationalization made easy
## Features
- Power of the browser Intl API
- ICU MessageFormat syntax for messages
- Formatted components
## Getting Started
> **Warning** VIntl for Nuxt is still very new and may not be fully production-ready for large scale apps. That being said, the fundamental functionality is already in place, so it's probably good enough for small apps and general testing. Please submit your feedback and bug reports [on GitHub](https://github.com/vintl-dev/nuxt/issues).
```bash
npm install @vintl/nuxt
```
## What's included
### 🌐 Automatic language detection
Detect the languages your user use and apply them automatically.
### ✏ Plurals, dates, and more
ICU MessageFormat syntax provides a powerful way to format your messages.
### 🚀 Parserless mode
Parse your messages once during the build to reduce bundle size and improve performance.
### 💾 Storage options
Store your users preferences with cookies, localStorage, or with the custom storage adapter.
## Documentation
Check out the [VIntl for Nuxt documentation site](https://vintl-nuxt.netlify.app/) for detailed usage instructions and examples.
## Credits
Made with 💜 by [Brawaru](https://github.com/brawaru). Released under [MIT Licence](./LICENSE).
<a href="https://github.com/Brawaru/Brawaru/blob/main/SUPPORT.md"><img alt="Support me by donating" height="56" src="https://cdn.jsdelivr.net/npm/@intergrav/devins-badges@3/assets/cozy/donate/generic-singular_vector.svg"></a>
+17
View File
@@ -0,0 +1,17 @@
import { defineBuildConfig } from 'unbuild'
export default defineBuildConfig({
hooks: {
'build:before'(ctx) {
for (const entry of ctx.options.entries) {
if (
entry.builder === 'mkdist' &&
'ext' in entry &&
entry.input.endsWith('vintl-nuxt/src/runtime')
) {
entry.ext = 'js'
}
}
},
},
})
+65
View File
@@ -0,0 +1,65 @@
{
"name": "@vintl/nuxt",
"version": "1.1.3",
"description": "Nuxt Module for VIntl integration",
"keywords": [
"i18n",
"intl",
"nuxt"
],
"homepage": "https://github.com/vintl-dev/nuxt/tree/main/packages/vintl-nuxt",
"bugs": "https://github.com/vintl-dev/nuxt/issues",
"author": {
"name": "Alexander 'Brawaru' Sorokin",
"url": "https://github.com/brawaru"
},
"funding": "https://github.com/brawaru/brawaru/blob/main/SUPPORT.md",
"repository": {
"type": "git",
"url": "https://github.com/vintl-dev/nuxt.git"
},
"license": "MIT",
"type": "module",
"exports": {
".": {
"types": "./dist/types.d.ts",
"import": "./dist/module.mjs",
"require": "./dist/module.cjs"
},
"./package.json": "./package.json"
},
"module": "./dist/module.mjs",
"types": "./dist/types.d.ts",
"files": [
"dist"
],
"scripts": {
"build": "nuxt-module-build",
"lint": "eslint --cache .",
"prepack": "pnpm run -s lint && pnpm run -s build"
},
"devDependencies": {
"@nuxt/module-builder": "^0.3.0",
"@types/hash-sum": "^1.0.0",
"@types/node": "^18.15.12",
"@unhead/vue": "^1.1.26",
"@vintl-dev/eslint-config-peony": "workspace:^",
"hookable": "^5.5.3",
"prettier-plugin-jsdoc": "^0.4.2",
"typescript": "^5.0.4"
},
"dependencies": {
"@formatjs/intl": "^2.7.1",
"@nuxt/kit": "^3.4.2",
"@nuxt/schema": "^3.4.2",
"@vintl/unplugin": "^1.2.1",
"@vintl/vintl": "^4.1.2",
"astring": "^1.8.4",
"hash-sum": "^2.0.0",
"import-meta-resolve": "^2.2.2",
"pathe": "^1.1.0",
"picocolors": "^1.0.0",
"slash": "^5.0.0",
"zod": "^3.21.4"
}
}
+3
View File
@@ -0,0 +1,3 @@
export class OptionsError extends Error {
public readonly code = 'ERR_NUXTINTL_BAD_OPTIONS'
}
+48
View File
@@ -0,0 +1,48 @@
import type { NuxtHooks } from '@nuxt/schema'
type Manifest = Parameters<NuxtHooks['build:manifest']>[0]
function purgeResourceTree(manifest: Manifest, resourceName: string) {
const resource = manifest[resourceName]
if (resource == null) return
delete manifest[resourceName]
if (resource.dynamicImports != null) {
for (const childResourceName of resource.dynamicImports) {
purgeResourceTree(manifest, childResourceName)
}
}
}
export function purgeEntryResources(
manifest: Manifest,
resourcesToPurge: string[],
) {
let entryResource: Manifest[string] | undefined
for (const resourceName in manifest) {
const resource = manifest[resourceName]
if (resource != null && (resource.isEntry ?? false)) {
entryResource = resource
break
}
}
if (entryResource == null) return
if (entryResource.dynamicImports == null) return
const purgableResources: string[] = []
for (const resourceName of entryResource.dynamicImports) {
if (resourcesToPurge.includes(resourceName)) {
purgableResources.push(resourceName)
}
}
for (const resourceName of purgableResources) {
const entryIndex = entryResource.dynamicImports.indexOf(resourceName)
if (entryIndex !== -1) entryResource.dynamicImports.splice(entryIndex, 1)
purgeResourceTree(manifest, resourceName)
}
}
+209
View File
@@ -0,0 +1,209 @@
import { fileURLToPath } from 'node:url'
import {
defineNuxtModule,
addPlugin,
addTemplate,
addImports,
addComponent,
extendViteConfig,
extendWebpackConfig,
} from '@nuxt/kit'
import {
relative as relativizePath,
resolve as resolvePath,
dirname,
} from 'pathe'
import { generate as generateOptions } from './options-gen.js'
import { createDirResolver } from './utils/resolvers.js'
import { purgeEntryResources } from './manifest-clean.js'
import { type z as t, ZodError } from 'zod'
import { moduleOptionsSchema } from './schemas/index.js'
import { PluginOptionsBank } from './parser-bank.js'
import { formatZodError } from './utils/zod-error.js'
import { OptionsError } from './errors.js'
import * as consola from 'console'
/** Path to the options file relative to `buildDir`. */
const optionsFilePath = 'i18n/options.mjs'
type _InputModuleOptions = typeof moduleOptionsSchema
export interface InputModuleOptions extends t.input<_InputModuleOptions> {}
export default defineNuxtModule<InputModuleOptions>({
meta: {
name: '@vintl/nuxt',
configKey: 'vintl',
compatibility: {
bridge: false,
nuxt: '^3.0.0',
},
},
async setup(inputOptions, nuxt) {
await nuxt.hooks.callHook('vintl:extendOptions', inputOptions)
const runtimeDir = fileURLToPath(new URL('./runtime', import.meta.url))
nuxt.options.build.transpile.push(runtimeDir)
nuxt.options.build.transpile.push('@vintl/vintl')
const resolveInRuntime = createDirResolver(runtimeDir)
addPlugin((await resolveInRuntime('./plugin.js')).path)
if (!nuxt.options._prepare) {
let options: t.output<typeof moduleOptionsSchema>
try {
options = moduleOptionsSchema.parse(inputOptions)
} catch (err) {
if (err instanceof ZodError) {
consola.error(
formatZodError(err, {
initialMessage: 'Invalid Nuxt VIntl configuration',
rootPropertyName: 'vintl',
}),
)
throw new OptionsError(
'You have errors in your Nuxt VIntl configuration, check console log for more information',
)
}
throw err
}
const parserlessModeEnabled = (() => {
const { enabled } = options.parserless
return (
enabled !== 'never' &&
((enabled === 'only-prod' && !nuxt.options.dev) ||
enabled === 'always')
)
})()
const pluginOptionsBank = new PluginOptionsBank()
const optionsFile = addTemplate({
filename: optionsFilePath,
write: true,
async getContents() {
const resolveInResDir = createDirResolver(
resolvePath(nuxt.options.srcDir, options.resolveDir ?? '.'),
)
return await generateOptions(options, {
async resolve(specifier) {
return (await resolveInResDir(specifier)).relativeTo(
optionsFile.dst,
)
},
registerMessagesFile(file, importPath) {
pluginOptionsBank.registerFile(
file,
resolvePath(dirname(optionsFile.dst), importPath),
)
},
async resolveRuntimeModule(specifier) {
return (await resolveInRuntime(specifier)).relativeTo(
optionsFile.dst,
)
},
state: {
parserlessModeEnabled,
},
})
},
})
nuxt.hook('build:manifest', (manifest) => {
purgeEntryResources(
manifest,
Array.from(pluginOptionsBank.enumerateFiles()).map((importPath) =>
relativizePath(nuxt.options.srcDir, importPath),
),
)
})
nuxt.options.alias['@vintl/nuxt-runtime/options'] = optionsFile.dst
const { icuMessages } = await import('@vintl/unplugin')
extendWebpackConfig((cfg) => {
const plugins = (cfg.plugins ??= [])
plugins.push(
...pluginOptionsBank
.createOptions({
output: {
type: parserlessModeEnabled ? 'ast' : 'raw',
},
})
.map((pluginOptions) => icuMessages.webpack(pluginOptions)),
)
})
extendViteConfig((cfg) => {
const plugins = (cfg.plugins ??= [])
plugins.push(
...pluginOptionsBank
.createOptions({
pluginsWrapping: true,
output: {
type: parserlessModeEnabled ? 'ast' : 'raw',
},
})
.map((pluginOptions) => icuMessages.vite(pluginOptions)),
)
})
if (parserlessModeEnabled) {
extendViteConfig((cfg) => {
const aliases = ((cfg.resolve ??= {}).alias ??= {})
if (Array.isArray(aliases)) {
aliases.push({
find: '@formatjs/icu-messageformat-parser',
replacement: '@formatjs/icu-messageformat-parser/lib/no-parser',
})
} else {
Object.assign(aliases, {
'@formatjs/icu-messageformat-parser':
'@formatjs/icu-messageformat-parser/lib/no-parser',
})
}
})
extendWebpackConfig((cfg) => {
const aliases = ((cfg.resolve ??= {}).alias ??= {})
if (Array.isArray(aliases)) {
aliases.push({
name: '@formatjs/icu-messageformat-parser',
alias: '@formatjs/icu-messageformat-parser/lib/no-parser',
})
} else {
aliases['@formatjs/icu-messageformat-parser'] =
'@formatjs/icu-messageformat-parser/lib/no-parser'
}
})
}
}
addImports({
from: '@vintl/vintl',
name: 'useVIntl',
})
addComponent({
filePath: '@vintl/vintl/components',
name: 'IntlFormatted',
export: 'IntlFormatted',
})
addImports({ from: '@formatjs/intl', name: 'defineMessages' })
addImports({ from: '@formatjs/intl', name: 'defineMessage' })
},
})
export interface ModuleHooks {
'vintl:extendOptions'(
options: t.input<typeof moduleOptionsSchema>,
): Promise<void> | void
}
File diff suppressed because it is too large Load Diff
+336
View File
@@ -0,0 +1,336 @@
import type { ModuleOptions } from '@nuxt/schema'
import { createDefu } from 'defu'
import { OptionsError } from './errors.js'
/**
* Represents an import source for the file. It can be just a path to import the
* default export from, or an array (tuple) of an import path and export name
* from the module imported from that path.
*
* For example, if you define your module as
*
* ```js
* export const americanEnglish = {
* greeting: 'Hello, {name}!',
* }
*
* export default { americanEnglish }
* ```
*
* And want to import just `americanEnglish`, then you should use an array
* containing `source` and `exportName` elements as such:
* `['./i18n/messages.js', 'americanEnglish']`. This would effectively resolve
* to this import construction:
*
* ```js
* // non-lazy locale:
* import { 'americanEnglish' as messages } from '<resolveDir>/i18n/messages.js'
*
* // lazy locale import:
* const messages = await import('<resolveDir>/i18n/messages.js').then(
* (imported) => imported['americanEnglish'],
* )
* ```
*/
export type ImportSource = string | [source: string, exportName: string]
/** Represents a configured locale. */
interface LocaleDescriptor {
/**
* A source of import for the messages file, which is resolved against the
* {@link Options.resolveDir}. If {@link files} option specified together with
* this option, this messages file will be imported before any other file
* defined in {@link files}.
*/
file?: ImportSource
/**
* An array of import sources for the message files, resolved against the
* {@link Options.resolveDir} and overriding the messages by previously
* imported sources in the order of their appeareance in the array.
*/
files?: ImportSource[]
/**
* BCP 47 language tag of the locale.
*
* @see https://www.w3.org/International/questions/qa-choosing-language-tags W3 guide on choosing the language tags.
*/
tag: string
/** List of additional side-effect only imports (like polyfill data). */
additionalImports?: string[]
/**
* An array of mapped resource imports.
*
* Unlike additional imports, which are used for side effects, these imports
* will be mapped to provided key in runtime.
*
* This is useful for language-associated documents, which would otherwise
* create frustrating experience for translators be they left as regular
* strings in the messages file.
*/
resources?: Record<string, ImportSource>
/**
* Custom meta for the locale that is always accessible even when the locale
* is not loaded.
*
* It can be used to store data like meta tags. Keep in mind, it needs to be
* JSON serialisable.
*/
meta?: Partial<VueIntlController.LocaleMeta>
}
/**
* Similar to Webpack's condition:
*
* - If a string, the module ID must start with the following string.
* - If a {@link RegExp}, then the module ID must match it.
* - If a function, it must return a truthy value for the module ID.
*/
export type Condition = string | RegExp | ((id: string) => boolean)
/** Settings for the parserless mode. */
export interface ParserlessOptions {
/** Whether to use parserless mode. */
enabled: 'always' | 'only-prod' | 'never' | boolean
}
/** Represents the Nuxt module options. */
export interface Options extends ModuleOptions {
/**
* BCP 47 code of the locale to use by default.
*
* @default 'en-US' // American English will be used as a default locale.
*/
defaultLocale: string
/**
* A directory where all the imports associated with the locales are being
* resolved.
*
* If it's relative, then it will be resolved against the Nuxt `srcDir`
* directory.
*
* @default '.' // Modules will be resolved from Nuxt srcDir.
*/
resolveDir?: string
/** An array of all the configured locales. */
locales: LocaleDescriptor[]
/**
* Either a built-in storage name (localStorage / cookie), node module name or
* path to a file that exports an adapter as default export.
*/
storage?: 'localStorage' | 'cookie' | (string & Record<never, never>)
/**
* Whether to use `BroadcastChannel` (if available) to synchronise locale
* change between multiple tabs on the same origin.
*
* @default true // Broadcasts locale changes to other tabs.
* @see https://developer.mozilla.org/en-US/docs/Web/API/BroadcastChannel
*/
broadcastLocaleChange?: boolean
/**
* Configuration options for the parserless mode, a mode in which the parser
* is removed from runtime and all strings are processed during the initial
* build, which can have drastic bundle size reduction and performance
* improvements. The tradeoff, however, is that no messages can be parsed
* anymore, they all will have to be processed beforehand.
*
* Parserless mode is still an experimental feature and will continue to
* improve with time.
*/
parserlessMode?: ParserlessOptions | ParserlessOptions['enabled']
}
export function createOptionsMerger() {
const mergeLocale = createDefu((output, key, value, namespace) => {
if (namespace === '' && key === 'resources') {
output[key] = Object.assign({}, output[key], value) // shallow
return true
}
})
return createDefu((output, key, value, namespace) => {
if (!(namespace === '' && key === 'locales')) return
if (!Array.isArray(value)) {
throw new TypeError('"locales" must be an array of locale descriptors')
}
const newLocales: LocaleDescriptor[] = []
if (output[key] != null) {
newLocales.push(...(output[key] as LocaleDescriptor[]))
}
for (const locale of value as LocaleDescriptor[]) {
const existingLocaleIndex = newLocales.findIndex(
(it) => it.tag === locale.tag,
)
if (existingLocaleIndex === -1) {
newLocales.push(locale)
} else {
newLocales[existingLocaleIndex] = mergeLocale(
locale,
newLocales[existingLocaleIndex],
)
}
}
output[key] = newLocales as any
return true
})
}
function toTypeString(value: unknown) {
const valueType = typeof value
if (valueType === 'object' && value == null) return 'null'
if (Array.isArray(value)) return 'array'
return valueType
}
function isValidImportSource(value: unknown): value is ImportSource {
return (
typeof value === 'string' ||
(Array.isArray(value) &&
value.length === 2 &&
typeof value[0] === 'string' &&
typeof value[1] === 'string')
)
}
export function assertOptionsValid(
options: Partial<Options>,
): asserts options is Options {
if (options.defaultLocale == null) {
throw new OptionsError('defaultLocale', '{} must have a value')
}
if (!Array.isArray(options.locales)) {
throw new OptionsError(
'locales',
`{} must be an array of locale descriptors (is ${toTypeString(
options.locales,
)})`,
)
}
if (options.locales.length === 0) {
throw new OptionsError(
'locales',
'{} must define at least one locale descriptor',
)
}
const uniqueLocaleCodes = new Set()
for (let i = 0, l = options.locales.length; i < l; i++) {
const locale = options.locales[i]
if (locale == null) {
throw new OptionsError(
`locales[${i}]`,
`{} must be an object (is ${toTypeString(locale)} instead)`,
)
}
if (typeof locale.tag !== 'string') {
throw new OptionsError(
`locales[${i}].tag`,
`{} must be a string containing BCP 47 language tag (is ${toTypeString(
locale.tag,
)} instead)`,
)
}
if (locale.file == null && locale.files == null) {
throw new OptionsError(
`locales[${i}]`,
'{} must include at least one import source containing the messages through `file`, `files`, or both of these options (has none)',
)
}
if (locale.file != null && !isValidImportSource(locale.file)) {
throw new OptionsError(
`locales[${i}].file`,
'{} must a be an import source string or a tuple containing both import source and a custom export name',
)
}
if (locale.files != null) {
if (!Array.isArray(locale.files)) {
throw new OptionsError(
`locales[${i}].files`,
'{} must be an array containing messages import sources',
)
}
if (locale.files.length === 0 && locale.file == null) {
throw new OptionsError(
`locales[${i}].files`,
'{} must include at least one messages import source if no import source is provided with `file` option',
)
}
for (let j = 0, l = locale.files.length; j < l; j++) {
if (!isValidImportSource(locale.files[j])) {
throw new OptionsError(
`locales[${i}].files[${j}]`,
'{} must a be an array of import sources strings or the tuples containing both import sources and their custom export names',
)
}
}
}
let intlLocale: Intl.Locale
try {
intlLocale = new Intl.Locale(locale.tag)
} catch (err) {
const message = err instanceof Error ? `${err.name}: ${err.message}` : err
throw new OptionsError(
`locales[${i}].code`,
`{} must be a valid BCP 47 tag (fails Intl.Locale instantiation: ${message})`,
)
}
const localeTag = intlLocale.toString()
if (uniqueLocaleCodes.has(localeTag)) {
throw new OptionsError(
`locales[${i}]`,
`{} must not duplicate previously added locale descriptor (locale descriptor with tag ${localeTag} is already defined)`,
)
}
uniqueLocaleCodes.add(localeTag)
if (locale.meta != null) {
try {
JSON.stringify(locale.meta)
} catch (err) {
throw new OptionsError(
`locales[${i}].meta`,
`{} must be JSON encodable object (${err})`,
)
}
}
}
if (!options.locales.some((locale) => locale.tag === options.defaultLocale)) {
throw new OptionsError(
'locales',
`{} must have a locale descriptor for default locale (no locale descriptor has code ${options.defaultLocale})`,
)
}
}
+72
View File
@@ -0,0 +1,72 @@
// We have a unplugin that pre-parses / transforms all messages files for us and
// we track every message file import, we need a special class that create
// unique plugin instances.
import type { PluginOptions } from '@vintl/unplugin'
import type { z as t } from 'zod'
import type {
messagesImportOptionsSchema,
messagesImportSourceSchema,
} from './schemas/messages-imports.js'
// we have two unique properties: 1) file structure format 2) file parser
type UniqueOptions = t.output<typeof messagesImportOptionsSchema>
export class PluginOptionsBank {
// let the uniqueOptions be a map of unique options to a list of files that have the same options
private readonly filesByOptions: Map<UniqueOptions, Set<string>> = new Map()
private findOrCreateFileSet(optionsVariation: UniqueOptions) {
for (const [knownOptionsVariation, files] of this.filesByOptions) {
if (
knownOptionsVariation.format === optionsVariation.format &&
knownOptionsVariation.parser === optionsVariation.parser
) {
return files
}
}
const filteredOptions: UniqueOptions = {
format: optionsVariation.format,
parser: optionsVariation.parser,
}
const fileSet = new Set<string>()
this.filesByOptions.set(filteredOptions, fileSet)
return fileSet
}
public registerFile(
file: t.output<typeof messagesImportSourceSchema>,
resolvedPath: string,
) {
this.findOrCreateFileSet(file).add(resolvedPath)
}
public createOptions<T extends { name: string }>(
baseOptions?: PluginOptions<T>,
): PluginOptions<T>[] {
const options: PluginOptions<T>[] = []
for (const [{ format, parser }, files] of this.filesByOptions) {
const filter = (id: string) => files.has(id)
options.push({
...baseOptions,
filter,
format,
parse: parser,
})
}
return options
}
public *enumerateFiles() {
for (const [, files] of this.filesByOptions) {
for (const file of files) {
yield file
}
}
}
}
@@ -0,0 +1,89 @@
import type { IntlController } from '@vintl/vintl/controller'
import type { AfterLocaleChangeEvent } from '@vintl/vintl/events'
import { isOfType } from './utils/type-checks.js'
export function setupBroadcasting(controller: IntlController<any>) {
if (!process.client) return
if (typeof BroadcastChannel !== 'function') {
console.warn(
'[@vintl/nuxt] BroadcastChannel is not available in this browser',
)
return
}
const channel = new BroadcastChannel('@vintl/nuxt:localeChange')
let lastBroadcast: LocaleChangeBroadcast | undefined
function isEqualToLastBroadcast(broadcast: LocaleChangeBroadcast) {
return (
lastBroadcast != null &&
lastBroadcast.automatic === broadcast.automatic &&
lastBroadcast.locale === broadcast.locale
)
}
function onLocaleChange(e: AfterLocaleChangeEvent) {
const broadcast: LocaleChangeBroadcast = {
locale: e.locale.tag,
automatic: e.automatic,
}
if (
((lastBroadcast?.automatic ?? false) && broadcast.automatic) ||
isEqualToLastBroadcast(broadcast)
) {
return // no-op if automation was enabled already
}
channel.postMessage(broadcast)
lastBroadcast = broadcast
}
function onBroadcast(event: MessageEvent<unknown>) {
const broadcast = event.data
if (!isLocaleChangeBroadcast(broadcast)) {
console.warn('[@vintl/nuxt] Received an invalid broadcast', broadcast)
return
}
if (isEqualToLastBroadcast(broadcast)) return
lastBroadcast = broadcast
controller
.changeLocale(broadcast.automatic ? 'auto' : broadcast.locale)
.then(
() => {},
(err) => {
console.warn(
'[@vintl/nuxt] Locale change in reaction to broadcast failed',
err,
)
},
)
}
controller.addEventListener('afterlocalechange', onLocaleChange)
channel.addEventListener('message', onBroadcast)
}
function isLocaleChangeBroadcast(
value: unknown,
): value is LocaleChangeBroadcast {
return (
value != null &&
isOfType('object', value) &&
isOfType('string', value.locale) &&
isOfType('boolean', value.automatic)
)
}
interface LocaleChangeBroadcast {
locale: string
automatic: boolean
}
+87
View File
@@ -0,0 +1,87 @@
import { useHead } from '#imports'
import type { IntlController } from '@vintl/vintl/controller'
import { computed } from 'vue'
import { useRouter } from 'nuxt/app'
type LocationQuery = ReturnType<
typeof useRouter
>['currentRoute']['value']['query']
// I wish there was a better way to do this T_T
function getSeachParams(query: LocationQuery) {
const sp = new URLSearchParams()
Object.entries(query).forEach(([key, value]) => {
if (Array.isArray(value)) {
for (const v of value) {
if (v != null) sp.append(key, v)
}
} else if (value != null) {
sp.append(key, value)
}
})
return sp
}
function withQueryParams(path: string, query: string) {
return query === '' ? path : `${path}?${query}`
}
type LangHrefLink = {
key?: string
rel: string
hreflang: string
href: string
}
export function initHead(controller: IntlController<any>, hlParam: string) {
const router = useRouter()
const currentRoute = computed(() => router.currentRoute.value)
useHead({
htmlAttrs: {
lang: () => controller.$config.locale,
},
link: () => {
const route = currentRoute.value
if (route == null) return []
const query = String(getSeachParams(route.query))
const { path } = route
let defaultEntry: LangHrefLink
{
const sp = new URLSearchParams(query)
sp.delete(hlParam)
defaultEntry = {
// key: `hreflang-default`,
rel: 'alternate',
hreflang: 'x-default',
href: withQueryParams(path, sp.toString()),
}
}
const hrefLangs: Map<string, LangHrefLink> = new Map()
for (const locale of controller.availableLocales) {
const hrefLang = locale.meta?.static?.iso ?? locale.tag
if (hrefLangs.has(hrefLang)) continue
const sp = new URLSearchParams(query)
sp.set(hlParam, locale.tag)
hrefLangs.set(hrefLang, {
// key: `hreflang-${locale.tag}`,
rel: 'alternate',
hreflang: hrefLang,
href: withQueryParams(path, sp.toString()),
})
}
return [defaultEntry, ...hrefLangs.values()]
},
})
}
+175
View File
@@ -0,0 +1,175 @@
import {
defaultLocale,
localeDefinitions,
storageAdapterFactory,
broadcastLocaleChange,
hostLanguageParam,
parserless,
} from '@vintl/nuxt-runtime/options'
import type { LocaleDescriptor, MessageValueType } from '@vintl/vintl'
import type { IntlController } from '@vintl/vintl/controller'
import { createPlugin, type InjectedProperties } from '@vintl/vintl/plugin'
import type {
AfterLocaleChangeEvent,
AutomaticStateChangeEvent,
ErrorEvent,
LocaleChangeEvent,
LocaleLoadEvent,
} from '@vintl/vintl/events'
import { useNavigatorLanguage } from '@vintl/vintl/sources/navigator'
import { useAcceptLanguageHeader } from '@vintl/vintl/sources/header'
import { defineNuxtPlugin } from 'nuxt/app'
import { syncCaller } from './utils/hookable.js'
import { initHead } from './head.js'
export default defineNuxtPlugin(async (nuxtApp) => {
const locales: LocaleDescriptor[] = Object.entries(localeDefinitions).map(
([tag, { meta }]) => ({ tag, meta }),
)
let locale: string | undefined
const storage = storageAdapterFactory?.(nuxtApp) ?? null
if (storage != null) {
try {
locale = (await storage.read()) ?? undefined
} catch (err) {
if (process.dev) {
console.error('[@vintl/nuxt] Cannot read last used locale', err)
}
}
}
if (hostLanguageParam != null) {
let hlLocale = nuxtApp._route.query[hostLanguageParam]
if (Array.isArray(hlLocale)) {
hlLocale = hlLocale[0]
}
if (hlLocale != null) {
locale = hlLocale
}
}
const plugin = createPlugin<MessageValueType>({
injectInto: [nuxtApp],
controllerOpts: {
defaultLocale,
locales,
locale,
listen: {
error(event) {
nuxtApp.hooks.callHookWith(syncCaller, 'i18n:error', {
event,
controller: this,
})
},
localechange(event) {
nuxtApp.hooks.callHookWith(syncCaller, 'i18n:beforeLocaleChange', {
event,
controller: this,
})
},
automatic(event) {
nuxtApp.hooks.callHookWith(syncCaller, 'i18n:automatic', {
event,
controller: this,
})
},
async localeload(event) {
const locale = localeDefinitions[event.locale.tag]
if (locale == null) {
console.warn(
`[@vintl/nuxt] Attempted to load a locale that is not defined: ${event.locale.tag}`,
)
} else {
const { messages, resources } = await locale.importFunction()
event.addMessages(messages)
event.addResources(resources)
}
await nuxtApp.callHook('i18n:extendLocale', {
event,
controller: this,
})
},
async afterlocalechange(event) {
try {
await storage?.save(event.automatic ? null : event.locale.tag)
} catch (_err) {
if (process.dev) {
console.error(
'[@vintl/nuxt] Cannot save last used locale',
event.locale.tag,
)
}
}
await nuxtApp.hooks.callHook('i18n:afterLocaleChange', {
event,
controller: this,
})
},
},
preferredLocaleSources: [
process.server
? (() => {
const acceptLanguage =
nuxtApp.ssrContext?.event.node.req.headers['accept-language']
return useAcceptLanguageHeader(acceptLanguage)
})()
: useNavigatorLanguage(),
],
defaultMessageOrder: parserless
? ['locale', 'descriptor']
: ['descriptor', 'locale'],
},
})
const controller = plugin.getOrCreateController()
await controller.waitUntilReady()
nuxtApp.vueApp.use(plugin)
if (broadcastLocaleChange) {
const { setupBroadcasting } = await import('./broadcasting.js')
setupBroadcasting(controller)
}
if (hostLanguageParam != null) {
nuxtApp.hook('vue:setup', () => initHead(controller, hostLanguageParam!))
}
await nuxtApp.callHook('i18n:ready', controller)
})
type EventContext<E> = {
event: E
controller: IntlController<MessageValueType>
}
declare module 'nuxt/app' {
interface NuxtApp
extends InjectedProperties<VueIntlController.MessageValueTypes> {}
interface RuntimeNuxtHooks {
'i18n:automatic'(ctx: EventContext<AutomaticStateChangeEvent>): void
'i18n:beforeLocaleChange'(ctx: EventContext<LocaleChangeEvent>): void
'i18n:extendLocale'(
ctx: EventContext<LocaleLoadEvent>,
): Promise<void> | void
'i18n:afterLocaleChange'(ctx: EventContext<AfterLocaleChangeEvent>): void
'i18n:error'(ctx: EventContext<ErrorEvent>): void
'i18n:ready'(
controller: IntlController<MessageValueType>,
): Promise<void> | void
}
}
@@ -0,0 +1,34 @@
import type { Plugin } from 'nuxt/app'
type _NuxtApp = Parameters<Plugin>[0]
type MaybePromise<T> = T | PromiseLike<T>
export interface StorageAdapter {
/**
* Saves the locale preference for the user.
*
* @param localeCode BCP 47 of the currently locale used by the user, or
* `null` if automatic mode has been enabled.
*/
save(localeCode: string | null): MaybePromise<void>
/**
* Retrieves the locale preference of the user.
*
* @returns Either BCP 47 locale code for the locale used by user or `null` if
* no there is no saved preference.
*/
read(): MaybePromise<string | null>
}
/** Represents a function that takes in Nuxt context and produces adapter. */
export type StorageAdapterFactory = (nuxtApp: _NuxtApp) => StorageAdapter
export function defineStorageAdapter(
adapterOrFactory: StorageAdapterFactory | StorageAdapter,
): StorageAdapterFactory {
if (typeof adapterOrFactory === 'function') return adapterOrFactory
return () => adapterOrFactory
}
@@ -0,0 +1,26 @@
import { useCookie } from 'nuxt/app'
import { defineStorageAdapter } from '../storage-adapter.js'
export default defineStorageAdapter(() => {
const cookie = useCookie('locale', {
maxAge: 60 * 60 * 24 * 365 * 10,
sameSite: 'strict',
secure: true,
httpOnly: false,
path: '/',
})
return {
read() {
const res = cookie.value
if (res == null || res === '') return null
return res
},
save(localeCode) {
cookie.value = localeCode
},
}
})
@@ -0,0 +1,33 @@
import { defineStorageAdapter } from '../storage-adapter.js'
export default defineStorageAdapter(() => ({
/**
* Retrieves the current locale name from the localStorage.
*
* No-op if `localStorage` is not defined.
*
* @returns Currently saved name in localStorage, or `null` if nothing saved.
*/
read() {
if (typeof localStorage === 'undefined') return null
return localStorage.getItem('locale')
},
/**
* Saves the locale into `localStorage`.
*
* No-op if `localStorage` is not defined.
*
* @param localeCode Locale code to save.
*/
save(localeCode: string | null) {
if (typeof localStorage === 'undefined') return
if (localeCode == null) {
localStorage.removeItem('locale')
} else {
localStorage.setItem('locale', localeCode)
}
},
}))
@@ -0,0 +1,11 @@
import type { HookCallback } from 'hookable'
/**
* Calls all the hooks in synchronous, sequential manner.
*
* @param hooks An array of hooks to call.
* @param arguments_ Arguments to call hooks with.
*/
export function syncCaller(hooks: HookCallback[], arguments_?: any[]): void {
for (const hook of hooks) hook(arguments_)
}
@@ -0,0 +1,103 @@
import type { MessagesMap, Locale } from '@vintl/vintl'
type ResourcesMap = keyof Locale['resources'] extends never
? Record<string, unknown>
: Locale['resources']
type ResourceMapKey = keyof ResourcesMap extends never
? string
: keyof ResourcesMap
type ResourceMapProp<K extends ResourceMapKey> = K extends keyof ResourcesMap
? ResourcesMap[K]
: unknown
const rawValue = Symbol('v')
interface RawValue<T> {
[rawValue]: T
}
export function raw<T>(value: T) {
return {
[rawValue]: value,
} as RawValue<T>
}
function isRaw<T>(value: unknown): value is RawValue<T> {
return value != null && typeof value === 'object' && rawValue in value
}
interface LocaleImport {
messages: MessagesMap
resources: ResourcesMap
}
// eslint-disable-next-line prefer-const
let defaultExport = 'default'
export function locale() {
// eslint-disable-next-line prefer-const
let messages: Partial<MessagesMap>[] = []
// eslint-disable-next-line prefer-const
let allRequests: PromiseLike<unknown>[] = []
// eslint-disable-next-line prefer-const
let resources: ResourcesMap = Object.create(null)
type ThenArgs = Parameters<PromiseLike<LocaleImport>['then']>
return {
m(
messagesImport:
| PromiseLike<Record<string, MessagesMap>>
| RawValue<MessagesMap>,
importProperty = defaultExport,
) {
// eslint-disable-next-line prefer-const
let id = messages.length
if (isRaw(messagesImport)) {
messages[id] = messagesImport[rawValue]
} else {
allRequests.push(
messagesImport.then((imported) => {
messages[id] = imported[importProperty]
}),
)
}
},
r<R extends ResourceMapKey>(
resourceName: R,
resourceImport:
| PromiseLike<Record<string, ResourceMapProp<R>>>
| RawValue<ResourceMapProp<R>>,
importProperty = defaultExport,
) {
if (isRaw(resourceImport)) {
resources[resourceName] = resourceImport[rawValue]
} else {
allRequests.push(
resourceImport.then((imported) => {
resources[resourceName] = imported[importProperty]
}),
)
}
},
i(importReturn: PromiseLike<unknown>) {
allRequests.push(importReturn)
},
then(onFulfilled: ThenArgs[0], onRejected: ThenArgs[1]) {
return Promise.all(allRequests).then(
() =>
onFulfilled?.({
messages: messages.reduce(
(current, value) => Object.assign(current, value),
Object.create(null),
),
resources,
}),
onRejected,
)
},
}
}
@@ -0,0 +1,44 @@
type TypeOfTypes =
| 'string'
| 'number'
| 'bigint'
| 'boolean'
| 'symbol'
| 'undefined'
| 'object'
| 'function'
type TypeOf<T extends TypeOfTypes> = T extends 'string'
? string
: T extends 'number'
? number
: T extends 'bigint'
? bigint
: T extends 'boolean'
? boolean
: T extends 'symbol'
? symbol
: T extends 'undefined'
? undefined
: T extends 'object'
? Record<PropertyKey, unknown> | null
: T extends 'function'
? (this: unknown, ...args: unknown[]) => unknown
: never
/**
* Uses `typeof` expression to check type of the file, provides TypeScript type
* assertion.
*
* @param type Type to use for checking, any valid return value by `typeof`
* expression.
* @param value Value to check using `typeof`.
* @returns Whether the result of `typeof` expression for the `value` matches
* {@link type}.
*/
export function isOfType<T extends TypeOfTypes>(
type: T,
value: unknown,
): value is TypeOf<T> {
return typeof value === type
}
@@ -0,0 +1,84 @@
import { z as t } from 'zod'
import { tSwitch } from '../utils/zod-utils.js'
/** A schema for an object containing import source and custom export name. */
export const importSourceObjectSchema = t.object({
/** Module source relative to the `options.resolveDir`. */
from: t.string({
invalid_type_error: 'Import source must be a string',
}),
/** Custom export name. */
name: t
.string({
invalid_type_error: 'Export name must be a string',
})
.default('default'),
/** Whether to resolve the import to a path or import as is. */
resolve: t.boolean().default(true),
})
/** A schema for the tuple consisting of an import path and a custom export name. */
export const importSourceTupleSchema = t.tuple([
t
.string({
required_error: 'A path must be provided',
invalid_type_error: 'Import path must be a string',
})
.describe(
'Import path from where the export with the name provided as a second element of the tuple is imported',
),
t
.string({
required_error: 'A custom export name must be provided',
invalid_type_error: 'Custom export name must be a string',
})
.describe('Custom export name')
.default('default'),
])
/**
* A schema for a union of import source path or a tuple with import source path
* and a custom export name.
*/
export const importSourceSchema = tSwitch((value) => {
if (typeof value === 'string') {
return t
.string()
.transform((from) => ({ from }))
.pipe(importSourceObjectSchema)
} else if (Array.isArray(value)) {
return importSourceTupleSchema
.transform(([from, name]) => ({ from, name }))
.pipe(importSourceObjectSchema)
} else if (typeof value === 'object' && value !== null) {
return importSourceObjectSchema
}
})
/**
* A schema for an import source without any specifiers (side-effect only
* import).
*/
export const unspecifiedImportSourceObjectSchema =
importSourceObjectSchema.omit({ name: true })
/**
* A schema for an import source without any specifiers (side-effect only
* import) in two form: a string or an object.
*/
export const unspecifiedImportSourceSchema = tSwitch((value) => {
if (typeof value === 'string') {
return t
.string()
.transform((from) => ({ from }))
.pipe(unspecifiedImportSourceObjectSchema)
} else if (
typeof value === 'object' &&
value !== null &&
!Array.isArray(value)
) {
return unspecifiedImportSourceObjectSchema
}
})
+6
View File
@@ -0,0 +1,6 @@
export * from './imports.js'
export * from './messages-imports.js'
export * from './language-tag.js'
export * from './json.js'
export * from './locales.js'
export * from './module-options.js'
+51
View File
@@ -0,0 +1,51 @@
import { z as t } from 'zod'
import { tSwitch } from '../utils/zod-utils.js'
/**
* Checks if provided value is an acceptable JSON literal.
*
* @param value The value to check.
* @returns `true` if the value is a JSON literal, `false` otherwise.
*/
function isLiteral(value: unknown): value is string | number | boolean | null {
return (
typeof value === 'string' ||
typeof value === 'number' ||
typeof value === 'boolean' ||
value === null
)
}
const literalSchema = tSwitch((value) => {
switch (typeof value) {
case 'string':
return t.string()
case 'number':
return t.number()
case 'boolean':
return t.boolean()
}
switch (value) {
case null:
return t.null()
case undefined:
return t.undefined()
}
})
type Literal = t.infer<typeof literalSchema>
type JSONValue = Literal | { [key: string]: JSONValue } | JSONValue[]
export const jsonValueSchema: t.ZodType<JSONValue> = t.lazy(() =>
tSwitch((value) => {
if (isLiteral(value)) {
return literalSchema
} else if (Array.isArray(value)) {
return t.array(jsonValueSchema)
} else if (typeof value === 'object') {
return t.record(jsonValueSchema)
}
}),
)
@@ -0,0 +1,21 @@
import { z as t } from 'zod'
export const languageTagSchema = t
.string({
description: 'BCP 47 language tag',
})
.nonempty()
.refine(
(value) => {
try {
new Intl.Locale(value)
return true
} catch (err) {
return false
}
},
{
message:
'Language tag must be a valid BCP 47 language tag (Intl.Locale instantiation failed)',
},
)
+102
View File
@@ -0,0 +1,102 @@
import { z as t } from 'zod'
import { importSourceSchema, unspecifiedImportSourceSchema } from './imports.js'
import { jsonValueSchema } from './json.js'
import { languageTagSchema } from './language-tag.js'
import { messagesImportSourceSchema } from './messages-imports.js'
export const localeMetaSchema = t
.object({
/** Properties that are used by VIntl. */
static: t
.object({
/**
* If there's a case where BCP 47 language tag wouldn't match `hreflang`
* specification, which is ISO 639-1 for language code and optionally,
* dash and ISO 3166-1 code of the country, this value must be
* specified.
*
* @see [Google Search Central — Tell Google about localized versions of your page § Language codes](https://developers.google.com/search/docs/specialty/international/localized-versions#language-codes)
*/
iso: t
.string()
.refine((v) => v !== 'x-default', 'Must not be x-default')
.optional(), // how about to go crazy and validate it lol
})
.describe('Static properties used by VIntl library')
.optional(),
})
.catchall(jsonValueSchema.optional())
.refine(
(value) => {
try {
JSON.stringify(value)
return true
} catch (err) {
return false
}
},
{ message: 'Locale meta must be JSON serialisable' },
)
export const localeDescriptorSchema = t
.object({
/**
* BCP 47 language of the locale.
*
* @see https://www.w3.org/International/questions/qa-choosing-language-tags W3 guide on choosing the language tags.
*/
tag: languageTagSchema,
/**
* A source of import for the messages file, which is resolved against the
* {@link Options.resolveDir}. If {@link files} option specified together with
* this option, this messages file will be imported before any other file
* defined in {@link files}.
*/
file: messagesImportSourceSchema.optional(),
/**
* BCP 47 language tag of the locale.
*
* @see https://www.w3.org/International/questions/qa-choosing-language-tags W3 guide on choosing the language tags.
*/
files: t.array(messagesImportSourceSchema).optional(),
/** List of additional side-effect only imports (like polyfill data). */
additionalImports: t
.array(unspecifiedImportSourceSchema)
.describe(
'List of additional side-effect only imports (like polyfill data)',
)
.optional(),
/**
* An array of mapped resource imports.
*
* Unlike additional imports, which are used for side effects, these imports
* will be mapped to provided key in runtime.
*
* This is useful for language-associated documents, which would otherwise
* create frustrating experience for translators be they left as regular
* strings in the messages file.
*/
resources: t.record(importSourceSchema).optional(),
/**
* Custom meta for the locale that is always accessible even when the locale
* is not loaded.
*
* It can be used to store data like translation coverage percentage, or
* display names. Keep in mind, it needs to be JSON serialisable.
*/
meta: localeMetaSchema.optional(),
})
.refine(
(value) => {
return value.file != null || value.files != null
},
{
message:
'LocaleDescriptor must contain at least one of `file` or `files`',
},
)
@@ -0,0 +1,107 @@
import { z as t } from 'zod'
import { tSwitch } from '../utils/zod-utils.js'
import { importSourceObjectSchema, importSourceTupleSchema } from './imports.js'
export const messagesImportFormatterName = t.string({
invalid_type_error: 'Format must be a string',
})
export const messagesImportFormatterFunction = t.function(
t.tuple([t.unknown()]),
t.record(t.string()),
)
/** A schema for the locale import options. */
export const messagesImportOptionsSchema = t.object({
/** Format of the messages file, either CLI name or . */
format: tSwitch((value) => {
if (typeof value === 'string') {
return messagesImportFormatterName
} else if (typeof value === 'function') {
return messagesImportFormatterFunction
}
}).default('default'),
/**
* A function that parses the imported file into a JS object later used by the
* formatter.
*/
parser: t
.function(
t.tuple([t.string().describe('Code'), t.string().describe('Module ID')]),
t.any().describe('Output used by the formatter'),
)
.optional(),
})
export const messagesImportSourceObjectSchema = importSourceObjectSchema
.omit({ resolve: true })
.merge(messagesImportOptionsSchema)
// const _messagesImportSourceSchema = t.union([
// t.string(),
// importSourceWithSpecifierSchema,
// messagesImportSourceObjectSchema,
// ])
// /** A schema for the locale import source. */
// export const messagesImportSourceSchema = t.any().transform((value, ctx) => {
// if (Array.isArray(value)) {
// const r = messagesImportSourceObjectSchema.safeParse({
// source: value[0],
// name: value[1],
// })
// if (r.success) {
// return r.data
// } else {
// r.error.issues.forEach((i) => ctx.addIssue(i))
// return undefined as never
// }
// } else if (typeof value === 'string') {
// const r = messagesImportSourceObjectSchema.safeParse({
// source: value,
// })
// if (r.success) {
// return r.data
// } else {
// r.error.issues.forEach((i) => ctx.addIssue(i))
// return undefined as never
// }
// } else if (typeof value === 'object' && value != null) {
// const r = messagesImportSourceObjectSchema.safeParse(value)
// if (r.success) {
// return r.data
// } else {
// r.error.issues.forEach((i) => ctx.addIssue(i))
// return undefined as never
// }
// }
// {
// const r = t.never().safeParse(value)
// if (r.success) {
// return r.data
// } else {
// r.error.issues.forEach((i) => ctx.addIssue(i))
// return undefined as never
// }
// }
// }) as unknown as typeof _messagesImportSourceSchema
export const messagesImportSourceSchema = tSwitch((value) => {
if (Array.isArray(value)) {
return importSourceTupleSchema
.transform((v) => ({ from: v[0], name: v[1] }))
.pipe(messagesImportSourceObjectSchema)
} else if (typeof value === 'string') {
return t
.string()
.transform((v) => ({ from: v }))
.pipe(messagesImportSourceObjectSchema)
} else if (typeof value === 'object' && value != null) {
return messagesImportSourceObjectSchema
}
})
// type In = t.input<typeof messagesImportSourceSchema>
// type Out = t.output<typeof messagesImportSourceSchema>
@@ -0,0 +1,202 @@
import { z as t } from 'zod'
import { tSwitch } from '../utils/zod-utils.js'
import { languageTagSchema } from './language-tag.js'
import { localeDescriptorSchema } from './locales.js'
const parselessModeEnumSchema = t.enum(['always', 'only-prod', 'never'])
export const parselessModeSchema = tSwitch((value) => {
if (typeof value === 'string') {
return parselessModeEnumSchema
} else if (typeof value === 'boolean') {
return t
.boolean()
.transform((value) => (value ? 'always' : 'never'))
.pipe(parselessModeEnumSchema)
}
})
export const parselessOptionsSchema = t
.object({
/** Specifies whether the parseless mode is enabled. */
enabled: parselessModeSchema.optional().default(false),
})
.describe('Options for the parseless mode')
export const storageValueSchema = t.custom<
'localStorage' | 'cookie' | (string & Record<never, never>)
>((value) => {
return t.string().safeParse(value).success
}, 'Storage name must be a string')
export const moduleOptionsSchema = t
.object({
/**
* BCP 47 code of the locale to use by default.
*
* @default 'en-US' // American English will be used as a default locale.
*/
defaultLocale: languageTagSchema.default('en-US'),
/**
* A directory where all the imports associated with the locales are being
* resolved.
*
* If it's relative, then it will be resolved against the Nuxt `srcDir`
* directory.
*
* @default '.' // Modules will be resolved from Nuxt srcDir.
*/
resolveDir: t
.string()
.describe('Directory where all the imports are being resolved')
.default('.'),
/** An array of all the configured locales. */
locales: t
.array(localeDescriptorSchema)
.min(1, {
message: 'Must define at least one locale',
})
.superRefine((locales, ctx) => {
const localeTagIndexes = new Map<string, number[]>()
const hrefLangIndexes = new Map<string, number[]>()
// const conflicts = new Map<
// number,
// {
// tags: number[]
// hreflangs: number[]
// }
// >()
// const mapConflicts = (localeIndex: number) => {
// let ret = conflicts.get(localeIndex)
// if (ret == null) {
// ret = {
// tags: [],
// hreflangs: [],
// }
// conflicts.set(localeIndex, ret)
// }
// return ret
// }
// const uniquePush = <T>(arr: T[], value: T) => {
// if (arr.includes(value)) {
// return
// }
// arr.push(value)
// }
for (let i = 0, l = locales.length; i < l; i++) {
const locale = locales[i]!
{
const prevIndexes = localeTagIndexes.get(locale.tag)
if (prevIndexes === undefined) {
localeTagIndexes.set(locale.tag, [i])
} else {
prevIndexes.push(i)
}
}
{
const hrefLang = locale.meta?.static?.iso ?? locale.tag
const prevIndexes = hrefLangIndexes.get(hrefLang)
if (prevIndexes === undefined) {
hrefLangIndexes.set(hrefLang, [i])
} else {
prevIndexes.push(i)
}
}
}
for (const [tag, indexes] of localeTagIndexes) {
if (indexes.length < 2) continue
ctx.addIssue({
code: 'custom',
params: {
type: 'language_tag_conflicts',
tag,
indexes,
},
message: `Language "${tag}" is defined multiple times at indexes ${indexes.join(
', ',
)}`,
})
}
for (const [hrefLang, indexes] of hrefLangIndexes) {
if (indexes.length < 2) continue
ctx.addIssue({
code: 'custom',
params: {
type: 'hreflang_conflicts',
hrefLang,
indexes,
},
message: `Multiple occurances of hreflang "${hrefLang}" at indexes ${indexes.join(
', ',
)}`,
})
}
}),
/**
* Either a built-in storage name (localStorage / cookie), node module name
* or path to a file that exports an adapter as default export.
*/
storage: storageValueSchema.optional(),
/**
* Whether to use `BroadcastChannel` (if available) to synchronise locale
* change between multiple tabs on the same origin.
*
* @default true // Broadcasts locale changes to other tabs.
* @see https://developer.mozilla.org/en-US/docs/Web/API/BroadcastChannel
*/
broadcastLocaleChange: t
.boolean()
.describe(
'A boolean value that specifies whether the `BroadcastChannel` is used to synchronise locale changes between multiple tabs on the same origin.',
)
.default(true),
/**
* Name of the host language URL parameter, used to override the default or
* user language. `null` to disable. If this value is `null`, the SEO tags
* generation will be disabled.
*
* @default 'hl' // For example, ?hl=en to use English locale (if defined).
*/
hostLanguageParam: t
.string()
.describe(
'Name of the host language URL parameter, used to override the default or user language.',
)
.nullable()
.default('hl'),
/**
* Configuration options for the parserless mode, a mode in which the parser
* is removed from runtime and all strings are processed during the initial
* build, which can have drastic bundle size reduction and performance
* improvements. The tradeoff, however, is that no messages can be parsed
* anymore, they all will have to be processed beforehand.
*
* Parserless mode is still an experimental feature and will continue to
* improve with time.
*/
parserless: tSwitch((value) => {
if (typeof value === 'string') {
return parselessModeSchema
.transform((value) => ({ enabled: value }))
.pipe(parselessOptionsSchema)
} else if (typeof value === 'object' && value !== null) {
return parselessOptionsSchema
}
}).default('only-prod'),
})
.refine((value) => {
return value.locales.some((locale) => locale.tag === value.defaultLocale)
}, 'Default locale must be defined')
View File
+63
View File
@@ -0,0 +1,63 @@
import { readdir, stat } from 'node:fs/promises'
import { join } from 'path'
/**
* Creates a generator that yields for each file in the directory, and files
* within each subdirectory as long as `depth` is not less than `1`.
*
* The {@link depth} parameter declares the depth this generator is willing to
* go. When visiting a subdirectory the depth will be reduced by one, therefore
* it will eventually settle at 0, unless it was `Infinity` (which it is by
* default!).
*
* For example, assuming you provide a depth of `1`, you will get the following
* results for our example directory path `animal_pictures`:
*
* - `cats` - visited, `depth` > 0
*
* - `other_cats` - ignored, `depth` is 0 at this level
*
* - `cheetah1.jpg` - not yielded: parent is never visited
* - `cat1.jpg` - yielded as `cats/cat1.jpg`
* - `cat2.jpg` - yielded as `cats/cat2.jpg`
* - `dogs` - visited, `depth` > 0
*
* - `dog1.jpg` - yielded as `dogs/dog1.jpg`
*
* Path separator matches the system one.
*
* This function has no recursion prevention in place, any directory link will
* be visited and if it leads to the current directory, it will also return. One
* way to prevent that would be to store all visited files, which is not done
* here for the simplicity, but since it's a generator, you can always use
* `break` to exit the loop, or throw an error, if you have to.
*
* @param directoryPath Path of the directory which file names to yield.
* @param depth The depth of the walk.
* @returns A generator which yields names of files in the directory and
* subdirectories as long as the depth allows.
*/
export async function* filesWithin(
directoryPath: string,
depth = Infinity,
): AsyncGenerator<string, void, boolean | undefined> {
for (const entry of await readdir(directoryPath)) {
const entryPath = join(directoryPath, entry)
const stats = await stat(entryPath)
if (stats.isDirectory()) {
if (depth > 0) {
for await (const subentry of filesWithin(entryPath, depth - 1)) {
yield join(entry, subentry)
}
} else {
continue
}
}
const yieldResult = yield entry
if (yieldResult != null && yieldResult) break
}
}
@@ -0,0 +1,32 @@
/**
* Checks whether `typeof` for the provided value equals to `'function'`.
*
* The reason for such wrapper is to avoid TypeScript complaints because
* behaviour of `typeof` in TypeScript is weird at best: if for `value` typeof
* is a `'function'` in regular TypeScript, then TypeScript assumes it's `typeof
* value & {}` (???) instead of just assuming that it `value` that extends
* function.
*
* This wrapper will do just that, but its return type is set to return
* assumption that `value` is all of `value` that extends function or never.
*
* Thus `isFunction(myValue)` where type of `myValue` is `(() => boolean) | (()
* => number) | boolean | number`, it will return assumption that if this
* function returns `true`, then `myValue` is one of `(() => boolean) | (() =>
* number)`.
*
* The opposite applies - if type of `myValue` would be just `boolean | number`,
* then it'd return an assumption that if this function returns `true`, then
* `myValue` is of `never` type, which is correct, because this function is
* never supposed to return `true` for that union type.
*
* Which is precisely the behaviour you'd expect from TypeScript, but oh well.
*
* @param value Value to check.
* @returns Whether the typeof value equals to `'function'`.
*/
export function isFunction<T>(
value: T,
): value is T extends (...args: any[]) => any ? T : never {
return typeof value === 'function'
}
@@ -0,0 +1,45 @@
import { fileURLToPath, pathToFileURL } from 'node:url'
import { resolve as rawResolve } from 'import-meta-resolve'
import { dirname, join as joinPaths, relative as relativizePath } from 'pathe'
import slash from 'slash'
export function createDirResolver(dir: string) {
const pseudoParent = pathToFileURL(joinPaths(dir, '.resolve-root')).toString()
return async function resolve(specifier: string) {
const resolved = await rawResolve(specifier, pseudoParent)
return {
/** A getter that returns resolved URL as is. */
get url() {
return resolved
},
/** A getter that converts resolved URL in a form of POSIX path. */
get path() {
return slash(fileURLToPath(resolved))
},
/**
* Converts resolved path to a relative path from the provided directory.
*
* @param from Directory to get relative path to the resolved path from.
* @returns Relative to the directory path.
*/
relativeToDir(from: string) {
return relativizePath(slash(from), this.path)
},
/**
* Converts resolved path to a relative path from the provided file.
*
* @param from File from which the module is imported relatively.
* @returns Relative to the file path.
*/
relativeTo(from: string) {
return this.relativeToDir(dirname(from))
},
}
}
}
export async function resolveToPath(specifier: string, parent: string) {
return slash(fileURLToPath(await rawResolve(specifier, parent)))
}

Some files were not shown because too many files have changed in this diff Show More