pepr 0.6.1 → 0.7.1

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.
package/README.md CHANGED
@@ -40,10 +40,20 @@ When(a.ConfigMap)
40
40
  });
41
41
  ```
42
42
 
43
+ ## Prerequisites
44
+
45
+ - [Node.js](https://nodejs.org/en/) v18.0.0+.
46
+
47
+ > _Recommend installing with [NVM](https://github.com/nvm-sh/nvm) or [NVM for Windows](https://github.com/coreybutler/nvm-windows) to avoid permission issues when installing the Pepr CLI globally._
48
+
49
+ - Recommended (optional) tools:
50
+ - [Visual Studio Code](https://code.visualstudio.com/) for inline debugging and [Pepr Capabilities](#capability) creation.
51
+ - A Kubernetes cluster for `pepr dev`. Pepr modules include `npm run k3d-setup` if you want to test locally with [K3d](https://k3d.io/) and [Docker](https://www.docker.com/).
52
+
43
53
  ## Wow too many words! tl;dr;
44
54
 
45
55
  ```bash
46
- # Install Pepr (you can also use npx)
56
+ # Install Pepr globally. If this command requires sudo, see the Prerequisites section to install Node.js with NVM or NVM for Windows.
47
57
  npm i -g pepr
48
58
 
49
59
  # Initialize a new Pepr Module
@@ -95,6 +105,7 @@ For example, a CapabilityAction could be responsible for adding a specific label
95
105
  See [CapabilityActions](./docs/actions.md) for more details.
96
106
 
97
107
  ## Logical Pepr Flow
108
+
98
109
  ![Module Diagram](./.images/modules.svg)
99
110
 
100
111
  ## TypeScript
package/dist/cli.js CHANGED
@@ -91,14 +91,17 @@ var banner = `\x1B[107;40m\x1B[38;5;016m \x1B[38;5;016m \x1B[38;5;016m \x1B[38;5
91
91
  \x1B[0m`;
92
92
 
93
93
  // src/cli/build.ts
94
+ var import_child_process2 = require("child_process");
94
95
  var import_esbuild = require("esbuild");
95
- var import_fs2 = require("fs");
96
+ var import_fs3 = require("fs");
96
97
  var import_path = require("path");
97
- var import_child_process = require("child_process");
98
98
 
99
99
  // src/lib/k8s/webhook.ts
100
100
  var import_client_node = require("@kubernetes/client-node");
101
+ var import_child_process = require("child_process");
101
102
  var import_crypto = __toESM(require("crypto"));
103
+ var import_fs = require("fs");
104
+ var import_ramda = require("ramda");
102
105
  var import_zlib = require("zlib");
103
106
 
104
107
  // src/lib/logger.ts
@@ -187,6 +190,14 @@ if (process.env.LOG_LEVEL) {
187
190
  }
188
191
  var logger_default = Log;
189
192
 
193
+ // src/lib/types.ts
194
+ var ErrorBehavior = /* @__PURE__ */ ((ErrorBehavior2) => {
195
+ ErrorBehavior2["ignore"] = "ignore";
196
+ ErrorBehavior2["audit"] = "audit";
197
+ ErrorBehavior2["reject"] = "reject";
198
+ return ErrorBehavior2;
199
+ })(ErrorBehavior || {});
200
+
190
201
  // src/lib/k8s/tls.ts
191
202
  var import_node_forge = __toESM(require("node-forge"));
192
203
  var caName = "Pepr Ephemeral CA";
@@ -338,7 +349,63 @@ var Webhook = class {
338
349
  }
339
350
  };
340
351
  }
