/
codegen.ts
385 lines (346 loc) · 8.99 KB
/
codegen.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
import {
LocationStub,
baseCompile,
CompileError,
ResourceNode,
CompileOptions,
detectHtmlTag
} from '@intlify/message-compiler'
import {
SourceMapGenerator,
SourceMapConsumer,
MappedPosition,
MappingItem
} from 'source-map'
import { format, escapeHtml as sanitizeHtml, isBoolean } from '@intlify/shared'
import type { RawSourceMap } from 'source-map'
/**
* Compilation dev environments
*
* @public
*/
export type DevEnv = 'development' | 'production'
export interface Position {
line: number
column: number
offset?: number
}
export interface SourceLocationable {
start?: number
loc?: {
start: Position
end: Position
} | null
}
/**
* @internal
*/
export interface CodeGenOptions {
type?: 'plain' | 'sfc' | 'bare'
legacy?: boolean
bridge?: boolean
exportESM?: boolean
source?: string
sourceMap?: boolean
filename?: string
inSourceMap?: RawSourceMap
isGlobal?: boolean
locale?: string
env?: DevEnv
forceStringify?: boolean
useClassComponent?: boolean
allowDynamic?: boolean
strictMessage?: boolean
escapeHtml?: boolean
onWarn?: (msg: string) => void
onError?: (
msg: string,
extra?: {
source: string
path: string
code?: CompileError['code']
domain?: CompileError['domain']
location?: CompileError['location']
}
) => void
}
export interface CodeGenContext {
source?: string
code: string
indentLevel: number
filename: string
line: number
column: number
offset: number
env: DevEnv
forceStringify: boolean
map?: SourceMapGenerator
}
export interface CodeGenerator {
context(): CodeGenContext
push<Node extends SourceLocationable>(
code: string,
node?: Node,
name?: string
): void
indent(withNewLine?: boolean): void
deindent(withNewLine?: boolean): void
newline(): void
pushline<Node extends SourceLocationable>(
code: string,
node?: Node,
name?: string
): void
}
/**
* @internal
*/
export interface CodeGenResult<ASTNode, CodeGenError extends Error = Error> {
code: string
ast: ASTNode
errors?: CodeGenError[]
map?: RawSourceMap
}
export function createCodeGenerator(
options: CodeGenOptions = {
filename: 'bundle.json',
sourceMap: false,
env: 'development',
forceStringify: false
}
): CodeGenerator {
const { sourceMap, source, filename } = options
const _context = Object.assign(
{
code: '',
column: 1,
line: 1,
offset: 0,
map: undefined,
indentLevel: 0
},
options
) as CodeGenContext
const context = (): CodeGenContext => _context
function push<Node extends SourceLocationable>(
code: string,
node?: Node,
name?: string
): void {
_context.code += code
if (_context.map && node) {
if (node.loc && node.loc !== LocationStub) {
addMapping(node.loc.start, name)
}
advancePositionWithSource(_context as Position, code)
}
}
function _newline(n: number): void {
push('\n' + ` `.repeat(n))
}
function indent(withNewLine = true): void {
const level = ++_context.indentLevel
withNewLine && _newline(level)
}
function deindent(withNewLine = true): void {
const level = --_context.indentLevel
withNewLine && _newline(level)
}
function newline(): void {
_newline(_context.indentLevel)
}
function pushline<Node extends SourceLocationable>(
code: string,
node?: Node,
name?: string
): void {
push(code, node, name)
newline()
}
function addMapping(loc: Position, name?: string) {
_context.map!.addMapping({
name,
source: _context.filename,
original: {
line: loc.line,
column: loc.column - 1
},
generated: {
line: _context.line,
column: _context.column - 1
}
})
}
if (sourceMap && source) {
_context.map = new SourceMapGenerator()
_context.map.setSourceContent(filename!, source)
}
return {
context,
push,
indent,
deindent,
newline,
pushline
}
}
function advancePositionWithSource(
pos: Position,
source: string,
numberOfCharacters: number = source.length
): Position {
if (pos.offset == null) {
return pos
}
let linesCount = 0
let lastNewLinePos = -1
for (let i = 0; i < numberOfCharacters; i++) {
if (source.charCodeAt(i) === 10 /* newline char code */) {
linesCount++
lastNewLinePos = i
}
}
pos.offset += numberOfCharacters
pos.line += linesCount
pos.column =
lastNewLinePos === -1
? pos.column + numberOfCharacters
: numberOfCharacters - lastNewLinePos
return pos
}
const DETECT_MESSAGE = `Detected HTML in '{msg}' message.`
const ON_ERROR_NOOP = () => {} // eslint-disable-line @typescript-eslint/no-empty-function
function parsePath(path?: string[]): string {
return path ? path.join('.') : ''
}
export function generateMessageFunction(
msg: string,
options: CodeGenOptions,
path?: string[]
): CodeGenResult<ResourceNode> {
const env = options.env != null ? options.env : 'development'
const strictMessage = isBoolean(options.strictMessage)
? options.strictMessage
: true
const escapeHtml = !!options.escapeHtml
const onError = options.onError || ON_ERROR_NOOP
const errors = [] as CompileError[]
let detecteHtmlInMsg = false
if (detectHtmlTag(msg)) {
detecteHtmlInMsg = true
if (strictMessage) {
const errMsg = format(DETECT_MESSAGE, { msg })
onError(format(errMsg), {
source: msg,
path: parsePath(path)
})
}
}
const _msg = detecteHtmlInMsg && escapeHtml ? sanitizeHtml(msg) : msg
const newOptions = Object.assign({ mode: 'arrow' }, options) as CompileOptions
newOptions.onError = (err: CompileError): void => {
if (onError) {
const extra: Parameters<Required<CodeGenOptions>['onError']>[1] = {
source: msg,
path: parsePath(path),
code: err.code,
domain: err.domain,
location: err.location
}
onError(err.message, extra)
errors.push(err)
}
}
const { code, ast, map } = baseCompile(_msg, newOptions)
const occured = errors.length > 0
const genCode = !occured
? env === 'development'
? `(()=>{const fn=${code};fn.source=${JSON.stringify(msg)};return fn;})()`
: `${code}`
: _msg
return { code: genCode, ast, map, errors }
}
export function mapLinesColumns(
resMap: RawSourceMap,
codeMaps: Map<string, RawSourceMap>,
inSourceMap?: RawSourceMap
): RawSourceMap | null {
if (!resMap) {
return null
}
const resMapConsumer = new SourceMapConsumer(resMap)
const inMapConsumer = inSourceMap ? new SourceMapConsumer(inSourceMap) : null
const mergedMapGenerator = new SourceMapGenerator()
let inMapFirstItem: MappingItem | null = null
if (inMapConsumer) {
inMapConsumer.eachMapping(m => {
if (inMapFirstItem) {
return
}
inMapFirstItem = m
})
}
resMapConsumer.eachMapping(res => {
if (res.originalLine == null) {
return
}
const map = codeMaps.get(res.name)
if (!map) {
return
}
let inMapOrigin: MappedPosition | null = null
if (inMapConsumer) {
inMapOrigin = inMapConsumer.originalPositionFor({
line: res.originalLine,
column: res.originalColumn - 1
})
if (inMapOrigin.source == null) {
inMapOrigin = null
return
}
}
const mapConsumer = new SourceMapConsumer(map)
mapConsumer.eachMapping(m => {
mergedMapGenerator.addMapping({
original: {
line: inMapFirstItem
? inMapFirstItem.originalLine + res.originalLine - 2
: res.originalLine,
column: inMapFirstItem
? inMapFirstItem.originalColumn + res.originalColumn
: res.originalColumn
},
generated: {
line: inMapFirstItem
? inMapFirstItem.generatedLine + res.originalLine - 2
: res.originalLine,
// map column with message format compilation code map
column: inMapFirstItem
? inMapFirstItem.generatedColumn +
res.originalColumn +
m.generatedColumn
: res.originalColumn + m.generatedColumn
},
source: inMapOrigin ? inMapOrigin.source : res.source,
name: m.name // message format compilation code
})
})
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const generator = mergedMapGenerator as any
// const targetConsumer = inMapConsumer || resMapConsumer
const targetConsumer = inMapConsumer || resMapConsumer
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(targetConsumer as any).sources.forEach((sourceFile: string) => {
generator._sources.add(sourceFile)
const sourceContent = targetConsumer.sourceContentFor(sourceFile)
if (sourceContent != null) {
mergedMapGenerator.setSourceContent(sourceFile, sourceContent)
}
})
generator._sourceRoot = inSourceMap
? inSourceMap.sourceRoot
: resMap.sourceRoot
generator._file = inSourceMap ? inSourceMap.file : resMap.file
return generator.toJSON()
}