Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type middy.MiddlewareFn doesn't exist #1147

Closed
jamiechong opened this issue Dec 2, 2023 · 21 comments
Closed

Type middy.MiddlewareFn doesn't exist #1147

jamiechong opened this issue Dec 2, 2023 · 21 comments

Comments

@jamiechong
Copy link

I'm using v5 of middy and reading these docs on custom middleware. https://middy.js.org/docs/writing-middlewares/with-typescript

But middy.MiddlewareFn isn't available.

@willfarrell
Copy link
Member

I see it in @middy/core/index.d.ts

declare namespace middy {
  export {
    Request,
    PluginHook,
    PluginHookWithMiddlewareName,
    PluginObject,
    MiddlewareFn,
    MiddlewareObj,
    MiddyfiedHandler
  }
}

export default middy

I'm not sure why it wouldn't be showing up for you.

@Valvide
Copy link

Valvide commented Dec 3, 2023

When importing and using @middy/core in my Node.js AWS Lambda application, I am running into the following error:

Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: No "exports" main defined in "<path>/node_modules/@middy/core/package.json"
This prevents being able to import and initialize middy properly.

Steps to Reproduce

  • Create Node.js handler that imports @middy/core
  • Initialize middy middleware with middy()
  • Build and run application
  • Notice error when middy is imported

Cause
Based on the error, it seems there needs to be an "exports" field defined in @middy/core's package.json to point to importable paths within the module.

When this "exports" mapping is not defined, Node is unable to resolve the import request properly at runtime.

@jamiechong
Copy link
Author

@willfarrell - VSCode doesn't seem to think so.

Screenshot 2023-12-03 at 10 26 22 AM Screenshot 2023-12-03 at 10 26 38 AM

@meganmajewski
Copy link

I'm having this same issue with /@middy/http-json-body-parser/package.json

When importing and using @middy/core in my Node.js AWS Lambda application, I am running into the following error:

Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: No "exports" main defined in "<path>/node_modules/@middy/core/package.json" This prevents being able to import and initialize middy properly.

Steps to Reproduce

* Create Node.js handler that imports @middy/core

* Initialize middy middleware with middy()

* Build and run application

* Notice error when middy is imported

Cause Based on the error, it seems there needs to be an "exports" field defined in @middy/core's package.json to point to importable paths within the module.

When this "exports" mapping is not defined, Node is unable to resolve the import request properly at runtime.

@Valvide
Copy link

Valvide commented Dec 20, 2023

@meganmajewski, I resolved the issue by updating the CommonJS usage as mentioned in the updated documentation for Middy. They've made changes from the previous usage, so review the migration guide from v4 to v5 for more details.

@jobuit
Copy link

jobuit commented Jan 29, 2024

Same error Here! @Valvide how do you resolve the issue ?
I was looking in the upgrade official page but I didn't find anything that help me.
https://middy.js.org/docs/upgrade/4-5
image

@david-eolas
Copy link

Having this same issue with @middy/http-json-body-parser
The project is set with Node 20, Yarn 4, serverless 3.38 and middy 5.2.3

Error:

Cannot load "serverless.ts": Initialization error: Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: No "exports" main defined in /Users/espi/workspace/backend/my-files-service/node_modules/@middy/http-json-body-parser/package.json
    at new NodeError (node:internal/errors:405:5)
    at exportsNotFound (node:internal/modules/esm/resolve:359:10)
    at packageExportsResolve (node:internal/modules/esm/resolve:639:13)
    at resolveExports (node:internal/modules/cjs/loader:567:36)
    at Function.Module._findPath (node:internal/modules/cjs/loader:636:31)
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:1063:27)
    at Function.Module._resolveFilename.sharedData.moduleResolveFilenameHook.installedValue (/Users/espi/workspace/backend/my-files-service/node_modules/@cspotcode/source-map-support/source-map-support.js:811:30)
    at Function.Module._resolveFilename (/Users/espi/workspace/backend/my-files-service/node_modules/tsconfig-paths/src/register.ts:115:36)
   .........

@lmammino
Copy link
Member

lmammino commented Feb 4, 2024

Hello all, sorry for the delay in addressing this.

I have tried to replicate the issue and I might have a possible solution in a branch.

Could you try to install @middy/core from this branch and see if that solves your issues? You should be able to do that with:

npm install 'https://gitpkg.now.sh/middyjs/middy/packages/core?fix-1147'

or by setting the following in your package.json and then running npm install:

{
  "dependencies": {
    "@middy/core": "https://gitpkg.now.sh/middyjs/middy/packages/core?fix-1147"
  }
}

It might also be useful to see what your tsconfig.json looks like. Here's my current one for reference:

{
    "compilerOptions": {
      "target": "es2020",
      "strict": true,
      "preserveConstEnums": true,
      "noEmit": true,
      "sourceMap": false,
      "module":"es2015",
      "moduleResolution":"node",
      "esModuleInterop": true, 
      "skipLibCheck": true,
      "forceConsistentCasingInFileNames": true,  
    },
    "exclude": ["node_modules", "**/*.test.ts"]
  }

