pepr 0.4.2 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ src/cli/init/templates/data.json
package/dist/cli.js CHANGED
@@ -724,6 +724,22 @@ var import_client_node2 = require("@kubernetes/client-node");
724
724
  var import_util = require("util");
725
725
  var import_uuid = require("uuid");
726
726
 
727
+ // src/cli/init/templates/.eslintrc.json
728
+ var eslintrc_default = {
729
+ env: {
730
+ browser: false,
731
+ es2021: true
732
+ },
733
+ extends: ["eslint:recommended", "plugin:@typescript-eslint/recommended"],
734
+ parser: "@typescript-eslint/parser",
735
+ parserOptions: {
736
+ ecmaVersion: 2022
737
+ },
738
+ plugins: ["@typescript-eslint"],
739
+ ignorePatterns: ["node_modules", "dist", "hack"],
740
+ root: true
741
+ };
742
+
727
743
  // src/cli/init/templates/.prettierrc.json
728
744
  var prettierrc_default = {
729
745
  arrowParens: "avoid",
@@ -879,7 +895,7 @@ var gitIgnore = "# Ignore node_modules and Pepr build artifacts\nnode_modules\nd
879
895
  var readmeMd = '# Pepr Module\n\nThis is a Pepr Module. [Pepr](https://github.com/defenseunicorns/pepr) is a Kubernetes transformation system\nwritten in Typescript.\n\nThe `capabilities` directory contains all the capabilities for this module. By default,\na capability is a single typescript file in the format of `capability-name.ts` that is\nimported in the root `pepr.ts` file as `import { HelloPepr } from "./capabilities/hello-pepr";`.\nBecause this is typescript, you can organize this however you choose, e.g. creating a sub-folder\nper-capability or common logic in shared files or folders.\n\nExample Structure:\n\n```\nModule Root\n\u251C\u2500\u2500 package.json\n\u251C\u2500\u2500 pepr.ts\n\u2514\u2500\u2500 capabilities\n \u251C\u2500\u2500 example-one.ts\n \u251C\u2500\u2500 example-three.ts\n \u2514\u2500\u2500 example-two.ts\n```\n';
880
896
  var peprTS = 'import { Log, PeprModule } from "pepr";\n// cfg loads your pepr configuration from package.json\nimport cfg from "./package.json";\n\n// HelloPepr is a demo capability that is included with Pepr. Comment or delete the line below to remove it.\nimport { HelloPepr } from "./capabilities/hello-pepr";\n\n/**\n * This is the main entrypoint for this Pepr module. It is run when the module is started.\n * This is where you register your Pepr configurations and capabilities.\n */\nnew PeprModule(\n cfg,\n [\n // "HelloPepr" is a demo capability that is included with Pepr. Comment or delete the line below to remove it.\n HelloPepr,\n\n // Your additional capabilities go here\n ],\n {\n // Any actions you want to perform before the request is processed, including modifying the request.\n // Comment out or delete the line below to remove the default beforeHook.\n beforeHook: req => Log.debug(`beforeHook: ${req.uid}`),\n\n // Any actions you want to perform after the request is processed, including modifying the response.\n // Comment out or delete the line below to remove the default afterHook.\n afterHook: res => Log.debug(`afterHook: ${res.uid}`),\n }\n);\n';
881
897
  var helloPeprTS = 'import {\n Capability,\n PeprRequest,\n RegisterKind,\n a,\n fetch,\n fetchStatus,\n} from "pepr";\n\n/**\n * The HelloPepr Capability is an example capability to demonstrate some general concepts of Pepr.\n * To test this capability you can run `pepr dev` or `npm start` and then run the following command:\n * `kubectl apply -f capabilities/hello-pepr.samples.yaml`\n */\nexport const HelloPepr = new Capability({\n name: "hello-pepr",\n description: "A simple example capability to show how things work.",\n namespaces: ["pepr-demo", "pepr-demo-2"],\n});\n\n// Use the \'When\' function to create a new Capability Action\nconst { When } = HelloPepr;\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * CAPABILITY ACTION (Namespace) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This Capability Action removes the label `remove-me` when a Namespace is created.\n * Note we don\'t need to specify the namespace here, because we\'ve already specified\n * it in the Capability definition above.\n */\nWhen(a.Namespace)\n .IsCreated()\n .Then(ns => ns.RemoveLabel("remove-me"));\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * CAPABILITY ACTION (CM Example 1) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This is a single Capability Action. They can be in the same file or put imported from other files.\n * In this example, when a ConfigMap is created with the name `example-1`, then add a label and annotation.\n *\n * Equivalent to manually running:\n * `kubectl label configmap example-1 pepr=was-here`\n * `kubectl annotate configmap example-1 pepr.dev=annotations-work-too`\n */\nWhen(a.ConfigMap)\n .IsCreated()\n .WithName("example-1")\n .Then(request =>\n request\n .SetLabel("pepr", "was-here")\n .SetAnnotation("pepr.dev", "annotations-work-too")\n );\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * CAPABILITY ACTION (CM Example 2) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This Capability Action does the exact same changes for example-2, except this time it uses\n * the `.ThenSet()` feature. You can stack multiple `.Then()` calls, but only a single `.ThenSet()`\n */\nWhen(a.ConfigMap)\n .IsCreated()\n .WithName("example-2")\n .ThenSet({\n metadata: {\n labels: {\n pepr: "was-here",\n },\n annotations: {\n "pepr.dev": "annotations-work-too",\n },\n },\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * CAPABILITY ACTION (CM Example 3) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This Capability Action combines different styles. Unlike the previous actions, this one will look\n * for any ConfigMap in the `pepr-demo` namespace that has the label `change=by-label` during either\n * CREATE or UPDATE. Note that all conditions added such as `WithName()`, `WithLabel()`, `InNamespace()`,\n * are ANDs so all conditions must be true for the request to be processed.\n */\nWhen(a.ConfigMap)\n .IsCreatedOrUpdated()\n .WithLabel("change", "by-label")\n .Then(request => {\n // The K8s object e are going to mutate\n const cm = request.Raw;\n\n // Get the username and uid of the K8s request\n const { username, uid } = request.Request.userInfo;\n\n // Store some data about the request in the configmap\n cm.data["username"] = username;\n cm.data["uid"] = uid;\n\n // You can still mix other ways of making changes too\n request.SetAnnotation("pepr.dev", "making-waves");\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * CAPABILITY ACTION (CM Example 4) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This Capability Action show how you can use the `Then()` function to make multiple changes to the\n * same object from different functions. This is useful if you want to keep your Capability Actions\n * small and focused on a single task, or if you want to reuse the same function in multiple\n * Capability Actions.\n *\n * Note that the order of the `.Then()` calls matters. The first call will be executed first,\n * then the second, and so on. Also note the functions are not called until the Capability Action\n * is triggered.\n */\nWhen(a.ConfigMap)\n .IsCreated()\n .WithName("example-4")\n .Then(cm => cm.SetLabel("pepr.dev/first", "true"))\n .Then(addSecond)\n .Then(addThird);\n\n//This function uses the complete type definition, but is not required.\nfunction addSecond(cm: PeprRequest<a.ConfigMap>) {\n cm.SetLabel("pepr.dev/second", "true");\n}\n\n// This function has no type definition, so you won\'t have intellisense in the function body.\nfunction addThird(cm) {\n cm.SetLabel("pepr.dev/third", "true");\n}\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * CAPABILITY ACTION (CM Example 4a) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This is the same as Example 4, except this only operates on a CM in the `pepr-demo-2` namespace.\n * Note because the Capability defines namespaces, the namespace specified here must be one of those.\n * Alternatively, you can remove the namespace from the Capability definition and specify it here.\n */\nWhen(a.ConfigMap)\n .IsCreated()\n .InNamespace("pepr-demo-2")\n .WithName("example-4a")\n .Then(cm => cm.SetLabel("pepr.dev/first", "true"))\n .Then(addSecond)\n .Then(addThird);\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * CAPABILITY ACTION (CM Example 5) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This Capability Action is a bit more complex. It will look for any ConfigMap in the `pepr-demo`\n * namespace that has the label `chuck-norris` during CREATE. When it finds one, it will fetch a\n * random Chuck Norris joke from the API and add it to the ConfigMap. This is a great example of how\n * you can use Pepr to make changes to your K8s objects based on external data.\n *\n * Note the use of the `async` keyword. This is required for any Capability Action that uses `await` or `fetch()`.\n *\n * Also note we are passing a type to the `fetch()` function. This is optional, but it will help you\n * avoid mistakes when working with the data returned from the API. You can also use the `as` keyword to\n * cast the data returned from the API.\n *\n * These are equivalent:\n * ```ts\n * const joke = await fetch<TheChuckNorrisJoke>("https://api.chucknorris.io/jokes/random?category=dev");\n * const joke = await fetch("https://api.chucknorris.io/jokes/random?category=dev") as TheChuckNorrisJoke;\n * ```\n *\n * Alternatively, you can drop the type completely:\n *\n * ```ts\n * fetch("https://api.chucknorris.io/jokes/random?category=dev")\n * ```\n */\ninterface TheChuckNorrisJoke {\n icon_url: string;\n id: string;\n url: string;\n value: string;\n}\n\nWhen(a.ConfigMap)\n .IsCreated()\n .WithLabel("chuck-norris")\n .Then(async change => {\n // Try/catch is not needed as a response object will always be returned\n const response = await fetch<TheChuckNorrisJoke>(\n "https://api.chucknorris.io/jokes/random?category=dev"\n );\n\n // Instead, check the `response.ok` field\n if (response.ok) {\n // Add the Chuck Norris joke to the configmap\n change.Raw.data["chuck-says"] = response.data.value;\n return;\n }\n\n // You can also assert on different HTTP response codes\n if (response.status === fetchStatus.NOT_FOUND) {\n // Do something else\n return;\n }\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * CAPABILITY ACTION (Untyped Custom Resource) *\n * ---------------------------------------------------------------------------------------------------\n *\n * Out of the box, Pepr supports all the standard Kubernetes objects. However, you can also create\n * your own types. This is useful if you are working with an Operator that creates custom resources.\n * There are two ways to do this, the first is to use the `When()` function with a `GenericKind`,\n * the second is to create a new class that extends `GenericKind` and use the `RegisterKind()` function.\n *\n * This example shows how to use the `When()` function with a `GenericKind`. Note that you\n * must specify the `group`, `version`, and `kind` of the object (if applicable). This is how Pepr knows\n * if the Capability Action should be triggered or not. Since we are using a `GenericKind`,\n * Pepr will not be able to provide any intellisense for the object, so you will need to refer to the\n * Kubernetes API documentation for the object you are working with.\n *\n * You will need ot wait for the CRD in `hello-pepr.samples.yaml` to be created, then you can apply\n *\n * ```yaml\n * apiVersion: pepr.dev/v1\n * kind: Unicorn\n * metadata:\n * name: example-1\n * namespace: pepr-demo\n * spec:\n * message: replace-me\n * counter: 0\n * ```\n */\nWhen(a.GenericKind, {\n group: "pepr.dev",\n version: "v1",\n kind: "Unicorn",\n})\n .IsCreated()\n .WithName("example-1")\n .ThenSet({\n spec: {\n message: "Hello Pepr without type data!",\n counter: Math.random(),\n },\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * CAPABILITY ACTION (Typed Custom Resource) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This example shows how to use the `RegisterKind()` function to create a new type. This is useful\n * if you are working with an Operator that creates custom resources and you want to have intellisense\n * for the object. Note that you must specify the `group`, `version`, and `kind` of the object (if applicable)\n * as this is how Pepr knows if the Capability Action should be triggered or not.\n *\n * Once you register a new Kind with Pepr, you can use the `When()` function with the new Kind. Ideally,\n * you should register custom Kinds at the top of your Capability file or Pepr Module so they are available\n * to all Capability Actions, but we are putting it here for demonstration purposes.\n *\n * You will need ot wait for the CRD in `hello-pepr.samples.yaml` to be created, then you can apply\n *\n * ```yaml\n * apiVersion: pepr.dev/v1\n * kind: Unicorn\n * metadata:\n * name: example-2\n * namespace: pepr-demo\n * spec:\n * message: replace-me\n * counter: 0\n * ```*\n */\nclass UnicornKind extends a.GenericKind {\n spec: {\n /**\n * JSDoc comments can be added to explain more details about the field.\n *\n * @example\n * ```ts\n * request.Raw.spec.message = "Hello Pepr!";\n * ```\n * */\n message: string;\n counter: number;\n };\n}\n\nRegisterKind(UnicornKind, {\n group: "pepr.dev",\n version: "v1",\n kind: "Unicorn",\n});\n\nWhen(UnicornKind)\n .IsCreated()\n .WithName("example-2")\n .ThenSet({\n spec: {\n message: "Hello Pepr now with type data!",\n counter: Math.random(),\n },\n });\n';
882
- var packageJSON = { name: "pepr", description: "Kubernetes application engine", author: "Defense Unicorns", homepage: "https://github.com/defenseunicorns/pepr", license: "Apache-2.0", bin: "dist/cli.js", repository: "defenseunicorns/pepr", engines: { node: ">=18.0.0" }, version: "0.4.2", main: "dist/lib.js", types: "dist/lib.d.ts", scripts: { prebuild: "rm -fr dist/* && node hack/build-template-data.js", build: "tsc && node build.mjs", test: "npm run test:unit && npm run test:e2e", "test:unit": "npm run build && tsc -p tsconfig.tests.json && ava dist/**/*.test.js", "test:e2e": "npm run test:e2e:k3d && npm run test:e2e:build && npm run test:e2e:image && npm run test:e2e:run", "test:e2e:k3d": "k3d cluster delete pepr-dev && k3d cluster create pepr-dev --k3s-arg '--debug@server:0'", "test:e2e:build": "npm run build && npm pack && npm uninstall pepr -g && npm install -g pepr-0.0.0-development.tgz && pepr", "test:e2e:image": "docker buildx build --tag pepr:dev . && k3d image import pepr:dev -c pepr-dev", "test:e2e:run": "ava hack/e2e.test.mjs --sequential --timeout=2m", "format:check": "eslint src && prettier src --check", "format:fix": "eslint src --fix && prettier src --write" }, dependencies: { "@kubernetes/client-node": "0.18.1", express: "4.18.2", "fast-json-patch": "3.1.1", "http-status-codes": "2.2.0", "node-fetch": "2.6.11", ramda: "0.29.0" }, devDependencies: { "@types/express": "4.17.17", "@types/node-fetch": "2.6.4", "@types/node-forge": "1.3.2", "@types/prompts": "2.4.4", "@types/ramda": "0.29.1", "@types/uuid": "9.0.1", "@typescript-eslint/eslint-plugin": "5.59.7", "@typescript-eslint/parser": "5.59.7", ava: "5.2.0", eslint: "8.41.0", nock: "13.3.1", prettier: "2.8.8" }, peerDependencies: { commander: "10.0.1", esbuild: "0.17.19", "node-forge": "1.3.1", prompts: "2.4.2", typescript: "5.0.4", uuid: "9.0.0" }, ava: { failFast: true, verbose: true } };
898
+ var packageJSON = { name: "pepr", description: "Kubernetes application engine", author: "Defense Unicorns", homepage: "https://github.com/defenseunicorns/pepr", license: "Apache-2.0", bin: "dist/cli.js", repository: "defenseunicorns/pepr", engines: { node: ">=18.0.0" }, version: "0.5.0", main: "dist/lib.js", types: "dist/lib.d.ts", scripts: { prebuild: "rm -fr dist/* && node hack/build-template-data.js", build: "tsc && node build.mjs", test: "npm run test:unit && npm run test:e2e", "test:unit": "npm run build && tsc -p tsconfig.tests.json && ava dist/**/*.test.js", "test:e2e": "npm run test:e2e:k3d && npm run test:e2e:build && npm run test:e2e:image && npm run test:e2e:run", "test:e2e:k3d": "k3d cluster delete pepr-dev && k3d cluster create pepr-dev --k3s-arg '--debug@server:0'", "test:e2e:build": "npm run build && npm pack && npm uninstall pepr -g && npm install -g pepr-0.0.0-development.tgz && pepr", "test:e2e:image": "docker buildx build --tag pepr:dev . && k3d image import pepr:dev -c pepr-dev", "test:e2e:run": "ava hack/e2e.test.mjs --sequential --timeout=2m", "format:check": "eslint src && prettier src --check", "format:fix": "eslint src --fix && prettier src --write" }, dependencies: { "@kubernetes/client-node": "0.18.1", express: "4.18.2", "fast-json-patch": "3.1.1", "http-status-codes": "2.2.0", "node-fetch": "2.6.11", ramda: "0.29.0" }, devDependencies: { "@types/eslint": "8.40.0", "@types/express": "4.17.17", "@types/node-fetch": "2.6.4", "@types/node-forge": "1.3.2", "@types/prettier": "2.7.2", "@types/prompts": "2.4.4", "@types/ramda": "0.29.2", "@types/uuid": "9.0.1", ava: "5.3.0", nock: "13.3.1" }, peerDependencies: { "@typescript-eslint/eslint-plugin": "5.59.7", "@typescript-eslint/parser": "5.59.7", commander: "10.0.1", esbuild: "0.17.19", eslint: "8.41.0", "node-forge": "1.3.1", prettier: "2.8.8", prompts: "2.4.2", typescript: "5.0.4", uuid: "9.0.0" }, ava: { failFast: true, verbose: true } };
883
899
 
884
900
  // src/cli/init/templates/pepr.code-snippets.json
885
901
  var pepr_code_snippets_default = {
@@ -907,6 +923,10 @@ var pepr_code_snippets_default = {
907
923
  // src/cli/init/templates/tsconfig.module.json
908
924
  var tsconfig_module_default = {
909
925
  compilerOptions: {
926
+ allowSyntheticDefaultImports: true,
927
+ declaration: true,
928
+ declarationMap: true,
929
+ emitDeclarationOnly: true,
910
930
  esModuleInterop: true,
911
931
  lib: ["ES2022"],
912
932
  module: "CommonJS",
@@ -953,7 +973,6 @@ function genPkgJSON(opts, pgkVerOverride) {
953
973
  const uuid = (0, import_uuid.v5)(opts.name, (0, import_uuid.v4)());
954
974
  const name = sanitizeName(opts.name);
955
975
  const { typescript } = peerDependencies;
956
- const { prettier: prettier2 } = devDependencies;
957
976
  const data = {
958
977
  name,
959
978
  version: "0.0.1",
@@ -978,7 +997,6 @@ function genPkgJSON(opts, pgkVerOverride) {
978
997
  pepr: pgkVerOverride || `${version}`
979
998
  },
980
999
  devDependencies: {
981
- prettier: prettier2,
982
1000
  typescript
983
1001
  }
984
1002
  };
@@ -1022,11 +1040,20 @@ var prettier = {
1022
1040
  path: ".prettierrc",
1023
1041
  data: prettierrc_default
1024
1042
  };
1043
+ var eslint = {
1044
+ path: ".eslintrc.json",
1045
+ data: eslintrc_default
1046
+ };
1025
1047
 
1026
1048
  // src/cli/build.ts
1049
+ var peprTS2 = "pepr.ts";
1027
1050
  function build_default(program2) {
1028
- program2.command("build").description("Build a Pepr Module for deployment").action(async () => {
1029
- const { cfg, path, uuid } = await buildModule();
1051
+ program2.command("build").description("Build a Pepr Module for deployment").option(
1052
+ "-e, --entry-point [file]",
1053
+ "Specify the entry point file to build with. Note that changing this disables embedding of NPM packages.",
1054
+ peprTS2
1055
+ ).action(async (opts) => {
1056
+ const { cfg, path, uuid } = await buildModule(void 0, opts.entryPoint);
1030
1057
  const code = await import_fs2.promises.readFile(path);
1031
1058
  const webhook = new Webhook({
1032
1059
  ...cfg.pepr,
@@ -1045,9 +1072,9 @@ function build_default(program2) {
1045
1072
  }
1046
1073
  var externalLibs = Object.keys(dependencies);
1047
1074
  externalLibs.push("pepr");
1048
- async function loadModule() {
1075
+ async function loadModule(entryPoint = peprTS2) {
1049
1076
  const cfgPath = (0, import_path.resolve)(".", "package.json");
1050
- const input = (0, import_path.resolve)(".", "pepr.ts");
1077
+ const input = (0, import_path.resolve)(".", entryPoint);
1051
1078
  try {
1052
1079
  await import_fs2.promises.access(cfgPath);
1053
1080
  await import_fs2.promises.access(input);
@@ -1079,21 +1106,24 @@ async function loadModule() {
1079
1106
  uuid
1080
1107
  };
1081
1108
  }
1082
- async function buildModule(reloader) {
1109
+ async function buildModule(reloader, entryPoint = peprTS2) {
1083
1110
  try {
1084
- const { cfg, path, uuid } = await loadModule();
1111
+ const { cfg, path, uuid } = await loadModule(entryPoint);
1085
1112
  (0, import_child_process.execSync)("./node_modules/.bin/tsc", { stdio: "inherit" });
1113
+ const customEntryPoint = entryPoint !== peprTS2;
1086
1114
  const ctx = await (0, import_esbuild.context)({
1087
1115
  bundle: true,
1088
- entryPoints: ["pepr.ts"],
1116
+ entryPoints: [entryPoint],
1089
1117
  external: externalLibs,
1090
1118
  format: "cjs",
1091
1119
  keepNames: true,
1092
1120
  legalComments: "external",
1093
1121
  metafile: true,
1094
- // Only minify the code if we're not in dev mode
1095
- minify: !reloader,
1122
+ // Only minify the code if we're not in dev mode and we're not using a custom entry point
1123
+ minify: !reloader && !customEntryPoint,
1096
1124
  outfile: path,
1125
+ // Only bundle the NPM packages if we're not using a custom entry point
1126
+ packages: customEntryPoint ? "external" : void 0,
1097
1127
  plugins: [
1098
1128
  {
1099
1129
  name: "reload-server",
@@ -1112,7 +1142,8 @@ async function buildModule(reloader) {
1112
1142
  platform: "node",
1113
1143
  // Only generate a sourcemap if we're in dev mode
1114
1144
  sourcemap: !!reloader,
1115
- treeShaking: true
1145
+ // Only tree shake the code if we're not using a custom entry point
1146
+ treeShaking: !customEntryPoint
1116
1147
  });
1117
1148
  if (reloader) {
1118
1149
  await ctx.watch();
@@ -1228,13 +1259,62 @@ function dev_default(program2) {
1228
1259
  });
1229
1260
  }
1230
1261
 
1262
+ // src/cli/format.ts
1263
+ var import_eslint = require("eslint");
1264
+ var import_fs5 = require("fs");
1265
+ var import_prettier = require("prettier");
1266
+ function format_default(program2) {
1267
+ program2.command("format").description("Lint and format this Pepr module").option("-v, --validate-only", "Do not modify files, only validate formatting").action(async (opts) => {
1268
+ try {
1269
+ const eslint2 = new import_eslint.ESLint();
1270
+ const results = await eslint2.lintFiles(["./**/*.ts"]);
1271
+ let hasFailure = false;
1272
+ results.forEach(async (result) => {
1273
+ const errorCount = result.fatalErrorCount + result.errorCount;
1274
+ if (errorCount > 0) {
1275
+ hasFailure = true;
1276
+ }
1277
+ });
1278
+ const formatter = await eslint2.loadFormatter("stylish");
1279
+ const resultText = await formatter.format(results);
1280
+ if (resultText) {
1281
+ console.log(resultText);
1282
+ }
1283
+ if (!opts.validateOnly) {
1284
+ await import_eslint.ESLint.outputFixes(results);
1285
+ }
1286
+ for (const { filePath } of results) {
1287
+ const content = await import_fs5.promises.readFile(filePath, "utf8");
1288
+ const cfg = await (0, import_prettier.resolveConfig)(filePath);
1289
+ const formatted = (0, import_prettier.format)(content, { filepath: filePath, ...cfg });
1290
+ if (opts.validateOnly) {
1291
+ if (formatted !== content) {
1292
+ hasFailure = true;
1293
+ logger_default.error(`File ${filePath} is not formatted correctly`);
1294
+ }
1295
+ } else {
1296
+ await import_fs5.promises.writeFile(filePath, formatted);
1297
+ }
1298
+ }
1299
+ if (opts.validateOnly && hasFailure) {
1300
+ process.exit(1);
1301
+ }
1302
+ logger_default.info("Module formatted");
1303
+ } catch (e) {
1304
+ logger_default.debug(e);
1305
+ logger_default.error(e.message);
1306
+ process.exit(1);
1307
+ }
1308
+ });
1309
+ }
1310
+
1231
1311
  // src/cli/init/index.ts
1232
1312
  var import_child_process3 = require("child_process");
1233
1313
  var import_path2 = require("path");
1234
1314
  var import_prompts4 = __toESM(require("prompts"));
1235
1315
 
1236
1316
  // src/cli/init/walkthrough.ts
1237
- var import_fs5 = require("fs");
1317
+ var import_fs6 = require("fs");
1238
1318
  var import_prompts3 = __toESM(require("prompts"));
1239
1319
 
1240
1320
  // src/lib/types.ts
@@ -1254,7 +1334,7 @@ function walkthrough() {
1254
1334
  validate: async (val) => {
1255
1335
  try {
1256
1336
  const name = sanitizeName(val);
1257
- await import_fs5.promises.access(name, import_fs5.promises.constants.F_OK);
1337
+ await import_fs6.promises.access(name, import_fs6.promises.constants.F_OK);
1258
1338
  return "A directory with this name already exists";
1259
1339
  } catch (e) {
1260
1340
  return val.length > 2 || "The name must be at least 3 characters long";
@@ -1297,10 +1377,12 @@ async function confirm(dirName, packageJSON2, peprTSPath) {
1297
1377
  To be generated:
1298
1378
 
1299
1379
  \x1B[1m${dirName}\x1B[0m
1380
+ \u251C\u2500\u2500 \x1B[1m${eslint.path}\x1B[0m
1300
1381
  \u251C\u2500\u2500 \x1B[1m${gitignore.path}\x1B[0m
1301
1382
  \u251C\u2500\u2500 \x1B[1m${prettier.path}\x1B[0m
1302
1383
  \u251C\u2500\u2500 \x1B[1mcapabilties\x1B[0m
1303
- | \u2514\u2500\u2500 \x1B[1mhello-pepr.ts\x1B[0m
1384
+ \u2502 \u251C\u2500\u2500 \x1B[1mhello-pepr.samples.yaml\x1B[0m
1385
+ \u2502 \u2514\u2500\u2500 \x1B[1mhello-pepr.ts\x1B[0m
1304
1386
  \u251C\u2500\u2500 \x1B[1m${packageJSON2.path}\x1B[0m
1305
1387
  ${packageJSON2.print.replace(/^/gm, " \u2502 ")}
1306
1388
  \u251C\u2500\u2500 \x1B[1m${peprTSPath}\x1B[0m
@@ -1326,8 +1408,8 @@ function init_default(program2) {
1326
1408
  const response = await walkthrough();
1327
1409
  const dirName = sanitizeName(response.name);
1328
1410
  const packageJSON2 = genPkgJSON(response, pkgOverride);
1329
- const peprTS2 = genPeprTS();
1330
- const confirmed = await confirm(dirName, packageJSON2, peprTS2.path);
1411
+ const peprTS3 = genPeprTS();
1412
+ const confirmed = await confirm(dirName, packageJSON2, peprTS3.path);
1331
1413
  if (confirmed) {
1332
1414
  console.log("Creating new Pepr module...");
1333
1415
  try {
@@ -1335,11 +1417,12 @@ function init_default(program2) {
1335
1417
  await createDir((0, import_path2.resolve)(dirName, ".vscode"));
1336
1418
  await createDir((0, import_path2.resolve)(dirName, "capabilities"));
1337
1419
  await write((0, import_path2.resolve)(dirName, gitignore.path), gitignore.data);
1420
+ await write((0, import_path2.resolve)(dirName, eslint.path), eslint.data);
1338
1421
  await write((0, import_path2.resolve)(dirName, prettier.path), prettier.data);
1339
1422
  await write((0, import_path2.resolve)(dirName, packageJSON2.path), packageJSON2.data);
1340
1423
  await write((0, import_path2.resolve)(dirName, readme.path), readme.data);
1341
1424
  await write((0, import_path2.resolve)(dirName, tsConfig.path), tsConfig.data);
1342
- await write((0, import_path2.resolve)(dirName, peprTS2.path), peprTS2.data);
1425
+ await write((0, import_path2.resolve)(dirName, peprTS3.path), peprTS3.data);
1343
1426
  await write((0, import_path2.resolve)(dirName, ".vscode", snippet.path), snippet.data);
1344
1427
  await write((0, import_path2.resolve)(dirName, "capabilities", samplesYaml.path), samplesYaml.data);
1345
1428
  await write((0, import_path2.resolve)(dirName, "capabilities", helloPepr.path), helloPepr.data);
@@ -1389,7 +1472,7 @@ var import_child_process4 = require("child_process");
1389
1472
  var import_path3 = require("path");
1390
1473
  var import_prompts5 = __toESM(require("prompts"));
1391
1474
  function update_default(program2) {
1392
- program2.command("update").description("Update this Pepr module").option("--skip-template-update", "Skip updating the template files`").action(async (opts) => {
1475
+ program2.command("update").description("Update this Pepr module").option("--skip-template-update", "Skip updating the template files").action(async (opts) => {
1393
1476
  if (!opts.skipTemplateUpdate) {
1394
1477
  const { confirm: confirm2 } = await (0, import_prompts5.default)({
1395
1478
  type: "confirm",
@@ -1402,11 +1485,13 @@ function update_default(program2) {
1402
1485
  }
1403
1486
  console.log("Updating the Pepr module...");
1404
1487
  try {
1405
- await write((0, import_path3.resolve)(prettier.path), prettier.data);
1406
- await write((0, import_path3.resolve)(tsConfig.path), tsConfig.data);
1407
- await write((0, import_path3.resolve)(".vscode", snippet.path), snippet.data);
1408
- await write((0, import_path3.resolve)("capabilities", samplesYaml.path), samplesYaml.data);
1409
- await write((0, import_path3.resolve)("capabilities", helloPepr.path), helloPepr.data);
1488
+ if (!opts.skipTemplateUpdate) {
1489
+ await write((0, import_path3.resolve)(prettier.path), prettier.data);
1490
+ await write((0, import_path3.resolve)(tsConfig.path), tsConfig.data);
1491
+ await write((0, import_path3.resolve)(".vscode", snippet.path), snippet.data);
1492
+ await write((0, import_path3.resolve)("capabilities", samplesYaml.path), samplesYaml.data);
1493
+ await write((0, import_path3.resolve)("capabilities", helloPepr.path), helloPepr.data);
1494
+ }
1410
1495
  (0, import_child_process4.execSync)("npm install pepr@latest", {
1411
1496
  stdio: "inherit"
1412
1497
  });
@@ -1437,4 +1522,5 @@ build_default(program);
1437
1522
  deploy_default(program);
1438
1523
  dev_default(program);
1439
1524
  update_default(program);
1525
+ format_default(program);
1440
1526
  program.parse();
@@ -23,7 +23,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
23
23
  mod
24
24
  ));
25
25
 
26
- // src/cli/run.ts
26
+ // src/runtime/controller.ts
27
27
  var import_child_process = require("child_process");
28
28
  var import_crypto = __toESM(require("crypto"));
29
29
  var import_fs = __toESM(require("fs"));
@@ -116,9 +116,9 @@ if (process.env.LOG_LEVEL) {
116
116
  var logger_default = Log;
117
117
 
118
118
  // src/cli/init/templates/data.json
119
- var packageJSON = { name: "pepr", description: "Kubernetes application engine", author: "Defense Unicorns", homepage: "https://github.com/defenseunicorns/pepr", license: "Apache-2.0", bin: "dist/cli.js", repository: "defenseunicorns/pepr", engines: { node: ">=18.0.0" }, version: "0.4.2", main: "dist/lib.js", types: "dist/lib.d.ts", scripts: { prebuild: "rm -fr dist/* && node hack/build-template-data.js", build: "tsc && node build.mjs", test: "npm run test:unit && npm run test:e2e", "test:unit": "npm run build && tsc -p tsconfig.tests.json && ava dist/**/*.test.js", "test:e2e": "npm run test:e2e:k3d && npm run test:e2e:build && npm run test:e2e:image && npm run test:e2e:run", "test:e2e:k3d": "k3d cluster delete pepr-dev && k3d cluster create pepr-dev --k3s-arg '--debug@server:0'", "test:e2e:build": "npm run build && npm pack && npm uninstall pepr -g && npm install -g pepr-0.0.0-development.tgz && pepr", "test:e2e:image": "docker buildx build --tag pepr:dev . && k3d image import pepr:dev -c pepr-dev", "test:e2e:run": "ava hack/e2e.test.mjs --sequential --timeout=2m", "format:check": "eslint src && prettier src --check", "format:fix": "eslint src --fix && prettier src --write" }, dependencies: { "@kubernetes/client-node": "0.18.1", express: "4.18.2", "fast-json-patch": "3.1.1", "http-status-codes": "2.2.0", "node-fetch": "2.6.11", ramda: "0.29.0" }, devDependencies: { "@types/express": "4.17.17", "@types/node-fetch": "2.6.4", "@types/node-forge": "1.3.2", "@types/prompts": "2.4.4", "@types/ramda": "0.29.1", "@types/uuid": "9.0.1", "@typescript-eslint/eslint-plugin": "5.59.7", "@typescript-eslint/parser": "5.59.7", ava: "5.2.0", eslint: "8.41.0", nock: "13.3.1", prettier: "2.8.8" }, peerDependencies: { commander: "10.0.1", esbuild: "0.17.19", "node-forge": "1.3.1", prompts: "2.4.2", typescript: "5.0.4", uuid: "9.0.0" }, ava: { failFast: true, verbose: true } };
119
+ var packageJSON = { name: "pepr", description: "Kubernetes application engine", author: "Defense Unicorns", homepage: "https://github.com/defenseunicorns/pepr", license: "Apache-2.0", bin: "dist/cli.js", repository: "defenseunicorns/pepr", engines: { node: ">=18.0.0" }, version: "0.5.0", main: "dist/lib.js", types: "dist/lib.d.ts", scripts: { prebuild: "rm -fr dist/* && node hack/build-template-data.js", build: "tsc && node build.mjs", test: "npm run test:unit && npm run test:e2e", "test:unit": "npm run build && tsc -p tsconfig.tests.json && ava dist/**/*.test.js", "test:e2e": "npm run test:e2e:k3d && npm run test:e2e:build && npm run test:e2e:image && npm run test:e2e:run", "test:e2e:k3d": "k3d cluster delete pepr-dev && k3d cluster create pepr-dev --k3s-arg '--debug@server:0'", "test:e2e:build": "npm run build && npm pack && npm uninstall pepr -g && npm install -g pepr-0.0.0-development.tgz && pepr", "test:e2e:image": "docker buildx build --tag pepr:dev . && k3d image import pepr:dev -c pepr-dev", "test:e2e:run": "ava hack/e2e.test.mjs --sequential --timeout=2m", "format:check": "eslint src && prettier src --check", "format:fix": "eslint src --fix && prettier src --write" }, dependencies: { "@kubernetes/client-node": "0.18.1", express: "4.18.2", "fast-json-patch": "3.1.1", "http-status-codes": "2.2.0", "node-fetch": "2.6.11", ramda: "0.29.0" }, devDependencies: { "@types/eslint": "8.40.0", "@types/express": "4.17.17", "@types/node-fetch": "2.6.4", "@types/node-forge": "1.3.2", "@types/prettier": "2.7.2", "@types/prompts": "2.4.4", "@types/ramda": "0.29.2", "@types/uuid": "9.0.1", ava: "5.3.0", nock: "13.3.1" }, peerDependencies: { "@typescript-eslint/eslint-plugin": "5.59.7", "@typescript-eslint/parser": "5.59.7", commander: "10.0.1", esbuild: "0.17.19", eslint: "8.41.0", "node-forge": "1.3.1", prettier: "2.8.8", prompts: "2.4.2", typescript: "5.0.4", uuid: "9.0.0" }, ava: { failFast: true, verbose: true } };
120
120
 
121
- // src/cli/run.ts
121
+ // src/runtime/controller.ts
122
122
  var { version } = packageJSON;
123
123
  function validateHash(expectedHash) {
124
124
  if (!expectedHash || expectedHash.length !== 64) {
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ export {};
3
+ //# sourceMappingURL=controller.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"controller.d.ts","sourceRoot":"","sources":["../../src/runtime/controller.ts"],"names":[],"mappings":""}
package/package.json CHANGED
@@ -9,7 +9,7 @@
9
9
  "engines": {
10
10
  "node": ">=18.0.0"
11
11
  },
12
- "version": "0.4.2",
12
+ "version": "0.5.0",
13
13
  "main": "dist/lib.js",
14
14
  "types": "dist/lib.d.ts",
15
15
  "scripts": {
@@ -34,23 +34,25 @@
34
34
  "ramda": "0.29.0"
35
35
  },
36
36
  "devDependencies": {
37
+ "@types/eslint": "8.40.0",
37
38
  "@types/express": "4.17.17",
38
39
  "@types/node-fetch": "2.6.4",
39
40
  "@types/node-forge": "1.3.2",
41
+ "@types/prettier": "2.7.2",
40
42
  "@types/prompts": "2.4.4",
41
- "@types/ramda": "0.29.1",
43
+ "@types/ramda": "0.29.2",
42
44
  "@types/uuid": "9.0.1",
43
- "@typescript-eslint/eslint-plugin": "5.59.7",
44
- "@typescript-eslint/parser": "5.59.7",
45
- "ava": "5.2.0",
46
- "eslint": "8.41.0",
47
- "nock": "13.3.1",
48
- "prettier": "2.8.8"
45
+ "ava": "5.3.0",
46
+ "nock": "13.3.1"
49
47
  },
50
48
  "peerDependencies": {
49
+ "@typescript-eslint/eslint-plugin": "5.59.7",
50
+ "@typescript-eslint/parser": "5.59.7",
51
51
  "commander": "10.0.1",
52
52
  "esbuild": "0.17.19",
53
+ "eslint": "8.41.0",
53
54
  "node-forge": "1.3.1",
55
+ "prettier": "2.8.8",
54
56
  "prompts": "2.4.2",
55
57
  "typescript": "5.0.4",
56
58
  "uuid": "9.0.0"
package/src/cli.ts CHANGED
@@ -7,6 +7,7 @@ import { banner } from "./cli/banner";
7
7
  import build from "./cli/build";
8
8
  import deploy from "./cli/deploy";
9
9
  import dev from "./cli/dev";
10
+ import format from "./cli/format";
10
11
  import init from "./cli/init/index";
11
12
  import { version } from "./cli/init/templates";
12
13
  import { RootCmd } from "./cli/root";
@@ -29,6 +30,7 @@ build(program);
29
30
  deploy(program);
30
31
  dev(program);
31
32
  update(program);
33
+ format(program);
32
34
 
33
35
  // @todo: finish/re-evaluate these commands
34
36
  // test(program);
@@ -0,0 +1,71 @@
1
+ #!/usr/bin/env node
2
+
3
+ // SPDX-License-Identifier: Apache-2.0
4
+ // SPDX-FileCopyrightText: 2023-Present The Pepr Authors
5
+
6
+ import { fork } from "child_process";
7
+ import crypto from "crypto";
8
+ import fs from "fs";
9
+ import { gunzipSync } from "zlib";
10
+
11
+ import Log from "../lib/logger";
12
+ import { packageJSON } from "../cli/init/templates/data.json";
13
+
14
+ const { version } = packageJSON;
15
+
16
+ function validateHash(expectedHash: string) {
17
+ // Require the hash to be 64 characters long
18
+ if (!expectedHash || expectedHash.length !== 64) {
19
+ Log.error("Invalid hash");
20
+ process.exit(1);
21
+ }
22
+ }
23
+
24
+ function runModule(expectedHash: string) {
25
+ const gzPath = `/app/load/module-${expectedHash}.js.gz`;
26
+ const jsPath = `/app/module-${expectedHash}.js`;
27
+
28
+ // Set the log level
29
+ Log.SetLogLevel("debug");
30
+
31
+ // Check if the path is a valid file
32
+ if (!fs.existsSync(gzPath)) {
33
+ Log.error(`File not found: ${gzPath}`);
34
+ process.exit(1);
35
+ }
36
+
37
+ try {
38
+ Log.info(`Loading module ${gzPath}`);
39
+
40
+ // Extract the code from the file
41
+ const codeGZ = fs.readFileSync(gzPath);
42
+ const code = gunzipSync(codeGZ);
43
+
44
+ // Get the hash of the extracted code
45
+ const actualHash = crypto.createHash("sha256").update(code).digest("hex");
46
+
47
+ // If the hash doesn't match, exit
48
+ if (expectedHash !== actualHash) {
49
+ Log.error(`File hash does not match, expected ${expectedHash} but got ${actualHash}`);
50
+ process.exit(1);
51
+ }
52
+
53
+ Log.info(`File hash matches, running module`);
54
+
55
+ // Write the code to a file
56
+ fs.writeFileSync(jsPath, code);
57
+
58
+ // Run the module
59
+ fork(jsPath);
60
+ } catch (e) {
61
+ Log.error(`Failed to decompress module: ${e}`);
62
+ process.exit(1);
63
+ }
64
+ }
65
+
66
+ Log.info(`Pepr Controller (v${version})`);
67
+
68
+ const hash = process.argv[2];
69
+
70
+ validateHash(hash);
71
+ runModule(hash);