Update app and tooling

This commit is contained in:
Lawrence Chen 2026-01-29 17:36:26 -08:00
parent 3046531bdd
commit e620ec7349
4950 changed files with 2975120 additions and 10 deletions

6
node_modules/@vercel/fun/dist/src/deferred.d.ts generated vendored Normal file
View file

@ -0,0 +1,6 @@
export interface Deferred<T> {
promise: Promise<T>;
resolve: (value?: T | PromiseLike<T>) => void;
reject: (reason?: any) => void;
}
export declare function createDeferred<T>(): Deferred<T>;

14
node_modules/@vercel/fun/dist/src/deferred.js generated vendored Normal file
View file

@ -0,0 +1,14 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createDeferred = void 0;
function createDeferred() {
let r;
let j;
const promise = new Promise((resolve, reject) => {
r = resolve;
j = reject;
});
return { promise, resolve: r, reject: j };
}
exports.createDeferred = createDeferred;
//# sourceMappingURL=deferred.js.map

1
node_modules/@vercel/fun/dist/src/deferred.js.map generated vendored Normal file
View file

@ -0,0 +1 @@
{"version":3,"file":"deferred.js","sourceRoot":"","sources":["../../src/deferred.ts"],"names":[],"mappings":";;;AAMA,SAAgB,cAAc;IAC7B,IAAI,CAAC,CAAC;IACN,IAAI,CAAC,CAAC;IACN,MAAM,OAAO,GAAG,IAAI,OAAO,CAC1B,CACC,OAA6C,EAC7C,MAA8B,EACvB,EAAE;QACT,CAAC,GAAG,OAAO,CAAC;QACZ,CAAC,GAAG,MAAM,CAAC;IACZ,CAAC,CACD,CAAC;IACF,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,CAAC;AAC3C,CAAC;AAbD,wCAaC"}

13
node_modules/@vercel/fun/dist/src/errors.d.ts generated vendored Normal file
View file

@ -0,0 +1,13 @@
/**
* Subclassing `Error` in TypeScript:
* https://stackoverflow.com/a/41102306/376773
*/
interface LambdaErrorPayload {
errorMessage?: string;
errorType?: string;
stackTrace?: string | string[];
}
export declare class LambdaError extends Error {
constructor(data?: LambdaErrorPayload);
}
export {};

27
node_modules/@vercel/fun/dist/src/errors.js generated vendored Normal file
View file