341
- mutatingWebhook(timeoutSeconds = 10) {
352
+ generateWebhookRules(path) {
353
+ return new Promise((resolve4, reject) => {
354
+ const rules = [];
355
+ const defaultRule = {
356
+ apiGroups: ["*"],
357
+ apiVersions: ["*"],
358
+ operations: ["CREATE", "UPDATE", "DELETE"],
359
+ resources: ["*/*"]
360
+ };
361
+ const program2 = (0, import_child_process.fork)(path, {
362
+ env: {
363
+ ...process.env,
364
+ LOG_LEVEL: "warn",
365
+ PEPR_MODE: "build"
366
+ }
367
+ });
368
+ program2.on("message", (message) => {
369
+ const { capabilities } = message.valueOf();
370
+ for (const capability of capabilities) {
371
+ logger_default.info(`Module ${this.config.uuid} has capability: ${capability._name}`);
372
+ const { _bindings } = capability;
373
+ for (const binding of _bindings) {
374
+ const { event, kind } = binding;
375
+ const operations = [];
376
+ if (event === "CREATEORUPDATE" /* CreateOrUpdate */) {
377
+ operations.push("CREATE" /* Create */, "UPDATE" /* Update */);
378
+ } else {
379
+ operations.push(event);
380
+ }
381
+ const resource = kind.plural || `${kind.kind.toLowerCase()}s`;
382
+ rules.push({
383
+ apiGroups: [kind.group],
384
+ apiVersions: [kind.version || "*"],
385
+ operations,
386
+ resources: [resource]
387
+ });
388
+ }
389
+ }
390
+ });
391
+ program2.on("exit", (code) => {
392
+ if (code !== 0) {
393
+ reject(new Error(`Child process exited with code ${code}`));
394
+ } else {
395
+ if (rules.length < 1) {
396
+ resolve4([defaultRule]);
397
+ } else {
398
+ const reducedRules = (0, import_ramda.uniqWith)(import_ramda.equals, rules);
399
+ resolve4(reducedRules);
400
+ }
401
+ }
402
+ });
403
+ program2.on("error", (error) => {
404
+ reject(error);
405
+ });
406
+ });
407
+ }
408
+ async mutatingWebhook(path, timeoutSeconds = 10) {
342
409
  const { name } = this;
343
410
  const ignore = [peprIgnore];
344
411
  if (this.config.alwaysIgnore.namespaces && this.config.alwaysIgnore.namespaces.length > 0) {
@@ -360,6 +427,7 @@ var Webhook = class {
360
427
  path: "/mutate"
361
428
  };
362
429
  }
430
+ const rules = await this.generateWebhookRules(path);
363
431
  return {
364
432
  apiVersion: "admissionregistration.k8s.io/v1",
365
433
  kind: "MutatingWebhookConfiguration",
@@ -378,15 +446,7 @@ var Webhook = class {
378
446
  objectSelector: {
379
447
  matchExpressions: ignore
380
448
  },
381
- // @todo: make this configurable
382
- rules: [
383
- {
384
- apiGroups: ["*"],
385
- apiVersions: ["*"],
386
- operations: ["CREATE", "UPDATE", "DELETE"],
387
- resources: ["*/*"]
388
- }
389
- ],
449
+ rules,
390
450
  // @todo: track side effects state
391
451
  sideEffects: "None"
392
452
  }
@@ -581,8 +641,10 @@ var Webhook = class {
581
641
  };
582
642
  return (0, import_client_node.dumpYaml)(zarfCfg, { noRefs: true });
583
643
  }
584
- allYaml(code) {
644
+ async allYaml(path) {
645
+ const code = await import_fs.promises.readFile(path);
585
646
  const hash = import_crypto.default.createHash("sha256").update(code).digest("hex");
647
+ const webhook = await this.mutatingWebhook(path);
586
648
  const resources = [
587
649
  this.namespace(),
588
650
  this.networkPolicy(),
@@ -590,23 +652,20 @@ var Webhook = class {
590
652
  this.clusterRoleBinding(),
591
653
  this.serviceAccount(),
592
654
  this.tlsSecret(),
593
- this.mutatingWebhook(),
655
+ webhook,
594
656
  this.deployment(hash),
595
657
  this.service(),
596
658
  this.moduleSecret(code, hash)
597
659
  ];
598
660
  return resources.map((r) => (0, import_client_node.dumpYaml)(r, { noRefs: true })).join("---\n");
599
661
  }
600
- async deploy(code, webhookTimeout) {
662
+ async deploy(path, webhookTimeout) {
601
663
  logger_default.info("Establishing connection to Kubernetes");
602
664
  const namespace = "pepr-system";
603
665
  const kubeConfig = new import_client_node.KubeConfig();
604
666
  kubeConfig.loadFromDefault();
605
667
  const coreV1Api = kubeConfig.makeApiClient(import_client_node.CoreV1Api);
606
- const rbacApi = kubeConfig.makeApiClient(import_client_node.RbacAuthorizationV1Api);
607
- const appsApi = kubeConfig.makeApiClient(import_client_node.AppsV1Api);
608
668
  const admissionApi = kubeConfig.makeApiClient(import_client_node.AdmissionregistrationV1Api);
609
- const networkApi = kubeConfig.makeApiClient(import_client_node.NetworkingV1Api);
610
669
  const ns = this.namespace();
611
670
  try {
612
671
  logger_default.info("Checking for namespace");
@@ -616,7 +675,7 @@ var Webhook = class {
616
675
  logger_default.info("Creating namespace");
617
676
  await coreV1Api.createNamespace(ns);
618
677
  }
619
- const wh = this.mutatingWebhook(webhookTimeout);
678
+ const wh = await this.mutatingWebhook(path, webhookTimeout);
620
679
  try {
621
680
  logger_default.info("Creating mutating webhook");
622
681
  await admissionApi.createMutatingWebhookConfiguration(wh);
@@ -629,18 +688,22 @@ var Webhook = class {
629
688
  if (this.host) {
630
689
  return;
631
690
  }
632
- if (!code) {
691
+ if (!path) {
633
692
  throw new Error("No code provided");
634
693
  }
694
+ const code = await import_fs.promises.readFile(path);
635
695
  const hash = import_crypto.default.createHash("sha256").update(code).digest("hex");
636
- const netpol = this.networkPolicy();
696
+ const appsApi = kubeConfig.makeApiClient(import_client_node.AppsV1Api);
697
+ const rbacApi = kubeConfig.makeApiClient(import_client_node.RbacAuthorizationV1Api);
698
+ const networkApi = kubeConfig.makeApiClient(import_client_node.NetworkingV1Api);
699
+ const networkPolicy = this.networkPolicy();
637
700
  try {
638
701
  logger_default.info("Checking for network policy");
639
- await networkApi.readNamespacedNetworkPolicy(netpol.metadata?.name ?? "", namespace);
702
+ await networkApi.readNamespacedNetworkPolicy(networkPolicy.metadata?.name ?? "", namespace);
640
703
  } catch (e) {
641
704
  logger_default.debug(e instanceof import_client_node.HttpError ? e.body : e);
642
705
  logger_default.info("Creating network policy");
643
- await networkApi.createNamespacedNetworkPolicy(namespace, netpol);
706
+ await networkApi.createNamespacedNetworkPolicy(namespace, networkPolicy);
644
707
  }
645
708
  const crb = this.clusterRoleBinding();
646
709
  try {
@@ -907,8 +970,8 @@ var hello_pepr_samples_default = [
907
970
  var gitIgnore = "# Ignore node_modules and Pepr build artifacts\nnode_modules\ndist\ninsecure*\n";
908
971
  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';
909
972
  var peprTS = 'import { 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(cfg, [\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';
910
- 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 (Secret Base64 Handling) *\n * ---------------------------------------------------------------------------------------------------\n *\n * The K8s JS client provides incomplete support for base64 encoding/decoding handling for secrets,\n * unlike the GO client. To make this less painful, Pepr automatically handles base64 encoding/decoding\n * secret data before and after the Capability Action is executed.\n */\nWhen(a.Secret)\n .IsCreated()\n .WithName("secret-1")\n .Then(request => {\n const secret = request.Raw;\n\n // This will be encoded at the end of all processing back to base64: "Y2hhbmdlLXdpdGhvdXQtZW5jb2Rpbmc="\n secret.data.magic = "change-without-encoding";\n\n // You can modify the data directly, and it will be encoded at the end of all processing\n secret.data.example += " - modified by Pepr";\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';
911
- 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.6.1", 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.3", "@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 } };
973
+ 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 run `pepr dev`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 (Secret Base64 Handling) *\n * ---------------------------------------------------------------------------------------------------\n *\n * The K8s JS client provides incomplete support for base64 encoding/decoding handling for secrets,\n * unlike the GO client. To make this less painful, Pepr automatically handles base64 encoding/decoding\n * secret data before and after the Capability Action is executed.\n */\nWhen(a.Secret)\n .IsCreated()\n .WithName("secret-1")\n .Then(request => {\n const secret = request.Raw;\n\n // This will be encoded at the end of all processing back to base64: "Y2hhbmdlLXdpdGhvdXQtZW5jb2Rpbmc="\n secret.data.magic = "change-without-encoding";\n\n // You can modify the data directly, and it will be encoded at the end of all processing\n secret.data.example += " - modified by Pepr";\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';
974
+ 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.7.1", 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.2", "@types/express": "4.17.17", "@types/node-fetch": "2.6.4", "@types/node-forge": "1.3.2", "@types/prettier": "2.7.3", "@types/prompts": "2.4.4", "@types/ramda": "0.29.2", "@types/uuid": "9.0.2", 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 } };
912
975
 
913
976
  // src/cli/init/templates/pepr.code-snippets.json
914
977
  var pepr_code_snippets_default = {
@@ -955,7 +1018,7 @@ var tsconfig_module_default = {
955
1018
  };
956
1019
 
957
1020
  // src/cli/init/utils.ts
958
- var import_fs = require("fs");
1021
+ var import_fs2 = require("fs");
959
1022
  function sanitizeName(name) {
960
1023
  let sanitized = name.toLowerCase().replace(/[^a-z0-9-]+/gi, "-");
961
1024
  sanitized = sanitized.replace(/^-+|-+$/g, "");
@@ -964,7 +1027,7 @@ function sanitizeName(name) {
964
1027
  }
965
1028
  async function createDir(dir) {
966
1029
  try {
967
- await import_fs.promises.mkdir(dir);
1030
+ await import_fs2.promises.mkdir(dir);
968
1031
  } catch (err) {
969
1032
  if (err && err.code === "EEXIST") {
970
1033
  throw new Error(`Directory ${dir} already exists`);
@@ -977,7 +1040,7 @@ function write(path, data) {
977
1040
  if (typeof data !== "string") {
978
1041
  data = JSON.stringify(data, null, 2);
979
1042
  }
980
- return import_fs.promises.writeFile(path, data);
1043
+ return import_fs2.promises.writeFile(path, data);
981
1044
  }
982
1045
 
983
1046
  // src/cli/init/templates.ts
@@ -991,6 +1054,9 @@ function genPkgJSON(opts, pgkVerOverride) {
991
1054
  version: "0.0.1",
992
1055
  description: opts.description,
993
1056
  keywords: ["pepr", "k8s", "policy-engine", "pepr-module", "security"],
1057
+ engines: {
1058
+ node: ">=18.0.0"
1059
+ },
994
1060
  pepr: {
995
1061
  name: opts.name.trim(),
996
1062
  uuid: pgkVerOverride ? "static-test" : uuid,
@@ -1001,8 +1067,7 @@ function genPkgJSON(opts, pgkVerOverride) {
1001
1067
  }
1002
1068
  },
1003
1069
  scripts: {
1004
- "k3d-setup": scripts["test:e2e:k3d"],
1005
- start: "pepr dev"
1070
+ "k3d-setup": scripts["test:e2e:k3d"]
1006
1071
  },
1007
1072
  dependencies: {
1008
1073
  pepr: pgkVerOverride || version
@@ -1065,18 +1130,21 @@ function build_default(program2) {
1065
1130
  peprTS2
1066
1131
  ).action(async (opts) => {
1067
1132
  const { cfg, path, uuid } = await buildModule(void 0, opts.entryPoint);
1068
- const code = await import_fs2.promises.readFile(path);
1133
+ if (opts.entryPoint !== peprTS2) {
1134
+ logger_default.info(`Module built successfully at ${path}`);
1135
+ return;
1136
+ }
1069
1137
  const webhook = new Webhook({
1070
1138
  ...cfg.pepr,
1071
1139
  description: cfg.description
1072
1140
  });
1073
1141
  const yamlFile = `pepr-module-${uuid}.yaml`;
1074
1142
  const yamlPath = (0, import_path.resolve)("dist", yamlFile);
1075
- const yaml = webhook.allYaml(code);
1143
+ const yaml = await webhook.allYaml(path);
1076
1144
  const zarfPath = (0, import_path.resolve)("dist", "zarf.yaml");
1077
1145
  const zarf = webhook.zarfYaml(yamlFile);
1078
- await import_fs2.promises.writeFile(yamlPath, yaml);
1079
- await import_fs2.promises.writeFile(zarfPath, zarf);
1146
+ await import_fs3.promises.writeFile(yamlPath, yaml);
1147
+ await import_fs3.promises.writeFile(zarfPath, zarf);
1080
1148
  logger_default.debug(`Module compiled successfully at ${path}`);
1081
1149
  logger_default.info(`K8s resource for the module saved to ${yamlPath}`);
1082
1150
  });
@@ -1087,15 +1155,15 @@ async function loadModule(entryPoint = peprTS2) {
1087
1155
  const cfgPath = (0, import_path.resolve)(".", "package.json");
1088
1156
  const input = (0, import_path.resolve)(".", entryPoint);
1089
1157
  try {
1090
- await import_fs2.promises.access(cfgPath);
1091
- await import_fs2.promises.access(input);
1158
+ await import_fs3.promises.access(cfgPath);
1159
+ await import_fs3.promises.access(input);
1092
1160
  } catch (e) {
1093
1161
  logger_default.error(
1094
1162
  `Could not find ${cfgPath} or ${input} in the current directory. Please run this command from the root of your module's directory.`
1095
1163
  );
1096
1164
  process.exit(1);
1097
1165
  }
1098
- const moduleText = await import_fs2.promises.readFile(cfgPath, { encoding: "utf-8" });
1166
+ const moduleText = await import_fs3.promises.readFile(cfgPath, { encoding: "utf-8" });
1099
1167
  const cfg = JSON.parse(moduleText);
1100
1168
  const { uuid } = cfg.pepr;
1101
1169
  const name = `pepr-${uuid}.js`;
@@ -1120,9 +1188,8 @@ async function loadModule(entryPoint = peprTS2) {
1120
1188
  async function buildModule(reloader, entryPoint = peprTS2) {
1121
1189
  try {
1122
1190
  const { cfg, path, uuid } = await loadModule(entryPoint);
1123
- (0, import_child_process.execSync)("./node_modules/.bin/tsc", { stdio: "inherit" });
1124
- const customEntryPoint = entryPoint !== peprTS2;
1125
- const ctx = await (0, import_esbuild.context)({
1191
+ (0, import_child_process2.execSync)("./node_modules/.bin/tsc", { stdio: "inherit" });
1192
+ const ctxCfg = {
1126
1193
  bundle: true,
1127
1194
  entryPoints: [entryPoint],
1128
1195
  external: externalLibs,
@@ -1130,11 +1197,8 @@ async function buildModule(reloader, entryPoint = peprTS2) {
1130
1197
  keepNames: true,
1131
1198
  legalComments: "external",
1132
1199
  metafile: true,
1133
- // Only minify the code if we're not in dev mode and we're not using a custom entry point
1134
- minify: !reloader && !customEntryPoint,
1200
+ minify: true,
1135
1201
  outfile: path,
1136
- // Only bundle the NPM packages if we're not using a custom entry point
1137
- packages: customEntryPoint ? "external" : void 0,
1138
1202
  plugins: [
1139
1203
  {
1140
1204
  name: "reload-server",
@@ -1144,18 +1208,26 @@ async function buildModule(reloader, entryPoint = peprTS2) {
1144
1208
  console.log(await (0, import_esbuild.analyzeMetafile)(r.metafile));
1145
1209
  }
1146
1210
  if (reloader) {
1147
- reloader(r);
1211
+ await reloader(r);
1148
1212
  }
1149
1213
  });
1150
1214
  }
1151
1215
  }
1152
1216
  ],
1153
1217
  platform: "node",
1154
- // Only generate a sourcemap if we're in dev mode
1155
- sourcemap: !!reloader,
1156
- // Only tree shake the code if we're not using a custom entry point
1157
- treeShaking: !customEntryPoint
1158
- });
1218
+ sourcemap: true,
1219
+ treeShaking: true
1220
+ };
1221
+ if (reloader) {
1222
+ ctxCfg.minify = false;
1223
+ }
1224
+ if (entryPoint !== peprTS2) {
1225
+ ctxCfg.minify = false;
1226
+ ctxCfg.outfile = (0, import_path.resolve)("dist", (0, import_path.basename)(entryPoint, (0, import_path.extname)(entryPoint))) + ".js";
1227
+ ctxCfg.packages = "external";
1228
+ ctxCfg.treeShaking = false;
1229
+ }
1230
+ const ctx = await (0, import_esbuild.context)(ctxCfg);
1159
1231
  if (reloader) {
1160
1232
  await ctx.watch();
1161
1233
  } else {
@@ -1173,7 +1245,6 @@ async function buildModule(reloader, entryPoint = peprTS2) {
1173
1245
  }
1174
1246
 
1175
1247
  // src/cli/deploy.ts
1176
- var import_fs3 = require("fs");
1177
1248
  var import_prompts = __toESM(require("prompts"));
1178
1249
  function deploy_default(program2) {
1179
1250
  program2.command("deploy").description("Deploy a Pepr Module").option("-i, --image [image]", "Override the image tag").option("--confirm", "Skip confirmation prompt").action(async (opts) => {
@@ -1188,7 +1259,6 @@ function deploy_default(program2) {
1188
1259
  }
1189
1260
  }
1190
1261
  const { cfg, path } = await buildModule();
1191
- const code = await import_fs3.promises.readFile(path);
1192
1262
  const webhook = new Webhook({
1193
1263
  ...cfg.pepr,
1194
1264
  description: cfg.description
@@ -1197,7 +1267,7 @@ function deploy_default(program2) {
1197
1267
  webhook.image = opts.image;
1198
1268
  }
1199
1269
  try {
1200
- await webhook.deploy(code);
1270
+ await webhook.deploy(path);
1201
1271
  logger_default.info(`Module deployed successfully`);
1202
1272
  } catch (e) {
1203
1273
  logger_default.error(`Error deploying module: ${e}`);
@@ -1207,7 +1277,7 @@ function deploy_default(program2) {
1207
1277
  }
1208
1278
 
1209
1279
  // src/cli/dev.ts
1210
- var import_child_process2 = require("child_process");
1280
+ var import_child_process3 = require("child_process");
1211
1281
  var import_fs4 = require("fs");
1212
1282
  var import_prompts2 = __toESM(require("prompts"));
1213
1283
  function dev_default(program2) {
@@ -1233,12 +1303,11 @@ function dev_default(program2) {
1233
1303
  await import_fs4.promises.writeFile("insecure-tls.crt", webhook.tls.pem.crt);
1234
1304
  await import_fs4.promises.writeFile("insecure-tls.key", webhook.tls.pem.key);
1235
1305
  try {
1236
- await webhook.deploy(void 0, 30);
1237
- logger_default.info(`Module deployed successfully`);
1238
1306
  let program3;
1239
- const runFork = () => {
1307
+ const runFork = async () => {
1240
1308
  logger_default.info(`Running module ${path}`);
1241
- program3 = (0, import_child_process2.fork)(path, {
1309
+ await webhook.deploy(path, 30);
1310
+ program3 = (0, import_child_process3.fork)(path, {
1242
1311
  env: {
1243
1312
  ...process.env,
1244
1313
  LOG_LEVEL: "debug",
@@ -1247,16 +1316,16 @@ function dev_default(program2) {
1247
1316
  }
1248
1317
  });
1249
1318
  };
1250
- await buildModule((r) => {
1319
+ await buildModule(async (r) => {
1251
1320
  if (r.errors.length > 0) {
1252
1321
  logger_default.error(`Error compiling module: ${r.errors}`);
1253
1322
  return;
1254
1323
  }
1255
1324
  if (program3) {
1256
1325
  program3.once("exit", runFork);
1257
- program3.kill();
1326
+ program3.kill("SIGKILL");
1258
1327
  } else {
1259
- runFork();
1328
+ await runFork();
1260
1329
  }
1261
1330
  });
1262
1331
  } catch (e) {
@@ -1316,23 +1385,13 @@ function format_default(program2) {
1316
1385
  }
1317
1386
 
1318
1387
  // src/cli/init/index.ts
1319
- var import_child_process3 = require("child_process");
1388
+ var import_child_process4 = require("child_process");
1320
1389
  var import_path2 = require("path");
1321
1390
  var import_prompts4 = __toESM(require("prompts"));
1322
1391
 
1323
1392
  // src/cli/init/walkthrough.ts
1324
1393
  var import_fs6 = require("fs");
1325
1394
  var import_prompts3 = __toESM(require("prompts"));
1326
-
1327
- // src/lib/types.ts
1328
- var ErrorBehavior = /* @__PURE__ */ ((ErrorBehavior2) => {
1329
- ErrorBehavior2["ignore"] = "ignore";
1330
- ErrorBehavior2["audit"] = "audit";
1331
- ErrorBehavior2["reject"] = "reject";
1332
- return ErrorBehavior2;
1333
- })(ErrorBehavior || {});
1334
-
1335
- // src/cli/init/walkthrough.ts
1336
1395
  function walkthrough() {
1337
1396
  const askName = {
1338
1397
  type: "text",
@@ -1435,14 +1494,14 @@ function init_default(program2) {
1435
1494
  await write((0, import_path2.resolve)(dirName, "capabilities", helloPepr.path), helloPepr.data);
1436
1495
  if (!opts.skipPostInit) {
1437
1496
  process.chdir(dirName);
1438
- (0, import_child_process3.execSync)("npm install", {
1497
+ (0, import_child_process4.execSync)("npm install", {
1439
1498
  stdio: "inherit"
1440
1499
  });
1441
- (0, import_child_process3.execSync)("git init", {
1500
+ (0, import_child_process4.execSync)("git init", {
1442
1501
  stdio: "inherit"
1443
1502
  });
1444
1503
  try {
1445
- (0, import_child_process3.execSync)("code .", {
1504
+ (0, import_child_process4.execSync)("code .", {
1446
1505
  stdio: "inherit"
1447
1506
  });
1448
1507
  } catch (e) {
@@ -1475,7 +1534,7 @@ var RootCmd = class extends import_commander.Command {
1475
1534
  };
1476
1535
 
1477
1536
  // src/cli/update.ts
1478
- var import_child_process4 = require("child_process");
1537
+ var import_child_process5 = require("child_process");
1479
1538
  var import_path3 = require("path");
1480
1539
  var import_prompts5 = __toESM(require("prompts"));
1481
1540
  function update_default(program2) {
@@ -1499,10 +1558,10 @@ function update_default(program2) {
1499
1558
  await write((0, import_path3.resolve)("capabilities", samplesYaml.path), samplesYaml.data);
1500
1559
  await write((0, import_path3.resolve)("capabilities", helloPepr.path), helloPepr.data);
1501
1560
  }
1502
- (0, import_child_process4.execSync)("npm install pepr@latest", {
1561
+ (0, import_child_process5.execSync)("npm install pepr@latest", {
1503
1562
  stdio: "inherit"
1504
1563
  });
1505
- (0, import_child_process4.execSync)("npm install -g pepr@latest", {
1564
+ (0, import_child_process5.execSync)("npm install -g pepr@latest", {
1506
1565
  stdio: "inherit"
1507
1566
  });
1508
1567
  console.log(`Module updated!`);
@@ -1516,12 +1575,41 @@ function update_default(program2) {
1516
1575
  });
1517
1576
  }
1518
1577
 
1578
+ // src/lib.ts
1579
+ var import_client_node4 = __toESM(require("@kubernetes/client-node"));
1580
+ var import_http_status_codes2 = require("http-status-codes");
1581
+ var utils = __toESM(require("ramda"));
1582
+
1583
+ // src/lib/k8s/upstream.ts
1584
+ var import_client_node3 = require("@kubernetes/client-node");
1585
+
1586
+ // src/lib/fetch.ts
1587
+ var import_http_status_codes = require("http-status-codes");
1588
+ var import_node_fetch = __toESM(require("node-fetch"));
1589
+
1590
+ // src/lib/module.ts
1591
+ var import_ramda3 = require("ramda");
1592
+
1593
+ // src/lib/controller.ts
1594
+ var import_express = __toESM(require("express"));
1595
+
1596
+ // src/lib/processor.ts
1597
+ var import_fast_json_patch = __toESM(require("fast-json-patch"));
1598
+
1599
+ // src/lib/request.ts
1600
+ var import_ramda2 = require("ramda");
1601
+
1519
1602
  // src/cli.ts
1520
1603
  var program = new RootCmd();
1521
1604
  program.version(version).description(`Pepr Kubernetes Thingy (v${version})`).action(() => {
1522
1605
  if (program.args.length < 1) {
1523
1606
  console.log(banner);
1524
1607
  program.help();
1608
+ } else {
1609
+ logger_default.error(`Invalid command '${program.args.join(" ")}'
1610
+ `);
1611
+ program.outputHelp();
1612
+ process.exitCode = 1;
1525
1613
  }
1526
1614
  });
1527
1615
  init_default(program);
@@ -116,7 +116,7 @@ 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.6.1", 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.3", "@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 } };
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.7.1", 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.2", "@types/express": "4.17.17", "@types/node-fetch": "2.6.4", "@types/node-forge": "1.3.2", "@types/prettier": "2.7.3", "@types/prompts": "2.4.4", "@types/ramda": "0.29.2", "@types/uuid": "9.0.2", 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
121
  // src/runtime/controller.ts
122
122
  var { version } = packageJSON;
@@ -1 +1 @@
1
- {"version":3,"file":"capability.d.ts","sourceRoot":"","sources":["../../src/lib/capability.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAE/C,OAAO,EAEL,OAAO,EAIP,aAAa,EAGb,YAAY,EACZ,SAAS,EACT,YAAY,EACb,MAAM,SAAS,CAAC;AAEjB;;GAEG;AACH,qBAAa,UAAW,YAAW,aAAa;IAC9C,OAAO,CAAC,KAAK,CAAS;IACtB,OAAO,CAAC,YAAY,CAAS;IAC7B,OAAO,CAAC,WAAW,CAAC,CAAuB;IAG3C,OAAO,CAAC,iBAAiB,CAAoB;IAE7C,OAAO,CAAC,SAAS,CAAiB;IAElC,IAAI,QAAQ,IAAI,OAAO,EAAE,CAExB;IAED,IAAI,IAAI,WAEP;IAED,IAAI,WAAW,WAEd;IAED,IAAI,UAAU,aAEb;IAED,IAAI,gBAAgB,cAEnB;gBAEW,GAAG,EAAE,aAAa;IAQ9B;;;;;;;;OAQG;IACH,IAAI,4CAA6C,gBAAgB,qBAuF/D;CACH"}
1
+ {"version":3,"file":"capability.d.ts","sourceRoot":"","sources":["../../src/lib/capability.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAE/C,OAAO,EAEL,OAAO,EAIP,aAAa,EAGb,YAAY,EACZ,SAAS,EACT,YAAY,EACb,MAAM,SAAS,CAAC;AAEjB;;GAEG;AACH,qBAAa,UAAW,YAAW,aAAa;IAC9C,OAAO,CAAC,KAAK,CAAS;IACtB,OAAO,CAAC,YAAY,CAAS;IAC7B,OAAO,CAAC,WAAW,CAAC,CAAuB;IAG3C,OAAO,CAAC,iBAAiB,CAAoB;IAE7C,OAAO,CAAC,SAAS,CAAiB;IAElC,IAAI,QAAQ,IAAI,OAAO,EAAE,CAExB;IAED,IAAI,IAAI,WAEP;IAED,IAAI,WAAW,WAEd;IAED,IAAI,UAAU,aAEb;IAED,IAAI,gBAAgB,cAEnB;gBAEW,GAAG,EAAE,aAAa;IAQ9B;;;;;;;;OAQG;IACH,IAAI,4CAA6C,gBAAgB,qBAwF/D;CACH"}