@shiwano/ggen 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Shogo Iwano
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.
@@ -0,0 +1,37 @@
1
+ export type GGenBackend = "cpu" | "cuda" | "rocm" | "vulkan" | "metal";
2
+ export interface Manifest {
3
+ version: string;
4
+ archives: Record<string, {
5
+ url: string;
6
+ sha256: string;
7
+ size: number;
8
+ }>;
9
+ }
10
+ export interface GGenDownloadProgress {
11
+ backend: GGenBackend;
12
+ completed: number;
13
+ total: number;
14
+ }
15
+ export interface BinaryOptions {
16
+ binaryDir?: string | undefined;
17
+ backend?: GGenBackend | "auto" | undefined;
18
+ download?: boolean | undefined;
19
+ onDownload?: ((progress: GGenDownloadProgress) => void) | undefined;
20
+ manifest?: Manifest | undefined;
21
+ }
22
+ export declare function manifest(): Manifest;
23
+ export declare function platform(): string;
24
+ export declare function defaultBinaryDir(version: string): string;
25
+ /** Returns the `ggen` executable and its backend, downloading it unless `download` is false. */
26
+ export declare function resolveBinary(options?: BinaryOptions): Promise<{
27
+ path: string;
28
+ backend: GGenBackend;
29
+ }>;
30
+ /**
31
+ * Calls `start` with the binary of each backend `options` allows, in order, until one succeeds.
32
+ * Under `auto` a backend whose binary cannot be had or started falls through to the next.
33
+ */
34
+ export declare function withBinary<T>(options: BinaryOptions, start: (binary: {
35
+ path: string;
36
+ backend: GGenBackend;
37
+ }) => Promise<T>): Promise<T>;
package/dist/binary.js ADDED
@@ -0,0 +1,214 @@
1
+ import { spawn } from "node:child_process";
2
+ import { createHash } from "node:crypto";
3
+ import { readFileSync } from "node:fs";
4
+ import { access, chmod, mkdir, mkdtemp, open, readFile, readdir, rename, rm, writeFile, } from "node:fs/promises";
5
+ import { homedir } from "node:os";
6
+ import { join } from "node:path";
7
+ import { Readable } from "node:stream";
8
+ import { GGenError } from "./errors.js";
9
+ import { extractZip } from "./zip.js";
10
+ const AUTO_ORDER = ["cuda", "vulkan", "cpu"];
11
+ const BACKENDS = ["cpu", "cuda", "rocm", "vulkan", "metal"];
12
+ let embedded;
13
+ export function manifest() {
14
+ embedded ??= JSON.parse(readFileSync(new URL("../manifest.json", import.meta.url), "utf8"));
15
+ return embedded;
16
+ }
17
+ export function platform() {
18
+ const os = { linux: "linux", darwin: "darwin", win32: "windows" }[process.platform];
19
+ const arch = { x64: "x86_64", arm64: "arm64" }[process.arch];
20
+ if (!os || !arch) {
21
+ throw new GGenError("BINARY_UNAVAILABLE", `unsupported platform ${process.platform}-${process.arch}`);
22
+ }
23
+ return `${os}-${arch}`;
24
+ }
25
+ export function defaultBinaryDir(version) {
26
+ const env = (name) => process.env[name] || undefined;
27
+ const cache = env("GGEN_CACHE_DIR") ?? join(env("XDG_CACHE_HOME") ?? join(homedir(), ".cache"), "ggen");
28
+ return join(cache, "bin", version);
29
+ }
30
+ const ARCHIVE_DIGEST = ".archive-sha256";
31
+ function executable(binaryDir, backend) {
32
+ return join(binaryDir, `${platform()}-${backend}`, "bin", process.platform === "win32" ? "ggen.exe" : "ggen");
33
+ }
34
+ async function exists(path) {
35
+ return access(path).then(() => true, () => false);
36
+ }
37
+ /** Returns the `ggen` executable and its backend, downloading it unless `download` is false. */
38
+ export async function resolveBinary(options = {}) {
39
+ return withBinary(options, async (binary) => binary);
40
+ }
41
+ /**
42
+ * Calls `start` with the binary of each backend `options` allows, in order, until one succeeds.
43
+ * Under `auto` a backend whose binary cannot be had or started falls through to the next.
44
+ */
45
+ export async function withBinary(options, start) {
46
+ const source = options.manifest ?? manifest();
47
+ const binaryDir = options.binaryDir ?? defaultBinaryDir(source.version);
48
+ const download = options.download ?? true;
49
+ const ensure = async (backend) => {
50
+ const path = executable(binaryDir, backend);
51
+ if (await exists(path)) {
52
+ const key = `${platform()}-${backend}`;
53
+ const expected = source.archives[key]?.sha256;
54
+ const recorded = await readFile(join(binaryDir, key, ARCHIVE_DIGEST), "utf8").catch(() => undefined);
55
+ if (expected && recorded && recorded.trim().toLowerCase() !== expected.toLowerCase()) {
56
+ throw new GGenError("BINARY_UNAVAILABLE", `${join(binaryDir, key)} holds another archive than the manifest of ${source.version}; remove it`);
57
+ }
58
+ return path;
59
+ }
60
+ if (!download) {
61
+ throw new GGenError("BINARY_UNAVAILABLE", `${path} not found and download is false`);
62
+ }
63
+ await install(source, binaryDir, backend, options.onDownload);
64
+ return path;
65
+ };
66
+ const order = options.backend === undefined || options.backend === "auto"
67
+ ? await detect(source, binaryDir, download, ensure)
68
+ : [options.backend];
69
+ const errors = [];
70
+ for (const backend of order) {
71
+ try {
72
+ return await start({ path: await ensure(backend), backend });
73
+ }
74
+ catch (error) {
75
+ errors.push(error);
76
+ }
77
+ }
78
+ if (errors.length === 1)
79
+ throw errors[0];
80
+ const last = errors.at(-1);
81
+ throw new GGenError(last instanceof GGenError ? last.code : "BINARY_UNAVAILABLE", order.map((backend, i) => `${backend}: ${errors[i].message}`).join("; "), { cause: last });
82
+ }
83
+ async function detect(source, binaryDir, download, ensure) {
84
+ const key = platform();
85
+ if (key === "darwin-arm64")
86
+ return ["metal"];
87
+ const present = (await readdir(binaryDir).catch(() => []))
88
+ .filter((name) => name.startsWith(`${key}-`))
89
+ .map((name) => name.slice(key.length + 1))
90
+ .filter((b) => BACKENDS.includes(b));
91
+ const installed = [];
92
+ for (const b of present)
93
+ if (await exists(executable(binaryDir, b)))
94
+ installed.push(b);
95
+ const candidates = AUTO_ORDER.filter((b) => installed.includes(b) || (download && `${key}-${b}` in source.archives));
96
+ if (candidates.length === 0) {
97
+ const where = download ? `${binaryDir} or the manifest of ${source.version}` : binaryDir;
98
+ const rocm = installed.includes("rocm") ? '; pass backend: "rocm" to use rocm' : "";
99
+ throw new GGenError("BINARY_UNAVAILABLE", `no ggen binary for ${key} in ${where}${rocm}`);
100
+ }
101
+ if (candidates.length === 1 && candidates[0] === "cpu")
102
+ return ["cpu"];
103
+ const probes = [
104
+ ...candidates.filter((b) => b === "cpu"),
105
+ ...candidates.filter((b) => b !== "cpu" && installed.includes(b)),
106
+ ...candidates.filter((b) => b !== "cpu" && !installed.includes(b)),
107
+ ];
108
+ const failures = [];
109
+ for (const probe of probes) {
110
+ let available;
111
+ try {
112
+ available = await devices(await ensure(probe));
113
+ }
114
+ catch (error) {
115
+ failures.push(`${probe}: ${error.message}`);
116
+ continue;
117
+ }
118
+ const usable = candidates.filter((b) => available.has(b));
119
+ if (usable.length > 0)
120
+ return usable;
121
+ failures.push(`${probe}: none of ${candidates.join(", ")} has a device`);
122
+ break;
123
+ }
124
+ if (candidates.includes("cpu"))
125
+ return ["cpu"];
126
+ throw new GGenError("BINARY_UNAVAILABLE", `no ggen backend for ${key} runs here (${failures.join("; ")})`);
127
+ }
128
+ async function devices(binary) {
129
+ const child = spawn(binary, ["devices"], {
130
+ stdio: ["ignore", "pipe", "pipe"],
131
+ windowsHide: true,
132
+ });
133
+ let stdout = "";
134
+ let stderr = "";
135
+ child.stdout.setEncoding("utf8").on("data", (chunk) => (stdout += chunk));
136
+ child.stderr.setEncoding("utf8").on("data", (chunk) => (stderr += chunk));
137
+ const code = await new Promise((resolve, reject) => {
138
+ child.once("error", reject);
139
+ child.once("close", resolve);
140
+ }).catch((cause) => {
141
+ throw new GGenError("PROCESS_EXITED", `${binary} devices: ${String(cause)}`, { cause });
142
+ });
143
+ if (code !== 0) {
144
+ throw new GGenError("PROCESS_EXITED", `${binary} devices exited with ${code}`, {
145
+ stderr: stderr.slice(-8192),
146
+ });
147
+ }
148
+ const { devices } = JSON.parse(stdout);
149
+ return new Set(devices.map((device) => device.backend));
150
+ }
151
+ async function install(source, binaryDir, backend, onDownload) {
152
+ const key = `${platform()}-${backend}`;
153
+ const entry = source.archives[key];
154
+ if (!entry) {
155
+ throw new GGenError("BINARY_UNAVAILABLE", `no archive for ${key} in the manifest of ${source.version}`);
156
+ }
157
+ const dest = join(binaryDir, key);
158
+ await mkdir(binaryDir, { recursive: true });
159
+ const temp = await mkdtemp(join(binaryDir, `.${key}-`));
160
+ try {
161
+ const archive = join(temp, "archive.zip");
162
+ try {
163
+ await fetchArchive(entry, archive, (completed) => onDownload?.({ backend, completed, total: entry.size }));
164
+ await extractZip(archive, join(temp, key));
165
+ }
166
+ catch (cause) {
167
+ if (cause instanceof GGenError)
168
+ throw cause;
169
+ throw new GGenError("BINARY_UNAVAILABLE", `${entry.url}: ${String(cause)}`, { cause });
170
+ }
171
+ if (!(await exists(executable(temp, backend)))) {
172
+ throw new GGenError("BINARY_UNAVAILABLE", `${entry.url}: no ggen executable in the archive`);
173
+ }
174
+ if (process.platform !== "win32")
175
+ await chmod(executable(temp, backend), 0o755);
176
+ await writeFile(join(temp, key, ARCHIVE_DIGEST), `${entry.sha256}\n`);
177
+ await rename(join(temp, key), dest).catch(async (cause) => {
178
+ if (!(await exists(executable(binaryDir, backend)))) {
179
+ throw new GGenError("BINARY_UNAVAILABLE", `${dest} exists without the ggen executable; remove it (${String(cause)})`, { cause });
180
+ }
181
+ const recorded = await readFile(join(dest, ARCHIVE_DIGEST), "utf8").catch(() => "");
182
+ if (recorded.trim().toLowerCase() !== entry.sha256.toLowerCase()) {
183
+ throw new GGenError("BINARY_UNAVAILABLE", `${dest} holds another archive than ${entry.url}; remove it`, { cause });
184
+ }
185
+ });
186
+ }
187
+ finally {
188
+ await rm(temp, { recursive: true, force: true });
189
+ }
190
+ }
191
+ async function fetchArchive(entry, path, progress) {
192
+ const response = await fetch(entry.url);
193
+ if (!response.ok || !response.body) {
194
+ throw new GGenError("BINARY_UNAVAILABLE", `${entry.url}: HTTP ${response.status}`);
195
+ }
196
+ const hash = createHash("sha256");
197
+ const file = await open(path, "w");
198
+ let completed = 0;
199
+ try {
200
+ for await (const chunk of Readable.fromWeb(response.body)) {
201
+ hash.update(chunk);
202
+ await file.write(chunk);
203
+ completed += chunk.byteLength;
204
+ progress(completed);
205
+ }
206
+ }
207
+ finally {
208
+ await file.close();
209
+ }
210
+ const digest = hash.digest("hex");
211
+ if (digest !== entry.sha256.toLowerCase()) {
212
+ throw new GGenError("BINARY_UNAVAILABLE", `${entry.url}: SHA-256 ${digest} does not match ${entry.sha256}`);
213
+ }
214
+ }
@@ -0,0 +1,58 @@
1
+ import type { components } from "./openapi.ts";
2
+ type S = components["schemas"];
3
+ export type Health = S["Health"];
4
+ export type Job = S["Job"];
5
+ export type JobRequest = S["JobRequest"];
6
+ export type JobStatus = S["JobStatus"];
7
+ export type JobSummary = S["JobSummary"];
8
+ export type OperationDefinition = S["OperationDefinition"];
9
+ export type Upload = S["Upload"];
10
+ export type UploadId = S["UploadId"];
11
+ export type MediaType = Upload["mediaType"];
12
+ export type BinaryInput = Uint8Array | ArrayBuffer | Blob;
13
+ export interface GGenClientOptions {
14
+ baseUrl: string | URL;
15
+ apiKey?: string | undefined;
16
+ fetch?: typeof fetch | undefined;
17
+ }
18
+ export interface RequestOptions {
19
+ signal?: AbortSignal | undefined;
20
+ }
21
+ export interface GetJobOptions extends RequestOptions {
22
+ since?: number | undefined;
23
+ waitMs?: number | undefined;
24
+ }
25
+ export declare function isTerminal(status: JobStatus): boolean;
26
+ export declare function uploadId(data: BinaryInput): Promise<UploadId>;
27
+ /** HTTP client of `ggen serve`. */
28
+ export declare class GGenClient {
29
+ #private;
30
+ readonly baseUrl: URL;
31
+ constructor(options: GGenClientOptions);
32
+ health(options?: RequestOptions): Promise<Health>;
33
+ operations(options?: RequestOptions): Promise<OperationDefinition[]>;
34
+ unload(options?: RequestOptions): Promise<Health>;
35
+ submitJob(jobId: string, request: JobRequest, options?: RequestOptions): Promise<{
36
+ job: Job;
37
+ created: boolean;
38
+ }>;
39
+ listJobs(options?: RequestOptions & {
40
+ status?: readonly JobStatus[];
41
+ }): Promise<JobSummary[]>;
42
+ getJob(jobId: string, options?: GetJobOptions): Promise<Job>;
43
+ cancelJob(jobId: string, options?: RequestOptions): Promise<Job>;
44
+ deleteJob(jobId: string, options?: RequestOptions): Promise<void>;
45
+ getJobLog(jobId: string, options?: RequestOptions & {
46
+ offset?: number;
47
+ }): Promise<{
48
+ data: Uint8Array;
49
+ nextOffset: number;
50
+ }>;
51
+ /** The output `name`, or item `index` of an `images` output. */
52
+ getJobOutput(jobId: string, name: string, index?: number, options?: RequestOptions): Promise<ReadableStream<Uint8Array>>;
53
+ listUploads(options?: RequestOptions): Promise<Upload[]>;
54
+ putUpload(data: BinaryInput, mediaType: MediaType, options?: RequestOptions): Promise<Upload>;
55
+ hasUpload(id: UploadId, options?: RequestOptions): Promise<boolean>;
56
+ deleteUpload(id: UploadId, options?: RequestOptions): Promise<void>;
57
+ }
58
+ export {};
package/dist/client.js ADDED
@@ -0,0 +1,147 @@
1
+ import { GGenError } from "./errors.js";
2
+ const STATUS_CODES = {
3
+ 401: "UNAUTHORIZED",
4
+ 404: "NOT_FOUND",
5
+ 408: "REQUEST_TIMEOUT",
6
+ 409: "JOB_CONFLICT",
7
+ 413: "PAYLOAD_TOO_LARGE",
8
+ 422: "INPUT_INVALID",
9
+ };
10
+ export function isTerminal(status) {
11
+ return status === "succeeded" || status === "failed" || status === "cancelled";
12
+ }
13
+ async function toBytes(data) {
14
+ if (data instanceof Blob)
15
+ return new Uint8Array(await data.arrayBuffer());
16
+ return new Uint8Array(data instanceof ArrayBuffer ? data.slice(0) : data);
17
+ }
18
+ async function digest(bytes) {
19
+ const hash = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
20
+ return `sha256:${Array.from(hash, (b) => b.toString(16).padStart(2, "0")).join("")}`;
21
+ }
22
+ export async function uploadId(data) {
23
+ return digest(await toBytes(data));
24
+ }
25
+ /** HTTP client of `ggen serve`. */
26
+ export class GGenClient {
27
+ baseUrl;
28
+ #apiKey;
29
+ #fetch;
30
+ constructor(options) {
31
+ const base = new URL(options.baseUrl);
32
+ if (!base.pathname.endsWith("/"))
33
+ base.pathname += "/";
34
+ this.baseUrl = base;
35
+ this.#apiKey = options.apiKey;
36
+ this.#fetch = options.fetch ?? ((input, init) => fetch(input, init));
37
+ }
38
+ health(options) {
39
+ return this.#json("GET", "v1/health", options);
40
+ }
41
+ async operations(options) {
42
+ const body = await this.#json("GET", "v1/operations", options);
43
+ return body.operations;
44
+ }
45
+ unload(options) {
46
+ return this.#json("POST", "v1/unload", options);
47
+ }
48
+ async submitJob(jobId, request, options) {
49
+ const response = await this.#request("PUT", jobPath(jobId), options, {
50
+ body: JSON.stringify(request),
51
+ headers: { "Content-Type": "application/json" },
52
+ });
53
+ return { job: (await response.json()), created: response.status === 201 };
54
+ }
55
+ async listJobs(options = {}) {
56
+ const query = new URLSearchParams();
57
+ if (options.status?.length)
58
+ query.set("status", options.status.join(","));
59
+ const body = await this.#json("GET", withQuery("v1/jobs", query), options);
60
+ return body.jobs;
61
+ }
62
+ getJob(jobId, options = {}) {
63
+ const query = new URLSearchParams();
64
+ if (options.since !== undefined)
65
+ query.set("since", String(options.since));
66
+ if (options.waitMs !== undefined)
67
+ query.set("waitMs", String(options.waitMs));
68
+ return this.#json("GET", withQuery(jobPath(jobId), query), options);
69
+ }
70
+ cancelJob(jobId, options) {
71
+ return this.#json("POST", `${jobPath(jobId)}/cancel`, options);
72
+ }
73
+ async deleteJob(jobId, options) {
74
+ await this.#request("DELETE", jobPath(jobId), options);
75
+ }
76
+ async getJobLog(jobId, options = {}) {
77
+ const query = new URLSearchParams();
78
+ if (options.offset !== undefined)
79
+ query.set("offset", String(options.offset));
80
+ const response = await this.#request("GET", withQuery(`${jobPath(jobId)}/log`, query), options);
81
+ return {
82
+ data: new Uint8Array(await response.arrayBuffer()),
83
+ nextOffset: Number(response.headers.get("X-Next-Offset")),
84
+ };
85
+ }
86
+ /** The output `name`, or item `index` of an `images` output. */
87
+ async getJobOutput(jobId, name, index, options) {
88
+ const item = index === undefined ? "" : `/${index}`;
89
+ const path = `${jobPath(jobId)}/outputs/${encodeURIComponent(name)}${item}`;
90
+ const response = await this.#request("GET", path, options);
91
+ return response.body ?? new Blob().stream();
92
+ }
93
+ async listUploads(options) {
94
+ return (await this.#json("GET", "v1/uploads", options)).uploads;
95
+ }
96
+ async putUpload(data, mediaType, options) {
97
+ const bytes = await toBytes(data);
98
+ const response = await this.#request("PUT", uploadPath(await digest(bytes)), options, {
99
+ body: bytes,
100
+ headers: { "Content-Type": mediaType },
101
+ });
102
+ return (await response.json());
103
+ }
104
+ async hasUpload(id, options) {
105
+ return (await this.#request("HEAD", uploadPath(id), options, {}, [404])).ok;
106
+ }
107
+ async deleteUpload(id, options) {
108
+ await this.#request("DELETE", uploadPath(id), options);
109
+ }
110
+ async #json(method, path, options) {
111
+ return (await (await this.#request(method, path, options)).json());
112
+ }
113
+ async #request(method, path, options = {}, init = {}, allowed = []) {
114
+ const headers = new Headers(init.headers);
115
+ if (this.#apiKey !== undefined)
116
+ headers.set("Authorization", `Bearer ${this.#apiKey}`);
117
+ const response = await this.#fetch(new URL(path, this.baseUrl), {
118
+ method,
119
+ headers,
120
+ body: init.body ?? null,
121
+ signal: options.signal ?? null,
122
+ });
123
+ if (response.ok || allowed.includes(response.status))
124
+ return response;
125
+ const status = response.status;
126
+ const text = await response.text().catch(() => "");
127
+ let detail;
128
+ try {
129
+ detail = JSON.parse(text).error;
130
+ }
131
+ catch { }
132
+ if (detail) {
133
+ throw new GGenError(detail.code, detail.message, { field: detail.field, status });
134
+ }
135
+ throw new GGenError(STATUS_CODES[status] ?? "INTERNAL", text || `HTTP ${status}`, { status });
136
+ }
137
+ }
138
+ function jobPath(jobId) {
139
+ return `v1/jobs/${encodeURIComponent(jobId)}`;
140
+ }
141
+ function uploadPath(id) {
142
+ return `v1/uploads/${encodeURIComponent(id)}`;
143
+ }
144
+ function withQuery(path, query) {
145
+ const search = query.toString();
146
+ return search ? `${path}?${search}` : path;
147
+ }
@@ -0,0 +1,21 @@
1
+ import type { components } from "./openapi.ts";
2
+ export type GGenErrorCode = components["schemas"]["ErrorCode"] | "BINARY_UNAVAILABLE" | "PROCESS_EXITED" | "CANCELLED";
3
+ export interface GGenErrorDetails {
4
+ field?: string | undefined;
5
+ log?: string | undefined;
6
+ stderr?: string | undefined;
7
+ status?: number | undefined;
8
+ cause?: unknown;
9
+ }
10
+ export declare class GGenError extends Error {
11
+ readonly code: GGenErrorCode;
12
+ /** The input the error is about. */
13
+ readonly field: string | undefined;
14
+ /** The job log of a failed job. */
15
+ readonly log: string | undefined;
16
+ /** The end of the process's stderr when it exited. */
17
+ readonly stderr: string | undefined;
18
+ /** The HTTP status, from `GGenClient`. */
19
+ readonly status: number | undefined;
20
+ constructor(code: GGenErrorCode, message: string, details?: GGenErrorDetails);
21
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,20 @@
1
+ export class GGenError extends Error {
2
+ code;
3
+ /** The input the error is about. */
4
+ field;
5
+ /** The job log of a failed job. */
6
+ log;
7
+ /** The end of the process's stderr when it exited. */
8
+ stderr;
9
+ /** The HTTP status, from `GGenClient`. */
10
+ status;
11
+ constructor(code, message, details = {}) {
12
+ super(message, details.cause === undefined ? undefined : { cause: details.cause });
13
+ this.name = "GGenError";
14
+ this.code = code;
15
+ this.field = details.field;
16
+ this.log = details.log;
17
+ this.stderr = details.stderr;
18
+ this.status = details.status;
19
+ }
20
+ }
package/dist/ggen.d.ts ADDED
@@ -0,0 +1,81 @@
1
+ import { type GGenBackend, type GGenDownloadProgress } from "./binary.ts";
2
+ import { type GGenKinds } from "./kinds.ts";
3
+ import type { components } from "./openapi.ts";
4
+ type S = components["schemas"];
5
+ type MediaRef = S["MediaRef"];
6
+ export type GGenKind = keyof GGenKinds;
7
+ export type GGenRequest<K extends GGenKind> = GGenKinds[K]["request"];
8
+ export type GGenFamily = S["FetchRequest"]["family"];
9
+ /** Media are file paths, or `MediaRef` objects. */
10
+ export type GGenInputs<T> = T extends MediaRef ? Exclude<keyof T, "upload" | "path"> extends never ? string | T : {
11
+ [K in keyof T]: GGenInputs<T[K]>;
12
+ } : T extends readonly (infer U)[] ? GGenInputs<U>[] : T extends object ? {
13
+ [K in keyof T]: GGenInputs<T[K]>;
14
+ } : T;
15
+ export type GGenFormats<K extends GGenKind> = GGenRequest<K> extends {
16
+ formats?: infer F;
17
+ } ? F : undefined;
18
+ type GGenOutputs<K extends GGenKind, F> = F extends {
19
+ video?: infer V;
20
+ } ? unknown extends V ? GGenKinds[K]["outputs"] : F extends {
21
+ video: "png";
22
+ } ? GGenKinds[K]["frameOutputs"] : "png" extends V ? GGenKinds[K]["frameOutputs"] | GGenKinds[K]["outputs"] : GGenKinds[K]["outputs"] : GGenKinds[K]["outputs"];
23
+ /** With a `formats.video` that may be `"png"` but is not known to be, either shape. */
24
+ export type GGenResult<K extends GGenKind, F = undefined> = GGenOutputs<K, F> & {
25
+ /** The request as run, with defaults and `seed` filled in. */
26
+ request: GGenRequest<K>;
27
+ };
28
+ export interface GGenProgress {
29
+ status: S["JobStatus"];
30
+ queuePosition: number | null;
31
+ stage: string | undefined;
32
+ completed: number | undefined;
33
+ total: number | undefined;
34
+ }
35
+ export interface GGenJobOptions {
36
+ onProgress?: ((progress: GGenProgress) => void) | undefined;
37
+ signal?: AbortSignal | undefined;
38
+ /** Job ID. Defaults to a random UUID. */
39
+ id?: string | undefined;
40
+ }
41
+ export interface GGenGenerateOptions<K extends GGenKind, F> extends GGenJobOptions {
42
+ inputs: GGenInputs<GGenRequest<K>["inputs"]>;
43
+ params?: GGenRequest<K>["params"];
44
+ components?: GGenRequest<K>["components"];
45
+ formats?: F;
46
+ }
47
+ export interface GGenFetchOptions extends GGenJobOptions {
48
+ components?: S["FetchRequest"]["components"];
49
+ }
50
+ export interface GGenOptions {
51
+ /** `--model-dir`. Defaults to the binary's default, `~/.cache/ggen/models`. */
52
+ modelDir?: string | readonly string[] | undefined;
53
+ /** Defaults to `~/.cache/ggen/bin/<version>`. */
54
+ binaryDir?: string | undefined;
55
+ backend?: GGenBackend | "auto" | undefined;
56
+ /** `false` downloads neither the binary nor weights. With `url`, only the binary. */
57
+ download?: boolean | undefined;
58
+ onDownload?: ((progress: GGenDownloadProgress) => void) | undefined;
59
+ /** Relays jobs to the `ggen serve` at this URL. */
60
+ url?: string | undefined;
61
+ apiKey?: string | undefined;
62
+ /** Passed to the process as `HF_TOKEN`. */
63
+ hfToken?: string | undefined;
64
+ /** `fake` runs jobs without an engine or weights, as `--engine fake`. */
65
+ engine?: "native" | "fake" | undefined;
66
+ }
67
+ export declare class GGen implements AsyncDisposable {
68
+ #private;
69
+ readonly backend: GGenBackend;
70
+ private constructor();
71
+ static open(options?: GGenOptions): Promise<GGen>;
72
+ generate<K extends GGenKind, const F extends GGenFormats<K> | undefined = undefined>(kind: K, options: GGenGenerateOptions<K, F>): Promise<GGenResult<K, F>>;
73
+ /** Downloads the default weights of `family` without generating. */
74
+ fetch(family: GGenFamily, options?: GGenFetchOptions): Promise<void>;
75
+ /** The process ID of `ggen session`. */
76
+ get pid(): number | undefined;
77
+ /** Cancels unfinished jobs, removes unsaved outputs and ends the process. */
78
+ close(): Promise<void>;
79
+ [Symbol.asyncDispose](): Promise<void>;
80
+ }
81
+ export {};