@webc.site/compile 0.0.0-stage → 0.1.0

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,30 @@
1
1
  {
2
2
  "name": "@webc.site/compile",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "AST compiler and .nt i18n bundler for webc components",
5
+ "license": "MulanPSL-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://atomgit.com/i18n-site/webc.git"
9
+ },
10
+ "publishConfig": {
11
+ "access": "public"
12
+ },
13
+ "type": "module",
14
+ "exports": {
15
+ ".": "./src/transform.js",
16
+ "./*": "./src/*"
17
+ },
18
+ "files": [
19
+ "src"
20
+ ],
21
+ "dependencies": {
22
+ "@1-/read": "^0.1.1",
23
+ "@i18n.site/nt": "^0.1.2",
24
+ "magic-string": "^1.4.5",
25
+ "oxc-parser": "^0.161.0"
26
+ },
27
+ "optionalDependencies": {
28
+ "@i18n.site/nt-js": "^0.1.0"
29
+ }
30
+ }
package/src/bfmt.js ADDED
@@ -0,0 +1,76 @@
1
+ import { ERR_NT_VAR, IDENT_RE } from './const.js'
2
+
3
+ const ARG_PREFIX = '_a',
4
+ // Parse `$[name]` placeholders and `\$` escapes matching bfmt syntax
5
+ parseSeg = (text) => {
6
+ const seg_li = []
7
+ let buf = '',
8
+ i = 0
9
+ while (i < text.length) {
10
+ const ch = text[i]
11
+ if (ch === '\\' && text[i + 1] === '$') {
12
+ buf += '$'
13
+ i += 2
14
+ continue
15
+ }
16
+ if (ch === '$' && text[i + 1] === '[') {
17
+ const end = text.indexOf(']', i + 2)
18
+ if (end !== -1) {
19
+ const name = text.slice(i + 2, end)
20
+ if (!IDENT_RE.test(name)) throw [ERR_NT_VAR, name]
21
+ if (buf) {
22
+ seg_li.push(buf)
23
+ buf = ''
24
+ }
25
+ seg_li.push({ name })
26
+ i = end + 1
27
+ continue
28
+ }
29
+ }
30
+ buf += ch
31
+ ++i
32
+ }
33
+ if (buf) seg_li.push(buf)
34
+ return seg_li
35
+ },
36
+ segJoin = (seg_li) => seg_li.join('')
37
+
38
+ export const tplScan = (text) => {
39
+ const raw_li = parseSeg(text),
40
+ var_li = [],
41
+ seg_li = raw_li.map((seg) => {
42
+ if (typeof seg === 'string') return seg
43
+ let idx = var_li.indexOf(seg.name)
44
+ if (idx === -1) {
45
+ idx = var_li.length
46
+ var_li.push(seg.name)
47
+ }
48
+ return idx
49
+ })
50
+ return { seg_li, var_li }
51
+ },
52
+ tplAlign = (text, fb_var_li) => {
53
+ const raw_li = parseSeg(text),
54
+ used_li = new Array(fb_var_li.length).fill(false),
55
+ seg_li = raw_li.map((seg) => {
56
+ if (typeof seg === 'string') return seg
57
+ const idx = fb_var_li.indexOf(seg.name)
58
+ if (idx === -1) throw [ERR_NT_VAR, seg.name]
59
+ used_li[idx] = true
60
+ return idx
61
+ }),
62
+ unused_li = fb_var_li.filter((_, idx) => !used_li[idx])
63
+ return { seg_li, unused_li }
64
+ },
65
+ tplJs = (seg_li, fb_var_li) => {
66
+ if (fb_var_li.length === 0) return JSON.stringify(segJoin(seg_li))
67
+ const arg_li = fb_var_li.map((_, idx) => ARG_PREFIX + idx)
68
+ if (seg_li.length === 0) return '(' + arg_li.join(',') + ")=>''"
69
+ const expr_li = seg_li.map((seg) =>
70
+ typeof seg === 'number' ? arg_li[seg] : JSON.stringify(seg)
71
+ )
72
+ if (typeof seg_li[0] === 'number') expr_li.unshift("''")
73
+ return '(' + arg_li.join(',') + ')=>' + expr_li.join('+')
74
+ },
75
+ tplLynx = (seg_li, fb_var_li) =>
76
+ fb_var_li.length === 0 ? segJoin(seg_li) : seg_li
package/src/const.js ADDED
@@ -0,0 +1,12 @@
1
+ export const ERR_NT_NESTED = 1,
2
+ ERR_NT_KEY = 2,
3
+ ERR_NT_VAR = 3,
4
+ ERR_MACRO_ARG = 4,
5
+ ERR_KEY_MISSING = 5,
6
+ ERR_NT_MULTI = 6,
7
+ ERR_NT_EMPTY = 7,
8
+ MODE_DEV = 'dev',
9
+ MODE_PROD = 'prod',
10
+ TARGET_WEB = 'web',
11
+ TARGET_LYNX = 'lynx',
12
+ IDENT_RE = /^[A-Za-z_$][A-Za-z0-9_$]*$/
package/src/deps.js ADDED
@@ -0,0 +1,59 @@
1
+ import { parseSync } from 'oxc-parser'
2
+ import { ERR_MACRO_ARG } from './const.js'
3
+
4
+ const pkgNameOf = (spec) => {
5
+ if (spec.startsWith('@')) {
6
+ const part_li = spec.split('/')
7
+ return part_li.length >= 2 ? part_li[0] + '/' + part_li[1] : spec
8
+ }
9
+ return spec.split('/')[0]
10
+ },
11
+ visit = (node, onSpec) => {
12
+ if (!node || typeof node !== 'object') return
13
+ if (Array.isArray(node)) {
14
+ for (let i = 0; i < node.length; ++i) visit(node[i], onSpec)
15
+ return
16
+ }
17
+ if (typeof node.type !== 'string') return
18
+ if (
19
+ node.type === 'ImportDeclaration' &&
20
+ typeof node.source?.value === 'string'
21
+ ) {
22
+ onSpec(node.source.value)
23
+ } else if (
24
+ node.type === 'ImportExpression' &&
25
+ node.source?.type === 'Literal' &&
26
+ typeof node.source.value === 'string'
27
+ ) {
28
+ onSpec(node.source.value)
29
+ }
30
+ for (const key of Object.keys(node)) {
31
+ if (key === 'type' || key === 'start' || key === 'end') continue
32
+ const val = node[key]
33
+ if (val && typeof val === 'object') visit(val, onSpec)
34
+ }
35
+ }
36
+
37
+ // Extract relative module specifiers and bare npm packages from a JS file
38
+ export const importScan = (code, file_path = 'input.js') => {
39
+ const { program, errors } = parseSync(file_path, code, {
40
+ sourceType: 'module'
41
+ })
42
+ if (errors.length > 0) throw [ERR_MACRO_ARG, file_path, errors[0].message]
43
+
44
+ const rel_set = new Set(),
45
+ pkg_set = new Set()
46
+
47
+ visit(program, (spec) => {
48
+ if (spec.startsWith('./') || spec.startsWith('../')) {
49
+ rel_set.add(spec)
50
+ } else if (!spec.startsWith('node:') && !spec.startsWith('bun:')) {
51
+ pkg_set.add(pkgNameOf(spec))
52
+ }
53
+ })
54
+
55
+ return {
56
+ rel_li: [...rel_set],
57
+ pkg_li: [...pkg_set]
58
+ }
59
+ }
package/src/nt.js ADDED
@@ -0,0 +1,270 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { existsSync, readdirSync, statSync } from 'node:fs'
3
+ import { createRequire } from 'node:module'
4
+ import { join, relative, resolve } from 'node:path'
5
+ import read from '@1-/read'
6
+ import ntLoad from '@i18n.site/nt/load.js'
7
+ import { tplAlign, tplJs, tplLynx, tplScan } from './bfmt.js'
8
+ import {
9
+ ERR_NT_EMPTY,
10
+ ERR_NT_KEY,
11
+ ERR_NT_MULTI,
12
+ ERR_NT_NESTED,
13
+ IDENT_RE,
14
+ MODE_DEV,
15
+ MODE_PROD,
16
+ TARGET_LYNX,
17
+ TARGET_WEB
18
+ } from './const.js'
19
+
20
+ const SKIP_DIR = new Set(['node_modules', '.git', 'dist', '.cache', 'target']),
21
+ COMP_FILE = '_.nt',
22
+ DEFAULT_FROM = 'zh',
23
+ DEFAULT_SUFFIX = '.js',
24
+ HASH_LEN = 12,
25
+ nativeNtLoad = () => {
26
+ const req = createRequire(import.meta.url),
27
+ target = process.env.WEBC_NT_NAPI || '@i18n.site/nt-js'
28
+ try {
29
+ const mod = req(target)
30
+ return typeof mod?.compileNt === 'function' ? mod.compileNt : null
31
+ } catch {
32
+ return null
33
+ }
34
+ },
35
+ posNorm = (path_str) => path_str.replaceAll('\\', '/') || '.',
36
+ hashOf = (text) =>
37
+ createHash('sha256').update(text).digest('base64url').slice(0, HASH_LEN),
38
+ isDir = (path_str) =>
39
+ existsSync(path_str) && statSync(path_str).isDirectory(),
40
+ compScan = (root_dir, include_demo = false) => {
41
+ const out_li = [],
42
+ walk = (dir) => {
43
+ const i18n_dir = join(dir, 'i18n')
44
+ if (isDir(i18n_dir)) out_li.push(dir)
45
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
46
+ if (!entry.isDirectory()) continue
47
+ const name = entry.name
48
+ if (name.startsWith('.') || SKIP_DIR.has(name)) continue
49
+ if (!include_demo && name === 'demo') continue
50
+ walk(join(dir, name))
51
+ }
52
+ }
53
+ if (isDir(root_dir)) walk(root_dir)
54
+ return out_li
55
+ },
56
+ // Read single-level key/value pairs from <lang_dir>/_.nt and reject nested dicts
57
+ langRead = async (lang_dir) => {
58
+ const file_li = readdirSync(lang_dir).filter((f) => f.endsWith('.nt'))
59
+ for (const file of file_li) {
60
+ if (file !== COMP_FILE) throw [ERR_NT_MULTI, lang_dir, file]
61
+ }
62
+ const nt_path = join(lang_dir, COMP_FILE)
63
+ if (!existsSync(nt_path)) return null
64
+ const raw = ntLoad(await read(nt_path))
65
+ if (raw === null) return {}
66
+ if (typeof raw !== 'object' || Array.isArray(raw)) {
67
+ throw [ERR_NT_NESTED, nt_path, 'root']
68
+ }
69
+ const entries = Object.entries(raw)
70
+ for (const [key, val] of entries) {
71
+ if (!IDENT_RE.test(key)) throw [ERR_NT_KEY, nt_path, key]
72
+ if (typeof val === 'string') continue
73
+ if (Array.isArray(val) && val.every((item) => typeof item === 'string')) {
74
+ continue
75
+ }
76
+ throw [ERR_NT_NESTED, nt_path, key]
77
+ }
78
+ return raw
79
+ },
80
+ compileEntry = (val, fb_meta, target) => {
81
+ if (Array.isArray(val)) {
82
+ const code_li = val.map((item) => {
83
+ const { seg_li } = tplAlign(item, fb_meta.var_li)
84
+ return target === TARGET_LYNX
85
+ ? tplLynx(seg_li, fb_meta.var_li)
86
+ : tplJs(seg_li, fb_meta.var_li)
87
+ })
88
+ return target === TARGET_LYNX ? code_li : '[' + code_li.join(',') + ']'
89
+ }
90
+ const { seg_li } = tplAlign(val, fb_meta.var_li)
91
+ return target === TARGET_LYNX
92
+ ? tplLynx(seg_li, fb_meta.var_li)
93
+ : tplJs(seg_li, fb_meta.var_li)
94
+ },
95
+ compileCompLang = (fb_li, lang_dict, lang, comp_key, target, diag_li) => {
96
+ const out_li = []
97
+ for (let i = 0; i < fb_li.length; ++i) {
98
+ const fb_meta = fb_li[i],
99
+ has_key = lang_dict && Object.hasOwn(lang_dict, fb_meta.key),
100
+ raw_val = has_key ? lang_dict[fb_meta.key] : fb_meta.raw_val
101
+ if (!has_key) {
102
+ diag_li.push(
103
+ lang +
104
+ ': ' +
105
+ comp_key +
106
+ '.' +
107
+ fb_meta.key +
108
+ ' missing, filled from fallback'
109
+ )
110
+ }
111
+ out_li.push(compileEntry(raw_val, fb_meta, target))
112
+ }
113
+ return target === TARGET_LYNX ? out_li : '[' + out_li.join(',') + ']'
114
+ },
115
+ // Parse fallback language entries into ordered slot metadata
116
+ fbBuild = (fb_dict) =>
117
+ Object.entries(fb_dict).map(([key, raw_val]) => {
118
+ if (Array.isArray(raw_val)) {
119
+ const var_li = []
120
+ for (const item of raw_val) {
121
+ const scanned = tplScan(item)
122
+ for (const v of scanned.var_li) {
123
+ if (!var_li.includes(v)) var_li.push(v)
124
+ }
125
+ }
126
+ return { key, raw_val, var_li }
127
+ }
128
+ const { var_li } = tplScan(raw_val)
129
+ return { key, raw_val, var_li }
130
+ })
131
+
132
+ export const compileNtJs = async ({
133
+ dir_li,
134
+ cwd = process.cwd(),
135
+ from_lang = DEFAULT_FROM,
136
+ target = TARGET_WEB,
137
+ mode = MODE_PROD,
138
+ suffix = DEFAULT_SUFFIX,
139
+ include_demo = false
140
+ }) => {
141
+ const base_dir = resolve(cwd),
142
+ comp_set = new Set()
143
+
144
+ for (const dir of dir_li) {
145
+ const abs_dir = resolve(base_dir, dir)
146
+ for (const comp_dir of compScan(
147
+ abs_dir,
148
+ include_demo || dir.endsWith('/demo')
149
+ )) {
150
+ comp_set.add(comp_dir)
151
+ }
152
+ }
153
+
154
+ const comp_dir_li = [...comp_set].sort((a, b) =>
155
+ posNorm(relative(base_dir, a)).localeCompare(
156
+ posNorm(relative(base_dir, b))
157
+ )
158
+ ),
159
+ manifest = {},
160
+ diag_li = [],
161
+ lang_set = new Set([from_lang]),
162
+ comp_meta_li = []
163
+
164
+ for (let i = 0; i < comp_dir_li.length; ++i) {
165
+ const comp_dir = comp_dir_li[i],
166
+ i18n_dir = join(comp_dir, 'i18n'),
167
+ from_dir = join(i18n_dir, from_lang)
168
+ if (!isDir(from_dir)) continue
169
+ const fb_dict = await langRead(from_dir)
170
+ if (!fb_dict) continue
171
+
172
+ const comp_key = posNorm(relative(base_dir, comp_dir)),
173
+ fb_li = fbBuild(fb_dict),
174
+ keys = {}
175
+ for (let k = 0; k < fb_li.length; ++k) keys[fb_li[k].key] = k
176
+
177
+ const lang_map = new Map()
178
+ for (const entry of readdirSync(i18n_dir, { withFileTypes: true })) {
179
+ if (!entry.isDirectory() || entry.name.startsWith('.')) continue
180
+ const dict = await langRead(join(i18n_dir, entry.name))
181
+ if (!dict) continue
182
+ lang_set.add(entry.name)
183
+ lang_map.set(entry.name, dict)
184
+ }
185
+
186
+ const comp_id = comp_meta_li.length
187
+ manifest[comp_key] = { id: comp_id, keys }
188
+ comp_meta_li.push({ comp_id, comp_key, fb_li, lang_map })
189
+ }
190
+
191
+ if (comp_meta_li.length === 0) throw [ERR_NT_EMPTY, dir_li]
192
+
193
+ const lang_li = [...lang_set].sort(),
194
+ asset_li = []
195
+
196
+ if (mode === MODE_DEV) {
197
+ for (const { comp_key, fb_li, lang_map } of comp_meta_li) {
198
+ for (const lang of lang_li) {
199
+ const dict = lang_map.get(lang),
200
+ compiled = compileCompLang(
201
+ fb_li,
202
+ dict,
203
+ lang,
204
+ comp_key,
205
+ target,
206
+ diag_li
207
+ ),
208
+ code =
209
+ target === TARGET_LYNX
210
+ ? JSON.stringify(compiled)
211
+ : 'export default ' + compiled
212
+ asset_li.push({
213
+ lang,
214
+ comp_key,
215
+ filename: comp_key + '/' + lang + '.js',
216
+ code
217
+ })
218
+ }
219
+ }
220
+ return { manifest, asset_li, diag_li }
221
+ }
222
+
223
+ for (const lang of lang_li) {
224
+ const bucket_li = comp_meta_li.map(({ comp_key, fb_li, lang_map }) =>
225
+ compileCompLang(
226
+ fb_li,
227
+ lang_map.get(lang),
228
+ lang,
229
+ comp_key,
230
+ target,
231
+ diag_li
232
+ )
233
+ ),
234
+ code =
235
+ target === TARGET_LYNX
236
+ ? JSON.stringify(bucket_li)
237
+ : 'export default [' + bucket_li.join(',') + ']',
238
+ filename = hashOf(code) + suffix
239
+ asset_li.push({ lang, filename, code })
240
+ }
241
+
242
+ return { manifest, asset_li, diag_li }
243
+ },
244
+ compileNt = async (opt) => {
245
+ if (!opt?.js_only) {
246
+ const nativeCompile = nativeNtLoad()
247
+ if (nativeCompile) {
248
+ const res = nativeCompile({
249
+ dirLi: opt.dir_li,
250
+ cwd: opt.cwd ?? process.cwd(),
251
+ fromLang: opt.from_lang ?? DEFAULT_FROM,
252
+ target: opt.target ?? TARGET_WEB,
253
+ mode: opt.mode ?? MODE_PROD,
254
+ suffix: opt.suffix ?? DEFAULT_SUFFIX,
255
+ includeDemo: Boolean(opt.include_demo)
256
+ })
257
+ return {
258
+ manifest: res.manifest,
259
+ asset_li: res.assetLi.map((a) => ({
260
+ lang: a.lang,
261
+ comp_key: a.compKey ?? undefined,
262
+ filename: a.filename,
263
+ code: a.code
264
+ })),
265
+ diag_li: res.diagLi
266
+ }
267
+ }
268
+ }
269
+ return compileNtJs(opt)
270
+ }
@@ -0,0 +1,272 @@
1
+ import MagicString from 'magic-string'
2
+ import { parseSync } from 'oxc-parser'
3
+ import { ERR_KEY_MISSING, ERR_MACRO_ARG } from './const.js'
4
+
5
+ const I18N_PKG = '@webc.site/i18n',
6
+ MACRO_NAME = '$i18n',
7
+ PROD_FN = 'i18nReg',
8
+ DEV_FN = 'i18nDev',
9
+ NON_REF_PARENT = new Set([
10
+ 'FunctionDeclaration',
11
+ 'FunctionExpression',
12
+ 'ArrowFunctionExpression',
13
+ 'VariableDeclarator',
14
+ 'CatchClause',
15
+ 'LabeledStatement',
16
+ 'BreakStatement',
17
+ 'ContinueStatement',
18
+ 'ImportSpecifier',
19
+ 'ImportDefaultSpecifier',
20
+ 'ImportNamespaceSpecifier',
21
+ 'ExportSpecifier'
22
+ ]),
23
+ collectPat = (pat, out_set) => {
24
+ if (!pat) return
25
+ if (pat.type === 'Identifier') {
26
+ out_set.add(pat.name)
27
+ return
28
+ }
29
+ if (pat.type === 'RestElement') {
30
+ collectPat(pat.argument, out_set)
31
+ return
32
+ }
33
+ if (pat.type === 'AssignmentPattern') {
34
+ collectPat(pat.left, out_set)
35
+ return
36
+ }
37
+ if (pat.type === 'ArrayPattern') {
38
+ for (let i = 0; i < pat.elements.length; ++i)
39
+ collectPat(pat.elements[i], out_set)
40
+ return
41
+ }
42
+ if (pat.type === 'ObjectPattern') {
43
+ for (let i = 0; i < pat.properties.length; ++i) {
44
+ const prop = pat.properties[i]
45
+ collectPat(
46
+ prop.type === 'RestElement' ? prop.argument : prop.value,
47
+ out_set
48
+ )
49
+ }
50
+ }
51
+ },
52
+ collectBlockDecls = (stmt_li, out_set) => {
53
+ for (let i = 0; i < stmt_li.length; ++i) {
54
+ const stmt = stmt_li[i]
55
+ if (!stmt) continue
56
+ if (stmt.type === 'VariableDeclaration') {
57
+ for (let j = 0; j < stmt.declarations.length; ++j) {
58
+ collectPat(stmt.declarations[j].id, out_set)
59
+ }
60
+ } else if (stmt.type === 'FunctionDeclaration' && stmt.id) {
61
+ out_set.add(stmt.id.name)
62
+ }
63
+ }
64
+ },
65
+ isRefIdent = (node, parent, prop_key) => {
66
+ if (!parent) return true
67
+ if (
68
+ parent.type === 'MemberExpression' &&
69
+ prop_key === 'property' &&
70
+ !parent.computed
71
+ ) {
72
+ return false
73
+ }
74
+ if (parent.type === 'Property') {
75
+ if (parent.shorthand) return true
76
+ if (prop_key === 'key' && !parent.computed) return false
77
+ }
78
+ if (
79
+ parent.type === 'MethodDefinition' &&
80
+ prop_key === 'key' &&
81
+ !parent.computed
82
+ ) {
83
+ return false
84
+ }
85
+ if (
86
+ NON_REF_PARENT.has(parent.type) &&
87
+ prop_key !== 'init' &&
88
+ prop_key !== 'body'
89
+ ) {
90
+ return false
91
+ }
92
+ return true
93
+ },
94
+ visitAst = (node, parent, prop_key, fn) => {
95
+ if (!node || typeof node !== 'object') return
96
+ if (Array.isArray(node)) {
97
+ for (let i = 0; i < node.length; ++i)
98
+ visitAst(node[i], parent, prop_key, fn)
99
+ return
100
+ }
101
+ if (typeof node.type !== 'string') return
102
+ if (fn(node, parent, prop_key) === false) return
103
+ for (const key of Object.keys(node)) {
104
+ if (key === 'type' || key === 'start' || key === 'end') continue
105
+ const val = node[key]
106
+ if (val && typeof val === 'object') visitAst(val, node, key, fn)
107
+ }
108
+ },
109
+ pickSafeName = (code, used_set) => {
110
+ let idx = 0
111
+ for (;;) {
112
+ const cand = idx === 0 ? '_l' : '_l' + idx
113
+ if (!used_set.has(cand) && !code.includes(cand)) return cand
114
+ ++idx
115
+ }
116
+ },
117
+ rewriteBody = (body_node, param_map, l_name, s) => {
118
+ const scope_li = [new Set()],
119
+ shadowed = (name) => {
120
+ for (let i = scope_li.length - 1; i >= 0; --i) {
121
+ if (scope_li[i].has(name)) return true
122
+ }
123
+ return false
124
+ },
125
+ walkBody = (node, parent, prop_key) => {
126
+ if (!node || typeof node !== 'object') return
127
+ if (Array.isArray(node)) {
128
+ for (let i = 0; i < node.length; ++i)
129
+ walkBody(node[i], parent, prop_key)
130
+ return
131
+ }
132
+ if (typeof node.type !== 'string') return
133
+
134
+ let pushed = false
135
+ if (node.type === 'BlockStatement' || node.type === 'Program') {
136
+ const set = new Set()
137
+ collectBlockDecls(node.body, set)
138
+ scope_li.push(set)
139
+ pushed = true
140
+ } else if (
141
+ node.type === 'ArrowFunctionExpression' ||
142
+ node.type === 'FunctionExpression' ||
143
+ node.type === 'FunctionDeclaration'
144
+ ) {
145
+ const set = new Set()
146
+ if (node.id) set.add(node.id.name)
147
+ for (let i = 0; i < node.params.length; ++i)
148
+ collectPat(node.params[i], set)
149
+ scope_li.push(set)
150
+ pushed = true
151
+ } else if (node.type === 'CatchClause' && node.param) {
152
+ const set = new Set()
153
+ collectPat(node.param, set)
154
+ scope_li.push(set)
155
+ pushed = true
156
+ }
157
+
158
+ if (node.type === 'Identifier' && isRefIdent(node, parent, prop_key)) {
159
+ const key_idx = param_map.get(node.name)
160
+ if (key_idx !== undefined && !shadowed(node.name)) {
161
+ const rep = l_name + '[' + key_idx + ']'
162
+ if (parent?.type === 'Property' && parent.shorthand) {
163
+ s.overwrite(node.start, node.end, node.name + ': ' + rep)
164
+ } else {
165
+ s.overwrite(node.start, node.end, rep)
166
+ }
167
+ }
168
+ }
169
+
170
+ for (const key of Object.keys(node)) {
171
+ if (key === 'type' || key === 'start' || key === 'end') continue
172
+ const val = node[key]
173
+ if (val && typeof val === 'object') walkBody(val, node, key)
174
+ }
175
+
176
+ if (pushed) scope_li.pop()
177
+ }
178
+
179
+ walkBody(body_node, null, '')
180
+ }
181
+
182
+ export const i18nTransform = (
183
+ code,
184
+ file_path,
185
+ comp_key,
186
+ key_map,
187
+ is_prod = false,
188
+ comp_id = 0
189
+ ) => {
190
+ if (!code.includes(MACRO_NAME)) return { code, map: null, changed: false }
191
+
192
+ const { program, errors } = parseSync(file_path, code, {
193
+ sourceType: 'module'
194
+ })
195
+ if (errors.length > 0) throw [ERR_MACRO_ARG, file_path, errors[0].message]
196
+
197
+ const s = new MagicString(code),
198
+ runtime_fn = is_prod ? PROD_FN : DEV_FN,
199
+ local_set = new Set(),
200
+ all_ident_set = new Set()
201
+
202
+ let changed = false
203
+
204
+ for (let i = 0; i < program.body.length; ++i) {
205
+ const stmt = program.body[i]
206
+ if (stmt.type !== 'ImportDeclaration' || stmt.source.value !== I18N_PKG)
207
+ continue
208
+ for (let j = 0; j < stmt.specifiers.length; ++j) {
209
+ const spec = stmt.specifiers[j]
210
+ if (
211
+ spec.type === 'ImportSpecifier' &&
212
+ spec.imported.name === MACRO_NAME
213
+ ) {
214
+ local_set.add(spec.local.name)
215
+ s.overwrite(spec.start, spec.end, runtime_fn)
216
+ changed = true
217
+ }
218
+ }
219
+ }
220
+
221
+ if (local_set.size === 0) return { code, map: null, changed: false }
222
+
223
+ visitAst(program, null, '', (node) => {
224
+ if (node.type === 'Identifier') all_ident_set.add(node.name)
225
+ })
226
+
227
+ const l_name = pickSafeName(code, all_ident_set),
228
+ comp_arg = is_prod ? String(comp_id) : JSON.stringify(comp_key)
229
+
230
+ visitAst(program, null, '', (node) => {
231
+ if (node.type !== 'CallExpression') return
232
+ if (node.callee.type !== 'Identifier' || !local_set.has(node.callee.name))
233
+ return
234
+
235
+ const cb = node.arguments[0]
236
+ if (!cb || cb.type !== 'ArrowFunctionExpression') {
237
+ throw [ERR_MACRO_ARG, file_path, 'callback must be an arrow function']
238
+ }
239
+
240
+ const param_map = new Map()
241
+ for (let i = 0; i < cb.params.length; ++i) {
242
+ const param = cb.params[i]
243
+ if (param.type !== 'Identifier') {
244
+ throw [ERR_MACRO_ARG, file_path, 'only plain identifier params allowed']
245
+ }
246
+ const key_idx = key_map[param.name]
247
+ if (key_idx === undefined) throw [ERR_KEY_MISSING, file_path, param.name]
248
+ param_map.set(param.name, key_idx)
249
+ }
250
+
251
+ s.overwrite(node.callee.start, node.callee.end, runtime_fn)
252
+ const search_from =
253
+ cb.params.length > 0 ? cb.params[cb.params.length - 1].end : cb.start,
254
+ arrow_pos = code.indexOf('=>', search_from),
255
+ prefix = cb.async ? 'async (' : '('
256
+ s.overwrite(
257
+ cb.start,
258
+ arrow_pos + 2,
259
+ comp_arg + ', ' + prefix + l_name + ') =>'
260
+ )
261
+ rewriteBody(cb.body, param_map, l_name, s)
262
+ changed = true
263
+ return false
264
+ })
265
+
266
+ if (!changed) return { code, map: null, changed: false }
267
+ return {
268
+ code: s.toString(),
269
+ map: s.generateMap({ hires: true }),
270
+ changed: true
271
+ }
272
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.