x-cem 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/README.md CHANGED
@@ -1,3 +1,34 @@
1
- # Temporary Holding Version
1
+ # x-cem
2
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.
3
+ 零依赖、词法级(不建 AST)的 Custom Elements Manifest 2.1.0 生成器。
4
+ npm 包内置一份跨平台 `core.wasm`,Node.js >= 18,无需 Rust 工具链。
5
+
6
+ ## 用法
7
+
8
+ ```sh
9
+ npx x-cem scan --src src --out custom-elements-manifest.json
10
+ # 不写 --out 时输出到 stdout
11
+ npx x-cem scan --src src
12
+ ```
13
+
14
+ Node API:
15
+
16
+ ```js
17
+ import { scanSource, scanDir } from 'x-cem';
18
+
19
+ const manifest = await scanDir('src');
20
+ // { schemaVersion: '2.1.0', modules: [...] }
21
+ ```
22
+
23
+ `scanSource({ path, source })` 解析单个源文件。完整文档、性能对比和限制清单见
24
+ [GitHub 仓库](https://github.com/CC19990113/x-cem)。
25
+
26
+ ## 限制
27
+
28
+ import 别名、装饰器注册、匿名类、动态 tag、跨模块同名 class 消歧、`.tsx` / `.mts` / `.cjs`
29
+ 均不支持;输出是 CEM 子集(无 `members` / `superclass` / `exports`)。详见仓库 README 的
30
+ 「它不做什么」。
31
+
32
+ ## License
33
+
34
+ MIT
package/cli.js ADDED
@@ -0,0 +1,151 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * x-cem CLI(npm / wasm 版)。
4
+ *
5
+ * 参数与 Rust 原生 CLI 保持一致(手写解析,零依赖):
6
+ * x-cem scan --src <目录或文件> [--out <输出文件>]
7
+ *
8
+ * 与原生 CLI 的差异只有一处:`--out` 可省略,缺省或 `-` 时输出到 stdout。
9
+ * 退出码:0 成功;1 扫描/解析失败;2 用法错误。
10
+ */
11
+
12
+ import { writeFile } from 'node:fs/promises';
13
+ import { createRequire } from 'node:module';
14
+
15
+ import { scanDirWithWarnings } from './index.js';
16
+
17
+ const require = createRequire(import.meta.url);
18
+ const pkg = require('./package.json');
19
+
20
+ const USAGE = `x-cem — 词法级 TS/JS Custom Elements Manifest 生成器(npm / wasm 版)
21
+
22
+ 用法:
23
+ x-cem scan --src <目录或文件> [--out <输出文件>]
24
+
25
+ 选项:
26
+ --src <path> 递归扫描 *.ts / *.js
27
+ --out <path> 输出 CEM JSON;缺省或 \`-\` 表示 stdout
28
+ -h, --help 显示帮助
29
+ -V, --version 显示版本
30
+ `;
31
+
32
+ function printUsage() {
33
+ process.stdout.write(USAGE);
34
+ }
35
+
36
+ function usageError(message) {
37
+ process.stderr.write(`x-cem: ${message}\n\n${USAGE}`);
38
+ return 2;
39
+ }
40
+
41
+ async function runScan(args) {
42
+ let src;
43
+ let out;
44
+
45
+ for (let i = 0; i < args.length; i += 1) {
46
+ const arg = args[i];
47
+ const equals = arg.indexOf('=');
48
+ const key = equals === -1 ? arg : arg.slice(0, equals);
49
+ const inlineValue = equals === -1 ? undefined : arg.slice(equals + 1);
50
+
51
+ if (key === '-h' || key === '--help') {
52
+ printUsage();
53
+ return 0;
54
+ }
55
+
56
+ if (key === '--src' || key === '--out') {
57
+ let value = inlineValue;
58
+ if (value === undefined) {
59
+ i += 1;
60
+ value = args[i];
61
+ if (value === undefined) {
62
+ return usageError(`\`${key}\` 缺少取值`);
63
+ }
64
+ }
65
+
66
+ if (key === '--src') {
67
+ src = value;
68
+ } else {
69
+ out = value;
70
+ }
71
+ continue;
72
+ }
73
+
74
+ return usageError(`未知参数 \`${key}\``);
75
+ }
76
+
77
+ if (src === undefined) {
78
+ return usageError('缺少 `--src`');
79
+ }
80
+
81
+ let manifest;
82
+ let warnings;
83
+ try {
84
+ ({ manifest, warnings } = await scanDirWithWarnings(src));
85
+ } catch (error) {
86
+ process.stderr.write(`x-cem: 扫描 \`${src}\` 失败: ${error.message}\n`);
87
+ return 1;
88
+ }
89
+
90
+ for (const warning of warnings) {
91
+ process.stderr.write(`x-cem: 警告: ${warning}\n`);
92
+ }
93
+
94
+ const json = `${JSON.stringify(manifest, null, 2)}\n`;
95
+ const useStdout = out === undefined || out === '-';
96
+
97
+ if (useStdout) {
98
+ process.stdout.write(json);
99
+ } else {
100
+ try {
101
+ await writeFile(out, json, 'utf8');
102
+ } catch (error) {
103
+ process.stderr.write(`x-cem: 写入 \`${out}\` 失败: ${error.message}\n`);
104
+ return 1;
105
+ }
106
+ }
107
+
108
+ const declarationCount = manifest.modules.reduce(
109
+ (sum, module) => sum + module.declarations.length,
110
+ 0,
111
+ );
112
+ process.stderr.write(
113
+ `x-cem: ${manifest.modules.length} 个模块 / ${declarationCount} 个声明 -> ${
114
+ useStdout ? '-' : out
115
+ }\n`,
116
+ );
117
+
118
+ return 0;
119
+ }
120
+
121
+ async function main(argv) {
122
+ const [command, ...rest] = argv;
123
+
124
+ if (command === undefined) {
125
+ return usageError('缺少子命令');
126
+ }
127
+
128
+ switch (command) {
129
+ case '-h':
130
+ case '--help':
131
+ printUsage();
132
+ return 0;
133
+ case '-V':
134
+ case '--version':
135
+ process.stdout.write(`x-cem ${pkg.version}\n`);
136
+ return 0;
137
+ case 'scan':
138
+ return runScan(rest);
139
+ default:
140
+ return usageError(`未知子命令 \`${command}\``);
141
+ }
142
+ }
143
+
144
+ main(process.argv.slice(2))
145
+ .then((code) => {
146
+ process.exitCode = code;
147
+ })
148
+ .catch((error) => {
149
+ process.stderr.write(`x-cem: ${error && error.stack ? error.stack : error}\n`);
150
+ process.exitCode = 1;
151
+ });
package/core.wasm ADDED
Binary file
package/index.js ADDED
@@ -0,0 +1,642 @@
1
+ /**
2
+ * x-cem 的 Node API。
3
+ *
4
+ * 分工:Node 侧负责读文件、遍历目录、拼装 CEM 根对象;解析全部在 wasm 里完成。
5
+ * Rust 侧 ABI 是「单文件」的(xcem_scan(path, src)),因此:
6
+ * - `scanSource` 一次只处理一个源文件;
7
+ * - `scanDir` 逐文件调用,再按 CEM 2.1.0 结构拼装。
8
+ *
9
+ * 跨文件 `customElements.define(tag, Class)` 的归属本应由 Rust 侧在目录级扫描时完成。
10
+ * 如果 Rust 侧返回的单文件 module 尚未回填 `tagName`,下面的 `backfillTagNames`
11
+ * 会做一次保守兜底:用轻量词法收集全部文件的 define,再按「同文件优先 / 跨文件唯一才分配」
12
+ * 的规则回填。兜底不覆盖 Rust 已经给出的 tagName;一旦 Rust 侧在 wasm 内完成关联,
13
+ * 这段逻辑自然变成 no-op。
14
+ */
15
+
16
+ import { readFile, readdir, realpath, stat } from 'node:fs/promises';
17
+ import path from 'node:path';
18
+
19
+ import { loadWasm } from './wasm-loader.js';
20
+
21
+ export const SCHEMA_VERSION = '2.1.0';
22
+
23
+ const SOURCE_EXTENSIONS = new Set(['.ts', '.js']);
24
+ const SKIP_DIR_NAMES = new Set(['node_modules', 'target', 'dist', 'coverage']);
25
+
26
+ const utf8Decoder = new TextDecoder('utf-8', { fatal: true });
27
+
28
+ /**
29
+ * 解析单个源文件,返回一个 CEM module 对象。
30
+ *
31
+ * @param {{ path: string, source: string }} input
32
+ * `path` 只用于 module.path / 错误信息;`source` 是 UTF-8 源码文本。
33
+ * @returns {Promise<object>} module 对象,形如 `{ kind: 'javascript-module', path, declarations }`
34
+ */
35
+ export async function scanSource({ path: sourcePath, source } = {}) {
36
+ if (typeof sourcePath !== 'string' || sourcePath.length === 0) {
37
+ throw new TypeError('scanSource: `path` 必须是非空字符串');
38
+ }
39
+ if (typeof source !== 'string') {
40
+ throw new TypeError('scanSource: `source` 必须是字符串');
41
+ }
42
+
43
+ const instance = await loadWasm();
44
+ const json = callScan(instance, sourcePath, source);
45
+
46
+ let parsed;
47
+ try {
48
+ parsed = JSON.parse(json);
49
+ } catch (error) {
50
+ throw new Error(
51
+ `wasm 返回了非法 JSON(${sourcePath}):${error.message}`,
52
+ { cause: error },
53
+ );
54
+ }
55
+
56
+ return normalizeModule(parsed, sourcePath);
57
+ }
58
+
59
+ /**
60
+ * 递归扫描目录(也接受单个文件),返回 CEM 根对象。
61
+ *
62
+ * @param {string} dir
63
+ * @returns {Promise<{ schemaVersion: string, modules: object[] }>}
64
+ */
65
+ export async function scanDir(dir) {
66
+ const { manifest } = await scanDirWithWarnings(dir);
67
+ return manifest;
68
+ }
69
+
70
+ /**
71
+ * 与 {@link scanDir} 相同,但额外返回关联阶段的 warning 文本。
72
+ * CLI 用它把警告打到 stderr,与 Rust 原生 CLI 行为一致。
73
+ *
74
+ * @param {string} dir
75
+ * @returns {Promise<{ manifest: { schemaVersion: string, modules: object[] }, warnings: string[] }>}
76
+ */
77
+ export async function scanDirWithWarnings(dir) {
78
+ if (typeof dir !== 'string' || dir.length === 0) {
79
+ throw new TypeError('scanDir: `dir` 必须是非空字符串');
80
+ }
81
+
82
+ const input = path.resolve(dir);
83
+ let root;
84
+ try {
85
+ root = await realpath(input);
86
+ } catch (error) {
87
+ const detail = error && error.code === 'ENOENT' ? '路径不存在' : error.message;
88
+ throw new Error(`无法访问 ${dir}:${detail}`, { cause: error });
89
+ }
90
+
91
+ let rootStat;
92
+ try {
93
+ rootStat = await stat(root);
94
+ } catch (error) {
95
+ throw new Error(`无法访问 ${dir}:${error.message}`, { cause: error });
96
+ }
97
+ const files = [];
98
+
99
+ if (rootStat.isFile()) {
100
+ files.push({
101
+ absolutePath: root,
102
+ displayPath: displayPath(root, path.dirname(root)),
103
+ });
104
+ } else if (rootStat.isDirectory()) {
105
+ await walk(root, files, root);
106
+ } else {
107
+ throw new Error(`无法访问 ${dir}:既不是普通文件也不是目录`);
108
+ }
109
+
110
+ const scanned = [];
111
+ const included = [];
112
+
113
+ files.sort((a, b) =>
114
+ a.absolutePath < b.absolutePath ? -1 : a.absolutePath > b.absolutePath ? 1 : 0,
115
+ );
116
+
117
+ for (const file of files) {
118
+ let buffer;
119
+ try {
120
+ buffer = await readFile(file.absolutePath);
121
+ } catch (error) {
122
+ throw new Error(`读取 ${file.absolutePath} 失败:${error.message}`, { cause: error });
123
+ }
124
+
125
+ let source;
126
+ try {
127
+ source = utf8Decoder.decode(buffer);
128
+ } catch {
129
+ throw new Error(`${file.displayPath} 不是合法 UTF-8;x-cem 只处理 UTF-8 源文件`);
130
+ }
131
+
132
+ const module = await scanSource({ path: file.displayPath, source });
133
+ const fileIndex = scanned.length;
134
+ scanned.push({ source });
135
+
136
+ if (module.declarations.length > 0) {
137
+ included.push({ module, fileIndex });
138
+ }
139
+ }
140
+
141
+ // 兜底:Rust 单文件 ABI 不会做跨文件关联时,在 JS 侧补 tagName。
142
+ // 所有声明都已有 tagName 时直接跳过,避免再做一遍 JS 词法扫描。
143
+ const needsBackfill = included.some(({ module }) =>
144
+ module.declarations.some((declaration) => !declaration.tagName),
145
+ );
146
+ const warnings = needsBackfill ? backfillTagNames(included, scanned) : [];
147
+
148
+ const manifest = {
149
+ schemaVersion: SCHEMA_VERSION,
150
+ modules: included.map(({ module }) => module),
151
+ };
152
+
153
+ return { manifest, warnings };
154
+ }
155
+
156
+ /* ------------------------------------------------------------------ */
157
+ /* wasm 调用 */
158
+ /* ------------------------------------------------------------------ */
159
+
160
+ const textEncoder = new TextEncoder();
161
+
162
+ function callScan(instance, sourcePath, source) {
163
+ const { exports } = instance;
164
+ const memory = exports.memory;
165
+
166
+ const pathBytes = textEncoder.encode(sourcePath);
167
+ const sourceBytes = textEncoder.encode(source);
168
+
169
+ // wasm 侧的 alloc(0) 行为未约定;统一至少分配 1 字节,free 时用同一个长度。
170
+ const pathLength = Math.max(1, pathBytes.length);
171
+ const sourceLength = Math.max(1, sourceBytes.length);
172
+
173
+ const pathPtr = exports.xcem_alloc(pathLength);
174
+ if (!pathPtr) {
175
+ throw new Error('wasm 内存分配失败:xcem_alloc 返回空指针');
176
+ }
177
+ const sourcePtr = exports.xcem_alloc(sourceLength);
178
+ if (!sourcePtr) {
179
+ exports.xcem_free(pathPtr, pathLength);
180
+ throw new Error('wasm 内存分配失败:xcem_alloc 返回空指针');
181
+ }
182
+
183
+ let resultBytes;
184
+ try {
185
+ // 每次取视图都必须基于最新的 memory.buffer:alloc 可能触发内存增长。
186
+ new Uint8Array(memory.buffer, pathPtr, pathBytes.length).set(pathBytes);
187
+ new Uint8Array(memory.buffer, sourcePtr, sourceBytes.length).set(sourceBytes);
188
+
189
+ const code = exports.xcem_scan(pathPtr, pathBytes.length, sourcePtr, sourceBytes.length);
190
+ if (code !== 0) {
191
+ const detail = readLastError(exports);
192
+ throw new Error(
193
+ `解析失败(${sourcePath}):wasm xcem_scan 返回错误码 ${code}${detail ? `(${detail})` : ''}`,
194
+ );
195
+ }
196
+
197
+ const resultPtr = exports.xcem_result_ptr();
198
+ const resultLength = exports.xcem_result_len();
199
+ if (resultLength > 0 && !resultPtr) {
200
+ throw new Error(`解析失败(${sourcePath}):xcem_result_ptr 返回空指针但长度为 ${resultLength}`);
201
+ }
202
+
203
+ // 先拷贝出 wasm 内存,再 free 输入缓冲。
204
+ resultBytes =
205
+ resultLength > 0
206
+ ? new Uint8Array(memory.buffer, resultPtr, resultLength).slice()
207
+ : new Uint8Array(0);
208
+ } finally {
209
+ exports.xcem_free(pathPtr, pathLength);
210
+ exports.xcem_free(sourcePtr, sourceLength);
211
+ }
212
+
213
+ try {
214
+ return utf8Decoder.decode(resultBytes);
215
+ } catch (error) {
216
+ throw new Error(
217
+ `解析失败(${sourcePath}):wasm 返回的结果不是合法 UTF-8:${error.message}`,
218
+ { cause: error },
219
+ );
220
+ }
221
+ }
222
+
223
+ /**
224
+ * 可选的 ABI 扩展:Rust 侧额外导出了 xcem_last_error_ptr / len。
225
+ * 没有这两个导出时退化为只有错误码,不影响主流程。
226
+ */
227
+ function readLastError(exports) {
228
+ if (
229
+ typeof exports.xcem_last_error_ptr !== 'function' ||
230
+ typeof exports.xcem_last_error_len !== 'function'
231
+ ) {
232
+ return '';
233
+ }
234
+
235
+ const ptr = exports.xcem_last_error_ptr();
236
+ const length = exports.xcem_last_error_len();
237
+ if (!ptr || !length) {
238
+ return '';
239
+ }
240
+
241
+ try {
242
+ const bytes = new Uint8Array(exports.memory.buffer, ptr, length).slice();
243
+ return utf8Decoder.decode(bytes);
244
+ } catch {
245
+ return '';
246
+ }
247
+ }
248
+
249
+ /**
250
+ * 兼容两种 wasm 返回形态:
251
+ * 1. 完整 CEM 根对象 `{ schemaVersion, modules: [...] }`(单文件时取 modules[0]);
252
+ * 2. 裸 module 对象 `{ kind: 'javascript-module', path, declarations }`。
253
+ */
254
+ function normalizeModule(parsed, sourcePath) {
255
+ if (parsed && Array.isArray(parsed.modules)) {
256
+ const module = parsed.modules[0];
257
+ if (!module) {
258
+ return { kind: 'javascript-module', path: sourcePath, declarations: [] };
259
+ }
260
+ return normalizeShape(module, sourcePath);
261
+ }
262
+
263
+ if (parsed && Array.isArray(parsed.declarations)) {
264
+ return normalizeShape(parsed, sourcePath);
265
+ }
266
+
267
+ throw new Error(
268
+ `wasm 返回结构无法识别(${sourcePath}):既不是 CEM 根对象(modules 数组),也不是 module 对象(declarations 数组)`,
269
+ );
270
+ }
271
+
272
+ function normalizeShape(module, fallbackPath) {
273
+ return {
274
+ ...module,
275
+ path: typeof module.path === 'string' && module.path.length > 0 ? module.path : fallbackPath,
276
+ declarations: module.declarations,
277
+ };
278
+ }
279
+
280
+ /* ------------------------------------------------------------------ */
281
+ /* 目录遍历 */
282
+ /* ------------------------------------------------------------------ */
283
+
284
+ async function walk(dir, files, root) {
285
+ const entries = await readdir(dir, { withFileTypes: true });
286
+ entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
287
+
288
+ for (const entry of entries) {
289
+ const absolutePath = path.join(dir, entry.name);
290
+
291
+ // 与 Rust 侧一致:不跟随符号链接。
292
+ if (entry.isSymbolicLink()) {
293
+ continue;
294
+ }
295
+
296
+ if (entry.isDirectory()) {
297
+ if (entry.name.startsWith('.') || SKIP_DIR_NAMES.has(entry.name)) {
298
+ continue;
299
+ }
300
+ await walk(absolutePath, files, root);
301
+ continue;
302
+ }
303
+
304
+ if (!entry.isFile()) {
305
+ continue;
306
+ }
307
+
308
+ if (!SOURCE_EXTENSIONS.has(path.extname(entry.name))) {
309
+ continue;
310
+ }
311
+
312
+ files.push({ absolutePath, displayPath: displayPath(absolutePath, root) });
313
+ }
314
+ }
315
+
316
+ /**
317
+ * 优先输出相对 cwd 的路径;src 在 cwd 之外时退回相对 src 的路径。
318
+ * 与 Rust CLI 的 display_path 规则一致,统一用 `/`。
319
+ */
320
+ function displayPath(file, root) {
321
+ const relativeToCwd = path.relative(process.cwd(), file);
322
+ if (relativeToCwd && !relativeToCwd.startsWith('..') && !path.isAbsolute(relativeToCwd)) {
323
+ return toPosix(relativeToCwd);
324
+ }
325
+
326
+ const relativeToRoot = path.relative(root, file);
327
+ if (relativeToRoot && !relativeToRoot.startsWith('..') && !path.isAbsolute(relativeToRoot)) {
328
+ return toPosix(relativeToRoot);
329
+ }
330
+
331
+ return toPosix(file);
332
+ }
333
+
334
+ function toPosix(value) {
335
+ return value.split(path.sep).join('/');
336
+ }
337
+
338
+ /* ------------------------------------------------------------------ */
339
+ /* 跨文件 tagName 兜底 */
340
+ /* ------------------------------------------------------------------ */
341
+
342
+ /**
343
+ * 从所有已读源码里收集 `customElements.define('tag', Class)`,再给缺失 tagName 的
344
+ * 声明回填。规则与 Rust 文档一致:
345
+ * - 同文件 define 优先;同文件多个不同 tag 视为冲突,不分配;
346
+ * - 否则看跨文件 define:唯一 tag 且该 class 只在一个模块中声明,才分配;
347
+ * - 其余歧义场景只记 warning,不分配。
348
+ *
349
+ * 注意:这是「单文件 ABI」下的兜底,不是完整模块图消歧;Rust 侧若已在目录级完成
350
+ * 关联,这里不会改动任何已有 tagName。
351
+ *
352
+ * @returns {string[]} warnings
353
+ */
354
+ function backfillTagNames(included, scanned) {
355
+ const warnings = [];
356
+
357
+ const definesByClass = new Map();
358
+ for (let fileIndex = 0; fileIndex < scanned.length; fileIndex += 1) {
359
+ for (const define of findDefines(scanned[fileIndex].source)) {
360
+ if (!definesByClass.has(define.className)) {
361
+ definesByClass.set(define.className, []);
362
+ }
363
+ definesByClass.get(define.className).push({ ...define, fileIndex });
364
+ }
365
+ }
366
+
367
+ if (definesByClass.size === 0) {
368
+ return warnings;
369
+ }
370
+
371
+ // 这个 class 名出现在哪些「有声明的模块」里。
372
+ const classModules = new Map();
373
+ for (const { module, fileIndex } of included) {
374
+ for (const declaration of module.declarations) {
375
+ if (!classModules.has(declaration.name)) {
376
+ classModules.set(declaration.name, new Set());
377
+ }
378
+ classModules.get(declaration.name).add(fileIndex);
379
+ }
380
+ }
381
+
382
+ for (const { module, fileIndex } of included) {
383
+ for (let index = 0; index < module.declarations.length; index += 1) {
384
+ const declaration = module.declarations[index];
385
+ if (declaration.tagName) {
386
+ continue;
387
+ }
388
+
389
+ const candidates = definesByClass.get(declaration.name);
390
+ if (!candidates || candidates.length === 0) {
391
+ continue;
392
+ }
393
+
394
+ const sameFile = candidates.filter((candidate) => candidate.fileIndex === fileIndex);
395
+ if (sameFile.length > 0) {
396
+ const tags = distinctTags(sameFile);
397
+ if (tags.length === 1) {
398
+ assignTagName(module, index, tags[0]);
399
+ } else {
400
+ warnings.push(
401
+ `类 ${declaration.name} 在 ${module.path} 内有多个不同的 define(${tags.join('、')}),未分配 tagName`,
402
+ );
403
+ }
404
+ continue;
405
+ }
406
+
407
+ const tags = distinctTags(candidates);
408
+ const declaringModules = classModules.get(declaration.name);
409
+
410
+ if (tags.length > 1) {
411
+ warnings.push(
412
+ `类 ${declaration.name} 被多个 define 指向(${tags.join('、')}),跨文件关联有歧义,未分配 tagName`,
413
+ );
414
+ } else if (!declaringModules || declaringModules.size > 1) {
415
+ warnings.push(
416
+ `类名 ${declaration.name} 在多个模块中出现,跨文件 define 无法确定归属,未分配 tagName`,
417
+ );
418
+ } else {
419
+ assignTagName(module, index, tags[0]);
420
+ }
421
+ }
422
+ }
423
+
424
+ return warnings;
425
+ }
426
+
427
+ /**
428
+ * 给声明补 tagName / customElement,并把它们插到 `name` 之后,
429
+ * 让 JS 兜底的输出字段顺序与 Rust 序列化一致。
430
+ */
431
+ function assignTagName(module, index, tag) {
432
+ const declaration = module.declarations[index];
433
+ const ordered = {};
434
+
435
+ for (const [key, value] of Object.entries(declaration)) {
436
+ if (key === 'tagName' || key === 'customElement') {
437
+ continue;
438
+ }
439
+ ordered[key] = value;
440
+ if (key === 'name') {
441
+ ordered.tagName = tag;
442
+ ordered.customElement = true;
443
+ }
444
+ }
445
+
446
+ if (!('tagName' in ordered)) {
447
+ ordered.tagName = tag;
448
+ ordered.customElement = true;
449
+ }
450
+
451
+ module.declarations[index] = ordered;
452
+ }
453
+
454
+ function distinctTags(candidates) {
455
+ const tags = [];
456
+ for (const candidate of candidates) {
457
+ if (!tags.includes(candidate.tag)) {
458
+ tags.push(candidate.tag);
459
+ }
460
+ }
461
+ return tags;
462
+ }
463
+
464
+ /**
465
+ * 极简 JS 词法扫描,只服务 define 兜底:
466
+ * 跳过注释与模板字符串,产出 ident / string / 单字符 punct。
467
+ * 它不是完整词法器,正则字面量等边界情况可能误判 —— 兜底只在 Rust 未回填时生效。
468
+ */
469
+ function findDefines(source) {
470
+ const tokens = tokenizeLite(source);
471
+ const defines = [];
472
+
473
+ for (let i = 0; i < tokens.length; i += 1) {
474
+ const token = tokens[i];
475
+ if (token.type !== 'ident' || token.value !== 'customElements') {
476
+ continue;
477
+ }
478
+
479
+ const parsed = parseDefine(tokens, i);
480
+ if (parsed) {
481
+ defines.push(parsed);
482
+ }
483
+ }
484
+
485
+ return defines;
486
+ }
487
+
488
+ function parseDefine(tokens, index) {
489
+ if (!isPunct(tokens[index + 1], '.')) return null;
490
+ if (!isIdent(tokens[index + 2], 'define')) return null;
491
+ if (!isPunct(tokens[index + 3], '(')) return null;
492
+
493
+ const tagToken = tokens[index + 4];
494
+ if (!tagToken || tagToken.type !== 'string') return null;
495
+ const tag = unescapeJs(tagToken.value);
496
+ if (!isValidTagName(tag)) return null;
497
+ if (!isPunct(tokens[index + 5], ',')) return null;
498
+
499
+ const first = tokens[index + 6];
500
+ if (!first || first.type !== 'ident') return null;
501
+
502
+ let className = first.value;
503
+ let cursor = index + 7;
504
+ while (isPunct(tokens[cursor], '.')) {
505
+ const next = tokens[cursor + 1];
506
+ if (!next || next.type !== 'ident') return null;
507
+ className = next.value;
508
+ cursor += 2;
509
+ }
510
+
511
+ return { tag, className };
512
+ }
513
+
514
+ function isIdent(token, value) {
515
+ return Boolean(token) && token.type === 'ident' && token.value === value;
516
+ }
517
+
518
+ function isPunct(token, value) {
519
+ return Boolean(token) && token.type === 'punct' && token.value === value;
520
+ }
521
+
522
+ function isValidTagName(tag) {
523
+ return /^[a-z][a-z0-9_.:-]*-[a-z0-9_.:-]*$/.test(tag);
524
+ }
525
+
526
+ const SIMPLE_ESCAPES = { n: '\n', r: '\r', t: '\t', b: '\b', f: '\f', v: '\v', 0: '\0' };
527
+
528
+ function unescapeJs(value) {
529
+ if (!value.includes('\\')) return value;
530
+
531
+ let out = '';
532
+ for (let i = 0; i < value.length; i += 1) {
533
+ const char = value[i];
534
+ if (char !== '\\') {
535
+ out += char;
536
+ continue;
537
+ }
538
+ const next = value[i + 1];
539
+ if (next === undefined) {
540
+ out += '\\';
541
+ break;
542
+ }
543
+ if (next === 'x' && /^[0-9a-fA-F]{2}$/.test(value.slice(i + 2, i + 4))) {
544
+ out += String.fromCharCode(Number.parseInt(value.slice(i + 2, i + 4), 16));
545
+ i += 3;
546
+ continue;
547
+ }
548
+ if (next === 'u') {
549
+ const braced = /^\{([0-9a-fA-F]{1,6})\}/.exec(value.slice(i + 2));
550
+ if (braced) {
551
+ out += String.fromCodePoint(Number.parseInt(braced[1], 16));
552
+ i += 2 + braced[0].length;
553
+ continue;
554
+ }
555
+ if (/^[0-9a-fA-F]{4}$/.test(value.slice(i + 2, i + 6))) {
556
+ out += String.fromCharCode(Number.parseInt(value.slice(i + 2, i + 6), 16));
557
+ i += 5;
558
+ continue;
559
+ }
560
+ }
561
+ out += SIMPLE_ESCAPES[next] ?? next;
562
+ i += 1;
563
+ }
564
+ return out;
565
+ }
566
+
567
+ function tokenizeLite(source) {
568
+ const tokens = [];
569
+ const length = source.length;
570
+ let i = 0;
571
+
572
+ const isIdentStart = (char) => /[A-Za-z_$]/.test(char);
573
+ const isIdentPart = (char) => /[A-Za-z0-9_$]/.test(char);
574
+
575
+ while (i < length) {
576
+ const char = source[i];
577
+
578
+ if (char === '/' && source[i + 1] === '/') {
579
+ const newline = source.indexOf('\n', i + 2);
580
+ i = newline === -1 ? length : newline + 1;
581
+ continue;
582
+ }
583
+
584
+ if (char === '/' && source[i + 1] === '*') {
585
+ const end = source.indexOf('*/', i + 2);
586
+ i = end === -1 ? length : end + 2;
587
+ continue;
588
+ }
589
+
590
+ if (char === '"' || char === "'" || char === '`') {
591
+ const quote = char;
592
+ let value = '';
593
+ i += 1;
594
+ while (i < length) {
595
+ const current = source[i];
596
+ if (current === '\\') {
597
+ value += current + (source[i + 1] ?? '');
598
+ i += 2;
599
+ continue;
600
+ }
601
+ if (current === quote) {
602
+ i += 1;
603
+ break;
604
+ }
605
+ if (quote !== '`' && current === '\n') {
606
+ break; // 未闭合的普通字符串,就地结束
607
+ }
608
+ value += current;
609
+ i += 1;
610
+ }
611
+ tokens.push({ type: 'string', value });
612
+ continue;
613
+ }
614
+
615
+ if (isIdentStart(char)) {
616
+ let end = i + 1;
617
+ while (end < length && isIdentPart(source[end])) {
618
+ end += 1;
619
+ }
620
+ tokens.push({ type: 'ident', value: source.slice(i, end) });
621
+ i = end;
622
+ continue;
623
+ }
624
+
625
+ if (/[0-9]/.test(char)) {
626
+ let end = i + 1;
627
+ while (end < length && /[0-9a-fA-F_xXobOBn.]/.test(source[end])) {
628
+ end += 1;
629
+ }
630
+ tokens.push({ type: 'number', value: source.slice(i, end) });
631
+ i = end;
632
+ continue;
633
+ }
634
+
635
+ if (!/\s/.test(char)) {
636
+ tokens.push({ type: 'punct', value: char });
637
+ }
638
+ i += 1;
639
+ }
640
+
641
+ return tokens;
642
+ }
package/package.json CHANGED
@@ -1,6 +1,41 @@
1
1
  {
2
2
  "name": "x-cem",
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)的 TS/JS Custom Elements Manifest(CEM 2.1.0)生成器,wasm 跨平台分发",
5
+ "keywords": [
6
+ "custom-elements",
7
+ "custom-elements-manifest",
8
+ "cem",
9
+ "web-components",
10
+ "typescript",
11
+ "javascript",
12
+ "wasm",
13
+ "manifest"
14
+ ],
15
+ "license": "MIT",
16
+ "type": "module",
17
+ "bin": {
18
+ "x-cem": "./cli.js"
19
+ },
20
+ "exports": {
21
+ ".": "./index.js"
22
+ },
23
+ "files": [
24
+ "cli.js",
25
+ "index.js",
26
+ "wasm-loader.js",
27
+ "core.wasm"
28
+ ],
29
+ "dependencies": {},
30
+ "engines": {
31
+ "node": ">=18"
32
+ },
33
+ "repository": {
34
+ "type": "git",
35
+ "url": "https://github.com/CC19990113/x-cem"
36
+ },
37
+ "homepage": "https://github.com/CC19990113/x-cem#readme",
38
+ "bugs": {
39
+ "url": "https://github.com/CC19990113/x-cem/issues"
40
+ }
41
+ }
package/wasm-loader.js ADDED
@@ -0,0 +1,101 @@
1
+ /**
2
+ * wasm 加载器:只做「读字节 → WebAssembly.instantiate」。
3
+ *
4
+ * 目标平台是 wasm32-unknown-unknown 的纯 wasm,没有 WASI、也没有任何宿主导入,
5
+ * 因此这里不引入 `node:wasi`,实例化时传入空导入对象。
6
+ *
7
+ * 文件名容错:优先 `core.wasm`,其次 `x_cem.wasm`(Cargo 的 cdylib 产物名)。
8
+ * 两者都不在时给出可操作的错误,而不是让 Node 抛裸 ENOENT。
9
+ */
10
+
11
+ import { readFile } from 'node:fs/promises';
12
+ import { fileURLToPath } from 'node:url';
13
+
14
+ /** 候选文件名,按优先级排列。 */
15
+ const WASM_CANDIDATES = ['core.wasm', 'x_cem.wasm'];
16
+
17
+ /** wasm ABI 必须导出的符号(见仓库根 README 的 ABI 契约)。 */
18
+ const REQUIRED_EXPORTS = [
19
+ 'memory',
20
+ 'xcem_alloc',
21
+ 'xcem_free',
22
+ 'xcem_scan',
23
+ 'xcem_result_ptr',
24
+ 'xcem_result_len',
25
+ ];
26
+
27
+ const HERE = fileURLToPath(new URL('./', import.meta.url));
28
+
29
+ /** 模块级缓存:同一个进程只实例化一次。失败不缓存,修复产物后可重试。 */
30
+ let instancePromise = null;
31
+
32
+ /**
33
+ * 加载并实例化 wasm。
34
+ *
35
+ * @returns {Promise<WebAssembly.Instance>}
36
+ */
37
+ export function loadWasm() {
38
+ if (!instancePromise) {
39
+ instancePromise = instantiateWasm().catch((error) => {
40
+ instancePromise = null;
41
+ throw error;
42
+ });
43
+ }
44
+ return instancePromise;
45
+ }
46
+
47
+ async function instantiateWasm() {
48
+ const found = await readFirstExisting();
49
+
50
+ let instance;
51
+ try {
52
+ // 空导入对象:纯 wasm 没有导入;若产物误用 WASI 会在这里抛出可定位的错误。
53
+ ({ instance } = await WebAssembly.instantiate(found.bytes, {}));
54
+ } catch (error) {
55
+ throw new Error(
56
+ `WebAssembly 实例化失败(${found.name}):${error.message}\n` +
57
+ '请确认该文件由 wasm32-unknown-unknown 目标构建(不是 WASI),且 Node.js >= 18。',
58
+ { cause: error },
59
+ );
60
+ }
61
+
62
+ const missing = REQUIRED_EXPORTS.filter((name) => !(name in instance.exports));
63
+ if (missing.length > 0) {
64
+ throw new Error(
65
+ `wasm 产物 ${found.name} 缺少 ABI 导出:${missing.join(', ')}。\n` +
66
+ '这个文件可能不是 x-cem 的 wasm 产物,或 Rust 侧 ABI 版本不匹配。',
67
+ );
68
+ }
69
+
70
+ return instance;
71
+ }
72
+
73
+ async function readFirstExisting() {
74
+ const missing = [];
75
+
76
+ for (const name of WASM_CANDIDATES) {
77
+ try {
78
+ const bytes = await readFile(new URL(name, import.meta.url));
79
+ return { name, bytes };
80
+ } catch (error) {
81
+ if (error && error.code === 'ENOENT') {
82
+ missing.push(name);
83
+ continue;
84
+ }
85
+ throw new Error(
86
+ `读取 wasm 产物失败(${name}):${error.message}\n查找目录:${HERE}`,
87
+ { cause: error },
88
+ );
89
+ }
90
+ }
91
+
92
+ throw new Error(
93
+ [
94
+ `找不到 wasm 产物:在 ${HERE} 下既没有 core.wasm,也没有 x_cem.wasm。`,
95
+ '请先在仓库根目录运行 `pnpm build:wasm`(若仓库未提供该脚本,手动执行):',
96
+ ' cargo build --release --target wasm32-unknown-unknown',
97
+ ' cp target/wasm32-unknown-unknown/release/x_cem.wasm npm/core.wasm',
98
+ `(本次查找过:${missing.join('、')})`,
99
+ ].join('\n'),
100
+ );
101
+ }