@ -0,0 +1,27 @@
"use strict";
/**
* Subclassing `Error` in TypeScript:
* https://stackoverflow.com/a/41102306/376773
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.LambdaError = void 0;
class LambdaError extends Error {
constructor(data = {}) {
super(data.errorMessage || 'Unspecified runtime initialization error');
Object.setPrototypeOf(this, LambdaError.prototype);
Object.defineProperty(this, 'name', {
value: data.errorType || this.constructor.name
});
if (Array.isArray(data.stackTrace)) {
this.stack = [
`${this.name}: ${this.message}`,
...data.stackTrace
].join('\n');
}
else if (typeof data.stackTrace === 'string') {
this.stack = data.stackTrace;
}
}
}
exports.LambdaError = LambdaError;
//# sourceMappingURL=errors.js.map

1
node_modules/@vercel/fun/dist/src/errors.js.map generated vendored Normal file
View file

@ -0,0 +1 @@
{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/errors.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAQH,MAAa,WAAY,SAAQ,KAAK;IACrC,YAAY,OAA2B,EAAE;QACxC,KAAK,CAAC,IAAI,CAAC,YAAY,IAAI,0CAA0C,CAAC,CAAC;QACvE,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,WAAW,CAAC,SAAS,CAAC,CAAC;QAEnD,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,MAAM,EAAE;YACnC,KAAK,EAAE,IAAI,CAAC,SAAS,IAAI,IAAI,CAAC,WAAW,CAAC,IAAI;SAC9C,CAAC,CAAC;QAEH,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC,EAAE;YACnC,IAAI,CAAC,KAAK,GAAG;gBACZ,GAAG,IAAI,CAAC,IAAI,KAAK,IAAI,CAAC,OAAO,EAAE;gBAC/B,GAAG,IAAI,CAAC,UAAU;aAClB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;SACb;aAAM,IAAI,OAAO,IAAI,CAAC,UAAU,KAAK,QAAQ,EAAE;YAC/C,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,UAAU,CAAC;SAC7B;IACF,CAAC;CACD;AAlBD,kCAkBC"}

12
node_modules/@vercel/fun/dist/src/index.d.ts generated vendored Normal file
View file

@ -0,0 +1,12 @@
import { Lambda, LambdaParams, InvokeParams, InvokeResult } from './types';
import * as providers from './providers';
import { funCacheDir, runtimes, initializeRuntime } from './runtimes';
export { Lambda, LambdaParams, InvokeParams, InvokeResult, runtimes, providers, funCacheDir, initializeRuntime };
export declare class ValidationError extends Error {
reserved?: string[];
constructor(message?: string);
}
export declare function createFunction(params: LambdaParams): Promise<Lambda>;
export declare function invoke(fn: Lambda, params: InvokeParams): Promise<InvokeResult>;
export declare function destroy(fn: Lambda): Promise<void>;
export declare function cleanCacheDir(): Promise<void>;

167
node_modules/@vercel/fun/dist/src/index.js generated vendored Normal file
View file

@ -0,0 +1,167 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.cleanCacheDir = exports.destroy = exports.invoke = exports.createFunction = exports.ValidationError = exports.initializeRuntime = exports.funCacheDir = exports.providers = exports.runtimes = void 0;
const debug_1 = __importDefault(require("debug"));
const promises_1 = require("node:fs/promises");
const unzip_1 = require("./unzip");
const errors_1 = require("./errors");
const providers = __importStar(require("./providers"));
exports.providers = providers;
const runtimes_1 = require("./runtimes");
Object.defineProperty(exports, "funCacheDir", { enumerable: true, get: function () { return runtimes_1.funCacheDir; } });
Object.defineProperty(exports, "runtimes", { enumerable: true, get: function () { return runtimes_1.runtimes; } });
Object.defineProperty(exports, "initializeRuntime", { enumerable: true, get: function () { return runtimes_1.initializeRuntime; } });
const debug = (0, debug_1.default)('@vercel/fun:index');
// Environment variable names that AWS Lambda does not allow to be overridden.
// https://docs.aws.amazon.com/lambda/latest/dg/current-supported-versions.html#lambda-environment-variables
const reservedEnvVars = new Set([
'_HANDLER',
'LAMBDA_TASK_ROOT',
'LAMBDA_RUNTIME_DIR',
'AWS_EXECUTION_ENV',
'AWS_DEFAULT_REGION',
'AWS_REGION',
'AWS_LAMBDA_LOG_GROUP_NAME',
'AWS_LAMBDA_LOG_STREAM_NAME',
'AWS_LAMBDA_FUNCTION_NAME',
'AWS_LAMBDA_FUNCTION_MEMORY_SIZE',
'AWS_LAMBDA_FUNCTION_VERSION',
'AWS_ACCESS_KEY',
'AWS_ACCESS_KEY_ID',
'AWS_SECRET_KEY',
'AWS_SECRET_ACCESS_KEY',
'AWS_SESSION_TOKEN',
'TZ'
]);
class ValidationError extends Error {
constructor(message) {
super(message);
// Restore prototype chain (see https://stackoverflow.com/a/41102306/376773)
this.name = ValidationError.name;
const actualProto = ValidationError.prototype;
Object.setPrototypeOf(this, actualProto);
}
}
exports.ValidationError = ValidationError;
function createFunction(params) {
return __awaiter(this, void 0, void 0, function* () {
const Provider = providers[params.Provider || 'native'];
if (!Provider) {
throw new TypeError(`Provider "${params.Provider}" is not implemented`);
}
const runtime = runtimes_1.runtimes[params.Runtime];
if (!runtime) {
throw new TypeError(`Runtime "${params.Runtime}" is not implemented`);
}
yield (0, runtimes_1.initializeRuntime)(runtime);
const envVars = (params.Environment && params.Environment.Variables) || {};
const reserved = Object.keys(envVars).filter(name => {
return reservedEnvVars.has(name.toUpperCase());
});
if (reserved.length > 0) {
const err = new ValidationError(`The following environment variables can not be configured: ${reserved.join(', ')}`);
err.reserved = reserved;
throw err;
}
const fn = function (payload) {
return __awaiter(this, void 0, void 0, function* () {
const result = yield fn.invoke({
InvocationType: 'RequestResponse',
Payload: JSON.stringify(payload)
});
let resultPayload = result.Payload;
if (typeof resultPayload !== 'string') {
// For Buffer / Blob
resultPayload = String(resultPayload);
}
const parsedPayload = JSON.parse(resultPayload);
if (result.FunctionError) {
throw new errors_1.LambdaError(parsedPayload);
}
else {
return parsedPayload;
}
});
};
fn.params = params;
fn.runtime = runtime;
fn.destroy = destroy.bind(null, fn);
fn.invoke = invoke.bind(null, fn);
fn.functionName = params.FunctionName;
fn.region = params.Region || 'us-west-1';
fn.version = '$LATEST';
fn.arn = '';
fn.timeout = typeof params.Timeout === 'number' ? params.Timeout : 3;
fn.memorySize =
typeof params.MemorySize === 'number' ? params.MemorySize : 128;
debug('Creating provider %o', Provider.name);
fn.provider = new Provider(fn);
if (params.Code.ZipFile) {
fn.extractedDir = yield (0, unzip_1.unzipToTemp)(params.Code.ZipFile);
}
return fn;
});
}
exports.createFunction = createFunction;
function invoke(fn, params) {
return __awaiter(this, void 0, void 0, function* () {
debug('Invoking function %o', fn.functionName);
const result = yield fn.provider.invoke(params);
return result;
});
}
exports.invoke = invoke;
function destroy(fn) {
return __awaiter(this, void 0, void 0, function* () {
const ops = [fn.provider.destroy()];
if (fn.extractedDir) {
debug('Deleting directory %o for function %o', fn.extractedDir, fn.functionName);
ops.push((0, promises_1.rm)(fn.extractedDir, { recursive: true }));
}
yield Promise.all(ops);
});
}
exports.destroy = destroy;
function cleanCacheDir() {
return __awaiter(this, void 0, void 0, function* () {
debug('Deleting fun cache directory %o', runtimes_1.funCacheDir);
yield (0, promises_1.rm)(runtimes_1.funCacheDir, { recursive: true });
});
}
exports.cleanCacheDir = cleanCacheDir;
//# sourceMappingURL=index.js.map

1
node_modules/@vercel/fun/dist/src/index.js.map generated vendored Normal file
View file

@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAOA,kDAAgC;AAChC,+CAAgD;AAChD,mCAAsC;AACtC,qCAAuC;AACvC,uDAAyC;AAWxC,8BAAS;AAVV,yCAAsE;AAWrE,4FAXQ,sBAAW,OAWR;AAFX,yFATqB,mBAAQ,OASrB;AAGR,kGAZ+B,4BAAiB,OAY/B;AAVlB,MAAM,KAAK,GAAG,IAAA,eAAW,EAAC,mBAAmB,CAAC,CAAC;AAa/C,8EAA8E;AAC9E,4GAA4G;AAC5G,MAAM,eAAe,GAAG,IAAI,GAAG,CAAC;IAC/B,UAAU;IACV,kBAAkB;IAClB,oBAAoB;IACpB,mBAAmB;IACnB,oBAAoB;IACpB,YAAY;IACZ,2BAA2B;IAC3B,4BAA4B;IAC5B,0BAA0B;IAC1B,iCAAiC;IACjC,6BAA6B;IAC7B,gBAAgB;IAChB,mBAAmB;IACnB,gBAAgB;IAChB,uBAAuB;IACvB,mBAAmB;IACnB,IAAI;CACJ,CAAC,CAAC;AAEH,MAAa,eAAgB,SAAQ,KAAK;IAGzC,YAAY,OAAgB;QAC3B,KAAK,CAAC,OAAO,CAAC,CAAC;QAEf,4EAA4E;QAC5E,IAAI,CAAC,IAAI,GAAG,e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dist/src/install-node.d.ts generated vendored Normal file
View file

@ -0,0 +1,3 @@
/// <reference types="node" />
export declare function generateNodeTarballUrl(version: string, platform?: NodeJS.Platform, arch?: string): string;
export declare function installNode(dest: string, version: string, platform?: NodeJS.Platform, arch?: string): Promise<void>;

75
node_modules/@vercel/fun/dist/src/install-node.js generated vendored Normal file
View file

@ -0,0 +1,75 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.installNode = exports.generateNodeTarballUrl = void 0;
const tar_1 = require("tar");
const promisepipe_1 = __importDefault(require("promisepipe"));
const node_fetch_1 = __importDefault(require("node-fetch"));
const debug_1 = __importDefault(require("debug"));
const node_zlib_1 = require("node:zlib");
const node_path_1 = require("node:path");
const node_fs_1 = require("node:fs");
const semver_1 = require("semver");
const unzip_1 = require("./unzip");
const debug = (0, debug_1.default)('@vercel/fun:install-node');
function generateNodeTarballUrl(version, platform = process.platform, arch = process.arch) {
if (!version.startsWith('v')) {
version = `v${version}`;
}
let ext;
let plat = platform;
if (platform === 'win32') {
ext = 'zip';
plat = 'win';
}
else {
ext = 'tar.gz';
}
return `https://nodejs.org/dist/${version}/node-${version}-${plat}-${arch}.${ext}`;
}
exports.generateNodeTarballUrl = generateNodeTarballUrl;
function installNode(dest, version, platform = process.platform, arch = process.arch) {
return __awaiter(this, void 0, void 0, function* () {
// For Apple M1, use the x64 binaries for v14 or less,
// since there are no arm64 binaries for these versions
if (platform === 'darwin' &&
arch === 'arm64' &&
(0, semver_1.satisfies)(version, '<= 14')) {
arch = 'x64';
}
const tarballUrl = generateNodeTarballUrl(version, platform, arch);
debug('Downloading Node.js %s tarball %o', version, tarballUrl);
const res = yield (0, node_fetch_1.default)(tarballUrl);
if (!res.ok) {
throw new Error(`HTTP request failed: ${res.status}`);
}
if (platform === 'win32') {
// Put it in the `bin` dir for consistency with the tarballs
const finalDest = (0, node_path_1.join)(dest, 'bin');
const zipName = (0, node_path_1.basename)(tarballUrl);
const zipPath = (0, node_path_1.join)(dest, zipName);
debug('Saving Node.js %s zip file to %o', version, zipPath);
yield (0, promisepipe_1.default)(res.body, (0, node_fs_1.createWriteStream)(zipPath));
debug('Extracting Node.js %s zip file to %o', version, finalDest);
const zipFile = yield (0, unzip_1.zipFromFile)(zipPath);
yield (0, unzip_1.unzip)(zipFile, finalDest, { strip: 1 });
}
else {
debug('Extracting Node.js %s tarball to %o', version, dest);
yield (0, promisepipe_1.default)(res.body, (0, node_zlib_1.createGunzip)(), (0, tar_1.extract)({ strip: 1, C: dest }));
}
});
}
exports.installNode = installNode;
//# sourceMappingURL=install-node.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"install-node.js","sourceRoot":"","sources":["../../src/install-node.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,6BAA8B;AAC9B,8DAA+B;AAC/B,4DAA+B;AAC/B,kDAAgC;AAChC,yCAAyC;AACzC,yCAA2C;AAC3C,qCAA4C;AAC5C,mCAAmC;AACnC,mCAA6C;AAE7C,MAAM,KAAK,GAAG,IAAA,eAAW,EAAC,0BAA0B,CAAC,CAAC;AAEtD,SAAgB,sBAAsB,CACrC,OAAe,EACf,WAA4B,OAAO,CAAC,QAAQ,EAC5C,OAAe,OAAO,CAAC,IAAI;IAE3B,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE;QAC7B,OAAO,GAAG,IAAI,OAAO,EAAE,CAAC;KACxB;IACD,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E,OAAO,CAAC,CAAC;YAC5D,MAAM,IAAA,qBAAI,EACT,GAAG,CAAC,IAAI,EACR,IAAA,2BAAiB,EAAC,OAAO,CAAC,CAC1B,CAAC;YAEF,KAAK,CAAC,sCAAsC,EAAE,OAAO,EAAE,SAAS,CAAC,CAAC;YAClE,MAAM,OAAO,GAAG,MAAM,IAAA,mBAAW,EAAC,OAAO,CAAC,CAAC;YAC3C,MAAM,IAAA,aAAK,EAAC,OAAO,EAAE,SAAS,EAAE,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,CAAC;SAC9C;aAAM;YACN,KAAK,CAAC,qCAAqC,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC;YAC5D,MAAM,IAAA,qBAAI,EACT,GAAG,CAAC,IAAI,EACR,IAAA,wBAAY,GAAE,EACd,IAAA,aAAO,EAAC,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,EAAE,IAAI,EAAE,CAAC,CAC9B,CAAC;SACF;IACF,CAAC;CAAA;AA7CD,kCA6CC"}

View file

@ -0,0 +1,3 @@
/// <reference types="node" />
export declare function generatePythonTarballUrl(version: string, platform?: NodeJS.Platform, arch?: string): string;
export declare function installPython(dest: string, version: string, platform?: NodeJS.Platform, arch?: string): Promise<void>;

48
node_modules/@vercel/fun/dist/src/install-python.js generated vendored Normal file
View file

@ -0,0 +1,48 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.installPython = exports.generatePythonTarballUrl = void 0;
const tar_1 = require("tar");
const node_fetch_1 = __importDefault(require("node-fetch"));
const debug_1 = __importDefault(require("debug"));
const node_zlib_1 = require("node:zlib");
const debug = (0, debug_1.default)('@vercel/fun:install-python');
function generatePythonTarballUrl(version, platform = process.platform, arch = process.arch) {
return `https://python-binaries.zeit.sh/python-${version}-${platform}-${arch}.tar.gz`;
}
exports.generatePythonTarballUrl = generatePythonTarballUrl;
function installPython(dest, version, platform = process.platform, arch = process.arch) {
return __awaiter(this, void 0, void 0, function* () {
// For Apple M1 use the x64 binaries
if (platform === 'darwin' && arch === 'arm64') {
arch = 'x64';
}
const tarballUrl = generatePythonTarballUrl(version, platform, arch);
debug('Downloading Python %s tarball %o', version, tarballUrl);
const res = yield (0, node_fetch_1.default)(tarballUrl);
if (!res.ok) {
throw new Error(`HTTP request ${tarballUrl} failed: ${res.status}`);
}
return new Promise((resolve, reject) => {
debug('Extracting Python %s tarball to %o', version, dest);
res.body
.pipe((0, node_zlib_1.createGunzip)())
.pipe((0, tar_1.extract)({ strip: 1, C: dest }))
.on('error', reject)
.on('end', resolve);
});
});
}
exports.installPython = installPython;
//# sourceMappingURL=install-python.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"install-python.js","sourceRoot":"","sources":["../../src/install-python.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,6BAA8B;AAC9B,4DAA+B;AAC/B,kDAAgC;AAChC,yCAAyC;AAEzC,MAAM,KAAK,GAAG,IAAA,eAAW,EAAC,4BAA4B,CAAC,CAAC;AAExD,SAAgB,wBAAwB,CACvC,OAAe,EACf,WAA4B,OAAO,CAAC,QAAQ,EAC5C,OAAe,OAAO,CAAC,IAAI;IAE3B,OAAO,0CAA0C,OAAO,IAAI,QAAQ,IAAI,IAAI,SAAS,CAAC;AACvF,CAAC;AAND,4DAMC;AAED,SAAsB,aAAa,CAClC,IAAY,EACZ,OAAe,EACf,WAA4B,OAAO,CAAC,QAAQ,EAC5C,OAAe,OAAO,CAAC,IAAI;;QAE3B,oCAAoC;QACpC,IAAI,QAAQ,KAAK,QAAQ,IAAI,IAAI,KAAK,OAAO,EAAE;YAC9C,IAAI,GAAG,KAAK,CAAC;SACb;QAED,MAAM,UAAU,GAAG,wBAAwB,CAAC,OAAO,EAAE,QAAQ,EAAE,IAAI,CAAC,CAAC;QACrE,KAAK,CAAC,kCAAkC,EAAE,OAAO,EAAE,UAAU,CAAC,CAAC;QAC/D,MAAM,GAAG,GAAG,MAAM,IAAA,oBAAK,EAAC,UAAU,CAAC,CAAC;QACpC,IAAI,CAAC,GAAG,CAAC,EAAE,EAAE;YACZ,MAAM,IAAI,KAAK,CAAC,gBAAgB,UAAU,YAAY,GAAG,CAAC,MAAM,EAAE,CAAC,CAAC;SACpE;QACD,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YACtC,KAAK,CAAC,oCAAoC,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC;YAC3D,GAAG,CAAC,IAAI;iBACN,IAAI,CAAC,IAAA,wBAAY,GAAE,CAAC;iBACpB,IAAI,CAAC,IAAA,aAAO,EAAC,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC;iBACpC,EAAE,CAAC,OAAO,EAAE,MAAM,CAAC;iBACnB,EAAE,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;QACtB,CAAC,CAAC,CAAC;IACJ,CAAC;CAAA;AAzBD,sCAyBC"}

View file

@ -0,0 +1 @@
export default function createProvider(): void;

View file

@ -0,0 +1,5 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function createProvider() { }
exports.default = createProvider;
//# sourceMappingURL=index.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/providers/docker/index.ts"],"names":[],"mappings":";;AAAA,SAAwB,cAAc,KAAI,CAAC;AAA3C,iCAA2C"}

View file

@ -0,0 +1,2 @@
import native from './native';
export { native };

9
node_modules/@vercel/fun/dist/src/providers/index.js generated vendored Normal file
View file

@ -0,0 +1,9 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.native = void 0;
const native_1 = __importDefault(require("./native"));
exports.native = native_1.default;
//# sourceMappingURL=index.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/providers/index.ts"],"names":[],"mappings":";;;;;;AAAA,sDAA8B;AACrB,iBADF,gBAAM,CACE"}

View file

@ -0,0 +1,16 @@
/// <reference types="node" />
import { ChildProcess } from 'child_process';
import { LambdaParams, InvokeParams, InvokeResult, Lambda, Provider } from '../../types';
export default class NativeProvider implements Provider {
private pool;
private lambda;
private params;
private runtimeApis;
constructor(fn: Lambda, params: LambdaParams);
createProcess(): Promise<ChildProcess>;
destroyProcess(proc: ChildProcess): Promise<void>;
freezeProcess(proc: ChildProcess): void;
unfreezeProcess(proc: ChildProcess): void;
invoke(params: InvokeParams): Promise<InvokeResult>;
destroy(): Promise<void>;
}

View file

@ -0,0 +1,201 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const ms_1 = __importDefault(require("ms"));
const node_crypto_1 = require("node:crypto");
const debug_1 = __importDefault(require("debug"));
const node_util_1 = require("node:util");
const async_listen_1 = __importDefault(require("async-listen"));
const tree_kill_1 = __importDefault(require("tree-kill"));
const generic_pool_1 = require("generic-pool");
const node_path_1 = require("node:path");
const child_process_1 = require("child_process");
const runtime_server_1 = require("../../runtime-server");
const isWin = process.platform === 'win32';
const debug = (0, debug_1.default)('@vercel/fun:providers/native');
const treeKill = (0, node_util_1.promisify)(tree_kill_1.default);
class NativeProvider {
constructor(fn, params) {
const factory = {
create: this.createProcess.bind(this),
destroy: this.destroyProcess.bind(this)
};
const opts = {
min: 0,
max: 10,
acquireTimeoutMillis: (0, ms_1.default)('5s')
// XXX: These 3 options are commented out because they cause
// the tests to never complete (doesn't exit cleanly).
// How often to check if a process needs to be shut down due to not
// being invoked
//evictionRunIntervalMillis: ms('10s'),
// How long a process is allowed to stay alive without being invoked
//idleTimeoutMillis: ms('15s')
};
this.lambda = fn;
this.params = params;
this.runtimeApis = new WeakMap();
this.pool = (0, generic_pool_1.createPool)(factory, opts);
this.pool.on('factoryCreateError', err => {
console.error('factoryCreateError', { err });
});
this.pool.on('factoryDestroyError', err => {
console.error('factoryDestroyError', { err });
});
}
createProcess() {
return __awaiter(this, void 0, void 0, function* () {
const { runtime, params, region, version, extractedDir } = this.lambda;
const binDir = (0, node_path_1.join)(runtime.cacheDir, 'bin');
const bootstrapFile = runtime.name === 'executable' ? 'executable' : 'bootstrap';
const bootstrap = (0, node_path_1.join)(runtime.cacheDir, isWin ? 'bootstrap.js' : bootstrapFile);
const server = new runtime_server_1.RuntimeServer(this.lambda);
yield (0, async_listen_1.default)(server, 0, '127.0.0.1');
const { port } = server.address();
debug('Creating process %o', bootstrap);
const taskDir = (0, node_path_1.resolve)(extractedDir || params.Code.Directory);
const functionName = params.FunctionName || (0, node_path_1.basename)(taskDir);
const logGroupName = `aws/lambda/${functionName}`;
const logStreamName = `2019/01/12/[${version}]${(0, node_crypto_1.randomUUID)().replace(/\-/g, '')}`;
// https://docs.aws.amazon.com/lambda/latest/dg/current-supported-versions.html
const env = Object.assign(Object.assign({
// Non-reserved env vars (can overwrite with params)
PATH: `${binDir}${node_path_1.delimiter}${process.env.PATH}`, LANG: 'en_US.UTF-8' }, (params.Environment && params.Environment.Variables)), {
// Restricted env vars
_HANDLER: params.Handler, AWS_REGION: region, AWS_ACCESS_KEY_ID: params.AccessKeyId, AWS_SECRET_ACCESS_KEY: params.SecretAccessKey, AWS_DEFAULT_REGION: region, AWS_EXECUTION_ENV: `AWS_Lambda_${params.Runtime}`, AWS_LAMBDA_FUNCTION_NAME: functionName, AWS_LAMBDA_FUNCTION_VERSION: version, AWS_LAMBDA_FUNCTION_MEMORY_SIZE: String(params.MemorySize || 128), AWS_LAMBDA_RUNTIME_API: `127.0.0.1:${port}`, AWS_LAMBDA_LOG_GROUP_NAME: logGroupName, AWS_LAMBDA_LOG_STREAM_NAME: logStreamName, LAMBDA_RUNTIME_DIR: runtime.cacheDir, LAMBDA_TASK_ROOT: taskDir, TZ: ':UTC' });
let bin = bootstrap;
const args = [];
if (isWin) {
args.push(bootstrap);
bin = process.execPath;
}
const proc = (0, child_process_1.spawn)(bin, args, {
env,
cwd: taskDir,
stdio: ['ignore', 'inherit', 'inherit']
});
this.runtimeApis.set(proc, server);
proc.on('exit', (code, signal) => __awaiter(this, void 0, void 0, function* () {
debug('Process (pid=%o) exited with code %o, signal %o', proc.pid, code, signal);
const server = this.runtimeApis.get(proc);
if (server) {
debug('Shutting down Runtime API for %o', proc.pid);
server.close();
this.runtimeApis.delete(proc);
}
else {
debug('No Runtime API server associated with process %o. This SHOULD NOT happen!', proc.pid);
}
}));
return proc;
});
}
destroyProcess(proc) {
return __awaiter(this, void 0, void 0, function* () {
try {
// Unfreeze the process first so it is able to process the `SIGTERM`
// signal and exit cleanly (clean up child processes, etc.)
this.unfreezeProcess(proc);
debug('Stopping process %o', proc.pid);
yield treeKill(proc.pid);
}
catch (err) {
// ESRCH means that the process ID no longer exists, which is fine
// in this case since we're shutting down the process anyways
if (err.code === 'ESRCH' || /not found/i.test(err.message)) {
debug('Got error stopping process %o: %s', proc.pid, err.message);
}
else {
throw err;
}
}
});
}
freezeProcess(proc) {
// `SIGSTOP` is not supported on Windows
if (!isWin) {
debug('Freezing process %o', proc.pid);
process.kill(proc.pid, 'SIGSTOP');
}
}
unfreezeProcess(proc) {
// `SIGCONT` is not supported on Windows
if (!isWin) {
debug('Unfreezing process %o', proc.pid);
process.kill(proc.pid, 'SIGCONT');
}
}
invoke(params) {
return __awaiter(this, void 0, void 0, function* () {
let result;
const proc = yield this.pool.acquire();
const server = this.runtimeApis.get(proc);
if (server.initDeferred) {
// The lambda process has just booted up, so wait for the
// initialization API call to come in before proceeding
debug('Waiting for init on process %o', proc.pid);
const initError = yield server.initDeferred.promise;
if (initError) {
debug('Lambda got initialization error on process %o', proc.pid);
// An error happend during initialization, so remove the
// process from the pool and return the error to the caller
yield this.pool.destroy(proc);
return initError;
}
debug('Lambda is initialized for process %o', proc.pid);
}
else {
// The lambda process is being re-used for a subsequent
// invocation, so unfreeze the process first
this.unfreezeProcess(proc);
}
try {
result = yield server.invoke(params);
}
catch (err) {
result = {
StatusCode: 200,
FunctionError: 'Unhandled',
ExecutedVersion: '$LATEST',
// TODO: make this into a `server.createError()` function
Payload: JSON.stringify({
errorMessage: err.message
})
};
}
if (result.FunctionError === 'Unhandled') {
// An "Unhandled" error means either init error or the process
// exited before sending the response. In either case, the process
// is unhealthy and needs to be removed from the pool
yield this.pool.destroy(proc);
}
else {
// Either a successful response, or a "Handled" error.
// The process may be re-used for the next invocation.
this.freezeProcess(proc);
yield this.pool.release(proc);
}
return result;
});
}
destroy() {
return __awaiter(this, void 0, void 0, function* () {
debug('Draining pool');
yield this.pool.drain();
this.pool.clear();
});
}
}
exports.default = NativeProvider;
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

22
node_modules/@vercel/fun/dist/src/runtime-server.d.ts generated vendored Normal file
View file

@ -0,0 +1,22 @@
/// <reference types="node" />
import http, { Server } from 'node:http';
import { Deferred } from './deferred';
import { Lambda, InvokeParams, InvokeResult } from './types';
export declare class RuntimeServer extends Server {
version: string;
initDeferred: Deferred<InvokeResult | void>;
resultDeferred: Deferred<InvokeResult>;
private nextDeferred;
private invokeDeferred;
private lambda;
private currentRequestId;
constructor(fn: Lambda);
resetInvocationState(): void;
serve(req: http.IncomingMessage, res: http.ServerResponse): Promise<any>;
handleNextInvocation(req: http.IncomingMessage, res: http.ServerResponse): Promise<void>;
handleInvocationResponse(req: any, res: any, requestId: string): Promise<void>;
handleInvocationError(req: any, res: any, requestId: string): Promise<void>;
handleInitializationError(req: any, res: any): Promise<void>;
invoke(params?: InvokeParams): Promise<InvokeResult>;
close(callback?: (err?: Error) => void): this;
}

200
node_modules/@vercel/fun/dist/src/runtime-server.js generated vendored Normal file
View file

@ -0,0 +1,200 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.RuntimeServer = void 0;
const node_http_1 = require("node:http");
const node_url_1 = require("node:url");
const debug_1 = __importDefault(require("debug"));
const micro_1 = require("micro");
const node_crypto_1 = require("node:crypto");
const path_to_regexp_1 = require("path-to-regexp");
const once_1 = __importDefault(require("@tootallnate/once"));
const deferred_1 = require("./deferred");
const matchFn = (0, path_to_regexp_1.match)('/:version/runtime/:subject/:target{/:action}');
const debug = (0, debug_1.default)('@vercel/fun:runtime-server');
function send404(res) {
res.statusCode = 404;
res.end();
}
class RuntimeServer extends node_http_1.Server {
constructor(fn) {
super();
this.version = '2018-06-01';
const serve = this.serve.bind(this);
this.on('request', (req, res) => (0, micro_1.run)(req, res, serve));
this.lambda = fn;
this.initDeferred = (0, deferred_1.createDeferred)();
this.resetInvocationState();
}
resetInvocationState() {
this.nextDeferred = (0, deferred_1.createDeferred)();
this.invokeDeferred = null;
this.resultDeferred = null;
this.currentRequestId = (0, node_crypto_1.randomUUID)();
}
serve(req, res) {
return __awaiter(this, void 0, void 0, function* () {
debug('%s %s', req.method, req.url);
const result = matchFn((0, node_url_1.parse)(req.url).pathname);
if (!result) {
return send404(res);
}
const { version, subject, target, action } = result.params;
if (this.version !== version) {
debug('Invalid API version, expected %o but got %o', this.version, version);
return send404(res);
}
// Routing logic
if (subject === 'invocation') {
if (target === 'next') {
return this.handleNextInvocation(req, res);
}
else {
// Assume it's an "AwsRequestId"
if (action === 'response') {
return this.handleInvocationResponse(req, res, target);
}
else if (action === 'error') {
return this.handleInvocationError(req, res, target);
}
else {
return send404(res);
}
}
}
else if (subject === 'init') {
if (target === 'error') {
return this.handleInitializationError(req, res);
}
else {
return send404(res);
}
}
else {
return send404(res);
}
});
}
handleNextInvocation(req, res) {
return __awaiter(this, void 0, void 0, function* () {
const { initDeferred } = this;
if (initDeferred) {
debug('Runtime successfully initialized');
this.initDeferred = null;
initDeferred.resolve();
}
this.invokeDeferred = (0, deferred_1.createDeferred)();
this.resultDeferred = (0, deferred_1.createDeferred)();
this.nextDeferred.resolve();
this.nextDeferred = null;
debug('Waiting for the `invoke()` function to be called');
// @ts-ignore
req.setTimeout(0); // disable default 2 minute socket timeout
const params = yield this.invokeDeferred.promise;
// TODO: use dynamic values from lambda params
const deadline = 5000;
const functionArn = 'arn:aws:lambda:us-west-1:977805900156:function:nate-dump';
res.setHeader('Lambda-Runtime-Aws-Request-Id', this.currentRequestId);
res.setHeader('Lambda-Runtime-Invoked-Function-Arn', functionArn);
res.setHeader('Lambda-Runtime-Deadline-Ms', String(deadline));
const finish = (0, once_1.default)(res, 'finish');
res.end(params.Payload);
yield finish;
});
}
handleInvocationResponse(req, res, requestId) {
return __awaiter(this, void 0, void 0, function* () {
// `RequestResponse` = 200
// `Event` = 202
// `DryRun` = 204
const statusCode = 200;
const payload = {
StatusCode: statusCode,
ExecutedVersion: '$LATEST',
Payload: yield (0, micro_1.text)(req, { limit: '6mb' })
};
res.statusCode = 202;
const finish = (0, once_1.default)(res, 'finish');
res.end();
yield finish;
this.resultDeferred.resolve(payload);
this.resetInvocationState();
});
}
handleInvocationError(req, res, requestId) {
return __awaiter(this, void 0, void 0, function* () {
const statusCode = 200;
const payload = {
StatusCode: statusCode,
FunctionError: 'Handled',
ExecutedVersion: '$LATEST',
Payload: yield (0, micro_1.text)(req, { limit: '6mb' })
};
res.statusCode = 202;
const finish = (0, once_1.default)(res, 'finish');
res.end();
yield finish;
this.resultDeferred.resolve(payload);
this.resetInvocationState();
});
}
handleInitializationError(req, res) {
return __awaiter(this, void 0, void 0, function* () {
const statusCode = 200;
const payload = {
StatusCode: statusCode,
FunctionError: 'Unhandled',
ExecutedVersion: '$LATEST',
Payload: yield (0, micro_1.text)(req, { limit: '6mb' })
};
res.statusCode = 202;
const finish = (0, once_1.default)(res, 'finish');
res.end();
yield finish;
this.initDeferred.resolve(payload);
});
}
invoke(params = { InvocationType: 'RequestResponse' }) {
return __awaiter(this, void 0, void 0, function* () {
if (this.nextDeferred) {
debug('Waiting for `next` invocation request from runtime');
yield this.nextDeferred.promise;
}
if (!params.Payload) {
params.Payload = '{}';
}
this.invokeDeferred.resolve(params);
const result = yield this.resultDeferred.promise;
return result;
});
}
close(callback) {
const deferred = this.initDeferred || this.resultDeferred;
if (deferred) {
const statusCode = 200;
deferred.resolve({
StatusCode: statusCode,
FunctionError: 'Unhandled',
ExecutedVersion: '$LATEST',
Payload: JSON.stringify({
errorMessage: `RequestId: ${this.currentRequestId} Process exited before completing request`
})
});
}
super.close(callback);
return this;
}
}
exports.RuntimeServer = RuntimeServer;
//# sourceMappingURL=runtime-server.js.map

File diff suppressed because one or more lines are too long

8
node_modules/@vercel/fun/dist/src/runtimes.d.ts generated vendored Normal file
View file

@ -0,0 +1,8 @@
import { Runtime } from './types';
interface Runtimes {
[name: string]: Runtime;
}
export declare const runtimes: Runtimes;
export declare const funCacheDir: string;
export declare function initializeRuntime(target: string | Runtime): Promise<Runtime>;
export {};

237
node_modules/@vercel/fun/dist/src/runtimes.js generated vendored Normal file
View file

@ -0,0 +1,237 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.initializeRuntime = exports.funCacheDir = exports.runtimes = void 0;
const node_path_1 = require("node:path");
const debug_1 = __importDefault(require("debug"));
const xdg_app_paths_1 = __importDefault(require("xdg-app-paths"));
const node_crypto_1 = require("node:crypto");
const promises_1 = require("node:fs/promises");
const go1x = __importStar(require("./runtimes/go1.x"));
const nodejs6 = __importStar(require("./runtimes/nodejs6.10"));
const nodejs8 = __importStar(require("./runtimes/nodejs8.10"));
const nodejs10 = __importStar(require("./runtimes/nodejs10.x"));
const nodejs12 = __importStar(require("./runtimes/nodejs12.x"));
const nodejs14 = __importStar(require("./runtimes/nodejs14.x"));
const python27 = __importStar(require("./runtimes/python2.7"));
const python3 = __importStar(require("./runtimes/python3"));
const python36 = __importStar(require("./runtimes/python3.6"));
const python37 = __importStar(require("./runtimes/python3.7"));
const debug = (0, debug_1.default)('@vercel/fun:runtimes');
const runtimesDir = (0, node_path_1.join)(__dirname, 'runtimes');
exports.runtimes = {};
exports.funCacheDir = (0, xdg_app_paths_1.default)('com.vercel.fun').cache();
function createRuntime(runtimes, name, mod) {
const runtime = Object.assign({ name, runtimeDir: (0, node_path_1.join)(runtimesDir, name) }, mod);
runtimes[name] = runtime;
}
createRuntime(exports.runtimes, 'executable');
createRuntime(exports.runtimes, 'provided');
createRuntime(exports.runtimes, 'go1.x', go1x);
createRuntime(exports.runtimes, 'nodejs');
createRuntime(exports.runtimes, 'nodejs6.10', nodejs6);
createRuntime(exports.runtimes, 'nodejs8.10', nodejs8);
createRuntime(exports.runtimes, 'nodejs10.x', nodejs10);
createRuntime(exports.runtimes, 'nodejs12.x', nodejs12);
createRuntime(exports.runtimes, 'nodejs14.x', nodejs14);
createRuntime(exports.runtimes, 'python');
createRuntime(exports.runtimes, 'python2.7', python27);
createRuntime(exports.runtimes, 'python3', python3);
createRuntime(exports.runtimes, 'python3.6', python36);
createRuntime(exports.runtimes, 'python3.7', python37);
/**
* Reads the file path `f` as an ascii string.
* Returns `null` if the file does not exist.
*/
function getCachedRuntimeSha(f) {
return __awaiter(this, void 0, void 0, function* () {
try {
return yield (0, promises_1.readFile)(f, 'ascii');
}
catch (err) {
if (err.code === 'ENOENT') {
return null;
}
throw err;
}
});
}
const runtimeShaPromises = new Map();
/**
* Calculates a sha256 of the files provided for a runtime. If any of the
* `bootstrap` or other dependent files change then the shasum will be
* different and the user's existing runtime cache will be invalidated.
*/
function _calculateRuntimeSha(src) {
return __awaiter(this, void 0, void 0, function* () {
debug('calculateRuntimeSha(%o)', src);
const hash = (0, node_crypto_1.createHash)('sha256');
yield calculateRuntimeShaDir(src, hash);
const sha = hash.digest('hex');
debug('Calculated runtime sha for %o: %o', src, sha);
return sha;
});
}
function calculateRuntimeShaDir(src, hash) {
return __awaiter(this, void 0, void 0, function* () {
const entries = yield (0, promises_1.readdir)(src);
for (const entry of entries) {
const srcPath = (0, node_path_1.join)(src, entry);
const s = yield (0, promises_1.lstat)(srcPath);
if (s.isDirectory()) {
yield calculateRuntimeShaDir(srcPath, hash);
}
else {
const contents = yield (0, promises_1.readFile)(srcPath);
hash.update(contents);
}
}
});
}
function calculateRuntimeSha(src) {
// The sha calculation promise gets memoized because the runtime code
// won't be changing (it's within a published npm module, after all)
let p = runtimeShaPromises.get(src);
if (!p) {
p = _calculateRuntimeSha(src);
runtimeShaPromises.set(src, p);
}
return p;
}
/**
* Until https://github.com/zeit/pkg/issues/639 is resolved, we have to
* implement the `copy()` operation without relying on `fs.copyFile()`.
*/
function copy(src, dest) {
return __awaiter(this, void 0, void 0, function* () {
debug('copy(%o, %o)', src, dest);
const [entries] = yield Promise.all([
(0, promises_1.readdir)(src),
(0, promises_1.mkdir)(dest, { recursive: true })
]);
debug('Entries: %o', entries);
for (const entry of entries) {
const srcPath = (0, node_path_1.join)(src, entry);
const destPath = (0, node_path_1.join)(dest, entry);
const s = yield (0, promises_1.lstat)(srcPath);
if (s.isDirectory()) {
yield copy(srcPath, destPath);
}
else {
const contents = yield (0, promises_1.readFile)(srcPath);
yield (0, promises_1.writeFile)(destPath, contents, { mode: s.mode });
}
}
});
}
// The Promises map is to ensure that a runtime is only initialized once
const initPromises = new Map();
function _initializeRuntime(runtime) {
return __awaiter(this, void 0, void 0, function* () {
const cacheDir = (0, node_path_1.join)(exports.funCacheDir, 'runtimes', runtime.name);
const cacheShaFile = (0, node_path_1.join)(cacheDir, '.cache-sha');
const [cachedRuntimeSha, runtimeSha] = yield Promise.all([
getCachedRuntimeSha(cacheShaFile),
calculateRuntimeSha(runtime.runtimeDir)
]);
runtime.cacheDir = cacheDir;
if (cachedRuntimeSha === runtimeSha) {
debug('Runtime %o is already initialized at %o', runtime.name, cacheDir);
}
else {
debug('Initializing %o runtime at %o', runtime.name, cacheDir);
try {
yield (0, promises_1.mkdir)(cacheDir, { recursive: true });
// The runtime directory is copied from the module dir to the cache
// dir. This is so that when compiled through `pkg`, then the
// bootstrap files exist on a real file system so that `execve()`
// works as expected.
yield copy(runtime.runtimeDir, cacheDir);
// Perform any runtime-specific initialization logic
if (typeof runtime.init === 'function') {
yield runtime.init(runtime);
}
yield (0, promises_1.writeFile)((0, node_path_1.join)(cacheDir, '.cache-sha'), runtimeSha);
}
catch (err) {
debug('Runtime %o `init()` failed %o. Cleaning up cache dir %o', runtime.name, err, cacheDir);
try {
yield (0, promises_1.rm)(cacheDir, { recursive: true });
}
catch (err2) {
debug('Cleaning up cache dir failed: %o', err2);
}
throw err;
}
}
});
}
function initializeRuntime(target) {
return __awaiter(this, void 0, void 0, function* () {
let runtime;
if (typeof target === 'string') {
runtime = exports.runtimes[target];
if (!runtime) {
throw new Error(`Could not find runtime with name "${target}"`);
}
}
else {
runtime = target;
}
let p = initPromises.get(runtime);
if (p) {
yield p;
}
else {
p = _initializeRuntime(runtime);
initPromises.set(runtime, p);
try {
yield p;
}
finally {
// Once the initialization is complete, remove the Promise. This is so that
// in case the cache is deleted during runtime, and then another Lambda
// function is created, the in-memory cache doesn't think the runtime is
// already initialized and will check the filesystem cache again.
initPromises.delete(runtime);
}
}
return runtime;
});
}
exports.initializeRuntime = initializeRuntime;
//# sourceMappingURL=runtimes.js.map

