kubernetes-fluent-client 3.0.4 → 3.0.5

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.
Files changed (74) hide show
  1. package/e2e/cli.e2e.test.ts +11 -7
  2. package/package.json +6 -6
  3. package/dist/cli.d.ts +0 -3
  4. package/dist/cli.d.ts.map +0 -1
  5. package/dist/cli.js +0 -68
  6. package/dist/fetch.d.ts +0 -22
  7. package/dist/fetch.d.ts.map +0 -1
  8. package/dist/fetch.js +0 -82
  9. package/dist/fetch.test.d.ts +0 -2
  10. package/dist/fetch.test.d.ts.map +0 -1
  11. package/dist/fetch.test.js +0 -97
  12. package/dist/fileSystem.d.ts +0 -11
  13. package/dist/fileSystem.d.ts.map +0 -1
  14. package/dist/fileSystem.js +0 -42
  15. package/dist/fileSystem.test.d.ts +0 -2
  16. package/dist/fileSystem.test.d.ts.map +0 -1
  17. package/dist/fileSystem.test.js +0 -75
  18. package/dist/fluent/index.d.ts +0 -12
  19. package/dist/fluent/index.d.ts.map +0 -1
  20. package/dist/fluent/index.js +0 -228
  21. package/dist/fluent/index.test.d.ts +0 -2
  22. package/dist/fluent/index.test.d.ts.map +0 -1
  23. package/dist/fluent/index.test.js +0 -193
  24. package/dist/fluent/types.d.ts +0 -187
  25. package/dist/fluent/types.d.ts.map +0 -1
  26. package/dist/fluent/types.js +0 -16
  27. package/dist/fluent/utils.d.ts +0 -41
  28. package/dist/fluent/utils.d.ts.map +0 -1
  29. package/dist/fluent/utils.js +0 -153
  30. package/dist/fluent/utils.test.d.ts +0 -2
  31. package/dist/fluent/utils.test.d.ts.map +0 -1
  32. package/dist/fluent/utils.test.js +0 -215
  33. package/dist/fluent/watch.d.ts +0 -86
  34. package/dist/fluent/watch.d.ts.map +0 -1
  35. package/dist/fluent/watch.js +0 -425
  36. package/dist/fluent/watch.spec.d.ts +0 -2
  37. package/dist/fluent/watch.spec.d.ts.map +0 -1
  38. package/dist/fluent/watch.spec.js +0 -261
  39. package/dist/generate.d.ts +0 -84
  40. package/dist/generate.d.ts.map +0 -1
  41. package/dist/generate.js +0 -208
  42. package/dist/generate.test.d.ts +0 -2
  43. package/dist/generate.test.d.ts.map +0 -1
  44. package/dist/generate.test.js +0 -320
  45. package/dist/helpers.d.ts +0 -33
  46. package/dist/helpers.d.ts.map +0 -1
  47. package/dist/helpers.js +0 -103
  48. package/dist/helpers.test.d.ts +0 -2
  49. package/dist/helpers.test.d.ts.map +0 -1
  50. package/dist/helpers.test.js +0 -37
  51. package/dist/index.d.ts +0 -14
  52. package/dist/index.d.ts.map +0 -1
  53. package/dist/index.js +0 -60
  54. package/dist/kinds.d.ts +0 -16
  55. package/dist/kinds.d.ts.map +0 -1
  56. package/dist/kinds.js +0 -570
  57. package/dist/kinds.test.d.ts +0 -2
  58. package/dist/kinds.test.d.ts.map +0 -1
  59. package/dist/kinds.test.js +0 -155
  60. package/dist/patch.d.ts +0 -7
  61. package/dist/patch.d.ts.map +0 -1
  62. package/dist/patch.js +0 -2
  63. package/dist/postProcessing.d.ts +0 -246
  64. package/dist/postProcessing.d.ts.map +0 -1
  65. package/dist/postProcessing.js +0 -497
  66. package/dist/postProcessing.test.d.ts +0 -2
  67. package/dist/postProcessing.test.d.ts.map +0 -1
  68. package/dist/postProcessing.test.js +0 -550
  69. package/dist/types.d.ts +0 -32
  70. package/dist/types.d.ts.map +0 -1
  71. package/dist/types.js +0 -16
  72. package/dist/upstream.d.ts +0 -4
  73. package/dist/upstream.d.ts.map +0 -1
  74. package/dist/upstream.js +0 -56
