@dhlotter/ai-usage 0.2.7 → 0.2.9

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 (2) hide show
  1. package/cli.mjs +74 -40
  2. package/package.json +1 -1
package/cli.mjs CHANGED
@@ -1,16 +1,17 @@
1
1
  #!/usr/bin/env node
2
2
  import { execFile } from 'node:child_process';
3
3
  import { createHash } from 'node:crypto';
4
- import { readFileSync } from 'node:fs';
5
- import { lstat, mkdir, mkdtemp, rename, rm, writeFile } from 'node:fs/promises';
4
+ import { readFileSync, realpathSync } from 'node:fs';
5
+ import { lstat, mkdir, mkdtemp, rm, rmdir, writeFile } from 'node:fs/promises';
6
6
  import { dirname, join, resolve } from 'node:path';
7
7
  import { parseArgs, promisify } from 'node:util';
8
+ import { fileURLToPath } from 'node:url';
8
9
 
9
10
  const { version } = JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8'));
10
11
  // Installer releases can change without a new Mac build.
11
- const appVersion = '0.2.6';
12
+ export const appVersion = '0.2.9';
12
13
  const asset = `https://github.com/dhlotter/ai-usage/releases/download/v${appVersion}/AI.Usage_${appVersion}_universal.dmg`;
13
- const sha256 = '7d34a4707588183e1b7b17b4cd83e0d9642de148dca0490b7fca5c60ca266ae7';
14
+ const sha256 = '4a34603609314759254c40ab71168a63bf93ecaa289c88b96f40e62c755dea8e';
14
15
  const app = 'AI Usage.app';
15
16
  const bundleId = 'com.dhlotter.ai-usage';
16
17
  const run = promisify(execFile);
@@ -70,9 +71,44 @@ async function requireClosedApp() {
70
71
  throw new Error('Quit AI Usage from the menu bar, then run this command again to update.');
71
72
  }
