@fragment-dev/cli
Version:
109 lines (106 loc) • 2.93 kB
JavaScript
import {
getSdk
} from "./chunk-UXTOXY2F.js";
import {
FragmentCommand,
GraphQLClient,
require_lib
} from "./chunk-UD22EIAP.js";
import {
colorizeJson
} from "./chunk-UDU5PBTV.js";
import {
__toESM,
init_cjs_shims
} from "./chunk-7GH3YGSC.js";
// src/lib/authenticatedCommand.ts
init_cjs_shims();
var import_core = __toESM(require_lib(), 1);
var AuthenticatedCommand = class extends FragmentCommand {
constructor() {
super(...arguments);
this._sdk = null;
}
static {
this.baseFlags = {
verbose: import_core.Flags.boolean({
char: "v",
description: "Enable verbose mode (prints GraphQL commands)."
})
};
}
static {
// Unfortunately this is a required default because oclif internally makes an unsafe read
// of this.ctor.flags[...]. Without it, that may be trying to read a property of undefined.
// https://github.com/oclif/core/blob/14b4e6a5365acb57d449f936d8b279bfba2d2392/src/command.ts#L284
this.flags = {};
}
async init() {
await super.init();
const { flags } = await this.parse({
flags: {
...this.ctor.flags,
...super.ctor.baseFlags
},
args: this.ctor.args,
strict: this.ctor.strict
});
this.flags = flags;
if (flags.verbose) {
this.log("Verbose mode enabled");
}
const config = await this.loadFragmentAuthConfigFromDisk();
this.assert(config, {
message: `Unable to locate credentials. Please authenticate with 'fragment login'`
});
const token = await this.fetchAccessToken(config);
this.assert(token, {
message: "Failed to fetch access token"
});
this.authToken = token;
this._sdk = this.setupGraphqlClient(
config.apiUrl,
this.authToken.access_token,
flags.verbose
);
}
get sdk() {
this.assert(this._sdk, {
message: "SDK not initialized yet"
});
return this._sdk;
}
setupGraphqlClient(url, token, verbose = false) {
const verboseMiddleware = (request) => {
this.log("Query:");
this.log(JSON.parse(request.body).query);
if (request.variables) {
this.log("Variables:");
this.log(colorizeJson(JSON.stringify(request.variables, null, 2)));
}
return request;
};
const options = {
headers: {
Authorization: `Bearer ${token}`,
"x-fragment-cli-version": this.config.version
},
requestMiddleware: verbose ? verboseMiddleware : void 0
};
const client = new GraphQLClient(url, options);
this.debug(`initialized graphql client with api url: ${url}`);
const wrapper = async (action) => {
try {
const result = await action();
this.log(`${colorizeJson(JSON.stringify(result, null, 2))}`);
return result;
} catch (e) {
return this.catch(e);
}
};
return getSdk(client, wrapper);
}
};
export {
AuthenticatedCommand
};