@@ -1,84 +0,0 @@
1
- import { InputData, TargetLanguage } from "quicktype-core";
2
- import { CustomResourceDefinition } from "./upstream";
3
- import { LogFn } from "./types";
4
- export interface GenerateOptions {
5
- source: string;
6
- directory?: string;
7
- plain?: boolean;
8
- language?: string | TargetLanguage;
9
- npmPackage?: string;
10
- logFn: LogFn;
11
- noPost?: boolean;
12
- }
13
- /**
14
- * Converts a CustomResourceDefinition to TypeScript types
15
- *
16
- * @param crd - The CustomResourceDefinition object to convert.
17
- * @param opts - The options for generating the TypeScript types.
18
- * @returns A promise that resolves to a record of generated TypeScript types.
19
- */
20
- export declare function convertCRDtoTS(crd: CustomResourceDefinition, opts: GenerateOptions): Promise<{
21
- results: Record<string, string[]>;
22
- name: string;
23
- crd: CustomResourceDefinition;
24
- version: string;
25
- }[]>;
26
- /**
27
- * Prepares the input data for quicktype from the provided schema.
28
- *
29
- * @param name - The name of the schema.
30
- * @param schema - The JSON schema as a string.
31
- * @returns A promise that resolves to the input data for quicktype.
32
- */
33
- export declare function prepareInputData(name: string, schema: string): Promise<InputData>;
34
- /**
35
- * Generates TypeScript types using quicktype.
36
- *
37
- * @param inputData - The input data for quicktype.
38
- * @param opts - The options for generating the TypeScript types.
39
- * @returns A promise that resolves to an array of generated TypeScript type lines.
40
- */
41
- export declare function generateTypes(inputData: InputData, opts: GenerateOptions): Promise<string[]>;
42
- /**
43
- * Writes the processed lines to the output file.
44
- *
45
- * @param fileName - The name of the file to write.
46
- * @param directory - The directory where the file will be written.
47
- * @param content - The content to write to the file.
48
- * @param language - The programming language of the file.
49
- */
50
- export declare function writeGeneratedFile(fileName: string, directory: string, content: string[], language: string | TargetLanguage): void;
51
- /**
52
- * Reads or fetches a CustomResourceDefinition from a file, URL, or the cluster.
53
- *
54
- * @param opts - The options for generating the TypeScript types.
55
- * @returns A promise that resolves to an array of CustomResourceDefinition objects.
56
- */
57
- export declare function readOrFetchCrd(opts: GenerateOptions): Promise<CustomResourceDefinition[]>;
58
- /**
59
- * Resolves the source file path, treating relative paths as local files.
60
- *
61
- * @param source - The source path to resolve.
62
- * @returns The resolved file path.
63
- */
64
- export declare function resolveFilePath(source: string): string;
65
- /**
66
- * Tries to parse the source as a URL.
67
- *
68
- * @param source - The source string to parse as a URL.
69
- * @returns The parsed URL object or null if parsing fails.
70
- */
71
- export declare function tryParseUrl(source: string): URL | null;
72
- /**
73
- * Main generate function to convert CRDs to TypeScript types.
74
- *
75
- * @param opts - The options for generating the TypeScript types.
76
- * @returns A promise that resolves to a record of generated TypeScript types.
77
- */
78
- export declare function generate(opts: GenerateOptions): Promise<{
79
- results: Record<string, string[]>;
80
- name: string;
81
- crd: CustomResourceDefinition;
82
- version: string;
83
- }[]>;
84
- //# sourceMappingURL=generate.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"generate.d.ts","sourceRoot":"","sources":["../src/generate.ts"],"names":[],"mappings":"AAMA,OAAO,EAEL,SAAS,EAET,cAAc,EAEf,MAAM,gBAAgB,CAAC;AAIxB,OAAO,EAAE,wBAAwB,EAAE,MAAM,YAAY,CAAC;AACtD,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAEhC,MAAM,WAAW,eAAe;IAC9B,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,QAAQ,CAAC,EAAE,MAAM,GAAG,cAAc,CAAC;IACnC,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,KAAK,EAAE,KAAK,CAAC;IACb,MAAM,CAAC,EAAE,OAAO,CAAC;CAClB;AAED;;;;;;GAMG;AACH,wBAAsB,cAAc,CAClC,GAAG,EAAE,wBAAwB,EAC7B,IAAI,EAAE,eAAe,GACpB,OAAO,CACR;IACE,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC;IAClC,IAAI,EAAE,MAAM,CAAC;IACb,GAAG,EAAE,wBAAwB,CAAC;IAC9B,OAAO,EAAE,MAAM,CAAC;CACjB,EAAE,CACJ,CAuCA;AAED;;;;;;GAMG;AACH,wBAAsB,gBAAgB,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,SAAS,CAAC,CAYvF;AAED;;;;;;GAMG;AACH,wBAAsB,aAAa,CACjC,SAAS,EAAE,SAAS,EACpB,IAAI,EAAE,eAAe,GACpB,OAAO,CAAC,MAAM,EAAE,CAAC,CAYnB;AAED;;;;;;;GAOG;AACH,wBAAgB,kBAAkB,CAChC,QAAQ,EAAE,MAAM,EAChB,SAAS,EAAE,MAAM,EACjB,OAAO,EAAE,MAAM,EAAE,EACjB,QAAQ,EAAE,MAAM,GAAG,cAAc,GAChC,IAAI,CAON;AAED;;;;;GAKG;AACH,wBAAsB,cAAc,CAAC,IAAI,EAAE,eAAe,GAAG,OAAO,CAAC,wBAAwB,EAAE,CAAC,CA0B/F;AAED;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAEtD;AAED;;;;;GAKG;AACH,wBAAgB,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,GAAG,GAAG,IAAI,CAMtD;AAED;;;;;GAKG;AACH,wBAAsB,QAAQ,CAAC,IAAI,EAAE,eAAe,GAAG,OAAO,CAC5D;IACE,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC;IAClC,IAAI,EAAE,MAAM,CAAC;IACb,GAAG,EAAE,wBAAwB,CAAC;IAC9B,OAAO,EAAE,MAAM,CAAC;CACjB,EAAE,CACJ,CA8BA"}
package/dist/generate.js DELETED
@@ -1,208 +0,0 @@
1
- "use strict";
2
- // SPDX-License-Identifier: Apache-2.0
3
- // SPDX-FileCopyrightText: 2023-Present The Kubernetes Fluent Client Authors
4
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
5
- if (k2 === undefined) k2 = k;
6
- var desc = Object.getOwnPropertyDescriptor(m, k);
7
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
8
- desc = { enumerable: true, get: function() { return m[k]; } };
9
- }
10
- Object.defineProperty(o, k2, desc);
11
- }) : (function(o, m, k, k2) {
12
- if (k2 === undefined) k2 = k;
13
- o[k2] = m[k];
14
- }));
15
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
16
- Object.defineProperty(o, "default", { enumerable: true, value: v });
17
- }) : function(o, v) {
18
- o["default"] = v;
19
- });
20
- var __importStar = (this && this.__importStar) || function (mod) {
21
- if (mod && mod.__esModule) return mod;
22
- var result = {};
23
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
24
- __setModuleDefault(result, mod);
25
- return result;
26
- };
27
- Object.defineProperty(exports, "__esModule", { value: true });
28
- exports.convertCRDtoTS = convertCRDtoTS;
29
- exports.prepareInputData = prepareInputData;
30
- exports.generateTypes = generateTypes;
31
- exports.writeGeneratedFile = writeGeneratedFile;
32
- exports.readOrFetchCrd = readOrFetchCrd;
33
- exports.resolveFilePath = resolveFilePath;
34
- exports.tryParseUrl = tryParseUrl;
35
- exports.generate = generate;
36
- const client_node_1 = require("@kubernetes/client-node");
37
- const fs = __importStar(require("fs"));
38
- const path = __importStar(require("path"));
39
- const quicktype_core_1 = require("quicktype-core");
40
- const fetch_1 = require("./fetch");
41
- const fluent_1 = require("./fluent");
42
- const upstream_1 = require("./upstream");
43
- /**
44
- * Converts a CustomResourceDefinition to TypeScript types
45
- *
46
- * @param crd - The CustomResourceDefinition object to convert.
47
- * @param opts - The options for generating the TypeScript types.
48
- * @returns A promise that resolves to a record of generated TypeScript types.
49
- */
50
- async function convertCRDtoTS(crd, opts) {
51
- const name = crd.spec.names.kind;
52
- const results = {};
53
- const output = [];
54
- // Check for missing versions or empty schema
55
- if (!crd.spec.versions || crd.spec.versions.length === 0) {
56
- opts.logFn(`Skipping ${crd.metadata?.name}, it does not appear to be a CRD`);
57
- return [];
58
- }
59
- // Iterate through each version of the CRD
60
- for (const match of crd.spec.versions) {
61
- if (!match.schema?.openAPIV3Schema) {
62
- opts.logFn(`Skipping ${crd.metadata?.name ?? "unknown"}, it does not appear to have a valid schema`);
63
- continue;
64
- }
65
- const schema = JSON.stringify(match.schema.openAPIV3Schema);
66
- opts.logFn(`- Generating ${crd.spec.group}/${match.name} types for ${name}`);
67
- const inputData = await prepareInputData(name, schema);
68
- const generatedTypes = await generateTypes(inputData, opts);
69
- const fileName = `${name.toLowerCase()}-${match.name.toLowerCase()}`;
70
- writeGeneratedFile(fileName, opts.directory || "", generatedTypes, opts.language || "ts");
71
- results[fileName] = generatedTypes;
72
- output.push({ results, name, crd, version: match.name });
73
- }
74
- return output;
75
- }
76
- /**
77
- * Prepares the input data for quicktype from the provided schema.
78
- *
79
- * @param name - The name of the schema.
80
- * @param schema - The JSON schema as a string.
81
- * @returns A promise that resolves to the input data for quicktype.
82
- */
83
- async function prepareInputData(name, schema) {
84
- // Create a new JSONSchemaInput
85
- const schemaInput = new quicktype_core_1.JSONSchemaInput(new quicktype_core_1.FetchingJSONSchemaStore());
86
- // Add the schema to the input
87
- await schemaInput.addSource({ name, schema });
88
- // Create a new InputData object
89
- const inputData = new quicktype_core_1.InputData();
90
- inputData.addInput(schemaInput);
91
- return inputData;
92
- }
93
- /**
94
- * Generates TypeScript types using quicktype.
95
- *
96
- * @param inputData - The input data for quicktype.
97
- * @param opts - The options for generating the TypeScript types.
98
- * @returns A promise that resolves to an array of generated TypeScript type lines.
99
- */
100
- async function generateTypes(inputData, opts) {
101
- // If the language is not specified, default to TypeScript
102
- const language = opts.language || "ts";
103
- // Generate the types
104
- const out = await (0, quicktype_core_1.quicktype)({
105
- inputData,
106
- lang: language,
107
- rendererOptions: { "just-types": "true" },
108
- });
109
- return out.lines;
110
- }
111
- /**
112
- * Writes the processed lines to the output file.
113
- *
114
- * @param fileName - The name of the file to write.
115
- * @param directory - The directory where the file will be written.
116
- * @param content - The content to write to the file.
117
- * @param language - The programming language of the file.
118
- */
119
- function writeGeneratedFile(fileName, directory, content, language) {
120
- language = language || "ts";
121
- if (!directory)
122
- return;
123
- const filePath = path.join(directory, `${fileName}.${language}`);
124
- fs.mkdirSync(directory, { recursive: true });
125
- fs.writeFileSync(filePath, content.join("\n"));
126
- }
127
- /**
128
- * Reads or fetches a CustomResourceDefinition from a file, URL, or the cluster.
129
- *
130
- * @param opts - The options for generating the TypeScript types.
131
- * @returns A promise that resolves to an array of CustomResourceDefinition objects.
132
- */
133
- async function readOrFetchCrd(opts) {
134
- try {
135
- const filePath = resolveFilePath(opts.source);
136
- if (fs.existsSync(filePath)) {
137
- opts.logFn(`Attempting to load ${opts.source} as a local file`);
138
- const content = fs.readFileSync(filePath, "utf8");
139
- return (0, client_node_1.loadAllYaml)(content);
140
- }
141
- const url = tryParseUrl(opts.source);
142
- if (url) {
143
- opts.logFn(`Attempting to load ${opts.source} as a URL`);
144
- const { ok, data } = await (0, fetch_1.fetch)(url.href);
145
- if (ok) {
146
- return (0, client_node_1.loadAllYaml)(data);
147
- }
148
- }
149
- // Fallback to Kubernetes cluster
150
- opts.logFn(`Attempting to read ${opts.source} from the Kubernetes cluster`);
151
- return [await (0, fluent_1.K8s)(upstream_1.CustomResourceDefinition).Get(opts.source)];
152
- }
153
- catch (error) {
154
- opts.logFn(`Error loading CRD: ${error.message}`);
155
- throw new Error(`Failed to read ${opts.source} as a file, URL, or Kubernetes CRD`);
156
- }
157
- }
158
- /**
159
- * Resolves the source file path, treating relative paths as local files.
160
- *
161
- * @param source - The source path to resolve.
162
- * @returns The resolved file path.
163
- */
164
- function resolveFilePath(source) {
165
- return source.startsWith("/") ? source : path.join(process.cwd(), source);
166
- }
167
- /**
168
- * Tries to parse the source as a URL.
169
- *
170
- * @param source - The source string to parse as a URL.
171
- * @returns The parsed URL object or null if parsing fails.
172
- */
173
- function tryParseUrl(source) {
174
- try {
175
- return new URL(source);
176
- }
177
- catch {
178
- return null;
179
- }
180
- }
181
- /**
182
- * Main generate function to convert CRDs to TypeScript types.
183
- *
184
- * @param opts - The options for generating the TypeScript types.
185
- * @returns A promise that resolves to a record of generated TypeScript types.
186
- */
187
- async function generate(opts) {
188
- const crds = (await readOrFetchCrd(opts)).filter(crd => !!crd);
189
- const allResults = [];
190
- opts.logFn("");
191
- for (const crd of crds) {
192
- if (crd.kind !== "CustomResourceDefinition" || !crd.spec?.versions?.length) {
193
- opts.logFn(`Skipping ${crd?.metadata?.name}, it does not appear to be a CRD`);
194
- // Ignore empty and non-CRD objects
195
- continue;
196
- }
197
- allResults.push(...(await convertCRDtoTS(crd, opts)));
198
- }
199
- if (opts.directory) {
200
- // Notify the user that the files have been generated
201
- opts.logFn(`\n✅ Generated ${allResults.length} files in the ${opts.directory} directory`);
202
- }
203
- else {
204
- // Log a message about the number of generated files even when no directory is provided
205
- opts.logFn(`\n✅ Generated ${allResults.length} files`);
206
- }
207
- return allResults;
208
- }
@@ -1,2 +0,0 @@
1
- export {};
2
- //# sourceMappingURL=generate.test.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"generate.test.d.ts","sourceRoot":"","sources":["../src/generate.test.ts"],"names":[],"mappings":""}
@@ -1,320 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- const globals_1 = require("@jest/globals");
7
- const generate_1 = require("./generate");
8
- const fs_1 = __importDefault(require("fs"));
9
- const path_1 = __importDefault(require("path"));
10
- const quicktype_core_1 = require("quicktype-core");
11
- const fetch_1 = require("./fetch");
12
- const client_node_1 = require("@kubernetes/client-node");
13
- const fluent_1 = require("./fluent");
14
- const upstream_1 = require("./upstream");
15
- // Mock the file system
16
- globals_1.jest.mock("fs", () => ({
17
- ...globals_1.jest.requireActual("fs"), // Preserve the rest of the fs module
18
- writeFileSync: globals_1.jest.fn(), // Mock only writeFileSync
19
- existsSync: globals_1.jest.fn(),
20
- readFileSync: globals_1.jest.fn(),
21
- }));
22
- globals_1.jest.mock("./fetch");
23
- globals_1.jest.mock("quicktype-core", () => {
24
- const actualQuicktypeCore = globals_1.jest.requireActual("quicktype-core");
25
- return {
26
- quicktype: globals_1.jest.fn(),
27
- JSONSchemaInput: actualQuicktypeCore.JSONSchemaInput,
28
- FetchingJSONSchemaStore: actualQuicktypeCore.FetchingJSONSchemaStore,
29
- InputData: actualQuicktypeCore.InputData,
30
- };
31
- });
32
- globals_1.jest.mock("@kubernetes/client-node", () => {
33
- const actualModule = globals_1.jest.requireActual("@kubernetes/client-node");
34
- return {
35
- ...(typeof actualModule === "object" ? actualModule : {}),
36
- loadAllYaml: globals_1.jest.fn(), // Mock only the specific method
37
- };
38
- });
39
- globals_1.jest.mock("./fluent", () => ({
40
- K8s: globals_1.jest.fn(),
41
- }));
42
- globals_1.jest.mock("./generate", () => {
43
- const actualGenerate = globals_1.jest.requireActual("./generate");
44
- return {
45
- ...(typeof actualGenerate === "object" ? actualGenerate : {}),
46
- resolveFilePath: globals_1.jest.fn(), // Mock resolveFilePath globally
47
- tryParseUrl: globals_1.jest.fn(),
48
- };
49
- });
50
- // Sample CRD content to use in tests
51
- const sampleCrd = {
52
- apiVersion: "apiextensions.k8s.io/v1",
53
- kind: "CustomResourceDefinition",
54
- metadata: { name: "movies.example.com" },
55
- spec: {
56
- group: "example.com",
57
- names: { kind: "Movie", plural: "movies" },
58
- scope: "Namespaced",
59
- versions: [
60
- {
61
- name: "v1",
62
- served: true,
63
- storage: true,
64
- schema: {
65
- openAPIV3Schema: {
66
- type: "object",
67
- description: "Movie nerd",
68
- properties: {
69
- spec: {
70
- properties: {
71
- title: { type: "string" },
72
- author: { type: "string" },
73
- },
74
- },
75
- },
76
- },
77
- },
78
- },
79
- ],
80
- },
81
- };
82
- const expectedMovie = [
83
- "/**",
84
- " * Movie nerd",
85
- " */",
86
- "export interface Movie {",
87
- " spec?: any[] | boolean | number | number | null | SpecObject | string;",
88
- " [property: string]: any;",
89
- "}",
90
- "",
91
- "export interface SpecObject {",
92
- " author?: string;",
93
- " title?: string;",
94
- " [property: string]: any;",
95
- "}",
96
- "",
97
- ];
98
- (0, globals_1.describe)("CRD Generate", () => {
99
- let logFn; // Mock log function
100
- (0, globals_1.beforeEach)(() => {
101
- globals_1.jest.clearAllMocks(); // Reset all mocks before each test
102
- logFn = globals_1.jest.fn(); // Mock the log function with correct typing
103
- });
104
- (0, globals_1.test)("convertCRDtoTS should generate the expected TypeScript file", async () => {
105
- // Mock convertCRDtoTS to return a valid result structure
106
- quicktype_core_1.quicktype.mockResolvedValueOnce({
107
- lines: expectedMovie,
108
- annotations: [],
109
- });
110
- const options = {
111
- source: "test-crd.yaml",
112
- language: "ts",
113
- logFn,
114
- directory: "test-dir",
115
- plain: false,
116
- npmPackage: "kubernetes-fluent-client",
117
- };
118
- // Call convertCRDtoTS with sample CRD
119
- const result = await (0, generate_1.convertCRDtoTS)(sampleCrd, options);
120
- // Extract the generated types from the result
121
- const generatedTypes = result[0].results["movie-v1"];
122
- // Assert that the generated types match the expected TypeScript code
123
- (0, globals_1.expect)(generatedTypes).toEqual(expectedMovie);
124
- // Assert the file writing happens with the expected TypeScript content
125
- (0, globals_1.expect)(fs_1.default.writeFileSync).toHaveBeenCalledWith(path_1.default.join("test-dir", "movie-v1.ts"), expectedMovie.join("\n"));
126
- // Assert the logs contain expected log messages
127
- (0, globals_1.expect)(logFn).toHaveBeenCalledWith("- Generating example.com/v1 types for Movie");
128
- });
129
- });
130
- (0, globals_1.describe)("readOrFetchCrd", () => {
131
- let mockOpts;
132
- (0, globals_1.beforeEach)(() => {
133
- globals_1.jest.clearAllMocks();
134
- mockOpts = {
135
- source: "mock-file-path",
136
- logFn: globals_1.jest.fn(),
137
- };
138
- // Reapply mock for resolveFilePath inside beforeEach
139
- const { resolveFilePath } = globals_1.jest.requireMock("./generate");
140
- resolveFilePath.mockReturnValue("mock-file-path");
141
- });
142
- (0, globals_1.test)("should load CRD from a local file", async () => {
143
- // Inside the test:
144
- const absoluteFilePath = path_1.default.join(process.cwd(), "mock-file-path");
145
- // Mock file system functions
146
- fs_1.default.existsSync.mockReturnValue(true);
147
- fs_1.default.readFileSync.mockReturnValue("mock file content");
148
- // Mock loadAllYaml to return parsed CRD
149
- const mockCrd = [{ kind: "CustomResourceDefinition" }];
150
- client_node_1.loadAllYaml.mockReturnValue(mockCrd);
151
- // Call the function
152
- const result = await (0, generate_1.readOrFetchCrd)(mockOpts);
153
- // Assert fs and loadAllYaml were called with correct args
154
- (0, globals_1.expect)(fs_1.default.existsSync).toHaveBeenCalledWith(absoluteFilePath);
155
- (0, globals_1.expect)(fs_1.default.readFileSync).toHaveBeenCalledWith(absoluteFilePath, "utf8");
156
- (0, globals_1.expect)(client_node_1.loadAllYaml).toHaveBeenCalledWith("mock file content");
157
- // Assert the result matches the mocked CRD
158
- (0, globals_1.expect)(result).toEqual(mockCrd);
159
- // Assert log function was called with correct message
160
- (0, globals_1.expect)(mockOpts.logFn).toHaveBeenCalledWith("Attempting to load mock-file-path as a local file");
161
- });
162
- });
163
- (0, globals_1.describe)("readOrFetchCrd with URL", () => {
164
- let mockOpts;
165
- (0, globals_1.beforeEach)(() => {
166
- globals_1.jest.clearAllMocks();
167
- mockOpts = {
168
- source: "http://example.com/mock-crd",
169
- logFn: globals_1.jest.fn(),
170
- };
171
- // Mock resolveFilePath to simulate URL logic
172
- const { resolveFilePath } = globals_1.jest.requireMock("./generate");
173
- resolveFilePath.mockReturnValue("mock-file-path");
174
- // Ensure fs.existsSync returns false for URL tests to skip file logic
175
- fs_1.default.existsSync.mockReturnValue(false);
176
- });
177
- (0, globals_1.test)("should fetch CRD from a URL and parse YAML", async () => {
178
- const { tryParseUrl } = globals_1.jest.requireMock("./generate");
179
- tryParseUrl.mockReturnValue(new URL("http://example.com/mock-crd"));
180
- // Mock fetch to return a valid response
181
- fetch_1.fetch.mockResolvedValue({
182
- ok: true,
183
- data: "mock fetched data",
184
- status: 0,
185
- statusText: "",
186
- });
187
- // Mock loadAllYaml to return parsed CRD
188
- const mockCrd = [{ kind: "CustomResourceDefinition" }];
189
- client_node_1.loadAllYaml.mockReturnValue(mockCrd);
190
- // Call the function
191
- const result = await (0, generate_1.readOrFetchCrd)(mockOpts);
192
- // Assert fetch was called with correct URL
193
- (0, globals_1.expect)(fetch_1.fetch).toHaveBeenCalledWith("http://example.com/mock-crd");
194
- // Assert loadAllYaml was called with fetched data
195
- (0, globals_1.expect)(client_node_1.loadAllYaml).toHaveBeenCalledWith("mock fetched data");
196
- // Assert the result matches the mocked CRD
197
- (0, globals_1.expect)(result).toEqual(mockCrd);
198
- // Assert log function was called with correct message
199
- (0, globals_1.expect)(mockOpts.logFn).toHaveBeenCalledWith("Attempting to load http://example.com/mock-crd as a URL");
200
- });
201
- });
202
- (0, globals_1.describe)("readOrFetchCrd from Kubernetes cluster", () => {
203
- let mockOpts;
204
- (0, globals_1.beforeEach)(() => {
205
- globals_1.jest.clearAllMocks();
206
- mockOpts = {
207
- source: "my-crd",
208
- logFn: globals_1.jest.fn(),
209
- };
210
- // Mock resolveFilePath and tryParseUrl to return null or invalid results
211
- const { resolveFilePath, tryParseUrl } = globals_1.jest.requireMock("./generate");
212
- resolveFilePath.mockReturnValue("mock-file-path");
213
- tryParseUrl.mockReturnValue(null);
214
- // Ensure fs.existsSync returns false to force fallback to Kubernetes
215
- fs_1.default.existsSync.mockReturnValue(false);
216
- });
217
- (0, globals_1.test)("should load CRD from Kubernetes cluster", async () => {
218
- // Mock K8s to return a mocked CRD from the Kubernetes cluster
219
- const mockCrd = { kind: "CustomResourceDefinition" };
220
- const mockK8sGet = globals_1.jest
221
- .fn()
222
- .mockResolvedValue(mockCrd);
223
- fluent_1.K8s.mockReturnValue({ Get: mockK8sGet });
224
- // Call the function
225
- const result = await (0, generate_1.readOrFetchCrd)(mockOpts);
226
- // Assert K8s.Get was called with the correct source
227
- (0, globals_1.expect)(fluent_1.K8s).toHaveBeenCalledWith(upstream_1.CustomResourceDefinition);
228
- (0, globals_1.expect)(mockK8sGet).toHaveBeenCalledWith("my-crd");
229
- // Assert the result matches the mocked CRD
230
- (0, globals_1.expect)(result).toEqual([mockCrd]);
231
- // Assert log function was called with correct message
232
- (0, globals_1.expect)(mockOpts.logFn).toHaveBeenCalledWith("Attempting to read my-crd from the Kubernetes cluster");
233
- });
234
- (0, globals_1.test)("should log an error if Kubernetes cluster read fails", async () => {
235
- // Mock K8s to throw an error
236
- const mockError = new Error("Kubernetes API error");
237
- const mockK8sGet = globals_1.jest.fn().mockRejectedValue(mockError);
238
- fluent_1.K8s.mockReturnValue({ Get: mockK8sGet });
239
- // Call the function and assert that it throws an error
240
- await (0, globals_1.expect)((0, generate_1.readOrFetchCrd)(mockOpts)).rejects.toThrowError(`Failed to read my-crd as a file, URL, or Kubernetes CRD`);
241
- // Assert log function was called with error message
242
- (0, globals_1.expect)(mockOpts.logFn).toHaveBeenCalledWith("Error loading CRD: Kubernetes API error");
243
- // Assert K8s.Get was called with the correct source
244
- (0, globals_1.expect)(fluent_1.K8s).toHaveBeenCalledWith(upstream_1.CustomResourceDefinition);
245
- (0, globals_1.expect)(mockK8sGet).toHaveBeenCalledWith("my-crd");
246
- });
247
- });
248
- (0, globals_1.describe)("readOrFetchCrd error handling", () => {
249
- let mockOpts;
250
- (0, globals_1.beforeEach)(() => {
251
- globals_1.jest.clearAllMocks();
252
- mockOpts = {
253
- source: "mock-source",
254
- logFn: globals_1.jest.fn(),
255
- };
256
- });
257
- (0, globals_1.test)("should throw an error if file reading fails", async () => {
258
- fs_1.default.existsSync.mockReturnValue(true);
259
- fs_1.default.readFileSync.mockImplementation(() => {
260
- throw new Error("File read error");
261
- });
262
- await (0, globals_1.expect)((0, generate_1.readOrFetchCrd)(mockOpts)).rejects.toThrowError("Failed to read mock-source as a file, URL, or Kubernetes CRD");
263
- (0, globals_1.expect)(mockOpts.logFn).toHaveBeenCalledWith("Error loading CRD: File read error");
264
- });
265
- });
266
- (0, globals_1.describe)("convertCRDtoTS with invalid CRD", () => {
267
- (0, globals_1.test)("should skip CRD with no versions", async () => {
268
- const invalidCrd = {
269
- ...sampleCrd,
270
- spec: {
271
- ...sampleCrd.spec,
272
- versions: [], // CRD with no versions
273
- },
274
- };
275
- const options = {
276
- source: "mock-source",
277
- language: "ts",
278
- logFn: globals_1.jest.fn(), // Ensure the mock log function is set
279
- directory: "test-dir",
280
- plain: false,
281
- npmPackage: "kubernetes-fluent-client",
282
- };
283
- const result = await (0, generate_1.convertCRDtoTS)(invalidCrd, options);
284
- // Assert that result is empty due to invalid CRD
285
- (0, globals_1.expect)(result).toEqual([]);
286
- // Assert the log function is called with the correct message
287
- (0, globals_1.expect)(options.logFn).toHaveBeenCalledWith("Skipping movies.example.com, it does not appear to be a CRD");
288
- });
289
- (0, globals_1.test)("should handle schema with no OpenAPI schema", async () => {
290
- // Modify the sampleCrd to simulate the invalid CRD
291
- const invalidCrd = {
292
- ...sampleCrd,
293
- spec: {
294
- ...sampleCrd.spec,
295
- versions: [
296
- {
297
- name: "v1",
298
- served: true,
299
- storage: true,
300
- schema: undefined, // No OpenAPI schema
301
- },
302
- ],
303
- },
304
- };
305
- const options = {
306
- source: "mock-source",
307
- language: "ts",
308
- logFn: globals_1.jest.fn(), // Mock log function
309
- directory: "test-dir",
310
- plain: false,
311
- npmPackage: "kubernetes-fluent-client",
312
- };
313
- // Call the convertCRDtoTS function with the invalid CRD
314
- const result = await (0, generate_1.convertCRDtoTS)(invalidCrd, options);
315
- // Assert that result is empty due to invalid schema
316
- (0, globals_1.expect)(result).toEqual([]);
317
- // Assert that the log function was called with the appropriate message
318
- (0, globals_1.expect)(options.logFn).toHaveBeenCalledWith("Skipping movies.example.com, it does not appear to have a valid schema");
319
- });
320
- });
package/dist/helpers.d.ts DELETED
@@ -1,33 +0,0 @@
1
- import { Cluster } from "@kubernetes/client-node";
2
- /**
3
- * Get an environment variable (Node, Deno or Bun), or throw an error if it's not set.
4
- *
5
- * @example
6
- * const value = fromEnv("MY_ENV_VAR");
7
- * console.log(value);
8
- * // => "my-value"
9
- *
10
- * @example
11
- * const value = fromEnv("MY_MISSING_ENV_VAR");
12
- * // => Error: Environment variable MY_MISSING_ENV_VAR is not set
13
- *
14
- * @param name The name of the environment variable to get.
15
- * @returns The value of the environment variable.
16
- * @throws An error if the environment variable is not set.
17
- */
18
- export declare function fromEnv(name: string): string;
19
- /**
20
- * Wait for the Kubernetes cluster to be ready.
21
- *
22
- * @param seconds The number of seconds to wait for the cluster to be ready.
23
- * @returns The current cluster.
24
- */
25
- export declare function waitForCluster(seconds?: number): Promise<Cluster>;
26
- /**
27
- * Determines if object has logs.
28
- *
29
- * @param kind The kind of Kubernetes object.
30
- * @returns boolean.
31
- */
32
- export declare function hasLogs(kind: string): boolean;
33
- //# sourceMappingURL=helpers.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"helpers.d.ts","sourceRoot":"","sources":["../src/helpers.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,OAAO,EAAc,MAAM,yBAAyB,CAAC;AAkB9D;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,OAAO,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAqB5C;AAED;;;;;GAKG;AACH,wBAAsB,cAAc,CAAC,OAAO,SAAK,GAAG,OAAO,CAAC,OAAO,CAAC,CAenE;AAED;;;;;GAKG;AACH,wBAAgB,OAAO,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAuB7C"}