@dhlotter/ai-usage 0.0.0-stage → 0.2.7
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 +21 -0
- package/cli.mjs +198 -0
- package/package.json +16 -4
- package/README.md +0 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Hermann Lotter
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/cli.mjs
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { execFile } from 'node:child_process';
|
|
3
|
+
import { createHash } from 'node:crypto';
|
|
4
|
+
import { readFileSync } from 'node:fs';
|
|
5
|
+
import { lstat, mkdir, mkdtemp, rename, rm, writeFile } from 'node:fs/promises';
|
|
6
|
+
import { dirname, join, resolve } from 'node:path';
|
|
7
|
+
import { parseArgs, promisify } from 'node:util';
|
|
8
|
+
|
|
9
|
+
const { version } = JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8'));
|
|
10
|
+
// Installer releases can change without a new Mac build.
|
|
11
|
+
const appVersion = '0.2.6';
|
|
12
|
+
const asset = `https://github.com/dhlotter/ai-usage/releases/download/v${appVersion}/AI.Usage_${appVersion}_universal.dmg`;
|
|
13
|
+
const sha256 = '7d34a4707588183e1b7b17b4cd83e0d9642de148dca0490b7fca5c60ca266ae7';
|
|
14
|
+
const app = 'AI Usage.app';
|
|
15
|
+
const bundleId = 'com.dhlotter.ai-usage';
|
|
16
|
+
const run = promisify(execFile);
|
|
17
|
+
const usage = `Usage: ai-usage install [--app-dir DIRECTORY]
|
|
18
|
+
Install or update AI Usage to ${appVersion} on macOS 14 or later (Apple Silicon or Intel).
|
|
19
|
+
Defaults to /Applications. Current and newer versions are left alone.`;
|
|
20
|
+
|
|
21
|
+
export async function downloadVerified(fetchRelease = fetch) {
|
|
22
|
+
const response = await fetchRelease(asset, { signal: AbortSignal.timeout(120_000) });
|
|
23
|
+
if (!response.ok || !response.body) throw new Error(`Release download failed (HTTP ${response.status}).`);
|
|
24
|
+
const hash = createHash('sha256');
|
|
25
|
+
const chunks = [];
|
|
26
|
+
let size = 0;
|
|
27
|
+
for await (const chunk of response.body) {
|
|
28
|
+
size += chunk.byteLength;
|
|
29
|
+
if (size > 32 * 1024 * 1024) throw new Error('Release download exceeded 32 MiB.');
|
|
30
|
+
hash.update(chunk);
|
|
31
|
+
chunks.push(chunk);
|
|
32
|
+
}
|
|
33
|
+
if (hash.digest('hex') !== sha256) throw new Error('SHA-256 mismatch. The disk image was not installed.');
|
|
34
|
+
return Buffer.concat(chunks, size);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
async function pathInfo(path) {
|
|
38
|
+
try {
|
|
39
|
+
return await lstat(path);
|
|
40
|
+
} catch (error) {
|
|
41
|
+
if (error.code !== 'ENOENT') throw error;
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async function readBundle(path) {
|
|
47
|
+
const info = await pathInfo(path);
|
|
48
|
+
if (!info) return null;
|
|
49
|
+
const unrecognised = `The item at ${path} is not a recognised AI Usage app. It was not changed.`;
|
|
50
|
+
if (!info.isDirectory()) throw new Error(unrecognised);
|
|
51
|
+
|
|
52
|
+
const plist = join(path, 'Contents', 'Info.plist');
|
|
53
|
+
const readKey = async key => (await run('/usr/bin/plutil', ['-extract', key, 'raw', '-expect', 'string', '-o', '-', plist])).stdout.trim();
|
|
54
|
+
const id = await readKey('CFBundleIdentifier').catch(() => '');
|
|
55
|
+
if (id !== bundleId) throw new Error(unrecognised);
|
|
56
|
+
const installedVersion = await readKey('CFBundleShortVersionString').catch(() => '');
|
|
57
|
+
if (!/^\d+\.\d+\.\d+$/.test(installedVersion)) {
|
|
58
|
+
throw new Error(`Cannot determine the AI Usage version at ${path}. It was not changed.`);
|
|
59
|
+
}
|
|
60
|
+
return { info, version: installedVersion };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
async function requireClosedApp() {
|
|
64
|
+
try {
|
|
65
|
+
await run('/usr/bin/pgrep', ['-x', 'ai-usage']);
|
|
66
|
+
} catch (error) {
|
|
67
|
+
if (error.code === 1) return;
|
|
68
|
+
throw new Error('Could not check if AI Usage is running. No update was made.', { cause: error });
|
|
69
|
+
}
|
|
70
|
+
throw new Error('Quit AI Usage from the menu bar, then run this command again to update.');
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async function moveIntoPlace(source, destination) {
|
|
74
|
+
await run('/bin/mv', ['-n', source, dirname(destination)]);
|
|
75
|
+
if (await pathInfo(source)) throw new Error(`The item at ${destination} already exists. It was not overwritten.`);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function isSameBundle(current, previous) {
|
|
79
|
+
return current && current.version === previous.version &&
|
|
80
|
+
current.info.dev === previous.info.dev && current.info.ino === previous.info.ino;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export async function replaceApp(staged, destination, backup, installed) {
|
|
84
|
+
await rename(destination, backup);
|
|
85
|
+
try {
|
|
86
|
+
if (!isSameBundle(await readBundle(backup), installed)) {
|
|
87
|
+
throw new Error('The installed app changed during the update. Run this command again.');
|
|
88
|
+
}
|
|
89
|
+
await moveIntoPlace(staged, destination);
|
|
90
|
+
} catch (error) {
|
|
91
|
+
try {
|
|
92
|
+
await moveIntoPlace(backup, destination);
|
|
93
|
+
} catch {
|
|
94
|
+
throw new Error(`Update failed and the old app could not be restored. Its backup is at ${backup}.`, { cause: error });
|
|
95
|
+
}
|
|
96
|
+
throw new Error(`Update failed. The old app was restored. ${error.message}`, { cause: error });
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
async function main(args) {
|
|
101
|
+
const { values, positionals } = parseArgs({
|
|
102
|
+
args,
|
|
103
|
+
options: { 'app-dir': { type: 'string' }, help: { type: 'boolean', short: 'h' }, version: { type: 'boolean' } },
|
|
104
|
+
allowPositionals: true,
|
|
105
|
+
});
|
|
106
|
+
if (values.version || values.help || args.length === 0) {
|
|
107
|
+
console.log(values.version ? version : usage);
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
if (positionals.length !== 1 || positionals[0] !== 'install') throw new Error(usage);
|
|
111
|
+
if (process.platform !== 'darwin') throw new Error('AI Usage requires macOS 14 or later.');
|
|
112
|
+
if (process.getuid() === 0) throw new Error('Run without sudo. Use --app-dir "$HOME/Applications" if needed.');
|
|
113
|
+
const { stdout: osVersion } = await run('/usr/bin/sw_vers', ['-productVersion']);
|
|
114
|
+
if (Number.parseInt(osVersion, 10) < 14) throw new Error('AI Usage requires macOS 14 or later.');
|
|
115
|
+
|
|
116
|
+
if (values['app-dir'] === '') throw new Error('--app-dir must not be empty.');
|
|
117
|
+
const directory = resolve(values['app-dir'] ?? '/Applications');
|
|
118
|
+
const destination = join(directory, app);
|
|
119
|
+
const installed = await readBundle(destination);
|
|
120
|
+
if (installed) {
|
|
121
|
+
const available = appVersion.split('.').map(BigInt);
|
|
122
|
+
const order = installed.version.split('.').map((part, i) => BigInt(part) - available[i]).find(part => part !== 0n) ?? 0n;
|
|
123
|
+
if (order === 0n) {
|
|
124
|
+
console.log(`AI Usage ${appVersion} is already up to date.`);
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
if (order > 0n) {
|
|
128
|
+
console.log(`Installed AI Usage ${installed.version} is newer than ${appVersion}. No changes made.`);
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
await requireClosedApp();
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
let temp;
|
|
135
|
+
try {
|
|
136
|
+
await mkdir(directory, { recursive: true });
|
|
137
|
+
temp = await mkdtemp(join(directory, '.ai-usage-'));
|
|
138
|
+
} catch (error) {
|
|
139
|
+
if (error.code === 'EACCES' || error.code === 'EPERM') {
|
|
140
|
+
throw new Error('Cannot write to the chosen folder. Try --app-dir "$HOME/Applications" without sudo.');
|
|
141
|
+
}
|
|
142
|
+
throw error;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const mount = join(temp, 'mount');
|
|
146
|
+
const dmg = join(temp, 'release.dmg');
|
|
147
|
+
const staged = join(temp, app);
|
|
148
|
+
const backup = join(temp, 'previous', app);
|
|
149
|
+
let mounted = false;
|
|
150
|
+
let installedSuccessfully = false;
|
|
151
|
+
try {
|
|
152
|
+
console.log(`Downloading AI Usage ${appVersion} from GitHub...`);
|
|
153
|
+
await writeFile(dmg, await downloadVerified(), { flag: 'wx', mode: 0o600 });
|
|
154
|
+
console.log('SHA-256 verified.');
|
|
155
|
+
await mkdir(mount);
|
|
156
|
+
await run('/usr/bin/hdiutil', ['attach', '-readonly', '-nobrowse', '-quiet', '-mountpoint', mount, dmg]);
|
|
157
|
+
mounted = true;
|
|
158
|
+
await run('/usr/bin/ditto', [join(mount, app), staged]);
|
|
159
|
+
await run('/usr/bin/codesign', ['--verify', '--deep', '--strict', '-R', `=identifier "${bundleId}"`, staged]);
|
|
160
|
+
if ((await readBundle(staged))?.version !== appVersion) throw new Error('The verified app has an unexpected version.');
|
|
161
|
+
|
|
162
|
+
// npm downloads are not tagged as browser downloads. Keep first-launch assessment with macOS.
|
|
163
|
+
await run('/usr/bin/xattr', ['-w', 'com.apple.quarantine', `0081;${Math.floor(Date.now() / 1000).toString(16)};AI Usage Installer;`, staged]);
|
|
164
|
+
await run('/usr/bin/hdiutil', ['detach', '-quiet', mount]);
|
|
165
|
+
mounted = false;
|
|
166
|
+
|
|
167
|
+
if (installed) {
|
|
168
|
+
await mkdir(dirname(backup));
|
|
169
|
+
if (!isSameBundle(await readBundle(destination), installed)) {
|
|
170
|
+
throw new Error('The installed app changed during the download. Run this command again.');
|
|
171
|
+
}
|
|
172
|
+
await requireClosedApp();
|
|
173
|
+
await replaceApp(staged, destination, backup, installed);
|
|
174
|
+
} else {
|
|
175
|
+
await moveIntoPlace(staged, destination);
|
|
176
|
+
}
|
|
177
|
+
installedSuccessfully = true;
|
|
178
|
+
console.log(`${installed ? `Updated AI Usage from ${installed.version} to ${appVersion} at` : 'Installed'} ${destination}. Open it from Finder.`);
|
|
179
|
+
console.log('This release is not notarized. macOS may ask you to review it in Privacy & Security.');
|
|
180
|
+
} finally {
|
|
181
|
+
if (mounted) {
|
|
182
|
+
try {
|
|
183
|
+
await run('/usr/bin/hdiutil', ['detach', '-quiet', mount]);
|
|
184
|
+
mounted = false;
|
|
185
|
+
} catch {
|
|
186
|
+
console.error(`Could not eject ${mount}. The temporary files were left in place.`);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
if (!mounted && (installedSuccessfully || !(await pathInfo(backup)))) await rm(temp, { recursive: true, force: true });
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
if (import.meta.main) {
|
|
194
|
+
main(process.argv.slice(2)).catch(error => {
|
|
195
|
+
console.error(`Error: ${error.message}`);
|
|
196
|
+
process.exitCode = 1;
|
|
197
|
+
});
|
|
198
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,18 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dhlotter/ai-usage",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.7",
|
|
4
|
+
"description": "Install the AI Usage menu bar app for macOS",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/dhlotter/ai-usage.git",
|
|
9
|
+
"directory": "scripts/npm-installer"
|
|
10
|
+
},
|
|
11
|
+
"bin": { "ai-usage": "./cli.mjs" },
|
|
12
|
+
"engines": { "node": ">=22.18.0" },
|
|
13
|
+
"os": ["darwin"],
|
|
14
|
+
"cpu": ["arm64", "x64"],
|
|
15
|
+
"files": ["cli.mjs"],
|
|
16
|
+
"publishConfig": { "access": "public", "registry": "https://registry.npmjs.org" },
|
|
17
|
+
"scripts": { "test": "node --test" }
|
|
18
|
+
}
|
package/README.md
DELETED