Best JavaScript code snippet using storybook-root
build.js
Source:build.js
1const path = require('path');2const fs = require('fs');3const ast = require('ast-types').builders;4const esprima = require('esprima');5const escodegen = require('escodegen');6const doctrine = require('doctrine');7const lodash = require('lodash');8const lodashCLI = require('lodash-cli');9const methods = require('../methods');10const BUNDLE_FILE_PATH = path.join(__dirname, '..', 'vendor', 'lodash.js');11const EXTERNS_FILE_PATH = path.join(__dirname, '..', 'externs', 'lodash.js');12const README_FILE_PATH = path.join(__dirname, '..', 'README.md');13const README_TEMPLATE_FILE_PATH = path.join(__dirname, '..', 'templates', 'README.md.jst');14const TAB = '\t';15const NEW_LINE = '\n';16const JSDOC_LINE_STARTER = `${TAB} * `;17const JSDOC_TAGS_RENAMING = {18 'returns': 'return'19};20const JSDOC_TAGS_BLACKLIST = [21 'category',22 'memberOf',23 'static',24 'example',25 'see'26];27const {28 ExpressionStatement,29 CallExpression,30 VariableDeclaration,31 FunctionDeclaration32} = esprima.Syntax;33let lodashPath;34try {35 lodashPath = require.resolve('lodash');36} catch (e) {37 throw new Error('Can\'t resolve lodash path');38}39const lodashAST = esprima.parse(fs.readFileSync(lodashPath, 'utf-8'), {40 attachComment: true41});42const lodashIIFE = lodashAST.body.find((node) =>43 node.type === ExpressionStatement &&44 node.expression.type === CallExpression45);46if (!lodashIIFE) {47 throw new Error('Lodash source code is not wrapped to IIFE');48}49const lodashIIFEBody = lodashIIFE.expression.callee.object.body.body;50fs.writeFileSync(EXTERNS_FILE_PATH, generateExterns(lodashIIFEBody), 'utf-8');51console.log(`Externs written at ${EXTERNS_FILE_PATH}`);52fs.writeFileSync(README_FILE_PATH, generateReadme(lodashIIFEBody), 'utf-8');53console.log(`Readme written at ${README_FILE_PATH}`);54lodashCLI([55 `include=${methods.join(',')}`,56 'iife=;(function() {%output%}).call(this); window.lodash=window._; delete window._;',57 '--output', BUNDLE_FILE_PATH,58 '--production'59], (data) => {60 // Remove line with build command from JSDoc61 data.source = data.source.replace(/(\* Build:(.*)\n) /, '');62 fs.writeFileSync(data.outputPath, data.source);63 console.log(`Bundle written at ${BUNDLE_FILE_PATH}`);64});65function generateExterns(lodashIIFEBody) {66 const contextRunnerVariable = lodashIIFEBody.find((node) =>67 node.type === VariableDeclaration &&68 node.declarations.find((declaration) => declaration.id.name === 'runInContext')69 );70 if (!contextRunnerVariable) {71 throw new Error('Expected presence of runInContext variable in lodash source code');72 }73 const contextRunnerBody = contextRunnerVariable.declarations[0].init.body.body;74 const externsMethods = methods.map((methodName) => {75 const declaration = contextRunnerBody.find((node) =>76 (node.type === FunctionDeclaration && node.id.name === methodName) ||77 (node.type === VariableDeclaration && node.declarations.find((declaration) =>78 declaration.id.name === methodName79 ))80 );81 if (!declaration) {82 throw new Error(`Can't find declaration of method ${methodName}`);83 }84 const JSDocBlock = declaration.leadingComments.find((node) =>85 node.type === 'Block' &&86 node.value.startsWith('*') // Guard for lodash's positional markers87 );88 if (!JSDocBlock) {89 throw new Error(`Method ${methodName} has no JSDoc`);90 }91 // Lodash uses proprietary tag "@param-" to describe internally used parameters92 const value = JSDocBlock.value.replace(/@param-.+/g, '');93 const JSDocAST = doctrine.parse(value, {94 sloppy: true,95 unwrap: true96 });97 modifyJSDoc(JSDocAST);98 const params = JSDocAST.tags.filter((tag) => tag.title === 'param')99 .map((tag) => ast.identifier(tag.name));100 const func = ast.functionExpression(null, params, ast.blockStatement([]));101 const property = ast.methodDefinition('method', ast.identifier(methodName), func);102 const block = ast.block(renderJSDoc(JSDocAST));103 // Assign to leadingComments for sake of escodegen104 property.leadingComments = [block];105 return property;106 });107 const lodashClass = ast.classDeclaration(108 ast.identifier('Lodash'),109 ast.classBody(externsMethods)110 );111 lodashClass.leadingComments = [ast.block(`*${NEW_LINE} `)];112 const lodashInstance = ast.expressionStatement(113 ast.memberExpression(114 ast.identifier('window'),115 ast.identifier('lodash')116 )117 );118 lodashInstance.leadingComments = [ast.block(`*${NEW_LINE} * @type {Lodash}${NEW_LINE} `)];119 const externsAST = ast.program([120 lodashClass,121 lodashInstance122 ]);123 return escodegen.generate(externsAST, {124 comment: true,125 format: {126 indent: {127 style: TAB128 }129 }130 }) + NEW_LINE;131}132function generateReadme(lodashIIFEBody) {133 const lodashVersionVariable = lodashIIFEBody.find((node) =>134 node.type === VariableDeclaration &&135 node.declarations.find((declaration) => declaration.id.name === 'VERSION')136 );137 if (!lodashVersionVariable) {138 throw new Error('Expected presence of VERSION variable in lodash source code');139 }140 const lodashVersion = lodashVersionVariable.declarations[0].init.value;141 return lodash.template(fs.readFileSync(README_TEMPLATE_FILE_PATH, 'utf-8'))({142 version: lodashVersion,143 methods: methods.map((name) => `* [${name}](https://lodash.com/docs/${lodashVersion}#${name})`)144 .join(NEW_LINE)145 });146}147function modifyJSDoc(JSDocAST) {148 const {149 OptionalType,150 RestType,151 RecordType,152 FieldType,153 UnionType,154 UndefinedLiteral155 } = doctrine.Syntax;156 // Add @nosideeffects tag for Closure Compiler optimisation157 JSDocAST.tags.unshift({158 title: 'nosideeffects',159 description: null160 });161 // Discard some tags162 JSDocAST.tags = JSDocAST.tags.filter((tag) => !JSDOC_TAGS_BLACKLIST.includes(tag.title));163 // Rename some tags164 JSDocAST.tags.forEach((tag) => {165 if (JSDOC_TAGS_RENAMING[tag.title]) {166 tag.title = JSDOC_TAGS_RENAMING[tag.title];167 }168 });169 const params = JSDocAST.tags.filter((tag) => tag.title === 'param');170 /*171 * Don't allow rest param that not in the end, e.g.:172 *173 * @param {...Array} arrays174 * @param {Function=} comparator175 *176 * will be translated to177 *178 * @param {Array} arrays179 * @param {Array=} arraysSup180 * @param {Function=} comparator181 */182 params.forEach((tag, index) => {183 const previousParam = params[index - 1];184 const nextParam = params[index + 1];185 const isPlainRest = tag.type && tag.type.type === RestType;186 const isOptionalRest = tag.type && tag.type.type === OptionalType && tag.type.expression.type === RestType;187 if (nextParam) {188 let expression;189 if (isPlainRest) {190 tag.type = expression = tag.type.expression;191 }192 if (isOptionalRest) {193 tag.type.expression = expression = tag.type.expression.expression;194 }195 /*196 * Add supplementary param when rest param is the first,197 * e.g. "xorBy" method has the next params signature:198 *199 * @param {...Array=} arrays The arrays to inspect.200 * @param {Function=} iteratee The iteratee invoked per element.201 *202 * To be able to compile such method we have to insert supplementary param and restrict arity203 */204 if (expression && !previousParam) {205 const tagName = tag.name;206 tag.name = `${tagName}0`;207 // Add supplementary param tag208 JSDocAST.tags.splice(JSDocAST.tags.indexOf(tag) + 1, 0, {209 title: 'param',210 name: `${tagName}1`,211 description: tag.description,212 type: {213 type: OptionalType,214 expression215 }216 });217 }218 }219 });220 /*221 * Don't allow optional params that not at the end, e.g.:222 *223 * @param {Array=} array224 * @param {Function} comparator225 *226 * will be translated to227 *228 * @param {Array} array229 * @param {Function} comparator230 */231 params.forEach((tag, index) => {232 const isOptional = tag.type && tag.type.type === OptionalType;233 const nextParam = params[index + 1];234 const isNextOptional = (235 nextParam &&236 nextParam.type &&237 nextParam.type.type === OptionalType238 );239 if (isOptional && nextParam && !isNextOptional) {240 tag.type = tag.type.expression;241 }242 });243 /*244 * Change notation for optional rest params, e.g.:245 *246 * @param {...Array} [array]247 *248 * will be translated to249 *250 * @param {...Array|undefined) array251 *252 * instead of253 *254 * @param {...Array=) array255 *256 * by default, which is invalid notation for Closure Compiler257 */258 params.forEach((tag) => {259 const isOptionalRest = tag.type.type === OptionalType && tag.type.expression.type === RestType;260 // Replace "=" notation to "|undefined" notation261 if (isOptionalRest) {262 tag.type = {263 type: UnionType,264 elements: [265 tag.type.expression,266 {type: UndefinedLiteral}267 ]268 };269 }270 });271 /*272 * Collapse object properties to record, e.g.:273 *274 * @param {Object} [options]275 * @param {number} [options.wait]276 *277 * will be translated to278 *279 * @param {{wait: number|undefined}=} options280 */281 JSDocAST.tags = JSDocAST.tags.reduce((handledTags, tag) => {282 if (tag.name && tag.name.indexOf('.') !== -1) {283 const masterTag = handledTags.find((candidateTag) =>284 candidateTag.name && tag.name.startsWith(candidateTag.name)285 );286 if (masterTag) {287 let masterType;288 if (masterTag.type.type === OptionalType) {289 if (masterTag.type.expression.type !== RecordType) {290 masterTag.type.expression = {291 type: RecordType,292 fields: []293 };294 }295 masterType = masterTag.type.expression;296 } else {297 if (masterTag.type !== RecordType) {298 masterTag.type = {299 type: RecordType,300 fields: []301 };302 }303 masterType = masterTag.type;304 }305 // Replace "=" notation to "|undefined" notation306 let tagType = tag.type;307 if (tagType.type === OptionalType) {308 tagType = {309 type: UnionType,310 elements: [311 tagType.expression,312 {type: UndefinedLiteral}313 ]314 };315 }316 masterType.fields.push({317 type: FieldType,318 key: tag.name.split('.')[1],319 value: tagType320 });321 return handledTags;322 }323 }324 return handledTags.concat([tag]);325 }, []);326}327function renderJSDoc(JSDocAST) {328 let description = '';329 if (JSDocAST.description) {330 description = JSDocAST.description.replace(new RegExp(NEW_LINE, 'g'), `${NEW_LINE}${JSDOC_LINE_STARTER}`);331 description = `${JSDOC_LINE_STARTER}${description}${NEW_LINE}${JSDOC_LINE_STARTER}${NEW_LINE}`;332 }333 const renderedTags = JSDocAST.tags.map((tag) => {334 const chunks = [335 `${JSDOC_LINE_STARTER}@${tag.title}`336 ];337 if (tag.type) {338 chunks.push(`{${doctrine.type.stringify(tag.type, {339 compact: true,340 topLevel: true341 })}}`);342 }343 if (tag.name) {344 chunks.push(tag.name);345 }346 if (tag.description) {347 // Replace new line characters to inline description text348 chunks.push(tag.description.replace(new RegExp(NEW_LINE, 'g'), ''));349 }350 return chunks.join(' ');351 });352 return `*${NEW_LINE}${description}${renderedTags.join(NEW_LINE)}${NEW_LINE}${TAB} `;...
transform-file.ts
Source:transform-file.ts
1import { readFileSync, writeFileSync } from 'fs';2import { explainSync } from 'jsdoc-api';3import { sync as mkdirp } from 'mkdirp';4import * as path from 'path';5import { createPrinter, createSourceFile, ListFormat, Printer, ScriptKind, ScriptTarget, SourceFile } from 'typescript';6import { preprocess } from './preprocess';7import { transformContent } from './transform-content';8export function transformFile(srcFile: string, destFile: string, dts: boolean): void {9 destFile = destFile.replace(/\.js$/, dts ? '.d.ts' : '.ts');10 const printer: Printer = createPrinter();11 const sourceFile: SourceFile = createSourceFile(12 destFile, '', ScriptTarget.ES2015, true, ScriptKind.TS,13 );14 const jsDocAst = explainSync({ files: srcFile });15 const fileContent = readFileSync(srcFile, 'utf-8');16 preprocess(jsDocAst, fileContent);17 const statements = transformContent(jsDocAst, dts);18 const content = printer.printList(ListFormat.MultiLine, statements, sourceFile);19 mkdirp(path.dirname(destFile));20 writeFileSync(destFile, content, 'utf-8');...
export-json.ts
Source:export-json.ts
1import { readFileSync, writeFileSync } from 'fs';2import { explainSync } from 'jsdoc-api';3import { sync as mkdirp } from 'mkdirp';4import * as path from 'path';5import { preprocess } from './preprocess';6export function exportJson(srcFile: string, destFile: string): void {7 destFile = destFile.replace(/\.js$/, '.json');8 const jsDocAst = explainSync({ files: srcFile });9 const fileContent = readFileSync(srcFile, 'utf-8');10 preprocess(jsDocAst, fileContent);11 mkdirp(path.dirname(destFile));12 writeFileSync(destFile, JSON.stringify(jsDocAst, null, 2), 'utf-8');...
Using AI Code Generation
1import { jsDocAst } from '@storybook/addon-docs/blocks';2export default {3 parameters: {4 docs: {5 page: () => {6 const mdast = jsDocAst(MyComponent);7 return <Markdown ast={mdast} />;8 },9 },10 },11};12import { DocsPage } from '@storybook/addon-docs/blocks';13export default {14 parameters: {15 docs: {16 },17 },18};19import { DocsPage } from '@storybook/addon-docs/blocks';20export default {21 parameters: {22 docs: {23 },24 },25};26import { DocsPage } from '@storybook/addon-docs/blocks';27export default {28 parameters: {29 docs: {30 },31 },32};33import { DocsPage } from '@storybook/addon-docs/blocks';34export default {35 parameters: {36 docs: {37 },38 },39};40import { DocsPage } from '@storybook/addon-docs/blocks';41export default {
Using AI Code Generation
1const storybookRoot = require("storybook-root");2const jsDocAst = storybookRoot.jsDocAst;3const storybookRoot = require("storybook-root");4const jsDocAst = storybookRoot.jsDocAst;5const storybookRoot = require("storybook-root");6const jsDocAst = storybookRoot.jsDocAst;7const storybookRoot = require("storybook-root");8const jsDocAst = storybookRoot.jsDocAst;9const storybookRoot = require("storybook-root");10const jsDocAst = storybookRoot.jsDocAst;11const storybookRoot = require("storybook-root");12const jsDocAst = storybookRoot.jsDocAst;13const storybookRoot = require("storybook-root");14const jsDocAst = storybookRoot.jsDocAst;15const storybookRoot = require("storybook-root");16const jsDocAst = storybookRoot.jsDocAst;17const storybookRoot = require("storybook-root");18const jsDocAst = storybookRoot.jsDocAst;19const storybookRoot = require("storybook-root");20const jsDocAst = storybookRoot.jsDocAst;21const storybookRoot = require("storybook-root");22const jsDocAst = storybookRoot.jsDocAst;23const storybookRoot = require("storybook-root");24const jsDocAst = storybookRoot.jsDocAst;25const storybookRoot = require("storybook-root");26const jsDocAst = storybookRoot.jsDocAst;27const storybookRoot = require("storybook-root");28const jsDocAst = storybookRoot.jsDocAst;29const storybookRoot = require("storybook-root
Using AI Code Generation
1import { jsDocAst } from 'storybook-root-alias';2import { jsDocAst } from 'storybook-root-alias';3import { jsDocAst } from 'storybook-root-alias';4import { jsDocAst } from 'storybook-root-alias';5import { jsDocAst } from 'storybook-root-alias';6import { jsDocAst } from 'storybook-root-alias';7import { jsDocAst } from 'storybook-root-alias';8import { jsDocAst } from 'storybook-root-alias';9import { jsDocAst } from 'storybook-root-alias';10import { jsDocAst } from 'storybook-root-alias';11import { jsDocAst } from 'storybook-root-alias';12import { jsDocAst } from 'storybook-root-alias';13import { jsDocAst } from 'storybook-root-alias';14import { jsDocAst } from 'storybook-root-alias';15import { jsDocAst } from 'storybook-root-alias';16import { jsDocAst } from 'storybook-root-alias';17import
Using AI Code Generation
1const jsDocAst = require("storybook-root/lib/utils/jsDocAst");2const jsDocAst = require("storybook-root/lib/utils/jsDocAst");3const jsDocAst = require("storybook-root/lib/utils/jsDocAst");4const jsDocAst = require("storybook-root/lib/utils/jsDocAst");5const jsDocAst = require("storybook-root/lib/utils/jsDocAst");6const jsDocAst = require("storybook-root/lib/utils/jsDocAst");7const jsDocAst = require("storybook-root/lib/utils/jsDocAst");8const jsDocAst = require("storybook-root/lib/utils/jsDocAst");9const jsDocAst = require("storybook-root/lib/utils/jsDocAst");10const jsDocAst = require("storybook-root/lib/utils/jsDocAst");11const jsDocAst = require("storybook-root/lib/utils/jsDocAst");12const jsDocAst = require("storybook-root/lib/utils/jsDocAst");13const jsDocAst = require("storybook-root/lib/utils/jsDocAst");14const jsDocAst = require("storybook-root/lib/utils/jsDocAst");15const jsDocAst = require("storybook-root/lib/utils/jsDocAst");16const jsDocAst = require("storybook-root/lib/utils/jsDocAst");
Using AI Code Generation
1const jsDocAst = require('storybook-root').jsDocAst;2const ast = jsDocAst('path/to/file.js');3const jsDocAst = require('storybook-root').jsDocAst;4const ast = jsDocAst('path/to/file.js');5const jsDocAst = require('storybook-root').jsDocAst;6const ast = jsDocAst('path/to/file.js');7const jsDocAst = require('storybook-root').jsDocAst;8const ast = jsDocAst('path/to/file.js');9const jsDocAst = require('storybook-root').jsDocAst;10const ast = jsDocAst('path/to/file.js');11const jsDocAst = require('storybook-root').jsDocAst;12const ast = jsDocAst('path/to/file.js');13const jsDocAst = require('storybook-root').jsDocAst;14const ast = jsDocAst('path/to/file.js');15const jsDocAst = require('storybook-root').jsDocAst;16const ast = jsDocAst('path/to/file.js');17const jsDocAst = require('storybook-root').jsDocAst;18const ast = jsDocAst('path/to/file.js');19const jsDocAst = require('storybook-root').jsDocAst;20const ast = jsDocAst('path/to/file.js');
Using AI Code Generation
1var jsDocAst = require('storybook-root').jsDocAst;2var path = require('path');3var ast = jsDocAst(path.join(__dirname, 'test.js'));4console.log(ast);5{ description: 'Path: test.js6 returns: { type: 'Object', description: '' },7 [ { title: 'method',8 lineNumber: 5 } ],9 code: 'var jsDocAst = require(\'storybook-root\').jsDocAst;\nvar path = require(\'path\');\n\nvar ast = jsDocAst(path.join(__dirname, \'test.js\'));\n\nconsole.log(ast);',10 file: '/Users/eshwar/Projects/storybook-root/test/test.js' }11var React = require('react');12var JsDocAst = React.createClass({13 render: function() {14 return (15 {JSON.stringify(this.props.ast, null, 4)}16 );17 }18});19module.exports = JsDocAst;20var React = require('react');21var storiesOf = require('storybook-root').storiesOf;22var JsDocAst = require('./JsDocAst');23var ast = require('storybook-root').jsDocAst(__filename);24storiesOf('JsDocAst', module)25 .add('with ast', () => (26 <JsDocAst ast={ast} />27 ));28var React = require('react');
Using AI Code Generation
1const { jsDocAst } = require('storybook-root');2const path = require('path');3const jsdocAst = jsDocAst(path.join(__dirname, 'index.js'));4const jsdoc = jsdocAst.getJsDocAst();5console.log(jsdoc);6 * @param {String} name - name of the person7 * @param {String} address - address of the person8 * @returns {String} - returns the name of the person9function getName(name, address) {10 return name;11}12module.exports = {13};
Using AI Code Generation
1const storybookAst = require("storybook-root").jsDocAst;2storybookAst("./path/to/file.js");3const storybookAst = require("storybook-root").jsDocAst;4storybookAst("./path/to/file.js");5const storybookAst = require("storybook-root").jsDocAst;6storybookAst("./path/to/file.js");7const storybookAst = require("storybook-root").jsDocAst;8storybookAst("./path/to/file.js");9const storybookAst = require("storybook-root").jsDocAst;10storybookAst("./path/to/file.js");11const storybookAst = require("storybook-root").jsDocAst;12storybookAst("./path/to/file.js");13const storybookAst = require("storybook-root").jsDocAst;14storybookAst("./path/to/file.js");15const storybookAst = require("storybook-root").jsDocAst;16storybookAst("./path/to/file.js");17const storybookAst = require("storybook-root").jsDocAst;18storybookAst("./path/to/file.js");19const storybookAst = require("storybook-root").jsDocAst;
Using AI Code Generation
1const jsDocAst = require('storybook-root').jsDocAst;2const ast = jsDocAst('./src/components/MyComponent.js');3console.log(ast);4import { configure, addDecorator } from '@storybook/react';5import { jsDocAst } from 'storybook-root';6const req = require.context('../src/components', true, /\.stories\.js$/);7function loadStories() {8 req.keys().forEach(filename => req(filename));9}10addDecorator((story, context) => {11 const { kind, story: storyName } = context;12 const ast = jsDocAst(`../src/components/${kind}/${storyName}.js`);13 console.log(ast);14 return story(context);15});16configure(loadStories, module);17jsDocAst(filePath)18jsDocAst(filePath, options)19jsDocAst('./src/components/MyComponent.js', {20});21MIT © [Chaitanya Joshi](
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!