From 587a9120a651f2e84c2d4ad082ede42fe55cc72e Mon Sep 17 00:00:00 2001 From: ehmicky Date: Tue, 8 Feb 2022 19:23:49 +0100 Subject: [PATCH] fix: simplify imports/exports of ES modules (#976) Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com> --- src/archive.ts | 17 ++++------ src/config.ts | 9 ++--- src/feature_flags.ts | 11 +++---- src/function.ts | 8 ++--- src/main.ts | 12 +++---- src/manifest.ts | 7 ++-- src/runtimes/detect_runtime.ts | 4 +-- src/runtimes/go/builder.ts | 4 +-- src/runtimes/index.ts | 6 ++-- src/runtimes/node/bundlers/esbuild/bundler.ts | 6 ++-- .../node/bundlers/esbuild/bundler_target.ts | 4 +-- .../esbuild/plugin_dynamic_imports.ts | 4 +-- .../bundlers/esbuild/plugin_native_modules.ts | 4 +-- .../bundlers/esbuild/plugin_node_builtin.ts | 4 +-- .../node/bundlers/esbuild/special_cases.ts | 4 +-- .../node/bundlers/esbuild/src_files.ts | 4 +-- src/runtimes/node/bundlers/index.ts | 13 +++----- src/runtimes/node/bundlers/nft/es_modules.ts | 4 +-- src/runtimes/node/bundlers/nft/transpile.ts | 4 +-- .../node/bundlers/zisi/list_imports.ts | 10 ++++-- src/runtimes/node/bundlers/zisi/nested.ts | 6 ++-- src/runtimes/node/bundlers/zisi/published.ts | 4 +-- src/runtimes/node/bundlers/zisi/resolve.ts | 6 ++-- src/runtimes/node/bundlers/zisi/side_files.ts | 4 +-- src/runtimes/node/bundlers/zisi/src_files.ts | 4 +-- src/runtimes/node/bundlers/zisi/traverse.ts | 4 +-- src/runtimes/node/bundlers/zisi/tree_files.ts | 4 +-- src/runtimes/node/bundlers/zisi/tree_shake.ts | 4 +-- src/runtimes/node/finder.ts | 6 ++-- src/runtimes/node/in_source_config/index.ts | 17 ++++------ src/runtimes/node/parser/exports.ts | 4 +-- src/runtimes/node/parser/helpers.ts | 8 ++--- src/runtimes/node/parser/imports.ts | 4 +-- src/runtimes/node/parser/index.ts | 6 ++-- src/runtimes/node/utils/base_path.ts | 4 +-- src/runtimes/node/utils/detect_es_module.ts | 4 +-- .../node/utils/detect_native_module.ts | 4 +-- src/runtimes/node/utils/entry_file.ts | 6 ++-- src/runtimes/node/utils/included_files.ts | 6 ++-- src/runtimes/node/utils/module.ts | 4 +-- src/runtimes/node/utils/node_version.ts | 21 ++++-------- src/runtimes/node/utils/normalize_path.ts | 4 +-- src/runtimes/node/utils/package_json.ts | 10 +++--- .../node/utils/plugin_modules_path.ts | 6 ++-- src/runtimes/node/utils/traversal_cache.ts | 6 ++-- src/runtimes/node/utils/zip.ts | 6 ++-- src/runtimes/runtime.ts | 24 ++++---------- src/runtimes/rust/builder.ts | 4 +-- src/runtimes/rust/cargo_manifest.ts | 4 +-- src/runtimes/rust/constants.ts | 6 ++-- src/utils/archive_size.ts | 4 +-- src/utils/format_result.ts | 7 ++-- src/utils/fs.ts | 33 ++++++------------- src/utils/non_nullable.ts | 4 +-- src/utils/remove_undefined.ts | 4 +-- src/zip.ts | 6 ++-- src/zip_binary.ts | 4 +-- .../conflicting-names-3/function/index.ts | 4 +-- .../fixtures/conflicting-names-4/function.ts | 4 +-- tests/fixtures/esm-throwing-error/function.js | 4 +-- tests/fixtures/list/five/util.ts | 4 +-- .../node-cjs-importing-mjs/lib/file.mjs | 4 +-- .../function/function.ts | 4 +-- .../function/index.ts | 4 +-- .../functions/function.ts | 4 +-- .../function.ts | 4 +-- .../node-typescript-with-imports/function.ts | 4 +-- .../node-typescript-with-imports/lib/util.ts | 4 +-- tests/fixtures/node-typescript/function.ts | 4 +-- 69 files changed, 142 insertions(+), 307 deletions(-) diff --git a/src/archive.ts b/src/archive.ts index 73bc72b0e..4b8209e80 100644 --- a/src/archive.ts +++ b/src/archive.ts @@ -6,12 +6,14 @@ import { promisify } from 'util' import archiver, { Archiver } from 'archiver' import endOfStream from 'end-of-stream' -type ArchiveFormat = 'none' | 'zip' +export { Archiver as ZipArchive } from 'archiver' + +export type ArchiveFormat = 'none' | 'zip' const pEndOfStream = promisify(endOfStream) // Start zipping files -const startZip = function (destPath: string): { archive: Archiver; output: Writable } { +export const startZip = function (destPath: string): { archive: Archiver; output: Writable } { const output = createWriteStream(destPath) const archive = archiver('zip') archive.pipe(output) @@ -19,7 +21,7 @@ const startZip = function (destPath: string): { archive: Archiver; output: Writa } // Add new file to zip -const addZipFile = function (archive: Archiver, file: string, name: string, stat: Stats): void { +export const addZipFile = function (archive: Archiver, file: string, name: string, stat: Stats): void { if (stat.isSymbolicLink()) { const linkContent = readlinkSync(file) archive.symlink(name, linkContent, stat.mode) @@ -35,17 +37,12 @@ const addZipFile = function (archive: Archiver, file: string, name: string, stat } // Add new file content to zip -const addZipContent = function (archive: Archiver, content: Buffer | string, name: string): void { +export const addZipContent = function (archive: Archiver, content: Buffer | string, name: string): void { archive.append(content, { name, date: new Date(0) }) } // End zipping files -const endZip = async function (archive: Archiver, output: Writable): Promise { +export const endZip = async function (archive: Archiver, output: Writable): Promise { archive.finalize() await pEndOfStream(output) } - -export { startZip, addZipFile, addZipContent, endZip } -export type { ArchiveFormat } - -export { Archiver as ZipArchive } from 'archiver' diff --git a/src/config.ts b/src/config.ts index 4c03184b9..09f995370 100644 --- a/src/config.ts +++ b/src/config.ts @@ -5,7 +5,7 @@ import { FunctionSource } from './function' import type { NodeVersionString } from './runtimes/node' import type { NodeBundlerName } from './runtimes/node/bundlers' -interface FunctionConfig { +export interface FunctionConfig { externalNodeModules?: string[] includedFiles?: string[] includedFilesBasePath?: string @@ -21,9 +21,9 @@ interface FunctionConfig { type GlobPattern = string -type Config = Record +export type Config = Record -const getConfigForFunction = ({ +export const getConfigForFunction = ({ config, func, }: { @@ -56,6 +56,3 @@ const getConfigForFunction = ({ return mergeOptions.apply({ concatArrays: true, ignoreUndefined: true }, matches) } - -export { getConfigForFunction } -export type { Config, FunctionConfig } diff --git a/src/feature_flags.ts b/src/feature_flags.ts index 8ff5a514b..b4e741c9f 100644 --- a/src/feature_flags.ts +++ b/src/feature_flags.ts @@ -1,6 +1,6 @@ import { env } from 'process' -const FLAGS: Record = { +export const defaultFlags: Record = { buildGoSource: Boolean(env.NETLIFY_EXPERIMENTAL_BUILD_GO_SOURCE), buildRustSource: Boolean(env.NETLIFY_EXPERIMENTAL_BUILD_RUST_SOURCE), defaultEsModulesToEsbuild: Boolean(env.NETLIFY_EXPERIMENTAL_DEFAULT_ES_MODULES_TO_ESBUILD), @@ -9,12 +9,12 @@ const FLAGS: Record = { zisi_pure_esm: false, } -type FeatureFlag = keyof typeof FLAGS -type FeatureFlags = Record +export type FeatureFlag = keyof typeof defaultFlags +export type FeatureFlags = Record // List of supported flags and their default value. -const getFlags = (input: Record = {}, flags = FLAGS) => +export const getFlags = (input: Record = {}, flags = defaultFlags) => Object.entries(flags).reduce( (result, [key, defaultValue]) => ({ ...result, @@ -22,6 +22,3 @@ const getFlags = (input: Record = {}, flags = FLAGS) => }), {}, ) - -export { FLAGS as defaultFlags, getFlags } -export type { FeatureFlag, FeatureFlags } diff --git a/src/function.ts b/src/function.ts index e1ca17bfa..47ae72ddb 100644 --- a/src/function.ts +++ b/src/function.ts @@ -4,7 +4,7 @@ import type { FunctionConfig } from './config' import type { Runtime, ZipFunctionResult } from './runtimes/runtime' // A function that has been processed and turned into an archive. -type FunctionArchive = ZipFunctionResult & { +export type FunctionArchive = ZipFunctionResult & { mainFile: string name: string runtime: Runtime @@ -12,7 +12,7 @@ type FunctionArchive = ZipFunctionResult & { } // A function file found on the filesystem. -interface SourceFile { +export interface SourceFile { extension: string filename: string mainFile: string @@ -23,9 +23,7 @@ interface SourceFile { } // A function associated with a runtime. -type FunctionSource = SourceFile & { +export type FunctionSource = SourceFile & { config: FunctionConfig runtime: Runtime } - -export { FunctionArchive, FunctionSource, SourceFile } diff --git a/src/main.ts b/src/main.ts index 40df970a9..81ff23a51 100644 --- a/src/main.ts +++ b/src/main.ts @@ -8,6 +8,8 @@ import { findISCDeclarationsInPath, ISCValues } from './runtimes/node/in_source_ import { GetSrcFilesFunction, RuntimeName } from './runtimes/runtime' import { listFunctionsDirectories, resolveFunctionsDirectories } from './utils/fs' +export { zipFunction, zipFunctions } from './zip' + interface ListedFunction { name: string mainFile: string @@ -42,7 +44,7 @@ const augmentWithISC = async (func: FunctionSource): Promise { +export const createManifest = async ({ functions, path }: { functions: FunctionResult[]; path: string }) => { const formattedFunctions = functions.map(formatFunctionForManifest) const payload: Manifest = { functions: formattedFunctions, @@ -43,6 +43,3 @@ const formatFunctionForManifest = ({ mainFile, name, path, runtime, schedule }: runtime, schedule, }) - -export { createManifest } -export type { Manifest } diff --git a/src/runtimes/detect_runtime.ts b/src/runtimes/detect_runtime.ts index 8f0f80247..316b0bd2d 100644 --- a/src/runtimes/detect_runtime.ts +++ b/src/runtimes/detect_runtime.ts @@ -7,7 +7,7 @@ import { cachedReadFile, FsCache } from '../utils/fs' import type { RuntimeName } from './runtime' // Try to guess the runtime by inspecting the binary file. -const detectBinaryRuntime = async function ({ +export const detectBinaryRuntime = async function ({ fsCache, path, }: { @@ -32,5 +32,3 @@ const detectBinaryRuntime = async function ({ } } catch {} } - -export { detectBinaryRuntime } diff --git a/src/runtimes/go/builder.ts b/src/runtimes/go/builder.ts index a987b7e4d..eb23658b2 100644 --- a/src/runtimes/go/builder.ts +++ b/src/runtimes/go/builder.ts @@ -4,7 +4,7 @@ import { basename } from 'path' import { shellUtils } from '../../utils/shell' import type { RuntimeName } from '../runtime' -const build = async ({ destPath, mainFile, srcDir }: { destPath: string; mainFile: string; srcDir: string }) => { +export const build = async ({ destPath, mainFile, srcDir }: { destPath: string; mainFile: string; srcDir: string }) => { const functionName = basename(srcDir) try { @@ -34,5 +34,3 @@ const build = async ({ destPath, mainFile, srcDir }: { destPath: string; mainFil stat, } } - -export { build } diff --git a/src/runtimes/index.ts b/src/runtimes/index.ts index b4050bb2a..5e9e762c1 100644 --- a/src/runtimes/index.ts +++ b/src/runtimes/index.ts @@ -75,7 +75,7 @@ const RUNTIMES = [jsRuntime, goRuntime, rustRuntime] /** * Gets a list of functions found in a list of paths. */ -const getFunctionsFromPaths = async ( +export const getFunctionsFromPaths = async ( paths: string[], { config, @@ -115,7 +115,7 @@ const getFunctionsFromPaths = async ( /** * Gets a list of functions found in a list of paths. */ -const getFunctionFromPath = async ( +export const getFunctionFromPath = async ( path: string, { config, featureFlags = defaultFlags }: { config?: Config; featureFlags?: FeatureFlags } = {}, ): Promise => { @@ -134,5 +134,3 @@ const getFunctionFromPath = async ( return undefined } - -export { getFunctionsFromPaths, getFunctionFromPath } diff --git a/src/runtimes/node/bundlers/esbuild/bundler.ts b/src/runtimes/node/bundlers/esbuild/bundler.ts index 097a727df..78339b4f4 100644 --- a/src/runtimes/node/bundlers/esbuild/bundler.ts +++ b/src/runtimes/node/bundlers/esbuild/bundler.ts @@ -16,14 +16,14 @@ import { getNodeBuiltinPlugin } from './plugin_node_builtin' // Maximum number of log messages that an esbuild instance will produce. This // limit is important to avoid out-of-memory errors due to too much data being // sent in the Go<>Node IPC channel. -const ESBUILD_LOG_LIMIT = 10 +export const ESBUILD_LOG_LIMIT = 10 // When resolving imports with no extension (e.g. require('./foo')), these are // the extensions that esbuild will look for, in this order. const RESOLVE_EXTENSIONS = ['.js', '.jsx', '.mjs', '.cjs', '.ts', '.json'] // eslint-disable-next-line max-statements -const bundleJsFile = async function ({ +export const bundleJsFile = async function ({ additionalModulePaths, basePath, config, @@ -173,5 +173,3 @@ const getBundlePaths = ({ const getCleanupFunction = (paths: string[]) => async () => { await Promise.all(paths.filter(Boolean).map(safeUnlink)) } - -export { bundleJsFile, ESBUILD_LOG_LIMIT } diff --git a/src/runtimes/node/bundlers/esbuild/bundler_target.ts b/src/runtimes/node/bundlers/esbuild/bundler_target.ts index 9f7d6d4c4..9409430a3 100644 --- a/src/runtimes/node/bundlers/esbuild/bundler_target.ts +++ b/src/runtimes/node/bundlers/esbuild/bundler_target.ts @@ -10,7 +10,7 @@ const versionMap = { type VersionKeys = keyof typeof versionMap type VersionValues = typeof versionMap[VersionKeys] -const getBundlerTarget = (suppliedVersion?: string): VersionValues => { +export const getBundlerTarget = (suppliedVersion?: string): VersionValues => { const version = normalizeVersion(suppliedVersion) if (version && version in versionMap) { @@ -25,5 +25,3 @@ const normalizeVersion = (version?: string) => { return match ? match[1] : version } - -export { getBundlerTarget } diff --git a/src/runtimes/node/bundlers/esbuild/plugin_dynamic_imports.ts b/src/runtimes/node/bundlers/esbuild/plugin_dynamic_imports.ts index 87e1f778a..c17c67a02 100644 --- a/src/runtimes/node/bundlers/esbuild/plugin_dynamic_imports.ts +++ b/src/runtimes/node/bundlers/esbuild/plugin_dynamic_imports.ts @@ -16,7 +16,7 @@ type PackageCache = Map> // issues. Secondly, it parses the dynamic expressions and tries to include in // the bundle all the files that are possibly needed to make the import work at // runtime. This is not always possible, but we do our best. -const getDynamicImportsPlugin = ({ +export const getDynamicImportsPlugin = ({ basePath, includedPaths, moduleNames, @@ -153,5 +153,3 @@ const registerModuleWithDynamicImports = async ({ // no-op } } - -export { getDynamicImportsPlugin } diff --git a/src/runtimes/node/bundlers/esbuild/plugin_native_modules.ts b/src/runtimes/node/bundlers/esbuild/plugin_native_modules.ts index dd473ab97..ce1508d14 100644 --- a/src/runtimes/node/bundlers/esbuild/plugin_native_modules.ts +++ b/src/runtimes/node/bundlers/esbuild/plugin_native_modules.ts @@ -28,7 +28,7 @@ const findNativeModule = (packageJsonPath: string, cache: NativeModuleCache) => return cache[packageJsonPath] } -const getNativeModulesPlugin = (externalizedModules: NativeNodeModules): Plugin => ({ +export const getNativeModulesPlugin = (externalizedModules: NativeNodeModules): Plugin => ({ name: 'external-native-modules', setup(build) { const cache: NativeModuleCache = {} @@ -78,5 +78,3 @@ const getNativeModulesPlugin = (externalizedModules: NativeNodeModules): Plugin }) }, }) - -export { getNativeModulesPlugin } diff --git a/src/runtimes/node/bundlers/esbuild/plugin_node_builtin.ts b/src/runtimes/node/bundlers/esbuild/plugin_node_builtin.ts index 1178b0523..85f0ef7ce 100644 --- a/src/runtimes/node/bundlers/esbuild/plugin_node_builtin.ts +++ b/src/runtimes/node/bundlers/esbuild/plugin_node_builtin.ts @@ -1,10 +1,8 @@ import type { Plugin } from '@netlify/esbuild' -const getNodeBuiltinPlugin = (): Plugin => ({ +export const getNodeBuiltinPlugin = (): Plugin => ({ name: 'builtin-modules', setup(build) { build.onResolve({ filter: /^node:/ }, (args) => ({ path: args.path.slice('node:'.length), external: true })) }, }) - -export { getNodeBuiltinPlugin } diff --git a/src/runtimes/node/bundlers/esbuild/special_cases.ts b/src/runtimes/node/bundlers/esbuild/special_cases.ts index 8b0086281..a637e3c18 100644 --- a/src/runtimes/node/bundlers/esbuild/special_cases.ts +++ b/src/runtimes/node/bundlers/esbuild/special_cases.ts @@ -14,7 +14,7 @@ const getModulesForNextJs = ({ dependencies, devDependencies }: PackageJson) => } } -const getExternalAndIgnoredModulesFromSpecialCases = async ({ srcDir }: { srcDir: string }) => { +export const getExternalAndIgnoredModulesFromSpecialCases = async ({ srcDir }: { srcDir: string }) => { const { dependencies = {}, devDependencies = {} } = await getPackageJsonIfAvailable(srcDir) const { externalModules: nextJsExternalModules, ignoredModules: nextJsIgnoredModules } = getModulesForNextJs({ dependencies, @@ -28,5 +28,3 @@ const getExternalAndIgnoredModulesFromSpecialCases = async ({ srcDir }: { srcDir ignoredModules, } } - -export { getExternalAndIgnoredModulesFromSpecialCases } diff --git a/src/runtimes/node/bundlers/esbuild/src_files.ts b/src/runtimes/node/bundlers/esbuild/src_files.ts index ff751d8dd..b86dac761 100644 --- a/src/runtimes/node/bundlers/esbuild/src_files.ts +++ b/src/runtimes/node/bundlers/esbuild/src_files.ts @@ -4,7 +4,7 @@ import { getPackageJson, PackageJson } from '../../utils/package_json' import { getNewCache, TraversalCache } from '../../utils/traversal_cache' import { getDependencyPathsForDependency } from '../zisi/traverse' -const getSrcFiles: GetSrcFilesFunction = async ({ config, mainFile, pluginsModulesPath, srcDir }) => { +export const getSrcFiles: GetSrcFilesFunction = async ({ config, mainFile, pluginsModulesPath, srcDir }) => { const { externalNodeModules = [], includedFiles = [], includedFilesBasePath } = config const { exclude: excludedPaths, paths: includedFilePaths } = await getPathsOfIncludedFiles( includedFiles, @@ -77,5 +77,3 @@ const getSrcFilesForDependency = async function ({ throw error } } - -export { getSrcFiles } diff --git a/src/runtimes/node/bundlers/index.ts b/src/runtimes/node/bundlers/index.ts index 7cdbd5e07..3a2b4dac0 100644 --- a/src/runtimes/node/bundlers/index.ts +++ b/src/runtimes/node/bundlers/index.ts @@ -17,9 +17,9 @@ type BundlerWarning = Message type CleanupFunction = () => Promise -type NativeNodeModules = Record> +export type NativeNodeModules = Record> -type BundleFunction = ( +export type BundleFunction = ( args: { basePath?: string config: FunctionConfig @@ -58,7 +58,7 @@ type BundleFunction = ( srcFiles: string[] }> -type GetSrcFilesFunction = ( +export type GetSrcFilesFunction = ( args: { basePath?: string config: FunctionConfig @@ -73,7 +73,7 @@ interface NodeBundler { getSrcFiles: GetSrcFilesFunction } -const getBundler = (name: NodeBundlerName): NodeBundler => { +export const getBundler = (name: NodeBundlerName): NodeBundler => { switch (name) { case 'esbuild': case 'esbuild_zisi': @@ -92,7 +92,7 @@ const getBundler = (name: NodeBundlerName): NodeBundler => { // We use ZISI as the default bundler, except for certain extensions, for which // esbuild is the only option. -const getDefaultBundler = async ({ +export const getDefaultBundler = async ({ extension, mainFile, featureFlags, @@ -121,6 +121,3 @@ const getDefaultBundler = async ({ return 'zisi' } - -export { getBundler, getDefaultBundler } -export type { BundleFunction, GetSrcFilesFunction, NativeNodeModules } diff --git a/src/runtimes/node/bundlers/nft/es_modules.ts b/src/runtimes/node/bundlers/nft/es_modules.ts index 3e9fbc4b8..817ab19b2 100644 --- a/src/runtimes/node/bundlers/nft/es_modules.ts +++ b/src/runtimes/node/bundlers/nft/es_modules.ts @@ -48,7 +48,7 @@ const patchESMPackage = async (path: string, fsCache: FsCache) => { return JSON.stringify(patchedPackageJson) } -const processESM = async ({ +export const processESM = async ({ basePath, config, esmPaths, @@ -174,5 +174,3 @@ const transpileESM = async ({ return rewrites } - -export { processESM } diff --git a/src/runtimes/node/bundlers/nft/transpile.ts b/src/runtimes/node/bundlers/nft/transpile.ts index ac05e1e76..1ccb996e9 100644 --- a/src/runtimes/node/bundlers/nft/transpile.ts +++ b/src/runtimes/node/bundlers/nft/transpile.ts @@ -3,7 +3,7 @@ import { build } from '@netlify/esbuild' import type { FunctionConfig } from '../../../../config' import { getBundlerTarget } from '../esbuild/bundler_target' -const transpile = async (path: string, config: FunctionConfig) => { +export const transpile = async (path: string, config: FunctionConfig) => { // The version of ECMAScript to use as the build target. This will determine // whether certain features are transpiled down or left untransformed. const nodeTarget = getBundlerTarget(config.nodeVersion) @@ -20,5 +20,3 @@ const transpile = async (path: string, config: FunctionConfig) => { return transpiled.outputFiles[0].text } - -export { transpile } diff --git a/src/runtimes/node/bundlers/zisi/list_imports.ts b/src/runtimes/node/bundlers/zisi/list_imports.ts index ab3807e0d..53b0571e7 100644 --- a/src/runtimes/node/bundlers/zisi/list_imports.ts +++ b/src/runtimes/node/bundlers/zisi/list_imports.ts @@ -30,7 +30,13 @@ const getListImportsPlugin = ({ imports, path }: { imports: Set; path: s }, }) -const listImports = async ({ functionName, path }: { functionName: string; path: string }): Promise => { +export const listImports = async ({ + functionName, + path, +}: { + functionName: string + path: string +}): Promise => { // We're not interested in the output that esbuild generates, we're just // using it for its parsing capabilities in order to find import/require // statements. However, if we don't give esbuild a path in `outfile`, it @@ -66,5 +72,3 @@ const listImports = async ({ functionName, path }: { functionName: string; path: return [...imports] } - -export { listImports } diff --git a/src/runtimes/node/bundlers/zisi/nested.ts b/src/runtimes/node/bundlers/zisi/nested.ts index 206b15d5d..3f5ee8e3a 100644 --- a/src/runtimes/node/bundlers/zisi/nested.ts +++ b/src/runtimes/node/bundlers/zisi/nested.ts @@ -5,7 +5,7 @@ import { PackageJson } from '../../utils/package_json' // Apply the Node.js module logic recursively on its own dependencies, using // the `package.json` `dependencies`, `peerDependencies` and // `optionalDependencies` keys -const getNestedDependencies = function ({ +export const getNestedDependencies = function ({ dependencies = {}, peerDependencies = {}, optionalDependencies = {}, @@ -48,7 +48,7 @@ const EXCLUDED_PEER_DEPENDENCIES = new Set(['@prisma/cli', 'prisma2', 'prisma']) // `optionalDependencies`: // - are not reported when missing // - are included in module dependencies -const handleModuleNotFound = function ({ +export const handleModuleNotFound = function ({ error, moduleName, packageJson, @@ -108,5 +108,3 @@ const isExternalCrittersModule = function ( return satisfiesRange(nextVersion) } - -export { getNestedDependencies, handleModuleNotFound } diff --git a/src/runtimes/node/bundlers/zisi/published.ts b/src/runtimes/node/bundlers/zisi/published.ts index 5c7f56cb0..a6e04e5e1 100644 --- a/src/runtimes/node/bundlers/zisi/published.ts +++ b/src/runtimes/node/bundlers/zisi/published.ts @@ -5,7 +5,7 @@ import glob from 'glob' const pGlob = promisify(glob) // We use all the files published by the Node.js except some that are not needed -const getPublishedFiles = async function (modulePath: string): Promise { +export const getPublishedFiles = async function (modulePath: string): Promise { const ignore = getIgnoredFiles(modulePath) const publishedFiles = await pGlob(`${modulePath}/**`, { ignore, @@ -33,5 +33,3 @@ const IGNORED_FILES = [ '*.ts', '*.patch', ] - -export { getPublishedFiles } diff --git a/src/runtimes/node/bundlers/zisi/resolve.ts b/src/runtimes/node/bundlers/zisi/resolve.ts index 0a425c15d..b2c0545d7 100644 --- a/src/runtimes/node/bundlers/zisi/resolve.ts +++ b/src/runtimes/node/bundlers/zisi/resolve.ts @@ -24,7 +24,7 @@ const BACKSLASH_REGEXP = /\\/g // However it does not give helpful error messages. // https://github.com/browserify/resolve/issues/223 // So, on errors, we fallback to `require.resolve()` -const resolvePackage = async function (moduleName: string, baseDirs: string[]): Promise { +export const resolvePackage = async function (moduleName: string, baseDirs: string[]): Promise { try { return await resolvePathPreserveSymlinks(`${moduleName}/package.json`, baseDirs) } catch (error) { @@ -63,7 +63,7 @@ const resolvePathPreserveSymlinksForDir = function (path: string, basedir: strin // the resolve library has a `paths` option but it's not the same as multiple basedirs // see https://github.com/browserify/resolve/issues/188#issuecomment-679010477 // we return the first resolved location or the first error if all failed -const resolvePathPreserveSymlinks = async function (path: string, baseDirs: string[]): Promise { +export const resolvePathPreserveSymlinks = async function (path: string, baseDirs: string[]): Promise { let firstError for (const basedir of baseDirs) { try { @@ -106,5 +106,3 @@ const isPackageDir = async function (moduleName: string, dir: string) { return dir } - -export { resolvePackage, resolvePathPreserveSymlinks } diff --git a/src/runtimes/node/bundlers/zisi/side_files.ts b/src/runtimes/node/bundlers/zisi/side_files.ts index eccad797a..0480c0b31 100644 --- a/src/runtimes/node/bundlers/zisi/side_files.ts +++ b/src/runtimes/node/bundlers/zisi/side_files.ts @@ -2,7 +2,7 @@ import { getPublishedFiles } from './published' // Some modules generate source files on `postinstall` that are not located // inside the module's directory itself. -const getSideFiles = async function (modulePath: string, moduleName: string): Promise { +export const getSideFiles = async function (modulePath: string, moduleName: string): Promise { const sideFiles = SIDE_FILES[moduleName] if (sideFiles === undefined) { return [] @@ -14,5 +14,3 @@ const getSideFiles = async function (modulePath: string, moduleName: string): Pr const SIDE_FILES: Record = { '@prisma/client': '../../.prisma', } - -export { getSideFiles } diff --git a/src/runtimes/node/bundlers/zisi/src_files.ts b/src/runtimes/node/bundlers/zisi/src_files.ts index 8c49837e3..9b787916a 100644 --- a/src/runtimes/node/bundlers/zisi/src_files.ts +++ b/src/runtimes/node/bundlers/zisi/src_files.ts @@ -20,7 +20,7 @@ import { shouldTreeShake } from './tree_shake' // Retrieve the paths to the Node.js files to zip. // We only include the files actually needed by the function because AWS Lambda // has a size limit for the zipped file. It also makes cold starts faster. -const getSrcFiles: GetSrcFilesFunction = async function ({ +export const getSrcFiles: GetSrcFilesFunction = async function ({ config, featureFlags, mainFile, @@ -204,6 +204,4 @@ const getTreeShakedDependencies = async function ({ }) return [path, ...depsPath] } - -export { getSrcFiles } /* eslint-enable max-lines */ diff --git a/src/runtimes/node/bundlers/zisi/traverse.ts b/src/runtimes/node/bundlers/zisi/traverse.ts index 8a4a57022..209548159 100644 --- a/src/runtimes/node/bundlers/zisi/traverse.ts +++ b/src/runtimes/node/bundlers/zisi/traverse.ts @@ -15,7 +15,7 @@ const EXCLUDED_MODULES = new Set(['aws-sdk']) // When a file requires a module, we find its path inside `node_modules` and // use all its published files. We also recurse on the module's dependencies. -const getDependencyPathsForDependency = async function ({ +export const getDependencyPathsForDependency = async function ({ dependency, basedir, state, @@ -109,5 +109,3 @@ const getNestedModules = async function ({ ) return depsPaths.flat() } - -export { getDependencyPathsForDependency } diff --git a/src/runtimes/node/bundlers/zisi/tree_files.ts b/src/runtimes/node/bundlers/zisi/tree_files.ts index 7584447de..7c0705a55 100644 --- a/src/runtimes/node/bundlers/zisi/tree_files.ts +++ b/src/runtimes/node/bundlers/zisi/tree_files.ts @@ -6,7 +6,7 @@ import glob from 'glob' const pGlob = promisify(glob) // When using a directory, we include all its descendants except `node_modules` -const getTreeFiles = async function (srcPath: string, stat: Stats): Promise { +export const getTreeFiles = async function (srcPath: string, stat: Stats): Promise { if (!stat.isDirectory()) { return [srcPath] } @@ -17,5 +17,3 @@ const getTreeFiles = async function (srcPath: string, stat: Stats): Promise { return indexB - indexA } -const findFunctionsInPaths: FindFunctionsInPathsFunction = async function ({ paths, fsCache, featureFlags }) { +export const findFunctionsInPaths: FindFunctionsInPathsFunction = async function ({ paths, fsCache, featureFlags }) { const functions = await Promise.all(paths.map((path) => findFunctionInPath({ path, fsCache, featureFlags }))) // It's fine to mutate the array since its scope is local to this function. @@ -46,7 +46,7 @@ const findFunctionsInPaths: FindFunctionsInPathsFunction = async function ({ pat return sortedFunctions } -const findFunctionInPath: FindFunctionInPathFunction = async function ({ path: srcPath }) { +export const findFunctionInPath: FindFunctionInPathFunction = async function ({ path: srcPath }) { const filename = basename(srcPath) if (filename === 'node_modules') { @@ -90,5 +90,3 @@ const getMainFile = async function (srcPath: string, filename: string, stat: Sta return srcPath } } - -export { findFunctionsInPaths, findFunctionInPath } diff --git a/src/runtimes/node/in_source_config/index.ts b/src/runtimes/node/in_source_config/index.ts index b9d0126d3..797ee68a5 100644 --- a/src/runtimes/node/in_source_config/index.ts +++ b/src/runtimes/node/in_source_config/index.ts @@ -7,14 +7,14 @@ import { getImports } from '../parser/imports' import { parse as parseSchedule } from './properties/schedule' -const IN_SOURCE_CONFIG_MODULE = '@netlify/functions' +export const IN_SOURCE_CONFIG_MODULE = '@netlify/functions' -type ISCValues = Partial> +export type ISCValues = Partial> // Parses a JS/TS file and looks for in-source config declarations. It returns // an array of all declarations found, with `property` indicating the name of // the property and `data` its value. -const findISCDeclarationsInPath = async (sourcePath: string): Promise => { +export const findISCDeclarationsInPath = async (sourcePath: string): Promise => { const ast = await safelyParseFile(sourcePath) if (ast === null) { @@ -22,8 +22,8 @@ const findISCDeclarationsInPath = async (sourcePath: string): Promise } const imports = ast.body.flatMap((node) => getImports(node, IN_SOURCE_CONFIG_MODULE)) - const exports = getMainExport(ast.body) - const iscExports = exports + const mainExports = getMainExport(ast.body) + const iscExports = mainExports .map(({ args, local: exportName }) => { const matchingImport = imports.find(({ local: importName }) => importName === exportName) @@ -47,12 +47,9 @@ const findISCDeclarationsInPath = async (sourcePath: string): Promise return mergedExports } -type ISCHandlerArg = ArgumentPlaceholder | Expression | SpreadElement | JSXNamespacedName +export type ISCHandlerArg = ArgumentPlaceholder | Expression | SpreadElement | JSXNamespacedName -interface ISCExport { +export interface ISCExport { local: string args: ISCHandlerArg[] } - -export { findISCDeclarationsInPath, IN_SOURCE_CONFIG_MODULE } -export type { ISCExport, ISCHandlerArg, ISCValues } diff --git a/src/runtimes/node/parser/exports.ts b/src/runtimes/node/parser/exports.ts index cd2e7c619..c453dbdca 100644 --- a/src/runtimes/node/parser/exports.ts +++ b/src/runtimes/node/parser/exports.ts @@ -5,7 +5,7 @@ import type { ISCExport } from '../in_source_config' import { isModuleExports } from './helpers' // Finds the main handler export in an AST. -const getMainExport = (nodes: Statement[]) => { +export const getMainExport = (nodes: Statement[]) => { let handlerExport: ISCExport[] = [] nodes.find((node) => { @@ -86,5 +86,3 @@ const getExportsFromCallExpression = (node: CallExpression) => { return exports } - -export { getMainExport } diff --git a/src/runtimes/node/parser/helpers.ts b/src/runtimes/node/parser/helpers.ts index e0d22c95a..64eeca129 100644 --- a/src/runtimes/node/parser/helpers.ts +++ b/src/runtimes/node/parser/helpers.ts @@ -28,10 +28,10 @@ const isDotExpression = (node: Expression, expression: string[]): boolean => { return node.object.type === 'Identifier' && object[0] === node.object.name && property === node.property.name } -const isImport = (node: Statement, importPath: string): node is ImportDeclaration => +export const isImport = (node: Statement, importPath: string): node is ImportDeclaration => node.type === 'ImportDeclaration' && node.source.value === importPath -const isModuleExports = ( +export const isModuleExports = ( node: Statement, dotExpression = ['module', 'exports'], ): node is ExpressionStatement & { expression: AssignmentExpression } => @@ -40,7 +40,7 @@ const isModuleExports = ( node.expression.left.type === 'MemberExpression' && isDotExpression(node.expression.left, dotExpression) -const isRequire = (node: Expression | undefined | null, requirePath: string) => { +export const isRequire = (node: Expression | undefined | null, requirePath: string) => { if (!node || node.type !== 'CallExpression') { return false } @@ -55,5 +55,3 @@ const isRequireCall = (node: Expression | V8IntrinsicIdentifier) => node.type === 'Identifier' && node.name === 'require' const isRequirePath = (node: StringLiteral, path: string) => node.type === 'StringLiteral' && node.value === path - -export { isImport, isModuleExports, isRequire } diff --git a/src/runtimes/node/parser/imports.ts b/src/runtimes/node/parser/imports.ts index 9c8187485..168c7e62a 100644 --- a/src/runtimes/node/parser/imports.ts +++ b/src/runtimes/node/parser/imports.ts @@ -5,7 +5,7 @@ import { nonNullable } from '../../../utils/non_nullable' import { isImport, isRequire } from './helpers' // Finds import/require statements of a given path in an AST. -const getImports = (node: Statement, importPath: string) => { +export const getImports = (node: Statement, importPath: string) => { const esmImports = getImportsFromESM(node, importPath) if (esmImports.length !== 0) { @@ -77,5 +77,3 @@ const getImportsFromESM = (node: Statement, importPath: string) => { return imports } - -export { getImports } diff --git a/src/runtimes/node/parser/index.ts b/src/runtimes/node/parser/index.ts index ba963c95d..36e735f1c 100644 --- a/src/runtimes/node/parser/index.ts +++ b/src/runtimes/node/parser/index.ts @@ -68,7 +68,7 @@ const getWildcardFromASTNode = (node: Expression | PrivateName | TSType) => { // - `includedPathsGlob`: A glob with the files to be included in the bundle // - `type`: The expression type (e.g. "require", "import") // eslint-disable-next-line complexity -const parseExpression = ({ +export const parseExpression = ({ basePath, expression: rawExpression, resolveDir, @@ -119,7 +119,7 @@ const parseFile = async (path: string) => { // Attempts to parse a JS/TS file at the given path, returning its AST if // successful, or `null` if not. -const safelyParseFile = async (path: string) => { +export const safelyParseFile = async (path: string) => { if (!path) { return null } @@ -226,6 +226,4 @@ const validateGlobNodes = (globNodes: string[]) => { return hasStrings && hasStaticHead } - -export { parseExpression, safelyParseFile } /* eslint-enable max-lines */ diff --git a/src/runtimes/node/utils/base_path.ts b/src/runtimes/node/utils/base_path.ts index 143e98723..44c5327be 100644 --- a/src/runtimes/node/utils/base_path.ts +++ b/src/runtimes/node/utils/base_path.ts @@ -1,11 +1,9 @@ import commonPathPrefix from 'common-path-prefix' -const getBasePath = (dirnames: string[]): string => { +export const getBasePath = (dirnames: string[]): string => { if (dirnames.length === 1) { return dirnames[0] } return commonPathPrefix(dirnames) } - -export { getBasePath } diff --git a/src/runtimes/node/utils/detect_es_module.ts b/src/runtimes/node/utils/detect_es_module.ts index c05b5a930..2cd609109 100644 --- a/src/runtimes/node/utils/detect_es_module.ts +++ b/src/runtimes/node/utils/detect_es_module.ts @@ -2,7 +2,7 @@ import { promises as fs } from 'fs' import { init, parse } from 'es-module-lexer' -const detectEsModule = async ({ mainFile }: { mainFile: string }): Promise => { +export const detectEsModule = async ({ mainFile }: { mainFile: string }): Promise => { if (!mainFile) { return false } @@ -17,5 +17,3 @@ const detectEsModule = async ({ mainFile }: { mainFile: string }): Promise { return `export { handler } from '${importPath}'` } -const getEntryFile = ({ +export const getEntryFile = ({ commonPrefix, filename, mainFile, @@ -41,5 +41,3 @@ const getEntryFile = ({ filename: entryFilename, } } - -export { EntryFile, getEntryFile } diff --git a/src/runtimes/node/utils/included_files.ts b/src/runtimes/node/utils/included_files.ts index 3810581a8..a5b1942c8 100644 --- a/src/runtimes/node/utils/included_files.ts +++ b/src/runtimes/node/utils/included_files.ts @@ -8,7 +8,7 @@ const pGlob = promisify(glob) // Returns the subset of `paths` that don't match any of the glob expressions // from `exclude`. -const filterExcludedPaths = (paths: string[], exclude: string[] = []) => { +export const filterExcludedPaths = (paths: string[], exclude: string[] = []) => { if (exclude.length === 0) { return paths } @@ -18,7 +18,7 @@ const filterExcludedPaths = (paths: string[], exclude: string[] = []) => { return excludedPaths } -const getPathsOfIncludedFiles = async ( +export const getPathsOfIncludedFiles = async ( includedFiles: string[], basePath?: string, ): Promise<{ exclude: string[]; paths: string[] }> => { @@ -59,5 +59,3 @@ const getPathsOfIncludedFiles = async ( return { exclude, paths: [...new Set(normalizedPaths)] } } - -export { filterExcludedPaths, getPathsOfIncludedFiles } diff --git a/src/runtimes/node/utils/module.ts b/src/runtimes/node/utils/module.ts index ac6cc6920..646f3389c 100644 --- a/src/runtimes/node/utils/module.ts +++ b/src/runtimes/node/utils/module.ts @@ -4,10 +4,8 @@ import requirePackageName from 'require-package-name' const BACKSLASH_REGEXP = /\\/g // When doing require("moduleName/file/path"), only keep `moduleName` -const getModuleName = function (dependency: string): string { +export const getModuleName = function (dependency: string): string { const dependencyA = dependency.replace(BACKSLASH_REGEXP, '/') const moduleName = requirePackageName(dependencyA) return moduleName } - -export { getModuleName } diff --git a/src/runtimes/node/utils/node_version.ts b/src/runtimes/node/utils/node_version.ts index de0293a53..1071ad46b 100644 --- a/src/runtimes/node/utils/node_version.ts +++ b/src/runtimes/node/utils/node_version.ts @@ -1,18 +1,18 @@ /* eslint-disable no-magic-numbers */ type SupportedVersionNumbers = 8 | 10 | 12 | 14 -type NodeVersionString = `${SupportedVersionNumbers}.x` | `nodejs${SupportedVersionNumbers}.x` +export type NodeVersionString = `${SupportedVersionNumbers}.x` | `nodejs${SupportedVersionNumbers}.x` -interface NodeVersionSupport { +export interface NodeVersionSupport { esm: boolean } // Must match the default version used in Bitballoon. -const DEFAULT_NODE_VERSION = 14 +export const DEFAULT_NODE_VERSION = 14 const VERSION_REGEX = /(nodejs)?(\d+)\.x/ -const getNodeVersion = (configVersion?: string) => parseVersion(configVersion) ?? DEFAULT_NODE_VERSION +export const getNodeVersion = (configVersion?: string) => parseVersion(configVersion) ?? DEFAULT_NODE_VERSION -const getNodeSupportMatrix = (configVersion?: string): NodeVersionSupport => { +export const getNodeSupportMatrix = (configVersion?: string): NodeVersionSupport => { const versionNumber = getNodeVersion(configVersion) return { @@ -22,7 +22,7 @@ const getNodeSupportMatrix = (configVersion?: string): NodeVersionSupport => { // Takes a string in the format defined by the `NodeVersion` type and returns // the numeric major version (e.g. "nodejs14.x" => 14). -const parseVersion = (input: string | undefined) => { +export const parseVersion = (input: string | undefined) => { if (input === undefined) { return } @@ -41,13 +41,4 @@ const parseVersion = (input: string | undefined) => { return version } - -export { - DEFAULT_NODE_VERSION, - getNodeSupportMatrix, - getNodeVersion, - NodeVersionString, - NodeVersionSupport, - parseVersion, -} /* eslint-enable no-magic-numbers */ diff --git a/src/runtimes/node/utils/normalize_path.ts b/src/runtimes/node/utils/normalize_path.ts index c0e91dad0..7c8c15e9a 100644 --- a/src/runtimes/node/utils/normalize_path.ts +++ b/src/runtimes/node/utils/normalize_path.ts @@ -5,7 +5,7 @@ import unixify from 'unixify' // `adm-zip` and `require()` expect Unix paths. // We remove the common path prefix. // With files on different Windows drives, we remove the drive letter. -const normalizeFilePath = function ({ +export const normalizeFilePath = function ({ commonPrefix, path, userNamespace, @@ -20,5 +20,3 @@ const normalizeFilePath = function ({ const pathC = unixify(pathB) return pathC } - -export { normalizeFilePath } diff --git a/src/runtimes/node/utils/package_json.ts b/src/runtimes/node/utils/package_json.ts index 03df3545e..4b1ae3180 100644 --- a/src/runtimes/node/utils/package_json.ts +++ b/src/runtimes/node/utils/package_json.ts @@ -2,7 +2,7 @@ import { promises as fs } from 'fs' import pkgDir from 'pkg-dir' -interface PackageJson { +export interface PackageJson { name?: string version?: string dependencies?: Record @@ -24,13 +24,13 @@ const sanitiseFiles = (files: unknown): string[] | undefined => { return files.filter((file) => typeof file === 'string') } -const sanitisePackageJson = (packageJson: Record): PackageJson => ({ +export const sanitisePackageJson = (packageJson: Record): PackageJson => ({ ...packageJson, files: sanitiseFiles(packageJson.files), }) // Retrieve the `package.json` of a specific project or module -const getPackageJson = async function (srcDir: string): Promise { +export const getPackageJson = async function (srcDir: string): Promise { const packageRoot = await pkgDir(srcDir) if (packageRoot === undefined) { @@ -47,7 +47,7 @@ const getPackageJson = async function (srcDir: string): Promise { } } -const getPackageJsonIfAvailable = async (srcDir: string): Promise => { +export const getPackageJsonIfAvailable = async (srcDir: string): Promise => { try { const packageJson = await getPackageJson(srcDir) @@ -56,5 +56,3 @@ const getPackageJsonIfAvailable = async (srcDir: string): Promise = return {} } } - -export { getPackageJson, getPackageJsonIfAvailable, PackageJson, sanitisePackageJson } diff --git a/src/runtimes/node/utils/plugin_modules_path.ts b/src/runtimes/node/utils/plugin_modules_path.ts index 2b9603d18..2aee33ed5 100644 --- a/src/runtimes/node/utils/plugin_modules_path.ts +++ b/src/runtimes/node/utils/plugin_modules_path.ts @@ -4,7 +4,7 @@ import findUp from 'find-up' const AUTO_PLUGINS_DIR = '.netlify/plugins/' -const createAliases = ( +export const createAliases = ( paths: string[], pluginsModulesPath: string | undefined, aliases: Map, @@ -21,7 +21,5 @@ const createAliases = ( }) } -const getPluginsModulesPath = (srcDir: string): Promise => +export const getPluginsModulesPath = (srcDir: string): Promise => findUp(`${AUTO_PLUGINS_DIR}node_modules`, { cwd: srcDir, type: 'directory' }) - -export { createAliases, getPluginsModulesPath } diff --git a/src/runtimes/node/utils/traversal_cache.ts b/src/runtimes/node/utils/traversal_cache.ts index b4771197b..dfb5801ce 100644 --- a/src/runtimes/node/utils/traversal_cache.ts +++ b/src/runtimes/node/utils/traversal_cache.ts @@ -1,14 +1,12 @@ // Local cache used for optimizing the traversal of module dependencies. -interface TraversalCache { +export interface TraversalCache { localFiles: Set moduleNames: Set modulePaths: Set } -const getNewCache = (): TraversalCache => ({ +export const getNewCache = (): TraversalCache => ({ localFiles: new Set(), moduleNames: new Set(), modulePaths: new Set(), }) - -export { TraversalCache, getNewCache } diff --git a/src/runtimes/node/utils/zip.ts b/src/runtimes/node/utils/zip.ts index 4562a5721..b13d3b626 100644 --- a/src/runtimes/node/utils/zip.ts +++ b/src/runtimes/node/utils/zip.ts @@ -21,7 +21,7 @@ const COPY_FILE_CONCURRENCY = os.cpus().length === 0 ? 2 : os.cpus().length * 2 // the entry file generated by zip-it-and-ship-it). const DEFAULT_USER_SUBDIRECTORY = 'src' -type ArchiveFormat = 'none' | 'zip' +export type ArchiveFormat = 'none' | 'zip' interface ZipNodeParameters { aliases?: Map @@ -142,7 +142,7 @@ const createZipArchive = async function ({ return destPath } -const zipNodeJs = function ({ +export const zipNodeJs = function ({ archiveFormat, ...options }: ZipNodeParameters & { archiveFormat: ArchiveFormat }): Promise { @@ -191,5 +191,3 @@ const zipJsFile = function ({ addZipFile(archive, srcFile, normalizedDestPath, stat) } } - -export { ArchiveFormat, zipNodeJs } diff --git a/src/runtimes/runtime.ts b/src/runtimes/runtime.ts index 43eb0493c..6c754d754 100644 --- a/src/runtimes/runtime.ts +++ b/src/runtimes/runtime.ts @@ -7,21 +7,21 @@ import { FsCache } from '../utils/fs' import type { NodeBundlerName } from './node/bundlers' import type { ISCValues } from './node/in_source_config' -type RuntimeName = 'go' | 'js' | 'rs' +export type RuntimeName = 'go' | 'js' | 'rs' -type FindFunctionsInPathsFunction = (args: { +export type FindFunctionsInPathsFunction = (args: { featureFlags: FeatureFlags fsCache: FsCache paths: string[] }) => Promise -type FindFunctionInPathFunction = (args: { +export type FindFunctionInPathFunction = (args: { featureFlags: FeatureFlags fsCache: FsCache path: string }) => Promise -type GetSrcFilesFunction = ( +export type GetSrcFilesFunction = ( args: { basePath?: string config: FunctionConfig @@ -30,7 +30,7 @@ type GetSrcFilesFunction = ( } & FunctionSource, ) => Promise -interface ZipFunctionResult { +export interface ZipFunctionResult { bundler?: NodeBundlerName bundlerErrors?: object[] bundlerWarnings?: object[] @@ -42,7 +42,7 @@ interface ZipFunctionResult { path: string } -type ZipFunction = ( +export type ZipFunction = ( args: { archiveFormat: ArchiveFormat basePath?: string @@ -53,20 +53,10 @@ type ZipFunction = ( } & FunctionSource, ) => Promise -interface Runtime { +export interface Runtime { findFunctionsInPaths: FindFunctionsInPathsFunction findFunctionInPath: FindFunctionInPathFunction getSrcFiles?: GetSrcFilesFunction name: RuntimeName zipFunction: ZipFunction } - -export { - FindFunctionInPathFunction, - FindFunctionsInPathsFunction, - GetSrcFilesFunction, - Runtime, - RuntimeName, - ZipFunction, - ZipFunctionResult, -} diff --git a/src/runtimes/rust/builder.ts b/src/runtimes/rust/builder.ts index 6f7e208ab..d235b4339 100644 --- a/src/runtimes/rust/builder.ts +++ b/src/runtimes/rust/builder.ts @@ -13,7 +13,7 @@ import { BUILD_TARGET, MANIFEST_NAME } from './constants' const runtimeName: RuntimeName = 'rs' -const build = async ({ config, name, srcDir }: { config: FunctionConfig; name: string; srcDir: string }) => { +export const build = async ({ config, name, srcDir }: { config: FunctionConfig; name: string; srcDir: string }) => { const functionName = basename(srcDir) try { @@ -124,5 +124,3 @@ const installToolchainOnce = () => { return toolchainInstallation } - -export { build } diff --git a/src/runtimes/rust/cargo_manifest.ts b/src/runtimes/rust/cargo_manifest.ts index 6f217d474..2426073ec 100644 --- a/src/runtimes/rust/cargo_manifest.ts +++ b/src/runtimes/rust/cargo_manifest.ts @@ -1,7 +1,5 @@ -interface CargoManifest { +export interface CargoManifest { package: { name: string } } - -export { CargoManifest } diff --git a/src/runtimes/rust/constants.ts b/src/runtimes/rust/constants.ts index 530b64f1e..e67c9d85c 100644 --- a/src/runtimes/rust/constants.ts +++ b/src/runtimes/rust/constants.ts @@ -1,4 +1,2 @@ -const BUILD_TARGET = 'x86_64-unknown-linux-musl' -const MANIFEST_NAME = 'Cargo.toml' - -export { BUILD_TARGET, MANIFEST_NAME } +export const BUILD_TARGET = 'x86_64-unknown-linux-musl' +export const MANIFEST_NAME = 'Cargo.toml' diff --git a/src/utils/archive_size.ts b/src/utils/archive_size.ts index e5fa40b6e..c9283c648 100644 --- a/src/utils/archive_size.ts +++ b/src/utils/archive_size.ts @@ -5,7 +5,7 @@ import type { FunctionArchive } from '../function' // Returns the input object with an additional `size` property containing the // size of the file at `path` when it is a ZIP archive. -const addArchiveSize = async (result: FunctionArchive) => { +export const addArchiveSize = async (result: FunctionArchive) => { const { path } = result if (extname(path) !== '.zip') { @@ -16,5 +16,3 @@ const addArchiveSize = async (result: FunctionArchive) => { return { ...result, size } } - -export { addArchiveSize } diff --git a/src/utils/format_result.ts b/src/utils/format_result.ts index bf7fdb126..743be9b7b 100644 --- a/src/utils/format_result.ts +++ b/src/utils/format_result.ts @@ -3,13 +3,13 @@ import { RuntimeName } from '../runtimes/runtime' import { removeUndefined } from './remove_undefined' -type FunctionResult = Omit & { +export type FunctionResult = Omit & { runtime: RuntimeName schedule?: string } // Takes the result of zipping a function and formats it for output. -const formatZipResult = (archive: FunctionArchive) => { +export const formatZipResult = (archive: FunctionArchive) => { const functionResult: FunctionResult = { ...archive, inSourceConfig: undefined, @@ -19,6 +19,3 @@ const formatZipResult = (archive: FunctionArchive) => { return removeUndefined(functionResult) } - -export { formatZipResult } -export type { FunctionResult } diff --git a/src/utils/fs.ts b/src/utils/fs.ts index 372a9c1b3..36186c331 100644 --- a/src/utils/fs.ts +++ b/src/utils/fs.ts @@ -3,7 +3,7 @@ import { dirname, format, join, parse, resolve } from 'path' import { nonNullable } from './non_nullable' -type FsCache = Record +export type FsCache = Record // This caches multiple FS calls to the same path. It creates a cache key with // the name of the function and the path (e.g. "readdir:/some/directory"). @@ -24,14 +24,14 @@ const makeCachedFunction = return cache[key] as ReturnType } -const cachedLstat = makeCachedFunction(fs.lstat) -const cachedReaddir = makeCachedFunction(fs.readdir) -const cachedReadFile = makeCachedFunction(fs.readFile) +export const cachedLstat = makeCachedFunction(fs.lstat) +export const cachedReaddir = makeCachedFunction(fs.readdir) +export const cachedReadFile = makeCachedFunction(fs.readFile) -const getPathWithExtension = (path: string, extension: string) => +export const getPathWithExtension = (path: string, extension: string) => format({ ...parse(path), base: undefined, ext: extension }) -const safeUnlink = async (path: string) => { +export const safeUnlink = async (path: string) => { try { await fs.unlink(path) } catch {} @@ -40,7 +40,7 @@ const safeUnlink = async (path: string) => { // Takes a list of absolute paths and returns an array containing all the // filenames within those directories, if at least one of the directories // exists. If not, an error is thrown. -const listFunctionsDirectories = async function (srcFolders: string[]) { +export const listFunctionsDirectories = async function (srcFolders: string[]) { const filenamesByDirectory = await Promise.all( srcFolders.map(async (srcFolder) => { try { @@ -61,7 +61,7 @@ const listFunctionsDirectories = async function (srcFolders: string[]) { return validDirectories.flat() } -const listFunctionsDirectory = async function (srcFolder: string) { +export const listFunctionsDirectory = async function (srcFolder: string) { try { const filenames = await fs.readdir(srcFolder) @@ -71,14 +71,14 @@ const listFunctionsDirectory = async function (srcFolder: string) { } } -const resolveFunctionsDirectories = (input: string | string[]) => { +export const resolveFunctionsDirectories = (input: string | string[]) => { const directories = Array.isArray(input) ? input : [input] const absoluteDirectories = directories.map((srcFolder) => resolve(srcFolder)) return absoluteDirectories } -const mkdirAndWriteFile: typeof fs.writeFile = async (path, ...params) => { +export const mkdirAndWriteFile: typeof fs.writeFile = async (path, ...params) => { if (typeof path === 'string') { const directory = dirname(path) @@ -87,16 +87,3 @@ const mkdirAndWriteFile: typeof fs.writeFile = async (path, ...params) => { return fs.writeFile(path, ...params) } - -export { - cachedLstat, - cachedReaddir, - cachedReadFile, - getPathWithExtension, - listFunctionsDirectories, - listFunctionsDirectory, - resolveFunctionsDirectories, - safeUnlink, - mkdirAndWriteFile, -} -export type { FsCache } diff --git a/src/utils/non_nullable.ts b/src/utils/non_nullable.ts index 040d5f21a..082570448 100644 --- a/src/utils/non_nullable.ts +++ b/src/utils/non_nullable.ts @@ -1,3 +1 @@ -const nonNullable = (value: T): value is NonNullable => value !== null && value !== undefined - -export { nonNullable } +export const nonNullable = (value: T): value is NonNullable => value !== null && value !== undefined diff --git a/src/utils/remove_undefined.ts b/src/utils/remove_undefined.ts index 6753f9bee..eb73ec702 100644 --- a/src/utils/remove_undefined.ts +++ b/src/utils/remove_undefined.ts @@ -1,7 +1,5 @@ import filterObj from 'filter-obj' -const removeUndefined = function (obj: T): T { +export const removeUndefined = function (obj: T): T { return filterObj(obj, (key, value) => value !== undefined) as T } - -export { removeUndefined } diff --git a/src/zip.ts b/src/zip.ts index 1bdb1ecfa..8820846d2 100644 --- a/src/zip.ts +++ b/src/zip.ts @@ -39,7 +39,7 @@ const validateArchiveFormat = (archiveFormat: ArchiveFormat) => { // Zip `srcFolder/*` (Node.js or Go files) to `destFolder/*.zip` so it can be // used by AWS Lambda -const zipFunctions = async function ( +export const zipFunctions = async function ( relativeSrcFolders: string | string[], destFolder: string, { @@ -99,7 +99,7 @@ const zipFunctions = async function ( return formattedResults } -const zipFunction = async function ( +export const zipFunction = async function ( relativeSrcPath: string, destFolder: string, { @@ -152,5 +152,3 @@ const zipFunction = async function ( return formatZipResult({ ...zipResult, mainFile, name, runtime }) } - -export { zipFunction, zipFunctions } diff --git a/src/zip_binary.ts b/src/zip_binary.ts index 216e1f4bd..ada1216f7 100644 --- a/src/zip_binary.ts +++ b/src/zip_binary.ts @@ -4,7 +4,7 @@ import { startZip, addZipFile, addZipContent, endZip } from './archive' import { Runtime } from './runtimes/runtime' // Zip a binary function file -const zipBinary = async function ({ +export const zipBinary = async function ({ destPath, filename, runtime, @@ -22,5 +22,3 @@ const zipBinary = async function ({ addZipContent(archive, JSON.stringify({ runtime: runtime.name }), 'netlify-toolchain') await endZip(archive, output) } - -export { zipBinary } diff --git a/tests/fixtures/conflicting-names-3/function/index.ts b/tests/fixtures/conflicting-names-3/function/index.ts index b1fd6cbdc..833437c69 100644 --- a/tests/fixtures/conflicting-names-3/function/index.ts +++ b/tests/fixtures/conflicting-names-3/function/index.ts @@ -1,5 +1,3 @@ type MyType = string -const type: MyType = 'index-ts-file-in-directory' - -export { type } +export const type: MyType = 'index-ts-file-in-directory' diff --git a/tests/fixtures/conflicting-names-4/function.ts b/tests/fixtures/conflicting-names-4/function.ts index 14bfb7398..a464de883 100644 --- a/tests/fixtures/conflicting-names-4/function.ts +++ b/tests/fixtures/conflicting-names-4/function.ts @@ -1,5 +1,3 @@ type MyType = string -const type: MyType = 'function-ts-file' - -export { type } +export const type: MyType = 'function-ts-file' diff --git a/tests/fixtures/esm-throwing-error/function.js b/tests/fixtures/esm-throwing-error/function.js index efa9883c1..c3371ccab 100644 --- a/tests/fixtures/esm-throwing-error/function.js +++ b/tests/fixtures/esm-throwing-error/function.js @@ -1,5 +1,3 @@ -const handler = () => { +export const handler = () => { throw new Error('uh-oh') } - -export { handler } diff --git a/tests/fixtures/list/five/util.ts b/tests/fixtures/list/five/util.ts index f27196102..92a000b35 100644 --- a/tests/fixtures/list/five/util.ts +++ b/tests/fixtures/list/five/util.ts @@ -1,5 +1,3 @@ type MyType = string -const type: MyType = '❤️ TypeScript' - -export { type } +export const type: MyType = '❤️ TypeScript' diff --git a/tests/fixtures/node-cjs-importing-mjs/lib/file.mjs b/tests/fixtures/node-cjs-importing-mjs/lib/file.mjs index 5f1c6de1a..f4372faa9 100644 --- a/tests/fixtures/node-cjs-importing-mjs/lib/file.mjs +++ b/tests/fixtures/node-cjs-importing-mjs/lib/file.mjs @@ -1,4 +1,4 @@ -class App { +export class App { constructor(event, context) { return { statusCode: 200, @@ -6,5 +6,3 @@ class App { } } } - -export { App } diff --git a/tests/fixtures/node-typescript-directory-1/function/function.ts b/tests/fixtures/node-typescript-directory-1/function/function.ts index f27196102..92a000b35 100644 --- a/tests/fixtures/node-typescript-directory-1/function/function.ts +++ b/tests/fixtures/node-typescript-directory-1/function/function.ts @@ -1,5 +1,3 @@ type MyType = string -const type: MyType = '❤️ TypeScript' - -export { type } +export const type: MyType = '❤️ TypeScript' diff --git a/tests/fixtures/node-typescript-directory-2/function/index.ts b/tests/fixtures/node-typescript-directory-2/function/index.ts index f27196102..92a000b35 100644 --- a/tests/fixtures/node-typescript-directory-2/function/index.ts +++ b/tests/fixtures/node-typescript-directory-2/function/index.ts @@ -1,5 +1,3 @@ type MyType = string -const type: MyType = '❤️ TypeScript' - -export { type } +export const type: MyType = '❤️ TypeScript' diff --git a/tests/fixtures/node-typescript-tsconfig-parent/functions/function.ts b/tests/fixtures/node-typescript-tsconfig-parent/functions/function.ts index f4d84ebfa..6779c6201 100644 --- a/tests/fixtures/node-typescript-tsconfig-parent/functions/function.ts +++ b/tests/fixtures/node-typescript-tsconfig-parent/functions/function.ts @@ -1,5 +1,3 @@ import testModule from 'module-name' -const value = testModule as boolean - -export { value } +export const value = testModule as boolean diff --git a/tests/fixtures/node-typescript-tsconfig-sibling/function.ts b/tests/fixtures/node-typescript-tsconfig-sibling/function.ts index f4d84ebfa..6779c6201 100644 --- a/tests/fixtures/node-typescript-tsconfig-sibling/function.ts +++ b/tests/fixtures/node-typescript-tsconfig-sibling/function.ts @@ -1,5 +1,3 @@ import testModule from 'module-name' -const value = testModule as boolean - -export { value } +export const value = testModule as boolean diff --git a/tests/fixtures/node-typescript-with-imports/function.ts b/tests/fixtures/node-typescript-with-imports/function.ts index d57c4503c..ca8fc4279 100644 --- a/tests/fixtures/node-typescript-with-imports/function.ts +++ b/tests/fixtures/node-typescript-with-imports/function.ts @@ -1,3 +1 @@ -import { type } from './lib/util' - -export { type } +export { type } from './lib/util' diff --git a/tests/fixtures/node-typescript-with-imports/lib/util.ts b/tests/fixtures/node-typescript-with-imports/lib/util.ts index f27196102..92a000b35 100644 --- a/tests/fixtures/node-typescript-with-imports/lib/util.ts +++ b/tests/fixtures/node-typescript-with-imports/lib/util.ts @@ -1,5 +1,3 @@ type MyType = string -const type: MyType = '❤️ TypeScript' - -export { type } +export const type: MyType = '❤️ TypeScript' diff --git a/tests/fixtures/node-typescript/function.ts b/tests/fixtures/node-typescript/function.ts index f27196102..92a000b35 100644 --- a/tests/fixtures/node-typescript/function.ts +++ b/tests/fixtures/node-typescript/function.ts @@ -1,5 +1,3 @@ type MyType = string -const type: MyType = '❤️ TypeScript' - -export { type } +export const type: MyType = '❤️ TypeScript'