Skip to content

armgit / E2B

Public Imported from GitHub
0

Open-source, secure environment with real-world tools for enterprise-grade agents.

feat: add template init for new template SDK (#881)

Jakub Dobry2ec9ea8a449a
diff --git a/.changeset/silent-coins-brush.md b/.changeset/silent-coins-brush.md
new file mode 100644
index 000000000..eec17d606
--- /dev/null
+++ b/.changeset/silent-coins-brush.md
@@ -0,0 +1,5 @@
+---
+'@e2b/cli': patch
+---
+
+add init command for the new template format
diff --git a/packages/cli/.prettierignore b/packages/cli/.prettierignore
index 5acb4c912..95ebb0038 100644
--- a/packages/cli/.prettierignore
+++ b/packages/cli/.prettierignore
@@ -1 +1,2 @@
-*.hbs
\ No newline at end of file
+*.hbs
+tests/**/fixtures/**/*
\ No newline at end of file
diff --git a/packages/cli/package.json b/packages/cli/package.json
index d6e77bf67..87e4a0cb6 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -54,6 +54,7 @@
"@types/inquirer": "^9.0.7",
"@types/json2md": "^1.5.4",
"@types/node": "^18.18.6",
+ "@types/npmcli__package-json": "^4.0.4",
"@types/statuses": "^2.0.5",
"@types/update-notifier": "6.0.5",
"@vitest/coverage-v8": "^3.2.4",
@@ -76,6 +77,7 @@
"dependencies": {
"@iarna/toml": "^2.2.5",
"@inquirer/prompts": "^5.5.0",
+ "@npmcli/package-json": "^5.2.1",
"async-listen": "^3.0.1",
"boxen": "^7.1.1",
"chalk": "^5.3.0",
diff --git a/packages/cli/src/commands/template/generators/handlebars.ts b/packages/cli/src/commands/template/generators/handlebars.ts
index ce1b18dcd..05ed90a2f 100644
--- a/packages/cli/src/commands/template/generators/handlebars.ts
+++ b/packages/cli/src/commands/template/generators/handlebars.ts
@@ -2,7 +2,12 @@ import { Template, TemplateClass } from 'e2b'
import * as fs from 'fs'
import HandlebarsLib from 'handlebars'
import * as path from 'path'
-import { TemplateJSON, TemplateWithStepsJSON } from './types'
+import {
+ GeneratedFiles,
+ Language,
+ TemplateJSON,
+ TemplateWithStepsJSON,
+} from './types'
class Handlebars {
private handlebars: typeof HandlebarsLib
@@ -189,3 +194,40 @@ export async function generatePythonCode(
buildContent: buildContent.trim(),
}
}
+
+/**
+ * Generate README.md content using Handlebars
+ */
+export async function generateReadmeContent(
+ alias: string,
+ templateDir: string,
+ generatedFiles: GeneratedFiles
+): Promise<string> {
+ const hb = new Handlebars()
+
+ // Load and compile README template
+ const templatesDir = path.join(__dirname, 'templates')
+ const readmeSource = fs.readFileSync(
+ path.join(templatesDir, 'readme.hbs'),
+ 'utf8'
+ )
+
+ const generateReadmeSource = hb.compile(readmeSource)
+
+ // Prepare template data
+ const templateData = {
+ alias,
+ templateDir,
+ templateFile: generatedFiles.templateFile,
+ buildDevFile: generatedFiles.buildDevFile,
+ buildProdFile: generatedFiles.buildProdFile,
+ isTypeScript: generatedFiles.language === Language.TypeScript,
+ isPython:
+ generatedFiles.language === Language.PythonSync ||
+ generatedFiles.language === Language.PythonAsync,
+ isPythonSync: generatedFiles.language === Language.PythonSync,
+ isPythonAsync: generatedFiles.language === Language.PythonAsync,
+ }
+
+ return generateReadmeSource(templateData).trim()
+}
diff --git a/packages/cli/src/commands/template/index.ts b/packages/cli/src/commands/template/index.ts
index aedfbff92..f303a82b6 100644
--- a/packages/cli/src/commands/template/index.ts
+++ b/packages/cli/src/commands/template/index.ts
@@ -6,6 +6,7 @@ import { initCommand } from './init'
import { deleteCommand } from './delete'
import { publishCommand, unPublishCommand } from './publish'
import { migrateCommand } from './migrate'
+import { initV2Command } from './init-v2'
export const templateCommand = new commander.Command('template')
.description('manage sandbox templates')
@@ -13,6 +14,7 @@ export const templateCommand = new commander.Command('template')
.addCommand(buildCommand)
.addCommand(listCommand)
.addCommand(initCommand)
+ .addCommand(initV2Command)
.addCommand(deleteCommand)
.addCommand(publishCommand)
.addCommand(unPublishCommand)
diff --git a/packages/cli/src/commands/template/init-v2.ts b/packages/cli/src/commands/template/init-v2.ts
new file mode 100644
index 000000000..139fac366
--- /dev/null
+++ b/packages/cli/src/commands/template/init-v2.ts
@@ -0,0 +1,326 @@
+import { input, select } from '@inquirer/prompts'
+import PackageJson from '@npmcli/package-json'
+import * as commander from 'commander'
+import { Template } from 'e2b'
+import * as fs from 'fs'
+import * as path from 'path'
+import { pathOption } from 'src/options'
+import { getRoot } from 'src/utils/filesystem'
+import { asPrimary } from 'src/utils/format'
+import {
+ generateAndWriteTemplateFiles,
+ GeneratedFiles,
+ Language,
+ languageDisplay,
+} from './generators'
+import { generateReadmeContent } from './generators/handlebars'
+
+const DEFAULT_TEMPLATE_NAME = 'my-template'
+
+/**
+ * Generate template files using shared template generation logic
+ */
+async function generateTemplateFiles(
+ root: string,
+ alias: string,
+ language: Language,
+ cpuCount?: number,
+ memoryMB?: number
+): Promise<GeneratedFiles> {
+ const template = Template().fromBaseImage().runCmd('echo Hello World E2B!')
+
+ return generateAndWriteTemplateFiles(
+ root,
+ alias,
+ language,
+ template,
+ cpuCount,
+ memoryMB
+ )
+}
+
+/**
+ * Add build scripts to Makefile if it exists or create a new one
+ */
+async function addMakefileScripts(
+ root: string,
+ files: GeneratedFiles,
+ templateDirName: string
+): Promise<void> {
+ try {
+ const makefileName = 'Makefile'
+ const makefileExists = fs.existsSync(path.join(root, makefileName))
+
+ let cdPrefix = ''
+ if (makefileExists) {
+ cdPrefix = `cd ${templateDirName} && `
+ }
+
+ const makefileContent = `
+.PHONY: e2b:build:dev
+e2b:build:dev:
+\t${cdPrefix}python ${files.buildDevFile}
+
+.PHONY: e2b:build:prod
+e2b:build:prod:
+\t${cdPrefix}python ${files.buildProdFile}
+`
+
+ if (makefileExists) {
+ const makefilePath = path.join(root, makefileName)
+ await fs.promises.appendFile(makefilePath, '\n' + makefileContent, 'utf8')
+ } else {
+ // Create a basic Makefile if it doesn't exist
+ const makefilePath = path.join(root, templateDirName, makefileName)
+ await fs.promises.writeFile(makefilePath, makefileContent, 'utf8')
+ }
+
+ console.log('\n๐Ÿ“ Added build scripts to Makefile:')
+ console.log(
+ ` ${asPrimary('make e2b:build:dev')} - Build development template`
+ )
+ console.log(
+ ` ${asPrimary('make e2b:build:prod')} - Build production template`
+ )
+ } catch (err) {
+ console.warn(
+ '\nโš ๏ธ Could not add scripts to Makefile:',
+ err instanceof Error ? err.message : err
+ )
+ }
+}
+
+/**
+ * Add build scripts to package.json if it exists or create a new one
+ */
+async function addPackageJsonScripts(
+ root: string,
+ files: GeneratedFiles,
+ templateDirName: string
+): Promise<void> {
+ try {
+ let cdPrefix = ''
+ let pkgJson: PackageJson
+ try {
+ // The library expects the directory path, not the full file path
+ pkgJson = await PackageJson.load(root)
+ cdPrefix = `cd ${templateDirName} && `
+ } catch (error) {
+ // Handle the case where package.json does not exist
+ const createRoot = path.join(root, templateDirName)
+ pkgJson = await PackageJson.create(createRoot)
+ }
+
+ pkgJson.update({
+ scripts: {
+ ...pkgJson.content.scripts,
+ 'e2b:build:dev': `${cdPrefix}npx tsx ${files.buildDevFile}`,
+ 'e2b:build:prod': `${cdPrefix}npx tsx ${files.buildProdFile}`,
+ },
+ })
+
+ // Save the changes
+ await pkgJson.save()
+
+ console.log('\n๐Ÿ“ Added build scripts to package.json:')
+ console.log(
+ ` ${asPrimary('npm run e2b:build:dev')} - Build development template`
+ )
+ console.log(
+ ` ${asPrimary('npm run e2b:build:prod')} - Build production template`
+ )
+ } catch (err) {
+ console.warn(
+ '\nโš ๏ธ Could not add scripts to package.json:',
+ err instanceof Error ? err.message : err
+ )
+ }
+}
+
+/**
+ * Check template name format
+ */
+function templateNameRegex(name: string): boolean {
+ return /^[a-z0-9][a-z0-9_-]*[a-z0-9]$|^[a-z0-9]$/.test(name)
+}
+
+function validateTemplateName(name: string) {
+ if (!name || name.trim().length === 0) {
+ throw new Error('Template name cannot be empty')
+ }
+ if (!templateNameRegex(name.trim())) {
+ throw new Error(
+ 'Template name must contain only lowercase letters, numbers, hyphens, and underscores, and cannot start or end with a hyphen or underscore'
+ )
+ }
+}
+
+export const initV2Command = new commander.Command('init-v2')
+ .description('initialize a new sandbox template using the SDK')
+ .addOption(pathOption)
+ .option('-n, --name <name>', 'template name (alias)', (value) => {
+ try {
+ validateTemplateName(value)
+ } catch (err) {
+ throw new commander.InvalidArgumentError(
+ err instanceof Error ? err.message : String(err)
+ )
+ }
+
+ return value
+ })
+ .option(
+ '-l, --language <language>',
+ `target language: ${Object.values(Language).join(', ')}`,
+ (value) => {
+ if (!Object.values(Language).includes(value as Language)) {
+ throw new commander.InvalidArgumentError(
+ `Invalid language. Must be one of: ${Object.values(Language).join(
+ ', '
+ )}`
+ )
+ }
+ return value as Language
+ }
+ )
+ .alias('it-v2')
+ .alias('create')
+ .action(
+ async (opts: { path?: string; name?: string; language?: Language }) => {
+ try {
+ process.stdout.write('\n')
+
+ const root = getRoot(opts.path)
+
+ console.log('๐Ÿš€ Initializing Sandbox Template...\n')
+
+ // Step 1: Get template name (from CLI or prompt)
+ let templateName: string = opts.name ?? DEFAULT_TEMPLATE_NAME
+ if (opts.name === undefined) {
+ templateName = await input({
+ message: 'Enter template name (alias):',
+ default: DEFAULT_TEMPLATE_NAME,
+ validate: (input: string) => {
+ try {
+ validateTemplateName(input)
+ } catch (err) {
+ return err instanceof Error ? err.message : err
+ }
+
+ return true
+ },
+ })
+ }
+ templateName = templateName.trim()
+ console.log(`Using template name: ${templateName}`)
+
+ // Step 2: Get language (from CLI or prompt)
+ let language: Language
+ if (opts.language) {
+ language = opts.language
+ console.log(`Using language: ${languageDisplay[language]}`)
+ } else {
+ language = await select({
+ message: 'Select target language for template files:',
+ choices: [
+ {
+ name: languageDisplay[Language.TypeScript],
+ value: Language.TypeScript,
+ description:
+ 'Generate .ts files for JavaScript/TypeScript projects',
+ },
+ {
+ name: languageDisplay[Language.PythonSync],
+ value: Language.PythonSync,
+ description: 'Generate synchronous Python template files',
+ },
+ {
+ name: languageDisplay[Language.PythonAsync],
+ value: Language.PythonAsync,
+ description: 'Generate asynchronous Python template files',
+ },
+ ],
+ default: Language.TypeScript,
+ })
+ }
+
+ // Step 3: Create template directory - fail if it already exists
+ const templateDirName = templateName
+ const templateDir = path.join(root, templateDirName)
+
+ if (fs.existsSync(templateDir)) {
+ throw new Error(
+ `Directory '${templateDirName}' already exists. Please choose a different template name or remove the existing directory.`
+ )
+ }
+
+ await fs.promises.mkdir(templateDir, { recursive: true })
+
+ // Step 4: Generate template and build files in the template directory
+ const generatedFiles = await generateTemplateFiles(
+ templateDir,
+ templateName,
+ language
+ )
+
+ // Step 5: Add scripts
+ switch (language) {
+ case Language.TypeScript:
+ await addPackageJsonScripts(root, generatedFiles, templateDirName)
+ break
+ case Language.PythonAsync:
+ case Language.PythonSync:
+ await addMakefileScripts(root, generatedFiles, templateDirName)
+ break
+ default:
+ throw new Error('Unsupported language for scripts')
+ }
+
+ // Step 6: Create README.md
+ const readmeContent = await generateReadmeContent(
+ templateName,
+ templateDirName,
+ generatedFiles
+ )
+ const readmeFilePath = path.join(templateDir, 'README.md')
+ await fs.promises.writeFile(readmeFilePath, readmeContent, 'utf8')
+
+ console.log('\n๐ŸŽ‰ Template initialized successfully!')
+ console.log(
+ `\nTemplate created in: ${asPrimary(`./${templateDirName}/`)}`
+ )
+ console.log('\nYou can now build your template using:')
+
+ switch (language) {
+ case Language.TypeScript:
+ console.log(
+ ` ${asPrimary('npm run e2b:build:dev')} (for development)`
+ )
+ console.log(
+ ` ${asPrimary('npm run e2b:build:prod')} (for production)`
+ )
+ break
+ case Language.PythonAsync:
+ case Language.PythonSync:
+ console.log(
+ ` ${asPrimary('make e2b:build:dev')} (for development)`
+ )
+ console.log(
+ ` ${asPrimary('make e2b:build:prod')} (for production)`
+ )
+ break
+ default:
+ throw new Error('Unsupported language for instructions')
+ }
+
+ console.log(
+ `\nLearn more about Sandbox Templates: ${asPrimary(
+ 'https://e2b.dev/docs'
+ )}\n`
+ )
+ } catch (err: any) {
+ console.error(err)
+ process.exit(1)
+ }
+ }
+ )
diff --git a/packages/cli/src/commands/template/migrate.ts b/packages/cli/src/commands/template/migrate.ts
index 4a998bdc7..51afdd48e 100644
--- a/packages/cli/src/commands/template/migrate.ts
+++ b/packages/cli/src/commands/template/migrate.ts
@@ -100,7 +100,7 @@ export const migrateCommand = new commander.Command('migrate')
`specify target language: ${Object.values(Language).join(', ')}`,
(value) => {
if (!Object.values(Language).includes(value as Language)) {
- throw new Error(
+ throw new commander.InvalidArgumentError(
`Invalid language. Must be one of: ${Object.values(Language).join(
', '
)}`
diff --git a/packages/cli/src/templates/readme.hbs b/packages/cli/src/templates/readme.hbs
new file mode 100644
index 000000000..62b2c1100
--- /dev/null
+++ b/packages/cli/src/templates/readme.hbs
@@ -0,0 +1,89 @@
+# {{alias}} - E2B Sandbox Template
+
+This is an E2B sandbox template that allows you to run code in a controlled environment.
+
+## Prerequisites
+
+Before you begin, make sure you have:
+- An E2B account (sign up at [e2b.dev](https://e2b.dev))
+- Your E2B API key (get it from your [E2B dashboard](https://e2b.dev/dashboard))
+{{#if isTypeScript}}- Node.js and npm/yarn (or similar) installed{{else if isPython}}- Python installed{{/if}}
+
+## Configuration
+
+1. Create a `.env` file in your project root or set the environment variable:
+ ```
+ E2B_API_KEY=your_api_key_here
+ ```
+
+## Building the Template
+
+```bash
+{{#if isTypeScript}}
+# For development
+npm run e2b:build:dev
+
+# For production
+npm run e2b:build:prod
+{{else if isPython}}
+# For development
+make e2b:build:dev
+
+# For production
+make e2b:build:prod
+{{/if}}
+```
+
+## Using the Template in a Sandbox
+
+Once your template is built, you can use it in your E2B sandbox:
+
+{{#if isTypeScript}}
+```typescript
+import { Sandbox } from 'e2b'
+
+// Create a new sandbox instance
+const sandbox = await Sandbox.create('{{alias}}')
+
+// Your sandbox is ready to use!
+console.log('Sandbox created successfully')
+```
+{{else if isPythonSync}}
+```python
+from e2b import Sandbox
+
+# Create a new sandbox instance
+sandbox = Sandbox.create('{{alias}}')
+
+# Your sandbox is ready to use!
+print('Sandbox created successfully')
+```
+{{else if isPythonAsync}}
+```python
+from e2b import AsyncSandbox
+import asyncio
+
+async def main():
+ # Create a new sandbox instance
+ sandbox = await AsyncSandbox.create('{{alias}}')
+
+ # Your sandbox is ready to use!
+ print('Sandbox created successfully')
+
+# Run the async function
+asyncio.run(main())
+```
+{{/if}}
+
+## Template Structure
+
+- `{{templateFile}}` - Defines the sandbox template configuration
+- `{{buildDevFile}}` - Builds the template for development
+- `{{buildProdFile}}` - Builds the template for production
+
+## Next Steps
+
+1. Customize the template in `{{templateFile}}` to fit your needs
+2. Build the template using one of the methods above
+3. Use the template in your E2B sandbox code
+4. Check out the [E2B documentation](https://e2b.dev/docs) for more advanced usage
diff --git a/packages/cli/tests/commands/template/init.test.ts b/packages/cli/tests/commands/template/init.test.ts
new file mode 100644
index 000000000..020c90195
--- /dev/null
+++ b/packages/cli/tests/commands/template/init.test.ts
@@ -0,0 +1,367 @@
+import { execSync } from 'child_process'
+import { existsSync } from 'fs'
+import * as fs from 'fs/promises'
+import * as path from 'path'
+import { afterEach, beforeEach, describe, expect, test } from 'vitest'
+import { Language } from '../../../src/commands/template/generators'
+
+describe('Template Init', () => {
+ let testDir: string
+ const cliPath = path.join(process.cwd(), 'dist', 'index.js')
+
+ beforeEach(async () => {
+ // Use Node.js built-in temp directory handling
+ testDir = await fs.mkdtemp('e2b-init-test-')
+ })
+
+ afterEach(async () => {
+ // Clean up test directory
+ if (testDir) {
+ await fs.rm(testDir, { recursive: true, force: true })
+ }
+ })
+
+ describe('CLI Options', () => {
+ Object.values(Language).forEach((language) => {
+ test(`should generate files with --name and --language ${language}`, async () => {
+ const templateName = 'my-test-template'
+
+ // Run init command with CLI options
+ execSync(
+ `node "${cliPath}" template init-v2 --name "${templateName}" --language "${language}" --path "${testDir}"`,
+ { stdio: 'inherit' }
+ )
+
+ // Verify template directory was created
+ const templateDir = path.join(testDir, templateName)
+ expect(existsSync(templateDir)).toBe(true)
+
+ // Verify files were created in the template directory
+ const expectedFiles = getExpectedFiles(language)
+
+ for (const file of expectedFiles) {
+ const filePath = path.join(templateDir, file)
+ expect(existsSync(filePath)).toBe(true)
+
+ // Verify file content is not empty
+ const content = await fs.readFile(filePath, 'utf8')
+ expect(content.trim().length).toBeGreaterThan(0)
+ }
+
+ // Verify template name is used in build files
+ await verifyTemplateNameInBuildFiles(
+ templateDir,
+ language,
+ templateName
+ )
+ })
+ })
+
+ test('should validate template name format', async () => {
+ const invalidNames = [
+ 'My-Template', // uppercase
+ '-invalid-start', // starts with hyphen
+ 'invalid-end-', // ends with hyphen
+ '_invalid-start', // starts with underscore
+ 'invalid-end_', // ends with underscore
+ 'invalid space', // contains space
+ '', // empty
+ ]
+
+ for (const invalidName of invalidNames) {
+ expect(() => {
+ execSync(
+ `node "${cliPath}" template init-v2 --name "${invalidName}" --language "typescript" --path "${testDir}"`,
+ { stdio: 'pipe' }
+ )
+ }).toThrow()
+ }
+ })
+
+ test('should validate language parameter', async () => {
+ expect(() => {
+ execSync(
+ `node "${cliPath}" template init-v2 --name "test" --language "invalid-lang" --path "${testDir}"`,
+ { stdio: 'pipe' }
+ )
+ }).toThrow()
+ })
+
+ test('should work with valid template names', async () => {
+ const validNames = [
+ 'a', // single character
+ 'abc', // simple
+ 'my-template', // with hyphens
+ 'my_template', // with underscores
+ 'my-template_name', // with hyphens and underscores
+ 'test123', // with numbers
+ '123test', // starting with number
+ 'a-b-c-d-e', // multiple hyphens
+ 'a_b_c_d_e', // multiple underscores
+ 'api-server_v2', // mixed hyphens and underscores
+ ]
+
+ for (const validName of validNames) {
+ // Clean directory before each test
+ const files = await fs.readdir(testDir)
+ for (const file of files) {
+ await fs.rm(path.join(testDir, file), {
+ recursive: true,
+ force: true,
+ })
+ }
+
+ // Should not throw
+ execSync(
+ `node "${cliPath}" template init-v2 --name "${validName}" --language "typescript" --path "${testDir}"`,
+ { stdio: 'pipe' }
+ )
+
+ // Verify template directory was created
+ const templateDir = path.join(testDir, validName)
+ expect(existsSync(templateDir)).toBe(true)
+
+ // Verify files were created in the template directory
+ const expectedFiles = getExpectedFiles(Language.TypeScript)
+ for (const file of expectedFiles) {
+ expect(existsSync(path.join(templateDir, file))).toBe(true)
+ }
+ }
+ })
+ })
+
+ describe('Package.json Integration', () => {
+ test('should add scripts to existing package.json', async () => {
+ // Create a package.json file in the parent directory
+ const packageJson = {
+ name: 'test-project',
+ version: '1.0.0',
+ scripts: {
+ test: 'echo "test"',
+ },
+ }
+ const packageJsonPath = path.join(testDir, 'package.json')
+ await fs.writeFile(packageJsonPath, JSON.stringify(packageJson, null, 2))
+
+ // Run init command
+ execSync(
+ `node "${cliPath}" template init-v2 --name "test-template" --language "typescript" --path "${testDir}"`,
+ { stdio: 'inherit' }
+ )
+
+ // Verify package.json was updated (it should remain in the parent directory)
+ const updatedPackageJson = JSON.parse(
+ await fs.readFile(packageJsonPath, 'utf8')
+ )
+
+ expect(updatedPackageJson.scripts).toHaveProperty('e2b:build:dev')
+ expect(updatedPackageJson.scripts).toHaveProperty('e2b:build:prod')
+ expect(updatedPackageJson.scripts.test).toBe('echo "test"') // existing script preserved
+ })
+
+ test('should work without package.json', async () => {
+ // Run init command without package.json
+ execSync(
+ `node "${cliPath}" template init-v2 --name "test-template" --language "typescript" --path "${testDir}"`,
+ { stdio: 'inherit' }
+ )
+
+ // Verify template directory was created
+ const templateDir = path.join(testDir, 'test-template')
+ expect(existsSync(templateDir)).toBe(true)
+
+ // Verify files were created in the template directory
+ const expectedFiles = getExpectedFiles(Language.TypeScript)
+ for (const file of expectedFiles) {
+ expect(existsSync(path.join(templateDir, file))).toBe(true)
+ }
+
+ // Verify package.json was created in the template directory
+ const createdPackageJSON = JSON.parse(
+ await fs.readFile(path.join(templateDir, 'package.json'), 'utf8')
+ )
+
+ expect(createdPackageJSON.scripts).toHaveProperty('e2b:build:dev')
+ expect(createdPackageJSON.scripts).toHaveProperty('e2b:build:prod')
+ })
+ })
+
+ describe('Makefile Integration', () => {
+ test('should add scripts to existing Makefile', async () => {
+ // Create a Makefile file in the parent directory
+ const makefile = `
+.PHONY: build
+build/%:
+\tCGO_ENABLED=1 go build
+ `
+ const makefilePath = path.join(testDir, 'Makefile')
+ await fs.writeFile(makefilePath, makefile)
+
+ // Run init command
+ execSync(
+ `node "${cliPath}" template init-v2 --name "test-template" --language "python-sync" --path "${testDir}"`,
+ { stdio: 'inherit' }
+ )
+
+ // Verify Makefile was updated (it should remain in the parent directory)
+ const updatedMakefile = await fs.readFile(makefilePath, 'utf8')
+
+ expect(updatedMakefile).toContain('e2b:build:dev')
+ expect(updatedMakefile).toContain('e2b:build:prod')
+ expect(updatedMakefile).toContain(`.PHONY: build
+build/%:
+\tCGO_ENABLED=1 go build`) // existing script preserved
+ })
+
+ test('should work without Makefile', async () => {
+ // Run init command without Makefile
+ execSync(
+ `node "${cliPath}" template init-v2 --name "test-template" --language "python-sync" --path "${testDir}"`,
+ { stdio: 'inherit' }
+ )
+
+ // Verify template directory was created
+ const templateDir = path.join(testDir, 'test-template')
+ expect(existsSync(templateDir)).toBe(true)
+
+ // Verify files were created in the template directory
+ const expectedFiles = getExpectedFiles(Language.PythonSync)
+ for (const file of expectedFiles) {
+ expect(existsSync(path.join(templateDir, file))).toBe(true)
+ }
+
+ // Verify Makefile was created in the template directory
+ const createdMakefile = await fs.readFile(
+ path.join(templateDir, 'Makefile'),
+ 'utf8'
+ )
+ expect(createdMakefile).toContain('e2b:build:dev')
+ expect(createdMakefile).toContain('e2b:build:prod')
+ })
+ })
+
+ describe('File Content Validation', () => {
+ test('should generate correct TypeScript template content', async () => {
+ execSync(
+ `node "${cliPath}" template init-v2 --name "test-ts" --language "typescript" --path "${testDir}"`,
+ { stdio: 'inherit' }
+ )
+
+ const templateDir = path.join(testDir, 'test-ts')
+ const templateContent = await fs.readFile(
+ path.join(templateDir, 'template.ts'),
+ 'utf8'
+ )
+
+ // Verify basic structure
+ expect(templateContent).toContain("import { Template } from 'e2b'")
+ expect(templateContent).toContain('export const template = Template()')
+ expect(templateContent).toContain('fromImage')
+ expect(templateContent).toContain('e2bdev/base')
+ })
+
+ test('should generate correct Python template content', async () => {
+ execSync(
+ `node "${cliPath}" template init-v2 --name "test-py" --language "python-sync" --path "${testDir}"`,
+ { stdio: 'inherit' }
+ )
+
+ const templateDir = path.join(testDir, 'test-py')
+ const templateContent = await fs.readFile(
+ path.join(templateDir, 'template.py'),
+ 'utf8'
+ )
+
+ // Verify basic structure
+ expect(templateContent).toContain('from e2b import Template')
+ expect(templateContent).toContain('template = (')
+ expect(templateContent).toContain('Template()')
+ expect(templateContent).toContain('from_image')
+ expect(templateContent).toContain('e2bdev/base')
+ })
+
+ test('should generate correct async Python template content', async () => {
+ execSync(
+ `node "${cliPath}" template init-v2 --name "test-py-async" --language "python-async" --path "${testDir}"`,
+ { stdio: 'inherit' }
+ )
+
+ const templateContent = await fs.readFile(
+ path.join(testDir, 'test-py-async', 'template.py'),
+ 'utf8'
+ )
+
+ // Verify async structure
+ expect(templateContent).toContain('from e2b import AsyncTemplate')
+ expect(templateContent).toContain('AsyncTemplate()')
+ })
+ })
+
+ describe('Directory Conflict Handling', () => {
+ test('should fail when directory already exists', async () => {
+ // Create a directory that would conflict
+ const conflictDir = path.join(testDir, 'test')
+ await fs.mkdir(conflictDir)
+ await fs.writeFile(
+ path.join(conflictDir, 'existing.txt'),
+ 'existing content'
+ )
+
+ // Should fail when trying to create template with existing directory name
+ expect(() => {
+ execSync(
+ `node "${cliPath}" template init-v2 --name "test" --language "typescript" --path "${testDir}"`,
+ { stdio: 'pipe' }
+ )
+ }).toThrow()
+
+ // Verify original directory is preserved and unchanged
+ expect(existsSync(path.join(conflictDir, 'existing.txt'))).toBe(true)
+
+ // Verify no template files were created in the existing directory
+ expect(existsSync(path.join(conflictDir, 'template.ts'))).toBe(false)
+ })
+ })
+})
+
+// Helper functions
+function getExpectedFiles(language: Language): string[] {
+ const extension = language === Language.TypeScript ? '.ts' : '.py'
+ const buildDevName =
+ language === Language.TypeScript ? 'build.dev' : 'build_dev'
+ const buildProdName =
+ language === Language.TypeScript ? 'build.prod' : 'build_prod'
+
+ return [
+ `template${extension}`,
+ `${buildDevName}${extension}`,
+ `${buildProdName}${extension}`,
+ ]
+}
+
+async function verifyTemplateNameInBuildFiles(
+ testDir: string,
+ language: Language,
+ templateName: string
+): Promise<void> {
+ const extension = language === Language.TypeScript ? '.ts' : '.py'
+ const buildDevName =
+ language === Language.TypeScript ? 'build.dev' : 'build_dev'
+ const buildProdName =
+ language === Language.TypeScript ? 'build.prod' : 'build_prod'
+
+ // Check dev build file contains template name with -dev suffix
+ const devContent = await fs.readFile(
+ path.join(testDir, `${buildDevName}${extension}`),
+ 'utf8'
+ )
+ expect(devContent).toContain(`${templateName}-dev`)
+
+ // Check prod build file contains template name
+ const prodContent = await fs.readFile(
+ path.join(testDir, `${buildProdName}${extension}`),
+ 'utf8'
+ )
+ expect(prodContent).toContain(templateName)
+ expect(prodContent).not.toContain(`${templateName}-dev`) // should not have -dev suffix
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 60689f7f3..256007d21 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -247,6 +247,9 @@ importers:
'@inquirer/prompts':
specifier: ^5.5.0
version: 5.5.0
+ '@npmcli/package-json':
+ specifier: ^5.2.1
+ version: 5.2.1
async-listen:
specifier: ^3.0.1
version: 3.0.1
@@ -311,6 +314,9 @@ importers:
'@types/node':
specifier: ^18.18.6
version: 18.18.6
+ '@types/npmcli__package-json':
+ specifier: ^4.0.4
+ version: 4.0.4
'@types/statuses':
specifier: ^2.0.5
version: 2.0.5
@@ -1299,6 +1305,10 @@ packages:
resolution: {integrity: sha512-9hwoB3gStVfa0N31ymBmrX+GuDGdVA/QWShZVqE0HK2Af+7QGGrCTbZia/SW0ImUTjTne7SP91qxDmtXvDHRPQ==}
engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0}
+ '@npmcli/[email protected]':
+ resolution: {integrity: sha512-liASfw5cqhjNW9UFd+ruwwdEf/lbOAQjLL2XY2dFW/bkJheXDYZgOyul/4gVvEV4BWkTXjYGmDqMw9uegdbJNQ==}
+ engines: {node: ^16.14.0 || >=18.0.0}
+
'@npmcli/[email protected]':
resolution: {integrity: sha512-xACzLPhnfD51GKvTOOuNX2/V4G4mz9/1I2MfDoye9kBM3RYe5g2YbscsaGoTlaWqkxeiapBWyseULVKpSVHtKQ==}
engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0}
@@ -1308,10 +1318,18 @@ packages:
resolution: {integrity: sha512-gp8pRXC2oOxu0DUE1/M3bYtb1b3/DbJ5aM113+XJBgfXdussRAsX0YOrOhdd8WvnAR6auDBvJomGAkLKA5ydxA==}
engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0}
+ '@npmcli/[email protected]':
+ resolution: {integrity: sha512-f7zYC6kQautXHvNbLEWgD/uGu1+xCn9izgqBfgItWSx22U0ZDekxN08A1vM8cTxj/cRVe0Q94Ode+tdoYmIOOQ==}
+ engines: {node: ^16.14.0 || >=18.0.0}
+
'@npmcli/[email protected]':
resolution: {integrity: sha512-gGq0NJkIGSwdbUt4yhdF8ZrmkGKVz9vAdVzpOfnom+V8PLSmSOVhZwbNvZZS1EYcJN5hzzKBxmmVVAInM6HQLg==}
engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0}
+ '@npmcli/[email protected]':
+ resolution: {integrity: sha512-xhfYPXoV5Dy4UkY0D+v2KkwvnDfiA/8Mt3sWCGI/hM03NsYIH8ZaG6QzS9x7pje5vHZBZJ2v6VRFVTWACnqcmQ==}
+ engines: {node: ^16.14.0 || >=18.0.0}
+
'@npmcli/[email protected]':
resolution: {integrity: sha512-NCcr1uQo1k5U+SYlnIrbAh3cxy+OQT1VtqiAbxdymSlptbzBb62AjH2xXgjNCoP073hoa1CfCAcwoZ8k96C4nA==}
engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0}
@@ -2742,6 +2760,9 @@ packages:
resolution: {integrity: sha512-gTVM8js2twdtqM+AE2PdGEe9zGQY4UvmFjan9rZcVb6FGdStfjWoWejdmy4CfWVO9rh5MiYQGZloKAGkJt8lMw==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-6QjlFUSHBmZJWuC08bz1ZCx6tm4t+7+OJXAdvM6tL2pI7n6Bh5SIp/YxQvnOLFf8MzCXs2ijyFgrzaiu1UFBGA==}
+
resolution: {integrity: sha512-TaAUE5rq2VQYxab5Ts7WZhKNmuN78Q6PiFonTDdpbx8a1H0M1vhy3rhiMjl+e2iHmogyMw7jZF4FrE6eJUy5HQ==}
@@ -4742,6 +4763,10 @@ packages:
resolution: {integrity: sha512-r0EI+HBMcXadMrugk0GCQ+6BQV39PiWAZVfq7oIckeGiN7sjRGyQxPdft3nQekFTCQbYxLBH+/axZMeH8UX6+w==}
engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0}
+ resolution: {integrity: sha512-puUZAUKT5m8Zzvs72XWy3HtvVbTWljRE66cP60bxJzAqf2DgICo7lYTY2IHUmLnNpjYvw5bvmoHvPc0QO2a62w==}
+ engines: {node: ^16.14.0 || >=18.0.0}
+
resolution: {integrity: sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==}
@@ -4848,6 +4873,10 @@ packages:
resolution: {integrity: sha512-QQnnxNyfvmHFIsj7gkPcYymR8Jdw/o7mp5ZFihxn6h8Ci6fh3Dx4E1gPjpQEpIuPo9XVNY/ZUwh4BPMjGyL01g==}
engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0}
+ resolution: {integrity: sha512-X7rqawQBvfdjS10YU1y1YVreA3SsLrW9dX2CewP2EbBJM4ypVNLDkO5y04gejPwKIY9lR+7r9gn3rFPt/kmWFg==}
+ engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0}
+
resolution: {integrity: sha512-7NXolsK4CAS5+xvdj5OMMbI962hU/wvwoxk+LWR9Ek9bVtyuuYScDN6eS0rUm6TxApFpw7CX1o4uJzcd4AyD3Q==}
@@ -5160,6 +5189,10 @@ packages:
resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==}
+ resolution: {integrity: sha512-LpB/54B+/2J5hqQ7imZHfdU31OlgQqx7ZicVlkm9kzg9/w8GKLEcFfJl/t7DCEDueOyBAD6zCCwTO6Fzs0NoEQ==}
+ engines: {node: '>=16'}
+
resolution: {integrity: sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==}
engines: {node: '>=8'}
@@ -5923,6 +5956,10 @@ packages:
resolution: {integrity: sha512-h9iPVIfrVZ9wVYQnxFgtw1ugSvGEMOlyPWWtm8BMJhnwyEL/FLbYbTY3V3PpjI/BUK67n9PEWDu6eHzu1fB15Q==}
engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0}
+ resolution: {integrity: sha512-V6gygoYb/5EmNI+MEGrWkC+e6+Rr7mTmfHrxDbLzxQogBkgzo76rkok0Am6thgSF7Mv2nLOajAJj5vDJZEFn7g==}
+ engines: {node: ^16.14.0 || >=18.0.0}
+
resolution: {integrity: sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==}
engines: {node: '>=0.10.0'}
@@ -5961,6 +5998,10 @@ packages:
resolution: {integrity: sha512-uFyyCEmgBfZTtrKk/5xDfHp6+MdrqGotX/VoOyEEl3mBwiEE5FlBaePanazJSVMPT7vKepcjYBY2ztg9A3yPIA==}
engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0}
+ resolution: {integrity: sha512-sHGJy8sOC1YraBywpzQlIKBE4pBbGbiF95U6Auspzyem956E0+FtDtsx1ZxlOJkQCZ1AFXAY/yuvtFYrOxF+Bw==}
+ engines: {node: ^16.14.0 || >=18.0.0}
+
resolution: {integrity: sha512-d6RGEuRrNS5/N84iglPivjaJPxhDbZmlbTwTDX2IbcRHG5bZCdtysYMhwiPvcF4GisXHGn7xsxv+GQ7T/02M5Q==}
engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0}
@@ -5969,6 +6010,10 @@ packages:
resolution: {integrity: sha512-1dKY+86/AIiq1tkKVD3l0WI+Gd3vkknVGAggsFeBkTvbhMQ1OND/LKkYv4JtXPKUJ8bOTCyLiqEg2P6QNdK+Gg==}
engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0}
+ resolution: {integrity: sha512-nkc+3pIIhqHVQr085X9d2JzPzLyjzQS96zbruppqC9aZRm/x8xx6xhI98gHtsfELP2bE+loHq8ZaHFHhe+NauA==}
+ engines: {node: ^16.14.0 || >=18.0.0}
+
resolution: {integrity: sha512-kIDMIo4aBm6xg7jOttupWZamsZRkAqMqwqqbVXnUqstY5+tapvv6bkH/qMR76jdgV+YljEUCyWx3hRYMrJiAgA==}
engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0}
@@ -6411,6 +6456,10 @@ packages:
resolution: {integrity: sha512-++Vn7NS4Xf9NacaU9Xq3URUuqZETPsf8L4j5/ckhaRYsfPeRyzGw+iDjFhV/Jr3uNmTvvddEJFWh5R1gRgUH8A==}
engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0}
+ resolution: {integrity: sha512-g8+OnU/L2v+wyiVK+D5fA34J7EH8jZ8DDlvwhRCMxmMj7UCBvxiO1mGeN+36JXIKF4zevU4kRBd8lVgG9vLelA==}
+ engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0}
+
resolution: {integrity: sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==}
engines: {node: '>=0.4.0'}
@@ -7871,6 +7920,11 @@ packages:
engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0}
hasBin: true
+ resolution: {integrity: sha512-GlaYyEb07DPxYCKhKzplCWBJtvxZcZMrL+4UkrTSJHHPyZU4mYYTv3qaOe77H7EODLSSopAUFAc6W8U4yqvscg==}
+ engines: {node: ^16.13.0 || >=18.0.0}
+ hasBin: true
+
resolution: {integrity: sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==}
engines: {node: '>=8'}
@@ -8270,7 +8324,7 @@ snapshots:
outdent: 0.5.0
prettier: 2.8.8
resolve-from: 5.0.0
- semver: 7.7.1
+ semver: 7.7.2
'@changesets/[email protected]':
dependencies:
@@ -8279,7 +8333,7 @@ snapshots:
'@changesets/should-skip-package': 0.1.1
'@changesets/types': 6.0.0
'@manypkg/get-packages': 1.1.3
- semver: 7.7.1
+ semver: 7.7.2
'@changesets/[email protected]':
dependencies:
@@ -8335,7 +8389,7 @@ snapshots:
'@changesets/types': 6.0.0
'@manypkg/get-packages': 1.1.3
picocolors: 1.1.1
- semver: 7.7.1
+ semver: 7.7.2
'@changesets/[email protected]':
dependencies:
@@ -9085,7 +9139,7 @@ snapshots:
'@npmcli/[email protected]':
dependencies:
- semver: 7.7.1
+ semver: 7.7.2
'@npmcli/[email protected]':
dependencies:
@@ -9095,11 +9149,25 @@ snapshots:
proc-log: 3.0.0
promise-inflight: 1.0.1
promise-retry: 2.0.1
- semver: 7.7.1
+ semver: 7.7.2
which: 3.0.1
transitivePeerDependencies:
- bluebird
+ '@npmcli/[email protected]':
+ dependencies:
+ '@npmcli/promise-spawn': 7.0.2
+ ini: 4.1.3
+ lru-cache: 10.4.3
+ npm-pick-manifest: 9.1.0
+ proc-log: 4.2.0
+ promise-inflight: 1.0.1
+ promise-retry: 2.0.1
+ semver: 7.7.2
+ which: 4.0.0
+ transitivePeerDependencies:
+ - bluebird
+
'@npmcli/[email protected]':
dependencies:
npm-bundled: 3.0.0
@@ -9107,10 +9175,26 @@ snapshots:
'@npmcli/[email protected]': {}
+ '@npmcli/[email protected]':
+ dependencies:
+ '@npmcli/git': 5.0.8
+ glob: 10.4.5
+ hosted-git-info: 7.0.2
+ json-parse-even-better-errors: 3.0.0
+ normalize-package-data: 6.0.2
+ proc-log: 4.2.0
+ semver: 7.7.2
+ transitivePeerDependencies:
+ - bluebird
+
'@npmcli/[email protected]':
dependencies:
which: 3.0.1
+ '@npmcli/[email protected]':
+ dependencies:
+ which: 4.0.0
+
'@npmcli/[email protected]':
dependencies:
'@npmcli/node-gyp': 3.0.0
@@ -10736,6 +10820,8 @@ snapshots:
dependencies:
undici-types: 6.21.0
+ '@types/[email protected]': {}
+
dependencies:
'@types/pg': 8.6.1
@@ -10976,7 +11062,7 @@ snapshots:
debug: 4.4.0([email protected])
globby: 11.1.0
is-glob: 4.0.3
- semver: 7.7.1
+ semver: 7.7.2
ts-api-utils: 1.0.3([email protected])
optionalDependencies:
typescript: 5.5.3
@@ -11036,7 +11122,7 @@ snapshots:
'@typescript-eslint/types': 6.7.2
'@typescript-eslint/typescript-estree': 6.7.2([email protected])
eslint: 8.57.1
- semver: 7.7.1
+ semver: 7.7.2
transitivePeerDependencies:
- supports-color
- typescript
@@ -11659,7 +11745,7 @@ snapshots:
dependencies:
- semver: 7.7.1
+ semver: 7.7.2
dependencies:
@@ -13056,7 +13142,7 @@ snapshots:
dependencies:
- foreground-child: 3.1.1
+ foreground-child: 3.3.1
jackspeak: 3.4.3
minimatch: 9.0.5
minipass: 7.1.2
@@ -13263,6 +13349,10 @@ snapshots:
dependencies:
lru-cache: 7.18.3
+ dependencies:
+ lru-cache: 10.4.3
+
@@ -13360,6 +13450,8 @@ snapshots:
+
@@ -13656,6 +13748,8 @@ snapshots:
+
@@ -14719,7 +14813,7 @@ snapshots:
nopt: 6.0.0
npmlog: 6.0.2
rimraf: 3.0.2
- semver: 7.7.1
+ semver: 7.7.2
tar: 6.2.1
which: 2.0.2
transitivePeerDependencies:
@@ -14746,7 +14840,13 @@ snapshots:
dependencies:
hosted-git-info: 6.1.1
is-core-module: 2.13.0
- semver: 7.7.1
+ semver: 7.7.2
+ validate-npm-package-license: 3.0.4
+
+ dependencies:
+ hosted-git-info: 7.0.2
+ semver: 7.7.2
validate-npm-package-license: 3.0.4
@@ -14838,7 +14938,7 @@ snapshots:
dependencies:
- semver: 7.7.1
+ semver: 7.7.2
@@ -14846,7 +14946,14 @@ snapshots:
dependencies:
hosted-git-info: 6.1.1
proc-log: 3.0.0
- semver: 7.7.1
+ semver: 7.7.2
+ validate-npm-package-name: 5.0.0
+
+ dependencies:
+ hosted-git-info: 7.0.2
+ proc-log: 4.2.0
+ semver: 7.7.2
validate-npm-package-name: 5.0.0
@@ -14858,7 +14965,14 @@ snapshots:
npm-install-checks: 6.3.0
npm-normalize-package-bin: 3.0.1
npm-package-arg: 10.1.0
- semver: 7.7.1
+ semver: 7.7.2
+
+ dependencies:
+ npm-install-checks: 6.3.0
+ npm-normalize-package-bin: 3.0.1
+ npm-package-arg: 11.0.3
+ semver: 7.7.2
dependencies:
@@ -15065,7 +15179,7 @@ snapshots:
got: 12.6.1
registry-auth-token: 5.0.2
registry-url: 6.0.1
- semver: 7.7.1
+ semver: 7.7.2
@@ -15325,6 +15439,8 @@ snapshots:
+
@@ -17124,6 +17240,10 @@ snapshots:
dependencies:
isexe: 2.0.0
+ dependencies:
+ isexe: 3.1.1
+
dependencies:
siginfo: 2.0.0