incode
v0.3.0
Published
Code injection library
Downloads
4
Readme
incode
is a library for building code injectors.
Example
Code with injectable regions:
class User {
// inj:emit("User", "pck")
// inj:end
}
Code injector:
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:
// 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 scopeend
- end regionassign(data: JSON)
- assign data to a local scopeObject.assign
merge(data: JSON)
- merge data to a local scope_.merge
emit(...args: Array<JSON>)
- emit code
API
function createDirectiveMatcher(prefix: string): RegExp;
createDirectiveMatcher
creates a RegExp
object that will be used as a directive matcher.
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
.
function inject(
text: string,
directiveMatcher: RegExp,
cb: (region: InjectableRegion) => string,
data = {},
): string;
inject
invokes cb
function and injects its result into a text.