npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@intlify/hono-edge

v0.1.1-28304927.e6f0de0

Published

Internationalization middleware & utilities for Hono

Downloads

6

Readme

@intlify/hono

npm version npm downloads CI

Internationalization middleware & utilities for Hono

🌟 Features

✅️  Translation: Simple API like vue-i18n

✅  Custom locale detector: You can implement your own locale detector on server-side

✅️️  Useful utilities: support internationalization composables utilities via @intlify/utils

💿 Installation

# Using npm
npm install @intlify/hono

# Using yarn
yarn add @intlify/hono

# Using pnpm
pnpm add @intlify/hono

# Using bun
bun add @intlify/hono

🚀 Usage

import { Hono } from 'hono'
import {
  defineI18nMiddleware,
  detectLocaleFromAcceptLanguageHeader,
  useTranslation,
} from '@intlify/hono'

// define middleware with vue-i18n like options
const i18nMiddleware = defineI18nMiddleware({
  // detect locale with `accept-language` header
  locale: detectLocaleFromAcceptLanguageHeader,
  // resource messages
  messages: {
    en: {
      hello: 'Hello {name}!',
    },
    ja: {
      hello: 'こんにちは、{name}!',
    },
  },
  // something options
  // ...
})

const app = new Hono()

// install middleware with `app.use`
app.use('*', i18nMiddleware)

app.get('/', c => {
  // use `useTranslation` in handler
  const t = useTranslation(c)
  return c.text(t('hello', { name: 'hono' }) + `\n`)
})

export default app

🛠️ Custom locale detection

You can detect locale with your custom logic from current Context.

example for detecting locale from url query:

import { defineI18nMiddleware, getQueryLocale } from '@intlify/hono'
import type { Context } from 'hono'

const DEFAULT_LOCALE = 'en'

// define custom locale detector
const localeDetector = (ctx: Context): string => {
  try {
    return getQueryLocale(ctx).toString()
  } catch () {
    return DEFAULT_LOCALE
  }
}

const middleware = defineI18nMiddleware({
  // set your custom locale detector
  locale: localeDetector,
  // something options
  // ...
})

🧩 Type-safe resources

[!WARNING]
This is experimental feature (inspired from vue-i18n). We would like to get feedback from you 🙂.

[!NOTE] The exeample code is here

You can support the type-safe resources with schema using TypeScript on defineI18nMiddleware options.

Locale messages resource:

export default {
  hello: 'hello, {name}!'
}

your application code:

import { defineI18nMiddleware } from '@intlify/hono'
import en from './locales/en.ts'

// define resource schema, as 'en' is master resource schema
type ResourceSchema = typeof en

const i18nMiddleware = defineI18nMiddleware<[ResourceSchema], 'en' | 'ja'>({
  messages: {
    en: { hello: 'Hello, {name}' },
  },
  // something options
  // ...
})

// someting your implementation code ...
// ...

Result of type checking with tsc:

npx tsc --noEmit
index.ts:13:3 - error TS2741: Property 'ja' is missing in type '{ en: { hello: string; }; }' but required in type '{ en: ResourceSchema; ja: ResourceSchema; }'.

13   messages: {
     ~~~~~~~~

  ../../node_modules/@intlify/core/node_modules/@intlify/core-base/dist/core-base.d.ts:125:5
    125     messages?: {
            ~~~~~~~~
    The expected type comes from property 'messages' which is declared here on type 'CoreOptions<string, { message: ResourceSchema; datetime: DateTimeFormat; number: NumberFormat; }, { messages: "en"; datetimeFormats: "en"; numberFormats: "en"; } | { ...; }, ... 8 more ..., NumberFormats<...>>'


Found 1 error in index.ts:13

If you are using Visual Studio Code as an editor, you can notice that there is a resource definition omission in the editor with the following error before you run the typescript compilation.

Type-safe resources

🖌️ Resource keys completion

[!WARNING]
This is experimental feature (inspired from vue-i18n). We would like to get feedback from you 🙂.

[!NOTE] Resource Keys completion can be used if you are using Visual Studio Code

You can completion resources key on translation function with useTranslation.

Key Completion

resource keys completion has twe ways.

Type parameter for useTranslation

[!NOTE] The exeample code is here

You can useTranslation set the type parameter to the resource schema you want to key completion of the translation function.

the part of example:

app.get('/', c => {
  type ResourceSchema = {
    hello: string
  }
  // set resource schema as type parameter
  const t = useTranslation<ResourceSchema>(c)
  // you can completion when you type `t('`
  return c.json(t('hello', { name: 'hono' }))
}),

global resource schema with declare module '@intlify/hono'

[!NOTE] The exeample code is here

You can do resource key completion with the translation function using the typescript declare module.

the part of example:

import en from './locales/en.ts'

// 'en' resource is master schema
type ResourceSchema = typeof en

// you can put the type extending with `declare module` as global resource schema
declare module '@intlify/hono' {
  // extend `DefineLocaleMessage` with `ResourceSchema`
  export interface DefineLocaleMessage extends ResourceSchema {}
}

app.get('/', c => {
  const t = useTranslation(c)
  // you can completion when you type `t('`
  return c.json(t('hello', { name: 'hono' }))
}),

The advantage of this way is that it is not necessary to specify the resource schema in the useTranslation type parameter.

🛠️ Utilites & Helpers

@intlify/hono has a concept of composable utilities & helpers.

Utilities

@intlify/hono composable utilities accept context (from (context) => {})) as their first argument. (Exclud useTranslation) return the Intl.Locale

Translations

  • useTranslation(context): use translation function

Headers

  • getHeaderLocale(context, options): get locale from accept-language header
  • getHeaderLocales(context, options): get some locales from accept-language header

Cookies

  • getCookieLocale(context, options): get locale from cookie
  • setCookieLocale(context, options): set locale to cookie

Misc

  • getPathLocale(context, options): get locale from path
  • getQueryLocale(context, options): get locale from query

Helpers

  • detectLocaleFromAcceptLanguageHeader(context): detect locale from accept-language header

🙌 Contributing guidelines

If you are interested in contributing to @intlify/hono, I highly recommend checking out the contributing guidelines here. You'll find all the relevant information such as how to make a PR, how to setup development) etc., there.

©️ License

MIT