1
node_modules/@vercel/fun/dist/src/runtimes.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1 @@
export {};

View file

@ -0,0 +1,8 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const node_path_1 = require("node:path");
const node_child_process_1 = require("node:child_process");
// Delegate out to the provided `executable` file within the lambda
const executable = (0, node_path_1.join)(process.env.LAMBDA_TASK_ROOT, 'executable');
(0, node_child_process_1.spawn)(executable, [], { stdio: 'inherit' });
//# sourceMappingURL=bootstrap.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"bootstrap.js","sourceRoot":"","sources":["../../../../src/runtimes/executable/bootstrap.ts"],"names":[],"mappings":";;AAAA,yCAAiC;AACjC,2DAA2C;AAE3C,mEAAmE;AACnE,MAAM,UAAU,GAAG,IAAA,gBAAI,EAAC,OAAO,CAAC,GAAG,CAAC,gBAAgB,EAAE,YAAY,CAAC,CAAC;AACpE,IAAA,0BAAK,EAAC,UAAU,EAAE,EAAE,EAAE,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC,CAAC"}

View file

@ -0,0 +1,3 @@
#!/bin/bash
# Delegate out to the provided `executable` file
exec "$LAMBDA_TASK_ROOT/executable" "$@"

View file

@ -0,0 +1 @@
export {};

