@botpress/cli 0.3.2 → 0.4.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/dist/code-generation/integration-secret.js +15 -6
- package/dist/code-generation/integration-secret.js.map +2 -2
- package/dist/command-implementations/dev-command.js +3 -3
- package/dist/command-implementations/dev-command.js.map +2 -2
- package/dist/command-implementations/gen-command.js +3 -10
- package/dist/command-implementations/gen-command.js.map +3 -3
- package/dist/command-implementations/project-command.js +15 -9
- package/dist/command-implementations/project-command.js.map +2 -2
- package/dist/utils/prompt-utils.js +12 -17
- package/dist/utils/prompt-utils.js.map +2 -2
- package/e2e/index.ts +2 -1
- package/e2e/tests/integration-secrets.ts +98 -0
- package/package.json +3 -3
- package/templates/echo-bot/package.json +2 -2
- package/templates/empty-integration/package.json +2 -2
- package/templates/empty-integration/src/index.ts +1 -2
|
@@ -30,17 +30,26 @@ class IntegrationSecretIndexModule extends import_module.Module {
|
|
|
30
30
|
static async create(integration) {
|
|
31
31
|
let content = import_const.GENERATED_HEADER;
|
|
32
32
|
content += "class Secrets {\n";
|
|
33
|
-
for (const secretName of integration.secrets ??
|
|
33
|
+
for (const [secretName, { optional }] of Object.entries(integration.secrets ?? {})) {
|
|
34
34
|
const envVariableName = secretEnvVariableName(secretName);
|
|
35
35
|
const fieldName = import_utils.casing.to.screamingSnakeCase(secretName);
|
|
36
|
-
|
|
36
|
+
if (optional) {
|
|
37
|
+
content += ` public get ${fieldName}(): string | undefined {
|
|
37
38
|
`;
|
|
38
|
-
|
|
39
|
+
content += ` const envVarValue = process.env.${envVariableName}
|
|
39
40
|
`;
|
|
40
|
-
|
|
41
|
+
content += " return envVarValue\n";
|
|
42
|
+
content += " }\n";
|
|
43
|
+
} else {
|
|
44
|
+
content += ` public get ${fieldName}(): string {
|
|
41
45
|
`;
|
|
42
|
-
|
|
43
|
-
|
|
46
|
+
content += ` const envVarValue = process.env.${envVariableName}
|
|
47
|
+
`;
|
|
48
|
+
content += ` if (!envVarValue) throw new Error('Missing required secret "${secretName}"')
|
|
49
|
+
`;
|
|
50
|
+
content += " return envVarValue\n";
|
|
51
|
+
content += " }\n";
|
|
52
|
+
}
|
|
44
53
|
}
|
|
45
54
|
content += "}\n";
|
|
46
55
|
content += "export const secrets = new Secrets()\n";
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/code-generation/integration-secret.ts"],
|
|
4
|
-
"sourcesContent": ["import type { IntegrationDefinition } from '@botpress/sdk'\nimport { casing } from '../utils'\nimport { GENERATED_HEADER, INDEX_FILE } from './const'\nimport { Module } from './module'\n\nexport const secretEnvVariableName = (secretName: string) => `SECRET_${casing.to.screamingSnakeCase(secretName)}`\n\nexport class IntegrationSecretIndexModule extends Module {\n public static async create(integration: IntegrationDefinition): Promise<IntegrationSecretIndexModule> {\n let content = GENERATED_HEADER\n content += 'class Secrets {\\n'\n for (const secretName of integration.secrets ??
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,mBAAuB;AACvB,mBAA6C;AAC7C,oBAAuB;AAEhB,MAAM,wBAAwB,CAAC,eAAuB,UAAU,oBAAO,GAAG,mBAAmB,UAAU;AAEvG,MAAM,qCAAqC,qBAAO;AAAA,EACvD,aAAoB,OAAO,aAA2E;AACpG,QAAI,UAAU;AACd,eAAW;AACX,eAAW,
|
|
4
|
+
"sourcesContent": ["import type { IntegrationDefinition } from '@botpress/sdk'\nimport { casing } from '../utils'\nimport { GENERATED_HEADER, INDEX_FILE } from './const'\nimport { Module } from './module'\n\nexport const secretEnvVariableName = (secretName: string) => `SECRET_${casing.to.screamingSnakeCase(secretName)}`\n\nexport class IntegrationSecretIndexModule extends Module {\n public static async create(integration: IntegrationDefinition): Promise<IntegrationSecretIndexModule> {\n let content = GENERATED_HEADER\n content += 'class Secrets {\\n'\n for (const [secretName, { optional }] of Object.entries(integration.secrets ?? {})) {\n const envVariableName = secretEnvVariableName(secretName)\n const fieldName = casing.to.screamingSnakeCase(secretName)\n\n if (optional) {\n content += ` public get ${fieldName}(): string | undefined {\\n`\n content += ` const envVarValue = process.env.${envVariableName}\\n`\n content += ' return envVarValue\\n'\n content += ' }\\n'\n } else {\n content += ` public get ${fieldName}(): string {\\n`\n content += ` const envVarValue = process.env.${envVariableName}\\n`\n content += ` if (!envVarValue) throw new Error('Missing required secret \"${secretName}\"')\\n`\n content += ' return envVarValue\\n'\n content += ' }\\n'\n }\n }\n content += '}\\n'\n content += 'export const secrets = new Secrets()\\n'\n return new IntegrationSecretIndexModule({ content, exportName: 'secrets', path: INDEX_FILE })\n }\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,mBAAuB;AACvB,mBAA6C;AAC7C,oBAAuB;AAEhB,MAAM,wBAAwB,CAAC,eAAuB,UAAU,oBAAO,GAAG,mBAAmB,UAAU;AAEvG,MAAM,qCAAqC,qBAAO;AAAA,EACvD,aAAoB,OAAO,aAA2E;AACpG,QAAI,UAAU;AACd,eAAW;AACX,eAAW,CAAC,YAAY,EAAE,SAAS,CAAC,KAAK,OAAO,QAAQ,YAAY,WAAW,CAAC,CAAC,GAAG;AAClF,YAAM,kBAAkB,sBAAsB,UAAU;AACxD,YAAM,YAAY,oBAAO,GAAG,mBAAmB,UAAU;AAEzD,UAAI,UAAU;AACZ,mBAAW,gBAAgB;AAAA;AAC3B,mBAAW,uCAAuC;AAAA;AAClD,mBAAW;AACX,mBAAW;AAAA,MACb,OAAO;AACL,mBAAW,gBAAgB;AAAA;AAC3B,mBAAW,uCAAuC;AAAA;AAClD,mBAAW,mEAAmE;AAAA;AAC9E,mBAAW;AACX,mBAAW;AAAA,MACb;AAAA,IACF;AACA,eAAW;AACX,eAAW;AACX,WAAO,IAAI,6BAA6B,EAAE,SAAS,YAAY,WAAW,MAAM,wBAAW,CAAC;AAAA,EAC9F;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -154,9 +154,9 @@ class DevCommand extends import_project_command.ProjectCommand {
|
|
|
154
154
|
}
|
|
155
155
|
};
|
|
156
156
|
_checkSecrets(integrationDef) {
|
|
157
|
-
const initialSecrets = this._initialDef?.secrets ??
|
|
158
|
-
const currentSecrets = integrationDef.secrets ??
|
|
159
|
-
const newSecrets = currentSecrets.filter((s) => !initialSecrets
|
|
157
|
+
const initialSecrets = this._initialDef?.secrets ?? {};
|
|
158
|
+
const currentSecrets = integrationDef.secrets ?? {};
|
|
159
|
+
const newSecrets = Object.keys(currentSecrets).filter((s) => !initialSecrets[s]);
|
|
160
160
|
if (newSecrets.length > 0) {
|
|
161
161
|
throw new errors.BotpressCLIError("Secrets were added while the server was running. A restart is required.");
|
|
162
162
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/command-implementations/dev-command.ts"],
|
|
4
|
-
"sourcesContent": ["import type * as bpclient from '@botpress/client'\nimport type * as bpsdk from '@botpress/sdk'\nimport { TunnelRequest, TunnelResponse } from '@bpinternal/tunnel'\nimport axios, { AxiosRequestConfig, AxiosResponse } from 'axios'\nimport chalk from 'chalk'\nimport * as pathlib from 'path'\nimport * as uuid from 'uuid'\nimport { prepareUpdateBotBody } from '../api/bot-body'\nimport type { ApiClient } from '../api/client'\nimport { prepareUpdateIntegrationBody, CreateIntegrationBody } from '../api/integration-body'\nimport type commandDefinitions from '../command-definitions'\nimport * as errors from '../errors'\nimport * as utils from '../utils'\nimport { Worker } from '../worker'\nimport { BuildCommand } from './build-command'\nimport { ProjectCommand } from './project-command'\n\nconst DEFAULT_BOT_PORT = 8075\nconst DEFAULT_INTEGRATION_PORT = 8076\nconst TUNNEL_HELLO_INTERVAL = 5000\n\nexport type DevCommandDefinition = typeof commandDefinitions.dev\nexport class DevCommand extends ProjectCommand<DevCommandDefinition> {\n private _initialDef: bpsdk.IntegrationDefinition | undefined = undefined\n\n public async run(): Promise<void> {\n this.logger.warn('This command is experimental and subject to breaking changes without notice.')\n\n const api = await this.ensureLoginAndCreateClient(this.argv)\n\n this._initialDef = await this.readIntegrationDefinitionFromFS()\n\n let env: Record<string, string> = {\n ...process.env,\n BP_API_URL: api.url,\n BP_TOKEN: api.token,\n }\n\n let defaultPort = DEFAULT_BOT_PORT\n if (this._initialDef) {\n defaultPort = DEFAULT_INTEGRATION_PORT\n const secrets = await this.promptSecrets(this._initialDef, this.argv)\n env = { ...env, ...secrets }\n }\n\n const port = this.argv.port ?? defaultPort\n\n const urlParseResult = utils.url.parse(this.argv.tunnelUrl)\n if (urlParseResult.status === 'error') {\n throw new errors.BotpressCLIError(`Invalid tunnel URL: ${urlParseResult.error}`)\n }\n\n const tunnelId = uuid.v4()\n\n const { url: parsedTunnelUrl } = urlParseResult\n const isSecured = parsedTunnelUrl.protocol === 'https' || parsedTunnelUrl.protocol === 'wss'\n\n const wsTunnelUrl: string = utils.url.format({ ...parsedTunnelUrl, protocol: isSecured ? 'wss' : 'ws' })\n const httpTunnelUrl: string = utils.url.format({\n ...parsedTunnelUrl,\n protocol: isSecured ? 'https' : 'http',\n path: `/${tunnelId}`,\n })\n\n let worker: Worker | undefined = undefined\n\n const supervisor = new utils.tunnel.TunnelSupervisor(wsTunnelUrl, tunnelId, this.logger)\n supervisor.events.on('connected', ({ tunnel }) => {\n // prevents the tunnel from closing due to inactivity\n const timer = setInterval(() => tunnel.hello(), TUNNEL_HELLO_INTERVAL)\n tunnel.events.on('close', () => clearInterval(timer))\n\n tunnel.events.on('request', (req) => {\n if (!worker) {\n this.logger.debug('Worker not ready yet, ignoring request')\n tunnel.send({ requestId: req.id, status: 503, body: 'Worker not ready yet' })\n return\n }\n\n void this._forwardTunnelRequest(`http://localhost:${port}`, req)\n .then((res) => {\n tunnel.send(res)\n })\n .catch((thrown) => {\n const err = errors.BotpressCLIError.wrap(thrown, 'An error occurred while handling request')\n this.logger.error(err.message)\n tunnel.send({\n requestId: req.id,\n status: 500,\n body: err.message,\n })\n })\n })\n })\n await supervisor.start()\n\n await this._runBuild()\n await this._deploy(api, httpTunnelUrl)\n worker = await this._spawnWorker(env, port)\n\n try {\n const watcher = await utils.filewatcher.FileWatcher.watch(\n this.argv.workDir,\n async (events) => {\n if (!worker) {\n this.logger.debug('Worker not ready yet, ignoring file change event')\n return\n }\n\n const typescriptEvents = events.filter((e) => pathlib.extname(e.path) === '.ts')\n if (typescriptEvents.length === 0) {\n return\n }\n\n this.logger.log('Changes detected, rebuilding')\n await this._restart(api, worker, httpTunnelUrl)\n },\n {\n ignore: [this.projectPaths.abs.outDir],\n }\n )\n\n await Promise.race([worker.wait(), watcher.wait(), supervisor.wait()])\n\n if (worker.running) {\n await worker.kill()\n }\n await watcher.close()\n supervisor.close()\n } catch (thrown) {\n throw errors.BotpressCLIError.wrap(thrown, 'An error occurred while running the dev server')\n } finally {\n if (worker.running) {\n await worker.kill()\n }\n }\n }\n\n private _restart = async (api: ApiClient, worker: Worker, tunnelUrl: string) => {\n try {\n await this._runBuild()\n } catch (thrown) {\n const error = errors.BotpressCLIError.wrap(thrown, 'Build failed')\n this.logger.error(error.message)\n return\n }\n\n await this._deploy(api, tunnelUrl)\n await worker.reload()\n }\n\n private _deploy = async (api: ApiClient, tunnelUrl: string) => {\n const integrationDef = await this.readIntegrationDefinitionFromFS()\n if (integrationDef) {\n this._checkSecrets(integrationDef)\n await this._deployDevIntegration(api, tunnelUrl, integrationDef)\n } else {\n await this._deployDevBot(api, tunnelUrl)\n }\n }\n\n private _checkSecrets(integrationDef: bpsdk.IntegrationDefinition) {\n const initialSecrets = this._initialDef?.secrets ?? []\n const currentSecrets = integrationDef.secrets ?? []\n const newSecrets = currentSecrets.filter((s) => !initialSecrets.includes(s))\n if (newSecrets.length > 0) {\n throw new errors.BotpressCLIError('Secrets were added while the server was running. A restart is required.')\n }\n }\n\n private _spawnWorker = async (env: Record<string, string>, port: number) => {\n const outfile = this.projectPaths.abs.outFile\n const importPath = utils.path.toUnix(outfile)\n const requireFrom = utils.path.rmExtension(importPath)\n const code = `require('${requireFrom}').default.start(${port})`\n const worker = await Worker.spawn(\n {\n type: 'code',\n code,\n env,\n },\n this.logger\n ).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, 'Could not start dev worker')\n })\n\n return worker\n }\n\n private _runBuild() {\n return new BuildCommand(this.api, this.prompt, this.logger, this.argv).run()\n }\n\n private async _deployDevIntegration(\n api: ApiClient,\n externalUrl: string,\n integrationDef: bpsdk.IntegrationDefinition\n ): Promise<void> {\n const devId = await this.projectCache.get('devId')\n\n let integration: bpclient.Integration | undefined = undefined\n\n if (devId) {\n const resp = await api.client.getIntegration({ id: devId }).catch(async (thrown) => {\n const err = errors.BotpressCLIError.wrap(thrown, `Could not find existing dev integration with id \"${devId}\"`)\n this.logger.warn(err.message)\n return { integration: undefined }\n })\n\n if (resp.integration?.dev) {\n integration = resp.integration\n } else {\n await this.projectCache.rm('devId')\n }\n }\n\n const line = this.logger.line()\n line.started(`Deploying dev integration ${chalk.bold(integrationDef.name)}...`)\n\n const integrationBody: CreateIntegrationBody = {\n ...this.parseIntegrationDefinition(integrationDef),\n url: externalUrl,\n }\n\n if (integration) {\n const updateIntegrationBody = prepareUpdateIntegrationBody(\n { ...integrationBody, id: integration.id },\n integration\n )\n\n const resp = await api.client.updateIntegration(updateIntegrationBody).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not update dev integration \"${integrationDef.name}\"`)\n })\n integration = resp.integration\n } else {\n const resp = await api.client.createIntegration({ ...integrationBody, dev: true }).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not deploy dev integration \"${integrationDef.name}\"`)\n })\n integration = resp.integration\n }\n\n line.success(`Dev Integration deployed with id \"${integration.id}\"`)\n line.commit()\n\n await this.projectCache.set('devId', integration.id)\n }\n\n private async _deployDevBot(api: ApiClient, externalUrl: string): Promise<void> {\n const devId = await this.projectCache.get('devId')\n\n let bot: bpclient.Bot | undefined = undefined\n\n if (devId) {\n const resp = await api.client.getBot({ id: devId }).catch(async (thrown) => {\n const err = errors.BotpressCLIError.wrap(thrown, `Could not find existing dev bot with id \"${devId}\"`)\n this.logger.warn(err.message)\n return { bot: undefined }\n })\n\n if (resp.bot?.dev) {\n bot = resp.bot\n } else {\n await this.projectCache.rm('devId')\n }\n }\n\n if (!bot) {\n const createLine = this.logger.line()\n createLine.started('Creating dev bot...')\n const resp = await api.client\n .createBot({\n dev: true,\n url: externalUrl,\n })\n .catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, 'Could not deploy dev bot')\n })\n\n bot = resp.bot\n createLine.success(`Dev Bot created with id \"${bot.id}\"`)\n createLine.commit()\n await this.projectCache.set('devId', bot.id)\n }\n\n const outfile = this.projectPaths.abs.outFile\n const { default: botImpl } = utils.require.requireJsFile<{ default: bpsdk.Bot }>(outfile)\n\n const updateLine = this.logger.line()\n updateLine.started('Deploying dev bot...')\n\n const updateBotBody = prepareUpdateBotBody(\n {\n id: bot.id,\n url: externalUrl,\n ...this.parseBot(botImpl),\n },\n bot\n )\n\n const { bot: updatedBot } = await api.client.updateBot(updateBotBody).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, 'Could not deploy dev bot')\n })\n updateLine.success(`Dev Bot deployed with id \"${updatedBot.id}\"`)\n updateLine.commit()\n\n this.displayWebhookUrls(updatedBot)\n }\n\n private _forwardTunnelRequest = async (baseUrl: string, request: TunnelRequest): Promise<TunnelResponse> => {\n const axiosConfig = {\n method: request.method,\n url: this._formatLocalUrl(baseUrl, request),\n headers: request.headers,\n data: request.body,\n responseType: 'text',\n validateStatus: () => true,\n } satisfies AxiosRequestConfig\n\n this.logger.debug(`Forwarding request to ${axiosConfig.url}`)\n const response = await axios(axiosConfig)\n this.logger.debug('Sending back response up the tunnel')\n\n return {\n requestId: request.id,\n status: response.status,\n headers: this._getHeaders(response.headers),\n body: response.data,\n }\n }\n\n private _formatLocalUrl = (baseUrl: string, req: TunnelRequest): string => {\n if (req.query) {\n return `${baseUrl}${req.path}?${req.query}`\n }\n return `${baseUrl}${req.path}`\n }\n\n private _getHeaders = (res: AxiosResponse['headers']): TunnelResponse['headers'] => {\n const headers: TunnelResponse['headers'] = {}\n for (const key in res) {\n if (typeof res[key] === 'string' || typeof res[key] === 'number') {\n headers[key] = res[key]\n }\n }\n return headers\n }\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,mBAAyD;AACzD,mBAAkB;AAClB,cAAyB;AACzB,WAAsB;AACtB,sBAAqC;AAErC,8BAAoE;AAEpE,aAAwB;AACxB,YAAuB;AACvB,oBAAuB;AACvB,2BAA6B;AAC7B,6BAA+B;AAE/B,MAAM,mBAAmB;AACzB,MAAM,2BAA2B;AACjC,MAAM,wBAAwB;AAGvB,MAAM,mBAAmB,sCAAqC;AAAA,EAC3D,cAAuD;AAAA,EAE/D,MAAa,MAAqB;AAChC,SAAK,OAAO,KAAK,8EAA8E;AAE/F,UAAM,MAAM,MAAM,KAAK,2BAA2B,KAAK,IAAI;AAE3D,SAAK,cAAc,MAAM,KAAK,gCAAgC;AAE9D,QAAI,MAA8B;AAAA,MAChC,GAAG,QAAQ;AAAA,MACX,YAAY,IAAI;AAAA,MAChB,UAAU,IAAI;AAAA,IAChB;AAEA,QAAI,cAAc;AAClB,QAAI,KAAK,aAAa;AACpB,oBAAc;AACd,YAAM,UAAU,MAAM,KAAK,cAAc,KAAK,aAAa,KAAK,IAAI;AACpE,YAAM,EAAE,GAAG,KAAK,GAAG,QAAQ;AAAA,IAC7B;AAEA,UAAM,OAAO,KAAK,KAAK,QAAQ;AAE/B,UAAM,iBAAiB,MAAM,IAAI,MAAM,KAAK,KAAK,SAAS;AAC1D,QAAI,eAAe,WAAW,SAAS;AACrC,YAAM,IAAI,OAAO,iBAAiB,uBAAuB,eAAe,OAAO;AAAA,IAC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,OAAO,KAAgB,cAAsB;AAC7D,UAAM,iBAAiB,MAAM,KAAK,gCAAgC;AAClE,QAAI,gBAAgB;AAClB,WAAK,cAAc,cAAc;AACjC,YAAM,KAAK,sBAAsB,KAAK,WAAW,cAAc;AAAA,IACjE,OAAO;AACL,YAAM,KAAK,cAAc,KAAK,SAAS;AAAA,IACzC;AAAA,EACF;AAAA,EAEQ,cAAc,gBAA6C;AACjE,UAAM,iBAAiB,KAAK,aAAa,WAAW,CAAC;AACrD,UAAM,iBAAiB,eAAe,WAAW,CAAC;AAClD,UAAM,aAAa,
|
|
4
|
+
"sourcesContent": ["import type * as bpclient from '@botpress/client'\nimport type * as bpsdk from '@botpress/sdk'\nimport { TunnelRequest, TunnelResponse } from '@bpinternal/tunnel'\nimport axios, { AxiosRequestConfig, AxiosResponse } from 'axios'\nimport chalk from 'chalk'\nimport * as pathlib from 'path'\nimport * as uuid from 'uuid'\nimport { prepareUpdateBotBody } from '../api/bot-body'\nimport type { ApiClient } from '../api/client'\nimport { prepareUpdateIntegrationBody, CreateIntegrationBody } from '../api/integration-body'\nimport type commandDefinitions from '../command-definitions'\nimport * as errors from '../errors'\nimport * as utils from '../utils'\nimport { Worker } from '../worker'\nimport { BuildCommand } from './build-command'\nimport { ProjectCommand } from './project-command'\n\nconst DEFAULT_BOT_PORT = 8075\nconst DEFAULT_INTEGRATION_PORT = 8076\nconst TUNNEL_HELLO_INTERVAL = 5000\n\nexport type DevCommandDefinition = typeof commandDefinitions.dev\nexport class DevCommand extends ProjectCommand<DevCommandDefinition> {\n private _initialDef: bpsdk.IntegrationDefinition | undefined = undefined\n\n public async run(): Promise<void> {\n this.logger.warn('This command is experimental and subject to breaking changes without notice.')\n\n const api = await this.ensureLoginAndCreateClient(this.argv)\n\n this._initialDef = await this.readIntegrationDefinitionFromFS()\n\n let env: Record<string, string> = {\n ...process.env,\n BP_API_URL: api.url,\n BP_TOKEN: api.token,\n }\n\n let defaultPort = DEFAULT_BOT_PORT\n if (this._initialDef) {\n defaultPort = DEFAULT_INTEGRATION_PORT\n const secrets = await this.promptSecrets(this._initialDef, this.argv)\n env = { ...env, ...secrets }\n }\n\n const port = this.argv.port ?? defaultPort\n\n const urlParseResult = utils.url.parse(this.argv.tunnelUrl)\n if (urlParseResult.status === 'error') {\n throw new errors.BotpressCLIError(`Invalid tunnel URL: ${urlParseResult.error}`)\n }\n\n const tunnelId = uuid.v4()\n\n const { url: parsedTunnelUrl } = urlParseResult\n const isSecured = parsedTunnelUrl.protocol === 'https' || parsedTunnelUrl.protocol === 'wss'\n\n const wsTunnelUrl: string = utils.url.format({ ...parsedTunnelUrl, protocol: isSecured ? 'wss' : 'ws' })\n const httpTunnelUrl: string = utils.url.format({\n ...parsedTunnelUrl,\n protocol: isSecured ? 'https' : 'http',\n path: `/${tunnelId}`,\n })\n\n let worker: Worker | undefined = undefined\n\n const supervisor = new utils.tunnel.TunnelSupervisor(wsTunnelUrl, tunnelId, this.logger)\n supervisor.events.on('connected', ({ tunnel }) => {\n // prevents the tunnel from closing due to inactivity\n const timer = setInterval(() => tunnel.hello(), TUNNEL_HELLO_INTERVAL)\n tunnel.events.on('close', () => clearInterval(timer))\n\n tunnel.events.on('request', (req) => {\n if (!worker) {\n this.logger.debug('Worker not ready yet, ignoring request')\n tunnel.send({ requestId: req.id, status: 503, body: 'Worker not ready yet' })\n return\n }\n\n void this._forwardTunnelRequest(`http://localhost:${port}`, req)\n .then((res) => {\n tunnel.send(res)\n })\n .catch((thrown) => {\n const err = errors.BotpressCLIError.wrap(thrown, 'An error occurred while handling request')\n this.logger.error(err.message)\n tunnel.send({\n requestId: req.id,\n status: 500,\n body: err.message,\n })\n })\n })\n })\n await supervisor.start()\n\n await this._runBuild()\n await this._deploy(api, httpTunnelUrl)\n worker = await this._spawnWorker(env, port)\n\n try {\n const watcher = await utils.filewatcher.FileWatcher.watch(\n this.argv.workDir,\n async (events) => {\n if (!worker) {\n this.logger.debug('Worker not ready yet, ignoring file change event')\n return\n }\n\n const typescriptEvents = events.filter((e) => pathlib.extname(e.path) === '.ts')\n if (typescriptEvents.length === 0) {\n return\n }\n\n this.logger.log('Changes detected, rebuilding')\n await this._restart(api, worker, httpTunnelUrl)\n },\n {\n ignore: [this.projectPaths.abs.outDir],\n }\n )\n\n await Promise.race([worker.wait(), watcher.wait(), supervisor.wait()])\n\n if (worker.running) {\n await worker.kill()\n }\n await watcher.close()\n supervisor.close()\n } catch (thrown) {\n throw errors.BotpressCLIError.wrap(thrown, 'An error occurred while running the dev server')\n } finally {\n if (worker.running) {\n await worker.kill()\n }\n }\n }\n\n private _restart = async (api: ApiClient, worker: Worker, tunnelUrl: string) => {\n try {\n await this._runBuild()\n } catch (thrown) {\n const error = errors.BotpressCLIError.wrap(thrown, 'Build failed')\n this.logger.error(error.message)\n return\n }\n\n await this._deploy(api, tunnelUrl)\n await worker.reload()\n }\n\n private _deploy = async (api: ApiClient, tunnelUrl: string) => {\n const integrationDef = await this.readIntegrationDefinitionFromFS()\n if (integrationDef) {\n this._checkSecrets(integrationDef)\n await this._deployDevIntegration(api, tunnelUrl, integrationDef)\n } else {\n await this._deployDevBot(api, tunnelUrl)\n }\n }\n\n private _checkSecrets(integrationDef: bpsdk.IntegrationDefinition) {\n const initialSecrets = this._initialDef?.secrets ?? {}\n const currentSecrets = integrationDef.secrets ?? {}\n const newSecrets = Object.keys(currentSecrets).filter((s) => !initialSecrets[s])\n if (newSecrets.length > 0) {\n throw new errors.BotpressCLIError('Secrets were added while the server was running. A restart is required.')\n }\n }\n\n private _spawnWorker = async (env: Record<string, string>, port: number) => {\n const outfile = this.projectPaths.abs.outFile\n const importPath = utils.path.toUnix(outfile)\n const requireFrom = utils.path.rmExtension(importPath)\n const code = `require('${requireFrom}').default.start(${port})`\n const worker = await Worker.spawn(\n {\n type: 'code',\n code,\n env,\n },\n this.logger\n ).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, 'Could not start dev worker')\n })\n\n return worker\n }\n\n private _runBuild() {\n return new BuildCommand(this.api, this.prompt, this.logger, this.argv).run()\n }\n\n private async _deployDevIntegration(\n api: ApiClient,\n externalUrl: string,\n integrationDef: bpsdk.IntegrationDefinition\n ): Promise<void> {\n const devId = await this.projectCache.get('devId')\n\n let integration: bpclient.Integration | undefined = undefined\n\n if (devId) {\n const resp = await api.client.getIntegration({ id: devId }).catch(async (thrown) => {\n const err = errors.BotpressCLIError.wrap(thrown, `Could not find existing dev integration with id \"${devId}\"`)\n this.logger.warn(err.message)\n return { integration: undefined }\n })\n\n if (resp.integration?.dev) {\n integration = resp.integration\n } else {\n await this.projectCache.rm('devId')\n }\n }\n\n const line = this.logger.line()\n line.started(`Deploying dev integration ${chalk.bold(integrationDef.name)}...`)\n\n const integrationBody: CreateIntegrationBody = {\n ...this.parseIntegrationDefinition(integrationDef),\n url: externalUrl,\n }\n\n if (integration) {\n const updateIntegrationBody = prepareUpdateIntegrationBody(\n { ...integrationBody, id: integration.id },\n integration\n )\n\n const resp = await api.client.updateIntegration(updateIntegrationBody).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not update dev integration \"${integrationDef.name}\"`)\n })\n integration = resp.integration\n } else {\n const resp = await api.client.createIntegration({ ...integrationBody, dev: true }).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not deploy dev integration \"${integrationDef.name}\"`)\n })\n integration = resp.integration\n }\n\n line.success(`Dev Integration deployed with id \"${integration.id}\"`)\n line.commit()\n\n await this.projectCache.set('devId', integration.id)\n }\n\n private async _deployDevBot(api: ApiClient, externalUrl: string): Promise<void> {\n const devId = await this.projectCache.get('devId')\n\n let bot: bpclient.Bot | undefined = undefined\n\n if (devId) {\n const resp = await api.client.getBot({ id: devId }).catch(async (thrown) => {\n const err = errors.BotpressCLIError.wrap(thrown, `Could not find existing dev bot with id \"${devId}\"`)\n this.logger.warn(err.message)\n return { bot: undefined }\n })\n\n if (resp.bot?.dev) {\n bot = resp.bot\n } else {\n await this.projectCache.rm('devId')\n }\n }\n\n if (!bot) {\n const createLine = this.logger.line()\n createLine.started('Creating dev bot...')\n const resp = await api.client\n .createBot({\n dev: true,\n url: externalUrl,\n })\n .catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, 'Could not deploy dev bot')\n })\n\n bot = resp.bot\n createLine.success(`Dev Bot created with id \"${bot.id}\"`)\n createLine.commit()\n await this.projectCache.set('devId', bot.id)\n }\n\n const outfile = this.projectPaths.abs.outFile\n const { default: botImpl } = utils.require.requireJsFile<{ default: bpsdk.Bot }>(outfile)\n\n const updateLine = this.logger.line()\n updateLine.started('Deploying dev bot...')\n\n const updateBotBody = prepareUpdateBotBody(\n {\n id: bot.id,\n url: externalUrl,\n ...this.parseBot(botImpl),\n },\n bot\n )\n\n const { bot: updatedBot } = await api.client.updateBot(updateBotBody).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, 'Could not deploy dev bot')\n })\n updateLine.success(`Dev Bot deployed with id \"${updatedBot.id}\"`)\n updateLine.commit()\n\n this.displayWebhookUrls(updatedBot)\n }\n\n private _forwardTunnelRequest = async (baseUrl: string, request: TunnelRequest): Promise<TunnelResponse> => {\n const axiosConfig = {\n method: request.method,\n url: this._formatLocalUrl(baseUrl, request),\n headers: request.headers,\n data: request.body,\n responseType: 'text',\n validateStatus: () => true,\n } satisfies AxiosRequestConfig\n\n this.logger.debug(`Forwarding request to ${axiosConfig.url}`)\n const response = await axios(axiosConfig)\n this.logger.debug('Sending back response up the tunnel')\n\n return {\n requestId: request.id,\n status: response.status,\n headers: this._getHeaders(response.headers),\n body: response.data,\n }\n }\n\n private _formatLocalUrl = (baseUrl: string, req: TunnelRequest): string => {\n if (req.query) {\n return `${baseUrl}${req.path}?${req.query}`\n }\n return `${baseUrl}${req.path}`\n }\n\n private _getHeaders = (res: AxiosResponse['headers']): TunnelResponse['headers'] => {\n const headers: TunnelResponse['headers'] = {}\n for (const key in res) {\n if (typeof res[key] === 'string' || typeof res[key] === 'number') {\n headers[key] = res[key]\n }\n }\n return headers\n }\n}\n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AAO;AAAA,MAC1C,SAAS,QAAQ;AAAA,MACjB,MAAM,QAAQ;AAAA,MACd,cAAc;AAAA,MACd,gBAAgB,MAAM;AAAA,IACxB;AAEA,SAAK,OAAO,MAAM,yBAAyB,YAAY,KAAK;AAC5D,UAAM,WAAW,UAAM,aAAAC,SAAM,WAAW;AACxC,SAAK,OAAO,MAAM,qCAAqC;AAEvD,WAAO;AAAA,MACL,WAAW,QAAQ;AAAA,MACnB,QAAQ,SAAS;AAAA,MACjB,SAAS,KAAK,YAAY,SAAS,OAAO;AAAA,MAC1C,MAAM,SAAS;AAAA,IACjB;AAAA,EACF;AAAA,EAEQ,kBAAkB,CAAC,SAAiB,QAA+B;AACzE,QAAI,IAAI,OAAO;AACb,aAAO,GAAG,UAAU,IAAI,QAAQ,IAAI;AAAA,IACtC;AACA,WAAO,GAAG,UAAU,IAAI;AAAA,EAC1B;AAAA,EAEQ,cAAc,CAAC,QAA6D;AAClF,UAAM,UAAqC,CAAC;AAC5C,eAAW,OAAO,KAAK;AACrB,UAAI,OAAO,IAAI,SAAS,YAAY,OAAO,IAAI,SAAS,UAAU;AAChE,gBAAQ,OAAO,IAAI;AAAA,MACrB;AAAA,IACF;AACA,WAAO;AAAA,EACT;AACF;",
|
|
6
6
|
"names": ["chalk", "axios"]
|
|
7
7
|
}
|
|
@@ -28,7 +28,6 @@ __export(gen_command_exports, {
|
|
|
28
28
|
});
|
|
29
29
|
module.exports = __toCommonJS(gen_command_exports);
|
|
30
30
|
var import_chalk = __toESM(require("chalk"));
|
|
31
|
-
var import_lodash = __toESM(require("lodash"));
|
|
32
31
|
var codegen = __toESM(require("../code-generation"));
|
|
33
32
|
var errors = __toESM(require("../errors"));
|
|
34
33
|
var utils = __toESM(require("../utils"));
|
|
@@ -61,15 +60,9 @@ class GenerateCommand extends import_project_command.ProjectCommand {
|
|
|
61
60
|
if (!secrets) {
|
|
62
61
|
return;
|
|
63
62
|
}
|
|
64
|
-
for (const
|
|
65
|
-
if (!utils.casing.is.screamingSnakeCase(
|
|
66
|
-
throw new errors.BotpressCLIError(`Secret ${
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
const groups = (0, import_lodash.default)(secrets).groupBy().mapValues((s) => s.length).toPairs().value();
|
|
70
|
-
for (const [secret, count] of groups) {
|
|
71
|
-
if (count > 1) {
|
|
72
|
-
throw new errors.BotpressCLIError(`Secret ${secret} is dupplicated; It appears ${count} times`);
|
|
63
|
+
for (const secretName in secrets) {
|
|
64
|
+
if (!utils.casing.is.screamingSnakeCase(secretName)) {
|
|
65
|
+
throw new errors.BotpressCLIError(`Secret ${secretName} should be in SCREAMING_SNAKE_CASE`);
|
|
73
66
|
}
|
|
74
67
|
}
|
|
75
68
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/command-implementations/gen-command.ts"],
|
|
4
|
-
"sourcesContent": ["import type { IntegrationDefinition } from '@botpress/sdk'\nimport chalk from 'chalk'\nimport
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,mBAAkB;AAClB,
|
|
6
|
-
"names": ["chalk"
|
|
4
|
+
"sourcesContent": ["import type { IntegrationDefinition } from '@botpress/sdk'\nimport chalk from 'chalk'\nimport * as codegen from '../code-generation'\nimport type commandDefinitions from '../command-definitions'\nimport * as errors from '../errors'\nimport * as utils from '../utils'\nimport { ProjectCommand } from './project-command'\n\nexport type GenerateCommandDefinition = typeof commandDefinitions.generate\nexport class GenerateCommand extends ProjectCommand<GenerateCommandDefinition> {\n public async run(): Promise<void> {\n const integrationDef = await this.readIntegrationDefinitionFromFS()\n if (!integrationDef) {\n this.logger.warn('No typings to generate for bot')\n return\n }\n\n this._validateSecrets(integrationDef)\n\n const line = this.logger.line()\n\n const { name } = integrationDef\n line.started(`Generating typings for integration ${chalk.bold(name)}...`)\n\n const fromWorkDir = this.projectPaths.rel('workDir')\n const fromOutDir = this.projectPaths.rel('outDir')\n\n const typingFiles = await codegen.generateIntegrationImplementationTypings(\n integrationDef,\n fromOutDir.implementationDir\n )\n\n const secretFiles = await codegen.generateIntegrationSecrets(integrationDef, fromOutDir.secretsDir)\n\n const indexFile = await codegen.generateIntegrationIndex(fromOutDir.implementationDir, fromOutDir.secretsDir)\n\n const generatedFiles = [...typingFiles, ...secretFiles, indexFile]\n\n await this.writeGeneratedFilesToOutFolder(generatedFiles)\n\n line.success(`Typings available at ${chalk.grey(fromWorkDir.outDir)}`)\n }\n\n private _validateSecrets(integrationDef: IntegrationDefinition): void {\n const { secrets } = integrationDef\n if (!secrets) {\n return\n }\n\n for (const secretName in secrets) {\n if (!utils.casing.is.screamingSnakeCase(secretName)) {\n throw new errors.BotpressCLIError(`Secret ${secretName} should be in SCREAMING_SNAKE_CASE`)\n }\n }\n }\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,mBAAkB;AAClB,cAAyB;AAEzB,aAAwB;AACxB,YAAuB;AACvB,6BAA+B;AAGxB,MAAM,wBAAwB,sCAA0C;AAAA,EAC7E,MAAa,MAAqB;AAChC,UAAM,iBAAiB,MAAM,KAAK,gCAAgC;AAClE,QAAI,CAAC,gBAAgB;AACnB,WAAK,OAAO,KAAK,gCAAgC;AACjD;AAAA,IACF;AAEA,SAAK,iBAAiB,cAAc;AAEpC,UAAM,OAAO,KAAK,OAAO,KAAK;AAE9B,UAAM,EAAE,KAAK,IAAI;AACjB,SAAK,QAAQ,sCAAsC,aAAAA,QAAM,KAAK,IAAI,MAAM;AAExE,UAAM,cAAc,KAAK,aAAa,IAAI,SAAS;AACnD,UAAM,aAAa,KAAK,aAAa,IAAI,QAAQ;AAEjD,UAAM,cAAc,MAAM,QAAQ;AAAA,MAChC;AAAA,MACA,WAAW;AAAA,IACb;AAEA,UAAM,cAAc,MAAM,QAAQ,2BAA2B,gBAAgB,WAAW,UAAU;AAElG,UAAM,YAAY,MAAM,QAAQ,yBAAyB,WAAW,mBAAmB,WAAW,UAAU;AAE5G,UAAM,iBAAiB,CAAC,GAAG,aAAa,GAAG,aAAa,SAAS;AAEjE,UAAM,KAAK,+BAA+B,cAAc;AAExD,SAAK,QAAQ,wBAAwB,aAAAA,QAAM,KAAK,YAAY,MAAM,GAAG;AAAA,EACvE;AAAA,EAEQ,iBAAiB,gBAA6C;AACpE,UAAM,EAAE,QAAQ,IAAI;AACpB,QAAI,CAAC,SAAS;AACZ;AAAA,IACF;AAEA,eAAW,cAAc,SAAS;AAChC,UAAI,CAAC,MAAM,OAAO,GAAG,mBAAmB,UAAU,GAAG;AACnD,cAAM,IAAI,OAAO,iBAAiB,UAAU,8CAA8C;AAAA,MAC5F;AAAA,IACF;AAAA,EACF;AACF;",
|
|
6
|
+
"names": ["chalk"]
|
|
7
7
|
}
|
|
@@ -162,23 +162,29 @@ class ProjectCommand extends import_global_command.GlobalCommand {
|
|
|
162
162
|
return {};
|
|
163
163
|
}
|
|
164
164
|
const secretArgv = this._parseArgvSecrets(argv.secrets);
|
|
165
|
-
const invalidSecret = Object.keys(secretArgv).find((s) => !secretDefinitions
|
|
165
|
+
const invalidSecret = Object.keys(secretArgv).find((s) => !secretDefinitions[s]);
|
|
166
166
|
if (invalidSecret) {
|
|
167
167
|
throw new errors.BotpressCLIError(`Secret ${invalidSecret} is not defined in integration definition`);
|
|
168
168
|
}
|
|
169
169
|
const values = {};
|
|
170
|
-
for (const
|
|
171
|
-
const argvSecret = secretArgv[
|
|
170
|
+
for (const [secretName, { optional }] of Object.entries(secretDefinitions)) {
|
|
171
|
+
const argvSecret = secretArgv[secretName];
|
|
172
172
|
if (argvSecret) {
|
|
173
|
-
this.logger.debug(`Using secret "${
|
|
174
|
-
values[
|
|
173
|
+
this.logger.debug(`Using secret "${secretName}" from argv`);
|
|
174
|
+
values[secretName] = argvSecret;
|
|
175
175
|
continue;
|
|
176
176
|
}
|
|
177
|
-
const
|
|
178
|
-
|
|
179
|
-
|
|
177
|
+
const mode = optional ? "optional" : "required";
|
|
178
|
+
const prompted = await this.prompt.text(`Enter value for secret "${secretName}" (${mode})`);
|
|
179
|
+
if (prompted) {
|
|
180
|
+
values[secretName] = prompted;
|
|
181
|
+
continue;
|
|
182
|
+
}
|
|
183
|
+
if (optional) {
|
|
184
|
+
this.logger.warn(`Secret "${secretName}" is unassigned`);
|
|
185
|
+
continue;
|
|
180
186
|
}
|
|
181
|
-
|
|
187
|
+
throw new errors.BotpressCLIError(`Secret "${secretName}" is required`);
|
|
182
188
|
}
|
|
183
189
|
const envVariables = import_lodash.default.mapKeys(values, (_v, k) => codegen.secretEnvVariableName(k));
|
|
184
190
|
return envVariables;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/command-implementations/project-command.ts"],
|
|
4
|
-
"sourcesContent": ["import type * as bpclient from '@botpress/client'\nimport type * as bpsdk from '@botpress/sdk'\nimport type { YargsConfig } from '@bpinternal/yargs-extra'\nimport chalk from 'chalk'\nimport fs from 'fs'\nimport _ from 'lodash'\nimport pathlib from 'path'\nimport * as codegen from '../code-generation'\nimport type * as config from '../config'\nimport * as consts from '../consts'\nimport * as errors from '../errors'\nimport type { CommandArgv, CommandDefinition } from '../typings'\nimport * as utils from '../utils'\nimport { GlobalCommand } from './global-command'\n\nexport type ProjectCommandDefinition = CommandDefinition<typeof config.schemas.project>\nexport type ProjectCache = { botId: string; devId: string }\n\ntype ConfigurableProjectPaths = { entryPoint: string; outDir: string; workDir: string }\ntype ConstantProjectPaths = typeof consts.fromOutDir & typeof consts.fromWorkDir\ntype AllProjectPaths = ConfigurableProjectPaths & ConstantProjectPaths\n\nclass ProjectPaths extends utils.path.PathStore<keyof AllProjectPaths> {\n public constructor(argv: CommandArgv<ProjectCommandDefinition>) {\n const absWorkDir = utils.path.absoluteFrom(utils.path.cwd(), argv.workDir)\n const absEntrypoint = utils.path.absoluteFrom(absWorkDir, argv.entryPoint)\n const absOutDir = utils.path.absoluteFrom(absWorkDir, argv.outDir)\n super({\n workDir: absWorkDir,\n entryPoint: absEntrypoint,\n outDir: absOutDir,\n ..._.mapValues(consts.fromOutDir, (p) => utils.path.absoluteFrom(absOutDir, p)),\n ..._.mapValues(consts.fromWorkDir, (p) => utils.path.absoluteFrom(absWorkDir, p)),\n })\n }\n}\n\nexport abstract class ProjectCommand<C extends ProjectCommandDefinition> extends GlobalCommand<C> {\n protected get projectPaths() {\n return new ProjectPaths(this.argv)\n }\n\n protected get projectCache() {\n return new utils.cache.FSKeyValueCache<ProjectCache>(this.projectPaths.abs.projectCacheFile)\n }\n\n protected parseBot(bot: bpsdk.Bot) {\n return {\n ...bot.props,\n integrations: _(bot.props.integrations)\n .values()\n .filter(utils.guards.is.defined)\n .keyBy((i) => i.id)\n .mapValues(({ enabled, configuration }) => ({ enabled, configuration }))\n .value(),\n configuration: bot.props.configuration\n ? {\n ...bot.props.configuration,\n schema: utils.schema.mapZodToJsonSchema(bot.props.configuration),\n }\n : undefined,\n events: bot.props.events\n ? _.mapValues(bot.props.events, (event) => ({\n ...event,\n schema: utils.schema.mapZodToJsonSchema(event),\n }))\n : undefined,\n states: bot.props.states\n ? _.mapValues(bot.props.states, (state) => ({\n ...state,\n schema: utils.schema.mapZodToJsonSchema(state),\n }))\n : undefined,\n }\n }\n\n protected parseIntegrationDefinition(integration: bpsdk.IntegrationDefinition) {\n return {\n ...integration,\n configuration: integration.configuration\n ? {\n ...integration.configuration,\n schema: utils.schema.mapZodToJsonSchema(integration.configuration),\n }\n : undefined,\n events: integration.events\n ? _.mapValues(integration.events, (event) => ({\n ...event,\n schema: utils.schema.mapZodToJsonSchema(event),\n }))\n : undefined,\n actions: integration.actions\n ? _.mapValues(integration.actions, (action) => ({\n ...action,\n input: {\n ...action.input,\n schema: utils.schema.mapZodToJsonSchema(action.input),\n },\n output: {\n ...action.output,\n schema: utils.schema.mapZodToJsonSchema(action.output),\n },\n }))\n : undefined,\n channels: integration.channels\n ? _.mapValues(integration.channels, (channel) => ({\n ...channel,\n messages: _.mapValues(channel.messages, (message) => ({\n ...message,\n schema: utils.schema.mapZodToJsonSchema(message),\n })),\n }))\n : undefined,\n states: integration.states\n ? _.mapValues(integration.states, (state) => ({\n ...state,\n schema: utils.schema.mapZodToJsonSchema(state),\n }))\n : undefined,\n }\n }\n\n protected async readIntegrationDefinitionFromFS(): Promise<bpsdk.IntegrationDefinition | undefined> {\n const abs = this.projectPaths.abs\n const rel = this.projectPaths.rel('workDir')\n\n if (!fs.existsSync(abs.definition)) {\n this.logger.debug(`Integration definition not found at ${rel.definition}`)\n return\n }\n\n const { outputFiles } = await utils.esbuild.buildEntrypoint({\n cwd: abs.workDir,\n outfile: '',\n entrypoint: rel.definition,\n write: false,\n })\n\n const artifact = outputFiles[0]\n if (!artifact) {\n throw new errors.BotpressCLIError('Could not read integration definition')\n }\n\n const { default: definition } = utils.require.requireJsCode<{ default: bpsdk.IntegrationDefinition }>(artifact.text)\n return definition\n }\n\n protected async writeGeneratedFilesToOutFolder(files: codegen.File[]) {\n for (const file of files) {\n const filePath = utils.path.absoluteFrom(this.projectPaths.abs.outDir, file.path)\n const dirPath = pathlib.dirname(filePath)\n await fs.promises.mkdir(dirPath, { recursive: true })\n await fs.promises.writeFile(filePath, file.content)\n }\n }\n\n protected displayWebhookUrls(bot: bpclient.Bot) {\n if (!_.keys(bot.integrations).length) {\n this.logger.debug('No integrations in bot')\n return\n }\n\n this.logger.log('Integrations:')\n for (const integration of Object.values(bot.integrations).filter(utils.guards.is.defined)) {\n if (!integration.enabled) {\n this.logger.log(`${chalk.grey(integration.name)} ${chalk.italic('(disabled)')}: ${integration.webhookUrl}`, {\n prefix: { symbol: '\u25CB', indent: 2 },\n })\n } else {\n this.logger.log(`${chalk.bold(integration.name)} : ${integration.webhookUrl}`, {\n prefix: { symbol: '\u25CF', indent: 2 },\n })\n }\n }\n }\n\n protected async promptSecrets(\n integrationDef: bpsdk.IntegrationDefinition,\n argv: YargsConfig<typeof config.schemas.secrets>\n ): Promise<Record<string, string>> {\n const { secrets: secretDefinitions } = integrationDef\n if (!secretDefinitions) {\n return {}\n }\n\n const secretArgv = this._parseArgvSecrets(argv.secrets)\n const invalidSecret = Object.keys(secretArgv).find((s) => !secretDefinitions
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,mBAAkB;AAClB,gBAAe;AACf,oBAAc;AACd,kBAAoB;AACpB,cAAyB;AAEzB,aAAwB;AACxB,aAAwB;AAExB,YAAuB;AACvB,4BAA8B;AAS9B,MAAM,qBAAqB,MAAM,KAAK,UAAiC;AAAA,EAC9D,YAAY,MAA6C;AAC9D,UAAM,aAAa,MAAM,KAAK,aAAa,MAAM,KAAK,IAAI,GAAG,KAAK,OAAO;AACzE,UAAM,gBAAgB,MAAM,KAAK,aAAa,YAAY,KAAK,UAAU;AACzE,UAAM,YAAY,MAAM,KAAK,aAAa,YAAY,KAAK,MAAM;AACjE,UAAM;AAAA,MACJ,SAAS;AAAA,MACT,YAAY;AAAA,MACZ,QAAQ;AAAA,MACR,GAAG,cAAAA,QAAE,UAAU,OAAO,YAAY,CAAC,MAAM,MAAM,KAAK,aAAa,WAAW,CAAC,CAAC;AAAA,MAC9E,GAAG,cAAAA,QAAE,UAAU,OAAO,aAAa,CAAC,MAAM,MAAM,KAAK,aAAa,YAAY,CAAC,CAAC;AAAA,IAClF,CAAC;AAAA,EACH;AACF;AAEO,MAAe,uBAA2D,oCAAiB;AAAA,EAChG,IAAc,eAAe;AAC3B,WAAO,IAAI,aAAa,KAAK,IAAI;AAAA,EACnC;AAAA,EAEA,IAAc,eAAe;AAC3B,WAAO,IAAI,MAAM,MAAM,gBAA8B,KAAK,aAAa,IAAI,gBAAgB;AAAA,EAC7F;AAAA,EAEU,SAAS,KAAgB;AACjC,WAAO;AAAA,MACL,GAAG,IAAI;AAAA,MACP,kBAAc,cA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{ YargsConfig } from '@bpinternal/yargs-extra'\nimport chalk from 'chalk'\nimport fs from 'fs'\nimport _ from 'lodash'\nimport pathlib from 'path'\nimport * as codegen from '../code-generation'\nimport type * as config from '../config'\nimport * as consts from '../consts'\nimport * as errors from '../errors'\nimport type { CommandArgv, CommandDefinition } from '../typings'\nimport * as utils from '../utils'\nimport { GlobalCommand } from './global-command'\n\nexport type ProjectCommandDefinition = CommandDefinition<typeof config.schemas.project>\nexport type ProjectCache = { botId: string; devId: string }\n\ntype ConfigurableProjectPaths = { entryPoint: string; outDir: string; workDir: string }\ntype ConstantProjectPaths = typeof consts.fromOutDir & typeof consts.fromWorkDir\ntype AllProjectPaths = ConfigurableProjectPaths & ConstantProjectPaths\n\nclass ProjectPaths extends utils.path.PathStore<keyof AllProjectPaths> {\n public constructor(argv: CommandArgv<ProjectCommandDefinition>) {\n const absWorkDir = utils.path.absoluteFrom(utils.path.cwd(), argv.workDir)\n const absEntrypoint = utils.path.absoluteFrom(absWorkDir, argv.entryPoint)\n const absOutDir = utils.path.absoluteFrom(absWorkDir, argv.outDir)\n super({\n workDir: absWorkDir,\n entryPoint: absEntrypoint,\n outDir: absOutDir,\n ..._.mapValues(consts.fromOutDir, (p) => utils.path.absoluteFrom(absOutDir, p)),\n ..._.mapValues(consts.fromWorkDir, (p) => utils.path.absoluteFrom(absWorkDir, p)),\n })\n }\n}\n\nexport abstract class ProjectCommand<C extends ProjectCommandDefinition> extends GlobalCommand<C> {\n protected get projectPaths() {\n return new ProjectPaths(this.argv)\n }\n\n protected get projectCache() {\n return new utils.cache.FSKeyValueCache<ProjectCache>(this.projectPaths.abs.projectCacheFile)\n }\n\n protected parseBot(bot: bpsdk.Bot) {\n return {\n ...bot.props,\n integrations: _(bot.props.integrations)\n .values()\n .filter(utils.guards.is.defined)\n .keyBy((i) => i.id)\n .mapValues(({ enabled, configuration }) => ({ enabled, configuration }))\n .value(),\n configuration: bot.props.configuration\n ? {\n ...bot.props.configuration,\n schema: utils.schema.mapZodToJsonSchema(bot.props.configuration),\n }\n : undefined,\n events: bot.props.events\n ? _.mapValues(bot.props.events, (event) => ({\n ...event,\n schema: utils.schema.mapZodToJsonSchema(event),\n }))\n : undefined,\n states: bot.props.states\n ? _.mapValues(bot.props.states, (state) => ({\n ...state,\n schema: utils.schema.mapZodToJsonSchema(state),\n }))\n : undefined,\n }\n }\n\n protected parseIntegrationDefinition(integration: bpsdk.IntegrationDefinition) {\n return {\n ...integration,\n configuration: integration.configuration\n ? {\n ...integration.configuration,\n schema: utils.schema.mapZodToJsonSchema(integration.configuration),\n }\n : undefined,\n events: integration.events\n ? _.mapValues(integration.events, (event) => ({\n ...event,\n schema: utils.schema.mapZodToJsonSchema(event),\n }))\n : undefined,\n actions: integration.actions\n ? _.mapValues(integration.actions, (action) => ({\n ...action,\n input: {\n ...action.input,\n schema: utils.schema.mapZodToJsonSchema(action.input),\n },\n output: {\n ...action.output,\n schema: utils.schema.mapZodToJsonSchema(action.output),\n },\n }))\n : undefined,\n channels: integration.channels\n ? _.mapValues(integration.channels, (channel) => ({\n ...channel,\n messages: _.mapValues(channel.messages, (message) => ({\n ...message,\n schema: utils.schema.mapZodToJsonSchema(message),\n })),\n }))\n : undefined,\n states: integration.states\n ? _.mapValues(integration.states, (state) => ({\n ...state,\n schema: utils.schema.mapZodToJsonSchema(state),\n }))\n : undefined,\n }\n }\n\n protected async readIntegrationDefinitionFromFS(): Promise<bpsdk.IntegrationDefinition | undefined> {\n const abs = this.projectPaths.abs\n const rel = this.projectPaths.rel('workDir')\n\n if (!fs.existsSync(abs.definition)) {\n this.logger.debug(`Integration definition not found at ${rel.definition}`)\n return\n }\n\n const { outputFiles } = await utils.esbuild.buildEntrypoint({\n cwd: abs.workDir,\n outfile: '',\n entrypoint: rel.definition,\n write: false,\n })\n\n const artifact = outputFiles[0]\n if (!artifact) {\n throw new errors.BotpressCLIError('Could not read integration definition')\n }\n\n const { default: definition } = utils.require.requireJsCode<{ default: bpsdk.IntegrationDefinition }>(artifact.text)\n return definition\n }\n\n protected async writeGeneratedFilesToOutFolder(files: codegen.File[]) {\n for (const file of files) {\n const filePath = utils.path.absoluteFrom(this.projectPaths.abs.outDir, file.path)\n const dirPath = pathlib.dirname(filePath)\n await fs.promises.mkdir(dirPath, { recursive: true })\n await fs.promises.writeFile(filePath, file.content)\n }\n }\n\n protected displayWebhookUrls(bot: bpclient.Bot) {\n if (!_.keys(bot.integrations).length) {\n this.logger.debug('No integrations in bot')\n return\n }\n\n this.logger.log('Integrations:')\n for (const integration of Object.values(bot.integrations).filter(utils.guards.is.defined)) {\n if (!integration.enabled) {\n this.logger.log(`${chalk.grey(integration.name)} ${chalk.italic('(disabled)')}: ${integration.webhookUrl}`, {\n prefix: { symbol: '\u25CB', indent: 2 },\n })\n } else {\n this.logger.log(`${chalk.bold(integration.name)} : ${integration.webhookUrl}`, {\n prefix: { symbol: '\u25CF', indent: 2 },\n })\n }\n }\n }\n\n protected async promptSecrets(\n integrationDef: bpsdk.IntegrationDefinition,\n argv: YargsConfig<typeof config.schemas.secrets>\n ): Promise<Record<string, string>> {\n const { secrets: secretDefinitions } = integrationDef\n if (!secretDefinitions) {\n return {}\n }\n\n const secretArgv = this._parseArgvSecrets(argv.secrets)\n const invalidSecret = Object.keys(secretArgv).find((s) => !secretDefinitions[s])\n if (invalidSecret) {\n throw new errors.BotpressCLIError(`Secret ${invalidSecret} is not defined in integration definition`)\n }\n\n const values: Record<string, string> = {}\n for (const [secretName, { optional }] of Object.entries(secretDefinitions)) {\n const argvSecret = secretArgv[secretName]\n if (argvSecret) {\n this.logger.debug(`Using secret \"${secretName}\" from argv`)\n values[secretName] = argvSecret\n continue\n }\n\n const mode = optional ? 'optional' : 'required'\n const prompted = await this.prompt.text(`Enter value for secret \"${secretName}\" (${mode})`)\n if (prompted) {\n values[secretName] = prompted\n continue\n }\n\n if (optional) {\n this.logger.warn(`Secret \"${secretName}\" is unassigned`)\n continue\n }\n\n throw new errors.BotpressCLIError(`Secret \"${secretName}\" is required`)\n }\n\n const envVariables = _.mapKeys(values, (_v, k) => codegen.secretEnvVariableName(k))\n return envVariables\n }\n\n private _parseArgvSecrets(argvSecrets: string[]): Record<string, string> {\n const parsed: Record<string, string> = {}\n for (const secret of argvSecrets) {\n const [key, value] = this._splitOnce(secret, '=')\n if (!value) {\n throw new errors.BotpressCLIError(\n `Secret \"${key}\" is missing a value. Expected format: \"SECRET_NAME=secretValue\"`\n )\n }\n parsed[key!] = value\n }\n\n return parsed\n }\n\n private _splitOnce = (text: string, separator: string): [string, string | undefined] => {\n const index = text.indexOf(separator)\n if (index === -1) {\n return [text, undefined]\n }\n return [text.slice(0, index), text.slice(index + 1)]\n }\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,mBAAkB;AAClB,gBAAe;AACf,oBAAc;AACd,kBAAoB;AACpB,cAAyB;AAEzB,aAAwB;AACxB,aAAwB;AAExB,YAAuB;AACvB,4BAA8B;AAS9B,MAAM,qBAAqB,MAAM,KAAK,UAAiC;AAAA,EAC9D,YAAY,MAA6C;AAC9D,UAAM,aAAa,MAAM,KAAK,aAAa,MAAM,KAAK,IAAI,GAAG,KAAK,OAAO;AACzE,UAAM,gBAAgB,MAAM,KAAK,aAAa,YAAY,KAAK,UAAU;AACzE,UAAM,YAAY,MAAM,KAAK,aAAa,YAAY,KAAK,MAAM;AACjE,UAAM;AAAA,MACJ,SAAS;AAAA,MACT,YAAY;AAAA,MACZ,QAAQ;AAAA,MACR,GAAG,cAAAA,QAAE,UAAU,OAAO,YAAY,CAAC,MAAM,MAAM,KAAK,aAAa,WAAW,CAAC,CAAC;AAAA,MAC9E,GAAG,cAAAA,QAAE,UAAU,OAAO,aAAa,CAAC,MAAM,MAAM,KAAK,aAAa,YAAY,CAAC,CAAC;AAAA,IAClF,CAAC;AAAA,EACH;AACF;AAEO,MAAe,uBAA2D,oCAAiB;AAAA,EAChG,IAAc,eAAe;AAC3B,WA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AAO,CAAC,MAAM,MAAS;AAAA,IACzB;AACA,WAAO,CAAC,KAAK,MAAM,GAAG,KAAK,GAAG,KAAK,MAAM,QAAQ,CAAC,CAAC;AAAA,EACrD;AACF;",
|
|
6
6
|
"names": ["_", "fs", "pathlib", "chalk"]
|
|
7
7
|
}
|
|
@@ -24,17 +24,10 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
24
24
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
25
25
|
var prompt_utils_exports = {};
|
|
26
26
|
__export(prompt_utils_exports, {
|
|
27
|
-
CLIPrompt: () => CLIPrompt
|
|
28
|
-
NonInteractiveError: () => NonInteractiveError
|
|
27
|
+
CLIPrompt: () => CLIPrompt
|
|
29
28
|
});
|
|
30
29
|
module.exports = __toCommonJS(prompt_utils_exports);
|
|
31
30
|
var import_prompts = __toESM(require("prompts"));
|
|
32
|
-
class NonInteractiveError extends Error {
|
|
33
|
-
constructor(message) {
|
|
34
|
-
super(`${message}:
|
|
35
|
-
Cannot prompt for input in non-interactive mode`);
|
|
36
|
-
}
|
|
37
|
-
}
|
|
38
31
|
class CLIPrompt {
|
|
39
32
|
constructor(_props, _logger) {
|
|
40
33
|
this._props = _props;
|
|
@@ -42,7 +35,7 @@ class CLIPrompt {
|
|
|
42
35
|
}
|
|
43
36
|
async confirm(message) {
|
|
44
37
|
if (this._props.confirm) {
|
|
45
|
-
this._logger.debug(`Confirming automatically: ${message}`);
|
|
38
|
+
this._logger.debug(`Confirming automatically (non-interactive mode): ${message}`);
|
|
46
39
|
return true;
|
|
47
40
|
}
|
|
48
41
|
const { confirm } = await this._prompts({
|
|
@@ -56,9 +49,10 @@ class CLIPrompt {
|
|
|
56
49
|
}
|
|
57
50
|
return true;
|
|
58
51
|
}
|
|
59
|
-
async password(message, opts) {
|
|
52
|
+
async password(message, opts = {}) {
|
|
60
53
|
if (this._props.confirm) {
|
|
61
|
-
|
|
54
|
+
this._logger.debug(`Return default (non-interactive mode): ${message}`);
|
|
55
|
+
return opts?.default;
|
|
62
56
|
}
|
|
63
57
|
const { prompted } = await this._prompts({
|
|
64
58
|
type: "password",
|
|
@@ -68,9 +62,10 @@ class CLIPrompt {
|
|
|
68
62
|
});
|
|
69
63
|
return prompted ? prompted : void 0;
|
|
70
64
|
}
|
|
71
|
-
async select(message, opts) {
|
|
65
|
+
async select(message, opts = {}) {
|
|
72
66
|
if (this._props.confirm) {
|
|
73
|
-
|
|
67
|
+
this._logger.debug(`Return default (non-interactive mode): ${message}`);
|
|
68
|
+
return opts?.default;
|
|
74
69
|
}
|
|
75
70
|
const { prompted } = await this._prompts({
|
|
76
71
|
type: "autocomplete",
|
|
@@ -81,9 +76,10 @@ class CLIPrompt {
|
|
|
81
76
|
});
|
|
82
77
|
return prompted ? prompted : void 0;
|
|
83
78
|
}
|
|
84
|
-
async text(message, opts) {
|
|
79
|
+
async text(message, opts = {}) {
|
|
85
80
|
if (this._props.confirm) {
|
|
86
|
-
|
|
81
|
+
this._logger.debug(`Return default (non-interactive mode): ${message}`);
|
|
82
|
+
return opts?.default;
|
|
87
83
|
}
|
|
88
84
|
const { prompted } = await this._prompts({
|
|
89
85
|
type: "text",
|
|
@@ -100,7 +96,6 @@ class CLIPrompt {
|
|
|
100
96
|
}
|
|
101
97
|
// Annotate the CommonJS export names for ESM import in node:
|
|
102
98
|
0 && (module.exports = {
|
|
103
|
-
CLIPrompt
|
|
104
|
-
NonInteractiveError
|
|
99
|
+
CLIPrompt
|
|
105
100
|
});
|
|
106
101
|
//# sourceMappingURL=prompt-utils.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/utils/prompt-utils.ts"],
|
|
4
|
-
"sourcesContent": ["import prompts from 'prompts'\nimport type { Logger } from '../logger'\n\nexport type CLIPromptsProps = {\n confirm: boolean\n}\n\nexport type CLIPromptsChoice<V extends string> = {\n title: string\n value: V\n}\n\
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA
|
|
4
|
+
"sourcesContent": ["import prompts from 'prompts'\nimport type { Logger } from '../logger'\n\nexport type CLIPromptsProps = {\n confirm: boolean\n}\n\nexport type CLIPromptsChoice<V extends string> = {\n title: string\n value: V\n}\n\ntype PasswordOptions = Partial<{\n default: string | undefined\n initial: string\n}>\ntype SelectOptions<V extends string> = Partial<{\n default: V | undefined\n initial: CLIPromptsChoice<V>\n choices: CLIPromptsChoice<V>[]\n}>\ntype TextOptions = Partial<{\n default: string | undefined\n initial: string\n}>\n\nexport class CLIPrompt {\n constructor(private _props: CLIPromptsProps, private _logger: Logger) {}\n\n public async confirm(message: string): Promise<boolean> {\n if (this._props.confirm) {\n this._logger.debug(`Confirming automatically (non-interactive mode): ${message}`)\n return true\n }\n\n const { confirm } = await this._prompts({\n type: 'confirm',\n name: 'confirm',\n message,\n initial: false,\n })\n\n if (!confirm) {\n return false\n }\n return true\n }\n\n public async password(message: string, opts: PasswordOptions = {}): Promise<string | undefined> {\n if (this._props.confirm) {\n this._logger.debug(`Return default (non-interactive mode): ${message}`)\n return opts?.default\n }\n\n const { prompted } = await this._prompts({\n type: 'password',\n name: 'prompted',\n message,\n initial: opts?.initial,\n })\n\n return prompted ? prompted : undefined\n }\n\n public async select<V extends string>(message: string, opts: SelectOptions<V> = {}): Promise<V | undefined> {\n if (this._props.confirm) {\n this._logger.debug(`Return default (non-interactive mode): ${message}`)\n return opts?.default\n }\n\n const { prompted } = await this._prompts({\n type: 'autocomplete',\n name: 'prompted',\n message,\n initial: opts?.initial?.value,\n choices: opts?.choices,\n })\n return prompted ? prompted : undefined\n }\n\n public async text(message: string, opts: TextOptions = {}): Promise<string | undefined> {\n if (this._props.confirm) {\n this._logger.debug(`Return default (non-interactive mode): ${message}`)\n return opts?.default\n }\n\n const { prompted } = await this._prompts({\n type: 'text',\n name: 'prompted',\n message,\n initial: opts?.initial,\n })\n\n return prompted ? prompted : undefined\n }\n\n private _prompts = (...args: Parameters<typeof prompts>): ReturnType<typeof prompts> => {\n this._logger.cleanup()\n return prompts(...args)\n }\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,qBAAoB;AA0Bb,MAAM,UAAU;AAAA,EACrB,YAAoB,QAAiC,SAAiB;AAAlD;AAAiC;AAAA,EAAkB;AAAA,EAEvE,MAAa,QAAQ,SAAmC;AACtD,QAAI,KAAK,OAAO,SAAS;AACvB,WAAK,QAAQ,MAAM,oDAAoD,SAAS;AAChF,aAAO;AAAA,IACT;AAEA,UAAM,EAAE,QAAQ,IAAI,MAAM,KAAK,SAAS;AAAA,MACtC,MAAM;AAAA,MACN,MAAM;AAAA,MACN;AAAA,MACA,SAAS;AAAA,IACX,CAAC;AAED,QAAI,CAAC,SAAS;AACZ,aAAO;AAAA,IACT;AACA,WAAO;AAAA,EACT;AAAA,EAEA,MAAa,SAAS,SAAiB,OAAwB,CAAC,GAAgC;AAC9F,QAAI,KAAK,OAAO,SAAS;AACvB,WAAK,QAAQ,MAAM,0CAA0C,SAAS;AACtE,aAAO,MAAM;AAAA,IACf;AAEA,UAAM,EAAE,SAAS,IAAI,MAAM,KAAK,SAAS;AAAA,MACvC,MAAM;AAAA,MACN,MAAM;AAAA,MACN;AAAA,MACA,SAAS,MAAM;AAAA,IACjB,CAAC;AAED,WAAO,WAAW,WAAW;AAAA,EAC/B;AAAA,EAEA,MAAa,OAAyB,SAAiB,OAAyB,CAAC,GAA2B;AAC1G,QAAI,KAAK,OAAO,SAAS;AACvB,WAAK,QAAQ,MAAM,0CAA0C,SAAS;AACtE,aAAO,MAAM;AAAA,IACf;AAEA,UAAM,EAAE,SAAS,IAAI,MAAM,KAAK,SAAS;AAAA,MACvC,MAAM;AAAA,MACN,MAAM;AAAA,MACN;AAAA,MACA,SAAS,MAAM,SAAS;AAAA,MACxB,SAAS,MAAM;AAAA,IACjB,CAAC;AACD,WAAO,WAAW,WAAW;AAAA,EAC/B;AAAA,EAEA,MAAa,KAAK,SAAiB,OAAoB,CAAC,GAAgC;AACtF,QAAI,KAAK,OAAO,SAAS;AACvB,WAAK,QAAQ,MAAM,0CAA0C,SAAS;AACtE,aAAO,MAAM;AAAA,IACf;AAEA,UAAM,EAAE,SAAS,IAAI,MAAM,KAAK,SAAS;AAAA,MACvC,MAAM;AAAA,MACN,MAAM;AAAA,MACN;AAAA,MACA,SAAS,MAAM;AAAA,IACjB,CAAC;AAED,WAAO,WAAW,WAAW;AAAA,EAC/B;AAAA,EAEQ,WAAW,IAAI,SAAiE;AACtF,SAAK,QAAQ,QAAQ;AACrB,eAAO,eAAAA,SAAQ,GAAG,IAAI;AAAA,EACxB;AACF;",
|
|
6
6
|
"names": ["prompts"]
|
|
7
7
|
}
|
package/e2e/index.ts
CHANGED
|
@@ -4,10 +4,11 @@ import * as consts from '../src/consts'
|
|
|
4
4
|
import { createDeployBot } from './tests/create-deploy-bot'
|
|
5
5
|
import { createDeployIntegration } from './tests/create-deploy-integration'
|
|
6
6
|
import { devBot } from './tests/dev-bot'
|
|
7
|
+
import { requiredSecrets } from './tests/integration-secrets'
|
|
7
8
|
import { Test } from './typings'
|
|
8
9
|
import { sleep, TmpDirectory } from './utils'
|
|
9
10
|
|
|
10
|
-
const tests: Test[] = [createDeployBot, createDeployIntegration, devBot]
|
|
11
|
+
const tests: Test[] = [createDeployBot, createDeployIntegration, devBot, requiredSecrets]
|
|
11
12
|
|
|
12
13
|
const timeout = (ms: number) =>
|
|
13
14
|
sleep(ms).then(() => {
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { Client } from '@botpress/client'
|
|
2
|
+
import * as sdk from '@botpress/sdk'
|
|
3
|
+
import fs from 'fs'
|
|
4
|
+
import pathlib from 'path'
|
|
5
|
+
import * as uuid from 'uuid'
|
|
6
|
+
import impl from '../../src/command-implementations'
|
|
7
|
+
import { fetchAllIntegrations, ApiIntegration } from '../api'
|
|
8
|
+
import defaults from '../defaults'
|
|
9
|
+
import { Test } from '../typings'
|
|
10
|
+
import * as utils from '../utils'
|
|
11
|
+
|
|
12
|
+
type SecretDef = NonNullable<sdk.IntegrationDefinitionProps['secrets']>
|
|
13
|
+
|
|
14
|
+
const fetchIntegration = async (client: Client, integrationName: string): Promise<ApiIntegration | undefined> => {
|
|
15
|
+
const integrations = await fetchAllIntegrations(client)
|
|
16
|
+
return integrations.find(({ name }) => name === integrationName)
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const appendSecretDefinition = (originalTsContent: string, secrets: SecretDef): string => {
|
|
20
|
+
const regex = /( *)version: (['"].*['"]),/
|
|
21
|
+
const replacement = [
|
|
22
|
+
'version: $2,',
|
|
23
|
+
'secrets: {',
|
|
24
|
+
...Object.entries(secrets).map(([secretName, secretDef]) => ` ${secretName}: ${JSON.stringify(secretDef)},`),
|
|
25
|
+
'},',
|
|
26
|
+
]
|
|
27
|
+
.map((s) => `$1${s}`) // for indentation
|
|
28
|
+
.join('\n')
|
|
29
|
+
|
|
30
|
+
const modifiedTsContent = originalTsContent.replace(regex, replacement)
|
|
31
|
+
return modifiedTsContent
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export const requiredSecrets: Test = {
|
|
35
|
+
name: 'cli should require required secrets',
|
|
36
|
+
handler: async ({ tmpDir, dependencies, ...creds }) => {
|
|
37
|
+
const botpressHomeDir = pathlib.join(tmpDir, '.botpresshome')
|
|
38
|
+
const baseDir = pathlib.join(tmpDir, 'integrations')
|
|
39
|
+
const integrationName = `myintegration-${uuid.v4()}`.replace(/-/g, '')
|
|
40
|
+
const integrationDir = pathlib.join(baseDir, integrationName)
|
|
41
|
+
|
|
42
|
+
const definitionPath = pathlib.join(integrationDir, 'integration.definition.ts')
|
|
43
|
+
|
|
44
|
+
const argv = {
|
|
45
|
+
...defaults,
|
|
46
|
+
botpressHome: botpressHomeDir,
|
|
47
|
+
confirm: true,
|
|
48
|
+
...creds,
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const client = new Client({ apiUrl: creds.apiUrl, token: creds.token, workspaceId: creds.workspaceId })
|
|
52
|
+
|
|
53
|
+
await impl
|
|
54
|
+
.init({ ...argv, workDir: baseDir, name: integrationName, type: 'integration' })
|
|
55
|
+
.then(utils.handleExitCode)
|
|
56
|
+
|
|
57
|
+
const originalDefinition: string = fs.readFileSync(definitionPath, 'utf-8')
|
|
58
|
+
const modifiedDefinition = appendSecretDefinition(originalDefinition, {
|
|
59
|
+
REQUIRED_SECRET: {},
|
|
60
|
+
OPTIONAL_SECRET: { optional: true },
|
|
61
|
+
})
|
|
62
|
+
fs.writeFileSync(definitionPath, modifiedDefinition, 'utf-8')
|
|
63
|
+
await impl.build({ ...argv, workDir: integrationDir }).then(utils.handleExitCode)
|
|
64
|
+
|
|
65
|
+
await utils.fixBotpressDependencies({ workDir: integrationDir, target: dependencies })
|
|
66
|
+
await utils.npmInstall({ workDir: integrationDir }).then(utils.handleExitCode)
|
|
67
|
+
await impl.build({ ...argv, workDir: integrationDir }).then(utils.handleExitCode)
|
|
68
|
+
await impl.login({ ...argv }).then(utils.handleExitCode)
|
|
69
|
+
|
|
70
|
+
const { exitCode } = await impl.deploy({
|
|
71
|
+
...argv,
|
|
72
|
+
workDir: integrationDir,
|
|
73
|
+
secrets: ['OPTIONAL_SECRET=lol'],
|
|
74
|
+
botId: undefined,
|
|
75
|
+
createNewBot: undefined,
|
|
76
|
+
})
|
|
77
|
+
if (exitCode === 0) {
|
|
78
|
+
throw new Error('Expected deploy to fail')
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
await impl
|
|
82
|
+
.deploy({
|
|
83
|
+
...argv,
|
|
84
|
+
workDir: integrationDir,
|
|
85
|
+
secrets: ['REQUIRED_SECRET=lol'],
|
|
86
|
+
botId: undefined,
|
|
87
|
+
createNewBot: undefined,
|
|
88
|
+
})
|
|
89
|
+
.then(utils.handleExitCode)
|
|
90
|
+
|
|
91
|
+
// cleanup deployed integration
|
|
92
|
+
const integration = await fetchIntegration(client, integrationName)
|
|
93
|
+
if (!integration) {
|
|
94
|
+
throw new Error(`Integration ${integrationName} should have been created`)
|
|
95
|
+
}
|
|
96
|
+
await client.deleteIntegration({ id: integration.id })
|
|
97
|
+
},
|
|
98
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@botpress/cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.1",
|
|
4
4
|
"description": "Botpress CLI",
|
|
5
5
|
"scripts": {
|
|
6
6
|
"build": "pnpm run bundle && pnpm run template:gen",
|
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
},
|
|
21
21
|
"main": "dist/index.js",
|
|
22
22
|
"dependencies": {
|
|
23
|
-
"@botpress/client": "0.3.
|
|
23
|
+
"@botpress/client": "0.3.5",
|
|
24
24
|
"@bpinternal/tunnel": "^0.1.0",
|
|
25
25
|
"@bpinternal/yargs-extra": "^0.0.3",
|
|
26
26
|
"@bpinternal/zod-to-json-schema": "^3.21.4",
|
|
@@ -47,7 +47,7 @@
|
|
|
47
47
|
"zod": "^3.20.6"
|
|
48
48
|
},
|
|
49
49
|
"devDependencies": {
|
|
50
|
-
"@botpress/sdk": "0.
|
|
50
|
+
"@botpress/sdk": "0.4.1",
|
|
51
51
|
"@bpinternal/log4bot": "^0.0.4",
|
|
52
52
|
"@types/bluebird": "^3.5.38",
|
|
53
53
|
"@types/json-schema": "^7.0.11",
|