Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
0bca8b6
fix(functions): load .env before bundling and importing functions
Harshi-Shah-CS Nov 18, 2026
0ce7259
fix(functions): parse the Cookie header into request.cookies
Harshi-Shah-CS Nov 18, 2026
a36c659
refactor(functions): name the cookie middleware
Harshi-Shah-CS Nov 18, 2026
cd978d7
fix(functions): give request.cookies an empty object with no Cookie h…
Harshi-Shah-CS Nov 18, 2026
9b8a08f
fix(functions): hand a text/plain body to the handler as the raw string
Harshi-Shah-CS Nov 18, 2026
6ae81f0
refactor(test): take sendRequest's method, headers and body as options
Harshi-Shah-CS Nov 18, 2026
fe55a28
fix(functions): hand an application/octet-stream body to the handler …
Harshi-Shah-CS Nov 18, 2026
1bd68c0
test(functions): pin JSON and urlencoded bodies reaching the handler …
Harshi-Shah-CS Nov 18, 2026
dd8f063
refactor(functions): register request middleware once, not once per f…
Harshi-Shah-CS Nov 18, 2026
05b0723
feat(functions): warn when a function imports a file outside functions/
Harshi-Shah-CS Nov 18, 2026
d76f874
fix(functions): do not warn about packages imported from node_modules
Harshi-Shah-CS Nov 18, 2026
165c29a
fix(functions): print the port the server listens on, not the one req…
Harshi-Shah-CS Nov 18, 2026
61d6434
fix(functions): accept text and octet-stream bodies up to Lambda's 6m…
Harshi-Shah-CS Nov 19, 2026
857f93c
fix(functions): stop flagging functions subfolders named with two lea…
Harshi-Shah-CS Nov 19, 2026
e70b8a3
fix(functions): warn about imports from another Windows drive
Harshi-Shah-CS Nov 19, 2026
a79b5ca
fix(functions): name the function that reaches an outside file, once
Harshi-Shah-CS Nov 19, 2026
3bfaba9
refactor(functions): report outside imports from one reporter per parse
Harshi-Shah-CS Nov 19, 2026
d2fa5df
fix(functions): send cache-control no-store on body parser errors too
Harshi-Shah-CS Nov 19, 2026
df1dae2
fix(functions): accept JSON and urlencoded bodies up to Lambda's 6mb cap
Harshi-Shah-CS Nov 19, 2026
842bd0d
fix(functions): accept only decimal digits as a port
Harshi-Shah-CS Nov 19, 2026
9cccb42
fix(functions): print the invalid port error to stderr, coloured only…
Harshi-Shah-CS Nov 19, 2026
66e78f7
fix(functions): print a missing --data-dir error to stderr through th…
Harshi-Shah-CS Nov 19, 2026
af8551f
fix(functions): refuse a --data-dir that is a file, naming the path
Harshi-Shah-CS Nov 19, 2026
c5d299c
fix(functions): create logs/ only when something is written to a log …
Harshi-Shah-CS Nov 19, 2026
53add7e
fix(functions): flush the invalid port record to disk before exiting
Harshi-Shah-CS Nov 19, 2026
ce9dad8
docs(agents): record functions:serve's approved differences from V1
Harshi-Shah-CS Nov 19, 2026
2b5bc79
Merge branch 'v2-dev' into CL-8791
Harshi-Shah-CS Nov 19, 2026
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
10 changes: 5 additions & 5 deletions .talismanrc
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ fileignoreconfig:
- filename: src/core/failure.test.ts
checksum: 3f5c731861dc816d141f6314c32bec55bc5197241447a4375bc76fa9f85339f0
- filename: test/integration/retired-commands.test.ts
checksum: c38d6e8dae6bd4d2034ff48bff488e89cc00d950a7417c6df890168ac743ae37
checksum: 84d9c9ddae05faf49e6bd29e2835051714ed53ac35c8a0283c87679f06902b0a
- filename: test/integration/manage-base-path.test.ts
checksum: 79eb9ad420ea47d5bee8045d812c45b010bbeeafcaf5f85d11653140b0cd0db1
- filename: src/transport/rest-client.ts
Expand Down Expand Up @@ -236,7 +236,7 @@ fileignoreconfig:
- "a project name passed on argv to the project resolver"
- "expect\\(Object.keys\\(DEPENDENCIES\\)\\).toEqual\\(\\['project', 'env'\\]\\)"
- filename: AGENTS.md
checksum: c20a023e033c6222c645e94bf9fba4bdf884aa75d6c52f5c74ab185b8c335b01
checksum: 06abd3d96ec675c81fdeb86bbe571bf027d9426da2c8bf10519dc8bd045dbc9d
allowed_patterns:
- "Do not add an exemption to a guard to make a new file pass"
- "passes its own error wording to `client.request\\(req, MESSAGES\\)`"
Expand Down Expand Up @@ -283,7 +283,7 @@ fileignoreconfig:
- filename: test/integration/projects-list-command.test.ts
checksum: 5f49dc7f384fb9e33c8fb91f1c67b17ffc2fd3bbde3663f90f820056407e98a0
- filename: src/functions/cloud-functions.test.ts
checksum: 5faf7b0497efc9f620983220019736a0ec2e8c43f22316f888201912bbcb5d62
checksum: 2b7d29ca3a8b87bc27e464d00517eb390d70b901ad892c0680bf613cb466920c
- filename: src/transport/proxy.test.ts
checksum: 06db291bb40ec55774179b02e3e1a9644bbaa116ec511c163e8d6012aebb3868
- filename: test/integration/project-upload-proxy.test.ts
Expand All @@ -301,7 +301,7 @@ fileignoreconfig:
- filename: src/transport/auth-strategy.ts
checksum: 6fe87def1b508cb67203d4445d9bd889570e512ed4194dfc4fdd3182bc8b87b2
- filename: src/functions/function.logger.test.ts
checksum: 840b2b2b7f938e0862881871e8d568112631c58e12cf6c8a5be32e7552b8cf9e
checksum: e088ab5844cf4214d03f9c0f0a903b21ec7167e6879fc484d647e46b96f7a100
- filename: src/transport/cma-client.test.ts
checksum: 85d62ef350b450cb09f1a840db79bdfb212d4f5fd650789d60d722915a892a59
- filename: src/core/search-list.test.ts
Expand Down Expand Up @@ -487,7 +487,7 @@ fileignoreconfig:
- filename: src/commands/launch/secrets/list.test.ts
checksum: 109d1165d7ce16943b50955f60fd8a753a870115fdf5501fb2a5e4a1cf436eaa
- filename: package.json
checksum: ae6f7fdb23fd9476dd4fca5b84d0f3999b578a73b8187af2f94edbb0a2172b16
checksum: aa850fff4d587e974f73c1fd734c6798feed147f0dce449b33930ef7190b370c
- filename: test/integration/secrets-set.test.ts
checksum: 2527d5d35198cc08e1859ab79941338392b6d4fcbc87506adef6d7b096089963
- filename: src/secrets/secret.rules.test.ts
Expand Down
50 changes: 34 additions & 16 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -500,27 +500,45 @@ promoting these to `src/core/catalog.ts` now.