72
73
 
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.`);
74
+ const renameOnMac = `
75
+ ObjC.import('Foundation');
76
+ ObjC.bindFunction('open', ['int', ['char *', 'int']]);
77
+ ObjC.bindFunction('flock', ['int', ['int', 'int']]);
78
+ ObjC.bindFunction('close', ['int', ['int']]);
79
+ ObjC.bindFunction('renamex_np', ['int', ['char *', 'char *', 'unsigned int']]);
80
+ function run(args) {
81
+ const [source, destination, directory, expectedDevice, expectedInode] = args;
82
+ const fd = $.open(directory, 0);
83
+ if (fd < 0) throw Error('Could not open the install directory');
84
+ try {
85
+ // LOCK_EX | LOCK_NB. The kernel releases the lock even if this process is interrupted.
86
+ if ($.flock(fd, 6) !== 0) throw Error('Could not lock the install directory');
87
+ if (expectedInode) {
88
+ const info = $.NSFileManager.defaultManager.attributesOfItemAtPathError(destination, null);
89
+ const field = key => ObjC.unwrap(info.objectForKey(key).stringValue);
90
+ if (!info || field($.NSFileSystemNumber) !== expectedDevice || field($.NSFileSystemFileNumber) !== expectedInode) {
91
+ throw Error('The installed app changed during the download');
92
+ }
93
+ }
94
+ // RENAME_SWAP for an update; RENAME_EXCL for a fresh install.
95
+ if ($.renamex_np(source, destination, expectedInode ? 2 : 4) !== 0) throw Error('Atomic rename failed');
96
+ } finally {
97
+ $.close(fd);
98
+ }
99
+ }
100
+ `;
101
+
102
+ export async function moveIntoPlace(source, destination, expected) {
103
+ try {
104
+ await run('/usr/bin/osascript', ['-l', 'JavaScript', '-e', renameOnMac, '--', source, destination,
105
+ dirname(destination), String(expected?.dev ?? ''), String(expected?.ino ?? '')]);
106
+ } catch (error) {
107
+ const reason = /installed app changed/.test(error.stderr ?? '') ? 'The installed app changed. Run the installer again.'
108
+ : /Could not lock/.test(error.stderr ?? '') ? 'The install folder is busy or could not be locked. Try again.'
109
+ : 'Check permissions and use a folder on a local APFS volume.';
110
+ throw new Error(`Could not place the app at ${destination}. ${reason}`, { cause: error });
111
+ }
76
112
  }
77
113
 
78
114
  function isSameBundle(current, previous) {
@@ -80,20 +116,13 @@ function isSameBundle(current, previous) {
80
116
  current.info.dev === previous.info.dev && current.info.ino === previous.info.ino;
81
117
  }
82
118
 
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 });
119
+ export async function replaceApp(staged, destination, installed) {
120
+ if (!isSameBundle(await readBundle(destination), installed)) {
121
+ throw new Error('The installed app changed during the download. Run this command again.');
122
+ }
123
+ await moveIntoPlace(staged, destination, installed.info);
124
+ if (!isSameBundle(await readBundle(staged).catch(() => null), installed)) {
125
+ throw new Error(`The installer displaced an unexpected app. It was preserved at ${staged}.`);
97
126
  }
98
127
  }
99
128
 
@@ -145,16 +174,13 @@ async function main(args) {
145
174
  const mount = join(temp, 'mount');
146
175
  const dmg = join(temp, 'release.dmg');
147
176
  const staged = join(temp, app);
148
- const backup = join(temp, 'previous', app);
149
- let mounted = false;
150
- let installedSuccessfully = false;
177
+ let keepStaging = false;
151
178
  try {
152
179
  console.log(`Downloading AI Usage ${appVersion} from GitHub...`);
153
180
  await writeFile(dmg, await downloadVerified(), { flag: 'wx', mode: 0o600 });
154
181
  console.log('SHA-256 verified.');
155
182
  await mkdir(mount);
156
183
  await run('/usr/bin/hdiutil', ['attach', '-readonly', '-nobrowse', '-quiet', '-mountpoint', mount, dmg]);
157
- mounted = true;
158
184
  await run('/usr/bin/ditto', [join(mount, app), staged]);
159
185
  await run('/usr/bin/codesign', ['--verify', '--deep', '--strict', '-R', `=identifier "${bundleId}"`, staged]);
160
186
  if ((await readBundle(staged))?.version !== appVersion) throw new Error('The verified app has an unexpected version.');
@@ -162,35 +188,43 @@ async function main(args) {
162
188
  // npm downloads are not tagged as browser downloads. Keep first-launch assessment with macOS.
163
189
  await run('/usr/bin/xattr', ['-w', 'com.apple.quarantine', `0081;${Math.floor(Date.now() / 1000).toString(16)};AI Usage Installer;`, staged]);
164
190
  await run('/usr/bin/hdiutil', ['detach', '-quiet', mount]);
165
- mounted = false;
166
191
 
167
192
  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
193
  await requireClosedApp();
173
- await replaceApp(staged, destination, backup, installed);
194
+ const downloaded = await lstat(staged);
195
+ // If the swap or its verification fails, delete only the original staged download.
196
+ keepStaging = true;
197
+ try {
198
+ await replaceApp(staged, destination, installed);
199
+ keepStaging = false;
200
+ } catch (error) {
201
+ const remaining = await pathInfo(staged).catch(() => null);
202
+ keepStaging = remaining?.dev !== downloaded.dev || remaining?.ino !== downloaded.ino;
203
+ throw error;
204
+ }
174
205
  } else {
175
206
  await moveIntoPlace(staged, destination);
176
207
  }
177
- installedSuccessfully = true;
178
208
  console.log(`${installed ? `Updated AI Usage from ${installed.version} to ${appVersion} at` : 'Installed'} ${destination}. Open it from Finder.`);
179
209
  console.log('This release is not notarized. macOS may ask you to review it in Privacy & Security.');
180
210
  } 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.`);
211
+ // Only remove staging once the mount is gone, even if attach itself failed.
212
+ if (await pathInfo(mount)) {
213
+ try { await rmdir(mount); }
214
+ catch {
215
+ try { await run('/usr/bin/hdiutil', ['detach', '-quiet', mount]); }
216
+ catch {
217
+ console.error(`Could not eject ${mount}. The temporary files were left in place.`);
218
+ keepStaging = true;
219
+ }
187
220
  }
188
221
  }
189
- if (!mounted && (installedSuccessfully || !(await pathInfo(backup)))) await rm(temp, { recursive: true, force: true });
222
+ if (keepStaging) console.error(`Kept the staging directory at ${temp}.`);
223
+ else await rm(temp, { recursive: true, force: true });
190
224
  }
191
225
  }
192
226
 
193
- if (import.meta.main) {
227
+ if (process.argv[1] && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
194
228
  main(process.argv.slice(2)).catch(error => {
195
229
  console.error(`Error: ${error.message}`);
196
230
  process.exitCode = 1;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dhlotter/ai-usage",
3
- "version": "0.2.7",
3
+ "version": "0.2.9",
4
4
  "description": "Install the AI Usage menu bar app for macOS",
5
5
  "license": "MIT",
6
6
  "repository": {