@things-factory/i18n-base 8.0.0-beta.9 → 8.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@things-factory/i18n-base",
3
- "version": "8.0.0-beta.9",
3
+ "version": "8.0.2",
4
4
  "main": "dist-server/index.js",
5
5
  "browser": "dist-client/index.js",
6
6
  "things-factory": true,
@@ -27,9 +27,9 @@
27
27
  "migration:create": "node ../../node_modules/typeorm/cli.js migration:create ./server/migrations/migration"
28
28
  },
29
29
  "dependencies": {
30
- "@operato/i18n": "^8.0.0-beta",
31
- "@things-factory/auth-base": "^8.0.0-beta.9",
32
- "@things-factory/shell": "^8.0.0-beta.9"
30
+ "@operato/i18n": "^8.0.0",
31
+ "@things-factory/auth-base": "^8.0.2",
32
+ "@things-factory/shell": "^8.0.2"
33
33
  },
34
- "gitHead": "86b1dfa26292926a2d5447fdc23bfa5a9e983245"
34
+ "gitHead": "39d60f56e142561233ddf6d47b539c637971357c"
35
35
  }
@@ -0,0 +1 @@
1
+ export * from './t'
@@ -0,0 +1,36 @@
1
+ import { getRepository } from '@things-factory/shell'
2
+
3
+ import { Terminology } from '../service/terminology/terminology'
4
+
5
+ export type T_Arugments = {
6
+ key: String
7
+ locale: String
8
+ options?: Object
9
+ }
10
+
11
+ export async function t({ key, locale = 'en-US', options }: T_Arugments) {
12
+ let value = await getTerminology({
13
+ key,
14
+ locale
15
+ })
16
+
17
+ return value
18
+ }
19
+
20
+ async function getTerminology({ key, locale }) {
21
+ const repo = getRepository(Terminology)
22
+ var value
23
+ try {
24
+ let term = await repo.findOne({
25
+ where: {
26
+ name: key,
27
+ locale
28
+ }
29
+ })
30
+ value = term.display
31
+ } catch (e) {
32
+ value = key
33
+ }
34
+
35
+ return value
36
+ }
@@ -0,0 +1,18 @@
1
+ import { config } from '@things-factory/env'
2
+
3
+ const disableCustomTerminologyFeature = config.get('i18n/disableCustomTerminologyFeature')
4
+
5
+ const path = require('path')
6
+ var fs = require('fs')
7
+
8
+ export function clearTranslationCacheForCertainDomain(subdomain: string) {
9
+ if (disableCustomTerminologyFeature) {
10
+ return
11
+ }
12
+
13
+ const cacheFileFolder = path.join('cache', 'translations', subdomain)
14
+
15
+ if (fs.existsSync(cacheFileFolder)) {
16
+ fs.rmSync(cacheFileFolder, { recursive: true })
17
+ }
18
+ }
@@ -0,0 +1,6 @@
1
+ import './routes'
2
+
3
+ export * from './service'
4
+ export * from './apis'
5
+ export * from './middlewares'
6
+ export * from './controllers/clear-cache-for-translation.js'
@@ -0,0 +1,36 @@
1
+ import fs from 'fs'
2
+ import i18next from 'i18next'
3
+
4
+ import koaI18next from './koa-i18next'
5
+ import { build } from './translations'
6
+
7
+ i18next.init({
8
+ debug: false,
9
+ ns: ['translations'],
10
+ defaultNS: 'translations',
11
+ preload: ['ko', 'en', 'jp', 'zh', 'ms'],
12
+ fallbackLng: 'en',
13
+ interpolation: {
14
+ prefix: '{',
15
+ suffix: '}'
16
+ },
17
+ load: 'languageOnly',
18
+ keySeparator: false
19
+ })
20
+
21
+ build(fs)
22
+
23
+ process.on('client-rebuilt' as any, (app, fs) => {
24
+ /* rebuild once done webpacking assets. only for development mode. */
25
+ build(fs)
26
+ })
27
+
28
+ export function initMiddlewares(app: any) {
29
+ app.use(
30
+ koaI18next(i18next, {
31
+ lookupCookie: 'i18next',
32
+ order: ['cookie', 'header'],
33
+ next: true // if koa is version 2
34
+ })
35
+ )
36
+ }
@@ -0,0 +1,108 @@
1
+ const DEFAULT_ORDER = ['querystring', 'cookie', 'header']
2
+
3
+ const detectors = {
4
+ cookie: function (context, options) {
5
+ let cookie = options.lookupCookie || 'i18next'
6
+ return context.cookies.get(cookie)
7
+ },
8
+
9
+ // fork from i18next-express-middleware
10
+ header: function (context) {
11
+ let acceptLanguage = context.get('accept-language')
12
+ let found
13
+ let locales = []
14
+ if (acceptLanguage) {
15
+ let lngs = []
16
+
17
+ // associate language tags by their 'q' value (between 1 and 0)
18
+ acceptLanguage.split(',').forEach(function (l) {
19
+ let parts = l.split(';') // 'en-GB;q=0.8' -> ['en-GB', 'q=0.8']
20
+
21
+ // get the language tag qvalue: 'q=0.8' -> 0.8
22
+ let qvalue = 1 // default qvalue
23
+
24
+ for (let i = 0; i < parts.length; i++) {
25
+ let part = parts[i].split('=')
26
+ if (part[0] === 'q' && !isNaN(part[1])) {
27
+ qvalue = Number(part[1])
28
+ break
29
+ }
30
+ }
31
+ // add the tag and primary subtag to the qvalue associations
32
+ lngs.push({
33
+ lng: parts[0],
34
+ q: qvalue
35
+ })
36
+ })
37
+
38
+ lngs.sort(function (a, b) {
39
+ return b.q - a.q
40
+ })
41
+
42
+ for (let i = 0; i < lngs.length; i++) {
43
+ locales.push(lngs[i].lng)
44
+ }
45
+
46
+ if (locales.length) found = locales
47
+ }
48
+
49
+ return found
50
+ },
51
+ path: function (context, options) {
52
+ let found
53
+
54
+ if (options.lookupPath !== undefined && context.params) {
55
+ found = context.params[options.lookupPath]
56
+ }
57
+
58
+ if (!found && options.lookupFromPathIndex !== undefined) {
59
+ let parts = context.path.split('/')
60
+ if (parts[0] === '') {
61
+ // Handle paths that start with a slash, i.e., '/foo' -> ['', 'foo']
62
+ parts.shift()
63
+ }
64
+
65
+ if (parts.length > options.lookupFromPathIndex) {
66
+ found = parts[options.lookupFromPathIndex]
67
+ }
68
+ }
69
+ return found
70
+ },
71
+ querystring: function (context, options) {
72
+ let name = options.lookupQuerystring || 'lng'
73
+ return context.query[name]
74
+ },
75
+
76
+ session: function (context, options) {
77
+ let name = options.lookupSession || 'lng'
78
+ return context.session && context.session[name]
79
+ }
80
+ }
81
+
82
+ export default function (context, options = {}) {
83
+ let { order, fallback } = options as any
84
+ order = order && Array.isArray(order) ? order : DEFAULT_ORDER
85
+
86
+ let lngs = []
87
+
88
+ for (let i = 0, len = order.length; i < len; i++) {
89
+ let detector = detectors[order[i]]
90
+ let lng
91
+ if (detector) {
92
+ lng = detector(context, options)
93
+ }
94
+ if (lng && typeof lng === 'string') {
95
+ lngs.push(lng)
96
+ } else {
97
+ lngs = lngs.concat(lng)
98
+ }
99
+ }
100
+ let found
101
+ for (let i = 0, len = lngs.length; i < len; i++) {
102
+ let cleanedLng = context.i18next.services.languageUtils.formatLanguageCode(lngs[i])
103
+ if (context.i18next.services.languageUtils.isSupportedCode(cleanedLng)) found = cleanedLng
104
+ if (found) break
105
+ }
106
+
107
+ return found || fallback
108
+ }
@@ -0,0 +1,142 @@
1
+ import detect from './detect'
2
+
3
+ import { config } from '@things-factory/env'
4
+
5
+ const disableUserFavoredLanguage = config.get('i18n/disableUserFavoredLanguage', false)
6
+ const defaultLanguage = config.get('i18n/defaultLanguage', 'en-US')
7
+
8
+ export default function koaI18next(i18next, options = {} as any) {
9
+ return async function i18nextMiddleware(ctx, next) {
10
+ ctx.i18next = i18next
11
+
12
+ let lng = disableUserFavoredLanguage ? defaultLanguage : detect(ctx, options)
13
+ lng && setLanguage(ctx, lng, options)
14
+
15
+ ctx.t = function (...args) {
16
+ // do detect path
17
+ if (!lng && isDetectPath(options.order)) {
18
+ lng = detect(ctx, Object.assign(options, { order: ['path'] }))
19
+ lng && setLanguage(ctx, lng, options)
20
+ }
21
+
22
+ if (args.length === 1) {
23
+ args.push({})
24
+ }
25
+
26
+ for (let i = 0, len = args.length; i < len; i++) {
27
+ let arg = args[i]
28
+ if (typeof arg === 'object' && !Array.isArray(arg)) {
29
+ arg.lng = lng
30
+ }
31
+ }
32
+ return i18next.t.apply(i18next, args)
33
+ }
34
+
35
+ await next()
36
+ }
37
+ }
38
+
39
+ function setPath(object, path, newValue) {
40
+ let stack
41
+ if (typeof path !== 'string') stack = [].concat(path)
42
+ if (typeof path === 'string') stack = path.split('.')
43
+
44
+ while (stack.length > 1) {
45
+ let key = stack.shift()
46
+ if (key.indexOf('###') > -1) key = key.replace(/###/g, '.')
47
+ if (!object[key]) object[key] = {}
48
+ object = object[key]
49
+ }
50
+
51
+ let key = stack.shift()
52
+ if (key.indexOf('###') > -1) key = key.replace(/###/g, '.')
53
+ object[key] = newValue
54
+ }
55
+
56
+ koaI18next.getResourcesHandler = function (i18next, options) {
57
+ options = options || {}
58
+ let maxAge = options.maxAge || 60 * 60 * 24 * 30
59
+ const propertyParam = options.propertyParam || 'query'
60
+
61
+ return async function (ctx, next) {
62
+ if (options.path && ctx.path !== options.path) {
63
+ return await next()
64
+ }
65
+ if (!i18next.services.backendConnector) return ctx.throw(404, 'koa-i18next-middleware:: no backend configured')
66
+
67
+ let resources = {}
68
+
69
+ ctx.type = 'json'
70
+ if (options.cache !== undefined ? options.cache : process.env.NODE_ENV === 'production') {
71
+ ctx.set('Cache-Control', 'public, max-age=' + maxAge)
72
+ ctx.set('Expires', new Date(new Date().getTime() + maxAge * 1000).toUTCString())
73
+ } else {
74
+ ctx.set('Pragma', 'no-cache')
75
+ ctx.set('Cache-Control', 'no-cache')
76
+ }
77
+
78
+ let languages = ctx[propertyParam][options.lngParam || 'lng']
79
+ ? ctx[propertyParam][options.lngParam || 'lng'].split(' ')
80
+ : []
81
+ let namespaces = ctx[propertyParam][options.nsParam || 'ns']
82
+ ? ctx[propertyParam][options.nsParam || 'ns'].split(' ')
83
+ : []
84
+
85
+ // extend ns
86
+ namespaces.forEach(ns => {
87
+ if (i18next.options.ns && i18next.options.ns.indexOf(ns) < 0) i18next.options.ns.push(ns)
88
+ })
89
+
90
+ i18next.services.backendConnector.load(languages, namespaces, function () {
91
+ languages.forEach(lng => {
92
+ namespaces.forEach(ns => {
93
+ setPath(resources, [lng, ns], i18next.getResourceBundle(lng, ns))
94
+ })
95
+ })
96
+ ctx.body = resources
97
+ })
98
+ }
99
+ }
100
+
101
+ koaI18next.getMissingKeyHandler = function (i18next, options) {
102
+ options = options || {}
103
+ const propertyParam = options.propertyParam || 'query'
104
+
105
+ return async function (ctx, next) {
106
+ if (options.path && ctx.path !== options.path) {
107
+ return await next()
108
+ }
109
+ let lng = ctx[propertyParam][options.lngParam || 'lng']
110
+ let ns = ctx[propertyParam][options.nsParam || 'ns']
111
+
112
+ if (!i18next.services.backendConnector) return ctx.throw(404, 'koa-i18next-middleware:: no backend configured')
113
+
114
+ for (var m in ctx.request.body) {
115
+ i18next.services.backendConnector.saveMissing([lng], ns, m, ctx.request.body[m])
116
+ }
117
+ ctx.body = 'ok'
118
+ }
119
+ }
120
+
121
+ function isDetectPath(order = []) {
122
+ return order.indexOf('path') !== -1
123
+ }
124
+
125
+ function setLanguage(context, lng, options = {} as any) {
126
+ const { lookupCookie, lookupPath, lookupSession } = options
127
+ context.locals = Object.assign(context.locals || {}, { lng })
128
+ context.state = Object.assign(context.state || {}, { lng })
129
+ context.language = context.lng = lng
130
+ context.set('content-language', lng)
131
+
132
+ if (lookupCookie) {
133
+ context.cookies.set(lookupCookie, lng, {
134
+ httpOnly: false,
135
+ signed: false,
136
+ sameSite: 'strict'
137
+ })
138
+ }
139
+ if (lookupSession && context.session) {
140
+ context.session[lookupSession] = lng
141
+ }
142
+ }
@@ -0,0 +1,27 @@
1
+ import FS from 'fs'
2
+ import i18next from 'i18next'
3
+ import path from 'path'
4
+
5
+ const { appRootPath } = require('@things-factory/env')
6
+
7
+ export function build(fs) {
8
+ fs = fs || FS
9
+
10
+ const PUBLIC_ROOT = path.resolve(appRootPath, 'dist-app') // webpack config output.path
11
+
12
+ const ns = 'translations'
13
+ var folder = path.join(PUBLIC_ROOT, 'translations')
14
+ try {
15
+ fs.readdirSync(folder).forEach(file => {
16
+ try {
17
+ var lng = file.split('.')[0]
18
+ var resourcePath = path.join(folder, file)
19
+ var resources = JSON.parse(fs.readFileSync(resourcePath))
20
+ i18next.removeResourceBundle(lng, ns)
21
+ i18next.addResourceBundle(lng, ns, resources, true, true)
22
+ } catch (e) {
23
+ console.error(e)
24
+ }
25
+ })
26
+ } catch (e) {}
27
+ }
@@ -0,0 +1,87 @@
1
+ import Router from 'koa-router'
2
+ import { ILike } from 'typeorm'
3
+
4
+ import { getRepository } from '@things-factory/shell'
5
+ import { Terminology } from '../service/terminology/terminology'
6
+ import { config } from '@things-factory/env'
7
+
8
+ const path = require('path')
9
+ const cacheFS = require('fs')
10
+ var fs = require('fs')
11
+
12
+ const disableCustomTerminologyFeature = config.get('i18n/disableCustomTerminologyFeature')
13
+
14
+ process.on('client-rebuilt' as any, (app, compilerFileSystem) => {
15
+ /* change filesystem whenever webpacking assets done. only for development mode. */
16
+ fs = compilerFileSystem
17
+
18
+ if (!disableCustomTerminologyFeature) {
19
+ const cacheFileFolder = path.join('cache', 'translations')
20
+
21
+ if (cacheFS.existsSync(cacheFileFolder)) {
22
+ cacheFS.rmSync(cacheFileFolder, { recursive: true })
23
+ }
24
+ }
25
+ })
26
+
27
+ export const translationsRouter = new Router()
28
+
29
+ translationsRouter.get('/translations/:filename', async (context, next) => {
30
+ const { filename } = context.params
31
+ const { domain } = context.state
32
+
33
+ const locale = (filename || 'en.json').split('.')[0]
34
+
35
+ // context.set('Cache-Control', 'public, max-age=31536000') // 캐시 기간 설정 : 1년
36
+ // context.set('Expires', new Date(Date.now() + 31536000000).toUTCString()) // 캐시 만료일 설정
37
+
38
+ if (disableCustomTerminologyFeature) {
39
+ var file = fs.readFileSync(path.resolve(path.join('dist-app', 'translations', filename)))
40
+
41
+ context.type = 'application/json'
42
+ context.body = file
43
+ return
44
+ }
45
+
46
+ const cacheFileFolder = path.join('cache', 'translations', domain.subdomain)
47
+ const cacheFilePath = path.join(cacheFileFolder, filename)
48
+
49
+ if (cacheFS.existsSync(cacheFilePath)) {
50
+ var file = cacheFS.readFileSync(cacheFilePath)
51
+ } else {
52
+ var file = fs.readFileSync(path.resolve(path.join('dist-app', 'translations', filename)))
53
+
54
+ try {
55
+ const terminologies = await getRepository(Terminology).find({
56
+ where: { domain: { id: domain.id }, locale: ILike(locale + '%') }
57
+ })
58
+
59
+ const json = JSON.parse(file)
60
+
61
+ terminologies.forEach(term => {
62
+ const { name, category, display } = term
63
+ json[`${category}.${name}`] = display
64
+ })
65
+
66
+ try {
67
+ if (!cacheFS.existsSync(cacheFileFolder)) {
68
+ cacheFS.mkdirSync(cacheFileFolder, { recursive: true })
69
+ }
70
+
71
+ cacheFS.writeFileSync(cacheFilePath, JSON.stringify(json))
72
+ } catch (err) {
73
+ console.error(err)
74
+ }
75
+
76
+ context.type = 'application/json'
77
+ context.body = json
78
+
79
+ return
80
+ } catch (err) {
81
+ console.error(err)
82
+ }
83
+ }
84
+
85
+ context.type = 'application/json'
86
+ context.body = file
87
+ })
@@ -0,0 +1,31 @@
1
+ import i18next from 'i18next'
2
+ import { config } from '@things-factory/env'
3
+
4
+ const disableCustomTerminologyFeature = config.get('i18n/disableCustomTerminologyFeature')
5
+ const isPathBaseDomain = !config.get('subdomain') && !config.get('useVirtualHostBasedDomain')
6
+
7
+ import { translationsRouter } from './routers/translations-router'
8
+
9
+ process.on('bootstrap-module-global-public-route' as any, (app, globalPublicRouter) => {
10
+ globalPublicRouter.get('/translations/translate/:lng/:key', async (context, next) => {
11
+ const { lng, key } = context.params
12
+ const translated = i18next.getFixedT(lng, 'translations' /* ns */)(key)
13
+
14
+ context.body = translated
15
+ })
16
+
17
+ globalPublicRouter.get('/translations/translate/:key', async (context, next) => {
18
+ const { key } = context.params
19
+ const translated = context.t(key)
20
+
21
+ context.body = translated
22
+ })
23
+ })
24
+
25
+ process.on('bootstrap-module-domain-public-route' as any, (app, domainPublicRouter) => {
26
+ if (isPathBaseDomain) {
27
+ domainPublicRouter.use('/domain/:subdomain', translationsRouter.routes(), translationsRouter.allowedMethods())
28
+ } else if (!disableCustomTerminologyFeature) {
29
+ domainPublicRouter.use('', translationsRouter.routes(), translationsRouter.allowedMethods())
30
+ }
31
+ })
@@ -0,0 +1,27 @@
1
+ /* EXPORT ENTITY TYPES */
2
+ export * from './terminology/terminology'
3
+ export * from './terminology/terminology-type'
4
+
5
+ /* IMPORT ENTITIES AND RESOLVERS */
6
+ import {
7
+ entities as TerminologyEntities,
8
+ resolvers as TerminologyResolvers,
9
+ subscribers as TerminologySubscribers
10
+ } from './terminology'
11
+
12
+ export const entities = [
13
+ /* ENTITIES */
14
+ ...TerminologyEntities
15
+ ]
16
+
17
+ export const subscribers = [
18
+ /* SUBSCRIBERS */
19
+ ...TerminologySubscribers
20
+ ]
21
+
22
+ export const schema = {
23
+ resolverClasses: [
24
+ /* RESOLVER CLASSES */
25
+ ...TerminologyResolvers
26
+ ]
27
+ }
@@ -0,0 +1,7 @@
1
+ import { Terminology } from './terminology'
2
+ import { TerminologyQuery } from './terminology-query'
3
+ import { TerminologyMutation } from './terminology-mutation'
4
+
5
+ export const entities = [Terminology]
6
+ export const resolvers = [TerminologyQuery, TerminologyMutation]
7
+ export const subscribers = []