pepr 0.52.2-nightly.1 → 0.52.2-nightly.3

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/dist/cli.js CHANGED
@@ -7376,12 +7376,6 @@ var banner = `\x1B[107;40m\x1B[38;5;m \x1B[38;5;m \x1B[38;5;m \x1B[38;5;m \x1B[3
7376
7376
  \x1B[0m
7377
7377
  `;
7378
7378
 
7379
- // src/cli/build.ts
7380
- var import_child_process3 = require("child_process");
7381
- var import_esbuild2 = require("esbuild");
7382
- var import_fs10 = require("fs");
7383
- var import_path4 = require("path");
7384
-
7385
7379
  // src/lib/assets/assets.ts
7386
7380
  var import_crypto = __toESM(require("crypto"));
7387
7381
 
@@ -8366,7 +8360,7 @@ function helmLayout(basePath, unique) {
8366
8360
  // src/lib/assets/loader.ts
8367
8361
  var import_child_process = require("child_process");
8368
8362
  function loadCapabilities(path4) {
8369
- return new Promise((resolve6, reject) => {
8363
+ return new Promise((resolve7, reject) => {
8370
8364
  const program2 = (0, import_child_process.fork)(path4, {
8371
8365
  env: {
8372
8366
  ...process.env,
@@ -8380,7 +8374,7 @@ function loadCapabilities(path4) {
8380
8374
  for (const capability of capabilities) {
8381
8375
  console.info(`Registered Pepr Capability "${capability.name}"`);
8382
8376
  }
8383
- resolve6(capabilities);
8377
+ resolve7(capabilities);
8384
8378
  });
8385
8379
  program2.on("error", (error) => {
8386
8380
  reject(error);
@@ -8629,528 +8623,76 @@ var Assets = class {
8629
8623
  };
8630
8624
  };
8631
8625
 
8632
- // src/cli/init/templates.ts
8633
- var import_client_node3 = require("@kubernetes/client-node");
8634
- var import_util = require("util");
8635
- var import_uuid = require("uuid");
8636
- var import_fs5 = require("fs");
8637
- var import_path2 = __toESM(require("path"));
8626
+ // src/cli/build/index.ts
8627
+ var import_commander = require("commander");
8638
8628
 
8639
- // src/templates/pepr.code-snippets.json
8640
- var pepr_code_snippets_default = {
8641
- "Create a new Pepr capability": {
8642
- prefix: "create pepr capability",
8643
- body: [
8644
- "import { Capability, a } from 'pepr';",
8645
- "",
8646
- "export const ${TM_FILENAME_BASE/(.*)/${1:/pascalcase}/} = new Capability({",
8647
- " name: '${TM_FILENAME_BASE}',",
8648
- " description: '${1:A brief description of this capability.}',",
8649
- " namespaces: [${2:}],",
8650
- "});",
8651
- "",
8652
- "// Use the 'When' function to create a new action",
8653
- "const { When } = ${TM_FILENAME_BASE/(.*)/${1:/pascalcase}/};",
8654
- "",
8655
- "// When(a.<Kind>).Is<Event>().Then(change => change.<changes>",
8656
- "When(${3:})"
8657
- ],
8658
- description: "Creates a new Pepr capability with a specified description, optional namespaces, and adds a When statement for the specified value."
8659
- }
8660
- };
8629
+ // src/lib/included-files.ts
8630
+ var import_fs4 = require("fs");
8631
+ async function createDockerfile(version3, description, includedFiles) {
8632
+ const file = `
8633
+ # Use an official Node.js runtime as the base image
8634
+ FROM ghcr.io/defenseunicorns/pepr/controller:v${version3}
8635
+
8636
+ LABEL description="${description}"
8637
+
8638
+ # Add the included files to the image
8639
+ ${includedFiles.map((f) => `ADD ${f} ${f}`).join("\n")}
8640
+
8641
+ `;
8642
+ await import_fs4.promises.writeFile("Dockerfile.controller", file, { encoding: "utf-8" });
8643
+ }
8661
8644
 
8662
- // src/templates/.prettierrc.json
8663
- var prettierrc_default = {
8664
- arrowParens: "avoid",
8665
- bracketSameLine: false,
8666
- bracketSpacing: true,
8667
- embeddedLanguageFormatting: "auto",
8668
- insertPragma: false,
8669
- printWidth: 100,
8670
- quoteProps: "as-needed",
8671
- requirePragma: false,
8672
- semi: true,
8673
- tabWidth: 2,
8674
- useTabs: false,
8675
- vueIndentScriptAndStyle: false
8676
- };
8645
+ // src/cli/build/build.helpers.ts
8646
+ var import_child_process2 = require("child_process");
8647
+ var import_esbuild = require("esbuild");
8648
+ var import_path2 = require("path");
8649
+ var import_fs6 = require("fs");
8677
8650
 
8678
- // src/templates/capabilities/hello-pepr.samples.json
8679
- var hello_pepr_samples_default = [
8680
- {
8681
- apiVersion: "v1",
8682
- kind: "Namespace",
8683
- metadata: {
8684
- name: "pepr-demo",
8685
- labels: {
8686
- "keep-me": "please",
8687
- "remove-me": "please"
8688
- }
8689
- }
8690
- },
8691
- {
8692
- apiVersion: "v1",
8693
- kind: "Namespace",
8694
- metadata: {
8695
- name: "pepr-demo-2"
8696
- }
8697
- },
8698
- {
8699
- apiVersion: "v1",
8700
- kind: "Secret",
8701
- metadata: {
8702
- name: "secret-1",
8703
- namespace: "pepr-demo"
8704
- },
8705
- data: {
8706
- example: "dW5pY29ybiBtYWdpYw==",
8707
- "binary-data": "iCZQUg8xYucNUqD+8lyl2YcKjYYygvTtiDSEV9b9WKUkxSSLFJTgIWMJ9GcFFYs4T9JCdda51u74jfq8yHzRuEASl60EdTS/NfWgIIFTGqcNRfqMw+vgpyTMmCyJVaJEDFq6AA==",
8708
- "ascii-with-white-space": "VGhpcyBpcyBzb21lIHJhbmRvbSB0ZXh0OgoKICAgIC0gd2l0aCBsaW5lIGJyZWFrcwogICAgLSBhbmQgdGFicw=="
8709
- }
8710
- },
8711
- {
8712
- apiVersion: "v1",
8713
- kind: "ConfigMap",
8714
- metadata: {
8715
- name: "example-1",
8716
- namespace: "pepr-demo"
8717
- },
8718
- data: {
8719
- key: "ex-1-val"
8720
- }
8721
- },
8722
- {
8723
- apiVersion: "v1",
8724
- kind: "ConfigMap",
8725
- metadata: {
8726
- name: "example-2",
8727
- namespace: "pepr-demo"
8728
- },
8729
- data: {
8730
- key: "ex-2-val"
8731
- }
8732
- },
8733
- {
8734
- apiVersion: "v1",
8735
- kind: "ConfigMap",
8736
- metadata: {
8737
- name: "example-evil-cm",
8738
- namespace: "pepr-demo",
8739
- annotations: {
8740
- evil: "true"
8651
+ // src/lib/assets/yaml/generateAllYaml.ts
8652
+ var import_crypto2 = __toESM(require("crypto"));
8653
+ var import_client_node3 = require("@kubernetes/client-node");
8654
+
8655
+ // src/lib/assets/k8sObjects.ts
8656
+ var import_zlib = require("zlib");
8657
+ function getNamespace(namespaceLabels) {
8658
+ if (namespaceLabels) {
8659
+ return {
8660
+ apiVersion: "v1",
8661
+ kind: "Namespace",
8662
+ metadata: {
8663
+ name: "pepr-system",
8664
+ labels: namespaceLabels ?? {}
8741
8665
  }
8742
- },
8743
- data: {
8744
- key: "ex-evil-cm-val"
8745
- }
8746
- },
8747
- {
8748
- apiVersion: "v1",
8749
- kind: "ConfigMap",
8750
- metadata: {
8751
- name: "example-3",
8752
- namespace: "pepr-demo",
8753
- labels: {
8754
- change: "by-label"
8666
+ };
8667
+ } else {
8668
+ return {
8669
+ apiVersion: "v1",
8670
+ kind: "Namespace",
8671
+ metadata: {
8672
+ name: "pepr-system"
8755
8673
  }
8756
- },
8757
- data: {
8758
- key: "ex-3-val"
8759
- }
8760
- },
8761
- {
8762
- apiVersion: "v1",
8763
- kind: "ConfigMap",
8764
- metadata: {
8765
- name: "example-4",
8766
- namespace: "pepr-demo"
8767
- },
8768
- data: {
8769
- key: "ex-4-val"
8770
- }
8771
- },
8772
- {
8773
- apiVersion: "v1",
8774
- kind: "ConfigMap",
8775
- metadata: {
8776
- name: "example-4a",
8777
- namespace: "pepr-demo-2"
8778
- },
8779
- data: {
8780
- key: "ex-4-val"
8781
- }
8782
- },
8783
- {
8784
- apiVersion: "v1",
8785
- kind: "ConfigMap",
8674
+ };
8675
+ }
8676
+ }
8677
+ function getWatcher(assets, hash, buildTimestamp, imagePullSecret) {
8678
+ const { name: name2, image, config } = assets;
8679
+ if (!isWatcher(assets.capabilities)) {
8680
+ return null;
8681
+ }
8682
+ const app = `${name2}-watcher`;
8683
+ const deploy = {
8684
+ apiVersion: "apps/v1",
8685
+ kind: "Deployment",
8786
8686
  metadata: {
8787
- name: "example-5",
8788
- namespace: "pepr-demo",
8687
+ name: app,
8688
+ namespace: "pepr-system",
8689
+ annotations: {
8690
+ "pepr.dev/description": config.description || ""
8691
+ },
8789
8692
  labels: {
8790
- "chuck-norris": "test"
8791
- }
8792
- },
8793
- data: {
8794
- key: "ex-5-val"
8795
- }
8796
- },
8797
- {
8798
- apiVersion: "apiextensions.k8s.io/v1",
8799
- kind: "CustomResourceDefinition",
8800
- metadata: {
8801
- name: "unicorns.pepr.dev"
8802
- },
8803
- spec: {
8804
- group: "pepr.dev",
8805
- versions: [
8806
- {
8807
- name: "v1",
8808
- served: true,
8809
- storage: true,
8810
- schema: {
8811
- openAPIV3Schema: {
8812
- type: "object",
8813
- properties: {
8814
- spec: {
8815
- type: "object",
8816
- properties: {
8817
- message: {
8818
- type: "string"
8819
- },
8820
- counter: {
8821
- type: "number"
8822
- }
8823
- }
8824
- }
8825
- }
8826
- }
8827
- }
8828
- }
8829
- ],
8830
- scope: "Namespaced",
8831
- names: {
8832
- plural: "unicorns",
8833
- singular: "unicorn",
8834
- kind: "Unicorn"
8835
- }
8836
- }
8837
- }
8838
- ];
8839
-
8840
- // src/templates/settings.json
8841
- var settings_default = {
8842
- "debug.javascript.terminalOptions": {
8843
- enableTurboSourcemaps: true,
8844
- resolveSourceMapLocations: [
8845
- "${workspaceFolder}/**",
8846
- "node_modules/kubernetes-fluent-client/**",
8847
- "node_modules/pepr/**"
8848
- ]
8849
- }
8850
- };
8851
-
8852
- // src/templates/tsconfig.module.json
8853
- var tsconfig_module_default = {
8854
- compilerOptions: {
8855
- allowSyntheticDefaultImports: true,
8856
- declaration: true,
8857
- declarationMap: true,
8858
- emitDeclarationOnly: true,
8859
- esModuleInterop: true,
8860
- lib: ["ES2022"],
8861
- module: "NodeNext",
8862
- moduleResolution: "NodeNext",
8863
- outDir: "dist",
8864
- resolveJsonModule: true,
8865
- rootDir: ".",
8866
- strict: false,
8867
- target: "ES2022",
8868
- useUnknownInCatchVariables: false
8869
- },
8870
- include: ["**/*.ts"]
8871
- };
8872
-
8873
- // src/templates/data.json
8874
- var gitIgnore = "# Ignore node_modules and Pepr build artifacts\nnode_modules\ndist\ninsecure*\n";
8875
- var readmeMd = '# Pepr Module\n\nThis is a Pepr Module. [Pepr](https://github.com/defenseunicorns/pepr) is a type-safe Kubernetes middleware system.\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```text\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';
8876
- 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';
8877
- var helloPeprTS = 'import {\n Capability,\n K8s,\n Log,\n PeprMutateRequest,\n RegisterKind,\n a,\n fetch,\n fetchStatus,\n kind,\n} from "pepr";\nimport { MockAgent, setGlobalDispatcher } from "undici";\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 action, use \'Store\' to persist data\nconst { When, Store } = HelloPepr;\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate Action (Namespace) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This 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 .Mutate(ns => ns.RemoveLabel("remove-me"));\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Watch Action with K8s SSA (Namespace) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This action watches for the `pepr-demo-2` namespace to be created, then creates a ConfigMap with\n * the name `pepr-ssa-demo` and adds the namespace UID to the ConfigMap data. Because Pepr uses\n * server-side apply for this operation, the ConfigMap will be created or updated if it already exists.\n */\nWhen(a.Namespace)\n .IsCreated()\n .WithName("pepr-demo-2")\n .Watch(async ns => {\n Log.info("Namespace pepr-demo-2 was created.");\n\n try {\n // Apply the ConfigMap using K8s server-side apply\n await K8s(kind.ConfigMap).Apply({\n metadata: {\n name: "pepr-ssa-demo",\n namespace: "pepr-demo-2",\n },\n data: {\n "ns-uid": ns.metadata.uid,\n },\n });\n } catch (error) {\n // You can use the Log object to log messages to the Pepr controller pod\n Log.error(error, "Failed to apply ConfigMap using server-side apply.");\n }\n\n // You can share data between actions using the Store, including between different types of actions\n Store.setItem("watch-data", "This data was stored by a Watch Action.");\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate Action (CM Example 1) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This is a single 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 .Mutate(request => {\n request.SetLabel("pepr", "was-here").SetAnnotation("pepr.dev", "annotations-work-too");\n\n // Use the Store to persist data between requests and Pepr controller pods\n Store.setItem("example-1", "was-here");\n\n // This data is written asynchronously and can be read back via `Store.getItem()` or `Store.subscribe()`\n Store.setItem("example-1-data", JSON.stringify(request.Raw.data));\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate & Validate Actions (CM Example 2) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This combines 3 different types of actions: \'Mutate\', \'Validate\', and \'Watch\'. The order\n * of the actions is required, but each action is optional. In this example, when a ConfigMap is created\n * with the name `example-2`, then add a label and annotation, validate that the ConfigMap has the label\n * `pepr`, and log the request.\n */\nWhen(a.ConfigMap)\n .IsCreated()\n .WithName("example-2")\n .Mutate(request => {\n // This Mutate Action will mutate the request before it is persisted to the cluster\n\n // Use `request.Merge()` to merge the new data with the existing data\n request.Merge({\n metadata: {\n labels: {\n pepr: "was-here",\n },\n annotations: {\n "pepr.dev": "annotations-work-too",\n },\n },\n });\n })\n .Validate(request => {\n // This Validate Action will validate the request before it is persisted to the cluster\n\n // Approve the request if the ConfigMap has the label \'pepr\'\n if (request.HasLabel("pepr")) {\n return request.Approve();\n }\n\n // Otherwise, deny the request with an error message (optional)\n return request.Deny("ConfigMap must have label \'pepr\'");\n })\n .Watch((cm, phase) => {\n // This Watch Action will watch the ConfigMap after it has been persisted to the cluster\n Log.info(cm, `ConfigMap was ${phase} with the name example-2`);\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate Action (CM Example 2a) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This action shows a simple validation that will deny any ConfigMap that has the\n * annotation `evil`. Note that the `Deny()` function takes an optional second parameter that is a\n * user-defined status code to return.\n */\nWhen(a.ConfigMap)\n .IsCreated()\n .Validate(request => {\n if (request.HasAnnotation("evil")) {\n return request.Deny("No evil CM annotations allowed.", 400);\n }\n\n return request.Approve();\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate Action (CM Example 3) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This 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 .Mutate(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// This action validates the label `change=by-label` is deleted\nWhen(a.ConfigMap)\n .IsDeleted()\n .WithLabel("change", "by-label")\n .Validate(request => {\n // Log and then always approve the request\n Log.info("CM with label \'change=by-label\' was deleted.");\n return request.Approve();\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate Action (CM Example 4) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This action show how you can use the `Mutate()` function without an inline function.\n * This is useful if you want to keep your actions small and focused on a single task,\n * or if you want to reuse the same function in multiple actions.\n */\nWhen(a.ConfigMap).IsCreated().WithName("example-4").Mutate(example4Cb);\n\n// This function uses the complete type definition, but is not required.\nfunction example4Cb(cm: PeprMutateRequest<a.ConfigMap>): void {\n cm.SetLabel("pepr.dev/first", "true");\n cm.SetLabel("pepr.dev/second", "true");\n cm.SetLabel("pepr.dev/third", "true");\n}\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate 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).IsCreated().InNamespace("pepr-demo-2").WithName("example-4a").Mutate(example4Cb);\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate Action (CM Example 5) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This 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 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://icanhazdadjoke.com/");\n * const joke = await fetch("https://icanhazdadjoke.com/") as TheChuckNorrisJoke;\n * ```\n *\n * Alternatively, you can drop the type completely:\n *\n * ```ts\n * fetch("https://icanhazdadjoke.com")\n * ```\n */\ninterface TheChuckNorrisJoke {\n id: string;\n joke: string;\n status: number;\n}\n\nWhen(a.ConfigMap)\n .IsCreatedOrUpdated()\n .WithLabel("chuck-norris")\n .Mutate(cm => cm.SetLabel("got-jokes", "true"))\n .Watch(async cm => {\n const jokeURL = "https://icanhazdadjoke.com";\n\n const mockAgent: MockAgent = new MockAgent();\n setGlobalDispatcher(mockAgent);\n const mockClient = mockAgent.get(jokeURL);\n mockClient.intercept({ path: "/", method: "GET" }).reply(\n 200,\n {\n id: "R7UfaahVfFd",\n joke: "Funny joke goes here.",\n status: 200,\n },\n {\n headers: {\n "Content-Type": "application/json; charset=utf-8",\n },\n },\n );\n\n // Try/catch is not needed as a response object will always be returned\n const response = await fetch<TheChuckNorrisJoke>(jokeURL, {\n headers: {\n Accept: "application/json",\n },\n });\n\n // Instead, check the `response.ok` field\n if (response.ok) {\n const { joke } = response.data;\n // Add Joke to the Store\n await Store.setItemAndWait(jokeURL, joke);\n // Add the Chuck Norris joke to the configmap\n try {\n await K8s(kind.ConfigMap).Apply({\n metadata: {\n name: cm.metadata.name,\n namespace: cm.metadata.namespace,\n },\n data: {\n "chuck-says": Store.getItem(jokeURL),\n },\n });\n } catch (error) {\n Log.error(error, "Failed to apply ConfigMap using server-side apply.", {\n cm,\n });\n }\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 * Mutate 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 action is executed.\n */\nWhen(a.Secret)\n .IsCreated()\n .WithName("secret-1")\n .Mutate(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 * Mutate 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 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 to 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 .Mutate(request => {\n request.Merge({\n spec: {\n message: "Hello Pepr without type data!",\n counter: Math.random(),\n },\n });\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate 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 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 actions, but we are putting it here for demonstration purposes.\n *\n * You will need to 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 .Mutate(request => {\n request.Merge({\n spec: {\n message: "Hello Pepr with type data!",\n counter: Math.random(),\n },\n });\n });\n\n/**\n * A callback function that is called once the Pepr Store is fully loaded.\n */\nStore.onReady(data => {\n Log.info(data, "Pepr Store Ready");\n});\n';
8878
- 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" }, files: ["/dist", "/src", "!src/**/*.test.ts", "!src/fixtures/**", "!dist/**/*.test.d.ts*"], version: "0.52.2-nightly.1", main: "dist/lib.js", types: "dist/lib.d.ts", scripts: { build: "tsc -p config/tsconfig.root.json && node build.mjs && npm pack", "build:image": "npm run build && docker buildx build --output type=docker --tag pepr:dev .", "build:image:unicorn": "npm run build && docker buildx build --output type=docker --tag pepr/private:dev $(node scripts/read-unicorn-build-args.mjs) .", ci: "npm ci", "format:check": "npm run format:src && npm run format:tests && npm run format:markdown && npm run format:integration && npm run format:prettier -- --check", "format:fix": "npm run format:src -- --fix && npm run format:markdown -- --fix && npm run format:integration -- --fix && npm run format:prettier -- --write", "format:integration": "eslint --config config/eslint.integration.config.mjs integration/cli integration/helpers", "format:markdown": 'npx -y markdownlint-cli --config config/.markdownlint.json --ignore adr --ignore integration/testroot --ignore pepr-test-module --ignore node_modules "**/*.md"', "format:prettier": "prettier --config config/.prettierrc src integration/cli/**/*.ts integration/helpers/**/*.ts", "format:src": "eslint --config config/eslint.root.config.mjs 'src/**/*.ts' --ignore-pattern '**/*.test.ts' --ignore-pattern 'src/templates/**'", "format:tests": "eslint --config config/eslint.test.config.mjs 'src/**/*.test.ts'", "gen-data-json": "node hack/build-template-data.js", prebuild: "rm -fr dist/* && npm run gen-data-json", prepare: `if [ "$NODE_ENV" != 'production' ]; then husky; fi`, "set:version": "node scripts/set-version.js", test: "npm run test:unit && npm run test:journey && npm run test:journey-wasm", "test:artifacts": "npm run build && vitest run src/build-artifact.test.ts", "test:docs": "vitest run --config=config/vitest.integration.config.ts integration/cli/docs/*.test.ts", "test:integration": "npm run test:integration:prep && npm run test:integration:run", "test:integration:prep": "./integration/prep.sh", "test:integration:run": "vitest run --config=config/vitest.integration.config.ts integration", "test:journey": "npm run test:journey:k3d && npm run build && npm run test:journey:image && npm run test:journey:run", "test:journey-wasm": "npm run test:journey:k3d && npm run build && npm run test:journey:image && npm run test:journey:run-wasm", "test:journey-wasm:unicorn": "npm run test:journey:k3d && npm run build && npm run test:journey:image:unicorn && npm run test:journey:run-wasm", "test:journey:image": "npm run build && docker buildx build --output type=docker --tag pepr:dev . && k3d image import pepr:dev -c pepr-dev", "test:journey:image:unicorn": "npm run build && docker buildx build --output type=docker --tag pepr/private:dev $(node scripts/read-unicorn-build-args.mjs) . && k3d image import pepr/private:dev -c pepr-dev", "test:journey:k3d": "k3d cluster delete pepr-dev && k3d cluster create pepr-dev --k3s-arg '--debug@server:0' --wait && kubectl rollout status deployment -n kube-system", "test:journey:run": "vitest run --config=config/vitest.journey.config.ts journey/entrypoint.test.ts", "test:journey:run-wasm": "vitest run --config=config/vitest.journey.config.ts journey/entrypoint-wasm.test.ts", "test:journey:unicorn": "npm run test:journey:k3d && npm run test:journey:image:unicorn && npm run test:journey:run", "test:unit": "npm run gen-data-json && NODE_OPTIONS=--no-deprecation vitest --config config/vitest.root.config.ts run --coverage", "test:upgrade:unicorn": "npm run test:journey:k3d && npm run test:journey:image:unicorn && vitest run integration/cluster/upgrade.test.ts", "test:upgrade:upstream": "npm run test:journey:k3d && npm run test:journey:image && vitest run integration/cluster/upgrade.test.ts" }, dependencies: { "@types/ramda": "0.30.2", commander: "14.0.0", express: "5.1.0", "fast-json-patch": "3.1.1", heredoc: "^1.3.1", "http-status-codes": "^2.3.0", "json-pointer": "^0.6.2", "kubernetes-fluent-client": "3.9.0", pino: "9.7.0", "pino-pretty": "13.0.0", "prom-client": "15.1.3", ramda: "0.31.3", sigstore: "3.1.0", "ts-morph": "^26.0.0" }, devDependencies: { "@commitlint/cli": "19.8.1", "@commitlint/config-conventional": "19.8.1", "@fast-check/vitest": "^0.2.1", "@types/eslint": "9.6.1", "@types/express": "5.0.3", "@types/json-pointer": "^1.0.34", "@types/node": "24.x.x", "@types/node-forge": "1.3.13", "@types/uuid": "10.0.0", "@types/ws": "^8.18.1", "@vitest/coverage-v8": "^3.2.3", "fast-check": "^4.0.0", globals: "^16.0.0", husky: "^9.1.6", "js-yaml": "^4.1.0", shellcheck: "^3.0.0", tsx: "^4.20.3", undici: "^7.0.1", vitest: "^3.2.3" }, overrides: { glob: "^9.0.0" }, peerDependencies: { "@types/prompts": "2.4.9", "@typescript-eslint/eslint-plugin": "8.33.0", "@typescript-eslint/parser": "8.33.0", esbuild: "0.25.5", eslint: "^9.26.0", "node-forge": "1.3.1", prettier: "3.5.3", prompts: "2.4.2", typescript: "5.8.3", uuid: "11.1.0" } };
8879
-
8880
- // src/cli/init/utils.ts
8881
- var import_fs4 = require("fs");
8882
- function sanitizeName(name2) {
8883
- if (typeof name2 !== "string") {
8884
- throw TypeError(
8885
- `sanitizeName() was called with a non-string value. The value is: ${name2} of type ${typeof name2}`
8886
- );
8887
- }
8888
- let sanitized = name2.toLowerCase().replace(/[^a-z0-9-]+/gi, "-");
8889
- sanitized = sanitized.replace(/^-+|-+$/g, "");
8890
- sanitized = sanitized.replace(/--+/g, "-");
8891
- return sanitized;
8892
- }
8893
- async function createDir(dir) {
8894
- try {
8895
- await import_fs4.promises.mkdir(dir);
8896
- } catch (err) {
8897
- if (err && err.code === "EEXIST") {
8898
- throw new Error(`Directory ${dir} already exists`);
8899
- } else {
8900
- throw err;
8901
- }
8902
- }
8903
- }
8904
- function write(path4, data) {
8905
- if (typeof data !== "string") {
8906
- data = JSON.stringify(data, null, 2);
8907
- }
8908
- return import_fs4.promises.writeFile(path4, data);
8909
- }
8910
-
8911
- // src/cli/init/templates.ts
8912
- var { dependencies, devDependencies, peerDependencies, scripts, version } = packageJSON;
8913
- function genPkgJSON(opts) {
8914
- const uuid = !opts.uuid ? (0, import_uuid.v4)() : opts.uuid;
8915
- const name2 = sanitizeName(opts.name);
8916
- const { typescript } = peerDependencies;
8917
- const data = {
8918
- name: name2,
8919
- version: "0.0.1",
8920
- description: opts.description,
8921
- keywords: ["pepr", "k8s", "policy-engine", "pepr-module", "security"],
8922
- engines: {
8923
- node: ">=20.0.0"
8924
- },
8925
- pepr: {
8926
- uuid,
8927
- onError: opts.errorBehavior,
8928
- webhookTimeout: 10,
8929
- customLabels: {
8930
- namespace: {
8931
- "pepr.dev": ""
8932
- }
8933
- },
8934
- alwaysIgnore: {
8935
- namespaces: []
8936
- },
8937
- admission: {
8938
- alwaysIgnore: {
8939
- namespaces: []
8940
- }
8941
- },
8942
- watch: {
8943
- alwaysIgnore: {
8944
- namespaces: []
8945
- }
8946
- },
8947
- includedFiles: [],
8948
- env: {}
8949
- },
8950
- scripts: {
8951
- "k3d-setup": scripts["test:journey:k3d"]
8952
- },
8953
- dependencies: {
8954
- pepr: version,
8955
- undici: "^7.0.1"
8956
- },
8957
- devDependencies: {
8958
- typescript
8959
- },
8960
- overrides: {
8961
- "brace-expansion": "1.1.11"
8962
- }
8963
- };
8964
- return {
8965
- data,
8966
- path: "package.json",
8967
- print: (0, import_util.inspect)(data, false, 5, true)
8968
- };
8969
- }
8970
- var peprTSTemplate = {
8971
- path: "pepr.ts",
8972
- data: peprTS
8973
- };
8974
- var readme = {
8975
- path: "README.md",
8976
- data: readmeMd
8977
- };
8978
- var helloPepr = {
8979
- path: "hello-pepr.ts",
8980
- data: helloPeprTS
8981
- };
8982
- var gitignore = {
8983
- path: ".gitignore",
8984
- data: gitIgnore
8985
- };
8986
- var samplesYaml = {
8987
- path: "hello-pepr.samples.yaml",
8988
- data: hello_pepr_samples_default.map((r) => (0, import_client_node3.dumpYaml)(r, { noRefs: true })).join("---\n")
8989
- };
8990
- var snippet = {
8991
- path: "pepr.code-snippets",
8992
- data: pepr_code_snippets_default
8993
- };
8994
- var codeSettings = {
8995
- path: "settings.json",
8996
- data: settings_default
8997
- };
8998
- var tsConfig = {
8999
- path: "tsconfig.json",
9000
- data: tsconfig_module_default
9001
- };
9002
- var prettier = {
9003
- path: ".prettierrc",
9004
- data: prettierrc_default
9005
- };
9006
- var eslint = {
9007
- path: "eslint.config.mjs",
9008
- data: (0, import_fs5.readFileSync)(
9009
- import_path2.default.resolve(
9010
- (() => {
9011
- const fullPath = __dirname;
9012
- const lengthOfSuffix = "pepr/".length;
9013
- const lastPeprIndex = fullPath.lastIndexOf("pepr/");
9014
- return fullPath.substring(0, lastPeprIndex + lengthOfSuffix);
9015
- })(),
9016
- "src/templates/eslint.config.mjs"
9017
- ),
9018
- "utf-8"
9019
- )
9020
- };
9021
-
9022
- // src/cli/build.ts
9023
- var import_commander = require("commander");
9024
-
9025
- // src/cli/format/index.ts
9026
- var import_eslint = require("eslint");
9027
-
9028
- // src/cli/format/format.helpers.ts
9029
- var import_fs6 = require("fs");
9030
- var import_prettier = require("prettier");
9031
- async function formatWithPrettier(results, validateOnly) {
9032
- let hasFailure = false;
9033
- for (const { filePath } of results) {
9034
- const content = await import_fs6.promises.readFile(filePath, "utf8");
9035
- const cfg = await (0, import_prettier.resolveConfig)(filePath);
9036
- const formatted = await (0, import_prettier.format)(content, { filepath: filePath, ...cfg });
9037
- if (validateOnly && formatted !== content) {
9038
- hasFailure = true;
9039
- console.error(`File ${filePath} is not formatted correctly`);
9040
- } else {
9041
- await import_fs6.promises.writeFile(filePath, formatted);
9042
- }
9043
- }
9044
- return hasFailure;
9045
- }
9046
-
9047
- // src/cli/format/index.ts
9048
- function format_default(program2) {
9049
- program2.command("format").description("Lint and format this Pepr module").option("-v, --validate-only", "Do not modify files, only validate formatting.").action(async (opts) => {
9050
- const success = await peprFormat(opts.validateOnly);
9051
- if (success) {
9052
- logger_default.info("Module formatted");
9053
- } else {
9054
- process.exit(1);
9055
- }
9056
- });
9057
- }
9058
- async function peprFormat(validateOnly) {
9059
- {
9060
- try {
9061
- const eslint2 = new import_eslint.ESLint();
9062
- const results = await eslint2.lintFiles(["./**/*.ts"]);
9063
- let hasFailure = false;
9064
- results.forEach(async (result) => {
9065
- const errorCount = result.fatalErrorCount + result.errorCount;
9066
- if (errorCount > 0) {
9067
- hasFailure = true;
9068
- }
9069
- });
9070
- const formatter = await eslint2.loadFormatter("stylish");
9071
- const resultText = await formatter.format(results, {});
9072
- if (resultText) {
9073
- logger_default.info(resultText);
9074
- }
9075
- if (!validateOnly) {
9076
- await import_eslint.ESLint.outputFixes(results);
9077
- }
9078
- hasFailure = hasFailure || await formatWithPrettier(results, validateOnly);
9079
- return !hasFailure;
9080
- } catch (error) {
9081
- logger_default.error(error, `Error formatting module:`);
9082
- return false;
9083
- }
9084
- }
9085
- }
9086
-
9087
- // src/lib/included-files.ts
9088
- var import_fs7 = require("fs");
9089
- async function createDockerfile(version3, description, includedFiles) {
9090
- const file = `
9091
- # Use an official Node.js runtime as the base image
9092
- FROM ghcr.io/defenseunicorns/pepr/controller:v${version3}
9093
-
9094
- LABEL description="${description}"
9095
-
9096
- # Add the included files to the image
9097
- ${includedFiles.map((f) => `ADD ${f} ${f}`).join("\n")}
9098
-
9099
- `;
9100
- await import_fs7.promises.writeFile("Dockerfile.controller", file, { encoding: "utf-8" });
9101
- }
9102
-
9103
- // src/cli/build.helpers.ts
9104
- var import_child_process2 = require("child_process");
9105
- var import_esbuild = require("esbuild");
9106
- var import_path3 = require("path");
9107
- var import_fs9 = require("fs");
9108
-
9109
- // src/lib/assets/yaml/generateAllYaml.ts
9110
- var import_crypto2 = __toESM(require("crypto"));
9111
- var import_client_node4 = require("@kubernetes/client-node");
9112
-
9113
- // src/lib/assets/k8sObjects.ts
9114
- var import_zlib = require("zlib");
9115
- function getNamespace(namespaceLabels) {
9116
- if (namespaceLabels) {
9117
- return {
9118
- apiVersion: "v1",
9119
- kind: "Namespace",
9120
- metadata: {
9121
- name: "pepr-system",
9122
- labels: namespaceLabels ?? {}
9123
- }
9124
- };
9125
- } else {
9126
- return {
9127
- apiVersion: "v1",
9128
- kind: "Namespace",
9129
- metadata: {
9130
- name: "pepr-system"
9131
- }
9132
- };
9133
- }
9134
- }
9135
- function getWatcher(assets, hash, buildTimestamp, imagePullSecret) {
9136
- const { name: name2, image, config } = assets;
9137
- if (!isWatcher(assets.capabilities)) {
9138
- return null;
9139
- }
9140
- const app = `${name2}-watcher`;
9141
- const deploy = {
9142
- apiVersion: "apps/v1",
9143
- kind: "Deployment",
9144
- metadata: {
9145
- name: app,
9146
- namespace: "pepr-system",
9147
- annotations: {
9148
- "pepr.dev/description": config.description || ""
9149
- },
9150
- labels: {
9151
- app,
9152
- "pepr.dev/controller": "watcher",
9153
- "pepr.dev/uuid": config.uuid
8693
+ app,
8694
+ "pepr.dev/controller": "watcher",
8695
+ "pepr.dev/uuid": config.uuid
9154
8696
  }
9155
8697
  },
9156
8698
  spec: {
@@ -9406,472 +8948,836 @@ function getDeployment(assets, hash, buildTimestamp, imagePullSecret) {
9406
8948
  }
9407
8949
  }
9408
8950
  };
9409
- if (imagePullSecret) {
9410
- deploy.spec.template.spec.imagePullSecrets = [{ name: imagePullSecret }];
8951
+ if (imagePullSecret) {
8952
+ deploy.spec.template.spec.imagePullSecrets = [{ name: imagePullSecret }];
8953
+ }
8954
+ return deploy;
8955
+ }
8956
+ function getModuleSecret(name2, data, hash) {
8957
+ const compressed = (0, import_zlib.gzipSync)(data);
8958
+ const path4 = `module-${hash}.js.gz`;
8959
+ const compressedData = compressed.toString("base64");
8960
+ if (secretOverLimit(compressedData)) {
8961
+ const error = new Error(`Module secret for ${name2} is over the 1MB limit`);
8962
+ throw error;
8963
+ } else {
8964
+ return {
8965
+ apiVersion: "v1",
8966
+ kind: "Secret",
8967
+ metadata: {
8968
+ name: `${name2}-module`,
8969
+ namespace: "pepr-system"
8970
+ },
8971
+ type: "Opaque",
8972
+ data: {
8973
+ [path4]: compressed.toString("base64")
8974
+ }
8975
+ };
8976
+ }
8977
+ }
8978
+ function service(name2, assets) {
8979
+ if (!isAdmission(assets.capabilities) && !norWatchOrAdmission(assets.capabilities)) {
8980
+ return null;
8981
+ }
8982
+ return {
8983
+ apiVersion: "v1",
8984
+ kind: "Service",
8985
+ metadata: {
8986
+ name: name2,
8987
+ namespace: "pepr-system",
8988
+ labels: {
8989
+ "pepr.dev/controller": "admission"
8990
+ }
8991
+ },
8992
+ spec: {
8993
+ selector: {
8994
+ app: name2,
8995
+ "pepr.dev/controller": "admission"
8996
+ },
8997
+ ports: [
8998
+ {
8999
+ port: 443,
9000
+ targetPort: 3e3
9001
+ }
9002
+ ]
9003
+ }
9004
+ };
9005
+ }
9006
+ function watcherService(name2, assets) {
9007
+ if (!isWatcher(assets.capabilities)) {
9008
+ return null;
9009
+ }
9010
+ return {
9011
+ apiVersion: "v1",
9012
+ kind: "Service",
9013
+ metadata: {
9014
+ name: `${name2}-watcher`,
9015
+ namespace: "pepr-system",
9016
+ labels: {
9017
+ "pepr.dev/controller": "watcher"
9018
+ }
9019
+ },
9020
+ spec: {
9021
+ selector: {
9022
+ app: `${name2}-watcher`,
9023
+ "pepr.dev/controller": "watcher"
9024
+ },
9025
+ ports: [
9026
+ {
9027
+ port: 443,
9028
+ targetPort: 3e3
9029
+ }
9030
+ ]
9031
+ }
9032
+ };
9033
+ }
9034
+
9035
+ // src/lib/assets/yaml/generateAllYaml.ts
9036
+ var import_fs5 = require("fs");
9037
+
9038
+ // src/lib/assets/webhooks.ts
9039
+ var import_ramda = require("ramda");
9040
+ var peprIgnoreNamespaces = ["kube-system", "pepr-system"];
9041
+ var validateRule = (binding, isMutateWebhook) => {
9042
+ const { event, kind: kind8, isMutate, isValidate } = binding;
9043
+ if (isMutateWebhook && !isMutate || !isMutateWebhook && !isValidate) {
9044
+ return void 0;
9045
+ }
9046
+ const operations = event === "CREATEORUPDATE" /* CREATE_OR_UPDATE */ ? ["CREATE" /* CREATE */, "UPDATE" /* UPDATE */] : [event];
9047
+ const resource = kind8.plural || `${kind8.kind.toLowerCase()}s`;
9048
+ const ruleObject = {
9049
+ apiGroups: [kind8.group],
9050
+ apiVersions: [kind8.version || "*"],
9051
+ operations,
9052
+ resources: [resource, ...resource === "pods" ? ["pods/ephemeralcontainers"] : []]
9053
+ };
9054
+ return ruleObject;
9055
+ };
9056
+ async function generateWebhookRules(assets, isMutateWebhook) {
9057
+ const { config, capabilities } = assets;
9058
+ const rules = capabilities.flatMap((capability) => {
9059
+ logger_default.info(`Module ${config.uuid} has capability: ${capability.name}`);
9060
+ return capability.bindings.map((binding) => validateRule(binding, isMutateWebhook)).filter((rule) => !!rule);
9061
+ });
9062
+ return (0, import_ramda.uniqWith)(import_ramda.equals, rules);
9063
+ }
9064
+ async function webhookConfigGenerator(assets, mutateOrValidate, timeoutSeconds = 10) {
9065
+ const ignore = [];
9066
+ const { name: name2, tls, config, apiPath, host } = assets;
9067
+ const ignoreNS = (0, import_ramda.concat)(
9068
+ peprIgnoreNamespaces,
9069
+ resolveIgnoreNamespaces(
9070
+ config?.alwaysIgnore?.namespaces?.length ? config?.alwaysIgnore?.namespaces : config?.admission?.alwaysIgnore?.namespaces
9071
+ )
9072
+ );
9073
+ if (ignoreNS) {
9074
+ ignore.push({
9075
+ key: "kubernetes.io/metadata.name",
9076
+ operator: "NotIn",
9077
+ values: ignoreNS
9078
+ });
9079
+ }
9080
+ const clientConfig = {
9081
+ caBundle: tls.ca
9082
+ };
9083
+ const fullApiPath = `/${mutateOrValidate}/${apiPath}`;
9084
+ if (host) {
9085
+ clientConfig.url = `https://${host}:3000${fullApiPath}`;
9086
+ } else {
9087
+ clientConfig.service = {
9088
+ name: name2,
9089
+ namespace: "pepr-system",
9090
+ path: fullApiPath
9091
+ };
9092
+ }
9093
+ const isMutate = mutateOrValidate === "mutate" /* MUTATE */;
9094
+ const rules = await generateWebhookRules(assets, isMutate);
9095
+ if (rules.length < 1) {
9096
+ return null;
9097
+ }
9098
+ return {
9099
+ apiVersion: "admissionregistration.k8s.io/v1",
9100
+ kind: isMutate ? "MutatingWebhookConfiguration" : "ValidatingWebhookConfiguration",
9101
+ metadata: { name: name2 },
9102
+ webhooks: [
9103
+ {
9104
+ name: `${name2}.pepr.dev`,
9105
+ admissionReviewVersions: ["v1", "v1beta1"],
9106
+ clientConfig,
9107
+ failurePolicy: config.onError === "reject" ? "Fail" : "Ignore",
9108
+ matchPolicy: "Equivalent",
9109
+ timeoutSeconds,
9110
+ namespaceSelector: {
9111
+ matchExpressions: ignore
9112
+ },
9113
+ rules,
9114
+ // @todo: track side effects state
9115
+ sideEffects: "None"
9116
+ }
9117
+ ]
9118
+ };
9119
+ }
9120
+
9121
+ // src/lib/assets/yaml/generateAllYaml.ts
9122
+ function pushControllerManifests(resources, deployments, services) {
9123
+ if (deployments.watch) {
9124
+ resources.push(deployments.watch);
9125
+ }
9126
+ if (deployments.admission) {
9127
+ resources.push(deployments.admission);
9128
+ }
9129
+ if (services.admission) {
9130
+ resources.push(services.admission);
9131
+ }
9132
+ if (services.watch) {
9133
+ resources.push(services.watch);
9134
+ }
9135
+ return resources;
9136
+ }
9137
+ async function generateAllYaml(assets, deployments, services) {
9138
+ const { name: name2, tls, apiPath, path: path4, config } = assets;
9139
+ const code = await import_fs5.promises.readFile(path4);
9140
+ const hash = import_crypto2.default.createHash("sha256").update(code).digest("hex");
9141
+ let resources = [
9142
+ getNamespace(assets.config.customLabels?.namespace),
9143
+ clusterRole(name2, assets.capabilities, config.rbacMode, config.rbac),
9144
+ clusterRoleBinding(name2),
9145
+ serviceAccount(name2),
9146
+ apiPathSecret(name2, apiPath),
9147
+ tlsSecret(name2, tls),
9148
+ getModuleSecret(name2, code, hash),
9149
+ storeRole(name2),
9150
+ storeRoleBinding(name2)
9151
+ ];
9152
+ resources = pushControllerManifests(resources, deployments, services);
9153
+ const webhooks = {
9154
+ mutate: await webhookConfigGenerator(assets, "mutate" /* MUTATE */, assets.config.webhookTimeout),
9155
+ validate: await webhookConfigGenerator(
9156
+ assets,
9157
+ "validate" /* VALIDATE */,
9158
+ assets.config.webhookTimeout
9159
+ )
9160
+ };
9161
+ const additionalResources = [webhooks.mutate, webhooks.validate].filter(
9162
+ (resource) => resource !== null && resource !== void 0
9163
+ );
9164
+ resources.push(...additionalResources);
9165
+ return resources.map((resource) => (0, import_client_node3.dumpYaml)(resource, { noRefs: true })).join("---\n");
9166
+ }
9167
+
9168
+ // src/lib/assets/yaml/generateZarfYaml.ts
9169
+ var import_client_node4 = require("@kubernetes/client-node");
9170
+ function generateZarfYamlGeneric(assets, path4, type) {
9171
+ const zarfComponentName = process.env.PEPR_CUSTOM_BUILD_NAME ?? "module";
9172
+ const manifestSettings = {
9173
+ name: zarfComponentName,
9174
+ namespace: "pepr-system",
9175
+ files: [path4]
9176
+ };
9177
+ const chartSettings = {
9178
+ name: zarfComponentName,
9179
+ namespace: "pepr-system",
9180
+ version: `${assets.config.appVersion || "0.0.1"}`,
9181
+ localPath: path4
9182
+ };
9183
+ const component = {
9184
+ name: zarfComponentName,
9185
+ required: true,
9186
+ images: [assets.image],
9187
+ [type]: [type === "manifests" ? manifestSettings : chartSettings]
9188
+ };
9189
+ const zarfCfg = {
9190
+ kind: "ZarfPackageConfig",
9191
+ metadata: {
9192
+ name: assets.name,
9193
+ description: `Pepr Module: ${assets.config.description}`,
9194
+ url: "https://github.com/defenseunicorns/pepr",
9195
+ version: `${assets.config.appVersion || "0.0.1"}`
9196
+ },
9197
+ components: [component]
9198
+ };
9199
+ return (0, import_client_node4.dumpYaml)(zarfCfg, { noRefs: true });
9200
+ }
9201
+
9202
+ // src/cli/build/build.helpers.ts
9203
+ function assignImage(imageOptions) {
9204
+ const { customImage, registryInfo, peprVersion, registry } = imageOptions;
9205
+ if (customImage) {
9206
+ return customImage;
9411
9207
  }
9412
- return deploy;
9208
+ if (registryInfo) {
9209
+ return `${registryInfo}/custom-pepr-controller:${peprVersion}`;
9210
+ }
9211
+ if (registry) {
9212
+ return checkIronBankImage(registry, "", peprVersion);
9213
+ }
9214
+ return "";
9413
9215
  }
9414
- function getModuleSecret(name2, data, hash) {
9415
- const compressed = (0, import_zlib.gzipSync)(data);
9416
- const path4 = `module-${hash}.js.gz`;
9417
- const compressedData = compressed.toString("base64");
9418
- if (secretOverLimit(compressedData)) {
9419
- const error = new Error(`Module secret for ${name2} is over the 1MB limit`);
9420
- throw error;
9216
+ function determineRbacMode(opts, cfg) {
9217
+ if (opts.rbacMode) {
9218
+ return opts.rbacMode;
9219
+ }
9220
+ if (cfg.pepr.rbacMode && cfg.pepr.rbacMode !== "scoped") {
9221
+ return "admin";
9222
+ }
9223
+ return cfg.pepr.rbacMode || "admin";
9224
+ }
9225
+ async function createOutputDirectory(outputDir) {
9226
+ try {
9227
+ const dir = outputDir === "" ? "dist" : outputDir;
9228
+ await createDirectoryIfNotExists(dir);
9229
+ return dir;
9230
+ } catch (error) {
9231
+ console.error(`Error creating output directory: ${error.message}`);
9232
+ process.exit(1);
9233
+ }
9234
+ }
9235
+ function checkIronBankImage(registry, image, peprVersion) {
9236
+ return registry === "Iron Bank" ? `registry1.dso.mil/ironbank/opensource/defenseunicorns/pepr/controller:v${peprVersion}` : image;
9237
+ }
9238
+ function validImagePullSecret(imagePullSecretName) {
9239
+ if (imagePullSecretName) {
9240
+ const error = "Invalid imagePullSecret. Please provide a valid name as defined in RFC 1123.";
9241
+ if (sanitizeResourceName(imagePullSecretName) !== imagePullSecretName) {
9242
+ console.error(error);
9243
+ process.exit(1);
9244
+ }
9245
+ }
9246
+ }
9247
+ async function handleCustomImageBuild(includedFiles, peprVersion, description, image) {
9248
+ if (includedFiles.length > 0) {
9249
+ await createDockerfile(peprVersion, description, includedFiles);
9250
+ (0, import_child_process2.execSync)(`docker build --tag ${image} -f Dockerfile.controller .`, {
9251
+ stdio: "inherit"
9252
+ });
9253
+ (0, import_child_process2.execSync)(`docker push ${image}`, { stdio: "inherit" });
9254
+ }
9255
+ }
9256
+ function handleValidCapabilityNames(capabilities) {
9257
+ try {
9258
+ validateCapabilityNames(capabilities);
9259
+ } catch (e) {
9260
+ console.error(`Error loading capability:`, e);
9261
+ process.exit(1);
9262
+ }
9263
+ }
9264
+ async function watchForChanges(ctxCfg, reloader) {
9265
+ const ctx = await (0, import_esbuild.context)(ctxCfg);
9266
+ if (reloader) {
9267
+ await ctx.watch();
9421
9268
  } else {
9422
- return {
9423
- apiVersion: "v1",
9424
- kind: "Secret",
9425
- metadata: {
9426
- name: `${name2}-module`,
9427
- namespace: "pepr-system"
9269
+ await ctx.rebuild();
9270
+ await ctx.dispose();
9271
+ }
9272
+ return ctx;
9273
+ }
9274
+ async function generateYamlAndWriteToDisk(obj) {
9275
+ const { uuid, imagePullSecret, outputDir, assets, zarf } = obj;
9276
+ const yamlFile = `pepr-module-${uuid}.yaml`;
9277
+ const chartPath = `${uuid}-chart`;
9278
+ const yamlPath = (0, import_path2.resolve)(outputDir, yamlFile);
9279
+ try {
9280
+ const yaml = await assets.allYaml(
9281
+ generateAllYaml,
9282
+ {
9283
+ getDeploymentFunction: getDeployment,
9284
+ getWatcherFunction: getWatcher,
9285
+ getServiceFunction: service,
9286
+ getWatcherServiceFunction: watcherService
9428
9287
  },
9429
- type: "Opaque",
9430
- data: {
9431
- [path4]: compressed.toString("base64")
9432
- }
9433
- };
9288
+ imagePullSecret
9289
+ );
9290
+ const zarfPath = (0, import_path2.resolve)(outputDir, "zarf.yaml");
9291
+ let localZarf = "";
9292
+ if (zarf === "chart") {
9293
+ localZarf = assets.zarfYamlChart(generateZarfYamlGeneric, chartPath);
9294
+ } else {
9295
+ localZarf = assets.zarfYaml(generateZarfYamlGeneric, yamlFile);
9296
+ }
9297
+ await import_fs6.promises.writeFile(yamlPath, yaml);
9298
+ await import_fs6.promises.writeFile(zarfPath, localZarf);
9299
+ await assets.generateHelmChart(webhookConfigGenerator, getWatcher, getModuleSecret, outputDir);
9300
+ console.info(`K8s resource for the module saved to ${yamlPath}`);
9301
+ } catch (error) {
9302
+ console.error(`Error generating YAML: ${error}`);
9303
+ process.exit(1);
9434
9304
  }
9435
9305
  }
9436
- function service(name2, assets) {
9437
- if (!isAdmission(assets.capabilities) && !norWatchOrAdmission(assets.capabilities)) {
9438
- return null;
9306
+
9307
+ // src/cli/build/buildModule.ts
9308
+ var import_child_process3 = require("child_process");
9309
+ var import_esbuild2 = require("esbuild");
9310
+ var import_path4 = require("path");
9311
+
9312
+ // src/cli/init/templates.ts
9313
+ var import_client_node5 = require("@kubernetes/client-node");
9314
+ var import_util = require("util");
9315
+ var import_uuid = require("uuid");
9316
+ var import_fs8 = require("fs");
9317
+ var import_path3 = __toESM(require("path"));
9318
+
9319
+ // src/templates/pepr.code-snippets.json
9320
+ var pepr_code_snippets_default = {
9321
+ "Create a new Pepr capability": {
9322
+ prefix: "create pepr capability",
9323
+ body: [
9324
+ "import { Capability, a } from 'pepr';",
9325
+ "",
9326
+ "export const ${TM_FILENAME_BASE/(.*)/${1:/pascalcase}/} = new Capability({",
9327
+ " name: '${TM_FILENAME_BASE}',",
9328
+ " description: '${1:A brief description of this capability.}',",
9329
+ " namespaces: [${2:}],",
9330
+ "});",
9331
+ "",
9332
+ "// Use the 'When' function to create a new action",
9333
+ "const { When } = ${TM_FILENAME_BASE/(.*)/${1:/pascalcase}/};",
9334
+ "",
9335
+ "// When(a.<Kind>).Is<Event>().Then(change => change.<changes>",
9336
+ "When(${3:})"
9337
+ ],
9338
+ description: "Creates a new Pepr capability with a specified description, optional namespaces, and adds a When statement for the specified value."
9439
9339
  }
9440
- return {
9340
+ };
9341
+
9342
+ // src/templates/.prettierrc.json
9343
+ var prettierrc_default = {
9344
+ arrowParens: "avoid",
9345
+ bracketSameLine: false,
9346
+ bracketSpacing: true,
9347
+ embeddedLanguageFormatting: "auto",
9348
+ insertPragma: false,
9349
+ printWidth: 100,
9350
+ quoteProps: "as-needed",
9351
+ requirePragma: false,
9352
+ semi: true,
9353
+ tabWidth: 2,
9354
+ useTabs: false,
9355
+ vueIndentScriptAndStyle: false
9356
+ };
9357
+
9358
+ // src/templates/capabilities/hello-pepr.samples.json
9359
+ var hello_pepr_samples_default = [
9360
+ {
9361
+ apiVersion: "v1",
9362
+ kind: "Namespace",
9363
+ metadata: {
9364
+ name: "pepr-demo",
9365
+ labels: {
9366
+ "keep-me": "please",
9367
+ "remove-me": "please"
9368
+ }
9369
+ }
9370
+ },
9371
+ {
9372
+ apiVersion: "v1",
9373
+ kind: "Namespace",
9374
+ metadata: {
9375
+ name: "pepr-demo-2"
9376
+ }
9377
+ },
9378
+ {
9379
+ apiVersion: "v1",
9380
+ kind: "Secret",
9381
+ metadata: {
9382
+ name: "secret-1",
9383
+ namespace: "pepr-demo"
9384
+ },
9385
+ data: {
9386
+ example: "dW5pY29ybiBtYWdpYw==",
9387
+ "binary-data": "iCZQUg8xYucNUqD+8lyl2YcKjYYygvTtiDSEV9b9WKUkxSSLFJTgIWMJ9GcFFYs4T9JCdda51u74jfq8yHzRuEASl60EdTS/NfWgIIFTGqcNRfqMw+vgpyTMmCyJVaJEDFq6AA==",
9388
+ "ascii-with-white-space": "VGhpcyBpcyBzb21lIHJhbmRvbSB0ZXh0OgoKICAgIC0gd2l0aCBsaW5lIGJyZWFrcwogICAgLSBhbmQgdGFicw=="
9389
+ }
9390
+ },
9391
+ {
9392
+ apiVersion: "v1",
9393
+ kind: "ConfigMap",
9394
+ metadata: {
9395
+ name: "example-1",
9396
+ namespace: "pepr-demo"
9397
+ },
9398
+ data: {
9399
+ key: "ex-1-val"
9400
+ }
9401
+ },
9402
+ {
9403
+ apiVersion: "v1",
9404
+ kind: "ConfigMap",
9405
+ metadata: {
9406
+ name: "example-2",
9407
+ namespace: "pepr-demo"
9408
+ },
9409
+ data: {
9410
+ key: "ex-2-val"
9411
+ }
9412
+ },
9413
+ {
9414
+ apiVersion: "v1",
9415
+ kind: "ConfigMap",
9416
+ metadata: {
9417
+ name: "example-evil-cm",
9418
+ namespace: "pepr-demo",
9419
+ annotations: {
9420
+ evil: "true"
9421
+ }
9422
+ },
9423
+ data: {
9424
+ key: "ex-evil-cm-val"
9425
+ }
9426
+ },
9427
+ {
9441
9428
  apiVersion: "v1",
9442
- kind: "Service",
9429
+ kind: "ConfigMap",
9443
9430
  metadata: {
9444
- name: name2,
9445
- namespace: "pepr-system",
9431
+ name: "example-3",
9432
+ namespace: "pepr-demo",
9446
9433
  labels: {
9447
- "pepr.dev/controller": "admission"
9434
+ change: "by-label"
9448
9435
  }
9449
9436
  },
9450
- spec: {
9451
- selector: {
9452
- app: name2,
9453
- "pepr.dev/controller": "admission"
9454
- },
9455
- ports: [
9456
- {
9457
- port: 443,
9458
- targetPort: 3e3
9459
- }
9460
- ]
9437
+ data: {
9438
+ key: "ex-3-val"
9461
9439
  }
9462
- };
9463
- }
9464
- function watcherService(name2, assets) {
9465
- if (!isWatcher(assets.capabilities)) {
9466
- return null;
9467
- }
9468
- return {
9440
+ },
9441
+ {
9469
9442
  apiVersion: "v1",
9470
- kind: "Service",
9443
+ kind: "ConfigMap",
9471
9444
  metadata: {
9472
- name: `${name2}-watcher`,
9473
- namespace: "pepr-system",
9445
+ name: "example-4",
9446
+ namespace: "pepr-demo"
9447
+ },
9448
+ data: {
9449
+ key: "ex-4-val"
9450
+ }
9451
+ },
9452
+ {
9453
+ apiVersion: "v1",
9454
+ kind: "ConfigMap",
9455
+ metadata: {
9456
+ name: "example-4a",
9457
+ namespace: "pepr-demo-2"
9458
+ },
9459
+ data: {
9460
+ key: "ex-4-val"
9461
+ }
9462
+ },
9463
+ {
9464
+ apiVersion: "v1",
9465
+ kind: "ConfigMap",
9466
+ metadata: {
9467
+ name: "example-5",
9468
+ namespace: "pepr-demo",
9474
9469
  labels: {
9475
- "pepr.dev/controller": "watcher"
9470
+ "chuck-norris": "test"
9476
9471
  }
9477
9472
  },
9478
- spec: {
9479
- selector: {
9480
- app: `${name2}-watcher`,
9481
- "pepr.dev/controller": "watcher"
9482
- },
9483
- ports: [
9484
- {
9485
- port: 443,
9486
- targetPort: 3e3
9487
- }
9488
- ]
9473
+ data: {
9474
+ key: "ex-5-val"
9489
9475
  }
9490
- };
9491
- }
9492
-
9493
- // src/lib/assets/yaml/generateAllYaml.ts
9494
- var import_fs8 = require("fs");
9495
-
9496
- // src/lib/assets/webhooks.ts
9497
- var import_ramda = require("ramda");
9498
- var peprIgnoreNamespaces = ["kube-system", "pepr-system"];
9499
- var validateRule = (binding, isMutateWebhook) => {
9500
- const { event, kind: kind8, isMutate, isValidate } = binding;
9501
- if (isMutateWebhook && !isMutate || !isMutateWebhook && !isValidate) {
9502
- return void 0;
9503
- }
9504
- const operations = event === "CREATEORUPDATE" /* CREATE_OR_UPDATE */ ? ["CREATE" /* CREATE */, "UPDATE" /* UPDATE */] : [event];
9505
- const resource = kind8.plural || `${kind8.kind.toLowerCase()}s`;
9506
- const ruleObject = {
9507
- apiGroups: [kind8.group],
9508
- apiVersions: [kind8.version || "*"],
9509
- operations,
9510
- resources: [resource, ...resource === "pods" ? ["pods/ephemeralcontainers"] : []]
9511
- };
9512
- return ruleObject;
9513
- };
9514
- async function generateWebhookRules(assets, isMutateWebhook) {
9515
- const { config, capabilities } = assets;
9516
- const rules = capabilities.flatMap((capability) => {
9517
- logger_default.info(`Module ${config.uuid} has capability: ${capability.name}`);
9518
- return capability.bindings.map((binding) => validateRule(binding, isMutateWebhook)).filter((rule) => !!rule);
9519
- });
9520
- return (0, import_ramda.uniqWith)(import_ramda.equals, rules);
9521
- }
9522
- async function webhookConfigGenerator(assets, mutateOrValidate, timeoutSeconds = 10) {
9523
- const ignore = [];
9524
- const { name: name2, tls, config, apiPath, host } = assets;
9525
- const ignoreNS = (0, import_ramda.concat)(
9526
- peprIgnoreNamespaces,
9527
- resolveIgnoreNamespaces(
9528
- config?.alwaysIgnore?.namespaces?.length ? config?.alwaysIgnore?.namespaces : config?.admission?.alwaysIgnore?.namespaces
9529
- )
9530
- );
9531
- if (ignoreNS) {
9532
- ignore.push({
9533
- key: "kubernetes.io/metadata.name",
9534
- operator: "NotIn",
9535
- values: ignoreNS
9536
- });
9537
- }
9538
- const clientConfig = {
9539
- caBundle: tls.ca
9540
- };
9541
- const fullApiPath = `/${mutateOrValidate}/${apiPath}`;
9542
- if (host) {
9543
- clientConfig.url = `https://${host}:3000${fullApiPath}`;
9544
- } else {
9545
- clientConfig.service = {
9546
- name: name2,
9547
- namespace: "pepr-system",
9548
- path: fullApiPath
9549
- };
9550
- }
9551
- const isMutate = mutateOrValidate === "mutate" /* MUTATE */;
9552
- const rules = await generateWebhookRules(assets, isMutate);
9553
- if (rules.length < 1) {
9554
- return null;
9555
- }
9556
- return {
9557
- apiVersion: "admissionregistration.k8s.io/v1",
9558
- kind: isMutate ? "MutatingWebhookConfiguration" : "ValidatingWebhookConfiguration",
9559
- metadata: { name: name2 },
9560
- webhooks: [
9561
- {
9562
- name: `${name2}.pepr.dev`,
9563
- admissionReviewVersions: ["v1", "v1beta1"],
9564
- clientConfig,
9565
- failurePolicy: config.onError === "reject" ? "Fail" : "Ignore",
9566
- matchPolicy: "Equivalent",
9567
- timeoutSeconds,
9568
- namespaceSelector: {
9569
- matchExpressions: ignore
9570
- },
9571
- rules,
9572
- // @todo: track side effects state
9573
- sideEffects: "None"
9574
- }
9575
- ]
9576
- };
9577
- }
9578
-
9579
- // src/lib/assets/yaml/generateAllYaml.ts
9580
- function pushControllerManifests(resources, deployments, services) {
9581
- if (deployments.watch) {
9582
- resources.push(deployments.watch);
9583
- }
9584
- if (deployments.admission) {
9585
- resources.push(deployments.admission);
9586
- }
9587
- if (services.admission) {
9588
- resources.push(services.admission);
9589
- }
9590
- if (services.watch) {
9591
- resources.push(services.watch);
9592
- }
9593
- return resources;
9594
- }
9595
- async function generateAllYaml(assets, deployments, services) {
9596
- const { name: name2, tls, apiPath, path: path4, config } = assets;
9597
- const code = await import_fs8.promises.readFile(path4);
9598
- const hash = import_crypto2.default.createHash("sha256").update(code).digest("hex");
9599
- let resources = [
9600
- getNamespace(assets.config.customLabels?.namespace),
9601
- clusterRole(name2, assets.capabilities, config.rbacMode, config.rbac),
9602
- clusterRoleBinding(name2),
9603
- serviceAccount(name2),
9604
- apiPathSecret(name2, apiPath),
9605
- tlsSecret(name2, tls),
9606
- getModuleSecret(name2, code, hash),
9607
- storeRole(name2),
9608
- storeRoleBinding(name2)
9609
- ];
9610
- resources = pushControllerManifests(resources, deployments, services);
9611
- const webhooks = {
9612
- mutate: await webhookConfigGenerator(assets, "mutate" /* MUTATE */, assets.config.webhookTimeout),
9613
- validate: await webhookConfigGenerator(
9614
- assets,
9615
- "validate" /* VALIDATE */,
9616
- assets.config.webhookTimeout
9617
- )
9618
- };
9619
- const additionalResources = [webhooks.mutate, webhooks.validate].filter(
9620
- (resource) => resource !== null && resource !== void 0
9621
- );
9622
- resources.push(...additionalResources);
9623
- return resources.map((resource) => (0, import_client_node4.dumpYaml)(resource, { noRefs: true })).join("---\n");
9624
- }
9625
-
9626
- // src/lib/assets/yaml/generateZarfYaml.ts
9627
- var import_client_node5 = require("@kubernetes/client-node");
9628
- function generateZarfYamlGeneric(assets, path4, type) {
9629
- const zarfComponentName = process.env.PEPR_CUSTOM_BUILD_NAME ?? "module";
9630
- const manifestSettings = {
9631
- name: zarfComponentName,
9632
- namespace: "pepr-system",
9633
- files: [path4]
9634
- };
9635
- const chartSettings = {
9636
- name: zarfComponentName,
9637
- namespace: "pepr-system",
9638
- version: `${assets.config.appVersion || "0.0.1"}`,
9639
- localPath: path4
9640
- };
9641
- const component = {
9642
- name: zarfComponentName,
9643
- required: true,
9644
- images: [assets.image],
9645
- [type]: [type === "manifests" ? manifestSettings : chartSettings]
9646
- };
9647
- const zarfCfg = {
9648
- kind: "ZarfPackageConfig",
9476
+ },
9477
+ {
9478
+ apiVersion: "apiextensions.k8s.io/v1",
9479
+ kind: "CustomResourceDefinition",
9649
9480
  metadata: {
9650
- name: assets.name,
9651
- description: `Pepr Module: ${assets.config.description}`,
9652
- url: "https://github.com/defenseunicorns/pepr",
9653
- version: `${assets.config.appVersion || "0.0.1"}`
9481
+ name: "unicorns.pepr.dev"
9654
9482
  },
9655
- components: [component]
9656
- };
9657
- return (0, import_client_node5.dumpYaml)(zarfCfg, { noRefs: true });
9658
- }
9659
-
9660
- // src/cli/build.helpers.ts
9661
- function assignImage(imageOptions) {
9662
- const { customImage, registryInfo, peprVersion, registry } = imageOptions;
9663
- if (customImage) {
9664
- return customImage;
9665
- }
9666
- if (registryInfo) {
9667
- return `${registryInfo}/custom-pepr-controller:${peprVersion}`;
9668
- }
9669
- if (registry) {
9670
- return checkIronBankImage(registry, "", peprVersion);
9483
+ spec: {
9484
+ group: "pepr.dev",
9485
+ versions: [
9486
+ {
9487
+ name: "v1",
9488
+ served: true,
9489
+ storage: true,
9490
+ schema: {
9491
+ openAPIV3Schema: {
9492
+ type: "object",
9493
+ properties: {
9494
+ spec: {
9495
+ type: "object",
9496
+ properties: {
9497
+ message: {
9498
+ type: "string"
9499
+ },
9500
+ counter: {
9501
+ type: "number"
9502
+ }
9503
+ }
9504
+ }
9505
+ }
9506
+ }
9507
+ }
9508
+ }
9509
+ ],
9510
+ scope: "Namespaced",
9511
+ names: {
9512
+ plural: "unicorns",
9513
+ singular: "unicorn",
9514
+ kind: "Unicorn"
9515
+ }
9516
+ }
9671
9517
  }
9672
- return "";
9673
- }
9674
- function determineRbacMode(opts, cfg) {
9675
- if (opts.rbacMode) {
9676
- return opts.rbacMode;
9518
+ ];
9519
+
9520
+ // src/templates/settings.json
9521
+ var settings_default = {
9522
+ "debug.javascript.terminalOptions": {
9523
+ enableTurboSourcemaps: true,
9524
+ resolveSourceMapLocations: [
9525
+ "${workspaceFolder}/**",
9526
+ "node_modules/kubernetes-fluent-client/**",
9527
+ "node_modules/pepr/**"
9528
+ ]
9677
9529
  }
9678
- if (cfg.pepr.rbacMode && cfg.pepr.rbacMode !== "scoped") {
9679
- return "admin";
9530
+ };
9531
+
9532
+ // src/templates/tsconfig.module.json
9533
+ var tsconfig_module_default = {
9534
+ compilerOptions: {
9535
+ allowSyntheticDefaultImports: true,
9536
+ declaration: true,
9537
+ declarationMap: true,
9538
+ emitDeclarationOnly: true,
9539
+ esModuleInterop: true,
9540
+ lib: ["ES2022"],
9541
+ module: "NodeNext",
9542
+ moduleResolution: "NodeNext",
9543
+ outDir: "dist",
9544
+ resolveJsonModule: true,
9545
+ rootDir: ".",
9546
+ strict: false,
9547
+ target: "ES2022",
9548
+ useUnknownInCatchVariables: false
9549
+ },
9550
+ include: ["**/*.ts"]
9551
+ };
9552
+
9553
+ // src/templates/data.json
9554
+ var gitIgnore = "# Ignore node_modules and Pepr build artifacts\nnode_modules\ndist\ninsecure*\n";
9555
+ var readmeMd = '# Pepr Module\n\nThis is a Pepr Module. [Pepr](https://github.com/defenseunicorns/pepr) is a type-safe Kubernetes middleware system.\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```text\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';
9556
+ 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';
9557
+ var helloPeprTS = 'import {\n Capability,\n K8s,\n Log,\n PeprMutateRequest,\n RegisterKind,\n a,\n fetch,\n fetchStatus,\n kind,\n} from "pepr";\nimport { MockAgent, setGlobalDispatcher } from "undici";\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 action, use \'Store\' to persist data\nconst { When, Store } = HelloPepr;\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate Action (Namespace) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This 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 .Mutate(ns => ns.RemoveLabel("remove-me"));\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Watch Action with K8s SSA (Namespace) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This action watches for the `pepr-demo-2` namespace to be created, then creates a ConfigMap with\n * the name `pepr-ssa-demo` and adds the namespace UID to the ConfigMap data. Because Pepr uses\n * server-side apply for this operation, the ConfigMap will be created or updated if it already exists.\n */\nWhen(a.Namespace)\n .IsCreated()\n .WithName("pepr-demo-2")\n .Watch(async ns => {\n Log.info("Namespace pepr-demo-2 was created.");\n\n try {\n // Apply the ConfigMap using K8s server-side apply\n await K8s(kind.ConfigMap).Apply({\n metadata: {\n name: "pepr-ssa-demo",\n namespace: "pepr-demo-2",\n },\n data: {\n "ns-uid": ns.metadata.uid,\n },\n });\n } catch (error) {\n // You can use the Log object to log messages to the Pepr controller pod\n Log.error(error, "Failed to apply ConfigMap using server-side apply.");\n }\n\n // You can share data between actions using the Store, including between different types of actions\n Store.setItem("watch-data", "This data was stored by a Watch Action.");\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate Action (CM Example 1) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This is a single 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 .Mutate(request => {\n request.SetLabel("pepr", "was-here").SetAnnotation("pepr.dev", "annotations-work-too");\n\n // Use the Store to persist data between requests and Pepr controller pods\n Store.setItem("example-1", "was-here");\n\n // This data is written asynchronously and can be read back via `Store.getItem()` or `Store.subscribe()`\n Store.setItem("example-1-data", JSON.stringify(request.Raw.data));\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate & Validate Actions (CM Example 2) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This combines 3 different types of actions: \'Mutate\', \'Validate\', and \'Watch\'. The order\n * of the actions is required, but each action is optional. In this example, when a ConfigMap is created\n * with the name `example-2`, then add a label and annotation, validate that the ConfigMap has the label\n * `pepr`, and log the request.\n */\nWhen(a.ConfigMap)\n .IsCreated()\n .WithName("example-2")\n .Mutate(request => {\n // This Mutate Action will mutate the request before it is persisted to the cluster\n\n // Use `request.Merge()` to merge the new data with the existing data\n request.Merge({\n metadata: {\n labels: {\n pepr: "was-here",\n },\n annotations: {\n "pepr.dev": "annotations-work-too",\n },\n },\n });\n })\n .Validate(request => {\n // This Validate Action will validate the request before it is persisted to the cluster\n\n // Approve the request if the ConfigMap has the label \'pepr\'\n if (request.HasLabel("pepr")) {\n return request.Approve();\n }\n\n // Otherwise, deny the request with an error message (optional)\n return request.Deny("ConfigMap must have label \'pepr\'");\n })\n .Watch((cm, phase) => {\n // This Watch Action will watch the ConfigMap after it has been persisted to the cluster\n Log.info(cm, `ConfigMap was ${phase} with the name example-2`);\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate Action (CM Example 2a) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This action shows a simple validation that will deny any ConfigMap that has the\n * annotation `evil`. Note that the `Deny()` function takes an optional second parameter that is a\n * user-defined status code to return.\n */\nWhen(a.ConfigMap)\n .IsCreated()\n .Validate(request => {\n if (request.HasAnnotation("evil")) {\n return request.Deny("No evil CM annotations allowed.", 400);\n }\n\n return request.Approve();\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate Action (CM Example 3) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This 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 .Mutate(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// This action validates the label `change=by-label` is deleted\nWhen(a.ConfigMap)\n .IsDeleted()\n .WithLabel("change", "by-label")\n .Validate(request => {\n // Log and then always approve the request\n Log.info("CM with label \'change=by-label\' was deleted.");\n return request.Approve();\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate Action (CM Example 4) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This action show how you can use the `Mutate()` function without an inline function.\n * This is useful if you want to keep your actions small and focused on a single task,\n * or if you want to reuse the same function in multiple actions.\n */\nWhen(a.ConfigMap).IsCreated().WithName("example-4").Mutate(example4Cb);\n\n// This function uses the complete type definition, but is not required.\nfunction example4Cb(cm: PeprMutateRequest<a.ConfigMap>): void {\n cm.SetLabel("pepr.dev/first", "true");\n cm.SetLabel("pepr.dev/second", "true");\n cm.SetLabel("pepr.dev/third", "true");\n}\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate 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).IsCreated().InNamespace("pepr-demo-2").WithName("example-4a").Mutate(example4Cb);\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate Action (CM Example 5) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This 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 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://icanhazdadjoke.com/");\n * const joke = await fetch("https://icanhazdadjoke.com/") as TheChuckNorrisJoke;\n * ```\n *\n * Alternatively, you can drop the type completely:\n *\n * ```ts\n * fetch("https://icanhazdadjoke.com")\n * ```\n */\ninterface TheChuckNorrisJoke {\n id: string;\n joke: string;\n status: number;\n}\n\nWhen(a.ConfigMap)\n .IsCreatedOrUpdated()\n .WithLabel("chuck-norris")\n .Mutate(cm => cm.SetLabel("got-jokes", "true"))\n .Watch(async cm => {\n const jokeURL = "https://icanhazdadjoke.com";\n\n const mockAgent: MockAgent = new MockAgent();\n setGlobalDispatcher(mockAgent);\n const mockClient = mockAgent.get(jokeURL);\n mockClient.intercept({ path: "/", method: "GET" }).reply(\n 200,\n {\n id: "R7UfaahVfFd",\n joke: "Funny joke goes here.",\n status: 200,\n },\n {\n headers: {\n "Content-Type": "application/json; charset=utf-8",\n },\n },\n );\n\n // Try/catch is not needed as a response object will always be returned\n const response = await fetch<TheChuckNorrisJoke>(jokeURL, {\n headers: {\n Accept: "application/json",\n },\n });\n\n // Instead, check the `response.ok` field\n if (response.ok) {\n const { joke } = response.data;\n // Add Joke to the Store\n await Store.setItemAndWait(jokeURL, joke);\n // Add the Chuck Norris joke to the configmap\n try {\n await K8s(kind.ConfigMap).Apply({\n metadata: {\n name: cm.metadata.name,\n namespace: cm.metadata.namespace,\n },\n data: {\n "chuck-says": Store.getItem(jokeURL),\n },\n });\n } catch (error) {\n Log.error(error, "Failed to apply ConfigMap using server-side apply.", {\n cm,\n });\n }\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 * Mutate 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 action is executed.\n */\nWhen(a.Secret)\n .IsCreated()\n .WithName("secret-1")\n .Mutate(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 * Mutate 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 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 to 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 .Mutate(request => {\n request.Merge({\n spec: {\n message: "Hello Pepr without type data!",\n counter: Math.random(),\n },\n });\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate 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 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 actions, but we are putting it here for demonstration purposes.\n *\n * You will need to 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 .Mutate(request => {\n request.Merge({\n spec: {\n message: "Hello Pepr with type data!",\n counter: Math.random(),\n },\n });\n });\n\n/**\n * A callback function that is called once the Pepr Store is fully loaded.\n */\nStore.onReady(data => {\n Log.info(data, "Pepr Store Ready");\n});\n';
9558
+ 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" }, files: ["/dist", "/src", "!src/**/*.test.ts", "!src/fixtures/**", "!dist/**/*.test.d.ts*"], version: "0.52.2-nightly.3", main: "dist/lib.js", types: "dist/lib.d.ts", scripts: { build: "tsc -p config/tsconfig.root.json && node build.mjs && npm pack", "build:image": "npm run build && docker buildx build --output type=docker --tag pepr:dev .", "build:image:unicorn": "npm run build && docker buildx build --output type=docker --tag pepr/private:dev $(node scripts/read-unicorn-build-args.mjs) .", ci: "npm ci", "format:check": "npm run format:src && npm run format:tests && npm run format:markdown && npm run format:integration && npm run format:prettier -- --check", "format:fix": "npm run format:src -- --fix && npm run format:markdown -- --fix && npm run format:integration -- --fix && npm run format:prettier -- --write", "format:integration": "eslint --config config/eslint.integration.config.mjs integration/cli integration/helpers", "format:markdown": 'npx -y markdownlint-cli --config config/.markdownlint.json --ignore adr --ignore integration/testroot --ignore pepr-test-module --ignore node_modules "**/*.md"', "format:prettier": "prettier --config config/.prettierrc src integration/cli/**/*.ts integration/helpers/**/*.ts", "format:src": "eslint --config config/eslint.root.config.mjs 'src/**/*.ts' --ignore-pattern '**/*.test.ts' --ignore-pattern 'src/templates/**'", "format:tests": "eslint --config config/eslint.test.config.mjs 'src/**/*.test.ts'", "gen-data-json": "node hack/build-template-data.js", prebuild: "rm -fr dist/* && npm run gen-data-json", prepare: `if [ "$NODE_ENV" != 'production' ]; then husky; fi`, "set:version": "node scripts/set-version.js", test: "npm run test:unit && npm run test:journey && npm run test:journey-wasm", "test:artifacts": "npm run build && vitest run src/build-artifact.test.ts", "test:docs": "vitest run --config=config/vitest.integration.config.ts integration/cli/docs/*.test.ts", "test:integration": "npm run test:integration:prep && npm run test:integration:run", "test:integration:prep": "./integration/prep.sh", "test:integration:run": "vitest run --config=config/vitest.integration.config.ts integration", "test:journey": "npm run test:journey:k3d && npm run build && npm run test:journey:image && npm run test:journey:run", "test:journey-wasm": "npm run test:journey:k3d && npm run build && npm run test:journey:image && npm run test:journey:run-wasm", "test:journey-wasm:unicorn": "npm run test:journey:k3d && npm run build && npm run test:journey:image:unicorn && npm run test:journey:run-wasm", "test:journey:image": "npm run build && docker buildx build --output type=docker --tag pepr:dev . && k3d image import pepr:dev -c pepr-dev", "test:journey:image:unicorn": "npm run build && docker buildx build --output type=docker --tag pepr/private:dev $(node scripts/read-unicorn-build-args.mjs) . && k3d image import pepr/private:dev -c pepr-dev", "test:journey:k3d": "k3d cluster delete pepr-dev && k3d cluster create pepr-dev --k3s-arg '--debug@server:0' --wait && kubectl rollout status deployment -n kube-system", "test:journey:run": "vitest run --config=config/vitest.journey.config.ts journey/entrypoint.test.ts", "test:journey:run-wasm": "vitest run --config=config/vitest.journey.config.ts journey/entrypoint-wasm.test.ts", "test:journey:unicorn": "npm run test:journey:k3d && npm run test:journey:image:unicorn && npm run test:journey:run", "test:unit": "npm run gen-data-json && NODE_OPTIONS=--no-deprecation vitest --config config/vitest.root.config.ts run --coverage", "test:upgrade:unicorn": "npm run test:journey:k3d && npm run test:journey:image:unicorn && vitest run integration/cluster/upgrade.test.ts", "test:upgrade:upstream": "npm run test:journey:k3d && npm run test:journey:image && vitest run integration/cluster/upgrade.test.ts" }, dependencies: { "@types/ramda": "0.31.0", commander: "14.0.0", express: "5.1.0", "fast-json-patch": "3.1.1", heredoc: "^1.3.1", "http-status-codes": "^2.3.0", "json-pointer": "^0.6.2", "kubernetes-fluent-client": "3.10.0", pino: "9.7.0", "pino-pretty": "13.0.0", "prom-client": "15.1.3", ramda: "0.31.3", sigstore: "3.1.0", "ts-morph": "^26.0.0" }, devDependencies: { "@commitlint/cli": "19.8.1", "@commitlint/config-conventional": "19.8.1", "@fast-check/vitest": "^0.2.1", "@types/eslint": "9.6.1", "@types/express": "5.0.3", "@types/json-pointer": "^1.0.34", "@types/node": "24.x.x", "@types/node-forge": "1.3.13", "@types/uuid": "10.0.0", "@types/ws": "^8.18.1", "@vitest/coverage-v8": "^3.2.3", "fast-check": "^4.0.0", globals: "^16.0.0", husky: "^9.1.6", "js-yaml": "^4.1.0", shellcheck: "^3.0.0", tsx: "^4.20.3", undici: "^7.0.1", vitest: "^3.2.3" }, overrides: { glob: "^9.0.0" }, peerDependencies: { "@types/prompts": "2.4.9", "@typescript-eslint/eslint-plugin": "8.33.0", "@typescript-eslint/parser": "8.33.0", esbuild: "0.25.5", eslint: "^9.26.0", "node-forge": "1.3.1", prettier: "3.5.3", prompts: "2.4.2", typescript: "5.8.3", uuid: "11.1.0" } };
9559
+
9560
+ // src/cli/init/utils.ts
9561
+ var import_fs7 = require("fs");
9562
+ function sanitizeName(name2) {
9563
+ if (typeof name2 !== "string") {
9564
+ throw TypeError(
9565
+ `sanitizeName() was called with a non-string value. The value is: ${name2} of type ${typeof name2}`
9566
+ );
9680
9567
  }
9681
- return cfg.pepr.rbacMode || "admin";
9568
+ let sanitized = name2.toLowerCase().replace(/[^a-z0-9-]+/gi, "-");
9569
+ sanitized = sanitized.replace(/^-+|-+$/g, "");
9570
+ sanitized = sanitized.replace(/--+/g, "-");
9571
+ return sanitized;
9682
9572
  }
9683
- async function createOutputDirectory(outputDir2) {
9573
+ async function createDir(dir) {
9684
9574
  try {
9685
- const dir = outputDir2 === "" ? "dist" : outputDir2;
9686
- await createDirectoryIfNotExists(dir);
9687
- return dir;
9688
- } catch (error) {
9689
- console.error(`Error creating output directory: ${error.message}`);
9690
- process.exit(1);
9691
- }
9692
- }
9693
- function checkIronBankImage(registry, image, peprVersion) {
9694
- return registry === "Iron Bank" ? `registry1.dso.mil/ironbank/opensource/defenseunicorns/pepr/controller:v${peprVersion}` : image;
9695
- }
9696
- function validImagePullSecret(imagePullSecretName) {
9697
- if (imagePullSecretName) {
9698
- const error = "Invalid imagePullSecret. Please provide a valid name as defined in RFC 1123.";
9699
- if (sanitizeResourceName(imagePullSecretName) !== imagePullSecretName) {
9700
- console.error(error);
9701
- process.exit(1);
9575
+ await import_fs7.promises.mkdir(dir);
9576
+ } catch (err) {
9577
+ if (err && err.code === "EEXIST") {
9578
+ throw new Error(`Directory ${dir} already exists`);
9579
+ } else {
9580
+ throw err;
9702
9581
  }
9703
9582
  }
9704
9583
  }
9705
- async function handleCustomImageBuild(includedFiles, peprVersion, description, image) {
9706
- if (includedFiles.length > 0) {
9707
- await createDockerfile(peprVersion, description, includedFiles);
9708
- (0, import_child_process2.execSync)(`docker build --tag ${image} -f Dockerfile.controller .`, {
9709
- stdio: "inherit"
9710
- });
9711
- (0, import_child_process2.execSync)(`docker push ${image}`, { stdio: "inherit" });
9712
- }
9713
- }
9714
- function handleValidCapabilityNames(capabilities) {
9715
- try {
9716
- validateCapabilityNames(capabilities);
9717
- } catch (e) {
9718
- console.error(`Error loading capability:`, e);
9719
- process.exit(1);
9720
- }
9721
- }
9722
- async function watchForChanges(ctxCfg, reloader) {
9723
- const ctx = await (0, import_esbuild.context)(ctxCfg);
9724
- if (reloader) {
9725
- await ctx.watch();
9726
- } else {
9727
- await ctx.rebuild();
9728
- await ctx.dispose();
9584
+ function write(path4, data) {
9585
+ if (typeof data !== "string") {
9586
+ data = JSON.stringify(data, null, 2);
9729
9587
  }
9730
- return ctx;
9588
+ return import_fs7.promises.writeFile(path4, data);
9731
9589
  }
9732
- async function generateYamlAndWriteToDisk(obj) {
9733
- const { uuid, imagePullSecret, outputDir: outputDir2, assets, zarf } = obj;
9734
- const yamlFile = `pepr-module-${uuid}.yaml`;
9735
- const chartPath = `${uuid}-chart`;
9736
- const yamlPath = (0, import_path3.resolve)(outputDir2, yamlFile);
9737
- try {
9738
- const yaml = await assets.allYaml(
9739
- generateAllYaml,
9740
- {
9741
- getDeploymentFunction: getDeployment,
9742
- getWatcherFunction: getWatcher,
9743
- getServiceFunction: service,
9744
- getWatcherServiceFunction: watcherService
9590
+
9591
+ // src/cli/init/templates.ts
9592
+ var { dependencies, devDependencies, peerDependencies, scripts, version } = packageJSON;
9593
+ function genPkgJSON(opts) {
9594
+ const uuid = !opts.uuid ? (0, import_uuid.v4)() : opts.uuid;
9595
+ const name2 = sanitizeName(opts.name);
9596
+ const { typescript } = peerDependencies;
9597
+ const data = {
9598
+ name: name2,
9599
+ version: "0.0.1",
9600
+ description: opts.description,
9601
+ keywords: ["pepr", "k8s", "policy-engine", "pepr-module", "security"],
9602
+ engines: {
9603
+ node: ">=20.0.0"
9604
+ },
9605
+ pepr: {
9606
+ uuid,
9607
+ onError: opts.errorBehavior,
9608
+ webhookTimeout: 10,
9609
+ customLabels: {
9610
+ namespace: {
9611
+ "pepr.dev": ""
9612
+ }
9745
9613
  },
9746
- imagePullSecret
9747
- );
9748
- const zarfPath = (0, import_path3.resolve)(outputDir2, "zarf.yaml");
9749
- let localZarf = "";
9750
- if (zarf === "chart") {
9751
- localZarf = assets.zarfYamlChart(generateZarfYamlGeneric, chartPath);
9614
+ alwaysIgnore: {
9615
+ namespaces: []
9616
+ },
9617
+ admission: {
9618
+ alwaysIgnore: {
9619
+ namespaces: []
9620
+ }
9621
+ },
9622
+ watch: {
9623
+ alwaysIgnore: {
9624
+ namespaces: []
9625
+ }
9626
+ },
9627
+ includedFiles: [],
9628
+ env: {}
9629
+ },
9630
+ scripts: {
9631
+ "k3d-setup": scripts["test:journey:k3d"]
9632
+ },
9633
+ dependencies: {
9634
+ pepr: version,
9635
+ undici: "^7.0.1"
9636
+ },
9637
+ devDependencies: {
9638
+ typescript
9639
+ },
9640
+ overrides: {
9641
+ "brace-expansion": "1.1.11"
9642
+ }
9643
+ };
9644
+ return {
9645
+ data,
9646
+ path: "package.json",
9647
+ print: (0, import_util.inspect)(data, false, 5, true)
9648
+ };
9649
+ }
9650
+ var peprTSTemplate = {
9651
+ path: "pepr.ts",
9652
+ data: peprTS
9653
+ };
9654
+ var readme = {
9655
+ path: "README.md",
9656
+ data: readmeMd
9657
+ };
9658
+ var helloPepr = {
9659
+ path: "hello-pepr.ts",
9660
+ data: helloPeprTS
9661
+ };
9662
+ var gitignore = {
9663
+ path: ".gitignore",
9664
+ data: gitIgnore
9665
+ };
9666
+ var samplesYaml = {
9667
+ path: "hello-pepr.samples.yaml",
9668
+ data: hello_pepr_samples_default.map((r) => (0, import_client_node5.dumpYaml)(r, { noRefs: true })).join("---\n")
9669
+ };
9670
+ var snippet = {
9671
+ path: "pepr.code-snippets",
9672
+ data: pepr_code_snippets_default
9673
+ };
9674
+ var codeSettings = {
9675
+ path: "settings.json",
9676
+ data: settings_default
9677
+ };
9678
+ var tsConfig = {
9679
+ path: "tsconfig.json",
9680
+ data: tsconfig_module_default
9681
+ };
9682
+ var prettier = {
9683
+ path: ".prettierrc",
9684
+ data: prettierrc_default
9685
+ };
9686
+ var eslint = {
9687
+ path: "eslint.config.mjs",
9688
+ data: (0, import_fs8.readFileSync)(
9689
+ import_path3.default.resolve(
9690
+ (() => {
9691
+ const fullPath = __dirname;
9692
+ const lengthOfSuffix = "pepr/".length;
9693
+ const lastPeprIndex = fullPath.lastIndexOf("pepr/");
9694
+ return fullPath.substring(0, lastPeprIndex + lengthOfSuffix);
9695
+ })(),
9696
+ "src/templates/eslint.config.mjs"
9697
+ ),
9698
+ "utf-8"
9699
+ )
9700
+ };
9701
+
9702
+ // src/cli/format/index.ts
9703
+ var import_eslint = require("eslint");
9704
+
9705
+ // src/cli/format/format.helpers.ts
9706
+ var import_fs9 = require("fs");
9707
+ var import_prettier = require("prettier");
9708
+ async function formatWithPrettier(results, validateOnly) {
9709
+ let hasFailure = false;
9710
+ for (const { filePath } of results) {
9711
+ const content = await import_fs9.promises.readFile(filePath, "utf8");
9712
+ const cfg = await (0, import_prettier.resolveConfig)(filePath);
9713
+ const formatted = await (0, import_prettier.format)(content, { filepath: filePath, ...cfg });
9714
+ if (validateOnly && formatted !== content) {
9715
+ hasFailure = true;
9716
+ console.error(`File ${filePath} is not formatted correctly`);
9752
9717
  } else {
9753
- localZarf = assets.zarfYaml(generateZarfYamlGeneric, yamlFile);
9718
+ await import_fs9.promises.writeFile(filePath, formatted);
9754
9719
  }
9755
- await import_fs9.promises.writeFile(yamlPath, yaml);
9756
- await import_fs9.promises.writeFile(zarfPath, localZarf);
9757
- await assets.generateHelmChart(webhookConfigGenerator, getWatcher, getModuleSecret, outputDir2);
9758
- console.info(`K8s resource for the module saved to ${yamlPath}`);
9759
- } catch (error) {
9760
- console.error(`Error generating YAML: ${error}`);
9761
- process.exit(1);
9762
9720
  }
9721
+ return hasFailure;
9763
9722
  }
9764
9723
 
9765
- // src/cli/build.ts
9766
- var peprTS2 = "pepr.ts";
9767
- var outputDir = "dist";
9768
- function build_default(program2) {
9769
- program2.command("build").description("Build a Pepr Module for deployment").addOption(
9770
- new import_commander.Option("-M, --rbac-mode <mode>", "Override module config and set RBAC mode.").choices([
9771
- "admin",
9772
- "scoped"
9773
- ])
9774
- ).addOption(
9775
- new import_commander.Option(
9776
- "-I, --registry-info <registry/username>",
9777
- "Provide the image registry and username for building and pushing a custom WASM container. Requires authentication. Conflicts with --custom-image and --registry. Builds and pushes `'<registry/username>/custom-pepr-controller:<current-version>'`."
9778
- ).conflicts(["customImage", "registry"])
9779
- ).option("-P, --with-pull-secret <name>", "Use image pull secret for controller Deployment.", "").addOption(
9780
- new import_commander.Option(
9781
- "-c, --custom-name <name>",
9782
- "Set name for zarf component and service monitors in helm charts."
9783
- )
9784
- ).option("-e, --entry-point <file>", "Specify the entry point file to build with.", peprTS2).addOption(
9785
- new import_commander.Option(
9786
- "-i, --custom-image <image>",
9787
- "Specify a custom image with version for deployments. Conflicts with --registry-info and --registry. Example: 'docker.io/username/custom-pepr-controller:v1.0.0'"
9788
- ).conflicts(["registryInfo", "registry"])
9789
- ).option(
9790
- "-n, --no-embed",
9791
- "Disable embedding of deployment files into output module. Useful when creating library modules intended solely for reuse/distribution via NPM."
9792
- ).option("-o, --output <directory>", "Set output directory.", "dist").addOption(
9793
- new import_commander.Option(
9794
- "-r, --registry <GitHub|Iron Bank>",
9795
- "Container registry: Choose container registry for deployment manifests. Conflicts with --custom-image and --registry-info."
9796
- ).conflicts(["customImage", "registryInfo"]).choices(["GitHub", "Iron Bank"])
9797
- ).option(
9798
- "-t, --timeout <seconds>",
9799
- "How long the API server should wait for a webhook to respond before treating the call as a failure.",
9800
- parseTimeout
9801
- ).addOption(
9802
- new import_commander.Option("-z, --zarf <manifest|chart>", "Set Zarf package type").choices(["manifest", "chart"]).default("manifest")
9803
- ).action(async (opts) => {
9804
- outputDir = await createOutputDirectory(opts.output);
9805
- const buildModuleResult = await buildModule(void 0, opts.entryPoint, opts.embed);
9806
- const { cfg, path: path4 } = buildModuleResult;
9807
- if (opts.customName) {
9808
- process.env.PEPR_CUSTOM_BUILD_NAME = opts.customName;
9809
- }
9810
- const image = assignImage({
9811
- customImage: opts.customImage,
9812
- registryInfo: opts.registryInfo,
9813
- peprVersion: cfg.pepr.peprVersion,
9814
- registry: opts.registry
9815
- });
9816
- if (opts.timeout !== void 0) {
9817
- cfg.pepr.webhookTimeout = opts.timeout;
9818
- }
9819
- if (opts.registryInfo !== void 0) {
9820
- console.info(`Including ${cfg.pepr.includedFiles.length} files in controller image.`);
9821
- await handleCustomImageBuild(
9822
- cfg.pepr.includedFiles,
9823
- cfg.pepr.peprVersion,
9824
- cfg.description,
9825
- image
9826
- );
9827
- }
9828
- if (!opts.embed) {
9829
- console.info(`Module built successfully at ${path4}`);
9830
- return;
9724
+ // src/cli/format/index.ts
9725
+ function format_default(program2) {
9726
+ program2.command("format").description("Lint and format this Pepr module").option("-v, --validate-only", "Do not modify files, only validate formatting.").action(async (opts) => {
9727
+ const success = await peprFormat(opts.validateOnly);
9728
+ if (success) {
9729
+ logger_default.info("Module formatted");
9730
+ } else {
9731
+ process.exit(1);
9831
9732
  }
9832
- const assets = new Assets(
9833
- {
9834
- ...cfg.pepr,
9835
- appVersion: cfg.version,
9836
- description: cfg.description,
9837
- alwaysIgnore: {
9838
- namespaces: cfg.pepr.alwaysIgnore?.namespaces
9839
- },
9840
- // Can override the rbacMode with the CLI option
9841
- rbacMode: determineRbacMode(opts, cfg)
9842
- },
9843
- path4,
9844
- opts.withPullSecret === "" ? [] : [opts.withPullSecret]
9845
- );
9846
- if (image !== "") assets.image = image;
9847
- validImagePullSecret(opts.withPullSecret);
9848
- handleValidCapabilityNames(assets.capabilities);
9849
- await generateYamlAndWriteToDisk({
9850
- uuid: cfg.pepr.uuid,
9851
- outputDir,
9852
- imagePullSecret: opts.withPullSecret,
9853
- zarf: opts.zarf,
9854
- assets
9855
- });
9856
9733
  });
9857
9734
  }
9858
- var externalLibs = Object.keys(dependencies);
9859
- externalLibs.push("pepr");
9860
- externalLibs.push("@kubernetes/client-node");
9861
- async function loadModule(entryPoint = peprTS2) {
9862
- const entryPointPath = (0, import_path4.resolve)(".", entryPoint);
9863
- const modulePath = (0, import_path4.dirname)(entryPointPath);
9864
- const cfgPath = (0, import_path4.resolve)(modulePath, "package.json");
9735
+ async function peprFormat(validateOnly) {
9736
+ {
9737
+ try {
9738
+ const eslint2 = new import_eslint.ESLint();
9739
+ const results = await eslint2.lintFiles(["./**/*.ts"]);
9740
+ let hasFailure = false;
9741
+ results.forEach(async (result) => {
9742
+ const errorCount = result.fatalErrorCount + result.errorCount;
9743
+ if (errorCount > 0) {
9744
+ hasFailure = true;
9745
+ }
9746
+ });
9747
+ const formatter = await eslint2.loadFormatter("stylish");
9748
+ const resultText = await formatter.format(results, {});
9749
+ if (resultText) {
9750
+ logger_default.info(resultText);
9751
+ }
9752
+ if (!validateOnly) {
9753
+ await import_eslint.ESLint.outputFixes(results);
9754
+ }
9755
+ hasFailure = hasFailure || await formatWithPrettier(results, validateOnly);
9756
+ return !hasFailure;
9757
+ } catch (error) {
9758
+ logger_default.error(error, `Error formatting module:`);
9759
+ return false;
9760
+ }
9761
+ }
9762
+ }
9763
+
9764
+ // src/cli/build/loadModule.ts
9765
+ var import_promises = __toESM(require("fs/promises"));
9766
+ var import_posix = require("path/posix");
9767
+ async function loadModule(outputDir, entryPoint) {
9768
+ const entryPointPath = (0, import_posix.resolve)(".", entryPoint);
9769
+ const modulePath = (0, import_posix.dirname)(entryPointPath);
9770
+ const cfgPath = (0, import_posix.resolve)(modulePath, "package.json");
9865
9771
  try {
9866
- await import_fs10.promises.access(cfgPath);
9867
- await import_fs10.promises.access(entryPointPath);
9772
+ await import_promises.default.access(cfgPath);
9773
+ await import_promises.default.access(entryPointPath);
9868
9774
  } catch {
9869
9775
  console.error(
9870
9776
  `Could not find ${cfgPath} or ${entryPointPath} in the current directory. Please run this command from the root of your module's directory.`
9871
9777
  );
9872
9778
  process.exit(1);
9873
9779
  }
9874
- const moduleText = await import_fs10.promises.readFile(cfgPath, { encoding: "utf-8" });
9780
+ const moduleText = await import_promises.default.readFile(cfgPath, { encoding: "utf-8" });
9875
9781
  const cfg = JSON.parse(moduleText);
9876
9782
  const { uuid } = cfg.pepr;
9877
9783
  const name2 = `pepr-${uuid}.js`;
@@ -9884,13 +9790,18 @@ async function loadModule(entryPoint = peprTS2) {
9884
9790
  entryPointPath,
9885
9791
  modulePath,
9886
9792
  name: name2,
9887
- path: (0, import_path4.resolve)(outputDir, name2),
9793
+ path: (0, import_posix.resolve)(outputDir, name2),
9888
9794
  uuid
9889
9795
  };
9890
9796
  }
9891
- async function buildModule(reloader, entryPoint = peprTS2, embed = true) {
9797
+
9798
+ // src/cli/build/buildModule.ts
9799
+ var externalLibs = Object.keys(dependencies);
9800
+ externalLibs.push("pepr");
9801
+ externalLibs.push("@kubernetes/client-node");
9802
+ async function buildModule(outputDir, reloader, entryPoint = "pepr.ts", embed = true) {
9892
9803
  try {
9893
- const { cfg, modulePath, path: path4, uuid } = await loadModule(entryPoint);
9804
+ const { cfg, modulePath, path: path4, uuid } = await loadModule(outputDir, entryPoint);
9894
9805
  await checkFormat();
9895
9806
  const npmRoot = (0, import_child_process3.execFileSync)("npm", ["root"]).toString().trim();
9896
9807
  const args = ["--project", `${modulePath}/tsconfig.json`, "--outdir", outputDir];
@@ -9978,12 +9889,109 @@ async function checkFormat() {
9978
9889
  }
9979
9890
  }
9980
9891
 
9892
+ // src/cli/build/index.ts
9893
+ function build_default(program2) {
9894
+ program2.command("build").description("Build a Pepr Module for deployment").addOption(
9895
+ new import_commander.Option("-M, --rbac-mode <mode>", "Override module config and set RBAC mode.").choices([
9896
+ "admin",
9897
+ "scoped"
9898
+ ])
9899
+ ).addOption(
9900
+ new import_commander.Option(
9901
+ "-I, --registry-info <registry/username>",
9902
+ "Provide the image registry and username for building and pushing a custom WASM container. Requires authentication. Conflicts with --custom-image and --registry. Builds and pushes `'<registry/username>/custom-pepr-controller:<current-version>'`."
9903
+ ).conflicts(["customImage", "registry"])
9904
+ ).option("-P, --with-pull-secret <name>", "Use image pull secret for controller Deployment.", "").addOption(
9905
+ new import_commander.Option(
9906
+ "-c, --custom-name <name>",
9907
+ "Set name for zarf component and service monitors in helm charts."
9908
+ )
9909
+ ).option("-e, --entry-point <file>", "Specify the entry point file to build with.", "pepr.ts").addOption(
9910
+ new import_commander.Option(
9911
+ "-i, --custom-image <image>",
9912
+ "Specify a custom image with version for deployments. Conflicts with --registry-info and --registry. Example: 'docker.io/username/custom-pepr-controller:v1.0.0'"
9913
+ ).conflicts(["registryInfo", "registry"])
9914
+ ).option(
9915
+ "-n, --no-embed",
9916
+ "Disable embedding of deployment files into output module. Useful when creating library modules intended solely for reuse/distribution via NPM."
9917
+ ).option("-o, --output <directory>", "Set output directory.", "dist").addOption(
9918
+ new import_commander.Option(
9919
+ "-r, --registry <GitHub|Iron Bank>",
9920
+ "Container registry: Choose container registry for deployment manifests. Conflicts with --custom-image and --registry-info."
9921
+ ).conflicts(["customImage", "registryInfo"]).choices(["GitHub", "Iron Bank"])
9922
+ ).option(
9923
+ "-t, --timeout <seconds>",
9924
+ "How long the API server should wait for a webhook to respond before treating the call as a failure.",
9925
+ parseTimeout
9926
+ ).addOption(
9927
+ new import_commander.Option("-z, --zarf <manifest|chart>", "Set Zarf package type").choices(["manifest", "chart"]).default("manifest")
9928
+ ).action(async (opts) => {
9929
+ const outputDir = await createOutputDirectory(opts.output);
9930
+ const buildModuleResult = await buildModule(
9931
+ outputDir,
9932
+ void 0,
9933
+ opts.entryPoint,
9934
+ opts.embed
9935
+ );
9936
+ const { cfg, path: path4 } = buildModuleResult;
9937
+ if (opts.customName) {
9938
+ process.env.PEPR_CUSTOM_BUILD_NAME = opts.customName;
9939
+ }
9940
+ const image = assignImage({
9941
+ customImage: opts.customImage,
9942
+ registryInfo: opts.registryInfo,
9943
+ peprVersion: cfg.pepr.peprVersion,
9944
+ registry: opts.registry
9945
+ });
9946
+ if (opts.timeout !== void 0) {
9947
+ cfg.pepr.webhookTimeout = opts.timeout;
9948
+ }
9949
+ if (opts.registryInfo !== void 0) {
9950
+ console.info(`Including ${cfg.pepr.includedFiles.length} files in controller image.`);
9951
+ await handleCustomImageBuild(
9952
+ cfg.pepr.includedFiles,
9953
+ cfg.pepr.peprVersion,
9954
+ cfg.description,
9955
+ image
9956
+ );
9957
+ }
9958
+ if (!opts.embed) {
9959
+ console.info(`Module built successfully at ${path4}`);
9960
+ return;
9961
+ }
9962
+ const assets = new Assets(
9963
+ {
9964
+ ...cfg.pepr,
9965
+ appVersion: cfg.version,
9966
+ description: cfg.description,
9967
+ alwaysIgnore: {
9968
+ namespaces: cfg.pepr.alwaysIgnore?.namespaces
9969
+ },
9970
+ // Can override the rbacMode with the CLI option
9971
+ rbacMode: determineRbacMode(opts, cfg)
9972
+ },
9973
+ path4,
9974
+ opts.withPullSecret === "" ? [] : [opts.withPullSecret]
9975
+ );
9976
+ if (image !== "") assets.image = image;
9977
+ validImagePullSecret(opts.withPullSecret);
9978
+ handleValidCapabilityNames(assets.capabilities);
9979
+ await generateYamlAndWriteToDisk({
9980
+ uuid: cfg.pepr.uuid,
9981
+ outputDir,
9982
+ imagePullSecret: opts.withPullSecret,
9983
+ zarf: opts.zarf,
9984
+ assets
9985
+ });
9986
+ });
9987
+ }
9988
+
9981
9989
  // src/cli/deploy.ts
9982
9990
  var import_prompts = __toESM(require("prompts"));
9983
9991
 
9984
9992
  // src/lib/assets/deploy.ts
9985
9993
  var import_crypto3 = __toESM(require("crypto"));
9986
- var import_fs11 = require("fs");
9994
+ var import_fs10 = require("fs");
9987
9995
  var import_kubernetes_fluent_client3 = require("kubernetes-fluent-client");
9988
9996
 
9989
9997
  // src/lib/k8s.ts
@@ -10092,7 +10100,7 @@ async function deployWebhook(assets, force, webhookTimeout) {
10092
10100
  logger_default.info("Applying the Pepr Store CRD if it doesn't exist");
10093
10101
  await (0, import_kubernetes_fluent_client3.K8s)(import_kubernetes_fluent_client3.kind.CustomResourceDefinition).Apply(peprStoreCRD, { force });
10094
10102
  if (assets.host) return;
10095
- const code = await import_fs11.promises.readFile(assets.path);
10103
+ const code = await import_fs10.promises.readFile(assets.path);
10096
10104
  if (!code.length) throw new Error("No code provided");
10097
10105
  const hash = import_crypto3.default.createHash("sha256").update(code).digest("hex");
10098
10106
  await setupRBAC(assets.name, assets.capabilities, force, assets.config);
@@ -10184,7 +10192,7 @@ async function namespaceDeploymentsReady(namespace = "pepr-system") {
10184
10192
  if (ready) {
10185
10193
  return ready;
10186
10194
  }
10187
- await new Promise((resolve6) => setTimeout(resolve6, 1e3));
10195
+ await new Promise((resolve7) => setTimeout(resolve7, 1e3));
10188
10196
  }
10189
10197
  logger_default.info(`All ${namespace} deployments are ready`);
10190
10198
  }
@@ -10248,7 +10256,7 @@ async function getUserConfirmation(opts) {
10248
10256
  return confirmation.yes ? true : false;
10249
10257
  }
10250
10258
  async function buildAndDeployModule(image, force) {
10251
- const builtModule = await buildModule();
10259
+ const builtModule = await buildModule("dist");
10252
10260
  if (!builtModule) {
10253
10261
  return;
10254
10262
  }
@@ -10303,7 +10311,7 @@ function validateNamespaces(capability, webhook) {
10303
10311
  var import_prompts2 = __toESM(require("prompts"));
10304
10312
  var import_child_process4 = require("child_process");
10305
10313
  var import_kubernetes_fluent_client5 = require("kubernetes-fluent-client");
10306
- var import_fs12 = require("fs");
10314
+ var import_fs11 = require("fs");
10307
10315
  function dev_default(program2) {
10308
10316
  program2.command("dev").description("Setup a local webhook development environment").option("-H, --host <host>", "Host to listen on", "host.k3d.internal").option("-y, --yes", "Skip confirmation prompt").action(async (opts) => {
10309
10317
  if (!opts.yes) {
@@ -10317,7 +10325,7 @@ function dev_default(program2) {
10317
10325
  return;
10318
10326
  }
10319
10327
  }
10320
- const { cfg, path: path4 } = await loadModule();
10328
+ const { cfg, path: path4 } = await loadModule("dist", "pepr.ts");
10321
10329
  const webhook = new Assets(
10322
10330
  {
10323
10331
  ...cfg.pepr,
@@ -10327,8 +10335,8 @@ function dev_default(program2) {
10327
10335
  [],
10328
10336
  opts.host
10329
10337
  );
10330
- await import_fs12.promises.writeFile("insecure-tls.crt", webhook.tls.pem.crt);
10331
- await import_fs12.promises.writeFile("insecure-tls.key", webhook.tls.pem.key);
10338
+ await import_fs11.promises.writeFile("insecure-tls.crt", webhook.tls.pem.crt);
10339
+ await import_fs11.promises.writeFile("insecure-tls.key", webhook.tls.pem.key);
10332
10340
  try {
10333
10341
  let program3;
10334
10342
  const name2 = `pepr-${cfg.pepr.uuid}`;
@@ -10370,7 +10378,7 @@ ${error}`
10370
10378
  console.debug(`Received SIGINT, removing webhooks`);
10371
10379
  });
10372
10380
  };
10373
- await buildModule(async (r) => {
10381
+ await buildModule("dist", async (r) => {
10374
10382
  if (r.errors.length > 0) {
10375
10383
  console.error(`Error compiling module: ${r.errors}`);
10376
10384
  return;
@@ -10483,7 +10491,7 @@ var import_child_process5 = require("child_process");
10483
10491
  var import_path5 = require("path");
10484
10492
 
10485
10493
  // src/cli/init/walkthrough.ts
10486
- var import_fs13 = require("fs");
10494
+ var import_fs12 = require("fs");
10487
10495
  var import_prompts3 = __toESM(require("prompts"));
10488
10496
 
10489
10497
  // src/cli/init/enums.ts
@@ -10530,7 +10538,7 @@ async function setName(name2) {
10530
10538
  validate: async (val) => {
10531
10539
  try {
10532
10540
  const name3 = sanitizeName(val);
10533
- await import_fs13.promises.access(name3, import_fs13.promises.constants.F_OK);
10541
+ await import_fs12.promises.access(name3, import_fs12.promises.constants.F_OK);
10534
10542
  return "A directory with this name already exists";
10535
10543
  } catch {
10536
10544
  return val.length > 2 || "The name must be at least 3 characters long";
@@ -10714,11 +10722,11 @@ function uuid_default(program2) {
10714
10722
  program2.command("uuid [uuid]").description("Module UUID(s) currently deployed in the cluster").action(async (uuid) => {
10715
10723
  const deployments = await getPeprDeploymentsByUUID(uuid);
10716
10724
  const uuidTable = buildUUIDTable(deployments);
10717
- console.log("UUID Description");
10718
- console.log("--------------------------------------------");
10719
- Object.entries(uuidTable).forEach(([uuid2, description]) => {
10720
- console.log(`${uuid2} ${description}`);
10721
- });
10725
+ const uuidTableEntries = Object.entries(uuidTable).map(([uuid2, description]) => ({
10726
+ UUID: uuid2,
10727
+ Description: description
10728
+ }));
10729
+ console.table(uuidTableEntries);
10722
10730
  });
10723
10731
  }
10724
10732
  async function getPeprDeploymentsByUUID(uuid) {
@@ -10751,7 +10759,7 @@ var import_commander6 = require("commander");
10751
10759
 
10752
10760
  // src/cli/update/index.ts
10753
10761
  var import_child_process6 = require("child_process");
10754
- var import_fs14 = __toESM(require("fs"));
10762
+ var import_fs13 = __toESM(require("fs"));
10755
10763
  var import_path6 = require("path");
10756
10764
  var import_prompts4 = __toESM(require("prompts"));
10757
10765
  function update_default(program2) {
@@ -10791,12 +10799,12 @@ function update_default(program2) {
10791
10799
  await write((0, import_path6.resolve)(".vscode", snippet.path), snippet.data);
10792
10800
  await write((0, import_path6.resolve)(".vscode", codeSettings.path), codeSettings.data);
10793
10801
  const samplePath = (0, import_path6.resolve)("capabilities", samplesYaml.path);
10794
- if (import_fs14.default.existsSync(samplePath)) {
10795
- import_fs14.default.unlinkSync(samplePath);
10802
+ if (import_fs13.default.existsSync(samplePath)) {
10803
+ import_fs13.default.unlinkSync(samplePath);
10796
10804
  await write(samplePath, samplesYaml.data);
10797
10805
  }
10798
10806
  const tsPath = (0, import_path6.resolve)("capabilities", helloPepr.path);
10799
- if (import_fs14.default.existsSync(tsPath)) {
10807
+ if (import_fs13.default.existsSync(tsPath)) {
10800
10808
  await write(tsPath, helloPepr.data);
10801
10809
  }
10802
10810
  }
@@ -10844,7 +10852,7 @@ var import_commander5 = require("commander");
10844
10852
  var import_commander3 = require("commander");
10845
10853
 
10846
10854
  // src/cli/crd/generate/generators.ts
10847
- var import_fs15 = __toESM(require("fs"));
10855
+ var import_fs14 = __toESM(require("fs"));
10848
10856
  var import_path7 = __toESM(require("path"));
10849
10857
  var import_yaml = __toESM(require_dist());
10850
10858
  var import_ts_morph = require("ts-morph");
@@ -10874,27 +10882,27 @@ function extractCRDDetails(content, sourceFile) {
10874
10882
  }
10875
10883
  async function generateCRDs(options) {
10876
10884
  logger_default.warn("This feature is currently in alpha.\n");
10877
- const outputDir2 = import_path7.default.resolve(options.output);
10878
- await createDirectoryIfNotExists(outputDir2);
10885
+ const outputDir = import_path7.default.resolve(options.output);
10886
+ await createDirectoryIfNotExists(outputDir);
10879
10887
  const project = new import_ts_morph.Project();
10880
10888
  const apiRoot = import_path7.default.resolve("api");
10881
10889
  const versions = getAPIVersions(apiRoot);
10882
10890
  for (const version3 of versions) {
10883
10891
  const sourceFiles = loadVersionFiles(project, import_path7.default.join(apiRoot, version3));
10884
10892
  for (const sourceFile of sourceFiles) {
10885
- processSourceFile(sourceFile, version3, outputDir2);
10893
+ processSourceFile(sourceFile, version3, outputDir);
10886
10894
  }
10887
10895
  }
10888
10896
  }
10889
10897
  function getAPIVersions(apiRoot) {
10890
- return import_fs15.default.readdirSync(apiRoot).filter((v) => import_fs15.default.statSync(import_path7.default.join(apiRoot, v)).isDirectory());
10898
+ return import_fs14.default.readdirSync(apiRoot).filter((v) => import_fs14.default.statSync(import_path7.default.join(apiRoot, v)).isDirectory());
10891
10899
  }
10892
10900
  function loadVersionFiles(project, versionDir) {
10893
- const files = import_fs15.default.readdirSync(versionDir).filter((f) => f.endsWith(".ts"));
10901
+ const files = import_fs14.default.readdirSync(versionDir).filter((f) => f.endsWith(".ts"));
10894
10902
  const filePaths = files.map((f) => import_path7.default.join(versionDir, f));
10895
10903
  return project.addSourceFilesAtPaths(filePaths);
10896
10904
  }
10897
- function processSourceFile(sourceFile, version3, outputDir2) {
10905
+ function processSourceFile(sourceFile, version3, outputDir) {
10898
10906
  const content = sourceFile.getFullText();
10899
10907
  const { kind: kind8, fqdn, scope, plural: plural2, shortNames } = extractCRDDetails(content, sourceFile);
10900
10908
  if (!kind8) {
@@ -10919,8 +10927,8 @@ function processSourceFile(sourceFile, version3, outputDir2) {
10919
10927
  specSchema,
10920
10928
  conditionSchema
10921
10929
  });
10922
- const outPath = import_path7.default.join(outputDir2, `${kind8.toLowerCase()}.yaml`);
10923
- import_fs15.default.writeFileSync(outPath, (0, import_yaml.stringify)(crd), "utf8");
10930
+ const outPath = import_path7.default.join(outputDir, `${kind8.toLowerCase()}.yaml`);
10931
+ import_fs14.default.writeFileSync(outPath, (0, import_yaml.stringify)(crd), "utf8");
10924
10932
  logger_default.info(`\u2714 Created ${outPath}`);
10925
10933
  }
10926
10934
  function extractSingleLineComment(content, label) {
@@ -11084,7 +11092,7 @@ function generate_default() {
11084
11092
 
11085
11093
  // src/cli/crd/create/index.ts
11086
11094
  var import_commander4 = require("commander");
11087
- var import_fs16 = require("fs");
11095
+ var import_fs15 = require("fs");
11088
11096
 
11089
11097
  // src/cli/crd/create/createCRDscaffold.ts
11090
11098
  var createCRDscaffold = (group2, version3, kind8, data) => {
@@ -11177,13 +11185,13 @@ function create_default() {
11177
11185
  ).choices(["Namespaced", "Cluster"]).default("Namespaced")
11178
11186
  ).option("-d, --domain <domain>", "Optional domain for CRD (e.g. pepr.dev)", "pepr.dev").requiredOption("-g, --group <group>", "API group (e.g. cache)").requiredOption("-k, --kind <kind>", "Kind name (e.g. memcached)").option("-p, --plural <plural>", "Plural name for CRD (e.g. memcacheds)").requiredOption("-s, --short-name <name>", "Short name for CRD (e.g. mc)").requiredOption("-v, --version <version>", "API version (e.g. v1alpha1)").action(async ({ group: group2, version: version3, kind: kind8, domain, scope, plural: plural2, shortName }) => {
11179
11187
  logger_default.warn("This feature is currently in alpha.");
11180
- const outputDir2 = import_path8.default.resolve(`./api/${version3}`);
11181
- await createDirectoryIfNotExists(outputDir2);
11182
- await import_fs16.promises.writeFile(
11188
+ const outputDir = import_path8.default.resolve(`./api/${version3}`);
11189
+ await createDirectoryIfNotExists(outputDir);
11190
+ await import_fs15.promises.writeFile(
11183
11191
  `./api/${version3}/${kind8.toLowerCase()}_types.ts`,
11184
11192
  createCRDscaffold(group2, version3, kind8, { domain, scope, plural: plural2, shortName })
11185
11193
  );
11186
- logger_default.info(`\u2714 Created ${kind8} TypeScript definition in ${outputDir2}`);
11194
+ logger_default.info(`\u2714 Created ${kind8} TypeScript definition in ${outputDir}`);
11187
11195
  });
11188
11196
  }
11189
11197