View file

@ -0,0 +1,273 @@
// Credits:
// https://github.com/lambci/docker-lambda/blob/f6b4765a9b659ceb949c34b19390026820ddd462/go1.x/run/aws-lambda-mock.go
// https://binx.io/blog/2018/12/03/aws-lambda-custom-bootstrap-in-go
package main
import (
"bytes"
"encoding/hex"
"fmt"
"github.com/aws/aws-lambda-go/lambda/messages"
"github.com/phayes/freeport"
"io/ioutil"
"log"
"math/rand"
"net"
"net/http"
"net/rpc"
"os"
"os/exec"
"os/signal"
"path"
"reflect"
"strconv"
"syscall"
"time"
)
func main() {
rand.Seed(time.Now().UTC().UnixNano())
mockContext := &MockLambdaContext{
FnName: getEnv("AWS_LAMBDA_FUNCTION_NAME", "test"),
Handler: getEnv("AWS_LAMBDA_FUNCTION_HANDLER", getEnv("_HANDLER", "handler")),
Version: getEnv("AWS_LAMBDA_FUNCTION_VERSION", "$LATEST"),
MemSize: getEnv("AWS_LAMBDA_FUNCTION_MEMORY_SIZE", "1536"),
Timeout: getEnv("AWS_LAMBDA_FUNCTION_TIMEOUT", "300"),
Region: getEnv("AWS_REGION", getEnv("AWS_DEFAULT_REGION", "us-east-1")),
AccountId: getEnv("AWS_ACCOUNT_ID", strconv.FormatInt(int64(rand.Int31()), 10)),
Start: time.Now(),
Pid: 1,
}
mockContext.ParseTimeout()
awsAccessKey := getEnv("AWS_ACCESS_KEY", getEnv("AWS_ACCESS_KEY_ID", "SOME_ACCESS_KEY_ID"))
awsSecretKey := getEnv("AWS_SECRET_KEY", getEnv("AWS_SECRET_ACCESS_KEY", "SOME_SECRET_ACCESS_KEY"))
awsSessionToken := getEnv("AWS_SESSION_TOKEN", os.Getenv("AWS_SECURITY_TOKEN"))
taskRoot := getEnv("LAMBDA_TASK_ROOT", "/var/task")
handlerPath := path.Join(taskRoot, mockContext.Handler)
os.Setenv("AWS_LAMBDA_FUNCTION_NAME", mockContext.FnName)
os.Setenv("AWS_LAMBDA_FUNCTION_VERSION", mockContext.Version)
os.Setenv("AWS_LAMBDA_FUNCTION_MEMORY_SIZE", mockContext.MemSize)
os.Setenv("AWS_LAMBDA_LOG_GROUP_NAME", "/aws/lambda/"+mockContext.FnName)
os.Setenv("AWS_LAMBDA_LOG_STREAM_NAME", logStreamName(mockContext.Version))
os.Setenv("AWS_REGION", mockContext.Region)
os.Setenv("AWS_DEFAULT_REGION", mockContext.Region)
os.Setenv("_HANDLER", mockContext.Handler)
port, err := freeport.GetFreePort()
if err != nil {
log.Fatal(fmt.Errorf("Freeport Error %s", err))
}
portStr := strconv.Itoa(port)
var cmd *exec.Cmd
cmd = exec.Command(handlerPath)
cmd.Env = append(os.Environ(),
"_LAMBDA_SERVER_PORT="+portStr,
"AWS_ACCESS_KEY="+awsAccessKey,
"AWS_ACCESS_KEY_ID="+awsAccessKey,
"AWS_SECRET_KEY="+awsSecretKey,
"AWS_SECRET_ACCESS_KEY="+awsSecretKey,
)
if len(awsSessionToken) > 0 {
cmd.Env = append(cmd.Env,
"AWS_SESSION_TOKEN="+awsSessionToken,
"AWS_SECURITY_TOKEN="+awsSessionToken,
)
}
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
if err = cmd.Start(); err != nil {
defer abortRequest(mockContext, err)
return
}
mockContext.Pid = cmd.Process.Pid
p, _ := os.FindProcess(-mockContext.Pid)
defer p.Signal(syscall.SIGKILL)
// Terminate the child process upon SIGINT / SIGTERM
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
<-c
p, _ := os.FindProcess(-mockContext.Pid)
p.Signal(syscall.SIGKILL)
os.Exit(0)
}()
var conn net.Conn
for {
conn, err = net.Dial("tcp", ":"+portStr)
if mockContext.HasExpired() {
defer abortRequest(mockContext, mockContext.TimeoutErr())
return
}
if err == nil {
break
}
if oerr, ok := err.(*net.OpError); ok {
// Connection refused, try again
if oerr.Op == "dial" && oerr.Net == "tcp" {
time.Sleep(5 * time.Millisecond)
continue
}
}
defer abortRequest(mockContext, err)
return
}
mockContext.Rpc = rpc.NewClient(conn)
for {
err = mockContext.Rpc.Call("Function.Ping", messages.PingRequest{}, &messages.PingResponse{})
if mockContext.HasExpired() {
defer abortRequest(mockContext, mockContext.TimeoutErr())
return
}
if err == nil {
break
}
time.Sleep(5 * time.Millisecond)
}
// XXX: The Go runtime seems to amortize the startup time, reset it here
mockContext.Start = time.Now()
// If we got to here then the handler process has initialized successfully
mockContext.ProcessEvents()
}
func abortRequest(mockContext *MockLambdaContext, err error) {
log.Fatal(err)
}
func getEnv(key, fallback string) string {
value := os.Getenv(key)
if value != "" {
return value
}
return fallback
}
func logStreamName(version string) string {
randBuf := make([]byte, 16)
rand.Read(randBuf)
hexBuf := make([]byte, hex.EncodedLen(len(randBuf)))
hex.Encode(hexBuf, randBuf)
return time.Now().Format("2006/01/02") + "/[" + version + "]" + string(hexBuf)
}
func getErrorType(err interface{}) string {
if errorType := reflect.TypeOf(err); errorType.Kind() == reflect.Ptr {
return errorType.Elem().Name()
} else {
return errorType.Name()
}
}
type LambdaError struct {
Message string `json:"errorMessage"`
Type string `json:"errorType,omitempty"`
StackTrace []*messages.InvokeResponse_Error_StackFrame `json:"stackTrace,omitempty"`
}
type MockLambdaContext struct {
Pid int
FnName string
Handler string
Version string
MemSize string
Timeout string
Region string
AccountId string
Start time.Time
TimeoutDuration time.Duration
Reply *messages.InvokeResponse
Rpc *rpc.Client
}
func (mc *MockLambdaContext) ProcessEvents() {
awsLambdaRuntimeApi := os.Getenv("AWS_LAMBDA_RUNTIME_API")
if awsLambdaRuntimeApi == "" {
panic("Missing: 'AWS_LAMBDA_RUNTIME_API'")
}
for {
// get the next event
requestUrl := fmt.Sprintf("http://%s/2018-06-01/runtime/invocation/next", awsLambdaRuntimeApi)
resp, err := http.Get(requestUrl)
if err != nil {
log.Fatal(fmt.Errorf("Error getting next invocation: %v", err))
}
requestId := resp.Header.Get("Lambda-Runtime-Aws-Request-Id")
eventData, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(fmt.Errorf("Error reading body: %s", err))
}
err = mc.Rpc.Call("Function.Invoke", mc.Request(requestId, eventData), &mc.Reply)
if err != nil {
log.Fatal(fmt.Errorf("Error invoking RPC call: %s", err))
}
responseUrl := fmt.Sprintf("http://%s/2018-06-01/runtime/invocation/%s/response", awsLambdaRuntimeApi, requestId)
req, err := http.NewRequest("POST", responseUrl, bytes.NewBuffer(mc.Reply.Payload))
if err != nil {
log.Fatal(fmt.Errorf("Error creating response HTTP request: %s", err))
}
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
client.Timeout = 0
_, err = client.Do(req)
if err != nil {
log.Fatal(fmt.Errorf("Error sending response: %s", err))
}
}
}
func (mc *MockLambdaContext) ParseTimeout() {
timeoutDuration, err := time.ParseDuration(mc.Timeout + "s")
if err != nil {
panic(err)
}
mc.TimeoutDuration = timeoutDuration
}
func (mc *MockLambdaContext) Deadline() time.Time {
return mc.Start.Add(mc.TimeoutDuration)
}
func (mc *MockLambdaContext) HasExpired() bool {
return time.Now().After(mc.Deadline())
}
func (mc *MockLambdaContext) Request(requestId string, payload []byte) *messages.InvokeRequest {
return &messages.InvokeRequest{
Payload: payload,
RequestId: requestId,
XAmznTraceId: getEnv("_X_AMZN_TRACE_ID", ""),
InvokedFunctionArn: getEnv("AWS_LAMBDA_FUNCTION_INVOKED_ARN", ""),
Deadline: messages.InvokeRequest_Timestamp{
Seconds: mc.Deadline().Unix(),
Nanos: int64(mc.Deadline().Nanosecond()),
},
}
}
func (mc *MockLambdaContext) TimeoutErr() error {
return fmt.Errorf("%s %s Task timed out after %s.00 seconds", time.Now().Format("2006-01-02T15:04:05.999Z"),
"1234", mc.Timeout)
}

