fcdev 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.
Files changed (71) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +81 -2
  3. package/bin/fcdev.mjs +17 -0
  4. package/package.json +38 -4
  5. package/src/build/build-plan.mjs +92 -0
  6. package/src/build/dependency-file.mjs +24 -0
  7. package/src/build/disk-builder.mjs +36 -0
  8. package/src/build/index.mjs +31 -0
  9. package/src/build/program-builder.mjs +209 -0
  10. package/src/build/source-collector.mjs +54 -0
  11. package/src/build/tool-arguments.mjs +83 -0
  12. package/src/cli/args-parser.mjs +84 -0
  13. package/src/cli/commands/build-command.mjs +34 -0
  14. package/src/cli/commands/debug-command.mjs +70 -0
  15. package/src/cli/commands/disasm-command.mjs +65 -0
  16. package/src/cli/commands/disk-command.mjs +34 -0
  17. package/src/cli/commands/info-command.mjs +33 -0
  18. package/src/cli/commands/project-info.mjs +57 -0
  19. package/src/cli/commands/run-command.mjs +68 -0
  20. package/src/cli/commands/sync-command.mjs +85 -0
  21. package/src/cli/index.mjs +100 -0
  22. package/src/config/config-loader.mjs +132 -0
  23. package/src/config/index.mjs +9 -0
  24. package/src/disasm/analysis.mjs +97 -0
  25. package/src/disasm/cdl.mjs +35 -0
  26. package/src/disasm/disassembler.mjs +114 -0
  27. package/src/disasm/index.mjs +16 -0
  28. package/src/disasm/info-writer.mjs +72 -0
  29. package/src/disasm/loaders.mjs +69 -0
  30. package/src/disasm/opcode-table.mjs +268 -0
  31. package/src/disasm/roundtrip.mjs +69 -0
  32. package/src/disasm/symbols.mjs +30 -0
  33. package/src/disasm/trace.mjs +25 -0
  34. package/src/emulator/debug-client.mjs +125 -0
  35. package/src/emulator/emulator-launcher.mjs +80 -0
  36. package/src/emulator/emulator-locator.mjs +62 -0
  37. package/src/emulator/index.mjs +11 -0
  38. package/src/packagers/fat-floppy.mjs +22 -0
  39. package/src/packagers/fat12-image.mjs +245 -0
  40. package/src/packagers/flat-binary.mjs +53 -0
  41. package/src/packagers/index.mjs +54 -0
  42. package/src/packagers/ines.mjs +38 -0
  43. package/src/shared/errors.mjs +25 -0
  44. package/src/shared/fs-utils.mjs +66 -0
  45. package/src/shared/index.mjs +11 -0
  46. package/src/shared/process.mjs +50 -0
  47. package/src/targets/index.mjs +17 -0
  48. package/src/targets/name-rules.mjs +33 -0
  49. package/src/targets/target-registry.mjs +187 -0
  50. package/src/toolchain/index.mjs +16 -0
  51. package/src/toolchain/toolchain-locator.mjs +104 -0
  52. package/targets/nes/asminc/fcnes.inc +16 -0
  53. package/targets/nes/chr/ascii-8x8.chr +0 -0
  54. package/targets/nes/chr/font8x8_basic.h +152 -0
  55. package/targets/nes/include/fcnes.h +45 -0
  56. package/targets/nes/lib/fcnes.lib +0 -0
  57. package/targets/nes/lib/nes-font.o +0 -0
  58. package/targets/nes/lib-build.json +9 -0
  59. package/targets/nes/src/fcnes.s +91 -0
  60. package/targets/nes/src/nes-font.s +12 -0
  61. package/targets/nes/target.json +27 -0
  62. package/targets/sb2000/asminc/sb2000.inc +216 -0
  63. package/targets/sb2000/include/sb2000-symbols.h +380 -0
  64. package/targets/sb2000/include/sb2000.h +52 -0
  65. package/targets/sb2000/lib/crt0.o +0 -0
  66. package/targets/sb2000/lib/sb2000.lib +0 -0
  67. package/targets/sb2000/lib-build.json +8 -0
  68. package/targets/sb2000/link.cfg +35 -0
  69. package/targets/sb2000/src/crt0.s +37 -0
  70. package/targets/sb2000/src/sb2000.s +67 -0
  71. package/targets/sb2000/target.json +28 -0
