2020-03-29 13:13:57 +00:00
|
|
|
import { InvalidArgumentError, NotFoundError } from '@apextoaster/js-utils';
|
2020-06-30 13:08:03 +00:00
|
|
|
import { SAFE_SCHEMA, safeLoad, Schema, Type as YamlType } from 'js-yaml';
|
2019-11-13 14:01:51 +00:00
|
|
|
import { join } from 'path';
|
|
|
|
|
2020-07-09 11:40:08 +00:00
|
|
|
export type IncludeReader = (path: string, options: { encoding: string }) => string;
|
|
|
|
|
2020-06-30 13:08:03 +00:00
|
|
|
export interface IncludeSchema {
|
2020-07-01 00:34:02 +00:00
|
|
|
exists: (path: string) => boolean;
|
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
|
|
|
/**
|
|
|
|
* The schema to be used for included files. This is necessary to work around circular dependency errors.
|
|
|
|
*/
|
2020-06-30 13:08:03 +00:00
|
|
|
export const includeSchema: IncludeSchema = {
|
|
|
|
exists: (path: string) => false,
|
|
|
|
read: (path: string, encoding: object) => {
|
|
|
|
throw new Error('read stub');
|
|
|
|
},
|
|
|
|
resolve: (path: string) => {
|
|
|
|
throw new Error('resolve stub');
|
|
|
|
},
|
2019-11-13 14:01:51 +00:00
|
|
|
schema: SAFE_SCHEMA,
|
|
|
|
};
|
|
|
|
|
|
|
|
export const includeType = new YamlType('!include', {
|
|
|
|
kind: 'scalar',
|
|
|
|
resolve(path: string) {
|
|
|
|
try {
|
|
|
|
const canonical = resolvePath(path);
|
|
|
|
// throws in node 11+
|
2020-06-30 13:08:03 +00:00
|
|
|
if (includeSchema.exists(canonical)) {
|
2019-11-13 14:01:51 +00:00
|
|
|
return true;
|
|
|
|
} else {
|
|
|
|
throw new NotFoundError('included file does not exist');
|
|
|
|
}
|
|
|
|
} catch (err) {
|
|
|
|
throw new NotFoundError('included file does not exist', err);
|
|
|
|
}
|
|
|
|
},
|
|
|
|
construct(path: string): unknown {
|
|
|
|
try {
|
2020-06-30 13:08:03 +00:00
|
|
|
return safeLoad(includeSchema.read(resolvePath(path), {
|
2019-11-13 14:01:51 +00:00
|
|
|
encoding: 'utf-8',
|
|
|
|
}), {
|
|
|
|
schema: includeSchema.schema,
|
|
|
|
});
|
|
|
|
} catch (err) {
|
2019-11-13 14:20:34 +00:00
|
|
|
throw new InvalidArgumentError('error including file', err);
|
2019-11-13 14:01:51 +00:00
|
|
|
}
|
|
|
|
},
|
|
|
|
});
|
|
|
|
|
|
|
|
export function resolvePath(path: string): string {
|
|
|
|
if (path[0] === '.') {
|
2020-06-30 13:08:03 +00:00
|
|
|
return includeSchema.resolve(join(__dirname, path));
|
2019-11-13 14:01:51 +00:00
|
|
|
} else {
|
2020-06-30 13:08:03 +00:00
|
|
|
return includeSchema.resolve(path);
|
2019-11-13 14:01:51 +00:00
|
|
|
}
|
|
|
|
}
|