mirror of
https://github.com/affaan-m/ECC.git
synced 2026-09-29 04:55:12 +02:00
99 lines
23 KiB
JSON
99 lines
23 KiB
JSON
{
|
|
"sql-injection-query": {
|
|
"src/users.js": "'use strict';\n\nfunction buildFindUserQuery(email) {\n return { text: 'SELECT id, email, name FROM users WHERE email = $1', values: [String(email)] };\n}\n\nfunction buildSearchUsersQuery(nameFragment, limit) {\n if (!Number.isInteger(limit) || limit < 1 || limit > 100) throw new RangeError('limit must be an integer from 1 to 100');\n return {\n text: \"SELECT id, email, name FROM users WHERE name ILIKE '%' || $1 || '%' ORDER BY name LIMIT $2\",\n values: [String(nameFragment), limit],\n };\n}\n\nmodule.exports = { buildFindUserQuery, buildSearchUsersQuery };\n"
|
|
},
|
|
"path-traversal-guard": {
|
|
"src/static.js": "'use strict';\nconst path = require('path');\n\nconst PUBLIC_ROOT = path.resolve(__dirname, '..', 'public');\n\nfunction resolvePublicPath(requestPath, root = PUBLIC_ROOT) {\n let decoded;\n try { decoded = decodeURIComponent(String(requestPath)); } catch { return null; }\n if (decoded.includes('\\0')) return null;\n const base = path.resolve(root);\n const target = path.resolve(base, '.' + path.sep + decoded);\n const rel = path.relative(base, target);\n if (rel === '') return target;\n if (rel.startsWith('..') || path.isAbsolute(rel)) return null;\n return target;\n}\n\nmodule.exports = { resolvePublicPath, PUBLIC_ROOT };\n"
|
|
},
|
|
"escape-comment-html": {
|
|
"src/render.js": "'use strict';\n\nconst MAP = { '&': '&', '<': '<', '>': '>', '\"': '"', \"'\": ''' };\nconst escapeHtml = value => String(value == null ? '' : value).replace(/[&<>\"']/g, ch => MAP[ch]);\n\nfunction safeHref(website) {\n try {\n const url = new URL(String(website));\n return url.protocol === 'http:' || url.protocol === 'https:' ? String(website) : '#';\n } catch { return '#'; }\n}\n\nfunction renderComment({ author, body, website }) {\n return '<li class=\"comment\"><a href=\"' + escapeHtml(safeHref(website)) + '\">' + escapeHtml(author)\n + '</a><p>' + escapeHtml(body) + '</p></li>';\n}\n\nmodule.exports = { renderComment, escapeHtml };\n"
|
|
},
|
|
"list-pagination": {
|
|
"src/listProducts.js": "'use strict';\n\nfunction parseIntParam(raw, fallback, min, max) {\n if (raw === undefined || raw === '') return { value: fallback };\n if (!/^\\d+$/.test(String(raw))) return { error: 'must be an integer' };\n const value = Number(raw);\n if (value < min || value > max) return { error: 'must be between ' + min + ' and ' + max };\n return { value };\n}\n\nfunction listProducts(query, store) {\n const limit = parseIntParam(query.limit, 20, 1, 100);\n const offset = parseIntParam(query.offset, 0, 0, Number.MAX_SAFE_INTEGER);\n const details = [];\n if (limit.error) details.push({ field: 'limit', message: 'limit ' + limit.error });\n if (offset.error) details.push({ field: 'offset', message: 'offset ' + offset.error });\n if (details.length) {\n return { status: 400, body: { error: { code: 'VALIDATION_ERROR', message: 'Invalid query parameters', details } } };\n }\n const items = store.all();\n const data = items.slice(offset.value, offset.value + limit.value);\n return { status: 200, body: { data, meta: { total: items.length, limit: limit.value, offset: offset.value,\n hasMore: offset.value + data.length < items.length } } };\n}\n\nmodule.exports = { listProducts };\n"
|
|
},
|
|
"create-user-status-codes": {
|
|
"src/usersRoute.js": "'use strict';\n\nconst error = (status, code, message, details) => ({ status,\n body: { error: { code, message, ...(details ? { details } : {}) } } });\n\nasync function createUser(req, repo) {\n const { email, name } = req.body || {};\n const details = [];\n if (typeof email !== 'string' || !email.includes('@')) details.push({ field: 'email', message: 'email must be a valid address' });\n if (typeof name !== 'string' || !name.trim()) details.push({ field: 'name', message: 'name is required' });\n if (details.length) return error(400, 'VALIDATION_ERROR', 'Invalid request body', details);\n if (await repo.findByEmail(email)) return error(409, 'CONFLICT', 'Email already registered');\n const user = await repo.create({ email, name });\n return { status: 201, headers: { Location: '/users/' + user.id }, body: { data: user } };\n}\n\nasync function getUser(req, repo) {\n const user = await repo.findById(req.params.id);\n if (!user) return error(404, 'NOT_FOUND', 'User not found');\n return { status: 200, body: { data: user } };\n}\n\nmodule.exports = { createUser, getUser };\n"
|
|
},
|
|
"retry-with-backoff": {
|
|
"src/retry.js": "'use strict';\n\nconst defaultSleep = ms => new Promise(resolve => setTimeout(resolve, ms));\nconst isRetryable = err => Boolean(err) && (err.retryable === true || err.status === 429\n || (typeof err.status === 'number' && err.status >= 500));\n\nasync function withRetry(fn, options = {}) {\n const { retries = 3, baseDelayMs = 100, maxDelayMs = 2000, sleep = defaultSleep } = options;\n for (let attempt = 1; ; attempt++) {\n try {\n return await fn(attempt);\n } catch (err) {\n if (!isRetryable(err) || attempt > retries) throw err;\n await sleep(Math.min(baseDelayMs * 2 ** (attempt - 1), maxDelayMs));\n }\n }\n}\n\nmodule.exports = { withRetry, isRetryable };\n"
|
|
},
|
|
"typed-config-errors": {
|
|
"src/config.js": "'use strict';\n\nclass ConfigError extends Error {\n constructor(code, message, options = {}) {\n super(message, options.cause ? { cause: options.cause } : undefined);\n this.name = 'ConfigError';\n this.code = code;\n if (options.field) this.field = options.field;\n }\n}\n\nfunction loadConfig(text) {\n let raw;\n try {\n raw = JSON.parse(text);\n } catch (cause) {\n throw new ConfigError('CONFIG_PARSE', 'Config is not valid JSON: ' + cause.message, { cause });\n }\n if (!raw || typeof raw !== 'object') throw new ConfigError('CONFIG_INVALID', 'Config must be a JSON object');\n for (const field of ['apiUrl', 'timeoutMs']) {\n if (raw[field] === undefined) throw new ConfigError('CONFIG_MISSING', 'Missing required field: ' + field, { field });\n }\n if (!Number.isInteger(raw.timeoutMs) || raw.timeoutMs <= 0) {\n throw new ConfigError('CONFIG_INVALID', 'timeoutMs must be a positive integer', { field: 'timeoutMs' });\n }\n return { apiUrl: raw.apiUrl, timeoutMs: raw.timeoutMs, retries: raw.retries === undefined ? 2 : raw.retries };\n}\n\nmodule.exports = { loadConfig, ConfigError };\n"
|
|
},
|
|
"batch-partial-failures": {
|
|
"src/batch.js": "'use strict';\n\nasync function processAll(items, worker) {\n const settled = await Promise.allSettled(items.map(item => Promise.resolve().then(() => worker(item))));\n const succeeded = [];\n const failed = [];\n settled.forEach((outcome, i) => {\n const id = items[i].id;\n if (outcome.status === 'fulfilled') succeeded.push({ id, result: outcome.value });\n else failed.push({ id, error: outcome.reason instanceof Error ? outcome.reason.message : String(outcome.reason) });\n });\n return { succeeded, failed };\n}\n\nmodule.exports = { processAll };\n"
|
|
},
|
|
"access-log-parser": {
|
|
"src/parseLog.js": "'use strict';\n\nconst LINE = /^(\\S+) \\S+ (\\S+) \\[([^\\]]+)\\] \"([A-Z]+) (\\S+) (HTTP\\/[0-9.]+)\" (\\d{3}) (\\d+|-)(?: \"([^\"]*)\" \"([^\"]*)\")?$/;\nconst dash = value => (value === undefined || value === '-' ? null : value);\n\nfunction parseLine(line) {\n const m = LINE.exec(line);\n if (!m) return null;\n return { ip: m[1], user: dash(m[2]), time: m[3], method: m[4], path: m[5], protocol: m[6],\n status: Number(m[7]), bytes: m[8] === '-' ? 0 : Number(m[8]), referrer: dash(m[9]), userAgent: dash(m[10]) };\n}\n\nfunction parseLog(text) {\n const entries = [];\n let invalid = 0;\n for (const line of String(text).split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n const entry = parseLine(line);\n if (entry) entries.push(entry); else invalid++;\n }\n return { entries, invalid };\n}\n\nmodule.exports = { parseLine, parseLog };\n"
|
|
},
|
|
"invoice-field-extraction": {
|
|
"src/extract.js": "'use strict';\n\nconst MONTHS = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september',\n 'october', 'november', 'december'];\nconst pad = n => String(n).padStart(2, '0');\n\nfunction parseDate(value) {\n let m = /^(\\d{4})-(\\d{2})-(\\d{2})\\b/.exec(value);\n if (m) return m[1] + '-' + m[2] + '-' + m[3];\n m = /^(\\d{1,2})\\/(\\d{1,2})\\/(\\d{4})\\b/.exec(value);\n if (m) return m[3] + '-' + pad(m[2]) + '-' + pad(m[1]);\n m = /^(\\d{1,2})\\s+([A-Za-z]+)\\s+(\\d{4})\\b/.exec(value);\n if (m && MONTHS.includes(m[2].toLowerCase())) return m[3] + '-' + pad(MONTHS.indexOf(m[2].toLowerCase()) + 1) + '-' + pad(m[1]);\n return null;\n}\n\nfunction parseAmount(value) {\n const m = /^(?:(\\$)|([A-Z]{3})\\s+)?([\\d,]+(?:\\.\\d+)?)(?:\\s+([A-Z]{3}))?\\s*$/.exec(value.trim());\n if (!m) return null;\n const currency = m[1] ? 'USD' : m[2] || m[4] || null;\n return { total: Number(m[3].replace(/,/g, '')), currency };\n}\n\nfunction extractInvoice(text) {\n const out = { invoiceNumber: null, date: null, total: null, currency: null };\n for (const line of String(text).split(/\\r?\\n/)) {\n let m;\n if (!out.invoiceNumber && (m = /^\\s*invoice\\s*(?:#|no\\.?|number)\\s*:?\\s*([A-Za-z0-9-]+)\\s*$/i.exec(line))) out.invoiceNumber = m[1];\n else if (!out.date && (m = /^\\s*(?:invoice\\s+date|date|issued)\\s*:\\s*(.+)$/i.exec(line))) out.date = parseDate(m[1].trim());\n else if (out.total === null && (m = /^\\s*(?:total(?:\\s+due)?|amount\\s+due)\\s*:\\s*(.+)$/i.exec(line))) {\n const amount = parseAmount(m[1]);\n if (amount) { out.total = amount.total; out.currency = amount.currency; }\n }\n }\n return out;\n}\n\nmodule.exports = { extractInvoice };\n"
|
|
},
|
|
"add-column-migration": {
|
|
"migrations/002_users_email_verified.up.sql": "-- PG 11+: adding a column with a constant default is metadata-only.\nALTER TABLE users ADD COLUMN email_verified boolean NOT NULL DEFAULT false;\n\n-- Build without blocking writes; cannot run inside a transaction.\nCREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS users_email_lower_key ON users (lower(email));\n",
|
|
"migrations/002_users_email_verified.down.sql": "DROP INDEX CONCURRENTLY IF EXISTS users_email_lower_key;\nALTER TABLE users DROP COLUMN IF EXISTS email_verified;\n"
|
|
},
|
|
"rename-column-expand": {
|
|
"migrations/002_add_display_name.up.sql": "ALTER TABLE customers ADD COLUMN display_name text;\nUPDATE customers SET display_name = full_name WHERE display_name IS NULL;\n",
|
|
"migrations/002_add_display_name.down.sql": "ALTER TABLE customers DROP COLUMN display_name;\n",
|
|
"src/customerRepo.js": "'use strict';\n\nfunction buildInsert(customer) {\n return { text: 'INSERT INTO customers (email, full_name, display_name) VALUES ($1, $2, $2) RETURNING id',\n values: [customer.email, customer.name] };\n}\n\nfunction buildUpdateName(id, name) {\n return { text: 'UPDATE customers SET full_name = $1, display_name = $1 WHERE id = $2', values: [name, id] };\n}\n\nfunction mapRow(row) {\n return { id: row.id, email: row.email, name: row.display_name != null ? row.display_name : row.full_name };\n}\n\nmodule.exports = { buildInsert, buildUpdateName, mapRow };\n"
|
|
},
|
|
"keyset-feed-query": {
|
|
"src/feedQuery.js": "'use strict';\n\nconst COLUMNS = 'SELECT id, user_id, body, created_at FROM posts';\n\nfunction encodeCursor(row) {\n return Buffer.from(JSON.stringify({ c: row.created_at, i: row.id })).toString('base64url');\n}\n\nfunction decodeCursor(cursor) {\n let value;\n try { value = JSON.parse(Buffer.from(String(cursor), 'base64url').toString('utf8')); } catch { value = null; }\n if (!value || typeof value.c !== 'string' || Number.isNaN(Date.parse(value.c))\n || !(Number.isSafeInteger(value.i) || /^\\d+$/.test(String(value.i)))) throw new Error('Malformed cursor');\n return value;\n}\n\nfunction buildFeedQuery({ userId, limit, cursor }) {\n if (!Number.isInteger(limit) || limit < 1 || limit > 50) throw new RangeError('limit must be an integer 1..50');\n if (cursor === undefined || cursor === null) {\n return { text: COLUMNS + ' WHERE user_id = $1 ORDER BY created_at DESC, id DESC LIMIT $2', values: [userId, limit] };\n }\n const { c, i } = decodeCursor(cursor);\n return { text: COLUMNS + ' WHERE user_id = $1 AND (created_at, id) < ($2, $3) ORDER BY created_at DESC, id DESC LIMIT $4',\n values: [userId, c, i, limit] };\n}\n\nmodule.exports = { buildFeedQuery, encodeCursor };\n",
|
|
"migrations/002_posts_feed_index.sql": "CREATE INDEX CONCURRENTLY IF NOT EXISTS posts_user_feed_idx ON posts (user_id, created_at DESC, id DESC);\n"
|
|
},
|
|
"upsert-inventory-sql": {
|
|
"src/inventory.js": "'use strict';\n\nasync function syncStock(db, items) {\n const latest = new Map();\n for (const item of items) { latest.delete(item.sku); latest.set(item.sku, item.quantity); }\n if (latest.size === 0) return 0;\n const values = [];\n const rows = [];\n for (const [sku, quantity] of latest) {\n values.push(sku, quantity);\n rows.push('($' + (values.length - 1) + ', $' + values.length + ', now())');\n }\n await db.query('INSERT INTO inventory (sku, quantity, updated_at) VALUES ' + rows.join(', ')\n + ' ON CONFLICT (sku) DO UPDATE SET quantity = EXCLUDED.quantity, updated_at = now()', values);\n return latest.size;\n}\n\nmodule.exports = { syncStock };\n"
|
|
},
|
|
"slugify-regression-tests": {
|
|
"src/slugify.js": "'use strict';\n\nfunction slugify(input) {\n return String(input)\n .normalize('NFKD')\n .replace(/[\\u0300-\\u036f]/g, '')\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '');\n}\n\nmodule.exports = { slugify };\n",
|
|
"test/slugify.test.js": "'use strict';\nconst test = require('node:test');\nconst assert = require('node:assert/strict');\nconst { slugify } = require('../src/slugify');\n\ntest('trims leading and trailing separators', () => {\n assert.equal(slugify(' Hello, World! '), 'hello-world');\n});\n\ntest('strips accents', () => {\n assert.equal(slugify('Cr\\u00e8me Br\\u00fbl\\u00e9e'), 'creme-brulee');\n});\n\ntest('collapses repeated separators and handles empty input', () => {\n assert.equal(slugify('a--b__c'), 'a-b-c');\n assert.equal(slugify(''), '');\n assert.equal(slugify(' -- '), '');\n});\n"
|
|
},
|
|
"content-hash-cache": {
|
|
"src/extractor.js": "'use strict';\nconst crypto = require('node:crypto');\n\nconst cacheKeyFor = buffer => crypto.createHash('sha256').update(buffer).digest('hex');\n\nfunction createExtractor({ readFile, parse }) {\n const cache = new Map();\n let hits = 0;\n let misses = 0;\n return {\n extract(filePath) {\n const bytes = readFile(filePath);\n const key = cacheKeyFor(bytes);\n if (cache.has(key)) {\n hits++;\n return cache.get(key);\n }\n misses++;\n const result = parse(bytes.toString('utf8'));\n cache.set(key, result);\n return result;\n },\n stats: () => ({ hits, misses }),\n };\n}\n\nmodule.exports = { createExtractor, cacheKeyFor };\n"
|
|
},
|
|
"batch-customer-lookup": {
|
|
"src/orders.js": "'use strict';\n\nasync function getOrdersWithCustomers(repo) {\n const orders = await repo.listOrders();\n if (orders.length === 0) return [];\n const ids = [...new Set(orders.map(order => order.customerId))];\n const customers = await repo.findCustomersByIds(ids);\n const byId = new Map(customers.map(customer => [customer.id, customer]));\n return orders.map(order => ({ ...order, customer: byId.get(order.customerId) || null }));\n}\n\nmodule.exports = { getOrdersWithCustomers };\n"
|
|
},
|
|
"rbac-middleware": {
|
|
"src/auth.js": "'use strict';\n\nconst ROLE_PERMISSIONS = {\n admin: ['read', 'write', 'delete'],\n editor: ['read', 'write'],\n viewer: ['read'],\n};\n\nconst KNOWN = new Set(Object.values(ROLE_PERMISSIONS).flat());\n\nfunction requirePermission(permission) {\n if (!KNOWN.has(permission)) throw new Error('Unknown permission: ' + permission);\n return (req, res, next) => {\n if (!req.user) return res.status(401).json({ error: { code: 'UNAUTHENTICATED', message: 'Authentication required' } });\n const role = req.user.role;\n const granted = typeof role === 'string' && Object.prototype.hasOwnProperty.call(ROLE_PERMISSIONS, role)\n ? ROLE_PERMISSIONS[role] : [];\n if (!granted.includes(permission)) {\n return res.status(403).json({ error: { code: 'FORBIDDEN', message: 'Missing permission: ' + permission } });\n }\n return next();\n };\n}\n\nmodule.exports = { requirePermission, ROLE_PERMISSIONS };\n"
|
|
},
|
|
"immutable-cart-update": {
|
|
"src/cart.js": "'use strict';\n\nfunction addItem(cart, item) {\n const exists = cart.items.some(i => i.sku === item.sku);\n const items = exists\n ? cart.items.map(i => (i.sku === item.sku ? { ...i, quantity: i.quantity + item.quantity } : i))\n : [...cart.items, { ...item }];\n return { ...cart, items };\n}\n\nfunction removeItem(cart, sku) {\n return { ...cart, items: cart.items.filter(i => i.sku !== sku) };\n}\n\nfunction applyDiscount(cart, pct) {\n if (typeof pct !== 'number' || !(pct >= 0 && pct <= 100)) throw new RangeError('pct must be between 0 and 100');\n return { ...cart, discountPct: pct };\n}\n\nfunction total(cart) {\n const sum = cart.items.reduce((acc, i) => acc + i.price * i.quantity, 0);\n return Math.round(sum * (1 - (cart.discountPct || 0) / 100) * 100) / 100;\n}\n\nmodule.exports = { addItem, removeItem, applyDiscount, total };\n"
|
|
},
|
|
"inject-signup-deps": {
|
|
"src/signup.js": "'use strict';\n\nfunction domainError(code, message) {\n return Object.assign(new Error(message), { code });\n}\n\nfunction createSignupService({ userRepository, mailer, clock }) {\n return {\n async signUp({ email, name }) {\n const normalized = String(email || '').trim().toLowerCase();\n if (!normalized.includes('@')) throw domainError('INVALID_EMAIL', 'Email address is invalid');\n if (await userRepository.findByEmail(normalized)) throw domainError('EMAIL_TAKEN', 'Email already registered');\n const user = await userRepository.save({ email: normalized, name, createdAt: clock.now().toISOString() });\n await mailer.sendWelcome({ to: user.email, name: user.name });\n return user;\n },\n };\n}\n\nmodule.exports = { createSignupService };\n",
|
|
"src/main.js": "'use strict';\nconst { createSignupService } = require('./signup');\n\nfunction buildApp() {\n const store = require('./adapters/pgUserStore');\n const smtp = require('./adapters/smtpMailer');\n return createSignupService({\n userRepository: { findByEmail: email => store.findByEmail(email), save: user => store.insert(user) },\n mailer: { sendWelcome: ({ to, name }) => smtp.sendWelcome(to, name) },\n clock: { now: () => new Date() },\n });\n}\n\nmodule.exports = { buildApp };\n"
|
|
},
|
|
"cache-aside-user": {
|
|
"src/userCache.js": "'use strict';\n\nfunction createUserCache({ redis, db, ttlSeconds = 300 }) {\n const key = id => 'user:' + id;\n const quietly = async op => { try { return await op(); } catch { return null; } };\n return {\n async getUser(id) {\n const cached = await quietly(() => redis.get(key(id)));\n if (cached) {\n try { return JSON.parse(cached); } catch { /* fall through to db */ }\n }\n const user = await db.findUser(id);\n if (user) await quietly(() => redis.set(key(id), JSON.stringify(user), { EX: ttlSeconds }));\n return user || null;\n },\n async updateUser(id, patch) {\n const updated = await db.updateUser(id, patch);\n await quietly(() => redis.del(key(id)));\n return updated;\n },\n };\n}\n\nmodule.exports = { createUserCache };\n"
|
|
},
|
|
"token-units-bigint": {
|
|
"src/units.js": "'use strict';\n\nconst assertDecimals = d => { if (!Number.isInteger(d) || d < 0 || d > 255) throw new RangeError('decimals must be 0..255'); };\n\nfunction formatUnits(raw, decimals) {\n assertDecimals(decimals);\n let value = BigInt(raw);\n const negative = value < 0n;\n if (negative) value = -value;\n const base = 10n ** BigInt(decimals);\n const whole = value / base;\n const fraction = (value % base).toString().padStart(decimals, '0').replace(/0+$/, '');\n return (negative ? '-' : '') + whole.toString() + (fraction ? '.' + fraction : '');\n}\n\nfunction parseUnits(value, decimals) {\n assertDecimals(decimals);\n const m = /^(-)?(\\d+)(?:\\.(\\d+))?$/.exec(String(value));\n if (!m) throw new Error('Invalid decimal amount: ' + value);\n const fraction = m[3] || '';\n if (fraction.length > decimals) throw new RangeError('Too many fractional digits for ' + decimals + ' decimals');\n const units = BigInt(m[2] + fraction.padEnd(decimals, '0'));\n return m[1] ? -units : units;\n}\n\nfunction normalizeAmount(raw, fromDecimals, toDecimals) {\n assertDecimals(fromDecimals);\n assertDecimals(toDecimals);\n const value = BigInt(raw);\n if (toDecimals >= fromDecimals) return value * 10n ** BigInt(toDecimals - fromDecimals);\n return value / 10n ** BigInt(fromDecimals - toDecimals);\n}\n\nmodule.exports = { formatUnits, parseUnits, normalizeAmount };\n"
|
|
},
|
|
"inclusive-range": {
|
|
"src/range.js": "'use strict';\n\n/** Returns the integers from start to end, inclusive. */\nfunction range(start, end) {\n const out = [];\n for (let i = start; i <= end; i++) out.push(i);\n return out;\n}\n\nmodule.exports = { range };\n"
|
|
},
|
|
"export-name-typo": {
|
|
"src/dates.js": "'use strict';\n\nfunction formatDate(date) {\n const pad = n => String(n).padStart(2, '0');\n return date.getUTCFullYear() + '-' + pad(date.getUTCMonth() + 1) + '-' + pad(date.getUTCDate());\n}\n\nmodule.exports = { formatDate, fromatDate: formatDate };\n"
|
|
},
|
|
"default-greeting": {
|
|
"src/greet.js": "'use strict';\n\nfunction greet(name) {\n const trimmed = name == null ? '' : String(name).trim();\n return 'Hello, ' + (trimmed || 'world') + '!';\n}\n\nmodule.exports = { greet };\n"
|
|
},
|
|
"sum-form-values": {
|
|
"src/total.js": "'use strict';\n\nfunction total(values) {\n return values.reduce((sum, v) => sum + (v === '' ? 0 : Number(v)), 0);\n}\n\nmodule.exports = { total };\n"
|
|
},
|
|
"changelog-capitalize": {
|
|
"src/changelog.js": "'use strict';\n\nfunction capitalize(text) {\n return text ? text[0].toUpperCase() + text.slice(1) : '';\n}\n\nfunction formatEntry(entry) {\n return '- ' + capitalize(entry.title) + ' (' + entry.type + ')';\n}\n\nmodule.exports = { capitalize, formatEntry };\n"
|
|
},
|
|
"test-summary-plural": {
|
|
"src/summary.js": "'use strict';\n\nconst noun = n => (n === 1 ? 'test' : 'tests');\n\nfunction formatSummary(passed, failed) {\n return passed + ' ' + noun(passed) + ' passed, ' + failed + ' ' + noun(failed) + ' failed';\n}\n\nmodule.exports = { formatSummary };\n"
|
|
},
|
|
"database-label-typo": {
|
|
"src/options.js": "'use strict';\n\nconst OPTIONS = [\n { value: 'database', label: 'Database' },\n { value: 'api', label: 'API' },\n { value: 'cache', label: 'Cache' },\n];\n\nfunction labelFor(value) {\n const option = OPTIONS.find(o => o.value === value);\n return option ? option.label : value;\n}\n\nmodule.exports = { OPTIONS, labelFor };\n"
|
|
},
|
|
"port-from-env": {
|
|
"src/server-config.js": "'use strict';\n\nfunction getPort(env = process.env) {\n const raw = env.PORT;\n if (typeof raw !== 'string' || !/^\\d+$/.test(raw)) return 3000;\n const port = Number(raw);\n return port >= 1 && port <= 65535 ? port : 3000;\n}\n\nmodule.exports = { getPort };\n"
|
|
}
|
|
}
|