2020-08-09 01:01:34 +00:00
|
|
|
import { InvalidArgumentError, NotFoundError } from '@apextoaster/js-utils';
|
|
|
|
import { safeLoad, Schema, Type as YamlType } from 'js-yaml';
|
2019-11-13 14:01:51 +00:00
|
|
|
|
2020-08-04 05:14:13 +00:00
|
|
|
export interface ReaderOptions {
|
2020-08-09 14:44:11 +00:00
|
|
|
encoding: BufferEncoding;
|
|
|
|
flag?: string;
|
2020-07-29 13:23:37 +00:00
|
|
|
}
|
|
|
|
|
2020-08-04 05:14:13 +00:00
|
|
|
export type IncludeReader = (path: string, options: ReaderOptions) => string;
|
2020-07-09 11:40:08 +00:00
|
|
|
|
2020-08-04 05:14:13 +00:00
|
|
|
export interface IncludeOptions {
|
2020-07-01 00:34:02 +00:00
|
|
|
exists: (path: string) => boolean;
|
2020-08-04 05:14:13 +00:00
|
|
|
join: (...path: Array<string>) => string;
|
2020-07-09 11:40:08 +00:00
|
|
|
read: IncludeReader;
|
2020-07-01 00:34:02 +00:00
|
|
|
resolve: (path: string) => string;
|
2020-06-30 13:08:03 +00:00
|
|
|
schema: Schema;
|
|
|
|
}
|
|
|
|
|
2020-06-29 23:56:08 +00:00
|
|
|
/**
|
2020-08-09 01:01:34 +00:00
|
|
|
* Instantiate an includer with closure over the provided options.
|
2020-08-01 15:57:05 +00:00
|
|
|
* @public
|
2020-06-29 23:56:08 +00:00
|
|
|
*/
|
2020-08-09 14:44:11 +00:00
|
|
|
export function createInclude(options: IncludeOptions) {
|
2020-08-09 01:01:34 +00:00
|
|
|
return new YamlType('!include', {
|
|
|
|
kind: 'scalar',
|
|
|
|
resolve(path: string) {
|
|
|
|
try {
|
2020-08-09 14:44:11 +00:00
|
|
|
const canonical = options.resolve(path);
|
2020-08-09 01:01:34 +00:00
|
|
|
// throws in node 11+
|
2020-08-09 14:44:11 +00:00
|
|
|
if (options.exists(canonical)) {
|
2020-08-09 01:01:34 +00:00
|
|
|
return true;
|
|
|
|
} else {
|
|
|
|
throw new NotFoundError('included file does not exist');
|
|
|
|
}
|
|
|
|
} catch (err) {
|
|
|
|
throw new NotFoundError('included file does not exist', err);
|
2019-11-13 14:01:51 +00:00
|
|
|
}
|
2020-08-09 01:01:34 +00:00
|
|
|
},
|
|
|
|
construct(path: string): unknown {
|
|
|
|
try {
|
2020-08-09 14:44:11 +00:00
|
|
|
const abs = options.resolve(path);
|
|
|
|
return safeLoad(options.read(abs, {
|
2020-08-09 01:01:34 +00:00
|
|
|
encoding: 'utf-8',
|
|
|
|
}), {
|
2020-08-09 14:44:11 +00:00
|
|
|
schema: options.schema,
|
2020-08-09 01:01:34 +00:00
|
|
|
});
|
|
|
|
} catch (err) {
|
|
|
|
throw new InvalidArgumentError('error including file', err);
|
|
|
|
}
|
|
|
|
},
|
|
|
|
});
|
2019-11-13 14:01:51 +00:00
|
|
|
}
|