anote-server-libs 0.11.6 → 0.11.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/services/utils.ts CHANGED
@@ -1,288 +1,287 @@
1
- import * as fs from 'fs';
2
- import {NextFunction, Request, Response} from 'express';
3
- import {Logger} from 'winston';
4
- import {BaseModelRepository} from '../models/repository/BaseModelRepository';
5
-
6
- export function atob(str: string): string {
7
- return Buffer.from(str, 'base64').toString('binary');
8
- }
9
-
10
- export function btoa(str: string): string {
11
- return Buffer.from(str).toString('base64');
12
- }
13
-
14
- export function clientErrorHandle(this: Logger, err: any, dbClient: any) {
15
- this.error('SQL [Client %d] ERROR: %j', dbClient.processID, err);
16
- }
17
- export const utils: {[id: string]: any} = {
18
- clientErrorHandler: undefined
19
- };
20
-
21
- function gcdTwo(a: number, b: number): number {
22
- if(a === 0)
23
- return b;
24
- return gcdTwo(b % a, a);
25
- }
26
-
27
- export function gcd(values: number[]): number {
28
- let result = values[0];
29
- for(let i = 1; i < values.length; i++)
30
- result = gcdTwo(values[i], result);
31
- return result;
32
- }
33
-
34
- export function lcm(values: number[]): number {
35
- let l = 1, divisor = 2;
36
- while(true) {
37
- let counter = 0;
38
- let divisible = false;
39
- for(let i = 0; i < values.length; i++) {
40
- if(values[i] === 0) {
41
- return 0;
42
- } else if(values[i] < 0) {
43
- values[i] = values[i] * (-1);
44
- }
45
- if(values[i] === 1) {
46
- counter++;
47
- }
48
- if(values[i] % divisor === 0) {
49
- divisible = true;
50
- values[i] = values[i] / divisor;
51
- }
52
- }
53
- if(divisible) {
54
- l = l * divisor;
55
- } else {
56
- divisor++;
57
- }
58
- if(counter === values.length) {
59
- return l;
60
- }
61
- }
62
- }
63
-
64
- export function jsonStringify(obj: any): string {
65
- const cache: any = {};
66
- return JSON.stringify(obj, function(_, value) {
67
- if(typeof value === 'object' && value !== null) {
68
- if(cache[value] !== -1) {
69
- try {
70
- return JSON.parse(JSON.stringify(value));
71
- } catch(error) {
72
- return;
73
- }
74
- }
75
- cache[value] = true;
76
- }
77
- return value;
78
- });
79
- }
80
-
81
- export function idempotent(repo: BaseModelRepository, debug: boolean, logger: Logger) {
82
- return function(req: Request, res: Response, next: NextFunction) {
83
- let idempotenceKey = req.header('x-idempotent-key');
84
- if(idempotenceKey) {
85
- idempotenceKey = idempotenceKey.substring(0, 40);
86
- repo.ApiCall.get(idempotenceKey).then(call => {
87
- if(!call) {
88
- const jsonTerminator = res.json;
89
- const endTerminator = res.end;
90
- const writeTerminator = res.write;
91
- let response = '';
92
- res.json = (function(obj: any) {
93
- repo.ApiCall.create({
94
- id: idempotenceKey,
95
- responseCode: res.statusCode,
96
- responseJson: jsonStringify(obj),
97
- expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000)
98
- }).then(() => jsonTerminator.call(res, obj), err => {
99
- if(err) logger.warn('Cannot save idempotent key: %j', err);
100
- jsonTerminator.call(res, obj);
101
- });
102
- }).bind(res);
103
- res.end = (function(buf: string) {
104
- if(buf) response = response + buf.toString();
105
- repo.ApiCall.create({
106
- id: idempotenceKey,
107
- responseCode: res.statusCode,
108
- responseJson: response,
109
- expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000)
110
- }).then(() => endTerminator.call(res, buf), err => {
111
- if(err) logger.warn('Cannot save idempotent key: %j', err);
112
- endTerminator.call(res, buf);
113
- });
114
- }).bind(res);
115
- res.write = (function(buf: string) {
116
- if(buf) response = response + buf.toString();
117
- writeTerminator.call(res, buf);
118
- }).bind(res);
119
- next();
120
- } else res.status(417).json({
121
- responseCode: call.responseCode,
122
- responseBody: call.responseJson
123
- });
124
- }, err => res.status(500).json({
125
- error: {
126
- errorKey: 'internal.db',
127
- additionalInfo: {message: err.message, stack: debug && err.stack}
128
- }
129
- }));
130
- } else next();
131
- };
132
- }
133
-
134
- export function sendSelfPostableMessage(res: Response, code: number, messageType: string, err?: any) {
135
- res.type('text/html').status(code).write(`
136
- <!DOCTYPE HTML>
137
- <html>
138
- <head>
139
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
140
- </head>
141
- <body>
142
- <script type="text/javascript">
143
- window.parent.postMessage({
144
- type: '${messageType}',
145
- confirm: ${!err},
146
- error: JSON.parse('${JSON.stringify(err) || 'null'}')
147
- }, '*');
148
- </script>
149
- </body>
150
- </html>
151
- `);
152
- res.end();
153
- }
154
-
155
- export function fpEuros(n: number) {
156
- return Math.round(n * 100) / 100;
157
- }
158
-
159
- export function digitize(value: number | string, opts?: {[key: string]: any}): string {
160
- if(value === undefined || value === null) return 'undefined';
161
- if(typeof value === 'number') {
162
- if(isNaN(value)) return '-';
163
- if(!isFinite(value)) return 'Infinite';
164
- value = String(value);
165
- } else if(typeof value === 'string') return value;
166
-
167
- const parts = value.split('.');
168
- const initialLength = parts[0].length;
169
- for(let i = initialLength - 3; i > 0; i -= 3) {
170
- parts[0] = parts[0].slice(0, i) + ',' + parts[0].slice(i);
171
- }
172
- if(parts[0].startsWith('-,'))
173
- parts[0] = '-' + parts[0].slice(2);
174
- if(parts[1]) {
175
- const expDecimals = parts[1].split(/[eE]-/);
176
- if (expDecimals.length > 1 && parseInt(expDecimals[1], 10) > 2) return '0.00';
177
- let decimals = fpEuros(parseFloat('0.' + parts[1])).toString().substr(2, 2);
178
- if (decimals.length === 1) decimals += '0';
179
- return parts[0] + '.' + decimals;
180
- }
181
- return (opts && opts.currency)? (parts[0] + '.00') : parts[0];
182
- }
183
-
184
- function loadEmailTemplates(path: string): Record<string, string> | undefined {
185
- if(!path || !fs.existsSync(path)) return undefined;
186
- const loadedEmailTemplates: {[id: string]: string} = {};
187
- const fileNames = fs.readdirSync(path);
188
- fileNames.forEach(fileName => {
189
- if(!fileName.startsWith('template-') || !fileName.endsWith('.html')) return;
190
- const templateIdentifier = fileName.slice('template-'.length, -'.html'.length);
191
- loadedEmailTemplates[templateIdentifier] = fs.readFileSync(path + '/' + fileName).toString('utf8');
192
- });
193
- return loadedEmailTemplates;
194
- }
195
-
196
- export function readEmailTemplates(path: string, config: Record<string, any>): {[id: string]: string} | undefined {
197
- const {product, name} = config.app;
198
- if(!product || !name) return loadEmailTemplates(path);
199
- const mainPath = path + '/' + product;
200
- const overridePath = product !== name ? path + `/${product}/${name}` : undefined;
201
- const defaultTemplates = loadEmailTemplates(mainPath);
202
- const overrideTemplates = overridePath ? loadEmailTemplates(overridePath) : {};
203
- return {...defaultTemplates, ...overrideTemplates};
204
- }
205
-
206
- export function replacePlaceholders(data: Record<string, any>, keys: string[], depth: number): any {
207
- if(!keys || depth >= keys.length) return undefined;
208
- if(depth === keys.length - 1) return (data || {})[keys[depth]];
209
- return replacePlaceholders((data || {})[keys[depth]], keys, depth + 1);
210
- }
211
-
212
- function getHtml(template: string, translationKeyValue: Record<string, any>): string | undefined {
213
- if(!template) return undefined;
214
- const pattern = new RegExp('{{\\s*([^{}]+?)\\s*}}', 'g');
215
- const replacer = (_: string, key: string) => replacePlaceholders(translationKeyValue, key.split('.'), 0) ?? key;
216
- template = template.replace(pattern, replacer);
217
- template = template.replace(pattern, replacer);
218
- template = template.replace(new RegExp('\\[\\[\\s*([a-zA-Z._0-9:]+)\\s*\\]\\]', 'g'), (_, key) => {
219
- const keyParts = key.split(':');
220
- return (replacePlaceholders(translationKeyValue, keyParts[1].split('.'), 0) || [])
221
- .map((subContext: any) => getHtml(keyParts[0], subContext)).join('');
222
- });
223
- template = template.replace(new RegExp('<<\\s*([a-zA-Z._0-9:]+)\\s*>>', 'g'), (_, key) => {
224
- const keyParts = key.split(':');
225
- if(replacePlaceholders(translationKeyValue, keyParts[1].split('.'), 0))
226
- return getHtml(keyParts[0], translationKeyValue);
227
- return '';
228
- });
229
- return template;
230
- }
231
-
232
- export function getHtmlReplaced(config: {frontend: string, app: {product: string, name: string, emailConfig: Record<string, string>}},
233
- templates: Record<string, string>,
234
- key: string, lang: number,
235
- defaultTemplateTranslations: Record<number, Record<string | number, string>> = {},
236
- projectSpecificTranslations: Record<string, Record<string | number, Record<string | number, string>>> = {},
237
- envSpecificTranslations?: Record<string, Record<string | number, Record<string | number, string>>>,
238
- extraData?: Record<string, any>,
239
- newPage?: boolean): string {
240
- const asTranslationMap = (value: unknown): Record<string | number, string> =>
241
- value && typeof value === 'object' ? value as Record<string | number, string> : {};
242
- const defaultTranslations = defaultTemplateTranslations?.[lang] || defaultTemplateTranslations?.[0] || {};
243
- const projectSpecificTrans = {
244
- ...asTranslationMap(projectSpecificTranslations?.[config.app.product]?.[lang] || projectSpecificTranslations?.[config.app.name]?.[0]),
245
- ...asTranslationMap(projectSpecificTranslations?.[config.app.product]?.[key]?.[lang] || projectSpecificTranslations?.[config.app.name]?.[key]?.[0])
246
- };
247
- const envSpecificTrans = {
248
- ...asTranslationMap(envSpecificTranslations?.[config.app.name]?.[lang] || envSpecificTranslations?.[config.app.name]?.[0]),
249
- ...asTranslationMap(envSpecificTranslations?.[config.app.name]?.[key]?.[lang] || envSpecificTranslations?.[config.app.name]?.[key]?.[0])
250
- };
251
- // Add {{}} around all extraData values so that they will be auto translated in the template if needed
252
- extraData = Object.fromEntries(Object.entries(extraData || {}).map(([k, v]) => [k, `{{${v}}}`]));
253
- const translationKeyValue = {
254
- ...defaultTranslations,
255
- ...projectSpecificTrans,
256
- ...envSpecificTrans,
257
- ...extraData,
258
- domain: config.frontend,
259
- ...config.app.emailConfig
260
- };
261
- let html = getHtml(templates[key], translationKeyValue);
262
- if(newPage) {
263
- html = html.replace('</head>', `<style>
264
- @media print {
265
- .new-page {
266
- page-break-before: always;
267
- }
268
- }
269
- </style>
270
- </head>`);
271
- html = html.replace('</body>', `<p class="new-page">Provided by Satoris</p>
272
- </body>`);
273
- }
274
- return html;
275
- }
276
-
277
- export function getEmailTitle(config: {frontend: string, app: {product: string, name: string, emailConfig: Record<string, any>}},
278
- key: string, lang: number,
279
- defaultTitles: Record<number, Record<string | number, string>> = {},
280
- projectSpecificTitles: Record<string, Record<number, Record<string | number, string>>> = {},
281
- envSpecificTitles: Record<string, Record<number, Record<string | number, string>>> = {},
282
- extraData: Record<string, string> = {}): string | undefined {
283
- const pattern = new RegExp('{{\\s*([a-zA-Z._0-9]+)\\s*}}', 'g');
284
- const title = envSpecificTitles?.[config.app.name]?.[lang]?.[key]
285
- || projectSpecificTitles?.[config.app.product]?.[lang]?.[key]
286
- || defaultTitles?.[lang]?.[key];
287
- return title?.replace(pattern, (_: string, placeholderKey: string) => extraData?.[placeholderKey] || config.app.emailConfig?.[placeholderKey] || placeholderKey);
288
- }
1
+ import * as fs from 'fs';
2
+ import {NextFunction, Request, Response} from 'express';
3
+ import {Logger} from 'winston';
4
+ import {BaseModelRepository} from '../models/repository/BaseModelRepository';
5
+
6
+ interface MinimalConfiguration {frontend: string, app: {product: string, name?: string, emailConfig: Record<string, string>}}
7
+
8
+ export function atob(str: string): string {
9
+ return Buffer.from(str, 'base64').toString('binary');
10
+ }
11
+
12
+ export function btoa(str: string): string {
13
+ return Buffer.from(str).toString('base64');
14
+ }
15
+
16
+ export function clientErrorHandle(this: Logger, err: any, dbClient: any) {
17
+ this.error('SQL [Client %d] ERROR: %j', dbClient.processID, err);
18
+ }
19
+ export const utils: {[id: string]: any} = {
20
+ clientErrorHandler: undefined
21
+ };
22
+
23
+ function gcdTwo(a: number, b: number): number {
24
+ if(a === 0)
25
+ return b;
26
+ return gcdTwo(b % a, a);
27
+ }
28
+
29
+ export function gcd(values: number[]): number {
30
+ let result = values[0];
31
+ for(let i = 1; i < values.length; i++)
32
+ result = gcdTwo(values[i], result);
33
+ return result;
34
+ }
35
+
36
+ export function lcm(values: number[]): number {
37
+ let l = 1, divisor = 2;
38
+ while(true) {
39
+ let counter = 0;
40
+ let divisible = false;
41
+ for(let i = 0; i < values.length; i++) {
42
+ if(values[i] === 0) {
43
+ return 0;
44
+ } else if(values[i] < 0) {
45
+ values[i] = values[i] * (-1);
46
+ }
47
+ if(values[i] === 1) {
48
+ counter++;
49
+ }
50
+ if(values[i] % divisor === 0) {
51
+ divisible = true;
52
+ values[i] = values[i] / divisor;
53
+ }
54
+ }
55
+ if(divisible) {
56
+ l = l * divisor;
57
+ } else {
58
+ divisor++;
59
+ }
60
+ if(counter === values.length) {
61
+ return l;
62
+ }
63
+ }
64
+ }
65
+
66
+ export function jsonStringify(obj: any): string {
67
+ const cache: any = {};
68
+ return JSON.stringify(obj, function(_, value) {
69
+ if(typeof value === 'object' && value !== null) {
70
+ if(cache[value] !== -1) {
71
+ try {
72
+ return JSON.parse(JSON.stringify(value));
73
+ } catch(error) {
74
+ return;
75
+ }
76
+ }
77
+ cache[value] = true;
78
+ }
79
+ return value;
80
+ });
81
+ }
82
+
83
+ export function idempotent(repo: BaseModelRepository, debug: boolean, logger: Logger) {
84
+ return function(req: Request, res: Response, next: NextFunction) {
85
+ let idempotenceKey = req.header('x-idempotent-key');
86
+ if(idempotenceKey) {
87
+ idempotenceKey = idempotenceKey.substring(0, 40);
88
+ repo.ApiCall.get(idempotenceKey).then(call => {
89
+ if(!call) {
90
+ const jsonTerminator = res.json;
91
+ const endTerminator = res.end;
92
+ const writeTerminator = res.write;
93
+ let response = '';
94
+ res.json = (function(obj: any) {
95
+ repo.ApiCall.create({
96
+ id: idempotenceKey,
97
+ responseCode: res.statusCode,
98
+ responseJson: jsonStringify(obj),
99
+ expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000)
100
+ }).then(() => jsonTerminator.call(res, obj), err => {
101
+ if(err) logger.warn('Cannot save idempotent key: %j', err);
102
+ jsonTerminator.call(res, obj);
103
+ });
104
+ }).bind(res);
105
+ res.end = (function(buf: string) {
106
+ if(buf) response = response + buf.toString();
107
+ repo.ApiCall.create({
108
+ id: idempotenceKey,
109
+ responseCode: res.statusCode,
110
+ responseJson: response,
111
+ expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000)
112
+ }).then(() => endTerminator.call(res, buf), err => {
113
+ if(err) logger.warn('Cannot save idempotent key: %j', err);
114
+ endTerminator.call(res, buf);
115
+ });
116
+ }).bind(res);
117
+ res.write = (function(buf: string) {
118
+ if(buf) response = response + buf.toString();
119
+ writeTerminator.call(res, buf);
120
+ }).bind(res);
121
+ next();
122
+ } else res.status(417).json({
123
+ responseCode: call.responseCode,
124
+ responseBody: call.responseJson
125
+ });
126
+ }, err => res.status(500).json({
127
+ error: {
128
+ errorKey: 'internal.db',
129
+ additionalInfo: {message: err.message, stack: debug && err.stack}
130
+ }
131
+ }));
132
+ } else next();
133
+ };
134
+ }
135
+
136
+ export function sendSelfPostableMessage(res: Response, code: number, messageType: string, err?: any) {
137
+ res.type('text/html').status(code).write(`
138
+ <!DOCTYPE HTML>
139
+ <html>
140
+ <head>
141
+ <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
142
+ </head>
143
+ <body>
144
+ <script type="text/javascript">
145
+ window.parent.postMessage({
146
+ type: '${messageType}',
147
+ confirm: ${!err},
148
+ error: JSON.parse('${JSON.stringify(err) || 'null'}')
149
+ }, '*');
150
+ </script>
151
+ </body>
152
+ </html>
153
+ `);
154
+ res.end();
155
+ }
156
+
157
+ export function fpEuros(n: number) {
158
+ return Math.round(n * 100) / 100;
159
+ }
160
+
161
+ export function digitize(value: number | string, opts?: {[key: string]: any}): string {
162
+ if(value === undefined || value === null) return 'undefined';
163
+ if(typeof value === 'number') {
164
+ if(isNaN(value)) return '-';
165
+ if(!isFinite(value)) return 'Infinite';
166
+ value = String(value);
167
+ } else if(typeof value === 'string') return value;
168
+
169
+ const parts = value.split('.');
170
+ const initialLength = parts[0].length;
171
+ for(let i = initialLength - 3; i > 0; i -= 3) {
172
+ parts[0] = parts[0].slice(0, i) + ',' + parts[0].slice(i);
173
+ }
174
+ if(parts[0].startsWith('-,'))
175
+ parts[0] = '-' + parts[0].slice(2);
176
+ if(parts[1]) {
177
+ const expDecimals = parts[1].split(/[eE]-/);
178
+ if (expDecimals.length > 1 && parseInt(expDecimals[1], 10) > 2) return '0.00';
179
+ let decimals = fpEuros(parseFloat('0.' + parts[1])).toString().substr(2, 2);
180
+ if (decimals.length === 1) decimals += '0';
181
+ return parts[0] + '.' + decimals;
182
+ }
183
+ return (opts && opts.currency)? (parts[0] + '.00') : parts[0];
184
+ }
185
+
186
+ function loadEmailTemplates(path: string): Record<string, string> | undefined {
187
+ if(!path || !fs.existsSync(path)) return undefined;
188
+ const loadedEmailTemplates: {[id: string]: string} = {};
189
+ const fileNames = fs.readdirSync(path);
190
+ fileNames.forEach(fileName => {
191
+ if(!fileName.startsWith('template-') || !fileName.endsWith('.html')) return;
192
+ const templateIdentifier = fileName.slice('template-'.length, -'.html'.length);
193
+ loadedEmailTemplates[templateIdentifier] = fs.readFileSync(path + '/' + fileName).toString('utf8');
194
+ });
195
+ return loadedEmailTemplates;
196
+ }
197
+
198
+ export function readEmailTemplates(path: string, config: MinimalConfiguration): {[id: string]: string} | undefined {
199
+ const {product, name} = config.app;
200
+ if(!product || !name) return loadEmailTemplates(path);
201
+ const mainPath = path + '/' + product;
202
+ const overridePath = product !== name ? path + `/${product}/${name}` : undefined;
203
+ const defaultTemplates = loadEmailTemplates(mainPath);
204
+ const overrideTemplates = overridePath ? loadEmailTemplates(overridePath) : {};
205
+ return {...defaultTemplates, ...overrideTemplates};
206
+ }
207
+
208
+ function replacePlaceholders(data: Record<string, any>, keys: string[], depth: number): any {
209
+ if(!keys || depth >= keys.length) return undefined;
210
+ if(depth === keys.length - 1) return (data || {})[keys[depth]];
211
+ return replacePlaceholders((data || {})[keys[depth]], keys, depth + 1);
212
+ }
213
+
214
+ function getHtml(template: string, translationKeyValue: Record<string, any>): string | undefined {
215
+ if(!template) return undefined;
216
+ const pattern = new RegExp('{{\\s*([^{}]+?)\\s*}}', 'g');
217
+ const replacer = (_: string, key: string) => replacePlaceholders(translationKeyValue, key.split('.'), 0) ?? key;
218
+ template = template.replace(pattern, replacer);
219
+ template = template.replace(pattern, replacer);
220
+ template = template.replace(new RegExp('\\[\\[\\s*([a-zA-Z._0-9:]+)\\s*\\]\\]', 'g'), (_, key) => {
221
+ const keyParts = key.split(':');
222
+ return (replacePlaceholders(translationKeyValue, keyParts[1].split('.'), 0) || [])
223
+ .map((subContext: any) => getHtml(keyParts[0], subContext)).join('');
224
+ });
225
+ template = template.replace(new RegExp('<<\\s*([a-zA-Z._0-9:]+)\\s*>>', 'g'), (_, key) => {
226
+ const keyParts = key.split(':');
227
+ if(replacePlaceholders(translationKeyValue, keyParts[1].split('.'), 0))
228
+ return getHtml(keyParts[0], translationKeyValue);
229
+ return '';
230
+ });
231
+ return template;
232
+ }
233
+
234
+ export function getHtmlReplaced(config: MinimalConfiguration, templates: Record<string, string>, key: string, lang: number,
235
+ translations: {
236
+ common: Record<number, Record<string, string>>,
237
+ byProduct: Record<string, Record<number, Record<string, string>>>,
238
+ byEnv: Record<string, Record<number, Record<string, string>>>
239
+ },
240
+ extraData?: Record<string, string>,
241
+ newPage?: boolean): string {
242
+ const {product, name} = config.app;
243
+ const merged = {
244
+ ...(translations.common[lang] ?? translations.common[0] ?? {}),
245
+ ...(translations.byProduct[product]?.[lang] ?? translations.byProduct[product]?.[0] ?? {}),
246
+ ...(name && name !== product ? (translations.byEnv[name]?.[lang] ?? translations.byEnv[name]?.[0] ?? {}) : {}),
247
+ };
248
+ const translationKeyValue = {
249
+ ...merged,
250
+ ...extraData,
251
+ domain: config.frontend,
252
+ ...config.app.emailConfig
253
+ };
254
+ let html = getHtml(templates[key], translationKeyValue);
255
+ if(newPage) {
256
+ html = html.replace('</head>', `<style>
257
+ @media print {
258
+ .new-page {
259
+ page-break-before: always;
260
+ }
261
+ }
262
+ </style>
263
+ </head>`);
264
+ html = html.replace('</body>', `<p class="new-page">Provided by Satoris</p>
265
+ </body>`);
266
+ }
267
+ return html;
268
+ }
269
+
270
+ export function getEmailOneSimpleValue(config: MinimalConfiguration, key: string, lang: number,
271
+ translations: {
272
+ common: Record<number, Record<string, string>>,
273
+ byProduct: Record<string, Record<number, Record<string, string>>>,
274
+ byEnv: Record<string, Record<number, Record<string, string>>>
275
+ },
276
+ extraData: Record<string, string> = {}): string | undefined {
277
+ const {product, name} = config.app;
278
+ const merged: Record<string, string> = {
279
+ ...(translations.common[lang] ?? translations.common[0] ?? {}),
280
+ ...(translations.byProduct[product]?.[lang] ?? translations.byProduct[product]?.[0] ?? {}),
281
+ ...(name && name !== product ? (translations.byEnv[name]?.[lang] ?? translations.byEnv[name]?.[0] ?? {}) : {}),
282
+ };
283
+ const pattern = new RegExp('{{\\s*([a-zA-Z._0-9]+)\\s*}}', 'g');
284
+ return merged[key]?.replace(pattern, (_: string, placeholderKey: string) =>
285
+ extraData[placeholderKey] ?? placeholderKey
286
+ );
287
+ }