Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
94 changes: 94 additions & 0 deletions cases/bootstrap/api-documentation.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
id: bootstrap-019
title: "Add API Documentation"
prompt: |
The following Node.js API has no documentation. Add comprehensive API documentation
to help developers understand and use the API.

The documentation should:
- Document all endpoints
- Include request/response examples
- Describe parameters and their types
- Include error codes and their meanings
- Provide usage examples
- Follow API documentation best practices
- Include authentication requirements

Run: npm run build
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Run command npm run build is inappropriate for a documentation exercise.

This exercise asks students to add API documentation (JSDoc, OpenAPI, etc.). The run command should reflect how to verify the documentation or start the server, not build it. Consider something like node api_server.js or a documentation generation command.

🤖 Prompt for AI Agents
In `@cases/bootstrap/api-documentation.yaml` at line 16, The Run command in the
api-documentation exercise currently uses an inappropriate build step ("Run: npm
run build"); update the Run field in cases/bootstrap/api-documentation.yaml to a
command that actually verifies or serves the documentation (for example start
the server with node api_server.js, run a docs generator like npm run docs or
openapi-generator-cli, or a script that launches the documentation preview).
Edit the Run entry so it invokes the verification/preview workflow (e.g. node
api_server.js or the project's docs generation script) instead of a generic
build command to make the exercise runnable for students.


source: bootstrap
category: documentation
language: javascript
difficulty: easy

tags:
- javascript
- documentation
- api-docs
- openapi

files:
- path: api_server.js
content: |
const http = require('http');

const server = http.createServer((req, res) => {
const url = req.url;
const method = req.method;

// GET /api/users - Get all users
if (url === '/api/users' && method === 'GET') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify([
{ id: 1, name: 'Alice', email: 'alice@example.com' },
{ id: 2, name: 'Bob', email: 'bob@example.com' }
]));
}
// POST /api/users - Create a new user
else if (url === '/api/users' && method === 'POST') {
let body = '';
req.on('data', chunk => body += chunk);
req.on('end', () => {
const user = JSON.parse(body);
res.writeHead(201, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ id: 3, ...user }));
});
}
// PUT /api/users/:id - Update a user
else if (url.startsWith('/api/users/') && method === 'PUT') {
const userId = url.split('/')[3];
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ id: parseInt(userId), message: 'User updated' }));
}
// DELETE /api/users/:id - Delete a user
else if (url.startsWith('/api/users/') && method === 'DELETE') {
const userId = url.split('/')[3];
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ id: parseInt(userId), message: 'User deleted' }));
}
// GET /api/posts - Get all posts
else if (url === '/api/posts' && method === 'GET') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify([
{ id: 1, title: 'First Post', content: 'Hello world' },
{ id: 2, title: 'Second Post', content: 'Another post' }
]));
}
// POST /api/posts - Create a new post
else if (url === '/api/posts' && method === 'POST') {
let body = '';
req.on('data', chunk => body += chunk);
req.on('end', () => {
const post = JSON.parse(body);
res.writeHead(201, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ id: 3, ...post }));
});
}
else {
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Not found' }));
}
});

server.listen(3000, () => {
console.log('Server running on port 3000');
});
64 changes: 64 additions & 0 deletions cases/bootstrap/authentication.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
id: bootstrap-018
title: "Implement Proper Authentication Checks"
prompt: |
The following Node.js API endpoints have no authentication or authorization.
Implement proper authentication to secure the API.

The authentication should:
- Implement JWT-based authentication
- Add authentication middleware
- Protect sensitive endpoints
- Handle authentication errors properly
- Support role-based access control
- Use secure password hashing

Run: node auth_test.js

source: bootstrap
category: security
language: javascript
difficulty: medium

tags:
- javascript
- security
- authentication
- authorization

files:
- path: api_server.js
content: |
const http = require('http');

// Simple API server without authentication
const server = http.createServer((req, res) => {
const url = req.url;
const method = req.method;

// Public endpoint
if (url === '/api/public' && method === 'GET') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ message: 'Public data' }));
}
// Protected endpoint - no authentication
else if (url === '/api/users' && method === 'GET') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify([
{ id: 1, name: 'Alice', email: 'alice@example.com' },
{ id: 2, name: 'Bob', email: 'bob@example.com' }
]));
}
// Protected endpoint - no authentication
else if (url === '/api/admin' && method === 'GET') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ message: 'Admin data' }));
}
else {
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Not found' }));
}
});

