nesties 1.1.5 → 1.1.7
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/dist/index.cjs +577 -24
- package/dist/index.cjs.map +4 -4
- package/dist/index.d.ts +2 -0
- package/dist/index.mjs +577 -18
- package/dist/index.mjs.map +4 -4
- package/dist/src/i18n-module/i18n-decorator.d.ts +2 -0
- package/dist/src/i18n-module/i18n-factory.d.ts +8 -0
- package/dist/src/i18n-module/i18n-middleware.type.d.ts +3 -0
- package/dist/src/i18n-module/i18n-module.options.d.ts +6 -0
- package/dist/src/i18n-module/i18n-token.d.ts +5 -0
- package/dist/src/i18n-module/i18n.interceptor.d.ts +7 -0
- package/dist/src/i18n-module/i18n.module.d.ts +3 -0
- package/dist/src/i18n-module/i18n.service.d.ts +22 -0
- package/dist/src/i18n-module/index.d.ts +9 -0
- package/dist/src/i18n-module/locale.pipe.d.ts +14 -0
- package/dist/src/i18n-module/middlewares/index.d.ts +1 -0
- package/dist/src/i18n-module/middlewares/lookup.d.ts +9 -0
- package/dist/src/resolver.d.ts +12 -0
- package/dist/src/token.guard.d.ts +10 -3
- package/dist/src/utility/awaitable.d.ts +1 -0
- package/dist/src/utility/parse-i18n.d.ts +14 -0
- package/index.ts +2 -0
- package/package.json +3 -2
- /package/dist/src/{abort-http-signal.d.ts → utility/abort-http-signal.d.ts} +0 -0
package/dist/index.cjs
CHANGED
|
@@ -6,11 +6,11 @@ var __export = (target, all) => {
|
|
|
6
6
|
for (var name in all)
|
|
7
7
|
__defProp(target, name, { get: all[name], enumerable: true });
|
|
8
8
|
};
|
|
9
|
-
var __copyProps = (to,
|
|
10
|
-
if (
|
|
11
|
-
for (let key of __getOwnPropNames(
|
|
9
|
+
var __copyProps = (to, from2, except, desc) => {
|
|
10
|
+
if (from2 && typeof from2 === "object" || typeof from2 === "function") {
|
|
11
|
+
for (let key of __getOwnPropNames(from2))
|
|
12
12
|
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
13
|
-
__defProp(to, key, { get: () =>
|
|
13
|
+
__defProp(to, key, { get: () => from2[key], enumerable: !(desc = __getOwnPropDesc(from2, key)) || desc.enumerable });
|
|
14
14
|
}
|
|
15
15
|
return to;
|
|
16
16
|
};
|
|
@@ -34,6 +34,7 @@ __export(index_exports, {
|
|
|
34
34
|
ApiBlankResponse: () => ApiBlankResponse,
|
|
35
35
|
ApiError: () => ApiError,
|
|
36
36
|
ApiErrorTyped: () => ApiErrorTyped,
|
|
37
|
+
ApiFromResolver: () => ApiFromResolver,
|
|
37
38
|
ApiTypeResponse: () => ApiTypeResponse,
|
|
38
39
|
As: () => As,
|
|
39
40
|
BlankPaginatedReturnMessageDto: () => BlankPaginatedReturnMessageDto,
|
|
@@ -43,22 +44,31 @@ __export(index_exports, {
|
|
|
43
44
|
DataQuery: () => DataQuery,
|
|
44
45
|
GenericPaginatedReturnMessageDto: () => GenericPaginatedReturnMessageDto,
|
|
45
46
|
GenericReturnMessageDto: () => GenericReturnMessageDto,
|
|
47
|
+
I18nInterceptor: () => I18nInterceptor,
|
|
48
|
+
I18nLookupMiddleware: () => I18nLookupMiddleware,
|
|
49
|
+
I18nModule: () => I18nModule,
|
|
50
|
+
I18nService: () => I18nService,
|
|
46
51
|
InjectAbortSignal: () => InjectAbortSignal,
|
|
47
52
|
InjectAbortable: () => InjectAbortable,
|
|
48
53
|
InsertField: () => InsertField,
|
|
54
|
+
LocalePipe: () => LocalePipe,
|
|
49
55
|
MergeClassDecorators: () => MergeClassDecorators,
|
|
50
56
|
MergeClassOrMethodDecorators: () => MergeClassOrMethodDecorators,
|
|
51
57
|
MergeMethodDecorators: () => MergeMethodDecorators,
|
|
52
58
|
MergeParameterDecorators: () => MergeParameterDecorators,
|
|
53
59
|
MergePropertyDecorators: () => MergePropertyDecorators,
|
|
54
60
|
PaginatedReturnMessageDto: () => PaginatedReturnMessageDto,
|
|
61
|
+
PutLocale: () => PutLocale,
|
|
55
62
|
RequireToken: () => RequireToken,
|
|
56
63
|
ReturnMessageDto: () => ReturnMessageDto,
|
|
57
64
|
StringReturnMessageDto: () => StringReturnMessageDto,
|
|
58
65
|
TokenGuard: () => TokenGuard,
|
|
59
66
|
abortableToken: () => abortableToken,
|
|
60
67
|
createAbortableProvider: () => createAbortableProvider,
|
|
68
|
+
createI18n: () => createI18n,
|
|
69
|
+
createI18nDecorator: () => createI18nDecorator,
|
|
61
70
|
createProvider: () => createProvider,
|
|
71
|
+
createResolver: () => createResolver,
|
|
62
72
|
fromAbortable: () => fromAbortable,
|
|
63
73
|
getClassFromClassOrArray: () => getClassFromClassOrArray,
|
|
64
74
|
takeUntilAbort: () => takeUntilAbort
|
|
@@ -254,40 +264,161 @@ var DataBody = createDataPipeDec(import_common2.Body);
|
|
|
254
264
|
// src/token.guard.ts
|
|
255
265
|
var import_common3 = require("@nestjs/common");
|
|
256
266
|
var import_config = require("@nestjs/config");
|
|
267
|
+
var import_swagger5 = require("@nestjs/swagger");
|
|
268
|
+
|
|
269
|
+
// src/resolver.ts
|
|
257
270
|
var import_swagger4 = require("@nestjs/swagger");
|
|
271
|
+
var coerceToString = (v) => {
|
|
272
|
+
if (v == null) return void 0;
|
|
273
|
+
if (v === false) return void 0;
|
|
274
|
+
if (Array.isArray(v)) return v.length ? coerceToString(v[0]) : void 0;
|
|
275
|
+
if (typeof v === "string") return v;
|
|
276
|
+
if (typeof v === "number") return String(v);
|
|
277
|
+
return void 0;
|
|
278
|
+
};
|
|
279
|
+
var getHeader = (req, name) => {
|
|
280
|
+
const viaMethod = typeof req.getHeader === "function" && req.getHeader(name) || typeof req.header === "function" && req.header(name) || typeof req.get === "function" && req.get(name);
|
|
281
|
+
if (viaMethod) {
|
|
282
|
+
return coerceToString(viaMethod);
|
|
283
|
+
}
|
|
284
|
+
const n = name.toLowerCase();
|
|
285
|
+
const headers = req.headers ?? {};
|
|
286
|
+
if (n in headers) return coerceToString(headers[n]);
|
|
287
|
+
const hit = Object.entries(headers).find(([k]) => k.toLowerCase() === n)?.[1];
|
|
288
|
+
return coerceToString(hit);
|
|
289
|
+
};
|
|
290
|
+
var pickPrimaryFromAcceptLanguage = (v) => {
|
|
291
|
+
if (!v) return void 0;
|
|
292
|
+
const first = v.split(",")[0]?.trim();
|
|
293
|
+
return first?.split(";")[0]?.trim() || first;
|
|
294
|
+
};
|
|
295
|
+
function getQueryValue(req, key) {
|
|
296
|
+
const q = req.query;
|
|
297
|
+
if (q && typeof q === "object" && !("raw" in q)) {
|
|
298
|
+
const v = q[key];
|
|
299
|
+
if (v != null) return coerceToString(v);
|
|
300
|
+
}
|
|
301
|
+
const rawUrl = req.originalUrl ?? req.url;
|
|
302
|
+
if (typeof rawUrl === "string" && rawUrl.includes("?")) {
|
|
303
|
+
try {
|
|
304
|
+
const search = rawUrl.startsWith("http") ? new URL(rawUrl).search : new URL(rawUrl, "http://localhost").search;
|
|
305
|
+
if (search) {
|
|
306
|
+
const params = new URLSearchParams(search);
|
|
307
|
+
const val = params.get(key);
|
|
308
|
+
if (val != null) return val;
|
|
309
|
+
}
|
|
310
|
+
} catch {
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
return void 0;
|
|
314
|
+
}
|
|
315
|
+
var createResolver = (_options) => {
|
|
316
|
+
if (typeof _options === "function") {
|
|
317
|
+
return _options;
|
|
318
|
+
}
|
|
319
|
+
const options = _options;
|
|
320
|
+
const field = options.paramType;
|
|
321
|
+
let name = options.paramName;
|
|
322
|
+
if (field === "header") name = name.toLowerCase();
|
|
323
|
+
return (ctx) => {
|
|
324
|
+
const req = ctx.switchToHttp().getRequest();
|
|
325
|
+
if (field === "header") {
|
|
326
|
+
let raw = getHeader(req, name);
|
|
327
|
+
if (name === "accept-language") raw = pickPrimaryFromAcceptLanguage(raw);
|
|
328
|
+
return raw;
|
|
329
|
+
}
|
|
330
|
+
if (field === "query") {
|
|
331
|
+
return getQueryValue(req, name);
|
|
332
|
+
}
|
|
333
|
+
throw new Error(`Unsupported paramType: ${field}`);
|
|
334
|
+
};
|
|
335
|
+
};
|
|
336
|
+
var ApiFromResolver = (_options, extras = {}) => {
|
|
337
|
+
if (typeof _options === "function") {
|
|
338
|
+
return () => {
|
|
339
|
+
};
|
|
340
|
+
}
|
|
341
|
+
const options = _options;
|
|
342
|
+
const paramType = options?.paramType;
|
|
343
|
+
const apiOptions = {
|
|
344
|
+
name: options.paramName,
|
|
345
|
+
...extras
|
|
346
|
+
};
|
|
347
|
+
return paramType === "header" ? (0, import_swagger4.ApiHeader)(apiOptions) : paramType === "query" ? (0, import_swagger4.ApiQuery)({ type: "string", ...apiOptions }) : () => {
|
|
348
|
+
};
|
|
349
|
+
};
|
|
350
|
+
|
|
351
|
+
// src/token.guard.ts
|
|
352
|
+
var import_typed_reflector = require("typed-reflector");
|
|
353
|
+
var import_core = require("@nestjs/core");
|
|
354
|
+
var reflector = new import_typed_reflector.Reflector();
|
|
355
|
+
var Metadata = new import_typed_reflector.MetadataSetter();
|
|
356
|
+
var defaultHeaderName = "x-server-token";
|
|
357
|
+
var defaultConfigName = "SERVER_TOKEN";
|
|
358
|
+
var defaultErrorCode = 401;
|
|
258
359
|
var TokenGuard = class {
|
|
259
|
-
constructor(config) {
|
|
360
|
+
constructor(config, moduleRef) {
|
|
260
361
|
this.config = config;
|
|
261
|
-
this.
|
|
362
|
+
this.moduleRef = moduleRef;
|
|
262
363
|
}
|
|
263
364
|
async canActivate(context) {
|
|
264
|
-
const
|
|
265
|
-
const
|
|
266
|
-
|
|
267
|
-
|
|
365
|
+
const controller = context.getClass();
|
|
366
|
+
const handlerName = context.getHandler()?.name;
|
|
367
|
+
let config = {};
|
|
368
|
+
if (controller) {
|
|
369
|
+
if (handlerName) {
|
|
370
|
+
config = reflector.get("requireTokenOptions", controller, handlerName) || {};
|
|
371
|
+
} else {
|
|
372
|
+
config = reflector.get("requireTokenOptions", controller) || {};
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
const resolver = createResolver(
|
|
376
|
+
config.resolver || { paramType: "header", paramName: defaultHeaderName }
|
|
377
|
+
);
|
|
378
|
+
const tokenSource = config.tokenSource || defaultConfigName;
|
|
379
|
+
const [tokenFromClient, tokenFromConfig] = await Promise.all([
|
|
380
|
+
resolver(context, this.moduleRef),
|
|
381
|
+
typeof tokenSource === "function" ? tokenSource(context, this.moduleRef) : this.config.get(tokenSource)
|
|
382
|
+
]);
|
|
383
|
+
if (tokenFromConfig && tokenFromConfig !== tokenFromClient) {
|
|
384
|
+
throw new BlankReturnMessageDto(
|
|
385
|
+
config.errorCode || defaultErrorCode,
|
|
386
|
+
"Unauthorized"
|
|
387
|
+
).toException();
|
|
268
388
|
}
|
|
269
389
|
return true;
|
|
270
390
|
}
|
|
271
391
|
};
|
|
272
392
|
TokenGuard = __decorateClass([
|
|
273
393
|
(0, import_common3.Injectable)(),
|
|
274
|
-
__decorateParam(0, (0, import_common3.Inject)(import_config.ConfigService))
|
|
394
|
+
__decorateParam(0, (0, import_common3.Inject)(import_config.ConfigService)),
|
|
395
|
+
__decorateParam(1, (0, import_common3.Inject)(import_core.ModuleRef))
|
|
275
396
|
], TokenGuard);
|
|
276
|
-
var RequireToken = () =>
|
|
277
|
-
|
|
278
|
-
(0, import_swagger4.ApiHeader)({
|
|
279
|
-
name: "x-server-token",
|
|
397
|
+
var RequireToken = (options = {}) => {
|
|
398
|
+
const swaggerDec = options.resolver ? ApiFromResolver(options.resolver, {
|
|
280
399
|
description: "Server token",
|
|
281
400
|
required: false
|
|
282
|
-
}),
|
|
283
|
-
|
|
284
|
-
|
|
401
|
+
}) : (0, import_swagger5.ApiHeader)({
|
|
402
|
+
name: defaultHeaderName,
|
|
403
|
+
description: "Server token",
|
|
404
|
+
required: false
|
|
405
|
+
});
|
|
406
|
+
return MergeClassOrMethodDecorators([
|
|
407
|
+
(0, import_common3.UseGuards)(TokenGuard),
|
|
408
|
+
swaggerDec,
|
|
409
|
+
ApiError(
|
|
410
|
+
options.errorCode || defaultErrorCode,
|
|
411
|
+
"Incorrect server token provided"
|
|
412
|
+
),
|
|
413
|
+
...options ? [Metadata.set("requireTokenOptions", options)] : []
|
|
414
|
+
]);
|
|
415
|
+
};
|
|
285
416
|
|
|
286
417
|
// src/abort-utils.ts
|
|
287
418
|
var import_rxjs = require("rxjs");
|
|
288
419
|
var import_common4 = require("@nestjs/common");
|
|
289
420
|
|
|
290
|
-
// src/abort-http-signal.ts
|
|
421
|
+
// src/utility/abort-http-signal.ts
|
|
291
422
|
function toRawReq(req) {
|
|
292
423
|
if (req?.raw?.socket) return req.raw;
|
|
293
424
|
return req;
|
|
@@ -364,7 +495,7 @@ var import_nfkit = require("nfkit");
|
|
|
364
495
|
|
|
365
496
|
// src/abortable-module/abort-signal.provider.ts
|
|
366
497
|
var import_common5 = require("@nestjs/common");
|
|
367
|
-
var
|
|
498
|
+
var import_core2 = require("@nestjs/core");
|
|
368
499
|
|
|
369
500
|
// src/create-provider.ts
|
|
370
501
|
var createProvider = (options, factory) => {
|
|
@@ -382,14 +513,14 @@ var AbortSignalProvider = createProvider(
|
|
|
382
513
|
{
|
|
383
514
|
provide: ABORT_SIGNAL,
|
|
384
515
|
scope: import_common5.Scope.REQUEST,
|
|
385
|
-
inject: [
|
|
516
|
+
inject: [import_core2.REQUEST]
|
|
386
517
|
},
|
|
387
518
|
createAbortSignalFromHttp
|
|
388
519
|
);
|
|
389
520
|
var InjectAbortSignal = () => (0, import_common5.Inject)(ABORT_SIGNAL);
|
|
390
521
|
|
|
391
522
|
// src/abortable-module/abortable.token.ts
|
|
392
|
-
var
|
|
523
|
+
var import_core3 = require("@nestjs/core");
|
|
393
524
|
var tokenMemo = /* @__PURE__ */ new Map();
|
|
394
525
|
var abortableToken = (token) => {
|
|
395
526
|
if (tokenMemo.has(token)) return tokenMemo.get(token);
|
|
@@ -419,10 +550,10 @@ function createAbortableProvider(token, opts) {
|
|
|
419
550
|
{
|
|
420
551
|
provide,
|
|
421
552
|
scope: import_common6.Scope.REQUEST,
|
|
422
|
-
inject: [
|
|
553
|
+
inject: [import_core3.ModuleRef, import_core3.REQUEST, ABORT_SIGNAL]
|
|
423
554
|
},
|
|
424
555
|
async (moduleRef, req, signal) => {
|
|
425
|
-
const ctxId =
|
|
556
|
+
const ctxId = import_core3.ContextIdFactory.getByRequest(req);
|
|
426
557
|
const svc = await moduleRef.resolve(token, ctxId, { strict: false });
|
|
427
558
|
if (svc == null) {
|
|
428
559
|
throw new Error(
|
|
@@ -461,6 +592,418 @@ var AbortableModule = class {
|
|
|
461
592
|
AbortableModule = __decorateClass([
|
|
462
593
|
(0, import_common7.Module)({})
|
|
463
594
|
], AbortableModule);
|
|
595
|
+
|
|
596
|
+
// src/i18n-module/i18n.service.ts
|
|
597
|
+
var import_common9 = require("@nestjs/common");
|
|
598
|
+
|
|
599
|
+
// src/i18n-module/i18n-token.ts
|
|
600
|
+
var import_common8 = require("@nestjs/common");
|
|
601
|
+
var I18nResolverToken = Symbol("I18nResolverToken");
|
|
602
|
+
var { ConfigurableModuleClass, MODULE_OPTIONS_TOKEN } = new import_common8.ConfigurableModuleBuilder().build();
|
|
603
|
+
var I18nModuleOptionsToken = MODULE_OPTIONS_TOKEN;
|
|
604
|
+
|
|
605
|
+
// src/utility/parse-i18n.ts
|
|
606
|
+
var parseI18n = (text) => {
|
|
607
|
+
const pieces = [];
|
|
608
|
+
if (!text) return pieces;
|
|
609
|
+
let i = 0;
|
|
610
|
+
const n = text.length;
|
|
611
|
+
while (i < n) {
|
|
612
|
+
const start = text.indexOf("#{", i);
|
|
613
|
+
if (start === -1) {
|
|
614
|
+
if (i < n) pieces.push({ type: "raw", value: text.slice(i) });
|
|
615
|
+
break;
|
|
616
|
+
}
|
|
617
|
+
let j = start + 2;
|
|
618
|
+
let depth = 1;
|
|
619
|
+
while (j < n && depth > 0) {
|
|
620
|
+
const ch = text.charCodeAt(j);
|
|
621
|
+
if (ch === 123) depth++;
|
|
622
|
+
else if (ch === 125) depth--;
|
|
623
|
+
j++;
|
|
624
|
+
}
|
|
625
|
+
if (depth !== 0) {
|
|
626
|
+
pieces.push({ type: "raw", value: text.slice(i) });
|
|
627
|
+
break;
|
|
628
|
+
}
|
|
629
|
+
if (start > i) {
|
|
630
|
+
pieces.push({ type: "raw", value: text.slice(i, start) });
|
|
631
|
+
}
|
|
632
|
+
const rawInner = text.slice(start + 2, j - 1);
|
|
633
|
+
const key = rawInner.trim();
|
|
634
|
+
pieces.push({ type: "ph", rawInner, key });
|
|
635
|
+
i = j;
|
|
636
|
+
}
|
|
637
|
+
return pieces;
|
|
638
|
+
};
|
|
639
|
+
|
|
640
|
+
// src/i18n-module/i18n.service.ts
|
|
641
|
+
var import_core4 = require("@nestjs/core");
|
|
642
|
+
var I18nService = class {
|
|
643
|
+
constructor(options, moduleRef) {
|
|
644
|
+
this.options = options;
|
|
645
|
+
this.moduleRef = moduleRef;
|
|
646
|
+
this.resolver = createResolver(this.options.resolver);
|
|
647
|
+
this.locales = new Set(this.options.locales);
|
|
648
|
+
this.defaultLocale = this.options.defaultLocale ?? this.options.locales[0];
|
|
649
|
+
this.middlewares = [];
|
|
650
|
+
this.logger = new import_common9.ConsoleLogger("I18nService");
|
|
651
|
+
}
|
|
652
|
+
middleware(mw, prior = false) {
|
|
653
|
+
if (prior) {
|
|
654
|
+
this.middlewares.unshift(mw);
|
|
655
|
+
} else {
|
|
656
|
+
this.middlewares.push(mw);
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
buildFallbackChain(locale) {
|
|
660
|
+
const best = this.getExactLocale(locale);
|
|
661
|
+
const parts = [];
|
|
662
|
+
const segs = best.split("-");
|
|
663
|
+
for (let i = segs.length; i > 1; i--)
|
|
664
|
+
parts.push(segs.slice(0, i).join("-"));
|
|
665
|
+
parts.push(segs[0]);
|
|
666
|
+
if (!parts.includes(this.defaultLocale)) parts.push(this.defaultLocale);
|
|
667
|
+
return Array.from(new Set(parts)).filter((p) => this.locales.has(p));
|
|
668
|
+
}
|
|
669
|
+
async applyMiddlewares(locale, text, ctx) {
|
|
670
|
+
const mws = this.middlewares;
|
|
671
|
+
const tryLocale = async (loc) => {
|
|
672
|
+
const dispatch = async (i) => {
|
|
673
|
+
if (i >= mws.length) return void 0;
|
|
674
|
+
const mw = mws[i];
|
|
675
|
+
let nextCalled = false;
|
|
676
|
+
const next = async () => {
|
|
677
|
+
nextCalled = true;
|
|
678
|
+
return dispatch(i + 1);
|
|
679
|
+
};
|
|
680
|
+
try {
|
|
681
|
+
const res = await mw(loc, text, next, ctx);
|
|
682
|
+
if (res == null && !nextCalled) {
|
|
683
|
+
return dispatch(i + 1);
|
|
684
|
+
}
|
|
685
|
+
return res;
|
|
686
|
+
} catch (e) {
|
|
687
|
+
if (e instanceof import_common9.HttpException) {
|
|
688
|
+
throw e;
|
|
689
|
+
}
|
|
690
|
+
this.logger.warn(`Middleware at index ${i} threw an error: ${e}`);
|
|
691
|
+
return dispatch(i + 1);
|
|
692
|
+
}
|
|
693
|
+
};
|
|
694
|
+
return dispatch(0);
|
|
695
|
+
};
|
|
696
|
+
for (const loc of this.buildFallbackChain(locale)) {
|
|
697
|
+
const result = await tryLocale(loc);
|
|
698
|
+
if (result != null) {
|
|
699
|
+
return result;
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
return void 0;
|
|
703
|
+
}
|
|
704
|
+
getExactLocale(locale) {
|
|
705
|
+
const input = (locale ?? "").trim();
|
|
706
|
+
if (!input) return this.defaultLocale;
|
|
707
|
+
if (this.locales.has(input)) return input;
|
|
708
|
+
const entries = Array.from(this.locales).map((l) => ({
|
|
709
|
+
orig: l,
|
|
710
|
+
lower: l.toLowerCase()
|
|
711
|
+
}));
|
|
712
|
+
const lower = input.toLowerCase();
|
|
713
|
+
const exact = entries.find((e) => e.lower === lower);
|
|
714
|
+
if (exact) return exact.orig;
|
|
715
|
+
const parts = lower.split("-");
|
|
716
|
+
while (parts.length > 1) {
|
|
717
|
+
parts.pop();
|
|
718
|
+
const candidate = parts.join("-");
|
|
719
|
+
const hit = entries.find((e) => e.lower === candidate);
|
|
720
|
+
if (hit) return hit.orig;
|
|
721
|
+
}
|
|
722
|
+
return this.defaultLocale;
|
|
723
|
+
}
|
|
724
|
+
async getExactLocaleFromRequest(ctx) {
|
|
725
|
+
const locale = await this.resolver(ctx, this.moduleRef);
|
|
726
|
+
return this.getExactLocale(locale);
|
|
727
|
+
}
|
|
728
|
+
async translateString(locale, text, ctx) {
|
|
729
|
+
if (!text) return text;
|
|
730
|
+
locale = this.getExactLocale(locale);
|
|
731
|
+
const pieces = parseI18n(text);
|
|
732
|
+
if (!pieces.some((p) => p.type === "ph")) {
|
|
733
|
+
return pieces.map((p) => p.type === "raw" ? p.value : `#{${p.rawInner}}`).join("");
|
|
734
|
+
}
|
|
735
|
+
const promises = [];
|
|
736
|
+
for (const p of pieces) {
|
|
737
|
+
if (p.type === "ph") {
|
|
738
|
+
promises.push(this.applyMiddlewares(locale, p.key, ctx));
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
const results = await Promise.all(promises);
|
|
742
|
+
let out = "";
|
|
743
|
+
let k = 0;
|
|
744
|
+
for (const p of pieces) {
|
|
745
|
+
if (p.type === "raw") {
|
|
746
|
+
out += p.value;
|
|
747
|
+
} else {
|
|
748
|
+
const r = results[k++];
|
|
749
|
+
out += r == null ? `#{${p.rawInner}}` : r;
|
|
750
|
+
}
|
|
751
|
+
}
|
|
752
|
+
return out;
|
|
753
|
+
}
|
|
754
|
+
async translate(locale, obj, ctx) {
|
|
755
|
+
const visited = /* @__PURE__ */ new WeakSet();
|
|
756
|
+
const isBuiltInObject = (v) => {
|
|
757
|
+
if (v == null || typeof v !== "object") return false;
|
|
758
|
+
if (v instanceof Date || v instanceof RegExp || v instanceof Map || v instanceof Set || v instanceof WeakMap || v instanceof WeakSet || v instanceof ArrayBuffer || v instanceof DataView || ArrayBuffer.isView(v))
|
|
759
|
+
return true;
|
|
760
|
+
const tag = Object.prototype.toString.call(v);
|
|
761
|
+
switch (tag) {
|
|
762
|
+
case "[object URL]":
|
|
763
|
+
case "[object URLSearchParams]":
|
|
764
|
+
case "[object Error]":
|
|
765
|
+
case "[object Blob]":
|
|
766
|
+
case "[object File]":
|
|
767
|
+
case "[object FormData]":
|
|
768
|
+
return true;
|
|
769
|
+
default:
|
|
770
|
+
return false;
|
|
771
|
+
}
|
|
772
|
+
};
|
|
773
|
+
const translateObjectPreservingProto = async (value) => {
|
|
774
|
+
const proto = Object.getPrototypeOf(value);
|
|
775
|
+
const out = Object.create(proto);
|
|
776
|
+
const keys = Reflect.ownKeys(value);
|
|
777
|
+
await Promise.all(
|
|
778
|
+
keys.map(async (key) => {
|
|
779
|
+
const desc = Object.getOwnPropertyDescriptor(value, key);
|
|
780
|
+
if (!desc) return;
|
|
781
|
+
if ("value" in desc) {
|
|
782
|
+
const newVal = await visit(desc.value);
|
|
783
|
+
Object.defineProperty(out, key, { ...desc, value: newVal });
|
|
784
|
+
return;
|
|
785
|
+
}
|
|
786
|
+
Object.defineProperty(out, key, desc);
|
|
787
|
+
let current = void 0;
|
|
788
|
+
if (typeof desc.get === "function") {
|
|
789
|
+
try {
|
|
790
|
+
current = desc.get.call(value);
|
|
791
|
+
} catch {
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
if (current === void 0) return;
|
|
795
|
+
try {
|
|
796
|
+
const newVal = await visit(current);
|
|
797
|
+
if (typeof desc.set === "function") {
|
|
798
|
+
try {
|
|
799
|
+
desc.set.call(out, newVal);
|
|
800
|
+
} catch {
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
} catch {
|
|
804
|
+
}
|
|
805
|
+
})
|
|
806
|
+
);
|
|
807
|
+
return out;
|
|
808
|
+
};
|
|
809
|
+
const isTranslatable = (v) => {
|
|
810
|
+
if (!v) return { ok: false };
|
|
811
|
+
const t = typeof v;
|
|
812
|
+
if (t === "number" || t === "bigint" || t === "symbol" || t === "function") {
|
|
813
|
+
return { ok: false };
|
|
814
|
+
}
|
|
815
|
+
if (t === "string") return { ok: true, kind: "string" };
|
|
816
|
+
if (t === "object") {
|
|
817
|
+
return { ok: true, kind: "object" };
|
|
818
|
+
}
|
|
819
|
+
return { ok: false };
|
|
820
|
+
};
|
|
821
|
+
const visit = async (value) => {
|
|
822
|
+
const check = isTranslatable(value);
|
|
823
|
+
if (!check.ok) {
|
|
824
|
+
return value;
|
|
825
|
+
}
|
|
826
|
+
if (check.kind === "string") {
|
|
827
|
+
return this.translateString(locale, value, ctx);
|
|
828
|
+
}
|
|
829
|
+
if (value instanceof Promise) {
|
|
830
|
+
return value.then((resolved) => visit(resolved));
|
|
831
|
+
}
|
|
832
|
+
if (typeof value === "object") {
|
|
833
|
+
if (!Array.isArray(value) && isBuiltInObject(value)) return value;
|
|
834
|
+
if (visited.has(value)) return value;
|
|
835
|
+
visited.add(value);
|
|
836
|
+
if (Array.isArray(value)) {
|
|
837
|
+
const out = await Promise.all(value.map((v) => visit(v)));
|
|
838
|
+
return out;
|
|
839
|
+
}
|
|
840
|
+
return translateObjectPreservingProto(value);
|
|
841
|
+
}
|
|
842
|
+
return value;
|
|
843
|
+
};
|
|
844
|
+
return visit(obj);
|
|
845
|
+
}
|
|
846
|
+
async translateRequest(ctx, obj) {
|
|
847
|
+
const locale = await this.resolver(ctx, this.moduleRef);
|
|
848
|
+
return this.translate(locale, obj, ctx);
|
|
849
|
+
}
|
|
850
|
+
};
|
|
851
|
+
I18nService = __decorateClass([
|
|
852
|
+
(0, import_common9.Injectable)(),
|
|
853
|
+
__decorateParam(0, (0, import_common9.Inject)(I18nModuleOptionsToken)),
|
|
854
|
+
__decorateParam(1, (0, import_common9.Inject)(import_core4.ModuleRef))
|
|
855
|
+
], I18nService);
|
|
856
|
+
|
|
857
|
+
// src/i18n-module/i18n.module.ts
|
|
858
|
+
var import_common11 = require("@nestjs/common");
|
|
859
|
+
|
|
860
|
+
// src/i18n-module/locale.pipe.ts
|
|
861
|
+
var import_common10 = require("@nestjs/common");
|
|
862
|
+
var LocalePipe = class {
|
|
863
|
+
constructor(i18nService) {
|
|
864
|
+
this.i18nService = i18nService;
|
|
865
|
+
}
|
|
866
|
+
async transform(ctx, metadata) {
|
|
867
|
+
const resolver = ctx.resolver;
|
|
868
|
+
if (resolver) {
|
|
869
|
+
const _resolver = createResolver(resolver);
|
|
870
|
+
const locale = await _resolver(ctx.ctx, void 0);
|
|
871
|
+
return this.i18nService.getExactLocale(locale);
|
|
872
|
+
} else {
|
|
873
|
+
return this.i18nService.getExactLocaleFromRequest(ctx.ctx);
|
|
874
|
+
}
|
|
875
|
+
}
|
|
876
|
+
};
|
|
877
|
+
LocalePipe = __decorateClass([
|
|
878
|
+
(0, import_common10.Injectable)(),
|
|
879
|
+
__decorateParam(0, (0, import_common10.Inject)(I18nService))
|
|
880
|
+
], LocalePipe);
|
|
881
|
+
var _dec = (0, import_common10.createParamDecorator)((resolver, ctx) => {
|
|
882
|
+
return { ctx, resolver };
|
|
883
|
+
});
|
|
884
|
+
var PutLocale = (resolver) => _dec(resolver, LocalePipe);
|
|
885
|
+
|
|
886
|
+
// src/i18n-module/i18n.module.ts
|
|
887
|
+
var I18nModule = class extends ConfigurableModuleClass {
|
|
888
|
+
};
|
|
889
|
+
I18nModule = __decorateClass([
|
|
890
|
+
(0, import_common11.Global)(),
|
|
891
|
+
(0, import_common11.Module)({
|
|
892
|
+
providers: [I18nService, LocalePipe],
|
|
893
|
+
exports: [I18nService, LocalePipe]
|
|
894
|
+
})
|
|
895
|
+
], I18nModule);
|
|
896
|
+
|
|
897
|
+
// src/i18n-module/i18n-decorator.ts
|
|
898
|
+
var import_common13 = require("@nestjs/common");
|
|
899
|
+
|
|
900
|
+
// src/i18n-module/i18n.interceptor.ts
|
|
901
|
+
var import_common12 = require("@nestjs/common");
|
|
902
|
+
var import_rxjs2 = require("rxjs");
|
|
903
|
+
var import_operators = require("rxjs/operators");
|
|
904
|
+
var I18nInterceptor = class {
|
|
905
|
+
constructor(i18nService) {
|
|
906
|
+
this.i18nService = i18nService;
|
|
907
|
+
}
|
|
908
|
+
intercept(context, next) {
|
|
909
|
+
return next.handle().pipe(
|
|
910
|
+
// 成功路径:把响应体交给 i18n 做异步翻译
|
|
911
|
+
(0, import_operators.mergeMap)((data) => this.i18nService.translateRequest(context, data)),
|
|
912
|
+
// 错误路径:若是 HttpException,把其 response 翻译后再抛
|
|
913
|
+
(0, import_operators.catchError)((err) => {
|
|
914
|
+
if (err instanceof import_common12.HttpException) {
|
|
915
|
+
const status = err.getStatus();
|
|
916
|
+
const resp = err.getResponse();
|
|
917
|
+
return (0, import_rxjs2.from)(this.i18nService.translateRequest(context, resp)).pipe(
|
|
918
|
+
(0, import_operators.mergeMap)(
|
|
919
|
+
(translated) => (0, import_rxjs2.throwError)(
|
|
920
|
+
() => new import_common12.HttpException(translated, status, { cause: err })
|
|
921
|
+
)
|
|
922
|
+
)
|
|
923
|
+
);
|
|
924
|
+
}
|
|
925
|
+
return (0, import_rxjs2.throwError)(() => err);
|
|
926
|
+
})
|
|
927
|
+
);
|
|
928
|
+
}
|
|
929
|
+
};
|
|
930
|
+
I18nInterceptor = __decorateClass([
|
|
931
|
+
(0, import_common12.Injectable)(),
|
|
932
|
+
__decorateParam(0, (0, import_common12.Inject)(I18nService))
|
|
933
|
+
], I18nInterceptor);
|
|
934
|
+
|
|
935
|
+
// src/i18n-module/i18n-decorator.ts
|
|
936
|
+
var createI18nDecorator = (options) => {
|
|
937
|
+
return () => MergeClassOrMethodDecorators([
|
|
938
|
+
(0, import_common13.UseInterceptors)(I18nInterceptor),
|
|
939
|
+
ApiFromResolver(options.resolver, {
|
|
940
|
+
description: "Locale for internationalization",
|
|
941
|
+
required: false,
|
|
942
|
+
default: options.defaultLocale ?? options.locales[0],
|
|
943
|
+
enum: options.locales
|
|
944
|
+
})
|
|
945
|
+
]);
|
|
946
|
+
};
|
|
947
|
+
|
|
948
|
+
// src/i18n-module/i18n-factory.ts
|
|
949
|
+
var createI18n = (options) => {
|
|
950
|
+
if (!options.resolver) {
|
|
951
|
+
options.resolver = {
|
|
952
|
+
paramType: "header",
|
|
953
|
+
paramName: "x-client-language"
|
|
954
|
+
};
|
|
955
|
+
}
|
|
956
|
+
return {
|
|
957
|
+
UseI18n: createI18nDecorator(options),
|
|
958
|
+
I18nModule: I18nModule.register(options)
|
|
959
|
+
};
|
|
960
|
+
};
|
|
961
|
+
|
|
962
|
+
// src/i18n-module/middlewares/lookup.ts
|
|
963
|
+
var I18nLookupMiddleware = (dict, options) => {
|
|
964
|
+
const matchType = options?.matchType ?? "exact";
|
|
965
|
+
const dictFactory = typeof dict === "function" ? dict : () => dict;
|
|
966
|
+
const pickBestByHierarchy = (input, locales) => {
|
|
967
|
+
if (!input) return void 0;
|
|
968
|
+
const entries = locales.map((l) => ({ orig: l, lower: l.toLowerCase() }));
|
|
969
|
+
const lower = input.toLowerCase();
|
|
970
|
+
const exact = entries.find((e) => e.lower === lower);
|
|
971
|
+
if (exact) return exact.orig;
|
|
972
|
+
const parts = lower.split("-");
|
|
973
|
+
while (parts.length > 1) {
|
|
974
|
+
parts.pop();
|
|
975
|
+
const candidate = parts.join("-");
|
|
976
|
+
const hit = entries.find((e) => e.lower === candidate);
|
|
977
|
+
if (hit) return hit.orig;
|
|
978
|
+
}
|
|
979
|
+
return void 0;
|
|
980
|
+
};
|
|
981
|
+
return async (locale, key, next, ctx) => {
|
|
982
|
+
const dictResolved = await dictFactory(locale, key, ctx);
|
|
983
|
+
let dictionary = dictResolved[locale];
|
|
984
|
+
if (!dictionary) {
|
|
985
|
+
if (matchType === "hierarchy") {
|
|
986
|
+
const best = pickBestByHierarchy(locale, Object.keys(dictResolved));
|
|
987
|
+
if (best) dictionary = dictResolved[best];
|
|
988
|
+
} else if (matchType === "startsWith") {
|
|
989
|
+
const keys = Object.keys(dictResolved).filter(
|
|
990
|
+
(k) => locale.startsWith(k)
|
|
991
|
+
);
|
|
992
|
+
if (keys.length) {
|
|
993
|
+
const best = keys.reduce((a, b) => b.length > a.length ? b : a);
|
|
994
|
+
dictionary = dictResolved[best];
|
|
995
|
+
}
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
if (dictionary && Object.prototype.hasOwnProperty.call(dictionary, key)) {
|
|
999
|
+
const val = dictionary[key];
|
|
1000
|
+
if (val != null) {
|
|
1001
|
+
return val;
|
|
1002
|
+
}
|
|
1003
|
+
}
|
|
1004
|
+
return next();
|
|
1005
|
+
};
|
|
1006
|
+
};
|
|
464
1007
|
// Annotate the CommonJS export names for ESM import in node:
|
|
465
1008
|
0 && (module.exports = {
|
|
466
1009
|
ABORT_SIGNAL,
|
|
@@ -469,6 +1012,7 @@ AbortableModule = __decorateClass([
|
|
|
469
1012
|
ApiBlankResponse,
|
|
470
1013
|
ApiError,
|
|
471
1014
|
ApiErrorTyped,
|
|
1015
|
+
ApiFromResolver,
|
|
472
1016
|
ApiTypeResponse,
|
|
473
1017
|
As,
|
|
474
1018
|
BlankPaginatedReturnMessageDto,
|
|
@@ -478,22 +1022,31 @@ AbortableModule = __decorateClass([
|
|
|
478
1022
|
DataQuery,
|
|
479
1023
|
GenericPaginatedReturnMessageDto,
|
|
480
1024
|
GenericReturnMessageDto,
|
|
1025
|
+
I18nInterceptor,
|
|
1026
|
+
I18nLookupMiddleware,
|
|
1027
|
+
I18nModule,
|
|
1028
|
+
I18nService,
|
|
481
1029
|
InjectAbortSignal,
|
|
482
1030
|
InjectAbortable,
|
|
483
1031
|
InsertField,
|
|
1032
|
+
LocalePipe,
|
|
484
1033
|
MergeClassDecorators,
|
|
485
1034
|
MergeClassOrMethodDecorators,
|
|
486
1035
|
MergeMethodDecorators,
|
|
487
1036
|
MergeParameterDecorators,
|
|
488
1037
|
MergePropertyDecorators,
|
|
489
1038
|
PaginatedReturnMessageDto,
|
|
1039
|
+
PutLocale,
|
|
490
1040
|
RequireToken,
|
|
491
1041
|
ReturnMessageDto,
|
|
492
1042
|
StringReturnMessageDto,
|
|
493
1043
|
TokenGuard,
|
|
494
1044
|
abortableToken,
|
|
495
1045
|
createAbortableProvider,
|
|
1046
|
+
createI18n,
|
|
1047
|
+
createI18nDecorator,
|
|
496
1048
|
createProvider,
|
|
1049
|
+
createResolver,
|
|
497
1050
|
fromAbortable,
|
|
498
1051
|
getClassFromClassOrArray,
|
|
499
1052
|
takeUntilAbort
|