@breinzhang/mivark 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,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,166 @@
1
- # Temporary Holding Version
1
+ <p align="center">
2
+ <img src="https://raw.githubusercontent.com/breinzhang/mivark/main/assets/brand/mivark-icon.png" alt="Mivark icon" width="96" height="96" />
3
+ </p>
2
4
 
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.
5
+ <h1 align="center">Mivark</h1>
6
+
7
+ <p align="center">
8
+ A local-first desktop Markdown and JSON editor with PDF and image viewing for macOS and Windows.
9
+ </p>
10
+
11
+ <p align="center">
12
+ <strong>English</strong> | <a href="https://github.com/breinzhang/mivark/blob/main/README.zh-CN.md">简体中文</a>
13
+ </p>
14
+
15
+ <p align="center">
16
+ <a href="https://github.com/breinzhang/mivark/blob/main/LICENSE"><img src="https://img.shields.io/badge/License-Apache--2.0-blue.svg" alt="License: Apache-2.0" /></a>
17
+ <img src="https://img.shields.io/badge/Platform-macOS%20%7C%20Windows-lightgrey.svg" alt="Platform: macOS | Windows" />
18
+ <img src="https://img.shields.io/badge/Built%20with-Tauri%202%20%2B%20React%20%2B%20Rust-orange.svg" alt="Built with Tauri 2, React, and Rust" />
19
+ </p>
20
+
21
+ ---
22
+
23
+ ## Features
24
+
25
+ - **Markdown Editing (Three Modes)**
26
+ - Switch seamlessly between **Rich (WYSIWYG)**, **Reader**, and **Source** modes while preserving a single canonical Markdown text state.
27
+ - Built-in **round-trip fidelity guard**: when a document contains syntax that rich editing cannot safely preserve, Mivark automatically keeps it in Source mode so your original bytes are never silently rewritten.
28
+ - Supports GitHub Flavored Markdown (GFM), Mermaid diagrams, slash commands, and light and dark themes.
29
+ - **Safe saving**: manual save by default (optional auto-save in Settings), disk modification conflict detection before writing, and atomic file replacement.
30
+ - **JSON Editor**
31
+ - Edit and save text in the syntax-highlighted **Raw** view, with find and replace. Switch to **Visual** to read the current buffer as an expandable tree with indented fields and values.
32
+ - Visual mode parses up to 8 MiB in a Web Worker and pages large branches. Files larger than 32 MiB open in a paged preview.
33
+ - **Image Viewer**
34
+ - View **PNG, JPEG, WebP, GIF, BMP, and SVG** files with zoom and fit-to-window controls.
35
+ - **PDF Viewer (Read-Only)**
36
+ - Read local PDFs up to 128 MiB with continuous scrolling, outline or thumbnail navigation, and zoom.
37
+ - **Desktop Workflow**
38
+ - Multi-tab workspace, folder explorer sidebar, drag-and-drop file opening, OS file associations, and single-instance window focus.
39
+
40
+ ## Security & Privacy
41
+
42
+ - **100% local-first**: works completely offline with no account or telemetry.
43
+ - **Untrusted content isolation**: Markdown, JSON, and SVG files are treated as untrusted — embedded scripts are never executed and remote resources referenced in Markdown are never loaded automatically.
44
+ - **Explicit file access**: filesystem operations are scoped through Tauri's Rust backend allowlist and explicit user actions.
45
+
46
+ ## Installation
47
+
48
+ ### 1. GitHub Releases (Recommended)
49
+
50
+ Download the prebuilt installer for your platform from [GitHub Releases](https://github.com/breinzhang/mivark/releases):
51
+
52
+ | Platform | Package |
53
+ | --- | --- |
54
+ | macOS (Apple Silicon — M1/M2/M3/M4) | `Mivark-<version>-darwin-arm64.dmg` |
55
+ | macOS (Intel) | `Mivark-<version>-darwin-x64.dmg` |
56
+ | Windows (x64) | `Mivark-<version>-win32-x64-setup.exe` (installer) or `Mivark-<version>-win32-x64.exe` (portable) |
57
+
58
+ Every release includes `SHA256SUMS.txt` for verifying download integrity.
59
+
60
+ ### 2. npm CLI Launcher (macOS & Windows, Offline-Ready)
61
+
62
+ If published to npm under a maintainer scope, you can install the precompiled desktop launcher globally (requires **Node.js 20+**; no Rust compilation and no runtime downloads from GitHub):
63
+
64
+ ```sh
65
+ npm install -g @breinzhang/mivark
66
+ mivark --version
67
+ mivark /path/to/README.md
68
+ ```
69
+
70
+ ### 3. Homebrew Cask (macOS)
71
+
72
+ If published to a Homebrew Tap:
73
+
74
+ ```sh
75
+ brew install --cask breinzhang/mivark/mivark
76
+ ```
77
+
78
+ ### First-Launch Notice (Unsigned / Ad-hoc Builds)
79
+
80
+ If a release is distributed without a paid Apple Developer ID or Windows Authenticode certificate:
81
+
82
+ - **macOS**: After dragging `Mivark.app` into `/Applications`, if macOS blocks the first launch, open **System Settings → Privacy & Security**, scroll down to Security, and click **Open Anyway**. If newer macOS versions report that the app "is damaged and can't be opened", clear the quarantine attribute once in Terminal:
83
+ ```sh
84
+ xattr -cr /Applications/Mivark.app
85
+ ```
86
+ - **Windows**: If Windows SmartScreen appears, click **More info → Run anyway**.
87
+
88
+ ## Build from Source
89
+
90
+ ### Prerequisites
91
+
92
+ - **Node.js** `22.13+` (with `npm`)
93
+ - **Rust** stable toolchain (`rustup`, `cargo`)
94
+ - Platform-specific [Tauri 2 prerequisites](https://v2.tauri.app/start/prerequisites/)
95
+
96
+ ### Development
97
+
98
+ ```sh
99
+ npm ci
100
+ npm run tauri dev
101
+ ```
102
+
103
+ ### Production Bundle
104
+
105
+ ```sh
106
+ npm run tauri build
107
+ ```
108
+
109
+ Generated installers and application bundles are written to `src-tauri/target/release/bundle/`.
110
+
111
+ ## Testing & Validation
112
+
113
+ Run the full verification suite locally:
114
+
115
+ ```sh
116
+ npm run typecheck
117
+ npm run lint
118
+ npm run format:check
119
+ npm run test:unit
120
+ npm run test:integration
121
+ npm run test:launcher
122
+ cargo test --manifest-path src-tauri/Cargo.toml
123
+ ```
124
+
125
+ ### Web End-to-End Tests (Playwright)
126
+
127
+ Before the first run, generate test fixtures and install Chromium:
128
+
129
+ ```sh
130
+ npm run fixtures:generate
131
+ npx playwright install chromium
132
+ npm run test:e2e:web
133
+ ```
134
+
135
+ ## Tech Stack
136
+
137
+ - **Desktop Shell & Backend**: [Tauri 2](https://v2.tauri.app/) (Rust)
138
+ - **Frontend**: React 19, TypeScript, Vite, Zustand
139
+ - **Editors & Viewers**: Milkdown Crepe (WYSIWYG), CodeMirror 6 (Source & JSON Raw), `react-markdown` + `remark-gfm` (Reader), Mermaid, `@tanstack/react-virtual` (JSON & PDF), DOMPurify
140
+
141
+ ## Release Automation
142
+
143
+ When automated publishing is enabled on `main`, pushing a version-bump commit triggers [.github/workflows/release.yml](https://github.com/breinzhang/mivark/blob/main/.github/workflows/release.yml) to build macOS Apple Silicon, macOS Intel, and Windows x64 from the same commit and distribute them to GitHub Releases, npm, and Homebrew Tap.
144
+
145
+ - Sync versions across npm, Cargo, and Tauri configs with:
146
+ ```sh
147
+ npm run release:version -- X.Y.Z
148
+ ```
149
+ - Maintainers can run the **Release** workflow manually via `workflow_dispatch` with `publish` unchecked to test cross-platform builds and download the `distribution` artifact without publishing.
150
+ - Apple Developer ID signing/notarization and Windows Authenticode signing are both optional: leave their secrets unset for ad-hoc / unsigned builds, or configure them to enable signed releases.
151
+
152
+ ## Contributing
153
+
154
+ Issues and Pull Requests are welcome! When reporting a bug, please include:
155
+
156
+ - Mivark version and operating system (including CPU architecture)
157
+ - Clear reproduction steps
158
+ - A minimal, non-sensitive sample file if applicable
159
+
160
+ Please run the [Testing & Validation](#testing--validation) checks before submitting a Pull Request.
161
+
162
+ ## License
163
+
164
+ Mivark is licensed under the [Apache License 2.0](https://github.com/breinzhang/mivark/blob/main/LICENSE).
165
+
166
+ Bundled third-party components retain their respective licenses and copyright notices; see [THIRD_PARTY_NOTICES.txt](https://github.com/breinzhang/mivark/blob/main/public/THIRD_PARTY_NOTICES.txt) and `vendor/`.
@@ -0,0 +1,52 @@
1
+ micromark-util-edit-map 1.0.0 (Mivark performance patch)
2
+ ========================================================
3
+
4
+ (The MIT License)
5
+
6
+ Copyright (c) Titus Wormer <tituswormer@gmail.com>
7
+
8
+ Permission is hereby granted, free of charge, to any person obtaining
9
+ a copy of this software and associated documentation files (the
10
+ 'Software'), to deal in the Software without restriction, including
11
+ without limitation the rights to use, copy, modify, merge, publish,
12
+ distribute, sublicense, and/or sell copies of the Software, and to
13
+ permit persons to whom the Software is furnished to do so, subject to
14
+ the following conditions:
15
+
16
+ The above copyright notice and this permission notice shall be
17
+ included in all copies or substantial portions of the Software.
18
+
19
+ THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
20
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
21
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
22
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
23
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
24
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
25
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
26
+
27
+
28
+ @milkdown/transformer 7.23.0 (Mivark performance patch)
29
+ =======================================================
30
+
31
+ The MIT License (MIT)
32
+
33
+ Copyright (c) 2020-present Mirone
34
+
35
+ Permission is hereby granted, free of charge, to any person obtaining a copy
36
+ of this software and associated documentation files (the "Software"), to deal
37
+ in the Software without restriction, including without limitation the rights
38
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
39
+ copies of the Software, and to permit persons to whom the Software is
40
+ furnished to do so, subject to the following conditions:
41
+
42
+ The above copyright notice and this permission notice shall be included in all
43
+ copies or substantial portions of the Software.
44
+
45
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
46
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
47
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
48
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
49
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
50
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
51
+ SOFTWARE.
52
+
package/bin/mivark.mjs ADDED
@@ -0,0 +1,152 @@
1
+ #!/usr/bin/env node
2
+ // Mivark CLI launcher responsibilities:
3
+ // --version / --help without starting the GUI
4
+ // platform resolution → optional platform package → payload verification
5
+ // macOS: unpack .app.zip into a versioned cache, codesign check, `open -a`
6
+ // Windows: spawn the precompiled Mivark.exe directly
7
+ // The CLI NEVER downloads anything from the network.
8
+ import { createRequire } from 'node:module';
9
+ import { existsSync, readFileSync } from 'node:fs';
10
+ import { homedir } from 'node:os';
11
+ import path from 'node:path';
12
+ import process from 'node:process';
13
+ import { launchDetached, prepareMacCache, runChecked, sha256File } from './runtime.mjs';
14
+
15
+ const {
16
+ name: cliName,
17
+ version: CLI_VERSION,
18
+ optionalDependencies,
19
+ } = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
20
+
21
+ const fail = (msg, code = 1) => {
22
+ console.error(`mivark: ${msg}`);
23
+ process.exit(code);
24
+ };
25
+
26
+ const args = process.argv.slice(2);
27
+ const flagArgs = args.slice(0, args.indexOf('--') < 0 ? args.length : args.indexOf('--'));
28
+
29
+ if (flagArgs.includes('--help') || flagArgs.includes('-h')) {
30
+ console.log(`mivark ${CLI_VERSION} — Mivark 桌面应用启动器
31
+
32
+ 用法:
33
+ mivark [--version] [--help]
34
+ mivark <文件路径...> 启动/聚焦 Mivark 并打开文件(支持 .md/.json/图片)
35
+
36
+ 说明:
37
+ - npm 包只负责启动预编译的桌面程序;不包含也不执行 Rust 编译。
38
+ - 首次运行会把平台包内的应用解包到本地缓存目录(macOS),之后离线可用。
39
+ - 支持 --ignore-scripts 安装;不要使用 --omit=optional,否则可能缺少平台包。`);
40
+ process.exit(0);
41
+ }
42
+
43
+ if (flagArgs.includes('--version') || flagArgs.includes('-V')) {
44
+ // Keep --version offline and cheap: report the CLI version; the desktop
45
+ // bundle version is verified at launch time against the payload manifest.
46
+ console.log(`mivark ${CLI_VERSION}`);
47
+ process.exit(0);
48
+ }
49
+
50
+ // ---------- platform resolution ----------
51
+ const platform = process.platform; // darwin | win32 | ...
52
+ const arch = process.arch; // arm64 | x64
53
+ const key = `${platform}-${arch}`;
54
+ const pkgName = Object.keys(optionalDependencies).find((name) => name.endsWith(`/mivark-${key}`));
55
+ if (!pkgName) {
56
+ fail(`不支持的平台 ${key}。支持: darwin-arm64, darwin-x64, win32-x64。`, 1);
57
+ }
58
+
59
+ // Resolve the platform package robustly: normal install layout first
60
+ // (relative to this file), then the invoking cwd (covers file:/symlinked
61
+ // development installs where import.meta.url is realpath'ed away).
62
+ const resolvers = [
63
+ createRequire(import.meta.url),
64
+ createRequire(path.join(process.cwd(), 'noop.js')),
65
+ ];
66
+ let payloadDir;
67
+ let resolveErr;
68
+ try {
69
+ let resolved;
70
+ for (const req of resolvers) {
71
+ try {
72
+ resolved = req.resolve(`${pkgName}/package.json`);
73
+ break;
74
+ } catch (e) {
75
+ resolveErr = e;
76
+ }
77
+ }
78
+ if (!resolved) throw resolveErr ?? new Error('MODULE_NOT_FOUND');
79
+ payloadDir = path.join(path.dirname(resolved), 'payload');
80
+ } catch (err) {
81
+ fail(
82
+ `缺少平台包 ${pkgName}(错误: ${err instanceof Error ? (err.code ?? err.message) : String(err)})。
83
+ 修复方式:
84
+ npm install -g ${cliName}@${CLI_VERSION}
85
+ # 或显式安装平台包: npm install -g ${pkgName}@${CLI_VERSION}
86
+ # 注意: 不要使用 --omit=optional 安装。`,
87
+ 1,
88
+ );
89
+ }
90
+
91
+ const manifestPath = path.join(payloadDir, 'manifest.json');
92
+ if (!existsSync(manifestPath)) {
93
+ fail(`平台包不完整: 未找到 ${manifestPath}。请重新安装 ${pkgName}。`, 1);
94
+ }
95
+ let manifest;
96
+ try {
97
+ manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
98
+ } catch {
99
+ fail(`平台包 manifest.json 损坏。请重新安装 ${pkgName}。`, 1);
100
+ }
101
+
102
+ if (manifest.version !== CLI_VERSION) {
103
+ fail(
104
+ `版本不一致: CLI ${CLI_VERSION} vs 平台包 ${pkgName} ${manifest.version}。请统一重装两个包。`,
105
+ 1,
106
+ );
107
+ }
108
+ if (manifest.platform !== platform || manifest.arch !== arch) {
109
+ fail(`平台包架构不匹配: 期望 ${key},实际 ${manifest.platform}-${manifest.arch}。`, 1);
110
+ }
111
+
112
+ async function verifyArtifact(file, expectedSha) {
113
+ const actual = await sha256File(file);
114
+ if (actual !== expectedSha) {
115
+ fail(
116
+ `完整性校验失败: ${path.basename(file)}\n 期望 SHA-256: ${expectedSha}\n 实际 SHA-256: ${actual}\n请重新安装 ${pkgName};不要绕过校验。`,
117
+ 1,
118
+ );
119
+ }
120
+ }
121
+
122
+ // Reject unknown options; `--` permits filenames beginning with a dash.
123
+ const separator = args.indexOf('--');
124
+ const options = separator < 0 ? args : args.slice(0, separator);
125
+ if (options.some((arg) => arg.startsWith('-')))
126
+ fail('未知选项。使用 --help 查看用法;以 - 开头的路径请放在 -- 后。');
127
+ const fileArgs = (separator < 0 ? args : [...options, ...args.slice(separator + 1)]).map((file) =>
128
+ path.resolve(file),
129
+ );
130
+ const expectedArtifact = platform === 'darwin' ? 'Mivark.app.zip' : 'Mivark.exe';
131
+ if (manifest.artifact !== expectedArtifact || !/^[a-f0-9]{64}$/.test(manifest.sha256)) {
132
+ fail('平台包 manifest 的 artifact 或 SHA-256 无效,请重新安装。');
133
+ }
134
+
135
+ try {
136
+ if (platform === 'darwin') {
137
+ const appPath = await prepareMacCache({
138
+ zipPath: path.join(payloadDir, expectedArtifact),
139
+ cacheBase: path.join(homedir(), 'Library', 'Application Support', 'Mivark', 'npm'),
140
+ manifest,
141
+ });
142
+ // Wait for LaunchServices acceptance, not for the long-lived GUI to exit.
143
+ runChecked('open', ['-a', appPath, ...(fileArgs.length ? ['--args', ...fileArgs] : [])]);
144
+ } else {
145
+ const exePath = path.join(payloadDir, expectedArtifact);
146
+ await verifyArtifact(exePath, manifest.sha256);
147
+ // Success means OS process creation, not GUI readiness/WebView2 availability.
148
+ await launchDetached(exePath, fileArgs);
149
+ }
150
+ } catch (error) {
151
+ fail(error instanceof Error ? error.message : String(error));
152
+ }
@@ -0,0 +1,151 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { spawn, spawnSync } from 'node:child_process';
3
+ import { createReadStream } from 'node:fs';
4
+ import {
5
+ lstat,
6
+ mkdir,
7
+ mkdtemp,
8
+ readFile,
9
+ readdir,
10
+ readlink,
11
+ rename,
12
+ rm,
13
+ writeFile,
14
+ } from 'node:fs/promises';
15
+ import path from 'node:path';
16
+ import { setTimeout as delay } from 'node:timers/promises';
17
+
18
+ export async function sha256File(file) {
19
+ const hash = createHash('sha256');
20
+ for await (const chunk of createReadStream(file)) hash.update(chunk);
21
+ return hash.digest('hex');
22
+ }
23
+
24
+ // Include names, modes and symlink targets, without following bundle symlinks.
25
+ export async function bundleDigest(root) {
26
+ const hash = createHash('sha256');
27
+ async function visit(relative) {
28
+ const file = path.join(root, relative);
29
+ const stat = await lstat(file);
30
+ hash.update(JSON.stringify([relative, stat.mode]));
31
+ if (stat.isSymbolicLink()) hash.update(JSON.stringify(await readlink(file)));
32
+ else if (stat.isDirectory()) {
33
+ for (const name of (await readdir(file)).sort()) await visit(path.join(relative, name));
34
+ } else if (stat.isFile()) hash.update(await sha256File(file));
35
+ else throw new Error('应用缓存包含不支持的文件类型。');
36
+ }
37
+ if (!(await lstat(root)).isDirectory()) throw new Error('应用缓存不是目录。');
38
+ await visit('');
39
+ return hash.digest('hex');
40
+ }
41
+
42
+ export function runChecked(command, args) {
43
+ const result = spawnSync(command, args, { encoding: 'utf8', timeout: 120_000 });
44
+ if (result.error || result.status !== 0) {
45
+ throw new Error(
46
+ `${command} 失败: ${result.error?.message ?? result.stderr?.trim() ?? result.status}`,
47
+ );
48
+ }
49
+ }
50
+
51
+ export async function withCacheLock(lock, action, timeoutMs = 30_000) {
52
+ const start = Date.now();
53
+ for (;;) {
54
+ try {
55
+ await mkdir(lock);
56
+ break;
57
+ } catch (error) {
58
+ if (error.code !== 'EEXIST') throw error;
59
+ if (Date.now() - start >= timeoutMs) {
60
+ throw new Error(
61
+ `等待缓存锁超时: ${lock}。确认其他 mivark 启动器已退出后,删除此锁目录再重试。`,
62
+ );
63
+ }
64
+ await delay(100);
65
+ }
66
+ }
67
+ try {
68
+ await writeFile(
69
+ path.join(lock, 'owner.json'),
70
+ JSON.stringify({ pid: process.pid, at: Date.now() }),
71
+ );
72
+ return await action();
73
+ } finally {
74
+ await rm(lock, { recursive: true, force: true });
75
+ }
76
+ }
77
+
78
+ export async function prepareMacCache({
79
+ zipPath,
80
+ cacheBase,
81
+ manifest,
82
+ run = runChecked,
83
+ renameCache = rename,
84
+ }) {
85
+ if (!/^[a-f0-9]{64}$/.test(manifest.sha256)) throw new Error('无效的 payload SHA-256。');
86
+ if ((await sha256File(zipPath)) !== manifest.sha256)
87
+ throw new Error('平台包完整性校验失败,请重新安装。');
88
+ // Content identity prevents same-version builds from reusing stale applications.
89
+ const cacheRoot = path.join(cacheBase, `${manifest.version}-${manifest.arch}-${manifest.sha256}`);
90
+ await mkdir(cacheBase, { recursive: true });
91
+ return withCacheLock(`${cacheRoot}.lock`, async () => {
92
+ const app = path.join(cacheRoot, 'Mivark.app');
93
+ try {
94
+ const stamp = JSON.parse(await readFile(path.join(cacheRoot, '.unpacked-ok'), 'utf8'));
95
+ if (stamp.sha256 === manifest.sha256 && stamp.digest === (await bundleDigest(app))) {
96
+ run('codesign', ['--verify', '--deep', '--strict', app]);
97
+ return app;
98
+ }
99
+ } catch {
100
+ // Rebuild damaged/old caches exclusively from the verified local payload.
101
+ }
102
+ const stage = await mkdtemp(path.join(cacheBase, '.mivark-stage-'));
103
+ let backup;
104
+ let cleanupBackup = false;
105
+ try {
106
+ run('ditto', ['-x', '-k', zipPath, stage]);
107
+ const extracted = path.join(stage, 'Mivark.app');
108
+ run('codesign', ['--verify', '--deep', '--strict', extracted]);
109
+ const digest = await bundleDigest(extracted);
110
+ await writeFile(
111
+ path.join(stage, '.unpacked-ok'),
112
+ JSON.stringify({ sha256: manifest.sha256, digest }),
113
+ );
114
+ // Stage on the same filesystem. Keep the previous cache until promotion succeeds.
115
+ try {
116
+ await lstat(cacheRoot);
117
+ backup = await mkdtemp(path.join(cacheBase, '.mivark-old-'));
118
+ await renameCache(cacheRoot, path.join(backup, 'cache'));
119
+ } catch (error) {
120
+ if (error.code !== 'ENOENT') throw error;
121
+ }
122
+ try {
123
+ await renameCache(stage, cacheRoot);
124
+ } catch (error) {
125
+ if (backup) await renameCache(path.join(backup, 'cache'), cacheRoot);
126
+ cleanupBackup = true;
127
+ throw error;
128
+ }
129
+ cleanupBackup = true;
130
+ return app;
131
+ } finally {
132
+ await rm(stage, { recursive: true, force: true });
133
+ if (backup && cleanupBackup) await rm(backup, { recursive: true, force: true });
134
+ }
135
+ });
136
+ }
137
+
138
+ export async function launchDetached(executable, args, spawnProcess = spawn) {
139
+ await new Promise((resolve, reject) => {
140
+ const child = spawnProcess(executable, args, {
141
+ detached: true,
142
+ stdio: 'ignore',
143
+ windowsHide: true,
144
+ });
145
+ child.once('error', reject);
146
+ child.once('spawn', () => {
147
+ child.unref();
148
+ resolve();
149
+ });
150
+ });
151
+ }
package/package.json CHANGED
@@ -1,6 +1,27 @@
1
1
  {
2
2
  "name": "@breinzhang/mivark",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Mivark desktop launcher — starts the precompiled Mivark.app / Mivark.exe",
5
+ "bin": {
6
+ "mivark": "bin/mivark.mjs"
7
+ },
8
+ "type": "module",
9
+ "engines": {
10
+ "node": ">=20"
11
+ },
12
+ "optionalDependencies": {
13
+ "@breinzhang/mivark-darwin-arm64": "0.1.1",
14
+ "@breinzhang/mivark-darwin-x64": "0.1.1",
15
+ "@breinzhang/mivark-win32-x64": "0.1.1"
16
+ },
17
+ "files": [
18
+ "bin/",
19
+ "README.md",
20
+ "THIRD_PARTY_NOTICES.txt"
21
+ ],
22
+ "license": "Apache-2.0",
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "git+https://github.com/breinzhang/mivark.git"
26
+ }
27
+ }