Skip to content

Commit 75afb40

Browse files
authored
Update renderers-core documentation (#861)
1 parent ffb0ada commit 75afb40

File tree

1 file changed

+179
-47
lines changed

1 file changed

+179
-47
lines changed

packages/renderers-core/README.md

Lines changed: 179 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -20,119 +20,251 @@ pnpm install @codama/renderers-core
2020
2121
## Filesystem wrappers
2222

23-
This package offers several helper functions that delegate to the native Filesystem API — i.e. `node:fs` — when using the Node.js runtime. However, in any other environment — such as the browser — these functions will throw a `CODAMA_ERROR__NODE_FILESYSTEM_FUNCTION_UNAVAILABLE` error as a Filesystem API is not available. This enables us to write renderers regardless of the runtime environment.
23+
This package offers several helper functions that delegate to the native Filesystem API — i.e. `node:fs` — when using the Node.js runtime. However, in any other environment — such as the browser — these functions will throw a `CODAMA_ERROR__NODE_FILESYSTEM_FUNCTION_UNAVAILABLE` error as a Filesystem API is not available. This enables us to import renderers regardless of the runtime environment.
2424

25-
```ts
26-
// Reads the UTF-8 content of a file as a JSON object.
27-
const json = readJson<MyJsonDefinition>(filePath);
25+
### `createDirectory`
26+
27+
Creates a directory at the given path, recursively.
2828

29-
// Creates a directory at the given path, recursively.
29+
```ts
3030
createDirectory(newDirectoryPath);
31+
```
32+
33+
### `deleteDirectory`
3134

32-
// Deletes a directory, recursively, if it exists.
35+
Deletes a directory, recursively, if it exists.
36+
37+
```ts
3338
deleteDirectory(directoryPath);
39+
```
3440

35-
// Creates a new file at the given path with the given content.
36-
// Creates its parent directory, recursively, if it does not exist.
41+
### `writeFile`
42+
43+
Creates a new file at the given path with the given content. Creates its parent directory, recursively, if it does not exist.
44+
45+
```ts
3746
writeFile(filePath, content);
3847
```
3948

49+
### `readFile`
50+
51+
Reads the UTF-8 content of a file as a string.
52+
53+
```ts
54+
const content = readFile(filePath);
55+
```
56+
57+
### `readJson`
58+
59+
Reads the UTF-8 content of a file as a JSON object.
60+
61+
```ts
62+
const json = readJson<MyJsonDefinition>(filePath);
63+
```
64+
65+
## Path wrappers
66+
67+
This package also offers several `path` helpers that delegate to the native `node:path` module when using the Node.js runtime but provide a fallback implementation when using any other runtime.
68+
69+
### `joinPath`
70+
71+
Joins multiple path segments into a single path.
72+
73+
```ts
74+
const path = joinPath('path', 'to', 'my', 'file.ts');
75+
```
76+
77+
### `pathDirectory`
78+
79+
Returns the parent directory of a given path.
80+
81+
```ts
82+
const parentPath = pathDirectory(path);
83+
```
84+
85+
## Fragments
86+
87+
The concept of fragments is commonly used in Codama renderers as a way to combine a piece of code with any context that is relevant to that piece of code. For instance, a fragment may include a dependency map that lists all the module imports required by that piece of code.
88+
89+
Since fragments vary from one renderer to another, this package cannot provide a one-size-fits-all `Fragment` type. Instead, it provides some base types and utility functions that can be used to build more specific fragment types.
90+
91+
### `BaseFragment`
92+
93+
The `BaseFragment` type is an object that includes a `content` string. Renderers may extend this type to include any additional context they need.
94+
95+
```ts
96+
type Fragment = BaseFragment & Readonly<{ importMap: ImportMap }>;
97+
```
98+
99+
### `mapFragmentContent`
100+
101+
The `mapFragmentContent` helper can be used to transform the `content` of a fragment while preserving the rest of its context.
102+
103+
```ts
104+
const updatedFragment = mapFragmentContent(fragment, c => `/** This is a fragment. */\n${c}`);
105+
```
106+
107+
### `setFragmentContent`
108+
109+
The `setFragmentContent` helper can be used to replace the `content` of a fragment while preserving the rest of its context.
110+
111+
```ts
112+
const updatedFragment = setFragmentContent(fragment, '[redacted]');
113+
```
114+
115+
### `createFragmentTemplate`
116+
117+
The `createFragmentTemplate` helper can be used to create [tagged template literal](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#tagged_templates) functions. For this, you need to provide a function that can merge multiple fragments together and a function that can identify fragments from other values.
118+
119+
```ts
120+
function fragment(template: TemplateStringsArray, ...items: unknown[]): Fragment {
121+
return createFragmentTemplate(template, items, isFragment, mergeFragments);
122+
}
123+
const apple = fragment`apple`;
124+
const banana = fragment`banana`;
125+
const fruits = fragment`${apple}, ${banana}`;
126+
```
127+
40128
## Render maps
41129

42-
The `RenderMap` class is a utility class that helps manage a collection of files to be rendered. It acts as a middleman between the logic that generates the content and the logic that writes the content to the filesystem. As such, it provides a way to access the generated content outside an environment that supports the Filesystem API — such as the browser. It also helps us write tests about the generated code without having to write it to the filesystem.
130+
This package also provides a `RenderMap` type and a handful of helpers to work with it.
43131

44-
### Adding content to a `RenderMap`
132+
A `RenderMap` is a utility type that helps manage a collection of files to be rendered. It acts as a middleman between the logic that generates the content and the logic that writes the content to the filesystem. As such, it provides a way to access the generated content outside an environment that supports the Filesystem API — such as the browser. It also helps us write tests about the generated code without having to write it to the filesystem.
45133

46-
The add content to a `RenderMap`, you can use the `add` method by providing a path and the content to be written to that path.
134+
### Creating new `RenderMaps`
47135

48-
Note that the path should be **relative to the base directory** that will be provided when writing the `RenderMap` to the filesystem.
136+
You can use the `createRenderMap` function with no arguments to create a new empty `RenderMap`.
49137

50138
```ts
51-
const renderMap = new RenderMap()
52-
.add('programs/token.ts', 'export type TokenProgram = { /* ... */ }')
53-
.add('accounts/mint.ts', 'export type MintAccount = { /* ... */ }')
54-
.add('instructions/transfer.ts', 'export function getTransferInstruction = { /* ... */ }');
139+
const renderMap = createRenderMap();
55140
```
56141

57-
Additionally, you can use the `mergeWith` method to merge multiple `RenderMap` instances together.
142+
You may provide the path and content of a file to create a `RenderMap` with a single file.
58143

59144
```ts
60-
const renderMapA = new RenderMap().add('programs/programA.ts', 'export type ProgramA = { /* ... */ }');
61-
const renderMapB = new RenderMap().add('programs/programB.ts', 'export type ProgramB = { /* ... */ }');
62-
const renderMapC = new RenderMap().mergeWith(renderMapA, renderMapB);
145+
const renderMap = createRenderMap('path/to/file.ts', 'file content');
63146
```
64147

65-
### Removing content from a `RenderMap`
148+
You may also provide an object mapping file paths to their content to create a `RenderMap` with multiple files.
149+
150+
```ts
151+
const renderMap = createRenderMap({
152+
'path/to/file.ts': 'file content',
153+
'path/to/another/file.ts': 'another file content',
154+
});
155+
```
156+
157+
Finally, note that any time a `string` is expected as the content of a file, you may also provide a `BaseFragment` instead. In that case, only the `content` field of the fragment will be used.
158+
159+
```ts
160+
const myFragment: BaseFragment = { content: 'file content' };
161+
162+
// From a single file.
163+
createRenderMap('path/to/file.ts', myFragment);
164+
165+
// From multiple files.
166+
createRenderMap({
167+
'path/to/file.ts': myFragment,
168+
'path/to/another/file.ts': 'another file content',
169+
});
170+
```
66171

67-
To remove files from a `RenderMap`, simply use the `remove` method by providing the relative path of the file to be removed.
172+
Note that when setting paths inside a `RenderMap`, they should be relative to the base directory that will be provided when writing the `RenderMap` to the filesystem. For instance, if we decide to use `src/generated` as the base directory when writing the `RenderMap`, then using a path such as `accounts/mint.ts` will result in the file being written to `src/generated/accounts/mint.ts`.
173+
174+
### Adding content to a `RenderMap`
175+
176+
To add content to a `RenderMap`, you may use the `addToRenderMap` function by providing the path and the content of the file to be added. Note that, here as well, the path should be relative to the base directory that will be provided when writing the `RenderMap` to the filesystem.
68177

69178
```ts
70-
renderMap.remove('programs/token.ts');
179+
const updatedRenderMap = addToRenderMap(renderMap, 'path/to/file.ts', 'file content');
71180
```
72181

73-
### Accessing content from a `RenderMap`
182+
Since `RenderMaps` are immutable, you may want to use the `pipe` function from `@codama/visitors-core` — also available in `codama` — to chain multiple updates together.
183+
184+
```ts
185+
const renderMap = pipe(
186+
createRenderMap(),
187+
m => addToRenderMap(m, 'programs/token.ts', 'export type TokenProgram = { /* ... */ }'),
188+
m => addToRenderMap(m, 'accounts/mint.ts', 'export type MintAccount = { /* ... */ }'),
189+
m => addToRenderMap(m, 'instructions/transfer.ts', 'export function getTransferInstruction = { /* ... */ }'),
190+
);
191+
```
192+
193+
### Merging multiple `RenderMaps`
74194

75-
The `RenderMap` class provides several methods to access the content of the files it manages. The `get` method returns the content of a file from its relative path. If the file does not exist on the `RenderMap`, a `CODAMA_ERROR__VISITORS__RENDER_MAP_KEY_NOT_FOUND` error will be thrown.
195+
You may use the `mergeRenderMaps` helper to combine multiple `RenderMap` instances into a single one. If two `RenderMap` instances contain the same file path, the content from the latter will overwrite the content from the former.
76196

77197
```ts
78-
const content: string = renderMap.get('programs/token.ts');
198+
const renderMapA = createRenderMap('programs/programA.ts', 'export type ProgramA = { /* ... */ }');
199+
const renderMapB = createRenderMap('programs/programB.ts', 'export type ProgramB = { /* ... */ }');
200+
const mergedRenderMap = mergeRenderMaps(renderMapA, renderMapB);
79201
```
80202

81-
To safely access the content of a file without throwing an error, you can use the `safeGet` method. This method returns the content of a file from its relative path, or `undefined` if the file does not exist.
203+
### Removing content from a `RenderMap`
204+
205+
To remove files from a `RenderMap`, simply use the `removeFromRenderMap` function by providing the relative path of the file to be removed.
82206

83207
```ts
84-
const content: string | undefined = renderMap.safeGet('programs/token.ts');
208+
const updatedRenderMap = removeFromRenderMap(renderMap, 'programs/token.ts');
85209
```
86210

87-
The `has` and `isEmpty` methods can also be used to verify the existence of files in the `RenderMap`.
211+
### Accessing content from a `RenderMap`
212+
213+
The `RenderMap` type is essentially a JavaScript `Map` so you can use all the methods available on the `Map` prototype. Therefore, you may use the `get` method to access the content of a file from its relative path.
88214

89215
```ts
90-
const hasTokenProgram = renderMap.has('programs/token.ts');
91-
const hasNoFiles = renderMap.isEmpty();
216+
const content: string | undefined = renderMap.get('programs/token.ts');
92217
```
93218

94-
Finally, the `contains` method can be used to check if a file contains a specific string or matches a regular expression.
219+
However, this may return `undefined` if the file does not exist on the `RenderMap`. If you want to access the content of a file and throw an error if it does not exist, you can use the `getFromRenderMap` helper instead.
95220

96221
```ts
97-
const hasTokenProgram = renderMap.contains('programs/token.ts', 'export type TokenProgram = { /* ... */ }');
98-
const hasMintAccount = renderMap.contains('programs/token.ts', /MintAccount/);
222+
const content: string = getFromRenderMap(renderMap, 'programs/token.ts');
99223
```
100224

101-
### Tranforming content from a `RenderMap`
225+
You may also use the `renderMapContains` helper to check if the provided file content exists in the `RenderMap` at the given path. The expected file content can be a string or a regular expression.
102226

103-
To map the content of files inside a `RenderMap`, you can use the `mapContent` method. This method accepts a function that takes the content of a file and returns a new content.
227+
```ts
228+
const hasTokenProgram = renderMapContains(renderMap, 'programs/token.ts', 'export type TokenProgram = { /* ... */ }');
229+
const hasMintAccount = renderMapContains(renderMap, 'programs/token.ts', /MintAccount/);
230+
```
231+
232+
### Transforming content from a `RenderMap`
233+
234+
To map the content of all files inside a `RenderMap`, you can use the `mapRenderMapContent` function. This method accepts a function that takes the content of a file and returns a new content.
104235

105236
```ts
106-
renderMap.mapContent(content => `/** Prefix for all files */\n\n${content}`);
237+
const updatedRenderMap = mapRenderMapContent(renderMap, c => `/** Prefix for all files */\n\n${c}`);
107238
```
108239

109-
An asynchronous version of this method called `mapContentAsync` is also available in case the transformation function needs to be asynchronous.
240+
An asynchronous version of this function called `mapRenderMapContentAsync` is also available in case the transformation function needs to be asynchronous.
110241

111242
```ts
112-
await renderMap.mapContentAsync(async content => {
243+
const updatedRenderMap = await mapRenderMapContentAsync(renderMap, async content => {
113244
const transformedContent = await someAsyncFunction(content);
114245
return `/** Prefix for all files */\n\n${transformedContent}`;
115246
});
116247
```
117248

118249
### Writing a `RenderMap` to the filesystem
119250

120-
When the `RenderMap` is ready to be written to the filesystem, you can use the `write` method by providing the base directory where all files should be written. Any relative path provided by the `add` method will be appended to this base directory.
251+
When the `RenderMap` is ready to be written to the filesystem, you can use the `writeRenderMap` helper by providing the base directory where all files should be written. All paths inside the `RenderMap` will be appended to this base directory.
121252

122253
```ts
123-
const renderMap = new RenderMap()
124-
.add('programs/token.ts', 'export type TokenProgram = { /* ... */ }')
125-
.add('accounts/mint.ts', 'export type MintAccount = { /* ... */ }');
254+
const renderMap = createRenderMap({
255+
'programs/token.ts': 'export type TokenProgram = { /* ... */ }',
256+
'accounts/mint.ts': 'export type MintAccount = { /* ... */ }',
257+
});
126258

127-
renderMap.write('src/generated');
259+
writeRenderMap(renderMap, 'src/generated');
128260
// In this example, files will be written to:
129261
// - src/generated/programs/token.ts
130262
// - src/generated/accounts/mint.ts.
131263
```
132264

133265
### Using visitors
134266

135-
When building renderers, you will most likely create a visitor that traverses the Codama IDL and returns a `RenderMap`. That way, you can test the generated content without having to write it to the filesystem. For instance, the [`@codama/renderers-js`](../renderers-js) package exports a `getRenderMapVisitor` function that does just that.
267+
When building renderers, you will most likely create a visitor that traverses the Codama IDL and returns a `RenderMap`. That way, you can test the generated content without having to write it to the filesystem. For instance, the [`@codama/renderers-js`](https://github.com/codama-idl/renderers-js) package exports a `getRenderMapVisitor` function that does just that.
136268

137269
```ts
138270
import { getRenderMapVisitor } from '@codama/renderers-js';
@@ -150,10 +282,10 @@ codama.accept(writeRenderMapVisitor(getRenderMapVisitor(), 'src/generated'));
150282

151283
Note however that, if you are writing your own renderer, you should probably offer a higher-level visitor that includes this logic and also does some additional work such as deleting the base directory before writing the new content if it already exists.
152284

153-
For instance, the recommended way of using the `@codama/renderers-js` package is to use the following `renderVisitor` function.
285+
For instance, the recommended way of using the `@codama/renderers-js` package is to use its default exported visitor which does exactly that.
154286

155287
```ts
156-
import { renderVisitor } from '@codama/renderers-js';
288+
import renderVisitor from '@codama/renderers-js';
157289

158290
codama.accept(renderVisitor('src/generated'));
159291
```

0 commit comments

Comments
 (0)