@botpress/cli 4.17.17 → 4.17.19
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/.turbo/turbo-build.log +12 -12
- package/dist/command-implementations/build-command.d.ts +1 -1
- package/dist/command-implementations/build-command.js +2 -2
- package/dist/command-implementations/build-command.js.map +2 -2
- package/dist/command-implementations/bundle-command.d.ts +1 -1
- package/dist/command-implementations/bundle-command.js +1 -1
- package/dist/command-implementations/bundle-command.js.map +2 -2
- package/dist/command-implementations/deploy-command.js +1 -1
- package/dist/command-implementations/deploy-command.js.map +2 -2
- package/dist/command-implementations/dev-command.js +11 -9
- package/dist/command-implementations/dev-command.js.map +2 -2
- package/dist/command-implementations/project-command.d.ts +8 -0
- package/dist/command-implementations/project-command.js +37 -14
- package/dist/command-implementations/project-command.js.map +2 -2
- package/dist/utils/esbuild-utils.d.ts +9 -3
- package/dist/utils/esbuild-utils.js +32 -13
- package/dist/utils/esbuild-utils.js.map +2 -2
- package/package.json +2 -2
- package/templates/empty-bot/package.json +1 -1
- package/templates/empty-integration/package.json +1 -1
- package/templates/empty-plugin/package.json +1 -1
- package/templates/hello-world/package.json +1 -1
- package/templates/webhook-message/package.json +1 -1
package/.turbo/turbo-build.log
CHANGED
|
@@ -1,36 +1,36 @@
|
|
|
1
1
|
|
|
2
|
-
> @botpress/cli@4.17.
|
|
2
|
+
> @botpress/cli@4.17.19 build /home/runner/work/botpress/botpress/packages/cli
|
|
3
3
|
> pnpm run build:types && pnpm run bundle && pnpm run template:gen
|
|
4
4
|
|
|
5
5
|
|
|
6
|
-
> @botpress/cli@4.17.
|
|
6
|
+
> @botpress/cli@4.17.19 build:types /home/runner/work/botpress/botpress/packages/cli
|
|
7
7
|
> tsc -p ./tsconfig.build.json
|
|
8
8
|
|
|
9
9
|
|
|
10
|
-
> @botpress/cli@4.17.
|
|
10
|
+
> @botpress/cli@4.17.19 bundle /home/runner/work/botpress/botpress/packages/cli
|
|
11
11
|
> ts-node -T build.ts
|
|
12
12
|
|
|
13
13
|
|
|
14
|
-
> @botpress/cli@4.17.
|
|
14
|
+
> @botpress/cli@4.17.19 template:gen /home/runner/work/botpress/botpress/packages/cli
|
|
15
15
|
> pnpm -r --stream -F @bp-templates/* exec bp gen
|
|
16
16
|
|
|
17
|
-
🤖 Botpress CLI v4.17.
|
|
18
|
-
🤖 Botpress CLI v4.17.
|
|
19
|
-
🤖 Botpress CLI v4.17.
|
|
20
|
-
🤖 Botpress CLI v4.17.
|
|
17
|
+
🤖 Botpress CLI v4.17.19
|
|
18
|
+
🤖 Botpress CLI v4.17.19
|
|
19
|
+
🤖 Botpress CLI v4.17.19
|
|
20
|
+
🤖 Botpress CLI v4.17.19
|
|
21
|
+
○ Generating typings for integration hello-world...
|
|
21
22
|
○ Generating typings for bot...
|
|
22
23
|
✓ Typings available at .botpress
|
|
23
24
|
|
|
24
|
-
○ Generating typings for
|
|
25
|
+
○ Generating typings for integration empty-integration...
|
|
25
26
|
✓ Typings available at .botpress
|
|
26
27
|
|
|
27
|
-
○ Generating typings for integration hello-world...
|
|
28
|
-
○ Generating typings for integration empty-integration...
|
|
29
28
|
✓ Typings available at .botpress
|
|
30
29
|
|
|
30
|
+
○ Generating typings for plugin empty-plugin...
|
|
31
31
|
✓ Typings available at .botpress
|
|
32
32
|
|
|
33
|
-
🤖 Botpress CLI v4.17.
|
|
33
|
+
🤖 Botpress CLI v4.17.19
|
|
34
34
|
○ Generating typings for integration webhook-message...
|
|
35
35
|
✓ Typings available at .botpress
|
|
36
36
|
|
|
@@ -3,7 +3,7 @@ import * as utils from '../utils';
|
|
|
3
3
|
import { ProjectCommand } from './project-command';
|
|
4
4
|
export type BuildCommandDefinition = typeof commandDefinitions.build;
|
|
5
5
|
export declare class BuildCommand extends ProjectCommand<BuildCommandDefinition> {
|
|
6
|
-
run(buildContext?: utils.esbuild.
|
|
6
|
+
run(buildContext?: utils.esbuild.BuildCodeContext): Promise<void>;
|
|
7
7
|
private _runGenerate;
|
|
8
8
|
private _runBundle;
|
|
9
9
|
}
|
|
@@ -38,10 +38,10 @@ class BuildCommand extends import_project_command.ProjectCommand {
|
|
|
38
38
|
this.logger.log(`Build completed in ${dt}ms`);
|
|
39
39
|
}
|
|
40
40
|
_runGenerate() {
|
|
41
|
-
return new import_gen_command.GenerateCommand(this.api, this.prompt, this.logger, this.argv).run();
|
|
41
|
+
return new import_gen_command.GenerateCommand(this.api, this.prompt, this.logger, this.argv).setProjectContext(this.projectContext).run();
|
|
42
42
|
}
|
|
43
43
|
_runBundle(buildContext) {
|
|
44
|
-
return new import_bundle_command.BundleCommand(this.api, this.prompt, this.logger, this.argv).run(buildContext);
|
|
44
|
+
return new import_bundle_command.BundleCommand(this.api, this.prompt, this.logger, this.argv).setProjectContext(this.projectContext).run(buildContext);
|
|
45
45
|
}
|
|
46
46
|
}
|
|
47
47
|
// Annotate the CommonJS export names for ESM import in node:
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/command-implementations/build-command.ts"],
|
|
4
|
-
"sourcesContent": ["import type commandDefinitions from '../command-definitions'\nimport * as utils from '../utils'\nimport { BundleCommand } from './bundle-command'\nimport { GenerateCommand } from './gen-command'\nimport { ProjectCommand } from './project-command'\n\nexport type BuildCommandDefinition = typeof commandDefinitions.build\nexport class BuildCommand extends ProjectCommand<BuildCommandDefinition> {\n public async run(buildContext?: utils.esbuild.
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,4BAA8B;AAC9B,yBAAgC;AAChC,6BAA+B;AAGxB,MAAM,qBAAqB,sCAAuC;AAAA,EACvE,MAAa,IAAI,
|
|
4
|
+
"sourcesContent": ["import type commandDefinitions from '../command-definitions'\nimport * as utils from '../utils'\nimport { BundleCommand } from './bundle-command'\nimport { GenerateCommand } from './gen-command'\nimport { ProjectCommand } from './project-command'\n\nexport type BuildCommandDefinition = typeof commandDefinitions.build\nexport class BuildCommand extends ProjectCommand<BuildCommandDefinition> {\n public async run(buildContext?: utils.esbuild.BuildCodeContext): Promise<void> {\n const t0 = Date.now()\n const { projectType } = this.readProjectDefinitionFromFS()\n\n if (projectType === 'interface') {\n this.logger.success('Interface projects have nothing to build.')\n return\n }\n\n await this._runGenerate()\n\n await this._runBundle(buildContext)\n const dt = Date.now() - t0\n this.logger.log(`Build completed in ${dt}ms`)\n }\n\n private _runGenerate() {\n return new GenerateCommand(this.api, this.prompt, this.logger, this.argv)\n .setProjectContext(this.projectContext)\n .run()\n }\n\n private _runBundle(buildContext?: utils.esbuild.BuildCodeContext) {\n return new BundleCommand(this.api, this.prompt, this.logger, this.argv)\n .setProjectContext(this.projectContext)\n .run(buildContext)\n }\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,4BAA8B;AAC9B,yBAAgC;AAChC,6BAA+B;AAGxB,MAAM,qBAAqB,sCAAuC;AAAA,EACvE,MAAa,IAAI,cAA8D;AAC7E,UAAM,KAAK,KAAK,IAAI;AACpB,UAAM,EAAE,YAAY,IAAI,KAAK,4BAA4B;AAEzD,QAAI,gBAAgB,aAAa;AAC/B,WAAK,OAAO,QAAQ,2CAA2C;AAC/D;AAAA,IACF;AAEA,UAAM,KAAK,aAAa;AAExB,UAAM,KAAK,WAAW,YAAY;AAClC,UAAM,KAAK,KAAK,IAAI,IAAI;AACxB,SAAK,OAAO,IAAI,sBAAsB,EAAE,IAAI;AAAA,EAC9C;AAAA,EAEQ,eAAe;AACrB,WAAO,IAAI,mCAAgB,KAAK,KAAK,KAAK,QAAQ,KAAK,QAAQ,KAAK,IAAI,EACrE,kBAAkB,KAAK,cAAc,EACrC,IAAI;AAAA,EACT;AAAA,EAEQ,WAAW,cAA+C;AAChE,WAAO,IAAI,oCAAc,KAAK,KAAK,KAAK,QAAQ,KAAK,QAAQ,KAAK,IAAI,EACnE,kBAAkB,KAAK,cAAc,EACrC,IAAI,YAAY;AAAA,EACrB;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -3,7 +3,7 @@ import * as utils from '../utils';
|
|
|
3
3
|
import { ProjectCommand } from './project-command';
|
|
4
4
|
export type BundleCommandDefinition = typeof commandDefinitions.bundle;
|
|
5
5
|
export declare class BundleCommand extends ProjectCommand<BundleCommandDefinition> {
|
|
6
|
-
run(buildContext?: utils.esbuild.
|
|
6
|
+
run(buildContext?: utils.esbuild.BuildCodeContext): Promise<void>;
|
|
7
7
|
private _bundle;
|
|
8
8
|
private get _code();
|
|
9
9
|
private get _buildOptions();
|
|
@@ -63,7 +63,7 @@ class BundleCommand extends import_project_command.ProjectCommand {
|
|
|
63
63
|
}
|
|
64
64
|
async _bundle(outfile, buildContext, props = {}) {
|
|
65
65
|
const abs = this.projectPaths.abs;
|
|
66
|
-
const context = buildContext ?? new utils.esbuild.
|
|
66
|
+
const context = buildContext ?? new utils.esbuild.BuildCodeContext();
|
|
67
67
|
await context.rebuild(
|
|
68
68
|
{
|
|
69
69
|
outfile,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/command-implementations/bundle-command.ts"],
|
|
4
|
-
"sourcesContent": ["import chalk from 'chalk'\nimport type commandDefinitions from '../command-definitions'\nimport * as errors from '../errors'\nimport * as utils from '../utils'\nimport { ProjectCommand } from './project-command'\n\nexport type BundleCommandDefinition = typeof commandDefinitions.bundle\nexport class BundleCommand extends ProjectCommand<BundleCommandDefinition> {\n public async run(buildContext?: utils.esbuild.
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAkB;AAElB,aAAwB;AACxB,YAAuB;AACvB,6BAA+B;AAGxB,MAAM,sBAAsB,sCAAwC;AAAA,EACzE,MAAa,IAAI,
|
|
4
|
+
"sourcesContent": ["import chalk from 'chalk'\nimport type commandDefinitions from '../command-definitions'\nimport * as errors from '../errors'\nimport * as utils from '../utils'\nimport { ProjectCommand } from './project-command'\n\nexport type BundleCommandDefinition = typeof commandDefinitions.bundle\nexport class BundleCommand extends ProjectCommand<BundleCommandDefinition> {\n public async run(buildContext?: utils.esbuild.BuildCodeContext): Promise<void> {\n const { projectType, resolveProjectDefinition } = this.readProjectDefinitionFromFS()\n\n const abs = this.projectPaths.abs\n const rel = this.projectPaths.rel('workDir')\n const line = this.logger.line()\n\n if (projectType === 'interface') {\n this.logger.success('Interface projects have no implementation to bundle.')\n } else if (projectType === 'integration') {\n const projectDef = await resolveProjectDefinition()\n const { name, __advanced } = projectDef.definition\n line.started(`Bundling integration ${chalk.bold(name)}...`)\n await this._bundle(abs.outFileCJS, buildContext, __advanced?.esbuild ?? {})\n } else if (projectType === 'bot') {\n line.started('Bundling bot...')\n await this._bundle(abs.outFileCJS, buildContext)\n } else if (projectType === 'plugin') {\n line.started('Bundling plugin with platform node...')\n await this._bundle(abs.outFileCJS, buildContext)\n\n line.started('Bundling plugin with platform browser...')\n await this._bundle(abs.outFileESM, buildContext, { platform: 'browser', format: 'esm' })\n } else {\n throw new errors.UnsupportedProjectType()\n }\n\n line.success(`Bundle available at ${chalk.grey(rel.outDir)}`)\n }\n\n private async _bundle(\n outfile: string,\n buildContext?: utils.esbuild.BuildCodeContext,\n props: Partial<utils.esbuild.BuildOptions> = {}\n ) {\n const abs = this.projectPaths.abs\n const context = buildContext ?? new utils.esbuild.BuildCodeContext()\n await context.rebuild(\n {\n outfile,\n absWorkingDir: abs.workDir,\n code: this._code,\n },\n {\n ...this._buildOptions,\n ...props,\n }\n )\n }\n\n private get _code() {\n const rel = this.projectPaths.rel('workDir')\n const unixPath = utils.path.toUnix(rel.entryPoint)\n const importFrom = utils.path.rmExtension(unixPath)\n return `import x from './${importFrom}'; export default x; export const handler = x.handler;`\n }\n\n private get _buildOptions(): Partial<utils.esbuild.BuildOptions> {\n return {\n logLevel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c,QACZ,SACA,cACA,QAA6C,CAAC,GAC9C;AACA,UAAM,MAAM,KAAK,aAAa;AAC9B,UAAM,UAAU,gBAAgB,IAAI,MAAM,QAAQ,iBAAiB;AACnE,UAAM,QAAQ;AAAA,MACZ;AAAA,QACE;AAAA,QACA,eAAe,IAAI;AAAA,QACnB,MAAM,KAAK;AAAA,MACb;AAAA,MACA;AAAA,QACE,GAAG,KAAK;AAAA,QACR,GAAG;AAAA,MACL;AAAA,IACF;AAAA,EACF;AAAA,EAEA,IAAY,QAAQ;AAClB,UAAM,MAAM,KAAK,aAAa,IAAI,SAAS;AAC3C,UAAM,WAAW,MAAM,KAAK,OAAO,IAAI,UAAU;AACjD,UAAM,aAAa,MAAM,KAAK,YAAY,QAAQ;AAClD,WAAO,oBAAoB,UAAU;AAAA,EACvC;AAAA,EAEA,IAAY,gBAAqD;AAC/D,WAAO;AAAA,MACL,UAAU,KAAK,KAAK,UAAU,SAAS;AAAA,MACvC,WAAW,KAAK,KAAK;AAAA,MACrB,QAAQ,KAAK,KAAK;AAAA,IACpB;AAAA,EACF;AACF;",
|
|
6
6
|
"names": ["chalk"]
|
|
7
7
|
}
|
|
@@ -67,7 +67,7 @@ class DeployCommand extends import_project_command.ProjectCommand {
|
|
|
67
67
|
throw new errors.UnsupportedProjectType();
|
|
68
68
|
}
|
|
69
69
|
async _runBuild() {
|
|
70
|
-
return new import_build_command.BuildCommand(this.api, this.prompt, this.logger, this.argv).run();
|
|
70
|
+
return new import_build_command.BuildCommand(this.api, this.prompt, this.logger, this.argv).setProjectContext(this.projectContext).run();
|
|
71
71
|
}
|
|
72
72
|
get _visibility() {
|
|
73
73
|
if (this.argv.public && this.argv.visibility === "private") {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/command-implementations/deploy-command.ts"],
|
|
4
|
-
"sourcesContent": ["import type * as client from '@botpress/client'\nimport * as sdk from '@botpress/sdk'\nimport chalk from 'chalk'\nimport * as fs from 'fs'\nimport semver from 'semver'\nimport * as apiUtils from '../api'\nimport type commandDefinitions from '../command-definitions'\nimport * as errors from '../errors'\nimport * as tables from '../tables'\nimport * as utils from '../utils'\nimport { BuildCommand } from './build-command'\nimport { ProjectCommand } from './project-command'\n\nexport type DeployCommandDefinition = typeof commandDefinitions.deploy\nexport class DeployCommand extends ProjectCommand<DeployCommandDefinition> {\n public async run(): Promise<void> {\n const api = await this.ensureLoginAndCreateClient(this.argv)\n\n if (!this.argv.noBuild) {\n await this._runBuild() // This ensures the bundle is always synced with source code\n }\n\n const { projectType, resolveProjectDefinition } = this.readProjectDefinitionFromFS()\n\n if (projectType === 'integration') {\n const projectDef = await resolveProjectDefinition()\n return this._deployIntegration(api, projectDef.definition)\n }\n if (projectType === 'interface') {\n const projectDef = await resolveProjectDefinition()\n return this._deployInterface(api, projectDef.definition)\n }\n if (projectType === 'plugin') {\n const projectDef = await resolveProjectDefinition()\n return this._deployPlugin(api, projectDef.definition)\n }\n if (projectType === 'bot') {\n const projectDef = await resolveProjectDefinition()\n return this._deployBot(api, projectDef.definition, this.argv.botId, this.argv.createNewBot)\n }\n throw new errors.UnsupportedProjectType()\n }\n\n private async _runBuild() {\n return new BuildCommand(this.api, this.prompt, this.logger, this.argv).run()\n }\n\n private get _visibility(): 'public' | 'private' | 'unlisted' {\n if (this.argv.public && this.argv.visibility === 'private') {\n this.logger.warn('The --public flag is deprecated. Please use \"--visibility public\" instead.')\n return 'public'\n }\n\n if (this.argv.public && this.argv.visibility !== 'private') {\n this.logger.warn('The --public flag and --visibility option are both present. Ignoring the --public flag...')\n }\n\n return this.argv.visibility\n }\n\n private async _deployIntegration(api: apiUtils.ApiClient, integrationDef: sdk.IntegrationDefinition) {\n const res = await this._manageWorkspaceHandle(api, integrationDef)\n if (!res) return\n const { integration: updatedIntegrationDef, workspaceId } = res\n integrationDef = updatedIntegrationDef\n if (workspaceId) {\n api = api.switchWorkspace(workspaceId)\n }\n\n const { name, version } = integrationDef\n\n if (integrationDef.icon && !integrationDef.icon.toLowerCase().endsWith('.svg')) {\n throw new errors.BotpressCLIError('Icon must be an SVG file')\n }\n\n if (integrationDef.readme && !integrationDef.readme.toLowerCase().endsWith('.md')) {\n throw new errors.BotpressCLIError('Readme must be a Markdown file')\n }\n\n const integration = await api.findPublicOrPrivateIntegration({ type: 'name', name, version })\n if (integration && integration.workspaceId !== api.workspaceId) {\n throw new errors.BotpressCLIError(\n `Public integration ${name} v${version} is already deployed in another workspace.`\n )\n }\n\n if (integration && integration.visibility !== 'private' && !api.isBotpressWorkspace) {\n throw new errors.BotpressCLIError(\n `Integration ${name} v${version} is already deployed publicly and cannot be updated. Please bump the version.`\n )\n }\n\n let message: string\n if (integration) {\n this.logger.warn('Integration already exists. If you decide to deploy, it will override the existing one.')\n message = `Are you sure you want to override integration ${name} v${version}?`\n } else {\n message = `Are you sure you want to deploy integration ${name} v${version}?`\n }\n\n const confirm = await this.prompt.confirm(message)\n if (!confirm) {\n this.logger.log('Aborted')\n return\n }\n\n this.logger.debug('Preparing integration request body...')\n\n const createBody = {\n ...(await this.prepareCreateIntegrationBody(integrationDef)),\n ...(await this.prepareIntegrationDependencies(integrationDef, api)),\n visibility: this._visibility,\n }\n\n const startedMessage = `Deploying integration ${chalk.bold(name)} v${version}...`\n const successMessage = 'Integration deployed'\n if (integration) {\n const updateBody = apiUtils.prepareUpdateIntegrationBody(\n {\n id: integration.id,\n ...createBody,\n },\n integration\n )\n\n const { secrets: knownSecrets } = integration\n updateBody.secrets = await this.promptSecrets(integrationDef, this.argv, { knownSecrets })\n this._detectDeprecatedFeatures(integrationDef, { allowDeprecated: true })\n\n const line = this.logger.line()\n line.started(startedMessage)\n\n if (this.argv.dryRun) {\n this.logger.log('Dry-run mode is active. Simulating integration update...')\n\n await api.client.validateIntegrationUpdate(updateBody).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not update integration \"${name}\"`)\n })\n } else {\n await api.client.updateIntegration(updateBody).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not update integration \"${name}\"`)\n })\n }\n\n line.success(successMessage)\n } else {\n this.logger.debug(`looking for previous version of integration \"${name}\"`)\n const previousVersion = await api.findPreviousIntegrationVersion({ type: 'name', name, version })\n\n if (previousVersion) {\n this.logger.debug(`previous version found: ${previousVersion.version}`)\n } else {\n this.logger.debug('no previous version found')\n }\n\n const knownSecrets = previousVersion?.secrets\n\n createBody.secrets = await this.promptSecrets(integrationDef, this.argv, { knownSecrets })\n this._detectDeprecatedFeatures(integrationDef, {\n allowDeprecated: this._allowDeprecatedFeatures(integrationDef, previousVersion),\n })\n\n const line = this.logger.line()\n line.started(startedMessage)\n\n if (this.argv.dryRun) {\n this.logger.log('Dry-run mode is active. Simulating integration creation...')\n\n await api.client.validateIntegrationCreation(createBody).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not create integration \"${name}\"`)\n })\n } else {\n await api.client.createIntegration(createBody).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not create integration \"${name}\"`)\n })\n }\n\n line.success(successMessage)\n }\n }\n\n private async _deployInterface(api: apiUtils.ApiClient, interfaceDeclaration: sdk.InterfaceDefinition) {\n if (this._visibility === 'unlisted') {\n throw new errors.BotpressCLIError(\n 'Unlisted visibility is not supported for interfaces. Please use \"public\" or \"private\".'\n )\n }\n\n if (interfaceDeclaration.icon && !interfaceDeclaration.icon.toLowerCase().endsWith('.svg')) {\n throw new errors.BotpressCLIError('Icon must be an SVG file')\n }\n\n if (interfaceDeclaration.readme && !interfaceDeclaration.readme.toLowerCase().endsWith('.md')) {\n throw new errors.BotpressCLIError('Readme must be a Markdown file')\n }\n\n const { name, version } = interfaceDeclaration\n const intrface = await api.findPublicOrPrivateInterface({ type: 'name', name, version })\n\n let message: string\n if (intrface) {\n this.logger.warn('Interface already exists. If you decide to deploy, it will override the existing one.')\n message = `Are you sure you want to override interface ${name} v${version}?`\n } else {\n message = `Are you sure you want to deploy interface ${name} v${version}?`\n }\n\n const confirm = await this.prompt.confirm(message)\n if (!confirm) {\n this.logger.log('Aborted')\n return\n }\n\n const icon = await this.readProjectFile(interfaceDeclaration.icon, 'base64')\n const readme = await this.readProjectFile(interfaceDeclaration.readme, 'base64')\n\n const createBody = {\n ...(await apiUtils.prepareCreateInterfaceBody(interfaceDeclaration)),\n public: this._visibility === 'public',\n icon,\n readme,\n }\n\n const startedMessage = `Deploying interface ${chalk.bold(name)} v${version}...`\n const successMessage = 'Interface deployed'\n if (intrface) {\n const updateBody = apiUtils.prepareUpdateInterfaceBody(\n {\n id: intrface.id,\n ...createBody,\n },\n intrface\n )\n\n const line = this.logger.line()\n line.started(startedMessage)\n\n if (this.argv.dryRun) {\n this.logger.warn('Dry-run mode is not supported for interface updates. Skipping deployment...')\n } else {\n await api.client.updateInterface(updateBody).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not update interface \"${name}\"`)\n })\n }\n\n line.success(successMessage)\n } else {\n const line = this.logger.line()\n line.started(startedMessage)\n\n if (this.argv.dryRun) {\n this.logger.warn('Dry-run mode is not supported for interface creation. Skipping deployment...')\n } else {\n await api.client.createInterface(createBody).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not create interface \"${name}\"`)\n })\n }\n\n line.success(successMessage)\n }\n }\n\n private async _deployPlugin(api: apiUtils.ApiClient, pluginDef: sdk.PluginDefinition) {\n if (this._visibility === 'unlisted') {\n throw new errors.BotpressCLIError(\n 'Unlisted visibility is not supported for plugins. Please use \"public\" or \"private\".'\n )\n }\n\n const codeCJS = await fs.promises.readFile(this.projectPaths.abs.outFileCJS, 'utf-8')\n const codeESM = await fs.promises.readFile(this.projectPaths.abs.outFileESM, 'utf-8')\n\n const { name, version } = pluginDef\n\n if (pluginDef.icon && !pluginDef.icon.toLowerCase().endsWith('.svg')) {\n throw new errors.BotpressCLIError('Icon must be an SVG file')\n }\n\n if (pluginDef.readme && !pluginDef.readme.toLowerCase().endsWith('.md')) {\n throw new errors.BotpressCLIError('Readme must be a Markdown file')\n }\n\n const plugin = await api.findPublicOrPrivatePlugin({ type: 'name', name, version })\n\n let message: string\n if (plugin) {\n this.logger.warn('Plugin already exists. If you decide to deploy, it will override the existing one.')\n message = `Are you sure you want to override plugin ${name} v${version}?`\n } else {\n message = `Are you sure you want to deploy plugin ${name} v${version}?`\n }\n\n const confirm = await this.prompt.confirm(message)\n if (!confirm) {\n this.logger.log('Aborted')\n return\n }\n\n this.logger.debug('Preparing plugin request body...')\n\n const icon = await this.readProjectFile(pluginDef.icon, 'base64')\n const readme = await this.readProjectFile(pluginDef.readme, 'base64')\n\n const createBody = {\n ...(await apiUtils.prepareCreatePluginBody(pluginDef)),\n ...(await this.preparePluginDependencies(pluginDef, api)),\n public: this._visibility === 'public',\n icon,\n readme,\n code: {\n node: codeCJS,\n browser: codeESM,\n },\n }\n\n const startedMessage = `Deploying plugin ${chalk.bold(name)} v${version}...`\n const successMessage = 'Plugin deployed'\n if (plugin) {\n const updateBody = apiUtils.prepareUpdatePluginBody(\n {\n id: plugin.id,\n ...createBody,\n },\n plugin\n )\n\n const line = this.logger.line()\n line.started(startedMessage)\n\n if (this.argv.dryRun) {\n this.logger.warn('Dry-run mode is not supported for plugin updates. Skipping deployment...')\n } else {\n await api.client.updatePlugin(updateBody).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not update plugin \"${name}\"`)\n })\n }\n\n line.success(successMessage)\n } else {\n const line = this.logger.line()\n line.started(startedMessage)\n\n if (this.argv.dryRun) {\n this.logger.warn('Dry-run mode is not supported for plugin creation. Skipping deployment...')\n } else {\n await api.client.createPlugin(createBody).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not create plugin \"${name}\"`)\n })\n }\n\n line.success(successMessage)\n }\n }\n\n private _allowDeprecatedFeatures(\n integrationDef: sdk.IntegrationDefinition,\n previousVersion: client.Integration | undefined\n ): boolean {\n if (this.argv.allowDeprecated) {\n return true\n }\n\n if (!previousVersion) {\n return false\n }\n\n const versionDiff = semver.diff(integrationDef.version, previousVersion.version)\n if (!versionDiff) {\n return false\n }\n\n return utils.semver.releases.lt(versionDiff, 'major')\n }\n\n private _detectDeprecatedFeatures(\n integrationDef: sdk.IntegrationDefinition,\n opts: { allowDeprecated?: boolean } = {}\n ) {\n const deprecatedFields: string[] = []\n const { user, channels } = integrationDef\n if (user?.creation?.enabled) {\n deprecatedFields.push('user.creation')\n }\n\n for (const [channelName, channel] of Object.entries(channels ?? {})) {\n if (channel?.conversation?.creation?.enabled) {\n deprecatedFields.push(`channels.${channelName}.creation`)\n }\n }\n\n if (!deprecatedFields.length) {\n return\n }\n\n const errorMessage = `The following fields of the integration's definition are deprecated: ${deprecatedFields.join(\n ', '\n )}`\n\n if (opts.allowDeprecated) {\n this.logger.warn(errorMessage)\n } else {\n throw new errors.BotpressCLIError(errorMessage)\n }\n }\n\n private async _deployBot(\n api: apiUtils.ApiClient,\n botDefinition: sdk.BotDefinition,\n argvBotId: string | undefined,\n argvCreateNew: boolean | undefined\n ) {\n if (this.argv.dryRun) {\n this.logger.warn('Dry-run mode is not supported for bot deployments. Skipping deployment...')\n return\n }\n\n const outfile = this.projectPaths.abs.outFileCJS\n const code = await fs.promises.readFile(outfile, 'utf-8')\n\n let bot: client.Bot\n if (argvBotId && argvCreateNew) {\n throw new errors.BotpressCLIError('Cannot specify both --botId and --createNew')\n } else if (argvCreateNew) {\n const confirm = await this.prompt.confirm('Are you sure you want to create a new bot ?')\n if (!confirm) {\n this.logger.log('Aborted')\n return\n }\n\n bot = await this._createNewBot(api)\n } else {\n bot = await this._getExistingBot(api, argvBotId)\n\n const confirm = await this.prompt.confirm(`Are you sure you want to deploy the bot \"${bot.name}\"?`)\n if (!confirm) {\n this.logger.log('Aborted')\n return\n }\n }\n\n const line = this.logger.line()\n line.started(`Deploying bot ${chalk.bold(bot.name)}...`)\n\n const updateBotBody = apiUtils.prepareUpdateBotBody(\n {\n ...(await apiUtils.prepareCreateBotBody(botDefinition)),\n ...(await this.prepareBotDependencies(botDefinition, api)),\n id: bot.id,\n code,\n },\n bot\n )\n\n const { bot: updatedBot } = await api.client.updateBot(updateBotBody).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not update bot \"${bot.name}\"`)\n })\n\n this.validateIntegrationRegistration(updatedBot, (failedIntegrations) =>\n this.logger.warn(\n `Some integrations failed to register:\\n${Object.entries(failedIntegrations)\n .map(([key, int]) => `\u2022 ${key}: ${int.statusReason}`)\n .join('\\n')}`\n )\n )\n\n const tablesPublisher = new tables.TablesPublisher({ api, logger: this.logger, prompt: this.prompt })\n await tablesPublisher.deployTables({ botId: updatedBot.id, botDefinition })\n\n line.success('Bot deployed')\n this.displayWebhookUrls(updatedBot)\n }\n\n private async _createNewBot(api: apiUtils.ApiClient): Promise<client.Bot> {\n const line = this.logger.line()\n const { bot: createdBot } = await api.client.createBot({}).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, 'Could not create bot')\n })\n line.success(`Bot created with ID \"${createdBot.id}\" and name \"${createdBot.name}\"`)\n await this.projectCache.set('botId', createdBot.id)\n return createdBot\n }\n\n private async _getExistingBot(api: apiUtils.ApiClient, botId: string | undefined): Promise<client.Bot> {\n const promptedBotId = await this.projectCache.sync('botId', botId, async (defaultId) => {\n const userBots = await api\n .listAllPages(api.client.listBots, (r) => r.bots)\n .catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, 'Could not fetch existing bots')\n })\n\n if (!userBots.length) {\n throw new errors.NoBotsFoundError()\n }\n\n const initial = userBots.find((bot) => bot.id === defaultId)\n\n const prompted = await this.prompt.select('Which bot do you want to deploy?', {\n initial: initial && { title: initial.name, value: initial.id },\n choices: userBots.map((bot) => ({ title: bot.name, value: bot.id })),\n })\n\n if (!prompted) {\n throw new errors.ParamRequiredError('Bot Id')\n }\n\n return prompted\n })\n\n const { bot: fetchedBot } = await api.client.getBot({ id: promptedBotId }).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, 'Could not get bot info')\n })\n\n return fetchedBot\n }\n\n private async _manageWorkspaceHandle(\n api: apiUtils.ApiClient,\n integration: sdk.IntegrationDefinition\n ): Promise<\n | {\n integration: sdk.IntegrationDefinition\n workspaceId?: string // Set if user opted to deploy on another available workspace\n }\n | undefined\n > {\n const { name: localName, workspaceHandle: localHandle } = this._parseIntegrationName(integration.name)\n if (!localHandle && api.isBotpressWorkspace) {\n this.logger.debug('Botpress workspace detected; workspace handle omitted')\n return { integration } // botpress has the right to omit workspace handle\n }\n\n const { handle: remoteHandle, name: workspaceName } = await api.getWorkspace().catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, 'Could not fetch workspace')\n })\n\n if (localHandle && remoteHandle) {\n let workspaceId: string | undefined = undefined\n if (localHandle !== remoteHandle) {\n const remoteWorkspace = await api.findWorkspaceByHandle(localHandle).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, 'Could not list workspaces')\n })\n if (!remoteWorkspace) {\n throw new errors.BotpressCLIError(\n `The integration handle \"${localHandle}\" is not associated with any of your workspaces.`\n )\n }\n this.logger.warn(\n `Your are logged in to workspace \"${workspaceName}\" but integration handle \"${localHandle}\" belongs to \"${remoteWorkspace.name}\".`\n )\n const confirmUseAlternateWorkspace = await this.prompt.confirm(\n 'Do you want to deploy integration on this workspace instead?'\n )\n if (!confirmUseAlternateWorkspace) {\n throw new errors.BotpressCLIError(\n `Cannot deploy integration with handle \"${localHandle}\" on workspace \"${workspaceName}\"`\n )\n }\n\n workspaceId = remoteWorkspace.id\n }\n return { integration, workspaceId }\n }\n\n const workspaceHandleIsMandatoryMsg = 'Cannot deploy integration without workspace handle'\n\n if (!localHandle && remoteHandle) {\n const confirmAddHandle = await this.prompt.confirm(\n `Your current workspace handle is \"${remoteHandle}\". Do you want to use the name \"${remoteHandle}/${localName}\"?`\n )\n if (!confirmAddHandle) {\n this.logger.log('Aborted')\n return\n }\n const newName = `${remoteHandle}/${localName}`\n return { integration: new sdk.IntegrationDefinition({ ...integration, name: newName }) }\n }\n\n if (localHandle && !remoteHandle) {\n const { available } = await api.client.checkHandleAvailability({ handle: localHandle }).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, 'Could not check handle availability')\n })\n\n if (!available) {\n throw new errors.BotpressCLIError(`Handle \"${localHandle}\" is not yours and is not available`)\n }\n\n const confirmClaimHandle = await this.prompt.confirm(\n `Handle \"${localHandle}\" is available. Do you want to claim it for your workspace ${workspaceName}?`\n )\n if (!confirmClaimHandle) {\n throw new errors.BotpressCLIError(workspaceHandleIsMandatoryMsg)\n }\n\n await api.updateWorkspace({ handle: localHandle }).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not claim handle \"${localHandle}\"`)\n })\n\n this.logger.success(`Handle \"${localHandle}\" is now yours!`)\n return { integration }\n }\n\n this.logger.warn(\"It seems you don't have a workspace handle yet.\")\n let claimedHandle: string | undefined = undefined\n do {\n const prompted = await this.prompt.text('Please enter a workspace handle')\n if (!prompted) {\n throw new errors.BotpressCLIError(workspaceHandleIsMandatoryMsg)\n }\n\n const { available, suggestions } = await api.client.checkHandleAvailability({ handle: prompted })\n if (!available) {\n this.logger.warn(`Handle \"${prompted}\" is not available. Suggestions: ${suggestions.join(', ')}`)\n continue\n }\n\n claimedHandle = prompted\n await api.updateWorkspace({ handle: claimedHandle }).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not claim handle \"${claimedHandle}\"`)\n })\n } while (!claimedHandle)\n\n this.logger.success(`Handle \"${claimedHandle}\" is yours!`)\n const newName = `${claimedHandle}/${localName}`\n return { integration: new sdk.IntegrationDefinition({ ...integration, name: newName }) }\n }\n\n private _parseIntegrationName = (integrationName: string): { name: string; workspaceHandle?: string } => {\n const parts = integrationName.split('/')\n if (parts.length > 2) {\n throw new errors.BotpressCLIError(\n `Invalid integration name \"${integrationName}\": a single forward slash is allowed`\n )\n }\n if (parts.length === 2) {\n const [workspaceHandle, name] = parts as [string, string]\n return { name, workspaceHandle }\n }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AAK,iDAAiD;AAClE,QAAI,gBAAoC;AACxC,OAAG;AACD,YAAM,WAAW,MAAM,KAAK,OAAO,KAAK,iCAAiC;AACzE,UAAI,CAAC,UAAU;AACb,cAAM,IAAI,OAAO,iBAAiB,6BAA6B;AAAA,MACjE;AAEA,YAAM,EAAE,WAAW,YAAY,IAAI,MAAM,IAAI,OAAO,wBAAwB,EAAE,QAAQ,SAAS,CAAC;AAChG,UAAI,CAAC,WAAW;AACd,aAAK,OAAO,KAAK,WAAW,QAAQ,oCAAoC,YAAY,KAAK,IAAI,CAAC,EAAE;AAChG;AAAA,MACF;AAEA,sBAAgB;AAChB,YAAM,IAAI,gBAAgB,EAAE,QAAQ,cAAc,CAAC,EAAE,MAAM,CAAC,WAAW;AACrE,cAAM,OAAO,iBAAiB,KAAK,QAAQ,2BAA2B,aAAa,GAAG;AAAA,MACxF,CAAC;AAAA,IACH,SAAS,CAAC;AAEV,SAAK,OAAO,QAAQ,WAAW,aAAa,aAAa;AACzD,UAAM,UAAU,GAAG,aAAa,IAAI,SAAS;AAC7C,WAAO,EAAE,aAAa,IAAI,IAAI,sBAAsB,EAAE,GAAG,aAAa,MAAM,QAAQ,CAAC,EAAE;AAAA,EACzF;AAAA,EAEQ,wBAAwB,CAAC,oBAAwE;AACvG,UAAM,QAAQ,gBAAgB,MAAM,GAAG;AACvC,QAAI,MAAM,SAAS,GAAG;AACpB,YAAM,IAAI,OAAO;AAAA,QACf,6BAA6B,eAAe;AAAA,MAC9C;AAAA,IACF;AACA,QAAI,MAAM,WAAW,GAAG;AACtB,YAAM,CAAC,iBAAiBC,KAAI,IAAI;AAChC,aAAO,EAAE,MAAAA,OAAM,gBAAgB;AAAA,IACjC;AACA,UAAM,CAAC,IAAI,IAAI;AACf,WAAO,EAAE,KAAK;AAAA,EAChB;AACF;",
|
|
4
|
+
"sourcesContent": ["import type * as client from '@botpress/client'\nimport * as sdk from '@botpress/sdk'\nimport chalk from 'chalk'\nimport * as fs from 'fs'\nimport semver from 'semver'\nimport * as apiUtils from '../api'\nimport type commandDefinitions from '../command-definitions'\nimport * as errors from '../errors'\nimport * as tables from '../tables'\nimport * as utils from '../utils'\nimport { BuildCommand } from './build-command'\nimport { ProjectCommand } from './project-command'\n\nexport type DeployCommandDefinition = typeof commandDefinitions.deploy\nexport class DeployCommand extends ProjectCommand<DeployCommandDefinition> {\n public async run(): Promise<void> {\n const api = await this.ensureLoginAndCreateClient(this.argv)\n\n if (!this.argv.noBuild) {\n await this._runBuild() // This ensures the bundle is always synced with source code\n }\n\n const { projectType, resolveProjectDefinition } = this.readProjectDefinitionFromFS()\n\n if (projectType === 'integration') {\n const projectDef = await resolveProjectDefinition()\n return this._deployIntegration(api, projectDef.definition)\n }\n if (projectType === 'interface') {\n const projectDef = await resolveProjectDefinition()\n return this._deployInterface(api, projectDef.definition)\n }\n if (projectType === 'plugin') {\n const projectDef = await resolveProjectDefinition()\n return this._deployPlugin(api, projectDef.definition)\n }\n if (projectType === 'bot') {\n const projectDef = await resolveProjectDefinition()\n return this._deployBot(api, projectDef.definition, this.argv.botId, this.argv.createNewBot)\n }\n throw new errors.UnsupportedProjectType()\n }\n\n private async _runBuild() {\n return new BuildCommand(this.api, this.prompt, this.logger, this.argv).setProjectContext(this.projectContext).run()\n }\n\n private get _visibility(): 'public' | 'private' | 'unlisted' {\n if (this.argv.public && this.argv.visibility === 'private') {\n this.logger.warn('The --public flag is deprecated. Please use \"--visibility public\" instead.')\n return 'public'\n }\n\n if (this.argv.public && this.argv.visibility !== 'private') {\n this.logger.warn('The --public flag and --visibility option are both present. Ignoring the --public flag...')\n }\n\n return this.argv.visibility\n }\n\n private async _deployIntegration(api: apiUtils.ApiClient, integrationDef: sdk.IntegrationDefinition) {\n const res = await this._manageWorkspaceHandle(api, integrationDef)\n if (!res) return\n const { integration: updatedIntegrationDef, workspaceId } = res\n integrationDef = updatedIntegrationDef\n if (workspaceId) {\n api = api.switchWorkspace(workspaceId)\n }\n\n const { name, version } = integrationDef\n\n if (integrationDef.icon && !integrationDef.icon.toLowerCase().endsWith('.svg')) {\n throw new errors.BotpressCLIError('Icon must be an SVG file')\n }\n\n if (integrationDef.readme && !integrationDef.readme.toLowerCase().endsWith('.md')) {\n throw new errors.BotpressCLIError('Readme must be a Markdown file')\n }\n\n const integration = await api.findPublicOrPrivateIntegration({ type: 'name', name, version })\n if (integration && integration.workspaceId !== api.workspaceId) {\n throw new errors.BotpressCLIError(\n `Public integration ${name} v${version} is already deployed in another workspace.`\n )\n }\n\n if (integration && integration.visibility !== 'private' && !api.isBotpressWorkspace) {\n throw new errors.BotpressCLIError(\n `Integration ${name} v${version} is already deployed publicly and cannot be updated. Please bump the version.`\n )\n }\n\n let message: string\n if (integration) {\n this.logger.warn('Integration already exists. If you decide to deploy, it will override the existing one.')\n message = `Are you sure you want to override integration ${name} v${version}?`\n } else {\n message = `Are you sure you want to deploy integration ${name} v${version}?`\n }\n\n const confirm = await this.prompt.confirm(message)\n if (!confirm) {\n this.logger.log('Aborted')\n return\n }\n\n this.logger.debug('Preparing integration request body...')\n\n const createBody = {\n ...(await this.prepareCreateIntegrationBody(integrationDef)),\n ...(await this.prepareIntegrationDependencies(integrationDef, api)),\n visibility: this._visibility,\n }\n\n const startedMessage = `Deploying integration ${chalk.bold(name)} v${version}...`\n const successMessage = 'Integration deployed'\n if (integration) {\n const updateBody = apiUtils.prepareUpdateIntegrationBody(\n {\n id: integration.id,\n ...createBody,\n },\n integration\n )\n\n const { secrets: knownSecrets } = integration\n updateBody.secrets = await this.promptSecrets(integrationDef, this.argv, { knownSecrets })\n this._detectDeprecatedFeatures(integrationDef, { allowDeprecated: true })\n\n const line = this.logger.line()\n line.started(startedMessage)\n\n if (this.argv.dryRun) {\n this.logger.log('Dry-run mode is active. Simulating integration update...')\n\n await api.client.validateIntegrationUpdate(updateBody).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not update integration \"${name}\"`)\n })\n } else {\n await api.client.updateIntegration(updateBody).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not update integration \"${name}\"`)\n })\n }\n\n line.success(successMessage)\n } else {\n this.logger.debug(`looking for previous version of integration \"${name}\"`)\n const previousVersion = await api.findPreviousIntegrationVersion({ type: 'name', name, version })\n\n if (previousVersion) {\n this.logger.debug(`previous version found: ${previousVersion.version}`)\n } else {\n this.logger.debug('no previous version found')\n }\n\n const knownSecrets = previousVersion?.secrets\n\n createBody.secrets = await this.promptSecrets(integrationDef, this.argv, { knownSecrets })\n this._detectDeprecatedFeatures(integrationDef, {\n allowDeprecated: this._allowDeprecatedFeatures(integrationDef, previousVersion),\n })\n\n const line = this.logger.line()\n line.started(startedMessage)\n\n if (this.argv.dryRun) {\n this.logger.log('Dry-run mode is active. Simulating integration creation...')\n\n await api.client.validateIntegrationCreation(createBody).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not create integration \"${name}\"`)\n })\n } else {\n await api.client.createIntegration(createBody).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not create integration \"${name}\"`)\n })\n }\n\n line.success(successMessage)\n }\n }\n\n private async _deployInterface(api: apiUtils.ApiClient, interfaceDeclaration: sdk.InterfaceDefinition) {\n if (this._visibility === 'unlisted') {\n throw new errors.BotpressCLIError(\n 'Unlisted visibility is not supported for interfaces. Please use \"public\" or \"private\".'\n )\n }\n\n if (interfaceDeclaration.icon && !interfaceDeclaration.icon.toLowerCase().endsWith('.svg')) {\n throw new errors.BotpressCLIError('Icon must be an SVG file')\n }\n\n if (interfaceDeclaration.readme && !interfaceDeclaration.readme.toLowerCase().endsWith('.md')) {\n throw new errors.BotpressCLIError('Readme must be a Markdown file')\n }\n\n const { name, version } = interfaceDeclaration\n const intrface = await api.findPublicOrPrivateInterface({ type: 'name', name, version })\n\n let message: string\n if (intrface) {\n this.logger.warn('Interface already exists. If you decide to deploy, it will override the existing one.')\n message = `Are you sure you want to override interface ${name} v${version}?`\n } else {\n message = `Are you sure you want to deploy interface ${name} v${version}?`\n }\n\n const confirm = await this.prompt.confirm(message)\n if (!confirm) {\n this.logger.log('Aborted')\n return\n }\n\n const icon = await this.readProjectFile(interfaceDeclaration.icon, 'base64')\n const readme = await this.readProjectFile(interfaceDeclaration.readme, 'base64')\n\n const createBody = {\n ...(await apiUtils.prepareCreateInterfaceBody(interfaceDeclaration)),\n public: this._visibility === 'public',\n icon,\n readme,\n }\n\n const startedMessage = `Deploying interface ${chalk.bold(name)} v${version}...`\n const successMessage = 'Interface deployed'\n if (intrface) {\n const updateBody = apiUtils.prepareUpdateInterfaceBody(\n {\n id: intrface.id,\n ...createBody,\n },\n intrface\n )\n\n const line = this.logger.line()\n line.started(startedMessage)\n\n if (this.argv.dryRun) {\n this.logger.warn('Dry-run mode is not supported for interface updates. Skipping deployment...')\n } else {\n await api.client.updateInterface(updateBody).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not update interface \"${name}\"`)\n })\n }\n\n line.success(successMessage)\n } else {\n const line = this.logger.line()\n line.started(startedMessage)\n\n if (this.argv.dryRun) {\n this.logger.warn('Dry-run mode is not supported for interface creation. Skipping deployment...')\n } else {\n await api.client.createInterface(createBody).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not create interface \"${name}\"`)\n })\n }\n\n line.success(successMessage)\n }\n }\n\n private async _deployPlugin(api: apiUtils.ApiClient, pluginDef: sdk.PluginDefinition) {\n if (this._visibility === 'unlisted') {\n throw new errors.BotpressCLIError(\n 'Unlisted visibility is not supported for plugins. Please use \"public\" or \"private\".'\n )\n }\n\n const codeCJS = await fs.promises.readFile(this.projectPaths.abs.outFileCJS, 'utf-8')\n const codeESM = await fs.promises.readFile(this.projectPaths.abs.outFileESM, 'utf-8')\n\n const { name, version } = pluginDef\n\n if (pluginDef.icon && !pluginDef.icon.toLowerCase().endsWith('.svg')) {\n throw new errors.BotpressCLIError('Icon must be an SVG file')\n }\n\n if (pluginDef.readme && !pluginDef.readme.toLowerCase().endsWith('.md')) {\n throw new errors.BotpressCLIError('Readme must be a Markdown file')\n }\n\n const plugin = await api.findPublicOrPrivatePlugin({ type: 'name', name, version })\n\n let message: string\n if (plugin) {\n this.logger.warn('Plugin already exists. If you decide to deploy, it will override the existing one.')\n message = `Are you sure you want to override plugin ${name} v${version}?`\n } else {\n message = `Are you sure you want to deploy plugin ${name} v${version}?`\n }\n\n const confirm = await this.prompt.confirm(message)\n if (!confirm) {\n this.logger.log('Aborted')\n return\n }\n\n this.logger.debug('Preparing plugin request body...')\n\n const icon = await this.readProjectFile(pluginDef.icon, 'base64')\n const readme = await this.readProjectFile(pluginDef.readme, 'base64')\n\n const createBody = {\n ...(await apiUtils.prepareCreatePluginBody(pluginDef)),\n ...(await this.preparePluginDependencies(pluginDef, api)),\n public: this._visibility === 'public',\n icon,\n readme,\n code: {\n node: codeCJS,\n browser: codeESM,\n },\n }\n\n const startedMessage = `Deploying plugin ${chalk.bold(name)} v${version}...`\n const successMessage = 'Plugin deployed'\n if (plugin) {\n const updateBody = apiUtils.prepareUpdatePluginBody(\n {\n id: plugin.id,\n ...createBody,\n },\n plugin\n )\n\n const line = this.logger.line()\n line.started(startedMessage)\n\n if (this.argv.dryRun) {\n this.logger.warn('Dry-run mode is not supported for plugin updates. Skipping deployment...')\n } else {\n await api.client.updatePlugin(updateBody).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not update plugin \"${name}\"`)\n })\n }\n\n line.success(successMessage)\n } else {\n const line = this.logger.line()\n line.started(startedMessage)\n\n if (this.argv.dryRun) {\n this.logger.warn('Dry-run mode is not supported for plugin creation. Skipping deployment...')\n } else {\n await api.client.createPlugin(createBody).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not create plugin \"${name}\"`)\n })\n }\n\n line.success(successMessage)\n }\n }\n\n private _allowDeprecatedFeatures(\n integrationDef: sdk.IntegrationDefinition,\n previousVersion: client.Integration | undefined\n ): boolean {\n if (this.argv.allowDeprecated) {\n return true\n }\n\n if (!previousVersion) {\n return false\n }\n\n const versionDiff = semver.diff(integrationDef.version, previousVersion.version)\n if (!versionDiff) {\n return false\n }\n\n return utils.semver.releases.lt(versionDiff, 'major')\n }\n\n private _detectDeprecatedFeatures(\n integrationDef: sdk.IntegrationDefinition,\n opts: { allowDeprecated?: boolean } = {}\n ) {\n const deprecatedFields: string[] = []\n const { user, channels } = integrationDef\n if (user?.creation?.enabled) {\n deprecatedFields.push('user.creation')\n }\n\n for (const [channelName, channel] of Object.entries(channels ?? {})) {\n if (channel?.conversation?.creation?.enabled) {\n deprecatedFields.push(`channels.${channelName}.creation`)\n }\n }\n\n if (!deprecatedFields.length) {\n return\n }\n\n const errorMessage = `The following fields of the integration's definition are deprecated: ${deprecatedFields.join(\n ', '\n )}`\n\n if (opts.allowDeprecated) {\n this.logger.warn(errorMessage)\n } else {\n throw new errors.BotpressCLIError(errorMessage)\n }\n }\n\n private async _deployBot(\n api: apiUtils.ApiClient,\n botDefinition: sdk.BotDefinition,\n argvBotId: string | undefined,\n argvCreateNew: boolean | undefined\n ) {\n if (this.argv.dryRun) {\n this.logger.warn('Dry-run mode is not supported for bot deployments. Skipping deployment...')\n return\n }\n\n const outfile = this.projectPaths.abs.outFileCJS\n const code = await fs.promises.readFile(outfile, 'utf-8')\n\n let bot: client.Bot\n if (argvBotId && argvCreateNew) {\n throw new errors.BotpressCLIError('Cannot specify both --botId and --createNew')\n } else if (argvCreateNew) {\n const confirm = await this.prompt.confirm('Are you sure you want to create a new bot ?')\n if (!confirm) {\n this.logger.log('Aborted')\n return\n }\n\n bot = await this._createNewBot(api)\n } else {\n bot = await this._getExistingBot(api, argvBotId)\n\n const confirm = await this.prompt.confirm(`Are you sure you want to deploy the bot \"${bot.name}\"?`)\n if (!confirm) {\n this.logger.log('Aborted')\n return\n }\n }\n\n const line = this.logger.line()\n line.started(`Deploying bot ${chalk.bold(bot.name)}...`)\n\n const updateBotBody = apiUtils.prepareUpdateBotBody(\n {\n ...(await apiUtils.prepareCreateBotBody(botDefinition)),\n ...(await this.prepareBotDependencies(botDefinition, api)),\n id: bot.id,\n code,\n },\n bot\n )\n\n const { bot: updatedBot } = await api.client.updateBot(updateBotBody).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not update bot \"${bot.name}\"`)\n })\n\n this.validateIntegrationRegistration(updatedBot, (failedIntegrations) =>\n this.logger.warn(\n `Some integrations failed to register:\\n${Object.entries(failedIntegrations)\n .map(([key, int]) => `\u2022 ${key}: ${int.statusReason}`)\n .join('\\n')}`\n )\n )\n\n const tablesPublisher = new tables.TablesPublisher({ api, logger: this.logger, prompt: this.prompt })\n await tablesPublisher.deployTables({ botId: updatedBot.id, botDefinition })\n\n line.success('Bot deployed')\n this.displayWebhookUrls(updatedBot)\n }\n\n private async _createNewBot(api: apiUtils.ApiClient): Promise<client.Bot> {\n const line = this.logger.line()\n const { bot: createdBot } = await api.client.createBot({}).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, 'Could not create bot')\n })\n line.success(`Bot created with ID \"${createdBot.id}\" and name \"${createdBot.name}\"`)\n await this.projectCache.set('botId', createdBot.id)\n return createdBot\n }\n\n private async _getExistingBot(api: apiUtils.ApiClient, botId: string | undefined): Promise<client.Bot> {\n const promptedBotId = await this.projectCache.sync('botId', botId, async (defaultId) => {\n const userBots = await api\n .listAllPages(api.client.listBots, (r) => r.bots)\n .catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, 'Could not fetch existing bots')\n })\n\n if (!userBots.length) {\n throw new errors.NoBotsFoundError()\n }\n\n const initial = userBots.find((bot) => bot.id === defaultId)\n\n const prompted = await this.prompt.select('Which bot do you want to deploy?', {\n initial: initial && { title: initial.name, value: initial.id },\n choices: userBots.map((bot) => ({ title: bot.name, value: bot.id })),\n })\n\n if (!prompted) {\n throw new errors.ParamRequiredError('Bot Id')\n }\n\n return prompted\n })\n\n const { bot: fetchedBot } = await api.client.getBot({ id: promptedBotId }).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, 'Could not get bot info')\n })\n\n return fetchedBot\n }\n\n private async _manageWorkspaceHandle(\n api: apiUtils.ApiClient,\n integration: sdk.IntegrationDefinition\n ): Promise<\n | {\n integration: sdk.IntegrationDefinition\n workspaceId?: string // Set if user opted to deploy on another available workspace\n }\n | undefined\n > {\n const { name: localName, workspaceHandle: localHandle } = this._parseIntegrationName(integration.name)\n if (!localHandle && api.isBotpressWorkspace) {\n this.logger.debug('Botpress workspace detected; workspace handle omitted')\n return { integration } // botpress has the right to omit workspace handle\n }\n\n const { handle: remoteHandle, name: workspaceName } = await api.getWorkspace().catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, 'Could not fetch workspace')\n })\n\n if (localHandle && remoteHandle) {\n let workspaceId: string | undefined = undefined\n if (localHandle !== remoteHandle) {\n const remoteWorkspace = await api.findWorkspaceByHandle(localHandle).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, 'Could not list workspaces')\n })\n if (!remoteWorkspace) {\n throw new errors.BotpressCLIError(\n `The integration handle \"${localHandle}\" is not associated with any of your workspaces.`\n )\n }\n this.logger.warn(\n `Your are logged in to workspace \"${workspaceName}\" but integration handle \"${localHandle}\" belongs to \"${remoteWorkspace.name}\".`\n )\n const confirmUseAlternateWorkspace = await this.prompt.confirm(\n 'Do you want to deploy integration on this workspace instead?'\n )\n if (!confirmUseAlternateWorkspace) {\n throw new errors.BotpressCLIError(\n `Cannot deploy integration with handle \"${localHandle}\" on workspace \"${workspaceName}\"`\n )\n }\n\n workspaceId = remoteWorkspace.id\n }\n return { integration, workspaceId }\n }\n\n const workspaceHandleIsMandatoryMsg = 'Cannot deploy integration without workspace handle'\n\n if (!localHandle && remoteHandle) {\n const confirmAddHandle = await this.prompt.confirm(\n `Your current workspace handle is \"${remoteHandle}\". Do you want to use the name \"${remoteHandle}/${localName}\"?`\n )\n if (!confirmAddHandle) {\n this.logger.log('Aborted')\n return\n }\n const newName = `${remoteHandle}/${localName}`\n return { integration: new sdk.IntegrationDefinition({ ...integration, name: newName }) }\n }\n\n if (localHandle && !remoteHandle) {\n const { available } = await api.client.checkHandleAvailability({ handle: localHandle }).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, 'Could not check handle availability')\n })\n\n if (!available) {\n throw new errors.BotpressCLIError(`Handle \"${localHandle}\" is not yours and is not available`)\n }\n\n const confirmClaimHandle = await this.prompt.confirm(\n `Handle \"${localHandle}\" is available. Do you want to claim it for your workspace ${workspaceName}?`\n )\n if (!confirmClaimHandle) {\n throw new errors.BotpressCLIError(workspaceHandleIsMandatoryMsg)\n }\n\n await api.updateWorkspace({ handle: localHandle }).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not claim handle \"${localHandle}\"`)\n })\n\n this.logger.success(`Handle \"${localHandle}\" is now yours!`)\n return { integration }\n }\n\n this.logger.warn(\"It seems you don't have a workspace handle yet.\")\n let claimedHandle: string | undefined = undefined\n do {\n const prompted = await this.prompt.text('Please enter a workspace handle')\n if (!prompted) {\n throw new errors.BotpressCLIError(workspaceHandleIsMandatoryMsg)\n }\n\n const { available, suggestions } = await api.client.checkHandleAvailability({ handle: prompted })\n if (!available) {\n this.logger.warn(`Handle \"${prompted}\" is not available. Suggestions: ${suggestions.join(', ')}`)\n continue\n }\n\n claimedHandle = prompted\n await api.updateWorkspace({ handle: claimedHandle }).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not claim handle \"${claimedHandle}\"`)\n })\n } while (!claimedHandle)\n\n this.logger.success(`Handle \"${claimedHandle}\" is yours!`)\n const newName = `${claimedHandle}/${localName}`\n return { integration: new sdk.IntegrationDefinition({ ...integration, name: newName }) }\n }\n\n private _parseIntegrationName = (integrationName: string): { name: string; workspaceHandle?: string } => {\n const parts = integrationName.split('/')\n if (parts.length > 2) {\n throw new errors.BotpressCLIError(\n `Invalid integration name \"${integrationName}\": a single forward slash is allowed`\n )\n }\n if (parts.length === 2) {\n const [workspaceHandle, name] = parts as [string, string]\n return { name, workspaceHandle }\n }\n const [name] = parts as [string]\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
46
46
|
const DEFAULT_BOT_PORT = 8075;
|
|
47
47
|
const DEFAULT_INTEGRATION_PORT = 8076;
|
|
48
48
|
const TUNNEL_HELLO_INTERVAL = 5e3;
|
|
49
|
-
const FILEWATCHER_DEBOUNCE_MS =
|
|
49
|
+
const FILEWATCHER_DEBOUNCE_MS = 500;
|
|
50
50
|
class DevCommand extends import_project_command.ProjectCommand {
|
|
51
51
|
_initialDef = void 0;
|
|
52
52
|
_cacheDevRequestBody;
|
|
53
53
|
_buildContext;
|
|
54
54
|
constructor(...args) {
|
|
55
55
|
super(...args);
|
|
56
|
-
this._buildContext = new utils.esbuild.
|
|
56
|
+
this._buildContext = new utils.esbuild.BuildCodeContext();
|
|
57
57
|
}
|
|
58
58
|
async run() {
|
|
59
59
|
this.logger.warn("This command is experimental and subject to breaking changes without notice.");
|
|
@@ -146,15 +146,17 @@ class DevCommand extends import_project_command.ProjectCommand {
|
|
|
146
146
|
this.logger.debug("Worker not ready yet, ignoring file change event");
|
|
147
147
|
return;
|
|
148
148
|
}
|
|
149
|
-
const typescriptEvents = events.filter((e) => pathlib.extname(e.path) === ".ts");
|
|
150
|
-
|
|
151
|
-
|
|
149
|
+
const typescriptEvents = events.filter((e) => !e.path.startsWith(this.projectPaths.abs.outDir)).filter((e) => pathlib.extname(e.path) === ".ts");
|
|
150
|
+
const distEvents = events.filter((e) => e.path.startsWith(this.projectPaths.abs.distDir));
|
|
151
|
+
if (typescriptEvents.length > 0) {
|
|
152
|
+
this.logger.log("Changes detected, rebuilding");
|
|
153
|
+
await this._restart(api, worker, httpTunnelUrl);
|
|
154
|
+
} else if (distEvents.length > 0) {
|
|
155
|
+
this.logger.log("Changes detected in output directory, reloading worker");
|
|
156
|
+
await worker.reload();
|
|
152
157
|
}
|
|
153
|
-
this.logger.log("Changes detected, rebuilding");
|
|
154
|
-
await this._restart(api, worker, httpTunnelUrl);
|
|
155
158
|
},
|
|
156
159
|
{
|
|
157
|
-
ignore: [this.projectPaths.abs.outDir],
|
|
158
160
|
debounceMs: FILEWATCHER_DEBOUNCE_MS
|
|
159
161
|
}
|
|
160
162
|
);
|
|
@@ -227,7 +229,7 @@ class DevCommand extends import_project_command.ProjectCommand {
|
|
|
227
229
|
return worker;
|
|
228
230
|
};
|
|
229
231
|
_runBuild() {
|
|
230
|
-
return new import_build_command.BuildCommand(this.api, this.prompt, this.logger, this.argv).run(this._buildContext);
|
|
232
|
+
return new import_build_command.BuildCommand(this.api, this.prompt, this.logger, this.argv).setProjectContext(this.projectContext).run(this._buildContext);
|
|
231
233
|
}
|
|
232
234
|
async _deployDevIntegration(api, externalUrl, integrationDef) {
|
|
233
235
|
const devId = await this.projectCache.get("devId");
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/command-implementations/dev-command.ts"],
|
|
4
|
-
"sourcesContent": ["import type * as client from '@botpress/client'\nimport type * as sdk from '@botpress/sdk'\nimport { TunnelRequest, TunnelResponse } from '@bpinternal/tunnel'\nimport axios, { AxiosRequestConfig, AxiosResponse } from 'axios'\nimport chalk from 'chalk'\nimport { isEqual } from 'lodash'\nimport * as pathlib from 'path'\nimport * as uuid from 'uuid'\nimport * as apiUtils from '../api'\nimport type commandDefinitions from '../command-definitions'\nimport * as errors from '../errors'\nimport * as tables from '../tables'\nimport * as utils from '../utils'\nimport { Worker } from '../worker'\nimport { BuildCommand } from './build-command'\nimport { ProjectCommand, ProjectDefinition } from './project-command'\n\nconst DEFAULT_BOT_PORT = 8075\nconst DEFAULT_INTEGRATION_PORT = 8076\nconst TUNNEL_HELLO_INTERVAL = 5000\nconst FILEWATCHER_DEBOUNCE_MS = 2000\n\nexport type DevCommandDefinition = typeof commandDefinitions.dev\nexport class DevCommand extends ProjectCommand<DevCommandDefinition> {\n private _initialDef: ProjectDefinition | undefined = undefined\n private _cacheDevRequestBody: apiUtils.UpdateBotRequestBody | apiUtils.UpdateIntegrationRequestBody | undefined\n private _buildContext: utils.esbuild.IncrementalBuildContext\n\n public constructor(...args: ConstructorParameters<typeof ProjectCommand<DevCommandDefinition>>) {\n super(...args)\n this._buildContext = new utils.esbuild.IncrementalBuildContext()\n }\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 const { projectType, resolveProjectDefinition } = this.readProjectDefinitionFromFS()\n if (projectType === 'interface') {\n throw new errors.BotpressCLIError('This feature is not available for interfaces.')\n }\n const projectDef = await resolveProjectDefinition()\n this._initialDef = projectDef\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.type === 'integration') {\n defaultPort = DEFAULT_INTEGRATION_PORT\n // TODO: store secrets in local cache to avoid prompting every time\n const secretEnvVariables = await this.promptSecrets(this._initialDef.definition, this.argv, { formatEnv: true })\n const nonNullSecretEnvVariables = utils.records.filterValues(secretEnvVariables, utils.guards.is.notNull)\n env = { ...env, ...nonNullSecretEnvVariables }\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 cachedTunnelId = await this.projectCache.get('tunnelId')\n\n let tunnelId: string\n if (this.argv.tunnelId) {\n tunnelId = this.argv.tunnelId\n } else if (cachedTunnelId) {\n tunnelId = cachedTunnelId\n } else {\n tunnelId = uuid.v4()\n }\n\n if (cachedTunnelId !== tunnelId) {\n await this.projectCache.set('tunnelId', tunnelId)\n }\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(() => {\n if (tunnel.closed) {\n return handleClose()\n }\n tunnel.hello()\n }, TUNNEL_HELLO_INTERVAL)\n const handleClose = (): void => clearInterval(timer)\n tunnel.events.on('close', handleClose)\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\n supervisor.events.on('manuallyClosed', () => {\n this.logger.debug('Tunnel manually closed')\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 debounceMs: FILEWATCHER_DEBOUNCE_MS,\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: apiUtils.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: apiUtils.ApiClient, tunnelUrl: string) => {\n const { projectType, resolveProjectDefinition } = this.readProjectDefinitionFromFS()\n\n if (projectType === 'interface') {\n throw new errors.BotpressCLIError('This feature is not available for interfaces.')\n }\n if (projectType === 'integration') {\n const projectDef = await resolveProjectDefinition()\n this._checkSecrets(projectDef.definition)\n return await this._deployDevIntegration(api, tunnelUrl, projectDef.definition)\n }\n if (projectType === 'bot') {\n const projectDef = await resolveProjectDefinition()\n return await this._deployDevBot(api, tunnelUrl, projectDef.definition)\n }\n throw new errors.UnsupportedProjectType()\n }\n\n private _checkSecrets(integrationDef: sdk.IntegrationDefinition) {\n if (this._initialDef?.type !== 'integration') {\n return\n }\n const initialSecrets = this._initialDef?.definition.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.outFileCJS\n const importPath = utils.path.toUnix(outfile)\n const code = `require('${importPath}').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(this._buildContext)\n }\n\n private async _deployDevIntegration(\n api: apiUtils.ApiClient,\n externalUrl: string,\n integrationDef: sdk.IntegrationDefinition\n ): Promise<void> {\n const devId = await this.projectCache.get('devId')\n\n let integration: client.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 createIntegrationBody = {\n ...(await this.prepareCreateIntegrationBody(integrationDef)),\n ...(await this.prepareIntegrationDependencies(integrationDef, api)),\n url: externalUrl,\n }\n\n if (integration) {\n const updateIntegrationBody = apiUtils.prepareUpdateIntegrationBody(\n { ...createIntegrationBody, 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({ ...createIntegrationBody, 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}\" at \"${externalUrl}\"`)\n line.commit()\n\n await this.projectCache.set('devId', integration.id)\n }\n\n private async _deployDevBot(api: apiUtils.ApiClient, externalUrl: string, botDef: sdk.BotDefinition): Promise<void> {\n const devId = await this.projectCache.get('devId')\n\n let bot: client.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.log('Dev Bot created')\n createLine.commit()\n await this.projectCache.set('devId', bot.id)\n }\n\n const updateBotBody = apiUtils.prepareUpdateBotBody(\n {\n ...(await apiUtils.prepareCreateBotBody(botDef)),\n ...(await this.prepareBotDependencies(botDef, api)),\n id: bot.id,\n url: externalUrl,\n },\n bot\n )\n\n if (!(await this._didDefinitionChange(updateBotBody))) {\n this.logger.log('Skipping deployment step. No changes found in bot.definition.ts')\n return\n }\n const updateLine = this.logger.line()\n updateLine.started('Deploying dev bot...')\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\n this.validateIntegrationRegistration(updatedBot, (failedIntegrations) => {\n throw new errors.BotpressCLIError(\n `Some integrations failed to register:\\n${Object.entries(failedIntegrations)\n .map(([key, int]) => `\u2022 ${key}: ${int.statusReason}`)\n .join('\\n')}`\n )\n })\n\n updateLine.success(`Dev Bot deployed with id \"${updatedBot.id}\" at \"${externalUrl}\"`)\n updateLine.commit()\n\n const tablesPublisher = new tables.TablesPublisher({ api, logger: this.logger, prompt: this.prompt })\n await tablesPublisher.deployTables({ botId: updatedBot.id, botDefinition: botDef })\n\n this.displayWebhookUrls(updatedBot)\n }\n\n private async _didDefinitionChange(body: apiUtils.UpdateBotRequestBody | apiUtils.UpdateIntegrationRequestBody) {\n const didChange = !isEqual(body, this._cacheDevRequestBody)\n this._cacheDevRequestBody = { ...body }\n return didChange\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] = String(res[key])\n }\n }\n return headers\n }\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,mBAAyD;AACzD,mBAAkB;AAClB,oBAAwB;AACxB,cAAyB;AACzB,WAAsB;AACtB,eAA0B;AAE1B,aAAwB;AACxB,aAAwB;AACxB,YAAuB;AACvB,oBAAuB;AACvB,2BAA6B;AAC7B,6BAAkD;AAElD,MAAM,mBAAmB;AACzB,MAAM,2BAA2B;AACjC,MAAM,wBAAwB;AAC9B,MAAM,0BAA0B;AAGzB,MAAM,mBAAmB,sCAAqC;AAAA,EAC3D,cAA6C;AAAA,EAC7C;AAAA,EACA;AAAA,EAED,eAAe,MAA0E;AAC9F,UAAM,GAAG,IAAI;AACb,SAAK,gBAAgB,IAAI,MAAM,QAAQ,
|
|
4
|
+
"sourcesContent": ["import type * as client from '@botpress/client'\nimport type * as sdk from '@botpress/sdk'\nimport { TunnelRequest, TunnelResponse } from '@bpinternal/tunnel'\nimport axios, { AxiosRequestConfig, AxiosResponse } from 'axios'\nimport chalk from 'chalk'\nimport { isEqual } from 'lodash'\nimport * as pathlib from 'path'\nimport * as uuid from 'uuid'\nimport * as apiUtils from '../api'\nimport type commandDefinitions from '../command-definitions'\nimport * as errors from '../errors'\nimport * as tables from '../tables'\nimport * as utils from '../utils'\nimport { Worker } from '../worker'\nimport { BuildCommand } from './build-command'\nimport { ProjectCommand, ProjectDefinition } from './project-command'\n\nconst DEFAULT_BOT_PORT = 8075\nconst DEFAULT_INTEGRATION_PORT = 8076\nconst TUNNEL_HELLO_INTERVAL = 5000\nconst FILEWATCHER_DEBOUNCE_MS = 500\n\nexport type DevCommandDefinition = typeof commandDefinitions.dev\nexport class DevCommand extends ProjectCommand<DevCommandDefinition> {\n private _initialDef: ProjectDefinition | undefined = undefined\n private _cacheDevRequestBody: apiUtils.UpdateBotRequestBody | apiUtils.UpdateIntegrationRequestBody | undefined\n private _buildContext: utils.esbuild.BuildCodeContext\n\n public constructor(...args: ConstructorParameters<typeof ProjectCommand<DevCommandDefinition>>) {\n super(...args)\n this._buildContext = new utils.esbuild.BuildCodeContext()\n }\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 const { projectType, resolveProjectDefinition } = this.readProjectDefinitionFromFS()\n if (projectType === 'interface') {\n throw new errors.BotpressCLIError('This feature is not available for interfaces.')\n }\n const projectDef = await resolveProjectDefinition()\n this._initialDef = projectDef\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.type === 'integration') {\n defaultPort = DEFAULT_INTEGRATION_PORT\n // TODO: store secrets in local cache to avoid prompting every time\n const secretEnvVariables = await this.promptSecrets(this._initialDef.definition, this.argv, { formatEnv: true })\n const nonNullSecretEnvVariables = utils.records.filterValues(secretEnvVariables, utils.guards.is.notNull)\n env = { ...env, ...nonNullSecretEnvVariables }\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 cachedTunnelId = await this.projectCache.get('tunnelId')\n\n let tunnelId: string\n if (this.argv.tunnelId) {\n tunnelId = this.argv.tunnelId\n } else if (cachedTunnelId) {\n tunnelId = cachedTunnelId\n } else {\n tunnelId = uuid.v4()\n }\n\n if (cachedTunnelId !== tunnelId) {\n await this.projectCache.set('tunnelId', tunnelId)\n }\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(() => {\n if (tunnel.closed) {\n return handleClose()\n }\n tunnel.hello()\n }, TUNNEL_HELLO_INTERVAL)\n const handleClose = (): void => clearInterval(timer)\n tunnel.events.on('close', handleClose)\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\n supervisor.events.on('manuallyClosed', () => {\n this.logger.debug('Tunnel manually closed')\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\n .filter((e) => !e.path.startsWith(this.projectPaths.abs.outDir))\n .filter((e) => pathlib.extname(e.path) === '.ts')\n\n const distEvents = events.filter((e) => e.path.startsWith(this.projectPaths.abs.distDir))\n\n if (typescriptEvents.length > 0) {\n this.logger.log('Changes detected, rebuilding')\n await this._restart(api, worker, httpTunnelUrl)\n } else if (distEvents.length > 0) {\n this.logger.log('Changes detected in output directory, reloading worker')\n await worker.reload()\n }\n },\n {\n debounceMs: FILEWATCHER_DEBOUNCE_MS,\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: apiUtils.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: apiUtils.ApiClient, tunnelUrl: string) => {\n const { projectType, resolveProjectDefinition } = this.readProjectDefinitionFromFS()\n\n if (projectType === 'interface') {\n throw new errors.BotpressCLIError('This feature is not available for interfaces.')\n }\n if (projectType === 'integration') {\n const projectDef = await resolveProjectDefinition()\n this._checkSecrets(projectDef.definition)\n return await this._deployDevIntegration(api, tunnelUrl, projectDef.definition)\n }\n if (projectType === 'bot') {\n const projectDef = await resolveProjectDefinition()\n return await this._deployDevBot(api, tunnelUrl, projectDef.definition)\n }\n throw new errors.UnsupportedProjectType()\n }\n\n private _checkSecrets(integrationDef: sdk.IntegrationDefinition) {\n if (this._initialDef?.type !== 'integration') {\n return\n }\n const initialSecrets = this._initialDef?.definition.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.outFileCJS\n const importPath = utils.path.toUnix(outfile)\n const code = `require('${importPath}').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)\n .setProjectContext(this.projectContext)\n .run(this._buildContext)\n }\n\n private async _deployDevIntegration(\n api: apiUtils.ApiClient,\n externalUrl: string,\n integrationDef: sdk.IntegrationDefinition\n ): Promise<void> {\n const devId = await this.projectCache.get('devId')\n\n let integration: client.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 createIntegrationBody = {\n ...(await this.prepareCreateIntegrationBody(integrationDef)),\n ...(await this.prepareIntegrationDependencies(integrationDef, api)),\n url: externalUrl,\n }\n\n if (integration) {\n const updateIntegrationBody = apiUtils.prepareUpdateIntegrationBody(\n { ...createIntegrationBody, 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({ ...createIntegrationBody, 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}\" at \"${externalUrl}\"`)\n line.commit()\n\n await this.projectCache.set('devId', integration.id)\n }\n\n private async _deployDevBot(api: apiUtils.ApiClient, externalUrl: string, botDef: sdk.BotDefinition): Promise<void> {\n const devId = await this.projectCache.get('devId')\n\n let bot: client.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.log('Dev Bot created')\n createLine.commit()\n await this.projectCache.set('devId', bot.id)\n }\n\n const updateBotBody = apiUtils.prepareUpdateBotBody(\n {\n ...(await apiUtils.prepareCreateBotBody(botDef)),\n ...(await this.prepareBotDependencies(botDef, api)),\n id: bot.id,\n url: externalUrl,\n },\n bot\n )\n\n if (!(await this._didDefinitionChange(updateBotBody))) {\n this.logger.log('Skipping deployment step. No changes found in bot.definition.ts')\n return\n }\n const updateLine = this.logger.line()\n updateLine.started('Deploying dev bot...')\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\n this.validateIntegrationRegistration(updatedBot, (failedIntegrations) => {\n throw new errors.BotpressCLIError(\n `Some integrations failed to register:\\n${Object.entries(failedIntegrations)\n .map(([key, int]) => `\u2022 ${key}: ${int.statusReason}`)\n .join('\\n')}`\n )\n })\n\n updateLine.success(`Dev Bot deployed with id \"${updatedBot.id}\" at \"${externalUrl}\"`)\n updateLine.commit()\n\n const tablesPublisher = new tables.TablesPublisher({ api, logger: this.logger, prompt: this.prompt })\n await tablesPublisher.deployTables({ botId: updatedBot.id, botDefinition: botDef })\n\n this.displayWebhookUrls(updatedBot)\n }\n\n private async _didDefinitionChange(body: apiUtils.UpdateBotRequestBody | apiUtils.UpdateIntegrationRequestBody) {\n const didChange = !isEqual(body, this._cacheDevRequestBody)\n this._cacheDevRequestBody = { ...body }\n return didChange\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] = String(res[key])\n }\n }\n return headers\n }\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,mBAAyD;AACzD,mBAAkB;AAClB,oBAAwB;AACxB,cAAyB;AACzB,WAAsB;AACtB,eAA0B;AAE1B,aAAwB;AACxB,aAAwB;AACxB,YAAuB;AACvB,oBAAuB;AACvB,2BAA6B;A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IAAI,KAAK;AAAA,IAC3C;AACA,WAAO,GAAG,OAAO,GAAG,IAAI,IAAI;AAAA,EAC9B;AAAA,EAEQ,cAAc,CAAC,QAA6D;AAClF,UAAM,UAAqC,CAAC;AAC5C,eAAW,OAAO,KAAK;AACrB,UAAI,OAAO,IAAI,GAAG,MAAM,YAAY,OAAO,IAAI,GAAG,MAAM,UAAU;AAChE,gBAAQ,GAAG,IAAI,OAAO,IAAI,GAAG,CAAC;AAAA,MAChC;AAAA,IACF;AACA,WAAO;AAAA,EACT;AACF;",
|
|
6
6
|
"names": ["chalk", "axios"]
|
|
7
7
|
}
|
|
@@ -65,7 +65,15 @@ type UpdatedBot = client.Bot;
|
|
|
65
65
|
declare class ProjectPaths extends utils.path.PathStore<keyof AllProjectPaths> {
|
|
66
66
|
constructor(argv: CommandArgv<ProjectCommandDefinition>);
|
|
67
67
|
}
|
|
68
|
+
export declare class ProjectDefinitionContext {
|
|
69
|
+
private _codeCache;
|
|
70
|
+
private _buildContext;
|
|
71
|
+
getOrResolveDefinition<T extends object>(code: string): T;
|
|
72
|
+
rebuildEntrypoint(...args: Parameters<utils.esbuild.BuildEntrypointContext['rebuild']>): Promise<utils.esbuild.BuildResult<utils.esbuild.BuildOptions>>;
|
|
73
|
+
}
|
|
68
74
|
export declare abstract class ProjectCommand<C extends ProjectCommandDefinition> extends GlobalCommand<C> {
|
|
75
|
+
protected projectContext: ProjectDefinitionContext;
|
|
76
|
+
setProjectContext(projectContext: ProjectDefinitionContext): this;
|
|
69
77
|
protected bootstrap(): Promise<void>;
|
|
70
78
|
protected get projectPaths(): ProjectPaths;
|
|
71
79
|
protected get projectCache(): utils.cache.FSKeyValueCache<ProjectCache>;
|
|
@@ -28,7 +28,8 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
28
28
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
29
|
var project_command_exports = {};
|
|
30
30
|
__export(project_command_exports, {
|
|
31
|
-
ProjectCommand: () => ProjectCommand
|
|
31
|
+
ProjectCommand: () => ProjectCommand,
|
|
32
|
+
ProjectDefinitionContext: () => ProjectDefinitionContext
|
|
32
33
|
});
|
|
33
34
|
module.exports = __toCommonJS(project_command_exports);
|
|
34
35
|
var import_chalk = __toESM(require("chalk"));
|
|
@@ -51,7 +52,28 @@ class ProjectPaths extends utils.path.PathStore {
|
|
|
51
52
|
});
|
|
52
53
|
}
|
|
53
54
|
}
|
|
55
|
+
class ProjectDefinitionContext {
|
|
56
|
+
_codeCache = /* @__PURE__ */ new Map();
|
|
57
|
+
_buildContext = new utils.esbuild.BuildEntrypointContext();
|
|
58
|
+
getOrResolveDefinition(code) {
|
|
59
|
+
const definition = this._codeCache.get(code);
|
|
60
|
+
if (definition) {
|
|
61
|
+
return definition;
|
|
62
|
+
}
|
|
63
|
+
const result = utils.require.requireJsCode(code);
|
|
64
|
+
this._codeCache.set(code, result.default);
|
|
65
|
+
return result.default;
|
|
66
|
+
}
|
|
67
|
+
rebuildEntrypoint(...args) {
|
|
68
|
+
return this._buildContext.rebuild(...args);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
54
71
|
class ProjectCommand extends import_global_command.GlobalCommand {
|
|
72
|
+
projectContext = new ProjectDefinitionContext();
|
|
73
|
+
setProjectContext(projectContext) {
|
|
74
|
+
this.projectContext = projectContext;
|
|
75
|
+
return this;
|
|
76
|
+
}
|
|
55
77
|
async bootstrap() {
|
|
56
78
|
await super.bootstrap();
|
|
57
79
|
await this._notifyUpdateSdk();
|
|
@@ -129,15 +151,15 @@ class ProjectCommand extends import_global_command.GlobalCommand {
|
|
|
129
151
|
throw new errors.BotpressCLIError("Could not read integration definition");
|
|
130
152
|
}
|
|
131
153
|
const bpLintDisabled = await this._isBpLintDisabled(abs.integrationDefinition);
|
|
132
|
-
const { outputFiles } = await
|
|
154
|
+
const { outputFiles } = await this.projectContext.rebuildEntrypoint({
|
|
133
155
|
absWorkingDir: abs.workDir,
|
|
134
156
|
entrypoint: rel.integrationDefinition
|
|
135
157
|
});
|
|
136
|
-
const artifact = outputFiles[0];
|
|
158
|
+
const artifact = outputFiles?.[0];
|
|
137
159
|
if (!artifact) {
|
|
138
160
|
throw new errors.BotpressCLIError("Could not read integration definition");
|
|
139
161
|
}
|
|
140
|
-
const
|
|
162
|
+
const definition = this.projectContext.getOrResolveDefinition(artifact.text);
|
|
141
163
|
(0, import_sdk.validateIntegrationDefinition)(definition);
|
|
142
164
|
return { definition, bpLintDisabled };
|
|
143
165
|
}
|
|
@@ -148,15 +170,15 @@ class ProjectCommand extends import_global_command.GlobalCommand {
|
|
|
148
170
|
throw new errors.BotpressCLIError("Could not read interface definition");
|
|
149
171
|
}
|
|
150
172
|
const bpLintDisabled = await this._isBpLintDisabled(abs.interfaceDefinition);
|
|
151
|
-
const { outputFiles } = await
|
|
173
|
+
const { outputFiles } = await this.projectContext.rebuildEntrypoint({
|
|
152
174
|
absWorkingDir: abs.workDir,
|
|
153
175
|
entrypoint: rel.interfaceDefinition
|
|
154
176
|
});
|
|
155
|
-
const artifact = outputFiles[0];
|
|
177
|
+
const artifact = outputFiles?.[0];
|
|
156
178
|
if (!artifact) {
|
|
157
179
|
throw new errors.BotpressCLIError("Could not read interface definition");
|
|
158
180
|
}
|
|
159
|
-
const
|
|
181
|
+
const definition = this.projectContext.getOrResolveDefinition(artifact.text);
|
|
160
182
|
return { definition, bpLintDisabled };
|
|
161
183
|
}
|
|
162
184
|
async _readBotDefinitionFromFS(projectPaths) {
|
|
@@ -166,15 +188,15 @@ class ProjectCommand extends import_global_command.GlobalCommand {
|
|
|
166
188
|
throw new errors.BotpressCLIError("Could not read bot definition");
|
|
167
189
|
}
|
|
168
190
|
const bpLintDisabled = await this._isBpLintDisabled(abs.botDefinition);
|
|
169
|
-
const { outputFiles } = await
|
|
191
|
+
const { outputFiles } = await this.projectContext.rebuildEntrypoint({
|
|
170
192
|
absWorkingDir: abs.workDir,
|
|
171
193
|
entrypoint: rel.botDefinition
|
|
172
194
|
});
|
|
173
|
-
const artifact = outputFiles[0];
|
|
195
|
+
const artifact = outputFiles?.[0];
|
|
174
196
|
if (!artifact) {
|
|
175
197
|
throw new errors.BotpressCLIError("Could not read bot definition");
|
|
176
198
|
}
|
|
177
|
-
const
|
|
199
|
+
const definition = this.projectContext.getOrResolveDefinition(artifact.text);
|
|
178
200
|
(0, import_sdk.validateBotDefinition)(definition);
|
|
179
201
|
return { definition, bpLintDisabled };
|
|
180
202
|
}
|
|
@@ -185,15 +207,15 @@ class ProjectCommand extends import_global_command.GlobalCommand {
|
|
|
185
207
|
throw new errors.BotpressCLIError("Could not read plugin definition");
|
|
186
208
|
}
|
|
187
209
|
const bpLintDisabled = await this._isBpLintDisabled(abs.pluginDefinition);
|
|
188
|
-
const { outputFiles } = await
|
|
210
|
+
const { outputFiles } = await this.projectContext.rebuildEntrypoint({
|
|
189
211
|
absWorkingDir: abs.workDir,
|
|
190
212
|
entrypoint: rel.pluginDefinition
|
|
191
213
|
});
|
|
192
|
-
const artifact = outputFiles[0];
|
|
214
|
+
const artifact = outputFiles?.[0];
|
|
193
215
|
if (!artifact) {
|
|
194
216
|
throw new errors.BotpressCLIError("Could not read plugin definition");
|
|
195
217
|
}
|
|
196
|
-
const
|
|
218
|
+
const definition = this.projectContext.getOrResolveDefinition(artifact.text);
|
|
197
219
|
return { definition, bpLintDisabled };
|
|
198
220
|
}
|
|
199
221
|
async _isBpLintDisabled(definitionPath) {
|
|
@@ -473,6 +495,7 @@ class ProjectCommand extends import_global_command.GlobalCommand {
|
|
|
473
495
|
}
|
|
474
496
|
// Annotate the CommonJS export names for ESM import in node:
|
|
475
497
|
0 && (module.exports = {
|
|
476
|
-
ProjectCommand
|
|
498
|
+
ProjectCommand,
|
|
499
|
+
ProjectDefinitionContext
|
|
477
500
|
});
|
|
478
501
|
//# sourceMappingURL=project-command.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/command-implementations/project-command.ts"],
|
|
4
|
-
"sourcesContent": ["import type * as client from '@botpress/client'\nimport type * as sdk from '@botpress/sdk'\nimport type { YargsConfig } from '@bpinternal/yargs-extra'\nimport chalk from 'chalk'\nimport fs from 'fs'\nimport _ from 'lodash'\nimport semver from 'semver'\nimport * as apiUtils from '../api'\nimport * as codegen from '../code-generation'\nimport * as config from '../config'\nimport * as consts from '../consts'\nimport * as errors from '../errors'\nimport { validateIntegrationDefinition, validateBotDefinition } from '../sdk'\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; tunnelId: string }\n\ntype ConfigurableProjectPaths = { workDir: string }\ntype ConstantProjectPaths = typeof consts.fromWorkDir\ntype AllProjectPaths = ConfigurableProjectPaths & ConstantProjectPaths\n\ntype LintIgnoredConfig = { bpLintDisabled?: boolean }\n\nexport type ProjectType = ProjectDefinition['type']\nexport type ProjectDefinition = LintIgnoredConfig &\n (\n | { type: 'integration'; definition: sdk.IntegrationDefinition }\n | { type: 'interface'; definition: sdk.InterfaceDefinition }\n | { type: 'bot'; definition: sdk.BotDefinition }\n | { type: 'plugin'; definition: sdk.PluginDefinition }\n )\n\ntype ProjectDefinitionResolver<T> = () => Promise<LintIgnoredConfig & T>\n\nexport type ProjectDefinitionLazy =\n | {\n projectType: 'integration'\n resolveProjectDefinition: ProjectDefinitionResolver<{\n type: 'integration'\n definition: sdk.IntegrationDefinition\n }>\n }\n | {\n projectType: 'bot'\n resolveProjectDefinition: ProjectDefinitionResolver<{ type: 'bot'; definition: sdk.BotDefinition }>\n }\n | {\n projectType: 'interface'\n resolveProjectDefinition: ProjectDefinitionResolver<{ type: 'interface'; definition: sdk.InterfaceDefinition }>\n }\n | {\n projectType: 'plugin'\n resolveProjectDefinition: ProjectDefinitionResolver<{ type: 'plugin'; definition: sdk.PluginDefinition }>\n }\n\ntype UpdatedBot = client.Bot\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 super({\n workDir: absWorkDir,\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 override async bootstrap() {\n await super.bootstrap()\n await this._notifyUpdateSdk()\n }\n\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 private _readProjectType(projectPaths: ProjectPaths): ProjectType {\n const abs = projectPaths.abs\n if (fs.existsSync(abs.integrationDefinition)) {\n return 'integration'\n }\n if (fs.existsSync(abs.interfaceDefinition)) {\n return 'interface'\n }\n if (fs.existsSync(abs.botDefinition)) {\n return 'bot'\n }\n if (fs.existsSync(abs.pluginDefinition)) {\n return 'plugin'\n }\n throw new errors.UnsupportedProjectType()\n }\n\n protected readProjectDefinitionFromFS(): ProjectDefinitionLazy {\n try {\n const type = this._readProjectType(this.projectPaths)\n if (type === 'integration') {\n return {\n projectType: 'integration',\n resolveProjectDefinition: async () => ({\n type: 'integration',\n ...(await this._readIntegrationDefinitionFromFS(this.projectPaths)),\n }),\n }\n }\n if (type === 'plugin') {\n return {\n projectType: 'plugin',\n resolveProjectDefinition: async () => ({\n type: 'plugin',\n ...(await this._readPluginDefinitionFromFS(this.projectPaths)),\n }),\n }\n }\n if (type === 'interface') {\n return {\n projectType: 'interface',\n resolveProjectDefinition: async () => ({\n type: 'interface',\n ...(await this._readInterfaceDefinitionFromFS(this.projectPaths)),\n }),\n }\n }\n if (type === 'bot') {\n return {\n projectType: 'bot',\n resolveProjectDefinition: async () => ({\n type: 'bot',\n ...(await this._readBotDefinitionFromFS(this.projectPaths)),\n }),\n }\n }\n } catch (thrown: unknown) {\n throw errors.BotpressCLIError.wrap(thrown, 'Error while reading project definition')\n }\n throw new errors.ProjectDefinitionNotFoundError(this.projectPaths.abs.workDir)\n }\n\n private async _readIntegrationDefinitionFromFS(\n projectPaths: utils.path.PathStore<'workDir' | 'integrationDefinition'>\n ): Promise<{ definition: sdk.IntegrationDefinition } & LintIgnoredConfig> {\n const abs = projectPaths.abs\n const rel = projectPaths.rel('workDir')\n\n if (!fs.existsSync(abs.integrationDefinition)) {\n throw new errors.BotpressCLIError('Could not read integration definition')\n }\n\n const bpLintDisabled = await this._isBpLintDisabled(abs.integrationDefinition)\n\n const { outputFiles } = await utils.esbuild.buildEntrypoint({\n absWorkingDir: abs.workDir,\n entrypoint: rel.integrationDefinition,\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: sdk.IntegrationDefinition }>(artifact.text)\n validateIntegrationDefinition(definition)\n return { definition, bpLintDisabled }\n }\n\n private async _readInterfaceDefinitionFromFS(\n projectPaths: utils.path.PathStore<'workDir' | 'interfaceDefinition'>\n ): Promise<{ definition: sdk.InterfaceDefinition } & LintIgnoredConfig> {\n const abs = projectPaths.abs\n const rel = projectPaths.rel('workDir')\n\n if (!fs.existsSync(abs.interfaceDefinition)) {\n throw new errors.BotpressCLIError('Could not read interface definition')\n }\n\n const bpLintDisabled = await this._isBpLintDisabled(abs.interfaceDefinition)\n\n const { outputFiles } = await utils.esbuild.buildEntrypoint({\n absWorkingDir: abs.workDir,\n entrypoint: rel.interfaceDefinition,\n })\n\n const artifact = outputFiles[0]\n if (!artifact) {\n throw new errors.BotpressCLIError('Could not read interface definition')\n }\n\n const { default: definition } = utils.require.requireJsCode<{ default: sdk.InterfaceDefinition }>(artifact.text)\n\n return { definition, bpLintDisabled }\n }\n\n private async _readBotDefinitionFromFS(\n projectPaths: utils.path.PathStore<'workDir' | 'botDefinition'>\n ): Promise<{ definition: sdk.BotDefinition } & LintIgnoredConfig> {\n const abs = projectPaths.abs\n const rel = projectPaths.rel('workDir')\n\n if (!fs.existsSync(abs.botDefinition)) {\n throw new errors.BotpressCLIError('Could not read bot definition')\n }\n\n const bpLintDisabled = await this._isBpLintDisabled(abs.botDefinition)\n\n const { outputFiles } = await utils.esbuild.buildEntrypoint({\n absWorkingDir: abs.workDir,\n entrypoint: rel.botDefinition,\n })\n\n const artifact = outputFiles[0]\n if (!artifact) {\n throw new errors.BotpressCLIError('Could not read bot definition')\n }\n\n const { default: definition } = utils.require.requireJsCode<{ default: sdk.BotDefinition }>(artifact.text)\n validateBotDefinition(definition)\n return { definition, bpLintDisabled }\n }\n\n private async _readPluginDefinitionFromFS(\n projectPaths: utils.path.PathStore<'workDir' | 'pluginDefinition'>\n ): Promise<{ definition: sdk.PluginDefinition } & LintIgnoredConfig> {\n const abs = projectPaths.abs\n const rel = projectPaths.rel('workDir')\n\n if (!fs.existsSync(abs.pluginDefinition)) {\n throw new errors.BotpressCLIError('Could not read plugin definition')\n }\n\n const bpLintDisabled = await this._isBpLintDisabled(abs.pluginDefinition)\n\n const { outputFiles } = await utils.esbuild.buildEntrypoint({\n absWorkingDir: abs.workDir,\n entrypoint: rel.pluginDefinition,\n })\n\n const artifact = outputFiles[0]\n if (!artifact) {\n throw new errors.BotpressCLIError('Could not read plugin definition')\n }\n\n const { default: definition } = utils.require.requireJsCode<{ default: sdk.PluginDefinition }>(artifact.text)\n // TODO: validate plugin definition\n return { definition, bpLintDisabled }\n }\n\n private async _isBpLintDisabled(definitionPath: string): Promise<boolean> {\n const tsContent = await fs.promises.readFile(definitionPath, 'utf-8')\n const regex = /\\/\\* bplint-disable \\*\\//\n return regex.test(tsContent)\n }\n\n protected displayWebhookUrls(bot: client.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: sdk.IntegrationDefinition,\n argv: YargsConfig<typeof config.schemas.secrets>,\n opts: { formatEnv?: boolean; knownSecrets?: string[] } = {}\n ): Promise<Record<string, string | null>> {\n const formatEnv = opts.formatEnv ?? false\n const knownSecrets = opts.knownSecrets ?? []\n\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 | null> = {}\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 alreadyKnown = knownSecrets.includes(secretName)\n let mode: string\n if (alreadyKnown) {\n mode = 'already set'\n } else if (optional) {\n mode = 'optional'\n } else {\n mode = 'required'\n }\n\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 (alreadyKnown) {\n this.logger.log(`Secret \"${secretName}\" is unchanged`)\n } else if (optional) {\n this.logger.warn(`Secret \"${secretName}\" is unassigned`)\n } else {\n throw new errors.BotpressCLIError(`Secret \"${secretName}\" is required`)\n }\n }\n\n for (const secretName of knownSecrets) {\n const isDefined = secretName in secretDefinitions\n if (isDefined) {\n continue\n }\n const prompted = await this.prompt.confirm(`Secret \"${secretName}\" was removed. Do you wish to delete it?`)\n if (prompted) {\n this.logger.log(`Deleting secret \"${secretName}\"`, { prefix: { symbol: '\u00D7', fg: 'red' } })\n values[secretName] = null\n }\n }\n\n if (!formatEnv) {\n return values\n }\n\n const envVariables = _.mapKeys(values, (_v, k) => codegen.secretEnvVariableName(k))\n return envVariables\n }\n\n protected async prepareCreateIntegrationBody(\n integrationDef: sdk.IntegrationDefinition\n ): Promise<apiUtils.CreateIntegrationRequestBody> {\n const partialBody = await apiUtils.prepareCreateIntegrationBody(integrationDef)\n\n let code: string | undefined = undefined\n if (fs.existsSync(this.projectPaths.abs.outFileCJS)) {\n code = await this.readProjectFile(this.projectPaths.abs.outFileCJS)\n }\n\n const icon = await this.readProjectFile(integrationDef.icon, 'base64')\n const readme = await this.readProjectFile(integrationDef.readme, 'base64')\n const extractScript = await this.readProjectFile(integrationDef.identifier?.extractScript)\n const fallbackHandlerScript = await this.readProjectFile(integrationDef.identifier?.fallbackHandlerScript)\n return {\n ...partialBody,\n code,\n icon,\n readme,\n identifier: {\n extractScript,\n fallbackHandlerScript,\n },\n configuration: integrationDef.configuration\n ? {\n schema: await utils.schema.mapZodToJsonSchema(integrationDef.configuration),\n identifier: {\n required: integrationDef.configuration.identifier?.required,\n linkTemplateScript: await this.readProjectFile(\n integrationDef.configuration.identifier?.linkTemplateScript\n ),\n },\n }\n : undefined,\n configurations: integrationDef.configurations\n ? await utils.records.mapValuesAsync(integrationDef.configurations, async (configuration) => ({\n title: configuration.title,\n description: configuration.description,\n schema: await utils.schema.mapZodToJsonSchema(configuration),\n identifier: {\n required: configuration.identifier?.required,\n linkTemplateScript: await this.readProjectFile(configuration.identifier?.linkTemplateScript),\n },\n }))\n : undefined,\n }\n }\n\n protected async prepareBotDependencies(\n botDef: sdk.BotDefinition,\n api: apiUtils.ApiClient\n ): Promise<Partial<apiUtils.UpdateBotRequestBody>> {\n const integrations = await this._fetchDependencies(botDef.integrations ?? {}, ({ name, version }) =>\n api.getPublicOrPrivateIntegration({ type: 'name', name, version })\n )\n\n const plugins = await this._fetchDependencies(\n botDef.plugins ?? {},\n async ({ name, version }) => await api.getPublicOrPrivatePlugin({ type: 'name', name, version })\n )\n\n const pluginsWithBackingIntegrations = await utils.records.mapValuesAsync(plugins, async (plugin) => ({\n ...plugin,\n interfaces: await this._fetchDependencies(\n plugin.interfaces ?? {},\n async (interfaceExtension) => await api.getPublicOrPrivateIntegration({ ...interfaceExtension, type: 'name' })\n ),\n }))\n\n return {\n integrations: _(integrations)\n .keyBy((i) => i.id)\n .mapValues(\n ({ enabled, configurationType, configuration, disabledChannels }) =>\n ({\n enabled,\n configurationType,\n configuration,\n disabledChannels,\n }) satisfies NonNullable<apiUtils.UpdateBotRequestBody['integrations']>[string]\n )\n .value(),\n plugins: utils.records.mapValues(pluginsWithBackingIntegrations, (plugin) => ({\n ...plugin,\n interfaces: utils.records.mapValues(plugin.interfaces ?? {}, (iface) => ({\n ...iface,\n integrationId: iface.id,\n })),\n })),\n }\n }\n\n protected async prepareIntegrationDependencies(\n integrationDef: sdk.IntegrationDefinition,\n api: apiUtils.ApiClient\n ): Promise<Partial<apiUtils.CreateIntegrationRequestBody>> {\n const interfaces = await this._fetchDependencies(integrationDef.interfaces ?? {}, ({ name, version }) =>\n api.getPublicInterface({ type: 'name', name, version })\n )\n return { interfaces }\n }\n\n protected async preparePluginDependencies(\n pluginDef: sdk.PluginDefinition,\n api: apiUtils.ApiClient\n ): Promise<Partial<apiUtils.CreatePluginRequestBody>> {\n const integrations = await this._fetchDependencies(pluginDef.integrations ?? {}, ({ name, version }) =>\n api.getPublicOrPrivateIntegration({ type: 'name', name, version })\n )\n const interfaces = await this._fetchDependencies(pluginDef.interfaces ?? {}, ({ name, version }) =>\n api.getPublicInterface({ type: 'name', name, version })\n )\n return {\n dependencies: {\n integrations,\n interfaces,\n },\n }\n }\n\n private _fetchDependencies = async <T extends { id?: string; name: string; version: string }>(\n deps: Record<string, T>,\n fetcher: (dep: T) => Promise<{ id: string }>\n ): Promise<Record<string, T & { id: string }>> => {\n const isRemote = (dep: T): dep is T & { id: string } => dep.id !== undefined\n return utils.records.mapValuesAsync(deps, async (dep): Promise<T & { id: string }> => {\n if (isRemote(dep)) {\n return dep\n }\n const { id } = await fetcher(dep)\n return { ...dep, id }\n })\n }\n\n protected readProjectFile = async (\n filePath: string | undefined,\n encoding: BufferEncoding = 'utf-8'\n ): Promise<string | undefined> => {\n if (!filePath) {\n return undefined\n }\n const absoluteFilePath = utils.path.absoluteFrom(this.projectPaths.abs.workDir, filePath)\n return fs.promises.readFile(absoluteFilePath, encoding).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not read file \"${absoluteFilePath}\"`)\n })\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] = utils.string.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 _notifyUpdateSdk = async (): Promise<void> => {\n try {\n this.logger.debug('Checking if sdk is up to date')\n\n const { workDir } = this.projectPaths.abs\n const projectPkgJson = await utils.pkgJson.readPackageJson(workDir)\n if (!projectPkgJson) {\n this.logger.debug(`Could not find package.json at \"${workDir}\"`)\n return\n }\n\n const sdkPackageName = '@botpress/sdk'\n const actualSdkVersion = utils.pkgJson.findDependency(projectPkgJson, sdkPackageName)\n if (!actualSdkVersion) {\n this.logger.debug(`Could not find dependency \"${sdkPackageName}\" in project package.json`)\n return\n }\n\n if (actualSdkVersion.startsWith('workspace:')) {\n return\n }\n\n const actualCleanedSdkVersion = semver.valid(semver.coerce(actualSdkVersion))\n if (!actualCleanedSdkVersion) {\n this.logger.debug(`Invalid sdk version \"${actualSdkVersion}\" in project package.json`)\n return\n }\n\n const cliPkgJson = await this.readPkgJson()\n const expectedSdkVersion = utils.pkgJson.findDependency(cliPkgJson, sdkPackageName)\n if (!expectedSdkVersion) {\n this.logger.debug(`Could not find dependency \"${sdkPackageName}\" in cli package.json`)\n return\n }\n\n const expectedCleanedSdkVersion = semver.valid(semver.coerce(expectedSdkVersion))\n if (!expectedCleanedSdkVersion) {\n this.logger.debug(`Invalid sdk version \"${expectedSdkVersion}\" in cli package.json`)\n return\n }\n\n if (semver.eq(actualCleanedSdkVersion, expectedCleanedSdkVersion)) {\n return\n }\n\n const diff = semver.diff(actualCleanedSdkVersion, expectedCleanedSdkVersion)\n if (!diff) {\n this.logger.debug(`Could not compare versions \"${actualCleanedSdkVersion}\" and \"${expectedCleanedSdkVersion}\"`)\n return\n }\n\n const errorMsg = `Project SDK version is \"${actualCleanedSdkVersion}\", but expected \"${expectedCleanedSdkVersion}\"`\n if (utils.semver.releases.lt(diff, 'minor')) {\n this.logger.debug(`${errorMsg}. This may cause compatibility issues.`)\n return\n }\n\n this.logger.warn(chalk.bold(`${errorMsg}. This will cause compatibility issues.`))\n } catch (thrown) {\n const err = errors.BotpressCLIError.map(thrown)\n this.logger.debug(`Failed to check if sdk is up to date: ${err.message}`)\n }\n }\n protected validateIntegrationRegistration(\n updatedBot: UpdatedBot,\n onFailCallback: (failedIntegrations: UpdatedBot['integrations']) => void\n ) {\n let failedIntegrations: UpdatedBot['integrations'] = {}\n for (const [integrationName, integration] of Object.entries(updatedBot.integrations)) {\n if (integration.status === 'registration_failed') {\n failedIntegrations = { ...failedIntegrations, [integrationName]: integration }\n }\n }\n if (Object.keys(failedIntegrations).length > 0) {\n onFailCallback(failedIntegrations)\n }\n }\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,mBAAkB;AAClB,gBAAe;AACf,oBAAc;AACd,oBAAmB;AACnB,eAA0B;AAC1B,cAAyB;AAEzB,aAAwB;AACxB,aAAwB;AACxB,iBAAqE;AAErE,YAAuB;AACvB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AM,MAAM,OAAO,iBAAiB,IAAI,MAAM;AAC9C,WAAK,OAAO,MAAM,yCAAyC,IAAI,OAAO,EAAE;AAAA,IAC1E;AAAA,EACF;AAAA,EACU,gCACR,YACA,gBACA;AACA,QAAI,qBAAiD,CAAC;AACtD,eAAW,CAAC,iBAAiB,WAAW,KAAK,OAAO,QAAQ,WAAW,YAAY,GAAG;AACpF,UAAI,YAAY,WAAW,uBAAuB;AAChD,6BAAqB,EAAE,GAAG,oBAAoB,CAAC,eAAe,GAAG,YAAY;AAAA,MAC/E;AAAA,IACF;AACA,QAAI,OAAO,KAAK,kBAAkB,EAAE,SAAS,GAAG;AAC9C,qBAAe,kBAAkB;AAAA,IACnC;AAAA,EACF;AACF;",
|
|
4
|
+
"sourcesContent": ["import type * as client from '@botpress/client'\nimport type * as sdk from '@botpress/sdk'\nimport type { YargsConfig } from '@bpinternal/yargs-extra'\nimport chalk from 'chalk'\nimport fs from 'fs'\nimport _ from 'lodash'\nimport semver from 'semver'\nimport * as apiUtils from '../api'\nimport * as codegen from '../code-generation'\nimport * as config from '../config'\nimport * as consts from '../consts'\nimport * as errors from '../errors'\nimport { validateIntegrationDefinition, validateBotDefinition } from '../sdk'\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; tunnelId: string }\n\ntype ConfigurableProjectPaths = { workDir: string }\ntype ConstantProjectPaths = typeof consts.fromWorkDir\ntype AllProjectPaths = ConfigurableProjectPaths & ConstantProjectPaths\n\ntype LintIgnoredConfig = { bpLintDisabled?: boolean }\n\nexport type ProjectType = ProjectDefinition['type']\nexport type ProjectDefinition = LintIgnoredConfig &\n (\n | { type: 'integration'; definition: sdk.IntegrationDefinition }\n | { type: 'interface'; definition: sdk.InterfaceDefinition }\n | { type: 'bot'; definition: sdk.BotDefinition }\n | { type: 'plugin'; definition: sdk.PluginDefinition }\n )\n\ntype ProjectDefinitionResolver<T> = () => Promise<LintIgnoredConfig & T>\n\nexport type ProjectDefinitionLazy =\n | {\n projectType: 'integration'\n resolveProjectDefinition: ProjectDefinitionResolver<{\n type: 'integration'\n definition: sdk.IntegrationDefinition\n }>\n }\n | {\n projectType: 'bot'\n resolveProjectDefinition: ProjectDefinitionResolver<{ type: 'bot'; definition: sdk.BotDefinition }>\n }\n | {\n projectType: 'interface'\n resolveProjectDefinition: ProjectDefinitionResolver<{ type: 'interface'; definition: sdk.InterfaceDefinition }>\n }\n | {\n projectType: 'plugin'\n resolveProjectDefinition: ProjectDefinitionResolver<{ type: 'plugin'; definition: sdk.PluginDefinition }>\n }\n\ntype UpdatedBot = client.Bot\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 super({\n workDir: absWorkDir,\n ..._.mapValues(consts.fromWorkDir, (p) => utils.path.absoluteFrom(absWorkDir, p)),\n })\n }\n}\n\nexport class ProjectDefinitionContext {\n private _codeCache: Map<string, object> = new Map()\n private _buildContext: utils.esbuild.BuildEntrypointContext = new utils.esbuild.BuildEntrypointContext()\n\n public getOrResolveDefinition<T extends object>(code: string): T {\n const definition = this._codeCache.get(code)\n if (definition) {\n return definition as T\n }\n const result = utils.require.requireJsCode<{ default: object }>(code)\n this._codeCache.set(code, result.default)\n return result.default as T\n }\n\n public rebuildEntrypoint(...args: Parameters<utils.esbuild.BuildEntrypointContext['rebuild']>) {\n return this._buildContext.rebuild(...args)\n }\n}\n\nexport abstract class ProjectCommand<C extends ProjectCommandDefinition> extends GlobalCommand<C> {\n protected projectContext: ProjectDefinitionContext = new ProjectDefinitionContext()\n\n public setProjectContext(projectContext: ProjectDefinitionContext) {\n this.projectContext = projectContext\n return this\n }\n\n protected override async bootstrap() {\n await super.bootstrap()\n await this._notifyUpdateSdk()\n }\n\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 private _readProjectType(projectPaths: ProjectPaths): ProjectType {\n const abs = projectPaths.abs\n if (fs.existsSync(abs.integrationDefinition)) {\n return 'integration'\n }\n if (fs.existsSync(abs.interfaceDefinition)) {\n return 'interface'\n }\n if (fs.existsSync(abs.botDefinition)) {\n return 'bot'\n }\n if (fs.existsSync(abs.pluginDefinition)) {\n return 'plugin'\n }\n throw new errors.UnsupportedProjectType()\n }\n\n protected readProjectDefinitionFromFS(): ProjectDefinitionLazy {\n try {\n const type = this._readProjectType(this.projectPaths)\n if (type === 'integration') {\n return {\n projectType: 'integration',\n resolveProjectDefinition: async () => ({\n type: 'integration',\n ...(await this._readIntegrationDefinitionFromFS(this.projectPaths)),\n }),\n }\n }\n if (type === 'plugin') {\n return {\n projectType: 'plugin',\n resolveProjectDefinition: async () => ({\n type: 'plugin',\n ...(await this._readPluginDefinitionFromFS(this.projectPaths)),\n }),\n }\n }\n if (type === 'interface') {\n return {\n projectType: 'interface',\n resolveProjectDefinition: async () => ({\n type: 'interface',\n ...(await this._readInterfaceDefinitionFromFS(this.projectPaths)),\n }),\n }\n }\n if (type === 'bot') {\n return {\n projectType: 'bot',\n resolveProjectDefinition: async () => ({\n type: 'bot',\n ...(await this._readBotDefinitionFromFS(this.projectPaths)),\n }),\n }\n }\n } catch (thrown: unknown) {\n throw errors.BotpressCLIError.wrap(thrown, 'Error while reading project definition')\n }\n throw new errors.ProjectDefinitionNotFoundError(this.projectPaths.abs.workDir)\n }\n\n private async _readIntegrationDefinitionFromFS(\n projectPaths: utils.path.PathStore<'workDir' | 'integrationDefinition'>\n ): Promise<{ definition: sdk.IntegrationDefinition } & LintIgnoredConfig> {\n const abs = projectPaths.abs\n const rel = projectPaths.rel('workDir')\n\n if (!fs.existsSync(abs.integrationDefinition)) {\n throw new errors.BotpressCLIError('Could not read integration definition')\n }\n\n const bpLintDisabled = await this._isBpLintDisabled(abs.integrationDefinition)\n\n const { outputFiles } = await this.projectContext.rebuildEntrypoint({\n absWorkingDir: abs.workDir,\n entrypoint: rel.integrationDefinition,\n })\n\n const artifact = outputFiles?.[0]\n if (!artifact) {\n throw new errors.BotpressCLIError('Could not read integration definition')\n }\n\n const definition = this.projectContext.getOrResolveDefinition<sdk.IntegrationDefinition>(artifact.text)\n validateIntegrationDefinition(definition)\n return { definition, bpLintDisabled }\n }\n\n private async _readInterfaceDefinitionFromFS(\n projectPaths: utils.path.PathStore<'workDir' | 'interfaceDefinition'>\n ): Promise<{ definition: sdk.InterfaceDefinition } & LintIgnoredConfig> {\n const abs = projectPaths.abs\n const rel = projectPaths.rel('workDir')\n\n if (!fs.existsSync(abs.interfaceDefinition)) {\n throw new errors.BotpressCLIError('Could not read interface definition')\n }\n\n const bpLintDisabled = await this._isBpLintDisabled(abs.interfaceDefinition)\n\n const { outputFiles } = await this.projectContext.rebuildEntrypoint({\n absWorkingDir: abs.workDir,\n entrypoint: rel.interfaceDefinition,\n })\n\n const artifact = outputFiles?.[0]\n if (!artifact) {\n throw new errors.BotpressCLIError('Could not read interface definition')\n }\n\n const definition = this.projectContext.getOrResolveDefinition<sdk.InterfaceDefinition>(artifact.text)\n\n return { definition, bpLintDisabled }\n }\n\n private async _readBotDefinitionFromFS(\n projectPaths: utils.path.PathStore<'workDir' | 'botDefinition'>\n ): Promise<{ definition: sdk.BotDefinition } & LintIgnoredConfig> {\n const abs = projectPaths.abs\n const rel = projectPaths.rel('workDir')\n\n if (!fs.existsSync(abs.botDefinition)) {\n throw new errors.BotpressCLIError('Could not read bot definition')\n }\n\n const bpLintDisabled = await this._isBpLintDisabled(abs.botDefinition)\n\n const { outputFiles } = await this.projectContext.rebuildEntrypoint({\n absWorkingDir: abs.workDir,\n entrypoint: rel.botDefinition,\n })\n\n const artifact = outputFiles?.[0]\n if (!artifact) {\n throw new errors.BotpressCLIError('Could not read bot definition')\n }\n\n const definition = this.projectContext.getOrResolveDefinition<sdk.BotDefinition>(artifact.text)\n validateBotDefinition(definition)\n return { definition, bpLintDisabled }\n }\n\n private async _readPluginDefinitionFromFS(\n projectPaths: utils.path.PathStore<'workDir' | 'pluginDefinition'>\n ): Promise<{ definition: sdk.PluginDefinition } & LintIgnoredConfig> {\n const abs = projectPaths.abs\n const rel = projectPaths.rel('workDir')\n\n if (!fs.existsSync(abs.pluginDefinition)) {\n throw new errors.BotpressCLIError('Could not read plugin definition')\n }\n\n const bpLintDisabled = await this._isBpLintDisabled(abs.pluginDefinition)\n\n const { outputFiles } = await this.projectContext.rebuildEntrypoint({\n absWorkingDir: abs.workDir,\n entrypoint: rel.pluginDefinition,\n })\n\n const artifact = outputFiles?.[0]\n if (!artifact) {\n throw new errors.BotpressCLIError('Could not read plugin definition')\n }\n\n const definition = this.projectContext.getOrResolveDefinition<sdk.PluginDefinition>(artifact.text)\n // TODO: validate plugin definition\n return { definition, bpLintDisabled }\n }\n\n private async _isBpLintDisabled(definitionPath: string): Promise<boolean> {\n const tsContent = await fs.promises.readFile(definitionPath, 'utf-8')\n const regex = /\\/\\* bplint-disable \\*\\//\n return regex.test(tsContent)\n }\n\n protected displayWebhookUrls(bot: client.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: sdk.IntegrationDefinition,\n argv: YargsConfig<typeof config.schemas.secrets>,\n opts: { formatEnv?: boolean; knownSecrets?: string[] } = {}\n ): Promise<Record<string, string | null>> {\n const formatEnv = opts.formatEnv ?? false\n const knownSecrets = opts.knownSecrets ?? []\n\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 | null> = {}\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 alreadyKnown = knownSecrets.includes(secretName)\n let mode: string\n if (alreadyKnown) {\n mode = 'already set'\n } else if (optional) {\n mode = 'optional'\n } else {\n mode = 'required'\n }\n\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 (alreadyKnown) {\n this.logger.log(`Secret \"${secretName}\" is unchanged`)\n } else if (optional) {\n this.logger.warn(`Secret \"${secretName}\" is unassigned`)\n } else {\n throw new errors.BotpressCLIError(`Secret \"${secretName}\" is required`)\n }\n }\n\n for (const secretName of knownSecrets) {\n const isDefined = secretName in secretDefinitions\n if (isDefined) {\n continue\n }\n const prompted = await this.prompt.confirm(`Secret \"${secretName}\" was removed. Do you wish to delete it?`)\n if (prompted) {\n this.logger.log(`Deleting secret \"${secretName}\"`, { prefix: { symbol: '\u00D7', fg: 'red' } })\n values[secretName] = null\n }\n }\n\n if (!formatEnv) {\n return values\n }\n\n const envVariables = _.mapKeys(values, (_v, k) => codegen.secretEnvVariableName(k))\n return envVariables\n }\n\n protected async prepareCreateIntegrationBody(\n integrationDef: sdk.IntegrationDefinition\n ): Promise<apiUtils.CreateIntegrationRequestBody> {\n const partialBody = await apiUtils.prepareCreateIntegrationBody(integrationDef)\n\n let code: string | undefined = undefined\n if (fs.existsSync(this.projectPaths.abs.outFileCJS)) {\n code = await this.readProjectFile(this.projectPaths.abs.outFileCJS)\n }\n\n const icon = await this.readProjectFile(integrationDef.icon, 'base64')\n const readme = await this.readProjectFile(integrationDef.readme, 'base64')\n const extractScript = await this.readProjectFile(integrationDef.identifier?.extractScript)\n const fallbackHandlerScript = await this.readProjectFile(integrationDef.identifier?.fallbackHandlerScript)\n return {\n ...partialBody,\n code,\n icon,\n readme,\n identifier: {\n extractScript,\n fallbackHandlerScript,\n },\n configuration: integrationDef.configuration\n ? {\n schema: await utils.schema.mapZodToJsonSchema(integrationDef.configuration),\n identifier: {\n required: integrationDef.configuration.identifier?.required,\n linkTemplateScript: await this.readProjectFile(\n integrationDef.configuration.identifier?.linkTemplateScript\n ),\n },\n }\n : undefined,\n configurations: integrationDef.configurations\n ? await utils.records.mapValuesAsync(integrationDef.configurations, async (configuration) => ({\n title: configuration.title,\n description: configuration.description,\n schema: await utils.schema.mapZodToJsonSchema(configuration),\n identifier: {\n required: configuration.identifier?.required,\n linkTemplateScript: await this.readProjectFile(configuration.identifier?.linkTemplateScript),\n },\n }))\n : undefined,\n }\n }\n\n protected async prepareBotDependencies(\n botDef: sdk.BotDefinition,\n api: apiUtils.ApiClient\n ): Promise<Partial<apiUtils.UpdateBotRequestBody>> {\n const integrations = await this._fetchDependencies(botDef.integrations ?? {}, ({ name, version }) =>\n api.getPublicOrPrivateIntegration({ type: 'name', name, version })\n )\n\n const plugins = await this._fetchDependencies(\n botDef.plugins ?? {},\n async ({ name, version }) => await api.getPublicOrPrivatePlugin({ type: 'name', name, version })\n )\n\n const pluginsWithBackingIntegrations = await utils.records.mapValuesAsync(plugins, async (plugin) => ({\n ...plugin,\n interfaces: await this._fetchDependencies(\n plugin.interfaces ?? {},\n async (interfaceExtension) => await api.getPublicOrPrivateIntegration({ ...interfaceExtension, type: 'name' })\n ),\n }))\n\n return {\n integrations: _(integrations)\n .keyBy((i) => i.id)\n .mapValues(\n ({ enabled, configurationType, configuration, disabledChannels }) =>\n ({\n enabled,\n configurationType,\n configuration,\n disabledChannels,\n }) satisfies NonNullable<apiUtils.UpdateBotRequestBody['integrations']>[string]\n )\n .value(),\n plugins: utils.records.mapValues(pluginsWithBackingIntegrations, (plugin) => ({\n ...plugin,\n interfaces: utils.records.mapValues(plugin.interfaces ?? {}, (iface) => ({\n ...iface,\n integrationId: iface.id,\n })),\n })),\n }\n }\n\n protected async prepareIntegrationDependencies(\n integrationDef: sdk.IntegrationDefinition,\n api: apiUtils.ApiClient\n ): Promise<Partial<apiUtils.CreateIntegrationRequestBody>> {\n const interfaces = await this._fetchDependencies(integrationDef.interfaces ?? {}, ({ name, version }) =>\n api.getPublicInterface({ type: 'name', name, version })\n )\n return { interfaces }\n }\n\n protected async preparePluginDependencies(\n pluginDef: sdk.PluginDefinition,\n api: apiUtils.ApiClient\n ): Promise<Partial<apiUtils.CreatePluginRequestBody>> {\n const integrations = await this._fetchDependencies(pluginDef.integrations ?? {}, ({ name, version }) =>\n api.getPublicOrPrivateIntegration({ type: 'name', name, version })\n )\n const interfaces = await this._fetchDependencies(pluginDef.interfaces ?? {}, ({ name, version }) =>\n api.getPublicInterface({ type: 'name', name, version })\n )\n return {\n dependencies: {\n integrations,\n interfaces,\n },\n }\n }\n\n private _fetchDependencies = async <T extends { id?: string; name: string; version: string }>(\n deps: Record<string, T>,\n fetcher: (dep: T) => Promise<{ id: string }>\n ): Promise<Record<string, T & { id: string }>> => {\n const isRemote = (dep: T): dep is T & { id: string } => dep.id !== undefined\n return utils.records.mapValuesAsync(deps, async (dep): Promise<T & { id: string }> => {\n if (isRemote(dep)) {\n return dep\n }\n const { id } = await fetcher(dep)\n return { ...dep, id }\n })\n }\n\n protected readProjectFile = async (\n filePath: string | undefined,\n encoding: BufferEncoding = 'utf-8'\n ): Promise<string | undefined> => {\n if (!filePath) {\n return undefined\n }\n const absoluteFilePath = utils.path.absoluteFrom(this.projectPaths.abs.workDir, filePath)\n return fs.promises.readFile(absoluteFilePath, encoding).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not read file \"${absoluteFilePath}\"`)\n })\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] = utils.string.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 _notifyUpdateSdk = async (): Promise<void> => {\n try {\n this.logger.debug('Checking if sdk is up to date')\n\n const { workDir } = this.projectPaths.abs\n const projectPkgJson = await utils.pkgJson.readPackageJson(workDir)\n if (!projectPkgJson) {\n this.logger.debug(`Could not find package.json at \"${workDir}\"`)\n return\n }\n\n const sdkPackageName = '@botpress/sdk'\n const actualSdkVersion = utils.pkgJson.findDependency(projectPkgJson, sdkPackageName)\n if (!actualSdkVersion) {\n this.logger.debug(`Could not find dependency \"${sdkPackageName}\" in project package.json`)\n return\n }\n\n if (actualSdkVersion.startsWith('workspace:')) {\n return\n }\n\n const actualCleanedSdkVersion = semver.valid(semver.coerce(actualSdkVersion))\n if (!actualCleanedSdkVersion) {\n this.logger.debug(`Invalid sdk version \"${actualSdkVersion}\" in project package.json`)\n return\n }\n\n const cliPkgJson = await this.readPkgJson()\n const expectedSdkVersion = utils.pkgJson.findDependency(cliPkgJson, sdkPackageName)\n if (!expectedSdkVersion) {\n this.logger.debug(`Could not find dependency \"${sdkPackageName}\" in cli package.json`)\n return\n }\n\n const expectedCleanedSdkVersion = semver.valid(semver.coerce(expectedSdkVersion))\n if (!expectedCleanedSdkVersion) {\n this.logger.debug(`Invalid sdk version \"${expectedSdkVersion}\" in cli package.json`)\n return\n }\n\n if (semver.eq(actualCleanedSdkVersion, expectedCleanedSdkVersion)) {\n return\n }\n\n const diff = semver.diff(actualCleanedSdkVersion, expectedCleanedSdkVersion)\n if (!diff) {\n this.logger.debug(`Could not compare versions \"${actualCleanedSdkVersion}\" and \"${expectedCleanedSdkVersion}\"`)\n return\n }\n\n const errorMsg = `Project SDK version is \"${actualCleanedSdkVersion}\", but expected \"${expectedCleanedSdkVersion}\"`\n if (utils.semver.releases.lt(diff, 'minor')) {\n this.logger.debug(`${errorMsg}. This may cause compatibility issues.`)\n return\n }\n\n this.logger.warn(chalk.bold(`${errorMsg}. This will cause compatibility issues.`))\n } catch (thrown) {\n const err = errors.BotpressCLIError.map(thrown)\n this.logger.debug(`Failed to check if sdk is up to date: ${err.message}`)\n }\n }\n protected validateIntegrationRegistration(\n updatedBot: UpdatedBot,\n onFailCallback: (failedIntegrations: UpdatedBot['integrations']) => void\n ) {\n let failedIntegrations: UpdatedBot['integrations'] = {}\n for (const [integrationName, integration] of Object.entries(updatedBot.integrations)) {\n if (integration.status === 'registration_failed') {\n failedIntegrations = { ...failedIntegrations, [integrationName]: integration }\n }\n }\n if (Object.keys(failedIntegrations).length > 0) {\n onFailCallback(failedIntegrations)\n }\n }\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,mBAAkB;AAClB,gBAAe;AACf,oBAAc;AACd,oBAAmB;AACnB,eAA0B;AAC1B,cAAyB;AAEzB,aAAwB;AACxB,aAAwB;AACxB,iBAAqE;AAErE,YAAuB;AACvB,4BAA8B;AA6C9B,MAAM,qBAAqB,MAAM,KAAK,UAAiC;AAAA,EAC9D,YAAY,MAA6C;AAC9D,UAAM,aAAa,MAAM,KAAK,aAAa,MAAM,KAAK,IAAI,GAAG,KAAK,OAAO;AACzE,UAAM;AAAA,MACJ,SAAS;AAAA,MACT,GAAG,cAAAA,QAAE,UAAU,OAAO,aAAa,CAAC,MAAM,MAAM,KAAK,aAAa,YAAY,CAAC,CAAC;AAAA,IAClF,CAAC;AAAA,EACH;AACF;AAEO,MAAM,yBAAyB;AAAA,EAC5B,aAAkC,oBAAI,IA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AK,aAAAD,QAAM,KAAK,GAAG,QAAQ,yCAAyC,CAAC;AAAA,IACnF,SAAS,QAAQ;AACf,YAAM,MAAM,OAAO,iBAAiB,IAAI,MAAM;AAC9C,WAAK,OAAO,MAAM,yCAAyC,IAAI,OAAO,EAAE;AAAA,IAC1E;AAAA,EACF;AAAA,EACU,gCACR,YACA,gBACA;AACA,QAAI,qBAAiD,CAAC;AACtD,eAAW,CAAC,iBAAiB,WAAW,KAAK,OAAO,QAAQ,WAAW,YAAY,GAAG;AACpF,UAAI,YAAY,WAAW,uBAAuB;AAChD,6BAAqB,EAAE,GAAG,oBAAoB,CAAC,eAAe,GAAG,YAAY;AAAA,MAC/E;AAAA,IACF;AACA,QAAI,OAAO,KAAK,kBAAkB,EAAE,SAAS,GAAG;AAC9C,qBAAe,kBAAkB;AAAA,IACnC;AAAA,EACF;AACF;",
|
|
6
6
|
"names": ["_", "fs", "chalk", "semver"]
|
|
7
7
|
}
|
|
@@ -10,12 +10,18 @@ export type BuildCodeProps = BaseProps & {
|
|
|
10
10
|
export type BuildEntrypointProps = BaseProps & {
|
|
11
11
|
entrypoint: string;
|
|
12
12
|
};
|
|
13
|
-
export declare class
|
|
13
|
+
export declare abstract class BuildContext<T> {
|
|
14
14
|
private _context;
|
|
15
15
|
private _previousProps;
|
|
16
16
|
private _previousOpts;
|
|
17
|
-
|
|
18
|
-
rebuild(props:
|
|
17
|
+
protected abstract _createContext(props: T, opts: esb.BuildOptions): Promise<esb.BuildContext>;
|
|
18
|
+
rebuild(props: T, opts?: esb.BuildOptions): Promise<esb.BuildResult<esb.BuildOptions>>;
|
|
19
|
+
}
|
|
20
|
+
export declare class BuildCodeContext extends BuildContext<BuildCodeProps> {
|
|
21
|
+
protected _createContext(props: BuildCodeProps, opts?: esb.BuildOptions): Promise<esb.BuildContext>;
|
|
22
|
+
}
|
|
23
|
+
export declare class BuildEntrypointContext extends BuildContext<BuildEntrypointProps> {
|
|
24
|
+
protected _createContext(props: BuildEntrypointProps, opts?: esb.BuildOptions): Promise<esb.BuildContext>;
|
|
19
25
|
}
|
|
20
26
|
/**
|
|
21
27
|
* Bundles a string of typescript code and writes the output to a file
|
|
@@ -29,7 +29,9 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
29
29
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
30
30
|
var esbuild_utils_exports = {};
|
|
31
31
|
__export(esbuild_utils_exports, {
|
|
32
|
-
|
|
32
|
+
BuildCodeContext: () => BuildCodeContext,
|
|
33
|
+
BuildContext: () => BuildContext,
|
|
34
|
+
BuildEntrypointContext: () => BuildEntrypointContext,
|
|
33
35
|
buildCode: () => buildCode,
|
|
34
36
|
buildEntrypoint: () => buildEntrypoint
|
|
35
37
|
});
|
|
@@ -49,10 +51,23 @@ const DEFAULT_OPTIONS = {
|
|
|
49
51
|
// important : https://github.com/node-fetch/node-fetch/issues/784#issuecomment-1014768204
|
|
50
52
|
minify: false
|
|
51
53
|
};
|
|
52
|
-
class
|
|
54
|
+
class BuildContext {
|
|
53
55
|
_context;
|
|
54
56
|
_previousProps;
|
|
55
57
|
_previousOpts = {};
|
|
58
|
+
async rebuild(props, opts = {}) {
|
|
59
|
+
if (!this._context || !import_lodash.default.isEqual(props, this._previousProps) || !import_lodash.default.isEqual(opts, this._previousOpts)) {
|
|
60
|
+
if (this._context) {
|
|
61
|
+
await this._context.dispose();
|
|
62
|
+
}
|
|
63
|
+
this._context = await this._createContext(props, opts);
|
|
64
|
+
this._previousOpts = opts;
|
|
65
|
+
this._previousProps = props;
|
|
66
|
+
}
|
|
67
|
+
return await this._context?.rebuild();
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
class BuildCodeContext extends BuildContext {
|
|
56
71
|
_createContext(props, opts = {}) {
|
|
57
72
|
const { absWorkingDir, code, outfile } = props;
|
|
58
73
|
return esb.context({
|
|
@@ -64,16 +79,18 @@ class IncrementalBuildContext {
|
|
|
64
79
|
write: true
|
|
65
80
|
});
|
|
66
81
|
}
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
82
|
+
}
|
|
83
|
+
class BuildEntrypointContext extends BuildContext {
|
|
84
|
+
_createContext(props, opts = {}) {
|
|
85
|
+
const { absWorkingDir, entrypoint } = props;
|
|
86
|
+
return esb.context({
|
|
87
|
+
...DEFAULT_OPTIONS,
|
|
88
|
+
...opts,
|
|
89
|
+
absWorkingDir,
|
|
90
|
+
entryPoints: [entrypoint],
|
|
91
|
+
outfile: void 0,
|
|
92
|
+
write: false
|
|
93
|
+
});
|
|
77
94
|
}
|
|
78
95
|
}
|
|
79
96
|
function buildCode(props, opts = {}) {
|
|
@@ -100,7 +117,9 @@ function buildEntrypoint(props, opts = {}) {
|
|
|
100
117
|
}
|
|
101
118
|
// Annotate the CommonJS export names for ESM import in node:
|
|
102
119
|
0 && (module.exports = {
|
|
103
|
-
|
|
120
|
+
BuildCodeContext,
|
|
121
|
+
BuildContext,
|
|
122
|
+
BuildEntrypointContext,
|
|
104
123
|
buildCode,
|
|
105
124
|
buildEntrypoint,
|
|
106
125
|
...require("esbuild")
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/utils/esbuild-utils.ts"],
|
|
4
|
-
"sourcesContent": ["import * as esb from 'esbuild'\nimport _ from 'lodash'\n\nexport * from 'esbuild'\n\ntype BaseProps = {\n absWorkingDir: string\n}\n\nexport type BuildCodeProps = BaseProps & {\n code: string\n outfile: string\n}\n\nexport type BuildEntrypointProps = BaseProps & {\n entrypoint: string\n}\n\nconst DEFAULT_OPTIONS: esb.BuildOptions = {\n bundle: true,\n sourcemap: false,\n logLevel: 'silent',\n platform: 'node',\n target: 'es2020',\n legalComments: 'none',\n logOverride: { 'equals-negative-zero': 'silent' },\n keepNames: true, // important : https://github.com/node-fetch/node-fetch/issues/784#issuecomment-1014768204\n minify: false,\n}\n\nexport class
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,UAAqB;AACrB,oBAAc;AAEd,kCAAc,oBAHd;AAkBA,MAAM,kBAAoC;AAAA,EACxC,QAAQ;AAAA,EACR,WAAW;AAAA,EACX,UAAU;AAAA,EACV,UAAU;AAAA,EACV,QAAQ;AAAA,EACR,eAAe;AAAA,EACf,aAAa,EAAE,wBAAwB,SAAS;AAAA,EAChD,WAAW;AAAA;AAAA,EACX,QAAQ;AACV;AAEO,
|
|
4
|
+
"sourcesContent": ["import * as esb from 'esbuild'\nimport _ from 'lodash'\n\nexport * from 'esbuild'\n\ntype BaseProps = {\n absWorkingDir: string\n}\n\nexport type BuildCodeProps = BaseProps & {\n code: string\n outfile: string\n}\n\nexport type BuildEntrypointProps = BaseProps & {\n entrypoint: string\n}\n\nconst DEFAULT_OPTIONS: esb.BuildOptions = {\n bundle: true,\n sourcemap: false,\n logLevel: 'silent',\n platform: 'node',\n target: 'es2020',\n legalComments: 'none',\n logOverride: { 'equals-negative-zero': 'silent' },\n keepNames: true, // important : https://github.com/node-fetch/node-fetch/issues/784#issuecomment-1014768204\n minify: false,\n}\n\nexport abstract class BuildContext<T> {\n private _context: esb.BuildContext | undefined\n private _previousProps: T | undefined\n private _previousOpts: esb.BuildOptions = {}\n\n protected abstract _createContext(props: T, opts: esb.BuildOptions): Promise<esb.BuildContext>\n\n public async rebuild(props: T, opts: esb.BuildOptions = {}) {\n if (!this._context || !_.isEqual(props, this._previousProps) || !_.isEqual(opts, this._previousOpts)) {\n if (this._context) {\n await this._context.dispose()\n }\n this._context = await this._createContext(props, opts)\n this._previousOpts = opts\n this._previousProps = props\n }\n return await this._context?.rebuild()\n }\n}\n\nexport class BuildCodeContext extends BuildContext<BuildCodeProps> {\n protected _createContext(props: BuildCodeProps, opts: esb.BuildOptions = {}): Promise<esb.BuildContext> {\n const { absWorkingDir, code, outfile } = props\n return esb.context({\n ...DEFAULT_OPTIONS,\n ...opts,\n absWorkingDir,\n outfile,\n stdin: { contents: code, resolveDir: absWorkingDir, loader: 'ts' },\n write: true,\n })\n }\n}\n\nexport class BuildEntrypointContext extends BuildContext<BuildEntrypointProps> {\n protected _createContext(props: BuildEntrypointProps, opts: esb.BuildOptions = {}): Promise<esb.BuildContext> {\n const { absWorkingDir, entrypoint } = props\n return esb.context({\n ...DEFAULT_OPTIONS,\n ...opts,\n absWorkingDir,\n entryPoints: [entrypoint],\n outfile: undefined,\n write: false,\n })\n }\n}\n\n/**\n * Bundles a string of typescript code and writes the output to a file\n */\nexport function buildCode(props: BuildCodeProps, opts: esb.BuildOptions = {}): Promise<esb.BuildResult> {\n const { absWorkingDir, code, outfile } = props\n return esb.build({\n ...DEFAULT_OPTIONS,\n ...opts,\n absWorkingDir,\n outfile,\n stdin: { contents: code, resolveDir: absWorkingDir, loader: 'ts' },\n write: true,\n })\n}\n\n/**\n * Bundles a typescript file and returns the output as a string\n */\nexport function buildEntrypoint(\n props: BuildEntrypointProps,\n opts: esb.BuildOptions = {}\n): Promise<esb.BuildResult & { outputFiles: esb.OutputFile[] }> {\n const { absWorkingDir, entrypoint } = props\n return esb.build({\n ...DEFAULT_OPTIONS,\n ...opts,\n absWorkingDir,\n entryPoints: [entrypoint],\n outfile: undefined,\n write: false,\n })\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,UAAqB;AACrB,oBAAc;AAEd,kCAAc,oBAHd;AAkBA,MAAM,kBAAoC;AAAA,EACxC,QAAQ;AAAA,EACR,WAAW;AAAA,EACX,UAAU;AAAA,EACV,UAAU;AAAA,EACV,QAAQ;AAAA,EACR,eAAe;AAAA,EACf,aAAa,EAAE,wBAAwB,SAAS;AA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AG;AAAA,IACH,GAAG;AAAA,IACH;AAAA,IACA;AAAA,IACA,OAAO,EAAE,UAAU,MAAM,YAAY,eAAe,QAAQ,KAAK;AAAA,IACjE,OAAO;AAAA,EACT,CAAC;AACH;AAKO,SAAS,gBACd,OACA,OAAyB,CAAC,GACoC;AAC9D,QAAM,EAAE,eAAe,WAAW,IAAI;AACtC,SAAO,IAAI,MAAM;AAAA,IACf,GAAG;AAAA,IACH,GAAG;AAAA,IACH;AAAA,IACA,aAAa,CAAC,UAAU;AAAA,IACxB,SAAS;AAAA,IACT,OAAO;AAAA,EACT,CAAC;AACH;",
|
|
6
6
|
"names": ["_"]
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@botpress/cli",
|
|
3
|
-
"version": "4.17.
|
|
3
|
+
"version": "4.17.19",
|
|
4
4
|
"description": "Botpress CLI",
|
|
5
5
|
"scripts": {
|
|
6
6
|
"build": "pnpm run build:types && pnpm run bundle && pnpm run template:gen",
|
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
"@apidevtools/json-schema-ref-parser": "^11.7.0",
|
|
25
25
|
"@botpress/chat": "0.5.1",
|
|
26
26
|
"@botpress/client": "1.25.0",
|
|
27
|
-
"@botpress/sdk": "4.15.
|
|
27
|
+
"@botpress/sdk": "4.15.10",
|
|
28
28
|
"@bpinternal/const": "^0.1.0",
|
|
29
29
|
"@bpinternal/tunnel": "^0.1.1",
|
|
30
30
|
"@bpinternal/yargs-extra": "^0.0.3",
|