`launch:functions:serve` is deliberately a plain oclif `Command` rather than a
`LaunchCommand`, because it talks to no API and needs no auth gate, and it is **outside**
this contract on purpose: the product owner's instruction is no functional difference from
V1 in `serve`. Its port handling is V1's, byte for byte:
this contract on purpose. It started as V1 byte for byte, on the product owner's instruction;
CL-8791 (V2 bug bash) then made it match deployed cloud functions and V2's error output. These
parts are still V1's and must stay so:

- The port is `process.env.PORT || flags.port`, applied by the command after parsing. A set
`PORT` beats an explicit `--port`, and an empty `PORT` falls through to the flag. The
`--port` flag therefore does **not** declare `env: 'PORT'` - oclif's precedence (argv
first) is the opposite of V1's, and restoring it would be a behaviour change.
- An invalid port prints `Invalid port number. Please provide a valid port number between 0
and 65535.` **once**, through the restored V1 logger (`src/functions/function.logger.ts`),
which writes every level - `error` included - to **stdout**, as winston's `Console`
transport does without `stderrLevels`, and records it in `logs/error.log`. The command
then calls `this.exit(EXIT_RUNTIME)`: exit **1**, and nothing on stderr. Do not add a
`this.error(...)` after the log line - that was a second print and an exit 2.

