@tapi-dev/sdk 0.1.1 → 0.1.2

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
@@ -10,6 +10,55 @@ npm install @tapi-dev/sdk
10
10
 
11
11
  This package is ESM-first and works in runtimes with `fetch`, including modern Node.js and browser-like server runtimes.
12
12
 
13
+ ## Install Tapi Studio
14
+
15
+ Tapi Studio is the desktop app used to author and test local Tapi integrations. Install the SDK first, then use the bundled CLI:
16
+
17
+ ```bash
18
+ npm install @tapi-dev/sdk
19
+ npx tapi studio install --channel pilot
20
+ npx tapi studio open
21
+ ```
22
+
23
+ You can also run the CLI directly from npm without adding the package first:
24
+
25
+ ```bash
26
+ npx @tapi-dev/sdk studio install --channel pilot
27
+ ```
28
+
29
+ The CLI reads the release manifest from:
30
+
31
+ ```text
32
+ https://downloads.tapi.dev/studio/channels/pilot/latest.json
33
+ ```
34
+
35
+ It downloads the Windows installer, verifies the manifest SHA256, caches the installer locally, and runs it. The installer cache defaults to:
36
+
37
+ ```text
38
+ %LOCALAPPDATA%\Tapi\Studio\downloads
39
+ ```
40
+
41
+ Useful commands:
42
+
43
+ ```bash
44
+ npx tapi studio install --channel pilot
45
+ npx tapi studio install --channel pilot --download-only
46
+ npx tapi studio install --manifest https://downloads.tapi.dev/studio/channels/pilot/latest.json
47
+ npx tapi studio open
48
+ npx tapi studio doctor
49
+ ```
50
+
51
+ Environment overrides:
52
+
53
+ ```env
54
+ TAPI_STUDIO_CHANNEL=pilot
55
+ TAPI_STUDIO_MANIFEST_URL=https://downloads.tapi.dev/studio/channels/pilot/latest.json
56
+ TAPI_DOWNLOADS_BASE_URL=https://downloads.tapi.dev
57
+ TAPI_STUDIO_EXE=C:\Users\you\AppData\Local\Tapi Studio\Tapi Studio.exe
58
+ ```
59
+
60
+ Tapi Studio desktop releases are currently published for Windows x64.
61
+
13
62
  ## Quick Start
14
63
 
15
64
  Create one TAPI client in your app's server-side code:
package/dist/cli.d.ts ADDED
@@ -0,0 +1,33 @@
1
+ #!/usr/bin/env node
2
+ export type StudioChannel = "pilot" | "stable" | "nightly";
3
+ export interface StudioReleaseManifest {
4
+ product?: string;
5
+ version: string;
6
+ channel: string;
7
+ platform: string;
8
+ artifactName: string;
9
+ url: string;
10
+ sha256: string;
11
+ sizeBytes?: number;
12
+ minSdkVersion?: string;
13
+ builtAt?: string;
14
+ commit?: string;
15
+ commitShort?: string;
16
+ ref?: string;
17
+ installerKind?: string;
18
+ }
19
+ interface StudioCliOptions {
20
+ channel: StudioChannel;
21
+ manifestUrl: string;
22
+ cacheDir: string;
23
+ downloadOnly: boolean;
24
+ silent: boolean;
25
+ exePath?: string;
26
+ }
27
+ export declare function runCli(argv?: string[]): Promise<number>;
28
+ export declare function parseStudioOptions(args: string[]): StudioCliOptions;
29
+ export declare function getDefaultStudioCacheDir(): string;
30
+ export declare function getStudioExecutableCandidates(): string[];
31
+ export declare function validateStudioManifest(input: unknown): StudioReleaseManifest;
32
+ export declare function compareVersions(left: string, right: string): number;
33
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,440 @@
1
+ #!/usr/bin/env node
2
+ import { spawn } from "node:child_process";
3
+ import { createHash } from "node:crypto";
4
+ import { createReadStream, createWriteStream, existsSync, readFileSync } from "node:fs";
5
+ import { mkdir, rename, unlink } from "node:fs/promises";
6
+ import { homedir } from "node:os";
7
+ import { basename, join, resolve } from "node:path";
8
+ import { Readable } from "node:stream";
9
+ import { pipeline } from "node:stream/promises";
10
+ import { fileURLToPath } from "node:url";
11
+ const DEFAULT_DOWNLOADS_BASE_URL = "https://downloads.tapi.dev";
12
+ const DEFAULT_CHANNEL = "pilot";
13
+ const SUPPORTED_STUDIO_PLATFORM = "windows-x86_64";
14
+ const sdkVersion = readSdkVersion();
15
+ export async function runCli(argv = process.argv.slice(2)) {
16
+ const [command, subcommand, ...rest] = argv;
17
+ if (!command || command === "help" || command === "--help" || command === "-h") {
18
+ printHelp();
19
+ return 0;
20
+ }
21
+ if (command === "--version" || command === "-v") {
22
+ console.log(sdkVersion);
23
+ return 0;
24
+ }
25
+ if (command === "doctor") {
26
+ if (hasHelpFlag([subcommand, ...rest])) {
27
+ printStudioHelp();
28
+ return 0;
29
+ }
30
+ return runDoctor(parseStudioOptions([subcommand, ...rest].filter(Boolean)));
31
+ }
32
+ if (command !== "studio") {
33
+ console.error(`Unknown command: ${command}`);
34
+ printHelp();
35
+ return 1;
36
+ }
37
+ if (!subcommand || subcommand === "help" || subcommand === "--help" || subcommand === "-h") {
38
+ printStudioHelp();
39
+ return 0;
40
+ }
41
+ if (hasHelpFlag(rest)) {
42
+ printStudioHelp();
43
+ return 0;
44
+ }
45
+ const options = parseStudioOptions(rest);
46
+ if (subcommand === "install") {
47
+ return installStudio(options);
48
+ }
49
+ if (subcommand === "open") {
50
+ return openStudio(options);
51
+ }
52
+ if (subcommand === "doctor") {
53
+ return runDoctor(options);
54
+ }
55
+ console.error(`Unknown studio command: ${subcommand}`);
56
+ printStudioHelp();
57
+ return 1;
58
+ }
59
+ export function parseStudioOptions(args) {
60
+ const raw = {};
61
+ for (let index = 0; index < args.length; index += 1) {
62
+ const arg = args[index];
63
+ if (!arg) {
64
+ continue;
65
+ }
66
+ if (arg === "--channel") {
67
+ raw.channel = parseChannel(requireOptionValue(args, ++index, "--channel"));
68
+ continue;
69
+ }
70
+ if (arg.startsWith("--channel=")) {
71
+ raw.channel = parseChannel(arg.slice("--channel=".length));
72
+ continue;
73
+ }
74
+ if (arg === "--manifest") {
75
+ raw.manifestUrl = requireOptionValue(args, ++index, "--manifest");
76
+ continue;
77
+ }
78
+ if (arg.startsWith("--manifest=")) {
79
+ raw.manifestUrl = arg.slice("--manifest=".length);
80
+ continue;
81
+ }
82
+ if (arg === "--cache-dir") {
83
+ raw.cacheDir = resolve(requireOptionValue(args, ++index, "--cache-dir"));
84
+ continue;
85
+ }
86
+ if (arg.startsWith("--cache-dir=")) {
87
+ raw.cacheDir = resolve(arg.slice("--cache-dir=".length));
88
+ continue;
89
+ }
90
+ if (arg === "--exe") {
91
+ raw.exePath = resolve(requireOptionValue(args, ++index, "--exe"));
92
+ continue;
93
+ }
94
+ if (arg.startsWith("--exe=")) {
95
+ raw.exePath = resolve(arg.slice("--exe=".length));
96
+ continue;
97
+ }
98
+ if (arg === "--download-only") {
99
+ raw.downloadOnly = true;
100
+ continue;
101
+ }
102
+ if (arg === "--silent") {
103
+ raw.silent = true;
104
+ continue;
105
+ }
106
+ if (arg === "--help" || arg === "-h") {
107
+ continue;
108
+ }
109
+ throw new Error(`Unknown option: ${arg}`);
110
+ }
111
+ const channel = raw.channel ?? parseChannel(envString("TAPI_STUDIO_CHANNEL") ?? DEFAULT_CHANNEL);
112
+ const downloadsBaseUrl = envString("TAPI_DOWNLOADS_BASE_URL") ?? DEFAULT_DOWNLOADS_BASE_URL;
113
+ const manifestUrl = raw.manifestUrl ??
114
+ envString("TAPI_STUDIO_MANIFEST_URL") ??
115
+ `${downloadsBaseUrl.replace(/\/+$/, "")}/studio/channels/${channel}/latest.json`;
116
+ return {
117
+ channel,
118
+ manifestUrl,
119
+ cacheDir: raw.cacheDir ?? getDefaultStudioCacheDir(),
120
+ downloadOnly: raw.downloadOnly ?? false,
121
+ silent: raw.silent ?? false,
122
+ exePath: raw.exePath ?? envString("TAPI_STUDIO_EXE"),
123
+ };
124
+ }
125
+ export function getDefaultStudioCacheDir() {
126
+ if (process.platform === "win32") {
127
+ const localAppData = process.env.LOCALAPPDATA ??
128
+ (process.env.USERPROFILE ? join(process.env.USERPROFILE, "AppData", "Local") : join(homedir(), "AppData", "Local"));
129
+ return join(localAppData, "Tapi", "Studio", "downloads");
130
+ }
131
+ return join(process.env.XDG_CACHE_HOME ?? join(homedir(), ".cache"), "tapi", "studio");
132
+ }
133
+ export function getStudioExecutableCandidates() {
134
+ const candidates = [
135
+ process.env.TAPI_STUDIO_EXE,
136
+ process.env.LOCALAPPDATA ? join(process.env.LOCALAPPDATA, "Tapi Studio", "Tapi Studio.exe") : undefined,
137
+ process.env.LOCALAPPDATA ? join(process.env.LOCALAPPDATA, "Programs", "Tapi Studio", "Tapi Studio.exe") : undefined,
138
+ process.env.LOCALAPPDATA ? join(process.env.LOCALAPPDATA, "com.tapi.studio", "Tapi Studio.exe") : undefined,
139
+ process.env.ProgramFiles ? join(process.env.ProgramFiles, "Tapi Studio", "Tapi Studio.exe") : undefined,
140
+ process.env["ProgramFiles(x86)"] ? join(process.env["ProgramFiles(x86)"], "Tapi Studio", "Tapi Studio.exe") : undefined,
141
+ ];
142
+ return [...new Set(candidates.filter((candidate) => Boolean(candidate)))];
143
+ }
144
+ export function validateStudioManifest(input) {
145
+ if (!input || typeof input !== "object") {
146
+ throw new Error("Studio manifest response was not a JSON object.");
147
+ }
148
+ const record = input;
149
+ const manifest = {
150
+ product: optionalString(record, "product"),
151
+ version: requiredString(record, "version"),
152
+ channel: requiredString(record, "channel"),
153
+ platform: requiredString(record, "platform"),
154
+ artifactName: requiredString(record, "artifactName"),
155
+ url: requiredString(record, "url"),
156
+ sha256: requiredString(record, "sha256").toLowerCase(),
157
+ sizeBytes: optionalNumber(record, "sizeBytes"),
158
+ minSdkVersion: optionalString(record, "minSdkVersion"),
159
+ builtAt: optionalString(record, "builtAt"),
160
+ commit: optionalString(record, "commit"),
161
+ commitShort: optionalString(record, "commitShort"),
162
+ ref: optionalString(record, "ref"),
163
+ installerKind: optionalString(record, "installerKind"),
164
+ };
165
+ if (!/^https?:\/\//i.test(manifest.url)) {
166
+ throw new Error("Studio manifest url must be an absolute HTTP(S) URL.");
167
+ }
168
+ if (!/^[a-f0-9]{64}$/i.test(manifest.sha256)) {
169
+ throw new Error("Studio manifest sha256 must be a 64-character hex digest.");
170
+ }
171
+ return manifest;
172
+ }
173
+ export function compareVersions(left, right) {
174
+ const leftParts = versionCore(left);
175
+ const rightParts = versionCore(right);
176
+ const maxLength = Math.max(leftParts.length, rightParts.length);
177
+ for (let index = 0; index < maxLength; index += 1) {
178
+ const leftValue = leftParts[index] ?? 0;
179
+ const rightValue = rightParts[index] ?? 0;
180
+ if (leftValue > rightValue) {
181
+ return 1;
182
+ }
183
+ if (leftValue < rightValue) {
184
+ return -1;
185
+ }
186
+ }
187
+ return 0;
188
+ }
189
+ async function installStudio(options) {
190
+ ensureWindowsHost();
191
+ console.log(`Fetching Tapi Studio ${options.channel} manifest...`);
192
+ const manifest = await fetchStudioManifest(options.manifestUrl);
193
+ ensureCompatibleManifest(manifest);
194
+ await mkdir(options.cacheDir, { recursive: true });
195
+ const installerPath = join(options.cacheDir, cachedInstallerName(manifest));
196
+ const verified = await hasVerifiedCachedInstaller(installerPath, manifest.sha256);
197
+ if (verified) {
198
+ console.log(`Using cached installer: ${installerPath}`);
199
+ }
200
+ else {
201
+ console.log(`Downloading Tapi Studio ${manifest.version}...`);
202
+ await downloadAndVerify(manifest.url, installerPath, manifest.sha256);
203
+ }
204
+ if (options.downloadOnly) {
205
+ console.log(`Downloaded installer: ${installerPath}`);
206
+ return 0;
207
+ }
208
+ const installerArgs = options.silent ? ["/S"] : [];
209
+ console.log(`Starting Tapi Studio installer: ${installerPath}`);
210
+ await runProcess(installerPath, installerArgs);
211
+ console.log("Tapi Studio installer finished.");
212
+ return 0;
213
+ }
214
+ async function openStudio(options) {
215
+ ensureWindowsHost();
216
+ const exePath = options.exePath ?? getStudioExecutableCandidates().find((candidate) => existsSync(candidate));
217
+ if (!exePath || !existsSync(exePath)) {
218
+ console.error("Tapi Studio executable was not found.");
219
+ console.error("Run `npx tapi studio install --channel pilot`, or set TAPI_STUDIO_EXE to the installed executable path.");
220
+ return 1;
221
+ }
222
+ const child = spawn(exePath, [], {
223
+ detached: true,
224
+ stdio: "ignore",
225
+ windowsHide: false,
226
+ });
227
+ child.unref();
228
+ console.log(`Opened Tapi Studio: ${exePath}`);
229
+ return 0;
230
+ }
231
+ async function runDoctor(options) {
232
+ console.log(`Tapi SDK: ${sdkVersion}`);
233
+ console.log(`Node: ${process.version}`);
234
+ console.log(`Platform: ${process.platform}/${process.arch}`);
235
+ console.log(`Studio channel: ${options.channel}`);
236
+ console.log(`Studio manifest: ${options.manifestUrl}`);
237
+ console.log(`Studio cache: ${options.cacheDir}`);
238
+ const exePath = options.exePath ?? getStudioExecutableCandidates().find((candidate) => existsSync(candidate));
239
+ console.log(`Studio executable: ${exePath && existsSync(exePath) ? exePath : "not found"}`);
240
+ try {
241
+ const manifest = await fetchStudioManifest(options.manifestUrl);
242
+ ensureCompatibleManifest(manifest);
243
+ console.log(`Latest Studio: ${manifest.version} (${manifest.platform})`);
244
+ }
245
+ catch (error) {
246
+ console.log(`Latest Studio: unavailable (${formatError(error)})`);
247
+ return 1;
248
+ }
249
+ return 0;
250
+ }
251
+ async function fetchStudioManifest(manifestUrl, fetchImpl = fetch) {
252
+ const response = await fetchImpl(manifestUrl, {
253
+ headers: {
254
+ Accept: "application/json",
255
+ },
256
+ });
257
+ if (!response.ok) {
258
+ throw new Error(`Failed to fetch Studio manifest: HTTP ${response.status}`);
259
+ }
260
+ return validateStudioManifest(await response.json());
261
+ }
262
+ async function downloadAndVerify(url, destination, expectedSha256) {
263
+ const partialPath = `${destination}.partial`;
264
+ await downloadFile(url, partialPath);
265
+ const actualSha256 = await sha256File(partialPath);
266
+ if (actualSha256 !== expectedSha256.toLowerCase()) {
267
+ await unlinkIfExists(partialPath);
268
+ throw new Error(`Studio installer checksum mismatch. Expected ${expectedSha256}, got ${actualSha256}.`);
269
+ }
270
+ await rename(partialPath, destination);
271
+ console.log(`Verified SHA256: ${actualSha256}`);
272
+ }
273
+ async function downloadFile(url, destination) {
274
+ const response = await fetch(url);
275
+ if (!response.ok) {
276
+ throw new Error(`Failed to download Studio installer: HTTP ${response.status}`);
277
+ }
278
+ if (!response.body) {
279
+ throw new Error("Studio installer response did not include a body.");
280
+ }
281
+ await pipeline(Readable.fromWeb(response.body), createWriteStream(destination));
282
+ }
283
+ async function hasVerifiedCachedInstaller(path, expectedSha256) {
284
+ if (!existsSync(path)) {
285
+ return false;
286
+ }
287
+ return (await sha256File(path)) === expectedSha256.toLowerCase();
288
+ }
289
+ async function sha256File(path) {
290
+ const hash = createHash("sha256");
291
+ await pipeline(createReadStream(path), hash);
292
+ return hash.digest("hex");
293
+ }
294
+ async function runProcess(command, args) {
295
+ await new Promise((resolvePromise, rejectPromise) => {
296
+ const child = spawn(command, args, {
297
+ stdio: "inherit",
298
+ windowsHide: false,
299
+ });
300
+ child.once("error", rejectPromise);
301
+ child.once("exit", (code) => {
302
+ if (code === 0) {
303
+ resolvePromise();
304
+ }
305
+ else {
306
+ rejectPromise(new Error(`Process exited with code ${code ?? "unknown"}.`));
307
+ }
308
+ });
309
+ });
310
+ }
311
+ function ensureWindowsHost() {
312
+ if (process.platform !== "win32" || process.arch !== "x64") {
313
+ throw new Error("Tapi Studio desktop installer is currently published for Windows x64 only.");
314
+ }
315
+ }
316
+ function ensureCompatibleManifest(manifest) {
317
+ if (manifest.platform !== SUPPORTED_STUDIO_PLATFORM) {
318
+ throw new Error(`This SDK expected ${SUPPORTED_STUDIO_PLATFORM}, but the manifest points to ${manifest.platform}.`);
319
+ }
320
+ if (manifest.minSdkVersion && compareVersions(sdkVersion, manifest.minSdkVersion) < 0) {
321
+ throw new Error(`Tapi Studio ${manifest.version} requires @tapi-dev/sdk >= ${manifest.minSdkVersion}; installed SDK is ${sdkVersion}.`);
322
+ }
323
+ }
324
+ function cachedInstallerName(manifest) {
325
+ const rawName = manifest.artifactName || basename(new URL(manifest.url).pathname) || `TapiStudioSetup-${manifest.version}.exe`;
326
+ return rawName.replace(/[^A-Za-z0-9._-]/g, "_");
327
+ }
328
+ function parseChannel(value) {
329
+ if (value === "pilot" || value === "stable" || value === "nightly") {
330
+ return value;
331
+ }
332
+ throw new Error(`Invalid Studio channel: ${value}. Expected pilot, stable, or nightly.`);
333
+ }
334
+ function requireOptionValue(args, index, option) {
335
+ const value = args[index];
336
+ if (!value || value.startsWith("--")) {
337
+ throw new Error(`${option} requires a value.`);
338
+ }
339
+ return value;
340
+ }
341
+ function requiredString(record, field) {
342
+ const value = record[field];
343
+ if (typeof value !== "string" || !value.trim()) {
344
+ throw new Error(`Studio manifest is missing required string field: ${field}`);
345
+ }
346
+ return value.trim();
347
+ }
348
+ function optionalString(record, field) {
349
+ const value = record[field];
350
+ if (typeof value === "string" && value.trim()) {
351
+ return value.trim();
352
+ }
353
+ return undefined;
354
+ }
355
+ function optionalNumber(record, field) {
356
+ const value = record[field];
357
+ if (typeof value === "number" && Number.isFinite(value)) {
358
+ return value;
359
+ }
360
+ return undefined;
361
+ }
362
+ function envString(name) {
363
+ const value = process.env[name];
364
+ return value && value.trim() ? value.trim() : undefined;
365
+ }
366
+ function hasHelpFlag(args) {
367
+ return args.some((arg) => arg === "--help" || arg === "-h");
368
+ }
369
+ function versionCore(version) {
370
+ return version
371
+ .split("-")[0]
372
+ .split(".")
373
+ .map((part) => Number.parseInt(part, 10))
374
+ .map((part) => (Number.isFinite(part) ? part : 0));
375
+ }
376
+ async function unlinkIfExists(path) {
377
+ try {
378
+ await unlink(path);
379
+ }
380
+ catch (error) {
381
+ if (error.code !== "ENOENT") {
382
+ throw error;
383
+ }
384
+ }
385
+ }
386
+ function readSdkVersion() {
387
+ const packageJson = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
388
+ if (!packageJson.version) {
389
+ throw new Error("Could not read @tapi-dev/sdk package version.");
390
+ }
391
+ return packageJson.version;
392
+ }
393
+ function printHelp() {
394
+ console.log(`Tapi CLI
395
+
396
+ Usage:
397
+ tapi studio install [--channel pilot] [--manifest URL]
398
+ tapi studio open
399
+ tapi studio doctor
400
+ tapi doctor
401
+
402
+ Commands:
403
+ studio install Download, verify, and run the Tapi Studio installer
404
+ studio open Open an installed Tapi Studio desktop app
405
+ studio doctor Check local SDK and Studio release configuration
406
+ doctor Alias for studio doctor
407
+ `);
408
+ }
409
+ function printStudioHelp() {
410
+ console.log(`Tapi Studio commands
411
+
412
+ Usage:
413
+ tapi studio install [options]
414
+ tapi studio open [options]
415
+ tapi studio doctor [options]
416
+
417
+ Options:
418
+ --channel <name> Release channel: pilot, stable, or nightly
419
+ --manifest <url> Exact release manifest URL
420
+ --cache-dir <path> Installer download cache directory
421
+ --download-only Download and verify without running the installer
422
+ --silent Run the NSIS installer with /S
423
+ --exe <path> Tapi Studio executable path for open/doctor
424
+ `);
425
+ }
426
+ function formatError(error) {
427
+ return error instanceof Error ? error.message : String(error);
428
+ }
429
+ function isCliEntrypoint() {
430
+ const invokedPath = process.argv[1];
431
+ return Boolean(invokedPath && resolve(invokedPath) === fileURLToPath(import.meta.url));
432
+ }
433
+ if (isCliEntrypoint()) {
434
+ runCli().then((code) => {
435
+ process.exitCode = code;
436
+ }, (error) => {
437
+ console.error(formatError(error));
438
+ process.exitCode = 1;
439
+ });
440
+ }
package/package.json CHANGED
@@ -1,15 +1,21 @@
1
1
  {
2
2
  "name": "@tapi-dev/sdk",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
7
+ "bin": {
8
+ "tapi": "dist/cli.js"
9
+ },
7
10
  "exports": {
8
11
  ".": {
9
12
  "types": "./dist/index.d.ts",
10
13
  "import": "./dist/index.js"
11
14
  }
12
15
  },
16
+ "engines": {
17
+ "node": ">=18"
18
+ },
13
19
  "files": [
14
20
  "dist"
15
21
  ],
@@ -23,6 +29,7 @@
23
29
  "access": "public"
24
30
  },
25
31
  "devDependencies": {
32
+ "@types/node": "^20.0.0",
26
33
  "typescript": "^5.5.0",
27
34
  "vitest": "^2.0.0"
28
35
  }