chore(deps): upgrade newrelic

This commit is contained in:
Karol Sójko 2023-01-18 09:49:38 +01:00
parent 9cf1a9e25c
commit 7ef59bb74c
No known key found for this signature in database
GPG key ID: A50543BF560BDEB0
160 changed files with 870 additions and 12442 deletions

140
.pnp.cjs generated
View file

@ -128,13 +128,13 @@ const RAW_RUNTIME_STATE =
["@lerna-lite/run", "npm:1.6.0"],\
["@sentry/node", "npm:7.28.1"],\
["@types/jest", "npm:29.1.1"],\
["@types/newrelic", "npm:7.0.4"],\
["@types/newrelic", "npm:9.4.0"],\
["@types/node", "npm:18.11.9"],\
["@typescript-eslint/parser", "virtual:8859b278716fedf3e7458b5628625f7e35678c418626878559a0b816445001b7e24c55546f4677ba4c20b521aa0cf52cc33ac07deff171e383ada6eeab69933f#npm:5.40.1"],\
["eslint", "npm:8.19.0"],\
["eslint-config-prettier", "virtual:8859b278716fedf3e7458b5628625f7e35678c418626878559a0b816445001b7e24c55546f4677ba4c20b521aa0cf52cc33ac07deff171e383ada6eeab69933f#npm:8.5.0"],\
["ini", "npm:3.0.0"],\
["newrelic", "npm:9.6.0"],\
["newrelic", "npm:9.8.0"],\
["npm-check-updates", "npm:16.0.1"],\
["prettier", "npm:2.7.1"],\
["ts-node", "virtual:8859b278716fedf3e7458b5628625f7e35678c418626878559a0b816445001b7e24c55546f4677ba4c20b521aa0cf52cc33ac07deff171e383ada6eeab69933f#npm:10.9.1"],\
@ -1130,6 +1130,18 @@ const RAW_RUNTIME_STATE =
"linkType": "HARD"\
}]\
]],\
["@contrast/fn-inspect", [\
["npm:3.3.0", {\
"packageLocation": "./.yarn/unplugged/@contrast-fn-inspect-npm-3.3.0-c6a8faa5b7/node_modules/@contrast/fn-inspect/",\
"packageDependencies": [\
["@contrast/fn-inspect", "npm:3.3.0"],\
["nan", "npm:2.16.0"],\
["node-gyp", "npm:9.0.0"],\
["node-gyp-build", "npm:4.5.0"]\
],\
"linkType": "HARD"\
}]\
]],\
["@cspotcode/source-map-support", [\
["npm:0.8.1", {\
"packageLocation": "./.yarn/cache/@cspotcode-source-map-support-npm-0.8.1-964f2de99d-4327d8e6e4.zip/node_modules/@cspotcode/source-map-support/",\
@ -1196,25 +1208,25 @@ const RAW_RUNTIME_STATE =
}]\
]],\
["@grpc/grpc-js", [\
["npm:1.6.7", {\
"packageLocation": "./.yarn/cache/@grpc-grpc-js-npm-1.6.7-2e10ef0dbb-be24dd50f5.zip/node_modules/@grpc/grpc-js/",\
["npm:1.8.4", {\
"packageLocation": "./.yarn/cache/@grpc-grpc-js-npm-1.8.4-287c8bdac8-6367a2ee38.zip/node_modules/@grpc/grpc-js/",\
"packageDependencies": [\
["@grpc/grpc-js", "npm:1.6.7"],\
["@grpc/proto-loader", "npm:0.6.13"],\
["@grpc/grpc-js", "npm:1.8.4"],\
["@grpc/proto-loader", "npm:0.7.4"],\
["@types/node", "npm:18.0.3"]\
],\
"linkType": "HARD"\
}]\
]],\
["@grpc/proto-loader", [\
["npm:0.6.13", {\
"packageLocation": "./.yarn/cache/@grpc-proto-loader-npm-0.6.13-658ac26dfb-6272a0318b.zip/node_modules/@grpc/proto-loader/",\
["npm:0.7.4", {\
"packageLocation": "./.yarn/cache/@grpc-proto-loader-npm-0.7.4-43d91344a0-1f5d4211fe.zip/node_modules/@grpc/proto-loader/",\
"packageDependencies": [\
["@grpc/proto-loader", "npm:0.6.13"],\
["@grpc/proto-loader", "npm:0.7.4"],\
["@types/long", "npm:4.0.2"],\
["lodash.camelcase", "npm:4.3.0"],\
["long", "npm:4.0.0"],\
["protobufjs", "npm:6.11.3"],\
["protobufjs", "npm:7.1.2"],\
["yargs", "npm:16.2.0"]\
],\
"linkType": "HARD"\
@ -1875,12 +1887,12 @@ const RAW_RUNTIME_STATE =
],\
"linkType": "SOFT"\
}],\
["virtual:f10080c2deb75096716a913b06010dcd94891c77539a757ab32210a1efc3ff91527b36d6c7c46e890db826160e0724553ca23acd0a8a734b5554c9600c71eb52#npm:5.0.0", {\
"packageLocation": "./.yarn/__virtual__/@newrelic-aws-sdk-virtual-ccf1e948b3/0/cache/@newrelic-aws-sdk-npm-5.0.0-7d9d10d58f-ed1dc3fa16.zip/node_modules/@newrelic/aws-sdk/",\
["virtual:4c49b89cbc97666c528d8405a7490a32a30cd8b65c1a61cb32c444f3a312dab1385405717f9866d113d67518b3d487f15de177279ba1a80f8958b28cad021846#npm:5.0.0", {\
"packageLocation": "./.yarn/__virtual__/@newrelic-aws-sdk-virtual-b32c5d232e/0/cache/@newrelic-aws-sdk-npm-5.0.0-7d9d10d58f-ed1dc3fa16.zip/node_modules/@newrelic/aws-sdk/",\
"packageDependencies": [\
["@newrelic/aws-sdk", "virtual:f10080c2deb75096716a913b06010dcd94891c77539a757ab32210a1efc3ff91527b36d6c7c46e890db826160e0724553ca23acd0a8a734b5554c9600c71eb52#npm:5.0.0"],\
["@newrelic/aws-sdk", "virtual:4c49b89cbc97666c528d8405a7490a32a30cd8b65c1a61cb32c444f3a312dab1385405717f9866d113d67518b3d487f15de177279ba1a80f8958b28cad021846#npm:5.0.0"],\
["@types/newrelic", null],\
["newrelic", "npm:9.6.0"]\
["newrelic", "npm:9.8.0"]\
],\
"packagePeers": [\
"@types/newrelic",\
@ -1897,12 +1909,12 @@ const RAW_RUNTIME_STATE =
],\
"linkType": "SOFT"\
}],\
["virtual:f10080c2deb75096716a913b06010dcd94891c77539a757ab32210a1efc3ff91527b36d6c7c46e890db826160e0724553ca23acd0a8a734b5554c9600c71eb52#npm:7.0.0", {\
"packageLocation": "./.yarn/__virtual__/@newrelic-koa-virtual-613d84b4f1/0/cache/@newrelic-koa-npm-7.0.0-903c251b9f-0fc2298c8b.zip/node_modules/@newrelic/koa/",\
["virtual:4c49b89cbc97666c528d8405a7490a32a30cd8b65c1a61cb32c444f3a312dab1385405717f9866d113d67518b3d487f15de177279ba1a80f8958b28cad021846#npm:7.0.0", {\
"packageLocation": "./.yarn/__virtual__/@newrelic-koa-virtual-cc6a41398f/0/cache/@newrelic-koa-npm-7.0.0-903c251b9f-0fc2298c8b.zip/node_modules/@newrelic/koa/",\
"packageDependencies": [\
["@newrelic/koa", "virtual:f10080c2deb75096716a913b06010dcd94891c77539a757ab32210a1efc3ff91527b36d6c7c46e890db826160e0724553ca23acd0a8a734b5554c9600c71eb52#npm:7.0.0"],\
["@newrelic/koa", "virtual:4c49b89cbc97666c528d8405a7490a32a30cd8b65c1a61cb32c444f3a312dab1385405717f9866d113d67518b3d487f15de177279ba1a80f8958b28cad021846#npm:7.0.0"],\
["@types/newrelic", null],\
["newrelic", "npm:9.6.0"]\
["newrelic", "npm:9.8.0"]\
],\
"packagePeers": [\
"@types/newrelic",\
@ -1932,12 +1944,12 @@ const RAW_RUNTIME_STATE =
],\
"linkType": "SOFT"\
}],\
["virtual:f10080c2deb75096716a913b06010dcd94891c77539a757ab32210a1efc3ff91527b36d6c7c46e890db826160e0724553ca23acd0a8a734b5554c9600c71eb52#npm:6.0.0", {\
"packageLocation": "./.yarn/__virtual__/@newrelic-superagent-virtual-37eb7b41a0/0/cache/@newrelic-superagent-npm-6.0.0-db8b77d0f3-b77997b792.zip/node_modules/@newrelic/superagent/",\
["virtual:4c49b89cbc97666c528d8405a7490a32a30cd8b65c1a61cb32c444f3a312dab1385405717f9866d113d67518b3d487f15de177279ba1a80f8958b28cad021846#npm:6.0.0", {\
"packageLocation": "./.yarn/__virtual__/@newrelic-superagent-virtual-dc0653ca20/0/cache/@newrelic-superagent-npm-6.0.0-db8b77d0f3-b77997b792.zip/node_modules/@newrelic/superagent/",\
"packageDependencies": [\
["@newrelic/superagent", "virtual:f10080c2deb75096716a913b06010dcd94891c77539a757ab32210a1efc3ff91527b36d6c7c46e890db826160e0724553ca23acd0a8a734b5554c9600c71eb52#npm:6.0.0"],\
["@newrelic/superagent", "virtual:4c49b89cbc97666c528d8405a7490a32a30cd8b65c1a61cb32c444f3a312dab1385405717f9866d113d67518b3d487f15de177279ba1a80f8958b28cad021846#npm:6.0.0"],\
["@types/newrelic", null],\
["newrelic", "npm:9.6.0"]\
["newrelic", "npm:9.8.0"]\
],\
"packagePeers": [\
"@types/newrelic",\
@ -1958,8 +1970,8 @@ const RAW_RUNTIME_STATE =
"packageLocation": "./.yarn/__virtual__/@newrelic-winston-enricher-virtual-6b8c53ab3d/0/cache/@newrelic-winston-enricher-npm-4.0.0-ebaf2d0d28-3fc901cded.zip/node_modules/@newrelic/winston-enricher/",\
"packageDependencies": [\
["@newrelic/winston-enricher", "virtual:c66bf20e88479ada0172094776519a9f51acc4731d22079b60a295bcec7ea42d5545cbce58a77a50d932bf953298799135e99707486e343da6d99ba1d167bdbd#npm:4.0.0"],\
["@types/newrelic", "npm:7.0.4"],\
["newrelic", "npm:9.6.0"]\
["@types/newrelic", "npm:9.4.0"],\
["newrelic", "npm:9.8.0"]\
],\
"packagePeers": [\
"@types/newrelic",\
@ -2635,7 +2647,7 @@ const RAW_RUNTIME_STATE =
["@types/ioredis", "npm:5.0.0"],\
["@types/jest", "npm:29.1.1"],\
["@types/mixpanel", "npm:2.14.4"],\
["@types/newrelic", "npm:7.0.4"],\
["@types/newrelic", "npm:9.4.0"],\
["@types/node", "npm:18.11.9"],\
["@typescript-eslint/eslint-plugin", "virtual:c66bf20e88479ada0172094776519a9f51acc4731d22079b60a295bcec7ea42d5545cbce58a77a50d932bf953298799135e99707486e343da6d99ba1d167bdbd#npm:5.30.5"],\
["aws-sdk", "npm:2.1260.0"],\
@ -2648,7 +2660,7 @@ const RAW_RUNTIME_STATE =
["jest", "virtual:fd909b174d079e30b336c4ce72c38a88c1e447767b1a8dd7655e07719a1e31b97807f0931368724fc78897ff15e6a6d00b83316c0f76d11f85111f342e08bb79#npm:29.1.2"],\
["mixpanel", "npm:0.17.0"],\
["mysql2", "npm:3.0.1"],\
["newrelic", "npm:9.6.0"],\
["newrelic", "npm:9.8.0"],\
["reflect-metadata", "npm:0.1.13"],\
["ts-jest", "virtual:fd909b174d079e30b336c4ce72c38a88c1e447767b1a8dd7655e07719a1e31b97807f0931368724fc78897ff15e6a6d00b83316c0f76d11f85111f342e08bb79#npm:29.0.3"],\
["typeorm", "virtual:c66bf20e88479ada0172094776519a9f51acc4731d22079b60a295bcec7ea42d5545cbce58a77a50d932bf953298799135e99707486e343da6d99ba1d167bdbd#npm:0.3.10"],\
@ -2691,7 +2703,7 @@ const RAW_RUNTIME_STATE =
["@types/ioredis", "npm:5.0.0"],\
["@types/jest", "npm:29.1.1"],\
["@types/jsonwebtoken", "npm:9.0.1"],\
["@types/newrelic", "npm:7.0.4"],\
["@types/newrelic", "npm:9.4.0"],\
["@types/prettyjson", "npm:0.0.30"],\
["@typescript-eslint/eslint-plugin", "virtual:04783e12400851b8a3d76e71495851cc94959db6e62f04cb0a31190080629440b182d8c8eb4d7f2b04e281912f2783a5fd4d2c3c6ab68d38b7097246c93f4c19#npm:5.40.1"],\
["aws-sdk", "npm:2.1260.0"],\
@ -2708,7 +2720,7 @@ const RAW_RUNTIME_STATE =
["ioredis", "npm:5.2.4"],\
["jest", "virtual:fd909b174d079e30b336c4ce72c38a88c1e447767b1a8dd7655e07719a1e31b97807f0931368724fc78897ff15e6a6d00b83316c0f76d11f85111f342e08bb79#npm:29.1.2"],\
["jsonwebtoken", "npm:9.0.0"],\
["newrelic", "npm:9.6.0"],\
["newrelic", "npm:9.8.0"],\
["nodemon", "npm:2.0.20"],\
["npm-check-updates", "npm:16.0.1"],\
["prettyjson", "npm:1.2.5"],\
@ -2759,7 +2771,7 @@ const RAW_RUNTIME_STATE =
["@types/express", "npm:4.17.14"],\
["@types/ioredis", "npm:5.0.0"],\
["@types/jest", "npm:29.1.1"],\
["@types/newrelic", "npm:7.0.4"],\
["@types/newrelic", "npm:9.4.0"],\
["@types/otplib", "npm:10.0.0"],\
["@types/prettyjson", "npm:0.0.30"],\
["@types/ua-parser-js", "npm:0.7.36"],\
@ -2779,7 +2791,7 @@ const RAW_RUNTIME_STATE =
["ioredis", "npm:5.2.4"],\
["jest", "virtual:fd909b174d079e30b336c4ce72c38a88c1e447767b1a8dd7655e07719a1e31b97807f0931368724fc78897ff15e6a6d00b83316c0f76d11f85111f342e08bb79#npm:29.1.2"],\
["mysql2", "npm:3.0.1"],\
["newrelic", "npm:9.6.0"],\
["newrelic", "npm:9.8.0"],\
["nodemon", "npm:2.0.20"],\
["npm-check-updates", "npm:16.0.1"],\
["otplib", "npm:12.0.1"],\
@ -2873,13 +2885,13 @@ const RAW_RUNTIME_STATE =
["@standardnotes/domain-events", "workspace:packages/domain-events"],\
["@types/ioredis", "npm:5.0.0"],\
["@types/jest", "npm:29.1.1"],\
["@types/newrelic", "npm:7.0.4"],\
["@types/newrelic", "npm:9.4.0"],\
["@typescript-eslint/eslint-plugin", "virtual:fd909b174d079e30b336c4ce72c38a88c1e447767b1a8dd7655e07719a1e31b97807f0931368724fc78897ff15e6a6d00b83316c0f76d11f85111f342e08bb79#npm:5.30.5"],\
["aws-sdk", "npm:2.1260.0"],\
["eslint-plugin-prettier", "virtual:fd909b174d079e30b336c4ce72c38a88c1e447767b1a8dd7655e07719a1e31b97807f0931368724fc78897ff15e6a6d00b83316c0f76d11f85111f342e08bb79#npm:4.2.1"],\
["ioredis", "npm:5.2.4"],\
["jest", "virtual:fd909b174d079e30b336c4ce72c38a88c1e447767b1a8dd7655e07719a1e31b97807f0931368724fc78897ff15e6a6d00b83316c0f76d11f85111f342e08bb79#npm:29.1.2"],\
["newrelic", "npm:9.6.0"],\
["newrelic", "npm:9.8.0"],\
["reflect-metadata", "npm:0.1.13"],\
["sqs-consumer", "virtual:685a6222c3349423674bb7f0684ba34e2ab20912010f352e04dcf707a156e13183fc382e2417cb37a60f3e7b52fd0178c53181674890e1773eb83e190dc13378#npm:5.7.0"],\
["ts-jest", "virtual:fd909b174d079e30b336c4ce72c38a88c1e447767b1a8dd7655e07719a1e31b97807f0931368724fc78897ff15e6a6d00b83316c0f76d11f85111f342e08bb79#npm:29.0.3"],\
@ -2914,7 +2926,7 @@ const RAW_RUNTIME_STATE =
["@standardnotes/time", "workspace:packages/time"],\
["@types/ioredis", "npm:5.0.0"],\
["@types/jest", "npm:29.1.1"],\
["@types/newrelic", "npm:7.0.4"],\
["@types/newrelic", "npm:9.4.0"],\
["@types/nodemailer", "npm:6.4.6"],\
["@typescript-eslint/eslint-plugin", "virtual:04783e12400851b8a3d76e71495851cc94959db6e62f04cb0a31190080629440b182d8c8eb4d7f2b04e281912f2783a5fd4d2c3c6ab68d38b7097246c93f4c19#npm:5.40.1"],\
["aws-sdk", "npm:2.1260.0"],\
@ -2925,7 +2937,7 @@ const RAW_RUNTIME_STATE =
["ioredis", "npm:5.2.4"],\
["jest", "virtual:fd909b174d079e30b336c4ce72c38a88c1e447767b1a8dd7655e07719a1e31b97807f0931368724fc78897ff15e6a6d00b83316c0f76d11f85111f342e08bb79#npm:29.1.2"],\
["mysql2", "npm:3.0.1"],\
["newrelic", "npm:9.6.0"],\
["newrelic", "npm:9.8.0"],\
["reflect-metadata", "npm:0.1.13"],\
["ts-jest", "virtual:fd909b174d079e30b336c4ce72c38a88c1e447767b1a8dd7655e07719a1e31b97807f0931368724fc78897ff15e6a6d00b83316c0f76d11f85111f342e08bb79#npm:29.0.3"],\
["typeorm", "virtual:c66bf20e88479ada0172094776519a9f51acc4731d22079b60a295bcec7ea42d5545cbce58a77a50d932bf953298799135e99707486e343da6d99ba1d167bdbd#npm:0.3.10"],\
@ -2979,7 +2991,7 @@ const RAW_RUNTIME_STATE =
["@types/ioredis", "npm:5.0.0"],\
["@types/jest", "npm:29.1.1"],\
["@types/jsonwebtoken", "npm:9.0.1"],\
["@types/newrelic", "npm:7.0.4"],\
["@types/newrelic", "npm:9.4.0"],\
["@types/prettyjson", "npm:0.0.30"],\
["@types/uuid", "npm:8.3.4"],\
["@typescript-eslint/eslint-plugin", "virtual:04783e12400851b8a3d76e71495851cc94959db6e62f04cb0a31190080629440b182d8c8eb4d7f2b04e281912f2783a5fd4d2c3c6ab68d38b7097246c93f4c19#npm:5.40.1"],\
@ -2999,7 +3011,7 @@ const RAW_RUNTIME_STATE =
["ioredis", "npm:5.2.4"],\
["jest", "virtual:fd909b174d079e30b336c4ce72c38a88c1e447767b1a8dd7655e07719a1e31b97807f0931368724fc78897ff15e6a6d00b83316c0f76d11f85111f342e08bb79#npm:29.1.2"],\
["jsonwebtoken", "npm:9.0.0"],\
["newrelic", "npm:9.6.0"],\
["newrelic", "npm:9.8.0"],\
["nodemon", "npm:2.0.20"],\
["npm-check-updates", "npm:16.0.1"],\
["prettyjson", "npm:1.2.5"],\
@ -3114,7 +3126,7 @@ const RAW_RUNTIME_STATE =
["@types/inversify-express-utils", "npm:2.0.0"],\
["@types/ioredis", "npm:5.0.0"],\
["@types/jest", "npm:29.1.1"],\
["@types/newrelic", "npm:7.0.4"],\
["@types/newrelic", "npm:9.4.0"],\
["@typescript-eslint/eslint-plugin", "virtual:04783e12400851b8a3d76e71495851cc94959db6e62f04cb0a31190080629440b182d8c8eb4d7f2b04e281912f2783a5fd4d2c3c6ab68d38b7097246c93f4c19#npm:5.40.1"],\
["aws-sdk", "npm:2.1260.0"],\
["cors", "npm:2.8.5"],\
@ -3128,7 +3140,7 @@ const RAW_RUNTIME_STATE =
["ioredis", "npm:5.2.4"],\
["jest", "virtual:fd909b174d079e30b336c4ce72c38a88c1e447767b1a8dd7655e07719a1e31b97807f0931368724fc78897ff15e6a6d00b83316c0f76d11f85111f342e08bb79#npm:29.1.2"],\
["mysql2", "npm:3.0.1"],\
["newrelic", "npm:9.6.0"],\
["newrelic", "npm:9.8.0"],\
["npm-check-updates", "npm:16.0.1"],\
["reflect-metadata", "npm:0.1.13"],\
["ts-jest", "virtual:fd909b174d079e30b336c4ce72c38a88c1e447767b1a8dd7655e07719a1e31b97807f0931368724fc78897ff15e6a6d00b83316c0f76d11f85111f342e08bb79#npm:29.0.3"],\
@ -3154,7 +3166,7 @@ const RAW_RUNTIME_STATE =
["@standardnotes/time", "workspace:packages/time"],\
["@types/ioredis", "npm:5.0.0"],\
["@types/jest", "npm:29.1.1"],\
["@types/newrelic", "npm:7.0.4"],\
["@types/newrelic", "npm:9.4.0"],\
["@types/node", "npm:18.11.9"],\
["@typescript-eslint/eslint-plugin", "virtual:04783e12400851b8a3d76e71495851cc94959db6e62f04cb0a31190080629440b182d8c8eb4d7f2b04e281912f2783a5fd4d2c3c6ab68d38b7097246c93f4c19#npm:5.40.1"],\
["aws-sdk", "npm:2.1260.0"],\
@ -3166,7 +3178,7 @@ const RAW_RUNTIME_STATE =
["ioredis", "npm:5.2.4"],\
["jest", "virtual:fd909b174d079e30b336c4ce72c38a88c1e447767b1a8dd7655e07719a1e31b97807f0931368724fc78897ff15e6a6d00b83316c0f76d11f85111f342e08bb79#npm:29.1.2"],\
["mysql2", "npm:3.0.1"],\
["newrelic", "npm:9.6.0"],\
["newrelic", "npm:9.8.0"],\
["npm-check-updates", "npm:16.0.1"],\
["reflect-metadata", "npm:0.1.13"],\
["ts-jest", "virtual:fd909b174d079e30b336c4ce72c38a88c1e447767b1a8dd7655e07719a1e31b97807f0931368724fc78897ff15e6a6d00b83316c0f76d11f85111f342e08bb79#npm:29.0.3"],\
@ -3208,13 +3220,13 @@ const RAW_RUNTIME_STATE =
["@lerna-lite/run", "npm:1.6.0"],\
["@sentry/node", "npm:7.28.1"],\
["@types/jest", "npm:29.1.1"],\
["@types/newrelic", "npm:7.0.4"],\
["@types/newrelic", "npm:9.4.0"],\
["@types/node", "npm:18.11.9"],\
["@typescript-eslint/parser", "virtual:8859b278716fedf3e7458b5628625f7e35678c418626878559a0b816445001b7e24c55546f4677ba4c20b521aa0cf52cc33ac07deff171e383ada6eeab69933f#npm:5.40.1"],\
["eslint", "npm:8.19.0"],\
["eslint-config-prettier", "virtual:8859b278716fedf3e7458b5628625f7e35678c418626878559a0b816445001b7e24c55546f4677ba4c20b521aa0cf52cc33ac07deff171e383ada6eeab69933f#npm:8.5.0"],\
["ini", "npm:3.0.0"],\
["newrelic", "npm:9.6.0"],\
["newrelic", "npm:9.8.0"],\
["npm-check-updates", "npm:16.0.1"],\
["prettier", "npm:2.7.1"],\
["ts-node", "virtual:8859b278716fedf3e7458b5628625f7e35678c418626878559a0b816445001b7e24c55546f4677ba4c20b521aa0cf52cc33ac07deff171e383ada6eeab69933f#npm:10.9.1"],\
@ -3290,7 +3302,7 @@ const RAW_RUNTIME_STATE =
["@types/ioredis", "npm:5.0.0"],\
["@types/jest", "npm:29.1.1"],\
["@types/jsonwebtoken", "npm:9.0.1"],\
["@types/newrelic", "npm:7.0.4"],\
["@types/newrelic", "npm:9.4.0"],\
["@types/prettyjson", "npm:0.0.30"],\
["@types/ua-parser-js", "npm:0.7.36"],\
["@types/uuid", "npm:8.3.4"],\
@ -3309,7 +3321,7 @@ const RAW_RUNTIME_STATE =
["jest", "virtual:fd909b174d079e30b336c4ce72c38a88c1e447767b1a8dd7655e07719a1e31b97807f0931368724fc78897ff15e6a6d00b83316c0f76d11f85111f342e08bb79#npm:29.1.2"],\
["jsonwebtoken", "npm:9.0.0"],\
["mysql2", "npm:3.0.1"],\
["newrelic", "npm:9.6.0"],\
["newrelic", "npm:9.8.0"],\
["nodemon", "npm:2.0.20"],\
["npm-check-updates", "npm:16.0.1"],\
["prettyjson", "npm:1.2.5"],\
@ -3383,7 +3395,7 @@ const RAW_RUNTIME_STATE =
["@types/express", "npm:4.17.14"],\
["@types/ioredis", "npm:5.0.0"],\
["@types/jest", "npm:29.1.1"],\
["@types/newrelic", "npm:7.0.4"],\
["@types/newrelic", "npm:9.4.0"],\
["@typescript-eslint/eslint-plugin", "virtual:04783e12400851b8a3d76e71495851cc94959db6e62f04cb0a31190080629440b182d8c8eb4d7f2b04e281912f2783a5fd4d2c3c6ab68d38b7097246c93f4c19#npm:5.40.1"],\
["aws-sdk", "npm:2.1260.0"],\
["axios", "npm:1.1.3"],\
@ -3397,7 +3409,7 @@ const RAW_RUNTIME_STATE =
["ioredis", "npm:5.2.4"],\
["jest", "virtual:fd909b174d079e30b336c4ce72c38a88c1e447767b1a8dd7655e07719a1e31b97807f0931368724fc78897ff15e6a6d00b83316c0f76d11f85111f342e08bb79#npm:29.1.2"],\
["mysql2", "npm:3.0.1"],\
["newrelic", "npm:9.6.0"],\
["newrelic", "npm:9.8.0"],\
["reflect-metadata", "npm:0.1.13"],\
["ts-jest", "virtual:fd909b174d079e30b336c4ce72c38a88c1e447767b1a8dd7655e07719a1e31b97807f0931368724fc78897ff15e6a6d00b83316c0f76d11f85111f342e08bb79#npm:29.0.3"],\
["typeorm", "virtual:c66bf20e88479ada0172094776519a9f51acc4731d22079b60a295bcec7ea42d5545cbce58a77a50d932bf953298799135e99707486e343da6d99ba1d167bdbd#npm:0.3.10"],\
@ -3426,7 +3438,7 @@ const RAW_RUNTIME_STATE =
["@types/express", "npm:4.17.14"],\
["@types/ioredis", "npm:5.0.0"],\
["@types/jest", "npm:29.1.1"],\
["@types/newrelic", "npm:7.0.4"],\
["@types/newrelic", "npm:9.4.0"],\
["@typescript-eslint/eslint-plugin", "virtual:04783e12400851b8a3d76e71495851cc94959db6e62f04cb0a31190080629440b182d8c8eb4d7f2b04e281912f2783a5fd4d2c3c6ab68d38b7097246c93f4c19#npm:5.40.1"],\
["aws-sdk", "npm:2.1260.0"],\
["cors", "npm:2.8.5"],\
@ -3439,7 +3451,7 @@ const RAW_RUNTIME_STATE =
["ioredis", "npm:5.2.4"],\
["jest", "virtual:fd909b174d079e30b336c4ce72c38a88c1e447767b1a8dd7655e07719a1e31b97807f0931368724fc78897ff15e6a6d00b83316c0f76d11f85111f342e08bb79#npm:29.1.2"],\
["mysql2", "npm:3.0.1"],\
["newrelic", "npm:9.6.0"],\
["newrelic", "npm:9.8.0"],\
["reflect-metadata", "npm:0.1.13"],\
["ts-jest", "virtual:fd909b174d079e30b336c4ce72c38a88c1e447767b1a8dd7655e07719a1e31b97807f0931368724fc78897ff15e6a6d00b83316c0f76d11f85111f342e08bb79#npm:29.0.3"],\
["typeorm", "virtual:c66bf20e88479ada0172094776519a9f51acc4731d22079b60a295bcec7ea42d5545cbce58a77a50d932bf953298799135e99707486e343da6d99ba1d167bdbd#npm:0.3.10"],\
@ -3830,10 +3842,10 @@ const RAW_RUNTIME_STATE =
}]\
]],\
["@types/newrelic", [\
["npm:7.0.4", {\
"packageLocation": "./.yarn/cache/@types-newrelic-npm-7.0.4-4f0b179b51-b44215b3ab.zip/node_modules/@types/newrelic/",\
["npm:9.4.0", {\
"packageLocation": "./.yarn/cache/@types-newrelic-npm-9.4.0-72a77bd5e6-adb12973e8.zip/node_modules/@types/newrelic/",\
"packageDependencies": [\
["@types/newrelic", "npm:7.0.4"]\
["@types/newrelic", "npm:9.4.0"]\
],\
"linkType": "HARD"\
}]\
@ -10764,16 +10776,17 @@ const RAW_RUNTIME_STATE =
}]\
]],\
["newrelic", [\
["npm:9.6.0", {\
"packageLocation": "./.yarn/cache/newrelic-npm-9.6.0-f10080c2de-eb378acde1.zip/node_modules/newrelic/",\
["npm:9.8.0", {\
"packageLocation": "./.yarn/cache/newrelic-npm-9.8.0-4c49b89cbc-ed3b893298.zip/node_modules/newrelic/",\
"packageDependencies": [\
["newrelic", "npm:9.6.0"],\
["@grpc/grpc-js", "npm:1.6.7"],\
["@grpc/proto-loader", "npm:0.6.13"],\
["@newrelic/aws-sdk", "virtual:f10080c2deb75096716a913b06010dcd94891c77539a757ab32210a1efc3ff91527b36d6c7c46e890db826160e0724553ca23acd0a8a734b5554c9600c71eb52#npm:5.0.0"],\
["@newrelic/koa", "virtual:f10080c2deb75096716a913b06010dcd94891c77539a757ab32210a1efc3ff91527b36d6c7c46e890db826160e0724553ca23acd0a8a734b5554c9600c71eb52#npm:7.0.0"],\
["newrelic", "npm:9.8.0"],\
["@contrast/fn-inspect", "npm:3.3.0"],\
["@grpc/grpc-js", "npm:1.8.4"],\
["@grpc/proto-loader", "npm:0.7.4"],\
["@newrelic/aws-sdk", "virtual:4c49b89cbc97666c528d8405a7490a32a30cd8b65c1a61cb32c444f3a312dab1385405717f9866d113d67518b3d487f15de177279ba1a80f8958b28cad021846#npm:5.0.0"],\
["@newrelic/koa", "virtual:4c49b89cbc97666c528d8405a7490a32a30cd8b65c1a61cb32c444f3a312dab1385405717f9866d113d67518b3d487f15de177279ba1a80f8958b28cad021846#npm:7.0.0"],\
["@newrelic/native-metrics", "npm:9.0.0"],\
["@newrelic/superagent", "virtual:f10080c2deb75096716a913b06010dcd94891c77539a757ab32210a1efc3ff91527b36d6c7c46e890db826160e0724553ca23acd0a8a734b5554c9600c71eb52#npm:6.0.0"],\
["@newrelic/superagent", "virtual:4c49b89cbc97666c528d8405a7490a32a30cd8b65c1a61cb32c444f3a312dab1385405717f9866d113d67518b3d487f15de177279ba1a80f8958b28cad021846#npm:6.0.0"],\
["@tyriar/fibonacci-heap", "npm:2.0.9"],\
["concat-stream", "npm:2.0.0"],\
["https-proxy-agent", "npm:5.0.1"],\
@ -11828,10 +11841,10 @@ const RAW_RUNTIME_STATE =
}]\
]],\
["protobufjs", [\
["npm:6.11.3", {\
"packageLocation": "./.yarn/unplugged/protobufjs-npm-6.11.3-566fb31188/node_modules/protobufjs/",\
["npm:7.1.2", {\
"packageLocation": "./.yarn/unplugged/protobufjs-npm-7.1.2-2e50888192/node_modules/protobufjs/",\
"packageDependencies": [\
["protobufjs", "npm:6.11.3"],\
["protobufjs", "npm:7.1.2"],\
["@protobufjs/aspromise", "npm:1.1.2"],\
["@protobufjs/base64", "npm:1.1.2"],\
["@protobufjs/codegen", "npm:2.0.4"],\
@ -11842,9 +11855,8 @@ const RAW_RUNTIME_STATE =
["@protobufjs/path", "npm:1.1.2"],\
["@protobufjs/pool", "npm:1.1.0"],\
["@protobufjs/utf8", "npm:1.1.0"],\
["@types/long", "npm:4.0.2"],\
["@types/node", "npm:18.0.3"],\
["long", "npm:4.0.0"]\
["long", "npm:5.2.1"]\
],\
"linkType": "HARD"\
}]\

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View file

@ -0,0 +1,18 @@
Copyright 2022 Contrast Security, Inc
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View file

@ -0,0 +1,43 @@
# @contrast/fn-inspect
[![Test](https://github.com/Contrast-Security-Inc/node-fn-inspect/actions/workflows/test.yml/badge.svg)](https://github.com/Contrast-Security-Inc/node-fn-inspect/actions/workflows/test.yml)
This module exposes some useful information from the underlying v8 engine,
including:
- file and line number given a function reference
- code events (i.e. `'LAZY_COMPILE'`)
## Usage
Getting details about a function:
```js
const { funcInfo } = require('@contrast/fn-inspect');
function testFn() {}
const results = funcInfo(testFn);
// => { lineNumber: 2, column: 15, file: 'example.js', method: 'testFn', type: 'Function' }
```
Registering a listener for code events:
```js
const { setCodeEventListener } = require('@contrast/fn-inspect');
setCodeEventListener((event) => {
console.log(event);
});
```
## Building locally
`npm run build` will build the project for your current OS and architecture.
`npm run download` will pull the most recent build artifacts from GitHub.
## Publishing
Simply run `npm version` and `git push && git push --tags`. CI will take care of
releasing on taggedcommits.

View file

@ -0,0 +1,36 @@
{
"variables" : {
"openssl_fips": "",
},
"targets": [
{
"target_name": "fninspect",
"sources": [
"src/addon.cc",
"src/code-events.cc",
"src/event-queue.cc",
"src/func-info.cc"
],
"include_dirs": [
"<!(node -e \"require('nan')\")"
],
"conditions": [
[
"OS == 'mac'",
{
"xcode_settings": {
"OTHER_CFLAGS": [
"-arch x86_64",
"-arch arm64"
],
"OTHER_LDFLAGS": [
"-arch x86_64",
"-arch arm64"
]
}
}
]
]
}
]
}

View file

@ -0,0 +1,45 @@
/* eslint-disable @typescript-eslint/ban-types */
declare interface FunctionInfo {
file: string;
column: number;
lineNumber: number;
method: string;
type: 'AsyncFunction' | 'Function';
}
declare interface CodeEvent {
func: string;
lineNumber: number;
script: string;
type:
| 'Builtin'
| 'Callback'
| 'Eval'
| 'Function'
| 'InterpretedFunction'
| 'Handler'
| 'BytecodeHandler'
| 'LazyCompile'
| 'RegExp'
| 'Script'
| 'Stub'
| 'Relocation'
}
declare const fnInspect: {
/** Retrieves name, type, column, lineNumber and file from a function reference */
funcInfo(fn: Function): FunctionInfo | null;
/**
* Sets the function for processing v8 code events.
* Will start listening for code events if not already listening.
* starts a timer which polls for an available code event once every `interval` ms.
*/
setCodeEventListener(cb: (event: CodeEvent) => void, interval?: number): void;
/** Stop listening for v8 code events */
stopListening(): void;
};
export = fnInspect;

View file

@ -0,0 +1,58 @@
'use strict';
const binding = require('node-gyp-build')(__dirname);
let codeEventsInited = false;
let codeEventListener = null;
let timer = null;
module.exports = {
/**
* Retrieves name, type, column, lineNumber and file from a function reference
*
* @param {Function} fn function reference to obtain info
* @return {FunctionInfo | null}
*/
funcInfo(fn) {
const info = binding.funcInfo(fn);
if (info === null) return null;
info.type = fn.constructor.name;
return info;
},
/**
* Sets the function for processing v8 code events.
* Will start listening for code events if not already listening.
* starts a timer which polls for an available code event once every `interval` value.
*
* @param {Function} cb callback function to call
* @param {number} [interval=1] how often to get code events in ms
*/
setCodeEventListener(cb, interval = 1) {
if (codeEventsInited) {
codeEventListener = cb;
return;
}
binding.initHandler();
codeEventsInited = true;
codeEventListener = cb;
timer = setInterval(() => {
const codeEvent = binding.getNextCodeEvent();
if (codeEvent) codeEventListener(codeEvent);
}, interval);
},
/**
* Stop listening for v8 code events
*/
stopListening() {
if (!codeEventsInited) return;
clearInterval(timer);
binding.deinitHandler();
codeEventListener = null;
codeEventsInited = false;
},
};

View file

@ -0,0 +1,63 @@
{
"name": "@contrast/fn-inspect",
"version": "3.3.0",
"description": "Retrieve function name and line number from a function reference",
"keywords": [
"instrumentation"
],
"author": "Contrast Security",
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/Contrast-Security-Inc/node-fn-inspect.git"
},
"bugs": {
"url": "https://github.com/Contrast-Security-Inc/node-fn-inspect/issues"
},
"homepage": "https://github.com/Contrast-Security-Inc/node-fn-inspect#readme",
"files": [
"prebuilds/",
"src/",
"binding.gyp",
"index.d.ts",
"index.js"
],
"main": "index.js",
"types": "index.d.ts",
"scripts": {
"install": "node-gyp-build",
"prepare": "husky install",
"build": "prebuildify -t 12.13.0 -t 14.15.0 -t 16.9.1 -t 18.7.0 --strip",
"build:linux": "prebuildify-cross -i centos7-devtoolset7 -i alpine -i linux-arm64 -t 12.13.0 -t 14.15.0 -t 16.9.1 -t 18.7.0 --strip",
"build:darwin": "npm run build -- --arch x64+arm64",
"build:win32": "npm run build",
"clean": "rimraf build/ coverage/ prebuilds/",
"download": "node scripts/download-artifacts.js",
"test": "c8 --reporter lcov --reporter text mocha .",
"test:valgrind": "valgrind --xml=yes --xml-file=./valgrind.xml --trace-children=yes --leak-check=full --show-leak-kinds=all mocha . && node scripts/parse-valgrind.js"
},
"engines": {
"node": ">=12.13.0"
},
"dependencies": {
"nan": "^2.16.0",
"node-gyp-build": "^4.4.0"
},
"devDependencies": {
"@contrast/eslint-config": "^3.1.1",
"@ls-lint/ls-lint": "^1.11.2",
"@octokit/rest": "^18.12.0",
"c8": "^7.11.3",
"chai": "^4.3.6",
"husky": "^8.0.1",
"inquirer": "^8.2.4",
"lint-staged": "^13.0.1",
"mocha": "^10.0.0",
"node-gyp": "^9.0.0",
"prebuildify": "^5.0.0",
"prebuildify-cross": "^5.0.0",
"rimraf": "^3.0.2",
"unzipper": "^0.10.11",
"xml-js": "^1.6.11"
}
}

View file

@ -0,0 +1,14 @@
#include <nan.h>
#include "code-events.h"
#include "func-info.h"
NAN_MODULE_INIT(Init) {
NAN_EXPORT(target, initHandler);
NAN_EXPORT(target, deinitHandler);
NAN_EXPORT(target, getNextCodeEvent);
NAN_EXPORT(target, funcInfo);
}
NODE_MODULE(addon, Init)

View file

@ -0,0 +1,75 @@
#include "code-events.h"
#include "event-queue.h"
using namespace v8;
class FnInspectCodeEventHandler : public CodeEventHandler {
public:
FnInspectCodeEventHandler(Isolate *isolate) : CodeEventHandler(isolate) {
this->isolate = isolate;
}
void Handle(CodeEvent *event) {
/*
* If Handle() is invoked from a worker thread (i.e. during
* garbage collection) we don't have access to the isolate
* so just bail
*/
if (Isolate::GetCurrent() != isolate) {
return;
}
events.enqueue(event);
}
EventNode *dequeue() {
return this->events.dequeue();
}
unsigned int eventCount() {
return this->events.length;
}
private:
Isolate *isolate;
EventQueue events;
};
FnInspectCodeEventHandler *handler;
NAN_METHOD(initHandler) {
handler = new FnInspectCodeEventHandler(info.GetIsolate());
handler->Enable();
}
NAN_METHOD(deinitHandler) {
handler->Disable();
delete handler;
handler = NULL;
}
NAN_METHOD(getNextCodeEvent) {
EventNode *node = handler->dequeue();
if (!node)
return;
Local<Object> obj = Nan::New<Object>();
Nan::Set(obj,
Nan::New("script").ToLocalChecked(),
Nan::New(node->script).ToLocalChecked());
Nan::Set(obj,
Nan::New("func").ToLocalChecked(),
Nan::New(node->func).ToLocalChecked());
Nan::Set(obj,
Nan::New("type").ToLocalChecked(),
Nan::New(node->type).ToLocalChecked());
Nan::Set(obj,
Nan::New("lineNumber").ToLocalChecked(),
Nan::New(node->lineNumber));
info.GetReturnValue().Set(obj);
delete node;
}

View file

@ -0,0 +1,11 @@
#pragma once
#include <nan.h>
#include <v8-profiler.h>
#include <v8.h>
#include "event-queue.h"
NAN_METHOD(initHandler);
NAN_METHOD(deinitHandler);
NAN_METHOD(getNextCodeEvent);

View file

@ -0,0 +1,61 @@
#include <v8-profiler.h>
#include <v8.h>
#include "event-queue.h"
using namespace v8;
EventQueue::EventQueue() {
this->head = NULL;
this->tail = NULL;
this->length = 0;
}
EventQueue::~EventQueue() {
EventNode *tmp;
while (this->head) {
tmp = this->head;
;
this->head = this->head->next;
delete tmp;
}
}
void EventQueue::enqueue(CodeEvent *event) {
if (Nan::Utf8String(event->GetScriptName()).length() == 0)
return;
EventNode *node = new EventNode();
node->type = strdup(CodeEvent::GetCodeEventTypeName(event->GetCodeType()));
node->script = strdup(*Nan::Utf8String(event->GetScriptName()));
node->func = strdup(*Nan::Utf8String(event->GetFunctionName()));
node->lineNumber = event->GetScriptLine();
if (this->tail) {
this->tail->next = node;
this->tail = node;
} else {
this->head = node;
this->tail = node;
}
this->length += 1;
}
EventNode *EventQueue::dequeue() {
EventNode *node = this->head;
if (!node)
return NULL;
this->head = this->head->next;
if (this->head == NULL) {
this->tail = NULL;
}
this->length -= 1;
return node;
}

View file

@ -0,0 +1,46 @@
#pragma once
#include <nan.h>
#include <v8-profiler.h>
#include <v8.h>
using namespace v8;
class EventNode {
public:
char *type;
char *script;
char *func;
int lineNumber;
EventNode *next;
~EventNode() {
free(this->type);
free(this->script);
free(this->func);
}
};
/**
* Implements a simple queue of code events that can be
* consumed.
*
* Thread-Safety: There's no locking on these methods so
* they aren't thread safe. However this should be OK
* as the expectation is these methods are only ever called
* from the main JS thread and they are blocking, there will
* only ever be a single thread calling it as a time. We
* may want to revisit this if we ever want to support
* handling events from worker_threads.
*/
class EventQueue {
public:
EventQueue();
~EventQueue();
void enqueue(CodeEvent *event);
EventNode *dequeue();
unsigned int length;
private:
EventNode *head;
EventNode *tail;
};

View file

@ -0,0 +1,28 @@
#include "func-info.h"
using namespace v8;
NAN_METHOD(funcInfo) {
if (info.Length() < 1 || info[0].IsEmpty() || !info[0]->IsFunction()) {
info.GetReturnValue().Set(Nan::Null());
return;
}
Local<Function> fn = info[0].As<Function>();
Local<Object> obj = Nan::New<Object>();
Local<Value> resourceName = fn->GetScriptOrigin().ResourceName();
if (!resourceName.IsEmpty()) {
Nan::Set(obj, Nan::New("file").ToLocalChecked(), resourceName);
Nan::Set(obj,
Nan::New("lineNumber").ToLocalChecked(),
Nan::New(fn->GetScriptLineNumber()));
Nan::Set(obj, Nan::New("method").ToLocalChecked(), fn->GetName());
Nan::Set(obj,
Nan::New("column").ToLocalChecked(),
Nan::New(fn->GetScriptColumnNumber()));
}
info.GetReturnValue().Set(obj);
}

View file

@ -0,0 +1,6 @@
#pragma once
#include <nan.h>
#include <v8.h>
NAN_METHOD(funcInfo);

File diff suppressed because it is too large Load diff

View file

@ -1,6 +0,0 @@
#!/usr/bin/env node
var path = require("path"),
cli = require(path.join(__dirname, "..", "cli", "pbjs.js"));
var ret = cli.main(process.argv.slice(2));
if (typeof ret === 'number')
process.exit(ret);

View file

@ -1,6 +0,0 @@
#!/usr/bin/env node
var path = require("path"),
cli = require(path.join(__dirname, "..", "cli", "pbts.js"));
var ret = cli.main(process.argv.slice(2));
if (typeof ret === 'number')
process.exit(ret);

View file

@ -1,33 +0,0 @@
Copyright (c) 2016, Daniel Wirtz All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of its author, nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---
Code generated by the command line utilities is owned by the owner
of the input file used when generating it. This code is not
standalone and requires a support library to be linked with it. This
support library is itself covered by the above license.

View file

@ -1,174 +0,0 @@
protobufjs-cli
==============
[![npm](https://img.shields.io/npm/v/protobufjscli.svg)](https://www.npmjs.com/package/protobufjs-cli)
Command line interface (CLI) for [protobuf.js](https://github.com/dcodeIO/protobuf.js). Translates between file formats and generates static code as well as TypeScript definitions.
* [CLI Documentation](https://github.com/dcodeIO/protobuf.js#command-line)
**Note** that moving the CLI to its own package is a work in progress. At the moment, it's still part of the main package.
* [pbjs for JavaScript](#pbjs-for-javascript)
* [pbts for TypeScript](#pbts-for-typescript)
* [Reflection vs. static code](#reflection-vs-static-code)
* [Command line API](#command-line-api)<br />
### pbjs for JavaScript
```
Translates between file formats and generates static code.
-t, --target Specifies the target format. Also accepts a path to require a custom target.
json JSON representation
json-module JSON representation as a module
proto2 Protocol Buffers, Version 2
proto3 Protocol Buffers, Version 3
static Static code without reflection (non-functional on its own)
static-module Static code without reflection as a module
-p, --path Adds a directory to the include path.
-o, --out Saves to a file instead of writing to stdout.
--sparse Exports only those types referenced from a main file (experimental).
Module targets only:
-w, --wrap Specifies the wrapper to use. Also accepts a path to require a custom wrapper.
default Default wrapper supporting both CommonJS and AMD
commonjs CommonJS wrapper
amd AMD wrapper
es6 ES6 wrapper (implies --es6)
closure A closure adding to protobuf.roots where protobuf is a global
-r, --root Specifies an alternative protobuf.roots name.
-l, --lint Linter configuration. Defaults to protobuf.js-compatible rules:
eslint-disable block-scoped-var, no-redeclare, no-control-regex, no-prototype-builtins
--es6 Enables ES6 syntax (const/let instead of var)
Proto sources only:
--keep-case Keeps field casing instead of converting to camel case.
Static targets only:
--no-create Does not generate create functions used for reflection compatibility.
--no-encode Does not generate encode functions.
--no-decode Does not generate decode functions.
--no-verify Does not generate verify functions.
--no-convert Does not generate convert functions like from/toObject
--no-delimited Does not generate delimited encode/decode functions.
--no-beautify Does not beautify generated code.
--no-comments Does not output any JSDoc comments.
--no-service Does not output service classes.
--force-long Enforces the use of 'Long' for s-/u-/int64 and s-/fixed64 fields.
--force-number Enforces the use of 'number' for s-/u-/int64 and s-/fixed64 fields.
--force-message Enforces the use of message instances instead of plain objects.
usage: pbjs [options] file1.proto file2.json ... (or pipe) other | pbjs [options] -
```
For production environments it is recommended to bundle all your .proto files to a single .json file, which minimizes the number of network requests and avoids any parser overhead (hint: works with just the **light** library):
```
$> pbjs -t json file1.proto file2.proto > bundle.json
```
Now, either include this file in your final bundle:
```js
var root = protobuf.Root.fromJSON(require("./bundle.json"));
```
or load it the usual way:
```js
protobuf.load("bundle.json", function(err, root) {
...
});
```
Generated static code, on the other hand, works with just the **minimal** library. For example
```
$> pbjs -t static-module -w commonjs -o compiled.js file1.proto file2.proto
```
will generate static code for definitions within `file1.proto` and `file2.proto` to a CommonJS module `compiled.js`.
**ProTip!** Documenting your .proto files with `/** ... */`-blocks or (trailing) `/// ...` lines translates to generated static code.
### pbts for TypeScript
```
Generates TypeScript definitions from annotated JavaScript files.
-o, --out Saves to a file instead of writing to stdout.
-g, --global Name of the global object in browser environments, if any.
--no-comments Does not output any JSDoc comments.
Internal flags:
-n, --name Wraps everything in a module of the specified name.
-m, --main Whether building the main library without any imports.
usage: pbts [options] file1.js file2.js ... (or) other | pbts [options] -
```
Picking up on the example above, the following not only generates static code to a CommonJS module `compiled.js` but also its respective TypeScript definitions to `compiled.d.ts`:
```
$> pbjs -t static-module -w commonjs -o compiled.js file1.proto file2.proto
$> pbts -o compiled.d.ts compiled.js
```
Additionally, TypeScript definitions of static modules are compatible with their reflection-based counterparts (i.e. as exported by JSON modules), as long as the following conditions are met:
1. Instead of using `new SomeMessage(...)`, always use `SomeMessage.create(...)` because reflection objects do not provide a constructor.
2. Types, services and enums must start with an uppercase letter to become available as properties of the reflected types as well (i.e. to be able to use `MyMessage.MyEnum` instead of `root.lookup("MyMessage.MyEnum")`).
For example, the following generates a JSON module `bundle.js` and a `bundle.d.ts`, but no static code:
```
$> pbjs -t json-module -w commonjs -o bundle.js file1.proto file2.proto
$> pbjs -t static-module file1.proto file2.proto | pbts -o bundle.d.ts -
```
### Reflection vs. static code
While using .proto files directly requires the full library respectively pure reflection/JSON the light library, pretty much all code but the relatively short descriptors is shared.
Static code, on the other hand, requires just the minimal library, but generates additional source code without any reflection features. This also implies that there is a break-even point where statically generated code becomes larger than descriptor-based code once the amount of code generated exceeds the size of the full respectively light library.
There is no significant difference performance-wise as the code generated statically is pretty much the same as generated at runtime and both are largely interchangeable as seen in the previous section.
| Source | Library | Advantages | Tradeoffs
|--------|---------|------------|-----------
| .proto | full | Easily editable<br />Interoperability with other libraries<br />No compile step | Some parsing and possibly network overhead
| JSON | light | Easily editable<br />No parsing overhead<br />Single bundle (no network overhead) | protobuf.js specific<br />Has a compile step
| static | minimal | Works where `eval` access is restricted<br />Fully documented<br />Small footprint for small protos | Can be hard to edit<br />No reflection<br />Has a compile step
### Command line API
Both utilities can be used programmatically by providing command line arguments and a callback to their respective `main` functions:
```js
var pbjs = require("protobufjs-cli/pbjs"); // or require("protobufjs-cli").pbjs / .pbts
pbjs.main([ "--target", "json-module", "path/to/myproto.proto" ], function(err, output) {
if (err)
throw err;
// do something with output
});
```
**License:** [BSD 3-Clause License](https://opensource.org/licenses/BSD-3-Clause)

View file

@ -1,6 +0,0 @@
#!/usr/bin/env node
var path = require("path"),
cli = require(path.join(__dirname, "..", "pbjs.js"));
var ret = cli.main(process.argv.slice(2));
if (typeof ret === 'number')
process.exit(ret);

View file

@ -1,6 +0,0 @@
#!/usr/bin/env node
var path = require("path"),
cli = require(path.join(__dirname, "..", "pbts.js"));
var ret = cli.main(process.argv.slice(2));
if (typeof ret === 'number')
process.exit(ret);

View file

@ -1,3 +0,0 @@
import * as pbjs from "./pbjs.js";
import * as pbts from "./pbts.js";
export { pbjs, pbts };

View file

@ -1,3 +0,0 @@
"use strict";
exports.pbjs = require("./pbjs");
exports.pbts = require("./pbts");

View file

@ -1,18 +0,0 @@
{
"tags": {
"allowUnknownTags": false
},
"plugins": [
"./tsd-jsdoc/plugin"
],
"opts": {
"encoding" : "utf8",
"recurse" : true,
"lenient" : true,
"template" : "./tsd-jsdoc",
"private" : false,
"comments" : true,
"destination" : false
}
}

View file

@ -1,21 +0,0 @@
The MIT License
Copyright (c) 2016 Chad Engler
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View file

@ -1,23 +0,0 @@
protobuf.js fork of tsd-jsdoc
=============================
This is a modified version of [tsd-jsdoc](https://github.com/englercj/tsd-jsdoc) v1.0.1 for use with protobuf.js, parked here so we can process issues and pull requests. The ultimate goal is to switch back to the a recent version of tsd-jsdoc once it meets our needs.
Options
-------
* **module: `string`**<br />
Wraps everything in a module of the specified name.
* **private: `boolean`**<br />
Includes private members when set to `true`.
* **comments: `boolean`**<br />
Skips comments when explicitly set to `false`.
* **destination: `string|boolean`**<br />
Saves to the specified destination file or to console when set to `false`.
Setting options on the command line
-----------------------------------
Providing `-q, --query <queryString>` on the command line will set respectively override existing options. Example: `-q module=protobufjs`

View file

@ -1,21 +0,0 @@
"use strict";
exports.defineTags = function(dictionary) {
dictionary.defineTag("template", {
mustHaveValue: true,
canHaveType: false,
canHaveName: false,
onTagged: function(doclet, tag) {
(doclet.templates || (doclet.templates = [])).push(tag.text);
}
});
dictionary.defineTag("tstype", {
mustHaveValue: true,
canHaveType: false,
canHaveName: false,
onTagged: function(doclet, tag) {
doclet.tsType = tag.text;
}
});
};

View file

@ -1,705 +0,0 @@
"use strict";
var fs = require("fs");
// output stream
var out = null;
// documentation data
var data = null;
// already handled objects, by name
var seen = {};
// indentation level
var indent = 0;
// whether indent has been written for the current line yet
var indentWritten = false;
// provided options
var options = {};
// queued interfaces
var queuedInterfaces = [];
// whether writing the first line
var firstLine = true;
// JSDoc hook
exports.publish = function publish(taffy, opts) {
options = opts || {};
// query overrides options
if (options.query)
Object.keys(options.query).forEach(function(key) {
if (key !== "query")
switch (options[key] = options.query[key]) {
case "true":
options[key] = true;
break;
case "false":
options[key] = false;
break;
case "null":
options[key] = null;
break;
}
});
// remove undocumented
taffy({ undocumented: true }).remove();
taffy({ ignore: true }).remove();
taffy({ inherited: true }).remove();
// remove private
if (!options.private)
taffy({ access: "private" }).remove();
// setup output
out = options.destination
? fs.createWriteStream(options.destination)
: process.stdout;
try {
// setup environment
data = taffy().get();
indent = 0;
indentWritten = false;
firstLine = true;
// wrap everything in a module if configured
if (options.module) {
writeln("export = ", options.module, ";");
writeln();
writeln("declare namespace ", options.module, " {");
writeln();
++indent;
}
// handle all
getChildrenOf(undefined).forEach(function(child) {
handleElement(child, null);
});
// process queued
while (queuedInterfaces.length) {
var element = queuedInterfaces.shift();
begin(element);
writeInterface(element);
writeln(";");
}
// end wrap
if (options.module) {
--indent;
writeln("}");
}
// close file output
if (out !== process.stdout)
out.end();
} finally {
// gc environment objects
out = data = null;
seen = options = {};
queuedInterfaces = [];
}
};
//
// Utility
//
// writes one or multiple strings
function write() {
var s = Array.prototype.slice.call(arguments).join("");
if (!indentWritten) {
for (var i = 0; i < indent; ++i)
s = " " + s;
indentWritten = true;
}
out.write(s);
firstLine = false;
}
// writes zero or multiple strings, followed by a new line
function writeln() {
var s = Array.prototype.slice.call(arguments).join("");
if (s.length)
write(s, "\n");
else if (!firstLine)
out.write("\n");
indentWritten = false;
}
var keepTags = [
"param",
"returns",
"throws",
"see"
];
// parses a comment into text and tags
function parseComment(comment) {
var lines = comment.replace(/^ *\/\*\* *|^ *\*\/| *\*\/ *$|^ *\* */mg, "").trim().split(/\r?\n|\r/g); // property.description has just "\r" ?!
var desc;
var text = [];
var tags = null;
for (var i = 0; i < lines.length; ++i) {
var match = /^@(\w+)\b/.exec(lines[i]);
if (match) {
if (!tags) {
tags = [];
desc = text;
}
text = [];
tags.push({ name: match[1], text: text });
lines[i] = lines[i].substring(match[1].length + 1).trim();
}
if (lines[i].length || text.length)
text.push(lines[i]);
}
return {
text: desc || text,
tags: tags || []
};
}
// writes a comment
function writeComment(comment, otherwiseNewline) {
if (!comment || options.comments === false) {
if (otherwiseNewline)
writeln();
return;
}
if (typeof comment !== "object")
comment = parseComment(comment);
comment.tags = comment.tags.filter(function(tag) {
return keepTags.indexOf(tag.name) > -1 && (tag.name !== "returns" || tag.text[0] !== "{undefined}");
});
writeln();
if (!comment.tags.length && comment.text.length < 2) {
writeln("/** " + comment.text[0] + " */");
return;
}
writeln("/**");
comment.text.forEach(function(line) {
if (line.length)
writeln(" * ", line);
else
writeln(" *");
});
comment.tags.forEach(function(tag) {
var started = false;
if (tag.text.length) {
tag.text.forEach(function(line, i) {
if (i > 0)
write(" * ");
else if (tag.name !== "throws")
line = line.replace(/^\{[^\s]*} ?/, "");
if (!line.length)
return;
if (!started) {
write(" * @", tag.name, " ");
started = true;
}
writeln(line);
});
}
});
writeln(" */");
}
// recursively replaces all occurencies of re's match
function replaceRecursive(name, re, fn) {
var found;
function replacer() {
found = true;
return fn.apply(null, arguments);
}
do {
found = false;
name = name.replace(re, replacer);
} while (found);
return name;
}
// tests if an element is considered to be a class or class-like
function isClassLike(element) {
return isClass(element) || isInterface(element);
}
// tests if an element is considered to be a class
function isClass(element) {
return element && element.kind === "class";
}
// tests if an element is considered to be an interface
function isInterface(element) {
return element && (element.kind === "interface" || element.kind === "mixin");
}
// tests if an element is considered to be a namespace
function isNamespace(element) {
return element && (element.kind === "namespace" || element.kind === "module");
}
// gets all children of the specified parent
function getChildrenOf(parent) {
var memberof = parent ? parent.longname : undefined;
return data.filter(function(element) {
return element.memberof === memberof;
});
}
// gets the literal type of an element
function getTypeOf(element) {
if (element.tsType)
return element.tsType.replace(/\r?\n|\r/g, "\n");
var name = "any";
var type = element.type;
if (type && type.names && type.names.length) {
if (type.names.length === 1)
name = element.type.names[0].trim();
else
name = "(" + element.type.names.join("|") + ")";
} else
return name;
// Replace catchalls with any
name = name.replace(/\*|\bmixed\b/g, "any");
// Ensure upper case Object for map expressions below
name = name.replace(/\bobject\b/g, "Object");
// Correct Something.<Something> to Something<Something>
name = replaceRecursive(name, /\b(?!Object|Array)([\w$]+)\.<([^>]*)>/gi, function($0, $1, $2) {
return $1 + "<" + $2 + ">";
});
// Replace Array.<string> with string[]
name = replaceRecursive(name, /\bArray\.?<([^>]*)>/gi, function($0, $1) {
return $1 + "[]";
});
// Replace Object.<string,number> with { [k: string]: number }
name = replaceRecursive(name, /\bObject\.?<([^,]*), *([^>]*)>/gi, function($0, $1, $2) {
return "{ [k: " + $1 + "]: " + $2 + " }";
});
// Replace functions (there are no signatures) with Function
name = name.replace(/\bfunction(?:\(\))?\b/g, "Function");
// Convert plain Object back to just object
name = name.replace(/\b(Object\b(?!\.))/g, function($0, $1) {
return $1.toLowerCase();
});
return name;
}
// begins writing the definition of the specified element
function begin(element, is_interface) {
if (!seen[element.longname]) {
if (isClass(element)) {
var comment = parseComment(element.comment);
var classdesc = comment.tags.find(function(tag) { return tag.name === "classdesc"; });
if (classdesc) {
comment.text = classdesc.text;
comment.tags = [];
}
writeComment(comment, true);
} else
writeComment(element.comment, is_interface || isClassLike(element) || isNamespace(element) || element.isEnum || element.scope === "global");
seen[element.longname] = element;
} else
writeln();
// ????: something changed in JSDoc 3.6.0? so that @exports + @enum does
// no longer yield a 'global' scope, but is some sort of unscoped module
// element now. The additional condition added below works around this.
if ((element.scope === "global" || element.isEnum && element.scope === undefined) && !options.module)
write("export ");
}
// writes the function signature describing element
function writeFunctionSignature(element, isConstructor, isTypeDef) {
write("(");
var params = {};
// this type
if (element.this)
params["this"] = {
type: element.this.replace(/^{|}$/g, ""),
optional: false
};
// parameter types
if (element.params)
element.params.forEach(function(param) {
var path = param.name.split(/\./g);
if (path.length === 1)
params[param.name] = {
type: getTypeOf(param),
variable: param.variable === true,
optional: param.optional === true,
defaultValue: param.defaultvalue // Not used yet (TODO)
};
else // Property syntax (TODO)
params[path[0]].type = "{ [k: string]: any }";
});
var paramNames = Object.keys(params);
paramNames.forEach(function(name, i) {
var param = params[name];
var type = param.type;
if (param.variable) {
name = "..." + name;
type = param.type.charAt(0) === "(" ? "any[]" : param.type + "[]";
}
write(name, !param.variable && param.optional ? "?: " : ": ", type);
if (i < paramNames.length - 1)
write(", ");
});
write(")");
// return type
if (!isConstructor) {
write(isTypeDef ? " => " : ": ");
var typeName;
if (element.returns && element.returns.length && (typeName = getTypeOf(element.returns[0])) !== "undefined")
write(typeName);
else
write("void");
}
}
// writes (a typedef as) an interface
function writeInterface(element) {
write("interface ", element.name);
writeInterfaceBody(element);
writeln();
}
function writeInterfaceBody(element) {
writeln("{");
++indent;
if (element.tsType)
writeln(element.tsType.replace(/\r?\n|\r/g, "\n"));
else if (element.properties && element.properties.length)
element.properties.forEach(writeProperty);
--indent;
write("}");
}
function writeProperty(property, declare) {
writeComment(property.description);
if (declare)
write("let ");
write(property.name);
if (property.optional)
write("?");
writeln(": ", getTypeOf(property), ";");
}
//
// Handlers
//
// handles a single element of any understood type
function handleElement(element, parent) {
if (element.scope === "inner")
return false;
if (element.optional !== true && element.type && element.type.names && element.type.names.length) {
for (var i = 0; i < element.type.names.length; i++) {
if (element.type.names[i].toLowerCase() === "undefined") {
// This element is actually optional. Set optional to true and
// remove the 'undefined' type
element.optional = true;
element.type.names.splice(i, 1);
i--;
}
}
}
if (seen[element.longname])
return true;
if (isClassLike(element))
handleClass(element, parent);
else switch (element.kind) {
case "module":
if (element.isEnum) {
handleEnum(element, parent);
break;
}
// eslint-disable-line no-fallthrough
case "namespace":
handleNamespace(element, parent);
break;
case "constant":
case "member":
handleMember(element, parent);
break;
case "function":
handleFunction(element, parent);
break;
case "typedef":
handleTypeDef(element, parent);
break;
case "package":
break;
}
seen[element.longname] = element;
return true;
}
// handles (just) a namespace
function handleNamespace(element/*, parent*/) {
var children = getChildrenOf(element);
if (!children.length)
return;
var first = true;
if (element.properties)
element.properties.forEach(function(property) {
if (!/^[$\w]+$/.test(property.name)) // incompatible in namespace
return;
if (first) {
begin(element);
writeln("namespace ", element.name, " {");
++indent;
first = false;
}
writeProperty(property, true);
});
children.forEach(function(child) {
if (child.scope === "inner" || seen[child.longname])
return;
if (first) {
begin(element);
writeln("namespace ", element.name, " {");
++indent;
first = false;
}
handleElement(child, element);
});
if (!first) {
--indent;
writeln("}");
}
}
// a filter function to remove any module references
function notAModuleReference(ref) {
return ref.indexOf("module:") === -1;
}
// handles a class or class-like
function handleClass(element, parent) {
var is_interface = isInterface(element);
begin(element, is_interface);
if (is_interface)
write("interface ");
else {
if (element.virtual)
write("abstract ");
write("class ");
}
write(element.name);
if (element.templates && element.templates.length)
write("<", element.templates.join(", "), ">");
write(" ");
// extended classes
if (element.augments) {
var augments = element.augments.filter(notAModuleReference);
if (augments.length)
write("extends ", augments[0], " ");
}
// implemented interfaces
var impls = [];
if (element.implements)
Array.prototype.push.apply(impls, element.implements);
if (element.mixes)
Array.prototype.push.apply(impls, element.mixes);
impls = impls.filter(notAModuleReference);
if (impls.length)
write("implements ", impls.join(", "), " ");
writeln("{");
++indent;
if (element.tsType)
writeln(element.tsType.replace(/\r?\n|\r/g, "\n"));
// constructor
if (!is_interface && !element.virtual)
handleFunction(element, parent, true);
// properties
if (is_interface && element.properties)
element.properties.forEach(function(property) {
writeProperty(property);
});
// class-compatible members
var incompatible = [];
getChildrenOf(element).forEach(function(child) {
if (isClassLike(child) || child.kind === "module" || child.kind === "typedef" || child.isEnum) {
incompatible.push(child);
return;
}
handleElement(child, element);
});
--indent;
writeln("}");
// class-incompatible members
if (incompatible.length) {
writeln();
if (element.scope === "global" && !options.module)
write("export ");
writeln("namespace ", element.name, " {");
++indent;
incompatible.forEach(function(child) {
handleElement(child, element);
});
--indent;
writeln("}");
}
}
// handles an enum
function handleEnum(element) {
begin(element);
var stringEnum = false;
element.properties.forEach(function(property) {
if (isNaN(property.defaultvalue)) {
stringEnum = true;
}
});
if (stringEnum) {
writeln("type ", element.name, " =");
++indent;
element.properties.forEach(function(property, i) {
write(i === 0 ? "" : "| ", JSON.stringify(property.defaultvalue));
});
--indent;
writeln(";");
} else {
writeln("enum ", element.name, " {");
++indent;
element.properties.forEach(function(property, i) {
write(property.name);
if (property.defaultvalue !== undefined)
write(" = ", JSON.stringify(property.defaultvalue));
if (i < element.properties.length - 1)
writeln(",");
else
writeln();
});
--indent;
writeln("}");
}
}
// handles a namespace or class member
function handleMember(element, parent) {
if (element.isEnum) {
handleEnum(element);
return;
}
begin(element);
var inClass = isClassLike(parent);
if (inClass) {
write(element.access || "public", " ");
if (element.scope === "static")
write("static ");
if (element.readonly)
write("readonly ");
} else
write(element.kind === "constant" ? "const " : "let ");
write(element.name);
if (element.optional)
write("?");
write(": ");
if (element.type && element.type.names && /^Object\b/i.test(element.type.names[0]) && element.properties) {
writeln("{");
++indent;
element.properties.forEach(function(property, i) {
writeln(JSON.stringify(property.name), ": ", getTypeOf(property), i < element.properties.length - 1 ? "," : "");
});
--indent;
writeln("};");
} else
writeln(getTypeOf(element), ";");
}
// handles a function or method
function handleFunction(element, parent, isConstructor) {
var insideClass = true;
if (isConstructor) {
writeComment(element.comment);
write("constructor");
} else {
begin(element);
insideClass = isClassLike(parent);
if (insideClass) {
write(element.access || "public", " ");
if (element.scope === "static")
write("static ");
} else
write("function ");
write(element.name);
if (element.templates && element.templates.length)
write("<", element.templates.join(", "), ">");
}
writeFunctionSignature(element, isConstructor, false);
writeln(";");
if (!insideClass)
handleNamespace(element);
}
// handles a type definition (not a real type)
function handleTypeDef(element, parent) {
if (isInterface(element)) {
if (isClassLike(parent))
queuedInterfaces.push(element);
else {
begin(element);
writeInterface(element);
}
} else {
writeComment(element.comment, true);
write("type ", element.name);
if (element.templates && element.templates.length)
write("<", element.templates.join(", "), ">");
write(" = ");
if (element.tsType)
write(element.tsType.replace(/\r?\n|\r/g, "\n"));
else {
var type = getTypeOf(element);
if (element.type && element.type.names.length === 1 && element.type.names[0] === "function")
writeFunctionSignature(element, false, true);
else if (type === "object") {
if (element.properties && element.properties.length)
writeInterfaceBody(element);
else
write("{}");
} else
write(type);
}
writeln(";");
}
}

View file

@ -1,8 +0,0 @@
{
"version": "6.9.0",
"dependencies": {
"escodegen": "^2.0.0",
"espree": "^7.1.0",
"tmp": "^0.2.1"
}
}

View file

@ -1,32 +0,0 @@
{
"name": "protobufjs-cli",
"description": "Translates between file formats and generates static code as well as TypeScript definitions.",
"version": "6.9.0",
"author": "Daniel Wirtz <dcode+protobufjs@dcode.io>",
"repository": {
"type": "git",
"url": "https://github.com/dcodeIO/protobuf.js.git"
},
"license": "BSD-3-Clause",
"main": "index.js",
"types": "index.d.ts",
"bin": {
"pbjs": "bin/pbjs",
"pbts": "bin/pbts"
},
"peerDependencies": {
"protobufjs": "~6.9.0"
},
"dependencies": {
"chalk": "^3.0.0",
"escodegen": "^1.13.0",
"espree": "^6.1.2",
"estraverse": "^4.3.0",
"glob": "^7.1.6",
"jsdoc": "^3.6.3",
"minimist": "^1.2.0",
"semver": "^7.1.2",
"tmp": "^0.1.0",
"uglify-js": "^3.7.7"
}
}

View file

@ -1,9 +0,0 @@
type pbjsCallback = (err: Error|null, output?: string) => void;
/**
* Runs pbjs programmatically.
* @param {string[]} args Command line arguments
* @param {function(?Error, string=)} [callback] Optional completion callback
* @returns {number|undefined} Exit code, if known
*/
export function main(args: string[], callback?: pbjsCallback): number|undefined;

View file

@ -1,330 +0,0 @@
"use strict";
var path = require("path"),
fs = require("fs"),
pkg = require("./package.json"),
util = require("./util");
util.setup();
var protobuf = require(util.pathToProtobufJs),
minimist = require("minimist"),
chalk = require("chalk"),
glob = require("glob");
var targets = util.requireAll("./targets");
/**
* Runs pbjs programmatically.
* @param {string[]} args Command line arguments
* @param {function(?Error, string=)} [callback] Optional completion callback
* @returns {number|undefined} Exit code, if known
*/
exports.main = function main(args, callback) {
var lintDefault = "eslint-disable " + [
"block-scoped-var",
"id-length",
"no-control-regex",
"no-magic-numbers",
"no-prototype-builtins",
"no-redeclare",
"no-shadow",
"no-var",
"sort-vars"
].join(", ");
var argv = minimist(args, {
alias: {
target: "t",
out: "o",
path: "p",
wrap: "w",
root: "r",
lint: "l",
// backward compatibility:
"force-long": "strict-long",
"force-message": "strict-message"
},
string: [ "target", "out", "path", "wrap", "dependency", "root", "lint" ],
boolean: [ "create", "encode", "decode", "verify", "convert", "delimited", "beautify", "comments", "service", "es6", "sparse", "keep-case", "force-long", "force-number", "force-enum-string", "force-message" ],
default: {
target: "json",
create: true,
encode: true,
decode: true,
verify: true,
convert: true,
delimited: true,
beautify: true,
comments: true,
service: true,
es6: null,
lint: lintDefault,
"keep-case": false,
"force-long": false,
"force-number": false,
"force-enum-string": false,
"force-message": false
}
});
var target = targets[argv.target],
files = argv._,
paths = typeof argv.path === "string" ? [ argv.path ] : argv.path || [];
// alias hyphen args in camel case
Object.keys(argv).forEach(function(key) {
var camelKey = key.replace(/-([a-z])/g, function($0, $1) { return $1.toUpperCase(); });
if (camelKey !== key)
argv[camelKey] = argv[key];
});
// protobuf.js package directory contains additional, otherwise non-bundled google types
paths.push(path.relative(process.cwd(), path.join(__dirname, "..")) || ".");
if (!files.length) {
var descs = Object.keys(targets).filter(function(key) { return !targets[key].private; }).map(function(key) {
return " " + util.pad(key, 14, true) + targets[key].description;
});
if (callback)
callback(Error("usage")); // eslint-disable-line callback-return
else
process.stderr.write([
"protobuf.js v" + pkg.version + " CLI for JavaScript",
"",
chalk.bold.white("Translates between file formats and generates static code."),
"",
" -t, --target Specifies the target format. Also accepts a path to require a custom target.",
"",
descs.join("\n"),
"",
" -p, --path Adds a directory to the include path.",
"",
" -o, --out Saves to a file instead of writing to stdout.",
"",
" --sparse Exports only those types referenced from a main file (experimental).",
"",
chalk.bold.gray(" Module targets only:"),
"",
" -w, --wrap Specifies the wrapper to use. Also accepts a path to require a custom wrapper.",
"",
" default Default wrapper supporting both CommonJS and AMD",
" commonjs CommonJS wrapper",
" amd AMD wrapper",
" es6 ES6 wrapper (implies --es6)",
" closure A closure adding to protobuf.roots where protobuf is a global",
"",
" --dependency Specifies which version of protobuf to require. Accepts any valid module id",
"",
" -r, --root Specifies an alternative protobuf.roots name.",
"",
" -l, --lint Linter configuration. Defaults to protobuf.js-compatible rules:",
"",
" " + lintDefault,
"",
" --es6 Enables ES6 syntax (const/let instead of var)",
"",
chalk.bold.gray(" Proto sources only:"),
"",
" --keep-case Keeps field casing instead of converting to camel case.",
"",
chalk.bold.gray(" Static targets only:"),
"",
" --no-create Does not generate create functions used for reflection compatibility.",
" --no-encode Does not generate encode functions.",
" --no-decode Does not generate decode functions.",
" --no-verify Does not generate verify functions.",
" --no-convert Does not generate convert functions like from/toObject",
" --no-delimited Does not generate delimited encode/decode functions.",
" --no-beautify Does not beautify generated code.",
" --no-comments Does not output any JSDoc comments.",
" --no-service Does not output service classes.",
"",
" --force-long Enfores the use of 'Long' for s-/u-/int64 and s-/fixed64 fields.",
" --force-number Enfores the use of 'number' for s-/u-/int64 and s-/fixed64 fields.",
" --force-message Enfores the use of message instances instead of plain objects.",
"",
"usage: " + chalk.bold.green("pbjs") + " [options] file1.proto file2.json ..." + chalk.gray(" (or pipe) ") + "other | " + chalk.bold.green("pbjs") + " [options] -",
""
].join("\n"));
return 1;
}
if (typeof argv["strict-long"] === "boolean")
argv["force-long"] = argv["strict-long"];
// Resolve glob expressions
for (var i = 0; i < files.length;) {
if (glob.hasMagic(files[i])) {
var matches = glob.sync(files[i]);
Array.prototype.splice.apply(files, [i, 1].concat(matches));
i += matches.length;
} else
++i;
}
// Require custom target
if (!target)
target = require(path.resolve(process.cwd(), argv.target));
var root = new protobuf.Root();
var mainFiles = [];
// Search include paths when resolving imports
root.resolvePath = function pbjsResolvePath(origin, target) {
var normOrigin = protobuf.util.path.normalize(origin),
normTarget = protobuf.util.path.normalize(target);
if (!normOrigin)
mainFiles.push(normTarget);
var resolved = protobuf.util.path.resolve(normOrigin, normTarget, true);
var idx = resolved.lastIndexOf("google/protobuf/");
if (idx > -1) {
var altname = resolved.substring(idx);
if (altname in protobuf.common)
resolved = altname;
}
if (fs.existsSync(resolved))
return resolved;
for (var i = 0; i < paths.length; ++i) {
var iresolved = protobuf.util.path.resolve(paths[i] + "/", target);
if (fs.existsSync(iresolved))
return iresolved;
}
return resolved;
};
// `--wrap es6` implies `--es6` but not the other way around. You can still use e.g. `--es6 --wrap commonjs`
if (argv.wrap === "es6") {
argv.es6 = true;
}
var parseOptions = {
"keepCase": argv["keep-case"] || false
};
// Read from stdin
if (files.length === 1 && files[0] === "-") {
var data = [];
process.stdin.on("data", function(chunk) {
data.push(chunk);
});
process.stdin.on("end", function() {
var source = Buffer.concat(data).toString("utf8");
try {
if (source.charAt(0) !== "{") {
protobuf.parse.filename = "-";
protobuf.parse(source, root, parseOptions);
} else {
var json = JSON.parse(source);
root.setOptions(json.options).addJSON(json);
}
callTarget();
} catch (err) {
if (callback) {
callback(err);
return;
}
throw err;
}
});
// Load from disk
} else {
try {
root.loadSync(files, parseOptions).resolveAll(); // sync is deterministic while async is not
if (argv.sparse)
sparsify(root);
callTarget();
} catch (err) {
if (callback) {
callback(err);
return undefined;
}
throw err;
}
}
function markReferenced(tobj) {
tobj.referenced = true;
// also mark a type's fields and oneofs
if (tobj.fieldsArray)
tobj.fieldsArray.forEach(function(fobj) {
fobj.referenced = true;
});
if (tobj.oneofsArray)
tobj.oneofsArray.forEach(function(oobj) {
oobj.referenced = true;
});
// also mark an extension field's extended type, but not its (other) fields
if (tobj.extensionField)
tobj.extensionField.parent.referenced = true;
}
function sparsify(root) {
// 1. mark directly or indirectly referenced objects
util.traverse(root, function(obj) {
if (!obj.filename)
return;
if (mainFiles.indexOf(obj.filename) > -1)
util.traverseResolved(obj, markReferenced);
});
// 2. empty unreferenced objects
util.traverse(root, function(obj) {
var parent = obj.parent;
if (!parent || obj.referenced) // root or referenced
return;
// remove unreferenced namespaces
if (obj instanceof protobuf.Namespace) {
var hasReferenced = false;
util.traverse(obj, function(iobj) {
if (iobj.referenced)
hasReferenced = true;
});
if (hasReferenced) { // replace with plain namespace if a namespace subclass
if (obj instanceof protobuf.Type || obj instanceof protobuf.Service) {
var robj = new protobuf.Namespace(obj.name, obj.options);
robj.nested = obj.nested;
parent.add(robj);
}
} else // remove completely if nothing inside is referenced
parent.remove(obj);
// remove everything else unreferenced
} else if (!(obj instanceof protobuf.Namespace))
parent.remove(obj);
});
// 3. validate that everything is fine
root.resolveAll();
}
function callTarget() {
target(root, argv, function targetCallback(err, output) {
if (err) {
if (callback)
return callback(err);
throw err;
}
try {
if (argv.out)
fs.writeFileSync(argv.out, output, { encoding: "utf8" });
else if (!callback)
process.stdout.write(output, "utf8");
return callback
? callback(null, output)
: undefined;
} catch (err) {
if (callback)
return callback(err);
throw err;
}
});
}
return undefined;
};

View file

@ -1,9 +0,0 @@
type pbtsCallback = (err: Error|null, output?: string) => void;
/**
* Runs pbts programmatically.
* @param {string[]} args Command line arguments
* @param {function(?Error, string=)} [callback] Optional completion callback
* @returns {number|undefined} Exit code, if known
*/
export function main(args: string[], callback?: pbtsCallback): number|undefined;

View file

@ -1,197 +0,0 @@
"use strict";
var child_process = require("child_process"),
path = require("path"),
fs = require("fs"),
pkg = require("./package.json"),
util = require("./util");
util.setup();
var minimist = require("minimist"),
chalk = require("chalk"),
glob = require("glob"),
tmp = require("tmp");
/**
* Runs pbts programmatically.
* @param {string[]} args Command line arguments
* @param {function(?Error, string=)} [callback] Optional completion callback
* @returns {number|undefined} Exit code, if known
*/
exports.main = function(args, callback) {
var argv = minimist(args, {
alias: {
name: "n",
out : "o",
main: "m",
global: "g",
import: "i"
},
string: [ "name", "out", "global", "import" ],
boolean: [ "comments", "main" ],
default: {
comments: true,
main: false
}
});
var files = argv._;
if (!files.length) {
if (callback)
callback(Error("usage")); // eslint-disable-line callback-return
else
process.stderr.write([
"protobuf.js v" + pkg.version + " CLI for TypeScript",
"",
chalk.bold.white("Generates TypeScript definitions from annotated JavaScript files."),
"",
" -o, --out Saves to a file instead of writing to stdout.",
"",
" -g, --global Name of the global object in browser environments, if any.",
"",
" -i, --import Comma delimited list of imports. Local names will equal camelCase of the basename.",
"",
" --no-comments Does not output any JSDoc comments.",
"",
chalk.bold.gray(" Internal flags:"),
"",
" -n, --name Wraps everything in a module of the specified name.",
"",
" -m, --main Whether building the main library without any imports.",
"",
"usage: " + chalk.bold.green("pbts") + " [options] file1.js file2.js ..." + chalk.bold.gray(" (or) ") + "other | " + chalk.bold.green("pbts") + " [options] -",
""
].join("\n"));
return 1;
}
// Resolve glob expressions
for (var i = 0; i < files.length;) {
if (glob.hasMagic(files[i])) {
var matches = glob.sync(files[i]);
Array.prototype.splice.apply(files, [i, 1].concat(matches));
i += matches.length;
} else
++i;
}
var cleanup = [];
// Read from stdin (to a temporary file)
if (files.length === 1 && files[0] === "-") {
var data = [];
process.stdin.on("data", function(chunk) {
data.push(chunk);
});
process.stdin.on("end", function() {
files[0] = tmp.tmpNameSync() + ".js";
fs.writeFileSync(files[0], Buffer.concat(data));
cleanup.push(files[0]);
callJsdoc();
});
// Load from disk
} else {
callJsdoc();
}
function callJsdoc() {
// There is no proper API for jsdoc, so this executes the CLI and pipes the output
var basedir = path.join(__dirname, ".");
var moduleName = argv.name || "null";
var nodePath = process.execPath;
var cmd = "\"" + nodePath + "\" \"" + require.resolve("jsdoc/jsdoc.js") + "\" -c \"" + path.join(basedir, "lib", "tsd-jsdoc.json") + "\" -q \"module=" + encodeURIComponent(moduleName) + "&comments=" + Boolean(argv.comments) + "\" " + files.map(function(file) { return "\"" + file + "\""; }).join(" ");
var child = child_process.exec(cmd, {
cwd: process.cwd(),
argv0: "node",
stdio: "pipe",
maxBuffer: 1 << 24 // 16mb
});
var out = [];
var ended = false;
var closed = false;
child.stdout.on("data", function(data) {
out.push(data);
});
child.stdout.on("end", function() {
if (closed) finish();
else ended = true;
});
child.stderr.pipe(process.stderr);
child.on("close", function(code) {
// clean up temporary files, no matter what
try { cleanup.forEach(fs.unlinkSync); } catch(e) {/**/} cleanup = [];
if (code) {
out = out.join("").replace(/\s*JSDoc \d+\.\d+\.\d+ [^$]+/, "");
process.stderr.write(out);
var err = Error("code " + code);
if (callback)
return callback(err);
throw err;
}
if (ended) return finish();
closed = true;
return undefined;
});
function getImportName(importItem) {
return path.basename(importItem, ".js").replace(/([-_~.+]\w)/g, function(match) {
return match[1].toUpperCase();
});
}
function finish() {
var output = [];
if (argv.main)
output.push(
"// DO NOT EDIT! This is a generated file. Edit the JSDoc in src/*.js instead and run 'npm run types'.",
""
);
if (argv.global)
output.push(
"export as namespace " + argv.global + ";",
""
);
if (!argv.main) {
// Ensure we have a usable array of imports
var importArray = typeof argv.import === "string" ? argv.import.split(",") : argv.import || [];
// Build an object of imports and paths
var imports = {
$protobuf: "protobufjs"
};
importArray.forEach(function(importItem) {
imports[getImportName(importItem)] = importItem;
});
// Write out the imports
Object.keys(imports).forEach(function(key) {
output.push("import * as " + key + " from \"" + imports[key] + "\";");
});
}
output = output.join("\n") + "\n" + out.join("");
try {
if (argv.out)
fs.writeFileSync(argv.out, output, { encoding: "utf8" });
else if (!callback)
process.stdout.write(output, "utf8");
return callback
? callback(null, output)
: undefined;
} catch (err) {
if (callback)
return callback(err);
throw err;
}
}
}
return undefined;
};

View file

@ -1,38 +0,0 @@
"use strict";
module.exports = json_module;
var util = require("../util");
var protobuf = require("../..");
json_module.description = "JSON representation as a module";
function jsonSafeProp(json) {
return json.replace(/^( +)"(\w+)":/mg, function($0, $1, $2) {
return protobuf.util.safeProp($2).charAt(0) === "."
? $1 + $2 + ":"
: $0;
});
}
function json_module(root, options, callback) {
try {
var rootProp = protobuf.util.safeProp(options.root || "default");
var output = [
(options.es6 ? "const" : "var") + " $root = ($protobuf.roots" + rootProp + " || ($protobuf.roots" + rootProp + " = new $protobuf.Root()))\n"
];
if (root.options) {
var optionsJson = jsonSafeProp(JSON.stringify(root.options, null, 2));
output.push(".setOptions(" + optionsJson + ")\n");
}
var json = jsonSafeProp(JSON.stringify(root.nested, null, 2).trim());
output.push(".addJSON(" + json + ");");
output = util.wrap(output.join(""), protobuf.util.merge({ dependency: "protobufjs/light" }, options));
process.nextTick(function() {
callback(null, output);
});
} catch (e) {
return callback(e);
}
return undefined;
}

View file

@ -1,8 +0,0 @@
"use strict";
module.exports = json_target;
json_target.description = "JSON representation";
function json_target(root, options, callback) {
callback(null, JSON.stringify(root, null, 2));
}

View file

@ -1,326 +0,0 @@
"use strict";
module.exports = proto_target;
proto_target.private = true;
var protobuf = require("../..");
var Namespace = protobuf.Namespace,
Enum = protobuf.Enum,
Type = protobuf.Type,
Field = protobuf.Field,
OneOf = protobuf.OneOf,
Service = protobuf.Service,
Method = protobuf.Method,
types = protobuf.types,
util = protobuf.util;
function underScore(str) {
return str.substring(0,1)
+ str.substring(1)
.replace(/([A-Z])(?=[a-z]|$)/g, function($0, $1) { return "_" + $1.toLowerCase(); });
}
var out = [];
var indent = 0;
var first = false;
var syntax = 3;
function proto_target(root, options, callback) {
if (options) {
switch (options.syntax) {
case undefined:
case "proto3":
case "3":
syntax = 3;
break;
case "proto2":
case "2":
syntax = 2;
break;
default:
return callback(Error("invalid syntax: " + options.syntax));
}
}
indent = 0;
first = false;
try {
buildRoot(root);
return callback(null, out.join("\n"));
} catch (err) {
return callback(err);
} finally {
out = [];
syntax = 3;
}
}
function push(line) {
if (line === "")
out.push("");
else {
var ind = "";
for (var i = 0; i < indent; ++i)
ind += " ";
out.push(ind + line);
}
}
function escape(str) {
return str.replace(/[\\"']/g, "\\$&")
.replace(/\r/g, "\\r")
.replace(/\n/g, "\\n")
.replace(/\u0000/g, "\\0"); // eslint-disable-line no-control-regex
}
function value(v) {
switch (typeof v) {
case "boolean":
return v ? "true" : "false";
case "number":
return v.toString();
default:
return "\"" + escape(String(v)) + "\"";
}
}
function buildRoot(root) {
root.resolveAll();
var pkg = [];
var ptr = root;
var repeat = true;
do {
var nested = ptr.nestedArray;
if (nested.length === 1 && nested[0] instanceof Namespace && !(nested[0] instanceof Type || nested[0] instanceof Service)) {
ptr = nested[0];
if (ptr !== root)
pkg.push(ptr.name);
} else
repeat = false;
} while (repeat);
out.push("syntax = \"proto" + syntax + "\";");
if (pkg.length)
out.push("", "package " + pkg.join(".") + ";");
buildOptions(ptr);
ptr.nestedArray.forEach(build);
}
function build(object) {
if (object instanceof Enum)
buildEnum(object);
else if (object instanceof Type)
buildType(object);
else if (object instanceof Field)
buildField(object);
else if (object instanceof OneOf)
buildOneOf(object);
else if (object instanceof Service)
buildService(object);
else if (object instanceof Method)
buildMethod(object);
else
buildNamespace(object);
}
function buildNamespace(namespace) { // just a namespace, not a type etc.
push("");
push("message " + namespace.name + " {");
++indent;
buildOptions(namespace);
consolidateExtends(namespace.nestedArray).remaining.forEach(build);
--indent;
push("}");
}
function buildEnum(enm) {
push("");
push("enum " + enm.name + " {");
buildOptions(enm);
++indent; first = true;
Object.keys(enm.values).forEach(function(name) {
var val = enm.values[name];
if (first) {
push("");
first = false;
}
push(name + " = " + val + ";");
});
--indent; first = false;
push("}");
}
function buildRanges(keyword, ranges) {
if (ranges && ranges.length) {
var parts = [];
ranges.forEach(function(range) {
if (typeof range === "string")
parts.push("\"" + escape(range) + "\"");
else if (range[0] === range[1])
parts.push(range[0]);
else
parts.push(range[0] + " to " + (range[1] === 0x1FFFFFFF ? "max" : range[1]));
});
push("");
push(keyword + " " + parts.join(", ") + ";");
}
}
function buildType(type) {
if (type.group)
return; // built with the sister-field
push("");
push("message " + type.name + " {");
++indent;
buildOptions(type);
type.oneofsArray.forEach(build);
first = true;
type.fieldsArray.forEach(build);
consolidateExtends(type.nestedArray).remaining.forEach(build);
buildRanges("extensions", type.extensions);
buildRanges("reserved", type.reserved);
--indent;
push("}");
}
function buildField(field, passExtend) {
if (field.partOf || field.declaringField || field.extend !== undefined && !passExtend)
return;
if (first) {
first = false;
push("");
}
if (field.resolvedType && field.resolvedType.group) {
buildGroup(field);
return;
}
var sb = [];
if (field.map)
sb.push("map<" + field.keyType + ", " + field.type + ">");
else if (field.repeated)
sb.push("repeated", field.type);
else if (syntax === 2 || field.parent.group)
sb.push(field.required ? "required" : "optional", field.type);
else
sb.push(field.type);
sb.push(underScore(field.name), "=", field.id);
var opts = buildFieldOptions(field);
if (opts)
sb.push(opts);
push(sb.join(" ") + ";");
}
function buildGroup(field) {
push(field.rule + " group " + field.resolvedType.name + " = " + field.id + " {");
++indent;
buildOptions(field.resolvedType);
first = true;
field.resolvedType.fieldsArray.forEach(function(field) {
buildField(field);
});
--indent;
push("}");
}
function buildFieldOptions(field) {
var keys;
if (!field.options || !(keys = Object.keys(field.options)).length)
return null;
var sb = [];
keys.forEach(function(key) {
var val = field.options[key];
var wireType = types.packed[field.resolvedType instanceof Enum ? "int32" : field.type];
switch (key) {
case "packed":
val = Boolean(val);
// skip when not packable or syntax default
if (wireType === undefined || syntax === 3 === val)
return;
break;
case "default":
if (syntax === 3)
return;
// skip default (resolved) default values
if (field.long && !util.longNeq(field.defaultValue, types.defaults[field.type]) || !field.long && field.defaultValue === types.defaults[field.type])
return;
// enum defaults specified as strings are type references and not enclosed in quotes
if (field.resolvedType instanceof Enum)
break;
// otherwise fallthrough
default:
val = value(val);
break;
}
sb.push(key + "=" + val);
});
return sb.length
? "[" + sb.join(", ") + "]"
: null;
}
function consolidateExtends(nested) {
var ext = {};
nested = nested.filter(function(obj) {
if (!(obj instanceof Field) || obj.extend === undefined)
return true;
(ext[obj.extend] || (ext[obj.extend] = [])).push(obj);
return false;
});
Object.keys(ext).forEach(function(extend) {
push("");
push("extend " + extend + " {");
++indent; first = true;
ext[extend].forEach(function(field) {
buildField(field, true);
});
--indent;
push("}");
});
return {
remaining: nested
};
}
function buildOneOf(oneof) {
push("");
push("oneof " + underScore(oneof.name) + " {");
++indent; first = true;
oneof.oneof.forEach(function(fieldName) {
var field = oneof.parent.get(fieldName);
if (first) {
first = false;
push("");
}
var opts = buildFieldOptions(field);
push(field.type + " " + underScore(field.name) + " = " + field.id + (opts ? " " + opts : "") + ";");
});
--indent;
push("}");
}
function buildService(service) {
push("service " + service.name + " {");
++indent;
service.methodsArray.forEach(build);
consolidateExtends(service.nestedArray).remaining.forEach(build);
--indent;
push("}");
}
function buildMethod(method) {
push(method.type + " " + method.name + " (" + (method.requestStream ? "stream " : "") + method.requestType + ") returns (" + (method.responseStream ? "stream " : "") + method.responseType + ");");
}
function buildOptions(object) {
if (!object.options)
return;
first = true;
Object.keys(object.options).forEach(function(key) {
if (first) {
first = false;
push("");
}
var val = object.options[key];
push("option " + key + " = " + JSON.stringify(val) + ";");
});
}

View file

@ -1,10 +0,0 @@
"use strict";
module.exports = proto2_target;
var protobuf = require("../..");
proto2_target.description = "Protocol Buffers, Version 2";
function proto2_target(root, options, callback) {
require("./proto")(root, protobuf.util.merge(options, { syntax: "proto2" }), callback);
}

View file

@ -1,10 +0,0 @@
"use strict";
module.exports = proto3_target;
var protobuf = require("../..");
proto3_target.description = "Protocol Buffers, Version 3";
function proto3_target(root, options, callback) {
require("./proto")(root, protobuf.util.merge(options, { syntax: "proto3" }), callback);
}

View file

@ -1,29 +0,0 @@
"use strict";
module.exports = static_module_target;
// - The default wrapper supports AMD, CommonJS and the global scope (as window.root), in this order.
// - You can specify a custom wrapper with the --wrap argument.
// - CommonJS modules depend on the minimal build for reduced package size with browserify.
// - AMD and global scope depend on the full library for now.
var util = require("../util");
var protobuf = require("../..");
static_module_target.description = "Static code without reflection as a module";
function static_module_target(root, options, callback) {
require("./static")(root, options, function(err, output) {
if (err) {
callback(err);
return;
}
try {
output = util.wrap(output, protobuf.util.merge({ dependency: "protobufjs/minimal" }, options));
} catch (e) {
callback(e);
return;
}
callback(null, output);
});
}

View file

@ -1,711 +0,0 @@
"use strict";
module.exports = static_target;
var protobuf = require("../.."),
UglifyJS = require("uglify-js"),
espree = require("espree"),
escodegen = require("escodegen"),
estraverse = require("estraverse");
var Type = protobuf.Type,
Service = protobuf.Service,
Enum = protobuf.Enum,
Namespace = protobuf.Namespace,
util = protobuf.util;
var out = [];
var indent = 0;
var config = {};
static_target.description = "Static code without reflection (non-functional on its own)";
function static_target(root, options, callback) {
config = options;
try {
var aliases = [];
if (config.decode)
aliases.push("Reader");
if (config.encode)
aliases.push("Writer");
aliases.push("util");
if (aliases.length) {
if (config.comments)
push("// Common aliases");
push((config.es6 ? "const " : "var ") + aliases.map(function(name) { return "$" + name + " = $protobuf." + name; }).join(", ") + ";");
push("");
}
if (config.comments) {
if (root.comment) {
pushComment("@fileoverview " + root.comment);
push("");
}
push("// Exported root namespace");
}
var rootProp = util.safeProp(config.root || "default");
push((config.es6 ? "const" : "var") + " $root = $protobuf.roots" + rootProp + " || ($protobuf.roots" + rootProp + " = {});");
buildNamespace(null, root);
return callback(null, out.join("\n"));
} catch (err) {
return callback(err);
} finally {
out = [];
indent = 0;
config = {};
}
}
function push(line) {
if (line === "")
return out.push("");
var ind = "";
for (var i = 0; i < indent; ++i)
ind += " ";
return out.push(ind + line);
}
function pushComment(lines) {
if (!config.comments)
return;
var split = [];
for (var i = 0; i < lines.length; ++i)
if (lines[i] != null && lines[i].substring(0, 8) !== "@exclude")
Array.prototype.push.apply(split, lines[i].split(/\r?\n/g));
push("/**");
split.forEach(function(line) {
if (line === null)
return;
push(" * " + line.replace(/\*\//g, "* /"));
});
push(" */");
}
function exportName(object, asInterface) {
if (asInterface) {
if (object.__interfaceName)
return object.__interfaceName;
} else if (object.__exportName)
return object.__exportName;
var parts = object.fullName.substring(1).split("."),
i = 0;
while (i < parts.length)
parts[i] = escapeName(parts[i++]);
if (asInterface)
parts[i - 1] = "I" + parts[i - 1];
return object[asInterface ? "__interfaceName" : "__exportName"] = parts.join(".");
}
function escapeName(name) {
if (!name)
return "$root";
return util.isReserved(name) ? name + "_" : name;
}
function aOrAn(name) {
return ((/^[hH](?:ou|on|ei)/.test(name) || /^[aeiouAEIOU][a-z]/.test(name)) && !/^us/i.test(name)
? "an "
: "a ") + name;
}
function buildNamespace(ref, ns) {
if (!ns)
return;
if (ns instanceof Service && !config.service)
return;
if (ns.name !== "") {
push("");
if (!ref && config.es6)
push("export const " + escapeName(ns.name) + " = " + escapeName(ref) + "." + escapeName(ns.name) + " = (() => {");
else
push(escapeName(ref) + "." + escapeName(ns.name) + " = (function() {");
++indent;
}
if (ns instanceof Type) {
buildType(undefined, ns);
} else if (ns instanceof Service)
buildService(undefined, ns);
else if (ns.name !== "") {
push("");
pushComment([
ns.comment || "Namespace " + ns.name + ".",
ns.parent instanceof protobuf.Root ? "@exports " + escapeName(ns.name) : "@memberof " + exportName(ns.parent),
"@namespace"
]);
push((config.es6 ? "const" : "var") + " " + escapeName(ns.name) + " = {};");
}
ns.nestedArray.forEach(function(nested) {
if (nested instanceof Enum)
buildEnum(ns.name, nested);
else if (nested instanceof Namespace)
buildNamespace(ns.name, nested);
});
if (ns.name !== "") {
push("");
push("return " + escapeName(ns.name) + ";");
--indent;
push("})();");
}
}
var reduceableBlockStatements = {
IfStatement: true,
ForStatement: true,
WhileStatement: true
};
var shortVars = {
"r": "reader",
"w": "writer",
"m": "message",
"t": "tag",
"l": "length",
"c": "end", "c2": "end2",
"k": "key",
"ks": "keys", "ks2": "keys2",
"e": "error",
"f": "impl",
"o": "options",
"d": "object",
"n": "long",
"p": "properties"
};
function beautifyCode(code) {
// Add semicolons
code = UglifyJS.minify(code, {
compress: false,
mangle: false,
output: { beautify: true }
}).code;
// Properly beautify
var ast = espree.parse(code);
estraverse.replace(ast, {
enter: function(node, parent) {
// rename short vars
if (node.type === "Identifier" && (parent.property !== node || parent.computed) && shortVars[node.name])
return {
"type": "Identifier",
"name": shortVars[node.name]
};
// replace var with let if es6
if (config.es6 && node.type === "VariableDeclaration" && node.kind === "var") {
node.kind = "let";
return undefined;
}
// remove braces around block statements with a single child
if (node.type === "BlockStatement" && reduceableBlockStatements[parent.type] && node.body.length === 1)
return node.body[0];
return undefined;
}
});
code = escodegen.generate(ast, {
format: {
newline: "\n",
quotes: "double"
}
});
// Add id, wireType comments
if (config.comments)
code = code.replace(/\.uint32\((\d+)\)/g, function($0, $1) {
var id = $1 >>> 3,
wireType = $1 & 7;
return ".uint32(/* id " + id + ", wireType " + wireType + " =*/" + $1 + ")";
});
return code;
}
var renameVars = {
"Writer": "$Writer",
"Reader": "$Reader",
"util": "$util"
};
function buildFunction(type, functionName, gen, scope) {
var code = gen.toString(functionName)
.replace(/((?!\.)types\[\d+])(\.values)/g, "$1"); // enums: use types[N] instead of reflected types[N].values
var ast = espree.parse(code);
/* eslint-disable no-extra-parens */
estraverse.replace(ast, {
enter: function(node, parent) {
// rename vars
if (
node.type === "Identifier" && renameVars[node.name]
&& (
(parent.type === "MemberExpression" && parent.object === node)
|| (parent.type === "BinaryExpression" && parent.right === node)
)
)
return {
"type": "Identifier",
"name": renameVars[node.name]
};
// replace this.ctor with the actual ctor
if (
node.type === "MemberExpression"
&& node.object.type === "ThisExpression"
&& node.property.type === "Identifier" && node.property.name === "ctor"
)
return {
"type": "Identifier",
"name": "$root" + type.fullName
};
// replace types[N] with the field's actual type
if (
node.type === "MemberExpression"
&& node.object.type === "Identifier" && node.object.name === "types"
&& node.property.type === "Literal"
)
return {
"type": "Identifier",
"name": "$root" + type.fieldsArray[node.property.value].resolvedType.fullName
};
return undefined;
}
});
/* eslint-enable no-extra-parens */
code = escodegen.generate(ast, {
format: {
newline: "\n",
quotes: "double"
}
});
if (config.beautify)
code = beautifyCode(code);
code = code.replace(/ {4}/g, "\t");
var hasScope = scope && Object.keys(scope).length,
isCtor = functionName === type.name;
if (hasScope) // remove unused scope vars
Object.keys(scope).forEach(function(key) {
if (!new RegExp("\\b(" + key + ")\\b", "g").test(code))
delete scope[key];
});
var lines = code.split(/\n/g);
if (isCtor) // constructor
push(lines[0]);
else if (hasScope) // enclose in an iife
push(escapeName(type.name) + "." + escapeName(functionName) + " = (function(" + Object.keys(scope).map(escapeName).join(", ") + ") { return " + lines[0]);
else
push(escapeName(type.name) + "." + escapeName(functionName) + " = " + lines[0]);
lines.slice(1, lines.length - 1).forEach(function(line) {
var prev = indent;
var i = 0;
while (line.charAt(i++) === "\t")
++indent;
push(line.trim());
indent = prev;
});
if (isCtor)
push("}");
else if (hasScope)
push("};})(" + Object.keys(scope).map(function(key) { return scope[key]; }).join(", ") + ");");
else
push("};");
}
function toJsType(field) {
var type;
switch (field.type) {
case "double":
case "float":
case "int32":
case "uint32":
case "sint32":
case "fixed32":
case "sfixed32":
type = "number";
break;
case "int64":
case "uint64":
case "sint64":
case "fixed64":
case "sfixed64":
type = config.forceLong ? "Long" : config.forceNumber ? "number" : "number|Long";
break;
case "bool":
type = "boolean";
break;
case "string":
type = "string";
break;
case "bytes":
type = "Uint8Array";
break;
default:
if (field.resolve().resolvedType)
type = exportName(field.resolvedType, !(field.resolvedType instanceof protobuf.Enum || config.forceMessage));
else
type = "*"; // should not happen
break;
}
if (field.map)
return "Object.<string," + type + ">";
if (field.repeated)
return "Array.<" + type + ">";
return type;
}
function buildType(ref, type) {
if (config.comments) {
var typeDef = [
"Properties of " + aOrAn(type.name) + ".",
type.parent instanceof protobuf.Root ? "@exports " + escapeName("I" + type.name) : "@memberof " + exportName(type.parent),
"@interface " + escapeName("I" + type.name)
];
type.fieldsArray.forEach(function(field) {
var prop = util.safeProp(field.name); // either .name or ["name"]
prop = prop.substring(1, prop.charAt(0) === "[" ? prop.length - 1 : prop.length);
var jsType = toJsType(field);
if (field.optional)
jsType = jsType + "|null";
typeDef.push("@property {" + jsType + "} " + (field.optional ? "[" + prop + "]" : prop) + " " + (field.comment || type.name + " " + field.name));
});
push("");
pushComment(typeDef);
}
// constructor
push("");
pushComment([
"Constructs a new " + type.name + ".",
type.parent instanceof protobuf.Root ? "@exports " + escapeName(type.name) : "@memberof " + exportName(type.parent),
"@classdesc " + (type.comment || "Represents " + aOrAn(type.name) + "."),
config.comments ? "@implements " + escapeName("I" + type.name) : null,
"@constructor",
"@param {" + exportName(type, true) + "=} [" + (config.beautify ? "properties" : "p") + "] Properties to set"
]);
buildFunction(type, type.name, Type.generateConstructor(type));
// default values
var firstField = true;
type.fieldsArray.forEach(function(field) {
field.resolve();
var prop = util.safeProp(field.name);
if (config.comments) {
push("");
var jsType = toJsType(field);
if (field.optional && !field.map && !field.repeated && field.resolvedType instanceof Type || field.partOf)
jsType = jsType + "|null|undefined";
pushComment([
field.comment || type.name + " " + field.name + ".",
"@member {" + jsType + "} " + field.name,
"@memberof " + exportName(type),
"@instance"
]);
} else if (firstField) {
push("");
firstField = false;
}
if (field.repeated)
push(escapeName(type.name) + ".prototype" + prop + " = $util.emptyArray;"); // overwritten in constructor
else if (field.map)
push(escapeName(type.name) + ".prototype" + prop + " = $util.emptyObject;"); // overwritten in constructor
else if (field.partOf)
push(escapeName(type.name) + ".prototype" + prop + " = null;"); // do not set default value for oneof members
else if (field.long)
push(escapeName(type.name) + ".prototype" + prop + " = $util.Long ? $util.Long.fromBits("
+ JSON.stringify(field.typeDefault.low) + ","
+ JSON.stringify(field.typeDefault.high) + ","
+ JSON.stringify(field.typeDefault.unsigned)
+ ") : " + field.typeDefault.toNumber(field.type.charAt(0) === "u") + ";");
else if (field.bytes) {
push(escapeName(type.name) + ".prototype" + prop + " = $util.newBuffer(" + JSON.stringify(Array.prototype.slice.call(field.typeDefault)) + ");");
} else
push(escapeName(type.name) + ".prototype" + prop + " = " + JSON.stringify(field.typeDefault) + ";");
});
// virtual oneof fields
var firstOneOf = true;
type.oneofsArray.forEach(function(oneof) {
if (firstOneOf) {
firstOneOf = false;
push("");
if (config.comments)
push("// OneOf field names bound to virtual getters and setters");
push((config.es6 ? "let" : "var") + " $oneOfFields;");
}
oneof.resolve();
push("");
pushComment([
oneof.comment || type.name + " " + oneof.name + ".",
"@member {" + oneof.oneof.map(JSON.stringify).join("|") + "|undefined} " + escapeName(oneof.name),
"@memberof " + exportName(type),
"@instance"
]);
push("Object.defineProperty(" + escapeName(type.name) + ".prototype, " + JSON.stringify(oneof.name) +", {");
++indent;
push("get: $util.oneOfGetter($oneOfFields = [" + oneof.oneof.map(JSON.stringify).join(", ") + "]),");
push("set: $util.oneOfSetter($oneOfFields)");
--indent;
push("});");
});
if (config.create) {
push("");
pushComment([
"Creates a new " + type.name + " instance using the specified properties.",
"@function create",
"@memberof " + exportName(type),
"@static",
"@param {" + exportName(type, true) + "=} [properties] Properties to set",
"@returns {" + exportName(type) + "} " + type.name + " instance"
]);
push(escapeName(type.name) + ".create = function create(properties) {");
++indent;
push("return new " + escapeName(type.name) + "(properties);");
--indent;
push("};");
}
if (config.encode) {
push("");
pushComment([
"Encodes the specified " + type.name + " message. Does not implicitly {@link " + exportName(type) + ".verify|verify} messages.",
"@function encode",
"@memberof " + exportName(type),
"@static",
"@param {" + exportName(type, !config.forceMessage) + "} " + (config.beautify ? "message" : "m") + " " + type.name + " message or plain object to encode",
"@param {$protobuf.Writer} [" + (config.beautify ? "writer" : "w") + "] Writer to encode to",
"@returns {$protobuf.Writer} Writer"
]);
buildFunction(type, "encode", protobuf.encoder(type));
if (config.delimited) {
push("");
pushComment([
"Encodes the specified " + type.name + " message, length delimited. Does not implicitly {@link " + exportName(type) + ".verify|verify} messages.",
"@function encodeDelimited",
"@memberof " + exportName(type),
"@static",
"@param {" + exportName(type, !config.forceMessage) + "} message " + type.name + " message or plain object to encode",
"@param {$protobuf.Writer} [writer] Writer to encode to",
"@returns {$protobuf.Writer} Writer"
]);
push(escapeName(type.name) + ".encodeDelimited = function encodeDelimited(message, writer) {");
++indent;
push("return this.encode(message, writer).ldelim();");
--indent;
push("};");
}
}
if (config.decode) {
push("");
pushComment([
"Decodes " + aOrAn(type.name) + " message from the specified reader or buffer.",
"@function decode",
"@memberof " + exportName(type),
"@static",
"@param {$protobuf.Reader|Uint8Array} " + (config.beautify ? "reader" : "r") + " Reader or buffer to decode from",
"@param {number} [" + (config.beautify ? "length" : "l") + "] Message length if known beforehand",
"@returns {" + exportName(type) + "} " + type.name,
"@throws {Error} If the payload is not a reader or valid buffer",
"@throws {$protobuf.util.ProtocolError} If required fields are missing"
]);
buildFunction(type, "decode", protobuf.decoder(type));
if (config.delimited) {
push("");
pushComment([
"Decodes " + aOrAn(type.name) + " message from the specified reader or buffer, length delimited.",
"@function decodeDelimited",
"@memberof " + exportName(type),
"@static",
"@param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from",
"@returns {" + exportName(type) + "} " + type.name,
"@throws {Error} If the payload is not a reader or valid buffer",
"@throws {$protobuf.util.ProtocolError} If required fields are missing"
]);
push(escapeName(type.name) + ".decodeDelimited = function decodeDelimited(reader) {");
++indent;
push("if (!(reader instanceof $Reader))");
++indent;
push("reader = new $Reader(reader);");
--indent;
push("return this.decode(reader, reader.uint32());");
--indent;
push("};");
}
}
if (config.verify) {
push("");
pushComment([
"Verifies " + aOrAn(type.name) + " message.",
"@function verify",
"@memberof " + exportName(type),
"@static",
"@param {Object.<string,*>} " + (config.beautify ? "message" : "m") + " Plain object to verify",
"@returns {string|null} `null` if valid, otherwise the reason why it is not"
]);
buildFunction(type, "verify", protobuf.verifier(type));
}
if (config.convert) {
push("");
pushComment([
"Creates " + aOrAn(type.name) + " message from a plain object. Also converts values to their respective internal types.",
"@function fromObject",
"@memberof " + exportName(type),
"@static",
"@param {Object.<string,*>} " + (config.beautify ? "object" : "d") + " Plain object",
"@returns {" + exportName(type) + "} " + type.name
]);
buildFunction(type, "fromObject", protobuf.converter.fromObject(type));
push("");
pushComment([
"Creates a plain object from " + aOrAn(type.name) + " message. Also converts values to other types if specified.",
"@function toObject",
"@memberof " + exportName(type),
"@static",
"@param {" + exportName(type) + "} " + (config.beautify ? "message" : "m") + " " + type.name,
"@param {$protobuf.IConversionOptions} [" + (config.beautify ? "options" : "o") + "] Conversion options",
"@returns {Object.<string,*>} Plain object"
]);
buildFunction(type, "toObject", protobuf.converter.toObject(type));
push("");
pushComment([
"Converts this " + type.name + " to JSON.",
"@function toJSON",
"@memberof " + exportName(type),
"@instance",
"@returns {Object.<string,*>} JSON object"
]);
push(escapeName(type.name) + ".prototype.toJSON = function toJSON() {");
++indent;
push("return this.constructor.toObject(this, $protobuf.util.toJSONOptions);");
--indent;
push("};");
}
}
function buildService(ref, service) {
push("");
pushComment([
"Constructs a new " + service.name + " service.",
service.parent instanceof protobuf.Root ? "@exports " + escapeName(service.name) : "@memberof " + exportName(service.parent),
"@classdesc " + (service.comment || "Represents " + aOrAn(service.name)),
"@extends $protobuf.rpc.Service",
"@constructor",
"@param {$protobuf.RPCImpl} rpcImpl RPC implementation",
"@param {boolean} [requestDelimited=false] Whether requests are length-delimited",
"@param {boolean} [responseDelimited=false] Whether responses are length-delimited"
]);
push("function " + escapeName(service.name) + "(rpcImpl, requestDelimited, responseDelimited) {");
++indent;
push("$protobuf.rpc.Service.call(this, rpcImpl, requestDelimited, responseDelimited);");
--indent;
push("}");
push("");
push("(" + escapeName(service.name) + ".prototype = Object.create($protobuf.rpc.Service.prototype)).constructor = " + escapeName(service.name) + ";");
if (config.create) {
push("");
pushComment([
"Creates new " + service.name + " service using the specified rpc implementation.",
"@function create",
"@memberof " + exportName(service),
"@static",
"@param {$protobuf.RPCImpl} rpcImpl RPC implementation",
"@param {boolean} [requestDelimited=false] Whether requests are length-delimited",
"@param {boolean} [responseDelimited=false] Whether responses are length-delimited",
"@returns {" + escapeName(service.name) + "} RPC service. Useful where requests and/or responses are streamed."
]);
push(escapeName(service.name) + ".create = function create(rpcImpl, requestDelimited, responseDelimited) {");
++indent;
push("return new this(rpcImpl, requestDelimited, responseDelimited);");
--indent;
push("};");
}
service.methodsArray.forEach(function(method) {
method.resolve();
var lcName = protobuf.util.lcFirst(method.name),
cbName = escapeName(method.name + "Callback");
push("");
pushComment([
"Callback as used by {@link " + exportName(service) + "#" + escapeName(lcName) + "}.",
// This is a more specialized version of protobuf.rpc.ServiceCallback
"@memberof " + exportName(service),
"@typedef " + cbName,
"@type {function}",
"@param {Error|null} error Error, if any",
"@param {" + exportName(method.resolvedResponseType) + "} [response] " + method.resolvedResponseType.name
]);
push("");
pushComment([
method.comment || "Calls " + method.name + ".",
"@function " + lcName,
"@memberof " + exportName(service),
"@instance",
"@param {" + exportName(method.resolvedRequestType, !config.forceMessage) + "} request " + method.resolvedRequestType.name + " message or plain object",
"@param {" + exportName(service) + "." + cbName + "} callback Node-style callback called with the error, if any, and " + method.resolvedResponseType.name,
"@returns {undefined}",
"@variation 1"
]);
push("Object.defineProperty(" + escapeName(service.name) + ".prototype" + util.safeProp(lcName) + " = function " + escapeName(lcName) + "(request, callback) {");
++indent;
push("return this.rpcCall(" + escapeName(lcName) + ", $root." + exportName(method.resolvedRequestType) + ", $root." + exportName(method.resolvedResponseType) + ", request, callback);");
--indent;
push("}, \"name\", { value: " + JSON.stringify(method.name) + " });");
if (config.comments)
push("");
pushComment([
method.comment || "Calls " + method.name + ".",
"@function " + lcName,
"@memberof " + exportName(service),
"@instance",
"@param {" + exportName(method.resolvedRequestType, !config.forceMessage) + "} request " + method.resolvedRequestType.name + " message or plain object",
"@returns {Promise<" + exportName(method.resolvedResponseType) + ">} Promise",
"@variation 2"
]);
});
}
function buildEnum(ref, enm) {
push("");
var comment = [
enm.comment || enm.name + " enum.",
enm.parent instanceof protobuf.Root ? "@exports " + escapeName(enm.name) : "@name " + exportName(enm),
config.forceEnumString ? "@enum {string}" : "@enum {number}",
];
Object.keys(enm.values).forEach(function(key) {
var val = config.forceEnumString ? key : enm.values[key];
comment.push((config.forceEnumString ? "@property {string} " : "@property {number} ") + key + "=" + val + " " + (enm.comments[key] || key + " value"));
});
pushComment(comment);
if (!ref && config.es6)
push("export const " + escapeName(enm.name) + " = " + escapeName(ref) + "." + escapeName(enm.name) + " = (() => {");
else
push(escapeName(ref) + "." + escapeName(enm.name) + " = (function() {");
++indent;
push((config.es6 ? "const" : "var") + " valuesById = {}, values = Object.create(valuesById);");
var aliased = [];
Object.keys(enm.values).forEach(function(key) {
var valueId = enm.values[key];
var val = config.forceEnumString ? JSON.stringify(key) : valueId;
if (aliased.indexOf(valueId) > -1)
push("values[" + JSON.stringify(key) + "] = " + val + ";");
else {
push("values[valuesById[" + valueId + "] = " + JSON.stringify(key) + "] = " + val + ";");
aliased.push(valueId);
}
});
push("return values;");
--indent;
push("})();");
}

View file

@ -1,183 +0,0 @@
"use strict";
var fs = require("fs"),
path = require("path"),
child_process = require("child_process");
var semver;
try {
// installed as a peer dependency
require.resolve("protobufjs");
exports.pathToProtobufJs = "protobufjs";
} catch (e) {
// local development, i.e. forked from github
exports.pathToProtobufJs = "..";
}
var protobuf = require(exports.pathToProtobufJs);
function basenameCompare(a, b) {
var aa = String(a).replace(/\.\w+$/, "").split(/(-?\d*\.?\d+)/g),
bb = String(b).replace(/\.\w+$/, "").split(/(-?\d*\.?\d+)/g);
for (var i = 0, k = Math.min(aa.length, bb.length); i < k; i++) {
var x = parseFloat(aa[i]) || aa[i].toLowerCase(),
y = parseFloat(bb[i]) || bb[i].toLowerCase();
if (x < y)
return -1;
if (x > y)
return 1;
}
return a.length < b.length ? -1 : 0;
}
exports.requireAll = function requireAll(dirname) {
dirname = path.join(__dirname, dirname);
var files = fs.readdirSync(dirname).sort(basenameCompare),
all = {};
files.forEach(function(file) {
var basename = path.basename(file, ".js"),
extname = path.extname(file);
if (extname === ".js")
all[basename] = require(path.join(dirname, file));
});
return all;
};
exports.traverse = function traverse(current, fn) {
fn(current);
if (current.fieldsArray)
current.fieldsArray.forEach(function(field) {
traverse(field, fn);
});
if (current.oneofsArray)
current.oneofsArray.forEach(function(oneof) {
traverse(oneof, fn);
});
if (current.methodsArray)
current.methodsArray.forEach(function(method) {
traverse(method, fn);
});
if (current.nestedArray)
current.nestedArray.forEach(function(nested) {
traverse(nested, fn);
});
};
exports.traverseResolved = function traverseResolved(current, fn) {
fn(current);
if (current.resolvedType)
traverseResolved(current.resolvedType, fn);
if (current.resolvedKeyType)
traverseResolved(current.resolvedKeyType, fn);
if (current.resolvedRequestType)
traverseResolved(current.resolvedRequestType, fn);
if (current.resolvedResponseType)
traverseResolved(current.resolvedResponseType, fn);
};
exports.inspect = function inspect(object, indent) {
if (!object)
return "";
var chalk = require("chalk");
var sb = [];
if (!indent)
indent = "";
var ind = indent ? indent.substring(0, indent.length - 2) + "└ " : "";
sb.push(
ind + chalk.bold(object.toString()) + (object.visible ? " (visible)" : ""),
indent + chalk.gray("parent: ") + object.parent
);
if (object instanceof protobuf.Field) {
if (object.extend !== undefined)
sb.push(indent + chalk.gray("extend: ") + object.extend);
if (object.partOf)
sb.push(indent + chalk.gray("oneof : ") + object.oneof);
}
sb.push("");
if (object.fieldsArray)
object.fieldsArray.forEach(function(field) {
sb.push(inspect(field, indent + " "));
});
if (object.oneofsArray)
object.oneofsArray.forEach(function(oneof) {
sb.push(inspect(oneof, indent + " "));
});
if (object.methodsArray)
object.methodsArray.forEach(function(service) {
sb.push(inspect(service, indent + " "));
});
if (object.nestedArray)
object.nestedArray.forEach(function(nested) {
sb.push(inspect(nested, indent + " "));
});
return sb.join("\n");
};
function modExists(name, version) {
for (var i = 0; i < module.paths.length; ++i) {
try {
var pkg = JSON.parse(fs.readFileSync(path.join(module.paths[i], name, "package.json")));
return semver
? semver.satisfies(pkg.version, version)
: parseInt(pkg.version, 10) === parseInt(version.replace(/^[\^~]/, ""), 10); // used for semver only
} catch (e) {/**/}
}
return false;
}
function modInstall(install) {
child_process.execSync("npm --silent install " + (typeof install === "string" ? install : install.join(" ")), {
cwd: __dirname,
stdio: "ignore"
});
}
exports.setup = function() {
var pkg = require(path.join(__dirname, "..", "package.json"));
var version = pkg.dependencies["semver"] || pkg.devDependencies["semver"];
if (!modExists("semver", version)) {
process.stderr.write("installing semver@" + version + "\n");
modInstall("semver@" + version);
}
semver = require("semver"); // used from now on for version comparison
var install = [];
pkg.cliDependencies.forEach(function(name) {
if (name === "semver")
return;
version = pkg.dependencies[name] || pkg.devDependencies[name];
if (!modExists(name, version)) {
process.stderr.write("installing " + name + "@" + version + "\n");
install.push(name + "@" + version);
}
});
require("../scripts/postinstall"); // emit postinstall warning, if any
if (!install.length)
return;
modInstall(install);
};
exports.wrap = function(OUTPUT, options) {
var name = options.wrap || "default";
var wrap;
try {
// try built-in wrappers first
wrap = fs.readFileSync(path.join(__dirname, "wrappers", name + ".js")).toString("utf8");
} catch (e) {
// otherwise fetch the custom one
wrap = fs.readFileSync(path.resolve(process.cwd(), name)).toString("utf8");
}
wrap = wrap.replace(/\$DEPENDENCY/g, JSON.stringify(options.dependency || "protobufjs"));
wrap = wrap.replace(/( *)\$OUTPUT;/, function($0, $1) {
return $1.length ? OUTPUT.replace(/^/mg, $1) : OUTPUT;
});
if (options.lint !== "")
wrap = "/*" + options.lint + "*/\n" + wrap;
return wrap.replace(/\r?\n/g, "\n");
};
exports.pad = function(str, len, l) {
while (str.length < len)
str = l ? str + " " : " " + str;
return str;
};

View file

@ -1,7 +0,0 @@
define([$DEPENDENCY], function($protobuf) {
"use strict";
$OUTPUT;
return $root;
});

View file

@ -1,7 +0,0 @@
(function($protobuf) {
"use strict";
$OUTPUT;
return $root;
})(protobuf);

View file

@ -1,7 +0,0 @@
"use strict";
var $protobuf = require($DEPENDENCY);
$OUTPUT;
module.exports = $root;

View file

@ -1,15 +0,0 @@
(function(global, factory) { /* global define, require, module */
/* AMD */ if (typeof define === 'function' && define.amd)
define([$DEPENDENCY], factory);
/* CommonJS */ else if (typeof require === 'function' && typeof module === 'object' && module && module.exports)
module.exports = factory(require($DEPENDENCY));
})(this, function($protobuf) {
"use strict";
$OUTPUT;
return $root;
});

View file

@ -1,5 +0,0 @@
import * as $protobuf from $DEPENDENCY;
$OUTPUT;
export { $root as default };

File diff suppressed because it is too large Load diff

View file

@ -1,150 +0,0 @@
"use strict";
var path = require("path"),
fs = require("fs");
var gitSemverTags = require("git-semver-tags"),
gitRawCommits = require("git-raw-commits"),
minimist = require("minimist");
var basedir = path.join(__dirname, "..");
var pkg = require(basedir + "/package.json");
var argv = minimist(process.argv, {
alias: {
tag : "t",
write : "w"
},
string: [ "tag" ],
boolean: [ "write" ],
default: {
tag: null,
write: false
}
});
// categories to be used in the future and regexes for lazy / older subjects
var validCategories = {
"Breaking": null,
"Fixed": /fix|properly|prevent|correctly/i,
"New": /added|initial/i,
"CLI": /pbjs|pbts|CLI/,
"Docs": /README/i,
"Other": null
};
var breakingFallback = /removed|stripped|dropped/i;
var repo = "https://github.com/protobufjs/protobuf.js";
gitSemverTags(function(err, tags) {
if (err)
throw err;
var categories = {};
Object.keys(validCategories).forEach(function(category) {
categories[category] = [];
});
var output = [];
var from = tags[0];
var to = "HEAD";
var tag;
if (argv.tag) {
var idx = tags.indexOf(argv.tag);
if (idx < 0)
throw Error("no such tag: " + argv.tag);
from = tags[idx + 1];
tag = to = tags[idx];
} else
tag = pkg.version;
var commits = gitRawCommits({
from: from,
to: to,
merges: false,
format: "%B%n#%H"
});
commits.on("error", function(err) {
throw err;
});
commits.on("data", function(chunk) {
var message = chunk.toString("utf8").trim();
var match = /##([0-9a-f]{40})$/.exec(message);
var hash;
if (match) {
message = message.substring(0, message.length - match[1].length).trim();
hash = match[1];
}
message.split(";").forEach(function(message) {
if (/^(Merge pull request |Post-merge)/.test(message))
return;
var match = /^(\w+):/i.exec(message = message.trim());
var category;
if (match && match[1] in validCategories) {
category = match[1];
message = message.substring(match[1].length + 1).trim();
} else {
var keys = Object.keys(validCategories);
for (var i = 0; i < keys.length; ++i) {
var re = validCategories[keys[i]];
if (re && re.test(message)) {
category = keys[i];
break;
}
}
message = message.replace(/^(\w+):/i, "").trim();
}
if (!category) {
if (breakingFallback.test(message))
category = "Breaking";
else
category = "Other";
}
var nl = message.indexOf("\n");
if (nl > -1)
message = message.substring(0, nl).trim();
if (!hash || message.length < 12)
return;
message = message.replace(/\[ci skip\]/, "").trim();
categories[category].push({
text: message,
hash: hash
});
});
});
commits.on("end", function() {
output.push("## [" + tag + "](" + repo + "/releases/tag/" + tag + ")\n");
Object.keys(categories).forEach(function(category) {
var messages = categories[category];
if (!messages.length)
return;
output.push("\n### " + category + "\n");
messages.forEach(function(message) {
var text = message.text.replace(/#(\d+)/g, "[#$1](" + repo + "/issues/$1)");
output.push("[:hash:](" + repo + "/commit/" + message.hash + ") " + text + "<br />\n");
});
});
var current;
try {
current = fs.readFileSync(basedir + "/CHANGELOG.md").toString("utf8");
} catch (e) {
current = "";
}
var re = new RegExp("^## \\[" + tag + "\\]");
if (re.test(current)) { // regenerated, replace
var pos = current.indexOf("## [", 1);
if (pos > -1)
current = current.substring(pos).trim();
else
current = "";
}
var contents = output.join("") + "\n" + current;
if (argv.write)
fs.writeFileSync(basedir + "/CHANGELOG.md", contents, "utf8");
else
process.stdout.write(contents);
});
});

View file

@ -27,14 +27,6 @@ Contents
* [Using services](#using-services)
* [Usage with TypeScript](#usage-with-typescript)<br />
* [Command line](#command-line)<br />
How to use the command line utility.
* [pbjs for JavaScript](#pbjs-for-javascript)
* [pbts for TypeScript](#pbts-for-typescript)
* [Reflection vs. static code](#reflection-vs-static-code)
* [Command line API](#command-line-api)<br />
* [Additional documentation](#additional-documentation)<br />
A list of available documentation resources.
@ -60,6 +52,12 @@ $> npm install protobufjs [--save --save-prefix=~]
var protobuf = require("protobufjs");
```
The command line utility lives in the protobufjs-cli package and must be installed separately:
```
$> npm install protobufjs-cli [--save --save-prefix=~]
```
**Note** that this library's versioning scheme is not semver-compatible for historical reasons. For guaranteed backward compatibility, always depend on `~6.A.B` instead of `^6.A.B` (hence the `--save-prefix` above).
### Browsers
@ -67,16 +65,16 @@ var protobuf = require("protobufjs");
Development:
```
<script src="//cdn.rawgit.com/dcodeIO/protobuf.js/6.X.X/dist/protobuf.js"></script>
<script src="//cdn.jsdelivr.net/npm/protobufjs@7.X.X/dist/protobuf.js"></script>
```
Production:
```
<script src="//cdn.rawgit.com/dcodeIO/protobuf.js/6.X.X/dist/protobuf.min.js"></script>
<script src="//cdn.jsdelivr.net/npm/protobufjs@7.X.X/dist/protobuf.min.js"></script>
```
**Remember** to replace the version tag with the exact [release](https://github.com/dcodeIO/protobuf.js/tags) your project depends upon.
**Remember** to replace the version tag with the exact [release](https://github.com/protobufjs/protobuf.js/tags) your project depends upon.
The library supports CommonJS and AMD loaders and also exports globally as `protobuf`.
@ -84,7 +82,7 @@ The library supports CommonJS and AMD loaders and also exports globally as `prot
Where bundle size is a factor, there are additional stripped-down versions of the [full library][dist-full] (~19kb gzipped) available that exclude certain functionality:
* When working with JSON descriptors (i.e. generated by [pbjs](#pbjs-for-javascript)) and/or reflection only, see the [light library][dist-light] (~16kb gzipped) that excludes the parser. CommonJS entry point is:
* When working with JSON descriptors (i.e. generated by [pbjs](cli/README.md#pbjs-for-javascript)) and/or reflection only, see the [light library][dist-light] (~16kb gzipped) that excludes the parser. CommonJS entry point is:
```js
var protobuf = require("protobufjs/light");
@ -96,9 +94,11 @@ Where bundle size is a factor, there are additional stripped-down versions of th
var protobuf = require("protobufjs/minimal");
```
[dist-full]: https://github.com/dcodeIO/protobuf.js/tree/master/dist
[dist-light]: https://github.com/dcodeIO/protobuf.js/tree/master/dist/light
[dist-minimal]: https://github.com/dcodeIO/protobuf.js/tree/master/dist/minimal
| Distribution | Location
|------------|-----------------------------------
| Full | <https://cdn.jsdelivr.net/npm/protobufjs/dist/>
| Light | <https://cdn.jsdelivr.net/npm/protobufjs/dist/light/>
| Minimal | <https://cdn.jsdelivr.net/npm/protobufjs/dist/minimal/>
Usage
-----
@ -597,171 +597,6 @@ Other notes:
**ProTip!** Not as pretty, but you can [use decorators in plain JavaScript](https://github.com/dcodeIO/protobuf.js/blob/master/examples/js-decorators.js) as well.
Command line
------------
**Note** that moving the CLI to [its own package](./cli) is a work in progress. At the moment, it's still part of the main package.
The command line interface (CLI) can be used to translate between file formats and to generate static code as well as TypeScript definitions.
### pbjs for JavaScript
```
Translates between file formats and generates static code.
-t, --target Specifies the target format. Also accepts a path to require a custom target.
json JSON representation
json-module JSON representation as a module
proto2 Protocol Buffers, Version 2
proto3 Protocol Buffers, Version 3
static Static code without reflection (non-functional on its own)
static-module Static code without reflection as a module
-p, --path Adds a directory to the include path.
-o, --out Saves to a file instead of writing to stdout.
--sparse Exports only those types referenced from a main file (experimental).
Module targets only:
-w, --wrap Specifies the wrapper to use. Also accepts a path to require a custom wrapper.
default Default wrapper supporting both CommonJS and AMD
commonjs CommonJS wrapper
amd AMD wrapper
es6 ES6 wrapper (implies --es6)
closure A closure adding to protobuf.roots where protobuf is a global
-r, --root Specifies an alternative protobuf.roots name.
-l, --lint Linter configuration. Defaults to protobuf.js-compatible rules:
eslint-disable block-scoped-var, no-redeclare, no-control-regex, no-prototype-builtins
--es6 Enables ES6 syntax (const/let instead of var)
Proto sources only:
--keep-case Keeps field casing instead of converting to camel case.
Static targets only:
--no-create Does not generate create functions used for reflection compatibility.
--no-encode Does not generate encode functions.
--no-decode Does not generate decode functions.
--no-verify Does not generate verify functions.
--no-convert Does not generate convert functions like from/toObject
--no-delimited Does not generate delimited encode/decode functions.
--no-beautify Does not beautify generated code.
--no-comments Does not output any JSDoc comments.
--force-long Enforces the use of 'Long' for s-/u-/int64 and s-/fixed64 fields.
--force-number Enforces the use of 'number' for s-/u-/int64 and s-/fixed64 fields.
--force-message Enforces the use of message instances instead of plain objects.
usage: pbjs [options] file1.proto file2.json ... (or pipe) other | pbjs [options] -
```
For production environments it is recommended to bundle all your .proto files to a single .json file, which minimizes the number of network requests and avoids any parser overhead (hint: works with just the **light** library):
```
$> pbjs -t json file1.proto file2.proto > bundle.json
```
Now, either include this file in your final bundle:
```js
var root = protobuf.Root.fromJSON(require("./bundle.json"));
```
or load it the usual way:
```js
protobuf.load("bundle.json", function(err, root) {
...
});
```
Generated static code, on the other hand, works with just the **minimal** library. For example
```
$> pbjs -t static-module -w commonjs -o compiled.js file1.proto file2.proto
```
will generate static code for definitions within `file1.proto` and `file2.proto` to a CommonJS module `compiled.js`.
**ProTip!** Documenting your .proto files with `/** ... */`-blocks or (trailing) `/// ...` lines translates to generated static code.
### pbts for TypeScript
```
Generates TypeScript definitions from annotated JavaScript files.
-o, --out Saves to a file instead of writing to stdout.
-g, --global Name of the global object in browser environments, if any.
--no-comments Does not output any JSDoc comments.
Internal flags:
-n, --name Wraps everything in a module of the specified name.
-m, --main Whether building the main library without any imports.
usage: pbts [options] file1.js file2.js ... (or) other | pbts [options] -
```
Picking up on the example above, the following not only generates static code to a CommonJS module `compiled.js` but also its respective TypeScript definitions to `compiled.d.ts`:
```
$> pbjs -t static-module -w commonjs -o compiled.js file1.proto file2.proto
$> pbts -o compiled.d.ts compiled.js
```
Additionally, TypeScript definitions of static modules are compatible with their reflection-based counterparts (i.e. as exported by JSON modules), as long as the following conditions are met:
1. Instead of using `new SomeMessage(...)`, always use `SomeMessage.create(...)` because reflection objects do not provide a constructor.
2. Types, services and enums must start with an uppercase letter to become available as properties of the reflected types as well (i.e. to be able to use `MyMessage.MyEnum` instead of `root.lookup("MyMessage.MyEnum")`).
For example, the following generates a JSON module `bundle.js` and a `bundle.d.ts`, but no static code:
```
$> pbjs -t json-module -w commonjs -o bundle.js file1.proto file2.proto
$> pbjs -t static-module file1.proto file2.proto | pbts -o bundle.d.ts -
```
### Reflection vs. static code
While using .proto files directly requires the full library respectively pure reflection/JSON the light library, pretty much all code but the relatively short descriptors is shared.
Static code, on the other hand, requires just the minimal library, but generates additional source code without any reflection features. This also implies that there is a break-even point where statically generated code becomes larger than descriptor-based code once the amount of code generated exceeds the size of the full respectively light library.
There is no significant difference performance-wise as the code generated statically is pretty much the same as generated at runtime and both are largely interchangeable as seen in the previous section.
| Source | Library | Advantages | Tradeoffs
|--------|---------|------------|-----------
| .proto | full | Easily editable<br />Interoperability with other libraries<br />No compile step | Some parsing and possibly network overhead
| JSON | light | Easily editable<br />No parsing overhead<br />Single bundle (no network overhead) | protobuf.js specific<br />Has a compile step
| static | minimal | Works where `eval` access is restricted<br />Fully documented<br />Small footprint for small protos | Can be hard to edit<br />No reflection<br />Has a compile step
### Command line API
Both utilities can be used programmatically by providing command line arguments and a callback to their respective `main` functions:
```js
var pbjs = require("protobufjs/cli/pbjs"); // or require("protobufjs/cli").pbjs / .pbts
pbjs.main([ "--target", "json-module", "path/to/myproto.proto" ], function(err, output) {
if (err)
throw err;
// do something with output
});
```
Additional documentation
------------------------

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