@bhxch/vviewer-detect 0.0.0-stage → 0.1.1

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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 vviewer contributors
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,48 @@
1
- # Temporary Holding Version
1
+ # @bhxch/vviewer-detect
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
+ 文件级判别纯函数层:扩展名提取、magic 签名嗅探、文本性判定、shebang 语言识别、
4
+ BOM+编码检测链与 chardet 精判。纯函数、零 DOM 依赖,唯一第三方依赖为
5
+ [chardet](https://www.npmjs.com/package/chardet),浏览器 / Node 双形态可用。
6
+ vviewer 格式派发器(`@bhxch/vviewer-core`)的判别底座,亦可独立用于任何需要
7
+ 「这个文件是什么」判定的场景。
8
+
9
+ ## 安装
10
+
11
+ ```bash
12
+ npm install @bhxch/vviewer-detect
13
+ ```
14
+
15
+ ## 使用
16
+
17
+ ```ts
18
+ import { detect, refineEncoding } from '@bhxch/vviewer-detect';
19
+
20
+ const head = bytes.slice(0, 4096); // 头部窗口(签名/编码链判定面)
21
+ const det = detect({ name: 'sample.bin', head }); // → BaseDetection
22
+ await refineEncoding(bytes, det); // 可选:chardet 精判,就地改写 det.encoding
23
+ ```
24
+
25
+ `BaseDetection` 字段:`ext`(小写无点扩展名,签名纠偏后为规范扩展名)、`lang?`
26
+ (helix 名,无扩展名时回退链写入 shebang 语言)、`encoding?`(BOM/编码链结果)、
27
+ `binary?`(magic 或编码检测判定)、`signature?`(20 值 magic 枚举:zip/png/jpeg/
28
+ mp4/webp/gz/7z/rar/flac/ogg/bmp 等,null=无命中)。
29
+
30
+ ## 导出面
31
+
32
+ - 总入口:`detect({ name, head, full? })`
33
+ - 分件(总入口各阶段皆可单独使用):
34
+ - `extractExtension(name)` —— 扩展名提取(小写无点)
35
+ - `sniffSignature(head)` —— magic 签名嗅探(20 值枚举)
36
+ - `looksTextual(head)` —— 文本性判定
37
+ - `shebangLangOf(text)` —— shebang → 语言(helix 名)
38
+ - `detectEncoding(bytes)` / `isStrictUtf8(b)` —— BOM+编码检测链
39
+ - `refineEncoding(bytes, det)` —— chardet 精判(置信度+白名单双闸,仅收窄
40
+ 严格 UTF-8 失败的文本,映射外维持 gb18030)
41
+ - 类型与运行时值:`Encoding`(28 值联合类型,由运行时常量 `ENCODING_VALUES`
42
+ 单源派生——「全量编码值清单」消费方直接 import 该数组,扩列不再漏跟)、
43
+ `BaseDetection`
44
+
45
+ ## 仓库与许可
46
+
47
+ - 仓库:[bhxch/vviewer](https://github.com/bhxch/vviewer),源码位于 `packages/vviewer-detect/`
48
+ - 许可:Apache-2.0;第三方依赖(chardet)许可见仓库 `THIRD_PARTY_NOTICES.md`
@@ -0,0 +1,6 @@
1
+ import type { Encoding } from '../types.js';
2
+ /** 严格校验 UTF-8 序列(RFC 3629,含 overlong/代理对拒绝) */
3
+ export declare function isStrictUtf8(b: Uint8Array): boolean;
4
+ /** 编码检测:BOM 优先,UTF-8 严格校验失败回退 gb18030。UTF-32 两判必须在 UTF-16LE
5
+ * 之前——FF FE 00 00 是 FF FE 的前缀包含,顺序颠倒会误判 utf-16le。 */
6
+ export declare function detectEncoding(bytes: Uint8Array): Encoding;
@@ -0,0 +1,65 @@
1
+ function hasUtf8Bom(b) { return b[0] === 0xef && b[1] === 0xbb && b[2] === 0xbf; }
2
+ function hasUtf16leBom(b) { return b[0] === 0xff && b[1] === 0xfe; }
3
+ function hasUtf16beBom(b) { return b[0] === 0xfe && b[1] === 0xff; }
4
+ function hasUtf32leBom(b) { return b[0] === 0xff && b[1] === 0xfe && b[2] === 0 && b[3] === 0; }
5
+ function hasUtf32beBom(b) { return b[0] === 0 && b[1] === 0 && b[2] === 0xfe && b[3] === 0xff; }
6
+ /** 严格校验 UTF-8 序列(RFC 3629,含 overlong/代理对拒绝) */
7
+ export function isStrictUtf8(b) {
8
+ let i = 0;
9
+ while (i < b.length) {
10
+ const c = b[i];
11
+ if (c < 0x80) {
12
+ i += 1;
13
+ continue;
14
+ }
15
+ let len;
16
+ let min;
17
+ let cp;
18
+ if ((c & 0xe0) === 0xc0) {
19
+ len = 2;
20
+ min = 0x80;
21
+ cp = c & 0x1f;
22
+ }
23
+ else if ((c & 0xf0) === 0xe0) {
24
+ len = 3;
25
+ min = 0x800;
26
+ cp = c & 0x0f;
27
+ }
28
+ else if ((c & 0xf8) === 0xf0) {
29
+ len = 4;
30
+ min = 0x10000;
31
+ cp = c & 0x07;
32
+ }
33
+ else
34
+ return false;
35
+ if (i + len > b.length)
36
+ return false;
37
+ for (let k = 1; k < len; k++) {
38
+ const cc = b[i + k];
39
+ if ((cc & 0xc0) !== 0x80)
40
+ return false;
41
+ cp = (cp << 6) | (cc & 0x3f);
42
+ }
43
+ if (cp < min || cp > 0x10ffff || (cp >= 0xd800 && cp <= 0xdfff))
44
+ return false;
45
+ i += len;
46
+ }
47
+ return true;
48
+ }
49
+ /** 编码检测:BOM 优先,UTF-8 严格校验失败回退 gb18030。UTF-32 两判必须在 UTF-16LE
50
+ * 之前——FF FE 00 00 是 FF FE 的前缀包含,顺序颠倒会误判 utf-16le。 */
51
+ export function detectEncoding(bytes) {
52
+ if (hasUtf32leBom(bytes))
53
+ return 'utf-32le';
54
+ if (hasUtf32beBom(bytes))
55
+ return 'utf-32be';
56
+ if (hasUtf8Bom(bytes))
57
+ return 'utf-8';
58
+ if (hasUtf16leBom(bytes))
59
+ return 'utf-16le';
60
+ if (hasUtf16beBom(bytes))
61
+ return 'utf-16be';
62
+ if (isStrictUtf8(bytes))
63
+ return 'utf-8';
64
+ return 'gb18030';
65
+ }
@@ -0,0 +1,5 @@
1
+ import type { BaseDetection } from '../types.js';
2
+ /** 精判:门控(gb18030 且文本性)→ chardet analyse → 置信度+白名单双闸 → 就地改写
3
+ * det.encoding。只动 encoding 一字段(binary 判定属 detect 同步面,不回流)。
4
+ * 形参收 BaseDetection:core 的 Detection extends BaseDetection,传入零摩擦。 */
5
+ export declare function refineEncoding(bytes: Uint8Array, det: BaseDetection): Promise<void>;
@@ -0,0 +1,66 @@
1
+ import { looksTextual } from './magic.js';
2
+ const CONFIDENCE_MIN = 90;
3
+ const SAMPLE_LIMIT = 64 * 1024;
4
+ let chardetPromise = null;
5
+ function loadChardet() {
6
+ chardetPromise ??= import('chardet');
7
+ return chardetPromise;
8
+ }
9
+ /** detector 编码名 → TextDecoder 标签白名单(键小写查表);映射外维持 gb18030。
10
+ * MacCyrillic → WHATWG x-mac-cyrillic;ASCII/UTF 族/GB18030 不可达(UTF-8 被严格
11
+ * 校验先行,UTF-16/32 被 BOM 先行,GB18030 为现状值)。ibm866/iso-8859-15/maccyrillic
12
+ * 为前瞻性键(chardet 2.2.0 识别器暂不产出,未来版本可能启用),查表 miss 即维持
13
+ * gb18030 无害。 */
14
+ const LABELS = {
15
+ 'shift_jis': 'shift_jis',
16
+ 'euc-jp': 'euc-jp',
17
+ 'iso-2022-jp': 'iso-2022-jp',
18
+ 'euc-kr': 'euc-kr',
19
+ 'big5': 'big5',
20
+ 'windows-1250': 'windows-1250',
21
+ 'windows-1251': 'windows-1251',
22
+ 'windows-1252': 'windows-1252',
23
+ 'windows-1253': 'windows-1253',
24
+ 'windows-1254': 'windows-1254',
25
+ 'windows-1255': 'windows-1255',
26
+ 'windows-1256': 'windows-1256',
27
+ 'windows-1257': 'windows-1257',
28
+ 'windows-1258': 'windows-1258',
29
+ 'koi8-r': 'koi8-r',
30
+ 'ibm866': 'ibm866',
31
+ 'iso-8859-2': 'iso-8859-2',
32
+ 'iso-8859-5': 'iso-8859-5',
33
+ 'iso-8859-7': 'iso-8859-7',
34
+ 'iso-8859-15': 'iso-8859-15',
35
+ 'maccyrillic': 'x-mac-cyrillic'
36
+ };
37
+ /** 精判:门控(gb18030 且文本性)→ chardet analyse → 置信度+白名单双闸 → 就地改写
38
+ * det.encoding。只动 encoding 一字段(binary 判定属 detect 同步面,不回流)。
39
+ * 形参收 BaseDetection:core 的 Detection extends BaseDetection,传入零摩擦。 */
40
+ export async function refineEncoding(bytes, det) {
41
+ if (det.encoding !== 'gb18030')
42
+ return;
43
+ const sample = bytes.length > SAMPLE_LIMIT ? bytes.subarray(0, SAMPLE_LIMIT) : bytes;
44
+ if (!looksTextual(sample))
45
+ return;
46
+ try {
47
+ const chardet = await loadChardet();
48
+ const matches = chardet.analyse(sample);
49
+ const best = matches[0];
50
+ if (!best || best.confidence < CONFIDENCE_MIN)
51
+ return;
52
+ // GB18030 自匹配守卫(fix round 1):chardet 已高置信确认真 GB18030 时维持现状
53
+ // 解码( analyse 匹配列非只看榜首——sbcs 98 分错配居首、GB18030 次席的反例见
54
+ // 评审),防「今天正确 → 明天 mojibake」
55
+ if (matches.some((m) => m.name.toLowerCase() === 'gb18030' && m.confidence >= CONFIDENCE_MIN))
56
+ return;
57
+ const label = LABELS[best.name.toLowerCase()];
58
+ // label !== 'gb18030' 为防御性条件:LABELS 现无该键(GB18030 走自匹配守卫前置
59
+ // return),未来误加键时此条件兜底
60
+ if (label !== undefined && label !== 'gb18030')
61
+ det.encoding = label;
62
+ }
63
+ catch {
64
+ // 探测器加载/分析失败:维持 gb18030(永不比今天更差)
65
+ }
66
+ }
@@ -0,0 +1,2 @@
1
+ /** 从文件名/URL 提取小写扩展名;无扩展名(含点文件)返回 '' */
2
+ export declare function extractExtension(name: string): string;
@@ -0,0 +1,9 @@
1
+ /** 从文件名/URL 提取小写扩展名;无扩展名(含点文件)返回 '' */
2
+ export function extractExtension(name) {
3
+ const clean = name.split(/[?#]/, 1)[0] ?? name;
4
+ const base = clean.split('/').pop() ?? clean;
5
+ const dot = base.lastIndexOf('.');
6
+ if (dot <= 0)
7
+ return ''; // <=0 覆盖无点与 .dotfile
8
+ return base.slice(dot + 1).toLowerCase();
9
+ }
@@ -0,0 +1,18 @@
1
+ import type { BaseDetection } from '../types.js';
2
+ export { extractExtension } from './extension.js';
3
+ export { sniffSignature } from './magic.js';
4
+ export { detectEncoding, isStrictUtf8 } from './encoding.js';
5
+ export { refineEncoding } from './encodingRefine.js';
6
+ export { looksTextual, shebangLangOf } from './magic.js';
7
+ /** 检测链:扩展名主路由 + magic 签名 + 编码。head 建议 ≥8KB;full 用于编码精确判定。
8
+ * BUG-32:binary 判定成立时不透出文本编码——编码检测对二进制字节无意义
9
+ * (png/jpg 严格 UTF-8 校验失败恒回退 gb18030 的误导值);消费方约定:getMeta 的
10
+ * encoding 为 undefined 时状态栏/属性面板隐藏「编码」段(ViewerPane/MetaPanel 的
11
+ * 真值判断),文本渲染器本就以 `det.encoding ?? 'utf-8'` 兜底不受影响。
12
+ * 返回 BaseDetection(本包基础形状);core 的 Detection extends BaseDetection
13
+ * 追加派发链标记,赋值/传参零摩擦。 */
14
+ export declare function detect(input: {
15
+ name: string;
16
+ head: Uint8Array;
17
+ full?: Uint8Array;
18
+ }): BaseDetection;
@@ -0,0 +1,33 @@
1
+ import { extractExtension } from './extension.js';
2
+ import { sniffSignature } from './magic.js';
3
+ import { detectEncoding } from './encoding.js';
4
+ export { extractExtension } from './extension.js';
5
+ export { sniffSignature } from './magic.js';
6
+ export { detectEncoding, isStrictUtf8 } from './encoding.js';
7
+ // 统一根入口(包化导出面):dispatcher 原三处 import('../detect'、
8
+ // '../detect/encodingRefine'、'../detect/magic')统一为 from '@bhxch/vviewer-detect' 后
9
+ // 符号不变,故在此补齐精判与文本性/shebang 符号的 re-export。
10
+ export { refineEncoding } from './encodingRefine.js';
11
+ export { looksTextual, shebangLangOf } from './magic.js';
12
+ /** 文本类扩展名窄表(detect 链 binary 判定用):手工维护、与 @bhxch/vviewer-highlight
13
+ * languages.json 无构建期同步(同 SHEBANG_LANGS,见 magic.ts 注释)——包化后成为
14
+ * 本包对外承诺,扩列时人工同步 languages.json 及派发侧约定。 */
15
+ const TEXT_EXTENSIONS = new Set(['txt', 'md', 'markdown', 'html', 'htm', 'css', 'scss', 'js', 'mjs', 'cjs', 'ts', 'tsx', 'jsx', 'json', 'jsonc', 'jsonl', 'ndjson', 'yaml', 'yml', 'toml', 'xml', 'svg', 'csv', 'log', 'py', 'rb', 'go', 'rs', 'java', 'kt', 'c', 'h', 'cpp', 'hpp', 'cc', 'sh', 'bash', 'zsh', 'fish', 'sql', 'lua', 'php', 'pl', 'swift', 'dart', 'vue', 'svelte', 'ini', 'conf', 'cfg', 'env', 'properties', 'gradle', 'cmake', 'dockerfile', 'gitignore', 'license', 'makefile']);
16
+ /** 检测链:扩展名主路由 + magic 签名 + 编码。head 建议 ≥8KB;full 用于编码精确判定。
17
+ * BUG-32:binary 判定成立时不透出文本编码——编码检测对二进制字节无意义
18
+ * (png/jpg 严格 UTF-8 校验失败恒回退 gb18030 的误导值);消费方约定:getMeta 的
19
+ * encoding 为 undefined 时状态栏/属性面板隐藏「编码」段(ViewerPane/MetaPanel 的
20
+ * 真值判断),文本渲染器本就以 `det.encoding ?? 'utf-8'` 兜底不受影响。
21
+ * 返回 BaseDetection(本包基础形状);core 的 Detection extends BaseDetection
22
+ * 追加派发链标记,赋值/传参零摩擦。 */
23
+ export function detect(input) {
24
+ const ext = extractExtension(input.name);
25
+ const signature = sniffSignature(input.head);
26
+ const encoding = detectEncoding(input.full ?? input.head);
27
+ // binary 判定:签名命中且扩展名不属于文本类(文本类扩展名但签名是 zip/ole 时 signature 仍记录,由派发器纠偏),
28
+ // 或编码检测为 gb18030(非 UTF 文本)且扩展名不属于文本类(保守)
29
+ const binary = signature !== null
30
+ ? !TEXT_EXTENSIONS.has(ext)
31
+ : encoding === 'gb18030' && !TEXT_EXTENSIONS.has(ext);
32
+ return { ext, encoding: binary ? undefined : encoding, binary, signature };
33
+ }
@@ -0,0 +1,12 @@
1
+ import type { BaseDetection } from '../types.js';
2
+ /** magic 签名嗅探:ZIP(PK\x03\x04 / PK\x05\x06 / PK\x07\x08)、OLE、PNG、JPEG、GIF、PDF、MPEG-TS;
3
+ * 议题二扩表:mp4/m4a/avif(ftyp 品牌)、webm、webp、wav、ico、gz、7z、rar、flac、ogg、bmp */
4
+ export declare function sniffSignature(head: Uint8Array): BaseDetection['signature'];
5
+ /**
6
+ * 无扩展名文件的文本性探测(BUG-07 回退链第 ② 步):
7
+ * 含 NUL 字节或可打印区外控制字符占比超阈值即判二进制;其余视为文本
8
+ * (严格 UTF-8 失败也可能是 gb18030 文本,不据此拒绝)。
9
+ */
10
+ export declare function looksTextual(head: Uint8Array): boolean;
11
+ /** 首行 shebang → 语言键;非 shebang 或解释器不在窄表返回 null */
12
+ export declare function shebangLangOf(text: string): string | null;
@@ -0,0 +1,117 @@
1
+ const startsWith = (head, sig, at = 0) => sig.every((v, i) => head[at + i] === v);
2
+ /** ftyp 视频品牌白名单(spec §3.2):未列品牌不命中,保守落探测链 */
3
+ const MP4_VIDEO_BRANDS = new Set(['isom', 'iso2', 'mp41', 'mp42', 'msnv', 'm4v ']);
4
+ /** magic 签名嗅探:ZIP(PK\x03\x04 / PK\x05\x06 / PK\x07\x08)、OLE、PNG、JPEG、GIF、PDF、MPEG-TS;
5
+ * 议题二扩表:mp4/m4a/avif(ftyp 品牌)、webm、webp、wav、ico、gz、7z、rar、flac、ogg、bmp */
6
+ export function sniffSignature(head) {
7
+ if (startsWith(head, [0x50, 0x4b, 0x03, 0x04]) || startsWith(head, [0x50, 0x4b, 0x05, 0x06]) || startsWith(head, [0x50, 0x4b, 0x07, 0x08]))
8
+ return 'zip';
9
+ if (startsWith(head, [0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1]))
10
+ return 'ole';
11
+ if (startsWith(head, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))
12
+ return 'png';
13
+ if (startsWith(head, [0xff, 0xd8, 0xff]))
14
+ return 'jpeg';
15
+ if (startsWith(head, [0x47, 0x49, 0x46, 0x38]))
16
+ return 'gif'; // GIF87a/GIF89a
17
+ if (startsWith(head, [0x25, 0x50, 0x44, 0x46]))
18
+ return 'pdf'; // %PDF
19
+ // MPEG-TS:包长 188、同步字节 0x47 固定在包首(0/188/376 三重校验——单字节 0x47='G'
20
+ // 太弱,TypeScript 源码等文本可能撞上;三重对齐后文本命中概率可忽略)。
21
+ // head 不足 377 字节不判定(保守:真实 TS 流远大于此)。
22
+ if (head.length >= 377 && head[0] === 0x47 && head[188] === 0x47 && head[376] === 0x47)
23
+ return 'mpegts';
24
+ // —— 议题二扩表:全部映射到真有渲染器消费的格式(spec §3.2);mp3 无稳定前缀不收 ——
25
+ // mp4/m4a/avif:ftyp box 在 offset 4,品牌 [8..11] 收窄分派;未列品牌不命中(保守落探测链)
26
+ if (startsWith(head, [0x66, 0x74, 0x79, 0x70], 4) && head.length >= 12) {
27
+ const brand = String.fromCharCode(head[8], head[9], head[10], head[11]);
28
+ if (brand === 'M4A ')
29
+ return 'm4a';
30
+ if (brand === 'avif' || brand === 'avis')
31
+ return 'avif';
32
+ if (MP4_VIDEO_BRANDS.has(brand))
33
+ return 'mp4';
34
+ }
35
+ if (startsWith(head, [0x1a, 0x45, 0xdf, 0xa3]))
36
+ return 'webm';
37
+ if (startsWith(head, [0x52, 0x49, 0x46, 0x46], 0) && startsWith(head, [0x57, 0x45, 0x42, 0x50], 8))
38
+ return 'webp';
39
+ if (startsWith(head, [0x52, 0x49, 0x46, 0x46], 0) && startsWith(head, [0x57, 0x41, 0x56, 0x45], 8))
40
+ return 'wav';
41
+ if (startsWith(head, [0x00, 0x00, 0x01, 0x00]))
42
+ return 'ico';
43
+ if (startsWith(head, [0x1f, 0x8b, 0x08]))
44
+ return 'gz'; // 第三字节 0x08=deflate 收窄
45
+ if (startsWith(head, [0x37, 0x7a, 0xbc, 0xaf, 0x27, 0x1c]))
46
+ return '7z';
47
+ if (startsWith(head, [0x52, 0x61, 0x72, 0x21, 0x1a, 0x07]))
48
+ return 'rar'; // v4/v5 共前缀
49
+ if (startsWith(head, [0x66, 0x4c, 0x61, 0x43]))
50
+ return 'flac'; // fLaC
51
+ if (startsWith(head, [0x4f, 0x67, 0x67, 0x53]))
52
+ return 'ogg'; // OggS
53
+ // bmp:'BM' 2 字节弱 → 保留字段 [6..9] 全零强校验为 10 字节有效签名(文本 "BM…" 无 NUL 天然排除)
54
+ if (head[0] === 0x42 && head[1] === 0x4d && head[6] === 0 && head[7] === 0 && head[8] === 0 && head[9] === 0)
55
+ return 'bmp';
56
+ return null;
57
+ }
58
+ /**
59
+ * 无扩展名文件的文本性探测(BUG-07 回退链第 ② 步):
60
+ * 含 NUL 字节或可打印区外控制字符占比超阈值即判二进制;其余视为文本
61
+ * (严格 UTF-8 失败也可能是 gb18030 文本,不据此拒绝)。
62
+ */
63
+ export function looksTextual(head) {
64
+ // 空文件按文本打开(显示空代码视图,优于报错)
65
+ if (head.length === 0)
66
+ return true;
67
+ let suspicious = 0;
68
+ const sample = head.length > 8192 ? head.subarray(0, 8192) : head;
69
+ for (const b of sample) {
70
+ if (b === 0)
71
+ return false; // NUL:文本不出现,出现即二进制(git 同口径)
72
+ // 排除常用文本控制符 \t \n \r \f 后,其余 <0x20 与 0x7f 计为可疑
73
+ if (b < 0x20 && b !== 0x09 && b !== 0x0a && b !== 0x0d && b !== 0x0c)
74
+ suspicious++;
75
+ else if (b === 0x7f)
76
+ suspicious++;
77
+ }
78
+ return suspicious / sample.length <= 0.05;
79
+ }
80
+ /**
81
+ * shebang 首行 → 语言(helix 语言键,与 @bhxch/vviewer-highlight languages.json 同源同形)。
82
+ * 仅无扩展名回退链使用:此窄表为 languages.json shebangs 的高频子集(完整表在
83
+ * highlight 包,本包不依赖上层;新语言先补 languages.json,本表按需同步)。
84
+ * 与 TEXT_EXTENSIONS 同为手工维护窄表、与 languages.json 无构建期同步——包化后
85
+ * 为本包对外承诺,扩列时人工同步。
86
+ */
87
+ const SHEBANG_LANGS = {
88
+ python: 'python', // SHEBANG_RE 剥版本号后捕获段:python3 → python
89
+ uv: 'python',
90
+ node: 'javascript',
91
+ deno: 'typescript',
92
+ bun: 'typescript',
93
+ sh: 'bash',
94
+ bash: 'bash',
95
+ dash: 'bash',
96
+ zsh: 'bash',
97
+ ruby: 'ruby',
98
+ perl: 'perl',
99
+ lua: 'lua',
100
+ luajit: 'lua',
101
+ php: 'php',
102
+ make: 'make',
103
+ gmake: 'make',
104
+ r: 'r',
105
+ fish: 'fish'
106
+ };
107
+ /** 与 @bhxch/vviewer-highlight langdetect.ts 的 SHEBANG_RE 同源:`#!/usr/bin/env python3` → `python` */
108
+ const SHEBANG_RE = /^#!\s*(?:\S*[/\\](?:env\s+(?:-\S+\s+)*)?)?([^\s.\d]+)/;
109
+ /** 首行 shebang → 语言键;非 shebang 或解释器不在窄表返回 null */
110
+ export function shebangLangOf(text) {
111
+ if (!text.startsWith('#!'))
112
+ return null;
113
+ const newline = text.indexOf('\n');
114
+ const firstLine = newline < 0 ? text : text.slice(0, newline);
115
+ const m = SHEBANG_RE.exec(firstLine);
116
+ return m ? SHEBANG_LANGS[m[1]] ?? null : null;
117
+ }
package/index.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ export * from './types.js';
2
+ export * from './detect/index.js';
package/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export * from './types.js';
2
+ export * from './detect/index.js';
package/package.json CHANGED
@@ -1,6 +1,33 @@
1
1
  {
2
2
  "name": "@bhxch/vviewer-detect",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "private": false,
5
+ "type": "module",
6
+ "main": "./index.js",
7
+ "types": "./index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./index.d.ts",
11
+ "default": "./index.js"
12
+ }
13
+ },
14
+ "files": [
15
+ "LICENSE",
16
+ "README.md",
17
+ "detect",
18
+ "index.d.ts",
19
+ "index.js",
20
+ "types.d.ts",
21
+ "types.js"
22
+ ],
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "git+https://github.com/bhxch/vviewer.git",
26
+ "directory": "packages/vviewer-detect"
27
+ },
28
+ "license": "Apache-2.0",
29
+ "dependencies": {
30
+ "chardet": "^2.2.0"
31
+ },
32
+ "contentHash": "5706d9f1fb38fd11"
33
+ }
package/types.d.ts ADDED
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Encoding 值单源(终审 I-1):联合类型由本常量数组派生,需「全量编码值清单」的
3
+ * 运行时消费点(remote.ts X-VV-Encoding 响应头白名单等)直接 import 本数组,
4
+ * 扩列时不再出现「类型扩了、运行时白名单漏跟」的静默丢弃。
5
+ * 本常量为运行时值,随 @bhxch/vviewer-detect 包发布;core/types.ts 转发导出保持既有
6
+ * import 路径零改动。
7
+ */
8
+ export declare const ENCODING_VALUES: readonly ["utf-8", "utf-16le", "utf-16be", "utf-32le", "utf-32be", "gb18030", "shift_jis", "euc-jp", "iso-2022-jp", "euc-kr", "big5", "windows-1250", "windows-1251", "windows-1252", "windows-1253", "windows-1254", "windows-1255", "windows-1256", "windows-1257", "windows-1258", "koi8-r", "ibm866", "iso-8859-2", "iso-8859-5", "iso-8859-7", "iso-8859-15", "x-mac-cyrillic"];
9
+ /**
10
+ * 议题三扩列(§4.3):追加 chardet 精判白名单标签——仅「严格 UTF-8 失败的文本」经
11
+ * 精判分层(detect/encodingRefine)采纳,置信度 + 白名单双闸,映射外维持 gb18030。
12
+ * 消费面:strategy.ts DECODERS(TextDecoder 标签表,编译期强制同步)与 decodeText。
13
+ */
14
+ export type Encoding = typeof ENCODING_VALUES[number];
15
+ /**
16
+ * 文件级判别结果的基础形状(本包单源):扩展名/语言/编码/二进制/magic 签名五类
17
+ * 判别字段。core 的 `Detection extends BaseDetection` 追加派发链标记
18
+ * (extless/reclassifiedFrom)——基础字段扩列改本包,派发语义字段改 core。
19
+ */
20
+ export interface BaseDetection {
21
+ ext: string;
22
+ lang?: string;
23
+ encoding?: Encoding;
24
+ binary?: boolean;
25
+ /**
26
+ * magic 签名(20 值枚举;null = 无命中)。core 的 SIGNATURE_ROUTES 按值路由,
27
+ * 枚举扩列需 @bhxch/vviewer-detect 与 @bhxch/vviewer-core 两包同步发版。
28
+ */
29
+ signature?: 'zip' | 'ole' | 'png' | 'jpeg' | 'gif' | 'pdf' | 'mpegts' | 'mp4' | 'm4a' | 'avif' | 'webm' | 'webp' | 'wav' | 'ico' | 'gz' | '7z' | 'rar' | 'flac' | 'ogg' | 'bmp' | null;
30
+ }
package/types.js ADDED
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Encoding 值单源(终审 I-1):联合类型由本常量数组派生,需「全量编码值清单」的
3
+ * 运行时消费点(remote.ts X-VV-Encoding 响应头白名单等)直接 import 本数组,
4
+ * 扩列时不再出现「类型扩了、运行时白名单漏跟」的静默丢弃。
5
+ * 本常量为运行时值,随 @bhxch/vviewer-detect 包发布;core/types.ts 转发导出保持既有
6
+ * import 路径零改动。
7
+ */
8
+ export const ENCODING_VALUES = [
9
+ 'utf-8', 'utf-16le', 'utf-16be', 'utf-32le', 'utf-32be', 'gb18030',
10
+ 'shift_jis', 'euc-jp', 'iso-2022-jp', 'euc-kr', 'big5',
11
+ 'windows-1250', 'windows-1251', 'windows-1252', 'windows-1253', 'windows-1254',
12
+ 'windows-1255', 'windows-1256', 'windows-1257', 'windows-1258',
13
+ 'koi8-r', 'ibm866', 'iso-8859-2', 'iso-8859-5', 'iso-8859-7', 'iso-8859-15',
14
+ 'x-mac-cyrillic'
15
+ ];