View file

@ -0,0 +1,9 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const node_path_1 = require("node:path");
const node_child_process_1 = require("node:child_process");
const filename_1 = require("./filename");
const out = (0, filename_1.getOutputFile)();
const bootstrap = (0, node_path_1.join)(__dirname, out);
(0, node_child_process_1.spawn)(bootstrap, [], { stdio: 'inherit' });
//# sourceMappingURL=bootstrap.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"bootstrap.js","sourceRoot":"","sources":["../../../../src/runtimes/go1.x/bootstrap.ts"],"names":[],"mappings":";;AAAA,yCAAiC;AACjC,2DAA2C;AAC3C,yCAA2C;AAE3C,MAAM,GAAG,GAAG,IAAA,wBAAa,GAAE,CAAC;AAC5B,MAAM,SAAS,GAAG,IAAA,gBAAI,EAAC,SAAS,EAAE,GAAG,CAAC,CAAC;AACvC,IAAA,0BAAK,EAAC,SAAS,EAAE,EAAE,EAAE,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC,CAAC"}

View file

@ -0,0 +1 @@
export declare function getOutputFile(): string;

View file

@ -0,0 +1,9 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getOutputFile = void 0;
function getOutputFile() {
const ext = process.platform === 'win32' ? '.exe' : '';
return `bootstrap${ext}`;
}
exports.getOutputFile = getOutputFile;
//# sourceMappingURL=filename.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"filename.js","sourceRoot":"","sources":["../../../../src/runtimes/go1.x/filename.ts"],"names":[],"mappings":";;;AAAA,SAAgB,aAAa;IAC5B,MAAM,GAAG,GAAG,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC;IACvD,OAAO,YAAY,GAAG,EAAE,CAAC;AAC1B,CAAC;AAHD,sCAGC"}

