unfazed 0.6.0 → 0.6.1
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 +101 -29
- package/dist/cli/login.d.ts +129 -0
- package/dist/cli/login.js +596 -0
- package/dist/cli/login.js.map +1 -0
- package/dist/cli/workflow.d.ts +31 -0
- package/dist/cli/workflow.js +157 -0
- package/dist/cli/workflow.js.map +1 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +173 -0
- package/dist/cli.js.map +1 -0
- package/dist/client.d.ts +26 -5
- package/dist/client.js +93 -48
- package/dist/client.js.map +1 -1
- package/dist/credentials.d.ts +123 -0
- package/dist/credentials.js +317 -0
- package/dist/credentials.js.map +1 -0
- package/dist/index.d.ts +12 -2
- package/dist/index.js +11 -2
- package/dist/index.js.map +1 -1
- package/dist/remote/app.js +2 -1
- package/dist/remote/app.js.map +1 -1
- package/dist/remote/world.d.ts +2 -2
- package/dist/remote/world.js +32 -16
- package/dist/remote/world.js.map +1 -1
- package/dist/unfazed.d.ts +1 -1
- package/dist/unfazed.js +1 -1
- package/dist/unfazed.js.map +1 -1
- package/package.json +18 -6
package/dist/client.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
+
import { LOGIN_COMMAND, openStoredLogin } from "./credentials.js";
|
|
1
2
|
import { UnfazedAuthError, UnfazedConfigError, UnfazedGraphQLError, UnfazedHTTPError, UnfazedTimeoutError, } from "./errors.js";
|
|
2
3
|
/** SDK version, sent as the User-Agent. Keep in sync with package.json. */
|
|
3
|
-
export const VERSION = "0.6.
|
|
4
|
+
export const VERSION = "0.6.1";
|
|
4
5
|
/**
|
|
5
6
|
* Default GraphQL endpoint.
|
|
6
7
|
*
|
|
@@ -36,7 +37,7 @@ export const ENDPOINT_ENV_VAR = "UNFZ_API_URL";
|
|
|
36
37
|
* deliberately covers only the agent-facing ones.
|
|
37
38
|
*
|
|
38
39
|
* ```ts
|
|
39
|
-
* const client = new UnfazedClient();
|
|
40
|
+
* const client = new UnfazedClient(); // UNFZ_API_TOKEN, else `npx unfazed login`
|
|
40
41
|
* const data = await client.query<{ whoami: { name: string } }, never>(
|
|
41
42
|
* `query { whoami { name } }`,
|
|
42
43
|
* );
|
|
@@ -45,20 +46,13 @@ export const ENDPOINT_ENV_VAR = "UNFZ_API_URL";
|
|
|
45
46
|
export class UnfazedClient {
|
|
46
47
|
/** Resolved GraphQL endpoint URL. */
|
|
47
48
|
endpoint;
|
|
48
|
-
|
|
49
|
+
/** A fixed bearer token, or the stored login handing out refreshed ones. */
|
|
50
|
+
#auth;
|
|
49
51
|
#headers;
|
|
50
52
|
#timeoutMs;
|
|
51
53
|
#fetch;
|
|
52
54
|
constructor(options = {}) {
|
|
53
|
-
const
|
|
54
|
-
if (!token) {
|
|
55
|
-
throw new UnfazedAuthError(`unfazed: no API token. Pass { token } or set ${TOKEN_ENV_VAR}. ` +
|
|
56
|
-
`Get one at ${DEFAULT_BASE_URL}/auth.md`);
|
|
57
|
-
}
|
|
58
|
-
this.#token = token.trim();
|
|
59
|
-
this.endpoint = resolveEndpoint(options);
|
|
60
|
-
this.#headers = { ...(options.headers ?? {}) };
|
|
61
|
-
this.#timeoutMs = options.timeoutMs ?? 60_000;
|
|
55
|
+
const env = options.env ?? processEnv();
|
|
62
56
|
const injected = options.fetch;
|
|
63
57
|
if (injected) {
|
|
64
58
|
this.#fetch = injected;
|
|
@@ -71,9 +65,40 @@ export class UnfazedClient {
|
|
|
71
65
|
this.#fetch = globalFetch.bind(globalThis);
|
|
72
66
|
}
|
|
73
67
|
const ua = options.userAgent ?? `unfazed-sdk/${VERSION}`;
|
|
68
|
+
const configured = configuredEndpoint(options, env);
|
|
69
|
+
const token = options.token ?? env[TOKEN_ENV_VAR];
|
|
70
|
+
if (token?.trim()) {
|
|
71
|
+
this.#auth = { token: token.trim() };
|
|
72
|
+
this.endpoint = configured ?? DEFAULT_ENDPOINT;
|
|
73
|
+
}
|
|
74
|
+
else {
|
|
75
|
+
const stored = options.login === false
|
|
76
|
+
? {}
|
|
77
|
+
: openStoredLogin({
|
|
78
|
+
env,
|
|
79
|
+
...(configured ? { endpoint: configured } : {}),
|
|
80
|
+
fetch: this.#fetch,
|
|
81
|
+
// The edge refuses some generic agents; always name ourselves.
|
|
82
|
+
userAgent: ua || `unfazed-sdk/${VERSION}`,
|
|
83
|
+
});
|
|
84
|
+
if (!stored.login) {
|
|
85
|
+
throw new UnfazedAuthError(noTokenMessage(configured, stored.other?.endpoint));
|
|
86
|
+
}
|
|
87
|
+
this.#auth = { login: stored.login };
|
|
88
|
+
this.endpoint = stored.login.endpoint;
|
|
89
|
+
}
|
|
90
|
+
this.#headers = { ...(options.headers ?? {}) };
|
|
91
|
+
this.#timeoutMs = options.timeoutMs ?? 60_000;
|
|
74
92
|
if (ua)
|
|
75
93
|
this.#headers["User-Agent"] = ua;
|
|
76
94
|
}
|
|
95
|
+
/**
|
|
96
|
+
* Where the bearer token comes from: `"token"` (passed or
|
|
97
|
+
* `UNFZ_API_TOKEN`) or `"login"` (the stored login of `npx unfazed login`).
|
|
98
|
+
*/
|
|
99
|
+
get authSource() {
|
|
100
|
+
return "login" in this.#auth ? "login" : "token";
|
|
101
|
+
}
|
|
77
102
|
/** Runs a query document. Identical wire behaviour to {@link mutate}. */
|
|
78
103
|
query(document, variables, options) {
|
|
79
104
|
return this.request(document, variables, options);
|
|
@@ -94,7 +119,6 @@ export class UnfazedClient {
|
|
|
94
119
|
*/
|
|
95
120
|
async request(document, variables, options = {}) {
|
|
96
121
|
const timeoutMs = options.timeoutMs ?? this.#timeoutMs;
|
|
97
|
-
const { signal, cleanup, didTimeout } = makeSignal(timeoutMs, options.signal);
|
|
98
122
|
// `document` may be a TypedDocumentString (a String object). JSON.stringify
|
|
99
123
|
// would serialise that fine, but String(...) keeps the wire body a plain
|
|
100
124
|
// primitive regardless of how the caller obtained the document.
|
|
@@ -103,27 +127,62 @@ export class UnfazedClient {
|
|
|
103
127
|
...(variables === undefined ? {} : { variables }),
|
|
104
128
|
...(options.operationName ? { operationName: options.operationName } : {}),
|
|
105
129
|
});
|
|
130
|
+
let token = await this.#token();
|
|
131
|
+
let { response, text } = await this.#send(body, token, timeoutMs, options.signal);
|
|
132
|
+
// A stored login's access token can be refused before its recorded
|
|
133
|
+
// expiry (the clock, a sign-out elsewhere): refresh once and retry. A
|
|
134
|
+
// fixed token has nothing to refresh.
|
|
135
|
+
if (response.status === 401 && "login" in this.#auth) {
|
|
136
|
+
token = await this.#auth.login.refresh(token);
|
|
137
|
+
({ response, text } = await this.#send(body, token, timeoutMs, options.signal));
|
|
138
|
+
}
|
|
139
|
+
if (!response.ok) {
|
|
140
|
+
throw new UnfazedHTTPError(response.status, text, this.endpoint);
|
|
141
|
+
}
|
|
142
|
+
let parsed;
|
|
143
|
+
try {
|
|
144
|
+
parsed = JSON.parse(text);
|
|
145
|
+
}
|
|
146
|
+
catch {
|
|
147
|
+
throw new UnfazedHTTPError(response.status, text, this.endpoint);
|
|
148
|
+
}
|
|
149
|
+
// A GraphQL 200 can still be a failure, and can be a PARTIAL failure: the
|
|
150
|
+
// batched writeFiles document resolves each aliased field independently.
|
|
151
|
+
// Attaching `data` to the error is what lets a caller see which writes
|
|
152
|
+
// landed before the failing one.
|
|
153
|
+
if (parsed.errors?.length) {
|
|
154
|
+
throw new UnfazedGraphQLError(parsed.errors, parsed.data);
|
|
155
|
+
}
|
|
156
|
+
if (parsed.data === undefined || parsed.data === null) {
|
|
157
|
+
throw new UnfazedGraphQLError([{ message: "response contained neither data nor errors" }], undefined);
|
|
158
|
+
}
|
|
159
|
+
return parsed.data;
|
|
160
|
+
}
|
|
161
|
+
#token() {
|
|
162
|
+
return "login" in this.#auth ? this.#auth.login.token() : Promise.resolve(this.#auth.token);
|
|
163
|
+
}
|
|
164
|
+
async #send(body, token, timeoutMs, external) {
|
|
165
|
+
const { signal, cleanup, didTimeout } = makeSignal(timeoutMs, external);
|
|
106
166
|
// The deadline covers BOTH phases — headers AND body. A proxy that answers
|
|
107
167
|
// with headers and then stalls the body is a real failure mode, and
|
|
108
168
|
// stopping the clock at the end of `fetch()` would leave `response.text()`
|
|
109
169
|
// hanging forever. `untilAborted` additionally races the signal itself, so
|
|
110
170
|
// an injected transport that ignores `signal` still cannot outlive the
|
|
111
171
|
// timeout.
|
|
112
|
-
let response;
|
|
113
|
-
let text;
|
|
114
172
|
try {
|
|
115
|
-
response = await untilAborted(this.#fetch(this.endpoint, {
|
|
173
|
+
const response = await untilAborted(this.#fetch(this.endpoint, {
|
|
116
174
|
method: "POST",
|
|
117
175
|
headers: {
|
|
118
176
|
...this.#headers,
|
|
119
177
|
"Content-Type": "application/json",
|
|
120
178
|
Accept: "application/json",
|
|
121
|
-
Authorization: `Bearer ${
|
|
179
|
+
Authorization: `Bearer ${token}`,
|
|
122
180
|
},
|
|
123
181
|
body,
|
|
124
182
|
...(signal ? { signal } : {}),
|
|
125
183
|
}), signal);
|
|
126
|
-
text = await untilAborted(response.text(), signal);
|
|
184
|
+
const text = await untilAborted(response.text(), signal);
|
|
185
|
+
return { response, text };
|
|
127
186
|
}
|
|
128
187
|
catch (cause) {
|
|
129
188
|
if (didTimeout()) {
|
|
@@ -137,50 +196,36 @@ export class UnfazedClient {
|
|
|
137
196
|
finally {
|
|
138
197
|
cleanup();
|
|
139
198
|
}
|
|
140
|
-
if (!response.ok) {
|
|
141
|
-
throw new UnfazedHTTPError(response.status, text, this.endpoint);
|
|
142
|
-
}
|
|
143
|
-
let parsed;
|
|
144
|
-
try {
|
|
145
|
-
parsed = JSON.parse(text);
|
|
146
|
-
}
|
|
147
|
-
catch {
|
|
148
|
-
throw new UnfazedHTTPError(response.status, text, this.endpoint);
|
|
149
|
-
}
|
|
150
|
-
// A GraphQL 200 can still be a failure, and can be a PARTIAL failure: the
|
|
151
|
-
// batched writeFiles document resolves each aliased field independently.
|
|
152
|
-
// Attaching `data` to the error is what lets a caller see which writes
|
|
153
|
-
// landed before the failing one.
|
|
154
|
-
if (parsed.errors?.length) {
|
|
155
|
-
throw new UnfazedGraphQLError(parsed.errors, parsed.data);
|
|
156
|
-
}
|
|
157
|
-
if (parsed.data === undefined || parsed.data === null) {
|
|
158
|
-
throw new UnfazedGraphQLError([{ message: "response contained neither data nor errors" }], undefined);
|
|
159
|
-
}
|
|
160
|
-
return parsed.data;
|
|
161
199
|
}
|
|
162
200
|
}
|
|
163
|
-
|
|
201
|
+
/** The endpoint the options or `UNFZ_API_URL` name, or undefined for the default. */
|
|
202
|
+
function configuredEndpoint(options, env) {
|
|
164
203
|
if (options.endpoint)
|
|
165
204
|
return options.endpoint;
|
|
166
205
|
if (options.baseUrl)
|
|
167
206
|
return trimSlash(options.baseUrl) + GRAPHQL_PATH;
|
|
168
|
-
const
|
|
207
|
+
const fromEnv = env[ENDPOINT_ENV_VAR];
|
|
169
208
|
// UNFZ_API_URL is documented as the full /query URL and is used verbatim.
|
|
170
209
|
// Tolerate a bare origin anyway, since that is the obvious mistake and
|
|
171
210
|
// guessing right costs nothing.
|
|
172
|
-
if (
|
|
173
|
-
const trimmed = trimSlash(
|
|
211
|
+
if (fromEnv) {
|
|
212
|
+
const trimmed = trimSlash(fromEnv);
|
|
174
213
|
return /\/query$|\/graphql$/.test(trimmed) ? trimmed : trimmed + GRAPHQL_PATH;
|
|
175
214
|
}
|
|
176
|
-
return
|
|
215
|
+
return undefined;
|
|
216
|
+
}
|
|
217
|
+
function noTokenMessage(endpoint, otherLogin) {
|
|
218
|
+
if (endpoint && otherLogin) {
|
|
219
|
+
return (`unfazed: no API token for ${endpoint}: the stored login is for ${otherLogin}. ` +
|
|
220
|
+
`Run \`${ENDPOINT_ENV_VAR}=${endpoint} ${LOGIN_COMMAND}\`, or pass { token } / set ${TOKEN_ENV_VAR}.`);
|
|
221
|
+
}
|
|
222
|
+
return (`unfazed: not signed in. Run \`${LOGIN_COMMAND}\` to sign in with your account, ` +
|
|
223
|
+
`or pass { token } / set ${TOKEN_ENV_VAR} (an agent token: ${DEFAULT_BASE_URL}/auth.md).`);
|
|
177
224
|
}
|
|
178
|
-
function
|
|
225
|
+
function processEnv() {
|
|
179
226
|
// Guarded: the SDK must also work in a browser or worker, where there is no
|
|
180
227
|
// `process` at all.
|
|
181
|
-
|
|
182
|
-
?.env;
|
|
183
|
-
return env?.[name] || undefined;
|
|
228
|
+
return globalThis.process?.env ?? {};
|
|
184
229
|
}
|
|
185
230
|
function trimSlash(u) {
|
|
186
231
|
return u.replace(/\/+$/, "");
|
package/dist/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,gBAAgB,EAChB,kBAAkB,EAClB,mBAAmB,EACnB,gBAAgB,EAChB,mBAAmB,GAEpB,MAAM,aAAa,CAAC;AAErB,2EAA2E;AAC3E,MAAM,CAAC,MAAM,OAAO,GAAG,OAAO,CAAC;AAE/B;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,2BAA2B,CAAC;AAE5D,iFAAiF;AACjF,MAAM,CAAC,MAAM,gBAAgB,GAAG,qBAAqB,CAAC;AAEtD,oDAAoD;AACpD,MAAM,CAAC,MAAM,YAAY,GAAG,QAAQ,CAAC;AAErC;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,aAAa,GAAG,gBAAgB,CAAC;AAE9C,kEAAkE;AAClE,MAAM,CAAC,MAAM,gBAAgB,GAAG,cAAc,CAAC;AA+E/C;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,OAAO,aAAa;IACxB,qCAAqC;IAC5B,QAAQ,CAAS;IAEjB,MAAM,CAAS;IACf,QAAQ,CAAyB;IACjC,UAAU,CAAS;IACnB,MAAM,CAAY;IAE3B,YAAY,UAAyB,EAAE;QACrC,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,IAAI,OAAO,CAAC,aAAa,CAAC,CAAC;QACtD,IAAI,CAAC,KAAK,EAAE,CAAC;YACX,MAAM,IAAI,gBA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C,CAAC,CAAC,EAAE,CAAC;YACzC,OAAO,EAAE,GAAG,EAAE,GAAE,CAAC;YACjB,UAAU,EAAE,GAAG,EAAE,CAAC,KAAK;SACxB,CAAC;IACJ,CAAC;IAED,MAAM,UAAU,GAAG,IAAI,eAAe,EAAE,CAAC;IACzC,IAAI,QAAQ,GAAG,KAAK,CAAC;IACrB,IAAI,KAAgD,CAAC;IAErD,IAAI,SAAS,GAAG,CAAC,EAAE,CAAC;QAClB,KAAK,GAAG,UAAU,CAAC,GAAG,EAAE;YACtB,QAAQ,GAAG,IAAI,CAAC;YAChB,UAAU,CAAC,KAAK,EAAE,CAAC;QACrB,CAAC,EAAE,SAAS,CAAC,CAAC;IAChB,CAAC;IAED,MAAM,eAAe,GAAG,GAAG,EAAE,CAAC,UAAU,CAAC,KAAK,EAAE,CAAC;IACjD,IAAI,QAAQ,EAAE,CAAC;QACb,IAAI,QAAQ,CAAC,OAAO;YAAE,UAAU,CAAC,KAAK,EAAE,CAAC;;YACpC,QAAQ,CAAC,gBAAgB,CAAC,OAAO,EAAE,eAAe,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;IAC3E,CAAC;IAED,OAAO;QACL,MAAM,EAAE,UAAU,CAAC,MAAM;QACzB,OAAO,EAAE,GAAG,EAAE;YACZ,IAAI,KAAK,KAAK,SAAS;gBAAE,YAAY,CAAC,KAAK,CAAC,CAAC;YAC7C,QAAQ,EAAE,mBAAmB,CAAC,OAAO,EAAE,eAAe,CAAC,CAAC;QAC1D,CAAC;QACD,UAAU,EAAE,GAAG,EAAE,CAAC,QAAQ;KAC3B,CAAC;AACJ,CAAC","sourcesContent":["import {\n UnfazedAuthError,\n UnfazedConfigError,\n UnfazedGraphQLError,\n UnfazedHTTPError,\n UnfazedTimeoutError,\n type GraphQLResponseError,\n} from \"./errors.js\";\n\n/** SDK version, sent as the User-Agent. Keep in sync with package.json. */\nexport const VERSION = \"0.6.0\";\n\n/**\n * Default GraphQL endpoint.\n *\n * Note this is the FULL endpoint, not an origin: the platform's own documented\n * convention (`UNFZ_API_URL=\"https://unfazed.dev/query\"`, and cmd/showcase-deploy\n * in the unfazed repo) treats the /query URL as the configurable unit, so the\n * SDK matches it rather than inventing a base-URL convention.\n */\nexport const DEFAULT_ENDPOINT = \"https://unfazed.dev/query\";\n\n/** Platform origin, used to derive the endpoint when only `baseUrl` is given. */\nexport const DEFAULT_BASE_URL = \"https://unfazed.dev\";\n\n/** Path of the GraphQL endpoint under an origin. */\nexport const GRAPHQL_PATH = \"/query\";\n\n/**\n * Environment variable holding the bearer token.\n *\n * This is the platform's documented name (docs/agent-deployments.md,\n * internal/agentdocs/reference.md). It accepts either an operator API token or\n * an agent access token from POST /agents/register — /query takes both as\n * plain bearers.\n */\nexport const TOKEN_ENV_VAR = \"UNFZ_API_TOKEN\";\n\n/** Environment variable holding the full GraphQL endpoint URL. */\nexport const ENDPOINT_ENV_VAR = \"UNFZ_API_URL\";\n\n/** Minimal structural type of the `fetch` the transport needs. */\nexport type FetchLike = (\n input: string,\n init: {\n method: string;\n headers: Record<string, string>;\n body: string;\n signal?: AbortSignal;\n },\n) => Promise<{\n ok: boolean;\n status: number;\n text(): Promise<string>;\n}>;\n\nexport interface ClientOptions {\n /**\n * Bearer token. Falls back to `UNFZ_API_TOKEN`. Get one from\n * https://unfazed.dev/auth.md — the same token the MCP server uses.\n */\n token?: string;\n /**\n * Full GraphQL endpoint URL. Wins over `baseUrl`. Falls back to\n * `UNFZ_API_URL`, then {@link DEFAULT_ENDPOINT}.\n */\n endpoint?: string;\n /**\n * Platform origin; `/query` is appended. Convenience for self-hosted or\n * staging control planes where only the host differs.\n */\n baseUrl?: string;\n /** Extra headers merged into every request. Authorization always wins. */\n headers?: Record<string, string>;\n /**\n * Per-request timeout in ms. Default 60_000. Pass 0 to disable.\n *\n * Bounds the WHOLE request — connect, headers and reading the response body —\n * so a proxy that answers with headers and then stalls still fails on time.\n */\n timeoutMs?: number;\n /** Injection point for tests and instrumented/proxied transports. */\n fetch?: FetchLike;\n /** Overrides the default `unfazed-sdk/<version>` User-Agent. */\n userAgent?: string;\n}\n\n/**\n * A GraphQL document.\n *\n * Structural rather than `string & {...}` on purpose: graphql-codegen emits\n * `TypedDocumentString`, a String SUBCLASS, which is not assignable to the\n * primitive `string`. Requiring only `toString()` plus the optional phantom\n * `__apiType` lets three things through with full inference:\n *\n * - generated `TypedDocumentString` documents (types inferred),\n * - documents assembled at runtime, like the batched writeFiles mutation,\n * - plain template-literal strings a caller wrote by hand.\n */\nexport interface GraphQLDocument<TResult, TVariables> {\n /** Phantom type carrier. Never called; present only to bind the generics. */\n __apiType?: (variables: TVariables) => TResult;\n toString(): string;\n}\n\n/** Result type carried by a typed document. */\nexport type ResultOf<T> = T extends GraphQLDocument<infer R, infer _V> ? R : unknown;\n\n/** Variables type carried by a typed document. */\nexport type VariablesOf<T> = T extends GraphQLDocument<infer _R, infer V> ? V : never;\n\n/** Per-request knobs. */\nexport interface RequestOptions {\n signal?: AbortSignal;\n timeoutMs?: number;\n operationName?: string;\n}\n\n/**\n * Layer 1 — a typed, dependency-free GraphQL transport over `fetch`.\n *\n * This is the SDK's entire networking surface. It understands auth, timeouts\n * and the GraphQL error envelope, and nothing about deployments. The workflow\n * layer ({@link import(\"./unfazed.js\").Unfazed}) is built strictly on top of\n * it, so you can always drop down here for any operation the workflow layer\n * does not wrap — the schema has ~660 fields and the workflow layer\n * deliberately covers only the agent-facing ones.\n *\n * ```ts\n * const client = new UnfazedClient(); // reads UNFZ_API_TOKEN\n * const data = await client.query<{ whoami: { name: string } }, never>(\n * `query { whoami { name } }`,\n * );\n * ```\n */\nexport class UnfazedClient {\n /** Resolved GraphQL endpoint URL. */\n readonly endpoint: string;\n\n readonly #token: string;\n readonly #headers: Record<string, string>;\n readonly #timeoutMs: number;\n readonly #fetch: FetchLike;\n\n constructor(options: ClientOptions = {}) {\n const token = options.token ?? readEnv(TOKEN_ENV_VAR);\n if (!token) {\n throw new UnfazedAuthError(\n `unfazed: no API token. Pass { token } or set ${TOKEN_ENV_VAR}. ` +\n `Get one at ${DEFAULT_BASE_URL}/auth.md`,\n );\n }\n this.#token = token.trim();\n\n this.endpoint = resolveEndpoint(options);\n\n this.#headers = { ...(options.headers ?? {}) };\n this.#timeoutMs = options.timeoutMs ?? 60_000;\n\n const injected = options.fetch;\n if (injected) {\n this.#fetch = injected;\n } else {\n const globalFetch = (globalThis as { fetch?: unknown }).fetch;\n if (typeof globalFetch !== \"function\") {\n throw new UnfazedConfigError(\n \"unfazed: no global fetch. Use Bun, Node >= 20, or pass { fetch } to the client.\",\n );\n }\n this.#fetch = globalFetch.bind(globalThis) as FetchLike;\n }\n\n const ua = options.userAgent ?? `unfazed-sdk/${VERSION}`;\n if (ua) this.#headers[\"User-Agent\"] = ua;\n }\n\n /** Runs a query document. Identical wire behaviour to {@link mutate}. */\n query<TResult, TVariables>(\n document: GraphQLDocument<TResult, TVariables>,\n variables?: TVariables,\n options?: RequestOptions,\n ): Promise<TResult> {\n return this.request(document, variables, options);\n }\n\n /**\n * Runs a mutation document. Distinct from {@link query} for call-site\n * readability only — GraphQL over HTTP POST makes no distinction.\n */\n mutate<TResult, TVariables>(\n document: GraphQLDocument<TResult, TVariables>,\n variables?: TVariables,\n options?: RequestOptions,\n ): Promise<TResult> {\n return this.request(document, variables, options);\n }\n\n /**\n * The single code path behind {@link query} and {@link mutate}.\n *\n * Throws {@link UnfazedHTTPError} on non-2xx, {@link UnfazedGraphQLError}\n * when the body carries `errors`, {@link UnfazedTimeoutError} on timeout or\n * abort. Resolves to the `data` object on success.\n */\n async request<TResult = unknown>(\n document: string | { toString(): string },\n variables?: unknown,\n options: RequestOptions = {},\n ): Promise<TResult> {\n const timeoutMs = options.timeoutMs ?? this.#timeoutMs;\n const { signal, cleanup, didTimeout } = makeSignal(timeoutMs, options.signal);\n\n // `document` may be a TypedDocumentString (a String object). JSON.stringify\n // would serialise that fine, but String(...) keeps the wire body a plain\n // primitive regardless of how the caller obtained the document.\n const body = JSON.stringify({\n query: String(document),\n ...(variables === undefined ? {} : { variables }),\n ...(options.operationName ? { operationName: options.operationName } : {}),\n });\n\n // The deadline covers BOTH phases — headers AND body. A proxy that answers\n // with headers and then stalls the body is a real failure mode, and\n // stopping the clock at the end of `fetch()` would leave `response.text()`\n // hanging forever. `untilAborted` additionally races the signal itself, so\n // an injected transport that ignores `signal` still cannot outlive the\n // timeout.\n let response: Awaited<ReturnType<FetchLike>>;\n let text: string;\n try {\n response = await untilAborted(\n this.#fetch(this.endpoint, {\n method: \"POST\",\n headers: {\n ...this.#headers,\n \"Content-Type\": \"application/json\",\n Accept: \"application/json\",\n Authorization: `Bearer ${this.#token}`,\n },\n body,\n ...(signal ? { signal } : {}),\n }),\n signal,\n );\n text = await untilAborted(response.text(), signal);\n } catch (cause) {\n if (didTimeout()) {\n throw new UnfazedTimeoutError(`unfazed: request timed out after ${timeoutMs}ms`, { cause });\n }\n if (isAbort(cause)) {\n throw new UnfazedTimeoutError(\"unfazed: request aborted\", { cause });\n }\n throw cause;\n } finally {\n cleanup();\n }\n\n if (!response.ok) {\n throw new UnfazedHTTPError(response.status, text, this.endpoint);\n }\n\n let parsed: { data?: TResult; errors?: GraphQLResponseError[] };\n try {\n parsed = JSON.parse(text) as typeof parsed;\n } catch {\n throw new UnfazedHTTPError(response.status, text, this.endpoint);\n }\n\n // A GraphQL 200 can still be a failure, and can be a PARTIAL failure: the\n // batched writeFiles document resolves each aliased field independently.\n // Attaching `data` to the error is what lets a caller see which writes\n // landed before the failing one.\n if (parsed.errors?.length) {\n throw new UnfazedGraphQLError(parsed.errors, parsed.data);\n }\n if (parsed.data === undefined || parsed.data === null) {\n throw new UnfazedGraphQLError(\n [{ message: \"response contained neither data nor errors\" }],\n undefined,\n );\n }\n return parsed.data;\n }\n}\n\nfunction resolveEndpoint(options: ClientOptions): string {\n if (options.endpoint) return options.endpoint;\n if (options.baseUrl) return trimSlash(options.baseUrl) + GRAPHQL_PATH;\n const env = readEnv(ENDPOINT_ENV_VAR);\n // UNFZ_API_URL is documented as the full /query URL and is used verbatim.\n // Tolerate a bare origin anyway, since that is the obvious mistake and\n // guessing right costs nothing.\n if (env) {\n const trimmed = trimSlash(env);\n return /\\/query$|\\/graphql$/.test(trimmed) ? trimmed : trimmed + GRAPHQL_PATH;\n }\n return DEFAULT_ENDPOINT;\n}\n\nfunction readEnv(name: string): string | undefined {\n // Guarded: the SDK must also work in a browser or worker, where there is no\n // `process` at all.\n const env = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process\n ?.env;\n return env?.[name] || undefined;\n}\n\nfunction trimSlash(u: string): string {\n return u.replace(/\\/+$/, \"\");\n}\n\nfunction isAbort(e: unknown): boolean {\n return typeof e === \"object\" && e !== null && (e as { name?: string }).name === \"AbortError\";\n}\n\nfunction abortError(): Error {\n const e = new Error(\"The operation was aborted.\");\n e.name = \"AbortError\";\n return e;\n}\n\n/**\n * Settles with `promise`, or rejects the moment `signal` aborts.\n *\n * A global `fetch` honours the signal for headers and body alike, but an\n * injected {@link FetchLike} — a proxy, an instrumented transport, a test\n * double — need not. Racing the signal makes the timeout an upper bound on the\n * whole request regardless of what the transport does with it. The loser's\n * rejection is swallowed by the already-settled promise rather than surfacing\n * as an unhandled rejection.\n */\nfunction untilAborted<T>(promise: Promise<T>, signal: AbortSignal | undefined): Promise<T> {\n if (!signal) return promise;\n if (signal.aborted) return Promise.reject(abortError());\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => reject(abortError());\n signal.addEventListener(\"abort\", onAbort, { once: true });\n const done = () => signal.removeEventListener(\"abort\", onAbort);\n promise.then(\n (value) => {\n done();\n resolve(value);\n },\n (error: unknown) => {\n done();\n reject(error as Error);\n },\n );\n });\n}\n\n/**\n * Combines the request timeout with any caller-supplied signal.\n *\n * `didTimeout` is tracked separately from the abort so a caller's own\n * cancellation is not mislabelled as a timeout in the thrown message.\n */\nfunction makeSignal(\n timeoutMs: number,\n external?: AbortSignal,\n): { signal?: AbortSignal; cleanup: () => void; didTimeout: () => boolean } {\n if (!timeoutMs && !external) return { cleanup: () => {}, didTimeout: () => false };\n if (typeof AbortController !== \"function\") {\n return {\n ...(external ? { signal: external } : {}),\n cleanup: () => {},\n didTimeout: () => false,\n };\n }\n\n const controller = new AbortController();\n let timedOut = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n if (timeoutMs > 0) {\n timer = setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, timeoutMs);\n }\n\n const onExternalAbort = () => controller.abort();\n if (external) {\n if (external.aborted) controller.abort();\n else external.addEventListener(\"abort\", onExternalAbort, { once: true });\n }\n\n return {\n signal: controller.signal,\n cleanup: () => {\n if (timer !== undefined) clearTimeout(timer);\n external?.removeEventListener(\"abort\", onExternalAbort);\n },\n didTimeout: () => timedOut,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,eAAe,EAAoB,MAAM,kBAAkB,CAAC;AACpF,OAAO,EACL,gBAAgB,EAChB,kBAAkB,EAClB,mBAAmB,EACnB,gBAAgB,EAChB,mBAAmB,GAEpB,MAAM,aAAa,CAAC;AAErB,2EAA2E;AAC3E,MAAM,CAAC,MAAM,OAAO,GAAG,OAAO,CAAC;AAE/B;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,2BAA2B,CAAC;AAE5D,iFAAiF;AACjF,MAAM,CAAC,MAAM,gBAAgB,GAAG,qBAAqB,CAAC;AAEtD,oDAAoD;AACpD,MAAM,CAAC,MAAM,YAAY,GAAG,QAAQ,CAAC;AAErC;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,aAAa,GAAG,gBAAgB,CAAC;AAE9C,kEAAkE;AAClE,MAAM,CAAC,MAAM,gBAAgB,GAAG,cAAc,CAAC;AA+F/C;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,OAAO,aAAa;IACxB,qCAAqC;IAC5B,QAAQ,CAAS;IA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,GAAG,IAAI,eAAe,EAAE,CAAC;IACzC,IAAI,QAAQ,GAAG,KAAK,CAAC;IACrB,IAAI,KAAgD,CAAC;IAErD,IAAI,SAAS,GAAG,CAAC,EAAE,CAAC;QAClB,KAAK,GAAG,UAAU,CAAC,GAAG,EAAE;YACtB,QAAQ,GAAG,IAAI,CAAC;YAChB,UAAU,CAAC,KAAK,EAAE,CAAC;QACrB,CAAC,EAAE,SAAS,CAAC,CAAC;IAChB,CAAC;IAED,MAAM,eAAe,GAAG,GAAG,EAAE,CAAC,UAAU,CAAC,KAAK,EAAE,CAAC;IACjD,IAAI,QAAQ,EAAE,CAAC;QACb,IAAI,QAAQ,CAAC,OAAO;YAAE,UAAU,CAAC,KAAK,EAAE,CAAC;;YACpC,QAAQ,CAAC,gBAAgB,CAAC,OAAO,EAAE,eAAe,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;IAC3E,CAAC;IAED,OAAO;QACL,MAAM,EAAE,UAAU,CAAC,MAAM;QACzB,OAAO,EAAE,GAAG,EAAE;YACZ,IAAI,KAAK,KAAK,SAAS;gBAAE,YAAY,CAAC,KAAK,CAAC,CAAC;YAC7C,QAAQ,EAAE,mBAAmB,CAAC,OAAO,EAAE,eAAe,CAAC,CAAC;QAC1D,CAAC;QACD,UAAU,EAAE,GAAG,EAAE,CAAC,QAAQ;KAC3B,CAAC;AACJ,CAAC","sourcesContent":["import { LOGIN_COMMAND, openStoredLogin, type StoredLogin } from \"./credentials.js\";\nimport {\n UnfazedAuthError,\n UnfazedConfigError,\n UnfazedGraphQLError,\n UnfazedHTTPError,\n UnfazedTimeoutError,\n type GraphQLResponseError,\n} from \"./errors.js\";\n\n/** SDK version, sent as the User-Agent. Keep in sync with package.json. */\nexport const VERSION = \"0.6.1\";\n\n/**\n * Default GraphQL endpoint.\n *\n * Note this is the FULL endpoint, not an origin: the platform's own documented\n * convention (`UNFZ_API_URL=\"https://unfazed.dev/query\"`, and cmd/showcase-deploy\n * in the unfazed repo) treats the /query URL as the configurable unit, so the\n * SDK matches it rather than inventing a base-URL convention.\n */\nexport const DEFAULT_ENDPOINT = \"https://unfazed.dev/query\";\n\n/** Platform origin, used to derive the endpoint when only `baseUrl` is given. */\nexport const DEFAULT_BASE_URL = \"https://unfazed.dev\";\n\n/** Path of the GraphQL endpoint under an origin. */\nexport const GRAPHQL_PATH = \"/query\";\n\n/**\n * Environment variable holding the bearer token.\n *\n * This is the platform's documented name (docs/agent-deployments.md,\n * internal/agentdocs/reference.md). It accepts either an operator API token or\n * an agent access token from POST /agents/register — /query takes both as\n * plain bearers.\n */\nexport const TOKEN_ENV_VAR = \"UNFZ_API_TOKEN\";\n\n/** Environment variable holding the full GraphQL endpoint URL. */\nexport const ENDPOINT_ENV_VAR = \"UNFZ_API_URL\";\n\n/** Minimal structural type of the `fetch` the transport needs. */\nexport type FetchLike = (\n input: string,\n init: {\n method: string;\n headers: Record<string, string>;\n body: string;\n signal?: AbortSignal;\n },\n) => Promise<{\n ok: boolean;\n status: number;\n text(): Promise<string>;\n}>;\n\nexport interface ClientOptions {\n /**\n * Bearer token. Falls back to `UNFZ_API_TOKEN`, then to the login\n * `npx unfazed login` stored (see {@link ClientOptions.login}). An agent gets\n * one from https://unfazed.dev/auth.md — the same token the MCP server uses.\n */\n token?: string;\n /**\n * Use the stored login of `npx unfazed login`\n * (`${XDG_CONFIG_HOME:-~/.config}/unfazed/credentials.json`) when no token\n * is passed and `UNFZ_API_TOKEN` is unset. Its access token is refreshed\n * before it expires and when the platform refuses it. Default `true`; it is\n * only used for the endpoint it was issued by, and is the endpoint when none\n * is configured.\n */\n login?: boolean;\n /**\n * Where `UNFZ_API_TOKEN`, `UNFZ_API_URL` and the stored login's location\n * (`XDG_CONFIG_HOME`, `HOME`) are read from. Default: `process.env`.\n */\n env?: Record<string, string | undefined>;\n /**\n * Full GraphQL endpoint URL. Wins over `baseUrl`. Falls back to\n * `UNFZ_API_URL`, then the stored login's endpoint, then\n * {@link DEFAULT_ENDPOINT}.\n */\n endpoint?: string;\n /**\n * Platform origin; `/query` is appended. Convenience for self-hosted or\n * staging control planes where only the host differs.\n */\n baseUrl?: string;\n /** Extra headers merged into every request. Authorization always wins. */\n headers?: Record<string, string>;\n /**\n * Per-request timeout in ms. Default 60_000. Pass 0 to disable.\n *\n * Bounds the WHOLE request — connect, headers and reading the response body —\n * so a proxy that answers with headers and then stalls still fails on time.\n */\n timeoutMs?: number;\n /** Injection point for tests and instrumented/proxied transports. */\n fetch?: FetchLike;\n /** Overrides the default `unfazed-sdk/<version>` User-Agent. */\n userAgent?: string;\n}\n\n/**\n * A GraphQL document.\n *\n * Structural rather than `string & {...}` on purpose: graphql-codegen emits\n * `TypedDocumentString`, a String SUBCLASS, which is not assignable to the\n * primitive `string`. Requiring only `toString()` plus the optional phantom\n * `__apiType` lets three things through with full inference:\n *\n * - generated `TypedDocumentString` documents (types inferred),\n * - documents assembled at runtime, like the batched writeFiles mutation,\n * - plain template-literal strings a caller wrote by hand.\n */\nexport interface GraphQLDocument<TResult, TVariables> {\n /** Phantom type carrier. Never called; present only to bind the generics. */\n __apiType?: (variables: TVariables) => TResult;\n toString(): string;\n}\n\n/** Result type carried by a typed document. */\nexport type ResultOf<T> = T extends GraphQLDocument<infer R, infer _V> ? R : unknown;\n\n/** Variables type carried by a typed document. */\nexport type VariablesOf<T> = T extends GraphQLDocument<infer _R, infer V> ? V : never;\n\n/** Per-request knobs. */\nexport interface RequestOptions {\n signal?: AbortSignal;\n timeoutMs?: number;\n operationName?: string;\n}\n\n/**\n * Layer 1 — a typed, dependency-free GraphQL transport over `fetch`.\n *\n * This is the SDK's entire networking surface. It understands auth, timeouts\n * and the GraphQL error envelope, and nothing about deployments. The workflow\n * layer ({@link import(\"./unfazed.js\").Unfazed}) is built strictly on top of\n * it, so you can always drop down here for any operation the workflow layer\n * does not wrap — the schema has ~660 fields and the workflow layer\n * deliberately covers only the agent-facing ones.\n *\n * ```ts\n * const client = new UnfazedClient(); // UNFZ_API_TOKEN, else `npx unfazed login`\n * const data = await client.query<{ whoami: { name: string } }, never>(\n * `query { whoami { name } }`,\n * );\n * ```\n */\nexport class UnfazedClient {\n /** Resolved GraphQL endpoint URL. */\n readonly endpoint: string;\n\n /** A fixed bearer token, or the stored login handing out refreshed ones. */\n readonly #auth: { token: string } | { login: StoredLogin };\n readonly #headers: Record<string, string>;\n readonly #timeoutMs: number;\n readonly #fetch: FetchLike;\n\n constructor(options: ClientOptions = {}) {\n const env = options.env ?? processEnv();\n\n const injected = options.fetch;\n if (injected) {\n this.#fetch = injected;\n } else {\n const globalFetch = (globalThis as { fetch?: unknown }).fetch;\n if (typeof globalFetch !== \"function\") {\n throw new UnfazedConfigError(\n \"unfazed: no global fetch. Use Bun, Node >= 20, or pass { fetch } to the client.\",\n );\n }\n this.#fetch = globalFetch.bind(globalThis) as FetchLike;\n }\n\n const ua = options.userAgent ?? `unfazed-sdk/${VERSION}`;\n\n const configured = configuredEndpoint(options, env);\n const token = options.token ?? env[TOKEN_ENV_VAR];\n if (token?.trim()) {\n this.#auth = { token: token.trim() };\n this.endpoint = configured ?? DEFAULT_ENDPOINT;\n } else {\n const stored =\n options.login === false\n ? {}\n : openStoredLogin({\n env,\n ...(configured ? { endpoint: configured } : {}),\n fetch: this.#fetch,\n // The edge refuses some generic agents; always name ourselves.\n userAgent: ua || `unfazed-sdk/${VERSION}`,\n });\n if (!stored.login) {\n throw new UnfazedAuthError(noTokenMessage(configured, stored.other?.endpoint));\n }\n this.#auth = { login: stored.login };\n this.endpoint = stored.login.endpoint;\n }\n\n this.#headers = { ...(options.headers ?? {}) };\n this.#timeoutMs = options.timeoutMs ?? 60_000;\n if (ua) this.#headers[\"User-Agent\"] = ua;\n }\n\n /**\n * Where the bearer token comes from: `\"token\"` (passed or\n * `UNFZ_API_TOKEN`) or `\"login\"` (the stored login of `npx unfazed login`).\n */\n get authSource(): \"token\" | \"login\" {\n return \"login\" in this.#auth ? \"login\" : \"token\";\n }\n\n /** Runs a query document. Identical wire behaviour to {@link mutate}. */\n query<TResult, TVariables>(\n document: GraphQLDocument<TResult, TVariables>,\n variables?: TVariables,\n options?: RequestOptions,\n ): Promise<TResult> {\n return this.request(document, variables, options);\n }\n\n /**\n * Runs a mutation document. Distinct from {@link query} for call-site\n * readability only — GraphQL over HTTP POST makes no distinction.\n */\n mutate<TResult, TVariables>(\n document: GraphQLDocument<TResult, TVariables>,\n variables?: TVariables,\n options?: RequestOptions,\n ): Promise<TResult> {\n return this.request(document, variables, options);\n }\n\n /**\n * The single code path behind {@link query} and {@link mutate}.\n *\n * Throws {@link UnfazedHTTPError} on non-2xx, {@link UnfazedGraphQLError}\n * when the body carries `errors`, {@link UnfazedTimeoutError} on timeout or\n * abort. Resolves to the `data` object on success.\n */\n async request<TResult = unknown>(\n document: string | { toString(): string },\n variables?: unknown,\n options: RequestOptions = {},\n ): Promise<TResult> {\n const timeoutMs = options.timeoutMs ?? this.#timeoutMs;\n\n // `document` may be a TypedDocumentString (a String object). JSON.stringify\n // would serialise that fine, but String(...) keeps the wire body a plain\n // primitive regardless of how the caller obtained the document.\n const body = JSON.stringify({\n query: String(document),\n ...(variables === undefined ? {} : { variables }),\n ...(options.operationName ? { operationName: options.operationName } : {}),\n });\n\n let token = await this.#token();\n let { response, text } = await this.#send(body, token, timeoutMs, options.signal);\n // A stored login's access token can be refused before its recorded\n // expiry (the clock, a sign-out elsewhere): refresh once and retry. A\n // fixed token has nothing to refresh.\n if (response.status === 401 && \"login\" in this.#auth) {\n token = await this.#auth.login.refresh(token);\n ({ response, text } = await this.#send(body, token, timeoutMs, options.signal));\n }\n\n if (!response.ok) {\n throw new UnfazedHTTPError(response.status, text, this.endpoint);\n }\n\n let parsed: { data?: TResult; errors?: GraphQLResponseError[] };\n try {\n parsed = JSON.parse(text) as typeof parsed;\n } catch {\n throw new UnfazedHTTPError(response.status, text, this.endpoint);\n }\n\n // A GraphQL 200 can still be a failure, and can be a PARTIAL failure: the\n // batched writeFiles document resolves each aliased field independently.\n // Attaching `data` to the error is what lets a caller see which writes\n // landed before the failing one.\n if (parsed.errors?.length) {\n throw new UnfazedGraphQLError(parsed.errors, parsed.data);\n }\n if (parsed.data === undefined || parsed.data === null) {\n throw new UnfazedGraphQLError(\n [{ message: \"response contained neither data nor errors\" }],\n undefined,\n );\n }\n return parsed.data;\n }\n\n #token(): Promise<string> {\n return \"login\" in this.#auth ? this.#auth.login.token() : Promise.resolve(this.#auth.token);\n }\n\n async #send(\n body: string,\n token: string,\n timeoutMs: number,\n external: AbortSignal | undefined,\n ): Promise<{ response: Awaited<ReturnType<FetchLike>>; text: string }> {\n const { signal, cleanup, didTimeout } = makeSignal(timeoutMs, external);\n // The deadline covers BOTH phases — headers AND body. A proxy that answers\n // with headers and then stalls the body is a real failure mode, and\n // stopping the clock at the end of `fetch()` would leave `response.text()`\n // hanging forever. `untilAborted` additionally races the signal itself, so\n // an injected transport that ignores `signal` still cannot outlive the\n // timeout.\n try {\n const response = await untilAborted(\n this.#fetch(this.endpoint, {\n method: \"POST\",\n headers: {\n ...this.#headers,\n \"Content-Type\": \"application/json\",\n Accept: \"application/json\",\n Authorization: `Bearer ${token}`,\n },\n body,\n ...(signal ? { signal } : {}),\n }),\n signal,\n );\n const text = await untilAborted(response.text(), signal);\n return { response, text };\n } catch (cause) {\n if (didTimeout()) {\n throw new UnfazedTimeoutError(`unfazed: request timed out after ${timeoutMs}ms`, { cause });\n }\n if (isAbort(cause)) {\n throw new UnfazedTimeoutError(\"unfazed: request aborted\", { cause });\n }\n throw cause;\n } finally {\n cleanup();\n }\n }\n}\n\n/** The endpoint the options or `UNFZ_API_URL` name, or undefined for the default. */\nfunction configuredEndpoint(options: ClientOptions, env: Record<string, string | undefined>): string | undefined {\n if (options.endpoint) return options.endpoint;\n if (options.baseUrl) return trimSlash(options.baseUrl) + GRAPHQL_PATH;\n const fromEnv = env[ENDPOINT_ENV_VAR];\n // UNFZ_API_URL is documented as the full /query URL and is used verbatim.\n // Tolerate a bare origin anyway, since that is the obvious mistake and\n // guessing right costs nothing.\n if (fromEnv) {\n const trimmed = trimSlash(fromEnv);\n return /\\/query$|\\/graphql$/.test(trimmed) ? trimmed : trimmed + GRAPHQL_PATH;\n }\n return undefined;\n}\n\nfunction noTokenMessage(endpoint: string | undefined, otherLogin: string | undefined): string {\n if (endpoint && otherLogin) {\n return (\n `unfazed: no API token for ${endpoint}: the stored login is for ${otherLogin}. ` +\n `Run \\`${ENDPOINT_ENV_VAR}=${endpoint} ${LOGIN_COMMAND}\\`, or pass { token } / set ${TOKEN_ENV_VAR}.`\n );\n }\n return (\n `unfazed: not signed in. Run \\`${LOGIN_COMMAND}\\` to sign in with your account, ` +\n `or pass { token } / set ${TOKEN_ENV_VAR} (an agent token: ${DEFAULT_BASE_URL}/auth.md).`\n );\n}\n\nfunction processEnv(): Record<string, string | undefined> {\n // Guarded: the SDK must also work in a browser or worker, where there is no\n // `process` at all.\n return (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env ?? {};\n}\n\nfunction trimSlash(u: string): string {\n return u.replace(/\\/+$/, \"\");\n}\n\nfunction isAbort(e: unknown): boolean {\n return typeof e === \"object\" && e !== null && (e as { name?: string }).name === \"AbortError\";\n}\n\nfunction abortError(): Error {\n const e = new Error(\"The operation was aborted.\");\n e.name = \"AbortError\";\n return e;\n}\n\n/**\n * Settles with `promise`, or rejects the moment `signal` aborts.\n *\n * A global `fetch` honours the signal for headers and body alike, but an\n * injected {@link FetchLike} — a proxy, an instrumented transport, a test\n * double — need not. Racing the signal makes the timeout an upper bound on the\n * whole request regardless of what the transport does with it. The loser's\n * rejection is swallowed by the already-settled promise rather than surfacing\n * as an unhandled rejection.\n */\nfunction untilAborted<T>(promise: Promise<T>, signal: AbortSignal | undefined): Promise<T> {\n if (!signal) return promise;\n if (signal.aborted) return Promise.reject(abortError());\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => reject(abortError());\n signal.addEventListener(\"abort\", onAbort, { once: true });\n const done = () => signal.removeEventListener(\"abort\", onAbort);\n promise.then(\n (value) => {\n done();\n resolve(value);\n },\n (error: unknown) => {\n done();\n reject(error as Error);\n },\n );\n });\n}\n\n/**\n * Combines the request timeout with any caller-supplied signal.\n *\n * `didTimeout` is tracked separately from the abort so a caller's own\n * cancellation is not mislabelled as a timeout in the thrown message.\n */\nfunction makeSignal(\n timeoutMs: number,\n external?: AbortSignal,\n): { signal?: AbortSignal; cleanup: () => void; didTimeout: () => boolean } {\n if (!timeoutMs && !external) return { cleanup: () => {}, didTimeout: () => false };\n if (typeof AbortController !== \"function\") {\n return {\n ...(external ? { signal: external } : {}),\n cleanup: () => {},\n didTimeout: () => false,\n };\n }\n\n const controller = new AbortController();\n let timedOut = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n if (timeoutMs > 0) {\n timer = setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, timeoutMs);\n }\n\n const onExternalAbort = () => controller.abort();\n if (external) {\n if (external.aborted) controller.abort();\n else external.addEventListener(\"abort\", onExternalAbort, { once: true });\n }\n\n return {\n signal: controller.signal,\n cleanup: () => {\n if (timer !== undefined) clearTimeout(timer);\n external?.removeEventListener(\"abort\", onExternalAbort);\n },\n didTimeout: () => timedOut,\n };\n}\n"]}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import type { FetchLike } from "./client.js";
|
|
2
|
+
/** The command that writes the stored login. Error messages point at it. */
|
|
3
|
+
export declare const LOGIN_COMMAND = "npx unfazed login";
|
|
4
|
+
/** The stored login's file name, under {@link credentialsDir}. */
|
|
5
|
+
export declare const CREDENTIALS_FILE = "credentials.json";
|
|
6
|
+
/** The access token is refreshed once it has less than this left. */
|
|
7
|
+
export declare const REFRESH_MARGIN_MS = 60000;
|
|
8
|
+
/** What `unfazed login` writes. Field names follow OAuth's own. */
|
|
9
|
+
export interface StoredCredentials {
|
|
10
|
+
version: 1;
|
|
11
|
+
/** The GraphQL endpoint the login is for, e.g. `https://unfazed.dev/query`. */
|
|
12
|
+
endpoint: string;
|
|
13
|
+
/** The OAuth issuer that signed the person in, e.g. `https://unfazed.dev`. */
|
|
14
|
+
issuer: string;
|
|
15
|
+
token_endpoint: string;
|
|
16
|
+
/** RFC 7009 revocation endpoint, when the server advertises one. */
|
|
17
|
+
revocation_endpoint?: string;
|
|
18
|
+
/** The OAuth client `unfazed login` registered (a public client: no secret). */
|
|
19
|
+
client_id: string;
|
|
20
|
+
access_token: string;
|
|
21
|
+
refresh_token?: string;
|
|
22
|
+
/** When the access token expires (ISO 8601). Unset: never refreshed proactively. */
|
|
23
|
+
expires_at?: string;
|
|
24
|
+
scope?: string;
|
|
25
|
+
/** Who signed in, from GraphQL `whoami` at login. Display only. */
|
|
26
|
+
account?: {
|
|
27
|
+
kind?: string;
|
|
28
|
+
user_id?: string;
|
|
29
|
+
name?: string;
|
|
30
|
+
};
|
|
31
|
+
created_at?: string;
|
|
32
|
+
updated_at?: string;
|
|
33
|
+
}
|
|
34
|
+
type Env = Record<string, string | undefined>;
|
|
35
|
+
/** `${XDG_CONFIG_HOME:-~/.config}/unfazed`, or undefined where there is no home. */
|
|
36
|
+
export declare function credentialsDir(env?: Env): string | undefined;
|
|
37
|
+
/** Where the stored login lives, or undefined where there is no home directory. */
|
|
38
|
+
export declare function credentialsPath(env?: Env): string | undefined;
|
|
39
|
+
/**
|
|
40
|
+
* Reads the stored login. `undefined` when there is none (or no filesystem on
|
|
41
|
+
* this runtime); throws {@link UnfazedConfigError} when the file is there but
|
|
42
|
+
* unusable, saying to log in again.
|
|
43
|
+
*/
|
|
44
|
+
export declare function readCredentials(path: string): StoredCredentials | undefined;
|
|
45
|
+
/**
|
|
46
|
+
* Writes the stored login atomically with mode 0600 (its directory 0700): a
|
|
47
|
+
* temporary file created exclusively with that mode, then renamed over the
|
|
48
|
+
* old one, so a reader never sees half a file and the tokens are never
|
|
49
|
+
* readable by anyone else, not even for a moment.
|
|
50
|
+
*/
|
|
51
|
+
export declare function writeCredentials(path: string, credentials: StoredCredentials): void;
|
|
52
|
+
/** Deletes the stored login. Returns whether there was one. */
|
|
53
|
+
export declare function deleteCredentials(path: string): boolean;
|
|
54
|
+
/** Whether the access token is expired or within {@link REFRESH_MARGIN_MS} of it. */
|
|
55
|
+
export declare function needsRefresh(credentials: StoredCredentials, now?: number): boolean;
|
|
56
|
+
/** The token endpoint's answer to a code or refresh grant. */
|
|
57
|
+
export interface TokenResponse {
|
|
58
|
+
access_token: string;
|
|
59
|
+
refresh_token?: string;
|
|
60
|
+
token_type?: string;
|
|
61
|
+
expires_in?: number;
|
|
62
|
+
scope?: string;
|
|
63
|
+
}
|
|
64
|
+
/** Turns a token response into the stored fields it replaces. */
|
|
65
|
+
export declare function tokenFields(response: TokenResponse, previous?: Pick<StoredCredentials, "refresh_token" | "scope">, now?: number): Pick<StoredCredentials, "access_token" | "refresh_token" | "expires_at" | "scope">;
|
|
66
|
+
/**
|
|
67
|
+
* Posts a form to an OAuth endpoint and parses its JSON answer. On an OAuth
|
|
68
|
+
* error the thrown message carries only `error` and `error_description` —
|
|
69
|
+
* never the request, which holds the secrets.
|
|
70
|
+
*/
|
|
71
|
+
export declare function postTokenForm(fetch: FetchLike, url: string, form: Record<string, string>, userAgent: string, signal?: AbortSignal): Promise<{
|
|
72
|
+
status: number;
|
|
73
|
+
body: Record<string, unknown>;
|
|
74
|
+
}>;
|
|
75
|
+
/** `error: description` from an OAuth error body, or the HTTP status. */
|
|
76
|
+
export declare function oauthErrorText(status: number, body: Record<string, unknown>): string;
|
|
77
|
+
/**
|
|
78
|
+
* Exchanges the stored refresh token for a new pair. Throws
|
|
79
|
+
* {@link UnfazedAuthError} saying to log in again when the server refuses it.
|
|
80
|
+
*/
|
|
81
|
+
export declare function refreshCredentials(credentials: StoredCredentials, fetch: FetchLike, userAgent: string, signal?: AbortSignal): Promise<StoredCredentials>;
|
|
82
|
+
/**
|
|
83
|
+
* The stored login as a token source for one client: hands out the access
|
|
84
|
+
* token, refreshing it before it expires and when the platform refuses it.
|
|
85
|
+
*
|
|
86
|
+
* Several processes may share the file (the Workflow CLI's web UI, a script,
|
|
87
|
+
* `npx unfazed whoami`): before refreshing, the file is read again and a token some
|
|
88
|
+
* other process already refreshed is adopted instead. Two that refresh at the
|
|
89
|
+
* same moment both end up with valid pairs: unfazed keeps a rotated refresh
|
|
90
|
+
* token exchangeable for a short grace window for exactly that race.
|
|
91
|
+
*/
|
|
92
|
+
export declare class StoredLogin {
|
|
93
|
+
#private;
|
|
94
|
+
readonly path: string;
|
|
95
|
+
constructor(path: string, credentials: StoredCredentials, fetch: FetchLike, userAgent: string);
|
|
96
|
+
/** The login's GraphQL endpoint. */
|
|
97
|
+
get endpoint(): string;
|
|
98
|
+
/** The current credentials (for display; the caller must not print tokens). */
|
|
99
|
+
get credentials(): StoredCredentials;
|
|
100
|
+
/** An access token that is not about to expire. */
|
|
101
|
+
token(): Promise<string>;
|
|
102
|
+
/**
|
|
103
|
+
* A token other than `stale`: one another process already wrote, else a
|
|
104
|
+
* freshly refreshed one. Concurrent callers share one refresh.
|
|
105
|
+
*/
|
|
106
|
+
refresh(stale: string): Promise<string>;
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Opens the stored login for `endpoint` (undefined: whichever endpoint the
|
|
110
|
+
* login is for). Returns undefined when there is no login, or when it is for
|
|
111
|
+
* another endpoint — a token is never sent anywhere but where it was issued.
|
|
112
|
+
*/
|
|
113
|
+
export declare function openStoredLogin(options: {
|
|
114
|
+
env: Env;
|
|
115
|
+
endpoint?: string;
|
|
116
|
+
fetch: FetchLike;
|
|
117
|
+
userAgent: string;
|
|
118
|
+
}): {
|
|
119
|
+
login?: StoredLogin;
|
|
120
|
+
other?: StoredCredentials;
|
|
121
|
+
};
|
|
122
|
+
export declare function sameEndpoint(a: string, b: string): boolean;
|
|
123
|
+
export {};
|