UNPKG

@agent-graph/core

Version:

A lightweight AI Agent orchestration solution

94 lines (93 loc) 3.13 kB
/** ref: https://github.com/dmnd/dedent */ export function dedent(str, options = {}) { const { escapeSpecialCharacters = false } = options; let result = str; if (escapeSpecialCharacters) { // handle escaped newlines, backticks, and interpolation characters result = result .replace(/\\\n[ \t]*/g, '') .replace(/\\`/g, '`') .replace(/\\\$/g, '$') .replace(/\\\{/g, '{'); } // strip indentation const lines = result.split('\n'); let mindent = null; for (const l of lines) { const m = l.match(/^(\s+)\S+/); if (m) { const indent = m[1].length; if (!mindent) { // this is the first indented line mindent = indent; } else { mindent = Math.min(mindent, indent); } } } if (mindent !== null) { const m = mindent; // appease TypeScript result = lines // https://github.com/typescript-eslint/typescript-eslint/issues/7140 // eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with .map((l) => (l[0] === ' ' || l[0] === '\t' ? l.slice(m) : l)) .join('\n'); } // dedent eats leading and trailing whitespace too result = result.trim(); if (escapeSpecialCharacters) { // handle escaped newlines at the end to ensure they don't get stripped too result = result.replace(/\\n/g, '\n'); } return result; } export function inject(template, params) { return template.replace(/{(.*?)}/g, (match, key) => { return key in params ? params[key] : match; }); } export class StringTemplate { constructor(template, options) { this.options = Object.assign({ dedent: true }, options); if (this.options.dedent) { this.template = dedent(template, this.options.dedentOptions); } else { this.template = template; } this.fill = this.fill.bind(this); this.partial = this.partial.bind(this); this.concat = this.concat.bind(this); this.toString = this.toString.bind(this); } fill(params) { return inject(this.template, params); } partial(params) { this.template = inject(this.template, params); return this; } concat(template) { return new StringTemplate(this.template + template.template); } toString() { return this.template; } } export function fromString(t) { return new StringTemplate(t); } const text1 = `hello, {name}! Welcome to {website}!`; const text2 = `I'm from {country}!`; const text3 = `I like {food}!`; const t1 = fromString(text1); const t2 = fromString(text2); const t3 = fromString(text3); const t4 = t1.concat(t2); const t5 = t4.concat(t3); t1.fill({ name: 'world', website: 'google.com' }); t2.fill({ country: 'USA' }); t3.fill({ food: 'pizza' }); t4.fill({ name: 'world', website: 'google', country: 'USA' }); t5.fill({ name: 'world', website: 'google', country: 'USA', food: 'pizza' });