If this helps fix your issue, we can create a PR, do a more formal review, and make sure the changes land in a new release.

Thanks

Note

Please note that we are not TypeScript experts and maintaining correct types and typescript configuration and docs is always something we struggle with. If someone wants to help to maintain that part more proactively we would love that.

@mkarsene
Copy link

@lmammino That didnt work for me...

@jobuit
Copy link

jobuit commented Feb 13, 2024

I'm getting this typescript error now
image
image
image
and the error continue
image

@david-eolas
Copy link

@lmammino Same error from my side:
Cannot load "serverless.ts": Initialization error: Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: No "exports" main defined in /Users/espi/workspace/backend/my-files-service/node_modules/@middy/http-json-body-parser/package.json

@lmammino
Copy link
Member

No "exports" main defined in .../node_modules/@middy/http-json-body-parser/package.json

That's interesting because I haven't changed that package (I only touched @middy/core)... So I am quite puzzled by this! 🤔

Either way... thanks to @mkarsene, @david-eolas, and @jobuit for testing this change. Could you be so kind to share your TSConfig or, even better, a minimal reproducible example that I can use as a starting point to try to resolve the issue. I am afraid that different versions of typescript and different TSConfig files might lead to very different results, so we would just keep guessing if we don't work on specific shared examples...

@RickDir
Copy link

RickDir commented Feb 19, 2024

Hi @lmammino ,

AWS lambda is throwing:

"errorMessage": "No "exports" main defined in /var/task/node_modules/@middy/http-multipart-body-parser/package.json",

I tried adding core still get the No "exports" error:

"errorMessage": "No "exports" main defined in /var/task/node_modules/@middy/core/package.json"

I’ve also tried various module ways to reference it (since I just need the httpMultipartBodyParser) but to no avail.

