chalk#bold TypeScript Examples
The following examples show how to use
chalk#bold.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.ts From yfm-transform with MIT License | 7 votes |
nestedCloseTokenIdxFactory =
(tokenName: string, matchOpenToken: MatchTokenFunction, matchCloseToken: MatchTokenFunction) =>
(tokens: Token[], idx: number, path: string, log: Logger) => {
let level = 0;
let i = idx;
while (i < tokens.length) {
if (matchOpenToken(tokens, i)) {
level++;
} else if (matchCloseToken(tokens, i)) {
if (level === 0) {
return i;
}
level--;
}
i++;
}
log.error(`${tokenName} must be closed${path ? ` in ${bold(path)}` : ''}`);
return null;
}
Example #2
Source File: index.ts From yfm-transform with MIT License | 6 votes |
addTitle = (options: Options) => {
const {hash, file, state, opts, isEmptyLink, tokens, idx, nextToken, href, currentPath, log} =
options;
const id = hash && hash.slice(1);
const fileTokens = getFileTokens(file, state, {
...opts,
disableLint: true,
disableTitleRefSubstitution: true,
disableCircularError: true,
inheritVars: false,
});
const sourceTokens = id ? findBlockTokens(fileTokens, id) : fileTokens;
const title = getTitleFromTokens(sourceTokens);
if (title) {
let textToken;
if (isEmptyLink) {
textToken = new state.Token('text', '', 0);
tokens.splice(idx + 1, 0, textToken);
} else {
textToken = nextToken;
}
textToken.content = title;
} else {
log.warn(`Title not found: ${bold(href)} in ${bold(currentPath)}`);
}
}
Example #3
Source File: index.ts From yfm-transform with MIT License | 6 votes |
index: MarkdownItPluginCb<Options> = (md, options) => {
const {path: optPath, log} = options;
const plugin = (state: StateCore) => {
const {env} = state;
const path = env.path || optPath;
env.includes = env.includes || [];
const isCircularInclude = env.includes.includes(path);
if (isCircularInclude && state.env.disableCircularError) {
return;
}
if (isCircularInclude) {
log.error(`Circular includes: ${bold(env.includes.concat(path).join(' ▶ '))}`);
process.exit(1);
}
env.includes.push(path);
unfoldIncludes(state, path, options);
env.includes.pop();
};
try {
md.core.ruler.before('curly_attributes', 'includes', plugin);
} catch (e) {
md.core.ruler.push('includes', plugin);
}
}
Example #4
Source File: create.ts From cli with Apache License 2.0 | 6 votes |
private async generateEndMessageFromOrgId(orgId: string) {
const {flags} = await this.parse(Create);
const color1 = bold.cyan;
let color2 = bold.magenta;
if (flags.setDefaultOrganization) {
this.configuration.set('organization', orgId);
color2 = bold.cyan;
}
const cfg = this.configuration.get();
const message = dedent`Organization ${color1(orgId)} successfully created.
You are currently logged into organization ${color2(
cfg.organization
)} and further command will be ran against that organization by default.
If you wish to switch organization use \`coveo config:set\`.
To see current configuration use \`coveo config:get\``;
return message;
}
Example #5
Source File: pull.ts From cli with Apache License 2.0 | 6 votes |
private async getSnapshot() {
const flags = await this.getFlags();
const target = await this.getTargetOrg();
if (flags.snapshotId) {
CliUx.ux.action.start('Retrieving Snapshot');
const waitOption = await this.getWaitOption();
return SnapshotFactory.createFromExistingSnapshot(
flags.snapshotId,
target,
waitOption
);
}
const resourcesToExport = await this.getResourceSnapshotTypesToExport();
CliUx.ux.action.start(`Creating Snapshot from ${bold.cyan(target)}`);
const waitOption = await this.getWaitOption();
return SnapshotFactory.createFromOrg(resourcesToExport, target, waitOption);
}
Example #6
Source File: pull.ts From cli with Apache License 2.0 | 6 votes |
private async getResourceSnapshotTypesToExport(): Promise<SnapshotPullModelResources> {
const flags = await this.getFlags();
if (flags.model) {
const cfg = this.configuration.get();
if (cfg.organization !== flags.model.orgId) {
const question = dedent`You are currently connected to the ${bold.cyan(
cfg.organization
)} organization, but are about to pull resources from the ${bold.cyan(
flags.model.orgId
)} organization.
Do you wish to continue? (y/n)`;
const pull = await confirmWithAnalytics(question, 'resource pull');
if (!pull) {
throw new ProcessAbort();
}
}
return flags.model.resourcesToExport;
} else {
return buildResourcesToExport(flags.resourceTypes);
}
}
Example #7
Source File: push.ts From cli with Apache License 2.0 | 6 votes |
private async applySnapshot(snapshot: Snapshot) {
CliUx.ux.action.start('Applying snapshot');
const cfg = this.configuration.get();
const {flags} = await this.parse(Push);
const {waitUntilDone} = await this.getOptions();
const reporter = await snapshot.apply(
flags.deleteMissingResources,
waitUntilDone
);
await reporter
.setReportHandler(SnapshotReportStatus.ERROR, async () => {
await handleReportWithErrors(snapshot, cfg, this.projectPath);
CliUx.ux.action.stop(red.bold('!'));
})
.setReportHandler(SnapshotReportStatus.SUCCESS, () => {
CliUx.ux.action.stop(green('✔'));
})
.handleReport();
}
Example #8
Source File: add.ts From cli with Apache License 2.0 | 6 votes |
fullUploadDescription = `Controls the way your items are added to your catalog source.
Setting this option to ${bold(
'false'
)} will trigger a document update (Default operation). Useful to perform incremental updates for smaller adjustments to your catalog that do not require pushing the entire catalog. A document update must only be performed after a full catalog upload.
See https://docs.coveo.com/en/l62e0540
Setting this option to ${bold(
'true'
)} will trigger a full catalog upload. This process acts as a full rebuild of your catalog source. Therefore, previous items that are not included in the new payload will be deleted.
See https://docs.coveo.com/en/lb4a0344
`
Example #9
Source File: index.ts From yfm-transform with MIT License | 6 votes |
function replaceImageSrc(
token: Token,
state: StateCore,
{assetsPublicPath = sep, root = '', path: optsPath, log}: ImageOpts,
) {
const src = token.attrGet('src') || '';
const currentPath = state.env.path || optsPath;
if (!isLocalUrl(src)) {
return;
}
const path = resolveRelativePath(currentPath, src);
if (isFileExists(path)) {
state.md.assets?.push(path);
} else {
log.error(`Asset not found: ${bold(src)} in ${bold(currentPath)}`);
}
const relativeToRoot = path.replace(root + sep, '');
const publicSrc = join(assetsPublicPath, relativeToRoot);
token.attrSet('src', publicSrc);
}
Example #10
Source File: tryCreateMissingVaultEntries.ts From cli with Apache License 2.0 | 6 votes |
export async function tryCreateMissingVaultEntries({
reporter,
snapshot,
}: VaultTransferFunctionsParam) {
const shouldCreate = await CliUx.ux.confirm(
`\nWould you like to create the missing vault entries in the destination organization ${bold.cyan(
snapshot.targetId
)}? (y/n)`
);
if (!shouldCreate) {
return false;
}
const vault = new VaultHandler(snapshot.targetId);
await vault.createEntries(Array.from(reporter.missingVaultEntries));
return true;
}
Example #11
Source File: lintPage.ts From yfm-docs with MIT License | 6 votes |
export function lintPage(options: ResolverLintOptions) {
const {inputPath, fileExtension, onFinish} = options;
const {input} = ArgvService.getConfig();
const resolvedPath: string = resolve(input, inputPath);
try {
const content: string = readFileSync(resolvedPath, 'utf8');
const lintFn: Function = FileLinter[fileExtension];
if (!lintFn) {
return;
}
lintFn(content, {path: inputPath});
} catch (e) {
const message = `No such file or has no access to ${bold(resolvedPath)}`;
console.error(message, e);
log.error(message);
}
if (onFinish) {
onFinish();
}
}
Example #12
Source File: substitutions.ts From yfm-transform with MIT License | 6 votes |
substitutions = (str: string, builtVars: Record<string, unknown>, path?: string) => {
const {keepNotVar} = ArgvService.getConfig();
return str.replace(varsRe, (match, _groupNotVar, flag, groupVar, groupVarValue) => {
if (flag) {
return keepNotVar ? _groupNotVar : groupVar;
}
const trimVarPath = groupVarValue.trim();
if (trimVarPath.startsWith('.')) {
return groupVar;
}
let value;
if (isVariable(trimVarPath)) {
value = getObject(trimVarPath, builtVars);
} else {
value = evalExp(trimVarPath, builtVars);
}
if (value === undefined) {
value = match;
log.warn(`Variable ${bold(trimVarPath)} not found${path ? ` in ${bold(path)}` : ''}`);
}
return value;
});
}
Example #13
Source File: cycles.ts From yfm-transform with MIT License | 5 votes |
function inlineConditions({
forTag,
vars,
content,
match,
path,
lastIndex,
sourceMap,
linesTotal,
}: Args2) {
let res = '';
const firstLineNumber = getLineNumber(content, forTag.startPos);
const lastLineNumber = getLineNumber(content, lastIndex);
const forRawLastIndex = forTag.startPos + forTag.forRaw.length;
const contentLastIndex = match.index;
const forTemplate = content.substring(forRawLastIndex, contentLastIndex);
const resFirstLineNumber = getLineNumber(content, forRawLastIndex + 1);
const resLastLineNumber = getLineNumber(content, contentLastIndex + 1);
let collection = evalExp(forTag.collectionName, vars);
if (!collection || !Array.isArray(collection)) {
collection = [];
log.error(`${bold(forTag.collectionName)} is undefined or not iterable`);
}
collection.forEach((item) => {
const newVars = {...vars, [forTag.variableName]: item};
res += applyLiquid(forTemplate, newVars, path).trimRight();
});
const contentLinesTotal = res.split('\n').length - 1;
changeSourceMap({
firstLineNumber,
lastLineNumber,
resFirstLineNumber,
resLastLineNumber,
linesTotal,
sourceMap,
contentLinesTotal,
});
const preparedLeftContent = getPreparedLeftContent({
content,
tagStartPos: forTag.startPos,
tagContent: res,
});
let shift = 0;
if (
res === '' &&
preparedLeftContent[preparedLeftContent.length - 1] === '\n' &&
content[lastIndex] === '\n'
) {
shift = 1;
}
if (res !== '') {
if (res[0] === ' ' || res[0] === '\n') {
res = res.substring(1);
}
}
const leftPart = preparedLeftContent + res;
return {
result: leftPart + content.substring(lastIndex + shift),
idx: leftPart.length,
};
}
Example #14
Source File: tocs.ts From yfm-docs with MIT License | 5 votes |
/**
* Replaces include fields in toc file by resolved toc.
* @param items
* @param tocDir
* @param sourcesDir
* @param vars
* @return
* @private
*/
function _replaceIncludes(items: YfmToc[], tocDir: string, sourcesDir: string, vars: Record<string, string>): YfmToc[] {
return items.reduce((acc, item) => {
let includedInlineItems: YfmToc[] | null = null;
if (item.name) {
const tocPath = join(tocDir, 'toc.yaml');
item.name = _liquidSubstitutions(item.name, vars, tocPath);
}
if (item.include) {
const {path, mode = IncludeMode.ROOT_MERGE} = item.include;
const includeTocPath = mode === IncludeMode.ROOT_MERGE
? resolve(sourcesDir, path)
: resolve(tocDir, path);
const includeTocDir = dirname(includeTocPath);
try {
const includeToc = load(readFileSync(includeTocPath, 'utf8')) as YfmToc;
// Should ignore included toc with tech-preview stage.
if (includeToc.stage === Stage.TECH_PREVIEW) {
return acc;
}
if (mode === IncludeMode.MERGE || mode === IncludeMode.ROOT_MERGE) {
_copyTocDir(includeTocPath, tocDir);
}
/* Save the path to exclude toc from the output directory in the next step */
includedTocPaths.add(includeTocPath);
let includedTocItems = (item.items || []).concat(includeToc.items);
/* Resolve nested toc inclusions */
const baseTocDir = mode === IncludeMode.LINK ? includeTocDir : tocDir;
includedTocItems = _replaceIncludes(includedTocItems, baseTocDir, sourcesDir, vars);
/* Make hrefs relative to the main toc */
if (mode === IncludeMode.LINK) {
includedTocItems = _replaceIncludesHrefs(includedTocItems, includeTocDir, tocDir);
}
if (item.name) {
item.items = includedTocItems;
} else {
includedInlineItems = includedTocItems;
}
} catch (err) {
const message = `Error while including toc: ${bold(includeTocPath)} to ${bold(join(tocDir, 'toc.yaml'))}`;
console.log(message, err);
log.error(message);
return acc;
} finally {
delete item.include;
}
} else if (item.items) {
item.items = _replaceIncludes(item.items, tocDir, sourcesDir, vars);
}
if (includedInlineItems) {
return acc.concat(includedInlineItems);
} else {
return acc.concat(item);
}
}, [] as YfmToc[]);
}
Example #15
Source File: errors.ts From yfm-transform with MIT License | 5 votes |
constructor(message: string, exp: string) {
super();
this.name = 'SkippedEvalError';
this.message = `${message}: ${bold(exp)}`;
}
Example #16
Source File: collect.ts From yfm-transform with MIT License | 5 votes |
collect = (input: string, options: Opts) => {
const {root, path, destPath = '', log, copyFile, singlePage} = options;
const INCLUDE_REGEXP = /{%\s*include\s*(notitle)?\s*\[(.+?)]\((.+?)\)\s*%}/g;
let match,
result = input;
while ((match = INCLUDE_REGEXP.exec(result)) !== null) {
let [, , , relativePath] = match;
const [matchedInclude] = match;
relativePath = relativePath.split('#')[0];
const includePath = resolveRelativePath(path, relativePath);
const targetDestPath = resolveRelativePath(destPath, relativePath);
if (includesPaths.includes(includePath)) {
log.error(`Circular includes: ${bold(includesPaths.concat(path).join(' ▶ '))}`);
break;
}
if (singlePage && !includesPaths.length) {
const newRelativePath = relative(root, includePath);
const newInclude = matchedInclude.replace(relativePath, newRelativePath);
result = result.replace(matchedInclude, newInclude);
const delta = matchedInclude.length - newInclude.length;
INCLUDE_REGEXP.lastIndex = INCLUDE_REGEXP.lastIndex - delta;
}
includesPaths.push(includePath);
const includeOptions = {
...options,
path: includePath,
destPath: targetDestPath,
};
try {
copyFile(includePath, targetDestPath, includeOptions);
} catch (e) {
log.error(`No such file or has no access to ${bold(includePath)} in ${bold(path)}`);
} finally {
includesPaths.pop();
}
}
if (singlePage) {
return result;
}
return null;
}
Example #17
Source File: notes.ts From yfm-transform with MIT License | 5 votes |
notes: MarkdownItPluginCb = (md, {lang, path: optPath, log}) => {
const plugin = (state: StateCore) => {
const {tokens, env} = state;
const path = env.path || optPath;
let i = 0;
while (i < tokens.length) {
const match = matchOpenToken(tokens, i);
if (match) {
const closeTokenIdx = findCloseTokenIdx(tokens, i + 4, path, log);
if (!closeTokenIdx) {
i += 3;
continue;
}
const type = match[1].toLowerCase();
const newOpenToken = new state.Token('yfm_note_open', 'div', 1);
newOpenToken.attrSet('class', `yfm-note yfm-accent-${type}`);
newOpenToken.attrSet('note-type', type);
const newCloseToken = new state.Token('yfm_note_close', 'div', -1);
// Add extra paragraph
const titleOpen = new state.Token('yfm_note_title_open', 'p', 1);
const inline = new state.Token('inline', '', 0);
const strongOpen = new state.Token('strong_open', 'strong', 1);
const inlineText = new state.Token('text', '', 0);
const strongClose = new state.Token('strong_close', 'strong', -1);
const titleClose = new state.Token('yfm_note_title_close', 'p', -1);
titleOpen.block = true;
titleClose.block = true;
inlineText.content = match[2] === undefined ? getTitle(type, lang) : match[2];
inline.children = [strongOpen, inlineText, strongClose];
const insideTokens = [
newOpenToken,
titleOpen,
inline,
titleClose,
...tokens.slice(i + 3, closeTokenIdx),
newCloseToken,
];
tokens.splice(i, closeTokenIdx - i + 3, ...insideTokens);
i++;
} else if (matchWrongNotes(tokens, i) && tokens[i + 1].content !== '{% endnote %}') {
log.warn(`Incorrect syntax for notes${path ? `, file ${bold(path)}` : ''}`);
i += 3;
} else {
i++;
}
}
};
try {
md.core.ruler.before('curly_attributes', 'notes', plugin);
} catch (e) {
md.core.ruler.push('notes', plugin);
}
}
Example #18
Source File: index.ts From yfm-transform with MIT License | 5 votes |
function transform(originInput: string, opts: OptionsType = {}): OutputType {
const {
vars = {},
path,
extractTitle: extractTitleOption,
needTitle,
allowHTML = false,
linkify = false,
breaks = true,
conditionsInCode = false,
disableLiquid = false,
leftDelimiter = '{',
rightDelimiter = '}',
isLiquided = false,
plugins = [meta, deflist, cut, notes, anchors, tabs, code, sup, video, monospace, yfmTable],
highlightLangs = {},
...customOptions
} = opts;
const pluginOptions = {
...customOptions,
vars,
path,
extractTitle: extractTitleOption,
disableLiquid,
log,
};
const input =
disableLiquid || isLiquided
? originInput
: liquid(originInput, vars, path, {conditionsInCode});
const highlight = makeHighlight(highlightLangs);
const md = initMd({html: allowHTML, linkify, highlight, breaks});
// Need for ids of headers
md.use(attrs, {leftDelimiter, rightDelimiter});
plugins.forEach((plugin) => md.use(plugin, pluginOptions));
try {
let title;
let tokens;
let titleTokens;
const env = {};
tokens = md.parse(input, env);
if (extractTitleOption) {
({title, tokens, titleTokens} = extractTitle(tokens));
// title tokens include other tokens that need to be transformed
if (titleTokens.length > 1) {
title = md.renderer.render(titleTokens, md.options, env);
}
}
if (needTitle) {
({title} = extractTitle(tokens));
}
const headings = getHeadings(tokens);
const html = md.renderer.render(tokens, md.options, env);
const assets = md.assets;
const meta = md.meta;
return {
result: {html, title, headings, assets, meta},
logs: log.get(),
};
} catch (err) {
log.error(`Error occurred${path ? ` in ${bold(path)}` : ''}`);
throw err;
}
}
Example #19
Source File: processPages.ts From yfm-docs with MIT License | 5 votes |
async function preparingPagesByOutputFormat(
path: PathData,
metaDataOptions: MetaDataOptions,
resolveConditions: boolean,
): Promise<void> {
const {
filename,
fileExtension,
fileBaseName,
outputDir,
resolvedPathToFile,
outputFormat,
pathToFile,
} = path;
try {
shell.mkdir('-p', outputDir);
const isYamlFileExtension = fileExtension === '.yaml';
if (resolveConditions && fileBaseName === 'index' && isYamlFileExtension) {
LeadingService.filterFile(pathToFile);
}
if (outputFormat === 'md' && isYamlFileExtension ||
outputFormat === 'html' && !isYamlFileExtension && fileExtension !== '.md') {
copyFileWithoutChanges(resolvedPathToFile, outputDir, filename);
return;
}
switch (outputFormat) {
case 'md':
await processingFileToMd(path, metaDataOptions);
return;
case 'html':
await processingFileToHtml(path, metaDataOptions);
return;
}
} catch (e) {
const message = `No such file or has no access to ${bold(resolvedPathToFile)}`;
console.log(message, e);
log.error(message);
}
}
Example #20
Source File: logger.ts From anchorcli with Apache License 2.0 | 5 votes |
export function info(text: string) {
console.log(bold(white(bgBlueBright(' INFO '))) + ' ' + blueBright(text));
}
Example #21
Source File: transferFromOrganization.ts From cli with Apache License 2.0 | 5 votes |
export async function tryTransferFromOrganization({
reporter,
snapshot,
projectPath,
}: VaultTransferFunctionsParam) {
if (!projectPath) {
return false;
}
const originOrgId = new Project(projectPath).getResourceManifest()?.orgId;
if (!originOrgId) {
return false;
}
const shouldTransfer = await CliUx.ux.confirm(
`\nWould you like to try transfering the vault entries from ${bold.cyan(
originOrgId
)} to the destination organization ${bold.cyan(snapshot.targetId)}? (y/n)`
);
if (!shouldTransfer) {
return false;
}
const authenticatedClient = new AuthenticatedClient();
if (!(await authenticatedClient.getUserHasAccessToOrg(originOrgId))) {
CliUx.ux.warn(dedent`
We mapped this snapshot to ${bold.cyan(originOrgId)}.
If you want to transfer the vault entries from ${bold.cyan(
originOrgId
)} to ${bold.cyan(snapshot.targetId)},
authenticate with an account that has access to both organizations and then try again.
`);
return false;
}
const originOrgVaultEntries = await getAllVaultEntriesFrom(originOrgId);
const missingEntriesFromOrigin = getEntriesMissingFromOrigin(
originOrgVaultEntries,
reporter.missingVaultEntries
);
if (missingEntriesFromOrigin.length > 0) {
CliUx.ux.warn(
new SnapshotMissingVaultEntriesFromOriginError(
originOrgId,
snapshot.targetId,
missingEntriesFromOrigin
)
);
return false;
}
const platformClient = await authenticatedClient.getClient({
organization: snapshot.targetId,
});
try {
CliUx.ux.action.start('Transfering vault entries');
await platformClient.vault.import(
snapshot.id,
originOrgId,
VaultFetchStrategy.onlyMissing
);
CliUx.ux.action.stop(green('✔'));
return true;
} catch (error) {
CliUx.ux.action.stop(red.bold('!'));
CliUx.ux.warn('Error encountered while transfering vault entries`');
CliUx.ux.warn(typeof error === 'string' ? error : JSON.stringify(error));
return false;
}
}
Example #22
Source File: push.ts From cli with Apache License 2.0 | 5 votes |
private async askForConfirmation(): Promise<boolean> {
const {flags} = await this.parse(Push);
const target = await getTargetOrg(this.configuration, flags.organization);
const question = `\nWould you like to apply the snapshot to the organization ${bold.cyan(
target
)}? (y/n)`;
return confirmWithAnalytics(question, 'snapshot apply');
}
Example #23
Source File: logger.ts From anchorcli with Apache License 2.0 | 5 votes |
export function success(text: string) {
console.log(
bold(white(bgGreenBright(' SUCCESS '))) + ' ' + greenBright(text),
);
}
Example #24
Source File: logger.ts From anchorcli with Apache License 2.0 | 5 votes |
export function error(text: string) {
console.log(bold(white(bgRedBright(' ERROR '))) + ' ' + redBright(text));
}
Example #25
Source File: logger.ts From anchorcli with Apache License 2.0 | 5 votes |
export function warn(text: string) {
console.log(bold(white(bgYellow(' WARNING '))) + ' ' + yellow(text));
}
Example #26
Source File: index.ts From yfm-transform with MIT License | 4 votes |
index: MarkdownItPluginCb<Options> = (
md,
{extractTitle, path, log, supportGithubAnchors},
) => {
const plugin = (state: StateCore) => {
/* Do not use the plugin if it is included in the file */
if (state.env.includes && state.env.includes.length) {
return;
}
const ids: Record<string, number> = {};
const tokens = state.tokens;
let i = 0;
const slugger = new GithubSlugger();
while (i < tokens.length) {
const token = tokens[i];
const isHeading = token.type === 'heading_open';
if (isHeading) {
const {title, level} = headingInfo(tokens, i);
const inlineToken = tokens[i + 1];
let id = token.attrGet('id');
let ghId: string;
if (!title) {
log.warn(`Header without title${path ? ` in ${bold(path)}` : ''}`);
}
if (level < 2 && extractTitle) {
i += 3;
continue;
}
const customIds = getCustomIds(inlineToken.content);
if (customIds) {
id = customIds[0];
removeCustomIds(tokens[i + 1]);
} else {
id = slugify(title, {
lower: true,
remove: /[*+~.()'"!:@`ь]/g,
});
ghId = slugger.slug(title);
}
token.attrSet('id', id);
if (ids[id]) {
id = id + ids[id]++;
token.attrSet('id', id);
} else {
ids[id] = 1;
}
const allAnchorIds = customIds ? customIds : [id];
allAnchorIds.forEach((customId) => {
const setId = id !== customId;
const linkTokens = createLinkTokens(state, customId, setId);
inlineToken.children?.unshift(...linkTokens);
if (supportGithubAnchors) {
const ghLinkTokens = createLinkTokens(state, ghId, true);
inlineToken.children?.unshift(...ghLinkTokens);
}
});
i += 3;
continue;
}
i++;
}
};
try {
md.core.ruler.after('includes', 'anchors', plugin);
} catch {
try {
md.core.ruler.after('curly_attributes', 'anchors', plugin);
} catch {
md.core.ruler.push('anchors', plugin);
}
}
}
Example #27
Source File: commands.ts From airnode with MIT License | 4 votes |
export async function deploy(configPath: string, secretsPath: string, receiptFile: string) {
const secrets = parseSecretsFile(secretsPath);
const config = loadConfig(configPath, secrets);
if (config.nodeSettings.cloudProvider.type === 'local') {
throw logAndReturnError(`Deployer can't deploy to "local" cloud provider`);
}
// TODO: Check this in validator
const mnemonic = config.nodeSettings.airnodeWalletMnemonic;
if (!validateMnemonic(mnemonic)) {
throw logAndReturnError('AIRNODE_WALLET_MNEMONIC in your secrets.env file is not valid');
}
// TODO: This should be check by validator
const maxConcurrency = config.chains.reduce((concurrency: number, chain) => {
if (chain.maxConcurrency <= 0) {
throw logAndReturnError(`Concurrency limit must be more than 0 for chain with ID ${chain.id}`);
}
if (chain.maxConcurrency < size(chain.providers)) {
throw logAndReturnError(
`Concurrency limit can't be lower than number of providers for chain with ID ${chain.id}`
);
}
return concurrency + chain.maxConcurrency;
}, 0);
const httpGateway = config.nodeSettings.httpGateway;
if (httpGateway.enabled) {
if (httpGateway.maxConcurrency !== undefined && httpGateway.maxConcurrency <= 0) {
throw logAndReturnError('Unable to deploy HTTP gateway: Maximal concurrency must be higher than 0');
}
}
const httpSignedDataGateway = config.nodeSettings.httpSignedDataGateway;
if (httpSignedDataGateway.enabled) {
if (httpSignedDataGateway.maxConcurrency !== undefined && httpSignedDataGateway.maxConcurrency <= 0) {
throw logAndReturnError('Unable to deploy HTTP gateway: Maximal concurrency must be higher than 0');
}
}
logger.debug('Creating a temporary secrets.json file');
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'airnode'));
const tmpSecretsPath = path.join(tmpDir, 'secrets.json');
fs.writeFileSync(tmpSecretsPath, JSON.stringify(secrets, null, 2));
const airnodeAddress = deriveAirnodeAddress(mnemonic);
// AWS doesn't allow uppercase letters in S3 bucket and lambda function names
const airnodeAddressShort = shortenAirnodeAddress(airnodeAddress);
// Deployment is not an atomic operation. It is possible that some resources are deployed even when there is a
// deployment error. We want to write a receipt file, because the user might use the receipt to remove the deployed
// resources from the failed deployment. (The removal is not guaranteed, but it's better compared to asking user to
// remove the resources manually in the cloud provider dashboard).
let deploymentError: Error | undefined;
let output = {};
try {
output = await deployAirnode({
airnodeAddressShort,
stage: config.nodeSettings.stage,
cloudProvider: { maxConcurrency, ...config.nodeSettings.cloudProvider },
httpGateway,
httpSignedDataGateway,
configPath,
secretsPath: tmpSecretsPath,
});
} catch (err) {
deploymentError = err as Error;
}
const deploymentTimestamp = new Date().toISOString();
logger.debug('Deleting a temporary secrets.json file');
fs.rmSync(tmpDir, { recursive: true });
writeReceiptFile(receiptFile, mnemonic, config, output, deploymentTimestamp);
if (deploymentError) {
logger.fail(
bold(
`Airnode deployment failed due to unexpected errors.\n` +
` It is possible that some resources have been deployed on cloud provider.\n` +
` Please use the "remove" command from the deployer CLI to ensure all cloud resources are removed.`
)
);
throw deploymentError;
}
}
Example #28
Source File: index.ts From yfm-transform with MIT License | 4 votes |
// eslint-disable-next-line complexity
function processLink(state: StateCore, tokens: Token[], idx: number, opts: ProcOpts) {
const {path: startPath, root, transformLink, notFoundCb, needSkipLinkFn, log} = opts;
const currentPath = state.env.path || startPath;
const linkToken = tokens[idx];
const nextToken = tokens[idx + 1];
let href = getHrefTokenAttr(linkToken);
if (!href) {
log.error(`Empty link in ${bold(startPath)}`);
return;
}
const {pathname, hash} = url.parse(href);
let file;
let fileExists;
let isPageFile;
if (!isLocalUrl(href)) {
linkToken.attrSet('target', '_blank');
linkToken.attrSet('rel', 'noreferrer noopener');
return;
}
if (pathname) {
file = resolve(path.parse(currentPath).dir, pathname);
fileExists = isFileExists(file);
isPageFile = PAGE_LINK_REGEXP.test(pathname);
if (isPageFile && !fileExists) {
let needShowError = true;
if (needSkipLinkFn) {
needShowError = !needSkipLinkFn(href);
}
if (notFoundCb && needShowError) {
notFoundCb(file.replace(root, ''));
}
if (needShowError) {
log.error(`Link is unreachable: ${bold(href)} in ${bold(currentPath)}`);
}
}
} else if (hash) {
file = startPath;
fileExists = true;
isPageFile = true;
} else {
return;
}
const isEmptyLink = nextToken.type === 'link_close';
const isTitleRefLink = nextToken.type === 'text' && nextToken.content === '{#T}';
if (
(isEmptyLink || isTitleRefLink) &&
fileExists &&
isPageFile &&
!state.env.disableTitleRefSubstitution
) {
addTitle({
hash,
file,
state,
opts,
isEmptyLink,
tokens,
idx,
nextToken,
href,
currentPath,
log,
});
}
let newPathname = '';
if (currentPath !== startPath) {
newPathname = relative(parse(startPath).dir, file);
href = url.format({
...url.parse(href),
pathname: newPathname,
});
}
if (pathname || newPathname) {
const transformer = transformLink || defaultTransformLink;
linkToken.attrSet('href', transformer(href));
}
}