@@ -0,0 +1,125 @@
1
+ // ------------------------------------------------------------------------
2
+ // 名称:debug-client.mjs
3
+ // 说明:模拟器调试服务的客户端:连接本机端口,发送一行命令,读取以单独的“.”行结束的应答。
4
+ // 作者:sungbin
5
+ // 邮箱:sungbin@3578.cn
6
+ // 日期:2026-11-10
7
+ // 备注:协议见 virtuanes/README.md;服务只监听 127.0.0.1,一次只处理一条命令。
8
+ // ------------------------------------------------------------------------
9
+ import net from 'node:net';
10
+ import { FcdevError } from '../shared/index.mjs';
11
+
12
+ /** fcdev 的调试服务默认端口 */
13
+ export const DEFAULT_DEBUG_PORT = 5699;
14
+
15
+ /** 连接调试服务的超时,单位毫秒 */
16
+ const CONNECT_TIMEOUT_MS = 5_000;
17
+
18
+ /** 一条命令默认的应答超时,单位毫秒 */
19
+ const COMMAND_TIMEOUT_MS = 30_000;
20
+
21
+ /**
22
+ * @typedef {object} DebugReply
23
+ * @property {boolean} ok 应答首行以 OK 开头
24
+ * @property {string} head 应答首行
25
+ * @property {string[]} lines 首行之后的各行
26
+ */
27
+
28
+ /**
29
+ * 解析不含结尾“.”行的应答文本。
30
+ * @param {string} text 应答文本
31
+ * @returns {DebugReply} 解析结果
32
+ */
33
+ export function parseReply(text) {
34
+ const lines = text.split('\n').filter((line) => line.length > 0);
35
+ const head = lines[0] ?? '';
36
+ return { ok: head.startsWith('OK'), head, lines: lines.slice(1) };
37
+ }
38
+
39
+ /** 调试服务客户端 */
40
+ export class DebugClient {
41
+ #socket;
42
+ #buffer = '';
43
+ #waiter = null;
44
+
45
+ /**
46
+ * @param {net.Socket} socket 已连接的套接字
47
+ */
48
+ constructor(socket) {
49
+ this.#socket = socket;
50
+ socket.setEncoding('utf8');
51
+ socket.on('data', (chunk) => {
52
+ this.#buffer += chunk;
53
+ this.#deliver();
54
+ });
55
+ socket.on('close', () => {
56
+ this.#waiter?.reject(new FcdevError('调试连接已关闭', { code: 'DEBUG_CONNECTION_CLOSED' }));
57
+ this.#waiter = null;
58
+ });
59
+ }
60
+
61
+ /**
62
+ * 连接本机调试服务。
63
+ * @param {{port?: number, timeoutMs?: number}} [options] 端口与连接超时
64
+ * @returns {Promise<DebugClient>} 客户端
65
+ * @throws {FcdevError} 连接失败或超时
66
+ */
67
+ static connect({ port = DEFAULT_DEBUG_PORT, timeoutMs = CONNECT_TIMEOUT_MS } = {}) {
68
+ return new Promise((resolve, reject) => {
69
+ const socket = net.connect({ host: '127.0.0.1', port });
70
+ const timer = setTimeout(() => {
71
+ socket.destroy();
72
+ reject(new FcdevError(`连接调试服务(端口 ${port})超时`, { code: 'DEBUG_CONNECT_FAILED' }));
73
+ }, timeoutMs);
74
+ socket.once('connect', () => {
75
+ clearTimeout(timer);
76
+ resolve(new DebugClient(socket));
77
+ });
78
+ socket.once('error', (error) => {
79
+ clearTimeout(timer);
80
+ reject(new FcdevError(`无法连接调试服务(端口 ${port})`, {
81
+ code: 'DEBUG_CONNECT_FAILED',
82
+ hint: '先用 fcdev run --debug 启动模拟器,或检查端口是否一致',
83
+ cause: error,
84
+ }));
85
+ });
86
+ });
87
+ }
88
+
89
+ /** 如果缓冲区里已经有完整应答,交给等待者 */
90
+ #deliver() {
91
+ if (!this.#waiter) return;
92
+ const end = this.#buffer.indexOf('\n.\n');
93
+ if (end < 0) return;
94
+ const reply = parseReply(this.#buffer.slice(0, end + 1));
95
+ this.#buffer = this.#buffer.slice(end + 3);
96
+ const { resolve, timer } = this.#waiter;
97
+ clearTimeout(timer);
98
+ this.#waiter = null;
99
+ resolve(reply);
100
+ }
101
+
102
+ /**
103
+ * 发送一条命令并等待应答;应答为 ERR 时不抛错,由调用者看 ok。
104
+ * @param {string} command 命令文本,不含换行
105
+ * @param {{timeoutMs?: number}} [options] 应答超时
106
+ * @returns {Promise<DebugReply>} 应答
107
+ * @throws {FcdevError} 上一条命令未返回、连接关闭或超时
108
+ */
109
+ send(command, { timeoutMs = COMMAND_TIMEOUT_MS } = {}) {
110
+ if (this.#waiter) throw new FcdevError('上一条调试命令尚未返回', { code: 'DEBUG_BUSY' });
111
+ return new Promise((resolve, reject) => {
112
+ const timer = setTimeout(() => {
113
+ this.#waiter = null;
114
+ reject(new FcdevError(`调试命令“${command}”超过 ${timeoutMs} 毫秒没有应答`, { code: 'DEBUG_TIMEOUT' }));
115
+ }, timeoutMs);
116
+ this.#waiter = { resolve, reject, timer };
117
+ this.#socket.write(`${command}\n`);
118
+ });
119
+ }
120
+
121
+ /** 关闭连接 */
122
+ close() {
123
+ this.#socket.end();
124
+ }
125
+ }
@@ -0,0 +1,80 @@
1
+ // ------------------------------------------------------------------------
2
+ // 名称:emulator-launcher.mjs
3
+ // 说明:启动模拟器:自由运行模式直接打开窗口,调试模式设置调试端口并等待服务就绪。
4
+ // 作者:sungbin
5
+ // 邮箱:sungbin@3578.cn
6
+ // 日期:2026-11-10
7
+ // 备注:模拟器进程与命令行脱离,命令行退出后窗口保持打开;调试模式下模拟器只在收到 run 命令时才运行。
8
+ // ------------------------------------------------------------------------
9
+ import { spawn } from 'node:child_process';
10
+ import { existsSync } from 'node:fs';
11
+ import net from 'node:net';
12
+ import path from 'node:path';
13
+ import { setTimeout as delay } from 'node:timers/promises';
14
+ import { FcdevError } from '../shared/index.mjs';
15
+ import { DEFAULT_DEBUG_PORT, DebugClient } from './debug-client.mjs';
16
+
17
+ /** 等待调试服务就绪的上限,单位毫秒 */
18
+ const READY_TIMEOUT_MS = 30_000;
19
+
20
+ /** 轮询调试服务的间隔,单位毫秒 */
21
+ const READY_POLL_MS = 300;
22
+
23
+ /**
24
+ * 确认本机端口空闲。端口被占用时模拟器的调试服务会静默启动失败,客户端反而可能连到别的模拟器。
25
+ * @param {number} port 端口
26
+ * @returns {Promise<void>}
27
+ * @throws {FcdevError} 端口已被占用
28
+ */
29
+ export function assertPortFree(port) {
30
+ return new Promise((resolve, reject) => {
31
+ const server = net.createServer();
32
+ server.once('error', (error) => reject(new FcdevError(`端口 ${port} 已被占用`, {
33
+ code: 'EMULATOR_PORT_BUSY',
34
+ hint: '用 --port 换一个端口,或关闭占用它的模拟器',
35
+ cause: error,
36
+ })));
37
+ server.listen(port, '127.0.0.1', () => server.close(() => resolve()));
38
+ });
39
+ }
40
+
41
+ /**
42
+ * 启动模拟器。
43
+ * @param {{executable: string, romFile: string, debug?: boolean, port?: number, readyTimeoutMs?: number}} input 模拟器程序、要加载的文件、是否调试模式与端口
44
+ * @returns {Promise<{pid: number|undefined, client: DebugClient|null}>} 进程号;调试模式下还有已连接的客户端,调用者负责关闭
45
+ * @throws {FcdevError} 文件不存在、无法启动,或调试服务没有在时限内就绪
46
+ */
47
+ export async function launchEmulator({ executable, romFile, debug = false, port = DEFAULT_DEBUG_PORT, readyTimeoutMs = READY_TIMEOUT_MS }) {
48
+ if (!existsSync(romFile)) throw new FcdevError(`找不到要加载的文件:${romFile}`, { code: 'EMULATOR_FILE_MISSING' });
49
+ if (debug) await assertPortFree(port);
50
+ const env = { ...process.env };
51
+ if (debug) env.FCDEV_DEBUG_PORT = String(port);
52
+ else delete env.FCDEV_DEBUG_PORT;
53
+
54
+ const child = spawn(executable, [romFile], { cwd: path.dirname(executable), env, stdio: 'ignore', detached: true });
55
+ const failure = new Promise((_, reject) => {
56
+ child.once('error', (error) => reject(new FcdevError(`无法启动模拟器 ${executable}`, { code: 'EMULATOR_START_FAILED', cause: error })));
57
+ });
58
+ child.unref();
59
+ if (!debug) {
60
+ // 给启动失败留出报错的机会,再返回
61
+ await Promise.race([failure, delay(300)]);
62
+ return { pid: child.pid, client: null };
63
+ }
64
+
65
+ const deadline = Date.now() + readyTimeoutMs;
66
+ while (Date.now() < deadline) {
67
+ try {
68
+ const client = await Promise.race([DebugClient.connect({ port, timeoutMs: 1000 }), failure]);
69
+ const status = await client.send('status');
70
+ if (status.head.includes('running=1')) return { pid: child.pid, client };
71
+ client.close();
72
+ } catch (error) {
73
+ if (error.code === 'EMULATOR_START_FAILED') throw error;
74
+ // 服务尚未就绪,稍后重试
75
+ }
76
+ await delay(READY_POLL_MS);
77
+ }
78
+ child.kill();
79
+ throw new FcdevError(`等待模拟器的调试服务(端口 ${port})就绪超时`, { code: 'EMULATOR_NOT_READY', hint: '检查端口是否被占用,或先关闭已打开的模拟器' });
80
+ }
@@ -0,0 +1,62 @@
1
+ // ------------------------------------------------------------------------
2
+ // 名称:emulator-locator.mjs
3
+ // 说明:定位模拟器程序:配置项、环境变量、平台包,按顺序查找。
4
+ // 作者:sungbin
5
+ // 邮箱:sungbin@3578.cn
6
+ // 日期:2026-11-10
7
+ // 备注:模拟器只有 Windows 版;其他系统明确报错,不影响构建。
8
+ // ------------------------------------------------------------------------
9
+ import { existsSync } from 'node:fs';
10
+ import { createRequire } from 'node:module';
11
+ import path from 'node:path';
12
+ import { FcdevError } from '../shared/index.mjs';
13
+
14
+ /** 环境变量:自备模拟器的路径 */
15
+ export const EMULATOR_ENV_NAME = 'FCDEV_EMULATOR';
16
+
17
+ /** 平台包里模拟器程序的相对路径 */
18
+ const PACKAGE_EXECUTABLE = path.join('bin', 'VirtuaNES.exe');
19
+
20
+ /**
21
+ * 模拟器平台包的名称,放在 @rujianjs 作用域下。
22
+ * @param {string} [platform] 系统,默认当前系统
23
+ * @param {string} [arch] 架构,默认当前架构
24
+ * @returns {string} 包名
25
+ */
26
+ export function getEmulatorPackageName(platform = process.platform, arch = process.arch) {
27
+ return `@rujianjs/fcdev-emulator-${platform}-${arch}`;
28
+ }
29
+
30
+ /**
31
+ * 按顺序定位模拟器:配置项 emulator、环境变量、平台包。
32
+ * @param {{configured?: string, env?: NodeJS.ProcessEnv, platform?: string}} [options] configured 为配置里的绝对路径
33
+ * @returns {{executable: string, source: string}} 模拟器程序与来源
34
+ * @throws {FcdevError} 系统不支持,或都找不到
35
+ */
36
+ export function locateEmulator({ configured, env = process.env, platform = process.platform } = {}) {
37
+ const explicit = configured ? { executable: configured, source: 'config' } : env[EMULATOR_ENV_NAME] ? { executable: path.resolve(env[EMULATOR_ENV_NAME]), source: 'env' } : null;
38
+ if (explicit) {
39
+ if (!existsSync(explicit.executable)) {
40
+ throw new FcdevError(`找不到模拟器:${explicit.executable}`, { code: 'EMULATOR_NOT_FOUND' });
41
+ }
42
+ return explicit;
43
+ }
44
+ if (platform !== 'win32') {
45
+ throw new FcdevError('模拟器只支持 Windows', {
46
+ code: 'EMULATOR_UNSUPPORTED',
47
+ hint: `其他系统可用 ${EMULATOR_ENV_NAME} 或 fcdev.json 的 emulator 指定自备的模拟器;构建不受影响`,
48
+ });
49
+ }
50
+ const packageName = getEmulatorPackageName(platform);
51
+ try {
52
+ const packageJson = createRequire(import.meta.url).resolve(`${packageName}/package.json`);
53
+ const executable = path.join(path.dirname(packageJson), PACKAGE_EXECUTABLE);
54
+ if (existsSync(executable)) return { executable, source: 'package' };
55
+ } catch {
56
+ // 平台包没有安装,落到下面统一的报错
57
+ }
58
+ throw new FcdevError('找不到模拟器', {
59
+ code: 'EMULATOR_NOT_FOUND',
60
+ hint: `任选一种:安装平台包 ${packageName};设置环境变量 ${EMULATOR_ENV_NAME} 指向模拟器程序;在 fcdev.json 里用 emulator 指定`,
61
+ });
62
+ }
@@ -0,0 +1,11 @@
1
+ // ------------------------------------------------------------------------
2
+ // 名称:index.mjs
3
+ // 说明:emulator 目录的对外入口:定位模拟器、启动模拟器、调试服务客户端。
4
+ // 作者:sungbin
5
+ // 邮箱:sungbin@3578.cn
6
+ // 日期:2026-11-10
7
+ // 备注:无
8
+ // ------------------------------------------------------------------------
9
+ export { DEFAULT_DEBUG_PORT, DebugClient, parseReply } from './debug-client.mjs';
10
+ export { assertPortFree, launchEmulator } from './emulator-launcher.mjs';
11
+ export { EMULATOR_ENV_NAME, getEmulatorPackageName, locateEmulator } from './emulator-locator.mjs';
@@ -0,0 +1,22 @@
1
+ // ------------------------------------------------------------------------
2
+ // 名称:fat-floppy.mjs
3
+ // 说明:磁盘镜像打包器 fat-floppy:把程序文件放进 1.44MB 的 FAT12 软盘镜像的根目录。
4
+ // 作者:sungbin
5
+ // 邮箱:sungbin@3578.cn
6
+ // 日期:2026-11-10
7
+ // 备注:磁盘打包器与程序打包器不同:输入是一组文件,输出是一个镜像文件。
8
+ // ------------------------------------------------------------------------
9
+ import { writeFileSync } from 'node:fs';
10
+ import { buildFat12Image } from './fat12-image.mjs';
11
+
12
+ /**
13
+ * 生成软盘镜像并写到文件。
14
+ * @param {{files: {name: string, data: Buffer, mtime?: Date}[], outputFile: string, options?: {label?: string}}} input 要放进镜像的文件、镜像路径与卷标
15
+ * @returns {{outputFile: string, size: number}} 镜像路径与大小
16
+ * @throws {import('../shared/index.mjs').FcdevError} 文件名不符合 8.3,或空间不足
17
+ */
18
+ export function packFatFloppy({ files, outputFile, options = {} }) {
19
+ const image = buildFat12Image(files, { label: options.label });
20
+ writeFileSync(outputFile, image);
21
+ return { outputFile, size: image.length };
22
+ }
@@ -0,0 +1,245 @@
1
+ // ------------------------------------------------------------------------
2
+ // 名称:fat12-image.mjs
3
+ // 说明:构建与读取 1.44MB 的 FAT12 软盘镜像(512 字节扇区、2 面、80 磁道、每磁道 18 扇区)。
4
+ // 作者:sungbin
5
+ // 邮箱:sungbin@3578.cn
6
+ // 日期:2026-11-10
7
+ // 备注:几何参数与模拟器的软驱控制器一致(LBA = 磁道*36 + 磁头*18 + 扇区-1,共 2880 个扇区)。
8
+ // 文件只写在根目录,每簇 1 个扇区,不支持子目录。
9
+ // ------------------------------------------------------------------------
10
+ import { FcdevError } from '../shared/index.mjs';
11
+
12
+ /** 1.44MB 软盘的固定参数 */
13
+ export const GEOMETRY = Object.freeze({
14
+ bytesPerSector: 512,
15
+ sectorsPerCluster: 1,
16
+ reservedSectors: 1,
17
+ fatCount: 2,
18
+ rootEntries: 224,
19
+ totalSectors: 2880,
20
+ mediaDescriptor: 0xf0,
21
+ sectorsPerFat: 9,
22
+ sectorsPerTrack: 18,
23
+ heads: 2,
24
+ });
25
+
26
+ /** 目录项大小 */
27
+ const ENTRY_SIZE = 32;
28
+
29
+ /** FAT12 的簇链结束标记 */
30
+ const END_OF_CHAIN = 0xfff;
31
+
32
+ /** 卷标属性位 */
33
+ const ATTR_VOLUME = 0x08;
34
+
35
+ /** 8.3 名字里允许的字符 */
36
+ const NAME_PART = /^[A-Z0-9_$~!#%&\-{}()@'`^]+$/;
37
+
38
+ /**
39
+ * 把文件名转成 11 字节的 8.3 目录项名字。
40
+ * @param {string} fileName 例如 "edit.exe"
41
+ * @returns {string} 11 个字符,不足补空格
42
+ * @throws {FcdevError} 文件名不符合 8.3 规则
43
+ */
44
+ export function toShortName(fileName) {
45
+ const upper = fileName.toUpperCase();
46
+ const dot = upper.lastIndexOf('.');
47
+ const base = dot < 0 ? upper : upper.slice(0, dot);
48
+ const ext = dot < 0 ? '' : upper.slice(dot + 1);
49
+ if (base.length < 1 || base.length > 8 || ext.length > 3 || !NAME_PART.test(base) || (ext && !NAME_PART.test(ext))) {
50
+ throw new FcdevError(`文件名不符合 8.3 规则:${fileName}`, { code: 'DISK_NAME_INVALID' });
51
+ }
52
+ return base.padEnd(8, ' ') + ext.padEnd(3, ' ');
53
+ }
54
+
55
+ /**
56
+ * 把 11 字节目录项名字还原成 NAME.EXT。
57
+ * @param {string} raw 11 个字符
58
+ * @returns {string} 文件名
59
+ */
60
+ function fromShortName(raw) {
61
+ const base = raw.slice(0, 8).trimEnd();
62
+ const ext = raw.slice(8, 11).trimEnd();
63
+ return ext ? `${base}.${ext}` : base;
64
+ }
65
+
66
+ /**
67
+ * 编码 DOS 日期与时间。
68
+ * @param {Date} date 日期时间
69
+ * @returns {{date: number, time: number}} 目录项里的日期与时间字段
70
+ */
71
+ function dosDateTime(date) {
72
+ const year = Math.min(Math.max(date.getFullYear(), 1980), 2107);
73
+ return {
74
+ date: ((year - 1980) << 9) | ((date.getMonth() + 1) << 5) | date.getDate(),
75
+ time: (date.getHours() << 11) | (date.getMinutes() << 5) | (date.getSeconds() >> 1),
76
+ };
77
+ }
78
+
79
+ /**
80
+ * 写入 FAT12 的一个 12 位条目。
81
+ * @param {Buffer} fat FAT 表
82
+ * @param {number} cluster 簇号
83
+ * @param {number} value 条目值
84
+ */
85
+ function setFatEntry(fat, cluster, value) {
86
+ const offset = Math.floor((cluster * 3) / 2);
87
+ if (cluster % 2 === 0) {
88
+ fat[offset] = value & 0xff;
89
+ fat[offset + 1] = (fat[offset + 1] & 0xf0) | ((value >> 8) & 0x0f);
90
+ } else {
91
+ fat[offset] = (fat[offset] & 0x0f) | ((value & 0x0f) << 4);
92
+ fat[offset + 1] = (value >> 4) & 0xff;
93
+ }
94
+ }
95
+
96
+ /**
97
+ * 读取 FAT12 的一个 12 位条目。
98
+ * @param {Buffer} fat FAT 表
99
+ * @param {number} cluster 簇号
100
+ * @returns {number} 条目值
101
+ */
102
+ function getFatEntry(fat, cluster) {
103
+ const offset = Math.floor((cluster * 3) / 2);
104
+ const pair = fat[offset] | (fat[offset + 1] << 8);
105
+ return cluster % 2 === 0 ? pair & 0x0fff : pair >> 4;
106
+ }
107
+
108
+ /**
109
+ * 生成引导扇区(含 BIOS 参数块与 55 AA 签名,不含启动代码)。
110
+ * @param {string} [label] 卷标
111
+ * @returns {Buffer} 512 字节
112
+ */
113
+ function buildBootSector(label) {
114
+ const g = GEOMETRY;
115
+ const sector = Buffer.alloc(g.bytesPerSector);
116
+ sector.set([0xeb, 0x3c, 0x90], 0);
117
+ sector.write('FCDEV ', 3, 'ascii');
118
+ sector.writeUInt16LE(g.bytesPerSector, 11);
119
+ sector.writeUInt8(g.sectorsPerCluster, 13);
120
+ sector.writeUInt16LE(g.reservedSectors, 14);
121
+ sector.writeUInt8(g.fatCount, 16);
122
+ sector.writeUInt16LE(g.rootEntries, 17);
123
+ sector.writeUInt16LE(g.totalSectors, 19);
124
+ sector.writeUInt8(g.mediaDescriptor, 21);
125
+ sector.writeUInt16LE(g.sectorsPerFat, 22);
126
+ sector.writeUInt16LE(g.sectorsPerTrack, 24);
127
+ sector.writeUInt16LE(g.heads, 26);
128
+ sector.writeUInt8(0x29, 38);
129
+ sector.writeUInt32LE(0x20261110, 39);
130
+ sector.write((label ?? 'NO NAME').toUpperCase().padEnd(11, ' ').slice(0, 11), 43, 'ascii');
131
+ sector.write('FAT12 ', 54, 'ascii');
132
+ sector.writeUInt16LE(0xaa55, 510);
133
+ return sector;
134
+ }
135
+
136
+ /**
137
+ * 构建 FAT12 软盘镜像。
138
+ * @param {{name: string, data: Buffer, mtime?: Date}[]} files 要写入根目录的文件
139
+ * @param {{label?: string}} [options] 卷标
140
+ * @returns {Buffer} 1474560 字节的镜像
141
+ * @throws {FcdevError} 文件名不符合 8.3、空间不足或根目录项过多
142
+ */
143
+ export function buildFat12Image(files, options = {}) {
144
+ const g = GEOMETRY;
145
+ const image = Buffer.alloc(g.totalSectors * g.bytesPerSector);
146
+ const fatBytes = g.sectorsPerFat * g.bytesPerSector;
147
+ const rootSectors = (g.rootEntries * ENTRY_SIZE) / g.bytesPerSector;
148
+ const fatStart = g.reservedSectors * g.bytesPerSector;
149
+ const rootStart = fatStart + g.fatCount * fatBytes;
150
+ const dataStart = rootStart + rootSectors * g.bytesPerSector;
151
+ const clusterBytes = g.sectorsPerCluster * g.bytesPerSector;
152
+ const clusterCount = Math.floor((image.length - dataStart) / clusterBytes);
153
+
154
+ buildBootSector(options.label).copy(image, 0);
155
+
156
+ const fat = Buffer.alloc(fatBytes);
157
+ setFatEntry(fat, 0, 0xf00 | g.mediaDescriptor);
158
+ setFatEntry(fat, 1, 0xfff);
159
+
160
+ const entries = [];
161
+ if (options.label) {
162
+ const labelEntry = Buffer.alloc(ENTRY_SIZE);
163
+ labelEntry.write(options.label.toUpperCase().padEnd(11, ' ').slice(0, 11), 0, 'ascii');
164
+ labelEntry.writeUInt8(ATTR_VOLUME, 11);
165
+ entries.push(labelEntry);
166
+ }
167
+
168
+ let nextCluster = 2;
169
+ for (const file of files) {
170
+ const need = Math.max(1, Math.ceil(file.data.length / clusterBytes));
171
+ if (file.data.length > 0 && nextCluster - 2 + need > clusterCount) {
172
+ throw new FcdevError(`软盘空间不足,放不下:${file.name}`, { code: 'DISK_FULL' });
173
+ }
174
+ const entry = Buffer.alloc(ENTRY_SIZE);
175
+ entry.write(toShortName(file.name), 0, 'ascii');
176
+ entry.writeUInt8(0x20, 11);
177
+ const stamp = dosDateTime(file.mtime ?? new Date(1998, 0, 1));
178
+ entry.writeUInt16LE(stamp.time, 22);
179
+ entry.writeUInt16LE(stamp.date, 24);
180
+ entry.writeUInt32LE(file.data.length, 28);
181
+
182
+ if (file.data.length > 0) {
183
+ entry.writeUInt16LE(nextCluster, 26);
184
+ for (let index = 0; index < need; index += 1) {
185
+ const cluster = nextCluster + index;
186
+ setFatEntry(fat, cluster, index === need - 1 ? END_OF_CHAIN : cluster + 1);
187
+ file.data.subarray(index * clusterBytes, (index + 1) * clusterBytes).copy(image, dataStart + (cluster - 2) * clusterBytes);
188
+ }
189
+ nextCluster += need;
190
+ }
191
+ entries.push(entry);
192
+ }
193
+
194
+ if (entries.length > g.rootEntries) throw new FcdevError('根目录项过多', { code: 'DISK_FULL' });
195
+ entries.forEach((entry, index) => entry.copy(image, rootStart + index * ENTRY_SIZE));
196
+ for (let copy = 0; copy < g.fatCount; copy += 1) fat.copy(image, fatStart + copy * fatBytes);
197
+ return image;
198
+ }
199
+
200
+ /**
201
+ * 列出镜像根目录里的文件。
202
+ * @param {Buffer} image FAT12 镜像
203
+ * @returns {{name: string, size: number, startCluster: number}[]} 文件列表
204
+ */
205
+ export function listFat12(image) {
206
+ const g = GEOMETRY;
207
+ const rootStart = (g.reservedSectors + g.fatCount * g.sectorsPerFat) * g.bytesPerSector;
208
+ const result = [];
209
+ for (let index = 0; index < g.rootEntries; index += 1) {
210
+ const at = rootStart + index * ENTRY_SIZE;
211
+ const first = image[at];
212
+ if (first === 0x00) break;
213
+ if (first === 0xe5 || (image[at + 11] & ATTR_VOLUME) !== 0) continue;
214
+ result.push({
215
+ name: fromShortName(image.toString('ascii', at, at + 11)),
216
+ size: image.readUInt32LE(at + 28),
217
+ startCluster: image.readUInt16LE(at + 26),
218
+ });
219
+ }
220
+ return result;
221
+ }
222
+
223
+ /**
224
+ * 读取镜像中一个文件的内容。
225
+ * @param {Buffer} image FAT12 镜像
226
+ * @param {{size: number, startCluster: number}} entry listFat12 返回的目录项
227
+ * @returns {Buffer} 文件内容
228
+ */
229
+ export function readFat12File(image, entry) {
230
+ const g = GEOMETRY;
231
+ const fatStart = g.reservedSectors * g.bytesPerSector;
232
+ const fat = image.subarray(fatStart, fatStart + g.sectorsPerFat * g.bytesPerSector);
233
+ const dataStart = (g.reservedSectors + g.fatCount * g.sectorsPerFat) * g.bytesPerSector + g.rootEntries * ENTRY_SIZE;
234
+ const clusterBytes = g.sectorsPerCluster * g.bytesPerSector;
235
+ const chunks = [];
236
+ let cluster = entry.startCluster;
237
+ let remaining = entry.size;
238
+ while (remaining > 0 && cluster >= 2 && cluster < 0xff8) {
239
+ const start = dataStart + (cluster - 2) * clusterBytes;
240
+ chunks.push(image.subarray(start, start + Math.min(clusterBytes, remaining)));
241
+ remaining -= clusterBytes;
242
+ cluster = getFatEntry(fat, cluster);
243
+ }
244
+ return Buffer.concat(chunks);
245
+ }
@@ -0,0 +1,53 @@
1
+ // ------------------------------------------------------------------------
2
+ // 名称:flat-binary.mjs
3
+ // 说明:平铺映像打包器:校验链接输出的文件头与大小,写成目标要求的程序文件。
4
+ // 作者:sungbin
5
+ // 邮箱:sungbin@3578.cn
6
+ // 日期:2026-11-10
7
+ // 备注:选项 header 为十六进制字符串,?? 表示任意字节;maxSize 为映像大小上限(字节)。
8
+ // ------------------------------------------------------------------------
9
+ import { readFileSync, writeFileSync } from 'node:fs';
10
+ import { FcdevError } from '../shared/index.mjs';
11
+
12
+ /**
13
+ * 把十六进制模式拆成字节列表,null 表示通配。
14
+ * @param {string} pattern 如 "4C????AA55"
15
+ * @returns {(number|null)[]} 字节列表
16
+ * @throws {FcdevError} 模式不合法
17
+ */
18
+ export function parseHeaderPattern(pattern) {
19
+ if (typeof pattern !== 'string' || pattern.length % 2 !== 0 || !/^([0-9A-Fa-f]{2}|\?\?)*$/.test(pattern)) {
20
+ throw new FcdevError(`header 选项“${pattern}”不是合法的十六进制模式`, { code: 'PACKAGER_OPTION_INVALID' });
21
+ }
22
+ const bytes = [];
23
+ for (let index = 0; index < pattern.length; index += 2) {
24
+ const pair = pattern.slice(index, index + 2);
25
+ bytes.push(pair === '??' ? null : Number.parseInt(pair, 16));
26
+ }
27
+ return bytes;
28
+ }
29
+
30
+ /**
31
+ * 校验并写出平铺映像。
32
+ * @param {{binaryFile: string, outputFile: string, options: {header?: string, maxSize?: number}}} input 链接输出、产物路径与打包选项
33
+ * @returns {{outputFile: string, size: number}} 产物路径与大小
34
+ * @throws {FcdevError} 文件头不符或超过大小上限
35
+ */
36
+ export function packFlatBinary({ binaryFile, outputFile, options }) {
37
+ const image = readFileSync(binaryFile);
38
+ if (options.header !== undefined) {
39
+ const expected = parseHeaderPattern(options.header);
40
+ const matches = image.length >= expected.length && expected.every((byte, index) => byte === null || image[index] === byte);
41
+ if (!matches) {
42
+ throw new FcdevError(`程序文件头不符:应为 ${options.header},实际为 ${image.subarray(0, expected.length).toString('hex').toUpperCase()}`, {
43
+ code: 'PACKAGE_HEADER_MISMATCH',
44
+ hint: '检查启动代码是否放在映像最前面',
45
+ });
46
+ }
47
+ }
48
+ if (options.maxSize !== undefined && image.length > options.maxSize) {
49
+ throw new FcdevError(`程序大小 ${image.length} 字节,超过上限 ${options.maxSize} 字节`, { code: 'PACKAGE_TOO_LARGE' });
50
+ }
51
+ writeFileSync(outputFile, image);
52
+ return { outputFile, size: image.length };
53
+ }
@@ -0,0 +1,54 @@
1
+ // ------------------------------------------------------------------------
2
+ // 名称:index.mjs
3
+ // 说明:packagers 目录的对外入口:按名称取打包器。
4
+ // 作者:sungbin
5
+ // 邮箱:sungbin@3578.cn
6
+ // 日期:2026-11-10
7
+ // 备注:新增打包器时在 PACKAGERS 里登记;每个打包器接收 { binaryFile, outputFile, options } 并返回 { outputFile, size }。
8
+ // ------------------------------------------------------------------------
9
+ import { FcdevError } from '../shared/index.mjs';
10
+ import { packFatFloppy } from './fat-floppy.mjs';
11
+ import { packFlatBinary } from './flat-binary.mjs';
12
+ import { packInes } from './ines.mjs';
13
+
14
+ export { listFat12, readFat12File } from './fat12-image.mjs';
15
+ export { parseHeaderPattern } from './flat-binary.mjs';
16
+
17
+ /** 已登记的程序打包器 */
18
+ const PACKAGERS = {
19
+ 'flat-exe': packFlatBinary,
20
+ ines: packInes,
21
+ };
22
+
23
+ /** 已登记的磁盘打包器:输入一组文件,输出一个镜像 */
24
+ const DISK_PACKAGERS = {
25
+ 'fat-floppy': packFatFloppy,
26
+ };
27
+
28
+ /**
29
+ * 按名称取打包器。
30
+ * @param {string} name 打包器名
31
+ * @returns {(input: {binaryFile: string, outputFile: string, options: Record<string, unknown>}) => {outputFile: string, size: number}} 打包函数
32
+ * @throws {FcdevError} 打包器没有登记
33
+ */
34
+ export function getPackager(name) {
35
+ const packager = PACKAGERS[name];
36
+ if (!packager) {
37
+ throw new FcdevError(`未知的打包器:${name}`, { code: 'PACKAGER_UNKNOWN', hint: `可用的打包器:${Object.keys(PACKAGERS).join('、')}` });
38
+ }
39
+ return packager;
40
+ }
41
+
42
+ /**
43
+ * 按名称取磁盘打包器。
44
+ * @param {string} name 打包器名
45
+ * @returns {(input: {files: {name: string, data: Buffer, mtime?: Date}[], outputFile: string, options?: Record<string, unknown>}) => {outputFile: string, size: number}} 打包函数
46
+ * @throws {FcdevError} 打包器没有登记
47
+ */
48
+ export function getDiskPackager(name) {
49
+ const packager = DISK_PACKAGERS[name];
50
+ if (!packager) {
51
+ throw new FcdevError(`未知的磁盘打包器:${name}`, { code: 'PACKAGER_UNKNOWN', hint: `可用的磁盘打包器:${Object.keys(DISK_PACKAGERS).join('、')}` });
52
+ }
53
+ return packager;
54
+ }