https://github.com/localvoid/incode
:syringe: Code injector
https://github.com/localvoid/incode
codegen injector
Last synced: 12 months ago
JSON representation
:syringe: Code injector
- Host: GitHub
- URL: https://github.com/localvoid/incode
- Owner: localvoid
- License: mit
- Created: 2017-10-24T06:28:15.000Z (over 8 years ago)
- Default Branch: master
- Last Pushed: 2018-05-18T14:47:08.000Z (about 8 years ago)
- Last Synced: 2025-01-25T06:25:20.047Z (over 1 year ago)
- Topics: codegen, injector
- Language: TypeScript
- Homepage:
- Size: 67.4 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# [incode](https://github.com/localvoid/incode) · [](https://github.com/localvoid/incode/blob/master/LICENSE) [](https://www.npmjs.com/package/incode) [](https://codecov.io/gh/localvoid/incode) [](https://circleci.com/gh/localvoid/incode) [](https://github.com/localvoid/incode)
`incode` is a library for building code injectors.
## Example
Code with injectable regions:
```js
class User {
// inj:emit("User", "pck")
// inj:end
}
```
Code injector:
```js
import { createDirectiveMatcher, inject } from "incode";
const s = inject(
text, // code with injectable regions
createDirectiveMatcher("inj"),
(region) => {
return `${region.args[1]}() { console.log("${region.args[0]} injected method"); }`;
},
);
```
Result after injection:
```js
// inj:assign({ schema: "User" })
class User {
// inj:emit("pck")
pck() { console.log("User injected method"); }
// inj:end
}
```
## Features
- Block-scoped variables
- Indentation autodection for injectable regions
- Automatic removal of existing code in injectable regions
## Directives
- `begin` - begin local scope
- `end` - end region
- `assign(data: JSON)` - assign data to a local scope `Object.assign`
- `merge(data: JSON)` - merge data to a local scope `_.merge`
- `emit(...args: Array)` - emit code
## API
```ts
function createDirectiveMatcher(prefix: string): RegExp;
```
`createDirectiveMatcher` creates a `RegExp` object that will be used as a directive matcher.
```ts
interface InjectableRegion {
readonly args: any[];
readonly data: {};
readonly padding: string;
readonly start: number;
readonly end: number;
}
function extractRegions(
text: string,
directiveMatcher: RegExp,
data = {},
): InjectableRegion[];
```
`extractRegions` extracts `InjectableRegions` from `text`.
```ts
function inject(
text: string,
directiveMatcher: RegExp,
cb: (region: InjectableRegion) => string,
data = {},
): string;
```
`inject` invokes `cb` function and injects its result into a text.