@bitefoundry/onenote 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,132 @@
1
- # Temporary Holding Version
1
+ <div align="center">
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
+ # `@bitefoundry/onenote`
4
+
5
+ **Keyboard-first Microsoft OneNote terminal client, CLI, HTTP API, and MCP server — powered by Rust, Ratatui, and local SQLite FTS5.**
6
+
7
+ [![npm version](https://img.shields.io/npm/v/%40bitefoundry%2Fonenote?style=flat-square&color=7719AA&label=npm)](https://www.npmjs.com/package/@bitefoundry/onenote)
8
+ [![Platforms](https://img.shields.io/badge/platforms-Windows%20%7C%20macOS%20%7C%20Linux-2b3137?style=flat-square)](docs/NPM.md)
9
+ [![Built with Rust & Ratatui](https://img.shields.io/badge/built%20with-Rust%20%2B%20Ratatui-dea584?style=flat-square)](Cargo.toml)
10
+ [![License: MIT](https://img.shields.io/badge/license-MIT-3fb950?style=flat-square)](package.json)
11
+
12
+ <br />
13
+
14
+ ![Microsoft OneNote TUI Demo](assets/demo.gif)
15
+
16
+ </div>
17
+
18
+ ---
19
+
20
+ ## Highlights
21
+
22
+ | Capability | Details |
23
+ | --- | --- |
24
+ | **Minimal-Chrome 3-Pane TUI** | Personal, Teams/Group & SharePoint notebooks, colored section ribbon, nested subpages (`level 0/1/2`), bidirectional XHTML ↔ Markdown canvas, surgical `data-id` `PATCH` edits, `0ms` optimistic to-do toggles, Link Extractor (`u`), File Picker with `zoxide` (`Ctrl+F`), and 6 themes. |
25
+ | **High-Res Terminal Images** | Inline thumbnails & fullscreen HD previews (`v` / `Alt+v`) with 80ms protocol probing for **Kitty**, **iTerm2**, **Sixel** (Floyd-Steinberg dithering), and **24-bit Unicode Half-Blocks** + `Ctrl+V` clipboard PNG upload. |
26
+ | **Local SQLite FTS5 + IPC Daemon** | WAL-mode SQLite cache with 4-reader pool, trigram full-text search (`/`), persistent `DraftStore`, and a shared background sync daemon (`onenote daemon start`). |
27
+ | **4-in-1 Agent Interface** | Interactive **TUI** (`onenote` / `note`), scriptable `--json` **CLI**, local **HTTP JSON API** (`onenote serve`, port `8788`), and stdio **MCP Server** (`onenote mcp`, 14 tools). |
28
+
29
+ ---
30
+
31
+ ## Quick Start
32
+
33
+ ```sh
34
+ # 1. Install globally via npm (precompiled native binary for win32 / darwin / linux)
35
+ npm i -g @bitefoundry/onenote
36
+
37
+ # 2. Authenticate with Microsoft 365 (PKCE loopback, --device-code, or --token-file)
38
+ onenote login
39
+
40
+ # 3. Launch the interactive TUI (or use the short alias `note`)
41
+ onenote
42
+ ```
43
+
44
+ > Required Microsoft Graph delegated scopes: `Notes.Read`, `Notes.ReadWrite`, `Notes.Create`, `User.Read`, `offline_access`.
45
+ > Prefer building from source? Run `cargo build --release` and see [docs/NPM.md](docs/NPM.md) for external token brokers & environment variables.
46
+
47
+ ---
48
+
49
+ ## Keybindings Cheat Sheet
50
+
51
+ | Key | Action |
52
+ | --- | --- |
53
+ | `Tab` / `Shift+Tab` | Cycle focus (Notebooks → Pages → Note Canvas) |
54
+ | `j` / `k` · `↑` / `↓` | Navigate notebooks, pages, subpages, or blocks |
55
+ | `[` / `]` | Switch to previous / next section tab |
56
+ | `n` / `N` | Create new page / subpage (Markdown + `Ctrl+V` PNG) |
57
+ | `a` / `e` | Append Markdown block / surgically edit selected block |
58
+ | `Space` / `x` | Toggle selected To-Do checkbox (`data-tag="to-do:completed"`) |
59
+ | `B` / `S` / `D` | Create notebook / create section / delete page |
60
+ | `u` / `h` | Open Link Extractor modal / toggle inline `href` URLs |
61
+ | `v` / `o` / `y` | HD image preview / open in browser / copy page Markdown |
62
+ | `Ctrl+F` | Interactive File Picker (`z` for `zoxide` directory jump) |
63
+ | `/` | Instant full-text search across cached pages (SQLite FTS5) |
64
+ | `Ctrl+P` / `Ctrl+K` | Unified Command Palette & Omni-Switcher |
65
+ | `.` / Right-click | Context Menu |
66
+ | `Ctrl+,` / `Ctrl+B` / `?` | Settings / Toggle sidebar / Keyboard shortcuts help |
67
+
68
+ ---
69
+
70
+ ## CLI, HTTP API & MCP
71
+
72
+ ### CLI (`--json` on every command)
73
+
74
+ ```sh
75
+ onenote notebooks --json
76
+ onenote pages "Acme Engineering/Architecture" --json
77
+ onenote read "Q4 Architecture RFC" --json
78
+ onenote create "Architecture" "Release Notes" --body "## Shipped\n- [x] WAL pool" --json
79
+ onenote check "Migration Cutover" "p:m3" --done --json
80
+ onenote search "canary" --json
81
+ ```
82
+
83
+ ### Local HTTP API (`onenote serve`)
84
+
85
+ ```sh
86
+ # Start local Axum JSON server (default 127.0.0.1:8788)
87
+ onenote serve --bind 127.0.0.1:8788 --token dev-secret
88
+
89
+ # Query pages & FTS5 search from scripts or agents
90
+ curl -H "Authorization: Bearer dev-secret" \
91
+ "http://127.0.0.1:8788/v1/onenote/search?q=canary&limit=10"
92
+ ```
93
+
94
+ Full route reference & OpenAPI 3.1 spec: [docs/API.md](docs/API.md) · [docs/openapi.yaml](docs/openapi.yaml).
95
+
96
+ ### Model Context Protocol (`onenote mcp`)
97
+
98
+ Add to Claude Desktop, Claude Code, Cursor, or Codex (`14` tools over stdio JSON-RPC 2.0):
99
+
100
+ ```json
101
+ {
102
+ "mcpServers": {
103
+ "onenote": {
104
+ "command": "onenote",
105
+ "args": ["mcp"]
106
+ }
107
+ }
108
+ }
109
+ ```
110
+
111
+ Full tool catalog & schemas: [docs/MCP.md](docs/MCP.md).
112
+
113
+ ---
114
+
115
+ ## `@bitefoundry` Enterprise Terminal Suite
116
+
117
+ | Package | Commands | Workspace Coverage |
118
+ | --- | --- | --- |
119
+ | [`@bitefoundry/teams`](https://www.npmjs.com/package/@bitefoundry/teams) | `teams`, `tm` | Microsoft Teams chats, channels, threads & meetings |
120
+ | [`@bitefoundry/outlook`](https://www.npmjs.com/package/@bitefoundry/outlook) | `outlook`, `mail`, `cal` | Microsoft Outlook mail, calendar & contacts |
121
+ | **`@bitefoundry/onenote`** | `onenote`, `note` | Microsoft OneNote notebooks, sections, pages & XHTML/Markdown |
122
+ | [`@bitefoundry/sharepoint`](https://www.npmjs.com/package/@bitefoundry/sharepoint) | `sharepoint`, `sp`, `onedrive`, `od` | Microsoft SharePoint sites, document libraries & OneDrive files |
123
+ | [`@bitefoundry/atlassian`](https://www.npmjs.com/package/@bitefoundry/atlassian) | `atlassian`, `jira`, `confluence` | Atlassian Jira issues, boards, sprints & Confluence pages |
124
+ | [`@bitefoundry/notion`](https://www.npmjs.com/package/@bitefoundry/notion) | `notion`, `nt` | Notion pages, databases, blocks & Markdown sync |
125
+
126
+ ---
127
+
128
+ ## License & Disclaimer
129
+
130
+ Licensed under the **MIT License**.
131
+
132
+ > Unofficial terminal client for Microsoft OneNote. Not affiliated with, endorsed by, or sponsored by Microsoft Corporation.
package/bin/note.js ADDED
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ require('./onenote.js');
package/bin/onenote.js ADDED
@@ -0,0 +1,99 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const fs = require('node:fs');
5
+ const os = require('node:os');
6
+ const path = require('node:path');
7
+ const { spawn } = require('node:child_process');
8
+
9
+ const SUPPORTED = [
10
+ 'win32-x64',
11
+ 'win32-arm64',
12
+ 'darwin-x64',
13
+ 'darwin-arm64',
14
+ 'linux-x64',
15
+ 'linux-arm64',
16
+ ];
17
+
18
+ function fail(message) {
19
+ process.stderr.write(`onenote: ${message}\n`);
20
+ process.exit(1);
21
+ }
22
+
23
+ const platform = process.platform;
24
+ const arch = process.arch;
25
+ const platformKey = `${platform}-${arch}`;
26
+ const packageName = `@bitefoundry/onenote-${platformKey}`;
27
+ const binaryName = platform === 'win32' ? 'onenote.exe' : 'onenote';
28
+
29
+ let packageDir = null;
30
+ try {
31
+ packageDir = path.dirname(require.resolve(`${packageName}/package.json`));
32
+ } catch {
33
+ packageDir = null;
34
+ }
35
+
36
+ const binaryPath = packageDir ? path.join(packageDir, 'bin', binaryName) : null;
37
+
38
+ if (!binaryPath || !fs.existsSync(binaryPath)) {
39
+ const lines = [
40
+ `no prebuilt binary found for ${platformKey}.`,
41
+ '',
42
+ `Expected the optional dependency "${packageName}" to provide:`,
43
+ ` ${binaryPath || `node_modules/${packageName}/bin/${binaryName}`}`,
44
+ '',
45
+ `Supported platforms: ${SUPPORTED.join(', ')}`,
46
+ '',
47
+ 'Try one of:',
48
+ ' npm install -g @bitefoundry/onenote --include=optional',
49
+ ' npm install @bitefoundry/onenote --include=optional',
50
+ ' npx --yes @bitefoundry/onenote',
51
+ '',
52
+ 'If you are on an unsupported platform (for example Alpine/musl Linux),',
53
+ 'build from source with Cargo:',
54
+ ' cargo build --release',
55
+ ];
56
+ fail(lines.join('\n'));
57
+ }
58
+
59
+ if (platform !== 'win32') {
60
+ try {
61
+ fs.chmodSync(binaryPath, 0o755);
62
+ } catch {
63
+ // Read-only install; spawn will report EACCES if the bit is missing.
64
+ }
65
+ }
66
+
67
+ const child = spawn(binaryPath, process.argv.slice(2), {
68
+ stdio: 'inherit',
69
+ windowsHide: false,
70
+ });
71
+
72
+ child.on('error', (err) => {
73
+ fail(`failed to launch ${binaryPath}: ${err.message}`);
74
+ });
75
+
76
+ for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) {
77
+ const handler = () => {
78
+ if (!child.killed) {
79
+ try {
80
+ child.kill(signal);
81
+ } catch {
82
+ // Child already exited.
83
+ }
84
+ }
85
+ };
86
+ try {
87
+ process.on(signal, handler);
88
+ } catch {
89
+ // Signal not supported on this platform.
90
+ }
91
+ }
92
+
93
+ child.on('exit', (code, signal) => {
94
+ if (signal) {
95
+ const number = os.constants.signals[signal] || 1;
96
+ process.exit(128 + number);
97
+ }
98
+ process.exit(code === null ? 1 : code);
99
+ });
package/docs/NPM.md ADDED
@@ -0,0 +1,142 @@
1
+ # npm distribution
2
+
3
+ `@bitefoundry/onenote` is distributed on npm as a small JavaScript launcher plus one
4
+ optional dependency per platform. The launcher resolves the prebuilt Rust binary
5
+ and execs it directly (with `scripts/postinstall.mjs` linking the native binary
6
+ into `bin/` and Windows shims for zero-Node-startup execution), so there is no
7
+ compiler, Node native addon, or network download during install.
8
+
9
+ The Rust crate is named `onenote-cli` and produces the standalone **Microsoft OneNote**
10
+ binary (`onenote` / `onenote.exe`). The npm package is scoped as `@bitefoundry/onenote`
11
+ and installs both **`onenote`** and the short alias **`note`**.
12
+
13
+ ## Install and run
14
+
15
+ ```sh
16
+ # one-off
17
+ npx @bitefoundry/onenote --version
18
+
19
+ # global install (installs `onenote` and `note`)
20
+ npm install -g @bitefoundry/onenote
21
+ onenote --version
22
+ note --version
23
+
24
+ # project-local
25
+ npm install @bitefoundry/onenote
26
+ npx onenote notebooks
27
+ ```
28
+
29
+ All workflows share the same Microsoft Entra ID login (or automatic M365 shared-session
30
+ bootstrap from `teams-cli` / `outlook-cli`), SQLite WAL + FTS5 cache (`cache.db`),
31
+ background sync daemon (`onenote daemon start | status | stop | restart`), local HTTP API
32
+ (`onenote serve`, default `127.0.0.1:8788`), MCP server (`onenote mcp`), and multi-protocol
33
+ terminal image preview (`Kitty` / `iTerm2` / `Sixel` / `Halfblock` via `onenote preview-file`
34
+ and the interactive TUI).
35
+
36
+ - `onenote login`, `onenote logout`, `onenote whoami`, `onenote doctor --online`
37
+ - `onenote notebooks`, `onenote sections [notebook]`, `onenote pages <section>`, `onenote read <page>`
38
+ - `onenote create-notebook <name>`, `onenote create-section <notebook> <name>`
39
+ - `onenote create <section> <title> [--body ...] [--image ...] [--level 0|1|2]`
40
+ - `onenote append <page> [--body ...] [--image ...]`
41
+ - `onenote update <page> [--block-id <id> --body ...] [--title ...] [--body ...]`
42
+ - `onenote check <page> <block-id> [--done | --undone]`, `onenote delete <page>`
43
+ - `onenote search <query>`, `onenote resource <page> [index] [--out ...]`
44
+ - `onenote sync`, `onenote daemon <start|status|stop|restart|run>`, `onenote tui`, `onenote serve`, `onenote mcp`, `onenote preview-file <path>`, `onenote self-update`
45
+
46
+ ## Supported platforms
47
+
48
+ | npm package | OS | CPU | Rust target |
49
+ | ------------------------------- | ------- | ----- | ----------------------------------- |
50
+ | `@bitefoundry/onenote-win32-x64` | Windows | x64 | `x86_64-pc-windows-msvc` |
51
+ | `@bitefoundry/onenote-win32-arm64` | Windows | arm64 | `aarch64-pc-windows-msvc` |
52
+ | `@bitefoundry/onenote-darwin-x64` | macOS | x64 | `x86_64-apple-darwin` |
53
+ | `@bitefoundry/onenote-darwin-arm64` | macOS | arm64 | `aarch64-apple-darwin` |
54
+ | `@bitefoundry/onenote-linux-x64` | Linux | x64 | `x86_64-unknown-linux-gnu` (2.28) |
55
+ | `@bitefoundry/onenote-linux-arm64` | Linux | arm64 | `aarch64-unknown-linux-gnu` (2.28) |
56
+
57
+ Linux packages are cross-compiled in CI with `cargo-zigbuild` against **GLIBC 2.28** (`*.2.28`)
58
+ and verified with `scripts/verify-glibc.mjs` plus an `almalinux:8` container smoke test, so
59
+ prebuilt binaries run out of the box on **AlmaLinux 8 / RHEL 8+ / Rocky Linux 8+ / Ubuntu 20.04+ / Debian 10+**.
60
+ Older glibc distributions (e.g., CentOS 7 with `GLIBC < 2.28`) and Alpine/musl Linux should
61
+ build from source with Cargo (`cargo build --release`).
62
+
63
+ ## How resolution works
64
+
65
+ `bin/onenote.js` and `bin/note.js` look up `@bitefoundry/onenote-<platform>-<arch>` through
66
+ `require.resolve`, then execute `node_modules/@bitefoundry/onenote-<platform>-<arch>/bin/onenote`
67
+ (or `onenote.exe` on Windows) with `stdio: 'inherit'`. On `npm install`, `scripts/postinstall.mjs`
68
+ additionally links the native binary directly for zero-Node-startup execution.
69
+ Signals (`SIGINT`, `SIGTERM`, `SIGHUP`) are forwarded and the launcher exits with the child's
70
+ exit code. If the platform package is missing, the launcher prints the supported platforms
71
+ and the `--include=optional` hint instead of a stack trace.
72
+
73
+ ## Layout
74
+
75
+ ```
76
+ package.json # @bitefoundry/onenote launcher package (bin: onenote, note)
77
+ bin/onenote.js # onenote launcher
78
+ bin/note.js # note shorthand launcher
79
+ scripts/postinstall.mjs # zero-Node native binary linker on npm install
80
+ npm/onenote-<platform>/ # one package per platform
81
+ package.json # os/cpu/files, same version as root
82
+ bin/onenote[.exe] # added by scripts/build-npm.mjs, never committed
83
+ scripts/build-npm.mjs # copy target/<triple>/release/onenote[.exe]
84
+ scripts/sync-version.mjs # Cargo.toml version -> all package.json files
85
+ scripts/verify-glibc.mjs # verify Linux ELF GLIBC <= 2.28 symbol ceiling
86
+ .github/workflows/release.yml # tag-triggered build, publish, GitHub Release
87
+ ```
88
+
89
+ ## Versioning
90
+
91
+ `Cargo.toml` (`[package].version`) is the single source of truth. To bump:
92
+
93
+ ```sh
94
+ # edit Cargo.toml [package].version
95
+ node scripts/sync-version.mjs
96
+ node scripts/sync-version.mjs --check
97
+ ```
98
+
99
+ ## External token brokers, M365 bootstrap & token scopes
100
+
101
+ ### Required Microsoft Graph delegated scopes
102
+
103
+ `offline_access`, `User.Read`, `Notes.Read`, `Notes.ReadWrite`, `Notes.Create`
104
+
105
+ Run `onenote whoami` or `onenote doctor` to inspect JWT `scp`/`roles` claims automatically.
106
+
107
+ ### `config.toml` (recommended persistent setup)
108
+
109
+ ```toml
110
+ # Windows: %APPDATA%\onenote-cli\config.toml
111
+ # Linux/macOS: ~/.config/onenote-cli/config.toml
112
+ token_file = "~/.cursor/tc-auth/access_token"
113
+ token_refresh_cmd = "python ~/.cursor/tc-auth/graph-auth.py refresh"
114
+ token_refresh_mins = 5
115
+ ```
116
+
117
+ ### Key environment variables
118
+
119
+ | Variable | Summary |
120
+ | --- | --- |
121
+ | `ONENOTE_ACCESS_TOKEN` | Static Bearer token override (automatically skips OS keyring) |
122
+ | `ONENOTE_TOKEN_FILE` | External token file path (raw JWT or JSON; skips OS keyring) |
123
+ | `ONENOTE_TOKEN_REFRESH_CMD` | Shell command run to refresh expiring/`401` tokens |
124
+ | `ONENOTE_TOKEN_REFRESH_MINS` | Refresh lead window in minutes before expiry (default `5`) |
125
+ | `ONENOTE_SHARE_M365_AUTH` | Share/bootstrap M365 token session from `TEAMS_TOKEN_FILE` or `teams-cli` (default `true`) |
126
+ | `ONENOTE_DISABLE_KEYRING=1` | Disable OS keyring and use `credentials.json` only |
127
+ | `ONENOTE_CLIENT_ID` | Override Entra ID application client ID (falls back to `TEAMS_CLIENT_ID`, `AZURE_CLIENT_ID`) |
128
+ | `ONENOTE_TENANT_ID` | Override Entra ID tenant ID (default `common`; falls back to `TEAMS_TENANT_ID`, `AZURE_TENANT_ID`) |
129
+ | `ONENOTE_CONFIG_DIR` | Override config/credentials directory |
130
+ | `ONENOTE_DATA_DIR` | Override SQLite cache (`cache.db`) directory |
131
+ | `ONENOTE_NO_BROWSER` | Disable automatic browser launch during login (`1` / `true`) |
132
+ | `ONENOTE_AUTO_DAEMON` | Auto-start/attach to the background sync daemon (`1` / `true`, default `false`) |
133
+ | `ONENOTE_IMAGE_PROTOCOL` | Terminal image protocol override (`auto`, `kitty`, `iterm2`, `sixel`, `halfblock`) |
134
+ | `ONENOTE_GITHUB_REPO` | Override GitHub `owner/repo` used by `onenote self-update` (default `BiteFoundry/onenote`) |
135
+ | `ONENOTE_GITHUB_TOKEN` | GitHub token for private release checks in `onenote self-update` |
136
+
137
+ ## Troubleshooting
138
+
139
+ - **`no prebuilt binary found for <platform>-<arch>`** — reinstall with
140
+ `npm install -g @bitefoundry/onenote --include=optional`.
141
+ - **Older Linux (`GLIBC < 2.28`) or Alpine/musl Linux** — build from source with Cargo (`cargo build --release`).
142
+ - **Verify the binary** — `node -p "require.resolve('@bitefoundry/onenote-win32-x64/package.json')"` (adjust for your platform).
package/package.json CHANGED
@@ -1,6 +1,49 @@
1
1
  {
2
2
  "name": "@bitefoundry/onenote",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Microsoft OneNote terminal client & AI agent toolkit — Notebooks, Sections, Pages, XHTML/Markdown & Resources (CLI, TUI, HTTP API, MCP)",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/BiteFoundry/onenote.git"
8
+ },
9
+ "license": "MIT",
10
+ "bin": {
11
+ "onenote": "bin/onenote.js",
12
+ "note": "bin/note.js"
13
+ },
14
+ "files": [
15
+ "bin/onenote.js",
16
+ "bin/note.js",
17
+ "scripts/postinstall.mjs",
18
+ "docs/NPM.md",
19
+ "README.md"
20
+ ],
21
+ "engines": {
22
+ "node": ">=18"
23
+ },
24
+ "keywords": [
25
+ "microsoft-onenote",
26
+ "onenote",
27
+ "note",
28
+ "microsoft-365",
29
+ "microsoft-graph",
30
+ "notebooks",
31
+ "markdown",
32
+ "cli",
33
+ "tui",
34
+ "mcp"
35
+ ],
36
+ "scripts": {
37
+ "postinstall": "node scripts/postinstall.mjs",
38
+ "sync-version": "node scripts/sync-version.mjs",
39
+ "build:npm": "node scripts/build-npm.mjs"
40
+ },
41
+ "optionalDependencies": {
42
+ "@bitefoundry/onenote-win32-x64": "0.1.0",
43
+ "@bitefoundry/onenote-win32-arm64": "0.1.0",
44
+ "@bitefoundry/onenote-darwin-x64": "0.1.0",
45
+ "@bitefoundry/onenote-darwin-arm64": "0.1.0",
46
+ "@bitefoundry/onenote-linux-x64": "0.1.0",
47
+ "@bitefoundry/onenote-linux-arm64": "0.1.0"
48
+ }
49
+ }
@@ -0,0 +1,266 @@
1
+ #!/usr/bin/env node
2
+ // Zero-Node-Process npm native binary linker.
3
+ //
4
+ // On Unix (linux/darwin): replaces installed `bin/onenote.js` and `bin/note.js` with
5
+ // hardlinks/symlinks directly to `@bitefoundry/onenote-<platform>-<arch>/bin/onenote` so npm's
6
+ // bin symlink execve's the native Rust binary directly (0ms Node startup, 0MB Node RSS).
7
+ //
8
+ // On Windows (win32): creates NTFS hardlinks (fallback copy) `bin/onenote.exe` & `bin/note.exe`
9
+ // and rewrites npm's `.bin/{onenote,note}[.cmd|.ps1]` shims when present to invoke
10
+ // the native executable directly without spawning `node.exe`.
11
+
12
+ import fs from 'node:fs';
13
+ import path from 'node:path';
14
+ import { createRequire } from 'node:module';
15
+ import { fileURLToPath } from 'node:url';
16
+
17
+ const BIN_NAMES = ['onenote', 'note'];
18
+ const PKG_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
19
+
20
+ function linkOrCopyFile(source, destination) {
21
+ const tmp = `${destination}.tmp-${process.pid}`;
22
+ try {
23
+ fs.rmSync(tmp, { force: true });
24
+ } catch {
25
+ // Ignore cleanup errors on nonexistent temp paths.
26
+ }
27
+ try {
28
+ fs.linkSync(source, tmp);
29
+ } catch {
30
+ fs.copyFileSync(source, tmp);
31
+ }
32
+ try {
33
+ fs.renameSync(tmp, destination);
34
+ } catch {
35
+ try {
36
+ fs.rmSync(destination, { force: true });
37
+ } catch {
38
+ // Ignore; renameSync below will surface or fail safely.
39
+ }
40
+ fs.renameSync(tmp, destination);
41
+ }
42
+ }
43
+
44
+ function replaceJsWithNativeLinkUnix(binaryPath, destinationJs) {
45
+ const tmp = `${destinationJs}.tmp-${process.pid}`;
46
+ try {
47
+ fs.rmSync(tmp, { force: true });
48
+ } catch {
49
+ // Ignore cleanup errors.
50
+ }
51
+ try {
52
+ fs.linkSync(binaryPath, tmp);
53
+ } catch {
54
+ try {
55
+ fs.rmSync(tmp, { force: true });
56
+ } catch {
57
+ // Ignore cleanup errors.
58
+ }
59
+ fs.symlinkSync(binaryPath, tmp);
60
+ }
61
+ try {
62
+ fs.renameSync(tmp, destinationJs);
63
+ } catch (err) {
64
+ try {
65
+ fs.rmSync(tmp, { force: true });
66
+ } catch {
67
+ // Ignore cleanup errors.
68
+ }
69
+ throw err;
70
+ }
71
+ }
72
+
73
+ function collectWindowsShimDirs(pkgRoot, env = process.env) {
74
+ const dirs = [];
75
+ const parentScope = path.dirname(pkgRoot);
76
+ const nodeModulesDir = path.dirname(parentScope);
77
+ if (
78
+ path.basename(parentScope) === '@bitefoundry' &&
79
+ path.basename(nodeModulesDir) === 'node_modules'
80
+ ) {
81
+ dirs.push(path.join(nodeModulesDir, '.bin'));
82
+ // On global Windows npm installs (`%APPDATA%\npm\node_modules\@bitefoundry\onenote`),
83
+ // shims sit directly in the parent of `node_modules` even when `npm_config_prefix` is unset in npm v9+.
84
+ dirs.push(path.dirname(nodeModulesDir));
85
+ }
86
+
87
+ if (env.npm_config_global === 'true' && env.npm_config_prefix) {
88
+ const prefix = path.resolve(env.npm_config_prefix);
89
+ dirs.push(prefix);
90
+ dirs.push(path.join(prefix, 'bin'));
91
+ }
92
+
93
+ return [...new Set(dirs)];
94
+ }
95
+
96
+ function shimReferencesLauncher(content, name) {
97
+ const normalized = content.replace(/\\/g, '/').toLowerCase();
98
+ return (
99
+ normalized.includes('@bitefoundry/onenote') &&
100
+ normalized.includes(`bin/${name}.js`)
101
+ );
102
+ }
103
+
104
+ function rewriteWindowsShims(shimDir, pkgRoot) {
105
+ if (!fs.existsSync(shimDir)) return 0;
106
+ let rewritten = 0;
107
+
108
+ for (const name of BIN_NAMES) {
109
+ const exePath = path.join(pkgRoot, 'bin', `${name}.exe`);
110
+ if (!fs.existsSync(exePath)) continue;
111
+
112
+ const relWin = path.relative(shimDir, exePath).replace(/\//g, '\\');
113
+ const relPosix = path.relative(shimDir, exePath).replace(/\\/g, '/');
114
+
115
+ // 1. `<name>.cmd`
116
+ const cmdPath = path.join(shimDir, `${name}.cmd`);
117
+ try {
118
+ if (fs.existsSync(cmdPath)) {
119
+ const content = fs.readFileSync(cmdPath, 'utf8');
120
+ if (shimReferencesLauncher(content, name)) {
121
+ fs.writeFileSync(cmdPath, `@ECHO off\r\n"%~dp0${relWin}" %*\r\n`, 'utf8');
122
+ rewritten += 1;
123
+ }
124
+ }
125
+ } catch {
126
+ // Fall back cleanly to bin/<name>.js if shim is read-only or locked.
127
+ }
128
+
129
+ // 2. `<name>.ps1`
130
+ const ps1Path = path.join(shimDir, `${name}.ps1`);
131
+ try {
132
+ if (fs.existsSync(ps1Path)) {
133
+ const content = fs.readFileSync(ps1Path, 'utf8');
134
+ if (shimReferencesLauncher(content, name)) {
135
+ const ps1Body = [
136
+ '#!/usr/bin/env pwsh',
137
+ '$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent',
138
+ `$exePath = Join-Path $basedir '${relWin.replace(/'/g, "''")}'`,
139
+ 'if ($MyInvocation.ExpectingInput) {',
140
+ ' $input | & $exePath @args',
141
+ '} else {',
142
+ ' & $exePath @args',
143
+ '}',
144
+ 'exit $LASTEXITCODE',
145
+ '',
146
+ ].join('\n');
147
+ fs.writeFileSync(ps1Path, ps1Body, 'utf8');
148
+ rewritten += 1;
149
+ }
150
+ }
151
+ } catch {
152
+ // Fall back cleanly.
153
+ }
154
+
155
+ // 3. `<name>` (Git Bash / MSYS2 POSIX shell shim)
156
+ const shPath = path.join(shimDir, name);
157
+ try {
158
+ if (fs.existsSync(shPath)) {
159
+ const content = fs.readFileSync(shPath, 'utf8');
160
+ if (shimReferencesLauncher(content, name)) {
161
+ const shBody = [
162
+ '#!/bin/sh',
163
+ 'basedir=$(dirname "$(echo "$0" | sed -e \'s,\\\\,/,g\')")',
164
+ `exec "$basedir/${relPosix}" "$@"`,
165
+ '',
166
+ ].join('\n');
167
+ fs.writeFileSync(shPath, shBody, 'utf8');
168
+ rewritten += 1;
169
+ }
170
+ }
171
+ } catch {
172
+ // Fall back cleanly.
173
+ }
174
+ }
175
+
176
+ return rewritten;
177
+ }
178
+
179
+ export function runPostinstall(options = {}) {
180
+ const pkgRoot = path.resolve(options.pkgRoot || PKG_ROOT);
181
+ const platform = options.platform || process.platform;
182
+ const arch = options.arch || process.arch;
183
+ const env = options.env || process.env;
184
+
185
+ // CRITICAL SAFETY GUARD: Never mutate files inside the git development repository.
186
+ if (
187
+ fs.existsSync(path.join(pkgRoot, 'Cargo.toml')) ||
188
+ fs.existsSync(path.join(pkgRoot, '.git'))
189
+ ) {
190
+ return { skipped: true, reason: 'dev_repo' };
191
+ }
192
+
193
+ const platformKey = `${platform}-${arch}`;
194
+ const packageName = `@bitefoundry/onenote-${platformKey}`;
195
+ const binaryName = platform === 'win32' ? 'onenote.exe' : 'onenote';
196
+
197
+ let packageDir = null;
198
+ try {
199
+ const requireFromPkg = createRequire(path.join(pkgRoot, 'package.json'));
200
+ packageDir = path.dirname(requireFromPkg.resolve(`${packageName}/package.json`));
201
+ } catch {
202
+ packageDir = null;
203
+ }
204
+
205
+ const binaryPath = packageDir ? path.join(packageDir, 'bin', binaryName) : null;
206
+ if (!binaryPath || !fs.existsSync(binaryPath)) {
207
+ return { skipped: true, reason: 'missing_platform_binary' };
208
+ }
209
+
210
+ const binDir = path.join(pkgRoot, 'bin');
211
+ if (!fs.existsSync(binDir)) {
212
+ return { skipped: true, reason: 'missing_bin_dir' };
213
+ }
214
+
215
+ if (platform === 'win32') {
216
+ let linked = 0;
217
+ for (const name of BIN_NAMES) {
218
+ const destExe = path.join(binDir, `${name}.exe`);
219
+ try {
220
+ linkOrCopyFile(binaryPath, destExe);
221
+ linked += 1;
222
+ } catch {
223
+ // Leave fallback JS launcher untouched.
224
+ }
225
+ }
226
+
227
+ let shimsRewritten = 0;
228
+ for (const shimDir of collectWindowsShimDirs(pkgRoot, env)) {
229
+ try {
230
+ shimsRewritten += rewriteWindowsShims(shimDir, pkgRoot);
231
+ } catch {
232
+ // Never fail npm install on read-only or custom shims.
233
+ }
234
+ }
235
+ return { skipped: false, platform, linked, shimsRewritten };
236
+ }
237
+
238
+ // Unix (linux, darwin): chmod once and replace bin/*.js with hardlink/symlink to native binary.
239
+ try {
240
+ fs.chmodSync(binaryPath, 0o755);
241
+ } catch {
242
+ // Ignore on read-only stores.
243
+ }
244
+
245
+ let linked = 0;
246
+ for (const name of BIN_NAMES) {
247
+ const destJs = path.join(binDir, `${name}.js`);
248
+ try {
249
+ replaceJsWithNativeLinkUnix(binaryPath, destJs);
250
+ linked += 1;
251
+ } catch {
252
+ // Leave fallback JS launcher intact.
253
+ }
254
+ }
255
+
256
+ return { skipped: false, platform, linked };
257
+ }
258
+
259
+ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
260
+ try {
261
+ runPostinstall();
262
+ } catch {
263
+ // Postinstall optimization must never fail npm install.
264
+ }
265
+ process.exit(0);
266
+ }