-
-
Notifications
You must be signed in to change notification settings - Fork 398
/
Copy pathlangs.ts
180 lines (154 loc) · 4.44 KB
/
langs.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
import fs from 'fs-extra'
import { EmulatedRegExp } from 'oniguruma-to-es'
import { loadLangs } from '../../langs/scripts/langs'
import { precompileGrammar } from './precompile'
export async function prepareLangs() {
const resolvedLangs = await loadLangs()
const exportedFileNames: string[] = []
for (const json of resolvedLangs) {
const deps: string[] = json.embeddedLangs || []
const depsStr = [
...deps.map(i => `...${i.replace(/\W/g, '_')}`),
'lang',
].join(',\n') || ''
let precompiledStr: string | undefined
try {
const precompiled = precompileGrammar(json)
precompiledStr = toJsLiteral(precompiled)
}
catch (e) {
console.error(`Failed to precompile ${json.name}: ${e}`)
}
await fs.writeFile(
`./dist/${json.name}.mjs`,
precompiledStr == null
? `export default []
throw new Error("${json.name} is not supported due to the grammar limits")
`
: `
${precompiledStr.includes('new EmulatedRegExp') ? 'import { EmulatedRegExp } from \'oniguruma-to-es\'' : ''}
${deps.map(i => `import ${i.replace(/\W/g, '_')} from './${i}.mjs'`).join('\n')}
const lang = Object.freeze(${precompiledStr})
export default [\n${depsStr}\n]
`.replace(/\n{2,}/g, '\n\n').trimStart(),
'utf-8',
)
for (const alias of json.aliases || []) {
if (isInvalidFilename(alias))
continue
await fs.writeFile(
`./dist/${alias}.mjs`,
`/* Alias ${alias} for ${json.name} */
export { default } from './${json.name}.mjs'
`,
'utf-8',
)
}
for (const name of [...json.aliases || [], json.name]) {
if (isInvalidFilename(name))
continue
exportedFileNames.push(name)
await fs.writeFile(
`./dist/${name}.d.mts`,
`import type { LanguageRegistration } from '@shikijs/types'
const langs: LanguageRegistration []
export default langs
`,
'utf-8',
)
}
}
await fs.writeFile(
'./dist/index.mjs',
`// Generated by scripts/prepare.ts
export const languageNames = [
${resolvedLangs.map(i => JSON.stringify(i.name)).join(',\n')}
]
`,
'utf-8',
)
await fs.writeFile(
'./dist/index.d.mts',
`export const languageNames: string[]`,
'utf-8',
)
const packageJson = JSON.parse(await fs.readFile('./package.json', 'utf-8'))
packageJson.exports = {
'.': './dist/index.mjs',
...Object.fromEntries(
exportedFileNames.map(i => [
`./${i}`,
`./dist/${i}.mjs`,
]),
),
}
await fs.writeFile('./package.json', `${JSON.stringify(packageJson, null, 2)}\n`, 'utf-8')
}
function isInvalidFilename(filename: string) {
return !filename.match(/^[\w-]+$/)
}
export function toJsLiteral(value: any, seen = new Set()): string {
// null
if (value === null) {
return 'null'
}
// undefined
if (typeof value === 'undefined') {
return 'undefined'
}
// Boolean or number
if (typeof value === 'boolean' || typeof value === 'number') {
return String(value)
}
if (value instanceof EmulatedRegExp) {
return `new EmulatedRegExp(${JSON.stringify(value.source)},${JSON.stringify(value.flags)},${JSON.stringify(value.rawOptions)})`
}
// RegExp
if (value instanceof RegExp) {
// e.g., /pattern/gi
return value.toString()
}
// String
if (typeof value === 'string') {
// Use JSON.stringify for correct escaping
return JSON.stringify(value)
}
// Array
if (Array.isArray(value)) {
// Before recursing, check for cycles.
if (seen.has(value)) {
throw new Error('Circular reference detected in array')
}
seen.add(value)
const elements = value.map(item => toJsLiteral(item, seen))
const content = elements.join(',')
return `[${content}]`
}
// Object
if (typeof value === 'object') {
// Before recursing, check for cycles.
if (seen.has(value)) {
throw new Error('Circular reference detected in object')
}
seen.add(value)
const entries = []
for (const key of Object.keys(value)) {
entries.push(`${safeKey(key)}:${toJsLiteral(value[key], seen)}`)
}
return `{${entries.join(',')}}`
}
// Fallback
return JSON.stringify(value)
}
/**
* Safely wraps the key in quotes if it's not a valid JS identifier.
*/
function safeKey(key: string) {
// A simple check for valid identifier names
const validIdentifier = /^[a-z_$][\w$]*$/i
if (validIdentifier.test(key)) {
return key // leave as is
}
// otherwise, wrap in quotes
return JSON.stringify(key)
}