@kubb/core 0.27.1 → 0.28.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +63 -37
- package/dist/index.js +105 -113
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +105 -113
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -1,9 +1,6 @@
|
|
|
1
1
|
import EventEmitter from 'events';
|
|
2
|
+
import { DirectoryTreeOptions } from 'directory-tree';
|
|
2
3
|
|
|
3
|
-
type GenerateTreeNodeOptions = {
|
|
4
|
-
extensions?: RegExp;
|
|
5
|
-
exclude?: RegExp[];
|
|
6
|
-
};
|
|
7
4
|
declare class TreeNode<T = unknown> {
|
|
8
5
|
data: T;
|
|
9
6
|
parent?: TreeNode<T>;
|
|
@@ -14,7 +11,7 @@ declare class TreeNode<T = unknown> {
|
|
|
14
11
|
leaves(): this[];
|
|
15
12
|
root(): any;
|
|
16
13
|
forEach(callback: (treeNode: TreeNode<T>) => void): this;
|
|
17
|
-
static generate(path: string, options?:
|
|
14
|
+
static generate(path: string, options?: DirectoryTreeOptions): TreeNode<{
|
|
18
15
|
name: string;
|
|
19
16
|
path: string;
|
|
20
17
|
type: "file" | "directory";
|
|
@@ -65,8 +62,6 @@ type Status = 'new' | 'success' | 'removed';
|
|
|
65
62
|
|
|
66
63
|
declare class FileManager {
|
|
67
64
|
private cache;
|
|
68
|
-
private readonly root;
|
|
69
|
-
private readonly output;
|
|
70
65
|
emitter: EventEmitter;
|
|
71
66
|
events: {
|
|
72
67
|
emitFile: (id: string, file: File) => void;
|
|
@@ -74,29 +69,21 @@ declare class FileManager {
|
|
|
74
69
|
emitStatusChangeById: (id: string, status: Status) => void;
|
|
75
70
|
emitSuccess: () => void;
|
|
76
71
|
emitRemove: (id: string, file: File) => void;
|
|
77
|
-
onAdd: (callback: (id: string, file: File) => void) =>
|
|
78
|
-
onStatusChange: (callback: (file: File) => void) =>
|
|
79
|
-
onStatusChangeById: (id: string, callback: (status: Status) => void) =>
|
|
80
|
-
onSuccess: (callback: () => void) =>
|
|
81
|
-
onRemove: (id: string, callback: (file: File) => void) =>
|
|
72
|
+
onAdd: (callback: (id: string, file: File) => void) => () => void;
|
|
73
|
+
onStatusChange: (callback: (file: File) => void) => () => void;
|
|
74
|
+
onStatusChangeById: (id: string, callback: (status: Status) => void) => () => void;
|
|
75
|
+
onSuccess: (callback: () => void) => () => void;
|
|
76
|
+
onRemove: (id: string, callback: (file: File) => void) => () => void;
|
|
82
77
|
};
|
|
83
|
-
constructor(
|
|
84
|
-
root?: string;
|
|
85
|
-
output?: string;
|
|
86
|
-
});
|
|
78
|
+
constructor();
|
|
87
79
|
private getCache;
|
|
88
80
|
private getCountOfStatus;
|
|
89
81
|
get files(): File[];
|
|
90
|
-
get tree(): TreeNode<{
|
|
91
|
-
name: string;
|
|
92
|
-
path: string;
|
|
93
|
-
type: "file" | "directory";
|
|
94
|
-
}>;
|
|
95
|
-
generateRootFiles(options: GenerateTreeNodeOptions): Promise<void>[];
|
|
96
82
|
add(file: File): Promise<File>;
|
|
97
83
|
setStatus(id: UUID, status: Status): void;
|
|
98
84
|
get(id: UUID): File | undefined;
|
|
99
85
|
remove(id: UUID): void;
|
|
86
|
+
static writeIndexes(root: string, output: string, options: Parameters<typeof TreeNode.generate>[1]): Promise<void>[];
|
|
100
87
|
}
|
|
101
88
|
|
|
102
89
|
interface Cache<TCache = any> {
|
|
@@ -126,30 +113,36 @@ type KubbConfig = {
|
|
|
126
113
|
* @default process.cwd()
|
|
127
114
|
*/
|
|
128
115
|
root: string;
|
|
129
|
-
mode?: 'single';
|
|
130
116
|
input: {
|
|
131
117
|
/**
|
|
132
|
-
* Path
|
|
118
|
+
* Path to be used as the input. Can be an absolute path, or a path relative from
|
|
119
|
+
* the defined root option.
|
|
133
120
|
*/
|
|
134
121
|
path: string;
|
|
135
122
|
};
|
|
136
123
|
output: {
|
|
137
124
|
/**
|
|
138
|
-
* Path to export
|
|
125
|
+
* Path to be used to export all generated files. Can be an absolute path, or a path relative from
|
|
126
|
+
* the defined root option.
|
|
139
127
|
*/
|
|
140
128
|
path: string;
|
|
129
|
+
/**
|
|
130
|
+
* Remove previous generated files and folders.
|
|
131
|
+
*/
|
|
141
132
|
clean?: boolean;
|
|
142
133
|
};
|
|
143
134
|
/**
|
|
144
135
|
* Array of Kubb plugins to use.
|
|
136
|
+
* The plugin/package can forsee some options that you need to pass through.
|
|
137
|
+
* Sometimes a plugin is depended on another plugin, if that's the case you will get an error back from the plugin you installed.
|
|
145
138
|
*/
|
|
146
139
|
plugins?: KubbPlugin[];
|
|
147
140
|
/**
|
|
148
|
-
* Hooks that
|
|
141
|
+
* Hooks that will be called when a specific action is triggered in Kubb.
|
|
149
142
|
*/
|
|
150
143
|
hooks?: {
|
|
151
144
|
/**
|
|
152
|
-
* Hook that will be
|
|
145
|
+
* Hook that will be triggerend at the end of all executions.
|
|
153
146
|
*/
|
|
154
147
|
done?: string | string[];
|
|
155
148
|
};
|
|
@@ -173,23 +166,55 @@ type PluginFactoryOptions<Options = unknown, Nested extends boolean = false, Api
|
|
|
173
166
|
api: Api;
|
|
174
167
|
};
|
|
175
168
|
type PluginLifecycle = {
|
|
169
|
+
/**
|
|
170
|
+
* Valdiate all plugins to see if their depended plugins are installed and configured.
|
|
171
|
+
* @type hookParallel
|
|
172
|
+
*/
|
|
176
173
|
validate: (this: PluginContext, plugins: KubbPlugin[]) => MaybePromise<ValidationResult>;
|
|
174
|
+
/**
|
|
175
|
+
* Start of the lifecycle of a plugin.
|
|
176
|
+
* @type hookParallel
|
|
177
|
+
*/
|
|
177
178
|
buildStart: (this: PluginContext, kubbConfig: KubbConfig) => MaybePromise<void>;
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
179
|
+
/**
|
|
180
|
+
* Resolve to an id based on importee(example: `./Pet.ts`) and directory(example: `./models`).
|
|
181
|
+
* @type hookFirst
|
|
182
|
+
* @example ('./Pet.ts', './src/gen/')
|
|
183
|
+
*/
|
|
184
|
+
resolveId: (this: PluginContext, fileName: string, directory?: string, options?: Record<string, any>) => OptionalPath;
|
|
185
|
+
/**
|
|
186
|
+
* Makes it possible to run async logic to override the path defined previously by `resolveId`.
|
|
187
|
+
* @type hookFirst
|
|
188
|
+
*/
|
|
189
|
+
load: (this: PluginContext, path: Path) => MaybePromise<TransformResult | null>;
|
|
190
|
+
/**
|
|
191
|
+
* Transform the source-code.
|
|
192
|
+
* @type hookReduceArg0
|
|
193
|
+
*/
|
|
194
|
+
transform: (this: PluginContext, source: string, path: Path) => MaybePromise<TransformResult>;
|
|
195
|
+
/**
|
|
196
|
+
* Write the result to the file-system based on the id(defined by `resolveId` or changed by `load`).
|
|
197
|
+
* @type hookParallel
|
|
198
|
+
*/
|
|
199
|
+
writeFile: (this: PluginContext, source: string | undefined, path: Path) => MaybePromise<void>;
|
|
200
|
+
/**
|
|
201
|
+
* End of the plugin lifecycle.
|
|
202
|
+
* @type hookParallel
|
|
203
|
+
*/
|
|
182
204
|
buildEnd: (this: PluginContext) => MaybePromise<void>;
|
|
183
205
|
};
|
|
184
206
|
type PluginLifecycleHooks = keyof PluginLifecycle;
|
|
185
207
|
type ResolveIdParams = {
|
|
186
|
-
|
|
187
|
-
|
|
208
|
+
fileName: string;
|
|
209
|
+
directory?: string | undefined;
|
|
188
210
|
/**
|
|
189
211
|
* When set, resolveId will only call resolveId of the name of the plugin set here.
|
|
190
212
|
* If not defined it will fall back on the resolveId of the core plugin.
|
|
191
213
|
*/
|
|
192
214
|
pluginName?: string;
|
|
215
|
+
/**
|
|
216
|
+
* Options to be passed to 'resolveId' 3th parameter
|
|
217
|
+
*/
|
|
193
218
|
options?: Record<string, any>;
|
|
194
219
|
};
|
|
195
220
|
type PluginContext = {
|
|
@@ -199,7 +224,7 @@ type PluginContext = {
|
|
|
199
224
|
addFile: (emitedFile: EmittedFile | File, options?: {
|
|
200
225
|
root?: true;
|
|
201
226
|
}) => Promise<File>;
|
|
202
|
-
resolveId: (params: ResolveIdParams) => MaybePromise<
|
|
227
|
+
resolveId: (params: ResolveIdParams) => MaybePromise<OptionalPath>;
|
|
203
228
|
load: (id: string) => MaybePromise<TransformResult | void>;
|
|
204
229
|
};
|
|
205
230
|
type ValidationResult = true | {
|
|
@@ -209,7 +234,8 @@ type TransformResult = string | null;
|
|
|
209
234
|
/**
|
|
210
235
|
* @description Computing the name of a file or directory together with its position in relation to other directories traced back in a line to the root
|
|
211
236
|
*/
|
|
212
|
-
type Path = string
|
|
237
|
+
type Path = string;
|
|
238
|
+
type OptionalPath = Path | null | undefined;
|
|
213
239
|
type FileName = string | null | undefined;
|
|
214
240
|
type LogType = 'error' | 'warn' | 'info';
|
|
215
241
|
type LogLevel = LogType | 'silent';
|
|
@@ -281,7 +307,7 @@ declare class PluginManager {
|
|
|
281
307
|
constructor(config: KubbConfig, options: {
|
|
282
308
|
logger?: Logger;
|
|
283
309
|
});
|
|
284
|
-
resolveId: (params: ResolveIdParams) => Promise<
|
|
310
|
+
resolveId: (params: ResolveIdParams) => Promise<OptionalPath>;
|
|
285
311
|
load: (id: string) => Promise<TransformResult>;
|
|
286
312
|
hookForPlugin<H extends PluginLifecycleHooks>(pluginName: string, hookName: H, parameters: Parameters<PluginLifecycle[H]>, skipped?: ReadonlySet<KubbPlugin> | null): Promise<ReturnType<PluginLifecycle[H]> | null>;
|
|
287
313
|
hookFirst<H extends PluginLifecycleHooks>(hookName: H, parameters: Parameters<PluginLifecycle[H]>, skipped?: ReadonlySet<KubbPlugin> | null): Promise<ReturnType<PluginLifecycle[H]> | null>;
|
|
@@ -306,4 +332,4 @@ declare class PluginManager {
|
|
|
306
332
|
private runSync;
|
|
307
333
|
}
|
|
308
334
|
|
|
309
|
-
export { Argument0, CLIOptions, Cache, CacheStore, CorePluginOptions, EmittedFile, File, FileManager, FileName,
|
|
335
|
+
export { Argument0, CLIOptions, Cache, CacheStore, CorePluginOptions, EmittedFile, File, FileManager, FileName, KubbConfig, KubbPlugin, KubbUserConfig, LogLevel, LogType, Logger, MaybePromise, OptionalPath, Path, PluginContext, PluginFactoryOptions, PluginLifecycle, PluginLifecycleHooks, PluginManager, ResolveIdParams, Status, Strategy, TransformResult, TreeNode, UUID, ValidationResult, build, createPlugin, createPluginCache, build as default, defineConfig, format, getRelativePath, hooks, isPromise, write };
|
package/dist/index.js
CHANGED
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
Object.defineProperty(exports, '__esModule', { value: true });
|
|
4
4
|
|
|
5
|
-
var path3 = require('path');
|
|
6
5
|
var fse = require('fs-extra');
|
|
6
|
+
var pathParser2 = require('path');
|
|
7
7
|
var prettier = require('prettier');
|
|
8
8
|
var EventEmitter = require('events');
|
|
9
9
|
var crypto = require('crypto');
|
|
@@ -29,18 +29,18 @@ var format = (text) => {
|
|
|
29
29
|
};
|
|
30
30
|
|
|
31
31
|
// src/utils/write.ts
|
|
32
|
-
var write = async (data,
|
|
32
|
+
var write = async (data, path, options = { format: false }) => {
|
|
33
33
|
const formattedData = options.format ? format(data) : data;
|
|
34
34
|
try {
|
|
35
|
-
await fse.stat(
|
|
36
|
-
const oldContent = await fse.readFile(
|
|
35
|
+
await fse.stat(path);
|
|
36
|
+
const oldContent = await fse.readFile(path, { encoding: "utf-8" });
|
|
37
37
|
if (oldContent?.toString() === formattedData) {
|
|
38
38
|
return;
|
|
39
39
|
}
|
|
40
40
|
} catch (_err) {
|
|
41
|
-
return fse.outputFile(
|
|
41
|
+
return fse.outputFile(path, formattedData);
|
|
42
42
|
}
|
|
43
|
-
return fse.outputFile(
|
|
43
|
+
return fse.outputFile(path, formattedData);
|
|
44
44
|
};
|
|
45
45
|
|
|
46
46
|
// src/utils/cache.ts
|
|
@@ -72,68 +72,10 @@ var getRelativePath = (root, file) => {
|
|
|
72
72
|
if (!root || !file) {
|
|
73
73
|
throw new Error("Root and file should be filled in when retrieving the relativePath");
|
|
74
74
|
}
|
|
75
|
-
const newPath =
|
|
75
|
+
const newPath = pathParser2.relative(root, file).replace("../", "").replace(".ts", "").trimEnd();
|
|
76
76
|
return `./${newPath}`;
|
|
77
77
|
};
|
|
78
78
|
|
|
79
|
-
// src/plugin.ts
|
|
80
|
-
function createPlugin(factory) {
|
|
81
|
-
return (options) => {
|
|
82
|
-
const plugin = factory(options);
|
|
83
|
-
if (Array.isArray(plugin)) {
|
|
84
|
-
throw new Error("Not implemented");
|
|
85
|
-
}
|
|
86
|
-
if (!plugin.transform) {
|
|
87
|
-
plugin.transform = function transform(code) {
|
|
88
|
-
return code;
|
|
89
|
-
};
|
|
90
|
-
}
|
|
91
|
-
return plugin;
|
|
92
|
-
};
|
|
93
|
-
}
|
|
94
|
-
var name = "core";
|
|
95
|
-
var isEmittedFile = (result) => {
|
|
96
|
-
return !!result.id;
|
|
97
|
-
};
|
|
98
|
-
var definePlugin = createPlugin((options) => {
|
|
99
|
-
const { fileManager, resolveId, load } = options;
|
|
100
|
-
const api = {
|
|
101
|
-
get config() {
|
|
102
|
-
return options.config;
|
|
103
|
-
},
|
|
104
|
-
fileManager,
|
|
105
|
-
async addFile(file, options2) {
|
|
106
|
-
if (isEmittedFile(file)) {
|
|
107
|
-
const resolvedId = await resolveId({ importee: file.id, importer: file.importer, options: file.options });
|
|
108
|
-
const filePath = resolvedId || file.importer || file.id;
|
|
109
|
-
return fileManager.add({
|
|
110
|
-
path: filePath,
|
|
111
|
-
fileName: file.name || file.id,
|
|
112
|
-
source: file.source || ""
|
|
113
|
-
});
|
|
114
|
-
}
|
|
115
|
-
if (options2?.root) ;
|
|
116
|
-
return fileManager.add(file);
|
|
117
|
-
},
|
|
118
|
-
resolveId,
|
|
119
|
-
load,
|
|
120
|
-
cache: createPluginCache(/* @__PURE__ */ Object.create(null))
|
|
121
|
-
};
|
|
122
|
-
return {
|
|
123
|
-
name,
|
|
124
|
-
api,
|
|
125
|
-
async buildEnd() {
|
|
126
|
-
await this.fileManager.generateRootFiles({ exclude: [/schemas/, /json/] });
|
|
127
|
-
},
|
|
128
|
-
resolveId(importee, importer) {
|
|
129
|
-
if (!importer) {
|
|
130
|
-
return null;
|
|
131
|
-
}
|
|
132
|
-
return path3.resolve(importer, importee);
|
|
133
|
-
}
|
|
134
|
-
};
|
|
135
|
-
});
|
|
136
|
-
|
|
137
79
|
// src/managers/fileManager/events.ts
|
|
138
80
|
var keys = {
|
|
139
81
|
getFileKey: () => `file`,
|
|
@@ -242,8 +184,8 @@ var TreeNode = class {
|
|
|
242
184
|
}
|
|
243
185
|
return this;
|
|
244
186
|
}
|
|
245
|
-
static generate(
|
|
246
|
-
const filteredTree = dirTree(
|
|
187
|
+
static generate(path, options = {}) {
|
|
188
|
+
const filteredTree = dirTree(path, { extensions: options?.extensions, exclude: options.exclude });
|
|
247
189
|
const treeNode = new TreeNode({ name: filteredTree.name, path: filteredTree.path, type: filteredTree.type });
|
|
248
190
|
const recurse = (node, item) => {
|
|
249
191
|
const subNode = node.addChild({ name: item.name, path: item.path, type: item.type });
|
|
@@ -261,13 +203,9 @@ var TreeNode = class {
|
|
|
261
203
|
// src/managers/fileManager/FileManager.ts
|
|
262
204
|
var FileManager = class {
|
|
263
205
|
cache = /* @__PURE__ */ new Map();
|
|
264
|
-
root;
|
|
265
|
-
output;
|
|
266
206
|
emitter = new EventEmitter();
|
|
267
207
|
events = getFileManagerEvents(this.emitter);
|
|
268
|
-
constructor(
|
|
269
|
-
this.root = path3.resolve(options.root || ".");
|
|
270
|
-
this.output = options?.output || process.cwd();
|
|
208
|
+
constructor() {
|
|
271
209
|
this.events.onStatusChange(() => {
|
|
272
210
|
if (this.getCountOfStatus("removed") === this.cache.size) {
|
|
273
211
|
this.events.emitSuccess();
|
|
@@ -293,11 +231,41 @@ var FileManager = class {
|
|
|
293
231
|
});
|
|
294
232
|
return files;
|
|
295
233
|
}
|
|
296
|
-
|
|
297
|
-
|
|
234
|
+
add(file) {
|
|
235
|
+
const cacheItem = { id: crypto.randomUUID(), file, status: "new" };
|
|
236
|
+
this.cache.set(cacheItem.id, cacheItem);
|
|
237
|
+
this.events.emitFile(cacheItem.id, file);
|
|
238
|
+
return new Promise((resolve) => {
|
|
239
|
+
const unsubscribe = this.events.onRemove(cacheItem.id, (file2) => {
|
|
240
|
+
resolve(file2);
|
|
241
|
+
unsubscribe();
|
|
242
|
+
});
|
|
243
|
+
});
|
|
298
244
|
}
|
|
299
|
-
|
|
300
|
-
const
|
|
245
|
+
setStatus(id, status) {
|
|
246
|
+
const cacheItem = this.getCache(id);
|
|
247
|
+
if (!cacheItem) {
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
cacheItem.status = status;
|
|
251
|
+
this.cache.set(id, cacheItem);
|
|
252
|
+
this.events.emitStatusChange(cacheItem.file);
|
|
253
|
+
this.events.emitStatusChangeById(id, status);
|
|
254
|
+
}
|
|
255
|
+
get(id) {
|
|
256
|
+
const cacheItem = this.getCache(id);
|
|
257
|
+
return cacheItem?.file;
|
|
258
|
+
}
|
|
259
|
+
remove(id) {
|
|
260
|
+
const cacheItem = this.getCache(id);
|
|
261
|
+
if (!cacheItem) {
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
this.setStatus(id, "removed");
|
|
265
|
+
this.events.emitRemove(id, cacheItem.file);
|
|
266
|
+
}
|
|
267
|
+
static writeIndexes(root, output, options) {
|
|
268
|
+
const tree = TreeNode.generate(output, { extensions: /\.ts/, ...options });
|
|
301
269
|
const fileReducer = (files2, item) => {
|
|
302
270
|
if (!item.children) {
|
|
303
271
|
return [];
|
|
@@ -312,7 +280,7 @@ var FileManager = class {
|
|
|
312
280
|
`;
|
|
313
281
|
}, "");
|
|
314
282
|
files2.push({
|
|
315
|
-
path:
|
|
283
|
+
path: pathParser2.resolve(root, item.data.path, "index.ts"),
|
|
316
284
|
fileName: "index.ts",
|
|
317
285
|
source
|
|
318
286
|
});
|
|
@@ -320,7 +288,7 @@ var FileManager = class {
|
|
|
320
288
|
item.children?.forEach((child) => {
|
|
321
289
|
const importPath = child.data.type === "directory" ? `./${child.data.name}` : `./${child.data.name.replace(/\.[^.]*$/, "")}`;
|
|
322
290
|
files2.push({
|
|
323
|
-
path:
|
|
291
|
+
path: pathParser2.resolve(root, item.data.path, "index.ts"),
|
|
324
292
|
fileName: "index.ts",
|
|
325
293
|
source: `export * from "${importPath}";
|
|
326
294
|
`
|
|
@@ -335,40 +303,65 @@ var FileManager = class {
|
|
|
335
303
|
const files = fileReducer([], tree);
|
|
336
304
|
return files.map((file) => write(file.source, file.path));
|
|
337
305
|
}
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
});
|
|
347
|
-
});
|
|
348
|
-
}
|
|
349
|
-
setStatus(id, status) {
|
|
350
|
-
const cacheItem = this.getCache(id);
|
|
351
|
-
if (!cacheItem) {
|
|
352
|
-
return;
|
|
306
|
+
};
|
|
307
|
+
|
|
308
|
+
// src/plugin.ts
|
|
309
|
+
function createPlugin(factory) {
|
|
310
|
+
return (options) => {
|
|
311
|
+
const plugin = factory(options);
|
|
312
|
+
if (Array.isArray(plugin)) {
|
|
313
|
+
throw new Error("Not implemented");
|
|
353
314
|
}
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
}
|
|
359
|
-
get(id) {
|
|
360
|
-
const cacheItem = this.getCache(id);
|
|
361
|
-
return cacheItem?.file;
|
|
362
|
-
}
|
|
363
|
-
remove(id) {
|
|
364
|
-
const cacheItem = this.getCache(id);
|
|
365
|
-
if (!cacheItem) {
|
|
366
|
-
return;
|
|
315
|
+
if (!plugin.transform) {
|
|
316
|
+
plugin.transform = function transform(code) {
|
|
317
|
+
return code;
|
|
318
|
+
};
|
|
367
319
|
}
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
320
|
+
return plugin;
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
var name = "core";
|
|
324
|
+
var isEmittedFile = (result) => {
|
|
325
|
+
return !!result.id;
|
|
371
326
|
};
|
|
327
|
+
var definePlugin = createPlugin((options) => {
|
|
328
|
+
const { fileManager, resolveId, load } = options;
|
|
329
|
+
const api = {
|
|
330
|
+
get config() {
|
|
331
|
+
return options.config;
|
|
332
|
+
},
|
|
333
|
+
fileManager,
|
|
334
|
+
async addFile(file, options2) {
|
|
335
|
+
if (isEmittedFile(file)) {
|
|
336
|
+
const resolvedId = await resolveId({ fileName: file.id, directory: file.importer, options: file.options });
|
|
337
|
+
const path = resolvedId || file.importer || file.id;
|
|
338
|
+
return fileManager.add({
|
|
339
|
+
path,
|
|
340
|
+
fileName: file.name || file.id,
|
|
341
|
+
source: file.source || ""
|
|
342
|
+
});
|
|
343
|
+
}
|
|
344
|
+
if (options2?.root) ;
|
|
345
|
+
return fileManager.add(file);
|
|
346
|
+
},
|
|
347
|
+
resolveId,
|
|
348
|
+
load,
|
|
349
|
+
cache: createPluginCache(/* @__PURE__ */ Object.create(null))
|
|
350
|
+
};
|
|
351
|
+
return {
|
|
352
|
+
name,
|
|
353
|
+
api,
|
|
354
|
+
async buildEnd() {
|
|
355
|
+
await FileManager.writeIndexes(this.config.root, this.config.output.path, { exclude: [/schemas/, /json/] });
|
|
356
|
+
},
|
|
357
|
+
resolveId(fileName, directory) {
|
|
358
|
+
if (!directory) {
|
|
359
|
+
return null;
|
|
360
|
+
}
|
|
361
|
+
return pathParser2.resolve(directory, fileName);
|
|
362
|
+
}
|
|
363
|
+
};
|
|
364
|
+
});
|
|
372
365
|
|
|
373
366
|
// src/managers/pluginManager/PluginManager.ts
|
|
374
367
|
var hookNames = {
|
|
@@ -390,7 +383,7 @@ var PluginManager = class {
|
|
|
390
383
|
constructor(config, options) {
|
|
391
384
|
this.logger = options.logger;
|
|
392
385
|
this.config = config;
|
|
393
|
-
this.fileManager = new FileManager(
|
|
386
|
+
this.fileManager = new FileManager();
|
|
394
387
|
this.core = definePlugin({
|
|
395
388
|
config,
|
|
396
389
|
fileManager: this.fileManager,
|
|
@@ -401,9 +394,9 @@ var PluginManager = class {
|
|
|
401
394
|
}
|
|
402
395
|
resolveId = (params) => {
|
|
403
396
|
if (params.pluginName) {
|
|
404
|
-
return this.hookForPlugin(params.pluginName, "resolveId", [params.
|
|
397
|
+
return this.hookForPlugin(params.pluginName, "resolveId", [params.fileName, params.directory, params.options]);
|
|
405
398
|
}
|
|
406
|
-
return this.hookFirst("resolveId", [params.
|
|
399
|
+
return this.hookFirst("resolveId", [params.fileName, params.directory, params.options]);
|
|
407
400
|
};
|
|
408
401
|
load = async (id) => {
|
|
409
402
|
return this.hookFirst("load", [id]);
|
|
@@ -533,7 +526,6 @@ async function buildImplementation(options, done) {
|
|
|
533
526
|
}
|
|
534
527
|
const pluginManager = new PluginManager(config, { logger });
|
|
535
528
|
const { plugins, fileManager } = pluginManager;
|
|
536
|
-
fse.readFileSync(path3.resolve(config.root, config.input.path), "utf-8");
|
|
537
529
|
const validations = await pluginManager.hookParallel("validate", [plugins]);
|
|
538
530
|
const validationsWithMessage = validations.filter(Boolean);
|
|
539
531
|
if (validationsWithMessage.some((validation) => typeof validation !== "boolean")) {
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/build.ts","../src/plugin.ts","../src/utils/isPromise.ts","../src/utils/write.ts","../src/utils/format.ts","../src/utils/cache.ts","../src/utils/read.ts","../src/managers/fileManager/FileManager.ts","../src/managers/fileManager/events.ts","../src/managers/fileManager/TreeNode.ts","../src/managers/pluginManager/PluginManager.ts","../src/config.ts","../src/index.ts"],"names":["path","fse","options","files","source","file","argument0"],"mappings":";AAAA,OAAOA,WAAU;AAEjB,OAAOC,UAAS;;;ACFhB,OAAOD,WAAU;;;ACEV,IAAM,YAAY,CAAI,WAAkD;AAC7E,SAAO,OAAQ,QAAgB,SAAS;AAC1C;;;ACHA,OAAO,SAAS;;;ACDhB,SAAS,UAAU,sBAAsB;AAIzC,IAAM,gBAAyB;A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BAAY,UAAU,IAAI,SAAS;AACnC,kBAAY,OAAO,EAAE;AAAA,IACvB;AAAA,EACF,CAAC;AAED,QAAM,cAAc,aAAa,cAAc,CAAC,MAAM,CAAC;AACzD;AAEO,SAAS,MAAM,SAA6C;AACjE,SAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACtC,QAAI;AACF,0BAAoB,SAAS,OAAO;AAAA,IACtC,SAAS,GAAP;AACA,aAAO,CAAC;AAAA,IACV;AAAA,EACF,CAAC;AACH;;;AW1FO,IAAM,eAAe,CAC1B,YAMG;;;ACLL,IAAO,cAAQ","sourcesContent":["import path from 'path'\n\nimport fse from 'fs-extra'\n\nimport { PluginManager } from './managers/pluginManager'\n\nimport type { PluginContext, TransformResult, ValidationResult, LogLevel, KubbPlugin } from './types'\n\ntype BuildOutput = void\n\n// Same type as ora\ntype Spinner = {\n start: (text?: string) => Spinner\n succeed: (text: string) => Spinner\n stopAndPersist: (options: { text: string }) => Spinner\n render: () => Spinner\n text: string\n info: (text: string) => Spinner\n}\n\nexport type Logger = {\n log: (message: string, logLevel: LogLevel) => void\n spinner?: Spinner\n}\ntype BuildOptions = {\n config: PluginContext['config']\n mode: 'development' | 'production'\n logger?: Logger\n}\n\nasync function transformReducer(this: PluginContext, _previousCode: string, result: TransformResult, _plugin: KubbPlugin) {\n if (result === null) {\n return null\n }\n return result\n}\n\nasync function buildImplementation(options: BuildOptions, done: (output: BuildOutput) => void) {\n const { config, logger } = options\n\n if (config.output.clean) {\n await fse.remove(config.output.path)\n }\n\n const pluginManager = new PluginManager(config, { logger })\n const { plugins, fileManager } = pluginManager\n const input = fse.readFileSync(path.resolve(config.root, config.input.path), 'utf-8')\n\n const validations = await pluginManager.hookParallel<'validate', ValidationResult>('validate', [plugins])\n const validationsWithMessage = validations.filter(Boolean)\n\n if (validationsWithMessage.some((validation) => typeof validation !== 'boolean')) {\n validationsWithMessage.forEach((validation) => {\n if (validation && typeof validation !== 'boolean' && validation?.message) {\n logger?.log(validation.message, 'warn')\n }\n })\n\n return\n }\n\n fileManager.events.onSuccess(async () => {\n await pluginManager.hookParallel('buildEnd')\n setTimeout(() => {\n done()\n }, 1000)\n })\n\n fileManager.events.onAdd(async (id, file) => {\n const { path: filePath } = file\n let { source: code } = file\n\n const loadedResult = await pluginManager.hookFirst('load', [filePath])\n if (loadedResult) {\n code = loadedResult\n }\n\n if (code) {\n const transformedCode = await pluginManager.hookReduceArg0('transform', [code, filePath], transformReducer)\n\n await pluginManager.hookParallel('writeFile', [transformedCode, filePath])\n fileManager.setStatus(id, 'success')\n fileManager.remove(id)\n }\n })\n\n await pluginManager.hookParallel('buildStart', [config])\n}\n\nexport function build(options: BuildOptions): Promise<BuildOutput> {\n return new Promise((resolve, reject) => {\n try {\n buildImplementation(options, resolve)\n } catch (e) {\n reject(e)\n }\n })\n}\n","import path from 'path'\n\nimport { createPluginCache } from './utils'\n\nimport type { FileManager, EmittedFile, File } from './managers/fileManager'\nimport type { PluginContext, KubbPlugin, PluginFactoryOptions } from './types'\n\ntype KubbPluginFactory<T extends PluginFactoryOptions = PluginFactoryOptions> = (\n options: T['options']\n) => T['nested'] extends true ? Array<KubbPlugin<T>> : KubbPlugin<T>\n\nexport function createPlugin<T extends PluginFactoryOptions = PluginFactoryOptions>(factory: KubbPluginFactory<T>) {\n return (options: T['options']) => {\n const plugin = factory(options)\n if (Array.isArray(plugin)) {\n throw new Error('Not implemented')\n }\n\n // default transform\n if (!plugin.transform) {\n plugin.transform = function transform(code) {\n return code\n }\n }\n\n return plugin\n }\n}\n\ntype Options = {\n config: PluginContext['config']\n fileManager: FileManager\n resolveId: PluginContext['resolveId']\n load: PluginContext['load']\n}\n\n// not publicly exported\nexport type CorePluginOptions = PluginFactoryOptions<Options, false, PluginContext>\n\nexport const name = 'core' as const\n\nconst isEmittedFile = (result: EmittedFile | File): result is EmittedFile => {\n return !!(result as any).id\n}\n\nexport const definePlugin = createPlugin<CorePluginOptions>((options) => {\n const { fileManager, resolveId, load } = options\n const indexFiles: File[] = []\n\n const api: PluginContext = {\n get config() {\n return options.config\n },\n fileManager,\n async addFile(file, options) {\n if (isEmittedFile(file)) {\n const resolvedId = await resolveId({ importee: file.id, importer: file.importer, options: file.options })\n const filePath = resolvedId || file.importer || file.id\n\n return fileManager.add({\n path: filePath,\n fileName: file.name || file.id,\n source: file.source || '',\n })\n }\n\n if (options?.root) {\n indexFiles.push(file)\n }\n\n return fileManager.add(file)\n },\n resolveId,\n load,\n cache: createPluginCache(Object.create(null)),\n }\n\n return {\n name,\n api,\n async buildEnd() {\n await this.fileManager.generateRootFiles({ exclude: [/schemas/, /json/] })\n },\n resolveId(importee, importer) {\n if (!importer) {\n return null\n }\n return path.resolve(importer, importee)\n },\n }\n})\n","import type { MaybePromise } from '../types'\n\nexport const isPromise = <T>(result: MaybePromise<T>): result is Promise<T> => {\n return typeof (result as any)?.then === 'function'\n}\n","/* eslint-disable consistent-return */\nimport fse from 'fs-extra'\n\nimport { format } from './format'\n\ntype WriteOptions = {\n format: boolean\n}\n\nexport const write = async (data: string, path: string, options: WriteOptions = { format: false }) => {\n const formattedData = options.format ? format(data) : data\n\n try {\n await fse.stat(path)\n const oldContent = await fse.readFile(path, { encoding: 'utf-8' })\n if (oldContent?.toString() === formattedData) {\n return\n }\n } catch (_err) {\n return fse.outputFile(path, formattedData)\n }\n\n return fse.outputFile(path, formattedData)\n}\n","import { format as prettierFormat } from 'prettier'\n\nimport type { Options } from 'prettier'\n\nconst formatOptions: Options = {\n tabWidth: 2,\n printWidth: 160,\n parser: 'typescript',\n singleQuote: true,\n semi: false,\n bracketSameLine: false,\n endOfLine: 'auto',\n}\nexport const format = (text: string) => {\n return prettierFormat(text, formatOptions)\n}\n","/* eslint-disable no-param-reassign */\n/* eslint-disable consistent-return */\n\nexport interface Cache<TCache = any> {\n delete(id: string): boolean\n get<T = TCache>(id: string): T\n has(id: string): boolean\n set<T = TCache>(id: string, value: T): void\n}\n\nexport function createPluginCache(cache: any): Cache {\n return {\n delete(id: string) {\n return delete cache[id]\n },\n get(id: string) {\n const item = cache[id]\n if (!item) return\n item[0] = 0\n return item[1]\n },\n has(id: string) {\n const item = cache[id]\n if (!item) return false\n item[0] = 0\n return true\n },\n set(id: string, value: any) {\n cache[id] = [0, value]\n },\n }\n}\n","import path from 'path'\n\n// TODO check for a better way or resolving the relative path\nexport const getRelativePath = (root?: string | null, file?: string | null) => {\n if (!root || !file) {\n throw new Error('Root and file should be filled in when retrieving the relativePath')\n }\n const newPath = path.relative(root, file).replace('../', '').replace('.ts', '').trimEnd()\n\n return `./${newPath}`\n}\n","import EventEmitter from 'events'\nimport { randomUUID } from 'crypto'\nimport path from 'path'\n\nimport { getFileManagerEvents } from './events'\nimport { TreeNode } from './TreeNode'\n\nimport { write } from '../../utils/write'\n\nimport type { GenerateTreeNodeOptions } from './TreeNode'\nimport type { CacheStore, UUID, Status, File } from './types'\n\nexport class FileManager {\n private cache: Map<CacheStore['id'], CacheStore> = new Map()\n\n private readonly root: string\n\n private readonly output: string\n\n emitter = new EventEmitter()\n\n events = getFileManagerEvents(this.emitter)\n\n constructor(options: { root?: string; output?: string } = {}) {\n this.root = path.resolve(options.root || '.')\n // TODO better types\n this.output = options?.output || process.cwd()\n this.events.onStatusChange(() => {\n if (this.getCountOfStatus('removed') === this.cache.size) {\n // all files are been resolved and written to the file system\n this.events.emitSuccess()\n }\n })\n }\n\n private getCache(id: UUID) {\n return this.cache.get(id)\n }\n\n private getCountOfStatus(status: Status) {\n let count = 0\n\n this.cache.forEach((item) => {\n if (item.status === status) {\n count++\n }\n })\n return count\n }\n\n get files() {\n const files: File[] = []\n this.cache.forEach((item) => {\n files.push(item.file)\n })\n\n return files\n }\n\n get tree() {\n return TreeNode.generate(this.output, { extensions: /\\.ts/ })\n }\n\n generateRootFiles(options: GenerateTreeNodeOptions) {\n const tree = TreeNode.generate(this.output, { extensions: /\\.ts/, ...options })\n\n const fileReducer = (files: File[], item: typeof tree) => {\n if (!item.children) {\n return []\n }\n\n if (item.children?.length > 1) {\n const source = item.children.reduce((source, file) => {\n if (!file) {\n return source\n }\n\n const importPath = file.data.type === 'directory' ? `./${file.data.name}` : `./${file.data.name.replace(/\\.[^.]*$/, '')}`\n\n return `${source}export * from \"${importPath}\";\\n`\n }, '')\n\n files.push({\n path: path.resolve(this.root, item.data.path, 'index.ts'),\n fileName: 'index.ts',\n source,\n })\n } else {\n item.children?.forEach((child) => {\n const importPath = child.data.type === 'directory' ? `./${child.data.name}` : `./${child.data.name.replace(/\\.[^.]*$/, '')}`\n\n files.push({\n path: path.resolve(this.root, item.data.path, 'index.ts'),\n fileName: 'index.ts',\n source: `export * from \"${importPath}\";\\n`,\n })\n })\n }\n\n item.children.forEach((childItem) => {\n fileReducer(files, childItem)\n })\n\n return files\n }\n\n const files = fileReducer([], tree)\n\n return files.map((file) => write(file.source, file.path))\n }\n\n add(file: File) {\n const cacheItem = { id: randomUUID(), file, status: 'new' as Status }\n\n this.cache.set(cacheItem.id, cacheItem)\n this.events.emitFile(cacheItem.id, file)\n\n return new Promise<File>((resolve) => {\n const unsubscribe = this.events.onRemove(cacheItem.id, (file) => {\n resolve(file)\n unsubscribe()\n })\n })\n }\n\n setStatus(id: UUID, status: Status) {\n const cacheItem = this.getCache(id)\n if (!cacheItem) {\n return\n }\n\n cacheItem.status = status\n this.cache.set(id, cacheItem)\n this.events.emitStatusChange(cacheItem.file)\n this.events.emitStatusChangeById(id, status)\n }\n\n get(id: UUID) {\n const cacheItem = this.getCache(id)\n return cacheItem?.file\n }\n\n remove(id: UUID) {\n const cacheItem = this.getCache(id)\n if (!cacheItem) {\n return\n }\n\n this.setStatus(id, 'removed')\n this.events.emitRemove(id, cacheItem.file)\n }\n}\n","import type EventEmitter from 'events'\nimport type { File, Status, UUID } from './types'\n\nconst keys = {\n getFileKey: () => `file`,\n getStatusChangeKey: () => `status-change`,\n getStatusChangeByIdKey: (id: string) => `${id}-status-change`,\n getSuccessKey: () => `success`,\n getRemoveKey: (id: string) => `${id}remove`,\n} as const\n\nexport const getFileManagerEvents = (emitter: EventEmitter) => {\n return {\n /**\n * Emiter\n */\n emitFile: (id: UUID, file: File): void => {\n emitter.emit(keys.getFileKey(), id, file)\n },\n emitStatusChange: (file: File): void => {\n emitter.emit(keys.getStatusChangeKey(), file)\n },\n emitStatusChangeById: (id: UUID, status: Status): void => {\n emitter.emit(keys.getStatusChangeByIdKey(id), status)\n },\n emitSuccess: (): void => {\n emitter.emit(keys.getSuccessKey())\n },\n emitRemove: (id: UUID, file: File): void => {\n emitter.emit(keys.getRemoveKey(id), file)\n },\n /**\n * Listeners\n */\n\n onAdd: (callback: (id: UUID, file: File) => void): VoidFunction => {\n emitter.on(keys.getFileKey(), callback)\n return () => emitter.removeListener(keys.getFileKey(), callback)\n },\n onStatusChange: (callback: (file: File) => void): VoidFunction => {\n emitter.on(keys.getStatusChangeKey(), callback)\n return () => emitter.removeListener(keys.getStatusChangeKey(), callback)\n },\n onStatusChangeById: (id: UUID, callback: (status: Status) => void): VoidFunction => {\n emitter.on(keys.getStatusChangeByIdKey(id), callback)\n return () => emitter.removeListener(keys.getStatusChangeByIdKey(id), callback)\n },\n onSuccess: (callback: () => void): VoidFunction => {\n emitter.on(keys.getSuccessKey(), callback)\n return () => emitter.removeListener(keys.getSuccessKey(), callback)\n },\n onRemove: (id: UUID, callback: (file: File) => void): VoidFunction => {\n emitter.on(keys.getRemoveKey(id), callback)\n return () => emitter.removeListener(keys.getRemoveKey(id), callback)\n },\n }\n}\n","import dirTree from 'directory-tree'\n\nimport type { DirectoryTree } from 'directory-tree'\n\nexport type GenerateTreeNodeOptions = { extensions?: RegExp; exclude?: RegExp[] }\n\nexport class TreeNode<T = unknown> {\n public data: T\n\n public parent?: TreeNode<T>\n\n public children: Array<TreeNode<T>>\n\n constructor(data: T, parent?: TreeNode<T>) {\n this.data = data\n this.parent = parent\n return this\n }\n\n addChild(data: T) {\n const child = new TreeNode(data, this)\n if (!this.children) {\n this.children = []\n }\n this.children.push(child)\n return child\n }\n\n find(data: T) {\n if (data === this.data) {\n return this\n }\n\n if (this.children) {\n for (let i = 0, { length } = this.children, target: any = null; i < length; i++) {\n target = this.children[i].find(data)\n if (target) {\n return target\n }\n }\n }\n\n return null\n }\n\n leaves() {\n if (!this.children || this.children.length === 0) {\n // this is a leaf\n return [this]\n }\n\n // if not a leaf, return all children's leaves recursively\n const leaves = []\n if (this.children) {\n for (let i = 0, { length } = this.children; i < length; i++) {\n // eslint-disable-next-line prefer-spread\n leaves.push.apply(leaves, this.children[i].leaves())\n }\n }\n return leaves\n }\n\n root() {\n if (!this.parent) {\n return this\n }\n return this.parent.root()\n }\n\n forEach(callback: (treeNode: TreeNode<T>) => void) {\n if (typeof callback !== 'function') {\n throw new TypeError('forEach() callback must be a function')\n }\n\n // run this node through function\n callback(this)\n\n // do the same for all children\n if (this.children) {\n for (let i = 0, { length } = this.children; i < length; i++) {\n this.children[i].forEach(callback)\n }\n }\n\n return this\n }\n\n public static generate(path: string, options: GenerateTreeNodeOptions = {}) {\n const filteredTree = dirTree(path, { extensions: options?.extensions, exclude: options.exclude })\n const treeNode = new TreeNode({ name: filteredTree.name, path: filteredTree.path, type: filteredTree.type })\n\n const recurse = (node: typeof treeNode, item: DirectoryTree) => {\n const subNode = node.addChild({ name: item.name, path: item.path, type: item.type })\n\n if (item.children?.length) {\n item.children?.forEach((child) => {\n recurse(subNode, child)\n })\n }\n }\n\n filteredTree.children?.forEach((child) => recurse(treeNode, child))\n\n return treeNode\n }\n}\n","/* eslint-disable no-await-in-loop */\n/* eslint-disable no-restricted-syntax */\n\nimport { definePlugin } from '../../plugin'\nimport { FileManager } from '../fileManager'\n\nimport type { Argument0, Strategy } from './types'\nimport type { KubbConfig, KubbPlugin, PluginLifecycleHooks, PluginLifecycle, MaybePromise, ResolveIdParams } from '../../types'\nimport type { Logger } from '../../build'\nimport type { CorePluginOptions } from '../../plugin'\n\n// inspired by: https://github.com/rollup/rollup/blob/master/src/utils/PluginDriver.ts#\n\n// This will make sure no input hook is omitted\nconst hookNames: {\n [P in PluginLifecycleHooks]: 1\n} = {\n validate: 1,\n buildStart: 1,\n resolveId: 1,\n load: 1,\n transform: 1,\n writeFile: 1,\n buildEnd: 1,\n}\nexport const hooks = Object.keys(hookNames) as [PluginLifecycleHooks]\n\nexport class PluginManager {\n public plugins: KubbPlugin[]\n\n public readonly fileManager: FileManager\n\n private readonly logger?: Logger\n\n private readonly config: KubbConfig\n\n public readonly core: KubbPlugin<CorePluginOptions>\n\n constructor(config: KubbConfig, options: { logger?: Logger }) {\n this.logger = options.logger\n this.config = config\n\n this.fileManager = new FileManager({ root: this.config.root, output: this.config.output.path })\n this.core = definePlugin({\n config,\n fileManager: this.fileManager,\n load: this.load,\n resolveId: this.resolveId,\n }) as KubbPlugin<CorePluginOptions> & {\n api: CorePluginOptions['api']\n }\n this.plugins = [this.core, ...(config.plugins || [])]\n }\n\n resolveId = (params: ResolveIdParams) => {\n if (params.pluginName) {\n return this.hookForPlugin(params.pluginName, 'resolveId', [params.importee, params.importer, params.options])\n }\n return this.hookFirst('resolveId', [params.importee, params.importer, params.options])\n }\n\n load = async (id: string) => {\n return this.hookFirst('load', [id])\n }\n\n // run only hook for a specific plugin name\n hookForPlugin<H extends PluginLifecycleHooks>(\n pluginName: string,\n hookName: H,\n parameters: Parameters<PluginLifecycle[H]>,\n skipped?: ReadonlySet<KubbPlugin> | null\n ): Promise<ReturnType<PluginLifecycle[H]> | null> {\n let promise: Promise<ReturnType<PluginLifecycle[H]> | null> = Promise.resolve(null)\n for (const plugin of this.getSortedPlugins(hookName, pluginName)) {\n if (skipped && skipped.has(plugin)) continue\n promise = promise.then((result) => {\n if (result != null) return result\n return this.run('hookFirst', hookName, parameters, plugin) as any\n })\n }\n return promise\n }\n\n // chains, first non-null result stops and returns\n hookFirst<H extends PluginLifecycleHooks>(\n hookName: H,\n parameters: Parameters<PluginLifecycle[H]>,\n skipped?: ReadonlySet<KubbPlugin> | null\n ): Promise<ReturnType<PluginLifecycle[H]> | null> {\n let promise: Promise<ReturnType<PluginLifecycle[H]> | null> = Promise.resolve(null)\n for (const plugin of this.getSortedPlugins(hookName)) {\n if (skipped && skipped.has(plugin)) continue\n promise = promise.then((result) => {\n if (result != null) return result\n return this.run('hookFirst', hookName, parameters, plugin) as any\n })\n }\n return promise\n }\n\n // parallel\n async hookParallel<H extends PluginLifecycleHooks, TOuput = void>(hookName: H, parameters?: Parameters<PluginLifecycle[H]> | undefined) {\n const parallelPromises: Promise<TOuput>[] = []\n\n for (const plugin of this.getSortedPlugins(hookName)) {\n if ((plugin[hookName] as { sequential?: boolean })?.sequential) {\n await Promise.all(parallelPromises)\n parallelPromises.length = 0\n await this.run('hookParallel', hookName, parameters, plugin)\n } else {\n const promise: Promise<TOuput> = this.run('hookParallel', hookName, parameters, plugin)\n\n parallelPromises.push(promise)\n }\n }\n return Promise.all(parallelPromises)\n }\n\n // chains, reduces returned value, handling the reduced value as the first hook argument\n hookReduceArg0<H extends PluginLifecycleHooks>(\n hookName: H,\n [argument0, ...rest]: Parameters<PluginLifecycle[H]>,\n reduce: (reduction: Argument0<H>, result: ReturnType<PluginLifecycle[H]>, plugin: KubbPlugin) => MaybePromise<Argument0<H> | null>\n ): Promise<Argument0<H>> {\n let promise = Promise.resolve(argument0)\n for (const plugin of this.getSortedPlugins(hookName)) {\n promise = promise.then((argument0) =>\n this.run('hookReduceArg0', hookName, [argument0, ...rest] as Parameters<PluginLifecycle[H]>, plugin).then((result) =>\n reduce.call(this.core.api, argument0, result, plugin)\n )\n )\n }\n return promise\n }\n\n // chains\n\n hookSeq<H extends PluginLifecycleHooks>(hookName: H, parameters?: Parameters<PluginLifecycle[H]>) {\n let promise: Promise<void> = Promise.resolve()\n for (const plugin of this.getSortedPlugins(hookName)) {\n promise = promise.then(() => this.run('hookSeq', hookName, parameters, plugin))\n }\n return promise.then(noReturn)\n }\n\n private getSortedPlugins(hookName: keyof PluginLifecycle, pluginName?: string): KubbPlugin[] {\n const plugins = [...this.plugins]\n\n if (pluginName) {\n const pluginsByPluginName = plugins.filter((item) => item.name === pluginName && item[hookName])\n if (pluginsByPluginName.length === 0) {\n // fallback on the core plugin when there is no match\n if (this.config.logLevel === 'warn' && this.logger?.spinner) {\n this.logger.spinner.info(`Plugin hook with ${hookName} not found for plugin ${pluginName}`)\n }\n return [this.core]\n }\n return pluginsByPluginName\n }\n\n return plugins\n }\n\n /**\n * Run an async plugin hook and return the result.\n * @param hookName Name of the plugin hook. Must be either in `PluginHooks` or `OutputPluginValueHooks`.\n * @param args Arguments passed to the plugin hook.\n * @param plugin The actual pluginObject to run.\n */\n // Implementation signature\n private run<H extends PluginLifecycleHooks, TResult = void>(\n strategy: Strategy,\n hookName: H,\n parameters: unknown[] | undefined,\n plugin: KubbPlugin\n ): Promise<TResult> {\n const hook = plugin[hookName]!\n\n return Promise.resolve().then(() => {\n if (typeof hook !== 'function') {\n return hook\n }\n\n if (this.config.logLevel === 'info' && this.logger?.spinner) {\n this.logger.spinner.text = `[${strategy}] ${hookName}: Excecuting task for plugin ${plugin.name} \\n`\n }\n\n const hookResult = (hook as any).apply(this.core.api, parameters)\n\n if (!hookResult?.then) {\n // short circuit for non-thenables and non-Promises\n if (this.config.logLevel === 'info' && this.logger?.spinner) {\n this.logger.spinner.succeed(`[${strategy}] ${hookName}: Excecuting task for plugin ${plugin.name} \\n`)\n }\n return hookResult\n }\n\n return Promise.resolve(hookResult).then((result) => {\n // action was fulfilled\n if (this.config.logLevel === 'info' && this.logger?.spinner) {\n this.logger.spinner.succeed(`[${strategy}] ${hookName}: Excecuting task for plugin ${plugin.name} \\n`)\n }\n return result\n })\n })\n }\n\n /**\n * Run a sync plugin hook and return the result.\n * @param hookName Name of the plugin hook. Must be in `PluginHooks`.\n * @param args Arguments passed to the plugin hook.\n * @param plugin The acutal plugin\n * @param replaceContext When passed, the plugin context can be overridden.\n */\n private runSync<H extends PluginLifecycleHooks>(hookName: H, parameters: Parameters<PluginLifecycle[H]>, plugin: KubbPlugin): ReturnType<PluginLifecycle[H]> {\n const hook = plugin[hookName]!\n\n // const context = this.pluginContexts.get(plugin)!;\n\n try {\n // eslint-disable-next-line @typescript-eslint/ban-types\n return (hook as Function).apply(this.core.api, parameters)\n } catch (error: any) {\n return error\n }\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-empty-function\nfunction noReturn() {}\n","import type { MaybePromise, KubbUserConfig, CLIOptions } from './types'\n\n/**\n * Type helper to make it easier to use kubb.config.ts\n * accepts a direct {@link KubbConfig} object, or a function that returns it.\n * The function receives a {@link ConfigEnv} object that exposes two properties:\n */\nexport const defineConfig = (\n options:\n | MaybePromise<KubbUserConfig>\n | ((\n /** The options derived from CLI flags */\n cliOptions: CLIOptions\n ) => MaybePromise<KubbUserConfig>)\n) => options\n","/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { build } from './build'\n\nexport * from './config'\nexport * from './build'\nexport { CorePluginOptions, createPlugin } from './plugin'\nexport * from './utils'\nexport * from './types'\nexport * from './managers'\nexport default build\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/build.ts","../src/plugin.ts","../src/utils/isPromise.ts","../src/utils/write.ts","../src/utils/format.ts","../src/utils/cache.ts","../src/utils/read.ts","../src/managers/fileManager/FileManager.ts","../src/managers/fileManager/events.ts","../src/managers/fileManager/TreeNode.ts","../src/managers/pluginManager/PluginManager.ts","../src/config.ts","../src/index.ts"],"names":["fse","pathParser","file","files","source","options","argument0"],"mappings":";AAAA,OAAOA,UAAS;;;ACAhB,OAAOC,iBAAgB;;;ACEhB,IAAM,YAAY,CAAI,WAAkD;AAC7E,SAAO,OAAQ,QAAgB,SAAS;AAC1C;;;ACHA,OAAO,SAAS;;;ACDhB,SAAS,UAAU,sBAAsB;AAIzC,IAAM,gBAAyB;AAAA,EAC7B,UAAU;AAAA,EACV,YAAY;AAAA,EACZ,QAAQ;AAAA,EACR,aAAa;AAAA,EACb,MAAM;AAAA,EACN,iBAAiB;AAAA,EACjB,WAAW;AACb;AACO,IAAM,SAAS,CAAC,SAAiB;AACtC,SAA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eAAe,SAAS,GAAG;AAChF,2BAAuB,QAAQ,CAAC,eAAe;AAC7C,UAAI,cAAc,OAAO,eAAe,aAAa,YAAY,SAAS;AACxE,gBAAQ,IAAI,WAAW,SAAS,MAAM;AAAA,MACxC;AAAA,IACF,CAAC;AAED;AAAA,EACF;AAEA,cAAY,OAAO,UAAU,YAAY;AACvC,UAAM,cAAc,aAAa,UAAU;AAC3C,eAAW,MAAM;AACf,WAAK;AAAA,IACP,GAAG,GAAI;AAAA,EACT,CAAC;AAED,cAAY,OAAO,MAAM,OAAO,IAAI,SAAS;AAC3C,UAAM,EAAE,MAAM,SAAS,IAAI;AAC3B,QAAI,EAAE,QAAQ,KAAK,IAAI;AAEvB,UAAM,eAAe,MAAM,cAAc,UAAU,QAAQ,CAAC,QAAQ,CAAC;AACrE,QAAI,cAAc;AAChB,aAAO;AAAA,IACT;AAEA,QAAI,MAAM;AACR,YAAM,kBAAkB,MAAM,cAAc,eAAe,aAAa,CAAC,MAAM,QAAQ,GAAG,gBAAgB;AAE1G,YAAM,cAAc,aAAa,aAAa,CAAC,iBAAiB,QAAQ,CAAC;AACzE,kBAAY,UAAU,IAAI,SAAS;AACnC,kBAAY,OAAO,EAAE;AAAA,IACvB;AAAA,EACF,CAAC;AAED,QAAM,cAAc,aAAa,cAAc,CAAC,MAAM,CAAC;AACzD;AAEO,SAAS,MAAM,SAA6C;AACjE,SAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACtC,QAAI;AACF,0BAAoB,SAAS,OAAO;AAAA,IACtC,SAAS,GAAP;AACA,aAAO,CAAC;AAAA,IACV;AAAA,EACF,CAAC;AACH;;;AWvFO,IAAM,eAAe,CAC1B,YAMG;;;ACLL,IAAO,cAAQ","sourcesContent":["import fse from 'fs-extra'\n\nimport { PluginManager } from './managers/pluginManager'\n\nimport type { PluginContext, TransformResult, ValidationResult, LogLevel, KubbPlugin } from './types'\n\ntype BuildOutput = void\n\n// Same type as ora\ntype Spinner = {\n start: (text?: string) => Spinner\n succeed: (text: string) => Spinner\n stopAndPersist: (options: { text: string }) => Spinner\n render: () => Spinner\n text: string\n info: (text: string) => Spinner\n}\n\nexport type Logger = {\n log: (message: string, logLevel: LogLevel) => void\n spinner?: Spinner\n}\ntype BuildOptions = {\n config: PluginContext['config']\n mode: 'development' | 'production'\n logger?: Logger\n}\n\nasync function transformReducer(this: PluginContext, _previousCode: string, result: TransformResult, _plugin: KubbPlugin) {\n if (result === null) {\n return null\n }\n return result\n}\n\nasync function buildImplementation(options: BuildOptions, done: (output: BuildOutput) => void) {\n const { config, logger } = options\n\n if (config.output.clean) {\n await fse.remove(config.output.path)\n }\n\n const pluginManager = new PluginManager(config, { logger })\n const { plugins, fileManager } = pluginManager\n\n const validations = await pluginManager.hookParallel<'validate', ValidationResult>('validate', [plugins])\n const validationsWithMessage = validations.filter(Boolean)\n\n if (validationsWithMessage.some((validation) => typeof validation !== 'boolean')) {\n validationsWithMessage.forEach((validation) => {\n if (validation && typeof validation !== 'boolean' && validation?.message) {\n logger?.log(validation.message, 'warn')\n }\n })\n\n return\n }\n\n fileManager.events.onSuccess(async () => {\n await pluginManager.hookParallel('buildEnd')\n setTimeout(() => {\n done()\n }, 1000)\n })\n\n fileManager.events.onAdd(async (id, file) => {\n const { path: filePath } = file\n let { source: code } = file\n\n const loadedResult = await pluginManager.hookFirst('load', [filePath])\n if (loadedResult) {\n code = loadedResult\n }\n\n if (code) {\n const transformedCode = await pluginManager.hookReduceArg0('transform', [code, filePath], transformReducer)\n\n await pluginManager.hookParallel('writeFile', [transformedCode, filePath])\n fileManager.setStatus(id, 'success')\n fileManager.remove(id)\n }\n })\n\n await pluginManager.hookParallel('buildStart', [config])\n}\n\nexport function build(options: BuildOptions): Promise<BuildOutput> {\n return new Promise((resolve, reject) => {\n try {\n buildImplementation(options, resolve)\n } catch (e) {\n reject(e)\n }\n })\n}\n","import pathParser from 'path'\n\nimport { createPluginCache } from './utils'\nimport { FileManager } from './managers/fileManager'\n\nimport type { EmittedFile, File } from './managers/fileManager'\nimport type { PluginContext, KubbPlugin, PluginFactoryOptions } from './types'\n\ntype KubbPluginFactory<T extends PluginFactoryOptions = PluginFactoryOptions> = (\n options: T['options']\n) => T['nested'] extends true ? Array<KubbPlugin<T>> : KubbPlugin<T>\n\nexport function createPlugin<T extends PluginFactoryOptions = PluginFactoryOptions>(factory: KubbPluginFactory<T>) {\n return (options: T['options']) => {\n const plugin = factory(options)\n if (Array.isArray(plugin)) {\n throw new Error('Not implemented')\n }\n\n // default transform\n if (!plugin.transform) {\n plugin.transform = function transform(code) {\n return code\n }\n }\n\n return plugin\n }\n}\n\ntype Options = {\n config: PluginContext['config']\n fileManager: FileManager\n resolveId: PluginContext['resolveId']\n load: PluginContext['load']\n}\n\n// not publicly exported\nexport type CorePluginOptions = PluginFactoryOptions<Options, false, PluginContext>\n\nexport const name = 'core' as const\n\nconst isEmittedFile = (result: EmittedFile | File): result is EmittedFile => {\n return !!(result as any).id\n}\n\nexport const definePlugin = createPlugin<CorePluginOptions>((options) => {\n const { fileManager, resolveId, load } = options\n const indexFiles: File[] = []\n\n const api: PluginContext = {\n get config() {\n return options.config\n },\n fileManager,\n async addFile(file, options) {\n if (isEmittedFile(file)) {\n const resolvedId = await resolveId({ fileName: file.id, directory: file.importer, options: file.options })\n const path = resolvedId || file.importer || file.id\n\n return fileManager.add({\n path,\n fileName: file.name || file.id,\n source: file.source || '',\n })\n }\n\n if (options?.root) {\n indexFiles.push(file)\n }\n\n return fileManager.add(file)\n },\n resolveId,\n load,\n cache: createPluginCache(Object.create(null)),\n }\n\n return {\n name,\n api,\n async buildEnd() {\n await FileManager.writeIndexes(this.config.root, this.config.output.path, { exclude: [/schemas/, /json/] })\n },\n resolveId(fileName, directory) {\n if (!directory) {\n return null\n }\n return pathParser.resolve(directory, fileName)\n },\n }\n})\n","import type { MaybePromise } from '../types'\n\nexport const isPromise = <T>(result: MaybePromise<T>): result is Promise<T> => {\n return typeof (result as any)?.then === 'function'\n}\n","/* eslint-disable consistent-return */\nimport fse from 'fs-extra'\n\nimport { format } from './format'\n\ntype WriteOptions = {\n format: boolean\n}\n\nexport const write = async (data: string, path: string, options: WriteOptions = { format: false }) => {\n const formattedData = options.format ? format(data) : data\n\n try {\n await fse.stat(path)\n const oldContent = await fse.readFile(path, { encoding: 'utf-8' })\n if (oldContent?.toString() === formattedData) {\n return\n }\n } catch (_err) {\n return fse.outputFile(path, formattedData)\n }\n\n return fse.outputFile(path, formattedData)\n}\n","import { format as prettierFormat } from 'prettier'\n\nimport type { Options } from 'prettier'\n\nconst formatOptions: Options = {\n tabWidth: 2,\n printWidth: 160,\n parser: 'typescript',\n singleQuote: true,\n semi: false,\n bracketSameLine: false,\n endOfLine: 'auto',\n}\nexport const format = (text: string) => {\n return prettierFormat(text, formatOptions)\n}\n","/* eslint-disable no-param-reassign */\n/* eslint-disable consistent-return */\n\nexport interface Cache<TCache = any> {\n delete(id: string): boolean\n get<T = TCache>(id: string): T\n has(id: string): boolean\n set<T = TCache>(id: string, value: T): void\n}\n\nexport function createPluginCache(cache: any): Cache {\n return {\n delete(id: string) {\n return delete cache[id]\n },\n get(id: string) {\n const item = cache[id]\n if (!item) return\n item[0] = 0\n return item[1]\n },\n has(id: string) {\n const item = cache[id]\n if (!item) return false\n item[0] = 0\n return true\n },\n set(id: string, value: any) {\n cache[id] = [0, value]\n },\n }\n}\n","import pathParser from 'path'\n\n// TODO check for a better way or resolving the relative path\nexport const getRelativePath = (root?: string | null, file?: string | null) => {\n if (!root || !file) {\n throw new Error('Root and file should be filled in when retrieving the relativePath')\n }\n const newPath = pathParser.relative(root, file).replace('../', '').replace('.ts', '').trimEnd()\n\n return `./${newPath}`\n}\n","import EventEmitter from 'events'\nimport { randomUUID } from 'crypto'\nimport pathParser from 'path'\n\nimport { getFileManagerEvents } from './events'\nimport { TreeNode } from './TreeNode'\n\nimport { write } from '../../utils/write'\n\nimport type { CacheStore, UUID, Status, File } from './types'\n\nexport class FileManager {\n private cache: Map<CacheStore['id'], CacheStore> = new Map()\n\n emitter = new EventEmitter()\n\n events = getFileManagerEvents(this.emitter)\n\n constructor() {\n this.events.onStatusChange(() => {\n if (this.getCountOfStatus('removed') === this.cache.size) {\n // all files are been resolved and written to the file system\n this.events.emitSuccess()\n }\n })\n }\n\n private getCache(id: UUID) {\n return this.cache.get(id)\n }\n\n private getCountOfStatus(status: Status) {\n let count = 0\n\n this.cache.forEach((item) => {\n if (item.status === status) {\n count++\n }\n })\n return count\n }\n\n get files() {\n const files: File[] = []\n this.cache.forEach((item) => {\n files.push(item.file)\n })\n\n return files\n }\n\n add(file: File) {\n const cacheItem = { id: randomUUID(), file, status: 'new' as Status }\n\n this.cache.set(cacheItem.id, cacheItem)\n this.events.emitFile(cacheItem.id, file)\n\n return new Promise<File>((resolve) => {\n const unsubscribe = this.events.onRemove(cacheItem.id, (file) => {\n resolve(file)\n unsubscribe()\n })\n })\n }\n\n setStatus(id: UUID, status: Status) {\n const cacheItem = this.getCache(id)\n if (!cacheItem) {\n return\n }\n\n cacheItem.status = status\n this.cache.set(id, cacheItem)\n this.events.emitStatusChange(cacheItem.file)\n this.events.emitStatusChangeById(id, status)\n }\n\n get(id: UUID) {\n const cacheItem = this.getCache(id)\n return cacheItem?.file\n }\n\n remove(id: UUID) {\n const cacheItem = this.getCache(id)\n if (!cacheItem) {\n return\n }\n\n this.setStatus(id, 'removed')\n this.events.emitRemove(id, cacheItem.file)\n }\n\n public static writeIndexes(root: string, output: string, options: Parameters<typeof TreeNode.generate>[1]) {\n const tree = TreeNode.generate(output, { extensions: /\\.ts/, ...options })\n\n const fileReducer = (files: File[], item: typeof tree) => {\n if (!item.children) {\n return []\n }\n\n if (item.children?.length > 1) {\n const source = item.children.reduce((source, file) => {\n if (!file) {\n return source\n }\n\n const importPath = file.data.type === 'directory' ? `./${file.data.name}` : `./${file.data.name.replace(/\\.[^.]*$/, '')}`\n\n return `${source}export * from \"${importPath}\";\\n`\n }, '')\n\n files.push({\n path: pathParser.resolve(root, item.data.path, 'index.ts'),\n fileName: 'index.ts',\n source,\n })\n } else {\n item.children?.forEach((child) => {\n const importPath = child.data.type === 'directory' ? `./${child.data.name}` : `./${child.data.name.replace(/\\.[^.]*$/, '')}`\n\n files.push({\n path: pathParser.resolve(root, item.data.path, 'index.ts'),\n fileName: 'index.ts',\n source: `export * from \"${importPath}\";\\n`,\n })\n })\n }\n\n item.children.forEach((childItem) => {\n fileReducer(files, childItem)\n })\n\n return files\n }\n\n const files = fileReducer([], tree)\n\n return files.map((file) => write(file.source, file.path))\n }\n}\n","import type EventEmitter from 'events'\nimport type { File, Status, UUID } from './types'\n\nconst keys = {\n getFileKey: () => `file`,\n getStatusChangeKey: () => `status-change`,\n getStatusChangeByIdKey: (id: string) => `${id}-status-change`,\n getSuccessKey: () => `success`,\n getRemoveKey: (id: string) => `${id}remove`,\n} as const\n\ntype VoidFunction = () => void\n\nexport const getFileManagerEvents = (emitter: EventEmitter) => {\n return {\n /**\n * Emiter\n */\n emitFile: (id: UUID, file: File): void => {\n emitter.emit(keys.getFileKey(), id, file)\n },\n emitStatusChange: (file: File): void => {\n emitter.emit(keys.getStatusChangeKey(), file)\n },\n emitStatusChangeById: (id: UUID, status: Status): void => {\n emitter.emit(keys.getStatusChangeByIdKey(id), status)\n },\n emitSuccess: (): void => {\n emitter.emit(keys.getSuccessKey())\n },\n emitRemove: (id: UUID, file: File): void => {\n emitter.emit(keys.getRemoveKey(id), file)\n },\n /**\n * Listeners\n */\n\n onAdd: (callback: (id: UUID, file: File) => void): VoidFunction => {\n emitter.on(keys.getFileKey(), callback)\n return () => emitter.removeListener(keys.getFileKey(), callback)\n },\n onStatusChange: (callback: (file: File) => void): VoidFunction => {\n emitter.on(keys.getStatusChangeKey(), callback)\n return () => emitter.removeListener(keys.getStatusChangeKey(), callback)\n },\n onStatusChangeById: (id: UUID, callback: (status: Status) => void): VoidFunction => {\n emitter.on(keys.getStatusChangeByIdKey(id), callback)\n return () => emitter.removeListener(keys.getStatusChangeByIdKey(id), callback)\n },\n onSuccess: (callback: () => void): VoidFunction => {\n emitter.on(keys.getSuccessKey(), callback)\n return () => emitter.removeListener(keys.getSuccessKey(), callback)\n },\n onRemove: (id: UUID, callback: (file: File) => void): VoidFunction => {\n emitter.on(keys.getRemoveKey(id), callback)\n return () => emitter.removeListener(keys.getRemoveKey(id), callback)\n },\n }\n}\n","import dirTree from 'directory-tree'\n\nimport type { DirectoryTree, DirectoryTreeOptions } from 'directory-tree'\n\nexport class TreeNode<T = unknown> {\n public data: T\n\n public parent?: TreeNode<T>\n\n public children: Array<TreeNode<T>>\n\n constructor(data: T, parent?: TreeNode<T>) {\n this.data = data\n this.parent = parent\n return this\n }\n\n addChild(data: T) {\n const child = new TreeNode(data, this)\n if (!this.children) {\n this.children = []\n }\n this.children.push(child)\n return child\n }\n\n find(data: T) {\n if (data === this.data) {\n return this\n }\n\n if (this.children) {\n for (let i = 0, { length } = this.children, target: any = null; i < length; i++) {\n target = this.children[i].find(data)\n if (target) {\n return target\n }\n }\n }\n\n return null\n }\n\n leaves() {\n if (!this.children || this.children.length === 0) {\n // this is a leaf\n return [this]\n }\n\n // if not a leaf, return all children's leaves recursively\n const leaves = []\n if (this.children) {\n for (let i = 0, { length } = this.children; i < length; i++) {\n // eslint-disable-next-line prefer-spread\n leaves.push.apply(leaves, this.children[i].leaves())\n }\n }\n return leaves\n }\n\n root() {\n if (!this.parent) {\n return this\n }\n return this.parent.root()\n }\n\n forEach(callback: (treeNode: TreeNode<T>) => void) {\n if (typeof callback !== 'function') {\n throw new TypeError('forEach() callback must be a function')\n }\n\n // run this node through function\n callback(this)\n\n // do the same for all children\n if (this.children) {\n for (let i = 0, { length } = this.children; i < length; i++) {\n this.children[i].forEach(callback)\n }\n }\n\n return this\n }\n\n public static generate(path: string, options: DirectoryTreeOptions = {}) {\n const filteredTree = dirTree(path, { extensions: options?.extensions, exclude: options.exclude })\n const treeNode = new TreeNode({ name: filteredTree.name, path: filteredTree.path, type: filteredTree.type })\n\n const recurse = (node: typeof treeNode, item: DirectoryTree) => {\n const subNode = node.addChild({ name: item.name, path: item.path, type: item.type })\n\n if (item.children?.length) {\n item.children?.forEach((child) => {\n recurse(subNode, child)\n })\n }\n }\n\n filteredTree.children?.forEach((child) => recurse(treeNode, child))\n\n return treeNode\n }\n}\n","/* eslint-disable no-await-in-loop */\n/* eslint-disable no-restricted-syntax */\n\nimport { definePlugin } from '../../plugin'\nimport { FileManager } from '../fileManager'\n\nimport type { Argument0, Strategy } from './types'\nimport type { KubbConfig, KubbPlugin, PluginLifecycleHooks, PluginLifecycle, MaybePromise, ResolveIdParams } from '../../types'\nimport type { Logger } from '../../build'\nimport type { CorePluginOptions } from '../../plugin'\n\n// inspired by: https://github.com/rollup/rollup/blob/master/src/utils/PluginDriver.ts#\n\n// This will make sure no input hook is omitted\nconst hookNames: {\n [P in PluginLifecycleHooks]: 1\n} = {\n validate: 1,\n buildStart: 1,\n resolveId: 1,\n load: 1,\n transform: 1,\n writeFile: 1,\n buildEnd: 1,\n}\nexport const hooks = Object.keys(hookNames) as [PluginLifecycleHooks]\n\nexport class PluginManager {\n public plugins: KubbPlugin[]\n\n public readonly fileManager: FileManager\n\n private readonly logger?: Logger\n\n private readonly config: KubbConfig\n\n public readonly core: KubbPlugin<CorePluginOptions>\n\n constructor(config: KubbConfig, options: { logger?: Logger }) {\n this.logger = options.logger\n this.config = config\n\n this.fileManager = new FileManager()\n this.core = definePlugin({\n config,\n fileManager: this.fileManager,\n load: this.load,\n resolveId: this.resolveId,\n }) as KubbPlugin<CorePluginOptions> & {\n api: CorePluginOptions['api']\n }\n this.plugins = [this.core, ...(config.plugins || [])]\n }\n\n resolveId = (params: ResolveIdParams) => {\n if (params.pluginName) {\n return this.hookForPlugin(params.pluginName, 'resolveId', [params.fileName, params.directory, params.options])\n }\n return this.hookFirst('resolveId', [params.fileName, params.directory, params.options])\n }\n\n load = async (id: string) => {\n return this.hookFirst('load', [id])\n }\n\n // run only hook for a specific plugin name\n hookForPlugin<H extends PluginLifecycleHooks>(\n pluginName: string,\n hookName: H,\n parameters: Parameters<PluginLifecycle[H]>,\n skipped?: ReadonlySet<KubbPlugin> | null\n ): Promise<ReturnType<PluginLifecycle[H]> | null> {\n let promise: Promise<ReturnType<PluginLifecycle[H]> | null> = Promise.resolve(null)\n for (const plugin of this.getSortedPlugins(hookName, pluginName)) {\n if (skipped && skipped.has(plugin)) continue\n promise = promise.then((result) => {\n if (result != null) return result\n return this.run('hookFirst', hookName, parameters, plugin) as any\n })\n }\n return promise\n }\n\n // chains, first non-null result stops and returns\n hookFirst<H extends PluginLifecycleHooks>(\n hookName: H,\n parameters: Parameters<PluginLifecycle[H]>,\n skipped?: ReadonlySet<KubbPlugin> | null\n ): Promise<ReturnType<PluginLifecycle[H]> | null> {\n let promise: Promise<ReturnType<PluginLifecycle[H]> | null> = Promise.resolve(null)\n for (const plugin of this.getSortedPlugins(hookName)) {\n if (skipped && skipped.has(plugin)) continue\n promise = promise.then((result) => {\n if (result != null) return result\n return this.run('hookFirst', hookName, parameters, plugin) as any\n })\n }\n return promise\n }\n\n // parallel\n async hookParallel<H extends PluginLifecycleHooks, TOuput = void>(hookName: H, parameters?: Parameters<PluginLifecycle[H]> | undefined) {\n const parallelPromises: Promise<TOuput>[] = []\n\n for (const plugin of this.getSortedPlugins(hookName)) {\n if ((plugin[hookName] as { sequential?: boolean })?.sequential) {\n await Promise.all(parallelPromises)\n parallelPromises.length = 0\n await this.run('hookParallel', hookName, parameters, plugin)\n } else {\n const promise: Promise<TOuput> = this.run('hookParallel', hookName, parameters, plugin)\n\n parallelPromises.push(promise)\n }\n }\n return Promise.all(parallelPromises)\n }\n\n // chains, reduces returned value, handling the reduced value as the first hook argument\n hookReduceArg0<H extends PluginLifecycleHooks>(\n hookName: H,\n [argument0, ...rest]: Parameters<PluginLifecycle[H]>,\n reduce: (reduction: Argument0<H>, result: ReturnType<PluginLifecycle[H]>, plugin: KubbPlugin) => MaybePromise<Argument0<H> | null>\n ): Promise<Argument0<H>> {\n let promise = Promise.resolve(argument0)\n for (const plugin of this.getSortedPlugins(hookName)) {\n promise = promise.then((argument0) =>\n this.run('hookReduceArg0', hookName, [argument0, ...rest] as Parameters<PluginLifecycle[H]>, plugin).then((result) =>\n reduce.call(this.core.api, argument0, result, plugin)\n )\n )\n }\n return promise\n }\n\n // chains\n\n hookSeq<H extends PluginLifecycleHooks>(hookName: H, parameters?: Parameters<PluginLifecycle[H]>) {\n let promise: Promise<void> = Promise.resolve()\n for (const plugin of this.getSortedPlugins(hookName)) {\n promise = promise.then(() => this.run('hookSeq', hookName, parameters, plugin))\n }\n return promise.then(noReturn)\n }\n\n private getSortedPlugins(hookName: keyof PluginLifecycle, pluginName?: string): KubbPlugin[] {\n const plugins = [...this.plugins]\n\n if (pluginName) {\n const pluginsByPluginName = plugins.filter((item) => item.name === pluginName && item[hookName])\n if (pluginsByPluginName.length === 0) {\n // fallback on the core plugin when there is no match\n if (this.config.logLevel === 'warn' && this.logger?.spinner) {\n this.logger.spinner.info(`Plugin hook with ${hookName} not found for plugin ${pluginName}`)\n }\n return [this.core]\n }\n return pluginsByPluginName\n }\n\n return plugins\n }\n\n /**\n * Run an async plugin hook and return the result.\n * @param hookName Name of the plugin hook. Must be either in `PluginHooks` or `OutputPluginValueHooks`.\n * @param args Arguments passed to the plugin hook.\n * @param plugin The actual pluginObject to run.\n */\n // Implementation signature\n private run<H extends PluginLifecycleHooks, TResult = void>(\n strategy: Strategy,\n hookName: H,\n parameters: unknown[] | undefined,\n plugin: KubbPlugin\n ): Promise<TResult> {\n const hook = plugin[hookName]!\n\n return Promise.resolve().then(() => {\n if (typeof hook !== 'function') {\n return hook\n }\n\n if (this.config.logLevel === 'info' && this.logger?.spinner) {\n this.logger.spinner.text = `[${strategy}] ${hookName}: Excecuting task for plugin ${plugin.name} \\n`\n }\n\n const hookResult = (hook as any).apply(this.core.api, parameters)\n\n if (!hookResult?.then) {\n // short circuit for non-thenables and non-Promises\n if (this.config.logLevel === 'info' && this.logger?.spinner) {\n this.logger.spinner.succeed(`[${strategy}] ${hookName}: Excecuting task for plugin ${plugin.name} \\n`)\n }\n return hookResult\n }\n\n return Promise.resolve(hookResult).then((result) => {\n // action was fulfilled\n if (this.config.logLevel === 'info' && this.logger?.spinner) {\n this.logger.spinner.succeed(`[${strategy}] ${hookName}: Excecuting task for plugin ${plugin.name} \\n`)\n }\n return result\n })\n })\n }\n\n /**\n * Run a sync plugin hook and return the result.\n * @param hookName Name of the plugin hook. Must be in `PluginHooks`.\n * @param args Arguments passed to the plugin hook.\n * @param plugin The acutal plugin\n * @param replaceContext When passed, the plugin context can be overridden.\n */\n private runSync<H extends PluginLifecycleHooks>(hookName: H, parameters: Parameters<PluginLifecycle[H]>, plugin: KubbPlugin): ReturnType<PluginLifecycle[H]> {\n const hook = plugin[hookName]!\n\n // const context = this.pluginContexts.get(plugin)!;\n\n try {\n // eslint-disable-next-line @typescript-eslint/ban-types\n return (hook as Function).apply(this.core.api, parameters)\n } catch (error: any) {\n return error\n }\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-empty-function\nfunction noReturn() {}\n","import type { MaybePromise, KubbUserConfig, CLIOptions } from './types'\n\n/**\n * Type helper to make it easier to use kubb.config.ts\n * accepts a direct {@link KubbConfig} object, or a function that returns it.\n * The function receives a {@link ConfigEnv} object that exposes two properties:\n */\nexport const defineConfig = (\n options:\n | MaybePromise<KubbUserConfig>\n | ((\n /** The options derived from the CLI flags */\n cliOptions: CLIOptions\n ) => MaybePromise<KubbUserConfig>)\n) => options\n","/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { build } from './build'\n\nexport * from './config'\nexport * from './build'\nexport { CorePluginOptions, createPlugin } from './plugin'\nexport * from './utils'\nexport * from './types'\nexport * from './managers'\nexport default build\n"]}
|
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import path3 from 'path';
|
|
2
1
|
import fse from 'fs-extra';
|
|
2
|
+
import pathParser2 from 'path';
|
|
3
3
|
import { format as format$1 } from 'prettier';
|
|
4
4
|
import EventEmitter from 'events';
|
|
5
5
|
import { randomUUID } from 'crypto';
|
|
@@ -25,18 +25,18 @@ var format = (text) => {
|
|
|
25
25
|
};
|
|
26
26
|
|
|
27
27
|
// src/utils/write.ts
|
|
28
|
-
var write = async (data,
|
|
28
|
+
var write = async (data, path, options = { format: false }) => {
|
|
29
29
|
const formattedData = options.format ? format(data) : data;
|
|
30
30
|
try {
|
|
31
|
-
await fse.stat(
|
|
32
|
-
const oldContent = await fse.readFile(
|
|
31
|
+
await fse.stat(path);
|
|
32
|
+
const oldContent = await fse.readFile(path, { encoding: "utf-8" });
|
|
33
33
|
if (oldContent?.toString() === formattedData) {
|
|
34
34
|
return;
|
|
35
35
|
}
|
|
36
36
|
} catch (_err) {
|
|
37
|
-
return fse.outputFile(
|
|
37
|
+
return fse.outputFile(path, formattedData);
|
|
38
38
|
}
|
|
39
|
-
return fse.outputFile(
|
|
39
|
+
return fse.outputFile(path, formattedData);
|
|
40
40
|
};
|
|
41
41
|
|
|
42
42
|
// src/utils/cache.ts
|
|
@@ -68,68 +68,10 @@ var getRelativePath = (root, file) => {
|
|
|
68
68
|
if (!root || !file) {
|
|
69
69
|
throw new Error("Root and file should be filled in when retrieving the relativePath");
|
|
70
70
|
}
|
|
71
|
-
const newPath =
|
|
71
|
+
const newPath = pathParser2.relative(root, file).replace("../", "").replace(".ts", "").trimEnd();
|
|
72
72
|
return `./${newPath}`;
|
|
73
73
|
};
|
|
74
74
|
|
|
75
|
-
// src/plugin.ts
|
|
76
|
-
function createPlugin(factory) {
|
|
77
|
-
return (options) => {
|
|
78
|
-
const plugin = factory(options);
|
|
79
|
-
if (Array.isArray(plugin)) {
|
|
80
|
-
throw new Error("Not implemented");
|
|
81
|
-
}
|
|
82
|
-
if (!plugin.transform) {
|
|
83
|
-
plugin.transform = function transform(code) {
|
|
84
|
-
return code;
|
|
85
|
-
};
|
|
86
|
-
}
|
|
87
|
-
return plugin;
|
|
88
|
-
};
|
|
89
|
-
}
|
|
90
|
-
var name = "core";
|
|
91
|
-
var isEmittedFile = (result) => {
|
|
92
|
-
return !!result.id;
|
|
93
|
-
};
|
|
94
|
-
var definePlugin = createPlugin((options) => {
|
|
95
|
-
const { fileManager, resolveId, load } = options;
|
|
96
|
-
const api = {
|
|
97
|
-
get config() {
|
|
98
|
-
return options.config;
|
|
99
|
-
},
|
|
100
|
-
fileManager,
|
|
101
|
-
async addFile(file, options2) {
|
|
102
|
-
if (isEmittedFile(file)) {
|
|
103
|
-
const resolvedId = await resolveId({ importee: file.id, importer: file.importer, options: file.options });
|
|
104
|
-
const filePath = resolvedId || file.importer || file.id;
|
|
105
|
-
return fileManager.add({
|
|
106
|
-
path: filePath,
|
|
107
|
-
fileName: file.name || file.id,
|
|
108
|
-
source: file.source || ""
|
|
109
|
-
});
|
|
110
|
-
}
|
|
111
|
-
if (options2?.root) ;
|
|
112
|
-
return fileManager.add(file);
|
|
113
|
-
},
|
|
114
|
-
resolveId,
|
|
115
|
-
load,
|
|
116
|
-
cache: createPluginCache(/* @__PURE__ */ Object.create(null))
|
|
117
|
-
};
|
|
118
|
-
return {
|
|
119
|
-
name,
|
|
120
|
-
api,
|
|
121
|
-
async buildEnd() {
|
|
122
|
-
await this.fileManager.generateRootFiles({ exclude: [/schemas/, /json/] });
|
|
123
|
-
},
|
|
124
|
-
resolveId(importee, importer) {
|
|
125
|
-
if (!importer) {
|
|
126
|
-
return null;
|
|
127
|
-
}
|
|
128
|
-
return path3.resolve(importer, importee);
|
|
129
|
-
}
|
|
130
|
-
};
|
|
131
|
-
});
|
|
132
|
-
|
|
133
75
|
// src/managers/fileManager/events.ts
|
|
134
76
|
var keys = {
|
|
135
77
|
getFileKey: () => `file`,
|
|
@@ -238,8 +180,8 @@ var TreeNode = class {
|
|
|
238
180
|
}
|
|
239
181
|
return this;
|
|
240
182
|
}
|
|
241
|
-
static generate(
|
|
242
|
-
const filteredTree = dirTree(
|
|
183
|
+
static generate(path, options = {}) {
|
|
184
|
+
const filteredTree = dirTree(path, { extensions: options?.extensions, exclude: options.exclude });
|
|
243
185
|
const treeNode = new TreeNode({ name: filteredTree.name, path: filteredTree.path, type: filteredTree.type });
|
|
244
186
|
const recurse = (node, item) => {
|
|
245
187
|
const subNode = node.addChild({ name: item.name, path: item.path, type: item.type });
|
|
@@ -257,13 +199,9 @@ var TreeNode = class {
|
|
|
257
199
|
// src/managers/fileManager/FileManager.ts
|
|
258
200
|
var FileManager = class {
|
|
259
201
|
cache = /* @__PURE__ */ new Map();
|
|
260
|
-
root;
|
|
261
|
-
output;
|
|
262
202
|
emitter = new EventEmitter();
|
|
263
203
|
events = getFileManagerEvents(this.emitter);
|
|
264
|
-
constructor(
|
|
265
|
-
this.root = path3.resolve(options.root || ".");
|
|
266
|
-
this.output = options?.output || process.cwd();
|
|
204
|
+
constructor() {
|
|
267
205
|
this.events.onStatusChange(() => {
|
|
268
206
|
if (this.getCountOfStatus("removed") === this.cache.size) {
|
|
269
207
|
this.events.emitSuccess();
|
|
@@ -289,11 +227,41 @@ var FileManager = class {
|
|
|
289
227
|
});
|
|
290
228
|
return files;
|
|
291
229
|
}
|
|
292
|
-
|
|
293
|
-
|
|
230
|
+
add(file) {
|
|
231
|
+
const cacheItem = { id: randomUUID(), file, status: "new" };
|
|
232
|
+
this.cache.set(cacheItem.id, cacheItem);
|
|
233
|
+
this.events.emitFile(cacheItem.id, file);
|
|
234
|
+
return new Promise((resolve) => {
|
|
235
|
+
const unsubscribe = this.events.onRemove(cacheItem.id, (file2) => {
|
|
236
|
+
resolve(file2);
|
|
237
|
+
unsubscribe();
|
|
238
|
+
});
|
|
239
|
+
});
|
|
294
240
|
}
|
|
295
|
-
|
|
296
|
-
const
|
|
241
|
+
setStatus(id, status) {
|
|
242
|
+
const cacheItem = this.getCache(id);
|
|
243
|
+
if (!cacheItem) {
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
cacheItem.status = status;
|
|
247
|
+
this.cache.set(id, cacheItem);
|
|
248
|
+
this.events.emitStatusChange(cacheItem.file);
|
|
249
|
+
this.events.emitStatusChangeById(id, status);
|
|
250
|
+
}
|
|
251
|
+
get(id) {
|
|
252
|
+
const cacheItem = this.getCache(id);
|
|
253
|
+
return cacheItem?.file;
|
|
254
|
+
}
|
|
255
|
+
remove(id) {
|
|
256
|
+
const cacheItem = this.getCache(id);
|
|
257
|
+
if (!cacheItem) {
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
260
|
+
this.setStatus(id, "removed");
|
|
261
|
+
this.events.emitRemove(id, cacheItem.file);
|
|
262
|
+
}
|
|
263
|
+
static writeIndexes(root, output, options) {
|
|
264
|
+
const tree = TreeNode.generate(output, { extensions: /\.ts/, ...options });
|
|
297
265
|
const fileReducer = (files2, item) => {
|
|
298
266
|
if (!item.children) {
|
|
299
267
|
return [];
|
|
@@ -308,7 +276,7 @@ var FileManager = class {
|
|
|
308
276
|
`;
|
|
309
277
|
}, "");
|
|
310
278
|
files2.push({
|
|
311
|
-
path:
|
|
279
|
+
path: pathParser2.resolve(root, item.data.path, "index.ts"),
|
|
312
280
|
fileName: "index.ts",
|
|
313
281
|
source
|
|
314
282
|
});
|
|
@@ -316,7 +284,7 @@ var FileManager = class {
|
|
|
316
284
|
item.children?.forEach((child) => {
|
|
317
285
|
const importPath = child.data.type === "directory" ? `./${child.data.name}` : `./${child.data.name.replace(/\.[^.]*$/, "")}`;
|
|
318
286
|
files2.push({
|
|
319
|
-
path:
|
|
287
|
+
path: pathParser2.resolve(root, item.data.path, "index.ts"),
|
|
320
288
|
fileName: "index.ts",
|
|
321
289
|
source: `export * from "${importPath}";
|
|
322
290
|
`
|
|
@@ -331,40 +299,65 @@ var FileManager = class {
|
|
|
331
299
|
const files = fileReducer([], tree);
|
|
332
300
|
return files.map((file) => write(file.source, file.path));
|
|
333
301
|
}
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
});
|
|
343
|
-
});
|
|
344
|
-
}
|
|
345
|
-
setStatus(id, status) {
|
|
346
|
-
const cacheItem = this.getCache(id);
|
|
347
|
-
if (!cacheItem) {
|
|
348
|
-
return;
|
|
302
|
+
};
|
|
303
|
+
|
|
304
|
+
// src/plugin.ts
|
|
305
|
+
function createPlugin(factory) {
|
|
306
|
+
return (options) => {
|
|
307
|
+
const plugin = factory(options);
|
|
308
|
+
if (Array.isArray(plugin)) {
|
|
309
|
+
throw new Error("Not implemented");
|
|
349
310
|
}
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
}
|
|
355
|
-
get(id) {
|
|
356
|
-
const cacheItem = this.getCache(id);
|
|
357
|
-
return cacheItem?.file;
|
|
358
|
-
}
|
|
359
|
-
remove(id) {
|
|
360
|
-
const cacheItem = this.getCache(id);
|
|
361
|
-
if (!cacheItem) {
|
|
362
|
-
return;
|
|
311
|
+
if (!plugin.transform) {
|
|
312
|
+
plugin.transform = function transform(code) {
|
|
313
|
+
return code;
|
|
314
|
+
};
|
|
363
315
|
}
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
316
|
+
return plugin;
|
|
317
|
+
};
|
|
318
|
+
}
|
|
319
|
+
var name = "core";
|
|
320
|
+
var isEmittedFile = (result) => {
|
|
321
|
+
return !!result.id;
|
|
367
322
|
};
|
|
323
|
+
var definePlugin = createPlugin((options) => {
|
|
324
|
+
const { fileManager, resolveId, load } = options;
|
|
325
|
+
const api = {
|
|
326
|
+
get config() {
|
|
327
|
+
return options.config;
|
|
328
|
+
},
|
|
329
|
+
fileManager,
|
|
330
|
+
async addFile(file, options2) {
|
|
331
|
+
if (isEmittedFile(file)) {
|
|
332
|
+
const resolvedId = await resolveId({ fileName: file.id, directory: file.importer, options: file.options });
|
|
333
|
+
const path = resolvedId || file.importer || file.id;
|
|
334
|
+
return fileManager.add({
|
|
335
|
+
path,
|
|
336
|
+
fileName: file.name || file.id,
|
|
337
|
+
source: file.source || ""
|
|
338
|
+
});
|
|
339
|
+
}
|
|
340
|
+
if (options2?.root) ;
|
|
341
|
+
return fileManager.add(file);
|
|
342
|
+
},
|
|
343
|
+
resolveId,
|
|
344
|
+
load,
|
|
345
|
+
cache: createPluginCache(/* @__PURE__ */ Object.create(null))
|
|
346
|
+
};
|
|
347
|
+
return {
|
|
348
|
+
name,
|
|
349
|
+
api,
|
|
350
|
+
async buildEnd() {
|
|
351
|
+
await FileManager.writeIndexes(this.config.root, this.config.output.path, { exclude: [/schemas/, /json/] });
|
|
352
|
+
},
|
|
353
|
+
resolveId(fileName, directory) {
|
|
354
|
+
if (!directory) {
|
|
355
|
+
return null;
|
|
356
|
+
}
|
|
357
|
+
return pathParser2.resolve(directory, fileName);
|
|
358
|
+
}
|
|
359
|
+
};
|
|
360
|
+
});
|
|
368
361
|
|
|
369
362
|
// src/managers/pluginManager/PluginManager.ts
|
|
370
363
|
var hookNames = {
|
|
@@ -386,7 +379,7 @@ var PluginManager = class {
|
|
|
386
379
|
constructor(config, options) {
|
|
387
380
|
this.logger = options.logger;
|
|
388
381
|
this.config = config;
|
|
389
|
-
this.fileManager = new FileManager(
|
|
382
|
+
this.fileManager = new FileManager();
|
|
390
383
|
this.core = definePlugin({
|
|
391
384
|
config,
|
|
392
385
|
fileManager: this.fileManager,
|
|
@@ -397,9 +390,9 @@ var PluginManager = class {
|
|
|
397
390
|
}
|
|
398
391
|
resolveId = (params) => {
|
|
399
392
|
if (params.pluginName) {
|
|
400
|
-
return this.hookForPlugin(params.pluginName, "resolveId", [params.
|
|
393
|
+
return this.hookForPlugin(params.pluginName, "resolveId", [params.fileName, params.directory, params.options]);
|
|
401
394
|
}
|
|
402
|
-
return this.hookFirst("resolveId", [params.
|
|
395
|
+
return this.hookFirst("resolveId", [params.fileName, params.directory, params.options]);
|
|
403
396
|
};
|
|
404
397
|
load = async (id) => {
|
|
405
398
|
return this.hookFirst("load", [id]);
|
|
@@ -529,7 +522,6 @@ async function buildImplementation(options, done) {
|
|
|
529
522
|
}
|
|
530
523
|
const pluginManager = new PluginManager(config, { logger });
|
|
531
524
|
const { plugins, fileManager } = pluginManager;
|
|
532
|
-
fse.readFileSync(path3.resolve(config.root, config.input.path), "utf-8");
|
|
533
525
|
const validations = await pluginManager.hookParallel("validate", [plugins]);
|
|
534
526
|
const validationsWithMessage = validations.filter(Boolean);
|
|
535
527
|
if (validationsWithMessage.some((validation) => typeof validation !== "boolean")) {
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/build.ts","../src/plugin.ts","../src/utils/isPromise.ts","../src/utils/write.ts","../src/utils/format.ts","../src/utils/cache.ts","../src/utils/read.ts","../src/managers/fileManager/FileManager.ts","../src/managers/fileManager/events.ts","../src/managers/fileManager/TreeNode.ts","../src/managers/pluginManager/PluginManager.ts","../src/config.ts","../src/index.ts"],"names":["path","fse","options","files","source","file","argument0"],"mappings":";AAAA,OAAOA,WAAU;AAEjB,OAAOC,UAAS;;;ACFhB,OAAOD,WAAU;;;ACEV,IAAM,YAAY,CAAI,WAAkD;AAC7E,SAAO,OAAQ,QAAgB,SAAS;AAC1C;;;ACHA,OAAO,SAAS;;;ACDhB,SAAS,UAAU,sBAAsB;AAIzC,IAAM,gBAAyB;AAAA,EAC7B,UAAU;AAAA,EACV,YAAY;AAAA,EACZ,QAAQ;AAAA,EACR,aAAa;AAAA,EACb,MAAM;AAAA,EACN,iBAAiB;AAAA,EACjB,WAAW;AACb;AACO,IAAM,SAAS,CAAC,SAAiB;AACtC,SAAO,eAAe,MAAM,aAAa;AAC3C;;;ADNO,IAAM,QAAQ,OAAO,MAAcA,OAAc,UAAwB,EAAE,QAAQ,MAAM,MAAM;AACpG,QAAM,gBAAgB,QAAQ,SAAS,OAAO,IAAI,IAAI;AAEtD,MAAI;AACF,UAAM,IAAI,KAAKA,KAAI;AACnB,UAAM,aAAa,MAAM,IAAI,SAASA,OAAM,EAAE,UAAU,QAAQ,CAAC;AACjE,QAA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O,CAAC;AACxG,QAAM,yBAAyB,YAAY,OAAO,OAAO;AAEzD,MAAI,uBAAuB,KAAK,CAAC,eAAe,OAAO,eAAe,SAAS,GAAG;AAChF,2BAAuB,QAAQ,CAAC,eAAe;AAC7C,UAAI,cAAc,OAAO,eAAe,aAAa,YAAY,SAAS;AACxE,gBAAQ,IAAI,WAAW,SAAS,MAAM;AAAA,MACxC;AAAA,IACF,CAAC;AAED;AAAA,EACF;AAEA,cAAY,OAAO,UAAU,YAAY;AACvC,UAAM,cAAc,aAAa,UAAU;AAC3C,eAAW,MAAM;AACf,WAAK;AAAA,IACP,GAAG,GAAI;AAAA,EACT,CAAC;AAED,cAAY,OAAO,MAAM,OAAO,IAAI,SAAS;AAC3C,UAAM,EAAE,MAAM,SAAS,IAAI;AAC3B,QAAI,EAAE,QAAQ,KAAK,IAAI;AAEvB,UAAM,eAAe,MAAM,cAAc,UAAU,QAAQ,CAAC,QAAQ,CAAC;AACrE,QAAI,cAAc;AAChB,aAAO;AAAA,IACT;AAEA,QAAI,MAAM;AACR,YAAM,kBAAkB,MAAM,cAAc,eAAe,aAAa,CAAC,MAAM,QAAQ,GAAG,gBAAgB;AAE1G,YAAM,cAAc,aAAa,aAAa,CAAC,iBAAiB,QAAQ,CAAC;AACzE,kBAAY,UAAU,IAAI,SAAS;AACnC,kBAAY,OAAO,EAAE;AAAA,IACvB;AAAA,EACF,CAAC;AAED,QAAM,cAAc,aAAa,cAAc,CAAC,MAAM,CAAC;AACzD;AAEO,SAAS,MAAM,SAA6C;AACjE,SAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACtC,QAAI;AACF,0BAAoB,SAAS,OAAO;AAAA,IACtC,SAAS,GAAP;AACA,aAAO,CAAC;AAAA,IACV;AAAA,EACF,CAAC;AACH;;;AW1FO,IAAM,eAAe,CAC1B,YAMG;;;ACLL,IAAO,cAAQ","sourcesContent":["import path from 'path'\n\nimport fse from 'fs-extra'\n\nimport { PluginManager } from './managers/pluginManager'\n\nimport type { PluginContext, TransformResult, ValidationResult, LogLevel, KubbPlugin } from './types'\n\ntype BuildOutput = void\n\n// Same type as ora\ntype Spinner = {\n start: (text?: string) => Spinner\n succeed: (text: string) => Spinner\n stopAndPersist: (options: { text: string }) => Spinner\n render: () => Spinner\n text: string\n info: (text: string) => Spinner\n}\n\nexport type Logger = {\n log: (message: string, logLevel: LogLevel) => void\n spinner?: Spinner\n}\ntype BuildOptions = {\n config: PluginContext['config']\n mode: 'development' | 'production'\n logger?: Logger\n}\n\nasync function transformReducer(this: PluginContext, _previousCode: string, result: TransformResult, _plugin: KubbPlugin) {\n if (result === null) {\n return null\n }\n return result\n}\n\nasync function buildImplementation(options: BuildOptions, done: (output: BuildOutput) => void) {\n const { config, logger } = options\n\n if (config.output.clean) {\n await fse.remove(config.output.path)\n }\n\n const pluginManager = new PluginManager(config, { logger })\n const { plugins, fileManager } = pluginManager\n const input = fse.readFileSync(path.resolve(config.root, config.input.path), 'utf-8')\n\n const validations = await pluginManager.hookParallel<'validate', ValidationResult>('validate', [plugins])\n const validationsWithMessage = validations.filter(Boolean)\n\n if (validationsWithMessage.some((validation) => typeof validation !== 'boolean')) {\n validationsWithMessage.forEach((validation) => {\n if (validation && typeof validation !== 'boolean' && validation?.message) {\n logger?.log(validation.message, 'warn')\n }\n })\n\n return\n }\n\n fileManager.events.onSuccess(async () => {\n await pluginManager.hookParallel('buildEnd')\n setTimeout(() => {\n done()\n }, 1000)\n })\n\n fileManager.events.onAdd(async (id, file) => {\n const { path: filePath } = file\n let { source: code } = file\n\n const loadedResult = await pluginManager.hookFirst('load', [filePath])\n if (loadedResult) {\n code = loadedResult\n }\n\n if (code) {\n const transformedCode = await pluginManager.hookReduceArg0('transform', [code, filePath], transformReducer)\n\n await pluginManager.hookParallel('writeFile', [transformedCode, filePath])\n fileManager.setStatus(id, 'success')\n fileManager.remove(id)\n }\n })\n\n await pluginManager.hookParallel('buildStart', [config])\n}\n\nexport function build(options: BuildOptions): Promise<BuildOutput> {\n return new Promise((resolve, reject) => {\n try {\n buildImplementation(options, resolve)\n } catch (e) {\n reject(e)\n }\n })\n}\n","import path from 'path'\n\nimport { createPluginCache } from './utils'\n\nimport type { FileManager, EmittedFile, File } from './managers/fileManager'\nimport type { PluginContext, KubbPlugin, PluginFactoryOptions } from './types'\n\ntype KubbPluginFactory<T extends PluginFactoryOptions = PluginFactoryOptions> = (\n options: T['options']\n) => T['nested'] extends true ? Array<KubbPlugin<T>> : KubbPlugin<T>\n\nexport function createPlugin<T extends PluginFactoryOptions = PluginFactoryOptions>(factory: KubbPluginFactory<T>) {\n return (options: T['options']) => {\n const plugin = factory(options)\n if (Array.isArray(plugin)) {\n throw new Error('Not implemented')\n }\n\n // default transform\n if (!plugin.transform) {\n plugin.transform = function transform(code) {\n return code\n }\n }\n\n return plugin\n }\n}\n\ntype Options = {\n config: PluginContext['config']\n fileManager: FileManager\n resolveId: PluginContext['resolveId']\n load: PluginContext['load']\n}\n\n// not publicly exported\nexport type CorePluginOptions = PluginFactoryOptions<Options, false, PluginContext>\n\nexport const name = 'core' as const\n\nconst isEmittedFile = (result: EmittedFile | File): result is EmittedFile => {\n return !!(result as any).id\n}\n\nexport const definePlugin = createPlugin<CorePluginOptions>((options) => {\n const { fileManager, resolveId, load } = options\n const indexFiles: File[] = []\n\n const api: PluginContext = {\n get config() {\n return options.config\n },\n fileManager,\n async addFile(file, options) {\n if (isEmittedFile(file)) {\n const resolvedId = await resolveId({ importee: file.id, importer: file.importer, options: file.options })\n const filePath = resolvedId || file.importer || file.id\n\n return fileManager.add({\n path: filePath,\n fileName: file.name || file.id,\n source: file.source || '',\n })\n }\n\n if (options?.root) {\n indexFiles.push(file)\n }\n\n return fileManager.add(file)\n },\n resolveId,\n load,\n cache: createPluginCache(Object.create(null)),\n }\n\n return {\n name,\n api,\n async buildEnd() {\n await this.fileManager.generateRootFiles({ exclude: [/schemas/, /json/] })\n },\n resolveId(importee, importer) {\n if (!importer) {\n return null\n }\n return path.resolve(importer, importee)\n },\n }\n})\n","import type { MaybePromise } from '../types'\n\nexport const isPromise = <T>(result: MaybePromise<T>): result is Promise<T> => {\n return typeof (result as any)?.then === 'function'\n}\n","/* eslint-disable consistent-return */\nimport fse from 'fs-extra'\n\nimport { format } from './format'\n\ntype WriteOptions = {\n format: boolean\n}\n\nexport const write = async (data: string, path: string, options: WriteOptions = { format: false }) => {\n const formattedData = options.format ? format(data) : data\n\n try {\n await fse.stat(path)\n const oldContent = await fse.readFile(path, { encoding: 'utf-8' })\n if (oldContent?.toString() === formattedData) {\n return\n }\n } catch (_err) {\n return fse.outputFile(path, formattedData)\n }\n\n return fse.outputFile(path, formattedData)\n}\n","import { format as prettierFormat } from 'prettier'\n\nimport type { Options } from 'prettier'\n\nconst formatOptions: Options = {\n tabWidth: 2,\n printWidth: 160,\n parser: 'typescript',\n singleQuote: true,\n semi: false,\n bracketSameLine: false,\n endOfLine: 'auto',\n}\nexport const format = (text: string) => {\n return prettierFormat(text, formatOptions)\n}\n","/* eslint-disable no-param-reassign */\n/* eslint-disable consistent-return */\n\nexport interface Cache<TCache = any> {\n delete(id: string): boolean\n get<T = TCache>(id: string): T\n has(id: string): boolean\n set<T = TCache>(id: string, value: T): void\n}\n\nexport function createPluginCache(cache: any): Cache {\n return {\n delete(id: string) {\n return delete cache[id]\n },\n get(id: string) {\n const item = cache[id]\n if (!item) return\n item[0] = 0\n return item[1]\n },\n has(id: string) {\n const item = cache[id]\n if (!item) return false\n item[0] = 0\n return true\n },\n set(id: string, value: any) {\n cache[id] = [0, value]\n },\n }\n}\n","import path from 'path'\n\n// TODO check for a better way or resolving the relative path\nexport const getRelativePath = (root?: string | null, file?: string | null) => {\n if (!root || !file) {\n throw new Error('Root and file should be filled in when retrieving the relativePath')\n }\n const newPath = path.relative(root, file).replace('../', '').replace('.ts', '').trimEnd()\n\n return `./${newPath}`\n}\n","import EventEmitter from 'events'\nimport { randomUUID } from 'crypto'\nimport path from 'path'\n\nimport { getFileManagerEvents } from './events'\nimport { TreeNode } from './TreeNode'\n\nimport { write } from '../../utils/write'\n\nimport type { GenerateTreeNodeOptions } from './TreeNode'\nimport type { CacheStore, UUID, Status, File } from './types'\n\nexport class FileManager {\n private cache: Map<CacheStore['id'], CacheStore> = new Map()\n\n private readonly root: string\n\n private readonly output: string\n\n emitter = new EventEmitter()\n\n events = getFileManagerEvents(this.emitter)\n\n constructor(options: { root?: string; output?: string } = {}) {\n this.root = path.resolve(options.root || '.')\n // TODO better types\n this.output = options?.output || process.cwd()\n this.events.onStatusChange(() => {\n if (this.getCountOfStatus('removed') === this.cache.size) {\n // all files are been resolved and written to the file system\n this.events.emitSuccess()\n }\n })\n }\n\n private getCache(id: UUID) {\n return this.cache.get(id)\n }\n\n private getCountOfStatus(status: Status) {\n let count = 0\n\n this.cache.forEach((item) => {\n if (item.status === status) {\n count++\n }\n })\n return count\n }\n\n get files() {\n const files: File[] = []\n this.cache.forEach((item) => {\n files.push(item.file)\n })\n\n return files\n }\n\n get tree() {\n return TreeNode.generate(this.output, { extensions: /\\.ts/ })\n }\n\n generateRootFiles(options: GenerateTreeNodeOptions) {\n const tree = TreeNode.generate(this.output, { extensions: /\\.ts/, ...options })\n\n const fileReducer = (files: File[], item: typeof tree) => {\n if (!item.children) {\n return []\n }\n\n if (item.children?.length > 1) {\n const source = item.children.reduce((source, file) => {\n if (!file) {\n return source\n }\n\n const importPath = file.data.type === 'directory' ? `./${file.data.name}` : `./${file.data.name.replace(/\\.[^.]*$/, '')}`\n\n return `${source}export * from \"${importPath}\";\\n`\n }, '')\n\n files.push({\n path: path.resolve(this.root, item.data.path, 'index.ts'),\n fileName: 'index.ts',\n source,\n })\n } else {\n item.children?.forEach((child) => {\n const importPath = child.data.type === 'directory' ? `./${child.data.name}` : `./${child.data.name.replace(/\\.[^.]*$/, '')}`\n\n files.push({\n path: path.resolve(this.root, item.data.path, 'index.ts'),\n fileName: 'index.ts',\n source: `export * from \"${importPath}\";\\n`,\n })\n })\n }\n\n item.children.forEach((childItem) => {\n fileReducer(files, childItem)\n })\n\n return files\n }\n\n const files = fileReducer([], tree)\n\n return files.map((file) => write(file.source, file.path))\n }\n\n add(file: File) {\n const cacheItem = { id: randomUUID(), file, status: 'new' as Status }\n\n this.cache.set(cacheItem.id, cacheItem)\n this.events.emitFile(cacheItem.id, file)\n\n return new Promise<File>((resolve) => {\n const unsubscribe = this.events.onRemove(cacheItem.id, (file) => {\n resolve(file)\n unsubscribe()\n })\n })\n }\n\n setStatus(id: UUID, status: Status) {\n const cacheItem = this.getCache(id)\n if (!cacheItem) {\n return\n }\n\n cacheItem.status = status\n this.cache.set(id, cacheItem)\n this.events.emitStatusChange(cacheItem.file)\n this.events.emitStatusChangeById(id, status)\n }\n\n get(id: UUID) {\n const cacheItem = this.getCache(id)\n return cacheItem?.file\n }\n\n remove(id: UUID) {\n const cacheItem = this.getCache(id)\n if (!cacheItem) {\n return\n }\n\n this.setStatus(id, 'removed')\n this.events.emitRemove(id, cacheItem.file)\n }\n}\n","import type EventEmitter from 'events'\nimport type { File, Status, UUID } from './types'\n\nconst keys = {\n getFileKey: () => `file`,\n getStatusChangeKey: () => `status-change`,\n getStatusChangeByIdKey: (id: string) => `${id}-status-change`,\n getSuccessKey: () => `success`,\n getRemoveKey: (id: string) => `${id}remove`,\n} as const\n\nexport const getFileManagerEvents = (emitter: EventEmitter) => {\n return {\n /**\n * Emiter\n */\n emitFile: (id: UUID, file: File): void => {\n emitter.emit(keys.getFileKey(), id, file)\n },\n emitStatusChange: (file: File): void => {\n emitter.emit(keys.getStatusChangeKey(), file)\n },\n emitStatusChangeById: (id: UUID, status: Status): void => {\n emitter.emit(keys.getStatusChangeByIdKey(id), status)\n },\n emitSuccess: (): void => {\n emitter.emit(keys.getSuccessKey())\n },\n emitRemove: (id: UUID, file: File): void => {\n emitter.emit(keys.getRemoveKey(id), file)\n },\n /**\n * Listeners\n */\n\n onAdd: (callback: (id: UUID, file: File) => void): VoidFunction => {\n emitter.on(keys.getFileKey(), callback)\n return () => emitter.removeListener(keys.getFileKey(), callback)\n },\n onStatusChange: (callback: (file: File) => void): VoidFunction => {\n emitter.on(keys.getStatusChangeKey(), callback)\n return () => emitter.removeListener(keys.getStatusChangeKey(), callback)\n },\n onStatusChangeById: (id: UUID, callback: (status: Status) => void): VoidFunction => {\n emitter.on(keys.getStatusChangeByIdKey(id), callback)\n return () => emitter.removeListener(keys.getStatusChangeByIdKey(id), callback)\n },\n onSuccess: (callback: () => void): VoidFunction => {\n emitter.on(keys.getSuccessKey(), callback)\n return () => emitter.removeListener(keys.getSuccessKey(), callback)\n },\n onRemove: (id: UUID, callback: (file: File) => void): VoidFunction => {\n emitter.on(keys.getRemoveKey(id), callback)\n return () => emitter.removeListener(keys.getRemoveKey(id), callback)\n },\n }\n}\n","import dirTree from 'directory-tree'\n\nimport type { DirectoryTree } from 'directory-tree'\n\nexport type GenerateTreeNodeOptions = { extensions?: RegExp; exclude?: RegExp[] }\n\nexport class TreeNode<T = unknown> {\n public data: T\n\n public parent?: TreeNode<T>\n\n public children: Array<TreeNode<T>>\n\n constructor(data: T, parent?: TreeNode<T>) {\n this.data = data\n this.parent = parent\n return this\n }\n\n addChild(data: T) {\n const child = new TreeNode(data, this)\n if (!this.children) {\n this.children = []\n }\n this.children.push(child)\n return child\n }\n\n find(data: T) {\n if (data === this.data) {\n return this\n }\n\n if (this.children) {\n for (let i = 0, { length } = this.children, target: any = null; i < length; i++) {\n target = this.children[i].find(data)\n if (target) {\n return target\n }\n }\n }\n\n return null\n }\n\n leaves() {\n if (!this.children || this.children.length === 0) {\n // this is a leaf\n return [this]\n }\n\n // if not a leaf, return all children's leaves recursively\n const leaves = []\n if (this.children) {\n for (let i = 0, { length } = this.children; i < length; i++) {\n // eslint-disable-next-line prefer-spread\n leaves.push.apply(leaves, this.children[i].leaves())\n }\n }\n return leaves\n }\n\n root() {\n if (!this.parent) {\n return this\n }\n return this.parent.root()\n }\n\n forEach(callback: (treeNode: TreeNode<T>) => void) {\n if (typeof callback !== 'function') {\n throw new TypeError('forEach() callback must be a function')\n }\n\n // run this node through function\n callback(this)\n\n // do the same for all children\n if (this.children) {\n for (let i = 0, { length } = this.children; i < length; i++) {\n this.children[i].forEach(callback)\n }\n }\n\n return this\n }\n\n public static generate(path: string, options: GenerateTreeNodeOptions = {}) {\n const filteredTree = dirTree(path, { extensions: options?.extensions, exclude: options.exclude })\n const treeNode = new TreeNode({ name: filteredTree.name, path: filteredTree.path, type: filteredTree.type })\n\n const recurse = (node: typeof treeNode, item: DirectoryTree) => {\n const subNode = node.addChild({ name: item.name, path: item.path, type: item.type })\n\n if (item.children?.length) {\n item.children?.forEach((child) => {\n recurse(subNode, child)\n })\n }\n }\n\n filteredTree.children?.forEach((child) => recurse(treeNode, child))\n\n return treeNode\n }\n}\n","/* eslint-disable no-await-in-loop */\n/* eslint-disable no-restricted-syntax */\n\nimport { definePlugin } from '../../plugin'\nimport { FileManager } from '../fileManager'\n\nimport type { Argument0, Strategy } from './types'\nimport type { KubbConfig, KubbPlugin, PluginLifecycleHooks, PluginLifecycle, MaybePromise, ResolveIdParams } from '../../types'\nimport type { Logger } from '../../build'\nimport type { CorePluginOptions } from '../../plugin'\n\n// inspired by: https://github.com/rollup/rollup/blob/master/src/utils/PluginDriver.ts#\n\n// This will make sure no input hook is omitted\nconst hookNames: {\n [P in PluginLifecycleHooks]: 1\n} = {\n validate: 1,\n buildStart: 1,\n resolveId: 1,\n load: 1,\n transform: 1,\n writeFile: 1,\n buildEnd: 1,\n}\nexport const hooks = Object.keys(hookNames) as [PluginLifecycleHooks]\n\nexport class PluginManager {\n public plugins: KubbPlugin[]\n\n public readonly fileManager: FileManager\n\n private readonly logger?: Logger\n\n private readonly config: KubbConfig\n\n public readonly core: KubbPlugin<CorePluginOptions>\n\n constructor(config: KubbConfig, options: { logger?: Logger }) {\n this.logger = options.logger\n this.config = config\n\n this.fileManager = new FileManager({ root: this.config.root, output: this.config.output.path })\n this.core = definePlugin({\n config,\n fileManager: this.fileManager,\n load: this.load,\n resolveId: this.resolveId,\n }) as KubbPlugin<CorePluginOptions> & {\n api: CorePluginOptions['api']\n }\n this.plugins = [this.core, ...(config.plugins || [])]\n }\n\n resolveId = (params: ResolveIdParams) => {\n if (params.pluginName) {\n return this.hookForPlugin(params.pluginName, 'resolveId', [params.importee, params.importer, params.options])\n }\n return this.hookFirst('resolveId', [params.importee, params.importer, params.options])\n }\n\n load = async (id: string) => {\n return this.hookFirst('load', [id])\n }\n\n // run only hook for a specific plugin name\n hookForPlugin<H extends PluginLifecycleHooks>(\n pluginName: string,\n hookName: H,\n parameters: Parameters<PluginLifecycle[H]>,\n skipped?: ReadonlySet<KubbPlugin> | null\n ): Promise<ReturnType<PluginLifecycle[H]> | null> {\n let promise: Promise<ReturnType<PluginLifecycle[H]> | null> = Promise.resolve(null)\n for (const plugin of this.getSortedPlugins(hookName, pluginName)) {\n if (skipped && skipped.has(plugin)) continue\n promise = promise.then((result) => {\n if (result != null) return result\n return this.run('hookFirst', hookName, parameters, plugin) as any\n })\n }\n return promise\n }\n\n // chains, first non-null result stops and returns\n hookFirst<H extends PluginLifecycleHooks>(\n hookName: H,\n parameters: Parameters<PluginLifecycle[H]>,\n skipped?: ReadonlySet<KubbPlugin> | null\n ): Promise<ReturnType<PluginLifecycle[H]> | null> {\n let promise: Promise<ReturnType<PluginLifecycle[H]> | null> = Promise.resolve(null)\n for (const plugin of this.getSortedPlugins(hookName)) {\n if (skipped && skipped.has(plugin)) continue\n promise = promise.then((result) => {\n if (result != null) return result\n return this.run('hookFirst', hookName, parameters, plugin) as any\n })\n }\n return promise\n }\n\n // parallel\n async hookParallel<H extends PluginLifecycleHooks, TOuput = void>(hookName: H, parameters?: Parameters<PluginLifecycle[H]> | undefined) {\n const parallelPromises: Promise<TOuput>[] = []\n\n for (const plugin of this.getSortedPlugins(hookName)) {\n if ((plugin[hookName] as { sequential?: boolean })?.sequential) {\n await Promise.all(parallelPromises)\n parallelPromises.length = 0\n await this.run('hookParallel', hookName, parameters, plugin)\n } else {\n const promise: Promise<TOuput> = this.run('hookParallel', hookName, parameters, plugin)\n\n parallelPromises.push(promise)\n }\n }\n return Promise.all(parallelPromises)\n }\n\n // chains, reduces returned value, handling the reduced value as the first hook argument\n hookReduceArg0<H extends PluginLifecycleHooks>(\n hookName: H,\n [argument0, ...rest]: Parameters<PluginLifecycle[H]>,\n reduce: (reduction: Argument0<H>, result: ReturnType<PluginLifecycle[H]>, plugin: KubbPlugin) => MaybePromise<Argument0<H> | null>\n ): Promise<Argument0<H>> {\n let promise = Promise.resolve(argument0)\n for (const plugin of this.getSortedPlugins(hookName)) {\n promise = promise.then((argument0) =>\n this.run('hookReduceArg0', hookName, [argument0, ...rest] as Parameters<PluginLifecycle[H]>, plugin).then((result) =>\n reduce.call(this.core.api, argument0, result, plugin)\n )\n )\n }\n return promise\n }\n\n // chains\n\n hookSeq<H extends PluginLifecycleHooks>(hookName: H, parameters?: Parameters<PluginLifecycle[H]>) {\n let promise: Promise<void> = Promise.resolve()\n for (const plugin of this.getSortedPlugins(hookName)) {\n promise = promise.then(() => this.run('hookSeq', hookName, parameters, plugin))\n }\n return promise.then(noReturn)\n }\n\n private getSortedPlugins(hookName: keyof PluginLifecycle, pluginName?: string): KubbPlugin[] {\n const plugins = [...this.plugins]\n\n if (pluginName) {\n const pluginsByPluginName = plugins.filter((item) => item.name === pluginName && item[hookName])\n if (pluginsByPluginName.length === 0) {\n // fallback on the core plugin when there is no match\n if (this.config.logLevel === 'warn' && this.logger?.spinner) {\n this.logger.spinner.info(`Plugin hook with ${hookName} not found for plugin ${pluginName}`)\n }\n return [this.core]\n }\n return pluginsByPluginName\n }\n\n return plugins\n }\n\n /**\n * Run an async plugin hook and return the result.\n * @param hookName Name of the plugin hook. Must be either in `PluginHooks` or `OutputPluginValueHooks`.\n * @param args Arguments passed to the plugin hook.\n * @param plugin The actual pluginObject to run.\n */\n // Implementation signature\n private run<H extends PluginLifecycleHooks, TResult = void>(\n strategy: Strategy,\n hookName: H,\n parameters: unknown[] | undefined,\n plugin: KubbPlugin\n ): Promise<TResult> {\n const hook = plugin[hookName]!\n\n return Promise.resolve().then(() => {\n if (typeof hook !== 'function') {\n return hook\n }\n\n if (this.config.logLevel === 'info' && this.logger?.spinner) {\n this.logger.spinner.text = `[${strategy}] ${hookName}: Excecuting task for plugin ${plugin.name} \\n`\n }\n\n const hookResult = (hook as any).apply(this.core.api, parameters)\n\n if (!hookResult?.then) {\n // short circuit for non-thenables and non-Promises\n if (this.config.logLevel === 'info' && this.logger?.spinner) {\n this.logger.spinner.succeed(`[${strategy}] ${hookName}: Excecuting task for plugin ${plugin.name} \\n`)\n }\n return hookResult\n }\n\n return Promise.resolve(hookResult).then((result) => {\n // action was fulfilled\n if (this.config.logLevel === 'info' && this.logger?.spinner) {\n this.logger.spinner.succeed(`[${strategy}] ${hookName}: Excecuting task for plugin ${plugin.name} \\n`)\n }\n return result\n })\n })\n }\n\n /**\n * Run a sync plugin hook and return the result.\n * @param hookName Name of the plugin hook. Must be in `PluginHooks`.\n * @param args Arguments passed to the plugin hook.\n * @param plugin The acutal plugin\n * @param replaceContext When passed, the plugin context can be overridden.\n */\n private runSync<H extends PluginLifecycleHooks>(hookName: H, parameters: Parameters<PluginLifecycle[H]>, plugin: KubbPlugin): ReturnType<PluginLifecycle[H]> {\n const hook = plugin[hookName]!\n\n // const context = this.pluginContexts.get(plugin)!;\n\n try {\n // eslint-disable-next-line @typescript-eslint/ban-types\n return (hook as Function).apply(this.core.api, parameters)\n } catch (error: any) {\n return error\n }\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-empty-function\nfunction noReturn() {}\n","import type { MaybePromise, KubbUserConfig, CLIOptions } from './types'\n\n/**\n * Type helper to make it easier to use kubb.config.ts\n * accepts a direct {@link KubbConfig} object, or a function that returns it.\n * The function receives a {@link ConfigEnv} object that exposes two properties:\n */\nexport const defineConfig = (\n options:\n | MaybePromise<KubbUserConfig>\n | ((\n /** The options derived from CLI flags */\n cliOptions: CLIOptions\n ) => MaybePromise<KubbUserConfig>)\n) => options\n","/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { build } from './build'\n\nexport * from './config'\nexport * from './build'\nexport { CorePluginOptions, createPlugin } from './plugin'\nexport * from './utils'\nexport * from './types'\nexport * from './managers'\nexport default build\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/build.ts","../src/plugin.ts","../src/utils/isPromise.ts","../src/utils/write.ts","../src/utils/format.ts","../src/utils/cache.ts","../src/utils/read.ts","../src/managers/fileManager/FileManager.ts","../src/managers/fileManager/events.ts","../src/managers/fileManager/TreeNode.ts","../src/managers/pluginManager/PluginManager.ts","../src/config.ts","../src/index.ts"],"names":["fse","pathParser","file","files","source","options","argument0"],"mappings":";AAAA,OAAOA,UAAS;;;ACAhB,OAAOC,iBAAgB;;;ACEhB,IAAM,YAAY,CAAI,WAAkD;AAC7E,SAAO,OAAQ,QAAgB,SAAS;AAC1C;;;ACHA,OAAO,SAAS;;;ACDhB,SAAS,UAAU,sBAAsB;AAIzC,IAAM,gBAAyB;AAAA,EAC7B,UAAU;AAAA,EACV,YAAY;AAAA,EACZ,QAAQ;AAAA,EACR,aAAa;AAAA,EACb,MAAM;AAAA,EACN,iBAAiB;AAAA,EACjB,WAAW;AACb;AACO,IAAM,SAAS,CAAC,SAAiB;AACtC,SAAO,eAAe,MAAM,aAAa;AAC3C;;;ADNO,IAAM,QAAQ,OAAO,MAAc,MAAc,UAAwB,EAAE,QAAQ,MAAM,MAAM;AACpG,QAAM,gBAAgB,QAAQ,SAAS,OAAO,IAAI,IAAI;AAEtD,MAAI;AACF,UAAM,IAAI,KAAK,IAAI;AACnB,UAAM,aAAa,MAAM,IAAI,SAAS,MAAM,EAAE,UAAU,QAAQ,CAAC;AACjE,QAAI,YAAY,SAAS,MAAM,eAAe;AAC5C;AAAA,IACF;AAAA,EACF,SAAS,MAAP;AACA,WAAO,IAAI,WAAW,MAAM,aAAa;AAAA,EAC3C;AAEA,SAAO,IAAI,WAAW,MAAM,aAAa;AAC3C;;;AEbO,SAAS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,eAAe,MAAM,cAAc,UAAU,QAAQ,CAAC,QAAQ,CAAC;AACrE,QAAI,cAAc;AAChB,aAAO;AAAA,IACT;AAEA,QAAI,MAAM;AACR,YAAM,kBAAkB,MAAM,cAAc,eAAe,aAAa,CAAC,MAAM,QAAQ,GAAG,gBAAgB;AAE1G,YAAM,cAAc,aAAa,aAAa,CAAC,iBAAiB,QAAQ,CAAC;AACzE,kBAAY,UAAU,IAAI,SAAS;AACnC,kBAAY,OAAO,EAAE;AAAA,IACvB;AAAA,EACF,CAAC;AAED,QAAM,cAAc,aAAa,cAAc,CAAC,MAAM,CAAC;AACzD;AAEO,SAAS,MAAM,SAA6C;AACjE,SAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACtC,QAAI;AACF,0BAAoB,SAAS,OAAO;AAAA,IACtC,SAAS,GAAP;AACA,aAAO,CAAC;AAAA,IACV;AAAA,EACF,CAAC;AACH;;;AWvFO,IAAM,eAAe,CAC1B,YAMG;;;ACLL,IAAO,cAAQ","sourcesContent":["import fse from 'fs-extra'\n\nimport { PluginManager } from './managers/pluginManager'\n\nimport type { PluginContext, TransformResult, ValidationResult, LogLevel, KubbPlugin } from './types'\n\ntype BuildOutput = void\n\n// Same type as ora\ntype Spinner = {\n start: (text?: string) => Spinner\n succeed: (text: string) => Spinner\n stopAndPersist: (options: { text: string }) => Spinner\n render: () => Spinner\n text: string\n info: (text: string) => Spinner\n}\n\nexport type Logger = {\n log: (message: string, logLevel: LogLevel) => void\n spinner?: Spinner\n}\ntype BuildOptions = {\n config: PluginContext['config']\n mode: 'development' | 'production'\n logger?: Logger\n}\n\nasync function transformReducer(this: PluginContext, _previousCode: string, result: TransformResult, _plugin: KubbPlugin) {\n if (result === null) {\n return null\n }\n return result\n}\n\nasync function buildImplementation(options: BuildOptions, done: (output: BuildOutput) => void) {\n const { config, logger } = options\n\n if (config.output.clean) {\n await fse.remove(config.output.path)\n }\n\n const pluginManager = new PluginManager(config, { logger })\n const { plugins, fileManager } = pluginManager\n\n const validations = await pluginManager.hookParallel<'validate', ValidationResult>('validate', [plugins])\n const validationsWithMessage = validations.filter(Boolean)\n\n if (validationsWithMessage.some((validation) => typeof validation !== 'boolean')) {\n validationsWithMessage.forEach((validation) => {\n if (validation && typeof validation !== 'boolean' && validation?.message) {\n logger?.log(validation.message, 'warn')\n }\n })\n\n return\n }\n\n fileManager.events.onSuccess(async () => {\n await pluginManager.hookParallel('buildEnd')\n setTimeout(() => {\n done()\n }, 1000)\n })\n\n fileManager.events.onAdd(async (id, file) => {\n const { path: filePath } = file\n let { source: code } = file\n\n const loadedResult = await pluginManager.hookFirst('load', [filePath])\n if (loadedResult) {\n code = loadedResult\n }\n\n if (code) {\n const transformedCode = await pluginManager.hookReduceArg0('transform', [code, filePath], transformReducer)\n\n await pluginManager.hookParallel('writeFile', [transformedCode, filePath])\n fileManager.setStatus(id, 'success')\n fileManager.remove(id)\n }\n })\n\n await pluginManager.hookParallel('buildStart', [config])\n}\n\nexport function build(options: BuildOptions): Promise<BuildOutput> {\n return new Promise((resolve, reject) => {\n try {\n buildImplementation(options, resolve)\n } catch (e) {\n reject(e)\n }\n })\n}\n","import pathParser from 'path'\n\nimport { createPluginCache } from './utils'\nimport { FileManager } from './managers/fileManager'\n\nimport type { EmittedFile, File } from './managers/fileManager'\nimport type { PluginContext, KubbPlugin, PluginFactoryOptions } from './types'\n\ntype KubbPluginFactory<T extends PluginFactoryOptions = PluginFactoryOptions> = (\n options: T['options']\n) => T['nested'] extends true ? Array<KubbPlugin<T>> : KubbPlugin<T>\n\nexport function createPlugin<T extends PluginFactoryOptions = PluginFactoryOptions>(factory: KubbPluginFactory<T>) {\n return (options: T['options']) => {\n const plugin = factory(options)\n if (Array.isArray(plugin)) {\n throw new Error('Not implemented')\n }\n\n // default transform\n if (!plugin.transform) {\n plugin.transform = function transform(code) {\n return code\n }\n }\n\n return plugin\n }\n}\n\ntype Options = {\n config: PluginContext['config']\n fileManager: FileManager\n resolveId: PluginContext['resolveId']\n load: PluginContext['load']\n}\n\n// not publicly exported\nexport type CorePluginOptions = PluginFactoryOptions<Options, false, PluginContext>\n\nexport const name = 'core' as const\n\nconst isEmittedFile = (result: EmittedFile | File): result is EmittedFile => {\n return !!(result as any).id\n}\n\nexport const definePlugin = createPlugin<CorePluginOptions>((options) => {\n const { fileManager, resolveId, load } = options\n const indexFiles: File[] = []\n\n const api: PluginContext = {\n get config() {\n return options.config\n },\n fileManager,\n async addFile(file, options) {\n if (isEmittedFile(file)) {\n const resolvedId = await resolveId({ fileName: file.id, directory: file.importer, options: file.options })\n const path = resolvedId || file.importer || file.id\n\n return fileManager.add({\n path,\n fileName: file.name || file.id,\n source: file.source || '',\n })\n }\n\n if (options?.root) {\n indexFiles.push(file)\n }\n\n return fileManager.add(file)\n },\n resolveId,\n load,\n cache: createPluginCache(Object.create(null)),\n }\n\n return {\n name,\n api,\n async buildEnd() {\n await FileManager.writeIndexes(this.config.root, this.config.output.path, { exclude: [/schemas/, /json/] })\n },\n resolveId(fileName, directory) {\n if (!directory) {\n return null\n }\n return pathParser.resolve(directory, fileName)\n },\n }\n})\n","import type { MaybePromise } from '../types'\n\nexport const isPromise = <T>(result: MaybePromise<T>): result is Promise<T> => {\n return typeof (result as any)?.then === 'function'\n}\n","/* eslint-disable consistent-return */\nimport fse from 'fs-extra'\n\nimport { format } from './format'\n\ntype WriteOptions = {\n format: boolean\n}\n\nexport const write = async (data: string, path: string, options: WriteOptions = { format: false }) => {\n const formattedData = options.format ? format(data) : data\n\n try {\n await fse.stat(path)\n const oldContent = await fse.readFile(path, { encoding: 'utf-8' })\n if (oldContent?.toString() === formattedData) {\n return\n }\n } catch (_err) {\n return fse.outputFile(path, formattedData)\n }\n\n return fse.outputFile(path, formattedData)\n}\n","import { format as prettierFormat } from 'prettier'\n\nimport type { Options } from 'prettier'\n\nconst formatOptions: Options = {\n tabWidth: 2,\n printWidth: 160,\n parser: 'typescript',\n singleQuote: true,\n semi: false,\n bracketSameLine: false,\n endOfLine: 'auto',\n}\nexport const format = (text: string) => {\n return prettierFormat(text, formatOptions)\n}\n","/* eslint-disable no-param-reassign */\n/* eslint-disable consistent-return */\n\nexport interface Cache<TCache = any> {\n delete(id: string): boolean\n get<T = TCache>(id: string): T\n has(id: string): boolean\n set<T = TCache>(id: string, value: T): void\n}\n\nexport function createPluginCache(cache: any): Cache {\n return {\n delete(id: string) {\n return delete cache[id]\n },\n get(id: string) {\n const item = cache[id]\n if (!item) return\n item[0] = 0\n return item[1]\n },\n has(id: string) {\n const item = cache[id]\n if (!item) return false\n item[0] = 0\n return true\n },\n set(id: string, value: any) {\n cache[id] = [0, value]\n },\n }\n}\n","import pathParser from 'path'\n\n// TODO check for a better way or resolving the relative path\nexport const getRelativePath = (root?: string | null, file?: string | null) => {\n if (!root || !file) {\n throw new Error('Root and file should be filled in when retrieving the relativePath')\n }\n const newPath = pathParser.relative(root, file).replace('../', '').replace('.ts', '').trimEnd()\n\n return `./${newPath}`\n}\n","import EventEmitter from 'events'\nimport { randomUUID } from 'crypto'\nimport pathParser from 'path'\n\nimport { getFileManagerEvents } from './events'\nimport { TreeNode } from './TreeNode'\n\nimport { write } from '../../utils/write'\n\nimport type { CacheStore, UUID, Status, File } from './types'\n\nexport class FileManager {\n private cache: Map<CacheStore['id'], CacheStore> = new Map()\n\n emitter = new EventEmitter()\n\n events = getFileManagerEvents(this.emitter)\n\n constructor() {\n this.events.onStatusChange(() => {\n if (this.getCountOfStatus('removed') === this.cache.size) {\n // all files are been resolved and written to the file system\n this.events.emitSuccess()\n }\n })\n }\n\n private getCache(id: UUID) {\n return this.cache.get(id)\n }\n\n private getCountOfStatus(status: Status) {\n let count = 0\n\n this.cache.forEach((item) => {\n if (item.status === status) {\n count++\n }\n })\n return count\n }\n\n get files() {\n const files: File[] = []\n this.cache.forEach((item) => {\n files.push(item.file)\n })\n\n return files\n }\n\n add(file: File) {\n const cacheItem = { id: randomUUID(), file, status: 'new' as Status }\n\n this.cache.set(cacheItem.id, cacheItem)\n this.events.emitFile(cacheItem.id, file)\n\n return new Promise<File>((resolve) => {\n const unsubscribe = this.events.onRemove(cacheItem.id, (file) => {\n resolve(file)\n unsubscribe()\n })\n })\n }\n\n setStatus(id: UUID, status: Status) {\n const cacheItem = this.getCache(id)\n if (!cacheItem) {\n return\n }\n\n cacheItem.status = status\n this.cache.set(id, cacheItem)\n this.events.emitStatusChange(cacheItem.file)\n this.events.emitStatusChangeById(id, status)\n }\n\n get(id: UUID) {\n const cacheItem = this.getCache(id)\n return cacheItem?.file\n }\n\n remove(id: UUID) {\n const cacheItem = this.getCache(id)\n if (!cacheItem) {\n return\n }\n\n this.setStatus(id, 'removed')\n this.events.emitRemove(id, cacheItem.file)\n }\n\n public static writeIndexes(root: string, output: string, options: Parameters<typeof TreeNode.generate>[1]) {\n const tree = TreeNode.generate(output, { extensions: /\\.ts/, ...options })\n\n const fileReducer = (files: File[], item: typeof tree) => {\n if (!item.children) {\n return []\n }\n\n if (item.children?.length > 1) {\n const source = item.children.reduce((source, file) => {\n if (!file) {\n return source\n }\n\n const importPath = file.data.type === 'directory' ? `./${file.data.name}` : `./${file.data.name.replace(/\\.[^.]*$/, '')}`\n\n return `${source}export * from \"${importPath}\";\\n`\n }, '')\n\n files.push({\n path: pathParser.resolve(root, item.data.path, 'index.ts'),\n fileName: 'index.ts',\n source,\n })\n } else {\n item.children?.forEach((child) => {\n const importPath = child.data.type === 'directory' ? `./${child.data.name}` : `./${child.data.name.replace(/\\.[^.]*$/, '')}`\n\n files.push({\n path: pathParser.resolve(root, item.data.path, 'index.ts'),\n fileName: 'index.ts',\n source: `export * from \"${importPath}\";\\n`,\n })\n })\n }\n\n item.children.forEach((childItem) => {\n fileReducer(files, childItem)\n })\n\n return files\n }\n\n const files = fileReducer([], tree)\n\n return files.map((file) => write(file.source, file.path))\n }\n}\n","import type EventEmitter from 'events'\nimport type { File, Status, UUID } from './types'\n\nconst keys = {\n getFileKey: () => `file`,\n getStatusChangeKey: () => `status-change`,\n getStatusChangeByIdKey: (id: string) => `${id}-status-change`,\n getSuccessKey: () => `success`,\n getRemoveKey: (id: string) => `${id}remove`,\n} as const\n\ntype VoidFunction = () => void\n\nexport const getFileManagerEvents = (emitter: EventEmitter) => {\n return {\n /**\n * Emiter\n */\n emitFile: (id: UUID, file: File): void => {\n emitter.emit(keys.getFileKey(), id, file)\n },\n emitStatusChange: (file: File): void => {\n emitter.emit(keys.getStatusChangeKey(), file)\n },\n emitStatusChangeById: (id: UUID, status: Status): void => {\n emitter.emit(keys.getStatusChangeByIdKey(id), status)\n },\n emitSuccess: (): void => {\n emitter.emit(keys.getSuccessKey())\n },\n emitRemove: (id: UUID, file: File): void => {\n emitter.emit(keys.getRemoveKey(id), file)\n },\n /**\n * Listeners\n */\n\n onAdd: (callback: (id: UUID, file: File) => void): VoidFunction => {\n emitter.on(keys.getFileKey(), callback)\n return () => emitter.removeListener(keys.getFileKey(), callback)\n },\n onStatusChange: (callback: (file: File) => void): VoidFunction => {\n emitter.on(keys.getStatusChangeKey(), callback)\n return () => emitter.removeListener(keys.getStatusChangeKey(), callback)\n },\n onStatusChangeById: (id: UUID, callback: (status: Status) => void): VoidFunction => {\n emitter.on(keys.getStatusChangeByIdKey(id), callback)\n return () => emitter.removeListener(keys.getStatusChangeByIdKey(id), callback)\n },\n onSuccess: (callback: () => void): VoidFunction => {\n emitter.on(keys.getSuccessKey(), callback)\n return () => emitter.removeListener(keys.getSuccessKey(), callback)\n },\n onRemove: (id: UUID, callback: (file: File) => void): VoidFunction => {\n emitter.on(keys.getRemoveKey(id), callback)\n return () => emitter.removeListener(keys.getRemoveKey(id), callback)\n },\n }\n}\n","import dirTree from 'directory-tree'\n\nimport type { DirectoryTree, DirectoryTreeOptions } from 'directory-tree'\n\nexport class TreeNode<T = unknown> {\n public data: T\n\n public parent?: TreeNode<T>\n\n public children: Array<TreeNode<T>>\n\n constructor(data: T, parent?: TreeNode<T>) {\n this.data = data\n this.parent = parent\n return this\n }\n\n addChild(data: T) {\n const child = new TreeNode(data, this)\n if (!this.children) {\n this.children = []\n }\n this.children.push(child)\n return child\n }\n\n find(data: T) {\n if (data === this.data) {\n return this\n }\n\n if (this.children) {\n for (let i = 0, { length } = this.children, target: any = null; i < length; i++) {\n target = this.children[i].find(data)\n if (target) {\n return target\n }\n }\n }\n\n return null\n }\n\n leaves() {\n if (!this.children || this.children.length === 0) {\n // this is a leaf\n return [this]\n }\n\n // if not a leaf, return all children's leaves recursively\n const leaves = []\n if (this.children) {\n for (let i = 0, { length } = this.children; i < length; i++) {\n // eslint-disable-next-line prefer-spread\n leaves.push.apply(leaves, this.children[i].leaves())\n }\n }\n return leaves\n }\n\n root() {\n if (!this.parent) {\n return this\n }\n return this.parent.root()\n }\n\n forEach(callback: (treeNode: TreeNode<T>) => void) {\n if (typeof callback !== 'function') {\n throw new TypeError('forEach() callback must be a function')\n }\n\n // run this node through function\n callback(this)\n\n // do the same for all children\n if (this.children) {\n for (let i = 0, { length } = this.children; i < length; i++) {\n this.children[i].forEach(callback)\n }\n }\n\n return this\n }\n\n public static generate(path: string, options: DirectoryTreeOptions = {}) {\n const filteredTree = dirTree(path, { extensions: options?.extensions, exclude: options.exclude })\n const treeNode = new TreeNode({ name: filteredTree.name, path: filteredTree.path, type: filteredTree.type })\n\n const recurse = (node: typeof treeNode, item: DirectoryTree) => {\n const subNode = node.addChild({ name: item.name, path: item.path, type: item.type })\n\n if (item.children?.length) {\n item.children?.forEach((child) => {\n recurse(subNode, child)\n })\n }\n }\n\n filteredTree.children?.forEach((child) => recurse(treeNode, child))\n\n return treeNode\n }\n}\n","/* eslint-disable no-await-in-loop */\n/* eslint-disable no-restricted-syntax */\n\nimport { definePlugin } from '../../plugin'\nimport { FileManager } from '../fileManager'\n\nimport type { Argument0, Strategy } from './types'\nimport type { KubbConfig, KubbPlugin, PluginLifecycleHooks, PluginLifecycle, MaybePromise, ResolveIdParams } from '../../types'\nimport type { Logger } from '../../build'\nimport type { CorePluginOptions } from '../../plugin'\n\n// inspired by: https://github.com/rollup/rollup/blob/master/src/utils/PluginDriver.ts#\n\n// This will make sure no input hook is omitted\nconst hookNames: {\n [P in PluginLifecycleHooks]: 1\n} = {\n validate: 1,\n buildStart: 1,\n resolveId: 1,\n load: 1,\n transform: 1,\n writeFile: 1,\n buildEnd: 1,\n}\nexport const hooks = Object.keys(hookNames) as [PluginLifecycleHooks]\n\nexport class PluginManager {\n public plugins: KubbPlugin[]\n\n public readonly fileManager: FileManager\n\n private readonly logger?: Logger\n\n private readonly config: KubbConfig\n\n public readonly core: KubbPlugin<CorePluginOptions>\n\n constructor(config: KubbConfig, options: { logger?: Logger }) {\n this.logger = options.logger\n this.config = config\n\n this.fileManager = new FileManager()\n this.core = definePlugin({\n config,\n fileManager: this.fileManager,\n load: this.load,\n resolveId: this.resolveId,\n }) as KubbPlugin<CorePluginOptions> & {\n api: CorePluginOptions['api']\n }\n this.plugins = [this.core, ...(config.plugins || [])]\n }\n\n resolveId = (params: ResolveIdParams) => {\n if (params.pluginName) {\n return this.hookForPlugin(params.pluginName, 'resolveId', [params.fileName, params.directory, params.options])\n }\n return this.hookFirst('resolveId', [params.fileName, params.directory, params.options])\n }\n\n load = async (id: string) => {\n return this.hookFirst('load', [id])\n }\n\n // run only hook for a specific plugin name\n hookForPlugin<H extends PluginLifecycleHooks>(\n pluginName: string,\n hookName: H,\n parameters: Parameters<PluginLifecycle[H]>,\n skipped?: ReadonlySet<KubbPlugin> | null\n ): Promise<ReturnType<PluginLifecycle[H]> | null> {\n let promise: Promise<ReturnType<PluginLifecycle[H]> | null> = Promise.resolve(null)\n for (const plugin of this.getSortedPlugins(hookName, pluginName)) {\n if (skipped && skipped.has(plugin)) continue\n promise = promise.then((result) => {\n if (result != null) return result\n return this.run('hookFirst', hookName, parameters, plugin) as any\n })\n }\n return promise\n }\n\n // chains, first non-null result stops and returns\n hookFirst<H extends PluginLifecycleHooks>(\n hookName: H,\n parameters: Parameters<PluginLifecycle[H]>,\n skipped?: ReadonlySet<KubbPlugin> | null\n ): Promise<ReturnType<PluginLifecycle[H]> | null> {\n let promise: Promise<ReturnType<PluginLifecycle[H]> | null> = Promise.resolve(null)\n for (const plugin of this.getSortedPlugins(hookName)) {\n if (skipped && skipped.has(plugin)) continue\n promise = promise.then((result) => {\n if (result != null) return result\n return this.run('hookFirst', hookName, parameters, plugin) as any\n })\n }\n return promise\n }\n\n // parallel\n async hookParallel<H extends PluginLifecycleHooks, TOuput = void>(hookName: H, parameters?: Parameters<PluginLifecycle[H]> | undefined) {\n const parallelPromises: Promise<TOuput>[] = []\n\n for (const plugin of this.getSortedPlugins(hookName)) {\n if ((plugin[hookName] as { sequential?: boolean })?.sequential) {\n await Promise.all(parallelPromises)\n parallelPromises.length = 0\n await this.run('hookParallel', hookName, parameters, plugin)\n } else {\n const promise: Promise<TOuput> = this.run('hookParallel', hookName, parameters, plugin)\n\n parallelPromises.push(promise)\n }\n }\n return Promise.all(parallelPromises)\n }\n\n // chains, reduces returned value, handling the reduced value as the first hook argument\n hookReduceArg0<H extends PluginLifecycleHooks>(\n hookName: H,\n [argument0, ...rest]: Parameters<PluginLifecycle[H]>,\n reduce: (reduction: Argument0<H>, result: ReturnType<PluginLifecycle[H]>, plugin: KubbPlugin) => MaybePromise<Argument0<H> | null>\n ): Promise<Argument0<H>> {\n let promise = Promise.resolve(argument0)\n for (const plugin of this.getSortedPlugins(hookName)) {\n promise = promise.then((argument0) =>\n this.run('hookReduceArg0', hookName, [argument0, ...rest] as Parameters<PluginLifecycle[H]>, plugin).then((result) =>\n reduce.call(this.core.api, argument0, result, plugin)\n )\n )\n }\n return promise\n }\n\n // chains\n\n hookSeq<H extends PluginLifecycleHooks>(hookName: H, parameters?: Parameters<PluginLifecycle[H]>) {\n let promise: Promise<void> = Promise.resolve()\n for (const plugin of this.getSortedPlugins(hookName)) {\n promise = promise.then(() => this.run('hookSeq', hookName, parameters, plugin))\n }\n return promise.then(noReturn)\n }\n\n private getSortedPlugins(hookName: keyof PluginLifecycle, pluginName?: string): KubbPlugin[] {\n const plugins = [...this.plugins]\n\n if (pluginName) {\n const pluginsByPluginName = plugins.filter((item) => item.name === pluginName && item[hookName])\n if (pluginsByPluginName.length === 0) {\n // fallback on the core plugin when there is no match\n if (this.config.logLevel === 'warn' && this.logger?.spinner) {\n this.logger.spinner.info(`Plugin hook with ${hookName} not found for plugin ${pluginName}`)\n }\n return [this.core]\n }\n return pluginsByPluginName\n }\n\n return plugins\n }\n\n /**\n * Run an async plugin hook and return the result.\n * @param hookName Name of the plugin hook. Must be either in `PluginHooks` or `OutputPluginValueHooks`.\n * @param args Arguments passed to the plugin hook.\n * @param plugin The actual pluginObject to run.\n */\n // Implementation signature\n private run<H extends PluginLifecycleHooks, TResult = void>(\n strategy: Strategy,\n hookName: H,\n parameters: unknown[] | undefined,\n plugin: KubbPlugin\n ): Promise<TResult> {\n const hook = plugin[hookName]!\n\n return Promise.resolve().then(() => {\n if (typeof hook !== 'function') {\n return hook\n }\n\n if (this.config.logLevel === 'info' && this.logger?.spinner) {\n this.logger.spinner.text = `[${strategy}] ${hookName}: Excecuting task for plugin ${plugin.name} \\n`\n }\n\n const hookResult = (hook as any).apply(this.core.api, parameters)\n\n if (!hookResult?.then) {\n // short circuit for non-thenables and non-Promises\n if (this.config.logLevel === 'info' && this.logger?.spinner) {\n this.logger.spinner.succeed(`[${strategy}] ${hookName}: Excecuting task for plugin ${plugin.name} \\n`)\n }\n return hookResult\n }\n\n return Promise.resolve(hookResult).then((result) => {\n // action was fulfilled\n if (this.config.logLevel === 'info' && this.logger?.spinner) {\n this.logger.spinner.succeed(`[${strategy}] ${hookName}: Excecuting task for plugin ${plugin.name} \\n`)\n }\n return result\n })\n })\n }\n\n /**\n * Run a sync plugin hook and return the result.\n * @param hookName Name of the plugin hook. Must be in `PluginHooks`.\n * @param args Arguments passed to the plugin hook.\n * @param plugin The acutal plugin\n * @param replaceContext When passed, the plugin context can be overridden.\n */\n private runSync<H extends PluginLifecycleHooks>(hookName: H, parameters: Parameters<PluginLifecycle[H]>, plugin: KubbPlugin): ReturnType<PluginLifecycle[H]> {\n const hook = plugin[hookName]!\n\n // const context = this.pluginContexts.get(plugin)!;\n\n try {\n // eslint-disable-next-line @typescript-eslint/ban-types\n return (hook as Function).apply(this.core.api, parameters)\n } catch (error: any) {\n return error\n }\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-empty-function\nfunction noReturn() {}\n","import type { MaybePromise, KubbUserConfig, CLIOptions } from './types'\n\n/**\n * Type helper to make it easier to use kubb.config.ts\n * accepts a direct {@link KubbConfig} object, or a function that returns it.\n * The function receives a {@link ConfigEnv} object that exposes two properties:\n */\nexport const defineConfig = (\n options:\n | MaybePromise<KubbUserConfig>\n | ((\n /** The options derived from the CLI flags */\n cliOptions: CLIOptions\n ) => MaybePromise<KubbUserConfig>)\n) => options\n","/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { build } from './build'\n\nexport * from './config'\nexport * from './build'\nexport { CorePluginOptions, createPlugin } from './plugin'\nexport * from './utils'\nexport * from './types'\nexport * from './managers'\nexport default build\n"]}
|