Commit 623b2f20 authored by David Sveningsson's avatar David Sveningsson

feat(transform): support returning iterators

makes it possible to use generators thus simplifying when chaining transformers
parent 4a6fd516
......@@ -15,7 +15,7 @@ import { Transformer, TransformContext } from "html-validate";
module.exports = function(
this: TransformContext,
source: Source
): Source[] {
): Iterable<Source> {
/* ... */
};
```
......@@ -24,7 +24,7 @@ module.exports = function(
```typescript
export interface TransformContext {
chain(source: Source, filename: string): Source[];
chain(source: Source, filename: string): Iterable<Source>;
}
```
......@@ -34,8 +34,9 @@ Chain transformations. Sometimes multiple transformers must be applied. For
instance, a Markdown file with JSX in a code-block.
```typescript
const source = myTransformation();
return this.chain(source, `${originalFilename}.foo`);
for (const source of myTransformation()) {
yield * this.chain(source, `${originalFilename}.foo`);
}
```
The above snippet will chain transformations using the current transformer
......
......@@ -340,7 +340,7 @@ export class Config {
};
if (transformer) {
try {
return transformer.fn.call(context, source);
return Array.from(transformer.fn.call(context, source));
} catch (err) {
throw new NestedError(
`When transforming "${source.filename}": ${err.message}`,
......
......@@ -4,11 +4,11 @@ import { Transformer, TransformContext } from "..";
/**
* Mock transformer chaining to a .foo file transformer.
*/
module.exports = function mockTransformChainFoo(
module.exports = function* mockTransformChainFoo(
this: TransformContext,
source: Source
) {
return this.chain(
yield* this.chain(
{
data: `data from mock-transform-chain-foo (was: ${source.data})`,
filename: source.filename,
......
......@@ -11,5 +11,5 @@ export interface TransformContext {
* @param filename - Filename to use to match next transformer (unrelated to
* filename set in source)
*/
chain(source: Source, filename: string): Source[];
chain(source: Source, filename: string): Iterable<Source>;
}
......@@ -4,4 +4,7 @@ import { TransformContext } from "./context";
export { TransformContext } from "./context";
export { TemplateExtractor } from "./template";
export type Transformer = (this: TransformContext, source: Source) => Source[];
export type Transformer = (
this: TransformContext,
source: Source
) => Iterable<Source>;
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment