@ownkeyhq/sdk 0.0.0-stage → 0.3.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.
@@ -0,0 +1,63 @@
1
+ import type { operations as Spec } from "./openapi.ts";
2
+ export type OpName = keyof Spec & string;
3
+ type Part<T> = [T] extends [never] ? object : T extends undefined ? object : NonNullable<T>;
4
+ type JsonBody<O> = O extends {
5
+ requestBody: {
6
+ content: {
7
+ "application/json": infer B;
8
+ };
9
+ };
10
+ } ? B : object;
11
+ export type Input<N extends OpName> = N extends OpName ? Part<Spec[N]["parameters"]["path"]> & Part<Spec[N]["parameters"]["query"]> & JsonBody<Spec[N]> : never;
12
+ export type Output<N extends OpName> = Spec[N]["responses"][200]["content"]["application/json"];
13
+ export type JsonSchema = {
14
+ type?: string | string[];
15
+ anyOf?: JsonSchema[];
16
+ items?: JsonSchema;
17
+ properties?: Record<string, JsonSchema>;
18
+ additionalProperties?: JsonSchema | boolean;
19
+ required?: string[];
20
+ description?: string;
21
+ default?: unknown;
22
+ enum?: unknown[];
23
+ };
24
+ export interface Operation {
25
+ name: string;
26
+ summary: string;
27
+ scope: string;
28
+ method: string;
29
+ path: string;
30
+ pathParams: string[];
31
+ fields: Record<string, JsonSchema>;
32
+ required: string[];
33
+ location: "query" | "body";
34
+ upload: boolean;
35
+ }
36
+ export interface Upload {
37
+ body: ReadableStream<Uint8Array> | Uint8Array<ArrayBuffer>;
38
+ length: number;
39
+ }
40
+ export type Fetch = (input: string, init: RequestInit) => Promise<Response>;
41
+ export interface ClientOptions {
42
+ baseUrl: string;
43
+ key: string;
44
+ fetch?: Fetch;
45
+ }
46
+ export declare class OwnkeyError extends Error {
47
+ readonly status: number;
48
+ readonly code: string;
49
+ constructor(status: number, code: string, message: string);
50
+ }
51
+ export declare function operations(): Operation[];
52
+ export interface Client {
53
+ call<N extends OpName>(name: N, input: Input<N>, upload?: Upload): Promise<Output<N>>;
54
+ }
55
+ export declare function createClient(options: Omit<ClientOptions, "key"> & {
56
+ key?: never;
57
+ }): Client;
58
+ export declare function createClient(options: ClientOptions): Client;
59
+ type Transfer = NonNullable<Output<"releases.prepareUpload">["transfer"]>;
60
+ export declare function releaseTransferUrl(value: string): string;
61
+ export declare function putReleaseFile(transfer: Transfer, upload: Upload, fetcher?: Fetch): Promise<void>;
62
+ export declare function releaseUploadRequestId(input: object): Promise<string>;
63
+ export {};
@@ -0,0 +1,153 @@
1
+ import spec from "../openapi.json" with { type: "json" };
2
+ export class OwnkeyError extends Error {
3
+ status;
4
+ code;
5
+ constructor(status, code, message) {
6
+ super(message);
7
+ this.name = "OwnkeyError";
8
+ this.status = status;
9
+ this.code = code;
10
+ }
11
+ }
12
+ function table() {
13
+ const out = new Map();
14
+ const paths = spec.paths;
15
+ for (const [path, methods] of Object.entries(paths)) {
16
+ for (const [method, op] of Object.entries(methods)) {
17
+ const fields = {};
18
+ const required = [];
19
+ for (const param of op.parameters) {
20
+ fields[param.name] = param.schema;
21
+ if (param.required)
22
+ required.push(param.name);
23
+ }
24
+ const body = op.requestBody?.content["application/json"]?.schema;
25
+ for (const [name, schema] of Object.entries(body?.properties ?? {}))
26
+ fields[name] = schema;
27
+ required.push(...(body?.required ?? []));
28
+ out.set(op.operationId, {
29
+ name: op.operationId,
30
+ summary: op.summary,
31
+ scope: op["x-scope"],
32
+ method: method.toUpperCase(),
33
+ path,
34
+ pathParams: op.parameters.filter((p) => p.in === "path").map((p) => p.name),
35
+ fields,
36
+ required,
37
+ location: body ? "body" : "query",
38
+ upload: op.requestBody?.content["application/octet-stream"] !== undefined,
39
+ });
40
+ }
41
+ }
42
+ return out;
43
+ }
44
+ const ops = table();
45
+ export function operations() {
46
+ return [...ops.values()];
47
+ }
48
+ function scalar(value) {
49
+ return typeof value === "object" && value !== null ? JSON.stringify(value) : String(value);
50
+ }
51
+ export function createClient(options) {
52
+ const send = options.fetch ?? ((input, init) => fetch(input, init));
53
+ const base = options.baseUrl.replace(/\/+$/, "");
54
+ async function request(name, input, upload) {
55
+ const op = ops.get(name);
56
+ if (!op)
57
+ throw new TypeError(`No operation "${name}"`);
58
+ const rest = { ...input };
59
+ let path = op.path;
60
+ for (const param of op.pathParams) {
61
+ const value = rest[param];
62
+ if (value === undefined || value === null || value === "") {
63
+ throw new TypeError(`"${name}" needs "${param}"`);
64
+ }
65
+ path = path.replace(`{${param}}`, encodeURIComponent(String(value)));
66
+ delete rest[param];
67
+ }
68
+ const url = new URL(base + path);
69
+ const headers = {};
70
+ if (options.key !== undefined)
71
+ headers.Authorization = `Bearer ${options.key}`;
72
+ const init = { method: op.method, headers };
73
+ if (op.location === "query") {
74
+ for (const [field, value] of Object.entries(rest)) {
75
+ if (value === undefined || !Object.hasOwn(op.fields, field))
76
+ continue;
77
+ for (const item of Array.isArray(value) ? value : [value]) {
78
+ url.searchParams.append(field, scalar(item));
79
+ }
80
+ }
81
+ }
82
+ else {
83
+ headers["Content-Type"] = "application/json";
84
+ init.body = JSON.stringify(rest);
85
+ }
86
+ if (op.upload) {
87
+ if (!upload)
88
+ throw new TypeError(`"${name}" needs a file`);
89
+ headers["Content-Type"] = "application/octet-stream";
90
+ headers["Content-Length"] = String(upload.length);
91
+ init.body = upload.body;
92
+ if (upload.body instanceof ReadableStream)
93
+ init.duplex = "half";
94
+ }
95
+ const res = await send(url.toString(), init);
96
+ const text = await res.text();
97
+ let body = null;
98
+ try {
99
+ body = text === "" ? null : JSON.parse(text);
100
+ }
101
+ catch { }
102
+ if (!res.ok) {
103
+ const error = body?.error;
104
+ throw new OwnkeyError(res.status, typeof error?.code === "string" ? error.code : `http_${res.status}`, typeof error?.message === "string" ? error.message : text.slice(0, 200));
105
+ }
106
+ return body;
107
+ }
108
+ return { call: request };
109
+ }
110
+ export function releaseTransferUrl(value) {
111
+ const url = URL.parse(value);
112
+ if (url?.protocol !== "https:" ||
113
+ !/^[a-f0-9]{32}\.r2\.cloudflarestorage\.com$/.test(url.host) ||
114
+ url.username ||
115
+ url.password) {
116
+ throw new OwnkeyError(0, "invalid_transfer", "The API returned an invalid upload destination");
117
+ }
118
+ return url.href;
119
+ }
120
+ export async function putReleaseFile(transfer, upload, fetcher = fetch) {
121
+ const url = releaseTransferUrl(transfer.url);
122
+ const streaming = upload.body instanceof ReadableStream;
123
+ let response;
124
+ try {
125
+ const init = {
126
+ method: "PUT",
127
+ headers: {
128
+ ...transfer.headers,
129
+ ...(streaming ? { "content-length": String(upload.length) } : {}),
130
+ },
131
+ credentials: "omit",
132
+ redirect: "error",
133
+ referrerPolicy: "no-referrer",
134
+ body: upload.body,
135
+ };
136
+ if (streaming)
137
+ init.duplex = "half";
138
+ response = await fetcher(url, init);
139
+ }
140
+ catch {
141
+ throw new OwnkeyError(0, "network", "The transfer stopped. Try the upload again.");
142
+ }
143
+ await response.body?.cancel();
144
+ if (!response.ok && response.status !== 412)
145
+ throw new OwnkeyError(response.status, "transfer_failed", "R2 refused the file transfer");
146
+ }
147
+ export async function releaseUploadRequestId(input) {
148
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(JSON.stringify(input)));
149
+ const hex = [...new Uint8Array(digest)]
150
+ .map((byte) => byte.toString(16).padStart(2, "0"))
151
+ .join("");
152
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-4${hex.slice(13, 16)}-8${hex.slice(17, 20)}-${hex.slice(20, 32)}`;
153
+ }
@@ -0,0 +1 @@
1
+ export { type Client, type ClientOptions, createClient, type Fetch, type Input, type JsonSchema, type Operation, type OpName, type Output, OwnkeyError, operations, putReleaseFile, releaseTransferUrl, releaseUploadRequestId, type Upload, } from "./client.ts";
@@ -0,0 +1 @@
1
+ export { createClient, OwnkeyError, operations, putReleaseFile, releaseTransferUrl, releaseUploadRequestId, } from "./client.js";