Three V1 defects stay fixed and are the only approved differences: an empty or whitespace
port, from either `--port` or `PORT`, is rejected through that same one-message exit-1 path
(V1 accepted it because `Number('') === 0` and served on a random port); a busy port raises
`PortInUseError` and exits 2 with a clean message (V1 crashed on an unhandled `error`
event); and filepath validation is linear-time (V1's regex took 41 seconds on a plausible
40-character filename). `test/integration/functions-serve-port.test.ts` pins the port
precedence and the single message end to end.
- An invalid port exits **1** (`bf9a139`), not the usage code 2.

The approved differences from V1 are these, and only these:

- **Errors go to stderr.** An invalid port is recorded in `logs/error.log`, and the command
awaits `logger.flush()` so the record is on disk before the process exits. It then calls
`this.error(message, { exit: EXIT_RUNTIME })`, so `Invalid port number. Please provide a
valid port number between 0 and 65535.` prints **once** on stderr through the shared failure
path, coloured only on a TTY. The project error logger (`src/functions/function.logger.ts`)
writes only to the file and has no `Console` transport. A `--data-dir` that does not exist,
or that is a file, fails the same way before the logger is built.
- **A port is decimal digits only**, 0-65535. Hex, exponent, signed, space-padded, empty and
whitespace values are rejected through that same exit-1 path. V1 read `0x10` as 16 and
accepted `''` as 0, a random port.
- **`logs/` appears only when something is written to it.** V1 created it, empty, on every
run.
- **Requests match AWS deployed functions** (`lambda-node-bridge/cf-sv-with-helpers.ts` in
`contentfly-deployment-agent`), as agreed with CL-8791's reporter. JSON and urlencoded
bodies are parsed, `text/plain` arrives as the raw string, `application/octet-stream` as a
Buffer, all up to Lambda's 6mb cap. `request.cookies` is the parsed `Cookie` header, or `{}`.
The project `.env` is loaded before the functions are bundled. Azure and GCP still run the
vendored V1 server, which leaves text and octet-stream bodies unparsed; locally a handler
that reads the raw request stream for those two types gets an empty stream.
- **A function that reaches a file outside `functions/` is warned about, not refused**, naming
the function file that crosses the boundary.
- **A busy port** raises `PortInUseError` and exits 2 with a clean message (V1 crashed on an
unhandled `error` event), and **filepath validation is linear-time** (V1's regex took 41
seconds on a plausible 40-character filename).

`test/integration/functions-serve-port.test.ts` pins the port precedence and the single stderr
message end to end.

A declined confirmation is a deliberate "no", not a failure, so it does not share code 1 with an
API 500 - a CI log has to be able to tell those apart. 130 would claim the process was killed by
Expand Down
11 changes: 11 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
"@rollup/plugin-json": "^6.1.0",
"@rollup/plugin-node-resolve": "^16.0.3",
"adm-zip": "^0.6.1",
"cookie": "^0.7.2",
"dotenv": "^16.4.7",
"express": "^4.22.3",
"https-proxy-agent": "^5.0.1",
Expand All @@ -39,6 +40,7 @@
"devDependencies": {
"@eslint/js": "^9.39.5",
"@oclif/test": "^4.2.0",
"@types/cookie": "^0.6.0",
"@types/express": "^4.17.25",
"@types/express-serve-static-core": "^4.19.9",
"@types/jest": "^29.5.14",
Expand Down
66 changes: 33 additions & 33 deletions src/commands/launch/functions/serve.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { cliux } from '@contentstack/cli-utilities';
import { Errors, Parser } from '@oclif/core';
import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync } from 'node:fs';
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';

Expand Down Expand Up @@ -28,11 +28,6 @@ function temporaryDirectory(): string {
return dir;
}

function logFiles(dir: string): string[] {
const logs = join(dir, 'logs');
return existsSync(logs) ? readdirSync(logs).sort() : [];
}