server.listen(3000, () => {
console.log('Server running on port 3000');
});
68 changes: 68 additions & 0 deletions cases/bootstrap/code-readability.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
id: bootstrap-015
title: "Improve Code Readability"
prompt: |
The following JavaScript code is functional but has poor readability due to
unclear naming, complex logic, and lack of structure.

Improve the code by:
- Renaming variables and functions to be descriptive
- Breaking down complex functions
- Adding comments where needed
- Following naming conventions
- Improving code structure
- Making the code self-documenting

Run: node readability_test.js

source: bootstrap
category: code-quality
language: javascript
difficulty: easy

tags:
- javascript
- code-quality
- readability
- maintainability

files:
- path: data_processor.js
content: |
function c(d, t, m) {
if (d <= 0) return 0;
if (m == 'domestic') {
if (d < 5) return 5;
if (d < 10) return 10;
if (d < 20) return 15;
return 25;
}
if (m == 'international') {
if (t == 'express') {
if (d < 5) return 20;
if (d < 10) return 35;
return 50;
}
if (d < 5) return 15;
if (d < 10) return 25;
return 40;
}
return null;
}

function p(d, u) {
const r = c(d, 'standard', 'international');
if (r === null) return null;
const s = r * 0.1;
const f = s + 2.5;
return f;
}

function s(d, t, m) {
const r = c(d, t, m);
if (r === null) return null;
const s = r * 0.1;
const f = s + 2.5;
return f;
}

module.exports = { c, p, s };
103 changes: 103 additions & 0 deletions cases/bootstrap/component-extraction.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
id: bootstrap-013
title: "Extract Reusable Components from Duplicated Code"
prompt: |
The following JavaScript code has significant code duplication. Extract common
logic into reusable functions or components.

The refactoring should:
- Identify duplicated code patterns
- Extract common logic into reusable functions
- Maintain the same functionality
- Improve code maintainability
- Follow DRY (Don't Repeat Yourself) principle
- Add proper documentation

Run: node component_test.js

source: bootstrap
category: refactoring
language: javascript
difficulty: medium

tags:
- javascript
- refactoring
- code-quality
- dpry

Comment on lines +22 to +27
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Typo in tag: dpry should be dry.

 tags:
   - javascript
   - refactoring
   - code-quality
-  - dpry
+  - dry
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
tags:
- javascript
- refactoring
- code-quality
- dpry
tags:
- javascript
- refactoring
- code-quality
- dry
🤖 Prompt for AI Agents
In `@cases/bootstrap/component-extraction.yaml` around lines 22 - 27, There's a
typo in the YAML tags list: replace the incorrect tag value "dpry" with the
correct "dry" under the tags key so the tags array contains "javascript",
"refactoring", "code-quality", and "dry"; update the entry "dpry" to "dry" in
the tags block to fix the typo.

files:
- path: data_processor.js
content: |
// Duplicated code - same validation logic repeated
function validateEmail1(email) {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
throw new Error('Invalid email format');
}
return true;
}

function validateEmail2(email) {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
throw new Error('Invalid email format');
}
return true;
}

function validateEmail3(email) {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
throw new Error('Invalid email format');
}
return true;
}

// Duplicated code - same formatting logic
function formatName1(firstName, lastName) {
return `${firstName} ${lastName}`.trim();
}

function formatName2(firstName, lastName) {
return `${firstName} ${lastName}`.trim();
}

function formatName3(firstName, lastName) {
return `${firstName} ${lastName}`.trim();
}

// Duplicated code - same error handling
function processUser1(user) {
try {
validateEmail1(user.email);
const formatted = formatName1(user.firstName, user.lastName);
return { ...user, formattedName: formatted };
} catch (err) {
console.error('Error processing user:', err.message);
return null;
}
}

function processUser2(user) {
try {
validateEmail2(user.email);
const formatted = formatName2(user.firstName, user.lastName);
return { ...user, formattedName: formatted };
} catch (err) {
console.error('Error processing user:', err.message);
return null;
}
}