View file

@ -0,0 +1,2 @@
import { Runtime } from '../../types';
export declare function init({ cacheDir }: Runtime): Promise<void>;

View file

@ -0,0 +1,57 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.init = void 0;
const node_path_1 = require("node:path");
const tinyexec_1 = require("tinyexec");
const debug_1 = __importDefault(require("debug"));
const promises_1 = require("node:fs/promises");
const filename_1 = require("./filename");
const debug = (0, debug_1.default)('@vercel/fun:runtimes/go1.x');
function _go(opts) {
return function go(...args) {
debug('Exec %o', `go ${args.join(' ')}`);
return (0, tinyexec_1.exec)('go', args, Object.assign({ stdio: 'inherit' }, opts));
};
}
function init({ cacheDir }) {
return __awaiter(this, void 0, void 0, function* () {
const source = (0, node_path_1.join)(cacheDir, 'bootstrap.go');
const out = (0, filename_1.getOutputFile)();
let data = yield (0, promises_1.readFile)(source, 'utf8');
// Fix windows
if (process.platform === 'win32') {
debug('detected windows, so stripping Setpgid');
data = data
.split('\n')
.filter(line => !line.includes('Setpgid'))
.join('\n');
}
// Prepare a temporary `$GOPATH`
const GOPATH = (0, node_path_1.join)(cacheDir, 'go');
// The source code must reside in `$GOPATH/src` for `go get` to work
const bootstrapDir = (0, node_path_1.join)(GOPATH, 'src', out);
yield (0, promises_1.mkdir)(bootstrapDir, { recursive: true });
yield (0, promises_1.writeFile)((0, node_path_1.join)(bootstrapDir, 'bootstrap.go'), data);
const go = _go({ cwd: bootstrapDir, env: Object.assign(Object.assign({}, process.env), { GOPATH }) });
const bootstrap = (0, node_path_1.join)(cacheDir, out);
debug('Compiling Go runtime binary %o -> %o', source, bootstrap);
yield go('get');
yield go('build', '-o', bootstrap, 'bootstrap.go');
// Clean up `$GOPATH` from the cacheDir
yield (0, promises_1.rm)(GOPATH, { recursive: true });
});
}
exports.init = init;
//# sourceMappingURL=index.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/runtimes/go1.x/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,yCAAiC;AACjC,uCAAgC;AAChC,kDAAgC;AAEhC,+CAA4E;AAC5E,yCAA2C;AAE3C,MAAM,KAAK,GAAG,IAAA,eAAW,EAAC,4BAA4B,CAAC,CAAC;AAExD,SAAS,GAAG,CAAC,IAAI;IAChB,OAAO,SAAS,EAAE,CAAC,GAAG,IAAI;QACzB,KAAK,CAAC,SAAS,EAAE,MAAM,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;QACzC,OAAO,IAAA,eAAI,EAAC,IAAI,EAAE,IAAI,kBAAI,KAAK,EAAE,SAAS,IAAK,IAAI,EAAG,CAAC;IACxD,CAAC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AK,CAAC,CAAC;QAChB,MAAM,EAAE,CAAC,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,cAAc,CAAC,CAAC;QAEnD,uCAAuC;QACvC,MAAM,IAAA,aAAM,EAAC,MAAM,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;IAC3C,CAAC;CAAA;AA9BD,oBA8BC"}

16
node_modules/@vercel/fun/dist/src/runtimes/nodejs/bootstrap generated vendored Executable file
View file

@ -0,0 +1,16 @@
#!/bin/sh
set -eu
# Credit: https://github.com/lambci/node-custom-lambda/blob/master/v10.x/bootstrap
# `NODE_PATH` is *not* a restricted env var, so only set the
# default one if the user did not provide one of their own
if [ -z "${NODE_PATH-}" ]; then
export NODE_PATH="/opt/nodejs/node8/node_modules:/opt/nodejs/node_modules:${LAMBDA_RUNTIME_DIR}/node_modules:${LAMBDA_RUNTIME_DIR}:${LAMBDA_TASK_ROOT}"
fi
exec node \
--expose-gc \
--max-semi-space-size=$((AWS_LAMBDA_FUNCTION_MEMORY_SIZE * 5 / 100)) \
--max-old-space-size=$((AWS_LAMBDA_FUNCTION_MEMORY_SIZE * 90 / 100)) \
"$LAMBDA_RUNTIME_DIR/bootstrap.js"

View file

@ -0,0 +1 @@
export {};

View file

@ -0,0 +1,204 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Credit: https://github.com/lambci/node-custom-lambda/blob/master/v10.x/bootstrap.js
*/
const http_1 = __importDefault(require("http"));
const RUNTIME_PATH = '/2018-06-01/runtime';
const { AWS_LAMBDA_FUNCTION_NAME, AWS_LAMBDA_FUNCTION_VERSION, AWS_LAMBDA_FUNCTION_MEMORY_SIZE, AWS_LAMBDA_LOG_GROUP_NAME, AWS_LAMBDA_LOG_STREAM_NAME, LAMBDA_TASK_ROOT, _HANDLER, AWS_LAMBDA_RUNTIME_API } = process.env;
delete process.env.SHLVL;
const [HOST, PORT] = AWS_LAMBDA_RUNTIME_API.split(':');
start();
// Simple `util.promisify()` polyfill for Node 6.x
function promisify(fn) {
return function (...args) {
return new Promise((resolve, reject) => {
args.push((err, result) => {
if (err)
return reject(err);
resolve(result);
});
const r = fn.apply(this, args);
if (typeof r !== 'undefined') {
resolve(r);
}
});
};
}
function start() {
return __awaiter(this, void 0, void 0, function* () {
let handler;
try {
handler = getHandler();
}
catch (e) {
yield initError(e);
return process.exit(1);
}
try {
yield processEvents(handler);
}
catch (e) {
console.error(e);
return process.exit(1);
}
});
}
function processEvents(handler) {
return __awaiter(this, void 0, void 0, function* () {
while (true) {
const { event, context } = yield nextInvocation();
let result;
try {
result = yield handler(event, context);
}
catch (e) {
yield invokeError(e, context);
continue;
}
yield invokeResponse(result, context);
}
});
}
function initError(err) {
return __awaiter(this, void 0, void 0, function* () {
return postError(`${RUNTIME_PATH}/init/error`, err);
});
}
function nextInvocation() {
return __awaiter(this, void 0, void 0, function* () {
const res = yield request({ path: `${RUNTIME_PATH}/invocation/next` });
if (res.statusCode !== 200) {
throw new Error(`Unexpected /invocation/next response: ${JSON.stringify(res)}`);
}
if (res.headers['lambda-runtime-trace-id']) {
process.env._X_AMZN_TRACE_ID = res.headers['lambda-runtime-trace-id'];
}
else {
delete process.env._X_AMZN_TRACE_ID;
}
const deadlineMs = Number(res.headers['lambda-runtime-deadline-ms']);
const awsRequestId = res.headers['lambda-runtime-aws-request-id'];
const context = {
callbackWaitsForEmptyEventLoop: false,
logGroupName: AWS_LAMBDA_LOG_GROUP_NAME,
logStreamName: AWS_LAMBDA_LOG_STREAM_NAME,
functionName: AWS_LAMBDA_FUNCTION_NAME,
memoryLimitInMB: AWS_LAMBDA_FUNCTION_MEMORY_SIZE,
functionVersion: AWS_LAMBDA_FUNCTION_VERSION,
invokeid: awsRequestId,
awsRequestId,
invokedFunctionArn: res.headers['lambda-runtime-invoked-function-arn'],
getRemainingTimeInMillis: () => deadlineMs - Date.now()
};
if (res.headers['lambda-runtime-client-context']) {
context.clientContext = JSON.parse(res.headers['lambda-runtime-client-context']);
}
if (res.headers['lambda-runtime-cognito-identity']) {
context.identity = JSON.parse(res.headers['lambda-runtime-cognito-identity']);
}
const event = JSON.parse(res.body);
return { event, context };
});
}
function invokeResponse(result, context) {
return __awaiter(this, void 0, void 0, function* () {
const res = yield request({
method: 'POST',
path: `${RUNTIME_PATH}/invocation/${context.awsRequestId}/response`,
body: JSON.stringify(result)
});
if (res.statusCode !== 202) {
throw new Error(`Unexpected /invocation/response response: ${JSON.stringify(res)}`);
}
});
}
function invokeError(err, context) {
return __awaiter(this, void 0, void 0, function* () {
return postError(`${RUNTIME_PATH}/invocation/${context.awsRequestId}/error`, err);
});
}
function postError(path, err) {
return __awaiter(this, void 0, void 0, function* () {
const lambdaErr = toLambdaErr(err);
const res = yield request({
method: 'POST',
path,
headers: {
'Content-Type': 'application/json',
'Lambda-Runtime-Function-Error-Type': lambdaErr.errorType
},
body: JSON.stringify(lambdaErr)
});
if (res.statusCode !== 202) {
throw new Error(`Unexpected ${path} response: ${JSON.stringify(res)}`);
}
});
}
function getHandler() {
const segments = _HANDLER.split('/');
const appParts = segments[segments.length - 1].split('.');
if (appParts.length !== 2) {
throw new Error(`Bad handler ${_HANDLER}`);
}
const [moduleFile, handlerName] = appParts;
const modulePath = [...segments.slice(0, -1), moduleFile].join('/');
let app;
try {
app = require(`${LAMBDA_TASK_ROOT}/${modulePath}`);
}
catch (e) {
if (e.code === 'MODULE_NOT_FOUND') {
throw new Error(`Unable to import module '${modulePath}'`);
}
throw e;
}
const userHandler = app[handlerName];
if (userHandler == null) {
throw new Error(`Handler '${handlerName}' missing on module '${modulePath}'`);
}
else if (typeof userHandler !== 'function') {
throw new Error(`Handler '${handlerName}' from '${modulePath}' is not a function`);
}
return userHandler.length >= 3 ? promisify(userHandler) : userHandler;
}
function request(options) {
return __awaiter(this, void 0, void 0, function* () {
options.host = HOST;
options.port = PORT;
return new Promise((resolve, reject) => {
const req = http_1.default.request(options, res => {
const bufs = [];
res.on('data', data => bufs.push(data));
res.on('end', () => resolve({
statusCode: res.statusCode,
headers: res.headers,
body: Buffer.concat(bufs).toString('utf8')
}));
res.on('error', reject);
});
req.on('error', reject);
req.end(options.body);
});
});
}
function toLambdaErr({ name, message, stack }) {
return {
errorType: name,
errorMessage: message,
stackTrace: (stack || '').split('\n').slice(1)
};
}
//# sourceMappingURL=bootstrap.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,9 @@
#!/bin/sh
set -eu
# Ensure the downloaded Node.js version is used
export PATH="$LAMBDA_RUNTIME_DIR/bin:$PATH"
# Execute the "nodejs" runtime bootstrap
export LAMBDA_RUNTIME_DIR="$(dirname "$0")/../nodejs"
exec "$LAMBDA_RUNTIME_DIR/bootstrap" "$@"

View file

@ -0,0 +1 @@
export {};

View file

