convex
Version:
Client for the Convex Cloud
190 lines (189 loc) • 6.38 kB
JavaScript
;
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var run_exports = {};
__export(run_exports, {
formatValue: () => formatValue,
runFunctionAndLog: () => runFunctionAndLog,
runPaginatedQuery: () => runPaginatedQuery,
runQuery: () => runQuery,
subscribe: () => subscribe,
subscribeAndLog: () => subscribeAndLog
});
module.exports = __toCommonJS(run_exports);
var import_chalk = __toESM(require("chalk"), 1);
var import_util = __toESM(require("util"), 1);
var import_ws = __toESM(require("ws"), 1);
var import_http_client = require("../../browser/http_client.js");
var import_browser = require("../../browser/index.js");
var import_server = require("../../server/index.js");
var import_value = require("../../values/value.js");
var import_context = require("../../bundler/context.js");
var import_utils = require("./utils/utils.js");
async function runFunctionAndLog(ctx, deploymentUrl, adminKey, functionName, args, componentPath, callbacks) {
const client = new import_http_client.ConvexHttpClient(deploymentUrl);
client.setAdminAuth(adminKey);
let result;
try {
result = await client.function(
(0, import_server.makeFunctionReference)(functionName),
componentPath,
args
);
} catch (err) {
return await ctx.crash({
exitCode: 1,
errorType: "invalid filesystem or env vars",
printedMessage: `Failed to run function "${functionName}":
${import_chalk.default.red(err.toString().trim())}`
});
}
callbacks?.onSuccess?.();
if (result !== null) {
(0, import_context.logOutput)(ctx, formatValue(result));
}
}
async function runPaginatedQuery(ctx, deploymentUrl, adminKey, functionName, args, limit) {
const results = [];
let cursor = null;
let isDone = false;
while (!isDone && (limit === void 0 || results.length < limit)) {
const paginationResult = await runQuery(
ctx,
deploymentUrl,
adminKey,
functionName,
{
...args,
// The pagination is limited on the backend, so the 10000
// means "give me as many as possible".
paginationOpts: {
cursor,
numItems: limit === void 0 ? 1e4 : limit - results.length
}
}
);
isDone = paginationResult.isDone;
cursor = paginationResult.continueCursor;
results.push(...paginationResult.page);
}
return results;
}
async function runQuery(ctx, deploymentUrl, adminKey, functionName, args) {
const client = new import_http_client.ConvexHttpClient(deploymentUrl);
client.setAdminAuth(adminKey);
try {
return await client.query(
(0, import_server.makeFunctionReference)(functionName),
args
);
} catch (err) {
return await ctx.crash({
exitCode: 1,
errorType: "invalid filesystem or env vars",
printedMessage: `Failed to run query "${functionName}":
${import_chalk.default.red(err.toString().trim())}`
});
}
}
function formatValue(value) {
const json = (0, import_value.convexToJson)(value);
if (process.stdout.isTTY) {
return import_util.default.inspect(value, { colors: true, depth: null });
} else {
return JSON.stringify(json, null, 2);
}
}
async function subscribeAndLog(ctx, deploymentUrl, adminKey, functionName, args) {
return subscribe(
ctx,
deploymentUrl,
adminKey,
functionName,
args,
(0, import_utils.waitForever)(),
{
onStart() {
(0, import_context.logFinishedStep)(
ctx,
`Watching query ${functionName} on ${deploymentUrl}...`
);
},
onChange(result) {
(0, import_context.logOutput)(ctx, formatValue(result));
},
onStop() {
(0, import_context.logMessage)(ctx, `Closing connection to ${deploymentUrl}...`);
}
}
);
}
async function subscribe(ctx, deploymentUrl, adminKey, functionName, args, until, callbacks) {
const client = new import_browser.BaseConvexClient(
deploymentUrl,
(updatedQueries) => {
for (const queryToken of updatedQueries) {
callbacks?.onChange?.(client.localQueryResultByToken(queryToken));
}
},
{
// pretend that a Node.js 'ws' library WebSocket is a browser WebSocket
webSocketConstructor: import_ws.default,
unsavedChangesWarning: false
}
);
client.setAdminAuth(adminKey);
const { unsubscribe } = client.subscribe(functionName, args);
callbacks?.onStart?.();
let done = false;
const [donePromise, onDone] = (0, import_utils.waitUntilCalled)();
const stopWatching = () => {
if (done) {
return;
}
done = true;
unsubscribe();
void client.close();
process.off("SIGINT", sigintListener);
onDone();
callbacks?.onStop?.();
};
function sigintListener() {
stopWatching();
}
process.on("SIGINT", sigintListener);
void until.finally(stopWatching);
while (!done) {
const oneDay = 24 * 60 * 60 * 1e3;
await Promise.race([
donePromise,
new Promise((resolve) => setTimeout(resolve, oneDay))
]);
}
}
//# sourceMappingURL=run.js.map