function readLog(dir: string, name: string): string {
const path = join(dir, 'logs', name);
return existsSync(path) ? readFileSync(path, 'utf8') : '';
Expand Down Expand Up @@ -85,7 +80,7 @@ beforeEach(() => {
afterEach(async () => {
for (const dir of temporaryDirectories.splice(0)) {
if (existsSync(join(dir, 'logs'))) {
await eventually(() => logFiles(dir).length === 2);
await eventually(() => readLog(dir, 'error.log') !== '');
}

rmSync(dir, { recursive: true, force: true });
Expand Down Expand Up @@ -122,18 +117,15 @@ describe('launch:functions:serve flag definitions', () => {
});

describe('launch:functions:serve init', () => {
it('stores the supplied data directory and port and creates the project log files there', async () => {
it('stores the supplied data directory and port without creating a logs folder there', async () => {
const dataDir = temporaryDirectory();
const command = commandWithFlags({ 'data-dir': dataDir, port: '4000' });

await command.init();

expect(Functions.prototype['parse']).toHaveBeenCalledWith(Functions);
expect(command['sharedConfig']).toEqual({ projectBasePath: dataDir, port: 4000 });
expect(existsSync(join(dataDir, 'logs'))).toBe(true);
await eventually(() => logFiles(dataDir).length === 2);
expect(logFiles(dataDir)).toEqual(['error.log', 'info.log']);
expect(readLog(dataDir, 'error.log')).toBe('');
expect(existsSync(join(dataDir, 'logs'))).toBe(false);
expect(stdout).toEqual([]);
});

Expand All @@ -149,7 +141,6 @@ describe('launch:functions:serve init', () => {
await command.init();

expect(command['sharedConfig']).toEqual({ projectBasePath: workingDirectory, port: 3000 });
expect(existsSync(join(workingDirectory, 'logs'))).toBe(true);
});

it.each(['0', '1', '3000', '65535'])('accepts the boundary port %s', async (port) => {
Expand All @@ -159,46 +150,55 @@ describe('launch:functions:serve init', () => {
await command.init();

expect(command['sharedConfig']).toEqual({ projectBasePath: dataDir, port: Number(port) });
await eventually(() => logFiles(dataDir).length === 2);
expect(readLog(dataDir, 'error.log')).toBe('');
expect(existsSync(join(dataDir, 'logs'))).toBe(false);
expect(stdout).toEqual([]);
});

it.each(['-1', '65536', '3000.5', 'abc', 'NaN', '1e400', '', ' '])(
'rejects the invalid port %p once through the project logger and exits 1 as v1 did',
it.each(['-1', '65536', '3000.5', 'abc', 'NaN', '1e400', '', ' ', '0x10', '1e3', '+3000', ' 3000'])(
'rejects the invalid port %p, with it on disk in error.log before failing with it to stderr, exiting 1',
async (port) => {
const dataDir = temporaryDirectory();
const command = commandWithFlags({ 'data-dir': dataDir, port });

const failure = await command.init().catch((error: Error & { oclif?: { exit?: number } }) => error);

expect(failure).toBeInstanceOf(Errors.ExitError);
expect(failure).toMatchObject({ oclif: { exit: EXIT_RUNTIME } });
expect((failure as Error).message).not.toContain(INVALID_PORT_MESSAGE);
expect(failure).toBeInstanceOf(Errors.CLIError);
expect(failure).toMatchObject({ message: INVALID_PORT_MESSAGE, oclif: { exit: EXIT_RUNTIME } });
expect(command['sharedConfig']).toBeUndefined();
expect(stdout).toEqual([`\u001b[31merror: ${INVALID_PORT_MESSAGE}\u001b[39m\n`]);
await eventually(() => readLog(dataDir, 'error.log') !== '');
expect(stdout).toEqual([]);
expect(readLog(dataDir, 'error.log')).toBe(`{"level":"error","message":"${INVALID_PORT_MESSAGE}"}\n`);
expect(readLog(dataDir, 'info.log')).toBe('');
},
);

it('exits 1 with the invalid base path error before validating the port when the data directory does not exist', async () => {
const exit = jest.spyOn(process, 'exit').mockImplementation(((code: number) => {
throw new Error(`exit ${code}`);
}) as never);
it('fails with the invalid base path error, exiting 1, before validating the port when the data directory does not exist', async () => {
const exit = jest.spyOn(process, 'exit').mockImplementation((() => undefined) as never);
const missing = join(temporaryDirectory(), 'no-such-dir');
const command = commandWithFlags({ 'data-dir': missing, port: '99999' });

await expect(command.init()).rejects.toThrow('exit 1');
const failure = await command.init().catch((error: Error & { oclif?: { exit?: number } }) => error);

expect(exit).toHaveBeenCalledTimes(1);
expect(exit).toHaveBeenCalledWith(1);
expect(stdout).toEqual(['\u001b[31merror: Provided base path is not valid\u001b[39m\n']);
expect(failure).toBeInstanceOf(Errors.CLIError);
expect(failure).toMatchObject({ message: 'Provided base path is not valid', oclif: { exit: EXIT_RUNTIME } });
expect(exit).not.toHaveBeenCalled();
expect(stdout).toEqual([]);
expect(existsSync(missing)).toBe(false);
expect(command['sharedConfig']).toBeUndefined();
});

it('fails naming the path, exiting 1, when the data directory is a file', async () => {
const file = join(temporaryDirectory(), 'not-a-dir.txt');
writeFileSync(file, 'x');
const command = commandWithFlags({ 'data-dir': file, port: '3000' });

const failure = await command.init().catch((error: Error & { oclif?: { exit?: number } }) => error);

expect(failure).toBeInstanceOf(Errors.CLIError);
expect(failure).toMatchObject({ message: `--data-dir ${file} is not a directory`, oclif: { exit: EXIT_RUNTIME } });
expect(stdout).toEqual([]);
expect(command['sharedConfig']).toBeUndefined();
});

it('routes the command log through the project logger', async () => {
const dataDir = temporaryDirectory();
const print = jest.spyOn(cliux, 'print').mockImplementation(() => undefined);
Expand Down Expand Up @@ -308,10 +308,10 @@ describe('launch:functions:serve port precedence', () => {

const failure = await command.init().catch((error: Error & { oclif?: { exit?: number } }) => error);

expect(failure).toBeInstanceOf(Errors.ExitError);
expect(failure).toMatchObject({ oclif: { exit: EXIT_RUNTIME } });
expect(failure).toBeInstanceOf(Errors.CLIError);
expect(failure).toMatchObject({ message: INVALID_PORT_MESSAGE, oclif: { exit: EXIT_RUNTIME } });
expect(command['sharedConfig']).toBeUndefined();
expect(stdout).toEqual([`\u001b[31merror: ${INVALID_PORT_MESSAGE}\u001b[39m\n`]);
expect(stdout).toEqual([]);
},
);

Expand Down
14 changes: 12 additions & 2 deletions src/commands/launch/functions/serve.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Command } from '@oclif/core';
import { existsSync, statSync } from 'node:fs';

import { EXIT_RUNTIME, EXIT_USAGE } from '../../../core/constants';
import { failureOutputOf, reportFailure } from '../../../core/failure';
Expand All @@ -24,14 +25,23 @@ export default class Functions extends Command {
const { flags } = await this.parse(Functions);
const currentWorkingDirectory = process.cwd();
const projectBasePath = flags['data-dir'] || currentWorkingDirectory;
if (!existsSync(projectBasePath)) {
this.error('Provided base path is not valid', { exit: EXIT_RUNTIME });
}

if (!statSync(projectBasePath).isDirectory()) {
this.error(`--data-dir ${projectBasePath} is not a directory`, { exit: EXIT_RUNTIME });
}

const logger = new Logger({ projectBasePath });
this.log = logger.log.bind(logger);

const port = process.env.PORT || flags.port;
if (!isValidPort(port)) {
this.log('Invalid port number. Please provide a valid port number between 0 and 65535.', 'error');
this.exit(EXIT_RUNTIME);
const message = 'Invalid port number. Please provide a valid port number between 0 and 65535.';
this.log(message, 'error');
await logger.flush();
this.error(message, { exit: EXIT_RUNTIME });
}

this.sharedConfig = {
Expand Down
Loading
Loading