exports.handler = httpMultipartBodyParser(async (event) => {

and then:

exports.handler = middy(async (event) => {

Here is my index.js:

console.log('Node version is: ' + process.version);
console.log(process.versions);

const isCustom = require('/opt/nodejs/myCustom');
const myUtil = require('/opt/nodejs/myUtil');

//const middy = require('@middy/core');
const httpMultipartBodyParser = require('@middy/http-multipart-body-parser');

const { S3Client } = require("@aws-sdk/client-s3");
const s3 = new S3Client({ region: "us-east-1" });

exports.handler = async(event) => {
    const res = await isCustom.handler(event);
    if (!res.isValid) { return res.res; }
    return res.def; 
};

Here is my AWS lambda config:

AWS lambda with:
Compatible architectures - Both:

  • x86_64
  • arm64
    Compatible runtimes:
  • nodejs 20.x

Fyi, removing all references to middy and adding the following into my lambda confirms the AWS lambda's are currently using node version: v20.11.0:

console.log('Node version is: ' + process.version);
console.log(process.versions);

This logging shows the following in CloudWatch:

Node version is: v20.11.0
{
node: '20.11.0',
acorn: '8.11.2',
ada: '2.7.4',
ares: '1.20.1',
base64: '0.5.1',
brotli: '1.0.9',
cjs_module_lexer: '1.2.2',
cldr: '43.1',
icu: '73.2',
llhttp: '8.1.1',
modules: '115',
napi: '9',
nghttp2: '1.58.0',
openssl: '3.1.4',
simdutf: '4.0.4',
tz: '2023c',
undici: '5.27.2',
unicode: '15.0',
uv: '1.46.0',
uvwasi: '0.0.19',
v8: '11.3.244.8-node.17',
zlib: '1.2.13.1-motley-5daffc7'
}

I have a super simple set up so anyone can easily reproduce the error:

  • Windows 10 with VS Code.
  • Just installed node 20.11.1 LTS from nodejs.org using the big button which downloads:

node-v20.11.1-x64.msi

  • In my VS Code terminal:
    npm install npm@latest -g
  • So now
    npm -v
    Shows version: 10.4.0
    node -v
    Shows version: v20.11.1
  1. Created my folder "c:\git\lmbd-202-api" and added in my "index.js" as shown above.
  2. In VS Code: File, Open [that] folder.
  3. In VS Code: Terminal, New terminal and type:
    npm init -y
  4. Then type:
    npm install @middy/http-multipart-body-parser
  5. Selected all the files in my "lmbd-202-api" folder, right mouse click: Send to: Compressed zip folder, and name it "lmbd-202-api.zip."
  6. In the AWS Lambda console, on the “Code source” page, click Upload from, .zip file. Select the lmbd-202-api.zip. Note "lmbd-202-api" is also the exact name of my Lambda function.
  7. In the AWS Lambda console, add a space after any semicolon so the Deploy button becomes active; Then click it.
  8. Hitting the end point with Postman throws a 500 level error and CloudWatch shows the errors stated above.
    Good Luck! I’d love to try out Middy 😊 Or if I screwed up someplace, please let me know. Thank you

Below is the full CloudWatch error:

2024-02-19T09:50:47.891Z undefined ERROR Uncaught Exception
{
"errorType": "Error",
"errorMessage": "No "exports" main defined in /var/task/node_modules/@middy/http-multipart-body-parser/package.json",
"code": "ERR_PACKAGE_PATH_NOT_EXPORTED",
"stack": [
"Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: No "exports" main defined in /var/task/node_modules/@middy/http-multipart-body-parser/package.json",
" at exportsNotFound (node:internal/modules/esm/resolve:308:10)",
" at packageExportsResolve (node:internal/modules/esm/resolve:598:13)",
" at resolveExports (node:internal/modules/cjs/loader:591:36)",
" at Module._findPath (node:internal/modules/cjs/loader:668:31)",
" at Module._resolveFilename (node:internal/modules/cjs/loader:1130:27)",
" at Module._load (node:internal/modules/cjs/loader:985:27)",
" at Module.require (node:internal/modules/cjs/loader:1235:19)",
" at require (node:internal/modules/helpers:176:18)",
" at Object. (/var/task/index.js:7:33)",
" at Module._compile (node:internal/modules/cjs/loader:1376:14)"
]
}

@willfarrell
Copy link
Member

@RickDir Middy v5 doesn't support CommonJS, v4 does if you're unable to update to ESM yet.

@RickDir
Copy link

RickDir commented Feb 20, 2024

@RickDir Middy v5 doesn't support CommonJS, v4 does if you're unable to update to ESM yet.

Thanks @willfarrell Testing with ESM exposed the install instructions I got were lacking as well (throws: Cannot find package '@middy/util') I’ll have to dive deeper into the documentation to make sure I'm starting off correctly. Thanks again

@micheledel
Copy link

Hi all,

someone has resolved the issue?

I'm encountering it with middy/core 5.3.1

@refjosh
Copy link

refjosh commented Mar 29, 2024

@RickDir Middy v5 doesn't support CommonJS, v4 does if you're unable to update to ESM yet.

Installing v4.7.0 does resolve the issue on my end

@willfarrell
Copy link
Member

We think this should be resolved in 5.3.3. Please reopen if now

@gbisaga
Copy link

gbisaga commented May 12, 2024

It is not resolved in 5.3.3, at least for my situation. However, I've been able to get around it. I figure this might act as a clue to the ultimate fix. The key was that it works fine, except when I do something like this:

function prepare(fn) {
  return middy(fn).(add a bunch of middleware here);
}
export const portalsGetList = prepare(fn);

/********* Meanwhile, in another file that imports `portalsGetList` *********/
console.log(portalsGetList.name); // <-- this is the problem

When I get rid of the direct reference and .name, it builds. Otherwise I am getting:

    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:995:15)
    at Function.Module._resolveFilename.sharedData.moduleResolveFilenameHook.installedValue [as _resolveFilename] (C:\src\vkd\vermontkidsdata-app\node_modules\@cspotcode\source-map-support\source-map-support.js:811:30)
    at Function.Module._load (node:internal/modules/cjs/loader:841:27)
    at Module.require (node:internal/modules/cjs/loader:1061:19)
    at require (node:internal/modules/cjs/helpers:103:18)
    at Object.<anonymous> (C:\src\vkd\vermontkidsdata-app\lib\portals-functions.ts:6:1)
    at Module._compile (node:internal/modules/cjs/loader:1159:14)
    at Module.m._compile (C:\src\vkd\vermontkidsdata-app\node_modules\ts-node\src\index.ts:1618:23)
    at Module._extensions..js (node:internal/modules/cjs/loader:1213:10)
    at Object.require.extensions.<computed> [as .ts] (C:\src\vkd\vermontkidsdata-app\node_modules\ts-node\src\index.ts:1621:12) {
  code: 'MODULE_NOT_FOUND',

@roastdev
Copy link

I'm running into the same thing on the latest version of Middy

No "exports" main defined in /var/task/node_modules/@middy/core/package.json.

My Lambda function does a simple export like this and we're using ESM now

"@middy/core": "^5.3.5"

@colmeye
Copy link

colmeye commented Jun 5, 2024

I am also encountering this issue. I've tried 5.3.2, 5.3.3, and 5.4.0 with no luck. I have a suspicion it has to do with how I'm importing it from another package in my monorepo 🤔 even though I have all middy dependencies installed in each package
Cannot load "serverless.ts": Initialization error: Error: No "exports" main defined in pathstuff/packages/shared-api/node_modules/@middy/core/package.json

Edit: Yep. Middy stuff does not enjoy being imported from another package within my pnpm monorepo... Not sure why that is though

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Development

No branches or pull requests