function processUser3(user) {
try {
validateEmail3(user.email);
const formatted = formatName3(user.firstName, user.lastName);
return { ...user, formattedName: formatted };
} catch (err) {
console.error('Error processing user:', err.message);
return null;
}
}

module.exports = { processUser1, processUser2, processUser3 };
63 changes: 63 additions & 0 deletions cases/bootstrap/error-handling.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
id: bootstrap-007
title: "Add Error Handling to Functions"
prompt: |
The following JavaScript functions perform operations without proper error handling.
Add try-catch blocks to handle potential errors gracefully.

The functions should:
- Handle file read errors
- Handle network request failures
- Handle invalid input types
- Return meaningful error messages
- Not crash the application

Run: node error_handling.test.js

source: bootstrap
category: error-handling
language: javascript
difficulty: easy

tags:
- javascript
- error-handling
- robustness

files:
- path: user_service.js
content: |
const fs = require('fs').promises;
const https = require('https');

// Function to read user profile
function getUserProfile(userId) {
const filePath = `/data/users/${userId}.json`;
const data = fs.readFileSync(filePath, 'utf-8');
return JSON.parse(data);
Comment on lines +29 to +36
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

fs.readFileSync is not available on fs.promises.

Line 29 imports require('fs').promises, but line 35 calls fs.readFileSync, which only exists on the base fs module. This will throw TypeError: fs.readFileSync is not a function — an unintentional bug unrelated to the exercise's error-handling goal.

Since the exercise focuses on adding try-catch around synchronous I/O, import the base fs module instead:

Proposed fix
-      const fs = require('fs').promises;
+      const fs = require('fs');
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const fs = require('fs').promises;
const https = require('https');
// Function to read user profile
function getUserProfile(userId) {
const filePath = `/data/users/${userId}.json`;
const data = fs.readFileSync(filePath, 'utf-8');
return JSON.parse(data);
const fs = require('fs');
const https = require('https');
// Function to read user profile
function getUserProfile(userId) {
const filePath = `/data/users/${userId}.json`;
const data = fs.readFileSync(filePath, 'utf-8');
return JSON.parse(data);
🤖 Prompt for AI Agents
In `@cases/bootstrap/error-handling.yaml` around lines 29 - 36, The code imports
fs.promises but calls fs.readFileSync in getUserProfile, causing a TypeError;
replace the import const fs = require('fs').promises; with the base module const
fs = require('fs'); so fs.readFileSync is available (or alternatively switch
getUserProfile to use fs.promises.readFile and make it async), ensuring the
function name getUserProfile and the read call (fs.readFileSync /
fs.promises.readFile) are updated consistently.

}

// Function to fetch user data from external API
function fetchUserData(userId) {
const url = `https://api.example.com/users/${userId}`;
const data = https.get(url, (res) => {
let body = '';
res.on('data', (chunk) => body += chunk);
res.on('end', () => {
return JSON.parse(body);
});
});
return data;
}
Comment on lines +40 to +50
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

fetchUserData is fundamentally broken beyond the error-handling scope.

https.get is callback-based — return data on line 49 returns the ClientRequest object, not the parsed response body. A student adding try-catch alone cannot make this function work correctly; it needs to be restructured as a Promise or use async/await.

For an "easy" difficulty exercise focused on error handling, consider either simplifying this to a synchronous example or explicitly noting in the prompt that the async pattern also needs fixing. Alternatively, bump the difficulty to "medium."

🤖 Prompt for AI Agents
In `@cases/bootstrap/error-handling.yaml` around lines 40 - 50, The fetchUserData
function is incorrect because https.get is callback-based and the current
function returns the ClientRequest instead of the parsed body; wrap the
https.get flow in a Promise (or convert to async/await) inside fetchUserData,
accumulate chunks from res.on('data'), resolve with JSON.parse(body) on
res.on('end'), and reject the Promise on request 'error' or JSON parse errors so
callers can try/catch; update references to fetchUserData and the
https.get/res.on handlers accordingly.


// Function to validate user input
function validateUserInput(input) {
if (typeof input !== 'string') {
throw new Error('Input must be a string');
}
if (input.length === 0) {
throw new Error('Input cannot be empty');
}
return true;
}

module.exports = { getUserProfile, fetchUserData, validateUserInput };
Loading
Loading