@ -0,0 +1,8 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const node_path_1 = require("node:path");
const node_child_process_1 = require("node:child_process");
const nodeBin = (0, node_path_1.join)(__dirname, 'bin', 'node');
const bootstrap = (0, node_path_1.join)(__dirname, '..', 'nodejs', 'bootstrap.js');
(0, node_child_process_1.spawn)(nodeBin, [bootstrap], { stdio: 'inherit' });
//# sourceMappingURL=bootstrap.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"bootstrap.js","sourceRoot":"","sources":["../../../../src/runtimes/nodejs10.x/bootstrap.ts"],"names":[],"mappings":";;AAAA,yCAAiC;AACjC,2DAA2C;AAE3C,MAAM,OAAO,GAAG,IAAA,gBAAI,EAAC,SAAS,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC;AAC/C,MAAM,SAAS,GAAG,IAAA,gBAAI,EAAC,SAAS,EAAE,IAAI,EAAE,QAAQ,EAAE,cAAc,CAAC,CAAC;AAClE,IAAA,0BAAK,EAAC,OAAO,EAAE,CAAC,SAAS,CAAC,EAAE,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC,CAAC"}

View file

@ -0,0 +1,2 @@
import { Runtime } from '../../types';
export declare function init({ cacheDir }: Runtime): Promise<void>;

View file

@ -0,0 +1,24 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.init = void 0;
const install_node_1 = require("../../install-node");
const runtimes_1 = require("../../runtimes");
function init({ cacheDir }) {
return __awaiter(this, void 0, void 0, function* () {
yield Promise.all([
(0, runtimes_1.initializeRuntime)(runtimes_1.runtimes.nodejs),
(0, install_node_1.installNode)(cacheDir, '10.15.3')
]);
});
}
exports.init = init;
//# sourceMappingURL=index.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/runtimes/nodejs10.x/index.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,qDAAiD;AACjD,6CAA6D;AAE7D,SAAsB,IAAI,CAAC,EAAE,QAAQ,EAAW;;QAC/C,MAAM,OAAO,CAAC,GAAG,CAAC;YACjB,IAAA,4BAAiB,EAAC,mBAAQ,CAAC,MAAM,CAAC;YAClC,IAAA,0BAAW,EAAC,QAAQ,EAAE,SAAS,CAAC;SAChC,CAAC,CAAC;IACJ,CAAC;CAAA;AALD,oBAKC"}

View file

@ -0,0 +1,9 @@
#!/bin/sh
set -eu
# Ensure the downloaded Node.js version is used
export PATH="$LAMBDA_RUNTIME_DIR/bin:$PATH"
# Execute the "nodejs" runtime bootstrap
export LAMBDA_RUNTIME_DIR="$(dirname "$0")/../nodejs"
exec "$LAMBDA_RUNTIME_DIR/bootstrap" "$@"

View file

@ -0,0 +1 @@
export {};

View file

@ -0,0 +1,8 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const node_path_1 = require("node:path");
const node_child_process_1 = require("node:child_process");
const nodeBin = (0, node_path_1.join)(__dirname, 'bin', 'node');
const bootstrap = (0, node_path_1.join)(__dirname, '..', 'nodejs', 'bootstrap.js');
(0, node_child_process_1.spawn)(nodeBin, [bootstrap], { stdio: 'inherit' });
//# sourceMappingURL=bootstrap.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"bootstrap.js","sourceRoot":"","sources":["../../../../src/runtimes/nodejs12.x/bootstrap.ts"],"names":[],"mappings":";;AAAA,yCAAiC;AACjC,2DAA2C;AAE3C,MAAM,OAAO,GAAG,IAAA,gBAAI,EAAC,SAAS,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC;AAC/C,MAAM,SAAS,GAAG,IAAA,gBAAI,EAAC,SAAS,EAAE,IAAI,EAAE,QAAQ,EAAE,cAAc,CAAC,CAAC;AAClE,IAAA,0BAAK,EAAC,OAAO,EAAE,CAAC,SAAS,CAAC,EAAE,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC,CAAC"}

View file

@ -0,0 +1,2 @@
import { Runtime } from '../../types';
export declare function init({ cacheDir }: Runtime): Promise<void>;

View file

@ -0,0 +1,24 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.init = void 0;
const install_node_1 = require("../../install-node");
const runtimes_1 = require("../../runtimes");
function init({ cacheDir }) {
return __awaiter(this, void 0, void 0, function* () {
yield Promise.all([
(0, runtimes_1.initializeRuntime)(runtimes_1.runtimes.nodejs),
(0, install_node_1.installNode)(cacheDir, '12.22.7')
]);
});
}
exports.init = init;
//# sourceMappingURL=index.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/runtimes/nodejs12.x/index.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,qDAAiD;AACjD,6CAA6D;AAE7D,SAAsB,IAAI,CAAC,EAAE,QAAQ,EAAW;;QAC/C,MAAM,OAAO,CAAC,GAAG,CAAC;YACjB,IAAA,4BAAiB,EAAC,mBAAQ,CAAC,MAAM,CAAC;YAClC,IAAA,0BAAW,EAAC,QAAQ,EAAE,SAAS,CAAC;SAChC,CAAC,CAAC;IACJ,CAAC;CAAA;AALD,oBAKC"}

View file

@ -0,0 +1,9 @@
#!/bin/sh
set -eu
# Ensure the downloaded Node.js version is used
export PATH="$LAMBDA_RUNTIME_DIR/bin:$PATH"
# Execute the "nodejs" runtime bootstrap
export LAMBDA_RUNTIME_DIR="$(dirname "$0")/../nodejs"
exec "$LAMBDA_RUNTIME_DIR/bootstrap" "$@"

View file

@ -0,0 +1 @@
export {};

View file

@ -0,0 +1,8 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const node_path_1 = require("node:path");
const node_child_process_1 = require("node:child_process");
const nodeBin = (0, node_path_1.join)(__dirname, 'bin', 'node');
const bootstrap = (0, node_path_1.join)(__dirname, '..', 'nodejs', 'bootstrap.js');
(0, node_child_process_1.spawn)(nodeBin, [bootstrap], { stdio: 'inherit' });
//# sourceMappingURL=bootstrap.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"bootstrap.js","sourceRoot":"","sources":["../../../../src/runtimes/nodejs14.x/bootstrap.ts"],"names":[],"mappings":";;AAAA,yCAAiC;AACjC,2DAA2C;AAE3C,MAAM,OAAO,GAAG,IAAA,gBAAI,EAAC,SAAS,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC;AAC/C,MAAM,SAAS,GAAG,IAAA,gBAAI,EAAC,SAAS,EAAE,IAAI,EAAE,QAAQ,EAAE,cAAc,CAAC,CAAC;AAClE,IAAA,0BAAK,EAAC,OAAO,EAAE,CAAC,SAAS,CAAC,EAAE,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC,CAAC"}

View file

@ -0,0 +1,2 @@
import { Runtime } from '../../types';
export declare function init({ cacheDir }: Runtime): Promise<void>;

View file

@ -0,0 +1,24 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.init = void 0;
const install_node_1 = require("../../install-node");
const runtimes_1 = require("../../runtimes");
function init({ cacheDir }) {
return __awaiter(this, void 0, void 0, function* () {
yield Promise.all([
(0, runtimes_1.initializeRuntime)(runtimes_1.runtimes.nodejs),
(0, install_node_1.installNode)(cacheDir, '14.18.1')
]);
});
}
exports.init = init;
//# sourceMappingURL=index.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/runtimes/nodejs14.x/index.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,qDAAiD;AACjD,6CAA6D;AAE7D,SAAsB,IAAI,CAAC,EAAE,QAAQ,EAAW;;QAC/C,MAAM,OAAO,CAAC,GAAG,CAAC;YACjB,IAAA,4BAAiB,EAAC,mBAAQ,CAAC,MAAM,CAAC;YAClC,IAAA,0BAAW,EAAC,QAAQ,EAAE,SAAS,CAAC;SAChC,CAAC,CAAC;IACJ,CAAC;CAAA;AALD,oBAKC"}

View file

@ -0,0 +1,9 @@
#!/bin/sh
set -eu
# Ensure the downloaded Node.js version is used
export PATH="$LAMBDA_RUNTIME_DIR/bin:$PATH"
# Execute the "nodejs" runtime bootstrap
export LAMBDA_RUNTIME_DIR="$(dirname "$0")/../nodejs"
exec "$LAMBDA_RUNTIME_DIR/bootstrap" "$@"

View file

@ -0,0 +1 @@
export {};

View file

@ -0,0 +1,8 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const node_path_1 = require("node:path");
const node_child_process_1 = require("node:child_process");
const nodeBin = (0, node_path_1.join)(__dirname, 'bin', 'node');
const bootstrap = (0, node_path_1.join)(__dirname, '..', 'nodejs', 'bootstrap.js');
(0, node_child_process_1.spawn)(nodeBin, [bootstrap], { stdio: 'inherit' });
//# sourceMappingURL=bootstrap.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"bootstrap.js","sourceRoot":"","sources":["../../../../src/runtimes/nodejs6.10/bootstrap.ts"],"names":[],"mappings":";;AAAA,yCAAiC;AACjC,2DAA2C;AAE3C,MAAM,OAAO,GAAG,IAAA,gBAAI,EAAC,SAAS,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC;AAC/C,MAAM,SAAS,GAAG,IAAA,gBAAI,EAAC,SAAS,EAAE,IAAI,EAAE,QAAQ,EAAE,cAAc,CAAC,CAAC;AAClE,IAAA,0BAAK,EAAC,OAAO,EAAE,CAAC,SAAS,CAAC,EAAE,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC,CAAC"}

View file

@ -0,0 +1,2 @@
import { Runtime } from '../../types';
export declare function init({ cacheDir }: Runtime): Promise<void>;

View file

@ -0,0 +1,24 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.init = void 0;
const install_node_1 = require("../../install-node");
const runtimes_1 = require("../../runtimes");
function init({ cacheDir }) {
return __awaiter(this, void 0, void 0, function* () {
yield Promise.all([
(0, runtimes_1.initializeRuntime)(runtimes_1.runtimes.nodejs),
(0, install_node_1.installNode)(cacheDir, '6.10.0')
]);
});
}
exports.init = init;
//# sourceMappingURL=index.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/runtimes/nodejs6.10/index.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,qDAAiD;AACjD,6CAA6D;AAE7D,SAAsB,IAAI,CAAC,EAAE,QAAQ,EAAW;;QAC/C,MAAM,OAAO,CAAC,GAAG,CAAC;YACjB,IAAA,4BAAiB,EAAC,mBAAQ,CAAC,MAAM,CAAC;YAClC,IAAA,0BAAW,EAAC,QAAQ,EAAE,QAAQ,CAAC;SAC/B,CAAC,CAAC;IACJ,CAAC;CAAA;AALD,oBAKC"}

View file

@ -0,0 +1,9 @@
#!/bin/sh
set -eu
# Ensure the downloaded Node.js version is used
export PATH="$LAMBDA_RUNTIME_DIR/bin:$PATH"
# Execute the "nodejs" runtime bootstrap
export LAMBDA_RUNTIME_DIR="$(dirname "$0")/../nodejs"
exec "$LAMBDA_RUNTIME_DIR/bootstrap" "$@"

View file

@ -0,0 +1 @@
export {};

View file

@ -0,0 +1,8 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const node_path_1 = require("node:path");
const node_child_process_1 = require("node:child_process");
const nodeBin = (0, node_path_1.join)(__dirname, 'bin', 'node');
const bootstrap = (0, node_path_1.join)(__dirname, '..', 'nodejs', 'bootstrap.js');
(0, node_child_process_1.spawn)(nodeBin, [bootstrap], { stdio: 'inherit' });
//# sourceMappingURL=bootstrap.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"bootstrap.js","sourceRoot":"","sources":["../../../../src/runtimes/nodejs8.10/bootstrap.ts"],"names":[],"mappings":";;AAAA,yCAAiC;AACjC,2DAA2C;AAE3C,MAAM,OAAO,GAAG,IAAA,gBAAI,EAAC,SAAS,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC;AAC/C,MAAM,SAAS,GAAG,IAAA,gBAAI,EAAC,SAAS,EAAE,IAAI,EAAE,QAAQ,EAAE,cAAc,CAAC,CAAC;AAClE,IAAA,0BAAK,EAAC,OAAO,EAAE,CAAC,SAAS,CAAC,EAAE,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC,CAAC"}

View file

@ -0,0 +1,2 @@
import { Runtime } from '../../types';
export declare function init({ cacheDir }: Runtime): Promise<void>;

View file

@ -0,0 +1,24 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.init = void 0;
const install_node_1 = require("../../install-node");
const runtimes_1 = require("../../runtimes");
function init({ cacheDir }) {
return __awaiter(this, void 0, void 0, function* () {
yield Promise.all([
(0, runtimes_1.initializeRuntime)(runtimes_1.runtimes.nodejs),
(0, install_node_1.installNode)(cacheDir, '8.10.0')
]);
});
}
exports.init = init;
//# sourceMappingURL=index.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/runtimes/nodejs8.10/index.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,qDAAiD;AACjD,6CAA6D;AAE7D,SAAsB,IAAI,CAAC,EAAE,QAAQ,EAAW;;QAC/C,MAAM,OAAO,CAAC,GAAG,CAAC;YACjB,IAAA,4BAAiB,EAAC,mBAAQ,CAAC,MAAM,CAAC;YAClC,IAAA,0BAAW,EAAC,QAAQ,EAAE,QAAQ,CAAC;SAC/B,CAAC,CAAC;IACJ,CAAC;CAAA;AALD,oBAKC"}

View file

@ -0,0 +1,3 @@
#!/bin/bash
# Delegate out to the provided `bootstrap` file
exec "$LAMBDA_TASK_ROOT/bootstrap" "$@"

View file

@ -0,0 +1 @@
export {};

View file

@ -0,0 +1,8 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const node_path_1 = require("node:path");
const node_child_process_1 = require("node:child_process");
// Delegate out to the provided `bootstrap` file within the lambda
const bootstrap = (0, node_path_1.join)(process.env.LAMBDA_TASK_ROOT, 'bootstrap');
(0, node_child_process_1.spawn)(bootstrap, [], { stdio: 'inherit' });
//# sourceMappingURL=bootstrap.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"bootstrap.js","sourceRoot":"","sources":["../../../../src/runtimes/provided/bootstrap.ts"],"names":[],"mappings":";;AAAA,yCAAiC;AACjC,2DAA2C;AAE3C,kEAAkE;AAClE,MAAM,SAAS,GAAG,IAAA,gBAAI,EAAC,OAAO,CAAC,GAAG,CAAC,gBAAgB,EAAE,WAAW,CAAC,CAAC;AAClE,IAAA,0BAAK,EAAC,SAAS,EAAE,EAAE,EAAE,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC,CAAC"}

10
node_modules/@vercel/fun/dist/src/runtimes/python/bootstrap generated vendored Executable file
View file

@ -0,0 +1,10 @@
#!/bin/sh
set -eu
# `PYTHONPATH` is *not* a restricted env var, so only set the
# default one if the user did not provide one of their own
if [ -z "${PYTHONPATH-}" ]; then
export PYTHONPATH="$LAMBDA_RUNTIME_DIR"
fi
exec python "$LAMBDA_RUNTIME_DIR/bootstrap.py"

View file

@ -0,0 +1 @@
export {};

View file

@ -0,0 +1,12 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const node_path_1 = require("node:path");
const node_child_process_1 = require("node:child_process");
// `PYTHONPATH` is *not* a restricted env var, so only set the
// default one if the user did not provide one of their own
if (!process.env.PYTHONPATH) {
process.env.PYTHONPATH = process.env.LAMBDA_RUNTIME_DIR;
}
const bootstrap = (0, node_path_1.join)(__dirname, 'bootstrap.py');
(0, node_child_process_1.spawn)('python', [bootstrap], { stdio: 'inherit' });
//# sourceMappingURL=bootstrap.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"bootstrap.js","sourceRoot":"","sources":["../../../../src/runtimes/python/bootstrap.ts"],"names":[],"mappings":";;AAAA,yCAAiC;AACjC,2DAA2C;AAE3C,8DAA8D;AAC9D,2DAA2D;AAC3D,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,UAAU,EAAE;IAC5B,OAAO,CAAC,GAAG,CAAC,UAAU,GAAG,OAAO,CAAC,GAAG,CAAC,kBAAkB,CAAC;CACxD;AAED,MAAM,SAAS,GAAG,IAAA,gBAAI,EAAC,SAAS,EAAE,cAAc,CAAC,CAAC;AAClD,IAAA,0BAAK,EAAC,QAAQ,EAAE,CAAC,SAAS,CAAC,EAAE,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC,CAAC"}

View file

@ -0,0 +1,147 @@
# Parts of this runtime based off of:
# https://gist.github.com/avoidik/78ddc7854c7b88607f7cf56db3e591e5
import os
import sys
import json
import importlib
is_python_3 = sys.version_info > (3, 0)
if is_python_3:
import urllib.request
else:
import urllib2
class LambdaRequest:
def __init__(self, path, data=None):
req = None
runtime_path = '/2018-06-01/runtime/'
url = (
'http://'
+ os.environ.get(
'AWS_LAMBDA_RUNTIME_API', '127.0.0.1:3000'
)
+ runtime_path
+ path
)
if is_python_3:
req = urllib.request.urlopen(url, data)
else:
req = urllib2.urlopen(url, data)
info = req.info()
body = req.read()
if is_python_3:
body = body.decode(encoding='UTF-8')
self.status_code = req.getcode()
self.body = body
self.info = info
def get_header(self, name):
if is_python_3:
return self.info.get(name)
else:
return self.info.getheader(name)
def get_json_body(self):
return json.loads(self.body)
def lambda_runtime_next_invocation():
res = LambdaRequest('invocation/next')
if res.status_code != 200:
raise Exception(
'Unexpected /invocation/next response: '
+ res.body
)
x_amzn_trace_id = res.get_header('Lambda-Runtime-Trace-Id')
if x_amzn_trace_id != None:
os.environ['_X_AMZN_TRACE_ID'] = x_amzn_trace_id
elif '_X_AMZN_TRACE_ID' in os.environ:
del os.environ['_X_AMZN_TRACE_ID']
aws_request_id = res.get_header('Lambda-Runtime-Aws-Request-Id')
context = {
# TODO: fill this out
'aws_request_id': aws_request_id
}
event = res.get_json_body()
return (event, context)
def lambda_runtime_invoke_response(result, context):
body = json.dumps(result, separators=(',', ':')).encode(
encoding='UTF-8'
)
res = LambdaRequest(
'invocation/'
+ context['aws_request_id']
+ '/response',
body,
)
if res.status_code != 202:
raise Exception(
'Unexpected /invocation/response response: '
+ res.body
)
def lambda_runtime_invoke_error(err, context):
body = json.dumps(err, separators=(',', ':')).encode(
encoding='UTF-8'
)
res = LambdaRequest(
'invocation/'
+ context['aws_request_id']
+ '/error',
body,
)
def lambda_runtime_get_handler():
(module_name, handler_name) = os.environ['_HANDLER'].split('.')
mod = importlib.import_module(module_name)
# TODO: invoke `__init__`?
return getattr(mod, handler_name)
def lambda_runtime_main():
if not is_python_3:
reload(sys)
sys.setdefaultencoding('utf-8')
sys.path.insert(
0, os.environ.get('LAMBDA_TASK_ROOT', '/var/task')
)
fn = lambda_runtime_get_handler()
while True:
(event, context) = lambda_runtime_next_invocation()
# print(event)
# print(context)
result = None
try:
result = fn(event, context)
except:
err = str(sys.exc_info()[0])
print(err)
lambda_runtime_invoke_error(
{'error': err}, context
)
else:
lambda_runtime_invoke_response(result, context)
if __name__ == '__main__':
lambda_runtime_main()

View file

@ -0,0 +1,9 @@
#!/bin/sh
set -eu
# Ensure the downloaded Python version is used
export PATH="$LAMBDA_RUNTIME_DIR/bin:$PATH"
# Execute the "python" runtime bootstrap
export LAMBDA_RUNTIME_DIR="$(dirname "$0")/../python"
exec "$LAMBDA_RUNTIME_DIR/bootstrap" "$@"

View file

@ -0,0 +1 @@
export {};

View file

@ -0,0 +1,8 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const node_path_1 = require("node:path");
const node_child_process_1 = require("node:child_process");
const pythonBin = (0, node_path_1.join)(__dirname, 'bin', 'python');
const bootstrap = (0, node_path_1.join)(__dirname, '..', 'python', 'bootstrap.py');
(0, node_child_process_1.spawn)(pythonBin, [bootstrap], { stdio: 'inherit' });
//# sourceMappingURL=bootstrap.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"bootstrap.js","sourceRoot":"","sources":["../../../../src/runtimes/python2.7/bootstrap.ts"],"names":[],"mappings":";;AAAA,yCAAiC;AACjC,2DAA2C;AAE3C,MAAM,SAAS,GAAG,IAAA,gBAAI,EAAC,SAAS,EAAE,KAAK,EAAE,QAAQ,CAAC,CAAC;AACnD,MAAM,SAAS,GAAG,IAAA,gBAAI,EAAC,SAAS,EAAE,IAAI,EAAE,QAAQ,EAAE,cAAc,CAAC,CAAC;AAClE,IAAA,0BAAK,EAAC,SAAS,EAAE,CAAC,SAAS,CAAC,EAAE,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC,CAAC"}

View file

@ -0,0 +1,2 @@
import { Runtime } from '../../types';
export declare function init({ cacheDir }: Runtime): Promise<void>;

View file

@ -0,0 +1,24 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.init = void 0;
const install_python_1 = require("../../install-python");
const runtimes_1 = require("../../runtimes");
function init({ cacheDir }) {
return __awaiter(this, void 0, void 0, function* () {
yield Promise.all([
(0, runtimes_1.initializeRuntime)(runtimes_1.runtimes.python),
(0, install_python_1.installPython)(cacheDir, '2.7.12')
]);
});
}
exports.init = init;
//# sourceMappingURL=index.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/runtimes/python2.7/index.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,yDAAqD;AACrD,6CAA6D;AAE7D,SAAsB,IAAI,CAAC,EAAE,QAAQ,EAAW;;QAC/C,MAAM,OAAO,CAAC,GAAG,CAAC;YACjB,IAAA,4BAAiB,EAAC,mBAAQ,CAAC,MAAM,CAAC;YAClC,IAAA,8BAAa,EAAC,QAAQ,EAAE,QAAQ,CAAC;SACjC,CAAC,CAAC;IACJ,CAAC;CAAA;AALD,oBAKC"}

View file

@ -0,0 +1,9 @@
#!/bin/sh
set -eu
# Ensure the downloaded Python version is used
export PATH="$LAMBDA_RUNTIME_DIR/bin:$PATH"
# Execute the "python" runtime bootstrap
export LAMBDA_RUNTIME_DIR="$(dirname "$0")/../python"
exec "$LAMBDA_RUNTIME_DIR/bootstrap" "$@"

Some files were not shown because too many files have changed in this diff Show more